lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
C++
src/devices/bin/driver_host/driver_host_context.cc
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
#include "driver_host_context.h" #include <stdio.h> #include <fbl/auto_lock.h> #include <fs/vfs.h> #include "log.h" void DriverHostContext::PushWorkItem(const fbl::RefPtr<zx_device_t>& dev, Callback callback) { auto work_item = std::make_unique<WorkItem>(dev, std::move(callback)); fbl::AutoLock al(&lock_); work_items_.push_back(std::move(work_item)); if (!event_waiter_->signaled()) { event_waiter_->signal(); } } void DriverHostContext::InternalRunWorkItems(size_t how_many_to_run) { { fbl::AutoLock al(&lock_); if (event_waiter_->signaled()) { event_waiter_->designal(); } } size_t work_items_run = 0; auto keep_running = [&]() { return work_items_run < how_many_to_run || how_many_to_run == 0; }; do { fbl::DoublyLinkedList<std::unique_ptr<WorkItem>> work_items; { fbl::AutoLock al(&lock_); work_items = std::move(work_items_); } if (work_items.is_empty()) { return; } std::unique_ptr<WorkItem> work_item; while (keep_running() && (work_item = work_items.pop_front())) { work_item->callback(); work_items_run++; } if (!work_items.is_empty()) { fbl::AutoLock al(&lock_); work_items_.splice(work_items_.begin(), work_items); } } while (keep_running()); fbl::AutoLock al(&lock_); if (!work_items_.is_empty() && !event_waiter_->signaled()) { event_waiter_->signal(); } } void DriverHostContext::RunWorkItems(size_t how_many_to_run) { std::unique_ptr<EventWaiter> event_waiter; { fbl::AutoLock al(&lock_); ZX_DEBUG_ASSERT(event_waiter_ != nullptr); if (work_items_.is_empty()) { return; } event_waiter = event_waiter_->Cancel(); } InternalRunWorkItems(how_many_to_run); EventWaiter::BeginWait(std::move(event_waiter), loop_.dispatcher()); } zx_status_t DriverHostContext::SetupEventWaiter() { zx::event event; if (zx_status_t status = zx::event::create(0, &event); status != ZX_OK) { return status; } constexpr uint32_t kBatchSize = 5; auto event_waiter = std::make_unique<EventWaiter>(std::move(event), [this]() { InternalRunWorkItems(kBatchSize); }); { fbl::AutoLock al(&lock_); event_waiter_ = event_waiter.get(); } return EventWaiter::BeginWait(std::move(event_waiter), loop_.dispatcher()); } void DriverHostContext::EventWaiter::HandleEvent(std::unique_ptr<EventWaiter> event_waiter, async_dispatcher_t* dispatcher, async::WaitBase* wait, zx_status_t status, const zx_packet_signal_t* signal) { if (status != ZX_OK) { log(ERROR, "driver_host: event waiter error: %d\n", status); return; } if (signal->observed & ZX_USER_SIGNAL_0) { event_waiter->InvokeCallback(); BeginWait(std::move(event_waiter), dispatcher); } else { printf("%s: invalid signals %x\n", __func__, signal->observed); abort(); } } zx_status_t DriverHostContext::DeviceConnect(const fbl::RefPtr<zx_device_t>& dev, uint32_t flags, zx::channel c) { auto options = fs::VnodeConnectionOptions::FromIoV1Flags(flags); fbl::RefPtr<fs::Vnode> target; zx_status_t status = dev->vnode->OpenValidating(options, &target); if (status != ZX_OK) { return status; } if (target == nullptr) { target = dev->vnode; } return vfs_.Serve(std::move(target), std::move(c), options); }
#include "driver_host_context.h" #include <stdio.h> #include <fbl/auto_lock.h> #include <fs/vfs.h>
nst zx_packet_signal_t* signal) { if (status != ZX_OK) { log(ERROR, "driver_host: event waiter error: %d\n", status); return; } if (signal->observed & ZX_USER_SIGNAL_0) { event_waiter->InvokeCallback(); BeginWait(std::move(event_waiter), dispatcher); } else { printf("%s: invalid signals %x\n", __func__, signal->observed); abort(); } } zx_status_t DriverHostContext::DeviceConnect(const fbl::RefPtr<zx_device_t>& dev, uint32_t flags, zx::channel c) { auto options = fs::VnodeConnectionOptions::FromIoV1Flags(flags); fbl::RefPtr<fs::Vnode> target; zx_status_t status = dev->vnode->OpenValidating(options, &target); if (status != ZX_OK) { return status; } if (target == nullptr) { target = dev->vnode; } return vfs_.Serve(std::move(target), std::move(c), options); }
#include "log.h" void DriverHostContext::PushWorkItem(const fbl::RefPtr<zx_device_t>& dev, Callback callback) { auto work_item = std::make_unique<WorkItem>(dev, std::move(callback)); fbl::AutoLock al(&lock_); work_items_.push_back(std::move(work_item)); if (!event_waiter_->signaled()) { event_waiter_->signal(); } } void DriverHostContext::InternalRunWorkItems(size_t how_many_to_run) { { fbl::AutoLock al(&lock_); if (event_waiter_->signaled()) { event_waiter_->designal(); } } size_t work_items_run = 0; auto keep_running = [&]() { return work_items_run < how_many_to_run || how_many_to_run == 0; }; do { fbl::DoublyLinkedList<std::unique_ptr<WorkItem>> work_items; { fbl::AutoLock al(&lock_); work_items = std::move(work_items_); } if (work_items.is_empty()) { return; } std::unique_ptr<WorkItem> work_item; while (keep_running() && (work_item = work_items.pop_front())) { work_item->callback(); work_items_run++; } if (!work_items.is_empty()) { fbl::AutoLock al(&lock_); work_items_.splice(work_items_.begin(), work_items); } } while (keep_running()); fbl::AutoLock al(&lock_); if (!work_items_.is_empty() && !event_waiter_->signaled()) { event_waiter_->signal(); } } void DriverHostContext::RunWorkItems(size_t how_many_to_run) { std::unique_ptr<EventWaiter> event_waiter; { fbl::AutoLock al(&lock_); ZX_DEBUG_ASSERT(event_waiter_ != nullptr); if (work_items_.is_empty()) { return; } event_waiter = event_waiter_->Cancel(); } InternalRunWorkItems(how_many_to_run); EventWaiter::BeginWait(std::move(event_waiter), loop_.dispatcher()); } zx_status_t DriverHostContext::SetupEventWaiter() { zx::event event; if (zx_status_t status = zx::event::create(0, &event); status != ZX_OK) { return status; } constexpr uint32_t kBatchSize = 5; auto event_waiter = std::make_unique<EventWaiter>(std::move(event), [this]() { InternalRunWorkItems(kBatchSize); }); { fbl::AutoLock al(&lock_); event_waiter_ = event_waiter.get(); } return EventWaiter::BeginWait(std::move(event_waiter), loop_.dispatcher()); } void DriverHostContext::EventWaiter::HandleEvent(std::unique_ptr<EventWaiter> event_waiter, async_dispatcher_t* dispatcher, async::WaitBase* wait, zx_status_t status, co
random
[]
C++
src/render/MCPT_EL.cc
ppwwyyxx/Ray-Tracing-Engine
af3ec164d6b5e5b592a54a75282432d610423ffb
#include "render/MCPT_EL.hh" using namespace std; Color MCPT_EL::do_trace(const Ray& ray, int depth, int use_emission) const { if (depth > max_depth) return Color::BLACK; m_assert(fabs(ray.dir.sqr() - 1) < EPS); auto first_trace = find_first(ray, true); if (!first_trace) return Color::BLACK; Vec norm = first_trace->normal(), inter_point = first_trace->intersection_point(); auto surf = first_trace->get_property(); Color diffu = surf->diffuse; real_t forward_density = first_trace->get_forward_density(); m_assert((fabs(norm.sqr() - 1) < EPS)); m_assert(norm.dot(ray.dir) <= 0); if (ray.debug) { print_debug("debug ray: arrive point (%lf, %lf, %lf) \n", inter_point.x, inter_point.y, inter_point.z); } real_t max_color_comp = diffu.get_max(); if (depth > 5 or fabs(max_color_comp) < EPS) { if (drand48() < max_color_comp) diffu = diffu * (1.0 / max_color_comp); else return surf->emission * use_emission; } real_t r1 = 2 * M_PI * drand48(), r2 = drand48(), r2s = sqrt(r2); Vec u = ((fabs(norm.x) > 0.1 ? Vec(0, 1, 0) : Vec(1, 0, 0)).cross(norm)).get_normalized(), v = norm.cross(u); Vec d = ((u * cos(r1)) * r2s + v * sin(r1) * r2s + norm * (sqrt(1 - r2))).get_normalized(); real_t diffuse_weight = min(1 - surf->specular, 1 - surf->transparency); Color now_diffuse = do_trace(Ray(inter_point - ray.dir * EPS, d), depth + 1) * diffuse_weight; real_t lighting = 0; for (auto & light : lights) { Vec l_src = light->get_src(); real_t l_size = light->get_size(); Vec sw = l_src - inter_point, su = (fabs(sw.x) > 0.1 ? Vec(0, 1, 0) : Vec(1, 0, 0)).get_normalized(), sv = sw.cross(su); real_t cos_a_max = sqrt(1 - ::sqr(l_size) / sw.sqr()); if (!isnormal(cos_a_max)) cos_a_max = 0; real_t eps1 = drand48(), eps2 = drand48(); real_t cos_a = 1 - eps1 + eps1 * cos_a_max, sin_a = sqrt(1 - ::sqr(cos_a)), phi = 2 * M_PI * eps2; Vec dir = su * cos(phi) * sin_a + sv * sin(phi) * sin_a + sw * cos_a; if (dir.dot(norm) < 0) continue; dir.normalize(); if (check_shadow_ray(Ray(inter_point + dir * EPS, dir), light)) { real_t omega = 2 * M_PI * (1 - cos_a_max); lighting += light->intensity * dir.dot(norm) * omega * M_1_PI; } } lighting *= diffuse_weight / 6; m_assert(diffuse_weight >= 0); m_assert(lighting >= 0); Color now_refl = Color::BLACK; if (surf->specular > 0 && !(first_trace->contain())) { Ray new_ray(inter_point - ray.dir * EPS, -norm.reflection(ray.dir), ray.density); m_assert(fabs((-norm.reflection(ray.dir)).sqr() - 1) < EPS); new_ray.debug = ray.debug; Color refl = do_trace(new_ray, depth + 1, 0); now_refl = refl * surf->specular; } Color now_transm = Color::BLACK; if (surf->transparency > EPS) { Ray refl_ray(inter_point - ray.dir * EPS, -norm.reflection(ray.dir), ray.density); refl_ray.debug = ray.debug; Vec tr_dir = norm.transmission(ray.dir, ray.density / forward_density); if (isfinite(tr_dir.x)) { Ray new_ray(inter_point + ray.dir * EPS, tr_dir, forward_density); new_ray.debug = ray.debug; real_t F0 = sqr(0.5) / sqr(ray.density + forward_density); real_t theta = first_trace->contain() ? tr_dir.dot(norm) : ray.dir.dot(norm); real_t Fr = F0 + (1 - F0) * pow(1 + theta, 5); real_t P = 0.25 + Fr * 0.5; if (drand48() < P) { Color refl = do_trace(refl_ray, depth + 1, 0) * surf->specular; now_transm = refl * Fr / P; } else { Color transm = do_trace(new_ray, depth + 1, 0); now_transm = transm * ((1 - Fr) / (1 - P)) * surf->transparency; } } else { Color refl = do_trace(refl_ray, depth + 1) * surf->specular; now_transm = refl; } } return surf->emission * use_emission + diffu * (now_diffuse + now_refl + now_transm) + diffu * lighting; } bool MCPT_EL::check_shadow_ray(const Ray& ray, const shared_ptr<Light>& light) const { real_t min = numeric_limits<real_t>::max(); for (auto & obj : objs) { auto tmp = obj->get_trace(ray, min == numeric_limits<real_t>::max() ? -1 : min); if (tmp) { real_t d = tmp->intersection_dist(); update_min(min, d); } } bool found = false; for (auto &l : lights) { auto tmp = l->get_trace(ray, min == numeric_limits<real_t>::max() ? -1 : min); if (tmp) { real_t d = tmp->intersection_dist(); if (update_min(min, d)) { if (found) return false; } else { if (l == light) return false; } if (l == light) found = true; } } return true; }
#include "render/MCPT_EL.hh" using namespace std; Color MCPT_EL::do_trace(const Ray& ray, int depth, int use_emission) const { if (depth > max_depth) return Color::BLACK; m_assert(fabs(ray.dir.sqr() - 1) < EPS); auto first_trace = find_first(ray, true); if (!first_trace) return Color::BLACK; Vec norm = first_trace->normal(), inter_point = first_trace->intersection_point(); auto surf = first_trace->get_property(); Color diffu = surf->diffuse; real_t forward_density = first_trace->get_forward_density(); m_assert((fabs(norm.sqr() - 1) < EPS)); m_assert(norm.dot(ray.dir) <= 0); if (ray.debug) { print_debug("debug ray: arrive point (%lf, %lf, %lf) \n", inter_point.x, inter_point.y, inter_point.z); } real_t max_color_comp = diffu.get_max(); if (depth > 5 or fabs(max_color_comp) < EPS) {
} real_t r1 = 2 * M_PI * drand48(), r2 = drand48(), r2s = sqrt(r2); Vec u = ((fabs(norm.x) > 0.1 ? Vec(0, 1, 0) : Vec(1, 0, 0)).cross(norm)).get_normalized(), v = norm.cross(u); Vec d = ((u * cos(r1)) * r2s + v * sin(r1) * r2s + norm * (sqrt(1 - r2))).get_normalized(); real_t diffuse_weight = min(1 - surf->specular, 1 - surf->transparency); Color now_diffuse = do_trace(Ray(inter_point - ray.dir * EPS, d), depth + 1) * diffuse_weight; real_t lighting = 0; for (auto & light : lights) { Vec l_src = light->get_src(); real_t l_size = light->get_size(); Vec sw = l_src - inter_point, su = (fabs(sw.x) > 0.1 ? Vec(0, 1, 0) : Vec(1, 0, 0)).get_normalized(), sv = sw.cross(su); real_t cos_a_max = sqrt(1 - ::sqr(l_size) / sw.sqr()); if (!isnormal(cos_a_max)) cos_a_max = 0; real_t eps1 = drand48(), eps2 = drand48(); real_t cos_a = 1 - eps1 + eps1 * cos_a_max, sin_a = sqrt(1 - ::sqr(cos_a)), phi = 2 * M_PI * eps2; Vec dir = su * cos(phi) * sin_a + sv * sin(phi) * sin_a + sw * cos_a; if (dir.dot(norm) < 0) continue; dir.normalize(); if (check_shadow_ray(Ray(inter_point + dir * EPS, dir), light)) { real_t omega = 2 * M_PI * (1 - cos_a_max); lighting += light->intensity * dir.dot(norm) * omega * M_1_PI; } } lighting *= diffuse_weight / 6; m_assert(diffuse_weight >= 0); m_assert(lighting >= 0); Color now_refl = Color::BLACK; if (surf->specular > 0 && !(first_trace->contain())) { Ray new_ray(inter_point - ray.dir * EPS, -norm.reflection(ray.dir), ray.density); m_assert(fabs((-norm.reflection(ray.dir)).sqr() - 1) < EPS); new_ray.debug = ray.debug; Color refl = do_trace(new_ray, depth + 1, 0); now_refl = refl * surf->specular; } Color now_transm = Color::BLACK; if (surf->transparency > EPS) { Ray refl_ray(inter_point - ray.dir * EPS, -norm.reflection(ray.dir), ray.density); refl_ray.debug = ray.debug; Vec tr_dir = norm.transmission(ray.dir, ray.density / forward_density); if (isfinite(tr_dir.x)) { Ray new_ray(inter_point + ray.dir * EPS, tr_dir, forward_density); new_ray.debug = ray.debug; real_t F0 = sqr(0.5) / sqr(ray.density + forward_density); real_t theta = first_trace->contain() ? tr_dir.dot(norm) : ray.dir.dot(norm); real_t Fr = F0 + (1 - F0) * pow(1 + theta, 5); real_t P = 0.25 + Fr * 0.5; if (drand48() < P) { Color refl = do_trace(refl_ray, depth + 1, 0) * surf->specular; now_transm = refl * Fr / P; } else { Color transm = do_trace(new_ray, depth + 1, 0); now_transm = transm * ((1 - Fr) / (1 - P)) * surf->transparency; } } else { Color refl = do_trace(refl_ray, depth + 1) * surf->specular; now_transm = refl; } } return surf->emission * use_emission + diffu * (now_diffuse + now_refl + now_transm) + diffu * lighting; } bool MCPT_EL::check_shadow_ray(const Ray& ray, const shared_ptr<Light>& light) const { real_t min = numeric_limits<real_t>::max(); for (auto & obj : objs) { auto tmp = obj->get_trace(ray, min == numeric_limits<real_t>::max() ? -1 : min); if (tmp) { real_t d = tmp->intersection_dist(); update_min(min, d); } } bool found = false; for (auto &l : lights) { auto tmp = l->get_trace(ray, min == numeric_limits<real_t>::max() ? -1 : min); if (tmp) { real_t d = tmp->intersection_dist(); if (update_min(min, d)) { if (found) return false; } else { if (l == light) return false; } if (l == light) found = true; } } return true; }
if (drand48() < max_color_comp) diffu = diffu * (1.0 / max_color_comp); else return surf->emission * use_emission;
if_condition
[ { "content": "class Color {\n\n\tpublic:\n\n\t\treal_t r = 0, g = 0, b = 0;\n\n\n\n\t\tColor():\n\n\t\t\tColor(EPS, EPS, EPS) { }\n\n\n\n\t\texplicit Color(real_t _r, real_t _g, real_t _b):\n\n\t\t\tr(_r), g(_g), b(_b) {}\n\n\n\n\t\texplicit Color(const Vec& v):\n\n\t\t\tr(v.x), g(v.y), b(v.z) {}\n\n\n\n\t\tstatic constexpr real_t C_EPS = 1e-4;\n\n\n\n\t\tbool black() const\n\n\t\t{ return fabs(r) < C_EPS && fabs(g) < C_EPS && fabs(b) < C_EPS; }\n\n\n\n\t\tbool valid() const {\n\n\t\t\treturn (BETW(r, 0, 1 + EPS)\n", "file_path": "src/include/color.hh", "rank": 0, "score": 92193.45843459477 }, { "content": "class Ray {\n\n\tpublic:\n\n\t\tbool debug = false;\n\n\n\n\t\tVec orig, dir;\n\n\n\n\t\treal_t density;\n\n\n\n\t\tRay(){}\n\n\n\n\t\tRay(const Vec & _orig, const Vec& _dir, real_t _density = 1, bool normalize = false):\n\n\t\t\torig(_orig), dir(_dir), density(_density) {\n\n\t\t\tif (normalize)\n\n\t\t\t\tdir.normalize();\n\n\t\t}\n\n\n\n\t\tvirtual ~Ray(){}\n\n\n\n\t\tVec get_dist(real_t d) const\n\n\t\t{ return orig + dir * d; }\n", "file_path": "src/include/geometry/ray.hh", "rank": 1, "score": 89689.35831577951 }, { "content": "class DistRay : public Ray {\n\n\tpublic:\n\n\t\treal_t dist = 0;\n\n\n\n\t\texplicit DistRay(const Ray& ray): Ray(ray) { }\n\n\n\n\t\tDistRay(const Vec & _orig, const Vec& _dir, real_t _density = 1, bool normalize = false):\n\n\t\t\tRay(_orig, _dir, _density, normalize) { }\n\n};\n\n\n", "file_path": "src/include/render/phong.hh", "rank": 2, "score": 79729.43735012307 }, { "content": "// File: const.hh\n\n\n\n// Author: Yuxin Wu <[email protected]>\n\n\n\n#pragma once\n\n\n\n#include <cmath>\n\n#include <vector>\n\n#include <iostream>\n\n#include <utility>\n\n#include <limits>\n\n\n\n#include \"lib/utils.hh\"\n\n\n\nconst real_t DEFAULT_TRACING_WEIGHT_THRESHOLD = 0.0005;\n\nconst real_t DEFAULT_REFRACTIVE_INDEX = 1.2;\n\nconst real_t AIR_REFRACTIVE_INDEX = 1;\n\nconst int MAX_PHONG_DEPTH = 4;\n\nconst int MAX_MCPT_DEPTH = 4;\n\n\n", "file_path": "src/include/const.hh", "rank": 3, "score": 61316.44788963191 }, { "content": "// color blending\n\nconst real_t AMBIENT_FACTOR = 0.0006;\n\nconst real_t AIR_BEER_DENSITY = 0.03;\n\nconst real_t DEFAULT_SPECULAR = 0.4;\n\nconst real_t REFL_DIFFUSE_FACTOR = 0.5;\n\nconst real_t TRANSM_DIFFUSE_FACTOR = 0.3;\n\nconst real_t REFL_DECAY = 0.04;\n\n\n\n\n\nconst int DOF_SAMPLE_CNT = 15;\n\nconst real_t DOF_SAMPLE_RADIUS = 0.4;\n\n\n\nconst real_t DOF_SCREEN_DIST_FACTOR = 0.1;\n\nconst int SOFT_SHADOW_LIGHT = 30;\n\nconst real_t SOFT_SHADOW_RADIUS = 0.8;\n\n\n\nconst int KDTREE_MAX_DEPTH = 100;\n\nconst int KDTREE_TERMINATE_OBJ_CNT = 10;\n\n\n\nconst int GLOBAL_ILLU_SAMPLE_CNT = 250;\n\nconst int ANTIALIAS_SAMPLE_CNT = 2;\n", "file_path": "src/include/const.hh", "rank": 4, "score": 61313.79542869718 }, { "content": "\n\n\t\tinline real_t get_max()\n\n\t\t{ return std::max(r, std::max(g, b)); }\n\n\n\n\t\tfriend std::ostream & operator << (std::ostream &os, const Color& vec)\n\n\t\t{ return os << vec.r << \" \" << vec.g << \" \" << vec.b;}\n\n\n\n\t\tstatic const Color NONE, WHITE, BLACK, RED, BLUE, GREEN, YELLOW, MAGNETA, CYAN;\n\n\n\n};\n\n\n", "file_path": "src/include/color.hh", "rank": 5, "score": 61293.126902328644 }, { "content": "\t\t\t\t\t&& BETW(g, 0, 1 + EPS)\n\n\t\t\t\t\t&& BETW(b, 0, 1 + EPS));\n\n\t\t}\n\n\n\n\t\tvoid check() const {\n\n\t\t\tif (!valid()) {\n\n\t\t\t\tstd::cout << *this << std::endl;\n\n\t\t\t\tm_assert(false);\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\tvoid normalize() {\n\n\t\t\treal_t max = get_max();\n\n\t\t\tif (max > 1) {\n\n\t\t\t\tr /= max;\n\n\t\t\t\tg /= max;\n\n\t\t\t\tb /= max;\n\n\t\t\t}\n\n\t\t}\n\n\n", "file_path": "src/include/color.hh", "rank": 6, "score": 61289.11748707736 }, { "content": "// File: color.hh\n\n\n\n// Author: Yuxin Wu <[email protected]>\n\n\n\n#pragma once\n\n\n\n#include <iostream>\n\n#include \"geometry/geometry.hh\"\n\n#include \"lib/debugutils.hh\"\n\n\n\n#include <cmath>\n\n\n", "file_path": "src/include/color.hh", "rank": 7, "score": 61288.8266723871 }, { "content": "\t\tColor operator + (const Color &v) const\n\n\t\t{ return Color(r + v.r, g + v.g, b + v.b); }\n\n\n\n\t\tColor& operator += (const Color &v)\n\n\t\t{ r += v.r; g += v.g; b += v.b; return *this; }\n\n\n\n\t\tColor operator - (const Color &v) const\n\n\t\t{ return Color(r - v.r, g - v.g, b - v.b); }\n\n\n\n\t\tColor operator * (real_t p) const\n\n\t\t{ return Color(r * p, g * p, b * p); }\n\n\n\n\t\tColor& operator *= (real_t p)\n\n\t\t{ r *= p; g *= p; b *= p; return *this; }\n\n\n\n\t\tColor operator * (const Color& c) const\n\n\t\t{ return Color(r * c.r, g * c.g, b * c.b); }\n\n\n\n\t\tColor operator / (real_t p) const\n\n\t\t{ return *this * (1.0 / p); }\n", "file_path": "src/include/color.hh", "rank": 8, "score": 61286.51466457658 }, { "content": "\n\n\t\treal_t distance(const Vec& p) const\n\n\t\t{ return sqrt(sqrdistance(p)); }\n\n\n\n\t\treal_t sqrdistance(const Vec& p) const\n\n\t\t{ return (project(p) - p).sqr(); }\n\n\n\n\t\tVec project(const Vec& p) const {\n\n\t\t\treal_t t = (p - orig).dot(dir);\n\n\t\t\treturn get_dist(t);\n\n\t\t}\n\n\n\n\t\tbool contains(const Vec& p) const\n\n\t\t{ return (fabs(sqrdistance(p)) < EPS) && ((p.x - orig.x) * (dir.x) >= -EPS); }\n\n\n\n\t\tfriend std::ostream& operator << (std::ostream & os, const Ray& ray)\n\n\t\t{ return os << \"orig: \" << ray.orig << \" , dir:\" << ray.dir; }\n\n};\n\n\n", "file_path": "src/include/geometry/ray.hh", "rank": 9, "score": 58584.55401038159 }, { "content": "// File: ray.hh\n\n\n\n// Author: Yuxin Wu <[email protected]>\n\n\n\n#pragma once\n\n\n\n#include <cmath>\n\n\n\n#include \"geometry/geometry.hh\"\n\n\n", "file_path": "src/include/geometry/ray.hh", "rank": 10, "score": 58577.35439831525 }, { "content": "#!/usr/bin/env python2\n\n# -*- coding: UTF-8 -*-\n\n# File: gen_list.py\n\n\n\n# Author: Yuxin Wu <[email protected]>\n\nimport sys\n\nf = open('list', 'w')\n\nNPIC = int(sys.argv[1])\n\n\n\nfor r in xrange(NPIC):\n\n print >> f, \"{0:03}.png\".format(r)\n\nf.close()\n", "file_path": "src/output/gen_list.py", "rank": 11, "score": 41108.051320449915 }, { "content": "class LinearDistribution: public RandomGen<real_t> {\n\n\tstatic std::mt19937 gen;\n\n\tstatic std::piecewise_linear_distribution<real_t> dist;\n\n\tstatic bool initialized = false;\n\n\tpublic:\n\n\t\tLinearDistribution() {\n\n\t\t\tif (!initialized) {\n\n\t\t\t\tdouble range[2] = { 0, 1 };\n\n\t\t\t\tdouble prob[2] = { 0, 1 };\n\n\t\t\t\tdist = std::piecewise_linear_distribution<real_t>(begin(range), end(range), begin(prob));\n\n\t\t\t\tinitialized = true;\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\treal_t get() override { return dist(gen); }\n\n};\n", "file_path": "src/include/lib/random.hh", "rank": 12, "score": 40847.7677570432 }, { "content": "// File: static_const.cc\n\n\n\n// Author: Yuxin Wu <[email protected]>\n\n\n\n#include \"color.hh\"\n\n#include \"material/surface.hh\"\n\n#include \"material/texture.hh\"\n\n#include \"renderable/plane.hh\"\n\n#include \"geometry/sphere.hh\"\n\n#include \"const.hh\"\n\nusing namespace std;\n\n\n\nconst Color Color::NONE(0, 0, 0),\n\n\t\t\tColor::BLACK(EPS, EPS, EPS),\n\n\t\t\tColor::WHITE(1, 1, 1),\n\n\t\t\tColor::RED(1, EPS, EPS),\n\n\t\t\tColor::BLUE(EPS, EPS, 1),\n\n\t\t\tColor::GREEN(EPS, 1, EPS),\n\n\t\t\tColor::YELLOW(1, 1, EPS),\n\n\t\t\tColor::CYAN(EPS, 1, 1),\n", "file_path": "src/static_const.cc", "rank": 13, "score": 32752.942577228012 }, { "content": "\t\t\tColor::MAGNETA(1, EPS, 1);\n\n\n\nconst Surface\n\n\tSurface::WHITE_REFL(0, 20, 1, Color::WHITE, DEFAULT_SPECULAR),\n\n\tSurface::BLACK_REFL(0, 20, 1, Color::BLACK, DEFAULT_SPECULAR),\n\n\tSurface::WHITE(0, 20, 1, Color::WHITE * 0.8, 0),\n\n\tSurface::BLACK(0, 20, 1, Color::BLACK, 0),\n\n\tSurface::BLUE(0.8, 50, 0.5, Color::BLUE, 0.2),\n\n\tSurface::CYAN(0, 20, 0.2, (Color)Color::CYAN * 0.6, 0),\n\n\tSurface::GOOD(0, 40, 0.5, Color(0.75, 0.35, 0.5), 0),\n\n\tSurface::GOOD_REFL(0, 40, 0.5, Color(0.75, 0.35, 0.5), DEFAULT_SPECULAR),\n\n\tSurface::GLASS(0.9, 40, 0.5, Color(1, 1, 1), 0.9),\n\n\tSurface::MIRROR(0, 40, 0.5, Color(1, 1, 1), 1),\n\n\tSurface::GREEN(0, 40, 0.5, (Color)(Color::GREEN * 0.6), 0);\n\n\n\n\n\nconst GridTexture\n\n\tGridTexture::BLACK_WHITE_REFL(1, Surface::BLACK_REFL, Surface::WHITE_REFL),\n\n\tGridTexture::BLACK_WHITE(1, Surface::BLACK, Surface::WHITE);\n\n\n\n\n\nconst PureSphere PureSphere::TestSphere(Vec(0, 0, 2), 1.99);\n\n\n\nconst InfPlane InfPlane::XYPLANE(Vec(0, 0, 1), 0);\n", "file_path": "src/static_const.cc", "rank": 14, "score": 32740.645386043096 }, { "content": "\t\tVec dir_w, dir_h;\n\n\n\n\t\tVec origin_norm;\t\t// the initial view\n\n\n\n\t\tbool use_dof = false;\n\n\t\tbool use_bended_screen = false;\n\n\n\n\t\tView(const Space& _sp, const Vec& _view_point,\n\n\t\t\t\tconst Vec& _mid, real_t w, const Geometry& _geo);\n\n\n\n\t\tvoid zoom(real_t ratio);\t// r > 1: zoom in\n\n\n\n\t\tvoid twist(int angle); // -180 ~ 180\n\n\n\n\t\tvoid rotate(int angle); // -180 ~ 180\n\n\n\n\t\tvoid orbit(int angle); // -180 ~ 180\n\n\n\n\t\tvoid shift(real_t dist, bool horiz);\n\n\n", "file_path": "src/include/view.hh", "rank": 15, "score": 28587.849507630694 }, { "content": "\t\tvoid move_screen(real_t dist);\n\n\n\n\t\tColor render(int i, int j) const;\t// i row j column\n\n\t\tColor render_bended(int i, int j) const;\n\n\n\n\t\tColor render_antialias(const Vec& dest, int sample) const; // render with n^2 sample at each pixel\n\n\n\n\t\tColor render_dof(const Vec& dest) const;\n\n\n\n\t\tconst Geometry& get_geo() const\n\n\t\t{ return geo; }\n\n\n\n};\n\n\n", "file_path": "src/include/view.hh", "rank": 16, "score": 28584.7952597832 }, { "content": "// File: viewer.hh\n\n\n\n// Author: Yuxin Wu <[email protected]>\n\n\n\n#pragma once\n\n#include <string>\n\n#include <thread>\n\n#include \"librender/myrender.hh\"\n\n#include \"view.hh\"\n\n\n", "file_path": "src/include/viewer.hh", "rank": 17, "score": 28577.81440464828 }, { "content": "// File: kdtree.hh\n\n// Author: Yuxin Wu <[email protected]>\n\n\n\n#pragma once\n\n#include <list>\n\n#include \"geometry/geometry.hh\"\n\n#include \"geometry/aabb.hh\"\n\n#include \"renderable/renderable.hh\"\n\n\n", "file_path": "src/include/kdtree.hh", "rank": 18, "score": 28577.75842426644 }, { "content": "// File: view.hh\n\n\n\n// Author: Yuxin Wu <[email protected]>\n\n\n\n#pragma once\n\n\n\n#include <memory>\n\n#include \"geometry/geometry.hh\"\n\n#include \"render/space.hh\"\n\n\n", "file_path": "src/include/view.hh", "rank": 19, "score": 28577.626980138837 }, { "content": "// File: matrix.hh\n\n\n\n// Author: Yuxin Wu <[email protected]>\n\n\n\n#pragma once\n\n#include <cstring>\n\n#include \"lib/utils.hh\"\n\n#include \"lib/debugutils.hh\"\n\n\n\n// basic 2-d array\n\ntemplate <typename T>\n", "file_path": "src/include/matrix.hh", "rank": 20, "score": 28577.515044431588 }, { "content": "\t\tMatrix(Matrix&& r) {\n\n\t\t\tval = r.val;\n\n\t\t\tw = r.w, h = r.h;\n\n\t\t\tr.val = nullptr;\n\n\t\t}\n\n\t\t// something ugly\n\n\n\n\t\t// get the ith row\n\n\t\tT*& operator [] (int i) {\n\n\t\t\tm_assert((0 <= i) && (i <= h));\n\n\t\t\treturn val[i];\n\n\t\t}\n\n\n\n\t\tconst T*& operator [] (int i) const {\n\n\t\t\tm_assert((0 <= i) && (i <= h));\n\n\t\t\treturn val[i];\n\n\t\t}\n\n\n\n};\n\n\n", "file_path": "src/include/matrix.hh", "rank": 21, "score": 28577.17458021313 }, { "content": "\t\t\t}\n\n\t\t}\n\n\n\n\t\t~Matrix() {\n\n\t\t\tfor (int i = 0; i < h; i++)\n\n\t\t\t\tdelete [] val[i];\n\n\t\t\tdelete [] val;\n\n\t\t}\n\n\n\n\t\t// something bad\n\n\t\tMatrix(const Matrix& m) {\n\n\t\t\tw = m.w, h = m.h;\n\n\t\t\tval = new T* [h];\n\n\t\t\tREP(i, h) {\n\n\t\t\t\tval[i] = new T[w]();\n\n\t\t\t\tmemcpy(val[i], m.val[i], w * sizeof(T));\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\tMatrix & operator = (const Matrix & m) {\n", "file_path": "src/include/matrix.hh", "rank": 22, "score": 28576.27814240851 }, { "content": "\t\t\tif (this != &m) {\n\n\t\t\t\tw = m.w, h = m.h;\n\n\t\t\t\tval = new T* [h];\n\n\t\t\t\tREP(i, h) {\n\n\t\t\t\t\tval[i] = new T[w]();\n\n\t\t\t\t\tmemcpy(val[i], m.val[i], w * sizeof(T));\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\treturn *this;\n\n\t\t}\n\n\n\n\t\tMatrix & operator = (Matrix && r) {\n\n\t\t\tm_assert(this != &r);\n\n\t\t\tfree_2d<T>(val, h);\n\n\t\t\tval = r.val;\n\n\t\t\tw = r.w, h = r.h;\n\n\t\t\tr.val = nullptr;\n\n\t\t\treturn *this;\n\n\t\t}\n\n\n", "file_path": "src/include/matrix.hh", "rank": 23, "score": 28573.59164247879 }, { "content": "\t\t\t\t\t\t\t\t//sscanf(input + 3, \"%lf %lf %lf\", &x, &y, &z);\n\n\t\t\t\t\t\t\t\t//mesh->set_norm(nnorm++, Vec(x, y, z));\n\n\t\t\t\t\t\t\t\t//don't use vn\n\n\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\tstd::cout << input << std::endl;\n\n\t\t\t\t\t\t\t\terror_exit(\"unrecognized format\");\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\tcase 'f':\n\n\t\t\t\t\t\t{\t\t\t\t// XXX some model is 'f 1 2 3 4 5 6'\n\n\t\t\t\t\t\t\tint x, y, z;\n\n\t\t\t\t\t\t\tsscanf(input + 2, \"%d %d %d\", &x, &y, &z);\n\n\t\t\t\t\t\t\tif (x != y && y != z && x != z) mesh->add_faceid(x - 1, y - 1, z - 1);\n\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\tcase 'g':\n\n\t\t\t\t\tcase 'u':\n\n\t\t\t\t\tcase 'm':\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault:\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tfin.close();\n\n\t\t}\n\n};\n", "file_path": "src/include/lib/objreader.hh", "rank": 24, "score": 27336.740107986796 }, { "content": "\t\tshared_ptr<Trace> get_trace(const Ray& ray, real_t max_dist) const override;\n\n\n\n\t\tAABB get_aabb() const override;\n\n\n\n\tprotected:\n\n\n\n\t\tfriend class PlaneTrace;\n\n\n\n\t\tVec surf_dir() const;\n\n\n\n\t\tinline Vec surf_point() const\n\n\t\t{ return plane.norm * plane.offset; }\n\n\n\n};\n\n\n", "file_path": "src/include/renderable/plane.hh", "rank": 25, "score": 27335.862730045596 }, { "content": "#define COLOR_CYAN \"\\x1b[36m\"\n\n#define COLOR_RESET \"\\x1b[0m\"\n\n\n\ntypedef double real_t;\n\nconst real_t EPS = 1e-6;\n\n\n\ninline real_t sqr(real_t x) { return x * x; }\n\n\n\n#define BETW(a, b, c) ((a >= b) && (a <= c))\n\n#define REP(x, y) for (auto x = decltype(y){0}; x < (y); x ++)\n\n#define REPL(x, y, z) for (auto x = decltype(z){y}; x < (z); x ++)\n\n#define REPD(x, y, z) for (auto x = decltype(z){y}; x >= (z); x --)\n\n\n\n#define P(a) std::cout << (a) << std::endl\n\n#define PP(a) std::cout << #a << \" \" << (a) << std::endl\n\n\n\ntemplate <typename T>\n\ninline void free_2d(T** ptr, int w) {\n\n\tif (ptr != nullptr)\n\n\t\tfor (int i = 0; i < w; i ++)\n", "file_path": "src/include/lib/utils.hh", "rank": 26, "score": 27335.174840033316 }, { "content": "\n\n\t\tinline bool in_plane(const Vec& p) const\n\n\t\t{ return fabs(dist(p)) < EPS; }\n\n\n\n\t\t/*\n\n\t\t *bool parallel(const Ray& ray) const\n\n\t\t *{ return fabs(norm.dot(ray.dir)) < EPS; }\n\n\t\t */\n\n\n\n\t\tstatic const InfPlane XYPLANE;\n\n};\n\n\n", "file_path": "src/include/geometry/infplane.hh", "rank": 27, "score": 27333.682364283835 }, { "content": "// File: renderable.hh\n\n// Author: Yuxin Wu <[email protected]>\n\n\n\n#pragma once\n\n\n\n#include <memory>\n\n#include \"geometry/ray.hh\"\n\n#include \"geometry/aabb.hh\"\n\n#include \"material/texture.hh\"\n\nusing std::shared_ptr;\n\nusing std::make_shared;\n\n\n", "file_path": "src/include/renderable/renderable.hh", "rank": 28, "score": 27333.607634884902 }, { "content": "\t\t\tsmooth = r.smooth;\n\n\t\t\tmapped = r.mapped;\n\n\t\t\tuse_tree = r.use_tree;\n\n\t\t\tvtxs = r.vtxs;\n\n\t\t\tfaces = r.faces;\n\n\t\t\tface_ids = r.face_ids;\n\n\t\t\tbound_min = r.bound_min;\n\n\t\t\tbound_max = r.bound_max;\n\n\t\t\ttree = r.tree;\n\n\n\n\t\t\t// IMPORTANT!!\n\n\t\t\tfor (auto & k : faces) k->host = this;\n\n\t\t}\n\n\n\n\t\tMesh(std::string fname, const Vec& _pivot,\n\n\t\t\t\treal_t _zsize, const shared_ptr<Texture>& _texture = nullptr);\n\n\n\n\t\tvoid add_vertex(const Vec& p) {\n\n\t\t\tvtxs.emplace_back(p);\n\n\t\t\tbound_min.update_min(p - Vec::eps()), bound_max.update_max(p + Vec::eps());\n", "file_path": "src/include/renderable/mesh.hh", "rank": 29, "score": 27333.087283220935 }, { "content": "// File: utils.hh\n\n\n\n// Author: Yuxin Wu <[email protected]>\n\n\n\n\n\n#pragma once\n\n\n\n#include <cstdarg>\n\n#include <cstdlib>\n\n#include <type_traits>\n\n#include <string>\n\n#include <sstream>\n\n\n\nstd::string TERM_COLOR(int k);\n\n\n\n#define COLOR_RED \"\\x1b[31m\"\n\n#define COLOR_GREEN \"\\x1b[32m\"\n\n#define COLOR_YELLOW \"\\x1b[33m\"\n\n#define COLOR_BLUE \"\\x1b[34m\"\n\n#define COLOR_MAGENTA \"\\x1b[35m\"\n", "file_path": "src/include/lib/utils.hh", "rank": 30, "score": 27332.706546157584 }, { "content": "// File: space.hh\n\n\n\n// Author: Yuxin Wu <[email protected]>\n\n\n\n#pragma once\n\n\n\n#include <vector>\n\n#include <list>\n\n#include <memory>\n\n\n\n#include \"renderable/renderable.hh\"\n\n#include \"renderable/light.hh\"\n\n#include \"kdtree.hh\"\n\n#include \"const.hh\"\n\nusing std::vector;\n\nusing std::list;\n\nusing std::shared_ptr;\n\nusing std::make_shared;\n\n\n", "file_path": "src/include/render/space.hh", "rank": 31, "score": 27332.246501773436 }, { "content": "// File: face.hh\n\n\n\n// Author: Yuxin Wu <[email protected]>\n\n\n\n#pragma once\n\n#include <memory>\n\n#include <vector>\n\n\n\n#include \"lib/debugutils.hh\"\n\n#include \"renderable/renderable.hh\"\n\n#include \"geometry/geometry.hh\"\n\nusing std::vector;\n\nusing std::array;\n\nusing std::shared_ptr;\n\n\n", "file_path": "src/include/renderable/face.hh", "rank": 32, "score": 27331.76918249636 }, { "content": "// File: mesh_simplifier.hh\n\n\n\n// Author: Yuxin Wu <[email protected]>\n\n\n\n#pragma once\n\n\n\n#include <vector>\n\n#include <unordered_set>\n\n#include <queue>\n\n#include \"renderable/mesh.hh\"\n\nusing std::vector;\n\nusing std::unordered_set;\n\nusing std::priority_queue;\n\n\n", "file_path": "src/include/mesh_simplifier.hh", "rank": 33, "score": 27331.764748741458 }, { "content": "\t\t\t\t\t::update_min(t_max, tmp_max); \\\n\n\t\t\t\t\tif (t_min + EPS > t_max) return false; \\\n\n\t\t\t\t} \\\n\n\t\t\t} while (0)\n\n\t\t\tUPDATE(x); UPDATE(y); UPDATE(z);\n\n#undef UPDATE\n\n\n\n\t\t\tif (t_max < 0) return false;\n\n\n\n\t\t\tif (t_min < 0) mind = t_max, inside = true;\n\n\t\t\telse mind = t_min, inside = false;\n\n\t\t\tif (ray.debug)\n\n\t\t\t\tstd::cout << \"intersect with box \" << (*this) << \" at \" << mind << \", inside: \" << inside << std::endl;\n\n\t\t\treturn true;\n\n\t\t}\n\n\n\n};\n\n\n", "file_path": "src/include/geometry/aabb.hh", "rank": 34, "score": 27331.712030504073 }, { "content": "\n\n\t\tvoid simplify(real_t ratio);\n\n\n\n\t\tvoid clear() {\n\n\t\t\tvtxs.clear(); faces.clear(); face_ids.clear();\n\n\t\t\tbound_min = Vec::max(), bound_max = -Vec::max();\n\n\t\t\ttree = nullptr;\n\n\t\t}\n\n\n\n\t\tshared_ptr<Trace> get_trace(const Ray& ray, real_t max_dist) const override;\n\n\n\n\t\tAABB get_aabb() const override\n\n\t\t{ return AABB(bound_min, bound_max); }\n\n\n\n\tprotected:\n\n\t\tvoid add_face(int a, int b, int c) {\n\n\t\t\tm_assert(INRANGE(std::max(a, std::max(b, c))));\n\n\t\t\tFace f(vtxs, a, b, c);\n\n\t\t\tf.host = this;\n\n\t\t\tfaces.push_back(make_shared<Face>(f));\n\n\t\t}\n\n};\n", "file_path": "src/include/renderable/mesh.hh", "rank": 35, "score": 27331.573976112304 }, { "content": "\t\tvoid add_light(const Light& light);\n\n\n\n\t\tvoid add_obj(const rdptr& objptr);\n\n\n\n\t\t// useful, keep lights\n\n\t\tvirtual void clear()\n\n\t\t{ objs.clear(); bound_min = Vec::max(), bound_max = -Vec::max(); }\n\n\n\n\t\tvirtual void finish();\n\n\n\n\t\tvoid build_tree();\n\n\n\n\t\tvirtual Color trace(const Ray& ray) const = 0;\n\n};\n\n\n", "file_path": "src/include/render/space.hh", "rank": 36, "score": 27331.37462974281 }, { "content": "\n\n\t\tvirtual Vec intersection_point() const {\n\n\t\t\tm_assert(std::isfinite(inter_dist) && inter_dist >= 0);\n\n\t\t\treturn ray.get_dist(inter_dist);\n\n\t\t}\n\n\n\n\t\tvirtual bool intersect(real_t) const = 0;\n\n\n\n\t\tvirtual real_t intersection_dist() const = 0;\n\n\n\n\t\tvirtual Vec normal() const = 0;\n\n\t\t// return Vec::zero if no normal exists\n\n\t\t// return a `normalized` normal vector\n\n\n\n\t\tvirtual real_t get_forward_density() const\n\n\t\t{ return ray.density; }\n\n\n\n\t\tvirtual bool contain() const\n\n\t\t{ return false; }\n\n\n", "file_path": "src/include/renderable/renderable.hh", "rank": 37, "score": 27331.209399038933 }, { "content": "// File: texture.hh\n\n\n\n// Author: Yuxin Wu <[email protected]>\n\n\n\n#pragma once\n\n\n\n#include <memory>\n\n#include \"material/surface.hh\"\n\n#include \"lib/imagereader.hh\"\n\nusing std::shared_ptr;\n\nusing std::make_shared;\n\n\n", "file_path": "src/include/material/texture.hh", "rank": 38, "score": 27331.093848468387 }, { "content": "\t\t{ return fabs(x - v.x) >= EPS or fabs(y - v.y) >= EPS or fabs(z - v.z) >= EPS; }\n\n\n\n\t\tinline const real_t& operator [](int c) const\n\n\t\t{ return c == 0 ? x : c == 1 ? y : z; }\n\n\n\n\t\tinline real_t& operator [](int c)\n\n\t\t{ return c == 0 ? x : c == 1 ? y : z; }\n\n\n\n\t\t// geometry\n\n\t\t//\n\n\t\t// i'm norm\n\n\t\tVector reflection(const Vector& v) const {\n\n\t\t\tm_assert(fabs(v.sqr() - 1) < EPS && (fabs(sqr() - 1) < EPS));\n\n\t\t\treturn *this * 2 * dot(v) - v;\n\n\t\t}\n\n\n\n\t\t// i'm norm, return normalized result\n\n\t\tVector transmission(const Vector& v_in, real_t density) const {\n\n\t\t\t// density = out_dens / in_dens\n\n\t\t\tVector ret = Vector::infinity();\n", "file_path": "src/include/geometry/geometry.hh", "rank": 39, "score": 27330.572387830503 }, { "content": "\t\tInfPlane(const Vec& v1, const Vec& v2, const Vec& v3) {\n\n\t\t\tnorm = (v2 - v1).cross(v3 - v1);\n\n\t\t\tnorm.normalize();\n\n\t\t\toffset = norm.dot(v1);\n\n\t\t}\n\n\n\n\t\t// ax + by + cz + w == 0\n\n\t\tInfPlane(real_t a, real_t b, real_t c, real_t w) {\n\n\t\t\tnorm = Vec(a, b, c);\n\n\t\t\tnorm.normalize();\n\n\t\t\toffset = -w;\n\n\t\t}\n\n\n\n\t\tvirtual ~InfPlane(){}\n\n\n\n\t\tinline real_t dist(const Vec& p) const\n\n\t\t{ return p.dot(norm) - offset; }\n\n\n\n\t\tinline bool in_half_space(const Vec& p) const\n\n\t\t{ return dist(p) >= EPS; }\n", "file_path": "src/include/geometry/infplane.hh", "rank": 40, "score": 27330.517345917353 }, { "content": "\n\n\t\tVec get_smooth_norm(real_t gx, real_t gy) const;\n\n\n\n\t\tAABB get_aabb() const override;\n\n\n\n\tprotected:\n\n\t\tfriend class FaceTrace;\n\n\n\n\t\tVec get_norm(int i) const;\n\n\n\n};\n\n\n", "file_path": "src/include/renderable/face.hh", "rank": 41, "score": 27330.437445630014 }, { "content": "\t\t\tr.min[pl.axis] = pl.pos;\n\n\t\t\treturn std::make_pair(l, r);\n\n\t\t}\n\n\n\n\t\t// An efficient and robust ray-box intersection algorithm\n\n\t\t// Williams, etc. SIGGRAPH 2005\n\n\t\tbool intersect(const Ray& ray, real_t &mind, bool &inside) {\n\n\t\t\tif (empty())\n\n\t\t\t\treturn false;\n\n\t\t\tVec inv(1.0 / ray.dir.x, 1.0 / ray.dir.y, 1.0 / ray.dir.z);\n\n\t\t\treal_t t_max = std::numeric_limits<real_t>::max(),\n\n\t\t\t\t t_min = -t_max;\n\n\n\n#define UPDATE(t) \\\n\n\t\t\tdo { \\\n\n\t\t\t\tif (fabs(ray.dir.t) > EPS) { \\\n\n\t\t\t\t\tbool sign = (inv.t < 0); \\\n\n\t\t\t\t\treal_t tmp_min = ((sign ? max : min).t - ray.orig.t) * inv.t; \\\n\n\t\t\t\t\treal_t tmp_max = ((sign ? min : max).t - ray.orig.t) * inv.t; \\\n\n\t\t\t\t\t::update_max(t_min, tmp_min); \\\n", "file_path": "src/include/geometry/aabb.hh", "rank": 42, "score": 27330.33942806452 }, { "content": "// File: geometry.hh\n\n\n\n// Author: Yuxin Wu <[email protected]>\n\n\n\n#pragma once\n\n\n\n#include <vector>\n\n#include <cmath>\n\n#include <limits>\n\nusing std::numeric_limits;\n\n\n\n#include \"lib/debugutils.hh\"\n\n#include \"lib/utils.hh\"\n\n\n", "file_path": "src/include/geometry/geometry.hh", "rank": 43, "score": 27329.762905537078 }, { "content": "// File: plane.hh\n\n\n\n// Author: Yuxin Wu <[email protected]>\n\n\n\n#pragma once\n\n\n\n#include <limits>\n\n#include \"renderable/renderable.hh\"\n\n#include \"geometry/infplane.hh\"\n\nusing std::shared_ptr;\n\n\n", "file_path": "src/include/renderable/plane.hh", "rank": 44, "score": 27329.708829470525 }, { "content": "\t\t{ return std::isfinite(x) && std::isfinite(y) && std::isfinite(z); }\n\n\n\n\t\tfriend inline std::ostream & operator << (std::ostream &os, const Vector& vec)\n\n\t\t{ return os << vec.x << \" \" << vec.y << \" \" << vec.z;}\n\n\n\n\t\tfriend inline Vector operator * (real_t x, const Vector& vec)\n\n\t\t{ return vec * x; }\n\n};\n\n\n\n\n\ntemplate<typename T>\n", "file_path": "src/include/geometry/geometry.hh", "rank": 45, "score": 27328.631866917818 }, { "content": "\n\n\t\tstatic Color get(const cv::Mat& img, int x, int y);\n\n\n\n\t\tColor get(int x, int y) const\n\n\t\t{ return MyRender::get(img, x, y); }\n\n\n\n\tprotected:\n\n\t\tvoid _write(int x, int y, const Color& c) override;\n\n};\n\n\n", "file_path": "src/include/librender/myrender.hh", "rank": 46, "score": 27328.52471802816 }, { "content": "\t\tvoid update(const AABB& b) {\n\n\t\t\tmin.update_min(b.min);\n\n\t\t\tmax.update_max(b.max);\n\n\t\t}\n\n\n\n\t\tinline void update(const Vec& v) {\n\n\t\t\tupdate_min(v);\n\n\t\t\tupdate_max(v);\n\n\t\t}\n\n\n\n\t\tinline void update_min(const Vec& v) { min.update_min(v); }\n\n\t\tinline void update_max(const Vec& v) { max.update_max(v); }\n\n\n\n\t\tstd::pair<AABB, AABB> cut(const AAPlane& pl) const {\n\n\t\t\tAABB l = *this, r = *this;\n\n\t\t\tif (!BETW(pl.pos, min[pl.axis] + 2 * EPS, max[pl.axis] - 2 * EPS))\n\n\t\t\t\t// !! otherwise, l.max or r.min can be equal to *this.max / *this.min,\n\n\t\t\t\t// resulting a same boundbox in child\n\n\t\t\t\tthrow \"Outside\";\n\n\t\t\tl.max[pl.axis] = pl.pos;\t\t// to loose\n", "file_path": "src/include/geometry/aabb.hh", "rank": 47, "score": 27327.62698142382 }, { "content": "\t\t}\n\n\n\n\t\t/*\n\n\t\t *void set_mapcoor(int t, const Vec2D& mapped) {\n\n\t\t * m_assert(INRANGE(t));\n\n\t\t * vtxs[t].mapcoor = mapped;\n\n\t\t *}\n\n\t\t */\n\n\n\n\t\tvoid add_faceid(int a, int b, int c) {\n\n\t\t\tm_assert(INRANGE(std::max(a, std::max(b, c))));\n\n\t\t\tface_ids.emplace_back(array<int, 3>{{a, b, c}});\n\n\t\t}\n\n\n\n\t\tvoid add_face(const array<int, 3>& t)\n\n\t\t{ add_face(t[0], t[1], t[2]); }\n\n\n\n\t\tvoid transform_vtxs();\n\n\n\n\t\tvoid finish();\n", "file_path": "src/include/renderable/mesh.hh", "rank": 48, "score": 27327.45597972814 }, { "content": "// File: aabb.hh\n\n\n\n// Author: Yuxin Wu <[email protected]>\n\n\n\n#pragma once\n\n#include <utility>\n\n#include <iostream>\n\n#include <limits>\n\n\n\n#include \"geometry/ray.hh\"\n\n\n", "file_path": "src/include/geometry/aabb.hh", "rank": 49, "score": 27327.322890684376 }, { "content": "// File: imagereader.hh\n\n\n\n// Author: Yuxin Wu <[email protected]>\n\n\n\n#pragma once\n\n\n\n#include <string>\n\n#include <Magick++.h>\n\n#include \"color.hh\"\n\n\n", "file_path": "src/include/lib/imagereader.hh", "rank": 50, "score": 27327.26912054955 }, { "content": "\n\n\t\tstatic inline Vector zero()\n\n\t\t{ return Vector(0, 0, 0); }\n\n\n\n\t\tstatic inline Vector eps()\n\n\t\t{ return Vector(EPS, EPS, EPS); }\n\n\n\n\t\tinline real_t get_max()\n\n\t\t{ return std::max(x, std::max(y, z)); }\n\n\n\n\t\tinline real_t get_abs_max()\n\n\t\t{ return abs().get_max(); }\n\n\n\n\t\tinline bool is_zero(real_t threshold = EPS) const\n\n\t\t{ return fabs(x) < threshold && fabs(y) < threshold && fabs(z) < threshold; }\n\n\n\n\t\tinline bool is_positive(real_t threshold = EPS) const\n\n\t\t{ return x > threshold && y > threshold && z > threshold; }\n\n\n\n\t\tinline bool isfinite() const\n", "file_path": "src/include/geometry/geometry.hh", "rank": 51, "score": 27327.204878649634 }, { "content": "// File: matrixrender.hh\n\n\n\n// Author: Yuxin Wu <[email protected]>\n\n\n\n#pragma once\n\n\n\n#include \"color.hh\"\n\n#include \"matrix.hh\"\n\n#include \"render.hh\"\n\n\n", "file_path": "src/include/librender/matrixrender.hh", "rank": 52, "score": 27327.147570524205 }, { "content": "// File: render.hh\n\n\n\n// Author: Yuxin Wu <[email protected]>\n\n\n\n\n\n#pragma once\n\n\n\n#include \"matrix.hh\"\n\n#include \"color.hh\"\n\n#include \"lib/imagereader.hh\"\n\n\n", "file_path": "src/include/librender/render.hh", "rank": 53, "score": 27327.088574404617 }, { "content": "\t\tfriend std::ostream& operator << (std::ostream& os, const Vector2D<TT>& v);\n\n\n\n\t\tvoid update_min(const Vector2D<T> &v)\n\n\t\t{ ::update_min(x, v.x); ::update_min(y, v.y);}\n\n\n\n\t\tvoid update_max(const Vector2D<T> &v)\n\n\t\t{ ::update_max(x, v.x); ::update_max(y, v.y);}\n\n\n\n\t\tstatic Vector2D<T> infinity()\n\n\t\t{ return Vector2D<T>(numeric_limits<T>::infinity(), numeric_limits<T>::infinity()); }\n\n};\n\n\n\ntemplate<typename T>\n\nstd::ostream& operator << (std::ostream& os, const Vector2D<T>& v) {\n\n\tos << v.x << ' ' << v.y;\n\n\treturn os;\n\n}\n\n\n\ntypedef Vector Vec;\n\ntypedef Vector2D<int> Coor;\n\n\n\ntypedef Vector2D<real_t> Vec2D;\n\n\n\ntypedef std::pair<Coor, Coor> Line2D;\n\n\n", "file_path": "src/include/geometry/geometry.hh", "rank": 54, "score": 27327.02709243852 }, { "content": "// File: mesh.hh\n\n\n\n// Author: Yuxin Wu <[email protected]>\n\n\n\n#pragma once\n\n#include <string>\n\n#include \"renderable/face.hh\"\n\n#include \"kdtree.hh\"\n\n\n\n#define INRANGE(x) (x) < (int)vtxs.size()\n\n\n", "file_path": "src/include/renderable/mesh.hh", "rank": 55, "score": 27326.843786111192 }, { "content": "\t\t\tinline bool contain(Vertex* v) const\n\n\t\t\t{ return (v == vtx[0]) + (v == vtx[1]) + (v == vtx[2]) == 1; }\n\n\n\n\t\t\tinline int count(Vertex* v) const\n\n\t\t\t{ return (v == vtx[0]) + (v == vtx[1]) + (v == vtx[2]); }\n\n#endif\n\n\t\t};\n\n\n\n\t\tstruct Vertex {\n\n\t\t\tVec pos;\n\n\t\t\tint id = -1;\n\n\t\t\tbool erased = false;\n\n\t\t\tunordered_set<Vertex*> adj_vtx;\n\n\t\t\tunordered_set<Face*> adj_face;\n\n\n\n\t\t\tint cost_timestamp = 0;\n\n\t\t\treal_t cost;\n\n\t\t\tVertex* candidate = nullptr;\n\n\n\n\t\t\tVertex(Vec _pos, int _id = -1):pos(_pos), id(_id) {}\n", "file_path": "src/include/mesh_simplifier.hh", "rank": 56, "score": 27326.782790418933 }, { "content": "// File: infplane.hh\n\n\n\n// Author: Yuxin Wu <[email protected]>\n\n\n\n\n\n#pragma once\n\n\n\n#include \"geometry/geometry.hh\"\n\n#include \"geometry/ray.hh\"\n\n\n\n// geometry plane object\n", "file_path": "src/include/geometry/infplane.hh", "rank": 57, "score": 27326.75855500132 }, { "content": "// File: light.hh\n\n\n\n// Author: Yuxin Wu <[email protected]>\n\n\n\n#pragma once\n\n\n\n#include \"geometry/geometry.hh\"\n\n#include \"renderable/sphere.hh\"\n\n\n\n#include <cmath>\n\n\n\n/**\n\n *\tlight is a sphere\n\n *\tbut in phone model, only the center will be used\n\n */\n", "file_path": "src/include/renderable/light.hh", "rank": 58, "score": 27326.752233138075 }, { "content": "\t\t\tREP(i, geo.w) REP(j, geo.h)\n\n\t\t\t\twrite(i, j, m[j][i]);\n\n\t\t}\n\n\n\n\t\tvoid write(ImageReader* r) {\n\n\t\t\tm_assert((r->size.h == geo.h) && (r->size.w == geo.w));\n\n\t\t\tColor *dest = r->pixel;\n\n\t\t\tREP(i, geo.h) REP(j, geo.w) {\n\n\t\t\t\twrite(j, i, *dest);\n\n\t\t\t\tdest ++;\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\tconst Geometry& get_geo() const\n\n\t\t{ return geo; }\n\n\n\n\tprotected:\n\n\t\tGeometry geo;\n\n\t\tvirtual void _write(int x, int y, const Color &c) = 0;\n\n};\n\n\n\n\n", "file_path": "src/include/librender/render.hh", "rank": 59, "score": 27326.624338597172 }, { "content": "// File: surface.hh\n\n\n\n// Author: Yuxin Wu <[email protected]>\n\n\n\n#pragma once\n\n\n\n#include \"color.hh\"\n\n\n", "file_path": "src/include/material/surface.hh", "rank": 60, "score": 27326.503123242794 }, { "content": "\n\n\t\tbool intersect(real_t) const override;\n\n\n\n\t\tVec intersection_point() const override;\n\n\n\n\t\treal_t intersection_dist() const override;\n\n\n\n\t\tVec normal() const override;\n\n\n\n\t\treal_t get_forward_density() const override;\n\n\n\n\t\tbool contain() const override\n\n\t\t{ return inside; }\n\n\n\n};\n", "file_path": "src/include/renderable/sphere.hh", "rank": 61, "score": 27326.487501839365 }, { "content": "\n\n\t\t\treal_t cos1 = -dot(v_in);\n\n\t\t\tm_assert(cos1 >= 0);\n\n\t\t\t//if (cos1 < EPS) return ret; // norm should towards ray dir, so this can only happen with mesh\n\n\t\t\t//if (cos1 / v_in.mod() < EPS) return v_in.get_normalized();\n\n\t\t\treal_t cos2 = 1 - ::sqr(density) * (1 - ::sqr(cos1));\n\n\t\t\tm_assert(cos2 >= 0);\n\n\t\t\tif (cos2 < 0) return ret;\n\n\t\t\tcos2 = sqrt(cos2);\n\n\n\n\t\t\tret = v_in * density + (*this) * (density * cos1 - cos2);\n\n\t\t\treturn ret.get_normalized();\n\n\t\t}\n\n\n\n\t\t// utility\n\n\t\tstatic inline Vector max()\n\n\t\t{ return Vector(numeric_limits<real_t>::max(), numeric_limits<real_t>::max(), numeric_limits<real_t>::max()); }\n\n\n\n\t\tstatic inline Vector infinity()\n\n\t\t{ return Vector(numeric_limits<real_t>::infinity(), numeric_limits<real_t>::infinity(), numeric_limits<real_t>::infinity()); }\n", "file_path": "src/include/geometry/geometry.hh", "rank": 62, "score": 27326.254288645363 }, { "content": "\n\ninline std::string string_format(const char* fmt, ...) {\n\n\tint size = 512;\n\n\tchar* buffer = 0;\n\n\tbuffer = new char[size];\n\n\tva_list ap;\n\n\tva_start(ap, fmt);\n\n\tint nsize = vsnprintf(buffer, size, fmt, ap);\n\n\tif(size <= nsize){ //fail delete buffer and try again\n\n\t\tdelete[] buffer;\n\n\t\tbuffer = 0;\n\n\t\tbuffer = new char[nsize + 1]; //+1 for /0\n\n\t\tnsize = vsnprintf(buffer, size, fmt, ap);\n\n\t}\n\n\tstd::string ret(buffer);\n\n\tva_end(ap);\n\n\tdelete[] buffer;\n\n\treturn ret;\n\n}\n\n\n\ninline void print_progress(int percent) {\n\n\tprintf(\"progress: %d %%\\r\", percent);\n\n\tfflush(stdout);\n\n}\n", "file_path": "src/include/lib/utils.hh", "rank": 63, "score": 27325.994274447 }, { "content": "\n\n\t\t\tinline void add_face(Face* f) {\n\n\t\t\t\tadj_face.insert(f);\n\n\t\t\t\tREP(k, 3) if (f->vtx[k] != this)\n\n\t\t\t\t\tadj_vtx.insert(f->vtx[k]);\n\n\t\t\t}\n\n\n\n\t\t\t// change adj_vtx, u to v\n\n\t\t\tvoid change_to(Vertex* u, Vertex* v);\n\n\t\t};\n\n\n\n\t\tstruct Elem {\n\n\t\t\t// element type to use in the heap\n\n\t\t\tVertex* v;\n\n\t\t\tint cost_timestamp;\n\n\n\n\t\t\tElem(Vertex* _v) :\n\n\t\t\t\tv(_v), cost_timestamp(v->cost_timestamp) {}\n\n\n\n\t\t\tbool operator < (const Elem& r) const\n", "file_path": "src/include/mesh_simplifier.hh", "rank": 64, "score": 27324.90761676072 }, { "content": "\n\n\t\tinline Vector& operator -= (const Vector &v)\n\n\t\t{ x -= v.x; y -= v.y; z -= v.z; return *this; }\n\n\n\n\t\tinline Vector operator * (real_t p) const\n\n\t\t{ return Vector(x * p, y * p, z * p); }\n\n\n\n\t\tinline Vector& operator *= (real_t p)\n\n\t\t{ x *= p; y *= p; z *= p; return *this; }\n\n\n\n\t\tinline Vector operator / (real_t p) const\n\n\t\t{ return *this * (1.0 / p); }\n\n\n\n\t\tinline bool operator == (const Vector &v) const\n\n\t\t{ return fabs(x - v.x) < EPS && fabs(y - v.y) < EPS && fabs(z - v.z) < EPS; }\n\n\n\n\t\tinline bool operator < (const Vector &v) const\t\t\t// loose judge\n\n\t\t{ return x < v.x + EPS && y < v.y + EPS && z < v.z + EPS; }\n\n\n\n\t\tinline bool operator != (const Vector &v) const\n", "file_path": "src/include/geometry/geometry.hh", "rank": 65, "score": 27324.407183813964 }, { "content": "\n\n\t\tconst shared_ptr<Texture>& get_texture() const\n\n\t\t{ return texture; }\n\n\n\n\t\tvirtual shared_ptr<Trace> get_trace(const Ray& ray, real_t max_dist) const = 0;\n\n\t\t// judge visibility and return ptr if visible\n\n\n\n\t\tshared_ptr<Trace> get_trace(const Ray& ray) const\n\n\t\t{ return get_trace(ray, -1); }\n\n\n\n\t\tvirtual AABB get_aabb() const = 0;\n\n};\n\n\n", "file_path": "src/include/renderable/renderable.hh", "rank": 66, "score": 27324.3201339099 }, { "content": "// File: objreader.hh\n\n\n\n// Author: Yuxin Wu <[email protected]>\n\n\n\n#pragma once\n\n#include <cstring>\n\n#include <fstream>\n\n#include \"renderable/mesh.hh\"\n\n\n", "file_path": "src/include/lib/objreader.hh", "rank": 67, "score": 27324.26237115752 }, { "content": "// File: myrender.hh\n\n\n\n// Author: Yuxin Wu <[email protected]>\n\n\n\n\n\n#pragma once\n\n#include <opencv2/opencv.hpp>\n\n\n\n#include <string>\n\n#include \"render.hh\"\n\n\n", "file_path": "src/include/librender/myrender.hh", "rank": 68, "score": 27324.23894583187 }, { "content": "// File: sphere.hh\n\n\n\n// Author: Yuxin Wu <[email protected]>\n\n\n\n#pragma once\n\n\n\n#include \"geometry/sphere.hh\"\n\n#include \"renderable/renderable.hh\"\n\n\n", "file_path": "src/include/renderable/sphere.hh", "rank": 69, "score": 27323.916148940356 }, { "content": "//File: random.hh\n\n\n\n//Author: Yuxin Wu <[email protected]>\n\n\n\n#pragma once\n\n#include \"lib/utils.hh\"\n\n#include <random>\n\n\n\ntemplate <typename T>\n", "file_path": "src/include/lib/random.hh", "rank": 70, "score": 27323.886781687128 }, { "content": "// File: Timer.h\n\n\n\n// Author: Yuxin Wu <[email protected]>\n\n\n\n#pragma once\n\n#ifdef WIN32 // Windows system specific\n\n#include <windows.h>\n\n#else // Unix based system specific\n\n#include <sys/time.h>\n\n#endif\n\n\n\n\n", "file_path": "src/include/lib/Timer.hh", "rank": 71, "score": 27323.77378917569 }, { "content": "\t\tVector2D<T> operator ! () const\n\n\t\t{ return Vector2D<T>(x, -y); }\n\n\n\n\t\t// swap the two component\n\n\t\tVector2D<T> operator ~ () const\n\n\t\t{ return Vector2D<T>(y, x); }\n\n\n\n\t\tbool is_zero() const\n\n\t\t{ return fabs(x) < EPS && fabs(y) < EPS; }\n\n\n\n\t\tT sqr() const\n\n\t\t{ return x * x + y * y; }\n\n\n\n\t\treal_t mod() const\n\n\t\t{ return hypot(x, y); }\n\n\n\n\t\tVector2D<T> get_normalized() const\n\n\t\t{ real_t m = mod(); m_assert(m > EPS); m = 1 / m; return Vector2D<T>(x * m, y * m); }\n\n\n\n\t\ttemplate <typename TT>\n", "file_path": "src/include/geometry/geometry.hh", "rank": 72, "score": 27323.766371436814 }, { "content": "// File: sphere.hh\n\n\n\n// Author: Yuxin Wu <[email protected]>\n\n\n\n#pragma once\n\n#include \"geometry/geometry.hh\"\n\n\n", "file_path": "src/include/geometry/sphere.hh", "rank": 73, "score": 27323.316880426435 }, { "content": "//File: phong.hh\n\n\n\n//Author: Yuxin Wu <[email protected]>\n\n\n\n#pragma once\n\n\n\n#include \"render/space.hh\"\n\n\n", "file_path": "src/include/render/phong.hh", "rank": 74, "score": 27323.316880426435 }, { "content": "\t\t\tdelete[] ptr[i];\n\n\tdelete[] ptr;\n\n}\n\n\n\ntemplate<typename T>\n\nbool update_min(T &dest, const T &val) {\n\n\tif (val < dest) { dest = val; return true; }\n\n\treturn false;\n\n}\n\n\n\ntemplate<typename T>\n\nbool update_max(T &dest, const T &val) {\n\n\tif (dest < val) { dest = val; return true; }\n\n\treturn false;\n\n}\n\n\n\n\n\nvoid c_printf(const char* col, const char* fmt, ...);\n\n\n\nvoid c_fprintf(const char* col, FILE* fp, const char* fmt, ...);\n", "file_path": "src/include/lib/utils.hh", "rank": 75, "score": 27323.24883113191 }, { "content": "\n\n\t\tVector2D<T>& operator += (const Vector2D<T> &v)\n\n\t\t{ x += v.x; y += v.y; return *this; }\n\n\n\n\t\tVector2D<T> operator - (const Vector2D<T> &v) const\n\n\t\t{ return Vector2D<T>(x - v.x, y - v.y); }\n\n\n\n\t\tVector2D<T>& operator -= (const Vector2D<T> &v)\n\n\t\t{ x -= v.x; y -= v.y; return *this; }\n\n\n\n\t\tVector2D<T> operator * (real_t f) const\n\n\t\t{ return Vector2D<T>(x * f, y * f); }\n\n\n\n\t\tVector2D<T> operator / (real_t f) const\n\n\t\t{ return *this * (1.0 / f); }\n\n\n\n\t\tbool operator == (const Vector2D<T> &v) const\n\n\t\t{ return fabs(x - v.x) < EPS && fabs(y - v.y) < EPS; }\n\n\n\n\t\t// take negative of the second component\n", "file_path": "src/include/geometry/geometry.hh", "rank": 76, "score": 27323.176192225405 }, { "content": "//File: MCPT.hh\n\n\n\n//Author: Yuxin Wu <[email protected]>\n\n\n\n#pragma once\n\n#include \"render/space.hh\"\n\n\n\n// Monte Carlo Path Tracing\n", "file_path": "src/include/render/MCPT.hh", "rank": 77, "score": 27323.15839494727 }, { "content": "\t\t\t{ return v->cost > r.v->cost; }\n\n\n\n\t\t\tinline bool outofdate() const\n\n\t\t\t{ return cost_timestamp < v->cost_timestamp; }\n\n\t\t};\n\n\n\n\t\tvector<Vertex> vtxs;\n\n\t\tvector<Face> faces;\n\n\t\tint target_num;\t\t\t// shrink to this number\n\n\t\tpriority_queue<Elem> heap;\n\n\n\n\t\treal_t cost(Vertex*, Vertex*) const;\n\n\n\n\t\tvoid update_cost(Vertex*);\n\n\n\n\t\tint collapse(Vertex*, Vertex*);\t\t// return the number of faces it simplified\n\n\n\n\t\tvoid do_simplify();\n\n\n\n\t\tvoid write_back();\n\n\n\n\tpublic:\n\n\t\tMeshSimplifier(Mesh& mesh, real_t _ratio);\n\n\n\n\t\tvoid simplify();\n\n};\n", "file_path": "src/include/mesh_simplifier.hh", "rank": 78, "score": 27323.07008752371 }, { "content": "\n\n\t\tinline real_t area() const // require *this > 0\n\n\t\t{ return x * y + y * z + z * x; }\n\n\n\n\t\tinline real_t dot(const Vector &v) const\n\n\t\t{ return x * v.x + y * v.y + z * v.z; }\n\n\n\n\t\tVector cross(const Vector &v) const\t\t// this cross v\n\n\t\t{ return Vector(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x); }\n\n\n\n\t\tVector& operator = (const Vector& v)\n\n\t\t{ x = v.x, y = v.y, z = v.z; return *this; }\n\n\n\n\t\tvirtual void normalize() {\n\n\t\t\treal_t m = 1.0 / mod();\n\n\t\t\t*this *= m;\t\t// work?\n\n\t\t\tm_assert(std::isfinite(m));\n\n\t\t}\n\n\n\n\t\tinline Vector get_normalized() const\n", "file_path": "src/include/geometry/geometry.hh", "rank": 79, "score": 27322.851816009457 }, { "content": "\t__m_assert_check__((expr), # expr, __FILE__, __PRETTY_FUNCTION__, __LINE__)\n\n\n\n\n\nvoid __print_debug__(const char *file, const char *func, int line, const char *fmt, ...)\n\n\t__attribute__((format(printf, 4, 5)));\n\n\n\n#else\n\n\n\n#define print_debug(fmt, ...)\n\n\n\n#define m_assert(expr)\n\n\n\n\n\n#endif\n", "file_path": "src/include/lib/debugutils.hh", "rank": 80, "score": 27322.7765565032 }, { "content": "\t\tvirtual shared_ptr<Surface> get_property() const {\n\n\t\t\tshared_ptr<Surface> ret = get_obj()->get_texture()->get_property();\n\n\t\t\tif (ret) return ret;\n\n\t\t\treturn transform_get_property();\n\n\t\t}\n\n\n\n\t\tvirtual IntersectInfo get_intersect_info() const {\n\n\t\t\treturn IntersectInfo{normal(),\n\n\t\t\t\t\tintersection_point(),\n\n\t\t\t\t\tget_property(),\n\n\t\t\t\t\tget_forward_density(),\n\n\t\t\t\t\tintersection_dist(),\n\n\t\t\t\t\tcontain()};\n\n\t\t}\n\n};\n\n\n", "file_path": "src/include/renderable/renderable.hh", "rank": 81, "score": 27322.56898118681 }, { "content": "// File: debugutils.hh\n\n\n\n// Author: Yuxin Wu <[email protected]>\n\n\n\n\n\n#pragma once\n\n\n\nvoid __m_assert_check__(bool val, const char *expr,\n\n\t\tconst char *file, const char *func, int line);\n\n\n\n\n\nvoid error_exit(const char *msg) __attribute__((noreturn));\n\n\n\n\n\n#ifdef DEBUG\n\n\n\n#define print_debug(fmt, ...) \\\n\n\t\t\t__print_debug__(__FILE__, __func__, __LINE__, fmt, ## __VA_ARGS__)\n\n\n\n#define m_assert(expr) \\\n", "file_path": "src/include/lib/debugutils.hh", "rank": 82, "score": 27322.34048068143 }, { "content": "class View {\n\n\tprivate:\n\n\t\tconst Geometry geo;\n\n\n\n\t\tinline void normalize_dir_vector()\n\n\t\t{ dir_w.normalize(); dir_h.normalize(); }\n\n\n\n\t\tinline void restore_dir_vector() {\n\n\t\t\t// we should have: |dir_w| * geo.w == size\n\n\t\t\t// as well as:\t\t |dir_w| == |dir_h|\n\n\t\t\tdir_w = dir_w.get_normalized() * (size / geo.w);\n\n\t\t\tdir_h = dir_h.get_normalized() * (size / geo.w);\n\n\t\t}\n\n\n\n\t\tconst Space& sp;\n\n\n\n\tpublic:\n\n\t\tVec view_point;\n\n\t\tVec mid;\n\n\t\treal_t size;\t\t// length the img cover in the scene\n", "file_path": "src/include/view.hh", "rank": 83, "score": 27320.180450178486 }, { "content": "\t\t{ Vector ret(*this); ret.normalize(); return ret; }\n\n\n\n\t\tinline void update_min(const Vector &v)\n\n\t\t{ ::update_min(x, v.x); ::update_min(y, v.y); ::update_min(z, v.z); }\n\n\n\n\t\tinline void update_max(const Vector &v)\n\n\t\t{ ::update_max(x, v.x); ::update_max(y, v.y); ::update_max(z, v.z); }\n\n\n\n\t\t// operator\n\n\t\tinline Vector operator + (const Vector &v) const\n\n\t\t{ return Vector(x + v.x, y + v.y, z + v.z); }\n\n\n\n\t\tinline Vector& operator += (const Vector &v)\n\n\t\t{ x += v.x; y += v.y; z += v.z; return *this; }\n\n\n\n\t\tinline Vector operator - (const Vector &v) const\n\n\t\t{ return Vector(x - v.x, y - v.y, z - v.z); }\n\n\n\n\t\tinline Vector operator - () const\n\n\t\t{ return Vector(-x, -y, -z); }\n", "file_path": "src/include/geometry/geometry.hh", "rank": 84, "score": 27320.180450178486 }, { "content": "class Matrix {\n\n\tpublic:\n\n\t\tT **val;\n\n\t\tint w, h;\n\n\n\n\t\tMatrix(int m_w, int m_h):\n\n\t\t\tw(m_w), h(m_h) {\n\n\t\t\t\tval = new T* [h];\n\n\t\t\t\tfor (int i = 0; i < h; i ++)\n\n\t\t\t\t\tval[i] = new T[w]();\n\n\t\t}\n\n\n\n\t\tMatrix(int m_w, int m_h, T** v)\n\n\t\t\t:w(m_w), h(m_h) {\n\n\t\t\tval = new T* [h];\n\n\t\t\tint rowlen = w * sizeof(T);\n\n\n\n\t\t\tfor (int i = 0; i < h; i++) {\n\n\t\t\t\tval[i] = new T [w];\n\n\t\t\t\tif (v) memcpy(val[i], v[i], rowlen);\n", "file_path": "src/include/matrix.hh", "rank": 85, "score": 27320.180450178486 }, { "content": "class Viewer {\n\n\tprotected:\n\n\t\tView& v;\n\n\t\tconst Geometry& geo;\n\n\tpublic:\n\n\t\tViewer(View& _v):\n\n\t\t\tv(_v), geo(_v.get_geo()){}\n\n\n\n\t\tvirtual ~Viewer(){}\n\n\n\n\t\tViewer(const Viewer&) = delete;\n\n\n\n\t\tViewer & operator = (const Viewer&) = delete;\n\n\n\n\t\tvirtual void view() = 0;\n\n\n\n\t\tvirtual void render_all() = 0;\n\n\n\n};\n\n\n", "file_path": "src/include/viewer.hh", "rank": 86, "score": 27320.180450178486 }, { "content": "// a combination of renderable object and a ray, to integrate some calculations\n\nclass Trace {\n\n\tprotected:\n\n\t\tconst Ray& ray;\t\t\t// ray must have longer lifecycle than any trace !\n\n\n\n\t\tvirtual\tshared_ptr<Surface> transform_get_property() const = 0;\n\n\n\n\t\t// two useful internal members\n\n\t\tmutable bool toward = true;\n\n\t\tmutable real_t inter_dist = std::numeric_limits<real_t>::infinity();\n\n\n\n\tpublic:\n\n\t\tTrace(const Ray& _ray): ray(_ray){}\n\n\n\n\t\t// we have `const Ray&, const Renderable*` member, so forbid copy of a Trace\n\n\t\tTrace(const Trace&) = delete;\n\n\t\tTrace& operator = (const Trace&) = delete;\n\n\n\n\t\tvirtual ~Trace(){ }\n\n\n\n\t\tvirtual const Renderable* get_obj() const = 0;\n", "file_path": "src/include/renderable/renderable.hh", "rank": 87, "score": 26175.61805353478 }, { "content": "//File: MCPT_EL.hh\n\n\n\n//Author: Yuxin Wu <[email protected]>\n\n\n\n#pragma once\n\n#include \"render/MCPT.hh\"\n\n\n\n// MCPT with explicit lighting, better at diffuse, cannot handle caustic\n", "file_path": "src/include/render/MCPT_EL.hh", "rank": 88, "score": 26174.94740851853 }, { "content": "class Timer {\n\n\tpublic:\n\n\t\tTimer();\n\n\t\t~Timer(){}\n\n\n\n\t\tvoid reset();\n\n\t\tvoid stop();\n\n\t\tdouble get_time_microsec();\n\n\n\n\t\tinline double get_time_millisec() { return get_time_microsec() * 1e-3; }\n\n\n\n\t\tinline double get_time_sec() { return get_time_microsec() * 1e-6; }\n\n\n\n\t\tinline double get_time() { return get_time_sec(); }\n\n\n\n\tprivate:\n\n\t\tbool stopped;\n\n\n\n#ifdef WIN32\n\n\t\tLARGE_INTEGER freq;\n\n\t\tLARGE_INTEGER startCount;\n\n\t\tLARGE_INTEGER endCount;\n\n#else\n\n\t\ttimeval startCount;\n\n\t\ttimeval endCount;\n\n#endif\n\n};\n", "file_path": "src/include/lib/Timer.hh", "rank": 89, "score": 26172.11270292267 }, { "content": "class Texture {\n\n\tpublic:\n\n\t\tvirtual shared_ptr<Surface> get_property(real_t x, real_t y) const = 0;\n\n\n\n\t\tvirtual shared_ptr<Surface> get_property() const\n\n\t\t\t// without coordinate, always call this before get_property(x, y)\n\n\t\t{ return nullptr; }\n\n\n\n\t\tvirtual ~Texture() {};\n\n};\n\n\n", "file_path": "src/include/material/texture.hh", "rank": 90, "score": 26172.11270292267 }, { "content": "class Vertex {\n\n\tpublic:\n\n\t\tVec pos;\n\n\n\n\t\tVec norm = Vec::infinity();\t\t// can be defined by obj\n\n//\t\tVec2D mapcoor = Vec2D::infinity();\n\n\n\n\t\tVertex(const Vec& _pos):\n\n\t\t\tpos(_pos) {}\n\n};\n\n\n", "file_path": "src/include/renderable/face.hh", "rank": 91, "score": 26172.11270292267 }, { "content": "class Geometry {\n\n\tpublic:\n\n\t\tint w, h;\n\n\n\n\t\texplicit Geometry(int m_w = 0, int m_h = 0):\n\n\t\t\tw(m_w), h(m_h) {}\n\n\n\n\t\tinline int area() const\n\n\t\t{ return w * h; }\n\n\n\n\t\treal_t ratio() const\n\n\t\t{ return (real_t) std::max(w, h) / std::min(w, h); }\n\n\n\n\t\tinline bool contain(int x, int y)\n\n\t\t{ return (x >= 0 && x < w && y >= 0 && y < h); }\n\n};\n\n\n", "file_path": "src/include/geometry/geometry.hh", "rank": 92, "score": 26172.11270292267 }, { "content": "class Vector {\n\n\tpublic:\n\n\t\treal_t x = 0, y = 0, z = 0;\n\n\n\n\t\tVector(){}\n\n\n\n\t\texplicit Vector(real_t _x, real_t _y, real_t _z):\n\n\t\t\tx(_x), y(_y), z(_z) {}\n\n\n\n\t\tinline Vector(const Vector &p0, const Vector &p1):\n\n\t\t\tx(p1.x - p0.x), y(p1.y -p0.y), z(p1.z - p0.z) {}\n\n\n\n\t\tinline Vector abs() const\n\n\t\t{ return Vector(fabs(x), fabs(y), fabs(z)); }\n\n\n\n\t\tinline real_t sqr() const\n\n\t\t{ return x * x + y * y + z * z; }\n\n\n\n\t\tinline real_t mod() const\n\n\t\t{ return sqrt(sqr()); }\n", "file_path": "src/include/geometry/geometry.hh", "rank": 93, "score": 26172.11270292267 }, { "content": "class Space {\n\n\tprotected:\n\n\t\tvector<shared_ptr<Light>> lights;\n\n\t\tlist<rdptr> objs;\n\n\n\n\t\tVec bound_min = Vec::max(), bound_max = -Vec::max();\n\n\n\n\t\tshared_ptr<Trace> find_first(const Ray& ray, bool include_light = false) const;\n\n\n\n\t\tbool find_any(const Ray& ray, real_t dist) const; // is there any obj on the ray within the dist?\n\n\n\n\tpublic:\n\n\t\t// config\n\n\t\tbool use_tree = true;\n\n\t\tbool use_soft_shadow = false;\n\n\n\n\t\tSpace(){ }\n\n\n\n\t\tvirtual ~Space(){}\n\n\n", "file_path": "src/include/render/space.hh", "rank": 94, "score": 26172.11270292267 }, { "content": "class Surface {\n\n\t// http://en.wikipedia.org/wiki/Phong_reflection_model\n\n\tpublic:\n\n\t\treal_t transparency = 0,\n\n\t\t\t shininess = 0,\n\n\t\t\t ambient = 0,\n\n\t\t\t specular = 0;\n\n\t\tColor diffuse = Color::BLACK,\n\n\t\t\t emission = Color::BLACK;\n\n\n\n\t\tSurface(){}\n\n\n\n\t\tSurface(real_t _transparency, real_t _shininess,\n\n\t\t\t\treal_t _ambient, const Color& _diffuse, real_t _specular, const Color& _emission = Color::NONE):\n\n\t\t\ttransparency(_transparency), shininess(_shininess),\n\n\t\t\tambient(_ambient), specular(_specular), diffuse(_diffuse),\n\n\t\t\temission(_emission) { }\n\n\n\n\t\tstatic const Surface BLACK, WHITE, WHITE_REFL, BLACK_REFL, BLUE, CYAN,\n\n\t\t\t\t\t GOOD, GOOD_REFL, GLASS, MIRROR, GREEN;\n\n};\n", "file_path": "src/include/material/surface.hh", "rank": 95, "score": 26172.11270292267 }, { "content": "class Triangle {\n\n\tpublic:\n\n\t\tVec v, e1, e2;\n\n\t\tVec norm;\n\n\n\n\t\tTriangle(const Vec& a, const Vec& b, const Vec& c):\n\n\t\t\tv(a), e1(b - a), e2(c - a), norm(e1.cross(e2)) {}\n\n\n\n\t\tVec get(int i) const {\n\n\t\t\tif (!i) return v + e1;\n\n\t\t\telse return v + e2;\n\n\t\t}\n\n\n\n\t\treal_t get_intersect(const Ray& ray, real_t& gx, real_t& gy) const;\n\n};\n\n\n", "file_path": "src/include/renderable/face.hh", "rank": 96, "score": 26172.11270292267 }, { "content": "\t\tclass RenderWrapper {\n\n\t\t\tpublic:\n\n\t\t\t\trdptr obj;\n\n\t\t\t\tAABB box;\n\n\t\t\t\tRenderWrapper(const rdptr& _obj, const AABB& _box):\n\n\t\t\t\t\tobj(_obj), box(_box){}\n\n\n\n\t\t};\n\n\n\n\t\tNode* root;\n\n\n\n\t\tVec bound_min = Vec::max(), bound_max = -Vec::max();\n\n\n\n\t\tKDTree(const std::list<rdptr>& objs, const AABB& space);\n\n\n\n\t\t~KDTree();\n\n\n\n\t\tshared_ptr<Trace> get_trace(const Ray& ray, real_t max_dist) const override;\n\n\n\n\t\tAABB get_aabb() const override\n\n\t\t{ return AABB(bound_min, bound_max); }\n\n\n\n\tprivate:\n\n\t\tNode* build(const std::list<RenderWrapper*>& objs, const AABB& box, int depth);\n\n\n\n\t\tAAPlane cut(const std::list<RenderWrapper*>& objs, int depth) const;\n\n\n\n};\n", "file_path": "src/include/kdtree.hh", "rank": 97, "score": 26172.11270292267 }, { "content": "// axis-aligned bounding box\n\nclass AABB {\n\n\tpublic:\n\n\t\tVec min = Vec::max(),\n\n\t\t\tmax = -Vec::max();\n\n\n\n\t\tAABB(){}\n\n\n\n\t\tAABB(const Vec& _min, const Vec& _max):\n\n\t\t\tmin(_min), max(_max) {}\n\n\n\n\t\tvoid set(const Vec& vmin, const Vec& vmax) { min = vmin, max = vmax; }\n\n\t\tVec size() const { return max - min; }\n\n\t\tbool empty() const { return (min.x >= max.x or min.y >= max.y or min.z >= max.z); }\n\n\t\treal_t area() const { return (max - min).area(); }\n\n\t\tbool contain(const Vec& p) const { return p < max && min < p; }\n\n\t\t// override >\n\n\t\t//\n\n\t\tfriend std::ostream& operator << (std::ostream & os, const AABB& b)\n\n\t\t{ return os << \"min: \" << b.min << \" , max:\" << b.max; }\n\n\n", "file_path": "src/include/geometry/aabb.hh", "rank": 98, "score": 26172.11270292267 }, { "content": "class Mesh;\n", "file_path": "src/include/renderable/face.hh", "rank": 99, "score": 26172.11270292267 } ]
C++
src/xcorr_engine.cpp
dev0x13/ust_x
d030ee40462933b645cee417856306f62cf37a28
#include <xcorr_engine.h> #include <XCorr.h> #include <HilbertTransformer.h> #include <algorithm> static const size_t defects = 14; UST::XCorrEngine::XCorrEngine(size_t window_size_axial_, size_t window_size_lateral_, size_t size1_, size_t size2_) : window_size_axial(window_size_axial_), window_size_lateral(window_size_lateral_), window_size_by_2_axial(window_size_axial_ / 2), window_size_by_2_lateral(window_size_lateral_ / 2), size1(size1_), size2(size2_) { windows = new Complex**[2 * numTasks]; for (size_t i = 0; i < 2 * numTasks; ++i) { windows[i] = new Complex*[window_size_lateral_]; for (size_t j = 0; j < window_size_lateral_; ++j) { windows[i][j] = new Complex[window_size_axial_]; } } hField1 = new Complex*[size1]; hField2 = new Complex*[size1]; for (size_t i = 0; i < size1; ++i) { hField1[i] = new Complex[size2]; hField2[i] = new Complex[size2]; } } UST::XCorrEngine::~XCorrEngine() { for (size_t i = 0; i < 2 * numTasks; ++i) { for (size_t j = 0; j < window_size_lateral; ++j) { delete[] windows[i][j]; } delete[] windows[i]; } delete[] windows; for (size_t i = 0; i < size1; ++i) { delete[] hField1[i]; delete[] hField2[i]; } delete[] hField1; delete[] hField2; } void UST::XCorrEngine::hilbertTask( short **sig1, short **sig2, const size_t begin, const size_t end) { thread_local static dsperado::HilbertTransformer<double> ht(size2); thread_local static UST::Complex *hIn = new Complex[size2]; size_t i, j; double mean1 = 0, mean2 = 0; for (i = begin; i < end; ++i) { for (j = defects; j < size2; ++j) { mean1 += sig1[i][j]; mean2 += sig2[i][j]; } mean1 /= size2 - defects; mean2 /= size2 - defects; for (j = defects; j < size2; ++j) { hIn[j].r = sig1[i][j] - mean1; hIn[j].i = 0; } ht.transform(hIn, hField1[i]); for (j = defects; j < size2; ++j) { hIn[j].r = sig2[i][j] - mean2; hIn[j].i = 0; } ht.transform(hIn, hField2[i]); } } void UST::XCorrEngine::xCorrTask(const size_t begin, const size_t end, size_t taskId) { auto window1 = this->windows[taskId * 2]; auto window2 = this->windows[taskId * 2 + 1]; double tmp1, tmp2; Complex xCorrRes; for (size_t n = begin; n < end; ++n) { for (size_t m = defects; m < size2; ++m) { size_t wj = 0, wk = 0; for (long j = (long)n - window_size_by_2_lateral; j < (long)n + window_size_by_2_lateral; ++j) { for (long k = (long)m - window_size_by_2_axial; k < (long)m + window_size_by_2_axial; ++k) { auto realJ = std::min((long)size1 - 1, std::max(j, (long)0)); auto realK = std::min((long)size2 - 1, std::max(k, (long)0)); window1[wj][wk] = hField1[realJ][realK]; window2[wj][wk] = hField2[realJ][realK]; wk++; } wj++; wk = 0; } xCorrRes = dsperado::XCorr::XCorr2DComplex<double>( window1, window2, window_size_lateral, window_size_axial, window_size_by_2_lateral, window_size_by_2_axial, 0); tmp1 = std::atan2(xCorrRes.i, xCorrRes.r); xCorrRes = dsperado::XCorr::XCorr2DComplex<double>( window1, window2, window_size_lateral, window_size_axial, window_size_by_2_lateral, window_size_by_2_axial, 1); tmp2 = std::atan2(xCorrRes.i, xCorrRes.r); xCorrRes = dsperado::XCorr::XCorr2DComplex<double>( window1, window2, window_size_lateral, window_size_axial, window_size_by_2_lateral, window_size_by_2_axial, -1); tmp2 -= std::atan2(xCorrRes.i, xCorrRes.r); out[n][m] = tmp1 / tmp2; } } } void UST::XCorrEngine::calcShift( short **sig1, short **sig2, double **out) { this->out = out; this->tp.startTaskBlock(numThreads); for (size_t i = 0; i < numThreads; ++i) { auto begin = i * pieceSize, end = begin + pieceSize; this->tp.runTask(&UST::XCorrEngine::hilbertTask, this, sig1, sig2, begin, end); } if (div != 0) { this->hilbertTask(sig1, sig2, size1 - div, size1); } this->tp.wait(); this->tp.startTaskBlock(numThreads); for (size_t i = 0; i < numThreads; ++i) { auto begin = i * pieceSize, end = begin + pieceSize; this->tp.runTask(&UST::XCorrEngine::xCorrTask, this, begin, end, i); } if (div != 0) { this->xCorrTask(size1 - div, size1, numThreads); } this->tp.wait(); }
#include <xcorr_engine.h> #include <XCorr.h> #include <HilbertTransformer.h> #include <algorithm> static const size_t defects = 14; UST::XCorrEngine::XCorrEngine(size_t window_size_axial_, size_t window_size_lateral_, size_t size1_, size_t size2_) : window_size_axial(window_size_axial_), window_size_lateral(window_size_lateral_), window_size_by_2_axial(window_size_axial_ / 2), window_size_by_2_lateral(window_size_lateral_ / 2), size1(size1_), size2(size2_) { windows = new Complex**[2 * numTasks]; for (size_t i = 0; i < 2 * numTasks; ++i) { windows[i] = new Complex*[window_size_lateral_]; for (size_t j = 0; j < window_size_lateral_; ++j) { windows[i][j] = new Complex[window_size_axial_]; } } hField1 = new Complex*[size1]; hField2 = new Complex*[size1]; for (size_t i = 0; i < size1; ++i) { hField1[i] = new Complex[size2]; hField2[i] = new Complex[size2]; } } UST::XCorrEngine::~XCorrEngine() { for (size_t i = 0; i < 2 * numTasks; ++i) { for (size_t j = 0; j < window_size_lateral; ++j) { delete[] windows[i][j]; } delete[] windows[i]; } delete[] windows; for (size_t i = 0; i < size1; ++i) { delete[] hField1[i]; delete[] hField2[i]; } delete[] hField1; delete[] hField2; } void UST::XCorrEngine::hilbertTask( short **sig1, short **sig2, const size_t begin, const size_t end) { thread_local static dsperado::HilbertTransformer<double> ht(size2); thread_local static UST::Complex *hIn = new Complex[size2]; size_t i, j; double mean1 = 0, mean2 = 0; for (i = begin; i < end; ++i) { for (j = defects; j < size2; ++j) { mean1 += sig1[i][j]; mean2 += sig2[i][j]; } mean1 /= size2 - defects; mean2 /= size2 - defects; for (j = defects; j < size2; ++j) { hIn[j].r = sig1[i][j] - mean1; hIn[j].i = 0; } ht.transform(hIn, hField1[i]); for (j = defects; j < size2; ++j) { hIn[j].r = sig2[i][j] - mean2; hIn[j].i = 0; } ht.transform(hIn, hField2[i]); } } void UST::XCorrEngine::xCorrTask(const size_t begin, const size_t end, size_t taskId) { auto window1 = this->windows[taskId * 2]; auto window2 = this->windows[taskId * 2 + 1]; double tmp1, tmp2; Complex xCorrRes; for (size_t n = begin; n < end; ++n) { for (size_t m = defects; m < size2; ++m) { size_t wj = 0, wk = 0;
void UST::XCorrEngine::calcShift( short **sig1, short **sig2, double **out) { this->out = out; this->tp.startTaskBlock(numThreads); for (size_t i = 0; i < numThreads; ++i) { auto begin = i * pieceSize, end = begin + pieceSize; this->tp.runTask(&UST::XCorrEngine::hilbertTask, this, sig1, sig2, begin, end); } if (div != 0) { this->hilbertTask(sig1, sig2, size1 - div, size1); } this->tp.wait(); this->tp.startTaskBlock(numThreads); for (size_t i = 0; i < numThreads; ++i) { auto begin = i * pieceSize, end = begin + pieceSize; this->tp.runTask(&UST::XCorrEngine::xCorrTask, this, begin, end, i); } if (div != 0) { this->xCorrTask(size1 - div, size1, numThreads); } this->tp.wait(); }
for (long j = (long)n - window_size_by_2_lateral; j < (long)n + window_size_by_2_lateral; ++j) { for (long k = (long)m - window_size_by_2_axial; k < (long)m + window_size_by_2_axial; ++k) { auto realJ = std::min((long)size1 - 1, std::max(j, (long)0)); auto realK = std::min((long)size2 - 1, std::max(k, (long)0)); window1[wj][wk] = hField1[realJ][realK]; window2[wj][wk] = hField2[realJ][realK]; wk++; } wj++; wk = 0; } xCorrRes = dsperado::XCorr::XCorr2DComplex<double>( window1, window2, window_size_lateral, window_size_axial, window_size_by_2_lateral, window_size_by_2_axial, 0); tmp1 = std::atan2(xCorrRes.i, xCorrRes.r); xCorrRes = dsperado::XCorr::XCorr2DComplex<double>( window1, window2, window_size_lateral, window_size_axial, window_size_by_2_lateral, window_size_by_2_axial, 1); tmp2 = std::atan2(xCorrRes.i, xCorrRes.r); xCorrRes = dsperado::XCorr::XCorr2DComplex<double>( window1, window2, window_size_lateral, window_size_axial, window_size_by_2_lateral, window_size_by_2_axial, -1); tmp2 -= std::atan2(xCorrRes.i, xCorrRes.r); out[n][m] = tmp1 / tmp2; } } }
function_block-function_prefix_line
[ { "content": "struct static_const\n\n{\n\n static constexpr T value{};\n\n};\n\n\n\ntemplate<typename T>\n\nconstexpr T static_const<T>::value;\n\n} // namespace detail\n\n} // namespace nlohmann\n\n\n\n// #include <nlohmann/detail/meta/type_traits.hpp>\n\n\n\n\n\n#include <limits> // numeric_limits\n\n#include <type_traits> // false_type, is_constructible, is_integral, is_same, true_type\n\n#include <utility> // declval\n\n\n\n// #include <nlohmann/detail/iterators/iterator_traits.hpp>\n\n\n\n\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 0, "score": 75493.48861101567 }, { "content": " class AlwaysVoid,\n\n template<class...> class Op,\n\n class... Args>\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 1, "score": 45502.68615347288 }, { "content": "namespace dsperado {\n\n template <typename T>\n\n struct Complex {\n\n T r, i;\n\n };\n", "file_path": "libs/dsperado-1.0/include/Complex.h", "rank": 2, "score": 43015.96035261157 }, { "content": "struct is_sax_static_asserts\n\n{\n\n private:\n\n static_assert(is_basic_json<BasicJsonType>::value,\n\n \"BasicJsonType must be of type basic_json<...>\");\n\n\n\n using number_integer_t = typename BasicJsonType::number_integer_t;\n\n using number_unsigned_t = typename BasicJsonType::number_unsigned_t;\n\n using number_float_t = typename BasicJsonType::number_float_t;\n\n using string_t = typename BasicJsonType::string_t;\n\n using binary_t = typename BasicJsonType::binary_t;\n\n using exception_t = typename BasicJsonType::exception;\n\n\n\n public:\n\n static_assert(is_detected_exact<bool, null_function_t, SAX>::value,\n\n \"Missing/invalid function: bool null()\");\n\n static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,\n\n \"Missing/invalid function: bool boolean(bool)\");\n\n static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,\n\n \"Missing/invalid function: bool boolean(bool)\");\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 3, "score": 43012.87988739348 }, { "content": " class NumberFloatType = double,\n\n template<typename U> class AllocatorType = std::allocator,\n\n template<typename T, typename SFINAE = void> class JSONSerializer =\n\n adl_serializer,\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 4, "score": 40781.88845085352 }, { "content": " function which serializes NaN or Infinity to `null`.\n\n\n\n @note The optimized formats for containers are supported: Parameter\n\n @a use_size adds size information to the beginning of a container and\n\n removes the closing marker. Parameter @a use_type further checks\n\n whether all elements of a container have the same type and adds the\n\n type marker to the beginning of the container. The @a use_type\n\n parameter must only be used together with @a use_size = true. Note\n\n that @a use_size = true alone may result in larger representations -\n\n the benefit of this parameter is that the receiving side is\n\n immediately informed on the number of elements of the container.\n\n\n\n @note If the JSON data contains the binary type, the value stored is a list\n\n of integers, as suggested by the UBJSON documentation. In particular,\n\n this means that serialization and the deserialization of a JSON\n\n containing binary values into UBJSON and back will result in a\n\n different JSON object.\n\n\n\n @param[in] j JSON value to serialize\n\n @param[in] use_size whether to add size annotations to container types\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 5, "score": 38760.51736665021 }, { "content": " class Allocator = std::allocator<std::pair<const Key, T>>>\n\n struct ordered_map : std::vector<std::pair<const Key, T>, Allocator>\n\n{\n\n using key_type = Key;\n\n using mapped_type = T;\n\n using Container = std::vector<std::pair<const Key, T>, Allocator>;\n\n using typename Container::iterator;\n\n using typename Container::const_iterator;\n\n using typename Container::size_type;\n\n using typename Container::value_type;\n\n\n\n // Explicit constructors instead of `using Container::Container`\n\n // otherwise older compilers choke on it (GCC <= 5.5, xcode <= 9.4)\n\n ordered_map(const Allocator& alloc = Allocator()) : Container{alloc} {}\n\n template <class It>\n\n ordered_map(It first, It last, const Allocator& alloc = Allocator())\n\n : Container{first, last, alloc} {}\n\n ordered_map(std::initializer_list<T> init, const Allocator& alloc = Allocator() )\n\n : Container{init, alloc} {}\n\n\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 6, "score": 37650.8504572529 }, { "content": "class tuple_element<N, ::nlohmann::detail::iteration_proxy_value<IteratorType >>\n\n{\n\n public:\n\n using type = decltype(\n\n get<N>(std::declval <\n\n ::nlohmann::detail::iteration_proxy_value<IteratorType >> ()));\n\n};\n\n#if defined(__clang__)\n\n #pragma clang diagnostic pop\n\n#endif\n\n} // namespace std\n\n\n\n// #include <nlohmann/detail/meta/cpp_future.hpp>\n\n\n\n// #include <nlohmann/detail/meta/type_traits.hpp>\n\n\n\n// #include <nlohmann/detail/value_t.hpp>\n\n\n\n\n\nnamespace nlohmann\n\n{\n\nnamespace detail\n\n{\n\n//////////////////\n\n// constructors //\n\n//////////////////\n\n\n\ntemplate<value_t> struct external_constructor;\n\n\n\ntemplate<>\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 7, "score": 35985.010424139495 }, { "content": "struct detector<Default, void_t<Op<Args...>>, Op, Args...>\n\n{\n\n using value_t = std::true_type;\n\n using type = Op<Args...>;\n\n};\n\n\n\ntemplate<template<class...> class Op, class... Args>\n\nusing is_detected = typename detector<nonesuch, void, Op, Args...>::value_t;\n\n\n\ntemplate<template<class...> class Op, class... Args>\n\nusing detected_t = typename detector<nonesuch, void, Op, Args...>::type;\n\n\n\ntemplate<class Default, template<class...> class Op, class... Args>\n\nusing detected_or = detector<Default, void, Op, Args...>;\n\n\n\ntemplate<class Default, template<class...> class Op, class... Args>\n\nusing detected_or_t = typename detected_or<Default, Op, Args...>::type;\n\n\n\ntemplate<class Expected, template<class...> class Op, class... Args>\n\nusing is_detected_exact = std::is_same<Expected, detected_t<Op, Args...>>;\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 8, "score": 35279.4357599314 }, { "content": "struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {};\n\n\n\ntemplate<typename BasicJsonType, typename CompatibleObjectType,\n\n typename = void>\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 9, "score": 34974.82641410787 }, { "content": "struct diyfp // f * 2^e\n\n{\n\n static constexpr int kPrecision = 64; // = q\n\n\n\n std::uint64_t f = 0;\n\n int e = 0;\n\n\n\n constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {}\n\n\n\n /*!\n\n @brief returns x - y\n\n @pre x.e == y.e and x.f >= y.f\n\n */\n\n static diyfp sub(const diyfp& x, const diyfp& y) noexcept\n\n {\n\n JSON_ASSERT(x.e == y.e);\n\n JSON_ASSERT(x.f >= y.f);\n\n\n\n return {x.f - y.f, x.e};\n\n }\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 10, "score": 23094.82974106919 }, { "content": "#pragma once\n\n\n\n#include <json.hpp>\n\n\n\n#include <defines.h>\n\n#include <file_manager.h>\n\n\n\n#include <vector>\n\n#include <fstream>\n\n#include <map>\n\n#include <string>\n\n\n\nusing json = nlohmann::json;\n\n\n\nstatic std::vector<std::string> fields = { \"epsilon\" };\n\n\n\n// This class provides a way to log field changes at defined coordinates to\n\n// a file\n\nnamespace Monitoring {\n\n struct MonitoringPoint {\n\n UST::ICoord coord;\n\n std::string name;\n\n\n\n MonitoringPoint(const std::string& _name, UST::ICoord _coord) : coord(_coord), name(_name) {}\n\n MonitoringPoint() = default;\n\n };\n\n\n", "file_path": "include/monitor.h", "rank": 11, "score": 21858.629360696083 }, { "content": " logFile.flush();\n\n return *this;\n\n }\n\n\n\n Logger(Logger const&) = delete;\n\n Logger& operator= (Logger const&) = delete;\n\n private:\n\n Logger() = default;\n\n\n\n ~Logger() {\n\n logFile.close();\n\n }\n\n\n\n std::ofstream logFile;\n\n bool enabled = true;\n\n bool enabledFile = true;\n\n };\n\n}\n\n\n\nstatic UST::Logger& logger = UST::Logger::Instance();", "file_path": "include/logger.h", "rank": 12, "score": 21858.359995572824 }, { "content": " ~Monitor();\n\n\n\n private:\n\n void _processPoints(const UST::Field& data, const std::string& type, const std::string& label);\n\n\n\n void _processLines(const UST::Field& data, const std::string& type, const std::string& label);\n\n\n\n bool _parseConfig(const std::string& filename, int beams, int vals, UST::DoublePair areaSize);\n\n\n\n Monitor() = default;\n\n };\n\n}\n", "file_path": "include/monitor.h", "rank": 13, "score": 21858.03072682038 }, { "content": "#pragma once\n\n\n\n#include <string>\n\n#include <fstream>\n\n#include <iostream>\n\n\n\nnamespace UST {\n\n // Simple logger class\n", "file_path": "include/logger.h", "rank": 14, "score": 21855.704530486473 }, { "content": "\n\n Logger &operator<<(std::ostream& (*pf) (std::ostream&)) {\n\n if (enabled) {\n\n std::cout << pf;\n\n if (enabledFile) {\n\n logFile << pf;\n\n }\n\n }\n\n logFile.flush();\n\n return *this;\n\n }\n\n\n\n template <typename T>\n\n Logger& operator<<(const T& info) {\n\n if (enabled) {\n\n std::cout << info;\n\n if (enabledFile) {\n\n logFile << info;\n\n }\n\n }\n", "file_path": "include/logger.h", "rank": 15, "score": 21849.50152696707 }, { "content": " void hilbertTask(\n\n short **sig1,\n\n short **sig2,\n\n size_t begin,\n\n size_t end);\n\n\n\n void xCorrTask(\n\n size_t begin,\n\n size_t end,\n\n size_t taskId);\n\n\n\n double **out;\n\n\n\n public:\n\n XCorrEngine(size_t window_size_axial_, size_t window_size_lateral_, size_t size1_, size_t size2_);\n\n\n\n void calcShift(short **sig1, short **sig2, double **out);\n\n\n\n ~XCorrEngine();\n\n };\n\n}\n", "file_path": "include/xcorr_engine.h", "rank": 16, "score": 20238.008904029175 }, { "content": " // Open stream for dynamic mode\n\n bool openBinStream(const std::string& fileName, const std::vector<std::string>& vars, int beams, int vals);\n\n\n\n // Write to opened stream\n\n bool writeToBinStream(const std::vector<std::reference_wrapper<UST::Field>>& fieldsData, const UST::PairField& coordData);\n\n\n\n // Close stream\n\n void closeBinStream();\n\n\n\n // Read RAW data file\n\n static bool readRAWFile(const std::string& fileName, short **rawBeamData, int beams, int vals);\n\n };\n\n}\n", "file_path": "include/file_manager.h", "rank": 17, "score": 20209.90418618076 }, { "content": " task();\n\n {\n\n std::unique_lock<std::mutex> lock(this->m);\n\n\n\n blockSize--;\n\n }\n\n\n\n }\n\n });\n\n }\n\n\n\n //logger << numThreads << \" concurrent threads are supported\\n\" << SEPARATOR;\n\n }\n\n\n\n template<class Function, class... Args>\n\n void runTask(Function&& f, Args&&... args) {\n\n auto task = std::bind(std::forward<Function>(f), std::forward<Args>(args)...);\n\n {\n\n std::unique_lock<std::mutex> lock(m);\n\n\n", "file_path": "include/thread_pool.h", "rank": 18, "score": 20208.200872467278 }, { "content": "#pragma once\n\n\n\n#include <vector>\n\n#include <string>\n\n#include <fstream>\n\n#include <iostream>\n\n#include <cassert>\n\n#include <filesystem>\n\n\n\n#include <TECIO.h>\n\n\n\n#include <defines.h>\n\n#include <logger.h>\n\n\n\nnamespace UST {\n", "file_path": "include/file_manager.h", "rank": 19, "score": 20207.75970120464 }, { "content": "#pragma once\n\n\n\n#include <condition_variable>\n\n#include <thread>\n\n#include <vector>\n\n#include <iostream>\n\n#include <mutex>\n\n#include <queue>\n\n#include <functional>\n\n\n\nnamespace UST {\n\n namespace Multithreading {\n", "file_path": "include/thread_pool.h", "rank": 20, "score": 20207.647818661702 }, { "content": " INTEGER4 StrandID = 1;\n\n INTEGER4 ParentZn = 0;\n\n INTEGER4 IsBlock = 1;\n\n INTEGER4 NFConns = 0;\n\n INTEGER4 FNMode = 0;\n\n INTEGER4 TotalNumFaceNodes = 0;\n\n INTEGER4 TotalNumBndryFaces = 0;\n\n INTEGER4 TotalNumBndryConnections = 0;\n\n INTEGER4 ShrConn = 0;\n\n INTEGER4 IMax;\n\n INTEGER4 JMax;\n\n INTEGER4 KMax = 1;\n\n INTEGER4 ZoneType = 0;\n\n INTEGER4 III;\n\n public:\n\n // Create directory\n\n static bool createDir(const std::string& dir) {\n\n return std::filesystem::create_directory(dir);\n\n }\n\n\n", "file_path": "include/file_manager.h", "rank": 21, "score": 20207.340105033483 }, { "content": "#pragma once\n\n\n\n#include <defines.h>\n\n#include <thread_pool.h>\n\n\n\nnamespace UST {\n", "file_path": "include/xcorr_engine.h", "rank": 22, "score": 20206.963576694478 }, { "content": " tasks.emplace(task);\n\n }\n\n cond.notify_one();\n\n }\n\n\n\n // Method for creating barrier by tasks counter e.g. for output\n\n void startTaskBlock(size_t size) {\n\n {\n\n std::unique_lock<std::mutex> lock(m);\n\n \n\n blockSize = size;\n\n }\n\n }\n\n\n\n void terminate() {\n\n {\n\n std::unique_lock<std::mutex> lock(m);\n\n\n\n done = true;\n\n }\n", "file_path": "include/thread_pool.h", "rank": 23, "score": 20205.956874970958 }, { "content": " cond.notify_all();\n\n\n\n for (std::thread &t : threads) {\n\n t.join();\n\n }\n\n }\n\n\n\n void wait() {\n\n while (blockSize > 0) {}\n\n {\n\n std::unique_lock<std::mutex> lock(m);\n\n\n\n blockSize = 0;\n\n }\n\n }\n\n\n\n size_t getNumThreads() {\n\n return numThreads;\n\n }\n\n\n\n ~ThreadPool() {\n\n terminate();\n\n }\n\n };\n\n }\n\n}\n", "file_path": "include/thread_pool.h", "rank": 24, "score": 20205.14008183764 }, { "content": " }\n\n\n\n for (size_t i = 0; i < numThreads; ++i) {\n\n threads.emplace_back([&] {\n\n for (;;) {\n\n std::function<void()> task;\n\n\n\n {\n\n std::unique_lock<std::mutex> lock(this->m);\n\n\n\n this->cond.wait(lock, [this] { return this->done || !this->tasks.empty(); });\n\n\n\n if (this->done && this->tasks.empty()) {\n\n return;\n\n }\n\n\n\n task = std::move(this->tasks.front());\n\n this->tasks.pop();\n\n }\n\n\n", "file_path": "include/thread_pool.h", "rank": 25, "score": 20204.955344867405 }, { "content": " class Monitor {\n\n public:\n\n std::vector<MonitoringPoint> monitoringPoints;\n\n std::vector<MonitoringPoint> monitoringLines;\n\n std::map<std::string, std::vector<std::ofstream>> outputPointsFiles;\n\n\n\n static Monitor& Instance() {\n\n static Monitor theSingleInstance;\n\n return theSingleInstance;\n\n }\n\n\n\n void init(const std::string& filename,\n\n int beams, int vals,\n\n const UST::DoublePair& areaSize);\n\n\n\n void process(const UST::Field& data, const std::string& type, const std::string& label);\n\n\n\n Monitor(const Monitor&) = delete;\n\n Monitor& operator=(const Monitor&) = delete;\n\n\n", "file_path": "include/monitor.h", "rank": 26, "score": 20201.04367380038 }, { "content": " // Simple logger class\n\n class Logger {\n\n public:\n\n static Logger& Instance() {\n\n static Logger s;\n\n return s;\n\n }\n\n\n\n void init(const std::string& logName) {\n\n if (!logFile.is_open()) {\n\n logFile.open(logName);\n\n\n\n if (logFile.is_open()) {\n\n enabledFile = true;\n\n }\n\n }\n\n }\n\n\n\n void setEnabled(bool enabled) {\n\n this->enabled = enabled;\n\n }\n", "file_path": "include/logger.h", "rank": 27, "score": 20201.04367380038 }, { "content": "struct wide_string_input_helper<BaseInputAdapter, 2>\n\n{\n\n // UTF-16\n\n static void fill_buffer(BaseInputAdapter& input,\n\n std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,\n\n size_t& utf8_bytes_index,\n\n size_t& utf8_bytes_filled)\n\n {\n\n utf8_bytes_index = 0;\n\n\n\n if (JSON_HEDLEY_UNLIKELY(input.empty()))\n\n {\n\n utf8_bytes[0] = std::char_traits<char>::eof();\n\n utf8_bytes_filled = 1;\n\n }\n\n else\n\n {\n\n // get the current character\n\n const auto wc = input.get_character();\n\n\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 28, "score": 20069.0450611685 }, { "content": "struct cached_power // c = f * 2^e ~= 10^k\n\n{\n\n std::uint64_t f;\n\n int e;\n\n int k;\n\n};\n\n\n\n/*!\n\nFor a normalized diyfp w = f * 2^e, this function returns a (normalized) cached\n\npower-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c\n\nsatisfies (Definition 3.2 from [1])\n\n\n\n alpha <= e_c + e + q <= gamma.\n\n*/\n\ninline cached_power get_cached_power_for_binary_exponent(int e)\n\n{\n\n // Now\n\n //\n\n // alpha <= e_c + e + q <= gamma (1)\n\n // ==> f_c * 2^alpha <= c * 2^e * 2^q\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 29, "score": 19851.03727317126 }, { "content": "#pragma once\n\n\n\n#include <cassert>\n\n#include <cstddef>\n\n\n\nnamespace dsperado {\n\n /*\n\n * Helper memory arena class. Not thread-safe.\n\n */\n\n template <typename T>\n", "file_path": "libs/dsperado-1.0/include/Arena.h", "rank": 30, "score": 18789.526880606198 }, { "content": " dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>());\n\n }\n\n\n\n void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/)\n\n {\n\n char* begin = number_buffer.data();\n\n char* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x);\n\n\n\n o->write_characters(begin, static_cast<size_t>(end - begin));\n\n }\n\n\n\n void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/)\n\n {\n\n // get number of digits for a float -> text -> float round-trip\n\n static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10;\n\n\n\n // the actual conversion\n\n std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), \"%.*g\", d, x);\n\n\n\n // negative value indicates an error\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 31, "score": 17572.62916482501 }, { "content": " */\n\n void transform(const T *in, Type *out) {\n\n if (!complexInAllocated) {\n\n complexIn = new Type[bufferSize];\n\n complexInAllocated = true;\n\n }\n\n\n\n for (ind = 0; ind < bufferSize; ++ind) {\n\n complexIn[ind].r = in[ind];\n\n complexIn[ind].i = 0;\n\n }\n\n\n\n transform(complexIn, out);\n\n }\n\n\n\n ~HilbertTransformer() {\n\n delete[] buffer;\n\n\n\n if (complexInAllocated) {\n\n delete[] complexIn;\n\n }\n\n }\n\n };\n\n}\n", "file_path": "libs/dsperado-1.0/include/HilbertTransformer.h", "rank": 32, "score": 17571.747969384127 }, { "content": " }\n\n\n\n /*\n\n * Perform FFT (real -> complex).\n\n * Params:\n\n * in - pointer to the input T number array\n\n * out - pointer to the output Complex<T> number array\n\n */\n\n void transform(const T* in, Type* out) {\n\n if (!complexInAllocated) {\n\n complexIn = new Type[size];\n\n complexInAllocated = true;\n\n }\n\n\n\n for (ind1 = 0; ind1 < size; ++ind1) {\n\n complexIn[ind1].r = in[ind1];\n\n complexIn[ind1].i = 0;\n\n }\n\n\n\n transform(complexIn, out);\n\n }\n\n\n\n ~FFTransformer() {\n\n if (complexInAllocated) {\n\n delete[] complexIn;\n\n }\n\n }\n\n };\n\n}", "file_path": "libs/dsperado-1.0/include/FFTransformer.h", "rank": 33, "score": 17569.469987072323 }, { "content": " static int ValueHandler(void* user, const char* section, const char* name,\n\n const char* value);\n\n};\n\n\n\n#endif // __INIREADER_H__\n\n\n\n\n\n#ifndef __INIREADER__\n\n#define __INIREADER__\n\n\n\n#include <algorithm>\n\n#include <cctype>\n\n#include <cstdlib>\n\n\n\nusing std::string;\n\n\n\ninline INIReader::INIReader(string filename)\n\n{\n\n _error = ini_parse(filename.c_str(), ValueHandler, this);\n\n}\n", "file_path": "libs/inih-42/include/INIReader.h", "rank": 34, "score": 17568.7964903085 }, { "content": " @param[in] x floating-point number to dump\n\n */\n\n void dump_float(number_float_t x)\n\n {\n\n // NaN / inf\n\n if (!std::isfinite(x))\n\n {\n\n o->write_characters(\"null\", 4);\n\n return;\n\n }\n\n\n\n // If number_float_t is an IEEE-754 single or double precision number,\n\n // use the Grisu2 algorithm to produce short numbers which are\n\n // guaranteed to round-trip, using strtof and strtod, resp.\n\n //\n\n // NB: The test below works if <long double> == <double>.\n\n static constexpr bool is_ieee_single_or_double\n\n = (std::numeric_limits<number_float_t>::is_iec559 && std::numeric_limits<number_float_t>::digits == 24 && std::numeric_limits<number_float_t>::max_exponent == 128) ||\n\n (std::numeric_limits<number_float_t>::is_iec559 && std::numeric_limits<number_float_t>::digits == 53 && std::numeric_limits<number_float_t>::max_exponent == 1024);\n\n\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 35, "score": 17568.199825745287 }, { "content": " }\n\n\n\n /// set iterator to a defined past the end\n\n void set_end() noexcept\n\n {\n\n m_it = end_value;\n\n }\n\n\n\n /// return whether the iterator can be dereferenced\n\n constexpr bool is_begin() const noexcept\n\n {\n\n return m_it == begin_value;\n\n }\n\n\n\n /// return whether the iterator is at end\n\n constexpr bool is_end() const noexcept\n\n {\n\n return m_it == end_value;\n\n }\n\n\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 36, "score": 17567.20520418565 }, { "content": " assert((bufferSize_ & (bufferSize_ - 1)) == 0);\n\n\n\n FFT = std::make_shared<dsperado::FFTransformer<T, true>>(bufferSize_);\n\n IFFT = std::make_shared<dsperado::FFTransformer<T, false>>(bufferSize_);\n\n\n\n buffer = new dsperado::Complex<T>[bufferSize_];\n\n\n\n auto mod_ = this->bufferSize % 2;\n\n limit1 = (this->bufferSize + mod_) / 2;\n\n limit2 = limit1 + ~mod_;\n\n }\n\n\n\n /*\n\n * Performs Hilbert transform (complex -> complex).\n\n * Params:\n\n * in - pointer to the input Complex<T> number array\n\n * out - pointer to the output Complex<T> number array\n\n */\n\n void transform(const Type *in, Type *out) {\n\n\n", "file_path": "libs/dsperado-1.0/include/HilbertTransformer.h", "rank": 37, "score": 17567.17300348494 }, { "content": "@since version 3.4.0\n\n*/\n\n#define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \\\n\n template<typename BasicJsonType> \\\n\n inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \\\n\n { \\\n\n static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE \" must be an enum!\"); \\\n\n static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \\\n\n auto it = std::find_if(std::begin(m), std::end(m), \\\n\n [e](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \\\n\n { \\\n\n return ej_pair.first == e; \\\n\n }); \\\n\n j = ((it != std::end(m)) ? it : std::begin(m))->second; \\\n\n } \\\n\n template<typename BasicJsonType> \\\n\n inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \\\n\n { \\\n\n static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE \" must be an enum!\"); \\\n\n static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \\\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 38, "score": 17567.031149788054 }, { "content": " // step 1: write control byte and the object size\n\n const auto N = j.m_value.object->size();\n\n if (N <= 0x17)\n\n {\n\n write_number(static_cast<std::uint8_t>(0xA0 + N));\n\n }\n\n else if (N <= (std::numeric_limits<std::uint8_t>::max)())\n\n {\n\n oa->write_character(to_char_type(0xB8));\n\n write_number(static_cast<std::uint8_t>(N));\n\n }\n\n else if (N <= (std::numeric_limits<std::uint16_t>::max)())\n\n {\n\n oa->write_character(to_char_type(0xB9));\n\n write_number(static_cast<std::uint16_t>(N));\n\n }\n\n else if (N <= (std::numeric_limits<std::uint32_t>::max)())\n\n {\n\n oa->write_character(to_char_type(0xBA));\n\n write_number(static_cast<std::uint32_t>(N));\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 39, "score": 17566.408075222298 }, { "content": " {\n\n // fixarray\n\n write_number(static_cast<std::uint8_t>(0x90 | N));\n\n }\n\n else if (N <= (std::numeric_limits<std::uint16_t>::max)())\n\n {\n\n // array 16\n\n oa->write_character(to_char_type(0xDC));\n\n write_number(static_cast<std::uint16_t>(N));\n\n }\n\n else if (N <= (std::numeric_limits<std::uint32_t>::max)())\n\n {\n\n // array 32\n\n oa->write_character(to_char_type(0xDD));\n\n write_number(static_cast<std::uint32_t>(N));\n\n }\n\n\n\n // step 2: write each element\n\n for (const auto& el : *j.m_value.array)\n\n {\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 40, "score": 17566.404576685476 }, { "content": " Type wn;\n\n\n\n for (size_t i = 1; i <= sizeLog; ++i) {\n\n auto n = pow(2, i);\n\n auto angle = calcCoeff<forward>(n);\n\n wn.r = cos(angle);\n\n wn.i = sin(angle);\n\n coeffs[n] = wn;\n\n }\n\n }\n\n\n\n /*\n\n * Performs FFT (complex -> complex).\n\n * Params:\n\n * in - pointer to the input Complex<T> number array\n\n * out - pointer to the output Complex<T> number array\n\n */\n\n void transform(const Type* in, Type* out) {\n\n this->arena->reset();\n\n this->fft(in, out, this->size);\n", "file_path": "libs/dsperado-1.0/include/FFTransformer.h", "rank": 41, "score": 17566.35023578617 }, { "content": " auto it = --this->base();\n\n return it.operator * ();\n\n }\n\n};\n\n} // namespace detail\n\n} // namespace nlohmann\n\n\n\n// #include <nlohmann/detail/iterators/primitive_iterator.hpp>\n\n\n\n// #include <nlohmann/detail/json_pointer.hpp>\n\n\n\n\n\n#include <algorithm> // all_of\n\n#include <cctype> // isdigit\n\n#include <limits> // max\n\n#include <numeric> // accumulate\n\n#include <string> // string\n\n#include <utility> // move\n\n#include <vector> // vector\n\n\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 42, "score": 17566.34009860595 }, { "content": " case value_t::string:\n\n {\n\n // step 1: write control byte and the string length\n\n const auto N = j.m_value.string->size();\n\n if (N <= 31)\n\n {\n\n // fixstr\n\n write_number(static_cast<std::uint8_t>(0xA0 | N));\n\n }\n\n else if (N <= (std::numeric_limits<std::uint8_t>::max)())\n\n {\n\n // str 8\n\n oa->write_character(to_char_type(0xD9));\n\n write_number(static_cast<std::uint8_t>(N));\n\n }\n\n else if (N <= (std::numeric_limits<std::uint16_t>::max)())\n\n {\n\n // str 16\n\n oa->write_character(to_char_type(0xDA));\n\n write_number(static_cast<std::uint16_t>(N));\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 43, "score": 17566.335856731814 }, { "content": "\n\n // step 1: write control byte and the binary array size\n\n const auto N = j.m_value.binary->size();\n\n if (N <= 0x17)\n\n {\n\n write_number(static_cast<std::uint8_t>(0x40 + N));\n\n }\n\n else if (N <= (std::numeric_limits<std::uint8_t>::max)())\n\n {\n\n oa->write_character(to_char_type(0x58));\n\n write_number(static_cast<std::uint8_t>(N));\n\n }\n\n else if (N <= (std::numeric_limits<std::uint16_t>::max)())\n\n {\n\n oa->write_character(to_char_type(0x59));\n\n write_number(static_cast<std::uint16_t>(N));\n\n }\n\n else if (N <= (std::numeric_limits<std::uint32_t>::max)())\n\n {\n\n oa->write_character(to_char_type(0x5A));\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 44, "score": 17566.035425438822 }, { "content": " oa->write_character(to_char_type(0xDE));\n\n write_number(static_cast<std::uint16_t>(N));\n\n }\n\n else if (N <= (std::numeric_limits<std::uint32_t>::max)())\n\n {\n\n // map 32\n\n oa->write_character(to_char_type(0xDF));\n\n write_number(static_cast<std::uint32_t>(N));\n\n }\n\n\n\n // step 2: write each element\n\n for (const auto& el : *j.m_value.object)\n\n {\n\n write_msgpack(el.first);\n\n write_msgpack(el.second);\n\n }\n\n break;\n\n }\n\n\n\n default:\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 45, "score": 17565.625307286187 }, { "content": "#endif\n\n#if defined(__cplusplus)\n\n #define JSON_HEDLEY_BEGIN_C_DECLS extern \"C\" {\n\n #define JSON_HEDLEY_END_C_DECLS }\n\n #define JSON_HEDLEY_C_DECL extern \"C\"\n\n#else\n\n #define JSON_HEDLEY_BEGIN_C_DECLS\n\n #define JSON_HEDLEY_END_C_DECLS\n\n #define JSON_HEDLEY_C_DECL\n\n#endif\n\n\n\n#if defined(JSON_HEDLEY_STATIC_ASSERT)\n\n #undef JSON_HEDLEY_STATIC_ASSERT\n\n#endif\n\n#if \\\n\n !defined(__cplusplus) && ( \\\n\n (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \\\n\n JSON_HEDLEY_HAS_FEATURE(c_static_assert) || \\\n\n JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \\\n\n JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \\\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 46, "score": 17565.435903707737 }, { "content": " // step 2: write the byte string\n\n oa->write_characters(\n\n reinterpret_cast<const CharType*>(j.m_value.binary->data()),\n\n N);\n\n\n\n break;\n\n }\n\n\n\n case value_t::object:\n\n {\n\n // step 1: write control byte and the object size\n\n const auto N = j.m_value.object->size();\n\n if (N <= 15)\n\n {\n\n // fixmap\n\n write_number(static_cast<std::uint8_t>(0x80 | (N & 0xF)));\n\n }\n\n else if (N <= (std::numeric_limits<std::uint16_t>::max)())\n\n {\n\n // map 16\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 47, "score": 17565.350120239833 }, { "content": " int > = 0 >\n\n static void construct(BasicJsonType& j, const CompatibleArrayType& arr)\n\n {\n\n using std::begin;\n\n using std::end;\n\n j.m_type = value_t::array;\n\n j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));\n\n j.assert_invariant();\n\n }\n\n\n\n template<typename BasicJsonType>\n\n static void construct(BasicJsonType& j, const std::vector<bool>& arr)\n\n {\n\n j.m_type = value_t::array;\n\n j.m_value = value_t::array;\n\n j.m_value.array->reserve(arr.size());\n\n for (const bool x : arr)\n\n {\n\n j.m_value.array->push_back(x);\n\n }\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 48, "score": 17565.185833355772 }, { "content": "\n\n// #include <nlohmann/detail/conversions/to_json.hpp>\n\n\n\n\n\n#include <algorithm> // copy\n\n#include <iterator> // begin, end\n\n#include <string> // string\n\n#include <tuple> // tuple, get\n\n#include <type_traits> // is_same, is_constructible, is_floating_point, is_enum, underlying_type\n\n#include <utility> // move, forward, declval, pair\n\n#include <valarray> // valarray\n\n#include <vector> // vector\n\n\n\n// #include <nlohmann/detail/iterators/iteration_proxy.hpp>\n\n\n\n\n\n#include <cstddef> // size_t\n\n#include <iterator> // input_iterator_tag\n\n#include <string> // string, to_string\n\n#include <tuple> // tuple_size, get, tuple_element\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 49, "score": 17565.1401363034 }, { "content": "}\n\n\n\ntemplate<typename BasicJsonType, typename T, std::size_t N>\n\nauto from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr,\n\n priority_tag<2> /*unused*/)\n\n-> decltype(j.template get<T>(), void())\n\n{\n\n for (std::size_t i = 0; i < N; ++i)\n\n {\n\n arr[i] = j.at(i).template get<T>();\n\n }\n\n}\n\n\n\ntemplate<typename BasicJsonType, typename ConstructibleArrayType>\n\nauto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/)\n\n-> decltype(\n\n arr.reserve(std::declval<typename ConstructibleArrayType::size_type>()),\n\n j.template get<typename ConstructibleArrayType::value_type>(),\n\n void())\n\n{\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 50, "score": 17565.078829285885 }, { "content": " if (it->first == key)\n\n {\n\n return it->second;\n\n }\n\n }\n\n\n\n throw std::out_of_range(\"key not found\");\n\n }\n\n\n\n size_type erase(const Key& key)\n\n {\n\n for (auto it = this->begin(); it != this->end(); ++it)\n\n {\n\n if (it->first == key)\n\n {\n\n // Since we cannot move const Keys, re-construct them in place\n\n for (auto next = it; ++next != this->end(); ++it)\n\n {\n\n it->~value_type(); // Destroy but keep allocation\n\n new (&*it) value_type{std::move(*next)};\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 51, "score": 17565.02519013463 }, { "content": " JSON_ASSERT(len > 0);\n\n // check if buffer was large enough\n\n JSON_ASSERT(static_cast<std::size_t>(len) < number_buffer.size());\n\n\n\n // erase thousands separator\n\n if (thousands_sep != '\\0')\n\n {\n\n const auto end = std::remove(number_buffer.begin(),\n\n number_buffer.begin() + len, thousands_sep);\n\n std::fill(end, number_buffer.end(), '\\0');\n\n JSON_ASSERT((end - number_buffer.begin()) <= len);\n\n len = (end - number_buffer.begin());\n\n }\n\n\n\n // convert decimal point to '.'\n\n if (decimal_point != '\\0' && decimal_point != '.')\n\n {\n\n const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);\n\n if (dec_pos != number_buffer.end())\n\n {\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 52, "score": 17564.99952834875 }, { "content": " break;\n\n }\n\n\n\n default:\n\n break;\n\n }\n\n }\n\n\n\n private:\n\n //////////\n\n // BSON //\n\n //////////\n\n\n\n /*!\n\n @return The size of a BSON document entry header, including the id marker\n\n and the entry name size (and its null-terminator).\n\n */\n\n static std::size_t calc_bson_entry_header_size(const string_t& name)\n\n {\n\n const auto it = name.find(static_cast<typename string_t::value_type>(0));\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 53, "score": 17564.94521971376 }, { "content": " const auto byte2_raw = get();\n\n if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, \"number\")))\n\n {\n\n return false;\n\n }\n\n\n\n const auto byte1 = static_cast<unsigned char>(byte1_raw);\n\n const auto byte2 = static_cast<unsigned char>(byte2_raw);\n\n\n\n // code from RFC 7049, Appendix D, Figure 3:\n\n // As half-precision floating-point numbers were only added\n\n // to IEEE 754 in 2008, today's programming platforms often\n\n // still only have limited support for them. It is very\n\n // easy to include at least decoding support for them even\n\n // without such support. An example of a small decoder for\n\n // half-precision floating-point numbers in the C language\n\n // is shown in Fig. 3.\n\n const auto half = static_cast<unsigned int>((byte1 << 8u) + byte2);\n\n const double val = [&half]\n\n {\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 54, "score": 17564.90478591586 }, { "content": " void dump_escaped(const string_t& s, const bool ensure_ascii)\n\n {\n\n std::uint32_t codepoint;\n\n std::uint8_t state = UTF8_ACCEPT;\n\n std::size_t bytes = 0; // number of bytes written to string_buffer\n\n\n\n // number of bytes written at the point of the last valid byte\n\n std::size_t bytes_after_last_accept = 0;\n\n std::size_t undumped_chars = 0;\n\n\n\n for (std::size_t i = 0; i < s.size(); ++i)\n\n {\n\n const auto byte = static_cast<uint8_t>(s[i]);\n\n\n\n switch (decode(state, codepoint, byte))\n\n {\n\n case UTF8_ACCEPT: // decode found a new code point\n\n {\n\n switch (codepoint)\n\n {\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 55, "score": 17564.802972263413 }, { "content": " return true;\n\n }\n\n\n\n bool end_object()\n\n {\n\n if (ref_stack.back() && !callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back()))\n\n {\n\n // discard object\n\n *ref_stack.back() = discarded;\n\n }\n\n\n\n JSON_ASSERT(!ref_stack.empty());\n\n JSON_ASSERT(!keep_stack.empty());\n\n ref_stack.pop_back();\n\n keep_stack.pop_back();\n\n\n\n if (!ref_stack.empty() && ref_stack.back() && ref_stack.back()->is_structured())\n\n {\n\n // remove discarded value\n\n for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it)\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 56, "score": 17564.72942105608 }, { "content": " [Container](https://en.cppreference.com/w/cpp/named_req/Container)\n\n requirements:\n\n - The complexity is constant.\n\n - Has the semantics of `const_cast<const basic_json&>(*this).end()`.\n\n\n\n @liveexample{The following code shows an example for `cend()`.,cend}\n\n\n\n @sa @ref end() -- returns an iterator to the end\n\n @sa @ref begin() -- returns an iterator to the beginning\n\n @sa @ref cbegin() -- returns a const iterator to the beginning\n\n\n\n @since version 1.0.0\n\n */\n\n const_iterator cend() const noexcept\n\n {\n\n const_iterator result(this);\n\n result.set_end();\n\n return result;\n\n }\n\n\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 57, "score": 17564.715831488124 }, { "content": " @requirement This function helps `basic_json` satisfying the\n\n [Container](https://en.cppreference.com/w/cpp/named_req/Container)\n\n requirements:\n\n - The complexity is constant.\n\n\n\n @liveexample{The following code shows an example for `end()`.,end}\n\n\n\n @sa @ref cend() -- returns a const iterator to the end\n\n @sa @ref begin() -- returns an iterator to the beginning\n\n @sa @ref cbegin() -- returns a const iterator to the beginning\n\n\n\n @since version 1.0.0\n\n */\n\n iterator end() noexcept\n\n {\n\n iterator result(this);\n\n result.set_end();\n\n return result;\n\n }\n\n\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 58, "score": 17564.715831488124 }, { "content": " }\n\n else if (N <= (std::numeric_limits<std::uint32_t>::max)())\n\n {\n\n // str 32\n\n oa->write_character(to_char_type(0xDB));\n\n write_number(static_cast<std::uint32_t>(N));\n\n }\n\n\n\n // step 2: write the string\n\n oa->write_characters(\n\n reinterpret_cast<const CharType*>(j.m_value.string->c_str()),\n\n j.m_value.string->size());\n\n break;\n\n }\n\n\n\n case value_t::array:\n\n {\n\n // step 1: write control byte and the array size\n\n const auto N = j.m_value.array->size();\n\n if (N <= 15)\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 59, "score": 17564.6082046109 }, { "content": " [](const BasicJsonType & elem)\n\n {\n\n return elem.template get<T>();\n\n });\n\n}\n\n\n\ntemplate<typename BasicJsonType, typename T, std::size_t N>\n\nauto from_json(const BasicJsonType& j, T (&arr)[N])\n\n-> decltype(j.template get<T>(), void())\n\n{\n\n for (std::size_t i = 0; i < N; ++i)\n\n {\n\n arr[i] = j.at(i).template get<T>();\n\n }\n\n}\n\n\n\ntemplate<typename BasicJsonType>\n\nvoid from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/)\n\n{\n\n arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 60, "score": 17564.524256031513 }, { "content": " static void construct(BasicJsonType& j, const CompatibleObjectType& obj)\n\n {\n\n using std::begin;\n\n using std::end;\n\n\n\n j.m_type = value_t::object;\n\n j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));\n\n j.assert_invariant();\n\n }\n\n};\n\n\n\n/////////////\n\n// to_json //\n\n/////////////\n\n\n\ntemplate<typename BasicJsonType, typename T,\n\n enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>\n\nvoid to_json(BasicJsonType& j, T b) noexcept\n\n{\n\n external_constructor<value_t::boolean>::construct(j, b);\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 61, "score": 17564.36138281838 }, { "content": " }\n\n // LCOV_EXCL_START\n\n else if (N <= (std::numeric_limits<std::uint64_t>::max)())\n\n {\n\n oa->write_character(to_char_type(0xBB));\n\n write_number(static_cast<std::uint64_t>(N));\n\n }\n\n // LCOV_EXCL_STOP\n\n\n\n // step 2: write each element\n\n for (const auto& el : *j.m_value.object)\n\n {\n\n write_cbor(el.first);\n\n write_cbor(el.second);\n\n }\n\n break;\n\n }\n\n\n\n default:\n\n break;\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 62, "score": 17564.36044430761 }, { "content": " else if (N <= (std::numeric_limits<std::uint64_t>::max)())\n\n {\n\n oa->write_character(to_char_type(0x7B));\n\n write_number(static_cast<std::uint64_t>(N));\n\n }\n\n // LCOV_EXCL_STOP\n\n\n\n // step 2: write the string\n\n oa->write_characters(\n\n reinterpret_cast<const CharType*>(j.m_value.string->c_str()),\n\n j.m_value.string->size());\n\n break;\n\n }\n\n\n\n case value_t::array:\n\n {\n\n // step 1: write control byte and the array size\n\n const auto N = j.m_value.array->size();\n\n if (N <= 0x17)\n\n {\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 63, "score": 17564.34609434909 }, { "content": " @brief convert any value type to a JSON value\n\n\n\n This function is usually called by the constructors of the @ref basic_json\n\n class.\n\n\n\n @param[in,out] j JSON value to write to\n\n @param[in] val value to read from\n\n */\n\n template<typename BasicJsonType, typename ValueType>\n\n static auto to_json(BasicJsonType& j, ValueType&& val) noexcept(\n\n noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val))))\n\n -> decltype(::nlohmann::to_json(j, std::forward<ValueType>(val)), void())\n\n {\n\n ::nlohmann::to_json(j, std::forward<ValueType>(val));\n\n }\n\n};\n\n\n\n} // namespace nlohmann\n\n\n\n// #include <nlohmann/byte_container_with_subtype.hpp>\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 64, "score": 17564.130349568102 }, { "content": "\n\n for (ind1 = 0; ind1 < n_d2; ++ind1) {\n\n tmp0 = &s0[ind1];\n\n tmp1 = &s1[ind1];\n\n tmp2 = &out[ind1];\n\n tmp3 = &out[ind1 + n_d2];\n\n\n\n tmpReal0 = w.r * tmp1->r - w.i * tmp1->i;\n\n tmpReal1 = w.r * tmp1->i + w.i * tmp1->r;\n\n\n\n tmp2->r = tmp0->r + tmpReal0;\n\n tmp2->i = tmp0->i + tmpReal1;\n\n\n\n tmp3->r = tmp0->r - tmpReal0;\n\n tmp3->i = tmp0->i - tmpReal1;\n\n\n\n divBy2<forward>(tmp2);\n\n divBy2<forward>(tmp3);\n\n\n\n tmpReal0 = w.r;\n", "file_path": "libs/dsperado-1.0/include/FFTransformer.h", "rank": 65, "score": 17564.126725209302 }, { "content": " oa->write_character(to_char_type(0x9B));\n\n write_number(static_cast<std::uint64_t>(N));\n\n }\n\n // LCOV_EXCL_STOP\n\n\n\n // step 2: write each element\n\n for (const auto& el : *j.m_value.array)\n\n {\n\n write_cbor(el);\n\n }\n\n break;\n\n }\n\n\n\n case value_t::binary:\n\n {\n\n if (j.m_value.binary->has_subtype())\n\n {\n\n write_number(static_cast<std::uint8_t>(0xd8));\n\n write_number(j.m_value.binary->subtype());\n\n }\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 66, "score": 17564.086456992907 }, { "content": " // recursive call to compare array values at index i\n\n auto temp_diff = diff(source[i], target[i], path + \"/\" + std::to_string(i));\n\n result.insert(result.end(), temp_diff.begin(), temp_diff.end());\n\n ++i;\n\n }\n\n\n\n // i now reached the end of at least one array\n\n // in a second pass, traverse the remaining elements\n\n\n\n // remove my remaining elements\n\n const auto end_index = static_cast<difference_type>(result.size());\n\n while (i < source.size())\n\n {\n\n // add operations in reverse order to avoid invalid\n\n // indices\n\n result.insert(result.begin() + end_index, object(\n\n {\n\n {\"op\", \"remove\"},\n\n {\"path\", path + \"/\" + std::to_string(i)}\n\n }));\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 67, "score": 17564.015408819418 }, { "content": " JSON_ASSERT(!f.empty());\n\n for (auto pos = s.find(f); // find first occurrence of f\n\n pos != std::string::npos; // make sure f was found\n\n s.replace(pos, f.size(), t), // replace with t, and\n\n pos = s.find(f, pos + t.size())) // find next occurrence of f\n\n {}\n\n }\n\n\n\n /// escape \"~\" to \"~0\" and \"/\" to \"~1\"\n\n static std::string escape(std::string s)\n\n {\n\n replace_substring(s, \"~\", \"~0\");\n\n replace_substring(s, \"/\", \"~1\");\n\n return s;\n\n }\n\n\n\n /// unescape \"~1\" to tilde and \"~0\" to slash (order is important!)\n\n static void unescape(std::string& s)\n\n {\n\n replace_substring(s, \"~1\", \"/\");\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 68, "score": 17563.8169115604 }, { "content": "#include <iterator> // random_access_iterator_tag\n\n\n\n// #include <nlohmann/detail/meta/void_t.hpp>\n\n\n\n\n\nnamespace nlohmann\n\n{\n\nnamespace detail\n\n{\n\ntemplate<typename ...Ts> struct make_void\n\n{\n\n using type = void;\n\n};\n\ntemplate<typename ...Ts> using void_t = typename make_void<Ts...>::type;\n\n} // namespace detail\n\n} // namespace nlohmann\n\n\n\n// #include <nlohmann/detail/meta/cpp_future.hpp>\n\n\n\n\n\nnamespace nlohmann\n\n{\n\nnamespace detail\n\n{\n\ntemplate<typename It, typename = void>\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 69, "score": 17563.801313495325 }, { "content": "\n\n /*!\n\n @brief inserts elements\n\n\n\n Inserts elements from range `[first, last)`.\n\n\n\n @param[in] first begin of the range of elements to insert\n\n @param[in] last end of the range of elements to insert\n\n\n\n @throw type_error.309 if called on JSON values other than objects; example:\n\n `\"cannot use insert() with string\"`\n\n @throw invalid_iterator.202 if iterator @a first or @a last does does not\n\n point to an object; example: `\"iterators first and last must point to\n\n objects\"`\n\n @throw invalid_iterator.210 if @a first and @a last do not belong to the\n\n same JSON value; example: `\"iterators do not fit\"`\n\n\n\n @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number\n\n of elements to insert.\n\n\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 70, "score": 17563.742147521723 }, { "content": " auto length = std::strlen(reinterpret_cast<const char*>(b));\n\n const auto* ptr = reinterpret_cast<const char*>(b);\n\n return input_adapter(ptr, ptr + length);\n\n}\n\n\n\ntemplate<typename T, std::size_t N>\n\nauto input_adapter(T (&array)[N]) -> decltype(input_adapter(array, array + N))\n\n{\n\n return input_adapter(array, array + N);\n\n}\n\n\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 71, "score": 17563.71897468626 }, { "content": " if (N <= 0x17)\n\n {\n\n write_number(static_cast<std::uint8_t>(0x60 + N));\n\n }\n\n else if (N <= (std::numeric_limits<std::uint8_t>::max)())\n\n {\n\n oa->write_character(to_char_type(0x78));\n\n write_number(static_cast<std::uint8_t>(N));\n\n }\n\n else if (N <= (std::numeric_limits<std::uint16_t>::max)())\n\n {\n\n oa->write_character(to_char_type(0x79));\n\n write_number(static_cast<std::uint16_t>(N));\n\n }\n\n else if (N <= (std::numeric_limits<std::uint32_t>::max)())\n\n {\n\n oa->write_character(to_char_type(0x7A));\n\n write_number(static_cast<std::uint32_t>(N));\n\n }\n\n // LCOV_EXCL_START\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 72, "score": 17563.71496153338 }, { "content": " iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept\n\n {\n\n m_object = other.m_object;\n\n m_it = other.m_it;\n\n return *this;\n\n }\n\n\n\n private:\n\n /*!\n\n @brief set the iterator to the first value\n\n @pre The iterator is initialized; i.e. `m_object != nullptr`.\n\n */\n\n void set_begin() noexcept\n\n {\n\n JSON_ASSERT(m_object != nullptr);\n\n\n\n switch (m_object->m_type)\n\n {\n\n case value_t::object:\n\n {\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 73, "score": 17563.696815985717 }, { "content": "#pragma once\n\n\n\n#include <vector>\n\n#include <complex>\n\n#include <cassert>\n\n#include <FFTransformer.h>\n\n\n\nnamespace dsperado {\n\n /*\n\n * Hilbert transformer class.\n\n * Actually creates complex analytic signal, the imaginary part of which\n\n * is the actual Hilbert transform result.\n\n * Intended to be used if multiple one-size transformations are needed.\n\n * The first template argument is the desired Complex base type.\n\n */\n\n template<typename T>\n", "file_path": "libs/dsperado-1.0/include/HilbertTransformer.h", "rank": 74, "score": 17563.683127134474 }, { "content": " //\n\n // decimal digits are sufficient to identify all binary floating-point\n\n // numbers (Matula, \"In-and-Out conversions\").\n\n // This implies that the algorithm does not produce more than N decimal\n\n // digits.\n\n //\n\n // N = 17 for p = 53 (IEEE double precision)\n\n // N = 9 for p = 24 (IEEE single precision)\n\n}\n\n\n\n/*!\n\nv = buf * 10^decimal_exponent\n\nlen is the length of the buffer (number of decimal digits)\n\nThe buffer must be large enough, i.e. >= max_digits10.\n\n*/\n\nJSON_HEDLEY_NON_NULL(1)\n\ninline void grisu2(char* buf, int& len, int& decimal_exponent,\n\n diyfp m_minus, diyfp v, diyfp m_plus)\n\n{\n\n JSON_ASSERT(m_plus.e == m_minus.e);\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 75, "score": 17563.65462217355 }, { "content": "#include <cstdint> // uint8_t\n\n#include <cstdio> // snprintf\n\n#include <limits> // numeric_limits\n\n#include <string> // string, char_traits\n\n#include <type_traits> // is_same\n\n#include <utility> // move\n\n\n\n// #include <nlohmann/detail/conversions/to_chars.hpp>\n\n\n\n\n\n#include <array> // array\n\n#include <cmath> // signbit, isfinite\n\n#include <cstdint> // intN_t, uintN_t\n\n#include <cstring> // memcpy, memmove\n\n#include <limits> // numeric_limits\n\n#include <type_traits> // conditional\n\n\n\n// #include <nlohmann/detail/macro_scope.hpp>\n\n\n\n\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 76, "score": 17563.608356168028 }, { "content": " write_number(static_cast<std::uint8_t>(0x80 + N));\n\n }\n\n else if (N <= (std::numeric_limits<std::uint8_t>::max)())\n\n {\n\n oa->write_character(to_char_type(0x98));\n\n write_number(static_cast<std::uint8_t>(N));\n\n }\n\n else if (N <= (std::numeric_limits<std::uint16_t>::max)())\n\n {\n\n oa->write_character(to_char_type(0x99));\n\n write_number(static_cast<std::uint16_t>(N));\n\n }\n\n else if (N <= (std::numeric_limits<std::uint32_t>::max)())\n\n {\n\n oa->write_character(to_char_type(0x9A));\n\n write_number(static_cast<std::uint32_t>(N));\n\n }\n\n // LCOV_EXCL_START\n\n else if (N <= (std::numeric_limits<std::uint64_t>::max)())\n\n {\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 77, "score": 17563.587043900294 }, { "content": " }\n\n\n\n size_type count(const Key& key) const\n\n {\n\n for (auto it = this->begin(); it != this->end(); ++it)\n\n {\n\n if (it->first == key)\n\n {\n\n return 1;\n\n }\n\n }\n\n return 0;\n\n }\n\n\n\n iterator find(const Key& key)\n\n {\n\n for (auto it = this->begin(); it != this->end(); ++it)\n\n {\n\n if (it->first == key)\n\n {\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 78, "score": 17563.57333390645 }, { "content": " return at(key);\n\n }\n\n\n\n T& at(const Key& key)\n\n {\n\n for (auto it = this->begin(); it != this->end(); ++it)\n\n {\n\n if (it->first == key)\n\n {\n\n return it->second;\n\n }\n\n }\n\n\n\n throw std::out_of_range(\"key not found\");\n\n }\n\n\n\n const T& at(const Key& key) const\n\n {\n\n for (auto it = this->begin(); it != this->end(); ++it)\n\n {\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 79, "score": 17563.50310773417 }, { "content": " j.assert_invariant();\n\n }\n\n\n\n template<typename BasicJsonType, typename T,\n\n enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>\n\n static void construct(BasicJsonType& j, const std::valarray<T>& arr)\n\n {\n\n j.m_type = value_t::array;\n\n j.m_value = value_t::array;\n\n j.m_value.array->resize(arr.size());\n\n if (arr.size() > 0)\n\n {\n\n std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin());\n\n }\n\n j.assert_invariant();\n\n }\n\n};\n\n\n\ntemplate<>\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 80, "score": 17563.486550056587 }, { "content": "\n\n // use a pointer to fill the buffer\n\n auto buffer_ptr = number_buffer.begin();\n\n\n\n const bool is_negative = std::is_same<NumberType, number_integer_t>::value && !(x >= 0); // see issue #755\n\n number_unsigned_t abs_value;\n\n\n\n unsigned int n_chars;\n\n\n\n if (is_negative)\n\n {\n\n *buffer_ptr = '-';\n\n abs_value = remove_sign(static_cast<number_integer_t>(x));\n\n\n\n // account one more byte for the minus sign\n\n n_chars = 1 + count_digits(abs_value);\n\n }\n\n else\n\n {\n\n abs_value = static_cast<number_unsigned_t>(x);\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 81, "score": 17563.451411388134 }, { "content": " @sa @ref patch -- apply a JSON patch\n\n @sa [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396)\n\n\n\n @since version 3.0.0\n\n */\n\n void merge_patch(const basic_json& apply_patch)\n\n {\n\n if (apply_patch.is_object())\n\n {\n\n if (!is_object())\n\n {\n\n *this = object();\n\n }\n\n for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it)\n\n {\n\n if (it.value().is_null())\n\n {\n\n erase(it.key());\n\n }\n\n else\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 82, "score": 17563.442993962537 }, { "content": " lexer(lexer&&) = default;\n\n lexer& operator=(lexer&) = delete;\n\n lexer& operator=(lexer&&) = default;\n\n ~lexer() = default;\n\n\n\n private:\n\n /////////////////////\n\n // locales\n\n /////////////////////\n\n\n\n /// return the locale-dependent decimal point\n\n JSON_HEDLEY_PURE\n\n static char get_decimal_point() noexcept\n\n {\n\n const auto* loc = localeconv();\n\n JSON_ASSERT(loc != nullptr);\n\n return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);\n\n }\n\n\n\n /////////////////////\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 83, "score": 17563.34699824347 }, { "content": "#pragma once\n\n\n\n#include <cassert>\n\n#include <cstddef>\n\n#include <cmath>\n\n#include <memory>\n\n#include <type_traits>\n\n#include <unordered_map>\n\n\n\n#include <Complex.h>\n\n#include <Arena.h>\n\n#include <Constants.h>\n\n\n\nnamespace dsperado {\n\n /*\n\n * Fast Fourier Transformer class.\n\n * Intended to be used if multiple one-size transformations are needed.\n\n * The first template argument is the desired Complex base type.\n\n * The second template argument is the FFT direction flag (true - FFT, false - IFFT).\n\n */\n\n template <typename T, bool forward = true>\n", "file_path": "libs/dsperado-1.0/include/FFTransformer.h", "rank": 84, "score": 17563.343027666455 }, { "content": " */\n\n using binary_t = nlohmann::byte_container_with_subtype<BinaryType>;\n\n /// @}\n\n\n\n private:\n\n\n\n /// helper for exception-safe object creation\n\n template<typename T, typename... Args>\n\n JSON_HEDLEY_RETURNS_NON_NULL\n\n static T* create(Args&& ... args)\n\n {\n\n AllocatorType<T> alloc;\n\n using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;\n\n\n\n auto deleter = [&](T * object)\n\n {\n\n AllocatorTraits::deallocate(alloc, object, 1);\n\n };\n\n std::unique_ptr<T, decltype(deleter)> object(AllocatorTraits::allocate(alloc, 1), deleter);\n\n AllocatorTraits::construct(alloc, object.get(), std::forward<Args>(args)...);\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 85, "score": 17563.33678609874 }, { "content": " @throw type_error.312 if called on JSON values other than objects; example:\n\n `\"cannot use update() with string\"`\n\n @throw invalid_iterator.202 if iterator @a first or @a last does does not\n\n point to an object; example: `\"iterators first and last must point to\n\n objects\"`\n\n @throw invalid_iterator.210 if @a first and @a last do not belong to the\n\n same JSON value; example: `\"iterators do not fit\"`\n\n\n\n @complexity O(N*log(size() + N)), where N is the number of elements to\n\n insert.\n\n\n\n @liveexample{The example shows how `update()` is used__range.,update}\n\n\n\n @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update\n\n\n\n @since version 3.0.0\n\n */\n\n void update(const_iterator first, const_iterator last)\n\n {\n\n // implicitly convert null value to an empty object\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 86, "score": 17563.137121966316 }, { "content": " /// generic iterator for all other types\n\n primitive_iterator_t primitive_iterator {};\n\n};\n\n} // namespace detail\n\n} // namespace nlohmann\n\n\n\n// #include <nlohmann/detail/iterators/iter_impl.hpp>\n\n\n\n\n\n#include <iterator> // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next\n\n#include <type_traits> // conditional, is_const, remove_const\n\n\n\n// #include <nlohmann/detail/exceptions.hpp>\n\n\n\n// #include <nlohmann/detail/iterators/internal_iterator.hpp>\n\n\n\n// #include <nlohmann/detail/iterators/primitive_iterator.hpp>\n\n\n\n// #include <nlohmann/detail/macro_scope.hpp>\n\n\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 87, "score": 17562.990790192416 }, { "content": " // default case: insert add offset\n\n parent.insert(parent.begin() + static_cast<difference_type>(idx), val);\n\n }\n\n break;\n\n }\n\n\n\n // if there exists a parent it cannot be primitive\n\n default: // LCOV_EXCL_LINE\n\n JSON_ASSERT(false); // LCOV_EXCL_LINE\n\n }\n\n };\n\n\n\n // wrapper for \"remove\" operation; remove value at ptr\n\n const auto operation_remove = [&result](json_pointer & ptr)\n\n {\n\n // get reference to parent of JSON pointer ptr\n\n const auto last_path = ptr.back();\n\n ptr.pop_back();\n\n basic_json& parent = result.at(ptr);\n\n\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 88, "score": 17562.980006924405 }, { "content": " // this function only makes sense after reading `\\u`\n\n JSON_ASSERT(current == 'u');\n\n int codepoint = 0;\n\n\n\n const auto factors = { 12u, 8u, 4u, 0u };\n\n for (const auto factor : factors)\n\n {\n\n get();\n\n\n\n if (current >= '0' && current <= '9')\n\n {\n\n codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x30u) << factor);\n\n }\n\n else if (current >= 'A' && current <= 'F')\n\n {\n\n codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x37u) << factor);\n\n }\n\n else if (current >= 'a' && current <= 'f')\n\n {\n\n codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x57u) << factor);\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 89, "score": 17562.856823855942 }, { "content": " @return JSON binary array value\n\n\n\n @complexity Linear in the size of @a init.\n\n\n\n @exceptionsafety Strong guarantee: if an exception is thrown, there are no\n\n changes to any JSON value.\n\n\n\n @since version 3.8.0\n\n */\n\n JSON_HEDLEY_WARN_UNUSED_RESULT\n\n static basic_json binary(const typename binary_t::container_type& init)\n\n {\n\n auto res = basic_json();\n\n res.m_type = value_t::binary;\n\n res.m_value = init;\n\n return res;\n\n }\n\n\n\n /*!\n\n @brief explicitly create a binary array (with subtype)\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 90, "score": 17562.61899174915 }, { "content": " write_number(static_cast<std::uint32_t>(N));\n\n }\n\n // LCOV_EXCL_START\n\n else if (N <= (std::numeric_limits<std::uint64_t>::max)())\n\n {\n\n oa->write_character(to_char_type(0x5B));\n\n write_number(static_cast<std::uint64_t>(N));\n\n }\n\n // LCOV_EXCL_STOP\n\n\n\n // step 2: write each element\n\n oa->write_characters(\n\n reinterpret_cast<const CharType*>(j.m_value.binary->data()),\n\n N);\n\n\n\n break;\n\n }\n\n\n\n case value_t::object:\n\n {\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 91, "score": 17562.61987142239 }, { "content": "\n\n Returns an iterator to the first element.\n\n\n\n @image html range-begin-end.svg \"Illustration from cppreference.com\"\n\n\n\n @return iterator to the first element\n\n\n\n @complexity Constant.\n\n\n\n @requirement This function helps `basic_json` satisfying the\n\n [Container](https://en.cppreference.com/w/cpp/named_req/Container)\n\n requirements:\n\n - The complexity is constant.\n\n\n\n @liveexample{The following code shows an example for `begin()`.,begin}\n\n\n\n @sa @ref cbegin() -- returns a const iterator to the beginning\n\n @sa @ref end() -- returns an iterator to the end\n\n @sa @ref cend() -- returns a const iterator to the end\n\n\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 92, "score": 17562.505581688532 }, { "content": "\n\n oa->write_character(to_char_type(output_type));\n\n write_number(static_cast<std::uint16_t>(N));\n\n }\n\n else if (N <= (std::numeric_limits<std::uint32_t>::max)())\n\n {\n\n std::uint8_t output_type = use_ext\n\n ? 0xC9 // ext 32\n\n : 0xC6; // bin 32\n\n\n\n oa->write_character(to_char_type(output_type));\n\n write_number(static_cast<std::uint32_t>(N));\n\n }\n\n\n\n // step 1.5: if this is an ext type, write the subtype\n\n if (use_ext)\n\n {\n\n write_number(static_cast<std::int8_t>(j.m_value.binary->subtype()));\n\n }\n\n\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 93, "score": 17562.494386242543 }, { "content": " m_it.object_iterator = m_object->m_value.object->begin();\n\n break;\n\n }\n\n\n\n case value_t::array:\n\n {\n\n m_it.array_iterator = m_object->m_value.array->begin();\n\n break;\n\n }\n\n\n\n case value_t::null:\n\n {\n\n // set to end so begin()==end() is true: null is empty\n\n m_it.primitive_iterator.set_end();\n\n break;\n\n }\n\n\n\n default:\n\n {\n\n m_it.primitive_iterator.set_begin();\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 94, "score": 17562.35304671245 }, { "content": " Returns a const iterator to the first element.\n\n\n\n @image html range-begin-end.svg \"Illustration from cppreference.com\"\n\n\n\n @return const iterator to the first element\n\n\n\n @complexity Constant.\n\n\n\n @requirement This function helps `basic_json` satisfying the\n\n [Container](https://en.cppreference.com/w/cpp/named_req/Container)\n\n requirements:\n\n - The complexity is constant.\n\n - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.\n\n\n\n @liveexample{The following code shows an example for `cbegin()`.,cbegin}\n\n\n\n @sa @ref begin() -- returns an iterator to the beginning\n\n @sa @ref end() -- returns an iterator to the end\n\n @sa @ref cend() -- returns a const iterator to the end\n\n\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 95, "score": 17562.3065840579 }, { "content": "#include <algorithm> // generate_n\n\n#include <array> // array\n\n#include <cmath> // ldexp\n\n#include <cstddef> // size_t\n\n#include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t\n\n#include <cstdio> // snprintf\n\n#include <cstring> // memcpy\n\n#include <iterator> // back_inserter\n\n#include <limits> // numeric_limits\n\n#include <string> // char_traits, string\n\n#include <utility> // make_pair, move\n\n\n\n// #include <nlohmann/detail/exceptions.hpp>\n\n\n\n// #include <nlohmann/detail/input/input_adapters.hpp>\n\n\n\n\n\n#include <array> // array\n\n#include <cstddef> // size_t\n\n#include <cstdio> //FILE *\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 96, "score": 17562.277665884525 }, { "content": "#include <cmath> // isnan, isinf\n\n\n\n// #include <nlohmann/detail/input/binary_reader.hpp>\n\n\n\n// #include <nlohmann/detail/macro_scope.hpp>\n\n\n\n// #include <nlohmann/detail/output/output_adapters.hpp>\n\n\n\n\n\n#include <algorithm> // copy\n\n#include <cstddef> // size_t\n\n#include <ios> // streamsize\n\n#include <iterator> // back_inserter\n\n#include <memory> // shared_ptr, make_shared\n\n#include <ostream> // basic_ostream\n\n#include <string> // basic_string\n\n#include <vector> // vector\n\n// #include <nlohmann/detail/macro_scope.hpp>\n\n\n\n\n", "file_path": "libs/json-3.9.1/include/json.hpp", "rank": 97, "score": 17562.253103297167 } ]
C++
centreon-engine/test/commands/raw_run_async.cc
centreon/centreon-collect
e63fc4d888a120d588a93169e7d36b360616bdee
#include <cstdlib> #include <cstring> #include <exception> #include "com/centreon/engine/commands/raw.hh" #include "com/centreon/engine/commands/set.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/process.hh" #include "test/commands/wait_process.hh" #include "test/unittest.hh" using namespace com::centreon; using namespace com::centreon::engine; using namespace com::centreon::engine::commands; static bool run_without_timeout() { std::shared_ptr<raw> cmd(new raw(__func__, "./bin_test_run --timeout=off")); wait_process wait_proc(cmd.get()); set::instance().add_command(cmd); nagios_macros mac; unsigned long id(cmd->run(cmd->get_command_line(), mac, 0)); wait_proc.wait(); result const& res = wait_proc.get_result(); return (!((res.command_id != id) || (res.exit_code != STATE_OK) || (res.exit_status != process::normal) || (res.output != cmd->get_command_line()))); } static bool run_with_timeout() { std::shared_ptr<raw> cmd(new raw(__func__, "./bin_test_run --timeout=on")); wait_process wait_proc(cmd.get()); set::instance().add_command(cmd); nagios_macros mac; uint64_t id(cmd->run(cmd->get_command_line(), mac, 1)); wait_proc.wait(); result const& res = wait_proc.get_result(); return (!((res.command_id != id) || (res.exit_code != STATE_UNKNOWN) || (res.exit_status != process::timeout) || (res.output != "(Process Timeout)"))); } static bool run_with_environment_macros() { config->enable_environment_macros(true); nagios_macros mac; char const* argv = "default_arg"; mac.argv[0] = new char[strlen(argv) + 1]; strcpy(mac.argv[0], argv); std::shared_ptr<raw> cmd(new raw(__func__, "./bin_test_run --check_macros")); wait_process wait_proc(cmd.get()); set::instance().add_command(cmd); unsigned long id(cmd->run(cmd->get_command_line(), mac, 0)); wait_proc.wait(); delete[] mac.argv[0]; result const& res = wait_proc.get_result(); return (!((res.command_id != id) || (res.exit_code != STATE_OK) || (res.exit_status != process::normal) || (res.output != cmd->get_command_line()))); } static bool run_with_single_quotes() { std::shared_ptr<raw> cmd( new raw(__func__, "'./bin_test_run' '--timeout'='off'")); wait_process wait_proc(cmd.get()); set::instance().add_command(cmd); nagios_macros mac; uint64_t id(cmd->run(cmd->get_command_line(), mac, 0)); wait_proc.wait(); result const& res = wait_proc.get_result(); return !((res.command_id != id) || (res.exit_code != STATE_OK) || (res.exit_status != process::normal) || (res.output != "./bin_test_run --timeout=off")); } static bool run_with_double_quotes() { std::shared_ptr<raw> cmd( new raw(__func__, "\"./bin_test_run\" \"--timeout\"=\"off\"")); wait_process wait_proc(cmd.get()); set::instance().add_command(cmd); nagios_macros mac; unsigned long id(cmd->run(cmd->get_command_line(), mac, 0)); wait_proc.wait(); result const& res = wait_proc.get_result(); return (!((res.command_id != id) || (res.exit_code != STATE_OK) || (res.exit_status != process::normal) || (res.output != "./bin_test_run --timeout=off"))); } int main_test(int argc, char** argv) { (void)argc; (void)argv; if (!run_without_timeout()) throw(engine_error() << "raw::run without timeout failed"); if (!run_with_timeout()) throw(engine_error() << "raw::run with timeout failed"); if (!run_with_environment_macros()) throw(engine_error() << "raw::run with macros failed"); if (!run_with_single_quotes()) throw(engine_error() << "raw::run with single quotes failed"); if (!run_with_double_quotes()) throw(engine_error() << "raw::run with double quotes failed"); return (EXIT_SUCCESS); } int main(int argc, char* argv[]) { unittest utest(argc, argv, &main_test); return (utest.run()); }
#include <cstdlib> #include <cstring> #include <exception> #include "com/centreon/engine/commands/raw.hh" #include "com/centreon/engine/commands/set.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/process.hh" #include "test/commands/wait_process.hh" #include "test/unittest.hh" using namespace com::centreon; using namespace com::centreon::engine; using namespace com::centreon::engine::commands; static bool run_without_timeout() { std::shared_ptr<raw> cmd(new raw(__func__, "./bin_test_run --timeout=off")); wait_process wait_proc(cmd.get()); set::instance().add_command(cmd); nagios_macros mac; unsigned long id(cmd->run(cmd->get_command_line(), mac, 0)); wait_proc.wait(); result const& res = wait_proc.get_result(); return (!((res.command_id != id) || (res.exit_code != STATE_OK) || (res.exit_status != process::normal) || (res.output != cmd->get_command_line()))); } static bool run_with_timeout() { std::shared_ptr<raw> cmd(new raw(__func__, "./bin_test_run --timeout=on")); wait_process wait_proc(cmd.get()); set::instance().add_command(cmd); nagios_macros mac; uint64_t id(cmd->run(cmd->get_command_line(), mac, 1)); wait_proc.wait(); result const& res = wait_proc.get_result(); return (!((res.command_id != id) || (res.exit_code != STATE_UNKNOWN) || (res.exit_status != process::timeout) || (res.output != "(Process Timeout)"))); } static bool run_with_environment_macros() { config->ena
d::shared_ptr<raw> cmd( new raw(__func__, "\"./bin_test_run\" \"--timeout\"=\"off\"")); wait_process wait_proc(cmd.get()); set::instance().add_command(cmd); nagios_macros mac; unsigned long id(cmd->run(cmd->get_command_line(), mac, 0)); wait_proc.wait(); result const& res = wait_proc.get_result(); return (!((res.command_id != id) || (res.exit_code != STATE_OK) || (res.exit_status != process::normal) || (res.output != "./bin_test_run --timeout=off"))); } int main_test(int argc, char** argv) { (void)argc; (void)argv; if (!run_without_timeout()) throw(engine_error() << "raw::run without timeout failed"); if (!run_with_timeout()) throw(engine_error() << "raw::run with timeout failed"); if (!run_with_environment_macros()) throw(engine_error() << "raw::run with macros failed"); if (!run_with_single_quotes()) throw(engine_error() << "raw::run with single quotes failed"); if (!run_with_double_quotes()) throw(engine_error() << "raw::run with double quotes failed"); return (EXIT_SUCCESS); } int main(int argc, char* argv[]) { unittest utest(argc, argv, &main_test); return (utest.run()); }
ble_environment_macros(true); nagios_macros mac; char const* argv = "default_arg"; mac.argv[0] = new char[strlen(argv) + 1]; strcpy(mac.argv[0], argv); std::shared_ptr<raw> cmd(new raw(__func__, "./bin_test_run --check_macros")); wait_process wait_proc(cmd.get()); set::instance().add_command(cmd); unsigned long id(cmd->run(cmd->get_command_line(), mac, 0)); wait_proc.wait(); delete[] mac.argv[0]; result const& res = wait_proc.get_result(); return (!((res.command_id != id) || (res.exit_code != STATE_OK) || (res.exit_status != process::normal) || (res.output != cmd->get_command_line()))); } static bool run_with_single_quotes() { std::shared_ptr<raw> cmd( new raw(__func__, "'./bin_test_run' '--timeout'='off'")); wait_process wait_proc(cmd.get()); set::instance().add_command(cmd); nagios_macros mac; uint64_t id(cmd->run(cmd->get_command_line(), mac, 0)); wait_proc.wait(); result const& res = wait_proc.get_result(); return !((res.command_id != id) || (res.exit_code != STATE_OK) || (res.exit_status != process::normal) || (res.output != "./bin_test_run --timeout=off")); } static bool run_with_double_quotes() { st
random
[ { "content": "class timeout : public std::exception {\n\n public:\n\n timeout() noexcept : std::exception() {}\n\n timeout& operator=(const timeout&) = delete;\n\n};\n\n} // namespace exceptions\n\n\n\nCCB_END()\n\n\n\n#endif // !CCB_EXCEPTIONS_TIMEOUT_HH\n", "file_path": "centreon-broker/core/inc/com/centreon/broker/exceptions/timeout.hh", "rank": 0, "score": 171384.84871247923 }, { "content": "struct timeval check_result::get_start_time() const {\n\n return _start_time;\n\n}\n\n\n\nvoid check_result::set_start_time(struct timeval start_time) {\n\n _start_time = start_time;\n\n}\n\n\n\nint check_result::get_return_code() const {\n\n return _return_code;\n\n}\n\n\n\nvoid check_result::set_return_code(int return_code) {\n\n _return_code = return_code;\n\n}\n\n\n\nbool check_result::get_early_timeout() const {\n\n return _early_timeout;\n\n}\n\n\n", "file_path": "centreon-engine/src/check_result.cc", "rank": 1, "score": 157072.8178203478 }, { "content": "struct timeval check_result::get_finish_time() const {\n\n return _finish_time;\n\n}\n\n\n\nvoid check_result::set_finish_time(struct timeval finish_time) {\n\n _finish_time = finish_time;\n\n}\n\n\n", "file_path": "centreon-engine/src/check_result.cc", "rank": 2, "score": 157072.8178203478 }, { "content": "enum check_source check_result::get_object_check_type() const {\n\n return _object_check_type;\n\n}\n\n\n\nvoid check_result::set_object_check_type(enum check_source object_check_type) {\n\n _object_check_type = object_check_type;\n\n}\n\n\n\nnotifier* check_result::get_notifier() {\n\n return _notifier;\n\n}\n\n\n\nvoid check_result::set_notifier(notifier* notifier) {\n\n _notifier = notifier;\n\n}\n\n\n", "file_path": "centreon-engine/src/check_result.cc", "rank": 3, "score": 152704.74942367658 }, { "content": "enum checkable::check_type check_result::get_check_type() const {\n\n return _check_type;\n\n}\n\n\n\nvoid check_result::set_check_type(enum checkable::check_type check_type) {\n\n _check_type = check_type;\n\n}\n\n\n\ndouble check_result::get_latency() const {\n\n return _latency;\n\n}\n\n\n\nvoid check_result::set_latency(double latency) {\n\n _latency = latency;\n\n}\n\n\n\nint check_result::get_check_options() const {\n\n return _check_options;\n\n}\n\n\n\nvoid check_result::set_check_options(int check_options) {\n\n _check_options = check_options;\n\n}\n", "file_path": "centreon-engine/src/check_result.cc", "rank": 4, "score": 149931.7238059252 }, { "content": "#include <string.h>\n\n#include <sstream>\n\n#include \"com/centreon/engine/exceptions/error.hh\"\n\n\n\nusing namespace com::centreon::engine;\n\n\n\n/**\n\n * Check that unsigned long long insertion works properly in error.\n\n *\n\n * @return 0 on success.\n\n */\n\nint main() {\n\n // Insert unsigned long longs.\n\n error e;\n\n e << 42ull << 1ull << 7896ull;\n\n\n\n#ifdef ULLONG_MAX\n\n e << ULLONG_MAX - 789 << ULLONG_MAX << 0ull;\n\n#endif // !ULLONG_MAX\n\n\n", "file_path": "centreon-engine/test/error/insert_unsigned_long_long.cc", "rank": 5, "score": 128053.05156870288 }, { "content": "/*\n\n** Copyright 2011-2013 Merethis\n\n**\n\n** This file is part of Centreon Engine.\n\n**\n\n** Centreon Engine is free software: you can redistribute it and/or\n\n** modify it under the terms of the GNU General Public License version 2\n\n** as published by the Free Software Foundation.\n\n**\n\n** Centreon Engine is distributed in the hope that it will be useful,\n\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\n** General Public License for more details.\n\n**\n\n** You should have received a copy of the GNU General Public License\n\n** along with Centreon Engine. If not, see\n\n** <http://www.gnu.org/licenses/>.\n\n*/\n\n\n\n#include <limits.h>\n", "file_path": "centreon-engine/test/error/insert_unsigned_long_long.cc", "rank": 6, "score": 128025.06142457516 }, { "content": " // Conversion reference.\n\n std::ostringstream oss;\n\n oss << 42ull << 1ull << 7896ull;\n\n\n\n#ifdef ULLONG_MAX\n\n oss << ULLONG_MAX - 789 << ULLONG_MAX << 0ull;\n\n#endif // !ULLONG_MAX\n\n\n\n // Check.\n\n return (strcmp(oss.str().c_str(), e.what()));\n\n}\n", "file_path": "centreon-engine/test/error/insert_unsigned_long_long.cc", "rank": 7, "score": 128016.15833180358 }, { "content": "class process {\n\n friend class process_manager;\n\n\n\n /* Constants */\n\n const std::array<bool, 3> _enable_stream;\n\n process_listener* const _listener;\n\n\n\n /* Constants except during exec() call */\n\n uint32_t _timeout;\n\n\n\n /* Constants except when they are initialized at exec() and closed when\n\n * process is over. */\n\n std::atomic_bool _is_timeout;\n\n std::atomic_int _status;\n\n std::array<int, 3> _stream;\n\n pid_t _process;\n\n\n\n /* Almost never changed, we have two such functions, one with pgid and the\n\n * other without. */\n\n pid_t (*_create_process)(char**, char**);\n", "file_path": "centreon-clib/inc/com/centreon/process.hh", "rank": 8, "score": 123521.66466141999 }, { "content": "class process;\n", "file_path": "centreon-clib/inc/com/centreon/process_manager.hh", "rank": 9, "score": 122295.88478487814 }, { "content": "class process {\n\n friend class process_manager;\n\n\n\n public:\n\n enum status { normal = 0, crash = 1, timeout = 2 };\n\n enum stream { in = 0, out = 1, err = 2 };\n\n\n\n private:\n\n std::string _buffer_err;\n\n std::string _buffer_out;\n\n pid_t (*_create_process)(char**, char**);\n\n mutable std::condition_variable _cv_buffer_err;\n\n mutable std::condition_variable _cv_buffer_out;\n\n mutable std::condition_variable _cv_process_running;\n\n const std::array<bool, 3> _enable_stream;\n\n std::array<int, 3> _stream;\n\n timestamp _end_time;\n\n bool _is_timeout;\n\n process_listener* _listener;\n\n mutable std::mutex _lock_process;\n", "file_path": "centreon-broker/neb/inc/com/centreon/process.hh", "rank": 10, "score": 122295.88478487814 }, { "content": "class result {\n\n void _internal_copy(result const& right);\n\n\n\n public:\n\n result();\n\n result(result const& right);\n\n ~result() noexcept;\n\n result& operator=(result const& right);\n\n bool operator==(result const& right) const noexcept;\n\n bool operator!=(result const& right) const noexcept;\n\n uint64_t command_id;\n\n timestamp end_time;\n\n int exit_code;\n\n process::status exit_status;\n\n timestamp start_time;\n\n std::string output;\n\n};\n\n} // namespace commands\n\n\n\nCCE_END()\n\n\n\n#endif // !CCE_COMMANDS_RESULT_HH\n", "file_path": "centreon-engine/inc/com/centreon/engine/commands/result.hh", "rank": 11, "score": 121186.9602219385 }, { "content": "class process;\n", "file_path": "centreon-broker/neb/inc/com/centreon/process_manager.hh", "rank": 12, "score": 121110.64754951699 }, { "content": "class result {\n\n void _internal_copy(result const& right);\n\n\n\n public:\n\n result();\n\n result(result const& right);\n\n ~result() noexcept;\n\n result& operator=(result const& right);\n\n bool operator==(result const& right) const noexcept;\n\n bool operator!=(result const& right) const noexcept;\n\n uint64_t command_id;\n\n timestamp end_time;\n\n int exit_code;\n\n process::status exit_status;\n\n timestamp start_time;\n\n std::string output;\n\n};\n\n} // namespace commands\n\n\n\nCCE_END()\n\n\n\n#endif // !CCE_COMMANDS_RESULT_HH\n", "file_path": "centreon-broker/neb/inc/com/centreon/engine/commands/result.hh", "rank": 13, "score": 120038.9355301661 }, { "content": "program const& state::globals() const throw() {\n\n return (_globals);\n\n}\n\n\n\n/**\n\n * Get hosts.\n\n *\n\n * @return The host list.\n\n */\n\nlist_host& state::hosts() throw() {\n\n return (_hosts);\n\n}\n\n\n\n/**\n\n * Get hosts.\n\n *\n\n * @return The host list.\n\n */\n\nlist_host const& state::hosts() const throw() {\n\n return (_hosts);\n", "file_path": "centreon-engine/src/retention/state.cc", "rank": 14, "score": 119696.43714784266 }, { "content": "class result {\n\n public:\n\n result();\n\n result(result const& r) = delete;\n\n ~result() = default;\n\n result& operator=(result const& r) = delete;\n\n uint64_t get_command_id() const noexcept;\n\n std::string const& get_error() const noexcept;\n\n bool get_executed() const noexcept;\n\n int get_exit_code() const noexcept;\n\n std::string const& get_output() const noexcept;\n\n void set_command_id(uint64_t cmd_id) noexcept;\n\n void set_error(std::string const& error);\n\n void set_executed(bool executed) noexcept;\n\n void set_exit_code(int code) noexcept;\n\n void set_output(std::string const& output);\n\n\n\n private:\n\n uint64_t _cmd_id;\n\n std::string _error;\n\n bool _executed;\n\n int _exit_code;\n\n std::string _output;\n\n};\n\n} // namespace checks\n\n\n\nCCCP_END()\n\n\n\n#endif // !CCCP_CHECKS_RESULT_HH\n", "file_path": "centreon-connector/perl/inc/com/centreon/connector/perl/checks/result.hh", "rank": 15, "score": 118927.66605082473 }, { "content": "class result {\n\n public:\n\n result();\n\n result(result const& r);\n\n ~result() = default;\n\n result& operator=(result const& r);\n\n unsigned long long get_command_id() const noexcept;\n\n std::string const& get_error() const noexcept;\n\n bool get_executed() const noexcept;\n\n int get_exit_code() const noexcept;\n\n std::string const& get_output() const noexcept;\n\n void set_command_id(unsigned long long cmd_id) noexcept;\n\n void set_error(std::string const& error);\n\n void set_executed(bool executed) noexcept;\n\n void set_exit_code(int code) noexcept;\n\n void set_output(std::string const& output);\n\n\n\n private:\n\n void _internal_copy(result const& r);\n\n\n", "file_path": "centreon-connector/ssh/inc/com/centreon/connector/ssh/checks/result.hh", "rank": 16, "score": 118927.66605082473 }, { "content": "class wait_process : public command_listener {\n\n public:\n\n /**\n\n * Constructor.\n\n *\n\n * @param[in] cmd Process.\n\n */\n\n wait_process(command* cmd) : _cmd(cmd) { _cmd->set_listener(this); }\n\n\n\n /**\n\n * Destructor.\n\n */\n\n ~wait_process() noexcept {}\n\n\n\n /**\n\n * Get command result.\n\n *\n\n * @return Command execution result.\n\n */\n\n result const& get_result() const noexcept { return _res; }\n", "file_path": "centreon-engine/test/commands/wait_process.hh", "rank": 17, "score": 110459.0831676819 }, { "content": "\n\n#include <exception>\n\n#include \"com/centreon/broker/namespace.hh\"\n\n\n\nCCB_BEGIN()\n\n\n\nnamespace exceptions {\n\n/**\n\n * @class timeout timeout.hh \"com/centreon/broker/exceptions/timeout.hh\"\n\n * @brief Timeout exception.\n\n *\n\n * Exception that is thrown upon timeout.\n\n */\n", "file_path": "centreon-broker/core/inc/com/centreon/broker/exceptions/timeout.hh", "rank": 18, "score": 109566.49052838133 }, { "content": "/*\n\n** Copyright 2015,2017,2020 Centreon\n\n**\n\n** Licensed under the Apache License, Version 2.0 (the \"License\");\n\n** you may not use this file except in compliance with the License.\n\n** You may obtain a copy of the License at\n\n**\n\n** http://www.apache.org/licenses/LICENSE-2.0\n\n**\n\n** Unless required by applicable law or agreed to in writing, software\n\n** distributed under the License is distributed on an \"AS IS\" BASIS,\n\n** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n** See the License for the specific language governing permissions and\n\n** limitations under the License.\n\n**\n\n** For more information : [email protected]\n\n*/\n\n\n\n#ifndef CCB_EXCEPTIONS_TIMEOUT_HH\n\n#define CCB_EXCEPTIONS_TIMEOUT_HH\n", "file_path": "centreon-broker/core/inc/com/centreon/broker/exceptions/timeout.hh", "rank": 19, "score": 109552.55894674755 }, { "content": "#include \"com/centreon/engine/checks/checker.hh\"\n\n#include \"com/centreon/engine/exceptions/error.hh\"\n\n#include \"com/centreon/engine/globals.hh\"\n\n#include \"com/centreon/engine/modules/external_commands/commands.hh\"\n\n#include \"com/centreon/logging/engine.hh\"\n\n#include \"test/unittest.hh\"\n\n\n\nusing namespace com::centreon::engine;\n\n\n\n/**\n\n * Run process_service_check_result test.\n\n */\n\nstatic int check_process_service_check_result(int argc, char** argv) {\n\n (void)argc;\n\n (void)argv;\n\n\n\n service* svc = add_service(\n\n \"name\", \"description\", NULL, NULL, 0, 42, 0, 0, 0, 42.0, 0.0, 0.0, NULL,\n\n 0, 0, 0, 0, 0, 0, 0, 0, NULL, 0, \"command\", 0, 0, 0.0, 0.0, 0, 0, 0, 0, 0,\n\n 0, 0, 0, 0, 0, NULL, 0, 0, NULL, NULL, NULL, NULL, NULL, 0, 0, 0);\n", "file_path": "centreon-engine/test/modules/external_commands/process_service_check_result.cc", "rank": 20, "score": 106755.68775954991 }, { "content": "#include \"com/centreon/engine/checks/checker.hh\"\n\n#include \"com/centreon/engine/exceptions/error.hh\"\n\n#include \"com/centreon/engine/globals.hh\"\n\n#include \"com/centreon/engine/modules/external_commands/commands.hh\"\n\n#include \"com/centreon/logging/engine.hh\"\n\n#include \"test/unittest.hh\"\n\n\n\nusing namespace com::centreon::engine;\n\n\n\n/**\n\n * Run process_host_check_result test.\n\n */\n\nstatic int check_process_host_check_result(int argc, char** argv) {\n\n (void)argc;\n\n (void)argv;\n\n\n\n host* hst =\n\n add_host(\"name\", NULL, NULL, \"localhost\", NULL, 0, 0.0, 0.0, 42, 0, 0, 0,\n\n 0, 0, 0.0, 0.0, NULL, 0, NULL, 0, 0, NULL, 0, 0, 0.0, 0.0, 0, 0,\n\n 0, 0, 0, 0, 0, 0, NULL, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL,\n", "file_path": "centreon-engine/test/modules/external_commands/process_host_check_result.cc", "rank": 21, "score": 106755.39054794812 }, { "content": " NULL, 0, 0, 0, 0.0, 0.0, 0.0, 0, 0, 0, 0, 0);\n\n if (!hst)\n\n throw(engine_error() << \"create host failed.\");\n\n\n\n hst->accept_passive_host_checks = true;\n\n char const* cmd(\"[1317196300] PROCESS_HOST_CHECK_RESULT;name;0;output\");\n\n process_external_command(cmd);\n\n\n\n if (com::centreon::engine::checks::checker::instance().reaper_is_empty())\n\n throw(engine_error() << \"process_host_check_result failed.\");\n\n return (0);\n\n}\n\n\n\n/**\n\n * Init unit test.\n\n */\n\nint main(int argc, char** argv) {\n\n unittest utest(argc, argv, &check_process_host_check_result);\n\n return (utest.run());\n\n}\n", "file_path": "centreon-engine/test/modules/external_commands/process_host_check_result.cc", "rank": 22, "score": 106735.20370585106 }, { "content": " if (!svc)\n\n throw(engine_error() << \"create service failed.\");\n\n\n\n host* hst =\n\n add_host(\"name\", NULL, NULL, \"localhost\", NULL, 0, 0.0, 0.0, 42, 0, 0, 0,\n\n 0, 0, 0.0, 0.0, NULL, 0, NULL, 0, 0, NULL, 0, 0, 0.0, 0.0, 0, 0,\n\n 0, 0, 0, 0, 0, 0, NULL, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL,\n\n NULL, 0, 0, 0, 0.0, 0.0, 0.0, 0, 0, 0, 0, 0);\n\n if (!hst)\n\n throw(engine_error() << \"create host failed.\");\n\n\n\n svc->accept_passive_service_checks = true;\n\n char const* cmd(\n\n \"[1317196300] PROCESS_SERVICE_CHECK_RESULT;name;description;0;output\");\n\n process_external_command(cmd);\n\n\n\n if (com::centreon::engine::checks::checker::instance().reaper_is_empty())\n\n throw(engine_error() << \"process_service_check_result failed.\");\n\n return (0);\n\n}\n\n\n\n/**\n\n * Init unit test.\n\n */\n\nint main(int argc, char** argv) {\n\n unittest utest(argc, argv, &check_process_service_check_result);\n\n return (utest.run());\n\n}\n", "file_path": "centreon-engine/test/modules/external_commands/process_service_check_result.cc", "rank": 23, "score": 106734.15856101879 }, { "content": "/*\n\n** Copyright 2011-2013 Merethis\n\n**\n\n** This file is part of Centreon Engine.\n\n**\n\n** Centreon Engine is free software: you can redistribute it and/or\n\n** modify it under the terms of the GNU General Public License version 2\n\n** as published by the Free Software Foundation.\n\n**\n\n** Centreon Engine is distributed in the hope that it will be useful,\n\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\n** General Public License for more details.\n\n**\n\n** You should have received a copy of the GNU General Public License\n\n** along with Centreon Engine. If not, see\n\n** <http://www.gnu.org/licenses/>.\n\n*/\n\n\n\n#include <exception>\n", "file_path": "centreon-engine/test/modules/external_commands/process_host_check_result.cc", "rank": 24, "score": 106733.97974410359 }, { "content": "/*\n\n** Copyright 2011-2013 Merethis\n\n**\n\n** This file is part of Centreon Engine.\n\n**\n\n** Centreon Engine is free software: you can redistribute it and/or\n\n** modify it under the terms of the GNU General Public License version 2\n\n** as published by the Free Software Foundation.\n\n**\n\n** Centreon Engine is distributed in the hope that it will be useful,\n\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\n** General Public License for more details.\n\n**\n\n** You should have received a copy of the GNU General Public License\n\n** along with Centreon Engine. If not, see\n\n** <http://www.gnu.org/licenses/>.\n\n*/\n\n\n\n#include <exception>\n", "file_path": "centreon-engine/test/modules/external_commands/process_service_check_result.cc", "rank": 25, "score": 106733.97974410359 }, { "content": "class result;\n\n} // namespace checks\n\nnamespace sessions {\n", "file_path": "centreon-connector/ssh/inc/com/centreon/connector/ssh/policy.hh", "rank": 26, "score": 104011.13716744985 }, { "content": "class result;\n\n} // namespace checks\n\n\n\n/**\n\n * @class policy policy.hh \"com/centreon/connector/perl/policy.hh\"\n\n * @brief Software policy.\n\n *\n\n * Wraps software policy within a class.\n\n */\n", "file_path": "centreon-connector/perl/inc/com/centreon/connector/perl/policy.hh", "rank": 27, "score": 104011.13716744985 }, { "content": "// Forward declaration.\n\nclass result;\n\n\n\n/**\n\n * @class check check.hh \"com/centreon/connector/ssh/checks/check.hh\"\n\n * @brief Execute a check on a host.\n\n *\n\n * Execute a check by opening a new channel on a SSH session.\n\n */\n", "file_path": "centreon-connector/ssh/inc/com/centreon/connector/ssh/checks/check.hh", "rank": 28, "score": 102707.64573178931 }, { "content": "class result;\n\n\n\n/**\n\n * @class check check.hh \"com/centreon/connector/perl/checks/check.hh\"\n\n * @brief Perl check.\n\n *\n\n * Class wrapping a Perl check as requested by the monitoring engine.\n\n */\n", "file_path": "centreon-connector/perl/inc/com/centreon/connector/perl/checks/check.hh", "rank": 29, "score": 102707.64573178931 }, { "content": "class timeout : public com::centreon::task {\n\n check* _check;\n\n\n\n public:\n\n timeout(check* chk = nullptr);\n\n ~timeout() noexcept override = default;\n\n timeout(timeout const& t) = delete;\n\n timeout& operator=(timeout const& t) = delete;\n\n check* get_check() const noexcept;\n\n void run() override;\n\n};\n\n} // namespace checks\n\n\n\nCCCS_END()\n\n\n\n#endif // !CCCS_CHECKS_TIMEOUT_HH\n", "file_path": "centreon-connector/ssh/inc/com/centreon/connector/ssh/checks/timeout.hh", "rank": 30, "score": 100440.46323627271 }, { "content": "class timeout : public com::centreon::task {\n\n check* _check;\n\n bool _final;\n\n\n\n public:\n\n explicit timeout(check* chk = NULL, bool final = false);\n\n timeout(timeout const& t) = delete;\n\n timeout& operator=(timeout const& t) = delete;\n\n void run() override;\n\n};\n\n} // namespace checks\n\n\n\nCCCP_END()\n\n\n\n#endif // !CCCP_CHECKS_TIMEOUT_HH\n", "file_path": "centreon-connector/perl/inc/com/centreon/connector/perl/checks/timeout.hh", "rank": 31, "score": 100440.46323627271 }, { "content": "--------------------------------------------------------------------------------\n\n-- Initializes the mapping on the elasticsearcg server\n\n-- @param socket the socket connected to the elasticsearch server\n\n--\n\n-- @return true on success, false otherwise\n\n--------------------------------------------------------------------------------\n\nlocal function init_index(socket)\n\n broker_log:info(1, \"init_index\")\n\n -- Initialize the index\n\n local header = 'PUT /centreon?pretty HTTP/1.1\\r\\nHost: '\n\n .. elastic.address .. ':' .. elastic.port\n\n .. '\\r\\nAccept: */*\\r\\nContent-Type: application/json\\r\\n'\n\n local content = [[{\n\n \"mappings\": {\n\n \"metrics\": {\n\n \"_all\": { \"enabled\": false },\n\n \"properties\": {\n\n \"host\": { \"type\": \"keyword\" },\n\n \"metric\": { \"type\": \"keyword\" },\n\n \"value\": { \"type\": \"double\" },\n\n \"timestamp\": { \"type\": \"date\" }\n\n }\n\n }\n\n }\n", "file_path": "centreon-broker/lua/examples/elastic.lua", "rank": 32, "score": 91006.71053155162 }, { "content": "enum checkable::check_type checkable::get_check_type() const {\n\n return _check_type;\n\n}\n\n\n\nvoid checkable::set_check_type(checkable::check_type check_type) {\n\n _check_type = check_type;\n\n}\n\n\n\nvoid checkable::set_current_attempt(int attempt) {\n\n _current_attempt = attempt;\n\n}\n\n\n\nint checkable::get_current_attempt() const {\n\n return _current_attempt;\n\n}\n\n\n\nvoid checkable::add_current_attempt(int num) {\n\n _current_attempt += num;\n\n}\n\n\n", "file_path": "centreon-engine/src/checkable.cc", "rank": 33, "score": 87067.7824297247 }, { "content": "enum checkable::state_type checkable::get_state_type() const {\n\n return _state_type;\n\n}\n\n\n\nvoid checkable::set_state_type(enum checkable::state_type state_type) {\n\n _state_type = state_type;\n\n}\n\n\n\ndouble checkable::get_percent_state_change() const {\n\n return _percent_state_change;\n\n}\n\n\n\nvoid checkable::set_percent_state_change(double percent_state_change) {\n\n _percent_state_change = percent_state_change;\n\n}\n\n\n\nbool checkable::get_obsess_over() const {\n\n return _obsess_over;\n\n}\n\n\n", "file_path": "centreon-engine/src/checkable.cc", "rank": 34, "score": 87067.7824297247 }, { "content": "enum host::host_state host::get_initial_state() const {\n\n return _initial_state;\n\n}\n\n\n\nvoid host::set_initial_state(enum host::host_state current_state) {\n\n _initial_state = current_state;\n\n}\n\n\n\nbool host::recovered() const {\n\n return _current_state == host::state_up;\n\n}\n\n\n\nint host::get_current_state_int() const {\n\n return static_cast<int>(_current_state);\n\n}\n\n\n\nstd::ostream& operator<<(std::ostream& os, host_map_unsafe const& obj) {\n\n for (host_map_unsafe::const_iterator it{obj.begin()}, end{obj.end()};\n\n it != end; ++it) {\n\n os << it->first;\n", "file_path": "centreon-engine/src/host.cc", "rank": 35, "score": 87067.7824297247 }, { "content": "enum host::host_state host::get_current_state() const {\n\n return _current_state;\n\n}\n\n\n\nvoid host::set_current_state(enum host::host_state current_state) {\n\n _current_state = current_state;\n\n}\n\n\n", "file_path": "centreon-engine/src/host.cc", "rank": 36, "score": 87067.7824297247 }, { "content": "enum host::host_state host::get_last_state() const {\n\n return _last_state;\n\n}\n\n\n\nvoid host::set_last_state(enum host::host_state last_state) {\n\n _last_state = last_state;\n\n}\n\n\n", "file_path": "centreon-engine/src/host.cc", "rank": 37, "score": 87067.7824297247 }, { "content": "enum service::service_state service::get_last_state() const {\n\n return _last_state;\n\n}\n\n\n\nvoid service::set_last_state(enum service::service_state last_state) {\n\n _last_state = last_state;\n\n}\n\n\n", "file_path": "centreon-engine/src/service.cc", "rank": 38, "score": 87067.7824297247 }, { "content": "enum service::service_state service::get_initial_state() const {\n\n return _initial_state;\n\n}\n\n\n\nvoid service::set_initial_state(enum service::service_state current_state) {\n\n _initial_state = current_state;\n\n}\n\n\n\nint service::get_process_performance_data(void) const {\n\n return _process_performance_data;\n\n}\n\n\n\nvoid service::set_process_performance_data(int perf_data) {\n\n _process_performance_data = perf_data;\n\n}\n\n\n\nbool service::get_check_flapping_recovery_notification(void) const {\n\n return _check_flapping_recovery_notification;\n\n}\n\n\n", "file_path": "centreon-engine/src/service.cc", "rank": 39, "score": 87067.7824297247 }, { "content": "enum service::service_state service::get_current_state() const {\n\n return _current_state;\n\n}\n\n\n\nvoid service::set_current_state(enum service::service_state current_state) {\n\n _current_state = current_state;\n\n}\n\n\n", "file_path": "centreon-engine/src/service.cc", "rank": 40, "score": 87067.7824297247 }, { "content": "enum host::host_state host::get_last_hard_state() const {\n\n return _last_hard_state;\n\n}\n\n\n\nvoid host::set_last_hard_state(enum host::host_state last_hard_state) {\n\n _last_hard_state = last_hard_state;\n\n}\n\n\n", "file_path": "centreon-engine/src/host.cc", "rank": 41, "score": 85883.74825613256 }, { "content": "enum service::service_state service::get_last_hard_state() const {\n\n return _last_hard_state;\n\n}\n\n\n\nvoid service::set_last_hard_state(enum service::service_state last_hard_state) {\n\n _last_hard_state = last_hard_state;\n\n}\n\n\n", "file_path": "centreon-engine/src/service.cc", "rank": 42, "score": 85883.74825613256 }, { "content": "--------------------------------------------------------------------------------\n\n-- Check if the desired index exists on the elasticsearch server\n\n-- @param socket the socket connected to the elasticsearch server\n\n--\n\n-- @return a boolean true on success, false otherwise.\n\n--------------------------------------------------------------------------------\n\nlocal function check_index(socket)\n\n -- Ask for the index\n\n socket:write('GET /centreon/_mapping?pretty HTTP/1.1\\r\\nHost: '\n\n .. elastic.address .. ':' .. elastic.port\n\n .. '\\r\\nAccept: */*\\r\\n\\r\\n')\n\n local answer = socket:read()\n\n if string.match(answer, \"HTTP/1.1 200 OK\") then\n\n return true\n\n end\n\n return false\n\nend\n\n\n", "file_path": "centreon-broker/lua/examples/elastic.lua", "rank": 43, "score": 85123.70913601277 }, { "content": "struct timeval get_broker_timestamp(struct timeval const* timestamp) {\n\n struct timeval tv;\n\n if (!timestamp)\n\n gettimeofday(&tv, NULL);\n\n else\n\n tv = *timestamp;\n\n return (tv);\n\n}\n\n}\n", "file_path": "centreon-engine/src/broker.cc", "rank": 44, "score": 84663.1501549785 }, { "content": "struct timeval get_broker_timestamp(struct timeval const* timestamp);\n\n\n\n#ifdef __cplusplus\n\n}\n\n#endif /* C++ */\n\n\n\n#endif /* !CCE_BROKER_HH */\n", "file_path": "centreon-engine/inc/com/centreon/engine/broker.hh", "rank": 45, "score": 81269.05736208949 }, { "content": "struct timeval get_broker_timestamp(struct timeval const* timestamp);\n\n\n\n#ifdef __cplusplus\n\n}\n\n#endif /* C++ */\n\n\n\n#endif /* !CCE_BROKER_HH */\n", "file_path": "centreon-broker/neb/inc/com/centreon/engine/broker.hh", "rank": 46, "score": 80236.15703212637 }, { "content": "--------------------------------------------------------------------------------\n", "file_path": "centreon-broker/lua/examples/elastic.lua", "rank": 47, "score": 78834.01219504356 }, { "content": "class bool_not : public bool_value {\n\n public:\n\n bool_not(bool_value::ptr val = bool_value::ptr());\n\n bool_not(bool_not const& right);\n\n ~bool_not();\n\n bool_not& operator=(bool_not const& right);\n\n bool child_has_update(computable* child, io::stream* visitor = NULL);\n\n void set_value(std::shared_ptr<bool_value>& value);\n\n double value_hard();\n\n double value_soft();\n\n bool state_known() const;\n\n bool in_downtime() const;\n\n\n\n private:\n\n void _internal_copy(bool_not const& right);\n\n\n\n bool_value::ptr _value;\n\n};\n\n} // namespace bam\n\n\n\nCCB_END()\n\n\n\n#endif // !CCB_BAM_BOOL_NOT_HH\n", "file_path": "centreon-broker/bam/inc/com/centreon/broker/bam/bool_not.hh", "rank": 48, "score": 74428.9726954854 }, { "content": "class bool_or : public bool_binary_operator {\n\n public:\n\n bool_or() = default;\n\n ~bool_or() noexcept override = default;\n\n bool_or(const bool_or&) = delete;\n\n bool_or& operator=(const bool_or&) = delete;\n\n double value_hard() override;\n\n double value_soft() override;\n\n};\n\n} // namespace bam\n\n\n\nCCB_END()\n\n\n\n#endif // !CCB_BAM_BOOL_OR_HH\n", "file_path": "centreon-broker/bam/inc/com/centreon/broker/bam/bool_or.hh", "rank": 49, "score": 73573.23899913211 }, { "content": "class bool_and : public bool_binary_operator {\n\n public:\n\n bool_and() = default;\n\n ~bool_and() noexcept = default;\n\n bool_and(const bool_and&) = delete;\n\n bool_and& operator=(const bool_and&) = delete;\n\n double value_hard() override;\n\n double value_soft() override;\n\n};\n\n} // namespace bam\n\n\n\nCCB_END()\n\n\n\n#endif // !CCB_BAM_BOOL_AND_HH\n", "file_path": "centreon-broker/bam/inc/com/centreon/broker/bam/bool_and.hh", "rank": 50, "score": 73573.23899913211 }, { "content": "class bool_more_than : public bool_binary_operator {\n\n const bool _strict;\n\n\n\n public:\n\n bool_more_than(bool strict = false);\n\n bool_more_than(bool_more_than const& right) = delete;\n\n ~bool_more_than() noexcept = default;\n\n bool_more_than& operator=(bool_more_than const&) = delete;\n\n double value_hard();\n\n double value_soft();\n\n};\n\n} // namespace bam\n\n\n\nCCB_END()\n\n\n\n#endif // !CCB_BAM_BOOL_MORE_THAN_HH\n", "file_path": "centreon-broker/bam/inc/com/centreon/broker/bam/bool_more_than.hh", "rank": 51, "score": 73573.23899913211 }, { "content": "#include <string.h>\n\n#include <sstream>\n\n#include \"com/centreon/engine/exceptions/error.hh\"\n\n\n\nusing namespace com::centreon::engine;\n\n\n\n/**\n\n * Check that long long insertion works properly in error.\n\n *\n\n * @return 0 on success.\n\n */\n\nint main() {\n\n // Insert long longs.\n\n error e;\n\n e << 74654646541515ll << 0ll << -1ll << 5465451141125787ll;\n\n\n\n#ifdef LLONG_MAX\n\n e << LLONG_MAX << 42ll << LLONG_MIN;\n\n#endif // !LLONG_MAX\n\n\n", "file_path": "centreon-engine/test/error/insert_long_long.cc", "rank": 52, "score": 73043.97381015694 }, { "content": "/*\n\n** Copyright 2011-2013 Merethis\n\n**\n\n** This file is part of Centreon Engine.\n\n**\n\n** Centreon Engine is free software: you can redistribute it and/or\n\n** modify it under the terms of the GNU General Public License version 2\n\n** as published by the Free Software Foundation.\n\n**\n\n** Centreon Engine is distributed in the hope that it will be useful,\n\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\n** General Public License for more details.\n\n**\n\n** You should have received a copy of the GNU General Public License\n\n** along with Centreon Engine. If not, see\n\n** <http://www.gnu.org/licenses/>.\n\n*/\n\n\n\n#include <limits.h>\n", "file_path": "centreon-engine/test/error/insert_long_long.cc", "rank": 53, "score": 73022.47569725543 }, { "content": " // Conversion reference.\n\n std::ostringstream oss;\n\n oss << 74654646541515ll << 0ll << -1ll << 5465451141125787ll;\n\n\n\n#ifdef LLONG_MAX\n\n oss << LLONG_MAX << 42ll << LLONG_MIN;\n\n#endif // !LLONG_MAX\n\n\n\n // Check.\n\n return (strcmp(oss.str().c_str(), e.what()));\n\n}\n", "file_path": "centreon-engine/test/error/insert_long_long.cc", "rank": 54, "score": 73013.57260448385 }, { "content": "class bool_constant : public bool_value {\n\n double _value;\n\n\n\n public:\n\n bool_constant(double value);\n\n bool_constant(bool_constant const& right);\n\n ~bool_constant() noexcept override = default;\n\n bool_constant& operator=(bool_constant const& right);\n\n bool child_has_update(computable* child, io::stream* visitor) override;\n\n double value_hard() override;\n\n double value_soft() override;\n\n bool state_known() const override;\n\n};\n\n} // namespace bam\n\n\n\nCCB_END()\n\n\n\n#endif // !CCB_BAM_BOOL_CONSTANT_HH\n", "file_path": "centreon-broker/bam/inc/com/centreon/broker/bam/bool_constant.hh", "rank": 55, "score": 72736.95892607553 }, { "content": "class bool_call : public bool_value {\n\n public:\n\n typedef std::shared_ptr<bool_call> ptr;\n\n\n\n bool_call(std::string const& name);\n\n bool_call(bool_call const& right);\n\n ~bool_call() noexcept override = default;\n\n bool_call& operator=(bool_call const& right);\n\n double value_hard() override;\n\n double value_soft() override;\n\n bool state_known() const override;\n\n std::string const& get_name() const;\n\n void set_expression(std::shared_ptr<bool_value> expression);\n\n bool child_has_update(computable* child,\n\n io::stream* visitor = nullptr) override;\n\n\n\n private:\n\n std::string _name;\n\n std::shared_ptr<bool_value> _expression;\n\n};\n\n} // namespace bam\n\n\n\nCCB_END()\n\n\n\n#endif // !CCB_BAM_BOOL_CALL_HH\n", "file_path": "centreon-broker/bam/inc/com/centreon/broker/bam/bool_call.hh", "rank": 56, "score": 72736.95892607553 }, { "content": "class bool_equal : public bool_binary_operator {\n\n public:\n\n bool_equal() = default;\n\n ~bool_equal() noexcept override = default;\n\n bool_equal(bool_equal const&) = delete;\n\n bool_equal& operator=(bool_equal const&) = delete;\n\n double value_hard() override;\n\n double value_soft() override;\n\n};\n\n} // namespace bam\n\n\n\nCCB_END()\n\n\n\n#endif // !CCB_BAM_BOOL_EQUAL_HH\n", "file_path": "centreon-broker/bam/inc/com/centreon/broker/bam/bool_equal.hh", "rank": 57, "score": 71919.4765651749 }, { "content": "class bool_operation : public bool_binary_operator {\n\n enum operation_type {\n\n addition,\n\n substraction,\n\n multiplication,\n\n division,\n\n modulo\n\n };\n\n const operation_type _type;\n\n\n\n public:\n\n bool_operation(std::string const& op);\n\n ~bool_operation() noexcept override = default;\n\n bool_operation(bool_operation const&) = delete;\n\n bool_operation& operator=(bool_operation const&) = delete;\n\n double value_hard() override;\n\n double value_soft() override;\n\n bool state_known() const override;\n\n};\n\n} // namespace bam\n\n\n\nCCB_END()\n\n\n\n#endif // !CCB_BAM_BOOL_OR_HH\n", "file_path": "centreon-broker/bam/inc/com/centreon/broker/bam/bool_operation.hh", "rank": 58, "score": 71919.4765651749 }, { "content": "class bool_xor : public bool_binary_operator {\n\n public:\n\n bool_xor() = default;\n\n ~bool_xor() noexcept = default;\n\n bool_xor(const bool_xor&) = delete;\n\n bool_xor& operator=(const bool_xor&) = delete;\n\n double value_hard() override;\n\n double value_soft() override;\n\n};\n\n} // namespace bam\n\n\n\nCCB_END()\n\n\n\n#endif // !CCB_BAM_BOOL_XOR_HH\n", "file_path": "centreon-broker/bam/inc/com/centreon/broker/bam/bool_xor.hh", "rank": 59, "score": 71919.4765651749 }, { "content": "class bool_less_than : public bool_binary_operator {\n\n const bool _strict;\n\n\n\n public:\n\n bool_less_than(bool strict = false);\n\n ~bool_less_than() noexcept = default;\n\n bool_less_than(bool_less_than const&) = delete;\n\n bool_less_than& operator=(bool_less_than const&) = delete;\n\n double value_hard();\n\n double value_soft();\n\n};\n\n} // namespace bam\n\n\n\nCCB_END()\n\n\n\n#endif // !CCB_BAM_BOOL_LESS_THAN_HH\n", "file_path": "centreon-broker/bam/inc/com/centreon/broker/bam/bool_less_than.hh", "rank": 60, "score": 71919.4765651749 }, { "content": "class bool_not_equal : public bool_binary_operator {\n\n public:\n\n bool_not_equal() = default;\n\n bool_not_equal(bool_not_equal const&) = delete;\n\n ~bool_not_equal() noexcept override = default;\n\n bool_not_equal& operator=(bool_not_equal const&) = delete;\n\n double value_hard() override;\n\n double value_soft() override;\n\n};\n\n} // namespace bam\n\n\n\nCCB_END()\n\n\n\n#endif // !CCB_BAM_BOOL_NOT_EQUAL_HH\n", "file_path": "centreon-broker/bam/inc/com/centreon/broker/bam/bool_not_equal.hh", "rank": 61, "score": 71919.4765651749 }, { "content": "class process_listener;\n", "file_path": "centreon-clib/inc/com/centreon/process.hh", "rank": 62, "score": 71669.72401028834 }, { "content": "class process_manager;\n\n\n\n/**\n\n * @class process process_posix.hh \"com/centreon/process_posix.hh\"\n\n * @brief Process execution class.\n\n *\n\n * Execute external process.\n\n */\n", "file_path": "centreon-clib/inc/com/centreon/process.hh", "rank": 63, "score": 71669.72401028834 }, { "content": "class bool_binary_operator : public bool_value {\n\n protected:\n\n std::shared_ptr<bool_value> _left;\n\n double _left_hard;\n\n double _left_soft;\n\n std::shared_ptr<bool_value> _right;\n\n double _right_hard;\n\n double _right_soft;\n\n bool _state_known;\n\n bool _in_downtime;\n\n\n\n public:\n\n typedef std::shared_ptr<bool_binary_operator> ptr;\n\n\n\n bool_binary_operator();\n\n bool_binary_operator(bool_binary_operator const& right);\n\n ~bool_binary_operator() noexcept override = default;\n\n bool_binary_operator& operator=(const bool_binary_operator&) = delete;\n\n bool child_has_update(computable* child,\n\n io::stream* visitor = nullptr) override;\n", "file_path": "centreon-broker/bam/inc/com/centreon/broker/bam/bool_binary_operator.hh", "rank": 64, "score": 71120.16516441459 }, { "content": "--\n", "file_path": "centreon-broker/test/mysql_v2/timeperiod_exceptions.sql", "rank": 65, "score": 70555.29682241511 }, { "content": "class process_listener {\n\n public:\n\n virtual ~process_listener() noexcept {}\n\n virtual void data_is_available(process& p) noexcept = 0;\n\n virtual void data_is_available_err(process& p) noexcept = 0;\n\n virtual void finished(process& p) noexcept = 0;\n\n};\n\n\n\nCC_END()\n\n\n\n#endif // !CC_PROCESS_LISTENER_HH\n", "file_path": "centreon-clib/inc/com/centreon/process_listener.hh", "rank": 66, "score": 70484.48677492717 }, { "content": "class process_listener;\n\n\n\n/**\n\n * @class process_manager process_manager_posix.hh\n\n *\"com/centreon/process_manager_posix.hh\"\n\n * @brief This class manage process.\n\n *\n\n * This class is a singleton, it manages processes by doing two things:\n\n * * waitpid() so it knows when a process is over.\n\n * * poll() so it knows when operations are available on fds.\n\n *\n\n * This singleton starts a thread running the main loop inside the _run()\n\n * method. This method is executed with a condition variable _running_cv and a\n\n * boolean _running. The constructor is released only when the boolean is set\n\n * to true, that is to say, the loop is really started.\n\n *\n\n * Once the loop is correctly started, the user can add to it processes. This\n\n * is done with the add() method. An important point is poll() and waitpid()\n\n * are called one after the other. And it is really better if no processes\n\n * are added between the two calls. So to avoid this case, processes are\n", "file_path": "centreon-clib/inc/com/centreon/process_manager.hh", "rank": 67, "score": 70484.48677492717 }, { "content": "class process_manager;\n\n\n\n/**\n\n * @class process process_posix.hh \"com/centreon/process_posix.hh\"\n\n * @brief Process execution class.\n\n *\n\n * Execute external process.\n\n */\n", "file_path": "centreon-broker/neb/inc/com/centreon/process.hh", "rank": 68, "score": 70484.48677492717 }, { "content": "class process_listener;\n", "file_path": "centreon-broker/neb/inc/com/centreon/process.hh", "rank": 69, "score": 70484.48677492717 }, { "content": "class process_manager {\n\n struct orphan {\n\n orphan(pid_t _pid = 0, int _status = 0) : pid(_pid), status(_status) {}\n\n pid_t pid;\n\n int status;\n\n };\n\n /**\n\n * A boolean set to true when file descriptors list needs to be updated.\n\n */\n\n std::atomic_bool _update;\n\n\n\n std::vector<pollfd> _fds;\n\n std::unordered_map<int32_t, process*> _processes_fd;\n\n std::atomic_bool _running;\n\n std::atomic_bool _finished;\n\n mutable std::mutex _running_m;\n\n mutable std::condition_variable _running_cv;\n\n std::thread _thread;\n\n\n\n std::deque<orphan> _orphans_pid;\n", "file_path": "centreon-clib/inc/com/centreon/process_manager.hh", "rank": 70, "score": 70484.48677492717 }, { "content": "class basic_exception : public std::exception {\n\n public:\n\n basic_exception(char const* message = \"\");\n\n basic_exception(basic_exception const& right);\n\n ~basic_exception() throw();\n\n basic_exception& operator=(basic_exception const& right);\n\n char const* what() const throw();\n\n\n\n private:\n\n basic_exception& _internal_copy(basic_exception const& right);\n\n\n\n char const* _message;\n\n};\n\n\n\nCCB_CONNECTOR_END()\n\n\n\n#endif // !CCB_CONNECTOR_BASIC_EXCEPTION\n", "file_path": "centreon-connector/test/centreon-benchmark/connector/inc/com/centreon/benchmark/connector/basic_exception.hh", "rank": 71, "score": 70342.97037342981 }, { "content": "class bool_service : public bool_value, public service_listener {\n\n const uint32_t _host_id;\n\n const uint32_t _service_id;\n\n short _state_hard;\n\n short _state_soft;\n\n bool _state_known;\n\n bool _in_downtime;\n\n\n\n public:\n\n typedef std::shared_ptr<bool_service> ptr;\n\n\n\n bool_service(uint32_t host_id, uint32_t service_id);\n\n ~bool_service() noexcept = default;\n\n bool_service(const bool_service&) = delete;\n\n bool_service& operator=(const bool_service&) = delete;\n\n bool child_has_update(computable* child,\n\n io::stream* visitor = nullptr) override;\n\n uint32_t get_host_id() const;\n\n uint32_t get_service_id() const;\n\n void service_update(std::shared_ptr<neb::service_status> const& status,\n", "file_path": "centreon-broker/bam/inc/com/centreon/broker/bam/bool_service.hh", "rank": 72, "score": 70338.42552834553 }, { "content": "class reader_exception : public com::centreon::exceptions::msg_fmt {\n\n public:\n\n reader_exception() = delete;\n\n\n\n template <typename... Args>\n\n explicit reader_exception(std::string const& str, const Args&... args)\n\n : msg_fmt(str, args...) {}\n\n reader_exception(const reader_exception&);\n\n ~reader_exception() noexcept {};\n\n};\n\n} // namespace configuration\n\n} // namespace bam\n\n\n\nCCB_END()\n\n\n\n#endif // !CCB_CONFIGURATION_READER_EXCEPTION_HH\n", "file_path": "centreon-broker/bam/inc/com/centreon/broker/bam/configuration/reader_exception.hh", "rank": 73, "score": 69578.17995219784 }, { "content": "class check_result {\n\n public:\n\n check_result() = delete;\n\n check_result(enum check_source object_check_type,\n\n notifier* notifier,\n\n enum checkable::check_type check_type,\n\n int check_options,\n\n bool reschedule_check,\n\n double latency,\n\n struct timeval start_time,\n\n struct timeval finish_time,\n\n bool early_timeout,\n\n bool exited_ok,\n\n int return_code,\n\n std::string const& output);\n\n check_result(check_result const&) = delete;\n\n check_result(check_result&&) = delete;\n\n check_result& operator=(check_result const&) = delete;\n\n\n\n enum check_source get_object_check_type() const;\n", "file_path": "centreon-engine/inc/com/centreon/engine/check_result.hh", "rank": 74, "score": 69419.53084291363 }, { "content": "--\n\n-- Configuration of timeperiod exceptions.\n\n--\n\nCREATE TABLE timeperiod_exceptions (\n\n exception_id int NOT NULL auto_increment,\n\n\n\n timeperiod_id int NOT NULL,\n\n days varchar(255) NOT NULL,\n\n timerange varchar(255) NOT NULL,\n\n\n\n PRIMARY KEY (exception_id),\n\n INDEX (timeperiod_id),\n\n FOREIGN KEY (timeperiod_id) REFERENCES timeperiod (tp_id)\n\n ON DELETE CASCADE\n\n) ENGINE=InnoDB CHARACTER SET utf8;\n", "file_path": "centreon-broker/test/mysql_v2/timeperiod_exceptions.sql", "rank": 75, "score": 69414.60358962428 }, { "content": "class process_listener;\n\n\n\n/**\n\n * @class process_manager process_manager_posix.hh\n\n *\"com/centreon/process_manager_posix.hh\"\n\n * @brief This class manage process.\n\n *\n\n * This class is a singleton, it manages processes. When it is instantiated, it\n\n *starts a thread running the main loop inside the _run() method. This _run\n\n *method is executed with a condition variable _running_cv and a boolean\n\n *running. The constructor is released only when the boolean is set to true,\n\n *that is to say, the loop is really started.\n\n *\n\n * Once the loop is correctly started, the user can add to it processes. This\n\n *is done with the add() method. Since the main loop is running while we add a\n\n *process, a mutex _lock_processes is used. During the add action,\n\n * * A map _processes_fd is completed, this one returns a process knowing its\n\n *output fd or its error fd.\n\n * * If the process is configured with a timeout, the table _processes_timeout\n\n *is also filled ; with it, from a timeout, we can get its process. It is a\n\n *multimap.\n\n * * It is also asked the file descriptors list to be updated by setting the\n\n *_update boolean to true.\n\n * * The process is stored in the _processes_pid table, here it is stored by\n\n *pid.\n\n */\n", "file_path": "centreon-broker/neb/inc/com/centreon/process_manager.hh", "rank": 76, "score": 69337.8134830523 }, { "content": "class process_manager {\n\n struct orphan {\n\n orphan(pid_t _pid = 0, int _status = 0) : pid(_pid), status(_status) {}\n\n pid_t pid;\n\n int status;\n\n };\n\n /**\n\n * A boolean set to true when file descriptors list needs to be updated.\n\n */\n\n std::atomic_bool _update;\n\n std::vector<pollfd> _fds;\n\n /**\n\n * Here is a boolean telling if the main loop is running or not. This variable\n\n * is set to true when the main loop starts and is set to false by the\n\n * process_manager destructor when we want to stop it.\n\n */\n\n std::atomic_bool _running;\n\n std::mutex _running_m;\n\n std::condition_variable _running_cv;\n\n std::thread _thread;\n", "file_path": "centreon-broker/neb/inc/com/centreon/process_manager.hh", "rank": 77, "score": 69337.8134830523 }, { "content": "class process_listener {\n\n public:\n\n virtual ~process_listener() noexcept {}\n\n virtual void data_is_available(process& p) noexcept = 0;\n\n virtual void data_is_available_err(process& p) noexcept = 0;\n\n virtual void finished(process& p) noexcept = 0;\n\n};\n\n\n\nCC_END()\n\n\n\n#endif // !CC_PROCESS_LISTENER_HH\n", "file_path": "centreon-broker/neb/inc/com/centreon/process_listener.hh", "rank": 78, "score": 69337.8134830523 }, { "content": "class check_result {\n\n public:\n\n check_result() = delete;\n\n check_result(enum check_source object_check_type,\n\n notifier* notifier,\n\n enum checkable::check_type check_type,\n\n int check_options,\n\n bool reschedule_check,\n\n double latency,\n\n struct timeval start_time,\n\n struct timeval finish_time,\n\n bool early_timeout,\n\n bool exited_ok,\n\n int return_code,\n\n std::string const& output);\n\n check_result(check_result const&) = delete;\n\n check_result(check_result&&) = delete;\n\n check_result& operator=(check_result const&) = delete;\n\n\n\n enum check_source get_object_check_type() const;\n", "file_path": "centreon-broker/neb/inc/com/centreon/engine/check_result.hh", "rank": 79, "score": 68308.26136357227 }, { "content": "--\n", "file_path": "centreon-broker/bam/postgresql_v3/mod_bam_reporting_timeperiods_exceptions.sql", "rank": 80, "score": 68296.39512680896 }, { "content": "--\n", "file_path": "centreon-broker/bam/mysql_v2/mod_bam_reporting_timeperiods_exceptions.sql", "rank": 81, "score": 68296.39512680896 }, { "content": "--\n", "file_path": "centreon-broker/bam/oracle_v2/mod_bam_reporting_timeperiods_exceptions.sql", "rank": 82, "score": 68296.39512680896 }, { "content": "class dimension_timeperiod_exception : public io::data {\n\n public:\n\n dimension_timeperiod_exception();\n\n dimension_timeperiod_exception(dimension_timeperiod_exception const& other);\n\n ~dimension_timeperiod_exception();\n\n dimension_timeperiod_exception& operator=(\n\n dimension_timeperiod_exception const& other);\n\n constexpr static uint32_t static_type() {\n\n return io::events::data_type<io::bam,\n\n bam::de_dimension_timeperiod_exception>::value;\n\n }\n\n\n\n std::string daterange;\n\n std::string timerange;\n\n uint32_t timeperiod_id;\n\n\n\n static mapping::entry const entries[];\n\n static io::event_info::event_operations const operations;\n\n\n\n private:\n\n void _internal_copy(dimension_timeperiod_exception const& other);\n\n};\n\n} // namespace bam\n\n\n\nCCB_END()\n\n\n\n#endif // !CCB_BAM_DIMENSION_TIMEPERIOD_EXCEPTION_HH\n", "file_path": "bbdo/bam/dimension_timeperiod_exception.hh", "rank": 83, "score": 68296.39512680896 }, { "content": "--\n", "file_path": "centreon-broker/bam/oracle_v3/mod_bam_reporting_timeperiods_exceptions.sql", "rank": 84, "score": 68296.39512680896 }, { "content": "class basic : public std::exception {\n\n public:\n\n basic();\n\n basic(char const* file, char const* function, int line);\n\n basic(basic const& other);\n\n virtual ~basic() throw();\n\n virtual basic& operator=(basic const& other);\n\n template <typename T>\n\n basic& operator<<(T t) {\n\n _buffer << t;\n\n return (*this);\n\n }\n\n virtual char const* what() const throw();\n\n\n\n private:\n\n void _internal_copy(basic const& other);\n\n\n\n misc::stringifier _buffer;\n\n};\n\n} // namespace exceptions\n", "file_path": "centreon-clib/inc/com/centreon/exceptions/basic.hh", "rank": 85, "score": 68296.39512680896 }, { "content": "--\n", "file_path": "centreon-broker/bam/mysql_v3/mod_bam_reporting_timeperiods_exceptions.sql", "rank": 86, "score": 68296.39512680896 }, { "content": "--\n", "file_path": "centreon-broker/bam/postgresql_v2/mod_bam_reporting_timeperiods_exceptions.sql", "rank": 87, "score": 68296.39512680896 }, { "content": "// Forward declaration.\n\nclass bool_value;\n\n\n\n/**\n\n * @class bool_not bool_not.hh \"com/centreon/broker/bam/bool_not.hh\"\n\n * @brief NOT boolean operator.\n\n *\n\n * In the context of a KPI computation, bool_not represents a logical\n\n * NOT on a bool_value.\n\n */\n", "file_path": "centreon-broker/bam/inc/com/centreon/broker/bam/bool_not.hh", "rank": 88, "score": 68291.98251053732 }, { "content": "class ProcessingTest : public ::testing::Test {\n\n public:\n\n void SetUp() override {\n\n try {\n\n config::applier::init(0, \"test_broker\");\n\n } catch (std::exception const& e) {\n\n (void)e;\n\n }\n\n\n\n std::shared_ptr<io::endpoint> endpoint =\n\n std::make_shared<temporary_endpoint>();\n\n _acceptor = std::make_unique<acceptor>(endpoint, \"temporary_endpoint\");\n\n }\n\n\n\n void TearDown() override {\n\n _acceptor.reset();\n\n config::applier::deinit();\n\n }\n\n\n\n protected:\n", "file_path": "centreon-broker/core/test/processing/acceptor.cc", "rank": 89, "score": 68227.85213712588 }, { "content": "class node_id {\n\n public:\n\n node_id();\n\n node_id(node_id const& obj);\n\n node_id& operator=(node_id const& obj);\n\n bool operator==(node_id const& other) const throw();\n\n explicit node_id(uint64_t host_id, uint64_t service_id = 0);\n\n bool operator<(node_id const& obj) const throw();\n\n bool operator!=(node_id const& obj) const throw();\n\n\n\n uint64_t get_host_id() const throw();\n\n uint64_t get_service_id() const throw();\n\n bool is_host() const throw();\n\n bool is_service() const throw();\n\n node_id to_host() const throw();\n\n bool empty() const throw();\n\n\n\n private:\n\n uint64_t _host_id;\n\n uint64_t _service_id;\n\n};\n\n} // namespace neb\n\n\n\nCCB_END()\n\n\n\nnamespace std {\n\ntemplate <>\n", "file_path": "centreon-broker/neb/inc/com/centreon/broker/neb/node_id.hh", "rank": 90, "score": 67250.98899905411 }, { "content": "class mysql_result {\n\n public:\n\n mysql_result(mysql_connection* parent, int statement = 0);\n\n mysql_result(mysql_connection* parent, MYSQL_RES* res);\n\n mysql_result(mysql_result&& other);\n\n ~mysql_result();\n\n mysql_result& operator=(mysql_result const& other);\n\n bool value_as_bool(int idx);\n\n float value_as_f32(int idx);\n\n double value_as_f64(int idx);\n\n int value_as_i32(int idx);\n\n std::string value_as_str(int idx);\n\n uint32_t value_as_u32(int idx);\n\n int64_t value_as_i64(int idx);\n\n uint64_t value_as_u64(int idx);\n\n bool value_is_null(int idx);\n\n bool is_empty() const;\n\n int get_rows_count() const;\n\n void set(MYSQL_RES* res);\n\n MYSQL_RES* get();\n", "file_path": "centreon-broker/core/inc/com/centreon/broker/database/mysql_result.hh", "rank": 91, "score": 67232.00977287172 }, { "content": "class error : public std::exception {\n\n template <typename T>\n\n void _insert_with_snprintf(T& t, char const* format);\n\n\n\n mutable char _buffer[4096];\n\n uint32_t _current;\n\n\n\n public:\n\n error() noexcept;\n\n error(char const* file, char const* function, int line) noexcept;\n\n error(error const& e) noexcept;\n\n ~error() throw() override;\n\n error& operator=(error const& e) noexcept;\n\n error& operator<<(char c) noexcept;\n\n error& operator<<(char const* str) noexcept;\n\n error& operator<<(int i) noexcept;\n\n error& operator<<(unsigned long u) noexcept;\n\n error& operator<<(unsigned int u) noexcept;\n\n error& operator<<(long l) noexcept;\n\n error& operator<<(long long ll) noexcept;\n", "file_path": "centreon-engine/inc/com/centreon/engine/exceptions/error.hh", "rank": 92, "score": 67220.33049821135 }, { "content": "class basic : public std::exception {\n\n public:\n\n basic();\n\n basic(char const* file, char const* function, int line);\n\n basic(basic const& other);\n\n virtual ~basic() throw();\n\n virtual basic& operator=(basic const& other);\n\n template <typename T>\n\n basic& operator<<(T t) {\n\n _buffer << t;\n\n return (*this);\n\n }\n\n virtual char const* what() const throw();\n\n\n\n private:\n\n void _internal_copy(basic const& other);\n\n\n\n misc::stringifier _buffer;\n\n};\n\n} // namespace exceptions\n", "file_path": "centreon-broker/neb/inc/com/centreon/exceptions/basic.hh", "rank": 93, "score": 67220.33049821135 }, { "content": "// Forward declaration.\n\nclass bool_value;\n\n\n\n/**\n\n * @class bool_expression bool_expression.hh\n\n * \"com/centreon/broker/bam/bool_expression.hh\"\n\n * @brief Boolean expression.\n\n *\n\n * Stores and entire boolean expression made of multiple boolean\n\n * operations and evaluate them to match the kpi interface.\n\n */\n", "file_path": "centreon-broker/bam/inc/com/centreon/broker/bam/bool_expression.hh", "rank": 94, "score": 67215.98740625764 }, { "content": "class interrupt : public std::exception {\n\n public:\n\n interrupt() = default;\n\n interrupt(const interrupt& other) : std::exception(other) {}\n\n virtual ~interrupt() noexcept = default;\n\n interrupt& operator=(const interrupt&) = delete;\n\n};\n\n} // namespace exceptions\n\n\n\nCCB_END()\n\n\n\n#endif // !CCB_EXCEPTIONS_INTERRUPT_HH\n", "file_path": "centreon-broker/core/inc/com/centreon/broker/exceptions/interrupt.hh", "rank": 95, "score": 66177.64842773552 }, { "content": "class error : public std::exception {\n\n template <typename T>\n\n void _insert_with_snprintf(T& t, char const* format);\n\n\n\n mutable char _buffer[4096];\n\n uint32_t _current;\n\n\n\n public:\n\n error() noexcept;\n\n error(char const* file, char const* function, int line) noexcept;\n\n error(error const& e) noexcept;\n\n ~error() throw() override;\n\n error& operator=(error const& e) noexcept;\n\n error& operator<<(char c) noexcept;\n\n error& operator<<(char const* str) noexcept;\n\n error& operator<<(int i) noexcept;\n\n error& operator<<(unsigned long u) noexcept;\n\n error& operator<<(unsigned int u) noexcept;\n\n error& operator<<(long l) noexcept;\n\n error& operator<<(long long ll) noexcept;\n", "file_path": "centreon-broker/neb/inc/com/centreon/engine/exceptions/error.hh", "rank": 96, "score": 66177.64842773552 }, { "content": "class bool_expression {\n\n public:\n\n bool_expression(uint32_t id = 0,\n\n std::string const& name = \"\",\n\n std::string const& expression = \"\",\n\n bool impact_if = false);\n\n bool_expression(bool_expression const& other);\n\n ~bool_expression();\n\n bool_expression& operator=(bool_expression const& other);\n\n bool operator==(bool_expression const& other) const;\n\n bool operator!=(bool_expression const& other) const;\n\n\n\n uint32_t get_id() const;\n\n std::string const& get_name() const;\n\n std::string const& get_expression() const;\n\n bool get_impact_if() const;\n\n\n\n void set_name(std::string const& name);\n\n void set_expression(std::string const& s);\n\n void set_id(uint32_t id);\n", "file_path": "centreon-broker/bam/inc/com/centreon/broker/bam/configuration/bool_expression.hh", "rank": 97, "score": 66173.37270325943 }, { "content": "class msg_fmt : public std::exception {\n\n const std::string _msg;\n\n\n\n public:\n\n template <typename... Args>\n\n explicit msg_fmt(const std::string& str, const Args&... args)\n\n : _msg(fmt::format(str, args...)) {}\n\n\n\n msg_fmt() = delete;\n\n msg_fmt& operator=(const msg_fmt&) = delete;\n\n const char* what() const noexcept final { return _msg.c_str(); }\n\n};\n\n} // namespace exceptions\n\nCC_END()\n\n#endif // !CC_EXCEPTIONS_MSG_FMT_HH\n", "file_path": "centreon-broker/neb/inc/com/centreon/exceptions/msg_fmt.hh", "rank": 98, "score": 65166.81921165864 }, { "content": "class bool_expression : public computable {\n\n uint32_t _id;\n\n std::shared_ptr<bool_value> _expression;\n\n bool _impact_if;\n\n\n\n public:\n\n bool_expression();\n\n bool_expression(bool_expression const& other) = delete;\n\n ~bool_expression() noexcept override = default;\n\n bool_expression& operator=(bool_expression const& other) = delete;\n\n bool child_has_update(computable* child,\n\n io::stream* visitor = nullptr) override;\n\n state get_state() const;\n\n bool state_known() const;\n\n void set_expression(std::shared_ptr<bool_value> const& expression);\n\n std::shared_ptr<bool_value> get_expression() const;\n\n void set_id(uint32_t id);\n\n void set_impact_if(bool impact_if);\n\n bool in_downtime() const;\n\n};\n\n} // namespace bam\n\n\n\nCCB_END()\n\n\n\n#endif // !CCB_BAM_BOOL_EXPRESSION_HH\n", "file_path": "centreon-broker/bam/inc/com/centreon/broker/bam/bool_expression.hh", "rank": 99, "score": 65162.608796653694 } ]
C++
core/indigo-core/molecule/src/molecule_inchi_utils.cpp
khyurri/Indigo
82f9ef9f43ca605f7265709e7a9256f1ff468d6c
#include "molecule/molecule_inchi_utils.h" #include "base_cpp/os_sync_wrapper.h" #include "molecule/elements.h" #include "molecule/molecule.h" #include "molecule/molecule_cis_trans.h" using namespace indigo; Array<int> MoleculeInChIUtils::_atom_lables_sorted; Array<int> MoleculeInChIUtils::_atom_lables_ranks; IMPL_ERROR(MoleculeInChIUtils, "InChI utility"); const Array<int>& MoleculeInChIUtils::getLexSortedAtomLables() { _ensureLabelsInitialized(); return _atom_lables_sorted; } const Array<int>& MoleculeInChIUtils::getLexSortedAtomLablesRanks() { _ensureLabelsInitialized(); return _atom_lables_ranks; } void MoleculeInChIUtils::_ensureLabelsInitialized() { if (_atom_lables_sorted.size() == 0) { static ThreadSafeStaticObj<OsLock> lock; OsLocker locker(lock.ref()); if (_atom_lables_sorted.size() == 0) _initializeAtomLabels(); } } void MoleculeInChIUtils::_initializeAtomLabels() { _atom_lables_sorted.reserve(ELEM_MAX); for (int i = ELEM_MIN; i < ELEM_MAX; i++) _atom_lables_sorted.push(i); _atom_lables_sorted.qsort(_compareAtomLabels, NULL); _atom_lables_ranks.resize(ELEM_MAX); _atom_lables_ranks.fffill(); for (int i = 0; i < _atom_lables_sorted.size(); i++) { int label = _atom_lables_sorted[i]; _atom_lables_ranks[label] = i; } } int MoleculeInChIUtils::_compareAtomLabels(int& label1, int& label2, void* context) { if (label1 == ELEM_C && label2 != ELEM_C) return -1; if (label1 != ELEM_C && label2 == ELEM_C) return 1; return strcmp(Element::toString(label1), Element::toString(label2)); } void MoleculeInChIUtils::stableSmallSort(Array<int>& indices, const Array<int>* ranks) { for (int i = 1; i < indices.size(); i++) { int i_value = indices[i]; int i_value_rank = i_value; if (ranks != NULL) i_value_rank = ranks->at(i_value); int j = i - 1; while (j >= 0) { int j_value_rank = indices[j]; if (ranks != NULL) j_value_rank = ranks->at(j_value_rank); if (i_value_rank >= j_value_rank) break; indices[j + 1] = indices[j]; j--; } indices[j + 1] = i_value; } } int MoleculeInChIUtils::compareHydrogens(int hyd1, int hyd2) { if (hyd1 == 0) hyd1 = 256; if (hyd2 == 0) hyd2 = 256; return hyd2 - hyd1; } int MoleculeInChIUtils::getParityInChI(Molecule& mol, int bond) { if (mol.cis_trans.getParity(bond) == 0) throw Error("Specified bond ins't stereogenic"); const Edge& edge = mol.getEdge(bond); const int* subst = mol.cis_trans.getSubstituents(bond); int max_first = std::max(subst[0], subst[1]); int max_second = std::max(subst[2], subst[3]); int value = MoleculeCisTrans::sameside(mol.getAtomXyz(edge.beg), mol.getAtomXyz(edge.end), mol.getAtomXyz(max_first), mol.getAtomXyz(max_second)); if (value > 0) return -1; return 1; }
#include "molecule/molecule_inchi_utils.h" #include "base_cpp/os_sync_wrapper.h" #include "molecule/elements.h" #include "molecule/molecule.h" #include "molecule/molecule_cis_trans.h" using namespace indigo; Array<int> MoleculeInChIUtils::_atom_lables_sorted; Array<int> MoleculeInChIUtils::_atom_lables_ranks; IMPL_ERROR(MoleculeInChIUtils, "InChI utility"); const Array<int>& MoleculeInChIUtils::getLexSortedAtomLables() { _ensureLabelsInitialized(); return _atom_lables_sorted; } const Array<int>& MoleculeInChIUtils::getLexSortedAtomLablesRanks() { _ensureLabelsInitialized(); return _atom_lables_ranks; } void MoleculeInChIUtils::_ensur
_initializeAtomLabels(); } } void MoleculeInChIUtils::_initializeAtomLabels() { _atom_lables_sorted.reserve(ELEM_MAX); for (int i = ELEM_MIN; i < ELEM_MAX; i++) _atom_lables_sorted.push(i); _atom_lables_sorted.qsort(_compareAtomLabels, NULL); _atom_lables_ranks.resize(ELEM_MAX); _atom_lables_ranks.fffill(); for (int i = 0; i < _atom_lables_sorted.size(); i++) { int label = _atom_lables_sorted[i]; _atom_lables_ranks[label] = i; } } int MoleculeInChIUtils::_compareAtomLabels(int& label1, int& label2, void* context) { if (label1 == ELEM_C && label2 != ELEM_C) return -1; if (label1 != ELEM_C && label2 == ELEM_C) return 1; return strcmp(Element::toString(label1), Element::toString(label2)); } void MoleculeInChIUtils::stableSmallSort(Array<int>& indices, const Array<int>* ranks) { for (int i = 1; i < indices.size(); i++) { int i_value = indices[i]; int i_value_rank = i_value; if (ranks != NULL) i_value_rank = ranks->at(i_value); int j = i - 1; while (j >= 0) { int j_value_rank = indices[j]; if (ranks != NULL) j_value_rank = ranks->at(j_value_rank); if (i_value_rank >= j_value_rank) break; indices[j + 1] = indices[j]; j--; } indices[j + 1] = i_value; } } int MoleculeInChIUtils::compareHydrogens(int hyd1, int hyd2) { if (hyd1 == 0) hyd1 = 256; if (hyd2 == 0) hyd2 = 256; return hyd2 - hyd1; } int MoleculeInChIUtils::getParityInChI(Molecule& mol, int bond) { if (mol.cis_trans.getParity(bond) == 0) throw Error("Specified bond ins't stereogenic"); const Edge& edge = mol.getEdge(bond); const int* subst = mol.cis_trans.getSubstituents(bond); int max_first = std::max(subst[0], subst[1]); int max_second = std::max(subst[2], subst[3]); int value = MoleculeCisTrans::sameside(mol.getAtomXyz(edge.beg), mol.getAtomXyz(edge.end), mol.getAtomXyz(max_first), mol.getAtomXyz(max_second)); if (value > 0) return -1; return 1; }
eLabelsInitialized() { if (_atom_lables_sorted.size() == 0) { static ThreadSafeStaticObj<OsLock> lock; OsLocker locker(lock.ref()); if (_atom_lables_sorted.size() == 0)
function_block-random_span
[ { "content": " final Indigo indigo;\n", "file_path": "api/java/indigo-inchi/src/main/java/com/epam/indigo/IndigoInchi.java", "rank": 0, "score": 207685.95766331634 }, { "content": "char *inchi__strnset( char *s, int val, size_t length )\n\n{\n\n char *ps = s;\n\n while (length-- && *ps)\n\n *ps++ = (char)val;\n\n return s;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 1, "score": 186592.51421077052 }, { "content": "void inchi_free(void *p)\n\n{\n\n if(p) {\n\n free(p); /*added check if zero*/\n\n }\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 2, "score": 186592.51421077052 }, { "content": "void *inchi_calloc(size_t c, size_t n)\n\n{\n\n return calloc(c,n);\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 3, "score": 186592.51421077052 }, { "content": "int inchi_stricmp( const char *s1, const char *s2 )\n\n{\n\n while ( *s1 )\n\n {\n\n if ( *s1 == *s2 ||\n\n __MYTOLOWER( (int)*s1 ) == __MYTOLOWER( (int)*s2 ))\n\n {\n\n s1 ++;\n\n s2 ++;\n\n }\n\n else\n\n {\n\n return\n\n __MYTOLOWER( (int)*s1 ) - __MYTOLOWER( (int)*s2 );\n\n }\n\n }\n\n\n\n if ( *s2 )\n\n return -1;\n\n\n\n return 0;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 4, "score": 186592.51421077052 }, { "content": "char *inchi__strdup( const char *string )\n\n{\n\n char *p = NULL;\n\n if ( string )\n\n {\n\n size_t length = strlen( string );\n\n p = (char *) inchi_malloc( length + 1 );\n\n if ( p )\n\n {\n\n strcpy( p, string );\n\n }\n\n }\n\n return p;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 5, "score": 186592.51421077052 }, { "content": "void *inchi_malloc(size_t c)\n\n{\n\n return malloc(c);\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 6, "score": 186592.51421077052 }, { "content": "int inchi_memicmp( const void * p1, const void * p2, size_t length )\n\n{\n\n const U_CHAR *s1 = (const U_CHAR*)p1;\n\n const U_CHAR *s2 = (const U_CHAR*)p2;\n\n while ( length-- )\n\n {\n\n if ( *s1 == *s2 ||\n\n __MYTOLOWER( (int)*s1 ) == __MYTOLOWER( (int)*s2 ))\n\n {\n\n s1 ++;\n\n s2 ++;\n\n }\n\n else\n\n {\n\n return\n\n __MYTOLOWER( (int)*s1 ) - __MYTOLOWER( (int)*s2 );\n\n }\n\n }\n\n\n\n return 0;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 7, "score": 186592.51421077052 }, { "content": "namespace indigo\n\n{\n\n\n\n // Whole InChI component with component molecule and InChI layers\n\n struct MoleculeInChICompoment\n\n {\n\n // Canonicaly-ordered molecule\n\n Molecule mol;\n\n\n\n // Layers\n\n MoleculeInChILayers::MainLayerFormula main_layer_formula;\n\n MoleculeInChILayers::MainLayerConnections main_layer_connections;\n\n MoleculeInChILayers::HydrogensLayer hydrogens_layer;\n\n\n\n MoleculeInChILayers::CisTransStereochemistryLayer cistrans_stereochemistry_layer;\n\n MoleculeInChILayers::TetrahedralStereochemistryLayer tetra_stereochemistry_layer;\n\n\n\n void construct(Molecule& original_component);\n\n\n\n void clear()\n\n {\n\n }\n\n\n\n void getCanonicalOrdering(Molecule& source_mol, Array<int>& mapping);\n\n static int cmpVertex(Graph& graph, int v1, int v2, const void* context);\n\n\n\n private:\n\n void _getCanonicalMolecule(Molecule& source_mol, Molecule& cano_mol);\n\n\n\n static int _cmpVertex(Graph& graph, int v1, int v2, const void* context);\n\n static int _cmpVertexStereo(Molecule& graph, int v1, int v2, const void* context);\n\n static int _cmpMappings(Graph& graph, const Array<int>& mapping1, const Array<int>& mapping2, const void* context);\n\n\n\n static bool _checkAutomorphism(Graph& graph, const Array<int>& mapping, const void* context);\n", "file_path": "core/indigo-core/molecule/molecule_inchi_component.h", "rank": 8, "score": 185841.8488344648 }, { "content": " // Utility class for InChI code creation\n\n class MoleculeInChIUtils\n\n {\n\n public:\n\n // Helpful structure with mappings\n\n struct Mapping\n\n {\n\n Mapping(const Array<int>& _mapping, const Array<int>& _inv_mapping) : mapping(_mapping), inv_mapping(_inv_mapping)\n\n {\n\n }\n\n\n\n const Array<int>&mapping, &inv_mapping;\n\n };\n\n\n\n // Returns indices for lexicographically-sorted atom labels\n\n // with exception that the first atom is Carbon\n\n static const Array<int>& getLexSortedAtomLables();\n\n // Returns inverse permutation for getLexSortedLables\n\n static const Array<int>& getLexSortedAtomLablesRanks();\n\n\n\n // Stable sort for small integer arrays with possibility to use array with ranks\n", "file_path": "core/indigo-core/molecule/molecule_inchi_utils.h", "rank": 9, "score": 185813.63992604223 }, { "content": "void extract_inchi_substring(char ** buf, const char *str, size_t slen)\n\n{\n\nsize_t i;\n\nconst char *p;\n\nchar pp;\n\n\n\n\n\n *buf = NULL;\n\n\n\n if (str==NULL)\n\n return;\n\n if (strlen(str)<1)\n\n return;\n\n\n\n p = strstr(str, \"InChI=\");\n\n if (NULL==p)\n\n return;\n\n\n\n for (i=0; i<slen; i++)\n\n {\n\n pp = p[i];\n\n\n\n if (pp >= 'A' && pp <='Z') continue;\n\n if (pp >= 'a' && pp <='z') continue;\n\n if (pp >= '0' && pp <='9') continue;\n\n switch ( pp )\n\n {\n\n case '(':\n\n case ')':\n\n case '*':\n\n case '+':\n\n case ',':\n\n case '-':\n\n case '.':\n\n case '/':\n\n case ';':\n\n case '=':\n\n case '?':\n\n case '@': continue;\n\n\n\n default: break;\n\n }\n\n\n\n break;\n\n }\n\n\n\n *buf = (char*) inchi_calloc(i+1, sizeof(char));\n\n memcpy(*buf, p, i);\n\n (*buf)[i] = '\\0';\n\n\n\n return;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 10, "score": 183565.71722257303 }, { "content": " Vertex bUsed; /* indicates the charge edge belongs to already processed atom */\n", "file_path": "third_party/inchi/INCHI_BASE/src/ichirvr1.c", "rank": 11, "score": 182450.14947971934 }, { "content": " double dAtMass;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 12, "score": 182244.11872953398 }, { "content": "int mystrncpy(char *target,const char *source,unsigned maxlen)\n\n{\n\nconst char *p;\n\nunsigned len;\n\n\n\n if (target==NULL || maxlen == 0 || source == NULL)\n\n return 0;\n\n\n\n if ( p = (const char*)memchr(source, 0, maxlen) )\n\n { /* maxlen does not include the found zero termination */\n\n len = (int) (p-source);\n\n }\n\n else\n\n { /* reduced length does not include one more byte for zero termination */\n\n len = maxlen-1;\n\n }\n\n\n\n if ( len )\n\n memmove( target, source, len );\n\n\n\n memset( target+len, 0, maxlen-len); /* zero termination */\n\n\n\n return 1;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 13, "score": 182242.108444821 }, { "content": "char* lrtrim( char *p, int* nLen )\n\n{\n\nint i, len=0;\n\n\n\n if ( p && (len = (int) strlen( p )) )\n\n {\n\n for ( i = 0; i < len && isascii( p[i] ) && isspace( p[i] ); i++ )\n\n ;\n\n if ( i )\n\n (memmove)( p, p+i, (len -= i)+1 );\n\n for ( ; 0 < len && isascii( p[len-1] ) && isspace( p[len-1] ); len--)\n\n ;\n\n p[len] = '\\0';\n\n }\n\n\n\n if ( nLen )\n\n *nLen = len;\n\n\n\n return p;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 14, "score": 182236.1604841529 }, { "content": " int nType;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 15, "score": 182236.1604841529 }, { "content": "AT_NUMB *is_in_the_list( AT_NUMB *pathAtom, AT_NUMB nNextAtom, int nPathLen )\n\n{\n\n for ( ; nPathLen && *pathAtom != nNextAtom; nPathLen--, pathAtom++ )\n\n ;\n\n return nPathLen? pathAtom : NULL;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 16, "score": 182236.1604841529 }, { "content": "int *is_in_the_ilist( int *pathAtom, int nNextAtom, int nPathLen )\n\n{\n\n for ( ; nPathLen && *pathAtom != nNextAtom; nPathLen--, pathAtom++ )\n\n ;\n\n return nPathLen? pathAtom : NULL;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 17, "score": 182236.16048415293 }, { "content": " int nAtMass;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 18, "score": 182236.16048415293 }, { "content": " S_CHAR cValence[NUM_ATOM_CHARGES][MAX_NUM_VALENCES];\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 19, "score": 182236.16048415293 }, { "content": " DLLEXPORT float length() const;\n", "file_path": "core/indigo-core/common/math/algebra.h", "rank": 20, "score": 182234.32901087354 }, { "content": " DLLEXPORT static void projectZ(Vec2f& v2, const Vec3f& v3);\n", "file_path": "core/indigo-core/common/math/algebra.h", "rank": 21, "score": 182225.15492851613 }, { "content": "/****************************************************************************\n\n * Copyright (C) from 2009 to Present EPAM Systems.\n\n *\n\n * This file is part of Indigo toolkit.\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n ***************************************************************************/\n\n\n\n#ifndef __molecule_inchi_utils_h__\n\n#define __molecule_inchi_utils_h__\n\n\n\n#include \"base_cpp/array.h\"\n\n#include \"base_cpp/exception.h\"\n\n\n\nnamespace indigo\n\n{\n\n\n", "file_path": "core/indigo-core/molecule/molecule_inchi_utils.h", "rank": 22, "score": 182207.7541813237 }, { "content": " // Note: it is better to add stable sort method in Array and\n\n // modify qsort (and other stable sort) to accept any comparators.\n\n static void stableSmallSort(Array<int>& indices, const Array<int>* ranks);\n\n\n\n // Compare atoms with hydrogens: C < CH4 < CH3 < CH2 < CH\n\n static int compareHydrogens(int hyd1, int hyd2);\n\n\n\n // Get parity according to InChI standart\n\n static int getParityInChI(Molecule& mol, int bond);\n\n\n\n DECL_ERROR;\n\n\n\n private:\n\n static void _ensureLabelsInitialized();\n\n static void _initializeAtomLabels();\n\n\n\n static int _compareAtomLabels(int& label1, int& label2, void* context);\n\n\n\n static Array<int> _atom_lables_sorted;\n\n static Array<int> _atom_lables_ranks;\n\n };\n\n\n\n} // namespace indigo\n\n\n\n#endif // __molecule_inchi_utils_h__\n", "file_path": "core/indigo-core/molecule/molecule_inchi_utils.h", "rank": 23, "score": 182198.09191674122 }, { "content": " int used; /* current number of objects */\n", "file_path": "third_party/inchi/INCHI_BASE/src/mol_fmt.h", "rank": 24, "score": 179106.821269317 }, { "content": " int bUseMulipliers;\n", "file_path": "third_party/inchi/INCHI_BASE/src/ichimain.h", "rank": 25, "score": 179106.82126931698 }, { "content": " int nUsedLength;\n", "file_path": "third_party/inchi/INCHI_BASE/src/mode.h", "rank": 26, "score": 179106.82126931698 }, { "content": " int nNormAtMass;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 27, "score": 178904.29667191204 }, { "content": "int is_ilist_inside( int *ilist, int nlist, int *ilist2, int nlist2 )\n\n{\n\n int k;\n\n for (k=0; k<nlist; k++)\n\n {\n\n if ( !is_in_the_ilist( ilist2, ilist[k], nlist2 ) )\n\n return 0;\n\n }\n\n return 1;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 28, "score": 178904.28342002776 }, { "content": "int normalize_string( char* name )\n\n{\n\nint i, len, n;\n\n\n\n len = (int)strlen(name);\n\n\n\n for ( i = 0, n = 0; i < len; i++ )\n\n {\n\n if ( isspace( UCINT name[i] ) /*|| !isprint( UCINT name[i] )*/ )\n\n {\n\n name[i] = ' '; /* exterminate tabs !!! */\n\n n++;\n\n }\n\n else\n\n {\n\n if ( n > 0 )\n\n {\n\n memmove( (void*) &name[i-n], (void*) &name[i], len-i+1 );\n\n i -= n;\n\n len -= n;\n\n }\n\n n = -1;\n\n }\n\n }\n\n if ( n == len ) /* empty line */\n\n name[len=0] = '\\0';\n\n else if ( ++n && n <= len )\n\n {\n\n len -= n;\n\n name[len] = '\\0';\n\n }\n\n\n\n return len;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 29, "score": 178897.41710981925 }, { "content": "int has_other_ion_neigh( inp_ATOM *at,\n\n int iat,\n\n int iat_ion_neigh,\n\n const char *el,\n\n int el_len )\n\n{\n\nint charge = at[iat_ion_neigh].charge;\n\nint i, neigh;\n\n\n\n for ( i = 0; i < at[iat].valence; i ++ )\n\n {\n\n neigh = at[iat].neighbor[i];\n\n\n\n if ( neigh != iat_ion_neigh && at[neigh].charge == charge &&\n\n NULL != memchr( el, at[neigh].el_number, el_len ) )\n\n {\n\n return 1;\n\n }\n\n }\n\n\n\n return 0;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 30, "score": 178897.41710981925 }, { "content": "int is_matching_any_delim( char c, char* delims )\n\n{\n\n int ic = UCINT c;\n\n while ( *delims )\n\n {\n\n if ( ic == *delims )\n\n return 1;\n\n delims++;\n\n }\n\n return 0;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 31, "score": 178897.41710981925 }, { "content": "const ELDATA ElData[] =\n\n{\n\n/* avg norm El No -------- Valence(s) of an ion or neutral atom -------------*/\n\n/* mw mass exact mw type neg H -2 -1 0 +1 +2 */\n\n{ \"H\", 1, 1, 1.007825035, 0 , 21, 0, {{0,}, {0,}, {1,}, {0,}, {0,} }},\n\n{ \"D\", 2, 2, 2.014101778, 0 , 21, 0, {{0,}, {0,}, {1,}, {0,}, {0,} }},\n\n{ \"T\", 3, 3, 3.016049268, 0 , 21, 0, {{0,}, {0,}, {1,}, {0,}, {0,} }},\n\n{ \"He\", 4, 4, 4.002600000, 0 , 0, 0, {{0,}, {0,}, {0,}, {0,}, {0,} }},\n\n{ \"Li\", 7, 7, 7.016000000, METAL , 10, 0, {{0,}, {0,}, {1,}, {0,}, {0,} }},\n\n{ \"Be\", 9, 9, 9.012180000, METAL , 15, 0, {{0,}, {0,}, {2,}, {1,}, {0,} }},\n\n{ \"B\", 11, 11, 11.009300000, 0 , 20, 0, {{3,}, {4,}, {3,}, {2,}, {1,} }},\n\n{ \"C\", 12, 12, 12.000000000, 0 , 25, 0, {{2,}, {3,}, {4,}, {3,}, {2,} }},\n\n{ \"N\", 14, 14, 14.003074000, 0 , 30, 0, {{1,}, {2,}, {3,5}, {4,}, {3,} }},\n\n{ \"O\", 16, 16, 15.994914630, 0 , 35, 0, {{0,}, {1,}, {2,}, {3,5,}, {4,} }},\n\n{ \"F\", 19, 19, 18.998403220, 0 , 40, 0, {{0,}, {0,}, {1,}, {2,}, {3,5} }},\n\n{ \"Ne\", 20, 20, 19.992440000, 0 , 0, 0, {{0,}, {0,}, {0,}, {0,}, {0,} }},\n\n{ \"Na\", 23, 23, 22.989770000, METAL , 9, 0, {{0,}, {0,}, {1,}, {0,}, {0,} }},\n\n{ \"Mg\", 24, 24, 23.985000000, METAL , 12, 0, {{0,}, {0,}, {2,}, {1,}, {0,} }},\n\n{ \"Al\", 27, 27, 26.981540000, METAL , 15, 0, {{3,5,}, {4,}, {3,}, {2,}, {1,} }},\n\n{ \"Si\", 28, 28, 27.976927100, 0 , 18, 0, {{2,}, {3,5}, {4,}, {3,}, {2,} }},\n\n{ \"P\", 31, 31, 30.973762000, 0 , 21, 0, {{1,3,5,7,}, {2,4,6,}, {3,5,}, {4,}, {3,} }},\n\n{ \"S\", 32, 32, 31.972070700, 0 , 25, 0, {{0,}, {1,3,5,7,}, {2,4,6}, {3,5,}, {4,} }},\n\n{ \"Cl\", 35, 35, 34.968852730, 0 , 30, 0, {{0,}, {0,}, {1,3,5,7}, {2,4,6}, {3,5,} }},\n\n{ \"Ar\", 40, 40, 39.962400000, 0 , 0, 0, {{0,}, {0,}, {0,}, {0,}, {0,} }},\n\n{ \"K\", 39, 39, 38.963700000, METAL , 8, 0, {{0,}, {0,}, {1,}, {0,}, {0,} }},\n\n{ \"Ca\", 40, 40, 39.962600000, METAL , 10, 0, {{0,}, {0,}, {2,}, {1,}, {0,} }},\n\n{ \"Sc\", 45, 45, 44.955910000, METAL , 13, 1, {{0,}, {0,}, {3,}, {0,}, {0,} }},\n\n{ \"Ti\", 48, 48, 47.947950000, METAL , 15, 1, {{0,}, {0,}, {3,4}, {0,}, {0,} }},\n\n{ \"V\", 51, 51, 50.943960000, METAL , 16, 1, {{0,}, {0,}, {2,3,4,5,}, {0,}, {0,} }},\n\n{ \"Cr\", 52, 52, 51.940500000, METAL , 16, 1, {{0,}, {0,}, {2,3,6,}, {0,}, {0,} }},\n\n{ \"Mn\", 55, 55, 54.938050000, METAL2, 15, 1, {{0,}, {0,}, {2,3,4,6,}, {0,}, {0,} }},\n\n{ \"Fe\", 56, 56, 55.934900000, METAL2, 18, 1, {{0,}, {0,}, {2,3,4,6,}, {0,}, {0,} }},\n\n{ \"Co\", 59, 59, 58.933200000, METAL2, 18, 1, {{0,}, {0,}, {2,3,}, {0,}, {0,} }},\n\n{ \"Ni\", 59, 58, 57.935300000, METAL2, 18, 1, {{0,}, {0,}, {2,3,}, {0,}, {0,} }},\n\n{ \"Cu\", 64, 63, 62.929600000, METAL , 19, 1, {{0,}, {0,}, {1,2,}, {0,}, {0,} }},\n\n{ \"Zn\", 65, 64, 63.929147000, METAL , 16, 1, {{0,}, {0,}, {2,}, {0,}, {0,} }},\n\n{ \"Ga\", 70, 69, 68.925600000, METAL , 18, 0, {{3,5,}, {4,}, {3,}, {0,}, {1,} }},\n\n{ \"Ge\", 73, 74, 73.921177400, 0 , 18, 0, {{2,4,6,}, {3,5,}, {4,}, {3,}, {0,} }},\n\n{ \"As\", 75, 75, 74.921594200, 0 , 20, 0, {{1,3,5,7,}, {2,4,6,}, {3,5,}, {4,}, {3,} }},\n\n{ \"Se\", 79, 80, 79.916519600, 0 , 24, 0, {{0,}, {1,3,5,7,}, {2,4,6,}, {3,5,}, {4,} }},\n\n{ \"Br\", 80, 79, 78.918336100, 0 , 28, 0, {{0,}, {0,}, {1,3,5,7,}, {2,4,6,}, {3,5,} }},\n\n{ \"Kr\", 84, 84, 83.911500000, 0 , 0, 0, {{0,}, {0,}, {0,}, {0,}, {0,} }},\n\n{ \"Rb\", 85, 85, 84.911800000, METAL , 8, 0, {{0,}, {0,}, {1,}, {0,}, {0,} }},\n\n{ \"Sr\", 88, 88, 87.905600000, METAL , 10, 0, {{0,}, {0,}, {2,}, {1,}, {0,} }},\n\n{ \"Y\", 89, 89, 88.905860000, METAL , 12, 1, {{0,}, {0,}, {3,}, {0,}, {0,} }},\n\n{ \"Zr\", 91, 90, 89.904700000, METAL , 14, 1, {{0,}, {0,}, {4,}, {0,}, {0,} }},\n\n{ \"Nb\", 93, 93, 92.906400000, METAL , 16, 1, {{0,}, {0,}, {3,5,}, {0,}, {0,} }},\n\n{ \"Mo\", 96, 98, 97.905400000, METAL , 18, 1, {{0,}, {0,}, {3,4,5,6,}, {0,}, {0,} }},\n\n{ \"Tc\", 98, 98, 97.907200000, METAL , 19, 1, {{0,}, {0,}, {7,}, {0,}, {0,} }},\n\n{ \"Ru\", 101, 102, 101.904300000, METAL , 22, 1, {{0,}, {0,}, {2,3,4,6,}, {0,}, {0,} }},\n\n{ \"Rh\", 103, 103, 102.905500000, METAL , 22, 1, {{0,}, {0,}, {2,3,4,}, {0,}, {0,} }},\n\n{ \"Pd\", 106, 106, 105.903500000, METAL , 22, 1, {{0,}, {0,}, {2,4,}, {0,}, {0,} }},\n\n{ \"Ag\", 108, 107, 106.905100000, METAL , 19, 1, {{0,}, {0,}, {1,}, {0,}, {0,} }},\n\n{ \"Cd\", 112, 114, 113.903400000, METAL , 17, 1, {{0,}, {0,}, {2,}, {0,}, {0,} }},\n\n{ \"In\", 115, 115, 114.903900000, METAL , 17, 0, {{3,5,}, {2,4,}, {3,}, {0,}, {1,} }},\n\n{ \"Sn\", 119, 120, 119.902200000, METAL2, 18, 0, {{2,4,6,}, {3,5}, {2,4,}, {3,}, {0,} }},\n\n{ \"Sb\", 122, 121, 120.903800000, METAL, 19, 0, {{1,3,5,7,}, {2,4,6,}, {3,5,}, {2,4,}, {3,} }},\n\n{ \"Te\", 128, 130, 129.906200000, 0 , 21, 0, {{0,}, {1,3,5,7,}, {2,4,6,}, {3,5,}, {2,4,} }},\n\n{ \"I\", 127, 127, 126.904500000, 0 , 25, 0, {{0,}, {0,}, {1,3,5,7,}, {2,4,6}, {3,5,} }},\n\n{ \"Xe\", 131, 132, 131.904100000, 0 , 0, 0, {{0,}, {0,}, {0,}, {0,}, {0,} }},\n\n{ \"Cs\", 133, 133, 132.905430000, METAL , 7, 0, {{0,}, {0,}, {1,}, {0,}, {0,} }},\n\n{ \"Ba\", 137, 138, 137.905200000, METAL , 9, 0, {{0,}, {0,}, {2,}, {1,}, {0,} }},\n\n{ \"La\", 139, 139, 138.906360000, METAL , 11, 1, {{0,}, {0,}, {3,}, {0,}, {0,} }},\n\n{ \"Ce\", 140, 140, 139.905400000, METAL2, 0, 1, {{0,}, {0,}, {3,4,}, {0,}, {0,} }},\n\n{ \"Pr\", 141, 141, 140.907660000, METAL2, 0, 1, {{0,}, {0,}, {3,4,}, {0,}, {0,} }},\n\n{ \"Nd\", 144, 142, 141.907719000, METAL , 0, 1, {{0,}, {0,}, {3,}, {0,}, {0,} }},\n\n{ \"Pm\", 145, 145, 144.912800000, METAL , 0, 1, {{0,}, {0,}, {3,}, {0,}, {0,} }},\n\n{ \"Sm\", 150, 152, 151.919700000, METAL2, 0, 1, {{0,}, {0,}, {2,3,}, {0,}, {0,} }},\n\n{ \"Eu\", 152, 153, 152.921200000, METAL2, 0, 1, {{0,}, {0,}, {2,3,}, {0,}, {0,} }},\n\n{ \"Gd\", 157, 158, 157.924099000, METAL , 0, 1, {{0,}, {0,}, {3,}, {0,}, {0,} }},\n\n{ \"Tb\", 159, 159, 158.925350000, METAL2, 0, 1, {{0,}, {0,}, {3,4,}, {0,}, {0,} }},\n\n{ \"Dy\", 163, 164, 163.929200000, METAL , 0, 1, {{0,}, {0,}, {3,}, {0,}, {0,} }}, /* mw rounding uncertain */\n\n{ \"Ho\", 165, 165, 164.930300000, METAL , 0, 1, {{0,}, {0,}, {3,}, {0,}, {0,} }},\n\n{ \"Er\", 167, 166, 165.930300000, METAL , 0, 1, {{0,}, {0,}, {3,}, {0,}, {0,} }},\n\n{ \"Tm\", 169, 169, 168.934230000, METAL2, 0, 1, {{0,}, {0,}, {2,3,}, {0,}, {0,} }},\n\n{ \"Yb\", 173, 174, 173.938900000, METAL2, 0, 1, {{0,}, {0,}, {2,3,}, {0,}, {0,} }},\n\n{ \"Lu\", 175, 175, 174.940800000, METAL , 0, 1, {{0,}, {0,}, {3,}, {0,}, {0,} }},\n\n{ \"Hf\", 178, 180, 179.946600000, METAL , 13, 1, {{0,}, {0,}, {4,}, {0,}, {0,} }},\n\n{ \"Ta\", 181, 181, 180.948010000, METAL , 15, 1, {{0,}, {0,}, {5,}, {0,}, {0,} }},\n\n{ \"W\", 184, 184, 183.951000000, METAL2, 17, 1, {{0,}, {0,}, {3,4,5,6,}, {0,}, {0,} }},\n\n{ \"Re\", 186, 187, 186.955800000, METAL2, 19, 1, {{0,}, {0,}, {2,4,6,7,}, {0,}, {0,} }},\n\n{ \"Os\", 190, 192, 191.961500000, METAL2, 22, 1, {{0,}, {0,}, {2,3,4,6,}, {0,}, {0,} }},\n\n{ \"Ir\", 192, 193, 192.962900000, METAL2, 22, 1, {{0,}, {0,}, {2,3,4,6,}, {0,}, {0,} }},\n\n{ \"Pt\", 195, 195, 194.964800000, METAL2, 22, 1, {{0,}, {0,}, {2,4,}, {0,}, {0,} }},\n\n{ \"Au\", 197, 197, 196.966560000, METAL , 24, 1, {{0,}, {0,}, {1,3,}, {0,}, {0,} }},\n\n{ \"Hg\", 201, 202, 201.970617000, METAL2, 19, 1, {{0,}, {0,}, {1,2,}, {0,}, {0,} }},\n\n{ \"Tl\", 204, 205, 204.974400000, METAL2, 18, 0, {{3,5,}, {2,4,}, {1,3,}, {0,}, {0,} }},\n\n{ \"Pb\", 207, 208, 207.976627000, METAL2, 18, 0, {{2,4,6,}, {3,5}, {2,4,}, {3,}, {0,} }},\n\n{ \"Bi\", 209, 209, 208.980390000, METAL , 19, 0, {{1,3,5,7,}, {2,4,6,}, {3,5,}, {2,4,}, {3,} }},\n\n{ \"Po\", 209, 209, 208.982400000, METAL2, 20, 0, {{0,}, {1,3,5,7,}, {2,4,6,}, {3,5,}, {2,4,} }},\n\n{ \"At\", 210, 210, 209.987100000, 0 , 22, 0, {{0,}, {0,}, {1,3,5,7,}, {2,4,6}, {3,5,} }},\n\n{ \"Rn\", 222, 222, 222.017500000, 0 , 0, 0, {{0,}, {0,}, {0,}, {0,}, {0,} }},\n\n{ \"Fr\", 223, 223, 223.019700000, METAL , 0, 0, {{0,}, {0,}, {1,}, {0,}, {0,} }},\n\n{ \"Ra\", 226, 226, 226.025410000, METAL , 0, 0, {{0,}, {0,}, {2,}, {1,}, {0,} }},\n\n{ \"Ac\", 227, 227, 227.027750000, METAL , 0, 1, {{0,}, {0,}, {3,}, {0,}, {0,} }},\n\n{ \"Th\", 232, 232, 232.038050000, METAL2, 0, 1, {{0,}, {0,}, {3,4,}, {0,}, {0,} }},\n\n{ \"Pa\", 231, 231, 231.035880000, METAL2, 0, 1, {{0,}, {0,}, {3,4,5,}, {0,}, {0,} }},\n\n{ \"U\", 238, 238, 238.050790000, METAL2, 0, 1, {{0,}, {0,}, {3,4,5,6,}, {0,}, {0,} }},\n\n{ \"Np\", 237, 237, 237.048170000, METAL2, 0, 1, {{0,}, {0,}, {3,4,5,6,}, {0,}, {0,} }},\n\n{ \"Pu\", 244, 244, 244.064200000, METAL2, 0, 1, {{0,}, {0,}, {3,4,5,6,}, {0,}, {0,} }},\n\n{ \"Am\", 243, 243, 243.061370000, METAL2, 0, 1, {{0,}, {0,}, {3,4,5,6,}, {0,}, {0,} }},\n\n{ \"Cm\", 247, 247, 247.070300000, METAL , 0, 1, {{0,}, {0,}, {3,}, {0,}, {0,} }},\n\n{ \"Bk\", 247, 247, 247.070300000, METAL , 0, 1, {{0,}, {0,}, {3,4,}, {0,}, {0,} }},\n\n{ \"Cf\", 251, 251, 251.079600000, METAL , 0, 1, {{0,}, {0,}, {3,}, {0,}, {0,} }},\n\n{ \"Es\", 252, 252, 252.082800000, METAL , 0, 1, {{0,}, {0,}, {3,}, {0,}, {0,} }},\n\n{ \"Fm\", 257, 257, 257.095100000, METAL , 0, 1, {{0,}, {0,}, {3,}, {0,}, {0,} }},\n\n{ \"Md\", 258, 258, 258.098600000, METAL , 0, 1, {{0,}, {0,}, {3,}, {0,}, {0,} }},\n\n{ \"No\", 259, 259, 259.100900000, METAL , 0, 1, {{0,}, {0,}, {1,}, {0,}, {0,} }},\n\n{ \"Lr\", 260, 260, 260.105400000, METAL , 0, 1, {{0,}, {0,}, {1,}, {0,}, {0,} }},\n\n{ \"Rf\", 261, 261, 261.108700000, METAL , 0, 1, {{0,}, {0,}, {1,}, {0,}, {0,} }},\n\n\n\n/*\n\n The elements below were added after v. 1.03.\n\n When available, the mass is given for isotope with the longest half-life.\n\n Standard valences given here are just placeholders.\n\n v. 1.04: added elements 105-112.\n\n Ref.: M. E. WIESER AND T. B. COPLEN.\n\n Atomic weights of the elements 2009 (IUPAC Technical Report).\n\n Pure Appl. Chem., Vol. 83, No. 2, pp. 359�396, 2011.\n\n v. 1.05: added elements 114 and 116;\n\n updated data for elements 105-112.\n\n Ref.: J. Meija, T.B. Coplen, M.Berglund et al.\n\n Atomic weights of the elements 2013 (IUPAC Technical Report).\n\n Pure Appl. Chem., Vol. 88, No. 3, pp. 265�291, 2016.\n\n added elements 113, 115, 117, and 118, according to IUPAC provisional recommendations:\n\n Ref.: L. Ohrstrom, J. Reedijk.\n\n Names and Symbols of the Elements with Atomic Numbers 113, 115, 117 and 118.\n\n Pure Appl. Chem., May 1, 2016, Manuscript ID PAC-REC-16-05-01\n\n http://iupac.org/cms/wp-content/uploads/2016/06/names-and-symbols-of-elements.pdf\n\n*/\n\n\n\n/* 105 dubnium Db ? Like: Ta */\n\n{ \"Db\", 270, 270, 270.131000000, METAL , 0, 1, {{0,}, {0,}, {1,}, {0,}, {0,} }},\n\n/* 106 seaborgium Sg ? Like: W */\n\n{ \"Sg\", 269, 269, 269.129000000, METAL , 0, 1, {{0,}, {0,}, {1,}, {0,}, {0,} }},\n\n/* 107 bohrium Bh ? Like: Re */\n\n{ \"Bh\", 270, 270, 270.133000000, METAL , 0, 1, {{0,}, {0,}, {1,}, {0,}, {0,} }},\n\n/* 108 hassium Hs ? Like: Os */\n\n{ \"Hs\", 270, 270, 270.134000000, METAL , 0, 1, {{0,}, {0,}, {1,}, {0,}, {0,} }},\n\n/* 109 meitnerium Mt ? Like: Ir */\n\n{ \"Mt\", 278, 278, 278.156000000, METAL , 0, 1, {{0,}, {0,}, {1,}, {0,}, {0,} }},\n\n/* 110 darmstadtium Ds ? Like: Pt */\n\n{ \"Ds\", 281, 281, 281.165000000, METAL , 0, 1, {{0,}, {0,}, {1,}, {0,}, {0,} }},\n\n/* 111 roentgenium Rg ? Like: Au */\n\n{ \"Rg\", 281, 281, 281.166000000, METAL , 0, 1, {{0,}, {0,}, {1,}, {0,}, {0,} }},\n\n/* 112 copernicium Cn ? Like: Hg */\n\n{ \"Cn\", 285, 285, 285.177000000, METAL , 0, 1, {{0,}, {0,}, {1,}, {0,}, {0,} }},\n\n/* 113 nihonium Nh ? Like: ? */\n\n{ \"Nh\", 278, 278, 278.000000000, METAL , 0, 1, {{0,}, {0,}, {1,}, {0,}, {0,} }},\n\n/* 114 flerovium Fl ? Like: Pb */\n\n{ \"Fl\", 289, 289, 289.190000000, METAL , 0, 1, {{0,}, {0,}, {1,}, {0,}, {0,} }},\n\n/* 115 moscovium Mc ? Like: ? */\n\n{ \"Mc\", 289, 289, 289.000000000, METAL , 0, 1, {{0,}, {0,}, {1,}, {0,}, {0,} }},\n\n/* 116 livermorium Lv ? Like: Po */\n\n{ \"Lv\", 293, 293, 293.204000000, METAL , 0, 1, {{0,}, {0,}, {1,}, {0,}, {0,} }},\n\n/* 117 tennessine Ts ? Like: ? */\n\n{ \"Ts\", 297, 297, 297.000000000, METAL , 0, 1, {{0,}, {0,}, {1,}, {0,}, {0,} }},\n\n/* 118 oganesson Og ? Like: ? */\n\n{ \"Og\", 294, 294, 294.000000000, METAL , 0, 1, {{0,}, {0,}, {1,}, {0,}, {0,} }},\n\n/* End of added in v. 1.04 - 1.05 */\n\n/*\n\n{ \"Zy\", 0, 0, 0.000000000, 0 , 0, 1, {{0,}, {0,}, {1,}, {0,}, {0,} }},\n\n*/\n\n{ \"Zz\", 0, 0, 0.000000000, 0 , 0, 1, {{0,}, {0,}, {1,}, {0,}, {0,} }},\n\n#ifdef INCHI_ZFRAG\n\n{ \"Zu\", 0, 0, 0.000000000, 0 , 0, 1, {{0,}, {0,}, {1,}, {0,}, {0,} }}, //single bond fragment\n\n{ \"Zv\", 0, 0, 0.000000000, 0 , 0, 1, {{0,}, {0,}, {2,}, {0,}, {0,} }}, //double bond fragment\n\n{ \"Zw\", 0, 0, 0.000000000, 0 , 0, 1, {{0,}, {0,}, {3,}, {0,}, {0,} }}, //triple bond fragment\n\n{ \"Zx\", 0, 0, 0.000000000, 0 , 0, 1, {{0,}, {0,}, {1,2,}, {0,}, {0,} }}, //aromatic bond fragment\n\n#endif\n\n\n\n{ \"\", 0, 0, 0.000000000, 0 , 0, 0, {{0,}, {0,}, {0,}, {0,}, {0,} }},\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 32, "score": 178897.41710981925 }, { "content": "int has_other_ion_in_sphere_2( inp_ATOM *at,\n\n int iat,\n\n int iat_ion_neigh,\n\n const char *el,\n\n int el_len )\n\n{\n\n#define MAXQ 16\n\n AT_NUMB q[MAXQ];\n\n int lenq=0, lenq2, dist = 0, i = 0, iq, neigh, j, nRet=0;\n\n q[lenq++] = iat;\n\n at[iat].cFlags = 1;\n\n\n\n iq = 0;\n\n dist = 1;\n\n /* use at->cFlags as an indicator */\n\n while ( dist <= 2 )\n\n {\n\n for ( lenq2 = lenq; iq < lenq2; iq ++ )\n\n {\n\n i = q[iq];\n\n\n\n for ( j = 0; j < at[i].valence; j ++ )\n\n {\n\n neigh = at[i].neighbor[j];\n\n\n\n if ( !at[neigh].cFlags &&\n\n at[neigh].valence <= 3 &&\n\n NULL != memchr( el, at[neigh].el_number, el_len ) )\n\n {\n\n q[lenq ++] = neigh;\n\n at[neigh].cFlags = 1;\n\n if ( neigh != iat_ion_neigh &&\n\n at[iat_ion_neigh].charge == at[neigh].charge )\n\n {\n\n nRet ++;\n\n }\n\n }\n\n }\n\n }\n\n\n\n dist ++;\n\n }\n\n\n\n for ( iq = 0; iq < lenq; iq ++ )\n\n {\n\n i = q[iq];\n\n at[i].cFlags = 0;\n\n }\n\n\n\n return nRet;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 33, "score": 178897.41710981925 }, { "content": "#define NEUTRAL_STATE (-MIN_ATOM_CHARGE)\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 34, "score": 178897.41710981925 }, { "content": "int is_el_a_metal( int nPeriodicNum )\n\n{\n\n return 0!=(ElData[nPeriodicNum+1].nType & IS_METAL);\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 35, "score": 178897.41710981925 }, { "content": "int num_of_H( inp_ATOM *at, int iat )\n\n{\n\nstatic int el_number_H;\n\nint i, n, num_explicit_H = 0;\n\ninp_ATOM *a = at + iat;\n\n\n\n if ( !el_number_H )\n\n el_number_H = get_periodic_table_number( \"H\" );\n\n\n\n for ( i = 0; i < a->valence; i ++ )\n\n {\n\n n = a->neighbor[i];\n\n num_explicit_H += ( 1 == at[n].valence && el_number_H == at[n].el_number );\n\n }\n\n\n\n return num_explicit_H+NUMH(at,iat);\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 36, "score": 178897.41710981925 }, { "content": "const int ERR_ELEM = 255;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 37, "score": 178897.41710981925 }, { "content": " class Molecule;\n\n\n", "file_path": "core/indigo-core/molecule/molecule_inchi_utils.h", "rank": 38, "score": 177908.29159012967 }, { "content": " Indigo indigo;\n", "file_path": "utils/legio/src/com/epam/indigo/legio/MainFrame.java", "rank": 39, "score": 177026.41154192563 }, { "content": " Indigo indigo;\n", "file_path": "utils/legio/src/com/epam/indigo/legio/LegioData.java", "rank": 40, "score": 177026.41154192563 }, { "content": " S_CHAR *bAtomUsedForStereo; /* 0 if not a stereo atom or during a canon. rank being mapped on this atom; */\n", "file_path": "third_party/inchi/INCHI_BASE/src/ichicant.h", "rank": 41, "score": 175895.65379358025 }, { "content": " S_CHAR *bRankUsedForStereo; /* canon. rank used for stereo mapping */\n", "file_path": "third_party/inchi/INCHI_BASE/src/ichicant.h", "rank": 42, "score": 175888.69664983262 }, { "content": "int get_atomic_mass(const char *elname)\n\n{\n\n int el_number, atw;\n\n if ( ERR_ELEM != (el_number = el_number_in_internal_ref_table( elname )) )\n\n {\n\n atw = ElData[el_number].nAtMass;\n\n }\n\n else\n\n {\n\n atw = 0;\n\n }\n\n\n\n return atw;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 43, "score": 175691.37946106942 }, { "content": "int get_el_type( int nPeriodicNum )\n\n{\n\n return ElData[nPeriodicNum+1].nType;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 44, "score": 175690.8774611479 }, { "content": "int get_num_H ( const char* elname,\n\n int inp_num_H,\n\n S_CHAR inp_num_iso_H[],\n\n int charge,\n\n int radical,\n\n int chem_bonds_valence,\n\n int atom_input_valence,\n\n int bAliased,\n\n int bDoNotAddH,\n\n int bHasMetalNeighbor )\n\n{\n\nint val, i, el_number, num_H = 0, num_iso_H;\n\nstatic int el_number_N = 0, el_number_S, el_number_O, el_number_C;\n\n\n\n if ( !el_number_N )\n\n {\n\n el_number_N = el_number_in_internal_ref_table( \"N\" );\n\n el_number_S = el_number_in_internal_ref_table( \"S\" );\n\n el_number_O = el_number_in_internal_ref_table( \"O\" );\n\n el_number_C = el_number_in_internal_ref_table( \"C\" );\n\n }\n\n\n\n /* atom_input_valence (cValence) cannot be specified in case of */\n\n /* aliased MOLFile atom with known inp_num_H or inp_num_iso_H[] */\n\n\n\n if ( bAliased )\n\n {\n\n num_H = inp_num_H;\n\n }\n\n else if ( atom_input_valence && (atom_input_valence !=15 || chem_bonds_valence) )\n\n {\n\n num_H = inchi_max( 0, atom_input_valence - chem_bonds_valence );\n\n }\n\n else if ( atom_input_valence == 15 && !chem_bonds_valence )\n\n {\n\n num_H = 0;\n\n }\n\n else if ( MIN_ATOM_CHARGE <= charge &&\n\n MAX_ATOM_CHARGE >= charge &&\n\n ERR_ELEM != (el_number=el_number_in_internal_ref_table( elname ) ) &&\n\n !ElData[el_number].bSkipAddingH && !bDoNotAddH )\n\n {\n\n /* add hydrogen atoms according to standard element valence */\n\n if ( radical && radical != RADICAL_SINGLET ) {\n\n if ( val = ElData[el_number].cValence[NEUTRAL_STATE+charge][0] )\n\n {\n\n val -= (radical==RADICAL_DOUBLET) ? 1\n\n : (radical==RADICAL_SINGLET || radical==RADICAL_TRIPLET )? 2 : val;\n\n /* if unknown radical then do not add H */\n\n num_H = inchi_max( 0, val - chem_bonds_valence );\n\n }\n\n }\n\n else\n\n {\n\n /* find the smallest valence that is greater than the sum of the chemical bond valences */\n\n for ( i = 0;\n\n (val=ElData[el_number].cValence[NEUTRAL_STATE+charge][i]) &&\n\n val < chem_bonds_valence;\n\n i++ )\n\n ;\n\n\n\n /* special case: do not add H to N(IV), S(III), S+(II), S-(II) */ /* S ions added 2004-05-10 */\n\n if ( el_number == el_number_N && !charge && !radical && val == 5 )\n\n val = 3;\n\n /*else if ( el_number == el_number_N && !charge && !radical && val == 3 &&\n\n chem_bonds_valence == 2 && bHasMetalNeighbor )\n\n val = 2;\n\n */\n\n else if ( el_number == el_number_S && !charge && !radical && val == 4 && chem_bonds_valence == 3 )\n\n val = 3;\n\n else if ( bHasMetalNeighbor && el_number != el_number_C && val > 0 )\n\n {\n\n val --;\n\n }\n\n /*\n\n if ( (el_number == el_number_S || el_number == el_number_O) &&\n\n abs(charge)==1 && !radical && val == 3 && chem_bonds_valence == 2 && bHasMetalNeighbor )\n\n val = 2;\n\n else\n\n */\n\n\n\n num_H = inchi_max( 0, val - chem_bonds_valence );\n\n }\n\n\n\n num_iso_H = 0;\n\n if ( inp_num_iso_H )\n\n {\n\n for ( i = 0; i < NUM_H_ISOTOPES; i ++ )\n\n {\n\n num_iso_H += inp_num_iso_H[i];\n\n }\n\n }\n\n\n\n /* should not happen because atom here is not aliased */\n\n if ( num_iso_H )\n\n {\n\n if ( num_H >= num_iso_H )\n\n {\n\n num_H -= num_iso_H;\n\n }\n\n else\n\n {\n\n num_H = inp_num_H; /* as requested in the alias */\n\n /* num_H = (num_iso_H - num_H) % 2; */ /* keep unchanged parity of the total number of H atoms */\n\n }\n\n }\n\n\n\n /* should not happen because atom here is not aliased */\n\n if ( inp_num_H > num_H )\n\n {\n\n num_H = inp_num_H; /* as requested in the alias */\n\n /* num_H = inp_num_H + (inp_num_H - num_H)%2; */ /* keep unchanged parity of the number of non-isotopic H atoms */\n\n }\n\n }\n\n else\n\n {\n\n num_H = inp_num_H;\n\n }\n\n\n\n return num_H;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 45, "score": 175690.79542556487 }, { "content": " int nElNegPauling10;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 46, "score": 175690.5645441373 }, { "content": "int read_upto_delim( char **pstring, char *field, int maxlen, char* delims )\n\n{\n\n int i, n;\n\n char *p = *pstring;\n\n\n\n if ( !p )\n\n return -1;\n\n\n\n /* skip leading spaces */\n\n for ( i=0; p[i] && isspace(UCINT p[i] ); i++ )\n\n ;\n\n p+= i;\n\n\n\n /* read up to next delim or eol */\n\n n = 0;\n\n while ( p[n] && !is_matching_any_delim( p[n], delims ) )\n\n {\n\n n++;\n\n }\n\n\n\n if ( n+1 > maxlen )\n\n return -1;\n\n\n\n mystrncpy( field, p, n+1 );\n\n field[n+1] = '\\0';\n\n\n\n if ( !p[n] )\n\n /* reached EOL */\n\n *pstring = NULL;\n\n else\n\n /* advance reading pos */\n\n *pstring = *pstring + i + n;\n\n\n\n return n;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 47, "score": 175689.16911066725 }, { "content": " const char *szElName;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 48, "score": 175683.6849820445 }, { "content": "int nNoMetalNeighIndex( inp_ATOM *at, int at_no )\n\n{\n\nint i;\n\n\n\n inp_ATOM *a = at + at_no;\n\n\n\n for ( i = 0; i < a->valence; i ++ )\n\n {\n\n if ( !is_el_a_metal( at[(int)a->neighbor[i]].el_number ) )\n\n return i;\n\n }\n\n\n\n return -1;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 49, "score": 175683.6849820445 }, { "content": "void remove_trailing_spaces( char* p )\n\n{\n\n int len;\n\n for( len = (int)strlen( p ) - 1; len >= 0 && isspace( UCINT p[len] ); len-- )\n\n ;\n\n p[++len] = '\\0';\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 50, "score": 175683.6849820445 }, { "content": "int nNoMetalNumBonds( inp_ATOM *at, int at_no )\n\n{\n\nint i;\n\n\n\n inp_ATOM *a = at + at_no;\n\n int num_H = NUMH(a, 0);\n\n int std_chem_bonds_valence = get_el_valence( a->el_number, a->charge, 0 );\n\n\n\n if ( a->chem_bonds_valence + num_H > std_chem_bonds_valence )\n\n {\n\n int valence_to_metal = 0;\n\n int num_bonds_to_metal = 0;\n\n\n\n for ( i = 0; i < a->valence; i ++ )\n\n {\n\n if ( is_el_a_metal( at[(int)a->neighbor[i]].el_number ) )\n\n {\n\n if ( (a->bond_type[i] & BOND_TYPE_MASK) >= BOND_TYPE_ALTERN )\n\n {\n\n return a->valence; /* fall back */\n\n }\n\n num_bonds_to_metal ++;\n\n valence_to_metal += (a->bond_type[i] & BOND_TYPE_MASK);\n\n }\n\n }\n\n\n\n if ( a->chem_bonds_valence + num_H - valence_to_metal == std_chem_bonds_valence )\n\n {\n\n /* removing bonds to metal produces standard valence */\n\n return a->valence - num_bonds_to_metal;\n\n }\n\n }\n\n\n\n#if ( S_VI_O_PLUS_METAL_FIX_BOND == 1 )\n\n else\n\n if ( 1 == a->charge && 2 == get_endpoint_valence(a->el_number) &&\n\n a->chem_bonds_valence + num_H == std_chem_bonds_valence )\n\n {\n\n int valence_to_metal = 0;\n\n int num_bonds_to_metal = 0;\n\n for ( i = 0; i < a->valence; i ++ )\n\n {\n\n if ( is_el_a_metal( at[(int)a->neighbor[i]].el_number ) )\n\n {\n\n if ( (a->bond_type[i] & BOND_TYPE_MASK) >= BOND_TYPE_ALTERN )\n\n {\n\n return a->valence; /* fall back */\n\n }\n\n num_bonds_to_metal ++;\n\n valence_to_metal += (a->bond_type[i] & BOND_TYPE_MASK);\n\n }\n\n }\n\n if ( 1 == valence_to_metal )\n\n {\n\n /* removing bonds to metal produces standard valence */\n\n return a->valence - num_bonds_to_metal;\n\n }\n\n }\n\n#endif\n\n\n\n return a->valence;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 51, "score": 175683.6849820445 }, { "content": "int get_endpoint_valence( U_CHAR el_number )\n\n{\n\n static U_CHAR el_numb[6];\n\n static int len, len2;\n\n int i;\n\n int len3;\n\n if (!len)\n\n {\n\n len3=0;\n\n el_numb[len3++] = (U_CHAR)get_periodic_table_number( \"O\" );\n\n el_numb[len3++] = (U_CHAR)get_periodic_table_number( \"S\" );\n\n el_numb[len3++] = (U_CHAR)get_periodic_table_number( \"Se\" );\n\n el_numb[len3++] = (U_CHAR)get_periodic_table_number( \"Te\" );\n\n len2 = len3;\n\n el_numb[len3++] = (U_CHAR)get_periodic_table_number( \"N\" );\n\n len=len3;\n\n }\n\n for ( i = 0; i < len; i ++ ) {\n\n if ( el_numb[i] == el_number ) {\n\n return i < len2? 2 : 3;\n\n }\n\n }\n\n return 0;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 52, "score": 175683.6849820445 }, { "content": "int extract_charges_and_radicals( char *elname, int *pnRadical, int *pnCharge )\n\n{\n\nchar *q, *r, *p;\n\nint nCharge=0, nRad = 0, charge_len = 0, k, nVal, nSign, nLastSign=1, len;\n\n\n\n p = elname;\n\n\n\n /* extract radicals & charges */\n\n while ( q = strpbrk( p, \"+-^\" ) )\n\n {\n\n switch ( *q )\n\n {\n\n case '+':\n\n case '-':\n\n for ( k = 0, nVal=0; (nSign = ('+' == q[k])) || (nSign = -('-' == q[k])); k++ )\n\n {\n\n nVal += (nLastSign = nSign);\n\n charge_len ++;\n\n }\n\n if ( nSign = (int)strtol( q+k, &r, 10 ) )\n\n {\n\n /* fixed 12-5-2001 */\n\n nVal += nLastSign * (nSign-1);\n\n }\n\n charge_len = (int) (r - q);\n\n nCharge += nVal;\n\n break;\n\n /* case '.': */ /* singlet '.' may be confused with '.' in formulas like CaO.H2O */\n\n case '^':\n\n nRad = 1; /* doublet here is 1. See below */\n\n charge_len = 1;\n\n for ( k = 1; q[0] == q[k]; k++ )\n\n {\n\n nRad ++;\n\n charge_len ++;\n\n }\n\n break;\n\n }\n\n memmove( q, q+charge_len, strlen(q+charge_len)+1 );\n\n }\n\n\n\n len = (int) strlen(p);\n\n\n\n /* radical */\n\n if ( (q = strrchr( p, ':' )) && !q[1])\n\n {\n\n nRad = RADICAL_SINGLET;\n\n q[0] = '\\0';\n\n len --;\n\n }\n\n else\n\n {\n\n while( (q = strrchr( p, '.' )) && !q[1] )\n\n {\n\n nRad ++;\n\n q[0] = '\\0';\n\n len --;\n\n }\n\n\n\n nRad = nRad == 1? RADICAL_DOUBLET :\n\n nRad == 2? RADICAL_TRIPLET : 0;\n\n }\n\n\n\n *pnRadical = nRad;\n\n *pnCharge = nCharge;\n\n return ( nRad || nCharge );\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 53, "score": 175683.6849820445 }, { "content": "int nNoMetalOtherNeighIndex( inp_ATOM *at, int at_no, int cur_neigh )\n\n{\n\nint i, neigh;\n\n\n\n inp_ATOM *a = at + at_no;\n\n\n\n for ( i = 0; i < a->valence; i ++ )\n\n {\n\n neigh = (int)a->neighbor[i];\n\n\n\n if ( neigh != cur_neigh && !is_el_a_metal( at[neigh].el_number ) )\n\n return i;\n\n }\n\n\n\n return -1;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 54, "score": 175683.6849820445 }, { "content": "int nNoMetalOtherNeighIndex2( inp_ATOM *at,\n\n int at_no,\n\n int cur_neigh,\n\n int cur_neigh2 )\n\n{\n\nint i, neigh;\n\n\n\n inp_ATOM *a = at + at_no;\n\n\n\n for ( i = 0; i < a->valence; i ++ )\n\n {\n\n neigh = (int)a->neighbor[i];\n\n\n\n if ( neigh != cur_neigh && neigh != cur_neigh2 && !is_el_a_metal( at[neigh].el_number ) )\n\n return i;\n\n }\n\n\n\n return -1;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 55, "score": 175683.6849820445 }, { "content": "int nBondsValToMetal( inp_ATOM* at, int iat )\n\n{\n\nint i, neigh, bond_type, nVal2Metal = 0;\n\ninp_ATOM* a = at + iat;\n\n\n\n for ( i = 0; i < a->valence; i ++ )\n\n {\n\n neigh = a->neighbor[i];\n\n\n\n if ( is_el_a_metal( at[(int)a->neighbor[i]].el_number ) )\n\n {\n\n bond_type = a->bond_type[i];\n\n\n\n if ( bond_type <= BOND_TYPE_TRIPLE )\n\n {\n\n nVal2Metal += bond_type;\n\n }\n\n else\n\n {\n\n return -1; /* bond to metal order is not well defined */\n\n }\n\n }\n\n }\n\n\n\n return nVal2Metal;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 56, "score": 175683.6849820445 }, { "content": "#define NUM_ATOM_CHARGES (MAX_ATOM_CHARGE - MIN_ATOM_CHARGE + 1)\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 57, "score": 175683.6849820445 }, { "content": "#define MAX_ATOM_CHARGE 2\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 58, "score": 175683.6849820445 }, { "content": "#define MAX_NUM_VALENCES 5 /* max. number + 1 to provide zero termination */\n\n\n\n\n\n\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 59, "score": 175683.6849820445 }, { "content": "int if_skip_add_H( int nPeriodicNum )\n\n /* was called if_skip_add_H(, renamed to avoid confusion with other procedures */\n\n{\n\n return\n\n ElData[nPeriodicNum>1? nPeriodicNum+1:0].bSkipAddingH;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 60, "score": 175683.6849820445 }, { "content": "void remove_one_lf( char* p)\n\n{\n\n size_t len;\n\n if ( p && 0 < (len = strlen(p)) && p[len-1] == '\\n' )\n\n {\n\n p[len-1] = '\\0';\n\n if ( len >= 2 && p[len-2] == '\\r' )\n\n p[len-2] = '\\0';\n\n }\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 61, "score": 175683.6849820445 }, { "content": "int get_el_valence( int nPeriodicNum, int charge, int val_num )\n\n{\n\n if ( charge < MIN_ATOM_CHARGE || charge > MAX_ATOM_CHARGE || val_num >= MAX_NUM_VALENCES )\n\n return 0;\n\n return\n\n ElData[nPeriodicNum>1? nPeriodicNum+1:0].cValence[NEUTRAL_STATE+charge][val_num];\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 62, "score": 175683.6849820445 }, { "content": "int nNoMetalBondsValence( inp_ATOM *at, int at_no )\n\n{\n\nint i;\n\n\n\n inp_ATOM *a = at + at_no;\n\n int num_H = NUMH(a, 0);\n\n int std_chem_bonds_valence = get_el_valence( a->el_number, a->charge, 0 );\n\n\n\n if ( a->chem_bonds_valence + num_H > std_chem_bonds_valence )\n\n {\n\n int valence_to_metal = 0;\n\n /*int num_bonds_to_metal = 0;*/\n\n\n\n for ( i = 0; i < a->valence; i ++ )\n\n {\n\n if ( is_el_a_metal( at[(int)a->neighbor[i]].el_number ) )\n\n {\n\n if ( (a->bond_type[i] & BOND_TYPE_MASK) >= BOND_TYPE_ALTERN )\n\n {\n\n return a->valence; /* fall back */\n\n }\n\n /* num_bonds_to_metal ++;*/\n\n valence_to_metal += (a->bond_type[i] & BOND_TYPE_MASK);\n\n }\n\n }\n\n\n\n if ( a->chem_bonds_valence + num_H - valence_to_metal == std_chem_bonds_valence )\n\n {\n\n /* removing bonds to metal produces standard valence */\n\n return a->chem_bonds_valence - valence_to_metal;\n\n }\n\n }\n\n\n\n#if ( S_VI_O_PLUS_METAL_FIX_BOND == 1 )\n\n else if ( 1 == a->charge && 2 == get_endpoint_valence(a->el_number) &&\n\n a->chem_bonds_valence + num_H == std_chem_bonds_valence )\n\n {\n\n\n\n int valence_to_metal = 0;\n\n /* int num_bonds_to_metal = 0;*/\n\n\n\n for ( i = 0; i < a->valence; i ++ )\n\n {\n\n if ( is_el_a_metal( at[(int)a->neighbor[i]].el_number ) )\n\n {\n\n if ( (a->bond_type[i] & BOND_TYPE_MASK) >= BOND_TYPE_ALTERN )\n\n {\n\n return a->valence; /* fall back */\n\n }\n\n /* num_bonds_to_metal ++;*/\n\n valence_to_metal += (a->bond_type[i] & BOND_TYPE_MASK);\n\n }\n\n }\n\n\n\n if ( 1 == valence_to_metal )\n\n /* removing bonds to metal produces standard valence */\n\n return a->chem_bonds_valence - valence_to_metal;\n\n }\n\n#endif\n\n\n\n return a->chem_bonds_valence;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 63, "score": 175683.6849820445 }, { "content": "#define MIN_ATOM_CHARGE (-2)\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 64, "score": 175683.6849820445 }, { "content": " int bSkipAddingH;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 65, "score": 175683.6849820445 }, { "content": "int extract_H_atoms( char *elname, S_CHAR num_iso_H[] )\n\n{\n\nint i, len, c, k, num_H, val;\n\nchar *q;\n\nchar elname1 = '\\0';\n\n\n\n i = 0;\n\n num_H = 0;\n\n len = (int) strlen(elname);\n\n c = UCINT elname[0];\n\n\n\n if ( len > 1 )\n\n elname1 = elname[1];\n\n\n\n while ( i < len )\n\n {\n\n switch ( c )\n\n {\n\n case 'H':\n\n k = 0;\n\n break;\n\n case 'D':\n\n k = 1;\n\n break;\n\n case 'T':\n\n k = 2;\n\n break;\n\n default:\n\n k = -1;\n\n break;\n\n }\n\n\n\n q = elname+i+1; /* pointer to the next to elname[i] character */\n\n c = UCINT q[0];\n\n\n\n if ( k >= 0 && !islower( c ) )\n\n {\n\n /* found a hydrogen */\n\n if ( isdigit( c ) )\n\n {\n\n val = (int)strtol( q, &q, 10 );\n\n /* q = pointer to the next to number of hydrogen atom(s) character */\n\n }\n\n else\n\n {\n\n val = 1;\n\n }\n\n if ( k )\n\n {\n\n num_iso_H[k] += val;\n\n }\n\n else\n\n {\n\n num_H += val;\n\n }\n\n\n\n /* remove the hydrogen atom from the string */\n\n len -= (int) (q-elname)-i;\n\n memmove( elname+i, q, len + 1 );\n\n /* c = UCINT elname[i]; */\n\n }\n\n else\n\n {\n\n i ++;\n\n }\n\n\n\n c = UCINT elname[i]; /* moved here 11-04-2002 */\n\n }\n\n\n\n len = (int) strlen(elname);\n\n if ( len == 2 )\n\n {\n\n if ( elname[1] != elname1 )\n\n /* Error, incorrect 2nd char of elname appears after 'subtracting' {H,D,T} */\n\n /* See a bug reported to inchi-discuss by A. Dalke for alias atom \"pH4d\" */\n\n /*^^^ 2017-01-06 */\n\n elname[1] = '?';\n\n }\n\n\n\n return num_H;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 66, "score": 175683.6849820445 }, { "content": "const int nElDataLen = sizeof(ElData)/sizeof(ElData[0])-1;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 67, "score": 175683.6849820445 }, { "content": "void SetUseAtomForStereo( S_CHAR *bAtomUsedForStereo, sp_ATOM *at, int num_atoms )\n\n{\n\n int i, k;\n\n memset( bAtomUsedForStereo, 0, sizeof( bAtomUsedForStereo[0] )*num_atoms );\n\n for ( i = 0; i < num_atoms; i ++ ) {\n\n if ( at[i].parity ) {\n\n for ( k = 0; k < MAX_NUM_STEREO_BONDS && at[i].stereo_bond_neighbor[k]; k ++ )\n\n ;\n\n bAtomUsedForStereo[i] = k? k : STEREO_AT_MARK;\n\n }\n\n }\n", "file_path": "third_party/inchi/INCHI_BASE/src/ichimap1.c", "rank": 76, "score": 172788.65187824087 }, { "content": "int dotify_non_printable_chars( char *line )\n\n{\n\nint i, c, num = 0;\n\n\n\n if ( line )\n\n {\n\n for ( i = 0; c = UCINT line[i]; i++ )\n\n {\n\n /* assuming ASCII charset */\n\n if ( c < ' ' || c >= 0x7F )\n\n {\n\n line[i] = '.';\n\n num++;\n\n }\n\n }\n\n }\n\n\n\n return num;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 77, "score": 172594.72740646492 }, { "content": "int get_element_chemical_symbol(int nAtNum, char *szElement )\n\n{\n\n nAtNum -= 1;\n\n\n\n if ( 0 < nAtNum )\n\n nAtNum += 2; /* bypass D, T */\n\n\n\n if ( 0 <= nAtNum && nAtNum < nElDataLen )\n\n {\n\n /* valid element symbol found */\n\n strcpy( szElement, ElData[nAtNum].szElName );\n\n return 0;\n\n }\n\n\n\n /* not found */\n\n strcpy( szElement, \"??\" );\n\n return -1;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 78, "score": 172594.50722439805 }, { "content": "int needed_unusual_el_valence( int nPeriodicNum,\n\n int charge,\n\n int radical,\n\n int bonds_valence,\n\n int actual_bonds_valence,\n\n int num_H, int\n\n num_bonds )\n\n{\n\nint i, num_found, num_found_known, chem_valence, rad_adj, known_chem_valence, exact_found;\n\nint num_H_expected;\n\nchar szElement[4];\n\n\n\n /*\n\n if ( !num_bonds && !num_H )\n\n return 0;\n\n */\n\n\n\n if ( num_bonds && get_element_chemical_symbol(nPeriodicNum, szElement )!=-1 )\n\n {\n\n num_H_expected = get_num_H( szElement, 0, NULL, charge, radical, actual_bonds_valence, 0,0,0,0 );\n\n }\n\n else\n\n {\n\n num_H_expected = num_H;\n\n }\n\n\n\n chem_valence = bonds_valence + num_H;\n\n if ( charge < MIN_ATOM_CHARGE || charge > MAX_ATOM_CHARGE ||\n\n !get_el_valence( nPeriodicNum, charge, 0 ) ||\n\n if_skip_add_H( nPeriodicNum ) || bonds_valence != actual_bonds_valence ||\n\n num_H_expected != num_H )\n\n {\n\n if ( !num_H && !num_H_expected && bonds_valence == actual_bonds_valence )\n\n return 0; /* no H */\n\n return chem_valence; /* needs to add H-atoms */\n\n }\n\n\n\n /* take into account radical */\n\n if (radical==RADICAL_DOUBLET)\n\n rad_adj = 1;\n\n else if (radical==RADICAL_TRIPLET )\n\n rad_adj = 2;\n\n else\n\n rad_adj = 0;\n\n\n\n num_found_known = 0;\n\n num_found = 0;\n\n exact_found = 0;\n\n\n\n for ( i = 0; i < MAX_NUM_VALENCES; i ++ )\n\n {\n\n if ( 0 < (known_chem_valence = get_el_valence( nPeriodicNum, charge, i )) &&\n\n bonds_valence <= (known_chem_valence -= rad_adj) )\n\n {\n\n /* found known valence that fits without H */\n\n num_found_known ++;\n\n if ( known_chem_valence <= chem_valence )\n\n {\n\n /* known valence is large enough to accommodate (implicit) H */\n\n num_found ++;\n\n }\n\n if ( known_chem_valence == chem_valence )\n\n {\n\n exact_found = 1;\n\n break;\n\n }\n\n }\n\n }\n\n\n\n return\n\n (exact_found&&1==num_found&&1==num_found_known) ? 0\n\n : chem_valence?chem_valence:-1; /* needs zero */\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 79, "score": 172587.85221305452 }, { "content": "int detect_unusual_el_valence( int nPeriodicNum,\n\n int charge,\n\n int radical,\n\n int bonds_valence,\n\n int num_H,\n\n int num_bonds )\n\n{\n\nint i, chem_valence, rad_adj, known_chem_valence;\n\n\n\n if ( !num_bonds && !num_H )\n\n return 0;\n\n\n\n if ( charge < MIN_ATOM_CHARGE || charge > MAX_ATOM_CHARGE )\n\n {\n\n if ( bonds_valence == num_bonds )\n\n return 0; /* all single bonds */\n\n return bonds_valence;\n\n }\n\n\n\n if ( !get_el_valence( nPeriodicNum, charge, 0 ) && bonds_valence == num_bonds )\n\n return 0;\n\n\n\n chem_valence = bonds_valence + num_H;\n\n rad_adj = 0;\n\n\n\n /* take into account radical */\n\n if (radical==RADICAL_DOUBLET)\n\n rad_adj = 1;\n\n else if (radical==RADICAL_TRIPLET || radical==RADICAL_SINGLET )\n\n rad_adj = 2;\n\n\n\n for ( i = 0; i < MAX_NUM_VALENCES; i ++ )\n\n {\n\n if ( 0 < (known_chem_valence = get_el_valence( nPeriodicNum, charge, i )-rad_adj) )\n\n {\n\n if ( known_chem_valence == chem_valence )\n\n {\n\n return 0;\n\n }\n\n }\n\n }\n\n\n\n return chem_valence;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 80, "score": 172587.85221305455 }, { "content": "int get_periodic_table_number( const char* elname )\n\n{\n\nint num;\n\n\n\n num = el_number_in_internal_ref_table( elname );\n\n\n\n if ( num < ERR_ELEM )\n\n /* account for D,T in internal table (but not Mendeleev's table) */\n\n num = inchi_max(1, num-1);\n\n\n\n return num;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 81, "score": 172587.85221305452 }, { "content": "int MakeRemovedProtonsString( int nNumRemovedProtons,\n\n NUM_H *nNumExchgIsotopicH,\n\n NUM_H *nNumRemovedProtonsIsotopic,\n\n int bIsotopic,\n\n char *szRemovedProtons,\n\n int *num_removed_iso_H )\n\n{\n\nint i, j, len, num;\n\n\n\n len = 0;\n\n\n\n if ( nNumRemovedProtons )\n\n {\n\n len = sprintf ( szRemovedProtons, \"Proton balance: %c %d H+\",\n\n nNumRemovedProtons>=0? '+':'-', abs(nNumRemovedProtons) );\n\n }\n\n\n\n if ( bIsotopic && (nNumRemovedProtonsIsotopic || nNumExchgIsotopicH) )\n\n {\n\n\n\n for ( i = 0, j = 0; i < NUM_H_ISOTOPES; i ++ )\n\n {\n\n\n\n num = (nNumExchgIsotopicH? nNumExchgIsotopicH[i]:0) +\n\n (nNumRemovedProtonsIsotopic? nNumRemovedProtonsIsotopic[i]:0);\n\n\n\n if ( num )\n\n {\n\n len += sprintf( szRemovedProtons+len, \"%s %d^%dH\",\n\n j? \", \":\" [ removed \", num, i+1);\n\n j ++;\n\n }\n\n }\n\n\n\n if ( j )\n\n {\n\n len += sprintf( szRemovedProtons+len, \" ]\" );\n\n if ( num_removed_iso_H )\n\n *num_removed_iso_H = j;\n\n }\n\n }\n\n\n\n if ( !len ) {\n\n szRemovedProtons[0] = '\\0';\n\n }\n\n return len;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 82, "score": 172587.85221305455 }, { "content": "int get_unusual_el_valence( int nPeriodicNum,\n\n int charge,\n\n int radical,\n\n int bonds_valence,\n\n int num_H,\n\n int num_bonds )\n\n{\n\nint i, num_found, chem_valence, rad_adj, known_chem_valence, exact_found;\n\n\n\n if ( !num_bonds && !num_H )\n\n return 0;\n\n\n\n if ( charge < MIN_ATOM_CHARGE || charge > MAX_ATOM_CHARGE )\n\n {\n\n if ( bonds_valence == num_bonds )\n\n return 0; /* all single bonds */\n\n return bonds_valence;\n\n }\n\n\n\n if ( !get_el_valence( nPeriodicNum, charge, 0 ) && bonds_valence == num_bonds )\n\n return 0;\n\n\n\n chem_valence = bonds_valence + num_H;\n\n rad_adj = 0;\n\n num_found = 0;\n\n exact_found = 0;\n\n\n\n /* Take into account a radical */\n\n if (radical==RADICAL_DOUBLET)\n\n rad_adj = 1;\n\n else if (radical==RADICAL_TRIPLET )\n\n rad_adj = 2;\n\n\n\n for ( i = 0; i < MAX_NUM_VALENCES; i ++ )\n\n {\n\n if ( 0 < (known_chem_valence = get_el_valence( nPeriodicNum, charge, i )-rad_adj) &&\n\n num_bonds <= known_chem_valence && known_chem_valence <= chem_valence )\n\n {\n\n num_found ++;\n\n if ( known_chem_valence == chem_valence )\n\n {\n\n exact_found = 1;\n\n break;\n\n }\n\n }\n\n }\n\n\n\n return (exact_found && 1==num_found) ? 0\n\n : chem_valence;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 83, "score": 172587.85221305455 }, { "content": "int get_atomic_mass_from_elnum( int nAtNum )\n\n{\n\n nAtNum-= 1;\n\n\n\n if ( 0 < nAtNum )\n\n nAtNum+= 2; /* bypass D, T */\n\n\n\n if ( 0 <= nAtNum && nAtNum < nElDataLen )\n\n return (int)ElData[nAtNum].nAtMass;\n\n\n\n return 0;\n", "file_path": "third_party/inchi/INCHI_BASE/src/util.c", "rank": 84, "score": 172587.85221305455 }, { "content": " def test_convert_inchi_aux(self):\n\n params = {'struct': 'c1ccccc1', 'output_format': 'chemical/x-inchi-aux'}\n\n headers, data = self.get_headers(\n\n params)\n\n result = requests.post(self.url_prefix + '/convert', headers=headers, data=data)\n\n result_data = json.loads(result.text)\n\n self.assertEqual('chemical/x-inchi-aux', result_data['format'])\n\n self.assertIn('AuxInfo=', result_data['struct'])\n\n\n\n result = requests.get(self.url_prefix+'/convert',params=params)\n", "file_path": "utils/indigo-service/service/test/api/indigo_test.py", "rank": 85, "score": 171569.09311707295 }, { "content": "local void fixedtables(state)\n", "file_path": "third_party/zlib/src/infback.c", "rank": 86, "score": 171203.9946617511 }, { "content": "local void fixedtables(state)\n", "file_path": "third_party/zlib/src/inflate.c", "rank": 87, "score": 171203.9946617511 }, { "content": "local void fill_window OF((deflate_state *s));\n", "file_path": "third_party/zlib/src/deflate.c", "rank": 88, "score": 171199.32613046071 }, { "content": "local void make_crc_table OF((void));\n", "file_path": "third_party/zlib/src/crc32.c", "rank": 89, "score": 171192.3742692537 }, { "content": "local void gz_reset(state)\n", "file_path": "third_party/zlib/src/gzlib.c", "rank": 90, "score": 171192.3742692537 }, { "content": "#include \"base_cpp/output.h\"\n\n#include \"molecule/elements.h\"\n\n#include \"molecule/molecule.h\"\n\n#include \"molecule/molecule_automorphism_search.h\"\n\n#include \"molecule/molecule_inchi_utils.h\"\n\n\n\nusing namespace indigo;\n\n\n\nusing namespace MoleculeInChILayers;\n\n\n\nIMPL_ERROR(MoleculeInChI, \"InChI canonicalizer\");\n\n\n\nCP_DEF(MoleculeInChI);\n\n\n\nMoleculeInChI::MoleculeInChI(Output& output) : _output(output), CP_INIT, TL_CP_GET(_components), TL_CP_GET(_component_indices)\n\n{\n\n prefix = \"Indigo=1.1\";\n\n}\n\n\n\nvoid MoleculeInChI::outputInChI(Molecule& mol)\n", "file_path": "core/indigo-core/molecule/src/molecule_inchi.cpp", "rank": 91, "score": 37.49140861447812 }, { "content": "#include \"base_cpp/output.h\"\n\n#include \"base_cpp/tlscont.h\"\n\n#include \"graph/dfs_walk.h\"\n\n#include \"molecule/elements.h\"\n\n#include \"molecule/molecule.h\"\n\n#include \"molecule/molecule_inchi_utils.h\"\n\n#include \"molecule/molecule_stereocenters.h\"\n\n\n\nusing namespace indigo;\n\nusing namespace indigo::MoleculeInChILayers;\n\n\n\nIMPL_ERROR(AbstractLayer, \"InChI layer\");\n\n\n\n//\n\n// AbstractLayer\n\n//\n\nAbstractLayer::AbstractLayer() : _mol(0)\n\n{\n\n}\n\n\n", "file_path": "core/indigo-core/molecule/src/molecule_inchi_layers.cpp", "rank": 92, "score": 36.71216558962175 }, { "content": "#include \"indigo_internal.h\"\n\n#include \"indigo_molecule.h\"\n\n\n\nusing namespace indigo;\n\n\n\nCEXPORT const char* indigoInchiVersion()\n\n{\n\n return InchiWrapper::version();\n\n}\n\n\n\n//\n\n// Session Inchi instance\n\n//\n", "file_path": "api/c/indigo-inchi/src/indigo_inchi_api.cpp", "rank": 93, "score": 35.79254326538351 }, { "content": "#include \"molecule/inchi_wrapper.h\"\n\n\n\n#include \"base_cpp/obj.h\"\n\n#include \"molecule/elements.h\"\n\n#include \"molecule/molecule.h\"\n\n#include \"molecule/molecule_dearom.h\"\n\n// #include \"mode.h\"\n\n\n\n\n\nusing namespace indigo;\n\n\n\n// Inchi doesn't seem to support multithreading\n\nstatic OsLock inchi_lock;\n\n\n\nnamespace indigo\n\n{\n\n // Structure that matches both inchi_OutputStruct and tagINCHI_Input\n\n struct InchiOutput\n\n {\n\n inchi_Atom* atom;\n", "file_path": "core/indigo-core/molecule/src/inchi_wrapper.cpp", "rank": 94, "score": 34.06084098160352 }, { "content": "#include \"molecule/molecule_arom_match.h\"\n\n#include \"molecule/molecule_exact_matcher.h\"\n\n#include \"molecule/molecule_inchi.h\"\n\n#include \"molecule/molecule_layered_molecules.h\"\n\n#include \"molecule/molecule_substructure_matcher.h\"\n\n#include \"molecule/molecule_tautomer.h\"\n\n#include \"molecule/molecule_tautomer_enumerator.h\"\n\n#include \"molecule/molecule_tautomer_utils.h\"\n\n\n\nusing namespace indigo;\n\n\n", "file_path": "core/indigo-core/molecule/src/molecule_tautomer_match.cpp", "rank": 95, "score": 33.621387282190724 }, { "content": "#include <gtest/gtest.h>\n\n\n\n#include <molecule/molecule_mass.h>\n\n\n\n#include <indigo-inchi.h>\n\n#include <indigo.h>\n\n#include <indigo_internal.h>\n\n\n\n#include \"common.h\"\n\n\n\nusing namespace indigo;\n\n\n\nTEST(IndigoBasicApiTest, test_mass)\n\n{\n\n Molecule t_mol;\n\n\n\n loadMolecule(\"[81Br]\", t_mol);\n\n\n\n MoleculeMass mm;\n\n\n", "file_path": "api/c/tests/unit/basic/basic_api_test.cpp", "rank": 96, "score": 32.252575956026234 }, { "content": "#include <gtest/gtest.h>\n\n\n\n#include <indigo-inchi.h>\n\n\n\n#include \"common.h\"\n\n\n\nusing namespace indigo;\n\n\n\nTEST(IndigoInChITest, basic)\n\n{\n\n indigoSetErrorHandler(errorHandling, nullptr);\n\n\n\n const char* inchi = \"InChI=1S/C10H20N2O2/c11-7-1-5-2-8(12)10(14)4-6(5)3-9(7)13/h5-10,13-14H,1-4,11-12H2\";\n\n const auto m = indigoInchiLoadMolecule(inchi);\n\n ASSERT_EQ(strcmp(indigoCanonicalSmiles(m), \"NC1CC2CC(N)C(O)CC2CC1O\"), 0);\n\n const char* res_inchi = indigoInchiGetInchi(m);\n\n ASSERT_EQ(strcmp(res_inchi, inchi), 0);\n\n}\n", "file_path": "api/c/tests/unit/formats/inchi.cpp", "rank": 97, "score": 31.661428427911275 }, { "content": "\n\n#include \"base_cpp/reusable_obj_array.h\"\n\n#include \"molecule/molecule.h\"\n\n#include \"molecule/molecule_layered_molecules.h\"\n\n#include \"molecule/molecule_tautomer.h\"\n\n\n\n#define USE_DEPRECATED_INCHI\n\n\n\nnamespace indigo\n\n{\n\n\n", "file_path": "core/indigo-core/molecule/molecule_tautomer_enumerator.h", "rank": 98, "score": 31.360327768554814 }, { "content": "#include <algorithm>\n\n\n\nusing namespace indigo;\n\n\n\n// private---------------------------------------------------------------------------------------\n\n\n\nvoid Dbitset::_recalculateWordsInUse()\n\n{\n\n // Traverse the bitset until a used word is found\n\n int i;\n\n for (i = _length - 1; i >= 0; --i)\n\n if (_words[i] != 0)\n\n break;\n\n _wordsInUse = i + 1; // The new logical size\n\n}\n\n\n\nvoid Dbitset::_initWords(int nbits)\n\n{\n\n _wordsInUse = 0;\n\n _length = _wordIndex(nbits - 1) + 1;\n", "file_path": "core/indigo-core/common/base_cpp/d_bitset.cpp", "rank": 99, "score": 30.42859527071571 } ]
C++
libcore/include/sirikata/core/trace/Trace.hpp
sirikata/sirikata
3a0d54a8c4778ad6e25ef031d461b2bc3e264860
#ifndef _SIRIKATA_CORE_TRACE_HPP_ #define _SIRIKATA_CORE_TRACE_HPP_ #include <sirikata/core/util/Platform.hpp> #include <sirikata/core/util/Thread.hpp> #include <sirikata/core/util/AtomicTypes.hpp> #include <sirikata/core/network/ObjectMessage.hpp> #include <sirikata/core/trace/BatchedBuffer.hpp> namespace Sirikata { namespace Trace { #define TRACE_DROP(nam) ((mContext->trace()->drops.n[::Sirikata::Trace::Drops::nam]=#nam )&&++(mContext->trace()->drops.d[::Sirikata::Trace::Drops::nam])); SILOG(drop,insane,#nam) struct Drops { enum { OH_DROPPED_AT_SEND, OH_DROPPED_AT_RECEIVE_QUEUE, SPACE_DROPPED_AT_MAIN_STRAND_CROSSING, DROPPED_AT_FORWARDED_LOCALLY, DROPPED_DURING_FORWARDING, DROPPED_DURING_FORWARDING_ROUTING, DROPPED_AT_SPACE_ENQUEUED, DROPPED_CSFQ_OVERFLOW, DROPPED_CSFQ_PROBABILISTIC, NUM_DROPS }; uint64 d[NUM_DROPS]; const char*n[NUM_DROPS]; Drops() { memset(d,0,NUM_DROPS*sizeof(uint64)); memset(n,0,NUM_DROPS*sizeof(const char*)); } void output(); }; #define ProximityTag 0 #define ObjectLocationTag 1 #define ServerDatagramQueuedTag 4 #define ServerDatagramSentTag 5 #define ServerDatagramReceivedTag 6 #define SegmentationChangeTag 10 #define MigrationBeginTag 11 #define MigrationAckTag 12 #define MigrationRoundTripTag 18 #define ServerLocationTag 13 #define ServerObjectEventTag 14 #define ObjectSegmentationCraqLookupRequestAnalysisTag 15 #define ObjectSegmentationProcessedRequestAnalysisTag 16 #define ObjectPingTag 17 #define ObjectPingCreatedTag 32 #define ObjectHitPointTag 34 #define OSegTrackedSetResultAnalysisTag 19 #define OSegShutdownEventTag 20 #define ObjectGeneratedLocationTag 22 #define OSegCacheResponseTag 23 #define OSegLookupNotOnServerAnalysisTag 24 #define OSegCumulativeTraceAnalysisTag 25 #define MessageTimestampTag 30 #define MessageCreationTimestampTag 31 #define ObjectConnectedTag 33 enum MessagePath { NONE, CREATED, DESTROYED, OH_HIT_NETWORK, OH_DROPPED_AT_SEND, OH_NET_RECEIVED, OH_DROPPED_AT_RECEIVE_QUEUE, OH_RECEIVED, SPACE_DROPPED_AT_MAIN_STRAND_CROSSING, HANDLE_OBJECT_HOST_MESSAGE, HANDLE_SPACE_MESSAGE, FORWARDED_LOCALLY, DROPPED_AT_FORWARDED_LOCALLY, FORWARDING_STARTED, FORWARDED_LOCALLY_SLOW_PATH, DROPPED_DURING_FORWARDING, OSEG_CACHE_CHECK_STARTED, OSEG_CACHE_CHECK_FINISHED, OSEG_LOOKUP_STARTED, OSEG_CACHE_LOOKUP_FINISHED, OSEG_SERVER_LOOKUP_FINISHED, OSEG_LOOKUP_FINISHED, SPACE_TO_SPACE_ENQUEUED, DROPPED_AT_SPACE_ENQUEUED, SPACE_TO_SPACE_HIT_NETWORK, SPACE_TO_SPACE_READ_FROM_NET, SPACE_TO_SPACE_SMR_DEQUEUED, SPACE_TO_OH_ENQUEUED, NUM_PATHS }; class SIRIKATA_EXPORT Trace { public: Drops drops; ~Trace(); static void InitOptions(); Trace(const String& filename); #define CREATE_TRACE_CHECK_DECL(___name) \ bool check ## ___name () const; #define CREATE_TRACE_EVAL_DECL(___name, ...) \ void ___name( __VA_ARGS__ ); #define CREATE_TRACE_DECL(___name, ...) \ CREATE_TRACE_CHECK_DECL(___name) \ CREATE_TRACE_EVAL_DECL(___name, __VA_ARGS__) #define CREATE_TRACE_CHECK_DEF(__klass, ___name , ___log_var) \ bool __klass :: check ## ___name () const { \ return ___log_var->as<bool>(); \ } #define CREATE_TRACE_EVAL_DEF(__klass, ___name , ... ) \ void __klass :: ___name ( __VA_ARGS__ ) #define CREATE_TRACE_DEF(__klass, ___name , ___log_var, ... ) \ CREATE_TRACE_CHECK_DEF(__klass, ___name, ___log_var) \ CREATE_TRACE_EVAL_DEF(__klass, ___name, __VA_ARGS__) CREATE_TRACE_DECL(timestampMessageCreation, const Time&t, uint64 packetId, MessagePath path, ObjectMessagePort optionalMessageSourcePort=0, ObjectMessagePort optionalMessageDestPort=0); CREATE_TRACE_DECL(timestampMessage, const Time&t, uint64 packetId, MessagePath path); void writeRecord(uint16 type_hint, BatchedBuffer::IOVec* data, uint32 iovcnt); template<typename T> void writeRecord(uint16 type_hint, const T& pl) { if (mShuttingDown) return; std::string serialized_pl; bool serialized_success = pl.SerializeToString(&serialized_pl); assert(serialized_success); const uint32 num_data = 1; BatchedBuffer::IOVec data_vec[num_data] = { BatchedBuffer::IOVec(&(serialized_pl[0]), serialized_pl.size()) }; writeRecord(type_hint, data_vec, num_data); } public: void prepareShutdown(); void shutdown(); private: void storageThread(const String& filename); BatchedBuffer data; bool mShuttingDown; Thread* mStorageThread; Sirikata::AtomicValue<bool> mFinishStorage; static OptionValue* mLogMessage; }; } #define TRACE(___trace, ___name, ...) \ { \ if ( ___trace-> check ## ___name () ) \ ___trace-> ___name ( __VA_ARGS__ ); \ } while(0) #define CONTEXT_TRACE(___name, ...) \ TRACE( mContext->trace(), ___name, mContext->simTime(), __VA_ARGS__) #define CONTEXT_TRACE_NO_TIME(___name, ...) \ TRACE( mContext->trace(), ___name, __VA_ARGS__) } #ifdef CBR_TIMESTAMP_PACKETS #define TIMESTAMP_FULL(trace, time, packetId, path) TRACE(trace, timestampMessage, time, packetId, path) #define TIMESTAMP_SIMPLE(packetId, path) TIMESTAMP_FULL(mContext->trace(), mContext->simTime(), packetId, path) #define TIMESTAMP(packet, path) TIMESTAMP_SIMPLE(packet->unique(), path) #define TIMESTAMP_START(prefix, packet) \ Sirikata::uint64 prefix ## _uniq = packet->unique(); #define TIMESTAMP_END(prefix, path) TIMESTAMP_SIMPLE(prefix ## _uniq, path) #define TIMESTAMP_PAYLOAD(packet, path) TIMESTAMP_SIMPLE(packet->payload_id(), path) #define TIMESTAMP_PAYLOAD_START(prefix, packet) \ Sirikata::uint64 prefix ## _uniq = packet->payload_id(); #define TIMESTAMP_PAYLOAD_END(prefix, path) TIMESTAMP_SIMPLE(prefix ## _uniq, path) #define TIMESTAMP_CREATED(packet, path) TRACE(mContext->trace(), timestampMessageCreation, mContext->simTime(), packet->unique(), path, packet->source_port(), packet->dest_port()) #else #define TIMESTAMP_FULL(trace, time, packetId, path) #define TIMESTAMP_SIMPLE(packetId, path) #define TIMESTAMP(packet, path) #define TIMESTAMP_START(prefix, packet) #define TIMESTAMP_END(prefix, path) #define TIMESTAMP_PAYLOAD(packet, path) #define TIMESTAMP_PAYLOAD_START(prefix, packet) #define TIMESTAMP_PAYLOAD_END(prefix, path) #define TIMESTAMP_CREATED(packet, path) #endif #endif
#ifndef _SIRIKATA_CORE_TRACE_HPP_ #define _SIRIKATA_CORE_TRACE_HPP_ #include <sirikata/core/util/Platform.hpp> #include <sirikata/core/util/Thread.hpp> #include <sirikata/core/util/AtomicTypes.hpp> #include <sirikata/core/network/ObjectMessage.hpp> #include <sirikata/core/trace/BatchedBuffer.hpp> namespace Sirikata { namespace Trace { #define TRACE_DROP(nam) ((mContext->trace()->drops.n[::Sirikata::Trace::Drops::nam]=#nam )&&++(mContext->trace()->drops.d[::Sirikata::Trace::Drops::nam])); SILOG(drop,insane,#nam) struct Drops { enum { OH_DROPPED_AT_SEND, OH_DROPPED_AT_RECEIVE_QUEUE, SPACE_DROPPED_AT_MAIN_STRAND_CROSSING, DROPPED_AT_FORWARDED_LOCALLY, DROPPED_DURING_FORWARDING,
ObjectMessagePort optionalMessageDestPort=0); CREATE_TRACE_DECL(timestampMessage, const Time&t, uint64 packetId, MessagePath path); void writeRecord(uint16 type_hint, BatchedBuffer::IOVec* data, uint32 iovcnt); template<typename T> void writeRecord(uint16 type_hint, const T& pl) { if (mShuttingDown) return; std::string serialized_pl; bool serialized_success = pl.SerializeToString(&serialized_pl); assert(serialized_success); const uint32 num_data = 1; BatchedBuffer::IOVec data_vec[num_data] = { BatchedBuffer::IOVec(&(serialized_pl[0]), serialized_pl.size()) }; writeRecord(type_hint, data_vec, num_data); } public: void prepareShutdown(); void shutdown(); private: void storageThread(const String& filename); BatchedBuffer data; bool mShuttingDown; Thread* mStorageThread; Sirikata::AtomicValue<bool> mFinishStorage; static OptionValue* mLogMessage; }; } #define TRACE(___trace, ___name, ...) \ { \ if ( ___trace-> check ## ___name () ) \ ___trace-> ___name ( __VA_ARGS__ ); \ } while(0) #define CONTEXT_TRACE(___name, ...) \ TRACE( mContext->trace(), ___name, mContext->simTime(), __VA_ARGS__) #define CONTEXT_TRACE_NO_TIME(___name, ...) \ TRACE( mContext->trace(), ___name, __VA_ARGS__) } #ifdef CBR_TIMESTAMP_PACKETS #define TIMESTAMP_FULL(trace, time, packetId, path) TRACE(trace, timestampMessage, time, packetId, path) #define TIMESTAMP_SIMPLE(packetId, path) TIMESTAMP_FULL(mContext->trace(), mContext->simTime(), packetId, path) #define TIMESTAMP(packet, path) TIMESTAMP_SIMPLE(packet->unique(), path) #define TIMESTAMP_START(prefix, packet) \ Sirikata::uint64 prefix ## _uniq = packet->unique(); #define TIMESTAMP_END(prefix, path) TIMESTAMP_SIMPLE(prefix ## _uniq, path) #define TIMESTAMP_PAYLOAD(packet, path) TIMESTAMP_SIMPLE(packet->payload_id(), path) #define TIMESTAMP_PAYLOAD_START(prefix, packet) \ Sirikata::uint64 prefix ## _uniq = packet->payload_id(); #define TIMESTAMP_PAYLOAD_END(prefix, path) TIMESTAMP_SIMPLE(prefix ## _uniq, path) #define TIMESTAMP_CREATED(packet, path) TRACE(mContext->trace(), timestampMessageCreation, mContext->simTime(), packet->unique(), path, packet->source_port(), packet->dest_port()) #else #define TIMESTAMP_FULL(trace, time, packetId, path) #define TIMESTAMP_SIMPLE(packetId, path) #define TIMESTAMP(packet, path) #define TIMESTAMP_START(prefix, packet) #define TIMESTAMP_END(prefix, path) #define TIMESTAMP_PAYLOAD(packet, path) #define TIMESTAMP_PAYLOAD_START(prefix, packet) #define TIMESTAMP_PAYLOAD_END(prefix, path) #define TIMESTAMP_CREATED(packet, path) #endif #endif
DROPPED_DURING_FORWARDING_ROUTING, DROPPED_AT_SPACE_ENQUEUED, DROPPED_CSFQ_OVERFLOW, DROPPED_CSFQ_PROBABILISTIC, NUM_DROPS }; uint64 d[NUM_DROPS]; const char*n[NUM_DROPS]; Drops() { memset(d,0,NUM_DROPS*sizeof(uint64)); memset(n,0,NUM_DROPS*sizeof(const char*)); } void output(); }; #define ProximityTag 0 #define ObjectLocationTag 1 #define ServerDatagramQueuedTag 4 #define ServerDatagramSentTag 5 #define ServerDatagramReceivedTag 6 #define SegmentationChangeTag 10 #define MigrationBeginTag 11 #define MigrationAckTag 12 #define MigrationRoundTripTag 18 #define ServerLocationTag 13 #define ServerObjectEventTag 14 #define ObjectSegmentationCraqLookupRequestAnalysisTag 15 #define ObjectSegmentationProcessedRequestAnalysisTag 16 #define ObjectPingTag 17 #define ObjectPingCreatedTag 32 #define ObjectHitPointTag 34 #define OSegTrackedSetResultAnalysisTag 19 #define OSegShutdownEventTag 20 #define ObjectGeneratedLocationTag 22 #define OSegCacheResponseTag 23 #define OSegLookupNotOnServerAnalysisTag 24 #define OSegCumulativeTraceAnalysisTag 25 #define MessageTimestampTag 30 #define MessageCreationTimestampTag 31 #define ObjectConnectedTag 33 enum MessagePath { NONE, CREATED, DESTROYED, OH_HIT_NETWORK, OH_DROPPED_AT_SEND, OH_NET_RECEIVED, OH_DROPPED_AT_RECEIVE_QUEUE, OH_RECEIVED, SPACE_DROPPED_AT_MAIN_STRAND_CROSSING, HANDLE_OBJECT_HOST_MESSAGE, HANDLE_SPACE_MESSAGE, FORWARDED_LOCALLY, DROPPED_AT_FORWARDED_LOCALLY, FORWARDING_STARTED, FORWARDED_LOCALLY_SLOW_PATH, DROPPED_DURING_FORWARDING, OSEG_CACHE_CHECK_STARTED, OSEG_CACHE_CHECK_FINISHED, OSEG_LOOKUP_STARTED, OSEG_CACHE_LOOKUP_FINISHED, OSEG_SERVER_LOOKUP_FINISHED, OSEG_LOOKUP_FINISHED, SPACE_TO_SPACE_ENQUEUED, DROPPED_AT_SPACE_ENQUEUED, SPACE_TO_SPACE_HIT_NETWORK, SPACE_TO_SPACE_READ_FROM_NET, SPACE_TO_SPACE_SMR_DEQUEUED, SPACE_TO_OH_ENQUEUED, NUM_PATHS }; class SIRIKATA_EXPORT Trace { public: Drops drops; ~Trace(); static void InitOptions(); Trace(const String& filename); #define CREATE_TRACE_CHECK_DECL(___name) \ bool check ## ___name () const; #define CREATE_TRACE_EVAL_DECL(___name, ...) \ void ___name( __VA_ARGS__ ); #define CREATE_TRACE_DECL(___name, ...) \ CREATE_TRACE_CHECK_DECL(___name) \ CREATE_TRACE_EVAL_DECL(___name, __VA_ARGS__) #define CREATE_TRACE_CHECK_DEF(__klass, ___name , ___log_var) \ bool __klass :: check ## ___name () const { \ return ___log_var->as<bool>(); \ } #define CREATE_TRACE_EVAL_DEF(__klass, ___name , ... ) \ void __klass :: ___name ( __VA_ARGS__ ) #define CREATE_TRACE_DEF(__klass, ___name , ___log_var, ... ) \ CREATE_TRACE_CHECK_DEF(__klass, ___name, ___log_var) \ CREATE_TRACE_EVAL_DEF(__klass, ___name, __VA_ARGS__) CREATE_TRACE_DECL(timestampMessageCreation, const Time&t, uint64 packetId, MessagePath path, ObjectMessagePort optionalMessageSourcePort=0,
random
[ { "content": "struct Batch {\n\n static const uint16 max_size = 65535;\n\n uint16 size;\n\n T items[max_size];\n\n\n\n Batch() : size(0) {}\n\n\n\n bool full() const {\n\n return (size >= max_size);\n\n }\n\n\n\n uint32 avail() const {\n\n return max_size - size;\n\n }\n\n};\n\n\n", "file_path": "libcore/include/sirikata/core/trace/BatchedBuffer.hpp", "rank": 2, "score": 250334.88444448687 }, { "content": "enum Type {\n\n Timer,\n\n Audio,\n\n Video,\n\n CD,\n\n Joystick,\n\n NumSubsystems\n\n};\n\n} // namespace Subsystem\n\n\n\n/** Initialize a single subsystem. Equivalent to SDL_InitSubsystem. Will invoke\n\n * Initialize() if necessary. Like SDL_InitSubsystem, returns 0 on\n\n * success, -1 in case of error.\n\n */\n\nint SIRIKATA_SDL_FUNCTION_EXPORT InitializeSubsystem(Subsystem::Type sub);\n\n\n\n/** Destroy a single subsystem. Equivalent to SDL_QuitSubsystem except that it\n\n * only passes the request to SDL when all InitializeSubsystem calls have been\n\n * matched.\n\n */\n\nvoid SIRIKATA_SDL_FUNCTION_EXPORT QuitSubsystem(Subsystem::Type sub);\n\n\n\n} // namespace SDL\n\n} // namespace Sirikata\n\n\n\n#endif //_SIRIKATA_LIBSDL_SDL_HPP_\n", "file_path": "libsdl/include/sirikata/sdl/SDL.hpp", "rank": 4, "score": 206414.53981551918 }, { "content": "struct Meshdata;\n\ntypedef std::tr1::shared_ptr<Meshdata> MeshdataPtr;\n\ntypedef std::tr1::weak_ptr<Meshdata> MeshdataWPtr;\n\n\n\n/** Represents a skinned animation. A skinned animation is directly associated\n\n * with a SubMeshGeometry.\n\n */\n", "file_path": "libmesh/include/sirikata/mesh/Meshdata.hpp", "rank": 5, "score": 206228.1018005848 }, { "content": "enum Type {\n\n INT,\n\n HUP,\n\n ABORT,\n\n TERM,\n\n KILL\n\n};\n\n\n\ntypedef std::tr1::function<void(Type)> Handler;\n\ntypedef int32 HandlerID;\n\n\n\nSIRIKATA_EXPORT HandlerID registerHandler(Handler handler);\n\nSIRIKATA_EXPORT void unregisterHandler(HandlerID& handler);\n\n\n\nSIRIKATA_EXPORT String typeAsString(Type t);\n\n\n\n} // namespace Signal\n\n} // namespace Sirikata\n\n\n\n#endif //_SIRIKATA_CORE_SERVICE_SIGNAL_HPP_\n", "file_path": "libcore/include/sirikata/core/service/Signal.hpp", "rank": 6, "score": 201385.44947303084 }, { "content": "enum Code {\n\n Requested,\n\n LoginDenied,\n\n Forced\n\n};\n\n\n\n} // namespace Disconnect\n\n} // namespace Sirikata\n\n\n\n#endif //_SIRIKATA_OH_DISCONNECT_CODES_HPP_\n", "file_path": "liboh/include/sirikata/oh/DisconnectCodes.hpp", "rank": 7, "score": 201385.44947303084 }, { "content": "enum Key {\n\n PATH_START = 0,\n\n\n\n // Full path to executable file\n\n FILE_EXE,\n\n // Full path to executable file's directory\n\n DIR_EXE,\n\n // Full path to executable file's bundle. On most platform's this is\n\n // equivalent to DIR_EXE. On OS X, it gives the directory of the .app\n\n // containing the binary when it is located in one.\n\n DIR_EXE_BUNDLE,\n\n // Full path to current directory\n\n DIR_CURRENT,\n\n // Full path to a user-specific directory, e.g. /home/username\n\n DIR_USER,\n\n // Full path to a hidden directory in a user-specific location,\n\n // e.g. /home/username/.sirikata\n\n DIR_USER_HIDDEN,\n\n // Full path to temporary directory, e.g. under /tmp\n\n DIR_TEMP,\n", "file_path": "libcore/include/sirikata/core/util/Paths.hpp", "rank": 8, "score": 201385.44947303084 }, { "content": "enum Tier\n\n{\n\n\tTIER_BACK = 0,\n\n\tTIER_MIDDLE,\n\n\tTIER_FRONT\n\n};\n\n\n", "file_path": "libogre/include/sirikata/ogre/ViewportOverlay.hpp", "rank": 9, "score": 201385.44947303084 }, { "content": "class Trace;\n\n}\n\n\n\nnamespace Command {\n", "file_path": "libcore/include/sirikata/core/service/Context.hpp", "rank": 10, "score": 201364.52324800068 }, { "content": "struct uuid;\n\n}\n\n}\n\n\n\nnamespace Sirikata {\n", "file_path": "libcore/include/sirikata/core/util/UUID.hpp", "rank": 11, "score": 201202.27414321684 }, { "content": "// A scene graph node. Contains a transformation, set of children nodes,\n\n// camera instances, geometry instances, skin controller instances, light\n\n// instances, and instances of other nodes.\n\nstruct SIRIKATA_MESH_EXPORT Node {\n\n Node();\n\n Node(NodeIndex par, const Matrix4x4f& xform);\n\n Node(const Matrix4x4f& xform);\n\n\n\n bool containsInstanceController;\n\n\n\n // Parent node in the actual hierarchy (not instantiated).\n\n NodeIndex parent;\n\n // Transformation to apply when traversing this node.\n\n Matrix4x4f transform;\n\n // Direct children, i.e. they are contained by this node directly and their\n\n // parent NodeIndex will reflect that.\n\n NodeIndexList children;\n\n // Instantiations of other nodes (and their children) into this\n\n // subtree. Because they are instantiations, their\n\n // instanceChildren[i]->parent != this node's index.\n\n NodeIndexList instanceChildren;\n\n\n\n // Map of name -> animation curve.\n\n typedef std::map<String, TransformationKeyFrames> AnimationMap;\n\n AnimationMap animations;\n\n};\n\ntypedef std::vector<Node> NodeList;\n\n\n", "file_path": "libmesh/include/sirikata/mesh/Meshdata.hpp", "rank": 12, "score": 200836.7016430123 }, { "content": "struct SIRIKATA_EXPORT Frame {\n\n /** Writes the data to the stream as a message. */\n\n static std::string write(const void* data, uint32 len);\n\n static std::string write(const std::string& data);\n\n\n\n /** Checks if a full message is available. Returns the contents and removes\n\n * them from the argument if it has a whole packet; returns an empty string\n\n * and does nothing to the argument if it does not have a whole packet.\n\n */\n\n static std::string parse(std::string& data);\n\n};\n\n\n\n} // namespace Network\n\n} // namespace Frame\n\n\n\n#endif //_SIRIKATA_LIBCORE_NETWORK_FRAME_HPP_\n", "file_path": "libcore/include/sirikata/core/network/Frame.hpp", "rank": 13, "score": 200836.7016430123 }, { "content": "//Stores progressive mesh information\n\nstruct SIRIKATA_MESH_EXPORT ProgressiveData {\n\n //The hash of the progressive stream\n\n Transfer::Fingerprint progressiveHash;\n\n //The number of triangles in the progressive stream\n\n\tuint32 numProgressiveTriangles;\n\n\t//Maps the names of mipmap archives to the mipmap archive data\n\n\tProgressiveMipmapMap mipmaps;\n\n};\n\ntypedef std::tr1::shared_ptr<ProgressiveData> ProgressiveDataPtr;\n\n\n", "file_path": "libmesh/include/sirikata/mesh/Meshdata.hpp", "rank": 14, "score": 196804.6892944746 }, { "content": "struct SIRIKATA_MESH_EXPORT LightInstance {\n\n int lightIndex; // Index in LightInfoList\n\n NodeIndex parentNode; // Index of node holding this instance\n\n};\n\ntypedef std::vector<LightInstance> LightInstanceList;\n\n\n", "file_path": "libmesh/include/sirikata/mesh/Meshdata.hpp", "rank": 15, "score": 196804.6892944746 }, { "content": "struct SIRIKATA_MESH_EXPORT SkinController {\n\n // Joints for this controls Indexes into the Meshdata.joints array\n\n // (which indexes into Meshdata.nodes).\n\n std::vector<uint32> joints;\n\n\n\n Matrix4x4f bindShapeMatrix;\n\n ///n+1 elements where n is the number of vertices, so that we can do simple\n\n ///subtraction to find out how many joints influence each vertex\n\n std::vector<unsigned int> weightStartIndices;\n\n // weights and jointIndices are the same size and are a sparse\n\n // representation of the (vertex,bone) = weight matrix: the\n\n // weightStartIndices let you figure out the range in these arrays that\n\n // correspond to a single vertex. In that range, each pair represents the\n\n // weight for one joint for the current vertex, with the rest of the joints\n\n // having weight 0.\n\n std::vector<float> weights;\n\n std::vector<unsigned int>jointIndices;\n\n // One inverse bind matrix per joint.\n\n std::vector<Matrix4x4f> inverseBindMatrices;\n\n};\n\ntypedef std::vector<SkinController> SkinControllerList;\n\n\n", "file_path": "libmesh/include/sirikata/mesh/Meshdata.hpp", "rank": 16, "score": 196804.6892944746 }, { "content": "// Component specification, specified in section B.2.2.\n\nstruct SIRIKATA_EXPORT component {\n\n\tint h; // Horizontal sampling factor.\n\n\tint v; // Vertical sampling factor.\n\n\tuint8 c; // Component identifier.\n\n\tuint8 tq; // Quantization table destination selector.\n\n component() {\n\n memset(this, 0, sizeof(component));\n\n }\n\n};\n\n\n\n\n", "file_path": "libcore/include/sirikata/core/jpeg-arhc/Decoder.hpp", "rank": 17, "score": 196804.6892944746 }, { "content": "struct SIRIKATA_MESH_EXPORT GeometryInstance {\n\n typedef std::map<SubMeshGeometry::Primitive::MaterialId,size_t> MaterialBindingMap;\n\n MaterialBindingMap materialBindingMap;//maps materialIndex to offset in Meshdata's materials\n\n unsigned int geometryIndex; // Index in SubMeshGeometryList\n\n NodeIndex parentNode; // Index of node holding this instance\n\n\n\n /** Compute the bounds of this instance with the given transform. This is\n\n * more precise, and much more expensive, than transforming the\n\n * SubMeshGeometry's bounds.\n\n */\n\n BoundingBox3f3f computeTransformedBounds(MeshdataPtr parent, const Matrix4x4f& xform) const;\n\n BoundingBox3f3f computeTransformedBounds(const Meshdata& parent, const Matrix4x4f& xform) const;\n\n void computeTransformedBounds(MeshdataPtr parent, const Matrix4x4f& xform, BoundingBox3f3f* bounds_out, double* radius_out) const;\n\n void computeTransformedBounds(const Meshdata& parent, const Matrix4x4f& xform, BoundingBox3f3f* bounds_out, double* radius_out) const;\n\n};\n\ntypedef std::vector<GeometryInstance> GeometryInstanceList;\n\n\n", "file_path": "libmesh/include/sirikata/mesh/Meshdata.hpp", "rank": 18, "score": 196804.6892944746 }, { "content": "/// Indicates which combination of reliability and ordered-ness should be used.\n\nenum StreamReliability {\n\n Unreliable,\n\n ReliableUnordered,\n\n ReliableOrdered\n\n};\n\n\n\n/** Stream interface for network connections.\n\n *\n\n * Streams are lightweight communication primitives, backed by a shared connection.\n\n * An individual stream is a reliable, ordered stream of arbitrarily sized messages.\n\n * The stream only returns full messages to the user.\n\n *\n\n * Streams can be created or cloned efficiently and can start accepting data without\n\n * having to first go through a connection procedure. When substreams are created by\n\n * the remote endpoint, the user is notified via a callback. Data can be sent from\n\n * any thread. Data is received via a callback, but the user can pause callbacks if\n\n * they cannot handle the rate of callbacks provided by the Stream.\n\n *\n\n * Note that substreams may outlast their parent streams. In this case, further substream\n\n * callbacks are dispatched to the original callback.\n\n */\n", "file_path": "libcore/include/sirikata/core/network/Stream.hpp", "rank": 19, "score": 196646.64867547335 }, { "content": "enum LOGGING_LEVEL {\n\n fatal=1,\n\n error=8,\n\n warning=64,\n\n warn=warning,\n\n info=512,\n\n debug=4096,\n\n detailed=8192,\n\n insane=32768\n\n};\n\n\n\nSIRIKATA_FUNCTION_EXPORT const String& LogModuleString(const char* base);\n\nSIRIKATA_FUNCTION_EXPORT const char* LogLevelString(LOGGING_LEVEL lvl, const char* lvl_as_string);\n\n\n\n// Public so the macros work efficiently instead of another call\n\nextern \"C\" SIRIKATA_EXPORT std::ostream* SirikataLogStream;\n\n\n\n/** Set the output file pointer for *all* output, not just SILOG output. This\n\n * includes both stdout and stderr.\n\n */\n", "file_path": "libcore/include/sirikata/core/util/Logging.hpp", "rank": 20, "score": 196646.64867547335 }, { "content": "enum RelativePosition\n\n{\n\n\tRP_LEFT,\n\n\tRP_TOPLEFT,\n\n\tRP_TOPCENTER,\n\n\tRP_TOPRIGHT,\n\n\tRP_RIGHT,\n\n\tRP_BOTTOMRIGHT,\n\n\tRP_BOTTOMCENTER,\n\n\tRP_BOTTOMLEFT,\n\n\tRP_CENTER\n\n};\n\n\n\n/**\n\n* Describes the position of a viewport-overlay in relative/absolute metrics.\n\n* Used by WebViewListener and ProxyWebViewObject.\n\n*/\n", "file_path": "libogre/include/sirikata/ogre/OverlayPosition.hpp", "rank": 21, "score": 196646.64867547335 }, { "content": "enum Axes {\n\n AXIS_CURSORX,\n\n AXIS_CURSORY,\n\n AXIS_RELX,\n\n AXIS_RELY,\n\n NUM_POINTER_AXES\n\n};\n\n\n\ntypedef uint32 AxisIndex;\n\n\n\ntypedef int32 MouseButton;\n\n\n\ntypedef int32 KeyButton;\n\n\n", "file_path": "libogre/include/sirikata/ogre/input/InputDevice.hpp", "rank": 22, "score": 196646.64867547335 }, { "content": "#if SIRIKATA_PLATFORM == SIRIKATA_PLATFORM_WINDOWS\n\nstruct HINSTANCE__;\n\n# define DL_HANDLE struct HINSTANCE__*\n\n#elif SIRIKATA_PLATFORM == SIRIKATA_PLATFORM_MAC || SIRIKATA_PLATFORM == SIRIKATA_PLATFORM_LINUX\n\n# define DL_HANDLE void*\n\n#endif\n\n\n\nnamespace Sirikata {\n\n\n\n/** DynamicLibrary represents a dynamically loadable module. This only handles\n\n * loading, unloading, and symbol lookup. This presumes nothing about the\n\n * interface provided by the module.\n\n */\n", "file_path": "libcore/include/sirikata/core/util/DynamicLibrary.hpp", "rank": 23, "score": 196474.5129660967 }, { "content": "struct SegmentationInfo {\n\n ServerID server;\n\n BoundingBoxList region;\n\n};\n\n\n", "file_path": "libcore/include/sirikata/core/util/Platform.hpp", "rank": 24, "score": 196466.54770181485 }, { "content": "struct LightInfo;\n\ntypedef std::tr1::shared_ptr<ProxyObject> ProxyObjectPtr;\n\n\n", "file_path": "liboh/include/sirikata/oh/HostedObject.hpp", "rank": 25, "score": 196466.54770181485 }, { "content": "// maxCodeLength is the maximum (inclusive) number of bits in a Huffman code.\n\n// huffman is a Huffman decoder, specified in section C.\n\nstruct huffman {\n\n enum {\n\n maxCodeLength = 16,\n\n \n\n // maxNCodes is the maximum (inclusive) number of codes in a Huffman tree.\n\n maxNCodes = 256,\n\n \n\n // lutSize is the log-2 size of the Huffman decoder's look-up table.\n\n lutSize = 8\n\n };\n\n\t// length is the number of codes in the tree.\n\n\tint32 nCodes;\n\n\t// lut is the look-up table for the next lutSize bits in the bit-stream.\n\n\t// The high 8 bits of the uint16 are the encoded value. The low 8 bits\n\n\t// are 1 plus the code length, or 0 if the value is too large to fit in\n\n\t// lutSize bits.\n\n\tuint16 lut [1 << lutSize];\n\n\t// vals are the decoded values, sorted by their encoding.\n\n\tuint8 vals [maxNCodes];\n\n\t// minCodes[i] is the minimum code of length i, or -1 if there are no\n", "file_path": "libcore/include/sirikata/core/jpeg-arhc/Huffman.hpp", "rank": 26, "score": 196466.54770181485 }, { "content": "struct TimerImpl;\n\n\n", "file_path": "libcore/include/sirikata/core/util/Timer.hpp", "rank": 27, "score": 196466.54770181485 }, { "content": "struct SIRIKATA_MESH_EXPORT LightInfo {\n\n enum LightTypes {\n\n POINT,SPOTLIGHT,DIRECTIONAL,NUM_TYPES//defaults to point=0?\n\n };\n\n enum Fields {\n\n NONE=0,\n\n DIFFUSE_COLOR=1,\n\n SPECULAR_COLOR=2,\n\n POWER=8,\n\n AMBIENT_COLOR=16,\n\n SHADOW_COLOR=32,\n\n LIGHT_RANGE=64,\n\n FALLOFF=128,\n\n CONE=256,\n\n TYPE=512,\n\n CAST_SHADOW=1024,\n\n ALL=2047\n\n };\n\n int32 mWhichFields;\n\n LightInfo() :\n", "file_path": "libmesh/include/sirikata/mesh/LightInfo.hpp", "rank": 28, "score": 192965.57725044503 }, { "content": "//Information about an archive of mipmaps\n\nstruct SIRIKATA_MESH_EXPORT ProgressiveMipmapArchive {\n\n //Contains the list of mipmap levels\n\n ProgressiveMipmaps mipmaps;\n\n //The name of the image in the mesh that references this\n\n std::string name;\n\n //The hash of the mipmap archive\n\n Transfer::Fingerprint archiveHash;\n\n};\n\n//A map containing the names of mipmap archives\n\ntypedef std::map<std::string, ProgressiveMipmapArchive> ProgressiveMipmapMap;\n", "file_path": "libmesh/include/sirikata/mesh/Meshdata.hpp", "rank": 29, "score": 192965.57725044503 }, { "content": "struct SIRIKATA_MESH_EXPORT InstanceSkinAnimation {\n\n};\n\n\n\n/** Represents a series of key frames */\n", "file_path": "libmesh/include/sirikata/mesh/Meshdata.hpp", "rank": 30, "score": 192965.57725044503 }, { "content": "struct SIRIKATA_MESH_EXPORT SubMeshGeometry {\n\n std::string name;\n\n\n\n std::vector<Sirikata::Vector3f> positions;\n\n std::vector<Sirikata::Vector3f> normals;\n\n std::vector<Sirikata::Vector3f> tangents;\n\n std::vector<Sirikata::Vector4f> colors;\n\n\n\n struct TextureSet {\n\n unsigned int stride;\n\n std::vector<float> uvs;\n\n };\n\n std::vector<TextureSet>texUVs;\n\n struct Primitive {\n\n std::vector<unsigned short> indices;\n\n\n\n enum PrimitiveType {\n\n TRIANGLES,\n\n LINES,\n\n POINTS,\n", "file_path": "libmesh/include/sirikata/mesh/Meshdata.hpp", "rank": 31, "score": 192965.57725044503 }, { "content": "struct SIRIKATA_MESH_EXPORT MaterialEffectInfo {\n\n struct Texture {\n\n std::string uri;\n\n Vector4f color;//color while the texture is pulled in, or if the texture is 404'd\n\n size_t texCoord;\n\n enum Affecting {\n\n DIFFUSE,\n\n SPECULAR,\n\n EMISSION,\n\n AMBIENT,\n\n REFLECTIVE,\n\n OPACITY,\n\n\n\n }affecting;\n\n enum SamplerType\n\n {\n\n\t\t\tSAMPLER_TYPE_UNSPECIFIED,\n\n\t\t\tSAMPLER_TYPE_1D,\n\n\t\t\tSAMPLER_TYPE_2D,\n\n\t\t\tSAMPLER_TYPE_3D,\n", "file_path": "libmesh/include/sirikata/mesh/Meshdata.hpp", "rank": 32, "score": 192965.57725044503 }, { "content": "struct SIRIKATA_MESH_EXPORT TransformationKeyFrames {\n\n typedef std::vector<float> TimeList;\n\n TimeList inputs;\n\n typedef std::vector<Matrix4x4f> TransformationList;\n\n TransformationList outputs;\n\n};\n\n\n", "file_path": "libmesh/include/sirikata/mesh/Meshdata.hpp", "rank": 33, "score": 192965.57725044503 }, { "content": "//Stores information about a single mipmap level\n\nstruct SIRIKATA_MESH_EXPORT ProgressiveMipmapLevel {\n\n //Offset within the tar file of the mipmap\n\n uint32 offset;\n\n //Length of the mipmap file within the tar file\n\n uint32 length;\n\n //Width of the mipmap image\n\n uint32 width;\n\n //Height of the mipmap image\n\n uint32 height;\n\n};\n\n//A map containing mipmap levels in an archive\n\ntypedef std::map<uint32, ProgressiveMipmapLevel> ProgressiveMipmaps;\n", "file_path": "libmesh/include/sirikata/mesh/Meshdata.hpp", "rank": 34, "score": 192965.57725044503 }, { "content": "enum PointerModifiers {\n\n //POINTER_STYLUS = 0, // default\n\n POINTER_ERASER = (1<<0),\n\n POINTER_CURSOR = (1<<1)\n\n};\n\n\n", "file_path": "libogre/include/sirikata/ogre/input/InputDevice.hpp", "rank": 35, "score": 192173.70829911422 }, { "content": "enum KeyboardModifiers {\n\n MOD_NONE = 0,\n\n MOD_SHIFT = 1,\n\n MOD_CTRL = 2,\n\n MOD_ALT = 4,\n\n MOD_GUI = 8\n\n};\n", "file_path": "libogre/include/sirikata/ogre/input/InputDevice.hpp", "rank": 36, "score": 192173.70829911422 }, { "content": "enum KeyEvent {\n\n KEY_PRESSED,\n\n KEY_DOWN,\n\n KEY_RELEASED,\n\n KEY_REPEATED\n\n};\n\n\n\n/** The three types of drag events. The START event will only be\n\n triggered once the motion is determined to be a drag (exceeded\n\n some number of pixels). The END event happens at the time the\n\n mouse button is released (mPressure == 0)\n\n\n\n The DRAG_END event Will not be called on release if still in\n\n the DRAG_DEADBAND state -- in this case, see MouseClickEvent.\n\n*/\n", "file_path": "libogre/include/sirikata/ogre/input/InputDevice.hpp", "rank": 37, "score": 192173.70829911422 }, { "content": "#define NullServerID 0\n\nstruct ServerIDNull {\n\n ServerID operator()() {\n\n return NullServerID;\n\n };\n\n};\n", "file_path": "libcore/include/sirikata/core/util/Platform.hpp", "rank": 38, "score": 192003.67064582618 }, { "content": "struct MethodSizeFunctor {\n\n uint32 operator()(const ElementType& e) const {\n\n return e.size();\n\n }\n\n};\n\n\n\ntemplate<typename ElementType>\n", "file_path": "libcore/include/sirikata/core/queue/Queue.hpp", "rank": 39, "score": 191996.50920134512 }, { "content": "struct AxisValue {\n\n float value;\n\n float get01() const {\n\n return (value + 1.0f)/2.0f;\n\n }\n\n float getCentered() const {\n\n return value;\n\n }\n\n static AxisValue fromCentered(float val) {\n\n AxisValue ret = {val};\n\n return ret;\n\n }\n\n static AxisValue from01(float val) {\n\n AxisValue ret = {(val-0.5f)*2.0f};\n\n return ret;\n\n }\n\n static AxisValue null() {\n\n return fromCentered(0.0f);\n\n }\n\n\n", "file_path": "libogre/include/sirikata/ogre/input/InputDevice.hpp", "rank": 40, "score": 191996.50920134512 }, { "content": "struct ObjectHostID {\n\n ObjectHostID()\n\n : id(0)\n\n {\n\n }\n\n\n\n explicit ObjectHostID(uint64 _id)\n\n : id(_id)\n\n {\n\n }\n\n\n\n uint64 id;\n\n};\n\n\n\nSIRIKATA_FUNCTION_EXPORT uint32 uint32_lexical_cast(const String& rhs);\n\nSIRIKATA_FUNCTION_EXPORT std::ostream& operator<<(std::ostream& os, const ObjectHostID& rhs);\n\nSIRIKATA_FUNCTION_EXPORT std::istream& operator>>(std::istream& is, ObjectHostID& rhs);\n\n\n\n} // namespace Sirikata\n\n\n", "file_path": "libcore/include/sirikata/core/util/Platform.hpp", "rank": 41, "score": 191996.50920134512 }, { "content": "struct ServerIDRandom {\n\n ServerID operator()() {\n\n // Because ServerIDs aren't really random (we start allocating linearly\n\n // from 1), this just tries to generate one that won't conflict by\n\n // choosing a large number ( > 1,000,000).\n\n return (1 << 20) + (rand() % (1 << 20));\n\n };\n\n};\n\n\n\n// Space Server Regions\n\ntypedef std::vector<BoundingBox3f> BoundingBoxList;\n", "file_path": "libcore/include/sirikata/core/util/Platform.hpp", "rank": 42, "score": 191996.50920134512 }, { "content": "struct JpegBlock {\n\n enum {\n\n blockSize = 64\n\n };\n\n int32 block[blockSize];\n\n JpegBlock() {\n\n memset(this, 0, sizeof(JpegBlock));\n\n }\n\n int32& operator[](const uint32 offset) {\n\n assert(offset < blockSize);\n\n return block[offset];\n\n }\n\n int32 operator[](const uint32 offset) const {\n\n assert(offset < blockSize);\n\n return block[offset];\n\n }\n\n};\n\n\n\n\n", "file_path": "libcore/include/sirikata/core/jpeg-arhc/Decoder.hpp", "rank": 43, "score": 191996.50920134512 }, { "content": "struct SIRIKATA_EXPORT BitByteStream {\n\n std::vector<uint8, JpegAllocator<uint8_t> > buffer;\n\n\tuint32 bits;\n\n\tuint8 nBits;\n\n\tuint32 bitReadCursor;\n\n BitByteStream(const JpegAllocator<uint8>&alloc=JpegAllocator<uint8>());\n\n void appendByte(uint8 x);\n\n void appendBytes(uint8*bytes, uint32 nBytes);\n\n void clear();\n\n void flushToWriter(DecoderWriter&);\n\n void emitBits(uint16 bits, uint8 nBits, bool stuffZeros);\n\n std::pair<uint32, JpegError> scanBits(uint32 nBits, bool stuffZeros);\n\n std::pair<uint32, JpegError> scanBitsNoStuffedZeros(uint32 nBits);\n\n std::pair<uint8, JpegError> scanAlignedByte();\n\n void pop();\n\n uint32 len() const;\n\n uint32 estimatedByteSize()const;\n\n void flushBits(bool stuffBits);\n\n};\n\n\n", "file_path": "libcore/include/sirikata/core/jpeg-arhc/Decoder.hpp", "rank": 44, "score": 189305.4721981277 }, { "content": "#!/usr/bin/python\n\n\n\n'''\n\nReads file generated through\n\nSirikata::Network::IOService::reportAllStats(filename,detailed) and\n\nparses its contents to track how long callbacks actually take.\n\nPerforms some basic statistics on time callbacks take (for now: avg,\n\nmax, median). Existing file can easily be expanded further to perform\n\nadditional operations (eg. plot, quartiles, etc.)\n\n'''\n\n\n\n\n\nimport sys;\n\nimport re as RegExp;\n\nimport math;\n\n\n\n#transitions linearly from one state to the next\n\nIOSERVICE_WAITING_FIRST_LINE = 0;\n\nIOSERVICE_READING_HEADER = 1;\n\nIOSERVICE_READING_SAMPLES = 2;\n\n\n\n\n\n##From\n\n##http://code.activestate.com/recipes/52304-static-methods-aka-class-methods-in-python/\n\nclass Callable:\n\n def __init__(self,anycallable):\n\n self.__call__ = anycallable;\n\n\n\n\n\n#will fill this in later\n\nclass SampleTag():\n\n\n\n \n\n def __init__(self,tag,time):\n\n '''\n\n @param {String} tag\n\n @param {Number} time (in seconds).\n\n '''\n\n self.tag = tag;\n\n self.time = time;\n\n\n\n def debugPrintSample(self):\n\n print('\\n------------------\\n');\n\n print('\\ttag: ' + self.tag);\n\n print('\\ttime(s): ' + str(self.time));\n\n print('\\n\\n');\n\n \n\n def parseSample(line):\n\n '''\n\n For strings with the following format, returns SampleTag\n\n sample: OgreRenderer::parseMeshWork more 157.173ms\n\n\n\n Otherwise, returns None.\n\n '''\n\n #starts with \"sample: \"\n\n #anything in middle\n\n #two spaces\n\n #number+\n\n #one optional decimpal\n\n #number+\n\n #[m,u]s\n\n #2e is hex for '.'\n\n isTagExpr = 'sample:\\s.*?\\s\\s\\d+[\\\\x2e]?\\d+[m,u]?s';\n\n allMatches = RegExp.findall(isTagExpr,line);\n\n if (len(allMatches) == 0):\n\n return None;\n\n\n\n #tag name\n\n tagNameExpr = 'sample:\\s(.*?)\\s\\s\\d+[\\\\x2e]?\\d+[m,u]?s';\n\n tagNameMatches = RegExp.findall(tagNameExpr,line);\n\n if (len(tagNameMatches) != 1):\n\n errString = '\\n\\nError: got ' + str(len(tagNameMatches));\n\n errString += ' tag name matches for line ' + line + '\\n\\n';\n\n print(errString);\n\n assert(False);\n\n\n\n tagName = tagNameMatches[0];\n\n\n\n #parse out time\n\n timeNumberExpr = 'sample:\\s.*?\\s\\s(\\d+[\\\\x2e]?\\d+)[m,u]?s';\n\n timeNumberMatches = RegExp.findall(timeNumberExpr,line);\n\n if (len(timeNumberMatches) != 1):\n\n errString = '\\n\\nError: got ' + str(len(timeNumberMatches));\n\n errString += ' time number matches for line ' + line + '\\n\\n';\n\n print(errString);\n\n assert(False);\n\n\n\n timeNumber = float(timeNumberMatches[0]);\n\n\n\n #parse out time units\n\n timeUnitExpr = 'sample:\\s.*?\\s\\s\\d+[\\\\x2e]?\\d+([m,u]?s)';\n\n timeUnitMatches = RegExp.findall(timeUnitExpr,line);\n\n if (len(timeUnitMatches) != 1):\n\n errString = '\\n\\nError: got ' + str(len(timeUnitMatches));\n\n errString += ' time unit matches for line ' + line + '\\n\\n';\n\n print(errString);\n\n assert(False);\n\n\n\n timeUnit = timeUnitMatches[0];\n\n multiplier = 1;\n\n if(timeUnit == 's'):\n\n pass;\n\n elif(timeUnit == 'us'):\n\n multiplier = .000001;\n\n elif(timeUnit == 'ms'):\n\n multiplier = .001\n\n else:\n\n print('\\n\\nUnknown time unit: ' + timeUnit + '\\n\\n');\n\n assert(False);\n\n\n\n return SampleTag(tagName,multiplier*timeNumber);\n\n\n\n \n\n #make parseSample a static member of Sampletag.\n\n parseSample = Callable(parseSample);\n\n \n\nclass IOService():\n\n\n\n def __init__ (self):\n\n self.header = '';\n\n #each of type SampleTag\n\n self.samples = [];\n\n self.state = IOSERVICE_WAITING_FIRST_LINE;\n\n\n\n def printStatistics(self):\n\n total = 0.;\n\n maxSample = SampleTag('noTag',0);\n\n for s in self.samples:\n\n total += s.time;\n\n if (maxSample.time < s.time):\n\n maxSample.time = s.time;\n\n maxSample.tag = s.tag;\n\n \n\n print('\\n');\n\n print('-----------------');\n\n print(self.header);\n\n print('\\n');\n\n avgTimeMsg = 'No samples: division by zero prevents avg';\n\n maxTimeMsg = 'No samples: max meaningless';\n\n medianTimeMsg = 'No samples: median meaningless';\n\n if (len(self.samples) != 0):\n\n avgTimeMsg = str(total/float(len(self.samples)));\n\n maxTimeMsg = str(maxSample.time) + ' for ' + maxSample.tag;\n\n timeList = [x.time for x in self.samples];\n\n timeList.sort();\n\n medianIndex = int(math.floor(len(timeList)/2));\n\n medianTimeMsg = str(timeList[medianIndex]);\n\n \n\n \n\n print('Avg: ' + avgTimeMsg);\n\n print('Max: ' + maxTimeMsg);\n\n print('Median: ' + medianTimeMsg);\n\n print('\\n\\n');\n\n \n\n def addLineOfText(self,textToAdd):\n\n '''\n\n @return {bool} True if this text should be added to this\n\n IOService, False otherwise.\n\n '''\n\n if (self.state == IOSERVICE_WAITING_FIRST_LINE):\n\n\n\n if (textToAdd.find('==============') != -1):\n\n self.state = IOSERVICE_READING_HEADER;\n\n \n\n return True;\n\n \n\n elif(self.state == IOSERVICE_READING_HEADER):\n\n\n\n #done reading: this is not part of our ioservice\n\n if (textToAdd.find('==============') != -1):\n\n return False;\n\n\n\n #state transition when report sample size\n\n if (textToAdd.find('Sample size: ') != -1):\n\n self.state = IOSERVICE_READING_SAMPLES\n\n\n\n self.header += textToAdd + '\\n';\n\n return True;\n\n \n\n\n\n elif(self.state == IOSERVICE_READING_SAMPLES):\n\n\n\n #done reading: this is not part of our ioservice\n\n if (textToAdd.find('==============') != -1):\n\n return False;\n\n\n\n sTag = SampleTag.parseSample(textToAdd);\n\n if (sTag != None):\n\n self.samples.append(sTag);\n\n\n\n return True;\n\n \n\n else:\n\n print('\\n\\nError: in unknown state\\n\\n');\n\n assert(False);\n\n \n\n\n\n\n\n \n\ndef parseFile(filename):\n\n\n\n filer = open (filename,'r');\n\n allIOServices = []\n\n allIOServices.append(IOService());\n\n\n\n for line in filer:\n\n #if addition of line of text fails for current ioservice (ie,\n\n #it's the beginning of a trace for a new ioservice, then\n\n #create a new IOService object.\n\n if(not allIOServices[-1].addLineOfText(line)):\n\n #create new ioservice, and append line of text to it.\n\n allIOServices.append(IOService());\n\n if (not allIOServices[-1].addLineOfText(line)):\n\n print('\\n\\nError. No IOService will claim line: ' + line);\n\n print('\\n\\n');\n\n assert(False);\n\n\n\n #basic print out at end of what averaged out to longest.\n\n for s in allIOServices:\n\n s.printStatistics();\n\n\n\n\n\nif __name__ == \"__main__\":\n\n\n\n if (len(sys.argv) != 2):\n\n print('Usage error: requires name of file to parse');\n\n else:\n\n parseFile(sys.argv[1]);\n\n\n\n\n", "file_path": "tools/trace/iostrandTraceParser.py", "rank": 45, "score": 189203.7434020481 }, { "content": "enum UnregisteredOptionBehavior {\n\n AllowUnregisteredOptions,\n\n FailOnUnregisteredOptions\n\n};\n\n\n\nSIRIKATA_FUNCTION_EXPORT void ParseOptions(int argc, char** argv, UnregisteredOptionBehavior unreg = FailOnUnregisteredOptions);\n\nSIRIKATA_FUNCTION_EXPORT void ParseOptionsFile(const String& fname, bool required=true, UnregisteredOptionBehavior unreg = FailOnUnregisteredOptions);\n\n\n\n/** Parse command line options and config files, ensuring the command line\n\n * arguments take priority but reading the config file from an option rather\n\n * than hard coding it.\n\n */\n\nSIRIKATA_FUNCTION_EXPORT void ParseOptions(int argc, char** argv, const String& config_file_option, UnregisteredOptionBehavior unreg = FailOnUnregisteredOptions);\n\n\n\n// Parses empty options to get options properly initialized\n\nSIRIKATA_FUNCTION_EXPORT void FakeParseOptions();\n\n\n\n/// Fills in default values, used after initial parsing to make sure we don't\n\n/// block overriding option values from a secondary source (e.g. config files)\n\n/// after parsing the first source (e.g. cmd line)\n", "file_path": "libcore/include/sirikata/core/options/CommonOptions.hpp", "rank": 46, "score": 187944.86551567703 }, { "content": "enum MouseButtonID\n\n{\n\n\tLeftMouseButton = 0,\n\n\tRightMouseButton = 1,\n\n\tMiddleMouseButton = 2,\n\n ScrollUpButton = 3,\n\n ScrollDownButton = 4,\n\n UnknownMouseButton = 0xFFFF\n\n};\n\n\n", "file_path": "libogre/include/sirikata/ogre/WebViewManager.hpp", "rank": 47, "score": 187944.86551567703 }, { "content": "enum MouseDragType {\n\n DRAG_DEADBAND, // Have not yet started an actual drag\n\n DRAG_START,\n\n DRAG_DRAG,\n\n DRAG_END\n\n};\n\n\n", "file_path": "libogre/include/sirikata/ogre/input/InputDevice.hpp", "rank": 48, "score": 187944.86551567703 }, { "content": "enum WindowEventType {\n\n WindowShown,\n\n WindowHidden,\n\n WindowExposed,\n\n WindowMoved,\n\n WindowResized,\n\n WindowMinimized,\n\n WindowMaximized,\n\n WindowRestored,\n\n WindowMouseEnter,\n\n WindowMouseLeave,\n\n WindowFocusGained,\n\n WindowFocusLost,\n\n WindowQuit\n\n};\n\n\n", "file_path": "libogre/include/sirikata/ogre/input/InputDevice.hpp", "rank": 49, "score": 187944.86551567703 }, { "content": "struct WebViewCoord {\n\n int x;\n\n int y;\n\n\n\n WebViewCoord(int _x, int _y)\n\n : x(_x), y(_y)\n\n {\n\n }\n\n};\n\n\n\n\n\n/**\n\n* Supreme dictator and Singleton: WebViewManager\n\n*\n\n* The class you will need to go to for all your WebView-related needs.\n\n*/\n", "file_path": "libogre/include/sirikata/ogre/WebViewManager.hpp", "rank": 50, "score": 187770.40993243767 }, { "content": "struct _SDL_Joystick;\n\n\n\nnamespace Sirikata {\n\nnamespace Input {\n\n\n", "file_path": "libogre/include/sirikata/ogre/input/SDLInputDevice.hpp", "rank": 51, "score": 187770.40993243767 }, { "content": "struct SIRIKATA_OGRE_EXPORT InputDeviceEvent {\n\n enum Type {ADDED, REMOVED} mType;\n\n InputDevicePtr mDevice;\n\n InputDeviceEvent(Type type, const InputDevicePtr &dev)\n\n : mType(type), mDevice(dev) {\n\n }\n\n};\n\n\n", "file_path": "libogre/include/sirikata/ogre/input/InputManager.hpp", "rank": 52, "score": 185811.81061262748 }, { "content": "struct SIRIKATA_OGRE_EXPORT Skybox : public Liveness {\n\n public:\n\n enum SkyboxShape {\n\n SKYBOX_CUBE,\n\n SKYBOX_DOME,\n\n SKYBOX_PLANE\n\n };\n\n\n\n Skybox();\n\n Skybox(SkyboxShape shap, const String& img);\n\n virtual ~Skybox();\n\n\n\n operator bool() const { return shape != (SkyboxShape)-1 && !image.empty(); }\n\n\n\n void load(Ogre::SceneManager* scene_mgr, ResourceLoader* loader, Transfer::TransferPoolPtr tpool);\n\n void unload();\n\n\n\n // Properties\n\n SkyboxShape shape;\n\n String image;\n", "file_path": "libogre/include/sirikata/ogre/Skybox.hpp", "rank": 53, "score": 184876.0100834185 }, { "content": "struct SIRIKATA_MESH_EXPORT Billboard : public Visual {\n\n private:\n\n static String sType;\n\n\n\n public:\n\n Billboard();\n\n Billboard(const String& img);\n\n virtual ~Billboard();\n\n\n\n virtual const String& type() const;\n\n\n\n String image;\n\n float32 aspectRatio; // Width / height\n\n enum BillboardFacing {\n\n FACING_CAMERA,\n\n FACING_FIXED\n\n };\n\n BillboardFacing facing;\n\n};\n\n\n\ntypedef std::tr1::shared_ptr<Billboard> BillboardPtr;\n\ntypedef std::tr1::weak_ptr<Billboard> BillboardWPtr;\n\n\n\n\n\n} // namespace Mesh\n\n} // namespace Sirikata\n\n\n\n#endif //_SIRIKATA_MESH_BILLBOARD_HPP_\n", "file_path": "libmesh/include/sirikata/mesh/Billboard.hpp", "rank": 54, "score": 184876.0100834185 }, { "content": "struct SIRIKATA_MESH_EXPORT Meshdata : public Visual {\n\n private:\n\n static String sType;\n\n\n\n public:\n\n\tMeshdata();\n\n\n\n virtual ~Meshdata();\n\n\n\n virtual const String& type() const;\n\n\n\n SubMeshGeometryList geometry;\n\n TextureList textures;\n\n LightInfoList lights;\n\n MaterialEffectInfoList materials;\n\n\n\n long id;\n\n\n\n bool hasAnimations;\n\n\n", "file_path": "libmesh/include/sirikata/mesh/Meshdata.hpp", "rank": 55, "score": 184876.0100834185 }, { "content": "class SIRIKATA_SPACE_EXPORT SpaceTrace {\n\npublic:\n\n SpaceTrace(Trace::Trace* _trace)\n\n : mTrace(_trace)\n\n {\n\n };\n\n\n\n static void InitOptions();\n\n\n\n // OSeg\n\n CREATE_TRACE_DECL(objectSegmentationCraqLookupRequest, const Time& t, const UUID& obj_id, const ServerID &sID_lookupTo);\n\n CREATE_TRACE_DECL(objectSegmentationLookupNotOnServerRequest, const Time& t, const UUID& obj_id, const ServerID &sID_lookupTo);\n\n CREATE_TRACE_DECL(objectSegmentationProcessedRequest, const Time&t, const UUID& obj_id, const ServerID &sID, const ServerID & sID_processor, uint32 dTime, uint32 stillInQueue);\n\n CREATE_TRACE_DECL(processOSegTrackedSetResults, const Time &t, const UUID& obj_id, const ServerID& sID_migratingTo, const Duration& dur);\n\n CREATE_TRACE_DECL(processOSegShutdownEvents, const Time &t, const ServerID& sID, const int& num_lookups, const int& num_on_this_server, const int& num_cache_hits, const int& num_craq_lookups, const int& num_time_elapsed_cache_eviction, const int& num_migration_not_complete_yet);\n\n CREATE_TRACE_DECL(osegCacheResponse, const Time &t, const ServerID& sID, const UUID& obj);\n\n CREATE_TRACE_DECL(osegCumulativeResponse, const Time &t, OSegLookupTraceToken* traceToken);\n\n\n\n // Migration\n\n CREATE_TRACE_DECL(objectBeginMigrate, const Time& t, const UUID& ojb_id, const ServerID migrate_from, const ServerID migrate_to);\n", "file_path": "libspace/include/sirikata/space/Trace.hpp", "rank": 68, "score": 182690.24727230213 }, { "content": "class SIRIKATA_OH_EXPORT OHTrace {\n\npublic:\n\n OHTrace(Trace::Trace* _trace)\n\n : mTrace(_trace)\n\n {\n\n };\n\n\n\n static void InitOptions();\n\n\n\n CREATE_TRACE_DECL(prox, const Time& t, const UUID& receiver, const UUID& source, bool entered, const TimedMotionVector3f& loc);\n\n\n\n CREATE_TRACE_DECL(objectConnected, const Time& t, const UUID& receiver, const ServerID& sid);\n\n CREATE_TRACE_DECL(objectLoc, const Time& t, const UUID& receiver, const UUID& source, const TimedMotionVector3f& loc);\n\n CREATE_TRACE_DECL(objectGenLoc, const Time& t, const UUID& source, const TimedMotionVector3f& loc, const BoundingSphere3f& bnds);\n\n\n\n CREATE_TRACE_DECL(pingCreated, const Time&sent, const UUID&src, const Time&recv, const UUID& dst, uint64 id, double distance, uint32 sz);\n\n CREATE_TRACE_DECL(ping, const Time&sent, const UUID&src, const Time&recv, const UUID& dst, uint64 id, double distance, uint64 uniquePacketId, uint32 sz);\n\n\n\n CREATE_TRACE_DECL(hitpoint, const Time&sent, const UUID&src, const Time&recv, const UUID& dst, double sentHP, double recvHP, double distance, double srcRadius, double dstRadius, uint32 sz);\n\nprivate:\n", "file_path": "liboh/include/sirikata/oh/Trace.hpp", "rank": 69, "score": 182690.24727230216 }, { "content": "enum Initializer { LENGTH, BOUNDS };\n\n\n\n/** Range identifier -- specifies two segments of a file. */\n", "file_path": "libcore/include/sirikata/core/transfer/Range.hpp", "rank": 70, "score": 180749.42471735875 }, { "content": "struct SDL_MouseMotionEvent;\n", "file_path": "libogre/include/sirikata/ogre/input/SDLInputDevice.hpp", "rank": 71, "score": 179974.28878834352 }, { "content": "struct SIRIKATA_OGRE_EXPORT SDLKeyRepeatInfo {\n\n SDLKeyRepeatInfo();\n\n ~SDLKeyRepeatInfo();\n\n\n\n bool isRepeating(uint32 key);\n\n void repeat(uint32 key, SDL_Event* evt);\n\n void unrepeat(uint32 key);\n\n\n\n typedef std::tr1::unordered_map<uint32, SDL_Event*> RepeatMap;\n\n RepeatMap mRepeat;\n\n};\n\ntypedef std::tr1::shared_ptr<SDLKeyRepeatInfo> SDLKeyRepeatInfoPtr;\n\n\n\n\n", "file_path": "libogre/include/sirikata/ogre/input/SDLInputManager.hpp", "rank": 72, "score": 179279.28867978696 }, { "content": "struct MethodSizeFunctor<ElementType*> {\n\n uint32 operator()(const ElementType* e) const {\n\n return e->size();\n\n }\n\n};\n\n\n\n/** Queue with maximum bytes of storage. */\n\ntemplate <typename ElementType, typename SizeFunctorType = MethodSizeFunctor<ElementType> >\n", "file_path": "libcore/include/sirikata/core/queue/Queue.hpp", "rank": 73, "score": 177034.0806641357 }, { "content": " * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\n\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n */\n\n\n\n#ifndef _SIRIKATA_SIMOH_TRACE_HPP_\n\n#define _SIRIKATA_SIMOH_TRACE_HPP_\n\n\n\n#include <sirikata/space/Platform.hpp>\n\n#include <sirikata/core/trace/Trace.hpp>\n\n#include <sirikata/core/util/MotionVector.hpp>\n\n#include <sirikata/space/OSegLookupTraceToken.hpp>\n\n\n\nnamespace Sirikata {\n\n\n", "file_path": "libspace/include/sirikata/space/Trace.hpp", "rank": 74, "score": 174560.65623892617 }, { "content": " * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\n\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n */\n\n\n\n#ifndef _SIRIKATA_LIBOH_TRACE_HPP_\n\n#define _SIRIKATA_LIBOH_TRACE_HPP_\n\n\n\n#include <sirikata/oh/Platform.hpp>\n\n#include <sirikata/core/trace/Trace.hpp>\n\n#include <sirikata/core/util/MotionVector.hpp>\n\n\n\nnamespace Sirikata {\n\n\n", "file_path": "liboh/include/sirikata/oh/Trace.hpp", "rank": 75, "score": 174560.36958723835 }, { "content": " Trace::Trace* mTrace;\n\n static OptionValue* mLogObject;\n\n static OptionValue* mLogPing;\n\n};\n\n\n\n// This version of the OHTRACE macro automatically uses mContext->trace() and\n\n// passes mContext->simTime() as the first argument, which is the most common\n\n// form.\n\n#define CONTEXT_OHTRACE(___name, ...) \\\n\n TRACE( mContext->ohtrace(), ___name, mContext->simTime(), __VA_ARGS__)\n\n\n\n// This version is like the above, but you can specify the time yourself. Use\n\n// this if you already called Context::simTime() recently. (It also works for\n\n// cases where the first parameter is not the current time.)\n\n#define CONTEXT_OHTRACE_NO_TIME(___name, ...) \\\n\n TRACE( mContext->ohtrace(), ___name, __VA_ARGS__)\n\n\n\n\n\n} // namespace Sirikata\n\n\n\n#endif //_SIRIKATA_LIBOH_TRACE_HPP_\n", "file_path": "liboh/include/sirikata/oh/Trace.hpp", "rank": 76, "score": 174551.9647151596 }, { "content": " static OptionValue* mLogMigration;\n\n static OptionValue* mLogDatagram;\n\n static OptionValue* mLogLocProx;\n\n static OptionValue* mLogCSeg;\n\n};\n\n\n\n// This version of the SPACETRACE macro automatically uses mContext->trace() and\n\n// passes mContext->simTime() as the first argument, which is the most common\n\n// form.\n\n#define CONTEXT_SPACETRACE(___name, ...) \\\n\n TRACE( mContext->spacetrace(), ___name, mContext->simTime(), __VA_ARGS__)\n\n\n\n// This version is like the above, but you can specify the time yourself. Use\n\n// this if you already called Context::simTime() recently. (It also works for\n\n// cases where the first parameter is not the current time.)\n\n#define CONTEXT_SPACETRACE_NO_TIME(___name, ...) \\\n\n TRACE( mContext->spacetrace(), ___name, __VA_ARGS__)\n\n\n\n\n\n} // namespace Sirikata\n\n\n\n#endif //_SIRIKATA_SIMOH_TRACE_HPP_\n", "file_path": "libspace/include/sirikata/space/Trace.hpp", "rank": 77, "score": 174550.61247140903 }, { "content": "/* Sirikata\n\n * Trace.hpp\n\n *\n\n * Copyright (c) 2010, Ewen Cheslack-Postava\n\n * All rights reserved.\n\n *\n\n * Redistribution and use in source and binary forms, with or without\n\n * modification, are permitted provided that the following conditions are\n\n * met:\n\n * * Redistributions of source code must retain the above copyright\n\n * notice, this list of conditions and the following disclaimer.\n\n * * Redistributions in binary form must reproduce the above copyright\n\n * notice, this list of conditions and the following disclaimer in\n\n * the documentation and/or other materials provided with the\n\n * distribution.\n\n * * Neither the name of Sirikata nor the names of its contributors may\n\n * be used to endorse or promote products derived from this software\n\n * without specific prior written permission.\n\n *\n\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n", "file_path": "libspace/include/sirikata/space/Trace.hpp", "rank": 78, "score": 174544.16619545448 }, { "content": "/* Sirikata\n\n * Trace.hpp\n\n *\n\n * Copyright (c) 2010, Ewen Cheslack-Postava\n\n * All rights reserved.\n\n *\n\n * Redistribution and use in source and binary forms, with or without\n\n * modification, are permitted provided that the following conditions are\n\n * met:\n\n * * Redistributions of source code must retain the above copyright\n\n * notice, this list of conditions and the following disclaimer.\n\n * * Redistributions in binary form must reproduce the above copyright\n\n * notice, this list of conditions and the following disclaimer in\n\n * the documentation and/or other materials provided with the\n\n * distribution.\n\n * * Neither the name of Sirikata nor the names of its contributors may\n\n * be used to endorse or promote products derived from this software\n\n * without specific prior written permission.\n\n *\n\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n", "file_path": "liboh/include/sirikata/oh/Trace.hpp", "rank": 79, "score": 174544.16619545448 }, { "content": " CREATE_TRACE_DECL(objectAcknowledgeMigrate, const Time& t, const UUID& obj_id, const ServerID& acknowledge_from,const ServerID& acknowledge_to);\n\n CREATE_TRACE_DECL(objectMigrationRoundTrip, const Time& t, const UUID& obj_id, const ServerID &sID_migratingFrom, const ServerID& sID_migratingTo, const Duration& round_trip);\n\n\n\n // Datagram\n\n CREATE_TRACE_DECL(serverDatagramQueued, const Time& t, const ServerID& dest, uint64 id, uint32 size);\n\n CREATE_TRACE_DECL(serverDatagramSent, const Time& start_time, const Time& end_time, float weight, const ServerID& dest, uint64 id, uint32 size);\n\n CREATE_TRACE_DECL(serverDatagramReceived, const Time& start_time, const Time& end_time, const ServerID& src, uint64 id, uint32 size);\n\n\n\n // Loc/Prox\n\n CREATE_TRACE_DECL(serverLoc, const Time& t, const ServerID& sender, const ServerID& receiver, const UUID& obj, const TimedMotionVector3f& loc);\n\n CREATE_TRACE_DECL(serverObjectEvent, const Time& t, const ServerID& source, const ServerID& dest, const UUID& obj, bool added, const TimedMotionVector3f& loc);\n\n\n\n // CSeg\n\n CREATE_TRACE_DECL(segmentationChanged, const Time& t, const BoundingBox3f& bbox, const ServerID& serverID);\n\n\n\n\n\nprivate:\n\n Trace::Trace* mTrace;\n\n static OptionValue* mLogOSeg;\n\n static OptionValue* mLogOSegCumulative;\n", "file_path": "libspace/include/sirikata/space/Trace.hpp", "rank": 80, "score": 174541.56433314912 }, { "content": "#!/usr/bin/python\n\n\n\n# Converts a bunch of processedTrace files from Second Life into a\n\n# single trace file, where all coordinates have been converted\n\n# properly. This assumes that the traces are laid out in a square\n\n# grid, that each server is 256m x 256m.\n\n\n\n\n\nif __name__ == \"__main__\":\n\n trace_file_fmt = '4x4/processedTrace_%d'\n\n servers_per_side = 4\n\n server_width = 256\n\n combined_file = 'sl.trace.4x4.dat'\n\n\n\n total_side_size = servers_per_side * server_width\n\n\n\n objects = set()\n\n blacklist = set()\n\n max_rad = 0\n\n min_rad = 10000\n\n min_x = 10000\n\n max_x = -10000\n\n min_y = 10000\n\n max_y = -10000\n\n min_z = 10000\n\n max_z = -10000\n\n fout = file(combined_file, 'w')\n\n for sy in range(servers_per_side):\n\n for sx in range(servers_per_side):\n\n idx = sy * servers_per_side + sx\n\n trace_file = trace_file_fmt % (idx)\n\n\n\n for line in file(trace_file):\n\n (uuid, colon, info) = line.partition(':')\n\n parts = info.split(',')\n\n x = float(parts[0].strip()) + (sx * 256.0)\n\n y = float(parts[1].strip()) + (sy * 256.0)\n\n z = float(parts[2].strip())\n\n t = int(float(parts[3].strip())) # milliseconds\n\n rad = float(parts[4].strip())\n\n\n\n objects.add(uuid)\n\n max_rad = max(max_rad, rad)\n\n min_rad = min(min_rad, rad)\n\n max_x = max(max_x, x)\n\n min_x = min(min_x, x)\n\n max_y = max(max_y, y)\n\n min_y = min(min_y, y)\n\n max_z = max(max_z, z)\n\n min_z = min(min_z, z)\n\n\n\n # the output should be sane, we should notice if\n\n # something's awry in the output for min and max,\n\n # which are from unmodified values\n\n x = min(total_side_size, max(0, x))\n\n y = min(total_side_size, max(0, y))\n\n print >>fout, uuid, x, y, z, t, rad\n\n fout.close()\n\n\n\n print \"Unique objects:\", len(objects)\n\n print \"Radii:\", max_rad, \"(max)\", min_rad, \"(min)\"\n\n print \"X:\", max_x, \"(max)\", min_x, \"(min)\"\n\n print \"Y:\", max_y, \"(max)\", min_y, \"(min)\"\n\n print \"Z:\", max_z, \"(max)\", min_z, \"(min)\"\n", "file_path": "scripts/traces/merge_traces.py", "rank": 81, "score": 172091.13979685248 }, { "content": "// Connections to servers\n\nstruct SIRIKATA_OH_EXPORT SpaceNodeConnection : public Liveness {\n\n public:\n\n typedef OHDPSST::Stream OHSSTStream;\n\n typedef OHDPSST::StreamPtr OHSSTStreamPtr;\n\n typedef OHDPSST::Endpoint OHSSTEndpoint;\n\n typedef OHDPSST::BaseDatagramLayer OHSSTBaseDatagramLayer;\n\n typedef OHDPSST::BaseDatagramLayerPtr OHSSTBaseDatagramLayerPtr;\n\n\n\n typedef std::tr1::function<void(SpaceNodeConnection*)> GotSpaceConnectionCallback;\n\n typedef std::tr1::function<void(SpaceNodeConnection*)> ReceiveCallback;\n\n\n\n typedef std::tr1::function<void(const Network::Stream::ConnectionStatus, const std::string&)> ConnectionEventCallback;\n\n\n\n SpaceNodeConnection(ObjectHostContext* ctx, Network::IOStrand* ioStrand, TimeProfiler::Stage* handle_read_stage, OptionSet *streamOptions, const SpaceID& spaceid, ServerID sid, OHDP::Service* ohdp_service, ConnectionEventCallback ccb, ReceiveCallback rcb);\n\n ~SpaceNodeConnection();\n\n\n\n // Push a packet to be sent out\n\n bool push(const ObjectMessage& msg);\n\n\n\n // Pull a packet from the receive queue\n", "file_path": "liboh/include/sirikata/oh/SpaceNodeConnection.hpp", "rank": 82, "score": 171189.72151276047 }, { "content": " class ShouldRoundPow2> struct ArrayBaseType4d {\n\n typedef T Array[RoundP2<s0, ShouldRoundPow2>::value][RoundP2<s1, ShouldRoundPow2>::value][RoundP2<s2, ShouldRoundPow2>::value][RoundP2<s3, ShouldRoundPow2>::value];\n\n};\n\ntemplate<class T, uint32_t s0, uint32_t s1, uint32_t s2, uint32_t s3, uint32_t s4,\n", "file_path": "libcore/include/sirikata/core/util/ArrayNd.hpp", "rank": 83, "score": 164970.43446035573 }, { "content": " class ShouldRoundPow2> struct ArrayBaseType3d {\n\n typedef T Array[RoundP2<s0, ShouldRoundPow2>::value][RoundP2<s1, ShouldRoundPow2>::value][RoundP2<s2, ShouldRoundPow2>::value];\n\n};\n\ntemplate<class T, uint32_t s0, uint32_t s1, uint32_t s2, uint32_t s3,\n", "file_path": "libcore/include/sirikata/core/util/ArrayNd.hpp", "rank": 84, "score": 164970.43446035573 }, { "content": " class ShouldRoundPow2> struct ArrayBaseType5d {\n\n typedef T Array[RoundP2<s0, ShouldRoundPow2>::value][RoundP2<s1, ShouldRoundPow2>::value][RoundP2<s2, ShouldRoundPow2>::value][RoundP2<s3, ShouldRoundPow2>::value][RoundP2<s4, ShouldRoundPow2>::value];\n\n};\n\ntemplate<class T, uint32_t s0, uint32_t s1, uint32_t s2,\n\n uint32_t s3, uint32_t s4, uint32_t s5, class ShouldRoundPow2> struct ArrayBaseType6d {\n\n typedef T Array[RoundP2<s0, ShouldRoundPow2>::value][RoundP2<s1, ShouldRoundPow2>::value][RoundP2<s2, ShouldRoundPow2>::value][RoundP2<s3, ShouldRoundPow2>::value][RoundP2<s4, ShouldRoundPow2>::value][RoundP2<s5, ShouldRoundPow2>::value];\n\n};\n\ntemplate<class T, uint32_t s0, uint32_t s1, uint32_t s2,\n\n uint32_t s3, uint32_t s4, uint32_t s5, uint32_t s6,\n", "file_path": "libcore/include/sirikata/core/util/ArrayNd.hpp", "rank": 85, "score": 164970.43446035573 }, { "content": " class ShouldRoundPow2> struct ArrayBaseType7d {\n\n typedef T Array[RoundP2<s0, ShouldRoundPow2>::value][RoundP2<s1, ShouldRoundPow2>::value][RoundP2<s2, ShouldRoundPow2>::value][RoundP2<s3, ShouldRoundPow2>::value][RoundP2<s4, ShouldRoundPow2>::value][RoundP2<s5, ShouldRoundPow2>::value][RoundP2<s6, ShouldRoundPow2>::value];\n\n};\n\n\n\ntemplate <class T,\n\n uint32_t s0, class ShouldRoundPow2 = DontRoundPow2,\n", "file_path": "libcore/include/sirikata/core/util/ArrayNd.hpp", "rank": 86, "score": 164970.43446035573 }, { "content": "// Copyright (c) 2011 Sirikata Authors. All rights reserved.\n\n// Use of this source code is governed by a BSD-style license that can\n\n// be found in the LICENSE file.\n\n\n\n#ifndef _SIRIKATA_CORE_TRACE_WINDOWED_STATS_HPP_\n\n#define _SIRIKATA_CORE_TRACE_WINDOWED_STATS_HPP_\n\n\n\n#include <sirikata/core/util/CircularBuffer.hpp>\n\n\n\nnamespace Sirikata {\n\nnamespace Trace {\n\n\n\n/** Tracks a window of a fixed number of recent samples and can report\n\n * statistics about them, e.g. average, max, min, etc. The sample type must\n\n * specify basic math operations.\n\n */\n\ntemplate<typename SampleType>\n", "file_path": "libcore/include/sirikata/core/trace/WindowedStats.hpp", "rank": 87, "score": 164185.45273157442 }, { "content": " const CircularBuffer<SampleType>& getSamples() const\n\n {\n\n return mSamples;\n\n }\n\n \n\nprivate:\n\n CircularBuffer<SampleType> mSamples;\n\n}; // class RecentStats\n\n\n\n} // namespace Trace\n\n} // namespace Sirikata\n\n\n\n#endif //_SIRIKATA_CORE_TRACE_WINDOWED_STATS_HPP_\n", "file_path": "libcore/include/sirikata/core/trace/WindowedStats.hpp", "rank": 88, "score": 164181.80672040966 }, { "content": " * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\n\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n */\n\n\n\n#ifndef _SIRIKATA_TIME_SERIES_HPP_\n\n#define _SIRIKATA_TIME_SERIES_HPP_\n\n\n\n#include <sirikata/core/util/Platform.hpp>\n\n#include <sirikata/core/util/Factory.hpp>\n\n\n\nnamespace Sirikata {\n\n\n", "file_path": "libcore/include/sirikata/core/trace/TimeSeries.hpp", "rank": 89, "score": 164179.06369138698 }, { "content": " * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\n\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n */\n\n\n\n#ifndef _SIRIKATA_BATCHED_BUFFER_HPP_\n\n#define _SIRIKATA_BATCHED_BUFFER_HPP_\n\n\n\n#include <sirikata/core/util/Platform.hpp>\n\n#include <boost/thread/recursive_mutex.hpp>\n\n\n\nnamespace Sirikata {\n\n\n\ntemplate<typename T>\n", "file_path": "libcore/include/sirikata/core/trace/BatchedBuffer.hpp", "rank": 90, "score": 164178.5474423841 }, { "content": "\n\n void flush();\n\n\n\n // write the buffer to an ostream\n\n void store(FILE* os);\n\n\n\n bool empty();\n\nprivate:\n\n // write the specified number of bytes from the pointer to the buffer\n\n void write(const void* buf, uint32 nbytes);\n\n\n\n typedef Batch<uint8> ByteBatch;\n\n boost::recursive_mutex mMutex;\n\n ByteBatch* filling;\n\n std::deque<ByteBatch*> batches;\n\n};\n\n\n\n} // namespace Sirikata\n\n\n\n#endif //_SIRIKATA_BATCHED_BUFFER_HPP_\n", "file_path": "libcore/include/sirikata/core/trace/BatchedBuffer.hpp", "rank": 91, "score": 164171.4783617388 }, { "content": "/* Sirikata\n\n * BatchedBuffer.hpp\n\n *\n\n * Copyright (c) 2010, Ewen Cheslack-Postava\n\n * All rights reserved.\n\n *\n\n * Redistribution and use in source and binary forms, with or without\n\n * modification, are permitted provided that the following conditions are\n\n * met:\n\n * * Redistributions of source code must retain the above copyright\n\n * notice, this list of conditions and the following disclaimer.\n\n * * Redistributions in binary form must reproduce the above copyright\n\n * notice, this list of conditions and the following disclaimer in\n\n * the documentation and/or other materials provided with the\n\n * distribution.\n\n * * Neither the name of Sirikata nor the names of its contributors may\n\n * be used to endorse or promote products derived from this software\n\n * without specific prior written permission.\n\n *\n\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n", "file_path": "libcore/include/sirikata/core/trace/BatchedBuffer.hpp", "rank": 92, "score": 164165.73468557786 }, { "content": "/* Sirikata\n\n * TimeSeries.hpp\n\n *\n\n * Copyright (c) 2011, Ewen Cheslack-Postava\n\n * All rights reserved.\n\n *\n\n * Redistribution and use in source and binary forms, with or without\n\n * modification, are permitted provided that the following conditions are\n\n * met:\n\n * * Redistributions of source code must retain the above copyright\n\n * notice, this list of conditions and the following disclaimer.\n\n * * Redistributions in binary form must reproduce the above copyright\n\n * notice, this list of conditions and the following disclaimer in\n\n * the documentation and/or other materials provided with the\n\n * distribution.\n\n * * Neither the name of Sirikata nor the names of its contributors may\n\n * be used to endorse or promote products derived from this software\n\n * without specific prior written permission.\n\n *\n\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n", "file_path": "libcore/include/sirikata/core/trace/TimeSeries.hpp", "rank": 93, "score": 164165.73468557786 }, { "content": "class SIRIKATA_EXPORT TimeSeries {\n\n public:\n\n TimeSeries(Context* ctx);\n\n virtual ~TimeSeries();\n\n\n\n virtual void report(const String& name, float64 val);\n\n\n\n protected:\n\n Context* mContext;\n\n}; // class TimeSeries\n\n\n", "file_path": "libcore/include/sirikata/core/trace/TimeSeries.hpp", "rank": 94, "score": 162650.037122242 }, { "content": "class Context;\n\n\n\nnamespace Trace {\n\n\n\n/** TimeSeries tracks numeric, time series data. It's very generic, just\n\n * reporting a value for a given key. Keys are just strings, but are encouraged\n\n * to be hierarchical, split with '.', e.g. space.server0.objects, allowing the\n\n * receiver to better organize data for exploration and display. Time values\n\n * are read from the current context, so you only need to specify the key and\n\n * value. Note that this data must *not* be sensitive to drops -- in order to\n\n * remain low cost, implementations may drop the data if they cannot quickly\n\n * and efficiently store or relay it.\n\n */\n", "file_path": "libcore/include/sirikata/core/trace/TimeSeries.hpp", "rank": 95, "score": 159421.88909340452 }, { "content": "class SIRIKATA_EXPORT TimeSeriesFactory :\n\n public Factory2<TimeSeries*,Context*,const String&>,\n\n public AutoSingleton<TimeSeriesFactory>\n\n{\n\n public:\n\n static TimeSeriesFactory& getSingleton();\n\n static void destroy();\n\n\n\n TimeSeriesFactory();\n\n ~TimeSeriesFactory();\n\n};\n\n\n\n} // namespace Trace\n\n} // namespace Sirikata\n\n\n\n#endif //_SIRIKATA_TIME_SERIES_HPP_\n", "file_path": "libcore/include/sirikata/core/trace/TimeSeries.hpp", "rank": 96, "score": 158988.2547901815 }, { "content": "class SIRIKATA_OGRE_EXPORT DragAndDropEvent {\n\npublic:\n\n int mXCoord;\n\n int mYCoord;\n\n std::vector<std::string> mFilenames;\n\n DragAndDropEvent(const std::vector<std::string>&files, int x=0, int y=0)\n\n : mXCoord(x), mYCoord(y), mFilenames(files) {\n\n }\n\n};\n\ntypedef std::tr1::shared_ptr<DragAndDropEvent> DragAndDropEventPtr;\n\n\n\n\n\n/** Events generated by a WebView calling Client.event(name, [args]) */\n", "file_path": "libogre/include/sirikata/ogre/input/InputEvents.hpp", "rank": 97, "score": 155526.66915208055 }, { "content": " * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\n\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n */\n\n\n\n\n\n#ifndef __OSEG_LOOKUP_TRACE_TOKEN__\n\n#define __OSEG_LOOKUP_TRACE_TOKEN__\n\n\n\n#include <sirikata/space/Platform.hpp>\n\n#include <sirikata/core/util/UUID.hpp>\n\n\n\nnamespace Sirikata\n", "file_path": "libspace/include/sirikata/space/OSegLookupTraceToken.hpp", "rank": 98, "score": 154974.32254178956 }, { "content": "{\n\n\n\n\n\n struct SIRIKATA_SPACE_EXPORT OSegLookupTraceToken\n\n {\n\n enum OSegTraceStage\n\n {\n\n OSEG_TRACE_INITIAL_LOOKUP_TIME,\n\n OSEG_TRACE_CHECK_CACHE_LOCAL_BEGIN,\n\n OSEG_TRACE_CHECK_CACHE_LOCAL_END,\n\n OSEG_TRACE_CRAQ_LOOKUP_BEGIN,\n\n OSEG_TRACE_CRAQ_LOOKUP_END,\n\n OSEG_TRACE_CRAQ_LOOKUP_NOT_ALREADY_LOOKING_UP_BEGIN,\n\n OSEG_TRACE_CRAQ_LOOKUP_NOT_ALREADY_LOOKING_UP_END,\n\n OSEG_TRACE_GET_MANAGER_ENQUEUE_BEGIN,\n\n OSEG_TRACE_GET_MANAGER_ENQUEUE_END,\n\n OSEG_TRACE_GET_MANAGER_DEQUEUED,\n\n OSEG_TRACE_GET_CONNECTION_NETWORK_GET_BEGIN,\n\n OSEG_TRACE_GET_CONNECTION_NETWORK_GET_END,\n\n OSEG_TRACE_GET_CONNECTION_NETWORK_RECEIVED,\n", "file_path": "libspace/include/sirikata/space/OSegLookupTraceToken.hpp", "rank": 99, "score": 154962.66593644474 } ]
C++
source/MaterialXContrib/MaterialXMaya/ShadingNodeOverrides.cpp
muenstc/MaterialX
b8365086a738fddae683065d78f65410aacd0dc4
#include "ShadingNodeOverrides.h" #include "MaterialXNode.h" #include "Plugin.h" #include "MaterialXUtil.h" #include "MayaUtil.h" #include <maya/MDGModifier.h> #include <maya/MGlobal.h> #include <maya/MShaderManager.h> #include <maya/MPxShadingNodeOverride.h> #include <maya/MPxSurfaceShadingNodeOverride.h> #include <MaterialXFormat/Util.h> #include <MaterialXGenShader/Util.h> #include <MaterialXGenShader/HwShaderGenerator.h> #include <MaterialXGenOgsXml/OgsFragment.h> #include <MaterialXGenOgsXml/OgsXmlGenerator.h> #include <MaterialXRender/ImageHandler.h> #include <iostream> namespace mx = MaterialX; namespace MaterialXMaya { const MString SurfaceOverride::REGISTRANT_ID = "materialXSurface", SurfaceOverride::DRAW_CLASSIFICATION = "drawdb/shader/surface/materialX"; const MString TextureOverride::REGISTRANT_ID = "materialXTexture", TextureOverride::DRAW_CLASSIFICATION = "drawdb/shader/texture/2d/materialX"; namespace { MStatus bindFileTexture(MHWRender::MShaderInstance& shaderInstance, const std::string& parameterName, const mx::FileSearchPath& searchPath, const std::string& fileName, const MHWRender::MSamplerStateDesc& samplerDescription, MHWRender::MTextureDescription& textureDescription, const mx::StringVec* udimIdentifiers = nullptr) { MStatus status = MStatus::kFailure; MHWRender::MRenderer* const renderer = MHWRender::MRenderer::theRenderer(); MHWRender::MTextureManager* const textureManager = renderer ? renderer->getTextureManager() : nullptr; if (textureManager) { MayaUtil::TextureUniquePtr texturePtr; if (udimIdentifiers && !udimIdentifiers->empty()) { const std::vector<mx::Vector2> udimCoordinates{mx::getUdimCoordinates(*udimIdentifiers)}; if (udimCoordinates.size() != udimIdentifiers->size()) { throw mx::Exception("Failed to resolve UDIM information for file: " + fileName); } mx::StringResolverPtr resolver = mx::StringResolver::create(); MStringArray mTilePaths; MFloatArray mTilePositions; for (size_t i = 0; i < udimIdentifiers->size(); ++i) { resolver->setUdimString((*udimIdentifiers)[i]); mx::FilePath resolvedPath = MaterialXUtil::findInSubdirectories( searchPath, resolver->resolve(fileName, mx::FILENAME_TYPE_STRING)); mTilePaths.append(resolvedPath.asString().c_str()); mTilePositions.append(udimCoordinates[i][0]); mTilePositions.append(udimCoordinates[i][1]); } mx::Vector2 scaleUV; mx::Vector2 offsetUV; mx::getUdimScaleAndOffset(udimCoordinates, scaleUV, offsetUV); unsigned int udimBakeWidth = 4096; unsigned int udimBakeHeight = 4096; const float ratio = scaleUV[1] / scaleUV[0]; if (ratio > 1.0) { udimBakeHeight = static_cast<unsigned int>(std::truncf(static_cast<float>(udimBakeHeight) * ratio)); } else { udimBakeWidth = static_cast<unsigned int>(std::truncf(static_cast<float>(udimBakeWidth) * ratio)); } static const MColor undefinedColor; MStringArray failedTilePaths; MFloatArray uvScaleOffset; texturePtr.reset(textureManager->acquireTiledTexture(fileName.c_str(), mTilePaths, mTilePositions, undefinedColor, udimBakeWidth, udimBakeHeight, failedTilePaths, uvScaleOffset)); } else { const mx::FilePath imagePath = MaterialXUtil::findInSubdirectories(searchPath, fileName); if (!imagePath.isEmpty()) { texturePtr.reset( textureManager->acquireTexture(imagePath.asString().c_str(), mx::EMPTY_STRING.c_str())); } } MHWRender::MTextureAssignment textureAssignment; textureAssignment.texture = texturePtr.get(); if (texturePtr) { texturePtr->textureDescription(textureDescription); } else { MString message("*Unable to find image file: "); message += fileName.c_str(); message += " in search paths: "; message += searchPath.asString().c_str(); MGlobal::displayError(message); } status = shaderInstance.setParameter(parameterName.c_str(), textureAssignment); if (!status) { MString message("*Unable to bind image file: "); message += fileName.c_str(); MGlobal::displayError(message); } } if (MayaUtil::SamplerUniquePtr samplerState{MHWRender::MStateManager::acquireSamplerState(samplerDescription)}) { const std::string samplerParameterName = mx::OgsXmlGenerator::textureToSamplerName(parameterName); status = shaderInstance.setParameter(samplerParameterName.c_str(), *samplerState); } return status; } void bindEnvironmentLighting(MHWRender::MShaderInstance& shaderInstance, const MStringArray& parameterList, const mx::FileSearchPath& imageSearchPath, const MaterialXNode& node) { MHWRender::MSamplerStateDesc samplerDescription; samplerDescription.filter = MHWRender::MSamplerState::kAnisotropic; samplerDescription.maxAnisotropy = 16; MStatus status; MHWRender::MTextureDescription textureDescription; if (parameterList.indexOf(mx::HW::ENV_IRRADIANCE.c_str()) >= 0) { status = bindFileTexture(shaderInstance, mx::HW::ENV_IRRADIANCE, imageSearchPath, node.getEnvIrradianceFileName().asChar(), samplerDescription, textureDescription, nullptr); } if (parameterList.indexOf(mx::HW::ENV_RADIANCE.c_str()) >= 0) { status = bindFileTexture(shaderInstance, mx::HW::ENV_RADIANCE, imageSearchPath, node.getEnvRadianceFileName().asChar(), samplerDescription, textureDescription, nullptr); if (status == MStatus::kSuccess) { if (parameterList.indexOf(mx::HW::ENV_RADIANCE_MIPS.c_str()) >= 0) { const int mipCount = static_cast<int>(std::log2(std::max(textureDescription.fWidth, textureDescription.fHeight))) + 1; status = shaderInstance.setParameter(mx::HW::ENV_RADIANCE_MIPS.c_str(), mipCount); } if (parameterList.indexOf(mx::HW::ENV_RADIANCE_SAMPLES.c_str()) >= 0) { constexpr int envSamples = 16; status = shaderInstance.setParameter(mx::HW::ENV_RADIANCE_SAMPLES.c_str(), envSamples); } } } if (parameterList.indexOf(mx::HW::ENV_MATRIX.c_str()) >= 0) { constexpr float Y_ROTATION_PI[4][4] { -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; static const MFloatMatrix ENV_MATRIX(Y_ROTATION_PI); status = shaderInstance.setParameter(mx::HW::ENV_MATRIX.c_str(), ENV_MATRIX); } } } template <class BASE> ShadingNodeOverride<BASE>::ShadingNodeOverride(const MObject& obj) : BASE(obj) , _object(obj) { } template <class BASE> ShadingNodeOverride<BASE>::~ShadingNodeOverride() { } template <class BASE> MString ShadingNodeOverride<BASE>::fragmentName() const { MStatus status; MFnDependencyNode depNode(_object, &status); const auto* const node = dynamic_cast<MaterialXNode*>(depNode.userNode()); const OgsFragment* const data = node ? node->getOgsFragment() : nullptr; if (data) { return data->getLightRigName().empty() ? data->getFragmentName().c_str() : data->getLightRigName().c_str(); } return ""; } template <class BASE> bool ShadingNodeOverride<BASE>::valueChangeRequiresFragmentRebuild(const MPlug* plug) const { if ( *plug == MaterialXNode::DOCUMENT_ATTRIBUTE || *plug == MaterialXNode::ELEMENT_ATTRIBUTE || *plug == MaterialXNode::ENV_RADIANCE_ATTRIBUTE || *plug == MaterialXNode::ENV_IRRADIANCE_ATTRIBUTE ) { return true; } return BASE::valueChangeRequiresFragmentRebuild(plug); } template <class BASE> void ShadingNodeOverride<BASE>::updateShader(MHWRender::MShaderInstance& shaderInstance, const MHWRender::MAttributeParameterMappingList& mappings) { MStatus status; MFnDependencyNode depNode(_object, &status); const auto* const node = dynamic_cast<MaterialXNode*>(depNode.userNode()); if (!node) { return; } const OgsFragment* const ogsFragment = node->getOgsFragment(); if (!ogsFragment) { return; } MStringArray parameterList; shaderInstance.parameterList(parameterList); mx::FilePath documentPath(node->getDocumentFilePath().asChar()); documentPath = documentPath.getParentPath(); mx::FileSearchPath imageSearchPath = Plugin::instance().getResourceSearchPath(); mx::FileSearchPath lightSearchPath = Plugin::instance().getLightSearchPath(); imageSearchPath.prepend(documentPath); lightSearchPath.prepend(documentPath); bindEnvironmentLighting(shaderInstance, parameterList, lightSearchPath, *node); mx::DocumentPtr document = ogsFragment->getDocument(); mx::flattenFilenames(document, imageSearchPath); mx::ValuePtr udimSetValue = document->getGeomPropValue("udimset"); const mx::StringVec* udimIdentifiers = nullptr; if (udimSetValue && udimSetValue->isA<mx::StringVec>()) { udimIdentifiers = &(udimSetValue->asA<mx::StringVec>()); } const std::vector<MSamplerState::TextureAddress> addressModes { MSamplerState::TextureAddress::kTexBorder, MSamplerState::TextureAddress::kTexClamp, MSamplerState::TextureAddress::kTexWrap, MSamplerState::TextureAddress::kTexMirror }; const std::vector<MHWRender::MSamplerState::TextureFilter> filterModes { MHWRender::MSamplerState::kMinMagMipPoint, MHWRender::MSamplerState::kMinMagMipLinear, MHWRender::MSamplerState::kAnisotropic }; const mx::StringMap& inputs = ogsFragment->getPathInputMap(); for (const auto& input : inputs) { const std::string& elementPath = input.first; mx::ElementPtr element = document->getDescendant(elementPath); if (!element) { std::string nodePath = mx::parentNamePath(elementPath); mx::ElementPtr uniformParent = document->getDescendant(nodePath); if (uniformParent) { mx::NodePtr uniformNode = uniformParent->asA<mx::Node>(); if (uniformNode) { mx::StringVec pathVec = mx::splitNamePath(elementPath); element = uniformNode->addInputFromNodeDef(pathVec[pathVec.size() - 1]); } } if (!element) { continue; } } mx::ValueElementPtr valueElement = element->asA<mx::ValueElement>(); if (!valueElement) { continue; } const std::string& inputName = input.second; const MHWRender::MAttributeParameterMapping* const mapping = mappings.findByParameterName(inputName.c_str()); const MString resolvedName = mapping ? mapping->resolvedParameterName() : inputName.c_str(); mx::ValuePtr mtxValue = valueElement->getValue(); if (mtxValue) { if (mtxValue->isA<mx::Matrix44>()) { mx::Matrix44 matrix44 = mtxValue->asA<mx::Matrix44>(); MFloatMatrix mayaValue; for (unsigned int i = 0; i < 4; i++) { for (unsigned int j = 0; j < 4; j++) { mayaValue[i][j] = matrix44[i][j]; } } status = shaderInstance.setParameter(resolvedName, mayaValue); } else if (mtxValue->isA<mx::Matrix33>()) { mx::Matrix33 matrix33 = mtxValue->asA<mx::Matrix33>(); MFloatMatrix mayaValue; mayaValue.setToIdentity(); for (unsigned int i = 0; i < 3; i++) { for (unsigned int j = 0; j < 3; j++) { mayaValue[i][j] = matrix33[i][j]; } } std::string matrix4Name = OgsFragment::getMatrix4Name(resolvedName.asChar()); status = shaderInstance.setParameter(matrix4Name.c_str(), mayaValue); } else if (valueElement->getType() == mx::FILENAME_TYPE_STRING) { const std::string textureParameterName(resolvedName.asChar()); const std::string& valueString = valueElement->getValueString(); if (!valueString.empty()) { MHWRender::MTextureDescription textureDescription; mx::ImageSamplingProperties samplingProperties = ogsFragment->getImageSamplingProperties(textureParameterName); MHWRender::MSamplerStateDesc samplerDescription; samplerDescription.borderColor[0] = samplingProperties.defaultColor[0]; samplerDescription.borderColor[1] = samplingProperties.defaultColor[1]; samplerDescription.borderColor[2] = samplingProperties.defaultColor[2]; samplerDescription.borderColor[3] = samplingProperties.defaultColor[3]; samplerDescription.addressV = MSamplerState::TextureAddress::kTexWrap; if (samplingProperties.vaddressMode != mx::ImageSamplingProperties::AddressMode::UNSPECIFIED) { samplerDescription.addressV = addressModes[static_cast<int>(samplingProperties.vaddressMode)]; } samplerDescription.addressU = MSamplerState::TextureAddress::kTexWrap; if (samplingProperties.uaddressMode != mx::ImageSamplingProperties::AddressMode::UNSPECIFIED) { samplerDescription.addressU = addressModes[static_cast<int>(samplingProperties.uaddressMode)]; } samplerDescription.filter = MHWRender::MSamplerState::kMinMagMipLinear; samplerDescription.maxAnisotropy = 16; if (samplingProperties.filterType != mx::ImageSamplingProperties::FilterType::UNSPECIFIED) { samplerDescription.filter = filterModes[static_cast<int>(samplingProperties.filterType)]; } status = bindFileTexture(shaderInstance, textureParameterName, imageSearchPath, valueString, samplerDescription, textureDescription, udimIdentifiers); } } } } } template class ShadingNodeOverride<MHWRender::MPxShadingNodeOverride>; template class ShadingNodeOverride<MHWRender::MPxSurfaceShadingNodeOverride>; MHWRender::MPxSurfaceShadingNodeOverride* SurfaceOverride::creator(const MObject& obj) { std::cout.rdbuf(std::cerr.rdbuf()); return new SurfaceOverride(obj); } MString SurfaceOverride::transparencyParameter() const { return mx::OgsXmlGenerator::VP_TRANSPARENCY_NAME.c_str(); } MHWRender::MPxShadingNodeOverride* TextureOverride::creator(const MObject& obj) { std::cout.rdbuf(std::cerr.rdbuf()); return new TextureOverride(obj); } }
#include "ShadingNodeOverrides.h" #include "MaterialXNode.h" #include "Plugin.h" #include "MaterialXUtil.h" #include "MayaUtil.h" #include <maya/MDGModifier.h> #include <maya/MGlobal.h> #include <maya/MShaderManager.h> #include <maya/MPxShadingNodeOverride.h> #include <maya/MPxSurfaceShadingNodeOverride.h> #include <MaterialXFormat/Util.h> #include <MaterialXGenShader/Util.h> #include <MaterialXGenShader/HwShaderGenerator.h> #include <MaterialXGenOgsXml/OgsFragment.h> #include <MaterialXGenOgsXml/OgsXmlGenerator.h> #include <MaterialXRender/ImageHandler.h> #include <iostream> namespace mx = MaterialX; namespace MaterialXMaya { const MString SurfaceOverride::REGISTRANT_ID = "materialXSurface", SurfaceOverride::DRAW_CLASSIFICATION = "drawdb/shader/surface/materialX"; const MString TextureOverride::REGISTRANT_ID = "materialXTexture", TextureOverride::DRAW_CLASSIFICATION = "drawdb/shader/texture/2d/materialX"; namespace { MStatus bindFileTexture(MHWRender::MShaderInstance& shaderInstance, const std::string& parameterName, const mx::FileSearchPath& searchPath, const std::string& fileName, const MHWRender::MSamplerStateDesc& samplerDescription, MHWRender::MTextureDescription& textureDescription, const mx::StringVec* udimIdentifiers = nullptr) { MStatus status = MStatus::kFailure; MHWRender::MRenderer* const renderer = MHWRender::MRenderer::theRenderer(); MHWRender::MTextureManager* const textureManager = renderer ? renderer->getTextureManager() : nullptr; if (textureManager) { MayaUtil::TextureUniquePtr texturePtr; if (udimIdentifiers && !udimIdentifiers->empty()) { const std::vector<mx::Vector2> udimCoordinates{mx::getUdimCoordinates(*udimIdentifiers)}; if (udimCoordinates.size() != udimIdentifiers->size()) { throw mx::Exception("Failed to resolve UDIM information for file: " + fileName); } mx::StringResolverPtr resolver = mx::StringResolver::create(); MStringArray mTilePaths; MFloatArray mTilePositions; for (size_t i = 0; i < udimIdentifiers->size(); ++i) { resolver->setUdimString((*udimIdentifiers)[i]); mx::FilePath resolvedPath = MaterialXUtil::findInSubdirectories( searchPath, resolver->resolve(fileName, mx::FILENAME_TYPE_STRING)); mTilePaths.append(resolvedPath.asString().c_str()); mTilePositions.append(udimCoordinates[i][0]); mTilePositions.append(udimCoordinates[i][1]); } mx::Vector2 scaleUV; mx::Vector2 offsetUV; mx::getUdimScaleAndOffset(udimCoordinates, scaleUV, offsetUV); unsigned int udimBakeWidth = 4096; unsigned int udimBakeHeight = 4096; const float ratio = scaleUV[1] / scaleUV[0]; if (ratio > 1.0) { udimBakeHeight = static_cast<unsigned int>(std::truncf(static_cast<float>(udimBakeHeight) * ratio)); } else { udimBakeWidth = static_cast<unsigned int>(std::truncf(static_cast<float>(udimBakeWidth) * ratio)); } static const MColor undefinedColor; MStringArray failedTilePaths; MFloatArray uvScaleOffset; texturePtr.reset(textureManager->acquireTiledTexture(fileName.c_str(), mTilePaths, mTilePositions, undefinedColor, udimBakeWidth, udimBakeHeight, failedTilePaths, uvScaleOffset)); } else { const mx::FilePath imagePath = MaterialXUtil::findInSubdirectories(searchPath, fileName); if (!imagePath.isEmpty()) { texturePtr.reset( textureManager->acquireTexture(imagePath.asString().c_str(), mx::EMPTY_STRING.c_str())); } } MHWRender::MTextureAssignment textureAssignment; textureAssignment.texture = texturePtr.get(); if (texturePtr) { texturePtr->textureDescription(textureDescription); } else { MString message("*Unable to find image file: "); message += fileName.c_str(); message += " in search paths: "; message += searchPath.asString().c_str(); MGlobal::displayError(message); } status = shaderInstance.setParameter(parameterName.c_str(), textureAssignment); if (!status) { MString message("*Unable to bind image file: "); message += fileName.c_str(); MGlobal::displayError(message); } } if (MayaUtil::SamplerUniquePtr samplerState{MHWRender::MStateManager::acquireSamplerState(samplerDescription)}) { const std::string samplerParameterName = mx::OgsXmlGenerator::textureToSamplerName(parameterName); status = shaderInstance.setParameter(samplerParameterName.c_str(), *samplerState); } return status; } void bindEnvironmentLighting(MHWRender::MShaderInstance& shaderInstance, const MStringArray& parameterList, const mx::FileSearchPath& imageSearchPath, const MaterialXNode& node) { MHWRender::MSamplerStateDesc samplerDescription; samplerDescription.filter = MHWRender::MSamplerState::kAnisotropic; samplerDescription.maxAnisotropy = 16; MStatus status; MHWRender::MTextureDescription textureDescription; if (parameterList.indexOf(mx::HW::ENV_IRRADIANCE.c_str()) >= 0) { status = bindFileTexture(shaderInstance, mx::HW::ENV_IRRADIANCE, imageSearchPath, node.getEnvIrradianceFileName().asChar(), samplerDescription, textureDescription, nullptr); } if (parameterList.indexOf(mx::HW::ENV_RADIANCE.c_str()) >= 0) { status = bindFileTexture(shaderInstance, mx::HW::ENV_RADIANCE, imageSearchPath, node.getEnvRadianceFileName().asChar(), samplerDescription, textureDescription, nullptr); if (status == MStatus::kSuccess) { if (parameterList.indexOf(mx::HW::ENV_RADIANCE_MIPS.c_str()) >= 0) { const int mipCount = static_cast<int>(std::log2(std::max(textureDescription.fWidth, textureDescription.fHeight))) + 1; status = shaderInstance.setParameter(mx::HW::ENV_RADIANCE_MIPS.c_str(), mipCount); } if (parameterList.indexOf(mx::HW::ENV_RADIANCE_SAMPLES.c_str()) >= 0) { constexpr int envSamples = 16; status = shaderInstance.setParameter(mx::HW::ENV_RADIANCE_SAMPLES.c_str(), envSamples); } } } if (parameterList.indexOf(mx::HW::ENV_MATRIX.c_str()) >= 0) { constexpr float Y_ROTATION_PI[4][4] { -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; static const MFloatMatrix ENV_MATRIX(Y_ROTATION_PI); status = shaderInstance.setParameter(mx::HW::ENV_MATRIX.c_str(), ENV_MATRIX); } } } template <class BASE> ShadingNodeOverride<BASE>::ShadingNodeOverride(const MObject& obj) : BASE(obj) , _object(obj) { } template <class BASE> ShadingNodeOverride<BASE>::~ShadingNodeOverride() { } template <class BASE> MString ShadingNodeOverride<BASE>::fragmentName() const { MStatus status; MFnDependencyNode depNode(_object, &status); const auto* const node = dynamic_cast<MaterialXNode*>(depNode.userNode()); const OgsFragment* const data = node ? node->getOgsFragment() : nullptr; if (data) { return data->getLightRigName().empty() ? data->getFragmentName().c_str() : data->getLightRigName().c_str(); } return ""; } template <class BASE> bool ShadingNodeOverride<BASE>::valueChangeRequiresFragmentRebuild(const MPlug* plug) const { if ( *plug == MaterialXNode::DOCUMENT_ATTRIBUTE || *plug == MaterialXNode::ELEMENT_ATTRIBUTE || *plug == MaterialXNode::ENV_RADIANCE_ATTRIBUTE || *plug == MaterialXNode::ENV_IRRADIANCE_ATTRIBUTE ) { return true; } return BASE::valueChangeRequiresFragmentRebuild(plug); } template <class BASE> void ShadingNodeOverride<BASE>::updateShader(MHWRender::MShaderInstance& shaderInstance, const MHWRender::MAttributeParameterMappingList& mappings) { MStatus status; MFnDependencyNode depNode(_object, &status); const auto* const node = dynamic_cast<MaterialXNode*>(depNode.userNode()); if (!node) { return; } const OgsFragment* const ogsFragment = node->getOgsFragment(); if (!ogsFragment) { return; } MStringArray parameterList; shaderInstance.parameterList(parameterList); mx::FilePath documentPath(node->getDocumentFilePath().asChar()); documentPath = documentPath.getParentPath(); mx::FileSearchPath imageSearchPath = Plugin::instance().getResourceSearchPath(); mx::FileSearchPath lightSearchPath = Plugin::instance().getLightSearchPath(); imageSearchPath.prepend(documentPath); lightSearchPath.prepend(documentPath); bindEnvironmentLighting(shaderInstance, parameterList, lightSearchPath, *node); mx::DocumentPtr document = ogsFragment->getDocument(); mx::flattenFilenames(document, imageSearchPath); mx::ValuePtr udimSetValue = document->getGeomPropValue("udimset"); const mx::StringVec* udimIdentifiers = nullptr; if (udimSetValue && udimSetValue->isA<mx::StringVec>()) { udimIdentifiers = &(udimSetValue->asA<mx::StringVec>()); } const std::vector<MSamplerState::TextureAddress> addressModes { MSamplerState::TextureAddress::kTexBorder, MSamplerState::TextureAddress::kTexClamp, MSamplerState::TextureAddress::kTexWrap, MSamplerState::TextureAddress::kTexMirror }; const std::vector<MHWRender::MSamplerState::TextureFilter> filterModes { MHWRender::MSamplerState::kMinMagMipPoint, MHWRender::MSamplerState::kMinMagMipLinear, MHWRender::MSamplerState::kAnisotropic }; const mx::StringMap& inputs = ogsFragment->getPathInputMap(); for (const auto& input : inputs) { const std::string& elementPath = input.first; mx::ElementPtr element = document->getDescendant(elementPath); if (!element) { std::string nodePath = mx::parentNamePath(elementPath); mx::ElementPtr uniformParent = document->getDescendant(nodePath); if (uniformParent) { mx::NodePtr uniformNode = uniformParent->asA<mx::Node>(); if (uniformNode) { mx::StringVec pathVec = mx::splitNamePath(elementPath); element = uniformNode->addInputFromNodeDef(pathVec[pathVec.size() - 1]); } } if (!element) { continue; } } mx::ValueElementPtr valueElement = element->asA<mx::ValueElement>(); if (!valueElement) { continue; } const std::string& inputName = input.second; const MHWRender::MAttributeParameterMapping* const mapping = mappings.findByParameterName(inputName.c_str()); const MString resolvedName = mapping ? mapping->resolvedParameterName() : inputName.c_str(); mx::ValuePtr mtxValue = valueElement->getValue(); if (mtxValue) { if (mtxValue->isA<mx::Matrix44>()) { mx::Matrix44 matrix44 = mtxValue->asA<mx::Matrix44>(); MFloatMatrix mayaValue; for (unsigned int i = 0; i < 4; i++) { for (unsigned int j = 0; j < 4; j++) { mayaValue[i][j] = matrix44[i][j]; } } status = shaderInstance.setParameter(resolvedName, mayaValue); } else if (mtxValue->isA<mx::Matrix33>()) { mx::Matrix33 matrix33 = mtxValue->asA<mx::Matrix33>(); MFloatMatrix mayaValue; mayaValue.setToIdentity(); for (unsigned int i = 0; i < 3; i++) { for (unsigned int j = 0; j < 3; j++) { mayaValue[i][j] = matrix33[i][j]; } } std::string matrix4Name = OgsFragment::getMatrix4Name(resolvedName.asChar()); status = shaderInstance.setParameter(matrix4Name.c_str(), mayaValue); } else if (valueElement->getType() == mx::FILENAME_TYPE_STRING) { const std::string textureParameterName(resolvedName.asChar()); const std::string& valueString = valueElement->getValueString(); if (!valueString.empty()) { MHWRender::MTextureDescription textureDescription; mx::ImageSamplingProperties samplingProperties = ogsFragment->getImageSamplingProperties(textureParameterName); MHWRender::MSamplerStateDesc samplerDescription; samplerDescription.borderColor[0] = samplingProperties.defaultColor[0]; samplerDescription.borderColor[1] = samplingProperties.defaultColor[1]; samplerDescription.borderColor[2] = samplingProperties.defaultColor[2]; samplerDescription.borderColor[3] = samplingProperties.defaultColor[3]; samplerDescription.addressV = MSamplerState::TextureAddress::kTe
template class ShadingNodeOverride<MHWRender::MPxShadingNodeOverride>; template class ShadingNodeOverride<MHWRender::MPxSurfaceShadingNodeOverride>; MHWRender::MPxSurfaceShadingNodeOverride* SurfaceOverride::creator(const MObject& obj) { std::cout.rdbuf(std::cerr.rdbuf()); return new SurfaceOverride(obj); } MString SurfaceOverride::transparencyParameter() const { return mx::OgsXmlGenerator::VP_TRANSPARENCY_NAME.c_str(); } MHWRender::MPxShadingNodeOverride* TextureOverride::creator(const MObject& obj) { std::cout.rdbuf(std::cerr.rdbuf()); return new TextureOverride(obj); } }
xWrap; if (samplingProperties.vaddressMode != mx::ImageSamplingProperties::AddressMode::UNSPECIFIED) { samplerDescription.addressV = addressModes[static_cast<int>(samplingProperties.vaddressMode)]; } samplerDescription.addressU = MSamplerState::TextureAddress::kTexWrap; if (samplingProperties.uaddressMode != mx::ImageSamplingProperties::AddressMode::UNSPECIFIED) { samplerDescription.addressU = addressModes[static_cast<int>(samplingProperties.uaddressMode)]; } samplerDescription.filter = MHWRender::MSamplerState::kMinMagMipLinear; samplerDescription.maxAnisotropy = 16; if (samplingProperties.filterType != mx::ImageSamplingProperties::FilterType::UNSPECIFIED) { samplerDescription.filter = filterModes[static_cast<int>(samplingProperties.filterType)]; } status = bindFileTexture(shaderInstance, textureParameterName, imageSearchPath, valueString, samplerDescription, textureDescription, udimIdentifiers); } } } } }
function_block-function_prefixed
[ { "content": "/// @class FileSearchPath\n\n/// A sequence of file paths, which may be queried to find the first instance\n\n/// of a given filename on the file system.\n\nclass MX_FORMAT_API FileSearchPath\n\n{\n\n public:\n\n using Iterator = FilePathVec::iterator;\n\n using ConstIterator = FilePathVec::const_iterator;\n\n\n\n public:\n\n FileSearchPath()\n\n {\n\n }\n\n ~FileSearchPath() { }\n\n\n\n /// Construct a search path from a string.\n\n /// @param searchPath A string containing a sequence of file paths joined\n\n /// by separator characters.\n\n /// @param sep The set of separator characters used in the search path.\n\n /// Defaults to the PATH_LIST_SEPARATOR character.\n\n FileSearchPath(const string& searchPath, const string& sep = PATH_LIST_SEPARATOR)\n\n {\n\n for (const string& path : splitString(searchPath, sep))\n", "file_path": "source/MaterialXFormat/File.h", "rank": 0, "score": 284915.6122496565 }, { "content": "/// @class Matrix44\n\n/// A 4x4 matrix of floating-point values.\n\n///\n\n/// Vector transformation methods follow the row-vector convention,\n\n/// with matrix-vector multiplication computed as v' = vM.\n\nclass MX_CORE_API Matrix44 : public MatrixN<Matrix44, float, 4>\n\n{\n\n public:\n\n using MatrixN<Matrix44, float, 4>::MatrixN;\n\n Matrix44() { }\n\n Matrix44(float m00, float m01, float m02, float m03,\n\n float m10, float m11, float m12, float m13,\n\n float m20, float m21, float m22, float m23,\n\n float m30, float m31, float m32, float m33) :\n\n MatrixN(Uninit{})\n\n {\n\n _arr = {m00, m01, m02, m03,\n\n m10, m11, m12, m13,\n\n m20, m21, m22, m23,\n\n m30, m31, m32, m33};\n\n }\n\n\n\n /// @name Vector Transformations\n\n /// @{\n\n\n", "file_path": "source/MaterialXCore/Types.h", "rank": 1, "score": 279320.9929981555 }, { "content": "/// @class Matrix33\n\n/// A 3x3 matrix of floating-point values.\n\n///\n\n/// Vector transformation methods follow the row-vector convention,\n\n/// with matrix-vector multiplication computed as v' = vM.\n\nclass MX_CORE_API Matrix33 : public MatrixN<Matrix33, float, 3>\n\n{\n\n public:\n\n using MatrixN<Matrix33, float, 3>::MatrixN;\n\n Matrix33() { }\n\n Matrix33(float m00, float m01, float m02,\n\n float m10, float m11, float m12,\n\n float m20, float m21, float m22) :\n\n MatrixN(Uninit{})\n\n {\n\n _arr = {m00, m01, m02,\n\n m10, m11, m12,\n\n m20, m21, m22};\n\n }\n\n\n\n /// @name Vector Transformations\n\n /// @{\n\n\n\n /// Return the product of this matrix and a 3D vector.\n\n Vector3 multiply(const Vector3& v) const;\n", "file_path": "source/MaterialXCore/Types.h", "rank": 2, "score": 279303.253513895 }, { "content": "/// @class Image\n\n/// Class representing an image in system memory\n\nclass MX_RENDER_API Image\n\n{\n\n public:\n", "file_path": "source/MaterialXRender/Image.h", "rank": 3, "score": 260271.3768162048 }, { "content": " /// Address mode options. Matches enumerations allowed for image address\n\n /// modes, except UNSPECIFIED which indicates no explicit mode was defined.\n\n enum class AddressMode : int\n\n { \n\n UNSPECIFIED = -1,\n\n CONSTANT = 0,\n\n CLAMP = 1, \n\n PERIODIC = 2,\n\n MIRROR = 3\n\n };\n\n\n\n /// Address mode in U\n\n AddressMode uaddressMode = AddressMode::UNSPECIFIED;\n\n /// Address mode in V\n\n AddressMode vaddressMode = AddressMode::UNSPECIFIED;\n\n\n", "file_path": "source/MaterialXRender/ImageHandler.h", "rank": 4, "score": 251122.31189846745 }, { "content": " /// Filter type options. Matches enumerations allowed for image filter\n\n /// types, except UNSPECIFIED which indicates no explicit type was defined.\n\n enum class FilterType : int\n\n {\n\n UNSPECIFIED = -1,\n\n CLOSEST = 0,\n\n LINEAR = 1,\n\n CUBIC = 2\n\n };\n\n\n\n /// Filter type\n\n FilterType filterType = FilterType::UNSPECIFIED;\n\n\n\n /// Enable mipmaps\n\n bool enableMipmaps = true;\n\n\n\n /// Default color. Corresponds to the \"default\" value on the image\n\n /// node definition.\n\n Color4 defaultColor = { 0.0f, 0.0f, 0.0f, 1.0f };\n\n};\n\n\n", "file_path": "source/MaterialXRender/ImageHandler.h", "rank": 5, "score": 251122.31189846745 }, { "content": "/// @class Document\n\n/// A MaterialX document, which represents the top-level element in the\n\n/// MaterialX ownership hierarchy.\n\n///\n\n/// Use the factory function createDocument() to create a Document instance.\n\nclass MX_CORE_API Document : public GraphElement\n\n{\n\n public:\n\n Document(ElementPtr parent, const string& name);\n\n virtual ~Document();\n\n\n\n /// Create a new document of the given subclass.\n\n template <class T> static shared_ptr<T> createDocument()\n\n {\n\n shared_ptr<T> doc = std::make_shared<T>(ElementPtr(), EMPTY_STRING);\n\n doc->initialize();\n\n return doc;\n\n }\n\n\n\n /// Initialize the document, removing any existing content.\n\n virtual void initialize();\n\n\n\n /// Create a deep copy of the document.\n\n virtual DocumentPtr copy() const\n\n {\n", "file_path": "source/MaterialXCore/Document.h", "rank": 6, "score": 250796.83463636553 }, { "content": "/// @class Node\n\n/// A node element within a NodeGraph or Document.\n\n///\n\n/// A Node represents an instance of a NodeDef within a graph, and its Input\n\n/// elements apply specific values and connections to that instance.\n\nclass MX_CORE_API Node : public InterfaceElement\n\n{\n\n public:\n\n Node(ElementPtr parent, const string& name) :\n\n InterfaceElement(parent, CATEGORY, name)\n\n {\n\n }\n\n virtual ~Node() { }\n\n\n\n /// @name Connections\n\n /// @{\n\n\n\n /// Set the node to which the given input is connected, creating a\n\n /// child input if needed. If the node argument is null, then any\n\n /// existing node connection on the input will be cleared.\n\n void setConnectedNode(const string& inputName, NodePtr node);\n\n\n\n /// Return the Node connected to the given input. If the given input is\n\n /// not present, then an empty NodePtr is returned.\n\n NodePtr getConnectedNode(const string& inputName) const;\n", "file_path": "source/MaterialXCore/Node.h", "rank": 7, "score": 250417.73346967998 }, { "content": "/// @class ImageLoader\n\n/// Abstract base class for file-system image loaders\n\nclass MX_RENDER_API ImageLoader\n\n{\n\n public:\n\n ImageLoader()\n\n {\n\n }\n\n virtual ~ImageLoader() { }\n\n\n\n /// Standard image file extensions\n\n static const string BMP_EXTENSION;\n\n static const string EXR_EXTENSION;\n\n static const string GIF_EXTENSION;\n\n static const string HDR_EXTENSION;\n\n static const string JPG_EXTENSION;\n\n static const string JPEG_EXTENSION;\n\n static const string PIC_EXTENSION;\n\n static const string PNG_EXTENSION;\n\n static const string PSD_EXTENSION;\n\n static const string TGA_EXTENSION;\n\n static const string TIF_EXTENSION;\n", "file_path": "source/MaterialXRender/ImageHandler.h", "rank": 8, "score": 250358.22750219685 }, { "content": "/// @class ImageHandler\n\n/// Base image handler class. Keeps track of images which are loaded from\n\n/// disk via supplied ImageLoader. Derived classes are responsible for\n\n/// determinining how to perform the logic for \"binding\" of these resources\n\n/// for a given target (such as a given shading language).\n\nclass MX_RENDER_API ImageHandler\n\n{\n\n public:\n\n static ImageHandlerPtr create(ImageLoaderPtr imageLoader)\n\n {\n\n return ImageHandlerPtr(new ImageHandler(imageLoader));\n\n }\n\n virtual ~ImageHandler() { }\n\n\n\n /// Add another image loader to the handler, which will be invoked if\n\n /// existing loaders cannot load a given image.\n\n void addLoader(ImageLoaderPtr loader);\n\n\n\n /// Get a list of extensions supported by the handler.\n\n StringSet supportedExtensions();\n\n\n\n /// Save image to disk. This method must be implemented by derived classes.\n\n /// The first image loader which supports the file name extension will be used.\n\n /// @param filePath File path to be written\n\n /// @param image The image to be saved\n", "file_path": "source/MaterialXRender/ImageHandler.h", "rank": 9, "score": 250355.87532607495 }, { "content": "/// @class ImageSamplingProperties\n\n/// Interface to describe sampling properties for images.\n\nclass MX_RENDER_API ImageSamplingProperties\n\n{\n\n public:\n\n /// Set the properties based on data in a uniform block.\n\n /// @param fileNameUniform Name of the file name uniform. Used to find\n\n /// corresponding sampler data in the uniform block\n\n /// @param uniformBlock Block containing sampler uniforms\n\n void setProperties(const string& fileNameUniform,\n\n const VariableBlock& uniformBlock);\n\n\n", "file_path": "source/MaterialXRender/ImageHandler.h", "rank": 10, "score": 245712.4982894846 }, { "content": "/// @class FilePath\n\n/// A generic file path, supporting both syntactic and file system operations.\n\nclass MX_FORMAT_API FilePath\n\n{\n\n public:\n\n enum Type\n\n {\n\n TypeRelative = 0,\n\n TypeAbsolute = 1,\n\n TypeNetwork = 2\n\n };\n\n\n\n enum Format\n\n {\n\n FormatWindows = 0,\n\n FormatPosix = 1,\n\n #if defined(_WIN32)\n\n FormatNative = FormatWindows\n\n #else\n\n FormatNative = FormatPosix\n\n #endif\n\n };\n", "file_path": "source/MaterialXFormat/File.h", "rank": 11, "score": 242168.59541329226 }, { "content": "class Document;\n\n\n\n/// A shared pointer to an Element\n\nusing ElementPtr = shared_ptr<Element>;\n\n/// A shared pointer to a const Element\n\nusing ConstElementPtr = shared_ptr<const Element>;\n\n\n\n/// A shared pointer to a TypedElement\n\nusing TypedElementPtr = shared_ptr<TypedElement>;\n\n/// A shared pointer to a const TypedElement\n\nusing ConstTypedElementPtr = shared_ptr<const TypedElement>;\n\n\n\n/// A shared pointer to a ValueElement\n\nusing ValueElementPtr = shared_ptr<ValueElement>;\n\n/// A shared pointer to a const ValueElement\n\nusing ConstValueElementPtr = shared_ptr<const ValueElement>;\n\n\n\n/// A shared pointer to a Token\n\nusing TokenPtr = shared_ptr<Token>;\n\n/// A shared pointer to a const Token\n", "file_path": "source/MaterialXCore/Element.h", "rank": 12, "score": 240893.4509407232 }, { "content": "/// @class Backdrop\n\n/// A layout element used to contain, group and document nodes within a graph.\n\nclass MX_CORE_API Backdrop : public Element\n\n{\n\n public:\n\n Backdrop(ElementPtr parent, const string& name) :\n\n Element(parent, CATEGORY, name)\n\n {\n\n }\n\n virtual ~Backdrop() { }\n\n\n\n /// @name Contains String\n\n /// @{\n\n\n\n /// Set the contains string for this backdrop.\n\n void setContainsString(const string& contains)\n\n {\n\n setAttribute(CONTAINS_ATTRIBUTE, contains);\n\n }\n\n\n\n /// Return true if this backdrop has a contains string.\n\n bool hasContainsString() const\n", "file_path": "source/MaterialXCore/Node.h", "rank": 13, "score": 240284.69436708323 }, { "content": " enum class BaseType\n\n {\n\n UINT8 = 0,\n\n UINT16 = 1,\n\n HALF = 2,\n\n FLOAT = 3\n\n };\n\n\n\n public:\n\n /// Create an empty image with the given properties.\n\n static ImagePtr create(unsigned int width, unsigned int height, unsigned int channelCount, BaseType baseType = BaseType::UINT8)\n\n {\n\n return ImagePtr(new Image(width, height, channelCount, baseType));\n\n }\n\n\n\n ~Image();\n\n\n\n /// @name Property Accessors\n\n /// @{\n\n\n", "file_path": "source/MaterialXRender/Image.h", "rank": 14, "score": 237445.60779861122 }, { "content": "/// @class Input\n\n/// An input element within a Node or NodeDef.\n\n///\n\n/// An Input holds either a uniform value or a connection to a spatially-varying\n\n/// Output, either of which may be modified within the scope of a Material.\n\nclass MX_CORE_API Input : public PortElement\n\n{\n\n public:\n\n Input(ElementPtr parent, const string& name) :\n\n PortElement(parent, CATEGORY, name)\n\n {\n\n }\n\n virtual ~Input() { }\n\n\n\n public:\n\n /// @name Default Geometric Property\n\n /// @{\n\n\n\n /// Set the defaultgeomprop string for the input.\n\n void setDefaultGeomPropString(const string& geomprop)\n\n {\n\n setAttribute(DEFAULT_GEOM_PROP_ATTRIBUTE, geomprop);\n\n }\n\n\n\n /// Return true if the given input has a defaultgeomprop string.\n", "file_path": "source/MaterialXCore/Interface.h", "rank": 15, "score": 235712.59225940687 }, { "content": "/// @class OiioImageLoader\n\n/// OpenImageIO image file loader\n\nclass MX_RENDER_API OiioImageLoader : public ImageLoader\n\n{\n\n public:\n\n OiioImageLoader() \n\n {\n\n // Set all extensions supported by OpenImageIO\n\n _extensions.insert(BMP_EXTENSION);\n\n _extensions.insert(GIF_EXTENSION);\n\n _extensions.insert(HDR_EXTENSION);\n\n _extensions.insert(JPG_EXTENSION);\n\n _extensions.insert(JPEG_EXTENSION);\n\n _extensions.insert(PIC_EXTENSION);\n\n _extensions.insert(PNG_EXTENSION);\n\n _extensions.insert(PSD_EXTENSION);\n\n _extensions.insert(TGA_EXTENSION);\n\n _extensions.insert(EXR_EXTENSION);\n\n _extensions.insert(TIF_EXTENSION);\n\n _extensions.insert(TIFF_EXTENSION);\n\n _extensions.insert(TX_EXTENSION);\n\n _extensions.insert(TXT_EXTENSION);\n", "file_path": "source/MaterialXRender/OiioImageLoader.h", "rank": 16, "score": 230027.7278735512 }, { "content": "/// @class StbImageLoader\n\n/// Stb image file loader\n\nclass MX_RENDER_API StbImageLoader : public ImageLoader\n\n{\n\n public:\n\n StbImageLoader()\n\n {\n\n // Set all extensions supported by stb image\n\n _extensions.insert(BMP_EXTENSION);\n\n _extensions.insert(GIF_EXTENSION);\n\n _extensions.insert(HDR_EXTENSION);\n\n _extensions.insert(JPG_EXTENSION);\n\n _extensions.insert(JPEG_EXTENSION);\n\n _extensions.insert(PIC_EXTENSION);\n\n _extensions.insert(PNG_EXTENSION);\n\n _extensions.insert(PSD_EXTENSION);\n\n _extensions.insert(TGA_EXTENSION);\n\n }\n\n virtual ~StbImageLoader() { } \n\n\n\n /// Create a new stb image loader\n\n static StbImageLoaderPtr create() { return std::make_shared<StbImageLoader>(); }\n", "file_path": "source/MaterialXRender/StbImageLoader.h", "rank": 17, "score": 230027.6515308286 }, { "content": "/// @class StringResolver\n\n/// A helper object for applying string modifiers to data values in the context\n\n/// of a specific element and geometry.\n\n///\n\n/// A StringResolver may be constructed through the Element::createStringResolver\n\n/// method, which initializes it in the context of a specific element, geometry,\n\n/// and material.\n\n///\n\n/// Calling the StringResolver::resolve method applies all modifiers to a\n\n/// particular string value.\n\n///\n\n/// Methods such as StringResolver::setFilePrefix may be used to edit the\n\n/// stored string modifiers before calling StringResolver::resolve.\n\nclass MX_CORE_API StringResolver\n\n{\n\n public:\n\n /// Create a new string resolver.\n\n static StringResolverPtr create()\n\n {\n\n return StringResolverPtr(new StringResolver());\n\n }\n\n\n\n virtual ~StringResolver() { }\n\n\n\n /// @name File Prefix\n\n /// @{\n\n\n\n /// Set the file prefix for this context.\n\n void setFilePrefix(const string& filePrefix)\n\n {\n\n _filePrefix = filePrefix;\n\n }\n\n\n", "file_path": "source/MaterialXCore/Element.h", "rank": 18, "score": 227328.9082666984 }, { "content": "#else // MSVC2015 has trouble with decltype in template aliases\n\nstruct is_template_base_of : decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T>*)nullptr)) { };\n\n#endif\n\n\n\n/// Check if T is an instantiation of the template `Class`. For example:\n\n/// `is_instantiation<shared_ptr, T>` is true if `T == shared_ptr<U>` where U can be anything.\n\ntemplate <template<typename...> class Class, typename T>\n", "file_path": "source/PyMaterialX/PyBind11/include/pybind11/detail/common.h", "rank": 19, "score": 225925.09156579612 }, { "content": "/// Extending the HwSourceCodeNode with requirements for image nodes.\n\nclass MX_GENSHADER_API HwImageNode : public HwSourceCodeNode\n\n{\n\npublic:\n\n static ShaderNodeImplPtr create();\n\n\n\n void addInputs(ShaderNode& node, GenContext& context) const override;\n\n void setValues(const Node& node, ShaderNode& shaderNode, GenContext& context) const override;\n\n};\n\n\n\n} // namespace MaterialX\n\n\n\n#endif\n", "file_path": "source/MaterialXGenShader/Nodes/HwImageNode.h", "rank": 20, "score": 222609.7611056778 }, { "content": "/// @class TinyObjLoader\n\n/// Wrapper for geometry loader to read in OBJ files using the TinyObj library.\n\nclass MX_RENDER_API TinyObjLoader : public GeometryLoader\n\n{\n\n public:\n\n TinyObjLoader()\n\n {\n\n _extensions = { \"obj\", \"OBJ\" };\n\n }\n\n virtual ~TinyObjLoader() { }\n\n\n\n /// Create a new TinyObjLoader\n\n static TinyObjLoaderPtr create() { return std::make_shared<TinyObjLoader>(); }\n\n\n\n /// Load geometry from disk\n\n bool load(const FilePath& filePath, MeshList& meshList) override;\n\n};\n\n\n\n} // namespace MaterialX\n\n\n\n#endif\n", "file_path": "source/MaterialXRender/TinyObjLoader.h", "rank": 21, "score": 221955.17886092243 }, { "content": "/// @class GraphElement\n\n/// The base class for graph elements such as NodeGraph and Document.\n\nclass MX_CORE_API GraphElement : public InterfaceElement\n\n{\n\n protected:\n\n GraphElement(ElementPtr parent, const string& category, const string& name) :\n\n InterfaceElement(parent, category, name)\n\n {\n\n }\n\n public:\n\n virtual ~GraphElement() { }\n\n\n\n /// @name Node Elements\n\n /// @{\n\n\n\n /// Add a Node to the graph.\n\n /// @param category The category of the new Node.\n\n /// @param name The name of the new Node.\n\n /// If no name is specified, then a unique name will automatically be\n\n /// generated.\n\n /// @param type An optional type string.\n\n /// @return A shared pointer to the new Node.\n", "file_path": "source/MaterialXCore/Node.h", "rank": 22, "score": 220163.82137020878 }, { "content": "/// @class NodeGraph\n\n/// A node graph element within a Document.\n\nclass MX_CORE_API NodeGraph : public GraphElement\n\n{\n\n public:\n\n NodeGraph(ElementPtr parent, const string& name) :\n\n GraphElement(parent, CATEGORY, name)\n\n {\n\n }\n\n virtual ~NodeGraph() { }\n\n\n\n /// @name NodeDef References\n\n /// @{\n\n\n\n /// Set the NodeDef element referenced by this NodeGraph.\n\n void setNodeDef(ConstNodeDefPtr nodeDef);\n\n\n\n /// Return the NodeDef element referenced by this NodeGraph.\n\n NodeDefPtr getNodeDef() const;\n\n\n\n /// Return the first implementation for this node graph\n\n /// @return An implementation for this node, or an empty shared pointer if\n", "file_path": "source/MaterialXCore/Node.h", "rank": 23, "score": 220064.1321732909 }, { "content": "class Image;\n\n\n\n/// A shared pointer to an image\n\nusing ImagePtr = shared_ptr<Image>;\n\n\n\n/// A shared pointer to a const image\n\nusing ConstImagePtr = shared_ptr<const Image>;\n\n\n\n/// A map from strings to images.\n\nusing ImageMap = std::unordered_map<string, ImagePtr>;\n\n\n\n/// A vetor of images.\n\nusing ImageVec = std::vector<ImagePtr>;\n\n\n\n/// A pair of images.\n\nusing ImagePair = std::pair<ImagePtr, ImagePtr>;\n\n\n\n/// A function to perform image buffer deallocation\n\nusing ImageBufferDeallocator = std::function<void(void*)>;\n\n\n", "file_path": "source/MaterialXRender/Image.h", "rank": 24, "score": 214105.53799446492 }, { "content": "/// @class TypedElement\n\n/// The base class for typed elements.\n\nclass MX_CORE_API TypedElement : public Element\n\n{\n\n protected:\n\n TypedElement(ElementPtr parent, const string& category, const string& name) :\n\n Element(parent, category, name)\n\n {\n\n }\n\n public:\n\n virtual ~TypedElement() { }\n\n\n\n protected:\n\n using TypeDefPtr = shared_ptr<class TypeDef>;\n\n\n\n public:\n\n /// @name Type String\n\n /// @{\n\n\n\n /// Set the element's type string.\n\n void setType(const string& type)\n\n {\n", "file_path": "source/MaterialXCore/Element.h", "rank": 25, "score": 211838.87175252175 }, { "content": "/// @class CommentElement\n\n/// An element representing a block of descriptive text within a document, which will\n\n/// be stored a comment when the document is written out.\n\n///\n\n/// The comment text may be accessed with the methods Element::setDocString and\n\n/// Element::getDocString.\n\n/// \n\nclass MX_CORE_API CommentElement : public Element\n\n{\n\n public:\n\n CommentElement(ElementPtr parent, const string& name) :\n\n Element(parent, CATEGORY, name)\n\n {\n\n }\n\n virtual ~CommentElement() { }\n\n\n\n public:\n\n static const string CATEGORY;\n\n};\n\n\n", "file_path": "source/MaterialXCore/Element.h", "rank": 26, "score": 211836.52581781306 }, { "content": "/// @class GenericElement\n\n/// A generic element subclass, for instantiating elements with unrecognized categories.\n\nclass MX_CORE_API GenericElement : public Element\n\n{\n\n public:\n\n GenericElement(ElementPtr parent, const string& name) :\n\n Element(parent, CATEGORY, name)\n\n {\n\n }\n\n virtual ~GenericElement() { }\n\n\n\n public:\n\n static const string CATEGORY;\n\n};\n\n\n", "file_path": "source/MaterialXCore/Element.h", "rank": 27, "score": 211831.65961031034 }, { "content": "class FilePath;\n\nusing FilePathVec = vector<FilePath>;\n\n\n\nextern MX_FORMAT_API const string PATH_LIST_SEPARATOR;\n\n\n", "file_path": "source/MaterialXFormat/File.h", "rank": 28, "score": 211069.86635426682 }, { "content": "/// @class Element\n\n/// The base class for MaterialX elements.\n\n///\n\n/// An Element is a named object within a Document, which may possess any\n\n/// number of child elements and attributes.\n\nclass MX_CORE_API Element : public std::enable_shared_from_this<Element>\n\n{\n\n protected:\n\n Element(ElementPtr parent, const string& category, const string& name) :\n\n _category(category),\n\n _name(name),\n\n _parent(parent),\n\n _root(parent ? parent->getRoot() : nullptr)\n\n {\n\n }\n\n public:\n\n virtual ~Element() { }\n\n Element(const Element&) = delete;\n\n Element& operator=(const Element&) = delete;\n\n\n\n protected:\n\n using DocumentPtr = shared_ptr<Document>;\n\n using ConstDocumentPtr = shared_ptr<const Document>;\n\n\n\n template <class T> friend class ElementRegistry;\n", "file_path": "source/MaterialXCore/Element.h", "rank": 29, "score": 208240.91469085758 }, { "content": "class VertexVector : public VectorN<VertexVector, float, 8>\n\n{\n\n public:\n\n using VectorN<VertexVector, float, 8>::VectorN;\n\n VertexVector(const Vector3& p, const Vector3& n, const Vector2& t) : VectorN(Uninit{})\n\n {\n\n _arr = {p[0], p[1], p[2], n[0], n[1], n[2], t[0], t[1]};\n\n }\n\n};\n\n\n\nusing VertexIndexMap = std::unordered_map<VertexVector, uint32_t, VertexVector::Hash>;\n\n\n\n} // anonymous namespace\n\n\n\n//\n\n// TinyObjLoader methods\n\n//\n\n\n\nbool TinyObjLoader::load(const FilePath& filePath, MeshList& meshList)\n\n{\n", "file_path": "source/MaterialXRender/TinyObjLoader.cpp", "rank": 30, "score": 207822.62697326473 }, { "content": "class MaterialFileReader : public MaterialReader {\n\n public:\n\n explicit MaterialFileReader(const std::string &mtl_basedir)\n\n : m_mtlBaseDir(mtl_basedir) {}\n\n virtual ~MaterialFileReader() {}\n\n virtual bool operator()(const std::string &matId,\n\n std::vector<material_t> *materials,\n\n std::map<std::string, int> *matMap, std::string *warn,\n\n std::string *err);\n\n\n\n private:\n\n std::string m_mtlBaseDir;\n\n};\n\n\n", "file_path": "source/MaterialXRender/External/TinyObjLoader/tiny_obj_loader.h", "rank": 31, "score": 206144.97159360917 }, { "content": "class ImageLoader;\n", "file_path": "source/MaterialXRender/ImageHandler.h", "rank": 32, "score": 205208.34425337415 }, { "content": "class ImageHandler;\n", "file_path": "source/MaterialXRender/ImageHandler.h", "rank": 33, "score": 205208.34425337415 }, { "content": "/// @class NodeDef\n\n/// A node definition element within a Document.\n\n///\n\n/// A NodeDef provides the declaration of a node interface, which may then\n\n/// be instantiated as a Node.\n\nclass MX_CORE_API NodeDef : public InterfaceElement\n\n{\n\n public:\n\n NodeDef(ElementPtr parent, const string& name) :\n\n InterfaceElement(parent, CATEGORY, name)\n\n {\n\n }\n\n virtual ~NodeDef() { }\n\n\n\n /// @name Node String\n\n /// @{\n\n\n\n /// Set the node string of the NodeDef.\n\n void setNodeString(const string& node)\n\n {\n\n setAttribute(NODE_ATTRIBUTE, node);\n\n }\n\n\n\n /// Return true if the given NodeDef has a node string.\n\n bool hasNodeString() const\n", "file_path": "source/MaterialXCore/Definition.h", "rank": 34, "score": 204853.06946372014 }, { "content": "/// @class GeomElement\n\n/// The base class for geometric elements, which support bindings to geometries\n\n/// and geometric collections.\n\nclass MX_CORE_API GeomElement : public Element\n\n{\n\n protected:\n\n GeomElement(ElementPtr parent, const string& category, const string& name) :\n\n Element(parent, category, name)\n\n {\n\n }\n\n public:\n\n virtual ~GeomElement() { }\n\n\n\n /// @name Geometry\n\n /// @{\n\n\n\n /// Set the geometry string of this element.\n\n void setGeom(const string& geom)\n\n {\n\n setAttribute(GEOM_ATTRIBUTE, geom);\n\n }\n\n\n\n /// Return true if this element has a geometry string.\n", "file_path": "source/MaterialXCore/Geom.h", "rank": 35, "score": 204316.3556745807 }, { "content": "class Document;\n\n\n\n/// A shared pointer to a Document\n\nusing DocumentPtr = shared_ptr<Document>;\n\n/// A shared pointer to a const Document\n\nusing ConstDocumentPtr = shared_ptr<const Document>;\n\n\n", "file_path": "source/MaterialXCore/Document.h", "rank": 36, "score": 199481.26310494757 }, { "content": "class Element;\n", "file_path": "source/MaterialXCore/Element.h", "rank": 37, "score": 199429.5741877539 }, { "content": "/// @class ShaderRenderer\n\n/// Helper class for rendering generated shader code to produce images.\n\nclass MX_RENDER_API ShaderRenderer\n\n{\n\n public:\n\n /// A map with name and source code for each shader stage.\n\n using StageMap = StringMap;\n\n\n\n public:\n\n virtual ~ShaderRenderer() { }\n\n\n\n /// @name Setup\n\n /// @{\n\n\n\n /// Renderer initialization \n\n virtual void initialize() = 0;\n\n\n\n /// Set image handler to use for image load and save\n\n /// @param imageHandler Handler used to save image\n\n void setImageHandler(ImageHandlerPtr imageHandler)\n\n {\n\n _imageHandler = imageHandler;\n", "file_path": "source/MaterialXRender/ShaderRenderer.h", "rank": 38, "score": 199078.71130658127 }, { "content": "class Node;\n", "file_path": "source/MaterialXCore/Node.h", "rank": 39, "score": 199045.19612655655 }, { "content": "class StringResolver;\n", "file_path": "source/MaterialXCore/Element.h", "rank": 40, "score": 197011.26375857557 }, { "content": "class GraphElement;\n", "file_path": "source/MaterialXCore/Node.h", "rank": 41, "score": 196585.2396776017 }, { "content": "/// @class ShaderInput\n\n/// An input on a ShaderNode\n\nclass MX_GENSHADER_API ShaderInput : public ShaderPort\n\n{\n\n public:\n\n ShaderInput(ShaderNode* node, const TypeDesc* type, const string& name);\n\n\n\n /// Return a connection to an upstream node output,\n\n /// or nullptr if not connected.\n\n ShaderOutput* getConnection() { return _connection; }\n\n\n\n /// Return a connection to an upstream node output,\n\n /// or nullptr if not connected.\n\n const ShaderOutput* getConnection() const { return _connection; }\n\n\n\n /// Make a connection from the given source output to this input.\n\n void makeConnection(ShaderOutput* src);\n\n\n\n /// Break the connection to this input.\n\n void breakConnection();\n\n\n\n /// Set optional channels value\n", "file_path": "source/MaterialXGenShader/ShaderNode.h", "rank": 42, "score": 196182.24812758702 }, { "content": "/// @class Half\n\n/// A lightweight 16-bit half-precision float class. Based on the public-domain\n\n/// implementation by Paul Tessier.\n\nclass MX_RENDER_API Half\n\n{\n\n public:\n\n explicit Half(float value) : _data(toFloat16(value)) { }\n\n operator float() const { return toFloat32(_data); }\n\n\n\n bool operator==(Half rhs) const { return float(*this) == float(rhs); }\n\n bool operator!=(Half rhs) const { return float(*this) != float(rhs); }\n\n bool operator<(Half rhs) const { return float(*this) < float(rhs); }\n\n bool operator>(Half rhs) const { return float(*this) > float(rhs); }\n\n bool operator<=(Half rhs) const { return float(*this) <= float(rhs); }\n\n bool operator>=(Half rhs) const { return float(*this) >= float(rhs); }\n\n\n\n Half operator+(Half rhs) const { return Half(float(*this) + float(rhs)); }\n\n Half operator-(Half rhs) const { return Half(float(*this) - float(rhs)); }\n\n Half operator*(Half rhs) const { return Half(float(*this) * float(rhs)); }\n\n Half operator/(Half rhs) const { return Half(float(*this) / float(rhs)); }\n\n\n\n Half& operator+=(Half rhs) { return operator=(*this + rhs); }\n\n Half& operator-=(Half rhs) { return operator=(*this - rhs); }\n", "file_path": "source/MaterialXRender/Types.h", "rank": 43, "score": 195299.7248694506 }, { "content": "/// @class Mesh\n\n/// Container for mesh data\n\nclass MX_RENDER_API Mesh\n\n{\n\n public:\n\n Mesh(const string& identifier);\n\n ~Mesh() { }\n\n\n\n /// Create a new mesh\n\n static MeshPtr create(const string& identifier)\n\n {\n\n return std::make_shared<Mesh>(identifier);\n\n }\n\n\n\n /// Get mesh identifier\n\n const string& getIdentifier() const\n\n {\n\n return _identifier;\n\n }\n\n\n\n /// Set the mesh's source URI.\n\n void setSourceUri(const string& sourceUri)\n", "file_path": "source/MaterialXRender/Mesh.h", "rank": 44, "score": 195294.1806764453 }, { "content": "class PyShaderRenderer : public mx::ShaderRenderer\n\n{\n\n public:\n\n PyShaderRenderer() :\n\n mx::ShaderRenderer()\n\n {\n\n }\n\n\n\n void initialize() override\n\n {\n\n PYBIND11_OVERLOAD_PURE(\n\n void,\n\n mx::ShaderRenderer,\n\n initialize\n\n );\n\n }\n\n\n\n void createProgram(mx::ShaderPtr shader) override\n\n {\n\n PYBIND11_OVERLOAD_PURE(\n", "file_path": "source/PyMaterialX/PyMaterialXRender/PyShaderRenderer.cpp", "rank": 45, "score": 195258.5020537682 }, { "content": " stbi_uc *data;\n", "file_path": "source/MaterialXRender/External/StbImage/stb_image.h", "rank": 46, "score": 193833.2780747151 }, { "content": "/// @class Collection\n\n/// A collection element within a Document.\n\nclass MX_CORE_API Collection : public Element\n\n{\n\n public:\n\n Collection(ElementPtr parent, const string& name) :\n\n Element(parent, CATEGORY, name)\n\n {\n\n }\n\n virtual ~Collection() { }\n\n\n\n /// @name Include Geometry\n\n /// @{\n\n\n\n /// Set the include geometry string of this element.\n\n void setIncludeGeom(const string& geom)\n\n {\n\n setAttribute(INCLUDE_GEOM_ATTRIBUTE, geom);\n\n }\n\n\n\n /// Return true if this element has an include geometry string.\n\n bool hasIncludeGeom() const\n", "file_path": "source/MaterialXCore/Geom.h", "rank": 47, "score": 192872.75337953362 }, { "content": "/// @class Look\n\n/// A look element within a Document.\n\nclass MX_CORE_API Look : public Element\n\n{\n\n public:\n\n Look(ElementPtr parent, const string& name) :\n\n Element(parent, CATEGORY, name)\n\n {\n\n }\n\n virtual ~Look() { }\n\n\n\n /// @name MaterialAssign Elements\n\n /// @{\n\n\n\n /// Add a MaterialAssign to the look.\n\n /// @param name The name of the new MaterialAssign.\n\n /// If no name is specified, then a unique name will automatically be\n\n /// generated.\n\n /// @param material An optional material string, which should match the\n\n /// name of the material node to be assigned.\n\n /// @return A shared pointer to the new MaterialAssign.\n\n MaterialAssignPtr addMaterialAssign(const string& name = EMPTY_STRING,\n", "file_path": "source/MaterialXCore/Look.h", "rank": 48, "score": 192872.75337953362 }, { "content": "/// @class Unit\n\n/// A unit declaration within a UnitDef.\n\nclass MX_CORE_API Unit : public Element\n\n{\n\n public:\n\n Unit(ElementPtr parent, const string& name) :\n\n Element(parent, CATEGORY, name)\n\n {\n\n }\n\n virtual ~Unit() { }\n\n\n\n public:\n\n static const string CATEGORY;\n\n};\n\n\n", "file_path": "source/MaterialXCore/Definition.h", "rank": 49, "score": 192860.16730337346 }, { "content": "/// @class MeshStream\n\n/// Class to represent a mesh data stream\n\nclass MX_RENDER_API MeshStream\n\n{\n\n public:\n\n static const string POSITION_ATTRIBUTE;\n\n static const string NORMAL_ATTRIBUTE;\n\n static const string TEXCOORD_ATTRIBUTE;\n\n static const string TANGENT_ATTRIBUTE;\n\n static const string BITANGENT_ATTRIBUTE;\n\n static const string COLOR_ATTRIBUTE;\n\n static const string GEOMETRY_PROPERTY_ATTRIBUTE;\n\n\n\n static const unsigned int STRIDE_3D = 3;\n\n static const unsigned int STRIDE_2D = 2;\n\n static const unsigned int DEFAULT_STRIDE = STRIDE_3D;\n\n\n\n public:\n\n MeshStream(const string& name, const string& type, unsigned int index) :\n\n _name(name),\n\n _type(type),\n\n _index(index),\n", "file_path": "source/MaterialXRender/Mesh.h", "rank": 50, "score": 191385.23746196917 }, { "content": "/// @class MeshPartition\n\n/// Class that describes a sub-region of a mesh using vertex indexing.\n\n/// Note that a face is considered to be a triangle.\n\nclass MX_RENDER_API MeshPartition\n\n{\n\n public:\n\n MeshPartition() :\n\n _faceCount(0)\n\n {\n\n }\n\n ~MeshPartition() { }\n\n\n\n /// Create a new mesh partition\n\n static MeshPartitionPtr create()\n\n {\n\n return std::make_shared<MeshPartition>();\n\n }\n\n\n\n /// Resize data to the given number of indices\n\n void resize(size_t indexCount)\n\n {\n\n _indices.resize(indexCount);\n\n }\n", "file_path": "source/MaterialXRender/Mesh.h", "rank": 51, "score": 191378.77187932713 }, { "content": "class VariableBlock;\n\n\n\n/// Shared pointer to an ImageHandler\n\nusing ImageHandlerPtr = std::shared_ptr<ImageHandler>;\n\n\n\n/// Shared pointer to an ImageLoader\n\nusing ImageLoaderPtr = std::shared_ptr<ImageLoader>;\n\n\n\n/// Map from strings to vectors of image loaders\n\nusing ImageLoaderMap = std::unordered_map< string, std::vector<ImageLoaderPtr> >;\n\n\n", "file_path": "source/MaterialXRender/ImageHandler.h", "rank": 52, "score": 190877.56476438147 }, { "content": "class Node;\n\nusing ShaderGraphInputSocket = ShaderOutput;\n\n\n\n/// Shared pointer to a ShaderNodeImpl\n\nusing ShaderNodeImplPtr = shared_ptr<class ShaderNodeImpl>;\n\n\n", "file_path": "source/MaterialXGenShader/ShaderNodeImpl.h", "rank": 53, "score": 190632.14734163237 }, { "content": "/// @class RtBindElement\n\n/// Base class for all schemas handling material bindings.\n\nclass RtBindElement : public RtTypedSchema\n\n{\n\n DECLARE_TYPED_SCHEMA(RtBindElement)\n\n\n\npublic:\n\n /// Constructor.\n\n RtBindElement(const RtPrim& prim) : RtTypedSchema(prim) {}\n\n\n\n /// Return the named relationship.\n\n /// Shorthand for getPrim().getRelationship(name).\n\n RtRelationship getRelationship(const RtString& name) const\n\n {\n\n return getPrim().getRelationship(name);\n\n }\n\n\n\n /// Return an iterator traversing all relationships on this\n\n /// element. Shorthand for getPrim().getRelationships().\n\n RtRelationshipIterator getRelationships() const\n\n {\n\n return getPrim().getRelationships();\n\n }\n\n};\n\n\n\n}\n\n\n\n#endif\n", "file_path": "source/MaterialXRuntime/RtBindElement.h", "rank": 54, "score": 190596.3126002458 }, { "content": "/// @class PropertySet\n\n/// A property set element within a Document.\n\nclass MX_CORE_API PropertySet : public Element\n\n{\n\n public:\n\n PropertySet(ElementPtr parent, const string& name) :\n\n Element(parent, CATEGORY, name)\n\n {\n\n }\n\n virtual ~PropertySet() { }\n\n\n\n /// @name Properties\n\n /// @{\n\n\n\n /// Add a Property to the set.\n\n /// @param name The name of the new Property.\n\n /// If no name is specified, then a unique name will automatically be\n\n /// generated.\n\n /// @return A shared pointer to the new Property.\n\n PropertyPtr addProperty(const string& name)\n\n {\n\n return addChild<Property>(name);\n", "file_path": "source/MaterialXCore/Property.h", "rank": 55, "score": 189139.34260787652 }, { "content": "/// @class VariantSet\n\n/// A variant set element within a Document.\n\nclass MX_CORE_API VariantSet : public Element\n\n{\n\n public:\n\n VariantSet(ElementPtr parent, const string& name) :\n\n Element(parent, CATEGORY, name)\n\n {\n\n }\n\n virtual ~VariantSet() { }\n\n\n\n /// @name Variant Elements\n\n /// @{\n\n\n\n /// Add a Variant to the variant set.\n\n /// @param name The name of the new Variant.\n\n /// If no name is specified, then a unique name will automatically be\n\n /// generated.\n\n /// @return A shared pointer to the new Variant.\n\n VariantPtr addVariant(const string& name = EMPTY_STRING)\n\n {\n\n return addChild<Variant>(name);\n", "file_path": "source/MaterialXCore/Variant.h", "rank": 56, "score": 189139.34260787655 }, { "content": "/// @class LookGroup\n\n/// A look group element within a Document.\n\nclass MX_CORE_API LookGroup : public Element\n\n{\n\n public:\n\n LookGroup(ElementPtr parent, const string& name) :\n\n Element(parent, CATEGORY, name)\n\n {\n\n }\n\n virtual ~LookGroup() { }\n\n\n\n /// Set comma-separated list of looks.\n\n void setLooks(const string& looks)\n\n {\n\n setAttribute(LOOKS_ATTRIBUTE, looks);\n\n }\n\n\n\n /// Get comma-separated list of looks.\n\n const string& getLooks() const\n\n {\n\n return getAttribute(LOOKS_ATTRIBUTE);\n\n }\n", "file_path": "source/MaterialXCore/Look.h", "rank": 57, "score": 189139.34260787655 }, { "content": "/// @class UnitDef\n\n/// A unit definition element within a Document.\n\nclass MX_CORE_API UnitDef : public Element\n\n{\n\n public:\n\n UnitDef(ElementPtr parent, const string& name) :\n\n Element(parent, CATEGORY, name)\n\n {\n\n }\n\n virtual ~UnitDef() { }\n\n\n\n /// @name Unit Type methods\n\n /// @{\n\n\n\n /// Set the element's unittype string.\n\n void setUnitType(const string& type)\n\n {\n\n setAttribute(UNITTYPE_ATTRIBUTE, type);\n\n }\n\n\n\n /// Return true if the given element has a unittype string.\n\n bool hasUnitType() const\n", "file_path": "source/MaterialXCore/Definition.h", "rank": 58, "score": 189139.34260787652 }, { "content": "/// @class TypeDef\n\n/// A type definition element within a Document.\n\nclass MX_CORE_API TypeDef : public Element\n\n{\n\n public:\n\n TypeDef(ElementPtr parent, const string& name) :\n\n Element(parent, CATEGORY, name)\n\n {\n\n }\n\n virtual ~TypeDef() { }\n\n\n\n /// @name Semantic\n\n /// @{\n\n\n\n /// Set the semantic string of the TypeDef.\n\n void setSemantic(const string& semantic)\n\n {\n\n setAttribute(SEMANTIC_ATTRIBUTE, semantic);\n\n }\n\n\n\n /// Return true if the given TypeDef has a semantic string.\n\n bool hasSemantic() const\n", "file_path": "source/MaterialXCore/Definition.h", "rank": 59, "score": 189139.34260787652 }, { "content": "/// @class VariantAssign\n\n/// A variant assignment element within a Look.\n\n/// @todo Add support for variant assignments in graph traversal and\n\n/// string resolution.\n\nclass MX_CORE_API VariantAssign : public Element\n\n{\n\n public:\n\n VariantAssign(ElementPtr parent, const string& name) :\n\n Element(parent, CATEGORY, name)\n\n {\n\n }\n\n virtual ~VariantAssign() { }\n\n\n\n /// @name Variant Set String\n\n /// @{\n\n\n\n /// Set the element's variant set string.\n\n void setVariantSetString(const string& variantSet)\n\n {\n\n setAttribute(VARIANT_SET_ATTRIBUTE, variantSet);\n\n }\n\n\n\n /// Return true if the given element has a variant set string.\n\n bool hasVariantSetString() const\n", "file_path": "source/MaterialXCore/Variant.h", "rank": 60, "score": 189131.93423775304 }, { "content": "/// @class Vector3\n\n/// A vector of three floating-point values\n\nclass MX_CORE_API Vector3 : public VectorN<Vector3, float, 3>\n\n{\n\n public:\n\n using VectorN<Vector3, float, 3>::VectorN;\n\n Vector3() { }\n\n Vector3(float x, float y, float z) : VectorN(Uninit{})\n\n {\n\n _arr = {x, y, z};\n\n }\n\n\n\n /// Return the cross product of two vectors.\n\n Vector3 cross(const Vector3& rhs) const\n\n {\n\n return Vector3(_arr[1] * rhs[2] - _arr[2] * rhs[1],\n\n _arr[2] * rhs[0] - _arr[0] * rhs[2],\n\n _arr[0] * rhs[1] - _arr[1] * rhs[0]);\n\n }\n\n};\n\n\n", "file_path": "source/MaterialXCore/Types.h", "rank": 61, "score": 188841.43919584973 }, { "content": "/// @class Vector4\n\n/// A vector of four floating-point values\n\nclass MX_CORE_API Vector4 : public VectorN<Vector4, float, 4>\n\n{\n\n public:\n\n using VectorN<Vector4, float, 4>::VectorN;\n\n Vector4() { }\n\n Vector4(float x, float y, float z, float w) : VectorN(Uninit{})\n\n {\n\n _arr = {x, y, z, w};\n\n }\n\n};\n\n\n", "file_path": "source/MaterialXCore/Types.h", "rank": 62, "score": 188841.43919584973 }, { "content": "/// @class Quaternion\n\n/// A quaternion vector\n\nclass MX_CORE_API Quaternion : public VectorN<Vector4, float, 4>\n\n{\n\n public:\n\n using VectorN<Vector4, float, 4>::VectorN;\n\n Quaternion() { }\n\n Quaternion(float x, float y, float z, float w) : VectorN(Uninit{})\n\n {\n\n _arr = {x, y, z, w};\n\n }\n\n\n\n Quaternion operator*(const Quaternion& q) const\n\n {\n\n return \n\n { \n\n _arr[0] * q._arr[3] + _arr[3] * q._arr[0] + _arr[1] * q._arr[2] - _arr[2] * q._arr[1], \n\n _arr[1] * q._arr[3] + _arr[3] * q._arr[1] + _arr[2] * q._arr[0] - _arr[0] * q._arr[2],\n\n _arr[2] * q._arr[3] + _arr[3] * q._arr[2] + _arr[0] * q._arr[1] - _arr[1] * q._arr[0], \n\n _arr[3] * q._arr[3] - _arr[0] * q._arr[0] - _arr[1] * q._arr[1] - _arr[2] * q._arr[2] \n\n };\n\n }\n", "file_path": "source/MaterialXCore/Types.h", "rank": 63, "score": 188835.5073569031 }, { "content": "/// @class Color3\n\n/// A three-component color value\n\nclass MX_CORE_API Color3 : public VectorN<Color3, float, 3>\n\n{\n\n public:\n\n using VectorN<Color3, float, 3>::VectorN;\n\n Color3() { }\n\n Color3(float r, float g, float b) : VectorN(Uninit{})\n\n {\n\n _arr = {r, g, b};\n\n }\n\n};\n\n\n", "file_path": "source/MaterialXCore/Types.h", "rank": 64, "score": 188835.33232983996 }, { "content": "/// @class Color4\n\n/// A four-component color value\n\nclass MX_CORE_API Color4 : public VectorN<Color4, float, 4>\n\n{\n\n public:\n\n using VectorN<Color4, float, 4>::VectorN;\n\n Color4() { }\n\n Color4(float r, float g, float b, float a) : VectorN(Uninit{})\n\n {\n\n _arr = {r, g, b, a};\n\n }\n\n};\n\n\n", "file_path": "source/MaterialXCore/Types.h", "rank": 65, "score": 188835.33232983996 }, { "content": "/// @class ShaderMetadataRegistry \n\n/// A registry for metadata that will be exported to the generated shader\n\n/// if found on nodes and inputs during shader generation.\n\nclass MX_GENSHADER_API ShaderMetadataRegistry : public GenUserData\n\n{\n\n public:\n\n static const string USER_DATA_NAME;\n\n\n\n /// Add a new metadata entry to the registry.\n\n /// The entry contains the name and data type\n\n /// for the metadata.\n\n void addMetadata(const string& name, const TypeDesc* type, ValuePtr value = nullptr)\n\n {\n\n if (_entryIndex.count(name) == 0)\n\n {\n\n _entryIndex[name] = _entries.size();\n\n _entries.emplace_back(name, type, value);\n\n }\n\n }\n\n\n\n /// Return the metadata registered for the given name, or nullptr\n\n /// if no such entry is found.\n\n const ShaderMetadata* findMetadata(const string& name) const\n", "file_path": "source/MaterialXGenShader/ShaderNode.h", "rank": 66, "score": 188230.5434657695 }, { "content": "class RtSchemaBase;\n\n\n\n/// Type for storing callback IDs.\n\nusing RtCallbackId = size_t;\n\n\n\n/// Function type for callback notifying when a prim has been created.\n\nusing RtCreatePrimCallbackFunc = std::function<void(RtStagePtr stage, const RtPrim& prim, void* userData)>;\n\n\n\n/// Function type for callback notifying when a prim is about to be removed.\n\nusing RtRemovePrimCallbackFunc = std::function<void(RtStagePtr stage, const RtPrim& prim, void* userData)>;\n\n\n\n/// Function type for callback notifying when a prim is about to be renamed.\n\nusing RtRenamePrimCallbackFunc = std::function<void(RtStagePtr stage, const RtPrim& prim, const RtString& newName, void* userData)>;\n\n\n\n/// Function type for callback notifying when a prim is about to be reparented.\n\nusing RtReparentPrimCallbackFunc = std::function<void(RtStagePtr stage, const RtPrim& prim, const RtPath& newPath, void* userData)>;\n\n\n\n/// Function type for callback notifying when a port value is set.\n\nusing RtSetPortValueCallbackFunc = std::function<void(const RtPort& port, const RtValue& value, void* userData)>;\n\n\n", "file_path": "source/MaterialXRuntime/RtMessage.h", "rank": 67, "score": 188018.25528161917 }, { "content": "/// @class GeometryLoader\n\n/// Base class representing a geometry loader. A loader can be\n\n/// associated with one or more file extensions.\n\nclass MX_RENDER_API GeometryLoader\n\n{\n\n public:\n\n GeometryLoader()\n\n {\n\n }\n\n virtual ~GeometryLoader() { }\n\n\n\n /// Returns a list of supported extensions\n\n /// @return List of support extensions\n\n const StringSet& supportedExtensions() const\n\n {\n\n return _extensions;\n\n }\n\n\n\n /// Load geometry from disk. Must be implemented by derived classes.\n\n /// @param filePath Path to file to load\n\n /// @param meshList List of meshes to update\n\n /// @return True if load was successful\n\n virtual bool load(const FilePath& filePath, MeshList& meshList) = 0;\n", "file_path": "source/MaterialXRender/GeometryHandler.h", "rank": 68, "score": 187669.65676278208 }, { "content": "/// @class ViewHandler\n\n/// Utility view handler for creating and providing \n\n/// View data for shader binding.\n\nclass MX_RENDER_API ViewHandler\n\n{\n\n public:\n\n ViewHandler()\n\n {\n\n }\n\n virtual ~ViewHandler() { }\n\n\n\n /// @name Utility Functions\n\n /// @{\n\n\n\n /// Create a new view handler.\n\n static ViewHandlerPtr create() { return std::make_shared<ViewHandler>(); }\n\n\n\n /// Create a view matrix given an eye position, a target position and an up vector.\n\n static Matrix44 createViewMatrix(const Vector3& eye,\n\n const Vector3& target,\n\n const Vector3& up);\n\n\n\n /// Create a perpective projection matrix given a set of clip planes.\n", "file_path": "source/MaterialXRender/ViewHandler.h", "rank": 69, "score": 187668.81591589813 }, { "content": "/// @class LightHandler\n\n/// Utility light handler for creating and providing\n\n/// light data for shader binding.\n\nclass MX_RENDER_API LightHandler\n\n{\n\n public:\n\n LightHandler()\n\n {\n\n }\n\n virtual ~LightHandler() { }\n\n\n\n /// Create a new light handler\n\n static LightHandlerPtr create() { return std::make_shared<LightHandler>(); }\n\n\n\n /// Adds a light source node\n\n void addLightSource(NodePtr node);\n\n\n\n /// Return the vector of active light sources.\n\n const vector<NodePtr>& getLightSources() const\n\n {\n\n return _lightSources;\n\n }\n\n\n", "file_path": "source/MaterialXRender/LightHandler.h", "rank": 70, "score": 187668.81591589813 }, { "content": "/// @class GeometryHandler\n\n/// Class which holds a set of geometry loaders. Each loader is associated with\n\n/// a given set of file extensions.\n\nclass MX_RENDER_API GeometryHandler\n\n{\n\n public:\n\n GeometryHandler()\n\n {\n\n }\n\n virtual ~GeometryHandler() { }\n\n\n\n /// Create a new geometry handler\n\n static GeometryHandlerPtr create()\n\n {\n\n return std::make_shared<GeometryHandler>();\n\n }\n\n\n\n /// Add a geometry loader\n\n /// @param loader Loader to add to list of available loaders.\n\n void addLoader(GeometryLoaderPtr loader);\n\n\n\n /// Get a list of extensions supported by the handler\n\n void supportedExtensions(StringSet& extensions);\n", "file_path": "source/MaterialXRender/GeometryHandler.h", "rank": 71, "score": 187663.99009150977 }, { "content": "class ShaderInput;\n", "file_path": "source/MaterialXGenShader/ShaderNode.h", "rank": 72, "score": 187623.3233785463 }, { "content": "/// @class GLTextureHandler\n\n/// An OpenGL texture handler class\n\nclass MX_RENDERGLSL_API GLTextureHandler : public ImageHandler\n\n{\n\n public:\n\n static ImageHandlerPtr create(ImageLoaderPtr imageLoader)\n\n {\n\n return ImageHandlerPtr(new GLTextureHandler(imageLoader));\n\n }\n\n\n\n /// Acquire an image from the cache or file system. If the image is not\n\n /// found in the cache, then each image loader will be applied in turn.\n\n ImagePtr acquireImage(const FilePath& filePath,\n\n bool generateMipMaps = true) override;\n\n\n\n /// Bind an image. This method will bind the texture to an active texture\n\n /// unit as defined by the corresponding image description. The method\n\n /// will fail if there are not enough available image units to bind to.\n\n bool bindImage(ImagePtr image, const ImageSamplingProperties& samplingProperties) override;\n\n\n\n /// Unbind an image. \n\n bool unbindImage(ImagePtr image) override;\n", "file_path": "source/MaterialXRenderGlsl/GLTextureHandler.h", "rank": 73, "score": 187314.92808054708 }, { "content": "class MaterialReader {\n\n public:\n\n MaterialReader() {}\n\n virtual ~MaterialReader();\n\n\n\n virtual bool operator()(const std::string &matId,\n\n std::vector<material_t> *materials,\n\n std::map<std::string, int> *matMap, std::string *warn,\n\n std::string *err) = 0;\n\n};\n\n\n", "file_path": "source/MaterialXRender/External/TinyObjLoader/tiny_obj_loader.h", "rank": 74, "score": 186596.16864088544 }, { "content": " class BakedImage\n\n {\n\n public:\n\n ImagePtr image;\n\n bool isUniform = false;\n\n Color4 uniformColor;\n\n FilePath filename;\n\n };\n", "file_path": "source/MaterialXRenderGlsl/TextureBaker.h", "rank": 75, "score": 186508.48490868724 }, { "content": "class Input;\n", "file_path": "source/MaterialXCore/Interface.h", "rank": 76, "score": 185895.80592762033 }, { "content": "class Element;\n\n\n\nusing ElementPtr = shared_ptr<Element>;\n\nusing ConstElementPtr = shared_ptr<const Element>;\n\n\n", "file_path": "source/MaterialXCore/Traversal.h", "rank": 77, "score": 185747.31316078105 }, { "content": "/// @class GeomPropDef\n\n/// An element representing a declaration of geometric property data.\n\n///\n\n/// A GeomPropDef element contains a reference to a geometric node and a set of\n\n/// modifiers for that node. For example, a world-space normal can be declared\n\n/// as a reference to the \"normal\" geometric node with a space setting of\n\n/// \"world\", or a specific set of texture coordinates can be declared as a\n\n/// reference to the \"texcoord\" geometric node with an index setting of \"1\".\n\nclass MX_CORE_API GeomPropDef : public Element\n\n{\n\n public:\n\n GeomPropDef(ElementPtr parent, const string& name) :\n\n Element(parent, CATEGORY, name)\n\n {\n\n }\n\n virtual ~GeomPropDef() { }\n\n\n\n /// @name Geometric Property\n\n /// @{\n\n\n\n /// Set the geometric property string of this element.\n\n void setGeomProp(const string& node)\n\n {\n\n setAttribute(GEOM_PROP_ATTRIBUTE, node);\n\n }\n\n\n\n /// Return true if this element has a geometric property string.\n\n bool hasGeomProp() const\n", "file_path": "source/MaterialXCore/Geom.h", "rank": 78, "score": 185598.83821614514 }, { "content": "/// @class UnitTypeDef\n\n/// A unit type definition element within a Document.\n\nclass MX_CORE_API UnitTypeDef : public Element\n\n{\n\n public:\n\n UnitTypeDef(ElementPtr parent, const string& name) :\n\n Element(parent, CATEGORY, name)\n\n {\n\n }\n\n virtual ~UnitTypeDef() { }\n\n\n\n /// Find all UnitDefs for the UnitTypeDef\n\n vector<UnitDefPtr> getUnitDefs() const;\n\n\n\n public:\n\n static const string CATEGORY;\n\n};\n\n\n", "file_path": "source/MaterialXCore/Definition.h", "rank": 79, "score": 185596.28238117768 }, { "content": "class Node;\n", "file_path": "source/MaterialXCore/Interface.h", "rank": 80, "score": 185446.19147271104 }, { "content": "/// @class ShaderNode\n\n/// Class representing a node in the shader generation DAG\n\nclass MX_GENSHADER_API ShaderNode\n\n{\n\n public:\n\n virtual ~ShaderNode() { }\n\n\n", "file_path": "source/MaterialXGenShader/ShaderNode.h", "rank": 81, "score": 185334.19468823532 }, { "content": "/// @class IfGreaterNode\n\n/// \"ifgreater\" node implementation\n\nclass MX_GENSHADER_API IfGreaterNode : public IfNode\n\n{\n\n public:\n\n static ShaderNodeImplPtr create();\n\n private:\n\n const string& equalityString() const override\n\n {\n\n return EQUALITY_STRING;\n\n }\n\n static string EQUALITY_STRING;\n\n};\n\n\n", "file_path": "source/MaterialXGenShader/Nodes/IfNode.h", "rank": 82, "score": 184055.1990306374 }, { "content": "/// @class IfEqualNode \n\n/// \"ifequal\" node implementation\n\nclass MX_GENSHADER_API IfEqualNode : public IfNode\n\n{\n\n public:\n\n static ShaderNodeImplPtr create();\n\n private:\n\n const string& equalityString() const override\n\n {\n\n return EQUALITY_STRING;\n\n }\n\n static string EQUALITY_STRING;\n\n};\n\n\n\n} // namespace MaterialX\n\n\n\n#endif\n", "file_path": "source/MaterialXGenShader/Nodes/IfNode.h", "rank": 83, "score": 184055.1990306374 }, { "content": "/// @class Vector3d\n\n/// A vector of three floating-point values (double-precision)\n\nclass MX_RENDER_API Vector3d : public VectorN<Vector3d, double, 3>\n\n{\n\n public:\n\n using VectorN<Vector3d, double, 3>::VectorN;\n\n Vector3d() { }\n\n Vector3d(double x, double y, double z) : VectorN(Uninit{})\n\n {\n\n _arr = {x, y, z};\n\n }\n\n};\n\n\n", "file_path": "source/MaterialXRender/Types.h", "rank": 84, "score": 183403.59317719046 }, { "content": "/// @class Vector4d\n\n/// A vector of four floating-point values (double-precision)\n\nclass MX_RENDER_API Vector4d : public VectorN<Vector4d, double, 4>\n\n{\n\n public:\n\n using VectorN<Vector4d, double, 4>::VectorN;\n\n Vector4d() { }\n\n Vector4d(double x, double y, double z, double w) : VectorN(Uninit{})\n\n {\n\n _arr = {x, y, z, w};\n\n }\n\n};\n\n\n", "file_path": "source/MaterialXRender/Types.h", "rank": 85, "score": 183403.59317719046 }, { "content": "/// @class Color3d\n\n/// A three-component color value (double-precision)\n\nclass MX_RENDER_API Color3d : public VectorN<Color3d, double, 3>\n\n{\n\n public:\n\n using VectorN<Color3d, double, 3>::VectorN;\n\n Color3d() { }\n\n Color3d(double r, double g, double b) : VectorN(Uninit{})\n\n {\n\n _arr = {r, g, b};\n\n }\n\n};\n\n\n", "file_path": "source/MaterialXRender/Types.h", "rank": 86, "score": 183397.6428807738 }, { "content": "class InterfaceElement;\n", "file_path": "source/MaterialXGenShader/ShaderNodeImpl.h", "rank": 87, "score": 183367.14864702887 }, { "content": "/// @class ValueElement\n\n/// The base class for elements that support typed values.\n\nclass MX_CORE_API ValueElement : public TypedElement\n\n{\n\n protected:\n\n ValueElement(ElementPtr parent, const string& category, const string& name) :\n\n TypedElement(parent, category, name)\n\n {\n\n }\n\n public:\n\n virtual ~ValueElement() { }\n\n\n\n /// @name Value String\n\n /// @{\n\n\n\n /// Set the value string of an element.\n\n void setValueString(const string& value)\n\n {\n\n setAttribute(VALUE_ATTRIBUTE, value);\n\n }\n\n\n\n /// Return true if the given element has a value string.\n", "file_path": "source/MaterialXCore/Element.h", "rank": 88, "score": 182854.20500608315 }, { "content": "class Document::Cache\n\n{\n\n public:\n\n Cache() :\n\n valid(false)\n\n {\n\n }\n\n ~Cache() { }\n\n\n\n void refresh()\n\n {\n\n // Thread synchronization for multiple concurrent readers of a single document.\n\n std::lock_guard<std::mutex> guard(mutex);\n\n\n\n if (!valid)\n\n {\n\n // Clear the existing cache.\n\n portElementMap.clear();\n\n nodeDefMap.clear();\n\n implementationMap.clear();\n", "file_path": "source/MaterialXCore/Document.cpp", "rank": 89, "score": 182604.5162859115 }, { "content": "/// @class HwResourceBindingContext\n\n/// Class representing a context for resource binding for hardware resources.\n\nclass MX_GENSHADER_API HwResourceBindingContext : public GenUserData\n\n{\n\n public:\n\n virtual ~HwResourceBindingContext() {}\n\n\n\n // Initialize the context before generation starts.\n\n virtual void initialize() = 0;\n\n\n\n // Emit directives required for binding support \n\n virtual void emitDirectives(GenContext& context, ShaderStage& stage) = 0;\n\n\n\n // Emit uniforms with binding information\n\n virtual void emitResourceBindings(GenContext& context, const VariableBlock& uniforms, ShaderStage& stage) = 0;\n\n\n\n // Emit struct uniforms with binding information\n\n virtual void emitStructuredResourceBindings(GenContext& context, const VariableBlock& uniforms,\n\n ShaderStage& stage, const std::string& structInstanceName,\n\n const std::string& arraySuffix = EMPTY_STRING) = 0;\n\n\n\n};\n\n\n\n} // namespace MaterialX\n\n\n\n#endif\n", "file_path": "source/MaterialXGenShader/HwShaderGenerator.h", "rank": 90, "score": 181291.30557682549 }, { "content": "/// @class IfNode\n\n/// Abstract base class for implementions which handle if conditions.\n\nclass MX_GENSHADER_API IfNode : public ShaderNodeImpl\n\n{\n\n public:\n\n void emitFunctionCall(const ShaderNode& node, GenContext& context, ShaderStage& stage) const override;\n\n\n\n private:\n\n /// Provides the shader code equality operator string to use\n\n virtual const string& equalityString() const = 0;\n\n\n\n static const StringVec INPUT_NAMES;\n\n};\n\n\n", "file_path": "source/MaterialXGenShader/Nodes/IfNode.h", "rank": 91, "score": 181207.47249864283 }, { "content": "/// @class IfGreaterEqNode \n\n/// \"ifgreatereq\" node implementation\n\nclass MX_GENSHADER_API IfGreaterEqNode : public IfNode\n\n{\n\n public:\n\n static ShaderNodeImplPtr create();\n\n private:\n\n const string& equalityString() const override\n\n {\n\n return EQUALITY_STRING;\n\n }\n\n static string EQUALITY_STRING;\n\n};\n\n\n", "file_path": "source/MaterialXGenShader/Nodes/IfNode.h", "rank": 92, "score": 181201.46799067518 }, { "content": "/// @class OslRenderer\n\n/// Helper class for rendering generated OSL code to produce images.\n\n///\n\n/// The main services provided are:\n\n/// - Source code validation: Use of \"oslc\" to compile and test output results\n\n/// - Introspection check: None at this time.\n\n/// - Binding: None at this time.\n\n/// - Render validation: Use of \"testrender\" to output rendered images. Assumes source compliation was success\n\n/// as it depends on the existence of corresponding .oso files.\n\n///\n\nclass MX_RENDEROSL_API OslRenderer : public ShaderRenderer\n\n{\n\n public:\n\n /// Create an OSL renderer instance\n\n static OslRendererPtr create(unsigned int width = 512, unsigned int height = 512, Image::BaseType baseType = Image::BaseType::UINT8);\n\n\n\n /// Destructor\n\n virtual ~OslRenderer();\n\n\n\n /// Color closure OSL string\n\n static string OSL_CLOSURE_COLOR_STRING;\n\n\n\n /// @name Setup\n\n /// @{\n\n\n\n /// Internal initialization required for program validation and rendering.\n\n /// An exception is thrown on failure.\n\n /// The exception will contain a list of initialization errors.\n\n void initialize() override;\n\n\n", "file_path": "source/MaterialXRenderOsl/OslRenderer.h", "rank": 93, "score": 179807.45703334193 }, { "content": "/// @class GlslRenderer\n\n/// Helper class for rendering generated GLSL code to produce images.\n\n///\n\n/// There are two main interfaces which can be used. One which takes in a HwShader and one which\n\n/// allows for explicit setting of shader stage code.\n\n///\n\n/// The main services provided are:\n\n/// - Validation: All shader stages are compiled and atteched to a GLSL shader program.\n\n/// - Introspection: The compiled shader program is examined for uniforms and attributes.\n\n/// - Binding: Uniforms and attributes which match the predefined variables generated the GLSL code generator\n\n/// will have values assigned to this. This includes matrices, attribute streams, and textures.\n\n/// - Rendering: The program with bound inputs will be used to drawing geometry to an offscreen buffer.\n\n/// An interface is provided to save this offscreen buffer to disk using an externally defined image handler.\n\n///\n\nclass MX_RENDERGLSL_API GlslRenderer : public ShaderRenderer\n\n{\n\n public:\n\n /// Create a GLSL renderer instance\n\n static GlslRendererPtr create(unsigned int width = 512, unsigned int height = 512, Image::BaseType baseType = Image::BaseType::UINT8);\n\n\n\n /// Destructor\n\n virtual ~GlslRenderer() { };\n\n\n\n /// @name Setup\n\n /// @{\n\n\n\n /// Internal initialization of stages and OpenGL constructs\n\n /// required for program validation and rendering.\n\n /// An exception is thrown on failure.\n\n /// The exception will contain a list of initialization errors.\n\n void initialize() override;\n\n\n\n /// @}\n\n /// @name Rendering\n", "file_path": "source/MaterialXRenderGlsl/GlslRenderer.h", "rank": 94, "score": 179804.93507738985 }, { "content": "/// @class ExceptionShaderRenderError\n\n/// An exception that is thrown when shader rendering fails.\n\n/// An error log of shader errors is cached as part of the exception.\n\n/// For example, if shader compilation fails, then a list of compilation errors is cached.\n\nclass MX_RENDER_API ExceptionShaderRenderError : public Exception\n\n{\n\n public:\n\n ExceptionShaderRenderError(const string& msg, const StringVec& errorList) :\n\n Exception(msg),\n\n _errorLog(errorList)\n\n {\n\n }\n\n\n\n ExceptionShaderRenderError(const ExceptionShaderRenderError& e) :\n\n Exception(e),\n\n _errorLog(e._errorLog)\n\n {\n\n }\n\n\n\n ExceptionShaderRenderError& operator=(const ExceptionShaderRenderError& e) \n\n {\n\n Exception::operator=(e);\n\n _errorLog = e._errorLog;\n\n return *this;\n", "file_path": "source/MaterialXRender/ShaderRenderer.h", "rank": 95, "score": 179792.67488228116 }, { "content": "// Class to redirect output as a context manager. C++ backend.\n\nclass OstreamRedirect {\n\n bool do_stdout_;\n\n bool do_stderr_;\n\n std::unique_ptr<scoped_ostream_redirect> redirect_stdout;\n\n std::unique_ptr<scoped_estream_redirect> redirect_stderr;\n\n\n\npublic:\n\n OstreamRedirect(bool do_stdout = true, bool do_stderr = true)\n\n : do_stdout_(do_stdout), do_stderr_(do_stderr) {}\n\n\n\n void enter() {\n\n if (do_stdout_)\n\n redirect_stdout.reset(new scoped_ostream_redirect());\n\n if (do_stderr_)\n\n redirect_stderr.reset(new scoped_estream_redirect());\n\n }\n\n\n\n void exit() {\n\n redirect_stdout.reset();\n\n redirect_stderr.reset();\n", "file_path": "source/PyMaterialX/PyBind11/include/pybind11/iostream.h", "rank": 96, "score": 179494.31174741036 }, { "content": " class pybind11_static_property(property):\n", "file_path": "source/PyMaterialX/PyBind11/include/pybind11/detail/class.h", "rank": 97, "score": 178757.71424657284 }, { "content": "/// @class ShaderNodeImpl\n\n/// Class handling the shader generation implementation for a node.\n\n/// Responsible for emitting the function definition and function call \n\n/// that is the node implementation.\n\nclass MX_GENSHADER_API ShaderNodeImpl\n\n{\n\n public:\n\n virtual ~ShaderNodeImpl() { }\n\n\n\n /// Return an identifier for the target used by this implementation.\n\n /// By default an empty string is returned, representing all targets.\n\n /// Only override this method if your derived node implementation class\n\n /// is for a specific target.\n\n virtual const string& getTarget() const { return EMPTY_STRING; }\n\n\n\n /// Initialize with the given implementation element.\n\n /// Initialization must set the name and hash for the implementation,\n\n /// as well as any other data needed to emit code for the node.\n\n virtual void initialize(const InterfaceElement& element, GenContext& context);\n\n\n\n /// Return the name of this implementation.\n\n const string& getName() const\n\n {\n\n return _name;\n", "file_path": "source/MaterialXGenShader/ShaderNodeImpl.h", "rank": 98, "score": 178680.1130328307 }, { "content": "/// @class Token\n\n/// A token element representing a string value.\n\n///\n\n/// Token elements are used to define input and output values for string\n\n/// substitutions in image filenames.\n\nclass MX_CORE_API Token : public ValueElement\n\n{\n\n public:\n\n Token(ElementPtr parent, const string& name) :\n\n ValueElement(parent, CATEGORY, name)\n\n {\n\n }\n\n virtual ~Token() { }\n\n\n\n public:\n\n static const string CATEGORY;\n\n};\n\n\n", "file_path": "source/MaterialXCore/Element.h", "rank": 99, "score": 178579.25710862732 } ]
C++
tutorials/Embedding/word2vec.hpp
ChanhyoLee/TextDataset
397571f476a89ad42ef3ed77b82c76fc19ac3e33
#include <iostream> #include <fstream> #include <algorithm> #include <vector> #include <ctime> #include <cstdlib> #include "../../WICWIU_src/Tensor.hpp" #include "../../WICWIU_src/DataLoader.hpp" #define NUMOFWORD 71291 //text8에서 단어의 개수! using namespace std; enum OPTION { TESTING, TRAINING }; template<typename DTYPE> void Make_INPUT(string pImagePath, DTYPE **pImage) { } template<typename DTYPE> void Make_LABEL(int numOfLable, int dimOfLabel, DTYPE **pLabel) { for (int i = 0; i < numOfLabel; i++) { pLabel[i] = new DTYPE[dimOfLabel]; pLabel[i][0] = 1; for(int j=1; j< dimOfLabel; j++) pLabel[i][j] = 0; } } template<typename DTYPE> class TextDataSet : public Dataset<DTYPE>{ private: DTYPE **m_aaInput; DTYPE **m_aaLabel; int m_numOfInput; int m_numOfLabel; int m_window; int m_negative; int m_dimOfInput; int m_dimOfLabel; OPTION m_option; public: TextDataSet(string pTextPath, int window, int negative, OPTION pOPTION) { m_aaInput = NULL; m_aaLabel = NULL; m_numOfInput = 0; m_numOfLabel = 0; m_window = 0; m_negative = 0; m_dimOfInput = 0; m_dimOfLabel = 0; m_option = pOPTION; Alloc(pTextPath, window, negative); } virtual ~TextDataSet() { Delete(); } virtual void Alloc(string pTextPath, int window, int negative); virtual void Delete(); virtual std::vector<Tensor<DTYPE> *>* GetData(int idx); virtual int GetLength(); }; template<typename DTYPE> void TextDataSet<DTYPE>::Alloc(string pTextPath, int window, int negative) { m_window = window; m_negative = negative; m_numOfInput = NUMOFWORD * (m_window - 1); m_numOfLabel = NUMOFWORD * (m_window - 1); m_dimOfInput = m_negative + 2; m_dimOfLabel = m_negative + 1; if (m_option == TRAINING) { m_aaInput = new DTYPE *[m_numOfInput]; Make_INPUT(pTextPath, m_aaInput); m_aaLabel = new DTYPE *[m_numOfLabel]; Make_LABEL(m_numOfLabel, m_dimOfLabel, m_aaLabel); } else if (m_option == TESTING) { m_aaInput = new DTYPE *[m_numOfInput]; Make_INPUT(pImagePath, m_aaInput); m_aaLabel = new DTYPE *[m_numOfInput]; Make_LABEL(m_numOfLabel, m_dimOfLabel, m_aaLabel); } else { printf("invalid option\n"); exit(-1); } } template<typename DTYPE> void TextDataSet<DTYPE>::Delete() { if (m_aaInput) { for (int i = 0; i < m_numOfInput; i++) { if (m_aaInput[i]) { delete[] m_aaInput[i]; m_aaInput[i] = NULL; } } delete m_aaInput; m_aaInput = NULL; } if (m_aaLabel) { for (int i = 0; i < m_numOfLabel; i++) { if (m_aaLabel[i]) { delete[] m_aaLabel[i]; m_aaLabel[i] = NULL; } } delete m_aaLabel; m_aaLabel = NULL; } } template<typename DTYPE> std::vector<Tensor<DTYPE> *> *TextDataSet<DTYPE>::GetData(int idx) { std::vector<Tensor<DTYPE> *> *result = new std::vector<Tensor<DTYPE> *>(0, NULL); Tensor<DTYPE> *image = Tensor<DTYPE>::Zeros(1, 1, 1, 1, m_dimOfInput); Tensor<DTYPE> *label = Tensor<DTYPE>::Zeros(1, 1, 1, 1, m_dimOfLabel); for (int i = 0; i < m_dimOfInput; i++) { (*image)[i] = m_aaInput[idx][i]; } (*label)[ (int)m_aaLabel[idx][0] ] = 1.f; result->push_back(image); result->push_back(label); return result; } template<typename DTYPE> int TextDataSet<DTYPE>::GetLength() { return m_numOfInput; }
#include <iostream> #include <fstream> #include <algorithm> #include <vector> #include <ctime> #include <cstdlib> #include "../../WICWIU_src/Tensor.hpp" #include "../../WICWIU_src/DataLoader.hpp" #define NUMOFWORD 71291 //text8에서 단어의 개수! using namespace std; enum OPTION { TESTING, TRAINING }; template<typename DTYPE> void Make_INPUT(string pImagePath, DTYPE **pImage) { } template<typename DTYPE> void Make_LABEL(int numOfLable, int dimOfLabel, DTYPE **pLabel) { for (int i = 0; i < numOfLabel; i++) { pLabel[i] = new DTYPE[dimOfLabel]; pLabel[i][0] = 1; for(int j=1; j< dimOfLabel; j++) pLabel[i][j] = 0; } } template<typename DTYPE> class TextDataSet : public Dataset<DTYPE>{ private: DTYPE **m_aaInput; DTYPE **m_aaLabel; int m_numOfInput; int m_numOfLabel; int m_window; int m_negative; int m_dimOfInput; int m_dimOfLabel; OPTION m_option; public: TextDataSet(string pTextPath, int window, int negative, OPTION pOPTION) { m_aaInput = NULL; m_aaLabel = NULL; m_numOfInput = 0; m_numOfLabel = 0; m_window = 0; m_negative = 0; m_dimOfInput = 0; m_dimOfLabel = 0; m_option = pOPTION; Alloc(pTextPath, window, negative); } virtual ~TextDataSet() { Delete(); } virtual void Alloc(string pTextPath, int window, int negative); virtual void Delete(); virtual std::vector<Tensor<DTYPE> *>* GetData(int idx); virtual int GetLength(); }; template<typename DTYPE> void TextDataSet<DTYPE>::Alloc(string pTextPath, int window, int negative) { m_window = window; m_negative = negative; m_numOfInput = NUMOFWORD * (m_window - 1); m_numOfLabel = NUMOFWORD * (m_window - 1); m_dimOfInput = m_negative + 2; m_dimOfLabel = m_negative + 1; if (m_option == TRAINING) { m_aaInput = new DTYPE *[m_numOfInput]; Make_INPUT(pTextPath, m_aaInput); m_aaLabel = new DTYPE *[m_numOfLabel]; Make_LABEL(m_numOfLabel, m_dimOfLabel, m_aaLabel); } else if (m_option == TESTING) { m_aaInput = new DTYPE *[m_numOfInput]; Make_INPUT(pImagePath, m_aaInput); m_aaLabel = new DTYPE *[m_numOfInput]; Make_LABEL(m_numOfLabel, m_dimOfLabel, m_aaLabel); } else { printf("invalid option\n"); exit(-1); } } template<typename DTYPE> void TextDataSet<DTYPE>::Delete() { if (m_aaInput) { for (int i = 0; i < m_numOfInput; i++) { if (m_aaInput[i]) { delete[] m_aaInput[i]; m_aaInput[i] = NULL; } } delete m_aaInput; m_aaInput = NULL; } if (m_aaLabel) { for (int i = 0; i < m_numOfLabel; i++) { if (m_aaLabel[
template<typename DTYPE> std::vector<Tensor<DTYPE> *> *TextDataSet<DTYPE>::GetData(int idx) { std::vector<Tensor<DTYPE> *> *result = new std::vector<Tensor<DTYPE> *>(0, NULL); Tensor<DTYPE> *image = Tensor<DTYPE>::Zeros(1, 1, 1, 1, m_dimOfInput); Tensor<DTYPE> *label = Tensor<DTYPE>::Zeros(1, 1, 1, 1, m_dimOfLabel); for (int i = 0; i < m_dimOfInput; i++) { (*image)[i] = m_aaInput[idx][i]; } (*label)[ (int)m_aaLabel[idx][0] ] = 1.f; result->push_back(image); result->push_back(label); return result; } template<typename DTYPE> int TextDataSet<DTYPE>::GetLength() { return m_numOfInput; }
i]) { delete[] m_aaLabel[i]; m_aaLabel[i] = NULL; } } delete m_aaLabel; m_aaLabel = NULL; } }
function_block-function_prefixed
[ { "content": "class NEG : public LossFunction<DTYPE>{\n\nprivate:\n\n DTYPE m_epsilon = 1e-6f; // for backprop\n\n\n\npublic:\n\n\n\n NEG(Operator<DTYPE> *pOperator, Operator<DTYPE> *pLabel, int epsilon = 1e-6f) : LossFunction<DTYPE>(pOperator, pLabel) {\n\n #ifdef __DEBUG__\n\n std::cout << \"NEG::NEG(Operator<DTYPE> *, Operator<DTYPE> *, int)\" << '\\n';\n\n #endif // __DEBUG__\n\n this->Alloc(pOperator, epsilon);\n\n }\n\n\n\n\n\n NEG(Operator<DTYPE> *pOperator, Operator<DTYPE> *pLabel, std::string pName) : LossFunction<DTYPE>(pOperator, pLabel, pName) {\n\n #ifdef __DEBUG__\n\n std::cout << \"NEG::NEG(Operator<DTYPE> *, Operator<DTYPE> *, std::string)\" << '\\n';\n\n #endif // __DEBUG__\n\n this->Alloc(pOperator, 1e-6f);\n\n }\n", "file_path": "WICWIU_src/LossFunction/NEG.hpp", "rank": 0, "score": 237384.99924656266 }, { "content": "class Softmax : public Operator<DTYPE>{\n\n DTYPE m_epsilon;\n\n ///< Softmax연산 중 더해지는 epsilon값.\n\n\n\n int m_timesize;\n\n ///< 연산 할 Tensor가 위치한 Time값.\n\n\n\n DTYPE **sum;\n\n ///< Softmax연산 중 Tensor값들의 합을 저장하기 위한 포인터.\n\n DTYPE **max;\n\n ///< Softmax연산 중 Tensor값들 중 가장 큰 값을 저장하기 위한 포인터.\n\n\n\n\n\npublic:\n\n /*!\n\n @brief Softmax의 생성자.\n\n @details 파라미터로 받은 pOperator, epsilon을 Alloc시킨다.\n\n @param pOperator Softmax할 대상 Operator, 이 매소드에서 Alloc시킨다.\n\n @param epsilon ForwardPropagate에 사용힐 값. 0으로 나누어지는 것을 방지하는 역할을 한다.\n\n @ref virtual int Alloc(Operator<DTYPE> *pOperator, DTYPE epsilon = 1e-6f\n", "file_path": "WICWIU_src/Operator/Softmax.hpp", "rank": 2, "score": 175052.0314090686 }, { "content": "class accuracy : public Dataset<DTYPE> {\n\nprivate:\n\n\n\n //textData에 있던 변수들!!!\n\n string* vocab; //이제 단어들을 갖고 있어야 하니깐!!!, 중복을 제거한 단어!\n\n char* TextData; //파일에서 읽어오기!\n\n\n\n string* wordTextData; //strtok를 사용하면 원래 data가 바뀌어서 추가한거!\n\n\n\n int vocab_size; //반복없는 단어의 개수\n\n int text_length; // 이거는 char 개수... //나중에 fastText에서 필요할 수도 있을거 같아서 남겨둠!!!\n\n int word_num; //단어의 개수\n\n\n\n //word2vec.hpp에 있던 거!!!\n\n DTYPE **m_aaInput;\n\n DTYPE **m_aaLabel;\n\n\n\n int m_numOfInput; //input data의 개수!!!\n\n\n\n int m_dimOfInput;\n", "file_path": "tutorials/SkipGram/accuracy.hpp", "rank": 3, "score": 175052.0314090686 }, { "content": "class Sequential : public Operator<DTYPE>{\n\n Operator<DTYPE> **m_listOfOperator;\n\n int m_numOfOperator;\n\npublic:\n\n Sequential(int numOfOperator, ...) {\n\n std::cout << \"Sequential::Sequential(Operator<DTYPE> *)\" << '\\n';\n\n\n\n m_listOfOperator = NULL;\n\n m_numOfOperator = 0;\n\n\n\n va_list ap;\n\n va_start(ap, numOfOperator);\n\n\n\n Alloc(numOfOperator, &ap);\n\n\n\n va_end(ap);\n\n }\n\n\n\n ~Sequential() {\n\n std::cout << \"Sequential::~Sequential()\" << '\\n';\n", "file_path": "WICWIU_src/Operator/Sequential.hpp", "rank": 4, "score": 175052.0314090686 }, { "content": "class Sigmoid : public Operator<DTYPE>{\n\npublic:\n\n /*!\n\n @brief Sigmoid의 생성자.\n\n @details 파라미터로 받은 pInput으로 Alloc한다.\n\n @param pInput Alloc할 대상 Operator\n\n @param pName Operator에 사용자가 부여한 이름.\n\n @ref int Alloc(Operator<DTYPE> *pInput)\n\n */\n\n Sigmoid(Operator<DTYPE> *pInput, std::string pName, int pLoadflag = TRUE) : Operator<DTYPE>(pInput, pName, pLoadflag) {\n\n #ifdef __DEBUG__\n\n std::cout << \"Sigmoid::Sigmoid(Operator *)\" << '\\n';\n\n #endif // __DEBUG__\n\n this->Alloc(pInput);\n\n }\n\n\n\n /*!\n\n @brief Sigmoid의 소멸자.\n\n */\n\n ~Sigmoid() {\n", "file_path": "WICWIU_src/Operator/Sigmoid.hpp", "rank": 5, "score": 175052.0314090686 }, { "content": "class Hadamard : public Operator<DTYPE>{\n\nprivate:\n\n\n\npublic:\n\n Hadamard(Operator<DTYPE> *pInput0, Operator<DTYPE> *pInput1, std::string pName, int pLoadflag = TRUE) : Operator<DTYPE>(pInput0, pInput1, pName, pLoadflag) {\n\n #ifdef __DEBUG__\n\n std::cout << \"Hadamard::Hadamard(Operator *)\" << '\\n';\n\n #endif // __DEBUG__\n\n this->Alloc(pInput0, pInput1);\n\n }\n\n\n\n\n\n ~Hadamard() {\n\n std::cout << \"Hadamard::~Hadamard()\" << '\\n';\n\n }\n\n\n\n /*!\n\n @brief 파라미터로 받은 pInput으로부터 맴버 변수들을 초기화 한다.\n\n @details Result와 Gradient를 저장하기 위해 pInput의 Shape과 같은 dim을 갖는 Tensor를 생성한다.\n\n @param pInput 생성 할 Tensor의 Shape정보를 가진 Operator\n", "file_path": "WICWIU_src/Operator/Hadamard.hpp", "rank": 6, "score": 175052.0314090686 }, { "content": "class text8 : public Dataset<DTYPE> {\n\nprivate:\n\n\n\n Langs langs;\n\n //textData에 있던 변수들!!!\n\n string* vocab; //이제 단어들을 갖고 있어야 하니깐!!!, 중복을 제거한 단어!\n\n char* TextData; //파일에서 읽어오기!\n\n\n\n string* wordTextData; //strtok를 사용하면 원래 data가 바뀌어서 추가한거!\n\n\n\n int vocab_size; //반복없는 단어의 개수\n\n int text_length; // 이거는 char 개수... //나중에 fastText에서 필요할 수도 있을거 같아서 남겨둠!!!\n\n int word_num; //단어의 개수\n\n\n\n //각 단어가 몇 번 나왔는지는 없음...! 이거 배열을 하나 더 만들어서 가능할듯!!! -> sampling 할때 필요!\n\n int* wordFrequency; //이걸.... 음.... vocab size를 미리 받아서 하는걸로 할까.... 아니면... 음... 우찌하면 좋을라나...\n\n\n\n\n\n OPTION option;\n\n\n", "file_path": "tutorials/SkipGram/text8.hpp", "rank": 7, "score": 175052.0314090686 }, { "content": "class Tanh : public Operator<DTYPE>{\n\nprivate:\n\n\n\n#ifdef __CUDNN__\n\n\n\n cudnnActivationDescriptor_t activationDesc;\n\n\n\n //deltaDesc = 본인의 deltaDesc\n\n //m_aInputDeltaDesc = 계산해서 아래에 넘겨줄 dalta\n\n cudnnTensorDescriptor_t m_aInputTensorDesc, m_aOutputTensorDesc, m_aDeltaDesc, m_aInputDeltaDesc;\n\n ///< GPU내의 Tensor값들을 가르키기 위한 descriptor.\n\n\n\n DTYPE *m_pDevInput, *m_pDevOutput, *m_pDevInputDelta, *m_pDevDelta;\n\n ///< cudnn 연산에서 사용 할 데이터를 가리키는 맴버 변수.\n\n\n\n float m_alpha;\n\n ///< 연산 간 두 Operand의 가중치를 표현하기 한 변수. ex) z = α*x + β*y\n\n float m_beta;\n\n ///< 연산 간 두 Operand의 가중치를 표현하기 귀한 변수. ex) z = α*x + β*y\n\n double m_coef;\n", "file_path": "WICWIU_src/Operator/Tanh.hpp", "rank": 8, "score": 175052.0314090686 }, { "content": "class LFWDataset : public Dataset<DTYPE>{\n\nprivate:\n\n int m_numOfImg;\n\n std::string m_rootPath;\n\n std::string m_dataPath;\n\n vision::Compose *m_transform;\n\n sem_t sem;\n\n\n\n // set of name of Class\n\n int m_useClasNum;\n\n std::vector<std::string> m_className;\n\n std::vector<std::string> m_aImagePath;\n\n std::vector<int> m_vSamplePerClass;\n\n// std::vector<int> m_aLabel;\n\n int trigger;\n\n int imgNum[20];\n\n// int count;\n\n// int check;\n\n\n\n void CheckClassList();\n", "file_path": "tutorials/LFW/LFWDataset.hpp", "rank": 9, "score": 171322.44797586554 }, { "content": "class MNISTDataSet : public Dataset<DTYPE>{\n\nprivate:\n\n DTYPE **m_aaImage;\n\n DTYPE **m_aaLabel;\n\n int m_numOfImg;\n\n\n\n OPTION m_option;\n\n\n\npublic:\n\n MNISTDataSet(string pImagePath, string pLabelPath, OPTION pOPTION) {\n\n m_aaImage = NULL;\n\n m_aaLabel = NULL;\n\n\n\n m_option = pOPTION;\n\n\n\n Alloc(pImagePath, pLabelPath);\n\n }\n\n\n\n virtual ~MNISTDataSet() {\n\n Delete();\n", "file_path": "tutorials/MNIST/MNIST.hpp", "rank": 10, "score": 171322.44797586554 }, { "content": "class BatchNormalize : public Operator<DTYPE>{\n\npublic:\n\n // enum class Mode;\n\n\n\n BatchNormalize(Operator<DTYPE> *pInput, Operator<DTYPE> *pScale, Operator<DTYPE> *pBias, int pIsChannelwise, std::string pName) : Operator<DTYPE>(pName) {\n\n #ifdef __DEBUG__\n\n std::cout << \"BatchNormalize:: BatchNormalize( Operator< DTYPE>*, Operator< DTYPE>*, Operator< DTYPE>*, int, std:: string)\" << '\\n';\n\n #endif // __DEBUG__\n\n\n\n Allocate(pInput, pScale, pBias, pIsChannelwise, 1e-6f);\n\n }\n\n\n\n BatchNormalize(Operator<DTYPE> *pInput, Operator<DTYPE> *pScale, Operator<DTYPE> *pBias, int pIsChannelwise, float pEpsilon, std::string pName) : Operator<DTYPE>(pName) {\n\n #ifdef __DEBUG__\n\n std::cout << \"BatchNormalize:: BatchNormalize( Operator< DTYPE>*, Operator< DTYPE>*, Operator< DTYPE>*, int, float, std:: string)\" << '\\n';\n\n #endif // __DEBUG__\n\n\n\n Allocate(pInput, pScale, pBias, pIsChannelwise, pEpsilon);\n\n }\n\n\n", "file_path": "WICWIU_src/backup/_BatchNormalize.h", "rank": 11, "score": 171322.4479758655 }, { "content": "class NoiseGenerator : public Operator<DTYPE>{\n\n private:\n\n public:\n\n NoiseGenerator(int pTimeSize, int pBatchSize, int pChannelSize, int pRowSize, int pColSize, std::string pName = \"No Name\") : Operator<DTYPE>(pName){\n\n this->SetResult(new Tensor<DTYPE>(pTimeSize, pBatchSize, pChannelSize, pRowSize, pColSize, NoUseTime));\n\n }\n\n\n\n NoiseGenerator(Shape *pShape, std::string pName = \"No Name\") : Operator<DTYPE>(pName){\n\n this->SetResult(new Tensor<DTYPE>(pShape, NoUseTime));\n\n }\n\n\n\n ~NoiseGenerator(){\n\n }\n\n};\n\n#endif //NOISEGENERATOR_H_", "file_path": "WICWIU_src/Operator/NoiseGenerator.hpp", "rank": 12, "score": 167807.82441469975 }, { "content": "class BatchNormalize : public Operator<DTYPE>{\n\nprivate:\n\n Tensor<DTYPE> *m_pTenInput;\n\n Tensor<DTYPE> *m_pTenScale;\n\n Tensor<DTYPE> *m_pTenBias;\n\n Tensor<DTYPE> *m_pTenResult;\n\n\n\n Tensor<DTYPE> *m_pTenDerInput;\n\n Tensor<DTYPE> *m_pTenDerScale;\n\n Tensor<DTYPE> *m_pTenDerBias;\n\n Tensor<DTYPE> *m_pTenDerResult;\n\n\n\n Tensor<DTYPE> *m_aTenTotalMean;\n\n Tensor<DTYPE> *m_aTenTotalVariance;\n\n\n\n Tensor<DTYPE> *m_aTenCachedMean;\n\n Tensor<DTYPE> *m_aTenCachedInvVariance;\n\n\n\n int m_inputTimeSize;\n\n int m_inputBatchSize;\n", "file_path": "WICWIU_src/Operator/BatchNormalize.hpp", "rank": 13, "score": 167807.82441469975 }, { "content": "class MSE : public LossFunction<DTYPE>{\n\npublic:\n\n /*!\n\n @brief MSE(Mean Squared Error) LossFunction 클래스 생성자\n\n @details LossFunction 클래스의 생성자를 호출하고, Operator를 매개변수로 전달하여 MSE<DTYPE>::Alloc(Operator<DTYPE> *pOperator) 메소드를 호출한다.\n\n @param pOperator MSE<DTYPE>::Alloc(Operator<DTYPE> *pOperator) 메소드의 매개변수로 전달할 Operator\n\n @param pLabel LossFunction의 입력 레이블에 해당하는 Operator\n\n @param pName LossFunction의 이름\n\n @return 없음\n\n @see MSE<DTYPE>::Alloc(Operator<DTYPE> *pOperator)\n\n */\n\n MSE(Operator<DTYPE> *pOperator, Operator<DTYPE> *pLabel, std::string pName) : LossFunction<DTYPE>(pOperator, pLabel, pName) {\n\n #ifdef __DEBUG__\n\n std::cout << \"MSE::MSE(Operator<DTYPE> *, MetaParameter *, std::string)\" << '\\n';\n\n #endif // __DEBUG__\n\n this->Alloc(pOperator);\n\n }\n\n\n\n /*!\n\n @brief MSE(Mean Squared Error) LossFunction 클래스 소멸자\n", "file_path": "WICWIU_src/LossFunction/MSE.hpp", "rank": 14, "score": 167807.82441469975 }, { "content": "class ReconstructionError : public Operator<DTYPE>{\n\npublic:\n\n ReconstructionError(Operator<DTYPE> *pInput, Operator<DTYPE> *pLabel, std::string pName) : Operator<DTYPE>(pInput, pLabel, pName) {\n\n #ifdef __DEBUG__\n\n std::cout << \"MSE::MSE(Operator<DTYPE> *, MetaParameter *, std::string)\" << '\\n';\n\n #endif // __DEBUG__\n\n this->Alloc(pInput);\n\n }\n\n\n\n virtual ~ReconstructionError() {\n\n #ifdef __DEBUG__\n\n std::cout << \"MSE::~MSE()\" << '\\n';\n\n #endif // __DEBUG__\n\n }\n\n\n\n virtual int Alloc(Operator<DTYPE> *pInput) {\n\n #ifdef __DEBUG__\n\n std::cout << \"MSE::Alloc(Operator<DTYPE> *, Operator<DTYPE> *)\" << '\\n';\n\n #endif // __DEBUG__\n\n\n", "file_path": "WICWIU_src/Operator/ReconstructionError.hpp", "rank": 15, "score": 167807.82441469975 }, { "content": "class ReShape : public Operator<DTYPE>{\n\npublic:\n\n /*!\n\n @brief ReShape의 생성자\n\n @details 파라미터로 받은 pInput, pRowSize, pColSize으로 Alloc한다.\n\n @param pInput ReShape할 Operator.\n\n @param pRowSize ReShape으로 새로 만들어질 Tensor의 rowsize.\n\n @param pColSize ReShape으로 새로 만들어질 Tensor의 colsize.\n\n @paramp pName 사용자가 부여한 Operator의 이름.\n\n @ref int Alloc(Operator<DTYPE> *pInput, int pTimeSize, int pBatchSize, int pChannelSize, int pRowSize, int pColSize)\n\n */\n\n ReShape(Operator<DTYPE> *pInput, int pRowSize, int pColSize, std::string pName, int pLoadflag = TRUE) : Operator<DTYPE>(pInput, pName, pLoadflag) {\n\n #ifdef __DEBUG__\n\n std::cout << \"ReShape::ReShape(Operator *)\" << '\\n';\n\n #endif // __DEBUG__\n\n this->Alloc(pInput, 0, 0, 0, pRowSize, pColSize);\n\n }\n\n\n\n /*!\n\n @brief ReShape의 생성자\n", "file_path": "WICWIU_src/Operator/ReShape.hpp", "rank": 16, "score": 167807.82441469975 }, { "content": "class LFWSampler : public DataLoader<DTYPE>{\n\nprivate:\n\n /* data */\n\n int m_numOfClass;\n\n\n\npublic:\n\n LFWSampler(int numOfClass, Dataset<DTYPE> *dataset, int batchSize = 1, int useShuffle = FALSE, int numOfWorker = 1, int dropLast = TRUE);\n\n virtual ~LFWSampler();\n\n\n\n virtual void MakeAllOfIndex(std::vector<int> *pAllOfIndex);\n\n\n\n virtual void DataPreprocess();\n\n void Tensor2Image(std::string filename, Tensor<DTYPE> *imgTensor, int doValuerScaling);\n\n};\n\n\n\ntemplate<typename DTYPE> LFWSampler<DTYPE>::LFWSampler(int numOfClass, Dataset<DTYPE> *dataset, int batchSize, int useShuffle, int numOfWorker, int dropLast)\n\n : DataLoader<DTYPE>(dataset, batchSize, useShuffle, numOfWorker, dropLast) {\n\n m_numOfClass = numOfClass;\n\n}\n\n\n", "file_path": "tutorials/LFW/LFWSampler.hpp", "rank": 17, "score": 167807.82441469975 }, { "content": "class ConcatenateChannelWise : public Operator<DTYPE>{\n\nprivate:\n\n int m_noOperator;\n\n int *m_aAccumulate;\n\n\n\n\n\npublic:\n\n ConcatenateChannelWise(Operator<DTYPE> *pInput0, Operator<DTYPE> *pInput1, std::string pName = \"NO NAME\", int pLoadflag = TRUE) : Operator<DTYPE>(pInput0, pInput1, pName, pLoadflag) {\n\n #ifdef __DEBUG__\n\n std::cout << \"ConcatenateChannelWise::ConcatenateChannelWise(Operator *)\" << '\\n';\n\n #endif // __DEBUG__\n\n\n\n m_noOperator = 0;\n\n this->Alloc(2, pInput0, pInput1);\n\n }\n\n\n\n ~ConcatenateChannelWise() {\n\n std::cout << \"ConcatenateChannelWise::~ConcatenateChannelWise()\" << '\\n';\n\n }\n\n\n", "file_path": "WICWIU_src/Operator/Concatenate.hpp", "rank": 18, "score": 167807.82441469975 }, { "content": "class CrossEntropy : public LossFunction<DTYPE>{\n\nprivate:\n\n DTYPE m_epsilon = 0.0; // for backprop\n\n\n\npublic:\n\n /*!\n\n @brief CrossEntropy LossFunction 클래스 생성자\n\n @details LossFunction 클래스의 생성자를 호출하고, Operator와 epsilon을 매개변수로 전달하여 CrossEntropy<DTYPE>::Alloc(Operator<DTYPE> *pOperator, int epsilon) 메소드를 호출한다.\n\n @param pOperator CrossEntropy<DTYPE>::Alloc(Operator<DTYPE> *pOperator, int epsilon) 메소드의 매개변수로 전달할 Operator\n\n @param pLabel LossFunction의 입력 레이블에 해당하는 Operator\n\n @param epsilon 더미 변수, 값을 미 지정시 1e-6f로 초기화\n\n @return 없음\n\n @see CrossEntropy<DTYPE>::Alloc(Operator<DTYPE> *pOperator, int epsilon)\n\n */\n\n CrossEntropy(Operator<DTYPE> *pOperator, Operator<DTYPE> *pLabel, int epsilon = 1e-6f) : LossFunction<DTYPE>(pOperator, pLabel) {\n\n #ifdef __DEBUG__\n\n std::cout << \"CrossEntropy::CrossEntropy(Operator<DTYPE> *, Operator<DTYPE> *, int)\" << '\\n';\n\n #endif // __DEBUG__\n\n this->Alloc(pOperator, epsilon);\n\n }\n", "file_path": "WICWIU_src/LossFunction/CrossEntropy.hpp", "rank": 19, "score": 161353.17083020345 }, { "content": "class HingeLoss : public LossFunction<DTYPE>{\n\nprivate:\n\n Tensor<DTYPE> *m_aindexForBackProp;\n\n ///< 역전파 메소드의 인덱스로 사용하기 위한 더미 Tensor\n\n float m_theta;\n\n ///< Hinge Loss 수식의 Threshold에 해당하는 값\n\n\n\npublic:\n\n /*!\n\n @brief HingeLoss LossFunction 클래스 생성자\n\n @details LossFunction 클래스의 생성자를 호출하고, Operator와 theta을 매개변수로 전달하여 HingeLoss<DTYPE>::Alloc(Operator<DTYPE> *pOperator, float theta) 메소드를 호출한다.\n\n @param pOperator HingeLoss<DTYPE>::Alloc(Operator<DTYPE> *pOperator, float theta) 메소드의 매개변수로 전달할 Operator\n\n @param pLabel LossFunction의 입력 레이블에 해당하는 Operator\n\n @param theta alloc 메소드의 theta 값으로 전달할 파라미터, 값을 지정하지 않을 시 1.f로 초기화\n\n @return 없음\n\n @see HingeLoss<DTYPE>::Alloc(Operator<DTYPE> *pOperator, float theta)\n\n */\n\n HingeLoss(Operator<DTYPE> *pOperator, Operator<DTYPE> *pLabel, float theta = 1.f) : LossFunction<DTYPE>(pOperator, pLabel) {\n\n #ifdef __DEBUG__\n\n std::cout << \"HingeLoss::HingeLoss(Operator<DTYPE> *, Operator<DTYPE> *, int)\" << '\\n';\n", "file_path": "WICWIU_src/LossFunction/HingeLoss.hpp", "rank": 20, "score": 161353.17083020345 }, { "content": "class CUDNNBatchNormalize : public Operator<DTYPE>{\n\npublic:\n\n CUDNNBatchNormalize(Operator<DTYPE> *pInput, Operator<DTYPE> *pScale, Operator<DTYPE> *pBias, int pIsChannelwise, std::string pName) : Operator<DTYPE>(pInput, pScale, pBias, pName) {\n\n# if __DEBUG__\n\n std::cout << \"CUDNNBatchNormalize:: CUDNNBatchNormalize( Operator< DTYPE>*, Operator< DTYPE>*, Operator< DTYPE>*, int, std:: string)\" << '\\n';\n\n# endif // __DEBUG__\n\n\n\n Alloc(pInput, pScale, pBias, pIsChannelwise, CUDNN_BN_MIN_EPSILON);\n\n }\n\n\n\n CUDNNBatchNormalize(Operator<DTYPE> *pInput, Operator<DTYPE> *pScale, Operator<DTYPE> *pBias, int pIsChannelwise, float pEpsilon, std::string pName) : Operator<DTYPE>(pInput, pScale, pBias, pName) {\n\n# if __DEBUG__\n\n std::cout << \"CUDNNBatchNormalize:: CUDNNBatchNormalize( Operator< DTYPE>*, Operator< DTYPE>*, Operator< DTYPE>*, int, float, std:: string)\" << '\\n';\n\n# endif // __DEBUG__\n\n\n\n Alloc(pInput, pScale, pBias, pIsChannelwise, pEpsilon);\n\n }\n\n\n\n ~CUDNNBatchNormalize() {\n\n# if __DEBUG__\n", "file_path": "WICWIU_src/backup/CUDNNBatchNormalize_backup.h", "rank": 21, "score": 161353.17083020345 }, { "content": "class CrossEntropy2 : public LossFunction<DTYPE>{\n\nprivate:\n\n DTYPE m_epsilon = 1e-6f; // for backprop\n\n\n\npublic:\n\n /*!\n\n @brief CrossEntropy LossFunction 클래스 생성자\n\n @details LossFunction 클래스의 생성자를 호출하고, Operator와 epsilon을 매개변수로 전달하여 CrossEntropy<DTYPE>::Alloc(Operator<DTYPE> *pOperator, int epsilon) 메소드를 호출한다.\n\n @param pOperator CrossEntropy<DTYPE>::Alloc(Operator<DTYPE> *pOperator, int epsilon) 메소드의 매개변수로 전달할 Operator\n\n @param pLabel LossFunction의 입력 레이블에 해당하는 Operator\n\n @param epsilon 더미 변수, 값을 미 지정시 1e-6f로 초기화\n\n @return 없음\n\n @see CrossEntropy<DTYPE>::Alloc(Operator<DTYPE> *pOperator, int epsilon)\n\n */\n\n CrossEntropy2(Operator<DTYPE> *pOperator, Operator<DTYPE> *pLabel, int epsilon = 1e-6f) : LossFunction<DTYPE>(pOperator, pLabel) {\n\n #ifdef __DEBUG__\n\n std::cout << \"CrossEntropy2::CrossEntropy2(Operator<DTYPE> *, Operator<DTYPE> *, int)\" << '\\n';\n\n #endif // __DEBUG__\n\n this->Alloc(pOperator, epsilon);\n\n }\n", "file_path": "WICWIU_src/LossFunction/CrossEntropy2.hpp", "rank": 22, "score": 161353.17083020345 }, { "content": "class TripletLoss : public LossFunction<DTYPE>{\n\nprivate:\n\n DTYPE m_margin;\n\n DTYPE **m_LossPerSample;\n\n\n\n int m_NumOfAnchorSample;\n\n int m_timesize;\n\n\n\n\n\npublic:\n\n TripletLoss(Operator<DTYPE> *pOperator, DTYPE margin, std::string pName = \"NO NAME\")\n\n : LossFunction<DTYPE>(pOperator, NULL, pName) {\n\n #ifdef __DEBUG__\n\n std::cout << \"TripletLoss::TripletLoss(LossFunction<DTYPE> * 3, float, )\" << '\\n';\n\n #endif // __DEBUG__\n\n\n\n Alloc(pOperator, margin);\n\n }\n\n\n\n TripletLoss(Operator<DTYPE> *pOperator, Operator<DTYPE> *pLabel, DTYPE margin, std::string pName = \"NO NAME\")\n", "file_path": "WICWIU_src/LossFunction/TripletLoss.hpp", "rank": 23, "score": 161353.17083020345 }, { "content": "class my_EmbeddingTest : public NeuralNetwork<float>{\n\nprivate:\n\npublic:\n\n my_EmbeddingTest(Tensorholder<float> *x, Tensorholder<float> *label, Operator<float> *pWeight) {\n\n SetInput(2, x, label);\n\n\n\n Operator<float> *out = NULL;\n\n\n\n out = new EmbeddingTestLayer<float>(x, pWeight, \"Embedding_Test_\");\n\n\n\n AnalyzeGraph(out);\n\n\n\n // ======================= Select LossFunction Function ===================\n\n SetLossFunction(new NEG<float>(out, label, \"NCE\"));\n\n SetOptimizer(new AdagradOptimizer<float>(GetParameter(), 0.001, 0.9, MINIMIZE));\n\n\n\n }\n\n\n\n virtual ~my_EmbeddingTest() {}\n\n};\n", "file_path": "tutorials/SkipGram/net/my_EmbeddingTest.hpp", "rank": 24, "score": 157981.6720321382 }, { "content": "class WGANDiscriminatorLoss : public LossFunction<DTYPE>{\n\npublic:\n\n WGANDiscriminatorLoss(Operator<DTYPE> *pOperator, Operator<DTYPE> *pLabel, std::string pName) : LossFunction<DTYPE>(pOperator, pLabel, pName){\n\n #ifdef __DEBUG__\n\n std::cout << \"WGANDiscriminatorLoss::WGANDiscriminatorLoss(Operator<DTYPE> *, MetaParameter *, std::string)\" << '\\n';\n\n #endif // __DEBUG__\n\n this->Alloc(pOperator);\n\n }\n\n\n\n virtual ~WGANDiscriminatorLoss(){\n\n #ifdef __DEBUG__\n\n std::cout << \"WGANDiscriminatorLoss::~WGANDiscriminatorLoss()\" << '\\n';\n\n #endif // __DEBUG__\n\n Delete();\n\n }\n\n\n\n virtual int Alloc(Operator<DTYPE> *pOperator){\n\n #ifdef __DEBUG__\n\n std::cout << \"WGANDiscriminatorLoss::Alloc(Operator<DTYPE> *)\" << '\\n';\n\n #endif // __DEBUG__\n", "file_path": "WICWIU_src/LossFunction/WGANDiscriminatorLoss.hpp", "rank": 25, "score": 155565.6601468825 }, { "content": "class BEGANDiscriminatorLoss : public LossFunction<DTYPE>{\n\npublic:\n\n BEGANDiscriminatorLoss(Operator<DTYPE> *pOperator, Operator<DTYPE> *pLabel, std::string pName) : LossFunction<DTYPE>(pOperator, pLabel, pName){\n\n #ifdef __DEBUG__\n\n std::cout << \"BEGANDiscriminatorLoss::BEGANDiscriminatorLoss(Operator<DTYPE> *, MetaParameter *, std::string)\" << '\\n';\n\n #endif // __DEBUG__\n\n this->Alloc(pOperator);\n\n }\n\n\n\n virtual ~BEGANDiscriminatorLoss(){\n\n #ifdef __DEBUG__\n\n std::cout << \"BEGANDiscriminatorLoss::~BEGANDiscriminatorLoss()\" << '\\n';\n\n #endif // __DEBUG__\n\n Delete();\n\n }\n\n\n\n virtual int Alloc(Operator<DTYPE> *pOperator){\n\n #ifdef __DEBUG__\n\n std::cout << \"BEGANDiscriminatorLoss::Alloc(Operator<DTYPE> *)\" << '\\n';\n\n #endif // __DEBUG__\n", "file_path": "WICWIU_src/LossFunction/BEGANDiscriminatorLoss.hpp", "rank": 26, "score": 155565.6601468825 }, { "content": "class SoftmaxCrossEntropy : public LossFunction<DTYPE>{\n\nprivate:\n\n Tensor<DTYPE> *m_aSoftmaxResult;\n\n ///< Softmax 연산의 Result 텐서에 대한 포인터\n\n DTYPE m_epsilon; // for backprop\n\n ///< translation 요소 멤버 변수\n\n\n\n int m_timesize;\n\n ///< Time 축의 사이즈 멤버 변수\n\n\n\n DTYPE **sum;\n\n ///< 텐서의 합을 저장하기 위한 이중 포인터\n\n DTYPE **max;\n\n ///< 텐서의 최댓값을 저장하기 위한 이중 포인터\n\n\n\npublic:\n\n /*!\n\n @brief SoftmaxCrossEntropy LossFunction 클래스 생성자\n\n @details LossFunction 클래스의 생성자를 호출하고, Operator와 epsilon을 매개변수로 전달하여 SoftmaxCrossEntropy<DTYPE>::Alloc(Operator<DTYPE> *pOperator, DTYPE epsilon) 메소드를 호출한다.\n\n @param pOperator SoftmaxCrossEntropy<DTYPE>::Alloc(Operator<DTYPE> *pOperator, DTYPE epsilon) 메소드의 매개변수로 전달할 Operator\n", "file_path": "WICWIU_src/LossFunction/SoftmaxCrossEntropy.hpp", "rank": 27, "score": 155565.6601468825 }, { "content": "class WGANGeneratorLoss : public LossFunction<DTYPE>{\n\npublic:\n\n WGANGeneratorLoss(Operator<DTYPE> *pOperator, Operator<DTYPE> *pLabel, std::string pName) : LossFunction<DTYPE>(pOperator, pLabel, pName){\n\n #ifdef __DEBUG__\n\n std::cout << \"WGANGeneratorLoss::WGANGeneratorLoss(Operator<DTYPE> *, MetaParameter *, std::string)\" << '\\n';\n\n #endif // __DEBUG__\n\n this->Alloc(pOperator);\n\n }\n\n\n\n virtual ~WGANGeneratorLoss(){\n\n #ifdef __DEBUG__\n\n std::cout << \"WGANGeneratorLoss::~WGANGeneratorLoss()\" << '\\n';\n\n #endif // __DEBUG__\n\n Delete();\n\n }\n\n\n\n virtual int Alloc(Operator<DTYPE> *pOperator){\n\n #ifdef __DEBUG__\n\n std::cout << \"WGANGeneratorLoss::Alloc(Operator<DTYPE> *)\" << '\\n';\n\n #endif // __DEBUG__\n", "file_path": "WICWIU_src/LossFunction/WGANGeneratorLoss.hpp", "rank": 28, "score": 155565.66014688247 }, { "content": "class BEGANGeneratorLoss : public LossFunction<DTYPE>{\n\npublic:\n\n BEGANGeneratorLoss(Operator<DTYPE> *pOperator, Operator<DTYPE> *pLabel, std::string pName) : LossFunction<DTYPE>(pOperator, pLabel, pName){\n\n #ifdef __DEBUG__\n\n std::cout << \"BEGANGeneratorLoss::BEGANGeneratorLoss(Operator<DTYPE> *, MetaParameter *, std::string)\" << '\\n';\n\n #endif // __DEBUG__\n\n this->Alloc(pOperator);\n\n }\n\n\n\n virtual ~BEGANGeneratorLoss(){\n\n #ifdef __DEBUG__\n\n std::cout << \"BEGANGeneratorLoss::~BEGANGeneratorLoss()\" << '\\n';\n\n #endif // __DEBUG__\n\n Delete();\n\n }\n\n\n\n virtual int Alloc(Operator<DTYPE> *pOperator){\n\n #ifdef __DEBUG__\n\n std::cout << \"BEGANGeneratorLoss::Alloc(Operator<DTYPE> *)\" << '\\n';\n\n #endif // __DEBUG__\n", "file_path": "WICWIU_src/LossFunction/BEGANGeneratorLoss.hpp", "rank": 29, "score": 155565.6601468825 }, { "content": "class VanillaGANGeneratorLoss : public LossFunction<DTYPE>{\n\nprivate:\n\nDTYPE m_epsilon;\n\npublic:\n\n VanillaGANGeneratorLoss(Operator<DTYPE> *pOperator, Operator<DTYPE> *pLabel, DTYPE epsilon, std::string pName) : LossFunction<DTYPE>(pOperator, pLabel, pName){\n\n #ifdef __DEBUG__\n\n std::cout << \"VanillaGANGeneratorLoss::VanillaGANGeneratorLoss(Operator<DTYPE> *, Operator<DTYPE> *, MetaParameter *, std::string)\" << '\\n';\n\n #endif // __DEBUG__\n\n this->Alloc(pOperator, epsilon);\n\n }\n\n\n\n VanillaGANGeneratorLoss(Operator<DTYPE> *pOperator, Operator<DTYPE> *pLabel, std::string pName) : LossFunction<DTYPE>(pOperator, pLabel, pName){\n\n #ifdef __DEBUG__\n\n std::cout << \"VanillaGANGeneratorLoss::VanillaGANGeneratorLoss(Operator<DTYPE> *, MetaParameter *, std::string)\" << '\\n';\n\n #endif // __DEBUG__\n\n this->Alloc(pOperator, 1e-6f);\n\n }\n\n\n\n virtual ~VanillaGANGeneratorLoss(){\n\n #ifdef __DEBUG__\n", "file_path": "WICWIU_src/LossFunction/VanillaGANGeneratorLoss.hpp", "rank": 30, "score": 150346.94272658654 }, { "content": "class VanillaGANDiscriminatorLoss : public LossFunction<DTYPE>{\n\nprivate:\n\n DTYPE m_epsilon;\n\npublic:\n\n VanillaGANDiscriminatorLoss(Operator<DTYPE> *pOperator, Operator<DTYPE> *pLabel, DTYPE epsilon, std::string pName) : LossFunction<DTYPE>(pOperator, pLabel, pName){\n\n #ifdef __DEBUG__\n\n std::cout << \"VanillaGANDiscriminatorLoss::VanillaGANDiscriminatorLoss(Operator<DTYPE> *, MetaParameter *, std::string)\" << '\\n';\n\n #endif // __DEBUG__\n\n this->Alloc(pOperator, epsilon);\n\n }\n\n\n\n VanillaGANDiscriminatorLoss(Operator<DTYPE> *pOperator, Operator<DTYPE> *pLabel, std::string pName) : LossFunction<DTYPE>(pOperator, pLabel, pName){\n\n #ifdef __DEBUG__\n\n std::cout << \"VanillaGANDiscriminatorLoss::VanillaGANDiscriminatorLoss(Operator<DTYPE> *, MetaParameter *, std::string)\" << '\\n';\n\n #endif // __DEBUG__\n\n this->Alloc(pOperator, 1e-6f);\n\n }\n\n\n\n virtual ~VanillaGANDiscriminatorLoss(){\n\n #ifdef __DEBUG__\n", "file_path": "WICWIU_src/LossFunction/VanillaGANDiscriminatorLoss.hpp", "rank": 31, "score": 150346.94272658654 }, { "content": "enum OPTION {\n\n ONEHOT,\n\n CBOWMODE,\n\n SKIPGRAM\n\n};\n\n\n\n\n\nvoid MakeOneHotVector(int* onehotvector, int vocab_size, int index){\n\n\n\n for(int i=0; i<vocab_size; i++){\n\n if(i==index)\n\n onehotvector[i] = 1;\n\n else\n\n onehotvector[i] = 0;\n\n }\n\n}\n\n\n\n\n\nvoid Eliminate(char *str, char ch){\n\n\n", "file_path": "tutorials/Embedding/text8.hpp", "rank": 32, "score": 150307.02096801356 }, { "content": "enum OPTION {\n\n TESTING,\n\n TRAINING\n\n};\n\n\n\nint ReverseInt(int i) {\n\n unsigned char ch1, ch2, ch3, ch4;\n\n\n\n ch1 = i & 255;\n\n ch2 = (i >> 8) & 255;\n\n ch3 = (i >> 16) & 255;\n\n ch4 = (i >> 24) & 255;\n\n\n\n return ((int)ch1 << 24) + ((int)ch2 << 16) + ((int)ch3 << 8) + ch4;\n\n}\n\n\n\ntemplate<typename DTYPE> void IMAGE_Reader(string pImagePath, DTYPE **pImage) {\n\n ifstream fin;\n\n fin.open(pImagePath, ios_base::binary);\n\n\n", "file_path": "tutorials/MNIST/MNIST.hpp", "rank": 34, "score": 150307.02096801356 }, { "content": "enum OPTION {\n\n ONEHOT,\n\n CBOWMODE\n\n};\n\n\n\n\n\nvoid MakeOneHotVector(int* onehotvector, int vocab_size, int index){\n\n\n\n for(int i=0; i<vocab_size; i++){\n\n if(i==index)\n\n onehotvector[i] = 1;\n\n else\n\n onehotvector[i] = 0;\n\n }\n\n}\n\n\n\n\n\nvoid Eliminate(char *str, char ch){\n\n\n\n int length = strlen(str);\n", "file_path": "tutorials/RNN/TextDataset2.hpp", "rank": 35, "score": 147078.67645640054 }, { "content": "enum OPTION {\n\n ONEHOT,\n\n //CBOW\n\n};\n\n\n\n\n\nvoid MakeOneHotVector(int* onehotvector, int vocab_size, int index){\n\n\n\n for(int i=0; i<vocab_size; i++){\n\n if(i==index)\n\n onehotvector[i] = 1;\n\n else\n\n onehotvector[i] = 0;\n\n }\n\n}\n\n\n\n//: public Dataset<DTYPE>{\n\n\n\ntemplate<typename DTYPE>\n", "file_path": "tutorials/RNN/TextDataset.hpp", "rank": 36, "score": 147078.67645640054 }, { "content": "enum OPTION {\n\n ONEHOT,\n\n CBOWMODE\n\n};\n\n\n\n\n\nvoid MakeOneHotVector(int* onehotvector, int vocab_size, int index){\n\n\n\n for(int i=0; i<vocab_size; i++){\n\n if(i==index)\n\n onehotvector[i] = 1;\n\n else\n\n onehotvector[i] = 0;\n\n }\n\n}\n\n\n\n\n\nvoid Eliminate(char *str, char ch){\n\n\n\n int length = strlen(str);\n", "file_path": "tutorials/Embedding/textData.hpp", "rank": 37, "score": 147078.67645640054 }, { "content": "enum OPTION {\n\n ONEHOT,\n\n CBOWMODE,\n\n SKIPGRAM,\n\n ACCURACY\n\n};\n\n\n\n\n\nvoid MakeOneHotVector(int* onehotvector, int vocab_size, int index){\n\n\n\n for(int i=0; i<vocab_size; i++){\n\n if(i==index)\n\n onehotvector[i] = 1;\n\n else\n\n onehotvector[i] = 0;\n\n }\n\n}\n\n\n\n\n\nvoid Eliminate(char *str, char ch){\n", "file_path": "tutorials/SkipGram/text8.hpp", "rank": 38, "score": 147078.67645640054 }, { "content": "enum OPTION {\n\n TESTING,\n\n TESTIMAGE,\n\n TESTLABEL,\n\n TRAINING,\n\n TRAINIMAGE,\n\n TRAINLABEL,\n\n DEFAULT\n\n};\n\nint random_generator(int upperbound) {\n\n return rand() % upperbound;\n\n}\n\n\n\ntemplate<typename DTYPE>\n", "file_path": "tutorials/GAN/DCGAN/MNIST_Reader.hpp", "rank": 39, "score": 144060.64565808955 }, { "content": "enum OPTION {\n\n ONEHOT,\n\n CBOWMODE\n\n};\n\n\n\n\n\nvoid MakeOneHotVector(int* onehotvector, int vocab_size, int index){\n\n\n\n for(int i=0; i<vocab_size; i++){\n\n if(i==index)\n\n onehotvector[i] = 1;\n\n else\n\n onehotvector[i] = 0;\n\n }\n\n}\n\n\n\n\n\nvoid Eliminate(char *str, char ch){\n\n\n\n int length = strlen(str);\n", "file_path": "tutorials/Embedding/BatchTextData.hpp", "rank": 40, "score": 144060.64565808955 }, { "content": "enum OPTION {\n\n TESTING,\n\n TESTIMAGE,\n\n TESTLABEL,\n\n TRAINING,\n\n TRAINIMAGE,\n\n TRAINLABEL,\n\n DEFAULT\n\n};\n\nint random_generator(int upperbound) {\n\n return rand() % upperbound;\n\n}\n\n\n\ntemplate<typename DTYPE>\n", "file_path": "tutorials/GAN/WGAN/MNIST_Reader.hpp", "rank": 41, "score": 144060.64565808955 }, { "content": "enum OPTION {\n\n TESTING,\n\n TESTIMAGE,\n\n TESTLABEL,\n\n TRAINING,\n\n TRAINIMAGE,\n\n TRAINLABEL,\n\n DEFAULT\n\n};\n\nint random_generator(int upperbound) {\n\n return rand() % upperbound;\n\n}\n\n\n\ntemplate<typename DTYPE>\n", "file_path": "tutorials/GAN/VanillaGAN/MNIST_Reader.hpp", "rank": 42, "score": 141233.02524031588 }, { "content": "enum OPTION {\n\n ONEHOT,\n\n CBOW\n\n};\n\n\n\n\n\nvoid MakeOneHotVector(int* onehotvector, int vocab_size, int index){\n\n\n\n for(int i=0; i<vocab_size; i++){\n\n if(i==index)\n\n onehotvector[i] = 1;\n\n else\n\n onehotvector[i] = 0;\n\n }\n\n}\n\n\n\nstring replaceAll(const string &str, const string &pattern, const string &replace){\n\n\n\n string result = str;\n\n string::size_type pos = 0;\n", "file_path": "tutorials/RNN/WordTextDataSet.hpp", "rank": 43, "score": 141233.02524031588 }, { "content": "enum OPTION {\n\n ONEHOT,\n\n CBOW\n\n};\n\n\n\n\n\nvoid MakeOneHotVector(int* onehotvector, int vocab_size, int index){\n\n\n\n for(int i=0; i<vocab_size; i++){\n\n if(i==index)\n\n onehotvector[i] = 1;\n\n else\n\n onehotvector[i] = 0;\n\n }\n\n}\n\n\n\n//: public Dataset<DTYPE>{\n\n\n\ntemplate<typename DTYPE>\n", "file_path": "tutorials/RNN/BatchTextDataSet.hpp", "rank": 44, "score": 141233.02524031588 }, { "content": "class Padding : public Transform{\n\nprivate:\n\n int p_value;\n\n int newHeight;\n\n int newWidth;\n\n\n\npublic:\n\n Padding(int padding_value) : p_value(padding_value){\n\n\n\n }\n\n\n\n virtual ~Padding() {}\n\n\n\n virtual void DoTransform(ImageWrapper& imgWrp){\n\n unsigned char *oldImgBuf = imgWrp.imgBuf;\n\n Shape *oldImgShape = imgWrp.imgShape;\n\n\n\n int oldWidth = oldImgShape->GetDim(2);\n\n int oldHeight = oldImgShape->GetDim(1);\n\n int channel = oldImgShape->GetDim(0);\n", "file_path": "tutorials/LFW/ImageProcess.hpp", "rank": 45, "score": 123871.17806359148 }, { "content": "class Compose : public Transform {\n\nprivate:\n\n std::vector<Transform *> m_listOfTransform;\n\n int m_size;\n\n\n\npublic:\n\n Compose(std::initializer_list<Transform *> lvalue) : m_listOfTransform(lvalue) {\n\n // std::cout << \"Compose\" << '\\n';\n\n m_size = m_listOfTransform.size();\n\n }\n\n\n\n virtual ~Compose() {\n\n for (int i = 0; i < m_size; i++) {\n\n delete m_listOfTransform[i];\n\n m_listOfTransform[i] = NULL;\n\n }\n\n }\n\n\n\n virtual void DoTransform(ImageWrapper& imgWrp) {\n\n // std::cout << \"do Compose\" << '\\n';\n", "file_path": "tutorials/LFW/ImageProcess.hpp", "rank": 46, "score": 123871.17806359148 }, { "content": "class Resize : public Transform {\n\nprivate:\n\n int newHeight;\n\n int newWidth;\n\n\n\npublic:\n\n Resize(int heigth, int width) : newHeight(heigth), newWidth(width) {\n\n // std::cout << \"CenterCrop\" << '\\n';\n\n }\n\n\n\n Resize(int size) : newHeight(size), newWidth(size) {\n\n // std::cout << \"CenterCrop\" << '\\n';\n\n }\n\n\n\n virtual ~Resize() {}\n\n\n\n virtual void DoTransform(ImageWrapper& imgWrp) {\n\n unsigned char *oldImgBuf = imgWrp.imgBuf;\n\n Shape *oldImgShape = imgWrp.imgShape;\n\n\n", "file_path": "tutorials/LFW/ImageProcess.hpp", "rank": 47, "score": 123871.17806359148 }, { "content": "class Normalize : public Transform{\n\nprivate:\n\n std::vector<float> list_mean;\n\n std::vector<float> list_stddev;\n\n\n\npublic:\n\n Normalize(std::initializer_list<float> mean_value, std::initializer_list<float> stddev_value) : list_mean(mean_value), list_stddev(stddev_value){\n\n\n\n }\n\n\n\n virtual ~Normalize() {\n\n }\n\n\n\n virtual void DoTransform(ImageWrapper& imgWrp){\n\n unsigned char *oldImgBuf = imgWrp.imgBuf;\n\n Shape *oldImgShape = imgWrp.imgShape;\n\n\n\n int oldWidth = oldImgShape->GetDim(2);\n\n int oldHeight = oldImgShape->GetDim(1);\n\n int channel = oldImgShape->GetDim(0);\n", "file_path": "tutorials/LFW/ImageProcess.hpp", "rank": 48, "score": 123871.17806359148 }, { "content": "class Padding : public Transform{\n\nprivate:\n\n int p_value;\n\n int newHeight;\n\n int newWidth;\n\n\n\npublic:\n\n Padding(int padding_value) : p_value(padding_value){\n\n\n\n }\n\n\n\n virtual ~Padding() {}\n\n\n\n virtual void DoTransform(ImageWrapper& imgWrp){\n\n unsigned char *oldImgBuf = imgWrp.imgBuf;\n\n Shape *oldImgShape = imgWrp.imgShape;\n\n\n\n int oldWidth = oldImgShape->GetDim(2);\n\n int oldHeight = oldImgShape->GetDim(1);\n\n int channel = oldImgShape->GetDim(0);\n", "file_path": "tutorials/GAN/BEGAN/ImageProcess.hpp", "rank": 49, "score": 121232.67145742854 }, { "content": "class Compose : public Transform {\n\nprivate:\n\n std::vector<Transform *> m_listOfTransform;\n\n int m_size;\n\n\n\npublic:\n\n Compose(std::initializer_list<Transform *> lvalue) : m_listOfTransform(lvalue) {\n\n m_size = m_listOfTransform.size();\n\n }\n\n\n\n virtual ~Compose() {\n\n for (int i = 0; i < m_size; i++) {\n\n delete m_listOfTransform[i];\n\n m_listOfTransform[i] = NULL;\n\n }\n\n }\n\n\n\n virtual void DoTransform(ImageWrapper& imgWrp) {\n\n for (int i = 0; i < m_size; i++) {\n\n m_listOfTransform[i]->DoTransform(imgWrp);\n\n }\n\n }\n\n};\n\n\n", "file_path": "tutorials/GAN/BEGAN/ImageProcess.hpp", "rank": 50, "score": 121232.67145742854 }, { "content": "class Normalize : public Transform{\n\nprivate:\n\n std::vector<float> list_mean;\n\n std::vector<float> list_stddev;\n\n\n\npublic:\n\n Normalize(std::initializer_list<float> mean_value, std::initializer_list<float> stddev_value) : list_mean(mean_value), list_stddev(stddev_value){\n\n\n\n }\n\n\n\n virtual ~Normalize() {\n\n }\n\n\n\n virtual void DoTransform(ImageWrapper& imgWrp){\n\n unsigned char *oldImgBuf = imgWrp.imgBuf;\n\n Shape *oldImgShape = imgWrp.imgShape;\n\n\n\n int oldWidth = oldImgShape->GetDim(2);\n\n int oldHeight = oldImgShape->GetDim(1);\n\n int channel = oldImgShape->GetDim(0);\n", "file_path": "tutorials/GAN/BEGAN/ImageProcess.hpp", "rank": 51, "score": 121232.67145742854 }, { "content": "class HorizentalFlip : public Transform {\n\nprivate:\n\n int m_heigth;\n\n int m_width;\n\n\n\npublic:\n\n HorizentalFlip(int heigth, int width) : m_heigth(heigth), m_width(width) {\n\n }\n\n\n\n HorizentalFlip(int size) : m_heigth(size), m_width(size) {\n\n }\n\n\n\n virtual ~HorizentalFlip() {}\n\n\n\n virtual void DoTransform(ImageWrapper& imgWrp) {\n\n unsigned char *imgBuf = imgWrp.imgBuf;\n\n Shape *imgShape = imgWrp.imgShape;\n\n\n\n int width = imgShape->GetDim(2);\n\n int height = imgShape->GetDim(1);\n", "file_path": "tutorials/LFW/ImageProcess.hpp", "rank": 52, "score": 121232.67145742854 }, { "content": "class Resize : public Transform {\n\nprivate:\n\n int newHeight;\n\n int newWidth;\n\n\n\npublic:\n\n Resize(int heigth, int width) : newHeight(heigth), newWidth(width) {\n\n // std::cout << \"CenterCrop\" << '\\n';\n\n }\n\n\n\n Resize(int size) : newHeight(size), newWidth(size) {\n\n // std::cout << \"CenterCrop\" << '\\n';\n\n }\n\n\n\n virtual ~Resize() {}\n\n\n\n virtual void DoTransform(ImageWrapper& imgWrp) {\n\n unsigned char *oldImgBuf = imgWrp.imgBuf;\n\n Shape *oldImgShape = imgWrp.imgShape;\n\n\n", "file_path": "tutorials/GAN/BEGAN/ImageProcess.hpp", "rank": 53, "score": 121232.67145742854 }, { "content": "class CenterCrop : public Transform {\n\nprivate:\n\n int m_heigth;\n\n int m_width;\n\n\n\npublic:\n\n CenterCrop(int heigth, int width) : m_heigth(heigth), m_width(width) {\n\n // std::cout << \"CenterCrop\" << '\\n';\n\n }\n\n\n\n CenterCrop(int size) : m_heigth(size), m_width(size) {\n\n // std::cout << \"CenterCrop\" << '\\n';\n\n }\n\n\n\n virtual ~CenterCrop() {}\n\n\n\n virtual void DoTransform(ImageWrapper& imgWrp) {\n\n unsigned char *imgBuf = imgWrp.imgBuf;\n\n Shape *imgShape = imgWrp.imgShape;\n\n\n", "file_path": "tutorials/LFW/ImageProcess.hpp", "rank": 54, "score": 121232.67145742854 }, { "content": "class VerticalFlip : public Transform {\n\nprivate:\n\n int m_heigth;\n\n int m_width;\n\n\n\npublic:\n\n VerticalFlip(int heigth, int width) : m_heigth(heigth), m_width(width) {\n\n }\n\n\n\n VerticalFlip(int size) : m_heigth(size), m_width(size) {\n\n }\n\n\n\n virtual ~VerticalFlip() {}\n\n\n\n virtual void DoTransform(ImageWrapper& imgWrp) {\n\n unsigned char *imgBuf = imgWrp.imgBuf;\n\n Shape *imgShape = imgWrp.imgShape;\n\n\n\n int width = imgShape->GetDim(2);\n\n int height = imgShape->GetDim(1);\n", "file_path": "tutorials/LFW/ImageProcess.hpp", "rank": 55, "score": 121232.67145742854 }, { "content": "class RandomCrop : public Transform {\n\nprivate:\n\n int m_heigth;\n\n int m_width;\n\n\n\npublic:\n\n RandomCrop(int heigth, int width) : m_heigth(heigth), m_width(width) {\n\n }\n\n\n\n RandomCrop(int size) : m_heigth(size), m_width(size) {\n\n }\n\n\n\n virtual ~RandomCrop() {}\n\n\n\n virtual void DoTransform(ImageWrapper& imgWrp) {\n\n unsigned char *imgBuf = imgWrp.imgBuf;\n\n Shape *imgShape = imgWrp.imgShape;\n\n\n\n int width = imgShape->GetDim(2);\n\n int height = imgShape->GetDim(1);\n", "file_path": "tutorials/LFW/ImageProcess.hpp", "rank": 56, "score": 121232.67145742854 }, { "content": "enum IsUseTime {\n\n UseTime,\n\n NoUseTime\n\n};\n\n\n\n/*!\n\n@class Tensor 다차원의 tensor데이터를 저장하고 관리하는 클래스\n\n@details 학습에 사용될 Tensor를 정의하기 위한 클래스\n\n@details Tensor클래스는 Shape와 LongArray를 이용하여 Tensor의 모양과 데이터를 저장한다.\n\n@details Operator클래스에서 m_aaResult(ForwardPropagate한 값)와 m_aaGradient(BackPropagate한 값)을 저장한다.\n\n*/\n\ntemplate<typename DTYPE> class Tensor {\n\nprivate:\n\n Shape *m_aShape;\n\n ///< Tensor를 구성하는 Shape 클래스, 텐서의 차원을 정의\n\n LongArray<DTYPE> *m_aLongArray;\n\n ///< Tensor를 구성하는 LongArray 클래스, 텐서의 원소들의 값을 저장\n\n Device m_Device;\n\n ///< 장치 사용 구분자, CPU 또는 GPU, Device 참고\n\n int m_idOfDevice;\n", "file_path": "WICWIU_src/Tensor.hpp", "rank": 57, "score": 119870.66352250989 }, { "content": "class RandomCrop : public Transform {\n\nprivate:\n\n int m_heigth;\n\n int m_width;\n\n\n\npublic:\n\n RandomCrop(int heigth, int width) : m_heigth(heigth), m_width(width) {\n\n }\n\n\n\n RandomCrop(int size) : m_heigth(size), m_width(size) {\n\n }\n\n\n\n virtual ~RandomCrop() {}\n\n\n\n virtual void DoTransform(ImageWrapper& imgWrp) {\n\n unsigned char *imgBuf = imgWrp.imgBuf;\n\n Shape *imgShape = imgWrp.imgShape;\n\n\n\n int width = imgShape->GetDim(2);\n\n int height = imgShape->GetDim(1);\n", "file_path": "tutorials/GAN/BEGAN/ImageProcess.hpp", "rank": 58, "score": 118750.75149846417 }, { "content": "class VerticalFlip : public Transform {\n\nprivate:\n\n int m_heigth;\n\n int m_width;\n\n\n\npublic:\n\n VerticalFlip(int heigth, int width) : m_heigth(heigth), m_width(width) {\n\n }\n\n\n\n VerticalFlip(int size) : m_heigth(size), m_width(size) {\n\n }\n\n\n\n virtual ~VerticalFlip() {}\n\n\n\n virtual void DoTransform(ImageWrapper& imgWrp) {\n\n unsigned char *imgBuf = imgWrp.imgBuf;\n\n Shape *imgShape = imgWrp.imgShape;\n\n\n\n int width = imgShape->GetDim(2);\n\n int height = imgShape->GetDim(1);\n", "file_path": "tutorials/GAN/BEGAN/ImageProcess.hpp", "rank": 59, "score": 118750.75149846417 }, { "content": "class HorizentalFlip : public Transform {\n\nprivate:\n\n int m_heigth;\n\n int m_width;\n\n\n\npublic:\n\n HorizentalFlip(int heigth, int width) : m_heigth(heigth), m_width(width) {\n\n }\n\n\n\n HorizentalFlip(int size) : m_heigth(size), m_width(size) {\n\n }\n\n\n\n virtual ~HorizentalFlip() {}\n\n\n\n virtual void DoTransform(ImageWrapper& imgWrp) {\n\n unsigned char *imgBuf = imgWrp.imgBuf;\n\n Shape *imgShape = imgWrp.imgShape;\n\n\n\n int width = imgShape->GetDim(2);\n\n int height = imgShape->GetDim(1);\n", "file_path": "tutorials/GAN/BEGAN/ImageProcess.hpp", "rank": 60, "score": 118750.75149846417 }, { "content": "class CenterCrop : public Transform {\n\nprivate:\n\n int m_heigth;\n\n int m_width;\n\n\n\npublic:\n\n CenterCrop(int heigth, int width) : m_heigth(heigth), m_width(width) {\n\n // std::cout << \"CenterCrop\" << '\\n';\n\n }\n\n\n\n CenterCrop(int size) : m_heigth(size), m_width(size) {\n\n // std::cout << \"CenterCrop\" << '\\n';\n\n }\n\n\n\n virtual ~CenterCrop() {}\n\n\n\n virtual void DoTransform(ImageWrapper& imgWrp) {\n\n unsigned char *imgBuf = imgWrp.imgBuf;\n\n Shape *imgShape = imgWrp.imgShape;\n\n\n", "file_path": "tutorials/GAN/BEGAN/ImageProcess.hpp", "rank": 61, "score": 118750.75149846417 }, { "content": "enum MODEL_OPTION {\n\n isSLP,\n\n isMLP\n\n};\n\n\n", "file_path": "tutorials/MNIST/net/my_NN.hpp", "rank": 62, "score": 116823.14640495976 }, { "content": "class my_NN : public NeuralNetwork<float>{\n\nprivate:\n\npublic:\n\n my_NN(Tensorholder<float> *x, Tensorholder<float> *label, MODEL_OPTION pOption) {\n\n SetInput(2, x, label);\n\n\n\n if (pOption == isSLP) SLP(x, label);\n\n else if (pOption == isMLP) MLP(x, label);\n\n }\n\n\n\n void SLP(Tensorholder<float> *x, Tensorholder<float> *label) {\n\n Operator<float> *out = x;\n\n\n\n // ======================= layer 1======================\n\n out = new Linear<float>(out, 784, 10, TRUE, \"1\");\n\n\n\n AnalyzeGraph(out);\n\n\n\n // ======================= Select LossFunction Function ===================\n\n SetLossFunction(new HingeLoss<float>(out, label, \"HL\"));\n", "file_path": "tutorials/MNIST/net/my_NN.hpp", "rank": 63, "score": 113913.79806085314 }, { "content": "class my_RNN : public NeuralNetwork<float>{\n\nprivate:\n\npublic:\n\n my_RNN(Tensorholder<float> *x, Tensorholder<float> *label, int vocab_length) {\n\n SetInput(2, x, label);\n\n\n\n Operator<float> *out = NULL;\n\n\n\n //out = new ReShape<float>(x, 28, 28, \"Flat2Image\");\n\n\n\n //out = new CBOW<float>(x(입력 배열), 아웃풋크기, \"CBOW\");\n\n //out = new OnehotVector<float>(x(입력 배열), 아웃풋크기, \"OnehotVector\");\n\n\n\n\n\n // ======================= layer 1=======================\n\n out = new RecurrentLayer<float>(x, vocab_length, 32, vocab_length, TRUE, \"Recur_1\");\n\n //out = new DeepRecurrentLayer<float>(x, vocab_length, 128, vocab_length, TRUE, \"Recur_1\");\n\n\n\n //out = new LSTMLayer<float>(x, vocab_length, 32, vocab_length, TRUE, \"Recur_1\");\n\n //out = new LSTM2Layer<float>(x, vocab_length, 128, vocab_length, TRUE, \"Recur_1\");\n", "file_path": "tutorials/RNN/net/my_RNN.hpp", "rank": 64, "score": 113913.79806085314 }, { "content": "class my_CNN : public NeuralNetwork<float>{\n\nprivate:\n\npublic:\n\n my_CNN(Tensorholder<float> *x, Tensorholder<float> *label) {\n\n SetInput(2, x, label);\n\n\n\n Operator<float> *out = NULL;\n\n\n\n out = new ReShape<float>(x, 28, 28, \"Flat2Image\");\n\n\n\n // ======================= layer 1=======================\n\n out = new ConvolutionLayer2D<float>(out, 1, 10, 3, 3, 1, 1, 0, FALSE, \"Conv_1\");\n\n out = new Relu<float>(out, \"Relu_1\");\n\n out = new Maxpooling2D<float>(out, 2, 2, 2, 2, \"MaxPool_1\");\n\n\n\n // ======================= layer 2=======================\n\n out = new ConvolutionLayer2D<float>(out, 10, 20, 3, 3, 1, 1, 0, FALSE, \"Conv_2\");\n\n out = new Relu<float>(out, \"Relu_2\");\n\n out = new Maxpooling2D<float>(out, 2, 2, 2, 2, \"MaxPool_2\");\n\n\n", "file_path": "tutorials/MNIST/net/my_CNN.hpp", "rank": 65, "score": 113913.79806085314 }, { "content": "class my_Embedding : public NeuralNetwork<float>{\n\nprivate:\n\npublic:\n\n my_Embedding(Tensorholder<float> *x, Tensorholder<float> *label, int vocab_length) {\n\n SetInput(2, x, label);\n\n\n\n Operator<float> *out = NULL;\n\n\n\n\n\n //CBOW 실험해보기!\n\n //out = new CBOWLayer<float>(x, vocab_length, 128, 2, \"CBOW\");\n\n out = new SKIPGRAMLayer<float>(x, vocab_length, 128, 2, \"CBOW\");\n\n\n\n\n\n\n\n AnalyzeGraph(out);\n\n\n\n // ======================= Select LossFunction Function ===================\n\n // SetLossFunction(new HingeLoss<float>(out, label, \"HL\"));\n\n // SetLossFunction(new MSE<float>(out, label, \"MSE\"));\n", "file_path": "tutorials/Embedding/net/my_Embedding.hpp", "rank": 66, "score": 113913.79806085314 }, { "content": "class my_CNN : public NeuralNetwork<float>{\n\nprivate:\n\npublic:\n\n my_CNN(Tensorholder<float> *x, Tensorholder<float> *label) {\n\n SetInput(2, x, label);\n\n\n\n Operator<float> *out = NULL;\n\n\n\n out = new ReShape<float>(x, 3, 32, 32, \"Flat2Image\");\n\n\n\n // ======================= layer 1=======================\n\n out = new ConvolutionLayer2D<float>(out, 3, 32, 3, 3, 1, 1, 0, TRUE, \"Conv_1\");\n\n out = new BatchNormalizeLayer<float>(out, TRUE, \"BN_1\");\n\n out = new Relu<float>(out, \"Relu_1\");\n\n out = new Maxpooling2D<float>(out, 2, 2, 2, 2, \"MaxPool_1\");\n\n\n\n // ======================= layer 2=======================\n\n out = new ConvolutionLayer2D<float>(out, 32, 64, 3, 3, 1, 1, 0, TRUE, \"Conv_2\");\n\n out = new BatchNormalizeLayer<float>(out, TRUE, \"BN_2\");\n\n out = new Relu<float>(out, \"Relu_2\");\n", "file_path": "tutorials/CIFAR10/net/my_CNN.hpp", "rank": 67, "score": 113913.79806085314 }, { "content": "class my_Embedding : public NeuralNetwork<float>{\n\nprivate:\n\npublic:\n\n my_Embedding(Tensorholder<float> *x, Tensorholder<float> *label, int vocab_length) {\n\n SetInput(2, x, label);\n\n\n\n Operator<float> *out = NULL;\n\n\n\n\n\n //CBOW 실험해보기!\n\n //out = new CBOWLayer<float>(x, vocab_length, 128, 2, \"CBOW\");\n\n out = new SKIPGRAMLayer<float>(x, vocab_length, 200, \"SKIPGRAM\"); // 128 : 이게 embedding dim!\n\n\n\n\n\n //skip gram with negative sampling에서는 sigmoid + corssentropy!!!\n\n out = new Sigmoid<float>(out, \"sigmoid\");\n\n\n\n AnalyzeGraph(out);\n\n\n\n // ======================= Select LossFunction Function ===================\n", "file_path": "tutorials/SkipGram/net/my_Embedding.hpp", "rank": 68, "score": 111574.9271062457 }, { "content": "class my_SeqToSeq : public NeuralNetwork<float>{\n\nprivate:\n\npublic:\n\n my_SeqToSeq(Tensorholder<float> *input1, Tensorholder<float> *input2, Tensorholder<float> *label, int vocab_length) {\n\n SetInput(2, input1, input2, label);\n\n\n\n Operator<float> *out = NULL;\n\n\n\n //out = new CBOW<float>(x(입력 배열), 아웃풋크기, \"CBOW\");\n\n //out = new OnehotVector<float>(x(입력 배열), 아웃풋크기, \"OnehotVector\");\n\n\n\n\n\n // ======================= layer 1=======================\n\n out = new Encoder<float>(input1, vocab_length, 32, TRUE, \"Encoder\");\n\n\n\n out = new Decoder<float>(input2, out, vocab_length, 32, vocab_length, TRUE, \"Decoder\");\n\n\n\n AnalyzeGraph(out);\n\n\n\n // ======================= Select LossFunction Function ===================\n", "file_path": "tutorials/RNN/net/my_SeqToSeq.hpp", "rank": 69, "score": 109367.08432415868 }, { "content": "class AutoEncoder : public NeuralNetwork<float>{\n\nprivate:\n\npublic:\n\n AutoEncoder(Tensorholder<float> *x, Tensorholder<float> *label) {\n\n SetInput(2, x, label);\n\n Operator<float> *out = NULL;\n\n\n\n out = new ReShape<float>(x, 28, 28, \"Flat2Image\");\n\n\n\n // ======================= layer 1=======================\n\n out = new ConvolutionLayer2D<float>(out, 1, 10, 3, 3, 1, 1, 0, TRUE, \"Conv_1\");\n\n\n\n out = new Relu<float>(out, \"Relu_1\");\n\n\n\n out = new Maxpooling2D<float>(out, 2, 2, 2, 2, \"MaxPool_1\");\n\n\n\n // ======================= layer 2=======================\n\n out = new ConvolutionLayer2D<float>(out, 10, 20, 7, 7, 1, 1, 0, TRUE, \"Conv_2\");\n\n\n\n out = new Relu<float>(out, \"Relu_2\");\n", "file_path": "tutorials/MNIST/net/AutoEncoder.hpp", "rank": 70, "score": 109367.08432415868 }, { "content": "class TextDataset {\n\nprivate:\n\n\n\n char* vocab ;\n\n char* TextData;\n\n\n\n int vocab_size;\n\n int text_length;\n\n\n\n Tensor<DTYPE>* input;\n\n Tensor<DTYPE>* label;\n\n\n\n OPTION option;\n\n\n\n int VOCAB_LENGTH;\n\n\n\npublic:\n\n TextDataset(string File_Path, int vocab_length, OPTION pOption) {\n\n vocab = NULL;\n\n TextData = NULL;\n", "file_path": "tutorials/RNN/TextDataset.hpp", "rank": 71, "score": 98272.51320461185 }, { "content": "enum Mode {\n\n TRAIN,\n\n ACCUMULATE,\n\n INFERENCE,\n\n};\n\n\n\n/*!\n\n * @class Operator class\n\n * @details 본 프래임워크의 가장 작은 연산 단위.\n\n */\n\ntemplate<typename DTYPE> class Operator {\n\nprivate:\n\n Container<Operator<DTYPE> *> *m_apOutput;\n\n ///< Operator의 m_aaResult값을 사용할 Operator들의 주소 값.\n\n Container<Operator<DTYPE> *> *m_apInput;\n\n ///< Operator에 input으로 들어오는 Operator들의 주소 값.\n\n Container<Tensor<DTYPE> *> *m_aaResult;\n\n ///< Operator의 결과 값.\n\n Container<Tensor<DTYPE> *> *m_aaGradient;\n\n ///< Operator의 Gradiuent값들의 Array.\n", "file_path": "WICWIU_src/Operator.hpp", "rank": 72, "score": 75123.54785211763 }, { "content": "class Shape {\n\nprivate:\n\n int m_Rank;\n\n ///< Shape 클래스를 구성하는 Rank 멤버변수, 텐서를 구성하는 축의 개수\n\n int *m_aDim;\n\n ///< Shape 클래스를 구성하는 Dimension 멤버변수, 각 축의 차원\n\n Device m_Device;\n\n ///< 장치 사용 구분자, CPU 또는 GPU, Device 참고\n\n int m_idOfDevice;\n\n ///< GPU 사용 시, 사용하려는 GPU의 번호. CPU의 경우 -1\n\n\n\n#ifdef __CUDNN__\n\n cudnnTensorDescriptor_t m_desc;\n\n ///< cudnn의 Tensor Descriptor, GPU 연산에서 사용하는 Tensor의 shape 정보를 담고 있는 포인터 변수\n\n#endif // if __CUDNN__\n\n\n\nprivate:\n\n int Alloc(int pRank, ...);\n\n int Alloc(Shape *pShape);\n\n void Delete();\n", "file_path": "WICWIU_src/Shape.hpp", "rank": 73, "score": 74015.25718499895 }, { "content": "class text8 {\n\nprivate:\n\n\n\n //textData에 있던 변수들!!!\n\n string* vocab; //이제 단어들을 갖고 있어야 하니깐!!!, 중복을 제거한 단어!\n\n char* TextData; //파일에서 읽어오기!\n\n\n\n string* wordTextData; //strtok를 사용하면 원래 data가 바뀌어서 추가한거!\n\n\n\n int vocab_size; //반복없는 단어의 개수\n\n int text_length; // 이거는 char 개수...\n\n int word_num; //단어의 개수\n\n\n\n //각 단어가 몇 번 나왔는지는 없음...! 이거 배열을 하나 더 만들어서 가능할듯!!!\n\n\n\n OPTION option;\n\n\n\n //word2vec.hpp에 있던 거!!!\n\n DTYPE **m_aaInput;\n\n DTYPE **m_aaLabel;\n", "file_path": "tutorials/Embedding/text8.hpp", "rank": 74, "score": 74015.25718499895 }, { "content": "enum OptimizeDirection {\n\n MAXIMIZE,\n\n MINIMIZE\n\n};\n\n\n\ntemplate<typename DTYPE> class Optimizer {\n\nprivate:\n\n float m_LearningRate;\n\n int m_OptimizeDirection; // 1 or -1\n\n float m_weightDecayRate;\n\n\n\n Container<Operator<DTYPE> *> *m_ppParameters;\n\n int m_numOfParameter;\n\n\n\n int m_idOfDevice;\n\n\n\n#ifdef __CUDNN__\n\n cudnnHandle_t m_pCudnnHandle;\n\n#endif // if __CUDNN__\n\n\n", "file_path": "WICWIU_src/Optimizer.hpp", "rank": 75, "score": 73509.53089859136 }, { "content": "class Transform {\n\nprivate:\n\n /* data */\n\n\n\npublic:\n\n Transform() {\n\n // std::cout << \"Transform\" << '\\n';\n\n }\n\n\n\n virtual ~Transform() {}\n\n\n\n virtual void DoTransform(ImageWrapper& imgWrp) {\n\n // std::cout << \"do Transform\" << '\\n';\n\n }\n\n};\n\n\n", "file_path": "tutorials/LFW/ImageProcess.hpp", "rank": 76, "score": 72417.62615812138 }, { "content": "class Langs {\n\n\n\nprivate:\n\n string lang1; // Language 1 이름\n\n string lang2; // Language 2 이름\n\n vector<string> line1; // Language 1 data\n\n vector<string> line2; // Language 2 data\n\n vector<string> vocab1; // Language 1 Vocab\n\n vector<string> vocab2; // Language 2 Vocab\n\n\n\n char* TextData; // 전체 text file 받을 char 배열 포인터\n\n\n\n vector<string> wordTextData1; // line1의 전체 vocab\n\n vector<string> wordTextData2; // line2의 전체 vocab\n\n\n\n vector<int> wordFrequency1; // vocab1 frequency\n\n vector<int> wordFrequency2; // vocab2 frequency\n\n\n\n int text_lines; // text file의 전체 line수\n\n\n", "file_path": "tutorials/SkipGram/Langs.hpp", "rank": 77, "score": 72417.62615812138 }, { "content": "class FewShotClassifier {\n\n\tstd::vector<std::string> m_aClassName;\n\n\tint m_noClass;\n\n\tint m_inputDim;\n\n\tint m_featureDim;\n\n\n\n\tNeuralNetwork<float> *m_pNN;\n\n\tKNearestNeighbor *m_knn;\t\t// k-NN classifier, dimension of knn = output dim of m_pNN\n\n\n\n\n\npublic:\n\n\tFewShotClassifier(int inputDim, int featureDim, const std::vector<std::string> vClassName, NeuralNetwork<float> *pNN, int noRef, int *pRefLabel, float *pRefSample[], int batchSize);\n\n\n\n\tFewShotClassifier(int inputDim, int featureDim, const std::vector<std::string> vClassName, NeuralNetwork<float> *pNN, KNearestNeighbor *kNN);\n\n\t// dim: sample dim (== input dim of m_pNN, 784 for MNIST)\n\n\t// vClassName.size() == <# of classes>\n\n\t// length of pLabel = noRefSample\n\n\n\n\tstd::string Recognize(float *pInputSample, int k = 3);\t\t\t\t// returns the name of the nearest class\n\n\n", "file_path": "WICWIU_src/FewShotClassifier.hpp", "rank": 78, "score": 70924.07439308855 }, { "content": "class ImageWrapper {\n\npublic:\n\n unsigned char *imgBuf;\n\n Shape *imgShape;\n\n\n\n ~ImageWrapper() {\n\n if (imgBuf) {\n\n delete[] imgBuf;\n\n imgBuf = NULL;\n\n }\n\n\n\n if (imgShape) {\n\n delete imgShape;\n\n imgShape = NULL;\n\n }\n\n }\n\n};\n\n\n\nnamespace vision {\n", "file_path": "tutorials/LFW/ImageProcess.hpp", "rank": 79, "score": 70924.07439308855 }, { "content": "class TextDataset2 {\n\nprivate:\n\n\n\n string* vocab; //이제 단어들을 갖고 있어야 하니깐!!!, 중복을 제거한 단어!\n\n char* TextData;\n\n\n\n string* wordTextData; //\n\n\n\n int vocab_size; //반복없는 단어의 개수\n\n int text_length; // 이거는 char 개수...\n\n int word_num; //단어의 개수\n\n\n\n Tensor<DTYPE>* input;\n\n Tensor<DTYPE>* label;\n\n\n\n OPTION option;\n\n\n\n int VOCAB_LENGTH;\n\n\n\npublic:\n", "file_path": "tutorials/RNN/TextDataset2.hpp", "rank": 80, "score": 70924.07439308855 }, { "content": "class Transform {\n\nprivate:\n\n /* data */\n\n\n\npublic:\n\n Transform() {\n\n // std::cout << \"Transform\" << '\\n';\n\n }\n\n\n\n virtual ~Transform() {}\n\n\n\n virtual void DoTransform(ImageWrapper& imgWrp) {\n\n // std::cout << \"do Transform\" << '\\n';\n\n }\n\n};\n\n\n", "file_path": "tutorials/GAN/BEGAN/ImageProcess.hpp", "rank": 81, "score": 70924.07439308855 }, { "content": "class textData {\n\nprivate:\n\n\n\n string* vocab; //이제 단어들을 갖고 있어야 하니깐!!!, 중복을 제거한 단어!\n\n char* TextData; //파일에서 읽어오기!\n\n\n\n string* wordTextData; //strtok를 사용하면 원래 data가 바뀌어서 추가한거!\n\n\n\n int vocab_size; //반복없는 단어의 개수\n\n int text_length; // 이거는 char 개수...\n\n int word_num; //단어의 개수\n\n\n\n Tensor<DTYPE>* input;\n\n Tensor<DTYPE>* label;\n\n\n\n OPTION option;\n\n\n\n int VOCAB_LENGTH;\n\n\n\npublic:\n", "file_path": "tutorials/Embedding/textData.hpp", "rank": 82, "score": 70924.07439308855 }, { "content": "class ImageWrapper {\n\npublic:\n\n unsigned char *imgBuf;\n\n Shape *imgShape;\n\n\n\n ~ImageWrapper() {\n\n if (imgBuf) {\n\n delete[] imgBuf;\n\n imgBuf = NULL;\n\n }\n\n\n\n if (imgShape) {\n\n delete imgShape;\n\n imgShape = NULL;\n\n }\n\n }\n\n};\n\n\n\nnamespace vision {\n", "file_path": "tutorials/GAN/BEGAN/ImageProcess.hpp", "rank": 83, "score": 69524.75220321157 }, { "content": "class Field {\n\nprivate:\n\n bool sequential; // 시퀀셜\n\n string* preprocessing;\n\n // bool use_vocab;\n\n // bool init_token;\n\n // bool eos_token;\n\n // bool fix_length;\n\n // string postprocessing;\n\n // bool lower;\n\n // bool include_lengths;\n\n\n\n\n\n // bool tokenize; // 뭐지?\n\n // tokenizer_language='en';\n\n //batch_first=False,\n\n // pad_token=\"<pad>\",\n\n // unk_token=\"<unk>\",\n\n // pad_first=False,\n\n // truncate_first=False,\n", "file_path": "tutorials/SkipGram/TextDataSet/Field.hpp", "rank": 84, "score": 68211.01474627685 }, { "content": "class BatchTextData {\n\nprivate:\n\n\n\n string* vocab; //이제 단어들을 갖고 있어야 하니깐!!!, 중복을 제거한 단어!\n\n char* TextData;\n\n\n\n string* wordTextData; //\n\n\n\n int vocab_size; //반복없는 단어의 개수\n\n int text_length; // 이거는 char 개수...\n\n int word_num; //단어의 개수\n\n int batch_size;\n\n\n\n Tensor<DTYPE>* input;\n\n Tensor<DTYPE>* label;\n\n\n\n OPTION option;\n\n\n\n int VOCAB_LENGTH;\n\n\n", "file_path": "tutorials/Embedding/BatchTextData.hpp", "rank": 85, "score": 68211.01474627685 }, { "content": "class KNearestNeighbor {\n\n int m_dim;\n\n int m_noClass;\n\n\n\n std::vector<float*> m_vRefVector;\n\n std::vector<int> m_vRefLabel;\n\n\tstd::vector<int> m_vRefIndex;\n\n\n\npublic:\n\n KNearestNeighbor(){\n\n m_dim = 0;\n\n m_noClass = 0;\n\n }\n\n\n\n KNearestNeighbor(int dim, int noClass, int noRef, int *pRefLabel, float *pRefVector[]);\n\n virtual ~KNearestNeighbor();\n\n\n\n void AddReference(int label, float *pRefVector);\n\n int Recognize(float *pInput, int k = 3);\n\n\n\n float GetAccuracy(int noTestSamples, int *pTestLabels, float *pTestVectors[], int k = 3);\n\n};\n\n\n\n#endif // __KNearsestNeighbor__\n", "file_path": "WICWIU_src/KNearestNeighbor.hpp", "rank": 86, "score": 68211.01474627685 }, { "content": "class MNISTDataSet {\n\nprivate:\n\n DTYPE **m_aaTestImage;\n\n DTYPE **m_aaTestLabel;\n\n DTYPE **m_aaTrainImage;\n\n DTYPE **m_aaTrainLabel;\n\n\n\n // µû·Î ÇØÁ¦\n\n Tensor<DTYPE> *m_aTestImageFeed;\n\n Tensor<DTYPE> *m_aTestLabelFeed;\n\n Tensor<DTYPE> *m_aTrainImageFeed;\n\n Tensor<DTYPE> *m_aTrainLabelFeed;\n\n\n\n vector<int> *m_ShuffledListTest;\n\n vector<int> *m_ShuffledListTrain;\n\n\n\n int m_RecallNumOfTest;\n\n int m_RecallNumOfTrain;\n\n\n\npublic:\n", "file_path": "tutorials/GAN/DCGAN/MNIST_Reader.hpp", "rank": 87, "score": 68211.01474627685 }, { "content": "class MNISTDataSet {\n\nprivate:\n\n DTYPE **m_aaTestImage;\n\n DTYPE **m_aaTestLabel;\n\n DTYPE **m_aaTrainImage;\n\n DTYPE **m_aaTrainLabel;\n\n\n\n // µû·Î ÇØÁ¦\n\n Tensor<DTYPE> *m_aTestImageFeed;\n\n Tensor<DTYPE> *m_aTestLabelFeed;\n\n Tensor<DTYPE> *m_aTrainImageFeed;\n\n Tensor<DTYPE> *m_aTrainLabelFeed;\n\n\n\n vector<int> *m_ShuffledListTest;\n\n vector<int> *m_ShuffledListTrain;\n\n\n\n int m_RecallNumOfTest;\n\n int m_RecallNumOfTrain;\n\n\n\npublic:\n", "file_path": "tutorials/GAN/WGAN/MNIST_Reader.hpp", "rank": 88, "score": 68211.01474627685 }, { "content": "enum IsTruncated{\n\n UseTruncated,\n\n NoUseTruncated,\n\n};\n\n\n\ntemplate<typename DTYPE> class GaussianNoiseGenerator : public NoiseGenerator<DTYPE> {\n\nprivate:\n\n std::queue<Tensor<DTYPE> *> *m_aaQForNoise;\n\n \n\n float m_mean;\n\n float m_stddev;\n\n float m_trunc;\n\n IsTruncated m_isTruncated;\n\n IsUseTime m_Answer;\n\n \n\n //for thread\n\n pthread_t m_thread;\n\n \n\n sem_t m_full;\n\n sem_t m_empty;\n", "file_path": "WICWIU_src/Operator/NoiseGenerator/GaussianNoiseGenerator.hpp", "rank": 89, "score": 68011.3288055121 }, { "content": "class MNISTDataSet {\n\nprivate:\n\n DTYPE **m_aaTestImage;\n\n DTYPE **m_aaTestLabel;\n\n DTYPE **m_aaTrainImage;\n\n DTYPE **m_aaTrainLabel;\n\n\n\n // µû·Î ÇØÁ¦\n\n Tensor<DTYPE> *m_aTestImageFeed;\n\n Tensor<DTYPE> *m_aTestLabelFeed;\n\n Tensor<DTYPE> *m_aTrainImageFeed;\n\n Tensor<DTYPE> *m_aTrainLabelFeed;\n\n\n\n vector<int> *m_ShuffledListTest;\n\n vector<int> *m_ShuffledListTrain;\n\n\n\n int m_RecallNumOfTest;\n\n int m_RecallNumOfTrain;\n\n\n\npublic:\n", "file_path": "tutorials/GAN/VanillaGAN/MNIST_Reader.hpp", "rank": 90, "score": 66975.24326570166 }, { "content": "class BatchTextDataSet {\n\nprivate:\n\n\n\n char* vocab ;\n\n char* TextData;\n\n\n\n int vocab_size;\n\n int text_length;\n\n\n\n Tensor<DTYPE>* input;\n\n Tensor<DTYPE>* label;\n\n\n\n OPTION option;\n\n\n\n //batch를 위해 추가\n\n int batchsize;\n\n int timesize;\n\n\n\n int VOCAB_LENGTH;\n\n\n", "file_path": "tutorials/RNN/BatchTextDataSet.hpp", "rank": 91, "score": 65810.69724075429 }, { "content": "class WordTextDataSet {\n\nprivate:\n\n\n\n char* vocab ;\n\n string *wordVocab; //string 배열?\n\n\n\n\n\n char* TextData;\n\n string strTextData;\n\n\n\n int vocab_size;\n\n int text_length;\n\n\n\n Tensor<DTYPE>* input;\n\n Tensor<DTYPE>* label;\n\n\n\n OPTION option;\n\n\n\n int VOCAB_LENGTH;\n\n\n", "file_path": "tutorials/RNN/WordTextDataSet.hpp", "rank": 92, "score": 65810.69724075429 }, { "content": "#include \"../WICWIU_src/NeuralNetwork.hpp\"\n\n\n\nint main(int argc, char const *argv[]) {\n\n\n\n int vocabsize = 10;\n\n int embeddingDim = 5;\n\n\n\n //batch 없는거!\n\n //Tensorholder<float> *pWeight = new Tensorholder<float>(Tensor<float>::Random_normal(1, 1, 1, vocabsize, embeddingDim, 0.0, 0.01), \"SKIPGRAMLayer_pWeight_in_\");\n\n //Tensorholder<float> *input0 = new Tensorholder<float>(Tensor<float>::Random_normal(1, 1, 1, 1, 3, 0.0, 0.1), \"label\");\n\n\n\n Tensorholder<float> *pWeight = new Tensorholder<float>(Tensor<float>::Random_normal(1, 1, 1, vocabsize, embeddingDim, 0.0, 0.01), \"SKIPGRAMLayer_pWeight_in_\");\n\n Tensorholder<float> *input0 = new Tensorholder<float>(Tensor<float>::Random_normal(1, 2, 1, 1, 3, 0.0, 0.1), \"label\");\n\n\n\n\n\n\n\n //batch1\n\n (*(input0->GetResult()))[0] = 0;\n\n (*(input0->GetResult()))[1] = 4;\n\n (*(input0->GetResult()))[2] = 9;\n", "file_path": "Test/EmbeddingTest.cpp", "rank": 93, "score": 60819.31845856986 }, { "content": " std::cout << embedding->GetResult()->GetShape() << '\\n';\n\n std::cout << embedding->GetResult() << '\\n';\n\n\n\n //batch1\n\n for(int i = 0; i < embeddingDim; i++){\n\n (*(embedding->GetGradient()))[i] = 1;\n\n }\n\n for(int i = 0; i < embeddingDim; i++){\n\n (*(embedding->GetGradient()))[i+embeddingDim] = 4;\n\n }\n\n for(int i = 0; i < embeddingDim; i++){\n\n (*(embedding->GetGradient()))[i+embeddingDim*2] = 9;\n\n }\n\n\n\n //batch2\n\n for(int i = 0; i < embeddingDim; i++){\n\n (*(embedding->GetGradient()))[i+embeddingDim*3] = 2;\n\n }\n\n for(int i = 0; i < embeddingDim; i++){\n\n (*(embedding->GetGradient()))[i+embeddingDim*4] = 6;\n", "file_path": "Test/EmbeddingTest.cpp", "rank": 94, "score": 60816.20036028822 }, { "content": " }\n\n for(int i = 0; i < embeddingDim; i++){\n\n (*(embedding->GetGradient()))[i+embeddingDim*5] = 7;\n\n }\n\n\n\n\n\n std::cout<<\"embedding의 gradient값\"<<'\\n';\n\n std::cout << embedding->GetGradient()->GetShape() << '\\n';\n\n std::cout << embedding->GetGradient() << '\\n';\n\n\n\n\n\n\n\n\n\n std::cout<<\"==========================backpropagate이후==========================\"<<'\\n';\n\n embedding->BackPropagate(0);\n\n std::cout << pWeight->GetGradient()->GetShape() << '\\n';\n\n std::cout << pWeight->GetGradient() << '\\n';\n\n\n\n\n\n }\n", "file_path": "Test/EmbeddingTest.cpp", "rank": 95, "score": 60815.78481779911 }, { "content": "\n\n Operator<float> *embedding = new Embedding<float>(pWeight, input0, \"embeddingtest\");\n\n\n\n #ifdef __CUDNN__\n\n std::cout<<\"GPU에서 동작 중 입니다.\"<<'\\n';\n\n cudnnHandle_t m_cudnnHandle;\n\n cudnnCreate(&m_cudnnHandle);\n\n pWeight->SetDeviceGPU(m_cudnnHandle, 0);\n\n input0->SetDeviceGPU(m_cudnnHandle, 0);\n\n embedding->SetDeviceGPU(m_cudnnHandle, 0);\n\n #endif // ifdef __CUDNN__\n\n\n\n\n\n #ifdef __CUDNN__\n\n embedding->ForwardPropagateOnGPU(0);\n\n #else // ifdef __CUDNN__\n\n embedding->ForwardPropagate(0);\n\n #endif\n\n\n\n std::cout<<\"forwardPropagate 결과\"<<'\\n';\n", "file_path": "Test/EmbeddingTest.cpp", "rank": 96, "score": 60814.17954917022 }, { "content": "\n\n //batch2\n\n (*(input0->GetResult()))[3] = 1;\n\n (*(input0->GetResult()))[4] = 6;\n\n (*(input0->GetResult()))[5] = 7;\n\n\n\n // (*(pWeight->GetResult()))[0] = 1;\n\n // (*(pWeight->GetResult()))[1] = 2;\n\n // (*(pWeight->GetResult()))[2] = 2;\n\n // (*(pWeight->GetResult()))[3] = 4;\n\n // (*(pWeight->GetResult()))[4] = 5;\n\n // (*(pWeight->GetResult()))[5] = 6;\n\n\n\n std::cout<<\"weight\"<<'\\n';\n\n std::cout << pWeight->GetResult()->GetShape() << '\\n';\n\n std::cout << pWeight->GetResult() << '\\n';\n\n\n\n std::cout<<\"input0\"<<'\\n';\n\n std::cout << input0->GetResult()->GetShape() << '\\n';\n\n std::cout << input0->GetResult() << '\\n';\n", "file_path": "Test/EmbeddingTest.cpp", "rank": 97, "score": 60812.20220921827 }, { "content": "#include \"../WICWIU_src/NeuralNetwork.hpp\"\n\n#include \"../WICWIU_src/DataLoader.hpp\"\n\n\n\n#include <unistd.h>\n\n\n\nint main(int argc, char const *argv[]) {\n\n Dataset<float> *ds = new Dataset<float>();\n\n //DataLoader(Dataset<DTYPE> *dataset, int batchSize, int useShuffle, int numOfWorker, int dropLast);\n\n DataLoader<float> * dl = new DataLoader<float>(ds, 6, FALSE, 5, FALSE);\n\n\n\n sleep(2);\n\n\n\n delete ds;\n\n delete dl;\n\n\n\n return 0;\n\n}\n", "file_path": "Test/DataLoaderTest.cpp", "rank": 98, "score": 59515.975304039704 }, { "content": "#include \"../WICWIU_src/NeuralNetwork.hpp\"\n\n\n\n\n\n//batch 적용해서 실험하기!!!\n\n//batch = 3\n\n//col = 5 -> embedding dim = 5\n\n//row = 4인 이유 : positive, neg, neg, neg\n\n\n\n//결과 : 1 3 1 1 4\n\n//pos neg neg neg\n\n\n\n//Operator<DTYPE> *pWeight, Operator<DTYPE> *pInput\n\n\n\nint main(int argc, char const *argv[]) {\n\n Tensorholder<float> *input0 = new Tensorholder<float>(Tensor<float>::Random_normal(1, 3, 1, 1, 5, 0.0, 0.1), \"x\");\n\n Tensorholder<float> *pWeight = new Tensorholder<float>(Tensor<float>::Random_normal(1, 3, 1, 4, 5, 0.0, 0.1), \"weight\");\n\n\n\n Tensorholder<float> *pWeight2 = new Tensorholder<float>(Tensor<float>::Random_normal(1, 1, 1, 10, 5, 0.0, 0.1), \"weight\");\n\n\n\n std::cout<<pWeight2->GetResult()<<'\\n';\n", "file_path": "Test/DotProductTest.cpp", "rank": 99, "score": 59514.84890553465 } ]
C++
include/GafferBindings/SignalBinding.inl
ddesmond/gaffer
4f25df88103b7893df75865ea919fb035f92bac0
#ifndef GAFFERBINDINGS_SIGNALBINDING_INL #define GAFFERBINDINGS_SIGNALBINDING_INL #include "IECorePython/ExceptionAlgo.h" #include "IECorePython/ScopedGILLock.h" #include "IECorePython/ScopedGILRelease.h" #include "boost/signals.hpp" #include "boost/version.hpp" namespace GafferBindings { namespace Detail { template<typename Signal, typename Caller> struct Slot; template<typename Result, typename... Args, typename Combiner, typename Caller> struct Slot<boost::signal<Result( Args... ), Combiner>, Caller> { Slot( boost::python::object slot ) : m_slot( boost::python::borrowed( slot.ptr() ) ) { } ~Slot() { IECorePython::ScopedGILLock gilLock; m_slot.reset(); } using Signal = boost::signal<Result( Args... ), Combiner>; typename Signal::slot_result_type operator()( Args&&... args ) { IECorePython::ScopedGILLock gilLock; try { return Caller()( boost::python::object( m_slot ), std::forward<Args>( args )... ); } catch( const boost::python::error_already_set &e ) { IECorePython::ExceptionAlgo::translatePythonException(); } } boost::python::handle<PyObject> m_slot; }; struct Trackable : public boost::signals::trackable { }; template<typename Visitor, typename Signal, typename Caller> void visit_each( Visitor &visitor, const Slot<Signal, Caller> &slot, int ) { boost::python::object gaffer = boost::python::import( "Gaffer" ); boost::python::object weakMethod = gaffer.attr( "WeakMethod" ); if( PyObject_IsInstance( slot.m_slot.get(), weakMethod.ptr() ) ) { boost::python::object self = boost::python::object( slot.m_slot ).attr( "instance" )(); boost::python::extract<Trackable &> e( self ); if( e.check() ) { boost::visit_each( visitor, e(), 0 ); } } } GAFFERBINDINGS_API boost::python::object pythonConnection( const boost::signals::connection &connection, bool scoped ); template<typename Signal, typename SlotCaller> boost::python::object connect( Signal &s, boost::python::object &slot, bool scoped ) { return pythonConnection( s.connect( Slot<Signal, SlotCaller>( slot ) ), scoped ); } template<typename Signal, typename SlotCaller> boost::python::object connectInGroup( Signal &s, int group, boost::python::object &slot, bool scoped ) { return pythonConnection( s.connect( group, Slot<Signal, SlotCaller>( slot ) ), scoped ); } } template<typename Signal> struct DefaultSignalCaller; template<typename Result, typename... Args, typename Combiner> struct DefaultSignalCaller<boost::signal<Result( Args... ), Combiner>> { using Signal = boost::signal<Result( Args... ), Combiner>; static Result call( Signal &s, Args... args ) { IECorePython::ScopedGILRelease gilRelease; return s( args... ); } }; template<typename Signal> struct DefaultSlotCaller; template<typename Result, typename... Args, typename Combiner> struct DefaultSlotCaller<boost::signal<Result( Args... ), Combiner>> { using Signal = boost::signal<Result ( Args... )>; typename Signal::slot_result_type operator()( boost::python::object slot, Args&&... args ) { return boost::python::extract<typename Signal::slot_result_type>( slot( std::forward<Args>( args )... ) )(); } }; template<typename Signal, typename SignalCaller, typename SlotCaller> SignalClass<Signal, SignalCaller, SlotCaller>::SignalClass( const char *className, const char *docString ) : boost::python::class_<Signal, boost::noncopyable>( className, docString ) { this->def( "connect", &Detail::connect<Signal, SlotCaller>, ( boost::python::arg( "slot" ), boost::python::arg( "scoped" ) = true ) ); this->def( "connect", &Detail::connectInGroup<Signal, SlotCaller>, ( boost::python::arg( "group" ), boost::python::arg( "slot" ), boost::python::arg( "scoped" ) = true ) ); this->def( "num_slots", &Signal::num_slots ); this->def( "empty", &Signal::empty ); this->def( "__call__", &SignalCaller::call ); } } #endif
#ifndef GAFFERBINDINGS_SIGNALBINDING_INL #define GAFFERBINDINGS_SIGNALBINDING_INL #include "IECorePython/ExceptionAlgo.h" #include "IECorePython/ScopedGILLock.h" #include "IECorePython/ScopedGILRelease.h" #include "boost/signals.hpp" #include "boost/version.hpp" namespace GafferBindings { namespace Detail { template<typename Signal, typename Caller> struct Slot; template<typename Result, typename... Args, typename Combiner, typename Caller> struct Slot<boost::signal<Result( Args... ), Combiner>, Caller> { Slot( boost::python::object slot ) : m_slot( boost::python::borrowed( slot.ptr() ) ) { } ~Slot() { IECorePython::ScopedGILLock gilLock; m_slot.reset(); } using Signal = boost::signal<Result( Args... ), Combiner>; typename Signal::slot_result_type operator()( Args&&... args ) { IECorePython::ScopedGILLock gilLock; try { return Caller()( boost::python::object( m_slot ), std::forward<Args>( args )... ); } catch( const boost::python::error_already_set &e ) { IECorePython::ExceptionAlgo::translatePythonException(); } } boost::python::handle<PyObject> m_slot; }; struct Trackable : public boost::signals::trackable { }; template<typename Visitor, typename Signal, typename Caller> void visit_each( Visitor &visitor, const Slot<Signal, Caller> &slot, int ) { boost::python::object gaffer = boost::python::import( "Gaffer" ); boost::python::object weakMethod = gaffer.attr( "WeakMethod" ); if( PyObject_IsInstance( slot.m_slot.ge
GAFFERBINDINGS_API boost::python::object pythonConnection( const boost::signals::connection &connection, bool scoped ); template<typename Signal, typename SlotCaller> boost::python::object connect( Signal &s, boost::python::object &slot, bool scoped ) { return pythonConnection( s.connect( Slot<Signal, SlotCaller>( slot ) ), scoped ); } template<typename Signal, typename SlotCaller> boost::python::object connectInGroup( Signal &s, int group, boost::python::object &slot, bool scoped ) { return pythonConnection( s.connect( group, Slot<Signal, SlotCaller>( slot ) ), scoped ); } } template<typename Signal> struct DefaultSignalCaller; template<typename Result, typename... Args, typename Combiner> struct DefaultSignalCaller<boost::signal<Result( Args... ), Combiner>> { using Signal = boost::signal<Result( Args... ), Combiner>; static Result call( Signal &s, Args... args ) { IECorePython::ScopedGILRelease gilRelease; return s( args... ); } }; template<typename Signal> struct DefaultSlotCaller; template<typename Result, typename... Args, typename Combiner> struct DefaultSlotCaller<boost::signal<Result( Args... ), Combiner>> { using Signal = boost::signal<Result ( Args... )>; typename Signal::slot_result_type operator()( boost::python::object slot, Args&&... args ) { return boost::python::extract<typename Signal::slot_result_type>( slot( std::forward<Args>( args )... ) )(); } }; template<typename Signal, typename SignalCaller, typename SlotCaller> SignalClass<Signal, SignalCaller, SlotCaller>::SignalClass( const char *className, const char *docString ) : boost::python::class_<Signal, boost::noncopyable>( className, docString ) { this->def( "connect", &Detail::connect<Signal, SlotCaller>, ( boost::python::arg( "slot" ), boost::python::arg( "scoped" ) = true ) ); this->def( "connect", &Detail::connectInGroup<Signal, SlotCaller>, ( boost::python::arg( "group" ), boost::python::arg( "slot" ), boost::python::arg( "scoped" ) = true ) ); this->def( "num_slots", &Signal::num_slots ); this->def( "empty", &Signal::empty ); this->def( "__call__", &SignalCaller::call ); } } #endif
t(), weakMethod.ptr() ) ) { boost::python::object self = boost::python::object( slot.m_slot ).attr( "instance" )(); boost::python::extract<Trackable &> e( self ); if( e.check() ) { boost::visit_each( visitor, e(), 0 ); } } }
function_block-function_prefixed
[]
C++
Sandbox2D/src/2dapp.cpp
dovker/Rosewood
5131a061632732222ce68e5da5a257b8bda36ea5
#include "Rosewood.h" #include "Rosewood/Core/EntryPoint.h" #include "imgui.h" #include "Sofa.h" #include "2DCameraController.h" const std::string Rosewood::FileSystem::ProjectRoot = "../../../Sandbox2D/"; class ExampleLayer : public Rosewood::Layer { public: unsigned int scrWidth = Rosewood::Application::Get().GetWindow().GetWidth(); unsigned int scrHeight = Rosewood::Application::Get().GetWindow().GetHeight(); float lastX = scrWidth / 2.0f; float lastY = scrHeight / 2.0f; Rosewood::Ref<Rosewood::Texture> texture; Rosewood::Ref<Rosewood::Texture> fontTexture; Sofa sofa; Rosewood::Ref<Rosewood::SpriteFont> font; Rosewood::Ref<Rosewood::VertexArray> m_VertexArray; Rosewood::Ref<Rosewood::Framebuffer> m_Framebuffer; Rosewood::Ref<Rosewood::Sound> sound; Rosewood::Ref<Rosewood::RenderMesh> mesh; Rosewood::Ref<Rosewood::RenderMesh> flatMesh; Rosewood::Ref<Rosewood::RenderMesh> planeMesh; Rosewood::Ref<Rosewood::DecalLight> decal; CameraControl camera = CameraControl(glm::vec2( (float)scrWidth, (float)scrHeight)); bool open = true; std::string text = "Help my pp is very hard because this works! :))) XDD ; \nHello love! This should be in a new line! \nHippopotamus!12 Hippopotamus! Hippopotamus!"; float scroll = 0.0f; float intensity = 1.0f; float intensityDecal = 1.0f; float gamma = 2.2f; float exposure = 1.0f; glm::vec3 color = glm::vec3(1.0f); glm::vec3 colorDecal = glm::vec3(1.0f); glm::vec3 bcs = glm::vec3(0.0f, 1.0f, 1.0f); glm::vec2 bwpoint = glm::vec2(0.0f, 1.0f); float linear = 0.014; float quadratic = 0.0007; glm::vec3 direction = {0.0f, 0.0f, -1.0f}; glm::vec3 ambient = glm::vec3(0.1f); float mouseX = 0.0f; float mouseY = 0.0f; ExampleLayer() : Layer("Example") { Rosewood::Ref<Rosewood::Texture> albedo = Rosewood::AssetManager::Load<Rosewood::Texture>("TestBox.png", "Deferred_Albedo"); Rosewood::Ref<Rosewood::Texture> normal = Rosewood::AssetManager::Load<Rosewood::Texture>("Deferred_Normal.png", "Deferred_Normal"); Rosewood::Ref<Rosewood::Texture> spec = Rosewood::AssetManager::Load<Rosewood::Texture>("Deferred_Specular.png", "Deferred_Specular"); Rosewood::Ref<Rosewood::Texture> lightTex = Rosewood::AssetManager::Load<Rosewood::Texture>("awesomeface.png", "DecalLight"); sofa.Load(); texture = lightTex; Rosewood::AssetManager::Load<Rosewood::Sound>("sound.mp3", "Sound"); Rosewood::AssetManager::Load<Rosewood::Texture>("Chroma.png", "Sprite_Font"); mesh = Rosewood::RenderMesh::CreateFoldedQuad(std::vector<Rosewood::Ref<Rosewood::Texture>>{albedo, normal, spec}, 0.5f); flatMesh = Rosewood::RenderMesh::CreateFlatQuad(std::vector<Rosewood::Ref<Rosewood::Texture>>{albedo, normal, spec}); planeMesh= Rosewood::RenderMesh::CreatePerpendicularQuad(std::vector<Rosewood::Ref<Rosewood::Texture>>{albedo, normal, spec}); sound = Rosewood::AssetManager::Get<Rosewood::Sound>("Sound"); fontTexture = Rosewood::AssetManager::Get<Rosewood::Texture>("Sprite_Font"); decal = Rosewood::DecalLight::Create(texture, {mouseX, mouseY, 0.0f}, direction, color * intensityDecal, {texture->GetWidth(), texture->GetHeight()}); font = Rosewood::SpriteFont::Create(fontTexture, "!\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ", 9, 9); Rosewood::DeferredRenderer::Init(); } void OnUpdate(Rosewood::Timestep timestep) override { camera.ProcessKeyboard(timestep.GetSeconds()); { Rosewood::GraphicsCommand::SetClearColor(glm::vec4(0.1f, 0.12f, 0.1f, 1.0f)); Rosewood::GraphicsCommand::Clear(); } Rosewood::DeferredRenderer::SetAmbient(ambient); Rosewood::DeferredRenderer::SetGamma(gamma); Rosewood::DeferredRenderer::SetExposure(exposure); Rosewood::DeferredRenderer::SetBCS(bcs); Rosewood::DeferredRenderer::SetBWPoint(bwpoint); Rosewood::DeferredRenderer::Begin(camera.GetCamera()); sofa.Draw(glm::vec3(0.0f, 0.0f, 0.0f)); mouseX = Rosewood::Input::GetMouseX() + camera.GetCamera().GetPosition().x; mouseY = Rosewood::Input::GetMouseY() + camera.GetCamera().GetPosition().y; decal->SetPosRot(glm::vec3(mouseX, mouseY, scroll), direction); decal->color = colorDecal * intensityDecal; Rosewood::DeferredRenderer::SubmitDecalLight(decal); Rosewood::DeferredRenderer::BeginLights(); Rosewood::DeferredRenderer::DrawPointLight(glm::vec3(mouseX, mouseY, scroll), color, intensity, 1.0, linear, quadratic); Rosewood::DeferredRenderer::DrawDecals(); Rosewood::DeferredRenderer::End(); } float col[3] {1.0f, 1.0f, 1.0f}; float colDec[3] {1.0f, 1.0f, 1.0f}; float ambCol[3] {0.1f, 0.1f, 0.1f}; float dir[3] {0.0f, 0.0f, -1.0f}; void OnImGuiRender() override { auto stats = Rosewood::BatchRenderer::GetStats(); ImGui::Begin("This is 2D Spritebatch System", &open, 0); ImGui::Text("Camera Pos: %f, %f, %f", camera.GetCamera().GetPosition().x, camera.GetCamera().GetPosition().y, camera.GetCamera().GetPosition().z); ImGui::Text("Batch stats: %i, %i", stats.DrawCount, stats.QuadCount); ImGui::Text("Scroll: %f", scroll); ImGui::Separator(); ImGui::SliderFloat3("Direction", dir, -1.0f, 1.0f); direction = glm::normalize(glm::vec3(dir[0], dir[1], dir[2])); ImGui::SliderFloat("Exposure", &exposure, 0.0f, 10.0f); ImGui::SliderFloat("Gamma", &gamma, 0.0f, 10.0f); ImGui::SliderFloat("Brightness", &bcs.x, -1.0f, 1.0f); ImGui::SliderFloat("Contrast", &bcs.y, 0.0f, 10.0f); ImGui::SliderFloat("Saturation", &bcs.z, 0.0f, 10.0f); ImGui::SliderFloat("Black Point", &bwpoint.x, 0.0f, 1.0f); ImGui::SliderFloat("White Point", &bwpoint.y, -1.0f, 1.0f); if(ImGui::Button("RECOMPILE RENDERER SHADERS")) Rosewood::DeferredRenderer::ReloadShaders(); ImGui::Separator(); ImGui::ColorPicker3("Decal Color", colDec); colorDecal = {colDec[0], colDec[1], colDec [2]}; ImGui::InputFloat("Decal Intensity", &intensityDecal); ImGui::ColorPicker3("Light Color", col); color = {col[0], col[1], col [2]}; ImGui::ColorPicker3("Ambient Color", ambCol); ambient = {ambCol[0], ambCol[1], ambCol[2]}; ImGui::InputFloat("Linear", &linear, 0.1f, 0.0f, "%.19f"); ImGui::InputFloat("Quadratic", &quadratic, 0.1f, 0.0f, "%.19f"); ImGui::InputFloat("Intensity", &intensity); ImGui::Separator(); int w = scrWidth; int h = scrHeight; ImGui::InputInt("px", &w); ImGui::InputInt("px", &h); ImGui::Image((void*)Rosewood::DeferredRenderer::GetAlbedoID(), {576, 324}); ImGui::Image((void*)Rosewood::DeferredRenderer::GetPosID(), {576, 324}); ImGui::Image((void*)Rosewood::DeferredRenderer::GetNormalID(), {576, 324}); ImGui::Image((void*)Rosewood::DeferredRenderer::GetLightID(), {576, 324}); ImGui::Image((void*)Rosewood::DeferredRenderer::GetDepthID(), {576, 324}); ImGui::Image((void*)decal->depth->GetDepthAttachmentRendererID(), {576, 324}); ImGui::End(); } void OnEvent(Rosewood::Event& event) override { Rosewood::EventDispatcher dispatcher(event); dispatcher.Dispatch<Rosewood::MouseButtonPressedEvent>(RW_BIND_EVENT_FN(ExampleLayer::OnMouseButtonPressedEvent)); dispatcher.Dispatch<Rosewood::MouseButtonReleasedEvent>(RW_BIND_EVENT_FN(ExampleLayer::OnMouseButtonReleasedEvent)); dispatcher.Dispatch<Rosewood::MouseMovedEvent>(RW_BIND_EVENT_FN(ExampleLayer::OnMouseMovedEvent)); dispatcher.Dispatch<Rosewood::MouseScrolledEvent>(RW_BIND_EVENT_FN(ExampleLayer::OnMouseScrolledEvent)); dispatcher.Dispatch<Rosewood::KeyPressedEvent>(RW_BIND_EVENT_FN(ExampleLayer::OnKeyPressedEvent)); dispatcher.Dispatch<Rosewood::KeyReleasedEvent>(RW_BIND_EVENT_FN(ExampleLayer::OnKeyReleasedEvent)); dispatcher.Dispatch<Rosewood::WindowResizeEvent>(RW_BIND_EVENT_FN(ExampleLayer::OnWindowResizeEvent)); } bool OnMouseButtonPressedEvent(Rosewood::MouseButtonPressedEvent& e) { if(e.GetMouseButton() == MOUSE_BUTTON_LEFT) { float mouseX = Rosewood::Input::GetMouseX() + camera.GetCamera().GetPosition().x; float mouseY = Rosewood::Input::GetMouseY() + camera.GetCamera().GetPosition().y; } return false; } bool OnMouseButtonReleasedEvent(Rosewood::MouseButtonReleasedEvent& e) { return false; } bool firstMouse = true; bool OnMouseMovedEvent(Rosewood::MouseMovedEvent& e) { return false; } bool OnMouseScrolledEvent(Rosewood::MouseScrolledEvent& e) { scroll += e.GetYOffset(); return false; } bool OnKeyPressedEvent(Rosewood::KeyPressedEvent& e) { int key = e.GetKeyCode(); if (key == KEY_R) Rosewood::Application::Get().GetWindow().LockCursor(); else if (key == KEY_T) Rosewood::Application::Get().GetWindow().UnlockCursor(); else if (key == KEY_F) sound->Play(); return false; } bool OnKeyReleasedEvent(Rosewood::KeyReleasedEvent& e) { return false; } bool OnWindowResizeEvent(Rosewood::WindowResizeEvent& e) { scrWidth = e.GetWidth(); scrHeight = e.GetHeight(); camera.ProcessScreenResize(glm::vec2(scrWidth, scrHeight)); Rosewood::GraphicsCommand::SetViewport(0, 0, scrWidth, scrHeight); return false; } }; class Sandbox : public Rosewood::Application { public: Sandbox() { PushLayer(new ExampleLayer()); } ~Sandbox() { Rosewood::BatchRenderer::Shutdown(); } }; Rosewood::Application* Rosewood::CreateApplication() { return new Sandbox(); }
#include "Rosewood.h" #include "Rosewood/Core/EntryPoint.h" #include "imgui.h" #include "Sofa.h" #include "2DCameraController.h" const std::string Rosewood::FileSystem::ProjectRoot = "../../../Sandbox2D/"; class ExampleLayer : public Rosewood::Layer { public: unsigned int scrWidth = Rosewood::Application::Get().GetWindow().GetWidth(); unsigned int scrHeight = Rosewood::Application::Get().GetWindow().GetHeight(); float lastX = scrWidth / 2.0f; float lastY = scrHeight / 2.0f; Rosewood::Ref<Rosewood::Texture> texture; Rosewood::Ref<Rosewood::Texture> fontTexture; Sofa sofa; Rosewood::Ref<Rosewood::SpriteFont> font; Rosewood::Ref<Rosewood::VertexArray> m_VertexArray; Rosewood::Ref<Rosewood::Framebuffer> m_Framebuffer; Rosewood::Ref<Rosewood::Sound> sound; Rosewood::Ref<Rosewood::RenderMesh> mesh; Rosewood::Ref<Rosewood::RenderMesh> flatMesh; Rosewood::Ref<Rosewood::RenderMesh> planeMesh; Rosewood::Ref<Rosewood::DecalLight> decal; CameraControl camera = CameraControl(glm::vec2( (float)scrWidth, (float)scrHeight)); bool open = true; std::string text = "Help my pp is very hard because this works! :))) XDD ; \nHello love! This should be in a new line! \nHippopotamus!12 Hippopotamus! Hippopotamus!"; float scroll = 0.0f; float intensity = 1.0f; float intensityDecal = 1.0f; float gamma = 2.2f; float exposure = 1.0f; glm::vec3 color = glm::vec3(1.0f); glm::vec3 colorDecal = glm::vec3(1.0f); glm::vec3 bcs = glm::vec3(0.0f, 1.0f, 1.0f); glm::vec2 bwpoint = glm::vec2(0.0f, 1.0f); float linear = 0.014; float quadratic = 0.0007; glm::vec3 direction = {0.0f, 0.0f, -1.0f}; glm::vec3 ambient = glm::vec3(0.1f); float mouseX = 0.0f; float mouseY = 0.0f; ExampleLayer() : Layer("Example") { Rosewood::Ref<Rosewood::Texture> albedo = Rosewood::AssetManager::Load<Rosewood::Texture>("TestBox.png", "Deferred_Albedo"); Rosewood::Ref<Rosewood::Texture> normal = Rosewood::AssetManager::Load<Rosewood::Texture>("Deferred_Normal.png", "Deferred_Normal"); Rosewood::Ref<Rosewood::Texture> spec = Rosewood::AssetManager::Load<Rosewood::Texture>("Deferred_Specular.png", "Deferred_Specular"); Rosewood::Ref<Rosewood::Texture> lightTex = Rosewood::AssetManager::Load<Rosewood::Texture>("awesomeface.png", "DecalLight"); sofa.Load(); texture = lightTex; Rosewood::AssetManager::Load<Rosewood::Sound>("sound.mp3", "Sound"); Rosewood::AssetManager::Load<Rosewood::Texture>("Chroma.png", "Sprite_Font"); mesh = Rosewood::RenderMesh::CreateFoldedQuad(std::vector<Rosewood::Ref<Rosewood::Texture>>{albedo, normal, spec}, 0.5f); flatMesh = Rosewood::RenderMesh::CreateFlatQuad(std::vector<Rosewood::Ref<Rosewood::Texture>>{albedo, normal, spec}); planeMesh= Rosewood::RenderMesh::CreatePerpendicularQuad(std::vector<Rosewood::Ref<Rosewood::Texture>>{albedo, normal, spec}); sound = Rosewood::AssetManager::Get<Rosewood::Sound>("Sound"); fontTexture = Rosewood::AssetManager::Get<Rosewood::Texture>("Sprite_Font"); decal = Rosewood::DecalLight::Create(texture, {mouseX, mouseY, 0.0f}, direction, color * intensityDecal, {texture->GetWidth(), texture->GetHeight()}); font = Rosewood::SpriteFont::Create(fontTexture, "!\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ", 9, 9); Rosewood::DeferredRenderer::Init(); } void OnUpdate(Rosewood::Timestep timestep) override { camera.ProcessKeyboard(timestep.GetSeconds()); { Rosewood::GraphicsCommand::SetClearColor(glm::vec4(0.1f, 0.12f, 0.1f, 1.0f)); Rosewood::GraphicsCommand::Clear(); } Rosewood::DeferredRenderer::SetAmbient(ambient); Rosewood::DeferredRenderer::SetGamma(gamma); Rosewood::DeferredRenderer::SetExposure(exposure); Rosewood::DeferredRenderer::SetBCS(bcs); Rosewood::DeferredRenderer::SetBWPoint(bwpoint); Rosewood::DeferredRenderer::Begin(camera.GetCamera()); sofa.Draw(glm::vec3(0.0f, 0.0f, 0.0f)); mouseX = Rosewood::Input::GetMouseX() + camera.GetCamera().GetPosition().x; mouseY = Rosewood::Input::GetMouseY() + camera.GetCamera().GetPosition().y; decal->SetPosRot(glm::vec3(mouseX, mouseY, scroll), direction); decal->color = colorDecal * intensityDecal; Rosewood::DeferredRenderer::SubmitDecalLight(decal); Rosewood::DeferredRenderer::BeginLights(); Rosewood::DeferredRenderer::DrawPointLight(glm::vec3(mouseX, mouseY, scroll), color, intensity, 1.0, linear, quadratic); Rosewood::DeferredRenderer::DrawDecals(); Rosewood::DeferredRenderer::End(); } float col[3] {1.0f, 1.0f, 1.0f}; float colDec[3] {1.0f, 1.0f, 1.0f}; float ambCol[3] {0.1f, 0.1f, 0.1f}; float dir[3] {0.0f, 0.0f, -1.0f}; void OnImGuiRender() override { auto stats = Rosewood::BatchRenderer::GetStats(); ImGui::Begin("This is 2D Spritebatch System", &open, 0); ImGui::Text("Camera Pos: %f, %f, %f", camera.GetCamera().GetPosition().x, camera.GetCamera().GetPosition().y, camera.GetCamera().GetPosition().z); ImGui::Text("Batch stats: %i, %i", stats.DrawCount, stats.QuadCount); ImGui::Text("Scroll: %f", scroll); ImGui::Separator(); ImGui::SliderFloat3("Direction", dir, -1.0f, 1.0f); direction = glm::normalize(glm::vec3(dir[0], dir[1], dir[2])); ImGui::SliderFloat("Exposure", &exposure, 0.0f, 10.0f); ImGui::SliderFloat("Gamma", &gamma, 0.0f, 10.0f); ImGui::SliderFloat("Brightness", &bcs.x, -1.0f, 1.0f); ImGui::SliderFloat("Contrast", &bcs.y, 0.0f, 10.0f); ImGui::SliderFloat("Saturation", &bcs.z, 0.0f, 10.0f); ImGui::SliderFloat("Black Point", &bwpoint.x, 0.0f, 1.0f); ImGui::SliderFloat("White Point", &bwpoint.y, -1.0f, 1.0f); if(ImGui::Button("RECOMPILE RENDERER SHADERS")) Rosewood::DeferredRenderer::ReloadShaders(); ImGui::Separator(); ImGui::ColorPicker3("Decal Color", colDec); colorDecal = {colDec[0], colDec[1], colDec [2]}; ImGui::InputFloat("Decal Intensity", &intensityDecal); ImGui::ColorPicker3("Light Color", col); color = {col[0], col[1], col [2]}; ImGui::ColorPicker3("Ambient Color", ambCol); ambient = {ambCol[0], ambCol[1], ambCol[2]}; ImGui::InputFloat("Linear", &linear, 0.1f, 0.0f, "%.19f"); ImGui::InputFloat("Quadratic", &quadratic, 0.1f, 0.0f, "%.19f"); ImGui::InputFloat("Intensity", &intensity); ImGui::Separator(); int w = scrWidth; int h = scrHeight; ImGui::InputInt("px", &w); ImGui::InputInt("px", &h); ImGui::Image((void*)Rosewood::DeferredRenderer::GetAlbedoID(), {576, 324}); ImGui::Image((void*)Rosewood::DeferredRenderer::GetPosID(), {576, 324}); ImGui::Image((void*)Rosewood::DeferredRenderer::GetNormalID(), {576, 324}); ImGui::Image((void*)Rosewood::DeferredRenderer::GetLightID(), {576, 324}); ImGui::Image((void*)Rosewood::DeferredRenderer::GetDepthID(), {576, 324}); ImGui::Image((void*)decal->depth->GetDepthAttachmentRendererID(), {576, 324}); ImGui::End(); } void OnEvent(Rosewood::Event& event) override { Rosewood::EventDispatcher dispatcher(event); dispatcher.Dispatch<Rosewood::MouseButtonPressedEvent>(RW_BIND_EVENT_FN(ExampleLayer::OnMouseButtonPressedEvent)); dispatcher.Dispatch<Rosewood::MouseButtonReleasedEvent>(RW_BIND_EVENT_FN(ExampleLayer::OnMouseButtonReleasedEvent)); dispatcher.Dispatch<Rosewood::MouseMovedEvent>(RW_BIND_EVENT_FN(ExampleLayer::OnMouseMovedEvent)); dispatcher.Dispatch<Rosewood::MouseScrolledEvent>(RW_BIND_EVENT_FN(ExampleLayer::OnMouseScrolledEvent)); dispatcher.Dispatch<Rosewood::KeyPressedEvent>(RW_BIND_EVENT_FN(ExampleLayer::OnKeyPressedEvent)); dispatcher.Dispatch<Rosewood::KeyReleasedEvent>(RW_BIND_EVENT_FN(ExampleLayer::OnKeyReleasedEvent)); dispatcher.Dispatch<Rosewood::WindowResizeEvent>(RW_BIND_EVENT_FN(ExampleLayer::OnWindowResizeEvent)); } bool OnMouseButtonPressedEvent(Rosewood::MouseButtonPressedEvent& e) { if(e.GetMouseButton() == MOUSE_BUTTON_LEFT) { float mouseX = Rosewood::Input::GetMouseX() + camera.GetCamera().GetPosition().x; float mouseY = Rosewood::Input::GetMouseY() + camera.GetCamera().GetPosition().y; } return false; } bool OnMouseButtonReleasedEvent(Rosewood::MouseButtonReleasedEvent& e) { return false; } bool firstMouse = true; bool OnMouseMovedEvent(Rosewood::MouseMovedEvent& e) { return false; } bool OnMouseScrolledEvent(Rosewood::MouseScrolledEvent& e) { scroll += e.GetYOffset(); return false; } bool OnKeyPressedEvent(Rosewood::KeyPressedEvent& e) { int key = e.GetKeyCode(); if (key == KEY_R) Rosewood::Applicatio
bool OnKeyReleasedEvent(Rosewood::KeyReleasedEvent& e) { return false; } bool OnWindowResizeEvent(Rosewood::WindowResizeEvent& e) { scrWidth = e.GetWidth(); scrHeight = e.GetHeight(); camera.ProcessScreenResize(glm::vec2(scrWidth, scrHeight)); Rosewood::GraphicsCommand::SetViewport(0, 0, scrWidth, scrHeight); return false; } }; class Sandbox : public Rosewood::Application { public: Sandbox() { PushLayer(new ExampleLayer()); } ~Sandbox() { Rosewood::BatchRenderer::Shutdown(); } }; Rosewood::Application* Rosewood::CreateApplication() { return new Sandbox(); }
n::Get().GetWindow().LockCursor(); else if (key == KEY_T) Rosewood::Application::Get().GetWindow().UnlockCursor(); else if (key == KEY_F) sound->Play(); return false; }
function_block-function_prefixed
[ { "content": "\tclass KeyEvent : public Event\n\n\t{\n\n\tpublic:\n\n\t\tinline int GetKeyCode() const { return m_KeyCode; }\n\n\n\n\t\tEVENT_CLASS_CATEGORY(EventCategoryKeyboard | EventCategoryInput)\n\n\tprotected:\n\n\t\tKeyEvent(int keycode)\n\n\t\t\t: m_KeyCode(keycode) {}\n\n\n\n\t\tint m_KeyCode;\n\n\t};\n\n\n", "file_path": "Rosewood/src/Rosewood/Events/KeyEvent.h", "rank": 0, "score": 397628.5598887423 }, { "content": " class OpenGLShader : public Shader\n\n {\n\n public:\n\n OpenGLShader(const std::string& filepath);\n\n OpenGLShader(const BinaryFile& file);\n\n OpenGLShader(const TextFile& file);\n\n\n\n virtual ~OpenGLShader() {}\n\n \n\n virtual void Bind() override;\n\n virtual void Unbind() override;\n\n\n\n virtual const std::string& GetPath() override { return m_Path; }\n\n\n\n \n\n virtual void setBool(const std::string& name, bool value) override;\n\n virtual void setInt(const std::string& name, int value) override;\n\n virtual void setIntPtr(const std::string& name, int count, int* value) override;\n\n virtual void setFloat(const std::string& name, float value) override;\n\n virtual void setMat4(const std::string& name, const glm::mat4& mat) override;\n", "file_path": "Rosewood/src/Platform/OpenGL/OpenGLShader.h", "rank": 1, "score": 393242.8152327944 }, { "content": "\tclass MouseScrolledEvent : public Event\n\n\t{\n\n\tpublic:\n\n\t\tMouseScrolledEvent(float xOffset, float yOffset)\n\n\t\t\t: m_XOffset(xOffset), m_YOffset(yOffset) {}\n\n\n\n\t\tinline float GetXOffset() const { return m_XOffset; }\n\n\t\tinline float GetYOffset() const { return m_YOffset; }\n\n\n\n\t\tstd::string ToString() const override\n\n\t\t{\n\n\t\t\tstd::stringstream ss;\n\n\t\t\tss << \"MouseScrolledEvent: \" << GetXOffset() << \", \" << GetYOffset();\n\n\t\t\treturn ss.str();\n\n\t\t}\n\n\n\n\t\tEVENT_CLASS_TYPE(MouseScrolled)\n\n\t\t\tEVENT_CLASS_CATEGORY(EventCategoryMouse | EventCategoryInput)\n\n\tprivate:\n\n\t\tfloat m_XOffset, m_YOffset;\n\n\t};\n\n\n", "file_path": "Rosewood/src/Rosewood/Events/MouseEvent.h", "rank": 2, "score": 382762.62831008557 }, { "content": "\tclass AppRenderEvent : public Event\n\n\t{\n\n\tpublic:\n\n\t\tAppRenderEvent() = default;\n\n\n\n\t\tEVENT_CLASS_TYPE(AppRender)\n\n\t\t\tEVENT_CLASS_CATEGORY(EventCategoryApplication)\n\n\t};\n\n}\n", "file_path": "Rosewood/src/Rosewood/Events/ApplicationEvent.h", "rank": 3, "score": 382724.7738024632 }, { "content": "\tclass KeyReleasedEvent : public KeyEvent\n\n\t{\n\n\tpublic:\n\n\t\tKeyReleasedEvent(int keycode)\n\n\t\t\t: KeyEvent(keycode) {}\n\n\n\n\t\tstd::string ToString() const override\n\n\t\t{\n\n\t\t\tstd::stringstream ss;\n\n\t\t\tss << \"KeyReleasedEvent: \" << (int)m_KeyCode;\n\n\t\t\treturn ss.str();\n\n\t\t}\n\n\n\n\t\tEVENT_CLASS_TYPE(KeyReleased)\n\n\t};\n\n\n", "file_path": "Rosewood/src/Rosewood/Events/KeyEvent.h", "rank": 4, "score": 359558.47365485656 }, { "content": "\tclass KeyTypedEvent : public KeyEvent\n\n\t{\n\n\tpublic:\n\n\t\tKeyTypedEvent(int keycode)\n\n\t\t\t: KeyEvent(keycode) {}\n\n\n\n\t\tstd::string ToString() const override\n\n\t\t{\n\n\t\t\tstd::stringstream ss;\n\n\t\t\tss << \"KeyTypedEvent: \" << (int)m_KeyCode;\n\n\t\t\treturn ss.str();\n\n\t\t}\n\n\n\n\t\tEVENT_CLASS_TYPE(KeyTyped)\n\n\t};\n\n}", "file_path": "Rosewood/src/Rosewood/Events/KeyEvent.h", "rank": 5, "score": 359558.47365485656 }, { "content": "\tclass KeyPressedEvent : public KeyEvent\n\n\t{\n\n\tpublic:\n\n\t\tKeyPressedEvent(int keycode, int repeatCount)\n\n\t\t\t: KeyEvent(keycode), m_RepeatCount(repeatCount) {}\n\n\n\n\t\tinline int GetRepeatCount() const { return m_RepeatCount; }\n\n\n\n\t\tstd::string ToString() const override\n\n\t\t{\n\n\t\t\tstd::stringstream ss;\n\n\t\t\tss << \"KeyPressedEvent: \" << (int)m_KeyCode << \" (\" << m_RepeatCount << \" repeats)\";\n\n\t\t\treturn ss.str();\n\n\t\t}\n\n\n\n\t\tEVENT_CLASS_TYPE(KeyPressed)\n\n\tprivate:\n\n\t\tint m_RepeatCount;\n\n\t};\n\n\n", "file_path": "Rosewood/src/Rosewood/Events/KeyEvent.h", "rank": 6, "score": 359558.47365485656 }, { "content": " class OpenGLTexture : public Texture\n\n {\n\n public:\n\n // the program ID\n\n OpenGLTexture(const std::string& path);\n\n OpenGLTexture(const BinaryFile& file);\n\n OpenGLTexture(uint32_t width, uint32_t height);\n\n \n\n ~OpenGLTexture();\n\n\n\n virtual uint32_t GetWidth() const override { return m_Width; }\n\n virtual uint32_t GetHeight() const override { return m_Height; }\n\n virtual uint32_t GetID() const override { return m_ID; }\n\n virtual std::string& GetPath() override { return m_Path; }\n\n\n\n virtual void SetData(void* data, uint32_t size) override;\n\n \n\n virtual bool operator==(const Texture& other) const override\n\n {\n\n return m_ID == ((OpenGLTexture&)other).m_ID;\n", "file_path": "Rosewood/src/Platform/OpenGL/OpenGLTexture.h", "rank": 7, "score": 354282.06616003613 }, { "content": "\tclass GamepadEvent : public Event\n\n\t{\n\n\tpublic:\n\n\t\tinline int GetGamepadButton() const { return m_Button; }\n\n\n\n\t\tEVENT_CLASS_CATEGORY(EventCategoryGamepad | EventCategoryGamepadButton | EventCategoryInput)\n\n\tprotected:\n\n\t\tGamepadEvent(int button)\n\n\t\t\t: m_Button(button) {}\n\n\n\n\t\tint m_Button;\n\n\t};\n\n\n", "file_path": "Rosewood/src/Rosewood/Events/GamepadEvent.h", "rank": 8, "score": 323338.6621608739 }, { "content": "\tclass WindowResizeEvent : public Event\n\n\t{\n\n\tpublic:\n\n\t\tWindowResizeEvent(unsigned int width, unsigned int height)\n\n\t\t\t: m_Width(width), m_Height(height) {}\n\n\n\n\t\tinline unsigned int GetWidth() const { return m_Width; }\n\n\t\tinline unsigned int GetHeight() const { return m_Height; }\n\n\n\n\t\tstd::string ToString() const override\n\n\t\t{\n\n\t\t\tstd::stringstream ss;\n\n\t\t\tss << \"WindowResizeEvent: \" << m_Width << \", \" << m_Height;\n\n\t\t\treturn ss.str();\n\n\t\t}\n\n\n\n\t\tEVENT_CLASS_TYPE(WindowResize)\n\n\t\t\tEVENT_CLASS_CATEGORY(EventCategoryApplication)\n\n\tprivate:\n\n\t\tunsigned int m_Width, m_Height;\n\n\t};\n\n\n", "file_path": "Rosewood/src/Rosewood/Events/ApplicationEvent.h", "rank": 9, "score": 321514.8879710015 }, { "content": "\tclass MouseMovedEvent : public Event\n\n\t{\n\n\tpublic:\n\n\t\tMouseMovedEvent(float x, float y)\n\n\t\t\t: m_MouseX(x), m_MouseY(y) {}\n\n\n\n\t\tinline float GetX() const { return m_MouseX; }\n\n\t\tinline float GetY() const { return m_MouseY; }\n\n\n\n\t\tstd::string ToString() const override\n\n\t\t{\n\n\t\t\tstd::stringstream ss;\n\n\t\t\tss << \"MouseMovedEvent: \" << m_MouseX << \", \" << m_MouseY;\n\n\t\t\treturn ss.str();\n\n\t\t}\n\n\n\n\t\tEVENT_CLASS_TYPE(MouseMoved)\n\n\t\t\tEVENT_CLASS_CATEGORY(EventCategoryMouse | EventCategoryInput)\n\n\tprivate:\n\n\t\tfloat m_MouseX, m_MouseY;\n\n\t};\n\n\n", "file_path": "Rosewood/src/Rosewood/Events/MouseEvent.h", "rank": 10, "score": 321514.8879710015 }, { "content": "\tclass AppTickEvent : public Event\n\n\t{\n\n\tpublic:\n\n\t\tAppTickEvent() = default;\n\n\n\n\t\tEVENT_CLASS_TYPE(AppTick)\n\n\t\t\tEVENT_CLASS_CATEGORY(EventCategoryApplication)\n\n\t};\n\n\n", "file_path": "Rosewood/src/Rosewood/Events/ApplicationEvent.h", "rank": 11, "score": 321514.8879710015 }, { "content": "\tclass WindowCloseEvent : public Event\n\n\t{\n\n\tpublic:\n\n\t\tWindowCloseEvent() = default;\n\n\n\n\t\tEVENT_CLASS_TYPE(WindowClose)\n\n\t\t\tEVENT_CLASS_CATEGORY(EventCategoryApplication)\n\n\t};\n\n\n", "file_path": "Rosewood/src/Rosewood/Events/ApplicationEvent.h", "rank": 12, "score": 321514.8879710015 }, { "content": "\tclass MouseButtonEvent : public Event\n\n\t{\n\n\tpublic:\n\n\t\tinline int GetMouseButton() const { return m_Button; }\n\n\n\n\t\tEVENT_CLASS_CATEGORY(EventCategoryMouse | EventCategoryInput)\n\n\tprotected:\n\n\t\tMouseButtonEvent(int button)\n\n\t\t\t: m_Button(button) {}\n\n\n\n\t\tint m_Button;\n\n\t};\n\n\n", "file_path": "Rosewood/src/Rosewood/Events/MouseEvent.h", "rank": 13, "score": 321514.8879710015 }, { "content": "\tclass AppUpdateEvent : public Event\n\n\t{\n\n\tpublic:\n\n\t\tAppUpdateEvent() = default;\n\n\n\n\t\tEVENT_CLASS_TYPE(AppUpdate)\n\n\t\t\tEVENT_CLASS_CATEGORY(EventCategoryApplication)\n\n\t};\n\n\n", "file_path": "Rosewood/src/Rosewood/Events/ApplicationEvent.h", "rank": 14, "score": 321514.8879710015 }, { "content": " class EditorCamera : public Camera\n\n {\n\n public:\n\n EditorCamera() = default;\n\n EditorCamera(float fov, float aspectRatio, float nearClip, float farClip);\n\n\n\n void OnUpdate(Timestep ts);\n\n void OnEvent(Event& e);\n\n\n\n inline float GetDistance() const { return m_Distance; }\n\n inline void SetDistance(float distance) { m_Distance = distance; }\n\n\n\n inline void SetViewportSize(float width, float height) { m_ViewportWidth = width; m_ViewportHeight = height; UpdateProjection(); }\n\n\n\n const glm::mat4& GetViewMatrix() const { return m_ViewMatrix; }\n\n glm::mat4 GetViewProjection() const { return m_Projection * m_ViewMatrix; }\n\n\n\n glm::vec3 GetUpDirection() const;\n\n glm::vec3 GetRightDirection() const;\n\n glm::vec3 GetForwardDirection() const;\n", "file_path": "Rosewood/src/Rosewood/Graphics/API/Camera.h", "rank": 15, "score": 320379.1621894544 }, { "content": "\tclass SceneCamera : public Camera\n\n\t{\n\n\tpublic:\n", "file_path": "Rosewood/src/Rosewood/ECS/SceneCamera.h", "rank": 16, "score": 320379.1621894544 }, { "content": " class OrthographicCamera : public Camera\n\n {\n\n public:\n\n OrthographicCamera() {}\n\n OrthographicCamera(float left, float right, float bottom, float top);\n\n\n\n void SetProjection(float left, float right, float bottom, float top);\n\n\n\n const glm::vec3& GetPosition() const { return m_Position; }\n\n void SetPosition(const glm::vec3& position) { m_Position = position; RecalculateViewMatrix(); }\n\n void SetZoom(const float& zoom) { m_Zoom = zoom; RecalculateViewMatrix(); }\n\n\n\n float GetRotation() const { return m_Rotation; }\n\n void SetRotation(float rotation) { m_Rotation = rotation; RecalculateViewMatrix(); }\n\n\n\n const glm::mat4& GetProjection() const { return m_Projection; }\n\n const glm::mat4& GetViewMatrix() const { return m_ViewMatrix; }\n\n glm::mat4 GetViewProjection() const { return m_Projection * m_ViewMatrix; }\n\n private:\n\n void RecalculateViewMatrix();\n\n private:\n\n glm::mat4 m_ViewMatrix = glm::mat4(1.0f);\n\n\n\n glm::vec3 m_Position = { 0.0f, 0.0f, 0.0f };\n\n float m_Rotation = 0.0f;\n\n float m_Zoom = 1.0f;\n\n };\n", "file_path": "Rosewood/src/Rosewood/Graphics/API/Camera.h", "rank": 17, "score": 320379.1621894544 }, { "content": "\tclass GamepadAxisMovedEvent : public Event\n\n\t{\n\n\tpublic:\n\n\t\tGamepadAxisMovedEvent(int axis, float value)\n\n\t\t\t: m_Axis(axis), m_AxisValue(value){}\n\n\n\n\t\tinline int GetGamepadAxis() const { return m_Axis; }\n\n\t\tinline float GetValue() const { return m_AxisValue; }\n\n\t\t\n\n\n\n\t\tstd::string ToString() const override\n\n\t\t{\n\n\t\t\tstd::stringstream ss;\n\n\t\t\tss << \"GamepadAxisMovedEvent: \" << (int)m_Axis << \" - \" << m_AxisValue;\n\n\t\t\treturn ss.str();\n\n\t\t}\n\n\n\n\t\tEVENT_CLASS_TYPE(GamepadAxisMoved)\n\n\t\tEVENT_CLASS_CATEGORY(EventCategoryGamepad | EventCategoryGamepadAxis | EventCategoryInput)\n\n\tprivate:\n\n\t\tint m_Axis;\n\n\t\tfloat m_AxisValue;\n\n\t};\n\n}", "file_path": "Rosewood/src/Rosewood/Events/GamepadEvent.h", "rank": 18, "score": 319729.20353478275 }, { "content": "\tclass GamepadReleasedEvent : public GamepadEvent\n\n\t{\n\n\tpublic:\n\n\t\tGamepadReleasedEvent(int button)\n\n\t\t\t: GamepadEvent(button) {}\n\n\n\n\t\tstd::string ToString() const override\n\n\t\t{\n\n\t\t\tstd::stringstream ss;\n\n\t\t\tss << \"GamepadReleasedEvent: \" << (int)m_Button;\n\n\t\t\treturn ss.str();\n\n\t\t}\n\n\n\n\t\tEVENT_CLASS_TYPE(GamepadButtonReleased)\n\n\t};\n\n\n", "file_path": "Rosewood/src/Rosewood/Events/GamepadEvent.h", "rank": 19, "score": 280775.65681041917 }, { "content": "\tclass GamepadPressedEvent : public GamepadEvent\n\n\t{\n\n\tpublic:\n\n\t\tGamepadPressedEvent(int button)\n\n\t\t\t: GamepadEvent(button) {}\n\n\n\n\n\n\t\tstd::string ToString() const override\n\n\t\t{\n\n\t\t\tstd::stringstream ss;\n\n\t\t\tss << \"GamepadPressedEvent: \" << (int)m_Button;\n\n\t\t\treturn ss.str();\n\n\t\t}\n\n\n\n\t\tEVENT_CLASS_TYPE(GamepadButtonPressed)\n\n\t\n\n\t};\n\n\n", "file_path": "Rosewood/src/Rosewood/Events/GamepadEvent.h", "rank": 20, "score": 280775.65681041917 }, { "content": " class OpenGL : public Graphics\n\n {\n\n public:\n\n \n\n virtual void Init() override;\n\n virtual void SetViewport(uint32_t x, uint32_t y, uint32_t width, uint32_t height) override;\n\n virtual void SetClearColor(const glm::vec4& color) override;\n\n virtual void Clear() override;\n\n \n\n virtual void ToggleDepthTest(bool toggle) override;\n\n virtual void ToggleBlending(bool toggle) override;\n\n virtual void ToggleBackfaceCulling(bool toggle) override;\n\n\n\n\n\n virtual void DrawIndexed(const Ref<VertexArray>& vertexArray, uint32_t indexCount = 0) override;\n\n virtual void BindTexture(uint32_t ID, uint32_t slot) override;\n\n //static bool Old;\n\n };\n\n}\n", "file_path": "Rosewood/src/Platform/OpenGL/OpenGL.h", "rank": 21, "score": 279474.9629270333 }, { "content": "\tclass MouseButtonPressedEvent : public MouseButtonEvent\n\n\t{\n\n\tpublic:\n\n\t\tMouseButtonPressedEvent(int button)\n\n\t\t\t: MouseButtonEvent(button) {}\n\n\n\n\t\tstd::string ToString() const override\n\n\t\t{\n\n\t\t\tstd::stringstream ss;\n\n\t\t\tss << \"MouseButtonPressedEvent: \" << (int)m_Button;\n\n\t\t\treturn ss.str();\n\n\t\t}\n\n\n\n\t\tEVENT_CLASS_TYPE(MouseButtonPressed)\n\n\t};\n\n\n", "file_path": "Rosewood/src/Rosewood/Events/MouseEvent.h", "rank": 22, "score": 277313.4980037139 }, { "content": "\tclass MouseButtonReleasedEvent : public MouseButtonEvent\n\n\t{\n\n\tpublic:\n\n\t\tMouseButtonReleasedEvent(int button)\n\n\t\t\t: MouseButtonEvent(button) {}\n\n\n\n\t\tstd::string ToString() const override\n\n\t\t{\n\n\t\t\tstd::stringstream ss;\n\n\t\t\tss << \"MouseButtonReleasedEvent: \" << (int)m_Button;\n\n\t\t\treturn ss.str();\n\n\t\t}\n\n\n\n\t\tEVENT_CLASS_TYPE(MouseButtonReleased)\n\n\t};\n\n\n\n}", "file_path": "Rosewood/src/Rosewood/Events/MouseEvent.h", "rank": 23, "score": 277313.4980037139 }, { "content": " class RenderQuad : public RenderItem2D\n\n {\n\n public:\n\n RenderQuad(glm::vec4 color) : RenderItem2D(color) {}\n\n\n\n virtual void Draw(Transform transform) override\n\n {\n\n BatchRenderer::DrawQuad(transform.GetTransform(), Color);\n\n }\n\n };\n\n\n", "file_path": "Rosewood/src/Rosewood/Graphics/2D/RenderItem2D.h", "rank": 24, "score": 274011.44976659305 }, { "content": " class RenderCircle : public RenderItem2D\n\n {\n\n public:\n\n static uint32_t CircleTextureWidth;\n\n static uint32_t CircleTextureHeight;\n\n static Ref<Texture> CircleTexture;\n\n RenderCircle(glm::vec4 color) : RenderItem2D(color){}\n\n\n\n virtual void Draw(Transform transform) override\n\n {\n\n transform.Scale.x /= CircleTextureWidth;\n\n transform.Scale.y /= CircleTextureHeight;\n\n transform.Position.x -= transform.Scale.x/2;\n\n transform.Position.x -= transform.Scale.x/2;\n\n\n\n BatchRenderer::DrawQuad(transform.GetTransform(), CircleTexture, glm::vec4(0.0f, 0.0f, 1.0f, 1.0f), Color);\n\n }\n\n };\n\n //TODO: ADD LINES\n\n //TODO: ADD POLYGONS \n\n}\n", "file_path": "Rosewood/src/Rosewood/Graphics/2D/RenderItem2D.h", "rank": 25, "score": 274011.44976659305 }, { "content": " class OpenGLContext : public GraphicsContext\n\n {\n\n public:\n\n OpenGLContext(GLFWwindow* windowHandle);\n\n \n\n virtual void Init() override;\n\n static void ForceModern();\n\n virtual void SwapBuffers() override;\n\n private:\n\n GLFWwindow* m_WindowHandle;\n\n };\n\n}\n", "file_path": "Rosewood/src/Platform/OpenGL/OpenGLContext.h", "rank": 26, "score": 273998.3820462758 }, { "content": " class OpenGLFramebuffer : public Framebuffer\n\n {\n\n public:\n\n OpenGLFramebuffer(const FramebufferSpecification& spec);\n\n virtual ~OpenGLFramebuffer();\n\n\n\n virtual void Invalidate();\n\n\n\n virtual void Bind() override;\n\n virtual void Unbind() override;\n\n\n\n virtual void Resize(uint32_t width, uint32_t height) override;\n\n \n\n virtual glm::vec2 GetSize() const override { return {m_Specification.Width, m_Specification.Height}; }\n\n\n\n virtual uint32_t GetColorAttachmentRendererID(uint32_t attachment = 0) const override { return m_ColorAttachments[attachment]; }\n\n \n\n virtual uint32_t GetDepthAttachmentRendererID() const override { return m_DepthAttachment; }\n\n \n\n\n", "file_path": "Rosewood/src/Platform/OpenGL/OpenGLFrameBuffer.h", "rank": 27, "score": 273998.3820462758 }, { "content": " class OpenGLIndexBuffer : public IndexBuffer\n\n {\n\n public:\n\n OpenGLIndexBuffer(uint32_t* indices, uint32_t count);\n\n virtual ~OpenGLIndexBuffer();\n\n \n\n virtual void Bind() const override;\n\n virtual void Unbind() const override;\n\n \n\n virtual uint32_t GetCount() const override { return m_Count; };\n\n \n\n private:\n\n uint32_t m_ID, m_Count;\n\n };\n\n}\n", "file_path": "Rosewood/src/Platform/OpenGL/OpenGLBuffer.h", "rank": 28, "score": 272246.2827901471 }, { "content": " class OpenGLVertexBuffer : public VertexBuffer\n\n {\n\n public:\n\n OpenGLVertexBuffer(float* vertices, uint32_t size);\n\n OpenGLVertexBuffer(Vertex* vertices, uint32_t size);\n\n\n\n OpenGLVertexBuffer(uint32_t size);\n\n \n\n virtual ~OpenGLVertexBuffer();\n\n \n\n virtual void Bind() const override;\n\n virtual void Unbind() const override;\n\n \n\n virtual void SetLayout(const BufferLayout& layout) override { m_Layout = layout; }\n\n virtual const BufferLayout& GetLayout() const override { return m_Layout; };\n\n \n\n virtual void SetData(const void* data, uint32_t size) override;\n\n \n\n private:\n\n uint32_t m_ID;\n\n BufferLayout m_Layout;\n\n };\n", "file_path": "Rosewood/src/Platform/OpenGL/OpenGLBuffer.h", "rank": 29, "score": 272246.2827901471 }, { "content": " class OpenGLVertexArray : public VertexArray\n\n {\n\n public:\n\n OpenGLVertexArray();\n\n virtual ~OpenGLVertexArray();\n\n\n\n virtual void Bind() const override;\n\n virtual void Unbind() const override;\n\n\n\n virtual void AddVertexBuffer(const Ref<VertexBuffer>& vertexBuffer) override;\n\n virtual void SetIndexBuffer(const Ref<IndexBuffer>& indexBuffer) override;\n\n\n\n virtual const std::vector<Ref<VertexBuffer>>& GetVertexBuffers() const override { return m_VertexBuffers; }\n\n virtual const Ref<IndexBuffer>& GetIndexBuffer() const override { return m_IndexBuffer; }\n\n private:\n\n uint32_t m_ID;\n\n std::vector<Ref<VertexBuffer>> m_VertexBuffers;\n\n Ref<IndexBuffer> m_IndexBuffer;\n\n\n\n };\n\n}\n\n\n", "file_path": "Rosewood/src/Platform/OpenGL/OpenGLVertexArray.h", "rank": 30, "score": 270528.9445894761 }, { "content": " class Sprite : public RenderItem2D\n\n {\n\n public:\n\n Ref<Texture> SpriteTexture;\n\n Rect SourceRect;\n\n \n\n Animation2D Animation;\n\n Offset2D Offset;\n\n \n\n Rect GetBounds(const Transform& transform)\n\n {\n\n glm::vec2 scale = {transform.Scale.x, transform.Scale.y};\n\n return Rect(glm::vec2(transform.Position.x, transform.Position.y) + (SourceRect.RelativeWidth() * scale) * Offset.Pivot,\n\n SourceRect.RelativeWidth() * scale);//TODO: FIXXXXXX\n\n }\n\n \n\n Sprite()\n\n : SpriteTexture(nullptr), RenderItem2D(glm::vec4(1.0f), false) {}\n\n\n\n Sprite(Ref<Rosewood::Texture> texture, glm::vec4 color = glm::vec4(1.0f), bool transparent = false)\n", "file_path": "Rosewood/src/Rosewood/Graphics/2D/Sprite.h", "rank": 31, "score": 261426.39026873527 }, { "content": " class DecalCamera\n\n {\n\n public:\n\n DecalCamera() {}\n\n DecalCamera(float left, float right, float bottom, float top);\n\n\n\n void SetProjection(float left, float right, float bottom, float top);\n\n\n\n const glm::vec3& GetPosition() const { return m_Position; }\n\n void SetPosition(const glm::vec3& position) { m_Position = position; RecalculateViewMatrix(); }\n\n\n\n const glm::vec3& GetLookat() const { return m_Lookat; }\n\n void SetLookat(glm::vec3 lookat) { m_Lookat = lookat; RecalculateViewMatrix(); }\n\n\n\n const glm::mat4& GetProjectionMatrix() const { return m_ProjectionMatrix; }\n\n const glm::mat4& GetViewMatrix() const { return m_ViewMatrix; }\n\n const glm::mat4& GetViewProjectionMatrix() const { return m_ViewProjectionMatrix; }\n\n //const glm::mat4& GetProjectionViewMatrix() const { return m_ProjectionViewMatrix; }\n\n private:\n\n void RecalculateViewMatrix();\n", "file_path": "Rosewood/src/Rosewood/Graphics/API/Camera.h", "rank": 32, "score": 252771.9220861547 }, { "content": " class RenderMesh {\n\n public:\n\n // mesh Data\n\n std::vector<float> vertices;\n\n std::vector<uint32_t> indices;\n\n std::vector<Ref<Texture>> textures;\n\n Ref<VertexArray> VA;\n\n // constructor\n\n RenderMesh() {}\n\n RenderMesh(std::vector<float>& vertices, std::vector<uint32_t>& indices, std::vector<Ref<Texture>>& textures)\n\n {\n\n this->vertices = vertices;\n\n this->indices = indices;\n\n this->textures = textures;\n\n \n\n VA = VertexArray::Create();\n\n \n\n Ref<VertexBuffer> VB = VertexBuffer::Create(vertices.data(), sizeof(float)*vertices.size());\n\n \n\n BufferLayout layout = {\n", "file_path": "Rosewood/src/Rosewood/Graphics/2D/Mesh.h", "rank": 33, "score": 252740.43571660577 }, { "content": "\t\tenum class ShaderType\n\n\t\t{\n\n\t\t\tNONE = -1, VERTEX = 0, FRAGMENT = 1\n\n\t\t};\n\n\t\tstd::string line;\n\n\t\tstd::stringstream ss[2];\n\n\t\tShaderType type = ShaderType::NONE;\n\n\t\ttry\n\n\t\t{\n\n\t\t\twhile (getline(stream, line))\n\n\t\t\t{\n\n\t\t\t\tif (line.find(\"#shader\") != std::string::npos)\n\n\t\t\t\t{\n\n\t\t\t\t\tif (line.find(\"vertex\") != std::string::npos)\n\n\t\t\t\t\t\ttype = ShaderType::VERTEX;\n\n\t\t\t\t\telse if (line.find(\"fragment\") != std::string::npos)\n\n\t\t\t\t\t\ttype = ShaderType::FRAGMENT;\n\n\n\n\t\t\t\t}\n\n\t\t\t\telse\n", "file_path": "Rosewood/src/Platform/OpenGL/OpenGLShader.cpp", "rank": 34, "score": 250916.67485574397 }, { "content": "\tclass Event\n\n\t{\n\n\tpublic:\n\n\t\tbool Handled = false;\n\n\n\n\t\tvirtual EventType GetEventType() const = 0;\n\n\t\tvirtual const char* GetName() const = 0;\n\n\t\tvirtual int GetCategoryFlags() const = 0;\n\n\t\tvirtual std::string ToString() const { return GetName(); }\n\n\t\t//TODO: union Data\n\n\n\n\t\tinline bool IsInCategory(EventCategory category)\n\n\t\t{\n\n\t\t\treturn GetCategoryFlags() & category;\n\n\t\t}\n\n\t};\n\n\n", "file_path": "Rosewood/src/Rosewood/Events/Event.h", "rank": 35, "score": 247110.99266438844 }, { "content": "class Sofa\n\n{\n\n \n\npublic:\n\n Ref<Texture> Top, Arm, Front, Thing, Seat, Back, blank;\n\n Ref<Texture> Top_n, Arm_n, Front_n, Thing_n, Seat_n, Back_n, Blank_n;\n\n Ref<RenderMesh> Top_m, Arm_m, Front_m, Thing_m, Seat_m, Back_m, Blank_m;\n\n float scale = 5.0f;\n\n void Load()\n\n {\n\n Top = Rosewood::AssetManager::Load<Texture>(\"Room/Sofa_Top.png\", \"Top\");\n\n Arm = Rosewood::AssetManager::Load<Texture>(\"Room/Sofa_ArmRest.png\", \"Arm\");\n\n Front = Rosewood::AssetManager::Load<Texture>(\"Room/Sofa_Front.png\", \"Front\");\n\n Thing = Rosewood::AssetManager::Load<Texture>(\"Room/Sofa_Thing.png\", \"Thing\");\n\n Seat = Rosewood::AssetManager::Load<Texture>(\"Room/Sofa_Seat.png\", \"Seat\");\n\n Back = Rosewood::AssetManager::Load<Texture>(\"Room/Sofa_Back.png\", \"Back\");\n\n \n\n Top_n = Rosewood::AssetManager::Load<Texture>(\"Room/Sofa_Normal_Top.png\", \"Top_n\");\n\n Arm_n = Rosewood::AssetManager::Load<Texture>(\"Room/Sofa_Normal_ArmRest.png\", \"Arm_n\");\n\n Front_n = Rosewood::AssetManager::Load<Texture>(\"Room/Sofa_Normal_Front.png\", \"Front_n\");\n", "file_path": "Sandbox2D/src/Sofa.h", "rank": 36, "score": 243777.22395583682 }, { "content": " class Timestep\n\n {\n\n public:\n\n Timestep(float time = 0.0f)\n\n : m_Time(time)\n\n {\n\n }\n\n\n\n operator float() const { return m_Time; }\n\n\n\n float GetSeconds() const { return m_Time; }\n\n float GetMilliseconds() const { return m_Time * 1000.0f; }\n\n private:\n\n float m_Time;\n\n };\n\n}\n", "file_path": "Rosewood/src/Rosewood/Core/Timestep.h", "rank": 37, "score": 242354.17151262454 }, { "content": " class Mesh {\n\n public:\n\n // mesh Data\n\n std::vector<float> vertices;\n\n std::vector<uint32_t> indices;\n\n std::vector<Ref<Texture>> textures;\n\n Ref<VertexArray> VA;\n\n \n\n bool HasTextures() {return textures.size() > 0;}\n\n // constructor\n\n Mesh() {}\n\n Mesh(std::vector<float>& vertices, std::vector<uint32_t>& indices, std::vector<Ref<Texture>> textures)\n\n : vertices(vertices), indices(indices), textures(textures)\n\n {\n\n VA = VertexArray::Create();\n\n \n\n Ref<VertexBuffer> VB = VertexBuffer::Create(vertices.data(), sizeof(float)*vertices.size());\n\n \n\n BufferLayout layout = {\n\n { ShaderDataType::Float3, \"a_Position\" },\n", "file_path": "Rosewood/src/Rosewood/Graphics/3D/Mesh.h", "rank": 38, "score": 240949.74290541298 }, { "content": " class Shader\n\n {\n\n public:\n\n virtual ~Shader() = default;\n\n \n\n virtual void Bind() = 0;\n\n virtual void Unbind() = 0;\n\n \n\n virtual const std::string& GetPath() = 0;\n\n virtual void Recompile() = 0;\n\n virtual void Recompile(const std::string& vs, const std::string& fs) = 0;\n\n\n\n \n\n virtual void setBool(const std::string& name, bool value) = 0;\n\n virtual void setInt(const std::string& name, int value) = 0;\n\n virtual void setIntPtr(const std::string& name, int count, int* value) = 0;\n\n virtual void setFloat(const std::string& name, float value) = 0;\n\n virtual void setMat4(const std::string& name, const glm::mat4& mat) = 0;\n\n virtual void setMat3(const std::string& name, const glm::mat3& mat) = 0;\n\n virtual void setMat2(const std::string& name, const glm::mat2& mat) = 0;\n", "file_path": "Rosewood/src/Rosewood/Graphics/API/Shader.h", "rank": 39, "score": 240944.67636070997 }, { "content": " class Camera\n\n {\n\n public:\n\n Camera() = default;\n\n Camera(const glm::mat4& projection)\n\n : m_Projection(projection) {}\n\n\n\n virtual ~Camera() = default;\n\n\n\n const glm::mat4& GetProjection() const { return m_Projection; }\n\n protected:\n\n glm::mat4 m_Projection = glm::mat4(1.0f);\n\n };\n\n\n", "file_path": "Rosewood/src/Rosewood/Graphics/API/Camera.h", "rank": 40, "score": 240932.6096627493 }, { "content": "class CameraControl\n\n{\n\npublic:\n\n \n\n /*Camera(float aspect_ratio) : m_MovementSpeed(SPEED), m_Zoom(ZOOM), m_AspectRatio(aspect_ratio),\n\n m_Camera(Rosewood::OrthographicCamera(-m_AspectRatio * m_Zoom, m_AspectRatio* m_Zoom, -m_Zoom, m_Zoom))\n\n {\n\n m_Position = camera.GetPosition();\n\n }*/\n\n CameraControl(glm::vec2 scrSize) : m_MovementSpeed(SPEED), m_Zoom(ZOOM), m_ScrSize(scrSize), m_Position(glm::vec3(0.0f, 0.0f, 0.0f)),\n\n m_Camera(Rosewood::OrthographicCamera(0, m_ScrSize.x / m_Zoom, m_ScrSize.y / m_Zoom, 0))\n\n {\n\n \n\n }\n\n\n\n Rosewood::OrthographicCamera &GetCamera()\n\n {\n\n return m_Camera;\n\n }\n\n void ProcessKeyboard(float deltaTime)\n", "file_path": "Sandbox2D/src/2DCameraController.h", "rank": 41, "score": 239569.38156209607 }, { "content": " class Sound\n\n {\n\n public:\n\n ~Sound() {}\n\n Sound();\n\n \n\n Sound(const std::string& path);\n\n Sound(const BinaryFile& file);\n\n const std::string& GetPath() { return m_Path; }\n\n \n\n void Play();\n\n void PlayBackground();\n\n\n\n void Stop();\n\n \n\n double GetLength();\n\n float GetVolume() {return m_Volume;}\n\n \n\n \n\n //TODO: Pitch, 3D, Filters, protect so on.\n", "file_path": "Rosewood/src/Rosewood/Audio/Audio.h", "rank": 42, "score": 230869.10878027987 }, { "content": " class System;\n\n\n", "file_path": "Rosewood/src/Rosewood/ECS/Scene.h", "rank": 43, "score": 230849.19128404243 }, { "content": " class Player : public Entity\n\n {\n\n public:\n\n Player();\n\n virtual void OnLoad() override;\n\n virtual void OnUpdate(float dt, std::vector<Entity*> entities) override;\n\n virtual void OnDraw() override;\n\n virtual void OnUnload() override;\n\n virtual void OnEvent(Rosewood::Event &e) override;\n\n\n\n void SetMap(Map* map) { m_Map = map; }\n\n\n\n private:\n\n Rosewood::Sprite m_SpriteAnim;\n\n Rosewood::Rect m_Collider;\n\n glm::vec2 m_Velocity;\n\n glm::vec2 m_Acceleration;\n\n Map* m_Map;\n\n\n\n void CalculateMovement();\n\n void CalculateCollisions(float dt, std::vector<Entity*> entities);\n\n void ResolveStaticCollisions(float dt, std::vector<std::pair<Rosewood::Rect, float>> rects);\n\n\n\n };\n\n}\n", "file_path": "TestGame/src/Entity/Player.h", "rank": 44, "score": 204796.6309649931 }, { "content": "\tclass WindowsWindow : public Window\n\n\t{\n\n\tpublic:\n\n\t\tWindowsWindow(const WindowProperties& properties);\n\n\t\tvirtual ~WindowsWindow();\n\n\n\n\t\tvoid OnUpdate() override;\n\n\n\n\t\tinline unsigned int GetWidth() const override { return m_Data.Width; }\n\n\t\tinline unsigned int GetHeight() const override { return m_Data.Height; }\n\n\t\tinline float GetTime() override;\n\n\n\n\t\tinline void LockCursor() \toverride;\n\n\t\tinline void UnlockCursor() \toverride;\n\n\t\t//extend to cursor modes\n\n\n\n\n\n\t\t// Window attributes\n\n\t\tinline void SetEventCallback(const EventCallbackFn& callback) override { m_Data.EventCallback = callback; }\n\n\t\tvoid SetVSync(bool enabled) override;\n", "file_path": "Rosewood/src/Platform/Windows/WindowsWindow.h", "rank": 45, "score": 201706.04848598727 }, { "content": "\tclass WindowsInput : public Input\n\n\t{\n\n\tprotected:\n\n\n\n\t\tvirtual bool IsKeyPressedPlatform(int keycode);\n\n\t\tvirtual bool IsMouseButtonPressedPlatform(int button);\n\n\t\tvirtual std::pair<float, float> GetMousePosPlatform();\n\n\t\tvirtual float GetMouseXPlatform();\n\n\t\tvirtual float GetMouseYPlatform();\n\n\n\n\t};\n\n}\n", "file_path": "Rosewood/src/Platform/Windows/WindowsInput.h", "rank": 46, "score": 201706.04848598727 }, { "content": " class wrap_Input : public LuaWrapper\n\n {\n\n private:\n\n static const char* Name;\n\n \n\n public:\n\n static int w_isKeyPressed(lua_State* L);\n\n static int w_isMouseButtonPressed(lua_State* L);\n\n\n\n wrap_Input(lua_State* L);\n\n virtual const char* GetName() const { return Name; }\n\n };\n\n}", "file_path": "Rosewood/src/Rosewood/Scripting/lua/wrappers/wrap_Input.h", "rank": 47, "score": 197342.36446418217 }, { "content": " class wrap_Window : public LuaWrapper\n\n {\n\n private:\n\n\n\n static const char* Name;\n\n public:\n\n static int w_setTitle(lua_State* L);\n\n static int w_getWidth(lua_State* L);\n\n static int w_getHeight(lua_State* L);\n\n\n\n wrap_Window(lua_State* L);\n\n virtual const char* GetName() const { return Name; }\n\n };\n\n}", "file_path": "Rosewood/src/Rosewood/Scripting/lua/wrappers/wrap_Core.h", "rank": 48, "score": 197342.36446418217 }, { "content": "\tclass ImGuiLayer : public Layer\n\n\t{\n\n\tpublic:\n\n\t\tImGuiLayer();\n\n\t\t~ImGuiLayer();\n\n\n\n\t\tvirtual void OnAttach() override;\n\n\t\tvirtual void OnDetach() override;\n\n\t\tvirtual void OnImGuiRender() override;\n\n\t\tvirtual void OnEvent(Event& e) override;\n\n\t\t\n\n\t\tvoid SetEventBlocking(bool blocking) { m_BlockEvents = blocking; }\n\n\n\n\t\tvoid Begin();\n\n\t\tvoid End();\n\n\n\n\n\n\tprivate:\n\n\t\tbool m_BlockEvents = true;\n\n\t};\n\n\n\n}\n", "file_path": "Rosewood/src/Rosewood/ImGui/ImGuiLayer.h", "rank": 49, "score": 197342.36446418217 }, { "content": " class wrap_Log : public LuaWrapper\n\n {\n\n private:\n\n static const char* Name;\n\n \n\n public:\n\n static int w_trace(lua_State* L);\n\n static int w_assert(lua_State* L);\n\n static int w_info(lua_State* L);\n\n static int w_warn(lua_State* L);\n\n static int w_error(lua_State* L);\n\n static int w_critical(lua_State* L);\n\n\n\n wrap_Log(lua_State* L);\n\n virtual const char* GetName() const { return Name; }\n\n };\n\n\n", "file_path": "Rosewood/src/Rosewood/Scripting/lua/wrappers/wrap_Debug.h", "rank": 50, "score": 197342.36446418217 }, { "content": " class wrap_ECS : public LuaWrapper\n\n {\n\n private:\n\n static const char* Name;\n\n \n\n public:\n\n wrap_ECS(lua_State* L);\n\n virtual const char* GetName() const { return Name; }\n\n };\n\n}", "file_path": "Rosewood/src/Rosewood/Scripting/lua/wrappers/wrap_ECS.h", "rank": 51, "score": 197342.36446418217 }, { "content": " class wrap_Math : public LuaWrapper\n\n {\n\n private:\n\n static const char* Name;\n\n \n\n public:\n\n wrap_Math(lua_State* L);\n\n virtual const char* GetName() const { return Name; }\n\n };\n\n}", "file_path": "Rosewood/src/Rosewood/Scripting/lua/wrappers/wrap_Math.h", "rank": 52, "score": 197342.36446418217 }, { "content": " class wrap_Application : public LuaWrapper\n\n {\n\n private:\n\n static const char* Name;\n\n \n\n public:\n\n static int w_getDeltaTime(lua_State* L);\n\n static int w_getDeltaTimeMiliseconds(lua_State* L);\n\n static int w_getTime(lua_State* L);\n\n static int w_getTimeMiliseconds(lua_State* L);\n\n\n\n wrap_Application(lua_State* L);\n\n virtual const char* GetName() const { return Name; }\n\n };\n\n\n", "file_path": "Rosewood/src/Rosewood/Scripting/lua/wrappers/wrap_Core.h", "rank": 53, "score": 197342.36446418217 }, { "content": " class wrap_Benchmark : public LuaWrapper\n\n {\n\n private:\n\n static const char* Name; \n\n public:\n\n wrap_Benchmark(lua_State* L);\n\n virtual const char* GetName() const { return Name; }\n\n\n\n };\n\n}", "file_path": "Rosewood/src/Rosewood/Scripting/lua/wrappers/wrap_Debug.h", "rank": 54, "score": 197342.36446418217 }, { "content": " class Game : public Rosewood::Layer\n\n {\n\n public:\n\n Game();\n\n virtual ~Game() = default;\n\n\n\n virtual void OnAttach() override;\n\n virtual void OnDetach() override;\n\n\n\n void OnUpdate(Rosewood::Timestep timestep) override;\n\n virtual void OnImGuiRender() override;\n\n void OnEvent(Rosewood::Event& e) override;\n\n\n\n };\n\n\n\n}\n\n\n", "file_path": "Game/Client/src/Game.h", "rank": 55, "score": 196888.73203126492 }, { "content": " class Game : public Rosewood::Layer\n\n {\n\n public:\n\n Game();\n\n virtual ~Game() = default;\n\n\n\n virtual void OnAttach() override;\n\n virtual void OnDetach() override;\n\n\n\n void OnUpdate(Rosewood::Timestep timestep) override;\n\n virtual void OnImGuiRender() override;\n\n void OnEvent(Rosewood::Event& e) override;\n\n\n\n static Scene* GetScene();\n\n private:\n\n static Scene* s_Scene;\n\n };\n\n\n\n}\n\n\n", "file_path": "TestGame/src/Game.h", "rank": 56, "score": 196888.73203126492 }, { "content": "\tclass EventDispatcher\n\n\t{\n\n\tpublic:\n\n\t\tEventDispatcher(Event& event)\n\n\t\t\t: m_Event(event)\n\n\t\t{\n\n\t\t}\n\n\n\n\t\t// F will be deduced by the compiler\n\n\t\ttemplate<typename T, typename F>\n\n\t\tbool Dispatch(const F& func)\n\n\t\t{\n\n\t\t\tif (m_Event.GetEventType() == T::GetStaticType())\n\n\t\t\t{\n\n\t\t\t\tm_Event.Handled |= func(static_cast<T&>(m_Event));\n\n\t\t\t\treturn true; //TODO: MAKE BUS FOR EVENTS DURING UPDATE\n\n\t\t\t}\n\n\t\t\treturn false;\n\n\t\t}\n\n\tprivate:\n\n\t\tEvent& m_Event;\n\n\t};\n\n\n\n\tinline std::ostream& operator<<(std::ostream& os, const Event& e)\n\n\t{\n\n\t\treturn os << e.ToString();\n\n\t}\n\n\n\n}\n", "file_path": "Rosewood/src/Rosewood/Events/Event.h", "rank": 57, "score": 195518.71595636033 }, { "content": "class Sandbox : public Rosewood::Application\n\n{\n\npublic:\n\n\n\n\tSandbox()\n\n\t{\n\n\t\tPushLayer(new ExampleLayer()); \n\n\t}\n\n\n\n\t~Sandbox()\n\n\t{\n\n\n\n }\n\n};\n\n\n\nRosewood::Application* Rosewood::CreateApplication()\n\n{\n\n\n\n\treturn new Sandbox();\n\n}\n\n\n\n\n", "file_path": "Sandbox3D/src/2dapp.cpp", "rank": 58, "score": 195324.4004684075 }, { "content": "class Sandbox : public Rosewood::Application\n\n{\n\npublic:\n\n\n\n Sandbox()\n\n {\n\n PushLayer(new TestGame::Game());\n\n }\n\n\n\n ~Sandbox()\n\n {\n\n Rosewood::Renderer2D::Shutdown();\n\n\n\n }\n\n};\n\n\n\nRosewood::Application* Rosewood::CreateApplication()\n\n{\n\n \n\n return new Sandbox();\n\n}\n\n\n\n\n", "file_path": "TestGame/src/Application.cpp", "rank": 59, "score": 195324.4004684075 }, { "content": "class GameApplication : public Rosewood::Application\n\n{\n\npublic:\n\n\n\n GameApplication()\n\n {\n\n PushLayer(new Game::Game());\n\n }\n\n\n\n ~GameApplication()\n\n {\n\n Rosewood::Renderer2D::Shutdown();\n\n }\n\n};\n\n\n\nRosewood::Application* Rosewood::CreateApplication()\n\n{\n\n return new GameApplication();\n\n}\n\n\n\n\n", "file_path": "Game/Client/src/Application.cpp", "rank": 61, "score": 193798.1495522591 }, { "content": "class ExampleLayer : public Rosewood::Layer\n\n{\n\npublic:\n\n\tunsigned int scrWidth = Rosewood::Application::Get().GetWindow().GetWidth();\n\n\tunsigned int scrHeight = Rosewood::Application::Get().GetWindow().GetHeight();\n\n\tfloat lastX = scrWidth / 2.0f;\n\n\tfloat lastY = scrHeight / 2.0f;\n\n\t\n\n Rosewood::Ref<Rosewood::Texture> texture;\n\n Rosewood::Ref<Rosewood::Texture> fontTexture;\n\n \n\n Rosewood::Ref<Rosewood::Model> model;\n\n \n\n Rosewood::Ref<Rosewood::Sound> sound;\n\n \n\n Rosewood::EditorCamera camera = Rosewood::EditorCamera(45.0f, 16.0f/9.0f, 0.1f, 1000.0f);\n\n \n\n bool open = true;\n\n \n\n float mouseX = 0.0f;\n", "file_path": "Sandbox3D/src/2dapp.cpp", "rank": 63, "score": 193798.1495522591 }, { "content": "\tclass Texture\n\n\t{\n\n public:\n\n virtual ~Texture() = default;\n\n\n\n virtual uint32_t GetWidth() const = 0;\n\n virtual uint32_t GetHeight() const = 0;\n\n virtual uint32_t GetID() const = 0;\n\n virtual std::string& GetPath() = 0;\n\n\n\n virtual void SetData(void* data, uint32_t size) = 0;\n\n\n\n virtual void Bind(uint32_t slot = 0) const = 0;\n\n \n\n virtual bool operator==(const Texture& other) const = 0;\n\n\n\n static AssetType GetAssetType() { return AssetType::Texture; }\n\n \n\n static Ref<Texture> Create(const std::string& path);\n\n static Ref<Texture> Create(const BinaryFile& file);\n\n static Ref<Texture> Create(uint32_t width, uint32_t height);\n\n\t};\n\n\n\n}\n", "file_path": "Rosewood/src/Rosewood/Graphics/API/Texture.h", "rank": 64, "score": 190597.83983185433 }, { "content": " class Renderer\n\n {\n\n public:\n\n static void Init();\n\n static void Begin(EditorCamera& camera);\n\n static void End();\n\n \n\n static void Submit(Ref<Model>& model, glm::mat4 transform);\n\n static void Submit(Ref<Mesh>& mesh, glm::mat4 transform);\n\n\n\n static void Submit(Ref<Mesh>& mesh, glm::mat4 transform, Ref<Shader> shader);\n\n \n\n };\n\n\n\n}\n\n\n", "file_path": "Rosewood/src/Rosewood/Graphics/3D/Renderer.h", "rank": 65, "score": 190560.5099287687 }, { "content": "function CameraScript:OnKeyReleased(key)\n\n if (key == Keys.DOWN) then\n\n InputDown = 0;\n\n elseif (key == Keys.UP) then\n\n InputUp = 0;\n\n end\n\nend", "file_path": "TestGame/Content/Scripts/CameraController.lua", "rank": 66, "score": 190463.2993177311 }, { "content": "function CameraScript:OnKeyPressed(key)\n\n if (key == Keys.DOWN) then\n\n InputDown = 1;\n\n elseif (key == Keys.UP) then\n\n InputUp = 1;\n\n end\n\nend\n\n\n", "file_path": "TestGame/Content/Scripts/CameraController.lua", "rank": 67, "score": 190463.2993177311 }, { "content": " class FileSystem\n\n {\n\n public:\n\n static const std::string EngineRoot;\n\n static const std::string ProjectRoot;\n\n static const std::string EngineFolder;\n\n static const std::string ProjectFolder;\n\n \n\n\n\n static std::string GetPath(const std::string& path, FilePathType type = FilePathType::PROJECT);\n\n static std::string GetRootPath(FilePathType type = FilePathType::PROJECT);\n\n static std::string GetFolderName(FilePathType type = FilePathType::PROJECT);\n\n\n\n static void CreateDirectory(const std::string& path, FilePathType type = FilePathType::PROJECT);\n\n static void CreateDirectories(const std::string& path, FilePathType type = FilePathType::PROJECT);\n\n\n\n static bool Exists(const std::string& path, FilePathType type = FilePathType::PROJECT);\n\n static bool Exists(std::filesystem::path& path);\n\n\n\n static void CopyFile(const std::string& pathFrom, const std::string& pathTo, FilePathType type = FilePathType::PROJECT);\n", "file_path": "Rosewood/src/Rosewood/Files/FileSystem.h", "rank": 68, "score": 189227.8917494158 }, { "content": " class SpriteFont\n\n {\n\n public:\n\n SpriteFont();\n\n ~SpriteFont() {}\n\n\n\n SpriteFont(Ref<Texture>& texture, const std::string& charset, uint32_t char_width, uint32_t char_height)\n\n : m_Texture(texture), m_CharWidth(char_width), m_CharHeight(char_height)\n\n {\n\n uint32_t i = 0;\n\n for(char c : charset)\n\n {\n\n m_CharSet[c] = i;\n\n i++;\n\n }\n\n }\n\n \n\n //TODO: SCALE\n\n\n\n void DrawString(glm::vec2 pos, std::string& text, glm::vec4 color, glm::vec2 scale = {1.0f, 1.0f}, uint32_t h_spacing = 0, uint32_t v_spacing = 0, uint32_t max_width = 250)\n", "file_path": "Rosewood/src/Rosewood/Graphics/API/SpriteFont.h", "rank": 69, "score": 187901.48364054732 }, { "content": "\tenum class EventType\n\n\t{\n\n\t\tNone = 0,\n\n\t\tWindowClose, WindowResize, WindowFocus, WindowLostFocus, WindowMoved,\n\n\t\tAppTick, AppUpdate, AppRender,\n\n\t\tKeyPressed, KeyReleased, KeyTyped,\n\n\t\tMouseButtonPressed, MouseButtonReleased, MouseMoved, MouseScrolled,\n\n\t\tGamepadButtonPressed, GamepadButtonReleased, GamepadAxisMoved\n\n\t};\n\n\n\n\tenum EventCategory\n\n\t{\n\n\t\tNone = 0,\n\n\t\tEventCategoryApplication = BIT(0),\n\n\t\tEventCategoryInput = BIT(1),\n\n\t\tEventCategoryKeyboard = BIT(2),\n\n\t\tEventCategoryMouse = BIT(3),\n\n\t\tEventCategoryMouseButton = BIT(4),\n\n\t\tEventCategoryGamepad = BIT(5),\n\n\t\tEventCategoryGamepadButton = BIT(6),\n\n\t\tEventCategoryGamepadAxis = BIT(7)\n\n\t};\n\n\n\n#define EVENT_CLASS_TYPE(type) static EventType GetStaticType() { return EventType::type; }\\\n\n\t\t\t\t\t\t\t\tvirtual EventType GetEventType() const override { return GetStaticType(); }\\\n\n\t\t\t\t\t\t\t\tvirtual const char* GetName() const override { return #type; }\n\n\n\n#define EVENT_CLASS_CATEGORY(category) virtual int GetCategoryFlags() const override { return category; }\n\n\n", "file_path": "Rosewood/src/Rosewood/Events/Event.h", "rank": 70, "score": 187880.01786002595 }, { "content": " class DeferredRenderer\n\n {\n\n public:\n\n static void Init();\n\n static void Begin(OrthographicCamera& camera);\n\n static void DrawDecals();\n\n static void BeginLights();\n\n static void End();\n\n \n\n \n\n static void DrawPointLight(glm::vec3 pos, glm::vec3 color, float intensity, float constant, float linear, float quadratic);\n\n \n\n static void SubmitDecalLight(Ref<DecalLight> decal);\n\n \n\n static void ReloadShaders();\n\n\n\n static void Submit(Ref<RenderMesh>& mesh, glm::vec3 pos, glm::vec3 scale);\n\n\n\n static uint32_t GetLightID();\n\n static uint32_t GetPosID();\n", "file_path": "Rosewood/src/Rosewood/Graphics/2D/DeferredRenderer.h", "rank": 71, "score": 187858.09430185036 }, { "content": " class BatchRenderer\n\n {\n\n public:\n\n \n\n static void Init();\n\n static void Begin(const OrthographicCamera& camera);\n\n static void Begin(const EditorCamera& camera);\n\n static void Begin(const Camera& camera, const glm::mat4& transform);\n\n\n\n\n\n static void BeginBatch();\n\n static void End();\n\n static void Draw();\n\n static void Flush();\n\n static void FlushAndReset();\n\n\n\n //Main Draw Functions\n\n static void DrawQuad(const glm::vec3& pos, const glm::vec2& size, Ref<Texture>& texture, const glm::vec4& uv, const glm::vec4& color);\n\n static void DrawQuad(const glm::mat4& transform, const glm::vec4& color);\n\n static void DrawQuad(const glm::mat4& transform, Ref<Texture>& texture, const glm::vec4& uv, const glm::vec4& color);\n", "file_path": "Rosewood/src/Rosewood/Graphics/2D/BatchRenderer.h", "rank": 72, "score": 187858.09430185036 }, { "content": " class RenderItem2D\n\n {\n\n public:\n\n bool Visible = true;\n\n bool Transparent = false;\n\n //bool AxisAligned = true;\n\n\n\n glm::vec4 Color = {1.0f, 1.0f, 1.0f, 1.0f};\n\n RenderItem2D(glm::vec4 color): Color(color)\n\n {\n\n Transparent = color.z < 1.0f;\n\n }\n\n RenderItem2D(glm::vec4 color, bool transparent): Color(color), Transparent(transparent)\n\n {}\n\n virtual void Draw(Transform transform){}\n\n };\n\n\n", "file_path": "Rosewood/src/Rosewood/Graphics/2D/RenderItem2D.h", "rank": 73, "score": 185264.3020536404 }, { "content": " class Server : public Rosewood::ServerInterface<GameMessages>\n\n {\n\n public:\n\n Server(uint16_t port, bool secure = false)\n\n : Rosewood::ServerInterface<GameMessages>(port, secure)\n\n {\n\n \n\n }\n\n protected:\n\n bool OnClientConnect(Rosewood::Ref<Rosewood::Connection<GameMessages>> client) override\n\n {\n\n \n\n return true;\n\n }\n\n\n\n void OnMessage(Rosewood::Ref<Rosewood::Connection<GameMessages>> client, Rosewood::Message<GameMessages> message) override\n\n {\n\n std::cout<<'\\n';\n\n RW_CORE_INFO(\"Message Data: {0}, {1}\", message.Header.Size, message.Header.Id);\n\n switch (message.Header.Id)\n", "file_path": "Game/Server/src/Application.cpp", "rank": 74, "score": 184405.18273206666 }, { "content": " class Client : public Rosewood::ClientInterface<GameMessages>\n\n {\n\n public:\n\n Client()\n\n : Rosewood::ClientInterface<GameMessages>()\n\n {}\n\n };\n\n\n\n Client client;\n\n \n\n Game::Game()\n\n : Layer(\"Example\") {}\n\n void Game::OnAttach()\n\n {\n\n Rosewood::Renderer2D::Init();\n\n Rosewood::Benchmark::Init();\n\n\n\n Rosewood::AssetLoader::LoadAssets(Rosewood::FileSystem::GetPath(\"Index.json\"));\n\n\n\n Rosewood::SceneManager::SetScene(Rosewood::Scene::Create());\n", "file_path": "Game/Client/src/Game.cpp", "rank": 75, "score": 184405.18273206666 }, { "content": " class System //Add Tags, names of some sorts for benchmarking\n\n {\n\n public:\n\n \n\n System() {};\n\n ~System() {};\n\n virtual void OnAttached() {}\n\n\n\n\t\tvirtual void OnUpdate(Timestep ts) {}\n\n\n\n virtual void OnRender() {}\n\n\n\n void AttachSceneData(Ref<Scene> scene) { m_Scene = scene; m_Registry = scene->GetRegistry(); }\n\n\n\n private:\n\n entt::registry* m_Registry; \n\n Ref<Scene> m_Scene = nullptr;\n\n };\n\n}", "file_path": "Rosewood/src/Rosewood/ECS/System.h", "rank": 76, "score": 181409.74873740698 }, { "content": "\t\tenum class ProjectionType { Perspective = 0, Orthographic = 1 };\n\n\tpublic:\n\n\t\tSceneCamera();\n\n\t\tvirtual ~SceneCamera() = default;\n\n\n\n\t\tvoid SetPerspective(float verticalFOV, float nearClip, float farClip);\n\n\t\tvoid SetOrthographic(float size, float nearClip, float farClip);\n\n\n\n\t\tvoid SetViewportSize(uint32_t width, uint32_t height);\n\n\n\n\t\tfloat GetPerspectiveVerticalFOV() const { return m_PerspectiveFOV; }\n\n\t\tvoid SetPerspectiveVerticalFOV(float verticalFov) { m_PerspectiveFOV = verticalFov; RecalculateProjection(); }\n\n\t\tfloat GetPerspectiveNearClip() const { return m_PerspectiveNear; }\n\n\t\tvoid SetPerspectiveNearClip(float nearClip) { m_PerspectiveNear = nearClip; RecalculateProjection(); }\n\n\t\tfloat GetPerspectiveFarClip() const { return m_PerspectiveFar; }\n\n\t\tvoid SetPerspectiveFarClip(float farClip) { m_PerspectiveFar = farClip; RecalculateProjection(); }\n\n\n\n\t\tfloat GetOrthographicSize() const { return m_OrthographicSize; }\n\n\t\tvoid SetOrthographicSize(float size) { m_OrthographicSize = size; RecalculateProjection(); }\n\n\t\tfloat GetOrthographicNearClip() const { return m_OrthographicNear; }\n", "file_path": "Rosewood/src/Rosewood/ECS/SceneCamera.h", "rank": 77, "score": 180537.05031524735 }, { "content": " class Connection : public std::enable_shared_from_this<Connection<T>>\n\n {\n\n public:\n", "file_path": "Rosewood/src/Rosewood/Net/Connection.h", "rank": 78, "score": 179045.037016012 }, { "content": " class TextFile\n\n {\n\n public:\n\n TextFile() {}\n\n TextFile(const std::string& filepath);\n\n TextFile(std::string& data);\n\n TextFile(const BinaryFile& data);\n\n\n\n ~TextFile() {};\n\n\n\n void Reload();\n\n void Write();\n\n void Write(const std::string& filepath);\n\n\n\n const std::string& GetPath() const { return m_Path; }\n\n const std::string& GetData() const { return m_Data; }\n\n const std::vector<byte> GetRawData();\n\n void SetData(const std::string& data) { m_Data = data; } // Maybe copy the data?\n\n\n\n\n", "file_path": "Rosewood/src/Rosewood/Files/File.h", "rank": 79, "score": 178851.30939239118 }, { "content": " class TextFile;\n\n\n", "file_path": "Rosewood/src/Rosewood/Files/File.h", "rank": 80, "score": 178851.30939239118 }, { "content": " def open(self, filename):\n\n \"\"\"Open a new file named 'filename'. This overrides both the\n\n 'filename' and 'file' arguments to the constructor.\"\"\"\n\n self.filename = filename\n\n self.file = io.open(self.filename, 'r', errors=self.errors)\n", "file_path": "Tools/venv/lib/python3.9/site-packages/setuptools/_distutils/text_file.py", "rank": 81, "score": 175783.27884932075 }, { "content": " enum class ShaderDataType\n\n {\n\n None = 0, Float, Float2, Float3, Float4, Mat3, Mat4, Int, Int2, Int3, Int4, Bool\n\n };\n\n\n\n static uint32_t ShaderDataTypeSize(ShaderDataType type)\n\n {\n\n switch (type) {\n\n case ShaderDataType::Float: return 4;\n\n case ShaderDataType::Float2: return 4 * 2;\n\n case ShaderDataType::Float3: return 4 * 3;\n\n case ShaderDataType::Float4: return 4 * 4;\n\n case ShaderDataType::Mat3: return 4 * 3 * 3;\n\n case ShaderDataType::Mat4: return 4 * 4 * 4;\n\n case ShaderDataType::Int: return 4;\n\n case ShaderDataType::Int2: return 4 * 2;\n\n case ShaderDataType::Int3: return 4 * 3;\n\n case ShaderDataType::Int4: return 4 * 4;\n\n case ShaderDataType::Bool: return 1;\n\n default: break;\n", "file_path": "Rosewood/src/Rosewood/Graphics/API/Buffer.h", "rank": 82, "score": 167760.91372390956 }, { "content": " enum class FilePathType\n\n {\n\n ENGINE = 0,\n\n PROJECT = 1,\n\n USER = 2,\n\n }; \n\n const uint32_t FilePathTypeCount = 3;\n\n const std::string FilePathTypeNames[3] =\n\n {\n\n \"Engine\",\n\n \"Project\",\n\n \"User\"\n\n };\n\n\n", "file_path": "Rosewood/src/Rosewood/Files/FileSystem.h", "rank": 83, "score": 167754.8403813152 }, { "content": " enum class FramebufferTextureFormat\n\n {\n\n None = 0,\n\n\n\n // Color\n\n RGBA8,\n\n RGB8,\n\n RGBA16F,\n\n RGB16F,\n\n // Depth/stencil\n\n DEPTH24STENCIL8,\n\n\n\n // Defaults\n\n Depth = DEPTH24STENCIL8\n\n };\n\n struct FramebufferTextureSpecification\n\n {\n\n FramebufferTextureSpecification() = default;\n\n FramebufferTextureSpecification(FramebufferTextureFormat format)\n\n : TextureFormat(format) {}\n", "file_path": "Rosewood/src/Rosewood/Graphics/API/FrameBuffer.h", "rank": 84, "score": 166268.62609293414 }, { "content": "#pragma once\n\n\n\n#include \"Event.h\"\n\n#include \"Rosewood/Core/Core.h\"\n\n#include \"rwpch.h\"\n\n\n\n\n\nnamespace Rosewood {\n\n\n", "file_path": "Rosewood/src/Rosewood/Events/KeyEvent.h", "rank": 85, "score": 141709.74781237188 }, { "content": " virtual void setMat3(const std::string& name, const glm::mat3& mat) override;\n\n virtual void setMat2(const std::string& name, const glm::mat2& mat) override;\n\n virtual void setVec4(const std::string& name, const glm::vec4& value) override;\n\n virtual void setVec3(const std::string& name, const glm::vec3& value) override;\n\n virtual void setVec2(const std::string& name, const glm::vec2& value) override;\n\n \n\n virtual void Recompile() override;\n\n virtual void Recompile(const std::string& vs, const std::string& fs) override;\n\n\n\n private:\n\n std::string m_Path;\n\n uint32_t m_ID;\n\n uint32_t CompileShader(unsigned int type, const std::string& source);\n\n uint32_t Compile();\n\n uint32_t Compile(const std::string& text);\n\n };\n\n}\n", "file_path": "Rosewood/src/Platform/OpenGL/OpenGLShader.h", "rank": 86, "score": 139008.72594028295 }, { "content": " }\n\n\n\n virtual void Bind(uint32_t slot = 0) const override;\n\n private:\n\n std::string m_Path;\n\n uint32_t m_Width, m_Height;\n\n GLenum m_InternalFormat, m_DataFormat;\n\n uint32_t m_ID;\n\n void loadTexture(unsigned char* data, int width, int height, int channels );\n\n };\n\n}\n", "file_path": "Rosewood/src/Platform/OpenGL/OpenGLTexture.h", "rank": 87, "score": 139008.31209024612 }, { "content": "#pragma once\n\n\n\n#include <string>\n\n#include \"Rosewood/Graphics/API/Texture.h\"\n\n#include \"Rosewood/Files/File.h\"\n\n\n\ntypedef unsigned int GLenum;\n\n\n\nnamespace Rosewood\n\n{\n\n\n", "file_path": "Rosewood/src/Platform/OpenGL/OpenGLTexture.h", "rank": 88, "score": 139006.31189373689 }, { "content": "#pragma once\n\n#include <rwpch.h>\n\n#include <glm/glm.hpp>\n\n#include <glm/gtc/matrix_transform.hpp>\n\n#include <glm/gtc/type_ptr.hpp>\n\n#include \"Rosewood/Graphics/API/Shader.h\"\n\n#include \"Rosewood/Files/File.h\"\n\n\n\nnamespace Rosewood\n\n{\n", "file_path": "Rosewood/src/Platform/OpenGL/OpenGLShader.h", "rank": 89, "score": 138999.91705019746 }, { "content": " }\n\n\n\n\tvoid OpenGLShader::setBool(const std::string& name, bool value)\n\n\t{\n\n\t\tglUniform1i(glGetUniformLocation(m_ID, name.c_str()), (int)value);\n\n\t}\n\n\tvoid OpenGLShader::setInt(const std::string& name, int value)\n\n\t{\n\n\t\tglUniform1i(glGetUniformLocation(m_ID, name.c_str()), value);\n\n\t}\n\n\tvoid OpenGLShader::setIntPtr(const std::string& name, int count, int* value)\n\n\t{\n\n\t\tglUniform1iv(glGetUniformLocation(m_ID, name.c_str()), count, value);\n\n\t}\n\n\tvoid OpenGLShader::setFloat(const std::string& name, float value)\n\n\t{\n\n\t\tglUniform1f(glGetUniformLocation(m_ID, name.c_str()), value);\n\n }\n\n\tvoid OpenGLShader::setVec2(const std::string& name, const glm::vec2& value)\n\n\t{\n", "file_path": "Rosewood/src/Platform/OpenGL/OpenGLShader.cpp", "rank": 90, "score": 137677.04747495684 }, { "content": "#include \"rwpch.h\"\n\n#include \"OpenGLTexture.h\"\n\n#include \"stb_image.h\"\n\n#include <glad/glad.h>\n\n#include \"OpenGL.h\"\n\n\n\nnamespace Rosewood\n\n{\n\n void OpenGLTexture::loadTexture(unsigned char* data, int width, int height, int channels )\n\n\t{\n\n\t\tm_Width = width;\n\n\t\tm_Height = height;\n\n\n\n\t\tGLenum internalFormat = 0, dataFormat = 0;\n\n\t\tif (channels == 4)\n\n\t\t{\n\n\t\t\tinternalFormat = GL_RGBA8;\n\n\t\t\tdataFormat = GL_RGBA;\n\n\t\t}\n\n\t\telse if (channels == 3)\n", "file_path": "Rosewood/src/Platform/OpenGL/OpenGLTexture.cpp", "rank": 91, "score": 137675.4452468462 }, { "content": "\tOpenGLShader::OpenGLShader(const TextFile& file)\n\n\t\t: m_Path(file.GetPath())\n\n\t{\n\n\t\tm_ID = Compile(file.GetData());\n\n\t}\n\n\n\n\tuint32_t OpenGLShader::CompileShader(unsigned int type, const std::string& source)\n\n\t{\n\n\t\tuint32_t id = glCreateShader(type);\n\n\t\tconst char* src = source.c_str();\n\n\t\tglShaderSource(id, 1, &src, nullptr);\n\n\t\tglCompileShader(id);\n\n\n\n\t\tint result;\n\n\n\n\t\tglGetShaderiv(id, GL_COMPILE_STATUS, &result);\n\n\n\n\t\tif (result == GL_FALSE)\n\n\t\t{\n\n\t\t\tint length;\n", "file_path": "Rosewood/src/Platform/OpenGL/OpenGLShader.cpp", "rank": 92, "score": 137671.86968213637 }, { "content": "#include \"rwpch.h\"\n\n#include \"OpenGLShader.h\"\n\n#include <glm/glm.hpp>\n\n#include <glm/gtc/matrix_transform.hpp>\n\n#include <glm/gtc/type_ptr.hpp>\n\n#include <glad/glad.h>\n\n\n\nnamespace Rosewood\n\n{\n\n\t\n\n\tOpenGLShader::OpenGLShader(const std::string& path)\n\n\t\t: m_Path(path)\n\n\t{\n\n\t\tm_ID = Compile();\n\n\t}\n\n\tOpenGLShader::OpenGLShader(const BinaryFile& file)\n\n\t\t: m_Path(file.GetPath())\n\n\t{\n\n\t\tm_ID = Compile(file.ToTextFile().GetData());\n\n\t}\n", "file_path": "Rosewood/src/Platform/OpenGL/OpenGLShader.cpp", "rank": 93, "score": 137671.55374300267 }, { "content": " glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);\n\n \n\n glTexImage2D(GL_TEXTURE_2D, 0, m_InternalFormat, m_Width, m_Height, 0, m_DataFormat, GL_UNSIGNED_BYTE, data);\n\n\n\n \n\n glBindTexture(GL_TEXTURE_2D, 0);\n\n delete [] data;\n\n \n\n\t}\n\n\n\n\n\n\n\n\n\n\tOpenGLTexture::~OpenGLTexture()\n\n\t{\n\n\t\tglDeleteTextures(1, &m_ID);\n\n\t}\n\n\n\n\tvoid OpenGLTexture::SetData(void* data, uint32_t size)\n\n\t{\n", "file_path": "Rosewood/src/Platform/OpenGL/OpenGLTexture.cpp", "rank": 94, "score": 137667.09101193122 }, { "content": "\n\n glAttachShader(m_ID, vertexShader);\n\n glAttachShader(m_ID, fragmentShader);\n\n glLinkProgram(m_ID);\n\n glValidateProgram(m_ID);\n\n\n\n glDeleteShader(vertexShader);\n\n glDeleteShader(fragmentShader);\n\n }\n\n\n\n\n\n\tvoid OpenGLShader::Bind()\n\n\t{\n\n\n\n\t\tglUseProgram(m_ID);\n\n\t}\n\n void OpenGLShader::Unbind()\n\n {\n\n\n\n glUseProgram(0);\n", "file_path": "Rosewood/src/Platform/OpenGL/OpenGLShader.cpp", "rank": 95, "score": 137667.0599605655 }, { "content": "\t\tglAttachShader(id, vs);\n\n\t\tglAttachShader(id, fs);\n\n\t\tglLinkProgram(id);\n\n\t\tglValidateProgram(id);\n\n\n\n\t\tglDeleteShader(vs);\n\n\t\tglDeleteShader(fs);\n\n\n\n\t\treturn id;\n\n\t}\n\n void OpenGLShader::Recompile()\n\n {\n\n m_ID = Compile();\n\n }\n\n\n\n void OpenGLShader::Recompile(const std::string& vs, const std::string& fs)\n\n {\n\n\n\n uint32_t vertexShader = CompileShader(GL_VERTEX_SHADER, vs);\n\n uint32_t fragmentShader = CompileShader(GL_FRAGMENT_SHADER, fs);\n", "file_path": "Rosewood/src/Platform/OpenGL/OpenGLShader.cpp", "rank": 96, "score": 137665.9187986359 }, { "content": "\t\tglAttachShader(id, vs);\n\n\t\tglAttachShader(id, fs);\n\n\t\tglLinkProgram(id);\n\n\t\tglValidateProgram(id);\n\n\n\n\t\tglDeleteShader(vs);\n\n\t\tglDeleteShader(fs);\n\n\n\n\t\treturn id;\n\n\t}\n\n\tuint32_t OpenGLShader::Compile(const std::string& text)\n\n\t{\n\n\t\tstd::stringstream stream;\n\n\t\tstream << text;\n", "file_path": "Rosewood/src/Platform/OpenGL/OpenGLShader.cpp", "rank": 97, "score": 137665.4246467343 }, { "content": " \n\n\t\tstbi_image_free(data);\n\n\t}\n\n\n\n\tOpenGLTexture::OpenGLTexture(const std::string& path)\n\n\t\t: m_Path(path)\n\n\t{\n\n\t\tint width, height, channels;\n\n\t\tstbi_set_flip_vertically_on_load(1);\n\n\n\n\t\tunsigned char* data = stbi_load(path.c_str(), &width, &height, &channels, 0);\n\n\t\n\n\t\tRW_CORE_ASSERT(data, \"Failed to load image! \" + m_Path + \" stb_image: \" + stbi_failure_reason());\n\n\n\n\t\tloadTexture(data, width, height, channels);\n\n\t}\n\n\tOpenGLTexture::OpenGLTexture(const BinaryFile& file)\n\n\t\t: m_Path(file.GetPath())\n\n\t{\n\n\t\tint width, height, channels;\n", "file_path": "Rosewood/src/Platform/OpenGL/OpenGLTexture.cpp", "rank": 98, "score": 137665.33864490857 } ]
C++
eip_device/src/eip_device_node.cpp
wpmccormick/eip_device
808628a7ede642eead1ed9b81db34c0c73ff8b5c
#include <stdio.h> #include <stdlib.h> #include <signal.h> #include <sys/capability.h> #include <sys/capability.h> extern "C" { #include "trace.h" #include "opener_api.h" #include "cipcommon.h" #include "trace.h" #include "POSIX/networkconfig.h" #include "doublylinkedlist.h" #include "cipconnectionobject.h" #include "appcontype.h" #include "cipidentity.h" #include "generic_networkhandler.h" } #include <ros/ros.h> #include "eip_device.h" #define DEVICE_SERIAL_NUM 123456789 using namespace std; void LeaveStack(int signal); int g_end_stack = 0; EipDevice eipDevice; int main(int argc, char **argv) { cap_t capabilities; cap_value_t capabilies_list[1]; ros::init(argc, argv, "eip_device"); ros::NodeHandle nh("~"); ROS_INFO("Starting eip_device ..."); ros::Time::init(); double freq; nh.param<double>("frequency", freq, 1); ros::Rate throttle(freq); string device; nh.param<std::string>("device", device, "eth0"); ROS_INFO_STREAM("Using Ethernet device: " << device); ROS_INFO("Getting Ethernet port capabilities ..."); capabilities = cap_get_proc(); if (NULL == capabilities) { ROS_ERROR("Could not get capabilities"); exit(0); } capabilies_list[0] = CAP_NET_RAW; if (-1 == cap_set_flag(capabilities, CAP_EFFECTIVE, 1, capabilies_list, CAP_SET) ) { cap_free(capabilities); ROS_ERROR("Could not set CAP_NET_RAW capability"); exit(0); } if (-1 == cap_set_proc(capabilities) ) { cap_free(capabilities); ROS_ERROR("Could not push CAP_NET_RAW capability to process"); exit(0); } if (-1 == cap_free(capabilities) ) { ROS_ERROR("Could not free capabilites value"); exit(0); } DoublyLinkedListInitialize(&connection_list, CipConnectionObjectListArrayAllocator, CipConnectionObjectListArrayFree); if (kEipStatusError == ConfigureNetworkInterface(device.c_str()) ) { ROS_ERROR("Network interface %s not found.\n", device.c_str()); exit(0); } ConfigureDomainName(); ConfigureHostName(); ConfigureMacAddress(device.c_str()); SetDeviceSerialNumber(DEVICE_SERIAL_NUM); EipUint16 unique_connection_id = rand(); CipStackInit(unique_connection_id); if (kEipStatusOk == NetworkHandlerInitialize() ) { g_end_stack = 0; } else { ROS_ERROR("Error initializing NetworkHandler! Exiting eip_device!"); exit(0); } ros::Publisher eip_data_pub = nh.advertise<eip_device::EipDataAsmOut>("eip_data_fmplc", 1); ros::Publisher eip_config_pub = nh.advertise<eip_device::EipDataAsmCfg>("eip_data_config", 1); ros::Publisher eip_status_pub = nh.advertise<eip_device::EipDeviceStatus>("eip_status", 100); ros::Subscriber eip_unsol_data_sub = nh.subscribe("eip_data_toplc_u", 1, &EipDevice::LoadAsmIn_Callback, &eipDevice); ros::Subscriber eip_sol_data_sub = nh.subscribe("eip_data_toplc_s", 1, &EipDevice::LoadAsmIn_Callback, &eipDevice); ROS_INFO("Starting Process Loop"); int EipStatus = kEipStatusOk; while(ros::ok() && (1 != g_end_stack) && (EipStatus == kEipStatusOk))2 { EipStatus = NetworkHandlerProcessOnce(); if (EipStatus != kEipStatusOk) { ROS_ERROR_STREAM("Error in NetworkHandler loop! Exiting eip_device! -- " << EipStatus ); break; } eipDevice.data_asm_out.raw_plc_data.assign(g_assembly_data096, g_assembly_data096 + OUTPUT_ASSEMBLY_BUFFER_SIZE); eipDevice.data_asm_cfg.raw_plc_data.assign(g_assembly_data097, g_assembly_data097 + CONFIG_ASSEMBLY_BUFFER_SIZE); eip_data_pub.publish(eipDevice.data_asm_out); eip_config_pub.publish(eipDevice.data_asm_cfg); eip_status_pub.publish(eipDevice.device_status); ros::spinOnce(); throttle.sleep(); } ROS_INFO("Finish network handler"); NetworkHandlerFinish(); ROS_INFO("Shutdown CIP Stack"); ShutdownCipStack(); return g_end_stack; } void LeaveStack(int signal) { (void) signal; OPENER_TRACE_STATE("got signal HUP\n"); ROS_INFO("HUP Signal!"); g_end_stack = 1; }
#include <stdio.h> #include <stdlib.h> #include <signal.h> #include <sys/capability.h> #include <sys/capability.h> extern "C" { #include "trace.h" #include "opener_api.h" #include "cipcommon.h" #include "trace.h" #include "POSIX/networkconfig.h" #include "doublylinkedlist.h" #include "cipconnectionobject.h" #include "appcontype.h" #include "cipidentity.h" #include "generic_networkhandler.h" } #include <ros/ros.h> #include "eip_device.h" #define DEVICE_SERIAL_NUM 123456789 using namespace std; void LeaveStack(int signal); int g_end_stack = 0; EipDevice eipDevice; int main(int argc, char **argv) { cap_t capabilities; cap_value_t capabilies_list[1]; ros::init(argc, argv, "eip_device"); ros::NodeHandle nh("~"); ROS_INFO("Starting eip_device ..."); ros::Time::init(); double freq; nh.param<double>("frequency", freq, 1); ros::Rate throttle(freq); string device; nh.param<std::string>("device", device, "eth0"); ROS_INFO_STREAM("Using Ethernet device: " << device); ROS_INFO("Getting Ethernet port capabilities ..."); capabilities = cap_get_proc(); if (NULL == capabilities) { ROS_ERROR("Could not get capabilities"); exit(0); } capabilies_list[0] = CAP_NET_RAW;
if (-1 == cap_set_proc(capabilities) ) { cap_free(capabilities); ROS_ERROR("Could not push CAP_NET_RAW capability to process"); exit(0); } if (-1 == cap_free(capabilities) ) { ROS_ERROR("Could not free capabilites value"); exit(0); } DoublyLinkedListInitialize(&connection_list, CipConnectionObjectListArrayAllocator, CipConnectionObjectListArrayFree); if (kEipStatusError == ConfigureNetworkInterface(device.c_str()) ) { ROS_ERROR("Network interface %s not found.\n", device.c_str()); exit(0); } ConfigureDomainName(); ConfigureHostName(); ConfigureMacAddress(device.c_str()); SetDeviceSerialNumber(DEVICE_SERIAL_NUM); EipUint16 unique_connection_id = rand(); CipStackInit(unique_connection_id); if (kEipStatusOk == NetworkHandlerInitialize() ) { g_end_stack = 0; } else { ROS_ERROR("Error initializing NetworkHandler! Exiting eip_device!"); exit(0); } ros::Publisher eip_data_pub = nh.advertise<eip_device::EipDataAsmOut>("eip_data_fmplc", 1); ros::Publisher eip_config_pub = nh.advertise<eip_device::EipDataAsmCfg>("eip_data_config", 1); ros::Publisher eip_status_pub = nh.advertise<eip_device::EipDeviceStatus>("eip_status", 100); ros::Subscriber eip_unsol_data_sub = nh.subscribe("eip_data_toplc_u", 1, &EipDevice::LoadAsmIn_Callback, &eipDevice); ros::Subscriber eip_sol_data_sub = nh.subscribe("eip_data_toplc_s", 1, &EipDevice::LoadAsmIn_Callback, &eipDevice); ROS_INFO("Starting Process Loop"); int EipStatus = kEipStatusOk; while(ros::ok() && (1 != g_end_stack) && (EipStatus == kEipStatusOk))2 { EipStatus = NetworkHandlerProcessOnce(); if (EipStatus != kEipStatusOk) { ROS_ERROR_STREAM("Error in NetworkHandler loop! Exiting eip_device! -- " << EipStatus ); break; } eipDevice.data_asm_out.raw_plc_data.assign(g_assembly_data096, g_assembly_data096 + OUTPUT_ASSEMBLY_BUFFER_SIZE); eipDevice.data_asm_cfg.raw_plc_data.assign(g_assembly_data097, g_assembly_data097 + CONFIG_ASSEMBLY_BUFFER_SIZE); eip_data_pub.publish(eipDevice.data_asm_out); eip_config_pub.publish(eipDevice.data_asm_cfg); eip_status_pub.publish(eipDevice.device_status); ros::spinOnce(); throttle.sleep(); } ROS_INFO("Finish network handler"); NetworkHandlerFinish(); ROS_INFO("Shutdown CIP Stack"); ShutdownCipStack(); return g_end_stack; } void LeaveStack(int signal) { (void) signal; OPENER_TRACE_STATE("got signal HUP\n"); ROS_INFO("HUP Signal!"); g_end_stack = 1; }
if (-1 == cap_set_flag(capabilities, CAP_EFFECTIVE, 1, capabilies_list, CAP_SET) ) { cap_free(capabilities); ROS_ERROR("Could not set CAP_NET_RAW capability"); exit(0); }
if_condition
[ { "content": "#ifndef EIP_DEVICE_H\n\n#define EIP_DEVICE_H\n\n\n\n#define INPUT_ASSEMBLY_BUFFER_SIZE 32\n\n#define OUTPUT_ASSEMBLY_BUFFER_SIZE 32\n\n#define CONFIG_ASSEMBLY_BUFFER_SIZE 10\n\n#define EXPLICIT_ASSEMBLY_BUFFER_SIZE 32\n\n\n\n#include <iostream>\n\n#include <string>\n\n#include<memory>\n\n\n\nextern \"C\" {\n\n #include \"typedefs.h\"\n\n}\n\n\n\n#include <eip_device/EipDataAsmIn.h>\n\n#include <eip_device/EipDataAsmOut.h>\n\n#include <eip_device/EipDataAsmExp.h>\n\n#include <eip_device/EipDataAsmCfg.h>\n\n#include <eip_device/EipDeviceStatus.h>\n\n\n\n\n\nextern EipUint8 g_assembly_data064[INPUT_ASSEMBLY_BUFFER_SIZE]; /* Input */\n\nextern EipUint8 g_assembly_data096[OUTPUT_ASSEMBLY_BUFFER_SIZE]; /* Output */\n\nextern EipUint8 g_assembly_data097[CONFIG_ASSEMBLY_BUFFER_SIZE]; /* Config */\n\nextern EipUint8 g_assembly_data09A[EXPLICIT_ASSEMBLY_BUFFER_SIZE]; /* Explicit */\n\n\n", "file_path": "eip_device/include/eip_device/eip_device.h", "rank": 0, "score": 19590.087816792595 }, { "content": "class EipDevice\n\n{\n\npublic:\n\n\n\n EipDevice() {device_status.status = -1; device_status.description = \"Initialize\";}\n\n //Callback for loading Input Assembly\n\n void LoadAsmIn_Callback(const eip_device::EipDataAsmIn::ConstPtr& msg);\n\n //Callback for loading Explicit Assembly\n\n void LoadAsmExp_Callback(const eip_device::EipDataAsmExp::ConstPtr& msg);\n\n\n\n eip_device::EipDeviceStatus device_status;\n\n eip_device::EipDataAsmIn data_asm_in;\n\n eip_device::EipDataAsmOut data_asm_out;\n\n eip_device::EipDataAsmCfg data_asm_cfg;\n\n eip_device::EipDataAsmExp data_asm_exp;\n\n};\n\n\n\n#endif // EIP_DEVICE_H\n\n\n\n\n", "file_path": "eip_device/include/eip_device/eip_device.h", "rank": 1, "score": 18452.04814156263 }, { "content": "static const MilliSeconds kOpenerTimerTickInMilliSeconds = 10;\n", "file_path": "eip_device/include/eip_device/opener_user_conf.h", "rank": 2, "score": 13789.784333412235 }, { "content": "#include \"eip_device.h\"\n\n\n\nvoid EipDevice::LoadAsmIn_Callback(const eip_device::EipDataAsmIn::ConstPtr& msg)\n\n{\n\n memcpy(g_assembly_data064, msg->raw_plc_data.data(), INPUT_ASSEMBLY_BUFFER_SIZE);\n\n}\n\n\n\n//Callback for loading Explicit Assembly\n\nvoid EipDevice::LoadAsmExp_Callback(const eip_device::EipDataAsmExp::ConstPtr& msg)\n\n{\n\n memcpy(g_assembly_data09A, msg->raw_plc_data.data(), EXPLICIT_ASSEMBLY_BUFFER_SIZE);\n\n}\n", "file_path": "eip_device/src/eip_device.cpp", "rank": 3, "score": 4642.795410514514 }, { "content": "/*******************************************************************************\n\n * Copyright (c) 2012, Rockwell Automation, Inc.\n\n * All rights reserved.\n\n *\n\n ******************************************************************************/\n\n\n\n#include <string.h>\n\n#include <stdlib.h>\n\n#include <stdbool.h>\n\n\n\nextern \"C\" {\n\n #include \"opener_api.h\"\n\n #include \"appcontype.h\"\n\n #include \"trace.h\"\n\n #include \"cipidentity.h\"\n\n #include \"typedefs.h\"\n\n}\n\n\n\n#include \"eip_device.h\"\n\n\n", "file_path": "eip_device/src/eip_device_application.cpp", "rank": 7, "score": 4492.134429225056 }, { "content": "void CheckIoConnectionEvent(unsigned int output_assembly_id,\n\n unsigned int input_assembly_id,\n\n IoConnectionEvent io_connection_event) {\n\n /* maintain a correct output state according to the connection state*/\n\n\n\n eipDevice.device_status.status = io_connection_event;\n\n switch(io_connection_event)\n\n {\n\n case kIoConnectionEventClosed:\n\n eipDevice.device_status.description = \"Device Closed\";\n\n break;\n\n case kIoConnectionEventOpened:\n\n eipDevice.device_status.description = \"Device Opened\";\n\n break;\n\n case kIoConnectionEventTimedOut:\n\n eipDevice.device_status.description = \"Device Timed Out\";\n\n break;\n\n default:\n\n eipDevice.device_status.description = \"Device Status Not Defined\";\n\n }\n", "file_path": "eip_device/src/eip_device_application.cpp", "rank": 10, "score": 4488.580242040665 }, { "content": " return kEipStatusOk;\n\n}\n\n\n\nEipStatus ResetDeviceToInitialConfiguration(void) {\n\n /*rest the parameters */\n\n g_encapsulation_inactivity_timeout = 120;\n\n /*than perform device reset*/\n\n ResetDevice();\n\n return kEipStatusOk;\n\n}\n\n\n\nvoid *\n\nCipCalloc(size_t number_of_elements,\n\n size_t size_of_element) {\n\n return calloc(number_of_elements, size_of_element);\n\n}\n\n\n\nvoid CipFree(void *data) {\n\n free(data);\n\n}\n", "file_path": "eip_device/src/eip_device_application.cpp", "rank": 12, "score": 4487.281117850847 }, { "content": "#define INPUT_ASSEMBLY_NUM 100 //0x064\n\n#define OUTPUT_ASSEMBLY_NUM 150 //0x096\n\n#define CONFIG_ASSEMBLY_NUM 151 //0x097\n\n#define HEARTBEAT_INPUT_ONLY_ASSEMBLY_NUM 152 //0x098\n\n#define HEARTBEAT_LISTEN_ONLY_ASSEMBLY_NUM 153 //0x099\n\n#define EXPLICT_ASSEMBLY_NUM 154 //0x09A\n\n\n\n/* global variables for demo application (4 assembly data fields) ************/\n\n\n\nextern CipUint g_encapsulation_inactivity_timeout;\n\nextern EipDevice eipDevice;\n\n\n\nEipUint8 g_assembly_data064[32]; /* Input */\n\nEipUint8 g_assembly_data096[32]; /* Output */\n\nEipUint8 g_assembly_data097[10]; /* Config */\n\nEipUint8 g_assembly_data09A[32]; /* Explicit */\n\n\n\nEipStatus ApplicationInitialization(void) {\n\n /* create 3 assembly object instances*/\n\n /*INPUT*/\n", "file_path": "eip_device/src/eip_device_application.cpp", "rank": 13, "score": 4487.093344946303 }, { "content": " return status;\n\n}\n\n\n\nEipBool8 BeforeAssemblyDataSend(CipInstance *pa_pstInstance) {\n\n /*update data to be sent e.g., read inputs of the device */\n\n /*In this sample app we mirror the data from out to inputs on data receive\n\n * therefore we need nothing to do here. Just return true to inform that\n\n * the data is new.\n\n */\n\n\n\n if (pa_pstInstance->instance_number == EXPLICT_ASSEMBLY_NUM) {\n\n /* do something interesting with the existing data\n\n * for the explicit get-data-attribute message */\n\n }\n\n return true;\n\n}\n\n\n\nEipStatus ResetDevice(void) {\n\n /* add reset code here*/\n\n CloseAllConnections();\n", "file_path": "eip_device/src/eip_device_application.cpp", "rank": 14, "score": 4487.031721940215 }, { "content": "\n\nvoid RunIdleChanged(EipUint32 run_idle_value) {\n\n OPENER_TRACE_INFO(\"Run/Idle handler triggered\\n\");\n\n if( (0x0001 & run_idle_value) == 1 ) {\n\n CipIdentitySetExtendedDeviceStatus(kAtLeastOneIoConnectionInRunMode);\n\n } else {\n\n CipIdentitySetExtendedDeviceStatus(\n\n kAtLeastOneIoConnectionEstablishedAllInIdleMode);\n\n }\n\n (void) run_idle_value;\n\n}\n\n\n", "file_path": "eip_device/src/eip_device_application.cpp", "rank": 15, "score": 4486.594774988835 }, { "content": "\n\n (void) output_assembly_id; /* suppress compiler warning */\n\n (void) input_assembly_id; /* suppress compiler warning */\n\n}\n\n\n\nEipStatus AfterAssemblyDataReceived(CipInstance *instance) {\n\n EipStatus status = kEipStatusOk;\n\n\n\n /*handle the data received e.g., update outputs of the device */\n\n switch (instance->instance_number) {\n\n case OUTPUT_ASSEMBLY_NUM : break;\n\n case EXPLICT_ASSEMBLY_NUM: break;\n\n case CONFIG_ASSEMBLY_NUM :\n\n status = kEipStatusOk;\n\n break;\n\n default:\n\n OPENER_TRACE_INFO(\n\n \"Unknown assembly instance ind AfterAssemblyDataReceived\");\n\n break;\n\n }\n", "file_path": "eip_device/src/eip_device_application.cpp", "rank": 17, "score": 4485.946157691847 }, { "content": " CreateAssemblyObject( INPUT_ASSEMBLY_NUM, g_assembly_data064,\n\n sizeof(g_assembly_data064) );\n\n\n\n /*OUTPUT*/\n\n CreateAssemblyObject( OUTPUT_ASSEMBLY_NUM, g_assembly_data096,\n\n sizeof(g_assembly_data096) );\n\n\n\n /*CONFIG*/\n\n CreateAssemblyObject( CONFIG_ASSEMBLY_NUM, g_assembly_data097,\n\n sizeof(g_assembly_data097) );\n\n\n\n /*Heart-beat output assembly for Input only connections */\n\n CreateAssemblyObject(HEARTBEAT_INPUT_ONLY_ASSEMBLY_NUM, NULL, 0);\n\n\n\n /*Heart-beat output assembly for Listen only connections */\n\n CreateAssemblyObject(HEARTBEAT_LISTEN_ONLY_ASSEMBLY_NUM, NULL, 0);\n\n\n\n /* assembly for explicit messaging */\n\n CreateAssemblyObject( EXPLICT_ASSEMBLY_NUM, g_assembly_data09A,\n\n sizeof(g_assembly_data09A) );\n", "file_path": "eip_device/src/eip_device_application.cpp", "rank": 18, "score": 4485.463698002604 }, { "content": "\n\n ConfigureExclusiveOwnerConnectionPoint(0, OUTPUT_ASSEMBLY_NUM,\n\n INPUT_ASSEMBLY_NUM,\n\n CONFIG_ASSEMBLY_NUM);\n\n ConfigureInputOnlyConnectionPoint(0,\n\n HEARTBEAT_INPUT_ONLY_ASSEMBLY_NUM,\n\n INPUT_ASSEMBLY_NUM,\n\n CONFIG_ASSEMBLY_NUM);\n\n ConfigureListenOnlyConnectionPoint(0,\n\n HEARTBEAT_LISTEN_ONLY_ASSEMBLY_NUM,\n\n INPUT_ASSEMBLY_NUM,\n\n CONFIG_ASSEMBLY_NUM);\n\n\n\n return kEipStatusOk;\n\n}\n\n\n\nvoid HandleApplication(void) {\n\n /* check if application needs to trigger an connection */\n\n}\n\n\n", "file_path": "eip_device/src/eip_device_application.cpp", "rank": 19, "score": 4485.4479977582005 }, { "content": "# ROS Ethernet/IP Device\n\n[![support level: community](https://img.shields.io/badge/support%20level-community-lightgray.png)](http://rosindustrial.org/news/2016/10/7/better-supporting-a-growing-ros-industrial-software-platform)\n\n## ROS Driver for OpENer package\n\ngit clone --recursive [email protected]:wpmccormick/eip_device.git\n", "file_path": "README.md", "rank": 22, "score": 2452.005597990852 } ]
C++
src/Plugins/TundraLogic/Client.cpp
realXtend/tundra-urho3d
436d41c3e3dd1a9b629703ee76fd0ef2ee212ef8
#include "StableHeaders.h" #include "Client.h" #include "UserConnectedResponseData.h" #include "TundraLogic.h" #include "KristalliProtocol.h" #include "SyncManager.h" #include "SyncState.h" #include "MsgLogin.h" #include "MsgLoginReply.h" #include "Framework.h" #include "Scene.h" #include "SceneAPI.h" #include "AssetAPI.h" #include "LoggingFunctions.h" #include "TundraLogicUtils.h" #include "TundraMessages.h" #include "Placeable.h" #include "UrhoRenderer.h" #include <Urho3D/Resource/XMLFile.h> #include <Urho3D/Resource/XMLElement.h> #include <Urho3D/Core/StringUtils.h> using namespace kNet; namespace Tundra { Client::Client(TundraLogic* owner) : Object(owner->GetContext()), owner_(owner), framework_(owner->GetFramework()), loginstate_(NotConnected), reconnect_(false), client_id_(0) { serverUserConnection_ = KNetUserConnectionPtr(new KNetUserConnection(context_)); serverUserConnection_->properties["authenticated"] = true; serverUserConnection_->syncState = SharedPtr<SceneSyncState>(new SceneSyncState(0, false)); } Client::~Client() { } void Client::Update(float) { if (!owner_->IsServer()) CheckLogin(); } void Client::Login(const String& address, unsigned short port, const String& username, const String& password, const String &protocol) { if (IsConnected()) DoLogout(); SetLoginProperty("username", username); SetLoginProperty("password", password); String p = protocol.Trimmed().ToLower(); kNet::SocketTransportLayer transportLayer = kNet::StringToSocketTransportLayer(p.CString()); if (transportLayer == kNet::InvalidTransportLayer && !p.Empty()) { LogError("Client::Login: Cannot log to server using unrecognized protocol: " + p); return; } Login(address, port, transportLayer); } void Client::Login(const String& address, unsigned short port, kNet::SocketTransportLayer protocol) { if (owner_->IsServer()) { LogError("Already running a server, cannot login to a world as a client"); return; } reconnect_ = false; KristalliProtocol *kristalli = owner_->KristalliProtocol(); if (protocol == kNet::InvalidTransportLayer) { LogInfo("Client::Login: No protocol specified, using the default value."); protocol = kristalli->defaultTransport; } SetLoginProperty("protocol", String(SocketTransportLayerToString(protocol).c_str()).ToLower()); SetLoginProperty("address", address); SetLoginProperty("port", port); SetLoginProperty("client-version", "2.5.4.1"); SetLoginProperty("client-name", "Name"); SetLoginProperty("client-organization", "Org"); kristalli->NetworkMessageReceived.Connect(this, &Client::HandleKristalliMessage); kristalli->ConnectionAttemptFailed.Connect(this, &Client::OnConnectionAttemptFailed); kristalli->Connect(address.CString(), port, protocol); loginstate_ = ConnectionPending; client_id_ = 0; } void Client::Logout() { DelayedLogout(); } void Client::DelayedLogout() { DoLogout(false); } void Client::DoLogout(bool fail) { if (loginstate_ != NotConnected) { if (MessageConnection()) { owner_->KristalliProtocol()->Disconnect(); LogInfo("Disconnected"); } serverUserConnection_->connection = 0; loginstate_ = NotConnected; client_id_ = 0; framework_->Scene()->RemoveScene("TundraClient"); framework_->Asset()->ForgetAllAssets(); Disconnected.Emit(); } if (fail) { String failreason = LoginProperty("LoginFailed").GetString(); LoginFailed.Emit(failreason); } else { properties_.Clear(); } SharedPtr<KristalliProtocol> kristalli = owner_->KristalliProtocol(); kristalli->NetworkMessageReceived.Disconnect(this, &Client::HandleKristalliMessage); kristalli->ConnectionAttemptFailed.Disconnect(this, &Client::OnConnectionAttemptFailed); LogInfo("Client logged out."); } bool Client::IsConnected() const { return loginstate_ == LoggedIn; } void Client::SetLoginProperty(String key, Urho3D::Variant value) { key = key.Trimmed(); if (value.IsEmpty()) properties_.Erase(properties_.Find(key)); else properties_[key] = value; } Urho3D::Variant Client::LoginProperty(String key) const { key = key.Trimmed(); auto i = properties_.Find(key); if (i != properties_.End()) return i.ptr_; else return Urho3D::Variant(); } bool Client::HasLoginProperty(String key) const { auto i = properties_.Find(key); if (i == properties_.End()) return false; else return !i->second_.IsEmpty(); } String Client::LoginPropertiesAsXml() const { Urho3D::XMLFile xml(owner_->GetContext()); Urho3D::XMLElement rootElem = xml.CreateRoot("login"); for(auto iter = properties_.Begin(); iter != properties_.End(); ++iter) { Urho3D::XMLElement element = rootElem.CreateChild(iter->first_); element.SetAttribute("value", iter->second_.ToString()); } return xml.ToString(); } void Client::CheckLogin() { kNet::MessageConnection* connection = MessageConnection(); switch(loginstate_) { case ConnectionPending: if (connection && connection->GetConnectionState() == kNet::ConnectionOK) { loginstate_ = ConnectionEstablished; MsgLogin msg; AboutToConnect.Emit(); msg.loginData = StringToBuffer(LoginPropertiesAsXml()); DataSerializer ds(msg.Size() + 4); msg.SerializeTo(ds); ds.AddVLE<kNet::VLE8_16_32>(cHighestSupportedProtocolVersion); connection->SendMessage(msg.messageID, msg.reliable, msg.inOrder, msg.priority, 0, ds.GetData(), ds.BytesFilled()); } break; case LoggedIn: if (!connection || connection->GetConnectionState() != kNet::ConnectionOK) loginstate_ = ConnectionPending; break; } } kNet::MessageConnection* Client::MessageConnection() { return owner_->KristalliProtocol()->MessageConnection(); } KNetUserConnectionPtr Client::ServerUserConnection() const { return serverUserConnection_; } void Client::OnConnectionAttemptFailed() { String address = LoginProperty("address").GetString(); String port = LoginProperty("port").GetString(); String protocol = LoginProperty("protocol").GetString(); String failReason = "Could not connect to host"; if (!address.Empty()) { failReason.Append(" " + address); if (!port.Empty()) failReason.Append(":" + port); if (!protocol.Empty()) failReason.Append(" with " + protocol.ToUpper()); } SetLoginProperty("LoginFailed", failReason); DoLogout(true); } void Client::HandleKristalliMessage(kNet::MessageConnection* source, kNet::packet_id_t packetId, kNet::message_id_t messageId, const char* data, size_t numBytes) { if (source != MessageConnection()) { LogWarning("Client: dropping message " + String(messageId) + " from unknown source"); return; } switch(messageId) { case MsgLoginReply::messageID: { HandleLoginReply(source, data, numBytes); } break; } NetworkMessageReceived.Emit(packetId, messageId, data, numBytes); serverUserConnection_->EmitNetworkMessageReceived(packetId, messageId, data, numBytes); } void Client::HandleLoginReply(kNet::MessageConnection* , const char *data, size_t numBytes) { DataDeserializer dd(data, numBytes); MsgLoginReply msg; msg.DeserializeFrom(dd); serverUserConnection_->protocolVersion = ProtocolOriginal; if (dd.BytesLeft()) serverUserConnection_->protocolVersion = (NetworkProtocolVersion)dd.ReadVLE<kNet::VLE8_16_32>(); if (msg.success) { loginstate_ = LoggedIn; client_id_ = msg.userID; LogInfo("Logged in successfully"); if (!reconnect_) { serverUserConnection_->connection = MessageConnection(); ScenePtr scene = framework_->Scene()->CreateScene("TundraClient", true, false); owner_->SyncManager()->RegisterToScene(scene); UserConnectedResponseData responseData; if (msg.loginReplyData.size() > 0) { String responseDataStr((const char *)&msg.loginReplyData[0], (int)msg.loginReplyData.size()); responseData.responseDataXml = new Urho3D::XMLFile(context_); responseData.responseDataXml->FromString(responseDataStr); } Connected.Emit(&responseData); } else { ScenePtr scene = framework_->Scene()->SceneByName("TundraClient"); if (scene) scene->RemoveAllEntities(true, AttributeChange::LocalOnly); } reconnect_ = true; } else { String response((const char *)&msg.loginReplyData[0], (int)msg.loginReplyData.size()); if (!response.Empty()) SetLoginProperty("LoginFailed", response); DoLogout(true); } } void Client::HandleClientJoined(kNet::MessageConnection* , const MsgClientJoined& ) { } void Client::HandleClientLeft(kNet::MessageConnection* , const MsgClientLeft& ) { } }
#include "StableHeaders.h" #include "Client.h" #include "UserConnectedResponseData.h" #include "TundraLogic.h" #include "KristalliProtocol.h" #include "SyncManager.h" #include "SyncState.h" #include "MsgLogin.h" #include "MsgLoginReply.h" #include "Framework.h" #include "Scene.h" #include "SceneAPI.h" #include "AssetAPI.h" #include "LoggingFunctions.h" #include "TundraLogicUtils.h" #include "TundraMessages.h" #include "Placeable.h" #include "UrhoRenderer.h" #include <Urho3D/Resource/XMLFile.h> #include <Urho3D/Resource/XMLElement.h> #include <Urho3D/Core/StringUtils.h> using namespace kNet; namespace Tundra { Client::Client(TundraLogic* owner) : Object(owner->GetContext()), owner_(owner), framework_(owner->GetFramework()), loginstate_(NotConnected), reconnect_(false), client_id_(0) { serverUserConnection_ = KNetUserConnectionPtr(new KNetUserConnection(context_)); serverUserConnection_->properties["authenticated"] = true; serverUserConnection_->syncState = SharedPtr<SceneSyncState>(new SceneSyncState(0, false)); } Client::~Client() { } void Client::Update(float) { if (!owner_->IsServer()) CheckLogin(); } void Client::Login(const String& address, unsigned short port, const String& username, const String& password, const String &protocol) { if (IsConnected()) DoLogout(); SetLoginProperty("username", username); SetLoginProperty("password", password); String p = protocol.Trimmed().ToLower(); kNet::SocketTransportLayer transportLayer = kNet::StringToSocketTransportLayer(p.CString()); if (transportLayer == kNet::InvalidTransportLayer && !p.Empty()) { LogError("Client::Login: Cannot log to server using unrecognized protocol: " + p); return; } Login(address, port, transportLayer); } void Client::Login(const String& address, unsigned short port, kNet::SocketTransportLayer protocol) { if (owner_->IsServer()) { LogError("Already running a server, cannot login to a world as a client"); return; } reconnect_ = false; KristalliProtocol *kristalli = owner_->KristalliProtocol();
SetLoginProperty("protocol", String(SocketTransportLayerToString(protocol).c_str()).ToLower()); SetLoginProperty("address", address); SetLoginProperty("port", port); SetLoginProperty("client-version", "2.5.4.1"); SetLoginProperty("client-name", "Name"); SetLoginProperty("client-organization", "Org"); kristalli->NetworkMessageReceived.Connect(this, &Client::HandleKristalliMessage); kristalli->ConnectionAttemptFailed.Connect(this, &Client::OnConnectionAttemptFailed); kristalli->Connect(address.CString(), port, protocol); loginstate_ = ConnectionPending; client_id_ = 0; } void Client::Logout() { DelayedLogout(); } void Client::DelayedLogout() { DoLogout(false); } void Client::DoLogout(bool fail) { if (loginstate_ != NotConnected) { if (MessageConnection()) { owner_->KristalliProtocol()->Disconnect(); LogInfo("Disconnected"); } serverUserConnection_->connection = 0; loginstate_ = NotConnected; client_id_ = 0; framework_->Scene()->RemoveScene("TundraClient"); framework_->Asset()->ForgetAllAssets(); Disconnected.Emit(); } if (fail) { String failreason = LoginProperty("LoginFailed").GetString(); LoginFailed.Emit(failreason); } else { properties_.Clear(); } SharedPtr<KristalliProtocol> kristalli = owner_->KristalliProtocol(); kristalli->NetworkMessageReceived.Disconnect(this, &Client::HandleKristalliMessage); kristalli->ConnectionAttemptFailed.Disconnect(this, &Client::OnConnectionAttemptFailed); LogInfo("Client logged out."); } bool Client::IsConnected() const { return loginstate_ == LoggedIn; } void Client::SetLoginProperty(String key, Urho3D::Variant value) { key = key.Trimmed(); if (value.IsEmpty()) properties_.Erase(properties_.Find(key)); else properties_[key] = value; } Urho3D::Variant Client::LoginProperty(String key) const { key = key.Trimmed(); auto i = properties_.Find(key); if (i != properties_.End()) return i.ptr_; else return Urho3D::Variant(); } bool Client::HasLoginProperty(String key) const { auto i = properties_.Find(key); if (i == properties_.End()) return false; else return !i->second_.IsEmpty(); } String Client::LoginPropertiesAsXml() const { Urho3D::XMLFile xml(owner_->GetContext()); Urho3D::XMLElement rootElem = xml.CreateRoot("login"); for(auto iter = properties_.Begin(); iter != properties_.End(); ++iter) { Urho3D::XMLElement element = rootElem.CreateChild(iter->first_); element.SetAttribute("value", iter->second_.ToString()); } return xml.ToString(); } void Client::CheckLogin() { kNet::MessageConnection* connection = MessageConnection(); switch(loginstate_) { case ConnectionPending: if (connection && connection->GetConnectionState() == kNet::ConnectionOK) { loginstate_ = ConnectionEstablished; MsgLogin msg; AboutToConnect.Emit(); msg.loginData = StringToBuffer(LoginPropertiesAsXml()); DataSerializer ds(msg.Size() + 4); msg.SerializeTo(ds); ds.AddVLE<kNet::VLE8_16_32>(cHighestSupportedProtocolVersion); connection->SendMessage(msg.messageID, msg.reliable, msg.inOrder, msg.priority, 0, ds.GetData(), ds.BytesFilled()); } break; case LoggedIn: if (!connection || connection->GetConnectionState() != kNet::ConnectionOK) loginstate_ = ConnectionPending; break; } } kNet::MessageConnection* Client::MessageConnection() { return owner_->KristalliProtocol()->MessageConnection(); } KNetUserConnectionPtr Client::ServerUserConnection() const { return serverUserConnection_; } void Client::OnConnectionAttemptFailed() { String address = LoginProperty("address").GetString(); String port = LoginProperty("port").GetString(); String protocol = LoginProperty("protocol").GetString(); String failReason = "Could not connect to host"; if (!address.Empty()) { failReason.Append(" " + address); if (!port.Empty()) failReason.Append(":" + port); if (!protocol.Empty()) failReason.Append(" with " + protocol.ToUpper()); } SetLoginProperty("LoginFailed", failReason); DoLogout(true); } void Client::HandleKristalliMessage(kNet::MessageConnection* source, kNet::packet_id_t packetId, kNet::message_id_t messageId, const char* data, size_t numBytes) { if (source != MessageConnection()) { LogWarning("Client: dropping message " + String(messageId) + " from unknown source"); return; } switch(messageId) { case MsgLoginReply::messageID: { HandleLoginReply(source, data, numBytes); } break; } NetworkMessageReceived.Emit(packetId, messageId, data, numBytes); serverUserConnection_->EmitNetworkMessageReceived(packetId, messageId, data, numBytes); } void Client::HandleLoginReply(kNet::MessageConnection* , const char *data, size_t numBytes) { DataDeserializer dd(data, numBytes); MsgLoginReply msg; msg.DeserializeFrom(dd); serverUserConnection_->protocolVersion = ProtocolOriginal; if (dd.BytesLeft()) serverUserConnection_->protocolVersion = (NetworkProtocolVersion)dd.ReadVLE<kNet::VLE8_16_32>(); if (msg.success) { loginstate_ = LoggedIn; client_id_ = msg.userID; LogInfo("Logged in successfully"); if (!reconnect_) { serverUserConnection_->connection = MessageConnection(); ScenePtr scene = framework_->Scene()->CreateScene("TundraClient", true, false); owner_->SyncManager()->RegisterToScene(scene); UserConnectedResponseData responseData; if (msg.loginReplyData.size() > 0) { String responseDataStr((const char *)&msg.loginReplyData[0], (int)msg.loginReplyData.size()); responseData.responseDataXml = new Urho3D::XMLFile(context_); responseData.responseDataXml->FromString(responseDataStr); } Connected.Emit(&responseData); } else { ScenePtr scene = framework_->Scene()->SceneByName("TundraClient"); if (scene) scene->RemoveAllEntities(true, AttributeChange::LocalOnly); } reconnect_ = true; } else { String response((const char *)&msg.loginReplyData[0], (int)msg.loginReplyData.size()); if (!response.Empty()) SetLoginProperty("LoginFailed", response); DoLogout(true); } } void Client::HandleClientJoined(kNet::MessageConnection* , const MsgClientJoined& ) { } void Client::HandleClientLeft(kNet::MessageConnection* , const MsgClientLeft& ) { } }
if (protocol == kNet::InvalidTransportLayer) { LogInfo("Client::Login: No protocol specified, using the default value."); protocol = kristalli->defaultTransport; }
if_condition
[ { "content": "/// Implements kNet protocol -based server and client functionality.\n\nclass TUNDRALOGIC_API KristalliProtocol : public Object, public kNet::IMessageHandler, public kNet::INetworkServerListener\n\n{\n\n URHO3D_OBJECT(KristalliProtocol, Object);\n\n\n\npublic:\n\n KristalliProtocol(TundraLogic* owner);\n\n ~KristalliProtocol();\n\n\n\n void Load();\n\n void Initialize();\n\n void Uninitialize();\n\n void Update(float frametime);\n\n\n\n /// Connects to the Kristalli server at the given address.\n\n void Connect(const char *ip, unsigned short port, kNet::SocketTransportLayer transport);\n\n\n\n void Disconnect();\n\n\n\n /// Starts a Kristalli server at the given port/transport.\n\n /// @return true if successful\n", "file_path": "src/Plugins/TundraLogic/KristalliProtocol.h", "rank": 0, "score": 237129.3729286024 }, { "content": " class KristalliProtocol;\n", "file_path": "src/Plugins/TundraLogic/TundraLogicFwd.h", "rank": 1, "score": 208685.27150089756 }, { "content": "\n\n /// Amount of retries remaining for reconnection. Is low for the initial connection, higher for reconnection\n\n int reconnectAttempts;\n\n\n\n void PerformConnection();\n\n \n\n /// If true, the connection attempt we've started has not yet been established, but is waiting\n\n /// for a transition to OK state. When this happens, the MsgLogin message is sent.\n\n bool connectionPending;\n\n \n\n /// This variable stores the server ip address we are desiring to connect to.\n\n /// This is used to remember where we need to reconnect in case the connection goes down.\n\n std::string serverIp;\n\n /// Store the port number we are desiring to connect to. Used for reconnecting\n\n unsigned short serverPort;\n\n /// Store the transport type. Used for reconnecting\n\n kNet::SocketTransportLayer serverTransport;\n\n \n\n TundraLogic* owner;\n\n kNet::Network network;\n\n Ptr(kNet::MessageConnection) serverConnection;\n\n kNet::NetworkServer *server;\n\n \n\n /// Users that are connected to server\n\n UserConnectionList connections;\n\n};\n\n\n\n}\n", "file_path": "src/Plugins/TundraLogic/KristalliProtocol.h", "rank": 2, "score": 167609.8797440909 }, { "content": " bool StartServer(unsigned short port, kNet::SocketTransportLayer transport);\n\n \n\n /// Stops Kristalli server\n\n void StopServer();\n\n \n\n /// Invoked by the Network library for each received network message.\n\n void HandleMessage(kNet::MessageConnection *source, kNet::packet_id_t packetId, kNet::message_id_t id, const char *data, size_t numBytes);\n\n\n\n /// Invoked by the Network library for each new connection\n\n void NewConnectionEstablished(kNet::MessageConnection* source);\n\n \n\n /// Invoked by the Network library for disconnected client\n\n void ClientDisconnected(kNet::MessageConnection* source);\n\n\n\n bool Connected() const;\n\n\n\n /// Return message connection, for use by other modules (null if no connection made)\n\n kNet::MessageConnection *MessageConnection() { return serverConnection.ptr(); }\n\n\n\n /// Return server, for use by other modules (null if not running)\n", "file_path": "src/Plugins/TundraLogic/KristalliProtocol.h", "rank": 3, "score": 167607.37420297606 }, { "content": "// For conditions of distribution and use, see copyright notice in LICENSE\n\n\n\n#pragma once\n\n\n\n#include <kNet/IMessageHandler.h>\n\n#include <kNet/INetworkServerListener.h>\n\n#include <kNet/Network.h>\n\n\n\n#include \"TundraLogicApi.h\"\n\n#include \"TundraLogicFwd.h\"\n\n#include \"Signals.h\"\n\n#include \"UserConnection.h\"\n\n\n\n#include <Urho3D/Core/Object.h>\n\n#include <Urho3D/Container/List.h>\n\n\n\n\n\nnamespace Tundra\n\n{\n\n\n\n/// Implements kNet protocol -based server and client functionality.\n", "file_path": "src/Plugins/TundraLogic/KristalliProtocol.h", "rank": 4, "score": 167600.33755771705 }, { "content": " kNet::NetworkServer* NetworkServer() const { return server; }\n\n\n\n kNet::Network *Network() { return &network; }\n\n\n\n /// Return whether we are a server\n\n bool IsServer() const { return server != 0; }\n\n \n\n /// Returns all user connections for a server\n\n UserConnectionList& UserConnections() { return connections; }\n\n\n\n /// Gets user by message connection. Returns null if no such connection\n\n UserConnectionPtr UserConnectionBySource(kNet::MessageConnection* source) const;\n\n UserConnectionPtr UserConnectionById(u32 id) const; /**< @overload @param id Connection ID. */\n\n\n\n /// What trasport layer to use. Read on startup from \"--protocol <udp|tcp>\". Defaults to UDP if no start param was given.\n\n kNet::SocketTransportLayer defaultTransport;\n\n\n\n /// Allocate a connection ID for new connection\n\n u32 AllocateNewConnectionID() const;\n\n\n", "file_path": "src/Plugins/TundraLogic/KristalliProtocol.h", "rank": 5, "score": 167583.15146526982 }, { "content": " void OpenKNetLogWindow();\n\n\n\n // signals\n\n\n\n /// Triggered whenever a new message is received rom the network.\n\n //void NetworkMessageReceived(kNet::MessageConnection *source, kNet::packet_id_t packetId, kNet::message_id_t messageId, const char *data, size_t numBytes);\n\n Signal5<kNet::MessageConnection* ARG(source), kNet::packet_id_t, kNet::message_id_t ARG(messageId), const char* ARG(data), size_t ARG(numBytes)> NetworkMessageReceived;\n\n\n\n /// Triggered on the server side when a new user connects.\n\n Signal1<UserConnection* ARG(connection)> ClientConnectedEvent;\n\n\n\n /// Triggered on the server side when a user disconnects.\n\n Signal1<UserConnection* ARG(connection)> ClientDisconnectedEvent;\n\n\n\n /// Triggered on the client side when a server connection attempt has failed.\n\n Signal0<void> ConnectionAttemptFailed;\n\n\n\nprivate:\n\n /// This timer tracks when we perform the next reconnection attempt when the connection is lost.\n\n kNet::PolledTimer reconnectTimer;\n", "file_path": "src/Plugins/TundraLogic/KristalliProtocol.h", "rank": 6, "score": 167582.01449717185 }, { "content": "class SignalWrapper_Client_LoginFailed\n\n{\n\npublic:\n\n SignalWrapper_Client_LoginFailed(Object* owner, Signal1< const String &>* signal) :\n\n owner_(owner),\n\n signal_(signal)\n\n {\n\n }\n\n\n\n WeakPtr<Object> owner_;\n\n Signal1< const String &>* signal_;\n\n};\n\n\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ClientBindings.cpp", "rank": 7, "score": 165291.1453316701 }, { "content": "namespace Tundra\n\n{\n\n\n\n/// Available log levels. Each log level includes all the output from the levels above it.\n\nenum LogLevel\n\n{\n\n LogLevelDebug = 0, // Urho3D::LOG_DEBUG\n\n LogLevelInfo = 1, // Urho3D::LOG_INFO\n\n LogLevelWarning = 2, // Urho3D::LOG_WARNING\n\n LogLevelError = 3, // Urho3D::LOG_ERROR\n\n LogLevelNone = 4 // Urho3D::LOG_NONE\n\n};\n\n\n\nnamespace Detail // Hide from Tundra namespace\n\n{\n\n#ifdef WIN32\n\n const String Newline = \"\\r\\n\";\n\n#else\n\n const String Newline = \"\\n\";\n\n#endif\n\n}\n\n\n\n/// Outputs a message to the log to the given channel (if @c level is enabled) to both stdout and ConsoleAPI.\n\n/** On Windows, yellow and red text colors are used for warning and error prints. */\n\nvoid TUNDRACORE_API PrintLogMessage(LogLevel level, const String &str);\n\n\n\n/// Returns true if the given log level is enabled.\n\nbool TUNDRACORE_API IsLogLevelEnabled(LogLevel level);\n\n\n\n/// Outputs a string to the stdout.\n\nvoid TUNDRACORE_API PrintRaw(const String &str);\n\n\n\n/// Outputs an error message to the log (if LogLevelError is enabled), both stdout and ConsoleAPI, with \"Error: \" prefix and with newline appended.\n\n/** On Windows, red text color is used for the stdout print. */\n\nstatic inline void LogError(const String &msg) { if (IsLogLevelEnabled(LogLevelError)) PrintLogMessage(LogLevelError, \"Error: \" + msg + Detail::Newline);}\n\n\n\n/// Outputs a warning message to the log (if LogLevelWarning is enabled), both stdout and ConsoleAPI, with \"Warning: \" prefix and with newline appended.\n\n/** On Windows, yellow text color is used for the stdout print. */\n\nstatic inline void LogWarning(const String &msg) { if (IsLogLevelEnabled(LogLevelWarning)) PrintLogMessage(LogLevelWarning, \"Warning: \" + msg + Detail::Newline);}\n\n\n\n/// Outputs an information message to the log (if LogLevelInfo is enabled), both stdout and ConsoleAPI, with newline appended.\n\nstatic inline void LogInfo(const String &msg) { if (IsLogLevelEnabled(LogLevelInfo)) PrintLogMessage(LogLevelInfo, msg + Detail::Newline);}\n\n\n\n/// Outputs a debug message to the log (if LogLevelDebug is enabled), both stdout and ConsoleAPI, with \"Debug: \" prefix and with newline appended.\n\nstatic inline void LogDebug(const String &msg) { if (IsLogLevelEnabled(LogLevelDebug)) PrintLogMessage(LogLevelDebug, \"Debug: \" + msg + Detail::Newline);}\n\n\n\nstatic inline void LogError(const std::string &msg) /**< @overload */ { if (IsLogLevelEnabled(LogLevelError)) PrintLogMessage(LogLevelError, \"Error: \" + String(msg.c_str()) + Detail::Newline); }\n\nstatic inline void LogWarning(const std::string &msg) /**< @overload */ { if (IsLogLevelEnabled(LogLevelWarning)) PrintLogMessage(LogLevelWarning, \"Warning: \" + String(msg.c_str()) + Detail::Newline); }\n\nstatic inline void LogInfo(const std::string &msg) /**< @overload */ { if (IsLogLevelEnabled(LogLevelInfo)) PrintLogMessage(LogLevelInfo, String(msg.c_str()) + Detail::Newline); }\n\nstatic inline void LogDebug(const std::string &msg) /**< @overload */ { if (IsLogLevelEnabled(LogLevelDebug)) PrintLogMessage(LogLevelDebug, \"Debug: \"+ String(msg.c_str()) + Detail::Newline); }\n\n\n\nstatic inline void LogError(const char *msg) /**< @overload */ { if (IsLogLevelEnabled(LogLevelError)) PrintLogMessage(LogLevelError, \"Error: \" + String(msg) + Detail::Newline); }\n\nstatic inline void LogWarning(const char *msg) /**< @overload */ { if (IsLogLevelEnabled(LogLevelWarning)) PrintLogMessage(LogLevelWarning, \"Warning: \" + String(msg) + Detail::Newline); }\n\nstatic inline void LogInfo(const char *msg) /**< @overload */ { if (IsLogLevelEnabled(LogLevelInfo)) PrintLogMessage(LogLevelInfo, String(msg) + Detail::Newline); }\n\nstatic inline void LogDebug(const char *msg) /**< @overload */ { if (IsLogLevelEnabled(LogLevelDebug)) PrintLogMessage(LogLevelDebug, \"Debug: \" + String(msg) + Detail::Newline); }\n\n\n\nnamespace Detail // Hide from Tundra namespace\n\n{\n\n static inline void LogFormatted(LogLevel level, const String &prefix, const char* formatString, va_list args)\n\n {\n\n String msg;\n\n if (!prefix.Empty())\n\n msg.Append(prefix);\n\n msg.AppendWithFormatArgs(formatString, args);\n\n va_end(args);\n\n msg.Append(Newline);\n\n PrintLogMessage(level, msg);\n\n }\n\n}\n\n\n\n/// Log formatted error. @see http://www.cplusplus.com/reference/cstdio/printf/.\n\nstatic inline void LogErrorF(const char* formatString, ...) { if (IsLogLevelEnabled(LogLevelError)) { va_list a; va_start(a, formatString); Detail::LogFormatted(LogLevelError, \"\", formatString, a); } }\n\n/// Log formatted warning. @see http://www.cplusplus.com/reference/cstdio/printf/.\n\nstatic inline void LogWarningF(const char* formatString, ...) { if (IsLogLevelEnabled(LogLevelWarning)) { va_list a; va_start(a, formatString); Detail::LogFormatted(LogLevelWarning, \"\", formatString, a); } }\n\n/// Log formatted info line. @see http://www.cplusplus.com/reference/cstdio/printf/.\n\nstatic inline void LogInfoF(const char* formatString, ...) { if (IsLogLevelEnabled(LogLevelInfo)) { va_list a; va_start(a, formatString); Detail::LogFormatted(LogLevelInfo, \"\", formatString, a); } }\n\n/// Log formatted debug line. @see http://www.cplusplus.com/reference/cstdio/printf/.\n\nstatic inline void LogDebugF(const char* formatString, ...) { if (IsLogLevelEnabled(LogLevelDebug)) { va_list a; va_start(a, formatString); Detail::LogFormatted(LogLevelDebug, \"\", formatString, a); } }\n\n\n\n/// Simple logger that provide a prefix 'name' to each line.\n\nstruct Logger\n\n{\n\n /// Creates new Logger with name.\n\n Logger(const String &name) : prefix(\"[\" + name + \"] \") {}\n\n\n\n void Error(const String &msg) const { if (IsLogLevelEnabled(LogLevelError)) LogError(prefix + msg); }\n\n void Warning(const String &msg) const { if (IsLogLevelEnabled(LogLevelWarning)) LogWarning(prefix + msg); }\n\n void Info(const String &msg) const { if (IsLogLevelEnabled(LogLevelInfo)) LogInfo(prefix + msg); }\n\n void Debug(const String &msg) const { if (IsLogLevelEnabled(LogLevelDebug)) LogDebug(prefix + msg); }\n\n\n\n void ErrorF(const char* formatString, ...) const { if (IsLogLevelEnabled(LogLevelError)) { va_list a; va_start(a, formatString); Detail::LogFormatted(LogLevelError, prefix, formatString, a); } }\n\n void WarningF(const char* formatString, ...) const { if (IsLogLevelEnabled(LogLevelWarning)) { va_list a; va_start(a, formatString); Detail::LogFormatted(LogLevelWarning, prefix, formatString, a); } }\n\n void InfoF(const char* formatString, ...) const { if (IsLogLevelEnabled(LogLevelInfo)) { va_list a; va_start(a, formatString); Detail::LogFormatted(LogLevelInfo, prefix, formatString, a); } }\n\n void DebugF(const char* formatString, ...) const { if (IsLogLevelEnabled(LogLevelDebug)) { va_list a; va_start(a, formatString); Detail::LogFormatted(LogLevelDebug, prefix, formatString, a); } }\n\n\n\n String prefix;\n", "file_path": "src/TundraCore/Framework/LoggingFunctions.h", "rank": 8, "score": 163506.7801723234 }, { "content": " \n\n if (Connected())\n\n serverConnection->Disconnect();\n\n}\n\n\n\nbool KristalliProtocol::StartServer(unsigned short port, kNet::SocketTransportLayer transport)\n\n{\n\n StopServer();\n\n \n\n const bool allowAddressReuse = true;\n\n server = network.StartServer(port, transport, this, allowAddressReuse);\n\n if (!server)\n\n {\n\n const String error = \"Failed to start server on port \" + String(port) + \".\";\n\n LogError(error);\n\n LogError(\"Please make sure that the port is free and not used by another application.\");\n\n return false;\n\n }\n\n\n\n Framework* framework = owner->GetFramework();\n", "file_path": "src/Plugins/TundraLogic/KristalliProtocol.cpp", "rank": 9, "score": 163493.63370001144 }, { "content": "void KristalliProtocol::Connect(const char *ip, unsigned short port, kNet::SocketTransportLayer transport)\n\n{\n\n if (Connected() && serverConnection->RemoteEndPoint().IPToString() != serverIp)\n\n Disconnect();\n\n \n\n serverIp = ip;\n\n serverPort = port;\n\n serverTransport = transport;\n\n reconnectAttempts = cInitialAttempts; // Initial attempts when establishing connection\n\n \n\n if (!Connected())\n\n PerformConnection(); // Start performing a connection attempt to the desired address/port/transport\n\n}\n\n\n\nvoid KristalliProtocol::PerformConnection()\n\n{\n\n if (serverConnection) // Make sure connection is fully closed before doing a potential reconnection.\n\n serverConnection->Close();\n\n\n\n // Connect to the server.\n", "file_path": "src/Plugins/TundraLogic/KristalliProtocol.cpp", "rank": 10, "score": 163478.74563583327 }, { "content": "\n\nKristalliProtocol::KristalliProtocol(TundraLogic* owner) :\n\n Object(owner->GetContext()),\n\n owner(owner),\n\n server(0),\n\n serverPort(0),\n\n serverConnection(0),\n\n connectionPending(false),\n\n reconnectAttempts(0)\n\n{\n\n}\n\n\n\nKristalliProtocol::~KristalliProtocol()\n\n{\n\n Disconnect();\n\n}\n\n\n\nvoid KristalliProtocol::Load()\n\n{\n\n Framework* framework = owner->GetFramework();\n", "file_path": "src/Plugins/TundraLogic/KristalliProtocol.cpp", "rank": 11, "score": 163477.85754451287 }, { "content": " \n\n std::cout << std::endl;\n\n LogInfo(\"Server started\");\n\n LogInfo(\"* Port : \" + String(port));\n\n LogInfo(\"* Protocol : \" + SocketTransportLayerToString(transport));\n\n LogInfo(\"* Headless : \" + String(framework->IsHeadless()));\n\n return true;\n\n}\n\n\n\nvoid KristalliProtocol::StopServer()\n\n{\n\n if (server)\n\n {\n\n network.StopServer();\n\n // We may have connections registered by other server modules. Only clear native connections\n\n for(auto iter = connections.Begin(); iter != connections.End();)\n\n {\n\n if (dynamic_cast<KNetUserConnection*>(iter->Get()))\n\n iter = connections.Erase(iter);\n\n else\n", "file_path": "src/Plugins/TundraLogic/KristalliProtocol.cpp", "rank": 12, "score": 163476.92934960636 }, { "content": "// For conditions of distribution and use, see copyright notice in LICENSE\n\n\n\n#include \"StableHeaders.h\"\n\n#include \"KristalliProtocol.h\"\n\n#include \"TundraLogic.h\"\n\n\n\n#include \"Framework.h\"\n\n#include \"CoreStringUtils.h\"\n\n#include \"ConsoleAPI.h\"\n\n#include \"LoggingFunctions.h\"\n\n\n\n#include <Urho3D/Core/Profiler.h>\n\n\n\n#include <kNet.h>\n\n#include <kNet/UDPMessageConnection.h>\n\n\n\nnamespace Tundra\n\n{\n\nstatic const int cInitialAttempts = 0;\n\nstatic const int cReconnectAttempts = 0;\n", "file_path": "src/Plugins/TundraLogic/KristalliProtocol.cpp", "rank": 13, "score": 163473.75620428703 }, { "content": " {\n\n NetworkMessageReceived.Emit(source, packetId, messageId, data, numBytes);\n\n }\n\n catch(std::exception &e)\n\n {\n\n LogError(\"KristalliProtocolModule: Exception \\\"\" + String(e.what()) + \"\\\" thrown when handling network message id \" +\n\n String(messageId) + \" size \" + String(numBytes) + \" from client \" + source->ToString().c_str());\n\n\n\n // Kill the connection. For debugging purposes, don't disconnect the client if the server is running a debug build.\n\n#ifndef _DEBUG\n\n source->Disconnect(0);\n\n source->Close(0);\n\n // kNet will call back to KristalliProtocolModule::ClientDisconnected() to clean up the high-level Tundra UserConnection object.\n\n#endif\n\n }\n\n}\n\n\n\nu32 KristalliProtocol::AllocateNewConnectionID() const\n\n{\n\n u32 newID = 1;\n", "file_path": "src/Plugins/TundraLogic/KristalliProtocol.cpp", "rank": 14, "score": 163472.9500287514 }, { "content": " serverConnection = network.Connect(serverIp.c_str(), serverPort, serverTransport, this);\n\n if (!serverConnection)\n\n {\n\n LogInfo(\"Unable to connect to \" + String(serverIp.c_str()) + String(\":\") + String(serverPort));\n\n return;\n\n }\n\n\n\n if (serverTransport == kNet::SocketOverUDP)\n\n static_cast<kNet::UDPMessageConnection*>(serverConnection.ptr())->SetDatagramSendRate(500);\n\n\n\n // For TCP mode sockets, set the TCP_NODELAY option to improve latency for the messages we send.\n\n if (serverConnection->GetSocket() && serverConnection->GetSocket()->TransportLayer() == kNet::SocketOverTCP)\n\n serverConnection->GetSocket()->SetNaglesAlgorithmEnabled(false);\n\n}\n\n\n\nvoid KristalliProtocol::Disconnect()\n\n{\n\n // Clear the remembered destination server ip address so that the automatic connection timer will not try to reconnect.\n\n serverIp = \"\";\n\n reconnectTimer.Stop();\n", "file_path": "src/Plugins/TundraLogic/KristalliProtocol.cpp", "rank": 15, "score": 163468.53336573808 }, { "content": " \n\n LogInfo(\"User disconnected, connection ID \" + String((*iter)->userID));\n\n connections.Erase(iter);\n\n return;\n\n }\n\n }\n\n LogInfo(\"Unknown user disconnected\");\n\n}\n\n\n\nbool KristalliProtocol::Connected() const\n\n{\n\n return serverConnection != 0 && serverConnection->Connected();\n\n}\n\n\n\nvoid KristalliProtocol::HandleMessage(kNet::MessageConnection *source, kNet::packet_id_t packetId, kNet::message_id_t messageId, const char *data, size_t numBytes)\n\n{\n\n assert(source);\n\n assert(data || numBytes == 0);\n\n\n\n try\n", "file_path": "src/Plugins/TundraLogic/KristalliProtocol.cpp", "rank": 16, "score": 163464.6987078146 }, { "content": " if (transportLayer != kNet::InvalidTransportLayer)\n\n defaultTransport = transportLayer;\n\n }\n\n}\n\n\n\nvoid KristalliProtocol::Uninitialize()\n\n{\n\n Disconnect();\n\n}\n\n\n\nvoid KristalliProtocol::OpenKNetLogWindow()\n\n{\n\n LogError(\"Cannot open kNet logging window - kNet was not built with Qt enabled!\");\n\n}\n\n\n\nvoid KristalliProtocol::Update(float /*frametime*/)\n\n{\n\n // Pulls all new inbound network messages and calls the message handler we've registered\n\n // for each of them.\n\n if (serverConnection)\n", "file_path": "src/Plugins/TundraLogic/KristalliProtocol.cpp", "rank": 17, "score": 163464.42368663612 }, { "content": " // Enable all non verbose channels.\n\n else\n\n kNet::SetLogChannels(kNet::LogInfo | kNet::LogError | kNet::LogUser);\n\n\n\n /* There seems to be no quiet mode for kNet logging, set to errors only.\n\n This needs to be set explicitly as kNet does not log via Urho, which\n\n will automatically suppress anything below LogLevelError. */\n\n if (framework->HasCommandLineParameter(\"--quiet\"))\n\n kNet::SetLogChannels(kNet::LogError);\n\n}\n\n\n\nvoid KristalliProtocol::Initialize()\n\n{\n\n Framework* framework = owner->GetFramework();\n\n\n\n defaultTransport = kNet::SocketOverUDP;\n\n StringVector cmdLineParams = framework->CommandLineParameters(\"--protocol\");\n\n if (cmdLineParams.Size() > 0)\n\n {\n\n kNet::SocketTransportLayer transportLayer = kNet::StringToSocketTransportLayer(cmdLineParams.Front().Trimmed().CString());\n", "file_path": "src/Plugins/TundraLogic/KristalliProtocol.cpp", "rank": 18, "score": 163461.3637282517 }, { "content": " Urho3D::StaticCast<KNetUserConnection>(connection)->connection = source;\n\n connections.Push(connection);\n\n\n\n // For TCP mode sockets, set the TCP_NODELAY option to improve latency for the messages we send.\n\n if (source->GetSocket() && source->GetSocket()->TransportLayer() == kNet::SocketOverTCP)\n\n source->GetSocket()->SetNaglesAlgorithmEnabled(false);\n\n\n\n LogInfo(String(\"User connected from \") + String(source->RemoteEndPoint().ToString().c_str()) + String(\", connection ID \") + String(connection->userID));\n\n\n\n ClientConnectedEvent.Emit(connection.Get());\n\n}\n\n\n\nvoid KristalliProtocol::ClientDisconnected(kNet::MessageConnection *source)\n\n{\n\n // Delete from connection list if it was a known user\n\n for(auto iter = connections.Begin(); iter != connections.End(); ++iter)\n\n {\n\n if ((*iter)->ConnectionType() == \"knet\" && Urho3D::StaticCast<KNetUserConnection>(*iter)->connection == source)\n\n {\n\n ClientDisconnectedEvent.Emit(iter->Get());\n", "file_path": "src/Plugins/TundraLogic/KristalliProtocol.cpp", "rank": 19, "score": 163460.7005559779 }, { "content": " {\n\n URHO3D_PROFILE(KristalliProtocolModule_kNet_client_Process);\n\n serverConnection->Process();\n\n }\n\n\n\n // Note: Calling the above serverConnection->Process() may set serverConnection to null if the connection gets disconnected.\n\n // Therefore, in the code below, we cannot assume serverConnection is non-null, and must check it again.\n\n\n\n // Our client->server connection is never kept half-open.\n\n // That is, at the moment the server write-closes the connection, we also write-close the connection.\n\n // Check here if the server has write-closed, and also write-close our end if so.\n\n if (serverConnection && !serverConnection->IsReadOpen() && serverConnection->IsWriteOpen())\n\n serverConnection->Disconnect(0);\n\n \n\n // Process server incoming connections & messages if server up\n\n if (server)\n\n {\n\n URHO3D_PROFILE(KristalliProtocolModule_kNet_server_Process);\n\n\n\n server->Process();\n", "file_path": "src/Plugins/TundraLogic/KristalliProtocol.cpp", "rank": 20, "score": 163457.13059774163 }, { "content": " }\n\n else\n\n {\n\n LogInfo(\"Failed to connect to \" + String(serverIp.c_str()) + String(\":\") + String(serverPort));\n\n \n\n ConnectionAttemptFailed.Emit();\n\n\n\n reconnectTimer.Stop();\n\n serverIp = \"\";\n\n }\n\n }\n\n else if (!reconnectTimer.Enabled())\n\n reconnectTimer.StartMSecs(cReconnectTimeout);\n\n }\n\n\n\n // If connection was made, enable a larger number of reconnection attempts in case it gets lost\n\n if (serverConnection && serverConnection->GetConnectionState() == kNet::ConnectionOK)\n\n reconnectAttempts = cReconnectAttempts;\n\n}\n\n\n", "file_path": "src/Plugins/TundraLogic/KristalliProtocol.cpp", "rank": 21, "score": 163455.93472189968 }, { "content": " ++iter;\n\n }\n\n LogInfo(\"Server stopped\");\n\n server = 0;\n\n }\n\n}\n\n\n\nvoid KristalliProtocol::NewConnectionEstablished(kNet::MessageConnection *source)\n\n{\n\n assert(source);\n\n if (!source)\n\n return;\n\n\n\n if (dynamic_cast<kNet::UDPMessageConnection*>(source))\n\n static_cast<kNet::UDPMessageConnection*>(source)->SetDatagramSendRate(500);\n\n\n\n source->RegisterInboundMessageHandler(this);\n\n \n\n UserConnectionPtr connection = UserConnectionPtr(new KNetUserConnection(context_));\n\n connection->userID = AllocateNewConnectionID();\n", "file_path": "src/Plugins/TundraLogic/KristalliProtocol.cpp", "rank": 22, "score": 163455.6294718406 }, { "content": "\n\n // In Tundra, we *never* keep half-open server->client connections alive. \n\n // (the usual case would be to wait for a file transfer to complete, but Tundra messaging mechanism doesn't use that).\n\n // So, bidirectionally close all half-open connections.\n\n kNet::NetworkServer::ConnectionMap connections = server->GetConnections();\n\n for(kNet::NetworkServer::ConnectionMap::iterator iter = connections.begin(); iter != connections.end(); ++iter)\n\n if (!iter->second->IsReadOpen() && iter->second->IsWriteOpen())\n\n iter->second->Disconnect(0);\n\n }\n\n \n\n if ((!serverConnection || serverConnection->GetConnectionState() == kNet::ConnectionClosed ||\n\n serverConnection->GetConnectionState() == kNet::ConnectionPending) && serverIp.length() != 0)\n\n {\n\n const float cReconnectTimeout = 5 * 1000.0f;\n\n if (reconnectTimer.Test())\n\n {\n\n if (reconnectAttempts)\n\n {\n\n PerformConnection();\n\n --reconnectAttempts;\n", "file_path": "src/Plugins/TundraLogic/KristalliProtocol.cpp", "rank": 23, "score": 163453.12012153066 }, { "content": " for(auto iter = connections.Begin(); iter != connections.End(); ++iter)\n\n newID = Max(newID, (*iter)->userID+1);\n\n \n\n return newID;\n\n}\n\n\n\nUserConnectionPtr KristalliProtocol::UserConnectionBySource(kNet::MessageConnection* source) const\n\n{\n\n for(auto iter = connections.Begin(); iter != connections.End(); ++iter)\n\n if ((*iter)->ConnectionType() == \"knet\" && Urho3D::StaticCast<KNetUserConnection>(*iter)->connection == source)\n\n return *iter;\n\n\n\n return UserConnectionPtr();\n\n}\n\n\n\nUserConnectionPtr KristalliProtocol::UserConnectionById(u32 id) const\n\n{\n\n for(auto iter = connections.Begin(); iter != connections.End(); ++iter)\n\n if ((*iter)->userID == id)\n\n return *iter;\n\n\n\n return UserConnectionPtr();\n\n}\n\n\n\n}\n", "file_path": "src/Plugins/TundraLogic/KristalliProtocol.cpp", "rank": 24, "score": 163447.8459063746 }, { "content": "\n\n // Reflect --loglevel to kNet\n\n if (framework->HasCommandLineParameter(\"--loglevel\") || framework->HasCommandLineParameter(\"--loglevelnetwork\"))\n\n {\n\n LogLevel level = framework->Console()->CurrentLogLevel();\n\n if (framework->HasCommandLineParameter(\"--loglevelnetwork\"))\n\n {\n\n // --loglevelnetwork overrides --loglevel.\n\n StringVector llNetwork = framework->CommandLineParameters(\"--loglevelnetwork\");\n\n level = (!llNetwork.Empty() ? ConsoleAPI::LogLevelFromString(llNetwork.Front()) : level);\n\n }\n\n if (level == LogLevelNone || level == LogLevelWarning || level == LogLevelError)\n\n kNet::SetLogChannels(kNet::LogError);\n\n else if (level == LogLevelInfo)\n\n kNet::SetLogChannels(kNet::LogError | kNet::LogUser);\n\n else if (level == LogLevelDebug)\n\n kNet::SetLogChannels(kNet::LogInfo | kNet::LogError | kNet::LogUser | kNet::LogVerbose); \n\n else\n\n kNet::SetLogChannels(kNet::LogInfo | kNet::LogError | kNet::LogUser); \n\n }\n", "file_path": "src/Plugins/TundraLogic/KristalliProtocol.cpp", "rank": 25, "score": 163446.3969646294 }, { "content": "namespace Tundra\n\n{\n\n\n\n/// Can be used as a custom comparator in std::map or similar when wanting case-insensitive comparison.\n\nstruct TUNDRACORE_API StringCompareCaseInsensitive\n\n{\n\n bool operator()(const String &a, const String &b) const\n\n {\n\n return a.Compare(b, false) < 0;\n\n }\n\n};\n\n\n\n/// Reads an UTF-8 encoded String from a data stream\n\nString TUNDRACORE_API ReadUtf8String(kNet::DataDeserializer &dd);\n\n\n\n/// Writes String to a data stream using UTF-8 encoding.\n\n/** The maximum allowed length for the string is 65535 characters. */\n\nvoid TUNDRACORE_API WriteUtf8String(kNet::DataSerializer &ds, const String &str);\n\n\n\n/// Parses a input string to a command and optional parameters.\n\n/** Works on both forms of: \"MyFunction(one, to, three)\" and \"MyFunction one to three\" */\n\nvoid TUNDRACORE_API ParseCommand(String input, String &command, StringVector &parameters);\n\n\n\n/// Pad a string with whitespace.\n\n/** Negative @pad will insert the whitespace to the left, positive to the right. */\n\nString TUNDRACORE_API PadString(String str, int pad);\n\n\n\n/// Format number digit grouping from 1234567 to \"1,234,567\" up to 999,999,9999.\n\nString TUNDRACORE_API FormatDigitGrouping(uint value, const String &fillChar = \",\");\n\n\n\n/// Templated string padding overload that accepts anything the Urho3d::String ctor accepts.\n\ntemplate <typename T>\n\nString PadString(T val, int pad)\n\n{\n\n return PadString(String(val), pad);\n\n}\n\n\n\nString TUNDRACORE_API Join(const StringVector &list, const String &sseparator);\n\n\n", "file_path": "src/TundraCore/Framework/CoreStringUtils.h", "rank": 26, "score": 161748.77062883024 }, { "content": "namespace Tundra\n\n{\n\n/// Network message for login reply.\n\nstruct MsgLoginReply\n\n{\n\n\tMsgLoginReply()\n\n\t{\n\n\t\tInitToDefault();\n\n\t}\n\n\n\n\tMsgLoginReply(const char *data, size_t numBytes)\n\n\t{\n\n\t\tInitToDefault();\n\n\t\tkNet::DataDeserializer dd(data, numBytes);\n\n\t\tDeserializeFrom(dd);\n\n\t}\n\n\n\n\tvoid InitToDefault()\n\n\t{\n\n\t\treliable = defaultReliable;\n\n\t\tinOrder = defaultInOrder;\n\n\t\tpriority = defaultPriority;\n\n\t}\n\n\n\n\tenum { messageID = 101 };\n\n\tstatic inline const char * Name() { return \"LoginReply\"; }\n\n\n\n\tstatic const bool defaultReliable = true;\n\n\tstatic const bool defaultInOrder = true;\n\n\tstatic const u32 defaultPriority = 100;\n\n\n\n\tbool reliable;\n\n\tbool inOrder;\n\n\tu32 priority;\n\n\n\n\tu8 success;\n\n\tu32 userID;\n\n\tstd::vector<s8> loginReplyData;\n\n\n\n\tinline size_t Size() const\n\n\t{\n\n\t\treturn 1 + 1 + 2 + loginReplyData.size()*1;\n\n\t}\n\n\n\n\tinline void SerializeTo(kNet::DataSerializer &dst) const\n\n\t{\n\n\t\tdst.Add<u8>(success);\n\n\t\tdst.AddVLE<kNet::VLE8_16_32>(userID);\n\n\t\tdst.Add<u16>((u16)loginReplyData.size());\n\n\t\tif (loginReplyData.size() > 0)\n\n\t\t\tdst.AddArray<s8>(&loginReplyData[0], (u32)loginReplyData.size());\n\n\t}\n\n\n\n\tinline void DeserializeFrom(kNet::DataDeserializer &src)\n\n\t{\n\n\t\tsuccess = src.Read<u8>();\n\n\t\tuserID = src.ReadVLE<kNet::VLE8_16_32>();\n\n\t\tloginReplyData.resize(src.Read<u16>());\n\n\t\tif (loginReplyData.size() > 0)\n\n\t\t\tsrc.ReadArray<s8>(&loginReplyData[0], loginReplyData.size());\n\n\t}\n\n\n", "file_path": "src/Plugins/TundraLogic/MsgLoginReply.h", "rank": 27, "score": 161719.76051652982 }, { "content": "namespace Tundra\n\n{\n\n\n\n/// Network message informing that client has joined the server.\n\nstruct MsgClientJoined\n\n{\n\n\tMsgClientJoined()\n\n\t{\n\n\t\tInitToDefault();\n\n\t}\n\n\n\n\tMsgClientJoined(const char *data, size_t numBytes)\n\n\t{\n\n\t\tInitToDefault();\n\n\t\tkNet::DataDeserializer dd(data, numBytes);\n\n\t\tDeserializeFrom(dd);\n\n\t}\n\n\n\n\tvoid InitToDefault()\n\n\t{\n\n\t\treliable = defaultReliable;\n\n\t\tinOrder = defaultInOrder;\n\n\t\tpriority = defaultPriority;\n\n\t}\n\n\n\n\tenum { messageID = 102 };\n\n\tstatic inline const char * Name() { return \"ClientJoined\"; }\n\n\n\n\tstatic const bool defaultReliable = true;\n\n\tstatic const bool defaultInOrder = true;\n\n\tstatic const u32 defaultPriority = 100;\n\n\n\n\tbool reliable;\n\n\tbool inOrder;\n\n\tu32 priority;\n\n\n\n\tu32 userID;\n\n\tString username;\n\n\n\n\tinline size_t Size() const\n\n\t{\n\n\t\treturn (size_t)kNet::VLE8_16_32::GetEncodedBitLength(userID) + 2 + username.Length();\n\n\t}\n\n\n\n\tinline void SerializeTo(kNet::DataSerializer &dst) const\n\n\t{\n\n\t\tdst.AddVLE<kNet::VLE8_16_32>(userID);\n\n\t\tWriteUtf8String(dst, username);\n\n\t}\n\n\n\n\tinline void DeserializeFrom(kNet::DataDeserializer &src)\n\n\t{\n\n\t\tuserID = src.ReadVLE<kNet::VLE8_16_32>();\n\n\t\tif (src.BytesLeft() > 0)\n\n\t\t username = ReadUtf8String(src);\n\n\t}\n", "file_path": "src/Plugins/TundraLogic/MsgClientJoined.h", "rank": 28, "score": 161709.36632643864 }, { "content": "namespace Tundra\n\n{\n\n\n\n/// Network message informing that client has left the server.\n\nstruct MsgClientLeft\n\n{\n\n\tMsgClientLeft()\n\n\t{\n\n\t\tInitToDefault();\n\n\t}\n\n\n\n\tMsgClientLeft(const char *data, size_t numBytes)\n\n\t{\n\n\t\tInitToDefault();\n\n\t\tkNet::DataDeserializer dd(data, numBytes);\n\n\t\tDeserializeFrom(dd);\n\n\t}\n\n\n\n\tvoid InitToDefault()\n\n\t{\n\n\t\treliable = defaultReliable;\n\n\t\tinOrder = defaultInOrder;\n\n\t\tpriority = defaultPriority;\n\n\t}\n\n\n\n\tenum { messageID = 103 };\n\n\tstatic inline const char * Name() { return \"ClientLeft\"; }\n\n\n\n\tstatic const bool defaultReliable = true;\n\n\tstatic const bool defaultInOrder = true;\n\n\tstatic const u32 defaultPriority = 100;\n\n\n\n\tbool reliable;\n\n\tbool inOrder;\n\n\tu32 priority;\n\n\n\n\tu32 userID;\n\n\n\n\tinline size_t Size() const\n\n\t{\n\n\t\treturn (size_t)kNet::VLE8_16_32::GetEncodedBitLength(userID);\n\n\t}\n\n\n\n\tinline void SerializeTo(kNet::DataSerializer &dst) const\n\n\t{\n\n\t\tdst.AddVLE<kNet::VLE8_16_32>(userID);\n\n\t}\n\n\n\n\tinline void DeserializeFrom(kNet::DataDeserializer &src)\n\n\t{\n\n\t\tuserID = src.ReadVLE<kNet::VLE8_16_32>();\n\n\t}\n", "file_path": "src/Plugins/TundraLogic/MsgClientLeft.h", "rank": 29, "score": 161709.36632643864 }, { "content": " class Client;\n", "file_path": "src/Plugins/TundraLogic/TundraLogicFwd.h", "rank": 30, "score": 158114.01177402283 }, { "content": " class Server;\n", "file_path": "src/Plugins/TundraLogic/TundraLogicFwd.h", "rank": 31, "score": 158039.154739584 }, { "content": "class SignalReceiver_Client_LoginFailed : public SignalReceiver\n\n{\n\npublic:\n\n void OnSignal(const String & param0)\n\n {\n\n duk_context* ctx = ctx_;\n\n duk_push_global_object(ctx);\n\n duk_get_prop_string(ctx, -1, \"_OnSignal\");\n\n duk_remove(ctx, -2);\n\n duk_push_number(ctx, (size_t)key_);\n\n duk_push_array(ctx);\n\n duk_push_string(ctx, param0.CString());\n\n duk_put_prop_index(ctx, -2, 0);\n\n bool success = duk_pcall(ctx, 2) == 0;\n\n if (!success) LogError(\"[JavaScript] OnSignal: \" + GetErrorString(ctx));\n\n duk_pop(ctx);\n\n }\n\n};\n\n\n\nstatic duk_ret_t SignalWrapper_Client_LoginFailed_Finalizer(duk_context* ctx)\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ClientBindings.cpp", "rank": 32, "score": 157942.49020199545 }, { "content": "namespace kNet { class DataSerializer; class DataDeserializer; }\n", "file_path": "src/TundraCore/Framework/CoreStringUtils.h", "rank": 33, "score": 155165.61303513282 }, { "content": " class String;\n", "file_path": "src/TundraCore/Framework/CoreTypes.h", "rank": 34, "score": 148005.38818017155 }, { "content": "struct DefaultVoidToVoid<DefaultVoid> { typedef void type; };\n\n\n\n// Translate from 'void' into 'DefaultVoid'\n\n// Everything else is unchanged\n\ntemplate <class T>\n", "file_path": "src/TundraCore/Signals/Delegate.h", "rank": 35, "score": 144416.56405293845 }, { "content": "struct VoidToDefaultVoid<void> { typedef DefaultVoid type; };\n\n\n\n\n\n\n\n////////////////////////////////////////////////////////////////////////////////\n\n// Fast Delegates, part 1:\n\n//\n\n// Conversion of member function pointer to a standard form\n\n//\n\n////////////////////////////////////////////////////////////////////////////////\n\n\n\n// GenericClass is a fake class, ONLY used to provide a type.\n\n// It is vitally important that it is never defined, so that the compiler doesn't\n\n// think it can optimize the invocation. For example, Borland generates simpler\n\n// code if it knows the class only uses single inheritance.\n\n\n\n// Compilers using Microsoft's structure need to be treated as a special case.\n\n#ifdef FASTDLGT_MICROSOFT_MFP\n\n\n\n#ifdef FASTDLGT_HASINHERITANCE_KEYWORDS\n", "file_path": "src/TundraCore/Signals/Delegate.h", "rank": 36, "score": 144416.56405293845 }, { "content": "/// Top-level scene and network protocol handling logic.\n\nclass TUNDRALOGIC_API Client : public Object\n\n{\n\n URHO3D_OBJECT(Client, Object);\n\n\n\npublic:\n\n explicit Client(TundraLogic* owner);\n\n ~Client();\n\n\n\n /// Perform any per-frame processing [noscript]\n\n void Update(float frametime);\n\n\n\n enum ClientLoginState\n\n {\n\n NotConnected = 0,\n\n ConnectionPending,\n\n ConnectionEstablished,\n\n LoggedIn\n\n };\n\n\n\n /// Returns connection/login state [property]\n", "file_path": "src/Plugins/TundraLogic/Client.h", "rank": 37, "score": 141782.01287021843 }, { "content": "/// Implements Tundra server functionality.\n\n/// \\todo Implement\n\nclass TUNDRALOGIC_API Server : public Object\n\n{\n\n URHO3D_OBJECT(Server, Object);\n\n \n\npublic:\n\n explicit Server(TundraLogic* owner);\n\n ~Server();\n\n\n\n /// Perform any per-frame processing [noscript]\n\n void Update(float frametime);\n\n\n\n /// Get matching userconnection from a messageconnection, or null if unknown\n\n /// @todo Rename to UserConnection(ForMessageConnection) or similar.\n\n UserConnectionPtr GetUserConnection(kNet::MessageConnection* source) const;\n\n\n\n /// Get all connected users [property]\n\n UserConnectionList& UserConnections() const;\n\n\n\n /// Set current action sender. Called by SyncManager\n\n void SetActionSender(UserConnection *user);\n", "file_path": "src/Plugins/TundraLogic/Server.h", "rank": 38, "score": 141700.87052014447 }, { "content": " uint16_t port; /* Converted UF_PORT string */\n", "file_path": "src/Plugins/HttpPlugin/HttpParser/http_parser.h", "rank": 39, "score": 139406.11088991686 }, { "content": " @Override\n\n public void run() {\n\n // Runs SDL_main()\n\n // Urho3D: pass filesDir\n\n SDLActivity.nativeInit(((Activity)SDLActivity.getContext()).getFilesDir().getAbsolutePath());\n\n //Log.v(\"SDL\", \"SDL thread terminated\");\n", "file_path": "src/Android/src/org/libsdl/app/SDLActivity.java", "rank": 40, "score": 133923.47789504935 }, { "content": " @Override\n\n public void run(){\n\n try {\n\n SDLActivity.mSDLThread.join();\n\n }\n\n catch(Exception e){}\n\n finally{ \n\n // Native thread has finished\n\n if (! SDLActivity.mExitCalledFromJava) {\n\n SDLActivity.handleNativeExit();\n\n }\n\n }\n", "file_path": "src/Android/src/org/libsdl/app/SDLActivity.java", "rank": 41, "score": 130624.78772754178 }, { "content": " @Override\n\n public void run() {\n\n AbsoluteLayout.LayoutParams params = new AbsoluteLayout.LayoutParams(\n\n w, h + HEIGHT_PADDING, x, y);\n\n\n\n if (mTextEdit == null) {\n\n mTextEdit = new DummyEdit(getContext());\n\n\n\n mLayout.addView(mTextEdit, params);\n\n } else {\n\n mTextEdit.setLayoutParams(params);\n\n }\n\n\n\n mTextEdit.setVisibility(View.VISIBLE);\n\n mTextEdit.requestFocus();\n\n\n\n InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);\n\n imm.showSoftInput(mTextEdit, 0);\n", "file_path": "src/Android/src/org/libsdl/app/SDLActivity.java", "rank": 42, "score": 127567.83867751341 }, { "content": "class SignalWrapper_Server_ServerStarted\n\n{\n\npublic:\n\n SignalWrapper_Server_ServerStarted(Object* owner, Signal0< void >* signal) :\n\n owner_(owner),\n\n signal_(signal)\n\n {\n\n }\n\n\n\n WeakPtr<Object> owner_;\n\n Signal0< void >* signal_;\n\n};\n\n\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ServerBindings.cpp", "rank": 43, "score": 126250.9896962711 }, { "content": "class SignalWrapper_Server_ServerStopped\n\n{\n\npublic:\n\n SignalWrapper_Server_ServerStopped(Object* owner, Signal0< void >* signal) :\n\n owner_(owner),\n\n signal_(signal)\n\n {\n\n }\n\n\n\n WeakPtr<Object> owner_;\n\n Signal0< void >* signal_;\n\n};\n\n\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ServerBindings.cpp", "rank": 44, "score": 126250.9896962711 }, { "content": " @Override\n\n public void run() {\n\n synchronized (lock) {\n\n results[0] = getSystemService(name);\n\n results[1] = Boolean.TRUE;\n\n lock.notify();\n\n }\n", "file_path": "src/Android/src/org/libsdl/app/SDLActivity.java", "rank": 45, "score": 126121.86221908499 }, { "content": "struct MsgLogin\n\n{\n\n\tMsgLogin()\n\n\t{\n\n\t\tInitToDefault();\n\n\t}\n\n\n\n\tMsgLogin(const char *data, size_t numBytes)\n\n\t{\n\n\t\tInitToDefault();\n\n\t\tkNet::DataDeserializer dd(data, numBytes);\n\n\t\tDeserializeFrom(dd);\n", "file_path": "src/Plugins/TundraLogic/MsgLogin.h", "rank": 46, "score": 122419.30214539012 }, { "content": "class SignalReceiver_Server_ServerStarted : public SignalReceiver\n\n{\n\npublic:\n\n void OnSignal()\n\n {\n\n duk_context* ctx = ctx_;\n\n duk_push_global_object(ctx);\n\n duk_get_prop_string(ctx, -1, \"_OnSignal\");\n\n duk_remove(ctx, -2);\n\n duk_push_number(ctx, (size_t)key_);\n\n duk_push_array(ctx);\n\n bool success = duk_pcall(ctx, 2) == 0;\n\n if (!success) LogError(\"[JavaScript] OnSignal: \" + GetErrorString(ctx));\n\n duk_pop(ctx);\n\n }\n\n};\n\n\n\nstatic duk_ret_t SignalWrapper_Server_ServerStarted_Finalizer(duk_context* ctx)\n\n{\n\n FinalizeValueObject<SignalWrapper_Server_ServerStarted>(ctx, SignalWrapper_Server_ServerStarted_ID);\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ServerBindings.cpp", "rank": 47, "score": 121966.56941628979 }, { "content": "class SignalReceiver_Server_ServerStopped : public SignalReceiver\n\n{\n\npublic:\n\n void OnSignal()\n\n {\n\n duk_context* ctx = ctx_;\n\n duk_push_global_object(ctx);\n\n duk_get_prop_string(ctx, -1, \"_OnSignal\");\n\n duk_remove(ctx, -2);\n\n duk_push_number(ctx, (size_t)key_);\n\n duk_push_array(ctx);\n\n bool success = duk_pcall(ctx, 2) == 0;\n\n if (!success) LogError(\"[JavaScript] OnSignal: \" + GetErrorString(ctx));\n\n duk_pop(ctx);\n\n }\n\n};\n\n\n\nstatic duk_ret_t SignalWrapper_Server_ServerStopped_Finalizer(duk_context* ctx)\n\n{\n\n FinalizeValueObject<SignalWrapper_Server_ServerStopped>(ctx, SignalWrapper_Server_ServerStopped_ID);\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ServerBindings.cpp", "rank": 48, "score": 121966.56941628979 }, { "content": "class SignalWrapper_Client_AboutToConnect\n\n{\n\npublic:\n\n SignalWrapper_Client_AboutToConnect(Object* owner, Signal0< void >* signal) :\n\n owner_(owner),\n\n signal_(signal)\n\n {\n\n }\n\n\n\n WeakPtr<Object> owner_;\n\n Signal0< void >* signal_;\n\n};\n\n\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ClientBindings.cpp", "rank": 49, "score": 120714.42906755878 }, { "content": "class SignalWrapper_Client_Disconnected\n\n{\n\npublic:\n\n SignalWrapper_Client_Disconnected(Object* owner, Signal0< void >* signal) :\n\n owner_(owner),\n\n signal_(signal)\n\n {\n\n }\n\n\n\n WeakPtr<Object> owner_;\n\n Signal0< void >* signal_;\n\n};\n\n\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ClientBindings.cpp", "rank": 50, "score": 120714.42906755878 }, { "content": "class SignalWrapper_Server_UserDisconnected\n\n{\n\npublic:\n\n SignalWrapper_Server_UserDisconnected(Object* owner, Signal2< u32, UserConnection * >* signal) :\n\n owner_(owner),\n\n signal_(signal)\n\n {\n\n }\n\n\n\n WeakPtr<Object> owner_;\n\n Signal2< u32, UserConnection * >* signal_;\n\n};\n\n\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ServerBindings.cpp", "rank": 51, "score": 118997.64787339432 }, { "content": "class SignalWrapper_Server_MessageReceived\n\n{\n\npublic:\n\n SignalWrapper_Server_MessageReceived(Object* owner, Signal5< UserConnection *, kNet::packet_id_t, kNet::message_id_t, const char *, size_t >* signal) :\n\n owner_(owner),\n\n signal_(signal)\n\n {\n\n }\n\n\n\n WeakPtr<Object> owner_;\n\n Signal5< UserConnection *, kNet::packet_id_t, kNet::message_id_t, const char *, size_t >* signal_;\n\n};\n\n\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ServerBindings.cpp", "rank": 52, "score": 118997.64787339432 }, { "content": "class SignalWrapper_Server_UserAboutToConnect\n\n{\n\npublic:\n\n SignalWrapper_Server_UserAboutToConnect(Object* owner, Signal2< u32, UserConnection * >* signal) :\n\n owner_(owner),\n\n signal_(signal)\n\n {\n\n }\n\n\n\n WeakPtr<Object> owner_;\n\n Signal2< u32, UserConnection * >* signal_;\n\n};\n\n\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ServerBindings.cpp", "rank": 53, "score": 118997.64787339432 }, { "content": "class SignalWrapper_Server_UserConnected\n\n{\n\npublic:\n\n SignalWrapper_Server_UserConnected(Object* owner, Signal3< u32, UserConnection *, UserConnectedResponseData * >* signal) :\n\n owner_(owner),\n\n signal_(signal)\n\n {\n\n }\n\n\n\n WeakPtr<Object> owner_;\n\n Signal3< u32, UserConnection *, UserConnectedResponseData * >* signal_;\n\n};\n\n\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ServerBindings.cpp", "rank": 54, "score": 118997.64787339432 }, { "content": "namespace Tundra\n\n{\n\n\n\nstd::vector<s8> StringToBuffer(const String& str);\n\n\n\nString BufferToString(const std::vector<s8>& buffer);\n\n\n", "file_path": "src/Plugins/TundraLogic/TundraLogicUtils.h", "rank": 55, "score": 117429.86180858909 }, { "content": "public class Tundra extends SDLActivity {\n\n\n\n @Override\n\n protected boolean onLoadLibrary(ArrayList<String> libraryNames) {\n\n // Only load these 3 hardcoded libs, rest are loaded dynamically at runtime\n\n libraryNames.clear();\n\n libraryNames.add(new String(\"Urho3D\"));\n\n libraryNames.add(new String(\"TundraCore\"));\n\n libraryNames.add(new String(\"Tundra\"));\n\n\n\n return super.onLoadLibrary(libraryNames);\n\n }\n", "file_path": "src/Android/src/org/realxtend/tundra/Tundra.java", "rank": 56, "score": 116857.32157057508 }, { "content": "class SignalReceiver_Client_Disconnected : public SignalReceiver\n\n{\n\npublic:\n\n void OnSignal()\n\n {\n\n duk_context* ctx = ctx_;\n\n duk_push_global_object(ctx);\n\n duk_get_prop_string(ctx, -1, \"_OnSignal\");\n\n duk_remove(ctx, -2);\n\n duk_push_number(ctx, (size_t)key_);\n\n duk_push_array(ctx);\n\n bool success = duk_pcall(ctx, 2) == 0;\n\n if (!success) LogError(\"[JavaScript] OnSignal: \" + GetErrorString(ctx));\n\n duk_pop(ctx);\n\n }\n\n};\n\n\n\nstatic duk_ret_t SignalWrapper_Client_Disconnected_Finalizer(duk_context* ctx)\n\n{\n\n FinalizeValueObject<SignalWrapper_Client_Disconnected>(ctx, SignalWrapper_Client_Disconnected_ID);\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ClientBindings.cpp", "rank": 57, "score": 115927.05022780492 }, { "content": "class SignalReceiver_Client_AboutToConnect : public SignalReceiver\n\n{\n\npublic:\n\n void OnSignal()\n\n {\n\n duk_context* ctx = ctx_;\n\n duk_push_global_object(ctx);\n\n duk_get_prop_string(ctx, -1, \"_OnSignal\");\n\n duk_remove(ctx, -2);\n\n duk_push_number(ctx, (size_t)key_);\n\n duk_push_array(ctx);\n\n bool success = duk_pcall(ctx, 2) == 0;\n\n if (!success) LogError(\"[JavaScript] OnSignal: \" + GetErrorString(ctx));\n\n duk_pop(ctx);\n\n }\n\n};\n\n\n\nstatic duk_ret_t SignalWrapper_Client_AboutToConnect_Finalizer(duk_context* ctx)\n\n{\n\n FinalizeValueObject<SignalWrapper_Client_AboutToConnect>(ctx, SignalWrapper_Client_AboutToConnect_ID);\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ClientBindings.cpp", "rank": 58, "score": 115927.05022780492 }, { "content": "const unsigned long cLoginMessage = 100;\n", "file_path": "src/Plugins/TundraLogic/TundraMessages.h", "rank": 59, "score": 114588.4168170111 }, { "content": "class SignalReceiver_Server_UserAboutToConnect : public SignalReceiver\n\n{\n\npublic:\n\n void OnSignal(u32 param0, UserConnection * param1)\n\n {\n\n duk_context* ctx = ctx_;\n\n duk_push_global_object(ctx);\n\n duk_get_prop_string(ctx, -1, \"_OnSignal\");\n\n duk_remove(ctx, -2);\n\n duk_push_number(ctx, (size_t)key_);\n\n duk_push_array(ctx);\n\n duk_push_number(ctx, param0);\n\n duk_put_prop_index(ctx, -2, 0);\n\n PushWeakObject(ctx, param1);\n\n duk_put_prop_index(ctx, -2, 1);\n\n bool success = duk_pcall(ctx, 2) == 0;\n\n if (!success) LogError(\"[JavaScript] OnSignal: \" + GetErrorString(ctx));\n\n duk_pop(ctx);\n\n }\n\n};\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ServerBindings.cpp", "rank": 60, "score": 114339.92743083235 }, { "content": "class SignalReceiver_Server_MessageReceived : public SignalReceiver\n\n{\n\npublic:\n\n void OnSignal(UserConnection * param0, kNet::packet_id_t param1, kNet::message_id_t param2, const char * param3, size_t param4)\n\n {\n\n duk_context* ctx = ctx_;\n\n duk_push_global_object(ctx);\n\n duk_get_prop_string(ctx, -1, \"_OnSignal\");\n\n duk_remove(ctx, -2);\n\n duk_push_number(ctx, (size_t)key_);\n\n duk_push_array(ctx);\n\n PushWeakObject(ctx, param0);\n\n duk_put_prop_index(ctx, -2, 0);\n\n bool success = duk_pcall(ctx, 2) == 0;\n\n if (!success) LogError(\"[JavaScript] OnSignal: \" + GetErrorString(ctx));\n\n duk_pop(ctx);\n\n }\n\n};\n\n\n\nstatic duk_ret_t SignalWrapper_Server_MessageReceived_Finalizer(duk_context* ctx)\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ServerBindings.cpp", "rank": 61, "score": 114339.92743083235 }, { "content": "class SignalReceiver_Server_UserConnected : public SignalReceiver\n\n{\n\npublic:\n\n void OnSignal(u32 param0, UserConnection * param1, UserConnectedResponseData * param2)\n\n {\n\n duk_context* ctx = ctx_;\n\n duk_push_global_object(ctx);\n\n duk_get_prop_string(ctx, -1, \"_OnSignal\");\n\n duk_remove(ctx, -2);\n\n duk_push_number(ctx, (size_t)key_);\n\n duk_push_array(ctx);\n\n duk_push_number(ctx, param0);\n\n duk_put_prop_index(ctx, -2, 0);\n\n PushWeakObject(ctx, param1);\n\n duk_put_prop_index(ctx, -2, 1);\n\n bool success = duk_pcall(ctx, 2) == 0;\n\n if (!success) LogError(\"[JavaScript] OnSignal: \" + GetErrorString(ctx));\n\n duk_pop(ctx);\n\n }\n\n};\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ServerBindings.cpp", "rank": 62, "score": 114339.92743083235 }, { "content": "class SignalReceiver_Server_UserDisconnected : public SignalReceiver\n\n{\n\npublic:\n\n void OnSignal(u32 param0, UserConnection * param1)\n\n {\n\n duk_context* ctx = ctx_;\n\n duk_push_global_object(ctx);\n\n duk_get_prop_string(ctx, -1, \"_OnSignal\");\n\n duk_remove(ctx, -2);\n\n duk_push_number(ctx, (size_t)key_);\n\n duk_push_array(ctx);\n\n duk_push_number(ctx, param0);\n\n duk_put_prop_index(ctx, -2, 0);\n\n PushWeakObject(ctx, param1);\n\n duk_put_prop_index(ctx, -2, 1);\n\n bool success = duk_pcall(ctx, 2) == 0;\n\n if (!success) LogError(\"[JavaScript] OnSignal: \" + GetErrorString(ctx));\n\n duk_pop(ctx);\n\n }\n\n};\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ServerBindings.cpp", "rank": 63, "score": 114339.92743083235 }, { "content": "namespace Tundra\n\n{\n\n/// Represents a reference to an entity, either by name or ID.\n\n/** This structure can be used as a parameter type to an EC attribute. */\n\nstruct TUNDRACORE_API EntityReference\n\n{\n\n EntityReference() {}\n\n\n\n explicit EntityReference(const String &entityName) : ref(entityName.Trimmed()) {}\n\n explicit EntityReference(entity_id_t id) : ref(String(id)) {}\n\n\n\n /// Set from an entity. If the name is unique within its parent scene, the name will be set, otherwise ID.\n\n void Set(EntityPtr entity);\n\n void Set(Entity* entity);\n\n\n\n /// Lookup an entity from the scene according to the ref. Return null pointer if not found\n\n EntityPtr Lookup(Scene* scene) const;\n\n /// Lookup a parent entity from the scene according to the ref. If the ref is empty, use the entity's parent (default value).\n\n EntityPtr LookupParent(Entity* entity) const;\n\n\n\n /// Returns if @c entity matches this EntityReference.\n\n bool Matches(Entity *entity) const;\n\n\n\n /// Return whether the ref does not refer to an entity\n\n bool IsEmpty() const;\n\n\n\n bool operator ==(const EntityReference &rhs) const { return this->ref == rhs.ref; }\n\n\n", "file_path": "src/TundraCore/Scene/EntityReference.h", "rank": 64, "score": 114213.22337529676 }, { "content": "namespace Tundra\n\n{\n\n\n\n/// Cache that can be utilized on a SceneDesc import.\n\n/** Resolving Tundras asset references can involde recursive disk searches\n\n that can get slow on large imports.\n\n @see SceneDest::assetCache. */\n\nstruct TUNDRACORE_API AssetDescCache\n\n{\n\n /// First = AssetDesc::source, Second = AssetDesc::destinationName.\n\n typedef Pair<String, String> FileInfoPair;\n\n\n\n String basePath;\n\n HashMap<String, FileInfoPair > cache;\n\n\n\n /// Fills @c desc source and destinationName attributes.\n\n /** @return True if found and filled, false otherwise. */\n\n bool Fill(const String assetRef, AssetDesc &desc);\n\n\n\n /// Add @c desc to cache.\n\n /** @return Returns if added. */\n\n bool Add(const String &assetRef, const AssetDesc &desc);\n\n};\n\n\n\n/// Description of an asset (*Asset, IAsset) or an asset reference (AssetReference).\n\nstruct TUNDRACORE_API AssetDesc\n\n{\n\n String source; ///< Specifies the source filename for the location of this asset.\n\n PODVector<unsigned char> data; ///< Specifies in-memory content for the asset data.\n\n\n\n /// If true, the data for this asset is loaded in memory, and specified by the member field 'data'. Otherwise,\n\n /// the data is loaded from disk, specified by the filename 'source'.\n\n bool dataInMemory;\n\n\n\n String subname; ///< If the source filename is a container for multiple files, subname represents name within the file.\n\n String typeName; ///< Type name of the asset.\n\n String destinationName; ///< Name for the asset in the destination asset storage.\n\n\n\n AssetDesc() : dataInMemory(false) {}\n\n\n\n#define LEX_CMP(a, b) if ((a) < (b)) return true; else if ((a) > (b)) return false;\n\n\n\n /// Less than operator. Compares source and subname only.\n\n bool operator <(const AssetDesc &rhs) const\n\n {\n\n LEX_CMP(source, rhs.source)\n\n LEX_CMP(subname, rhs.subname)\n\n return false;\n\n }\n\n\n\n#undef LEX_CMP\n\n\n\n /// Equality operator. Returns true if filenames match, false otherwise.\n\n bool operator ==(const AssetDesc &rhs) const { return source == rhs.source; }\n", "file_path": "src/TundraCore/Scene/SceneDesc.h", "rank": 65, "score": 114213.22337529676 }, { "content": "namespace Tundra\n\n{\n\n\n\n/// Represents a reference to an asset.\n\n/** This structure can be used as a parameter type to an EC attribute. */\n\nstruct TUNDRACORE_API AssetReference\n\n{\n\npublic:\n\n /// Default constructor\n\n AssetReference() {}\n\n\n\n /// Constructs an asset reference pointing to the given asset.\n\n /// @param reference The URL of the asset to point to, e.g. \"local://myasset.mesh\", or \"http://www.website.com/texture.png\".\n\n explicit AssetReference(const String &reference) : ref(reference) {}\n\n\n\n /// @note This form of a ctor should not be used, since asset references can contain unicode characters, which a std::string cannot represent.\n\n explicit AssetReference(const char *reference) : ref(reference) {}\n\n\n\n AssetReference(const String &reference, const String &type_) : ref(reference), type(type_) {}\n\n\n\n /// Perform assignment\n\n /** @note This will not modify the type if already set. Set the type explicitly if required. */\n\n AssetReference& operator = (const AssetReference &rhs) { ref = rhs.ref; if (type.Empty()) type = rhs.type; return *this; }\n\n \n\n bool operator ==(const AssetReference &rhs) const { return this->ref == rhs.ref; }\n\n\n", "file_path": "src/TundraCore/Asset/AssetReference.h", "rank": 66, "score": 114213.22337529676 }, { "content": " Client::ClientLoginState ret = thisObj->LoginState();\n\n duk_push_number(ctx, ret);\n\n return 1;\n\n}\n\n\n\nstatic duk_ret_t Client_ConnectionId(duk_context* ctx)\n\n{\n\n Client* thisObj = GetThisWeakObject<Client>(ctx);\n\n u32 ret = thisObj->ConnectionId();\n\n duk_push_number(ctx, ret);\n\n return 1;\n\n}\n\n\n\nstatic duk_ret_t Client_Login_String_unsigned_short_String_String_String(duk_context* ctx)\n\n{\n\n int numArgs = duk_get_top(ctx);\n\n Client* thisObj = GetThisWeakObject<Client>(ctx);\n\n String address = duk_require_string(ctx, 0);\n\n unsigned short port = (unsigned short)duk_require_number(ctx, 1);\n\n String username = duk_require_string(ctx, 2);\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ClientBindings.cpp", "rank": 67, "score": 113895.1575778909 }, { "content": " String password = duk_require_string(ctx, 3);\n\n String protocol = numArgs > 4 ? duk_require_string(ctx, 4) : String();\n\n thisObj->Login(address, port, username, password, protocol);\n\n return 0;\n\n}\n\n\n\nstatic duk_ret_t Client_Logout(duk_context* ctx)\n\n{\n\n Client* thisObj = GetThisWeakObject<Client>(ctx);\n\n thisObj->Logout();\n\n return 0;\n\n}\n\n\n\nstatic duk_ret_t Client_DoLogout_bool(duk_context* ctx)\n\n{\n\n int numArgs = duk_get_top(ctx);\n\n Client* thisObj = GetThisWeakObject<Client>(ctx);\n\n bool fail = numArgs > 0 ? duk_require_boolean(ctx, 0) : false;\n\n thisObj->DoLogout(fail);\n\n return 0;\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ClientBindings.cpp", "rank": 68, "score": 113892.28386750724 }, { "content": "// For conditions of distribution and use, see copyright notice in LICENSE\n\n// This file has been autogenerated with BindingsGenerator\n\n\n\n#include \"StableHeaders.h\"\n\n#include \"CoreTypes.h\"\n\n#include \"JavaScriptInstance.h\"\n\n#include \"LoggingFunctions.h\"\n\n#include \"Client.h\"\n\n\n\n#ifdef _MSC_VER\n\n#pragma warning(disable: 4800)\n\n#endif\n\n\n\n\n\n\n\nusing namespace Tundra;\n\nusing namespace std;\n\n\n\nnamespace JSBindings\n\n{\n\n\n\n\n\n\n\nstatic const char* Client_ID = \"Client\";\n\n\n\nconst char* SignalWrapper_Client_AboutToConnect_ID = \"SignalWrapper_Client_AboutToConnect\";\n\n\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ClientBindings.cpp", "rank": 69, "score": 113888.47063932961 }, { "content": " String ret = thisObj->LoginPropertiesAsXml();\n\n duk_push_string(ctx, ret.CString());\n\n return 1;\n\n}\n\n\n\nstatic duk_ret_t Client_ClearLoginProperties(duk_context* ctx)\n\n{\n\n Client* thisObj = GetThisWeakObject<Client>(ctx);\n\n thisObj->ClearLoginProperties();\n\n return 0;\n\n}\n\n\n\nstatic const duk_function_list_entry Client_Functions[] = {\n\n {\"LoginState\", Client_LoginState, 0}\n\n ,{\"ConnectionId\", Client_ConnectionId, 0}\n\n ,{\"Login\", Client_Login_String_unsigned_short_String_String_String, DUK_VARARGS}\n\n ,{\"Logout\", Client_Logout, 0}\n\n ,{\"DoLogout\", Client_DoLogout_bool, DUK_VARARGS}\n\n ,{\"IsConnected\", Client_IsConnected, 0}\n\n ,{\"SetLoginProperty\", Client_SetLoginProperty_String_Variant, 2}\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ClientBindings.cpp", "rank": 70, "score": 113882.52603540281 }, { "content": " ,{\"LoginProperty\", Client_LoginProperty_String, 1}\n\n ,{\"HasLoginProperty\", Client_HasLoginProperty_String, 1}\n\n ,{\"LoginPropertiesAsXml\", Client_LoginPropertiesAsXml, 0}\n\n ,{\"ClearLoginProperties\", Client_ClearLoginProperties, 0}\n\n ,{nullptr, nullptr, 0}\n\n};\n\n\n\nvoid Expose_Client(duk_context* ctx)\n\n{\n\n duk_push_object(ctx);\n\n duk_push_number(ctx, 0);\n\n duk_put_prop_string(ctx, -2, \"NotConnected\");\n\n duk_push_number(ctx, 1);\n\n duk_put_prop_string(ctx, -2, \"ConnectionPending\");\n\n duk_push_number(ctx, 2);\n\n duk_put_prop_string(ctx, -2, \"ConnectionEstablished\");\n\n duk_push_number(ctx, 3);\n\n duk_put_prop_string(ctx, -2, \"LoggedIn\");\n\n duk_push_object(ctx);\n\n duk_put_function_list(ctx, -1, Client_Functions);\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ClientBindings.cpp", "rank": 71, "score": 113880.60929532583 }, { "content": "}\n\n\n\nstatic duk_ret_t SignalWrapper_Client_LoginFailed_Disconnect(duk_context* ctx)\n\n{\n\n SignalWrapper_Client_LoginFailed* wrapper = GetThisValueObject<SignalWrapper_Client_LoginFailed>(ctx, SignalWrapper_Client_LoginFailed_ID);\n\n if (!wrapper->owner_) return 0;\n\n CallDisconnectSignal(ctx, wrapper->signal_);\n\n return 0;\n\n}\n\n\n\nstatic duk_ret_t SignalWrapper_Client_LoginFailed_Emit(duk_context* ctx)\n\n{\n\n SignalWrapper_Client_LoginFailed* wrapper = GetThisValueObject<SignalWrapper_Client_LoginFailed>(ctx, SignalWrapper_Client_LoginFailed_ID);\n\n if (!wrapper->owner_) return 0;\n\n String param0 = duk_require_string(ctx, 0);\n\n wrapper->signal_->Emit(param0);\n\n return 0;\n\n}\n\n\n\nstatic duk_ret_t Client_Get_LoginFailed(duk_context* ctx)\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ClientBindings.cpp", "rank": 72, "score": 113877.25057207282 }, { "content": "{\n\n Client* thisObj = GetThisWeakObject<Client>(ctx);\n\n String key = duk_require_string(ctx, 0);\n\n Variant ret = thisObj->LoginProperty(key);\n\n PushVariant(ctx, ret);\n\n return 1;\n\n}\n\n\n\nstatic duk_ret_t Client_HasLoginProperty_String(duk_context* ctx)\n\n{\n\n Client* thisObj = GetThisWeakObject<Client>(ctx);\n\n String key = duk_require_string(ctx, 0);\n\n bool ret = thisObj->HasLoginProperty(key);\n\n duk_push_boolean(ctx, ret);\n\n return 1;\n\n}\n\n\n\nstatic duk_ret_t Client_LoginPropertiesAsXml(duk_context* ctx)\n\n{\n\n Client* thisObj = GetThisWeakObject<Client>(ctx);\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ClientBindings.cpp", "rank": 73, "score": 113873.77331424775 }, { "content": "{\n\n Client* thisObj = GetThisWeakObject<Client>(ctx);\n\n SignalWrapper_Client_LoginFailed* wrapper = new SignalWrapper_Client_LoginFailed(thisObj, &thisObj->LoginFailed);\n\n PushValueObject(ctx, wrapper, SignalWrapper_Client_LoginFailed_ID, SignalWrapper_Client_LoginFailed_Finalizer, false);\n\n duk_push_c_function(ctx, SignalWrapper_Client_LoginFailed_Connect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"Connect\");\n\n duk_push_c_function(ctx, SignalWrapper_Client_LoginFailed_Connect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"connect\");\n\n duk_push_c_function(ctx, SignalWrapper_Client_LoginFailed_Disconnect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"Disconnect\");\n\n duk_push_c_function(ctx, SignalWrapper_Client_LoginFailed_Disconnect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"disconnect\");\n\n duk_push_c_function(ctx, SignalWrapper_Client_LoginFailed_Emit, 1);\n\n duk_put_prop_string(ctx, -2, \"Emit\");\n\n return 1;\n\n}\n\n\n\nstatic duk_ret_t Client_LoginState(duk_context* ctx)\n\n{\n\n Client* thisObj = GetThisWeakObject<Client>(ctx);\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ClientBindings.cpp", "rank": 74, "score": 113873.53707601968 }, { "content": "{\n\n FinalizeValueObject<SignalWrapper_Client_LoginFailed>(ctx, SignalWrapper_Client_LoginFailed_ID);\n\n return 0;\n\n}\n\n\n\nstatic duk_ret_t SignalWrapper_Client_LoginFailed_Connect(duk_context* ctx)\n\n{\n\n SignalWrapper_Client_LoginFailed* wrapper = GetThisValueObject<SignalWrapper_Client_LoginFailed>(ctx, SignalWrapper_Client_LoginFailed_ID);\n\n if (!wrapper->owner_) return 0;\n\n HashMap<void*, SharedPtr<SignalReceiver> >& signalReceivers = JavaScriptInstance::InstanceFromContext(ctx)->SignalReceivers();\n\n if (signalReceivers.Find(wrapper->signal_) == signalReceivers.End())\n\n {\n\n SignalReceiver_Client_LoginFailed* receiver = new SignalReceiver_Client_LoginFailed();\n\n receiver->ctx_ = ctx;\n\n receiver->key_ = wrapper->signal_;\n\n wrapper->signal_->Connect(receiver, &SignalReceiver_Client_LoginFailed::OnSignal);\n\n signalReceivers[wrapper->signal_] = receiver;\n\n }\n\n CallConnectSignal(ctx, wrapper->signal_);\n\n return 0;\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ClientBindings.cpp", "rank": 75, "score": 113873.4282261155 }, { "content": "}\n\n\n\nstatic duk_ret_t Client_IsConnected(duk_context* ctx)\n\n{\n\n Client* thisObj = GetThisWeakObject<Client>(ctx);\n\n bool ret = thisObj->IsConnected();\n\n duk_push_boolean(ctx, ret);\n\n return 1;\n\n}\n\n\n\nstatic duk_ret_t Client_SetLoginProperty_String_Variant(duk_context* ctx)\n\n{\n\n Client* thisObj = GetThisWeakObject<Client>(ctx);\n\n String key = duk_require_string(ctx, 0);\n\n Variant value = GetVariant(ctx, 1);\n\n thisObj->SetLoginProperty(key, value);\n\n return 0;\n\n}\n\n\n\nstatic duk_ret_t Client_LoginProperty_String(duk_context* ctx)\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ClientBindings.cpp", "rank": 76, "score": 113872.97639436832 }, { "content": " DefineProperty(ctx, \"AboutToConnect\", Client_Get_AboutToConnect, nullptr);\n\n DefineProperty(ctx, \"Disconnected\", Client_Get_Disconnected, nullptr);\n\n DefineProperty(ctx, \"LoginFailed\", Client_Get_LoginFailed, nullptr);\n\n DefineProperty(ctx, \"loginState\", Client_LoginState, nullptr);\n\n DefineProperty(ctx, \"connectionId\", Client_ConnectionId, nullptr);\n\n DefineProperty(ctx, \"connected\", Client_IsConnected, nullptr);\n\n duk_put_prop_string(ctx, -2, \"prototype\");\n\n duk_put_global_string(ctx, Client_ID);\n\n}\n\n\n\n}\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ClientBindings.cpp", "rank": 77, "score": 113872.55316753463 }, { "content": " PushValueObject(ctx, wrapper, SignalWrapper_Client_Disconnected_ID, SignalWrapper_Client_Disconnected_Finalizer, false);\n\n duk_push_c_function(ctx, SignalWrapper_Client_Disconnected_Connect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"Connect\");\n\n duk_push_c_function(ctx, SignalWrapper_Client_Disconnected_Connect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"connect\");\n\n duk_push_c_function(ctx, SignalWrapper_Client_Disconnected_Disconnect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"Disconnect\");\n\n duk_push_c_function(ctx, SignalWrapper_Client_Disconnected_Disconnect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"disconnect\");\n\n duk_push_c_function(ctx, SignalWrapper_Client_Disconnected_Emit, 0);\n\n duk_put_prop_string(ctx, -2, \"Emit\");\n\n return 1;\n\n}\n\n\n\nconst char* SignalWrapper_Client_LoginFailed_ID = \"SignalWrapper_Client_LoginFailed\";\n\n\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ClientBindings.cpp", "rank": 78, "score": 113870.98836660433 }, { "content": " return 0;\n\n}\n\n\n\nstatic duk_ret_t SignalWrapper_Client_AboutToConnect_Connect(duk_context* ctx)\n\n{\n\n SignalWrapper_Client_AboutToConnect* wrapper = GetThisValueObject<SignalWrapper_Client_AboutToConnect>(ctx, SignalWrapper_Client_AboutToConnect_ID);\n\n if (!wrapper->owner_) return 0;\n\n HashMap<void*, SharedPtr<SignalReceiver> >& signalReceivers = JavaScriptInstance::InstanceFromContext(ctx)->SignalReceivers();\n\n if (signalReceivers.Find(wrapper->signal_) == signalReceivers.End())\n\n {\n\n SignalReceiver_Client_AboutToConnect* receiver = new SignalReceiver_Client_AboutToConnect();\n\n receiver->ctx_ = ctx;\n\n receiver->key_ = wrapper->signal_;\n\n wrapper->signal_->Connect(receiver, &SignalReceiver_Client_AboutToConnect::OnSignal);\n\n signalReceivers[wrapper->signal_] = receiver;\n\n }\n\n CallConnectSignal(ctx, wrapper->signal_);\n\n return 0;\n\n}\n\n\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ClientBindings.cpp", "rank": 79, "score": 113866.80559312551 }, { "content": " return 0;\n\n}\n\n\n\nstatic duk_ret_t SignalWrapper_Client_Disconnected_Connect(duk_context* ctx)\n\n{\n\n SignalWrapper_Client_Disconnected* wrapper = GetThisValueObject<SignalWrapper_Client_Disconnected>(ctx, SignalWrapper_Client_Disconnected_ID);\n\n if (!wrapper->owner_) return 0;\n\n HashMap<void*, SharedPtr<SignalReceiver> >& signalReceivers = JavaScriptInstance::InstanceFromContext(ctx)->SignalReceivers();\n\n if (signalReceivers.Find(wrapper->signal_) == signalReceivers.End())\n\n {\n\n SignalReceiver_Client_Disconnected* receiver = new SignalReceiver_Client_Disconnected();\n\n receiver->ctx_ = ctx;\n\n receiver->key_ = wrapper->signal_;\n\n wrapper->signal_->Connect(receiver, &SignalReceiver_Client_Disconnected::OnSignal);\n\n signalReceivers[wrapper->signal_] = receiver;\n\n }\n\n CallConnectSignal(ctx, wrapper->signal_);\n\n return 0;\n\n}\n\n\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ClientBindings.cpp", "rank": 80, "score": 113866.80559312551 }, { "content": " PushValueObject(ctx, wrapper, SignalWrapper_Client_AboutToConnect_ID, SignalWrapper_Client_AboutToConnect_Finalizer, false);\n\n duk_push_c_function(ctx, SignalWrapper_Client_AboutToConnect_Connect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"Connect\");\n\n duk_push_c_function(ctx, SignalWrapper_Client_AboutToConnect_Connect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"connect\");\n\n duk_push_c_function(ctx, SignalWrapper_Client_AboutToConnect_Disconnect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"Disconnect\");\n\n duk_push_c_function(ctx, SignalWrapper_Client_AboutToConnect_Disconnect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"disconnect\");\n\n duk_push_c_function(ctx, SignalWrapper_Client_AboutToConnect_Emit, 0);\n\n duk_put_prop_string(ctx, -2, \"Emit\");\n\n return 1;\n\n}\n\n\n\nconst char* SignalWrapper_Client_Disconnected_ID = \"SignalWrapper_Client_Disconnected\";\n\n\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ClientBindings.cpp", "rank": 81, "score": 113866.5067429882 }, { "content": "static duk_ret_t SignalWrapper_Client_Disconnected_Disconnect(duk_context* ctx)\n\n{\n\n SignalWrapper_Client_Disconnected* wrapper = GetThisValueObject<SignalWrapper_Client_Disconnected>(ctx, SignalWrapper_Client_Disconnected_ID);\n\n if (!wrapper->owner_) return 0;\n\n CallDisconnectSignal(ctx, wrapper->signal_);\n\n return 0;\n\n}\n\n\n\nstatic duk_ret_t SignalWrapper_Client_Disconnected_Emit(duk_context* ctx)\n\n{\n\n SignalWrapper_Client_Disconnected* wrapper = GetThisValueObject<SignalWrapper_Client_Disconnected>(ctx, SignalWrapper_Client_Disconnected_ID);\n\n if (!wrapper->owner_) return 0;\n\n wrapper->signal_->Emit();\n\n return 0;\n\n}\n\n\n\nstatic duk_ret_t Client_Get_Disconnected(duk_context* ctx)\n\n{\n\n Client* thisObj = GetThisWeakObject<Client>(ctx);\n\n SignalWrapper_Client_Disconnected* wrapper = new SignalWrapper_Client_Disconnected(thisObj, &thisObj->Disconnected);\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ClientBindings.cpp", "rank": 82, "score": 113865.54284977443 }, { "content": "static duk_ret_t SignalWrapper_Client_AboutToConnect_Disconnect(duk_context* ctx)\n\n{\n\n SignalWrapper_Client_AboutToConnect* wrapper = GetThisValueObject<SignalWrapper_Client_AboutToConnect>(ctx, SignalWrapper_Client_AboutToConnect_ID);\n\n if (!wrapper->owner_) return 0;\n\n CallDisconnectSignal(ctx, wrapper->signal_);\n\n return 0;\n\n}\n\n\n\nstatic duk_ret_t SignalWrapper_Client_AboutToConnect_Emit(duk_context* ctx)\n\n{\n\n SignalWrapper_Client_AboutToConnect* wrapper = GetThisValueObject<SignalWrapper_Client_AboutToConnect>(ctx, SignalWrapper_Client_AboutToConnect_ID);\n\n if (!wrapper->owner_) return 0;\n\n wrapper->signal_->Emit();\n\n return 0;\n\n}\n\n\n\nstatic duk_ret_t Client_Get_AboutToConnect(duk_context* ctx)\n\n{\n\n Client* thisObj = GetThisWeakObject<Client>(ctx);\n\n SignalWrapper_Client_AboutToConnect* wrapper = new SignalWrapper_Client_AboutToConnect(thisObj, &thisObj->AboutToConnect);\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ClientBindings.cpp", "rank": 83, "score": 113865.54284977443 }, { "content": " Server* thisObj = GetThisWeakObject<Server>(ctx);\n\n String ret = thisObj->Protocol();\n\n duk_push_string(ctx, ret.CString());\n\n return 1;\n\n}\n\n\n\nstatic duk_ret_t Server_Start_unsigned_short_String(duk_context* ctx)\n\n{\n\n int numArgs = duk_get_top(ctx);\n\n Server* thisObj = GetThisWeakObject<Server>(ctx);\n\n unsigned short port = (unsigned short)duk_require_number(ctx, 0);\n\n String protocol = numArgs > 1 ? duk_require_string(ctx, 1) : \"\";\n\n bool ret = thisObj->Start(port, protocol);\n\n duk_push_boolean(ctx, ret);\n\n return 1;\n\n}\n\n\n\nstatic duk_ret_t Server_Stop(duk_context* ctx)\n\n{\n\n Server* thisObj = GetThisWeakObject<Server>(ctx);\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ServerBindings.cpp", "rank": 84, "score": 113823.9905320951 }, { "content": "// For conditions of distribution and use, see copyright notice in LICENSE\n\n// This file has been autogenerated with BindingsGenerator\n\n\n\n#include \"StableHeaders.h\"\n\n#include \"CoreTypes.h\"\n\n#include \"JavaScriptInstance.h\"\n\n#include \"LoggingFunctions.h\"\n\n#include \"Server.h\"\n\n\n\n#ifdef _MSC_VER\n\n#pragma warning(disable: 4800)\n\n#endif\n\n\n\n#include \"UserConnection.h\"\n\n\n\n\n\nusing namespace Tundra;\n\nusing namespace std;\n\n\n\nnamespace JSBindings\n\n{\n\n\n\n\n\n\n\nstatic const char* Server_ID = \"Server\";\n\n\n\nconst char* SignalWrapper_Server_UserAboutToConnect_ID = \"SignalWrapper_Server_UserAboutToConnect\";\n\n\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ServerBindings.cpp", "rank": 85, "score": 113822.42931548675 }, { "content": " UserConnectionPtr ret = thisObj->ActionSender();\n\n PushWeakObject(ctx, ret.Get());\n\n return 1;\n\n}\n\n\n\nstatic const duk_function_list_entry Server_Functions[] = {\n\n {\"UserConnections\", Server_UserConnections, 0}\n\n ,{\"SetActionSender\", Server_SetActionSender_UserConnection, 1}\n\n ,{\"Port\", Server_Port, 0}\n\n ,{\"Protocol\", Server_Protocol, 0}\n\n ,{\"Start\", Server_Start_unsigned_short_String, DUK_VARARGS}\n\n ,{\"Stop\", Server_Stop, 0}\n\n ,{\"IsRunning\", Server_IsRunning, 0}\n\n ,{\"IsAboutToStart\", Server_IsAboutToStart, 0}\n\n ,{\"AuthenticatedUsers\", Server_AuthenticatedUsers, 0}\n\n ,{\"UserConnectionById\", Server_UserConnectionById_u32, 1}\n\n ,{\"ActionSender\", Server_ActionSender, 0}\n\n ,{nullptr, nullptr, 0}\n\n};\n\n\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ServerBindings.cpp", "rank": 86, "score": 113821.68615684686 }, { "content": "void Expose_Server(duk_context* ctx)\n\n{\n\n duk_push_object(ctx);\n\n duk_push_object(ctx);\n\n duk_put_function_list(ctx, -1, Server_Functions);\n\n DefineProperty(ctx, \"UserAboutToConnect\", Server_Get_UserAboutToConnect, nullptr);\n\n DefineProperty(ctx, \"UserConnected\", Server_Get_UserConnected, nullptr);\n\n DefineProperty(ctx, \"MessageReceived\", Server_Get_MessageReceived, nullptr);\n\n DefineProperty(ctx, \"UserDisconnected\", Server_Get_UserDisconnected, nullptr);\n\n DefineProperty(ctx, \"ServerStarted\", Server_Get_ServerStarted, nullptr);\n\n DefineProperty(ctx, \"ServerStopped\", Server_Get_ServerStopped, nullptr);\n\n DefineProperty(ctx, \"userConnections\", Server_UserConnections, nullptr);\n\n DefineProperty(ctx, \"port\", Server_Port, nullptr);\n\n DefineProperty(ctx, \"protocol\", Server_Protocol, nullptr);\n\n DefineProperty(ctx, \"running\", Server_IsRunning, nullptr);\n\n DefineProperty(ctx, \"aboutToStart\", Server_IsAboutToStart, nullptr);\n\n DefineProperty(ctx, \"authenticatedUsers\", Server_AuthenticatedUsers, nullptr);\n\n DefineProperty(ctx, \"actionSender\", Server_ActionSender, Server_SetActionSender_UserConnection);\n\n duk_put_prop_string(ctx, -2, \"prototype\");\n\n duk_put_global_string(ctx, Server_ID);\n\n}\n\n\n\n}\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ServerBindings.cpp", "rank": 87, "score": 113813.23510072916 }, { "content": "}\n\n\n\nstatic duk_ret_t Server_SetActionSender_UserConnection(duk_context* ctx)\n\n{\n\n Server* thisObj = GetThisWeakObject<Server>(ctx);\n\n UserConnection* user = GetWeakObject<UserConnection>(ctx, 0);\n\n thisObj->SetActionSender(user);\n\n return 0;\n\n}\n\n\n\nstatic duk_ret_t Server_Port(duk_context* ctx)\n\n{\n\n Server* thisObj = GetThisWeakObject<Server>(ctx);\n\n int ret = thisObj->Port();\n\n duk_push_number(ctx, ret);\n\n return 1;\n\n}\n\n\n\nstatic duk_ret_t Server_Protocol(duk_context* ctx)\n\n{\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ServerBindings.cpp", "rank": 88, "score": 113804.35821977776 }, { "content": "}\n\n\n\nstatic duk_ret_t SignalWrapper_Server_MessageReceived_Disconnect(duk_context* ctx)\n\n{\n\n SignalWrapper_Server_MessageReceived* wrapper = GetThisValueObject<SignalWrapper_Server_MessageReceived>(ctx, SignalWrapper_Server_MessageReceived_ID);\n\n if (!wrapper->owner_) return 0;\n\n CallDisconnectSignal(ctx, wrapper->signal_);\n\n return 0;\n\n}\n\n\n\nstatic duk_ret_t Server_Get_MessageReceived(duk_context* ctx)\n\n{\n\n Server* thisObj = GetThisWeakObject<Server>(ctx);\n\n SignalWrapper_Server_MessageReceived* wrapper = new SignalWrapper_Server_MessageReceived(thisObj, &thisObj->MessageReceived);\n\n PushValueObject(ctx, wrapper, SignalWrapper_Server_MessageReceived_ID, SignalWrapper_Server_MessageReceived_Finalizer, false);\n\n duk_push_c_function(ctx, SignalWrapper_Server_MessageReceived_Connect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"Connect\");\n\n duk_push_c_function(ctx, SignalWrapper_Server_MessageReceived_Connect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"connect\");\n\n duk_push_c_function(ctx, SignalWrapper_Server_MessageReceived_Disconnect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"Disconnect\");\n\n duk_push_c_function(ctx, SignalWrapper_Server_MessageReceived_Disconnect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"disconnect\");\n\n return 1;\n\n}\n\n\n\nconst char* SignalWrapper_Server_UserDisconnected_ID = \"SignalWrapper_Server_UserDisconnected\";\n\n\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ServerBindings.cpp", "rank": 89, "score": 113802.24380512953 }, { "content": " return 0;\n\n}\n\n\n\nstatic duk_ret_t SignalWrapper_Server_ServerStarted_Connect(duk_context* ctx)\n\n{\n\n SignalWrapper_Server_ServerStarted* wrapper = GetThisValueObject<SignalWrapper_Server_ServerStarted>(ctx, SignalWrapper_Server_ServerStarted_ID);\n\n if (!wrapper->owner_) return 0;\n\n HashMap<void*, SharedPtr<SignalReceiver> >& signalReceivers = JavaScriptInstance::InstanceFromContext(ctx)->SignalReceivers();\n\n if (signalReceivers.Find(wrapper->signal_) == signalReceivers.End())\n\n {\n\n SignalReceiver_Server_ServerStarted* receiver = new SignalReceiver_Server_ServerStarted();\n\n receiver->ctx_ = ctx;\n\n receiver->key_ = wrapper->signal_;\n\n wrapper->signal_->Connect(receiver, &SignalReceiver_Server_ServerStarted::OnSignal);\n\n signalReceivers[wrapper->signal_] = receiver;\n\n }\n\n CallConnectSignal(ctx, wrapper->signal_);\n\n return 0;\n\n}\n\n\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ServerBindings.cpp", "rank": 90, "score": 113801.63604827168 }, { "content": " return 0;\n\n}\n\n\n\nstatic duk_ret_t SignalWrapper_Server_ServerStopped_Connect(duk_context* ctx)\n\n{\n\n SignalWrapper_Server_ServerStopped* wrapper = GetThisValueObject<SignalWrapper_Server_ServerStopped>(ctx, SignalWrapper_Server_ServerStopped_ID);\n\n if (!wrapper->owner_) return 0;\n\n HashMap<void*, SharedPtr<SignalReceiver> >& signalReceivers = JavaScriptInstance::InstanceFromContext(ctx)->SignalReceivers();\n\n if (signalReceivers.Find(wrapper->signal_) == signalReceivers.End())\n\n {\n\n SignalReceiver_Server_ServerStopped* receiver = new SignalReceiver_Server_ServerStopped();\n\n receiver->ctx_ = ctx;\n\n receiver->key_ = wrapper->signal_;\n\n wrapper->signal_->Connect(receiver, &SignalReceiver_Server_ServerStopped::OnSignal);\n\n signalReceivers[wrapper->signal_] = receiver;\n\n }\n\n CallConnectSignal(ctx, wrapper->signal_);\n\n return 0;\n\n}\n\n\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ServerBindings.cpp", "rank": 91, "score": 113801.63604827168 }, { "content": " PushValueObject(ctx, wrapper, SignalWrapper_Server_ServerStarted_ID, SignalWrapper_Server_ServerStarted_Finalizer, false);\n\n duk_push_c_function(ctx, SignalWrapper_Server_ServerStarted_Connect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"Connect\");\n\n duk_push_c_function(ctx, SignalWrapper_Server_ServerStarted_Connect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"connect\");\n\n duk_push_c_function(ctx, SignalWrapper_Server_ServerStarted_Disconnect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"Disconnect\");\n\n duk_push_c_function(ctx, SignalWrapper_Server_ServerStarted_Disconnect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"disconnect\");\n\n duk_push_c_function(ctx, SignalWrapper_Server_ServerStarted_Emit, 0);\n\n duk_put_prop_string(ctx, -2, \"Emit\");\n\n return 1;\n\n}\n\n\n\nconst char* SignalWrapper_Server_ServerStopped_ID = \"SignalWrapper_Server_ServerStopped\";\n\n\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ServerBindings.cpp", "rank": 92, "score": 113801.40260491769 }, { "content": " PushValueObject(ctx, wrapper, SignalWrapper_Server_ServerStopped_ID, SignalWrapper_Server_ServerStopped_Finalizer, false);\n\n duk_push_c_function(ctx, SignalWrapper_Server_ServerStopped_Connect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"Connect\");\n\n duk_push_c_function(ctx, SignalWrapper_Server_ServerStopped_Connect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"connect\");\n\n duk_push_c_function(ctx, SignalWrapper_Server_ServerStopped_Disconnect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"Disconnect\");\n\n duk_push_c_function(ctx, SignalWrapper_Server_ServerStopped_Disconnect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"disconnect\");\n\n duk_push_c_function(ctx, SignalWrapper_Server_ServerStopped_Emit, 0);\n\n duk_put_prop_string(ctx, -2, \"Emit\");\n\n return 1;\n\n}\n\n\n\nstatic duk_ret_t Server_UserConnections(duk_context* ctx)\n\n{\n\n Server* thisObj = GetThisWeakObject<Server>(ctx);\n\n UserConnectionList & ret = thisObj->UserConnections();\n\n PushWeakObjectVector(ctx, ret);\n\n return 1;\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ServerBindings.cpp", "rank": 93, "score": 113801.0573435342 }, { "content": " thisObj->Stop();\n\n return 0;\n\n}\n\n\n\nstatic duk_ret_t Server_IsRunning(duk_context* ctx)\n\n{\n\n Server* thisObj = GetThisWeakObject<Server>(ctx);\n\n bool ret = thisObj->IsRunning();\n\n duk_push_boolean(ctx, ret);\n\n return 1;\n\n}\n\n\n\nstatic duk_ret_t Server_IsAboutToStart(duk_context* ctx)\n\n{\n\n Server* thisObj = GetThisWeakObject<Server>(ctx);\n\n bool ret = thisObj->IsAboutToStart();\n\n duk_push_boolean(ctx, ret);\n\n return 1;\n\n}\n\n\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ServerBindings.cpp", "rank": 94, "score": 113800.8312359985 }, { "content": "}\n\n\n\nstatic duk_ret_t Server_Get_UserDisconnected(duk_context* ctx)\n\n{\n\n Server* thisObj = GetThisWeakObject<Server>(ctx);\n\n SignalWrapper_Server_UserDisconnected* wrapper = new SignalWrapper_Server_UserDisconnected(thisObj, &thisObj->UserDisconnected);\n\n PushValueObject(ctx, wrapper, SignalWrapper_Server_UserDisconnected_ID, SignalWrapper_Server_UserDisconnected_Finalizer, false);\n\n duk_push_c_function(ctx, SignalWrapper_Server_UserDisconnected_Connect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"Connect\");\n\n duk_push_c_function(ctx, SignalWrapper_Server_UserDisconnected_Connect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"connect\");\n\n duk_push_c_function(ctx, SignalWrapper_Server_UserDisconnected_Disconnect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"Disconnect\");\n\n duk_push_c_function(ctx, SignalWrapper_Server_UserDisconnected_Disconnect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"disconnect\");\n\n duk_push_c_function(ctx, SignalWrapper_Server_UserDisconnected_Emit, 2);\n\n duk_put_prop_string(ctx, -2, \"Emit\");\n\n return 1;\n\n}\n\n\n\nconst char* SignalWrapper_Server_ServerStarted_ID = \"SignalWrapper_Server_ServerStarted\";\n\n\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ServerBindings.cpp", "rank": 95, "score": 113800.72984293375 }, { "content": " duk_put_prop_string(ctx, -2, \"connect\");\n\n duk_push_c_function(ctx, SignalWrapper_Server_UserConnected_Disconnect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"Disconnect\");\n\n duk_push_c_function(ctx, SignalWrapper_Server_UserConnected_Disconnect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"disconnect\");\n\n return 1;\n\n}\n\n\n\nconst char* SignalWrapper_Server_MessageReceived_ID = \"SignalWrapper_Server_MessageReceived\";\n\n\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ServerBindings.cpp", "rank": 96, "score": 113800.60133387383 }, { "content": "{\n\n FinalizeValueObject<SignalWrapper_Server_MessageReceived>(ctx, SignalWrapper_Server_MessageReceived_ID);\n\n return 0;\n\n}\n\n\n\nstatic duk_ret_t SignalWrapper_Server_MessageReceived_Connect(duk_context* ctx)\n\n{\n\n SignalWrapper_Server_MessageReceived* wrapper = GetThisValueObject<SignalWrapper_Server_MessageReceived>(ctx, SignalWrapper_Server_MessageReceived_ID);\n\n if (!wrapper->owner_) return 0;\n\n HashMap<void*, SharedPtr<SignalReceiver> >& signalReceivers = JavaScriptInstance::InstanceFromContext(ctx)->SignalReceivers();\n\n if (signalReceivers.Find(wrapper->signal_) == signalReceivers.End())\n\n {\n\n SignalReceiver_Server_MessageReceived* receiver = new SignalReceiver_Server_MessageReceived();\n\n receiver->ctx_ = ctx;\n\n receiver->key_ = wrapper->signal_;\n\n wrapper->signal_->Connect(receiver, &SignalReceiver_Server_MessageReceived::OnSignal);\n\n signalReceivers[wrapper->signal_] = receiver;\n\n }\n\n CallConnectSignal(ctx, wrapper->signal_);\n\n return 0;\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ServerBindings.cpp", "rank": 97, "score": 113800.58615492209 }, { "content": "}\n\n\n\nstatic duk_ret_t Server_Get_UserAboutToConnect(duk_context* ctx)\n\n{\n\n Server* thisObj = GetThisWeakObject<Server>(ctx);\n\n SignalWrapper_Server_UserAboutToConnect* wrapper = new SignalWrapper_Server_UserAboutToConnect(thisObj, &thisObj->UserAboutToConnect);\n\n PushValueObject(ctx, wrapper, SignalWrapper_Server_UserAboutToConnect_ID, SignalWrapper_Server_UserAboutToConnect_Finalizer, false);\n\n duk_push_c_function(ctx, SignalWrapper_Server_UserAboutToConnect_Connect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"Connect\");\n\n duk_push_c_function(ctx, SignalWrapper_Server_UserAboutToConnect_Connect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"connect\");\n\n duk_push_c_function(ctx, SignalWrapper_Server_UserAboutToConnect_Disconnect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"Disconnect\");\n\n duk_push_c_function(ctx, SignalWrapper_Server_UserAboutToConnect_Disconnect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"disconnect\");\n\n duk_push_c_function(ctx, SignalWrapper_Server_UserAboutToConnect_Emit, 2);\n\n duk_put_prop_string(ctx, -2, \"Emit\");\n\n return 1;\n\n}\n\n\n\nconst char* SignalWrapper_Server_UserConnected_ID = \"SignalWrapper_Server_UserConnected\";\n\n\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ServerBindings.cpp", "rank": 98, "score": 113800.5887404809 }, { "content": " CallConnectSignal(ctx, wrapper->signal_);\n\n return 0;\n\n}\n\n\n\nstatic duk_ret_t SignalWrapper_Server_UserConnected_Disconnect(duk_context* ctx)\n\n{\n\n SignalWrapper_Server_UserConnected* wrapper = GetThisValueObject<SignalWrapper_Server_UserConnected>(ctx, SignalWrapper_Server_UserConnected_ID);\n\n if (!wrapper->owner_) return 0;\n\n CallDisconnectSignal(ctx, wrapper->signal_);\n\n return 0;\n\n}\n\n\n\nstatic duk_ret_t Server_Get_UserConnected(duk_context* ctx)\n\n{\n\n Server* thisObj = GetThisWeakObject<Server>(ctx);\n\n SignalWrapper_Server_UserConnected* wrapper = new SignalWrapper_Server_UserConnected(thisObj, &thisObj->UserConnected);\n\n PushValueObject(ctx, wrapper, SignalWrapper_Server_UserConnected_ID, SignalWrapper_Server_UserConnected_Finalizer, false);\n\n duk_push_c_function(ctx, SignalWrapper_Server_UserConnected_Connect, DUK_VARARGS);\n\n duk_put_prop_string(ctx, -2, \"Connect\");\n\n duk_push_c_function(ctx, SignalWrapper_Server_UserConnected_Connect, DUK_VARARGS);\n", "file_path": "src/Plugins/TundraLogic/TundraLogicBindings/ServerBindings.cpp", "rank": 99, "score": 113800.51572798565 } ]
C++
Audio/src/Windows/AudioOutput_WASAPI.cpp
Pants/unnamed-sdvx-clone
28a4b537e40bfe45a48c63c20f5dc4ae5702feab
#include "stdafx.h" #include "AudioOutput.hpp" #include "Shared/Thread.hpp" #ifdef _WIN32 #include "Audioclient.h" #include "Mmdeviceapi.h" #include "comdef.h" #include "Functiondiscoverykeys_devpkey.h" #define REFTIME_NS (100) #define REFTIMES_PER_MICROSEC (1000/REFTIME_NS) #define REFTIMES_PER_MILLISEC (REFTIMES_PER_MICROSEC * 1000) #define REFTIMES_PER_SEC (REFTIMES_PER_MILLISEC * 1000) #define SAFE_RELEASE(punk) \ if ((punk) != NULL) \ { (punk)->Release(); (punk) = nullptr; } static const uint32_t freq = 44100; static const uint32_t channels = 2; static const uint32_t numBuffers = 2; static const uint32_t bufferLength = 10; static const REFERENCE_TIME bufferDuration = (REFERENCE_TIME)(bufferLength * REFTIMES_PER_MILLISEC); class NotificationClient : public IMMNotificationClient { public: class AudioOutput_Impl* output; virtual HRESULT STDMETHODCALLTYPE OnDeviceStateChanged(_In_ LPCWSTR pwstrDeviceId, _In_ DWORD dwNewState); virtual HRESULT STDMETHODCALLTYPE OnDeviceAdded(_In_ LPCWSTR pwstrDeviceId); virtual HRESULT STDMETHODCALLTYPE OnDeviceRemoved(_In_ LPCWSTR pwstrDeviceId); virtual HRESULT STDMETHODCALLTYPE OnDefaultDeviceChanged(_In_ EDataFlow flow, _In_ ERole role, _In_ LPCWSTR pwstrDefaultDeviceId); virtual HRESULT STDMETHODCALLTYPE OnPropertyValueChanged(_In_ LPCWSTR pwstrDeviceId, _In_ const PROPERTYKEY key); virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject) { return E_NOINTERFACE; } virtual ULONG STDMETHODCALLTYPE AddRef(void) { return 0; } virtual ULONG STDMETHODCALLTYPE Release(void) { return 0; } }; class AudioOutput_Impl { public: struct IAudioClient* m_audioClient = nullptr; struct IAudioRenderClient* m_audioRenderClient = nullptr; struct IMMDevice* m_device = nullptr; tWAVEFORMATEX m_format; IMMDeviceEnumerator* m_deviceEnumerator = nullptr; uint32_t m_numBufferFrames; NotificationClient m_notificationClient; double m_bufferLength; static const uint32 m_dummyChannelCount = 2; static const uint32 m_dummyBufferLength = (uint32)((double)freq * 0.2); float m_dummyBuffer[m_dummyBufferLength * m_dummyChannelCount]; double m_dummyTimerPos; Timer m_dummyTimer; IMMDevice* m_pendingDevice = nullptr; bool m_pendingDeviceChange = false; bool m_runAudioThread = false; Thread m_audioThread; IMixer* m_mixer = nullptr; bool m_exclusive = false; public: AudioOutput_Impl() { m_notificationClient.output = this; } ~AudioOutput_Impl() { Stop(); CloseDevice(); SAFE_RELEASE(m_pendingDevice); if(m_deviceEnumerator) { m_deviceEnumerator->UnregisterEndpointNotificationCallback(&m_notificationClient); SAFE_RELEASE(m_deviceEnumerator); } } void Start() { if(m_runAudioThread) return; m_runAudioThread = true; m_audioThread = Thread(&AudioOutput_Impl::AudioThread, this); } void Stop() { if(!m_runAudioThread) return; m_runAudioThread = false; if(m_audioThread.joinable()) m_audioThread.join(); } bool Init(bool exclusive) { m_exclusive = exclusive; HRESULT res; const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator); const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator); CoInitialize(nullptr); if(!m_deviceEnumerator) { res = CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void**)&m_deviceEnumerator); if(res != S_OK) throw _com_error(res); m_deviceEnumerator->RegisterEndpointNotificationCallback(&m_notificationClient); } IMMDevice* defaultDevice = nullptr; m_deviceEnumerator->GetDefaultAudioEndpoint(EDataFlow::eRender, ERole::eMultimedia, &defaultDevice); return OpenDevice(defaultDevice); } void CloseDevice() { if(m_audioClient) m_audioClient->Stop(); SAFE_RELEASE(m_device); SAFE_RELEASE(m_audioClient); SAFE_RELEASE(m_audioRenderClient); } IMMDevice* FindDevice(LPCWSTR devId) { assert(m_deviceEnumerator); IMMDevice* newDevice = nullptr; if(m_deviceEnumerator->GetDevice(devId, &newDevice) != S_OK) { SAFE_RELEASE(newDevice); return nullptr; } return newDevice; } bool OpenDevice(LPCWSTR devId) { return OpenDevice(FindDevice(devId)); } bool OpenDevice(IMMDevice* device) { CloseDevice(); if(!device) return OpenNullDevice(); HRESULT res = 0; m_device = device; res = m_device->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr, (void**)&m_audioClient); if(res != S_OK) throw _com_error(res); WAVEFORMATEX* mixFormat = nullptr; res = m_audioClient->GetMixFormat(&mixFormat); if (m_exclusive) { REFERENCE_TIME defaultDevicePeriod, minDevicePeriod; m_audioClient->GetDevicePeriod(&defaultDevicePeriod, &minDevicePeriod); res = m_audioClient->IsFormatSupported(AUDCLNT_SHAREMODE_EXCLUSIVE, mixFormat, NULL); if (res == AUDCLNT_E_UNSUPPORTED_FORMAT) { Log("Default format not supported in exclusive mode, attempting other formats", Logger::Error); int numFormats = 2; WORD formats[2] = { WAVE_FORMAT_PCM, WAVE_FORMAT_IEEE_FLOAT }; int numRates = 5; long sampleRates[5] = {192000L, 96000L, 88200L, 48000L, 44100L}; int numDepths = 3; int bitDepths[3] = {32, 24, 16 }; Vector<WAVEFORMATEX> allFormats; for (size_t f = 0; f < numFormats; f++) { for (size_t d = 0; d < numDepths; d++) { for (size_t r = 0; r < numRates; r++) { long avgBytesPerSec = (bitDepths[d] / 8) * sampleRates[r] * 2; WAVEFORMATEX newformat; newformat.wFormatTag = formats[f]; newformat.nChannels = 2; newformat.nSamplesPerSec = sampleRates[r]; newformat.nAvgBytesPerSec = avgBytesPerSec; newformat.nBlockAlign = 4; newformat.wBitsPerSample = bitDepths[d]; newformat.cbSize = 0; allFormats.Add(newformat); } } } int attemptingFormat = 0; while (res != S_OK) { *mixFormat = allFormats[attemptingFormat]; Logf("Attempting exclusive mode format:\nSample Rate: %dhz,\nBit Depth: %dbit,\nFormat: %s\n-----", Logger::Info, mixFormat->nSamplesPerSec, mixFormat->wBitsPerSample, mixFormat->wFormatTag == WAVE_FORMAT_PCM ? "PCM" : "IEEE FLOAT" ); res = m_audioClient->IsFormatSupported(AUDCLNT_SHAREMODE_EXCLUSIVE, mixFormat, NULL); attemptingFormat++; if (attemptingFormat >= allFormats.size()) { break; } } if (res == S_OK) Log("Format successful", Logger::Info); else Log("No accepted format found", Logger::Error); } res = m_audioClient->Initialize(AUDCLNT_SHAREMODE_EXCLUSIVE, 0, bufferDuration, defaultDevicePeriod, mixFormat, nullptr); } else { res = m_audioClient->Initialize(AUDCLNT_SHAREMODE_SHARED, 0, bufferDuration, 0, mixFormat, nullptr); } m_format = *mixFormat; CoTaskMemFree(mixFormat); if(res != S_OK) { Log("Failed to initialize audio client with the selected settings", Logger::Error); SAFE_RELEASE(device); SAFE_RELEASE(m_audioClient); return false; } res = m_audioClient->GetService(__uuidof(IAudioRenderClient), (void**)&m_audioRenderClient); if(res != S_OK) { Log("Failed to get audio render client service.", Logger::Error); SAFE_RELEASE(device); SAFE_RELEASE(m_audioClient); return false; } m_audioClient->GetBufferSize(&m_numBufferFrames); m_bufferLength = (double)m_numBufferFrames / (double)m_format.nSamplesPerSec; res = m_audioClient->Start(); return true; } bool OpenNullDevice() { m_format.nSamplesPerSec = freq; m_format.nChannels = 2; m_dummyTimer.Restart(); m_dummyTimerPos = 0; return true; } bool NullBegin(float*& buffer, uint32_t& numSamples) { if(m_dummyTimer.Milliseconds() > 2) { m_dummyTimerPos += m_dummyTimer.SecondsAsDouble(); m_dummyTimer.Restart(); uint32 availableSamples = (uint32)(m_dummyTimerPos * (double)m_format.nSamplesPerSec); if(availableSamples > 0) { numSamples = Math::Min(m_dummyBufferLength, availableSamples); m_dummyTimerPos = 0; buffer = m_dummyBuffer; return true; } } return false; } bool Begin(float*& buffer, uint32_t& numSamples) { if(m_pendingDeviceChange) { OpenDevice(m_pendingDevice); m_pendingDeviceChange = false; } if(!m_device) return NullBegin(buffer, numSamples); uint32_t numFramesPadding; m_audioClient->GetCurrentPadding(&numFramesPadding); numSamples = m_numBufferFrames - numFramesPadding; if(numSamples > 0) { HRESULT hr = m_audioRenderClient->GetBuffer(numSamples, (BYTE**)&buffer); if(hr != S_OK) { if(hr == AUDCLNT_E_DEVICE_INVALIDATED) { Logf("Audio device unplugged", Logger::Warning); return false; } else { assert(false); } } return true; } return false; } void End(uint32_t numSamples) { if(!m_device) return; if(numSamples > 0) { m_audioRenderClient->ReleaseBuffer(numSamples, 0); } } void AudioThread() { while(m_runAudioThread) { int32 sleepDuration = 1; float* data; uint32 numSamples; if(Begin(data, numSamples)) { if(m_mixer) m_mixer->Mix(data, numSamples); End(numSamples); } std::this_thread::sleep_for(std::chrono::microseconds(100)); } } }; HRESULT STDMETHODCALLTYPE NotificationClient::OnDeviceStateChanged(_In_ LPCWSTR pwstrDeviceId, _In_ DWORD dwNewState) { return S_OK; } HRESULT STDMETHODCALLTYPE NotificationClient::OnDeviceAdded(_In_ LPCWSTR pwstrDeviceId) { return S_OK; } HRESULT STDMETHODCALLTYPE NotificationClient::OnDeviceRemoved(_In_ LPCWSTR pwstrDeviceId) { return S_OK; } HRESULT STDMETHODCALLTYPE NotificationClient::OnDefaultDeviceChanged(_In_ EDataFlow flow, _In_ ERole role, _In_ LPCWSTR pwstrDefaultDeviceId) { if(flow == EDataFlow::eRender && role == ERole::eMultimedia) { output->m_pendingDeviceChange = true; output->m_pendingDevice = output->FindDevice(pwstrDefaultDeviceId); } return S_OK; } HRESULT STDMETHODCALLTYPE NotificationClient::OnPropertyValueChanged(_In_ LPCWSTR pwstrDeviceId, _In_ const PROPERTYKEY key) { return S_OK; } AudioOutput::AudioOutput() { m_impl = new AudioOutput_Impl(); } AudioOutput::~AudioOutput() { delete m_impl; } bool AudioOutput::Init(bool exclusive) { return m_impl->Init(exclusive); } void AudioOutput::Start(IMixer* mixer) { m_impl->m_mixer = mixer; m_impl->Start(); } void AudioOutput::Stop() { m_impl->Stop(); m_impl->m_mixer = nullptr; } uint32_t AudioOutput::GetNumChannels() const { return m_impl->m_format.nChannels; } uint32_t AudioOutput::GetSampleRate() const { return m_impl->m_format.nSamplesPerSec; } double AudioOutput::GetBufferLength() const { return m_impl->m_bufferLength; } bool AudioOutput::IsIntegerFormat() const { return m_impl->m_format.wFormatTag == WAVE_FORMAT_PCM && m_impl->m_format.wBitsPerSample != 32; } #endif
#include "stdafx.h" #include "AudioOutput.hpp" #include "Shared/Thread.hpp" #ifdef _WIN32 #include "Audioclient.h" #include "Mmdeviceapi.h" #include "comdef.h" #include "Functiondiscoverykeys_devpkey.h" #define REFTIME_NS (100) #define REFTIMES_PER_MICROSEC (1000/REFTIME_NS) #define REFTIMES_PER_MILLISEC (REFTIMES_PER_MICROSEC * 1000) #define REFTIMES_PER_SEC (REFTIMES_PER_MILLISEC * 1000) #define SAFE_RELEASE(punk) \ if ((punk) != NULL) \ { (punk)->Release(); (punk) = nullptr; } static const uint32_t freq = 44100; static const uint32_t channels = 2; static const uint32_t numBuffers = 2; static const uint32_t bufferLength = 10; static const REFERENCE_TIME bufferDuration = (REFERENCE_TIME)(bufferLength * REFTIMES_PER_MILLISEC); class NotificationClient : public IMMNotificationClient { public: class AudioOutput_Impl* output; virtual HRESULT STDMETHODCALLTYPE OnDeviceStateChanged(_In_ LPCWSTR pwstrDeviceId, _In_ DWORD dwNewState); virtual HRESULT STDMETHODCALLTYPE OnDeviceAdded(_In_ LPCWSTR pwstrDeviceId); virtual HRESULT STDMETHODCALLTYPE OnDeviceRemoved(_In_ LPCWSTR pwstrDeviceId); virtual HRESULT STDMETHODCALLTYPE OnDefaultDeviceChanged(_In_ EDataFlow flow, _In_ ERole role, _In_ LPCWSTR pwstrDefaultDeviceId); virtual HRESULT STDMETHODCALLTYPE OnPropertyValueChanged(_In_ LPCWSTR pwstrDeviceId, _In_ const PROPERTYKEY key); virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject) { return E_NOINTERFACE; } virtual ULONG STDMETHODCALLTYPE AddRef(void) { return 0; } virtual ULONG STDMETHODCALLTYPE Release(void) { return 0; } }; class AudioOutput_Impl { public: struct IAudioClient* m_audioClient = nullptr; struct IAudioRenderClient* m_audioRenderClient = nullptr; struct IMMDevice* m_device = nullptr; tWAVEFORMATEX m_format; IMMDeviceEnumerator* m_deviceEnumerator = nullptr; uint32_t m_numBufferFrames; NotificationClient m_notificationClient; double m_bufferLength; static const uint32 m_dummyChannelCount = 2; static const uint32 m_dummyBufferLength = (uint32)((double)freq * 0.2); float m_dummyBuffer[m_dummyBufferLength * m_dummyChannelCount]; double m_dummyTimerPos; Timer m_dummyTimer; IMMDevice* m_pendingDevice = nullptr; bool m_pendingDeviceChange = false; bool m_runAudioThread = false; Thread m_audioThread; IMixer* m_mixer = nullptr; bool m_exclusive = false; public: AudioOutput_Impl() { m_notificationClient.output = this; } ~AudioOutput_Impl() { Stop(); CloseDevice(); SAFE_RELEASE(m_pendingDevice); if(m_deviceEnumerator) { m_deviceEnumerator->UnregisterEndpointNotificationCallback(&m_notificationClient); SAFE_RELEASE(m_deviceEnumerator); } } void Start() { if(m_runAudioThread) return; m_runAudioThread = true; m_audioThread = Thread(&AudioOutput_Impl::AudioThread, this); } void Stop() { if(!m_runAudioThread) return; m_runAudioThread = false; if(m_audioThread.joinable()) m_audioThread.join(); } bool Init(bool exclusive) { m_exclusive = exclusive; HRESULT res; const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator); const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator); CoInitialize(nullptr); if(!m_deviceEnumerator) { res = CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void**)&m_deviceEnumerator); if(res != S_OK) throw _com_error(res); m_deviceEnumerator->RegisterEndpointNotificationCallback(&m_notificationClient); } IMMDevice* defaultDevice = nullptr; m_deviceEnumerator->GetDefaultAudioEndpoint(EDataFlow::eRender, ERole::eMultimedia, &defaultDevice); return OpenDevice(defaultDevice); } void CloseDevice() { if(m_audioClient) m_audioClient->Stop(); SAFE_RELEASE(m_device); SAFE_RELEASE(m_audioClient); SAFE_RELEASE(m_audioRenderClient); } IMMDevice* FindDevice(LPCWSTR devId) { assert(m_deviceEnumerator); IMMDevice* newDevice = nullptr; if(m_deviceEnumerator->GetDevice(devId, &newDevice) != S_OK) { SAFE_RELEASE(newDevice); return nullptr; } return newDevice; } bool OpenDevice(LPCWSTR devId) { return OpenDevice(FindDevice(devId)); } bool OpenDevice(IMMDevice* device) { CloseDevice(); if(!device) return OpenNullDevice(); HRESULT res = 0; m_device = device; res = m_device->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr, (void**)&m_audioClient); if(res != S_OK) throw _com_error(res); WAVEFORMATEX* mixFormat = nullptr; res = m_audioClient->GetMixFormat(&mixFormat); if (m_exclusive) { REFERENCE_TIME defaultDevicePeriod, minDevicePeriod; m_audioClient->GetDevicePeriod(&defaultDevicePeriod, &minDevicePeriod); res = m_audioClient->IsFormatSupported(AUDCLNT_SHAREMODE_EXCLUSIVE, mixFormat, NULL); if (res == AUDCLNT_E_UNSUPPORTED_FORMAT) { Log("Default format not supported in exclusive mode, attempting other formats", Logger::Error); int numFormats = 2; WORD formats[2] = { WAVE_FORMAT_PCM, WAVE_FORMAT_IEEE_FLOAT }; int numRates = 5; long sampleRates[5] = {192000L, 96000L, 88200L, 48000L, 44100L}; int numDepths = 3; int bitDepths[3] = {32, 24, 16 }; Vector<WAVEFORMATEX> allFormats; for (size_t f = 0; f < numFormats; f++) { for (size_t d = 0; d < numDepths; d++) { for (size_t r = 0; r < numRates; r++) { long avgBytesPerSec = (bitDepths[d] / 8) * sampleRates[r] * 2; WAVEFORMATEX newformat; newformat.wFormatTag = formats[f]; newformat.nChannels = 2; newformat.nSamplesPerSec = sampleRates[r]; newformat.nAvgBytesPerSec = avgBytesPerSec; newformat.nBlockAlign = 4; newformat.wBitsPerSample = bitDepths[d]; newformat.cbSize = 0; allFormats.Add(newformat); } } } int attemptingFormat = 0; while (res != S_OK) { *mixFormat = allFormats[attemptingFormat];
; res = m_audioClient->IsFormatSupported(AUDCLNT_SHAREMODE_EXCLUSIVE, mixFormat, NULL); attemptingFormat++; if (attemptingFormat >= allFormats.size()) { break; } } if (res == S_OK) Log("Format successful", Logger::Info); else Log("No accepted format found", Logger::Error); } res = m_audioClient->Initialize(AUDCLNT_SHAREMODE_EXCLUSIVE, 0, bufferDuration, defaultDevicePeriod, mixFormat, nullptr); } else { res = m_audioClient->Initialize(AUDCLNT_SHAREMODE_SHARED, 0, bufferDuration, 0, mixFormat, nullptr); } m_format = *mixFormat; CoTaskMemFree(mixFormat); if(res != S_OK) { Log("Failed to initialize audio client with the selected settings", Logger::Error); SAFE_RELEASE(device); SAFE_RELEASE(m_audioClient); return false; } res = m_audioClient->GetService(__uuidof(IAudioRenderClient), (void**)&m_audioRenderClient); if(res != S_OK) { Log("Failed to get audio render client service.", Logger::Error); SAFE_RELEASE(device); SAFE_RELEASE(m_audioClient); return false; } m_audioClient->GetBufferSize(&m_numBufferFrames); m_bufferLength = (double)m_numBufferFrames / (double)m_format.nSamplesPerSec; res = m_audioClient->Start(); return true; } bool OpenNullDevice() { m_format.nSamplesPerSec = freq; m_format.nChannels = 2; m_dummyTimer.Restart(); m_dummyTimerPos = 0; return true; } bool NullBegin(float*& buffer, uint32_t& numSamples) { if(m_dummyTimer.Milliseconds() > 2) { m_dummyTimerPos += m_dummyTimer.SecondsAsDouble(); m_dummyTimer.Restart(); uint32 availableSamples = (uint32)(m_dummyTimerPos * (double)m_format.nSamplesPerSec); if(availableSamples > 0) { numSamples = Math::Min(m_dummyBufferLength, availableSamples); m_dummyTimerPos = 0; buffer = m_dummyBuffer; return true; } } return false; } bool Begin(float*& buffer, uint32_t& numSamples) { if(m_pendingDeviceChange) { OpenDevice(m_pendingDevice); m_pendingDeviceChange = false; } if(!m_device) return NullBegin(buffer, numSamples); uint32_t numFramesPadding; m_audioClient->GetCurrentPadding(&numFramesPadding); numSamples = m_numBufferFrames - numFramesPadding; if(numSamples > 0) { HRESULT hr = m_audioRenderClient->GetBuffer(numSamples, (BYTE**)&buffer); if(hr != S_OK) { if(hr == AUDCLNT_E_DEVICE_INVALIDATED) { Logf("Audio device unplugged", Logger::Warning); return false; } else { assert(false); } } return true; } return false; } void End(uint32_t numSamples) { if(!m_device) return; if(numSamples > 0) { m_audioRenderClient->ReleaseBuffer(numSamples, 0); } } void AudioThread() { while(m_runAudioThread) { int32 sleepDuration = 1; float* data; uint32 numSamples; if(Begin(data, numSamples)) { if(m_mixer) m_mixer->Mix(data, numSamples); End(numSamples); } std::this_thread::sleep_for(std::chrono::microseconds(100)); } } }; HRESULT STDMETHODCALLTYPE NotificationClient::OnDeviceStateChanged(_In_ LPCWSTR pwstrDeviceId, _In_ DWORD dwNewState) { return S_OK; } HRESULT STDMETHODCALLTYPE NotificationClient::OnDeviceAdded(_In_ LPCWSTR pwstrDeviceId) { return S_OK; } HRESULT STDMETHODCALLTYPE NotificationClient::OnDeviceRemoved(_In_ LPCWSTR pwstrDeviceId) { return S_OK; } HRESULT STDMETHODCALLTYPE NotificationClient::OnDefaultDeviceChanged(_In_ EDataFlow flow, _In_ ERole role, _In_ LPCWSTR pwstrDefaultDeviceId) { if(flow == EDataFlow::eRender && role == ERole::eMultimedia) { output->m_pendingDeviceChange = true; output->m_pendingDevice = output->FindDevice(pwstrDefaultDeviceId); } return S_OK; } HRESULT STDMETHODCALLTYPE NotificationClient::OnPropertyValueChanged(_In_ LPCWSTR pwstrDeviceId, _In_ const PROPERTYKEY key) { return S_OK; } AudioOutput::AudioOutput() { m_impl = new AudioOutput_Impl(); } AudioOutput::~AudioOutput() { delete m_impl; } bool AudioOutput::Init(bool exclusive) { return m_impl->Init(exclusive); } void AudioOutput::Start(IMixer* mixer) { m_impl->m_mixer = mixer; m_impl->Start(); } void AudioOutput::Stop() { m_impl->Stop(); m_impl->m_mixer = nullptr; } uint32_t AudioOutput::GetNumChannels() const { return m_impl->m_format.nChannels; } uint32_t AudioOutput::GetSampleRate() const { return m_impl->m_format.nSamplesPerSec; } double AudioOutput::GetBufferLength() const { return m_impl->m_bufferLength; } bool AudioOutput::IsIntegerFormat() const { return m_impl->m_format.wFormatTag == WAVE_FORMAT_PCM && m_impl->m_format.wBitsPerSample != 32; } #endif
Logf("Attempting exclusive mode format:\nSample Rate: %dhz,\nBit Depth: %dbit,\nFormat: %s\n-----", Logger::Info, mixFormat->nSamplesPerSec, mixFormat->wBitsPerSample, mixFormat->wFormatTag == WAVE_FORMAT_PCM ? "PCM" : "IEEE FLOAT" )
call_expression
[ { "content": "struct StaticBinding : public IFunctionBinding<R, A...>\n\n{\n\n\tStaticBinding(R(*func)(A...)) : func(func) {};\n\n\tvirtual R Call(A... args) override\n\n\t{\n\n\t\treturn (*func)(args...);\n\n\t}\n\n\tR(*func)(A...);\n\n};\n\n\n\n/* Lambda function binding */\n\ntemplate<typename T, typename R, typename... A>\n", "file_path": "Shared/include/Shared/Bindable.hpp", "rank": 0, "score": 305108.3890215333 }, { "content": "class Thread : public std::thread\n\n{\n\npublic:\n\n\tusing std::thread::thread;\n\n\tsize_t SetAffinityMask(size_t affinityMask);\n\n\tstatic size_t SetCurrentThreadAffinityMask(size_t affinityMask);\n\n};\n\n\n\n/* \n\n\tMutex class to fit program naming convention\n\n*/\n", "file_path": "Shared/include/Shared/Thread.hpp", "rank": 1, "score": 303867.5241522651 }, { "content": "class AudioOutput : public Unique\n\n{\n\npublic:\n\n\tAudioOutput();\n\n\t~AudioOutput();\n\n\n\n\tbool Init(bool exclusive);\n\n\n\n\t// Safe to start mixing\n\n\tvoid Start(IMixer* mixer);\n\n\t// Should stop mixing\n\n\tvoid Stop();\n\n\n\n\tuint32_t GetNumChannels() const;\n\n\tuint32_t GetSampleRate() const;\n\n\n\n\t// The actual length of the buffer in seconds\n\n\tdouble GetBufferLength() const;\n\n\tbool IsIntegerFormat() const;\n\n\n\nprivate:\n", "file_path": "Audio/include/Audio/AudioOutput.hpp", "rank": 2, "score": 267233.0534797101 }, { "content": "struct ConstantBinding : public IFunctionBinding<R, A...>\n\n{\n\n\tConstantBinding(const R& value) : value(value) {};\n\n\tvirtual R Call(A...) override\n\n\t{\n\n\t\treturn value;\n\n\t}\n\n\tR value;\n\n};", "file_path": "Shared/include/Shared/Bindable.hpp", "rank": 3, "score": 253996.92080109974 }, { "content": "struct LambdaBinding : public IFunctionBinding<R, A...>\n\n{\n\n\t// Copies the given lambda\n\n\tLambdaBinding(T&& lambda) : lambda(std::forward<T>(lambda)) {};\n\n\tvirtual R Call(A... args) override\n\n\t{\n\n\t\treturn lambda(args...);\n\n\t}\n\n\tT lambda;\n\n};\n\n\n\n/* Constant return value binding */\n\ntemplate<typename R, typename... A>\n", "file_path": "Shared/include/Shared/Bindable.hpp", "rank": 4, "score": 253996.92080109974 }, { "content": "struct ObjectBinding : public IFunctionBinding<R, A...>\n\n{\n\n\tObjectBinding(Class* object, R (Class::*func)(A...)) : object(object), func(func) {};\n\n\tvirtual R Call(A... args) override\n\n\t{\n\n\t\treturn ((object)->*func)(args...);\n\n\t}\n\n\n\n\tClass* object;\n\n\tR (Class::*func)(A...);\n\n};\n\n\n\n/* Static function binding */\n\ntemplate<typename R, typename... A>\n", "file_path": "Shared/include/Shared/Bindable.hpp", "rank": 5, "score": 253996.92080109974 }, { "content": "class TapeStopDSP : public DSP\n\n{\n\npublic:\n\n\tvoid SetLength(double length);\n\n\n\n\tvirtual void Process(float* out, uint32 numSamples);\n\nprivate:\n\n\tuint32 m_length = 0;\n\n\tVector<float> m_sampleBuffer;\n\n\tfloat m_sampleIdx = 0.0f;\n\n\tuint32 m_lastSample = 0;\n\n\tuint32 m_currentSample = 0;\n\n};\n\n\n", "file_path": "Audio/include/Audio/DSP.hpp", "rank": 6, "score": 252877.94378196896 }, { "content": "class Timer\n\n{\n\npublic:\n\n\tTimer() : m_start(std::chrono::high_resolution_clock::now()) {}\n\n\ttemplate<typename rep, typename period> Timer(std::chrono::duration<rep, period> duration) : m_start(std::chrono::high_resolution_clock::now())\n\n\t{\n\n\t\tm_start -= duration;\n\n\t}\n\n\ttemplate<typename rep, typename period> Timer& operator=(std::chrono::duration<rep, period> duration)\n\n\t{\n\n\t\tRestart();\n\n\t\tm_start -= duration;\n\n\t\treturn *this;\n\n\t}\n\n\n\n\tinline void Restart()\n\n\t{\n\n\t\tm_start = std::chrono::high_resolution_clock::now();\n\n\t}\n\n\n", "file_path": "Shared/include/Shared/Timer.hpp", "rank": 7, "score": 252633.7852598375 }, { "content": "class Mutex : public std::mutex\n\n{\n\n};", "file_path": "Shared/include/Shared/Thread.hpp", "rank": 8, "score": 251526.88226587066 }, { "content": "class BoolConfigEntry : public IConfigEntry\n\n{\n\npublic:\n\n\tbool data;\n\npublic:\n\n\tvirtual String ToString() const override;\n\n\tvirtual void FromString(const String& str) override;\n\n\tEntryType GetType() override { return EntryType::Boolean; };\n\n};\n\n\n", "file_path": "Shared/include/Shared/ConfigEntry.hpp", "rank": 9, "score": 243456.04848374793 }, { "content": "class FloatConfigEntry : public IConfigEntry\n\n{\n\npublic:\n\n\tfloat data;\n\npublic:\n\n\tvirtual String ToString() const override;\n\n\tvirtual void FromString(const String& str) override;\n\n\tEntryType GetType() override { return EntryType::Float; };\n\n};\n\n\n", "file_path": "Shared/include/Shared/ConfigEntry.hpp", "rank": 10, "score": 243446.7167210381 }, { "content": "class IntConfigEntry : public IConfigEntry\n\n{\n\npublic:\n\n\tint32 data;\n\npublic:\n\n\tvirtual String ToString() const override;\n\n\tvirtual void FromString(const String& str) override;\n\n\tEntryType GetType() override { return EntryType::Integer; };\n\n};\n\n\n", "file_path": "Shared/include/Shared/ConfigEntry.hpp", "rank": 11, "score": 243424.17324006784 }, { "content": "\tclass AudioOutput_Impl* m_impl;\n\n};\n", "file_path": "Audio/include/Audio/AudioOutput.hpp", "rank": 12, "score": 224036.51733273987 }, { "content": "class Color : public Vector4\n\n{\n\npublic:\n\n\tusing Vector4::Vector4;\n\n\tColor() = default;\n\n\t// Constructor with alpha=1\n\n\tColor(float all);\n\n\t// Constructor with alpha=1\n\n\tColor(float r, float g, float b);\n\n\tColor(const VectorMath::VectorBase<uint8, 4>& icolor);\n\n\tbool operator ==(const Color& other);\n\n\tbool operator !=(const Color& other);\n\n\tColori ToRGBA8() const;\n\n\t// Returns the same color, but with a different alpha value\n\n\tColor WithAlpha(float a) const;\n\n\t// Color from hue, saturation and value\n\n\tstatic Color FromHSV(float hue, float saturation, float value);\n\n\n\n\tstatic const Color White;\n\n\tstatic const Color Black;\n\n\tstatic const Color Red;\n\n\tstatic const Color Green;\n\n\tstatic const Color Blue;\n\n\tstatic const Color Yellow;\n\n\tstatic const Color Magenta;\n\n\tstatic const Color Cyan;\n\n};\n\n\n\n ", "file_path": "Shared/include/Shared/Color.hpp", "rank": 13, "score": 208304.31512383584 }, { "content": "class Beatmap : public Unique\n\n{\n\npublic:\n\n\tvirtual ~Beatmap();\n\n\tBeatmap() = default;\n\n\tBeatmap(Beatmap&& other);\n\n\tBeatmap& operator=(Beatmap&& other);\n\n\n\n\tbool Load(BinaryStream& input, bool metadataOnly = false);\n\n\t// Saves the map as it's own format\n\n\tbool Save(BinaryStream& output) const;\n\n\n\n\t// Returns the settings of the map, contains metadata + song/image paths.\n\n\tconst BeatmapSettings& GetMapSettings() const;\n\n\n\n\t// Vector of timing points in the map, sorted by when they appear in the map\n\n\t// Must keep the beatmap class instance alive for these to stay valid\n\n\t// Can contain multiple objects at the same time\n\n\tconst Vector<TimingPoint*>& GetLinearTimingPoints() const;\n\n\t// Vector of chart stops in the chart, sorted by when they appear in the map\n", "file_path": "Beatmap/include/Beatmap/Beatmap.hpp", "rank": 14, "score": 208304.31512383587 }, { "content": "// Biquad Filter\n\n// Thanks to https://www.youtube.com/watch?v=FnpkBE4kJ6Q&list=WL&index=8 for the explanation\n\n// Also http://www.musicdsp.org/files/Audio-EQ-Cookbook.txt for the coefficient formulas\n\nclass BQFDSP : public DSP\n\n{\n\npublic:\n\n\tfloat b0 = 1.0f;\n\n\tfloat b1 = 0.0f;\n\n\tfloat b2 = 0.0f;\n\n\tfloat a0 = 1.0f;\n\n\tfloat a1 = 0.0f;\n\n\tfloat a2 = 0.0f;\n\n\n\n\tvirtual void Process(float* out, uint32 numSamples);\n\n\n\n\t// Sets the filter parameters\n\n\tvoid SetPeaking(float q, float freq, float gain);\n\n\tvoid SetLowPass(float q, float freq);\n\n\tvoid SetHighPass(float q, float freq);\n\n\n\n\tvoid SetPeaking(float q, float freq, float gain, float sampleRate);\n\n\tvoid SetLowPass(float q, float freq, float sampleRate);\n\n\tvoid SetHighPass(float q, float freq, float sampleRate);\n\nprivate:\n\n\t// Delayed samples\n\n\tstatic const uint32 order = 2;\n\n\t// FIR Delay buffers\n\n\tfloat zb[2][order];\n\n\t// IIR Delay buffers\n\n\tfloat za[2][order];\n\n};\n\n\n", "file_path": "Audio/include/Audio/DSP.hpp", "rank": 15, "score": 208304.31512383584 }, { "content": "class Database : public Unique\n\n{\n\npublic:\n\n\t~Database();\n\n\tvoid Close();\n\n\tbool Open(const String& path);\n\n\tDBStatement Query(const String& queryString);\n\n\tbool Exec(const String& queryString);\n\n\tbool ExecDirect(const String& queryString);\n\n\n\n\tstruct sqlite3* db = nullptr;\n\n};\n", "file_path": "Beatmap/include/Beatmap/Database.hpp", "rank": 16, "score": 208304.31512383584 }, { "content": "class Action : public Unique\n\n{\n\npublic:\n\n\tAction() = default;\n\n\tAction(R(*staticFunction)(A...))\n\n\t{\n\n\t\tm_binding = new StaticBinding<R, A...>(staticFunction);\n\n\t}\n\n\ttemplate<typename L>\n\n\tAction(L&& lambda)\n\n\t{\n\n\t\tm_binding = new LambdaBinding<L, R, A...>(std::forward<L>(lambda));\n\n\t}\n\n\tAction(Action&& other)\n\n\t{\n\n\t\tm_binding = other.m_binding;\n\n\t\tother.m_binding = nullptr;\n\n\t}\n\n\tAction& operator=(Action&& other)\n\n\t{\n", "file_path": "Shared/include/Shared/Action.hpp", "rank": 17, "score": 208304.31512383587 }, { "content": "\tclass File_Impl* m_impl = nullptr;\n\npublic:\n\n\tFile();\n\n\t~File();\n\n\n\n\tbool OpenRead(const String& path);\n\n\tbool OpenWrite(const String& path, bool append = false, bool noLog = false);\n\n\tvoid Close();\n\n\t// Seek from file start\n\n\tvoid Seek(size_t pos);\n\n\t// Seek from current position\n\n\tvoid Skip(int64 pos);\n\n\t// Seek from the end of the file\n\n\tvoid SeekReverse(size_t pos);\n\n\tsize_t Tell() const;\n\n\tsize_t GetSize() const;\n\n\tsize_t Read(void* data, size_t len);\n\n\tsize_t Write(const void* data, size_t len);\n\n\n\n\t// Get the last write time of the file\n", "file_path": "Shared/include/Shared/File.hpp", "rank": 18, "score": 204492.45301520333 }, { "content": "\t\tclass Particle* m_particles = nullptr;\n\n\t\tuint32 m_poolSize = 0;\n\n\n\n\t\t// Particle parameters private\n\n#define PARTICLE_PARAMETER(__name, __type)\\\n\n\tIParticleParameter<__type>* m_param_##__name = nullptr;\n\n#include <Graphics/ParticleParameters.hpp>\n\n\t};\n\n}", "file_path": "Graphics/include/Graphics/ParticleEmitter.hpp", "rank": 19, "score": 204492.45301520333 }, { "content": "class JobBase : public Unique\n\n{\n\npublic:\n\n\tvirtual ~JobBase() = default;\n\n\n\n\tbool IsFinished() const;\n\n\tbool IsSuccessfull() const;\n\n\tbool IsQueued() const;\n\n\n\n\t// Either cancel this job or wait till it finished if it is already being processed\n\n\tvoid Terminate();\n\n\t\n\n\t// Flags for jobs\n\n\t// make sure to add the IO flag if this job performs file operations\n\n\tJobFlags jobFlags = JobFlags::None;\n\n\n\n\t// Performs the task to be done, returns success\n\n\tvirtual bool Run() = 0;\n\n\t// Called on the main thread before the delegate callback\n\n\tvirtual void Finalize();\n", "file_path": "Shared/include/Shared/Jobs.hpp", "rank": 21, "score": 204334.74569569615 }, { "content": "class WobbleDSP : public BQFDSP\n\n{\n\npublic:\n\n\tvoid SetLength(double length);\n\n\n\n\t// Frequency range\n\n\tfloat fmin = 500.0f;\n\n\tfloat fmax = 20000.0f;\n\n\tfloat q = 1.414f;\n\n\n\n\tvirtual void Process(float* out, uint32 numSamples);\n\nprivate:\n\n\tuint32 m_length;\n\n\tuint32 m_currentSample = 0;\n\n};\n\n\n", "file_path": "Audio/include/Audio/DSP.hpp", "rank": 22, "score": 204334.74569569615 }, { "content": "class Config : public ConfigBase\n\n{\n\npublic:\n\n\ttypedef typename EnumClass::EnumType KeyType;\n\n\tConfig()\n\n\t{\n\n\t\tfor(auto it : EnumClass::GetMap())\n\n\t\t{\n\n\t\t\tm_keys.Add(it.second, (uint32)it.first);\n\n\t\t\tm_reverseKeys.Add((uint32)it.first, it.second);\n\n\t\t}\n\n\t}\n\n\tbool IsSet(KeyType key) const\n\n\t{\n\n\t\tauto it = m_entries.find((uint32)key);\n\n\t\treturn it != m_entries.end();\n\n\t}\n\n\n\n\tint32 GetInt(KeyType key) const\n\n\t{\n", "file_path": "Shared/include/Shared/Config.hpp", "rank": 23, "score": 204334.74569569615 }, { "content": "class GateDSP : public DSP\n\n{\n\npublic:\n\n\t// The amount of time for a single cycle in samples\n\n\tvoid SetLength(double length);\n\n\tvoid SetGating(float gating);\n\n\n\n\t// Low volume\n\n\tfloat low = 0.1f;\n\n\n\n\tvirtual void Process(float* out, uint32 numSamples);\n\nprivate:\n\n\tfloat m_gating = 0.5f;\n\n\tuint32 m_length = 0;\n\n\tuint32 m_fadeIn = 0; // Fade In mark\n\n\tuint32 m_fadeOut = 0; // Fade Out mark\n\n\tuint32 m_halfway; // Halfway mark\n\n\tuint32 m_currentSample = 0;\n\n};\n\n\n", "file_path": "Audio/include/Audio/DSP.hpp", "rank": 24, "score": 204334.74569569615 }, { "content": "class FlangerDSP : public DSP\n\n{\n\npublic:\n\n\tvoid SetLength(double length);\n\n\tvoid SetDelayRange(uint32 min, uint32 max);\n\n\n\n\tvirtual void Process(float* out, uint32 numSamples);\n\nprivate:\n\n\tuint32 m_length = 0;\n\n\n\n\t// Delay range\n\n\tuint32 m_min = 0;\n\n\tuint32 m_max = 0;\n\n\n\n\tVector<float> m_sampleBuffer;\n\n\tuint32 m_time = 0;\n\n\tuint32 m_bufferLength = 0;\n\n\tsize_t m_bufferOffset = 0;\n\n};\n\n\n", "file_path": "Audio/include/Audio/DSP.hpp", "rank": 25, "score": 204334.74569569615 }, { "content": "// Basic limiter\n\nclass LimiterDSP : public DSP\n\n{\n\npublic:\n\n\tfloat releaseTime = 0.1f;\n\n\tvirtual void Process(float* out, uint32 numSamples);\n\nprivate:\n\n\tfloat m_currentMaxVolume = 1.0f;\n\n\tfloat m_currentReleaseTimer = releaseTime;\n\n};\n\n\n", "file_path": "Audio/include/Audio/DSP.hpp", "rank": 26, "score": 204334.74569569615 }, { "content": "// Referenced http://www.musicdsp.org/files/phaser.cpp\n\nclass PhaserDSP : public DSP\n\n{ \n\npublic:\n\n\tuint32 time = 0;\n\n\n\n\t// Frequency range\n\n\tfloat dmin = 1000.0f;\n\n\tfloat dmax = 4000.0f;\n\n\tfloat fb = 0.2f; //feedback\n\n\tfloat lmix = 0.33f; //local mix\n\n\n\n\tvoid SetLength(double length);\n\n\n\n\tvirtual void Process(float* out, uint32 numSamples);\n\n\n\nprivate:\n\n\tuint32 m_length = 0;\n\n\n\n\t// All pass filter\n\n\tstruct APF\n\n\t{\n\n\t\tfloat Update(float in);\n\n\t\tfloat a1 = 0.0f;\n\n\t\tfloat za = 0.0f;\n\n\t};\n\n\n\n\tAPF filters[2][6];\n\n\tfloat za[2] = { 0.0f };\n\n};\n\n\n", "file_path": "Audio/include/Audio/DSP.hpp", "rank": 27, "score": 204334.74569569615 }, { "content": "class RetriggerDSP : public DSP\n\n{\n\npublic:\n\n\tvoid SetLength(double length);\n\n\tvoid SetResetDuration(uint32 resetDuration);\n\n\tvoid SetGating(float gating);\n\n\tvoid SetMaxLength(uint32 length);\n\n\n\n\tvirtual void Process(float* out, uint32 numSamples);\n\nprivate:\n\n\tfloat m_gating = 0.75f;\n\n\tuint32 m_length = 0;\n\n\tuint32 m_gateLength = 0;\n\n\tuint32 m_resetDuration = 0;\n\n\tVector<float> m_sampleBuffer;\n\n\tuint32 m_loops = 0;\n\n\tuint32 m_currentSample = 0;\n\n\tbool m_bufferReserved = false;\n\n};\n\n\n", "file_path": "Audio/include/Audio/DSP.hpp", "rank": 28, "score": 204334.74569569615 }, { "content": "class EchoDSP : public DSP\n\n{\n\npublic:\n\n\tvoid SetLength(double length);\n\n\n\n\tfloat feedback = 0.6f;\n\n\n\n\tvirtual void Process(float* out, uint32 numSamples);\n\nprivate:\n\n\tuint32 m_bufferLength = 0;\n\n\tsize_t m_bufferOffset = 0;\n\n\tuint32 m_numLoops = 0;\n\n\tVector<float> m_sampleBuffer;\n\n};\n\n\n\n\n", "file_path": "Audio/include/Audio/DSP.hpp", "rank": 29, "score": 204334.74569569615 }, { "content": "class CopyableBuffer : public Buffer\n\n{\n\npublic:\n\n\tusing Buffer::Buffer;\n\n\tCopyableBuffer() = default;\n\n\tCopyableBuffer(const CopyableBuffer& rhs);\n\n\tCopyableBuffer& operator=(const CopyableBuffer& rhs);\n\n};", "file_path": "Shared/include/Shared/Buffer.hpp", "rank": 30, "score": 204334.74569569615 }, { "content": "class DBStatement : public Unique\n\n{\n\npublic:\n\n\tDBStatement(DBStatement&& other);\n\n\t~DBStatement();\n\n\tbool Step();\n\n\tbool StepRow();\n\n\tvoid Rewind();\n\n\tvoid Finish();\n\n\tint32 IntColumn(int32 index = 0) const;\n\n\tint64 Int64Column(int32 index = 0) const;\n\n\tdouble DoubleColumn(int32 index = 0) const;\n\n\tString StringColumn(int32 index = 0) const;\n\n\tString StringColumnEmptyOnNull(int32 index = 0) const;\n\n\tBuffer BlobColumn(int32 index = 0) const;\n\n\tvoid BindInt(int32 index, const int32& value);\n\n\tvoid BindInt64(int32 index, const int64& value);\n\n\tvoid BindDouble(int32 index, const double& value);\n\n\tvoid BindString(int32 index, const String& value);\n\n\tvoid BindBlob(int32 index, const Buffer& value);\n", "file_path": "Beatmap/include/Beatmap/Database.hpp", "rank": 31, "score": 204334.74569569615 }, { "content": "class JobSheduler : public Unique\n\n{\n\npublic:\n\n\tJobSheduler();\n\n\t~JobSheduler();\n\n\n\n\t// Runs callbacks on finished tasks on the main thread\n\n\t// should thus be called from the main thread only\n\n\tvoid Update();\n\n\n\n\t// Queue job\n\n\tbool Queue(Job job);\n\n\n\nprivate:\n", "file_path": "Shared/include/Shared/Jobs.hpp", "rank": 32, "score": 204334.74569569615 }, { "content": "class ConfigBase : public Unique\n\n{\n\npublic:\n\n\tvirtual ~ConfigBase();\n\n\n\n\t// Load from text file\n\n\tbool Load(BinaryStream& stream);\n\n\tbool Load(const String& path);\n\n\t// Save to text file\n\n\tvoid Save(BinaryStream& stream);\n\n\tbool Save(const String& path);\n\n\n\n\tbool IsDirty() const;\n\n\n\n\t// Resets config back to default state\n\n\tvoid Clear();\n\n\n\nprotected:\n\n\tConfigBase();\n\n\tvirtual void InitDefaults() = 0;\n", "file_path": "Shared/include/Shared/Config.hpp", "rank": 33, "score": 204334.74569569615 }, { "content": "class PanDSP : public DSP\n\n{\n\npublic:\n\n\t// -1 to 1 LR pan value\n\n\tfloat panning = 0.0f;\n\n\tvirtual void Process(float* out, uint32 numSamples);\n\n};\n\n\n", "file_path": "Audio/include/Audio/DSP.hpp", "rank": 34, "score": 204334.74569569615 }, { "content": "class SidechainDSP : public DSP\n\n{\n\npublic:\n\n\t// Set sidechain length in samples\n\n\tvoid SetLength(double length);\n\n\n\n\t// Volume multiplier for the sidechaing\n\n\tfloat amount = 0.25f;\n\n\n\n\tInterpolation::CubicBezier curve;\n\n\n\n\tvirtual void Process(float* out, uint32 numSamples);\n\nprivate:\n\n\tuint32 m_length = 0;\n\n\tsize_t m_time = 0;\n\n};\n\n\n", "file_path": "Audio/include/Audio/DSP.hpp", "rank": 35, "score": 204334.74569569615 }, { "content": "class IMixer\n\n{\n\npublic:\n\n\tvirtual void Mix(void* data, uint32& numSamples) = 0;\n\n};\n\n\n\n/*\n\n\tLow level audio output\n\n*/\n", "file_path": "Audio/include/Audio/AudioOutput.hpp", "rank": 36, "score": 201234.43517847723 }, { "content": "\t\tclass OpenGL* m_ogl = nullptr;\n\n\t};\n\n}", "file_path": "Graphics/include/Graphics/RenderQueue.hpp", "rank": 37, "score": 200708.92067569756 }, { "content": "\tclass LimiterDSP* limiter = nullptr;\n\n\n\n\t// Used to limit rendering to a fixed number of samples (512)\n\n\tfloat* m_sampleBuffer = nullptr;\n\n\tuint32 m_sampleBufferLength = 384;\n\n\tuint32 m_remainingSamples = 0;\n\n\n\n\tthread audioThread;\n\n\tbool runAudioThread = false;\n\n\tAudioOutput* output = nullptr;\n\n};", "file_path": "Audio/include/Audio/Audio_Impl.hpp", "rank": 38, "score": 200708.92067569756 }, { "content": "\tclass JobSheduler_Impl* m_sheduler = nullptr;\n\n\tfriend class JobSheduler_Impl;\n\n};\n\n\n\n/*\n\n\tJob that runs a lambda that returns a boolean\n\n*/\n\ntemplate<typename Lambda, typename... Args>\n", "file_path": "Shared/include/Shared/Jobs.hpp", "rank": 39, "score": 200708.92067569756 }, { "content": "\tclass Audio_Impl* audio = nullptr;\n\nprivate:\n\n\tfloat m_volume = 1.0f;\n\n};", "file_path": "Audio/include/Audio/AudioBase.hpp", "rank": 40, "score": 200708.92067569756 }, { "content": "class BitCrusherDSP : public DSP\n\n{\n\npublic:\n\n\t// Duration of samples, <1 = disable\n\n\tvoid SetPeriod(float period = 0);\n\n\tvirtual void Process(float* out, uint32 numSamples);\n\nprivate:\n\n\tuint32 m_period = 1;\n\n\tuint32 m_increment = 0;\n\n\tfloat m_sampleBuffer[2] = { 0.0f };\n\n\tuint32 m_currentDuration = 0;\n\n};\n\n\n", "file_path": "Audio/include/Audio/DSP.hpp", "rank": 41, "score": 200553.41907453802 }, { "content": "class Audio_Impl : public IMixer\n\n{\n\npublic:\n\n\tvoid Start();\n\n\tvoid Stop();\n\n\t// Get samples\n\n\tvirtual void Mix(void* data, uint32& numSamples) override;\n\n\t// Registers an AudioBase to be rendered\n\n\tvoid Register(AudioBase* audio);\n\n\t// Removes an AudioBase so it is no longer rendered\n\n\tvoid Deregister(AudioBase* audio);\n\n\n\n\tuint32 GetSampleRate() const;\n\n\tdouble GetSecondsPerSample() const;\n\n\n\n\tfloat globalVolume = 1.0f;\n\n\n\n\tmutex lock;\n\n\tVector<AudioBase*> itemsToRender;\n\n\tVector<DSP*> globalDSPs;\n\n\n", "file_path": "Audio/include/Audio/Audio_Impl.hpp", "rank": 42, "score": 200553.41907453802 }, { "content": "class MapDatabase : public Unique\n\n{\n\npublic:\n\n\tMapDatabase();\n\n\t~MapDatabase();\n\n\n\n\t// Checks the background scanning and actualized the current map database\n\n\tvoid Update();\n\n\n\n\tbool IsSearching() const;\n\n\tvoid StartSearching();\n\n\tvoid StopSearching();\n\n\n\n\t// Grab all the maps, with their id's\n\n\tMap<int32, MapIndex*> GetMaps();\n\n\t// Finds maps using the search query provided\n\n\t// search artist/title/tags for maps for any space separated terms\n\n\tMap<int32, MapIndex*> FindMaps(const String& search);\n\n\tMap<int32, MapIndex*> FindMapsByHash(const String& hash);\n\n\tMap<int32, MapIndex*> FindMapsByFolder(const String& folder);\n", "file_path": "Beatmap/include/Beatmap/MapDatabase.hpp", "rank": 43, "score": 200553.41907453802 }, { "content": "class LambdaJob : public JobBase\n\n{\n\npublic:\n\n\tLambdaJob(Lambda& lambda, Args... args) : m_lambda(lambda)\n\n\t{\n\n\t\tm_args = { args... };\n\n\t}\n\n\tvirtual bool Run()\n\n\t{\n\n\t\treturn m_CallFunc(std::index_sequence_for<Args...>{});\n\n\t}\n\n\n\nprivate:\n\n\ttemplate<size_t... I>\n\n\tbool m_CallFunc(std::index_sequence<I...>)\n\n\t{\n\n\t\treturn m_lambda(std::get<I>(m_args)...);\n\n\t}\n\n\n\n\tstd::tuple<Args...> m_args;\n", "file_path": "Shared/include/Shared/Jobs.hpp", "rank": 44, "score": 200553.41907453802 }, { "content": "class RefCounted : public IRefCounted\n\n{\n\npublic:\n\n\t// Can be used for objects allocated with new to get a reference counted handle to this object\n\n\tRef<T> MakeShared()\n\n\t{\n\n\t\treturn Ref<T>((T*)this, _GetRefCounter());\n\n\t}\n\n};\n\n\n\n\n\n// Possibly assign reference counter in RefCounted object\n\ntemplate<typename T, bool> struct RefCounterHelper\n\n{\n\n\tstatic void Assign(T* obj, int32* counter)\n\n\t{\n\n\t}\n\n\tstatic int32* CreateCounter(T* obj)\n\n\t{\n\n\t\treturn new int32(0);\n", "file_path": "Shared/include/Shared/Ref.hpp", "rank": 45, "score": 200553.41907453802 }, { "content": "\tclass RenderQueue : public Unique\n\n\t{\n\n\tpublic:\n\n\t\tRenderQueue() = default;\n\n\t\tRenderQueue(OpenGL* ogl, const RenderState& rs);\n\n\t\tRenderQueue(RenderQueue&& other);\n\n\t\tRenderQueue& operator=(RenderQueue&& other);\n\n\t\t~RenderQueue();\n\n\t\t// Processes all render commands\n\n\t\tvoid Process(bool clearQueue = true);\n\n\t\t// Clears all the render commands in the queue\n\n\t\tvoid Clear();\n\n\t\tvoid Draw(Transform worldTransform, Mesh m, Material mat, const MaterialParameterSet& params = MaterialParameterSet());\n\n\t\tvoid Draw(Transform worldTransform, Ref<class TextRes> text, Material mat, const MaterialParameterSet& params = MaterialParameterSet());\n\n\t\tvoid DrawScissored(Rect scissor, Transform worldTransform, Mesh m, Material mat, const MaterialParameterSet& params = MaterialParameterSet());\n\n\t\tvoid DrawScissored(Rect scissor, Transform worldTransform, Ref<class TextRes> text, Material mat, const MaterialParameterSet& params = MaterialParameterSet());\n\n\n\n\t\t// Draw for lines/points with point size parameter\n\n\t\tvoid DrawPoints(Mesh m, Material mat, const MaterialParameterSet& params, float pointSize);\n\n\n\n\tprivate:\n\n\t\tRenderState m_renderState;\n\n\t\tVector<RenderQueueItem*> m_orderedCommands;\n", "file_path": "Graphics/include/Graphics/RenderQueue.hpp", "rank": 46, "score": 200553.41907453802 }, { "content": "class SampleRes : public AudioBase\n\n{\n\npublic:\n\n\tstatic Ref<SampleRes> Create(class Audio* audio, const String& path);\n\n\tvirtual ~SampleRes() = default;\n\n\n\npublic:\n\n\tvirtual const Buffer& GetData() const = 0;\n\n\tvirtual uint32 GetBitsPerSample() const = 0;\n\n\tvirtual uint32 GetNumChannels() const = 0;\n\n\n\n\t// Plays this sample from the start\n\n\tvirtual void Play(bool looping = false) = 0;\n\n\tvirtual void Stop() = 0;\n\n};\n\n\n\ntypedef Ref<SampleRes> Sample;", "file_path": "Audio/include/Audio/Sample.hpp", "rank": 47, "score": 200553.41907453802 }, { "content": "class PitchShiftDSP : public DSP\n\n{\n\npublic:\n\n\t// Pitch change amount\n\n\tfloat amount = 0.0f;\n\n\n\n\tPitchShiftDSP();\n\n\t~PitchShiftDSP();\n\n\n\n\tvirtual void Process(float* out, uint32 numSamples);\n\nprivate:\n", "file_path": "Audio/include/Audio/DSP.hpp", "rank": 48, "score": 200553.41907453802 }, { "content": "// Combinded Low/High-pass and Peaking filter\n\nclass CombinedFilterDSP : public DSP\n\n{\n\npublic:\n\n\tvoid SetLowPass(float q, float freq, float peakQ, float peakGain);\n\n\tvoid SetHighPass(float q, float freq, float peakQ, float peakGain);\n\n\n\n\tvirtual void Process(float* out, uint32 numSamples);\n\nprivate:\n\n\tBQFDSP a;\n\n\tBQFDSP peak;\n\n};\n\n\n", "file_path": "Audio/include/Audio/DSP.hpp", "rank": 49, "score": 200553.41907453802 }, { "content": "\tclass LaserCharacters : public Map<char, uint32>\n\n\t{\n\n\tpublic:\n\n\t\tLaserCharacters()\n\n\t\t{\n\n\t\t\tuint32 numChars = 0;\n\n\t\t\tauto AddRange = [&](char start, char end)\n\n\t\t\t{\n\n\t\t\t\tfor(char c = start; c <= end; c++)\n\n\t\t\t\t{\n\n\t\t\t\t\tAdd(c, numChars++);\n\n\t\t\t\t}\n\n\t\t\t};\n\n\t\t\tAddRange('0', '9');\n\n\t\t\tAddRange('A', 'Z');\n\n\t\t\tAddRange('a', 'o');\n\n\t\t}\n\n\t};\n\n\tstatic LaserCharacters laserCharacters;\n\n\n\n\tuint32* index = laserCharacters.Find(c);\n\n\tif(!index)\n\n\t{\n\n\t\tLogf(\"Invalid laser control point '%c'\", Logger::Warning, c);\n\n\t\treturn 0.0f;\n\n\t}\n\n\treturn (float)index[0] / (float)(laserCharacters.size()-1);\n\n}\n\nconst char* KShootMap::c_sep = \"--\";", "file_path": "Beatmap/src/KShootMap.cpp", "rank": 50, "score": 200140.71882161588 }, { "content": "struct static_const\n\n{\n\n static constexpr T value{};\n\n};\n\n\n\ntemplate<typename T>\n\nconstexpr T static_const<T>::value;\n\n} // namespace detail\n\n} // namespace nlohmann\n\n\n\n// #include <nlohmann/detail/meta/type_traits.hpp>\n\n\n\n\n\n#include <ciso646> // not\n\n#include <limits> // numeric_limits\n\n#include <type_traits> // false_type, is_constructible, is_integral, is_same, true_type\n\n#include <utility> // declval\n\n\n\n// #include <nlohmann/detail/iterators/iterator_traits.hpp>\n\n\n", "file_path": "third_party/nlohmann_json/json.hpp", "rank": 51, "score": 198396.48228107387 }, { "content": "// Chart stop object\n\nstruct ChartStop\n\n{\n\n\tMapTime time;\n\n\tMapTime duration;\n\n};\n", "file_path": "Beatmap/include/Beatmap/BeatmapObjects.hpp", "rank": 52, "score": 197403.0413384584 }, { "content": "\tclass AudioBase* audioBase = nullptr;\n", "file_path": "Audio/include/Audio/AudioBase.hpp", "rank": 53, "score": 197100.6533298647 }, { "content": "class SoundTouch : public FIFOProcessor\n\n{\n\nprivate:\n", "file_path": "third_party/soundtouch/include/SoundTouch.h", "rank": 54, "score": 196947.25527131383 }, { "content": "/// Linear transposer class that uses floating point arithmetics\n\nclass InterpolateLinearFloat : public TransposerBase\n\n{\n\nprotected:\n\n double fract;\n\n\n\n virtual void resetRegisters();\n\n\n\n virtual int transposeMono(SAMPLETYPE *dest, \n\n const SAMPLETYPE *src, \n\n int &srcSamples);\n\n virtual int transposeStereo(SAMPLETYPE *dest, \n\n const SAMPLETYPE *src, \n\n int &srcSamples);\n\n virtual int transposeMulti(SAMPLETYPE *dest, const SAMPLETYPE *src, int &srcSamples);\n\n\n\npublic:\n\n InterpolateLinearFloat();\n\n};\n\n\n\n}\n\n\n\n#endif\n", "file_path": "third_party/soundtouch/src/InterpolateLinear.h", "rank": 55, "score": 194418.70805255423 }, { "content": "class output_string_adapter : public output_adapter_protocol<CharType>\n\n{\n\n public:\n\n explicit output_string_adapter(StringType& s) noexcept\n\n : str(s)\n\n {}\n\n\n\n void write_character(CharType c) override\n\n {\n\n str.push_back(c);\n\n }\n\n\n\n void write_characters(const CharType* s, std::size_t length) override\n\n {\n\n str.append(s, length);\n\n }\n\n\n\n private:\n\n StringType& str;\n\n};\n\n\n\ntemplate<typename CharType, typename StringType = std::basic_string<CharType>>\n", "file_path": "third_party/nlohmann_json/json.hpp", "rank": 56, "score": 193727.85701219237 }, { "content": "class output_vector_adapter : public output_adapter_protocol<CharType>\n\n{\n\n public:\n\n explicit output_vector_adapter(std::vector<CharType>& vec) noexcept\n\n : v(vec)\n\n {}\n\n\n\n void write_character(CharType c) override\n\n {\n\n v.push_back(c);\n\n }\n\n\n\n void write_characters(const CharType* s, std::size_t length) override\n\n {\n\n std::copy(s, s + length, std::back_inserter(v));\n\n }\n\n\n\n private:\n\n std::vector<CharType>& v;\n\n};\n\n\n\n/// output adapter for output streams\n\ntemplate<typename CharType>\n", "file_path": "third_party/nlohmann_json/json.hpp", "rank": 57, "score": 193727.85701219237 }, { "content": "class output_stream_adapter : public output_adapter_protocol<CharType>\n\n{\n\n public:\n\n explicit output_stream_adapter(std::basic_ostream<CharType>& s) noexcept\n\n : stream(s)\n\n {}\n\n\n\n void write_character(CharType c) override\n\n {\n\n stream.put(c);\n\n }\n\n\n\n void write_characters(const CharType* s, std::size_t length) override\n\n {\n\n stream.write(s, static_cast<std::streamsize>(length));\n\n }\n\n\n\n private:\n\n std::basic_ostream<CharType>& stream;\n\n};\n\n\n\n/// output adapter for basic_string\n\ntemplate<typename CharType, typename StringType = std::basic_string<CharType>>\n", "file_path": "third_party/nlohmann_json/json.hpp", "rank": 58, "score": 193727.85701219237 }, { "content": "class Colori : public VectorMath::VectorBase<uint8, 4>\n\n{\n\npublic:\n\n\tusing VectorMath::VectorBase<uint8, 4>::VectorBase;\n\n\tColori() = default;\n\n\t// Constructor with alpha=1\n\n\tColori(uint8 r, uint8 g, uint8 b);\n\n\n\n\tstatic const Colori White;\n\n\tstatic const Colori Black;\n\n\tstatic const Colori Red;\n\n\tstatic const Colori Green;\n\n\tstatic const Colori Blue;\n\n\tstatic const Colori Yellow;\n\n\tstatic const Colori Magenta;\n\n\tstatic const Colori Cyan;\n\n};\n\n\n\n/*\n\n\tFloating point color class (RGBA32)\n\n*/\n", "file_path": "Shared/include/Shared/Color.hpp", "rank": 59, "score": 193611.92202661873 }, { "content": "class StringConfigEntry : public IConfigEntry\n\n{\n\npublic:\n\n\tString data;\n\npublic:\n\n\tvirtual String ToString() const override;\n\n\tvirtual void FromString(const String& str) override;\n\n\tEntryType GetType() override { return EntryType::String; };\n\n};\n\n\n", "file_path": "Shared/include/Shared/ConfigEntry.hpp", "rank": 60, "score": 193504.35867650755 }, { "content": "class FileReader : public FileStreamBase\n\n{\n\npublic:\n\n\tFileReader() = default;\n\n\tFileReader(File& file);\n\n\tvirtual size_t Serialize(void* data, size_t len);\n\n};\n\n\n\n/* Stream that writes to a buffer */\n", "file_path": "Shared/include/Shared/FileStream.hpp", "rank": 61, "score": 193504.35867650755 }, { "content": "class MemoryStreamBase : public BinaryStream\n\n{\n\nprotected:\n\n\tBuffer* m_buffer = nullptr;\n\n\tsize_t m_cursor = 0; // Write position\n\npublic:\n\n\tMemoryStreamBase() = default;\n\n\tMemoryStreamBase(Buffer& buffer, bool isReading);\n\n\tvirtual void Seek(size_t pos);\n\n\tvirtual size_t Tell() const;\n\n\tvirtual size_t GetSize() const;\n\n};\n\n\n\n/* Stream that reads from a buffer */\n", "file_path": "Shared/include/Shared/MemoryStream.hpp", "rank": 62, "score": 193504.35867650755 }, { "content": "class FileWriter : public FileStreamBase\n\n{\n\npublic:\n\n\tFileWriter() = default;\n\n\tFileWriter(File& file);\n\n\tvirtual size_t Serialize(void* data, size_t len);\n\n};", "file_path": "Shared/include/Shared/FileStream.hpp", "rank": 63, "score": 193504.35867650755 }, { "content": "class FileStreamBase : public BinaryStream\n\n{\n\nprotected:\n\n\tFile* m_file = nullptr;\n\npublic:\n\n\tFileStreamBase()= default;\n\n\tFileStreamBase(File& file, bool isReading);\n\n\tvirtual void Seek(size_t pos);\n\n\tvirtual size_t Tell() const;\n\n\tvirtual size_t GetSize() const;\n\n\tFile& GetFile();\n\n};\n\n\n\n/* Stream that reads from a buffer */\n", "file_path": "Shared/include/Shared/FileStream.hpp", "rank": 64, "score": 193504.35867650755 }, { "content": "class MemoryWriter : public MemoryStreamBase\n\n{\n\npublic:\n\n\tMemoryWriter() = default;\n\n\tMemoryWriter(Buffer& buffer);\n\n\tvirtual size_t Serialize(void* data, size_t len);\n\n};\n", "file_path": "Shared/include/Shared/MemoryStream.hpp", "rank": 65, "score": 193504.35867650755 }, { "content": "class ColorConfigEntry : public IConfigEntry\n\n{\n\npublic:\n\n\tColor data;\n\n\tvirtual String ToString() const override;\n\n\tvirtual void FromString(const String& str) override;\n\n\tEntryType GetType() override { return EntryType::Color; };\n\n};\n\n\n\ntemplate<typename EnumClass>\n", "file_path": "Shared/include/Shared/ConfigEntry.hpp", "rank": 66, "score": 193504.35867650755 }, { "content": "class EnumConfigEntry : public IConfigEntry\n\n{\n\npublic:\n\n\ttypename EnumClass::EnumType data;\n\npublic:\n\n\tvirtual String ToString() const override\n\n\t{\n\n\t\treturn EnumClass::ToString(data);\n\n\t}\n\n\tvirtual void FromString(const String& str) override\n\n\t{\n\n\t\tdata = EnumClass::FromString(str);\n\n\t}\n\n\tEntryType GetType() override { return EntryType::Enum; };\n\n};", "file_path": "Shared/include/Shared/ConfigEntry.hpp", "rank": 67, "score": 193504.35867650755 }, { "content": "class AudioStreamRes : public AudioBase\n\n{\n\npublic:\n\n\tstatic Ref<AudioStreamRes> Create(class Audio* audio, const String& path, bool preload);\n\n\tvirtual ~AudioStreamRes() = default;\n\npublic:\n\n\t// Starts playback of the stream or continues a paused stream\n\n\tvirtual void Play() = 0;\n\n\tvirtual void Pause() = 0;\n\n\n\n\tvirtual bool HasEnded() const = 0;\n\n\n\n\t// Sets the playback position in milliseconds\n\n\t// negative time alowed, which will produce no audio for a certain amount of time\n\n\tvirtual void SetPosition(int32 pos) = 0;\n\n};\n\n\n\ntypedef Ref<AudioStreamRes> AudioStream;", "file_path": "Audio/include/Audio/AudioStream.hpp", "rank": 68, "score": 193504.35867650755 }, { "content": "class MemoryReader : public MemoryStreamBase\n\n{\n\npublic:\n\n\tMemoryReader() = default;\n\n\tMemoryReader(Buffer& buffer);\n\n\tvirtual size_t Serialize(void* data, size_t len);\n\n};\n\n\n\n/* Stream that writes to a buffer */\n", "file_path": "Shared/include/Shared/MemoryStream.hpp", "rank": 69, "score": 193504.35867650755 }, { "content": "class Vector : public std::vector<I>\n\n{\n\npublic:\n\n\tusing std::vector<I>::vector;\n\n\t\n\n\t// These are for allowing function to be called on the base class when compiling on GCC\n\n\tusing std::vector<I>::back;\n\n\tusing std::vector<I>::front;\n\n\tusing std::vector<I>::begin;\n\n\tusing std::vector<I>::end;\n\n\tusing std::vector<I>::erase;\n\n\tusing std::vector<I>::push_back;\n\n\t\n\n\t// Adds a new element and returns it\n\n\tI& Add(const I& obj = I()) { push_back(obj); return back(); };\n\n\tI& AddZeroed() { push_back(I()); memset(&back(), 0, sizeof(I)); return back(); };\n\n\tvoid AddUnique(const I& obj)\n\n\t{\n\n\t\tif(!Contains(obj))\n\n\t\t\tAdd(obj);\n", "file_path": "Shared/include/Shared/Vector.hpp", "rank": 70, "score": 193138.0661844298 }, { "content": "class List : public std::list<I>\n\n{\n\npublic:\n\n\tusing std::list<I>::list;\n\n\tusing std::list<I>::list::insert;\n\n\tusing std::list<I>::list::begin;\n\n\tusing std::list<I>::list::end;\n\n\tusing std::list<I>::list::sort;\n\n\tusing std::list<I>::list::front;\n\n\tusing std::list<I>::list::back;\n\n\tusing std::list<I>::list::pop_front;\n\n\tusing std::list<I>::list::pop_back;\n\n\n\n\tI& AddBack(const I& item = I())\n\n\t{\n\n\t\tauto it = insert(end(), item);\n\n\t\treturn *it;\n\n\t}\n\n\tI& AddFront(const I& item = I())\n\n\t{\n", "file_path": "Shared/include/Shared/List.hpp", "rank": 71, "score": 193138.0661844298 }, { "content": "\tenum class TextureFormat\n\n\t{\n\n\t\tRGBA8,\n\n\t\tD32,\n\n\t\tInvalid\n\n\t};\n\n\n", "file_path": "Graphics/include/Graphics/Texture.hpp", "rank": 73, "score": 190387.16234815735 }, { "content": "/// Base-class for sound processing routines working in FIFO principle. With this base \n\n/// class it's easy to implement sound processing stages that can be chained together,\n\n/// so that samples that are fed into beginning of the pipe automatically go through \n\n/// all the processing stages.\n\n///\n\n/// When samples are input to this class, they're first processed and then put to \n\n/// the FIFO pipe that's defined as output of this class. This output pipe can be\n\n/// either other processing stage or a FIFO sample buffer.\n\nclass FIFOProcessor :public FIFOSamplePipe\n\n{\n\nprotected:\n\n /// Internal pipe where processed samples are put.\n\n FIFOSamplePipe *output;\n\n\n\n /// Sets output pipe.\n\n void setOutPipe(FIFOSamplePipe *pOutput)\n\n {\n\n assert(output == NULL);\n\n assert(pOutput != NULL);\n\n output = pOutput;\n\n }\n\n\n\n\n\n /// Constructor. Doesn't define output pipe; it has to be set be \n\n /// 'setOutPipe' function.\n\n FIFOProcessor()\n\n {\n\n output = NULL;\n", "file_path": "third_party/soundtouch/include/FIFOSamplePipe.h", "rank": 74, "score": 190231.54062856594 }, { "content": "\t// Command for points/lines with size/width parameter\n\n\tclass PointDrawCall : public RenderQueueItem\n\n\t{\n\n\tpublic:\n\n\t\t// List of points/lines\n\n\t\tMesh mesh;\n\n\t\tMaterial mat;\n\n\t\tMaterialParameterSet params;\n\n\t\tfloat size;\n\n\t};\n\n\n\n\t/*\n\n\t\tThis class is a queue that collects draw commands\n\n\t\teach of these is stored together with their wanted render state.\n\n\n\n\t\tWhen Process is called, the commands are sorted and grouped, then sent to the graphics pipeline.\n\n\t*/\n", "file_path": "Graphics/include/Graphics/RenderQueue.hpp", "rank": 75, "score": 190213.88697217187 }, { "content": "\t// Most basic draw command that only contains a material, it's parameters and a world transform\n\n\tclass SimpleDrawCall : public RenderQueueItem\n\n\t{\n\n\tpublic:\n\n\t\tSimpleDrawCall();\n\n\t\t// The mesh to draw\n\n\t\tMesh mesh;\n\n\t\t// Material to use\n\n\t\tMaterial mat;\n\n\t\tMaterialParameterSet params;\n\n\t\t// The world transform\n\n\t\tTransform worldTransform; \n\n\t\t// Scissor rectangle\n\n\t\tRect scissorRect;\n\n\t};\n\n\n", "file_path": "Graphics/include/Graphics/RenderQueue.hpp", "rank": 76, "score": 190213.88697217187 }, { "content": "class Set : public std::set<K>\n\n{\n\npublic:\n\n\tusing std::set<K>::set;\n\n\tusing std::set<K>::set::find;\n\n\tusing std::set<K>::set::end;\n\n\tusing std::set<K>::set::insert;\n\n\t\n\n\tbool Contains(const K& key) const\n\n\t{\n\n\t\treturn find(key) != end();\n\n\t}\n\n\tconst K& Add(const K& key)\n\n\t{\n\n\t\treturn *insert(key).first;\n\n\t}\n\n};", "file_path": "Shared/include/Shared/Set.hpp", "rank": 77, "score": 189356.73956327164 }, { "content": "class Buffer : public Vector<uint8>, Unique\n\n{\n\npublic:\n\n\tusing Vector<uint8>::Vector;\n\n\tBuffer() = default;\n\n\tBuffer(Buffer&& rhs);\n\n\tBuffer& operator=(Buffer&& rhs);\n\n\t// Creates a new buffer from a string, without the terminating null character\n\n\tBuffer(const char* string);\n\n\t// Creates a new buffer with an initial size\n\n\tBuffer(size_t initialSize);\n\n\t// Creates a copy of this buffer\n\n\tBuffer Copy() const;\n\n};\n", "file_path": "Shared/include/Shared/Buffer.hpp", "rank": 78, "score": 189356.73956327164 }, { "content": "class AudioOutput_Impl\n\n{\n\npublic:\n\n\tSDL_AudioSpec m_audioSpec = { 0 };\n\n\tSDL_AudioDeviceID m_deviceId = 0;\n\n\tIMixer* m_mixer = nullptr;\n\n\tvolatile bool m_running = false;\n\n\n\npublic:\n\n\tAudioOutput_Impl()\n\n\t{\n\n int32 numAudioDrivers = SDL_GetNumAudioDrivers();\n\n for(int32 i = 0; i < numAudioDrivers; i++)\n\n\t\t{\n\n const char* drvName = SDL_GetAudioDriver(i);\n\n Logf(\"Audio driver [%d]: %s\", Logger::Info, i, drvName);\n\n\t\t}\n\n\n\n\t\tSDLAudio::Main();\n\n\t}\n", "file_path": "Audio/src/AudioOutput_SDL.cpp", "rank": 79, "score": 188389.9402262894 }, { "content": "// Config for game settings\n\nclass GameConfig : public Config<Enum_GameConfigKeys>\n\n{\n\npublic:\n\n\tGameConfig();\n\n\tvoid SetKeyBinding(GameConfigKeys key, Key value);\n\n\n\nprotected:\n\n\tvirtual void InitDefaults() override;\n\n\n\n};\n\n\n\n// Main config instance\n\nextern class GameConfig g_gameConfig;\n", "file_path": "Main/GameConfig.hpp", "rank": 80, "score": 188001.59596016267 }, { "content": "\tclass PPConstant : public IParticleParameter<T>\n\n\t{\n\n\tpublic:\n\n\t\tPPConstant(const T& val) : val(val) {};\n\n\t\tvirtual T Sample(float in) override\n\n\t\t{\n\n\t\t\treturn val;\n\n\t\t}\n\n\t\tvirtual T GetMax()\n\n\t\t{\n\n\t\t\treturn val;\n\n\t\t}\n\n\t\tIMPLEMENT_DUPLICATE(T, PPConstant);\n\n\tprivate:\n\n\t\tT val;\n\n\t};\n\n\n\n\t/* A random value between A and B */\n\n\ttemplate<typename T>\n", "file_path": "Graphics/include/Graphics/ParticleParameter.hpp", "rank": 81, "score": 187107.6944886453 }, { "content": "\tclass PPBox : public IParticleParameter<Vector3>\n\n\t{\n\n\tpublic:\n\n\t\tPPBox(Vector3 size) : size(size)\n\n\t\t{\n\n\t\t}\n\n\t\tvirtual Vector3 Sample(float in) override\n\n\t\t{\n\n\t\t\tVector3 offset = -size * 0.5f;\n\n\t\t\toffset.x += Random::Float() * size.x;\n\n\t\t\toffset.y += Random::Float() * size.y;\n\n\t\t\toffset.z += Random::Float() * size.z;\n\n\t\t\treturn offset;\n\n\t\t}\n\n\t\tvirtual Vector3 GetMax()\n\n\t\t{\n\n\t\t\treturn size;\n\n\t\t}\n\n\t\tIMPLEMENT_DUPLICATE(Vector3, PPBox);\n\n\tprivate:\n\n\t\tVector3 size;\n\n\t};\n\n\n\n\t/*\n\n\tCone directional particle parameter\n\n\tCone angle is in degrees\n\n\t*/\n", "file_path": "Graphics/include/Graphics/ParticleParameter.hpp", "rank": 82, "score": 187107.6944886453 }, { "content": "\tclass PPCone : public IParticleParameter<Vector3>\n\n\t{\n\n\tpublic:\n\n\t\tPPCone(Vector3 dir, float angle, float lengthMin, float lengthMax)\n\n\t\t\t: angle(angle * Math::degToRad), lengthMin(lengthMin), lengthMax(lengthMax)\n\n\t\t{\n\n\t\t\tVector3 normal = dir.Normalized();\n\n\t\t\tVector3 tangent = Vector3(normal.y, -normal.x, normal.z);\n\n\t\t\tif(normal.x == 0 && normal.y == 0)\n\n\t\t\t\ttangent = Vector3(normal.z, normal.y, -normal.x);\n\n\t\t\ttangent = VectorMath::Cross(tangent, normal).Normalized();\n\n\t\t\tVector3 bitangent = VectorMath::Cross(tangent, normal);\n\n\t\t\tmat = Transform::FromAxes(bitangent, tangent, normal);\n\n\t\t}\n\n\t\tvirtual Vector3 Sample(float in) override\n\n\t\t{\n\n\t\t\tfloat length = Random::FloatRange(lengthMin, lengthMax);\n\n\n\n\t\t\tfloat a = Random::FloatRange(-1, 1);\n\n\t\t\tfloat b = Random::FloatRange(-1, 1);\n", "file_path": "Graphics/include/Graphics/ParticleParameter.hpp", "rank": 83, "score": 187107.6944886453 }, { "content": "class ResourceManager : public IResourceManager, Unique\n\n{\n\n\t// List of managed object\n\n\tVector<Ref<T>> m_objects;\n\n\tMutex m_lock;\n\npublic:\n\n\tResourceManager()\n\n\t{\n\n\t}\n\n\t~ResourceManager()\n\n\t{\n\n\t}\n\n\t// Creates a new reference counted object to this object and returns it\n\n\t// when the object is no longer referenced the resource manager will collect it when the next garbage collection triggers\n\n\tconst Ref<T> Register(T* pObject)\n\n\t{\n\n\t\tRef<T> ret = Utility::MakeRef(pObject);\n\n\t\tm_lock.lock();\n\n\t\tm_objects.push_back(ret);\n\n\t\tm_lock.unlock();\n", "file_path": "Shared/include/Shared/ResourceManager.hpp", "rank": 84, "score": 187107.6944886453 }, { "content": "\tclass PPRange : public IParticleParameter<T>\n\n\t{\n\n\tpublic:\n\n\t\tPPRange(const T& min, const T& max) : min(min), max(max) { delta = max - min; };\n\n\t\tvirtual T Sample(float in) override\n\n\t\t{\n\n\t\t\treturn (max - min) * in + min;\n\n\t\t}\n\n\t\tvirtual T GetMax()\n\n\t\t{\n\n\t\t\treturn Math::Max(max, min);\n\n\t\t}\n\n\t\tIMPLEMENT_DUPLICATE(T, PPRange);\n\n\tprivate:\n\n\t\tT delta;\n\n\t\tT min, max;\n\n\t};\n\n\n\n\t/* A 2 point gradient with a fade in value */\n\n\ttemplate<typename T>\n", "file_path": "Graphics/include/Graphics/ParticleParameter.hpp", "rank": 85, "score": 187107.6944886453 }, { "content": "\tclass PPSphere : public IParticleParameter<Vector3>\n\n\t{\n\n\tpublic:\n\n\t\tPPSphere(float radius) : radius(radius)\n\n\t\t{\n\n\t\t}\n\n\t\tvirtual Vector3 Sample(float in) override\n\n\t\t{\n\n\t\t\treturn Vector3(Random::FloatRange(-1.0f, 1.0f), Random::FloatRange(-1.0f, 1.0f), Random::FloatRange(-1.0f, 1.0f)) * radius;\n\n\t\t}\n\n\t\tvirtual Vector3 GetMax()\n\n\t\t{\n\n\t\t\treturn Vector3(radius);\n\n\t\t}\n\n\t\tIMPLEMENT_DUPLICATE(Vector3, PPSphere);\n\n\tprivate:\n\n\t\tfloat radius;\n\n\t};\n\n\n\n\t/* A centered random box particle parameter with a size */\n", "file_path": "Graphics/include/Graphics/ParticleParameter.hpp", "rank": 86, "score": 187107.6944886453 }, { "content": "\tclass RectangleBase3D : public RectangleBase<T>\n\n\t{\n\n\tpublic:\n\n\t\ttypedef VectorMath::VectorBase<T, 2> VectorType;\n\n\t\tusing RectangleBase<T>::RectangleBase;\n\n\t\tusing RectangleBase<T>::RectangleBase::pos;\n\n\t\tusing RectangleBase<T>::RectangleBase::size;\n\n\n\n\t\tRectangleBase3D() = default;\n\n\t\t// Conversion from other types\n\n\t\ttemplate<typename Q>\n\n\t\tRectangleBase3D(const RectangleBase<Q>& other)\n\n\t\t{\n\n\t\t\tpos = (VectorType)other.pos;\n\n\t\t\tsize = (VectorType)other.size;\n\n\t\t}\n\n\t\tRectangleBase3D(const RectangleBase<T>& other)\n\n\t\t{\n\n\t\t\tpos = other.pos;\n\n\t\t\tsize = other.size;\n", "file_path": "Shared/include/Shared/Rect.hpp", "rank": 87, "score": 187107.6944886453 }, { "content": "/// Sample buffer working in FIFO (first-in-first-out) principle. The class takes\n\n/// care of storage size adjustment and data moving during input/output operations.\n\n///\n\n/// Notice that in case of stereo audio, one sample is considered to consist of \n\n/// both channel data.\n\nclass FIFOSampleBuffer : public FIFOSamplePipe\n\n{\n\nprivate:\n\n /// Sample buffer.\n\n SAMPLETYPE *buffer;\n\n\n\n // Raw unaligned buffer memory. 'buffer' is made aligned by pointing it to first\n\n // 16-byte aligned location of this buffer\n\n SAMPLETYPE *bufferUnaligned;\n\n\n\n /// Sample buffer size in bytes\n\n uint sizeInBytes;\n\n\n\n /// How many samples are currently in buffer.\n\n uint samplesInBuffer;\n\n\n\n /// Channels, 1=mono, 2=stereo.\n\n uint channels;\n\n\n\n /// Current position pointer to the buffer. This pointer is increased when samples are \n", "file_path": "third_party/soundtouch/include/FIFOSampleBuffer.h", "rank": 88, "score": 187078.4456017022 }, { "content": "class AudioStreamBase : public AudioStreamRes\n\n{\n\nprotected:\n\n\t// Fixed point format for sample positions (used in resampling)\n\n\tstatic const uint64 fp_sampleStep;\n\n\n\n\tAudio* m_audio;\n\n\tFile m_file;\n\n\tBuffer m_data;\n\n\tMemoryReader m_memoryReader;\n\n\tFileReader m_fileReader;\n\n\tbool m_preloaded = false;\n\n\tBinaryStream& Reader();\n\n\n\n\tmutex m_lock;\n\n\n\n\tfloat** m_readBuffer = nullptr;\n\n\tuint32 m_bufferSize = 4096;\n\n\tuint32 m_numChannels = 0;\n\n\tuint32 m_currentBufferSize = 0;\n", "file_path": "Audio/include/Audio/AudioStreamBase.hpp", "rank": 89, "score": 187065.93707759626 }, { "content": "\tenum class MaterialBlendMode\n\n\t{\n\n\t\tNormal,\n\n\t\tAdditive,\n\n\t\tMultiply,\n\n\t};\n\n\n\n\t/*\n\n\t\tAbstracts the use of shaders/uniforms/pipelines into a single interface class\n\n\t*/\n", "file_path": "Graphics/include/Graphics/Material.hpp", "rank": 90, "score": 186418.92737383448 }, { "content": "// A Hold button, extends a normal button with duration and effect type\n\nstruct ObjectTypeData_Hold : public ObjectTypeData_Button\n\n{\n\n\tTObjectState<ObjectTypeData_Hold>* GetRoot();\n\n\t// Used for hold notes, 0 is a normal note\n\n\tMapTime duration = 0;\n\n\t// The sound effect on the note\n\n\tEffectType effectType = EffectType::None;\n\n\t// The parameter for effects that have it\n\n\t// the maximum number of parameters is 2 (only echo uses this)\n\n\tint16 effectParams[2] = { 0 };\n\n\n\n\t// Set for hold notes that are a continuation of the previous one, but with a different effect\n\n\tTObjectState<ObjectTypeData_Hold>* next = nullptr;\n\n\tTObjectState<ObjectTypeData_Hold>* prev = nullptr;\n\n\n\n\tstatic const ObjectType staticType = ObjectType::Hold;\n\n};\n\n\n\n\n", "file_path": "Beatmap/include/Beatmap/BeatmapObjects.hpp", "rank": 92, "score": 184284.42548487842 }, { "content": "\tclass PPRandomRange : public IParticleParameter<T>\n\n\t{\n\n\tpublic:\n\n\t\tPPRandomRange(const T& min, const T& max) : min(min), max(max) { delta = max - min; };\n\n\t\tvirtual T Init(float systemTime) override\n\n\t\t{\n\n\t\t\treturn Sample(Random::Float());\n\n\t\t}\n\n\t\tvirtual T Sample(float in) override\n\n\t\t{\n\n\t\t\treturn (max - min) * in + min;\n\n\t\t}\n\n\t\tvirtual T GetMax()\n\n\t\t{\n\n\t\t\treturn Math::Max(max, min);\n\n\t\t}\n\n\t\tIMPLEMENT_DUPLICATE(T, PPRandomRange);\n\n\tprivate:\n\n\t\tT delta;\n\n\t\tT min, max;\n\n\t};\n\n\n\n\t/* A value that transitions from A to B over time */\n\n\ttemplate<typename T>\n", "file_path": "Graphics/include/Graphics/ParticleParameter.hpp", "rank": 93, "score": 183817.22278430962 }, { "content": "\tclass PPRangeFadeIn : public IParticleParameter<T>\n\n\t{\n\n\tpublic:\n\n\t\tPPRangeFadeIn(const T& min, const T& max, const float fadeIn) : fadeIn(fadeIn), min(min), max(max)\n\n\t\t{\n\n\t\t\tdelta = max - min;\n\n\t\t\trangeOut = 1.0f - fadeIn;\n\n\t\t};\n\n\t\tvirtual T Sample(float in) override\n\n\t\t{\n\n\t\t\tif(in < fadeIn)\n\n\t\t\t{\n\n\t\t\t\treturn min * (in / fadeIn);\n\n\t\t\t}\n\n\t\t\telse\n\n\t\t\t{\n\n\t\t\t\treturn (in - fadeIn) / rangeOut * (max - min) + min;\n\n\t\t\t}\n\n\t\t}\n\n\t\tvirtual T GetMax()\n", "file_path": "Graphics/include/Graphics/ParticleParameter.hpp", "rank": 94, "score": 183817.22278430962 }, { "content": " class NumberFloatType = double,\n\n template<typename U> class AllocatorType = std::allocator,\n\n template<typename T, typename SFINAE = void> class JSONSerializer =\n\n adl_serializer>\n", "file_path": "third_party/nlohmann_json/json.hpp", "rank": 95, "score": 183589.69416241854 }, { "content": "class StringBase : public std::basic_string<T>\n\n{\n\npublic:\n\n\tusing std::basic_string<T>::basic_string;\n\n\n\n\t// These are for allowing function to be called on the base class when compiling on GCC\n\n\tusing std::basic_string<T>::c_str;\n\n\tusing std::basic_string<T>::substr;\n\n\tusing std::basic_string<T>::begin;\n\n\tusing std::basic_string<T>::end;\n\n\tusing std::basic_string<T>::length;\n\n\tusing std::basic_string<T>::back;\n\n\tusing std::basic_string<T>::empty;\n\n\tusing std::basic_string<T>::front;\n\n\tusing std::basic_string<T>::find;\n\n\tusing std::basic_string<T>::find_last_of;\n\n\n\n\tStringBase() = default;\n\n\tStringBase(const T* cs);\n\n\tStringBase(const std::basic_string<T>& ss);\n", "file_path": "Shared/include/Shared/String.hpp", "rank": 96, "score": 182307.6791652412 }, { "content": "class Multimap : public std::multimap<K, V>\n\n{\n\npublic:\n\n\tusing std::multimap<K, V>::multimap;\n\n\n\n\t// These are for allowing function to be called on the base class when compiling on GCC\n\n\tusing std::multimap<K, V>::begin;\n\n\tusing std::multimap<K, V>::end;\n\n\tusing std::multimap<K, V>::erase;\n\n\tusing std::multimap<K, V>::insert;\n\n\tusing std::multimap<K, V>::find;\n\n\n\n\tbool Contains(const K& key) const\n\n\t{\n\n\t\treturn find(key) != end();\n\n\t}\n\n\tV& Add(const K& k, const V& v = V())\n\n\t{\n\n\t\tauto it = insert(std::make_pair(k, v));\n\n\t\treturn it->second;\n\n\t}\n\n};", "file_path": "Shared/include/Shared/Map.hpp", "rank": 97, "score": 182015.7378010792 }, { "content": "class Map : public std::map<K, V>\n\n{\n\npublic:\n\n\tusing std::map<K, V>::map;\n\n\t\n\n\t// These are for allowing function to be called on the base class when compiling on GCC\n\n\tusing std::map<K, V>::begin;\n\n\tusing std::map<K, V>::end;\n\n\tusing std::map<K, V>::erase;\n\n\tusing std::map<K, V>::insert;\n\n\tusing std::map<K, V>::find;\n\n\t\n\n\tbool Contains(const K& key) const\n\n\t{\n\n\t\treturn find(key) != end();\n\n\t}\n\n\tV& FindOrAdd(const K& key, const V& defaultValue = V())\n\n\t{\n\n\t\tauto it = find(key);\n\n\t\tif(it == end())\n", "file_path": "Shared/include/Shared/Map.hpp", "rank": 98, "score": 182015.7378010792 } ]
C++
src/local_edge.cc
yjxiong/convnet
f51261942ce5121255c7edd61ce1a589509e76e5
#include "local_edge.h" #include "cudamat_conv.cuh" #include <iostream> LocalEdge::LocalEdge(const config::Edge& edge_config) : EdgeWithWeight(edge_config), kernel_size_(edge_config.kernel_size()), stride_(edge_config.stride()), padding_(edge_config.padding()) {} void LocalEdge::SetTiedTo(Edge* e) { EdgeWithWeight::SetTiedTo(e); LocalEdge* ee = dynamic_cast<LocalEdge*> (e); kernel_size_ = ee->GetKernelSize(); stride_ = ee->GetStride(); padding_ = ee->GetPadding(); } void LocalEdge::DisplayWeights() { if (img_display_ != NULL) { weights_.CopyToHost(); img_display_->DisplayWeights(weights_.GetHostData(), kernel_size_, num_output_channels_, 250, false); } } void LocalEdge::SetImageSize(int image_size) { Edge::SetImageSize(image_size); num_modules_ = (image_size + 2 * padding_ - kernel_size_) / stride_ + 1; } void LocalEdge::AllocateMemoryFprop() { int input_size = kernel_size_ * kernel_size_ * num_input_channels_ * num_modules_ * num_modules_; int bias_locs = num_modules_ * num_modules_; weights_.AllocateGPUMemory(num_output_channels_, input_size); bias_.AllocateGPUMemory(1, num_output_channels_ * bias_locs); } void LocalEdge::AllocateMemoryBprop() { int input_size = kernel_size_ * kernel_size_ * num_input_channels_ * num_modules_ * num_modules_; int bias_locs = num_modules_ * num_modules_; grad_weights_.AllocateGPUMemory(num_output_channels_, input_size); weight_optimizer_->AllocateMemory(num_output_channels_, input_size); grad_bias_.AllocateGPUMemory(1, num_output_channels_ * bias_locs); bias_optimizer_->AllocateMemory(1, num_output_channels_ * bias_locs); } void LocalEdge::AllocateMemory(bool fprop_only) { if (is_tied_) return; Edge::AllocateMemory(fprop_only); num_modules_ = (image_size_ + 2 * padding_ - kernel_size_) / stride_ + 1; cout << name_ << " "; printf("Kernel: %d-%d-%d to %d ", kernel_size_, kernel_size_, num_input_channels_, num_output_channels_); printf("Layer: %d-%d-%d (%d) ", image_size_, image_size_, num_input_channels_, image_size_ * image_size_ * num_input_channels_); AllocateMemoryFprop(); if (!fprop_only) AllocateMemoryBprop(); cout << " Allocated weight " << weights_.GetRows() << " " << weights_.GetCols() << " Locally Connected" << endl; if (num_input_channels_ == 3) { int num_filters = num_output_channels_; int num_filters_w = int(sqrt(num_filters)); int num_filters_h = num_filters / num_filters_w + (((num_filters % num_filters_w) > 0) ? 1 : 0); int width = 250; int height = (width * num_filters_h) / num_filters_w; img_display_ = new ImageDisplayer(width, height, 3, false, "weights"); } } void LocalEdge::ComputeUp(Matrix& input, Matrix& output, bool overwrite) { cudamat *input_mat = input.GetMat(), *output_mat = output.GetMat(), *w_mat = is_tied_? tied_edge_->GetWeight().GetMat() : weights_.GetMat(); int scale_targets = overwrite ? 0 : 1; localUp(input_mat, w_mat, output_mat, num_modules_, -padding_, stride_, num_input_channels_, 1, scale_targets); if (!has_no_bias_) { cudamat* b_mat = is_tied_? tied_edge_->GetBias().GetMat() : bias_.GetMat(); add_row_vec(output_mat, b_mat, output_mat); } } void LocalEdge::ComputeDown(Matrix& deriv_output, Matrix& input, Matrix& output, Matrix& deriv_input, bool overwrite) { cudamat* deriv_output_mat = deriv_output.GetMat(); cudamat* deriv_input_mat = deriv_input.GetMat(); cudamat* w_mat = is_tied_? tied_edge_->GetWeight().GetMat() : weights_.GetMat(); int scale_targets = overwrite ? 0 : 1; localDown(deriv_output_mat, w_mat, deriv_input_mat, image_size_, -padding_, stride_, num_input_channels_, 1, scale_targets); } void LocalEdge::ComputeOuter(Matrix& input, Matrix& deriv_output) { cudamat* input_mat = input.GetMat(); cudamat* deriv_output_mat = deriv_output.GetMat(); cudamat* dw_mat = is_tied_ ? tied_edge_->GetGradWeight().GetMat() : grad_weights_.GetMat(); const int batch_size = input.GetRows(); int scale_targets = GetNumGradsReceived() > 0 ? 1 : 0; localOutp(input_mat, deriv_output_mat, dw_mat, num_modules_, kernel_size_, -padding_, stride_, num_input_channels_, 1, scale_targets, scale_gradients_ / batch_size); if (!has_no_bias_) { cudamat* db_mat = is_tied_ ? tied_edge_->GetGradBias().GetMat() : grad_bias_.GetMat(); Matrix ones; Matrix::GetOnes(1, batch_size, ones); dot(ones.GetMat(), deriv_output_mat, db_mat, scale_targets, scale_gradients_ / batch_size); } IncrementNumGradsReceived(); }
#include "local_edge.h" #include "cudamat_conv.cuh" #include <iostream> LocalEdge::LocalEdge(const config::Edge& edge_config) : EdgeWithWeight(edge_config), kernel_size_(edge_config.kernel_size()), stride_(edge_config.stride()), padding_(edge_config.padding()) {} void LocalEdge::SetTiedTo(Edge* e) { EdgeWithWeight::SetTiedTo(e); LocalEdge* ee = dynamic_cast<LocalEdge*> (e); kernel_size_ = ee->GetKernelSize(); stride_ = ee->GetStride(); padding_ = ee->GetPadding(); } void LocalEdge::DisplayWeights() {
} void LocalEdge::SetImageSize(int image_size) { Edge::SetImageSize(image_size); num_modules_ = (image_size + 2 * padding_ - kernel_size_) / stride_ + 1; } void LocalEdge::AllocateMemoryFprop() { int input_size = kernel_size_ * kernel_size_ * num_input_channels_ * num_modules_ * num_modules_; int bias_locs = num_modules_ * num_modules_; weights_.AllocateGPUMemory(num_output_channels_, input_size); bias_.AllocateGPUMemory(1, num_output_channels_ * bias_locs); } void LocalEdge::AllocateMemoryBprop() { int input_size = kernel_size_ * kernel_size_ * num_input_channels_ * num_modules_ * num_modules_; int bias_locs = num_modules_ * num_modules_; grad_weights_.AllocateGPUMemory(num_output_channels_, input_size); weight_optimizer_->AllocateMemory(num_output_channels_, input_size); grad_bias_.AllocateGPUMemory(1, num_output_channels_ * bias_locs); bias_optimizer_->AllocateMemory(1, num_output_channels_ * bias_locs); } void LocalEdge::AllocateMemory(bool fprop_only) { if (is_tied_) return; Edge::AllocateMemory(fprop_only); num_modules_ = (image_size_ + 2 * padding_ - kernel_size_) / stride_ + 1; cout << name_ << " "; printf("Kernel: %d-%d-%d to %d ", kernel_size_, kernel_size_, num_input_channels_, num_output_channels_); printf("Layer: %d-%d-%d (%d) ", image_size_, image_size_, num_input_channels_, image_size_ * image_size_ * num_input_channels_); AllocateMemoryFprop(); if (!fprop_only) AllocateMemoryBprop(); cout << " Allocated weight " << weights_.GetRows() << " " << weights_.GetCols() << " Locally Connected" << endl; if (num_input_channels_ == 3) { int num_filters = num_output_channels_; int num_filters_w = int(sqrt(num_filters)); int num_filters_h = num_filters / num_filters_w + (((num_filters % num_filters_w) > 0) ? 1 : 0); int width = 250; int height = (width * num_filters_h) / num_filters_w; img_display_ = new ImageDisplayer(width, height, 3, false, "weights"); } } void LocalEdge::ComputeUp(Matrix& input, Matrix& output, bool overwrite) { cudamat *input_mat = input.GetMat(), *output_mat = output.GetMat(), *w_mat = is_tied_? tied_edge_->GetWeight().GetMat() : weights_.GetMat(); int scale_targets = overwrite ? 0 : 1; localUp(input_mat, w_mat, output_mat, num_modules_, -padding_, stride_, num_input_channels_, 1, scale_targets); if (!has_no_bias_) { cudamat* b_mat = is_tied_? tied_edge_->GetBias().GetMat() : bias_.GetMat(); add_row_vec(output_mat, b_mat, output_mat); } } void LocalEdge::ComputeDown(Matrix& deriv_output, Matrix& input, Matrix& output, Matrix& deriv_input, bool overwrite) { cudamat* deriv_output_mat = deriv_output.GetMat(); cudamat* deriv_input_mat = deriv_input.GetMat(); cudamat* w_mat = is_tied_? tied_edge_->GetWeight().GetMat() : weights_.GetMat(); int scale_targets = overwrite ? 0 : 1; localDown(deriv_output_mat, w_mat, deriv_input_mat, image_size_, -padding_, stride_, num_input_channels_, 1, scale_targets); } void LocalEdge::ComputeOuter(Matrix& input, Matrix& deriv_output) { cudamat* input_mat = input.GetMat(); cudamat* deriv_output_mat = deriv_output.GetMat(); cudamat* dw_mat = is_tied_ ? tied_edge_->GetGradWeight().GetMat() : grad_weights_.GetMat(); const int batch_size = input.GetRows(); int scale_targets = GetNumGradsReceived() > 0 ? 1 : 0; localOutp(input_mat, deriv_output_mat, dw_mat, num_modules_, kernel_size_, -padding_, stride_, num_input_channels_, 1, scale_targets, scale_gradients_ / batch_size); if (!has_no_bias_) { cudamat* db_mat = is_tied_ ? tied_edge_->GetGradBias().GetMat() : grad_bias_.GetMat(); Matrix ones; Matrix::GetOnes(1, batch_size, ones); dot(ones.GetMat(), deriv_output_mat, db_mat, scale_targets, scale_gradients_ / batch_size); } IncrementNumGradsReceived(); }
if (img_display_ != NULL) { weights_.CopyToHost(); img_display_->DisplayWeights(weights_.GetHostData(), kernel_size_, num_output_channels_, 250, false); }
if_condition
[ { "content": "#include \"conv_edge.h\"\n\n#include \"cudamat_conv.cuh\"\n\n#include <iostream>\n\n\n\nConvEdge::ConvEdge(const config::Edge& edge_config) :\n\n EdgeWithWeight(edge_config),\n\n kernel_size_(edge_config.kernel_size()),\n\n stride_(edge_config.stride()),\n\n padding_(edge_config.padding()),\n\n partial_sum_(edge_config.partial_sum()),\n\n shared_bias_(edge_config.shared_bias()) {}\n\n\n\nvoid ConvEdge::SetTiedTo(Edge* e) {\n\n EdgeWithWeight::SetTiedTo(e);\n\n ConvEdge* ee = dynamic_cast<ConvEdge*>(e);\n\n kernel_size_ = ee->GetKernelSize();\n\n stride_ = ee->GetStride();\n\n padding_ = ee->GetPadding();\n\n if (partial_sum_ == 0) {\n\n partial_sum_ = ee->GetPartialSum();\n", "file_path": "src/conv_edge.cc", "rank": 1, "score": 13.404241966392544 }, { "content": "#include \"cpuconv.h\"\n\n#include <iostream>\n\n#include <cfloat>\n\n#include <cmath>\n\n#include <chrono>\n\n\n\nusing namespace std;\n\n\n\nCPUMatrix::CPUMatrix(): data_(NULL), rows_(0), cols_(0) {\n\n}\n\n\n\nCPUMatrix::CPUMatrix(const int rows, const int cols): rows_(rows), cols_(cols) {\n\n AllocateMemory(rows, cols);\n\n}\n\n\n\nvoid CPUMatrix::FreeMemory() {\n\n if (rows_ * cols_ > 0) delete data_;\n\n}\n\n\n\nvoid CPUMatrix::AllocateMemory(int rows, int cols) {\n", "file_path": "cpu/cpuconv.cc", "rank": 2, "score": 11.1759233532056 }, { "content": "#include \"maxpool_edge.h\"\n\n#include \"cudamat_conv.cuh\"\n\n\n\nMaxPoolEdge::MaxPoolEdge(const config::Edge& edge_config) :\n\n Edge(edge_config),\n\n kernel_size_(edge_config.kernel_size()),\n\n stride_(edge_config.stride()),\n\n padding_(edge_config.padding()){}\n\n\n\nvoid MaxPoolEdge::SetTiedTo(Edge* e) {\n\n Edge::SetTiedTo(e);\n\n MaxPoolEdge* ee = dynamic_cast<MaxPoolEdge*> (e);\n\n kernel_size_ = ee->GetKernelSize();\n\n stride_ = ee->GetStride();\n\n padding_ = ee->GetPadding();\n\n}\n\n\n\n\n\nvoid MaxPoolEdge::SetImageSize(int image_size) {\n\n Edge::SetImageSize(image_size);\n", "file_path": "src/maxpool_edge.cc", "rank": 3, "score": 11.032551061028173 }, { "content": "#include \"util.h\"\n\n#include <stdlib.h>\n\n#include <string.h>\n\n#include <iostream>\n\n#include <fstream>\n\n#include <ctime>\n\n#include <sstream>\n\n\n\nusing namespace std;\n\n\n\nvoid WaitForEnter() {\n\n cout << \"Press ENTER to continue...\";\n\n cin.ignore(numeric_limits<streamsize>::max(), '\\n');\n\n}\n\n\n\nint Bound(int val, int lb, int ub) {\n\n val = val > ub ? ub : val;\n\n val = val < lb ? lb : val;\n\n return val;\n\n}\n", "file_path": "src/util.cc", "rank": 4, "score": 10.839077219140457 }, { "content": "#include \"response_norm_edge.h\"\n\n#include \"cudamat_conv.cuh\"\n\n\n\nResponseNormEdge::ResponseNormEdge(const config::Edge& edge_config) :\n\n Edge(edge_config),\n\n num_filters_response_norm_(0),\n\n blocked_(edge_config.response_norm_in_blocks()),\n\n add_scale_(edge_config.add_scale()),\n\n pow_scale_(edge_config.pow_scale()),\n\n frac_of_filters_response_norm_(edge_config.frac_of_filters_response_norm()){}\n\n\n\nvoid ResponseNormEdge::SetTiedTo(Edge* e) {\n\n Edge::SetTiedTo(e);\n\n ResponseNormEdge* ee = dynamic_cast<ResponseNormEdge*> (e);\n\n blocked_ = ee->Blocked();\n\n add_scale_ = ee->AddScale();\n\n pow_scale_ = ee->PowScale();\n\n frac_of_filters_response_norm_ = ee->FracOfFilters();\n\n}\n\n\n", "file_path": "src/response_norm_edge.cc", "rank": 5, "score": 10.146239698718581 }, { "content": "#define cimg_use_jpeg\n\n#include \"CImg.h\"\n\n#include \"convnet_cpu.h\"\n\n#include <string>\n\n#include <iostream>\n\n#include <fstream>\n\n#include <chrono>\n\nusing namespace cimg_library;\n\nusing namespace std;\n\n\n\nCImgDisplay disp;\n\nvoid GetCoordinates(int image_size, int width, int height, int position,\n\n int* left, int* top, bool* flip) {\n\n *flip = position >= 5;\n\n position %= 5;\n\n int x_slack = width - image_size;\n\n int y_slack = height - image_size;\n\n switch(position) {\n\n case 0 : // Center. \n\n *left = x_slack / 2;\n", "file_path": "cpu/extract_representation_cpu.cc", "rank": 6, "score": 10.08837326876194 }, { "content": "#include \"grad_check.h\"\n\n#include \"edge_with_weight.h\" \n\n#include <iostream>\n\nusing namespace std;\n\n\n\nGradChecker::GradChecker(const string& model_file) : ConvNet(model_file) {}\n\n\n\nvoid GradChecker::GetLoss(vector<float>& error) {\n\n Fprop(false);\n\n error.clear();\n\n for (Layer* l: output_layers_) {\n\n error.push_back(l->GetLoss2());\n\n }\n\n}\n\n\n\nvoid GradChecker::Run(Matrix& w, Matrix& dLbydw_analytical, float epsilon, const vector<float>& analytical_error) {\n\n w.CopyToHost();\n\n dLbydw_analytical.CopyToHost();\n\n float* w_dataptr = w.GetHostData();\n\n float* dLbydw_analytical_ptr = dLbydw_analytical.GetHostData();\n", "file_path": "src/grad_check.cc", "rank": 7, "score": 9.921268099403731 }, { "content": "#include \"convnet.h\"\n\n#include <iostream>\n\n#include <fstream>\n\n#include <string>\n\n#include <stdlib.h>\n\n#include <algorithm>\n\n#include <sstream>\n\n#include <stack>\n\n#include <chrono>\n\n#include <csignal>\n\n\n\n#include <ctime>\n\n#include <iostream>\n\nusing namespace std;\n\n\n\nusing namespace std;\n\nConvNet::ConvNet(const string& model_file):\n\n max_iter_(0), batch_size_(0), current_iter_(0),\n\n lr_reduce_counter_(0),\n\n train_dataset_(NULL), val_dataset_(NULL),\n", "file_path": "src/convnet.cc", "rank": 8, "score": 9.278838812356517 }, { "content": "// condition_variable example\n\n#include <iostream> // std::cout\n\n#include <thread> // std::thread\n\n#include <mutex> // std::mutex, std::unique_lock\n\n#include <condition_variable> // std::condition_variable\n\n\n\nusing namespace std;\n\nmutex fprop_start_mutex_, fprop_finished_mutex_;\n\ncondition_variable fprop_finish_cond_var_, fprop_start_cond_var_;\n\nbool ready_for_fprop_ = false, fprop_finish_ = false;\n\n\n\nvoid fprop () {\n\n unique_lock<mutex> lock1(fprop_start_mutex_);\n\n while (!ready_for_fprop_) {\n\n // wait for TrainOneBatch to set this off.\n\n cout << \"Waiting for signal to start fprop \" << endl;\n\n fprop_start_cond_var_.wait(lock1);\n\n cout << \"Got signal\" << endl;\n\n }\n\n ready_for_fprop_ = false;\n", "file_path": "src/sample.cc", "rank": 9, "score": 9.125989587690501 }, { "content": "#include \"conv_onetoone_edge.h\"\n\n#include <iostream>\n\n\n\nConvOneToOneEdge::ConvOneToOneEdge(const config::Edge& edge_config) :\n\n EdgeWithWeight(edge_config) {}\n\n\n\nvoid ConvOneToOneEdge::SetImageSize(int image_size) {\n\n Edge::SetImageSize(image_size);\n\n num_modules_ = image_size;\n\n}\n\n\n\nvoid ConvOneToOneEdge::AllocateMemory(bool fprop_only) {\n\n if (is_tied_) return;\n\n Edge::AllocateMemory(fprop_only);\n\n\n\n cout << name_ << \" \";\n\n printf(\"One to one convolution: %d - %d \", num_input_channels_, num_output_channels_);\n\n printf(\"Layer: %d-%d-%d (%d) \", image_size_, image_size_, num_input_channels_,\n\n image_size_ * image_size_ * num_input_channels_);\n\n \n", "file_path": "src/conv_onetoone_edge.cc", "rank": 10, "score": 9.103969619038152 }, { "content": "#ifndef EDGE_H_\n\n#define EDGE_H_\n\n#include \"util.h\"\n\n#include \"matrix.h\"\n\n#include <iostream>\n\n\n", "file_path": "src/edge.h", "rank": 11, "score": 8.957655875857295 }, { "content": "#include <stdio.h>\n\n#include <execinfo.h>\n\n#include <signal.h>\n\n#include <stdlib.h>\n\n#include <unistd.h>\n\n\n\n\n\nvoid handler(int sig) {\n\n void *array[10];\n\n size_t size;\n\n\n\n size = backtrace(array, 10);\n\n\n\n fprintf(stderr, \"Error: signal %d:\\n\", sig);\n\n backtrace_symbols_fd(array, size, STDERR_FILENO);\n\n exit(1);\n\n}\n\n\n\nvoid baz() {\n\n int *foo = (int*)-1;\n", "file_path": "src/backtrace.cc", "rank": 12, "score": 8.859253176959314 }, { "content": "#include <execinfo.h>\n\n#include <signal.h>\n\n#include <stdio.h>\n\n#include <stdlib.h>\n\n#include <string.h>\n\n#include <ucontext.h>\n\n#include <unistd.h>\n\n\n\nusing namespace cimg_library;\n\nusing namespace std;\n\n\n\n// Outputs a string that describes the err_code.\n\nstring GetStringError(int err_code);\n\n// Reads model_file from the disk and instantiates a Model.\n\nvoid ReadModel(const string& model_file, config::Model& model);\n\nvoid ReadModelText(const string& model_file, config::Model& model);\n\nvoid ReadDataConfig(const string& data_config_file, config::DatasetConfig& data_config);\n\nvoid ReadLayerConfig(const string& layer_config_file, config::Layer& layer_config);\n\nvoid WriteModelBinary(const string& output_file, const config::Model& model);\n\nvoid ReadModelBinary(const string& input_file, config::Model& model);\n", "file_path": "src/util.h", "rank": 13, "score": 8.63480693060195 }, { "content": "#include \"fc_edge.h\"\n\n#include <iostream>\n\n\n\nFCEdge::FCEdge(const config::Edge& edge_config) :\n\n EdgeWithWeight(edge_config){}\n\n\n\nvoid FCEdge::AllocateMemoryBprop() {\n\n int input_size = image_size_ * image_size_ * num_input_channels_;\n\n grad_weights_.AllocateGPUMemory(num_output_channels_, input_size, GetName() + \"_grad_weight\");\n\n weight_optimizer_->AllocateMemory(num_output_channels_, input_size);\n\n\n\n if (!has_no_bias_) {\n\n grad_bias_.AllocateGPUMemory(1, num_output_channels_, GetName() + \"_grad_bias\");\n\n bias_optimizer_->AllocateMemory(1, num_output_channels_);\n\n }\n\n}\n\n\n\nvoid FCEdge::AllocateMemoryFprop() {\n\n int input_size = image_size_ * image_size_ * num_input_channels_;\n\n weights_.AllocateGPUMemory(num_output_channels_, input_size, GetName() + \"_weight\");\n", "file_path": "src/fc_edge.cc", "rank": 14, "score": 8.490624678655301 }, { "content": "#include \"edge.h\"\n\n#include \"matrix.h\"\n\n#include \"util.h\"\n\n#include <iostream>\n\n#include \"edge_with_weight.h\"\n\n#include \"fc_edge.h\"\n\n#include \"conv_edge.h\"\n\n#include \"maxpool_edge.h\"\n\n#include \"local_edge.h\"\n\n#include \"upsample_edge.h\"\n\n#include \"downsample_edge.h\"\n\n#include \"response_norm_edge.h\"\n\n#include \"rgb_to_yuv_edge.h\"\n\n#include \"conv_onetoone_edge.h\"\n\nusing namespace std;\n\n\n\nEdge* Edge::ChooseEdgeClass(const config::Edge& edge_config) {\n\n Edge* e = NULL;\n\n switch (edge_config.edge_type()) {\n\n case config::Edge::FC :\n", "file_path": "src/edge.cc", "rank": 15, "score": 8.150612456526392 }, { "content": "#ifndef IMAGE_ITERATORS_\n\n#define IMAGE_ITERATORS_\n\n#define cimg_use_jpeg\n\n#define cimg_use_lapack\n\n#include <string>\n\n#include <iostream>\n\n#include <vector>\n\n#include \"CImg.h\"\n\nusing namespace cimg_library;\n\nusing namespace std;\n\n\n\n/** An iterator over list of image files.\n\n * Takes a list of image files and iterates over them.\n\n * Images are cropped, jittered, flip etc.\n\n */ \n\ntemplate<typename T>\n", "file_path": "src/image_iterators.h", "rank": 16, "score": 7.8670221002493514 }, { "content": "#include \"matrix.h\"\n\n#include \"util.h\"\n\n#include <cstdio>\n\n#include <iostream>\n\n#include <sstream>\n\n\n\nvector<rnd_struct> Matrix::rnd_;\n\nvector<Matrix> Matrix::ones_, Matrix::temp_;\n\nvector<int> Matrix::boards_, Matrix::temp_size_, Matrix::ones_size_;\n\nint Matrix::current_gpu_id_ = 0, Matrix::num_boards_ = 0;\n\n\n\nMatrix::Matrix() {\n\n mat_.data_host = NULL;\n\n mat_.data_device = NULL;\n\n mat_.on_host = 1;\n\n mat_.on_device = 0;\n\n mat_.is_trans = 0;\n\n mat_.size[0] = 0;\n\n mat_.size[1] = 0;\n\n mat_t_ = mat_;\n", "file_path": "src/matrix.cc", "rank": 17, "score": 7.6602928412718025 }, { "content": "#include \"datahandler.h\"\n\n#include \"image_iterators.h\"\n\n#include <algorithm>\n\n#include <iostream>\n\n#include <fstream>\n\n#include <sstream>\n\n\n\nDataHandler::DataHandler(const config::DatasetConfig& config) :\n\n preload_thread_(NULL),\n\n batch_size_(config.batch_size()),\n\n chunk_size_(config.chunk_size()),\n\n max_reuse_count_(config.max_reuse_count()),\n\n reuse_counter_(0),\n\n random_access_chunk_size_(config.random_access_chunk_size()),\n\n dataset_size_(-1),\n\n start_(0),\n\n restart_(true),\n\n nothing_on_gpu_(true),\n\n fits_on_gpu_(false),\n\n pipeline_loads_(config.pipeline_loads()),\n", "file_path": "src/datahandler.cc", "rank": 18, "score": 7.629375778158275 }, { "content": "#include \"convnet_cpu.h\"\n\n#include <google/protobuf/text_format.h>\n\n#include <sstream>\n\n#include <fstream>\n\n#include <iostream>\n\n#include <stack>\n\nusing namespace std;\n\n\n\nConvNetCPU::ConvNetCPU(\n\n const string& model_structure, const string& model_parameters,\n\n const string& mean_file, int batch_size) {\n\n model_ = new config::Model;\n\n stringstream ss;\n\n string line;\n\n ifstream file(model_structure.c_str());\n\n ss << file.rdbuf();\n\n if (!google::protobuf::TextFormat::ParseFromString(ss.str(), model_)) {\n\n cerr << \"Could not read text proto buffer : \" << model_structure << endl;\n\n exit(1);\n\n }\n", "file_path": "cpu/convnet_cpu.cc", "rank": 19, "score": 7.584741004573548 }, { "content": "#include \"optimizer.h\"\n\n#include <sstream>\n\n#include <iostream>\n\n\n\nusing namespace std;\n\n\n\nOptimizer* Optimizer::ChooseOptimizer(const config::Optimizer& config) {\n\n Optimizer* opt = NULL;\n\n switch (config.optimizer_type()) {\n\n case config::Optimizer::STOCHASTIC_GRADIENT_DESCENT :\n\n opt = new SGDOptimizer(config);\n\n break;\n\n case config::Optimizer::LBFGS :\n\n opt = new LBFGSOptimizer(config);\n\n break;\n\n default:\n\n cerr << \"Undefined optimizer.\" << endl;\n\n exit(1);\n\n }\n\n return opt;\n", "file_path": "src/optimizer.cc", "rank": 20, "score": 7.491999300111483 }, { "content": "#include \"layer.h\"\n\n#include <iostream>\n\n#include <sstream>\n\n#include <set>\n\nusing namespace std;\n\n\n\nLayer* Layer::ChooseLayerClass(const config::Layer& config) {\n\n Layer* l = NULL;\n\n switch (config.activation()) {\n\n case config::Layer::LINEAR :\n\n l = new LinearLayer(config);\n\n break;\n\n case config::Layer::LOGISTIC :\n\n l = new LogisticLayer(config);\n\n break;\n\n case config::Layer::RECTIFIED_LINEAR :\n\n l = new ReLULayer(config);\n\n break;\n\n case config::Layer::SOFTMAX :\n\n l = new SoftmaxLayer(config);\n", "file_path": "src/layer.cc", "rank": 21, "score": 7.476187340690396 }, { "content": "#include \"grad_check.h\"\n\n#include <iostream>\n\nusing namespace std;\n\n\n\nint main(int argc, char** argv) {\n\n int board = atoi(argv[1]);\n\n string model_file(argv[2]);\n\n string data_file(argv[3]);\n\n\n\n Matrix::SetupCUDADevice(board);\n\n cout << \"Using board \" << board << endl;\n\n\n\n GradChecker gcheck = GradChecker(model_file);\n\n gcheck.SetupDataset(data_file);\n\n gcheck.AllocateMemory(false);\n\n gcheck.Run();\n\n\n\n return 0;\n\n}\n", "file_path": "src/run_grad_check.cc", "rank": 22, "score": 6.986890782304137 }, { "content": "#include \"rgb_to_yuv_edge.h\"\n\n#include \"cudamat_conv.cuh\"\n\n\n\nRGBToYUVEdge::RGBToYUVEdge(const config::Edge& edge_config) :\n\n Edge(edge_config), image_size_(0) {}\n\n\n\nvoid RGBToYUVEdge::AllocateMemory(int image_size) {\n\n image_size_ = image_size;\n\n}\n\n\n\nvoid RGBToYUVEdge::ComputeUp(Matrix& input, Matrix& output, bool overwrite) {\n\n cudamat* input_mat = input.GetMat();\n\n cudamat* output_mat = output.GetMat();\n\n RGBToYUV(input_mat, output_mat);\n\n}\n\n\n\nvoid RGBToYUVEdge::ComputeDown(Matrix& deriv_output, Matrix& input,\n\n Matrix& output, Matrix& deriv_input, bool overwrite) {\n\n cerr << \"RGBtoYUV backprop Not implemented.\" << endl;\n\n exit(1);\n\n}\n", "file_path": "src/rgb_to_yuv_edge.cc", "rank": 23, "score": 6.87889360064483 }, { "content": "// Writes jpeg files into an hdf5 dataset as unsigned chars.\n\n// Crops out central 256*256 patch after resizing the image\n\n// so that its shorter side is 256.\n\n#include \"image_iterators.h\"\n\n#include \"hdf5.h\"\n\n#include <string>\n\n#include <iostream>\n\nusing namespace std;\n\n\n\nint main(int argc, char ** argv) {\n\n const int image_size = 256;\n\n const int big_image_size = 256;\n\n string filelist(argv[1]);\n\n string output_file(argv[2]);\n\n string name = \"data\";\n\n RawImageFileIterator<unsigned char> it = RawImageFileIterator<unsigned char>(\n\n filelist, image_size, big_image_size, false, false);\n\n const int dataset_size = it.GetDataSetSize();\n\n const int num_dims = image_size * image_size * 3;\n\n unsigned char* image_buf = new unsigned char[num_dims];\n", "file_path": "src/jpeg2hdf5.cc", "rank": 24, "score": 6.756634353794384 }, { "content": "#include \"convnet.h\"\n\n#include <iostream>\n\nusing namespace std;\n\n\n\nint main(int argc, char** argv) {\n\n int board = atoi(argv[1]);\n\n string model_file(argv[2]);\n\n string data_file(argv[3]);\n\n\n\n Matrix::SetupCUDADevice(board);\n\n cout << \"Using board \" << board << endl;\n\n\n\n ConvNet net = ConvNet(model_file);\n\n if (argc > 4) { // Use a validation set.\n\n string val_data_file(argv[4]);\n\n net.SetupDataset(data_file, val_data_file);\n\n } else {\n\n net.SetupDataset(data_file);\n\n }\n\n net.AllocateMemory(false);\n\n net.Train();\n\n return 0;\n\n}\n", "file_path": "src/train_convnet.cc", "rank": 25, "score": 6.502190772274464 }, { "content": "#include \"multigpu_convnet.h\"\n\n#include <iostream>\n\nusing namespace std;\n\n\n\n\n\nint main(int argc, char** argv) {\n\n vector<int> boards;\n\n boards.push_back(atoi(argv[1]));\n\n boards.push_back(atoi(argv[2]));\n\n string model_file(argv[3]);\n\n string data_file(argv[4]);\n\n\n\n Matrix::SetupCUDADevices(boards);\n\n cout << \"Using boards \" << boards[0] << \" and \" << boards[1] << endl;\n\n\n\n ConvNet *net = new MultiGPUConvNet(model_file);\n\n\n\n if (argc > 5) { // Use a validation set.\n\n string val_data_file(argv[5]);\n\n net->SetupDataset(data_file, val_data_file);\n", "file_path": "src/train_multigpu_convnet.cc", "rank": 26, "score": 6.418985807737682 }, { "content": "#include \"convnet.h\"\n\n#include <iostream>\n\nusing namespace std;\n\n\n\n\n\nint main(int argc, char** argv) {\n\n int board = atoi(argv[1]);\n\n string model_file(argv[2]);\n\n string data_file(argv[3]);\n\n string output_file(argv[4]);\n\n vector<string> layer_names;\n\n for (int i = 5; i < argc; i++) {\n\n layer_names.push_back(string(argv[i]));\n\n }\n\n\n\n Matrix::SetupCUDADevice(board);\n\n cout << \"Using board \" << board << endl;\n\n\n\n ConvNet net = ConvNet(model_file);\n\n net.SetupDataset(data_file);\n\n net.AllocateMemory(true);\n\n cout << \"Dumping outputs to \" << output_file << endl;\n\n net.DumpOutputs(output_file, layer_names);\n\n return 0;\n\n}\n", "file_path": "src/extract_representation.cc", "rank": 27, "score": 6.259033897229557 }, { "content": "#include \"edge_with_weight.h\"\n\n#include <sstream>\n\n#include <iostream>\n\n\n\nEdgeWithWeight::EdgeWithWeight(const config::Edge& edge_config) :\n\n Edge(edge_config),\n\n weight_optimizer_(Optimizer::ChooseOptimizer(edge_config.weight_optimizer())),\n\n bias_optimizer_(Optimizer::ChooseOptimizer(edge_config.bias_optimizer())),\n\n initialization_(edge_config.initialization()),\n\n polyak_queue_size_(edge_config.polyak_queue_size()),\n\n polyak_index_(0),\n\n polyak_queue_full_(false),\n\n init_wt_(edge_config.init_wt()),\n\n init_bias_(edge_config.init_bias()),\n\n has_no_bias_(edge_config.has_no_bias()),\n\n num_grads_received_(0),\n\n num_shares_(1),\n\n scale_gradients_(edge_config.scale_gradients()),\n\n pretrained_model_(edge_config.pretrained_model()),\n\n pretrained_edge_name_(edge_config.has_pretrained_edge_name() ? edge_config.pretrained_edge_name() : name_) {\n", "file_path": "src/edge_with_weight.cc", "rank": 28, "score": 6.2441666710881405 }, { "content": "#include \"upsample_edge.h\"\n\n#include \"cudamat_conv.cuh\"\n\n\n\nUpSampleEdge::UpSampleEdge(const config::Edge& edge_config) :\n\n Edge(edge_config),\n\n sample_factor_(edge_config.sample_factor()) {}\n\n\n\nvoid UpSampleEdge::SetImageSize(int image_size) {\n\n Edge::SetImageSize(image_size);\n\n num_modules_ = image_size * sample_factor_;\n\n}\n\n\n\nvoid UpSampleEdge::ComputeUp(Matrix& input, Matrix& output, bool overwrite) {\n\n cudamat *input_mat = input.GetMat(),\n\n *output_mat = output.GetMat();\n\n int scale_targets = overwrite ? 0 : 1;\n\n UpSample(input_mat, output_mat, sample_factor_, image_size_, scale_targets);\n\n}\n\n\n\nvoid UpSampleEdge::ComputeDown(Matrix& deriv_output, Matrix& input,\n\n Matrix& output, Matrix& deriv_input, bool overwrite) {\n\n cudamat *deriv_output_mat = deriv_output.GetMat(),\n\n *deriv_input_mat = deriv_input.GetMat();\n\n DownSample(deriv_output_mat, deriv_input_mat, sample_factor_,\n\n sample_factor_ * image_size_);\n\n}\n", "file_path": "src/upsample_edge.cc", "rank": 29, "score": 6.220298407819869 }, { "content": "#include \"downsample_edge.h\"\n\n#include \"cudamat_conv.cuh\"\n\n\n\nDownSampleEdge::DownSampleEdge(const config::Edge& edge_config) :\n\n Edge(edge_config),\n\n sample_factor_(edge_config.sample_factor()) {}\n\n\n\nvoid DownSampleEdge::SetImageSize(int image_size) {\n\n Edge::SetImageSize(image_size);\n\n num_modules_ = image_size / sample_factor_;\n\n}\n\n\n\nvoid DownSampleEdge::ComputeUp(Matrix& input, Matrix& output, bool overwrite) {\n\n cudamat *input_mat = input.GetMat(),\n\n *output_mat = output.GetMat();\n\n DownSample(input_mat, output_mat, sample_factor_, image_size_);\n\n}\n\n\n\nvoid DownSampleEdge::ComputeDown(Matrix& deriv_output, Matrix& input,\n\n Matrix& output, Matrix& deriv_input, bool overwrite) {\n\n cudamat* deriv_output_mat = deriv_output.GetMat();\n\n cudamat* deriv_input_mat = deriv_input.GetMat();\n\n\n\n int scale_targets = overwrite ? 0 : 1;\n\n UpSample(deriv_output_mat, deriv_input_mat, sample_factor_,\n\n sample_factor_ * image_size_, scale_targets);\n\n}\n", "file_path": "src/downsample_edge.cc", "rank": 30, "score": 6.203825229450645 }, { "content": "#include \"multigpu_convnet.h\"\n\n#include <iostream>\n\nusing namespace std;\n\n\n\nint main(int argc, char** argv) {\n\n vector<int> boards;\n\n boards.push_back(atoi(argv[1]));\n\n boards.push_back(atoi(argv[2]));\n\n string model_file(argv[3]);\n\n string data_file(argv[4]);\n\n string output_file(argv[5]);\n\n vector<string> layer_names;\n\n for (int i = 6; i < argc; i++) {\n\n layer_names.push_back(string(argv[i]));\n\n }\n\n\n\n Matrix::SetupCUDADevices(boards);\n\n cout << \"Using boards \" << boards[0] << \" and \" << boards[1] << endl;\n\n\n\n ConvNet *net = new MultiGPUConvNet(model_file);\n\n net->SetupDataset(data_file);\n\n net->AllocateMemory(true);\n\n cout << \"Dumping outputs to \" << output_file << endl;\n\n net->DumpOutputs(output_file, layer_names);\n\n delete net;\n\n return 0;\n\n}\n", "file_path": "src/extract_multigpu_representation.cc", "rank": 31, "score": 5.870217866876377 }, { "content": " }\n\n shared_bias_ = ee->GetSharedBias();\n\n}\n\n\n\nvoid ConvEdge::SetImageSize(int image_size) {\n\n Edge::SetImageSize(image_size);\n\n num_modules_ = (image_size + 2 * padding_ - kernel_size_) / stride_ + 1;\n\n if (partial_sum_ > 0) {\n\n int num_locs = num_modules_ * num_modules_;\n\n int partial_sums = num_locs / partial_sum_;\n\n cout << \"Num locs \" << num_locs << \" Partial sum \" << partial_sum_ << endl;\n\n if (partial_sum_ * partial_sums != num_locs) {\n\n cout << \"Partial sum must divide number of locations.\" <<\n\n \" Setting to 1. If this crashes set partial sum to 0.\" << endl;\n\n partial_sum_ = 1;\n\n }\n\n }\n\n}\n\n\n\nvoid ConvEdge::DisplayWeights() {\n", "file_path": "src/conv_edge.cc", "rank": 32, "score": 5.7723542522049875 }, { "content": "#include \"multigpu_convnet.h\"\n\n#include <stdio.h>\n\n\n\nMultiGPUConvNet::MultiGPUConvNet(const string& model_file):\n\n ConvNet(model_file) {}\n\n\n\n\n\nvoid MultiGPUConvNet::Fprop(bool train) {\n\n int dst_layer_gpu_id, edge_gpu_id, src_layer_gpu_id;\n\n Layer *src_layer;\n\n Matrix *dst, *src;\n\n\n\n const int num_gpus = Matrix::GetNumBoards();\n\n vector<bool> overwrite(num_gpus);\n\n for(Layer* l : layers_) {\n\n for (int i = 0; i < num_gpus; i++) overwrite[i] = true;\n\n dst_layer_gpu_id = l->GetGPUId();\n\n for (Edge* e : l->incoming_edge_) {\n\n src_layer = e->GetSource();\n\n edge_gpu_id = e->GetGPUId();\n", "file_path": "src/multigpu_convnet.cc", "rank": 33, "score": 5.69000846826582 }, { "content": "#ifndef UTIL_H_\n\n#define UTIL_H_\n\n\n\n#ifndef _GNU_SOURCE\n\n#define _GNU_SOURCE\n\n#endif\n\n#ifndef __USE_GNU\n\n#define __USE_GNU\n\n#endif\n\n\n\n#include <string>\n\n#define cimg_use_jpeg\n\n#define cimg_use_lapack\n\n#include \"CImg.h\"\n\n#include \"cudamat.cuh\"\n\n#include <stdio.h>\n\n#include <google/protobuf/text_format.h>\n\n#include \"convnet_config.pb.h\"\n\n#include \"hdf5.h\"\n\n#include <signal.h>\n", "file_path": "src/util.h", "rank": 34, "score": 5.115434418896485 }, { "content": "#ifndef CONVNET_CPU\n\n#define CONVNET_CPU\n\n#include \"cpuconv.h\"\n\n#include \"hdf5.h\"\n\n#include \"convnet_config.pb.h\"\n\n#include <vector>\n\n#include <string>\n\nusing namespace std;\n", "file_path": "cpu/convnet_cpu.h", "rank": 35, "score": 5.108478060760426 }, { "content": "#ifndef MATRIX_H_\n\n#define MATRIX_H_\n\n#include <string>\n\n#include \"cudamat.cuh\"\n\n#include \"cublas.h\"\n\n#include \"hdf5.h\"\n\n#include <vector>\n\nusing namespace std;\n\n\n\n/** A GPU matrix class.*/\n", "file_path": "src/matrix.h", "rank": 36, "score": 5.098420426557696 }, { "content": "#ifndef DATAHANDLER_H_\n\n#define DATAHANDLER_H_\n\n#include \"layer.h\"\n\n#include \"image_iterators.h\"\n\n#include <random>\n\n#include <thread>\n\nclass DataIterator;\n\n\n\n/** Makes data accessible to the model.\n\n * Provides a GetBatch() method that is used by the model to fetch\n\n * mini-batches.\n\n * Handles multiple streams of data.\n\n */ \n", "file_path": "src/datahandler.h", "rank": 37, "score": 5.062278936815318 }, { "content": "#ifndef DATAHANDLER_H_\n\n#define DATAHANDLER_H_\n\n#include \"layer.h\"\n\n#include \"image_iterators.h\"\n\n#include <random>\n\n#include <thread>\n", "file_path": "src/datahandler.h", "rank": 38, "score": 5.062278936815318 }, { "content": "#ifndef CONVNET_H_\n\n#define CONVNET_H_\n\n#include \"layer.h\"\n\n#include \"hdf5.h\"\n\n#include \"datahandler.h\"\n\n#include <vector>\n\n#include <string>\n\nusing namespace std;\n\n\n\n/**\n\n * A Convolutional Net Model.\n\n * This class provides the interface for training and using conv nets.\n\n */\n", "file_path": "src/convnet.h", "rank": 39, "score": 5.048720512510213 }, { "content": "#ifndef CPUCONV_H_\n\n#define CPUCONV_H_\n\n#include \"hdf5.h\"\n\n//#include <smmintrin.h>\n\n#include <string>\n\nusing namespace std;\n", "file_path": "cpu/cpuconv.h", "rank": 40, "score": 4.892881248789898 }, { "content": "#ifndef OPTIMIZER_H_\n\n#define OPTIMIZER_H_\n\n#include \"util.h\"\n\n#include \"matrix.h\"\n\n\n\n/** Base class for all optimizers.\n\n */\n", "file_path": "src/optimizer.h", "rank": 41, "score": 4.647693752593307 }, { "content": "#ifndef LAYER_H_\n\n#define LAYER_H_\n\n#include \"edge.h\"\n\n#include <set>\n\n\n\n/** The base class for all layers.\n\n * Each layer has a state_ and deriv_.\n\n */ \n", "file_path": "src/layer.h", "rank": 42, "score": 4.585963504905683 }, { "content": "#ifndef EDGE_WITH_WEIGHT_H_\n\n#define EDGE_WITH_WEIGHT_H_\n\n#include \"edge.h\"\n\n#include \"optimizer.h\"\n\n\n\n/** Base class for all edges which have weights.\n\n * All edges which have trainable parameters should inherit from this class.\n\n */ \n", "file_path": "src/edge_with_weight.h", "rank": 43, "score": 4.506162907813163 }, { "content": " void SquashRelu();\n\n\n\n int GetGPUId() const { return gpu_id_; }\n\n void SetReady();\n\n void WaitTillReady();\n\n\n\n static void GetOnes(int rows, int cols, Matrix& ones);\n\n static void RegisterTempMemory(int size);\n\n static void RegisterTempMemory(int size, const string& why);\n\n static void RegisterOnes(int size);\n\n static void GetTemp(int rows, int cols, Matrix& temp);\n\n static void InitRandom(int seed);\n\n static void SetupCUDADevice(int gpu_id);\n\n static void SetupCUDADevices(const vector<int>& boards);\n\n static void SetDevice(int gpu_id);\n\n static void SyncAllDevices();\n\n static int GetDevice();\n\n static int GetNumBoards() {return num_boards_;}\n\n\n\n static vector<Matrix> ones_, temp_;\n", "file_path": "src/matrix.h", "rank": 44, "score": 4.384139306264894 }, { "content": " void CopyToDeviceSlice(const int start, const int end);\n\n void CopyToHostSlice(const int start, const int end);\n\n void CopyFromMainMemory(Matrix& mat);\n\n void Reshape(const int rows, const int cols);\n\n float Norm();\n\n void Print();\n\n void WriteToFile(FILE* file);\n\n void ReadFromFile(FILE* file);\n\n void WriteHDF5(hid_t file, const string& name);\n\n void ReadHDF5(hid_t file, const string& name);\n\n void AllocateAndReadHDF5(hid_t file, const string& name);\n\n string GetShapeString();\n\n cudamat* GetMat() { return &mat_; }\n\n cudamat* GetMatTranspose() { return &mat_t_; }\n\n float* GetHostData() { return mat_.data_host; }\n\n int GetRows() const {return mat_.size[0];}\n\n int GetCols() const {return mat_.size[1];}\n\n int GetNumEls() const {return mat_.size[1] * mat_.size[0]; }\n\n float Sum();\n\n void Add(Matrix& m);\n", "file_path": "src/matrix.h", "rank": 45, "score": 4.30906373076411 }, { "content": " * @param error A vector of errors (one element for each output layer).\n\n */ \n\n void Validate(vector<float>& error);\n\n\n\n /** Write the model to disk.*/\n\n void Save();\n\n\n\n /** Write the model to disk in the file specified. */\n\n void Save(const string& output_file);\n\n\n\n /** Load the model.*/\n\n void Load();\n\n\n\n /** Load the model from the file specified.*/\n\n void Load(const string& input_file);\n\n\n\n /** Display the state of the model.\n\n * Shows the layers and edges for which display is enabled.\n\n */ \n\n void Display();\n", "file_path": "src/convnet.h", "rank": 46, "score": 4.266360546617104 }, { "content": " /** Computes the loss function (to be displayed).*/ \n\n virtual void GetLoss(vector<float>& error);\n\n\n\n /** Write the state of the layers to disk.\n\n * This method runs the model on the specified dataset and writes the layer\n\n * states out to disk in a hdf5 file.\n\n * @param output_file: The name of the output hdf5 file.\n\n * @param dataset: The dataset to be run.\n\n * @param layers: The layers whose state needs to be written out.\n\n */ \n\n void DumpOutputs(const string& output_file, DataHandler* dataset, vector<Layer*>& layers) ;\n\n\n\n\n\n /** Takes one optimization step.*/ \n\n virtual void TrainOneBatch(vector<float>& error);\n\n void DisplayLayers();\n\n void DisplayEdges();\n\n void InsertPolyak();\n\n void LoadPolyakWeights();\n\n void LoadCurrentWeights();\n", "file_path": "src/convnet.h", "rank": 47, "score": 4.226864085202575 }, { "content": " return tied_edge_name_;\n\n}\n\n/*\n\nbool Edge::RequiresMemoryForDeriv() const {\n\n return false;\n\n} \n\n*/\n\n\n\nbool Edge::IsTied() {\n\n return is_tied_;\n\n}\n\n\n\nvoid Edge::SetImageSize(int image_size) {\n\n image_size_ = image_size;\n\n}\n\n\n\nvoid Edge::InsertPolyak() {\n\n}\n\n\n\nvoid Edge::BackupCurrent() {\n\n}\n\nvoid Edge::LoadCurrentOnGPU() {\n\n}\n\nvoid Edge::LoadPolyakOnGPU() {\n\n}\n", "file_path": "src/edge.cc", "rank": 48, "score": 4.22535090308359 }, { "content": " virtual float GetLoss2();\n\n\n\n /** Apply dropout to this layer.\n\n * @param train If train is true, drop units stochastically,\n\n * else use all the units.\n\n */ \n\n void ApplyDropout(bool train);\n\n\n\n /** Apply derivative of dropout.\n\n * This method scales the derivative to compensate for dropout.\n\n */ \n\n void ApplyDerivativeofDropout();\n\n\n\n // Methods for preventing race conditions when using multiple GPUs.\n\n void AccessStateBegin();\n\n void AccessStateEnd();\n\n void AccessDerivBegin();\n\n void AccessDerivEnd();\n\n\n\n /** Returns the incoming edge by index. */\n", "file_path": "src/layer.h", "rank": 49, "score": 4.19955289193619 }, { "content": " // no op.\n\n}\n\n\n\nvoid Edge::ComputeOuter(Matrix& input, Matrix& deriv_output) {\n\n // no op.\n\n}\n\n\n\nvoid Edge::UpdateWeights() {\n\n // no op.\n\n}\n\n\n\nfloat Edge::GetRMSWeight() {\n\n return 0;\n\n}\n\n\n\nvoid Edge::SetSource(Layer* source) {\n\n source_ = source;\n\n}\n\n\n\nvoid Edge::SetDest(Layer* dest) {\n", "file_path": "src/edge.cc", "rank": 50, "score": 4.165293669269424 }, { "content": " * @param file The file handle. The file has been opened for reading. Do not close it.\n\n */ \n\n virtual void LoadParameters(hid_t file);\n\n\n\n virtual void InsertPolyak();\n\n virtual void BackupCurrent();\n\n virtual void LoadCurrentOnGPU();\n\n virtual void LoadPolyakOnGPU();\n\n\n\n /** Returns the root mean square weight value.*/\n\n virtual float GetRMSWeight();\n\n\n\n /** Reduce the learning rate by factor.*/\n\n virtual void ReduceLearningRate(float factor);\n\n\n\n /** Returns whether the edge has any parameters.*/\n\n virtual bool HasNoParameters() const;\n\n\n\n /** Returns the number of modules.\n\n * This is relevant for convolution-like edges.\n", "file_path": "src/edge.h", "rank": 51, "score": 4.160463257167576 }, { "content": "void Edge::SetInputChannels(int a) {\n\n num_input_channels_ = a;\n\n}\n\n\n\nvoid Edge::SetOutputChannels(int a) {\n\n num_output_channels_ = a;\n\n}\n\n\n\nvoid Edge::SaveParameters(hid_t file) {\n\n // no op.\n\n // Parameter saving implemented in EdgeWithWeight or derived classes thereof.\n\n}\n\n\n\nvoid Edge::LoadParameters(hid_t file) {\n\n // no op.\n\n // Parameter loading implemented in EdgeWithWeight or derived classes thereof.\n\n}\n\n\n\nvoid Edge::Initialize() {\n\n // no op. Initialization done in derived classes.\n", "file_path": "src/edge.cc", "rank": 52, "score": 4.123989970797976 }, { "content": "void WriteHDF5CPU(hid_t file, float* mat, int rows, int cols, const string& name);\n\nvoid ReadHDF5IntAttr(hid_t file, const string& name, int* val);\n\nvoid WriteHDF5IntAttr(hid_t file, const string& name, const int* val);\n\n\n\n// mat must already be allocated. Use ReadHDF5Shape to figure out the shape, if needed.\n\nvoid ReadHDF5CPU(hid_t file, float* mat, int size, const string& name);\n\nvoid ReadHDF5Shape(hid_t file, const string& name, int* rows, int* cols);\n\nvoid ReadHDF5ShapeFromFile(const string& file_name, const string& dataset_name, int* rows, int* cols);\n\n\n\nvoid SetupBackTraceHandler();\n\nvoid WaitForEnter();\n\nint Bound(int val, int lb, int ub);\n\nstring GetTimeStamp();\n\nvoid TimestampModelFile(const string& src_file, const string& dest_file, const string& timestamp);\n\n\n\nbool ReadLines(const string& filename, vector<string>& lines);\n\n\n\n\n", "file_path": "src/util.h", "rank": 53, "score": 4.118939537873279 }, { "content": " /** Allocate memory for the model.\n\n * @param fprop_only If true, does not allocate memory needed for optimization.\n\n */ \n\n void AllocateMemory(bool fprop_only);\n\n\n\n protected:\n\n /** Creates layers and edges.*/ \n\n void BuildNet();\n\n\n\n /** Release all memory held by the model.*/\n\n void DestroyNet();\n\n\n\n /** Allocate layer memory for using mini-batches of batch_size_.*/\n\n void AllocateLayerMemory();\n\n\n\n /** Allocate memory for edges.\n\n * @param fprop_only If true, does not allocate memory needed for optimization.\n\n */ \n\n void AllocateEdgeMemory(bool fprop_only);\n\n \n", "file_path": "src/convnet.h", "rank": 54, "score": 4.108826025434346 }, { "content": " const float scale_targets);\n\n\n\n static void FCUp(\n\n const float* inputs, const float* weights, float* targets,\n\n const int num_images, const int num_outputs, const int num_inputs,\n\n const float scale_outputs, const float scale_targets);\n\n\n\n static void UpperBound(const float* inputs, float* outputs, const int length, const float limit);\n\n static void LowerBound(const float* inputs, float* outputs, const int length, const float limit);\n\n static void AddBias(const float* inputs, const float* bias, float* outputs, const int num_images, const int num_dims);\n\n static void Softmax(const float* inputs, float* outputs, const int num_images, const int num_dims);\n\n static void Logistic(const float* inputs, float* outputs, const int length);\n\n static void Argmax(const float* inputs, int* outputs, const int num_images, const int num_dims);\n\n static void ReadHDF5(hid_t file, float* mat, int size, const string& name);\n\n static void ReadHDF5Shape(hid_t file, const string& name, int* rows, int* cols);\n\n\n\n private:\n\n float* data_;\n\n int rows_, cols_;\n\n};\n\n#endif\n", "file_path": "cpu/cpuconv.h", "rank": 55, "score": 4.08547442784018 }, { "content": " Matrix& GetGradWeight() { return grad_weights_;}\n\n Matrix& GetBias() { return bias_;}\n\n Matrix& GetGradBias() { return grad_bias_;}\n\n\n\n float GetDecayedEpsilon(float base_epsilon) const;\n\n float GetMomentum() const;\n\n\n\n virtual void InsertPolyak();\n\n virtual void BackupCurrent();\n\n virtual void LoadCurrentOnGPU();\n\n virtual void LoadPolyakOnGPU();\n\n\n\n protected:\n\n // Tied edge management.\n\n void IncrementNumGradsReceived();\n\n int GetNumGradsReceived();\n\n\n\n Matrix weights_, grad_weights_, bias_, grad_bias_;\n\n Optimizer * const weight_optimizer_;\n\n Optimizer * const bias_optimizer_;\n", "file_path": "src/edge_with_weight.h", "rank": 56, "score": 4.020133636865622 }, { "content": " \n\n /** Set the spatial size of the input to this edge.*/\n\n virtual void SetImageSize(int image_size);\n\n\n\n /** Returns whether back prop is blocked through this edge.*/\n\n bool IsBackPropBlocked() const { return block_backprop_; }\n\n\n\n void SetSource(Layer* source);\n\n void SetDest(Layer* dest);\n\n Layer* GetSource();\n\n Layer* GetDest();\n\n const string& GetSourceName();\n\n const string& GetDestName();\n\n const string& GetName();\n\n\n\n /** Set the number of input channels.*/\n\n void SetInputChannels(int a);\n\n /** Set the number of output channels.*/\n\n void SetOutputChannels(int a);\n\n\n", "file_path": "src/edge.h", "rank": 57, "score": 4.020133636865622 }, { "content": "#ifndef MULTIGPU_CONVNET_H_\n\n#define MULTIGPU_CONVNET_H_\n\n#include \"convnet.h\"\n\n\n", "file_path": "src/multigpu_convnet.h", "rank": 58, "score": 4.009027614214986 }, { "content": "#ifndef GRAD_CHECK_H_\n\n#define GRAD_CHECK_H_\n\n\n\n#include \"convnet.h\"\n\n\n", "file_path": "src/grad_check.h", "rank": 59, "score": 4.009027614214986 }, { "content": " const string& GetName() const { return name_; }\n\n int GetNumChannels() const { return num_channels_; }\n\n int GetSize() const { return image_size_; }\n\n bool IsInput() const { return is_input_; }\n\n bool IsOutput() const { return is_output_; }\n\n\n\n int GetGPUId() const { return gpu_id_; }\n\n void AllocateMemoryOnOtherGPUs();\n\n Matrix& GetOtherState(int gpu_id);\n\n Matrix& GetOtherDeriv(int gpu_id);\n\n\n\n void AccumulateState();\n\n void AccumulateDeriv();\n\n void BroadcastState();\n\n void BroadcastDeriv();\n\n\n\n static Layer* ChooseLayerClass(const config::Layer& layer_config);\n\n\n\n vector<Edge*> incoming_edge_, outgoing_edge_;\n\n bool has_incoming_from_same_gpu_, has_outgoing_to_same_gpu_;\n", "file_path": "src/layer.h", "rank": 60, "score": 3.9772079844057737 }, { "content": "}\n\n\n\nvoid Matrix::RegisterTempMemory(int size, const string& why) {\n\n if (size > temp_size_[current_gpu_id_]) {\n\n temp_size_[current_gpu_id_] = size;\n\n //cout << \"Max for \" << why << \" \" << size << endl;\n\n }\n\n}\n\n\n\nvoid Matrix::RegisterTempMemory(int size) {\n\n RegisterTempMemory(size, \"\");\n\n}\n\n\n\nvoid Matrix::RegisterOnes(int size) {\n\n if (size > ones_size_[current_gpu_id_]) {\n\n ones_size_[current_gpu_id_] = size;\n\n }\n\n}\n\n\n\nvoid Matrix::SetReady() {\n", "file_path": "src/matrix.cc", "rank": 61, "score": 3.9710157661835583 }, { "content": " */ \n\n virtual int GetNumModules() const;\n\n\n\n /** Displays the weights.\n\n * Supportsinput layer weights only.\n\n */\n\n virtual void DisplayWeights();\n\n\n\n /** Displays the statistics of the weights.*/\n\n virtual void DisplayWeightStats();\n\n\n\n /** Sets the edge to be tied to another edge.*/\n\n virtual void SetTiedTo(Edge* e);\n\n\n\n /** Computes the output layer state given the input.\n\n * Applies the weights and adds bias.\n\n */\n\n virtual void ComputeUp(Matrix& input, Matrix& output, bool overwrite) = 0;\n\n \n\n /** Computes the derivative w.r.t the inputs of this edge given the derivative\n", "file_path": "src/edge.h", "rank": 62, "score": 3.962215484424344 }, { "content": " Edge* GetIncomingEdge(int index) { return incoming_edge_[index]; } // TODO:add check for size.\n\n\n\n /** Returns a reference to the state of the layer.*/\n\n Matrix& GetState() { return state_;}\n\n\n\n /** Returns a reference to the deriv at this layer.*/\n\n Matrix& GetDeriv() { return deriv_;}\n\n \n\n /** Returns a reference to the data at this layer.*/\n\n Matrix& GetData() { return data_;}\n\n\n\n void Display();\n\n void Display(int image_id);\n\n\n\n /** Add an incoming edge to this layer.*/\n\n void AddIncoming(Edge* e);\n\n\n\n /** Add an outgoing edge from this layer.*/\n\n void AddOutgoing(Edge* e);\n\n\n", "file_path": "src/layer.h", "rank": 63, "score": 3.9360471241736135 }, { "content": " Matrix::SetDevice(gpu_id_);\n\n\n\n}\n\n\n\nvoid Edge::AllocateMemory(bool fprop_only) {\n\n Matrix::SetDevice(gpu_id_);\n\n Matrix::RegisterTempMemory(num_output_channels_, \"Used for computing average length of incoming weight vectors.\");\n\n // Actual memory allocation will happen in the derived class because memory\n\n // requirements differ for different kinds of edges.\n\n}\n\n\n\nvoid Edge::DisplayWeights() {\n\n // no op.\n\n}\n\n\n\nvoid Edge::DisplayWeightStats() {\n\n // no op.\n\n}\n\n\n\nvoid Edge::ReduceLearningRate(float factor) {\n", "file_path": "src/edge.cc", "rank": 64, "score": 3.9360471241736135 }, { "content": " mat_.owns_data = 1;\n\n}\n\n\n\nvoid Matrix::CopyToDevice() {\n\n CopyToDeviceSlice(0, mat_.size[1]);\n\n}\n\n\n\nvoid Matrix::CopyToHost() {\n\n CopyToHostSlice(0, mat_.size[1]);\n\n}\n\n\n\nvoid Matrix::CopyFromMainMemory(Matrix& mat) {\n\n float* src = mat.GetHostData();\n\n float* dest = GetHostData();\n\n memcpy(dest, src, sizeof(float) * GetNumEls());\n\n}\n\n\n\nvoid Matrix::Set(const float val) {\n\n int err_code = assign_scalar(&mat_, val);\n\n if (err_code != 0) {\n", "file_path": "src/matrix.cc", "rank": 65, "score": 3.927400981282825 }, { "content": " printf(\"%d\\n\", *foo);\n\n}\n\n\n\nvoid bar() { baz(); }\n\nvoid foo() { bar(); }\n\n\n\n\n\nint main(int argc, char **argv) {\n\n signal(SIGSEGV, handler);\n\n foo();\n\n}\n", "file_path": "src/backtrace.cc", "rank": 66, "score": 3.905908825375566 }, { "content": "#ifndef MAXPOOL_EDGE_H_\n\n#define MAXPOOL_EDGE_H_\n\n#include \"edge.h\"\n\n\n\n/** Implements a Max-pool edge.*/\n", "file_path": "src/maxpool_edge.h", "rank": 67, "score": 3.8886255784418604 }, { "content": "#ifndef CONV_EDGE_H_\n\n#define CONV_EDGE_H_\n\n#include \"edge_with_weight.h\"\n\n\n\n/** Implements a convolutional edge.*/\n", "file_path": "src/conv_edge.h", "rank": 68, "score": 3.8886255784418604 }, { "content": "#ifndef LOCAL_EDGE_H_\n\n#define LOCAL_EDGE_H_\n\n#include \"edge_with_weight.h\"\n\n\n\n/** Implements a locally connected edge.*/\n", "file_path": "src/local_edge.h", "rank": 69, "score": 3.8596466489719434 }, { "content": "#ifndef FC_EDGE_H_\n\n#define FC_EDGE_H_\n\n#include \"edge_with_weight.h\"\n\n\n\n/** Implements a fully-connected edge.*/\n", "file_path": "src/fc_edge.h", "rank": 70, "score": 3.8596466489719434 }, { "content": "void Layer::ApplyDropoutAtTestTime() {\n\n if (dropprob_ > 0) {\n\n // Scale down.\n\n if (!dropout_scale_up_at_train_time_ && !gaussian_dropout_) {\n\n mult_by_scalar(state_.GetMat(), 1 - dropprob_, state_.GetMat());\n\n }\n\n }\n\n}\n\n\n\nfloat Layer::GetLoss2() {\n\n return GetLoss();\n\n}\n\n\n\nvoid Layer::Display() {\n\n Display(0);\n\n}\n\n\n\nvoid Layer::Display(int image_id) {\n\n if (img_display_ != NULL && display_) {\n\n state_.CopyToHost();\n", "file_path": "src/layer.cc", "rank": 71, "score": 3.8360990580507277 }, { "content": "\n\nvoid ConvNet::InsertPolyak() {\n\n for (Edge* e : edges_) e->InsertPolyak();\n\n}\n\n\n\nvoid ConvNet::LoadPolyakWeights() {\n\n for (Edge* e : edges_) {\n\n e->BackupCurrent();\n\n e->LoadPolyakOnGPU();\n\n }\n\n}\n\n\n\nvoid ConvNet::LoadCurrentWeights() {\n\n for (Edge* e : edges_) e->LoadCurrentOnGPU();\n\n}\n\n\n\nstring ConvNet::GetCheckpointFilename() {\n\n string filename = checkpoint_dir_ + \"/\" + model_name_ + \"_\" + timestamp_ + \".h5\";\n\n return filename;\n\n}\n", "file_path": "src/convnet.cc", "rank": 72, "score": 3.825156103684682 }, { "content": "#ifndef UPSAMPLE_EDGE_H_\n\n#define UPSAMPLE_EDGE_H_\n\n#include \"edge.h\"\n\n\n\n/** Implements an up-sampling edge.\n\n * Only integer up-sampling factors are supported.\n\n */ \n", "file_path": "src/upsample_edge.h", "rank": 73, "score": 3.802965507020178 }, { "content": "#ifndef RESPONSE_NORM_EDGE_H_\n\n#define RESPONSE_NORM_EDGE_H_\n\n#include \"edge.h\"\n\n\n\n/** Response Normalization across filters at the same location.\n\n */\n", "file_path": "src/response_norm_edge.h", "rank": 74, "score": 3.802965507020178 }, { "content": "#ifndef RGB_TO_YUV_EDGE_H_\n\n#define RGB_TO_YUV_EDGE_H_\n\n#include \"edge.h\"\n\n\n\n/** Implements an edge that maps RGB to YUV.*/\n", "file_path": "src/rgb_to_yuv_edge.h", "rank": 75, "score": 3.802965507020178 }, { "content": " * @param edge the edge connecting the input to the output.\n\n * @param overwrite If true, overwrite the deriv present in input, else add\n\n * to it.\n\n * @param update_weights If true, the weights will be updated.\n\n */ \n\n virtual void Bprop(Layer& output, Layer& input, Edge& edge, bool overwrite, bool update_weights);\n\n\n\n /** Forward propagate through the network.\n\n * @param train If true, this forward prop is being done during training,\n\n * otherwise during test/validation. Used for determining whether to use drop\n\n * units stochastcially or use all of them.\n\n */ \n\n virtual void Fprop(bool train);\n\n\n\n /** Backpropagate through the network and update weights.*/ \n\n virtual void Bprop(bool update_weights);\n\n \n\n /** Computes the derivative of the loss function.*/ \n\n virtual void ComputeDeriv();\n\n\n", "file_path": "src/convnet.h", "rank": 76, "score": 3.778018819073136 }, { "content": " name_(config.name()),\n\n num_channels_(config.num_channels()),\n\n is_input_(config.is_input()),\n\n is_output_(config.is_output()),\n\n image_size_(0), batch_size_(0), num_dims_(0) {}\n\n\n\nLayer::~Layer() {\n\n state_.FreeMemory();\n\n}\n\nvoid Layer::Print() {\n\n state_.Print(image_size_ * image_size_, num_channels_);\n\n}\n\nvoid Layer::AddIncoming(Edge* e) {\n\n incoming_edge_.push_back(e);\n\n}\n\n\n\nvoid Layer::AddOutgoing(Edge* e) {\n\n outgoing_edge_.push_back(e);\n\n}\n\n\n", "file_path": "cpu/convnet_cpu.cc", "rank": 77, "score": 3.7607873933827625 }, { "content": "#ifndef DOWNSAMPLE_EDGE_H_\n\n#define DOWNSAMPLE_EDGE_H_\n\n#include \"edge.h\"\n\n\n\n/** Implements a down-sampling edge.\n\n * Only integer down-sampling factors are supported.\n\n */ \n", "file_path": "src/downsample_edge.h", "rank": 78, "score": 3.747925061161524 }, { "content": "#ifndef CONV_ONETOONE_EDGE_H_\n\n#define CONV_ONETOONE_EDGE_H_\n\n#include \"edge_with_weight.h\"\n\n\n\n/** An edge with one-to-one connectivity over spatial locations.\n\n */ \n", "file_path": "src/conv_onetoone_edge.h", "rank": 79, "score": 3.747925061161524 }, { "content": " }\n\n}\n\n\n\nvoid ConvNet::DisplayEdges() {\n\n for (int i = 0; i < edges_.size(); i++){\n\n edges_[i]->DisplayWeights();\n\n }\n\n}\n\n\n\nvoid ConvNet::WriteLog(int current_iter, float time, float training_error) {\n\n vector<float> temp(1);\n\n temp[0] = training_error;\n\n WriteLog(current_iter, time, temp);\n\n}\n\n\n\nvoid ConvNet::WriteLog(int current_iter, float time_, const vector<float>& training_error) {\n\n\n\n\ttime_t now = time(0);\n\n\t struct tm tstruct;\n\n\t char buf[80];\n", "file_path": "src/convnet.cc", "rank": 80, "score": 3.7294086446289083 }, { "content": "#include \"image_iterators.h\"\n\n#include <fstream>\n\n\n\ntemplate <typename T>\n\nRawImageFileIterator<T>::RawImageFileIterator(\n\n const string& filelist, const int image_size, const int raw_image_size,\n\n const bool flip, const bool translate) :\n\n row_(0), image_id_(-1), position_(0), image_size_(image_size),\n\n num_positions_((flip ? 2 : 1) * (translate ? 5 : 1)),\n\n raw_image_size_(raw_image_size) {\n\n\n\n ifstream f(filelist, ios::in);\n\n if (!f.is_open()) {\n\n cerr << \"Could not open data file : \" << filelist << endl;\n\n exit(1);\n\n }\n\n while (!f.eof()) {\n\n string str;\n\n f >> str;\n\n if (!f.eof()) filenames_.push_back(str);\n", "file_path": "src/image_iterators.cc", "rank": 81, "score": 3.7277595745580117 }, { "content": " img_display_->DisplayImage(state_.GetHostData(), state_.GetRows(), image_id);\n\n //copy_to_host(&deriv_);\n\n //img_display->DisplayImage(deriv_.data_host, deriv_.size[0], image_id);\n\n }\n\n}\n\n\n\nvoid Layer::ApplyDropout(bool train) {\n\n if (train) {\n\n ApplyDropoutAtTrainTime();\n\n } else {\n\n ApplyDropoutAtTestTime();\n\n }\n\n}\n\n\n\nvoid LinearLayer::ApplyActivation(bool train) {\n\n // Linear layer, do nothing.\n\n ApplyDropout(train);\n\n}\n\n\n\nvoid LinearLayer::ApplyDerivativeOfActivation() {\n", "file_path": "src/layer.cc", "rank": 82, "score": 3.6883758827702726 }, { "content": " for (Layer* l: output_layers_) l->ComputeDeriv();\n\n}\n\n\n\nvoid ConvNet::GetLoss(vector<float>& error) {\n\n error.clear();\n\n for (Layer* l: output_layers_) {\n\n error.push_back(l->GetLoss());\n\n }\n\n}\n\n\n\nvoid ConvNet::TrainOneBatch(vector<float>& error) {\n\n train_dataset_->GetBatch(data_layers_);\n\n Fprop(true);\n\n ComputeDeriv();\n\n GetLoss(error);\n\n Bprop(true);\n\n}\n\n\n\nvoid ConvNet::SetupDataset(const string& train_data_config_file) {\n\n SetupDataset(train_data_config_file, \"\");\n", "file_path": "src/convnet.cc", "rank": 83, "score": 3.668196246082694 }, { "content": " for (Edge* e : edges_) {\n\n e->ReduceLearningRate(factor);\n\n }\n\n}\n\n\n\nvoid ConvNet::Validate(vector<float>& error) {\n\n Validate(val_dataset_, error);\n\n}\n\n\n\nvoid ConvNet::TimestampModel() {\n\n timestamp_ = GetTimeStamp();\n\n string fname = checkpoint_dir_ + \"/\" + model_name_ + \"_\" + timestamp_;\n\n TimestampModelFile(model_filename_, fname + \".pbtxt\", timestamp_);\n\n log_file_ = fname + \"_train.log\";\n\n val_log_file_ = fname + \"_valid.log\";\n\n}\n\n\n\nvoid ConvNet::AddVectors(vector<float>& a, vector<float>& b) {\n\n if (a.size() == 0) a.resize(b.size());\n\n if (a.size() != b.size()) {\n", "file_path": "src/convnet.cc", "rank": 84, "score": 3.638337442343515 }, { "content": " void LoadParameters(hid_t file);\n\n void AllocateMemory();\n\n\n\n void ComputeUp(const float* input, float* output, bool overwrite, int batch_size);\n\n void ComputeUp(const float* input, float* output, bool overwrite, int batch_size, int image_size);\n\n\n\n private:\n\n const config::Edge::EdgeType edge_type_;\n\n Layer *source_, *dest_;\n\n const string source_node_, dest_node_, name_, tied_edge_name_;\n\n Edge* tied_edge_;\n\n int num_input_channels_, num_output_channels_, image_size_, num_modules_;\n\n bool mark_; // Used for topological sorting.\n\n\n\n const int kernel_size_, stride_, padding_, factor_;\n\n const bool is_tied_, shared_bias_, blocked_;\n\n const float add_scale_, pow_scale_, frac_of_filters_response_norm_;\n\n int num_filters_response_norm_;\n\n CPUMatrix weights_, bias_;\n\n};\n\n\n", "file_path": "cpu/convnet_cpu.h", "rank": 85, "score": 3.6248260867644815 }, { "content": "}\n\n\n\nOptimizer::Optimizer(const config::Optimizer& optimizer_config) :\n\n epsilon_decay_type_(optimizer_config.epsilon_decay()),\n\n epsilon_(optimizer_config.epsilon()),\n\n minimum_epsilon_(optimizer_config.minimum_epsilon()),\n\n epsilon_decay_timescale_(optimizer_config.epsilon_decay_timescale()),\n\n start_optimization_after_(optimizer_config.start_optimization_after()),\n\n l2_decay_(optimizer_config.l2_decay()),\n\n weight_norm_limit_(optimizer_config.weight_norm_limit()), // impose upper limit.\n\n weight_norm_constraint_(optimizer_config.weight_norm_constraint()), // impose equality.\n\n step_(0) \n\n{}\n\n\n\nOptimizer::~Optimizer() {}\n\nvoid Optimizer::AllocateMemory(const int rows, const int cols) {}\n\nvoid Optimizer::LoadParameters(hid_t file, const string& prefix) {}\n\nvoid Optimizer::SaveParameters(hid_t file, const string& prefix) {}\n\nvoid Optimizer::ReduceLearningRate(float factor) {\n\n epsilon_ *= factor;\n", "file_path": "src/optimizer.cc", "rank": 86, "score": 3.617491905865669 }, { "content": " center_x_(0), center_y_(0), done_(true) {}\n\n\n\ntemplate <typename T>\n\nvoid SlidingWindowIterator<T>::SetImage(const string& filename) {\n\n image_.assign(filename.c_str());\n\n center_x_ = 0;\n\n center_y_ = 0;\n\n int num_modules_x = (image_.width() - window_size_ % 2) / stride_ + 1;\n\n int num_modules_y = (image_.height() - window_size_ % 2) / stride_ + 1;\n\n num_windows_ = num_modules_x * num_modules_y;\n\n done_ = false;\n\n}\n\n\n\ntemplate <typename T>\n\nvoid SlidingWindowIterator<T>::Reset() {\n\n done_ = true;\n\n}\n\n\n\ntemplate <typename T>\n\nvoid SlidingWindowIterator<T>::GetNext(T* data_ptr) {\n", "file_path": "src/image_iterators.cc", "rank": 87, "score": 3.5992737351509234 }, { "content": " * w.r.t the outputs of this edge.\n\n * @param deriv_output Derivative w.r.t outputs of this edge.(In)\n\n * @param input The input to this edge.(In)\n\n * @param output The output of this edge.(In)\n\n * @param deriv_input Derivative w.r.t inputs of this edge.(Out)\n\n */\n\n virtual void ComputeDown(Matrix& deriv_output, Matrix& input,\n\n Matrix& output, Matrix& deriv_input,\n\n bool overwrite) = 0;\n\n\n\n /** Computes the gradient for the weights and biases.\n\n * @param input The input to this edge.\n\n * @param deriv_output The derivative w.r.t the output of this edge.\n\n */ \n\n virtual void ComputeOuter(Matrix& input, Matrix& deriv_output);\n\n \n\n /** Update the weights.*/\n\n virtual void UpdateWeights();\n\n\n\n //virtual bool RequiresMemoryForDeriv() const;\n", "file_path": "src/edge.h", "rank": 88, "score": 3.5896385246683185 }, { "content": " outputs[i] = inputs[i] + bias[i % num_dims];\n\n }\n\n}\n\n\n\nvoid CPUMatrix::UpperBound(const float* inputs, float* outputs, const int length, const float limit) {\n\n #pragma omp parallel for if(length > 10000)\n\n for (int i = 0; i < length; i++) {\n\n outputs[i] = inputs[i] > limit ? limit : inputs[i];\n\n }\n\n}\n\n\n\nvoid CPUMatrix::LowerBound(const float* inputs, float* outputs, const int length, const float limit) {\n\n #pragma omp parallel for if(length > 10000)\n\n for (int i = 0; i < length; i++) {\n\n outputs[i] = inputs[i] < limit ? limit : inputs[i];\n\n }\n\n}\n\n\n\nvoid CPUMatrix::Argmax(const float* inputs, int* outputs, const int num_images, const int num_dims) {\n\n #pragma omp parallel for if(num_images > 1000)\n", "file_path": "cpu/cpuconv.cc", "rank": 89, "score": 3.580054763131887 }, { "content": " }\n\n}\n\n\n\nvoid ConvNet::Bprop(bool update_weights) {\n\n Layer *l;\n\n bool overwrite;\n\n for (int i = layers_.size() - 1; i >= 0; i--) {\n\n overwrite = true;\n\n l = layers_[i];\n\n for (Edge* e : l->outgoing_edge_) {\n\n Bprop(*(e->GetDest()), *l, *e, overwrite, update_weights);\n\n overwrite = false;\n\n }\n\n if (!l->IsInput() && l->outgoing_edge_.size() > 0) {\n\n l->ApplyDerivativeOfActivation();\n\n }\n\n }\n\n}\n\n\n\nvoid ConvNet::ComputeDeriv() {\n", "file_path": "src/convnet.cc", "rank": 90, "score": 3.577643279449669 }, { "content": " void WriteLog(int current_iter, float time, float training_error);\n\n void WriteLog(int current_iter, float time, const vector<float>& training_error);\n\n void WriteValLog(int current_iter, const vector<float>& error);\n\n Layer* GetLayerByName(const string& name);\n\n \n\n /** Decides if learning rate should be reduced.*/\n\n bool CheckReduceLearningRate(const vector<float>& val_error);\n\n\n\n /** Multiply learning rate by factor.*/\n\n void ReduceLearningRate(const float factor);\n\n\n\n config::Model model_; /** The model protobuf config.*/\n\n vector<Layer*> layers_; /** The layers in the network.*/\n\n vector<Layer*> data_layers_; /** Layers which have data associated with them.*/\n\n vector<Layer*> input_layers_; /** Input layers.*/\n\n vector<Layer*> output_layers_; /** Output layers.*/\n\n vector<Edge*> edges_; /** The edges in the network.*/\n\n int max_iter_, batch_size_, current_iter_, lr_reduce_counter_;\n\n DataHandler *train_dataset_, *val_dataset_;\n\n string checkpoint_dir_, output_file_, model_name_;\n\n ImageDisplayer displayer_;\n\n string model_filename_, timestamp_, log_file_, val_log_file_;\n\n\n\n // a+=b;\n\n static void AddVectors(vector<float>& a, vector<float>& b);\n\n};\n\n\n\n#endif\n", "file_path": "src/convnet.h", "rank": 91, "score": 3.5705407918068444 }, { "content": "void Matrix::Add(Matrix& m) {\n\n add_elementwise(&mat_, m.GetMat(), &mat_);\n\n}\n\n\n\nvoid Matrix::CopyToDeviceSlice(const int start, const int end) {\n\n\n\n int err_code = copy_to_device_slice(&mat_, start, end);\n\n if (err_code != 0) {\n\n cerr << \"Error copying matrix of size \" << mat_.size[0] << \" \"\n\n << mat_.size[1] << \" slice \" << start << \":\" << end << \" to device: \"\n\n << GetStringError(err_code) << endl;\n\n exit(1);\n\n } else {\n\n //cout << \"Successfully copied matrix of size \" << mat_.size[0] << \" \" << mat_.size[1] << \" to device.\" << endl;\n\n }\n\n}\n\n\n\nvoid Matrix::CopyToHostSlice(const int start, const int end) {\n\n int err_code = copy_to_host_slice(&mat_, start, end);\n\n if (err_code != 0) {\n", "file_path": "src/matrix.cc", "rank": 92, "score": 3.5610399473266994 }, { "content": "void EdgeWithWeight::LoadParameters(hid_t file) {\n\n stringstream ss;\n\n ss << source_node_ << \":\" << dest_node_;\n\n LoadParameters(file, ss.str());\n\n}\n\n\n\nvoid EdgeWithWeight::DisplayWeights() {\n\n if (img_display_ != NULL) {\n\n weights_.CopyToHost();\n\n int kernel_size = (int)sqrt(num_input_channels_);\n\n img_display_->DisplayWeights(weights_.GetHostData(), kernel_size, num_output_channels_, 250, false);\n\n }\n\n}\n\n\n\nvoid EdgeWithWeight::DisplayWeightStats() {\n\n /*\n\n FILE* pipe = gnuplotpipe_;\n\n if (pipe == NULL) return;\n\n fprintf(pipe, \"set term wx\\n\"); // set the terminal\n\n fprintf(pipe, \"plot '-' with lines\\n\"); // plot type\n", "file_path": "src/edge_with_weight.cc", "rank": 93, "score": 3.551608084129047 }, { "content": " it.second->Seek(row);\n\n }\n\n}\n\n\n\nvoid DataHandler::Sync() {\n\n if (pipeline_loads_) WaitForPreload();\n\n}\n\n\n\nvoid DataHandler::ShuffleIndices() {\n\n float* cpu_rand_perm_indices = rand_perm_indices_.GetHostData();\n\n const int dataset_size = rand_perm_indices_.GetCols();\n\n random_shuffle(cpu_rand_perm_indices, cpu_rand_perm_indices + dataset_size);\n\n rand_perm_indices_.CopyToDevice();\n\n}\n\n\n\nvoid DataHandler::GetBatch(vector<Layer*>& data_layers) {\n\n int end = start_ + batch_size_;\n\n if (end > chunk_size_ || restart_) {\n\n if (reuse_counter_ < max_reuse_count_ && !restart_) {\n\n reuse_counter_++;\n", "file_path": "src/datahandler.cc", "rank": 94, "score": 3.542226051905059 }, { "content": " if (gaussian_dropout_ && rectify_after_gaussian_dropout_) {\n\n lower_bound_scalar(state, 0, state);\n\n }\n\n}\n\n\n\nvoid ReLULayer::ApplyDerivativeOfActivation() {\n\n ApplyDerivativeofDropout();\n\n cudamat* deriv = deriv_.GetMat();\n\n cudamat* state = state_.GetMat();\n\n apply_rectified_linear_deriv(deriv, state, deriv);\n\n}\n\n\n\nvoid SoftmaxLayer::AllocateMemory(int image_size, int batch_size) {\n\n Layer::AllocateMemory(image_size, batch_size);\n\n if (is_output_) data_.AllocateGPUMemory(batch_size, 1);\n\n Matrix::RegisterTempMemory(batch_size);\n\n}\n\n\n\nvoid SoftmaxLayer::ApplyActivation(bool train) {\n\n cudamat* state = state_.GetMat();\n", "file_path": "src/layer.cc", "rank": 95, "score": 3.505188417230709 }, { "content": "\n\nvoid ConvNet::Load() {\n\n Load(GetCheckpointFilename());\n\n}\n\n\n\nvoid ConvNet::Load(const string& input_file) {\n\n cout << \"Loading model from \" << input_file << endl;\n\n hid_t file = H5Fopen(input_file.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);\n\n for (Edge* e : edges_) e->LoadParameters(file);\n\n ReadHDF5IntAttr(file, \"__lr_reduce_counter__\", &lr_reduce_counter_);\n\n for (int i = 0; i < lr_reduce_counter_; i++) {\n\n ReduceLearningRate(model_.reduce_lr_factor());\n\n }\n\n ReadHDF5IntAttr(file, \"__current_iter__\", &current_iter_);\n\n H5Fclose(file);\n\n}\n\n\n\nvoid ConvNet::DisplayLayers() {\n\n for (int i = 0; i < layers_.size(); i++){\n\n layers_[i]->Display(0);\n", "file_path": "src/convnet.cc", "rank": 96, "score": 3.477914523849384 }, { "content": " rows_ = rows;\n\n cols_ = cols;\n\n data_ = new float[rows * cols];\n\n}\n\n\n\nvoid CPUMatrix::Print() {\n\n Print(rows_, cols_);\n\n}\n\n\n\nvoid CPUMatrix::Print(int rows, int cols) {\n\n for (int i = 0; i < rows && i < 10; i++) {\n\n for (int j = 0; j < cols && j < 10; j++) {\n\n cout << data_[j + i * cols] << \" \";\n\n }\n\n if (!(i == 9 || i == rows - 1)) cout << endl;\n\n }\n\n float max = -FLT_MAX;\n\n for (int j = 0; j < rows * cols; j++) if (max < data_[j]) max = data_[j];\n\n cout << \"... Max \" << max << endl;\n\n}\n", "file_path": "cpu/cpuconv.cc", "rank": 97, "score": 3.466653168175075 }, { "content": " string GetCheckpointFilename();\n\n void TimestampModel();\n\n\n\n /** Topologically sort layers.*/\n\n void Sort();\n\n\n\n /** Forward propagate one layer.\n\n * Passes up input through the edge and updates the state of the output.\n\n * @param input the input layer.\n\n * @param output the output layer.\n\n * @param edge the edge connecting the input to the output.\n\n * @param overwrite If true, overwrite the state present in output, else add to it.\n\n */ \n\n void Fprop(Layer& input, Layer& output, Edge& edge, bool overwrite);\n\n \n\n /** Back propagate through one layer.\n\n * Passes down the gradients from the output layer to the input layer.\n\n * Also updates the weights on the edge (if update_weights is true).\n\n * @param output the output layer (gradients w.r.t this have been computed).\n\n * @param input the input layer (gradients w.r.t this will be computed here).\n", "file_path": "src/convnet.h", "rank": 98, "score": 3.459966509562737 }, { "content": "}\n\n\n\nvoid Layer::AccumulateDeriv() {\n\n bool overwrite = !has_outgoing_to_same_gpu_;\n\n for (int gpu_id : other_outgoing_gpu_ids_) {\n\n Matrix& other = GetOtherDeriv(gpu_id);\n\n other.WaitTillReady(); // setready after computedown.\n\n if (overwrite) {\n\n deriv_.Set(other);\n\n } else {\n\n deriv_.Add(other);\n\n }\n\n overwrite = false;\n\n }\n\n}\n\n\n\nvoid Layer::BroadcastState() {\n\n if (has_outgoing_to_other_gpus_) {\n\n for (int gpu_id: other_outgoing_gpu_ids_) {\n\n Matrix::SetDevice(gpu_id);\n", "file_path": "src/layer.cc", "rank": 99, "score": 3.4532617441528215 } ]
C++
coursework/os/code/src/emsh/fs/stream.cpp
huaouo/history_code
475193986caf025c9569fb0690a12bed0cf630b4
#include <math.h> #include <string.h> #include "stream.h" #include "lnkblk.h" namespace emsh::fs { Stream::Stream(const uint16_t iaddr) : io(IO::get_instance()), fs(FS::get_instance()), iaddr(iaddr), inode(fs.read_inode(iaddr)), read_pos(0), write_pos(0) {} bool Stream::truncate(size_t len) { if (len > inode.size) return false; auto original_blk_index = static_cast<int>(inode.size / BLK_SIZE); if (inode.size % BLK_SIZE == 0) --original_blk_index; auto target_blk_index = static_cast<int>(len / BLK_SIZE); if (len % BLK_SIZE == 0) --target_blk_index; if (target_blk_index < original_blk_index) { for (auto blk_index = original_blk_index; blk_index > target_blk_index; --blk_index) { if (blk_index < INODE_DADDR_BLK_CNT) { fs.free_dblk(inode.d_addr[blk_index]); inode.d_addr[blk_index] = 0; } else if (blk_index < INODE_DJADDR_BLK_CNT) { Blk _j_blk = io.read_block(inode.j_addr); auto j_blk = (LnkBlk *) &_j_blk; fs.free_dblk(j_blk->addr[blk_index - INODE_DADDR_BLK_CNT]); j_blk->addr[blk_index - INODE_DADDR_BLK_CNT] = 0; io.write_block(&_j_blk, inode.j_addr); if (blk_index == INODE_DADDR_BLK_CNT) { fs.free_dblk(inode.j_addr); inode.j_addr = 0; } } else { auto blk_index_remain = static_cast<uint16_t>(blk_index - INODE_DJADDR_BLK_CNT); auto blk_index_id = static_cast<uint16_t>(blk_index_remain / LNK_ENTRY_PER_BLK); auto blk_index_offset = static_cast<uint16_t>(blk_index_remain % LNK_ENTRY_PER_BLK); Blk _j_blk = io.read_block(inode.jj_addr); auto j_blk = (LnkBlk *) &_j_blk; Blk _jj_blk = io.read_block(j_blk->addr[blk_index_id]); auto jj_blk = (LnkBlk *) &_jj_blk; fs.free_dblk(jj_blk->addr[blk_index_offset]); jj_blk->addr[blk_index_offset] = 0; io.write_block(&_jj_blk, j_blk->addr[blk_index_id]); if (blk_index_offset == 0) { fs.free_dblk(j_blk->addr[blk_index_id]); j_blk->addr[blk_index_id] = 0; io.write_block(&_j_blk, inode.jj_addr); } if (blk_index_remain == 0) { fs.free_dblk(inode.jj_addr); inode.jj_addr = 0; } } } } inode.size = len; inode.stamp = time(nullptr); fs.write_inode(&inode, iaddr); return true; } size_t Stream::write(const char *data, size_t len) { if (!fs.can_alloc_dblk(static_cast<uint16_t>(len/BLK_SIZE))) return 0; size_t data_pos = 0; auto current_blk_left_bytes = write_pos - write_pos / BLK_SIZE * BLK_SIZE; auto new_alloc_blk_num = static_cast<uint16_t>( ceil(static_cast<double>(len - current_blk_left_bytes) / BLK_SIZE)); if (!fs.can_alloc_dblk(new_alloc_blk_num)) return 0; while (true) { bool alloc_fail = false; auto blk_index = static_cast<uint16_t>(write_pos / BLK_SIZE); auto offset = static_cast<uint16_t>(write_pos % BLK_SIZE); auto write_cycle_size = static_cast<uint16_t>( std::min(static_cast<size_t>(BLK_SIZE - offset), len - data_pos)); if (write_cycle_size == 0) break; uint16_t blk_id = 0; if (blk_index < INODE_DADDR_BLK_CNT) { if ((blk_id = inode.d_addr[blk_index]) == 0) { uint16_t new_blk_id = fs.alloc_dblk(); if (new_blk_id == DBLK_FAIL_ID) { alloc_fail = true; } else { blk_id = inode.d_addr[blk_index] = new_blk_id; fs.write_inode(&inode, iaddr); } } } else if (blk_index < INODE_DJADDR_BLK_CNT) { bool prev_alloc = false; if (inode.j_addr == 0) { uint16_t new_j_addr = fs.alloc_dblk(); if (new_j_addr == DBLK_FAIL_ID) { alloc_fail = true; } else { prev_alloc = true; inode.j_addr = new_j_addr; fs.write_inode(&inode, iaddr); io.clear_block(new_j_addr); } } if (!alloc_fail) { Blk _j_blk = io.read_block(inode.j_addr); auto j_blk = (LnkBlk *) &_j_blk; if ((blk_id = j_blk->addr[blk_index - INODE_DADDR_BLK_CNT]) == 0) { uint16_t new_blk_id = fs.alloc_dblk(); if (new_blk_id == DBLK_FAIL_ID) { if (prev_alloc) { fs.free_dblk(inode.j_addr); inode.j_addr = 0; fs.write_inode(&inode, iaddr); } alloc_fail = true; } else { blk_id = j_blk->addr[blk_index - INODE_DADDR_BLK_CNT] = new_blk_id; io.write_block(&_j_blk, inode.j_addr); } } } } else { bool pprev_alloc = false, prev_alloc = false; auto blk_index_remain = static_cast<uint16_t>(blk_index - INODE_DJADDR_BLK_CNT); auto blk_index_id = static_cast<uint16_t>(blk_index_remain / LNK_ENTRY_PER_BLK); auto blk_index_offset = static_cast<uint16_t>(blk_index_remain % LNK_ENTRY_PER_BLK); if (inode.jj_addr == 0) { uint16_t new_j_blk_id = fs.alloc_dblk(); if (new_j_blk_id == DBLK_FAIL_ID) { alloc_fail = true; } else { inode.jj_addr = new_j_blk_id; fs.write_inode(&inode, iaddr); io.clear_block(new_j_blk_id); pprev_alloc = true; } } Blk _j_blk{}; auto j_blk = (LnkBlk *) &_j_blk; if (!alloc_fail) { _j_blk = io.read_block(inode.jj_addr); if (j_blk->addr[blk_index_id] == 0) { uint16_t new_jj_blk_id = fs.alloc_dblk(); if (new_jj_blk_id == DBLK_FAIL_ID) { if (pprev_alloc) { fs.free_dblk(inode.jj_addr); inode.jj_addr = 0; fs.write_inode(&inode, iaddr); } alloc_fail = true; } else { j_blk->addr[blk_index_id] = new_jj_blk_id; io.write_block(&_j_blk, inode.jj_addr); io.clear_block(new_jj_blk_id); prev_alloc = true; } } } if (!alloc_fail) { Blk _jj_blk = io.read_block(j_blk->addr[blk_index_id]); auto jj_blk = (LnkBlk *) &_jj_blk; if ((blk_id = jj_blk->addr[blk_index_offset]) == 0) { uint16_t new_blk_id = fs.alloc_dblk(); if (new_blk_id == DBLK_FAIL_ID) { if (prev_alloc) { fs.free_dblk(j_blk->addr[blk_index_id]); j_blk->addr[blk_index_id] = 0; io.write_block(&_j_blk, inode.jj_addr); } if (pprev_alloc) { fs.free_dblk(inode.jj_addr); inode.jj_addr = 0; fs.write_inode(&inode, iaddr); } alloc_fail = true; } else { blk_id = jj_blk->addr[blk_index_offset] = new_blk_id; io.write_block(&_jj_blk, j_blk->addr[blk_index_id]); } } } } if (alloc_fail) break; IF_INTERNAL_ERROR(blk_id == 0); Blk blk = io.read_block(blk_id); memcpy((char *) &blk + offset, data + data_pos, write_cycle_size); io.write_block(&blk, blk_id); write_pos += write_cycle_size; data_pos += write_cycle_size; if (write_pos > inode.size) inode.size = write_pos; } inode.stamp = time(nullptr); fs.write_inode(&inode, iaddr); return data_pos; } size_t Stream::read(char *data, size_t len) { size_t data_pos = 0; while (true) { auto blk_index = static_cast<uint16_t>(read_pos / BLK_SIZE); auto offset = static_cast<uint16_t>(read_pos % BLK_SIZE); auto read_cycle_size = static_cast<uint16_t>( std::min(static_cast<size_t>(BLK_SIZE - offset), std::min(inode.size - read_pos, len - data_pos))); if (read_cycle_size == 0) break; Blk blk{}; if (blk_index < INODE_DADDR_BLK_CNT) { blk = io.read_block(inode.d_addr[blk_index]); } else if (blk_index < INODE_DJADDR_BLK_CNT) { Blk _j_blk = io.read_block(inode.j_addr); auto j_blk = (LnkBlk *) &_j_blk; blk = io.read_block(j_blk->addr[blk_index - INODE_DADDR_BLK_CNT]); } else { auto blk_index_remain = static_cast<uint16_t>(blk_index - INODE_DJADDR_BLK_CNT); auto blk_index_id = static_cast<uint16_t>(blk_index_remain / LNK_ENTRY_PER_BLK); auto blk_index_offset = static_cast<uint16_t>(blk_index_remain % LNK_ENTRY_PER_BLK); Blk _j_blk = io.read_block(inode.jj_addr); auto j_blk = (LnkBlk *) &_j_blk; Blk _jj_blk = io.read_block(j_blk->addr[blk_index_id]); auto jj_blk = (LnkBlk *) &_jj_blk; blk = io.read_block(jj_blk->addr[blk_index_offset]); } memcpy(data + data_pos, (char *) &blk + offset, read_cycle_size); read_pos += read_cycle_size; data_pos += read_cycle_size; } return data_pos; } void Stream::seekw(size_t pos) { if (pos > inode.size) pos = inode.size; write_pos = pos; } void Stream::seekr(size_t pos) { if (pos >= inode.size) pos = inode.size; read_pos = pos; } size_t Stream::get_wpos() { return write_pos; } size_t Stream::get_rpos() { return read_pos; } size_t Stream::size() { return inode.size; } }
#include <math.h> #include <string.h> #include "stream.h" #include "lnkblk.h" namespace emsh::fs { Stream::Stream(const uint16_t iaddr) : io(IO::get_instance()), fs(FS::get_instance()), iaddr(iaddr), inode(fs.read_inode(iaddr)), read_pos(0), write_pos(0) {} bool Stream::truncate(size_t len) { if (len > inode.size) return false; auto original_blk_index = static_cast<int>(inode.size / BLK_SIZE); if (inode.size % BLK_SIZE == 0) --original_blk_index; auto target_blk_index = static_cast<int>(len / BLK_SIZE); if (len % BLK_SIZE == 0) --target_blk_index; if (target_blk_index < original_blk_index) { for (auto blk_index = original_blk_index; blk_index > target_blk_index; --blk_index) { if (blk_index < INODE_DADDR_BLK_CNT) { fs.free_dblk(inode.d_addr[blk_index]); inode.d_addr[blk_index] = 0; } else if (blk_index < INODE_DJADDR_BLK_CNT) { Blk _j_blk = io.read_block(inode.j_addr); auto j_blk = (LnkBlk *) &_j_blk; fs.free_dblk(j_blk->addr[blk_index - INODE_DADDR_BLK_CNT]); j_blk->addr[blk_index - INODE_DADDR_BLK_CNT] = 0; io.write_block(&_j_blk, inode.j_addr); if (blk_index == INODE_DADDR_BLK_CNT) { fs.free_dblk(inode.j_addr); inode.j_addr = 0; } } else { auto blk_index_remain = static_cast<uint16_t>(blk_index - INODE_DJADDR_BLK_CNT); auto blk_index_id = static_cast<uint16_t>(blk_index_remain / LNK_ENTRY_PER_BLK); auto blk_index_offset = static_cast<uint16_t>(blk_index_remain % LNK_ENTRY_PER_BLK); Blk _j_blk = io.read_block(inode.jj_addr); auto j_blk = (LnkBlk *) &_j_blk; Blk _jj_blk = io.read_block(j_blk->addr[blk_index_id]); auto jj_blk = (LnkBlk *) &_jj_blk; fs.free_dblk(jj_blk->addr[blk_index_offset]); jj_blk->addr[blk_index_offset] = 0; io.write_block(&_jj_blk, j_blk->addr[blk_index_id]); if (blk_index_offset == 0) { fs.free_dblk(j_blk->addr[blk_index_id]); j_blk->addr[blk_index_id] = 0; io.write_block(&_j_blk, inode.jj_addr); } if (blk_index_remain == 0) { fs.free_dblk(inode.jj_addr); inode.jj_addr = 0; } } } } inode.size = len; inode.stamp = time(nullptr); fs.write_inode(&inode, iaddr); return true; } size_t Stream::write(const char *data, size_t len) { if (!fs.can_alloc_dblk(static_cast<uint16_t>(len/BLK_SIZE))) return 0; size_t data_pos = 0; auto current_blk_left_bytes = write_pos - write_pos / BLK_SIZE * BLK_SIZE; auto new_alloc_blk_num = static_cast<uint16_t>( ceil(static_cast<double>(len - current_blk_left_bytes) / BLK_SIZE)); if (!fs.can_alloc_dblk(new_alloc_blk_num)) return 0; while (true) { bool alloc_fail = false; auto blk_index = static_cast<uint16_t>(write_pos / BLK_SIZE); auto offset = static_cast<uint16_t>(write_pos % BLK_SIZE); auto write_cycle_size = static_cast<uint16_t>( std::min(static_cast<size_t>(BLK_SIZE - offset), len - data_pos)); if (write_cycle_size == 0) break; uint16_t blk_id = 0; if (blk_index < INODE_DADDR_BLK_CNT) { if ((blk_id = inode.d_addr[blk_index]) == 0) { uint16_t new_blk_id = fs.alloc_dblk(); if (new_blk_id == DBLK_FAIL_ID) { alloc_fail = true; } else { blk_id = inode.d_addr[blk_index] = new_blk_id; fs.write_inode(&inode, iaddr); } } } else if (blk_index < INODE_DJADDR_BLK_CNT) { bool prev_alloc = false; if (inode.j_addr == 0) { uint16_t new_j_addr = fs.alloc_dblk(); if (new_j_addr == DBLK_FAIL_ID) { alloc_fail = true; } else { prev_alloc = true; inode.j_addr = new_j_addr; fs.write_inode(&inode, iaddr); io.clear_block(new_j_addr); } } if (!alloc_fail) { Blk _j_blk = io.read_block(inode.j_addr); auto j_blk = (LnkBlk *) &_j_blk; if ((blk_id = j_blk->addr[blk_index - INODE_DADDR_BLK_CNT]) == 0) { uint16_t new_blk_id = fs.alloc_dblk(); if (new_blk_id == DBLK_FAIL_ID) { if (prev_alloc) { fs.free_dblk(inode.j_addr); inode.j_addr = 0; fs.write_inode(&inode, iaddr); } alloc_fail = true; } else { blk_id = j_blk->addr[blk_index - INODE_DADDR_BLK_CNT] = new_blk_id; io.write_block(&_j_blk, inode.j_addr); } } } } else { bool pprev_alloc = false, prev_alloc = false; auto blk_index_remain = static_cast<uint16_t>(blk_index - INODE_DJADDR_BLK_CNT); auto blk_index_id = static_cast<uint16_t>(blk_index_remain / LNK_ENTRY_PER_BLK); auto blk_index_offset = static_cast<uint16_t>(blk_index_remain % LNK_ENTRY_PER_BLK); if (inode.jj_addr == 0) { uint16_t new_j_blk_id = fs.alloc_dblk(); if (new_j_blk_id == DBLK_FAIL_ID) { alloc_fail = true; } else { inode.jj_addr = new_j_blk_id; fs.write_inode(&inode, iaddr); io.clear_block(new_j_blk_id); pprev_alloc = true; } } Blk _j_blk{}; auto j_blk = (LnkBlk *) &_j_blk; if (!alloc_fail) { _j_blk = io.read_block(inode.jj_addr); if (j_blk->addr[blk_index_id] == 0) { uint16_t new_jj_blk_id = fs.alloc_dblk(); if (new_jj_blk_id == DBLK_FAIL_ID) { if (pprev_alloc) { fs.free_dblk(inode.jj_addr); inode.jj_addr = 0; fs.write_inode(&inode, iaddr); } alloc_fail = true; } else { j_blk->addr[blk_index_id] = new_jj_blk_id; io.write_block(&_j_blk, inode.jj_addr); io.clear_block(new_jj_blk_id); prev_alloc = true; } } } if (!alloc_fail) { Blk _jj_blk = io.read_block(j_blk->addr[blk_index_id]); auto jj_blk = (LnkBlk *) &_jj_blk; if ((blk_id = jj_blk->addr[blk_index_offset]) == 0) { uint16_t new_blk_id = fs.alloc_dblk(); if (new_blk_id == DBLK_FAIL_ID) { if (prev_alloc) { fs.free_dblk(j_blk->addr[blk_index_id]); j_blk->addr[blk_index_id] = 0; io.write_block(&_j_blk, inode.jj_addr); } if (pprev_alloc) { fs.free_dblk(inode.jj_addr); inode.jj_addr = 0; fs.write_inode(&inode, iaddr); } alloc_fail = true; } else { blk_id = jj_blk->addr[blk_index_offset] = new_blk_id; io.write_block(&_jj_blk, j_blk->addr[blk_index_id]); } } } } if (alloc_fail) break; IF_INTERNAL_ERROR(blk_id == 0); Blk blk = io.read_block(blk_id); memcpy((char *) &blk + offset, data + data_pos, write_cycle_size); io.write_block(&blk, blk_id); write_pos += write_cycle_size; data_pos += write_cycle_size; if (write_pos > inode.size) inode.size = write_pos; } inode.stamp = time(nullptr); fs.write_inode(&inode, iaddr); return data_pos; } size_t Stream::read(char *data, size_t len) { size_t data_pos = 0; while (true) { auto blk_index = static_cast<uint16_t>(read_pos / BLK_SIZE); auto offset = static_cast<uint16_t>(read_pos % BLK_SIZE); auto read_cycle_size = static_cast<uint16_t>( std::min(static_cast<size_t>(BLK_SIZE - offset), std::min(inode.size - read_pos, len - data_pos))); if (read_cycle_size == 0) break; Blk blk{}; if (blk_index < INODE_DADDR_BLK_CNT) { blk = io.read_block(inode.d_addr[blk_index]); } else
memcpy(data + data_pos, (char *) &blk + offset, read_cycle_size); read_pos += read_cycle_size; data_pos += read_cycle_size; } return data_pos; } void Stream::seekw(size_t pos) { if (pos > inode.size) pos = inode.size; write_pos = pos; } void Stream::seekr(size_t pos) { if (pos >= inode.size) pos = inode.size; read_pos = pos; } size_t Stream::get_wpos() { return write_pos; } size_t Stream::get_rpos() { return read_pos; } size_t Stream::size() { return inode.size; } }
if (blk_index < INODE_DJADDR_BLK_CNT) { Blk _j_blk = io.read_block(inode.j_addr); auto j_blk = (LnkBlk *) &_j_blk; blk = io.read_block(j_blk->addr[blk_index - INODE_DADDR_BLK_CNT]); } else { auto blk_index_remain = static_cast<uint16_t>(blk_index - INODE_DJADDR_BLK_CNT); auto blk_index_id = static_cast<uint16_t>(blk_index_remain / LNK_ENTRY_PER_BLK); auto blk_index_offset = static_cast<uint16_t>(blk_index_remain % LNK_ENTRY_PER_BLK); Blk _j_blk = io.read_block(inode.jj_addr); auto j_blk = (LnkBlk *) &_j_blk; Blk _jj_blk = io.read_block(j_blk->addr[blk_index_id]); auto jj_blk = (LnkBlk *) &_jj_blk; blk = io.read_block(jj_blk->addr[blk_index_offset]); }
if_condition
[]
C++
example/m5stack/transmitter/src/main.cpp
yukima77/EnOceanModule
c4d2cdf8738890333085980afb66478f499d21aa
#include <M5Stack.h> #include <SoftwareSerial.h> #define SYNC 0x55 // SYNC SoftwareSerial enoceanSerial(21, 22); const byte CRC8Table[256] = { 0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15, 0x38, 0x3f, 0x36, 0x31, 0x24, 0x23, 0x2a, 0x2d, 0x70, 0x77, 0x7e, 0x79, 0x6c, 0x6b, 0x62, 0x65, 0x48, 0x4f, 0x46, 0x41, 0x54, 0x53, 0x5a, 0x5d, 0xe0, 0xe7, 0xee, 0xe9, 0xfc, 0xfb, 0xf2, 0xf5, 0xd8, 0xdf, 0xd6, 0xd1, 0xc4, 0xc3, 0xca, 0xcd, 0x90, 0x97, 0x9e, 0x99, 0x8c, 0x8b, 0x82, 0x85, 0xa8, 0xaf, 0xa6, 0xa1, 0xb4, 0xb3, 0xba, 0xbd, 0xc7, 0xc0, 0xc9, 0xce, 0xdb, 0xdc, 0xd5, 0xd2, 0xff, 0xf8, 0xf1, 0xf6, 0xe3, 0xe4, 0xed, 0xea, 0xb7, 0xb0, 0xb9, 0xbe, 0xab, 0xac, 0xa5, 0xa2, 0x8f, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9d, 0x9a, 0x27, 0x20, 0x29, 0x2e, 0x3b, 0x3c, 0x35, 0x32, 0x1f, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0d, 0x0a, 0x57, 0x50, 0x59, 0x5e, 0x4b, 0x4c, 0x45, 0x42, 0x6f, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7d, 0x7a, 0x89, 0x8e, 0x87, 0x80, 0x95, 0x92, 0x9b, 0x9c, 0xb1, 0xb6, 0xbf, 0xb8, 0xad, 0xaa, 0xa3, 0xa4, 0xf9, 0xfe, 0xf7, 0xf0, 0xe5, 0xe2, 0xeb, 0xec, 0xc1, 0xc6, 0xcf, 0xc8, 0xdd, 0xda, 0xd3, 0xd4, 0x69, 0x6e, 0x67, 0x60, 0x75, 0x72, 0x7b, 0x7c, 0x51, 0x56, 0x5f, 0x58, 0x4d, 0x4a, 0x43, 0x44, 0x19, 0x1e, 0x17, 0x10, 0x05, 0x02, 0x0b, 0x0c, 0x21, 0x26, 0x2f, 0x28, 0x3d, 0x3a, 0x33, 0x34, 0x4e, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5c, 0x5b, 0x76, 0x71, 0x78, 0x7f, 0x6A, 0x6d, 0x64, 0x63, 0x3e, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2c, 0x2b, 0x06, 0x01, 0x08, 0x0f, 0x1a, 0x1d, 0x14, 0x13, 0xae, 0xa9, 0xa0, 0xa7, 0xb2, 0xb5, 0xbc, 0xbb, 0x96, 0x91, 0x98, 0x9f, 0x8a, 0x8D, 0x84, 0x83, 0xde, 0xd9, 0xd0, 0xd7, 0xc2, 0xc5, 0xcc, 0xcb, 0xe6, 0xe1, 0xe8, 0xef, 0xfa, 0xfd, 0xf4, 0xf3}; byte len_data_dl = 0x01; byte len_raw_data = len_data_dl + 6; byte header[] = { 0x00, len_raw_data, 0x02, 0x0A, }; byte data[] = { 0x21, 0xAA, 0xAA, 0xAA, 0xAA, 0x08, 0xAA, 0xAA, 0xAA }; void setup() { M5.begin(); Serial.begin(9600); Serial.println(); enoceanSerial.begin(57600); M5.Lcd.clear(BLACK); } void loop() { int i; if (M5.BtnA.wasPressed()) { Serial.println("Pressed BtnA."); enoceanSerial.write(SYNC); enoceanSerial.write(header, 4); byte crc8h = 0; for (i = 0; i < 4; i++) { crc8h = CRC8Table[crc8h ^ header[i]]; }; enoceanSerial.write(crc8h); if (data[5] == 0x08) { data[5] = 0x09; Serial.println("Close"); M5.Lcd.clear(BLACK); M5.Lcd.setTextSize(5); M5.Lcd.println("Close"); } else if (data[5] == 0x09) { data[5] = 0x08; Serial.println("Open"); M5.Lcd.clear(BLACK); M5.Lcd.setTextSize(5); M5.Lcd.println("Open"); } enoceanSerial.write(data, len_raw_data + 2); byte crc8d = 0; for (i = 0; i < (len_raw_data + 2); i++) { crc8d = CRC8Table[crc8d ^ data[i]]; }; enoceanSerial.write(crc8d); } M5.Lcd.setCursor(5, 5); M5.update(); delay(100); }
#include <M5Stack.h> #include <SoftwareSerial.h> #define SYNC 0x55 // SYNC SoftwareSerial enoceanSerial(21, 22); const byte CRC8Table[256] = { 0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15, 0x38, 0x3f, 0x36, 0x31, 0x24, 0x23, 0x2a, 0x2d, 0x70, 0x77, 0x7e, 0x79, 0x6c, 0x6b, 0x62, 0x65, 0x48, 0x4f, 0x46, 0x41, 0x54, 0x53, 0x5a, 0x5d, 0xe0, 0xe7, 0xee, 0xe9, 0xfc, 0xfb, 0xf2, 0xf5, 0xd8, 0xdf, 0xd6, 0xd1, 0xc4, 0xc3, 0xca, 0xcd, 0x90, 0x97, 0x9e, 0x99, 0x8c, 0x8b, 0x82, 0x85, 0xa8, 0xaf, 0xa6, 0xa1, 0xb4, 0xb3, 0xba, 0xbd, 0xc7, 0xc0, 0xc9, 0xce, 0xdb, 0xdc, 0xd5, 0xd2, 0xff, 0xf8, 0xf1, 0xf6, 0xe3, 0xe4, 0xed, 0xea, 0xb7, 0xb0, 0xb9, 0xbe, 0xab, 0xac, 0xa5, 0xa2, 0x8f, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9d, 0x9a, 0x27, 0x20, 0x29, 0x2e, 0x3b, 0x3c, 0x35, 0x32, 0x1f, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0d, 0x0a, 0x57, 0x50, 0x59, 0x5e, 0x4b, 0x4c, 0x45, 0x42, 0x6f, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7d, 0x7a, 0x89, 0x8e, 0x87, 0x80, 0x95, 0x92, 0x9b, 0x9c, 0xb1, 0xb6, 0xbf, 0xb8, 0xad, 0xaa, 0xa3, 0xa4, 0xf9, 0xfe, 0xf7, 0xf0, 0xe5, 0xe2, 0xeb, 0xec, 0xc1, 0xc6, 0xcf, 0xc8, 0xdd, 0xda, 0xd3, 0xd4, 0x69, 0x6e, 0x67, 0x60, 0x75, 0x72, 0x7b, 0x7c, 0x51, 0x56, 0x5f, 0x58, 0x4d, 0x4a, 0x43, 0x44, 0x19, 0x1e, 0x17, 0x10, 0x05, 0x02, 0x0b, 0x0c, 0x21, 0x26, 0x2f, 0x28, 0x3d, 0x3a, 0x33, 0x34, 0x4e, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5c, 0x5b, 0x76, 0x71, 0x78, 0x7f, 0x6A, 0x6d, 0x64, 0x63, 0x3e, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2c, 0x2b, 0x06, 0x01, 0x08, 0x0f, 0x1a, 0x1d, 0x14, 0x13, 0xae, 0xa9, 0xa0, 0xa7, 0xb2, 0xb5, 0xbc, 0xbb, 0x96, 0x91, 0x98, 0x9f, 0x8a, 0x8D, 0x84, 0x83, 0xde, 0xd9, 0xd0, 0xd7, 0xc2, 0xc5, 0xcc, 0xcb, 0xe6, 0xe1, 0xe8, 0xef, 0xfa, 0xfd, 0xf4, 0xf3}; byte len_data_dl = 0x01; byte len_raw_data = len_data_dl + 6; byte header[] = { 0x00, len_raw_data, 0x02, 0x0A, }; byte data[] = { 0x21, 0xAA, 0xAA, 0xAA, 0xAA, 0x08, 0xAA, 0xAA, 0xAA }; void setup() { M5.begin(); Serial.begin(9600); Serial.println(); enoceanSerial.begin(57600); M5.Lcd.clear(BLACK); } void loop() { int i; if (M5.BtnA.wasPressed()) { Serial.println("Pressed BtnA."); enoceanSerial.write(SYNC); enoceanSerial.write(header, 4); byte crc8h = 0; for (i = 0; i < 4; i++) { crc8h = CRC8Table[crc8h ^ header[i]]; }; enoceanSerial.write(crc8h); if (data[5] == 0x08) { data[5] = 0x09; Serial.println("Close"); M5.Lcd.clear(BLACK); M5.Lcd.setTextSize(5); M5.Lcd.println("Close"); } else
enoceanSerial.write(data, len_raw_data + 2); byte crc8d = 0; for (i = 0; i < (len_raw_data + 2); i++) { crc8d = CRC8Table[crc8d ^ data[i]]; }; enoceanSerial.write(crc8d); } M5.Lcd.setCursor(5, 5); M5.update(); delay(100); }
if (data[5] == 0x09) { data[5] = 0x08; Serial.println("Open"); M5.Lcd.clear(BLACK); M5.Lcd.setTextSize(5); M5.Lcd.println("Open"); }
if_condition
[ { "content": "#include <M5Stack.h>\n\n#include <SoftwareSerial.h>\n\n\n\n#define LCDHIGH 240\n\n#define LCDWIDTH 320\n\n\n\n#define TEMPID 0x05002729 // EnOceanモジュールID\n\n#define SYNC 0x55 // SYNCバイト\n\n\n\nSoftwareSerial enoceanSerial(21, 22); // RX, TX\n\n\n\nvoid setup()\n\n{\n\n M5.begin();\n\n\n\n Serial.begin(9600);\n\n Serial.println();\n\n\n\n // Initialize EnOcean.\n\n enoceanSerial.begin(57600);\n", "file_path": "example/m5stack/receiver/src/main.cpp", "rank": 3, "score": 6.948624892931811 }, { "content": "#include <M5StickC.h>\n\n#include <SoftwareSerial.h>\n\n\n\n#define TEMPID 0xXXXXXXXX // EnOceanモジュールID\n\n#define SYNC 0x55 // SYNCバイト\n\n\n\nSoftwareSerial enoceanSerial(32, 33); // RX, TX\n\n\n\nvoid setup()\n\n{\n\n M5.begin();\n\n M5.Lcd.setRotation(3);\n\n\n\n Serial.begin(9600);\n\n Serial.println();\n\n\n\n // Initialize EnOcean.\n\n enoceanSerial.begin(57600);\n\n\n\n // 初期化画面\n", "file_path": "example/m5stick/receiver/src/main.cpp", "rank": 4, "score": 6.896520166626711 }, { "content": "#include <M5EPD.h>\n\n\n\n#define SYNC 0x55 // SYNCバイト\n\n#define TEMPID 0xFFFFFFFF // EnOceanモジュールID\n\n\n\nM5EPD_Canvas canvas(&M5.EPD);\n\n\n\nvoid setup()\n\n{\n\n\n\n M5.begin();\n\n M5.EPD.SetRotation(90);\n\n M5.EPD.Clear(true);\n\n\n\n M5.RTC.begin();\n\n\n\n Serial1.begin(57600, SERIAL_8N1, 25, 32); // PORT.A\n\n //Serial1.begin(57600, SERIAL_8N1, 26, 33); // PORT.B\n\n //Serial1.begin(57600, SERIAL_8N1, 18, 19); // PORT.C\n\n\n", "file_path": "example/m5paper/receiver/src/main.cpp", "rank": 5, "score": 5.846795249326906 }, { "content": "\n\n // 初期化画面\n\n M5.Lcd.clear(BLACK);\n\n}\n\n\n\nvoid loop()\n\n{\n\n\n\n /********* EnOcean add *********/\n\n unsigned char dataReceive = 0; //受信確認フラグ\n\n unsigned char data = 0; //データ格納用変数\n\n unsigned char pos = 0; //ESPデータ位置\n\n unsigned long senderID = 0; //モジュールのID\n\n unsigned short dataLength = 0; //データ長\n\n unsigned char optLength = 0; //オプションデータ長\n\n unsigned char packettype = 0; //パケットタイプ\n\n unsigned char doorStatus = 0; // ドアの状態\n\n char buf[8];\n\n bool isOpen = true;\n\n\n", "file_path": "example/m5stack/receiver/src/main.cpp", "rank": 6, "score": 5.005454166725133 }, { "content": " M5.Lcd.fillScreen(BLACK);\n\n}\n\n\n\nvoid loop()\n\n{\n\n\n\n /********* EnOcean add *********/\n\n unsigned char dataReceive = 0; //受信確認フラグ\n\n unsigned char data = 0; //データ格納用変数\n\n unsigned char pos = 0; //ESPデータ位置\n\n unsigned long senderID = 0; //モジュールのID\n\n unsigned short dataLength = 0; //データ長\n\n unsigned char optLength = 0; //オプションデータ長\n\n unsigned char packettype = 0; //パケットタイプ\n\n unsigned char doorStatus = 0; // ドアの状態\n\n char buf[8];\n\n bool isOpen = true;\n\n\n\n // EnOceanからのデータ受信\n\n while (enoceanSerial.available() > 0)\n", "file_path": "example/m5stick/receiver/src/main.cpp", "rank": 7, "score": 4.640892692237265 }, { "content": " canvas.createCanvas(540, 960);\n\n canvas.setTextSize(3);\n\n canvas.drawString(\"M5Paper EnOcean Test\", 45, 350);\n\n canvas.pushCanvas(0, 0, UPDATE_MODE_DU4);\n\n}\n\n\n\nvoid loop()\n\n{\n\n\n\n /********* EnOcean add *********/\n\n unsigned char dataReceive = 0; //受信確認フラグ\n\n unsigned char aChar = 0; //データ格納用変数\n\n unsigned char pos = 0; //ESPデータ位置\n\n unsigned long senderID = 0; //モジュールのID\n\n unsigned short dataLength = 0; //データ長\n\n unsigned char optLength = 0; //オプションデータ長\n\n unsigned char packettype = 0; //パケットタイプ\n\n unsigned char doorStatus = 0; // ドアの状態\n\n char buf[8];\n\n bool isOpen = true;\n", "file_path": "example/m5paper/receiver/src/main.cpp", "rank": 8, "score": 4.257275378845974 }, { "content": " pos++; // pos移動 dataLength -> dataLength\n\n break;\n\n case (2):\n\n dataLength = (dataLength << 8) + aChar; // dataLength 下位1バイトです。\n\n pos++; // pos移動 dataLength -> optLength\n\n break;\n\n case (3):\n\n optLength = aChar; // optionLength\n\n pos++; // pos移動 optLength -> packet type\n\n break;\n\n case (4):\n\n packettype = aChar; // packettype\n\n pos++; // pos移動 packet type -> crc\n\n break;\n\n case (5):\n\n pos++; // pos移動 crc -> header\n\n break;\n\n case (6):\n\n pos++; // pos移動 header -> ID1\n\n break;\n", "file_path": "example/m5paper/receiver/src/main.cpp", "rank": 9, "score": 4.079772605653412 }, { "content": " bool shouldSendMessage = false;\n\n\n\n // EnOceanからのデータ受信\n\n while (Serial1.available() > 0)\n\n {\n\n //delay(5);\n\n aChar = Serial1.read();\n\n\n\n switch (pos)\n\n {\n\n case (0):\n\n if (SYNC == aChar)\n\n { // SYNCバイトだったら受信開始\n\n delay(5);\n\n pos++; // pos移動 SYNC -> dataLength\n\n dataReceive = 1;\n\n }\n\n break;\n\n case (1):\n\n dataLength = 0x00FF & aChar; // dataLength 上位1バイトです。\n", "file_path": "example/m5paper/receiver/src/main.cpp", "rank": 11, "score": 3.9809828458824508 }, { "content": " {\n\n //delay(5);\n\n data = enoceanSerial.read();\n\n\n\n switch (pos)\n\n {\n\n case (0):\n\n if (SYNC == data)\n\n { // SYNCバイトだったら受信開始\n\n delay(5);\n\n pos++;\n\n dataReceive = 1;\n\n }\n\n break;\n\n case (1):\n\n dataLength = 0x00FF & data;\n\n pos++;\n\n break;\n\n case (2):\n\n dataLength = (dataLength << 8) + data;\n", "file_path": "example/m5stick/receiver/src/main.cpp", "rank": 12, "score": 3.928995801854069 }, { "content": " // EnOceanからのデータ受信\n\n while (enoceanSerial.available() > 0)\n\n {\n\n //delay(5);\n\n data = enoceanSerial.read();\n\n\n\n switch (pos)\n\n {\n\n case (0):\n\n if (SYNC == data)\n\n { // SYNCバイトだったら受信開始\n\n delay(5);\n\n pos++;\n\n dataReceive = 1;\n\n }\n\n break;\n\n case (1):\n\n dataLength = 0x00FF & data;\n\n pos++;\n\n break;\n", "file_path": "example/m5stack/receiver/src/main.cpp", "rank": 14, "score": 3.6868728119033456 }, { "content": " case (2):\n\n dataLength = (dataLength << 8) + data;\n\n pos++;\n\n break;\n\n case (3):\n\n optLength = data;\n\n pos++;\n\n break;\n\n case (4):\n\n packettype = data;\n\n pos++;\n\n break;\n\n case (5):\n\n pos++;\n\n break;\n\n case (6):\n\n pos++;\n\n break;\n\n case (7):\n\n senderID = 0x0000FF & data;\n", "file_path": "example/m5stack/receiver/src/main.cpp", "rank": 15, "score": 2.31894938107248 }, { "content": " pos++;\n\n break;\n\n case (3):\n\n optLength = data;\n\n pos++;\n\n break;\n\n case (4):\n\n packettype = data;\n\n pos++;\n\n break;\n\n case (5):\n\n pos++;\n\n break;\n\n case (6):\n\n pos++;\n\n break;\n\n case (7):\n\n senderID = 0x0000FF & data;\n\n pos++;\n\n break;\n", "file_path": "example/m5stick/receiver/src/main.cpp", "rank": 16, "score": 2.1046918116180118 }, { "content": " case (13):\n\n pos++;\n\n break;\n\n case (14):\n\n pos++;\n\n break;\n\n case (15):\n\n pos++;\n\n break;\n\n default:\n\n pos++;\n\n break;\n\n }\n\n // デバッグ用のシリアルモニタ出力\n\n Serial.print(data, HEX);\n\n Serial.print(\" \");\n\n }\n\n\n\n // データ受信時の処理\n\n if (dataReceive == 1)\n", "file_path": "example/m5stack/receiver/src/main.cpp", "rank": 17, "score": 1.997705192457277 }, { "content": " break;\n\n case (14):\n\n pos++;\n\n break;\n\n case (15):\n\n pos++;\n\n break;\n\n default:\n\n pos++;\n\n break;\n\n }\n\n // デバッグ用のシリアルモニタ出力\n\n Serial.print(data, HEX);\n\n Serial.print(\" \");\n\n }\n\n\n\n // データ受信時の処理\n\n if (dataReceive == 1)\n\n {\n\n if (TEMPID == senderID)\n", "file_path": "example/m5stick/receiver/src/main.cpp", "rank": 18, "score": 1.9847928850624994 }, { "content": " case (8):\n\n case (9):\n\n case (10):\n\n senderID = (senderID << 8) + data;\n\n pos++;\n\n break;\n\n case (11):\n\n if (TEMPID == senderID)\n\n {\n\n // ドアビット\n\n doorStatus = data;\n\n }\n\n\n\n pos++;\n\n break;\n\n case (12):\n\n pos++;\n\n break;\n\n case (13):\n\n pos++;\n", "file_path": "example/m5stick/receiver/src/main.cpp", "rank": 19, "score": 1.9594626371411565 }, { "content": " pos++;\n\n break;\n\n case (8):\n\n case (9):\n\n case (10):\n\n senderID = (senderID << 8) + data;\n\n pos++;\n\n break;\n\n case (11):\n\n if (TEMPID == senderID)\n\n {\n\n // ドアビット\n\n doorStatus = data;\n\n }\n\n\n\n pos++;\n\n break;\n\n case (12):\n\n pos++;\n\n break;\n", "file_path": "example/m5stack/receiver/src/main.cpp", "rank": 20, "score": 1.9594626371411565 }, { "content": " if (battery <= 0.01)\n\n {\n\n battery = 0.01;\n\n }\n\n if (battery > 1)\n\n {\n\n battery = 1;\n\n }\n\n uint8_t px = battery * 25;\n\n sprintf(buf, \"%d%%\", (int)(battery * 100));\n\n canvas.setTextSize(2);\n\n canvas.drawString(buf, 498 - 10, 24);\n\n canvas.fillRect(498 + 3, 8 + 10, px, 13, 15);\n\n canvas.pushCanvas(0, 0, UPDATE_MODE_DU4);\n\n\n\n M5.update();\n\n sleep(5);\n\n}", "file_path": "example/m5paper/receiver/src/main.cpp", "rank": 21, "score": 1.8416470984692797 }, { "content": "**バージョンによって、ピンアサインが変更になっています。ご注意ください。誤って設定した場合もモジュールが破損することはありません。**\n\n\n\n# EnOceanModule\n\n![商品](https://github.com/yukima77/EnOceanModule/blob/images/001.JPG)\n\n\n\n# 説明\n\nEnOcean用送受信モジュールです。TCM410Jを搭載しています。\n\n\n\n# ピンアサイン\n\nSeeed株式会社のGroveSystemのピンアサインに合わせる為、v1.1よりピンアサインを変更しています。バージョン情報がプリント基板に記載されていない以前のモジュールとはピンアサインが変更になっていますのでご注意下さい。v1.1以降は、GroveSystemの使ったボードでのHardwareSerialを使った通信も可能になります。\n\n[Seeed株式会社GroveSystem](https://wiki.seeedstudio.com/Grove_System/)\n\n\n\n### v1.1\n\n1.RX (which the base unit uses to receive data, so it is an input) \n\n2.TX (which the base unit uses to transmit data to the Grove module) \n\n3.VCC \n\n4.GND \n\n\n\n### 無印\n\n1.TX (which the base unit uses to transmit data to the Grove module) \n\n2.RX (which the base unit uses to receive data, so it is an input) \n\n3.VCC \n\n4.GND \n\n\n\n# 使い方\n\nボーレート57600baudでシリアル通信が出来ます\n\n\n\n# 対応基板(動作確認済み)\n\nM5Stack \n\nM5Stick \n\nM5Paper \n\nAtom Matrix \n\nmicro:bit \n\nSeeeduinoXIAO\n\n\n\n# 接続例\n\n![M5Stack](https://github.com/yukima77/EnOceanModule/blob/images/002.JPG)\n\n![micro:bit](https://github.com/yukima77/EnOceanModule/blob/images/003.JPG)\n\n\n\n# License\n\nThis software is released under the MIT License, see LICENSE.\n", "file_path": "README.md", "rank": 22, "score": 1.4417094637563783 }, { "content": "\n\n // データ受信時の処理\n\n if (dataReceive == 1)\n\n {\n\n if (TEMPID == senderID)\n\n {\n\n // ドア状態の判定\n\n if (doorStatus == 0x08)\n\n {\n\n Serial.println(\"Open\");\n\n canvas.fillCanvas(0);\n\n canvas.setTextSize(5);\n\n canvas.drawString(\"Open\", 45, 350);\n\n canvas.pushCanvas(0, 0, UPDATE_MODE_DU4);\n\n }\n\n else if (doorStatus == 0x09)\n\n {\n\n Serial.println(\"Close\");\n\n canvas.fillCanvas(0);\n\n canvas.setTextSize(5);\n", "file_path": "example/m5paper/receiver/src/main.cpp", "rank": 23, "score": 1.3400316714693712 } ]
C++
src/appleseed/foundation/array/meshalgorithm.cpp
jaichhabra/appleseed
bc952ad860ca6f93bfe4cdd2b966acac4cb42e20
#include "foundation/array/applyvisitor.h" #include "foundation/array/array.h" #include "foundation/array/arrayview.h" #include "foundation/array/exception.h" #include "foundation/array/meshalgorithm.h" #include <algorithm> #include <cstdint> namespace foundation { namespace { struct ComputeBBoxVisitor { AABB3f m_bbox; ComputeBBoxVisitor() { m_bbox.invalidate(); } explicit ComputeBBoxVisitor(const AABB3f& bbox) : m_bbox(bbox) { } void operator()(const ArrayView<Vector3f>& view) { for (const Vector3f& p : view) m_bbox.insert(p); } template <typename T> void operator()(const ArrayView<T>& view) { throw BadArrayTypeException(); } }; class FaceSidesInfoVisitor { public: explicit FaceSidesInfoVisitor(FaceSidesInfo& stats) : m_stats(stats) { } void operator()(const ArrayView<std::uint8_t>& view) { collect_stats(view); } void operator()(const ArrayView<std::uint16_t>& view) { collect_stats(view); } void operator()(const ArrayView<std::uint32_t>& view) { collect_stats(view); } template <typename T> void operator()(const ArrayView<T>& view) { throw BadArrayTypeException(); } private: FaceSidesInfo& m_stats; template <typename T> void collect_stats(const ArrayView<T>& view) { for (const T n : view) { m_stats.m_face_count++; if (n < 3) m_stats.m_invalid_count++; else if (n == 3) m_stats.m_triangle_count++; else if (n == 4) m_stats.m_quad_count++; else m_stats.m_ngon_count++; m_stats.m_max_face_sides = std::max( m_stats.m_max_face_sides, static_cast<size_t>(n)); } } }; } AABB3f compute_bounding_box(const Array& vertices) { ComputeBBoxVisitor v; apply_visitor(vertices, v); return v.m_bbox; } AABB3f compute_bounding_box(const Array& vertices, const AABB3f& initial_bbox) { ComputeBBoxVisitor v(initial_bbox); apply_visitor(vertices, v); return v.m_bbox; } FaceSidesInfo get_face_sides_info(const Array& verts_per_face) { FaceSidesInfo info; apply_visitor(verts_per_face, FaceSidesInfoVisitor(info)); return info; } }
#include "foundation/array/applyvisitor.h" #include "foundation/array/array.h" #include "foundation/array/arrayview.h" #include "foundation/array/exception.h" #include "foundation/array/meshalgorithm.h" #include <algorithm> #include <cstdint> namespace foundation { namespace { struct ComputeBBoxVisitor { AABB3f m_bbox; ComputeBBoxVisitor() { m_bbox.invalidate(); } explicit ComputeBBoxVisitor(const AABB3f& bbox) : m_bbox(bbox) { } void operator()(const ArrayView<Vector3f>& view) { for (const Vector3f& p : view) m_bbox.insert(p); } template <typename T> void operator()(const ArrayView<T>& view) { throw BadArrayTypeException(); } }; class FaceSidesInfoVisitor { public: explicit FaceSidesInfoVisitor(FaceSidesInfo& stats) : m_stats(stats) { } void operator()(const ArrayView<std::uint8_t>& view) { collect_stats(view); } void operator()(const ArrayView<std::uint16_t>& view) { collect_stats(view); } void operator()(const ArrayView<std::uint32_t>& view) { collect_stats(view); } template <typename T> void operator()(const ArrayView<T>& view) { throw BadArrayTypeException(); } private: FaceSidesInfo& m_stats; template <typename T> void collect_stats(const ArrayView<T>& view) { for (const T n : view) { m_stats.m_face_count++;
m_stats.m_max_face_sides = std::max( m_stats.m_max_face_sides, static_cast<size_t>(n)); } } }; } AABB3f compute_bounding_box(const Array& vertices) { ComputeBBoxVisitor v; apply_visitor(vertices, v); return v.m_bbox; } AABB3f compute_bounding_box(const Array& vertices, const AABB3f& initial_bbox) { ComputeBBoxVisitor v(initial_bbox); apply_visitor(vertices, v); return v.m_bbox; } FaceSidesInfo get_face_sides_info(const Array& verts_per_face) { FaceSidesInfo info; apply_visitor(verts_per_face, FaceSidesInfoVisitor(info)); return info; } }
if (n < 3) m_stats.m_invalid_count++; else if (n == 3) m_stats.m_triangle_count++; else if (n == 4) m_stats.m_quad_count++; else m_stats.m_ngon_count++;
if_condition
[ { "content": "class Matrix<T, N, N>\n\n{\n\n public:\n\n // Types.\n\n typedef T ValueType;\n\n typedef Matrix<T, N, N> MatrixType;\n\n\n\n // Dimensions and number of components.\n\n static const size_t Rows = N;\n\n static const size_t Columns = N;\n\n static const size_t Components = N * N;\n\n\n\n // Constructors.\n\n#if APPLESEED_COMPILER_CXX_DEFAULTED_FUNCTIONS\n\n Matrix() = default; // leave all components uninitialized\n\n#else\n\n Matrix() {} // leave all components uninitialized\n\n#endif\n\n explicit Matrix(const ValueType val); // set all components to `val`\n\n\n", "file_path": "src/appleseed/foundation/math/matrix.h", "rank": 0, "score": 265352.80162116425 }, { "content": "class AlignedAllocator<void>\n\n{\n\n public:\n\n typedef void value_type;\n\n typedef value_type* pointer;\n\n typedef const value_type* const_pointer;\n\n\n\n template <typename U>\n\n struct rebind\n\n {\n\n typedef AlignedAllocator<U> other;\n\n };\n\n\n\n explicit AlignedAllocator(const size_t alignment = 16)\n\n : m_alignment(alignment)\n\n {\n\n }\n\n\n\n template <typename U>\n\n AlignedAllocator(const AlignedAllocator<U>& rhs)\n", "file_path": "src/appleseed/foundation/memory/alignedallocator.h", "rank": 1, "score": 256256.6621925969 }, { "content": "class ArrayAllocator<void>\n\n{\n\n public:\n\n typedef void value_type;\n\n typedef value_type* pointer;\n\n typedef const value_type* const_pointer;\n\n\n\n template <typename U>\n\n struct rebind\n\n {\n\n typedef ArrayAllocator<U> other;\n\n };\n\n\n\n ArrayAllocator() = default;\n\n\n\n template <typename U>\n\n ArrayAllocator(const ArrayAllocator<U>&)\n\n {\n\n }\n\n};\n\n\n\n} // namespace foundation\n", "file_path": "src/appleseed/foundation/array/arrayallocator.h", "rank": 2, "score": 256256.6621925969 }, { "content": "struct ExceptionEOF : public Exception {};\n\n\n\n// Throws foundation::ExceptionEOF or foundation::ExceptionIOError.\n\ntemplate <typename File>\n\nvoid checked_read(File& file, void* outbuf, const size_t size);\n\n\n\n// Throws foundation::ExceptionEOF or foundation::ExceptionIOError.\n\ntemplate <typename File, typename T>\n\nvoid checked_read(File& file, T& object);\n\n\n\n// Throws foundation::ExceptionIOError.\n\ntemplate <typename File>\n\nvoid checked_write(File& file, const void* inbuf, const size_t size);\n\n\n\n// Throws foundation::ExceptionIOError.\n\ntemplate <typename File, typename T>\n\nvoid checked_write(File& file, const T& object);\n\n\n\n\n\n//\n\n// Base classes for foundation::BufferedFile adapters.\n\n//\n\n\n", "file_path": "src/appleseed/foundation/utility/bufferedfile.h", "rank": 3, "score": 243504.17032197615 }, { "content": " // Exception thrown when the feature of IES file is not supported by this parser.\n\n class NotSupportedException : public Exception\n\n {\n\n public:\n\n NotSupportedException(const char* message, int line)\n\n : Exception(message, line)\n\n {\n\n }\n\n };\n\n\n\n // Dictionary containing IES file keywords and corresponding values.\n\n typedef std::unordered_map<std::string, std::string> KeywordsDictionary;\n\n\n\n // Type of IES file format.\n\n enum Format\n\n {\n\n UnknownFormat,\n\n Format1986,\n\n Format1991,\n\n Format1995,\n\n Format2002,\n", "file_path": "src/appleseed/foundation/utility/iesparser.h", "rank": 4, "score": 242426.8153684485 }, { "content": " // Exception thrown when file format violates the IES specifications.\n\n class ParsingException : public Exception\n\n {\n\n public:\n\n ParsingException(const char* message, int line)\n\n : Exception(message, line)\n\n {\n\n }\n\n };\n\n\n", "file_path": "src/appleseed/foundation/utility/iesparser.h", "rank": 5, "score": 242426.8153684485 }, { "content": "// Exception thrown when attempting to invert a singular matrix.\n\nstruct ExceptionSingularMatrix : public Exception {};\n\n\n\n// Matrix inversion using Gauss-Jordan elimination with partial pivoting.\n\n// Throws a foundation::ExceptionSingularMatrix exception if the matrix is singular.\n\ntemplate <typename T, size_t N>\n\nMatrix<T, N, N> inverse(\n\n const Matrix<T, N, N>& mat,\n\n const T eps = default_eps<T>());\n\n\n\n\n\n//\n\n// 3x3 matrix class of arbitrary type.\n\n//\n\n\n\ntemplate <typename T>\n", "file_path": "src/appleseed/foundation/math/matrix.h", "rank": 6, "score": 239448.82745089094 }, { "content": "// Exception thrown by the utility function foundation::from_string()\n\n// when an error occurred when converting a value to a string.\n\nclass ExceptionStringConversionError : public Exception {};\n\n\n\n// Convert a value to a string.\n\ntemplate <typename T>\n\nstd::string to_string(const T& value);\n\n\n\n// Convert an array of values to a string.\n\ntemplate <typename T>\n\nstd::string to_string(\n\n const T array[],\n\n const size_t n,\n\n const std::string& separator = \" \");\n\n\n\n// Convert a string to a value.\n\ntemplate <typename T>\n\nT from_string(const std::string& s);\n\ntemplate <typename T>\n\nT from_string(const char* s);\n\n\n\n\n", "file_path": "src/appleseed/foundation/string/string.h", "rank": 7, "score": 234515.37986043096 }, { "content": "class const_each\n\n{\n\n public:\n\n // Types.\n\n typedef typename C::const_iterator const_iterator;\n\n typedef typename const_iterator::value_type value_type;\n\n\n\n // Constructor.\n\n const_each(const C& c);\n\n\n\n // Conversion to bool, return true if the iterator\n\n // hasn't yet reached the end of the collection.\n\n operator bool() const;\n\n\n\n // Preincrement operator.\n\n const_each& operator++();\n\n\n\n // Iterator comparison.\n\n bool operator==(const const_iterator& rhs) const;\n\n bool operator!=(const const_iterator& rhs) const;\n", "file_path": "src/appleseed/foundation/utility/foreach.h", "rank": 8, "score": 234018.9747943455 }, { "content": "class PoisonImpl<Ray<T, N>>\n\n{\n\n public:\n\n static void do_poison(Ray<T, N>& ray);\n\n};\n\n\n\n// Exact inequality and equality tests.\n\ntemplate <typename T, size_t N> bool operator!=(const Ray<T, N>& lhs, const Ray<T, N>& rhs);\n\ntemplate <typename T, size_t N> bool operator==(const Ray<T, N>& lhs, const Ray<T, N>& rhs);\n\n\n\n// Approximate equality tests.\n\ntemplate <typename T, size_t N> bool feq(const Ray<T, N>& lhs, const Ray<T, N>& rhs);\n\ntemplate <typename T, size_t N> bool feq(const Ray<T, N>& lhs, const Ray<T, N>& rhs, const T eps);\n\n\n\n\n\n//\n\n// Full specializations for 2D, 3D and 4D rays of type float and double.\n\n//\n\n\n\ntypedef Ray<float, 2> Ray2f;\n", "file_path": "src/appleseed/foundation/math/ray.h", "rank": 9, "score": 231066.83953733818 }, { "content": "class PoisonImpl<Color<T, N>>\n\n{\n\n public:\n\n static void do_poison(Color<T, N>& c);\n\n};\n\n\n\n// Exact inequality and equality tests.\n\ntemplate <typename T, size_t N> bool operator!=(const Color<T, N>& lhs, const Color<T, N>& rhs);\n\ntemplate <typename T, size_t N> bool operator==(const Color<T, N>& lhs, const Color<T, N>& rhs);\n\n\n\n// Return whether all components of a color are exactly zero.\n\ntemplate <typename T, size_t N> bool is_zero(const Color<T, N>& c);\n\n\n\n// Approximate equality tests.\n\ntemplate <typename T, size_t N> bool feq(const Color<T, N>& lhs, const Color<T, N>& rhs);\n\ntemplate <typename T, size_t N> bool feq(const Color<T, N>& lhs, const Color<T, N>& rhs, const T eps);\n\n\n\n// Approximate zero tests.\n\ntemplate <typename T, size_t N> bool fz(const Color<T, N>& c);\n\ntemplate <typename T, size_t N> bool fz(const Color<T, N>& c, const T eps);\n", "file_path": "src/appleseed/foundation/image/color.h", "rank": 10, "score": 231066.83953733818 }, { "content": "class PoisonImpl<Vector<T, N>>\n\n{\n\n public:\n\n static void do_poison(Vector<T, N>& v);\n\n};\n\n\n\n// Exact inequality and equality tests.\n\ntemplate <typename T, size_t N> bool operator!=(const Vector<T, N>& lhs, const Vector<T, N>& rhs);\n\ntemplate <typename T, size_t N> bool operator==(const Vector<T, N>& lhs, const Vector<T, N>& rhs);\n\n\n\n// Approximate equality tests.\n\ntemplate <typename T, size_t N> bool feq(const Vector<T, N>& lhs, const Vector<T, N>& rhs);\n\ntemplate <typename T, size_t N> bool feq(const Vector<T, N>& lhs, const Vector<T, N>& rhs, const T eps);\n\n\n\n// Approximate zero tests.\n\ntemplate <typename T, size_t N> bool fz(const Vector<T, N>& v);\n\ntemplate <typename T, size_t N> bool fz(const Vector<T, N>& v, const T eps);\n\n\n\n// Vector arithmetic.\n\ntemplate <typename T, size_t N> Vector<T, N> operator+ (const Vector<T, N>& lhs, const Vector<T, N>& rhs);\n", "file_path": "src/appleseed/foundation/math/vector.h", "rank": 11, "score": 231066.83953733818 }, { "content": "class CwiseUnaryView : public CwiseUnaryViewImpl<ViewOp, MatrixType, typename internal::traits<MatrixType>::StorageKind>\n\n{\n\n public:\n\n\n\n typedef typename CwiseUnaryViewImpl<ViewOp, MatrixType,typename internal::traits<MatrixType>::StorageKind>::Base Base;\n\n EIGEN_GENERIC_PUBLIC_INTERFACE(CwiseUnaryView)\n\n typedef typename internal::ref_selector<MatrixType>::non_const_type MatrixTypeNested;\n\n typedef typename internal::remove_all<MatrixType>::type NestedExpression;\n\n\n\n explicit inline CwiseUnaryView(MatrixType& mat, const ViewOp& func = ViewOp())\n\n : m_matrix(mat), m_functor(func) {}\n\n\n\n EIGEN_INHERIT_ASSIGNMENT_OPERATORS(CwiseUnaryView)\n\n\n\n EIGEN_STRONG_INLINE Index rows() const { return m_matrix.rows(); }\n\n EIGEN_STRONG_INLINE Index cols() const { return m_matrix.cols(); }\n\n\n\n /** \\returns the functor representing unary operation */\n\n const ViewOp& functor() const { return m_functor; }\n\n\n", "file_path": "src/thirdparty/bcd/ext/eigen/Eigen/src/Core/CwiseUnaryView.h", "rank": 12, "score": 229447.07303581486 }, { "content": "class ArrayView\n\n{\n\n public:\n\n typedef T value_type;\n\n\n\n // Constructor.\n\n explicit ArrayView(const Array& array)\n\n : m_begin(reinterpret_cast<const T*>(array.begin()))\n\n , m_end (reinterpret_cast<const T*>(array.end()))\n\n {\n\n assert(array.type() == ArrayTraits<T>::array_type());\n\n }\n\n\n\n // Return true if the array is empty.\n\n bool empty() const\n\n {\n\n return m_begin == m_end;\n\n }\n\n\n\n // Return the number of items in the array.\n", "file_path": "src/appleseed/foundation/array/arrayview.h", "rank": 13, "score": 229346.86882563712 }, { "content": "struct ExceptionJsonValue : public foundation::Exception\n\n{\n\n};\n\n\n", "file_path": "src/appleseed.bench/utility/backendapi.h", "rank": 14, "score": 228111.3633703625 }, { "content": "class CopyIndexedVisitor\n\n{\n\n public:\n\n CopyIndexedVisitor(\n\n const Array& src,\n\n const RandomAccessIter first_index,\n\n const RandomAccessIter last_index)\n\n : m_src(src)\n\n , m_first_index(first_index)\n\n , m_last_index(last_index)\n\n {\n\n }\n\n\n\n template <typename T>\n\n void operator()(ArrayRef<T>& dst)\n\n {\n\n const ArrayView<T> src(m_src);\n\n\n\n for (RandomAccessIter it = m_first_index; it != m_last_index; ++it)\n\n dst.push_back(src[*it]);\n", "file_path": "src/appleseed/foundation/array/algorithm.h", "rank": 15, "score": 224919.4322739757 }, { "content": "class IndexedView : public IndexedViewImpl<XprType, RowIndices, ColIndices, typename internal::traits<XprType>::StorageKind>\n\n{\n\npublic:\n\n typedef typename IndexedViewImpl<XprType, RowIndices, ColIndices, typename internal::traits<XprType>::StorageKind>::Base Base;\n\n EIGEN_GENERIC_PUBLIC_INTERFACE(IndexedView)\n\n EIGEN_INHERIT_ASSIGNMENT_OPERATORS(IndexedView)\n\n\n\n typedef typename internal::ref_selector<XprType>::non_const_type MatrixTypeNested;\n\n typedef typename internal::remove_all<XprType>::type NestedExpression;\n\n\n\n template<typename T0, typename T1>\n\n IndexedView(XprType& xpr, const T0& rowIndices, const T1& colIndices)\n\n : m_xpr(xpr), m_rowIndices(rowIndices), m_colIndices(colIndices)\n\n {}\n\n\n\n /** \\returns number of rows */\n\n Index rows() const { return internal::size(m_rowIndices); }\n\n\n\n /** \\returns number of columns */\n\n Index cols() const { return internal::size(m_colIndices); }\n", "file_path": "src/thirdparty/bcd/ext/eigen/Eigen/src/Core/IndexedView.h", "rank": 16, "score": 223582.1418658891 }, { "content": "class PoisonImpl<Matrix<T, M, N>>\n\n{\n\n public:\n\n static void do_poison(Matrix<T, M, N>& m);\n\n};\n\n\n\n// Exact inequality and equality tests.\n\ntemplate <typename T, size_t M, size_t N> bool operator!=(const Matrix<T, M, N>& lhs, const Matrix<T, M, N>& rhs);\n\ntemplate <typename T, size_t M, size_t N> bool operator==(const Matrix<T, M, N>& lhs, const Matrix<T, M, N>& rhs);\n\n\n\n// Approximate equality tests.\n\ntemplate <typename T, size_t M, size_t N> bool feq(const Matrix<T, M, N>& lhs, const Matrix<T, M, N>& rhs);\n\ntemplate <typename T, size_t M, size_t N> bool feq(const Matrix<T, M, N>& lhs, const Matrix<T, M, N>& rhs, const T eps);\n\n\n\n// Approximate zero tests.\n\ntemplate <typename T, size_t M, size_t N> bool fz(const Matrix<T, M, N>& m);\n\ntemplate <typename T, size_t M, size_t N> bool fz(const Matrix<T, M, N>& m, const T eps);\n\n\n\n// Matrix arithmetic.\n\ntemplate <typename T, size_t M, size_t N> Matrix<T, M, N> operator+ (const Matrix<T, M, N>& lhs, const Matrix<T, M, N>& rhs);\n", "file_path": "src/appleseed/foundation/math/matrix.h", "rank": 17, "score": 221334.91916782793 }, { "content": " class InnerIterator : public EvalIterator\n\n {\n\n typedef typename XprType::Scalar Scalar;\n\n public:\n\n\n\n EIGEN_STRONG_INLINE InnerIterator(const unary_evaluator& sve, Index outer)\n\n : EvalIterator(sve.m_argImpl,outer), m_view(sve.m_view)\n\n {\n\n incrementToNonZero();\n\n }\n\n\n\n EIGEN_STRONG_INLINE InnerIterator& operator++()\n\n {\n\n EvalIterator::operator++();\n\n incrementToNonZero();\n\n return *this;\n\n }\n\n\n\n using EvalIterator::value;\n\n\n", "file_path": "src/thirdparty/bcd/ext/eigen/Eigen/src/SparseCore/SparseView.h", "rank": 18, "score": 219962.64635884884 }, { "content": "class SparseView : public SparseMatrixBase<SparseView<MatrixType> >\n\n{\n\n typedef typename MatrixType::Nested MatrixTypeNested;\n\n typedef typename internal::remove_all<MatrixTypeNested>::type _MatrixTypeNested;\n\n typedef SparseMatrixBase<SparseView > Base;\n\npublic:\n\n EIGEN_SPARSE_PUBLIC_INTERFACE(SparseView)\n\n typedef typename internal::remove_all<MatrixType>::type NestedExpression;\n\n\n\n explicit SparseView(const MatrixType& mat, const Scalar& reference = Scalar(0),\n\n const RealScalar &epsilon = NumTraits<Scalar>::dummy_precision())\n\n : m_matrix(mat), m_reference(reference), m_epsilon(epsilon) {}\n\n\n\n inline Index rows() const { return m_matrix.rows(); }\n\n inline Index cols() const { return m_matrix.cols(); }\n\n\n\n inline Index innerSize() const { return m_matrix.innerSize(); }\n\n inline Index outerSize() const { return m_matrix.outerSize(); }\n\n \n\n /** \\returns the nested expression */\n", "file_path": "src/thirdparty/bcd/ext/eigen/Eigen/src/SparseCore/SparseView.h", "rank": 19, "score": 219044.381727186 }, { "content": " class InnerIterator : public EvalIterator\n\n {\n\n typedef EvalIterator Base;\n\n public:\n\n\n\n EIGEN_STRONG_INLINE InnerIterator(const unary_evaluator& xprEval, Index outer)\n\n : Base(xprEval.m_argImpl,outer), m_returnOne(false), m_containsDiag(Base::outer()<xprEval.m_arg.innerSize())\n\n {\n\n if(SkipFirst)\n\n {\n\n while((*this) && ((HasUnitDiag||SkipDiag) ? this->index()<=outer : this->index()<outer))\n\n Base::operator++();\n\n if(HasUnitDiag)\n\n m_returnOne = m_containsDiag;\n\n }\n\n else if(HasUnitDiag && ((!Base::operator bool()) || Base::index()>=Base::outer()))\n\n {\n\n if((!SkipFirst) && Base::operator bool())\n\n Base::operator++();\n\n m_returnOne = m_containsDiag;\n", "file_path": "src/thirdparty/bcd/ext/eigen/Eigen/src/SparseCore/SparseTriangularView.h", "rank": 20, "score": 216910.7537940934 }, { "content": "class BboxSortPredicate\n\n{\n\n public:\n\n BboxSortPredicate(\n\n const AABBVector& bboxes,\n\n const size_t dim);\n\n\n\n bool operator()(const size_t lhs, const size_t rhs) const;\n\n\n\n private:\n\n typedef typename AABBVector::value_type AABBType;\n\n typedef typename AABBType::ValueType ValueType;\n\n\n\n const AABBVector& m_bboxes;\n\n const size_t m_dim;\n\n};\n\n\n\n\n\n//\n\n// Same as BboxSortPredicate but provides a stable sort.\n\n//\n\n\n\ntemplate <typename AABBVector>\n", "file_path": "src/appleseed/foundation/math/bvh/bvh_bboxsortpredicate.h", "rank": 21, "score": 216627.53082222614 }, { "content": "class PoolAllocator<void, ItemsPerPage, FallBackAllocator>\n\n{\n\n public:\n\n typedef void value_type;\n\n typedef value_type* pointer;\n\n typedef const value_type* const_pointer;\n\n\n\n template <typename U>\n\n struct rebind\n\n {\n\n typedef PoolAllocator<\n\n U,\n\n ItemsPerPage,\n\n typename FallBackAllocator::template rebind<U>::other\n\n > other;\n\n };\n\n\n\n explicit PoolAllocator(FallBackAllocator allocator = FallBackAllocator())\n\n : m_fallback_alloc(allocator)\n\n {\n", "file_path": "src/appleseed/foundation/memory/poolallocator.h", "rank": 22, "score": 216526.94483506988 }, { "content": "class const_blas_data_mapper : public blas_data_mapper<const Scalar, Index, StorageOrder> {\n\n public:\n\n EIGEN_ALWAYS_INLINE const_blas_data_mapper(const Scalar *data, Index stride) : blas_data_mapper<const Scalar, Index, StorageOrder>(data, stride) {}\n\n\n\n EIGEN_ALWAYS_INLINE const_blas_data_mapper<Scalar, Index, StorageOrder> getSubMapper(Index i, Index j) const {\n\n return const_blas_data_mapper<Scalar, Index, StorageOrder>(&(this->operator()(i, j)), this->m_stride);\n\n }\n\n};\n\n\n\n\n\n/* Helper class to analyze the factors of a Product expression.\n\n * In particular it allows to pop out operator-, scalar multiples,\n\n * and conjugate */\n\ntemplate<typename XprType> struct blas_traits\n\n{\n\n typedef typename traits<XprType>::Scalar Scalar;\n\n typedef const XprType& ExtractType;\n\n typedef XprType _ExtractType;\n\n enum {\n\n IsComplex = NumTraits<Scalar>::IsComplex,\n", "file_path": "src/thirdparty/bcd/ext/eigen/Eigen/src/Core/util/BlasUtil.h", "rank": 23, "score": 215695.68996929936 }, { "content": " // Constant iterator.\n\n class APPLESEED_DLLSYMBOL const_iterator\n\n {\n\n public:\n\n // Value type.\n\n typedef const_iterator value_type;\n\n\n\n // Constructors.\n\n const_iterator();\n\n const_iterator(const const_iterator& rhs);\n\n const_iterator(const iterator& rhs);\n\n\n\n // Destructor.\n\n ~const_iterator();\n\n\n\n // Assignment operator.\n\n const_iterator& operator=(const const_iterator& rhs);\n\n\n\n // Equality and inequality tests.\n\n bool operator==(const const_iterator& rhs) const;\n\n bool operator!=(const const_iterator& rhs) const;\n", "file_path": "src/appleseed/foundation/containers/dictionary.h", "rank": 24, "score": 214326.1409282045 }, { "content": "class StableBboxSortPredicate\n\n{\n\n public:\n\n StableBboxSortPredicate(\n\n const AABBVector& bboxes,\n\n const size_t dim);\n\n\n\n bool operator()(const size_t lhs, const size_t rhs) const;\n\n\n\n private:\n\n typedef typename AABBVector::value_type AABBType;\n\n typedef typename AABBType::ValueType ValueType;\n\n\n\n const AABBVector& m_bboxes;\n\n const size_t m_dim;\n\n};\n\n\n\n\n\n//\n\n// BboxSortPredicate class implementation.\n", "file_path": "src/appleseed/foundation/math/bvh/bvh_bboxsortpredicate.h", "rank": 25, "score": 212758.02746002024 }, { "content": "struct TypeConv : public impl::TypeConv<sizeof(T)> {};\n\n\n\n\n\n//\n\n// Check whether a type is a pointer type.\n\n//\n\n// Reference:\n\n//\n\n// http://semantics.org/once_weakly/w02_SFINAE.pdf\n\n//\n\n\n\ntemplate <typename T> struct IsPointer { enum { R = false }; };\n\ntemplate <typename T> struct IsPointer<T*> { enum { R = true }; };\n\ntemplate <typename T> struct IsPointer<T* const> { enum { R = true }; };\n\ntemplate <typename T> struct IsPointer<T* volatile> { enum { R = true }; };\n\ntemplate <typename T> struct IsPointer<T* const volatile> { enum { R = true }; };\n\n\n\n\n\n//\n\n// Dereference a type at compile-time.\n", "file_path": "src/appleseed/foundation/utility/typetraits.h", "rank": 26, "score": 210096.5837828308 }, { "content": "struct DictionaryDictionary::const_iterator::Impl\n\n{\n\n DictionaryMap::const_iterator m_it;\n\n};\n\n\n\nDictionaryDictionary::const_iterator::const_iterator()\n\n : impl(new Impl())\n\n{\n\n}\n\n\n\nDictionaryDictionary::const_iterator::const_iterator(const const_iterator& rhs)\n\n : impl(new Impl())\n\n{\n\n impl->m_it = rhs.impl->m_it;\n\n}\n\n\n\nDictionaryDictionary::const_iterator::const_iterator(const iterator& rhs)\n\n : impl(new Impl())\n\n{\n\n impl->m_it = rhs.impl->m_it;\n", "file_path": "src/appleseed/foundation/containers/dictionary.cpp", "rank": 27, "score": 202777.78144915076 }, { "content": "struct StringDictionary::const_iterator::Impl\n\n{\n\n StringMap::const_iterator m_it;\n\n};\n\n\n\nStringDictionary::const_iterator::const_iterator()\n\n : impl(new Impl())\n\n{\n\n}\n\n\n\nStringDictionary::const_iterator::const_iterator(const const_iterator& rhs)\n\n : impl(new Impl(*rhs.impl))\n\n{\n\n}\n\n\n\nStringDictionary::const_iterator::~const_iterator()\n\n{\n\n delete impl;\n\n}\n\n\n", "file_path": "src/appleseed/foundation/containers/dictionary.cpp", "rank": 28, "score": 202777.78144915076 }, { "content": "struct ScalarBinaryOpTraits<void,void,BinaryOp>\n\n{\n\n typedef void ReturnType;\n\n};\n\n\n\n// We require Lhs and Rhs to have \"compatible\" scalar types.\n\n// It is tempting to always allow mixing different types but remember that this is often impossible in the vectorized paths.\n\n// So allowing mixing different types gives very unexpected errors when enabling vectorization, when the user tries to\n\n// add together a float matrix and a double matrix.\n\n#define EIGEN_CHECK_BINARY_COMPATIBILIY(BINOP,LHS,RHS) \\\n\n EIGEN_STATIC_ASSERT((Eigen::internal::has_ReturnType<ScalarBinaryOpTraits<LHS, RHS,BINOP> >::value), \\\n\n YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY)\n\n \n\n} // end namespace Eigen\n\n\n\n#endif // EIGEN_XPRHELPER_H\n", "file_path": "src/thirdparty/bcd/ext/eigen/Eigen/src/Core/util/XprHelper.h", "rank": 30, "score": 187684.75179027842 }, { "content": "// Class to implement the multiscale Bayesian Collaborative Filtering for\n\n// Monte-Carlo Rendering\n\nclass MultiscaleDenoiser : public IDenoiser\n\n{\n\n public:\n\n explicit MultiscaleDenoiser(int i_nbOfScales);\n\n\n\n virtual ~MultiscaleDenoiser() {}\n\n\n\n public:\n\n virtual bool denoise() override;\n\n\n\n private:\n\n\n\n void setInputs(const DenoiserInputs& i_rInputs) override;\n\n\n\n typedef std::vector<std::unique_ptr<DeepImage<float>>> DeepImageVec;\n\n\n\n static DeepImageVec generateDownscaledEmptyImages(\n\n const DeepImage<float>& i_rScale0Image,\n\n int i_nbOfScalesToGenerate);\n\n\n", "file_path": "src/thirdparty/bcd/bcd/MultiscaleDenoiser.h", "rank": 31, "score": 182178.9260721576 }, { "content": "class ProceduralInput : public ImageInput\n\n{\n\n public:\n\n ProceduralInput();\n\n ~ProceduralInput() override;\n\n\n\n const char* format_name() const override;\n\n\n\n int supports(string_view feature) const override;\n\n\n\n bool valid_file(const std::string& filename) const override;\n\n\n\n bool open(const std::string& name, ImageSpec& newspec) override;\n\n bool open(const std::string& name, ImageSpec& newspec, const ImageSpec& config) override;\n\n\n\n bool close() override;\n\n\n\n int current_subimage() const override;\n\n int current_miplevel() const override;\n\n\n", "file_path": "sandbox/examples/cpp/proceduraltexture/proceduraltexture.cpp", "rank": 32, "score": 179553.32703461757 }, { "content": "class SparseLU : public SparseSolverBase<SparseLU<_MatrixType,_OrderingType> >, public internal::SparseLUImpl<typename _MatrixType::Scalar, typename _MatrixType::StorageIndex>\n\n{\n\n protected:\n\n typedef SparseSolverBase<SparseLU<_MatrixType,_OrderingType> > APIBase;\n\n using APIBase::m_isInitialized;\n\n public:\n\n using APIBase::_solve_impl;\n\n \n\n typedef _MatrixType MatrixType; \n\n typedef _OrderingType OrderingType;\n\n typedef typename MatrixType::Scalar Scalar; \n\n typedef typename MatrixType::RealScalar RealScalar; \n\n typedef typename MatrixType::StorageIndex StorageIndex;\n\n typedef SparseMatrix<Scalar,ColMajor,StorageIndex> NCMatrix;\n\n typedef internal::MappedSuperNodalMatrix<Scalar, StorageIndex> SCMatrix;\n\n typedef Matrix<Scalar,Dynamic,1> ScalarVector;\n\n typedef Matrix<StorageIndex,Dynamic,1> IndexVector;\n\n typedef PermutationMatrix<Dynamic, Dynamic, StorageIndex> PermutationType;\n\n typedef internal::SparseLUImpl<Scalar, StorageIndex> Base;\n\n\n", "file_path": "src/thirdparty/bcd/ext/eigen/Eigen/src/SparseLU/SparseLU.h", "rank": 33, "score": 178990.48492908405 }, { "content": "struct evaluator<const T>\n\n : evaluator<T>\n\n{\n\n EIGEN_DEVICE_FUNC\n\n explicit evaluator(const T& xpr) : evaluator<T>(xpr) {}\n\n};\n\n\n\n// ---------- base class for all evaluators ----------\n\n\n\ntemplate<typename ExpressionType>\n", "file_path": "src/thirdparty/bcd/ext/eigen/Eigen/src/Core/CoreEvaluators.h", "rank": 34, "score": 175703.5856242853 }, { "content": "class Inverse : public InverseImpl<XprType,typename internal::traits<XprType>::StorageKind>\n\n{\n\npublic:\n\n typedef typename XprType::StorageIndex StorageIndex;\n\n typedef typename XprType::PlainObject PlainObject;\n\n typedef typename XprType::Scalar Scalar;\n\n typedef typename internal::ref_selector<XprType>::type XprTypeNested;\n\n typedef typename internal::remove_all<XprTypeNested>::type XprTypeNestedCleaned;\n\n typedef typename internal::ref_selector<Inverse>::type Nested;\n\n typedef typename internal::remove_all<XprType>::type NestedExpression;\n\n \n\n explicit EIGEN_DEVICE_FUNC Inverse(const XprType &xpr)\n\n : m_xpr(xpr)\n\n {}\n\n\n\n EIGEN_DEVICE_FUNC Index rows() const { return m_xpr.rows(); }\n\n EIGEN_DEVICE_FUNC Index cols() const { return m_xpr.cols(); }\n\n\n\n EIGEN_DEVICE_FUNC const XprTypeNestedCleaned& nestedExpression() const { return m_xpr; }\n\n\n\nprotected:\n\n XprTypeNested m_xpr;\n\n};\n\n\n\n// Generic API dispatcher\n\ntemplate<typename XprType, typename StorageKind>\n", "file_path": "src/thirdparty/bcd/ext/eigen/Eigen/src/Core/Inverse.h", "rank": 35, "score": 175160.3313858945 }, { "content": "struct Assignment<DstXprType, Solve<CwiseUnaryOp<internal::scalar_conjugate_op<typename DecType::Scalar>, const Transpose<const DecType> >,RhsType>,\n\n internal::assign_op<Scalar,Scalar>, Dense2Dense>\n\n{\n\n typedef Solve<CwiseUnaryOp<internal::scalar_conjugate_op<typename DecType::Scalar>, const Transpose<const DecType> >,RhsType> SrcXprType;\n\n static void run(DstXprType &dst, const SrcXprType &src, const internal::assign_op<Scalar,Scalar> &)\n\n {\n\n Index dstRows = src.rows();\n\n Index dstCols = src.cols();\n\n if((dst.rows()!=dstRows) || (dst.cols()!=dstCols))\n\n dst.resize(dstRows, dstCols);\n\n \n\n src.dec().nestedExpression().nestedExpression().template _solve_impl_transposed<true>(src.rhs(), dst);\n\n }\n\n};\n\n\n\n} // end namepsace internal\n\n\n\n} // end namespace Eigen\n\n\n\n#endif // EIGEN_SOLVE_H\n", "file_path": "src/thirdparty/bcd/ext/eigen/Eigen/src/Core/Solve.h", "rank": 36, "score": 172357.4360122535 }, { "content": "class each\n\n{\n\n public:\n\n // Types.\n\n typedef typename C::iterator iterator;\n\n typedef typename iterator::value_type value_type;\n\n\n\n // Constructor.\n\n each(C& c);\n\n\n\n // Conversion to bool, return true if the iterator\n\n // hasn't yet reached the end of the collection.\n\n operator bool() const;\n\n\n\n // Preincrement operator.\n\n each& operator++();\n\n\n\n // Iterator comparison.\n\n bool operator==(const iterator& rhs) const;\n\n bool operator!=(const iterator& rhs) const;\n", "file_path": "src/appleseed/foundation/utility/foreach.h", "rank": 37, "score": 172334.49680520754 }, { "content": "struct blas_traits<const T>\n\n : blas_traits<T>\n\n{};\n\n\n\ntemplate<typename T, bool HasUsableDirectAccess=blas_traits<T>::HasUsableDirectAccess>\n", "file_path": "src/thirdparty/bcd/ext/eigen/Eigen/src/Core/util/BlasUtil.h", "rank": 38, "score": 171192.15629466262 }, { "content": "struct IsNotBase\n\n : public impl::IsNotBase<Base, Derived>::type\n\n{\n\n};\n\n\n\n} // namespace foundation\n", "file_path": "src/appleseed/foundation/utility/typetraits.h", "rank": 39, "score": 170468.91820987395 }, { "content": "struct IsBase\n\n : public impl::IsBase<Base, Derived>::type\n\n{\n\n};\n\n\n\ntemplate <typename Base, typename Derived>\n", "file_path": "src/appleseed/foundation/utility/typetraits.h", "rank": 40, "score": 170468.91820987395 }, { "content": "class Solve : public SolveImpl<Decomposition,RhsType,typename internal::traits<RhsType>::StorageKind>\n\n{\n\npublic:\n\n typedef typename internal::traits<Solve>::PlainObject PlainObject;\n\n typedef typename internal::traits<Solve>::StorageIndex StorageIndex;\n\n \n\n Solve(const Decomposition &dec, const RhsType &rhs)\n\n : m_dec(dec), m_rhs(rhs)\n\n {}\n\n \n\n EIGEN_DEVICE_FUNC Index rows() const { return m_dec.cols(); }\n\n EIGEN_DEVICE_FUNC Index cols() const { return m_rhs.cols(); }\n\n\n\n EIGEN_DEVICE_FUNC const Decomposition& dec() const { return m_dec; }\n\n EIGEN_DEVICE_FUNC const RhsType& rhs() const { return m_rhs; }\n\n\n\nprotected:\n\n const Decomposition &m_dec;\n\n const RhsType &m_rhs;\n\n};\n\n\n\n\n\n// Specialization of the Solve expression for dense results\n\ntemplate<typename Decomposition, typename RhsType>\n", "file_path": "src/thirdparty/bcd/ext/eigen/Eigen/src/Core/Solve.h", "rank": 41, "score": 170258.22187255154 }, { "content": "class IndexedViewImpl\n\n : public internal::generic_xpr_base<IndexedView<XprType, RowIndices, ColIndices> >::type\n\n{\n\npublic:\n\n typedef typename internal::generic_xpr_base<IndexedView<XprType, RowIndices, ColIndices> >::type Base;\n\n};\n\n\n\nnamespace internal {\n\n\n\n\n\ntemplate<typename ArgType, typename RowIndices, typename ColIndices>\n", "file_path": "src/thirdparty/bcd/ext/eigen/Eigen/src/Core/IndexedView.h", "rank": 42, "score": 169390.57165327854 }, { "content": "class IndexedViewImpl;\n\n\n\n\n\n/** \\class IndexedView\n\n * \\ingroup Core_Module\n\n *\n\n * \\brief Expression of a non-sequential sub-matrix defined by arbitrary sequences of row and column indices\n\n *\n\n * \\tparam XprType the type of the expression in which we are taking the intersections of sub-rows and sub-columns\n\n * \\tparam RowIndices the type of the object defining the sequence of row indices\n\n * \\tparam ColIndices the type of the object defining the sequence of column indices\n\n *\n\n * This class represents an expression of a sub-matrix (or sub-vector) defined as the intersection\n\n * of sub-sets of rows and columns, that are themself defined by generic sequences of row indices \\f$ \\{r_0,r_1,..r_{m-1}\\} \\f$\n\n * and column indices \\f$ \\{c_0,c_1,..c_{n-1} \\}\\f$. Let \\f$ A \\f$ be the nested matrix, then the resulting matrix \\f$ B \\f$ has \\c m\n\n * rows and \\c n columns, and its entries are given by: \\f$ B(i,j) = A(r_i,c_j) \\f$.\n\n *\n\n * The \\c RowIndices and \\c ColIndices types must be compatible with the following API:\n\n * \\code\n\n * <integral type> operator[](Index) const;\n", "file_path": "src/thirdparty/bcd/ext/eigen/Eigen/src/Core/IndexedView.h", "rank": 43, "score": 169390.57165327854 }, { "content": "class Statistics\n\n{\n\n public:\n\n struct ExceptionDuplicateName\n\n : public StringException\n\n {\n\n explicit ExceptionDuplicateName(const char* name);\n\n };\n\n\n\n struct ExceptionTypeMismatch\n\n : public StringException\n\n {\n\n explicit ExceptionTypeMismatch(const char* name);\n\n };\n\n\n\n struct Entry\n\n {\n\n std::string m_name;\n\n std::string m_unit;\n\n\n", "file_path": "src/appleseed/foundation/utility/statistics.h", "rank": 44, "score": 169089.53304161713 }, { "content": "class Color\n\n{\n\n public:\n\n // Value type and number of components.\n\n typedef T ValueType;\n\n static const size_t Components = N;\n\n\n\n // Constructors.\n\n#if APPLESEED_COMPILER_CXX_DEFAULTED_FUNCTIONS\n\n Color() = default; // leave all components uninitialized\n\n#else\n\n Color() {} // leave all components uninitialized\n\n#endif\n\n explicit Color(const ValueType val); // set all components to `val`\n\n\n\n // Construct a color from another color of a different type.\n\n template <typename U>\n\n explicit Color(const Color<U, N>& rhs);\n\n\n\n // Construct a color from an array of N scalars.\n", "file_path": "src/appleseed/foundation/image/color.h", "rank": 45, "score": 169089.53304161713 }, { "content": "class Drawing\n\n{\n\n public:\n\n // Draw a filled rectangle without anti-aliasing.\n\n static void draw_filled_rect(\n\n Image& image, // RGBA, linear space, premultiplied alpha\n\n const Vector2i& from, // inclusive\n\n const Vector2i& to, // inclusive\n\n const Color4f& color); // RGBA, linear space, straight alpha\n\n\n\n // Draw an antialiased 4x4 pixel dot.\n\n static void draw_dot(\n\n Image& image, // RGBA, linear space, premultiplied alpha\n\n const Vector2d& position, // position of the center of the dot\n\n const Color4f& color); // RGBA, linear space, straight alpha\n\n\n\n // Blit a bitmap.\n\n static void blit_bitmap(\n\n Image& image, // RGBA, linear space, premultiplied alpha\n\n const Vector2i& position, // position of the top-left corner\n\n const void* bitmap, // RGBA, linear space, premultiplied alpha\n\n const size_t bitmap_width,\n\n const size_t bitmap_height,\n\n const PixelFormat bitmap_pixel_format,\n\n const Color4f& tint); // RGBA, linear space, straight alpha\n\n};\n\n\n\n} // namespace foundation\n", "file_path": "src/appleseed/foundation/image/drawing.h", "rank": 46, "score": 169089.53304161713 }, { "content": "class Spinlock\n\n : public NonCopyable\n\n{\n\n public:\n\n Spinlock();\n\n\n\n bool try_lock();\n\n void lock();\n\n void unlock();\n\n\n", "file_path": "src/appleseed/foundation/platform/thread.h", "rank": 47, "score": 169089.53304161713 }, { "content": "class AABB\n\n : public AABBBase<T, N>\n\n{\n\n public:\n\n // Value, vector and AABB types.\n\n typedef T ValueType;\n\n typedef Vector<T, N> VectorType;\n\n typedef AABB<T, N> AABBType;\n\n\n\n // Constructors.\n\n#if APPLESEED_COMPILER_CXX_DEFAULTED_FUNCTIONS\n\n AABB() = default; // leave all components uninitialized\n\n#else\n\n AABB() {} // leave all components uninitialized\n\n#endif\n\n AABB(\n\n const VectorType& min, // lower bound\n\n const VectorType& max); // upper bound\n\n\n\n // Construct a bounding box from another bounding box of a different type.\n", "file_path": "src/appleseed/foundation/math/aabb.h", "rank": 48, "score": 169089.53304161713 }, { "content": " class IsBase\n\n {\n\n private:\n\n static Yes is_base(Base*);\n\n static No is_base(...);\n\n\n\n public:\n\n typedef typename test_result<sizeof(is_base((Derived*)nullptr))>::type type;\n\n };\n\n\n\n template <typename Base, typename Derived>\n", "file_path": "src/appleseed/foundation/utility/typetraits.h", "rank": 49, "score": 169089.53304161713 }, { "content": "class Dual\n\n{\n\n public:\n\n // Types.\n\n typedef T ValueType;\n\n\n\n // Constructors.\n\n#if APPLESEED_COMPILER_CXX_DEFAULTED_FUNCTIONS\n\n Dual() = default; // leave all components uninitialized\n\n#else\n\n Dual() {} // leave all components uninitialized\n\n#endif\n\n\n\n explicit Dual(const T& value);\n\n Dual(const T& value, const T& dx, const T& dy);\n\n\n\n // Construct a dual from another dual of a different type.\n\n template <typename U>\n\n explicit Dual(const Dual<U>& rhs);\n\n\n", "file_path": "src/appleseed/foundation/math/dual.h", "rank": 50, "score": 169089.53304161713 }, { "content": "class Registrar\n\n : public NonCopyable\n\n{\n\n public:\n\n typedef std::map<std::string, T*> Items;\n\n\n\n // Destructor.\n\n ~Registrar();\n\n\n\n // Remove all items.\n\n void clear();\n\n\n\n // Insert an item, replacing any existing item with the same name.\n\n void insert(const std::string& name, auto_release_ptr<T> item);\n\n\n\n // Lookup an item. Returns 0 if the item could not be found.\n\n T* lookup(const std::string& name) const;\n\n\n\n // Access the items directly.\n\n const Items& items() const;\n", "file_path": "src/appleseed/foundation/utility/registrar.h", "rank": 51, "score": 169089.53304161713 }, { "content": "class TLS\n\n{\n\n public:\n\n // Constructor.\n\n // thread_count is the number of threads having access to this object.\n\n explicit TLS(const size_t thread_count);\n\n\n\n // Set the number of threads having access to this object.\n\n void set_thread_count(const size_t thread_count);\n\n\n\n // Get the number of threads having access to this object.\n\n size_t get_thread_count() const;\n\n\n\n // Direct access to the storage area for a given thread.\n\n T& operator[](const size_t thread_index);\n\n const T& operator[](const size_t thread_index) const;\n\n\n\n private:\n\n size_t m_thread_count;\n\n size_t m_stride;\n", "file_path": "src/appleseed/foundation/utility/tls.h", "rank": 52, "score": 169089.53304161713 }, { "content": "class Stopwatch\n\n : public NonCopyable\n\n{\n\n public:\n", "file_path": "src/appleseed/foundation/utility/stopwatch.h", "rank": 53, "score": 169089.53304161713 }, { "content": " class IsNotBase\n\n {\n\n private:\n\n static No is_not_base(Base*);\n\n static Yes is_not_base(...);\n\n\n\n public:\n\n typedef typename test_result<sizeof(is_not_base((Derived*)nullptr))>::type type;\n\n };\n\n}\n\n\n\ntemplate <typename Base, typename Derived>\n", "file_path": "src/appleseed/foundation/utility/typetraits.h", "rank": 54, "score": 169089.53304161713 }, { "content": "class Arena\n\n{\n\n public:\n\n Arena();\n\n\n\n void clear();\n\n\n\n void* allocate(const size_t size);\n\n\n\n template <typename T> T* allocate();\n\n template <typename T> T* allocate_noinit();\n\n\n\n const std::uint8_t* get_storage() const;\n\n\n\n private:\n\n enum { ArenaSize = 384 * 1024 }; // bytes\n\n\n\n APPLESEED_SIMD4_ALIGN std::uint8_t m_storage[ArenaSize];\n\n const std::uint8_t* m_end;\n\n std::uint8_t* m_current;\n", "file_path": "src/appleseed/foundation/memory/arena.h", "rank": 55, "score": 169089.53304161713 }, { "content": "class Frustum\n\n{\n\n public:\n\n typedef T ValueType;\n\n\n\n // Set a given plane of the frustum.\n\n void set_plane(\n\n const size_t index,\n\n const Vector<T, 4>& plane);\n\n void set_plane(\n\n const size_t index,\n\n const Vector<T, 3>& normal); // unit-length\n\n\n\n // Get a given plane of the frustum.\n\n const Vector<T, 4>& get_plane(const size_t index) const;\n\n\n\n private:\n\n Vector<T, 4> m_planes[N];\n\n};\n\n\n", "file_path": "src/appleseed/foundation/math/frustum.h", "rank": 56, "score": 169089.53304161713 }, { "content": "class Filter1\n\n{\n\n public:\n\n typedef T ValueType;\n\n\n\n explicit Filter1(const T radius);\n\n\n\n T get_radius() const;\n\n\n\n protected:\n\n const T m_radius;\n\n const T m_rcp_radius;\n\n};\n\n\n\n\n\n//\n\n// 1D box filter.\n\n//\n\n\n\ntemplate <typename T>\n", "file_path": "src/appleseed/foundation/math/filter.h", "rank": 57, "score": 169089.53304161713 }, { "content": "class Quaternion\n\n{\n\n public:\n\n // Types.\n\n typedef T ValueType;\n\n typedef Vector<T, 3> VectorType;\n\n typedef Quaternion<T> QuaternionType;\n\n\n\n // Public members.\n\n ValueType s; // scalar part\n\n VectorType v; // vector part\n\n\n\n // Constructors.\n\n#if APPLESEED_COMPILER_CXX_DEFAULTED_FUNCTIONS\n\n Quaternion() = default; // leave all components uninitialized\n\n#else\n\n Quaternion() {} // leave all components uninitialized\n\n#endif\n\n Quaternion(const ValueType s, const VectorType& v); // initializing constructor\n\n\n", "file_path": "src/appleseed/foundation/math/quaternion.h", "rank": 58, "score": 169089.53304161713 }, { "content": "class Transform\n\n{\n\n public:\n\n // Matrix, vector and transform types.\n\n typedef Matrix<T, 4, 4> MatrixType;\n\n typedef Vector<T, 3> VectorType;\n\n typedef Transform<T> TransformType;\n\n\n\n // Constructors.\n\n#if APPLESEED_COMPILER_CXX_DEFAULTED_FUNCTIONS\n\n Transform() = default; // leave the transformation uninitialized\n\n#else\n\n Transform() {} // leave the transformation uninitialized\n\n#endif\n\n explicit Transform( // throws a foundation::ExceptionSingularMatrix exception if local_to_parent is singular\n\n const MatrixType& local_to_parent);\n\n Transform(\n\n const MatrixType& local_to_parent,\n\n const MatrixType& parent_to_local); // must be equal to inverse(local_to_parent)\n\n\n", "file_path": "src/appleseed/foundation/math/transform.h", "rank": 59, "score": 169089.53304161713 }, { "content": "class Vector\n\n{\n\n public:\n\n // Types.\n\n typedef T ValueType;\n\n typedef Vector<T, N> VectorType;\n\n\n\n // Dimension.\n\n static const size_t Dimension = N;\n\n\n\n // Constructors.\n\n#if APPLESEED_COMPILER_CXX_DEFAULTED_FUNCTIONS\n\n Vector() = default; // leave all components uninitialized\n\n#else\n\n Vector() {} // leave all components uninitialized\n\n#endif\n\n explicit Vector(const ValueType val); // set all components to `val`\n\n\n\n // Construct a vector from another vector of a different type.\n\n template <typename U>\n", "file_path": "src/appleseed/foundation/math/vector.h", "rank": 60, "score": 169089.53304161713 }, { "content": "class Split\n\n{\n\n public:\n\n // Value type.\n\n typedef T ValueType;\n\n\n\n // Split dimension and abscissa.\n\n size_t m_dimension; // split dimension\n\n ValueType m_abscissa; // split abscissa\n\n\n\n // Constructors.\n\n Split(); // leave the members uninitialized\n\n Split(\n\n const size_t dimension,\n\n const ValueType abscissa);\n\n\n\n // Create a middle split for a given bounding box.\n\n template <size_t N>\n\n static Split middle(const AABB<T, N>& bbox);\n\n};\n", "file_path": "src/appleseed/foundation/math/split.h", "rank": 61, "score": 169089.53304161713 }, { "content": "class Filter2\n\n{\n\n public:\n\n typedef T ValueType;\n\n\n\n Filter2(const T xradius, const T yradius);\n\n\n\n virtual ~Filter2() {}\n\n\n\n T get_xradius() const;\n\n T get_yradius() const;\n\n\n\n virtual T evaluate(const T x, const T y) const = 0;\n\n\n\n protected:\n\n const T m_xradius;\n\n const T m_yradius;\n\n const T m_rcp_xradius;\n\n const T m_rcp_yradius;\n\n};\n", "file_path": "src/appleseed/foundation/math/filter.h", "rank": 62, "score": 169089.53304161713 }, { "content": "class GTR1MDF\n\n{\n\n public:\n\n static float D(\n\n const Vector3f& m,\n\n const float alpha_x,\n\n const float alpha_y);\n\n\n\n static float G(\n\n const Vector3f& wi,\n\n const Vector3f& wo,\n\n const Vector3f& m,\n\n const float alpha_x,\n\n const float alpha_y);\n\n\n\n static float G1(\n\n const Vector3f& v,\n\n const Vector3f& m,\n\n const float alpha_x,\n\n const float alpha_y);\n", "file_path": "src/appleseed/foundation/math/microfacet.h", "rank": 63, "score": 169089.53304161713 }, { "content": "class Triangulator\n\n{\n\n public:\n\n // Value and vector types.\n\n typedef T ValueType;\n\n typedef Vector<T, 2> Vector2Type;\n\n typedef Vector<T, 3> Vector3Type;\n\n\n\n // Polygon types.\n\n typedef std::vector<Vector2Type> Polygon2;\n\n typedef std::vector<Vector3Type> Polygon3;\n\n\n\n // Index array.\n\n typedef std::vector<size_t> IndexArray;\n\n\n\n enum Options\n\n {\n\n Default = 0, // none of the flags below\n\n KeepDegenerateTriangles = 1UL << 0 // insert degenerate triangles into triangulation\n\n };\n", "file_path": "src/appleseed/foundation/math/triangulator.h", "rank": 64, "score": 169089.53304161713 }, { "content": " // Exception that can store erroneous line number.\n\n class Exception\n\n : public foundation::Exception\n\n {\n\n public:\n\n Exception(const char* message, const int line);\n\n\n\n virtual int line() const\n\n {\n\n return m_line_number;\n\n }\n\n\n\n protected:\n\n int m_line_number;\n\n };\n\n\n", "file_path": "src/appleseed/foundation/utility/iesparser.h", "rank": 65, "score": 169089.53304161713 }, { "content": "class Pixel\n\n{\n\n public:\n\n // Return the size in bytes of a given pixel format.\n\n static size_t size(PixelFormat format);\n\n\n\n //\n\n // The convert_*() methods below allow conversion of a given range of value\n\n // in a given pixel format to another pixel format, with arbitrary striding\n\n // in both source and destination. They take advantage of the fact that in\n\n // most cases, either the source format or the destination format is known\n\n // at compile time.\n\n\n\n //\n\n // The non-specialized versions of these methods are intentionally left\n\n // unimplemented so that attempting to convert to or from a non-supported\n\n // pixel format will result in a compilation error.\n\n //\n\n\n\n // Convert from templatized format to variable format.\n", "file_path": "src/appleseed/foundation/image/pixel.h", "rank": 66, "score": 169089.53304161713 }, { "content": "class Ray\n\n{\n\n public:\n\n // Types.\n\n typedef T ValueType;\n\n typedef Vector<T, N> VectorType;\n\n typedef Ray<T, N> RayType;\n\n\n\n // Dimension.\n\n static const size_t Dimension = N;\n\n\n\n // Public members.\n\n VectorType m_org; // ray origin\n\n VectorType m_dir; // ray direction (not necessarily unit-length)\n\n ValueType m_tmin; // beginning of the ray interval (inclusive)\n\n ValueType m_tmax; // end of the ray interval (exclusive)\n\n\n\n // Constructors.\n\n#if APPLESEED_COMPILER_CXX_DEFAULTED_FUNCTIONS\n\n Ray() = default; // leave all fields uninitialized\n", "file_path": "src/appleseed/foundation/math/ray.h", "rank": 67, "score": 169089.53304161713 }, { "content": "class Population\n\n{\n\n public:\n\n // Value and population type.\n\n typedef T ValueType;\n\n typedef Population<T> PopulationType;\n\n\n\n // Constructor.\n\n Population(); // empty population\n\n\n\n // Insert `count` times the value `val` into the population.\n\n void insert(const ValueType& val, const size_t count = 1);\n\n\n\n // Merge another population into this one.\n\n void merge(const PopulationType& pop);\n\n\n\n // Return the size of the population.\n\n size_t get_size() const;\n\n\n\n // Return various properties of the population defined so far.\n", "file_path": "src/appleseed/foundation/math/population.h", "rank": 68, "score": 169089.53304161713 }, { "content": " class Plot\n\n {\n\n public:\n\n Plot& set_points(const std::vector<Vector2d>& points);\n\n Plot& set_points(const std::vector<Vector2f>& points);\n\n Plot& set_title(const std::string& title);\n\n Plot& set_color(const std::string& color);\n\n Plot& set_style(const std::string& style);\n\n Plot& set_smoothing(const std::string& smoothing);\n\n\n\n private:\n\n friend class GnuplotFile;\n\n\n\n std::vector<Vector2d> m_points;\n\n std::string m_title;\n\n std::string m_color;\n\n std::string m_style;\n\n std::string m_smoothing;\n\n\n\n void write_decl(std::ofstream& file) const;\n", "file_path": "src/appleseed/foundation/utility/gnuplotfile.h", "rank": 69, "score": 169089.53304161713 }, { "content": "class Matrix\n\n{\n\n public:\n\n // Types.\n\n typedef T ValueType;\n\n typedef Matrix<T, M, N> MatrixType;\n\n\n\n // Dimensions and number of components.\n\n static const size_t Rows = M;\n\n static const size_t Columns = N;\n\n static const size_t Components = M * N;\n\n\n\n // Constructors.\n\n#if APPLESEED_COMPILER_CXX_DEFAULTED_FUNCTIONS\n\n Matrix() = default; // leave all components uninitialized\n\n#else\n\n Matrix() {} // leave all components uninitialized\n\n#endif\n\n explicit Matrix(const ValueType val); // set all components to `val`\n\n\n", "file_path": "src/appleseed/foundation/math/matrix.h", "rank": 70, "score": 169089.53304161713 }, { "content": " class iterator;\n\n\n", "file_path": "src/appleseed/foundation/containers/dictionary.h", "rank": 71, "score": 169089.53304161713 }, { "content": " class Pool\n\n : public Singleton<Pool<ItemSize, ItemsPerPage>>\n\n {\n\n public:\n\n // Allocate a memory block.\n\n void* allocate()\n\n {\n\n Spinlock::ScopedLock lock(m_spinlock);\n\n\n\n if (Node* node = m_free_head)\n\n {\n\n // Return the first node from the list of free nodes.\n\n m_free_head = m_free_head->m_next;\n\n return node;\n\n }\n\n else\n\n {\n\n // The current page is full, allocate a new page of nodes.\n\n if (m_page_index == ItemsPerPage)\n\n {\n", "file_path": "src/appleseed/foundation/memory/poolallocator.h", "rank": 72, "score": 169089.53304161713 }, { "content": "class Lazy\n\n : public NonCopyable\n\n{\n\n public:\n\n // Object, lazy object and object factory types.\n\n typedef Object ObjectType;\n\n typedef Lazy<Object> LazyType;\n\n typedef ILazyFactory<Object> FactoryType;\n\n\n\n // Construct a lazy object with a factory to create the actual\n\n // object the first time it is accessed.\n\n explicit Lazy(std::unique_ptr<FactoryType> factory);\n\n\n\n // Construct a lazy object that simply wraps an existing source object,\n\n // effectively bypassing lazy object construction altogether.\n\n explicit Lazy(ObjectType* source_object);\n\n\n\n // Destructor, deletes the factory, as well as the object if\n\n // it is owned by the lazy object.\n\n ~Lazy();\n", "file_path": "src/appleseed/foundation/utility/lazy.h", "rank": 73, "score": 169089.53304161713 }, { "content": "class Half\n\n{\n\n public:\n\n // Constructors.\n\n Half(); // leave half value uninitialized\n\n Half(const float rhs); // allow implicit float-to-half conversion\n\n\n\n // Construct a half by directly specifying its bits.\n\n static Half from_bits(const std::uint16_t bits);\n\n\n\n // Get underlying bits.\n\n std::uint16_t bits() const;\n\n\n\n // Implicit float-to-half conversion via assignment.\n\n Half& operator=(const float rhs);\n\n\n\n // Implicit half-to-float conversion.\n\n operator float() const;\n\n\n\n private:\n", "file_path": "src/appleseed/foundation/math/half.h", "rank": 74, "score": 169089.53304161713 }, { "content": "class Access\n\n{\n\n public:\n\n // Object and lazy object types.\n\n typedef Object ObjectType;\n\n typedef Lazy<Object> LazyType;\n\n\n\n // Constructor, acquires access to a lazy object.\n\n explicit Access(LazyType* lazy = nullptr);\n\n\n\n // Copy constructor.\n\n Access(const Access& rhs);\n\n\n\n // Assignment operator.\n\n Access<Object>& operator=(const Access& rhs);\n\n\n\n // Destructor.\n\n ~Access();\n\n\n\n // Acquire access to another lazy object.\n", "file_path": "src/appleseed/foundation/utility/lazy.h", "rank": 75, "score": 169089.53304161713 }, { "content": "class GGXMDF\n\n{\n\n public:\n\n static float D(\n\n const Vector3f& m,\n\n const float alpha_x,\n\n const float alpha_y);\n\n\n\n static float G(\n\n const Vector3f& wi,\n\n const Vector3f& wo,\n\n const Vector3f& m,\n\n const float alpha_x,\n\n const float alpha_y);\n\n\n\n static float G1(\n\n const Vector3f& v,\n\n const Vector3f& m,\n\n const float alpha_x,\n\n const float alpha_y);\n", "file_path": "src/appleseed/foundation/math/microfacet.h", "rank": 76, "score": 169089.53304161713 }, { "content": "class CDF\n\n{\n\n public:\n\n typedef std::pair<Item, Weight> ItemWeightPair;\n\n\n\n // Constructor.\n\n CDF();\n\n\n\n // Return the number of items in the CDF.\n\n size_t size() const;\n\n\n\n // Return true if the CDF is empty.\n\n bool empty() const;\n\n\n\n // Return true if the CDF has at least one item with a positive weight.\n\n bool valid() const;\n\n\n\n // Return the sum of the weight of all inserted items.\n\n Weight weight() const;\n\n\n", "file_path": "src/appleseed/foundation/math/cdf.h", "rank": 77, "score": 169089.53304161713 }, { "content": "class Basis3\n\n{\n\n public:\n\n // Vector and basis types.\n\n typedef Vector<T, 3> VectorType;\n\n typedef Basis3<T> BasisType;\n\n\n\n // Constructors.\n\n#if APPLESEED_COMPILER_CXX_DEFAULTED_FUNCTIONS\n\n Basis3() = default; // leave all components uninitialized\n\n#else\n\n Basis3() {} // leave all components uninitialized\n\n#endif\n\n explicit Basis3(const VectorType& normal); // normal must be unit-length\n\n Basis3(\n\n const VectorType& normal, // must be unit-length\n\n const VectorType& u); // does not need to be unit-length\n\n Basis3(\n\n const VectorType& normal, // must be unit-length\n\n const VectorType& u, // must be unit-length\n", "file_path": "src/appleseed/foundation/math/basis.h", "rank": 78, "score": 169089.53304161713 }, { "content": "local void zip64local_putValue_inmemory OF((void* dest, ZPOS64_T x, int nbByte));\n", "file_path": "src/appleseed/foundation/utility/minizip/zip.c", "rank": 79, "score": 168773.7360755551 }, { "content": " class InnerIterator : public EvalIterator\n\n {\n\n public:\n\n EIGEN_STRONG_INLINE InnerIterator(const unary_evaluator& unaryOp, Index outer)\n\n : EvalIterator(unaryOp.m_argImpl,outer)\n\n {}\n\n \n\n Index row() const { return EvalIterator::col(); }\n\n Index col() const { return EvalIterator::row(); }\n\n };\n\n \n\n enum {\n\n CoeffReadCost = evaluator<ArgType>::CoeffReadCost,\n\n Flags = XprType::Flags\n\n };\n\n \n\n explicit unary_evaluator(const XprType& op) :m_argImpl(op.nestedExpression()) {}\n\n\n\n protected:\n\n evaluator<ArgType> m_argImpl;\n\n};\n\n\n\n} // end namespace internal\n\n\n\n} // end namespace Eigen\n\n\n\n#endif // EIGEN_SPARSETRANSPOSE_H\n", "file_path": "src/thirdparty/bcd/ext/eigen/Eigen/src/SparseCore/SparseTranspose.h", "rank": 80, "score": 168033.92660817137 }, { "content": "struct NoWaitPolicy\n\n{\n\n static void pause(const std::uint32_t iteration) {}\n\n};\n\n\n", "file_path": "src/appleseed/foundation/platform/thread.h", "rank": 81, "score": 167375.4719372841 }, { "content": "struct IsCopyable\n\n : public IsNotBase<NonCopyable, T>\n\n{\n\n};\n\n\n\n} // namespace foundation\n", "file_path": "src/appleseed/foundation/core/concepts/noncopyable.h", "rank": 82, "score": 167375.4719372841 }, { "content": " enum class SearchPathType { Environment, Explicit };\n\n}\n\n\n\nQ_DECLARE_METATYPE(SearchPathType);\n\n\n\nnamespace appleseed {\n\nnamespace studio {\n\n\n\n//\n\n// SearchPathsWindow class implementation.\n\n//\n\n\n\nnamespace\n\n{\n\n QListWidgetItem* make_item(const SearchPathType search_path_type, const QString& text = QString())\n\n {\n\n QListWidgetItem* item = new QListWidgetItem(text);\n\n\n\n item->setData(Qt::UserRole, QVariant::fromValue(search_path_type));\n\n item->setFlags(item->flags() | Qt::ItemIsEditable);\n", "file_path": "src/appleseed.studio/mainwindow/project/searchpathswindow.cpp", "rank": 83, "score": 167348.2382218006 }, { "content": " // Constant iterator.\n\n class const_iterator\n\n : public EntityMap::const_iterator\n\n {\n\n public:\n\n // Types.\n\n typedef T value_type;\n\n typedef const T& reference;\n\n typedef const T* pointer;\n\n\n\n // Constructor.\n\n const_iterator(const EntityMap::const_iterator& rhs);\n\n\n\n // Dereference operators.\n\n const value_type& operator*() const;\n\n const value_type* operator->() const;\n\n };\n\n\n\n // Constructor.\n\n explicit TypedEntityMap(Entity* parent = nullptr);\n\n\n", "file_path": "src/appleseed/renderer/modeling/entity/entitymap.h", "rank": 84, "score": 166011.21637481495 }, { "content": " // Constant iterator.\n\n class const_iterator\n\n : public EntityVector::const_iterator\n\n {\n\n public:\n\n // Value type.\n\n typedef T value_type;\n\n\n\n // Constructor.\n\n const_iterator(const EntityVector::const_iterator& rhs);\n\n\n\n // Dereference operators.\n\n const value_type& operator*() const;\n\n const value_type* operator->() const;\n\n };\n\n\n\n // Constructor.\n\n explicit TypedEntityVector(Entity* parent = nullptr);\n\n\n\n // Insert an entity into the container and return its index.\n\n size_t insert(foundation::auto_release_ptr<T> entity);\n", "file_path": "src/appleseed/renderer/modeling/entity/entityvector.h", "rank": 85, "score": 166011.21637481495 }, { "content": " class const_iterator\n\n {\n\n public:\n\n const_iterator();\n\n const_iterator(const scalar* i_pPixelDataPtr, int i_nbOfScalarsInPixelData);\n\n const scalar* operator*() const;\n\n const_iterator& operator++();\n\n const scalar& operator[](int i_dimensionIndex) const;\n\n bool operator!=(const const_iterator& i_rIt) const;\n\n\n\n private:\n\n const scalar* m_pCurrentPixelDataPtr;\n\n int m_nbOfScalarsInPixelData;\n\n };\n\n\n\n DeepImage();\n\n\n\n DeepImage(\n\n int i_width,\n\n int i_height,\n", "file_path": "src/thirdparty/bcd/bcd/DeepImage.h", "rank": 86, "score": 166011.21637481495 }, { "content": "// Exception thrown by the 'throw_otherwise' macro.\n\nclass SwitchException\n\n : public Exception\n\n{\n\n public:\n\n SwitchException()\n\n : Exception(\"unhandled case in switch statement\")\n\n {\n\n }\n\n};\n\n\n\n// Call assert() when reaching an unhandled case.\n\n#ifdef NDEBUG\n\n #define assert_otherwise \\\n\n default: \\\n\n APPLESEED_UNREACHABLE; \\\n\n break\n\n#else\n\n #define assert_otherwise \\\n\n default: \\\n\n assert(!\"Unhandled case in switch statement.\"); \\\n", "file_path": "src/appleseed/foundation/utility/otherwise.h", "rank": 87, "score": 166010.45773215606 }, { "content": "class AttributeSet\n\n : public NonCopyable\n\n{\n\n public:\n\n typedef size_t ChannelID;\n\n static const ChannelID InvalidChannelID = ~ChannelID(0);\n\n\n\n // Destructor.\n\n ~AttributeSet();\n\n\n\n // Create a new attribute channel.\n\n ChannelID create_channel(\n\n const std::string& name,\n\n const NumericTypeID type,\n\n const size_t dimension);\n\n\n\n // Delete an existing channel.\n\n void delete_channel(const ChannelID channel_id);\n\n\n\n // Find a given attribute channel. Return InvalidChannelID if\n", "file_path": "src/appleseed/foundation/utility/attributeset.h", "rank": 88, "score": 166003.08346373393 }, { "content": "class ZipException\n\n : public foundation::Exception\n\n{\n\n public:\n\n ZipException(const char* what);\n\n ZipException(const char* what, const int err);\n\n};\n\n\n\n//\n\n// Extracts zip file zipFilename to unzipped_dir directory.\n\n//\n\n// Throws ZipException in case of exception.\n\n// If exception is thrown, unzipped folder is deleted.\n\n//\n\n\n\nvoid unzip(const std::string& zip_filename, const std::string& unzipped_dir);\n\n\n\n//\n\n// Archives directory_to_zip to zip_filename zip file.\n\n//\n", "file_path": "src/appleseed/foundation/utility/zip.h", "rank": 89, "score": 166003.08346373393 }, { "content": "class LRUCache\n\n : public cache_impl::CacheBase\n\n{\n\n public:\n\n // Types.\n\n typedef Key KeyType;\n\n typedef KeyHasher KeyHasherType;\n\n typedef Element ElementType;\n\n typedef ElementSwapper ElementSwapperType;\n\n typedef Allocator AllocatorType;\n\n\n\n // Constructor.\n\n LRUCache(\n\n KeyHasherType& key_hasher,\n\n ElementSwapperType& element_swapper,\n\n AllocatorType allocator = AllocatorType());\n\n\n\n // Destructor.\n\n ~LRUCache();\n\n\n", "file_path": "src/appleseed/foundation/utility/cache.h", "rank": 90, "score": 166003.08346373393 }, { "content": "class StackWalker\n\n{\n\npublic:\n\n typedef enum StackWalkOptions\n\n {\n\n // No addition info will be retrived \n\n // (only the address is available)\n\n RetrieveNone = 0,\n\n \n\n // Try to get the symbol-name\n\n RetrieveSymbol = 1,\n\n \n\n // Try to get the line for this symbol\n\n RetrieveLine = 2,\n\n \n\n // Try to retrieve the module-infos\n\n RetrieveModuleInfo = 4,\n\n \n\n // Also retrieve the version for the DLL/EXE\n\n RetrieveFileVersion = 8,\n", "file_path": "src/appleseed/foundation/platform/win32stackwalker.h", "rank": 91, "score": 166003.08346373393 }, { "content": "class PoisonImpl\n\n{\n\n public:\n\n static void do_poison(T& x)\n\n {\n\n std::memset(&x, 0xADU, sizeof(x));\n\n }\n\n};\n\n\n\ntemplate <typename T>\n\ninline void always_poison(T& x)\n\n{\n\n PoisonImpl<T>::do_poison(x);\n\n}\n\n\n\ntemplate <typename T>\n\ninline void debug_poison(T& x)\n\n{\n\n#ifdef APPLESEED_DEBUG\n\n PoisonImpl<T>::do_poison(x);\n\n#endif\n\n}\n\n\n\ntemplate <typename T>\n", "file_path": "src/appleseed/foundation/utility/poison.h", "rank": 92, "score": 166003.08346373393 }, { "content": "class NumericType\n\n{\n\n public:\n\n // Return the ID of the type T. Attempting to get the ID of\n\n // an unsupported type will result in a compilation error.\n\n template <typename T> static NumericTypeID id();\n\n\n\n // Return the size in byte of a numeric type.\n\n // Return 0 if ID is not a valid numeric type.\n\n static size_t size(const NumericTypeID id);\n\n\n\n // Return the name of a type.\n\n // Return an empty string if ID is not a valid type.\n\n static const char* name(const NumericTypeID id);\n\n};\n\n\n\n\n\n//\n\n// NumericType class implementation.\n\n//\n", "file_path": "src/appleseed/foundation/utility/numerictype.h", "rank": 93, "score": 166003.08346373393 }, { "content": "class XMLElement\n\n{\n\n public:\n\n // Constructor, opens the element.\n\n XMLElement(\n\n const std::string& name,\n\n std::FILE* file,\n\n Indenter& indenter);\n\n\n\n // Destructor, closes the element.\n\n ~XMLElement();\n\n\n\n // Append an attribute to the element.\n\n template <typename T>\n\n void add_attribute(\n\n const std::string& name,\n\n const T& value);\n\n\n\n enum ContentType\n\n {\n", "file_path": "src/appleseed/foundation/utility/xmlelement.h", "rank": 94, "score": 166003.08346373393 }, { "content": "class SACache\n\n : public cache_impl::CacheBase\n\n{\n\n public:\n\n // Types.\n\n typedef Key KeyType;\n\n typedef KeyHasher KeyHasherType;\n\n typedef Element ElementType;\n\n typedef ElementSwapper ElementSwapperType;\n\n\n\n // Line and way count.\n\n static const size_t Lines = Lines_;\n\n static const size_t Ways = Ways_;\n\n\n\n // Constructor.\n\n SACache(\n\n KeyHasherType& key_hasher,\n\n ElementSwapperType& element_swapper,\n\n const KeyType& invalid_key);\n\n\n", "file_path": "src/appleseed/foundation/utility/cache.h", "rank": 95, "score": 166003.08346373393 }, { "content": " class CacheBase\n\n : public NonCopyable\n\n {\n\n public:\n\n // Constructor.\n\n CacheBase()\n\n {\n\n clear_statistics();\n\n }\n\n\n\n // Reset the cache performance statistics.\n\n void clear_statistics()\n\n {\n\n m_hit_count = 0;\n\n m_miss_count = 0;\n\n }\n\n\n\n // Return the number of cache hits.\n\n std::uint64_t get_hit_count() const\n\n {\n", "file_path": "src/appleseed/foundation/utility/cache.h", "rank": 96, "score": 166003.08346373393 }, { "content": "class SharedLibrary\n\n : public NonCopyable\n\n{\n\n public:\n\n // Return the OS' default file extension for shared libraries.\n\n static const char* get_default_file_extension();\n\n\n\n // Constructor.\n\n explicit SharedLibrary(const char* path);\n\n\n\n // Destructor.\n\n ~SharedLibrary();\n\n\n\n // Get a symbol from the shared library.\n\n void* get_symbol(const char* name, const bool no_throw = true) const;\n\n\n\n private:\n\n#ifdef _WIN32\n\n HMODULE m_handle;\n\n#else\n\n void* m_handle;\n\n#endif\n\n};\n\n\n\n} // namespace foundation\n", "file_path": "src/appleseed/foundation/platform/sharedlibrary.h", "rank": 97, "score": 166003.08346373393 }, { "content": "class BitMask2\n\n{\n\n public:\n\n // The constructor does not initialize the content of the bit mask.\n\n BitMask2(\n\n const size_t width,\n\n const size_t height);\n\n\n\n ~BitMask2();\n\n\n\n size_t get_width() const;\n\n size_t get_height() const;\n\n\n\n void clear();\n\n\n\n void clear(\n\n const size_t x,\n\n const size_t y);\n\n\n\n void set(\n", "file_path": "src/appleseed/foundation/utility/bitmask.h", "rank": 98, "score": 166003.08346373393 }, { "content": "#include \"foundation/platform/_beginexrheaders.h\"\n\n#include \"OpenEXR/ImathColor.h\"\n\n#include \"foundation/platform/_endexrheaders.h\"\n\n#endif\n\n\n\n// Standard headers.\n\n#include <algorithm>\n\n#include <cassert>\n\n#include <cmath>\n\n#include <cstddef>\n\n#include <cstdint>\n\n\n\nnamespace foundation\n\n{\n\n\n\n//\n\n// N-dimensional color class and operations.\n\n//\n\n\n\ntemplate <typename T, size_t N>\n", "file_path": "src/appleseed/foundation/image/color.h", "rank": 99, "score": 47.82041759664145 } ]
C++
apps/vdcwizard/dataholder.cpp
yyr/vapor
cdebac81212ffa3f811064bbd7625ffa9089782e
#include <stdlib.h> #include <stdio.h> #include <sstream> #include <iterator> #include <cstdio> #include <QDebug> #include <QString> #include <vapor/WrfVDFcreator.h> #include <vapor/vdfcreate.h> #include <vapor/Copy2VDF.h> #include <vapor/MetadataVDC.h> #include <vapor/WaveCodecIO.h> #include <vapor/DCReader.h> #include <vapor/DCReaderGRIB.h> #include <vapor/DCReaderMOM.h> #include <vapor/DCReaderROMS.h> #include <vapor/DCReaderWRF.h> #include <vapor/WrfVDCcreator.h> #include "dataholder.h" using namespace VAPoR; vector<const char*> errors; void ErrMsgCBHandler(const char* error, int){ errors.push_back(error); } vector<const char*> DataHolder::getErrors() { return errors; } void DataHolder::clearErrors() { errors.clear(); } DataHolder::DataHolder(){ MyBase::SetErrMsgCB(ErrMsgCBHandler); VDFstartTime = "0"; PDstartTime = "0"; reader = NULL; ncdfFilesChanged = true; vdfSettingsChanged = true; vdcSettingsChanged = true; } DataHolder::~DataHolder(){ } void DataHolder::deleteReader() { if (reader) delete reader; reader = NULL; } void DataHolder::getExtents(){ reader->GetLatLonExtents(0,lonExtents,latExtents); for (size_t i=1;i<atoi(VDFnumTS.c_str());i++){ double lonBuffer[2]; double latBuffer[2]; reader->GetLatLonExtents(i,lonBuffer,latBuffer); if (latBuffer[0]<latExtents[0]) latExtents[0]=latBuffer[0]; if (latBuffer[1]>latExtents[1]) latExtents[1]=latBuffer[1]; if (lonBuffer[0]<lonExtents[0]) lonExtents[0]=lonBuffer[0]; if (lonBuffer[1]>lonExtents[1]) lonExtents[1]=lonBuffer[1]; } } void DataHolder::setVDFstartTime(string startTime) { VDFstartTime = startTime; vdfSettingsChanged = true; } void DataHolder::setVDFnumTS(string numTS) { VDFnumTS = numTS; vdfSettingsChanged = true; } void DataHolder::setVDFDisplayedVars(vector<string> selectedVars) { VDFDisplayedVars = selectedVars; vdfSettingsChanged = true; } void DataHolder::setVDFSelectedVars(vector<string> selectedVars) { if (VDFSelectedVars != selectedVars) vdfSettingsChanged = true; VDFSelectedVars = selectedVars; } void DataHolder::addVDFDisplayedVar(string var) { VDFDisplayedVars.push_back(var); vdfSettingsChanged = true; } void DataHolder::addVDFSelectedVar(string var) { VDFSelectedVars.push_back(var); vdfSettingsChanged = true; } void DataHolder::deleteVDFSelectedVar(string var) { for (int i=0;i<VDFSelectedVars.size();i++) { if (VDFSelectedVars[i] == var) VDFSelectedVars.erase(VDFSelectedVars.begin()+i); } vdfSettingsChanged = true; } void DataHolder::clearVDFSelectedVars() { VDFSelectedVars.clear(); vdfSettingsChanged = true; } int DataHolder::createReader() { if (reader==NULL){ if (fileType == "ROMS") reader = new DCReaderROMS(dataFiles); else if (fileType == "CAM") reader = new DCReaderROMS(dataFiles); else if (fileType == "GRIB") reader = new DCReaderGRIB(dataFiles); else if (fileType == "WRF") reader = new DCReaderWRF(dataFiles); else reader = new DCReaderMOM(dataFiles); if (MyBase::GetErrCode()!=0) return 1; std::stringstream strstream; strstream << reader->GetNumTimeSteps(); strstream >> VDFnumTS; setPDnumTS(VDFnumTS); ncdfVars = reader->GetVariableNames(); std::sort(ncdfVars.begin(),ncdfVars.end()); if (MyBase::GetErrCode()!=0) return 1; } return 0; } void DataHolder::findPopDataVars() { VDFIOBase *vdfio = NULL; WaveCodecIO *wcwriter = NULL; MetadataVDC metadata(getPDinputVDFfile()); wcwriter = new WaveCodecIO(metadata,1); vdfio = wcwriter; vector<string> emptyVars; vector<string> outVars; launcher2VDF.GetVariables(vdfio, reader, emptyVars, outVars); std::sort(outVars.begin(),outVars.end()); setPDDisplayedVars(outVars); delete wcwriter; } string DataHolder::getCreateVDFcmd() { vector<std::string> argv; if (getFileType() == "ROMS") argv.push_back("romsvdfcreate"); else if (getFileType() == "CAM") argv.push_back("camvdfcreate"); else if (getFileType() == "WRF") argv.push_back("wrfvdfcreate"); else if (getFileType() == "GRIB") argv.push_back("gribvdfcreate"); else argv.push_back("momvdfcreate"); argv.push_back("-quiet"); if (getFileType()=="WRF") argv.push_back("-vdc2"); if (VDFSBFactor != "") { argv.push_back("-bs"); argv.push_back(VDFSBFactor); } if (VDFcomment != "") { argv.push_back("-comment"); argv.push_back(VDFcomment); } if (VDFcrList != "") { argv.push_back("-cratios"); argv.push_back(VDFcrList); } if (VDFPeriodicity != "") { argv.push_back("-periodic"); argv.push_back(VDFPeriodicity); } if (VDFSelectedVars.size() != 0) { argv.push_back("-vars"); string stringVars; for(vector<string>::iterator it = VDFSelectedVars.begin(); it != VDFSelectedVars.end(); ++it) { if(it != VDFSelectedVars.begin()) stringVars += ":"; stringVars += *it; } argv.push_back(stringVars); } for (int i=0;i<dataFiles.size();i++){ argv.push_back(dataFiles.at(i)); } if (VDFfileName != "") { argv.push_back(VDFfileName); } std::ostringstream imploded; const char* const delim = " "; std::copy(argv.begin(), argv.end(),std::ostream_iterator<string>(imploded,delim)); return imploded.str(); } string DataHolder::getPopDataCmd() { vector<std::string> argv; if (getFileType() == "ROMS") argv.push_back("roms2vdf"); else if (getFileType() == "GRIB") argv.push_back("grib2vdf"); else if (getFileType() == "CAM") argv.push_back("cam2vdf"); else if (getFileType() == "WRF") argv.push_back("wrf2vdf"); else argv.push_back("mom2vdf"); argv.push_back("-quiet"); if (PDrefinement != "") { argv.push_back("-level"); argv.push_back(PDrefinement); } if (PDcompression != "") { argv.push_back("-lod"); argv.push_back(PDcompression); } if (PDnumThreads != "") { argv.push_back("-nthreads"); argv.push_back(PDnumThreads); } if (getFileType() != "GRIB") { argv.push_back("-numts"); argv.push_back(PDnumTS); argv.push_back("-startts"); argv.push_back(PDstartTime); } if (PDSelectedVars.size() != 0) { argv.push_back("-vars"); if (getFileType()!="MOM"){ if (std::find(PDSelectedVars.begin(), PDSelectedVars.end(), "ELEVATION") == PDSelectedVars.end()) { PDSelectedVars.push_back("ELEVATION"); } } string stringVars; for(vector<string>::iterator it = PDSelectedVars.begin(); it != PDSelectedVars.end(); ++it) { if(it != PDSelectedVars.begin()) stringVars += ":"; stringVars += *it; } argv.push_back(stringVars); } if (getFileType()=="WRF"){ argv.push_back(PDinputVDFfile); } for (int i=0;i<dataFiles.size();i++){ argv.push_back(dataFiles.at(i)); } if (getFileType() != "WRF"){ argv.push_back(PDinputVDFfile); } char** args = new char*[ argv.size() + 1 ]; for(size_t a=0; a<argv.size(); a++) { args[a] = strdup(argv[a].c_str()); } std::ostringstream imploded; const char* const delim = " "; std::copy(argv.begin(), argv.end(), std::ostream_iterator<string>(imploded,delim)); return imploded.str(); } int DataHolder::VDFCreate() { int argc = 2; vector<std::string> argv; if (getFileType() == "ROMS") argv.push_back("romsvdfcreate"); else if (getFileType() == "CAM") argv.push_back("camvdfcreate"); else if (getFileType() == "GRIB") argv.push_back("gribvdfcreate"); else if (getFileType() == "WRF") argv.push_back("wrfvdfcreate"); else argv.push_back("momvdfcreate"); argv.push_back("-quiet"); if (getFileType() == "WRF") { argv.push_back("-vdc2"); argc++; } if (VDFSBFactor != "") { argv.push_back("-bs"); argv.push_back(VDFSBFactor); argc+=2; } if (VDFcomment != "") { argv.push_back("-comment"); argv.push_back(VDFcomment); argc+=2; } if (VDFcrList != "") { argv.push_back("-cratios"); argv.push_back(VDFcrList); argc+=2; } if (VDFPeriodicity != "") { argv.push_back("-periodic"); argv.push_back(VDFPeriodicity); argc+=2; } if (VDFSelectedVars.size() != 0) { argv.push_back("-vars"); argc++; if (getFileType()!="MOM"){ if (std::find(PDSelectedVars.begin(), PDSelectedVars.end(), "ELEVATION") == PDSelectedVars.end()) { PDSelectedVars.push_back("ELEVATION"); } } string stringVars; for(vector<string>::iterator it = VDFSelectedVars.begin(); it != VDFSelectedVars.end(); ++it) { if(it != VDFSelectedVars.begin()) stringVars += ":"; stringVars += *it; } argv.push_back(stringVars); argc++; } for (int i=0;i<dataFiles.size();i++){ argv.push_back(dataFiles.at(i)); argc++; } if (VDFfileName != "") { argv.push_back(VDFfileName); argc++; } char** args = new char*[ argv.size() + 1 ]; for(size_t a=0; a<argv.size(); a++) { args[a] = strdup(argv[a].c_str()); } if (getFileType()=="WRF") { wrfvdfcreate launcherWrfVdfCreate; int rc = launcherWrfVdfCreate.launchVdfCreate(argc,args); return rc; } else return launcherVdfCreate.launchVdfCreate(argc,args,getFileType()); } int DataHolder::run2VDFcomplete() { int argc = 2; vector<std::string> argv; if (getFileType() == "ROMS") argv.push_back("roms2vdf"); else if (getFileType() == "CAM") argv.push_back("cam2vdf"); else if (getFileType() == "GRIB") argv.push_back("grib2vdf"); else if (getFileType() == "WRF") argv.push_back("wrf2vdf"); else argv.push_back("mom2vdf"); argv.push_back("-quiet"); if (PDrefinement != "") { argv.push_back("-level"); argv.push_back(PDrefinement); argc+=2; } if (PDcompression != "") { argv.push_back("-lod"); argv.push_back(PDcompression); argc+=2; } if (PDnumThreads != "") { argv.push_back("-nthreads"); argv.push_back(PDnumThreads); argc+=2; } if (getFileType() != "GRIB") { if (PDnumTS != "") { argv.push_back("-numts"); argv.push_back(PDnumTS); argc+=2; } if (PDstartTime != "") { argv.push_back("-startts"); argv.push_back(PDstartTime); argc+=2; } } if (PDSelectedVars.size() != 0) { argv.push_back("-vars"); argc++; if (getFileType()!="MOM"){ if (std::find(PDSelectedVars.begin(), PDSelectedVars.end(), "ELEVATION") == PDSelectedVars.end()) { PDSelectedVars.push_back("ELEVATION"); } } string stringVars; for(vector<string>::iterator it = PDSelectedVars.begin(); it != PDSelectedVars.end(); ++it) { if(it != PDSelectedVars.begin()) stringVars += ":"; stringVars += *it; } argv.push_back(stringVars); argc++; } for (int i=0;i<dataFiles.size();i++){ argv.push_back(dataFiles.at(i)); argc++; } argv.push_back(PDinputVDFfile); argc++; char** args = new char*[ argv.size() + 1 ]; for(size_t a=0; a<argv.size(); a++) { args[a] = strdup(argv[a].c_str()); } return launcher2VDF.launch2vdf(argc, args, getFileType(), reader); } int DataHolder::run2VDFincremental(string start, string var) { int argc = 2; vector<std::string> argv; if (getFileType() == "ROMS") argv.push_back("roms2vdf"); else if (getFileType() == "CAM") argv.push_back("cam2vdf"); else if (getFileType() == "GRIB") argv.push_back("grib2vdf"); else if (getFileType() == "WRF") argv.push_back("wrf2vdf"); else argv.push_back("mom2vdf"); argv.push_back("-quiet"); if (PDrefinement != "") { argv.push_back("-level"); argv.push_back(PDrefinement); argc+=2; } if (PDcompression != "") { argv.push_back("-lod"); argv.push_back(PDcompression); argc+=2; } if (PDnumThreads != "") { argv.push_back("-nthreads"); argv.push_back(PDnumThreads); argc+=2; } if (getFileType() != "GRIB") { argv.push_back("-numts"); argv.push_back("1"); argc+=2; argv.push_back("-startts"); argv.push_back(start); argc+=2; } argv.push_back("-vars"); argc++; argv.push_back(var); argc++; if (getFileType()=="WRF"){ argv.push_back(PDinputVDFfile); argc++; } for (int i=0;i<dataFiles.size();i++){ argv.push_back(dataFiles.at(i)); argc++; } if (getFileType() != "WRF"){ argv.push_back(PDinputVDFfile); argc++; } char** args = new char*[ argv.size() + 1 ]; for(size_t a=0; a<argv.size(); a++) { args[a] = strdup(argv[a].c_str()); } int rc; if (getFileType()=="WRF") { rc = w2v.launchWrf2Vdf(argc, args, (DCReaderWRF*) reader); } else { rc = launcher2VDF.launch2vdf(argc, args, getFileType(), reader); } if (args) delete [] args; return rc; } void DataHolder::purgeObjects() { launcher2VDF.deleteObjects(); w2v.deleteObjects(); }
#include <stdlib.h> #include <stdio.h> #include <sstream> #include <iterator> #include <cstdio> #include <QDebug> #include <QString> #include <vapor/WrfVDFcreator.h> #include <vapor/vdfcreate.h> #include <vapor/Copy2VDF.h> #include <vapor/MetadataVDC.h> #include <vapor/WaveCodecIO.h> #include <vapor/DCReader.h> #include <vapor/DCReaderGRIB.h> #include <vapor/DCReaderMOM.h> #include <vapor/DCReaderROMS.h> #include <vapor/DCReaderWRF.h> #include <vapor/WrfVDCcreator.h> #include "dataholder.h" using namespace VAPoR; vector<const char*> errors; void ErrMsgCBHandler(const char* error, int){ errors.push_back(error); } vector<const char*> DataHolder::getErrors() { return errors; } void DataHolder::clearErrors() { errors.clear(); } DataHolder::DataHolder(){ MyBase::SetErrMsgCB(ErrMsgCBHandler); VDFstartTime = "0"; PDstartTime = "0"; reader = NULL; ncdfFilesChanged = true; vdfSettingsChanged = true; vdcSettingsChanged = true; } DataHolder::~DataHolder(){ } void DataHolder::deleteReader() { if (reader) delete reader; reader = NULL; } void DataHolder::getExtents(){ reader->GetLatLonExtents(0,lonExtents,latExtents); for (size_t i=1;i<atoi(VDFnumTS.c_str());i++){ double lonBuffer[2]; double latBuffer[2]; reader->GetLatLonExtents(i,lonBuffer,latBuffer); if (latBuffer[0]<latExtents[0]) latExtents[0]=latBuffer[0]; if (latBuffer[1]>latExtents[1]) latExtents[1]=latBuffer[1]; if (lonBuffer[0]<lonExtents[0]) lonExtents[0]=lonBuffer[0]; if (lonBuffer[1]>lonExtents[1]) lonExtents[1]=lonBuffer[1]; } } void DataHolder::setVDFstartTime(string startTime) { VDFstartTime = startTime; vdfSettingsChanged = true; } void DataHolder::setVDFnumTS(string numTS) { VDFnumTS = numTS; vdfSettingsChanged = true; } void DataHolder::setVDFDisplayedVars(vector<string> selectedVars) { VDFDisplayedVars = selectedVars; vdfSettingsChanged = true; } void DataHolder::setVDFSelectedVars(vector<string> selectedVars) { if (VDFSelectedVars != selectedVars) vdfSettingsChanged = true; VDFSelectedVars = selectedVars; } void DataHolder::addVDFDisplayedVar(string var) { VDFDisplayedVars.push_back(var); vdfSettingsChanged = true; } void DataHolder::addVDFSelectedVar(string var) { VDFSelectedVars.push_back(var); vdfSettingsChanged = true; } void DataHolder::deleteVDFSelectedVar(string var) { for (int i=0;i<VDFSelectedVars.size();i++) { if (VDFSelectedVars[i] == var) VDFSelectedVars.erase(VDFSelectedVars.begin()+i); } vdfSettingsChanged = true; } void DataHolder::clearVDFSelectedVars() { VDFSelectedVars.clear(); vdfSettingsChanged = true; } int DataHolder::createReader() { if (reader==NULL){ if (fileType == "ROMS") reader = new DCReaderROMS(dataFiles); else if (fileType == "CAM") reader = new DCReaderROMS(dataFiles); else if (fileType == "GRIB") reader = new DCReaderGRIB(dataFiles); else if (fileType == "WRF") reader = new DCReaderWRF(dataFiles); else reader = new DCReaderMOM(dataFiles); if (MyBase::GetErrCode()!=0) return 1; std::stringstream strstream; strstream << reader->GetNumTimeSteps(); strstream >> VDFnumTS; setPDnumTS(VDFnumTS); ncdfVars = reader->GetVariableNames(); std::sort(ncdfVars.begin(),ncdfVars.end()); if (MyBase::GetErrCode()!=0) return 1; } return 0; } void DataHolder::findPopDataVars() { VDFIOBase *vdfio = NULL; WaveCodecIO *wcwriter = NULL; MetadataVDC metadata(getPDinputVDFfile()); wcwriter = new WaveCodecIO(metadata,1); vdfio = wcwriter; vector<string> emptyVars; vector<string> outVars; launcher2VDF.GetVariables(vdfio, reader, emptyVars, outVars); std::sort(outVars.begin(),outVars.end()); setPDDisplayedVars(outVars); delete wcwriter; } string DataHolder::getCreateVDFcmd() { vector<std::string> argv; if (getFileType() == "ROMS") argv.push_back("romsvdfcreate"); else if (getFileType() == "CAM") argv.push_back("camvdfcreate"); else if (getFileType() == "WRF") argv.push_back("wrfvdfcreate"); else if (getFileType() == "GRIB") argv.push_back("gribvdfcreate"); else argv.push_back("momvdfcreate"); argv.push_back("-quiet"); if (getFileTyp
string DataHolder::getPopDataCmd() { vector<std::string> argv; if (getFileType() == "ROMS") argv.push_back("roms2vdf"); else if (getFileType() == "GRIB") argv.push_back("grib2vdf"); else if (getFileType() == "CAM") argv.push_back("cam2vdf"); else if (getFileType() == "WRF") argv.push_back("wrf2vdf"); else argv.push_back("mom2vdf"); argv.push_back("-quiet"); if (PDrefinement != "") { argv.push_back("-level"); argv.push_back(PDrefinement); } if (PDcompression != "") { argv.push_back("-lod"); argv.push_back(PDcompression); } if (PDnumThreads != "") { argv.push_back("-nthreads"); argv.push_back(PDnumThreads); } if (getFileType() != "GRIB") { argv.push_back("-numts"); argv.push_back(PDnumTS); argv.push_back("-startts"); argv.push_back(PDstartTime); } if (PDSelectedVars.size() != 0) { argv.push_back("-vars"); if (getFileType()!="MOM"){ if (std::find(PDSelectedVars.begin(), PDSelectedVars.end(), "ELEVATION") == PDSelectedVars.end()) { PDSelectedVars.push_back("ELEVATION"); } } string stringVars; for(vector<string>::iterator it = PDSelectedVars.begin(); it != PDSelectedVars.end(); ++it) { if(it != PDSelectedVars.begin()) stringVars += ":"; stringVars += *it; } argv.push_back(stringVars); } if (getFileType()=="WRF"){ argv.push_back(PDinputVDFfile); } for (int i=0;i<dataFiles.size();i++){ argv.push_back(dataFiles.at(i)); } if (getFileType() != "WRF"){ argv.push_back(PDinputVDFfile); } char** args = new char*[ argv.size() + 1 ]; for(size_t a=0; a<argv.size(); a++) { args[a] = strdup(argv[a].c_str()); } std::ostringstream imploded; const char* const delim = " "; std::copy(argv.begin(), argv.end(), std::ostream_iterator<string>(imploded,delim)); return imploded.str(); } int DataHolder::VDFCreate() { int argc = 2; vector<std::string> argv; if (getFileType() == "ROMS") argv.push_back("romsvdfcreate"); else if (getFileType() == "CAM") argv.push_back("camvdfcreate"); else if (getFileType() == "GRIB") argv.push_back("gribvdfcreate"); else if (getFileType() == "WRF") argv.push_back("wrfvdfcreate"); else argv.push_back("momvdfcreate"); argv.push_back("-quiet"); if (getFileType() == "WRF") { argv.push_back("-vdc2"); argc++; } if (VDFSBFactor != "") { argv.push_back("-bs"); argv.push_back(VDFSBFactor); argc+=2; } if (VDFcomment != "") { argv.push_back("-comment"); argv.push_back(VDFcomment); argc+=2; } if (VDFcrList != "") { argv.push_back("-cratios"); argv.push_back(VDFcrList); argc+=2; } if (VDFPeriodicity != "") { argv.push_back("-periodic"); argv.push_back(VDFPeriodicity); argc+=2; } if (VDFSelectedVars.size() != 0) { argv.push_back("-vars"); argc++; if (getFileType()!="MOM"){ if (std::find(PDSelectedVars.begin(), PDSelectedVars.end(), "ELEVATION") == PDSelectedVars.end()) { PDSelectedVars.push_back("ELEVATION"); } } string stringVars; for(vector<string>::iterator it = VDFSelectedVars.begin(); it != VDFSelectedVars.end(); ++it) { if(it != VDFSelectedVars.begin()) stringVars += ":"; stringVars += *it; } argv.push_back(stringVars); argc++; } for (int i=0;i<dataFiles.size();i++){ argv.push_back(dataFiles.at(i)); argc++; } if (VDFfileName != "") { argv.push_back(VDFfileName); argc++; } char** args = new char*[ argv.size() + 1 ]; for(size_t a=0; a<argv.size(); a++) { args[a] = strdup(argv[a].c_str()); } if (getFileType()=="WRF") { wrfvdfcreate launcherWrfVdfCreate; int rc = launcherWrfVdfCreate.launchVdfCreate(argc,args); return rc; } else return launcherVdfCreate.launchVdfCreate(argc,args,getFileType()); } int DataHolder::run2VDFcomplete() { int argc = 2; vector<std::string> argv; if (getFileType() == "ROMS") argv.push_back("roms2vdf"); else if (getFileType() == "CAM") argv.push_back("cam2vdf"); else if (getFileType() == "GRIB") argv.push_back("grib2vdf"); else if (getFileType() == "WRF") argv.push_back("wrf2vdf"); else argv.push_back("mom2vdf"); argv.push_back("-quiet"); if (PDrefinement != "") { argv.push_back("-level"); argv.push_back(PDrefinement); argc+=2; } if (PDcompression != "") { argv.push_back("-lod"); argv.push_back(PDcompression); argc+=2; } if (PDnumThreads != "") { argv.push_back("-nthreads"); argv.push_back(PDnumThreads); argc+=2; } if (getFileType() != "GRIB") { if (PDnumTS != "") { argv.push_back("-numts"); argv.push_back(PDnumTS); argc+=2; } if (PDstartTime != "") { argv.push_back("-startts"); argv.push_back(PDstartTime); argc+=2; } } if (PDSelectedVars.size() != 0) { argv.push_back("-vars"); argc++; if (getFileType()!="MOM"){ if (std::find(PDSelectedVars.begin(), PDSelectedVars.end(), "ELEVATION") == PDSelectedVars.end()) { PDSelectedVars.push_back("ELEVATION"); } } string stringVars; for(vector<string>::iterator it = PDSelectedVars.begin(); it != PDSelectedVars.end(); ++it) { if(it != PDSelectedVars.begin()) stringVars += ":"; stringVars += *it; } argv.push_back(stringVars); argc++; } for (int i=0;i<dataFiles.size();i++){ argv.push_back(dataFiles.at(i)); argc++; } argv.push_back(PDinputVDFfile); argc++; char** args = new char*[ argv.size() + 1 ]; for(size_t a=0; a<argv.size(); a++) { args[a] = strdup(argv[a].c_str()); } return launcher2VDF.launch2vdf(argc, args, getFileType(), reader); } int DataHolder::run2VDFincremental(string start, string var) { int argc = 2; vector<std::string> argv; if (getFileType() == "ROMS") argv.push_back("roms2vdf"); else if (getFileType() == "CAM") argv.push_back("cam2vdf"); else if (getFileType() == "GRIB") argv.push_back("grib2vdf"); else if (getFileType() == "WRF") argv.push_back("wrf2vdf"); else argv.push_back("mom2vdf"); argv.push_back("-quiet"); if (PDrefinement != "") { argv.push_back("-level"); argv.push_back(PDrefinement); argc+=2; } if (PDcompression != "") { argv.push_back("-lod"); argv.push_back(PDcompression); argc+=2; } if (PDnumThreads != "") { argv.push_back("-nthreads"); argv.push_back(PDnumThreads); argc+=2; } if (getFileType() != "GRIB") { argv.push_back("-numts"); argv.push_back("1"); argc+=2; argv.push_back("-startts"); argv.push_back(start); argc+=2; } argv.push_back("-vars"); argc++; argv.push_back(var); argc++; if (getFileType()=="WRF"){ argv.push_back(PDinputVDFfile); argc++; } for (int i=0;i<dataFiles.size();i++){ argv.push_back(dataFiles.at(i)); argc++; } if (getFileType() != "WRF"){ argv.push_back(PDinputVDFfile); argc++; } char** args = new char*[ argv.size() + 1 ]; for(size_t a=0; a<argv.size(); a++) { args[a] = strdup(argv[a].c_str()); } int rc; if (getFileType()=="WRF") { rc = w2v.launchWrf2Vdf(argc, args, (DCReaderWRF*) reader); } else { rc = launcher2VDF.launch2vdf(argc, args, getFileType(), reader); } if (args) delete [] args; return rc; } void DataHolder::purgeObjects() { launcher2VDF.deleteObjects(); w2v.deleteObjects(); }
e()=="WRF") argv.push_back("-vdc2"); if (VDFSBFactor != "") { argv.push_back("-bs"); argv.push_back(VDFSBFactor); } if (VDFcomment != "") { argv.push_back("-comment"); argv.push_back(VDFcomment); } if (VDFcrList != "") { argv.push_back("-cratios"); argv.push_back(VDFcrList); } if (VDFPeriodicity != "") { argv.push_back("-periodic"); argv.push_back(VDFPeriodicity); } if (VDFSelectedVars.size() != 0) { argv.push_back("-vars"); string stringVars; for(vector<string>::iterator it = VDFSelectedVars.begin(); it != VDFSelectedVars.end(); ++it) { if(it != VDFSelectedVars.begin()) stringVars += ":"; stringVars += *it; } argv.push_back(stringVars); } for (int i=0;i<dataFiles.size();i++){ argv.push_back(dataFiles.at(i)); } if (VDFfileName != "") { argv.push_back(VDFfileName); } std::ostringstream imploded; const char* const delim = " "; std::copy(argv.begin(), argv.end(),std::ostream_iterator<string>(imploded,delim)); return imploded.str(); }
function_block-function_prefixed
[ { "content": " class DerivedVarElevation : public NetCDFCollection::DerivedVar {\n\n public:\n\n DerivedVarElevation(\n\n NetCDFCollection *ncdfcf, float grav\n\n );\n\n virtual ~DerivedVarElevation();\n\n\n\n virtual int Open(size_t ts);\n\n virtual int ReadSlice(float *slice, int );\n\n virtual int Read(float *buf, int );\n\n virtual int SeekSlice(int offset, int whence, int );\n\n virtual int Close(int fd);\n\n virtual bool TimeVarying() const {return(true); };\n\n virtual std::vector <size_t> GetSpatialDims() const { return(_dims); }\n\n virtual std::vector <string> GetSpatialDimNames() const { return(_dimnames); }\n\n virtual size_t GetTimeDim() const { return(_num_ts); }\n\n virtual string GetTimeDimName() const { return(\"Time\"); };\n\n virtual bool GetMissingValue(double &mv) const {mv=0.0; return(false); }\n\n\n\n private:\n", "file_path": "include/vapor/DCReaderWRF.h", "rank": 0, "score": 281960.3632253658 }, { "content": "int grib_iterator_delete(grib_iterator *i)\n\n{\n\n grib_iterator_class *c = i->cclass;\n\n while(c)\n\n {\n\n grib_iterator_class *s = c->super ? *(c->super) : NULL;\n\n if(c->destroy) c->destroy(i);\n\n c = s;\n\n }\n\n /* This should go in a top class */\n\n grib_context_free(i->h->context,i);\n\n return 0;\n", "file_path": "lib/gribapi/grib_iterator.c", "rank": 1, "score": 256900.09728256217 }, { "content": "//\n\n// $Id$\n\n//\n\n\n\n\n\n#ifndef\t_DCReaderROMS_h_\n\n#define\t_DCReaderROMS_h_\n\n\n\n#include <vector>\n\n#include <cassert>\n\n#include <vapor/NetCDFCFCollection.h>\n\n#include <vapor/DCReaderNCDF.h>\n\n#include <vapor/WeightTable.h>\n\n#ifdef WIN32\n\n#pragma warning(disable : 4251)\n\n#endif\n\n\n\nnamespace VAPoR {\n\n\n\n//\n\n//! \\class DCReaderROMS\n\n//! \\brief ???\n\n//!\n\n//! \\author John Clyne\n\n//! \\version $Revision$\n\n//! \\date $Date$\n\n//!\n\n//!\n", "file_path": "include/vapor/DCReaderROMS.h", "rank": 2, "score": 256636.10244938926 }, { "content": " void _InitDimensions(\n\n NetCDFCFCollection *ncdfc,\n\n vector <size_t> &dims,\n\n vector <string> &vars3d,\n\n vector <string> &vars2dxy\n\n );\n\n //\n\n // Convert horizontal extents expressed in lat-lon to Cartesian\n\n // coordinates in whatever units the vertical coordinate is\n\n // expressed in.\n\n //\n\n int _InitCartographicExtents(\n\n\tstring mapProj,\n\n\tconst double lonExts[2],\n\n\tconst double latExts[2],\n\n\tconst std::vector <double> vertCoordinates,\n\n\tstd::vector <double> &extents\n\n ) const;\n\n\n\n float *_get_2d_var(NetCDFCFCollection *ncdfc, size_t ts, string name) const;\n\n float *_get_1d_var(NetCDFCFCollection *ncdfc, size_t ts, string name) const;\n\n\n\n \n\n\n\n};\n\n};\n\n\n\n#endif\t//\t_DCReaderROMS_h_\n", "file_path": "include/vapor/DCReaderROMS.h", "rank": 3, "score": 256629.02972639006 }, { "content": "\n\n virtual int CloseVariable();\n\n\n\n virtual int ReadSlice(float *slice);\n\n\n\n virtual int Read(float *data);\n\n\n\n virtual bool VariableExists(size_t ts, string varname, int i0=0, int i1=0) const {\n\n\tif (IsVariableDerived(varname)) return (true);\n\n return(_ncdfc->VariableExists(ts, varname));\n\n }\n\n\n\n virtual bool IsVariableDerived(string varname) const {\n\n\treturn(find(_varsDerived.begin(), _varsDerived.end(), varname) != _varsDerived.end());\n\n }\n\n\n\n virtual void GetLatLonExtents(\n\n size_t ts, double lon_exts[2], double lat_exts[2]\n\n ) const {\n\n lon_exts[0] = _lonExts[0]; lon_exts[1] = _lonExts[1];\n", "file_path": "include/vapor/DCReaderROMS.h", "rank": 4, "score": 256628.12045857933 }, { "content": " std::vector <size_t> _GetSpatialDims(\n\n NetCDFCFCollection *ncdfc, string varname\n\n ) const;\n\n std::vector <string> _GetSpatialDimNames(\n\n NetCDFCFCollection *ncdfc, string varname\n\n ) const;\n\n\n\n int _InitCoordVars(NetCDFCFCollection *ncdfc);\n\n\n\n void _ParseCoordVarNames(\n\n NetCDFCFCollection *ncdfc, const vector <string> &cvars,\n\n string &timecv, string &vertcv, string &latcv, string &loncv\n\n ) const;\n\n\n\n\n\n int _InitVerticalCoordinates(\n\n\tNetCDFCFCollection *ncdfc, \n\n\tconst std::vector <string> &cvars, std::vector <double> &vertCoords\n\n );\n\n\n", "file_path": "include/vapor/DCReaderROMS.h", "rank": 5, "score": 256624.83884341147 }, { "content": " }\n\n\n\n virtual std::vector<long> GetGridPermutation() const {\n\n vector <long> p;\n\n p.push_back(0); p.push_back(1); p.push_back(2);\n\n return(p);\n\n}\n\n\n\n double GetTSUserTime(size_t ts) const ;\n\n\n\n bool GetMissingValue(string varname, float &value) const;\n\n\n\n void GetTSUserTimeStamp(size_t ts, string &s) const;\n\n \n\n virtual bool IsCoordinateVariable(string varname) const;\n\n\n\n\n\n virtual int OpenVariableRead(\n\n size_t timestep, string varname, int reflevel=0, int lod=0\n\n );\n", "file_path": "include/vapor/DCReaderROMS.h", "rank": 6, "score": 256620.1103084341 }, { "content": " lat_exts[0] = _latExts[0]; lat_exts[1] = _latExts[1];\n\n }\n\n\n\nprivate:\n\n std::vector <size_t> _dims;\n\n double _latExts[2];\n\n double _lonExts[2];\n\n std::vector <double> _vertCoordinates;\n\n std::vector <double> _cartesianExtents;\n\n std::vector <string> _vars3d;\n\n std::vector <string> _vars2dXY;\n\n std::vector <string> _vars3dExcluded;\n\n std::vector <string> _vars2dExcluded;\n\n std::vector <string> _varsDerived;\n\n WeightTable * _weightTable;\n\n std::map <string, string> _varsLatLonMap;\n\n NetCDFCFCollection *_ncdfc;\n\n float *_sliceBuffer;\t// buffer for reading data\n\n float *_angleRADBuf;\t// buffer for derived \"angleRAD\" variable\n\n float *_latDEGBuf;\t// buffer for derived \"latDEG\" variable\n", "file_path": "include/vapor/DCReaderROMS.h", "rank": 7, "score": 256615.1576695304 }, { "content": " string _timeCV;\t// time coordinate variable name\n\n std::vector <string> _latCVs;\t// all valid latitude coordinate variables\n\n std::vector <string> _lonCVs;\t// all valid longitude coordinate variables\n\n std::vector <string> _vertCVs;\t// all valid vertical coordinate variables\n\n string _ovr_varname;\n\n size_t _ovr_slice;\n\n int _ovr_fd;\n\n float _defaultMV;\n\n size_t _dataReversed;\n\n\n", "file_path": "include/vapor/DCReaderROMS.h", "rank": 8, "score": 256614.5546173263 }, { "content": " return(_vars2dXY);\n\n }; \n\n\n\n\n\n virtual std::vector <string> GetVariables2DXZ() const {\n\n\tstd::vector <string> empty; return(empty);\n\n };\n\n\n\n virtual std::vector <string> GetVariables2DYZ() const {\n\n\tstd::vector <string> empty; return(empty);\n\n };\n\n\n\n virtual std::vector <string> GetVariables3DExcluded() const {\n\n return(_vars3dExcluded);\n\n };\n\n\n\n virtual std::vector <string> GetVariables2DExcluded() const {\n\n return(_vars2dExcluded);\n\n };\n\n\n", "file_path": "include/vapor/DCReaderROMS.h", "rank": 9, "score": 256610.983734935 }, { "content": " virtual std::vector<double> GetTSZCoords(size_t ) const {\n\n return(_vertCoordinates);\n\n };\n\n\n\n virtual std::vector <double> GetExtents(size_t ts = 0) const {\n\n\treturn(_cartesianExtents);\n\n }\n\n\n\n\n\n long GetNumTimeSteps() const {\n\n\treturn((long) _ncdfc->GetNumTimeSteps());\n\n }\n\n\n\n virtual string GetMapProjection() const;\n\n\n\n virtual std::vector <string> GetVariables3D() const {\n\n return(_vars3d);\n\n }; \n\n\n\n virtual std::vector <string> GetVariables2DXY() const {\n", "file_path": "include/vapor/DCReaderROMS.h", "rank": 10, "score": 256609.79857381742 }, { "content": "\n\n //\n\n // There a no spatial coordinate variables because we project\n\n // the data to a horizontally uniformly sampled Cartesian\n\n // grid.\n\n //\n\n virtual std::vector <string> GetCoordinateVariables() const {\n\n\tvector <string> v;\n\n\tv.push_back(\"NONE\"); v.push_back(\"NONE\"); v.push_back(\"NONE\");\n\n\treturn(v);\n\n}\n\n\n\n //\n\n // Boundary may be periodic in X (longitude), but we have no way\n\n // of knowing this by examining the netCDF files\n\n //\n\n virtual std::vector<long> GetPeriodicBoundary() const {\n\n vector <long> p;\n\n p.push_back(0); p.push_back(0); p.push_back(0);\n\n return(p);\n", "file_path": "include/vapor/DCReaderROMS.h", "rank": 11, "score": 256608.88912903462 }, { "content": "//\n\n// $Id$\n\n//\n\n\n\n\n\n#ifndef\t_DCReaderWRF_h_\n\n#define\t_DCReaderWRF_h_\n\n\n\n#include <vector>\n\n#include <cassert>\n\n#include <vapor/DCReader.h>\n\n#include <vapor/NetCDFCollection.h>\n\n#include <vapor/common.h>\n\n#include <vapor/Proj4API.h>\n\n\n\n#ifdef WIN32\n\n#pragma warning(disable : 4251)\n\n#endif\n\n\n\nnamespace VAPoR {\n", "file_path": "include/vapor/DCReaderWRF.h", "rank": 12, "score": 256604.71572082187 }, { "content": " std::vector <string> _timeStamps;\n\n std::vector <double> _times;\n\n std::vector <size_t> _timeLookup;\n\n NetCDFCollection *_ncdfc;\n\n float *_sliceBuffer;\t// buffer for reading data\n\n int _ovr_fd;\n\n string _projString;\n\n Proj4API _proj4API;\n\n int _mapProj;\n\n float _dx;\n\n float _dy;\n\n float _cen_lat;\n\n float _cen_lon;\n\n float _pole_lat;\n\n float _pole_lon;\n\n float _grav;\n\n float _days_per_year;\n\n float _radius;\t// planet radius for PlanetWRF\n\n float _p2si;\t// multiplier for time conversion for PlanetWRF\n\n DerivedVarElevation *_elev;\n", "file_path": "include/vapor/DCReaderWRF.h", "rank": 13, "score": 256590.43480723433 }, { "content": " return(p);\n\n}\n\n\n\n double GetTSUserTime(size_t ts) const ;\n\n\n\n bool GetMissingValue(string varname, float &value) const {\n\n\tvalue = 0.0;\n\n\treturn(false);\n\n };\n\n\n\n void GetTSUserTimeStamp(size_t ts, string &s) const;\n\n \n\n virtual bool IsCoordinateVariable(string varname) const;\n\n\n\n\n\n virtual int OpenVariableRead(\n\n size_t timestep, string varname, int reflevel=0, int lod=0\n\n );\n\n\n\n virtual int CloseVariable();\n", "file_path": "include/vapor/DCReaderWRF.h", "rank": 14, "score": 256589.15592551662 }, { "content": " double _timeBias;\n\n\n\n \n\n std::vector <size_t> _GetSpatialDims(\n\n NetCDFCollection *ncdfc, string varname\n\n ) const;\n\n std::vector <string> _GetSpatialDimNames(\n\n NetCDFCollection *ncdfc, string varname\n\n ) const;\n\n\n\n\n\n int _InitAtts(NetCDFCollection *ncdfc);\n\n int _InitProjection(NetCDFCollection *ncdfc, float radius);\n\n int _InitDimensions(NetCDFCollection *ncdfc);\n\n int _InitVerticalCoordinates(NetCDFCollection *ncdfc);\n\n int _InitTime(NetCDFCollection *ncdfc);\n\n int _InitVars(NetCDFCollection *ncdfc);\n\n\n\n int _GetVerticalExtents(\n\n\tNetCDFCollection *ncdfc, size_t ts, double height[2]\n", "file_path": "include/vapor/DCReaderWRF.h", "rank": 15, "score": 256587.07370456238 }, { "content": "\n\n virtual int ReadSlice(float *slice);\n\n\n\n virtual int Read(float *data);\n\n\n\n virtual bool VariableExists(size_t ts, string varname, int i0=0, int i1=0) const {\n\n\tts = _timeLookup[ts];\n\n return(_ncdfc->VariableExists(ts, varname));\n\n }\n\n\n\n\n\n void EnableLegacyTimeConversion() {\n\n\t_timeBias = 978307200.0; // Make consistent with legacy code\n\n }\n\n\n\n virtual void GetLatLonExtents(\n\n size_t ts, double lon_exts[2], double lat_exts[2]\n\n ) const {\n\n\tdouble dummy[4];\n\n\tts = _timeLookup[ts];\n\n\t(void) _GetLatLonExtentsCorners(\n\n\t\t_ncdfc, ts, lon_exts, lat_exts, dummy, dummy\n\n\t);\n\n }\n\n\n\n\n\nprivate:\n\n\n", "file_path": "include/vapor/DCReaderWRF.h", "rank": 16, "score": 256586.58158791898 }, { "content": " ) const; \n\n\n\n int _GetLatLonExtentsCorners(\n\n NetCDFCollection *ncdfc,\n\n size_t ts, double lon_exts[2], double lat_exts[2],\n\n double lon_corners[4], double lat_corners[4]\n\n ) const;\n\n\n\n};\n\n\n\n};\n\n\n\n#endif\t//\t_DCReaderWRF_h_\n", "file_path": "include/vapor/DCReaderWRF.h", "rank": 17, "score": 256586.56587885148 }, { "content": " std::vector <size_t> _dims;\n\n std::vector <string> _dimnames;\n\n float _grav;\n\n string _PHvar;\n\n string _PHBvar;\n\n float *_PH;\n\n float *_PHB;\n\n int _PHfd;\n\n int _PHBfd;\n\n size_t _num_ts;\n\n bool _is_open;\n\n bool _ok;\n\n };\n\n\n\n\n\n std::vector <size_t> _dims;\n\n std::vector <string> _vars3d;\n\n std::vector <string> _vars2dXY;\n\n std::vector <string> _vars3dExcluded;\n\n std::vector <string> _vars2dExcluded;\n", "file_path": "include/vapor/DCReaderWRF.h", "rank": 18, "score": 256584.1387185003 }, { "content": "\n\n//\n\n//! \\class DCReaderWRF\n\n//! \\brief ???\n\n//!\n\n//! \\author John Clyne\n\n//! \\version $Revision$\n\n//! \\date $Date$\n\n//!\n\n//!\n", "file_path": "include/vapor/DCReaderWRF.h", "rank": 19, "score": 256583.65302261247 }, { "content": "\tstd::vector <string> empty; return(empty);\n\n };\n\n\n\n virtual std::vector <string> GetVariables2DYZ() const {\n\n\tstd::vector <string> empty; return(empty);\n\n };\n\n\n\n virtual std::vector <string> GetVariables3DExcluded() const {\n\n return(_vars3dExcluded);\n\n };\n\n\n\n virtual std::vector <string> GetVariables2DExcluded() const {\n\n return(_vars2dExcluded);\n\n };\n\n\n\n\n\n //\n\n // There a no spatial coordinate variables because we project\n\n // the data to a horizontally uniformly sampled Cartesian\n\n // grid.\n", "file_path": "include/vapor/DCReaderWRF.h", "rank": 20, "score": 256578.5633671123 }, { "content": " virtual std::vector <double> GetExtents(size_t ts = 0) const;\n\n\n\n long GetNumTimeSteps() const {\n\n\treturn(_ncdfc->GetNumTimeSteps());\n\n }\n\n\n\n virtual string GetMapProjection() const {\n\n\treturn(_projString);\n\n };\n\n\n\n virtual std::vector <string> GetVariables3D() const {\n\n return(_vars3d);\n\n }; \n\n\n\n virtual std::vector <string> GetVariables2DXY() const {\n\n return(_vars2dXY);\n\n }; \n\n\n\n\n\n virtual std::vector <string> GetVariables2DXZ() const {\n", "file_path": "include/vapor/DCReaderWRF.h", "rank": 21, "score": 256578.52046245718 }, { "content": " //\n\n virtual std::vector <string> GetCoordinateVariables() const {\n\n\tvector <string> v;\n\n\tv.push_back(\"NONE\"); v.push_back(\"NONE\"); v.push_back(\"ELEVATION\");\n\n\treturn(v);\n\n}\n\n\n\n //\n\n // Boundary may be periodic in X (longitude), but we have no way\n\n // of knowing this by examining the netCDF files\n\n //\n\n virtual std::vector<long> GetPeriodicBoundary() const {\n\n vector <long> p;\n\n p.push_back(0); p.push_back(0); p.push_back(0);\n\n return(p);\n\n }\n\n\n\n virtual std::vector<long> GetGridPermutation() const {\n\n vector <long> p;\n\n p.push_back(0); p.push_back(1); p.push_back(2);\n", "file_path": "include/vapor/DCReaderWRF.h", "rank": 22, "score": 256576.5761446838 }, { "content": "\t\tclass GribParser {\n\n\t\t\tpublic:\n\n\t\t\t\tGribParser();\n\n\t\t\t\t~GribParser();\n\n\t\t\t\tint _LoadRecord(string file, size_t offset);\n\n\t\t\t\tint _LoadRecordKeys(const string file);\t// loads only the keys that we need for vdc creation\n\n\t\t\t\tint _VerifyKeys();\t\t\t\t\t// verifies that key/values conform to our reqs\n\n\t\t\t\tstd::vector<std::map<std::string, std::string> > GetRecords() const {return _recordKeys;}\n\n\t\t\t\t int doWeIgnoreForecastTimes() {return _ignoreForecastTimes;}\n\n\n\n\t\t\tprivate:\n\n\t\t\t\tint _err;\n\n\t\t\t\tstd::vector<std::map<std::string, std::string> > _recordKeys;\n\n\t\t\t\tstd::vector<std::string> _consistentKeys;\n\n\t\t\t\tstd::vector<std::string> _varyingKeys;\n\n\t\t\t\tbool _recordKeysVerified;\n\n\t\t\t\tint _ignoreForecastTimes;\n\n\t\t\t\tDCReaderGRIB *_metadata;\n\n\n\n\t\t\t\t// vars for key iteration \n", "file_path": "include/vapor/DCReaderGRIB.h", "rank": 23, "score": 255877.50279717153 }, { "content": "//\n\n//! \\class DCReaderROMS\n\n//! \\brief ???\n\n//!\n\n//! \\author John Clyne\n\n//! \\version $Revision$\n\n//! \\date $Date$\n\n//!\n\n//!\n\nclass VDF_API DCReaderROMS : public DCReader {\n\npublic:\n\n\n\n DCReaderROMS(const std::vector <string> &files);\n\n\n\n virtual ~DCReaderROMS();\n\n\n\n virtual void GetGridDim(size_t dim[3]) const {\n\n\tfor (int i=0; i<3; i++) dim[i] = _dims[i];\n\n }\n\n\n\n void GetBlockSize(size_t bs[3], int) const {\n\n\tDCReaderROMS::GetGridDim(bs);\n\n }\n\n\n\n virtual string GetGridType() const {\n\n\tif (_vertCVs.size()) return(\"layered\"); \n\n\telse return(\"regular\");\n\n }\n\n\n", "file_path": "include/vapor/DCReaderROMS.h", "rank": 24, "score": 254932.92493614095 }, { "content": "//\n\n//! \\class DCReaderWRF\n\n//! \\brief ???\n\n//!\n\n//! \\author John Clyne\n\n//! \\version $Revision$\n\n//! \\date $Date$\n\n//!\n\n//!\n\nclass VDF_API DCReaderWRF : public DCReader {\n\n\n\npublic:\n\n\n\n DCReaderWRF(const std::vector <string> &files);\n\n\n\n virtual ~DCReaderWRF();\n\n\n\n virtual void GetGridDim(size_t dim[3]) const {\n\n\tfor (int i=0; i<3; i++) dim[i] = _dims[i];\n\n }\n\n\n\n void GetBlockSize(size_t bs[3], int) const {\n\n\tDCReaderWRF::GetGridDim(bs);\n\n }\n\n\n\n virtual string GetGridType() const {\n\n\treturn(\"layered\"); \n\n }\n\n\n", "file_path": "include/vapor/DCReaderWRF.h", "rank": 25, "score": 254898.11276534 }, { "content": "#ifndef DCREADERGRIB_H\n\n#define DCREADERGRIB_H\n\n#include \"grib_api.h\"\n\n#include <vapor/DCReader.h>\n\n#include <iostream>\n\n#include <string>\n\n#include <vector>\n\n#include <map>\n\n\n\n#include <vapor/UDUnitsClass.h>\n\n#ifdef _WINDOWS\n\n#include \"vapor/udunits2.h\"\n\n#else\n\n#include <udunits2.h>\n\n#endif\n\n\n\nnamespace VAPoR {\n\n\n", "file_path": "include/vapor/DCReaderGRIB.h", "rank": 26, "score": 253756.08434321958 }, { "content": "\t\t//int _Initialize(std::vector<std::map<std::string, std::string> > records);\n\n\t\tint _Initialize(vector<string> files);\n\n\t\tint _SetGribEnv();\n\n\t\tint PrintVar(string var);\n\n\t\tfloat GetLevel(int index) const {return _pressureLevels[index];}\n\n\t\tvoid PrintLevels();\n\n\t\tvoid Print3dVars();\n\n\t\tvoid Print1dVars();\n\n\t\tdouble BarometricFormula(const double pressure) const;\n\n\t\tint _InitCartographicExtents(string mapProj);\n\n\t\t/////\n\n\n\n\t\tstruct MessageLocation {\n\n\t\t\tstring fileName;\n\n\t\t\tint offset;\n\n\t\t};\n\n\n", "file_path": "include/vapor/DCReaderGRIB.h", "rank": 27, "score": 253752.97575562555 }, { "content": "\t\t\t\tunsigned long _key_iterator_filter_flags;\n\n\t\t\t\tint _grib_count;\n\n\t\t\t char* _value;\n\n\t\t\t size_t _vlen;\n\n\n\n\t\t\t\t// vars for data dump\n\n\t\t\t\tdouble *_values;\n\n\t\t\t\tdouble _min,_max,_average;\n\n\t\t\t\tsize_t _values_len;\n\n\t\t\t\tstring _filename;\n\n\t\t};\n\n\n\n\t\tGribParser *parser;\n\n\n", "file_path": "include/vapor/DCReaderGRIB.h", "rank": 28, "score": 253748.38646753808 }, { "content": "\t\t\t\t\t\t\t\t fclose(_inFile); return 0;}\n\n\t \tvirtual int Read(float *values);\n\n\t \tvirtual int ReadSlice(float *slice);\n\n\t \tvirtual bool VariableExists(size_t ts, string varname,\n\n int reflevel=0, int lod=0) const; // not pure\n\n\t \tvirtual void GetLatLonExtents(size_t ts, double lon_exts[2],\n\n double lat_exts[2]) const;\n\n\t \tvirtual std::vector<std::string> GetVariables2DExcluded() const;\n\n \t \tvirtual std::vector<std::string> GetVariables3DExcluded() const;\n\n\n\n \tvirtual long GetNumTimeSteps() const; // from Metadata.h\n\n \tvirtual void GetGridDim(size_t dim[3]) const; // from Metadata.h\n\n \tvirtual std::vector<string> GetVariables3D() const; // from Metadata.h\n\n \tvirtual std::vector<string> GetVariables2DXY() const; // from Metadata.h\n\n \tvirtual double GetTSUserTime(size_t ts) const {return _gribTimes[ts];} // from Metadata.h\n\n\t \tvirtual std::vector<string> GetVariables2DXZ() const { // from Metadata.h\n\n \tstd::vector<string> empty; return(empty);};\n\n \tvirtual std::vector<string> GetVariables2DYZ() const { // from Metadata.h\n\n \tstd::vector<string> empty; return(empty);};\n\n\t\t// END DCReader Functions\n", "file_path": "include/vapor/DCReaderGRIB.h", "rank": 29, "score": 253743.04644612301 }, { "content": "\t\tbool _jScanPos;\n\n\t\tstring _gridType;\n\n\t\tstring _openVar;\n\n\t\tstring _Latin1InDegrees;\n\n\t\tstring _Latin2InDegrees;\n\n\t\tstring _orientationOfTheGridInDegrees; \n\n\n\n\t\tstatic int _openTS; \n\n\t\tFILE* _inFile; \n\n\t\tgrib_handle* h;\n\n\t\tstd::vector<double> _pressureLevels;\n\n\t\tstd::vector<double> _vertCoordinates;\n\n\t\tstd::vector<double> _cartesianExtents;\n\n\t\tstd::vector<double> _cartographicExtents;\n\n\t\tstd::vector<double> _gribTimes;\n\n\t\tstd::map<std::string, Variable*> _vars1d;\n\n\t\tstd::map<std::string, Variable*> _vars2d;\n\n\t\tstd::map<std::string, Variable*> _vars3d;\n\n\t\tdouble* _gaussianLats;\n\n\t\tstd::vector<double> _weights;\n\n\t\tstd::vector<int> _latIndices;\n\n\t\tfloat* _iValues;\n\n\t\tdouble* _regularLats;\n\n\t\tfloat* _hydrostaticElevation;\n\n\n\n\t\tUDUnits *_udunit;\n\n\n", "file_path": "include/vapor/DCReaderGRIB.h", "rank": 30, "score": 253741.2539861629 }, { "content": "\t\t\t\tvoid _SortTimes() {sort(_unitTimes.begin(), _unitTimes.end());}\n\n\t\t\t\tbool _Exists(double time) const;\n\n\t\t\t\tvoid setScanDirection(bool i, bool j) {iScan = i; jScan = j;}\n\n\t\t\t\tvoid setOperatingCenter(string oc) {_operatingCenter = oc;}\n\n\t\t\t\tvoid setParamId(int id) {_paramId = id;}\n\n\t\t\t\tstring getOperatingCenter() {return _operatingCenter;}\n\n\t\t\t\tint getParamId() {return _paramId;}\n\n\t\t\t\tbool getiScan() const {return iScan;}\n\n\t\t\t\tbool getjScan() const {return jScan;}\n\n\n\n\t\t\tprivate:\n\n\t\t\t\t// time level\n\n\t\t\t\tstd::map<double, std::map<float, MessageLocation> > _indices;\n\n\t\t\t\tstd::vector<int> _messages;\n\n\t\t\t\tstd::vector<float> _pressureLevels;\n\n\n\n\t\t\t\t//! list of time indices that a variable exists within\n\n\t\t\t\tstd::vector<size_t> _varTimes;\n\n\t\t\t\t//! times stored in udunit2 format\n\n\t\t\t std::vector<double> _unitTimes;\n", "file_path": "include/vapor/DCReaderGRIB.h", "rank": 31, "score": 253740.35145272934 }, { "content": "\t\t/////\n\n\n\n\t\n\n\t\t/////\n\n\t\t// Metadata Pure Virtual Functions\n\n\t\tvirtual void GetBlockSize(size_t bs[3], int reflevel) const { GetGridDim(bs); }\n\n\t\tvirtual std::vector<double> GetExtents(size_t ts = 0) const {return _cartographicExtents;}//_cartesianExtents;}\n\n\t\tvirtual std::vector<long> GetPeriodicBoundary() const;\t\t\t\t// Needs implementation!\n\n\t\tvirtual std::vector<long> GetGridPermutation() const;\t\t\t\t// Needs implementation!\n\n\t\tvirtual void GetTSUserTimeStamp(size_t ts, std::string &s) const;\n\n\t\tvirtual std::string GetMapProjection() const;\n\n\t\t// END Metadata Virtual Functions\n\n\t\t/////\n\n\n\n\t\tvector <double> GetZCoordsInMeters() const {return _vertCoordinates;}\n\n\t\tvoid _LinearInterpolation(float* values);\n\n\t\n\n private:\n\n\t\t/////\n\n\t\t// Convenience functions\n", "file_path": "include/vapor/DCReaderGRIB.h", "rank": 32, "score": 253735.3292217649 }, { "content": "\t\t\t\tstring _operatingCenter;\n\n\t\t\t\tint _paramId;\n\n\t\t\t\tbool iScan;\n\n\t\t\t\tbool jScan;\n\n\t\t\t\tbool isGaussian;\n\n\t\t};\n\n\n\n\t\tbool _ignoreForecastData;\n\n\t\tstatic int _sliceNum;\n\n\t\tint _Ni;\n\n\t\tint _Nj;\n\n\t\tdouble _DxInMetres;\n\n\t\tdouble _DyInMetres;\n\n\t\tdouble _LaDInDegrees;\n\n\t\tdouble _LoVInDegrees;\n\n\t\tdouble _minLat;\n\n\t\tdouble _minLon;\n\n\t\tdouble _maxLat;\n\n\t\tdouble _maxLon;\n\n\t\tbool _iScanNeg;\n", "file_path": "include/vapor/DCReaderGRIB.h", "rank": 33, "score": 253732.3687738372 }, { "content": "//************************************************************************\n\n// *\n\n// Copyright (C) 2004 *\n\n// University Corporation for Atmospheric Research *\n\n// All Rights Reserved *\n\n// *\n\n//************************************************************************/\n\n//\n\n// File: DCReaderGRIB.h\n\n//\n\n// Author: Scott Pearse\n\n// National Center for Atmospheric Research\n\n// PO 3000, Boulder, Colorado\n\n//\n\n// Date: June 2014\n\n//\n\n// Description: TBD \n\n// \n\n//\n\n\n", "file_path": "include/vapor/DCReaderGRIB.h", "rank": 34, "score": 253732.2432023527 }, { "content": "class VDF_API DCReaderGRIB : public DCReader {\n\n\tpublic:\n\n\t\tDCReaderGRIB();\n\n\t\tDCReaderGRIB(const vector<string> files);\n\n\t\t~DCReaderGRIB();\n\n\n\n\t\tint HydrostaticPressureEqn();\n\n\t\tint LoadHydroData(float* T, float* Q, float* Sp);\n\n\t\tint CalcVirtualTemperature(float* T, float* Q, float* Sum, float* Tv);\n\n\t\tint DoHydroVarsExist();\n\n\t\tvoid Print2dVars();\n\n\t\tvoid _generateWeightTable();\n\n\t\tstring GetGridType() const;\n\n\t\tvirtual std::vector<double> GetTSZCoords(size_t ) const {\n\n\t\t\treturn(_vertCoordinates);};\n\n\t\t/////\n\n\t\t// DCReader Virtual Functions\n\n \tvirtual int OpenVariableRead(size_t timestep, string varname, \n\n \t int reflevel=0, int lod=0);\n\n\t \tvirtual int CloseVariable() {//grib_handle_delete(h);\n", "file_path": "include/vapor/DCReaderGRIB.h", "rank": 35, "score": 251802.09665493766 }, { "content": "int grib_keys_iterator_delete( grib_keys_iterator* kiter)\n\n{\n\n if (kiter) {\n\n if(kiter->seen)\n\n grib_trie_delete(kiter->seen);\n\n if (kiter->name_space)\n\n grib_context_free(kiter->handle->context,kiter->name_space);\n\n grib_context_free(kiter->handle->context,kiter);\n\n }\n\n return 0;\n", "file_path": "lib/gribapi/grib_keys_iterator.c", "rank": 36, "score": 248691.38577270802 }, { "content": "grib_keys_iterator* grib_keys_iterator_new(grib_handle* h,unsigned long filter_flags, char* name_space)\n\n{\n\n grib_keys_iterator* ki=NULL;\n\n\n\n if (!h) return NULL;\n\n\n\n ki= grib_context_malloc_clear(h->context,sizeof(grib_keys_iterator));\n\n if (!ki) return NULL;\n\n\n\n ki->filter_flags = filter_flags;\n\n ki->handle = h;\n\n ki->name_space = NULL;\n\n\n\n if (name_space != NULL)\n\n ki->name_space = grib_context_strdup(h->context,name_space);\n\n\n\n ki->at_start = 1;\n\n ki->match = 0;\n\n\n\n grib_keys_iterator_set_flags(ki,filter_flags);\n\n\n\n return ki;\n", "file_path": "lib/gribapi/grib_keys_iterator.c", "rank": 37, "score": 248671.02692431814 }, { "content": "grib_iterator* grib_iterator_new(grib_handle* h,unsigned long flags,int* error)\n\n{ \n\n\tgrib_accessor* a = NULL;\n\n\tgrib_accessor_iterator* ita =NULL; \n\n\tgrib_iterator* iter =NULL;\n\n\t*error=GRIB_NOT_IMPLEMENTED;\n\n\ta = grib_find_accessor(h,\"ITERATOR\");\n\n\tita = (grib_accessor_iterator*)a;\n\n\n\n\tif (!a) return NULL;\n\n\n\n\titer = grib_iterator_factory(h,ita->args,flags,error);\n\n\n\n\tif (iter) *error=GRIB_SUCCESS;\n\n\n\n\treturn iter;\n", "file_path": "lib/gribapi/grib_accessor_class_iterator.c", "rank": 38, "score": 248671.02692431814 }, { "content": " class VDF_API DCReaderGRIB : public DCReader {\n\n public:\n\n\t DCReaderGRIB();\n\n\t ~DCReaderGRIB();\n\n\n\n\t/////\n\n\t// DCReader Virtual Functions\n\n virtual int OpenVariableRead(size_t timestep, string varname, \n\n int reflevel=0, int lod=0);\n\n\t virtual int CloseVariable() {return 0;}\n\n\t virtual int ReadSlice(float *slice);\n\n\t virtual bool VariableExists(size_t ts, string varname,\n\n int reflevel=0, int lod=0) const; // not pure\n\n\t virtual void GetLatLonExtents(size_t ts, double lon_exts[2],\n\n double lat_exts[2]) const;\n\n\t virtual std::vector<std::string> GetVariables2DExcluded() const;\n\n \t virtual std::vector<std::string> GetVariables3DExcluded() const;\n\n\n\n virtual long GetNumTimeSteps() const; // from Metadata.h\n\n virtual void GetGridDim(size_t dim[3]) const; // from Metadata.h\n", "file_path": "include/vapor/GribParser.h", "rank": 39, "score": 248312.177906738 }, { "content": "\t\tclass Variable {\n\n\t\t\tpublic:\n\n\t\t\t\tVariable();\n\n\t\t\t\t~Variable();\n\n\t\t\t\t//! Add a udunits-created double time value to _unitTimes\n\n\t\t\t\tvoid _AddTime(double t) {_unitTimes.push_back(t);}\n\n\t\t\t\tvoid _AddMessage(int msg) {_messages.push_back(msg);} \n\n\t\t\t\tvoid _AddLevel(float lvl) {_pressureLevels.push_back(lvl);}\n\n\t\t\t\tvoid _AddIndex(double time, float level, string file, int offset);\n\n\n\n\t\t\t\tint GetOffset(double time, float level) const;\n\n\t\t\t\tstring GetFileName(double time, float level) const;\n\n\t\t\t\tstd::vector<int> GetMessages() const {return _messages;}\n\n\t\t\t\tstd::vector<double> GetTimes() const {return _unitTimes;}\n\n\t\t\t\tstd::vector<float> GetLevels() const {return _pressureLevels;}\n\n\t\t\t\tfloat GetLevel(int index) const {return _pressureLevels[index];}\n\n\t\t\t\tvoid PrintTimes();\n\n\t\t\t\tvoid PrintMessages();\n\n\t\t\t\tvoid PrintIndex(double time, float level);\n\n\t\t\t\tvoid _SortLevels() {sort(_pressureLevels.begin(), _pressureLevels.end());}\n", "file_path": "include/vapor/DCReaderGRIB.h", "rank": 40, "score": 247940.90275884146 }, { "content": "\t\tclass Record {\n\n\t\t\tpublic:\n\n\t\t\t\tRecord();\n\n\t\t\t\tRecord(string file, int recordNum);\n\n\t\t\t\t~Record();\n\n\t\t\t\tvoid setTime(string input) {time = input;}\n\n\t\t\t\tvoid setUnits(string input) {units = input;}\n\n\t\t\t\tvoid setNi(string input) {Ni = input;}\n\n\t\t\t\tvoid setNj(string input) {Nj = input;}\n\n\t\t\t\tvoid setGridType(string input) {gridType = input;}\n\n\t\t\t\tvoid setVarName(string input) {varName = input;}\n\n\t\t\t\tstring getTime() {return time;}\n\n\t\t\t\tstring getUnits() {return units;}\n\n\t\t\t\tstring getNi() {return Ni;}\n\n\t\t\t\tstring getNj() {return Nj;}\n\n\t\t\t\tstring getGridType() {return gridType;}\n\n\t\t\t\tstring getVarName() {return varName;}\n\n\n\n\t\t\tprivate:\n\n\t\t\t\tstring time;\n\n\t\t\t\tstring units;\n\n\t\t\t\tstring Ni;\n\n\t\t\t\tstring Nj;\n\n\t\t\t\tstring gridType;\n\n\t\t\t\tstring varName;\n\n\t\t};\n\n\t};\n\n};\n\n#endif // GRIBPARSER_H\n", "file_path": "include/vapor/DCReaderGRIB.h", "rank": 41, "score": 247940.90275884146 }, { "content": "int grib_keys_iterator_get_string(grib_keys_iterator* kiter,char* v,size_t* len)\n\n{\n\n return grib_unpack_string( kiter->current,v,len);\n", "file_path": "lib/gribapi/grib_keys_iterator.c", "rank": 42, "score": 244737.30991966184 }, { "content": "int grib_keys_iterator_get_double(grib_keys_iterator* kiter,double* v,size_t* len)\n\n{\n\n return grib_unpack_double( kiter->current,v,len);\n", "file_path": "lib/gribapi/grib_keys_iterator.c", "rank": 43, "score": 244682.45124352584 }, { "content": "class UDUnits;\n\n\n", "file_path": "include/vapor/DCReaderGRIB.h", "rank": 44, "score": 242417.72413735362 }, { "content": " class latLonBuf {\n\n public:\n\n size_t _nx;\n\n size_t _ny;\n\n float *_latbuf;\n\n float *_lonbuf;\n\n float _latexts[2];\n\n float _lonexts[2];\n\n };\n\n\n\n\n\n int _initLatLonBuf(\n\n\tNetCDFCFCollection *ncdfc, string latvar, string lonvar,\n\n\tDCReaderROMS::latLonBuf &llb\n\n ) const;\n\n\n\n void _getRotationVariables(\n\n\tWeightTable * wt, float *_angleRADBuf, float *_latDEGBuf\n\n ) const;\n\n\n", "file_path": "include/vapor/DCReaderROMS.h", "rank": 45, "score": 239828.5458866444 }, { "content": "int grib_iterator_delete(grib_iterator *i);\n", "file_path": "lib/gribapi/grib_api_prototypes.h", "rank": 46, "score": 237510.44848296436 }, { "content": "grib_iterator *grib_iterator_new(grib_handle *h, unsigned long flags, int *error);\n", "file_path": "lib/gribapi/grib_api_prototypes.h", "rank": 47, "score": 237503.3247824201 }, { "content": "grib_expression* new_true_expression(grib_context* c)\n\n{\n\n\tgrib_expression_true* e = grib_context_malloc_clear_persistent(c,sizeof(grib_expression_true));\n\n\te->base.cclass = grib_expression_class_true;\n\n\treturn (grib_expression*)e;\n", "file_path": "lib/gribapi/grib_expression_class_true.c", "rank": 48, "score": 233981.31178212658 }, { "content": "grib_expression* new_string_expression(grib_context* c,const char* value)\n\n{\n\n\tgrib_expression_string* e = grib_context_malloc_clear_persistent(c,sizeof(grib_expression_string));\n\n\te->base.cclass = grib_expression_class_string;\n\n\te->value = grib_context_strdup_persistent(c,value);\n\n\treturn (grib_expression*)e;\n", "file_path": "lib/gribapi/grib_expression_class_string.c", "rank": 49, "score": 233896.61387352267 }, { "content": "grib_expression* new_double_expression(grib_context* c,double value)\n\n{\n\n\tgrib_expression_double* e = grib_context_malloc_clear_persistent(c,sizeof(grib_expression_double));\n\n\te->base.cclass = grib_expression_class_double;\n\n\te->value = value;\n\n\treturn (grib_expression*)e;\n", "file_path": "lib/gribapi/grib_expression_class_double.c", "rank": 50, "score": 233825.2746709034 }, { "content": "static void grib_fieldset_delete_int_array(grib_int_array* f);\n", "file_path": "lib/gribapi/grib_fieldset.c", "rank": 51, "score": 233320.25573380696 }, { "content": "int grib_keys_iterator_delete(grib_keys_iterator *kiter);\n", "file_path": "lib/gribapi/grib_api_prototypes.h", "rank": 52, "score": 233254.14314804092 }, { "content": "grib_keys_iterator *grib_keys_iterator_new(grib_handle *h, unsigned long filter_flags, char *name_space);\n", "file_path": "lib/gribapi/grib_api_prototypes.h", "rank": 53, "score": 233247.6156964433 }, { "content": "int grib_keys_iterator_get_string(grib_keys_iterator *kiter, char *v, size_t *len);\n", "file_path": "lib/gribapi/grib_api_prototypes.h", "rank": 54, "score": 229099.7331551519 }, { "content": " int error;\n", "file_path": "lib/gribapi/grib_api.h", "rank": 55, "score": 229079.74953353108 }, { "content": "int grib_keys_iterator_get_double(grib_keys_iterator *kiter, double *v, size_t *len);\n", "file_path": "lib/gribapi/grib_api_prototypes.h", "rank": 56, "score": 229044.87447901594 }, { "content": "#define STRING 342\n", "file_path": "lib/gribapi/grib_yacc.c", "rank": 57, "score": 229019.85026803124 }, { "content": "#define STRING 342\n", "file_path": "lib/gribapi/grib_yacc.h", "rank": 58, "score": 229019.85026803124 }, { "content": "//\n\n//! \\class DataMgrROMS\n\n//! \\brief A cache based data reader\n\n//! \\author John Clyne\n\n//! \\version $Revision$\n\n//! \\date $Date$\n\n//!\n\n//\n\nclass VDF_API DataMgrROMS : public DataMgr, DCReaderROMS {\n\n\n\npublic:\n\n\n\n DataMgrROMS(\n\n\tconst vector <string> &files,\n\n\tsize_t mem_size\n\n );\n\n\n\n\n\n virtual ~DataMgrROMS() { }; \n\n\n\nprotected:\n\n\n\n\n\n //\n\n //\tMetadata methods\n\n //\n\n\n\n virtual void _GetDim(size_t dim[3], int ) const {\n", "file_path": "include/vapor/DataMgrROMS.h", "rank": 59, "score": 228237.6739955524 }, { "content": "//\n\n//! \\class DataMgrWRF\n\n//! \\brief A cache based data reader\n\n//! \\author John Clyne\n\n//! \\version $Revision$\n\n//! \\date $Date$\n\n//!\n\n//\n\nclass VDF_API DataMgrWRF : public DataMgr, DCReaderWRF {\n\n\n\npublic:\n\n\n\n DataMgrWRF(\n\n\tconst vector <string> &files,\n\n\tsize_t mem_size\n\n );\n\n\n\n\n\n virtual ~DataMgrWRF() { }; \n\n\n\nprotected:\n\n\n\n\n\n //\n\n //\tMetadata methods\n\n //\n\n\n\n virtual void _GetDim(size_t dim[3], int ) const {\n", "file_path": "include/vapor/DataMgrWRF.h", "rank": 60, "score": 228200.2646665881 }, { "content": "grib_expression* new_string_compare_expression(grib_context* c,\n\n grib_expression* left,grib_expression* right)\n\n{\n\n grib_expression_string_compare* e = grib_context_malloc_clear_persistent(c,sizeof(grib_expression_string_compare));\n\n e->base.cclass = grib_expression_class_string_compare;\n\n e->left = left;\n\n e->right = right;\n\n return (grib_expression*)e;\n", "file_path": "lib/gribapi/grib_expression_class_string_compare.c", "rank": 61, "score": 225857.2557045904 }, { "content": " const char *var;\n", "file_path": "lib/gribapi/grib_api_internal.h", "rank": 62, "score": 225325.63694722817 }, { "content": " int error;\n", "file_path": "lib/gribapi/grib_api_internal.h", "rank": 63, "score": 225316.3342416685 }, { "content": "static int error = 0;\n", "file_path": "lib/gribapi/grib_parse_utils.c", "rank": 64, "score": 225316.3342416685 }, { "content": " char* string;\n", "file_path": "lib/gribapi/grib_api_internal.h", "rank": 65, "score": 225257.6995688225 }, { "content": "//\n\n//! \\class DataMgrGRIB\n\n//! \\brief A cache based data reader\n\n//! \\author John Clyne\n\n//! \\version $Revision$\n\n//! \\date $Date$\n\n//!\n\n//\n\nclass VDF_API DataMgrGRIB : public DataMgr, DCReaderGRIB {\n\n\n\npublic:\n\n\n\n DataMgrGRIB(\n\n\tconst vector <string> &files,\n\n\tsize_t mem_size\n\n );\n\n\n\n\n\n virtual ~DataMgrGRIB() { }; \n\n\n\nprotected:\n\n\n\n\n\n //\n\n //\tMetadata methods\n\n //\n\n\n\n virtual void _GetDim(size_t dim[3], int ) const {\n", "file_path": "include/vapor/DataMgrGRIB.h", "rank": 66, "score": 224886.50814694207 }, { "content": "grib_expression *new_true_expression(grib_context *c);\n", "file_path": "lib/gribapi/grib_api_prototypes.h", "rank": 67, "score": 223010.02348763825 }, { "content": "grib_expression *new_string_expression(grib_context *c, const char *value);\n", "file_path": "lib/gribapi/grib_api_prototypes.h", "rank": 68, "score": 222942.13405888353 }, { "content": "static int evaluate_double(grib_expression*,grib_handle*,double*);\n", "file_path": "lib/gribapi/grib_expression_class_true.c", "rank": 69, "score": 222905.05460889093 }, { "content": "grib_expression *new_double_expression(grib_context *c, double value);\n", "file_path": "lib/gribapi/grib_api_prototypes.h", "rank": 70, "score": 222885.21168629202 }, { "content": "static int unpack_string (grib_accessor*, char*, size_t *len);\n", "file_path": "lib/gribapi/grib_accessor_class_double.c", "rank": 71, "score": 222837.2589587007 }, { "content": "extern grib_accessor_class* grib_accessor_class_double;\n", "file_path": "lib/gribapi/grib_accessor_class_simple_packing_error.c", "rank": 72, "score": 221325.11414384207 }, { "content": "extern grib_accessor_class* grib_accessor_class_double;\n", "file_path": "lib/gribapi/grib_accessor_class_reference_value_error.c", "rank": 73, "score": 221325.11414384207 }, { "content": "grib_expression *new_string_compare_expression(grib_context *c, grib_expression *left, grib_expression *right);\n", "file_path": "lib/gribapi/grib_api_prototypes.h", "rank": 74, "score": 218473.64527750714 }, { "content": "static int evaluate_double(grib_expression*,grib_handle*,double*);\n", "file_path": "lib/gribapi/grib_expression_class_string_compare.c", "rank": 75, "score": 218370.77508599337 }, { "content": "static int unpack_double(grib_accessor*, double* val,size_t *len);\n", "file_path": "lib/gribapi/grib_accessor_class_simple_packing_error.c", "rank": 76, "score": 214133.29467383004 }, { "content": "static int unpack_double(grib_accessor*, double* val,size_t *len);\n", "file_path": "lib/gribapi/grib_accessor_class_reference_value_error.c", "rank": 77, "score": 214133.29467383004 }, { "content": "//\n\n//! \\class VDFIOBase\n\n//! \\brief Abstract base class for performing data IO to a VDC\n\n//! \\author John Clyne\n\n//! \\version $Revision$\n\n//! \\date $Date$\n\n//!\n\n//! This class provides an API for performing low-level IO \n\n//! to/from a Vapor Data Collection (VDC)\n\n//\n\nclass VDF_API\tVDFIOBase : public MetadataVDC {\n\n\n\npublic:\n\n\n\n //! Constructor for the VDFIOBase class.\n\n //! \\param[in] metadata Pointer to a metadata class object for which all\n\n //! future class operations will apply\n\n //! \\note The success or failure of this constructor can be checked\n\n //! with the GetErrCode() method.\n\n //!\n\n //! \\sa Metadata, GetErrCode(),\n\n //\n\n VDFIOBase(\n\n\tconst MetadataVDC &metadata\n\n );\n\n\n\n //! Constructor for the VDFIOBase class.\n\n //! \\param[in] metafile Path to a metadata file for which all\n\n //! future class operations will apply\n\n //! \\note The success or failure of this constructor can be checked\n", "file_path": "include/vapor/VDFIOBase.h", "rank": 78, "score": 209101.55267987493 }, { "content": "int grib_iterator_previous(grib_iterator *i,double* lat,double* lon,double* value)\n\n{\n\n grib_iterator_class *c = i->cclass;\n\n while(c)\n\n {\n\n grib_iterator_class *s = c->super ? *(c->super) : NULL;\n\n if(c->previous) return c->previous(i, lat, lon, value);\n\n c = s;\n\n }\n\n Assert(0);\n\n return 0;\n", "file_path": "lib/gribapi/grib_iterator.c", "rank": 79, "score": 198339.06153363918 }, { "content": "int grib_iterator_init(grib_iterator* i, grib_handle *h, grib_arguments* args)\n\n{\n\n return init_iterator(i->cclass,i,h,args);\n", "file_path": "lib/gribapi/grib_iterator.c", "rank": 80, "score": 198339.06153363918 }, { "content": "int grib_iterator_has_next(grib_iterator *i)\n\n{\n\n grib_iterator_class *c = i->cclass;\n\n while(c)\n\n {\n\n grib_iterator_class *s = c->super ? *(c->super) : NULL;\n\n if(c->has_next) return c->has_next(i);\n\n c = s;\n\n }\n\n Assert(0);\n\n return 0;\n", "file_path": "lib/gribapi/grib_iterator.c", "rank": 81, "score": 198339.06153363918 }, { "content": "int grib_iterator_next(grib_iterator *i,double* lat,double* lon,double* value)\n\n{\n\n grib_iterator_class *c = i->cclass;\n\n while(c)\n\n {\n\n grib_iterator_class *s = c->super ? *(c->super) : NULL;\n\n if(c->next) return c->next(i, lat, lon, value);\n\n c = s;\n\n }\n\n Assert(0);\n\n return 0;\n", "file_path": "lib/gribapi/grib_iterator.c", "rank": 82, "score": 198339.06153363918 }, { "content": "int grib_iterator_reset(grib_iterator *i)\n\n{\n\n grib_iterator_class *c = i->cclass;\n\n while(c)\n\n {\n\n grib_iterator_class *s = c->super ? *(c->super) : NULL;\n\n if(c->reset) return c->reset(i);\n\n c = s;\n\n }\n\n Assert(0);\n\n return 0;\n", "file_path": "lib/gribapi/grib_iterator.c", "rank": 83, "score": 198339.06153363918 }, { "content": "//\n\n// $Id$\n\n//\n\n\n\n\n\n#ifndef\t_VDFIOBase_h_\n\n#define\t_VDFIOBase_h_\n\n\n\n#include <cstdio>\n\n#include <vapor/MyBase.h>\n\n#include <vapor/MetadataVDC.h>\n\n#include <vapor/CFuncs.h>\n\n\n\nnamespace VAPoR {\n\n\n\n\n\n//\n\n//! \\class VDFIOBase\n\n//! \\brief Abstract base class for performing data IO to a VDC\n\n//! \\author John Clyne\n\n//! \\version $Revision$\n\n//! \\date $Date$\n\n//!\n\n//! This class provides an API for performing low-level IO \n\n//! to/from a Vapor Data Collection (VDC)\n\n//\n", "file_path": "include/vapor/VDFIOBase.h", "rank": 84, "score": 195949.09488572998 }, { "content": "\n\n int _VDFIOBase();\n\n\n\n int _mask_open(\n\n\tsize_t timestep, string varname, int reflevel, size_t &bitmasksz\n\n );\n\n void _downsample(const BitMask &bm0, BitMask &bm1, int l0, int l1) const;\n\n\n\n};\n\n\n\n}\n\n\n\n#endif\t//\t\n", "file_path": "include/vapor/VDFIOBase.h", "rank": 85, "score": 195942.74036788577 }, { "content": " void _WriteTimerReset() {_write_timer_acc = 0;};\n\n void _WriteTimerStart() {_write_timer = VetsUtil::GetTime();};\n\n void _WriteTimerStop() {_write_timer_acc += (VetsUtil::GetTime() - _write_timer);};\n\n\n\n void _XFormTimerReset() {_xform_timer_acc = 0;};\n\n void _XFormTimerStart() {_xform_timer = VetsUtil::GetTime();};\n\n void _XFormTimerStop() {_xform_timer_acc += (VetsUtil::GetTime() - _xform_timer);};\n\n\n\n //\n\n // The Mask* methods are used to support missing data. If no missing \n\n // data are present the methods below are no-ops. The missing value\n\n // is determined by MetadataVDC::GetMissingValue()\n\n //\n\n\n\n // Open a mask file in the VDC for writing. \n\n //\n\n int _MaskOpenWrite(size_t timestep, string varname, int reflevel);\n\n int _MaskOpenRead(size_t timestep, string varname, int reflevel);\n\n int _MaskClose();\n\n int _MaskWrite(\n", "file_path": "include/vapor/VDFIOBase.h", "rank": 86, "score": 195939.40787573287 }, { "content": "\n\n virtual int OpenVariableRead(\n\n size_t timestep, const char *varname, int reflevel=0, int lod=0\n\n ) {_varname = varname; return(0); };\n\n\n\n virtual int BlockReadRegion(\n\n const size_t bmin[3], const size_t bmax[3], float *region, bool unblock=true\n\n ) = 0;\n\n\n\n virtual int ReadRegion(\n\n const size_t min[3], const size_t max[3], float *region\n\n ) = 0;\n\n\n\n virtual int ReadRegion(float *region) = 0;\n\n\n\n virtual int ReadSlice(float *slice) = 0;\n\n\n\n virtual int OpenVariableWrite(\n\n size_t timestep, const char *varname, int reflevel=0, int lod=0\n\n ) {_varname = varname; return(0); };\n", "file_path": "include/vapor/VDFIOBase.h", "rank": 87, "score": 195936.20339031337 }, { "content": "\tconst float *srcblk, const size_t bmin_p[3], const size_t bmax_p[3], \n\n\tbool block\n\n );\n\n int _MaskRead(const size_t bmin_p[3], const size_t bmax_p[3]); \n\n\n\n //\n\n // Removes missing values from a data block and replaces them with the \n\n // block's average value. If all of elements of 'blk' are missing values,\n\n // 'valid_data' will be set to false, otherwise it will be true\n\n //\n\n void _MaskRemove(float *blk, bool &valid_data) const;\n\n\n\n //\n\n // Using a BitMask read by _MaskRead(), restore the missing values\n\n // previously removed with _MaskRemove()\n\n //\n\n void _MaskReplace(size_t bx, size_t by, size_t bz, float *blk) const;\n\n\t\n\n\n\n static void _UnpackCoord(\n", "file_path": "include/vapor/VDFIOBase.h", "rank": 88, "score": 195936.10384253965 }, { "content": " //! with the GetErrCode() method.\n\n //!\n\n //! \\sa Metadata, GetErrCode(),\n\n //\n\n VDFIOBase(\n\n\tconst string &metafile\n\n );\n\n\n\n virtual ~VDFIOBase();\n\n\n\n //! Return the read timer\n\n //!\n\n //! This method returns the accumulated clock time, in seconds, \n\n //! spent reading data from files. \n\n //!\n\n double\tGetReadTimer() const { return(_read_timer_acc); };\n\n\n\n //! Return the seek timer\n\n //!\n\n //! This method returns the accumulated clock time, in seconds, \n", "file_path": "include/vapor/VDFIOBase.h", "rank": 89, "score": 195936.08728083555 }, { "content": " double\t_write_timer;\n\n double\t_seek_timer;\n\n double\t_xform_timer;\n\n\n\n //\n\n // state info to handle data sets with missing data values\n\n //\n\n int _ncid_mask;\n\n int _varid_mask;\n\n VarType_T _vtype_mask;\n\n float _mv_mask;\n\n size_t _bs_p_mask[3];\n\n size_t _bdim_p_mask[3];\n\n int _reflevel_mask;\n\n int _reflevel_file_mask;\n\n string _ncpath_mask;\n\n string _ncpath_mask_tmp;\n\n bool _open_write_mask;\n\n vector <BitMask> _bitmasks;\n\n string _varname; // currently opened variable;\n", "file_path": "include/vapor/VDFIOBase.h", "rank": 90, "score": 195935.88989604305 }, { "content": "\n\n\t//\n\n\t// Return pointer to the internal storage for a bit mask. The length\n\n\t// of the array returned is getSize(nbits) bytes\n\n\t//\n\n\tunsigned char *getStorage() const;\n\n\tBitMask &operator=(const BitMask &bm);\n\n\t\n\n private:\n\n\tunsigned char *_bitmask;\t// storage for bitmask\n\n\tsize_t _bitmask_sz;\t\t// size of _bitmask buffer in bytes\n\n\tsize_t _nbits;\n\n\n\n\tvoid _BitMask(size_t nbits);\n\n };\n\n\n\n void _ReadTimerReset() {_read_timer_acc = 0;};\n\n void _ReadTimerStart() {_read_timer = VetsUtil::GetTime();};\n\n void _ReadTimerStop() {_read_timer_acc += (VetsUtil::GetTime() - _read_timer);};\n\n\n", "file_path": "include/vapor/VDFIOBase.h", "rank": 91, "score": 195934.8222903449 }, { "content": " VarType_T vtype, const size_t src[3], size_t dst[3], size_t fill\n\n );\n\n\n\n static void _PackCoord(\n\n\tVarType_T vtype, const size_t src[3], size_t dst[3], size_t fill\n\n );\n\n\n\n static void _FillPackedCoord(\n\n\tVarType_T vtype, const size_t src[3], size_t dst[3], size_t fill\n\n );\n\n\n\n\n\nprivate:\n\n\n\n double\t_read_timer_acc;\n\n double\t_write_timer_acc;\n\n double\t_seek_timer_acc;\n\n double\t_xform_timer_acc;\n\n\n\n double\t_read_timer;\n", "file_path": "include/vapor/VDFIOBase.h", "rank": 92, "score": 195931.39025533092 }, { "content": "\n\n virtual int BlockWriteRegion(\n\n const float *region, const size_t bmin[3], const size_t bmax[3], \n\n\tbool block=true\n\n ) = 0;\n\n\n\n virtual int WriteRegion(\n\n const float *region, const size_t min[3], const size_t max[3]\n\n ) = 0;\n\n\n\n virtual int WriteRegion(const float *region) = 0;\n\n\n\n virtual int WriteSlice(const float *slice) = 0;\n\n\n\n virtual int CloseVariable() {_varname.clear(); return(0);};\n\n\n\n virtual const float *GetDataRange() const = 0;\n\n\n\nprotected:\n\n\n", "file_path": "include/vapor/VDFIOBase.h", "rank": 93, "score": 195930.9432733123 }, { "content": "#include <cstdio>\n\n#include <cstdlib>\n\n#include <vapor/vdfcreate.h>\n\n\n\nusing namespace std;\n\nusing namespace VAPoR;\n\nusing namespace VetsUtil;\n\n\n\nint main(int argc, char **argv) {\n\n\t\n\n\tMyBase::SetErrMsgFilePtr(stderr);\n\n\tvdfcreate vdfc;\n\n//\tstd::string command = \"ROMS\";\n\n\tstd::string command = \"CAM\";\n\n\tint rc = vdfc.launchVdfCreate(argc, argv, command);\n\n\n\n\tif (rc == 0) return(0);\n\n\telse return(1);\n\n}\n", "file_path": "apps/camvdfcreate/camvdfcreate.cpp", "rank": 94, "score": 58.48617521472833 }, { "content": "\tstring metafile = argv[argc-1];\n\n\t\n\n\t// If we are receiving an optionalReader, we're using the wizard\n\n\t// Therefore we want to clear any previous wcwriter that may have\n\n\t// been created in a previous conversion\n\n\tif (optionalReader != NULL) {\n\n\t\tDCData = optionalReader;\n\n\t\tif (wcwriter) delete wcwriter;\n\n\t\twcwriter = NULL;\n\n\t}\n\n\tif (DCData==NULL){\n\n\t\tif ((dataType == \"ROMS\") || (dataType == \"CAM\")) DCData = new DCReaderROMS(ncdffiles); \n\n\t\telse if (dataType == \"GRIB\") DCData = new DCReaderGRIB(ncdffiles);\n\n\t\telse DCData = new DCReaderMOM(ncdffiles);\n\n\t}\n\n\n\n\tif (MyBase::GetErrCode() != 0) return(-1);\n\n\n\n\tWaveletBlockIOBase\t*wbwriter3D = NULL;\t// VDC type 1 writer\n\n\tVDFIOBase *vdfio = NULL;\n", "file_path": "lib/vdf/Copy2VDF.cpp", "rank": 95, "score": 58.47282055719046 }, { "content": "#include <cstdio>\n\n#include <cstdlib>\n\n#include <vapor/Copy2VDF.h>\n\n\n\nusing namespace VAPoR;\n\nusing namespace VetsUtil;\n\n\n\nint main(int argc, char **argv) {\n\n\t\t\n\n\tMyBase::SetErrMsgFilePtr(stderr);\n\n\tCopy2VDF copy2vdf;\n\n//\tstring command = \"ROMS\";\n\n\tstring command = \"CAM\";\n\n\tint rc = copy2vdf.launch2vdf(argc, argv, command);\n\n\n\n\tif (rc == 0) exit(0); \n\n\telse exit(1);\n\n}\n", "file_path": "apps/cam2vdf/cam2vdf.cpp", "rank": 96, "score": 57.88135469597461 }, { "content": "//\n\n// $Id$\n\n//\n\n\n\n#include <iostream>\n\n#include <sstream>\n\n#include <iterator>\n\n#include <cassert>\n\n\n\n#include <vapor/GeoUtil.h>\n\n#include <vapor/DCReaderROMS.h>\n\n#include <vapor/Proj4API.h>\n\n#ifdef WIN32\n\n#pragma warning(disable : 4251)\n\n#endif\n\n\n\nusing namespace VAPoR;\n\nusing namespace std;\n\n\n\nDCReaderROMS::DCReaderROMS(const vector <string> &files) {\n", "file_path": "lib/vdf/DCReaderROMS.cpp", "rank": 99, "score": 54.09688587478228 } ]
C++
TinySTL/set.hpp
syn1w/TinySTL
04961c8fcec560d23cb99d049d44ff1b88113118
 #pragma once #include "rbtree.hpp" namespace tiny_stl { template <typename Key, typename Compare = tiny_stl::less<Key>, typename Alloc = tiny_stl::allocator<Key>> class set : public RBTree<Key, Compare, Alloc, false> { public: using allocator_type = Alloc; private: using Base = RBTree<Key, Compare, allocator_type, false>; using AlTraits = allocator_traits<allocator_type>; using AlNode = typename Base::AlNode; using AlNodeTraits = typename Base::AlNodeTraits; public: using key_type = Key; using value_type = Key; using size_type = typename Alloc::size_type; using difference_type = typename Alloc::difference_type; using key_compare = Compare; using value_compare = Compare; using reference = value_type&; using const_reference = const value_type&; using pointer = typename AlTraits::pointer; using const_pointer = typename AlTraits::const_pointer; using iterator = typename Base::iterator; using const_iterator = typename Base::const_iterator; using reverse_iterator = typename Base::reverse_iterator; using const_reverse_iterator = typename Base::const_reverse_iterator; public: set() : set(Compare()) { } explicit set(const Compare& cmp, const Alloc& alloc = Alloc()) : Base(cmp, alloc) { } explicit set(const Alloc& alloc) : Base(key_compare(), alloc) { } template <typename InIter> set(InIter first, InIter last, const key_compare& cmp, const Alloc& alloc = Alloc()) : Base(cmp, alloc) { this->insert_unique(first, last); } template <typename InIter> set(InIter first, InIter last, const Alloc& alloc) : Base(key_compare(), alloc) { this->insert_unique(first, last); } set(const set& rhs) : Base(rhs, AlTraits::select_on_container_copy_construction( rhs.get_allocator())) { } set(const set& rhs, const Alloc& alloc) : Base(rhs, alloc) { } set(set&& rhs) : Base(tiny_stl::move(rhs)) { } set(set&& rhs, const Alloc& alloc) : Base(tiny_stl::move(rhs), alloc) { } set(std::initializer_list<value_type> ilist, const Compare& cmp = Compare(), const Alloc& alloc = Alloc()) : Base(cmp, alloc) { this->insert_unique(ilist.begin(), ilist.end()); } set(std::initializer_list<value_type> ilist, const Alloc& alloc) : set(ilist, Compare(), alloc) { } set& operator=(const set& rhs) { Base::operator=(rhs); return *this; } set& operator=(set&& rhs) { Base::operator=(tiny_stl::move(rhs)); return *this; } set& operator=(std::initializer_list<value_type> ilist) { set tmp(ilist); this->swap(tmp); return *this; } pair<iterator, bool> insert(const value_type& val) { return this->insert_unique(val); } pair<iterator, bool> insert(value_type&& val) { return this->insert_unique(tiny_stl::move(val)); } template <typename InIter> void insert(InIter first, InIter last) { this->insert_unique(first, last); } void insert(std::initializer_list<value_type> ilist) { this->insert_unique(ilist.begin(), ilist.end()); } template <typename... Args> pair<iterator, bool> emplace(Args&&... args) { return this->emplace_unique(tiny_stl::forward<Args>(args)...); } void swap(set& rhs) { Base::swap(rhs); } key_compare key_comp() const { return key_compare{}; } value_compare value_comp() const { return value_compare{}; } }; template <typename Key, typename Compare, typename Alloc> inline void swap(set<Key, Compare, Alloc>& lhs, set<Key, Compare, Alloc>& rhs) noexcept(noexcept(lhs.swap(rhs))) { lhs.swap(rhs); } template <typename Key, typename Compare = tiny_stl::less<Key>, typename Alloc = tiny_stl::allocator<Key>> class multiset : public RBTree<Key, Compare, Alloc, false> { public: using allocator_type = Alloc; private: using Base = RBTree<Key, Compare, allocator_type, false>; using AlTraits = allocator_traits<allocator_type>; using AlNode = typename Base::AlNode; using AlNodeTraits = typename Base::AlNodeTraits; public: using key_type = Key; using value_type = Key; using size_type = std::size_t; using difference_type = std::ptrdiff_t; using key_compare = Compare; using value_compare = Compare; using reference = value_type&; using const_reference = const value_type&; using pointer = typename AlTraits::pointer; using const_pointer = typename AlTraits::const_pointer; using iterator = typename Base::iterator; using const_iterator = typename Base::const_iterator; using reverse_iterator = typename Base::reverse_iterator; using const_reverse_iterator = typename Base::const_reverse_iterator; public: multiset() : multiset(Compare()) { } explicit multiset(const Compare& cmp, const Alloc& alloc = Alloc()) : Base(cmp, alloc) { } explicit multiset(const Alloc& alloc) : Base(key_compare(), alloc) { } template <typename InIter> multiset(InIter first, InIter last, const key_compare& cmp, const Alloc& alloc = Alloc()) : Base(cmp, alloc) { this->insert_equal(first, last); } template <typename InIter> multiset(InIter first, InIter last, const Alloc& alloc) : Base(key_compare(), alloc) { this->insert_equal(first, last); } multiset(const multiset& rhs) : Base(rhs, AlTraits::select_on_container_copy_construction( rhs.get_allocator())) { } multiset(const multiset& rhs, const Alloc& alloc) : Base(rhs, alloc) { } multiset(multiset&& rhs) : Base(tiny_stl::move(rhs)) { } multiset(multiset&& rhs, const Alloc& alloc) : Base(tiny_stl::move(rhs), alloc) { } multiset(std::initializer_list<value_type> ilist, const Compare& cmp = Compare(), const Alloc& alloc = Alloc()) : Base(cmp, alloc) { this->insert_equal(ilist.begin(), ilist.end()); } multiset(std::initializer_list<value_type> ilist, const Alloc& alloc) : multiset(ilist, Compare(), alloc) { } multiset& operator=(const multiset& rhs) { Base::operator=(rhs); return *this; } multiset& operator=(multiset&& rhs) { Base::operator=(tiny_stl::move(rhs)); return *this; } multiset& operator=(std::initializer_list<value_type> ilist) { multiset tmp(ilist); this->swap(tmp); return *this; } iterator insert(const value_type& val) { return this->insert_equal(val); } iterator insert(value_type&& val) { return this->insert_equal(tiny_stl::move(val)); } template <typename InIter> void insert(InIter first, InIter last) { this->insert_equal(first, last); } void insert(std::initializer_list<value_type> ilist) { this->insert_equal(ilist.begin(), ilist.end()); } template <typename... Args> iterator emplace(Args&&... args) { return this->insert_equal(tiny_stl::forward<Args>(args)...); } void swap(multiset& rhs) { Base::swap(rhs); } key_compare key_comp() const { return key_compare{}; } value_compare value_comp() const { return value_compare{}; } }; template <typename Key, typename Compare, typename Alloc> inline void swap(multiset<Key, Compare, Alloc>& lhs, multiset<Key, Compare, Alloc>& rhs) noexcept(noexcept(lhs.swap(rhs))) { lhs.swap(rhs); } }
 #pragma once #include "rbtree.hpp" namespace tiny_stl { template <typename Key, typename Compare = tiny_stl::less<Key>, typename Alloc = tiny_stl::allocator<Key>> class set : public RBTree<Key, Compare, Alloc, false> { public: using allocator_type = Alloc; private: using Base = RBTree<Key, Compare, allocator_type, false>; using AlTraits = allocator_traits<allocator_type>; using AlNode = typename Base::AlNode; using AlNodeTraits = typename Base::AlNodeTraits; public: using key_type = Key; using value_type = Key; using size_type = typename Alloc::size_type; using difference_type = typename Alloc::difference_type; using key_compare = Compare; using value_compare = Compare; using reference = value_type&; using const_reference = const value_type&; using pointer = typename AlTraits::pointer; using const_pointer = typename AlTraits::const_pointer; using iterator = typename Base::iterator; using const_iterator = typename Base::const_iterator; using reverse_iterator = typename Base::reverse_iterator; using const_reverse_iterator = typename Base::const_reverse_iterator; public: set() : set(Compare()) { } explicit set(const Compare& cmp, const Alloc& alloc = Alloc()) : Base(cmp, alloc) { } explicit set(const Alloc& alloc) : Base(key_compare(), alloc) { } template <typename InIter> set(InIter first, InIter last, const key_compare& cmp, const Alloc& alloc = Alloc()) : Base(cmp, alloc) { this->insert_unique(first, last); } template <typename InIter> set(InIter first, InIter last, const Alloc& alloc) : Base(key_compare(), alloc) { this->insert_unique(first, last); } set(const set& rhs) : Base(rhs, AlTraits::select_on_container_copy_construction( rhs.get_allocator())) { } set(const set& rhs, const Alloc& alloc) : Base(rhs, alloc) { } set(set&& rhs) : Base(tiny_stl::move(rhs)) { } set(set&& rhs, const Alloc& alloc) : Base(tiny_stl::move(rhs), alloc) { } set(std::initializer_list<value_type> ilist, const Compare& cmp = Compare(), const Alloc& alloc = Alloc()) : Base(cmp, alloc) { this->insert_unique(ilist.begin(), ilist.end()); } set(std::initializer_list<value_type> ilist, const Alloc& alloc) : set(ilist, Compare(), alloc) { } set& operator=(const set& rhs) { Base::operator=(rhs); return *this; } set& operator=(set&& rhs) { Base::operator=(tiny_stl::move(rhs)); return *this; } set& operator=(std::initializer_list<value_type> ilist) { set tmp(ilist); this->swap(tmp); return *this; } pair<iterator, bool> insert(const value_type& val) { return this->insert_unique(val); } pair<iterator, bool> insert(value_type&& val) { return this->insert_unique(tiny_stl::move(val)); } template <typename InIter> void insert(InIter first, InIter last) { this->insert_unique(first, last); } void insert(std::initializer_list<value_type> ilist) { this->insert_unique(ilist.begin(), ilist.end()); } template <typename... Args> pair<iterator, bool> emplace(Args&&... args) { return this->emplace_unique(tiny_stl::forward<Args>(args)...); } void swap(set& rhs) { Base::swap(rhs); } key_compare key_comp() const { return key_compare{}; } value_compare value_comp() const { return value_compare{}; } }; template <typename Key, typename Compare, typename Alloc> inline void swap(set<Key, Compare, Alloc>& lhs, set<Key, Compare, Alloc>& rhs) noexcept(noexcept(lhs.swap(rhs))) { lhs.swap(rhs); } template <typename Key, typename Compare = tiny_stl::less<Key>, typename Alloc = tiny_st
ltiset<Key, Compare, Alloc>& rhs) noexcept(noexcept(lhs.swap(rhs))) { lhs.swap(rhs); } }
l::allocator<Key>> class multiset : public RBTree<Key, Compare, Alloc, false> { public: using allocator_type = Alloc; private: using Base = RBTree<Key, Compare, allocator_type, false>; using AlTraits = allocator_traits<allocator_type>; using AlNode = typename Base::AlNode; using AlNodeTraits = typename Base::AlNodeTraits; public: using key_type = Key; using value_type = Key; using size_type = std::size_t; using difference_type = std::ptrdiff_t; using key_compare = Compare; using value_compare = Compare; using reference = value_type&; using const_reference = const value_type&; using pointer = typename AlTraits::pointer; using const_pointer = typename AlTraits::const_pointer; using iterator = typename Base::iterator; using const_iterator = typename Base::const_iterator; using reverse_iterator = typename Base::reverse_iterator; using const_reverse_iterator = typename Base::const_reverse_iterator; public: multiset() : multiset(Compare()) { } explicit multiset(const Compare& cmp, const Alloc& alloc = Alloc()) : Base(cmp, alloc) { } explicit multiset(const Alloc& alloc) : Base(key_compare(), alloc) { } template <typename InIter> multiset(InIter first, InIter last, const key_compare& cmp, const Alloc& alloc = Alloc()) : Base(cmp, alloc) { this->insert_equal(first, last); } template <typename InIter> multiset(InIter first, InIter last, const Alloc& alloc) : Base(key_compare(), alloc) { this->insert_equal(first, last); } multiset(const multiset& rhs) : Base(rhs, AlTraits::select_on_container_copy_construction( rhs.get_allocator())) { } multiset(const multiset& rhs, const Alloc& alloc) : Base(rhs, alloc) { } multiset(multiset&& rhs) : Base(tiny_stl::move(rhs)) { } multiset(multiset&& rhs, const Alloc& alloc) : Base(tiny_stl::move(rhs), alloc) { } multiset(std::initializer_list<value_type> ilist, const Compare& cmp = Compare(), const Alloc& alloc = Alloc()) : Base(cmp, alloc) { this->insert_equal(ilist.begin(), ilist.end()); } multiset(std::initializer_list<value_type> ilist, const Alloc& alloc) : multiset(ilist, Compare(), alloc) { } multiset& operator=(const multiset& rhs) { Base::operator=(rhs); return *this; } multiset& operator=(multiset&& rhs) { Base::operator=(tiny_stl::move(rhs)); return *this; } multiset& operator=(std::initializer_list<value_type> ilist) { multiset tmp(ilist); this->swap(tmp); return *this; } iterator insert(const value_type& val) { return this->insert_equal(val); } iterator insert(value_type&& val) { return this->insert_equal(tiny_stl::move(val)); } template <typename InIter> void insert(InIter first, InIter last) { this->insert_equal(first, last); } void insert(std::initializer_list<value_type> ilist) { this->insert_equal(ilist.begin(), ilist.end()); } template <typename... Args> iterator emplace(Args&&... args) { return this->insert_equal(tiny_stl::forward<Args>(args)...); } void swap(multiset& rhs) { Base::swap(rhs); } key_compare key_comp() const { return key_compare{}; } value_compare value_comp() const { return value_compare{}; } }; template <typename Key, typename Compare, typename Alloc> inline void swap(multiset<Key, Compare, Alloc>& lhs, mu
random
[ { "content": "class unordered_set : public HashTable<Key, Hash, KeyEqual, Alloc, false> {\n\npublic:\n\n using allocator_type = Alloc;\n\nprivate:\n\n using Base = HashTable<Key, Hash, KeyEqual, Alloc, false>;\n\n using AlTraits = allocator_traits<allocator_type>;\n\n\n\npublic:\n\n using key_type = Key;\n\n using value_type = Key;\n\n using size_type = typename Alloc::size_type;\n\n using difference_type = typename Alloc::difference_type;\n\n using hasher = Hash;\n\n using key_equal = KeyEqual;\n\n using reference = value_type&;\n\n using const_reference = const value_type&;\n\n using pointer = typename AlTraits::pointer;\n\n using const_pointer = typename AlTraits::const_pointer;\n\n using iterator = typename Base::iterator;\n\n using const_iterator = typename Base::const_iterator;\n", "file_path": "TinySTL/unordered_set.hpp", "rank": 2, "score": 229541.25398223544 }, { "content": "struct GetConstVoidPointer<Alloc, void_t<typename Alloc::const_void_pointer>> {\n\n using type = typename Alloc::const_void_pointer;\n\n};\n\n\n\ntemplate <typename Alloc, typename = void>\n", "file_path": "TinySTL/memory.hpp", "rank": 3, "score": 222928.6453870218 }, { "content": "class unordered_multiset : public HashTable<Key, Hash, KeyEqual, Alloc, false> {\n\npublic:\n\n using allocator_type = Alloc;\n\nprivate:\n\n using Base = HashTable<Key, Hash, KeyEqual, Alloc, false>;\n\n using AlTraits = allocator_traits<allocator_type>;\n\n\n\npublic:\n\n using key_type = Key;\n\n using value_type = Key;\n\n using size_type = std::size_t;\n\n using difference_type = std::ptrdiff_t;\n\n using hasher = Hash;\n\n using key_equal = KeyEqual;\n\n using reference = value_type&;\n\n using const_reference = const value_type&;\n\n using pointer = typename AlTraits::pointer;\n\n using const_pointer = typename AlTraits::const_pointer;\n\n using iterator = typename Base::iterator;\n\n using const_iterator = typename Base::const_iterator;\n", "file_path": "TinySTL/unordered_set.hpp", "rank": 4, "score": 217479.77995633535 }, { "content": "struct GetConstPointer<Alloc, void_t<typename Alloc::const_pointer>> {\n\n using type = typename Alloc::const_pointer;\n\n};\n\n\n\ntemplate <typename Alloc, typename = void>\n", "file_path": "TinySTL/memory.hpp", "rank": 5, "score": 213198.62056921603 }, { "content": "class map : public RBTree<pair<Key, T>, Compare, Alloc, true> {\n\npublic:\n\n using allocator_type = Alloc;\n\n\n\nprivate:\n\n using Base = RBTree<pair<Key, T>, Compare, Alloc, true>;\n\n using AlTraits = allocator_traits<allocator_type>;\n\n using AlNode = typename Base::AlNode;\n\n using AlNodeTraits = typename Base::AlNodeTraits;\n\n\n\npublic:\n\n using key_type = Key;\n\n using mapped_type = T;\n\n using value_type = pair<const Key, T>;\n\n using size_type = typename Alloc::size_type;\n\n using difference_type = typename Alloc::difference_type;\n\n using key_compare = Compare;\n\n using reference = value_type&;\n\n using const_reference = const value_type&;\n\n using pointer = typename AlTraits::pointer;\n\n using const_pointer = typename AlTraits::const_pointer;\n\n using iterator = typename Base::iterator;\n\n using const_iterator = typename Base::const_iterator;\n\n using reverse_iterator = typename Base::reverse_iterator;\n\n using const_reverse_iterator = typename Base::const_reverse_iterator;\n\n\n\npublic:\n", "file_path": "TinySTL/map.hpp", "rank": 6, "score": 209349.18585841084 }, { "content": "class multimap : public RBTree<pair<Key, T>, Compare, Alloc, true> {\n\npublic:\n\n using allocator_type = Alloc;\n\n\n\nprivate:\n\n using Base = RBTree<pair<Key, T>, Compare, Alloc, true>;\n\n using AlNode = typename Base::AlNode;\n\n using AlNodeTraits = typename Base::AlNodeTraits;\n\n using AlTraits = allocator_traits<allocator_type>;\n\n\n\npublic:\n\n using key_type = Key;\n\n using mapped_type = T;\n\n using value_type = pair<const Key, T>;\n\n using size_type = std::size_t;\n\n using difference_type = std::ptrdiff_t;\n\n using key_compare = Compare;\n\n using reference = value_type&;\n\n using const_reference = const value_type&;\n\n using pointer = typename AlTraits::pointer;\n\n using const_pointer = typename AlTraits::const_pointer;\n\n using iterator = typename Base::iterator;\n\n using const_iterator = typename Base::const_iterator;\n\n using reverse_iterator = typename Base::reverse_iterator;\n\n using const_reverse_iterator = typename Base::const_reverse_iterator;\n\n\n\npublic:\n", "file_path": "TinySTL/map.hpp", "rank": 7, "score": 209349.18585841087 }, { "content": "class RBTree : public RBTreeBase<T, Compare, Alloc> {\n\npublic:\n\n using key_type = typename AssociatedTypeHelper<T, isMap>::key_type;\n\n using mapped_type = typename AssociatedTypeHelper<T, isMap>::mapped_type;\n\n using value_type = T;\n\n using key_compare = Compare; // if it is map, compare pair\n\n using allocator_type = Alloc;\n\n using size_type = std::size_t;\n\n using difference_type = std::ptrdiff_t;\n\n using reference = value_type&;\n\n using const_reference = const value_type&;\n\n using pointer = value_type*;\n\n using const_pointer = const value_type*;\n\n\n\n using AlTraits = allocator_traits<Alloc>;\n\n using Node = RBTNode<value_type>;\n\n using NodePtr = RBTNode<value_type>*;\n\n using AlNode = typename AlTraits::template rebind_alloc<Node>;\n\n using AlNodeTraits = allocator_traits<AlNode>;\n\n using Base = RBTreeBase<value_type, Compare, Alloc>;\n", "file_path": "TinySTL/rbtree.hpp", "rank": 8, "score": 208657.66219058193 }, { "content": "struct GetPointer<Alloc, void_t<typename Alloc::pointer>> {\n\n using type = typename Alloc::pointer;\n\n};\n\n\n\ntemplate <typename Alloc, typename = void>\n", "file_path": "TinySTL/memory.hpp", "rank": 9, "score": 201631.56469724144 }, { "content": "class vector : public VectorBase<T, Alloc> {\n\npublic:\n\n static_assert(tiny_stl::is_same_v<T, typename Alloc::value_type>,\n\n \"Alloc::value_type is not the same as T\");\n\n\n\nprivate:\n\n using Base = VectorBase<T, Alloc>;\n\n\n\npublic:\n\n using allocator_type = typename Base::allocator_type;\n\n using size_type = typename Base::size_type;\n\n using difference_type = typename Base::difference_type;\n\n using pointer = typename Base::pointer;\n\n using const_pointer = typename Base::const_pointer;\n\n using reference = typename Base::reference;\n\n using const_reference = typename Base::const_reference;\n\n using iterator = typename Base::iterator;\n\n using const_iterator = typename Base::const_iterator;\n\n using reverse_iterator = tiny_stl::reverse_iterator<iterator>;\n\n using const_reverse_iterator = tiny_stl::reverse_iterator<const_iterator>;\n", "file_path": "TinySTL/vector.hpp", "rank": 10, "score": 197716.7313456427 }, { "content": "class list : public ListBase<T, Alloc> {\n\npublic:\n\n using value_type = T;\n\n using allocator_type = Alloc; // In fact, will be not be used\n\n using size_type = typename Alloc::size_type;\n\n using difference_type = typename Alloc::difference_type;\n\n using reference = T&;\n\n using const_reference = const T&;\n\n using pointer = typename allocator_traits<Alloc>::pointer;\n\n using const_pointer = typename allocator_traits<Alloc>::const_pointer;\n\n using iterator = ListIterator<T>;\n\n using const_iterator = ListConstIterator<T>;\n\n using reverse_iterator = tiny_stl::reverse_iterator<iterator>;\n\n using const_reverse_iterator = tiny_stl::reverse_iterator<const_iterator>;\n\n\n\n using Base = ListBase<T, Alloc>;\n\n using Node = LNode<T>;\n\n using NodePtr = LNode<T>*;\n\n using AlNode =\n\n typename allocator_traits<Alloc>::template rebind_alloc<Node>;\n", "file_path": "TinySTL/list.hpp", "rank": 11, "score": 197716.7313456427 }, { "content": "class deque : public DequeBase<T, Alloc> {\n\npublic:\n\n static_assert(is_same<T, typename Alloc::value_type>::value,\n\n \"Allocator::value_type is not the same as T\");\n\n\n\npublic:\n\n using value_type = T;\n\n using allocator_type = Alloc;\n\n using size_type = typename Alloc::size_type;\n\n using difference_type = typename Alloc::difference_type;\n\n using pointer = T*;\n\n using const_pointer = const T*;\n\n using reference = T&;\n\n using const_reference = const T&;\n\n using iterator = DequeIterator<T>;\n\n using const_iterator = DequeConstIterator<T>;\n\n using reverse_iterator = tiny_stl::reverse_iterator<iterator>;\n\n using const_reverse_iterator = tiny_stl::reverse_iterator<const_iterator>;\n\n\n\nprotected:\n", "file_path": "TinySTL/deque.hpp", "rank": 12, "score": 197716.7313456427 }, { "content": "struct GetVoidPointer<Alloc, void_t<typename Alloc::void_pointer>> {\n\n using type = typename Alloc::void_pointer;\n\n};\n\n\n\ntemplate <typename Alloc, typename = void>\n", "file_path": "TinySTL/memory.hpp", "rank": 13, "score": 190821.20249442538 }, { "content": "class allocator<void> {\n\npublic:\n\n using value_type = void;\n\n using pointer = void*;\n\n using const_pointer = const void*;\n\n\n\n template <class U>\n\n struct rebind {\n\n using other = allocator<U>;\n\n };\n\n\n\npublic:\n\n allocator() noexcept {\n\n }\n\n allocator(const allocator<void>&) noexcept {\n\n }\n\n\n\n template <typename Other>\n\n allocator(const allocator<Other>&) noexcept {\n\n }\n", "file_path": "TinySTL/allocators.hpp", "rank": 14, "score": 186142.1879838803 }, { "content": "class forward_list : public FListBase<T, Alloc> {\n\npublic:\n\n static_assert(is_same<T, typename Alloc::value_type>::value,\n\n \"Alloc::value_type is not the same as T\");\n\n\n\npublic:\n\n using value_type = T;\n\n using allocator_type = Alloc;\n\n using size_type = typename Alloc::size_type;\n\n using difference_type = typename Alloc::difference_type;\n\n using reference = T&;\n\n using const_reference = const T&;\n\n using pointer = typename allocator_traits<Alloc>::pointer;\n\n using const_pointer = typename allocator_traits<Alloc>::pointer;\n\n using iterator = FListIterator<T>;\n\n using const_iterator = FListConstIterator<T>;\n\n\n\n using Base = FListBase<T, Alloc>;\n\n using Self = forward_list<T, Alloc>;\n\n using Node = FLNode<T>;\n", "file_path": "TinySTL/forward_list.hpp", "rank": 15, "score": 184830.09994259302 }, { "content": "class ArrayIterator : public ArrayConstIterator<T, Size> {\n\nprivate:\n\n using Base = ArrayConstIterator<T, Size>;\n\n\n\npublic:\n\n using pointer = T*;\n\n using reference = T&;\n\n\n\n constexpr ArrayIterator() {\n\n }\n\n\n\n constexpr explicit ArrayIterator(pointer p, std::ptrdiff_t offset)\n\n : Base(p, offset) {\n\n }\n\n\n\n constexpr reference operator*() const {\n\n return const_cast<reference>(Base::operator*());\n\n }\n\n\n\n constexpr pointer operator->() const {\n", "file_path": "TinySTL/array.hpp", "rank": 16, "score": 177886.784562175 }, { "content": "class RefCountResourceAlloc : public RefCountBase {\n\nprivate:\n\n // allocator<RefCountResourceAlloc>\n\n using AllocType = GetAllocBindType<Alloc, RefCountResourceAlloc>;\n\n\n\npublic:\n\n RefCountResourceAlloc(T p, D d, const Alloc& alloc) : RefCountBase() {\n\n }\n\n\n\n virtual void*\n\n getDeleter(const std::type_info& type) const noexcept override {\n\n if (type == typeid(D)) {\n\n return const_cast<D*>(tiny_stl::addressof(mPair.get_first()));\n\n }\n\n\n\n return nullptr;\n\n }\n\n\n\nprivate:\n\n virtual void destroyAux() noexcept override {\n", "file_path": "TinySTL/memory.hpp", "rank": 17, "score": 175177.37256280586 }, { "content": "class RefCountObjAlloc : public RefCountBase {\n\npublic:\n\n template <typename... Args>\n\n explicit RefCountObjAlloc(const Alloc& al, Args&&... args) {\n\n ::new (static_cast<void*>(&mPair.get_second()))\n\n T(tiny_stl::forward<Args>(args)...);\n\n }\n\n\n\n T* getPtr() {\n\n return reinterpret_cast<T*>(&mPair.get_second());\n\n }\n\n\n\nprivate:\n\n using AllocType = typename allocator_traits<Alloc>::template rebind_alloc<\n\n RefCountObjAlloc>;\n\n\n\n void destroyAux() noexcept override {\n\n getPtr()->~T();\n\n }\n\n\n", "file_path": "TinySTL/memory.hpp", "rank": 18, "score": 175177.37256280586 }, { "content": "struct HasAllocateHint<Alloc, Size_type, Const_void_pointer,\n\n void_t<decltype(tiny_stl::declval<Alloc&>().allocate(\n\n tiny_stl::declval<const Size_type&>(),\n\n tiny_stl::declval<const Const_void_pointer&>()))>>\n\n : true_type {};\n\n\n\ntemplate <typename Alloc, typename = void>\n", "file_path": "TinySTL/memory.hpp", "rank": 19, "score": 157463.40232567565 }, { "content": "class RefCount : public RefCountBase {\n\npublic:\n\n explicit RefCount(T* p) : RefCountBase(), mPtr(p) {\n\n }\n\n\n\nprivate:\n\n virtual void destroyAux() noexcept override {\n\n delete mPtr;\n\n }\n\n\n\n virtual void deleteThis() noexcept override {\n\n delete this;\n\n }\n\n\n\nprivate:\n\n T* mPtr;\n\n};\n\n\n\n// handle reference counting for object with deleter\n\ntemplate <typename T, typename D>\n", "file_path": "TinySTL/memory.hpp", "rank": 20, "score": 151812.177126407 }, { "content": "class RefCountResource : public RefCountBase {\n\npublic:\n\n RefCountResource(T p, D d) : RefCountBase(), mPair(tiny_stl::move(d), p) {\n\n }\n\n\n\n virtual void*\n\n getDeleter(const std::type_info& type) const noexcept override {\n\n if (type.hash_code() == typeid(D).hash_code()) {\n\n return const_cast<D*>(tiny_stl::addressof(mPair.get_first()));\n\n }\n\n\n\n return nullptr;\n\n }\n\n\n\nprivate:\n\n virtual void destroyAux() noexcept override {\n\n mPair.get_first()(mPair.get_second());\n\n }\n\n\n\n virtual void deleteThis() noexcept override {\n\n delete this;\n\n }\n\n\n\nprivate:\n\n extra::compress_pair<D, T> mPair;\n\n};\n\n\n\n// handle refernece counting for object with deleter and allocator\n\ntemplate <typename T, typename D, typename Alloc>\n", "file_path": "TinySTL/memory.hpp", "rank": 21, "score": 148359.75812723447 }, { "content": "class RefCountObj : public RefCountBase {\n\npublic:\n\n template <typename... Args>\n\n explicit RefCountObj(Args&&... args) noexcept : RefCountBase(), mStroage() {\n\n ::new (static_cast<void*>(&mStroage)) T(tiny_stl::forward<T>(args)...);\n\n }\n\n\n\n T* getPtr() {\n\n return reinterpret_cast<T*>(&mStroage);\n\n }\n\n\n\nprivate:\n\n void destroyAux() noexcept override {\n\n getPtr()->~T();\n\n }\n\n\n\n void deleteThis() noexcept override {\n\n delete this;\n\n }\n\n\n", "file_path": "TinySTL/memory.hpp", "rank": 22, "score": 148359.7581272345 }, { "content": "class shared_ptr : public PtrBase<T> {\n\npublic:\n\n#ifdef TINY_STL_CXX17\n\n using weak_type = weak_ptr<T>;\n\n#endif // TINY_STL_CXX17\n\n using element_type = typename PtrBase<T>::element_type;\n\n\n\n constexpr shared_ptr() noexcept {\n\n }\n\n\n\n constexpr shared_ptr(std::nullptr_t) noexcept {\n\n }\n\n\n\n // no C++17, in other words, no shared_ptr<T[]>\n\n // TODO: support C++17\n\n template <typename U, enable_if_t<is_convertible_v<U*, T*>, int> = 0>\n\n explicit shared_ptr(U* ptr) {\n\n setPtr(ptr);\n\n }\n\n\n", "file_path": "TinySTL/memory.hpp", "rank": 23, "score": 146733.80431678682 }, { "content": "class weak_ptr : public PtrBase<T> {\n\npublic:\n\n constexpr weak_ptr() noexcept {\n\n }\n\n\n\n weak_ptr(const weak_ptr& rhs) noexcept {\n\n this->weaklyConstructFrom(rhs);\n\n }\n\n\n\n // TODO\n\n template <typename U, enable_if_t<is_convertible_v<U*, T*>, int> = 0>\n\n weak_ptr(const weak_ptr<U>& rhs) noexcept {\n\n this->weaklyConstructFrom(rhs.lock());\n\n }\n\n\n\n template <typename U, enable_if_t<is_convertible_v<U*, T*>, int> = 0>\n\n weak_ptr(const shared_ptr<U>& rhs) noexcept {\n\n this->weaklyConstructFrom(rhs);\n\n }\n\n\n", "file_path": "TinySTL/memory.hpp", "rank": 24, "score": 146733.80431678682 }, { "content": "class ArrayConstIterator {\n\npublic:\n\n using iterator_category = random_access_iterator_tag;\n\n using value_type = T;\n\n using difference_type = std::ptrdiff_t;\n\n using pointer = const T*;\n\n using reference = const T&;\n\n\n\npublic:\n\n#ifndef NDEBUG // DEBUG\n\n pointer ptr;\n\n std::size_t idx;\n\n\n\n constexpr ArrayConstIterator() : ptr(nullptr), idx(0) {\n\n }\n\n\n\n constexpr explicit ArrayConstIterator(pointer p, std::size_t offset = 0)\n\n : ptr(p), idx(offset) {\n\n }\n\n\n", "file_path": "TinySTL/array.hpp", "rank": 25, "score": 142923.2912528458 }, { "content": "struct GetIsAlwaysEqual<Alloc, void_t<typename Alloc::is_always_equal>> {\n\n using type = typename Alloc::is_always_equal;\n\n};\n\n\n\ntemplate <typename Alloc, typename Other, typename = void>\n", "file_path": "TinySTL/memory.hpp", "rank": 26, "score": 130754.7604094799 }, { "content": "struct GetSizeType<Alloc, void_t<typename Alloc::size_type>> {\n\n using type = typename Alloc::size_type;\n\n};\n\n\n\ntemplate <typename Alloc, typename = void>\n", "file_path": "TinySTL/memory.hpp", "rank": 27, "score": 130754.7604094799 }, { "content": "struct GetDifferenceType<Alloc, void_t<typename Alloc::difference_type>> {\n\n using type = typename Alloc::difference_type;\n\n};\n\n\n\ntemplate <typename Alloc, typename = void>\n", "file_path": "TinySTL/memory.hpp", "rank": 28, "score": 130754.7604094799 }, { "content": "struct HasAllocatorType<Con, Alloc, void_t<typename Con::allocator_type>>\n\n : is_convertible<Alloc, typename Con::allocator_type>::type {};\n\n\n\ntemplate <typename Alloc, typename ValueType>\n\nusing RebindAllocType =\n\n typename allocator_traits<Alloc>::template rebind_alloc<ValueType>;\n\n\n\ntemplate <typename Con, typename Alloc>\n", "file_path": "TinySTL/memory.hpp", "rank": 29, "score": 125665.54117049935 }, { "content": "class allocator {\n\npublic:\n\n using value_type = T;\n\n using pointer = T*;\n\n using const_pointer = const T*;\n\n using reference = T&;\n\n using const_reference = const T&;\n\n using size_type = std::size_t;\n\n using difference_type = std::ptrdiff_t;\n\n\n\n using propagate_on_container_move_assignment = tiny_stl::true_type; // c++14\n\n using is_always_equal = tiny_stl::true_type; // c++17\n\n\n\n using NotUserSpecialized = void;\n\n\n\npublic:\n\n allocator() noexcept {\n\n } // do nothing\n\n allocator(const allocator<T>&) noexcept {\n\n }\n", "file_path": "TinySTL/allocators.hpp", "rank": 30, "score": 124394.85820400473 }, { "content": "struct uses_allocator<priority_queue<T, Container, Compare>, Alloc>\n\n : tiny_stl::uses_allocator<Container, Alloc>::type {};\n\n\n\n} // namespace tiny_stl\n", "file_path": "TinySTL/queue.hpp", "rank": 31, "score": 123681.3601483766 }, { "content": "class reverse_iterator {\n\nprotected:\n\n Iter current;\n\n\n\npublic:\n\n using iterator_category = typename iterator_traits<Iter>::iterator_category;\n\n using value_type = typename iterator_traits<Iter>::value_type;\n\n using difference_type = typename iterator_traits<Iter>::difference_type;\n\n using pointer = typename iterator_traits<Iter>::pointer;\n\n using reference = typename iterator_traits<Iter>::reference;\n\n using iterator_type = Iter;\n\n using Self = reverse_iterator<Iter>;\n\n\n\npublic:\n\n constexpr reverse_iterator() : current() {\n\n }\n\n constexpr explicit reverse_iterator(iterator_type x) : current(x) {\n\n }\n\n\n\n template <typename Other>\n", "file_path": "TinySTL/iterator.hpp", "rank": 32, "score": 121197.03773854143 }, { "content": "class move_iterator {\n\nprotected:\n\n Iter current;\n\n\n\npublic:\n\n using iterator_type = Iter;\n\n using iterator_category = typename iterator_traits<Iter>::iterator_category;\n\n using value_type = typename iterator_traits<Iter>::value_type;\n\n using difference_type = typename iterator_traits<Iter>::difference_type;\n\n using pointer = Iter;\n\n using reference = value_type&&;\n\n\n\n constexpr move_iterator() : current() {\n\n }\n\n\n\n constexpr explicit move_iterator(Iter iter) : current(iter) {\n\n }\n\n\n\n template <typename Other>\n\n constexpr move_iterator(const move_iterator<Other>& rhs)\n", "file_path": "TinySTL/iterator.hpp", "rank": 33, "score": 121197.03773854143 }, { "content": "struct IteratorTraitsPointerBase {\n\n using iterator_category = random_access_iterator_tag;\n\n using value_type = remove_cv_t<T>;\n\n using difference_type = std::ptrdiff_t;\n\n using pointer = T*;\n\n using reference = T&;\n\n};\n\n\n\ntemplate <typename Iter>\n", "file_path": "TinySTL/iterator.hpp", "rank": 34, "score": 116439.5903611782 }, { "content": "struct iterator_traits : IteratorTraitsBase<Iter> {};\n\n\n\ntemplate <typename T>\n", "file_path": "TinySTL/iterator.hpp", "rank": 35, "score": 114634.77772572864 }, { "content": "struct is_iterator<T, void_t<typename iterator_traits<T>::iterator_category>>\n\n : true_type {};\n\n\n\ntemplate <typename T>\n\nconstexpr bool is_iterator_v = is_iterator<T>::value;\n\n\n\nnamespace details {\n\n\n\ntemplate <typename Iter>\n\ninline typename iterator_traits<Iter>::category iterator_category(const Iter&) {\n\n using category = typename iterator_traits<Iter>::iterator_category;\n\n return category{};\n\n}\n\n\n\ntemplate <typename Iter>\n\ninline typename iterator_traits<Iter>::difference_type*\n\ndistance_type(const Iter&) {\n\n return static_cast<typename iterator_traits<Iter>::difference*>(0);\n\n}\n\n\n", "file_path": "TinySTL/iterator.hpp", "rank": 36, "score": 110184.06709032202 }, { "content": " class value_compare {\n\n friend multimap;\n\n\n\n protected:\n\n Compare mCmp;\n\n\n\n value_compare(Compare c) : mCmp(c) {\n\n }\n\n\n\n public:\n\n bool operator()(const value_type& lhs, const value_type& rhs) const {\n\n return mCmp(lhs.first, rhs.first);\n\n }\n\n };\n\n\n\npublic:\n\n multimap() : multimap(Compare()) {\n\n }\n\n explicit multimap(const Compare& cmp, const Alloc& alloc = Alloc())\n\n : Base(cmp, alloc) {\n", "file_path": "TinySTL/map.hpp", "rank": 37, "score": 110000.05185478431 }, { "content": "class VectorBase {\n\npublic:\n\n using value_type = T;\n\n using size_type = typename Alloc::size_type;\n\n using difference_type = typename Alloc::difference_type;\n\n using pointer = T*;\n\n using const_pointer = const T*;\n\n using reference = T&;\n\n using const_reference = const T&;\n\n using iterator = VectorIterator<T>;\n\n using const_iterator = VectorConstIterator<T>;\n\n using reverse_iterator = tiny_stl::reverse_iterator<iterator>;\n\n using const_reverse_iterator = tiny_stl::reverse_iterator<const_iterator>;\n\n using allocator_type = Alloc;\n\n\n\nprotected:\n\n allocator_type alloc;\n\n\n\n T* first;\n\n T* last;\n", "file_path": "TinySTL/vector.hpp", "rank": 38, "score": 109910.64969484392 }, { "content": "class PtrBase {\n\npublic:\n\n#ifdef TINY_STL_CXX17\n\n using element_type = remove_extent_t<T>;\n\n#else\n\n using element_type = T;\n\n#endif // TINY_STL_CXX17\n\n\n\npublic:\n\n long use_count() const noexcept {\n\n return mRep ? mRep->useCount() : 0;\n\n }\n\n\n\n template <typename U>\n\n bool owner_before(const PtrBase<U>& rhs) const noexcept {\n\n // compare the be managed object pointer\n\n return mPtr < rhs.mPtr;\n\n }\n\n\n\n element_type* get() const noexcept {\n", "file_path": "TinySTL/memory.hpp", "rank": 39, "score": 109910.64969484392 }, { "content": "class ListBase {\n\npublic:\n\n using value_type = T;\n\n using allocator_type = Alloc; // In face, will be not be used\n\n using size_type = std::size_t;\n\n using difference_type = std::ptrdiff_t;\n\n using reference = T&;\n\n using const_reference = const T&;\n\n using pointer = typename allocator_traits<Alloc>::pointer;\n\n using const_pointer = typename allocator_traits<Alloc>::const_pointer;\n\n using iterator = ListIterator<T>;\n\n using const_iterator = ListConstIterator<T>;\n\n using reverse_iterator = tiny_stl::reverse_iterator<iterator>;\n\n using const_reverse_iterator = tiny_stl::reverse_iterator<const_iterator>;\n\n\n\n using Node = LNode<T>;\n\n using NodePtr = LNode<T>*;\n\n using AlNode =\n\n typename allocator_traits<Alloc>::template rebind_alloc<Node>;\n\n\n", "file_path": "TinySTL/list.hpp", "rank": 40, "score": 109910.64969484392 }, { "content": "class DequeBase {\n\npublic:\n\n using value_type = T;\n\n using allocator_type = Alloc;\n\n using size_type = std::size_t;\n\n using difference_type = std::ptrdiff_t;\n\n using pointer = T*;\n\n using const_pointer = const T*;\n\n using reference = T&;\n\n using const_reference = const T&;\n\n using iterator = DequeIterator<T>;\n\n using const_iterator = DequeConstIterator<T>;\n\n using reverse_iterator = tiny_stl::reverse_iterator<iterator>;\n\n using const_reverse_iterator = tiny_stl::reverse_iterator<const_iterator>;\n\n\n\nprotected:\n\n using MapPtr = pointer*;\n\n using AlPtr =\n\n typename allocator_traits<Alloc>::template rebind_alloc<pointer>;\n\n\n", "file_path": "TinySTL/deque.hpp", "rank": 41, "score": 109910.64969484392 }, { "content": "struct iterator_traits<T*> : IteratorTraitsPointerBase<T> {};\n\n\n\ntemplate <typename T, typename = void>\n", "file_path": "TinySTL/iterator.hpp", "rank": 42, "score": 108866.99140805309 }, { "content": "struct bidirectional_iterator_tag : public forward_iterator_tag {};\n", "file_path": "TinySTL/iterator.hpp", "rank": 43, "score": 108468.22521832304 }, { "content": "struct forward_iterator_tag : public input_iterator_tag {};\n", "file_path": "TinySTL/iterator.hpp", "rank": 44, "score": 108468.22521832304 }, { "content": "// reference count abstract base class\n\nclass RefCountBase {\n\nprotected:\n\n using AtomicCounterType = unsigned long;\n\n\n\nprivate:\n\n virtual void destroyAux() noexcept = 0;\n\n virtual void deleteThis() noexcept = 0;\n\n\n\nprivate:\n\n // assure use count operation is threads safe\n\n // why not use atomic\n\n std::atomic<AtomicCounterType> mUses;\n\n std::atomic<AtomicCounterType> mWeaks;\n\n\n\nprotected:\n\n // no-atomic initialization\n\n RefCountBase() : mUses(1), mWeaks(1) {\n\n }\n\n\n\npublic:\n", "file_path": "TinySTL/memory.hpp", "rank": 45, "score": 106778.25909253818 }, { "content": "class RBTreeBase {\n\npublic:\n\n using value_type = T;\n\n using allocator_type = Alloc;\n\n using size_type = typename Alloc::size_type;\n\n using difference_type = typename Alloc::difference_type;\n\n\n\nprivate:\n\n using AlTraits = allocator_traits<Alloc>;\n\n using Node = RBTNode<T>;\n\n using NodePtr = RBTNode<T>*;\n\n using AlNode = typename AlTraits::template rebind_alloc<Node>;\n\n using AlNodeTraits = allocator_traits<AlNode>;\n\n\n\nprotected:\n\n NodePtr header;\n\n size_type mCount;\n\n AlNode alloc;\n\n Compare compare;\n\n\n", "file_path": "TinySTL/rbtree.hpp", "rank": 46, "score": 106764.05727334181 }, { "content": "struct random_access_iterator_tag : public bidirectional_iterator_tag {};\n\n\n\ntemplate <typename T, typename Distance>\n", "file_path": "TinySTL/iterator.hpp", "rank": 47, "score": 106472.83434729476 }, { "content": "struct GetConstVoidPointer {\n\n using Ptr = typename GetPointer<Alloc>::type;\n\n using type = typename pointer_traits<Ptr>::template rebind<const void>;\n\n};\n\n\n\ntemplate <typename Alloc>\n", "file_path": "TinySTL/memory.hpp", "rank": 48, "score": 104648.24975950446 }, { "content": "class FListBase {\n\npublic:\n\n using Node = FLNode<T>;\n\n using NodePtr = FLNode<T>*;\n\n using AlNode =\n\n typename allocator_traits<Alloc>::template rebind_alloc<Node>;\n\n\n\nprotected:\n\n extra::compress_pair<AlNode, NodePtr> mPair;\n\n\n\n AlNode& getAlloc() noexcept {\n\n return mPair.get_first();\n\n }\n\n\n\n const AlNode& getAlloc() const noexcept {\n\n return mPair.get_first();\n\n }\n\n\n\n NodePtr& getHead() noexcept {\n\n return mPair.get_second();\n", "file_path": "TinySTL/forward_list.hpp", "rank": 49, "score": 103868.5572991414 }, { "content": "struct uses_allocator : HasAllocatorType<Con, Alloc>::type {};\n\n\n\ntemplate <typename Con, typename Alloc>\n\nconstexpr bool uses_allocator_value = uses_allocator<Con, Alloc>::value;\n\n\n\ntemplate <typename T>\n", "file_path": "TinySTL/memory.hpp", "rank": 50, "score": 103834.89855014751 }, { "content": "struct uses_allocator<queue<T, Container>, Alloc>\n\n : uses_allocator<Container, Alloc>::type {};\n\n\n\ntemplate <typename T, typename Container = tiny_stl::vector<T>,\n\n typename Compare = tiny_stl::less<typename Container::value_type>>\n", "file_path": "TinySTL/queue.hpp", "rank": 51, "score": 99659.08646396459 }, { "content": "struct uses_allocator<stack<T, Container>, Alloc>\n\n : uses_allocator<Container, Alloc>::type {};\n\n\n\n} // namespace tiny_stl\n", "file_path": "TinySTL/stack.hpp", "rank": 52, "score": 99659.08646396459 }, { "content": "struct uses_allocator<tuple<Ts...>, Alloc> : true_type {};\n\n\n\n} // namespace tiny_stl\n", "file_path": "TinySTL/tuple.hpp", "rank": 53, "score": 97408.04806325147 }, { "content": "class compress_pair final : private T1 {\n\npublic:\n\n using first_type = T1;\n\n using second_type = T2;\n\n\n\nprivate:\n\n T2 second;\n\n using Base = T1;\n\n\n\npublic:\n\n constexpr explicit compress_pair() : T1(), second() {\n\n }\n\n\n\n template <typename U1, typename... U2>\n\n compress_pair(U1&& f, U2&&... s)\n\n : T1(tiny_stl::forward<U1>(f)), second(tiny_stl::forward<U2>(s)...) {\n\n }\n\n\n\n T1& get_first() noexcept {\n\n return *this;\n", "file_path": "TinySTL/utility.hpp", "rank": 54, "score": 91813.93544117073 }, { "content": "struct is_void : tiny_stl::is_same<void, tiny_stl::remove_cv_t<T>> {};\n\n\n\ntemplate <typename T>\n\nconstexpr bool is_void_v = is_void<T>::value;\n\n\n\ntemplate <typename T>\n", "file_path": "TinySTL/type_traits.hpp", "rank": 55, "score": 89928.56984737204 }, { "content": "struct GetRebindType<T, Other, void_t<typename T::template rebind<Other>>> {\n\n using type = typename T::template rebind<Other>;\n\n};\n\n\n\n// deal with type of like pointer\n\ntemplate <typename Ptr>\n", "file_path": "TinySTL/memory.hpp", "rank": 56, "score": 87437.08030254448 }, { "content": "class tuple<Head, Tail...> : private tuple<Tail...> {\n\npublic:\n\n using First = Head;\n\n using Base = tuple<Tail...>;\n\n\n\n static constexpr std::size_t size = 1 + sizeof...(Tail);\n\n\n\nprotected:\n\n Head mHead;\n\n\n\npublic:\n\n // (1)\n\n template <enable_if_t<is_default_constructible<Head>::value, int> = 0>\n\n explicit tuple() : Base(), mHead() {\n\n }\n\n\n\n // (2)\n\n template <enable_if_t<is_copy_constructible<Head>::value, int> = 0>\n\n explicit constexpr tuple(Head h, Tail... t) : Base(t...), mHead(h) {\n\n }\n", "file_path": "TinySTL/tuple.hpp", "rank": 57, "score": 85478.31097212776 }, { "content": "struct is_function<Ret(Args..., ...) const&&> : true_type {};\n\n\n\ntemplate <typename Ret, typename... Args>\n", "file_path": "TinySTL/type_traits.hpp", "rank": 58, "score": 85338.35334994362 }, { "content": "struct is_function<Ret(Args..., ...) const&> : true_type {};\n\n\n\ntemplate <typename Ret, typename... Args>\n", "file_path": "TinySTL/type_traits.hpp", "rank": 59, "score": 85338.35334994362 }, { "content": "struct is_function<Ret(Args..., ...) const> : true_type {};\n\n\n\ntemplate <typename Ret, typename... Args>\n", "file_path": "TinySTL/type_traits.hpp", "rank": 60, "score": 85338.35334994362 }, { "content": "struct is_function<Ret(Args...) const&&> : true_type {};\n\n\n\ntemplate <typename Ret, typename... Args>\n", "file_path": "TinySTL/type_traits.hpp", "rank": 61, "score": 85338.35334994362 }, { "content": "struct is_function<Ret(Args...) const> : true_type {};\n\n\n\ntemplate <typename Ret, typename... Args>\n", "file_path": "TinySTL/type_traits.hpp", "rank": 62, "score": 85338.35334994362 }, { "content": "struct is_function<Ret(Args...) const&> : true_type {};\n\n\n\ntemplate <typename Ret, typename... Args>\n", "file_path": "TinySTL/type_traits.hpp", "rank": 63, "score": 85338.35334994362 }, { "content": "struct IteratorTraitsBase<\n\n Iter, void_t<typename Iter::iterator_category, typename Iter::value_type,\n\n typename Iter::difference_type, typename Iter::pointer,\n\n typename Iter::reference>> {\n\n using iterator_category = typename Iter::iterator_category;\n\n using value_type = typename Iter::value_type;\n\n using difference_type = typename Iter::difference_type;\n\n using pointer = typename Iter::pointer;\n\n using reference = typename Iter::reference;\n\n};\n\n\n\n// pointer to object\n\ntemplate <typename T, bool = is_object<T>::value>\n", "file_path": "TinySTL/iterator.hpp", "rank": 64, "score": 84248.59367204156 }, { "content": "struct IteratorTraitsBase {};\n\n\n\ntemplate <typename Iter>\n", "file_path": "TinySTL/iterator.hpp", "rank": 65, "score": 84248.59367204156 }, { "content": "struct is_function<Ret(Args..., ...) const volatile&&> : true_type {};\n\n\n\ntemplate <typename T>\n\nconstexpr bool is_function_v = is_function<T>::value;\n\n\n\ntemplate <typename... Ts>\n\nusing void_t = void;\n\n\n\ntemplate <typename T>\n", "file_path": "TinySTL/type_traits.hpp", "rank": 66, "score": 81397.51518390686 }, { "content": "struct is_function<Ret(Args..., ...) const volatile> : true_type {};\n\n\n\n// specialization for function types that have ref-qualifiers\n\ntemplate <typename Ret, typename... Args>\n", "file_path": "TinySTL/type_traits.hpp", "rank": 67, "score": 81397.51518390686 }, { "content": "struct is_function<Ret(Args...) const volatile&> : true_type {};\n\n\n\ntemplate <typename Ret, typename... Args>\n", "file_path": "TinySTL/type_traits.hpp", "rank": 68, "score": 81397.51518390686 }, { "content": "struct is_function<Ret(Args...) const volatile> : true_type {};\n\n\n\ntemplate <typename Ret, typename... Args>\n", "file_path": "TinySTL/type_traits.hpp", "rank": 69, "score": 81397.51518390686 }, { "content": "struct is_function<Ret(Args..., ...) const volatile&> : true_type {};\n\n\n\ntemplate <typename Ret, typename... Args>\n", "file_path": "TinySTL/type_traits.hpp", "rank": 70, "score": 81397.51518390686 }, { "content": "struct is_function<Ret(Args...) const volatile&&> : true_type {};\n\n\n\ntemplate <typename Ret, typename... Args>\n", "file_path": "TinySTL/type_traits.hpp", "rank": 71, "score": 81397.51518390686 }, { "content": "struct DequeIterator : DequeConstIterator<T> {\n\n using iterator_category = random_access_iterator_tag;\n\n using value_type = T;\n\n using pointer = T*;\n\n using reference = T&;\n\n using size_type = std::size_t;\n\n using difference_type = std::ptrdiff_t;\n\n\n\n using MapPtr = T**;\n\n using Base = DequeConstIterator<T>;\n\n using Self = DequeIterator<T>;\n\n\n\n using Base::cur;\n\n\n\n DequeIterator() : Base() {\n\n }\n\n DequeIterator(T* c, T* f, T* l, MapPtr n) : Base(c, f, l, n) {\n\n }\n\n DequeIterator(const Self&) = default;\n\n\n", "file_path": "TinySTL/deque.hpp", "rank": 72, "score": 76507.53778349486 }, { "content": "struct VectorIterator : VectorConstIterator<T> {\n\n using iterator_category = random_access_iterator_tag;\n\n using value_type = T;\n\n using difference_type = std::ptrdiff_t;\n\n using pointer = T*;\n\n using reference = T&;\n\n\n\n using Base = VectorConstIterator<T>;\n\n using Self = VectorIterator<T>;\n\n\n\n VectorIterator() : Base() {\n\n }\n\n\n\n VectorIterator(T* p) : Base(p) {\n\n }\n\n\n\n reference operator*() const {\n\n return const_cast<reference>(Base::operator*());\n\n }\n\n\n", "file_path": "TinySTL/vector.hpp", "rank": 73, "score": 76507.53778349486 }, { "content": "struct StringIterator : StringConstIterator<T> {\n\n using iterator_category = random_access_iterator_tag;\n\n using value_type = T;\n\n using pointer = T*;\n\n using reference = T&;\n\n using difference_type = std::ptrdiff_t;\n\n using Base = StringConstIterator<T>;\n\n using Self = StringIterator<T>;\n\n\n\n StringIterator() = default;\n\n StringIterator(T* p) : Base(p) {\n\n }\n\n\n\n reference operator*() const {\n\n return const_cast<reference>(*this->ptr);\n\n }\n\n\n\n pointer operator->() const {\n\n return pointer_traits<pointer>::pointer_to(**this);\n\n }\n", "file_path": "TinySTL/string.hpp", "rank": 74, "score": 76507.53778349486 }, { "content": "struct ListIterator : ListConstIterator<T> {\n\n using iterator_category = bidirectional_iterator_tag;\n\n using value_type = T;\n\n using difference_type = std::ptrdiff_t;\n\n using pointer = T*;\n\n using reference = T&;\n\n using Ptr = LNode<T>*;\n\n using Base = ListConstIterator<T>;\n\n\n\n ListIterator() : Base() {\n\n }\n\n ListIterator(Ptr x) : Base(x) {\n\n }\n\n ListIterator(const ListIterator& rhs) : Base(rhs.ptr) {\n\n }\n\n\n\n reference operator*() const {\n\n return this->ptr->data;\n\n }\n\n\n", "file_path": "TinySTL/list.hpp", "rank": 75, "score": 76507.53778349486 }, { "content": "struct HasNoAllocDestroy<Alloc, Ptr,\n\n void_t<decltype(tiny_stl::declval<Alloc&>().destroy(\n\n tiny_stl::declval<Ptr>()))>> : false_type {};\n\n\n\ntemplate <typename Alloc, typename Ptr>\n\nusing UseDefaultDestroy =\n\n disjunction<IsDefaultAllocator<Alloc>, HasNoAllocDestroy<Alloc, Ptr>>;\n\n\n\ntemplate <typename FwdIter, typename Alloc>\n\ninline void destroyAllocRangeAux(FwdIter first, FwdIter last, Alloc&,\n\n true_type) {\n\n // do nothing\n\n}\n\n\n\ntemplate <typename FwdIter, typename Alloc>\n\ninline void destroyAllocRangeAux(FwdIter first, FwdIter last, Alloc& alloc,\n\n false_type) {\n\n for (; first != last; ++first)\n\n alloc.destroy(tiny_stl::addressof(*first));\n\n}\n", "file_path": "TinySTL/memory.hpp", "rank": 76, "score": 74277.51096086219 }, { "content": "class array {\n\npublic:\n\n T elements[Size];\n\n\n\npublic:\n\n using value_type = T;\n\n using size_type = std::size_t;\n\n using difference_type = std::ptrdiff_t;\n\n using pointer = T*;\n\n using const_pointer = const T*;\n\n using reference = T&;\n\n using const_reference = const T&;\n\n using iterator = ArrayIterator<T, Size>;\n\n using const_iterator = ArrayConstIterator<T, Size>;\n\n using reverse_iterator = tiny_stl::reverse_iterator<iterator>;\n\n using const_reverse_iterator = tiny_stl::reverse_iterator<const_iterator>;\n\n\n\n // Constructor implicit declaration\n\n // Destructor implicit declaration\n\n // operator=() implicit declaration\n", "file_path": "TinySTL/array.hpp", "rank": 77, "score": 73677.17001973765 }, { "content": "class tuple<> {\n\npublic:\n\n constexpr tuple() noexcept {\n\n }\n\n\n\n constexpr tuple(const tuple&) noexcept {\n\n }\n\n\n\n constexpr tuple(tuple&&) noexcept {\n\n }\n\n\n\n tuple& operator=(const tuple&) noexcept {\n\n return *this;\n\n }\n\n\n\n tuple& operator=(tuple&&) noexcept {\n\n return *this;\n\n }\n\n\n\n void swap(tuple&) noexcept {\n", "file_path": "TinySTL/tuple.hpp", "rank": 78, "score": 73677.17001973765 }, { "content": "class queue {\n\npublic:\n\n using container_type = Container;\n\n using value_type = typename Container::value_type;\n\n using size_type = typename Container::size_type;\n\n using reference = typename Container::reference;\n\n using const_reference = typename Container::const_reference;\n\n\n\npublic:\n\n static_assert(is_same<T, value_type>::value,\n\n \"container_type::value_type error\");\n\n\n\nprivate:\n\n container_type cont;\n\n\n\npublic:\n\n // (1)\n\n explicit queue(const container_type& c) : cont(c) {\n\n }\n\n\n", "file_path": "TinySTL/queue.hpp", "rank": 79, "score": 73677.17001973765 }, { "content": "class tuple;\n\n\n\ntemplate <>\n", "file_path": "TinySTL/tuple.hpp", "rank": 80, "score": 73677.17001973765 }, { "content": " class C {};\n\n struct S {};\n", "file_path": "TinySTL/test.cpp", "rank": 81, "score": 73677.17001973765 }, { "content": "class tuple;\n\n\n\ntemplate <typename T1, typename T2>\n", "file_path": "TinySTL/utility.hpp", "rank": 82, "score": 73677.17001973765 }, { "content": "class stack {\n\npublic:\n\n using container_type = Container;\n\n using value_type = typename Container::value_type;\n\n using size_type = typename Container::size_type;\n\n using reference = typename Container::reference;\n\n using const_reference = typename Container::const_reference;\n\n\n\npublic:\n\n static_assert(is_same<T, value_type>::value,\n\n \"container_type::value_type error\");\n\n\n\nprivate:\n\n container_type cont;\n\n\n\npublic:\n\n // (1)\n\n explicit stack(const container_type& c) : cont(c) {\n\n }\n\n\n", "file_path": "TinySTL/stack.hpp", "rank": 83, "score": 73677.17001973765 }, { "content": "struct remove_const<const T> {\n\n using type = T;\n\n};\n\n\n\ntemplate <typename T>\n\nusing remove_const_t = typename remove_const<T>::type;\n\n\n\ntemplate <typename T>\n", "file_path": "TinySTL/type_traits.hpp", "rank": 84, "score": 73185.40272315354 }, { "content": "struct GetAllocBindType<Alloc, Other,\n\n void_t<typename Alloc::template rebind<Other>::other>> {\n\n using type = typename Alloc::template rebind<Other>::other;\n\n};\n\n\n\ntemplate <typename Alloc, typename Size_type, typename Const_void_pointer,\n\n typename = void>\n", "file_path": "TinySTL/memory.hpp", "rank": 85, "score": 73063.24476801485 }, { "content": "struct GetVoidPointer {\n\n using Ptr = typename GetPointer<Alloc>::type;\n\n using type = typename pointer_traits<Ptr>::template rebind<void>;\n\n};\n\n\n\ntemplate <typename Alloc>\n", "file_path": "TinySTL/memory.hpp", "rank": 86, "score": 72702.440398138 }, { "content": "struct GetConstPointer {\n\n using Ptr = typename GetPointer<Alloc>::type;\n\n using Val = typename Alloc::value_type;\n\n using type = typename pointer_traits<Ptr>::template rebind<const Val>;\n\n};\n\n\n\ntemplate <typename Alloc>\n", "file_path": "TinySTL/memory.hpp", "rank": 87, "score": 72667.55813697305 }, { "content": "struct StringConstIterator {\n\n using iterator_category = random_access_iterator_tag;\n\n using value_type = T;\n\n using pointer = const T*;\n\n using reference = const T&;\n\n using difference_type = std::ptrdiff_t;\n\n using Self = StringConstIterator<T>;\n\n\n\n const T* ptr;\n\n\n\n StringConstIterator() = default;\n\n StringConstIterator(const T* p) : ptr(p) {\n\n }\n\n\n\n reference operator*() const {\n\n return *ptr;\n\n }\n\n\n\n pointer operator->() const {\n\n return pointer_traits<pointer>::pointer_to(**this);\n", "file_path": "TinySTL/string.hpp", "rank": 88, "score": 72527.78209069639 }, { "content": "struct HashConstIterator {\n\n using iterator_category = forward_iterator_tag;\n\n using value_type = T;\n\n using difference_type = std::ptrdiff_t;\n\n using reference = const T&;\n\n using pointer = const T*;\n\n\n\n std::size_t idx_bucket;\n\n FListConstIterator<T> iter;\n\n HashTableType* hashtable;\n\n\n\n HashConstIterator() = default;\n\n HashConstIterator(std::size_t idx, FListConstIterator<T> it,\n\n HashTableType* ht)\n\n : idx_bucket(idx), iter(it), hashtable(ht) {\n\n }\n\n\n\n HashConstIterator(const HashConstIterator&) = default;\n\n\n\n HashConstIterator(const HashIterator<T, remove_const_t<HashTableType>>& rhs)\n", "file_path": "TinySTL/hashtable.hpp", "rank": 89, "score": 72527.78209069639 }, { "content": "struct VectorConstIterator {\n\n using iterator_category = random_access_iterator_tag;\n\n using value_type = T;\n\n using difference_type = std::ptrdiff_t;\n\n using pointer = const T*;\n\n using reference = const T&;\n\n using Self = VectorConstIterator<T>;\n\n\n\n T* ptr;\n\n\n\n VectorConstIterator() : ptr() {\n\n }\n\n\n\n VectorConstIterator(T* p) : ptr(p) {\n\n }\n\n\n\n reference operator*() const {\n\n return *ptr;\n\n }\n\n\n", "file_path": "TinySTL/vector.hpp", "rank": 90, "score": 72527.78209069639 }, { "content": "struct ListConstIterator {\n\n using iterator_category = bidirectional_iterator_tag;\n\n using value_type = T;\n\n using difference_type = std::ptrdiff_t;\n\n using pointer = const T*;\n\n using reference = const T&;\n\n using Ptr = LNode<T>*;\n\n\n\n Ptr ptr;\n\n\n\n ListConstIterator() : ptr(nullptr) {\n\n }\n\n ListConstIterator(Ptr x) : ptr(x) {\n\n }\n\n ListConstIterator(const ListConstIterator& rhs) : ptr(rhs.ptr) {\n\n }\n\n\n\n reference operator*() const {\n\n return ptr->data;\n\n }\n", "file_path": "TinySTL/list.hpp", "rank": 91, "score": 72527.78209069639 }, { "content": "struct DequeConstIterator {\n\n using iterator_category = random_access_iterator_tag;\n\n using value_type = T;\n\n using pointer = const T*;\n\n using reference = const T&;\n\n using size_type = std::size_t;\n\n using difference_type = std::ptrdiff_t;\n\n\n\n using MapPtr = T**;\n\n using Self = DequeConstIterator<T>;\n\n\n\n constexpr static size_type buffer_size() {\n\n constexpr size_type sz = sizeof(T);\n\n return sz < 512 ? static_cast<size_type>(512 / sz)\n\n : static_cast<size_type>(1);\n\n }\n\n\n\n T* cur; // point to current element\n\n T* first; // point to first element in current buffer\n\n T* last; // point to last element in current buffer\n", "file_path": "TinySTL/deque.hpp", "rank": 92, "score": 72527.78209069639 }, { "content": "struct is_reference : bool_constant<is_lvalue_reference<T>::value ||\n\n is_rvalue_reference<T>::value> {};\n\n\n\ntemplate <typename T>\n\nconstexpr bool is_reference_v = is_reference<T>::value;\n\n\n\ntemplate <typename T>\n", "file_path": "TinySTL/type_traits.hpp", "rank": 93, "score": 72487.42952810726 }, { "content": "struct is_pointer : IsPointer<typename remove_cv<T>::type> {};\n\n\n\ntemplate <typename T>\n\nconstexpr bool is_pointer_v = is_pointer<T>::value;\n\n\n\ntemplate <typename T>\n", "file_path": "TinySTL/type_traits.hpp", "rank": 94, "score": 72420.52321519186 }, { "content": "struct is_class : bool_constant<std::is_class<T>::value> {};\n\n\n\ntemplate <typename T>\n\nconstexpr bool is_class_v = is_class<T>::value;\n\n\n\ntemplate <typename T>\n", "file_path": "TinySTL/type_traits.hpp", "rank": 95, "score": 72229.06929585128 }, { "content": "struct RBTreeIterator : RBTreeConstIterator<T> {\n\n using iterator_category = bidirectional_iterator_tag;\n\n using value_type = T;\n\n using difference_type = std::ptrdiff_t;\n\n using pointer = T*;\n\n using reference = T&;\n\n\n\n using Ptr = RBTNode<T>*;\n\n using Base = RBTreeConstIterator<T>;\n\n\n\n RBTreeIterator() : Base() {\n\n }\n\n RBTreeIterator(Ptr x) : Base(x) {\n\n }\n\n RBTreeIterator(const RBTreeIterator& rhs) : Base(rhs.ptr) {\n\n }\n\n\n\n reference operator*() const {\n\n return const_cast<reference>(Base::operator*());\n\n }\n", "file_path": "TinySTL/rbtree.hpp", "rank": 96, "score": 72150.7623662601 }, { "content": "struct ReplaceFirstParameter<NewFirst, T<First, Rest...>> {\n\n using type = T<NewFirst, Rest...>;\n\n};\n\n\n\ntemplate <typename T, typename Other, typename = void>\n", "file_path": "TinySTL/memory.hpp", "rank": 97, "score": 72142.2499230385 }, { "content": "class basic_string {\n\npublic:\n\n static_assert(is_same<typename Traits::char_type, CharT>::value,\n\n \"char type error\");\n\n\n\npublic:\n\n using traits_type = Traits;\n\n using value_type = CharT;\n\n using allocator_type = Alloc;\n\n using size_type = typename Alloc::size_type;\n\n using difference_type = typename Alloc::difference_type;\n\n using reference = value_type&;\n\n using const_reference = const value_type&;\n\n using pointer = value_type*;\n\n using const_pointer = const value_type*;\n\n using iterator = StringIterator<value_type>;\n\n using const_iterator = StringConstIterator<value_type>;\n\n using reverse_iterator = tiny_stl::reverse_iterator<iterator>;\n\n using const_reverse_iterator = tiny_stl::reverse_iterator<const_iterator>;\n\n using AllocTraits = allocator_traits<Alloc>;\n\n\n\n using Alty = RebindAllocType<Alloc, value_type>;\n\n\n\npublic:\n\n static const size_type npos = static_cast<size_type>(-1);\n\n\n\nprivate:\n", "file_path": "TinySTL/string.hpp", "rank": 98, "score": 71965.19468822482 } ]
C++
parallel/SolverConfiguration.cc
jiriklepl/glucose-syrup-4.1
3a444d2cde0fbb1538e7965410db67db27940c09
#include "glucose/parallel/MultiSolvers.h" #include "glucose/core/Solver.h" #include "glucose/parallel/SolverConfiguration.h" using namespace Glucose; void SolverConfiguration::configure(MultiSolvers *ms, int nbsolvers) { for(int i = 1;i<nbsolvers;i++) { ms->solvers[i]->randomizeFirstDescent = true; ms->solvers[i]->adaptStrategies = (i%2==0); ms->solvers[i]->forceUnsatOnNewDescent = (i%4==0); } if (nbsolvers > 8) { for(int i=0;i<nbsolvers;i++) { ms->solvers[i]->goodlimitlbd = 5; ms->solvers[i]->goodlimitsize = 15; } } } void SolverConfiguration::configureSAT15Adapt(MultiSolvers *ms, int nbsolvers) { for(int i = 1;i<nbsolvers;i++) { ms->solvers[i]->randomizeFirstDescent = true; ms->solvers[i]->adaptStrategies = (i%2==0); } if (nbsolvers > 8) { for(int i=0;i<nbsolvers;i++) { ms->solvers[i]->goodlimitlbd = 5; ms->solvers[i]->goodlimitsize = 15; } } } void SolverConfiguration::configureSAT15Default(MultiSolvers *ms, int nbsolvers) { for(int i = 1;i<nbsolvers;i++) ms->solvers[i]->randomizeFirstDescent = true; if (nbsolvers > 8) { for(int i=0;i<nbsolvers;i++) { ms->solvers[i]->goodlimitlbd = 5; ms->solvers[i]->goodlimitsize = 15; } } } void SolverConfiguration::configureSAT14(MultiSolvers *ms, int nbsolvers) { if (nbsolvers < 2 ) return; ms->solvers[1]->var_decay = 0.94; ms->solvers[1]->max_var_decay = 0.96; ms->solvers[1]->firstReduceDB=600; if (nbsolvers < 3 ) return; ms->solvers[2]->var_decay = 0.90; ms->solvers[2]->max_var_decay = 0.97; ms->solvers[2]->firstReduceDB=500; if (nbsolvers < 4 ) return; ms->solvers[3]->var_decay = 0.85; ms->solvers[3]->max_var_decay = 0.93; ms->solvers[3]->firstReduceDB=400; if (nbsolvers < 5 ) return; ms->solvers[4]->var_decay = 0.95; ms->solvers[4]->max_var_decay = 0.95; ms->solvers[4]->firstReduceDB=4000; ms->solvers[4]->lbdQueue.growTo(100); ms->solvers[4]->sizeLBDQueue = 100; ms->solvers[4]->K = 0.7; ms->solvers[4]->incReduceDB = 500; if (nbsolvers < 6 ) return; ms->solvers[5]->var_decay = 0.93; ms->solvers[5]->max_var_decay = 0.96; ms->solvers[5]->firstReduceDB=100; ms->solvers[5]->incReduceDB = 500; if (nbsolvers < 7 ) return; ms->solvers[6]->var_decay = 0.75; ms->solvers[6]->max_var_decay = 0.94; ms->solvers[6]->firstReduceDB=2000; if (nbsolvers < 8 ) return; ms->solvers[7]->var_decay = 0.94; ms->solvers[7]->max_var_decay = 0.96; ms->solvers[7]->firstReduceDB=800; if (nbsolvers < 9) return; if (nbsolvers < 10 ) return; if (nbsolvers < 11 ) return; double noisevar_decay = 0.005; int noiseReduceDB = 50; for (int i=10;i<nbsolvers;i++) { ms->solvers[i]-> var_decay = ms->solvers[i%8]->var_decay; ms->solvers[i]-> max_var_decay = ms->solvers[i%8]->max_var_decay; ms->solvers[i]-> firstReduceDB= ms->solvers[i%8]->firstReduceDB; ms->solvers[i]->var_decay += noisevar_decay; ms->solvers[i]->firstReduceDB+=noiseReduceDB; if ((i+1) % 8 == 0) { noisevar_decay += 0.006; noiseReduceDB += 25; } } }
#include "glucose/parallel/MultiSolvers.h" #include "glucose/core/Solver.h" #include "glucose/parallel/SolverConfiguration.h" using namespace Glucose; void SolverConfiguration::configure(MultiSolvers *ms, int nbsolvers) { for(int i = 1;i<nbsolvers;i++) { ms->solvers[i]->randomizeFirstDescent = true; ms->solvers[i]->adaptStrategies = (i%2==0); ms->solvers[i]->forceUnsatOnNewDescent = (i%4==0); } if (nbsolvers > 8) { for(int i=0;i<nbsolvers;i++) { ms->solvers[i]->goodlimitlbd = 5; ms->solvers[i]->goodlimitsize = 15; } } } void SolverConfiguration::configureSAT15Adapt(MultiSolvers *ms, int nbsolvers) { for(int i = 1;i<nbsolvers;i++) { ms->solvers[i]->randomizeFirstDescent = true; ms->solvers[i]->adaptStrategies = (i%2==0); } if (nbsolvers > 8) { for(int i=0;i<nbsolvers;i++) { ms->solvers[i]->goodlimitlbd = 5; ms->solvers[i]->goodlimitsize = 15; } } } void SolverConfiguration::configureSAT15Default(MultiSolvers *ms, int nbsolvers) { for(int i = 1;i<nbsolvers;i++) ms->solvers[i]->randomizeFirstDescent = true; if (nbsolvers > 8) { for(int i=0;i<nbsolvers;i++) { ms->solvers[i]->goodlimitlbd = 5; ms->solvers[i]->goodlimitsize = 15; } } } void SolverConfiguration::configureSAT14(MultiSolvers *ms, int nbsolvers) { if (nbsolvers < 2 ) return; ms->solvers[1]->var_decay = 0.94; ms->solvers[1]->max_var_decay = 0.96; ms->solvers[1]->firstReduceDB=600; if (nbsolvers < 3 ) return; ms->solvers[2]->var_decay = 0.90; ms->solvers[2]->max_var_decay = 0.97; ms->solvers[2]->firstReduceDB=500; if (nbsolvers < 4 ) return; ms->solvers[3]->var_decay = 0.85; ms->solvers[3]->max_var_decay = 0.93; ms->solvers[3]->firstReduceDB=400; if (nbsolvers < 5 ) return; ms->solvers[4]->var_decay = 0.95; ms->solvers[4]->max_var_decay = 0.95; ms->solvers[4]->firstReduceDB=4000; ms->solvers[4]->lbdQueue.growTo(100); ms->solvers[4]->sizeLBDQueue = 100; ms->solvers[4]->K = 0.7; ms->solvers[4]->incReduceDB = 500; if (nbsolvers < 6 ) return; ms->solvers[5]->var_decay = 0.93; ms->solvers[5]->max_var_decay = 0.96; ms->solvers[5]->firstReduceDB=100; ms->solvers[5]->incReduceDB = 500; if (nbsolvers < 7 ) return; ms->solvers[6]->var_decay = 0.75; ms->solvers[6]->max_var_decay = 0.94; ms->solvers[6]->firstReduceDB=2000; if (nbsolvers < 8 ) return; ms->solvers[7]->var_decay = 0.94; ms->solvers[7]->max_var_decay = 0.96; ms->solvers[7]->firstReduceDB=800; if (nbsolvers < 9) return; if (nbsolvers < 10 ) return;
if (nbsolvers < 11 ) return; double noisevar_decay = 0.005; int noiseReduceDB = 50; for (int i=10;i<nbsolvers;i++) { ms->solvers[i]-> var_decay = ms->solvers[i%8]->var_decay; ms->solvers[i]-> max_var_decay = ms->solvers[i%8]->max_var_decay; ms->solvers[i]-> firstReduceDB= ms->solvers[i%8]->firstReduceDB; ms->solvers[i]->var_decay += noisevar_decay; ms->solvers[i]->firstReduceDB+=noiseReduceDB; if ((i+1) % 8 == 0) { noisevar_decay += 0.006; noiseReduceDB += 25; } } }
function_block-function_prefix_line
[ { "content": "struct IntRange {\n\n int begin;\n\n int end;\n\n IntRange(int b, int e) : begin(b), end(e) {}\n\n};\n\n\n", "file_path": "utils/Options.h", "rank": 0, "score": 30383.65854647451 }, { "content": "class IntOption : public Option\n\n{\n\n protected:\n\n IntRange range;\n\n int32_t value;\n\n\n\n public:\n\n IntOption(const char* c, const char* n, const char* d, int32_t def = int32_t(), IntRange r = IntRange(INT32_MIN, INT32_MAX))\n\n : Option(n, d, c, \"<int32>\"), range(r), value(def) {}\n\n \n\n operator int32_t (void) const { return value; }\n\n operator int32_t& (void) { return value; }\n\n IntOption& operator= (int32_t x) { value = x; return *this; }\n\n\n\n virtual bool parse(const char* str){\n\n const char* span = str; \n\n\n\n if (!match(span, \"-\") || !match(span, name) || !match(span, \"=\"))\n\n return false;\n\n\n", "file_path": "utils/Options.h", "rank": 1, "score": 26523.474930473072 }, { "content": "\n\n#include \"glucose/simp/SimpSolver.h\"\n\n#include \"glucose/parallel/ParallelSolver.h\"\n\n#include \"glucose/parallel/MultiSolvers.h\"\n\n\n\nusing namespace Glucose;\n\n\n\n\n\n\n\nstatic MultiSolvers* pmsolver;\n\n\n\n// Terminate by notifying the solver and back out gracefully. This is mainly to have a test-case\n\n// for this feature of the Solver as it may take longer than an immediate call to '_exit()'.\n\n//static void SIGINT_interrupt(int signum) { pmsolver->interrupt(); }\n\n\n\n\n\n// Note that '_exit()' rather than 'exit()' has to be used. The reason is that 'exit()' calls\n\n// destructors and may cause deadlocks if a malloc/free function happens to be running (these\n\n// functions are guarded by locks for multithreaded use).\n\nstatic void SIGINT_exit(int signum) {\n", "file_path": "parallel/Main.cc", "rank": 6, "score": 16.70021487714317 }, { "content": "#include \"glucose/utils/Options.h\"\n\n#include \"glucose/utils/ParseUtils.h\"\n\n\n\nusing namespace Glucose;\n\n\n\nvoid Glucose::parseOptions(int& argc, char** argv, bool strict)\n\n{\n\n int i, j;\n\n for (i = j = 1; i < argc; i++){\n\n const char* str = argv[i];\n\n if (match(str, \"--\") && match(str, Option::getHelpPrefixString()) && match(str, \"help\")){\n\n if (*str == '\\0')\n\n printUsageAndExit(argc, argv);\n\n else if (match(str, \"-verb\"))\n\n printUsageAndExit(argc, argv, true);\n\n } else {\n\n bool parsed_ok = false;\n\n \n\n for (int k = 0; !parsed_ok && k < Option::getOptionList().size(); k++){\n\n parsed_ok = Option::getOptionList()[k]->parse(argv[i]);\n", "file_path": "utils/Options.cc", "rank": 7, "score": 16.51492408842748 }, { "content": "#define Glucose_Options_h\n\n\n\n#include <stdlib.h>\n\n#include <stdio.h>\n\n#include <math.h>\n\n#include <string.h>\n\n\n\n#include \"glucose/mtl/IntTypes.h\"\n\n#include \"glucose/mtl/Vec.h\"\n\n#include \"glucose/utils/ParseUtils.h\"\n\n\n\nnamespace Glucose {\n\n\n\n//==================================================================================================\n\n// Top-level option parse/help functions:\n\n\n\n\n\nextern void parseOptions (int& argc, char** argv, bool strict = false);\n\nextern void printUsageAndExit(int argc, char** argv, bool verbose = false);\n\nextern void setUsageHelp (const char* str);\n\nextern void setHelpPrefixStr (const char* str);\n\n\n\n\n\n//==================================================================================================\n\n// Options is an abstract class that gives the interface for all types options:\n\n\n\n\n", "file_path": "utils/Options.h", "rank": 9, "score": 15.134252834653928 }, { "content": "#ifndef Glucose_Vec_h\n\n#define Glucose_Vec_h\n\n\n\n#include <assert.h>\n\n#include <new>\n\n\n\n#include \"glucose/mtl/IntTypes.h\"\n\n#include \"glucose/mtl/XAlloc.h\"\n\n#include<string.h>\n\n\n\nnamespace Glucose {\n\n\n\n//=================================================================================================\n\n// Automatically resizable arrays\n\n//\n\n// NOTE! Don't use this vector on datatypes that cannot be re-located in memory (with realloc)\n\n\n\ntemplate<class T>\n", "file_path": "mtl/Vec.h", "rank": 10, "score": 14.036790784908648 }, { "content": "\n\n#ifndef Glucose_VecThreads_h\n\n#define Glucose_VecThreads_h\n\n\n\n#include <assert.h>\n\n#include <new>\n\n\n\n#include \"glucose/mtl/IntTypes.h\"\n\n#include \"glucose/mtl/XAlloc.h\"\n\n#include<string.h>\n\n\n\nnamespace Glucose {\n\n\n\n//=================================================================================================\n\n// Automatically resizable arrays\n\n//\n\n// NOTE! Don't use this vector on datatypes that cannot be re-located in memory (with realloc)\n\n\n\ntemplate<class T>\n", "file_path": "mtl/VecThreads.h", "rank": 11, "score": 13.86431116882286 }, { "content": "#include \"glucose/mtl/Map.h\"\n\n#include \"glucose/mtl/Alloc.h\"\n\n\n\n\n\nnamespace Glucose {\n\n\n\n//=================================================================================================\n\n// Variables, literals, lifted booleans, clauses:\n\n\n\n\n\n// NOTE! Variables are just integers. No abstraction here. They should be chosen from 0..N,\n\n// so that they can be used as array indices.\n\n\n\ntypedef int Var;\n\n#define var_Undef (-1)\n\n\n\n\n", "file_path": "core/SolverTypes.h", "rank": 12, "score": 13.823572686634884 }, { "content": "#include \"glucose/utils/System.h\"\n\n\n\n#if defined(__linux__)\n\n\n\n#include <stdio.h>\n\n#include <stdlib.h>\n\n\n\nusing namespace Glucose;\n\n\n\n// TODO: split the memory reading functions into two: one for reading high-watermark of RSS, and\n\n// one for reading the current virtual memory size.\n\n\n\nstatic inline int memReadStat(int field)\n\n{\n\n char name[256];\n\n pid_t pid = getpid();\n\n int value;\n\n\n\n sprintf(name, \"/proc/%d/statm\", pid);\n\n FILE* in = fopen(name, \"rb\");\n", "file_path": "utils/System.cc", "rank": 13, "score": 13.639481819376435 }, { "content": "\tunsigned int addIndex(unsigned int i, unsigned int a); \n\n\tvoid removeLastClause(); \n\n\t \n\n\tvoid noCheckPush(uint32_t x);\n\n\tuint32_t noCheckPop(unsigned int & index);\n\n\n\n\t// Return true if the clause was succesfully added\n\n bool pushClause(int threadId, Clause & c);\n\n bool getClause(int threadId, int & threadOrigin, vec<Lit> & resultClause, bool firstFound = false); \n\n\t\n\n\tint maxSize() const {return maxsize;}\n\n uint32_t getCap();\n\n\tvoid growTo(int size) {\n\n\t assert(0); // Not implemented (essentially for efficiency reasons)\n\n\t elems.growTo(size); \n\n\t first=0; maxsize=size; queuesize = 0;last = 0;\n\n\t for(int i=0;i<size;i++) elems[i]=0; \n\n\t}\n\n\n\n\tvoid fastclear() {first = 0; last = 0; queuesize=0; } \n", "file_path": "parallel/ClausesBuffer.h", "rank": 14, "score": 13.329055113825214 }, { "content": " ParallelSolver(int threadId);\n\n ParallelSolver(const ParallelSolver &s);\n\n ~ParallelSolver();\n\n \n\n /**\n\n * Clone function\n\n */\n\n virtual Clone* clone() const {\n\n return new ParallelSolver(*this);\n\n } \n\n\n\n int threadNumber () const;\n\n void setThreadNumber (int i);\n\n void reportProgress();\n\n void reportProgressArrayImports(vec<unsigned int> &totalColumns);\n\n virtual void reduceDB();\n\n virtual lbool solve_ (bool do_simp = true, bool turn_off_simp = false);\n\n\n\n vec<Lit> importedClause; // Temporary clause used to copy each imported clause\n\n unsigned int goodlimitlbd; // LBD score of the \"good\" clauses, locally\n", "file_path": "parallel/ParallelSolver.h", "rank": 15, "score": 13.153620684878494 }, { "content": " template <typename T> unsigned int computeLBD(const T & lits,int end=-1);\n\n void minimisationWithBinaryResolution(vec<Lit> &out_learnt);\n\n\n\n virtual void relocAll (ClauseAllocator& to);\n\n\n\n // Misc:\n\n //\n\n int decisionLevel () const; // Gives the current decisionlevel.\n\n uint32_t abstractLevel (Var x) const; // Used to represent an abstraction of sets of decision levels.\n\n CRef reason (Var x) const;\n\n int level (Var x) const;\n\n double progressEstimate () const; // DELETE THIS ?? IT'S NOT VERY USEFUL ...\n\n bool withinBudget () const;\n\n inline bool isSelector(Var v) {return (incremental && v>nbVarsInitialFormula);}\n\n\n\n // Static helpers:\n\n //\n\n\n\n // Returns a random float 0 <= x < 1. Seed must never be 0.\n\n static inline double drand(double& seed) {\n", "file_path": "core/Solver.h", "rank": 16, "score": 12.82315550399602 }, { "content": "void MultiSolvers::adjustParameters() {\n\n SolverConfiguration::configure(this, nbsolvers);\n\n}\n\n\n\n\n\nvoid MultiSolvers::adjustNumberOfCores() {\n\n float mem = memUsed();\n\n if(nbthreads == 0) { // Automatic configuration\n\n if(verb >= 1)\n\n printf(\"c | Automatic Adjustement of the number of solvers. MaxMemory=%5d, MaxCores=%3d. |\\n\", maxmemory, maxnbsolvers);\n\n unsigned int tmpnbsolvers = maxmemory * 4 / 10 / mem;\n\n if(tmpnbsolvers > maxnbsolvers) tmpnbsolvers = maxnbsolvers;\n\n if(tmpnbsolvers < 1) tmpnbsolvers = 1;\n\n if(verb >= 1)\n\n printf(\"c | One Solver is taking %.2fMb... Let's take %d solvers for this run (max 40%% of the maxmemory). |\\n\", mem, tmpnbsolvers);\n\n nbsolvers = tmpnbsolvers;\n\n nbthreads = nbsolvers;\n\n } else {\n\n assert(nbthreads == nbsolvers);\n\n }\n", "file_path": "parallel/MultiSolvers.cc", "rank": 17, "score": 12.76207911967237 }, { "content": "substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT\n\nNOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT\n\nOF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n **************************************************************************************************/\n\n\n\n#include \"glucose/core/Solver.h\"\n\n#include \"glucose/parallel/ParallelSolver.h\"\n\n#include \"glucose/core/SolverTypes.h\"\n\n#include \"glucose/parallel/ClausesBuffer.h\"\n\n#include \"glucose/parallel/SharedCompanion.h\"\n\n\n\n\n\nusing namespace Glucose;\n\n\n\nSharedCompanion::SharedCompanion(int _nbThreads) :\n\n nbThreads(_nbThreads), \n", "file_path": "parallel/SharedCompanion.cc", "rank": 19, "score": 12.581141670252313 }, { "content": "bool MultiSolvers::eliminate() {\n\n\n\n // TODO allow variable elimination when all threads are built!\n\n assert(allClonesAreBuilt == false);\n\n\n\n SimpSolver *s = (SimpSolver *) getPrimarySolver();\n\n s->use_simplification = use_simplification;\n\n if(!use_simplification) return true;\n\n\n\n return s->eliminate(true);\n\n}\n\n\n\n\n\n// TODO: Use a template here\n\nvoid *localLaunch(void *arg) {\n\n ParallelSolver *s = (ParallelSolver *) arg;\n\n\n\n (void) s->solve();\n\n\n\n pthread_exit(NULL);\n", "file_path": "parallel/MultiSolvers.cc", "rank": 20, "score": 12.535919826264593 }, { "content": " }\n\n if(sumconf > 10000000 && sumimported > 4 * sumconf) { // too many many imported clauses (after a while)\n\n for(int i = 0; i < nbsolvers; i++) { // we have like 32 threads, so we need to export just very good clauses\n\n solvers[i]->goodlimitlbd -= 2;\n\n solvers[i]->goodlimitsize -= 4;\n\n }\n\n adjustedlimitonce = true;\n\n printf(\"c adjusting (once) the limits to send fewer clauses.\\n\");\n\n }\n\n }\n\n }\n\n\n\n (void) pthread_mutex_unlock(&m);\n\n\n\n for(i = 0; i < nbsolvers; i++) { // Wait for all threads to finish\n\n pthread_join(*threads[i], NULL);\n\n }\n\n\n\n assert(sharedcomp != NULL);\n\n result = sharedcomp->jobStatus;\n", "file_path": "parallel/MultiSolvers.cc", "rank": 21, "score": 12.411068462435601 }, { "content": "double MiniSat::memUsedPeak(void) { return memUsed(); }\n\n\n\n\n\n#elif defined(__APPLE__)\n\n#include <malloc/malloc.h>\n\n\n\ndouble Glucose::memUsed(void) {\n\n malloc_statistics_t t;\n\n malloc_zone_statistics(NULL, &t);\n\n return (double)t.max_size_in_use / (1024*1024); }\n\n\n\n#else\n\ndouble Glucose::memUsed() { \n\n return 0; }\n\n#endif\n", "file_path": "utils/System.cc", "rank": 22, "score": 12.140781782678063 }, { "content": "#ifndef Glucose_ParseUtils_h\n\n#define Glucose_ParseUtils_h\n\n\n\n#include <stdlib.h>\n\n#include <stdio.h>\n\n#include <math.h>\n\n\n\n#include <zlib.h>\n\n\n\nnamespace Glucose {\n\n\n\n//-------------------------------------------------------------------------------------------------\n\n// A simple buffered character stream class:\n\n\n\nstatic const int buffer_size = 1048576;\n\n\n\n\n", "file_path": "utils/ParseUtils.h", "rank": 23, "score": 11.710349320363957 }, { "content": " vecThreads(int size, const T& pad) : data(NULL) , sz(0) , cap(0), lock(false), nbusers(0) { growTo(size, pad); }\n\n ~vecThreads() { clear(true); }\n\n\n\n // Pointer to first element:\n\n operator T* (void) { return data; }\n\n\n\n // Size operations:\n\n int size (void) const { return sz; }\n\n void shrink (int nelems) { assert(nelems <= sz); for (int i = 0; i < nelems; i++) sz--, data[sz].~T(); }\n\n void shrink_ (int nelems) { assert(nelems <= sz); sz -= nelems; }\n\n int capacity (void) const { return cap; }\n\n void capacity (int min_cap);\n\n void capacityProtected (int min_cap);\n\n void growTo (int size);\n\n void growTo (int size, const T& pad);\n\n void clear (bool dealloc = false);\n\n\n\n // Stack interface:\n\n void push (void) { if (sz == cap) capacity(sz+1); new (&data[sz]) T(); sz++; }\n\n void push (const T& elem) { if (sz == cap) capacity(sz+1); data[sz++] = elem; }\n", "file_path": "mtl/VecThreads.h", "rank": 24, "score": 11.388309744274594 }, { "content": "\n\n // Main internal methods:\n\n //\n\n void insertVarOrder (Var x); // Insert a variable in the decision order priority queue.\n\n Lit pickBranchLit (); // Return the next decision variable.\n\n void newDecisionLevel (); // Begins a new decision level.\n\n void uncheckedEnqueue (Lit p, CRef from = CRef_Undef); // Enqueue a literal. Assumes value of literal is undefined.\n\n bool enqueue (Lit p, CRef from = CRef_Undef); // Test if fact 'p' contradicts current state, enqueue otherwise.\n\n CRef propagate (); // Perform unit propagation. Returns possibly conflicting clause.\n\n CRef propagateUnaryWatches(Lit p); // Perform propagation on unary watches of p, can find only conflicts\n\n void cancelUntil (int level); // Backtrack until a certain level.\n\n void analyze (CRef confl, vec<Lit>& out_learnt, vec<Lit> & selectors, int& out_btlevel,unsigned int &nblevels,unsigned int &szWithoutSelectors); // (bt = backtrack)\n\n void analyzeFinal (Lit p, vec<Lit>& out_conflict); // COULD THIS BE IMPLEMENTED BY THE ORDINARIY \"analyze\" BY SOME REASONABLE GENERALIZATION?\n\n bool litRedundant (Lit p, uint32_t abstract_levels); // (helper method for 'analyze()')\n\n lbool search (int nof_conflicts); // Search for a given number of conflicts.\n\n virtual lbool solve_ (bool do_simp = true, bool turn_off_simp = false); // Main solve method (assumptions given in 'assumptions').\n\n virtual void reduceDB (); // Reduce the set of learnt clauses.\n\n void removeSatisfied (vec<CRef>& cs); // Shrink 'cs' to contain only non-satisfied clauses.\n\n void rebuildOrderHeap ();\n\n\n", "file_path": "core/Solver.h", "rank": 25, "score": 11.268923398668285 }, { "content": " FILE* certifiedOutput;\n\n bool certifiedUNSAT;\n\n bool vbyte;\n\n\n\n void write_char (unsigned char c);\n\n void write_lit (int n);\n\n\n\n\n\n // Panic mode. \n\n // Save memory\n\n uint32_t panicModeLastRemoved, panicModeLastRemovedShared;\n\n \n\n bool useUnaryWatched; // Enable unary watched literals\n\n bool promoteOneWatchedClause; // One watched clauses are promotted to two watched clauses if found empty\n\n \n\n // Functions useful for multithread solving\n\n // Useless in the sequential case \n\n // Overide in ParallelSolver\n\n virtual void parallelImportClauseDuringConflictAnalysis(Clause &c,CRef confl);\n\n virtual bool parallelImportClauses(); // true if the empty clause was received\n", "file_path": "core/Solver.h", "rank": 26, "score": 11.21152918075427 }, { "content": " * + origin is the thread id of the thread which added this clause to the fifo\n\n * + l1 l2 l3 are the literals of the clause\n\n *\n\n * **********************************************************************************************\n\n * **CAREFUL** This class is not thread-safe. In glucose-syrup, the SharedCompanion is \n\n * responsible for ensuring atomicity of main functions\n\n * **********************************************************************************************\n\n *\n\n * */\n\n\n\n#include \"glucose/parallel/ClausesBuffer.h\"\n\n\n\n//=================================================================================================\n\n\n\nusing namespace Glucose;\n\n\n\nextern BoolOption opt_whenFullRemoveOlder;\n\nextern IntOption opt_fifoSizeByCore;\n\n\n\n// index : size clause\n", "file_path": "parallel/ClausesBuffer.cc", "rank": 27, "score": 11.14384120612577 }, { "content": "substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT\n\nNOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT\n\nOF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n **************************************************************************************************/\n\n\n\n#include <math.h>\n\n\n\n#include \"glucose/utils/System.h\"\n\n#include \"glucose/mtl/Sort.h\"\n\n#include \"glucose/core/Solver.h\"\n\n#include \"glucose/core/Constants.h\"\n\n#include\"simp/SimpSolver.h\"\n\n\n\nusing namespace Glucose;\n\n\n\n\n", "file_path": "core/Solver.cc", "rank": 28, "score": 11.086170744303056 }, { "content": " virtual bool parallelImportClauses(); // true if the empty clause was received\n\n virtual void parallelImportUnaryClauses();\n\n virtual void parallelExportUnaryClause(Lit p);\n\n virtual void parallelExportClauseDuringSearch(Clause &c);\n\n virtual bool parallelJobIsFinished();\n\n virtual bool panicModeIsEnabled();\n\n \n\n bool shareClause(Clause & c); // true if the clause was succesfully sent\n\n\n\n \n\n\n\n};\n\n\n\n\n\n inline int ParallelSolver::threadNumber () const {return thn;}\n\n inline void ParallelSolver::setThreadNumber (int i) {thn = i;}\n\n}\n\n#endif\t/* PARALLELSOLVER_H */\n\n\n", "file_path": "parallel/ParallelSolver.h", "rank": 29, "score": 11.059529553590815 }, { "content": "substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT\n\nNOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT\n\nOF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n **************************************************************************************************/\n\n\n\n#include <pthread.h>\n\n#include \"glucose/parallel/MultiSolvers.h\"\n\n#include \"glucose/mtl/Sort.h\"\n\n#include \"glucose/utils/System.h\"\n\n#include \"glucose/simp/SimpSolver.h\"\n\n#include <errno.h>\n\n#include <string.h>\n\n#include \"glucose/parallel/SolverConfiguration.h\"\n\n\n\nusing namespace Glucose;\n\n\n", "file_path": "parallel/MultiSolvers.cc", "rank": 30, "score": 10.977529864516793 }, { "content": "substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT\n\nNOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT\n\nOF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n **************************************************************************************************/\n\n\n\n#include \"glucose/mtl/Sort.h\"\n\n#include \"glucose/simp/SimpSolver.h\"\n\n#include \"glucose/utils/System.h\"\n\n\n\nusing namespace Glucose;\n\n\n\n//=================================================================================================\n\n// Options:\n\n\n\n\n\nstatic const char* _cat = \"SIMP\";\n", "file_path": "simp/SimpSolver.cc", "rank": 31, "score": 10.763097667488882 }, { "content": "\n\n if (value(v) != l_Undef || cls.size() == 0)\n\n return true;\n\n\n\n for (int i = 0; i < cls.size(); i++)\n\n if (!asymm(v, cls[i]))\n\n return false;\n\n\n\n return backwardSubsumptionCheck();\n\n}\n\n\n\n\n\nstatic void mkElimClause(vec<uint32_t>& elimclauses, Lit x)\n\n{\n\n elimclauses.push(toInt(x));\n\n elimclauses.push(1);\n\n}\n\n\n\n\n\nstatic void mkElimClause(vec<uint32_t>& elimclauses, Var v, Clause& c)\n", "file_path": "simp/SimpSolver.cc", "rank": 32, "score": 10.745057025602083 }, { "content": "\t occs[i].memCopyTo(copy.occs[i]);\n\n\tdirty.memCopyTo(copy.dirty);\n\n\tdirties.memCopyTo(copy.dirties);\n\n }\n\n\n\n void clean (const Idx& idx);\n\n void smudge (const Idx& idx){\n\n if (dirty[toInt(idx)] == 0){\n\n dirty[toInt(idx)] = 1;\n\n dirties.push(idx);\n\n }\n\n }\n\n\n\n void clear(bool free = true){\n\n occs .clear(free);\n\n dirty .clear(free);\n\n dirties.clear(free);\n\n }\n\n};\n\n\n", "file_path": "core/SolverTypes.h", "rank": 33, "score": 10.720596423524075 }, { "content": " return true;\n\n }\n\n // Clones are built, need to pass the clause to all the threads\n\n for(int i = 1; i < nbsolvers; i++) {\n\n solvers[i]->addClause(ps);\n\n }\n\n numclauses++;\n\n }\n\n return true;\n\n}\n\n\n\n\n\nbool MultiSolvers::simplify() {\n\n assert(solvers[0] != NULL); // There is at least one solver.\n\n\n\n if(!okay()) return false;\n\n return ok = solvers[0]->simplify();\n\n}\n\n\n\n\n", "file_path": "parallel/MultiSolvers.cc", "rank": 34, "score": 10.657067167897823 }, { "content": "\n\nstatic inline double cpuTime(void) {\n\n struct rusage ru;\n\n getrusage(RUSAGE_SELF, &ru);\n\n return (double) ru.ru_utime.tv_sec + (double) ru.ru_utime.tv_usec / 1000000;\n\n}\n\n\n\n\n\nvoid MultiSolvers::informEnd(lbool res) {\n\n result = res;\n\n pthread_cond_broadcast(&cfinished);\n\n}\n\n\n\n\n\nMultiSolvers::MultiSolvers(ParallelSolver *s) :\n\n use_simplification(true), ok(true), maxnbthreads(4), nbthreads(opt_nbsolversmultithreads), nbsolvers(opt_nbsolversmultithreads), nbcompanions(4), nbcompbysolver(2),\n\n allClonesAreBuilt(0), showModel(false), winner(-1), var_decay(1 / 0.95), clause_decay(1 / 0.999), cla_inc(1), var_inc(1), random_var_freq(0.02), restart_first(100),\n\n restart_inc(1.5), learntsize_factor((double) 1 / (double) 3), learntsize_inc(1.1), expensive_ccmin(true), polarity_mode(polarity_false), maxmemory(opt_maxmemory),\n\n maxnbsolvers(opt_maxnbsolvers), verb(0), verbEveryConflicts(10000), numvar(0), numclauses(0) {\n\n result = l_Undef;\n", "file_path": "parallel/MultiSolvers.cc", "rank": 35, "score": 10.521071893488122 }, { "content": " struct timespec timeout;\n\n time(&timeout.tv_sec);\n\n timeout.tv_sec += MAXIMUM_SLEEP_DURATION;\n\n timeout.tv_nsec = 0;\n\n if(pthread_cond_timedwait(&cfinished, &mfinished, &timeout) != ETIMEDOUT)\n\n done = true;\n\n else\n\n printStats();\n\n\n\n float mem = memUsed();\n\n if(verb >= 1) printf(\"c Total Memory so far : %.2fMb\\n\", mem);\n\n if((maxmemory > 0) && (mem > maxmemory) && !sharedcomp->panicMode)\n\n printf(\"c ** reduceDB switching to Panic Mode due to memory limitations !\\n\"), sharedcomp->panicMode = true;\n\n\n\n if(!done && !adjustedlimitonce) {\n\n uint64_t sumconf = 0;\n\n uint64_t sumimported = 0;\n\n for(int i = 0; i < nbsolvers; i++) {\n\n sumconf += solvers[i]->conflicts;\n\n sumimported += solvers[i]->stats[nbimported];\n", "file_path": "parallel/MultiSolvers.cc", "rank": 36, "score": 10.51284922922064 }, { "content": " T& last (void) { return data[sz-1]; }\n\n\n\n // Vector interface:\n\n const T& operator [] (int index) const { return data[index]; }\n\n T& operator [] (int index) { return data[index]; }\n\n\n\n // Duplicatation (preferred instead):\n\n void copyTo(vec<T>& copy) const { copy.clear(); copy.growTo(sz); for (int i = 0; i < sz; i++) copy[i] = data[i]; }\n\n void moveTo(vec<T>& dest) { dest.clear(true); dest.data = data; dest.sz = sz; dest.cap = cap; data = NULL; sz = 0; cap = 0; }\n\n void memCopyTo(vec<T>& copy) const{\n\n copy.capacity(cap);\n\n copy.sz = sz;\n\n memcpy(copy.data,data,sizeof(T)*cap);\n\n }\n\n\n\n};\n\n\n\n\n\ntemplate<class T>\n\nvoid vec<T>::capacity(int min_cap) {\n", "file_path": "mtl/Vec.h", "rank": 37, "score": 10.397220868457346 }, { "content": "substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT\n\nNOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT\n\nOF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n **************************************************************************************************/\n\n\n\n#include \"glucose/parallel/ParallelSolver.h\"\n\n#include \"glucose/mtl/Sort.h\"\n\n\n\nusing namespace Glucose;\n\n\n\n//=====================================================================\n\n// == Options\n\n\n\nconst char* _cunstable = \"CORE/PARALLEL -- UNSTABLE FEATURES\";\n\nconst char* _parallel = \"PARALLEL\";\n\n\n", "file_path": "parallel/ParallelSolver.cc", "rank": 38, "score": 10.38581547477832 }, { "content": " {\n\n int x = heap[0];\n\n heap[0] = heap.last();\n\n indices[heap[0]] = 0;\n\n indices[x] = -1;\n\n heap.pop();\n\n if (heap.size() > 1) percolateDown(0);\n\n return x; \n\n }\n\n\n\n\n\n // Rebuild the heap from scratch, using the elements in 'ns':\n\n void build(vec<int>& ns) {\n\n for (int i = 0; i < heap.size(); i++)\n\n indices[heap[i]] = -1;\n\n heap.clear();\n\n\n\n for (int i = 0; i < ns.size(); i++){\n\n indices[ns[i]] = i;\n\n heap.push(ns[i]); }\n", "file_path": "mtl/Heap.h", "rank": 39, "score": 10.368889691849594 }, { "content": " int i,j;\n\n for (i = j = 0; i < clauses.size(); i++)\n\n if (ca[clauses[i]].mark() == 0)\n\n clauses[j++] = clauses[i];\n\n clauses.shrink(i - j);\n\n}\n\n\n\n\n\n//=================================================================================================\n\n// Garbage Collection methods:\n\n\n\n\n\nvoid SimpSolver::relocAll(ClauseAllocator& to)\n\n{\n\n if (!use_simplification) return;\n\n\n\n // All occurs lists:\n\n //\n\n for (int i = 0; i < nVars(); i++){\n\n vec<CRef>& cs = occurs[i];\n", "file_path": "simp/SimpSolver.cc", "rank": 40, "score": 10.346226320852596 }, { "content": "\n\n\n\n return result;\n\n}\n\n\n\n\n\n\n\nbool SimpSolver::addClause_(vec<Lit>& ps)\n\n{\n\n#ifndef NDEBUG\n\n for (int i = 0; i < ps.size(); i++)\n\n assert(!isEliminated(var(ps[i])));\n\n#endif\n\n int nclauses = clauses.size();\n\n\n\n if (use_rcheck && implied(ps))\n\n return true;\n\n\n\n if (!Solver::addClause_(ps))\n\n return false;\n", "file_path": "simp/SimpSolver.cc", "rank": 41, "score": 10.28590276026825 }, { "content": " c.strengthen(l);\n\n attachClause(cr);\n\n remove(occurs[var(l)], cr);\n\n n_occ[toInt(l)]--;\n\n updateElimHeap(var(l));\n\n }\n\n\n\n return c.size() == 1 ? enqueue(c[0]) && propagate() == CRef_Undef : true;\n\n}\n\n\n\n\n\n// Returns FALSE if clause is always satisfied ('out_clause' should not be used).\n\nbool SimpSolver::merge(const Clause& _ps, const Clause& _qs, Var v, vec<Lit>& out_clause)\n\n{\n\n merges++;\n\n out_clause.clear();\n\n\n\n bool ps_smallest = _ps.size() < _qs.size();\n\n const Clause& ps = ps_smallest ? _qs : _ps;\n\n const Clause& qs = ps_smallest ? _ps : _qs;\n", "file_path": "simp/SimpSolver.cc", "rank": 42, "score": 10.261288783957909 }, { "content": " }\n\n \n\n // NOTE: it seems possible that overflow can happen in the 'sz+1' expression of 'push()', but\n\n // in fact it can not since it requires that 'cap' is equal to INT_MAX. This in turn can not\n\n // happen given the way capacities are calculated (below). Essentially, all capacities are\n\n // even, but INT_MAX is odd.\n\n\n\n const T& last (void) const { return data[sz-1]; }\n\n T& last (void) { return data[sz-1]; }\n\n\n\n // Vector interface:\n\n const T& operator [] (int index) const { return data[index]; }\n\n T& operator [] (int index) { return data[index]; }\n\n\n\n // Duplicatation (preferred instead):\n\n void copyTo(vecThreads<T>& copy) const { copy.clear(); copy.growTo(sz); \n\n\tstartLoop();for (int i = 0; i < sz; i++) copy[i] = data[i]; endLoop();}\n\n void moveTo(vecThreads<T>& dest) { \n\n\tassert(false); // This cannot be made thread safe from here.\n\n\tdest.clear(true);\n", "file_path": "mtl/VecThreads.h", "rank": 43, "score": 10.247072030417295 }, { "content": "// This function set the incremental mode to true.\n\n// You can add special code for this mode here.\n\n\n\nvoid Solver::setIncrementalMode() {\n\n#ifdef INCREMENTAL\n\n incremental = true;\n\n#else\n\n fprintf(stderr, \"c Trying to set incremental mode, but not compiled properly for this.\\n\");\n\n exit(1);\n\n#endif\n\n}\n\n\n\n\n\n// Number of variables without selectors\n\nvoid Solver::initNbInitialVars(int nb) {\n\n nbVarsInitialFormula = nb;\n\n}\n\n\n\n\n\nbool Solver::isIncremental() {\n", "file_path": "core/Solver.cc", "rank": 44, "score": 10.186164099217073 }, { "content": " void insert (const K& k, const D& d) { if (checkCap(size+1)) rehash(); _insert(k, d); size++; }\n\n bool peek (const K& k, D& d) const {\n\n if (size == 0) return false;\n\n const vec<Pair>& ps = table[index(k)];\n\n for (int i = 0; i < ps.size(); i++)\n\n if (equals(ps[i].key, k)){\n\n d = ps[i].data;\n\n return true; } \n\n return false;\n\n }\n\n\n\n bool has (const K& k) const {\n\n if (size == 0) return false;\n\n const vec<Pair>& ps = table[index(k)];\n\n for (int i = 0; i < ps.size(); i++)\n\n if (equals(ps[i].key, k))\n\n return true;\n\n return false;\n\n }\n\n\n", "file_path": "mtl/Map.h", "rank": 45, "score": 10.125755335381212 }, { "content": " void adaptSolver(); // Adapt solver strategies\n\n\n\n // Maintaining Variable/Clause activity:\n\n //\n\n void varDecayActivity (); // Decay all variables with the specified factor. Implemented by increasing the 'bump' value instead.\n\n void varBumpActivity (Var v, double inc); // Increase a variable with the current 'bump' value.\n\n void varBumpActivity (Var v); // Increase a variable with the current 'bump' value.\n\n void claDecayActivity (); // Decay all clauses with the specified factor. Implemented by increasing the 'bump' value instead.\n\n void claBumpActivity (Clause& c); // Increase a clause with the current 'bump' value.\n\n\n\n // Operations on clauses:\n\n //\n\n void attachClause (CRef cr); // Attach a clause to watcher lists.\n\n void detachClause (CRef cr, bool strict = false); // Detach a clause to watcher lists.\n\n void detachClausePurgatory(CRef cr, bool strict = false);\n\n void attachClausePurgatory(CRef cr);\n\n void removeClause (CRef cr, bool inPurgatory = false); // Detach and free a clause.\n\n bool locked (const Clause& c) const; // Returns TRUE if a clause is a reason for some implication in the current state.\n\n bool satisfied (const Clause& c) const; // Returns TRUE if a clause is satisfied in the current state.\n\n\n", "file_path": "core/Solver.h", "rank": 46, "score": 10.034176739054026 }, { "content": " return false;\n\n else\n\n goto next;\n\n size++;\n\n }\n\n next:;\n\n }\n\n\n\n return true;\n\n}\n\n\n\n\n\nvoid SimpSolver::gatherTouchedClauses()\n\n{\n\n if (n_touched == 0) return;\n\n\n\n int i,j;\n\n for (i = j = 0; i < subsumption_queue.size(); i++)\n\n if (ca[subsumption_queue[i]].mark() == 0)\n\n ca[subsumption_queue[i]].mark(2);\n", "file_path": "simp/SimpSolver.cc", "rank": 47, "score": 10.002101830527522 }, { "content": "// Note that '_exit()' rather than 'exit()' has to be used. The reason is that 'exit()' calls\n\n// destructors and may cause deadlocks if a malloc/free function happens to be running (these\n\n// functions are guarded by locks for multithreaded use).\n\nstatic void SIGINT_exit(int signum) {\n\n printf(\"\\n\"); printf(\"*** INTERRUPTED ***\\n\");\n\n if (solver->verbosity > 0){\n\n printStats(*solver);\n\n printf(\"\\n\"); printf(\"*** INTERRUPTED ***\\n\"); }\n\n _exit(1); }\n\n\n\n\n\n//=================================================================================================\n\n// Main:\n\n\n\nint main(int argc, char** argv)\n\n{\n\n try {\n\n printf(\"c\\nc This is glucose 4.0 -- based on MiniSAT (Many thanks to MiniSAT team)\\nc\\n\");\n\n\n\n\n", "file_path": "simp/Main.cc", "rank": 48, "score": 9.937591437957966 }, { "content": "}\n\n\n\n\n\nMultiSolvers::MultiSolvers() : MultiSolvers(new ParallelSolver(-1)) {\n\n\n\n}\n\n\n\n\n\nMultiSolvers::~MultiSolvers() { }\n\n\n\n\n\n/**\n\n * Generate All solvers\n\n */\n\n\n\nvoid MultiSolvers::generateAllSolvers() {\n\n assert(solvers[0] != NULL);\n\n assert(allClonesAreBuilt == 0);\n\n\n\n for(int i = 1; i < nbsolvers; i++) {\n", "file_path": "parallel/MultiSolvers.cc", "rank": 49, "score": 9.908373969842815 }, { "content": " while(!__sync_bool_compare_and_swap(&lock,false, true));\n\n nbusers++; \n\n lock = false;\n\n}\n\ntemplate<class T>\n\ninline void vecThreads<T>::capacityProtected(int min_cap) {\n\n\tstartMaintenance();\n\n\tcapacity(min_cap);\n\n\tendMaintenance();\n\n}\n\n\n\ntemplate<class T>\n\nvoid vecThreads<T>::capacity(int min_cap) {\n\n if (cap >= min_cap) return;\n\n\n\n int add = imax((min_cap - cap + 1) & ~1, ((cap >> 1) + 2) & ~1); // NOTE: grow by approximately 3/2\n\n if (add > INT_MAX - cap || ((data = (T*)::realloc(data, (cap += add) * sizeof(T))) == NULL) && errno == ENOMEM)\n\n throw OutOfMemoryException();\n\n\n\n }\n", "file_path": "mtl/VecThreads.h", "rank": 51, "score": 9.884140947532163 }, { "content": " seed *= 1389796;\n\n int q = (int)(seed / 2147483647);\n\n seed -= (double)q * 2147483647;\n\n return seed / 2147483647; }\n\n\n\n // Returns a random integer 0 <= x < size. Seed must never be 0.\n\n static inline int irand(double& seed, int size) {\n\n return (int)(drand(seed) * size); }\n\n};\n\n\n\n\n\n//=================================================================================================\n\n// Implementation of inline methods:\n\n\n\ninline CRef Solver::reason(Var x) const { return vardata[x].reason; }\n\ninline int Solver::level (Var x) const { return vardata[x].level; }\n\n\n\ninline void Solver::insertVarOrder(Var x) {\n\n if (!order_heap.inHeap(x) && decision[x]) order_heap.insert(x); }\n\n\n", "file_path": "core/Solver.h", "rank": 52, "score": 9.857234514583523 }, { "content": "substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT\n\nNOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT\n\nOF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n **************************************************************************************************/\n\n\n\n#ifndef SOLVERSTATS_H\n\n#define\tSOLVERSTATS_H\n\n\n\n#include \"glucose/mtl/Map.h\"\n\n#include <string>\n\nnamespace Glucose {\n\n\n", "file_path": "core/SolverStats.h", "rank": 53, "score": 9.853754634604192 }, { "content": "inline int toInt (Lit p) { return p.x; } \n\ninline Lit toLit (int i) { Lit p; p.x = i; return p; } \n\n\n\n//const Lit lit_Undef = mkLit(var_Undef, false); // }- Useful special constants.\n\n//const Lit lit_Error = mkLit(var_Undef, true ); // }\n\n\n\nconst Lit lit_Undef = { -2 }; // }- Useful special constants.\n\nconst Lit lit_Error = { -1 }; // }\n\n\n\n\n\n//=================================================================================================\n\n// Lifted booleans:\n\n//\n\n// NOTE: this implementation is optimized for the case when comparisons between values are mostly\n\n// between one variable and one constant. Some care had to be taken to make sure that gcc \n\n// does enough constant propagation to produce sensible code, and this appears to be somewhat\n\n// fragile unfortunately.\n\n\n\n#define l_True (Glucose::lbool((uint8_t)0)) // gcc does not do constant propagation if these are real constants.\n\n#define l_False (Glucose::lbool((uint8_t)1))\n\n#define l_Undef (Glucose::lbool((uint8_t)2))\n\n\n", "file_path": "core/SolverTypes.h", "rank": 54, "score": 9.847273843221803 }, { "content": "}\n\n\n\n\n\n\n\n// Return true if the clause was succesfully added\n\nbool ClausesBuffer::pushClause(int threadId, Clause & c) {\n\n if (!whenFullRemoveOlder && (queuesize + c.size() + headerSize >= maxsize))\n\n\treturn false; // We need to remove some old clauses\n\n while (queuesize + c.size() + headerSize >= maxsize) { // We need to remove some old clauses\n\n\tforcedRemovedClauses ++;\n\n\tremoveLastClause();\n\n\tassert(queuesize > 0);\n\n }\n\n noCheckPush(c.size());\n\n noCheckPush(nbThreads>1?nbThreads-1:1);\n\n noCheckPush(threadId);\n\n for(int i=0;i<c.size();i++)\n\n\tnoCheckPush(toInt(c[i]));\n\n queuesize += c.size()+headerSize;\n\n return true;\n", "file_path": "parallel/ClausesBuffer.cc", "rank": 55, "score": 9.77424557182881 }, { "content": "substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT\n\nNOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT\n\nOF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n **************************************************************************************************/\n\n\n\n#ifndef Glucose_SimpSolver_h\n\n#define Glucose_SimpSolver_h\n\n\n\n#include \"glucose/mtl/Queue.h\"\n\n#include \"glucose/core/Solver.h\"\n\n#include \"glucose/mtl/Clone.h\"\n\n\n\nnamespace Glucose {\n\n\n\n//=================================================================================================\n\n\n\n\n", "file_path": "simp/SimpSolver.h", "rank": 56, "score": 9.745978370262286 }, { "content": "substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT\n\nNOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT\n\nOF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n **************************************************************************************************/\n\n\n\n\n\n#ifndef Glucose_SolverTypes_h\n\n#define Glucose_SolverTypes_h\n\n\n\n#include <assert.h>\n\n#include <stdint.h>\n\n#include <pthread.h>\n\n\n\n#include \"glucose/mtl/IntTypes.h\"\n\n#include \"glucose/mtl/Alg.h\"\n\n#include \"glucose/mtl/Vec.h\"\n", "file_path": "core/SolverTypes.h", "rank": 57, "score": 9.742777696565943 }, { "content": " // again during 'gatherTouchedClauses()'. If nothing happens\n\n // in between, it will only be checked once. Otherwise, it may\n\n // be checked twice unnecessarily. This is an unfortunate\n\n // consequence of how backward subsumption is used to mimic\n\n // forward subsumption.\n\n subsumption_queue.insert(cr);\n\n for (int i = 0; i < c.size(); i++){\n\n occurs[var(c[i])].push(cr);\n\n n_occ[toInt(c[i])]++;\n\n touched[var(c[i])] = 1;\n\n n_touched++;\n\n if (elim_heap.inHeap(var(c[i])))\n\n elim_heap.increase(var(c[i]));\n\n }\n\n }\n\n\n\n return true;\n\n}\n\n\n\n\n", "file_path": "simp/SimpSolver.cc", "rank": 58, "score": 9.633301208267381 }, { "content": "substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT\n\nNOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT\n\nOF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n **************************************************************************************************/\n\n\n\n#ifndef Glucose_Solver_h\n\n#define Glucose_Solver_h\n\n\n\n#include \"glucose/mtl/Heap.h\"\n\n#include \"glucose/mtl/Alg.h\"\n\n#include \"glucose/utils/Options.h\"\n\n#include \"glucose/core/SolverTypes.h\"\n\n#include \"glucose/core/BoundedQueue.h\"\n\n#include \"glucose/core/Constants.h\"\n\n#include \"glucose/mtl/Clone.h\"\n\n#include \"glucose/core/SolverStats.h\"\n\n\n\n\n\nnamespace Glucose {\n\n// Core stats \n\n \n", "file_path": "core/Solver.h", "rank": 59, "score": 9.525522098440907 }, { "content": " }\n\n learnts.shrink(i - j);\n\n checkGarbage();\n\n}\n\n\n\n\n\nvoid Solver::removeSatisfied(vec <CRef> &cs) {\n\n\n\n int i, j;\n\n for(i = j = 0; i < cs.size(); i++) {\n\n Clause &c = ca[cs[i]];\n\n\n\n\n\n if(satisfied(c)) if(c.getOneWatched())\n\n removeClause(cs[i], true);\n\n else\n\n removeClause(cs[i]);\n\n else\n\n cs[j++] = cs[i];\n\n }\n", "file_path": "core/Solver.cc", "rank": 60, "score": 9.47842618576722 }, { "content": "substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT\n\nNOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT\n\nOF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n **************************************************************************************************/\n\n\n\n#ifndef PARALLELSOLVER_H\n\n#define\tPARALLELSOLVER_H\n\n\n\n#include \"glucose/core/SolverTypes.h\"\n\n#include \"glucose/core/Solver.h\"\n\n#include \"glucose/simp/SimpSolver.h\"\n\n#include \"glucose/parallel/SharedCompanion.h\"\n\nnamespace Glucose {\n\n \n\n enum ParallelStats{\n\n nbexported=coreStatsSize,\n", "file_path": "parallel/ParallelSolver.h", "rank": 61, "score": 9.469444245115325 }, { "content": "\n\n // Pointer to first element:\n\n operator T* (void) { return data; }\n\n\n\n // Size operations:\n\n int size (void) const { return sz; }\n\n void shrink (int nelems) { assert(nelems <= sz); for (int i = 0; i < nelems; i++) sz--, data[sz].~T(); }\n\n void shrink_ (int nelems) { assert(nelems <= sz); sz -= nelems; }\n\n int capacity (void) const { return cap; }\n\n void capacity (int min_cap);\n\n void growTo (int size);\n\n void growTo (int size, const T& pad);\n\n void clear (bool dealloc = false);\n\n\n\n // Stack interface:\n\n void push (void) { if (sz == cap) capacity(sz+1); new (&data[sz]) T(); sz++; }\n\n void push (const T& elem) { if (sz == cap) capacity(sz+1); data[sz++] = elem; }\n\n void push_ (const T& elem) { assert(sz < cap); data[sz++] = elem; }\n\n void pop (void) { assert(sz > 0); sz--, data[sz].~T(); }\n\n \n", "file_path": "mtl/Vec.h", "rank": 62, "score": 9.452171813636404 }, { "content": " int peak_kb = 0;\n\n while (!feof(in) && fscanf(in, \"VmPeak: %d kB\", &peak_kb) != 1)\n\n while (!feof(in) && fgetc(in) != '\\n')\n\n ;\n\n fclose(in);\n\n\n\n return peak_kb;\n\n}\n\n\n\ndouble Glucose::memUsed() { return (double)memReadStat(0) * (double)getpagesize() / (1024*1024); }\n\ndouble Glucose::memUsedPeak() { \n\n double peak = memReadPeak() / 1024;\n\n return peak == 0 ? memUsed() : peak; }\n\n\n\n#elif defined(__FreeBSD__)\n\n\n\ndouble Glucose::memUsed(void) {\n\n struct rusage ru;\n\n getrusage(RUSAGE_SELF, &ru);\n\n return (double)ru.ru_maxrss / 1024; }\n", "file_path": "utils/System.cc", "rank": 63, "score": 9.407175303999761 }, { "content": "substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT\n\nNOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT\n\nOF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n **************************************************************************************************/\n\n\n\n#ifndef MultiSolvers_h\n\n#define MultiSolvers_h\n\n\n\n#include \"glucose/parallel/ParallelSolver.h\"\n\n\n\nnamespace Glucose {\n", "file_path": "parallel/MultiSolvers.h", "rank": 64, "score": 9.402662853928067 }, { "content": "}\n\n\n\n\n\nlbool MultiSolvers::solve() {\n\n pthread_attr_t thAttr;\n\n int i;\n\n\n\n adjustNumberOfCores();\n\n sharedcomp->setNbThreads(nbsolvers);\n\n if(verb >= 1)\n\n printf(\"c | Generating clones |\\n\");\n\n generateAllSolvers();\n\n if(verb >= 1) {\n\n printf(\"c |  all clones generated. Memory = %6.2fMb. |\\n\", memUsed());\n\n printf(\"c ========================================================================================================|\\n\");\n\n }\n\n\n\n\n\n model.clear();\n\n\n", "file_path": "parallel/MultiSolvers.cc", "rank": 65, "score": 9.362720204392499 }, { "content": "\n\nvoid SimpSolver::removeClause(CRef cr,bool inPurgatory)\n\n{\n\n const Clause& c = ca[cr];\n\n\n\n if (use_simplification)\n\n for (int i = 0; i < c.size(); i++){\n\n n_occ[toInt(c[i])]--;\n\n updateElimHeap(var(c[i]));\n\n occurs.smudge(var(c[i]));\n\n }\n\n\n\n Solver::removeClause(cr,inPurgatory);\n\n}\n\n\n\n\n\nbool SimpSolver::strengthenClause(CRef cr, Lit l)\n\n{\n\n Clause& c = ca[cr];\n\n assert(decisionLevel() == 0);\n", "file_path": "simp/SimpSolver.cc", "rank": 66, "score": 9.354045452786892 }, { "content": "substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT\n\nNOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT\n\nOF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n **************************************************************************************************/\n\n\n\n\n\n#ifndef BoundedQueue_h\n\n#define BoundedQueue_h\n\n\n\n#include \"glucose/mtl/Vec.h\"\n\n\n\n//=================================================================================================\n\n\n\nnamespace Glucose {\n\n\n\ntemplate <class T>\n", "file_path": "core/BoundedQueue.h", "rank": 67, "score": 9.342358683094384 }, { "content": "\n\n // Finally we can use old activity or size, we choose the last one\n\n return ca[x].activity() < ca[y].activity();\n\n //return x->size() < y->size();\n\n\n\n //return ca[x].size() > 2 && (ca[y].size() == 2 || ca[x].activity() < ca[y].activity()); } \n\n }\n\n};\n\n\n\n// @overide\n\nvoid ParallelSolver::reduceDB() {\n\n\n\n int i, j;\n\n stats[nbReduceDB]++;\n\n \n\n int limit;\n\n\n\n if (chanseokStrategy)\n\n sort(learnts, reduceDBAct_lt(ca));\n\n else \n", "file_path": "parallel/ParallelSolver.cc", "rank": 68, "score": 9.290653759500163 }, { "content": " if(incremental)\n\n return (value(c[0]) == l_True) || (value(c[1]) == l_True);\n\n#endif\n\n\n\n // Default mode\n\n for(int i = 0; i < c.size(); i++)\n\n if(value(c[i]) == l_True)\n\n return true;\n\n return false;\n\n}\n\n\n\n\n\n/************************************************************\n\n * Compute LBD functions\n\n *************************************************************/\n\n\n\ntemplate <typename T>inline unsigned int Solver::computeLBD(const T &lits, int end) {\n\n int nblevels = 0;\n\n MYFLAG++;\n\n#ifdef INCREMENTAL\n", "file_path": "core/Solver.cc", "rank": 69, "score": 9.267381987638984 }, { "content": "substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT\n\nNOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT\n\nOF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n **************************************************************************************************/\n\n\n\n/* This class is a general companion for a solver.\n\n * The idea is to be able to have different kind of companions:\n\n * - SharedCompanion that shares clauses between threads\n\n * - NetworkCompanion (Not in this version) that sends clauses over the network\n\n *\n\n * The implementaton is trivial. Just keep track of watched Solvers by the companion.\n\n **/\n\n\n\n#include \"glucose/parallel/SolverCompanion.h\"\n\n\n\nusing namespace Glucose;\n", "file_path": "parallel/SolverCompanion.cc", "rank": 70, "score": 9.209670604416562 }, { "content": "substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT\n\nNOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT\n\nOF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n **************************************************************************************************/\n\n\n\n#ifndef ClausesBuffer_h \n\n#define ClausesBuffer_h\n\n\n\n#include \"glucose/mtl/Vec.h\"\n\n#include \"glucose/core/SolverTypes.h\"\n\n#include \"glucose/core/Solver.h\"\n\n\n\n//=================================================================================================\n\n\n\nnamespace Glucose {\n\n // index : size clause\n\n // index + 1 : nbSeen\n\n // index + 2 : threadId\n\n // index + 3 : .. index + 3 + size : Lit of clause\n", "file_path": "parallel/ClausesBuffer.h", "rank": 71, "score": 9.143270120206118 }, { "content": "bool SimpSolver::eliminate(bool turn_off_elim)\n\n{\n\n if (!simplify()) {\n\n ok = false;\n\n return false;\n\n }\n\n else if (!use_simplification)\n\n return true;\n\n\n\n // Main simplification loop:\n\n //\n\n\n\n int toPerform = clauses.size()<=4800000;\n\n \n\n if(!toPerform) {\n\n printf(\"c Too many clauses... No preprocessing\\n\");\n\n }\n\n\n\n while (toPerform && (n_touched > 0 || bwdsub_assigns < trail.size() || elim_heap.size() > 0)){\n\n\n", "file_path": "simp/SimpSolver.cc", "rank": 72, "score": 9.118964768861801 }, { "content": "\t value = value*(1-exp)/(1-a);\n\n\t expComputed = true;\n\n\t return value;\n\n\t \n\n\n\n\t}\n\n\tvoid fastclear() {first = 0; last = 0; queuesize=0; sumofqueue=0;} // to be called after restarts... Discard the queue\n\n\t\n\n int size(void) { return queuesize; }\n\n\n\n void clear(bool dealloc = false) { elems.clear(dealloc); first = 0; maxsize=0; queuesize=0;sumofqueue=0;}\n\n\n\n void copyTo(bqueue &dest) const {\n\n dest.last = last;\n\n dest.sumofqueue = sumofqueue;\n\n dest.maxsize = maxsize;\n\n dest.queuesize = queuesize;\n\n dest.expComputed = expComputed;\n\n dest.exp = exp;\n\n dest.value = value;\n\n dest.first = first; \n\n elems.copyTo(dest.elems);\n\n }\n\n};\n\n}\n\n//=================================================================================================\n\n\n\n#endif\n", "file_path": "core/BoundedQueue.h", "rank": 73, "score": 9.059676374194291 }, { "content": "#define Glucose_Map_h\n\n\n\n#include \"glucose/mtl/IntTypes.h\"\n\n#include \"glucose/mtl/Vec.h\"\n\n#include <string>\n\n#include <unordered_map>\n\n\n\nnamespace Glucose {\n\n\n\n//=================================================================================================\n\n// Default hash/equals functions\n\n//\n\n\n\nstatic inline uint32_t hash(std::string x) {std::hash<std::string> hasher;return hasher(x); }\n\n\n\ntemplate<class K> struct Hash { uint32_t operator()(const K& k) const { return hash(k); } };\n\ntemplate<class K> struct Equal { bool operator()(const K& k1, const K& k2) const { return k1 == k2; } };\n\n\n\ntemplate<class K> struct DeepHash { uint32_t operator()(const K* k) const { return hash(*k); } };\n\ntemplate<class K> struct DeepEqual { bool operator()(const K* k1, const K* k2) const { return *k1 == *k2; } };\n", "file_path": "mtl/Map.h", "rank": 74, "score": 9.025607483761558 }, { "content": " }\n\n\n\n\n\n public:\n\n Heap(const Comp& c) : lt(c) { }\n\n\n\n int size () const { return heap.size(); }\n\n bool empty () const { return heap.size() == 0; }\n\n bool inHeap (int n) const { return n < indices.size() && indices[n] >= 0; }\n\n int operator[](int index) const { assert(index < heap.size()); return heap[index]; }\n\n\n\n\n\n void decrease (int n) { assert(inHeap(n)); percolateUp (indices[n]); }\n\n void increase (int n) { assert(inHeap(n)); percolateDown(indices[n]); }\n\n\n\n void copyTo(Heap& copy) const {heap.copyTo(copy.heap);indices.copyTo(copy.indices);}\n\n\n\n // Safe variant of insert/decrease/increase:\n\n void update(int n)\n\n {\n", "file_path": "mtl/Heap.h", "rank": 75, "score": 8.939925595908651 }, { "content": "substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT\n\nNOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT\n\nOF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n **************************************************************************************************/\n\n\n\n/* This class is responsible for protecting (by mutex) information exchange between threads.\n\n * It also allows each solver to send / receive clause / unary clauses.\n\n *\n\n * Only one sharedCompanion is created for all the solvers\n\n */\n\n\n\n\n\n#ifndef SharedCompanion_h\n\n#define SharedCompanion_h\n\n#include \"glucose/core/SolverTypes.h\"\n\n#include \"glucose/parallel/ParallelSolver.h\"\n\n#include \"glucose/parallel/SolverCompanion.h\"\n\n#include \"glucose/parallel/ClausesBuffer.h\"\n\n\n\nnamespace Glucose {\n\n\n\n \n", "file_path": "parallel/SharedCompanion.h", "rank": 76, "score": 8.91385919567561 }, { "content": "\n\n\tint size(void) { return queuesize; }\n\n\n\n\tvoid clear(bool dealloc = false) { elems.clear(dealloc); first = 0; maxsize=0; queuesize=0;}\n\n\tinline int toInt (Lit p) { return p.x; } \n\n\n\n };\n\n}\n\n//=================================================================================================\n\n\n\n#endif\n", "file_path": "parallel/ClausesBuffer.h", "rank": 77, "score": 8.911877888160756 }, { "content": " return incremental;\n\n}\n\n\n\n\n\n//=================================================================================================\n\n// Minor methods:\n\n\n\n\n\n// Creates a new SAT variable in the solver. If 'decision' is cleared, variable will not be\n\n// used as a decision variable (NOTE! This has effects on the meaning of a SATISFIABLE result).\n\n//\n\n\n\nVar Solver::newVar(bool sign, bool dvar) {\n\n int v = nVars();\n\n watches.init(mkLit(v, false));\n\n watches.init(mkLit(v, true));\n\n watchesBin.init(mkLit(v, false));\n\n watchesBin.init(mkLit(v, true));\n\n unaryWatches.init(mkLit(v, false));\n\n unaryWatches.init(mkLit(v, true));\n", "file_path": "core/Solver.cc", "rank": 78, "score": 8.843808248095812 }, { "content": " fpu_control_t oldcw, newcw;\n\n _FPU_GETCW(oldcw); newcw = (oldcw & ~_FPU_EXTENDED) | _FPU_DOUBLE; _FPU_SETCW(newcw);\n\n printf(\"c WARNING: for repeatability, setting FPU to use double precision\\n\");\n\n#endif\n\n // Extra options:\n\n //\n\n IntOption verb (\"MAIN\", \"verb\", \"Verbosity level (0=silent, 1=some, 2=more).\", 1, IntRange(0, 2));\n\n BoolOption mod (\"MAIN\", \"model\", \"show model.\", false);\n\n IntOption vv (\"MAIN\", \"vv\", \"Verbosity every vv conflicts\", 10000, IntRange(1,INT32_MAX));\n\n BoolOption pre (\"MAIN\", \"pre\", \"Completely turn on/off any preprocessing.\", true);\n\n\n\n IntOption cpu_lim(\"MAIN\", \"cpu-lim\",\"Limit on CPU time allowed in seconds.\\n\", INT32_MAX, IntRange(0, INT32_MAX));\n\n IntOption mem_lim(\"MAIN\", \"mem-lim\",\"Limit on memory usage in megabytes.\\n\", INT32_MAX, IntRange(0, INT32_MAX));\n\n \n\n parseOptions(argc, argv, true);\n\n\n\n\tMultiSolvers msolver;\n\n pmsolver = & msolver;\n\n msolver.setVerbosity(verb);\n\n msolver.setVerbEveryConflicts(vv);\n", "file_path": "parallel/Main.cc", "rank": 79, "score": 8.768557926795035 }, { "content": "substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT\n\nNOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT\n\nOF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n **************************************************************************************************/\n\n\n\n\n\n#ifndef SolverConfiguration_h\n\n#define SolverConfiguration_h\n\n\n\n\n\n\n\nnamespace Glucose {\n\n\n", "file_path": "parallel/SolverConfiguration.h", "rank": 80, "score": 8.732299161461558 }, { "content": "\tdouble random_seed;\n\n\n\n\t// Returns a random float 0 <= x < 1. Seed must never be 0.\n\n\tstatic inline double drand(double& seed) {\n\n\t seed *= 1389796;\n\n\t int q = (int)(seed / 2147483647);\n\n\t seed -= (double)q * 2147483647;\n\n\t return seed / 2147483647; }\n\n\n\n\t// Returns a random integer 0 <= x < size. Seed must never be 0.\n\n\tstatic inline int irand(double& seed, int size) {\n\n\t return (int)(drand(seed) * size); }\n\n\n\n};\n\n}\n\n#endif\n", "file_path": "parallel/SharedCompanion.h", "rank": 81, "score": 8.680727704867616 }, { "content": " setUsageHelp(\"c USAGE: %s [options] <input-file> <result-output-file>\\n\\n where input may be either in plain or gzipped DIMACS.\\n\");\n\n\n\n\n\n#if defined(__linux__)\n\n fpu_control_t oldcw, newcw;\n\n _FPU_GETCW(oldcw); newcw = (oldcw & ~_FPU_EXTENDED) | _FPU_DOUBLE; _FPU_SETCW(newcw);\n\n //printf(\"c WARNING: for repeatability, setting FPU to use double precision\\n\");\n\n#endif\n\n // Extra options:\n\n //\n\n IntOption verb (\"MAIN\", \"verb\", \"Verbosity level (0=silent, 1=some, 2=more).\", 1, IntRange(0, 2));\n\n BoolOption mod (\"MAIN\", \"model\", \"show model.\", false);\n\n IntOption vv (\"MAIN\", \"vv\", \"Verbosity every vv conflicts\", 10000, IntRange(1,INT32_MAX));\n\n BoolOption pre (\"MAIN\", \"pre\", \"Completely turn on/off any preprocessing.\", true);\n\n StringOption dimacs (\"MAIN\", \"dimacs\", \"If given, stop after preprocessing and write the result to this file.\");\n\n IntOption cpu_lim(\"MAIN\", \"cpu-lim\",\"Limit on CPU time allowed in seconds.\\n\", INT32_MAX, IntRange(0, INT32_MAX));\n\n IntOption mem_lim(\"MAIN\", \"mem-lim\",\"Limit on memory usage in megabytes.\\n\", INT32_MAX, IntRange(0, INT32_MAX));\n\n // BoolOption opt_incremental (\"MAIN\",\"incremental\", \"Use incremental SAT solving\",false);\n\n\n\n BoolOption opt_certified (_certified, \"certified\", \"Certified UNSAT using DRUP format\", false);\n", "file_path": "simp/Main.cc", "rank": 82, "score": 8.59209672278176 }, { "content": " touched .push(0);\n\n elim_heap .insert(v);\n\n }\n\n return v; }\n\n\n\nlbool SimpSolver::solve_(bool do_simp, bool turn_off_simp)\n\n{\n\n vec<Var> extra_frozen;\n\n lbool result = l_True;\n\n do_simp &= use_simplification;\n\n\n\n if (do_simp){\n\n // Assumptions must be temporarily frozen to run variable elimination:\n\n for (int i = 0; i < assumptions.size(); i++){\n\n Var v = var(assumptions[i]);\n\n\n\n // If an assumption has been eliminated, remember it.\n\n assert(!isEliminated(v));\n\n\n\n if (!frozen[v]){\n", "file_path": "simp/SimpSolver.cc", "rank": 83, "score": 8.54272149805645 }, { "content": "extern const char *_parallel;\n\nextern const char *_cunstable;\n\n// Options at the parallel solver level\n\nstatic IntOption opt_nbsolversmultithreads(_parallel, \"nthreads\", \"Number of core threads for syrup (0 for automatic)\", 0);\n\nstatic IntOption opt_maxnbsolvers(_parallel, \"maxnbthreads\", \"Maximum number of core threads to ask for (when nbthreads=0)\", 4);\n\nstatic IntOption opt_maxmemory(_parallel, \"maxmemory\", \"Maximum memory to use (in Mb, 0 for no software limit)\", 20000);\n\nstatic IntOption opt_statsInterval(_parallel, \"statsinterval\", \"Seconds (real time) between two stats reports\", 5);\n\n//\n\n// Shared with ClausesBuffer.cc\n\nBoolOption opt_whenFullRemoveOlder(_parallel, \"removeolder\", \"When the FIFO for exchanging clauses between threads is full, remove older clauses\", false);\n\nIntOption opt_fifoSizeByCore(_parallel, \"fifosize\", \"Size of the FIFO structure for exchanging clauses between threads, by threads\", 100000);\n\n//\n\n// Shared options with Solver.cc \n\nBoolOption opt_dontExportDirectReusedClauses(_cunstable, \"reusedClauses\", \"Don't export directly reused clauses\", false);\n\nBoolOption opt_plingeling(_cunstable, \"plingeling\", \"plingeling strategy for sharing clauses (exploratory feature)\", false);\n\n\n\n#include <sys/time.h>\n\n#include <sys/resource.h>\n\n#include <unistd.h>\n\n\n", "file_path": "parallel/MultiSolvers.cc", "rank": 84, "score": 8.478364946332379 }, { "content": " //\n\n int parsing;\n\n int grow; // Allow a variable elimination step to grow by a number of clauses (default to zero).\n\n int clause_lim; // Variables are not eliminated if it produces a resolvent with a length above this limit.\n\n // -1 means no limit.\n\n int subsumption_lim; // Do not check if subsumption against a clause larger than this. -1 means no limit.\n\n double simp_garbage_frac; // A different limit for when to issue a GC during simplification (Also see 'garbage_frac').\n\n\n\n bool use_asymm; // Shrink clauses by asymmetric branching.\n\n bool use_rcheck; // Check if a clause is already implied. Prett costly, and subsumes subsumptions :)\n\n bool use_elim; // Perform variable elimination.\n\n // Statistics:\n\n //\n\n int merges;\n\n int asymm_lits;\n\n int eliminated_vars;\n\n bool use_simplification;\n\n\n\n protected:\n\n\n", "file_path": "simp/SimpSolver.h", "rank": 85, "score": 8.45719523129428 }, { "content": "\n\ntemplate<class T>\n\nvoid vecThreads<T>::endLoop() {\n\n while(!__sync_bool_compare_and_swap(&lock,false, true));\n\n nbusers--; \n\n lock = false;\n\n}\n\n\n\ntemplate<class T>\n\ninline void vecThreads<T>::startMaintenance() {\n\n bool retry = true;\n\n while (retry) {\n\n\twhile(!__sync_bool_compare_and_swap(&lock,false, true));\n\n\tif (nbusers == 0) {nbusers--; retry=false;}\n\n\tlock = false;\n\n }\n\n}\n\n\n\ntemplate<class T>\n\ninline void vecThreads<T>::endMaintenance() {\n", "file_path": "mtl/VecThreads.h", "rank": 86, "score": 8.437124842617195 }, { "content": "substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT\n\nNOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT\n\nOF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n **************************************************************************************************/\n\n\n\n/* This class is a general companion for a solver.\n\n * The idea is to be able to have different kind of companions:\n\n * - SharedCompanion that shares clauses between threads\n\n * - NetworkCompanion (Not in this version) that sends clauses over the network\n\n **/\n\n\n\n#ifndef SolverCompanion_h\n\n#define SolverCompanion_h\n\n#include \"glucose/mtl/Vec.h\"\n\nnamespace Glucose {\n\n \n", "file_path": "parallel/SolverCompanion.h", "rank": 87, "score": 8.426783751442908 }, { "content": " , use_asymm (opt_use_asymm)\n\n , use_rcheck (opt_use_rcheck)\n\n , use_elim (opt_use_elim)\n\n , merges (0)\n\n , asymm_lits (0)\n\n , eliminated_vars (0)\n\n , use_simplification (true)\n\n , elimorder (1)\n\n , occurs (ClauseDeleted(ca))\n\n , elim_heap (ElimLt(n_occ))\n\n , bwdsub_assigns (0)\n\n , n_touched (0)\n\n{\n\n vec<Lit> dummy(1,lit_Undef);\n\n ca.extra_clause_field = true; // NOTE: must happen before allocating the dummy clause below.\n\n bwdsub_tmpunit = ca.alloc(dummy);\n\n remove_satisfied = false;\n\n}\n\n\n\n\n", "file_path": "simp/SimpSolver.cc", "rank": 88, "score": 8.388106158485018 }, { "content": " CRef bwdsub_tmpunit;\n\n\n\n // Main internal methods:\n\n //\n\n virtual lbool solve_ (bool do_simp = true, bool turn_off_simp = false);\n\n bool asymm (Var v, CRef cr);\n\n bool asymmVar (Var v);\n\n void updateElimHeap (Var v);\n\n void gatherTouchedClauses ();\n\n bool merge (const Clause& _ps, const Clause& _qs, Var v, vec<Lit>& out_clause);\n\n bool merge (const Clause& _ps, const Clause& _qs, Var v, int& size);\n\n bool backwardSubsumptionCheck (bool verbose = false);\n\n bool eliminateVar (Var v);\n\n void extendModel ();\n\n\n\n void removeClause (CRef cr,bool inPurgatory=false);\n\n bool strengthenClause (CRef cr, Lit l);\n\n void cleanUpClauses ();\n\n bool implied (const vec<Lit>& c);\n\n virtual void relocAll (ClauseAllocator& to);\n", "file_path": "simp/SimpSolver.h", "rank": 89, "score": 8.381211548630345 }, { "content": "\n\n // fprintf(stderr, \"checking %d: %s against flag <%s> (%s)\\n\", i, argv[i], Option::getOptionList()[k]->name, parsed_ok ? \"ok\" : \"skip\");\n\n }\n\n\n\n if (!parsed_ok)\n\n if (strict && match(argv[i], \"-\"))\n\n fprintf(stderr, \"ERROR! Unknown flag \\\"%s\\\". Use '--%shelp' for help.\\n\", argv[i], Option::getHelpPrefixString()), exit(1);\n\n else\n\n argv[j++] = argv[i];\n\n }\n\n }\n\n\n\n argc -= (i - j);\n\n}\n\n\n\n\n\nvoid Glucose::setUsageHelp (const char* str){ Option::getUsageString() = str; }\n\nvoid Glucose::setHelpPrefixStr (const char* str){ Option::getHelpPrefixString() = str; }\n\nvoid Glucose::printUsageAndExit (int argc, char** argv, bool verbose)\n\n{\n", "file_path": "utils/Options.cc", "rank": 90, "score": 8.3762545077656 }, { "content": "#ifndef Glucose_XAlloc_h\n\n#define Glucose_XAlloc_h\n\n\n\n#include <errno.h>\n\n#include <stdlib.h>\n\n#include <stdio.h>\n\n\n\nnamespace Glucose {\n\n\n\n//=================================================================================================\n\n// Simple layer on top of malloc/realloc to catch out-of-memory situtaions and provide some typing:\n\n\n", "file_path": "mtl/XAlloc.h", "rank": 91, "score": 8.368332687906332 }, { "content": "\n\n\n\n// Check if 'p' can be removed. 'abstract_levels' is used to abort early if the algorithm is\n\n// visiting literals at levels that cannot be removed later.\n\n\n\nbool Solver::litRedundant(Lit p, uint32_t abstract_levels) {\n\n analyze_stack.clear();\n\n analyze_stack.push(p);\n\n int top = analyze_toclear.size();\n\n while(analyze_stack.size() > 0) {\n\n assert(reason(var(analyze_stack.last())) != CRef_Undef);\n\n Clause &c = ca[reason(var(analyze_stack.last()))];\n\n analyze_stack.pop(); //\n\n if(c.size() == 2 && value(c[0]) == l_False) {\n\n assert(value(c[1]) == l_True);\n\n Lit tmp = c[0];\n\n c[0] = c[1], c[1] = tmp;\n\n }\n\n\n\n for(int i = 1; i < c.size(); i++) {\n", "file_path": "core/Solver.cc", "rank": 92, "score": 8.248602267955413 }, { "content": "\n\ninline void MultiSolvers::setVerbosity(int i) {verb = i;}\n\ninline void MultiSolvers::setVerbEveryConflicts(int i) {verbEveryConflicts=i;}\n\ninline int MultiSolvers::nVars () const { return numvar; }\n\ninline int MultiSolvers::nClauses () const { return numclauses; }\n\ninline int MultiSolvers::verbosity() {return verb;}\n\ninline ParallelSolver* MultiSolvers::getPrimarySolver() {return solvers[0];}\n\n\n\n\n\n}\n\n#endif\n\n\n", "file_path": "parallel/MultiSolvers.h", "rank": 93, "score": 8.247866643638238 }, { "content": "\n\nstatic BoolOption opt_use_asymm (_cat, \"asymm\", \"Shrink clauses by asymmetric branching.\", false);\n\nstatic BoolOption opt_use_rcheck (_cat, \"rcheck\", \"Check if a clause is already implied. (costly)\", false);\n\nstatic BoolOption opt_use_elim (_cat, \"elim\", \"Perform variable elimination.\", true);\n\nstatic IntOption opt_grow (_cat, \"grow\", \"Allow a variable elimination step to grow by a number of clauses.\", 0);\n\nstatic IntOption opt_clause_lim (_cat, \"cl-lim\", \"Variables are not eliminated if it produces a resolvent with a length above this limit. -1 means no limit\", 20, IntRange(-1, INT32_MAX));\n\nstatic IntOption opt_subsumption_lim (_cat, \"sub-lim\", \"Do not check if subsumption against a clause larger than this. -1 means no limit.\", 1000, IntRange(-1, INT32_MAX));\n\nstatic DoubleOption opt_simp_garbage_frac(_cat, \"simp-gc-frac\", \"The fraction of wasted memory allowed before a garbage collection is triggered during simplification.\", 0.5, DoubleRange(0, false, HUGE_VAL, false));\n\n\n\n\n\n//=================================================================================================\n\n// Constructor/Destructor:\n\n\n\n\n\nSimpSolver::SimpSolver() :\n\n Solver()\n\n , grow (opt_grow)\n\n , clause_lim (opt_clause_lim)\n\n , subsumption_lim (opt_subsumption_lim)\n\n , simp_garbage_frac (opt_simp_garbage_frac)\n", "file_path": "simp/SimpSolver.cc", "rank": 94, "score": 8.244422693666444 }, { "content": " \n\n bool simplify (); // Removes already satisfied clauses.\n\n \n\n int nVars () const; // The current number of variables.\n\n int nClauses () const; // The current number of variables.\n\n ParallelSolver *getPrimarySolver();\n\n \n\n void generateAllSolvers();\n\n \n\n // Solving:\n\n //\n\n lbool solve (); // Search without assumptions.\n\n bool eliminate(); // Perform variable elimination\n\n void adjustParameters();\n\n void adjustNumberOfCores();\n\n void interrupt() {}\n\n vec<lbool> model; // If problem is satisfiable, this vector contains the model (if any).\n\n inline bool okay() {\n\n if(!ok) return ok;\n\n for(int i = 0;i<solvers.size();i++) {\n", "file_path": "parallel/MultiSolvers.h", "rank": 95, "score": 8.20017588248965 }, { "content": "static DoubleOption opt_random_seed(_cat, \"rnd-seed\", \"Used by the random variable selection\", 91648253, DoubleRange(0, false, HUGE_VAL, false));\n\nstatic IntOption opt_ccmin_mode(_cat, \"ccmin-mode\", \"Controls conflict clause minimization (0=none, 1=basic, 2=deep)\", 2, IntRange(0, 2));\n\nstatic IntOption opt_phase_saving(_cat, \"phase-saving\", \"Controls the level of phase saving (0=none, 1=limited, 2=full)\", 2, IntRange(0, 2));\n\nstatic BoolOption opt_rnd_init_act(_cat, \"rnd-init\", \"Randomize the initial activity\", false);\n\nstatic DoubleOption opt_garbage_frac(_cat, \"gc-frac\", \"The fraction of wasted memory allowed before a garbage collection is triggered\", 0.20,\n\n DoubleRange(0, false, HUGE_VAL, false));\n\nstatic BoolOption opt_glu_reduction(_cat, \"gr\", \"glucose strategy to fire clause database reduction (must be false to fire Chanseok strategy)\", true);\n\nstatic BoolOption opt_luby_restart(_cat, \"luby\", \"Use the Luby restart sequence\", false);\n\nstatic DoubleOption opt_restart_inc(_cat, \"rinc\", \"Restart interval increase factor\", 2, DoubleRange(1, false, HUGE_VAL, false));\n\nstatic IntOption opt_luby_restart_factor(_cred, \"luby-factor\", \"Luby restart factor\", 100, IntRange(1, INT32_MAX));\n\n\n\nstatic IntOption opt_randomize_phase_on_restarts(_cat, \"phase-restart\",\n\n \"The amount of randomization for the phase at each restart (0=none, 1=first branch, 2=first branch (no bad clauses), 3=first branch (only initial clauses)\",\n\n 0, IntRange(0, 3));\n\nstatic BoolOption opt_fixed_randomize_phase_on_restarts(_cat, \"fix-phas-rest\", \"Fixes the first 7 levels at random phase\", false);\n\n\n\nstatic BoolOption opt_adapt(_cat, \"adapt\", \"Adapt dynamically stategies after 100000 conflicts\", true);\n\n\n\nstatic BoolOption opt_forceunsat(_cat,\"forceunsat\",\"Force the phase for UNSAT\",true);\n\n//=================================================================================================\n", "file_path": "core/Solver.cc", "rank": 96, "score": 8.132898576865394 }, { "content": "\t}\n\n\tprintf(\"c reinitialization of all variables activity/phase/learnt clauses.\\n\");\n\n*/\n\n printf(\"c Removing of non permanent clauses.\\n\");\n\n }\n\n\n\n}\n\n\n\n\n\n/*_________________________________________________________________________________________________\n\n|\n\n| search : (nof_conflicts : int) (params : const SearchParams&) -> [lbool]\n\n| \n\n| Description:\n\n| Search for a model the specified number of conflicts. \n\n| NOTE! Use negative value for 'nof_conflicts' indicate infinity.\n\n| \n\n| Output:\n\n| 'l_True' if a partial assigment that is consistent with respect to the clauseset is found. If\n\n| all variables are decision variables, this means that the clause set is satisfiable. 'l_False'\n", "file_path": "core/Solver.cc", "rank": 97, "score": 8.095119861604962 }, { "content": "\n\n\n\ntemplate<class T>\n\nvoid vecThreads<T>::growTo(int size, const T& pad) {\n\n if (sz >= size) return;\n\n startMaintenance();\n\n capacity(size);\n\n for (int i = sz; i < size; i++) data[i] = pad;\n\n sz = size; \n\n endMaintenance();\n\n}\n\n\n\n\n\ntemplate<class T>\n\nvoid vecThreads<T>::growTo(int size) {\n\n if (sz >= size) return;\n\n startMaintenance();\n\n capacity(size);\n\n for (int i = sz; i < size; i++) new (&data[i]) T();\n\n sz = size; \n", "file_path": "mtl/VecThreads.h", "rank": 98, "score": 8.032560448418593 }, { "content": "#ifndef Glucose_Alloc_h\n\n#define Glucose_Alloc_h\n\n\n\n#include \"glucose/mtl/XAlloc.h\"\n\n#include \"glucose/mtl/Vec.h\"\n\n\n\nnamespace Glucose {\n\n\n\n//=================================================================================================\n\n// Simple Region-based memory allocator:\n\n\n\ntemplate<class T>\n", "file_path": "mtl/Alloc.h", "rank": 99, "score": 8.017925967536268 } ]
C++
aesxx/utils/encrypt_block.cpp
egor-tensin/aesni
76ae97ff1434941dcf0c6bf1679146dcb28718aa
#include "block_cmd_parser.hpp" #include "block_dumper.hpp" #include "block_input.hpp" #include <aesxx/all.hpp> #include <boost/program_options.hpp> #include <exception> #include <iostream> #include <stdexcept> #include <string> namespace { template <aes::Algorithm algorithm, aes::Mode mode> void encrypt_with_mode( const Input& input, bool verbose = false) { typename aes::Types<algorithm>::Block iv; if (aes::ModeRequiresInitVector<mode>::value) { aes::from_string<algorithm>(iv, input.iv); if (verbose) dump_iv<algorithm>(iv); } typename aes::Types<algorithm>::Key key; aes::from_string<algorithm>(key, input.key); if (verbose) dump_key<algorithm>(key); aes::EncryptWrapper<algorithm, mode> encrypt{key, iv}; if (verbose) dump_wrapper<algorithm, mode>(encrypt); for (const auto& input_block_string : input.blocks) { typename aes::Types<algorithm>::Block plaintext, ciphertext; aes::from_string<algorithm>(plaintext, input_block_string); encrypt.encrypt_block(plaintext, ciphertext); if (verbose) { dump_plaintext<algorithm>(plaintext); dump_ciphertext<algorithm>(ciphertext); dump_next_iv<algorithm, mode>(encrypt); } else { std::cout << aes::to_string<algorithm>(ciphertext) << '\n'; } } } template <aes::Algorithm algorithm> void encrypt_with_algorithm( aes::Mode mode, const Input& input, bool verbose = false) { switch (mode) { case AES_ECB: encrypt_with_mode<algorithm, AES_ECB>(input, verbose); break; case AES_CBC: encrypt_with_mode<algorithm, AES_CBC>(input, verbose); break; case AES_CFB: encrypt_with_mode<algorithm, AES_CFB>(input, verbose); break; case AES_OFB: encrypt_with_mode<algorithm, AES_OFB>(input, verbose); break; case AES_CTR: encrypt_with_mode<algorithm, AES_CTR>(input, verbose); break; default: throw std::runtime_error("the selected mode of operation is not implemented"); break; } } void encrypt_using_cxx_api( aes::Algorithm algorithm, aes::Mode mode, const Input& input, bool verbose = false) { switch (algorithm) { case AES_AES128: encrypt_with_algorithm<AES_AES128>(mode, input, verbose); break; case AES_AES192: encrypt_with_algorithm<AES_AES192>(mode, input, verbose); break; case AES_AES256: encrypt_with_algorithm<AES_AES256>(mode, input, verbose); break; default: throw std::runtime_error("the selected algorithm is not implemented"); break; } } void encrypt_using_particular_box( aes::Box& box, const std::vector<std::string>& input_block_strings) { for (const auto& input_block_string : input_block_strings) { aes::Box::Block plaintext; box.parse_block(plaintext, input_block_string); aes::Box::Block ciphertext; box.encrypt_block(plaintext, ciphertext); std::cout << box.format_block(ciphertext) << '\n'; } } void encrypt_using_boxes( aes::Algorithm algorithm, aes::Mode mode, const Input& input) { aes::Box::Key key; aes::Box::parse_key(key, algorithm, input.key); if (aes::mode_requires_init_vector(mode)) { aes::Box::Block iv; aes::Box::parse_block(iv, algorithm, input.iv); aes::Box box{algorithm, key, mode, iv}; encrypt_using_particular_box(box, input.blocks); } else { aes::Box box{algorithm, key}; encrypt_using_particular_box(box, input.blocks); } } } int main(int argc, char** argv) { try { BlockSettings settings{argv[0]}; try { settings.parse(argc, argv); } catch (const boost::program_options::error& e) { settings.usage_error(e); return 1; } if (settings.exit_with_usage) { settings.usage(); return 0; } for (const auto& input : settings.inputs) { if (settings.use_boxes) { encrypt_using_boxes( settings.algorithm, settings.mode, input); } else { encrypt_using_cxx_api( settings.algorithm, settings.mode, input, settings.verbose); } } } catch (const aes::Error& e) { std::cerr << e; return 1; } catch (const std::exception& e) { std::cerr << e.what() << "\n"; return 1; } return 0; }
#include "block_cmd_parser.hpp" #include "block_dumper.hpp" #include "block_input.hpp" #include <aesxx/all.hpp> #include <boost/program_options.hpp> #include <exception> #include <iostream> #include <stdexcept> #include <string> namespace { template <aes::Algorithm algorithm, aes::Mode mode> void encrypt_with_mode( const Input& input, bool verbose = false) { typename aes::Types<algorithm>::Block iv; if (aes::ModeRequiresInitVector<mode>::value) { aes::from_string<algorithm>(iv, input.iv); if (verbose) dump_iv<algorithm>(iv); } typename aes::Types<algorithm>::Key key; aes::from_string<algorithm>(key, input.key); if (verbose) dump_key<algorithm>(key); aes::EncryptWrapper<algorithm, mode> encrypt{key, iv}; if (verbose) dump_wrapper<algorithm, mode>(encrypt); for (const auto& input_block_string : input.blocks) { typename aes::Types<algorithm>::Block plaintext, ciphertext; aes::from_string<algorithm>(plaintext, input_block_string); encrypt.encrypt_block(plaintext, ciphertext); if (verbose) { dump_plaintext<algorithm>(plaintext); dump_ciphertext<algorithm>(ciphertext); dump_next_iv<algorithm, mode>(encrypt); } else { std::cout << aes::to_string<algorithm>(ciphertext) << '\n'; } } } template <aes::Algorithm algorithm> void encrypt_with_algorithm( aes::Mode mode, const Input& input, bool verbose = false) { switch (mode) { case AES_ECB: encrypt_with_mode<algorithm, AES_ECB>(input, verbose); break; case AES_CBC: encrypt_with_mode<algorithm, AES_CBC>(input, verbose); break; case AES_CFB: encrypt_with_mode<algorithm, AES_CFB>(input, verbose); break; case AES_OFB: encrypt_with_mode<algorithm, AES_OFB>(input, verbose); break; case AES_CTR: encrypt_with_mode<algorithm, AES_CTR>(input, verbose); break; default: throw std::runtime_error("the selected mode of operation is not implemented"); break; } } void encrypt_using_cxx_api( aes::Algorithm algorithm, aes::Mode mode, const Input& input, bool verbose = false) { switch (algorithm) { case AES_AES128: encrypt_with_algorithm<AES_AES128>(mode, input, verbose); break; case AES_AES192: encrypt_with_algorithm<AES_AES192>(mode, input, verbose); break; case AES_AES256: encrypt_with_algorithm<AES_AES256>(mode, input, verbose); break; default: throw std::runtime_error("the selected algorithm is not implemented"); break; } } void encrypt_using_particular_box( aes::Box& box, const std::vector<std::string>& input_block_strings) { for (const auto& input_block_string : input_block_strings) { aes::Box::Block plaintext; box.parse_block(plaintext, input_block_string); aes::Box::Block ciphertext; box.encrypt_block(plaintext, ciphertext); std::cout << box.format_block(ciphertext) << '\n'; } } void encrypt_using_boxes( aes::Algorithm algorithm, aes::Mode mode, const Input& input) { aes::Box::Key key; aes::Box::parse_key(key, algorithm, input.key); if (aes::mode_requires_init_vector(mode)) { aes::Box::Block iv; aes::Box::parse_block(iv, algorithm, input.iv); aes::Box box{algorithm, key, mode, iv}; encrypt_using_particular_box(box, input.blocks); } else { aes::Box box{algorithm, key}; encrypt_using_particular_box(box, input.blocks); } } } int main(int argc, char** argv) { try { BlockSettings settings{argv[0]}; try { settings.parse(argc, argv); } catch (const boost::program_options::error& e) { settings.usage_error(e); return 1; } if (settings.exit_with_usage) { settings.usage(); return 0; } for (const auto& input : settings.inputs) {
} } catch (const aes::Error& e) { std::cerr << e; return 1; } catch (const std::exception& e) { std::cerr << e.what() << "\n"; return 1; } return 0; }
if (settings.use_boxes) { encrypt_using_boxes( settings.algorithm, settings.mode, input); } else { encrypt_using_cxx_api( settings.algorithm, settings.mode, input, settings.verbose); }
if_condition
[ { "content": " AES_BoxBlock iv;\n", "file_path": "aes/include/aes/box_data.h", "rank": 0, "score": 107986.0012956743 }, { "content": " const AES_BoxAlgorithmInterface* algorithm;\n", "file_path": "aes/include/aes/box_data.h", "rank": 1, "score": 107862.82410899692 }, { "content": " AES_Mode mode;\n", "file_path": "aes/include/aes/box_data.h", "rank": 2, "score": 107797.53246657422 }, { "content": " class Box\n\n {\n\n public:\n\n typedef AES_BoxBlock Block;\n\n typedef AES_BoxKey Key;\n\n\n\n static std::string format_key(const Key& src, Algorithm algorithm)\n\n {\n\n AES_BoxKeyString str;\n\n aes_box_format_key(\n\n &str, algorithm, &src, ErrorDetailsThrowsInDestructor{});\n\n return reinterpret_cast<const char*>(&str);\n\n }\n\n\n\n static std::string format_block(const Block& src, Algorithm algorithm)\n\n {\n\n AES_BoxBlockString str;\n\n aes_box_format_block(\n\n &str, algorithm, &src, ErrorDetailsThrowsInDestructor{});\n\n return reinterpret_cast<const char*>(&str);\n", "file_path": "aesxx/include/aesxx/box.hpp", "rank": 3, "score": 90981.77131566702 }, { "content": " AES_AES_Block key;\n", "file_path": "aes/include/aes/aes.h", "rank": 4, "score": 82826.04882815441 }, { "content": " AES_BoxEncryptionRoundKeys encryption_keys;\n", "file_path": "aes/include/aes/box_data.h", "rank": 5, "score": 77578.72692257781 }, { "content": " AES_BoxFormatKey format_key;\n", "file_path": "aes/include/aes/box_data.h", "rank": 6, "score": 77578.72692257781 }, { "content": " AES_BoxDecryptionRoundKeys decryption_keys;\n", "file_path": "aes/include/aes/box_data.h", "rank": 7, "score": 77578.72692257781 }, { "content": " AES_BoxParseKey parse_key;\n", "file_path": "aes/include/aes/box_data.h", "rank": 8, "score": 77578.72692257781 }, { "content": " AES_BoxCalculateRoundKeys calc_round_keys;\n", "file_path": "aes/include/aes/box_data.h", "rank": 9, "score": 75011.32702798091 }, { "content": "// Copyright (c) 2015 Egor Tensin <[email protected]>\n\n// This file is part of the \"AES tools\" project.\n\n// For details, see https://github.com/egor-tensin/aes-tools.\n\n// Distributed under the MIT License.\n\n\n\n#pragma once\n\n\n\n#include <aes/all.h>\n\n\n\nnamespace aes\n\n{\n\n typedef AES_Algorithm Algorithm;\n\n}\n", "file_path": "aesxx/include/aesxx/algorithm.hpp", "rank": 10, "score": 65672.57434716045 }, { "content": " inline bool mode_uses_encryption_keys_only(Mode mode)\n\n {\n\n return mode != AES_ECB && mode != AES_CBC;\n\n }\n\n\n\n#define AESXX_ENCRYPT_BLOCK_ECB(prefix) \\\n\n template <> \\\n\n inline void encrypt_block<AES_## prefix, AES_ECB>( \\\n\n const typename Types<AES_## prefix>::Block& plaintext, \\\n\n const typename Types<AES_## prefix>::RoundKeys& encryption_keys, \\\n\n typename Types<AES_## prefix>::Block& ciphertext) \\\n\n { \\\n\n ciphertext = aes_## prefix ##_encrypt_block_ECB(plaintext, &encryption_keys); \\\n\n }\n\n\n\n#define AESXX_DECRYPT_BLOCK_ECB(prefix) \\\n\n template <> \\\n\n inline void decrypt_block<AES_## prefix, AES_ECB>( \\\n\n const typename Types<AES_## prefix>::Block& ciphertext, \\\n\n const typename Types<AES_## prefix>::RoundKeys& decryption_keys, \\\n", "file_path": "aesxx/include/aesxx/mode.hpp", "rank": 11, "score": 65603.11376063134 }, { "content": "#define AESXX_DECRYPT_BLOCK_OFB(prefix) \\\n\n template <> \\\n\n inline void decrypt_block<AES_## prefix, AES_OFB>( \\\n\n const typename Types<AES_## prefix>::Block& ciphertext, \\\n\n const typename Types<AES_## prefix>::RoundKeys& encryption_keys, \\\n\n typename Types<AES_## prefix>::Block& iv, \\\n\n typename Types<AES_## prefix>::Block& plaintext) \\\n\n { \\\n\n plaintext = aes_## prefix ##_decrypt_block_OFB(ciphertext, &encryption_keys, iv, &iv); \\\n\n }\n\n\n\n#define AESXX_ENCRYPT_BLOCK_CTR(prefix) \\\n\n template <> \\\n\n inline void encrypt_block<AES_## prefix, AES_CTR>( \\\n\n const typename Types<AES_## prefix>::Block& plaintext, \\\n\n const typename Types<AES_## prefix>::RoundKeys& encryption_keys, \\\n\n typename Types<AES_## prefix>::Block& iv, \\\n\n typename Types<AES_## prefix>::Block& ciphertext) \\\n\n { \\\n\n ciphertext = aes_## prefix ##_encrypt_block_CTR(plaintext, &encryption_keys, iv, &iv); \\\n", "file_path": "aesxx/include/aesxx/mode.hpp", "rank": 12, "score": 65601.98900231566 }, { "content": " typename Types<AES_## prefix>::Block& plaintext) \\\n\n { \\\n\n plaintext = aes_## prefix ##_decrypt_block_ECB(ciphertext, &decryption_keys); \\\n\n }\n\n\n\n#define AESXX_ENCRYPT_BLOCK_CBC(prefix) \\\n\n template <> \\\n\n inline void encrypt_block<AES_## prefix, AES_CBC>( \\\n\n const typename Types<AES_## prefix>::Block& plaintext, \\\n\n const typename Types<AES_## prefix>::RoundKeys& encryption_keys, \\\n\n typename Types<AES_## prefix>::Block& iv, \\\n\n typename Types<AES_## prefix>::Block& ciphertext) \\\n\n { \\\n\n ciphertext = aes_## prefix ##_encrypt_block_CBC(plaintext, &encryption_keys, iv, &iv); \\\n\n }\n\n\n\n#define AESXX_DECRYPT_BLOCK_CBC(prefix) \\\n\n template <> \\\n\n inline void decrypt_block<AES_## prefix, AES_CBC>( \\\n\n const typename Types<AES_## prefix>::Block& ciphertext, \\\n", "file_path": "aesxx/include/aesxx/mode.hpp", "rank": 13, "score": 65601.79778798409 }, { "content": " const typename Types<AES_## prefix>::RoundKeys& decryption_keys, \\\n\n typename Types<AES_## prefix>::Block& iv, \\\n\n typename Types<AES_## prefix>::Block& plaintext) \\\n\n { \\\n\n plaintext = aes_## prefix ##_decrypt_block_CBC(ciphertext, &decryption_keys, iv, &iv); \\\n\n }\n\n\n\n#define AESXX_ENCRYPT_BLOCK_CFB(prefix) \\\n\n template <> \\\n\n inline void encrypt_block<AES_## prefix, AES_CFB>( \\\n\n const typename Types<AES_## prefix>::Block& plaintext, \\\n\n const typename Types<AES_## prefix>::RoundKeys& encryption_keys, \\\n\n typename Types<AES_## prefix>::Block& iv, \\\n\n typename Types<AES_## prefix>::Block& ciphertext) \\\n\n { \\\n\n ciphertext = aes_## prefix ##_encrypt_block_CFB(plaintext, &encryption_keys, iv, &iv); \\\n\n }\n\n\n\n#define AESXX_DECRYPT_BLOCK_CFB(prefix) \\\n\n template <> \\\n", "file_path": "aesxx/include/aesxx/mode.hpp", "rank": 14, "score": 65601.72906747382 }, { "content": " inline void decrypt_block<AES_## prefix, AES_CFB>( \\\n\n const typename Types<AES_## prefix>::Block& ciphertext, \\\n\n const typename Types<AES_## prefix>::RoundKeys& encryption_keys, \\\n\n typename Types<AES_## prefix>::Block& iv, \\\n\n typename Types<AES_## prefix>::Block& plaintext) \\\n\n { \\\n\n plaintext = aes_## prefix ##_decrypt_block_CFB(ciphertext, &encryption_keys, iv, &iv); \\\n\n }\n\n\n\n#define AESXX_ENCRYPT_BLOCK_OFB(prefix) \\\n\n template <> \\\n\n inline void encrypt_block<AES_## prefix, AES_OFB>( \\\n\n const typename Types<AES_## prefix>::Block& plaintext, \\\n\n const typename Types<AES_## prefix>::RoundKeys& encryption_keys, \\\n\n typename Types<AES_## prefix>::Block& iv, \\\n\n typename Types<AES_## prefix>::Block& ciphertext) \\\n\n { \\\n\n ciphertext = aes_## prefix ##_encrypt_block_OFB(plaintext, &encryption_keys, iv, &iv); \\\n\n }\n\n\n", "file_path": "aesxx/include/aesxx/mode.hpp", "rank": 15, "score": 65601.61138457134 }, { "content": " }\n\n\n\n#define AESXX_DECRYPT_BLOCK_CTR(prefix) \\\n\n template <> \\\n\n inline void decrypt_block<AES_## prefix, AES_CTR>( \\\n\n const typename Types<AES_## prefix>::Block& ciphertext, \\\n\n const typename Types<AES_## prefix>::RoundKeys& encryption_keys, \\\n\n typename Types<AES_## prefix>::Block& iv, \\\n\n typename Types<AES_## prefix>::Block& plaintext) \\\n\n { \\\n\n plaintext = aes_## prefix ##_decrypt_block_CTR(ciphertext, &encryption_keys, iv, &iv); \\\n\n }\n\n}\n", "file_path": "aesxx/include/aesxx/mode.hpp", "rank": 16, "score": 65601.22642935289 }, { "content": " struct ModeRequiresInitVector<AES_ECB> : public std::false_type\n\n { };\n\n\n\n template <Mode mode>\n\n struct ModeUsesEncryptionKeysOnly : public std::true_type\n\n { };\n\n\n\n inline bool mode_requires_init_vector(Mode mode)\n\n {\n\n return mode != AES_ECB;\n\n }\n\n\n\n template <>\n\n struct ModeUsesEncryptionKeysOnly<AES_ECB> : public std::false_type\n\n { };\n\n\n\n template <>\n\n struct ModeUsesEncryptionKeysOnly<AES_CBC> : public std::false_type\n\n { };\n\n\n", "file_path": "aesxx/include/aesxx/mode.hpp", "rank": 17, "score": 65597.77949353702 }, { "content": "// Copyright (c) 2015 Egor Tensin <[email protected]>\n\n// This file is part of the \"AES tools\" project.\n\n// For details, see https://github.com/egor-tensin/aes-tools.\n\n// Distributed under the MIT License.\n\n\n\n#pragma once\n\n\n\n#include <aes/all.h>\n\n\n\n#include <type_traits>\n\n\n\nnamespace aes\n\n{\n\n typedef AES_Mode Mode;\n\n\n\n template <Mode mode>\n\n struct ModeRequiresInitVector : public std::true_type\n\n { };\n\n\n\n template <>\n", "file_path": "aesxx/include/aesxx/mode.hpp", "rank": 18, "score": 65596.97439523562 }, { "content": " aes_box_init(&impl, algorithm, &key, mode, nullptr,\n\n ErrorDetailsThrowsInDestructor{});\n\n }\n\n\n\n Box(Algorithm algorithm, const Key& key, Mode mode, const Block& iv)\n\n : algorithm{algorithm}\n\n , mode{mode}\n\n {\n\n aes_box_init(&impl, algorithm, &key, mode, &iv,\n\n ErrorDetailsThrowsInDestructor{});\n\n }\n\n\n\n void encrypt_block(const Block& plaintext, Block& ciphertext)\n\n {\n\n aes_box_encrypt_block(\n\n &impl, &plaintext, &ciphertext,\n\n ErrorDetailsThrowsInDestructor{});\n\n }\n\n\n\n void decrypt_block(const Block& ciphertext, Block& plaintext)\n", "file_path": "aesxx/include/aesxx/box.hpp", "rank": 19, "score": 64489.738842086015 }, { "content": " Key& dest,\n\n Algorithm algorithm,\n\n const char* src)\n\n {\n\n aes_box_parse_key(&dest, algorithm, src,\n\n ErrorDetailsThrowsInDestructor{});\n\n }\n\n\n\n static void parse_key(\n\n Key& dest,\n\n Algorithm algorithm,\n\n const std::string& src)\n\n {\n\n parse_key(dest, algorithm, src.c_str());\n\n }\n\n\n\n Box(Algorithm algorithm, const Key& key)\n\n : algorithm{algorithm}\n\n , mode{AES_ECB}\n\n {\n", "file_path": "aesxx/include/aesxx/box.hpp", "rank": 20, "score": 64482.60476116888 }, { "content": " {\n\n parse_block(dest, src.c_str());\n\n }\n\n\n\n void parse_key(Key& dest, const char* src)\n\n {\n\n parse_key(dest, get_algorithm(), src);\n\n }\n\n\n\n void parse_key(Key& dest, const std::string& src)\n\n {\n\n parse_key(dest, src.c_str());\n\n }\n\n\n\n Algorithm get_algorithm() const { return algorithm; }\n\n\n\n Mode get_mode() const { return mode; }\n\n\n\n private:\n\n Key key;\n\n\n\n Algorithm algorithm;\n\n Mode mode;\n\n\n\n AES_Box impl;\n\n };\n\n}\n", "file_path": "aesxx/include/aesxx/box.hpp", "rank": 21, "score": 64481.26486063089 }, { "content": " }\n\n\n\n static void parse_block(\n\n Block& dest,\n\n Algorithm algorithm,\n\n const char* src)\n\n {\n\n aes_box_parse_block(&dest, algorithm, src,\n\n ErrorDetailsThrowsInDestructor{});\n\n }\n\n\n\n static void parse_block(\n\n Block& dest,\n\n Algorithm algorithm,\n\n const std::string& src)\n\n {\n\n parse_block(dest, algorithm, src.c_str());\n\n }\n\n\n\n static void parse_key(\n", "file_path": "aesxx/include/aesxx/box.hpp", "rank": 22, "score": 64479.0958556447 }, { "content": " {\n\n aes_box_decrypt_block(\n\n &impl, &ciphertext, &plaintext,\n\n ErrorDetailsThrowsInDestructor{});\n\n }\n\n\n\n std::vector<unsigned char> encrypt_buffer(\n\n const void* src_buf,\n\n std::size_t src_size)\n\n {\n\n std::size_t dest_size = 0;\n\n\n\n aes_box_encrypt_buffer(\n\n &impl,\n\n src_buf,\n\n src_size,\n\n nullptr,\n\n &dest_size,\n\n aes::ErrorDetailsThrowsInDestructor{});\n\n\n", "file_path": "aesxx/include/aesxx/box.hpp", "rank": 23, "score": 64475.93055887605 }, { "content": " dest_buf.resize(dest_size);\n\n return dest_buf;\n\n }\n\n\n\n std::string format_block(const Block& src)\n\n {\n\n return format_block(src, get_algorithm());\n\n }\n\n\n\n std::string format_key(const Key& src)\n\n {\n\n return format_key(src, get_algorithm());\n\n }\n\n\n\n void parse_block(Block& dest, const char* src)\n\n {\n\n parse_block(dest, get_algorithm(), src);\n\n }\n\n\n\n void parse_block(Block& dest, const std::string& src)\n", "file_path": "aesxx/include/aesxx/box.hpp", "rank": 24, "score": 64475.33634521018 }, { "content": "// Copyright (c) 2015 Egor Tensin <[email protected]>\n\n// This file is part of the \"AES tools\" project.\n\n// For details, see https://github.com/egor-tensin/aes-tools.\n\n// Distributed under the MIT License.\n\n\n\n#pragma once\n\n\n\n#include \"algorithm.hpp\"\n\n#include \"error.hpp\"\n\n#include \"mode.hpp\"\n\n\n\n#include <aes/all.h>\n\n\n\n#include <cstddef>\n\n\n\n#include <string>\n\n#include <vector>\n\n\n\nnamespace aes\n\n{\n", "file_path": "aesxx/include/aesxx/box.hpp", "rank": 25, "score": 64473.84183510051 }, { "content": " std::vector<unsigned char> dest_buf;\n\n dest_buf.resize(dest_size);\n\n\n\n aes_box_encrypt_buffer(\n\n &impl,\n\n src_buf,\n\n src_size,\n\n dest_buf.data(),\n\n &dest_size,\n\n aes::ErrorDetailsThrowsInDestructor{});\n\n\n\n dest_buf.resize(dest_size);\n\n return dest_buf;\n\n }\n\n\n\n std::vector<unsigned char> decrypt_buffer(\n\n const void* src_buf,\n\n std::size_t src_size)\n\n {\n\n std::size_t dest_size = 0;\n", "file_path": "aesxx/include/aesxx/box.hpp", "rank": 26, "score": 64470.150770276705 }, { "content": "\n\n aes_box_decrypt_buffer(\n\n &impl,\n\n src_buf,\n\n src_size,\n\n nullptr,\n\n &dest_size,\n\n aes::ErrorDetailsThrowsInDestructor{});\n\n\n\n std::vector<unsigned char> dest_buf;\n\n dest_buf.resize(dest_size);\n\n\n\n aes_box_decrypt_buffer(\n\n &impl,\n\n src_buf,\n\n src_size,\n\n dest_buf.data(),\n\n &dest_size,\n\n aes::ErrorDetailsThrowsInDestructor{});\n\n\n", "file_path": "aesxx/include/aesxx/box.hpp", "rank": 27, "score": 64469.53368660444 }, { "content": "static const AES_BoxAlgorithmInterface* aes_box_algorithms[] =\n\n{\n\n &aes_box_algorithm_aes128,\n\n &aes_box_algorithm_aes192,\n\n &aes_box_algorithm_aes256,\n", "file_path": "aes/src/box.c", "rank": 28, "score": 63976.50102187517 }, { "content": "class Input\n\n{\n\npublic:\n\n Input(const std::string& key, const std::string& iv, std::vector<std::string>&& blocks)\n\n : key{key}\n\n , iv{iv}\n\n , blocks{std::move(blocks)}\n\n { }\n\n\n\n Input(const std::string& key, std::vector<std::string>&& blocks)\n\n : key{key}\n\n , blocks{std::move(blocks)}\n\n { }\n\n\n\n const std::string key;\n\n const std::string iv;\n\n const std::vector<std::string> blocks;\n\n};\n", "file_path": "aesxx/utils/block_input.hpp", "rank": 29, "score": 61853.630958315865 }, { "content": "AES_StatusCode aes_box_parse_key(\n\n AES_BoxKey* dest,\n\n AES_Algorithm algorithm,\n\n const char* src,\n\n AES_ErrorDetails* err_details)\n\n{\n\n if (dest == NULL)\n\n return aes_error_null_argument(err_details, \"dest\");\n\n if (src == NULL)\n\n return aes_error_null_argument(err_details, \"src\");\n\n\n\n return aes_box_algorithms[algorithm]->parse_key(\n\n dest, src, err_details);\n", "file_path": "aes/src/box.c", "rank": 30, "score": 61810.13435789359 }, { "content": "AES_StatusCode aes_box_format_key(\n\n AES_BoxKeyString* dest,\n\n AES_Algorithm algorithm,\n\n const AES_BoxKey* src,\n\n AES_ErrorDetails* err_details)\n\n{\n\n if (dest == NULL)\n\n return aes_error_null_argument(err_details, \"dest\");\n\n if (src == NULL)\n\n return aes_error_null_argument(err_details, \"src\");\n\n\n\n return aes_box_algorithms[algorithm]->format_key(\n\n dest, src, err_details);\n", "file_path": "aes/src/box.c", "rank": 31, "score": 61810.13435789359 }, { "content": "AES_BoxAlgorithmInterface aes_box_algorithm_aes192 =\n\n{\n\n &aes_box_derive_params_aes192,\n\n &aes_box_parse_block_aes,\n\n &aes_box_parse_key_aes192,\n\n &aes_box_format_block_aes,\n\n &aes_box_format_key_aes192,\n\n &aes_box_encrypt_block_aes192,\n\n &aes_box_decrypt_block_aes192,\n\n &aes_box_xor_block_aes,\n\n &aes_box_inc_block_aes,\n\n &aes_box_get_block_size_aes,\n\n &aes_box_store_block_aes,\n\n &aes_box_load_block_aes,\n", "file_path": "aes/src/box_aes.c", "rank": 32, "score": 60474.367954329864 }, { "content": "AES_BoxAlgorithmInterface aes_box_algorithm_aes128 =\n\n{\n\n &aes_box_derive_params_aes128,\n\n &aes_box_parse_block_aes,\n\n &aes_box_parse_key_aes128,\n\n &aes_box_format_block_aes,\n\n &aes_box_format_key_aes128,\n\n &aes_box_encrypt_block_aes128,\n\n &aes_box_decrypt_block_aes128,\n\n &aes_box_xor_block_aes,\n\n &aes_box_inc_block_aes,\n\n &aes_box_get_block_size_aes,\n\n &aes_box_store_block_aes,\n\n &aes_box_load_block_aes,\n", "file_path": "aes/src/box_aes.c", "rank": 33, "score": 60474.367954329864 }, { "content": "AES_BoxAlgorithmInterface aes_box_algorithm_aes256 =\n\n{\n\n &aes_box_derive_params_aes256,\n\n &aes_box_parse_block_aes,\n\n &aes_box_parse_key_aes256,\n\n &aes_box_format_block_aes,\n\n &aes_box_format_key_aes256,\n\n &aes_box_encrypt_block_aes256,\n\n &aes_box_decrypt_block_aes256,\n\n &aes_box_xor_block_aes,\n\n &aes_box_inc_block_aes,\n\n &aes_box_get_block_size_aes,\n\n &aes_box_store_block_aes,\n\n &aes_box_load_block_aes,\n", "file_path": "aes/src/box_aes.c", "rank": 34, "score": 60474.367954329864 }, { "content": "static AES_BoxDecryptBlockInMode aes_box_decrypt_block_in_mode[] =\n\n{\n\n &aes_box_decrypt_block_ecb,\n\n &aes_box_decrypt_block_cbc,\n\n &aes_box_decrypt_block_cfb,\n\n &aes_box_encrypt_block_ofb,\n\n &aes_box_encrypt_block_ctr,\n", "file_path": "aes/src/box.c", "rank": 35, "score": 60413.39785113637 }, { "content": "static AES_BoxEncryptBlockInMode aes_box_encrypt_block_in_mode[] =\n\n{\n\n &aes_box_encrypt_block_ecb,\n\n &aes_box_encrypt_block_cbc,\n\n &aes_box_encrypt_block_cfb,\n\n &aes_box_encrypt_block_ofb,\n\n &aes_box_encrypt_block_ctr,\n", "file_path": "aes/src/box.c", "rank": 36, "score": 60413.39785113637 }, { "content": "static AES_StatusCode aes_box_parse_key_aes256(\n\n AES_BoxKey* dest,\n\n const char* src,\n\n AES_ErrorDetails* err_details)\n\n{\n\n if (dest == NULL)\n\n return aes_error_null_argument(err_details, \"dest\");\n\n\n\n return aes_AES256_parse_key(&dest->aes256_key, src, err_details);\n", "file_path": "aes/src/box_aes.c", "rank": 37, "score": 58526.71890144257 }, { "content": "static AES_StatusCode aes_box_parse_key_aes192(\n\n AES_BoxKey* dest,\n\n const char* src,\n\n AES_ErrorDetails* err_details)\n\n{\n\n if (dest == NULL)\n\n return aes_error_null_argument(err_details, \"dest\");\n\n\n\n return aes_AES192_parse_key(&dest->aes192_key, src, err_details);\n", "file_path": "aes/src/box_aes.c", "rank": 38, "score": 58526.71890144257 }, { "content": "static AES_StatusCode aes_box_parse_key_aes128(\n\n AES_BoxKey* dest,\n\n const char* src,\n\n AES_ErrorDetails* err_details)\n\n{\n\n if (dest == NULL)\n\n return aes_error_null_argument(err_details, \"dest\");\n\n\n\n return aes_AES128_parse_key(&dest->aes128_key, src, err_details);\n", "file_path": "aes/src/box_aes.c", "rank": 39, "score": 58526.71890144257 }, { "content": "static AES_StatusCode aes_box_format_key_aes128(\n\n AES_BoxKeyString* dest,\n\n const AES_BoxKey* src,\n\n AES_ErrorDetails* err_details)\n\n{\n\n if (dest == NULL)\n\n return aes_error_null_argument(err_details, \"dest\");\n\n if (src == NULL)\n\n return aes_error_null_argument(err_details, \"src\");\n\n\n\n return aes_AES128_format_key(&dest->aes128, &src->aes128_key, err_details);\n", "file_path": "aes/src/box_aes.c", "rank": 40, "score": 58526.71890144257 }, { "content": "static AES_StatusCode aes_box_format_key_aes256(\n\n AES_BoxKeyString* dest,\n\n const AES_BoxKey* src,\n\n AES_ErrorDetails* err_details)\n\n{\n\n if (dest == NULL)\n\n return aes_error_null_argument(err_details, \"dest\");\n\n if (src == NULL)\n\n return aes_error_null_argument(err_details, \"src\");\n\n\n\n return aes_AES256_format_key(&dest->aes256, &src->aes256_key, err_details);\n", "file_path": "aes/src/box_aes.c", "rank": 41, "score": 58526.71890144257 }, { "content": "static AES_StatusCode aes_box_format_key_aes192(\n\n AES_BoxKeyString* dest,\n\n const AES_BoxKey* src,\n\n AES_ErrorDetails* err_details)\n\n{\n\n if (dest == NULL)\n\n return aes_error_null_argument(err_details, \"dest\");\n\n if (src == NULL)\n\n return aes_error_null_argument(err_details, \"src\");\n\n\n\n return aes_AES192_format_key(&dest->aes192, &src->aes192_key, err_details);\n", "file_path": "aes/src/box_aes.c", "rank": 42, "score": 58526.71890144257 }, { "content": " def algorithm(self):\n", "file_path": "test/cavp.py", "rank": 43, "score": 56934.41069122891 }, { "content": "class Algorithm(Enum):\n\n @staticmethod\n\n def parse(s):\n\n return Algorithm(s.lower())\n\n\n\n @staticmethod\n\n def try_parse(s):\n\n try:\n\n return Algorithm.parse(s)\n\n except ValueError:\n\n return None\n\n\n\n AES128, AES192, AES256 = 'aes128', 'aes192', 'aes256'\n\n\n\n def __str__(self):\n", "file_path": "test/toolkit.py", "rank": 44, "score": 56934.41069122891 }, { "content": "class Mode(Enum):\n\n @staticmethod\n\n def parse(s):\n\n s = s.lower()\n\n if '{}128'.format(Mode.CFB) == s:\n\n return Mode.CFB\n\n return Mode(s)\n\n\n\n @staticmethod\n\n def try_parse(s):\n\n try:\n\n return Mode.parse(s)\n\n except ValueError:\n\n return None\n\n\n\n ECB, CBC, CFB, OFB, CTR = 'ecb', 'cbc', 'cfb', 'ofb', 'ctr'\n\n\n\n def requires_init_vector(self):\n\n return self != Mode.ECB\n\n\n\n def __str__(self):\n", "file_path": "test/toolkit.py", "rank": 45, "score": 56864.138156541274 }, { "content": " def mode(self):\n", "file_path": "test/cavp.py", "rank": 46, "score": 56864.138156541274 }, { "content": " class ErrorDetailsThrowsInDestructor\n\n {\n\n public:\n\n ErrorDetailsThrowsInDestructor()\n\n {\n\n aes_success(get());\n\n }\n\n\n\n ~ErrorDetailsThrowsInDestructor() BOOST_NOEXCEPT_IF(false)\n\n {\n\n if (aes_is_error(aes_get_error_code(get())))\n\n throw Error(impl);\n\n }\n\n\n\n AES_ErrorDetails* get() { return &impl; }\n\n\n\n operator AES_ErrorDetails*() { return get(); }\n\n\n\n private:\n\n AES_ErrorDetails impl;\n\n };\n\n}\n", "file_path": "aesxx/include/aesxx/error.hpp", "rank": 47, "score": 56137.03779689483 }, { "content": " AES_AES_Block keys[15];\n", "file_path": "aes/include/aes/aes.h", "rank": 48, "score": 55623.0894413275 }, { "content": "def get_tested_algorithms_and_modes():\n\n for algorithm in _TEST_CIPHERTEXTS:\n\n for mode in _TEST_CIPHERTEXTS[algorithm]:\n", "file_path": "test/nist.py", "rank": 49, "score": 53375.70443568077 }, { "content": " AES_BoxStoreBlock store_block;\n", "file_path": "aes/include/aes/box_data.h", "rank": 50, "score": 51223.63208465599 }, { "content": " AES_BoxLoadBlock load_block;\n", "file_path": "aes/include/aes/box_data.h", "rank": 51, "score": 51223.63208465599 }, { "content": " AES_BoxFormatBlock format_block;\n", "file_path": "aes/include/aes/box_data.h", "rank": 52, "score": 51223.63208465599 }, { "content": " AES_BoxIncBlock inc_block;\n", "file_path": "aes/include/aes/box_data.h", "rank": 53, "score": 51223.63208465599 }, { "content": " AES_BoxEncryptBlock encrypt_block;\n", "file_path": "aes/include/aes/box_data.h", "rank": 54, "score": 51223.63208465599 }, { "content": " AES_BoxXorBlock xor_block;\n", "file_path": "aes/include/aes/box_data.h", "rank": 55, "score": 51223.63208465599 }, { "content": " AES_BoxDecryptBlock decrypt_block;\n", "file_path": "aes/include/aes/box_data.h", "rank": 56, "score": 51223.63208465599 }, { "content": " AES_BoxParseBlock parse_block;\n", "file_path": "aes/include/aes/box_data.h", "rank": 57, "score": 51223.63208465599 }, { "content": " AES_BoxGetBlockSize get_block_size;\n", "file_path": "aes/include/aes/box_data.h", "rank": 58, "score": 49528.43092794891 }, { "content": "AES_StatusCode aes_box_init(\n\n AES_Box* box,\n\n AES_Algorithm algorithm,\n\n const AES_BoxKey* box_key,\n\n AES_Mode mode,\n\n const AES_BoxBlock* iv,\n\n AES_ErrorDetails* err_details)\n\n{\n\n AES_StatusCode status = AES_SUCCESS;\n\n\n\n box->algorithm = aes_box_algorithms[algorithm];\n\n\n\n if (aes_is_error(status = box->algorithm->calc_round_keys(\n\n box_key,\n\n &box->encryption_keys,\n\n &box->decryption_keys,\n\n err_details)))\n\n return status;\n\n\n\n box->mode = mode;\n\n if (iv != NULL)\n\n box->iv = *iv;\n\n\n\n return status;\n", "file_path": "aes/src/box.c", "rank": 59, "score": 36310.1902462369 }, { "content": "AES_StatusCode aes_box_encrypt_buffer(\n\n AES_Box* box,\n\n const void* src,\n\n size_t src_size,\n\n void* dest,\n\n size_t* dest_size,\n\n AES_ErrorDetails* err_details)\n\n{\n\n AES_StatusCode status = AES_SUCCESS;\n\n\n\n if (box == NULL)\n\n return aes_error_null_argument(err_details, \"box\");\n\n if (dest_size == NULL)\n\n return aes_error_null_argument(err_details, \"dest_size\");\n\n\n\n size_t padding_size = 0;\n\n\n\n if (aes_is_error(status = aes_box_get_encrypted_buffer_size(\n\n box, src_size, dest_size, &padding_size, err_details)))\n\n return status;\n\n\n\n if (dest == NULL)\n\n return AES_SUCCESS;\n\n if (src == NULL && src_size != 0)\n\n return aes_error_null_argument(err_details, \"src\");\n\n\n\n size_t block_size;\n\n\n\n if (aes_is_error(status = box->algorithm->get_block_size(\n\n &block_size, err_details)))\n\n return status;\n\n\n\n const size_t src_len = src_size / block_size;\n\n\n\n for (size_t i = 0; i < src_len; ++i)\n\n {\n\n if (aes_is_error(status = aes_box_encrypt_buffer_block(\n\n box, src, dest, err_details)))\n\n return status;\n\n\n\n src = (char*) src + block_size;\n\n dest = (char*) dest + block_size;\n\n }\n\n\n\n if (padding_size == 0)\n\n return aes_box_encrypt_buffer_partial_block(\n\n box, src, src_size % block_size, dest, err_details);\n\n else\n\n return aes_box_encrypt_buffer_partial_block_with_padding(\n\n box, src, src_size % block_size, dest, padding_size, err_details);\n", "file_path": "aes/src/box.c", "rank": 60, "score": 35455.03951997176 }, { "content": "AES_StatusCode aes_box_encrypt_block(\n\n AES_Box* box,\n\n const AES_BoxBlock* input,\n\n AES_BoxBlock* output,\n\n AES_ErrorDetails* err_details)\n\n{\n\n return aes_box_encrypt_block_in_mode[box->mode](\n\n box, input, output, err_details);\n", "file_path": "aes/src/box.c", "rank": 61, "score": 35455.03951997176 }, { "content": "AES_StatusCode aes_box_decrypt_block(\n\n AES_Box* box,\n\n const AES_BoxBlock* input,\n\n AES_BoxBlock* output,\n\n AES_ErrorDetails* err_details)\n\n{\n\n return aes_box_decrypt_block_in_mode[box->mode](\n\n box, input, output, err_details);\n", "file_path": "aes/src/box.c", "rank": 62, "score": 35455.03951997176 }, { "content": "AES_StatusCode aes_box_parse_block(\n\n AES_BoxBlock* dest,\n\n AES_Algorithm algorithm,\n\n const char* src,\n\n AES_ErrorDetails* err_details)\n\n{\n\n if (dest == NULL)\n\n return aes_error_null_argument(err_details, \"dest\");\n\n if (src == NULL)\n\n return aes_error_null_argument(err_details, \"src\");\n\n\n\n return aes_box_algorithms[algorithm]->parse_block(\n\n dest, src, err_details);\n", "file_path": "aes/src/box.c", "rank": 63, "score": 35455.03951997176 }, { "content": "AES_StatusCode aes_box_decrypt_buffer(\n\n AES_Box* box,\n\n const void* src,\n\n size_t src_size,\n\n void* dest,\n\n size_t* dest_size,\n\n AES_ErrorDetails* err_details)\n\n{\n\n if (box == NULL)\n\n return aes_error_null_argument(err_details, \"box\");\n\n if (dest_size == NULL)\n\n return aes_error_null_argument(err_details, \"dest_size\");\n\n\n\n AES_StatusCode status = AES_SUCCESS;\n\n size_t max_padding_size = 0;\n\n\n\n if (aes_is_error(status = aes_box_get_decrypted_buffer_size(\n\n box, src_size, dest_size, &max_padding_size, err_details)))\n\n return status;\n\n\n\n if (dest == NULL)\n\n return AES_SUCCESS;\n\n if (src == NULL)\n\n return aes_error_null_argument(err_details, \"src\");\n\n\n\n size_t block_size;\n\n\n\n if (aes_is_error(status = box->algorithm->get_block_size(\n\n &block_size, err_details)))\n\n return status;\n\n\n\n const size_t src_len = src_size / block_size;\n\n\n\n for (size_t i = 0; i < src_len; ++i)\n\n {\n\n if (aes_is_error(status = aes_box_decrypt_buffer_block(\n\n box, src, dest, err_details)))\n\n return status;\n\n\n\n src = (char*) src + block_size;\n\n dest = (char*) dest + block_size;\n\n }\n\n\n\n if (max_padding_size == 0)\n\n {\n\n return aes_box_decrypt_buffer_partial_block(\n\n box, src, src_size % block_size, dest, err_details);\n\n }\n\n else\n\n {\n\n size_t padding_size;\n\n\n\n if (aes_is_error(status = aes_extract_padding_size(\n\n AES_PADDING_PKCS7,\n\n (char*) dest - block_size,\n\n block_size,\n\n &padding_size,\n\n err_details)))\n\n return status;\n\n\n\n *dest_size -= padding_size;\n\n return status;\n\n }\n", "file_path": "aes/src/box.c", "rank": 64, "score": 35455.03951997176 }, { "content": "AES_StatusCode aes_box_format_block(\n\n AES_BoxBlockString* dest,\n\n AES_Algorithm algorithm,\n\n const AES_BoxBlock* src,\n\n AES_ErrorDetails* err_details)\n\n{\n\n if (dest == NULL)\n\n return aes_error_null_argument(err_details, \"dest\");\n\n if (src == NULL)\n\n return aes_error_null_argument(err_details, \"src\");\n\n\n\n return aes_box_algorithms[algorithm]->format_block(\n\n dest, src, err_details);\n", "file_path": "aes/src/box.c", "rank": 65, "score": 35455.03951997176 }, { "content": "static AES_StatusCode aes_box_encrypt_buffer_block(\n\n AES_Box* box,\n\n const void* src,\n\n void* dest,\n\n AES_ErrorDetails* err_details)\n\n{\n\n AES_StatusCode status = AES_SUCCESS;\n\n\n\n AES_BoxBlock plaintext;\n\n\n\n if (aes_is_error(status = box->algorithm->load_block(\n\n &plaintext, src, err_details)))\n\n return status;\n\n\n\n AES_BoxBlock ciphertext;\n\n\n\n if (aes_is_error(status = aes_box_encrypt_block(\n\n box, &plaintext, &ciphertext, err_details)))\n\n return status;\n\n\n\n if (aes_is_error(status = box->algorithm->store_block(\n\n dest, &ciphertext, err_details)))\n\n return status;\n\n\n\n return status;\n", "file_path": "aes/src/box.c", "rank": 66, "score": 34639.241736286785 }, { "content": "static AES_StatusCode aes_box_encrypt_block_ecb(\n\n AES_Box* box,\n\n const AES_BoxBlock* input,\n\n AES_BoxBlock* output,\n\n AES_ErrorDetails* err_details)\n\n{\n\n return box->algorithm->encrypt_block(\n\n input, &box->encryption_keys, output, err_details);\n", "file_path": "aes/src/box.c", "rank": 67, "score": 34639.241736286785 }, { "content": "static AES_StatusCode aes_box_decrypt_block_cfb(\n\n AES_Box* box,\n\n const AES_BoxBlock* input,\n\n AES_BoxBlock* output,\n\n AES_ErrorDetails* err_details)\n\n{\n\n AES_StatusCode status = AES_SUCCESS;\n\n\n\n if (aes_is_error(status = box->algorithm->encrypt_block(\n\n &box->iv, &box->encryption_keys, output, err_details)))\n\n return status;\n\n\n\n if (aes_is_error(status = box->algorithm->xor_block(\n\n output, input, err_details)))\n\n return status;\n\n\n\n box->iv = *input;\n\n return status;\n", "file_path": "aes/src/box.c", "rank": 68, "score": 34639.241736286785 }, { "content": "static AES_StatusCode aes_box_decrypt_buffer_block(\n\n AES_Box* box,\n\n const void* src,\n\n void* dest,\n\n AES_ErrorDetails* err_details)\n\n{\n\n AES_StatusCode status = AES_SUCCESS;\n\n\n\n AES_BoxBlock ciphertext;\n\n\n\n if (aes_is_error(status = box->algorithm->load_block(\n\n &ciphertext, src, err_details)))\n\n return status;\n\n\n\n AES_BoxBlock plaintext;\n\n\n\n if (aes_is_error(status = aes_box_decrypt_block(\n\n box, &ciphertext, &plaintext, err_details)))\n\n return status;\n\n\n\n if (aes_is_error(status = box->algorithm->store_block(\n\n dest, &plaintext, err_details)))\n\n return status;\n\n\n\n return status;\n", "file_path": "aes/src/box.c", "rank": 69, "score": 34639.241736286785 }, { "content": "static AES_StatusCode aes_box_decrypt_block_ecb(\n\n AES_Box* box,\n\n const AES_BoxBlock* input,\n\n AES_BoxBlock* output,\n\n AES_ErrorDetails* err_details)\n\n{\n\n return box->algorithm->decrypt_block(\n\n input, &box->decryption_keys, output, err_details);\n", "file_path": "aes/src/box.c", "rank": 70, "score": 34639.241736286785 }, { "content": "static AES_StatusCode aes_box_encrypt_block_cfb(\n\n AES_Box* box,\n\n const AES_BoxBlock* input,\n\n AES_BoxBlock* output,\n\n AES_ErrorDetails* err_details)\n\n{\n\n AES_StatusCode status = AES_SUCCESS;\n\n\n\n if (aes_is_error(status = box->algorithm->encrypt_block(\n\n &box->iv, &box->encryption_keys, output, err_details)))\n\n return status;\n\n\n\n if (aes_is_error(status = box->algorithm->xor_block(\n\n output, input, err_details)))\n\n return status;\n\n\n\n box->iv = *output;\n\n return status;\n", "file_path": "aes/src/box.c", "rank": 71, "score": 34639.241736286785 }, { "content": "static AES_StatusCode aes_box_encrypt_block_cbc(\n\n AES_Box* box,\n\n const AES_BoxBlock* input,\n\n AES_BoxBlock* output,\n\n AES_ErrorDetails* err_details)\n\n{\n\n AES_StatusCode status = AES_SUCCESS;\n\n AES_BoxBlock xored_input = *input;\n\n\n\n if (aes_is_error(status = box->algorithm->xor_block(\n\n &xored_input, &box->iv, err_details)))\n\n return status;\n\n\n\n if (aes_is_error(status = box->algorithm->encrypt_block(\n\n &xored_input, &box->encryption_keys, output, err_details)))\n\n return status;\n\n\n\n box->iv = *output;\n\n return status;\n", "file_path": "aes/src/box.c", "rank": 72, "score": 34639.241736286785 }, { "content": "static AES_StatusCode aes_box_decrypt_block_cbc(\n\n AES_Box* box,\n\n const AES_BoxBlock* input,\n\n AES_BoxBlock* output,\n\n AES_ErrorDetails* err_details)\n\n{\n\n AES_StatusCode status = AES_SUCCESS;\n\n\n\n if (aes_is_error(status = box->algorithm->decrypt_block(\n\n input, &box->decryption_keys, output, err_details)))\n\n return status;\n\n\n\n if (aes_is_error(status = box->algorithm->xor_block(\n\n output, &box->iv, err_details)))\n\n return status;\n\n\n\n box->iv = *input;\n\n return status;\n", "file_path": "aes/src/box.c", "rank": 73, "score": 34639.241736286785 }, { "content": "static AES_StatusCode aes_box_encrypt_block_ctr(\n\n AES_Box* box,\n\n const AES_BoxBlock* input,\n\n AES_BoxBlock* output,\n\n AES_ErrorDetails* err_details)\n\n{\n\n AES_StatusCode status = AES_SUCCESS;\n\n\n\n if (aes_is_error(status = box->algorithm->encrypt_block(\n\n &box->iv, &box->encryption_keys, output, err_details)))\n\n return status;\n\n\n\n if (aes_is_error(status = box->algorithm->xor_block(\n\n output, input, err_details)))\n\n return status;\n\n\n\n if (aes_is_error(status = box->algorithm->inc_block(\n\n &box->iv, err_details)))\n\n return status;\n\n\n\n return status;\n", "file_path": "aes/src/box.c", "rank": 74, "score": 34639.241736286785 }, { "content": "static AES_StatusCode aes_box_encrypt_block_ofb(\n\n AES_Box* box,\n\n const AES_BoxBlock* input,\n\n AES_BoxBlock* output,\n\n AES_ErrorDetails* err_details)\n\n{\n\n AES_StatusCode status = AES_SUCCESS;\n\n\n\n if (aes_is_error(status = box->algorithm->encrypt_block(\n\n &box->iv, &box->encryption_keys, &box->iv, err_details)))\n\n return status;\n\n\n\n *output = box->iv;\n\n\n\n if (aes_is_error(status = box->algorithm->xor_block(\n\n output, input, err_details)))\n\n return status;\n\n\n\n return status;\n", "file_path": "aes/src/box.c", "rank": 75, "score": 34639.241736286785 }, { "content": "static AES_StatusCode aes_box_format_block_aes(\n\n AES_BoxBlockString* dest,\n\n const AES_BoxBlock* src,\n\n AES_ErrorDetails* err_details)\n\n{\n\n if (dest == NULL)\n\n return aes_error_null_argument(err_details, \"dest\");\n\n if (src == NULL)\n\n return aes_error_null_argument(err_details, \"src\");\n\n\n\n return aes_AES128_format_block(&dest->aes, &src->aes_block, err_details);\n", "file_path": "aes/src/box_aes.c", "rank": 76, "score": 33860.14153519653 }, { "content": "static AES_StatusCode aes_box_encrypt_block_aes256(\n\n const AES_BoxBlock* input,\n\n const AES_BoxEncryptionRoundKeys* params,\n\n AES_BoxBlock* output,\n\n AES_ErrorDetails* err_details)\n\n{\n\n AES_UNUSED_PARAMETER(err_details);\n\n output->aes_block = aes_AES256_encrypt_block_(\n\n input->aes_block,\n\n &params->aes256_encryption_keys);\n\n return AES_SUCCESS;\n", "file_path": "aes/src/box_aes.c", "rank": 77, "score": 33860.14153519653 }, { "content": "static AES_StatusCode aes_box_decrypt_block_aes256(\n\n const AES_BoxBlock* input,\n\n const AES_BoxDecryptionRoundKeys* params,\n\n AES_BoxBlock* output,\n\n AES_ErrorDetails* err_details)\n\n{\n\n AES_UNUSED_PARAMETER(err_details);\n\n output->aes_block = aes_AES256_decrypt_block_(\n\n input->aes_block,\n\n &params->aes256_decryption_keys);\n\n return AES_SUCCESS;\n", "file_path": "aes/src/box_aes.c", "rank": 78, "score": 33860.14153519653 }, { "content": "static AES_StatusCode aes_box_decrypt_buffer_partial_block(\n\n AES_Box* box,\n\n const void* src,\n\n size_t src_size,\n\n void* dest,\n\n AES_ErrorDetails* err_details)\n\n{\n\n AES_StatusCode status = AES_SUCCESS;\n\n\n\n if (src_size == 0)\n\n return status;\n\n\n\n size_t block_size;\n\n\n\n if (aes_is_error(status = box->algorithm->get_block_size(\n\n &block_size, err_details)))\n\n return status;\n\n\n\n void* ciphertext_buf = malloc(block_size);\n\n\n\n if (ciphertext_buf == NULL)\n\n return status = aes_error_memory_allocation(err_details);\n\n\n\n memset(ciphertext_buf, 0x00, block_size);\n\n memcpy(ciphertext_buf, src, src_size);\n\n\n\n void* plaintext_buf = malloc(block_size);\n\n\n\n if (plaintext_buf == NULL)\n\n {\n\n status = aes_error_memory_allocation(err_details);\n\n goto FREE_CIPHERTEXT_BUF;\n\n }\n\n\n\n if (aes_is_error(status = aes_box_decrypt_buffer_block(\n\n box, ciphertext_buf, plaintext_buf, err_details)))\n\n goto FREE_PLAINTEXT_BUF;\n\n\n\n memcpy(dest, plaintext_buf, src_size);\n\n\n\nFREE_PLAINTEXT_BUF:\n\n free(plaintext_buf);\n\n\n\nFREE_CIPHERTEXT_BUF:\n\n free(ciphertext_buf);\n\n\n\n return status;\n", "file_path": "aes/src/box.c", "rank": 79, "score": 33860.14153519653 }, { "content": "static AES_StatusCode aes_box_encrypt_block_aes192(\n\n const AES_BoxBlock* input,\n\n const AES_BoxEncryptionRoundKeys* params,\n\n AES_BoxBlock* output,\n\n AES_ErrorDetails* err_details)\n\n{\n\n AES_UNUSED_PARAMETER(err_details);\n\n output->aes_block = aes_AES192_encrypt_block_(\n\n input->aes_block,\n\n &params->aes192_encryption_keys);\n\n return AES_SUCCESS;\n", "file_path": "aes/src/box_aes.c", "rank": 80, "score": 33860.14153519653 }, { "content": "static AES_StatusCode aes_box_derive_params_aes128(\n\n const AES_BoxKey* box_key,\n\n AES_BoxEncryptionRoundKeys* encryption_keys,\n\n AES_BoxDecryptionRoundKeys* decryption_keys,\n\n AES_ErrorDetails* err_details)\n\n{\n\n AES_UNUSED_PARAMETER(err_details);\n\n aes_AES128_expand_key_(\n\n box_key->aes128_key.key,\n\n &encryption_keys->aes128_encryption_keys);\n\n aes_AES128_derive_decryption_keys_(\n\n &encryption_keys->aes128_encryption_keys,\n\n &decryption_keys->aes128_decryption_keys);\n\n return AES_SUCCESS;\n", "file_path": "aes/src/box_aes.c", "rank": 81, "score": 33860.14153519653 }, { "content": "static AES_StatusCode aes_box_derive_params_aes192(\n\n const AES_BoxKey* box_key,\n\n AES_BoxEncryptionRoundKeys* encryption_keys,\n\n AES_BoxDecryptionRoundKeys* decryption_keys,\n\n AES_ErrorDetails* err_details)\n\n{\n\n AES_UNUSED_PARAMETER(err_details);\n\n aes_AES192_expand_key_(\n\n box_key->aes192_key.lo,\n\n box_key->aes192_key.hi,\n\n &encryption_keys->aes192_encryption_keys);\n\n aes_AES192_derive_decryption_keys_(\n\n &encryption_keys->aes192_encryption_keys,\n\n &decryption_keys->aes192_decryption_keys);\n\n return AES_SUCCESS;\n", "file_path": "aes/src/box_aes.c", "rank": 82, "score": 33860.14153519653 }, { "content": "static AES_StatusCode aes_box_derive_params_aes256(\n\n const AES_BoxKey* box_key,\n\n AES_BoxEncryptionRoundKeys* encryption_keys,\n\n AES_BoxDecryptionRoundKeys* decryption_keys,\n\n AES_ErrorDetails* err_details)\n\n{\n\n AES_UNUSED_PARAMETER(err_details);\n\n aes_AES256_expand_key_(\n\n box_key->aes256_key.lo,\n\n box_key->aes256_key.hi,\n\n &encryption_keys->aes256_encryption_keys);\n\n aes_AES256_derive_decryption_keys_(\n\n &encryption_keys->aes256_encryption_keys,\n\n &decryption_keys->aes256_decryption_keys);\n\n return AES_SUCCESS;\n", "file_path": "aes/src/box_aes.c", "rank": 83, "score": 33860.14153519653 }, { "content": "static AES_StatusCode aes_box_decrypt_block_aes192(\n\n const AES_BoxBlock* input,\n\n const AES_BoxDecryptionRoundKeys* params,\n\n AES_BoxBlock* output,\n\n AES_ErrorDetails* err_details)\n\n{\n\n AES_UNUSED_PARAMETER(err_details);\n\n output->aes_block = aes_AES192_decrypt_block_(\n\n input->aes_block,\n\n &params->aes192_decryption_keys);\n\n return AES_SUCCESS;\n", "file_path": "aes/src/box_aes.c", "rank": 84, "score": 33860.14153519653 }, { "content": "static AES_StatusCode aes_box_store_block_aes(\n\n void* dest,\n\n const AES_BoxBlock* src,\n\n AES_ErrorDetails* err_details)\n\n{\n\n AES_UNUSED_PARAMETER(err_details);\n\n aes_store_block128(dest, src->aes_block);\n\n return AES_SUCCESS;\n", "file_path": "aes/src/box_aes.c", "rank": 85, "score": 33860.14153519653 }, { "content": "static AES_StatusCode aes_box_xor_block_aes(\n\n AES_BoxBlock* dest,\n\n const AES_BoxBlock* src,\n\n AES_ErrorDetails* err_details)\n\n{\n\n AES_UNUSED_PARAMETER(err_details);\n\n dest->aes_block = aes_AES_xor_blocks(dest->aes_block, src->aes_block);\n\n return AES_SUCCESS;\n", "file_path": "aes/src/box_aes.c", "rank": 86, "score": 33860.14153519653 }, { "content": "static AES_StatusCode aes_box_encrypt_block_aes128(\n\n const AES_BoxBlock* input,\n\n const AES_BoxEncryptionRoundKeys* params,\n\n AES_BoxBlock* output,\n\n AES_ErrorDetails* err_details)\n\n{\n\n AES_UNUSED_PARAMETER(err_details);\n\n output->aes_block = aes_AES128_encrypt_block_(\n\n input->aes_block,\n\n &params->aes128_encryption_keys);\n\n return AES_SUCCESS;\n", "file_path": "aes/src/box_aes.c", "rank": 87, "score": 33860.14153519653 }, { "content": "static AES_StatusCode aes_box_get_decrypted_buffer_size(\n\n AES_Box* box,\n\n size_t src_size,\n\n size_t* dest_size,\n\n size_t* max_padding_size,\n\n AES_ErrorDetails* err_details)\n\n{\n\n AES_StatusCode status = AES_SUCCESS;\n\n\n\n switch (box->mode)\n\n {\n\n case AES_ECB:\n\n case AES_CBC:\n\n {\n\n size_t block_size;\n\n\n\n if (aes_is_error(status = box->algorithm->get_block_size(\n\n &block_size, err_details)))\n\n return status;\n\n\n\n if (src_size == 0 || src_size % block_size != 0)\n\n return aes_error_missing_padding(err_details);\n\n\n\n *dest_size = src_size;\n\n *max_padding_size = block_size;\n\n return status;\n\n }\n\n\n\n case AES_CFB:\n\n case AES_OFB:\n\n case AES_CTR:\n\n *dest_size = src_size;\n\n *max_padding_size = 0;\n\n return status;\n\n\n\n default:\n\n return aes_error_not_implemented(\n\n err_details, \"unsupported mode of operation\");\n\n }\n", "file_path": "aes/src/box.c", "rank": 88, "score": 33860.14153519653 }, { "content": "static AES_StatusCode aes_box_decrypt_block_aes128(\n\n const AES_BoxBlock* input,\n\n const AES_BoxDecryptionRoundKeys* params,\n\n AES_BoxBlock* output,\n\n AES_ErrorDetails* err_details)\n\n{\n\n AES_UNUSED_PARAMETER(err_details);\n\n output->aes_block = aes_AES128_decrypt_block_(\n\n input->aes_block,\n\n &params->aes128_decryption_keys);\n\n return AES_SUCCESS;\n", "file_path": "aes/src/box_aes.c", "rank": 89, "score": 33860.14153519653 }, { "content": "static AES_StatusCode aes_box_encrypt_buffer_partial_block(\n\n AES_Box* box,\n\n const void* src,\n\n size_t src_size,\n\n void* dest,\n\n AES_ErrorDetails* err_details)\n\n{\n\n AES_StatusCode status = AES_SUCCESS;\n\n\n\n if (src_size == 0)\n\n return status;\n\n\n\n size_t block_size;\n\n\n\n if (aes_is_error(status = box->algorithm->get_block_size(\n\n &block_size, err_details)))\n\n return status;\n\n\n\n void* plaintext_buf = malloc(block_size);\n\n\n\n if (plaintext_buf == NULL)\n\n return status = aes_error_memory_allocation(err_details);\n\n\n\n memset(plaintext_buf, 0x00, block_size);\n\n memcpy(plaintext_buf, src, src_size);\n\n\n\n void* ciphertext_buf = malloc(block_size);\n\n\n\n if (ciphertext_buf == NULL)\n\n {\n\n status = aes_error_memory_allocation(err_details);\n\n goto FREE_PLAINTEXT_BUF;\n\n }\n\n\n\n if (aes_is_error(status = aes_box_encrypt_buffer_block(\n\n box, plaintext_buf, ciphertext_buf, err_details)))\n\n goto FREE_CIPHERTEXT_BUF;\n\n\n\n memcpy(dest, ciphertext_buf, src_size);\n\n\n\nFREE_CIPHERTEXT_BUF:\n\n free(ciphertext_buf);\n\n\n\nFREE_PLAINTEXT_BUF:\n\n free(plaintext_buf);\n\n\n\n return status;\n", "file_path": "aes/src/box.c", "rank": 90, "score": 33860.14153519653 }, { "content": "static AES_StatusCode aes_box_get_encrypted_buffer_size(\n\n AES_Box* box,\n\n size_t src_size,\n\n size_t* dest_size,\n\n size_t* padding_size,\n\n AES_ErrorDetails* err_details)\n\n{\n\n AES_StatusCode status = AES_SUCCESS;\n\n\n\n switch (box->mode)\n\n {\n\n case AES_ECB:\n\n case AES_CBC:\n\n {\n\n size_t block_size;\n\n\n\n if (aes_is_error(status = box->algorithm->get_block_size(\n\n &block_size, err_details)))\n\n return status;\n\n\n\n *padding_size = block_size - src_size % block_size;\n\n *dest_size = src_size + *padding_size;\n\n return status;\n\n }\n\n\n\n case AES_CFB:\n\n case AES_OFB:\n\n case AES_CTR:\n\n *dest_size = src_size;\n\n *padding_size = 0;\n\n return status;\n\n\n\n default:\n\n return aes_error_not_implemented(\n\n err_details, \"unsupported mode of operation\");\n\n }\n", "file_path": "aes/src/box.c", "rank": 91, "score": 33860.14153519653 }, { "content": "static AES_StatusCode aes_box_parse_block_aes(\n\n AES_BoxBlock* dest,\n\n const char* src,\n\n AES_ErrorDetails* err_details)\n\n{\n\n if (dest == NULL)\n\n return aes_error_null_argument(err_details, \"dest\");\n\n\n\n return aes_AES_parse_block(&dest->aes_block, src, err_details);\n", "file_path": "aes/src/box_aes.c", "rank": 92, "score": 33860.14153519653 }, { "content": "static AES_StatusCode aes_box_load_block_aes(\n\n AES_BoxBlock* dest,\n\n const void* src,\n\n AES_ErrorDetails* err_details)\n\n{\n\n AES_UNUSED_PARAMETER(err_details);\n\n dest->aes_block = aes_load_block128(src);\n\n return AES_SUCCESS;\n", "file_path": "aes/src/box_aes.c", "rank": 93, "score": 33860.14153519653 }, { "content": "static AES_StatusCode aes_box_inc_block_aes(\n\n AES_BoxBlock* ctr,\n\n AES_ErrorDetails* err_details)\n\n{\n\n AES_UNUSED_PARAMETER(err_details);\n\n ctr->aes_block = aes_AES_inc_block(ctr->aes_block);\n\n return AES_SUCCESS;\n", "file_path": "aes/src/box_aes.c", "rank": 94, "score": 33860.14153519653 }, { "content": "// Copyright (c) 2015 Egor Tensin <[email protected]>\n\n// This file is part of the \"AES tools\" project.\n\n// For details, see https://github.com/egor-tensin/aes-tools.\n\n// Distributed under the MIT License.\n\n\n\n#pragma once\n\n\n\n#include <string>\n\n#include <utility>\n\n#include <vector>\n\n\n", "file_path": "aesxx/utils/block_input.hpp", "rank": 95, "score": 33709.141462919484 }, { "content": "// Copyright (c) 2015 Egor Tensin <[email protected]>\n\n// This file is part of the \"AES tools\" project.\n\n// For details, see https://github.com/egor-tensin/aes-tools.\n\n// Distributed under the MIT License.\n\n\n\n#pragma once\n\n\n\n#include \"aes.hpp\"\n\n#include \"algorithm.hpp\"\n\n#include \"api.hpp\"\n\n#include \"box.hpp\"\n\n#include \"data.hpp\"\n\n#include \"debug.hpp\"\n\n#include \"error.hpp\"\n\n#include \"mode.hpp\"\n", "file_path": "aesxx/include/aesxx/all.hpp", "rank": 96, "score": 33492.42704472897 }, { "content": "static AES_StatusCode aes_box_get_block_size_aes(\n\n size_t* block_size,\n\n AES_ErrorDetails* err_details)\n\n{\n\n AES_UNUSED_PARAMETER(err_details);\n\n *block_size = 16;\n\n return AES_SUCCESS;\n", "file_path": "aes/src/box_aes.c", "rank": 97, "score": 33115.317197409655 }, { "content": " boost::program_options::value<std::string>(&output_path)\n\n ->required()\n\n ->value_name(\"PATH\"),\n\n \"set output file path\");\n\n }\n\n\n\n const char* get_short_description() const override\n\n {\n\n return \"[-h|--help] [-a|--algorithm NAME] [-m|--mode MODE]\"\n\n \" [-k|--key KEY] [-v|--iv BLOCK]\"\n\n \" [-i|--input PATH] [-o|--output PATH]\";\n\n }\n\n\n\n void parse(int argc, char** argv) override\n\n {\n\n SettingsParser::parse(argc, argv);\n\n\n\n if (aes::mode_requires_init_vector(mode) && iv.empty())\n\n {\n\n throw boost::program_options::error{\n\n \"an initialization vector is required for the selected mode of operation\"};\n\n }\n\n }\n\n};\n", "file_path": "aesxx/utils/file_cmd_parser.hpp", "rank": 98, "score": 29.172694340185437 }, { "content": "\n\n if (aes::mode_requires_init_vector(mode))\n\n {\n\n aes::Box::Block iv;\n\n aes::Box::parse_block(iv, algorithm, settings.iv);\n\n\n\n aes::Box box{algorithm, key, mode, iv};\n\n decrypt_bmp(box, settings.input_path, settings.output_path);\n\n }\n\n else\n\n {\n\n aes::Box box{algorithm, key};\n\n decrypt_bmp(box, settings.input_path, settings.output_path);\n\n }\n\n }\n\n}\n\n\n\nint main(int argc, char** argv)\n\n{\n\n try\n", "file_path": "aesxx/utils/decrypt_bmp.cpp", "rank": 99, "score": 27.97143948138429 } ]
C++
src/particle_filter.cpp
siva1729/CarND-Kidnapped-Vehicle-T2P3
3021d48321f7c907a0aace54f23ff892e1eea3db
#include <random> #include <algorithm> #include <iostream> #include <numeric> #include <math.h> #include <iostream> #include <sstream> #include <string> #include <iterator> #include "particle_filter.h" using namespace std; #define NUM_PARTICLES 50 #define EPS 0.001 void dbg_pp (Particle &particle) { cout << "Sample: " << particle.id << " " << particle.x <<" " << particle.y << " " << particle.theta << endl; } void dbg_po (LandmarkObs &obs) { cout << "Observation: " << obs.id << " " << obs.x <<" " << obs.y << endl; } void ParticleFilter::init(double x, double y, double theta, double std[]) { num_particles = NUM_PARTICLES; weights.resize(num_particles); particles.resize(num_particles); random_device rd; default_random_engine gen(rd()); normal_distribution<double> dist_x(x, std[0]); normal_distribution<double> dist_y(y, std[1]); normal_distribution<double> dist_theta(theta, std[2]); for (int i = 0; i < particles.size(); ++i) { particles[i].id = i; particles[i].x = dist_x(gen); particles[i].y = dist_y(gen); particles[i].theta = dist_theta(gen); particles[i].weight = 1.0; } is_initialized = true; } void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) { random_device rd; default_random_engine gen(rd()); double velocity_dt = velocity * delta_t; double yaw_rate_dt = yaw_rate * delta_t; for (int i = 0; i < particles.size(); ++i) { if (fabs(yaw_rate) < EPS) { particles[i].x += velocity_dt * cos(particles[i].theta); particles[i].y += velocity_dt * sin(particles[i].theta); } else { double velocity_yaw_rate = velocity/yaw_rate; double theta_dt = particles[i].theta + yaw_rate_dt; particles[i].x += velocity_yaw_rate * (sin(theta_dt) - sin(particles[i].theta)); particles[i].y += velocity_yaw_rate * (cos(particles[i].theta) - cos(theta_dt)); particles[i].theta = theta_dt; } normal_distribution<double> dist_x(particles[i].x, std_pos[0]); normal_distribution<double> dist_y(particles[i].y, std_pos[1]); normal_distribution<double> dist_theta(particles[i].theta, std_pos[2]); particles[i].x = dist_x(gen); particles[i].y = dist_y(gen); particles[i].theta = dist_theta(gen); } } void ParticleFilter::dataAssociation(std::vector<LandmarkObs> predicted, std::vector<LandmarkObs>& observations) { for (int i = 0; i < observations.size(); i++) { double dist_min = numeric_limits<double>::max(); int associated_landmark_id = -1; double obx = observations[i].x; double oby = observations[i].y; for (int j = 0; j < predicted.size(); j++) { double dist_landmark = dist(obx, oby, predicted[j].x, predicted[j].y); if (dist_landmark < dist_min) { associated_landmark_id = predicted[j].id; dist_min = dist_landmark; observations[i].x = fabs(obx - predicted[j].x); observations[i].y = fabs(oby - predicted[j].y); } } if (associated_landmark_id == -1) { cout << "Error: No associated landmark found" << endl; } observations[i].id = associated_landmark_id; } } void ParticleFilter::updateWeights(double sensor_range, double std_landmark[], const std::vector<LandmarkObs> &observations, const Map &map_landmarks) { double weight_sum = 0.0; for (int i = 0; i < particles.size(); i++) { double par_x = particles[i].x; double par_y = particles[i].y; double par_t = particles[i].theta; vector<LandmarkObs> within_range_landmarks; for (int j = 0; j < map_landmarks.landmark_list.size(); j++) { double mx = map_landmarks.landmark_list[j].x_f; double my = map_landmarks.landmark_list[j].y_f; if ( dist(par_x, par_y, mx, my) <= sensor_range ) { within_range_landmarks.push_back(LandmarkObs{map_landmarks.landmark_list[j].id_i, mx, my}); } } vector<LandmarkObs> mapped_observations; for (int j = 0; j < observations.size(); j++) { double mapx = cos(par_t) * observations[j].x - sin(par_t) * observations[j].y + par_x; double mapy = sin(par_t) * observations[j].x + cos(par_t) * observations[j].y + par_y; mapped_observations.push_back(LandmarkObs{observations[j].id, mapx, mapy}); } dataAssociation(within_range_landmarks, mapped_observations); particles[i].weight = 1.0; for (int j = 0; j < mapped_observations.size(); j++) { double mvg_prob; double diffX = mapped_observations[j].x; double diffY = mapped_observations[j].y; if (mapped_observations[j].id != -1) { double mvg_prob = (1/(2*M_PI*std_landmark[0]*std_landmark[1])) * exp(-((diffX*diffX)/(2*std_landmark[0]*std_landmark[0]) + (diffY*diffY)/(2*std_landmark[1]*std_landmark[1]))); if (mvg_prob < EPS) { mvg_prob = EPS; } particles[i].weight *= mvg_prob; } } weight_sum += particles[i].weight; } for (int i = 0; i < particles.size(); i++) { particles[i].weight /= weight_sum; weights[i] = particles[i].weight; } } void ParticleFilter::resample() { random_device rd; default_random_engine gen(rd()); vector<Particle> resampled_particles; resampled_particles.resize(particles.size()); discrete_distribution<int> dist_resample(weights.begin(), weights.end()); for (int i = 0; i < particles.size(); i++) { resampled_particles[i] = particles[dist_resample(gen)]; } particles = resampled_particles; } Particle ParticleFilter::SetAssociations(Particle& particle, const std::vector<int>& associations, const std::vector<double>& sense_x, const std::vector<double>& sense_y) { particle.associations= associations; particle.sense_x = sense_x; particle.sense_y = sense_y; } string ParticleFilter::getAssociations(Particle best) { vector<int> v = best.associations; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<int>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); return s; } string ParticleFilter::getSenseX(Particle best) { vector<double> v = best.sense_x; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); return s; } string ParticleFilter::getSenseY(Particle best) { vector<double> v = best.sense_y; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); return s; }
#include <random> #include <algorithm> #include <iostream> #include <numeric> #include <math.h> #include <iostream> #include <sstream> #include <string> #include <iterator> #include "particle_filter.h" using namespace std; #define NUM_PARTICLES 50 #define EPS 0.001 void dbg_pp (Particle &particle) { cout << "Sample: " << particle.id << " " << particle.x <<" " << particle.y << " " << particle.theta << endl; } void dbg_po (LandmarkObs &obs) { cout << "Observation: " << obs.id << " " << obs.x <<" " << obs.y << endl; } void ParticleFilter::init(double x, double y, double theta, double std[]) { num_particles = NUM_PARTICLES; weights.resize(num_particles); particles.resize(num_particles); random_device rd; default_random_engine gen(rd()); normal_distribution<double> dist_x(x, std[0]); normal_distribution<double> dist_y(y, std[1]); normal_distribution<double> dist_theta(theta, std[2]); for (int i = 0; i < particles.size(); ++i) { particles[i].id = i; particles[i].x = dist_x(gen); particles[i].y = dist_y(gen); particles[i].theta = dist_theta(gen); particles[i].weight = 1.0; } is_initialized = true; } void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) { random_device rd; default_random_engine gen(rd()); double velocity_dt = velocity * delta_t; double yaw_rate_dt = yaw_rate * delta_t; for (int i = 0; i < particles.size(); ++i) { if (fabs(yaw_rate) < EPS) { particles[i].x += velocity_dt * cos(particles[i].theta); particles[i].y += velocity_dt * sin(particles[i].theta); } else { double velocity_yaw_rate = velocity/yaw_rate; double theta_dt = particles[i].theta + yaw_rate_dt; particles[i].x += velocity_yaw_rate * (sin(theta_dt) - sin(particles[i].theta)); particles[i].y += velocity_yaw_rate * (cos(particles[i].theta) - cos(theta_dt)); particles[i].theta = theta_dt; } normal_distribution<double> dist_x(particles[i].x, std_pos[0]); normal_distribution<double> dist_y(particles[i].y, std_pos[1]); normal_distribution<double> dist_theta(particles[i].theta, std_pos[2]); particles[i].x = dist_x(gen); particles[i].y = dist_y(gen); particles[i].theta = dist_theta(gen); } } void ParticleFilter::dataAssociation(std::vector<LandmarkObs> predicted, std::vector<LandmarkObs>& observations) { for (int i = 0; i < observations.size(); i++) { double dist_min = numeric_limits<double>::max(); int associated_landmark_id = -1; double obx = observations[i].x; double oby = observations[i].y; for (int j = 0; j < predicted.size(); j++) { double dist_landmark = dist(obx, oby, predicted[j].x, predicted[j].y); if (dist_landmark < dist_min) { associated_landmark_id = predicted[j].id; dist_min = dist_landmark; observations[i].x = fabs(obx - predicted[j].x); observations[i].y = fabs(oby - predicted[j].y); } } if (associated_landmark_id == -1) { cout << "Error: No associated landmark found" << endl; } observations[i].id = associated_landmark_id; } } void ParticleFilter::updateWeights(double sensor_range, double std_landmark[], const std::vector<LandmarkObs> &observations, const Map &map_landmarks) { double weight_sum = 0.0; for (int i = 0; i < particles.size(); i++) { double par_x = particles[i].x; double par_y = particles[i].y; double par_t = particles[i].theta; vector<LandmarkObs> within_range_landmarks; for (int j = 0; j < map_landmarks.landmark_list.size(); j++) { double mx = map_landmarks.landmark_list[j].x_f; double my = map_landmarks.landmark_list[j].y_f; if ( dist(par_x, par_y, mx, my) <= sensor_range ) { within_range_landmarks.push_back(LandmarkObs{map_landmarks.landmark_list[j].i
void ParticleFilter::resample() { random_device rd; default_random_engine gen(rd()); vector<Particle> resampled_particles; resampled_particles.resize(particles.size()); discrete_distribution<int> dist_resample(weights.begin(), weights.end()); for (int i = 0; i < particles.size(); i++) { resampled_particles[i] = particles[dist_resample(gen)]; } particles = resampled_particles; } Particle ParticleFilter::SetAssociations(Particle& particle, const std::vector<int>& associations, const std::vector<double>& sense_x, const std::vector<double>& sense_y) { particle.associations= associations; particle.sense_x = sense_x; particle.sense_y = sense_y; } string ParticleFilter::getAssociations(Particle best) { vector<int> v = best.associations; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<int>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); return s; } string ParticleFilter::getSenseX(Particle best) { vector<double> v = best.sense_x; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); return s; } string ParticleFilter::getSenseY(Particle best) { vector<double> v = best.sense_y; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); return s; }
d_i, mx, my}); } } vector<LandmarkObs> mapped_observations; for (int j = 0; j < observations.size(); j++) { double mapx = cos(par_t) * observations[j].x - sin(par_t) * observations[j].y + par_x; double mapy = sin(par_t) * observations[j].x + cos(par_t) * observations[j].y + par_y; mapped_observations.push_back(LandmarkObs{observations[j].id, mapx, mapy}); } dataAssociation(within_range_landmarks, mapped_observations); particles[i].weight = 1.0; for (int j = 0; j < mapped_observations.size(); j++) { double mvg_prob; double diffX = mapped_observations[j].x; double diffY = mapped_observations[j].y; if (mapped_observations[j].id != -1) { double mvg_prob = (1/(2*M_PI*std_landmark[0]*std_landmark[1])) * exp(-((diffX*diffX)/(2*std_landmark[0]*std_landmark[0]) + (diffY*diffY)/(2*std_landmark[1]*std_landmark[1]))); if (mvg_prob < EPS) { mvg_prob = EPS; } particles[i].weight *= mvg_prob; } } weight_sum += particles[i].weight; } for (int i = 0; i < particles.size(); i++) { particles[i].weight /= weight_sum; weights[i] = particles[i].weight; } }
function_block-function_prefixed
[ { "content": " class iter_impl : public std::iterator<std::random_access_iterator_tag, U>\n\n {\n\n /// allow basic_json to access private members\n\n friend class basic_json;\n\n\n\n // make sure U is basic_json or const basic_json\n\n static_assert(std::is_same<U, basic_json>::value\n\n or std::is_same<U, const basic_json>::value,\n\n \"iter_impl only accepts (const) basic_json\");\n\n\n\n public:\n\n /// the type of the values when the iterator is dereferenced\n\n using value_type = typename basic_json::value_type;\n\n /// a type to represent differences between iterators\n\n using difference_type = typename basic_json::difference_type;\n\n /// defines a pointer to the type iterated over (value_type)\n\n using pointer = typename std::conditional<std::is_const<U>::value,\n\n typename basic_json::const_pointer,\n\n typename basic_json::pointer>::type;\n\n /// defines a reference to the type iterated over (value_type)\n", "file_path": "src/json.hpp", "rank": 0, "score": 78711.06772647453 }, { "content": " class StringType = std::string,\n", "file_path": "src/json.hpp", "rank": 1, "score": 69548.87403294678 }, { "content": "class Map {\n\npublic:\n\n\t\n\n\tstruct single_landmark_s{\n\n\n\n\t\tint id_i ; // Landmark ID\n\n\t\tfloat x_f; // Landmark x-position in the map (global coordinates)\n\n\t\tfloat y_f; // Landmark y-position in the map (global coordinates)\n\n\t};\n\n\n\n\tstd::vector<single_landmark_s> landmark_list ; // List of landmarks in the map\n\n\n\n};\n\n\n\n\n\n\n\n#endif /* MAP_H_ */\n", "file_path": "src/map.h", "rank": 2, "score": 53827.16195750034 }, { "content": " class json_reverse_iterator : public std::reverse_iterator<Base>\n\n {\n\n public:\n\n /// shortcut to the reverse iterator adaptor\n\n using base_iterator = std::reverse_iterator<Base>;\n\n /// the reference type for the pointed-to element\n\n using reference = typename Base::reference;\n\n\n\n /// create reverse iterator from iterator\n\n json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept\n\n : base_iterator(it)\n\n {}\n\n\n\n /// create reverse iterator from base class\n\n json_reverse_iterator(const base_iterator& it) noexcept\n\n : base_iterator(it)\n\n {}\n\n\n\n /// post-increment (it++)\n\n json_reverse_iterator operator++(int)\n", "file_path": "src/json.hpp", "rank": 3, "score": 50709.662537701945 }, { "content": " class is a @ref const_iterator this function is not called.\n\n */\n\n operator const_iterator() const\n\n {\n\n const_iterator ret;\n\n\n\n if (m_object)\n\n {\n\n ret.m_object = m_object;\n\n ret.m_it = m_it;\n\n }\n\n\n\n return ret;\n\n }\n\n\n\n /*!\n\n @brief copy constructor\n\n @param[in] other iterator to copy from\n\n @note It is not checked whether @a other is initialized.\n\n */\n", "file_path": "src/json.hpp", "rank": 4, "score": 43028.787591798144 }, { "content": "struct Particle {\n\n\n\n\tint id;\n\n\tdouble x;\n\n\tdouble y;\n\n\tdouble theta;\n\n\tdouble weight;\n\n\tstd::vector<int> associations;\n\n\tstd::vector<double> sense_x;\n\n\tstd::vector<double> sense_y;\n\n};\n\n\n\n\n\n\n", "file_path": "src/particle_filter.h", "rank": 5, "score": 39989.88044052399 }, { "content": "class ParticleFilter {\n\n\t\n\n\t// Number of particles to draw\n\n\tint num_particles; \n\n\t\n\n\t\n\n\t\n\n\t// Flag, if filter is initialized\n\n\tbool is_initialized;\n\n\t\n\n\t// Vector of weights of all particles\n\n\tstd::vector<double> weights;\n\n\t\n\npublic:\n\n\t\n\n\t// Set of current particles\n\n\tstd::vector<Particle> particles;\n\n\n\n\t// Constructor\n\n\t// @param num_particles Number of particles\n", "file_path": "src/particle_filter.h", "rank": 6, "score": 37742.67965259883 }, { "content": "\tdouble theta;\t// Global vehicle yaw [rad]\n", "file_path": "src/helper_functions.h", "rank": 7, "score": 35381.84753731691 }, { "content": "/*\n\n * map.h\n\n *\n\n * Created on: Dec 12, 2016\n\n * Author: mufferm\n\n */\n\n\n\n#ifndef MAP_H_\n\n#define MAP_H_\n\n\n", "file_path": "src/map.h", "rank": 8, "score": 34880.73788070064 }, { "content": "#ifndef HELPER_FUNCTIONS_H_\n\n#define HELPER_FUNCTIONS_H_\n\n\n\n#include <sstream>\n\n#include <fstream>\n\n#include <math.h>\n\n#include <vector>\n\n#include \"map.h\"\n\n\n\n// for portability of M_PI (Vis Studio, MinGW, etc.)\n\n#ifndef M_PI\n\nconst double M_PI = 3.14159265358979323846;\n\n#endif\n\n\n\n/*\n\n * Struct representing one position/control measurement.\n\n */\n\nstruct control_s {\n\n\t\n\n\tdouble velocity;\t// Velocity [m/s]\n\n\tdouble yawrate;\t\t// Yaw rate [rad/s]\n\n};\n\n\n\n/*\n\n * Struct representing one ground truth position.\n\n */\n\nstruct ground_truth {\n\n\t\n\n\tdouble x;\t\t// Global vehicle x position [m]\n\n\tdouble y;\t\t// Global vehicle y position\n\n\tdouble theta;\t// Global vehicle yaw [rad]\n\n};\n\n\n\n/*\n\n * Struct representing one landmark observation measurement.\n\n */\n\nstruct LandmarkObs {\n\n\t\n\n\tint id;\t\t\t\t// Id of matching landmark in the map.\n\n\tdouble x;\t\t\t// Local (vehicle coordinates) x position of landmark observation [m]\n\n\tdouble y;\t\t\t// Local (vehicle coordinates) y position of landmark observation [m]\n\n};\n\n\n\n/*\n\n * Computes the Euclidean distance between two 2D points.\n\n * @param (x1,y1) x and y coordinates of first point\n\n * @param (x2,y2) x and y coordinates of second point\n\n * @output Euclidean distance between two 2D points\n\n */\n\ninline double dist(double x1, double y1, double x2, double y2) {\n\n\treturn sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));\n\n}\n\n\n\ninline double * getError(double gt_x, double gt_y, double gt_theta, double pf_x, double pf_y, double pf_theta) {\n\n\tstatic double error[3];\n\n\terror[0] = fabs(pf_x - gt_x);\n\n\terror[1] = fabs(pf_y - gt_y);\n\n\terror[2] = fabs(pf_theta - gt_theta);\n\n\terror[2] = fmod(error[2], 2.0 * M_PI);\n\n\tif (error[2] > M_PI) {\n\n\t\terror[2] = 2.0 * M_PI - error[2];\n\n\t}\n\n\treturn error;\n\n}\n\n\n\n/* Reads map data from a file.\n\n * @param filename Name of file containing map data.\n\n * @output True if opening and reading file was successful\n\n */\n\ninline bool read_map_data(std::string filename, Map& map) {\n\n\n\n\t// Get file of map:\n\n\tstd::ifstream in_file_map(filename.c_str(),std::ifstream::in);\n\n\t// Return if we can't open the file.\n\n\tif (!in_file_map) {\n\n\t\treturn false;\n\n\t}\n\n\t\n\n\t// Declare single line of map file:\n\n\tstd::string line_map;\n\n\n\n\t// Run over each single line:\n\n\twhile(getline(in_file_map, line_map)){\n\n\n\n\t\tstd::istringstream iss_map(line_map);\n\n\n\n\t\t// Declare landmark values and ID:\n\n\t\tfloat landmark_x_f, landmark_y_f;\n\n\t\tint id_i;\n\n\n\n\t\t// Read data from current line to values::\n\n\t\tiss_map >> landmark_x_f;\n\n\t\tiss_map >> landmark_y_f;\n\n\t\tiss_map >> id_i;\n\n\n\n\t\t// Declare single_landmark:\n\n\t\tMap::single_landmark_s single_landmark_temp;\n\n\n\n\t\t// Set values\n\n\t\tsingle_landmark_temp.id_i = id_i;\n\n\t\tsingle_landmark_temp.x_f = landmark_x_f;\n\n\t\tsingle_landmark_temp.y_f = landmark_y_f;\n\n\n\n\t\t// Add to landmark list of map:\n\n\t\tmap.landmark_list.push_back(single_landmark_temp);\n\n\t}\n\n\treturn true;\n\n}\n\n\n\n/* Reads control data from a file.\n\n * @param filename Name of file containing control measurements.\n\n * @output True if opening and reading file was successful\n\n */\n\ninline bool read_control_data(std::string filename, std::vector<control_s>& position_meas) {\n\n\n\n\t// Get file of position measurements:\n\n\tstd::ifstream in_file_pos(filename.c_str(),std::ifstream::in);\n\n\t// Return if we can't open the file.\n\n\tif (!in_file_pos) {\n\n\t\treturn false;\n\n\t}\n\n\n\n\t// Declare single line of position measurement file:\n\n\tstd::string line_pos;\n\n\n\n\t// Run over each single line:\n\n\twhile(getline(in_file_pos, line_pos)){\n\n\n\n\t\tstd::istringstream iss_pos(line_pos);\n\n\n\n\t\t// Declare position values:\n\n\t\tdouble velocity, yawrate;\n\n\n\n\t\t// Declare single control measurement:\n\n\t\tcontrol_s meas;\n\n\n\n\t\t//read data from line to values:\n\n\n\n\t\tiss_pos >> velocity;\n\n\t\tiss_pos >> yawrate;\n\n\n\n\t\t\n\n\t\t// Set values\n\n\t\tmeas.velocity = velocity;\n\n\t\tmeas.yawrate = yawrate;\n\n\n\n\t\t// Add to list of control measurements:\n\n\t\tposition_meas.push_back(meas);\n\n\t}\n\n\treturn true;\n\n}\n\n\n\n/* Reads ground truth data from a file.\n\n * @param filename Name of file containing ground truth.\n\n * @output True if opening and reading file was successful\n\n */\n\ninline bool read_gt_data(std::string filename, std::vector<ground_truth>& gt) {\n\n\n\n\t// Get file of position measurements:\n\n\tstd::ifstream in_file_pos(filename.c_str(),std::ifstream::in);\n\n\t// Return if we can't open the file.\n\n\tif (!in_file_pos) {\n\n\t\treturn false;\n\n\t}\n\n\n\n\t// Declare single line of position measurement file:\n\n\tstd::string line_pos;\n\n\n\n\t// Run over each single line:\n\n\twhile(getline(in_file_pos, line_pos)){\n\n\n\n\t\tstd::istringstream iss_pos(line_pos);\n\n\n\n\t\t// Declare position values:\n\n\t\tdouble x, y, azimuth;\n\n\n\n\t\t// Declare single ground truth:\n\n\t\tground_truth single_gt; \n\n\n\n\t\t//read data from line to values:\n\n\t\tiss_pos >> x;\n\n\t\tiss_pos >> y;\n\n\t\tiss_pos >> azimuth;\n\n\n\n\t\t// Set values\n\n\t\tsingle_gt.x = x;\n\n\t\tsingle_gt.y = y;\n\n\t\tsingle_gt.theta = azimuth;\n\n\n\n\t\t// Add to list of control measurements and ground truth:\n\n\t\tgt.push_back(single_gt);\n\n\t}\n\n\treturn true;\n\n}\n\n\n\n/* Reads landmark observation data from a file.\n\n * @param filename Name of file containing landmark observation measurements.\n\n * @output True if opening and reading file was successful\n\n */\n\ninline bool read_landmark_data(std::string filename, std::vector<LandmarkObs>& observations) {\n\n\n\n\t// Get file of landmark measurements:\n\n\tstd::ifstream in_file_obs(filename.c_str(),std::ifstream::in);\n\n\t// Return if we can't open the file.\n\n\tif (!in_file_obs) {\n\n\t\treturn false;\n\n\t}\n\n\n\n\t// Declare single line of landmark measurement file:\n\n\tstd::string line_obs;\n\n\n\n\t// Run over each single line:\n\n\twhile(getline(in_file_obs, line_obs)){\n\n\n\n\t\tstd::istringstream iss_obs(line_obs);\n\n\n\n\t\t// Declare position values:\n\n\t\tdouble local_x, local_y;\n\n\n\n\t\t//read data from line to values:\n\n\t\tiss_obs >> local_x;\n\n\t\tiss_obs >> local_y;\n\n\n\n\t\t// Declare single landmark measurement:\n\n\t\tLandmarkObs meas;\n\n\n\n\t\t// Set values\n\n\t\tmeas.x = local_x;\n\n\t\tmeas.y = local_y;\n\n\n\n\t\t// Add to list of control measurements:\n\n\t\tobservations.push_back(meas);\n\n\t}\n\n\treturn true;\n\n}\n\n\n", "file_path": "src/helper_functions.h", "rank": 9, "score": 32641.204894773087 }, { "content": "\t * @param std_pos[] Array of dimension 3 [standard deviation of x [m], standard deviation of y [m]\n\n\t * standard deviation of yaw [rad]]\n\n\t * @param velocity Velocity of car from t to t+1 [m/s]\n\n\t * @param yaw_rate Yaw rate of car from t to t+1 [rad/s]\n\n\t */\n\n\tvoid prediction(double delta_t, double std_pos[], double velocity, double yaw_rate);\n\n\t\n\n\t/**\n\n\t * dataAssociation Finds which observations correspond to which landmarks (likely by using\n\n\t * a nearest-neighbors data association).\n\n\t * @param predicted Vector of predicted landmark observations\n\n\t * @param observations Vector of landmark observations\n\n\t */\n\n\tvoid dataAssociation(std::vector<LandmarkObs> predicted, std::vector<LandmarkObs>& observations);\n\n\t\n\n\t/**\n\n\t * updateWeights Updates the weights for each particle based on the likelihood of the \n\n\t * observed measurements. \n\n\t * @param sensor_range Range [m] of sensor\n\n\t * @param std_landmark[] Array of dimension 2 [Landmark measurement uncertainty [x [m], y [m]]]\n", "file_path": "src/particle_filter.h", "rank": 10, "score": 31522.609082318108 }, { "content": "\t * @param observations Vector of landmark observations\n\n\t * @param map Map class containing map landmarks\n\n\t */\n\n\tvoid updateWeights(double sensor_range, double std_landmark[], const std::vector<LandmarkObs> &observations,\n\n\t\t\tconst Map &map_landmarks);\n\n\t\n\n\t/**\n\n\t * resample Resamples from the updated set of particles to form\n\n\t * the new set of particles.\n\n\t */\n\n\tvoid resample();\n\n\n\n\t/*\n\n\t * Set a particles list of associations, along with the associations calculated world x,y coordinates\n\n\t * This can be a very useful debugging tool to make sure transformations are correct and assocations correctly connected\n\n\t */\n\n\tParticle SetAssociations(Particle& particle, const std::vector<int>& associations,\n\n\t\t const std::vector<double>& sense_x, const std::vector<double>& sense_y);\n\n\n\n\t\n", "file_path": "src/particle_filter.h", "rank": 11, "score": 31520.4360107907 }, { "content": "\tParticleFilter() : num_particles(0), is_initialized(false) {}\n\n\n\n\t// Destructor\n\n\t~ParticleFilter() {}\n\n\n\n\t/**\n\n\t * init Initializes particle filter by initializing particles to Gaussian\n\n\t * distribution around first position and all the weights to 1.\n\n\t * @param x Initial x position [m] (simulated estimate from GPS)\n\n\t * @param y Initial y position [m]\n\n\t * @param theta Initial orientation [rad]\n\n\t * @param std[] Array of dimension 3 [standard deviation of x [m], standard deviation of y [m]\n\n\t * standard deviation of yaw [rad]]\n\n\t */\n\n\tvoid init(double x, double y, double theta, double std[]);\n\n\n\n\t/**\n\n\t * prediction Predicts the state for the next time step\n\n\t * using the process model.\n\n\t * @param delta_t Time between time step t and t+1 in measurements [s]\n", "file_path": "src/particle_filter.h", "rank": 12, "score": 31505.851296046636 }, { "content": "\tstd::string getAssociations(Particle best);\n\n\tstd::string getSenseX(Particle best);\n\n\tstd::string getSenseY(Particle best);\n\n\n\n\t/**\n\n\t* initialized Returns whether particle filter is initialized yet or not.\n\n\t*/\n\n\tconst bool initialized() const {\n\n\t\treturn is_initialized;\n\n\t}\n\n};\n\n\n\n\n\n\n\n#endif /* PARTICLE_FILTER_H_ */\n", "file_path": "src/particle_filter.h", "rank": 13, "score": 31503.85994180246 }, { "content": "/*\n\n * particle_filter.h\n\n *\n\n * 2D particle filter class.\n\n * Created on: Dec 12, 2016\n\n * Author: Tiffany Huang\n\n */\n\n\n\n#ifndef PARTICLE_FILTER_H_\n\n#define PARTICLE_FILTER_H_\n\n\n\n#include \"helper_functions.h\"\n\n\n", "file_path": "src/particle_filter.h", "rank": 14, "score": 31491.83932804022 }, { "content": "struct external_constructor<value_t::string>\n\n{\n\n template<typename BasicJsonType>\n\n static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)\n\n {\n\n j.m_type = value_t::string;\n\n j.m_value = s;\n\n j.assert_invariant();\n\n }\n\n};\n\n\n\ntemplate<>\n", "file_path": "src/json.hpp", "rank": 15, "score": 29254.575336149286 }, { "content": "object if no parse error occurred.\n\n\n\n@param[in] s a string representation of a JSON Pointer\n\n@param[in] n the length of string @a s\n\n@return a JSON pointer object\n\n\n\n@since version 2.0.0\n\n*/\n\ninline nlohmann::json::json_pointer operator \"\" _json_pointer(const char* s, std::size_t n)\n\n{\n\n return nlohmann::json::json_pointer(std::string(s, n));\n\n}\n\n\n\n// restore GCC/clang diagnostic settings\n\n#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)\n\n #pragma GCC diagnostic pop\n\n#endif\n\n\n\n// clean up\n\n#undef JSON_CATCH\n\n#undef JSON_DEPRECATED\n\n#undef JSON_THROW\n\n#undef JSON_TRY\n\n\n\n#endif\n", "file_path": "src/json.hpp", "rank": 16, "score": 29031.487558695713 }, { "content": " class NumberIntegerType = std::int64_t,\n", "file_path": "src/json.hpp", "rank": 31, "score": 27750.213332075757 }, { "content": " class NumberUnsignedType = std::uint64_t,\n", "file_path": "src/json.hpp", "rank": 32, "score": 27750.213332075757 }, { "content": "struct static_const\n\n{\n\n static constexpr T value{};\n\n};\n\n\n\ntemplate<typename T>\n\nconstexpr T static_const<T>::value;\n\n} // namespace detail\n\n\n\n\n\n/// namespace to hold default `to_json` / `from_json` functions\n\nnamespace\n\n{\n\nconstexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value;\n\nconstexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value;\n\n}\n\n\n\n\n\n/*!\n\n@brief default JSONSerializer template argument\n\n\n\nThis serializer ignores the template arguments and uses ADL\n\n([argument-dependent lookup](http://en.cppreference.com/w/cpp/language/adl))\n\nfor serialization.\n\n*/\n\ntemplate<typename = void, typename = void>\n", "file_path": "src/json.hpp", "rank": 33, "score": 26621.454802570992 }, { "content": " class primitive_iterator_t\n\n {\n\n public:\n\n\n\n difference_type get_value() const noexcept\n\n {\n\n return m_it;\n\n }\n\n /// set iterator to a defined beginning\n\n void set_begin() noexcept\n\n {\n\n m_it = begin_value;\n\n }\n\n\n\n /// set iterator to a defined past the end\n\n void set_end() noexcept\n\n {\n\n m_it = end_value;\n\n }\n\n\n", "file_path": "src/json.hpp", "rank": 34, "score": 26598.11242436531 }, { "content": " class iteration_proxy\n\n {\n\n private:\n", "file_path": "src/json.hpp", "rank": 35, "score": 26598.11242436531 }, { "content": "struct is_compatible_object_type_impl : std::false_type {};\n\n\n\ntemplate<class RealType, class CompatibleObjectType>\n", "file_path": "src/json.hpp", "rank": 36, "score": 25316.782736937916 }, { "content": "struct is_compatible_integer_type_impl : std::false_type {};\n\n\n\ntemplate<typename RealIntegerType, typename CompatibleNumberIntegerType>\n", "file_path": "src/json.hpp", "rank": 37, "score": 25316.782736937916 }, { "content": " /// helper class for iteration\n\n class iteration_proxy_internal\n\n {\n\n private:\n\n /// the iterator\n\n IteratorType anchor;\n\n /// an index for arrays (used to create key names)\n\n size_t array_index = 0;\n\n\n\n public:\n\n explicit iteration_proxy_internal(IteratorType it) noexcept\n\n : anchor(it)\n\n {}\n\n\n\n /// dereference operator (needed for range-based for)\n\n iteration_proxy_internal& operator*()\n\n {\n\n return *this;\n\n }\n\n\n\n /// increment operator (needed for range-based for)\n", "file_path": "src/json.hpp", "rank": 38, "score": 24656.637174010593 }, { "content": " class NumberFloatType = double,\n\n template<typename U> class AllocatorType = std::allocator,\n\n template<typename T, typename SFINAE = void> class JSONSerializer = adl_serializer\n\n >\n", "file_path": "src/json.hpp", "rank": 39, "score": 22996.854046048993 }, { "content": " function does not implicitly add an element to the position defined by @a\n\n key. This function is furthermore also applicable to const objects.\n\n\n\n @param[in] key key of the element to access\n\n @param[in] default_value the value to return if @a key is not found\n\n\n\n @tparam ValueType type compatible to JSON values, for instance `int` for\n\n JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for\n\n JSON arrays. Note the type of the expected value at @a key and the default\n\n value @a default_value must be compatible.\n\n\n\n @return copy of the element at key @a key or @a default_value if @a key\n\n is not found\n\n\n\n @throw std::domain_error if JSON is not an object; example: `\"cannot use\n\n value() with null\"`\n\n\n\n @complexity Logarithmic in the size of the container.\n\n\n\n @liveexample{The example below shows how object elements can be queried\n", "file_path": "src/json.hpp", "rank": 40, "score": 21528.998743346812 }, { "content": "struct is_compatible_object_type_impl<true, RealType, CompatibleObjectType>\n\n{\n\n static constexpr auto value =\n\n std::is_constructible<typename RealType::key_type,\n\n typename CompatibleObjectType::key_type>::value and\n\n std::is_constructible<typename RealType::mapped_type,\n\n typename CompatibleObjectType::mapped_type>::value;\n\n};\n\n\n\ntemplate<class BasicJsonType, class CompatibleObjectType>\n", "file_path": "src/json.hpp", "rank": 41, "score": 21455.426424817695 }, { "content": "struct is_compatible_integer_type_impl<true, RealIntegerType, CompatibleNumberIntegerType>\n\n{\n\n // is there an assert somewhere on overflows?\n\n using RealLimits = std::numeric_limits<RealIntegerType>;\n\n using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;\n\n\n\n static constexpr auto value =\n\n std::is_constructible<RealIntegerType,\n\n CompatibleNumberIntegerType>::value and\n\n CompatibleLimits::is_integer and\n\n RealLimits::is_signed == CompatibleLimits::is_signed;\n\n};\n\n\n\ntemplate<typename RealIntegerType, typename CompatibleNumberIntegerType>\n", "file_path": "src/json.hpp", "rank": 42, "score": 20015.752272573598 }, { "content": "\tdouble x;\t\t\t// Local (vehicle coordinates) x position of landmark observation [m]\n", "file_path": "src/helper_functions.h", "rank": 43, "score": 18236.353252912955 }, { "content": "\tdouble velocity;\t// Velocity [m/s]\n", "file_path": "src/helper_functions.h", "rank": 44, "score": 17150.28824732808 }, { "content": "struct conjunction<B1, Bn...> : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};\n\n\n\ntemplate<class B> struct negation : std::integral_constant < bool, !B::value > {};\n\n\n\n// dispatch utility (taken from ranges-v3)\n\ntemplate<unsigned N> struct priority_tag : priority_tag < N - 1 > {};\n\ntemplate<> struct priority_tag<0> {};\n\n\n\n\n\n//////////////////\n\n// constructors //\n\n//////////////////\n\n\n\ntemplate<value_t> struct external_constructor;\n\n\n\ntemplate<>\n", "file_path": "src/json.hpp", "rank": 45, "score": 16963.92552199599 }, { "content": "inline double * getError(double gt_x, double gt_y, double gt_theta, double pf_x, double pf_y, double pf_theta) {\n\n\tstatic double error[3];\n\n\terror[0] = fabs(pf_x - gt_x);\n\n\terror[1] = fabs(pf_y - gt_y);\n\n\terror[2] = fabs(pf_theta - gt_theta);\n\n\terror[2] = fmod(error[2], 2.0 * M_PI);\n\n\tif (error[2] > M_PI) {\n\n\t\terror[2] = 2.0 * M_PI - error[2];\n\n\t}\n\n\treturn error;\n", "file_path": "src/helper_functions.h", "rank": 46, "score": 16316.529849566798 }, { "content": "inline bool read_landmark_data(std::string filename, std::vector<LandmarkObs>& observations) {\n\n\n\n\t// Get file of landmark measurements:\n\n\tstd::ifstream in_file_obs(filename.c_str(),std::ifstream::in);\n\n\t// Return if we can't open the file.\n\n\tif (!in_file_obs) {\n\n\t\treturn false;\n\n\t}\n\n\n\n\t// Declare single line of landmark measurement file:\n\n\tstd::string line_obs;\n\n\n\n\t// Run over each single line:\n\n\twhile(getline(in_file_obs, line_obs)){\n\n\n\n\t\tstd::istringstream iss_obs(line_obs);\n\n\n\n\t\t// Declare position values:\n\n\t\tdouble local_x, local_y;\n\n\n\n\t\t//read data from line to values:\n\n\t\tiss_obs >> local_x;\n\n\t\tiss_obs >> local_y;\n\n\n\n\t\t// Declare single landmark measurement:\n\n\t\tLandmarkObs meas;\n\n\n\n\t\t// Set values\n\n\t\tmeas.x = local_x;\n\n\t\tmeas.y = local_y;\n\n\n\n\t\t// Add to list of control measurements:\n\n\t\tobservations.push_back(meas);\n\n\t}\n\n\treturn true;\n", "file_path": "src/helper_functions.h", "rank": 47, "score": 15577.060272606392 }, { "content": "inline bool read_map_data(std::string filename, Map& map) {\n\n\n\n\t// Get file of map:\n\n\tstd::ifstream in_file_map(filename.c_str(),std::ifstream::in);\n\n\t// Return if we can't open the file.\n\n\tif (!in_file_map) {\n\n\t\treturn false;\n\n\t}\n\n\t\n\n\t// Declare single line of map file:\n\n\tstd::string line_map;\n\n\n\n\t// Run over each single line:\n\n\twhile(getline(in_file_map, line_map)){\n\n\n\n\t\tstd::istringstream iss_map(line_map);\n\n\n\n\t\t// Declare landmark values and ID:\n\n\t\tfloat landmark_x_f, landmark_y_f;\n\n\t\tint id_i;\n\n\n\n\t\t// Read data from current line to values::\n\n\t\tiss_map >> landmark_x_f;\n\n\t\tiss_map >> landmark_y_f;\n\n\t\tiss_map >> id_i;\n\n\n\n\t\t// Declare single_landmark:\n\n\t\tMap::single_landmark_s single_landmark_temp;\n\n\n\n\t\t// Set values\n\n\t\tsingle_landmark_temp.id_i = id_i;\n\n\t\tsingle_landmark_temp.x_f = landmark_x_f;\n\n\t\tsingle_landmark_temp.y_f = landmark_y_f;\n\n\n\n\t\t// Add to landmark list of map:\n\n\t\tmap.landmark_list.push_back(single_landmark_temp);\n\n\t}\n\n\treturn true;\n", "file_path": "src/helper_functions.h", "rank": 48, "score": 15568.842908596973 }, { "content": " \t\t\tstd::copy(std::istream_iterator<float>(iss_y),\n\n \tstd::istream_iterator<float>(),\n\n \tstd::back_inserter(y_sense));\n\n\n\n \tfor(int i = 0; i < x_sense.size(); i++)\n\n \t{\n\n \t\tLandmarkObs obs;\n\n \t\tobs.x = x_sense[i];\n\n\t\t\t\tobs.y = y_sense[i];\n\n\t\t\t\tnoisy_observations.push_back(obs);\n\n \t}\n\n\n\n\t\t // Update the weights and resample\n\n\t\t pf.updateWeights(sensor_range, sigma_landmark, noisy_observations, map);\n\n\t\t pf.resample();\n\n\n\n\t\t // Calculate and output the average weighted error of the particle filter over all time steps so far.\n\n\t\t vector<Particle> particles = pf.particles;\n\n\t\t int num_particles = particles.size();\n\n\t\t double highest_weight = -1.0;\n", "file_path": "src/main.cpp", "rank": 49, "score": 33.10666538914421 }, { "content": "\n\n\t\t\tpf.prediction(delta_t, sigma_pos, previous_velocity, previous_yawrate);\n\n\t\t }\n\n\n\n\t\t // receive noisy observation data from the simulator\n\n\t\t // sense_observations in JSON format [{obs_x,obs_y},{obs_x,obs_y},...{obs_x,obs_y}]\n\n\t\t \tvector<LandmarkObs> noisy_observations;\n\n\t\t \tstring sense_observations_x = j[1][\"sense_observations_x\"];\n\n\t\t \tstring sense_observations_y = j[1][\"sense_observations_y\"];\n\n\n\n\t\t \tstd::vector<float> x_sense;\n\n \t\t\tstd::istringstream iss_x(sense_observations_x);\n\n\n\n \t\t\tstd::copy(std::istream_iterator<float>(iss_x),\n\n \tstd::istream_iterator<float>(),\n\n \tstd::back_inserter(x_sense));\n\n\n\n \tstd::vector<float> y_sense;\n\n \t\t\tstd::istringstream iss_y(sense_observations_y);\n\n\n", "file_path": "src/main.cpp", "rank": 50, "score": 31.792247230643923 }, { "content": "#include <uWS/uWS.h>\n\n#include <iostream>\n\n#include \"json.hpp\"\n\n#include <math.h>\n\n#include \"particle_filter.h\"\n\n\n\nusing namespace std;\n\n\n\n// for convenience\n\nusing json = nlohmann::json;\n\n\n\n// Checks if the SocketIO event has JSON data.\n\n// If there is data the JSON object in string format will be returned,\n\n// else the empty string \"\" will be returned.\n\nstd::string hasData(std::string s) {\n\n auto found_null = s.find(\"null\");\n\n auto b1 = s.find_first_of(\"[\");\n\n auto b2 = s.find_first_of(\"]\");\n\n if (found_null != std::string::npos) {\n\n return \"\";\n", "file_path": "src/main.cpp", "rank": 51, "score": 29.220066722941326 }, { "content": "#include <cstring> // strlen\n\n#include <forward_list> // forward_list\n\n#include <functional> // function, hash, less\n\n#include <initializer_list> // initializer_list\n\n#include <iomanip> // setw\n\n#include <iostream> // istream, ostream\n\n#include <iterator> // advance, begin, back_inserter, bidirectional_iterator_tag, distance, end, inserter, iterator, iterator_traits, next, random_access_iterator_tag, reverse_iterator\n\n#include <limits> // numeric_limits\n\n#include <locale> // locale\n\n#include <map> // map\n\n#include <memory> // addressof, allocator, allocator_traits, unique_ptr\n\n#include <numeric> // accumulate\n\n#include <sstream> // stringstream\n\n#include <stdexcept> // domain_error, invalid_argument, out_of_range\n\n#include <string> // getline, stoi, string, to_string\n\n#include <type_traits> // add_pointer, conditional, decay, enable_if, false_type, integral_constant, is_arithmetic, is_base_of, is_const, is_constructible, is_convertible, is_default_constructible, is_enum, is_floating_point, is_integral, is_nothrow_move_assignable, is_nothrow_move_constructible, is_pointer, is_reference, is_same, is_scalar, is_signed, remove_const, remove_cv, remove_pointer, remove_reference, true_type, underlying_type\n\n#include <utility> // declval, forward, make_pair, move, pair, swap\n\n#include <vector> // vector\n\n\n\n// exclude unsupported compilers\n", "file_path": "src/json.hpp", "rank": 52, "score": 28.212665770919642 }, { "content": "3. ./run.sh\n\n\n\nTips for setting up your environment can be found [here](https://classroom.udacity.com/nanodegrees/nd013/parts/40f38239-66b6-46ec-ae68-03afd8a601c8/modules/0949fca6-b379-42af-a919-ee50aa304e6a/lessons/f758c44c-5e40-4e01-93b5-1a82aa4e044f/concepts/23d376c7-0195-4276-bdf0-e02f1f3c665d)\n\n\n\nNote that the programs that need to be written to accomplish the project are src/particle_filter.cpp, and particle_filter.h\n\n\n\nThe program main.cpp has already been filled out, but feel free to modify it.\n\n\n\nHere is the main protcol that main.cpp uses for uWebSocketIO in communicating with the simulator.\n\n\n\nINPUT: values provided by the simulator to the c++ program\n\n\n\n// sense noisy position data from the simulator\n\n\n\n[\"sense_x\"] \n\n\n\n[\"sense_y\"] \n\n\n\n[\"sense_theta\"] \n\n\n\n// get the previous velocity and yaw rate to predict the particle's transitioned state\n\n\n\n[\"previous_velocity\"]\n\n\n\n[\"previous_yawrate\"]\n\n\n\n// receive noisy observation data from the simulator, in a respective list of x/y values\n\n\n\n[\"sense_observations_x\"] \n\n\n\n[\"sense_observations_y\"] \n\n\n\n\n\nOUTPUT: values provided by the c++ program to the simulator\n\n\n\n// best particle values used for calculating the error evaluation\n\n\n\n[\"best_particle_x\"]\n\n\n\n[\"best_particle_y\"]\n\n\n\n[\"best_particle_theta\"] \n\n\n\n//Optional message data used for debugging particle's sensing and associations\n\n\n\n// for respective (x,y) sensed positions ID label \n\n\n\n[\"best_particle_associations\"]\n\n\n\n// for respective (x,y) sensed positions\n\n\n\n[\"best_particle_sense_x\"] <= list of sensed x positions\n\n\n\n[\"best_particle_sense_y\"] <= list of sensed y positions\n\n\n\n\n\nYour job is to build out the methods in `particle_filter.cpp` until the simulator output says:\n\n\n\n```\n\nSuccess! Your particle filter passed!\n\n```\n\n\n", "file_path": "README.md", "rank": 53, "score": 23.46120990158692 }, { "content": "\t\t Particle best_particle;\n\n\t\t double weight_sum = 0.0;\n\n\t\t for (int i = 0; i < num_particles; ++i) {\n\n\t\t\tif (particles[i].weight > highest_weight) {\n\n\t\t\t\thighest_weight = particles[i].weight;\n\n\t\t\t\tbest_particle = particles[i];\n\n\t\t\t}\n\n\t\t\tweight_sum += particles[i].weight;\n\n\t\t }\n\n\t\t cout << \"highest w \" << highest_weight << endl;\n\n\t\t cout << \"average w \" << weight_sum/num_particles << endl;\n\n\n\n json msgJson;\n\n msgJson[\"best_particle_x\"] = best_particle.x;\n\n msgJson[\"best_particle_y\"] = best_particle.y;\n\n msgJson[\"best_particle_theta\"] = best_particle.theta;\n\n\n\n //Optional message data used for debugging particle's sensing and associations\n\n msgJson[\"best_particle_associations\"] = pf.getAssociations(best_particle);\n\n msgJson[\"best_particle_sense_x\"] = pf.getSenseX(best_particle);\n", "file_path": "src/main.cpp", "rank": 54, "score": 22.64387017207057 }, { "content": " }\n\n else if (b1 != std::string::npos && b2 != std::string::npos) {\n\n return s.substr(b1, b2 - b1 + 1);\n\n }\n\n return \"\";\n\n}\n\n\n\nint main()\n\n{\n\n uWS::Hub h;\n\n\n\n //Set up parameters here\n\n double delta_t = 0.1; // Time elapsed between measurements [sec]\n\n double sensor_range = 50; // Sensor range [m]\n\n\n\n double sigma_pos [3] = {0.3, 0.3, 0.01}; // GPS measurement uncertainty [x [m], y [m], theta [rad]]\n\n double sigma_landmark [2] = {0.3, 0.3}; // Landmark measurement uncertainty [x [m], y [m]]\n\n\n\n // Read map data\n\n Map map;\n", "file_path": "src/main.cpp", "rank": 55, "score": 21.74569884773294 }, { "content": " auto j = json::parse(s);\n\n std::string event = j[0].get<std::string>();\n\n \n\n if (event == \"telemetry\") {\n\n // j[1] is the data JSON object\n\n\n\n\n\n if (!pf.initialized()) {\n\n\n\n \t// Sense noisy position data from the simulator\n\n\t\t\tdouble sense_x = std::stod(j[1][\"sense_x\"].get<std::string>());\n\n\t\t\tdouble sense_y = std::stod(j[1][\"sense_y\"].get<std::string>());\n\n\t\t\tdouble sense_theta = std::stod(j[1][\"sense_theta\"].get<std::string>());\n\n\n\n\t\t\tpf.init(sense_x, sense_y, sense_theta, sigma_pos);\n\n\t\t }\n\n\t\t else {\n\n\t\t\t// Predict the vehicle's next state from previous (noiseless control) data.\n\n\t\t \tdouble previous_velocity = std::stod(j[1][\"previous_velocity\"].get<std::string>());\n\n\t\t\tdouble previous_yawrate = std::stod(j[1][\"previous_yawrate\"].get<std::string>());\n", "file_path": "src/main.cpp", "rank": 56, "score": 21.676266515037888 }, { "content": "\n\n @tparam InputIT an input iterator type (@ref iterator or @ref\n\n const_iterator)\n\n\n\n @param[in] first begin of the range to copy from (included)\n\n @param[in] last end of the range to copy from (excluded)\n\n\n\n @pre Iterators @a first and @a last must be initialized. **This\n\n precondition is enforced with an assertion.**\n\n\n\n @throw std::domain_error if iterators are not compatible; that is, do not\n\n belong to the same JSON value; example: `\"iterators are not compatible\"`\n\n @throw std::out_of_range if iterators are for a primitive type (number,\n\n boolean, or string) where an out of range error can be detected easily;\n\n example: `\"iterators out of range\"`\n\n @throw std::bad_alloc if allocation for object, array, or string fails\n\n @throw std::domain_error if called with a null value; example: `\"cannot\n\n use construct with iterators from null\"`\n\n\n\n @complexity Linear in distance between @a first and @a last.\n", "file_path": "src/json.hpp", "rank": 57, "score": 20.992767364426655 }, { "content": " if (!read_map_data(\"../data/map_data.txt\", map)) {\n\n\t cout << \"Error: Could not open map file\" << endl;\n\n\t return -1;\n\n }\n\n\n\n // Create particle filter\n\n ParticleFilter pf;\n\n\n\n h.onMessage([&pf,&map,&delta_t,&sensor_range,&sigma_pos,&sigma_landmark](uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, uWS::OpCode opCode) {\n\n // \"42\" at the start of the message means there's a websocket message event.\n\n // The 4 signifies a websocket message\n\n // The 2 signifies a websocket event\n\n\n\n if (length && length > 2 && data[0] == '4' && data[1] == '2')\n\n {\n\n\n\n auto s = hasData(std::string(data));\n\n if (s != \"\") {\n\n \t\n\n \t\n", "file_path": "src/main.cpp", "rank": 58, "score": 20.626907451511862 }, { "content": " erase, including the `end()` iterator.\n\n\n\n @throw std::domain_error if called on a `null` value; example: `\"cannot\n\n use erase() with null\"`\n\n @throw std::domain_error if called on iterators which does not belong to\n\n the current JSON value; example: `\"iterators do not fit current value\"`\n\n @throw std::out_of_range if called on a primitive type with invalid\n\n iterators (i.e., if `first != begin()` and `last != end()`); example:\n\n `\"iterators out of range\"`\n\n\n\n @complexity The complexity depends on the type:\n\n - objects: `log(size()) + std::distance(first, last)`\n\n - arrays: linear in the distance between @a first and @a last, plus linear\n\n in the distance between @a last and end of the container\n\n - strings: linear in the length of the string\n\n - other types: constant\n\n\n\n @liveexample{The example shows the result of `erase()` for different JSON\n\n types.,erase__IteratorType_IteratorType}\n\n\n", "file_path": "src/json.hpp", "rank": 59, "score": 20.300671484921295 }, { "content": " }\n\n else\n\n {\n\n JSON_THROW(std::domain_error(\"cannot use swap() with \" + type_name()));\n\n }\n\n }\n\n\n\n /*!\n\n @brief exchanges the values\n\n\n\n Exchanges the contents of a JSON string with those of @a other. Does not\n\n invoke any move, copy, or swap operations on individual elements. All\n\n iterators and references remain valid. The past-the-end iterator is\n\n invalidated.\n\n\n\n @param[in,out] other string to exchange the contents with\n\n\n\n @throw std::domain_error when JSON value is not a string; example: `\"cannot\n\n use swap() with boolean\"`\n\n\n", "file_path": "src/json.hpp", "rank": 60, "score": 20.239006219314266 }, { "content": " // to generate \"unexpected EOF\" error message\n\n if (std::distance(first, last) <= 0)\n\n {\n\n return parser(\"\").parse();\n\n }\n\n\n\n return parser(first, last, cb).parse();\n\n }\n\n\n\n /*!\n\n @brief deserialize from a container with contiguous storage\n\n\n\n This function reads from a container with contiguous storage of 1-byte\n\n values. Compatible container types include `std::vector`, `std::string`,\n\n `std::array`, and `std::initializer_list`. User-defined containers can be\n\n used as long as they implement random-access iterators and a contiguous\n\n storage.\n\n\n\n @pre The container storage is contiguous. Violating this precondition\n\n yields undefined behavior. **This precondition is enforced with an\n", "file_path": "src/json.hpp", "rank": 61, "score": 19.413047787663007 }, { "content": "\n\n JSON_THROW(std::domain_error(\"cannot use insert() with \" + type_name()));\n\n }\n\n\n\n /*!\n\n @brief inserts elements\n\n\n\n Inserts elements from range `[first, last)` before iterator @a pos.\n\n\n\n @param[in] pos iterator before which the content will be inserted; may be\n\n the end() iterator\n\n @param[in] first begin of the range of elements to insert\n\n @param[in] last end of the range of elements to insert\n\n\n\n @throw std::domain_error if called on JSON values other than arrays;\n\n example: `\"cannot use insert() with string\"`\n\n @throw std::domain_error if @a pos is not an iterator of *this; example:\n\n `\"iterator does not fit current value\"`\n\n @throw std::domain_error if @a first and @a last do not belong to the same\n\n JSON value; example: `\"iterators do not fit\"`\n", "file_path": "src/json.hpp", "rank": 62, "score": 19.407480401647767 }, { "content": " std::is_base_of<\n\n std::random_access_iterator_tag,\n\n typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>\n\n static basic_json parse(IteratorType first, IteratorType last,\n\n const parser_callback_t cb = nullptr)\n\n {\n\n // assertion to check that the iterator range is indeed contiguous,\n\n // see http://stackoverflow.com/a/35008842/266378 for more discussion\n\n assert(std::accumulate(first, last, std::pair<bool, int>(true, 0),\n\n [&first](std::pair<bool, int> res, decltype(*first) val)\n\n {\n\n res.first &= (val == *(std::next(std::addressof(*first), res.second++)));\n\n return res;\n\n }).first);\n\n\n\n // assertion to check that each element is 1 byte long\n\n static_assert(sizeof(typename std::iterator_traits<IteratorType>::value_type) == 1,\n\n \"each element in the iterator range must have the size of 1 byte\");\n\n\n\n // if iterator range is empty, create a parser with an empty string\n", "file_path": "src/json.hpp", "rank": 63, "score": 19.29579973261812 }, { "content": " @complexity Constant.\n\n\n\n @liveexample{The example below shows how strings can be swapped with\n\n `swap()`.,swap__string_t}\n\n\n\n @since version 1.0.0\n\n */\n\n void swap(string_t& other)\n\n {\n\n // swap only works for strings\n\n if (is_string())\n\n {\n\n std::swap(*(m_value.string), other);\n\n }\n\n else\n\n {\n\n JSON_THROW(std::domain_error(\"cannot use swap() with \" + type_name()));\n\n }\n\n }\n\n\n", "file_path": "src/json.hpp", "rank": 64, "score": 19.2465331690504 }, { "content": " example: `\"cannot use insert() with string\"`\n\n @throw std::domain_error if @a pos is not an iterator of *this; example:\n\n `\"iterator does not fit current value\"`\n\n\n\n @complexity Constant plus linear in the distance between @a pos and end of\n\n the container.\n\n\n\n @liveexample{The example shows how `insert()` is used.,insert}\n\n\n\n @since version 1.0.0\n\n */\n\n iterator insert(const_iterator pos, const basic_json& val)\n\n {\n\n // insert only works for arrays\n\n if (is_array())\n\n {\n\n // check if iterator pos fits to this JSON value\n\n if (pos.m_object != this)\n\n {\n\n JSON_THROW(std::domain_error(\"iterator does not fit current value\"));\n", "file_path": "src/json.hpp", "rank": 65, "score": 18.442394133978823 }, { "content": "\n\n This function reads from an iterator range of a container with contiguous\n\n storage of 1-byte values. Compatible container types include\n\n `std::vector`, `std::string`, `std::array`, `std::valarray`, and\n\n `std::initializer_list`. Furthermore, C-style arrays can be used with\n\n `std::begin()`/`std::end()`. User-defined containers can be used as long\n\n as they implement random-access iterators and a contiguous storage.\n\n\n\n @pre The iterator range is contiguous. Violating this precondition yields\n\n undefined behavior. **This precondition is enforced with an assertion.**\n\n @pre Each element in the range has a size of 1 byte. Violating this\n\n precondition yields undefined behavior. **This precondition is enforced\n\n with a static assertion.**\n\n\n\n @warning There is no way to enforce all preconditions at compile-time. If\n\n the function is called with noncompliant iterators and with\n\n assertions switched off, the behavior is undefined and will most\n\n likely yield segmentation violation.\n\n\n\n @tparam IteratorType iterator of container with contiguous storage\n", "file_path": "src/json.hpp", "rank": 66, "score": 18.062517275556814 }, { "content": " be valid and dereferenceable. Thus the `end()` iterator (which is valid,\n\n but is not dereferenceable) cannot be used as a value for @a pos.\n\n\n\n If called on a primitive type other than `null`, the resulting JSON value\n\n will be `null`.\n\n\n\n @param[in] pos iterator to the element to remove\n\n @return Iterator following the last removed element. If the iterator @a\n\n pos refers to the last element, the `end()` iterator is returned.\n\n\n\n @tparam IteratorType an @ref iterator or @ref const_iterator\n\n\n\n @post Invalidates iterators and references at or after the point of the\n\n erase, including the `end()` iterator.\n\n\n\n @throw std::domain_error if called on a `null` value; example: `\"cannot\n\n use erase() with null\"`\n\n @throw std::domain_error if called on an iterator which does not belong to\n\n the current JSON value; example: `\"iterator does not fit current value\"`\n\n @throw std::out_of_range if called on a primitive type with invalid\n", "file_path": "src/json.hpp", "rank": 67, "score": 17.887977085354446 }, { "content": "using is_unscoped_enum =\n\n std::integral_constant<bool, std::is_convertible<T, int>::value and\n\n std::is_enum<T>::value>;\n\n\n\n/*\n\nImplementation of two C++17 constructs: conjunction, negation. This is needed\n\nto avoid evaluating all the traits in a condition\n\n\n\nFor example: not std::is_same<void, T>::value and has_value_type<T>::value\n\nwill not compile when T = void (on MSVC at least). Whereas\n\nconjunction<negation<std::is_same<void, T>>, has_value_type<T>>::value will\n\nstop evaluating if negation<...>::value == false\n\n\n\nPlease note that those constructs must be used with caution, since symbols can\n\nbecome very long quickly (which can slow down compilation and cause MSVC\n\ninternal compiler errors). Only use it when you have to (see example ahead).\n\n*/\n\ntemplate<class...> struct conjunction : std::true_type {};\n\ntemplate<class B1> struct conjunction<B1> : B1 {};\n\ntemplate<class B1, class... Bn>\n", "file_path": "src/json.hpp", "rank": 68, "score": 17.591795941092798 }, { "content": " iterator result(this);\n\n result.m_it.array_iterator = m_value.array->insert(\n\n pos.m_it.array_iterator,\n\n first.m_it.array_iterator,\n\n last.m_it.array_iterator);\n\n return result;\n\n }\n\n\n\n /*!\n\n @brief inserts elements\n\n\n\n Inserts elements from initializer list @a ilist before iterator @a pos.\n\n\n\n @param[in] pos iterator before which the content will be inserted; may be\n\n the end() iterator\n\n @param[in] ilist initializer list to insert the values from\n\n\n\n @throw std::domain_error if called on JSON values other than arrays;\n\n example: `\"cannot use insert() with string\"`\n\n @throw std::domain_error if @a pos is not an iterator of *this; example:\n", "file_path": "src/json.hpp", "rank": 69, "score": 17.53505865329307 }, { "content": " */\n\n void swap(array_t& other)\n\n {\n\n // swap only works for arrays\n\n if (is_array())\n\n {\n\n std::swap(*(m_value.array), other);\n\n }\n\n else\n\n {\n\n JSON_THROW(std::domain_error(\"cannot use swap() with \" + type_name()));\n\n }\n\n }\n\n\n\n /*!\n\n @brief exchanges the values\n\n\n\n Exchanges the contents of a JSON object with those of @a other. Does not\n\n invoke any move, copy, or swap operations on individual elements. All\n\n iterators and references remain valid. The past-the-end iterator is\n", "file_path": "src/json.hpp", "rank": 70, "score": 17.278800536548196 }, { "content": "# Implementing the Particle Filter\n\nThe directory structure of this repository is as follows:\n\n\n\n```\n\nroot\n\n| build.sh\n\n| clean.sh\n\n| CMakeLists.txt\n\n| README.md\n\n| run.sh\n\n|\n\n|___data\n\n| | \n\n| | map_data.txt\n\n| \n\n| \n\n|___src\n\n | helper_functions.h\n\n | main.cpp\n\n | map.h\n\n | particle_filter.cpp\n\n | particle_filter.h\n\n```\n\n\n\nThe only file you should modify is `particle_filter.cpp` in the `src` directory. The file contains the scaffolding of a `ParticleFilter` class and some associated methods. Read through the code, the comments, and the header file `particle_filter.h` to get a sense for what this code is expected to do.\n\n\n\nIf you are interested, take a look at `src/main.cpp` as well. This file contains the code that will actually be running your particle filter and calling the associated methods.\n\n\n\n## Inputs to the Particle Filter\n\nYou can find the inputs to the particle filter in the `data` directory. \n\n\n\n#### The Map*\n\n`map_data.txt` includes the position of landmarks (in meters) on an arbitrary Cartesian coordinate system. Each row has three columns\n\n1. x position\n\n2. y position\n\n3. landmark id\n\n\n\n### All other data the simulator provides, such as observations and controls.\n\n\n\n> * Map data provided by 3D Mapping Solutions GmbH.\n\n\n\n## Success Criteria\n\nIf your particle filter passes the current grading code in the simulator (you can make sure you have the current version at any time by doing a `git pull`), then you should pass! \n\n\n\nThe things the grading code is looking for are:\n\n\n\n\n\n1. **Accuracy**: your particle filter should localize vehicle position and yaw to within the values specified in the parameters `max_translation_error` and `max_yaw_error` in `src/main.cpp`.\n\n\n\n2. **Performance**: your particle filter should complete execution within the time of 100 seconds.\n\n\n\n## How to write a README\n\nA well written README file can enhance your project and portfolio. Develop your abilities to create professional README files by completing [this free course](https://www.udacity.com/course/writing-readmes--ud777).\n\n\n\n\n\n\n", "file_path": "README.md", "rank": 71, "score": 17.221566067051164 }, { "content": " invalidated.\n\n\n\n @param[in,out] other object to exchange the contents with\n\n\n\n @throw std::domain_error when JSON value is not an object; example:\n\n `\"cannot use swap() with string\"`\n\n\n\n @complexity Constant.\n\n\n\n @liveexample{The example below shows how objects can be swapped with\n\n `swap()`.,swap__object_t}\n\n\n\n @since version 1.0.0\n\n */\n\n void swap(object_t& other)\n\n {\n\n // swap only works for objects\n\n if (is_object())\n\n {\n\n std::swap(*(m_value.object), other);\n", "file_path": "src/json.hpp", "rank": 72, "score": 16.901998902683165 }, { "content": " /*!\n\n @brief inserts elements\n\n\n\n Inserts @a cnt copies of @a val before iterator @a pos.\n\n\n\n @param[in] pos iterator before which the content will be inserted; may be\n\n the end() iterator\n\n @param[in] cnt number of copies of @a val to insert\n\n @param[in] val element to insert\n\n @return iterator pointing to the first element inserted, or @a pos if\n\n `cnt==0`\n\n\n\n @throw std::domain_error if called on JSON values other than arrays;\n\n example: `\"cannot use insert() with string\"`\n\n @throw std::domain_error if @a pos is not an iterator of *this; example:\n\n `\"iterator does not fit current value\"`\n\n\n\n @complexity Linear in @a cnt plus linear in the distance between @a pos\n\n and end of the container.\n\n\n", "file_path": "src/json.hpp", "rank": 73, "score": 16.80027565178955 }, { "content": "\n\n JSON_THROW(std::domain_error(\"cannot use operator[] with \" + type_name()));\n\n }\n\n\n\n /*!\n\n @brief access specified object element\n\n\n\n Returns a reference to the element at with specified key @a key.\n\n\n\n @note If @a key is not found in the object, then it is silently added to\n\n the object and filled with a `null` value to make `key` a valid reference.\n\n In case the value was `null` before, it is converted to an object.\n\n\n\n @param[in] key key of the element to access\n\n\n\n @return reference to the element at key @a key\n\n\n\n @throw std::domain_error if JSON is not an object or null; example:\n\n `\"cannot use operator[] with string\"`\n\n\n", "file_path": "src/json.hpp", "rank": 74, "score": 16.63665626798727 }, { "content": " /// @{\n\n\n\n /*!\n\n @brief a type for an object\n\n\n\n [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:\n\n > An object is an unordered collection of zero or more name/value pairs,\n\n > where a name is a string and a value is a string, number, boolean, null,\n\n > object, or array.\n\n\n\n To store objects in C++, a type is defined by the template parameters\n\n described below.\n\n\n\n @tparam ObjectType the container to store objects (e.g., `std::map` or\n\n `std::unordered_map`)\n\n @tparam StringType the type of the keys or names (e.g., `std::string`).\n\n The comparison function `std::less<StringType>` is used to order elements\n\n inside the container.\n\n @tparam AllocatorType the allocator to use for objects (e.g.,\n\n `std::allocator`)\n", "file_path": "src/json.hpp", "rank": 75, "score": 16.351489917272232 }, { "content": " @brief create a JSON value\n\n\n\n This is a \"catch all\" constructor for all compatible JSON types; that is,\n\n types for which a `to_json()` method exsits. The constructor forwards the\n\n parameter @a val to that method (to `json_serializer<U>::to_json` method\n\n with `U = uncvref_t<CompatibleType>`, to be exact).\n\n\n\n Template type @a CompatibleType includes, but is not limited to, the\n\n following types:\n\n - **arrays**: @ref array_t and all kinds of compatible containers such as\n\n `std::vector`, `std::deque`, `std::list`, `std::forward_list`,\n\n `std::array`, `std::set`, `std::unordered_set`, `std::multiset`, and\n\n `unordered_multiset` with a `value_type` from which a @ref basic_json\n\n value can be constructed.\n\n - **objects**: @ref object_t and all kinds of compatible associative\n\n containers such as `std::map`, `std::unordered_map`, `std::multimap`,\n\n and `std::unordered_multimap` with a `key_type` compatible to\n\n @ref string_t and a `value_type` from which a @ref basic_json value can\n\n be constructed.\n\n - **strings**: @ref string_t, string literals, and all compatible string\n", "file_path": "src/json.hpp", "rank": 76, "score": 16.18362501729048 }, { "content": " @throw std::domain_error if @a first or @a last are iterators into\n\n container for which insert is called; example: `\"passed iterators may not\n\n belong to container\"`\n\n\n\n @return iterator pointing to the first element inserted, or @a pos if\n\n `first==last`\n\n\n\n @complexity Linear in `std::distance(first, last)` plus linear in the\n\n distance between @a pos and end of the container.\n\n\n\n @liveexample{The example shows how `insert()` is used.,insert__range}\n\n\n\n @since version 1.0.0\n\n */\n\n iterator insert(const_iterator pos, const_iterator first, const_iterator last)\n\n {\n\n // insert only works for arrays\n\n if (not is_array())\n\n {\n\n JSON_THROW(std::domain_error(\"cannot use insert() with \" + type_name()));\n", "file_path": "src/json.hpp", "rank": 77, "score": 16.17834894005344 }, { "content": " {\n\n case basic_json::value_t::object:\n\n {\n\n JSON_THROW(std::domain_error(\"cannot use offsets with object iterators\"));\n\n }\n\n\n\n case basic_json::value_t::array:\n\n {\n\n std::advance(m_it.array_iterator, i);\n\n break;\n\n }\n\n\n\n default:\n\n {\n\n m_it.primitive_iterator += i;\n\n break;\n\n }\n\n }\n\n\n\n return *this;\n", "file_path": "src/json.hpp", "rank": 78, "score": 16.130548429316917 }, { "content": " JSON_THROW(std::out_of_range(\"code points above 0x10FFFF are invalid\"));\n\n }\n\n\n\n return result;\n\n }\n\n\n\n /// return name of values of type token_type (only used for errors)\n\n static std::string token_type_name(const token_type t)\n\n {\n\n switch (t)\n\n {\n\n case token_type::uninitialized:\n\n return \"<uninitialized>\";\n\n case token_type::literal_true:\n\n return \"true literal\";\n\n case token_type::literal_false:\n\n return \"false literal\";\n\n case token_type::literal_null:\n\n return \"null literal\";\n\n case token_type::value_string:\n", "file_path": "src/json.hpp", "rank": 79, "score": 16.071371428860495 }, { "content": " {\n\n last_token = m_lexer.scan();\n\n return last_token;\n\n }\n\n\n\n void expect(typename lexer::token_type t) const\n\n {\n\n if (t != last_token)\n\n {\n\n std::string error_msg = \"parse error - unexpected \";\n\n error_msg += (last_token == lexer::token_type::parse_error ? (\"'\" + m_lexer.get_token_string() +\n\n \"'\") :\n\n lexer::token_type_name(last_token));\n\n error_msg += \"; expected \" + lexer::token_type_name(t);\n\n JSON_THROW(std::invalid_argument(error_msg));\n\n }\n\n }\n\n\n\n void unexpect(typename lexer::token_type t) const\n\n {\n", "file_path": "src/json.hpp", "rank": 80, "score": 15.710162163432532 }, { "content": " using reference = typename std::conditional<std::is_const<U>::value,\n\n typename basic_json::const_reference,\n\n typename basic_json::reference>::type;\n\n /// the category of the iterator\n\n using iterator_category = std::bidirectional_iterator_tag;\n\n\n\n /// default constructor\n\n iter_impl() = default;\n\n\n\n /*!\n\n @brief constructor for a given JSON instance\n\n @param[in] object pointer to a JSON object for this iterator\n\n @pre object != nullptr\n\n @post The iterator is initialized; i.e. `m_object != nullptr`.\n\n */\n\n explicit iter_impl(pointer object) noexcept\n\n : m_object(object)\n\n {\n\n assert(m_object != nullptr);\n\n\n", "file_path": "src/json.hpp", "rank": 81, "score": 15.662468370846973 }, { "content": " msgJson[\"best_particle_sense_y\"] = pf.getSenseY(best_particle);\n\n\n\n auto msg = \"42[\\\"best_particle\\\",\" + msgJson.dump() + \"]\";\n\n // std::cout << msg << std::endl;\n\n ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);\n\n\t \n\n }\n\n } else {\n\n std::string msg = \"42[\\\"manual\\\",{}]\";\n\n ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);\n\n }\n\n }\n\n\n\n });\n\n\n\n // We don't need this since we're not using HTTP but if it's removed the program\n\n // doesn't compile :-(\n\n h.onHttpRequest([](uWS::HttpResponse *res, uWS::HttpRequest req, char *data, size_t, size_t) {\n\n const std::string s = \"<h1>Hello world!</h1>\";\n\n if (req.getUrl().valueLength == 1)\n", "file_path": "src/main.cpp", "rank": 82, "score": 15.57656743193241 }, { "content": " found) or `1` (@a key was found).\n\n\n\n @post References and iterators to the erased elements are invalidated.\n\n Other references and iterators are not affected.\n\n\n\n @throw std::domain_error when called on a type other than JSON object;\n\n example: `\"cannot use erase() with null\"`\n\n\n\n @complexity `log(size()) + count(key)`\n\n\n\n @liveexample{The example shows the effect of `erase()`.,erase__key_type}\n\n\n\n @sa @ref erase(IteratorType) -- removes the element at a given position\n\n @sa @ref erase(IteratorType, IteratorType) -- removes the elements in\n\n the given range\n\n @sa @ref erase(const size_type) -- removes the element from an array at\n\n the given index\n\n\n\n @since version 1.0.0\n\n */\n", "file_path": "src/json.hpp", "rank": 83, "score": 15.452489326921242 }, { "content": " std::is_pointer<PointerType>::value and\n\n std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0>\n\n constexpr const PointerType get_ptr() const noexcept\n\n {\n\n // get the type of the PointerType (remove pointer and const)\n\n using pointee_t = typename std::remove_const<typename\n\n std::remove_pointer<typename\n\n std::remove_const<PointerType>::type>::type>::type;\n\n // make sure the type matches the allowed types\n\n static_assert(\n\n std::is_same<object_t, pointee_t>::value\n\n or std::is_same<array_t, pointee_t>::value\n\n or std::is_same<string_t, pointee_t>::value\n\n or std::is_same<boolean_t, pointee_t>::value\n\n or std::is_same<number_integer_t, pointee_t>::value\n\n or std::is_same<number_unsigned_t, pointee_t>::value\n\n or std::is_same<number_float_t, pointee_t>::value\n\n , \"incompatible pointer type\");\n\n\n\n // delegate the call to get_impl_ptr<>() const\n", "file_path": "src/json.hpp", "rank": 84, "score": 15.406288175123063 }, { "content": "\n\n switch (m_object->m_type)\n\n {\n\n case basic_json::value_t::object:\n\n {\n\n JSON_THROW(std::domain_error(\"cannot use offsets with object iterators\"));\n\n }\n\n\n\n case basic_json::value_t::array:\n\n {\n\n return m_it.array_iterator - other.m_it.array_iterator;\n\n }\n\n\n\n default:\n\n {\n\n return m_it.primitive_iterator - other.m_it.primitive_iterator;\n\n }\n\n }\n\n }\n\n\n", "file_path": "src/json.hpp", "rank": 85, "score": 15.267871369578735 }, { "content": "\n\n case 0xfb: // Double-Precision Float (eight-byte IEEE 754)\n\n {\n\n // copy bytes in reverse order into the double variable\n\n double res;\n\n for (size_t byte = 0; byte < sizeof(double); ++byte)\n\n {\n\n reinterpret_cast<uint8_t*>(&res)[sizeof(double) - byte - 1] = v.at(current_idx + 1 + byte);\n\n }\n\n idx += sizeof(double); // skip content bytes\n\n return res;\n\n }\n\n\n\n default: // anything else (0xFF is handled inside the other types)\n\n {\n\n JSON_THROW(std::invalid_argument(\"error parsing a CBOR @ \" + std::to_string(current_idx) + \": \" + std::to_string(static_cast<int>(v[current_idx]))));\n\n }\n\n }\n\n }\n\n\n", "file_path": "src/json.hpp", "rank": 86, "score": 14.9200086644592 }, { "content": " for (size_t i = 0; i < len; ++i)\n\n {\n\n std::string key = from_msgpack_internal(v, idx);\n\n result[key] = from_msgpack_internal(v, idx);\n\n }\n\n return result;\n\n }\n\n\n\n default:\n\n {\n\n JSON_THROW(std::invalid_argument(\"error parsing a msgpack @ \" + std::to_string(current_idx) + \": \" + std::to_string(static_cast<int>(v[current_idx]))));\n\n }\n\n }\n\n }\n\n }\n\n\n\n /*!\n\n @brief create a JSON value from a given CBOR vector\n\n\n\n @param[in] v CBOR serialization\n", "file_path": "src/json.hpp", "rank": 87, "score": 14.903417684327536 }, { "content": " */\n\n template<class IteratorType, typename std::enable_if<\n\n std::is_same<IteratorType, typename basic_json_t::iterator>::value or\n\n std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type\n\n = 0>\n\n IteratorType erase(IteratorType pos)\n\n {\n\n // make sure iterator fits the current value\n\n if (this != pos.m_object)\n\n {\n\n JSON_THROW(std::domain_error(\"iterator does not fit current value\"));\n\n }\n\n\n\n IteratorType result = end();\n\n\n\n switch (m_type)\n\n {\n\n case value_t::boolean:\n\n case value_t::number_float:\n\n case value_t::number_integer:\n", "file_path": "src/json.hpp", "rank": 88, "score": 14.884627438135386 }, { "content": " @param[in] first begin of the range to parse (included)\n\n @param[in] last end of the range to parse (excluded)\n\n @param[in] cb a parser callback function of type @ref parser_callback_t\n\n which is used to control the deserialization by filtering unwanted values\n\n (optional)\n\n\n\n @return result of the deserialization\n\n\n\n @complexity Linear in the length of the input. The parser is a predictive\n\n LL(1) parser. The complexity can be higher if the parser callback function\n\n @a cb has a super-linear complexity.\n\n\n\n @note A UTF-8 byte order mark is silently ignored.\n\n\n\n @liveexample{The example below demonstrates the `parse()` function reading\n\n from an iterator range.,parse__iteratortype__parser_callback_t}\n\n\n\n @since version 2.0.3\n\n */\n\n template<class IteratorType, typename std::enable_if<\n", "file_path": "src/json.hpp", "rank": 89, "score": 14.843216359266266 }, { "content": "\n\n /*!\n\n @brief exchanges the values\n\n\n\n Exchanges the contents of a JSON array with those of @a other. Does not\n\n invoke any move, copy, or swap operations on individual elements. All\n\n iterators and references remain valid. The past-the-end iterator is\n\n invalidated.\n\n\n\n @param[in,out] other array to exchange the contents with\n\n\n\n @throw std::domain_error when JSON value is not an array; example:\n\n `\"cannot use swap() with string\"`\n\n\n\n @complexity Constant.\n\n\n\n @liveexample{The example below shows how arrays can be swapped with\n\n `swap()`.,swap__array_t}\n\n\n\n @since version 1.0.0\n", "file_path": "src/json.hpp", "rank": 90, "score": 14.831295815561322 }, { "content": " */\n\n typename object_t::key_type key() const\n\n {\n\n assert(m_object != nullptr);\n\n\n\n if (m_object->is_object())\n\n {\n\n return m_it.object_iterator->first;\n\n }\n\n\n\n JSON_THROW(std::domain_error(\"cannot use key() for non-object iterators\"));\n\n }\n\n\n\n /*!\n\n @brief return the value of an iterator\n\n @pre The iterator is initialized; i.e. `m_object != nullptr`.\n\n */\n\n reference value() const\n\n {\n\n return operator*();\n", "file_path": "src/json.hpp", "rank": 91, "score": 14.821858783618428 }, { "content": " last.m_it.object_iterator);\n\n break;\n\n }\n\n\n\n case value_t::array:\n\n {\n\n m_value.array = create<array_t>(first.m_it.array_iterator,\n\n last.m_it.array_iterator);\n\n break;\n\n }\n\n\n\n default:\n\n {\n\n JSON_THROW(std::domain_error(\"cannot use construct with iterators from \" + first.m_object->type_name()));\n\n }\n\n }\n\n\n\n assert_invariant();\n\n }\n\n\n", "file_path": "src/json.hpp", "rank": 92, "score": 14.821858783618428 }, { "content": " `\"iterator does not fit current value\"`\n\n\n\n @return iterator pointing to the first element inserted, or @a pos if\n\n `ilist` is empty\n\n\n\n @complexity Linear in `ilist.size()` plus linear in the distance between\n\n @a pos and end of the container.\n\n\n\n @liveexample{The example shows how `insert()` is used.,insert__ilist}\n\n\n\n @since version 1.0.0\n\n */\n\n iterator insert(const_iterator pos, std::initializer_list<basic_json> ilist)\n\n {\n\n // insert only works for arrays\n\n if (not is_array())\n\n {\n\n JSON_THROW(std::domain_error(\"cannot use insert() with \" + type_name()));\n\n }\n\n\n", "file_path": "src/json.hpp", "rank": 93, "score": 14.765456659167151 }, { "content": "\n\n case value_t::object:\n\n {\n\n result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);\n\n break;\n\n }\n\n\n\n case value_t::array:\n\n {\n\n result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);\n\n break;\n\n }\n\n\n\n default:\n\n {\n\n JSON_THROW(std::domain_error(\"cannot use erase() with \" + type_name()));\n\n }\n\n }\n\n\n\n return result;\n", "file_path": "src/json.hpp", "rank": 94, "score": 14.700532462291637 }, { "content": "\n\n @param[in] key key of the element to access\n\n\n\n @return const reference to the element at key @a key\n\n\n\n @throw std::domain_error if the JSON value is not an object; example:\n\n `\"cannot use at() with boolean\"`\n\n @throw std::out_of_range if the key @a key is is not stored in the object;\n\n that is, `find(key) == end()`; example: `\"key \"the fast\" not found\"`\n\n\n\n @complexity Logarithmic in the size of the container.\n\n\n\n @liveexample{The example below shows how object elements can be read using\n\n `at()`.,at__object_t_key_type_const}\n\n\n\n @sa @ref operator[](const typename object_t::key_type&) for unchecked\n\n access by reference\n\n @sa @ref value() for access by value with a default value\n\n\n\n @since version 1.0.0\n", "file_path": "src/json.hpp", "rank": 95, "score": 14.590997921649405 }, { "content": " JSON_THROW(\n\n std::domain_error(\"type must be number, but is \" + j.type_name()));\n\n }\n\n }\n\n}\n\n\n\ntemplate<typename BasicJsonType>\n\nvoid from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)\n\n{\n\n if (not j.is_boolean())\n\n {\n\n JSON_THROW(std::domain_error(\"type must be boolean, but is \" + j.type_name()));\n\n }\n\n b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();\n\n}\n\n\n\ntemplate<typename BasicJsonType>\n\nvoid from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)\n\n{\n\n if (not j.is_string())\n", "file_path": "src/json.hpp", "rank": 96, "score": 14.586475075418882 }, { "content": " /*!\n\n @brief access to successor\n\n @pre The iterator is initialized; i.e. `m_object != nullptr`.\n\n */\n\n reference operator[](difference_type n) const\n\n {\n\n assert(m_object != nullptr);\n\n\n\n switch (m_object->m_type)\n\n {\n\n case basic_json::value_t::object:\n\n {\n\n JSON_THROW(std::domain_error(\"cannot use operator[] for object iterators\"));\n\n }\n\n\n\n case basic_json::value_t::array:\n\n {\n\n return *std::next(m_it.array_iterator, n);\n\n }\n\n\n", "file_path": "src/json.hpp", "rank": 97, "score": 14.579658139747153 }, { "content": " ambiguities as these types implicitly convert to `std::string`.\n\n\n\n @return copy of the JSON value, converted to type @a ValueType\n\n\n\n @throw std::domain_error in case passed type @a ValueType is incompatible\n\n to JSON, thrown by @ref get() const\n\n\n\n @complexity Linear in the size of the JSON value.\n\n\n\n @liveexample{The example below shows several conversions from JSON values\n\n to other types. There a few things to note: (1) Floating-point numbers can\n\n be converted to integers\\, (2) A JSON array can be converted to a standard\n\n `std::vector<short>`\\, (3) A JSON object can be converted to C++\n\n associative containers such as `std::unordered_map<std::string\\,\n\n json>`.,operator__ValueType}\n\n\n\n @since version 1.0.0\n\n */\n\n template < typename ValueType, typename std::enable_if <\n\n not std::is_pointer<ValueType>::value and\n", "file_path": "src/json.hpp", "rank": 98, "score": 14.574789437903608 }, { "content": "void to_json(BasicJsonType& j, T b) noexcept\n\n{\n\n external_constructor<value_t::boolean>::construct(j, b);\n\n}\n\n\n\ntemplate<typename BasicJsonType, typename CompatibleString,\n\n enable_if_t<std::is_constructible<typename BasicJsonType::string_t,\n\n CompatibleString>::value, int> = 0>\n\nvoid to_json(BasicJsonType& j, const CompatibleString& s)\n\n{\n\n external_constructor<value_t::string>::construct(j, s);\n\n}\n\n\n\ntemplate<typename BasicJsonType, typename FloatType,\n\n enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>\n\nvoid to_json(BasicJsonType& j, FloatType val) noexcept\n\n{\n\n external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));\n\n}\n\n\n", "file_path": "src/json.hpp", "rank": 99, "score": 14.553706404710423 } ]
C++
source/grid/setup_grid_NG_MPI.cpp
jfbucas/PION
e0a66aa301e4d94d581ba4df078f1a3b82faab99
#include "defines/functionality_flags.h" #include "defines/testing_flags.h" #include "tools/reporting.h" #include "tools/command_line_interface.h" #include "raytracing/raytracer_SC.h" #include "grid/setup_grid_NG_MPI.h" #include "grid/uniform_grid.h" #include "grid/uniform_grid_pllel.h" #include "spatial_solvers/solver_eqn_hydro_adi.h" #include "spatial_solvers/solver_eqn_mhd_adi.h" #include "microphysics/microphysics_base.h" #include "microphysics/mp_only_cooling.h" #include "microphysics/MPv3.h" #include "microphysics/MPv5.h" #include "microphysics/MPv6.h" #include "microphysics/MPv7.h" #include "microphysics/MPv8.h" #ifdef FITS #include "dataIO/dataio_fits_MPI.h" #endif #ifndef EXCLUDE_HD_MODULE #include "microphysics/MPv9.h" #endif #ifdef CODE_EXT_HHE #include "future/mpv9_HHe.h" #endif #include <iostream> #include <sstream> #include <fstream> #include <string> #include <sys/time.h> #include <time.h> #include <climits> using namespace std; setup_grid_NG_MPI::setup_grid_NG_MPI() { #ifdef TESTING cout <<"setup_grid_NG_MPI constructor called.\n"; #endif return; } setup_grid_NG_MPI::~setup_grid_NG_MPI() { #ifdef TESTING cout <<"setup_grid_NG_MPI destructor called.\n"; #endif return; } void setup_grid_NG_MPI::setup_NG_grid_levels( class SimParams &SimPM ) { int err=0; setup_NG_grid::setup_NG_grid_levels(SimPM); int myrank=-1, nproc=-1; COMM->get_rank_nproc(&myrank,&nproc); for (int l=0;l<SimPM.grid_nlevels;l++) { SimPM.levels[l].MCMD.set_myrank(myrank); SimPM.levels[l].MCMD.set_nproc(nproc); err = SimPM.levels[l].MCMD.decomposeDomain(SimPM, SimPM.levels[l]); rep.errorTest("PLLEL Init():Decompose Domain!",0,err); SimPM.levels[l].MCMD.ReadSingleFile = true; } for (int l=0;l<SimPM.grid_nlevels;l++) { SimPM.levels[l].MCMD.set_NG_hierarchy(SimPM,l); } return; } int setup_grid_NG_MPI::setup_grid( vector<class GridBaseClass *> &grid, class SimParams &SimPM ) { cout <<"(pion) Setting up MPI NG grid\n"; if (SimPM.ndim <1 || SimPM.ndim>3) rep.error("Only know 1D,2D,3D methods!",SimPM.ndim); #ifdef TESTING cout <<"Setting number of boundary cells == spatial OOA: "; cout <<SimPM.spOOA<<"\n"; #endif if (SimPM.spOOA==OA2) {SimPM.Nbc = 6; SimPM.Nbc_DD = 4;} else if (SimPM.spOOA==OA1) {SimPM.Nbc = 4; SimPM.Nbc_DD = 2;} else rep.error("unhandles spatial order of accuracy",SimPM.spOOA); setup_cell_extra_data(SimPM); double dx=(SimPM.Xmax[XX]-SimPM.Xmin[XX])/SimPM.NG[XX]; CI.set_nlevels(dx,SimPM.grid_nlevels); CI.set_ndim(SimPM.ndim); CI.set_nvar(SimPM.nvar); CI.set_xmin(SimPM.Xmin); #ifdef TESTING cout <<"(setup_grid_NG_MPI::setup_grid) Setting up grid...\n"; #endif for (int l=0; l<SimPM.grid_nlevels; l++) { #ifdef TESTING cout <<"Init: level="<< l <<", &grid="<< &(grid[l]); cout <<", and grid="<< grid[l] <<"\n"; #endif if (grid[l]) rep.error("Grid already set up!",grid[l]); if (SimPM.coord_sys==COORD_CRT) grid[l] = new UniformGridParallel ( SimPM.ndim, SimPM.nvar, SimPM.eqntype, SimPM.Nbc, SimPM.levels[l].MCMD.LocalXmin, SimPM.levels[l].MCMD.LocalXmax, SimPM.levels[l].MCMD.LocalNG, SimPM.levels[l].Xmin, SimPM.levels[l].Xmax, SimPM.Xmin, SimPM.Xmax); else if (SimPM.coord_sys==COORD_CYL) grid[l] = new uniform_grid_cyl_parallel ( SimPM.ndim, SimPM.nvar, SimPM.eqntype, SimPM.Nbc, SimPM.levels[l].MCMD.LocalXmin, SimPM.levels[l].MCMD.LocalXmax, SimPM.levels[l].MCMD.LocalNG, SimPM.levels[l].Xmin, SimPM.levels[l].Xmax, SimPM.Xmin, SimPM.Xmax); else if (SimPM.coord_sys==COORD_SPH) grid[l] = new uniform_grid_sph_parallel ( SimPM.ndim, SimPM.nvar, SimPM.eqntype, SimPM.Nbc, SimPM.levels[l].MCMD.LocalXmin, SimPM.levels[l].MCMD.LocalXmax, SimPM.levels[l].MCMD.LocalNG, SimPM.levels[l].Xmin, SimPM.levels[l].Xmax, SimPM.Xmin, SimPM.Xmax); else rep.error("Bad Geometry in setup_grid()",SimPM.coord_sys); if (grid[l]==0) rep.error("(setup_grid_NG_MPI::setup_grid)", grid[l]); #ifdef TESTING cout <<"(setup_grid_NG_MPI::setup_grid) Done. &grid="; cout << &(grid[l])<<", and grid="<<grid[l]<<"\n"; cout <<"DX = "<<(grid[l])->DX()<<"\n"; #endif } for (int l=0;l<SimPM.grid_nlevels;l++) { SimPM.levels[l].grid = grid[l]; if (l==0) { SimPM.levels[l].parent = 0; if (SimPM.grid_nlevels>1) SimPM.levels[l].child = grid[l+1]; } else if (l==SimPM.grid_nlevels-1) { if (SimPM.grid_nlevels>1) SimPM.levels[l].parent = grid[l-1]; SimPM.levels[l].child = 0; } else { SimPM.levels[l].parent = grid[l-1]; SimPM.levels[l].child = grid[l+1]; } } set_leaf_cells(grid,SimPM); setup_flux_vectors(SimPM.grid_nlevels); for (int l=0;l<SimPM.grid_nlevels;l++) { if (l!=0) setup_flux_send(SimPM,grid[l],l-1); if (l!=SimPM.grid_nlevels-1) setup_flux_recv(SimPM,grid[l],l+1); } return(0); } int setup_grid_NG_MPI::setup_raytracing( class SimParams &SimPM, vector<class GridBaseClass *> &grid ) { if (!SimPM.EP.raytracing) { return 0; } int err = 0; for (int l=0;l<SimPM.grid_nlevels;l++) { #ifdef TESTING cout <<"setting up raytracing for grid level "<<l<<"\n"; #endif err += setup_fixed_grid_pllel::setup_raytracing(SimPM,grid[l]); rep.errorTest("setup_grid_NG_MPI::setup_raytracing()",0,err); } #ifdef TESTING cout <<"NG-MPI setting up evolving RT sources from setup_raytracing.\n"; #endif err += setup_evolving_RT_sources(SimPM); rep.errorTest("setup_grid_NG_MPI::setup_evolving_RT_sources()",0,err); for (int l=0;l<SimPM.grid_nlevels;l++) { #ifdef TESTING cout <<"NG-MPI l="<<l<<": updating evolving RT sources from setup_raytracing.\n"; #endif err += update_evolving_RT_sources(SimPM,SimPM.levels[l].simtime,grid[l]->RT); rep.errorTest("setup_grid_NG_MPI::update_evolving_RT_sources()",0,err); } return 0; } int setup_grid_NG_MPI::boundary_conditions( class SimParams &par, vector<class GridBaseClass *> &grid ) { #ifdef TESTING cout <<"Setting up BCs in MPI-NG Grid with Nbc="<<par.Nbc<<"\n"; #endif int err = setup_NG_grid::boundary_conditions(par,grid); rep.errorTest("setup_grid_NG_MPI::boundary_conditions",0,err); #ifdef TESTING cout <<"(setup_grid_NG_MPI::boundary_conditions) Done.\n"; #endif return 0; } int setup_grid_NG_MPI::setup_boundary_structs( class SimParams &par, class GridBaseClass *grid, const int l ) { #ifdef TESTING cout <<"Set BC types...\n"; #endif int err = 0; #ifdef TESTING cout <<"setting up serial boundary structs\n"; #endif err = setup_fixed_grid::setup_boundary_structs(par,grid,l); rep.errorTest("png::setup_boundary_structs fixed grid",0,err); #ifdef SKIP_C2F_BC if (1==0) { #endif if (l>0) { #ifdef TESTING cout <<"replacing external BCs with C2F as needed\n"; #endif for (int i=0; i<par.ndim; i++) { if (!pconst.equalD(par.levels[l-1].Xmin[i], par.levels[l].Xmin[i]) && pconst.equalD(par.levels[l].Xmin[i], grid->Xmin(static_cast<axes>(i))) ) { #ifdef TESTING cout <<"reassigning neg. bc for axis "<<i<<" to COARSE_TO_FINE\n"; #endif grid->BC_bd[2*i]->itype = COARSE_TO_FINE_RECV; grid->BC_bd[2*i]->type = "COARSE_TO_FINE_RECV"; } if (!pconst.equalD(par.levels[l-1].Xmax[i], par.levels[l].Xmax[i]) && pconst.equalD(par.levels[l].Xmax[i], grid->Xmax(static_cast<axes>(i))) ) { #ifdef TESTING cout <<"reassigning pos. bc for axis "<<i<<" to COARSE_TO_FINE\n"; #endif grid->BC_bd[2*i+1]->itype = COARSE_TO_FINE_RECV; grid->BC_bd[2*i+1]->type = "COARSE_TO_FINE_RECV"; } } } #ifdef SKIP_C2F_BC } #endif if (l < par.grid_nlevels-1) { #ifdef SKIP_F2C_BC if (1==0) { #endif #ifdef TESTING cout <<"Adding FINE_TO_COARSE_RECV boundary for level "; cout <<l<<", current # boundaries: "<<grid->BC_bd.size() <<"\n"; #endif struct boundary_data *bd = new boundary_data; bd->itype = FINE_TO_COARSE_RECV; bd->type = "FINE_TO_COARSE_RECV"; bd->dir = NO; bd->ondir = NO; bd->refval=0; grid->BC_bd.push_back(bd); #ifdef SKIP_F2C_BC } #endif #ifdef SKIP_C2F_BC if (1==0) { #endif #ifdef TESTING cout <<"Adding COARSE_TO_FINE_SEND boundary for level "; cout <<l<<", current # boundaries: "<<grid->BC_bd.size() <<"\n"; #endif struct boundary_data *bd2 = new boundary_data; bd2->itype = COARSE_TO_FINE_SEND; bd2->type = "COARSE_TO_FINE_SEND"; bd2->dir = NO; bd2->ondir = NO; bd2->refval=0; grid->BC_bd.push_back(bd2); #ifdef SKIP_C2F_BC } #endif } #ifdef SKIP_F2C_BC if (1==0) { #endif if (l>0) { #ifdef TESTING cout <<"Adding FINE_TO_COARSE_SEND boundary for level "; cout <<l<<", current # boundaries: "<<grid->BC_bd.size() <<"\n"; #endif struct boundary_data *bd = new boundary_data; bd->itype = FINE_TO_COARSE_SEND; bd->type = "FINE_TO_COARSE_SEND"; bd->dir = NO; bd->ondir = NO; bd->refval=0; grid->BC_bd.push_back(bd); } #ifdef SKIP_F2C_BC } #endif #ifdef TESTING cout <<"BC structs set up.\n"; for (unsigned int v=0; v<grid->BC_bd.size(); v++) { cout<<"i="<<v<<", BC type= "<<grid->BC_bd[v]->type; cout <<", BC itype= "<<grid->BC_bd[v]->itype<<"\n"; } #endif #ifdef TESTING cout <<"calling pll fixed grid setup function.\n"; #endif err = setup_fixed_grid_pllel::setup_boundary_structs(par,grid,l); rep.errorTest("png::setup_boundary_structs pll fixed grid",0,err); #ifdef TESTING cout <<"BC structs set up.\n"; for (unsigned int v=0; v<grid->BC_bd.size(); v++) { cout<<"i="<<v<<", BC type= "<<grid->BC_bd[v]->type<<"\n"; } #endif return 0; } void setup_grid_NG_MPI::setup_dataio_class( class SimParams &par, const int typeOfFile ) { switch (typeOfFile) { #ifdef SILO case 5: dataio = new dataio_silo_utility (par, "DOUBLE", &(par.levels[0].MCMD)); break; #endif default: rep.error("sim_control_NG_MPI::Init unhandled filetype",typeOfFile); } return; }
#include "defines/functionality_flags.h" #include "defines/testing_flags.h" #include "tools/reporting.h" #include "tools/command_line_interface.h" #include "raytracing/raytracer_SC.h" #include "grid/setup_grid_NG_MPI.h" #include "grid/uniform_grid.h" #include "grid/uniform_grid_pllel.h" #include "spatial_solvers/solver_eqn_hydro_adi.h" #include "spatial_solvers/solver_eqn_mhd_adi.h" #include "microphysics/microphysics_base.h" #include "microphysics/mp_only_cooling.h" #include "microphysics/MPv3.h" #include "microphysics/MPv5.h" #include "microphysics/MPv6.h" #include "microphysics/MPv7.h" #include "microphysics/MPv8.h" #ifdef FITS #include "dataIO/dataio_fits_MPI.h" #endif #ifndef EXCLUDE_HD_MODULE #include "microphysics/MPv9.h" #endif #ifdef CODE_EXT_HHE #include "future/mpv9_HHe.h" #endif #include <iostream> #include <sstream> #include <fstream> #include <string> #include <sys/time.h> #include <time.h> #include <climits> using namespace std; setup_grid_NG_MPI::setup_grid_NG_MPI() { #ifdef TESTING cout <<"setup_grid_NG_MPI constructor called.\n"; #endif return; } setup_grid_NG_MPI::~setup_grid_NG_MPI() { #ifdef TESTING cout <<"setup_grid_NG_MPI destructor called.\n"; #endif return; } void setup_grid_NG_MPI::setup_NG_grid_levels( class SimParams &SimPM ) { int err=0; setup_NG_grid::setup_NG_grid_levels(SimPM); int myrank=-1, nproc=-1; COMM->get_rank_nproc(&myrank,&nproc); for (int l=0;l<SimPM.grid_nlevels;l++) { SimPM.levels[l].MCMD.set_myrank(myrank); SimPM.levels[l].MCMD.set_nproc(nproc); err = SimPM.levels[l].MCMD.decomposeDomain(SimPM, SimPM.levels[l]); rep.errorTest("PLLEL Init():Decompose Domain!",0,err); SimPM.levels[l].MCMD.ReadSingleFile = true; } for (int l=0;l<SimPM.grid_nlevels;l++) { SimPM.levels[l].MCMD.set_NG_hierarchy(SimPM,l); } return; } int setup_grid_NG_MPI::setup_grid( vector<class GridBaseClass *> &grid, class SimParams &SimPM ) { cout <<"(pion) Setting up MPI NG grid\n"; if (SimPM.ndim <1 || SimPM.ndim>3) rep.error("Only know 1D,2D,3D methods!",SimPM.ndim); #ifdef TESTING cout <<"Setting number of boundary cells == spatial OOA: "; cout <<SimPM.spOOA<<"\n"; #endif
setup_cell_extra_data(SimPM); double dx=(SimPM.Xmax[XX]-SimPM.Xmin[XX])/SimPM.NG[XX]; CI.set_nlevels(dx,SimPM.grid_nlevels); CI.set_ndim(SimPM.ndim); CI.set_nvar(SimPM.nvar); CI.set_xmin(SimPM.Xmin); #ifdef TESTING cout <<"(setup_grid_NG_MPI::setup_grid) Setting up grid...\n"; #endif for (int l=0; l<SimPM.grid_nlevels; l++) { #ifdef TESTING cout <<"Init: level="<< l <<", &grid="<< &(grid[l]); cout <<", and grid="<< grid[l] <<"\n"; #endif if (grid[l]) rep.error("Grid already set up!",grid[l]); if (SimPM.coord_sys==COORD_CRT) grid[l] = new UniformGridParallel ( SimPM.ndim, SimPM.nvar, SimPM.eqntype, SimPM.Nbc, SimPM.levels[l].MCMD.LocalXmin, SimPM.levels[l].MCMD.LocalXmax, SimPM.levels[l].MCMD.LocalNG, SimPM.levels[l].Xmin, SimPM.levels[l].Xmax, SimPM.Xmin, SimPM.Xmax); else if (SimPM.coord_sys==COORD_CYL) grid[l] = new uniform_grid_cyl_parallel ( SimPM.ndim, SimPM.nvar, SimPM.eqntype, SimPM.Nbc, SimPM.levels[l].MCMD.LocalXmin, SimPM.levels[l].MCMD.LocalXmax, SimPM.levels[l].MCMD.LocalNG, SimPM.levels[l].Xmin, SimPM.levels[l].Xmax, SimPM.Xmin, SimPM.Xmax); else if (SimPM.coord_sys==COORD_SPH) grid[l] = new uniform_grid_sph_parallel ( SimPM.ndim, SimPM.nvar, SimPM.eqntype, SimPM.Nbc, SimPM.levels[l].MCMD.LocalXmin, SimPM.levels[l].MCMD.LocalXmax, SimPM.levels[l].MCMD.LocalNG, SimPM.levels[l].Xmin, SimPM.levels[l].Xmax, SimPM.Xmin, SimPM.Xmax); else rep.error("Bad Geometry in setup_grid()",SimPM.coord_sys); if (grid[l]==0) rep.error("(setup_grid_NG_MPI::setup_grid)", grid[l]); #ifdef TESTING cout <<"(setup_grid_NG_MPI::setup_grid) Done. &grid="; cout << &(grid[l])<<", and grid="<<grid[l]<<"\n"; cout <<"DX = "<<(grid[l])->DX()<<"\n"; #endif } for (int l=0;l<SimPM.grid_nlevels;l++) { SimPM.levels[l].grid = grid[l]; if (l==0) { SimPM.levels[l].parent = 0; if (SimPM.grid_nlevels>1) SimPM.levels[l].child = grid[l+1]; } else if (l==SimPM.grid_nlevels-1) { if (SimPM.grid_nlevels>1) SimPM.levels[l].parent = grid[l-1]; SimPM.levels[l].child = 0; } else { SimPM.levels[l].parent = grid[l-1]; SimPM.levels[l].child = grid[l+1]; } } set_leaf_cells(grid,SimPM); setup_flux_vectors(SimPM.grid_nlevels); for (int l=0;l<SimPM.grid_nlevels;l++) { if (l!=0) setup_flux_send(SimPM,grid[l],l-1); if (l!=SimPM.grid_nlevels-1) setup_flux_recv(SimPM,grid[l],l+1); } return(0); } int setup_grid_NG_MPI::setup_raytracing( class SimParams &SimPM, vector<class GridBaseClass *> &grid ) { if (!SimPM.EP.raytracing) { return 0; } int err = 0; for (int l=0;l<SimPM.grid_nlevels;l++) { #ifdef TESTING cout <<"setting up raytracing for grid level "<<l<<"\n"; #endif err += setup_fixed_grid_pllel::setup_raytracing(SimPM,grid[l]); rep.errorTest("setup_grid_NG_MPI::setup_raytracing()",0,err); } #ifdef TESTING cout <<"NG-MPI setting up evolving RT sources from setup_raytracing.\n"; #endif err += setup_evolving_RT_sources(SimPM); rep.errorTest("setup_grid_NG_MPI::setup_evolving_RT_sources()",0,err); for (int l=0;l<SimPM.grid_nlevels;l++) { #ifdef TESTING cout <<"NG-MPI l="<<l<<": updating evolving RT sources from setup_raytracing.\n"; #endif err += update_evolving_RT_sources(SimPM,SimPM.levels[l].simtime,grid[l]->RT); rep.errorTest("setup_grid_NG_MPI::update_evolving_RT_sources()",0,err); } return 0; } int setup_grid_NG_MPI::boundary_conditions( class SimParams &par, vector<class GridBaseClass *> &grid ) { #ifdef TESTING cout <<"Setting up BCs in MPI-NG Grid with Nbc="<<par.Nbc<<"\n"; #endif int err = setup_NG_grid::boundary_conditions(par,grid); rep.errorTest("setup_grid_NG_MPI::boundary_conditions",0,err); #ifdef TESTING cout <<"(setup_grid_NG_MPI::boundary_conditions) Done.\n"; #endif return 0; } int setup_grid_NG_MPI::setup_boundary_structs( class SimParams &par, class GridBaseClass *grid, const int l ) { #ifdef TESTING cout <<"Set BC types...\n"; #endif int err = 0; #ifdef TESTING cout <<"setting up serial boundary structs\n"; #endif err = setup_fixed_grid::setup_boundary_structs(par,grid,l); rep.errorTest("png::setup_boundary_structs fixed grid",0,err); #ifdef SKIP_C2F_BC if (1==0) { #endif if (l>0) { #ifdef TESTING cout <<"replacing external BCs with C2F as needed\n"; #endif for (int i=0; i<par.ndim; i++) { if (!pconst.equalD(par.levels[l-1].Xmin[i], par.levels[l].Xmin[i]) && pconst.equalD(par.levels[l].Xmin[i], grid->Xmin(static_cast<axes>(i))) ) { #ifdef TESTING cout <<"reassigning neg. bc for axis "<<i<<" to COARSE_TO_FINE\n"; #endif grid->BC_bd[2*i]->itype = COARSE_TO_FINE_RECV; grid->BC_bd[2*i]->type = "COARSE_TO_FINE_RECV"; } if (!pconst.equalD(par.levels[l-1].Xmax[i], par.levels[l].Xmax[i]) && pconst.equalD(par.levels[l].Xmax[i], grid->Xmax(static_cast<axes>(i))) ) { #ifdef TESTING cout <<"reassigning pos. bc for axis "<<i<<" to COARSE_TO_FINE\n"; #endif grid->BC_bd[2*i+1]->itype = COARSE_TO_FINE_RECV; grid->BC_bd[2*i+1]->type = "COARSE_TO_FINE_RECV"; } } } #ifdef SKIP_C2F_BC } #endif if (l < par.grid_nlevels-1) { #ifdef SKIP_F2C_BC if (1==0) { #endif #ifdef TESTING cout <<"Adding FINE_TO_COARSE_RECV boundary for level "; cout <<l<<", current # boundaries: "<<grid->BC_bd.size() <<"\n"; #endif struct boundary_data *bd = new boundary_data; bd->itype = FINE_TO_COARSE_RECV; bd->type = "FINE_TO_COARSE_RECV"; bd->dir = NO; bd->ondir = NO; bd->refval=0; grid->BC_bd.push_back(bd); #ifdef SKIP_F2C_BC } #endif #ifdef SKIP_C2F_BC if (1==0) { #endif #ifdef TESTING cout <<"Adding COARSE_TO_FINE_SEND boundary for level "; cout <<l<<", current # boundaries: "<<grid->BC_bd.size() <<"\n"; #endif struct boundary_data *bd2 = new boundary_data; bd2->itype = COARSE_TO_FINE_SEND; bd2->type = "COARSE_TO_FINE_SEND"; bd2->dir = NO; bd2->ondir = NO; bd2->refval=0; grid->BC_bd.push_back(bd2); #ifdef SKIP_C2F_BC } #endif } #ifdef SKIP_F2C_BC if (1==0) { #endif if (l>0) { #ifdef TESTING cout <<"Adding FINE_TO_COARSE_SEND boundary for level "; cout <<l<<", current # boundaries: "<<grid->BC_bd.size() <<"\n"; #endif struct boundary_data *bd = new boundary_data; bd->itype = FINE_TO_COARSE_SEND; bd->type = "FINE_TO_COARSE_SEND"; bd->dir = NO; bd->ondir = NO; bd->refval=0; grid->BC_bd.push_back(bd); } #ifdef SKIP_F2C_BC } #endif #ifdef TESTING cout <<"BC structs set up.\n"; for (unsigned int v=0; v<grid->BC_bd.size(); v++) { cout<<"i="<<v<<", BC type= "<<grid->BC_bd[v]->type; cout <<", BC itype= "<<grid->BC_bd[v]->itype<<"\n"; } #endif #ifdef TESTING cout <<"calling pll fixed grid setup function.\n"; #endif err = setup_fixed_grid_pllel::setup_boundary_structs(par,grid,l); rep.errorTest("png::setup_boundary_structs pll fixed grid",0,err); #ifdef TESTING cout <<"BC structs set up.\n"; for (unsigned int v=0; v<grid->BC_bd.size(); v++) { cout<<"i="<<v<<", BC type= "<<grid->BC_bd[v]->type<<"\n"; } #endif return 0; } void setup_grid_NG_MPI::setup_dataio_class( class SimParams &par, const int typeOfFile ) { switch (typeOfFile) { #ifdef SILO case 5: dataio = new dataio_silo_utility (par, "DOUBLE", &(par.levels[0].MCMD)); break; #endif default: rep.error("sim_control_NG_MPI::Init unhandled filetype",typeOfFile); } return; }
if (SimPM.spOOA==OA2) {SimPM.Nbc = 6; SimPM.Nbc_DD = 4;} else if (SimPM.spOOA==OA1) {SimPM.Nbc = 4; SimPM.Nbc_DD = 2;} else rep.error("unhandles spatial order of accuracy",SimPM.spOOA);
if_condition
[ { "content": " // Else, make a vector of structs with a list of cells contained\n\n // in each coarse cell (2,4,or 8) of the parent grid. This grid\n\n // is (by design) entirely contained within the parent.\n\n class GridBaseClass *grid = par.levels[l].grid;\n\n int nc=1; // number of fine cells per coarse cell\n\n for (int i=0;i<par.ndim;i++) nc*=2;\n\n int nel = grid->Ncell()/nc; // number of coarse cells\n\n // initialise the \"avg\" vector to hold the average state.\n\n b->avg.resize(nel);\n\n for (int v=0;v<nel;v++) {\n\n b->avg[v].c.resize(nc);\n\n b->avg[v].avg_state = mem.myalloc(b->avg[v].avg_state,\n\n par.nvar+F2C_Nxd);\n\n }\n\n // add cells from this grid to the avg vectors.\n\n add_cells_to_avg(par.ndim,grid,nel,b->avg);\n\n#ifdef TEST_MPI_NG_F2C\n\n cout <<\"***F2C added \"<<nel<<\" avg cells to this grid\\n\";\n\n#endif\n\n \n\n } // if parent is not on a different MPI process\n\n\n\n return 0;\n\n}\n\n\n\n\n\n\n\n// ##################################################################\n\n// ##################################################################\n\n\n\n\n\n\n\nint NG_MPI_fine_to_coarse_bc::BC_update_FINE_TO_COARSE_SEND(\n", "file_path": "source/boundaries/NG_MPI_fine_to_coarse_boundaries.cpp", "rank": 0, "score": 382388.49594433844 }, { "content": " // else we have to send data to another MPI process:\n\n class GridBaseClass *grid = par.levels[l].grid;\n\n int nc = b->avg[0].c.size();\n\n int nel = b->avg.size();\n\n\n\n // data to send will be ordered as position,conserved-var,X-data\n\n // for each averaged cell. Position only needed for testing.\n\n pion_flt *data = 0;\n\n#ifdef NG_F2C_POS\n\n data = mem.myalloc(data,nel*(par.nvar+F2C_Nxd+par.ndim));\n\n#else\n\n data = mem.myalloc(data,nel*(par.nvar+F2C_Nxd));\n\n#endif\n\n\n\n\n\n // loop through avg vector and add cells and positions to\n\n // data array.\n\n int v=0;\n\n int nv = par.nvar + F2C_Nxd; // conserved vector and optical depths\n\n double cd[nv];\n\n size_t ct=0;\n", "file_path": "source/boundaries/NG_MPI_fine_to_coarse_boundaries.cpp", "rank": 1, "score": 382381.34668456507 }, { "content": " class GridBaseClass *grid = par.levels[l].grid;\n\n\n\n if (MCMD->get_myrank() == b->NGrecvC2F_parent) {\n\n#ifdef TEST_C2F\n\n cout <<\"my rank == parent rank, calling serial \";\n\n cout <<\"COARSE_TO_FINE\"<<endl;\n\n#endif\n\n NG_coarse_to_fine_bc::BC_update_COARSE_TO_FINE(\n\n par,solver,l,b,step);\n\n }\n\n else {\n\n#ifdef TEST_C2F\n\n cout <<\"my rank != parent rank, so updating \";\n\n cout <<\"COARSE_TO_FINE_RECV: \";\n\n cout <<\"me=\"<<MCMD->get_myrank();\n\n cout <<\", parent=\"<<b->NGrecvC2F_parent<<endl;\n\n#endif\n\n\n\n // receive data.\n\n string recv_id; int recv_tag=-1; int from_rank=-1;\n", "file_path": "source/boundaries/NG_MPI_coarse_to_fine_boundaries.cpp", "rank": 2, "score": 382375.04235603614 }, { "content": " class GridBaseClass *grid = par.levels[l].grid;\n\n\n\n int cl_ixmin[MAX_DIM], cl_ixmax[MAX_DIM];\n\n int fl_ixmin[MAX_DIM], fl_ixmax[MAX_DIM];\n\n int cg_ixmin[MAX_DIM], cg_ixmax[MAX_DIM];\n\n int fg_ixmin[MAX_DIM], fg_ixmax[MAX_DIM];\n\n\n\n CI.get_ipos_vec(par.levels[l-1].Xmin, cl_ixmin);\n\n CI.get_ipos_vec(par.levels[l-1].Xmax, cl_ixmax);\n\n CI.get_ipos_vec(par.levels[l].Xmin, fl_ixmin);\n\n CI.get_ipos_vec(par.levels[l].Xmax, fl_ixmax);\n\n for (int v=0;v<par.ndim;v++)\n\n fg_ixmin[v] = grid->iXmin(static_cast<axes>(v));\n\n for (int v=0;v<par.ndim;v++)\n\n fg_ixmax[v] = grid->iXmax(static_cast<axes>(v));\n\n\n\n // get data on parent grid, and neighbours of parent grid.\n\n struct cgrid pg;\n\n std::vector<struct cgrid> pgngb;\n\n MCMD->get_parent_grid_info(&pg);\n", "file_path": "source/boundaries/NG_MPI_coarse_to_fine_boundaries.cpp", "rank": 3, "score": 382375.0423560362 }, { "content": " class GridBaseClass *grid ///< pointer to grid.\n\n )\n\n{\n\n int err = 0;\n\n struct boundary_data *b;\n\n\n\n //\n\n // assign data for each boundary.\n\n //\n\n for (size_t i=0; i<grid->BC_bd.size(); i++) {\n\n#ifdef TEST_MPI_NG\n\n cout <<\"LEVEL \"<<level<<\": NG grid assign BCs: BC[\"<<i<<\"] starting.\\n\";\n\n cout.flush();\n\n#endif\n\n b = grid->BC_bd[i];\n\n switch (b->itype) {\n\n case PERIODIC:\n\n#ifdef TEST_MPI_NG\n\n cout <<\"LEVEL \"<<level<<\": NG_MPI_Assign: assigning bc \"<<i;\n\n cout <<\" with type \"<<b->type<<\"\\n\";\n", "file_path": "source/boundaries/assign_update_bcs_NG_MPI.cpp", "rank": 4, "score": 372311.6671761781 }, { "content": " class GridBaseClass *grid = par.levels[l].grid;\n", "file_path": "source/boundaries/NG_MPI_BC89flux.cpp", "rank": 5, "score": 372311.6671761781 }, { "content": " class GridBaseClass *grid, ///< pointer to grid.\n", "file_path": "source/boundaries/assign_update_bcs_NG_MPI.cpp", "rank": 6, "score": 372311.6671761781 }, { "content": " class GridBaseClass *, ///< pointer to grid.\n", "file_path": "source/boundaries/assign_update_bcs_NG_MPI.h", "rank": 7, "score": 369327.1247298592 }, { "content": " class GridBaseClass * ///< pointer to grid.\n\n );\n\n\n\n ///\n\n /// Runs through ghost boundary cells and does the appropriate\n\n /// time update on them.\n\n ///\n\n int TimeUpdateExternalBCs(\n", "file_path": "source/boundaries/assign_update_bcs_NG_MPI.h", "rank": 8, "score": 369327.1247298592 }, { "content": " class GridBaseClass *grid, ///< pointer to coarse-level grid\n", "file_path": "source/boundaries/NG_MPI_coarse_to_fine_boundaries.cpp", "rank": 9, "score": 369207.6626837434 }, { "content": " class GridBaseClass *grid, ///< pointer to coarse-level grid\n\n struct c2f *bdata, ///< pointer to list of cells\n\n int *ixmin, ///< child grid xmin (integer)\n\n int *ixmax, ///< child grid xmax (integer)\n\n const int lf, ///< level of fine grid.\n\n const int *fl_xmin, ///< level xmin of fine grid.\n\n const int *fl_xmax ///< level xmax of fine grid.\n\n )\n\n{\n\n#ifdef TEST_C2F\n\n rep.printVec(\"C2F Setup Send: ixmin\",ixmin,3);\n\n rep.printVec(\"C2F Setup Send: ixmax\",ixmax,3);\n\n#endif\n\n \n\n int bsize = grid->idx()*par.Nbc/2; // idx is >=2, Nbc is >=1.\n\n int n = 0;\n\n \n\n // define domain of boundary region\n\n int xn=0,xp=0,yn=0,yp=0,zn=0,zp=0;\n\n switch (bdata->dir) {\n", "file_path": "source/boundaries/NG_MPI_coarse_to_fine_boundaries.cpp", "rank": 10, "score": 369207.6626837434 }, { "content": " class GridBaseClass *grid, // pointer to finer grid.\n\n const int lm1 ///< level to send to\n\n )\n\n{\n\n#ifdef TEST_BC89FLUX\n\n cout <<\" NG_MPI_BC89flux::setup_flux_send() send to level=\";\n\n cout <<lm1<<\" from MY LEVEL l=\"<<lm1+1<<\"\\n\";\n\n#endif\n\n\n\n int err = NG_BC89flux::setup_flux_send(par,grid,lm1);\n\n rep.errorTest(\"NG_BC89flux::setup_flux_send\",0,err);\n\n\n\n // Add ranks for each send, based on parent rank.\n\n int l = lm1+1; // my level\n\n int fg_ixmin[MAX_DIM], fg_ixmax[MAX_DIM];\n\n for (int v=0;v<par.ndim;v++)\n\n fg_ixmin[v] = grid->iXmin(static_cast<axes>(v));\n\n for (int v=0;v<par.ndim;v++)\n\n fg_ixmax[v] = grid->iXmax(static_cast<axes>(v));\n\n \n", "file_path": "source/boundaries/NG_MPI_BC89flux.cpp", "rank": 11, "score": 367894.75448393455 }, { "content": " class GridBaseClass *grid, // pointer to coarse grid.\n\n const int lp1 ///< fine level to receive from\n\n )\n\n{\n\n#ifdef TEST_BC89FLUX\n\n cout <<\"NG_MPI_BC89flux::setup_flux_recv() recv from level=\";\n\n cout <<lp1<<\"\\n\";\n\n#endif\n\n int l = lp1-1; // my level\n\n size_t nc = 1; // number of cells in each interface\n\n int ixmin[MAX_DIM], ixmax[MAX_DIM], ncell[MAX_DIM]; // interface region\n\n int f_lxmin[MAX_DIM], f_lxmax[MAX_DIM]; // finer grid\n\n int d_xmin[MAX_DIM], d_xmax[MAX_DIM]; // full domain\n\n struct flux_interface *fi = 0;\n", "file_path": "source/boundaries/NG_MPI_BC89flux.cpp", "rank": 12, "score": 367894.75448393455 }, { "content": " class GridBaseClass *, ///< pointer to finer grid.\n\n const int ///< level to send to\n\n );\n\n\n\n ///\n\n /// Send fine-level fluxes at level boundary to coarser parent\n\n /// grid(s) for static mesh refinement.\n\n ///\n\n int send_BC89_fluxes_F2C(\n", "file_path": "source/boundaries/NG_MPI_BC89flux.h", "rank": 13, "score": 364186.02816560504 }, { "content": " class GridBaseClass *, ///< pointer to coarse grid.\n\n const int ///< level to receive from\n\n );\n\n\n\n ///\n\n /// Setup the flux struct flux_update_send with list of interfaces\n\n /// that need to be sent to a coarser level grid.\n\n /// These fluxes are used to correct the fluxes on the coarse grid,\n\n /// to ensure that they are consistent across all levels.\n\n /// This is an MPI-parallelised version which can deal with grids\n\n /// not on this process.\n\n ///\n\n int setup_flux_send(\n", "file_path": "source/boundaries/NG_MPI_BC89flux.h", "rank": 14, "score": 364186.02816560504 }, { "content": " class GridBaseClass *, ///< pointer to coarse-level grid\n\n struct c2f *bdata, ///< pointer to list of cells\n\n int *ixmin, ///< child grid xmin (integer)\n\n int *ixmax, ///< child grid xmax (integer)\n\n const int , ///< level of fine grid.\n\n const int *, ///< level xmin of fine grid.\n\n const int * ///< level xmax of fine grid.\n\n );\n\n\n\n /// do what it says for 2D grids\n\n void add_cells_to_C2F_send_list_2D(\n", "file_path": "source/boundaries/NG_MPI_coarse_to_fine_boundaries.h", "rank": 15, "score": 363573.04501600785 }, { "content": " class GridBaseClass *grid, ///< pointer to grid.\n\n struct boundary_data *b,\n\n const int cstep,\n\n const int maxstep\n\n )\n\n{\n\n //\n\n // For parallel grid, periodic data can be on a different proc.,\n\n // which is already pointed to by ppar->ngbprocs[b->dir]\n\n // So I just have to call BC_update_BCMPI and it will do the job.\n\n //\n\n int err=0;\n", "file_path": "source/boundaries/periodic_boundaries_MPI.cpp", "rank": 16, "score": 353460.2217464446 }, { "content": " class GridBaseClass *grid, ///< pointer to grid.\n\n struct RT_boundary_list_element &send_b ///< boundary info.\n\n )\n\n{\n\n#ifdef RT_TESTING\n\n cout <<\"RT_MPI_bc::setup_RT_send_boundary() \";\n\n cout <<\"starting (dir=\"<<send_b.dir<<\").\\n\";\n\n#endif \n\n int err=0;\n\n //\n\n // get a pointer to the existing grid boundary.\n\n //\n\n boundary_data *grid_b = grid->BC_bd[send_b.dir];\n\n if (!grid_b) {\n\n rep.error(\"RT boundary in dir with no real boundary!\",send_b.dir);\n\n }\n\n\n\n //\n\n // Set up boundary data.\n\n //\n", "file_path": "source/boundaries/RT_MPI_boundaries.cpp", "rank": 17, "score": 353460.2217464447 }, { "content": " class GridBaseClass *grid, ///< pointer to grid.\n\n boundary_data *b, ///< boundary data\n", "file_path": "source/boundaries/NG_fine_to_coarse_boundaries.cpp", "rank": 18, "score": 349387.94167704356 }, { "content": " class GridBaseClass *grid, ///< pointer to grid.\n\n boundary_data *b, ///< boundary data\n", "file_path": "source/boundaries/NG_coarse_to_fine_boundaries.cpp", "rank": 19, "score": 349387.94167704356 }, { "content": " class GridBaseClass *, ///< pointer to grid.\n\n boundary_data *, ///< Boundary to update.\n\n const int, ///< current fractional step being taken.\n\n const int ///< final step.\n\n );\n\n};\n\n\n\n#endif // PERIODIC_BOUNDARIES_MPI_H\n\n\n", "file_path": "source/boundaries/periodic_boundaries_MPI.h", "rank": 20, "score": 349018.6000885905 }, { "content": " class GridBaseClass *, ///< pointer to grid.\n\n boundary_data * ///< pointer to boundary data.\n\n );\n\n\n\n /// Updates data on a periodic boundary.\n\n int BC_update_PERIODIC(\n", "file_path": "source/boundaries/periodic_boundaries_MPI.h", "rank": 21, "score": 349018.6000885905 }, { "content": " class GridBaseClass *, ///< pointer to grid.\n\n struct RT_boundary_list_element & ///< pointer to boundary info.\n\n );\n\n\n\n ///\n\n /// Add cells to the receive boundary list, so we know what to\n\n /// expect. \n\n ///\n\n int RT_populate_recv_boundary(\n\n struct boundary_data *, ///< pointer to RT boundary data.\n\n const struct boundary_data *, ///< pointer to BC boundary data.\n\n const enum direction ///< face direction\n\n );\n\n};\n\n\n\n\n\n#endif // RT_MPI_BOUNDARIES_H\n", "file_path": "source/boundaries/RT_MPI_boundaries.h", "rank": 22, "score": 349018.6000885905 }, { "content": " class GridBaseClass *grid, ///< fine-level grid\n\n const int ncells, ///< number of fine-level cells\n\n std::vector<cell *> &c, ///< list of cells\n\n const pion_flt *cpos, ///< centre of coarse cell.\n\n double *cd ///< [OUTPUT] averaged data (conserved var).\n\n )\n\n{\n\n pion_flt u[par.nvar];\n\n //\n\n // loop through list, adding conserved var * cell-vol,\n\n // then divide by coarse cell vol.\n\n //\n\n double sum_vol=0.0, vol=0.0;\n\n vector<cell*>::iterator c_iter;\n\n\n\n // DEBUG\n\n /*\n\n double pmin=1.0e99, pmax=-1.0, pmean=0.0, temp[par.nvar];\n\n double ke=0.0, kemin=1.0e99, kemax=-1.0, kemean=0.0;\n\n double be=0.0, bemin=1.0e99, bemax=-1.0, bemean=0.0;\n", "file_path": "source/boundaries/NG_fine_to_coarse_boundaries.cpp", "rank": 23, "score": 345457.18116763467 }, { "content": " class GridBaseClass *, ///< pointer to grid.\n\n boundary_data *, ///< boundary data\n", "file_path": "source/boundaries/NG_fine_to_coarse_boundaries.h", "rank": 24, "score": 344424.6117178172 }, { "content": " class GridBaseClass *, ///< pointer to grid.\n\n boundary_data *, ///< boundary data\n", "file_path": "source/boundaries/NG_coarse_to_fine_boundaries.h", "rank": 25, "score": 344424.6117178172 }, { "content": " class GridBaseClass *, ///< pointer to grid.\n\n const int ///< level of grid in NG\n\n );\n\n\n\n /// function to setup parallel data-I/O class.\n\n void setup_dataio_class(\n", "file_path": "source/grid/setup_grid_NG_MPI.h", "rank": 27, "score": 341259.977891264 }, { "content": " class GridBaseClass *grid, ///< pointer to child grid.\n\n int nel, ///< number of coarse cells\n\n std::vector<struct averaging> &avg ///< avg list\n\n )\n\n{\n\n#ifdef TEST_MPI_NG\n\n cout <<\"NG_fine_to_coarse_bc::add_cells_to_avg()\";\n\n cout <<\" nd=\"<<ndim<<\", grid=\"<<grid<<\", nel=\"<<nel;\n\n cout <<\", avg.size=\"<<avg.size()<<\"\\n\";\n\n cout <<\"NG=\"<<grid->NG(XX)<<\"\\n\";\n\n#endif\n\n // loop through avg vector and add cells and positions\n\n cell *f = grid->FirstPt(), *m=f;\n\n int v=0, ix=0, iy=0, iz=0;\n\n int ipos[MAX_DIM];\n\n int dxo2 = grid->idx()/2;\n\n \n\n for (v=0;v<nel;v++) {\n\n#ifdef TEST_MPI_NG\n\n //cout <<\"v=\"<<v<<\" working! ix=\"<<ix<<\"\\n\";\n", "file_path": "source/boundaries/NG_fine_to_coarse_boundaries.cpp", "rank": 28, "score": 341040.26847539115 }, { "content": " class GridBaseClass *, ///< fine-level grid\n\n const int, ///< number of fine-level cells\n\n std::vector<cell *> &, ///< list of cells\n\n const pion_flt *, ///< centre of coarse cell.\n\n pion_flt * ///< [OUTPUT] averaged data (conserved var).\n\n );\n\n\n\n /// Get optical depths for radiation sources from list of cells,\n\n /// and take appropriate combination of them for the coarse cell.\n\n ///\n\n void get_F2C_TauAvg(\n", "file_path": "source/boundaries/NG_fine_to_coarse_boundaries.h", "rank": 29, "score": 340006.8600290512 }, { "content": " class GridBaseClass *grid, ///< pointer to grid.\n\n enum direction d, ///< which direction we're facing\n\n int *ixmin, ///< xmin of interface region (integer units)\n\n int *ixmax, ///< xmax of interface region (integer units)\n\n int *nface, ///< number of elements in interface region\n\n const int ncell, ///< number of cells per face.\n\n struct flux_update &flux ///< list to populate \n\n )\n\n{\n\n int a=static_cast<int>(d)/2;\n\n cell *c = grid->FirstPt_All();\n\n int idx = grid->idx();\n\n \n\n#ifdef TEST_BC89FLUX\n\n cout <<\"add_cells_to_face(\"<<d<<\", \"<<ixmin[a]<<\", \"<<ixmax[a];\n\n cout <<\", \"<<nface[a]<<\", \"<<ncell<<\"), list-size=\"<<flux.fi.size()<<\"\\n\";\n\n rep.printVec(\"ixmin\",ixmin,par.ndim);\n\n rep.printVec(\"ixmax\",ixmax,par.ndim);\n\n rep.printVec(\"nface\",nface,par.ndim);\n\n#endif\n", "file_path": "source/boundaries/NG_BC89flux.cpp", "rank": 30, "score": 338795.1056559506 }, { "content": " class cell *c=grid[l]->FirstPt();\n\n do {\n\n if (c->isdomain && c->isleaf) {\n\n dv = spatial_solver->CellVolume(c,dx);\n\n spatial_solver->PtoU(c->P,u,SimPM.gamma);\n\n nowERG += u[ERG]*dv;\n\n nowMMX += u[MMX]*dv;\n\n nowMMY += u[MMY]*dv;\n\n nowMMZ += u[MMZ]*dv;\n\n nowMASS += u[RHO]*dv;\n\n totmom += sqrt(u[MMX]*u[MMX] + u[MMY]*u[MMY] + u[MMZ]*u[MMZ])\n\n *dv;\n\n }\n\n } while ( (c =grid[l]->NextPt(c)) !=0);\n\n }\n\n\n\n //cout <<\"(local quantities) [\"<< nowERG <<\", \";\n\n //cout << nowMMX <<\", \";\n\n //cout << nowMMY <<\", \";\n\n //cout << nowMMZ <<\", \";\n", "file_path": "source/sim_control/sim_control_NG_MPI.cpp", "rank": 31, "score": 336678.8003180712 }, { "content": " class GridBaseClass *, ///< grid pointer.\n", "file_path": "source/dataIO/dataio_fits_MPI.h", "rank": 32, "score": 335932.7997479137 }, { "content": " class GridBaseClass *, ///< pointer to fine grid\n", "file_path": "source/boundaries/NG_coarse_to_fine_boundaries.h", "rank": 33, "score": 334865.7634647971 }, { "content": " class GridBaseClass *, ///< pointer to child grid.\n\n int , ///< number of coarse cells\n\n std::vector<struct averaging> & ///< avg list\n\n );\n\n\n\n int F2C_Nxd; ///< number of extra data variables to send.\n\n vector<int> F2C_tauoff; ///< offsets of optical depths from 0.\n\n\n\n};\n\n\n\n\n\n#endif // NG_FINE_TO_COARSE_BOUNDARIES_H\n\n\n", "file_path": "source/boundaries/NG_fine_to_coarse_boundaries.h", "rank": 34, "score": 334865.7634647971 }, { "content": " class GridBaseClass * ///< pointer to parent grid.\n\n );\n\n\n\n /// Updates data to an external boundary from coarser grid.\n\n virtual int BC_update_COARSE_TO_FINE(\n", "file_path": "source/boundaries/NG_coarse_to_fine_boundaries.h", "rank": 35, "score": 334865.7634647971 }, { "content": " class GridBaseClass *g = grid[v];\n\n delete g;\n\n }\n\n\n\n //\n\n // Also delete any dynamic memory in the stellarwind_list in\n\n // global.h, since we may have added wind sources in the\n\n // read-params functions.\n\n //\n\n while (SWP.params.size()>0) {\n\n int i=static_cast<int>(SWP.params.size())-1;\n\n struct stellarwind_params *temp = SWP.params[i];\n\n SWP.params.pop_back(); // remove struct from list.\n\n temp = mem.myfree(temp); // delete struct.\n\n }\n\n\n\n delete [] args; args=0;\n\n cout << \"rank: \" << SimPM.levels[0].MCMD.get_myrank();\n\n cout << \" nproc: \" << SimPM.levels[0].MCMD.get_nproc() << \"\\n\";\n\n COMM->finalise();\n", "file_path": "source/ics/icgen_NG_MPI.cpp", "rank": 36, "score": 334693.5435298858 }, { "content": " class GridBaseClass *, ///< pointer to grid.\n\n enum direction, ///< which direction we're facing\n\n int *, ///< xmin of interface region (integer units)\n\n int *, ///< xmax of interface region (integer units)\n\n int *, ///< number of elements in interface region\n\n const int, ///< number of cells per face, per dim.\n\n struct flux_update & ///< struct with list to populate\n\n );\n\n\n\n /// array of interfaces for a finer grid within this grid.\n\n /// Each element contains a single cell that needs to be updated.\n\n ///\n\n /// First dimension is for levels, second for directions on that\n\n /// level. Directions correspond to outward normal of fine level.\n\n ///\n\n /// The list has each direction as an element of the outer array\n\n /// index, and each interface in that direction as the inner index.\n\n /// Note that it is not a matix because each direction doesn't\n\n /// necessarily have any elements.\n\n ///\n", "file_path": "source/boundaries/NG_BC89flux.h", "rank": 37, "score": 334672.96386891254 }, { "content": " class GridBaseClass *grid = par.levels[l].grid;\n\n enum axes ax;\n\n double dt = par.levels[l].dt;\n\n \n\n // loop over boundaries, and, for each direction that has a\n\n // non-zero boundary, correct the coarse fluxes.\n\n for (unsigned int d=0; d<flux_update_recv[l].size(); d++) {\n\n#ifdef TEST_BC89FLUX\n\n cout <<\"flux update: \"<<d<<\", looping through faces.\\n\";\n\n#endif\n\n ax = static_cast<enum axes>(d/2);\n\n\n\n if (flux_update_recv[l][d].fi[0] ==0) {\n\n continue;\n\n }\n\n else {\n\n#ifdef TEST_BC89FLUX\n\n cout <<\"flux update: \"<<d<<\", receiving.\\n\";\n\n#endif\n\n err += recv_BC89_flux_boundary(spatial_solver, par, grid, dt,\n", "file_path": "source/boundaries/NG_BC89flux.cpp", "rank": 38, "score": 334592.2502860304 }, { "content": " class GridBaseClass *grid, ///< pointer to grid.\n", "file_path": "source/boundaries/assign_update_bcs_NG.cpp", "rank": 39, "score": 334592.2502860304 }, { "content": " class GridBaseClass *grid, ///< pointer to grid.\n", "file_path": "source/boundaries/assign_update_bcs_NG.cpp", "rank": 40, "score": 334592.2502860304 }, { "content": " class GridBaseClass *grid ///< pointer to grid.\n\n )\n\n{\n\n // first call the Uniform Grid version.\n\n int err = assign_update_bcs::assign_boundary_data(par,level,grid);\n\n rep.errorTest(\"assign_update_bcs::assign_boundary_data\",err,0);\n\n\n\n //\n\n // Then check for NG-grid boundaries and assign data for them.\n\n //\n\n for (size_t i=0; i<grid->BC_bd.size(); i++) {\n\n#ifdef TESTING\n\n cout <<\"NG grid assign BCs: BC[\"<<i<<\"] starting.\\n\";\n\n#endif\n\n switch (grid->BC_bd[i]->itype) {\n\n case FINE_TO_COARSE:\n\n#ifdef TESTING\n\n cout <<\"NG grid setup: Assigning FINE_TO_COARSE BC\\n\";\n\n#endif\n\n err += BC_assign_FINE_TO_COARSE(par,grid,grid->BC_bd[i],\n", "file_path": "source/boundaries/assign_update_bcs_NG.cpp", "rank": 41, "score": 334592.2502860304 }, { "content": " class GridBaseClass *grid ///< pointer to grid.\n\n )\n\n{\n", "file_path": "source/boundaries/assign_update_bcs_MPI.cpp", "rank": 42, "score": 334580.6202134921 }, { "content": " class GridBaseClass *grid, ///< pointer to grid.\n", "file_path": "source/boundaries/assign_update_bcs_MPI.cpp", "rank": 43, "score": 334580.6202134921 }, { "content": " class GridBaseClass *grid, // pointer to finer grid.\n\n const int lm1 ///< level to send to\n\n )\n\n{\n\n#ifdef TEST_BC89FLUX\n\n cout <<\" NG_BC89flux::setup_flux_send() send to level=\"<<lm1<<\"\\n\";\n\n#endif\n\n //\n\n // Get size of interface region and number of cells.\n\n //\n\n size_t nc = 1; // number of cells in each interface\n\n int l = lm1+1;\n\n int ixmin[MAX_DIM], ixmax[MAX_DIM],\n\n ncell[MAX_DIM], nface[MAX_DIM]; // interface\n\n int c_lxmin[MAX_DIM], c_lxmax[MAX_DIM]; // coarser grid\n\n int fg_ixmin[MAX_DIM], fg_ixmax[MAX_DIM]; // finer grid\n\n bool send[2*par.ndim]; // whether to send data in this direction\n\n size_t nel[2*par.ndim]; // number of interfaces in each direction\n\n struct flux_interface *fi = 0;\n\n int idx = grid->idx();\n", "file_path": "source/boundaries/NG_BC89flux.cpp", "rank": 44, "score": 330175.3375937869 }, { "content": " class GridBaseClass *grid, // pointer to coarse grid.\n\n const int lp1 // fine level to receive from\n\n )\n\n{\n\n#ifdef TEST_BC89FLUX\n\n cout <<\" NG_BC89flux::setup_flux_recv() recv from level=\"<<lp1<<\"\\n\";\n\n#endif\n\n //\n\n // Get size of interface region and number of cells.\n\n //\n\n size_t nc = 1; // number of cells in each interface\n\n int l = lp1-1;\n\n int ixmin[MAX_DIM], ixmax[MAX_DIM], ncell[MAX_DIM]; // interface\n\n int f_lxmin[MAX_DIM], f_lxmax[MAX_DIM]; // finer level\n\n int cg_ixmin[MAX_DIM], cg_ixmax[MAX_DIM]; // coarser grid\n\n\n\n bool recv[2*par.ndim]; // whether to get data in this direction\n\n size_t nel[2*par.ndim]; // number of interfaces in each direction\n\n struct flux_interface *fi = 0;\n\n int idx = grid->idx();\n", "file_path": "source/boundaries/NG_BC89flux.cpp", "rank": 45, "score": 330175.3375937869 }, { "content": " class GridBaseClass *grid, ///< pointer to coarse grid\n\n const double dt, ///< timestep\n\n struct flux_update &send, ///< data for fine grid\n\n struct flux_update &recv, ///< data for coarse grid\n\n const unsigned int d, ///< direction of outward normal\n\n const axes ax ///< axis of normal direction.\n\n )\n\n{ \n\n#ifdef SKIP_BC89_FLUX\n\n return 0;\n\n#endif\n\n struct flux_interface *fc=0;\n\n struct flux_interface *ff=0;\n\n double ftmp[par.nvar],utmp[par.nvar];\n\n for (int v=0;v<par.nvar;v++) ftmp[v]=0.0;\n\n for (int v=0;v<par.nvar;v++) utmp[v]=0.0;\n\n\n\n if (send.fi.size() != recv.fi.size()) {\n\n cout <<\"send=\"<<send.fi.size()<<\", recv=\"<<recv.fi.size()<<\"\\n\";\n\n rep.error(\"fine and parent face arrays r different size\",2);\n", "file_path": "source/boundaries/NG_BC89flux.cpp", "rank": 46, "score": 330175.3375937869 }, { "content": " class GridBaseClass * ///< pointer to grid.\n\n );\n\n\n\n\n\n ///\n\n /// Runs through ghost boundary cells and does the appropriate\n\n /// time update on them.\n\n ///\n\n virtual int TimeUpdateExternalBCs(\n", "file_path": "source/boundaries/assign_update_bcs_NG.h", "rank": 47, "score": 329892.24528187525 }, { "content": " class GridBaseClass *, ///< pointer to grid.\n", "file_path": "source/boundaries/assign_update_bcs_NG.h", "rank": 48, "score": 329892.24528187525 }, { "content": " class GridBaseClass * ///< pointer to grid.\n\n );\n\n\n\n ///\n\n /// Runs through ghost boundary cells and does the appropriate\n\n /// time update on them.\n\n ///\n\n virtual int TimeUpdateExternalBCs(\n", "file_path": "source/boundaries/assign_update_bcs_MPI.h", "rank": 49, "score": 329879.97053132404 }, { "content": " class GridBaseClass *, ///< pointer to grid.\n", "file_path": "source/boundaries/assign_update_bcs_MPI.h", "rank": 50, "score": 329879.97053132404 }, { "content": "///\n\n/// Set up a static NG grid structure. Serial code, so each\n\n/// level of the NG has a single grid.\n\n///\n\nclass setup_grid_NG_MPI :\n\n virtual public assign_update_bcs_NG_MPI,\n\n virtual public setup_NG_grid,\n\n virtual public setup_fixed_grid_pllel,\n\n virtual public NG_MPI_BC89flux\n\n{\n\n public:\n\n setup_grid_NG_MPI();\n\n ~setup_grid_NG_MPI();\n\n\n\n ///\n\n /// Populate the array SimPM.levels with Xmin,Xmax,Range,dx,etc.\n\n ///\n\n void setup_NG_grid_levels(\n", "file_path": "source/grid/setup_grid_NG_MPI.h", "rank": 51, "score": 326297.58987218514 }, { "content": " class GridBaseClass *, ///< pointer to finer grid.\n\n const int ///< level to send to\n\n );\n\n\n\n ///\n\n /// Add fluxes from boundary cells to grid structures, for cells\n\n /// at the grid boundary, to be sent to the coarser level grid.\n\n /// Assumes that fluxes have already been calculated and saved in\n\n /// array \"F\" of all relevant cells.\n\n /// \n\n /// These fluxes are used to correct the fluxes on the coarse grid,\n\n /// to ensure that they are consistent across all levels, following\n\n /// Berger & Colella (1989,JCP,82,64).\n\n ///\n\n virtual void save_fine_fluxes(\n", "file_path": "source/boundaries/NG_BC89flux.h", "rank": 52, "score": 324751.1487176211 }, { "content": " class GridBaseClass *, ///< pointer to coarse grid.\n\n const int ///< finer level to receive from\n\n );\n\n\n\n ///\n\n /// Setup the flux struct flux_update_send with list of interfaces\n\n /// that need to be sent to a coarser level grid.\n\n /// These fluxes are used to correct the fluxes on the coarse grid,\n\n /// to ensure that they are consistent across all levels, following\n\n /// Berger & Colella (1989,JCP,82,64).\n\n ///\n\n virtual int setup_flux_send(\n", "file_path": "source/boundaries/NG_BC89flux.h", "rank": 53, "score": 324751.1487176211 }, { "content": " class GridBaseClass *, ///< pointer to coarse grid\n\n const double, ///< timestep\n\n struct flux_update &, ///< data for fine grid\n\n struct flux_update &, ///< data for coarse grid\n\n const unsigned int, ///< direction of outward normal\n\n const axes ///< axis of normal direction.\n\n );\n\n protected:\n\n ///\n\n /// Add cells to the flux_update_recv and flux_update_send lists,\n\n /// for keeping track of flux entering/leaving a grid on one level.\n\n /// This is book-keeping for NG/AMR to ensure fluxes are\n\n /// consistent across all levels.\n\n /// \n\n int add_cells_to_face(\n", "file_path": "source/boundaries/NG_BC89flux.h", "rank": 54, "score": 324751.1487176211 }, { "content": " class cell *c = grid[l]->FirstPt_All();\n\n do {\n\n // if outside domain, then cell is not a leaf.\n\n for (int v=0;v<par.ndim;v++) {\n\n if (c->pos[v]<sxmin[v] || c->pos[v]>sxmax[v]) c->isleaf=false;\n\n }\n\n if (l<par.grid_nlevels-1) {\n\n notleaf=true;\n\n CI.get_ipos_vec(par.levels[l+1].Xmin, lxmin);\n\n CI.get_ipos_vec(par.levels[l+1].Xmax, lxmax);\n\n for (int v=0;v<par.ndim;v++) {\n\n if (c->pos[v]>lxmax[v] || c->pos[v]<lxmin[v]) notleaf=false;\n\n }\n\n if (notleaf) c->isleaf=false;\n\n }\n\n if (!c->isleaf) c->timestep=false;\n\n\n\n } while ( (c=grid[l]->NextPt_All(c))!=0);\n\n }\n\n return;\n\n}\n\n\n\n\n\n\n\n// ##################################################################\n\n// ##################################################################\n\n\n\n\n\n\n\nint setup_NG_grid::setup_raytracing(\n", "file_path": "source/grid/setup_NG_grid.cpp", "rank": 55, "score": 323845.442223541 }, { "content": " class GridBaseClass *grid = SimPM.levels[l].grid;\n\n bool finest_level = (l<SimPM.grid_nlevels-1) ? false : true;\n\n\n\n#ifdef TEST_INT\n\n cout <<\"advance_step_OA2: child=\"<<SimPM.levels[l].child<<endl;\n\n#endif\n\n\n\n // --------------------------------------------------------\n\n // 0. See if there are coarse-to-fine boundary data to send\n\n int c2f = -1, f2cs=-1, f2cr=-1;\n\n if (!finest_level) {\n\n for (size_t i=0;i<grid->BC_bd.size();i++) {\n\n //cout <<\"i=\"<<i<<\", BD type = \"<<grid->BC_bd[i]->type<<\"\\n\";\n\n // there's only one C2F boundary\n\n if (grid->BC_bd[i]->itype == COARSE_TO_FINE_SEND) c2f=i;\n\n }\n\n // F2C data to receive\n\n for (size_t i=0;i<grid->BC_bd.size();i++) {\n\n if (grid->BC_bd[i]->itype == FINE_TO_COARSE_RECV) f2cr=i;\n\n }\n", "file_path": "source/sim_control/sim_control_NG_MPI.cpp", "rank": 56, "score": 323015.5886869535 }, { "content": " class GridBaseClass *fine = par.levels[level].grid;\n\n#ifdef TEST_C2F\n\n cout <<\"C2F: fine=\"<<fine<<\", parent=\"<<coarse<<\", level=\";\n\n cout <<level<<\"\\n\";\n\n#endif\n\n\n\n list<cell*>::iterator f_iter=b->data.begin();\n\n cell *f, *c;\n\n\n\n // ----------------------------------------------------------------\n\n //\n\n // if on an odd-numbered step, then need to update the data on the\n\n // coarse grid to half way through a coarse step. Assume dU has\n\n // been calculated for the coarse grid, but the state vector not\n\n // updated, so we can convert U+0.5*dU into a new primitive\n\n // state for the half step.\n\n // NB: We overwrite Ph[] in the coarse cell, assuming it is not\n\n // needed anymore on the coarse grid because dU[] is already\n\n // calculated.\n\n //\n", "file_path": "source/boundaries/NG_coarse_to_fine_boundaries.cpp", "rank": 57, "score": 322632.54324221116 }, { "content": " class GridBaseClass *fine, ///< pointer to fine grid\n", "file_path": "source/boundaries/NG_coarse_to_fine_boundaries.cpp", "rank": 58, "score": 321827.36026853765 }, { "content": " class GridBaseClass *child, ///< pointer to child grid.\n\n const int i ///< which element of NGrecvF2C to use\n\n )\n\n{\n\n //\n\n // Make a list of child-grid cells to map onto the coarse grid\n\n //\n\n if (b->NGrecvF2C.size() <= static_cast<unsigned int>(i))\n\n rep.error(\"BC_assign_FINE_TO_COARSE: recv vec too small\",i);\n\n if (b->NGrecvF2C[i].empty())\n\n rep.error(\"BC_assign_FINE_TO_COARSE: empty boundary data\",\n\n b->itype);\n\n\n\n //\n\n // If we are doing raytracing, then also send the column densities\n\n // from fine to coarse grids. Here we set up the number of them.\n\n //\n\n struct rad_src_info *s;\n\n F2C_Nxd = 0;\n\n F2C_tauoff.resize(par.RS.Nsources);\n", "file_path": "source/boundaries/NG_fine_to_coarse_boundaries.cpp", "rank": 59, "score": 321827.36026853765 }, { "content": " class GridBaseClass *parent ///< pointer to parent grid.\n\n )\n\n{\n\n //\n\n // Make a list of pointers to cells in the coarser grid that map\n\n // onto this (finer) grid external boundary, and then write an\n\n // alogrithm to interpolate the coarse data onto the finer grid.\n\n //\n\n if (b->data.empty())\n\n rep.error(\"BC_assign_COARSE_TO_FINE: empty boundary data\",\n\n b->itype);\n\n\n\n //\n\n // If we are doing raytracing, then also send the column densities\n\n // from coarse to fine grids. Here we set up the number of them.\n\n //\n\n#ifdef C2F_TAU\n\n struct rad_src_info *s;\n\n C2F_Nxd = 0;\n\n C2F_tauoff.resize(par.RS.Nsources);\n", "file_path": "source/boundaries/NG_coarse_to_fine_boundaries.cpp", "rank": 60, "score": 321827.36026853765 }, { "content": " class GridBaseClass *grid, ///< pointer to grid.\n\n struct boundary_data *b,\n\n const int cstep,\n\n const int maxstep\n\n )\n\n{\n\n //\n\n // Outflow or Absorbing BCs; boundary cells are same as edge cells.\n\n // This is zeroth order outflow bcs.\n\n //\n\n list<cell*>::iterator c=b->data.begin();\n\n cell *gc;\n\n\n\n for (c=b->data.begin(); c!=b->data.end(); ++c) {\n\n //\n\n // gc is the on-grid cell.\n\n //\n\n gc = (*c)->npt;\n\n for (int v=0;v<par.nvar;v++) (*c)->Ph[v] = gc->Ph[v];\n\n for (int v=0;v<par.nvar;v++) (*c)->dU[v] = 0.;\n", "file_path": "source/boundaries/outflow_boundaries.cpp", "rank": 61, "score": 312490.6049718312 }, { "content": " class GridBaseClass *grid, ///< pointer to grid.\n\n struct boundary_data *b,\n\n const int cstep,\n\n const int maxstep\n\n )\n\n{\n\n //\n\n // Fixed means all boundary points have same fixed value, stored\n\n // in refval.\n\n //\n\n list<cell*>::iterator c=b->data.begin();\n\n for (c=b->data.begin(); c!=b->data.end(); ++c) {\n\n for (int v=0;v<par.nvar;v++) (*c)->dU[v]=0.;\n\n for (int v=0;v<par.nvar;v++) (*c)->P[v] = b->refval[v];\n\n for (int v=0;v<par.nvar;v++) (*c)->Ph[v] = b->refval[v];\n\n } // all cells. \n\n return 0;\n\n}\n\n\n\n\n\n\n\n// ##################################################################\n\n// ##################################################################\n\n\n\n\n\n\n\n\n", "file_path": "source/boundaries/fixed_boundaries.cpp", "rank": 62, "score": 312490.6049718312 }, { "content": " class GridBaseClass *grid, ///< pointer to grid.\n\n struct boundary_data *b,\n\n const int cstep,\n\n const int maxstep\n\n )\n\n{\n\n //\n\n // same routine as for outflow, except multiply v_n,B_n by -1.\n\n //\n\n list<cell*>::iterator c=b->data.begin();\n\n for (c=b->data.begin(); c!=b->data.end(); ++c) {\n\n for (int v=0;v<par.nvar;v++) {\n\n (*c)->Ph[v] = (*c)->npt->Ph[v] *b->refval[v];\n\n }\n\n for (int v=0;v<par.nvar;v++) (*c)->dU[v] = 0.;\n\n if (cstep==maxstep) {\n\n for (int v=0;v<par.nvar;v++) {\n\n (*c)->P[v] = (*c)->npt->P[v] *b->refval[v];\n\n }\n\n }\n", "file_path": "source/boundaries/reflecting_boundaries.cpp", "rank": 63, "score": 312490.6049718312 }, { "content": " class GridBaseClass *grid, ///< pointer to grid.\n\n struct boundary_data *b,\n\n const int,\n\n const int\n\n )\n\n{\n\n#ifdef SOFTJET\n\n double dist=0.0;\n\n double jr = JP.jetradius*grid->DX();\n\n#endif //SOFTJET\n\n\n\n list<cell*>::iterator c=b->data.begin();\n\n for (c=b->data.begin(); c!=b->data.end(); ++c) {\n\n for (int v=0;v<par.nvar;v++) (*c)->dU[v]=0.0;\n\n for (int v=0;v<par.nvar;v++) (*c)->P[v] = b->refval[v];\n\n for (int v=0;v<par.nvar;v++) (*c)->Ph[v] = b->refval[v];\n\n#ifdef SOFTJET\n\n dist =0.0;\n\n if (par.ndim==2) dist = CI.get_dpos(*c,YY);\n\n else if (par.ndim==3) {\n", "file_path": "source/boundaries/jet_boundaries.cpp", "rank": 64, "score": 312490.6049718312 }, { "content": " class GridBaseClass *grid, ///< pointer to grid.\n\n boundary_data *b\n\n )\n\n{\n\n //\n\n // The setup for this is identical to outflow.\n\n //\n\n int err=BC_assign_OUTFLOW(par,grid,b);\n\n return err;\n\n}\n\n\n\n\n\n\n\n// ##################################################################\n\n// ##################################################################\n\n\n\n\n\n\n\nint oneway_out_bc::BC_update_ONEWAY_OUT(\n", "file_path": "source/boundaries/oneway_out_boundaries.cpp", "rank": 65, "score": 312490.6049718312 }, { "content": "\n\n#include \"spatial_solvers/solver_eqn_hydro_adi.h\"\n\n#include \"spatial_solvers/solver_eqn_mhd_adi.h\"\n\n#include \"setup_fixed_grid.h\"\n\n#include \"grid/grid_base_class.h\"\n\n#include \"grid/uniform_grid.h\"\n\n\n\n#include <iostream>\n\n#include <sstream>\n\n#include <fstream>\n\n#include <string>\n\n#include <sys/time.h>\n\n#include <time.h>\n\n#include <climits>\n\nusing namespace std;\n\n\n\n\n\n\n\n// ##################################################################\n\n// ##################################################################\n", "file_path": "source/grid/setup_fixed_grid.cpp", "rank": 66, "score": 63.61861367804462 }, { "content": "/// \\file NG_MPI_coarse_to_fine_boundaries.cpp\n\n/// \\brief Class definitions for NG_MPI_coarse_to_fine boundaries\n\n/// \\author Jonathan Mackey\n\n/// \n\n/// Modifications :\\n\n\n/// - 2018.09.06 JM: started writing code.\n\n\n\n\n\n#include \"boundaries/NG_MPI_coarse_to_fine_boundaries.h\"\n\n#include \"tools/mem_manage.h\"\n\n#include <sstream>\n\nusing namespace std;\n\n\n\n//#define TEST_C2F\n\n//#define TEST_MPI_NG\n\n\n\n// ##################################################################\n\n// ##################################################################\n\n\n\n\n\n\n\nint NG_MPI_coarse_to_fine_bc::BC_assign_COARSE_TO_FINE_SEND(\n", "file_path": "source/boundaries/NG_MPI_coarse_to_fine_boundaries.cpp", "rank": 67, "score": 59.016406398975725 }, { "content": " // ----------------------------------------------------------------\n\n for (int l=0; l<SimPM.grid_nlevels; l++) {\n\n#ifdef TESTING\n\n cout <<\"NG_MPI updating external boundaries for level \"<<l<<\"\\n\";\n\n cout <<\"@@@@@@@@@@@@ UPDATING EXTERNAL BOUNDARIES FOR LEVEL \";\n\n cout <<l<<\"\\n\";\n\n#endif\n\n err += TimeUpdateExternalBCs(SimPM,l,grid[l], spatial_solver,\n\n SimPM.simtime,SimPM.tmOOA,SimPM.tmOOA);\n\n }\n\n rep.errorTest(\"NG_MPI INIT: error from bounday update\",0,err);\n\n // ----------------------------------------------------------------\n\n\n\n\n\n // ----------------------------------------------------------------\n\n for (int l=SimPM.grid_nlevels-1; l>=0; l--) {\n\n#ifdef TESTING\n\n cout <<\"NG_MPI updating internal boundaries for level \"<<l<<\"\\n\";\n\n cout <<\"@@@@@@@@@@@@ UPDATING INTERNAL BOUNDARIES FOR LEVEL \";\n\n cout <<l<<\"\\n\";\n", "file_path": "source/sim_control/sim_control_NG_MPI.cpp", "rank": 68, "score": 58.08229631194499 }, { "content": "#include <iostream>\n\nusing namespace std;\n\n\n\n\n\n//#define GLM_ZERO_BOUNDARY ///< Set this flag to make Psi=0 on boundary cells.\n\n#define GLM_NEGATIVE_BOUNDARY ///< Set this flag for Psi[boundary cell]=-Psi[edge cell]\n\n\n\n\n\n\n\n// ##################################################################\n\n// ##################################################################\n\n\n\n\n\n\n\nUniformGrid::UniformGrid(\n\n int nd,\n\n int nv,\n\n int eqt,\n\n int Nbc,\n\n double *g_xn,\n", "file_path": "source/old_code/static_grid.cpp", "rank": 70, "score": 56.9464946864549 }, { "content": " double NG_centre[MAX_DIM];\n\n int NG_refine[MAX_DIM];\n\n std::vector<class level> levels;\n\n\n\n // Boundary cell data.\n\n std::string BC_XN; ///< Type of boundary condition.\n\n std::string BC_XP; ///< Type of boundary condition.\n\n std::string BC_YN; ///< Type of boundary condition.\n\n std::string BC_YP; ///< Type of boundary condition.\n\n std::string BC_ZN; ///< Type of boundary condition.\n\n std::string BC_ZP; ///< Type of boundary condition.\n\n int BC_Nint; ///< Number of internal boundary regions\n\n std::string *BC_INT; ///< List of internal boundary regions.\n\n std::string BC_STRING; ///< For reading pre-2018 data-files.\n\n\n\n int Nbc; ///< Depth of boundary/ghost cells from edge of grid.\n\n int Nbc_DD; ///< Depth of boundary cells for MPI boundaries.\n\n // Integration accuracy\n\n int spOOA; ///< Spatial Order of Accuracy in the code.\n\n int tmOOA; ///< Time Order of Accuracy in the code.\n", "file_path": "source/sim_params.h", "rank": 71, "score": 56.2520429732794 }, { "content": "#include \"tools/reporting.h\"\n\n#include \"tools/timer.h\"\n\n#include \"tools/mem_manage.h\"\n\n\n\n#include \"constants.h\"\n\n\n\n#include \"decomposition/MCMD_control.h\"\n\n#include \"sim_control/sim_control_NG_MPI.h\"\n\n#include \"raytracing/raytracer_SC.h\"\n\n\n\n\n\n#include <iostream>\n\n#include <sstream>\n\n#include <fstream>\n\nusing namespace std;\n\n\n\n#ifdef PARALLEL\n\n\n\n//#define TEST_INT\n\n\n", "file_path": "source/sim_control/sim_control_NG_MPI.cpp", "rank": 72, "score": 55.7539216989492 }, { "content": "#include \"dataIO/dataio_base.h\"\n\n#ifdef SILO\n\n#include \"dataIO/dataio_silo_utility.h\"\n\n#endif // if SILO\n\n\n\n#include \"grid/uniform_grid.h\"\n\n#include \"grid/setup_grid_NG_MPI.h\"\n\n#include \"microphysics/microphysics_base.h\"\n\n#include \"raytracing/raytracer_base.h\"\n\n\n\n#include <sstream>\n\nusing namespace std;\n\n\n\n//#define TESTING\n\n\n\n// ##################################################################\n\n// ##################################################################\n\n\n\n\n\n\n\nint main(int argc, char **argv)\n\n{\n\n int err = COMM->init(&argc, &argv);\n\n if (err) rep.error(\"comms init error\",err);\n\n\n\n int r=-1, np=-1;\n\n COMM->get_rank_nproc(&r,&np);\n", "file_path": "source/ics/icgen_NG_MPI.cpp", "rank": 73, "score": 55.57461576112733 }, { "content": "/// \\file NG_MPI_fine_to_coarse_boundaries.cpp\n\n/// \\brief Class definitions for NG_MPI_fine_to_coarse boundaries\n\n/// \\author Jonathan Mackey\n\n/// \n\n/// \\section Description\n\n/// Coarse-to-Fine boundary updates send grid data from a coarse grid\n\n/// to update the external boundaries of a fine grid contained within\n\n/// the coarse grid. This version is parallelised with MPI.\n\n/// \n\n/// Modifications :\\n\n\n/// - 2018.08.08 JM: moved code.\n\n\n\n\n\n#include \"boundaries/NG_MPI_fine_to_coarse_boundaries.h\"\n\n#include \"tools/mem_manage.h\"\n\nusing namespace std;\n\n\n\n//#define TEST_MPI_NG_F2C\n\n//#define NG_F2C_POS\n\n\n\n// ##################################################################\n\n// ##################################################################\n\n\n\n\n\n\n\nint NG_MPI_fine_to_coarse_bc::BC_assign_FINE_TO_COARSE_SEND(\n", "file_path": "source/boundaries/NG_MPI_fine_to_coarse_boundaries.cpp", "rank": 74, "score": 55.35405968351003 }, { "content": " cout <<\"ICGEN_NG_MPI: Setting up boundaries\\n\";\n\n//#endif\n\n SimSetup->boundary_conditions(SimPM,grid);\n\n if (err) rep.error(\"icgen: Couldn't set up boundaries.\",err);\n\n\n\n//#ifdef TESTING\n\n cout <<\"ICGEN_NG_MPI: Setting up raytracing\\n\";\n\n//#endif\n\n err += SimSetup->setup_raytracing(SimPM,grid);\n\n if (err) rep.error(\"icgen: Failed to setup raytracer\",err);\n\n\n\n for (int l=0;l<SimPM.grid_nlevels;l++) {\n\n#ifdef TESTING\n\n cout <<\"icgen_NG_MPI: assigning boundary data for level \"<<l<<\"\\n\";\n\n#endif\n\n err = SimSetup->assign_boundary_data(SimPM,l,grid[l]);\n\n COMM->barrier(\"level assign boundary data\");\n\n rep.errorTest(\"icgen_NG_MPI::assign_boundary_data\",0,err);\n\n }\n\n // ----------------------------------------------------------------\n", "file_path": "source/ics/icgen_NG_MPI.cpp", "rank": 75, "score": 54.58716178990474 }, { "content": "\n\n#include \"dataIO/dataio_base.h\"\n\n#ifdef SILO\n\n#include \"dataIO/dataio_silo.h\"\n\n#endif // if SILO\n\n#ifdef FITS\n\n#include \"dataIO/dataio_fits.h\"\n\n#endif // if FITS\n\n\n\n\n\n#include <iostream>\n\n#include <sstream>\n\n#include <fstream>\n\n#include <string>\n\n#include <sys/time.h>\n\n#include <time.h>\n\n#include <climits>\n\nusing namespace std;\n\n\n\n\n", "file_path": "source/grid/setup_NG_grid.cpp", "rank": 76, "score": 54.02106862867696 }, { "content": " cout <<\"sim_control_NG_MPI destructor.\\n\";\n\n#endif\n\n}\n\n\n\n\n\n\n\n// ##################################################################\n\n// ##################################################################\n\n\n\n\n\n\n\nint sim_control_NG_MPI::Init(\n\n string infile,\n\n int typeOfFile,\n\n int narg,\n\n string *args,\n\n vector<class GridBaseClass *> &grid ///< address of vector of grid pointers.\n\n )\n\n{\n\n cout <<\"(pion) Init: infile = \"<<infile<<\"\\n\";\n", "file_path": "source/sim_control/sim_control_NG_MPI.cpp", "rank": 77, "score": 53.668635701213844 }, { "content": "#include \"constants.h\"\n\n#include \"sim_params.h\"\n\n\n\n#include \"decomposition/MCMD_control.h\"\n\n#include \"grid/setup_fixed_grid_MPI.h\"\n\n#include \"grid/uniform_grid.h\"\n\n#include \"dataIO/dataio_fits.h\"\n\n\n\n#include <sstream>\n\n#include \"fitsio.h\"\n\nusing namespace std;\n\n\n\nint main(int argc, char **argv)\n\n{\n\n\n\n //\n\n // First initialise MPI, even though this is a single processor\n\n // piece of code.\n\n //\n\n int err = COMM->init(&argc, &argv);\n", "file_path": "analysis/zz_deprecated/merge_fits_files/merge_fits_files.cpp", "rank": 78, "score": 53.432747065067105 }, { "content": "#ifdef TEST_INT\n\n cout <<\"NG_MPI F2C cleared all sends.\\n\";\n\n#endif\n\n rep.errorTest(\"NG_MPI time-int: error from bounday update\",0,err);\n\n // ----------------------------------------------------------------\n\n\n\n // ----------------------------------------------------------------\n\n // update coarse-to-fine level boundaries\n\n for (int l=0; l<SimPM.grid_nlevels; l++) {\n\n#ifdef TEST_INT\n\n cout <<\"NG_MPI updating C2F boundaries for level \"<<l<<\"\\n\";\n\n cout <<l<<\"\\n\";\n\n#endif\n\n#ifdef TEST_INT\n\n cout <<\"updating external boundaries for level \"<<l<<\"\\n\";\n\n#endif\n\n if (l>0) {\n\n for (size_t i=0;i<grid[l]->BC_bd.size();i++) {\n\n if (grid[l]->BC_bd[i]->itype == COARSE_TO_FINE_RECV) {\n\n err += BC_update_COARSE_TO_FINE_RECV(SimPM,spatial_solver,\n", "file_path": "source/sim_control/sim_control_NG_MPI.cpp", "rank": 79, "score": 53.35357610691686 }, { "content": "#endif\n\n err += TimeUpdateInternalBCs(SimPM,l,grid[l], spatial_solver,\n\n SimPM.simtime,SimPM.tmOOA,SimPM.tmOOA);\n\n }\n\n rep.errorTest(\"NG_MPI INIT: error from bounday update\",0,err);\n\n\n\n // ----------------------------------------------------------------\n\n // update fine-to-coarse level boundaries\n\n for (int l=SimPM.grid_nlevels-1; l>=0; l--) {\n\n#ifdef TESTING\n\n cout <<\"NG_MPI updating F2C boundaries for level \"<<l<<\"\\n\";\n\n cout <<l<<\"\\n\";\n\n#endif\n\n if (l>0) {\n\n for (size_t i=0;i<grid[l]->BC_bd.size();i++) {\n\n if (grid[l]->BC_bd[i]->itype == FINE_TO_COARSE_SEND) {\n\n err += BC_update_FINE_TO_COARSE_SEND(SimPM,\n\n spatial_solver, l, grid[l]->BC_bd[i], 2,2);\n\n }\n\n }\n", "file_path": "source/sim_control/sim_control_NG_MPI.cpp", "rank": 80, "score": 53.34436516372264 }, { "content": " cout <<\"UPDATING EXTERNAL BOUNDARIES FOR LEVEL \";\n\n cout <<l<<\"\\n\";\n\n#endif\n\n err += TimeUpdateExternalBCs(SimPM,l,grid[l], spatial_solver,\n\n SimPM.simtime,SimPM.tmOOA,SimPM.tmOOA);\n\n }\n\n rep.errorTest(\"NG_MPI INIT: error from bounday update\",0,err);\n\n // ----------------------------------------------------------------\n\n\n\n // ----------------------------------------------------------------\n\n for (int l=0; l<SimPM.grid_nlevels; l++) {\n\n#ifdef TESTING\n\n cout <<\"NG_MPI updating C2F boundaries for level \"<<l<<\"\\n\";\n\n cout <<\"UPDATING C2F BOUNDARIES FOR LEVEL \";\n\n cout <<l<<\"\\n\";\n\n#endif\n\n if (l<SimPM.grid_nlevels-1) {\n\n for (size_t i=0;i<grid[l]->BC_bd.size();i++) {\n\n if (grid[l]->BC_bd[i]->itype == COARSE_TO_FINE_SEND) {\n\n err += BC_update_COARSE_TO_FINE_SEND(SimPM,grid[l],\n", "file_path": "source/sim_control/sim_control_NG_MPI.cpp", "rank": 81, "score": 53.17056046760919 }, { "content": " // ----------------------------------------------------------------\n\n err = set_equations(SimPM);\n\n rep.errorTest(\"(NG_MPI INIT::set_equations)\",0,err);\n\n spatial_solver->SetEOS(SimPM.gamma);\n\n\n\n // set up Microphysics, if needed.\n\n // ----------------------------------------------------------------\n\n err = setup_microphysics(SimPM);\n\n rep.errorTest(\"(NG_MPI INIT::setup_microphysics)\",0,err);\n\n \n\n // assign data to the grid from snapshot file.\n\n // ----------------------------------------------------------------\n\n err = dataio->ReadData(infile, grid, SimPM);\n\n rep.errorTest(\"(NG_MPI INIT::assign_initial_data)\",0,err);\n\n\n\n // ----------------------------------------------------------------\n\n // Set Ph[] = P[], and then implement the boundary conditions.\n\n for (int l=0; l<SimPM.grid_nlevels; l++) {\n\n cell *c = grid[l]->FirstPt();\n\n double u[SimPM.nvar];\n", "file_path": "source/sim_control/sim_control_NG_MPI.cpp", "rank": 82, "score": 53.15740014538686 }, { "content": "/// - 2012.05.15 JM: Added function for global-reduce (max/min/sum)\n\n/// of arrays.\n\n/// - 2013.01.17 JM: Made class less verbose; wrapped cout in TEST_COMMS\n\n/// flags.\n\n/// - 2015.01.26 JM: removed references to mpiPM (no longer global),\n\n/// added COMM pointer setup, added get_rank_nproc()\n\n/// - 2015.08.05 JM: Added pion_flt to send/receive for cell data.\n\n/// - 2016.03.14 JM: Worked on parallel Grid_v2 update (full\n\n/// boundaries).\n\n\n\n#ifdef PARALLEL\n\n#ifdef USE_MPI\n\n\n\n//#define TEST_COMMS\n\n\n\n#include \"defines/functionality_flags.h\"\n\n#include \"defines/testing_flags.h\"\n\n#include \"constants.h\"\n\n\n\n#include \"tools/mem_manage.h\"\n\n#include \"tools/reporting.h\"\n\n#include \"tools/command_line_interface.h\"\n\n\n\n#include \"comms/comm_mpi.h\"\n\n\n\n#include <sstream>\n\nusing namespace std;\n\n\n", "file_path": "source/comms/comm_mpi.cpp", "rank": 83, "score": 53.10397148186116 }, { "content": "\n\n#include \"sim_control/calc_timestep.h\"\n\n#include \"grid/setup_fixed_grid.h\"\n\n#include \"microphysics/microphysics_base.h\"\n\n#include \"raytracing/raytracer_SC.h\"\n\n#include \"spatial_solvers/solver_eqn_base.h\"\n\n\n\n#include <iostream>\n\n#include <sstream>\n\n#include <fstream>\n\n#include <sys/time.h>\n\n#include <time.h>\n\n#include <climits>\n\nusing namespace std;\n\n\n\n\n\n\n\n// ##################################################################\n\n// ##################################################################\n\n\n", "file_path": "source/sim_control/calc_timestep.cpp", "rank": 84, "score": 52.980429421623526 }, { "content": "\n\n\n\n // ----------------------------------------------------------------\n\n//#ifdef TESTING\n\n cout <<\"icgen_NG_MPI: updating boundary data\\n\";\n\n//#endif\n\n#ifdef TESTING\n\n cout <<\"icgen_NG_MPI: updating external boundaries\\n\";\n\n#endif\n\n for (int l=0; l<SimPM.grid_nlevels; l++) {\n\n err += SimSetup->TimeUpdateExternalBCs(SimPM,l,grid[l], solver,\n\n SimPM.simtime,SimPM.tmOOA,SimPM.tmOOA);\n\n }\n\n rep.errorTest(\"sim_init_NG: error from boundary update\",0,err);\n\n // ----------------------------------------------------------------\n\n\n\n // ----------------------------------------------------------------\n\n#ifdef TESTING\n\n cout <<\"icgen_NG_MPI: updating C2F boundaries\\n\";\n\n#endif\n", "file_path": "source/ics/icgen_NG_MPI.cpp", "rank": 85, "score": 52.93363024376849 }, { "content": "\n\n // ----------------------------------------------------------------\n\n for (int l=SimPM.grid_nlevels-1; l>=0; l--) {\n\n#ifdef TESTING\n\n cout <<\"updating internal boundaries for level \"<<l<<\"\\n\";\n\n#endif\n\n err += TimeUpdateInternalBCs(SimPM,l,grid[l], spatial_solver,\n\n SimPM.simtime,SimPM.tmOOA,SimPM.tmOOA);\n\n }\n\n rep.errorTest(\"NG_INIT: error from bounday update\",0,err);\n\n // ----------------------------------------------------------------\n\n\n\n //\n\n // If testing the code, this calculates the momentum and energy on\n\n // the domain.\n\n //\n\n initial_conserved_quantities(grid);\n\n\n\n //\n\n // If using opfreq_time, set the next output time correctly.\n", "file_path": "source/sim_control/sim_control_NG.cpp", "rank": 86, "score": 52.929045674930485 }, { "content": "/// - noise=D : add noise to icfile if desired, at fractional level of D\n\n/// - finishtime=D : set time to finish simulation, in code time units.\n\n/// - coordsys=NAME : set coordinate system to [cartesian,cylindrical]. DANGEROUS TO OVERRIDE!\n\n/// - cfl=D : change the CFL no. for the simulation, in range (0,1).\n\n/// - cooling=N : cooling=0 for no cooling, 1 for Sutherland&Dopita1993.\n\n/// \n\n/// Modifications:\n\n/// - 2018.08.30 JM: wrote code.\n\n\n\n#include <iostream>\n\n#include <sstream>\n\nusing namespace std;\n\n\n\n#include \"defines/functionality_flags.h\"\n\n#include \"defines/testing_flags.h\"\n\n#include \"sim_constants.h\"\n\n#include \"tools/reporting.h\"\n\n#include \"grid/grid_base_class.h\"\n\n#include \"sim_control/sim_control_NG_MPI.h\"\n\n\n", "file_path": "source/main_NG_MPI.cpp", "rank": 87, "score": 52.92475192675465 }, { "content": " G_fpt_all);\n\n }\n\n \n\n //\n\n // assign memory for all cells, including boundary cells.\n\n //\n\n#ifdef TESTING\n\n cout <<\"\\t allocating memory for grid.\\n\";\n\n#endif // TESTING\n\n int err = allocate_grid_data();\n\n if(err!=0)\n\n rep.error(\"Error setting up grid, allocate_grid_data\",err);\n\n\n\n //\n\n // assign grid structure on cells, setting positions and ngb\n\n // pointers.\n\n //\n\n#ifdef TESTING\n\n cout <<\"\\t assigning pointers to neighbours.\\n\";\n\n#endif // TESTING\n", "file_path": "source/grid/uniform_grid.cpp", "rank": 88, "score": 52.86833451493538 }, { "content": " for (int l=0; l<SimPM.grid_nlevels; l++) {\n\n SimPM.levels[l].dt = 0.0;\n\n SimPM.levels[l].simtime = SimPM.simtime;\n\n }\n\n\n\n\n\n // --------------------------------------------------------------\n\n // Update internal and external boundaries.\n\n\n\n for (int l=SimPM.grid_nlevels-1; l>=0; l--) {\n\n#ifdef TEST_INT\n\n cout <<\"updating internal boundaries for level \"<<l<<\"... \";\n\n#endif\n\n err += TimeUpdateInternalBCs(SimPM, l, grid[l], spatial_solver,\n\n SimPM.levels[l].simtime,SimPM.tmOOA,SimPM.tmOOA);\n\n#ifdef TEST_INT\n\n cout <<\"... done \\n\";\n\n#endif\n\n }\n\n rep.errorTest(\"sim_control_NG_MPI: internal boundary\",0,err);\n", "file_path": "source/sim_control/sim_control_NG_MPI.cpp", "rank": 89, "score": 52.78456443350733 }, { "content": "#include \"boundaries/NG_MPI_BC89flux.h\"\n\n#include \"tools/reporting.h\"\n\n#include \"tools/mem_manage.h\"\n\n#include \"constants.h\"\n\n#include <iostream>\n\nusing namespace std;\n\n\n\n\n\n\n\n\n\n\n\n// ##################################################################\n\n// ##################################################################\n\n\n\n\n\n\n\nint NG_MPI_BC89flux::setup_flux_recv(\n", "file_path": "source/boundaries/NG_MPI_BC89flux.cpp", "rank": 90, "score": 52.02856539950421 }, { "content": "#ifdef TEST_INT\n\n cout <<\"updating internal boundaries for level \"<<l<<\"\\n\";\n\n#endif\n\n grid = par.levels[l].grid;\n\n // F2C gets data from child grid onto this grid.\n\n err = TimeUpdateInternalBCs(par, l, grid, spatial_solver,\n\n par.simtime,par.tmOOA,par.tmOOA);\n\n rep.errorTest(\"NG RT_all_sources_levels: pass 2 BC-int\",0,err);\n\n#ifdef TEST_INT\n\n cout <<\"doing raytracing for level \"<<l<<\"\\n\";\n\n#endif\n\n err = do_ongrid_raytracing(par,grid,l);\n\n //err = do_offgrid_raytracing(par,grid,l);\n\n rep.errorTest(\"NG RT_all_sources_levels: pass 2 RT\",0,err);\n\n#ifdef TEST_INT\n\n cout <<\"moving on to next level.\\n\";\n\n#endif\n\n }\n\n rep.errorTest(\"sim_control_NG: internal boundary update\",0,err);\n\n // --------------------------------------------------------------\n", "file_path": "source/sim_control/sim_control_NG.cpp", "rank": 91, "score": 51.793825173585624 }, { "content": "/// \\file RT_MPI_boundaries.cpp\n\n/// \\brief Class definitions for raytracing across a parallel\n\n/// decomposed domain, by communicating with neighbouring MPI\n\n/// processes\n\n/// \\author Jonathan Mackey\n\n/// \n\n/// Modifications :\\n\n\n/// - 2018.08.09 JM: moved code from parallel uniform grid.\n\n\n\n\n\n#include \"defines/functionality_flags.h\"\n\n#include \"defines/testing_flags.h\"\n\n\n\n#include \"tools/reporting.h\"\n\n#include \"tools/mem_manage.h\"\n\n#include \"boundaries/RT_MPI_boundaries.h\"\n\n#include <iostream>\n\n#include <vector>\n\nusing namespace std;\n\n\n", "file_path": "source/boundaries/RT_MPI_boundaries.cpp", "rank": 92, "score": 51.45051592149932 }, { "content": "#endif // TESTING\n\n\n\n#include \"grid/grid_base_class.h\"\n\n#include \"grid/stellar_wind_angle.h\"\n\n#include \"microphysics/microphysics_base.h\"\n\n#include <sstream>\n\n\n\n\n\n#include \"constants.h\"\n\n#include <iostream>\n\n#include <cmath>\n\n#include <vector>\n\n#include <cstdio>\n\nusing namespace std;\n\n\n\n\n\n// ##################################################################\n\n// ##################################################################\n\n\n\n\n", "file_path": "source/grid/stellar_wind_angle.cpp", "rank": 93, "score": 51.22969782736951 }, { "content": "\n\n // ----------------------------------------------------------------\n\n for (int l=0;l<SimPM.grid_nlevels;l++) {\n\n err = assign_boundary_data(SimPM, l, grid[l]);\n\n rep.errorTest(\"NG_INIT::assign_boundary_data\",0,err);\n\n }\n\n // ----------------------------------------------------------------\n\n\n\n\n\n\n\n // ----------------------------------------------------------------\n\n for (int l=0; l<SimPM.grid_nlevels; l++) {\n\n#ifdef TESTING\n\n cout <<\"updating external boundaries for level \"<<l<<\"\\n\";\n\n#endif\n\n err += TimeUpdateExternalBCs(SimPM,l,grid[l], spatial_solver,\n\n SimPM.simtime,SimPM.tmOOA,SimPM.tmOOA);\n\n }\n\n rep.errorTest(\"NG_INIT: error from bounday update\",0,err);\n\n // ----------------------------------------------------------------\n", "file_path": "source/sim_control/sim_control_NG.cpp", "rank": 95, "score": 50.60989612168334 }, { "content": " // --------------------------------------------------------------\n\n // ----------------------------------------------------------------\n\n // update fine-to-coarse level boundaries\n\n for (int l=SimPM.grid_nlevels-1; l>=0; l--) {\n\n if (l<SimPM.grid_nlevels-1) {\n\n#ifdef TEST_INT\n\n cout <<\"NG_MPI Receiving F2C boundaries for level \"<<l<<\"\\n\";\n\n#endif\n\n for (size_t i=0;i<grid[l]->BC_bd.size();i++) {\n\n if (grid[l]->BC_bd[i]->itype == FINE_TO_COARSE_RECV) {\n\n err += BC_update_FINE_TO_COARSE_RECV(SimPM,spatial_solver,\n\n l,grid[l]->BC_bd[i],2,2);\n\n }\n\n }\n\n }\n\n\n\n#ifdef TEST_INT\n\n cout <<\"NG_MPI raytracing level \"<<l<<\"\\n\";\n\n#endif\n\n err = update_evolving_RT_sources(\n", "file_path": "source/sim_control/sim_control_NG_MPI.cpp", "rank": 96, "score": 50.49503638189784 }, { "content": " /// Returns dimensionality of grid.\n\n virtual int Ndim() const {return(G_ndim);}\n\n\n\n /// Returns length of state vectors.\n\n virtual int Nvar() const {return(G_nvar);}\n\n\n\n /// Returns number of grid cells along given axis, excluding\n\n /// boundary cells.\n\n virtual int NG(\n\n const enum axes ax ///< axis of grid.\n\n ) const {return G_ng[ax];} \n\n \n\n /// Returns number of grid cells along given axis, including\n\n /// boundary cells.\n\n virtual int NG_All(\n\n const enum axes ax ///< axis of grid.\n\n ) const {return G_ng_all[ax];}\n\n\n\n /// Returns x/y/z lower boundary of grid in code units.\n\n virtual double Xmin(enum axes a) const\n", "file_path": "source/grid/uniform_grid.h", "rank": 97, "score": 49.795141172272665 }, { "content": "/// units) and removed STARBENCH1 boundary.\n\n/// - 2018.05.10 JM: Moved boundary assignment to setup_fixed_grid,\n\n/// and boundary updates to update_boundaries.cpp\n\n\n\n#include \"defines/functionality_flags.h\"\n\n#include \"defines/testing_flags.h\"\n\n\n\n\n\n#include \"grid/uniform_grid.h\"\n\n#include \"tools/reporting.h\"\n\n#include \"tools/mem_manage.h\"\n\n#include \"constants.h\"\n\n#include <fstream>\n\n#include <iostream>\n\nusing namespace std;\n\n\n\n\n\n\n\n//#define TEST_BC89FLUX\n\n//#define BC_DEBUG\n", "file_path": "source/grid/uniform_grid.cpp", "rank": 98, "score": 49.77457711814749 }, { "content": "/// \\file NG_MPI_fine_to_coarse_boundaries.h\n\n/// \\brief Class declaration for NG_fine_to_coarse boundaries\n\n/// \\author Jonathan Mackey\n\n/// \n\n/// Modifications :\\n\n\n/// - 2018.08.24 JM: writing parallel algorithms\n\n\n\n#ifndef NG_MPI_FINE_TO_COARSE_BOUNDARIES_H\n\n#define NG_MPI_FINE_TO_COARSE_BOUNDARIES_H\n\n\n\n#include \"defines/functionality_flags.h\"\n\n#include \"defines/testing_flags.h\"\n\n\n\n#include \"sim_params.h\"\n\n#include \"boundaries/boundaries.h\"\n\n#include \"boundaries/NG_fine_to_coarse_boundaries.h\"\n\n#include \"grid/grid_base_class.h\"\n\n#include \"spatial_solvers/solver_eqn_base.h\"\n\n\n\n\n\n///\n\n/// Implements NG_fine_to_coarse boundaries for a uniform grid,\n\n/// parallelised with MPI. The fine-level data are averaged and\n\n/// sent to the coarse-level grid, where they replace whatever\n\n/// was calculated on the coarse grid.\n\n/// This class is set up on both fine and coarse grids, and one\n\n/// calls the send function and the other the receive function.\n\n///\n", "file_path": "source/boundaries/NG_MPI_fine_to_coarse_boundaries.h", "rank": 99, "score": 49.72792609013027 } ]
C++
milk/supervised/_lasso.cpp
aflaxman/milk
252806fd081dc1b3c7fe34b14f9e7a4b646e0b49
#include <iostream> #include <memory> #include <cmath> #include <random> #include <cassert> #include <queue> #include <eigen3/Eigen/Dense> using namespace Eigen; extern "C" { #include <Python.h> #include <numpy/ndarrayobject.h> } namespace { template <typename T> int random_int(T& random, const int max) { std::uniform_int_distribution<int> dist(0, max - 1); return dist(random); } inline float soft(const float val, const float lam) { return std::copysign(std::fdim(std::fabs(val), lam), val); } typedef Map<Matrix<float, Dynamic, Dynamic, RowMajor>, Aligned> MapXAf; bool has_nans(const MapXAf& X) { for (int i = 0; i != X.rows(); ++i) { for (int j = 0; j != X.cols(); ++j) { if (std::isnan(X(i,j))) return true; } } return false; } struct lasso_solver { lasso_solver(const MapXAf& X, const MapXAf& Y, const MapXAf& W, MapXAf& B, const int max_iter, const float lam, const float eps) :X(X) ,Y(Y) ,W(W) ,B(B) ,max_iter(max_iter) ,lam(lam) ,eps(eps) { } void next_coords(int& i, int& j) { ++j; if (j == B.cols()) { j = 0; ++i; if (i == B.rows()) { i = 0; } } } int solve() { Matrix<float, Dynamic, Dynamic, RowMajor> residuals; int i = 0; int j = -1; bool sweep = false; bool changed = false; assert(!has_nans(X)); assert(!has_nans(Y)); assert(!has_nans(B)); for (int it = 0; it != max_iter; ++it) { this->next_coords(i, j); if (i == 0 && j == 0) { if (sweep && !changed) { return it; } if (!changed) { sweep = true; residuals = Y - B*X; } else { sweep = false; } changed = false; } if (!sweep && B(i,j) == 0.0) continue; const float prev = B(i,j); assert(Y.cols() == W.cols()); assert(Y.cols() == X.cols()); assert(Y.cols() == residuals.cols()); const float x2 = (W.row(i).array()*X.row(j).array() * X.row(j).array()).sum(); const float xy = (W.row(i).array()*X.row(j).array() * residuals.row(i).array()).sum(); const float raw_step = (x2 == 0.0 ? 0.0 : xy/x2); const float best = soft(prev + raw_step, lam); const float step = best - prev; if (std::fabs(step) > eps) { assert(!std::isnan(best)); B(i,j) = best; residuals.row(i) -= step*X.row(j); changed = true; } } return max_iter; } std::mt19937 r; const MapXAf& X; const MapXAf& Y; const MapXAf& W; MapXAf& B; const int max_iter; const float lam; const float eps; }; MapXAf as_eigen(PyArrayObject* arr) { assert(PyArray_EquivTypenums(PyArray_TYPE(arr), NPY_FLOAT32)); assert(PyArray_ISCARRAY_RO(arr)); return MapXAf( static_cast<float*>(PyArray_DATA(arr)), PyArray_DIM(arr, 0), PyArray_DIM(arr, 1)); } const char* errmsg = "INTERNAL ERROR"; PyObject* py_lasso(PyObject* self, PyObject* args) { PyArrayObject* X; PyArrayObject* Y; PyArrayObject* W; PyArrayObject* B; int max_iter; float lam; float eps; if (!PyArg_ParseTuple(args, "OOOOiff", &X, &Y, &W, &B, &max_iter, &lam, &eps)) return NULL; if (!PyArray_Check(X) || !PyArray_ISCARRAY_RO(X) || !PyArray_Check(Y) || !PyArray_ISCARRAY_RO(Y) || !PyArray_Check(W) || !PyArray_ISCARRAY_RO(W) || !PyArray_Check(B) || !PyArray_ISCARRAY(B) || !PyArray_EquivTypenums(PyArray_TYPE(X), NPY_FLOAT32) || !PyArray_EquivTypenums(PyArray_TYPE(Y), NPY_FLOAT32) || !PyArray_EquivTypenums(PyArray_TYPE(W), NPY_FLOAT32) || !PyArray_EquivTypenums(PyArray_TYPE(B), NPY_FLOAT32)) { PyErr_SetString(PyExc_RuntimeError,errmsg); return 0; } MapXAf mX = as_eigen(X); MapXAf mY = as_eigen(Y); MapXAf mW = as_eigen(W); MapXAf mB = as_eigen(B); max_iter *= mB.size(); lasso_solver solver(mX, mY, mW, mB, max_iter, lam, eps); const int iters = solver.solve(); return Py_BuildValue("i", iters); } PyMethodDef methods[] = { {"lasso", py_lasso, METH_VARARGS , "Do NOT call directly.\n" }, {NULL, NULL,0,NULL}, }; const char * module_doc = "Internal Module.\n" "\n" "Do NOT use directly!\n"; } extern "C" void init_lasso() { import_array(); (void)Py_InitModule3("_lasso", methods, module_doc); }
#include <iostream> #include <memory> #include <cmath> #include <random> #include <cassert> #include <queue> #include <eigen3/Eigen/Dense> using namespace Eigen; extern "C" { #include <Python.h> #include <numpy/ndarrayobject.h> } namespace { template <typename T> int random_int(T& random, const int max) { std::uniform_int_distribution<int> dist(0, max - 1); return dist(random); } inline float soft(const float val, const float lam) { return std::copysign(std::fdim(std::fabs(val), lam), val); } typedef Map<Matrix<float, Dynamic, Dynamic, RowMajor>, Aligned> MapXAf; bool has_nans(const MapXAf& X) { for (int i = 0; i != X.rows(); ++i) { for (int j = 0; j != X.cols(); ++j) { if (std::isnan(X(i,j))) return true; } } return false; } struct lasso_solver { lasso_solver(const MapXAf& X, const MapXAf& Y, const MapXAf& W, MapXAf& B, const int max_iter, const float lam, const float eps) :X(X) ,Y(Y) ,W(W) ,B(B) ,max_iter(max_iter) ,lam(lam) ,eps(eps) { } void next_coords(int& i, int& j) { ++j; if (j == B.cols()) { j = 0; ++i; if (i == B.rows()) { i = 0; } } } int solve() { Matrix<float, Dynamic, Dynamic, RowMajor> residuals; int i = 0; int j = -1; bool
- B*X; } else { sweep = false; } changed = false; } if (!sweep && B(i,j) == 0.0) continue; const float prev = B(i,j); assert(Y.cols() == W.cols()); assert(Y.cols() == X.cols()); assert(Y.cols() == residuals.cols()); const float x2 = (W.row(i).array()*X.row(j).array() * X.row(j).array()).sum(); const float xy = (W.row(i).array()*X.row(j).array() * residuals.row(i).array()).sum(); const float raw_step = (x2 == 0.0 ? 0.0 : xy/x2); const float best = soft(prev + raw_step, lam); const float step = best - prev; if (std::fabs(step) > eps) { assert(!std::isnan(best)); B(i,j) = best; residuals.row(i) -= step*X.row(j); changed = true; } } return max_iter; } std::mt19937 r; const MapXAf& X; const MapXAf& Y; const MapXAf& W; MapXAf& B; const int max_iter; const float lam; const float eps; }; MapXAf as_eigen(PyArrayObject* arr) { assert(PyArray_EquivTypenums(PyArray_TYPE(arr), NPY_FLOAT32)); assert(PyArray_ISCARRAY_RO(arr)); return MapXAf( static_cast<float*>(PyArray_DATA(arr)), PyArray_DIM(arr, 0), PyArray_DIM(arr, 1)); } const char* errmsg = "INTERNAL ERROR"; PyObject* py_lasso(PyObject* self, PyObject* args) { PyArrayObject* X; PyArrayObject* Y; PyArrayObject* W; PyArrayObject* B; int max_iter; float lam; float eps; if (!PyArg_ParseTuple(args, "OOOOiff", &X, &Y, &W, &B, &max_iter, &lam, &eps)) return NULL; if (!PyArray_Check(X) || !PyArray_ISCARRAY_RO(X) || !PyArray_Check(Y) || !PyArray_ISCARRAY_RO(Y) || !PyArray_Check(W) || !PyArray_ISCARRAY_RO(W) || !PyArray_Check(B) || !PyArray_ISCARRAY(B) || !PyArray_EquivTypenums(PyArray_TYPE(X), NPY_FLOAT32) || !PyArray_EquivTypenums(PyArray_TYPE(Y), NPY_FLOAT32) || !PyArray_EquivTypenums(PyArray_TYPE(W), NPY_FLOAT32) || !PyArray_EquivTypenums(PyArray_TYPE(B), NPY_FLOAT32)) { PyErr_SetString(PyExc_RuntimeError,errmsg); return 0; } MapXAf mX = as_eigen(X); MapXAf mY = as_eigen(Y); MapXAf mW = as_eigen(W); MapXAf mB = as_eigen(B); max_iter *= mB.size(); lasso_solver solver(mX, mY, mW, mB, max_iter, lam, eps); const int iters = solver.solve(); return Py_BuildValue("i", iters); } PyMethodDef methods[] = { {"lasso", py_lasso, METH_VARARGS , "Do NOT call directly.\n" }, {NULL, NULL,0,NULL}, }; const char * module_doc = "Internal Module.\n" "\n" "Do NOT use directly!\n"; } extern "C" void init_lasso() { import_array(); (void)Py_InitModule3("_lasso", methods, module_doc); }
sweep = false; bool changed = false; assert(!has_nans(X)); assert(!has_nans(Y)); assert(!has_nans(B)); for (int it = 0; it != max_iter; ++it) { this->next_coords(i, j); if (i == 0 && j == 0) { if (sweep && !changed) { return it; } if (!changed) { sweep = true; residuals = Y
random
[ { "content": "struct Kmeans_Exception {\n\n Kmeans_Exception(const char* msg): msg(msg) { }\n\n const char* msg;\n\n\n\n};\n\nvoid assert_type_contiguous(PyArrayObject* array,int type) { \n\n if (!PyArray_Check(array) ||\n\n PyArray_TYPE(array) != type ||\n\n !PyArray_ISCONTIGUOUS(array)) {\n\n throw Kmeans_Exception(\"Arguments to kmeans don't conform to expectation. Are you calling this directly? This is an internal function!\");\n\n }\n\n}\n\n\n\ntemplate <typename ftype>\n\nint computecentroids(ftype* f, ftype* centroids, PyArrayObject* a_assignments, PyArrayObject* a_counts, const int N, const int Nf, const int k) {\n\n\n\n int zero_counts = 0;\n\n Py_BEGIN_ALLOW_THREADS\n\n const npy_int32* assignments = static_cast<npy_int32*>(PyArray_DATA(a_assignments));\n\n npy_int32* counts = static_cast<npy_int32*>(PyArray_DATA(a_counts));\n", "file_path": "milk/unsupervised/_kmeans.cpp", "rank": 0, "score": 81781.86270788717 }, { "content": "struct SOM_Exception {\n\n SOM_Exception(const char* msg): msg(msg) { }\n\n const char* msg;\n\n\n\n};\n\nvoid assert_type_contiguous(PyArrayObject* array,int type) { \n\n if (!PyArray_Check(array) ||\n\n PyArray_TYPE(array) != type ||\n\n !PyArray_ISCONTIGUOUS(array)) {\n\n throw SOM_Exception(\"Arguments to putpoints don't conform to expectation. Are you calling this directly? This is an internal function!\");\n\n }\n\n}\n\n\n\nvoid putpoints(PyArrayObject* grid, PyArrayObject* points, float L, int radius) {\n\n if (PyArray_NDIM(grid) != 3) throw SOM_Exception(\"grid should be three dimensional\");\n\n if (PyArray_NDIM(points) != 2) throw SOM_Exception(\"points should be two dimensional\");\n\n const int rows = PyArray_DIM(grid, 0);\n\n const int cols = PyArray_DIM(grid, 1);\n\n const int d = PyArray_DIM(grid, 2);\n\n const int n = PyArray_DIM(points, 0);\n", "file_path": "milk/unsupervised/_som.cpp", "rank": 2, "score": 81781.86270788717 }, { "content": "struct SMO_Exception {\n\n SMO_Exception(const char* msg): msg(msg) { }\n\n const char* msg;\n\n\n\n};\n\n\n", "file_path": "milk/supervised/_svm.cpp", "rank": 3, "score": 81781.86270788717 }, { "content": "struct Python_Exception { };\n\nvoid check_for_interrupts() {\n\n PyErr_CheckSignals();\n\n if (PyErr_Occurred()) {\n\n throw Python_Exception();\n\n }\n\n}\n\n\n", "file_path": "milk/supervised/_svm.cpp", "rank": 4, "score": 81781.86270788717 }, { "content": "# -*- coding: utf-8 -*-\n\n# Copyright (C) 2011, Luis Pedro Coelho <[email protected]>\n\n# vim: set ts=4 sts=4 sw=4 expandtab smartindent:\n\n# License: MIT. See COPYING.MIT file in the milk distribution\n\n\n\nfrom __future__ import division\n\nimport numpy as np\n\n\n", "file_path": "template.py", "rank": 5, "score": 45050.52839753289 }, { "content": "def residual_sum_squares(fmatrix,assignments,centroids,distance='euclidean',**kwargs):\n\n '''\n\n rss = residual_sum_squares(fmatrix, assignments, centroids, distance='euclidean', **kwargs)\n\n\n\n Computes residual sum squares\n\n\n\n Parameters\n\n ----------\n\n fmatrix : 2D ndarray\n\n feature matrix\n\n assignments : 1D ndarray\n\n Assignments array\n\n centroids : 2D ndarray\n\n centroids\n\n\n\n Returns\n\n -------\n\n rss : float\n\n residual sum squares\n\n '''\n\n if distance != 'euclidean':\n\n raise NotImplemented(\"residual_sum_squares only implemented for 'euclidean' distance\")\n\n rss = 0.0\n\n for k, c in enumerate(centroids):\n\n diff = fmatrix[assignments == k] - c\n\n diff = diff.ravel()\n\n rss += np.dot(diff, diff)\n", "file_path": "milk/unsupervised/kmeans.py", "rank": 6, "score": 40902.375110879664 }, { "content": " def fixW():\n", "file_path": "milk/unsupervised/nnmf/hoyer.py", "rank": 7, "score": 40894.81992822931 }, { "content": "def set_max_processors(value=None):\n\n '''\n\n set_max_processors(value=None)\n\n\n\n Set the maximum number of processors to ``value`` (or to the number of\n\n physical CPUs if ``None``).\n\n\n\n Note that this is valid for the current process and its children, but not\n\n the parent.\n\n\n\n Parameters\n\n ----------\n\n value : int, optional\n\n Number of processors to use. Defaults to number of CPUs (as returned by\n\n ``multiprocessing.cpu_count()``).\n\n '''\n\n global max_procs\n\n if value is None:\n\n value = multiprocessing.cpu_count()\n", "file_path": "milk/utils/parallel.py", "rank": 8, "score": 40893.92190527158 }, { "content": "def one_minus_max(model,pool):\n\n '''\n\n oneminus = one_minus_max(model,pool)\n\n\n\n oneminus[i] = 1 - max_L { P(pool_i == L) }\n\n\n\n Returns one minus the probability for the best label guess.\n\n '''\n\n def _minus1(labels, ps):\n\n return 1. - np.max(ps)\n", "file_path": "milk/active/uncertainty.py", "rank": 9, "score": 40892.08728397113 }, { "content": "def _solve_ecoc_model(codes, p):\n\n try:\n\n import scipy.optimize\n\n except ImportError:\n\n raise ImportError(\"milk.supervised.ecoc: fitting ECOC probability models requires scipy.optimize\")\n\n\n\n z,_ = scipy.optimize.nnls(codes.T, p)\n\n z /= z.sum()\n", "file_path": "milk/supervised/multi.py", "rank": 10, "score": 40885.999132876685 }, { "content": "def _solve_alpha(s,m,L2):\n\n sm = s-m\n\n s2 = np.dot(s,s)\n\n sm2 = np.dot(sm, sm)\n\n m2 = np.dot(m, m)\n\n dot = np.dot(m, sm)\n\n alpha = (-dot + np.sqrt(dot**2 - sm2*(m2-L2**2)))/sm2\n", "file_path": "milk/unsupervised/nnmf/hoyer.py", "rank": 11, "score": 40885.999132876685 }, { "content": "def test_random():\n\n R=numpy.random.RandomState(123)\n\n X=R.rand(10,3)\n\n X[:5]+=1.\n\n C=2\n\n Y=numpy.ones(10)\n\n Y[5:] *= -1\n\n Alphas,b=svm_learn_smo(X,Y,rbf,C)\n\n SVM=(X,Y,Alphas,b,C,rbf)\n\n assert_more_than_50(SVM,X,Y)\n\n\n\n Alphas,b=svm_learn_libsvm(X,Y,rbf,C)\n\n SVM=(X,Y,Alphas,b,C,rbf)\n", "file_path": "milk/tests/test_svm.py", "rank": 12, "score": 40877.75987724969 }, { "content": "def test_lam_zero():\n\n np.random.seed(2)\n\n for i in xrange(8):\n\n X = np.random.rand(24,2)\n\n Y = np.random.rand(1,2)\n\n B = milk.supervised.lasso(X,Y, lam=0.0)\n\n R = Y - np.dot(B,X)\n\n R = R.ravel()\n", "file_path": "milk/tests/test_lasso.py", "rank": 13, "score": 40154.01450772975 }, { "content": "def test_gridminimise_return():\n\n from milksets.wine import load\n\n features,labels = load()\n\n learner = fast_classifier()\n\n gridminimise(learner, features, labels, { 'ignore' : [0] })\n\n _,error = gridminimise(learner, features, labels, { 'ignore' : [0] }, return_value=True, nfolds=5)\n\n cmat,_ = milk.nfoldcrossvalidation(features, labels, learner=learner, nfolds=5)\n", "file_path": "milk/tests/test_gridsearch.py", "rank": 14, "score": 40154.01450772975 }, { "content": "def test_better_than_random():\n\n learner = milk.supervised.logistic.logistic_learner()\n\n features, labels = milksets.wine.load()\n\n model = learner.train(features, labels == 0)\n\n error = np.array([np.abs(model.apply(f)-(l == 0))\n\n for f,l in zip(features, labels)])\n", "file_path": "milk/tests/test_logistic.py", "rank": 15, "score": 40137.26349780379 }, { "content": "def test_cross_random():\n\n assert get_pyrandom(get_nprandom(1)).random() == get_pyrandom(get_nprandom(1)).random()\n", "file_path": "milk/tests/test_utils.py", "rank": 16, "score": 40137.26349780379 }, { "content": "// Copyright (C) 2010, Luis Pedro Coelho <[email protected]>\n\n// License: MIT\n\n\n\n#include <iostream>\n\n#include <memory>\n\n#include <cmath>\n\n#include <cassert>\n\nextern \"C\" {\n\n #include <Python.h>\n\n #include <numpy/ndarrayobject.h>\n\n}\n\n\n\n\n\nnamespace {\n\n\n\ntemplate <typename T>\n\ndouble set_entropy(const T* data, const int N, double* counts, long clen) {\n\n for (int i = 0; i != clen; ++i) counts[i] = 0.;\n\n\n\n for (int i = 0; i != N; ++i) {\n", "file_path": "milk/supervised/_tree.cpp", "rank": 20, "score": 22.736718967730123 }, { "content": "\n\n#include <cassert>\n\n#include <math.h>\n\n#include <iostream>\n\n#include <stdio.h>\n\n#include <list>\n\n#include <memory>\n\n#include <cmath>\n\n#include <vector>\n\n//#include <debug/vector>\n\n//#include <debug/list>\n\n//using __gnu_debug::vector;\n\n//using __gnu_debug::list;\n\n\n\nusing std::vector;\n\nusing std::list;\n\nextern \"C\" {\n\n #include <Python.h>\n\n #include <numpy/ndarrayobject.h>\n\n}\n", "file_path": "milk/supervised/_svm.cpp", "rank": 22, "score": 19.508707972828375 }, { "content": "def lasso_walk(X, Y, B=None, nr_steps=None, start=None, step=None, tol=None, return_lams=False):\n\n '''\n\n Bs = lasso_walk(X, Y, B={np.zeros()}, nr_steps={64}, start={automatically inferred}, step={.9}, tol=None, return_lams=False)\n\n Bs,lams = lasso_walk(X, Y, B={np.zeros()}, nr_steps={64}, start={automatically inferred}, step={.9}, tol=None, return_lams=True)\n\n\n\n Repeatedly solve LASSO Optimisation\n\n\n\n B* = arg min_B ½/n || Y - BX ||₂² + λ||B||₁\n\n\n\n for different values of λ.\n\n\n\n Parameters\n\n ----------\n\n X : ndarray\n\n Design matrix\n\n Y : ndarray\n\n Matrix of outputs\n\n B : ndarray, optional\n\n Starting values for approximation. This can be used for a warm start if\n\n you have an estimate of where the solution should be.\n\n start : float, optional\n\n first λ to use (default is ``np.abs(Y).max()``)\n\n nr_steps : int, optional\n\n How many steps in the path (default is 64)\n\n step : float, optional\n\n Multiplicative step to take (default is 0.9)\n\n tol : float, optional\n\n This is the tolerance parameter. It is passed to the lasso function\n\n unmodified.\n\n return_lams : bool, optional\n\n Whether to return the values of λ used (default: False)\n\n\n\n Returns\n\n -------\n\n Bs : ndarray\n\n '''\n\n if nr_steps is None:\n\n nr_steps = 64\n\n if step is None:\n\n step = .9\n\n if start is None:\n\n n = Y.size\n\n start = 0.5/n*np.nanmax(np.abs(Y))*np.abs(X).max()\n\n\n\n\n\n lam = start\n\n lams = []\n\n Bs = []\n\n for i in xrange(nr_steps):\n\n # The central idea is that each iteration is already \"warm\" and this\n\n # should be faster than starting from zero each time\n\n B = lasso(X, Y, B, lam=lam, tol=tol)\n\n lams.append(lam)\n\n Bs.append(B.copy())\n\n lam *= step\n\n if return_lams:\n\n return np.array(Bs), np.array(lams)\n", "file_path": "milk/supervised/lasso.py", "rank": 23, "score": 18.962444174466764 }, { "content": "// Copyright (C) 2011, Luis Pedro Coelho <[email protected]>\n\n// License: MIT\n\n\n\n#include <iostream>\n\n#include <memory>\n\n#include <cmath>\n\n#include <cassert>\n\nextern \"C\" {\n\n #include <Python.h>\n\n #include <numpy/ndarrayobject.h>\n\n}\n\n\n\n\n\nnamespace {\n\n\n\ntemplate <typename T>\n\nint perceptron(PyArrayObject* data_arr, const long* labels, PyArrayObject* weights_arr, double eta) {\n\n const T* data = reinterpret_cast<T*>(PyArray_DATA(data_arr));\n\n T* weights = reinterpret_cast<T*>(PyArray_DATA(weights_arr));\n\n const int N0 = PyArray_DIM(data_arr, 0);\n", "file_path": "milk/supervised/_perceptron.cpp", "rank": 25, "score": 17.486767324042187 }, { "content": "#include <limits>\n\n#include <iostream>\n\n#include <cstdlib>\n\n\n\nextern \"C\" {\n\n #include <Python.h>\n\n #include <numpy/ndarrayobject.h>\n\n}\n\n\n\nnamespace {\n", "file_path": "milk/unsupervised/_som.cpp", "rank": 27, "score": 16.512710097653972 }, { "content": "def lasso(X, Y, B=None, lam=1., max_iter=None, tol=None):\n\n '''\n\n B = lasso(X, Y, B={np.zeros()}, lam=1. max_iter={1024}, tol={1e-5})\n\n\n\n Solve LASSO Optimisation\n\n\n\n B* = arg min_B ½/n || Y - BX ||₂² + λ||B||₁\n\n\n\n where $n$ is the number of samples.\n\n\n\n Milk uses coordinate descent, looping through the coordinates in order\n\n (with an active set strategy to update only non-zero βs, if possible). The\n\n problem is convex and the solution is guaranteed to be optimal (within\n\n floating point accuracy).\n\n\n\n Parameters\n\n ----------\n\n X : ndarray\n\n Design matrix\n\n Y : ndarray\n\n Matrix of outputs\n\n B : ndarray, optional\n\n Starting values for approximation. This can be used for a warm start if\n\n you have an estimate of where the solution should be. If used, the\n\n solution might be written in-place (if the array has the right format).\n\n lam : float, optional\n\n λ (default: 1.0)\n\n max_iter : int, optional\n\n Maximum nr of iterations (default: 1024)\n\n tol : float, optional\n\n Tolerance. Whenever a parameter is to be updated by a value smaller\n\n than ``tolerance``, that is considered a null update. Be careful that\n\n if the value is too small, performance will degrade horribly.\n\n (default: 1e-5)\n\n\n\n Returns\n\n -------\n\n B : ndarray\n\n '''\n\n X = np.ascontiguousarray(X, dtype=np.float32)\n\n Y = np.ascontiguousarray(Y, dtype=np.float32)\n\n if B is None:\n\n B = np.zeros((Y.shape[0],X.shape[0]), np.float32)\n\n else:\n\n B = np.ascontiguousarray(B, dtype=np.float32)\n\n if max_iter is None:\n\n max_iter = 1024\n\n if tol is None:\n\n tol = 1e-5\n\n if X.shape[0] != B.shape[1] or \\\n\n Y.shape[0] != B.shape[0] or \\\n\n X.shape[1] != Y.shape[1]:\n\n raise ValueError('milk.supervised.lasso: Dimensions do not match')\n\n if np.any(np.isnan(X)) or np.any(np.isnan(B)):\n\n raise ValueError('milk.supervised.lasso: NaNs are only supported in the ``Y`` matrix')\n\n W = np.ascontiguousarray(~np.isnan(Y), dtype=np.float32)\n\n Y = np.nan_to_num(Y)\n\n n = Y.size\n\n _lasso.lasso(X, Y, W, B, max_iter, float(2*n*lam), float(tol))\n", "file_path": "milk/supervised/lasso.py", "rank": 28, "score": 15.470877490804796 }, { "content": "def svm_learn_libsvm(features, labels, kernel, C, eps=1e-4, tol=1e-2, cache_size=(1<<20), alphas=None):\n\n '''\n\n Learn a svm classifier using LIBSVM optimiser\n\n\n\n This is a very raw interface. In general, you should use a class\n\n like svm_classifier.\n\n\n\n This uses the LIBSVM optimisation algorithm\n\n\n\n Parameters\n\n ----------\n\n X : ndarray\n\n data\n\n Y : ndarray\n\n labels in SVM format (ie Y[i] in (1,-1))\n\n kernel : kernel\n\n C : float\n\n eps : float, optional\n\n tol : float, optional\n\n cache_size : int, optional\n\n alphas : ndarray, optional\n\n\n\n Returns\n\n -------\n\n alphas : ndarray\n\n b : float\n\n '''\n\n if not np.all(np.abs(labels) == 1):\n\n raise ValueError('milk.supervised.svm.svm_learn_libsvm: Y[i] != (-1,+1)')\n\n assert len(features) == len(labels)\n\n n = len(labels)\n\n labels = labels.astype(np.int32)\n\n p = -np.ones(n, np.double)\n\n params = np.array([0,C,eps,tol], dtype=np.double)\n\n if alphas is None:\n\n alphas = np.zeros(n, np.double)\n\n elif alphas.dtype != np.double or len(alphas) != n:\n\n raise ValueError('milk.supervised.svm_learn_libsvm: alphas is in wrong format')\n\n _svm.eval_LIBSVM(features, labels, alphas, p, params, kernel, cache_size)\n", "file_path": "milk/supervised/svm.py", "rank": 30, "score": 14.845211072135072 }, { "content": " \"Do NOT use directly!\\n\";\n\n\n\n} // namespace\n\n\n\nextern \"C\"\n\nvoid init_perceptron()\n\n {\n\n import_array();\n\n (void)Py_InitModule3(\"_perceptron\", methods, module_doc);\n\n }\n\n\n", "file_path": "milk/supervised/_perceptron.cpp", "rank": 31, "score": 14.761664186769371 }, { "content": "#include <algorithm>\n\n\n\nextern \"C\" {\n\n #include <Python.h>\n\n #include <numpy/ndarrayobject.h>\n\n}\n\n\n\nnamespace {\n", "file_path": "milk/unsupervised/_kmeans.cpp", "rank": 32, "score": 14.071745176446376 }, { "content": "\n\n\n\nnamespace { \n\nconst double INF = HUGE_VAL;\n\n// This is a boost function\n\n// Copied here for convenience.\n\ntemplate <typename Iter>\n\ninline Iter prior(Iter it) {\n\n --it;\n\n return it;\n\n}\n\nusing std::max;\n\nusing std::min;\n\n\n\ntemplate <typename T>\n\nT median(T bot, T mid, T hi) {\n\n if (mid < bot) return bot;\n\n if (mid > hi) return hi;\n\n return mid;\n\n}\n\n\n", "file_path": "milk/supervised/_svm.cpp", "rank": 33, "score": 13.466583161402966 }, { "content": "def release_procs(n, count_current=True):\n\n '''\n\n release_procs(n, count_current=True)\n\n\n\n Returns ``n`` processors to the pool\n\n\n\n Parameters\n\n ----------\n\n n : int\n\n Number of processors to release\n\n count_current : bool, optional\n\n Whether the current processor is to be included in ``n`` (default: True)\n\n '''\n\n if count_current:\n\n n -= 1\n\n if n > 0:\n\n with _plock:\n", "file_path": "milk/utils/parallel.py", "rank": 34, "score": 13.17954486221544 }, { "content": "class svm_raw(object):\n\n '''\n\n svm_raw: classifier\n\n\n\n classifier = svm_raw(kernel, C, eps=1e-3, tol=1e-8)\n\n\n\n Parameters\n\n ----------\n\n kernel : callable\n\n the kernel to use. This should be a function that takes two data\n\n arguments see rbf_kernel and polynomial_kernel.\n\n C : float\n\n the C parameter\n\n eps : float, optional\n\n the precision to which to solve the problem (default 1e-3)\n\n tol : float, optional\n\n (|x| < tol) is considered zero\n\n '''\n\n def __init__(self, kernel=None, C=1., eps=1e-3, tol=1e-8):\n\n self.C = C\n\n self.kernel = kernel\n\n self.eps = eps\n\n self.tol = tol\n\n self.algorithm = 'libsvm'\n\n\n\n\n\n def train(self, features, labels, normalisedlabels=False, **kwargs):\n\n assert self.kernel is not None, 'milk.supervised.svm_raw.train: kernel not set!'\n\n assert self.algorithm in ('libsvm','smo'), 'milk.supervised.svm_raw: unknown algorithm (%s)' % self.algorithm\n\n assert not (np.isinf(self.C) or np.isnan(self.C)), 'milk.supervised.svm_raw: setting C to NaN or Inf causes problems.'\n\n features = np.asanyarray(features)\n\n if normalisedlabels:\n\n Y = labels.copy()\n\n else:\n\n Y,_ = normaliselabels(labels)\n\n assert Y.max() == 1, 'milk.supervised.svm_raw can only handle binary problems'\n\n Y *= 2\n\n Y -= 1\n\n kernel = self.kernel\n\n try:\n\n kernel = (self.kernel.kernel_nr_, self.kernel.kernel_arg_)\n\n features = np.ascontiguousarray(features, np.double)\n\n except AttributeError:\n\n pass\n\n if self.algorithm == 'smo':\n\n alphas,b = svm_learn_smo(features,Y,kernel,self.C,self.eps,self.tol)\n\n else:\n\n alphas,b = svm_learn_libsvm(features,Y,kernel,self.C,self.eps,self.tol)\n\n svsi = (alphas != 0)\n\n svs = features[svsi]\n\n w = alphas[svsi]\n\n Y = Y[svsi]\n\n Yw = w * Y\n\n return svm_raw_model(svs, Yw, b, self.kernel)\n\n\n\n def get_params(self):\n\n return self.C, self.eps,self.tol\n\n\n\n def set_params(self,params):\n\n self.C,self.eps,self.tol = params\n\n\n\n def set_option(self, optname, value):\n", "file_path": "milk/supervised/svm.py", "rank": 35, "score": 13.085314839280347 }, { "content": " if (take_step(i1,i2)) return true;\n\n }\n\n }\n\n return false;\n\n}\n\n\n\nvoid SMO::optimise() {\n\n b = 0;\n\n for (int i = 0; i != N; ++i) Alphas[i] = 0;\n\n int changed = 0;\n\n bool examineAll = true;\n\n //int iter = 0;\n\n while (changed || examineAll) {\n\n //std::cout << \"SMO::optimize loop: \" << iter++ << \"\\n\";\n\n check_for_interrupts();\n\n changed = 0;\n\n for (int i = 0; i != N; ++i) {\n\n if (examineAll || (Alphas[i] != 0 && Alphas[i] != C)) {\n\n changed += examine_example(i);\n\n }\n", "file_path": "milk/supervised/_svm.cpp", "rank": 36, "score": 12.311667405477465 }, { "content": " {\"computecentroids\", py_computecentroids, METH_VARARGS , \"Do NOT call directly.\\n\" },\n\n {NULL, NULL,0,NULL},\n\n};\n\n\n\nconst char * module_doc = \n\n \"Internal _kmeans Module.\\n\"\n\n \"\\n\"\n\n \"Do NOT use directly!\\n\";\n\n\n\n} // namespace\n\nextern \"C\"\n\nvoid init_kmeans()\n\n {\n\n import_array();\n\n (void)Py_InitModule3(\"_kmeans\", methods, module_doc);\n\n }\n\n\n", "file_path": "milk/unsupervised/_kmeans.cpp", "rank": 37, "score": 11.717888387523686 }, { "content": "def get_procs(desired=None, use_current=True):\n\n '''\n\n n = get_procs(desired=None, use_current=True)\n\n\n\n Get the up to ``desired`` processors (use None for no maximum).\n\n\n\n Parameters\n\n ----------\n\n desired : int, optional\n\n Number of processors you wish. By default, there is no maximum\n\n use_current: bool, optional\n\n Whether to count the current processor, True by default.\n\n '''\n\n if desired is None:\n\n desired = 1024 # This should last a few years\n\n n = (1 if use_current else 0)\n\n while n < desired:\n\n if get_proc():\n\n n += 1\n\n else:\n\n return n\n", "file_path": "milk/utils/parallel.py", "rank": 39, "score": 10.823283175904464 }, { "content": " if (clen > 8) delete [] counts;\n\n return PyFloat_FromDouble(H);\n\n}\n\n\n\nPyMethodDef methods[] = {\n\n {\"set_entropy\", py_set_entropy, METH_VARARGS , \"Do NOT call directly.\\n\" },\n\n {\"information_gain\", py_information_gain, METH_VARARGS , \"Do NOT call directly.\\n\" },\n\n {NULL, NULL,0,NULL},\n\n};\n\n\n\nconst char * module_doc =\n\n \"Internal Module.\\n\"\n\n \"\\n\"\n\n \"Do NOT use directly!\\n\";\n\n\n\n} // namespace\n\n\n\nextern \"C\"\n\nvoid init_tree()\n\n {\n\n import_array();\n\n (void)Py_InitModule3(\"_tree\", methods, module_doc);\n\n }\n\n\n", "file_path": "milk/supervised/_tree.cpp", "rank": 40, "score": 10.732720116601048 }, { "content": " if (Gmin_idx == -1) return true;\n\n\tif(Gmax+Gmax2 < eps) return true;\n\n\tout_i = Gmax_idx;\n\n\tout_j = Gmin_idx;\n\n\treturn false;\n\n}\n\n\n\nbool LIBSVM_Solver::be_shrunken(int i, const double Gmax1, const double Gmax2)\n\n{\n\n\tif(is_upper_bound(i)) {\n\n\t\tif(Y[i]==+1) return -G[i] > Gmax1;\n\n return -G[i] > Gmax2;\n\n\t} else if(is_lower_bound(i)) {\n\n\t\tif (Y[i]==+1) return G[i] > Gmax2;\n\n return G[i] > Gmax1;\n\n\t}\n\n return false;\n\n}\n\n\n\nvoid LIBSVM_Solver::do_shrinking()\n", "file_path": "milk/supervised/_svm.cpp", "rank": 41, "score": 10.512986438052785 }, { "content": " }\n\n bool is_upper_bound(int i) const { return alpha_status[i] == upper_bound; }\n\n bool is_lower_bound(int i) const { return alpha_status[i] == lower_bound; }\n\n bool is_free(int i) const { return alpha_status[i] == free; }\n\n void swap_index(int i, int j);\n\n void reconstruct_gradient();\n\n virtual bool select_working_set(int &i, int &j);\n\n virtual double calculate_rho();\n\n virtual void do_shrinking();\n\n private:\n\n bool be_shrunken(int i, double Gmax1, double Gmax2);\n\n void print_status() const;\t\n\n};\n\n\n\nvoid LIBSVM_Solver::swap_index(int i, int j)\n\n{\n\n // We *do not* swap in the cache or kernel\n\n // Therefore *all acesses* to the cache or kernel\n\n // must be of the form cache_.get_kernel(active_set[i])\n\n // instead of cache_.get_kernel(i)!\n", "file_path": "milk/supervised/_svm.cpp", "rank": 42, "score": 10.487260388592766 }, { "content": " vector<alpha_status_e> alpha_status;\n\n int active_size;\n\n vector<int> active_set;\n\n double *p;\n\n vector<double> G_bar;\t\t// gradient, if we treat free variables as 0\n\n bool unshrinked;\t// XXX\n\n bool shrinking;\n\n double tau;\n\n\n\n double get_C(int i) const {\n\n return C;\n\n //return (Y[i] > 0)? Cp : Cn;\n\n }\n\n void update_alpha_status(int i)\n\n {\n\n if(Alphas[i] >= get_C(i))\n\n alpha_status[i] = upper_bound;\n\n else if(Alphas[i] <= 0)\n\n alpha_status[i] = lower_bound;\n\n else alpha_status[i] = free;\n", "file_path": "milk/supervised/_svm.cpp", "rank": 43, "score": 10.267721939573995 }, { "content": "PyMethodDef methods[] = {\n\n {\"eval_SMO\",eval_SMO, METH_VARARGS , \"Do NOT call directly.\\n\" },\n\n {\"eval_LIBSVM\",eval_LIBSVM, METH_VARARGS , \"Do NOT call directly.\\n\" },\n\n {NULL, NULL,0,NULL},\n\n};\n\n\n\nconst char * module_doc = \n\n \"Internal SVM Module.\\n\"\n\n \"\\n\"\n\n \"Do NOT use directly!\\n\";\n\n\n\n} // namespace\n\n\n\nextern \"C\"\n\nvoid init_svm()\n\n {\n\n import_array();\n\n (void)Py_InitModule3(\"_svm\", methods, module_doc);\n\n }\n\n\n", "file_path": "milk/supervised/_svm.cpp", "rank": 44, "score": 9.95280078406802 }, { "content": " //std::cout << \"SMO::apply( \" << j << \" ): \" << sum << '\\n';\n\n return sum;\n\n}\n\nbool SMO::take_step(int i1, int i2) {\n\n //std::cout << \"take_step( \" << i1 << \", \" << i2 << \" );\\n\";\n\n if (i1 == i2) return false;\n\n const double alpha1 = Alphas[i1];\n\n const double alpha2 = Alphas[i2];\n\n const int y1 = Y[i1];\n\n const int y2 = Y[i2];\n\n double L, H;\n\n if (y1 != y2) {\n\n L = max(0.,alpha2-alpha1);\n\n H = min(C,C+alpha2-alpha1);\n\n } else {\n\n L = max(0.,alpha1+alpha2-C);\n\n H = min(C,alpha1+alpha2);\n\n }\n\n if (L == H) return false;\n\n const int s = y1*y2;\n", "file_path": "milk/supervised/_svm.cpp", "rank": 45, "score": 9.916469288352731 }, { "content": "def get_pyrandom(R):\n\n '''\n\n R = get_pyrandom(R)\n\n\n\n Returns a random.Random object based on R\n\n\n\n Parameters\n\n ----------\n\n R : can be one of:\n\n None : Returns the default numpy global state\n\n integer : Uses it as a seed for constructing a new random generator\n\n RandomState : returns R\n\n\n\n Returns\n\n -------\n\n R' : random.Random\n\n '''\n\n if R is None:\n\n return random.seed.im_self\n\n if type(R) is int:\n\n return random.Random(R)\n\n if type(R) is np.random.RandomState:\n\n return random.Random(R.randint(2**30))\n\n if type(R) is random.Random:\n\n return R\n", "file_path": "milk/utils/utils.py", "rank": 46, "score": 9.899677450747738 }, { "content": "def get_nprandom(R):\n\n '''\n\n R' = get_nprandom(R)\n\n\n\n Returns a numpy.RandomState from R\n\n\n\n Parameters\n\n ----------\n\n R : can be one of:\n\n None : Returns the default numpy global state\n\n integer : Uses it as a seed for constructing a new random generator\n\n RandomState : returns R\n\n\n\n Returns\n\n -------\n\n R' : np.RandomState\n\n '''\n\n if R is None:\n\n return np.random.mtrand._rand\n\n if type(R) == int:\n\n return np.random.RandomState(R)\n\n if type(R) is random.Random:\n\n return np.random.RandomState(R.randint(0, 2**30))\n\n if type(R) is np.random.RandomState:\n\n return R\n", "file_path": "milk/utils/utils.py", "rank": 47, "score": 9.499364519137352 }, { "content": " }\n\n }\n\n }\n\n const int start_y = std::max(0, min_y - radius);\n\n const int start_x = std::max(0, min_x - radius);\n\n const int end_y = std::min(rows, min_y + radius);\n\n const int end_x = std::min(rows, min_x + radius);\n\n \n\n for (int y = start_y; y != end_y; ++y) {\n\n for (int x = start_x; x != end_x; ++x) {\n\n const float L2 = L /(1 + std::abs(min_y - y) + std::abs(min_x - x));\n\n float* gpoint = static_cast<float*>(PyArray_GETPTR2(grid, y, x));\n\n for (int j = 0; j != d; ++j) {\n\n gpoint[j] *= (1.-L2);\n\n gpoint[j] += L2 * p[j];\n\n }\n\n }\n\n }\n\n }\n\n Py_END_ALLOW_THREADS\n", "file_path": "milk/unsupervised/_som.cpp", "rank": 48, "score": 9.281360415700274 }, { "content": "def get_proc():\n\n '''\n\n available = get_proc()\n\n\n\n Reserve a processor\n\n\n\n Returns\n\n -------\n\n available : bool\n\n True if a processor is available\n\n '''\n\n with _plock:\n\n if _used_procs.value >= max_procs:\n\n return False\n\n _used_procs.value += 1\n", "file_path": "milk/utils/parallel.py", "rank": 49, "score": 9.258200784502511 }, { "content": " long val = 0; \\\n\n if (PyArray_TYPE(labels ## index) == NPY_INT) val = *reinterpret_cast<const int*>(PyArray_GETPTR1(labels ## index, i)); \\\n\n else if (PyArray_TYPE(labels ## index) == NPY_LONG) val = *reinterpret_cast<const int*>(PyArray_GETPTR1(labels ## index, i)); \\\n\n if (val > clen) clen = val; \\\n\n } \\\n\n }\n\n GET_MAX(0);\n\n GET_MAX(1);\n\n ++clen;\n\n if (clen > 8) {\n\n counts = new(std::nothrow) double[clen];\n\n if (!counts) {\n\n PyErr_NoMemory();\n\n return 0;\n\n }\n\n } else {\n\n counts = counts_array;\n\n }\n\n const double N = N0 + N1;\n\n double H = - N0/N * set_entropy(labels0, counts, clen) - N1/N * set_entropy(labels1, counts, clen);\n", "file_path": "milk/supervised/_tree.cpp", "rank": 50, "score": 9.247053555685863 }, { "content": " if (PyArray_DIM(points, 1) != d) throw SOM_Exception(\"second dimension of points is not third dimension of grid\");\n\n\n\n Py_BEGIN_ALLOW_THREADS\n\n\n\n for (int i = 0; i != n; i++){\n\n const float* p = static_cast<float*>(PyArray_GETPTR1(points, i));\n\n int min_y = 0;\n\n int min_x = 0;\n\n float best = std::numeric_limits<float>::max();\n\n for (int y = 0; y != rows; ++y) {\n\n for (int x = 0; x != cols; ++x) {\n\n float dist = 0.;\n\n const float* gpoint = static_cast<float*>(PyArray_GETPTR2(grid, y, x));\n\n for (int j = 0; j != d; ++j) {\n\n dist += (p[j] - gpoint[j])*(p[j] - gpoint[j]);\n\n }\n\n if (dist < best) {\n\n best = dist;\n\n min_y = y;\n\n min_x = x;\n", "file_path": "milk/unsupervised/_som.cpp", "rank": 51, "score": 8.964440896994606 }, { "content": "def precision_recall(values, labels, mode='all', nr_steps=100):\n\n '''\n\n precision, recall = precision_recall(values, labels, mode='all', nr_steps=100)\n\n\n\n Compute a precision-recall curve.\n\n\n\n For a given threshold ``T``, consider that the positions where ``values >=\n\n T`` are classified as True. Precision is defined as ``TP/(TP+FP)``, while\n\n recall is defined as ``TP/(TP+FN)``.\n\n\n\n Parameters\n\n ----------\n\n values : sequence of numbers\n\n labels : boolean sequence\n\n mode : str, optional\n\n Which thresholds to consider. Either 'all' (i.e., use all values of\n\n `values` as possible thresholds), or 'step' (using `nr_steps`\n\n equidistant points from ``min(values)`` to ``max(values)``)\n\n nr_steps : integer, optional\n\n How many steps to use. Only meaningfule if ``mode == 'steps'``\n\n\n\n Returns\n\n -------\n\n precision : a sequence of floats\n\n recall : a sequence of floats\n\n\n\n Actually, ``2 x P`` array is returned.\n\n '''\n\n\n\n values = np.asanyarray(values)\n\n labels = np.asanyarray(labels)\n\n if len(values) != len(labels):\n\n raise ValueError('milk.measures.precision_recall: `values` must be of same length as `labels`')\n\n if mode == 'all':\n\n points = list(set(values))\n\n points.sort()\n\n elif mode == 'steps':\n\n points = np.linspace(values.min(), values.max(), nr_steps)\n\n else:\n\n raise ValueError('milk.measures.precision_recall: cannot handle mode: `%s`' % mode)\n\n true_pos = float(np.sum(labels))\n\n precision_recall = np.empty((len(points),2), np.float)\n\n\n\n for i,p in enumerate(points):\n\n selected = (values >= p)\n\n selected = labels[selected]\n\n precision_recall[i] = (np.mean(selected), np.sum(selected)/true_pos)\n", "file_path": "milk/measures/curves.py", "rank": 52, "score": 8.919692626723908 }, { "content": "def pca(X, zscore=True):\n\n '''\n\n Y,V = pca(X, zscore=True)\n\n\n\n Principal Component Analysis\n\n\n\n Performs principal component analysis. Returns transformed\n\n matrix and principal components\n\n\n\n Parameters\n\n ----------\n\n X : 2-dimensional ndarray\n\n data matrix\n\n zscore : boolean, optional\n\n whether to normalise to zscores (default: True)\n\n\n\n Returns\n\n -------\n\n Y : ndarray\n\n Transformed matrix (of same dimension as X)\n\n V : ndarray\n\n principal components\n\n '''\n\n if zscore:\n\n X = normalise.zscore(X)\n\n C = np.cov(X.T)\n\n w,v = linalg.eig(C)\n\n Y = np.dot(v,X.T).T\n", "file_path": "milk/unsupervised/pca.py", "rank": 53, "score": 8.633676324055042 }, { "content": " cache_iter[idx]=prior(cache_lru.end());\n\n return cache_[idx];\n\n}\n\n\n\ndouble* KernelCache::get_diag() {\n\n if (!dcache_) {\n\n dcache_ = new double[N_];\n\n for (int i = 0; i != N_; ++i) {\n\n if (cache_[i]) dcache_[i] = cache_[i][i];\n\n else dcache_[i] = do_kernel(i,i);\n\n }\n\n }\n\n return dcache_;\n\n}\n\n\n\n\n\n/***\n\n * Returns the value of Kernel(X_i1, X_i2).\n\n * Uses the cache if possible, but does not update it.\n\n */\n", "file_path": "milk/supervised/_svm.cpp", "rank": 54, "score": 8.611856938336125 }, { "content": " } catch (const SOM_Exception& exc) {\n\n PyErr_SetString(PyExc_RuntimeError,exc.msg);\n\n return 0;\n\n } catch (...) {\n\n PyErr_SetString(PyExc_RuntimeError,\"Some sort of exception in putpoints.\");\n\n return 0;\n\n }\n\n}\n\n\n\nPyMethodDef methods[] = {\n\n {\"putpoints\", py_putpoints, METH_VARARGS , \"Do NOT call directly.\\n\" },\n\n {NULL, NULL,0,NULL},\n\n};\n\n\n\nconst char * module_doc = \n\n \"Internal SOM Module.\\n\"\n\n \"\\n\"\n\n \"Do NOT use directly!\\n\";\n\n\n\n} // namespace\n\nextern \"C\"\n\nvoid init_som()\n\n {\n\n import_array();\n\n (void)Py_InitModule3(\"_som\", methods, module_doc);\n\n }\n\n\n", "file_path": "milk/unsupervised/_som.cpp", "rank": 55, "score": 8.485058505070317 }, { "content": " if ( ( (r2 < -tol) && (alpha2 < C) ) ||\n\n ( (r2 > tol) && (alpha2 > 0) )){\n\n int best_i1 = -1;\n\n double bestE = -1;\n\n\n\n for (int i = 0; i != N; ++i) {\n\n if (Alphas[i] != 0 && Alphas[i] != C) {\n\n double dE = E2-get_error(i);\n\n if (dE < 0.) dE = -dE;\n\n if (dE > bestE) {\n\n bestE=dE;\n\n best_i1 = i;\n\n }\n\n }\n\n }\n\n if (best_i1 != -1 && take_step(best_i1,i2)) return true;\n\n for (int i1 = 0; i1 != N; ++i1) {\n\n if (Alphas[i1] && Alphas[i1] != C && take_step(i1,i2)) return true;\n\n }\n\n for (int i1 = 0; i1 != N; ++i1) {\n", "file_path": "milk/supervised/_svm.cpp", "rank": 56, "score": 8.294251123402644 }, { "content": "def svm_simple(C, kernel):\n\n '''\n\n learner = svm_simple(C, kernel)\n\n\n\n Returns a one-against-one SVM based classifier with `C` and `kernel`\n\n\n\n Parameters\n\n ----------\n\n C : double\n\n C parameter\n\n kernel : kernel\n\n Kernel to use\n\n\n\n Returns\n\n -------\n\n learner : supervised learner\n\n\n\n See Also\n\n --------\n\n feature_selection_simple : Perform feature selection\n\n defaultlearner : feature selection and gridsearch for SVM parameters\n\n '''\n\n from . import svm\n\n from .multi import one_against_one\n", "file_path": "milk/supervised/defaultlearner.py", "rank": 57, "score": 8.252738440452971 }, { "content": " double& b;\n\n double C;\n\n int N;\n\n mutable KernelCache cache_;\n\n const double eps;\n\n const double tol;\n\n};\n\n\n\ndouble SMO::get_error(int j) const {\n\n return apply(j) - Y[j];\n\n}\n\n\n\ndouble SMO::apply(int j) const {\n\n double sum = -b;\n\n double* Kernel_Line = cache_.get_kline(j);\n\n for (int i = 0; i != N; ++i) {\n\n if (Alphas[i] != C) {\n\n sum += Y[i] * Alphas[i] * Kernel_Line[i];\n\n }\n\n }\n", "file_path": "milk/supervised/_svm.cpp", "rank": 58, "score": 8.231747877935453 }, { "content": "def pdist(X, Y=None, distance='euclidean2'):\n\n '''\n\n D = pdist(X, Y={X}, distance='euclidean2')\n\n\n\n Compute distance matrix::\n\n\n\n D[i,j] == np.sum( (X[i] - Y[j])**2 )\n\n\n\n Parameters\n\n ----------\n\n X : feature matrix\n\n Y : feature matrix (default: use `X`)\n\n distance : one of 'euclidean' or 'euclidean2' (default)\n\n\n\n Returns\n\n -------\n\n D : matrix of doubles\n\n '''\n\n # Use Dij = np.dot(Xi, Xi) + np.dot(Xj,Xj) - 2.*np.dot(Xi,Xj)\n\n if Y is None:\n\n D = np.dot(X, X.T)\n\n x2 = D.diagonal()\n\n y2 = x2\n\n else:\n\n D = np.dot(X, Y.T)\n\n x2 = np.array([np.dot(x,x) for x in X])\n\n y2 = np.array([np.dot(y,y) for y in Y])\n\n D *= -2.\n\n D += x2[:,np.newaxis]\n\n D += y2\n\n\n\n # Because of numerical imprecision, we might get negative numbers\n\n # (which cause problems down the road, e.g., when doing the sqrt):\n\n np.maximum(D, 0, D)\n\n if distance == 'euclidean':\n\n np.sqrt(D, D)\n", "file_path": "milk/unsupervised/pdist.py", "rank": 59, "score": 8.107892976559226 }, { "content": "def rand_arand_jaccard(recovered, labels):\n\n '''\n\n rand, a_rand, jaccard = rand_arand_jaccard(recovered, labels)\n\n\n\n Compute Rand, Adjusted Rand, and Jaccard indices\n\n\n\n These share most of the computation. Therefore, it is best to compute them\n\n together even if you are only going to use some.\n\n\n\n Parameters\n\n ----------\n\n recovered : sequence of int\n\n The recovered clusters\n\n labels : sequence of int\n\n Underlying labels\n\n\n\n Returns\n\n -------\n\n rand : float\n\n Rand index\n\n a_rand : float\n\n Adjusted Rand index\n\n jaccard : float\n\n Jaccard index\n\n\n\n References\n\n ----------\n\n http://en.wikipedia.org/wiki/Rand_index\n\n http://en.wikipedia.org/wiki/Jaccard_index\n\n '''\n\n\n\n from scipy.misc import comb\n\n recovered = np.asanyarray(recovered)\n\n labels = np.asanyarray(labels)\n\n contig,_,_ = np.histogram2d(recovered, labels,np.arange(max(recovered.max()+2,labels.max()+2)))\n\n A_0 = contig.sum(0)\n\n A_1 = contig.sum(1)\n\n Ai2 = np.sum(A_0*(A_0-1)/2.)\n\n Bi2 = np.sum(A_1*(A_1-1)/2.)\n\n n = A_0.sum()\n\n\n\n a = comb(contig.ravel(), 2).sum()\n\n b = comb(A_0, 2).sum()-a\n\n c = comb(A_1, 2).sum()-a\n\n d = comb(n, 2)-a-b-c\n\n rand = (a+d)/(a+b+c+d)\n\n jaccard = (a+d)/(b+c+d)\n\n\n\n index = np.sum(contig*(contig-1)/2)\n\n expected = Ai2*Bi2/n/(n-1)*2.\n\n maxindex = (Ai2+Bi2)/2.\n\n a_rand = (index-expected)/(maxindex-expected)\n\n\n", "file_path": "milk/measures/cluster_agreement.py", "rank": 60, "score": 7.892890893794099 }, { "content": "def closest(grid, f):\n\n '''\n\n y,x = closest(grid, f)\n\n\n\n Finds the coordinates of the closest point in the `grid` to `f`\n\n\n\n ::\n\n\n\n y,x = \\\\argmin_{y,x} { || grid[y,x] - f ||^2 }\n\n\n\n Parameters\n\n ----------\n\n grid : ndarray of shape Y,X,J\n\n self-organised map\n\n f : ndarray of shape J\n\n point\n\n\n\n Returns\n\n -------\n\n y,x : integers\n\n coordinates into `grid`\n\n '''\n\n delta = grid - f\n\n delta **= 2\n\n delta = delta.sum(2)\n", "file_path": "milk/unsupervised/som.py", "rank": 61, "score": 7.845805223214301 }, { "content": " struct SolutionInfo {\n\n double obj;\n\n double rho;\n\n double upper_bound_p;\n\n double upper_bound_n;\n\n double r;\t// for LIBSVM_Solver_NU\n\n };\n\n\n\n void optimise();\n\n protected:\n\n double* Alphas;\n\n int* Y;\n\n double& b;\n\n double C;\n\n const int N;\n\n LIBSVM_KernelCache cache_;\n\n const double eps;\n\n const double tol;\n\n vector<double> G;\t\t// gradient of objective function\n\n enum alpha_status_e { lower_bound, upper_bound, free};\n", "file_path": "milk/supervised/_svm.cpp", "rank": 62, "score": 7.770490962005666 }, { "content": " if (!PyArray_ISCARRAY(X)) {\n\n throw SMO_Exception(\"Dot Kernel used but not with CARRAY.\");\n\n }\n\n Py_INCREF(X);\n\n }\n\n\n\nDotKernel::~DotKernel() {\n\n Py_DECREF(X_);\n\n}\n\n\n\ndouble DotKernel::do_kernel(int i1, int i2) const {\n\n assert(i1 < N_);\n\n assert(i2 < N_);\n\n const double* data1 = static_cast<const double*>(PyArray_GETPTR1(X_,i1));\n\n const double* data2 = static_cast<const double*>(PyArray_GETPTR1(X_,i2));\n\n double dotsum = 0.;\n\n for (int i = 0; i != N1_; ++i) {\n\n dotsum += data1[i] * data2[i];\n\n }\n\n return dotsum;\n\n}\n\n\n", "file_path": "milk/supervised/_svm.cpp", "rank": 63, "score": 7.736004828674263 }, { "content": " throw SMO_Exception(\"RBF Kernel used, but not with numpy array.\");\n\n }\n\n if (!PyArray_ISCARRAY(X)) {\n\n throw SMO_Exception(\"RBF Kernel used but not with CARRAY.\");\n\n }\n\n Py_INCREF(X);\n\n }\n\n\n\nRBFKernel::~RBFKernel() {\n\n Py_DECREF(X_);\n\n}\n\n\n\ndouble RBFKernel::do_kernel(int i1, int i2) const {\n\n assert(i1 < N_);\n\n assert(i2 < N_);\n\n const double* data1 = static_cast<const double*>(PyArray_GETPTR1(X_,i1));\n\n const double* data2 = static_cast<const double*>(PyArray_GETPTR1(X_,i2));\n\n double sumdiff = 0.;\n\n for (int i = 0; i != N1_; ++i) {\n\n double diff = data1[i]-data2[i];\n\n sumdiff += diff * diff;\n\n }\n\n sumdiff *= ngamma_;\n\n double res = std::exp(sumdiff);\n\n return res;\n\n}\n\n\n", "file_path": "milk/supervised/_svm.cpp", "rank": 64, "score": 7.698616051011896 }, { "content": "def mds(features, ndims, zscore=False):\n\n '''\n\n X = mds(features, ndims, zscore=False)\n\n\n\n Euclidean Multi-dimensional Scaling\n\n\n\n Parameters\n\n ----------\n\n features : ndarray\n\n data matrix\n\n ndims : int\n\n Number of dimensions to return\n\n zscore : boolean, optional\n\n Whether to zscore the features (default: False)\n\n\n\n Returns\n\n -------\n\n X : ndarray\n\n array of size ``(m, ndims)`` where ``m = len(features)``\n\n '''\n\n if zscore:\n\n X = normalise.zscore(features)\n\n P2 = pdist(features)\n\n n = len(P2)\n\n J = np.eye(n) - (1./n)* np.ones((n,n))\n\n B = -.5 * np.dot(J,np.dot(P2,J))\n\n w,v = np.linalg.eig(B)\n\n\n\n\n\n w = w[:ndims]\n\n s = np.sign(w)\n\n w = np.abs(w).real\n\n w = np.diag(np.sqrt(s * w))\n\n X = np.dot(v[:,:ndims], w)\n", "file_path": "milk/unsupervised/pca.py", "rank": 65, "score": 7.697733802381151 }, { "content": "def sparse_nnmf(V, r, sparsenessW=None, sparsenessH=None, max_iter=10000, R=None):\n\n '''\n\n W,H = hoyer.sparse_nnmf(V, r, sparsenessW = None, sparsenessH = None, max_iter=10000, R=None)\n\n\n\n Implement sparse nonnegative matrix factorisation.\n\n\n\n Parameters\n\n ----------\n\n V : 2-D matrix\n\n input feature matrix\n\n r : integer\n\n number of latent features\n\n sparsenessW : double, optional\n\n sparseness contraint on W (default: no sparsity contraint)\n\n sparsenessH : double, optional\n\n sparseness contraint on H (default: no sparsity contraint)\n\n max_iter : integer, optional\n\n maximum nr of iterations (default: 10000)\n\n R : integer, optional\n\n source of randomness\n\n\n\n Returns\n\n -------\n\n W : 2-ndarray\n\n H : 2-ndarray\n\n\n\n Reference\n\n ---------\n\n \"Non-negative Matrix Factorisation with Sparseness Constraints\"\n\n by Patrik Hoyer\n\n in Journal of Machine Learning Research 5 (2004) 1457--1469\n\n '''\n\n \n\n n,m = V.shape\n\n R = get_nprandom(R)\n\n mu_W = .15\n\n mu_H = .15\n\n eps = 1e-8\n\n W = R.standard_normal((n,r))**2\n\n H = R.standard_normal((r,m))**2\n\n\n\n def fix(X, sparseness):\n\n for i in xrange(r):\n\n row = X[i]\n\n L2 = np.sqrt(np.dot(row, row))\n\n row /= L2\n\n X[i] = _project(row, _L1for(sparseness, row, 1.), 1.)\n\n\n\n def fixW():\n\n fix(W.T, sparsenessW)\n\n def fixH():\n\n fix(H, sparsenessH)\n\n\n\n if sparsenessW is not None: fixW()\n\n if sparsenessH is not None: fixH()\n\n for i in xrange(max_iter):\n\n if sparsenessW is not None:\n\n W -= mu_W * np.dot(np.dot(W,H)-V,H.T)\n\n fixW()\n\n else:\n\n updateW = np.dot(V,H.T)/(np.dot(W,np.dot(H,H.T))+eps)\n\n W *= updateW\n\n if sparsenessH is not None:\n\n H -= mu_H * np.dot(W.T,np.dot(W,H)-V)\n\n fixH()\n\n else:\n\n updateH = np.dot(W.T,V)/(np.dot(np.dot(W.T,W),H)+eps)\n\n H *= updateH\n", "file_path": "milk/unsupervised/nnmf/hoyer.py", "rank": 66, "score": 7.6455137973375304 }, { "content": "def plike(X, sigma2=None):\n\n '''\n\n L = plike(X, sigma2={guess based on X})\n\n\n\n Compute likelihood that any two objects come from the same distribution\n\n under a Gaussian distribution hypothesis::\n\n\n\n L[i,j] = exp( ||X[i] - X[j]||^2 / sigma2 )\n\n\n\n Parameters\n\n ----------\n\n X : ndarray\n\n feature matrix\n\n sigma2 : float, optional\n\n bandwidth\n\n\n\n Returns\n\n -------\n\n L : ndarray\n\n likelihood matrix\n\n\n\n See Also\n\n --------\n\n pdist : function\n\n Compute distances between objects\n\n '''\n\n\n\n L = pdist(X)\n\n if sigma2 is None:\n\n sigma2 = np.median(L)\n\n L /= -sigma2\n\n np.exp(L, L)\n", "file_path": "milk/unsupervised/pdist.py", "rank": 67, "score": 7.5237520361916275 }, { "content": " const int N1 = PyArray_DIM(data_arr, 1);\n\n int nr_errors = 0;\n\n for (int i = 0; i != N0; ++i, data += N1, ++labels) {\n\n T val = weights[0];\n\n for (int j = 0; j != N1; ++j) {\n\n val += weights[j+1] * data[j];\n\n }\n\n int ell = (val > 0);\n\n if (ell != *labels) {\n\n int pm = (*labels ? +1 : -1);\n\n ++nr_errors;\n\n T error = pm * eta * std::abs(pm-val);\n\n weights[0] += error;\n\n for (int j = 0; j != N1; ++j) {\n\n weights[j+1] += error*data[j];\n\n }\n\n }\n\n }\n\n return nr_errors;\n\n}\n", "file_path": "milk/supervised/_perceptron.cpp", "rank": 68, "score": 7.469009076310941 }, { "content": "def linearly_independent_subset(V, threshold=1.e-5, return_orthogonal_basis=False):\n\n '''\n\n subset = linearly_independent_subset(V, threshold=1.e-5)\n\n subset,U = linearly_independent_subset(V, threshold=1.e-5, return_orthogonal_basis=True)\n\n\n\n Discover a linearly independent subset of `V`\n\n\n\n Parameters\n\n ----------\n\n V : sequence of input vectors\n\n threshold : float, optional\n\n vectors with 2-norm smaller or equal to this are considered zero\n\n (default: 1e.-5)\n\n return_orthogonal_basis : Boolean, optional\n\n whether to return orthogonal basis set\n\n\n\n Returns\n\n -------\n\n subset : ndarray of integers\n\n indices used for basis\n\n U : 2-array\n\n orthogonal basis into span{V}\n\n\n\n Implementation Reference\n\n ------------------------\n\n Use Gram-Schmidt with a check for when the v_k is close enough to zero to ignore\n\n\n\n See http://en.wikipedia.org/wiki/Gram-Schmidt_process\n\n '''\n\n V = np.array(V, copy=True)\n\n orthogonal = []\n\n used = []\n\n for i,u in enumerate(V):\n\n for v in orthogonal:\n\n u -= np.dot(u,v)/np.dot(v,v) * v\n\n if np.dot(u,u) > threshold:\n\n orthogonal.append(u)\n\n used.append(i)\n\n if return_orthogonal_basis:\n\n return np.array(used),np.array(orthogonal)\n", "file_path": "milk/supervised/featureselection.py", "rank": 69, "score": 7.357202447008559 }, { "content": "def affinity_propagation(S, p=None, convit=30, maxit=200, damping=0.5, copy=True, R=0):\n\n \"\"\"Perform Affinity Propagation Clustering of data\n\n\n\n Parameters\n\n ----------\n\n S : array [n_points, n_points]\n\n Matrix of similarities between points\n\n p : array [n_points,] or float, optional\n\n Preferences for each point\n\n damping : float, optional\n\n Damping factor\n\n copy : boolean, optional\n\n If copy is False, the affinity matrix is modified inplace by the\n\n algorithm, for memory efficiency\n\n R : source of randomness\n\n\n\n Returns\n\n -------\n\n\n\n cluster_centers_indices : array [n_clusters]\n\n index of clusters centers\n\n\n\n labels : array [n_points]\n\n cluster labels for each point\n\n\n\n Notes\n\n -----\n\n See examples/plot_affinity_propagation.py for an example.\n\n\n\n Reference:\n\n Brendan J. Frey and Delbert Dueck, \"Clustering by Passing Messages\n\n Between Data Points\", Science Feb. 2007\n\n\n\n \"\"\"\n\n if copy:\n\n # Copy the affinity matrix to avoid modifying it inplace\n\n S = S.copy()\n\n\n\n n_points = S.shape[0]\n\n\n\n assert S.shape[0] == S.shape[1]\n\n\n\n if p is None:\n\n p = np.median(S)\n\n\n\n if damping < 0.5 or damping >= 1:\n\n raise ValueError('damping must be >= 0.5 and < 1')\n\n\n\n random_state = np.random.RandomState(R)\n\n\n\n # Place preferences on the diagonal of S\n\n S.flat[::(n_points+1)] = p\n\n\n\n A = np.zeros((n_points, n_points))\n\n R = np.zeros((n_points, n_points)) # Initialize messages\n\n\n\n # Remove degeneracies\n\n noise = random_state.randn(n_points, n_points)\n\n typeinfo = np.finfo(S.dtype)\n\n noise *= typeinfo.tiny*100\n\n S += noise\n\n del noise\n\n\n\n # Execute parallel affinity propagation updates\n\n e = np.zeros((n_points, convit))\n\n\n\n ind = np.arange(n_points)\n\n\n\n for it in range(maxit):\n\n Aold = A.copy()\n\n Rold = R.copy()\n\n A += S\n\n\n\n I = np.argmax(A, axis=1)\n\n Y = A[ind, I]#np.max(A, axis=1)\n\n\n\n A[ind, I] = typeinfo.min\n\n\n\n Y2 = np.max(A, axis=1)\n\n R = S - Y[:, np.newaxis]\n\n\n\n R[ind, I[ind]] = S[ind, I] - Y2\n\n\n\n Rold *= damping\n\n R *= (1-damping)\n\n R += Rold\n\n\n\n # Compute availabilities\n\n Rd = R.diagonal().copy()\n\n np.maximum(R, 0, R)\n\n R.flat[::n_points+1] = Rd\n\n\n\n A = np.sum(R, axis=0)[np.newaxis, :] - R\n\n\n\n dA = np.diag(A)\n\n A = np.minimum(A, 0)\n\n\n\n A.flat[::n_points+1] = dA\n\n\n\n Aold *= damping\n\n A *= (1-damping)\n\n A += Aold\n\n\n\n # Check for convergence\n\n E = (np.diag(A) + np.diag(R)) > 0\n\n e[:, it % convit] = E\n\n K = np.sum(E, axis=0)\n\n\n\n if it >= convit:\n\n se = np.sum(e, axis=1);\n\n unconverged = np.sum((se == convit) + (se == 0)) != n_points\n\n if (not unconverged and (K>0)) or (it==maxit):\n\n print \"Converged after %d iterations.\" % it\n\n break\n\n else:\n\n print \"Did not converge\"\n\n\n\n I = np.where(np.diag(A+R) > 0)[0]\n\n K = I.size # Identify exemplars\n\n\n\n if K > 0:\n\n c = np.argmax(S[:, I], axis=1)\n\n c[I] = np.arange(K) # Identify clusters\n\n # Refine the final set of exemplars and clusters and return results\n\n for k in range(K):\n\n ii = np.where(c==k)[0]\n\n j = np.argmax(np.sum(S[ii, ii], axis=0))\n\n I[k] = ii[j]\n\n\n\n c = np.argmax(S[:, I], axis=1)\n\n c[I] = np.arange(K)\n\n labels = I[c]\n\n # Reduce labels to a sorted, gapless, list\n\n cluster_centers_indices = np.unique(labels)\n\n labels = np.searchsorted(cluster_centers_indices, labels)\n\n else:\n\n labels = np.empty((n_points, 1))\n\n cluster_centers_indices = None\n\n labels.fill(np.nan)\n\n\n", "file_path": "milk/unsupervised/affinity.py", "rank": 70, "score": 7.344920051434625 }, { "content": "def repeated_kmeans(fmatrix,k,iterations,distance='euclidean',max_iter=1000,R=None,**kwargs):\n\n '''\n\n assignments,centroids = repeated_kmeans(fmatrix, k, repeats, distance='euclidean',max_iter=1000,**kwargs)\n\n\n\n Runs kmeans repeats times and returns the best result as evaluated\n\n according to distance\n\n\n\n See Also\n\n --------\n\n kmeans : runs kmeans once\n\n\n\n Parameters\n\n ----------\n\n fmatrix : feature matrix\n\n k : nr of centroids\n\n iterations : Nr of repetitions\n\n distance : 'euclidean' (default) or 'seuclidean'\n\n max_iter : Max nr of iterations per kmeans run\n\n R : random source\n\n\n\n Returns\n\n -------\n\n assignments : 1-D array of assignments\n\n centroids : centroids\n\n\n\n These are the same returns as the kmeans function\n\n '''\n\n kwargs['max_iter'] = max_iter\n", "file_path": "milk/unsupervised/kmeans.py", "rank": 71, "score": 7.199778653044675 }, { "content": "def gridminimise(learner, features, labels, params, measure=None, nfolds=10, return_value=False, train_kwargs=None, nprocs=None, origins=None):\n\n '''\n\n best = gridminimise(learner, features, labels, params, measure={0/1 loss}, nfolds=10, return_value=False, nprocs=None)\n\n best, value = gridminimise(learner, features, labels, params, measure={0/1 loss}, nfolds=10, return_value=True, nprocs=None)\n\n\n\n Grid search for the settings of parameters that maximises a given measure\n\n\n\n This function is equivalent to searching the grid, but does not actually\n\n search the whole grid.\n\n\n\n Parameters\n\n ----------\n\n learner : a classifier object\n\n features : sequence of features\n\n labels : sequence of labels\n\n params : dictionary of sequences\n\n keys are the options to change,\n\n values are sequences of corresponding elements to try\n\n measure : function, optional\n\n a function that takes labels and outputs and returns the loss.\n\n Default: 0/1 loss. This must be an *additive* function.\n\n nfolds : integer, optional\n\n nr of folds to run, default: 10\n\n return_value : boolean, optional\n\n Whether to return the error value as well. Default False\n\n train_kwargs : dict, optional\n\n Options that are passed to the train() method of the classifier, using\n\n the ``train(features, labels, **train_kwargs)`` syntax. Defaults to {}.\n\n nprocs : integer, optional\n\n Number of processors to use. By default, uses the\n\n ``milk.utils.parallel`` framework to check the number of\n\n processors.\n\n\n\n Returns\n\n -------\n\n best : a sequence of assignments\n\n value : float\n\n Only returned if ``return_value`` is true\n\n '''\n\n # The algorithm is as follows:\n\n #\n\n # for all assignments: error = 0, next_iteration = 0\n\n #\n\n # at each iteration:\n\n # look for assignment with smallest error\n\n # if that is done: return it\n\n # else: perform one more iteration\n\n #\n\n # When the function returns, that assignment has the lowest error of all\n\n # assignments and all the iterations are done. Therefore, other assignments\n\n # could only be worse even if we never computed the whole error!\n\n\n\n from ..measures.nfoldcrossvalidation import foldgenerator\n\n from ..utils import parallel\n\n if measure is None:\n\n from ..measures.measures import zero_one_loss\n\n measure = zero_one_loss\n\n if train_kwargs is None:\n\n train_kwargs = {}\n\n try:\n\n features = np.asanyarray(features)\n\n except:\n\n features = np.array(features, dtype=object)\n\n\n\n labels,_ = normaliselabels(labels)\n\n options = list(_allassignments(params))\n\n iteration = np.zeros(len(options), int)\n\n error = np.zeros(len(options), float)\n\n folds = [(Tr.copy(), Te.copy()) for Tr,Te in foldgenerator(labels, nfolds=nfolds, origins=origins)]\n\n # foldgenerator might actually decide on a smaller number of folds,\n\n # depending on the distribution of class sizes:\n\n nfolds = len(folds)\n\n assert nfolds\n\n if nprocs is None:\n\n nprocs = len(options)\n\n else:\n\n nprocs = min(nprocs, len(options))\n\n assert nprocs > 0, 'milk.supervised.gridminimise: nprocs <= 0!!'\n\n nprocs = parallel.get_procs(nprocs, use_current=True)\n\n\n\n executing = set()\n\n workers = []\n\n if nprocs > 1:\n\n inqueue = multiprocessing.Queue()\n\n outqueue = multiprocessing.Queue()\n\n for i in xrange(nprocs):\n\n inqueue.put((i,0))\n\n executing.add(i)\n\n\n\n w = Grid1(learner, features, labels, measure, train_kwargs, options, folds, inqueue, outqueue)\n\n w.start()\n\n workers.append(w)\n\n getnext = outqueue.get\n\n queuejob = lambda next, fold: inqueue.put( (next, fold) )\n\n else:\n\n worker = Grid1(learner, features, labels, measure, train_kwargs, options, folds, None, None)\n\n queue = []\n\n def queuejob(index,fold):\n\n queue.append((index,fold))\n\n def getnext():\n\n index,fold = queue.pop()\n\n return index, worker.execute_one(index,fold)\n\n queuejob(0,0)\n\n executing.add(0)\n\n\n\n try:\n\n while True:\n\n p,err = getnext()\n\n if p == 'error':\n\n raise RuntimeError(err)\n\n executing.remove(p)\n\n iteration[p] += 1\n\n error[p] += err\n\n for best in np.where(error == error.min())[0]:\n\n if iteration[best] == nfolds:\n\n if return_value:\n\n return options[best], error[best]\n\n return options[best]\n\n for next in error.argsort():\n\n if iteration[next] < nfolds and next not in executing:\n\n executing.add(next)\n\n queuejob(next, iteration[next])\n\n break\n\n finally:\n\n assert np.max(iteration) <= nfolds\n\n if len(workers):\n\n for w in workers:\n\n inqueue.put( ('shutdown', None) )\n\n inqueue.close()\n\n inqueue.join_thread()\n\n for w in workers:\n\n w.join()\n", "file_path": "milk/supervised/gridsearch.py", "rank": 72, "score": 7.162732232622813 }, { "content": "\t\t\tif(ui) {\n\n\t\t\t\tfor(int k=0;k<N;k++)\n\n\t\t\t\t\tG_bar[k] -= C_i * Q_i[active_set[k]];\n\n } else {\n\n\t\t\t\tfor(int k=0;k<N;k++)\n\n\t\t\t\t\tG_bar[k] += C_i * Q_i[active_set[k]];\n\n }\n\n\t\t}\n\n\n\n\t\tif(uj != is_upper_bound(j)) {\n\n\t\t\tQ_j = cache_.get_kline(active_set[j], N);\n\n\t\t\tif(uj) {\n\n\t\t\t\tfor(int k=0;k<N;k++)\n\n\t\t\t\t\tG_bar[k] -= C_j * Q_j[active_set[k]];\n\n } else {\n\n\t\t\t\tfor(int k=0;k<N;k++)\n\n\t\t\t\t\tG_bar[k] += C_j * Q_j[active_set[k]];\n\n }\n\n\t\t}\n\n\t}\n", "file_path": "milk/supervised/_svm.cpp", "rank": 73, "score": 7.043598298508641 }, { "content": " unsigned N = PyArray_DIM(Y,0);\n\n double& b = *static_cast<double*>(PyArray_GETPTR1(params,0));\n\n double C = *static_cast<double*>(PyArray_GETPTR1(params,1));\n\n double eps = *static_cast<double*>(PyArray_GETPTR1(params,2));\n\n double tol = *static_cast<double*>(PyArray_GETPTR1(params,3));\n\n LIBSVM_Solver optimiser(X,Yv,Alphas,pv,b,C,N,kernel,eps,tol,cache_size, true);\n\n optimiser.optimise();\n\n Py_RETURN_NONE;\n\n } catch (const Python_Exception&) {\n\n // if Python_Exception was thrown, then PyErr is already set.\n\n return 0;\n\n } catch (const SMO_Exception& exc) {\n\n PyErr_SetString(PyExc_RuntimeError,exc.msg);\n\n return 0;\n\n } catch (...) {\n\n PyErr_SetString(PyExc_RuntimeError,\"Some sort of exception in eval_LIBSVM.\");\n\n return 0;\n\n }\n\n}\n\n\n", "file_path": "milk/supervised/_svm.cpp", "rank": 74, "score": 7.02455029886915 }, { "content": " }\n\n\n\nPrecomputedKernel::~PrecomputedKernel() {\n\n Py_DECREF(X_);\n\n}\n\n\n\ndouble PrecomputedKernel::do_kernel(int i1, int i2) const {\n\n const double* data = static_cast<const double*>(PyArray_GETPTR2(X_,i1,i2));\n\n return *data;\n\n}\n\n\n\nstd::auto_ptr<KernelComputation> get_kernel(PyObject* X, PyObject* kernel) {\n\n typedef std::auto_ptr<KernelComputation> res_type;\n\n if (PyCallable_Check(kernel)) return res_type(new PyKernel(X, kernel, PySequence_Length(X)));\n\n if (!PyTuple_Check(kernel) || PyTuple_Size(kernel) != 2) throw SMO_Exception(\"Cannot parse kernel.\");\n\n PyObject* type = PyTuple_GET_ITEM(kernel,0);\n\n PyObject* arg = PyTuple_GET_ITEM(kernel,1);\n\n if (!PyInt_Check(type) || !PyFloat_Check(arg)) throw SMO_Exception(\"Cannot parse kernel (wrong types)\");\n\n long type_nr = PyInt_AsLong(type);\n\n double arg_value = PyFloat_AsDouble(arg);\n", "file_path": "milk/supervised/_svm.cpp", "rank": 75, "score": 6.8471762547824015 }, { "content": "def bayesian_significance(n, c0, c1):\n\n '''\n\n sig = bayesian_significance(n, c0, c1)\n\n\n\n Computes the Bayesian significance of the difference between a classifier\n\n that gets ``c0`` correct versus one that gets ``c1`` right on ``n``\n\n examples.\n\n\n\n Parameters\n\n ----------\n\n n : int\n\n Total number of examples\n\n c0 : int\n\n Examples that first classifier got correct\n\n c1 : int\n\n Examples that second classifier got correct\n\n\n\n Returns\n\n -------\n\n sig : float\n\n Significance value\n\n '''\n\n def _logp(r, n, c):\n\n return c*np.log(r)+(n-c)*np.log(1-r)\n\n r = np.linspace(.0001,.9999,100)\n\n lp0 = _logp(r,n,c0)\n\n lp1 = _logp(r,n,c1)\n\n mat = lp0 + lp1[:,np.newaxis]\n\n mat -= mat.max()\n\n mat = np.exp(mat)\n\n mat /= mat.sum()\n\n sig = np.triu(mat).sum()-mat.trace()/2.\n", "file_path": "milk/measures/measures.py", "rank": 76, "score": 6.745877302292726 }, { "content": " counts, \\\n\n N, Nf, k)) { \\\n\n Py_RETURN_TRUE; \\\n\n } \\\n\n Py_RETURN_FALSE;\n\n\n\n TRY_TYPE(NPY_FLOAT, float);\n\n TRY_TYPE(NPY_DOUBLE, double);\n\n }\n\n throw Kmeans_Exception(\"Cannot handle this type.\");\n\n } catch (const Kmeans_Exception& exc) {\n\n PyErr_SetString(PyExc_RuntimeError,exc.msg);\n\n return 0;\n\n } catch (...) {\n\n PyErr_SetString(PyExc_RuntimeError,\"Some sort of exception in computecentroids.\");\n\n return 0;\n\n }\n\n}\n\n\n\nPyMethodDef methods[] = {\n", "file_path": "milk/unsupervised/_kmeans.cpp", "rank": 77, "score": 6.6976871625693395 }, { "content": "def nfoldcrossvalidation(features, labels, nfolds=None, learner=None, origins=None, return_predictions=False, folds=None, initial_measure=0, classifier=None,):\n\n '''\n\n Perform n-fold cross validation\n\n\n\n cmatrix,names = nfoldcrossvalidation(features, labels, nfolds=10, learner={defaultclassifier()}, origins=None, return_predictions=False)\n\n cmatrix,names,predictions = nfoldcrossvalidation(features, labels, nfolds=10, learner={defaultclassifier()}, origins=None, return_predictions=True)\n\n\n\n cmatrix will be a N x N matrix, where N is the number of classes\n\n\n\n cmatrix[i,j] will be the number of times that an element of class i was\n\n classified as class j\n\n\n\n names[i] will correspond to the label name of class i\n\n\n\n Parameters\n\n ----------\n\n features : a sequence\n\n labels : an array of labels, where label[i] is the label corresponding to features[i]\n\n nfolds : integer, optional\n\n Nr of folds. Default: 10\n\n learner : learner object, optional\n\n learner should implement the train() method to return a model\n\n (something with an apply() method). defaultclassifier() by default\n\n This parameter used to be called `classifier` and that name is still supported\n\n\n\n origins : sequence, optional\n\n Origin ID (see foldgenerator)\n\n return_predictions : bool, optional\n\n whether to return predictions (default: False)\n\n folds : sequence of int, optional\n\n which folds to generate\n\n initial_measure : any, optional\n\n what initial value to use for the results reduction (default: 0)\n\n\n\n\n\n Returns\n\n -------\n\n cmatrix : ndarray\n\n confusion matrix\n\n names : sequence\n\n sequence of labels so that cmatrix[i,j] corresponds to names[i], names[j]\n\n predictions : sequence\n\n predicted output for each element\n\n '''\n\n import operator\n\n from .measures import confusion_matrix\n\n if len(features) != len(labels):\n\n raise ValueError('milk.measures.nfoldcrossvalidation: len(features) should match len(labels)')\n\n if classifier is not None:\n\n if learner is not None:\n\n raise ValueError('milk.nfoldcrossvalidation: Using both `learner` and `classifier` arguments. They are the same, but `learner` is preferred')\n\n learner = classifier\n\n if learner is None:\n\n from ..supervised.defaultclassifier import defaultclassifier\n\n learner = defaultclassifier()\n\n labels,names = normaliselabels(labels)\n\n if return_predictions:\n\n predictions = np.empty_like(labels)\n\n predictions.fill(-1) # This makes it clearer if there are bugs in the programme\n\n\n\n try:\n\n features = np.asanyarray(features)\n\n except:\n\n features = np.asanyarray(features, dtype=object)\n\n\n\n if origins is not None:\n\n origins = np.asanyarray(origins)\n\n\n\n nclasses = labels.max() + 1\n\n results = []\n\n measure = confusion_matrix\n\n train_kwargs = {}\n\n for trainingset,testingset in foldgenerator(labels, nfolds, origins=origins, folds=folds):\n\n if origins is not None:\n\n train_kwargs = { 'corigins' : origins[trainingset] }\n\n model = learner.train(features[trainingset], labels[trainingset], **train_kwargs)\n\n cur_preds = np.array([model.apply(f) for f in features[testingset]])\n\n if return_predictions:\n\n predictions[testingset] = cur_preds\n\n results.append(measure(labels[testingset], cur_preds))\n\n\n\n result = reduce(operator.add, results, initial_measure)\n\n if return_predictions:\n\n return result, names, predictions\n", "file_path": "milk/measures/nfoldcrossvalidation.py", "rank": 78, "score": 6.534281201083649 }, { "content": "def zscore(features, axis=0, can_have_nans=True, inplace=False):\n\n \"\"\"\n\n features = zscore(features, axis=0, can_have_nans=True, inplace=False)\n\n\n\n Returns a copy of features which has been normalised to zscores\n\n\n\n Parameters\n\n ----------\n\n features : ndarray\n\n 2-D input array\n\n axis : integer, optional\n\n which axis to normalise (default: 0)\n\n can_have_nans : boolean, optional\n\n whether ``features`` is allowed to have NaNs (default: True)\n\n inplace : boolean, optional\n\n Whether to operate inline (i.e., potentially change the input array).\n\n Default is False\n\n\n\n Returns\n\n -------\n\n features : ndarray\n\n zscored version of features\n\n \"\"\"\n\n if features.ndim != 2:\n\n raise('milk.unsupervised.zscore: Can only handle 2-D arrays')\n\n if not inplace:\n\n features = features.copy()\n\n if can_have_nans:\n\n mu = _nanmean(features, axis)\n\n sigma = _nanstd(features, axis)\n\n else:\n\n mu = features.mean(axis)\n\n sigma = np.std(features, axis)\n\n sigma[sigma == 0] = 1.\n\n if axis == 0:\n\n features -= mu\n\n features /= sigma\n\n elif axis == 1:\n\n features -= mu[:,None]\n\n features /= sigma[:,None]\n", "file_path": "milk/unsupervised/normalise.py", "rank": 79, "score": 6.4560031591950064 }, { "content": " # if Alphas[i] in (0,C):\n\n # continue\n\n # elif i == i1 or i == i2:\n\n # E[i] = 0\n\n # else:\n\n # E[i] += y1*(a1-alpha1)*kernel_apply(i1,i)+y2*(a2-alpha2)*kernel_apply(i2,i) + (b-new_b) # Eq. (12.11)\n\n #E[i1]=f_at(i1)-y1\n\n #E[i2]=f_at(i2)-y2\n\n */\n\n b = new_b;\n\n return true;\n\n}\n\n\n\nbool SMO::examine_example(int i2) {\n\n //std::cout << \"examine_example( \" << i2 << \" ) \" << std::endl;\n\n const int y2 = Y[i2];\n\n const double alpha2 = Alphas[i2];\n\n const double E2 = get_error(i2);\n\n const double r2 = E2 * y2;\n\n //#print 'alpha2', alpha2, 'E2', E2, 'r2', r2\n", "file_path": "milk/supervised/_svm.cpp", "rank": 80, "score": 6.357332916522112 }, { "content": "def rank_corr(features, labels):\n\n '''\n\n rs = rank_corr(features, labels)\n\n\n\n Computes the following expression::\n\n\n\n rs[i] = max_e COV²(rank(features[:,i]), labels == e)\n\n\n\n This is appropriate for numeric features and categorical labels.\n\n\n\n Parameters\n\n ----------\n\n features : ndarray\n\n feature matrix\n\n labels : sequence\n\n\n\n Returns\n\n -------\n\n rs : ndarray of float\n\n rs are the rank correlations\n\n '''\n\n features = np.asanyarray(features)\n\n labels = np.asanyarray(labels)\n\n\n\n n = len(features)\n\n ranks = features.argsort(0)\n\n ranks = ranks.astype(float)\n\n binlabels = np.array([(labels == ell) for ell in set(labels)], dtype=float)\n\n mx = ranks.mean(0)\n\n my = binlabels.mean(1)\n\n sx = ranks.std(0)\n\n sy = binlabels.std(1)\n\n\n\n r = np.dot(binlabels,ranks)\n\n r -= np.outer(n*my, mx)\n\n r /= np.outer(sy, sx)\n\n r /= n # Use n [instead of n-1] to match numpy's corrcoef\n\n r **= 2\n", "file_path": "milk/supervised/featureselection.py", "rank": 81, "score": 6.145054897784464 }, { "content": "{\n\n\tdouble Gmax1 = -INF;\t\t// max { -y_i * grad(f)_i | i in I_up(\\alpha) }\n\n\tdouble Gmax2 = -INF;\t\t// max { y_i * grad(f)_i | i in I_low(\\alpha) }\n\n\n\n\t// find maximal violating pair first\n\n\tfor(int i=0;i<active_size;i++) {\n\n\t\tif(Y[i]==+1)\t{\n\n\t\t\tif(!is_upper_bound(i)) Gmax1 = max(-G[i],Gmax1);\n\n\t\t\tif(!is_lower_bound(i)) Gmax2 = max( G[i],Gmax2);\n\n\t\t} else\t{\n\n\t\t\tif(!is_upper_bound(i)) Gmax2 = max(-G[i],Gmax2);\n\n\t\t\tif(!is_lower_bound(i)) Gmax1 = max( G[i],Gmax1);\n\n\t\t}\n\n\t}\n\n\n\n\t// shrink\n\n\tfor(int i=0;i<active_size;++i) {\n\n\t\tif (be_shrunken(i, Gmax1, Gmax2)) {\n\n\t\t\t--active_size;\n\n\t\t\twhile (active_size > i) {\n", "file_path": "milk/supervised/_svm.cpp", "rank": 82, "score": 6.138118760519297 }, { "content": "def BIC(fmatrix, assignments, centroids, model='one_variance', covs=None):\n\n '''\n\n B = BIC(fmatrix, assignments, centroids, model='one_variance', covs={From Data})\n\n\n\n Compute Bayesian Information Criterion\n\n\n\n Parameters\n\n ----------\n\n fmatrix : 2d-array\n\n feature matrix\n\n assignments : 2d-array\n\n Centroid assignments\n\n centroids : sequence\n\n Centroids\n\n model : str, optional\n\n one of\n\n\n\n 'one_variance'\n\n All features share the same variance parameter sigma^2. Default\n\n\n\n 'full_covariance'\n\n Estimate a full covariance matrix or use covs[i] for centroid[i]\n\n covs : sequence or matrix, optional\n\n Covariance matrices. If None, then estimate from the data. If scalars\n\n instead of matrices are given, then s stands for sI (i.e., the diagonal\n\n matrix with s along the diagonal).\n\n\n\n Returns\n\n -------\n\n B : float\n\n BIC value\n\n\n\n See Also\n\n --------\n\n AIC\n\n '''\n", "file_path": "milk/unsupervised/gaussianmixture.py", "rank": 83, "score": 6.087759822300129 }, { "content": "def nnmf(V, r, cost='norm2', max_iter=int(1e4), tol=1e-8, R=None):\n\n '''\n\n A,S = nnmf(X, r, cost='norm2', tol=1e-8, R=None)\n\n\n\n Implement Lee & Seung's algorithm\n\n\n\n Parameters\n\n ----------\n\n V : 2-ndarray\n\n input matrix\n\n r : integer\n\n nr of latent features\n\n cost : one of:\n\n 'norm2' : minimise || X - AS ||_2 (default)\n\n 'i-div' : minimise D(X||AS), where D is I-divergence (generalisation of K-L divergence)\n\n max_iter : integer, optional\n\n maximum number of iterations (default: 10000)\n\n tol : double\n\n tolerance threshold for early exit (when the update factor is with tol\n\n of 1., the function exits)\n\n R : integer, optional\n\n random seed\n\n\n\n Returns\n\n -------\n\n A : 2-ndarray\n\n S : 2-ndarray\n\n\n\n Reference\n\n ---------\n\n \"Algorithms for Non-negative Matrix Factorization\"\n\n by Daniel D Lee, Sebastian H Seung\n\n (available at http://citeseer.ist.psu.edu/lee01algorithms.html)\n\n '''\n\n # Nomenclature in the function follows lee & seung, while outside nomenclature follows \n\n eps = 1e-8\n\n n,m = V.shape\n\n R = get_nprandom(R)\n\n W = R.standard_normal((n,r))**2\n\n H = R.standard_normal((r,m))**2\n\n for i in xrange(max_iter):\n\n if cost == 'norm2':\n\n updateH = dot(W.T,V)/(dot(dot(W.T,W),H)+eps)\n\n H *= updateH\n\n updateW = dot(V,H.T)/(dot(W,dot(H,H.T))+eps)\n\n W *= updateW\n\n elif cost == 'i-div':\n\n raise NotImplementedError,'I-Div not implemented in lee_seung.nnmf'\n\n if True or (i % 10) == 0:\n\n max_update = max(updateW.max(),updateH.max())\n\n if abs(1.-max_update) < tol:\n\n break\n", "file_path": "milk/unsupervised/nnmf/lee_seung.py", "rank": 84, "score": 6.05488260504874 }, { "content": "class rf_learner(object):\n\n '''\n\n Random Forest Learner\n\n\n\n learner = rf_learner(rf=101, frac=.7)\n\n\n\n Attributes\n\n ----------\n\n rf : integer, optional\n\n Nr of trees to learn (default: 101)\n\n frac : float, optional\n\n Sample fraction\n\n R : np.random object\n\n Source of randomness\n\n '''\n\n def __init__(self, rf=101, frac=.7, R=None):\n\n self.rf = rf\n\n self.frac = frac\n\n self.R = get_nprandom(R)\n\n\n\n def train(self, features, labels, normalisedlabels=False, names=None, return_label=True, **kwargs):\n\n N,M = features.shape\n\n m = int(self.frac*M)\n\n n = int(self.frac*N)\n\n R = get_nprandom(kwargs.get('R', self.R))\n\n tree = milk.supervised.tree.tree_learner(return_label=return_label)\n\n forest = []\n\n if not normalisedlabels:\n\n labels,names = normaliselabels(labels)\n\n elif names is None:\n\n names = (0,1)\n\n for i in xrange(self.rf):\n\n forest.append(\n\n tree.train(*_sample(features, labels, n, R),\n\n **{'normalisedlabels' : True})) # This syntax is necessary for Python 2.5\n", "file_path": "milk/supervised/randomforest.py", "rank": 85, "score": 6.043137801327806 }, { "content": "class fisher_tuned_rbf_svm(object):\n\n '''\n\n F = fisher_tuned_rbf_svm(sigmas, base)\n\n\n\n Returns a wrapper classifier that uses RBF kernels automatically\n\n tuned using sigma_value_fisher.\n\n\n\n '''\n\n def __init__(self, sigmas, base):\n\n self.sigmas = sigmas\n\n self.base = base\n\n\n\n def train(self, features, labels, **kwargs):\n\n f = sigma_value_fisher(features, labels)\n\n fs = [f(s) for s in self.sigmas]\n\n self.sigma = self.sigmas[np.argmin(fs)]\n\n self.base.set_option('kernel',rbf_kernel(self.sigma))\n", "file_path": "milk/supervised/svm.py", "rank": 86, "score": 6.033317453043082 }, { "content": "def build_tree(features, labels, criterion, min_split=4, subsample=None, R=None, weights=None):\n\n '''\n\n tree = build_tree(features, labels, criterion, min_split=4, subsample=None, R=None, weights={all 1s})\n\n\n\n Parameters\n\n ----------\n\n features : sequence\n\n features to use\n\n labels : sequence\n\n labels\n\n criterion : function {labels} x {labels} -> float\n\n function to measure goodness of split\n\n min_split : integer\n\n minimum size to split on\n\n subsample : integer, optional\n\n if given, then, at each step, choose\n\n R : source of randomness, optional\n\n See `milk.util.get_pyrandom`\n\n weights : sequence, optional\n\n weight of instance (default: all the same)\n\n\n\n Returns\n\n -------\n\n tree : Tree\n\n '''\n\n assert len(features) == len(labels), 'build_tree: Nr of labels does not match nr of features'\n\n features = np.asanyarray(features)\n\n labels = np.asanyarray(labels, dtype=np.int)\n\n if subsample is not None:\n\n if subsample <= 0:\n\n raise ValueError('milk.supervised.tree.build_tree: `subsample` must be > 0.\\nDid you mean to use None to signal no subsample?')\n\n from ..utils import get_pyrandom\n\n R = get_pyrandom(R)\n\n\n\n def recursive(features, labels):\n\n N = float(len(labels))\n\n if N < min_split:\n\n return Leaf(labels.sum()/N, N)\n\n S = _split(features, labels, weights, criterion, subsample, R)\n\n if S is None:\n\n return Leaf(labels.sum()/N, N)\n\n i,thresh = S\n\n split = features[:,i] < thresh\n\n return Node(featid=i,\n\n featval=thresh,\n\n left =recursive(features[ split], labels[ split]),\n\n right=recursive(features[~split], labels[~split]))\n", "file_path": "milk/supervised/tree.py", "rank": 87, "score": 5.981323288215343 }, { "content": "};\n\n\n\nKernelCache::KernelCache(std::auto_ptr<KernelComputation> computation, int N, int cache_nr_floats):\n\n N_(N),\n\n computation_(computation),\n\n dcache_(0) {\n\n cache_ = new double*[N_];\n\n for (int i = 0; i != N_; ++i) cache_[i] = 0;\n\n cache_free_ = (cache_nr_floats/N_);\n\n cache_iter.resize(N_,cache_lru.end());\n\n}\n\n\n\nKernelCache::~KernelCache() {\n\n for (int i = 0; i != N_; ++i) delete [] cache_[i];\n\n delete [] cache_;\n\n delete [] dcache_;\n\n}\n\n\n\ndouble* KernelCache::get_kline(int idx, int s) {\n\n if (s == -1) s = N_;\n", "file_path": "milk/supervised/_svm.cpp", "rank": 88, "score": 5.920958058740846 }, { "content": " }\n\n if (examineAll) examineAll = false;\n\n else if (!changed) examineAll = true;\n\n }\n\n}\n\n\n\nvoid assert_type_contiguous(PyArrayObject* array,int type) { \n\n if (!PyArray_Check(array) ||\n\n PyArray_TYPE(array) != type ||\n\n !PyArray_ISCONTIGUOUS(array)) {\n\n throw SMO_Exception(\"Arguments to eval_(SMO|LIBSVM) don't conform to expectation. Are you calling this directly? This is an internal function!\");\n\n }\n\n}\n\n\n\nPyObject* eval_SMO(PyObject* self, PyObject* args) {\n\n try {\n\n PyObject* X;\n\n PyArrayObject* Y;\n\n PyArrayObject* Alphas0;\n\n PyArrayObject* params;\n", "file_path": "milk/supervised/_svm.cpp", "rank": 89, "score": 5.860703059677078 }, { "content": "\t\t\t\tif (!be_shrunken(active_size, Gmax1, Gmax2)) {\n\n\t\t\t\t\tswap_index(i,active_size);\n\n\t\t\t\t\tbreak;\n\n\t\t\t\t}\n\n\t\t\t\t--active_size;\n\n\t\t\t}\n\n\t\t}\n\n }\n\n\n\n\t// unshrink, check all variables again before final iterations\n\n\n\n\tif(unshrinked || Gmax1 + Gmax2 > eps*10) return;\n\n\t\n\n\tunshrinked = true;\n\n\treconstruct_gradient();\n\n\n\n\tfor(int i= N-1; i >= active_size; --i) {\n\n\t\tif (!be_shrunken(i, Gmax1, Gmax2)) {\n\n\t\t\twhile (active_size < i) {\n\n\t\t\t\tif (be_shrunken(active_size, Gmax1, Gmax2)) {\n", "file_path": "milk/supervised/_svm.cpp", "rank": 90, "score": 5.798183695014094 }, { "content": "def information_gain(labels0, labels1, include_entropy=False):\n\n '''\n\n ig = information_gain(labels0, labels1, include_entropy=False)\n\n\n\n Information Gain\n\n See http://en.wikipedia.org/wiki/Information_gain_in_decision_trees\n\n\n\n The function calculated here does not include the original entropy unless\n\n you explicitly ask for it (by passing include_entropy=True)\n\n '''\n\n if include_entropy:\n\n return set_entropy(np.concatenate( (labels0, labels1) )) + \\\n\n _information_gain(labels0, labels1)\n", "file_path": "milk/supervised/tree.py", "rank": 91, "score": 5.780466137438102 }, { "content": " const int max_iters = 10*1000;\n\n\n\n for (int iter = 0; iter != max_iters; ++iter) {\n\n if (!(iter % 16)) check_for_interrupts();\n\n\t\t// show progress and do shrinking\n\n\t\tif(--counter == 0) {\n\n\t\t\tcounter = min(N,1000);\n\n\t\t\tif(shrinking) do_shrinking();\n\n\t\t\t//info(\".\"); info_flush();\n\n\t\t}\n\n\n\n\t\tint i,j;\n\n\t\tif(select_working_set(i,j)) {\n\n\t\t\t// reconstruct the whole gradient\n\n\t\t\treconstruct_gradient();\n\n\t\t\t// reset active set size and check\n\n\t\t\tactive_size = N;\n\n\t\t\t//info(\"*\"); info_flush();\n\n\t\t\tif(select_working_set(i,j)) {\n\n break;\n", "file_path": "milk/supervised/_svm.cpp", "rank": 92, "score": 5.65958084715027 }, { "content": "def AIC(fmatrix,assignments,centroids,model='one_variance',covs=None):\n\n '''\n\n A = AIC(fmatrix,assignments,centroids,model)\n\n\n\n Compute Akaike Information Criterion\n\n\n\n Parameters\n\n ----------\n\n fmatrix : 2d-array\n\n feature matrix\n\n assignments : 2d-array\n\n Centroid assignments\n\n centroids : sequence\n\n Centroids\n\n model : str, optional\n\n one of\n\n\n\n 'one_variance'\n\n All features share the same variance parameter sigma^2. Default\n\n\n\n 'full_covariance'\n\n Estimate a full covariance matrix or use covs[i] for centroid[i]\n\n covs : sequence, optional\n\n Covariance matrices. If None, then estimate from the data. If scalars\n\n instead of matrices are given, then s stands for sI (i.e., the diagonal\n\n matrix with s along the diagonal).\n\n\n\n Returns\n\n -------\n\n B : float\n\n AIC value\n\n\n\n See Also\n\n --------\n\n BIC\n\n '''\n", "file_path": "milk/unsupervised/gaussianmixture.py", "rank": 93, "score": 5.584038792367007 }, { "content": "def kmeans(fmatrix, k, distance='euclidean', max_iter=1000, R=None, **kwargs):\n\n '''\n\n assignments, centroids = kmean(fmatrix, k, distance='euclidean', max_iter=1000, R=None, icov=None, covmat=None)\n\n\n\n k-Means Clustering\n\n\n\n Parameters\n\n ----------\n\n fmatrix : ndarray\n\n 2-ndarray (Nelements x Nfeatures)\n\n distance: string, optional\n\n one of:\n\n - 'euclidean' : euclidean distance (default)\n\n - 'seuclidean' : standartised euclidean distance. This is equivalent to first normalising the features.\n\n - 'mahalanobis' : mahalanobis distance.\n\n This can make use of the following keyword arguments:\n\n + 'icov' (the inverse of the covariance matrix),\n\n + 'covmat' (the covariance matrix)\n\n If neither is passed, then the function computes the covariance from the feature matrix\n\n max_iter : integer, optional\n\n Maximum number of iteration (default: 1000)\n\n R : source of randomness, optional\n\n\n\n Returns\n\n -------\n\n assignments : ndarray\n\n An 1-D array of size `len(fmatrix)`\n\n centroids : ndarray\n\n An array of `k'` centroids\n\n '''\n\n fmatrix = np.asanyarray(fmatrix)\n\n if not np.issubdtype(fmatrix.dtype, np.float):\n\n fmatrix = fmatrix.astype(np.float)\n\n if distance == 'seuclidean':\n\n fmatrix = zscore(fmatrix)\n\n distance = 'euclidean'\n\n if distance == 'euclidean':\n\n def distfunction(fmatrix, cs, dists):\n\n dists = _dot3(fmatrix, (-2)*cs.T, dists)\n\n dists += np.array([np.dot(c,c) for c in cs])\n\n # For a distance, we'd need to add the fmatrix**2 components, but\n\n # it doesn't matter because we are going to perform an argmin() on\n\n # the result.\n\n return dists\n\n elif distance == 'mahalanobis':\n\n icov = kwargs.get('icov', None)\n\n if icov is None:\n\n covmat = kwargs.get('covmat', None)\n\n if covmat is None:\n\n covmat = np.cov(fmatrix.T)\n\n icov = linalg.inv(covmat)\n\n def distfunction(fmatrix, cs, _):\n\n return np.array([_mahalanobis2(fmatrix, c, icov) for c in cs]).T\n\n else:\n\n raise ValueError('milk.unsupervised.kmeans: `distance` argument unknown (%s)' % distance)\n\n if k < 2:\n\n raise ValueError('milk.unsupervised.kmeans `k` should be >= 2.')\n\n if fmatrix.dtype in (np.float32, np.float64) and fmatrix.flags['C_CONTIGUOUS']:\n\n computecentroids = _kmeans.computecentroids\n\n else:\n\n computecentroids = _pycomputecentroids\n\n R = get_pyrandom(R)\n\n\n\n centroids = np.array(R.sample(fmatrix,k), fmatrix.dtype)\n\n prev = np.zeros(len(fmatrix), np.int32)\n\n counts = np.empty(k, np.int32)\n\n dists = None\n\n for i in xrange(max_iter):\n\n dists = distfunction(fmatrix, centroids, dists)\n\n assignments = dists.argmin(1)\n\n if np.all(assignments == prev):\n\n break\n\n if computecentroids(fmatrix, centroids, assignments.astype(np.int32), counts):\n\n (empty,) = np.where(counts == 0)\n\n centroids = np.delete(centroids, empty, axis=0)\n\n k = len(centroids)\n\n counts = np.empty(k, np.int32)\n\n # This will cause new matrices to be allocated in the next iteration\n\n dists = None\n\n prev[:] = assignments\n", "file_path": "milk/unsupervised/kmeans.py", "rank": 94, "score": 5.513807753644686 }, { "content": "\tG.resize(N);\n\n\tG_bar.resize(N);\n\n\tfor(int i=0;i<N;++i) {\n\n\t\tG[i] = p[i];\n\n\t\tG_bar[i] = 0;\n\n\t}\n\n\tfor(int i=0;i<N;i++) {\n\n\t\tif(!is_lower_bound(i))\n\n\t\t{\n\n\t\t\tconst double *Q_i= cache_.get_kline(active_set[i]);\n\n\t\t\tconst double alpha_i = Alphas[i];\n\n\t\t\tfor(int j=0;j<N;j++) G[j] += alpha_i*Q_i[j];\n\n\t\t\tif(is_upper_bound(i)) {\n\n\t\t\t\tfor(int j=0;j<N;j++) G_bar[j] += get_C(i) * Q_i[j];\n\n }\n\n\t\t}\n\n\t}\n\n\n\n //MAIN LOOP\n\n\tint counter = min(N,1000)+1;\n", "file_path": "milk/supervised/_svm.cpp", "rank": 95, "score": 5.4395970692218985 }, { "content": " Py_XDECREF(obj1);\n\n Py_XDECREF(obj2);\n\n Py_DECREF(arglist);\n\n if (!result) { \n\n check_for_interrupts();\n\n throw SMO_Exception(\"svm.eval_SMO: Unable to call kernel\");\n\n }\n\n double val = PyFloat_AsDouble(result);\n\n Py_DECREF(result);\n\n return val;\n\n}\n\n\n", "file_path": "milk/supervised/_svm.cpp", "rank": 96, "score": 5.383800526048972 }, { "content": "def defaultlearner(mode='medium', multi_strategy='1-vs-1', expanded=False):\n\n '''\n\n learner = defaultlearner(mode='medium')\n\n\n\n Return the default classifier learner\n\n\n\n This is an SVM based classifier using the 1-vs-1 technique for multi-class\n\n problems (by default, see the ``multi_strategy`` parameter). The features\n\n will be first cleaned up (normalised to [-1, +1]) and go through SDA\n\n feature selection.\n\n\n\n Parameters\n\n -----------\n\n mode : string, optional\n\n One of ('fast','medium','slow', 'really-slow'). This defines the speed\n\n accuracy trade-off. It essentially defines how large the SVM parameter\n\n range is.\n\n multi_strategy : str, optional\n\n One of ('1-vs-1', '1-vs-rest', 'ecoc'). This defines the strategy used\n\n to convert the base binary classifier to a multi-class classifier.\n\n expanded : boolean, optional\n\n If true, then instead of a single learner, it returns a list of\n\n possible learners.\n\n\n\n Returns\n\n -------\n\n learner : classifier learner object or list\n\n If `expanded`, then it returns a list\n\n\n\n See Also\n\n --------\n\n feature_selection_simple : Just perform the feature selection\n\n svm_simple : Perform classification\n\n '''\n\n # These cannot be imported at module scope!\n\n # The reason is that they introduce a dependency loop:\n\n # gridsearch depends on nfoldcrossvalidation\n\n # nfoldcrossvalidation depends on defaultlearner\n\n # which cannot depend on gridsearch\n\n #\n\n # Importing at function level keeps all these issues at bay\n\n #\n\n from .classifier import ctransforms\n\n from .gridsearch import gridsearch\n\n from . import svm\n\n from .normalise import chkfinite, interval_normalise\n\n from .featureselection import sda_filter, featureselector, linear_independent_features\n\n from .multi import one_against_one, one_against_rest, ecoc_learner\n\n\n\n assert mode in ('really-slow', 'slow', 'medium', 'fast'), \\\n\n \"milk.supervised.defaultlearner: mode must be one of 'fast','slow','medium'.\"\n\n if multi_strategy == '1-vs-1':\n\n multi_adaptor = one_against_one\n\n elif multi_strategy == '1-vs-rest':\n\n multi_adaptor = one_against_rest\n\n elif multi_strategy == 'ecoc':\n\n multi_adaptor = ecoc_learner\n\n else:\n\n raise ValueError('milk.supervised.defaultlearner: Unknown value for multi_strategy: %s' % multi_strategy)\n\n\n\n if mode == 'fast':\n\n c_range = np.arange(-2,4)\n\n sigma_range = np.arange(-2,3)\n\n elif mode == 'medium':\n\n c_range = np.arange(-2,4)\n\n sigma_range = np.arange(-4,4)\n\n elif mode == 'really-slow':\n\n c_range = np.arange(-4,10)\n\n sigma_range = np.arange(-7,7)\n\n else: # mode == 'slow'\n\n c_range = np.arange(-9,5)\n\n sigma_range = np.arange(-7,4)\n\n\n\n kernels = [svm.rbf_kernel(2.**i) for i in sigma_range]\n\n Cs = 2.**c_range\n\n\n\n if expanded:\n\n return [ctransforms(feature_selection_simple(),\n\n multi_adaptor(svm.svm_to_binary(svm.svm_raw(C=C, kernel=kernel))))\n\n for C in Cs for kernel in kernels]\n\n return ctransforms(feature_selection_simple(),\n\n gridsearch(multi_adaptor(svm.svm_to_binary(svm.svm_raw())),\n", "file_path": "milk/supervised/defaultlearner.py", "rank": 97, "score": 5.285576939311445 }, { "content": " } else {\n\n a2 = alpha2;\n\n }\n\n }\n\n if (a2 < tol) a2 = 0;\n\n else if (a2 > C-tol) a2 = C;\n\n if (std::abs(a2-alpha2) < eps*(a2+alpha2+eps)) return false;\n\n\n\n a1 = alpha1+s*(alpha2-a2);\n\n if (a1 < tol) a1 = 0;\n\n if (a1 > C-tol) a1 = C;\n\n\n\n // update everything\n\n Alphas[i1]=a1;\n\n Alphas[i2]=a2;\n\n double b1 = E1 + Y[i1]*(a1-alpha1)*k11+Y[i2]*(a2-alpha2)*k12+b; // Eq. (12.9)\n\n double b2 = E2 + Y[i1]*(a1-alpha1)*k12+Y[i2]*(a2-alpha2)*k22+b; // Eq. (12.10)\n\n const double new_b = (b1+b2)/2.;\n\n /*\n\n #for i in xrange(N):\n", "file_path": "milk/supervised/_svm.cpp", "rank": 98, "score": 5.1919942864459845 }, { "content": "\n\n// An SMO algorithm in Fan et al., JMLR 6(2005), p. 1889--1918\n\n// Solves:\n\n//\n\n//\tmin 0.5(\\alpha^T Q \\alpha) + p^T \\alpha\n\n//\n\n//\t\ty^T \\alpha = \\delta\n\n//\t\ty_i = +1 or -1\n\n//\t\t0 <= alpha_i <= Cp for y_i = 1\n\n//\t\t0 <= alpha_i <= Cn for y_i = -1\n\n//\n\n// Given:\n\n//\n\n//\tQ, p, y, Cp, Cn, and an initial feasible point \\alpha\n\n//\tl is the size of vectors and matrices\n\n//\teps is the stopping tolerance\n\n//\n\n// solution will be put in \\alpha, objective value will be put in obj\n\n//\n\n\n\n#define info printf\n\nvoid info_flush() { }\n\n\n", "file_path": "milk/supervised/_svm.cpp", "rank": 99, "score": 5.162688818393997 } ]
C++
MsgParser.cpp
fri000/MsgParser
edbc48e664416f144e00712d879a45298d8728d2
#include <avr/pgmspace.h> #include <inttypes.h> #include <string.h> #include <stdlib.h> #include "MsgParser.h" MsgParser::MsgParser() { m_BufferWriteIndex = 0; m_pRead = m_pInputBuffer; m_pMsgParserCommand = NULL; m_msgStartByte = '/'; m_msgEndByte = '\r'; m_useStartByte = false; m_state = WAITING_FOR_START_BYTE; m_pFuncTable = NULL; m_funcTableLength = 0; m_pCmdNotFoundFunc = NULL; memset(m_pInputBuffer, NULL, MSGPARSER_INPUT_BUFFER_SIZE); memset(m_pDescBuf, NULL, MSGPARSER_DESCRIPTION_SIZE); useStartByteSet(m_useStartByte); } void MsgParser::setTable(const FuncEntry_t* newFunctTable, uint8_t newFunctTableLength) { if(newFunctTable != NULL) { m_pFuncTable = (FuncEntry_t*)newFunctTable; m_funcTableLength = newFunctTableLength; } } void MsgParser::useStartByteSet(bool newStatus) { m_useStartByte = newStatus; if( (m_state == WAITING_FOR_START_BYTE) && (m_useStartByte == false) ) { m_state = READING_MESSAGE; } else { } } void MsgParser::setHandlerForCmdNotFound(cmdNotFoundHandler_t pNewHandlerFunc) { m_pCmdNotFoundFunc = pNewHandlerFunc; } void MsgParser::processByte(uint8_t newByte) { switch (m_state) { case WAITING_FOR_START_BYTE: if( newByte == m_msgStartByte ) { m_state = READING_MESSAGE; } else { } break; case READING_MESSAGE: if( newByte == m_msgEndByte ) { if(m_useStartByte == true) m_state = WAITING_FOR_START_BYTE; bool msgFound = false; char *ptr = m_pRead; char *rest; memcpy(m_pOrigMsg, m_pInputBuffer, m_BufferWriteIndex); m_pMsgParserCommand = strtok_r(ptr, " ", &rest); m_pRead = rest; uint8_t i = 0; while( (msgFound == false) && (i < m_funcTableLength) ) { memcpy_P( &m_bufStruct, &(m_pFuncTable[i]), sizeof(m_bufStruct) ); if ( strcmp_P( m_pMsgParserCommand, m_bufStruct.pCmdString ) == 0) { msgFound = true; } else { ++i; } } if(i < m_funcTableLength) { (*m_bufStruct.pFunc)(); } else { if(m_pCmdNotFoundFunc != NULL) { (*m_pCmdNotFoundFunc)((uint8_t*)m_pOrigMsg, m_BufferWriteIndex); } else { } } clearTheBuffer(); } else { m_pInputBuffer[m_BufferWriteIndex] = newByte; m_BufferWriteIndex++; if(m_BufferWriteIndex == MSGPARSER_INPUT_BUFFER_SIZE) { clearTheBuffer(); if(m_useStartByte == true) { m_state = WAITING_FOR_START_BYTE; } else { m_state = READING_MESSAGE; } } else { } } break; default: break; } } void MsgParser::setEndByte(uint8_t newEndByte) { m_msgEndByte = newEndByte; } long MsgParser::getLong() { char *numPtr; char *ptr = m_pRead; char *rest; numPtr = strtok_r(ptr, " ", &rest); m_pRead = rest; return( atol(numPtr) ); } int MsgParser::getInt() { char *numPtr; char *ptr = m_pRead; char *rest; numPtr = strtok_r(ptr, " ", &rest); m_pRead = rest; return( atoi(numPtr) ); } float MsgParser::getFloat() { char *numPtr; char *ptr = m_pRead; char *rest; numPtr = strtok_r(ptr, " ", &rest); m_pRead = rest; return( atof(numPtr) ); } void MsgParser::clearTheBuffer() { m_BufferWriteIndex = 0; m_pRead = m_pInputBuffer; memset(m_pInputBuffer, NULL, MSGPARSER_INPUT_BUFFER_SIZE); } uint8_t MsgParser::numCmds() { return m_funcTableLength; } char* MsgParser::cmdString(uint8_t cmdIndex) { if(cmdIndex >= numCmds()) { return NULL; } memcpy_P( &m_bufStruct, &(m_pFuncTable[cmdIndex]), sizeof(m_bufStruct) ); memcpy_P( m_pDescBuf, m_bufStruct.pCmdString, MSGPARSER_DESCRIPTION_SIZE); return m_pDescBuf; } char* MsgParser::cmdDesc(uint8_t cmdIndex) { if(cmdIndex >= numCmds()) { return NULL; } memcpy_P( &m_bufStruct, &(m_pFuncTable[cmdIndex]), sizeof(m_bufStruct) ); if(m_bufStruct.pDescString != NULL) { memcpy_P( m_pDescBuf, m_bufStruct.pDescString, MSGPARSER_DESCRIPTION_SIZE); return m_pDescBuf; } else { return NULL; } } uint8_t MsgParser::version() { return 0x05; }
#include <avr/pgmspace.h> #include <inttypes.h> #include <string.h> #include <stdlib.h> #include "MsgParser.h" MsgParser::MsgParser() { m_BufferWriteIndex = 0; m_pRead = m_pInputBuffer; m_pMsgParserCommand = NULL; m_msgStartByte = '/'; m_msgEndByte = '\r'; m_useStartByte = false; m_state = WAITING_FOR_START_BYTE; m_pFuncTable = NULL; m_funcTableLength = 0; m_pCmdNotFoundFunc = NULL; memset(m_pInputBuffer, NULL, MSGPARSER_INPUT_BUFFER_SIZE); memset(m_pDescBuf, NULL, MSGPARSER_DESCRIPTION_SIZE); useStartByteSet(m_useStartByte); } void MsgParser::setTable(const FuncEntry_t* newFunctTable, uint8_t newFunctTableLength) { if(newFunctTable != NULL) { m_pFuncTable = (FuncEntry_t*)newFunctTable; m_funcTableLength = newFunctTableLength; } } void MsgParser::useStartByteSet(bool newStatus) { m_useStartByte = newStatus; if( (m_state == WAITING_FOR_START_BYTE) && (m_useStartByte == false) ) { m_state = READING_MESSAGE; } else { } } void MsgParser::setHandlerForCmdNotFound(cmdNotFoundHandler_t pNewHandlerFunc) { m_pCmdNotFoundFunc = pNewHandlerFunc; } void MsgParser::processByte(uint8_t newByte) { switch (m_state) { case WAITING_FOR_START_BYTE: if( newByte == m_msgStartByte ) { m_state = READING_MESSAGE; } else { } break; case READING_MESSAGE: if( newByte == m_msgEndByte ) { if(m_useStartByte == true) m_state = WAITING_FOR_START_BYTE; bool msgFound = false; char *ptr = m_pRead; char *rest; memcpy(m_pOrigMsg, m_pInputBuffer, m_BufferWriteIndex); m_pMsgParserCommand = strtok_r(ptr, " ", &rest); m_pRead = rest; uint8_t i = 0; while( (msgFound == false) && (i < m_funcTableLength) ) { memcpy_P( &m_bufStruct, &(m_pFuncTable[i]), sizeof(m_bufStruct) ); if ( strcmp_P( m_pMsgParserCommand, m_bufStruct.pCmdString ) == 0) { msgFound = true; } else { ++i; } } if(i < m_funcTableLength) { (*m_bufStruct.pFunc)(); } else { if(m_pCmdNotFoundFunc != NULL) { (*m_pCmdNotFoundFunc)((uint8_t*)m_pOrigMsg, m_BufferWriteIndex); } else {
e == true) { m_state = WAITING_FOR_START_BYTE; } else { m_state = READING_MESSAGE; } } else { } } break; default: break; } } void MsgParser::setEndByte(uint8_t newEndByte) { m_msgEndByte = newEndByte; } long MsgParser::getLong() { char *numPtr; char *ptr = m_pRead; char *rest; numPtr = strtok_r(ptr, " ", &rest); m_pRead = rest; return( atol(numPtr) ); } int MsgParser::getInt() { char *numPtr; char *ptr = m_pRead; char *rest; numPtr = strtok_r(ptr, " ", &rest); m_pRead = rest; return( atoi(numPtr) ); } float MsgParser::getFloat() { char *numPtr; char *ptr = m_pRead; char *rest; numPtr = strtok_r(ptr, " ", &rest); m_pRead = rest; return( atof(numPtr) ); } void MsgParser::clearTheBuffer() { m_BufferWriteIndex = 0; m_pRead = m_pInputBuffer; memset(m_pInputBuffer, NULL, MSGPARSER_INPUT_BUFFER_SIZE); } uint8_t MsgParser::numCmds() { return m_funcTableLength; } char* MsgParser::cmdString(uint8_t cmdIndex) { if(cmdIndex >= numCmds()) { return NULL; } memcpy_P( &m_bufStruct, &(m_pFuncTable[cmdIndex]), sizeof(m_bufStruct) ); memcpy_P( m_pDescBuf, m_bufStruct.pCmdString, MSGPARSER_DESCRIPTION_SIZE); return m_pDescBuf; } char* MsgParser::cmdDesc(uint8_t cmdIndex) { if(cmdIndex >= numCmds()) { return NULL; } memcpy_P( &m_bufStruct, &(m_pFuncTable[cmdIndex]), sizeof(m_bufStruct) ); if(m_bufStruct.pDescString != NULL) { memcpy_P( m_pDescBuf, m_bufStruct.pDescString, MSGPARSER_DESCRIPTION_SIZE); return m_pDescBuf; } else { return NULL; } } uint8_t MsgParser::version() { return 0x05; }
} } clearTheBuffer(); } else { m_pInputBuffer[m_BufferWriteIndex] = newByte; m_BufferWriteIndex++; if(m_BufferWriteIndex == MSGPARSER_INPUT_BUFFER_SIZE) { clearTheBuffer(); if(m_useStartByt
random
[ { "content": " const char* pCmdString; //pointer to a null terminated char array\n\n const char* pDescString; //Short help text about this command. Pointer to a null terminated char array\n\n FuncPtr_t pFunc; //pointer to a function\n\n\n\n}FuncEntry_t;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "file_path": "MsgParser.h", "rank": 4, "score": 6.5128478734498145 }, { "content": "\n\n//********************** CONSTANTS **********************\n\n\n\nstatic const uint8_t MSGPARSER_INPUT_BUFFER_SIZE = 64; //This is the max length of a received message\n\nstatic const uint8_t MSGPARSER_DESCRIPTION_SIZE = 128; //This is the length of a description string, that is the help msg for a command.\n\n\n\n\n\n\n\n\n\n//************************ TYPES ************************\n\n\n\n//define a pointer to a function that returns void and accepts no parameters\n\ntypedef void (*FuncPtr_t)(void);\n\n\n\n// define a point to a function that returns void and accepts a pointer to a byte array and array length.\n\ntypedef void (*cmdNotFoundHandler_t)(uint8_t*, uint16_t);\n\n\n\n\n\ntypedef struct\n\n{\n", "file_path": "MsgParser.h", "rank": 9, "score": 3.5767891916418506 }, { "content": " // Private Variables\n\n //***************************************************\n\n FuncEntry_t m_bufStruct;\n\n\n\n char m_pInputBuffer[MSGPARSER_INPUT_BUFFER_SIZE]; //buffer that holds incoming data\n\n uint8_t m_BufferWriteIndex; //index of the first free space in the buffer\n\n char* m_pRead; \t\t //Points to within our input buffer to the current location we are reading.\n\n \n\n char m_pOrigMsg[MSGPARSER_INPUT_BUFFER_SIZE]; //Before we start partitioning the received message in \"buffer\",\n\n // we make a copy of it into this buffer.\n\n \n\n char* m_pMsgParserCommand; //points to the first \"token\" in the receive buffer\n\n \n\n uint8_t m_msgStartByte; //this byte marks the start of the message\n\n uint8_t m_msgEndByte; //this byte marks the end of the message\n\n bool m_useStartByte; //flag if the parser should use a start byte or not;\n\n \n\n STATE_T m_state; //keeps track of which state we are in\n\n \n\n FuncEntry_t* m_pFuncTable; //pointer to the function lookup table in FLASH space\n", "file_path": "MsgParser.h", "rank": 13, "score": 3.010026885215888 }, { "content": "/* MsgParser\n\n * Ilya Brutman\n\n *\n\n */\n\n\n\n#ifndef MsgParser_h\n\n#define MsgParser_h\n\n\n\n#ifdef __cplusplus //use extern \"C\" to make msgParser compatible with c++ compilers\n\n extern \"C\" {\n\n#endif\n\n\n\n\n\n#include <avr/pgmspace.h>\n\n#include <inttypes.h>\n\n#include <string.h>\n\n#include <stdlib.h>\n\n\n\n\n\n\n", "file_path": "MsgParser.h", "rank": 16, "score": 2.7899973982711783 }, { "content": "\n\nprivate:\n\n\n\n //***************************************************\n\n // Private Types\n\n //***************************************************\n\n typedef enum\n\n {\n\n WAITING_FOR_START_BYTE = 0,\n\n READING_MESSAGE,\n\n } STATE_T;\n\n\n\n\n\n //***************************************************\n\n // Private Functions\n\n //***************************************************\n\n void clearTheBuffer();\n\n\n\n\n\n //***************************************************\n", "file_path": "MsgParser.h", "rank": 23, "score": 1.754054804779224 }, { "content": " uint8_t m_funcTableLength; //length of the functions table\n\n \n\n cmdNotFoundHandler_t m_pCmdNotFoundFunc; // Function to call if we received a command that we are not going to handle.\n\n\tchar m_pDescBuf[MSGPARSER_DESCRIPTION_SIZE]; // When we returning a string from PROGMEM, we first copy it here and return pointer to this buffer.\n\n}; //end MsgParser\n\n\n\n\n\n\n\n\n\n#ifdef __cplusplus\n\n }\n\n#endif\n\n\n\n#endif //MsgParser_h\n", "file_path": "MsgParser.h", "rank": 28, "score": 1.5135578936729586 } ]
C++
ModelsAPI/DependentValues.cpp
FlowsheetSimulation/Dyssol-open
557d57d959800868e1b3fd161b26cad16481382b
#include "DependentValues.h" #include "ContainerFunctions.h" #include "StringFunctions.h" #include <ostream> #include <sstream> #include <numeric> CDependentValues::CDependentValues(const std::vector<double>& _params, const std::vector<double>& _values) { SetValues(_params, _values); } bool CDependentValues::IsEmpty() const { return m_values.empty(); } size_t CDependentValues::Size() const { return m_values.size(); } double CDependentValues::GetValue(double _param) const { if (m_values.empty()) return 0; if (m_values.size() == 1) return m_values.front(); return Interpolate(_param); } void CDependentValues::SetValue(double _param, double _value) { const auto pos = std::lower_bound(m_params.begin(), m_params.end(), _param); if (pos == m_params.end()) { m_values.emplace_back(_value); m_params.emplace_back(_param); } else if (std::abs(*pos - _param) <= m_eps) { m_values[std::distance(m_params.begin(), pos)] = _value; *pos = _param; } else { m_values.insert(m_values.begin() + std::distance(m_params.begin(), pos), _value); m_params.insert(pos, _param); } } void CDependentValues::SetValues(const std::vector<double>& _params, const std::vector<double>& _values) { if (m_params.size() != m_values.size()) return; if (IsEmpty()) { m_params = _params; m_values = _values; } else for (size_t i = 0; i < _params.size(); ++i) SetValue(_params[i], _values[i]); } void CDependentValues::RemoveValue(double _param) { const auto pos = std::lower_bound(m_params.begin(), m_params.end(), _param); if (pos != m_params.end() && std::abs(*pos - _param) <= m_eps) { m_values.erase(m_values.begin() + std::distance(m_params.begin(), pos)); m_params.erase(pos); } } double CDependentValues::GetParamAt(size_t _index) const { if (_index >= m_params.size()) return {}; return m_params[_index]; } double CDependentValues::GetValueAt(size_t _index) const { if (_index >= m_values.size()) return {}; return m_values[_index]; } std::pair<double, double> CDependentValues::GetPairAt(size_t _index) const { if (_index >= m_values.size()) return {}; return { m_params[_index], m_values[_index] }; } void CDependentValues::RemovePairAt(size_t _index) { if (_index >= m_values.size()) return; m_params.erase(m_params.begin() + _index); m_values.erase(m_values.begin() + _index); } std::vector<double> CDependentValues::GetParamsList() const { return m_params; } std::vector<double> CDependentValues::GetValuesList() const { return m_values; } void CDependentValues::SetParamsList(const std::vector<double>& _params) { if (_params.size() == m_params.size()) m_params = VectorSort(_params); } void CDependentValues::SetValuesList(const std::vector<double>& _values) { if (_values.size() == m_values.size()) m_values = _values; } bool CDependentValues::HasParam(double _param) const { return VectorContainsSorted(m_params, _param); } bool CDependentValues::IsConst() const { if (m_values.empty()) return true; return std::adjacent_find(m_values.begin(), m_values.end(), std::not_equal_to<>()) == m_values.end(); } void CDependentValues::Clear() { m_params.clear(); m_values.clear(); } bool CDependentValues::operator==(const CDependentValues& _v) const { return m_params == _v.m_params && m_values == _v.m_values; } double CDependentValues::Interpolate(double _param) const { const auto upper = std::upper_bound(m_params.begin(), m_params.end(), _param); if (upper == m_params.end()) return m_values.back(); if (upper == m_params.begin()) return m_values.front(); auto lower = upper; --lower; const double upar = *upper; const double lpar = *lower; const double uval = m_values[std::distance(m_params.begin(), upper)]; const double lval = m_values[std::distance(m_params.begin(), lower)]; if (std::abs(upar - _param) <= m_eps) return uval; if (std::abs(lpar - _param) <= m_eps) return lval; return (uval - lval) / (upar - lpar) * (_param - lpar) + lval; } std::ostream& operator<<(std::ostream& _s, const CDependentValues& _obj) { for (size_t i = 0; i < _obj.Size(); ++i) _s << " " << _obj.GetParamAt(i) << " " << _obj.GetValueAt(i); return _s; } std::istream& operator>>(std::istream& _s, CDependentValues& _obj) { _obj.Clear(); const auto timeOrValue = StringFunctions::GetValueFromStream<double>(_s); if (_s.eof()) _obj.SetValue(0.0, timeOrValue); else { _obj.SetValue(timeOrValue, StringFunctions::GetValueFromStream<double>(_s)); while (!_s.eof()) { const auto param = StringFunctions::GetValueFromStream<double>(_s); const auto value = StringFunctions::GetValueFromStream<double>(_s); _obj.SetValue(param, value); } } return _s; }
#include "DependentValues.h" #include "ContainerFunctions.h" #include "StringFunctions.h" #include <ostream> #include <sstream> #include <numeric> CDependentValues::CDependentValues(const std::vector<double>& _params, const std::vector<double>& _values) { SetValues(_params, _values); } bool CDependentValues::IsEmpty() const { return m_values.empty(); } size_t CDependentValues::Size() const { return m_values.size(); } double CDependentValues::GetValue(double _param) const { if (m_values.empty()) return 0; if (m_values.size() == 1) return m_values.front(); return Interpolate(_param); } void CDependentValues::SetValue(double _param, double _value) { const auto pos = std::lower_bound(m_params.begin(), m_params.end(), _param); if (pos == m_params.end()) { m_values.emplace_back(_value); m_params.emplace_back(_param); } else if (std::abs(*pos - _param) <= m_eps) { m_values[std::distance(m_params.begin(), pos)] = _value; *pos = _param; } else { m_values.insert(m_values.begin() + std::distance(m_params.begin(), pos), _value); m_params.insert(pos, _param); } } void CDependentValues::SetValues(const std::vector<double>& _params, const std::vector<double>& _values) { if (m_params.size() != m_values.size()) return; if (IsEmpty()) { m_params = _params; m_values = _values; } else for (size_t i = 0; i < _params.size(); ++i) SetValue(_params[i], _values[i]); } void CDependentValues::RemoveValue(double _param) { const auto pos = std::lower_bound(m_params.begin(), m_params.end(), _param); if (pos != m_params.end() && std::abs(*pos - _param) <= m_eps) { m_values.erase(m_values.be
irAt(size_t _index) { if (_index >= m_values.size()) return; m_params.erase(m_params.begin() + _index); m_values.erase(m_values.begin() + _index); } std::vector<double> CDependentValues::GetParamsList() const { return m_params; } std::vector<double> CDependentValues::GetValuesList() const { return m_values; } void CDependentValues::SetParamsList(const std::vector<double>& _params) { if (_params.size() == m_params.size()) m_params = VectorSort(_params); } void CDependentValues::SetValuesList(const std::vector<double>& _values) { if (_values.size() == m_values.size()) m_values = _values; } bool CDependentValues::HasParam(double _param) const { return VectorContainsSorted(m_params, _param); } bool CDependentValues::IsConst() const { if (m_values.empty()) return true; return std::adjacent_find(m_values.begin(), m_values.end(), std::not_equal_to<>()) == m_values.end(); } void CDependentValues::Clear() { m_params.clear(); m_values.clear(); } bool CDependentValues::operator==(const CDependentValues& _v) const { return m_params == _v.m_params && m_values == _v.m_values; } double CDependentValues::Interpolate(double _param) const { const auto upper = std::upper_bound(m_params.begin(), m_params.end(), _param); if (upper == m_params.end()) return m_values.back(); if (upper == m_params.begin()) return m_values.front(); auto lower = upper; --lower; const double upar = *upper; const double lpar = *lower; const double uval = m_values[std::distance(m_params.begin(), upper)]; const double lval = m_values[std::distance(m_params.begin(), lower)]; if (std::abs(upar - _param) <= m_eps) return uval; if (std::abs(lpar - _param) <= m_eps) return lval; return (uval - lval) / (upar - lpar) * (_param - lpar) + lval; } std::ostream& operator<<(std::ostream& _s, const CDependentValues& _obj) { for (size_t i = 0; i < _obj.Size(); ++i) _s << " " << _obj.GetParamAt(i) << " " << _obj.GetValueAt(i); return _s; } std::istream& operator>>(std::istream& _s, CDependentValues& _obj) { _obj.Clear(); const auto timeOrValue = StringFunctions::GetValueFromStream<double>(_s); if (_s.eof()) _obj.SetValue(0.0, timeOrValue); else { _obj.SetValue(timeOrValue, StringFunctions::GetValueFromStream<double>(_s)); while (!_s.eof()) { const auto param = StringFunctions::GetValueFromStream<double>(_s); const auto value = StringFunctions::GetValueFromStream<double>(_s); _obj.SetValue(param, value); } } return _s; }
gin() + std::distance(m_params.begin(), pos)); m_params.erase(pos); } } double CDependentValues::GetParamAt(size_t _index) const { if (_index >= m_params.size()) return {}; return m_params[_index]; } double CDependentValues::GetValueAt(size_t _index) const { if (_index >= m_values.size()) return {}; return m_values[_index]; } std::pair<double, double> CDependentValues::GetPairAt(size_t _index) const { if (_index >= m_values.size()) return {}; return { m_params[_index], m_values[_index] }; } void CDependentValues::RemovePa
random
[ { "content": "// Description of a constant property of a pure compound.\n\nclass CConstProperty : public CBaseProperty\n\n{\n\n\tdouble m_defaultValue;\t// Default value.\n\n\tdouble m_dValue;\t\t// Current value of the constant property.\n\n\n\npublic:\n\n\tCConstProperty(unsigned _nProperty, const std::string& _sName, const std::wstring& _sUnits, double _defaultValue);\n\n\n\n\t// Returns value of the constant property.\n\n\tdouble GetValue() const;\n\n\t// Sets value of the constant property.\n\n\tvoid SetValue(double _dValue);\n\n\n\n\t// Checks if the default value is set.\n\n\tbool IsDefaultValue() const override;\n\n};\n", "file_path": "MaterialsDatabase/ConstProperty.h", "rank": 0, "score": 49454.36184429831 }, { "content": "/* Copyright (c) 2020, Dyssol Development Team. All rights reserved. This file is part of Dyssol. See LICENSE file for license information. */\n\n\n\n#pragma once\n\n\n\n#include \"BaseProperty.h\"\n\n\n\n// Description of a constant property of a pure compound.\n", "file_path": "MaterialsDatabase/ConstProperty.h", "rank": 1, "score": 47366.99928157397 }, { "content": "/* Copyright (c) 2020, Dyssol Development Team. All rights reserved. This file is part of Dyssol. See LICENSE file for license information. */\n\n\n\n#include \"ConstProperty.h\"\n\n\n\nCConstProperty::CConstProperty(unsigned _nProperty, const std::string& _sName, const std::wstring& _sUnits, double _defaultValue)\n\n\t: CBaseProperty(_nProperty, _sName, _sUnits),\n\n\tm_defaultValue{ _defaultValue },\n\n\tm_dValue{ _defaultValue }\n\n{\n\n}\n\n\n\ndouble CConstProperty::GetValue() const\n\n{\n\n\treturn m_dValue;\n\n}\n\n\n\nvoid CConstProperty::SetValue(double _dValue)\n\n{\n\n\tm_dValue = _dValue;\n\n}\n\n\n\nbool CConstProperty::IsDefaultValue() const\n\n{\n\n\treturn m_dValue == m_defaultValue;\n\n}\n", "file_path": "MaterialsDatabase/ConstProperty.cpp", "rank": 2, "score": 45280.82744334385 }, { "content": "\tenum class EMethod : size_t { NEWTON = 0, KR2 };\n\n\n\n\tCMaterialStream* m_inStream{ nullptr };\t\t\t\t// Pointer to input stream.\n\n\tCMaterialStream* m_outStream{ nullptr };\t\t\t// Pointer to output stream.\n\n\tCHoldup* m_holdup{ nullptr };\t\t\t\t\t\t// Pointer to holdup.\n\n\n\n\tsize_t m_classesNum{};\t\t\t\t\t\t\t\t// Number of classes for PSD.\n\n\tstd::vector<double> m_means;\t\t\t\t\t\t// Classes means of PSD.\n\n\tstd::vector<double> m_sizes;\t\t\t\t\t\t// Classes sizes of PSD.\n\n\tstd::vector<double> m_grid;\t\t\t\t\t\t\t// Classes limits for PSD.\n\n\tdouble m_holdupMass{ 0 };\t\t\t\t\t\t\t// Mass in the holdup.\n\n\tstd::vector<double> m_S;\t\t\t\t\t\t\t// Values of selection function.\n\n\tstd::vector<std::vector<double>> m_B;\t\t\t\t// Values of breakage function.\n\n\tstd::vector<double> m_nu;\t\t\t\t\t\t\t// Parameter for the calculation of weights.\n\n\tstd::vector<double> m_WB;\t\t\t\t\t\t\t// Weighted parameters for birth rate.\n\n\tstd::vector<double> m_WD;\t\t\t\t\t\t\t// Weighted parameters for death rate.\n\n\tCMatrix2D m_PT;\t\t\t\t\t\t\t\t\t\t// Precalculated matrix to calculate transformation.\n\n\tCMatrix2D m_I;\t\t\t\t\t\t\t\t\t\t// Identity matrix.\n\n\tCTransformMatrix m_TM;\t\t\t\t\t\t\t\t// Transformation matrix.\n\n\tdouble m_dtMin{};\t\t\t\t\t\t\t\t\t// Minimum allowable time step for integration.\n", "file_path": "Units/CrusherPBMTM/CrusherPBMTM.h", "rank": 3, "score": 40606.663133614566 }, { "content": "namespace StrConst\n\n{\n\n//////////////////////////////////////////////////////////////////////////\n\n/// Global\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const G_RegPath = \"HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\Dyssol\";\n\n\tconst char* const G_RegKey = \"key\";\n\n\tconst char* const G_TUHHRegPath = \"HKEY_LOCAL_MACHINE\\\\SYSTEM\\\\CurrentControlSet\\\\Services\\\\Tcpip\\\\Parameters\";\n\n\tconst char* const G_TUHHRegKeyName = \"NV Domain\";\n\n\tconst char* const G_TUHHRegKeyValue = \"tu-harburg.de\";\n\n\n\n\tconst std::string COMMENT_SYMBOL = \"$\";\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// Dyssol\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const Dyssol_ApplicationName = \"Dyssol\";\n\n\tconst char* const Dyssol_ConfigApp = \"application\";\n\n\tconst char* const Dyssol_ConfigFileName = \"config.ini\";\n\n\tconst char* const Dyssol_ConfigLastParamName = \"lastFile\";\n\n\tconst char* const Dyssol_ConfigRecentParamName = \"recentFiles\";\n\n\tconst char* const Dyssol_ConfigLoadLastFlag = \"loadLast\";\n\n\tconst char* const Dyssol_ConfigDMDBPath = \"materialsDBPath\";\n\n\tconst char* const Dyssol_ConfigCachePath = \"cachePath\";\n\n\tconst char* const Dyssol_CacheDirRelease = \"/cache\";\n\n\tconst char* const Dyssol_CacheDirDebug = \"/cache_debug\";\n\n\tconst char* const Dyssol_HelpURL = \"https://flowsheetsimulation.github.io/Dyssol-open/\";\n\n\tconst char* const Dyssol_MainWindowName = \"Dyssol\";\n\n\tconst char* const Dyssol_MDBWindowName\t\t = \"Materials Database\";\n\n\tconst char* const Dyssol_FlowsheetTabName = \"Flowsheet\";\n\n\tconst char* const Dyssol_SimulatorTabName = \"Simulator\";\n\n\tconst char* const Dyssol_StreamsTabName = \"Streams\";\n\n\tconst char* const Dyssol_UnitsTabName = \"Units\";\n\n\tconst char* const Dyssol_SaveMessageBoxText = \"Save current flowsheet?\";\n\n\tconst char* const Dyssol_SaveMDBMessageBoxText = \"Save current materials database?\";\n\n\tconst char* const Dyssol_AbortMessage = \"This will abort the current simulation and close Dyssol. Proceed?\";\n\n\tconst char* const Dyssol_DialogDflwFilter = \"DYSSOL files (*.dflw);;All files (*.*);;\";\n\n\tconst char* const Dyssol_DialogTxtFilter = \"Text files (*.txt);;All files (*.*);;\";\n\n\tconst char* const Dyssol_DialogGraphFilter = \"DOT files (*.gv);;All files (*.*);;\";\n\n\tconst char* const Dyssol_DialogPNGFilter = \"PNG files (*.png);;All files (*.*);;\";\n\n\tconst char* const Dyssol_DialogSaveName = \"Save flowsheet\";\n\n\tconst char* const Dyssol_DialogOpenName = \"Open flowsheet\";\n\n\tconst char* const Dyssol_DialogSaveConfigName = \"Save configuration file\";\n\n\tconst char* const Dyssol_DialogSaveGraphName = \"Save graph file\";\n\n\tconst char* const Dyssol_DialogSaveImageName = \"Save graph image file\";\n\n\tconst char* const Dyssol_StatusLoadingTitle = \"Loading\";\n\n\tconst char* const Dyssol_StatusLoadingText = \"Flowsheet is loading. <br/>Please wait\";\n\n\tconst char* const Dyssol_StatusLoadingQuestion = \"Terminate loading of the flowsheet?\";\n\n\tconst char* const Dyssol_StatusSavingTitle = \"Saving\";\n\n\tconst char* const Dyssol_StatusSavingText = \"Flowsheet is saving. <br/>Please wait\";\n\n\tconst char* const Dyssol_StatusSavingQuestion = \"Terminate saving of the flowsheet?\";\n\n\tconst char* const Dyssol_AboutDyssolDescr = \"Dyssol: Dynamic Simulation of Solids Processes\";\n\n\tconst char* const Dyssol_AppFolderPathLink = \"AppFolder.lnk\";\n\n\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// DyssolC\n\n//////////////////////////////////////////////////////////////////////////\n\n\tinline std::string DyssolC_WriteSrc(const std::string& src, const std::string& dst) {\n\n\t\treturn dst + \" is not specified. \" + src + \" will be used to store simulation results\"; }\n\n\tinline std::string DyssolC_LoadMDB(const std::string& s) {\n\n\t\treturn \"Loading materials database file: \\n\\t\" + s; }\n\n\tinline std::string DyssolC_LoadModels(const std::string& s) {\n\n\t\treturn \"Loading models from: \\n\\t\" + s; }\n\n\tinline std::string DyssolC_LoadFlowsheet(const std::string& s) {\n\n\t\treturn \"Loading flowsheet file: \\n\\t\" + s; }\n\n\tinline std::string DyssolC_SaveFlowsheet(const std::string& s) {\n\n\t\treturn \"Saving flowsheet to: \\n\\t\" + s; }\n\n\tinline std::string DyssolC_Initialize()\t{\n\n\t\treturn \"Initializing flowsheet\"; }\n\n\tinline std::string DyssolC_Start() {\n\n\t\treturn \"Starting simulation\"; }\n\n\tinline std::string DyssolC_ExportResults(const std::string& s)\t{\n\n\t\treturn \"Exporting results to: \\n\\t\" + s; }\n\n\tinline std::string DyssolC_ExportGraph(const std::string& s)\t{\n\n\t\treturn \"Exporting graph to: \\n\\t\" + s; }\n\n\tinline std::string DyssolC_ScriptFinished(const int64_t& time) {\n\n\t\treturn \"Script job finished in \" + std::to_string(time) + \" [s]\"; }\n\n\tinline std::string DyssolC_SimFinished(const int64_t& time) {\n\n\t\treturn \"Simulation finished in \" + std::to_string(time) + \" [s]\"; }\n\n\tinline std::string DyssolC_WarningUnknown(const std::string& s) {\n\n\t\treturn \"Warning while parsing script file: Unknown keyword \" + StringFunctions::Quote(s); }\n\n\tinline std::string DyssolC_ErrorNoScript() {\n\n\t\treturn \"Error: Unable to open script file\"; }\n\n\tinline std::string DyssolC_ErrorSrcDst(const std::string& src, const std::string& dst) {\n\n\t\treturn \"Error: Neither \" + src + \" nor \" + dst + \" is specified. Aborting\"; }\n\n\tinline std::string DyssolC_ErrorMDB() {\n\n\t\treturn \"Error: Unable to load materials database file\"; }\n\n\tinline std::string DyssolC_ErrorLoad() {\n\n\t\treturn \"Error: Unable to load flowsheet file\"; }\n\n\tinline std::string DyssolC_ErrorExportFile() {\n\n\t\treturn \"Error: Unable to open text file for export\"; }\n\n\tinline std::string DyssolC_ErrorGraphFile() {\n\n\t\treturn \"Error: Unable to open graph file for export\"; }\n\n\tinline std::string DyssolC_ErrorNoUnit(const std::string& p, const std::string& n, size_t i) {\n\n\t\treturn \"Error while applying \" + p + \": \\n\\tCannot find a unit neither by its name \" + StringFunctions::Quote(n) + \" nor by its index \" + std::to_string(i + 1); }\n\n\tinline std::string DyssolC_ErrorLoadModel(const std::string& p, const std::string& s) {\n\n\t\treturn \"Error while applying \" + p + \": \\n\\tCannot load a model for unit \" + StringFunctions::Quote(s); }\n\n\tinline std::string DyssolC_ErrorNoUP(const std::string& p, const std::string& u, const std::string& n, size_t i) {\n\n\t\treturn \"Error while applying \" + p + \": \\n\\tCannot find a parameter in unit \" + StringFunctions::Quote(u) + \" neither by its name \" + StringFunctions::Quote(n) + \" nor by its index \" + std::to_string(i + 1); }\n\n\tinline std::string DyssolC_ErrorNoHoldup(const std::string& p, const std::string& u, const std::string& n, size_t i) {\n\n\t\treturn \"Error while applying \" + p + \": \\n\\tCannot find a holdup in unit \" + StringFunctions::Quote(u) + \" neither by its name \" + StringFunctions::Quote(n) + \" nor by its index \" + std::to_string(i + 1); }\n\n\tinline std::string DyssolC_ErrorArgumentsNumber(const std::string& p, const std::string& u, const std::string& n, size_t i) {\n\n\t\treturn \"Error while applying \" + p + \", unit \" + StringFunctions::Quote(u) + \", holdup \" + (!n.empty() ? StringFunctions::Quote(n) : std::to_string(i + 1)) + \":\\n\\tWrong number of arguments\"; }\n\n\tinline std::string DyssolC_ErrorArgumentsNumber(const std::string& p, const std::string& u, const std::string& n, size_t i, const std::string& ph, int64_t iph) {\n\n\t\treturn \"Error while applying \" + p + \", unit \" + StringFunctions::Quote(u) + \", holdup \" + (!n.empty() ? StringFunctions::Quote(n) : std::to_string(i + 1)) + \", phase \" + (!ph.empty() ? ph : std::to_string(iph)) + \":\\n\\tWrong number of arguments\"; }\n\n\tinline std::string DyssolC_ErrorNoPhase(const std::string& p, const std::string& u, const std::string& n, size_t i, const std::string& ph, int64_t iph) {\n\n\t\treturn \"Error while applying \" + p + \", unit \" + StringFunctions::Quote(u) + \", holdup \" + (!n.empty() ? StringFunctions::Quote(n) : std::to_string(i + 1)) + \":\\n\\tPhase \" + (!ph.empty() ? ph : std::to_string(iph)) + \" is not defined in the flowsheet\"; }\n\n\tinline std::string DyssolC_ErrorNoCompound(const std::string& p, const std::string& u, const std::string& n, size_t i, const std::string& c) {\n\n\t\treturn \"Error while applying \" + p + \", unit \" + StringFunctions::Quote(u) + \", holdup \" + (!n.empty() ? StringFunctions::Quote(n) : std::to_string(i + 1)) + \":\\n\\tCannot find compound \" + c + \" neither by its name nor by its key\"; }\n\n\tinline std::string DyssolC_ErrorNoDistribution(const std::string& p, const std::string& u, const std::string& n, size_t i, const std::string& d, int64_t id) {\n\n\t\treturn \"Error while applying \" + p + \", unit \" + StringFunctions::Quote(u) + \", holdup \" + (!n.empty() ? StringFunctions::Quote(n) : std::to_string(i + 1)) + \":\\n\\tDistribution \" + (!d.empty() ? d : std::to_string(id)) + \" is not defined in the flowsheet\"; }\n\n\tinline std::string DyssolC_ErrorArgumentsNumberGrid(const std::string& p, const std::string& u, const std::string& n, int64_t i) {\n\n\t\treturn \"Error while applying \" + p + \", unit \" + StringFunctions::Quote(u) + \", distribution \" + (!n.empty() ? StringFunctions::Quote(n) : std::to_string(i + 1)) + \":\\n\\tWrong number of arguments\"; }\n\n\tinline std::string DyssolC_ErrorArgumentsNumberUnit(const std::string& p) {\n\n\t\treturn \"Error while applying \" + p + \": \\n\\tWrong number of arguments\"; }\n\n\tinline std::string DyssolC_ErrorNoCompounds(const std::string& p, const std::string& c) {\n\n\t\treturn \"Error while applying \" + p + \": \\n\\tCannot find a compound \" + StringFunctions::Quote(c) + \" neither by its name nor by its key\"; }\n\n\tinline std::string DyssolC_ErrorNoModel(const std::string& p, const std::string& v) {\n\n\t\treturn \"Error while applying \" + p + \": \\n\\tCannot find a model \" + StringFunctions::Quote(v) + \" neither by its unique ID, name nor by its path\"; }\n\n\tinline std::string DyssolC_ErrorNoPort(const std::string& p, const std::string& u, const std::string& n, size_t i) {\n\n\t\treturn \"Error while applying \" + p + \": \\n\\tCannot find a port neither by its name \" + StringFunctions::Quote(n) + \" nor by its index \" + std::to_string(i + 1) + \" in unit \" + StringFunctions::Quote(u); }\n\n\tinline std::string DyssolC_ErrorNoStream(const std::string& p, const std::string& n, uint64_t i) {\n\n\t\treturn \"Error while applying \" + p + \": \\n\\tCannot find a stream neither by its name \" + StringFunctions::Quote(n) + \" nor by its index \" + std::to_string(i + 1); }\n\n\tinline std::string DyssolC_ErrorNoStateVar(const std::string& p, const std::string& u, const std::string& n, size_t i) {\n\n\t\treturn \"Error while applying \" + p + \": \\n\\tCannot find a state variable in unit \" + StringFunctions::Quote(u) + \" neither by its name \" + StringFunctions::Quote(n) + \" nor by its index \" + std::to_string(i + 1); }\n\n\tinline std::string DyssolC_ErrorNoPlot(const std::string& p, const std::string& u, const std::string& n, size_t i) {\n\n\t\treturn \"Error while applying \" + p + \": \\n\\tCannot find a plot in unit \" + StringFunctions::Quote(u) + \" neither by its name \" + StringFunctions::Quote(n) + \" nor by its index \" + std::to_string(i + 1); }\n\n\tinline std::string DyssolC_ErrorNoCurve(const std::string& p, const std::string& u, const std::string& d, const std::string& n, size_t i) {\n\n\t\treturn \"Error while applying \" + p + \": \\n\\tCannot find a curve in plot \" + StringFunctions::Quote(d) + \" in unit \" + StringFunctions::Quote(u) + \" neither by its name \" + StringFunctions::Quote(n) + \" nor by its index \" + std::to_string(i + 1); }\n\n\tinline std::string DyssolC_ErrorInit(const std::string& s) {\n\n\t\treturn \"Error during initialization: \" + s; }\n\n\tinline std::string DyssolC_ErrorFinish() {\n\n\t\treturn \"Finished with errors!\"; }\n\n\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CBaseModel\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const BModel_H5ModelName\t = \"ModelName\";\n\n\tconst char* const BModel_H5ModelKey\t\t = \"ModelKey\";\n\n\tconst char* const BModel_H5GroupUnit\t = \"Unit\";\n\n\tconst char* const BModel_H5AttrSaveVersion = \"SaveVersion\";\n\n\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CUnitContainer\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const BCont_H5UnitName = \"UnitName\";\n\n\tconst char* const BCont_H5UnitKey = \"UnitKey\";\n\n\tconst char* const BCont_H5ModelKey = \"ModelKey\";\n\n\tconst char* const BCont_H5GroupModel = \"Unit\";\n\n\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CUnitPort\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const UPort_H5AttrPortsNum = \"PortsNumber\";\n\n\tconst char* const UPort_H5GroupPortName = \"Port\";\n\n\tconst char* const UPort_H5PortsNames = \"UnitPortsNames\";\n\n\tconst char* const UPort_H5PortsKeys = \"UnitPortsKeys\";\n\n\tconst char* const UPort_H5Name = \"Name\";\n\n\tconst char* const UPort_H5Type = \"Type\";\n\n\tconst char* const UPort_H5StreamKey = \"StreamKey\";\n\n\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CStateVariable\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const SVar_H5Name = \"Name\";\n\n\tconst char* const SVar_H5Value = \"Value\";\n\n\tconst char* const SVar_H5History = \"History\";\n\n\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CStreamManager\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const StrMngr_H5AttrFeedsInitNum = \"FeedsInitNumber\";\n\n\tconst char* const StrMngr_H5AttrFeedsWorkNum = \"FeedsWorkNumber\";\n\n\tconst char* const StrMngr_H5AttrHoldupsInitNum = \"HoldupsInitNumber\";\n\n\tconst char* const StrMngr_H5AttrHoldupsWorkNum = \"HoldupsWorkNumber\";\n\n\tconst char* const StrMngr_H5AttrStreamsWorkNum = \"StreamsWorkNumber\";\n\n\tconst char* const StrMngr_H5GroupFeedsInit = \"FeedsInit\";\n\n\tconst char* const StrMngr_H5GroupFeedsWork = \"FeedsWork\";\n\n\tconst char* const StrMngr_H5GroupHoldupsInit = \"HoldupsInit\";\n\n\tconst char* const StrMngr_H5GroupHoldupsWork = \"HoldupsWork\";\n\n\tconst char* const StrMngr_H5GroupStreamsWork = \"StreamsWork\";\n\n\tconst char* const StrMngr_H5GroupFeedName = \"Feed\";\n\n\tconst char* const StrMngr_H5GroupHoldupName = \"Holdup\";\n\n\tconst char* const StrMngr_H5GroupStreamName = \"Stream\";\n\n\tconst char* const StrMngr_H5Names = \"Names\";\n\n\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CPlotManager\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const PlotMngr_H5AttrPlotsNum = \"PlotsNumber\";\n\n\tconst char* const PlotMngr_H5GroupPlotName = \"Plot\";\n\n\tconst char* const PlotMngr_H5PlotName = \"PlotName\";\n\n\tconst char* const PlotMngr_H5PlotXAxis = \"XAxis\";\n\n\tconst char* const PlotMngr_H5PlotYAxis = \"YAxis\";\n\n\tconst char* const PlotMngr_H5PlotZAxis = \"ZAxis\";\n\n\tconst char* const PlotMngr_H5AttrCurvesNum = \"CurvesNumber\";\n\n\tconst char* const PlotMngr_H5GroupCurves = \"Curves\";\n\n\tconst char* const PlotMngr_H5GroupCurveName = \"Curve\";\n\n\tconst char* const PlotMngr_H5CurveName = \"CurveName\";\n\n\tconst char* const PlotMngr_H5CurveZValue = \"ZValue\";\n\n\tconst char* const PlotMngr_H5CurveData = \"Data\";\n\n\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CStateVariablesManager\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const SVMngr_H5AttrStateVarsNum = \"StateVarsNumber\";\n\n\tconst char* const SVMngr_H5GroupStateVarName = \"StateVariable\";\n\n\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CBaseUnit\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const BUnit_DefaultPortName = \"Port\";\n\n\n\n\tconst char* const BUnit_UnspecValue\t = \"Unspecified\";\n\n\tconst char* const BUnit_NoWarnings\t = \"\";\n\n\tconst char* const BUnit_NoErrors\t = \"\";\n\n\tconst char* const BUnit_NoInfos\t\t = \"\";\n\n\tconst char* const BUnit_UnknownWarning = \"Unknown unit's warning\";\n\n\tconst char* const BUnit_UnknownError = \"Unknown unit's error\";\n\n\n\n\tconst char* const BUnit_H5UnitKey\t\t\t = \"UnitKey\";\n\n\tconst char* const BUnit_H5GroupPorts\t\t\t = \"Ports\";\n\n\tconst char* const BUnit_H5GroupPortName\t\t\t = \"Port\";\n\n\tconst char* const BUnit_H5UnitPorts\t\t\t = \"UnitPorts\";\n\n\tconst char* const BUnit_H5UnitPortsKeys\t\t = \"UnitPortsKeys\";\n\n\tconst char* const BUnit_H5UnitPortsNames\t\t = \"UnitPortsNames\";\n\n\tconst char* const BUnit_H5GroupInternalMaterials = \"InternalMaterials\";\n\n\tconst char* const BUnit_H5GroupHoldups\t = \"Holdups\";\n\n\tconst char* const BUnit_H5HoldupsNames\t = \"HoldupsNames\";\n\n\tconst char* const BUnit_H5GroupHoldupName\t = \"Holdup\";\n\n\tconst char* const BUnit_H5GroupHoldupsWork\t = \"WorkHoldups\";\n\n\tconst char* const BUnit_H5GroupHoldupWorkName = \"WorkHoldup\";\n\n\tconst char* const BUnit_H5WorkHoldupsNames\t\t = \"WorkHoldupsNames\";\n\n\tconst char* const BUnit_H5GroupStreamsWork\t = \"WorkStreams\";\n\n\tconst char* const BUnit_H5GroupStreamWorkName = \"WorkStream\";\n\n\tconst char* const BUnit_H5WorkStreamsNames\t\t = \"WorkStreamsNames\";\n\n\tconst char* const BUnit_H5GroupParams\t\t = \"UnitParameters\";\n\n\tconst char* const BUnit_H5GroupStateVars = \"StateVariables\";\n\n\tconst char* const BUnit_H5GroupStateVarName\t = \"StateVariable\";\n\n\tconst char* const BUnit_H5StateVarName = \"Name\";\n\n\tconst char* const BUnit_H5StateVarValue\t\t = \"Value\";\n\n\tconst char* const BUnit_H5StateVarSavedVal\t = \"SavedValue\";\n\n\tconst char* const BUnit_H5StateVarIsSaved\t = \"IsSaved\";\n\n\tconst char* const BUnit_H5StateVarTimes\t\t = \"Times\";\n\n\tconst char* const BUnit_H5StateVarValues\t = \"Values\";\n\n\tconst char* const BUnit_H5AttrPortsNum\t\t\t = \"PortsNumber\";\n\n\tconst char* const BUnit_H5AttrHoldupsNum\t = \"HoldupsNumber\";\n\n\tconst char* const BUnit_H5AttrHoldupsWorkNum = \"WorkHoldupsNumber\";\n\n\tconst char* const BUnit_H5AttrStreamsWorkNum = \"WorkStreamsNumber\";\n\n\tconst char* const BUnit_H5AttrStateVarsNum\t = \"StateVarsNumber\";\n\n\tconst char* const BUnit_H5AttrSaveVersion\t = \"SaveVersion\";\n\n\n\n\tconst char* const BUnit_H5AttrPlotsNum\t\t = \"PlotsNumber\";\n\n\tconst char* const BUnit_H5GroupPlots\t = \"Plots\";\n\n\tconst char* const BUnit_H5GroupPlotName\t = \"Plot\";\n\n\tconst char* const BUnit_H5PlotName = \"PlotName\";\n\n\tconst char* const BUnit_H5PlotXAxis = \"XAxis\";\n\n\tconst char* const BUnit_H5PlotYAxis = \"YAxis\";\n\n\tconst char* const BUnit_H5PlotZAxis = \"ZAxis\";\n\n\tconst char* const BUnit_H5PlotIs2D = \"Is2D\";\n\n\tconst char* const BUnit_H5AttrCurvesNum = \"CurvesNumber\";\n\n\tconst char* const BUnit_H5GroupCurves = \"Curves\";\n\n\tconst char* const BUnit_H5GroupCurveName = \"Curve\";\n\n\tconst char* const BUnit_H5CurveName = \"Name\";\n\n\tconst char* const BUnit_H5CurveX = \"XVector\";\n\n\tconst char* const BUnit_H5CurveY = \"YVector\";\n\n\tconst char* const BUnit_H5CurveZ = \"ZValue\";\n\n\n\n\t// TODO: delete unused\n\n\tinline std::string BUnit_Err0(const std::string& unit, const std::string& fun) {\n\n\t\treturn std::string(\"Error in unit '\" + unit + \"', function call \" + fun + \"(): \"); }\n\n\tinline std::string BUnit_Err1(const std::string& unit, const std::string& fun, const std::string& param1) {\n\n\t\treturn std::string(\"Error in unit '\" + unit + \"', function call \" + fun + \"('\" + param1 + \"'): \"); }\n\n\tinline std::string BUnit_Err2(const std::string& unit, const std::string& fun, const std::string& param1, const std::string& param2) {\n\n\t\treturn std::string(\"Error in unit '\" + unit + \"', function call \" + fun + \"('\" + param1 + \"', '\" + param2 + \"'): \"); }\n\n\tinline std::string BUnit_Err3(const std::string& unit, const std::string& fun, const std::string& param1, const std::string& param2, const std::string& param3) {\n\n\t\treturn std::string(\"Error in unit '\" + unit + \"', function call \" + fun + \"('\" + param1 + \"', '\" + param2 + \"', '\" + param3 + \"'): \"); }\n\n\tinline std::string BUnit_ErrAddPort(const std::string& s1, const std::string& s2, const std::string& s3) {\n\n\t\treturn BUnit_Err1(s1, s3, s2) + \"Port '\" + s2 + \"' has duplicates. Ports names must be unique within the unit.\"; }\n\n\tinline std::string BUnit_ErrGetPort(const std::string& s1, const std::string& s2, const std::string& s3) {\n\n\t\treturn BUnit_Err1(s1, s3, s2) + \"A port with such name does not exist in this unit.\"; }\n\n\tinline std::string BUnit_ErrGetPortEmpty(const std::string& s1, const std::string& s2, const std::string& s3) {\n\n\t\treturn BUnit_Err1(s1, s3, s2) + \"A port is not connected to the stream.\"; }\n\n\tinline std::string BUnit_ErrAddFeed(const std::string& s1, const std::string& s2, const std::string& s3) {\n\n\t\treturn BUnit_Err1(s1, s3, s2) + \"Feed '\" + s2 + \"' has duplicates. Feeds names must be unique within the unit.\"; }\n\n\tinline std::string BUnit_ErrAddHoldup(const std::string& s1, const std::string& s2, const std::string& s3) {\n\n\t\treturn BUnit_Err1(s1, s3, s2) + \"Holdup '\" + s2 + \"' has duplicates. Holdups names must be unique within the unit.\"; }\n\n\tinline std::string BUnit_ErrAddStream(const std::string& s1, const std::string& s2, const std::string& s3) {\n\n\t\treturn BUnit_Err1(s1, s3, s2) + \"Stream '\" + s2 + \"' has duplicates. Streams names must be unique within the unit.\"; }\n\n\tinline std::string BUnit_ErrGetFeed(const std::string& s1, const std::string& s2, const std::string& s3) {\n\n\t\treturn BUnit_Err1(s1, s3, s2) + \"A feed with such name does not exist in this unit.\"; }\n\n\tinline std::string BUnit_ErrGetHoldup(const std::string& s1, const std::string& s2, const std::string& s3) {\n\n\t\treturn BUnit_Err1(s1, s3, s2) + \"A holdup with such name does not exist in this unit.\"; }\n\n\tinline std::string BUnit_ErrGetStream(const std::string& s1, const std::string& s2, const std::string& s3) {\n\n\t\treturn BUnit_Err1(s1, s3, s2) + \"A stream with such name does not exist in this unit.\"; }\n\n\tinline std::string BUnit_ErrGetParam(const std::string& s1, const std::string& s2, const std::string& s3) {\n\n\t\treturn std::string(\"Error in unit '\" + s1 + \"', function call \" + s3 + \"('\" + s2 + \"'): unit parameter with such combination of name and type does not exist in this unit.\");\t}\n\n\tinline std::string BUnit_ErrAddParam(const std::string& s1, const std::string& s2, const std::string& s3) {\n\n\t\treturn BUnit_Err1(s1, s3, s2) + \"Unit parameter '\" + s2 + \"' has duplicates. Unit parameters names must be unique within the unit.\"; }\n\n\tinline std::string BUnit_ErrAddComboParam(const std::string& s1, const std::string& s2, const std::string& s3) {\n\n\t\treturn BUnit_Err1(s1, s3, s2) + \"Unit parameter '\" + s2 + \"' cannot be added. The number of items must be equal to the number of names.\"; }\n\n\tinline std::string BUnit_ErrGroupParamBlock(const std::string& s1, const std::string& s2, const std::string& s3, const std::string& s4) {\n\n\t\treturn BUnit_Err3(s1, s4, s2, s3, \"{}\") + \"A group unit parameter with name '\" + s2 + \"' does not exist in this unit.\";\t}\n\n\tinline std::string BUnit_ErrGroupParamGroup(const std::string& s1, const std::string& s2, const std::string& s3, const std::string& s4) {\n\n\t\treturn BUnit_Err3(s1, s4, s2, s3, \"{}\") + \"A group with name '\" + s3 + \"' does not exist in this group unit parameter.\"; }\n\n\tinline std::string BUnit_ErrGroupParamParam(const std::string& s1, const std::string& s2, const std::string& s3, const std::string& s4, const std::string& s5) {\n\n\t\treturn BUnit_Err3(s1, s5, s2, s3, s4) + std::string(\"A unit parameter with name '\" + s4 + \"' does not exist in this unit.\"); }\n\n\tinline std::string BUnit_ErrAddSV(const std::string& s1, const std::string& s2, const std::string& s3) {\n\n\t\treturn BUnit_Err1(s1, s3, s2) + \"State variable '\" + s2 + \"' has duplicates. State variables names must be unique within the unit.\"; }\n\n\tinline std::string BUnit_ErrGetSV(const std::string& s1, const std::string& s2, const std::string& s3) {\n\n\t\treturn BUnit_Err1(s1, s3, s2) + \"A state variable with such name does not exist in this unit.\";}\n\n\tinline std::string BUnit_ErrAddPlot(const std::string& s1, const std::string& s2, const std::string& s3) {\n\n\t\treturn BUnit_Err1(s1, s3, s2) + (\"Plot '\" + s2 + \"' has duplicates. Plots names must be unique within the unit.\"); }\n\n\tinline std::string BUnit_ErrAddCurve2D(const std::string& s1, const std::string& s2, const std::string& s3, const std::string& s4) {\n\n\t\treturn BUnit_Err2(s1, s4, s3, s2) + \"Curve '\" + s3 + \"' has duplicates in plot '\" + s2 + \"'. Curves names must be unique within the plot.\"; }\n\n\tinline std::string BUnit_ErrAddCurve3D(const std::string& s1, const std::string& s2, double s3, const std::string& s4) {\n\n\t\treturn BUnit_Err2(s1, s4, StringFunctions::Double2String(s3), s2) + (\"A curve with Z-value '\" + StringFunctions::Double2String(s3) + \"' has duplicates in plot '\" + s2 + \"'. Z-values must be unique within the plot.\"); }\n\n\tinline std::string BUnit_ErrGetPlot(const std::string& s1, const std::string& s2, const std::string& s3) {\n\n\t\treturn BUnit_Err1(s1, s3, s2) + \"A plot with such name does not exist in this unit\"; }\n\n\tinline std::string BUnit_ErrGetCurve2D(const std::string& s1, const std::string& s2, const std::string& s3, const std::string& s4) {\n\n\t\treturn BUnit_Err2(s1, s4, s3, s2) + \"A curve with such name does not exist in plot '\" + s2 + \"'.\"; }\n\n\tinline std::string BUnit_ErrGetCurve3D(const std::string& s1, const std::string& s2, double s3, const std::string& s4) {\n\n\t\treturn BUnit_Err2(s1, s4, StringFunctions::Double2String(s3), s2) + \"A curve with such Z-value does not exist in plot '\" + s2 + \"'.\"; }\n\n\tinline std::string BUnit_ErrCopyToPort(const std::string& s1, const std::string& s2, const std::string& s3, const std::string& s4) {\n\n\t\treturn BUnit_Err2(s1, s4, s2, s3) + \"Cannot copy to input port with name '\" + s3 + \"'.\"; }\n\n\tinline std::string BUnit_ErrCopyFromPort(const std::string& s1, const std::string& s2, const std::string& s3, const std::string& s4) {\n\n\t\treturn BUnit_Err2(s1, s4, s2, s3) + \"Cannot copy from output port with name '\" + s2 + \"'.\"; }\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CUnitParameters\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const UParam_H5Times = \"Times\";\n\n\tconst char* const UParam_H5Values = \"Values\";\n\n\tconst char* const UParam_H5StrValue = \"StrValue\";\n\n\tconst char* const UParam_H5AttrReactionsNum = \"ReactionsNumber\";\n\n\tconst char* const UParam_H5Reaction = \"Reaction\";\n\n\tconst char* const UParam_H5Names = \"ParamsNames\";\n\n\tconst char* const UParam_H5GroupParamName = \"UnitParameter\";\n\n\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CDenseDistr2D\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const Distr2D_H5AttrDimsNum\t\t= \"DimensionsNumber\";\n\n\tconst char* const Distr2D_H5TimePoints\t\t= \"TimePoints\";\n\n\tconst char* const Distr2D_H5Data\t\t\t= \"Data\";\n\n\tconst char* const Distr2D_H5AttrSaveVersion\t= \"SaveVersion\";\n\n\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CDistributionsGrid\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const DGrid_H5AttrGridsNum\t = \"GridsNumber\";\n\n\tconst char* const DGrid_H5GroupName\t = \"Grid\";\n\n\tconst char* const DGrid_H5GridType\t = \"States\";\n\n\tconst char* const DGrid_H5DistrType\t\t = \"Types\";\n\n\tconst char* const DGrid_H5GridFun\t\t = \"Function\";\n\n\tconst char* const DGrid_H5Classes\t = \"Classes\";\n\n\tconst char* const DGrid_H5Units\t\t\t = \"Units\";\n\n\tconst char* const DGrid_H5NumGrid\t = \"NumGrid\";\n\n\tconst char* const DGrid_H5StrGrid = \"StrGrid\";\n\n\tconst char* const DGrid_H5AttrSaveVersion = \"SaveVersion\";\n\n\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CSimulator\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const\tSim_ErrMinTWLength = \"The minimum length of the time window is reached. Simulation stopped.\";\n\n\tconst char* const\tSim_ErrMaxTWIterations = \"Maximum number of iterations has been reached. Simulation will be stopped.\";\n\n\tconst char* const\tSim_InfoSaveInitTearStreams = \"Saving new initial values of tear streams...\";\n\n\tconst char* const\tSim_InfoFalseInitTearStreams = \"Cannot converge using previous results as initial values. Resetting to defaults and restarting.\";\n\n\tinline std::string Sim_InfoRecycleStreamCalculating(unsigned iWin, unsigned iIter, double t1, double t2) {\n\n\t\treturn std::string(\"Recycle stream. Time window #\" + std::to_string(iWin) + \". Iteration #\" + std::to_string(iIter) + \" [\" + StringFunctions::Double2String(t1) + \", \" + StringFunctions::Double2String(t2) + \"]...\"); }\n\n\tinline std::string Sim_InfoRecycleStreamFinishing(unsigned iWin, unsigned iIter, double t1, double t2) {\n\n\t\treturn std::string(\"Finishing recycle stream. Time window #\" + std::to_string(iWin) + \". Iteration #\" + std::to_string(iIter) + \" [\" + StringFunctions::Double2String(t1) + \", \" + StringFunctions::Double2String(t2) + \"]...\"); }\n\n\tinline std::string Sim_InfoUnitInitialization(const std::string& unit, const std::string& model) {\n\n\t\treturn std::string(\"Initialization of \" + unit + \" (\" + model + \")...\"); }\n\n\tinline std::string Sim_InfoUnitSimulation(const std::string& unit, const std::string& model, double t1, double t2) {\n\n\t\treturn std::string(\"Simulation of \" + unit + \" (\" + model + \"): [\" + StringFunctions::Double2String(t1) + \", \" + StringFunctions::Double2String(t2) + \"]...\"); }\n\n\tinline std::string Sim_InfoUnitFinalization(const std::string& unit, const std::string& model) {\n\n\t\treturn std::string(\"Finalization of \" + unit + \" (\" + model + \")...\"); }\n\n\tinline std::string Sim_WarningParamOutOfRange(const std::string& unit, const std::string& model, const std::string& param) {\n\n\t\treturn std::string(\"In unit '\" + unit + \"' (\" + model + \"), parameter '\" + param + \"': value is out of range.\"); }\n\n\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CFlowsheet\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const Flow_H5AttrUnitsNum\t\t = \"ModelsNumber\";\n\n\tconst char* const Flow_H5GroupUnits\t\t = \"Models\";\n\n\tconst char* const Flow_H5GroupUnitName\t\t = \"Model\";\n\n\tconst char* const Flow_H5ModelKey\t\t\t = \"UnitKey\";\n\n\tconst char* const Flow_H5AttrStreamsNum\t\t = \"StreamsNumber\";\n\n\tconst char* const Flow_H5GroupStreams\t\t = \"Streams\";\n\n\tconst char* const Flow_H5GroupStreamName\t = \"Stream\";\n\n\tconst char* const Flow_H5GroupCalcSeq\t\t\t = \"CalculationSequence\";\n\n\tconst char* const Flow_H5GroupInitTearStreams\t = \"InitTearStreams\";\n\n\tconst char* const Flow_H5GroupPartitionName\t = \"Partition\";\n\n\tconst char* const Flow_H5GroupInitTearStreamName = \"InitTearStream\";\n\n\tconst char* const Flow_H5Compounds\t\t\t = \"Compounds\";\n\n\tconst char* const Flow_H5AttrOverallsNum = \"OverallsNumber\";\n\n\tconst char* const Flow_H5GroupOveralls = \"OverallProperties\";\n\n\tconst char* const Flow_H5GroupOverallName = \"OverallProperty\";\n\n\tconst char* const Flow_H5OverallType = \"Type\";\n\n\tconst char* const Flow_H5OverallName = \"Name\";\n\n\tconst char* const Flow_H5OverallUnits = \"Units\";\n\n\tconst char* const Flow_H5AttrPhasesNum = \"PhasesNumber\";\n\n\tconst char* const Flow_H5GroupPhases\t\t = \"Phases\";\n\n\tconst char* const Flow_H5GroupPhaseName = \"Phase\";\n\n\tconst char* const Flow_H5PhaseType = \"Type\";\n\n\tconst char* const Flow_H5PhaseName = \"Name\";\n\n\tconst char* const Flow_H5PhasesNames\t\t = \"PhaseNames\";\n\n\tconst char* const Flow_H5PhasesSOA\t\t\t = \"PhaseAggregationStates\";\n\n\tconst char* const Flow_H5GroupOptions\t\t = \"Options\";\n\n\tconst char* const Flow_H5OptionSimTime\t\t = \"SimulationTime\";\n\n\tconst char* const Flow_H5AttrSaveVersion\t = \"SaveVersion\";\n\n\n\n\tinline std::string Flow_ErrEmptyHoldup(const std::string& s1, const std::string& s2) {\n\n\t\treturn std::string(\"Holdup '\" + s2 + \"' in unit '\" + s1 + \"' is empty.\"); }\n\n\tinline std::string Flow_ErrEmptyUnit(const std::string& s1) {\n\n\t\treturn std::string(\"No model is assigned to unit '\" + s1 + \"'.\"); }\n\n\tinline std::string Flow_ErrPhaseFractions(const std::string& u, const std::string& h, double t) {\n\n\t\treturn std::string(\"Phase fractions of holdup '\" + h + \"' in unit '\" + u + \"' at time point \" + std::to_string(t) + \" s do not sum up to 1.\"); }\n\n\tinline std::string Flow_ErrCompoundFractions(const std::string& u, const std::string& h, const std::string& p, double t) {\n\n\t\treturn std::string(\"Compound fractions of holdup '\" + h + \"' of phase '\" + p + \"' in unit '\" + u + \"' at time point \" + std::to_string(t) + \" s do not sum up to 1.\"); }\n\n\tconst char* const\tFlow_ErrEmptyMDB = \"Materials database file has not been loaded or empty.\";\n\n\tconst char* const\tFlow_ErrEmptySequence = \"Calculation sequence is empty.\";\n\n\tconst char* const\tFlow_ErrWrongSequence = \"Wrong calculation sequence.\";\n\n\tinline std::string Flow_ErrIncompSequence(const std::string& s1) { return std::string(\"Unit '\" + s1 + \"' is not in calculation sequence.\"); }\n\n\tconst char* const\tFlow_ErrMultSolids = \"More than 1 solid phase has been defined.\";\n\n\tconst char* const\tFlow_ErrMultVapors = \"More than 1 vapor phase has been defined.\";\n\n\tconst char* const\tFlow_ErrNoCompounds = \"No compounds specified.\";\n\n\tinline std::string\tFlow_ErrWrongCompound(const std::string& s1) {\n\n\t\treturn std::string(\"Cannot find compound '\" + s1 + \"' in the loaded materials database.\");\t}\n\n\tinline std::string\tFlow_ErrWrongCompoundParam(const std::string& s1, const std::string& s2) {\n\n\t\treturn std::string(\"Cannot find compound '\" + s2 + \"', defined in unit parameter '\" + s1 + \"', in the loaded materials database.\"); }\n\n\tconst char* const\tFlow_ErrNoPhases = \"No phases specified.\";\n\n\tinline std::string Flow_ErrUnconnectedPorts(const std::string& s1, const std::string& s2) {\n\n\t\treturn \"Port '\" + s2 + \"' in unit '\" + s1 + \"' is unconnected.\"; }\n\n\tinline std::string\tFlow_ErrWrongStreams(const std::string& s1) {\n\n\t\treturn std::string(\"Stream '\" + s1 + \"' is not correctly connected. Each stream must be connected to one input and to one output port.\"); }\n\n\tinline std::string Flow_ErrSolverKeyEmpty(const std::string& s1, const std::string& s2) { return std::string(\"Solver '\" + s1 + \"' in unit '\" + s2 + \"' has not been chosen in unit parameters.\"); }\n\n\tinline std::string Flow_ErrCannotLoadSolverLib(const std::string& s1, const std::string& s2) { return std::string(\"Solver '\" + s1 + \"' in unit '\" + s2 + \"' can not be found or loaded.\"); }\n\n\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CCalculationSequence\n\n//////////////////////////////////////////////////////////////////////////\n\n\n\n\tconst char* const Seq_H5AttrPartitionsNum = \"PartitionsNumber\";\n\n\tconst char* const Seq_H5GroupPartitionName = \"Partition\";\n\n\tconst char* const Seq_H5ModelsKeys = \"ModelsKeys\";\n\n\tconst char* const Seq_H5TearStreamsKeys = \"TearStreamsKeys\";\n\n\tconst char* const Seq_H5AttrSaveVersion = \"SaveVersion\";\n\n\tconst char* const Seq_H5GroupInitTears = \"InitialTearStreams\";\n\n\tconst char* const Seq_H5GroupInitTearName = \"Stream\";\n\n\n\n\tconst char* const Seq_ErrEmptySequence = \"Calculation sequence is empty.\";\n\n\tconst char* const Seq_ErrEmptyModel = \"Some model in calculation sequence is empty.\";\n\n\tconst char* const Seq_ErrEmptyStream = \"Some tear stream in calculation sequence is empty.\";\n\n\tinline std::string Seq_ErrMissingUnit(const std::string& s1) { return std::string(\"Unit '\" + s1 + \"' is not in calculation sequence.\"); }\n\n\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CParametersHolder\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const FlPar_H5ATol\t\t = \"AbsTolerance\";\n\n\tconst char* const FlPar_H5RTol\t\t = \"RelTolerance\";\n\n\tconst char* const FlPar_H5MinFrac\t = \"MinimalFraction\";\n\n\tconst char* const FlPar_H5SimTime = \"SimulationTime\";\n\n\tconst char* const FlPar_H5InitTimeWin = \"InitialTimeWindow\";\n\n\tconst char* const FlPar_H5MinTimeWin\t = \"MinTimeWindow\";\n\n\tconst char* const FlPar_H5MaxTimeWin\t = \"MaxTimeWindow\";\n\n\tconst char* const FlPar_H5MaxStepsNum\t = \"MaxStepsNum\";\n\n\tconst char* const FlPar_H5UpperLimit\t = \"ItersUpperLimit\";\n\n\tconst char* const FlPar_H5LowerLimit\t = \"ItersLowerLimit\";\n\n\tconst char* const FlPar_H51stUpperLimit = \"Iters1stUpperLimit\";\n\n\tconst char* const FlPar_H5MagnificRatio = \"TimeWindowRatio\";\n\n\tconst char* const FlPar_H5ConvMethod\t = \"ConvergenceMethod\";\n\n\tconst char* const FlPar_H5WegsteinParam = \"WegsteinAccelParam\";\n\n\tconst char* const FlPar_H5RelaxParam\t = \"RelaxationParam\";\n\n\tconst char* const FlPar_H5ExtrapMethod\t = \"ExtrapolationMethod\";\n\n\tconst char* const FlPar_H5SaveTimeStep\t = \"SaveFileStep\";\n\n\tconst char* const FlPar_H5SaveTimeStepFlagHoldups = \"SaveTimeStepFlagHoldups\";\n\n\tconst char* const FlPar_H5CacheFlagStreams = \"CacheFlag\";\n\n\tconst char* const FlPar_H5CacheFlagHoldups = \"CacheFlagHoldups\";\n\n\tconst char* const FlPar_H5CacheFlagInternal = \"CacheFlagInternal\";\n\n\tconst char* const FlPar_H5CacheWindow\t = \"CacheWindow\";\n\n\tconst char* const FlPar_H5FileSingleFlag\t = \"FileSingleFlag\";\n\n\tconst char* const FlPar_H5InitTearStreamsFlag\t = \"InitTearStreamsFlag\";\n\n\tconst char* const FlPar_H5EnthalpyMinT = \"EnthalpyMinTemperature\";\n\n\tconst char* const FlPar_H5EnthalpyMaxT = \"EnthalpyMaxTemperature\";\n\n\tconst char* const FlPar_H5EnthalpyIntervals = \"EnthalpyIntervals\";\n\n\tconst char* const FlPar_H5AttrSaveVersion = \"SaveVersion\";\n\n\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CMDMatrix\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const MDM_H5Dimensions\t\t= \"Dimensions\";\n\n\tconst char* const MDM_H5Classes\t\t\t= \"Classes\";\n\n\tconst char* const MDM_H5TimePoints\t\t= \"TimePoints\";\n\n\tconst char* const MDM_H5Data\t\t\t= \"Data\";\n\n\tconst char* const MDM_H5AttrBlocksNum\t= \"BlocksNumber\";\n\n\tconst char* const MDM_H5AttrSaveVersion\t= \"SaveVersion\";\n\n\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CStream\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const Stream_UnspecStreamName\t= \"Unspecified\";\n\n\tconst char* const Stream_FileExt\t\t\t= \".dat\";\n\n\tconst char* const Stream_FileNameStream\t\t= \"stream\";\n\n\tconst char* const Stream_FileNameMTP\t\t= \"mtp\";\n\n\tconst char* const Stream_FileNamePhaseFrac\t= \"phs\";\n\n\tconst char* const Stream_FileNamePhaseDistr\t= \"phase_distribution\";\n\n\n\n\tconst char* const Stream_H5StreamName\t\t= \"StreamName\";\n\n\tconst char* const Stream_H5StreamKey\t\t= \"StreamKey\";\n\n\tconst char* const Stream_H5TimePoints\t\t= \"TimePoints\";\n\n\tconst char* const Stream_H5AttrPhasesNum\t= \"PhasesNumber\";\n\n\tconst char* const Stream_H5GroupPhases\t\t= \"Phases\";\n\n\tconst char* const Stream_H5GroupPhaseName\t= \"Phase\";\n\n\tconst char* const Stream_H5Attr2DDistrNum\t= \"2DDistrNumber\";\n\n\tconst char* const Stream_H5Group2DDistrs\t= \"Distributions\";\n\n\tconst char* const Stream_H5Group2DDistrName\t= \"Distribution\";\n\n\tconst char* const Stream_H5OverallKeys = \"OverallKeys\";\n\n\tconst char* const Stream_H5GroupOveralls = \"Overalls\";\n\n\tconst char* const Stream_H5GroupOverallName = \"Overall\";\n\n\tconst char* const Stream_H5PhaseKeys = \"PhaseKeys\";\n\n\tconst char* const Stream_H5PhaseName\t\t= \"PhaseName\";\n\n\tconst char* const Stream_H5PhaseSOA\t\t\t= \"PhaseSOA\";\n\n\tconst char* const Stream_H5AttrSaveVersion\t= \"SaveVersion\";\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CTimeDependentValue\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const TDV_H5Name = \"Name\";\n\n\tconst char* const TDV_H5Units = \"Units\";\n\n\tconst char* const TDV_H5Data = \"Data\";\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CPhase\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const Phase_H5Name = \"Name\";\n\n\tconst char* const Phase_H5State = \"State\";\n\n\tconst char* const Phase_H5Fractions = \"Fractions\";\n\n\tconst char* const Phase_H5Distribution = \"Distribution\";\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CChemicalReaction\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const Reac_H5Name = \"Name\";\n\n\tconst char* const Reac_H5Base = \"BaseSubstance\";\n\n\tconst char* const Reac_H5SubstancesNumber = \"SubstancesNumber\";\n\n\tconst char* const Reac_H5Substance = \"Substance\";\n\n\tconst char* const Reac_H5SubstanceKey = \"Key\";\n\n\tconst char* const Reac_H5SubstanceNu = \"Nu\";\n\n\tconst char* const Reac_H5SubstanceOrder = \"Order\";\n\n\tconst char* const Reac_H5SubstancePhase = \"Phase\";\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// HDF5 saving/loading\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const H5AttrSaveVersion = \"SaveVersion\";\n\n\tconst char* const H5GroupDistrGrid = \"DistrGrid\";\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CH5Handler\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst std::string HDF5H_FileExt\t\t = \"dflw\";\n\n\tconst std::string HDF5H_DotFileExt\t\t = \".\" + HDF5H_FileExt;\n\n\tconst std::string HDF5H_FileExtSpec\t = \"%d\";\n\n\tconst std::string HDF5H_FileExtInitRegex = R\"(\\[\\[([0-9]+)\\]\\])\";\n\n\tconst std::string HDF5H_FileExtFinalRegex = R\"(\\[\\[(%d)\\]\\])\";\n\n\tconst std::string HDF5H_FileExtMult\t = \"[[\" + HDF5H_FileExtSpec + \"]]\";\n\n\tconst std::string HDF5H_DotFileExtMult\t = \".\" + HDF5H_FileExtMult;\n\n\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CFlowsheetEditor\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const FE_PortTypeInput = \"Input\";\n\n\tconst char* const FE_PortTypeOutput = \"Output\";\n\n\tconst char* const FE_UnitParamMinVal = \"Min = \";\n\n\tconst char* const FE_UnitParamMaxVal = \"Max = \";\n\n\tconst char* const FE_UnitDefaultName = \"Unit\";\n\n\tconst char* const FE_StreamDefaultName = \"Stream\";\n\n\tconst char* const FE_TDParamMessage = \"Use the table below to set values\";\n\n\tconst char* const FE_TDRemoveLast = \"At least one time point must remain\";\n\n\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CGridEditor\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const GE_GridTypeManual\t\t = \"Manual\";\n\n\tconst char* const GE_GridTypeEquidistant = \"Equidistant\";\n\n\tconst char* const GE_GridTypeGeometricS2L\t= \"Geometric inc\";\n\n\tconst char* const GE_GridTypeLogarithmicS2L = \"Logarithmic inc\";\n\n\tconst char* const GE_GridTypeGeometricL2S\t= \"Geometric dec\";\n\n\tconst char* const GE_GridTypeLogarithmicL2S = \"Logarithmic dec\";\n\n\tconst char* const GE_GridEntryNumeric = \"Numeric\";\n\n\tconst char* const GE_GridEntrySymbolic\t = \"Symbolic\";\n\n\tconst char* const GE_ErrorDuplicates = \"Unable to apply: duplicated distributions.\";\n\n\tconst char* const GE_ErrorUndefined = \"Unable to apply: undefined distribution.\";\n\n\tinline std::string GE_ErrorEmpty(const std::string& s) {\n\n\t\treturn std::string(\"Unable to apply: distribution grid for '\" + s + \"' is empty.\"); }\n\n\tinline std::string GE_ErrorNegative(const std::string& s) {\n\n\t\treturn std::string(\"Unable to apply: distribution grid for '\" + s + \"' contains negative values.\"); }\n\n\tinline std::string GE_ErrorSequence(const std::string& s) {\n\n\t\treturn std::string(\"Unable to apply: distribution grid for '\" + s + \"' does not form an ascending sequence.\"); }\n\n\tinline std::string GE_ErrorGaps(const std::string& s) {\n\n\t\treturn std::string(\"Unable to apply: distribution grid for '\" + s + \"' contains empty values.\"); }\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CModelsManager\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const MM_ConfigModelsParamName\t = \"modelsFolders\";\n\n\tconst char* const MM_ConfigModelsFlagsParamName = \"modelsFoldersActivity\";\n\n#ifdef _MSC_VER\n\n\tconst char* const MM_LibraryFileExtension = \".dll\";\n\n#else\n\n\tconst char* const MM_LibraryFileExtension = \".so\";\n\n#endif\n\n\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CSimulatorTab\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const ST_ButtonRunTextRun = \"Start simulation\";\n\n\tconst char* const ST_ButtonRunTextStop = \"Stop simulation\";\n\n\n\n\tconst char* const ST_LogSimStopRequest = \"Simulation stop requested...\";\n\n\tconst char* const ST_LogSimUserStop = \"Simulation was stopped by user!\";\n\n\tinline std::string ST_LogSimStart(const std::string& s1, const std::string& s2) {\n\n\t\treturn std::string(\"Simulation started at \" + s1 + \" on \" + s2); }\n\n\tinline std::string ST_LogSimFinishedTime(const std::string& s1, const std::string& s2, const std::string& s3)\t{\n\n\t\treturn std::string(\"\\nSimulation finished at \" + s1 + \" on \" + s2 + \" in \" + s3 + \" s\"); }\n\n\tconst char* const ST_LogInitStart = \"Initialization of flowsheet is started\";\n\n\tconst char* const ST_LogInitFinish = \"Initialization of flowsheet is finished\\n\";\n\n\n\n\tconst char* const ST_TitleClearResults = \"Clear simulation results\";\n\n\tconst char* const ST_QuestionClearResults = \"All simulation results will be removed. Proceed?\";\n\n\tconst char* const ST_TitleClearRecycles = \"Clear recycle streams\";\n\n\tconst char* const ST_QuestionClearRecycles = \"Initial values of all recycle streams will be removed. Proceed?\";\n\n\tconst char* const ST_TitleClearAll = \"Clear all\";\n\n\tconst char* const ST_QuestionClearAll = \"All simulation results and initial values of all recycle streams will be removed. Proceed?\";\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CBasicStreamsViewer\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const BSV_TabNameTable = \"Table view\";\n\n\tconst char* const BSV_TabNamePlot = \"Plot view\";\n\n\tconst char* const BSV_PropMass = \"Mass\";\n\n\tconst char* const BSV_PropMassFlow = \"Mass flow\";\n\n\tconst char* const BSV_PropTemperature = \"Temperature\";\n\n\tconst char* const BSV_PropPressure = \"Pressure\";\n\n\tconst char* const BSV_PropPhaseFractions = \"Phase fractions\";\n\n\tconst char* const BSV_PropSolidDistribution = \"Solid distribution\";\n\n\tconst char* const BSV_PropSauterDiameter = \"Sauter diameter\";\n\n\tconst char* const BSV_ComboBoxNoDimension\t= \" \";\n\n\tconst char* const BSV_ComboBoxAllCompounds = \"All compounds\";\n\n\tconst char* const BSV_LabelDistribution = \"Distribution:\";\n\n\tconst char* const BSV_LabelRows = \" Rows:\";\n\n\tconst char* const BSV_TableHeaderTime = \"Time [s]\";\n\n\tconst char* const BSV_TableHeaderNumber = \"Number\";\n\n\tconst char* const BSV_TableHeaderq3 = \"q3\";\n\n\tconst char* const BSV_TableHeaderQ3 = \"Q3\";\n\n\tconst char* const BSV_TableHeaderq2 = \"q2\";\n\n\tconst char* const BSV_TableHeaderQ2 = \"Q2\";\n\n\tconst char* const BSV_TableHeaderq0 = \"q0\";\n\n\tconst char* const BSV_TableHeaderQ0 = \"Q0\";\n\n\tconst char* const BSV_TableHeaderMassFrac = \"Mass fraction\";\n\n\tconst char* const BSV_TableHeaderSauter = \"Sauter diameter [m]\";\n\n\tconst char* const BSV_HeaderDiameter\t\t= \"Diameter\";\n\n\tconst char* const BSV_HeaderVolume\t\t\t= \"Volume\";\n\n\tconst char* const BSV_HeaderPartPorosity = \"Particle porosity [-]\";\n\n\tconst char* const BSV_HeaderFormFactor\t\t= \"Form factor [-]\";\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CBasicStreamsEditor\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const SDE_CompoundsMixture = \"Total mixture\";\n\n\tconst char* const SDE_TotalMixture = \"Total mixture\";\n\n\n\n\tconst char* const FUN_EmptyUnits\t = \"[-]\";\n\n\tconst char* const FUN_DiameterUnits = \"[m]\";\n\n\tconst char* const FUN_VolumeUnits\t = \"[m3]\";\n\n\tconst char* const FUN_DiameterUnitsInv = \"[1/m]\";\n\n\tconst char* const FUN_VolumeUnitsInv = \"[1/m3]\";\n\n\tconst char* const FUN_NormalName = \"Normal\";\n\n\tconst char* const FUN_RRSBName = \"RRSB\";\n\n\tconst char* const FUN_GGSName = \"GGS\";\n\n\tconst char* const FUN_LogNormalName = \"LogNormal\";\n\n\tconst char* const FUN_NormalParam1\t = \"D50\";\n\n\tconst char* const FUN_NormalParam2\t = \"Standard deviation\";\n\n\tconst char* const FUN_RRSBParam1\t = \"D63\";\n\n\tconst char* const FUN_RRSBParam2\t = \"Dispersion\";\n\n\tconst char* const FUN_GGSParam1\t = \"Dmax\";\n\n\tconst char* const FUN_GGSParam2\t = \"Dispersion\";\n\n\tconst char* const FUN_LogNormalParam1 = \"D50\";\n\n\tconst char* const FUN_LogNormalParam2 = \"Geometric mean deviation\";\n\n\tconst char* const FUN_UndefinedParam = \"Undefined\";\n\n\tconst char* const FUN_ErrorName = \"Wrong parameters\";\n\n\tinline std::string FUN_ErrorZeroParameter(const std::string& s1) {\n\n\t\treturn std::string(s1 + \" can not be equal to zero!\"); }\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CTearStreamsEditor\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const TSE_PartitionName = \"Partition\";\n\n\tconst char* const TSE_WindowName = \"Tear Streams Editor\";\n\n\tconst char* const TSE_InfoWrongMode = \"You cannot change initial data in Auto mode.\";\n\n\tconst char* const TSE_QuestionRemoveAll = \"Do you really want to remove all initial data from all tear streams?\";\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CMaterialsDatabaseTab\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const MDT_DialogSaveName = \"Save database\";\n\n\tconst char* const MDT_DialogLoadName = \"Load database\";\n\n\tconst char* const MDT_DialogDMDBFilter = \"Materials database (*.dmdb);;All files (*.*);;\";\n\n\tconst char* const MDT_RemoveCompoundTitle = \"Remove compound\";\n\n\tinline std::string MDT_RemoveCompoundConfirm(const std::string& s1) { return std::string(\"Do you really want to remove \" + s1 + \"?\"); }\n\n\tconst char* const MDT_RemoveCorrelationsTitle = \"Remove correlations\";\n\n\tinline std::string MDT_RemoveCorrelationsConfirm(const std::string& s1) { return std::string(\"Do you really want to remove all correlations of \" + s1 + \"?\"); }\n\n\tconst char* const MDT_WindowTitle = \"Compounds editor\";\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CModulesManagerTab\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const MMT_Dynamic = \"Dynamic unit\";\n\n\tconst char* const MMT_SteadyState = \"Steady-state unit\";\n\n\tconst char* const MMT_Solver = \"solver\";\n\n\n\n//////////////////////////////////////////////////////////////////////////\n\n/// CCalculationSequenceEditor\n\n//////////////////////////////////////////////////////////////////////////\n\n\tconst char* const CSE_Partition = \"Partition \";\n\n\tconst char* const CSE_Models = \"Models\";\n\n\tconst char* const CSE_Streams = \"Tear streams\";\n", "file_path": "Utilities/DyssolStringConstants.h", "rank": 4, "score": 35761.26323797379 }, { "content": "\tenum class EBreakage : size_t { BINARY = 0, DIEMER, VOGEL, AUSTIN };\n", "file_path": "Units/CrusherPBMTM/CrusherPBMTM.h", "rank": 5, "score": 34889.788391587994 }, { "content": "class CGridDimensionNumeric : public CGridDimension\n\n{\n\n\tstatic constexpr unsigned m_saveVersion{ 1 };\t// Current version of the saving procedure.\n\n\n\n\tstd::vector<double> m_grid{ 0 , 1 };\t\t\t// Grid itself.\n\n\n\npublic:\n\n\tCGridDimensionNumeric();\n\n\texplicit CGridDimensionNumeric(EDistrTypes _type);\n\n\tCGridDimensionNumeric(EDistrTypes _type, std::vector<double> _grid);\n\n\n\n\t// Returns a non-managed pointer to a copy of this.\n\n\t[[nodiscard]] CGridDimensionNumeric* Clone() const override;\n\n\n\n\t// Returns the number of classes defined in this grid dimension.\n\n\t[[nodiscard]] size_t ClassesNumber() const override;\n\n\t// Returns current numerical grid.\n\n\t[[nodiscard]] std::vector<double> Grid() const;\n\n\n\n\t// Sets new grid.\n", "file_path": "ModelsAPI/MultidimensionalGrid.h", "rank": 6, "score": 34558.27736853347 }, { "content": "class CConstUnitParameter : public CBaseUnitParameter\n\n{\n\n\tstatic const unsigned m_cnSaveVersion{ 1 };\n\n\n\n\tT m_value{};\t\t\t\t\t\t\t\t\t///< Const value.\n\n\tT m_min{};\t\t\t\t\t\t\t\t\t\t///< Minimum allowed value.\n\n\tT m_max{};\t\t\t\t\t\t\t\t\t\t///< Maximum allowed value.\n\n\n\npublic:\n\n\tCConstUnitParameter();\n\n\tCConstUnitParameter(std::string _name, std::string _units, std::string _description, T _min, T _max, T _value);\n\n\n\n\tvoid Clear() override;\t\t\t\t\t\t\t///< Sets value to zero.\n\n\n\n\tT GetValue() const { return m_value; }\t\t\t///< Returns constant unit parameter value.\n\n\tT GetMin() const{ return m_min; }\t\t\t\t///< Returns minimum allowed value.\n\n\tT GetMax() const{ return m_max; }\t\t\t\t///< Returns maximum allowed value.\n\n\n\n\tvoid SetValue(T _value) { m_value = _value; }\t///< Sets constant unit parameter value.\n\n\tvoid SetMin(T _min){ m_min = _min; }\t\t\t///< Sets minimum allowed value.\n", "file_path": "ModelsAPI/UnitParameters.h", "rank": 7, "score": 33422.27654238813 }, { "content": "\tenum class EType { STREAMS = 0, UNITS = 1 } m_focusType{ EType::STREAMS };\n\n\n\npublic:\n\n\tCDustFormationTesterTab(const CFlowsheet* _pFlowsheet, const CMaterialsDatabase* _matrialsDB, QWidget* parent = Q_NULLPTR);\n\n\n\n\tvoid InitializeConnections();\n\n\tvoid UpdateWholeView();\n\n\n\npublic slots:\n\n\tvoid setVisible(bool _bVisible) override;\n\n\n\nprivate:\n\n\tvoid UpdateStreams() const;\n\n\tvoid UpdateUnits() const;\n\n\tvoid UpdateHoldups() const;\n\n\tvoid UpdatePorosity() const;\n\n\tvoid UpdateMoisture() const;\n\n\tvoid UpdateMoisture90() const;\n\n\tvoid UpdateCompounds() const;\n\n\tvoid UpdateDataTable();\n", "file_path": "GUIDialogs/DustFormationTesterTab/DustFormationTesterTab.h", "rank": 8, "score": 32612.66096301005 }, { "content": "\tenum class ESelection : size_t { CONSTANT = 0, LINEAR, QUADRATIC, POWER, EXPONENTIAL, KING, AUSTIN };\n", "file_path": "Units/CrusherPBMTM/CrusherPBMTM.h", "rank": 9, "score": 28806.445388073007 }, { "content": "\tenum class EKernels : size_t\n\n\t{\n\n\t\tCONSTANT = 0,\n\n\t\tSUM = 1,\n\n\t\tPRODUCT = 2,\n\n\t\tBROWNIAN = 3,\n\n\t\tSHEAR = 4,\n\n\t\tPEGLOW = 5,\n\n\t\tCOAGULATION = 6,\n\n\t\tGRAVITATIONAL = 7,\n\n\t\tEKE = 8,\n\n\t\tTHOMPSON = 9,\n\n\t\tCUSTOM = 10,\n\n\t};\n\n\n\nprotected:\n\n\tusing u_matr_t = std::vector<std::vector<size_t>>;\n\n\tusing d_matr_t = std::vector<std::vector<double>>;\n\n\tusing u_vect_t = std::vector<size_t>;\n\n\tusing d_vect_t = std::vector<double>;\n", "file_path": "BaseSolvers/AgglomerationSolver.h", "rank": 10, "score": 26919.74312966407 }, { "content": "}\n\n\n\nbool CDimensionParameters::SetMessageAndReturn(const std::string& _message) const\n\n{\n\n\tm_message = _message;\n\n\treturn false;\n\n}\n\n\n\nbool CDimensionParameters::IsValid() const\n\n{\n\n\tm_message.clear();\n\n\tif (m_grid->DimensionType() == DISTR_UNDEFINED)\n\n\t\treturn SetMessageAndReturn(StrConst::GE_ErrorUndefined);\n\n\tconst auto distrName = std::vector<std::string>(DISTR_NAMES)[GetDistributionTypeIndex(static_cast<EDistrTypes>(ui.comboDistribution->currentData().toUInt()))];\n\n\tif (m_grid->GridType() == EGridEntry::GRID_NUMERIC)\n\n\t{\n\n\t\tconst auto& grid = dynamic_cast<CGridDimensionNumeric*>(m_grid.get())->Grid();\n\n\t\tif (grid.empty())\n\n\t\t\treturn SetMessageAndReturn(StrConst::GE_ErrorEmpty(distrName));\n\n\t\tif (std::any_of(grid.begin(), grid.end(), [](auto v) { return v < 0; }))\n", "file_path": "GUIDialogs/GridEditor/DimensionParameters.cpp", "rank": 11, "score": 23.25563102762053 }, { "content": "/* Copyright (c) 2021, Dyssol Development Team. All rights reserved. This file is part of Dyssol. See LICENSE file for license information. */\n\n\n\n#include \"ScriptRunner.h\"\n\n#include \"ScriptJob.h\"\n\n#include \"DyssolStringConstants.h\"\n\n#include \"DyssolUtilities.h\"\n\n#include <sstream>\n\n#include <fstream>\n\n#include <functional>\n\n\n\nusing namespace ScriptInterface;\n\nusing namespace StrConst;\n\nnamespace fs = std::filesystem;\n\nnamespace ch = std::chrono;\n\n\n\nbool CScriptRunner::RunJob(const CScriptJob& _job)\n\n{\n\n\tconst auto tStart = ch::steady_clock::now();\n\n\n\n\tClear();\n", "file_path": "ScriptInterface/ScriptRunner.cpp", "rank": 13, "score": 20.835265443679205 }, { "content": "\tvoid SetParamsList(const std::vector<double>& _params);\n\n\t// Sets list of values.\n\n\tvoid SetValuesList(const std::vector<double>& _values);\n\n\n\n\t// Returns whether the value for specified parameter has been defined in the list.\n\n\t[[nodiscard]] bool HasParam(double _param) const;\n\n\t// Checks if the values are the same for all defined params.\n\n\t[[nodiscard]] bool IsConst() const;\n\n\t// Removes all previously defined values from the list.\n\n\tvoid Clear();\n\n\n\n\t// Output stream operator.\n\n\tfriend std::ostream& operator<<(std::ostream& _s, const CDependentValues& _obj);\n\n\t// Input stream operator.\n\n\tfriend std::istream& operator>>(std::istream& _s, CDependentValues& _obj);\n\n\n\n\t// Comparison.\n\n\tbool operator==(const CDependentValues& _v) const;\n\n\n\nprivate:\n\n\t// Performs linear interpolation. If the parameter is out of defined limits, performs nearest-neighbor extrapolation of data.\n\n\t[[nodiscard]] double Interpolate(double _param) const;\n\n};\n", "file_path": "ModelsAPI/DependentValues.h", "rank": 14, "score": 20.40161398931021 }, { "content": "\tstd::string GetKey() const;\n\n\t// Sets new compound's key\n\n\tvoid SetKey(const std::string& _sKey);\n\n\n\n\t// Returns number of const properties\n\n\tsize_t ConstPropertiesNumber() const;\n\n\t// Returns number of temperature/pressure-dependent properties.\n\n\tsize_t TPPropertiesNumber() const;\n\n\n\n\t// Returns true if the compound contains specified constant property.\n\n\tbool HasConstProperty(ECompoundConstProperties _nType) const;\n\n\t// Returns true if the compound contains specified temperature/pressure-dependent property.\n\n\tbool HasTPProperty(ECompoundTPProperties _nType) const;\n\n\t// Returns true if the compound contains specified constant or temperature/pressure-dependent property.\n\n\tbool HasProperty(unsigned _nType) const;\n\n\n\n\t// Adds new constant property if it does not exist yet.\n\n\tvoid AddConstProperty(ECompoundConstProperties _key, const std::string& _name, const std::wstring& _units, double _defaultValue);\n\n\t// Adds new temperature/pressure-dependent property if it does not exist yet.\n\n\tvoid AddTPDepProperty(ECompoundTPProperties _key, const std::string& _name, const std::wstring& _units, double _defaultValue);\n", "file_path": "MaterialsDatabase/Compound.h", "rank": 15, "score": 19.92863646377175 }, { "content": "\tvoid RemoveTimePoint( double _dTime );\n\n\t/** Removes time points from interval, including or excluding boundaries.*/\n\n\tvoid RemoveTimePoints( double _dStart, double _dEnd, bool _inclusive = true);\n\n\t/** Removes all time points after the specified time.\n\n\t*\tIf _bIncludeTime == true, than _dTime will be includede in this time interval.*/\n\n\tvoid RemoveTimePointsAfter( double _dTime, bool _bIncludeTime = false );\n\n\t/** Removes all defined time points.*/\n\n\tvoid RemoveAllTimePoints();\n\n\t/** Returns vector of time points for interval.*/\n\n\tstd::vector<double> GetTimePoints( double _dStart, double _dEnd ) const;\n\n\t/** Returns all defined time points.*/\n\n\tstd::vector<double> GetAllTimePoints() const;\n\n\t/** Returns time point with specified index. If there is no such time point, than -1 will be returned.*/\n\n\tdouble GetTimeForIndex( unsigned _nIndex ) const;\n\n\t/** Returns number of defined time points.*/\n\n\tsize_t GetTimePointsNumber() const;\n\n\n\n\t// ========== Functions to work with MINIMAL FRACTION\n\n\n\n\t/** Returns current minimal fraction.*/\n", "file_path": "ModelsAPI/MDMatrix.h", "rank": 16, "score": 19.60636006798409 }, { "content": "\tbool HasItem(size_t _item) const;\t\t\t\t ///< Returns true if m_items contains _item.\n\n\tbool HasName(const std::string& _name) const;\t ///< Returns true if m_items contains item with _name.\n\n\n\n\tbool IsInBounds() const override;\t\t\t\t ///< Checks whether m_selected is one of the m_items.\n\n\n\n\t// Outputs user-specified values of the parameter to a stream.\n\n\tstd::ostream& ValueToStream(std::ostream& _s) override;\n\n\t// Reads user-specified values of the parameter from a stream.\n\n\tstd::istream& ValueFromStream(std::istream& _s) override;\n\n\n\n\tvoid SaveToFile(CH5Handler& _h5Saver, const std::string& _path) const;\n\n\tvoid LoadFromFile(const CH5Handler& _h5Loader, const std::string& _path);\n\n};\n\n\n\n\n", "file_path": "ModelsAPI/UnitParameters.h", "rank": 17, "score": 19.311668979998963 }, { "content": "\treturn new CGridDimensionNumeric(*this);\n\n}\n\n\n\nbool CGridDimensionNumeric::Equal(const CGridDimension& _other) const\n\n{\n\n\tconst auto* p = dynamic_cast<const CGridDimensionNumeric*>(&_other);\n\n\treturn p && CGridDimension::Equal(_other) && m_grid == p->m_grid;\n\n}\n\n\n\nsize_t CGridDimensionNumeric::ClassesNumber() const\n\n{\n\n\treturn m_grid.size() - 1;\n\n}\n\n\n\nstd::vector<double> CGridDimensionNumeric::Grid() const\n\n{\n\n\treturn m_grid;\n\n}\n\n\n\nvoid CGridDimensionNumeric::SetGrid(const std::vector<double>& _grid)\n", "file_path": "ModelsAPI/MultidimensionalGrid.cpp", "rank": 18, "score": 17.696454209376913 }, { "content": "\tvoid SetMax(T _max){ m_max = _max; }\t\t\t///< Sets maximum allowed value.\n\n\n\n\tbool IsInBounds() const override;\t\t\t\t///< Checks whether m_value lays in range [m_min; m_max].\n\n\n\n\t// Outputs user-specified values of the parameter to a stream.\n\n\tstd::ostream& ValueToStream(std::ostream& _s) override;\n\n\t// Reads user-specified values of the parameter from a stream.\n\n\tstd::istream& ValueFromStream(std::istream& _s) override;\n\n\n\n\tvoid SaveToFile(CH5Handler& _h5File, const std::string& _path) const;\n\n\tvoid LoadFromFile(const CH5Handler& _h5File, const std::string& _path);\n\n};\n\n\n\nusing CConstRealUnitParameter = CConstUnitParameter<double>;\n\nusing CConstIntUnitParameter = CConstUnitParameter<int64_t>;\n\nusing CConstUIntUnitParameter = CConstUnitParameter<uint64_t>;\n\n\n\n// Class for constant list unit parameters.\n\ntemplate<typename T>\n", "file_path": "ModelsAPI/UnitParameters.h", "rank": 19, "score": 17.523365369993513 }, { "content": "\t//void CrearData();\n\n\n\n\t// Saves data to file.\n\n\tvoid SaveToFile(CH5Handler& _h5File, const std::string& _path) const;\n\n\t// Loads data from file\n\n\tvoid LoadFromFile(const CH5Handler& _h5File, const std::string& _path);\n\n\n\nprivate:\n\n\t// Performs linear interpolation. If the parameter is outside of the defined limits, performs nearest-neighbor extrapolation of data. Returns zero if the data vector is empty.\n\n\tdouble Interpolate(double _time) const;\n\n\t// Checks whether the given time point exists.\n\n\tbool HasTime(double _time) const;\n\n\t// Returns the nearest time point before _time.\n\n\tdouble PreviousTime(double _time) const;\n\n\t// Returns iterators pointing on values between the specified interval, including or excluding boundaries. If the values cannot be found, return two iterators to the end.\n\n\tstd::pair<std::vector<STDValue>::iterator, std::vector<STDValue>::iterator> Interval(double _timeBeg, double _timeEnd, bool _inclusive = true);\n\n\t// Returns const iterators pointing on values between the specified interval, including or excluding boundaries. If the values cannot be found, return two iterators to the end.\n\n\tstd::pair<std::vector<STDValue>::const_iterator, std::vector<STDValue>::const_iterator> Interval(double _timeBeg, double _timeEnd, bool _inclusive = true) const;\n\n};\n", "file_path": "ModelsAPI/TimeDependentValue.h", "rank": 20, "score": 17.44346915540563 }, { "content": "\tfriend bool operator==(const CGridDimension& _lhs, const CGridDimension& _rhs);\n\n\t// Compares two objects.\n\n\tfriend bool operator!=(const CGridDimension& _lhs, const CGridDimension& _rhs);\n\n\n\n\t// Returns the type of the dimension.\n\n\t[[nodiscard]] EDistrTypes DimensionType() const;\n\n\t// Returns the type of the grid for this dimension.\n\n\t[[nodiscard]] EGridEntry GridType() const;\n\n\t// Returns the number of classes defined in this grid dimension.\n\n\t[[nodiscard]] virtual size_t ClassesNumber() const;\n\n\n\n\t// Sets new distribution type.\n\n\tvoid SetType(EDistrTypes _type);\n\n\n\nprotected:\n\n\t// Compares for equality with another object.\n\n\t[[nodiscard]] virtual bool Equal(const CGridDimension& _other) const;\n\n};\n\n\n\n/*\n\n * Numeric grid.\n\n */\n", "file_path": "ModelsAPI/MultidimensionalGrid.h", "rank": 21, "score": 17.427782128148642 }, { "content": "\tdouble GetValue(double _time) const;\t\t///< Returns unit parameter value at given time point using interpolation if necessary.\n\n\tvoid SetValue(double _time, double _value);\t///< Adds new unit parameter value at given time point or changes the value of existing one.\n\n\tvoid RemoveValue(double _time); ///< Removes unit parameter value at given time point if it exists.\n\n\n\n\tstd::vector<double> GetTimes() const;\t\t///< Returns list of all defined time points.\n\n\tstd::vector<double> GetValues() const;\t\t///< Returns list of all defined values.\n\n\tconst CDependentValues& GetTDData() const; ///< Returns the time dependent data itself.\n\n\n\n\tsize_t Size() const;\t ///< Returns number of defined time points.\n\n\tbool IsEmpty() const;\t ///< Checks whether any time point is defined.\n\n\tbool IsInBounds() const override; ///< Checks whether all m_values lay in range [m_min; m_max].\n\n\n\n\t// Outputs user-specified values of the parameter to a stream.\n\n\tstd::ostream& ValueToStream(std::ostream& _s) override;\n\n\t// Reads user-specified values of the parameter from a stream.\n\n\tstd::istream& ValueFromStream(std::istream& _s) override;\n\n\n\n\tvoid SaveToFile(CH5Handler& _h5File, const std::string& _path) const;\n\n\tvoid LoadFromFile(const CH5Handler& _h5File, const std::string& _path);\n\n};\n\n\n\n\n", "file_path": "ModelsAPI/UnitParameters.h", "rank": 22, "score": 17.331393863803882 }, { "content": "\tEUnitParameter GetType() const; ///< Returns parameter type.\n\n\tstd::string GetName() const; ///< Returns parameter name.\n\n\tstd::string GetUnits() const; ///< Returns parameter units.\n\n\tstd::string GetDescription() const; ///< Returns parameter description.\n\n\n\n\tvoid SetType(EUnitParameter _type); ///< Sets parameter type.\n\n\tvoid SetName(const std::string& _name); ///< Sets parameter name.\n\n\tvoid SetUnits(const std::string& _units); ///< Sets parameter units.\n\n\tvoid SetDescription(const std::string& _description); ///< Sets parameter description.\n\n\n\n\tvirtual bool IsInBounds() const;\t ///< Checks whether all values lay in allowed range.\n\n\n\n\t// Outputs user-specified values of the parameter to a stream.\n\n\tvirtual std::ostream& ValueToStream(std::ostream& _s) = 0;\n\n\t// Reads user-specified values of the parameter from a stream.\n\n\tvirtual std::istream& ValueFromStream(std::istream& _s) = 0;\n\n\n\n\t//virtual void SaveToFile(CH5Handler& _h5Saver, const std::string& _path) = 0;\n\n\t//virtual void LoadFromFile(CH5Handler& _h5Loader, const std::string& _path) = 0;\n\n};\n\n\n\n\n\n// Class for constant single-value unit parameters.\n\ntemplate<typename T>\n", "file_path": "ModelsAPI/UnitParameters.h", "rank": 23, "score": 17.00794407680395 }, { "content": "\n\n\tCCompound* GetSelectedCompound(int _row = -1) const;\t\t\t\t\t// Returns pointer to a currently selected compound (if _row == -1) or to a compound from specified row.\n\n\tstd::pair<CCompound*, CCompound*> GetSelectedInterCompounds() const;\t// Returns pointers to currently selected compounds on Interactions tab.\n\n\tCInteraction* GetSelectedInteraction() const;\t\t\t\t\t\t\t// Returns pointers to currently selected interaction.\n\n\tstatic unsigned GetPropertyKey(const CQtTable* _pTable, int _iRow);\n\n\tbool IsConstProperty(int _iRow) const;\t\t\t\t\t\t\t\t\t\t// Returns true if the property in the specified row is constant.\n\n\n\n\tvoid SelectCompound(const CCompound* _pCompound) const;\t// Makes specified compound currently selected.\n\n\tvoid TogglePropertyConstancy(CQtTable* _pTable, int _iRow, CTPDProperty* _pProp);\n\n\n\n\tvoid SetMaterialsDatabaseModified(bool _bModified);//set value for state MDB flag\n\n\tbool IsUserConfirm(); // Asks user about saving of current database state and saves it if needed. Returns false if user pressed Cancel.\n\n\n\n\t// Returns a list of user defined properties of all types.\n\n\tstd::vector<unsigned> ActiveUDProps() const;\n\n\t// Retunrs the first available user defined property of a specified type.\n\n\tunsigned FirstAvailableUDProp(MDBDescriptors::EPropertyType _type) const;\n\n\n\nsignals:\n\n\tvoid MaterialDatabaseWasChanged();\t// Called when material database has been changed.\n\n};\n", "file_path": "GUIDialogs/MaterialsDatabaseTab/MaterialsDatabaseTab.h", "rank": 24, "score": 16.71859914056274 }, { "content": "\treturn m_vConstProperties.size();\n\n}\n\n\n\nsize_t CCompound::TPPropertiesNumber() const\n\n{\n\n\treturn m_vTPProperties.size();\n\n}\n\n\n\nbool CCompound::HasConstProperty(ECompoundConstProperties _nType) const\n\n{\n\n\tfor (const auto& c : m_vConstProperties)\n\n\t\tif (c.GetType() == _nType)\n\n\t\t\treturn true;\n\n\treturn false;\n\n}\n\n\n\nbool CCompound::HasTPProperty(ECompoundTPProperties _nType) const\n\n{\n\n\tfor (const auto& tp : m_vTPProperties)\n\n\t\tif (tp.GetType() == _nType)\n", "file_path": "MaterialsDatabase/Compound.cpp", "rank": 25, "score": 16.671067481527032 }, { "content": "\t// Add new path to look for models. Returns true on success.\n\n\tbool AddDir(const std::filesystem::path& _path, bool _active = true);\n\n\t// Removes the specified path with models. Returns true on success.\n\n\tbool RemoveDir(size_t _index);\n\n\t// Moves path upwards in the list. Returns true on success.\n\n\tbool UpDir(size_t _index);\n\n\t// Moves path downwards in the list. Returns true on success.\n\n\tbool DownDir(size_t _index);\n\n\t// Returns path.\n\n\tstd::filesystem::path GetDirPath(size_t _index) const;\n\n\t// Returns all active paths.\n\n\tstd::vector<std::filesystem::path> GetAllActiveDirPaths() const;\n\n\t// Returns activity of the specified path.\n\n\tbool GetDirActivity(size_t _index) const;\n\n\t// Sets activity of the specified path.\n\n\tvoid SetDirActivity(size_t _index, bool _active);\n\n\t// Removes all paths and models.\n\n\tvoid Clear();\n\n\n\n\t// Returns a list of descriptors for all available units.\n", "file_path": "SimulatorCore/ModelsManager.h", "rank": 26, "score": 16.495239889920988 }, { "content": "\t// Removes constant property if it exists.\n\n\tvoid RemoveConstProperty(ECompoundConstProperties _key);\n\n\t// Removes temperature/pressure-dependent property if it exists.\n\n\tvoid RemoveTPDepProperty(ECompoundTPProperties _key);\n\n\n\n\t//////////////////////////////////////////////////////////////////////////\n\n\t/// Pointers getters\n\n\n\n\t// Returns pointer to a specified const property. Returns nullptr if property is not found.\n\n\tCConstProperty* GetConstProperty(ECompoundConstProperties _nType);\n\n\t// Returns constant pointer to a specified const property. Returns nullptr if property is not found.\n\n\tconst CConstProperty* GetConstProperty(ECompoundConstProperties _nType) const;\n\n\t// Returns vector of defined const properties.\n\n\tconst std::vector<CConstProperty>& GetConstProperties() const;\n\n\t// Returns pointer to a specified temperature/pressure-dependent property. Returns nullptr if property is not found.\n\n\tCTPDProperty* GetTPProperty(ECompoundTPProperties _nType);\n\n\t// Returns constant pointer to a specified temperature/pressure-dependent property. Returns nullptr if property is not found.\n\n\tconst CTPDProperty* GetTPProperty(ECompoundTPProperties _nType) const;\n\n\t// Returns pointer to a specified temperature/pressure-dependent property by its index. Returns nullptr if property is not found.\n\n\tCTPDProperty* GetTPPropertyByIndex(size_t _index);\n", "file_path": "MaterialsDatabase/Compound.h", "rank": 27, "score": 16.243869256285436 }, { "content": "\tvoid CacheFlagStreamsAfterReload(bool val);\n\n\tproxy<bool> cacheFlagHoldupsAfterReload;\n\n\tvoid CacheFlagHoldupsAfterReload(bool val);\n\n\tproxy<bool> cacheFlagInternalAfterReload;\n\n\tvoid CacheFlagInternalAfterReload(bool val);\n\n\tproxy<uint32_t> cacheWindow;\n\n\tvoid CacheWindow(uint32_t val);\n\n\tproxy<uint32_t> cacheWindowAfterReload;\n\n\tvoid CacheWindowAfterReload(uint32_t val);\n\n\n\n\t// == File saving\n\n\tproxy<bool> fileSingleFlag;\t\t// true - single file, false - file is split on subfiles with MAX_FILE_SIZE size\n\n\tvoid FileSingleFlag(bool val);\n\n\n\n\t// == Initialization of tear streams\n\n\tproxy<bool> initializeTearStreamsAutoFlag;\t// true - automatically calculate initialization values using previous calculations, false - user defined initial values\n\n\tvoid InitializeTearStreamsAutoFlag(bool val);\n\n\n\n\t// == Enthalpy calculator\n\n\tproxy<double> enthalpyMinT;\n\n\tvoid EnthalpyMinT(double val);\n\n\tproxy<double> enthalpyMaxT;\n\n\tvoid EnthalpyMaxT(double val);\n\n\tproxy<uint32_t> enthalpyInt;\n\n\tvoid EnthalpyInt(uint32_t val);\n\n};\n\n\n", "file_path": "SimulatorCore/ParametersHolder.h", "rank": 28, "score": 15.75741785052131 }, { "content": "\tvoid ClearCache();\n\n\n\n\tvoid CreateMenu(); // create window menu\n\n\tvoid UpdateMenu(); // update recent files options in the menu\n\n\n\n\tvoid SaveToFile( const QString &_sFileName ) const;\t// save flowsheet to specified file\n\n\tvoid LoadFromFile( const QString &_sFileName ) const;\t// load flowsheet from specified file\n\n\n\n\tvoid SetCurrFlowsheetFile(const QString &_fileName);\t\t// set new flowsheet file\n\n\tvoid AddFileToRecentList(const QString& _fileToAdd);\t// Adds a flowsheet file _fileName to the list of recent files.\n\n\tbool CheckAndAskUnsaved();\t// Asks user about saving of current flowsheet and saves it if needed. Returns false if the calling process should be cancelled.\n\n\tbool SaveAndWait(); // Starts saving thread and waits until current flowsheet is saved. Returns true on successful save.\n\n\tstatic void CloseDyssol(int _errCode = 0); // terminates the application with selected error code\n\n\tvoid SetFlowsheetModified(bool _bModified);\n\n\tbool IsFlowsheetModified() const;\n\n\n\n\tvoid LoadMaterialsDatabase();\n\n\tstatic size_t OtherRunningDyssolCount(); // Returns the amount of running instances of Dyssol except this one.\n\n\n\npublic slots:\n", "file_path": "DyssolMainWindow/Dyssol.h", "rank": 29, "score": 15.5408169180925 }, { "content": "}\n\n\n\ntemplate<typename T>\n\nbool CConstUnitParameter<T>::IsInBounds() const\n\n{\n\n\treturn m_value >= m_min && m_value <= m_max;\n\n}\n\n\n\ntemplate <typename T>\n\nstd::ostream& CConstUnitParameter<T>::ValueToStream(std::ostream& _s)\n\n{\n\n\treturn _s << m_value;\n\n}\n\n\n\ntemplate <typename T>\n\nstd::istream& CConstUnitParameter<T>::ValueFromStream(std::istream& _s)\n\n{\n\n\treturn _s >> m_value;\n\n}\n\n\n", "file_path": "ModelsAPI/UnitParameters.cpp", "rank": 30, "score": 15.495203517431221 }, { "content": "\tconst CStream* GetStream(const std::string & _name) const;\n\n\t// Returns a stream with the specified name. If such stream does not exist, a logic_error exception is thrown.\n\n\tCStream* GetStream(const std::string& _name);\n\n\t// Removes the stream with the specified name from the unit. If such stream does not exist, a logic_error exception is thrown.\n\n\tvoid RemoveStream(const std::string& _name);\n\n\n\n\t// Sets up the stream structure (MD dimensions, phases, materials, etc.) the same as it is configured in the unit. Removes all existing data.\n\n\tvoid SetupStream(CBaseStream* _stream) const;\n\n\n\n\t////////////////////////////////////////////////////////////////////////////////\n\n\t// Unit parameters\n\n\t//\n\n\n\n\t// Returns a const reference to unit parameters manager.\n\n\tconst CUnitParametersManager& GetUnitParametersManager() const;\n\n\t// Returns a reference to unit parameters manager.\n\n\tCUnitParametersManager& GetUnitParametersManager();\n\n\n\n\t// Adds a new real constant unit parameter and returns a pointer to it. If the unit already has a parameter with the same name, logic_error exception is thrown.\n\n\tCConstRealUnitParameter* AddConstRealParameter(const std::string& _name, double _initValue, const std::string& _units, const std::string& _description, double _minValue = std::numeric_limits<double>::lowest(), double _maxValue = std::numeric_limits<double>::max());\n", "file_path": "ModelsAPI/BaseUnit.h", "rank": 31, "score": 15.479034440568253 }, { "content": "\treturn m_values.Size();\n\n}\n\n\n\nbool CTDUnitParameter::IsEmpty() const\n\n{\n\n\treturn m_values.IsEmpty();\n\n}\n\n\n\nbool CTDUnitParameter::IsInBounds() const\n\n{\n\n\tfor (const auto& value : m_values.GetValuesList())\n\n\t\tif (value < m_min || value > m_max)\n\n\t\t\treturn false;\n\n\treturn true;\n\n}\n\n\n\nstd::ostream& CTDUnitParameter::ValueToStream(std::ostream& _s)\n\n{\n\n\treturn _s << m_values;\n\n}\n", "file_path": "ModelsAPI/UnitParameters.cpp", "rank": 32, "score": 15.471016753858123 }, { "content": "size_t CUnitParametersManager::ParametersNumber() const\n\n{\n\n\treturn m_parameters.size();\n\n}\n\n\n\nbool CUnitParametersManager::IsNameExist(const std::string& _name) const\n\n{\n\n\tfor (const auto& p : m_parameters)\n\n\t\tif (p->GetName() == _name)\n\n\t\t\treturn true;\n\n\treturn false;\n\n}\n\n\n\nvoid CUnitParametersManager::AddConstRealParameter(const std::string& _name, const std::string& _units, const std::string& _description, double _min, double _max, double _value)\n\n{\n\n\tif (IsNameExist(_name)) return;\n\n\tm_parameters.emplace_back(new CConstUnitParameter<double>{ _name, _units, _description, _min, _max, _value });\n\n}\n\n\n\nvoid CUnitParametersManager::AddConstIntParameter(const std::string& _name, const std::string& _units, const std::string& _description, int64_t _min, int64_t _max, int64_t _value)\n", "file_path": "ModelsAPI/UnitParameters.cpp", "rank": 33, "score": 15.26441654230593 }, { "content": "\t{\n\n\t\tconst auto vals = dynamic_cast<CGridDimensionNumeric*>(m_grid.get())->Grid();\n\n\t\tui.tableGrid->setRowCount(static_cast<int>(vals.size()));\n\n\t\tui.tableGrid->SetItemsColEditable(0, 0, FromM(vals));\n\n\t}\n\n\telse if (m_grid->GridType() == EGridEntry::GRID_SYMBOLIC)\n\n\t{\n\n\t\tauto vals = dynamic_cast<CGridDimensionSymbolic*>(m_grid.get())->Grid();\n\n\t\tui.tableGrid->setRowCount(static_cast<int>(vals.size()));\n\n\t\tif (m_grid->DimensionType() == DISTR_COMPOUNDS)\n\n\t\t\tfor (auto& v : vals)\n\n\t\t\t\tif (const auto* compound = m_materialsDB.GetCompound(v))\n\n\t\t\t\t\tv = compound->GetName();\n\n\t\tui.tableGrid->SetItemsColEditable(0, 0, vals);\n\n\t}\n\n}\n\n\n\nvoid CDimensionParameters::UpdateWidgetsVisibility() const\n\n{\n\n\tconst bool visibleFun = m_grid->GridType() == EGridEntry::GRID_NUMERIC;\n", "file_path": "GUIDialogs/GridEditor/DimensionParameters.cpp", "rank": 34, "score": 15.214986186370592 }, { "content": "\tif (val > 0)\n\n\t\tcacheWindowAfterReload = val;\n\n}\n\n\n\nvoid CParametersHolder::FileSingleFlag(bool val)\n\n{\n\n\tfileSingleFlag = val;\n\n}\n\n\n\nvoid CParametersHolder::InitializeTearStreamsAutoFlag(bool val)\n\n{\n\n\tinitializeTearStreamsAutoFlag = val;\n\n}\n\n\n\nvoid CParametersHolder::EnthalpyMinT(double val)\n\n{\n\n\tenthalpyMinT = val;\n\n}\n\n\n\nvoid CParametersHolder::EnthalpyMaxT(double val)\n\n{\n\n\tenthalpyMaxT = val;\n\n}\n\n\n\nvoid CParametersHolder::EnthalpyInt(uint32_t val)\n\n{\n\n\tenthalpyInt = val;\n\n}\n", "file_path": "SimulatorCore/ParametersHolder.cpp", "rank": 35, "score": 15.157321154035781 }, { "content": "\t\t\treturn SetMessageAndReturn(StrConst::GE_ErrorNegative(distrName));\n\n\t\tif (!std::is_sorted(grid.begin(), grid.end()))\n\n\t\t\treturn SetMessageAndReturn(StrConst::GE_ErrorSequence(distrName));\n\n\t}\n\n\telse if (m_grid->GridType() == EGridEntry::GRID_SYMBOLIC)\n\n\t{\n\n\t\tconst auto grid = dynamic_cast<CGridDimensionSymbolic*>(m_grid.get())->Grid();\n\n\t\tif (std::any_of(grid.begin(), grid.end(), [](auto v) { return v.empty(); }))\n\n\t\t\treturn SetMessageAndReturn(StrConst::GE_ErrorGaps(distrName));\n\n\t}\n\n\treturn true;\n\n}\n\n\n\nQString CDimensionParameters::LastMessage() const\n\n{\n\n\treturn QString::fromStdString(m_message);\n\n}\n\n\n\nCGridDimension& CDimensionParameters::GetGrid() const\n\n{\n\n\treturn *m_grid;\n\n}", "file_path": "GUIDialogs/GridEditor/DimensionParameters.cpp", "rank": 36, "score": 15.113878842057098 }, { "content": "\tUpdateLimits();\n\n\tUpdateGrid();\n\n}\n\n\n\nvoid CDimensionParameters::SetGrid() const\n\n{\n\n\tif (m_grid->GridType() == EGridEntry::GRID_NUMERIC)\n\n\t\tdynamic_cast<CGridDimensionNumeric*>(m_grid.get())->SetGrid(CalculateGridNumeric());\n\n\telse if (m_grid->GridType() == EGridEntry::GRID_SYMBOLIC)\n\n\t\tdynamic_cast<CGridDimensionSymbolic*>(m_grid.get())->SetGrid(CalculateGridSymbolic());\n\n}\n\n\n\nstd::vector<double> CDimensionParameters::CalculateGridNumeric() const\n\n{\n\n\tconst auto fun = static_cast<EGridFunction>(ui.comboFun->currentData().toUInt());\n\n\tconst size_t number = ui.spinClasses->value() + 1;\n\n\tstd::vector<double> res(number);\n\n\tif (fun != EGridFunction::GRID_FUN_MANUAL)\n\n\t\tres = CreateGrid(fun, ui.spinClasses->value(), ui.lineMin->text().toDouble(), ui.lineMax->text().toDouble());\n\n\telse\n", "file_path": "GUIDialogs/GridEditor/DimensionParameters.cpp", "rank": 37, "score": 15.09691691160208 }, { "content": "\tbool SetDimensions( unsigned _nType1, unsigned _nClasses1, unsigned _nType2, unsigned _nClasses2 );\n\n\tbool SetDimensions( unsigned _nType1, unsigned _nClasses1, unsigned _nType2, unsigned _nClasses2, unsigned _nType3, unsigned _nClasses3 );\n\n\tbool SetDimensions( const std::vector<unsigned>& _vTypes, const std::vector<unsigned>& _vClasses );\n\n\t/** Returns vector of defined types.*/\n\n\tstd::vector<unsigned> GetDimensions() const;\n\n\t/** Returns vector of defined classes.*/\n\n\tstd::vector<unsigned> GetClasses() const;\n\n\t/** Returns current number of defined dimensions.*/\n\n\tsize_t GetDimensionsNumber() const;\n\n\t/** Clears all data and information about dimensions.*/\n\n\tvoid Clear();\n\n\n\n\t// ============= Functions to work with DATA\n\n\n\n\t/** Clears all data in the matrix. Dimensions set won't be erased.*/\n\n\tvoid ClearData();\n\n\n\n\t/** Normalizes data in matrix: sets sum of material which transfers from each single class to 1.*/\n\n\tvoid Normalize();\n\n\n", "file_path": "ModelsAPI/TransformMatrix.h", "rank": 38, "score": 15.050387375299035 }, { "content": "\n\n\t// ========== Functions to SAVE / LOAD arrays\n\n\n\n\tvoid GetCacheArray( const std::vector<double>& _vTP, std::vector<double>& _vOut );\n\n\tbool SetCacheArray( const std::vector<double>& _vTP, const std::vector<double>& _vData );\n\n\n\n\tvoid GetDataForSave( const std::vector<double>& _vTP, std::vector<double>& _vOut );\n\n\tbool SetDataForLoad( const std::vector<double>& _vTP, const std::vector<double>& _vData );\n\n\n\n\t// ========== Other functions\n\n\n\n\t// Clears all data in array.*/\n\n\tvoid Clear();\n\n\t/** Returns true if m_data doesn't contain data.*/\n\n\tbool IsEmpty() const;\n\n\t/** Returns number of values in m_data.*/\n\n\tsize_t GetDataLength() const;\n\n\n\n\tCTDArray& operator=( CTDArray& _source );\n\n\n", "file_path": "ModelsAPI/TDArray.h", "rank": 39, "score": 14.976046969088413 }, { "content": "void CChemicalReaction::SetEnthalpy(double _enthalpy)\n\n{\n\n\tm_enthalpy = _enthalpy;\n\n}\n\n\n\ndouble CChemicalReaction::GetEnthalpy() const\n\n{\n\n\treturn m_enthalpy;\n\n}\n\n\n\nvoid CChemicalReaction::Initialize(const CMaterialsDatabase& _materials)\n\n{\n\n\tm_enthalpy = 0.0;\n\n\tfor (const auto& s : m_substances)\n\n\t\tm_enthalpy += s->nu * _materials.GetConstPropertyValue(s->key, STANDARD_FORMATION_ENTHALPY);\n\n\tfor (auto& s : m_substances)\n\n\t\ts->MM = _materials.GetConstPropertyValue(s->key, MOLAR_MASS);\n\n}\n\n\n\nvoid CChemicalReaction::SaveToFile(CH5Handler& _h5File, const std::string& _path) const\n", "file_path": "ModelsAPI/ChemicalReaction.cpp", "rank": 40, "score": 14.968305467936984 }, { "content": "\t// Returns aggregation state of the phase.\n\n\tEPhase GetState() const;\n\n\n\n\t// Adds a new temp point _time if it doesn't already exist.\n\n\t// TODO: maybe remove.\n\n\tvoid AddTimePoint(double _time);\n\n\t// Adds a new temp point _timeDst if it doesn't already exist and fills it with the data of existing time point _timeSrc.\n\n\tvoid CopyTimePoint(double _timeDst, double _timeSrc);\n\n\t// Removes all existing time points in the specified interval, including or excluding boundaries.\n\n\tvoid RemoveTimePoints(double _timeBeg, double _timeEnd, bool _inclusive = true);\n\n\t// Removes all existing time points.\n\n\tvoid RemoveAllTimePoints();\n\n\n\n\t// Adds new compound distribution to the phase.\n\n\tvoid AddCompound(const std::string& _compoundKey);\n\n\t// Removes the distribution of the corresponding compound from the phase.\n\n\tvoid RemoveCompound(const std::string& _compoundKey);\n\n\n\n\t// Returns mass fraction of the phase at the given time point.\n\n\tdouble GetFraction(double _time) const;\n", "file_path": "ModelsAPI/Phase.h", "rank": 41, "score": 14.960144897944847 }, { "content": "\treturn res;\n\n}\n\n\n\nvoid CGridDimensionNumeric::SaveToFile(const CH5Handler& _h5File, const std::string& _path) const\n\n{\n\n\t_h5File.WriteData(_path, StrConst::DGrid_H5DistrType, E2I(DimensionType()));\n\n\t_h5File.WriteData(_path, StrConst::DGrid_H5GridType, E2I(GridType()));\n\n\t_h5File.WriteData(_path, StrConst::DGrid_H5NumGrid, m_grid);\n\n}\n\n\n\nvoid CGridDimensionNumeric::LoadFromFile(const CH5Handler& _h5File, const std::string& _path)\n\n{\n\n\tEDistrTypes type;\n\n\t_h5File.ReadData(_path, StrConst::DGrid_H5DistrType, reinterpret_cast<uint32_t&>(type));\n\n\tSetType(type);\n\n\t_h5File.ReadData(_path, StrConst::DGrid_H5NumGrid, m_grid);\n\n}\n\n\n\nCGridDimensionNumeric* CGridDimensionNumeric::Clone() const\n\n{\n", "file_path": "ModelsAPI/MultidimensionalGrid.cpp", "rank": 42, "score": 14.858678638556157 }, { "content": "public:\n\n\tCSimulatorLog();\n\n\t~CSimulatorLog();\n\n\n\n\t// Removes all messages and resets read and write positions.\n\n\tvoid Clear();\n\n\n\n\t// Writes a message with the specified color to the current write position and advances this position. If _console is set, the message will be additionally written into std::out.\n\n\tvoid Write(const std::string& _text, ELogColor _color, bool _console);\n\n\t// Writes an info message with the pre-defined color to the current write position and advances this position. If _console is set, the message will be additionally written into std::out.\n\n\tvoid WriteInfo(const std::string& _text, bool _console = false);\n\n\t// Writes a warning message with the pre-defined color to the current write position and advances this position. If _console is set, the message will be additionally written into std::out.\n\n\tvoid WriteWarning(const std::string& _text, bool _console = true);\n\n\t// Writes an error message with the pre-defined color to the current write position and advances this position. If _console is set, the message will be additionally written into std::out.\n\n\tvoid WriteError(const std::string& _text, bool _console = true);\n\n\n\n\t// Returns message from the current read position and advances this position. Returns empty string if the end of log is reached.\n\n\tstd::string Read();\n\n\t// Returns color from the current read position.\n\n\tELogColor GetReadColor() const;\n\n\n\n\t// Returns true if the end of the log file is reached (the read position is equal to the write position).\n\n\tbool EndOfLog() const;\n\n};\n\n\n", "file_path": "SimulatorCore/SimulatorLog.h", "rank": 43, "score": 14.846012116531547 }, { "content": "\t// Removes all existing time points after the specified one, inclusive or exclusive _time.\n\n\tvoid RemoveTimePointsAfter(double _time, bool _inclusive = false);\n\n\t// Removes all existing time points.\n\n\tvoid RemoveAllTimePoints();\n\n\t// Removes time points within the specified interval [timeBeg; timeEnd) that are closer together than step.\n\n\tvoid ReduceTimePoints(double _timeBeg, double _timeEnd, double _step);\n\n\t// Returns all defined time points.\n\n\tstd::vector<double> GetAllTimePoints() const;\n\n\t// Returns all defined time points in the specified time interval.\n\n\tstd::vector<double> GetTimePoints(double _timeBeg, double _timeEnd) const;\n\n\t// Returns all defined time points in the specified closed time interval, boundaries are unconditionally included into result.\n\n\tstd::vector<double> GetTimePointsClosed(double _timeBeg, double _timeEnd) const;\n\n\t// Returns the last (largest) defined time point.\n\n\tdouble GetLastTimePoint() const;\n\n\t// Returns the nearest time point before _time, or zero if such time can not be found.\n\n\tdouble GetPreviousTimePoint(double _time) const;\n\n\n\n\t////////////////////////////////////////////////////////////////////////////////\n\n\t// Overall parameters\n\n\t//\n", "file_path": "ModelsAPI/BaseStream.h", "rank": 44, "score": 14.772101361815256 }, { "content": "/* Copyright (c) 2020, Dyssol Development Team. All rights reserved. This file is part of Dyssol. See LICENSE file for license information. */\n\n\n\n#include \"ArgumentsParser.h\"\n\n#include \"ScriptParser.h\"\n\n#include \"ScriptRunner.h\"\n\n#include \"ThreadPool.h\"\n\n#include \"DyssolSystemDefines.h\"\n\n\n\n// Prints information about command line arguments.\n\nvoid PrintArgumentsInfo(const CArgumentsParser& _parser)\n\n{\n\n\tstd::cout << \"Usage: DyssolC --key[=value] [--key[=value]] [...]\" << std::endl;\n\n\tfor (const auto& k : _parser.AllAllowedKeys())\n\n\t{\n\n\t\tfor (const auto& s : k.keysS)\n\n\t\t\tstd::cout << \"-\" << s << \" \";\n\n\t\tstd::cout << '\\t';\n\n\t\tfor (const auto& l : k.keysL)\n\n\t\t\tstd::cout << \"--\" << l << \" \";\n\n\t\tstd::cout << k.description << std::endl;\n", "file_path": "DyssolConsole/main.cpp", "rank": 45, "score": 14.74460225956713 }, { "content": "\t// Returns a value of the check box widget at the selected column of the given existing item.\n\n\tbool GetCheckBoxValue(QTreeWidgetItem* _item, int _col) const;\n\n\n\n\t// Sets flags to the given item.\n\n\tvoid SetItemFlags(QTreeWidgetItem* _item, EFlags _flags);\n\n\n\n\t// Sets an item with the specified index as current.\n\n\tvoid SetCurrentItem(const std::vector<size_t>& _indices);\n\n\t// Sets an item with the specified user data as current.\n\n\tvoid SetCurrentItem(const QVariant& _data);\n\n\t// Returns an item with the specified user data.\n\n\tQTreeWidgetItem* GetItem(const QVariant& _data) const;\n\n\n\n\t// Returns user data of the given column in the specified item.\n\n\tQString GetData(const QTreeWidgetItem* _item, int _col = 0) const;\n\n\t// Returns user data of the given column in current item.\n\n\tQString GetCurrentData(int _col = 0) const;\n\n\n\n\tbool blockSignals(bool _flag);\n\n\tbool eventFilter(QObject* _object, QEvent* _event) override;\n", "file_path": "GUIWidgets/QtWidgets/QtTree.h", "rank": 46, "score": 14.741414043537954 }, { "content": "\t\tif (nPortsI != nPortsO || nPortsI != 1 && nPortsI != 0)\n\n\t\t\treturn StrConst::Flow_ErrWrongStreams(stream->GetName());\n\n\t}\n\n\n\n\treturn {};\n\n}\n\n\n\nvoid CFlowsheet::ClearSimulationResults()\n\n{\n\n\tfor (auto& stream : m_streams)\n\n\t\tstream->RemoveAllTimePoints();\n\n\tm_streamsI.clear();\n\n\tfor (auto& unit : m_units)\n\n\t\tif (auto* model = unit->GetModel())\n\n\t\t\tmodel->ClearSimulationResults();\n\n}\n\n\n\nvoid CFlowsheet::SetMainGrid(const CMultidimensionalGrid& _grid)\n\n{\n\n\tfor (auto& unit : m_units)\n", "file_path": "SimulatorCore/Flowsheet.cpp", "rank": 47, "score": 14.698943743807067 }, { "content": "\n\n\t// TODO: remove this function\n\n\t// Adds a new temp point _time if it doesn't already exist and fills it with the data of previous time point.\n\n\tvoid AddTimePoint(double _time);\n\n\t// Adds a new temp point _timeDst if it doesn't already exist and fills it with the data of existing time point _timeSrc.\n\n\tvoid CopyTimePoint(double _timeDst, double _timeSrc);\n\n\t// Removes the specified time point if it does already exist.\n\n\tvoid RemoveTimePoint(double _time);\n\n\t// Removes all existing time points in the specified interval, including or excluding boundaries.\n\n\tvoid RemoveTimePoints(double _timeBeg, double _timeEnd, bool _inclusive = true);\n\n\t// Removes all existing time points.\n\n\tvoid RemoveAllTimePoints();\n\n\n\n\t// TODO: remove\n\n\tsize_t GetTimePointsNumber() const;\t\t\t\t// Returns the number of defined time points.\n\n\tstd::vector<double> GetAllTimePoints() const;\t// Returns all defined time points.\n\n\n\n\tvoid SetValue(double _time, double _value);\t// Sets new value at the given time point. Creates a new time point if needed.\n\n\tdouble GetValue(double _time) const;\t\t// Returns the value at the given time point.\n\n\n", "file_path": "ModelsAPI/TimeDependentValue.h", "rank": 48, "score": 14.67669334631406 }, { "content": "\t// Returns name of the property.\n\n\tstd::string GetName() const;\n\n\t// Set name of the property.\n\n\tvoid SetName(const std::string& _sName);\n\n\n\n\t// Returns measurements units of the property.\n\n\tstd::wstring GetUnits() const;\n\n\t// Sets measurements units of the property.\n\n\tvoid SetUnits(const std::wstring& _sUnits);\n\n\n\n\t// Checks if the default value is set.\n\n\tvirtual bool IsDefaultValue() const = 0;\n\n};\n", "file_path": "MaterialsDatabase/BaseProperty.h", "rank": 49, "score": 14.647426297734624 }, { "content": "/* Copyright (c) 2020, Dyssol Development Team. All rights reserved. This file is part of Dyssol. See LICENSE file for license information. */\n\n\n\n#include \"MaterialsDatabase.h\"\n\n#include \"StringFunctions.h\"\n\n#include \"DyssolUtilities.h\"\n\n#include \"DyssolStringConstants.h\"\n\n#include \"ContainerFunctions.h\"\n\n#include <fstream>\n\n#include <sstream>\n\n\n\nusing namespace StringFunctions;\n\n\n\nCMaterialsDatabase::CMaterialsDatabase()\n\n{\n\n\tm_sFileName = MDBDescriptors::DEFAULT_MDB_FILE_NAME;\n\n\n\n\tactiveConstProperties = MDBDescriptors::defaultConstProperties;\n\n\tactiveTPDepProperties = MDBDescriptors::defaultTPDProperties;\n\n\tactiveInterProperties = MDBDescriptors::defaultInteractionProperties;\n\n}\n", "file_path": "MaterialsDatabase/MaterialsDatabase.cpp", "rank": 50, "score": 14.587915426892845 }, { "content": "/* Copyright (c) 2020, Dyssol Development Team. All rights reserved. This file is part of Dyssol. See LICENSE file for license information. */\n\n\n\n#include \"ModelsManager.h\"\n\n#include \"DynamicUnit.h\"\n\n#include \"FileSystem.h\"\n\n#include \"DyssolStringConstants.h\"\n\n#include \"ContainerFunctions.h\"\n\n#ifdef _MSC_VER\n\n#else\n\n#include <dlfcn.h>\n\n#endif\n\n\n\nsize_t CModelsManager::DirsNumber() const\n\n{\n\n\treturn m_dirsList.size();\n\n}\n\n\n\nbool CModelsManager::AddDir(const std::filesystem::path& _path, bool _active)\n\n{\n\n\tconst auto& it = std::find_if(m_dirsList.begin(), m_dirsList.end(), [&](const SModelDir& entry) { return entry.path == _path; });\n", "file_path": "SimulatorCore/ModelsManager.cpp", "rank": 51, "score": 14.562199974715377 }, { "content": "\tm_checked = false;\n\n}\n\n\n\nbool CCheckBoxUnitParameter::IsChecked() const\n\n{\n\n\treturn m_checked;\n\n}\n\n\n\nvoid CCheckBoxUnitParameter::SetChecked(bool _checked)\n\n{\n\n\tm_checked = _checked;\n\n}\n\n\n\nstd::ostream& CCheckBoxUnitParameter::ValueToStream(std::ostream& _s)\n\n{\n\n\treturn _s << m_checked;\n\n}\n\n\n\nstd::istream& CCheckBoxUnitParameter::ValueFromStream(std::istream& _s)\n\n{\n", "file_path": "ModelsAPI/UnitParameters.cpp", "rank": 52, "score": 14.526502205858694 }, { "content": "/* Copyright (c) 2020, Dyssol Development Team. All rights reserved. This file is part of Dyssol. See LICENSE file for license information. */\n\n\n\n#include \"DustFormationTester.h\"\n\n#include \"DistributionsFunctions.h\"\n\n#include <numeric>\n\n#include <algorithm>\n\n\n\nvoid CDustFormationTester::SetBulkPorosity(double _porosity)\n\n{\n\n\tif (eps == _porosity) return;\n\n\teps = _porosity;\n\n\teps = std::max(0., std::min(eps, 1.));\n\n\tconsistent = IsConsistent();\n\n\tPrecalculateAll();\n\n}\n\n\n\nvoid CDustFormationTester::SetMoistureContent(double _moisture)\n\n{\n\n\tXa = std::max(0., std::min(_moisture, 1.));\n\n}\n", "file_path": "Modules/DustFormationTester/DustFormationTester.cpp", "rank": 53, "score": 14.283740252596242 }, { "content": "void CStateVariablesManager::SaveState()\n\n{\n\n\tfor (auto& var : m_stateVariables)\n\n\t\tvar->SaveState();\n\n}\n\n\n\nvoid CStateVariablesManager::LoadState()\n\n{\n\n\tfor (auto& var : m_stateVariables)\n\n\t\tvar->LoadState();\n\n}\n\n\n\nvoid CStateVariablesManager::SaveToFile(CH5Handler& _h5File, const std::string& _path) const\n\n{\n\n\tif (!_h5File.IsValid()) return;\n\n\n\n\t// current version of save procedure\n\n\t_h5File.WriteAttribute(_path, StrConst::H5AttrSaveVersion, m_saveVersion);\n\n\n\n\t_h5File.WriteAttribute(_path, StrConst::SVMngr_H5AttrStateVarsNum, static_cast<int>(m_stateVariables.size()));\n", "file_path": "ModelsAPI/StateVariable.cpp", "rank": 54, "score": 14.194951354301567 }, { "content": "\t// Checks if all values lay in range [min; max].\n\n\t[[nodiscard]] bool IsInBounds() const override { return std::all_of(m_values.begin(), m_values.end(), [&](const auto val) { return val >= m_min && val <= m_max; }); }\n\n\n\n\t// Outputs user-specified values of the parameter to a stream.\n\n\tstd::ostream& ValueToStream(std::ostream& _s) override;\n\n\t// Reads user-specified values of the parameter from a stream.\n\n\tstd::istream& ValueFromStream(std::istream& _s) override;\n\n\n\n\tvoid SaveToFile(CH5Handler& _h5File, const std::string& _path) const;\n\n\tvoid LoadFromFile(const CH5Handler& _h5File, const std::string& _path);\n\n};\n\n\n\nusing CListRealUnitParameter = CListUnitParameter<double>;\n\nusing CListIntUnitParameter = CListUnitParameter<int64_t>;\n\nusing CListUIntUnitParameter = CListUnitParameter<uint64_t>;\n\n\n", "file_path": "ModelsAPI/UnitParameters.h", "rank": 55, "score": 14.106273159493352 }, { "content": "\tCGridDimensionSymbolic* AddSymbolicDimension(EDistrTypes _type, const std::vector<std::string>& _grid);\n\n\t// Adds a new numerical dimension with the given parameters to the grid if it does not exist yet.\n\n\tCGridDimensionSymbolic* AddSymbolicDimension(const CGridDimensionSymbolic& _gridDimension);\n\n\n\n\t// Returns grid dimension by its type. Returns nullptr if such dimension does not exist.\n\n\t[[nodiscard]] const CGridDimension* GetGridDimension(EDistrTypes _type) const;\n\n\t// Returns grid dimension by its type. Returns nullptr if such dimension does not exist.\n\n\t[[nodiscard]] CGridDimension* GetGridDimension(EDistrTypes _type);\n\n\t// Returns numeric grid dimension by its type. Returns nullptr if such dimension does not exist.\n\n\t[[nodiscard]] const CGridDimensionNumeric* GetGridDimensionNumeric(EDistrTypes _type) const;\n\n\t// Returns numeric grid dimension by its type. Returns nullptr if such dimension does not exist.\n\n\t[[nodiscard]] CGridDimensionNumeric* GetGridDimensionNumeric(EDistrTypes _type);\n\n\t// Returns symbolic grid dimension by its type. Returns nullptr if such dimension does not exist.\n\n\t[[nodiscard]] const CGridDimensionSymbolic* GetGridDimensionSymbolic(EDistrTypes _type) const;\n\n\t// Returns symbolic grid dimension by its type. Returns nullptr if such dimension does not exist.\n\n\t[[nodiscard]] CGridDimensionSymbolic* GetGridDimensionSymbolic(EDistrTypes _type);\n\n\n\n\t// Removes the specified dimension form the grid.\n\n\tvoid RemoveDimension(EDistrTypes _type);\n\n\n", "file_path": "ModelsAPI/MultidimensionalGrid.h", "rank": 56, "score": 14.093997328708905 }, { "content": "\t/** Sets distribution by specified dimensions and time. Uses SetVectorValue() functions.*/\n\n\tbool SetDistribution( double _dTime, const CDenseMDMatrix& _Distr );\n\n\n\n\t// ========== Functions to work with matrix TRANSFORMATIONS\n\n\n\n\t/** Transforms matrix according to matrix _Transformation. Returns false on error.*/\n\n\tbool Transform( double _dTime, const CTransformMatrix& _TMatrix );\n\n\n\n\t// ========== Functions for matrix NORMALIZATION\n\n\n\n\t/** Normalizes data in matrix for specified time point. If time point wasn't defined, than nothing will be done.*/\n\n\tvoid NormalizeMatrix( double _dTime );\n\n\t/** Normalizes data in matrix for time interval (incl).*/\n\n\tvoid NormalizeMatrix( double _dStart, double _dEnd );\n\n\t/** Normalizes data in matrix for all time points.*/\n\n\tvoid NormalizeMatrix();\n\n\t/** Returns true if matrix is normalized in specified time point.*/\n\n\tbool IsNormalized( double _dTime );\n\n\n\n\t// ========== Functions to work with ANOTHER MATRICES\n", "file_path": "ModelsAPI/MDMatrix.h", "rank": 57, "score": 14.029144165147548 }, { "content": "\tstd::string GetName() const;\n\n\t// Sets new name of the stream.\n\n\tvoid SetName(const std::string& _name);\n\n\t// Returns unique key of the stream.\n\n\tstd::string GetKey() const;\n\n\t// Sets new unique key of the stream.\n\n\tvoid SetKey(const std::string& _key);\n\n\n\n\t////////////////////////////////////////////////////////////////////////////////\n\n\t// Time points\n\n\t//\n\n\n\n\t// Adds a new temp point _time if it doesn't already exist.\n\n\tvoid AddTimePoint(double _time);\n\n\t// Adds a new temp point _timeDst if it doesn't already exist and fills it with the data of existing time point _timeSrc.\n\n\tvoid CopyTimePoint(double _timeDst, double _timeSrc);\n\n\t// Removes the specified time point if it does already exist.\n\n\tvoid RemoveTimePoint(double _time);\n\n\t// Removes all existing time points in the specified interval, including or excluding boundaries.\n\n\tvoid RemoveTimePoints(double _timeBeg, double _timeEnd, bool _inclusive = true);\n", "file_path": "ModelsAPI/BaseStream.h", "rank": 58, "score": 13.983016048109198 }, { "content": "\tbool SetDimensions( const std::vector<unsigned>& _vTypes, const std::vector<unsigned>& _vClasses );\n\n\t/** Returns vector of defined types.*/\n\n\tstd::vector<unsigned> GetDimensions() const;\n\n\t/** Returns vector of defined classes.*/\n\n\tstd::vector<unsigned> GetClasses() const;\n\n\t/** Returns current number of defined dimensions.*/\n\n\tsize_t GetDimensionsNumber() const;\n\n\t/** Clears all data and information about dimensions.*/\n\n\tvoid Clear();\n\n\n\n\t// ============= Functions to work with DATA\n\n\n\n\t/** Clears all data in the matrix by setting all values to 0. Dimensions set won't be erased.*/\n\n\tvoid ClearData();\n\n\n\n\t/** Returns pointer to data.*/\n\n\tconst double* GetDataPtr() const;\n\n\tdouble* GetDataPtr();\n\n\n\n\t/** Returns length of the plain array m_vData*/\n", "file_path": "ModelsAPI/DenseMDMatrix.h", "rank": 59, "score": 13.968559019472343 }, { "content": "\t// Returns all curves defined in the plot.\n\n\tstd::vector<const CCurve*> GetAllCurves() const;\n\n\t// Returns all curves defined in the plot.\n\n\tstd::vector<CCurve*> GetAllCurves();\n\n\n\n\t// Returns Z values of all defined curves.\n\n\tstd::vector<double> GetZValues() const;\n\n\n\n\t// Checks if the plot is a 2D plot, based on the presence of Z values.\n\n\tbool Is2D() const;\n\n\n\n\t// Returns a number of defined curves.\n\n\tsize_t GetCurvesNumber() const;\n\n\n\n\t// Removes all defined curves from the plot.\n\n\tvoid ClearData();\n\n\t// Removes all data from the plot.\n\n\tvoid Clear();\n\n\n\n\t// Saves data to file.\n\n\tvoid SaveToFile(CH5Handler& _h5File, const std::string& _path) const;\n\n\t// Loads data from file.\n\n\tvoid LoadFromFile(CH5Handler& _h5File, const std::string& _path);\n\n};\n\n\n\n////////////////////////////////////////////////////////////////////////////////\n\n// CPlotManager\n\n//\n\n\n", "file_path": "ModelsAPI/PlotManager.h", "rank": 60, "score": 13.965789381402326 }, { "content": "}\n\n\n\nvoid CBaseUnitParameter::SetUnits(const std::string& _units)\n\n{\n\n\tm_units = _units;\n\n}\n\n\n\nvoid CBaseUnitParameter::SetDescription(const std::string& _description)\n\n{\n\n\tm_description = _description;\n\n}\n\n\n\nbool CBaseUnitParameter::IsInBounds() const\n\n{\n\n\treturn true;\n\n}\n\n\n\n\n\n////////////////////////////////////////////////////////////////////////////////////////////////////\n\n/// CConstUnitParameter\n", "file_path": "ModelsAPI/UnitParameters.cpp", "rank": 61, "score": 13.94588289231729 }, { "content": "\n\nvoid CGridDimensionSymbolic::LoadFromFile(const CH5Handler& _h5File, const std::string& _path)\n\n{\n\n\tEDistrTypes type;\n\n\t_h5File.ReadData(_path, StrConst::DGrid_H5DistrType, reinterpret_cast<uint32_t&>(type));\n\n\tSetType(type);\n\n\t_h5File.ReadData(_path, StrConst::DGrid_H5StrGrid, m_grid);\n\n}\n\n\n\nCGridDimensionSymbolic* CGridDimensionSymbolic::Clone() const\n\n{\n\n\treturn new CGridDimensionSymbolic(*this);\n\n}\n\n\n\nbool CGridDimensionSymbolic::Equal(const CGridDimension& _other) const\n\n{\n\n\tconst auto* p = dynamic_cast<const CGridDimensionSymbolic*>(&_other);\n\n\treturn p && CGridDimension::Equal(_other) && m_grid == p->m_grid;\n\n}\n\n\n", "file_path": "ModelsAPI/MultidimensionalGrid.cpp", "rank": 62, "score": 13.881556895504934 }, { "content": "\t/// Functions to work with file\n\n\n\n\t// Returns the name of the current database file.\n\n\tstd::filesystem::path GetFileName() const;\n\n\n\n\t// Creates new database by removing information about compounds and file name.\n\n\tvoid Clear();\n\n\n\n\t// Saves database to a text file with specified name. If the name is not specified, data will be written to the default file. Returns true on success.\n\n\tbool SaveToFile(const std::filesystem::path& _fileName = \"\");\n\n\t// Loads database from a text file with specified name. If the name is not specified, data will be loaded from the default file. Returns true on success.\n\n\tbool LoadFromFile(const std::filesystem::path& _fileName = \"\");\n\n\t// Loads database from the file. Loads file with old syntax for versions before v0.7. Returns true on success.\n\n\tbool LoadFromFileV0(std::ifstream& _file);\n\n\t// Loads database from the file. Loads file with old syntax for versions before v0.9.1. Returns true on success.\n\n\tbool LoadFromFileV2(std::ifstream& _file);\n\n\t// Loads database from the file.\n\n\tbool LoadFromFileV3(std::ifstream& _file);\n\n\n\n\n", "file_path": "MaterialsDatabase/MaterialsDatabase.h", "rank": 63, "score": 13.7072016085878 }, { "content": "{\n\n\tif (_col >= columnCount()) return std::vector<double>{};\n\n\tstd::vector<double> res;\n\n\tfor (int i = 0; i < rowCount(); ++i)\n\n\t\tres.push_back(item(i, _col)->text().toDouble());\n\n\treturn res;\n\n}\n\n\n\nvoid CQtTable::ShowRow(int _row, bool _show)\n\n{\n\n\tif (_show)\tshowRow(_row);\n\n\telse\t\thideRow(_row);\n\n}\n\n\n\nvoid CQtTable::ShowCol(int _col, bool _show)\n\n{\n\n\tif (_show)\tshowColumn(_col);\n\n\telse\t\thideColumn(_col);\n\n}\n\n\n", "file_path": "GUIWidgets/QtWidgets/QtTable.cpp", "rank": 65, "score": 13.689138846162106 }, { "content": "/* Copyright (c) 2020, Dyssol Development Team. All rights reserved. This file is part of Dyssol. See LICENSE file for license information. */\n\n\n\n#include \"TwoWayMap.h\"\n\n#include \"ContainerFunctions.h\"\n\n#include <numeric>\n\n\n\nvoid CTwoWayMap::Set(double _left, double _right)\n\n{\n\n\tif (m_direct.HasParam(_left) || m_revert.HasParam(_right)) return;\n\n\tm_direct.SetValue(_left, _right);\n\n\tm_revert.SetValue(_right, _left);\n\n}\n\n\n\nvoid CTwoWayMap::SetLeftToRight(const CDependentValues& _table)\n\n{\n\n\tm_direct = Unique(_table);\n\n\tm_revert = Reverted(m_direct);\n\n}\n\n\n\nvoid CTwoWayMap::SetRightToLeft(const CDependentValues& _table)\n", "file_path": "ModelsAPI/TwoWayMap.cpp", "rank": 66, "score": 13.688788408885706 }, { "content": "\n\nvoid CDistrFunctionDialog::FunctionChanged(int _index)\n\n{\n\n\tm_distrFun = static_cast<EDistrFunction>(_index + 1);\n\n\tUpdateParamLabels();\n\n\tUpdateUnits();\n\n}\n\n\n\nvoid CDistrFunctionDialog::OKClicked()\n\n{\n\n\tm_dParam1 = ui.lineEditParam1->text().toDouble();\n\n\tm_dParam2 = ui.lineEditParam2->text().toDouble();\n\n\tm_distrFun = static_cast<EDistrFunction>(ui.comboBox->currentIndex() + 1);\n\n\n\n\tswitch (m_distrFun)\n\n\t{\n\n\tcase EDistrFunction::Normal:\n\n\t\tif (m_dParam2 == 0) {\tQMessageBox::critical(this, StrConst::FUN_ErrorName, QString::fromStdString(StrConst::FUN_ErrorZeroParameter(StrConst::FUN_NormalParam2)));\t\treturn;\t}\n\n\t\tbreak;\n\n\tcase EDistrFunction::RRSB:\n", "file_path": "GUIWidgets/BasicStreamEditor/DistrFunctionDialog.cpp", "rank": 67, "score": 13.590969325367196 }, { "content": "/* Copyright (c) 2021, Dyssol Development Team. All rights reserved. This file is part of Dyssol. See LICENSE file for license information. */\n\n\n\n#include \"ScriptExporter.h\"\n\n#include \"ScriptJob.h\"\n\n#include \"Flowsheet.h\"\n\n#include \"BaseUnit.h\"\n\n#include \"MaterialsDatabase.h\"\n\n#include <fstream>\n\n#include <sstream>\n\n\n\nnamespace fs = std::filesystem;\n\n\n\nnamespace ScriptInterface\n\n{\n\n\tbool ExportScript(const fs::path& _scriptFile, const fs::path& _flowsheetFile, const CFlowsheet& _flowsheet,\n\n\t\tconst CModelsManager& _modelsManager, const CMaterialsDatabase& _materialsDB)\n\n\t{\n\n\t\tstd::ofstream file(_scriptFile);\n\n\t\tif (!file) return false;\n\n\n", "file_path": "ScriptInterface/ScriptExporter.cpp", "rank": 68, "score": 13.582277512758704 }, { "content": "\tvoid LoadFromFile(const CH5Handler& _h5File, const std::string& _sPath );\n\n\tvoid LoadMDBlockFromFile(const CH5Handler& _h5File, const std::string& _sPath, unsigned _iFirst, unsigned _iLast, std::vector<std::vector<double>>& vvBuf);\n\n\n\n\tvoid SetCachePath(const std::wstring& _sPath);\n\n\tvoid SetCacheParams(bool _bEnabled, size_t _nWindow);\n\n\n\n\t/** Removes all data, which can be approximated.*/\n\n\tvoid CompressData( double _dStartTime, double _dEndTime, double _dATol, double _dRTol );\n\n\n\n\tvoid ExtrapolateToPoint( double _dT1, double _dT2, double _dTExtra );\n\n\tvoid ExtrapolateToPoint( double _dT0, double _dT1, double _dT2, double _dTExtra );\n\n\n\nprivate:\n\n\t/** Checks the duplicates in vector. Return true if there are no duplicates.*/\n\n\tbool CheckDuplicates( const std::vector<unsigned>& _vVec ) const;\n\n\t/** Returns index of time point. Strict search returns -1 if there is no such time, not strict search returns index to paste.*/\n\n\tunsigned GetTimeIndex(double _dTime, bool _bIsStrict = true) const;\n\n\t/** Initializes current fraction with specified size.*/\n\n\tsFraction* IitialiseDimension( unsigned _nSize ) const;\n\n\t/*\tIncrements last coordinate for getting/setting vectors according to a dimensions set. Must be _vCoords.size()+1 == _vSizes.size().\n", "file_path": "ModelsAPI/MDMatrix.h", "rank": 69, "score": 13.561236547461315 }, { "content": "\tvoid SetGrid(const std::vector<double>& _grid);\n\n\n\n\t// Returns mean values for each class.\n\n\t[[nodiscard]] std::vector<double> GetClassesMeans() const;\n\n\t// Returns sizes of classes.\n\n\t[[nodiscard]] std::vector<double> GetClassesSizes() const;\n\n\n\n\t// Saves grid to a HDF5 file.\n\n\tvoid SaveToFile(const CH5Handler& _h5File, const std::string& _path) const;\n\n\t// Loads grid from a HDF5 file.\n\n\tvoid LoadFromFile(const CH5Handler& _h5File, const std::string& _path);\n\n\n\nprivate:\n\n\t// Compares for equality with another object.\n\n\t[[nodiscard]] bool Equal(const CGridDimension& _other) const override;\n\n};\n\n\n\n/*\n\n * Symbolic grid.\n\n */\n", "file_path": "ModelsAPI/MultidimensionalGrid.h", "rank": 70, "score": 13.56085966141919 }, { "content": "\tvoid SetValue(size_t _index, T _value) { if (_index < m_values.size()) m_values[_index] = _value; }\n\n\t// Removes value at the given index of the list if it exists.\n\n\tvoid RemoveValue(size_t _index)\t{ if (_index < m_values.size()) m_values.erase(m_values.begin() + _index); }\n\n\t// Returns all defined values.\n\n\t[[nodiscard]] std::vector<T> GetValues() const { return m_values; }\n\n\n\n\t// Returns minimum allowed value.\n\n\t[[nodiscard]] T GetMin() const { return m_min; }\n\n\t// Returns maximum allowed value.\n\n\t[[nodiscard]] T GetMax() const { return m_max; }\n\n\n\n\t// Sets new minimum allowed value.\n\n\tvoid SetMin(T _min) { m_min = _min; }\n\n\t// Sets new maximum allowed value.\n\n\tvoid SetMax(T _max) { m_max = _max; }\n\n\n\n\t// Returns the number of defined values.\n\n\t[[nodiscard]] size_t Size() const { return m_values.size(); }\n\n\t// Checks if any value is defined.\n\n\t[[nodiscard]] bool IsEmpty() const { return m_values.empty(); }\n", "file_path": "ModelsAPI/UnitParameters.h", "rank": 71, "score": 13.552537470741543 }, { "content": "\n\n\tif( m_vTimePoints.empty() )\n\n\t\tm_data = RemoveFractionsRecursive( m_data );\n\n\tCorrectWinBoundary();\n\n\n\n\tm_bCacheCoherent = false;\n\n}\n\n\n\nvoid CMDMatrix::RemoveTimePointsAfter(double _dTime, bool _bIncludeTime /*= false */)\n\n{\n\n\tif( m_vTimePoints.empty() ) // nothing to remove\n\n\t\treturn;\n\n\n\n\tunsigned i=0;\n\n\tif( _bIncludeTime )\n\n\t\twhile( i < m_vTimePoints.size() )\n\n\t\t\tif( m_vTimePoints[i] >= _dTime )\n\n\t\t\t\tbreak;\n\n\t\t\telse\n\n\t\t\t\ti++;\n", "file_path": "ModelsAPI/MDMatrix.cpp", "rank": 72, "score": 13.536890863650294 }, { "content": "\t// Returns all defined grid dimensions.\n\n\t[[nodiscard]] std::vector<const CGridDimension*> GetGridDimensions() const;\n\n\t// Returns all defined grid dimensions.\n\n\t[[nodiscard]] std::vector<CGridDimension*> GetGridDimensions();\n\n\n\n\t// Returns a numeric grid defined for the given distribution type if the distribution with such grid type exists.\n\n\t[[nodiscard]] std::vector<double> GetNumericGrid(EDistrTypes _type) const;\n\n\t// Returns a symbolic grid defined for the given distribution type if the distribution with such grid type exists.\n\n\t[[nodiscard]] std::vector<std::string> GetSymbolicGrid(EDistrTypes _type) const;\n\n\t// Returns a grid defined for PSD if it exists.\n\n\t[[nodiscard]] std::vector<double> GetPSDGrid(EPSDGridType _type = EPSDGridType::DIAMETER) const;\n\n\t// Returns mean values of each class of the grid defined for PSD if it exists.\n\n\t[[nodiscard]] std::vector<double> GetPSDMeans(EPSDGridType _type = EPSDGridType::DIAMETER) const;\n\n\n\n\t// Checks if the grid for this dimension is already defined.\n\n\t[[nodiscard]] bool HasDimension(EDistrTypes _type) const;\n\n\n\n\t// Equality operator\n\n\tbool operator==(const CMultidimensionalGrid& _other) const;\n\n\t// Inequality operator\n", "file_path": "ModelsAPI/MultidimensionalGrid.h", "rank": 73, "score": 13.528571539438362 }, { "content": "\tvoid AddListIntParameter(const std::string& _name, const std::string& _units, const std::string& _description, int64_t _min, int64_t _max, const std::vector<int64_t>& _values);\n\n\t// Adds new unsigned integer list unit parameter. If parameter with the given name already exists, does nothing.\n\n\tvoid AddListUIntParameter(const std::string& _name, const std::string& _units, const std::string& _description, uint64_t _min, uint64_t _max, const std::vector<uint64_t>& _values);\n\n\n\n\t// Returns list of all defined parameters.\n\n\tstd::vector<CBaseUnitParameter*> GetParameters() const;\n\n\n\n\t// Returns pointer to the unit parameter with the specified _index.\n\n\tconst CBaseUnitParameter* GetParameter(size_t _index) const;\n\n\t// Returns const pointer to the unit parameter with the specified _index.\n\n\tCBaseUnitParameter* GetParameter(size_t _index);\n\n\t// Returns pointer to the unit parameter with the specified _name.\n\n\tconst CBaseUnitParameter* GetParameter(const std::string& _name) const;\n\n\t// Returns const pointer to the unit parameter with the specified _name.\n\n\tCBaseUnitParameter* GetParameter(const std::string& _name);\n\n\n\n\t// Returns const pointer to the real constant unit parameter with the specified _index. If such parameter does not exist, returns nullptr.\n\n\tconst CConstRealUnitParameter* GetConstRealParameter(size_t _index) const;\n\n\t// Returns pointer to the constant real unit parameter with the specified _index. If such parameter does not exist, returns nullptr.\n\n\tCConstRealUnitParameter* GetConstRealParameter(size_t _index);\n", "file_path": "ModelsAPI/UnitParameters.h", "rank": 74, "score": 13.45911801658552 }, { "content": "\tstd::string m_unitName;\t\t\t\t// Name of the currently calculated unit.\n\n\n\n\t//// parameters of convergence methods\n\n\tbool m_bSteffensenTrigger;\n\n\n\npublic:\n\n\tCSimulator();\n\n\n\n\t/// Sets pointer to a flowsheet.\n\n\tvoid SetFlowsheet(CFlowsheet* _pFlowsheet);\n\n\n\n\t// Change status of simulator.\n\n\tvoid SetCurrentStatus(ESimulatorStatus _nStatus);\n\n\t// Returns current status of the simulator.\n\n\tESimulatorStatus GetCurrentStatus() const;\n\n\n\n\t/// Perform simulation.\n\n\tvoid Simulate();\n\n\n\nprivate:\n", "file_path": "SimulatorCore/Simulator.h", "rank": 75, "score": 13.339715007024491 }, { "content": "\t// Removes all existing data and sets parameters to their default values.\n\n\tvoid Clear();\n\n\t// Checks if the flowsheet is empty.\n\n\tbool IsEmpty() const;\n\n\n\n\t////////////////////////////////////////////////////////////////////////////////\n\n\t// Units\n\n\t//\n\n\n\n\t// Returns the number of defined units.\n\n\tsize_t GetUnitsNumber() const;\n\n\n\n\t// Adds a new unit to the flowsheet and returns a pointer to it.\n\n\tCUnitContainer* AddUnit(const std::string& _key = \"\");\n\n\t// Removes a unit with the specified unique key.\n\n\tvoid DeleteUnit(const std::string& _key);\n\n\t// Moves a unit with the specified unique key upwards/downwards in the list of units.\n\n\tvoid ShiftUnit(const std::string& _key, EDirection _direction);\n\n\n\n\t// Returns a unit by its index. If no such unit has been defined, returns nullptr.\n", "file_path": "SimulatorCore/Flowsheet.h", "rank": 76, "score": 13.331440849605901 }, { "content": "\n\n\t// Returns type of the correlation.\n\n\tECorrelationTypes GetType() const;\n\n\t// Sets type of the correlation and resizes vector of parameters accordingly.\n\n\tvoid SetType(ECorrelationTypes _nType);\n\n\n\n\t// Returns vector of correlation parameters.\n\n\tstd::vector<double> GetParameters() const;\n\n\t// Sets vector of correlation parameters. In the case of LIST_OF_T_VALUES and LIST_OF_P_VALUES, it must be a list of pairs [parameter:value].\n\n\tbool SetParameters(const std::vector<double>& _vParams);\n\n\n\n\t// Returns value of the correlation at the specified Temperature and Pressure. For the LIST_OF_T_VALUES and LIST_OF_P_VALUES returns a linearly interpolated value.\n\n\t// If the specified T or P are out of defined intervals, returns value at the nearest boundary.\n\n\tdouble GetValue(double _dT, double _dP) const;\n\n\n\n\t// Returns true if T lays within the defined interval for this correlation.\n\n\tbool IsTInInterval(double _dT) const;\n\n\t// Returns true if P lays within the defined interval for this correlation.\n\n\tbool IsPInInterval(double _dP) const;\n\n\t// Returns true if both parameters are within the defined interval for this correlation.\n", "file_path": "MaterialsDatabase/Correlation.h", "rank": 77, "score": 13.291236444745673 }, { "content": "}\n\n\n\nvoid Dyssol::SetFlowsheetModified(bool _bModified)\n\n{\n\n\tm_bFlowsheetChanged = _bModified;\n\n\tsetWindowModified(_bModified);\n\n}\n\n\n\nbool Dyssol::IsFlowsheetModified() const\n\n{\n\n\treturn m_bFlowsheetChanged;\n\n}\n\n\n\nvoid Dyssol::LoadMaterialsDatabase()\n\n{\n\n\tconst QVariant mdbPath = m_pSettings->value(StrConst::Dyssol_ConfigDMDBPath);\n\n\tif (!mdbPath.isValid()) return;\n\n\tm_MaterialsDatabase.LoadFromFile(mdbPath.toString().toStdWString()); // try to load as from absolute path\n\n\tif (m_MaterialsDatabase.CompoundsNumber() == 0) // loaded MDB is empty\n\n\t{\n", "file_path": "DyssolMainWindow/Dyssol.cpp", "rank": 78, "score": 13.288294100974733 }, { "content": "\tbool SetFixedPointSolverParameters(unsigned _nMAA, double _dDampingAA);\n\n\n\n\t/** Set model to a solver.\n\n\t *\t\\param _pModel Pointer to a model\n\n\t *\t\\retval true No errors occurred*/\n\n\tbool SetModel(CNLModel* _pModel);\n\n\n\n\t/** Solve problem on a given time point.\n\n\t *\t\\param _dTime Time point\n\n\t *\t\\retval true No errors occurred*/\n\n\tbool Calculate(realtype _dTime);\n\n\n\n\t/** Save current state of solver. Should be called during saving of unit.*/\n\n\tvoid SaveState();\n\n\t/** Load current state of solver. Should be called during loading of unit.*/\n\n\tvoid LoadState();\n\n\n\n\t/** Return error description.*/\n\n\tstd::string GetError() const;\n\n\n", "file_path": "EquationSolvers/NLSolver.h", "rank": 79, "score": 13.287159164279272 }, { "content": "\tauto* curve = plot->GetCurve(_valueZ);\n\n\tif (!curve)\n\n\t\tthrow std::logic_error(StrConst::BUnit_ErrGetCurve3D(m_unitName, _plotName, _valueZ, __func__));\n\n\tcurve->AddPoint(_x, _y);\n\n}\n\n\n\nvoid CBaseUnit::AddPointsOnCurve(const std::string& _plotName, const std::string& _curveName, const std::vector<double>& _x, const std::vector<double>& _y)\n\n{\n\n\tauto* plot = m_plots.GetPlot(_plotName);\n\n\tif (!plot)\n\n\t\tthrow std::logic_error(StrConst::BUnit_ErrGetPlot(m_unitName, _plotName, __func__));\n\n\tauto* curve = plot->GetCurve(_curveName);\n\n\tif (!curve)\n\n\t\tthrow std::logic_error(StrConst::BUnit_ErrGetCurve2D(m_unitName, _plotName, _curveName, __func__));\n\n\tcurve->AddPoints(_x, _y);\n\n}\n\n\n\nvoid CBaseUnit::AddPointsOnCurve(const std::string& _plotName, double _valueZ, const std::vector<double>& _x, const std::vector<double>& _y)\n\n{\n\n\tauto* plot = m_plots.GetPlot(_plotName);\n", "file_path": "ModelsAPI/BaseUnit.cpp", "rank": 80, "score": 13.279529344518354 }, { "content": "/* Copyright (c) 2020, Dyssol Development Team. All rights reserved. This file is part of Dyssol. See LICENSE file for license information. */\n\n\n\n#include \"UnitParameters.h\"\n\n#include \"DyssolStringConstants.h\"\n\n#include \"ContainerFunctions.h\"\n\n#include \"DyssolUtilities.h\"\n\n#include <set>\n\n#include <utility>\n\n\n\n\n\ntemplate<typename T>\n\nEUnitParameter DeduceTypeConst()\n\n{\n\n\tif (std::is_same_v<T, double>)\t\treturn EUnitParameter::CONSTANT_DOUBLE;\n\n\tif (std::is_same_v<T, int64_t>)\t\treturn EUnitParameter::CONSTANT_INT64;\n\n\tif (std::is_same_v<T, uint64_t>)\treturn EUnitParameter::CONSTANT_UINT64;\n\n\treturn EUnitParameter::UNKNOWN;\n\n}\n\n\n\n///< Deduces type of the unit parameter depending on the template argument.\n", "file_path": "ModelsAPI/UnitParameters.cpp", "rank": 81, "score": 13.234612441795772 }, { "content": "\t*\t\\param _dEndTime End of the time interval\n\n\t*\t\\retval true No errors occurred*/\n\n\tbool Calculate(realtype _dStartTime, realtype _dEndTime);\n\n\t/** Solve problem on a given time point.\n\n\t*\t\\param _dTime Time point\n\n\t*\t\\retval true No errors occurred*/\n\n\tbool Calculate(realtype _dTime);\n\n\n\n\t/** Save current state of solver. Should be called during saving of unit.*/\n\n\tvoid SaveState();\n\n\t/** Load current state of solver. Should be called during loading of unit.*/\n\n\tvoid LoadState();\n\n\n\n\t/** Return error description.*/\n\n\tstd::string GetError();\n\n\n\n\t/** Sets maximum time step for solver.*/\n\n\tbool SetMaxStep(double _dStep);\n\n\n\nprivate:\n", "file_path": "EquationSolvers/DAESolver.h", "rank": 82, "score": 13.231708259949464 }, { "content": "\n\n\t////////////////////////////////////////////////////////////////////////////////\n\n\t// Phases\n\n\t//\n\n\n\n\t// Returns the number of defined phases.\n\n\tsize_t GetPhasesNumber() const;\n\n\t// Adds a new phase with the specified parameters to the flowsheet, if it does not exist yet.\n\n\tvoid AddPhase(EPhase _phase, const std::string& _name);\n\n\t// Remove a phase with the specified type from the flowsheet.\n\n\tvoid RemovePhase(EPhase _phase);\n\n\t// Sets new set of phases.\n\n\tvoid SetPhases(const std::vector<SPhaseDescriptor>& _phases);\n\n\t// Returns descriptors of all defined phases.\n\n\tstd::vector<SPhaseDescriptor> GetPhases() const;\n\n\t// Checks if a phase of the specified type exists in the flowsheet.\n\n\tbool HasPhase(EPhase _phase);\n\n\n\n\t////////////////////////////////////////////////////////////////////////////////\n\n\t// Related to simulation\n", "file_path": "SimulatorCore/Flowsheet.h", "rank": 83, "score": 13.219810108145946 }, { "content": "\t\tthrow std::logic_error(StrConst::BUnit_ErrAddCurve3D(m_unitName, _plotName, _valueZ, __func__));\n\n\treturn plot->AddCurve(_valueZ);\n\n}\n\n\n\nvoid CBaseUnit::AddPointOnCurve(const std::string& _plotName, const std::string& _curveName, double _x, double _y)\n\n{\n\n\tauto* plot = m_plots.GetPlot(_plotName);\n\n\tif (!plot)\n\n\t\tthrow std::logic_error(StrConst::BUnit_ErrGetPlot(m_unitName, _plotName, __func__));\n\n\tauto* curve = plot->GetCurve(_curveName);\n\n\tif (!curve)\n\n\t\tthrow std::logic_error(StrConst::BUnit_ErrGetCurve2D(m_unitName, _plotName, _curveName, __func__));\n\n\tcurve->AddPoint(_x, _y);\n\n}\n\n\n\nvoid CBaseUnit::AddPointOnCurve(const std::string& _plotName, double _valueZ, double _x, double _y)\n\n{\n\n\tauto* plot = m_plots.GetPlot(_plotName);\n\n\tif (!plot)\n\n\t\tthrow std::logic_error(StrConst::BUnit_ErrGetPlot(m_unitName, _plotName, __func__));\n", "file_path": "ModelsAPI/BaseUnit.cpp", "rank": 84, "score": 13.216054078621116 }, { "content": "\tvoid SetGrid(const CMultidimensionalGrid& _grid);\n\n\n\n\t// Returns the number of defined distributed parameters.\n\n\tsize_t GetDistributionsNumber() const;\n\n\t// Returns all defined distributed parameters.\n\n\tstd::vector<EDistrTypes> GetDistributionsTypes() const;\n\n\t// Returns numbers of classes of all defined distributed parameters.\n\n\tstd::vector<size_t> GetDistributionsClasses() const;\n\n\t// Returns grid type (GRID_NUMERIC, GRID_SYMBOLIC) of the given distributed parameter. Returns -1 if the given distributed parameter is not defined.\n\n\tEGridEntry GetDistributionGridType(EDistrTypes _distribution) const;\n\n\n\n\t// Returns the number of classes defined for the specified distributed parameter.\n\n\tsize_t GetClassesNumber(EDistrTypes _distribution) const;\n\n\t// Returns a continuous or discrete numeric grid defined for the specified distributed parameter.\n\n\tstd::vector<double> GetNumericGrid(EDistrTypes _distribution) const;\n\n\t// Returns a symbolic discrete grid defined for the specified distributed parameter.\n\n\tstd::vector<std::string> GetSymbolicGrid(EDistrTypes _distribution) const;\n\n\t// Returns the sizes of classes defined in the grid of the specified distributed parameter.\n\n\tstd::vector<double> GetClassesSizes(EDistrTypes _distribution) const;\n\n\t// Returns the mean values of classes defined in the grid of the specified distributed parameter.\n", "file_path": "ModelsAPI/BaseUnit.h", "rank": 85, "score": 13.130552012360909 }, { "content": "/* Copyright (c) 2020, Dyssol Development Team. All rights reserved. This file is part of Dyssol. See LICENSE file for license information. */\n\n\n\n#include \"Compound.h\"\n\n#include \"StringFunctions.h\"\n\n\n\nCCompound::CCompound(const MDBDescriptors::constDescr& _constDescrs, const MDBDescriptors::tpdepDescr& _tpdDescrs, const std::string& _sUniqueCompoundKey /*= \"\"*/)\n\n{\n\n\tm_sUniqueKey = _sUniqueCompoundKey.empty() ? StringFunctions::GenerateRandomKey() : _sUniqueCompoundKey;\n\n\tm_sName = \"New compound\";\n\n\n\n\t// add all const properties\n\n\tfor (const auto& c : _constDescrs)\n\n\t\tm_vConstProperties.emplace_back(c.first, c.second.name, c.second.units, c.second.defaultValue);\n\n\t// add all TP-properties\n\n\tfor (const auto& tp : _tpdDescrs)\n\n\t\tm_vTPProperties.emplace_back(tp.first, tp.second.name, tp.second.units, CCorrelation{ tp.second.defuaultType, tp.second.defaultParameters });\n\n}\n\n\n\nstd::string CCompound::GetName() const\n\n{\n", "file_path": "MaterialsDatabase/Compound.cpp", "rank": 86, "score": 13.128673295673842 }, { "content": "\t\t\treturn true;\n\n\treturn false;\n\n}\n\n\n\nbool CCompound::HasProperty(unsigned _nType) const\n\n{\n\n\treturn HasConstProperty(static_cast<ECompoundConstProperties>(_nType)) || HasTPProperty(static_cast<ECompoundTPProperties>(_nType));\n\n}\n\n\n\nvoid CCompound::AddConstProperty(ECompoundConstProperties _key, const std::string& _name, const std::wstring& _units, double _defaultValue)\n\n{\n\n\tif (HasConstProperty(_key)) return;\n\n\tm_vConstProperties.emplace_back(_key, _name, _units, _defaultValue);\n\n}\n\n\n\nvoid CCompound::AddTPDepProperty(ECompoundTPProperties _key, const std::string& _name, const std::wstring& _units, double _defaultValue)\n\n{\n\n\tif (HasTPProperty(_key)) return;\n\n\tm_vTPProperties.emplace_back(_key, _name, _units, CCorrelation{ ECorrelationTypes::CONSTANT, {_defaultValue} });\n\n}\n", "file_path": "MaterialsDatabase/Compound.cpp", "rank": 87, "score": 13.086908237334525 }, { "content": "\tvoid RemoveCompound(const std::string& _key);\n\n\t// Sets new set of compounds.\n\n\tvoid SetCompounds(const std::vector<std::string>& _keys);\n\n\t// Returns unique keys of all defined compounds.\n\n\tstd::vector<std::string> GetCompounds() const;\n\n\n\n\t////////////////////////////////////////////////////////////////////////////////\n\n\t// Overall properties\n\n\t//\n\n\n\n\t// Returns the number of defined overall properties.\n\n\tsize_t GetOverallPropertiesNumber() const;\n\n\t// Adds a new overall property with the specified parameters to the flowsheet, if it does not exist yet.\n\n\tvoid AddOverallProperty(EOverall _property, const std::string& _name, const std::string& _units);\n\n\t// Remove an overall property with the specified type from the flowsheet.\n\n\tvoid RemoveOverallProperty(EOverall _property);\n\n\t// Returns descriptors of all defined overall properties.\n\n\tstd::vector<SOverallDescriptor> GetOveralProperties() const;\n\n\t// Checks whether the specified overall property is defined.\n\n\tbool HasOverallProperty(EOverall _property) const;\n", "file_path": "SimulatorCore/Flowsheet.h", "rank": 88, "score": 13.059845986259667 }, { "content": "/* Copyright (c) 2020, Dyssol Development Team. All rights reserved. This file is part of Dyssol. See LICENSE file for license information. */\n\n\n\n#include \"SimulatorLog.h\"\n\n#include <iostream>\n\n\n\nCSimulatorLog::CSimulatorLog()\n\n{\n\n\tm_log.resize(MAX_LOG_SIZE);\n\n\tm_iReadPos = 0;\n\n\tm_iWritePos = 0;\n\n}\n\n\n\nCSimulatorLog::~CSimulatorLog()\n\n{\n\n}\n\n\n\nvoid CSimulatorLog::Clear()\n\n{\n\n\tfor(auto l : m_log)\n\n\t{\n", "file_path": "SimulatorCore/SimulatorLog.cpp", "rank": 89, "score": 13.032285699021145 }, { "content": "\n\n\tCheckNormalization();\n\n\n\n\tm_bAvoidSignal = false;\n\n}\n\n\n\n//void CMDMTable::setVisible( bool _bVisible )\n\n//{\n\n//\tif ( _bVisible )\n\n//\t\tUpdateWholeView();\n\n//\tQWidget::setVisible( _bVisible );\n\n//}\n\n\n\nvoid CMDMTable::ItemWasChanged( QTableWidgetItem* _pItem )\n\n{\n\n\tif( m_bAvoidSignal ) return;\n\n\n\n\tunsigned nTimeIndex = _pItem->row();\n\n\tunsigned nCoord = _pItem->column() - 1;\n\n\tdouble dVal = _pItem->text().toDouble();\n", "file_path": "GUIWidgets/BasicStreamEditor/MDMTable.cpp", "rank": 90, "score": 13.001823547129005 }, { "content": "\tCStream* GetStream(const std::string& _key);\n\n\t// Returns a stream with the specified name. If no such stream has been defined, returns nullptr. If several streams have the same name, returns an arbitrary one.\n\n\t[[nodiscard]] const CStream* GetStreamByName(const std::string& _name) const;\n\n\t// Returns a stream with the specified name. If no such stream has been defined, returns nullptr. If several streams have the same name, returns an arbitrary one.\n\n\tCStream* GetStreamByName(const std::string& _name);\n\n\n\n\t// Returns const pointers to all defined streams.\n\n\tstd::vector<const CStream*> GetAllStreams() const;\n\n\t// Returns pointers to all defined streams.\n\n\tstd::vector<CStream*> GetAllStreams();\n\n\n\n\t////////////////////////////////////////////////////////////////////////////////\n\n\t// Topology\n\n\t//\n\n\n\n\t// Determines the calculation sequence. Returns true if the analysis is successful.\n\n\tbool DetermineCalculationSequence();\n\n\t// Sets the flag indicating whether the flowsheet structure has changed since the last run of the calculation sequence analysis.\n\n\tvoid SetTopologyModified(bool _flag);\n\n\t// Returns a const pointer to calculation sequence.\n", "file_path": "SimulatorCore/Flowsheet.h", "rank": 91, "score": 12.984544595007925 }, { "content": "\t// Adds the specified phase to all feeds, holdups and streams in the unit, if it does not exist yet.\n\n\tvoid AddPhase(EPhase _phase, const std::string& _name);\n\n\t// Removes the specified phase from all feeds, holdups and streams in the unit.\n\n\tvoid RemovePhase(EPhase _phase);\n\n\t// Returns the name of the specified phase.\n\n\tstd::string GetPhaseName(EPhase _phase) const;\n\n\t// Returns the type of the phase with the specified index.\n\n\tEPhase GetPhaseType(size_t _index) const;\n\n\t// Returns types of all defined phases.\n\n\tstd::vector<EPhase> GetAllPhases() const;\n\n\t// Returns the number of defined phases.\n\n\tsize_t GetPhasesNumber() const;\n\n\t// Checks if a specified phase is defined.\n\n\tbool IsPhaseDefined(EPhase _phase) const;\n\n\n\n\t////////////////////////////////////////////////////////////////////////////////\n\n\t// Distributed properties\n\n\t//\n\n\n\n\t// Updates grids of distributed parameters and compounds.\n", "file_path": "ModelsAPI/BaseUnit.h", "rank": 92, "score": 12.9235235116721 }, { "content": "\tSetGrid();\n\n\tUpdateGrid();\n\n}\n\n\n\nvoid CDimensionParameters::EntryChanged()\n\n{\n\n\tconst auto entry = static_cast<EGridEntry>(ui.comboEntry->currentData().toUInt());\n\n\tif (entry == EGridEntry::GRID_NUMERIC)\n\n\t\tm_grid.reset(new CGridDimensionNumeric(m_grid->DimensionType(), CalculateGridNumeric()));\n\n\telse if (entry == EGridEntry::GRID_SYMBOLIC)\n\n\t\tm_grid.reset(new CGridDimensionSymbolic(m_grid->DimensionType(), CalculateGridSymbolic()));\n\n\tUpdateWidgetsVisibility();\n\n\tUpdateGrid();\n\n}\n\n\n\nvoid CDimensionParameters::FunctionChanged() const\n\n{\n\n\tSetGrid();\n\n\tUpdateWidgetsVisibility();\n\n\tUpdateGrid();\n", "file_path": "GUIDialogs/GridEditor/DimensionParameters.cpp", "rank": 93, "score": 12.91489231392133 }, { "content": "\t[[nodiscard]] size_t TokensCount() const;\n\n\t// Determines if the argument with the given key or its alias exists.\n\n\t[[nodiscard]] bool HasKey(const std::string& _key) const;\n\n\t// Returns value of the argument by its key. If there are several arguments with the same key, any of them may be returned. Returns an empty string if such key does not exist.\n\n\t[[nodiscard]] std::string GetValue(const std::string& _key) const;\n\n\t// Returns values of all the defined arguments with the given key. Returns an empty vector if such key does not exist.\n\n\t[[nodiscard]] std::vector<std::string> GetValues(const std::string& _key) const;\n\n\n\nprivate:\n\n\t// Parses argument returning a key and a value.\n\n\t[[nodiscard]] SToken ParseArgument(const std::string& _argument) const;\n\n\t// Filters parsed tokens removing those with not allowed keys.\n\n\tvoid FilterTokens();\n\n\n\n\t// Checks if the given string represents a long key.\n\n\t[[nodiscard]] bool IsKeyL(const std::string& _str) const;\n\n\t// Checks if the given string represents a short key.\n\n\t[[nodiscard]] bool IsKeyS(const std::string& _str) const;\n\n\t// Checks if the given string represents a long or short key.\n\n\t[[nodiscard]] bool IsKey(const std::string& _str) const;\n", "file_path": "ScriptInterface/ArgumentsParser.h", "rank": 94, "score": 12.911324976982602 }, { "content": "/* Copyright (c) 2021, Dyssol Development Team. All rights reserved. This file is part of Dyssol. See LICENSE file for license information. */\n\n\n\n#include \"ScriptTypes.h\"\n\n#include \"StringFunctions.h\"\n\n\n\nusing namespace StringFunctions;\n\n\n\nnamespace ScriptInterface\n\n{\n\n\tstd::istream& operator>>(std::istream& _s, SNameOrIndex& _obj)\n\n\t{\n\n\t\tconst auto str = GetValueFromStream<std::string>(_s);\n\n\t\t_obj.name = IsSimpleUInt(str) ? \"\" : str;\n\n\t\t_obj.index = IsSimpleUInt(str) ? static_cast<size_t>(std::stoull(str) - 1) : -1;\n\n\t\treturn _s;\n\n\t}\n\n\tstd::ostream& operator<<(std::ostream& _s, const SNameOrIndex& _obj)\n\n\t{\n\n\t\t_s << Quote(_obj.name);\n\n\t\treturn _s;\n", "file_path": "ScriptInterface/ScriptTypes.cpp", "rank": 95, "score": 12.861765481856272 }, { "content": "void Dyssol::setVisible(bool _visible)\n\n{\n\n\tQMainWindow::setVisible(_visible);\n\n\tif (_visible)\n\n\t\tUpdateWholeView();\n\n}\n\n\n\nvoid Dyssol::LoadRecentFile()\n\n{\n\n\tauto* pAction = qobject_cast<QAction*>(sender());\n\n\tif (!pAction) return;\n\n\tif (!CheckAndAskUnsaved()) return;\n\n\tconst QString newFile = pAction->data().toString();\n\n\tif (newFile == m_sCurrFlowsheetFile) return;\n\n\tLoadFromFile(newFile);\n\n\tSetFlowsheetModified(false);\n\n}\n\n\n\nvoid Dyssol::NewFlowsheet()\n\n{\n", "file_path": "DyssolMainWindow/Dyssol.cpp", "rank": 96, "score": 12.828105388154976 }, { "content": "}\n\n\n\nbool CFlowsheet::HasPhase(EPhase _phase)\n\n{\n\n\treturn VectorContains(m_phases, [&](const auto& p) { return p.state == _phase; });\n\n}\n\n\n\nstd::string CFlowsheet::Initialize()\n\n{\n\n\t// clear previous results\n\n\tClearSimulationResults();\n\n\n\n\t// check that all units have assigned models\n\n\tfor (const auto& unit : m_units)\n\n\t\tif (!unit->GetModel())\n\n\t\t\treturn StrConst::Flow_ErrEmptyUnit(unit->GetName());\n\n\n\n\t// set pointers to the streams into the corresponding unit's ports\n\n\tSetStreamsToPorts();\n\n\n", "file_path": "SimulatorCore/Flowsheet.cpp", "rank": 97, "score": 12.814470972904456 }, { "content": "}\n\n\n\nvoid CDimensionParameters::UpdateLimits() const\n\n{\n\n\t[[maybe_unused]] CSignalBlocker blocker{ ui.lineMin, ui.lineMax };\n\n\tif (m_grid->GridType() != EGridEntry::GRID_NUMERIC) return;\n\n\tconst auto& vals = dynamic_cast<CGridDimensionNumeric*>(m_grid.get())->Grid();\n\n\tui.lineMin->setText(QString::number(FromM(vals.front())));\n\n\tui.lineMax->setText(QString::number(FromM(vals.back ())));\n\n}\n\n\n\nvoid CDimensionParameters::UpdateUnits() const\n\n{\n\n\tSelectComboboxValue(ui.comboUnits, E2I(DetermineUnits()));\n\n}\n\n\n\nvoid CDimensionParameters::UpdateGrid() const\n\n{\n\n\t[[maybe_unused]] CSignalBlocker blocker{ ui.tableGrid };\n\n\tif (m_grid->GridType() == EGridEntry::GRID_NUMERIC)\n", "file_path": "GUIDialogs/GridEditor/DimensionParameters.cpp", "rank": 98, "score": 12.792822518486751 }, { "content": "\t{\n\n\t\treturn !_s.empty() && std::find_if(_s.begin(), _s.end(), [](auto c) { return !std::isdigit(c); }) == _s.end();\n\n\t}\n\n\n\n\tbool Contains(const std::string& _s, char _c)\n\n\t{\n\n\t\treturn _s.find(_c) != std::string::npos;\n\n\t}\n\n\n\n\tbool Contains(const std::string& _s, const std::string& _subs)\n\n\t{\n\n\t\treturn _s.find(_subs) != std::string::npos;\n\n\t}\n\n\n\n\tvoid ReplaceAll(std::string& _s, const std::string& _old, const std::string& _new)\n\n\t{\n\n\t\tif (_old.empty() || _s.empty()) return;\n\n\t\tsize_t pos = _s.find(_old);\n\n\t\twhile (pos != std::string::npos)\n\n\t\t{\n", "file_path": "Utilities/StringFunctions.cpp", "rank": 99, "score": 12.791670978860303 } ]
C++
frameworks/base/media/agifencoder/jni/agifencoder_jni.cpp
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
#include <jni.h> #include <utils/Log.h> #include <stdio.h> #include <stdlib.h> #include "SkBitmap.h" #include "GraphicsJNI.h" #include "SkPixelRef.h" #include <cutils/xlog.h> #define LOG_TAG "AGIF_ENCODER_JNI" #if 0 #include "SkMovie.h" #include "SkStream.h" #include "GraphicsJNI.h" #include "SkTemplates.h" #include "SkUtils.h" #endif #include "AGifEncoder.h" #include <androidfw/Asset.h> #include <androidfw/ResourceTypes.h> #include <netinet/in.h> #include "utils/Log.h" static jmethodID gOutputStream_writeMethodID; static jmethodID gOutputStream_flushMethodID; #define RETURN_NULL_IF_NULL(value) \ do { if (!(value)) { SkASSERT(0); return NULL; } } while (false) class GifSkJavaOutputStream : public SkWStream { public: GifSkJavaOutputStream(JNIEnv* env, jobject stream, jbyteArray storage) : fEnv(env), fJavaOutputStream(stream), fJavaByteArray(storage) { fCapacity = env->GetArrayLength(storage); } virtual bool write(const void* buffer, size_t size) { JNIEnv* env = fEnv; jbyteArray storage = fJavaByteArray; while (size > 0) { size_t requested = size; if (requested > fCapacity) { requested = fCapacity; } env->SetByteArrayRegion(storage, 0, requested, reinterpret_cast<const jbyte*>(buffer)); if (env->ExceptionCheck()) { env->ExceptionDescribe(); env->ExceptionClear(); SkDebugf("--- write:SetByteArrayElements threw an exception\n"); return false; } fEnv->CallVoidMethod(fJavaOutputStream, gOutputStream_writeMethodID, storage, 0, requested); if (env->ExceptionCheck()) { env->ExceptionDescribe(); env->ExceptionClear(); SkDebugf("------- write threw an exception\n"); return false; } buffer = (void*)((char*)buffer + requested); size -= requested; } return true; } virtual void flush() { fEnv->CallVoidMethod(fJavaOutputStream, gOutputStream_flushMethodID); } private: JNIEnv* fEnv; jobject fJavaOutputStream; jbyteArray fJavaByteArray; size_t fCapacity; }; SkWStream* GifCreateJavaOutputStreamAdaptor(JNIEnv* env, jobject stream, jbyteArray storage) { static bool gInited; if (!gInited) { XLOGI("AGIFE::GifCreateJavaOutputStreamAdaptor Init %d, go L:%d!!\n",gInited, __LINE__); jclass outputStream_Clazz = env->FindClass("java/io/OutputStream"); RETURN_NULL_IF_NULL(outputStream_Clazz); gOutputStream_writeMethodID = env->GetMethodID(outputStream_Clazz, "write", "([BII)V"); RETURN_NULL_IF_NULL(gOutputStream_writeMethodID); gOutputStream_flushMethodID = env->GetMethodID(outputStream_Clazz, "flush", "()V"); RETURN_NULL_IF_NULL(gOutputStream_flushMethodID); gInited = true; } return new GifSkJavaOutputStream(env, stream, storage); } static jclass gAGifEncoder_class; static jmethodID gAGifEncoder_constructorMethodID; static jfieldID gAGifEncoder_nativeInstanceID; jobject create_jmovie(JNIEnv* env, AGifEncoder* encoder, int width, int height) { if (NULL == encoder) { XLOGI("AGIFE::create_jmovie create fail, go L:%d!!\n", __LINE__); return NULL; } #if 1 jobject obj = env->AllocObject(gAGifEncoder_class); if (obj) { env->CallVoidMethod(obj, gAGifEncoder_constructorMethodID, (jint)encoder, (jint)width, (jint)height ); } return obj; #else return env->NewObject(gAGifEncoder_class, gAGifEncoder_constructorMethodID, static_cast<jint>(reinterpret_cast<uintptr_t>(encoder))); #endif } static AGifEncoder* J2AGifEncoder(JNIEnv* env, jobject movie) { SkASSERT(env); SkASSERT(movie); SkASSERT(env->IsInstanceOf(movie, gAGifEncoder_class)); AGifEncoder* m = (AGifEncoder*)env->GetIntField(movie, gAGifEncoder_nativeInstanceID); SkASSERT(m); XLOGI("AGIFE::J2AGifEncoder get encoder %x->%x, go L:%d!!\n", (unsigned int)movie, (unsigned int)m,__LINE__); return m; } static int agifenc_width(JNIEnv* env, jobject movie, AGifEncoder* enc) { XLOGI("AGIFE::agifenc_width, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_ZERO(env, movie); if(enc != NULL) return enc->width(); else return 0 ; } static int agifenc_height(JNIEnv* env, jobject movie, AGifEncoder* enc) { XLOGI("AGIFE::agifenc_height, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_ZERO(env, movie); if(enc != NULL) return enc->height(); else return 0 ; } static int agifenc_duration(JNIEnv* env, jobject movie, AGifEncoder* enc) { XLOGI("AGIFE::agifenc_duration, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_ZERO(env, movie); if(enc != NULL) return enc->duration(); else return 0 ; } static jboolean agifenc_setDuration(JNIEnv* env, jobject movie, AGifEncoder* enc, int ms) { XLOGI("AGIFE::agifenc_setDuration, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_ZERO(env, movie); if(enc!=NULL) return enc->setFrameDuration(ms); else return false ; } static jboolean agifenc_setWidth(JNIEnv* env, jobject movie, int width) { XLOGI("AGIFE::agifenc_setWidth, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_ZERO(env, movie); AGifEncoder* m = J2AGifEncoder(env, movie); return m->setWidth(width); } static jboolean agifenc_setHeight(JNIEnv* env, jobject movie, int height) { XLOGI("AGIFE::agifenc_setHeight, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_ZERO(env, movie); AGifEncoder* m = J2AGifEncoder(env, movie); return m->setHeight(height); } static jboolean agifenc_gifFrameBitmap(JNIEnv* env, jobject movie, AGifEncoder* enc, jintArray pixelArray, jobject jstream, jbyteArray jstorage) { bool ret = false ; jint* dst = env->GetIntArrayElements(pixelArray, NULL); SkWStream* strm = GifCreateJavaOutputStreamAdaptor(env, jstream, jstorage); if(dst == NULL){ XLOGI("AGIFE::agifenc_gifFrameBitmap NULL bitmap, go L:%d!!\n",__LINE__); return false; } if(strm != NULL){ XLOGI("AGIFE::agifenc_gifFrameBitmap %x, go L:%d!!\n", dst,__LINE__); ret = enc->encodeBitmap((unsigned char *)dst, strm); env->ReleaseIntArrayElements(pixelArray, dst, 0); delete strm; } return ret ; } static jobject agifenc_CreateAGifEncoder(JNIEnv* env, jobject movie, int width, int height, jobject jstream, jbyteArray jstorage) { jobject obj ; XLOGI("AGIFE::agifenc_CreateAGifEncoder, go L:%d!!\n", __LINE__); AGifEncoder* encoder = new AGifEncoder(); encoder->setWidth(width); encoder->setHeight(height); encoder->setFrameDuration(100); obj = create_jmovie(env, encoder, width, height); { #if 0 NPE_CHECK_RETURN_ZERO(env, obj); XLOGI("AGIFE::create_jmovie check encoder, go L:%d!!\n", __LINE__); AGifEncoder* m = J2AGifEncoder(env, obj); XLOGI("AGIFE::create_jmovie check encoder %x, go L:%d!!\n", (unsigned int)m,__LINE__); #endif } XLOGI("AGIFE::create_jmovie check obj %x, go L:%d!!\n", (unsigned int)obj,__LINE__); return obj ; } static jobject agifenc_CreateEncoder(JNIEnv* env, jobject movie, int width, int height, jobject jstream, jbyteArray jstorage) { jobject obj ; AGifEncoder* encoder = new AGifEncoder(); XLOGI("AGIFE::create_jmovie encoder %x, go L:%d!!\n", encoder,__LINE__); encoder->setWidth(width); encoder->setHeight(height); encoder->setFrameDuration(100); obj = create_jmovie(env, encoder, width,height); #if 0 { NPE_CHECK_RETURN_ZERO(env, obj); XLOGI("AGIFE::create_jmovie check encoder, go L:%d!!\n", __LINE__); AGifEncoder* m = J2AGifEncoder(env, obj); XLOGI("AGIFE::create_jmovie check encoder %x, go L:%d!!\n", (unsigned int)m,__LINE__); } #endif return obj ; } static jboolean agifenc_setOutputStream(JNIEnv* env, jobject movie, AGifEncoder* enc, jobject jstream, jbyteArray jstorage) { XLOGI("AGIFE::agifenc_setOutputStream obj %x, enc %x, go L:%d!!\n",movie, enc,__LINE__); SkWStream* strm = GifCreateJavaOutputStreamAdaptor(env, jstream, jstorage); if (NULL != strm) { XLOGI("AGIFE::setOutputStream encoder %x, go L:%d!!\n", (unsigned int)enc,__LINE__); enc->setEncodeStream(strm); delete strm; return true ; } return true ; } static int agifenc_encodeFrameCount(JNIEnv* env, jobject movie) { XLOGI("AGIFE::agifenc_encodeFrameCount, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_ZERO(env, movie); AGifEncoder* m = J2AGifEncoder(env, movie); return m->getGifTotalFrameCount(); } static void agifenc_closeGif(JNIEnv* env, jobject movie, jobject jstream, jbyteArray jstorage) { XLOGI("AGIFE::agifenc_closeGif, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_VOID(env, movie); AGifEncoder* m = J2AGifEncoder(env, movie); SkWStream* strm = GifCreateJavaOutputStreamAdaptor(env, jstream, jstorage); if (NULL != strm) { m->setEncodeStream(strm); m->closeGif(); delete strm; delete m; } } static void agifenc_closeStream(JNIEnv* env, jobject movie, AGifEncoder* enc, jobject jstream, jbyteArray jstorage) { XLOGI("AGIFE::agifenc_closeStream, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_VOID(env, movie); SkWStream* strm = GifCreateJavaOutputStreamAdaptor(env, jstream, jstorage); if(enc != NULL){ XLOGI("AGIFE::agifenc_closeStream stream %x, go L:%d!!\n", (unsigned int)enc,__LINE__); enc->setEncodeStream(strm); enc->closeGif(); delete enc; } if (NULL != strm){ delete strm; } env->SetIntField(movie,gAGifEncoder_nativeInstanceID,0); } static void agifenc_destructor(JNIEnv* env, jobject movie, AGifEncoder* enc) { XLOGI("AGIFE::agifenc_destructor, go L:%d!!\n", __LINE__); if(enc != NULL){ XLOGI("AGIFE::agifenc_destructor delete encoder %x, go L:%d!!\n", (unsigned int)enc,__LINE__); delete enc; } env->SetIntField(movie,gAGifEncoder_nativeInstanceID,0); } #include <android_runtime/AndroidRuntime.h> static JNINativeMethod gMethods[] = { { "nativeWidth" , "(I)I", (void*)agifenc_width }, { "nativeHeight" , "(I)I", (void*)agifenc_height }, { "nativeDuration" , "(I)I", (void*)agifenc_duration }, { "nativeSetDuration" , "(II)Z", (void*)agifenc_setDuration }, { "nativeEncodeFrameCount" , "()I", (void*)agifenc_encodeFrameCount }, { "nativeEncodeBitmap" , "(I[ILjava/io/OutputStream;[B)Z", (void*)agifenc_gifFrameBitmap }, { "nativeCloseStream" , "(ILjava/io/OutputStream;[B)Z" , (void*)agifenc_closeStream }, { "nativeCloseGif" , "(Ljava/io/OutputStream;[B)Z" , (void*)agifenc_closeGif }, { "nativeDestructor" , "(I)V", (void*)agifenc_destructor }, { "nativeSetOutputStream" , "(ILjava/io/OutputStream;[B)Z", (void*)agifenc_setOutputStream }, { "nativeCreateEncoder" , "(IILjava/io/OutputStream;[B)Lcom/mediatek/agifencoder/AGifEncoder;", (void*)agifenc_CreateEncoder }, { "nativeCreateAGifEncoder" , "(II)Lcom/mediatek/agifencoder/AGifEncoder;", (void*)agifenc_CreateAGifEncoder }, }; static const char *kClassPathName = "com/mediatek/agifencoder/AGifEncoder"; #define RETURN_ERR_IF_NULL(value) do { if (!(value)) { assert(0); return -1; } } while (false) static int registerNativeMethods(JNIEnv* env, const char* className, JNINativeMethod* gMethods, int numMethods) { jclass clazz; XLOGI("JNI_register, go L:%d!!\n", __LINE__); clazz = env->FindClass(className); if (clazz == NULL) { XLOGE("Native registration unable to find class '%s'", className); return JNI_FALSE; } if (env->RegisterNatives(clazz, gMethods, numMethods) < 0) { XLOGE("RegisterNatives failed for '%s'", className); return JNI_FALSE; } return JNI_TRUE; } int register_android_graphics_AGifEncoder(JNIEnv* env); int register_android_graphics_AGifEncoder(JNIEnv* env) { XLOGI("JNI_register, go L:%d!!\n", __LINE__); gAGifEncoder_class = env->FindClass(kClassPathName); RETURN_ERR_IF_NULL(gAGifEncoder_class); gAGifEncoder_class = (jclass)env->NewGlobalRef(gAGifEncoder_class); gAGifEncoder_constructorMethodID = env->GetMethodID(gAGifEncoder_class, "<init>", "(III)V"); RETURN_ERR_IF_NULL(gAGifEncoder_constructorMethodID); gAGifEncoder_nativeInstanceID = env->GetFieldID(gAGifEncoder_class, "mNativeAGifEncoder", "I"); RETURN_ERR_IF_NULL(gAGifEncoder_nativeInstanceID); if (!registerNativeMethods(env, kClassPathName, gMethods, sizeof(gMethods) / sizeof(gMethods[0])) ) { return JNI_FALSE; } XLOGI("JNI_register, go L:%d!!\n", __LINE__); return JNI_TRUE ; } typedef union { JNIEnv* env; void* venv; } UnionJNIEnvToVoid; jint JNI_OnLoad(JavaVM* vm, void* reserved) { UnionJNIEnvToVoid uenv; uenv.venv = NULL; jint result = -1; JNIEnv* env = NULL; XLOGI("JNI_OnLoad"); if (vm->GetEnv(&uenv.venv, JNI_VERSION_1_4) != JNI_OK) { XLOGE("ERROR: GetEnv failed"); goto bail; } env = uenv.env; if (register_android_graphics_AGifEncoder(env) != JNI_TRUE) { XLOGE("ERROR: registerNatives failed"); goto bail; } result = JNI_VERSION_1_4; bail: return result; }
#include <jni.h> #include <utils/Log.h> #include <stdio.h> #include <stdlib.h> #include "SkBitmap.h" #include "GraphicsJNI.h" #include "SkPixelRef.h" #include <cutils/xlog.h> #define LOG_TAG "AGIF_ENCODER_JNI" #if 0 #include "SkMovie.h" #include "SkStream.h" #include "GraphicsJNI.h" #include "SkTemplates.h" #include "SkUtils.h" #endif #include "AGifEncoder.h" #include <androidfw/Asset.h> #include <androidfw/ResourceTypes.h> #include <netinet/in.h> #include "utils/Log.h" static jmethodID gOutputStream_writeMethodID; static jmethodID gOutputStream_flushMethodID; #define RETURN_NULL_IF_NULL(value) \ do { if (!(value)) { SkASSERT(0); return NULL; } } while (false) class GifSkJavaOutputStream : public SkWStream { public: GifSkJavaOutputStream(JNIEnv* env, jobject stream, jbyteArray storage) : fEnv(env), fJavaOutputStream(stream), fJavaByteArray(storage) { fCapacity = env->GetArrayLength(storage); } virtual bool write(const void* buffer, size_t size) { JNIEnv* env = fEnv; jbyteArray storage = fJavaByteArray; while (size > 0) { size_t requested = size; if (requested > fCapacity) { requested = fCapacity; } env->SetByteArrayRegion(storage, 0, requested, reinterpret_cast<const jbyte*>(buffer)); if (env->ExceptionCheck()) { env->ExceptionDescribe(); env->Ex
m; return true ; } return true ; } static int agifenc_encodeFrameCount(JNIEnv* env, jobject movie) { XLOGI("AGIFE::agifenc_encodeFrameCount, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_ZERO(env, movie); AGifEncoder* m = J2AGifEncoder(env, movie); return m->getGifTotalFrameCount(); } static void agifenc_closeGif(JNIEnv* env, jobject movie, jobject jstream, jbyteArray jstorage) { XLOGI("AGIFE::agifenc_closeGif, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_VOID(env, movie); AGifEncoder* m = J2AGifEncoder(env, movie); SkWStream* strm = GifCreateJavaOutputStreamAdaptor(env, jstream, jstorage); if (NULL != strm) { m->setEncodeStream(strm); m->closeGif(); delete strm; delete m; } } static void agifenc_closeStream(JNIEnv* env, jobject movie, AGifEncoder* enc, jobject jstream, jbyteArray jstorage) { XLOGI("AGIFE::agifenc_closeStream, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_VOID(env, movie); SkWStream* strm = GifCreateJavaOutputStreamAdaptor(env, jstream, jstorage); if(enc != NULL){ XLOGI("AGIFE::agifenc_closeStream stream %x, go L:%d!!\n", (unsigned int)enc,__LINE__); enc->setEncodeStream(strm); enc->closeGif(); delete enc; } if (NULL != strm){ delete strm; } env->SetIntField(movie,gAGifEncoder_nativeInstanceID,0); } static void agifenc_destructor(JNIEnv* env, jobject movie, AGifEncoder* enc) { XLOGI("AGIFE::agifenc_destructor, go L:%d!!\n", __LINE__); if(enc != NULL){ XLOGI("AGIFE::agifenc_destructor delete encoder %x, go L:%d!!\n", (unsigned int)enc,__LINE__); delete enc; } env->SetIntField(movie,gAGifEncoder_nativeInstanceID,0); } #include <android_runtime/AndroidRuntime.h> static JNINativeMethod gMethods[] = { { "nativeWidth" , "(I)I", (void*)agifenc_width }, { "nativeHeight" , "(I)I", (void*)agifenc_height }, { "nativeDuration" , "(I)I", (void*)agifenc_duration }, { "nativeSetDuration" , "(II)Z", (void*)agifenc_setDuration }, { "nativeEncodeFrameCount" , "()I", (void*)agifenc_encodeFrameCount }, { "nativeEncodeBitmap" , "(I[ILjava/io/OutputStream;[B)Z", (void*)agifenc_gifFrameBitmap }, { "nativeCloseStream" , "(ILjava/io/OutputStream;[B)Z" , (void*)agifenc_closeStream }, { "nativeCloseGif" , "(Ljava/io/OutputStream;[B)Z" , (void*)agifenc_closeGif }, { "nativeDestructor" , "(I)V", (void*)agifenc_destructor }, { "nativeSetOutputStream" , "(ILjava/io/OutputStream;[B)Z", (void*)agifenc_setOutputStream }, { "nativeCreateEncoder" , "(IILjava/io/OutputStream;[B)Lcom/mediatek/agifencoder/AGifEncoder;", (void*)agifenc_CreateEncoder }, { "nativeCreateAGifEncoder" , "(II)Lcom/mediatek/agifencoder/AGifEncoder;", (void*)agifenc_CreateAGifEncoder }, }; static const char *kClassPathName = "com/mediatek/agifencoder/AGifEncoder"; #define RETURN_ERR_IF_NULL(value) do { if (!(value)) { assert(0); return -1; } } while (false) static int registerNativeMethods(JNIEnv* env, const char* className, JNINativeMethod* gMethods, int numMethods) { jclass clazz; XLOGI("JNI_register, go L:%d!!\n", __LINE__); clazz = env->FindClass(className); if (clazz == NULL) { XLOGE("Native registration unable to find class '%s'", className); return JNI_FALSE; } if (env->RegisterNatives(clazz, gMethods, numMethods) < 0) { XLOGE("RegisterNatives failed for '%s'", className); return JNI_FALSE; } return JNI_TRUE; } int register_android_graphics_AGifEncoder(JNIEnv* env); int register_android_graphics_AGifEncoder(JNIEnv* env) { XLOGI("JNI_register, go L:%d!!\n", __LINE__); gAGifEncoder_class = env->FindClass(kClassPathName); RETURN_ERR_IF_NULL(gAGifEncoder_class); gAGifEncoder_class = (jclass)env->NewGlobalRef(gAGifEncoder_class); gAGifEncoder_constructorMethodID = env->GetMethodID(gAGifEncoder_class, "<init>", "(III)V"); RETURN_ERR_IF_NULL(gAGifEncoder_constructorMethodID); gAGifEncoder_nativeInstanceID = env->GetFieldID(gAGifEncoder_class, "mNativeAGifEncoder", "I"); RETURN_ERR_IF_NULL(gAGifEncoder_nativeInstanceID); if (!registerNativeMethods(env, kClassPathName, gMethods, sizeof(gMethods) / sizeof(gMethods[0])) ) { return JNI_FALSE; } XLOGI("JNI_register, go L:%d!!\n", __LINE__); return JNI_TRUE ; } typedef union { JNIEnv* env; void* venv; } UnionJNIEnvToVoid; jint JNI_OnLoad(JavaVM* vm, void* reserved) { UnionJNIEnvToVoid uenv; uenv.venv = NULL; jint result = -1; JNIEnv* env = NULL; XLOGI("JNI_OnLoad"); if (vm->GetEnv(&uenv.venv, JNI_VERSION_1_4) != JNI_OK) { XLOGE("ERROR: GetEnv failed"); goto bail; } env = uenv.env; if (register_android_graphics_AGifEncoder(env) != JNI_TRUE) { XLOGE("ERROR: registerNatives failed"); goto bail; } result = JNI_VERSION_1_4; bail: return result; }
ceptionClear(); SkDebugf("--- write:SetByteArrayElements threw an exception\n"); return false; } fEnv->CallVoidMethod(fJavaOutputStream, gOutputStream_writeMethodID, storage, 0, requested); if (env->ExceptionCheck()) { env->ExceptionDescribe(); env->ExceptionClear(); SkDebugf("------- write threw an exception\n"); return false; } buffer = (void*)((char*)buffer + requested); size -= requested; } return true; } virtual void flush() { fEnv->CallVoidMethod(fJavaOutputStream, gOutputStream_flushMethodID); } private: JNIEnv* fEnv; jobject fJavaOutputStream; jbyteArray fJavaByteArray; size_t fCapacity; }; SkWStream* GifCreateJavaOutputStreamAdaptor(JNIEnv* env, jobject stream, jbyteArray storage) { static bool gInited; if (!gInited) { XLOGI("AGIFE::GifCreateJavaOutputStreamAdaptor Init %d, go L:%d!!\n",gInited, __LINE__); jclass outputStream_Clazz = env->FindClass("java/io/OutputStream"); RETURN_NULL_IF_NULL(outputStream_Clazz); gOutputStream_writeMethodID = env->GetMethodID(outputStream_Clazz, "write", "([BII)V"); RETURN_NULL_IF_NULL(gOutputStream_writeMethodID); gOutputStream_flushMethodID = env->GetMethodID(outputStream_Clazz, "flush", "()V"); RETURN_NULL_IF_NULL(gOutputStream_flushMethodID); gInited = true; } return new GifSkJavaOutputStream(env, stream, storage); } static jclass gAGifEncoder_class; static jmethodID gAGifEncoder_constructorMethodID; static jfieldID gAGifEncoder_nativeInstanceID; jobject create_jmovie(JNIEnv* env, AGifEncoder* encoder, int width, int height) { if (NULL == encoder) { XLOGI("AGIFE::create_jmovie create fail, go L:%d!!\n", __LINE__); return NULL; } #if 1 jobject obj = env->AllocObject(gAGifEncoder_class); if (obj) { env->CallVoidMethod(obj, gAGifEncoder_constructorMethodID, (jint)encoder, (jint)width, (jint)height ); } return obj; #else return env->NewObject(gAGifEncoder_class, gAGifEncoder_constructorMethodID, static_cast<jint>(reinterpret_cast<uintptr_t>(encoder))); #endif } static AGifEncoder* J2AGifEncoder(JNIEnv* env, jobject movie) { SkASSERT(env); SkASSERT(movie); SkASSERT(env->IsInstanceOf(movie, gAGifEncoder_class)); AGifEncoder* m = (AGifEncoder*)env->GetIntField(movie, gAGifEncoder_nativeInstanceID); SkASSERT(m); XLOGI("AGIFE::J2AGifEncoder get encoder %x->%x, go L:%d!!\n", (unsigned int)movie, (unsigned int)m,__LINE__); return m; } static int agifenc_width(JNIEnv* env, jobject movie, AGifEncoder* enc) { XLOGI("AGIFE::agifenc_width, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_ZERO(env, movie); if(enc != NULL) return enc->width(); else return 0 ; } static int agifenc_height(JNIEnv* env, jobject movie, AGifEncoder* enc) { XLOGI("AGIFE::agifenc_height, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_ZERO(env, movie); if(enc != NULL) return enc->height(); else return 0 ; } static int agifenc_duration(JNIEnv* env, jobject movie, AGifEncoder* enc) { XLOGI("AGIFE::agifenc_duration, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_ZERO(env, movie); if(enc != NULL) return enc->duration(); else return 0 ; } static jboolean agifenc_setDuration(JNIEnv* env, jobject movie, AGifEncoder* enc, int ms) { XLOGI("AGIFE::agifenc_setDuration, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_ZERO(env, movie); if(enc!=NULL) return enc->setFrameDuration(ms); else return false ; } static jboolean agifenc_setWidth(JNIEnv* env, jobject movie, int width) { XLOGI("AGIFE::agifenc_setWidth, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_ZERO(env, movie); AGifEncoder* m = J2AGifEncoder(env, movie); return m->setWidth(width); } static jboolean agifenc_setHeight(JNIEnv* env, jobject movie, int height) { XLOGI("AGIFE::agifenc_setHeight, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_ZERO(env, movie); AGifEncoder* m = J2AGifEncoder(env, movie); return m->setHeight(height); } static jboolean agifenc_gifFrameBitmap(JNIEnv* env, jobject movie, AGifEncoder* enc, jintArray pixelArray, jobject jstream, jbyteArray jstorage) { bool ret = false ; jint* dst = env->GetIntArrayElements(pixelArray, NULL); SkWStream* strm = GifCreateJavaOutputStreamAdaptor(env, jstream, jstorage); if(dst == NULL){ XLOGI("AGIFE::agifenc_gifFrameBitmap NULL bitmap, go L:%d!!\n",__LINE__); return false; } if(strm != NULL){ XLOGI("AGIFE::agifenc_gifFrameBitmap %x, go L:%d!!\n", dst,__LINE__); ret = enc->encodeBitmap((unsigned char *)dst, strm); env->ReleaseIntArrayElements(pixelArray, dst, 0); delete strm; } return ret ; } static jobject agifenc_CreateAGifEncoder(JNIEnv* env, jobject movie, int width, int height, jobject jstream, jbyteArray jstorage) { jobject obj ; XLOGI("AGIFE::agifenc_CreateAGifEncoder, go L:%d!!\n", __LINE__); AGifEncoder* encoder = new AGifEncoder(); encoder->setWidth(width); encoder->setHeight(height); encoder->setFrameDuration(100); obj = create_jmovie(env, encoder, width, height); { #if 0 NPE_CHECK_RETURN_ZERO(env, obj); XLOGI("AGIFE::create_jmovie check encoder, go L:%d!!\n", __LINE__); AGifEncoder* m = J2AGifEncoder(env, obj); XLOGI("AGIFE::create_jmovie check encoder %x, go L:%d!!\n", (unsigned int)m,__LINE__); #endif } XLOGI("AGIFE::create_jmovie check obj %x, go L:%d!!\n", (unsigned int)obj,__LINE__); return obj ; } static jobject agifenc_CreateEncoder(JNIEnv* env, jobject movie, int width, int height, jobject jstream, jbyteArray jstorage) { jobject obj ; AGifEncoder* encoder = new AGifEncoder(); XLOGI("AGIFE::create_jmovie encoder %x, go L:%d!!\n", encoder,__LINE__); encoder->setWidth(width); encoder->setHeight(height); encoder->setFrameDuration(100); obj = create_jmovie(env, encoder, width,height); #if 0 { NPE_CHECK_RETURN_ZERO(env, obj); XLOGI("AGIFE::create_jmovie check encoder, go L:%d!!\n", __LINE__); AGifEncoder* m = J2AGifEncoder(env, obj); XLOGI("AGIFE::create_jmovie check encoder %x, go L:%d!!\n", (unsigned int)m,__LINE__); } #endif return obj ; } static jboolean agifenc_setOutputStream(JNIEnv* env, jobject movie, AGifEncoder* enc, jobject jstream, jbyteArray jstorage) { XLOGI("AGIFE::agifenc_setOutputStream obj %x, enc %x, go L:%d!!\n",movie, enc,__LINE__); SkWStream* strm = GifCreateJavaOutputStreamAdaptor(env, jstream, jstorage); if (NULL != strm) { XLOGI("AGIFE::setOutputStream encoder %x, go L:%d!!\n", (unsigned int)enc,__LINE__); enc->setEncodeStream(strm); delete str
random
[]
C++
src/network-container.cc
imonlius/interactive-neurons
da8cbdad8cf5595a2be1b48125ecad5e6c802f2c
#include "neurons/network-container.h" #include "neurons/utilities.h" namespace neurons { NetworkContainer::NetworkContainer(NodeDeque& nodes, const std::deque<Link>& links) : links_(links) { if (!utilities::NodesAndLinksConsistent(nodes, links)) { throw std::invalid_argument("Passed nodes and links are inconsistent."); } if (utilities::CountConnectedComponents(nodes, links) != 1) { throw std::invalid_argument("Graph does not consist of 1 component."); } if (utilities::ContainsDirectedCycle(nodes, links)) { throw std::invalid_argument("Graph contains a directed cycle."); } if (!utilities::AreNodeInputsSatisfied(nodes, links)) { throw std::invalid_argument("Graph node inputs are not satisfied."); } if (!utilities::AreNodeOutputsSatisfied(nodes, links)) { throw std::invalid_argument("Graph node outputs are not satisfied."); } NodeDeque sorted = utilities::TopologicalSort(nodes, links); data_node_id_ = sorted.front()->GetId(); sorted.pop_front(); loss_node_id_ = sorted.back()->GetId(); sorted.pop_back(); for (auto& node : sorted) { auto module_node = std::dynamic_pointer_cast<ModuleNode>(node); add(module_node); } } std::vector<fl::Variable> Add(const std::vector<fl::Variable>& lhs, const std::vector<fl::Variable>& rhs) { if (lhs.size() != rhs.size()) { throw std::invalid_argument("Vector sizes do not match!"); } std::vector<fl::Variable> result; for (size_t i = 0; i < lhs.size(); ++i) { result.push_back(lhs.at(i) + rhs.at(i)); } return result; } std::vector<fl::Variable> NetworkContainer::forward( const std::vector<fl::Variable>& input) { if (input.size() != 1) { throw std::invalid_argument("Network expects only one input"); } auto output_maps = std::map<fl::ModulePtr, std::vector<fl::Variable>>(); for (const auto& module : modules_) { std::vector<fl::Variable> module_input; for (const auto& link : links_) { if (std::dynamic_pointer_cast<void>(link.output_) != std::dynamic_pointer_cast<void>(module)) { continue; } std::vector<fl::Variable> link_input; if (link.input_->GetId() == data_node_id_) { link_input = input; } else { auto module_ptr = std::dynamic_pointer_cast<fl::Module>(link.input_); if (module_ptr == nullptr) { throw std::runtime_error("Network links are invalid."); } link_input = output_maps.at(module_ptr); } module_input = module_input.empty() ? link_input : Add(module_input, link_input); } auto module_output = module->forward(module_input); output_maps.insert({module, module_output}); } std::vector<fl::Variable> output; for (const auto& link : links_) { if (link.output_->GetId() == loss_node_id_) { auto module_ptr = std::dynamic_pointer_cast<fl::Module>(link.input_); if (module_ptr == nullptr) { throw std::runtime_error("Network container modules are invalid."); } auto link_output = output_maps.at(module_ptr); output = output.empty() ? link_output : Add(output, link_output); } } if (input.size() != output.size()) { throw std::runtime_error("Unexpected container output size."); } return output; } fl::Variable NetworkContainer::forward(const fl::Variable& input) { std::vector<fl::Variable> output = {input}; output = forward(output); return output.front(); } fl::Variable NetworkContainer::operator()(const fl::Variable& input) { return forward(input); } std::string NetworkContainer::prettyString() const { std::ostringstream output; output << "Network:" << std::endl; output << "["; bool first_link = true; for (const auto& link : links_) { if (!first_link) { output << ", "; } else { first_link = false; } if (link.input_->GetId() == data_node_id_) { output << "input"; } else { output << "(" << link.input_->GetId() << ")"; } output << " -> "; if (link.output_->GetId() == loss_node_id_) { output << "output"; } else { output << "(" << link.output_->GetId() << ")"; } } output << "]" << std::endl; for (const auto& module : modules_) { output << "(" << std::dynamic_pointer_cast<ModuleNode>(module)->GetId() << "): "; output << module->prettyString() << std::endl; } return output.str(); } }
#include "neurons/network-container.h" #include "neurons/utilities.h" namespace neurons { NetworkContainer::NetworkContainer(NodeDeque& nodes, const std::deque<Link>& links) : links_(links) { if (!utilities::NodesAndLinksConsistent(nodes, links)) { throw std::in
std::vector<fl::Variable> Add(const std::vector<fl::Variable>& lhs, const std::vector<fl::Variable>& rhs) { if (lhs.size() != rhs.size()) { throw std::invalid_argument("Vector sizes do not match!"); } std::vector<fl::Variable> result; for (size_t i = 0; i < lhs.size(); ++i) { result.push_back(lhs.at(i) + rhs.at(i)); } return result; } std::vector<fl::Variable> NetworkContainer::forward( const std::vector<fl::Variable>& input) { if (input.size() != 1) { throw std::invalid_argument("Network expects only one input"); } auto output_maps = std::map<fl::ModulePtr, std::vector<fl::Variable>>(); for (const auto& module : modules_) { std::vector<fl::Variable> module_input; for (const auto& link : links_) { if (std::dynamic_pointer_cast<void>(link.output_) != std::dynamic_pointer_cast<void>(module)) { continue; } std::vector<fl::Variable> link_input; if (link.input_->GetId() == data_node_id_) { link_input = input; } else { auto module_ptr = std::dynamic_pointer_cast<fl::Module>(link.input_); if (module_ptr == nullptr) { throw std::runtime_error("Network links are invalid."); } link_input = output_maps.at(module_ptr); } module_input = module_input.empty() ? link_input : Add(module_input, link_input); } auto module_output = module->forward(module_input); output_maps.insert({module, module_output}); } std::vector<fl::Variable> output; for (const auto& link : links_) { if (link.output_->GetId() == loss_node_id_) { auto module_ptr = std::dynamic_pointer_cast<fl::Module>(link.input_); if (module_ptr == nullptr) { throw std::runtime_error("Network container modules are invalid."); } auto link_output = output_maps.at(module_ptr); output = output.empty() ? link_output : Add(output, link_output); } } if (input.size() != output.size()) { throw std::runtime_error("Unexpected container output size."); } return output; } fl::Variable NetworkContainer::forward(const fl::Variable& input) { std::vector<fl::Variable> output = {input}; output = forward(output); return output.front(); } fl::Variable NetworkContainer::operator()(const fl::Variable& input) { return forward(input); } std::string NetworkContainer::prettyString() const { std::ostringstream output; output << "Network:" << std::endl; output << "["; bool first_link = true; for (const auto& link : links_) { if (!first_link) { output << ", "; } else { first_link = false; } if (link.input_->GetId() == data_node_id_) { output << "input"; } else { output << "(" << link.input_->GetId() << ")"; } output << " -> "; if (link.output_->GetId() == loss_node_id_) { output << "output"; } else { output << "(" << link.output_->GetId() << ")"; } } output << "]" << std::endl; for (const auto& module : modules_) { output << "(" << std::dynamic_pointer_cast<ModuleNode>(module)->GetId() << "): "; output << module->prettyString() << std::endl; } return output.str(); } }
valid_argument("Passed nodes and links are inconsistent."); } if (utilities::CountConnectedComponents(nodes, links) != 1) { throw std::invalid_argument("Graph does not consist of 1 component."); } if (utilities::ContainsDirectedCycle(nodes, links)) { throw std::invalid_argument("Graph contains a directed cycle."); } if (!utilities::AreNodeInputsSatisfied(nodes, links)) { throw std::invalid_argument("Graph node inputs are not satisfied."); } if (!utilities::AreNodeOutputsSatisfied(nodes, links)) { throw std::invalid_argument("Graph node outputs are not satisfied."); } NodeDeque sorted = utilities::TopologicalSort(nodes, links); data_node_id_ = sorted.front()->GetId(); sorted.pop_front(); loss_node_id_ = sorted.back()->GetId(); sorted.pop_back(); for (auto& node : sorted) { auto module_node = std::dynamic_pointer_cast<ModuleNode>(node); add(module_node); } }
function_block-function_prefixed
[ { "content": "class Link {\n\n\n\n public:\n\n\n\n // Public member variables.\n\n std::shared_ptr<Node> input_;\n\n std::shared_ptr<Node> output_;\n\n\n\n // Get link ID.\n\n [[nodiscard]] size_t GetId() const;\n\n\n\n // Public constructor. Pass shared_ptr by value as Links will share ownership.\n\n Link(size_t id, std::shared_ptr<Node> input, std::shared_ptr<Node> output):\n\n input_(std::move(input)), output_(std::move(output)), id_(id) { };\n\n\n\n private:\n\n\n\n // ID should not be edited after construction.\n\n size_t id_;\n\n\n\n};\n\n\n\n} // namespace neurons\n\n\n\n#endif // FINALPROJECT_NEURONS_LINK_H_\n", "file_path": "include/neurons/link.h", "rank": 0, "score": 114563.72640974264 }, { "content": "// Abstract class to represent a Node in the Network.\n\nclass Node {\n\n\n\n public:\n\n\n\n // Get Node ID\n\n [[nodiscard]] size_t GetId() const;\n\n\n\n // Get Node type\n\n [[nodiscard]] NodeType GetNodeType() const;\n\n\n\n // Get String representation of Node. Must be overriden in derived classes.\n\n [[nodiscard]] virtual std::string prettyString() const = 0;\n\n\n\n // Public constructor\n\n Node(size_t id, NodeType type) : id_(id), type_(type) {};\n\n\n\n // Virtual destructor\n\n virtual ~Node() = default;\n\n\n\n private:\n", "file_path": "include/neurons/node.h", "rank": 1, "score": 112201.65104027331 }, { "content": "class DataNode : public Node {\n\n\n\n public:\n\n // DataNode Constructor\n\n DataNode(size_t id, std::unique_ptr<fl::Dataset> train_set,\n\n std::unique_ptr<fl::Dataset> valid_set,\n\n std::unique_ptr<fl::Dataset> test_set);\n\n\n\n // Pretty string\n\n [[nodiscard]] std::string prettyString() const override;\n\n\n\n // datasets are public members as various functions such as DatasetIterator\n\n // need a non-const reference to it\n\n std::unique_ptr<fl::Dataset> train_dataset_;\n\n std::unique_ptr<fl::Dataset> valid_dataset_;\n\n std::unique_ptr<fl::Dataset> test_dataset_;\n\n\n\n};\n\n\n\n} // namespace neurons\n\n\n\n#endif // FINALPROJECT_NEURONS_DATA_NODE_H_", "file_path": "include/neurons/data-node.h", "rank": 2, "score": 98449.63636297209 }, { "content": "// Copyright (c) 2020 Simon Liu. All rights reserved.\n\n#ifndef FINALPROJECT_NEURONS_LINK_H_\n\n#define FINALPROJECT_NEURONS_LINK_H_\n\n\n\n#include <utility>\n\n\n\n#include \"module-node.h\"\n\n\n\nnamespace neurons {\n\n\n", "file_path": "include/neurons/link.h", "rank": 3, "score": 95444.67355590868 }, { "content": "// Copyright (c) 2020 Simon Liu. All rights reserved.\n\n#ifndef FINALPROJECT_NEURONS_NODE_H_\n\n#define FINALPROJECT_NEURONS_NODE_H_\n\n\n\n#include <deque>\n\n#include <memory>\n\n#include <string>\n\n\n\nnamespace neurons {\n\n\n", "file_path": "include/neurons/node.h", "rank": 4, "score": 93885.64992919029 }, { "content": "\n\n size_t id_;\n\n NodeType type_;\n\n\n\n};\n\n\n\ntypedef std::deque<std::shared_ptr<Node>> NodeDeque;\n\n\n\n} // namespace neurons\n\n\n\n#endif //FINALPROJECT_NEURONS_NODE_H_", "file_path": "include/neurons/node.h", "rank": 5, "score": 93881.94869648051 }, { "content": "enum NodeType {\n\n Dummy, Conv2D, Linear, Sigmoid, Tanh, HardTanh, ReLU, LeakyReLU, ELU,\n\n ThresholdReLU, GatedLinearUnit, LogSoftmax, Log, Dropout, Pool2D,\n\n View, LayerNorm, BatchNorm, CategoricalCrossEntropy, MeanAbsoluteError,\n\n MeanSquaredError, Dataset\n\n};\n\n\n\n// Get the NodeType as an std::string\n\nstd::string NodeTypeToString(NodeType type);\n\n\n", "file_path": "include/neurons/node.h", "rank": 6, "score": 93057.6651101401 }, { "content": "// Copyright (c) 2020 Simon Liu. All rights reserved.\n\n#ifndef FINALPROJECT_NEURONS_MODULE_NODE_H_\n\n#define FINALPROJECT_NEURONS_MODULE_NODE_H_\n\n\n\n#include <flashlight/flashlight.h>\n\n\n\n#include \"node.h\"\n\n\n\nnamespace neurons {\n\n\n", "file_path": "include/neurons/module-node.h", "rank": 7, "score": 89196.41229591527 }, { "content": "// Copyright (c) 2020 Simon Liu. All rights reserved.\n\n#ifndef FINALPROJECT_NEURONS_DATA_NODE_H_\n\n#define FINALPROJECT_NEURONS_DATA_NODE_H_\n\n\n\n#include <flashlight/flashlight.h>\n\n\n\n#include \"module-node.h\"\n\n\n\nnamespace neurons {\n\n\n", "file_path": "include/neurons/data-node.h", "rank": 8, "score": 89196.41229591527 }, { "content": " class ModuleNode : public Node, public fl::Module {\n\n\n\n public:\n\n\n\n // Node Constructor\n\n ModuleNode(size_t id, NodeType type, std::unique_ptr<fl::Module> module);\n\n\n\n // Wrapper methods that will be called on the wrapped fl::Module.\n\n void train() override;\n\n void eval() override;\n\n void setParams(const fl::Variable& var, int position) override;\n\n std::vector<fl::Variable> forward(\n\n const std::vector<fl::Variable>& inputs) override;\n\n [[nodiscard]] std::string prettyString() const override;\n\n\n\n private:\n\n // Unique pointer ensures that Node has sole ownership over module\n\n std::unique_ptr<fl::Module> module_;\n\n};\n\n\n\n} // namespace neurons\n\n\n\n#endif // FINALPROJECT_NEURONS_MODULE_NODE_H_\n", "file_path": "include/neurons/module-node.h", "rank": 9, "score": 87520.21611188899 }, { "content": " Link* link_;\n", "file_path": "include/imgui_adapter/link-adapter.h", "rank": 10, "score": 78881.15503722371 }, { "content": "namespace neurons::adapter {\n\n\n\n// Adapter between a graph link and a neuron Link\n\n// Graph link relies on pins\n\nstruct LinkAdapter {\n\n size_t id_;\n\n size_t start_id_;\n\n size_t end_id_;\n\n\n\n Link* link_;\n\n\n\n // Constructor from Link\n\n explicit LinkAdapter(Link& link);\n\n};\n\n\n\n// Return a vector of LinkAdapters wrapped around the passed links\n\nstd::vector<LinkAdapter> BuildLinkAdapters(std::deque<Link>& links);\n\n\n\n// Returns a pointer to the Link in the passed vector with the passed link ID.\n\n// If multiple Links have the same link ID, will return the first one.\n\n// Returns nullptr if none of the Pins match the criteria.\n\nLinkAdapter* FindOwnerLink(std::vector<LinkAdapter>& links, size_t id);\n\n\n", "file_path": "include/imgui_adapter/link-adapter.h", "rank": 11, "score": 78464.25291178882 }, { "content": "namespace neurons::adapter {\n\n\n\n// Each NodeAdapter requires three unique IDs: NodeId, input PinId, output PinId\n\n// To create a bijection from Link IDs and Node IDs to Adapter IDs:\n\n// Link IDs and Node IDs must be multiplied by 3 to get their Adapter IDs\n\nstatic const size_t kIdMultiplier = 3;\n\n\n\n// Adapter between the imgui-node-editor graph node and a neuron Node\n\nstruct NodeAdapter {\n\n size_t id_;\n\n size_t input_id_;\n\n size_t output_id_;\n\n\n\n std::shared_ptr<Node> node_;\n\n\n\n // Constructor from Node\n\n explicit NodeAdapter(const std::shared_ptr<Node>& node);\n\n};\n\n\n\n\n\n// Return a vector of NodeAdapters wrapped around the passed nodes\n\nstd::vector<NodeAdapter> BuildNodeAdapters(NodeDeque& nodes);\n\n\n\n// Returns a pointer to a Node in the passed vector that owns the node ID.\n\n// If multiple nodes have the node ID, will return the first one.\n\n// Returns nullptr if none of the Nodes match the criteria.\n\nNodeAdapter* FindOwnerNode(std::vector<NodeAdapter>& nodes, size_t id);\n\n\n\n// Returns a pointer to a Node in the passed vector that owns the pin ID.\n\n// If multiple nodes have the pin ID, will return the first one.\n\n// Returns nullptr if none of the Nodes match the criteria.\n\nNodeAdapter* FindPinOwner(std::vector<NodeAdapter>& nodes, size_t id);\n\n\n", "file_path": "include/imgui_adapter/node-adapter.h", "rank": 12, "score": 77326.59483198183 }, { "content": " explicit LinkAdapter(Link& link);\n", "file_path": "include/imgui_adapter/link-adapter.h", "rank": 13, "score": 76329.11522105412 }, { "content": " explicit NodeAdapter(const std::shared_ptr<Node>& node);\n", "file_path": "include/imgui_adapter/node-adapter.h", "rank": 14, "score": 74793.49846385262 }, { "content": " std::shared_ptr<Node> node_;\n", "file_path": "include/imgui_adapter/node-adapter.h", "rank": 15, "score": 71360.96381918056 }, { "content": " size_t id_;\n", "file_path": "include/imgui_adapter/link-adapter.h", "rank": 16, "score": 69756.04385484474 }, { "content": " size_t id_;\n", "file_path": "include/imgui_adapter/node-adapter.h", "rank": 17, "score": 68618.38577503775 }, { "content": " size_t end_id_;\n", "file_path": "include/imgui_adapter/link-adapter.h", "rank": 18, "score": 67174.36706164348 }, { "content": " size_t start_id_;\n", "file_path": "include/imgui_adapter/link-adapter.h", "rank": 19, "score": 67174.36706164348 }, { "content": " size_t output_id_;\n", "file_path": "include/imgui_adapter/node-adapter.h", "rank": 20, "score": 66078.81379886637 }, { "content": " size_t input_id_;\n", "file_path": "include/imgui_adapter/node-adapter.h", "rank": 21, "score": 66078.81379886637 }, { "content": "// Copyright (c) 2020 Simon Liu. All rights reserved.\n\n#ifndef FINALPROJECT_NEURONS_NETWORK_H\n\n#define FINALPROJECT_NEURONS_NETWORK_H\n\n\n\n#include \"data-node.h\"\n\n#include \"link.h\"\n\n#include \"module-node.h\"\n\n#include \"node.h\"\n\n\n\nnamespace neurons {\n\n\n", "file_path": "include/neurons/network.h", "rank": 22, "score": 63020.8839696435 }, { "content": "\n\n private:\n\n\n\n // Keep track of next unique ID for Nodes/Links.\n\n size_t unique_id_;\n\n\n\n // Deque of all the Node pointers in the network.\n\n NodeDeque nodes_;\n\n\n\n // Deque of all the Links in the network.\n\n std::deque<Link> links_;\n\n\n\n};\n\n\n\n} // namespace neurons\n\n\n\n#endif // FINALPROJECT_NEURONS_NETWORK_H\n", "file_path": "include/neurons/network.h", "rank": 23, "score": 63017.450083150485 }, { "content": " std::unique_ptr<fl::Dataset> valid_set,\n\n std::unique_ptr<fl::Dataset> test_set);\n\n\n\n // Add a Link to the network if the input and output form a valid Link.\n\n // Returns a pointer to the Link if successful. Otherwise, returns nullptr.\n\n Link* AddLink(const std::shared_ptr<Node>& input, const std::shared_ptr<Node>& output);\n\n\n\n // Delete a Link from the network.\n\n void DeleteLink(const Link& link);\n\n\n\n // Delete a Node from the network.\n\n void DeleteNode(const Node& node);\n\n\n\n // Returns pointer to the data node of the network. If network does not have\n\n // a data node set, returns nullptr.\n\n [[nodiscard]] std::shared_ptr<DataNode> GetDataNode() const;\n\n\n\n // Returns pointer to the loss node of the network. If network does not have\n\n // a loss node set, returns nullptr.\n\n [[nodiscard]] std::shared_ptr<Node> GetLossNode() const;\n", "file_path": "include/neurons/network.h", "rank": 24, "score": 63011.97257175206 }, { "content": "// Copyright (c) 2020 Simon Liu. All rights reserved.\n\n#ifndef FINALPROJECT_NEURONS_NETWORK_CONTAINER_H_\n\n#define FINALPROJECT_NEURONS_NETWORK_CONTAINER_H_\n\n\n\n#include <flashlight/flashlight.h>\n\n#include \"neurons/link.h\"\n\n#include \"neurons/node.h\"\n\n\n\nnamespace neurons {\n\n\n\n// A subclass of fl::Container generated by a neurons::Network\n\n// does not have an \"is-a\" relationship with fl::Container but rather an\n\n// \"implemented-in-terms-of\" relationship.\n\n// As fl::Container requires adding layers by fl::Module, whereas this requires\n\n// a Node wrapper and Links to indicate Node connections.\n", "file_path": "include/neurons/network-container.h", "rank": 25, "score": 59871.99855142405 }, { "content": " std::vector<fl::Variable> forward(\n\n const std::vector<fl::Variable>& input) override;\n\n\n\n fl::Variable forward(const fl::Variable& input);\n\n\n\n fl::Variable operator()(const fl::Variable& input);\n\n\n\n // Generates a stringified representation of the `NetworkContainer` by\n\n // concatenating string representations for each contained `Module`\n\n std::string prettyString() const override;\n\n\n\n private:\n\n // Data node ID\n\n size_t data_node_id_;\n\n\n\n // Loss node ID\n\n size_t loss_node_id_;\n\n\n\n // Links connecting the modules\n\n const std::deque<Link> links_;\n\n\n\n};\n\n\n\n} // namespace neurons\n\n\n\n#endif // FINALPROJECT_NEURONS_NETWORK_CONTAINER_H_\n", "file_path": "include/neurons/network-container.h", "rank": 26, "score": 59867.809280759044 }, { "content": "class Network {\n\n\n\n public:\n\n\n\n // Retrieve std::deque of Nodes.\n\n [[nodiscard]] NodeDeque& GetNodes();\n\n\n\n // Retrieve std::deque of Links.\n\n [[nodiscard]] std::deque<Link>& GetLinks();\n\n\n\n // Add a ModuleNode to the network with a unique_ptr to an fl::Module.\n\n // Network will take ownership of the fl::Module pointer.\n\n // Returns a pointer to the Node if successful. Otherwise, returns nullptr.\n\n std::shared_ptr<Node> AddNode(NodeType type,\n\n std::unique_ptr<fl::Module> module);\n\n\n\n // Add a DataNode to the network with a unique_ptr to an fl::Dataset.\n\n // Only adds a new node if no DataNode exists in the network.\n\n // If a DataNode already exists, returns a pointer to that node.\n\n std::shared_ptr<Node> AddNode(std::unique_ptr<fl::Dataset> train_set,\n", "file_path": "include/neurons/network.h", "rank": 27, "score": 59858.01691064415 }, { "content": "namespace neurons::utilities {\n\n\n\n// Returns whether node IDs and link IDs are all unique\n\n// and link input and outputs correspond to nodes in the passed NodeDeque.\n\nbool NodesAndLinksConsistent(const NodeDeque& nodes,\n\n const std::deque<Link>& links);\n\n\n\n// Returns a NodeDeque with nodes sorted topologically, i.e.\n\n// for every pair of distinct nodes a and b, if a serves as the input for\n\n// b, then a will appear before b in the returned NodeDeque.\n\n// Nodes that belong to directed cycles will have arbitrary relative ordering.\n\nNodeDeque TopologicalSort(const NodeDeque& nodes,\n\n const std::deque<Link>& links);\n\n\n\n// Returns whether the graph constructed by the passed links contains\n\n// a directed cycle. Note: a directed cycle, as used here, must have > 1 nodes.\n\nbool ContainsDirectedCycle(const NodeDeque& nodes,\n\n const std::deque<Link>& links);\n\n\n\n// Returns the number of connected components in the graph.\n\nsize_t CountConnectedComponents(const NodeDeque& nodes,\n\n const std::deque<Link>& links);\n\n\n\n// Returns whether every node that requires an input has an input link.\n\nbool AreNodeInputsSatisfied(const NodeDeque& nodes,\n\n const std::deque<Link>& links);\n\n\n\n// Returns whether every node that provides an output has an output link.\n\nbool AreNodeOutputsSatisfied(const NodeDeque& nodes,\n\n const std::deque<Link>& links);\n\n\n", "file_path": "include/neurons/utilities.h", "rank": 28, "score": 58475.98635111017 }, { "content": "namespace neurons::spawner {\n\n\n\n// Spawn an MNIST DataNode in the passed network with the\n\n// passed data directory and batch size. Returns true on success.\n\nbool SpawnMnistDataNode(neurons::Network& network,\n\n const std::string& data_directory, dim_t batch_size);\n\n\n\n// Spawn a Node of the passed Node type. Returns true if successful. Freezes\n\n// editor when called, unfreezes editor once action is completed.\n\nbool SpawnModuleNode(neurons::Network& network, neurons::NodeType type,\n\n bool& freeze_editor);\n\n\n", "file_path": "apps/node_creator.h", "rank": 29, "score": 57529.634308085566 }, { "content": "// A subclass of fl::Container generated by a neurons::Network\n\n// does not have an \"is-a\" relationship with fl::Container but rather an\n\n// \"implemented-in-terms-of\" relationship.\n\n// As fl::Container requires adding layers by fl::Module, whereas this requires\n\n// a Node wrapper and Links to indicate Node connections.\n\nclass NetworkContainer : private fl::Container {\n\n\n\n public:\n\n\n\n // Allow access to all methods from fl::Container except fl::Container::add\n\n using fl::Container::eval;\n\n using fl::Container::module;\n\n using fl::Container::modules;\n\n using fl::Container::param;\n\n using fl::Container::params;\n\n using fl::Container::setParams;\n\n using fl::Container::train;\n\n using fl::Container::zeroGrad;\n\n\n\n // Public constructor.\n\n // Checks if passed nodes and links constitute a valid model.\n\n // Graphs must have no directed cycles, only consist of one component,\n\n // and have node inputs and node outputs satisfied.\n\n NetworkContainer(NodeDeque& nodes, const std::deque<Link>& links);\n\n\n", "file_path": "include/neurons/network-container.h", "rank": 30, "score": 47903.02781863133 }, { "content": "namespace neurons::mnist_utilities {\n\n\n\n// MNIST Data loading functions below.\n\n// All functions from MNIST flashlight example:\n\n// https://github.com/facebookresearch/flashlight/blob/master/examples/Mnist.cpp\n\n// using the byte-form MNIST datasets: http://yann.lecun.com/exdb/mnist/\n\n\n\nconst int kTrainSize = 60000;\n\nconst int kValSize = 5000; /* Held-out from train. */\n\nconst int kTestSize = 10000;\n\nconst int kImDim = 28;\n\nconst int kPixelMax = 255;\n\nconst int kInputIdx = 0;\n\nconst int kTargetIdx = 1;\n\n\n\n// Load data from MNIST files from data_dir.\n\nstd::pair<af::array, af::array> load_dataset(const std::string& data_dir,\n\n bool test = false);\n\n\n\n// Return a pair of categorical cross entropy loss and\n\n// error for the model evaluated on the passed dataset.\n\nstd::pair<double, double> eval_loop(neurons::NetworkContainer& model,\n\n fl::Dataset& dataset);\n\n\n\n// Train the passed model with the passed data node with the optimizer\n\n// for the passed number of epochs. Uses categorical cross entropy loss and\n\n// writes model training log to output. Sets training to whether training\n\n// is still in progress (allows for checking in multi-threaded programs).\n\n// If training becomes false during run, it will stop the process.\n\n// Writes any exceptions that happens to exception_ptr.\n\nvoid train_model(neurons::NetworkContainer& model, neurons::DataNode& data,\n\n fl::FirstOrderOptimizer& optimizer, int epochs, std::ostream& output,\n\n bool& training, std::exception_ptr& exception_ptr);\n\n\n", "file_path": "include/mnist-utilities.h", "rank": 31, "score": 47895.82331698624 }, { "content": "// Copyright (c) 2020 Simon Liu. All rights reserved.\n\n\n\n#include <neurons/link.h>\n\n#include <stdexcept>\n\n\n\nnamespace neurons {\n\n\n\nsize_t Link::GetId() const {\n\n return id_;\n\n}\n\n\n\n} // namespace neurons\n", "file_path": "src/link.cc", "rank": 32, "score": 32438.441510390738 }, { "content": "class InteractiveNeurons : public cinder::app::App {\n\n public:\n\n InteractiveNeurons();\n\n void setup() override;\n\n void update() override;\n\n void draw() override;\n\n void quit() override;\n\n\n\n private:\n\n Network network_;\n\n // Whether node editor should be frozen\n\n bool freeze_editor_;\n\n // Whether model training is in progress\n\n bool training_;\n\n // Training future\n\n std::future<void> train_result_;\n\n // Training log\n\n std::stringstream log_;\n\n // Training exception pointer\n\n std::exception_ptr exception_ptr;\n\n const std::string kDataDirectory = getAssetPath(\"mnist\");\n\n};\n\n\n\n} // namespace neurons\n\n\n\n#endif // FINALPROJECT_APPS_INTERACTIVE_NEURONS_H_\n", "file_path": "apps/interactive_neurons.h", "rank": 33, "score": 32182.88675979975 }, { "content": "// Copyright (c) 2020 Simon Liu. All rights reserved.\n\n\n\n#ifndef FINALPROJECT_APPS_INTERACTIVE_NEURONS_H_\n\n#define FINALPROJECT_APPS_INTERACTIVE_NEURONS_H_\n\n\n\n#include <cinder/app/App.h>\n\n#include <future>\n\n#include <imgui_adapter/link-adapter.h>\n\n#include <imgui_adapter/node-adapter.h>\n\n#include <neurons/network.h>\n\n\n\nnamespace neurons {\n\n\n", "file_path": "apps/interactive_neurons.h", "rank": 34, "score": 30956.493568753798 }, { "content": "// Copyright (c) 2020 Simon Liu. All rights reserved.\n\n\n\n#include <neurons/node.h>\n\n\n\nnamespace neurons {\n\n\n\nsize_t Node::GetId() const {\n\n return id_;\n\n}\n\n\n\nNodeType Node::GetNodeType() const {\n\n return type_;\n\n}\n\n\n\n} // namespace neurons", "file_path": "src/node.cc", "rank": 35, "score": 30880.60716900273 }, { "content": "// Copyright (c) 2020 Simon Liu. All rights reserved.\n\n\n\n#include <neurons/link.h>\n\n#include <neurons/module-node.h>\n\n\n\n#include <catch2/catch.hpp>\n\n\n\n\n\n/*\n\n * Link(size_t id, Node& input, Node& output);\n\n */\n\n\n\nTEST_CASE(\"Link: Constructor\", \"[Link][Constructor]\") {\n\n auto input_module = fl::Conv2D(1, 1, 1, 1, 1, 1, 1, 1);\n\n auto input_node = std::make_shared<neurons::ModuleNode>(\n\n neurons::ModuleNode(1,neurons::NodeType::Conv2D,\n\n std::make_unique<fl::Conv2D>(input_module)));\n\n auto output_module = fl::Conv2D(1, 1, 1, 1, 1, 1, 1, 1);\n\n auto output_node = std::make_shared<neurons::ModuleNode>(\n\n neurons::ModuleNode(1,neurons::NodeType::Conv2D,\n\n std::make_unique<fl::Conv2D>(output_module)));\n\n\n\n auto link = neurons::Link(3, input_node, output_node);\n\n REQUIRE(link.GetId() == 3);\n\n REQUIRE(link.input_ == input_node);\n\n REQUIRE(link.output_ == output_node);\n\n}\n\n\n", "file_path": "tests/test-link.cc", "rank": 36, "score": 30817.116655048856 }, { "content": "// Copyright (c) 2020 Simon Liu. All rights reserved.\n\n\n\n#include \"imgui_adapter/link-adapter.h\"\n\n\n\n#include \"imgui_adapter/node-adapter.h\"\n\n\n\nnamespace neurons::adapter {\n\n\n\nLinkAdapter::LinkAdapter(Link& link) {\n\n link_ = &link;\n\n\n\n id_ = kIdMultiplier * link.GetId();\n\n // will throw exception if output_ or input_ is nullptr\n\n end_id_ = kIdMultiplier * link.output_->GetId() + 1;\n\n start_id_ = kIdMultiplier * link.input_->GetId() + 2;\n\n}\n\n\n\nstd::vector<LinkAdapter> BuildLinkAdapters(std::deque<Link>& links) {\n\n auto adapters = std::vector<LinkAdapter>();\n\n adapters.reserve(links.size());\n", "file_path": "src/link-adapter.cc", "rank": 37, "score": 30815.75641839436 }, { "content": " for (auto& link : links) {\n\n adapters.emplace_back(link);\n\n }\n\n return adapters;\n\n}\n\n\n\nLinkAdapter* FindOwnerLink(std::vector<LinkAdapter>& links, size_t id) {\n\n for (auto& link : links) {\n\n if (link.id_ == id) {\n\n return &link;\n\n }\n\n }\n\n return nullptr;\n\n}\n\n\n\n} // namespace neurons::adapter", "file_path": "src/link-adapter.cc", "rank": 38, "score": 30813.398850389633 }, { "content": "// Copyright (c) 2020 Simon Liu. All rights reserved.\n\n\n\n#include \"interactive_neurons.h\"\n\n\n\n#include <cinder/CinderImGui.h>\n\n#include <cinder/gl/wrapper.h>\n\n#include <imnodes.h>\n\n#include <thread>\n\n\n\n#include \"imgui_adapter/link-adapter.h\"\n\n#include \"imgui_adapter/node-adapter.h\"\n\n#include \"mnist-utilities.h\"\n\n#include \"neurons/network-container.h\"\n\n#include \"node_creator.h\"\n\n\n\nnamespace neurons {\n\n\n\nusing cinder::app::KeyEvent;\n\nusing cinder::app::MouseEvent;\n\n\n", "file_path": "apps/interactive_neurons.cc", "rank": 39, "score": 29410.514159812825 }, { "content": "using neurons::adapter::NodeAdapter;\n\nusing neurons::adapter::LinkAdapter;\n\nusing neurons::Network;\n\nusing neurons::Link;\n\n\n\nInteractiveNeurons::InteractiveNeurons() {\n\n network_ = Network();\n\n freeze_editor_ = false;\n\n training_ = false;\n\n\n\n dim_t kBatchSize = 64;\n\n spawner::SpawnMnistDataNode(network_, kDataDirectory, kBatchSize);\n\n}\n\n\n\nvoid InteractiveNeurons::setup() {\n\n ImGui::Initialize(ImGui::Options());\n\n imnodes::Initialize();\n\n}\n\n\n\nvoid InteractiveNeurons::update() { }\n", "file_path": "apps/interactive_neurons.cc", "rank": 40, "score": 29405.251535129897 }, { "content": " network.AddLink(start->node_, end->node_);\n\n}\n\n\n\n// Handle Link deletion\n\nvoid HandleLinkDeletion(std::vector<LinkAdapter>& links, Network& network) {\n\n // See if any links are selected\n\n const size_t num_links_selected = imnodes::NumSelectedLinks();\n\n\n\n if (num_links_selected > 0 &&\n\n ImGui::IsKeyReleased(ImGui::GetIO().KeyMap[ImGuiKey_Backspace])) {\n\n std::vector<int> selected_links;\n\n selected_links.resize(num_links_selected);\n\n // Load selected_nodes with IDs of selected nodes\n\n imnodes::GetSelectedLinks(selected_links.data());\n\n while(!selected_links.empty()) {\n\n auto adapter = neurons::adapter::FindOwnerLink(links,\n\n selected_links.back());\n\n selected_links.pop_back();\n\n // could occur if user selects node and then presses delete twice\n\n if (adapter == nullptr) {\n", "file_path": "apps/interactive_neurons.cc", "rank": 41, "score": 29404.746037153425 }, { "content": " continue;\n\n }\n\n network.DeleteLink(*adapter->link_);\n\n }\n\n }\n\n}\n\n\n\n// Handle Node deletion\n\nvoid HandleNodeDeletion(std::vector<NodeAdapter>& nodes, Network& network) {\n\n // See if any nodes are selected\n\n const size_t num_nodes_selected = imnodes::NumSelectedNodes();\n\n\n\n if (num_nodes_selected > 0 &&\n\n ImGui::IsKeyReleased(ImGui::GetIO().KeyMap[ImGuiKey_Backspace])) {\n\n std::vector<int> selected_nodes;\n\n selected_nodes.resize(num_nodes_selected);\n\n // Load selected_nodes with IDs of selected nodes\n\n imnodes::GetSelectedNodes(selected_nodes.data());\n\n while(!selected_nodes.empty()) {\n\n auto adapter = neurons::adapter::FindOwnerNode(nodes,\n", "file_path": "apps/interactive_neurons.cc", "rank": 42, "score": 29403.841883449182 }, { "content": " DrawNodes(nodes);\n\n\n\n // Draw Links\n\n auto links = adapter::BuildLinkAdapters(network_.GetLinks());\n\n for (const LinkAdapter& link : links) {\n\n imnodes::Link(link.id_, link.start_id_, link.end_id_);\n\n }\n\n\n\n HandleNodeCreation(network_, freeze_editor_);\n\n imnodes::EndNodeEditor();\n\n\n\n static std::shared_ptr<NetworkContainer> container;\n\n\n\n if (ImGui::BeginMenuBar()) {\n\n if (ImGui::BeginMenu(\"Model Actions\")) {\n\n if (!training_ && !freeze_editor_ && exception_ptr == nullptr &&\n\n ImGui::MenuItem(\"Train Model\")) {\n\n // this block will throw exceptions if model is invalid architecture\n\n try {\n\n container = std::make_shared<NetworkContainer>(\n", "file_path": "apps/interactive_neurons.cc", "rank": 43, "score": 29403.292604362352 }, { "content": " // loss nodes should not have an output pin\n\n if (!(type == CategoricalCrossEntropy || type == MeanSquaredError ||\n\n type == MeanAbsoluteError)) {\n\n imnodes::BeginOutputAttribute(node.output_id_);\n\n ImGui::Indent(50);\n\n ImGui::Text(\"Output\");\n\n imnodes::EndAttribute();\n\n }\n\n\n\n imnodes::EndNode();\n\n }\n\n}\n\n\n\n// Attempt to create a link between Nodes on the Network.\n\nvoid AttemptLink(std::vector<NodeAdapter>& nodes,\n\n std::vector<LinkAdapter>& links, Network& network,\n\n size_t start_id, size_t end_id) {\n\n\n\n NodeAdapter* start = adapter::FindPinOwner(nodes, start_id);\n\n NodeAdapter* end = adapter::FindPinOwner(nodes, end_id);\n", "file_path": "apps/interactive_neurons.cc", "rank": 44, "score": 29403.091903796514 }, { "content": " train_result_ =\n\n std::async(std::launch::async, mnist_utilities::train_model,\n\n std::ref(*container), std::ref(*network_.GetDataNode()),\n\n std::ref(*optim), epochs, std::ref(log_),\n\n std::ref(training_), std::ref(exception_ptr));\n\n }\n\n }\n\n\n\n if (!freeze_editor_ && !training_) {\n\n HandleNodeDeletion(nodes, network_);\n\n HandleLinkDeletion(links, network_);\n\n\n\n // See if any links were drawn\n\n int start_pin;\n\n int end_pin;\n\n if (imnodes::IsLinkCreated(&start_pin, &end_pin)) {\n\n AttemptLink(nodes, links, network_, start_pin, end_pin);\n\n }\n\n }\n\n\n", "file_path": "apps/interactive_neurons.cc", "rank": 45, "score": 29403.01916673295 }, { "content": " ImGui::End();\n\n\n\n // check training_thread for any exceptions\n\n if (exception_ptr != nullptr) {\n\n try {\n\n std::rethrow_exception(exception_ptr);\n\n } catch (const std::exception& exception) {\n\n log_ << exception.what() << std::endl;\n\n }\n\n exception_ptr = nullptr;\n\n // halt training in the event of an exception\n\n training_ = false;\n\n container = nullptr;\n\n }\n\n\n\n DrawLog(log_);\n\n}\n\n\n\nvoid InteractiveNeurons::quit() {\n\n imnodes::Shutdown();\n\n ImGui::DestroyContext();\n\n}\n\n\n\n} // namespace neurons\n", "file_path": "apps/interactive_neurons.cc", "rank": 46, "score": 29401.767345377164 }, { "content": " selected_nodes.back());\n\n selected_nodes.pop_back();\n\n // nullptr could occur if user selects node and then presses delete twice\n\n // do not allow deletion of Dataset node either\n\n if (adapter == nullptr || adapter->node_->GetNodeType() == Dataset) {\n\n continue;\n\n }\n\n network.DeleteNode(*adapter->node_);\n\n }\n\n }\n\n}\n\n\n\n// Handle node creation\n\nvoid HandleNodeCreation(Network& network, bool& freeze_editor) {\n\n // If a non-node/link area is right-clicked\n\n if (ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) &&\n\n !ImGui::IsAnyItemHovered() &&\n\n ImGui::IsMouseReleased(ImGuiMouseButton_Right)) {\n\n ImGui::OpenPopup(\"Add Node\");\n\n }\n", "file_path": "apps/interactive_neurons.cc", "rank": 47, "score": 29401.52892925423 }, { "content": " std::stringstream log_copy;\n\n log_copy << log.str();\n\n\n\n std::string line;\n\n while (std::getline(log_copy, line)) {\n\n ImGui::Text(\"%s\", line.c_str());\n\n }\n\n ImGui::EndChild();\n\n ImGui::End();\n\n}\n\n\n\nvoid InteractiveNeurons::draw() {\n\n cinder::gl::clear(cinder:: Color( 0, 0, 0 ) );\n\n\n\n static bool menu_bar_active = false;\n\n ImGui::Begin(\"Network Editor\", &menu_bar_active, ImGuiWindowFlags_MenuBar);\n\n imnodes::BeginNodeEditor();\n\n\n\n // Draw nodes\n\n auto nodes = adapter::BuildNodeAdapters(network_.GetNodes());\n", "file_path": "apps/interactive_neurons.cc", "rank": 48, "score": 29401.06380667794 }, { "content": "\n\n // nullptr safety, then check that the connection is between two diff. nodes\n\n if (start == nullptr || end == nullptr || start == end) {\n\n return;\n\n }\n\n\n\n // figure out the input and the output nodes\n\n if (start->output_id_ == start_id && end->input_id_ == end_id) {\n\n // connection dragged from output to input pin\n\n // do nothing\n\n } else if (start->input_id_ == start_id && end->output_id_ == end_id) {\n\n // connection dragged from input to output pin\n\n std::swap(start, end);\n\n } else {\n\n // pins are either both input or output pins\n\n // which we treat as an invalid connection\n\n return;\n\n }\n\n\n\n // attempt to add link\n", "file_path": "apps/interactive_neurons.cc", "rank": 49, "score": 29400.864876104657 }, { "content": "\n\n// Draw all the nodes on the imnodes NodeEditor.\n\nvoid DrawNodes(const std::vector<NodeAdapter>& nodes) {\n\n for (const NodeAdapter& node : nodes) {\n\n imnodes::BeginNode(node.id_);\n\n\n\n imnodes::BeginNodeTitleBar();\n\n auto test = node.node_->prettyString();\n\n ImGui::TextWrapped(\"%s\", node.node_->prettyString().c_str());\n\n imnodes::EndNodeTitleBar();\n\n\n\n NodeType type = node.node_->GetNodeType();\n\n\n\n // data nodes should not have an input pin\n\n if (type != Dataset) {\n\n imnodes::BeginInputAttribute(node.input_id_);\n\n ImGui::Text(\"Input\");\n\n imnodes::EndAttribute();\n\n }\n\n\n", "file_path": "apps/interactive_neurons.cc", "rank": 50, "score": 29400.226100692395 }, { "content": " }\n\n }\n\n ImGui::EndPopup();\n\n }\n\n\n\n if (spawn_node != Dummy) {\n\n node_created = spawner::SpawnModuleNode(\n\n network, spawn_node, freeze_editor);\n\n }\n\n\n\n // if Node Creator has relinquished control, reset the spawn node\n\n if (!freeze_editor) {\n\n spawn_node = Dummy;\n\n }\n\n\n\n if (node_created) {\n\n // set the position of the spawned node to the cursor position\n\n auto adapter = NodeAdapter(network.GetNodes().back());\n\n imnodes::SetNodeScreenSpacePos(adapter.id_, mouse_position);\n\n }\n", "file_path": "apps/interactive_neurons.cc", "rank": 51, "score": 29400.10945908854 }, { "content": " }\n\n\n\n // Loss nodes. Only show if no Loss node exists (short-circuit eval.)\n\n if (network.GetLossNode() == nullptr && ImGui::BeginMenu(\"Loss\")) {\n\n // MNIST dataset only allows use of CategoricalCrossEntropy loss\n\n const std::vector<NodeType> losses = {CategoricalCrossEntropy};\n\n for (auto loss : losses) {\n\n if (ImGui::MenuItem(NodeTypeToString(loss).c_str())) {\n\n spawn_node = loss;\n\n }\n\n }\n\n ImGui::EndMenu();\n\n }\n\n\n\n // Every other Node type\n\n const std::vector<NodeType> types =\n\n {BatchNorm, LayerNorm, Dropout, View, Conv2D, Pool2D, Linear};\n\n for (auto type : types) {\n\n if (ImGui::MenuItem(NodeTypeToString(type).c_str())) {\n\n spawn_node = type;\n", "file_path": "apps/interactive_neurons.cc", "rank": 52, "score": 29399.89979259863 }, { "content": "\n\n static ImVec2 mouse_position;\n\n bool node_created = false;\n\n static NodeType spawn_node = Dummy;\n\n\n\n if (ImGui::BeginPopup(\"Add Node\")) {\n\n // record mouse position on right click\n\n mouse_position = ImGui::GetMousePosOnOpeningCurrentPopup();\n\n\n\n // Activation nodes\n\n if (ImGui::BeginMenu(\"Activation\")) {\n\n const std::vector<NodeType> activations =\n\n {Sigmoid, Tanh, HardTanh, ReLU, LeakyReLU, ELU,\n\n ThresholdReLU, GatedLinearUnit, LogSoftmax, Log};\n\n for (auto activation : activations) {\n\n if (ImGui::MenuItem(NodeTypeToString(activation).c_str())) {\n\n spawn_node = activation;\n\n }\n\n }\n\n ImGui::EndMenu();\n", "file_path": "apps/interactive_neurons.cc", "rank": 53, "score": 29399.75603597698 }, { "content": " NetworkContainer(network_.GetNodes(), network_.GetLinks()));\n\n } catch (std::exception& exception) {\n\n exception_ptr = std::current_exception();\n\n }\n\n }\n\n if (training_ && !freeze_editor_ && ImGui::MenuItem(\"Stop Training\")) {\n\n training_ = false;\n\n }\n\n ImGui::EndMenu();\n\n }\n\n ImGui::EndMenuBar();\n\n }\n\n\n\n if (!training_ && container != nullptr && exception_ptr == nullptr) {\n\n int epochs;\n\n std::shared_ptr<fl::FirstOrderOptimizer> optim;\n\n if (GetTrainConfiguration(container, freeze_editor_, optim, epochs)) {\n\n // use multi-threading to allow Cinder to run while training\n\n // train_model has a void return type, but store value so that\n\n // it operates as an asynchronous thread otherwise it will block main\n", "file_path": "apps/interactive_neurons.cc", "rank": 54, "score": 29399.70712630614 }, { "content": "}\n\n\n\n// Modifies the passed shared_ptr<fl::FirstOrderOptimizer> and epochs\n\n// with the configuration. Returns true if modification successful.\n\n// Prints any errors/exceptions to output.\n\nbool GetTrainConfiguration(std::shared_ptr<NetworkContainer>& container,\n\n bool& freeze_editor, std::shared_ptr<fl::FirstOrderOptimizer>& optim,\n\n int& epochs) {\n\n\n\n freeze_editor = true;\n\n ImGui::OpenPopup(\"Train Model\");\n\n\n\n bool configured = false;\n\n\n\n if (ImGui::BeginPopupModal(\"Train Model\")) {\n\n static int config_epochs;\n\n ImGui::Text(\"Training Epochs:\");\n\n ImGui::InputInt(\"##Epochs\", &config_epochs);\n\n\n\n static std::string optimizer_str;\n", "file_path": "apps/interactive_neurons.cc", "rank": 55, "score": 29396.91731411473 }, { "content": "\n\n if (optim_valid) {\n\n if (optimizer_str == \"AdadeltaOptimizer\") {\n\n optimizer = std::make_shared<fl::AdadeltaOptimizer>(\n\n fl::AdadeltaOptimizer(container->params(),\n\n args[0], args[1], args[2], args[3]));\n\n } else {\n\n optimizer = std::make_shared<fl::RMSPropOptimizer>(\n\n fl::RMSPropOptimizer(container->params(),\n\n args[0], args[1], args[2], args[3]));\n\n }\n\n }\n\n }\n\n\n\n if (optimizer_str == \"AdagradOptimizer\") {\n\n static float args[3]; // must be static to be preserved between draws\n\n const std::string labels[] =\n\n {\"Learning Rate\", \"Epsilon\", \"Weight Decay\"};\n\n\n\n for (size_t i = 0; i < 3; ++i) {\n", "file_path": "apps/interactive_neurons.cc", "rank": 56, "score": 29396.91731411473 }, { "content": " std::string optim_options[] = {\"AdadeltaOptimizer\", \"AdagradOptimizer\",\n\n \"AdamOptimizer\", \"AMSgradOptimizer\",\n\n \"NovogradOptimizer\", \"RMSPropOptimizer\",\n\n \"SGDOptimizer\"};\n\n\n\n // Get the Optimizer from a drop-down selection\n\n // derived from github.com/ocornut/imgui/issues/1658\n\n ImGui::Text(\"Optimizer:\");\n\n if (ImGui::BeginCombo(\"##Optimizer\", optimizer_str.data())) {\n\n for (const auto & option : optim_options) {\n\n bool is_selected = (optimizer_str == option);\n\n if (ImGui::Selectable(option.c_str(), is_selected)) {\n\n optimizer_str = option;\n\n }\n\n if (is_selected) {\n\n // sets the initial focus of the list when opened\n\n ImGui::SetItemDefaultFocus();\n\n }\n\n }\n\n ImGui::EndCombo();\n", "file_path": "apps/interactive_neurons.cc", "rank": 57, "score": 29396.91731411473 }, { "content": " ImGui::Text(\"%s\", labels[i].c_str());\n\n std::string label = \"##\" + labels[i]; // ## makes invis. label\n\n ImGui::InputFloat(label.c_str(), &args[i]);\n\n }\n\n\n\n optim_valid = args[0] > 0 && args[1] > 0 && args[2] >= 0;\n\n\n\n if (optim_valid) {\n\n optimizer = std::make_shared<fl::AdagradOptimizer>(\n\n fl::AdagradOptimizer(container->params(),\n\n args[0], args[1], args[2]));\n\n }\n\n }\n\n\n\n if (optimizer_str == \"AdamOptimizer\" ||\n\n optimizer_str == \"AMSgradOptimizer\" ||\n\n optimizer_str == \"NovogradOptimizer\") {\n\n static float args[5]; // must be static to be preserved between draws\n\n const std::string labels[] =\n\n {\"Learning Rate\", \"Beta1\", \"Beta2\", \"Epsilon\", \"Weight Decay\"};\n", "file_path": "apps/interactive_neurons.cc", "rank": 58, "score": 29396.91731411473 }, { "content": " if (optim_valid && config_epochs > 0) {\n\n ImGui::CloseCurrentPopup();\n\n freeze_editor = false;\n\n\n\n // set the values for caller to have access\n\n epochs = config_epochs;\n\n optim = optimizer;\n\n\n\n configured = true;\n\n }\n\n }\n\n ImGui::EndPopup();\n\n }\n\n return configured;\n\n}\n\n\n\nvoid DrawLog(const std::stringstream& log) {\n\n ImGui::Begin(\"Training Log\");\n\n ImGui::BeginChild(\"Scrolling\");\n\n // make a copy of log_ so we can read the log without erasing it\n", "file_path": "apps/interactive_neurons.cc", "rank": 59, "score": 29396.91731411473 }, { "content": " ImGui::Text(\"%s\", labels[3].c_str());\n\n ImGui::Checkbox((\"##\" + labels[3]).c_str(), &use_nesterov);\n\n\n\n optim_valid = args[0] > 0 && args[1] > 0 && args[2] >= 0;\n\n\n\n if (optim_valid) {\n\n optimizer = std::make_shared<fl::SGDOptimizer>(\n\n fl::SGDOptimizer(container->params(),args[0],\n\n args[1], args[2], use_nesterov));\n\n }\n\n }\n\n\n\n if (ImGui::Button(\"Cancel\")) {\n\n ImGui::CloseCurrentPopup();\n\n // Clear the container\n\n container = nullptr;\n\n freeze_editor = false;\n\n }\n\n\n\n if (ImGui::Button(\"Train\")) {\n", "file_path": "apps/interactive_neurons.cc", "rank": 60, "score": 29396.91731411473 }, { "content": " optimizer = std::make_shared<fl::NovogradOptimizer>(\n\n fl::NovogradOptimizer(container->params(),args[0],\n\n args[1], args[2], args[3], args[4]));\n\n\n\n }\n\n }\n\n }\n\n\n\n if (optimizer_str == \"SGDOptimizer\") {\n\n static float args[3]; // must be static to be preserved between draws\n\n static bool use_nesterov;\n\n const std::string labels[] =\n\n {\"Learning Rate\", \"Momentum\", \"Weight Decay\", \"Use Nesterov\"};\n\n\n\n for (size_t i = 0; i < 3; ++i) {\n\n ImGui::Text(\"%s\", labels[i].c_str());\n\n std::string label = \"##\" + labels[i]; // ## makes invis. label\n\n ImGui::InputFloat(label.c_str(), &args[i]);\n\n }\n\n\n", "file_path": "apps/interactive_neurons.cc", "rank": 61, "score": 29396.91731411473 }, { "content": "\n\n for (size_t i = 0; i < 5; ++i) {\n\n ImGui::Text(\"%s\", labels[i].c_str());\n\n std::string label = \"##\" + labels[i]; // ## makes invis. label\n\n ImGui::InputFloat(label.c_str(), &args[i]);\n\n }\n\n\n\n optim_valid = args[0] > 0 && args[1] > 0 && args[2] > 0 && args[3] > 0 &&\n\n args[4] >= 0;\n\n\n\n if (optim_valid) {\n\n if (optimizer_str == \"AdamOptimizer\") {\n\n optimizer = std::make_shared<fl::AdamOptimizer>(\n\n fl::AdamOptimizer(container->params(),args[0],\n\n args[1], args[2], args[3], args[4]));\n\n } else if (optimizer_str == \"AMSgradOptimizer\") {\n\n optimizer = std::make_shared<fl::AMSgradOptimizer>(\n\n fl::AMSgradOptimizer(container->params(),args[0],\n\n args[1], args[2], args[3], args[4]));\n\n } else {\n", "file_path": "apps/interactive_neurons.cc", "rank": 62, "score": 29396.91731411473 }, { "content": " }\n\n\n\n static std::shared_ptr<fl::FirstOrderOptimizer> optimizer;\n\n\n\n static bool optim_valid = false;\n\n\n\n // Load rest of required arguments based on selected optimizer\n\n if (optimizer_str == \"AdadeltaOptimizer\" ||\n\n optimizer_str == \"RMSPropOptimizer\") {\n\n static float args[4]; // must be static to be preserved between draws\n\n const std::string labels[] =\n\n {\"Learning Rate\", \"Rho\", \"Epsilon\", \"Weight Decay\"};\n\n\n\n for (size_t i = 0; i < 4; ++i) {\n\n ImGui::Text(\"%s\", labels[i].c_str());\n\n std::string label = \"##\" + labels[i]; // ## makes invis. label\n\n ImGui::InputFloat(label.c_str(), &args[i]);\n\n }\n\n\n\n optim_valid = args[0] > 0 && args[1] > 0 && args[2] > 0 && args[3] >= 0;\n", "file_path": "apps/interactive_neurons.cc", "rank": 63, "score": 29396.91731411473 }, { "content": "// Copyright (c) 2020 Simon Liu. All rights reserved.\n\n\n\n#include \"imgui_adapter/link-adapter.h\"\n\n\n\n#include \"imgui_adapter/node-adapter.h\"\n\n#include <catch2/catch.hpp>\n\n\n\n/*\n\n * LinkAdapter::LinkAdapter(Link& link);\n\n */\n\n\n\nTEST_CASE(\"LinkAdapter: Constructor\", \"[LinkAdapter][Constructor]\") {\n\n\n\n const size_t input_id = 1;\n\n const size_t output_id = 2;\n\n const size_t link_id = 3;\n\n\n\n auto input_module = fl::Conv2D(1, 1, 1, 1, 1, 1, 1, 1);\n\n auto input_node = std::make_shared<neurons::ModuleNode>(\n\n neurons::ModuleNode(input_id, neurons::NodeType::Conv2D,\n", "file_path": "tests/test-link-adapter.cc", "rank": 64, "score": 29351.434319995762 }, { "content": " neurons::ModuleNode(input_id, neurons::NodeType::Conv2D,\n\n std::make_unique<fl::Conv2D>(input_module)));\n\n auto output_module = fl::Conv2D(1, 1, 1, 1, 1, 1, 1, 1);\n\n auto output_node = std::make_shared<neurons::ModuleNode>(\n\n neurons::ModuleNode(output_id, neurons::NodeType::Conv2D,\n\n std::make_unique<fl::Conv2D>(output_module)));\n\n\n\n auto link = neurons::Link(link_id, input_node, output_node);\n\n auto link_reverse = neurons::Link(reverse_link_id, output_node, input_node);\n\n\n\n std::deque<neurons::Link> links = {link, link_reverse};\n\n auto link_adapters = neurons::adapter::BuildLinkAdapters(links);\n\n REQUIRE(link_adapters.size() == 2);\n\n\n\n REQUIRE(link_adapters.at(0).link_ == &links.at(0));\n\n\n\n REQUIRE(link_adapters.at(0).id_ ==\n\n link_id * neurons::adapter::kIdMultiplier);\n\n REQUIRE(link_adapters.at(0).start_id_ ==\n\n input_id * neurons::adapter::kIdMultiplier + 2);\n", "file_path": "tests/test-link-adapter.cc", "rank": 65, "score": 29349.087461221596 }, { "content": " const size_t input_id = 1;\n\n const size_t output_id = 2;\n\n const size_t link_id = 3;\n\n const size_t reverse_link_id = 4;\n\n\n\n auto input_module = fl::Conv2D(1, 1, 1, 1, 1, 1, 1, 1);\n\n auto input_node = std::make_shared<neurons::ModuleNode>(\n\n neurons::ModuleNode(input_id, neurons::NodeType::Conv2D,\n\n std::make_unique<fl::Conv2D>(input_module)));\n\n auto output_module = fl::Conv2D(1, 1, 1, 1, 1, 1, 1, 1);\n\n auto output_node = std::make_shared<neurons::ModuleNode>(\n\n neurons::ModuleNode(output_id, neurons::NodeType::Conv2D,\n\n std::make_unique<fl::Conv2D>(output_module)));\n\n\n\n auto link = neurons::Link(link_id, input_node, output_node);\n\n auto link_reverse = neurons::Link(reverse_link_id, output_node, input_node);\n\n\n\n std::deque<neurons::Link> links = {link, link_reverse};\n\n auto link_adapters = neurons::adapter::BuildLinkAdapters(links);\n\n\n", "file_path": "tests/test-link-adapter.cc", "rank": 66, "score": 29349.010137590933 }, { "content": " std::make_unique<fl::Conv2D>(input_module)));\n\n auto output_module = fl::Conv2D(1, 1, 1, 1, 1, 1, 1, 1);\n\n auto output_node = std::make_shared<neurons::ModuleNode>(\n\n neurons::ModuleNode(output_id, neurons::NodeType::Conv2D,\n\n std::make_unique<fl::Conv2D>(output_module)));\n\n\n\n auto link = neurons::Link(link_id, input_node, output_node);\n\n\n\n auto link_adapter = neurons::adapter::LinkAdapter(link);\n\n\n\n REQUIRE(link_adapter.link_ == &link);\n\n\n\n REQUIRE(link_adapter.id_ ==\n\n link_id * neurons::adapter::kIdMultiplier);\n\n REQUIRE(link_adapter.start_id_ ==\n\n input_id * neurons::adapter::kIdMultiplier + 2);\n\n REQUIRE(link_adapter.end_id_ ==\n\n output_id * neurons::adapter::kIdMultiplier + 1);\n\n}\n\n\n", "file_path": "tests/test-link-adapter.cc", "rank": 67, "score": 29348.69740088885 }, { "content": "/*\n\n * std::vector<LinkAdapter> BuildLinkAdapters(std::deque<Link>& links);\n\n */\n\n\n\nTEST_CASE(\"LinkAdapter: BuildLinkAdapters\",\n\n \"[LinkAdapter][BuildLinkAdapters]\") {\n\n\n\n SECTION(\"No Links\") {\n\n std::deque<neurons::Link> links;\n\n REQUIRE(neurons::adapter::BuildLinkAdapters(links).empty());\n\n }\n\n\n\n SECTION(\"Multiple Links\") {\n\n const size_t input_id = 1;\n\n const size_t output_id = 2;\n\n const size_t link_id = 3;\n\n const size_t reverse_link_id = 4;\n\n\n\n auto input_module = fl::Conv2D(1, 1, 1, 1, 1, 1, 1, 1);\n\n auto input_node = std::make_shared<neurons::ModuleNode>(\n", "file_path": "tests/test-link-adapter.cc", "rank": 68, "score": 29347.610864366903 }, { "content": " REQUIRE(link_adapters.at(0).end_id_ ==\n\n output_id * neurons::adapter::kIdMultiplier + 1);\n\n\n\n REQUIRE(link_adapters.at(1).link_ == &links.at(1));\n\n\n\n REQUIRE(link_adapters.at(1).id_ ==\n\n reverse_link_id * neurons::adapter::kIdMultiplier);\n\n REQUIRE(link_adapters.at(1).start_id_ ==\n\n output_id * neurons::adapter::kIdMultiplier + 2);\n\n REQUIRE(link_adapters.at(1).end_id_ ==\n\n input_id * neurons::adapter::kIdMultiplier + 1);\n\n }\n\n}\n\n\n\n/*\n\n * LinkAdapter* FindOwnerLink(std::vector<LinkAdapter>& links, size_t id)\n\n */\n\n\n\nTEST_CASE(\"LinkAdapter: FindOwnerLink\", \"[LinkAdapter][FindOwnerLink]\") {\n\n\n", "file_path": "tests/test-link-adapter.cc", "rank": 69, "score": 29345.909310791147 }, { "content": " SECTION(\"Link is present\") {\n\n const auto result = neurons::adapter::FindOwnerLink(link_adapters,\n\n link_adapters.at(0).id_);\n\n REQUIRE(result == &link_adapters.at(0));\n\n }\n\n\n\n SECTION(\"Link is not represent\") {\n\n const auto result = neurons::adapter::FindOwnerLink(link_adapters,\n\n 83472);\n\n REQUIRE(result == nullptr);\n\n }\n\n}", "file_path": "tests/test-link-adapter.cc", "rank": 70, "score": 29345.738489499417 }, { "content": "// Copyright (c) 2020 Simon Liu. All rights reserved.\n\n\n\n#include <cinder/CinderImGui.h>\n\n#include <imnodes.h>\n\n\n\n#include \"mnist-utilities.h\"\n\n#include \"node_creator.h\"\n\n\n\nusing neurons::Node;\n\n\n\nnamespace neurons::spawner {\n\n\n\nbool SpawnMnistDataNode(neurons::Network& network,\n\n const std::string& data_directory, dim_t batch_size) {\n\n // Initialize DataNode of the Network\n\n af::array train_x;\n\n af::array train_y;\n\n af::array test_x;\n\n af::array test_y;\n\n // train_x and train_y are passed as references\n", "file_path": "apps/node_creator.cc", "rank": 71, "score": 29336.83501149069 }, { "content": "// Copyright (c) 2020 Simon Liu. All rights reserved.\n\n\n\n#include <flashlight/flashlight.h>\n\n#include <neurons/module-node.h>\n\n\n\nnamespace neurons {\n\n\n\nstd::string NodeTypeToString(NodeType type) {\n\n switch (type) {\n\n case Dummy:\n\n return \"Dummy\";\n\n case Conv2D:\n\n return \"Conv2D\";\n\n case Linear:\n\n return \"Linear\";\n\n case Sigmoid:\n\n return \"Sigmoid\";\n\n case Tanh:\n\n return \"Tanh\";\n\n case HardTanh:\n", "file_path": "src/module-node.cc", "rank": 72, "score": 29336.604521185152 }, { "content": "// Copyright (c) 2020 Simon Liu. All rights reserved.\n\n\n\n#include <flashlight/flashlight.h>\n\n#include <neurons/data-node.h>\n\n\n\nnamespace neurons {\n\n\n\nDataNode::DataNode(size_t id, std::unique_ptr<fl::Dataset> train_set,\n\n std::unique_ptr<fl::Dataset> valid_set,\n\n std::unique_ptr<fl::Dataset> test_set) : Node(id, Dataset) {\n\n train_dataset_ = std::move(train_set);\n\n valid_dataset_ = std::move(valid_set);\n\n test_dataset_ = std::move(test_set);\n\n}\n\n\n\n// Pretty string\n\nstd::string DataNode::prettyString() const {\n\n return \"Dataset\";\n\n}\n\n\n\n} // namespace neurons", "file_path": "src/data-node.cc", "rank": 73, "score": 29336.325969275753 }, { "content": "// Copyright (c) 2020 Simon Liu. All rights reserved.\n\n\n\n#include \"imgui_adapter/node-adapter.h\"\n\n\n\nnamespace neurons::adapter {\n\n\n\nNodeAdapter::NodeAdapter(const std::shared_ptr<Node>& node) {\n\n node_ = node;\n\n\n\n id_ = kIdMultiplier * node->GetId();\n\n input_id_ = kIdMultiplier * node->GetId() + 1;\n\n output_id_ = kIdMultiplier * node->GetId() + 2;\n\n}\n\n\n\nstd::vector<NodeAdapter> BuildNodeAdapters(NodeDeque& nodes) {\n\n auto adapters = std::vector<NodeAdapter>();\n\n adapters.reserve(nodes.size());\n\n for (auto& node : nodes) {\n\n adapters.emplace_back(node);\n\n }\n", "file_path": "src/node-adapter.cc", "rank": 74, "score": 29334.17271361096 }, { "content": " return adapters;\n\n}\n\n\n\nNodeAdapter* FindOwnerNode(std::vector<NodeAdapter>& nodes, size_t id) {\n\n for (auto& node : nodes) {\n\n if (node.id_ == id) {\n\n return &node;\n\n }\n\n }\n\n return nullptr;\n\n}\n\n\n\nNodeAdapter* FindPinOwner(std::vector<NodeAdapter>& nodes, size_t id) {\n\n for (auto& node : nodes) {\n\n if (node.input_id_ == id || node.output_id_ == id) {\n\n return &node;\n\n }\n\n }\n\n return nullptr;\n\n}\n\n\n\n} // namespace neurons::adapter", "file_path": "src/node-adapter.cc", "rank": 75, "score": 29333.021146450614 }, { "content": "}\n\n\n\nvoid ModuleNode::train() {\n\n this->module_->train();\n\n}\n\n\n\nvoid ModuleNode::eval() {\n\n this->module_->eval();\n\n}\n\n\n\nvoid ModuleNode::setParams(const fl::Variable& var, int position) {\n\n this->module_->setParams(var, position);\n\n}\n\n\n\nstd::vector<fl::Variable> ModuleNode::forward(\n\n const std::vector<fl::Variable>& inputs) {\n\n return this->module_->forward(inputs);\n\n}\n\n\n\nstd::string ModuleNode::prettyString() const {\n\n return this->module_->prettyString();\n\n}\n\n\n\n} // namespace neurons\n", "file_path": "src/module-node.cc", "rank": 76, "score": 29332.685178204858 }, { "content": " case CategoricalCrossEntropy:\n\n case MeanAbsoluteError:\n\n case MeanSquaredError:\n\n return SpawnLossNode(network, type);\n\n case BatchNorm:\n\n return SpawnBatchNormNode(network, freeze_editor);\n\n case LayerNorm:\n\n return SpawnLayerNormNode(network, freeze_editor);\n\n case Dropout:\n\n return SpawnDropoutNode(network, freeze_editor);\n\n case View:\n\n return SpawnViewNode(network, freeze_editor);\n\n case Conv2D:\n\n return SpawnConv2DNode(network, freeze_editor);\n\n case Pool2D:\n\n return SpawnPool2DNode(network, freeze_editor);\n\n case Linear:\n\n return SpawnLinearNode(network, freeze_editor);\n\n default:\n\n return false;\n\n }\n\n}\n\n\n\n} // namespace neurons::spawner", "file_path": "apps/node_creator.cc", "rank": 77, "score": 29331.56570485588 }, { "content": " case LogSoftmax:\n\n module = std::make_unique<fl::LogSoftmax>(fl::LogSoftmax());\n\n break;\n\n case Log:\n\n module = std::make_unique<fl::Log>(fl::Log());\n\n break;\n\n default:\n\n // if no activation node is selected\n\n return false;\n\n }\n\n\n\n network.AddNode(type, std::move(module));\n\n return true;\n\n}\n\n\n\n// Spawn an Loss Node of the passed NodeType. If type does not\n\n// correspond to a valid loss node type, do nothing. Returns true\n\n// if successful.\n\nbool SpawnLossNode(neurons::Network& network, neurons::NodeType type) {\n\n std::unique_ptr<fl::BinaryModule> module;\n", "file_path": "apps/node_creator.cc", "rank": 78, "score": 29330.922408390907 }, { "content": " if (args_valid) {\n\n network.AddNode(Linear,std::make_unique<fl::Linear>(\n\n fl::Linear(n_args[0], n_args[1], bias)));\n\n node_created = true;\n\n freeze_editor = false;\n\n ImGui::CloseCurrentPopup();\n\n }\n\n }\n\n ImGui::EndPopup();\n\n }\n\n return node_created;\n\n}\n\n\n\nbool SpawnModuleNode(neurons::Network& network, neurons::NodeType type,\n\n bool& freeze_editor) {\n\n const std::vector config_types =\n\n {BatchNorm, LayerNorm, Dropout, View, Conv2D, Pool2D, Linear};\n\n\n\n // check if node requires a config pop up window.\n\n if (std::find(config_types.begin(), config_types.end(), type) !=\n", "file_path": "apps/node_creator.cc", "rank": 79, "score": 29330.630270415077 }, { "content": " std::vector<af::array>{valid_x, valid_y}), batch_size);\n\n auto test_set = fl::BatchDataset(std::make_shared<fl::TensorDataset>(\n\n std::vector<af::array>{test_x, test_y}), batch_size);\n\n\n\n network.AddNode(std::make_unique<fl::BatchDataset>(train_set),\n\n std::make_unique<fl::BatchDataset>(valid_set),\n\n std::make_unique<fl::BatchDataset>(test_set));\n\n return true;\n\n}\n\n\n\n// Spawn an Activation Node of the passed NodeType. If type does not\n\n// correspond to a valid activation node type, do nothing. Returns true\n\n// if successful.\n\nbool SpawnActivationNode(neurons::Network& network, neurons::NodeType type) {\n\n std::unique_ptr<fl::Module> module;\n\n switch (type) {\n\n case Sigmoid:\n\n module = std::make_unique<fl::Sigmoid>(fl::Sigmoid());\n\n break;\n\n case Tanh:\n", "file_path": "apps/node_creator.cc", "rank": 80, "score": 29330.255659425413 }, { "content": " network.AddNode(View, std::make_unique<fl::View>(\n\n fl::View(af::dim4(\n\n dims[0], dims[1], dims[2], dims[3]))));\n\n node_created = true;\n\n freeze_editor = false;\n\n ImGui::CloseCurrentPopup();\n\n }\n\n }\n\n ImGui::EndPopup();\n\n }\n\n return node_created;\n\n}\n\n\n\n// Starts pop-up configuration for a new Conv2D Node.\n\n// Returns true if spawning was successful. Sets freeze_editor to whether\n\n// method is currently controlling the GUI.\n\nbool SpawnConv2DNode(neurons::Network& network, bool& freeze_editor) {\n\n bool node_created = false;\n\n\n\n ImGui::OpenPopup(\"Conv2D\");\n", "file_path": "apps/node_creator.cc", "rank": 81, "score": 29329.912826103024 }, { "content": " n_args[7], n_args[8],n_args[9], bias)));\n\n node_created = true;\n\n freeze_editor = false;\n\n ImGui::CloseCurrentPopup();\n\n }\n\n }\n\n ImGui::EndPopup();\n\n }\n\n return node_created;\n\n}\n\n\n\n// Starts pop-up configuration for a new Pool2D Node.\n\n// Returns true if spawning was successful. Sets freeze_editor to whether\n\n// method is currently controlling the GUI.\n\nbool SpawnPool2DNode(neurons::Network& network, bool& freeze_editor) {\n\n bool node_created = false;\n\n\n\n ImGui::OpenPopup(\"Pool2D\");\n\n if (ImGui::BeginPopupModal(\"Pool2D\")) {\n\n\n", "file_path": "apps/node_creator.cc", "rank": 82, "score": 29329.888864192 }, { "content": " n_args[3],n_args[4], n_args[5], pooling)));\n\n node_created = true;\n\n freeze_editor = false;\n\n ImGui::CloseCurrentPopup();\n\n }\n\n }\n\n ImGui::EndPopup();\n\n }\n\n return node_created;\n\n}\n\n\n\n// Starts pop-up configuration for a new Linear Node.\n\n// Returns true if spawning was successful. Sets freeze_editor to whether\n\n// method is currently controlling the GUI.\n\nbool SpawnLinearNode(neurons::Network& network, bool& freeze_editor) {\n\n bool node_created = false;\n\n\n\n ImGui::OpenPopup(\"Linear\");\n\n if (ImGui::BeginPopupModal(\"Linear\")) {\n\n static int n_args[2]; // must be static to be preserved between draws\n", "file_path": "apps/node_creator.cc", "rank": 83, "score": 29329.829049073658 }, { "content": " network.AddNode(BatchNorm, std::make_unique<fl::BatchNorm>(\n\n fl::BatchNorm(int_args[0], int_args[1], double_args[0],\n\n double_args[1], bool_args[0], bool_args[1])));\n\n node_created = true;\n\n freeze_editor = false;\n\n ImGui::CloseCurrentPopup();\n\n }\n\n }\n\n ImGui::EndPopup();\n\n }\n\n return node_created;\n\n}\n\n\n\n// Starts pop-up configuration for a new LayerNorm Node.\n\n// Returns true if spawning was successful. Sets freeze_editor to whether\n\n// method is currently controlling the GUI.\n\nbool SpawnLayerNormNode(neurons::Network& network, bool& freeze_editor) {\n\n bool node_created = false;\n\n\n\n ImGui::OpenPopup(\"LayerNorm\");\n", "file_path": "apps/node_creator.cc", "rank": 84, "score": 29329.754467331113 }, { "content": "bool SpawnViewNode(neurons::Network& network, bool& freeze_editor) {\n\n bool node_created = false;\n\n\n\n ImGui::OpenPopup(\"View\");\n\n if (ImGui::BeginPopupModal(\"View\")) {\n\n static int dims[4];\n\n const std::string labels[] = {\"Dimension 1\", \"Dimension 2\",\n\n \"Dimension 3\", \"Dimenison 4\"};\n\n for (size_t i = 0; i < 4; ++i ) {\n\n ImGui::Text(\"%s\", labels[i].c_str());\n\n std::string label = \"##\" + labels[i]; // ## makes invis. label\n\n ImGui::InputInt(label.c_str(), &dims[i]);\n\n }\n\n\n\n if (ImGui::Button(\"Cancel\")) {\n\n freeze_editor = false;\n\n ImGui::CloseCurrentPopup();\n\n }\n\n\n\n ImGui::SameLine();\n", "file_path": "apps/node_creator.cc", "rank": 85, "score": 29329.126186548863 }, { "content": "\n\n// Starts pop-up configuration for a new BatchNorm Node.\n\n// Returns true if spawning was successful. Sets freeze_editor to whether\n\n// method is currently controlling the GUI.\n\nbool SpawnBatchNormNode(neurons::Network& network, bool& freeze_editor) {\n\n bool node_created = false;\n\n\n\n ImGui::OpenPopup(\"BatchNorm\");\n\n if (ImGui::BeginPopupModal(\"BatchNorm\")) {\n\n static int int_args[2]; // must be static to be preserved between draws\n\n static double double_args[2];\n\n static bool bool_args[2];\n\n const std::string labels[] = {\"Feature Axis\", \"Feature Size\",\n\n \"Momentum\", \"Epsilon\", \"Affine\",\n\n \"Track Stats\"};\n\n for (size_t i = 0; i < 6; ++i) {\n\n ImGui::Text(\"%s\", labels[i].c_str());\n\n std::string label = \"##\" + labels[i]; // ## makes invis. label\n\n if (i < 2) {\n\n ImGui::InputInt(label.c_str(), &int_args[i]);\n", "file_path": "apps/node_creator.cc", "rank": 86, "score": 29328.988666601028 }, { "content": "// Returns true if spawning was successful. Sets freeze_editor to whether\n\n// method is currently controlling the GUI.\n\nbool SpawnDropoutNode(neurons::Network& network, bool& freeze_editor) {\n\n bool node_created = false;\n\n\n\n ImGui::OpenPopup(\"Dropout\");\n\n if (ImGui::BeginPopupModal(\"Dropout\")) {\n\n static double ratio; // must be static to be preserved between draws\n\n const std::string labels[] = {\"Dropout Ratio\"};\n\n\n\n ImGui::Text(\"%s\", labels[0].c_str());\n\n // ## makes invis. label\n\n ImGui::InputDouble((\"##\" + labels[0]).c_str(), &ratio);\n\n\n\n if (ImGui::Button(\"Cancel\")) {\n\n freeze_editor = false;\n\n ImGui::CloseCurrentPopup();\n\n }\n\n\n\n ImGui::SameLine();\n", "file_path": "apps/node_creator.cc", "rank": 87, "score": 29328.93505046364 }, { "content": " for (const auto & mode : modes) {\n\n bool is_selected = (pooling_mode == mode);\n\n if (ImGui::Selectable(mode.c_str(), is_selected)) {\n\n pooling_mode = mode;\n\n }\n\n if (is_selected) {\n\n // sets the initial focus of the list when opened\n\n ImGui::SetItemDefaultFocus();\n\n }\n\n }\n\n ImGui::EndCombo();\n\n }\n\n\n\n // translate pooling_mode string into PoolingMode\n\n fl::PoolingMode pooling;\n\n if (pooling_mode == \"MAX\") {\n\n pooling = fl::PoolingMode::MAX;\n\n } else if (pooling_mode == \"AVG_INCLUDE_POOLING\") {\n\n pooling = fl::PoolingMode::AVG_INCLUDE_PADDING;\n\n } else {\n", "file_path": "apps/node_creator.cc", "rank": 88, "score": 29328.518156366616 }, { "content": " if (ImGui::Button(\"Add Node\")) {\n\n // Check that arguments are valid\n\n bool args_valid = (ratio >= 0 && ratio < 1);\n\n\n\n if (args_valid) {\n\n network.AddNode(Dropout,std::make_unique<fl::Dropout>(\n\n fl::Dropout(ratio)));\n\n node_created = true;\n\n freeze_editor = false;\n\n ImGui::CloseCurrentPopup();\n\n }\n\n }\n\n ImGui::EndPopup();\n\n }\n\n return node_created;\n\n}\n\n\n\n// Starts pop-up configuration for a new View Node.\n\n// Returns true if spawning was successful. Sets freeze_editor to whether\n\n// method is currently controlling the GUI.\n", "file_path": "apps/node_creator.cc", "rank": 89, "score": 29328.387754230087 }, { "content": "\n\n ImGui::SameLine();\n\n if (ImGui::Button(\"Add Node\")) {\n\n // arguments valid if Feature Axis >= 0\n\n bool args_valid = (axis >= 0);\n\n\n\n if (args_valid) {\n\n network.AddNode(LayerNorm, std::make_unique<fl::LayerNorm>(\n\n fl::LayerNorm(axis, epsilon, affine, fl::kLnVariableAxisSize)));\n\n node_created = true;\n\n freeze_editor = false;\n\n ImGui::CloseCurrentPopup();\n\n }\n\n }\n\n ImGui::EndPopup();\n\n }\n\n return node_created;\n\n}\n\n\n\n// Starts pop-up configuration for a new Dropout Node.\n", "file_path": "apps/node_creator.cc", "rank": 90, "score": 29328.37911365178 }, { "content": " return \"View\";\n\n case LayerNorm:\n\n return \"LayerNorm\";\n\n case BatchNorm:\n\n return \"BatchNorm\";\n\n case CategoricalCrossEntropy:\n\n return \"CategoricalCrossEntropy\";\n\n case MeanAbsoluteError:\n\n return \"MeanAbsoluteError\";\n\n case MeanSquaredError:\n\n return \"MeanSquaredError\";\n\n default:\n\n throw std::exception();\n\n }\n\n}\n\n\n\nModuleNode::ModuleNode(size_t id, NodeType type,\n\n std::unique_ptr<fl::Module> module) :\n\n Node(id, type), Module(module->params()){\n\n module_ = std::move(module);\n", "file_path": "src/module-node.cc", "rank": 91, "score": 29328.30305470841 }, { "content": "\n\n switch (type) {\n\n case CategoricalCrossEntropy:\n\n module = std::make_unique<fl::CategoricalCrossEntropy>(\n\n fl::CategoricalCrossEntropy());\n\n break;\n\n case MeanAbsoluteError:\n\n module = std::make_unique<fl::MeanAbsoluteError>(fl::MeanAbsoluteError());\n\n break;\n\n case MeanSquaredError:\n\n module = std::make_unique<fl::MeanSquaredError>(fl::MeanSquaredError());\n\n break;\n\n default:\n\n // if no loss node is selected\n\n return false;\n\n }\n\n\n\n network.AddNode(type, std::move(module));\n\n return true;\n\n}\n", "file_path": "apps/node_creator.cc", "rank": 92, "score": 29327.715244722527 }, { "content": " ImGui::CloseCurrentPopup();\n\n }\n\n\n\n ImGui::SameLine();\n\n if (ImGui::Button(\"Add Node\")) {\n\n // Check that arguments are valid\n\n bool args_valid = true;\n\n for (size_t i = 0; i < 10; ++i) {\n\n // zero-padding can be >= -1, everything else must be positive.\n\n // zero-padding of -1 uses smallest possible padding such that\n\n // out_size = ceil(in_size / stride)\n\n if (!(n_args[i] > 0 || ((i == 6 || i == 7) && n_args[i] >= -1))) {\n\n args_valid = false;\n\n }\n\n }\n\n\n\n if (args_valid) {\n\n network.AddNode(Conv2D,std::make_unique<fl::Conv2D>(\n\n fl::Conv2D(n_args[0], n_args[1], n_args[2],\n\n n_args[3],n_args[4], n_args[5], n_args[6],\n", "file_path": "apps/node_creator.cc", "rank": 93, "score": 29327.632656617207 }, { "content": " pooling = fl::PoolingMode::AVG_EXCLUDE_PADDING;\n\n }\n\n\n\n if (ImGui::Button(\"Cancel\")) {\n\n freeze_editor = false;\n\n ImGui::CloseCurrentPopup();\n\n }\n\n\n\n ImGui::SameLine();\n\n if (ImGui::Button(\"Add Node\")) {\n\n // Check that arguments are valid\n\n // All fields must be greater than 0, except padding which must be >= -1\n\n // zero-padding of -1 uses smallest possible padding such that\n\n // out_size = ceil(in_size / stride)\n\n bool args_valid = n_args[0] > 0 && n_args[1] > 0 && n_args[2] > 0 &&\n\n n_args[3] > 0 && n_args[4] >= -1 && n_args[5] >= -1;\n\n\n\n if (args_valid) {\n\n network.AddNode(Pool2D, std::make_unique<fl::Pool2D>(\n\n fl::Pool2D(n_args[0], n_args[1], n_args[2],\n", "file_path": "apps/node_creator.cc", "rank": 94, "score": 29327.535758951806 }, { "content": " if (ImGui::Button(\"Add Node\")) {\n\n // Check that arguments are valid\n\n bool args_valid = true;\n\n\n\n // View must have either nonnegative or -1 arguments\n\n size_t num_negative_one = 0;\n\n for (int dim : dims) {\n\n if (dim == -1) {\n\n ++num_negative_one;\n\n } else if (dim < 0) {\n\n args_valid = false;\n\n }\n\n }\n\n\n\n // View can only have one -1 argument\n\n if (num_negative_one > 1) {\n\n args_valid = false;\n\n }\n\n\n\n if (args_valid) {\n", "file_path": "apps/node_creator.cc", "rank": 95, "score": 29327.27692714433 }, { "content": " static int n_args[6]; // must be static to be preserved between draws\n\n const std::string labels[] = {\n\n \"Pooling Window X-dim\", \"Pooling Window Y-dim\",\n\n \"Stride X-dim\", \"Stride Y-dim\",\n\n \"Zero-Padding X-dim\", \"Zero-Padding Y-dim\", \"Pooling Mode\"};\n\n\n\n static std::string pooling_mode;\n\n const std::string modes[] = {\"MAX\", \"AVG_INCLUDE_PADDING\",\n\n \"AVG_EXCLUDE_PADDING\"};\n\n\n\n for (size_t i = 0; i < 6; ++i) {\n\n ImGui::Text(\"%s\", labels[i].c_str());\n\n std::string label = \"##\" + labels[i]; // ## makes invis. label\n\n ImGui::InputInt(label.c_str(), &n_args[i]);\n\n }\n\n\n\n // Get the Pooling Mode from a dropdown selection\n\n // derived from github.com/ocornut/imgui/issues/1658\n\n ImGui::Text(\"%s\", labels[6].c_str());\n\n if (ImGui::BeginCombo((\"##\" + labels[6]).c_str(), pooling_mode.data())) {\n", "file_path": "apps/node_creator.cc", "rank": 96, "score": 29327.254395994245 }, { "content": " config_types.end()) {\n\n freeze_editor = true;\n\n\n\n // default window spawn size is too small for editing\n\n ImVec2 window_size = ImVec2(300, 300);\n\n ImGui::SetNextWindowContentSize(window_size);\n\n }\n\n\n\n switch (type) {\n\n case Sigmoid:\n\n case Tanh:\n\n case HardTanh:\n\n case ReLU:\n\n case LeakyReLU:\n\n case ELU:\n\n case ThresholdReLU:\n\n case GatedLinearUnit:\n\n case LogSoftmax:\n\n case Log:\n\n return SpawnActivationNode(network, type);\n", "file_path": "apps/node_creator.cc", "rank": 97, "score": 29327.06551448709 }, { "content": " } else if (i < 4) {\n\n // subtract 2 from index to account for separate array\n\n ImGui::InputDouble(label.c_str(), &double_args[i - 2]);\n\n } else {\n\n // subtract 4 from index to account for separate array\n\n ImGui::Checkbox(label.c_str(), &bool_args[i - 4]);\n\n }\n\n }\n\n\n\n if (ImGui::Button(\"Cancel\")) {\n\n freeze_editor = false;\n\n ImGui::CloseCurrentPopup();\n\n }\n\n\n\n ImGui::SameLine();\n\n if (ImGui::Button(\"Add Node\")) {\n\n // arguments valid if Feature Axis >= 0 and Feature Size > 0\n\n bool args_valid = (int_args[0] >= 0 && int_args[1] > 0);\n\n\n\n if (args_valid) {\n", "file_path": "apps/node_creator.cc", "rank": 98, "score": 29327.06551448709 }, { "content": " static bool bias;\n\n const std::string labels[] = {\"Input Size\", \"Output Size\"};\n\n for (size_t i = 0; i < 2; ++i) {\n\n ImGui::Text(\"%s\", labels[i].c_str());\n\n std::string label = \"##\" + labels[i]; // ## makes invis. label\n\n ImGui::InputInt(label.c_str(), &n_args[i]);\n\n }\n\n\n\n ImGui::Checkbox(\"Learnable Bias: \", &bias);\n\n\n\n if (ImGui::Button(\"Cancel\")) {\n\n freeze_editor = false;\n\n ImGui::CloseCurrentPopup();\n\n }\n\n\n\n ImGui::SameLine();\n\n if (ImGui::Button(\"Add Node\")) {\n\n // Check that arguments are valid\n\n bool args_valid = (n_args[0] > 0 && n_args[1] > 0);\n\n\n", "file_path": "apps/node_creator.cc", "rank": 99, "score": 29327.031893180832 } ]
C++
src/elements/areas/AreaProduction.cpp
FlorianEith/rcll_status_board
2358ca07d72ad090408c0810071b95c03416b02c
#include <AreaProduction.h> rcll_draw::AreaProduction::AreaProduction(){ hp_header = HeaderPanel("LOGISTICS LEAGUE", rcll_draw::NO_TEAM); thp_team_header_cyan = TeamHeaderPanel(); thp_team_header_magenta = TeamHeaderPanel(); vsp_gameinfo = VStatusPanel(rcll_draw::NO_TEAM); pi_productinfo_cyan = ProductInfo(rcll_draw::CYAN, 3); pi_productinfo_magenta = ProductInfo(rcll_draw::MAGENTA, 3); mip_machineinfo_cyan = MachineInfoProduction(rcll_draw::CYAN); mip_machineinfo_magenta = MachineInfoProduction(rcll_draw::MAGENTA); ri_robotinfo_cyan = RobotInfo(rcll_draw::CYAN); ri_robotinfo_magenta = RobotInfo(rcll_draw::MAGENTA); gf_gamefield = GameField(); blbl_text.setContent("The task for the robots is to produce products with the help of the machines."); blbl_text.setAlignment(rcll_draw::Alignment::CenterCenter); blbl_text.setBackgroundColor(rcll_draw::C_WHITE); blbl_text.setBorderColor(rcll_draw::C_WHITE); blbl_text.setFontSize(1.0); mip_machineinfo_cyan.setShortDisplay(true); mip_machineinfo_magenta.setShortDisplay(true); gf_gamefield.setRefBoxView(false); } rcll_draw::AreaProduction::~AreaProduction(){ } void rcll_draw::AreaProduction::setGeometry(int x, int y, int w, int h){ this->x = x; this->y = y; this->w = w; this->h = h; int cur_y = y; hp_header.setGeometry(x + (w - hp_header.getW(1.0)) / 2, cur_y, 1.0); thp_team_header_cyan.setGeometry(x, cur_y, 1.0); thp_team_header_magenta.setGeometry(x + w - thp_team_header_magenta.getW(1.0), cur_y, 1.0); cur_y += hp_header.getH(1.0) + gapsize; vsp_gameinfo.setGeometry(x + (w - vsp_gameinfo.getW(0.71)) / 2, cur_y, 0.71); cur_y += vsp_gameinfo.getH(0.71); pi_productinfo_cyan.setGeometry(x, cur_y - pi_productinfo_cyan.getH(0.65), 0.65); pi_productinfo_magenta.setGeometry(x + w - pi_productinfo_magenta.getW(0.65), cur_y - pi_productinfo_magenta.getH(0.65), 0.65); ri_robotinfo_cyan.setGeometry(x, cur_y - ri_robotinfo_cyan.getH(1.0), 1.0); ri_robotinfo_magenta.setGeometry(x + w - ri_robotinfo_magenta.getW(1.0), cur_y - ri_robotinfo_magenta.getH(1.0), 1.0); cur_y += gapsize; mip_machineinfo_cyan.setGeometry(x + gapsize, cur_y, 0.80); mip_machineinfo_magenta.setGeometry(x + w - mip_machineinfo_magenta.getW(0.80) - gapsize, cur_y, 0.80); gf_gamefield.setGeometry(x + (w - gf_gamefield.getW(0.60)) / 2, cur_y, 0.60); cur_y += gf_gamefield.getH(0.60) + gapsize / 3; blbl_text.setSize(w, h * 0.05); blbl_text.setPos(x, cur_y); } void rcll_draw::AreaProduction::setGameInfo(rcll_vis_msgs::GameInfo &gameinfo){ vsp_gameinfo.setContent(gameinfo); gf_gamefield.setPhase((rcll_draw::GamePhase)gameinfo.game_phase); thp_team_header_cyan.setTeam(gameinfo.team_name_cyan, rcll_draw::CYAN); thp_team_header_magenta.setTeam(gameinfo.team_name_magenta, rcll_draw::MAGENTA); } void rcll_draw::AreaProduction::setMachines(std::vector<rcll_vis_msgs::Machine> &machines){ mip_machineinfo_cyan.setMachines(machines); mip_machineinfo_magenta.setMachines(machines); gf_gamefield.setMachines(machines); } void rcll_draw::AreaProduction::setRobots(std::vector<rcll_vis_msgs::Robot> &robots){ ri_robotinfo_cyan.setRobots(robots); ri_robotinfo_magenta.setRobots(robots); gf_gamefield.setRobots(robots); } void rcll_draw::AreaProduction::setGameField(rcll_vis_msgs::SetGameField &setgamefield){ gf_gamefield.setGameField(setgamefield); } void rcll_draw::AreaProduction::setRefBoxView(bool refbox_view){ gf_gamefield.setRefBoxView(refbox_view); } void rcll_draw::AreaProduction::setProducts(std::vector<rcll_vis_msgs::Product> &products){ pi_productinfo_cyan.setProducts(products); pi_productinfo_magenta.setProducts(products); } void rcll_draw::AreaProduction::setPaging(double paging_time, double paging_wait_time, int shift_increase){ this->paging_time = paging_time; pi_productinfo_cyan.setPaging(paging_wait_time, shift_increase); pi_productinfo_magenta.setPaging(paging_wait_time, shift_increase); last_paging = ros::Time::now(); } void rcll_draw::AreaProduction::draw(cv::Mat &mat, bool show_element_borders){ hp_header.draw(mat, show_element_borders); thp_team_header_cyan.draw(mat, show_element_borders); thp_team_header_magenta.draw(mat, show_element_borders); vsp_gameinfo.draw(mat, show_element_borders); bool allow_paging_by_move = true; if (paging_count % 2 == 0){ pi_productinfo_cyan.draw(mat, show_element_borders); pi_productinfo_magenta.draw(mat, show_element_borders); allow_paging_by_move &= !pi_productinfo_cyan.move(); allow_paging_by_move &= !pi_productinfo_magenta.move(); } else { allow_paging_by_move = true; ri_robotinfo_cyan.draw(mat, show_element_borders); ri_robotinfo_magenta.draw(mat, show_element_borders); } if (allow_paging_by_move && (ros::Time::now() - last_paging).toSec() >= paging_time){ paging_count++; last_paging = ros::Time::now(); } mip_machineinfo_cyan.draw(mat, show_element_borders); mip_machineinfo_magenta.draw(mat, show_element_borders); gf_gamefield.draw(mat, show_element_borders); blbl_text.draw(mat); }
#include <AreaProduction.h> rcll_draw::AreaProduction::AreaProduction(){ hp_header = HeaderPanel("LOGISTICS LEAGUE", rcll_draw::NO_TEAM); thp_team_header_cyan = TeamHeaderPanel(); thp_team_header_magenta = TeamHeaderPanel(); vsp_gameinfo = VStatusPanel(rcll_draw::NO_TEAM); pi_productinfo_cyan = ProductInfo(rcll_draw::CYAN, 3); pi_productinfo_magenta = ProductInfo(rcll_draw::MAGENTA, 3); mip_machineinfo_cyan = MachineInfoProduction(rcll_draw::CYAN); mip_machineinfo_magenta = MachineInfoProduction(rcll_draw::MAGENTA); ri_robotinfo_cyan = RobotInfo(rcll_draw::CYAN); ri_robotinfo_magenta = RobotInfo(rcll_draw::MAGENTA); gf_gamefield = GameField(); blbl_text.setContent("The task for the robots is to produce products with the help of the machines."); blbl_text.setAlignment(rcll_draw::Alignment::CenterCenter); blbl_text.setBackgroundColor(rcll_draw::C_WHITE); blbl_text.setBorderColor(rcll_draw::C_WHITE); blbl_text.setFontSize(1.0); mip_machineinfo_cyan.setShortDisplay(true); mip_machineinfo_magenta.setShortDisplay(true); gf_gamefield.setRefBoxView(false); } rcll_draw::AreaProduction::~AreaProduction(){ } void rcll_draw::AreaProduction::setGeometry(int x, int y, int w, int h){ this->x = x; this->y = y; this->w = w; this->h = h; int cur_y = y; hp_header.setGeometry(x + (w - hp_header.getW(1.0)) / 2, cur_y, 1.0); thp_team_header_cyan.setGeometry(x, cur_y, 1.0); thp_team_header_magenta.setGeometry(x + w - thp_team_header_magenta.getW(1.0), cur_y, 1.0); cur_y += hp_header.getH(1.0) + gapsize; vsp_gameinfo.setGeometry(x + (w - vsp_gameinfo.getW(0.71)) / 2, cur_y, 0.71); cur_y += vsp_gameinfo.getH(0.71); pi_productinfo_cyan.setGeometry(x, cur_y - pi_productinfo_cyan.getH(0.65), 0.65); pi_productinfo_magenta.setGeometry(x + w - pi_productinfo_magenta.getW(0.65), cur_y - pi_productinfo_magenta.getH(0.65), 0.65); ri_robotinfo_cyan.setGeometry(x, cur_y - ri_robotinfo_cyan.getH(1.0), 1.0); ri_robotinfo_magenta.setGeometry(x + w - ri_robotinfo_magenta.getW(1.0), cur_y - ri_robotinfo_magenta.getH(1.0), 1.0); cur_y += gapsize; mip_machineinfo_cyan.setGeometry(x + gapsize, cur_y, 0.80); mip_machineinfo_magenta.setGeometry(x + w - mip_machineinfo_magenta.getW(0.80) - gapsize, cur_y, 0.80); gf_gamefield.setGeometry(x + (w - gf_gamefield.getW(0.60)) / 2, cur_y, 0.60); cur_y += gf_gamefield.getH(0.60) + gapsize / 3; blbl_text.setSize(w, h * 0.05); blbl_text.setPos(x, cur_y); } void rcll_draw::AreaProduction::setGameInfo(rcll_vis_msgs::GameInfo &gameinfo){ vsp_gameinfo.setContent(gameinfo); gf_gamefield.setPhase((rcll_draw::GamePhase)gameinfo.game_phase); thp_team_header_cyan.setTeam(gameinfo.team_name_cyan, rcll_draw::CYAN); thp_team_header_magenta.setTeam(gameinfo.team_name_magenta, rcll_draw::MAGENTA); } void rcll_draw::AreaProduction::setMachines(std::vector<rcll_vis_msgs::Machine> &machines){ mip_machineinfo_cyan.setMachines(machines); mip_machineinfo_magenta.setMachines(machines); gf_gamefield.setMachines(machines); } void rcll_draw::AreaProduction::setRobots(std::vector<rcll_vis_msgs::Robot> &robots){ ri_robotinfo_cyan.setRobots(robots); ri_robotinfo_magenta.setRobots(robots); gf_gamefield.setRobots(robots); } void rcll_draw::AreaProduction::setGameField(rcll_vis_msgs::SetGameField &setgamefield){ gf_gamefield.setGameField(setgamefield); } void rcll_draw::AreaProduction::setRefBoxView(bool refbox_view){ gf_gamefield.setRefBoxView(refbox_view); } void rcll_draw::AreaProduction::setProducts(std::vector<rcll_vis_msgs::Product> &products){ pi_productinfo_cyan.setProducts(products); pi_productinfo_magenta.setProducts(products); } void rcll_draw::AreaProduction::setPaging(double paging_time, double paging_wait_time, int shift_increase){ this->paging_time = paging_time; pi_productinfo_cyan.setPaging(paging_wait_time, shift_increase); pi_productinfo_magenta.setPaging(paging_wait_time, shift_increase); last_paging = ros::Time::now(); } void rcll_draw::AreaProduction::draw(cv::Mat &mat, bool show_element_borders){ hp_header.draw(mat, show_element_borders); thp_team_header_cyan.draw(mat, show_element_borders); thp_team_header_magenta.draw(mat, show_element_borders); vsp_gameinfo.draw(mat, show_element_borders); bool allow_paging_by_move = true; if (paging_count % 2 == 0){ pi_productinfo_cyan.draw(mat, show_element_borders); pi_productinfo_magenta.draw(mat, show_element_borders
, show_element_borders); mip_machineinfo_magenta.draw(mat, show_element_borders); gf_gamefield.draw(mat, show_element_borders); blbl_text.draw(mat); }
); allow_paging_by_move &= !pi_productinfo_cyan.move(); allow_paging_by_move &= !pi_productinfo_magenta.move(); } else { allow_paging_by_move = true; ri_robotinfo_cyan.draw(mat, show_element_borders); ri_robotinfo_magenta.draw(mat, show_element_borders); } if (allow_paging_by_move && (ros::Time::now() - last_paging).toSec() >= paging_time){ paging_count++; last_paging = ros::Time::now(); } mip_machineinfo_cyan.draw(mat
function_block-random_span
[ { "content": " class MachineInfoProduction {\n\n public:\n\n MachineInfoProduction();\n\n MachineInfoProduction(Team team);\n\n ~MachineInfoProduction();\n\n\n\n void setShortDisplay(bool short_display);\n\n void setGeometry(int x, int y, double scale);\n\n\n\n int getW(double scale = 1.0);\n\n int getH(double scale = 1.0);\n\n\n\n void setMachines(std::vector<rcll_vis_msgs::Machine> &machines);\n\n void draw(cv::Mat &mat, bool show_element_border = false);\n\n\n\n private:\n\n int x, y = 0;\n\n int w = 980, h = 345;\n\n int gapsize = 20;\n\n double scale = 1.0;\n", "file_path": "include/elements/components/MachineInfoProduction.h", "rank": 0, "score": 101352.42867967843 }, { "content": " class MachineLabelProduction {\n\n public:\n\n MachineLabelProduction(rcll_draw::Team team);\n\n ~MachineLabelProduction();\n\n\n\n void setGeometry(int x, int y, int w, int h);\n\n void setMachine(rcll_vis_msgs::Machine &machine);\n\n void draw(cv::Mat &mat);\n\n\n\n private:\n\n BoxLabel blbl_border;\n\n BoxLabel blbl_machinename;\n\n Color lamp1_color;\n\n Color lamp2_color;\n\n BoxLabel blbl_lamp1;\n\n BoxLabel blbl_lamp2;\n\n bool flashing;\n\n };\n\n}\n\n\n\n#endif\n", "file_path": "include/elements/subcomponents/MachineLabelProduction.h", "rank": 1, "score": 101352.42867967844 }, { "content": "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\nSOFTWARE.\n\n*/\n\n\n\n#ifndef RCLL_MACHINE_INFO_PRODUCTION_H\n\n#define RCLL_MACHINE_INFO_PRODUCTION_H\n\n\n\n#include <util.h>\n\n#include <BoxLabel.h>\n\n#include <MachineLabelProduction.h>\n\n\n\n#include <rcll_vis_msgs/Machine.h>\n\n\n\nnamespace rcll_draw {\n\n\n", "file_path": "include/elements/components/MachineInfoProduction.h", "rank": 2, "score": 92317.11446137654 }, { "content": "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\nSOFTWARE.\n\n*/\n\n\n\n#ifndef RCLL_MACHINE_LABEL_PRODUCTION_H\n\n#define RCLL_MACHINE_LABEL_PRODUCTION_H\n\n\n\n#include <util.h>\n\n#include <BoxLabel.h>\n\n\n\n#include <rcll_vis_msgs/Machine.h>\n\n\n\nnamespace rcll_draw {\n", "file_path": "include/elements/subcomponents/MachineLabelProduction.h", "rank": 3, "score": 92316.52236897266 }, { "content": " cv::Mat origin;\n\n\n\n bool short_display = false;\n\n\n\n Team team;\n\n BoxLabel blbl_header;\n\n\n\n std::vector<std::string> keys = {\"BS\", \"DS\", \"SS\", \"CS1\", \"CS2\", \"RS1\", \"RS2\"};\n\n std::map<std::string, size_t> machine_map;\n\n std::vector<MachineLabelProduction> mlp_machines;\n\n };\n\n}\n\n\n\n#endif\n", "file_path": "include/elements/components/MachineInfoProduction.h", "rank": 4, "score": 92312.87899958182 }, { "content": "/*\n\nThe MIT License (MIT)\n\n\n\nCopyright (c) 2017-2018 Florian Eith <[email protected]>\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", "file_path": "include/elements/components/MachineInfoProduction.h", "rank": 5, "score": 92302.7866011431 }, { "content": "/*\n\nThe MIT License (MIT)\n\n\n\nCopyright (c) 2017-2018 Florian Eith <[email protected]>\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", "file_path": "include/elements/subcomponents/MachineLabelProduction.h", "rank": 6, "score": 92302.7866011431 }, { "content": " class RobotInfo {\n\n public:\n\n RobotInfo();\n\n RobotInfo(Team team);\n\n ~RobotInfo();\n\n\n\n void setGeometry(int x, int y, double scale);\n\n\n\n int getW(double scale = 1.0);\n\n int getH(double scale = 1.0);\n\n\n\n void setRobots(std::vector<rcll_vis_msgs::Robot> &robots);\n\n void draw(cv::Mat &mat, bool show_element_border = false);\n\n\n\n private:\n\n int x, y = 0;\n\n int w = 805, h = 345;\n\n int gapsize = 20;\n\n double scale = 1.0;\n\n cv::Mat origin;\n", "file_path": "include/elements/components/RobotInfo.h", "rank": 7, "score": 69059.64944967994 }, { "content": " class RobotLabel {\n\n public:\n\n RobotLabel();\n\n ~RobotLabel();\n\n\n\n void setGeometry(int x, int y, int w, int h);\n\n void setRobot(rcll_vis_msgs::Robot &robot);\n\n void draw(cv::Mat &mat);\n\n\n\n private:\n\n std::string key;\n\n\n\n BoxLabel blbl_name;\n\n MultilineBoxLabel mlblbl_activity;\n\n BoxLabel blbl_activetime;\n\n BoxLabel blbl_maintenance;\n\n };\n\n}\n\n\n\n#endif\n", "file_path": "include/elements/subcomponents/RobotLabel.h", "rank": 8, "score": 69059.64944967994 }, { "content": " class RobotMarker {\n\n public:\n\n RobotMarker();\n\n RobotMarker(Team team);\n\n ~RobotMarker();\n\n\n\n void setOrigin(int origin_x, int origin_y, int pixel_per_meter);\n\n void setRefBoxView(bool refbox_view);\n\n void setRobot(rcll_vis_msgs::Robot &robot);\n\n void draw(cv::Mat &mat);\n\n\n\n private:\n\n int pixel_per_meter = 10;\n\n int origin_x, origin_y = 0;\n\n\n\n rcll_vis_msgs::Robot robot;\n\n double diameter;\n\n bool pose_set = false;\n\n bool refbox_view;\n\n\n\n Circle crc_robot;\n\n Line ln_direction;\n\n BoxLabel blbl_id;\n\n Arrow arr_heading;\n\n };\n\n}\n\n\n\n#endif\n", "file_path": "include/elements/subcomponents/RobotMarker.h", "rank": 9, "score": 69059.64944967994 }, { "content": " class MachineMarker {\n\n public:\n\n MachineMarker();\n\n MachineMarker(Team team);\n\n ~MachineMarker();\n\n\n\n void setPhase(rcll_draw::GamePhase gamephase);\n\n void setOrigin(int origin_x, int origin_y, int pixel_per_meter);\n\n void setRefBoxView(bool refbox_view);\n\n void setMachine(rcll_vis_msgs::Machine &machine);\n\n void recalculate();\n\n void draw(cv::Mat &mat);\n\n\n\n\n\n private:\n\n int pixel_per_meter = 10;\n\n int origin_x, origin_y = 0;\n\n bool refbox_view;\n\n\n\n cv::Mat img;\n", "file_path": "include/elements/subcomponents/MachineMarker.h", "rank": 10, "score": 68565.4015728976 }, { "content": " class ProductLabel {\n\n public:\n\n ProductLabel();\n\n ~ProductLabel();\n\n\n\n void setGeometry(int x, int y);\n\n int getW();\n\n int getH();\n\n void setProduct(rcll_vis_msgs::Product &product, rcll_draw::Team team);\n\n cv::Mat createProductImage(ProductPlan plan);\n\n void draw(cv::Mat &mat);\n\n\n\n private:\n\n int x, y = 0;\n\n int w = 400, h = 540;\n\n cv::Mat origin;\n\n\n\n BoxLabel blbl_name;\n\n BoxLabel blbl_progress;\n\n BoxLabel blbl_deadline;\n\n BoxLabel blbl_points;\n\n Image img_product;\n\n std::vector<Image> img_step_progress;\n\n Image img_product_progress;\n\n };\n\n}\n\n\n\n#endif\n", "file_path": "include/elements/subcomponents/ProductLabel.h", "rank": 11, "score": 68313.10302118912 }, { "content": " class AreaProduction {\n\n public:\n\n AreaProduction();\n\n ~AreaProduction();\n\n\n\n void setGeometry(int x, int y, int w, int h);\n\n void setGameInfo(rcll_vis_msgs::GameInfo &gameinfo);\n\n void setMachines(std::vector<rcll_vis_msgs::Machine> &machines);\n\n void setRobots(std::vector<rcll_vis_msgs::Robot> &robots);\n\n void setGameField(rcll_vis_msgs::SetGameField &setgamefield);\n\n void setProducts(std::vector<rcll_vis_msgs::Product> &products);\n\n void setPaging(double paging_time, double paging_wait_time, int shift_increase);\n\n void setRefBoxView(bool refbox_view);\n\n void draw(cv::Mat &mat, bool show_element_borders = false);\n\n\n\n private:\n\n int x, y = 0;\n\n int w, h = 1;\n\n int gapsize = 40;\n\n\n", "file_path": "include/elements/areas/AreaProduction.h", "rank": 12, "score": 68313.10302118912 }, { "content": " class ProductInfo {\n\n public:\n\n ProductInfo();\n\n ProductInfo(rcll_draw::Team team, int displayed_products = 4);\n\n ~ProductInfo();\n\n\n\n void setGeometry(int x, int y, double scale);\n\n\n\n int getW(double scale = 1.0);\n\n int getH(double scale = 1.0);\n\n\n\n void setProducts(std::vector<rcll_vis_msgs::Product> &products);\n\n void setPaging(double paging_wait_time, int shift_increase);\n\n void prepare_draw();\n\n bool move();\n\n void draw(cv::Mat &mat, bool show_element_border = false);\n\n\n\n static void getKeys(std::map<std::string, rcll_draw::ProductLabel> &mapping, std::vector<std::string> &keys);\n\n\n\n private:\n", "file_path": "include/elements/components/ProductInfo.h", "rank": 13, "score": 68313.10302118912 }, { "content": " class HStatusPanel {\n\n public:\n\n HStatusPanel();\n\n ~HStatusPanel();\n\n\n\n void setGeometry(int x, int y, double scale);\n\n\n\n int getW(double scale = 1.0);\n\n int getH(double scale = 1.0);\n\n\n\n void setContent(rcll_vis_msgs::GameInfo &gameinfo);\n\n void draw(cv::Mat &mat, bool show_element_border = false);\n\n private:\n\n int x, y = 0;\n\n int w = 1087, h = 86;\n\n double scale = 1.0;\n\n cv::Mat origin;\n\n\n\n BoxLabel blbl_state_header;\n\n BoxLabel blbl_state_value;\n", "file_path": "include/elements/components/HStatusPanel.h", "rank": 14, "score": 64769.18002586933 }, { "content": "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\nSOFTWARE.\n\n*/\n\n\n\n#ifndef RCLL_ROBOT_INFO_H\n\n#define RCLL_ROBOT_INFO_H\n\n\n\n#include <util.h>\n\n#include <BoxLabel.h>\n\n#include <RobotLabel.h>\n\n\n\n#include <rcll_vis_msgs/Robots.h>\n\n\n\nnamespace rcll_draw {\n", "file_path": "include/elements/components/RobotInfo.h", "rank": 15, "score": 64689.21980453646 }, { "content": "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\nSOFTWARE.\n\n*/\n\n\n\n#ifndef RCLL_ROBOT_MARKER_H\n\n#define RCLL_ROBOT_MARKER_H\n\n\n\n#include <util.h>\n\n#include <Arrow.h>\n\n#include <Circle.h>\n\n#include <Line.h>\n\n#include <BoxLabel.h>\n\n\n\n#include <rcll_vis_msgs/Robot.h>\n\n\n\nnamespace rcll_draw {\n", "file_path": "include/elements/subcomponents/RobotMarker.h", "rank": 16, "score": 64689.09091085805 }, { "content": "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\nSOFTWARE.\n\n*/\n\n\n\n#ifndef RCLL_ROBOT_LABEL_H\n\n#define RCLL_ROBOT_LABEL_H\n\n\n\n#include <util.h>\n\n#include <BoxLabel.h>\n\n#include <MultilineBoxLabel.h>\n\n\n\n#include <rcll_vis_msgs/Robot.h>\n\n\n\nnamespace rcll_draw {\n", "file_path": "include/elements/subcomponents/RobotLabel.h", "rank": 17, "score": 64688.93126212883 }, { "content": "\n\n Team team;\n\n BoxLabel blbl_header;\n\n\n\n std::vector<std::string> keys = {\"R1\", \"R2\", \"R3\"};\n\n std::map<std::string, size_t> robot_map;\n\n std::vector<RobotLabel> rl_robots;\n\n };\n\n}\n\n\n\n#endif\n", "file_path": "include/elements/components/RobotInfo.h", "rank": 18, "score": 64680.158533703834 }, { "content": "/*\n\nThe MIT License (MIT)\n\n\n\nCopyright (c) 2017-2018 Florian Eith <[email protected]>\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", "file_path": "include/elements/components/RobotInfo.h", "rank": 19, "score": 64679.11669666547 }, { "content": "/*\n\nThe MIT License (MIT)\n\n\n\nCopyright (c) 2017-2018 Florian Eith <[email protected]>\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", "file_path": "include/elements/subcomponents/RobotMarker.h", "rank": 20, "score": 64679.11669666547 }, { "content": "/*\n\nThe MIT License (MIT)\n\n\n\nCopyright (c) 2017-2018 Florian Eith <[email protected]>\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", "file_path": "include/elements/subcomponents/RobotLabel.h", "rank": 21, "score": 64679.11669666547 }, { "content": " class RobotInfo;\n", "file_path": "include/llsf_communicator.h", "rank": 22, "score": 64675.440799365766 }, { "content": "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\nSOFTWARE.\n\n*/\n\n\n\n#ifndef RCLL_MACHINE_MARKER_H\n\n#define RCLL_MACHINE_MARKER_H\n\n\n\n#include <util.h>\n\n#include <BoxLabel.h>\n\n#include <Line.h>\n\n#include <Circle.h>\n\n\n\n#include <rcll_vis_msgs/Machine.h>\n\n\n\nnamespace rcll_draw {\n", "file_path": "include/elements/subcomponents/MachineMarker.h", "rank": 23, "score": 64282.466925126915 }, { "content": " rcll_vis_msgs::Machine machine;\n\n\n\n GamePhase gamephase;\n\n Team team;\n\n BoxLabel blbl_machine;\n\n Line ln_input;\n\n Circle crc_output;\n\n BoxLabel blbl_in;\n\n BoxLabel blbl_out;\n\n };\n\n}\n\n\n\n#endif\n", "file_path": "include/elements/subcomponents/MachineMarker.h", "rank": 24, "score": 64273.55946377381 }, { "content": "/*\n\nThe MIT License (MIT)\n\n\n\nCopyright (c) 2017-2018 Florian Eith <[email protected]>\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", "file_path": "include/elements/subcomponents/MachineMarker.h", "rank": 25, "score": 64272.6334479842 }, { "content": " class MachineInfo;\n", "file_path": "include/llsf_communicator.h", "rank": 26, "score": 64268.95755068449 }, { "content": " class MachineLabelExploration {\n\n public:\n\n MachineLabelExploration(rcll_draw::Team team);\n\n ~MachineLabelExploration();\n\n\n\n void setGeometry(int x, int y, int w, int h);\n\n void setShortDisplay(bool short_display);\n\n void setMachine(rcll_vis_msgs::Machine &machine);\n\n void setHeader(std::string status1, std::string status2);\n\n void draw(cv::Mat &mat);\n\n\n\n private:\n\n bool short_display = false;\n\n\n\n BoxLabel blbl_machinename;\n\n BoxLabel blbl_status1;\n\n BoxLabel blbl_status2;\n\n Image img_status1;\n\n Image img_status2;\n\n };\n\n}\n\n\n\n#endif\n", "file_path": "include/elements/subcomponents/MachineLabelExploration.h", "rank": 27, "score": 64087.96755326557 }, { "content": " class MachineInfoExploration {\n\n public:\n\n MachineInfoExploration();\n\n MachineInfoExploration(Team team);\n\n ~MachineInfoExploration();\n\n\n\n void setGeometry(int x, int y, double scale);\n\n\n\n int getW(double scale = 1.0);\n\n int getH(double scale = 1.0);\n\n\n\n void setShortDisplay(bool short_display);\n\n void setMachines(std::vector<rcll_vis_msgs::Machine> &machines);\n\n void draw(cv::Mat &mat, bool show_element_border = false);\n\n\n\n private:\n\n int x, y = 0;\n\n int w = 1000, h = 691;\n\n double scale = 1.0;\n\n cv::Mat origin;\n", "file_path": "include/elements/components/MachineInfoExploration.h", "rank": 28, "score": 64087.96755326557 }, { "content": "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\nSOFTWARE.\n\n*/\n\n\n\n#ifndef RCLL_AREA_PRODUCTION_H\n\n#define RCLL_AREA_PRODUCTION_H\n\n\n\n#include <util.h>\n\n\n\n#include <HeaderPanel.h>\n\n#include <TeamHeaderPanel.h>\n\n#include <VStatusPanel.h>\n\n#include <ProductInfo.h>\n\n#include <MachineInfoProduction.h>\n\n#include <RobotInfo.h>\n\n#include <GameField.h>\n\n\n\n#include <rcll_vis_msgs/GameInfo.h>\n\n#include <rcll_vis_msgs/Machine.h>\n\n#include <rcll_vis_msgs/Robot.h>\n\n#include <rcll_vis_msgs/Product.h>\n\n\n\nnamespace rcll_draw {\n", "file_path": "include/elements/areas/AreaProduction.h", "rank": 29, "score": 64081.795232216 }, { "content": " int x, y = 0;\n\n int w = 1640, h = 540;\n\n int w_product = 400;\n\n int gapsize = 20;\n\n double scale = 1.0;\n\n cv::Mat origin;\n\n cv::Mat canvas;\n\n cv::Mat crop;\n\n\n\n size_t displayed_products = 4;\n\n Team team;\n\n\n\n std::vector<std::string> keys;\n\n std::vector<std::string> display;\n\n std::map<std::string, ProductLabel> pls_products;\n\n\n\n int shift = 0;\n\n double paging_wait_time = 5.0;\n\n int shift_increase = 10;\n\n bool wait_active = false;\n\n ros::Time last_wait_begin;\n\n };\n\n}\n\n\n\n#endif\n", "file_path": "include/elements/components/ProductInfo.h", "rank": 30, "score": 64080.38217282043 }, { "content": " Team team;\n\n\n\n int paging_count = 0;\n\n double paging_time = 5.0;\n\n ros::Time last_paging;\n\n\n\n HeaderPanel hp_header;\n\n TeamHeaderPanel thp_team_header_cyan;\n\n TeamHeaderPanel thp_team_header_magenta;\n\n VStatusPanel vsp_gameinfo;\n\n ProductInfo pi_productinfo_cyan;\n\n ProductInfo pi_productinfo_magenta;\n\n MachineInfoProduction mip_machineinfo_cyan;\n\n MachineInfoProduction mip_machineinfo_magenta;\n\n RobotInfo ri_robotinfo_cyan;\n\n RobotInfo ri_robotinfo_magenta;\n\n GameField gf_gamefield;\n\n BoxLabel blbl_text;\n\n };\n\n}\n\n\n\n#endif\n", "file_path": "include/elements/areas/AreaProduction.h", "rank": 31, "score": 64079.99767894451 }, { "content": "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\nSOFTWARE.\n\n*/\n\n\n\n#ifndef RCLL_PRODUCT_LABEL_H\n\n#define RCLL_PRODUCT_LABEL_H\n\n\n\n#include <util.h>\n\n\n\n#include <rcll_vis_msgs/Product.h>\n\n\n\n#include <BoxLabel.h>\n\n#include <Image.h>\n\n\n\nnamespace rcll_draw {\n\n\n\n struct ProductPlan {\n\n int complexity; //0-3\n\n int base; // 1=RED, 2=BLACK, 3=SILVER\n\n int ring1; // 1=BLUE, 2=GREEN, 3=ORANGE, 4=YELLOW\n", "file_path": "include/elements/subcomponents/ProductLabel.h", "rank": 32, "score": 64078.76271976962 }, { "content": "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\nSOFTWARE.\n\n*/\n\n#ifndef RCLL_PRODUCT_INFO_H\n\n#define RCLL_PRODUCT_INFO_H\n\n\n\n#include <util.h>\n\n\n\n#include <rcll_vis_msgs/Product.h>\n\n\n\n#include <ProductLabel.h>\n\n\n\nnamespace rcll_draw {\n", "file_path": "include/elements/components/ProductInfo.h", "rank": 33, "score": 64075.07004232818 }, { "content": " int ring2; // 1=BLUE, 2=GREEN, 3=ORANGE, 4=YELLOW\n\n int ring3; // 1=BLUE, 2=GREEN, 3=ORANGE, 4=YELLOW\n\n int cap; // 1=BLACK, 2=GREY\n\n\n\n int status_product; // 0=not started, 1=construction, 2=delivery, 3=completed\n\n int status_base;\n\n int status_ring1;\n\n int status_ring2;\n\n int status_ring3;\n\n int status_cap;\n\n };\n\n\n\n struct ProductInformation {\n\n int product_id;\n\n int quantity_id;\n\n ProductPlan plan;\n\n double progress;\n\n int deadline;\n\n int points;\n\n int points_max;\n\n };\n\n\n", "file_path": "include/elements/subcomponents/ProductLabel.h", "rank": 34, "score": 64071.06397777983 }, { "content": "/*\n\nThe MIT License (MIT)\n\n\n\nCopyright (c) 2017-2018 Florian Eith <[email protected]>\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", "file_path": "include/elements/components/ProductInfo.h", "rank": 35, "score": 64065.13607722421 }, { "content": "/*\n\nThe MIT License (MIT)\n\n\n\nCopyright (c) 2017-2018 Florian Eith <[email protected]>\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", "file_path": "include/elements/areas/AreaProduction.h", "rank": 36, "score": 64065.13607722421 }, { "content": "/*\n\nThe MIT License (MIT)\n\n\n\nCopyright (c) 2017-2018 Florian Eith <[email protected]>\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", "file_path": "include/elements/subcomponents/ProductLabel.h", "rank": 37, "score": 64065.13607722421 }, { "content": " class AreaProductionTeam {\n\n public:\n\n AreaProductionTeam();\n\n AreaProductionTeam(Team team);\n\n ~AreaProductionTeam();\n\n\n\n void setGeometry(int x, int y, int w, int h, int gapsize);\n\n void setGameInfo(rcll_vis_msgs::GameInfo &gameinfo);\n\n void setMachines(std::vector<rcll_vis_msgs::Machine> &machines);\n\n void setRobots(std::vector<rcll_vis_msgs::Robot> &robots);\n\n void setProducts(std::vector<rcll_vis_msgs::Product> &products);\n\n void setPaging(double paging_wait_time, int shift_increase);\n\n void draw(cv::Mat &mat, bool show_element_borders = false);\n\n\n\n private:\n\n int x, y = 0;\n\n int w, h = 1;\n\n\n\n Team team;\n\n\n", "file_path": "include/elements/areas/AreaProductionTeam.h", "rank": 38, "score": 63849.4601781326 }, { "content": "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\nSOFTWARE.\n\n*/\n\n\n\n#ifndef RCLL_HSTATUS_PANEL_H\n\n#define RCLL_HSTATUS_PANEL_H\n\n\n\n#include <util.h>\n\n#include <BoxLabel.h>\n\n\n\n#include <rcll_vis_msgs/GameInfo.h>\n\n\n\nnamespace rcll_draw {\n\n\n", "file_path": "include/elements/components/HStatusPanel.h", "rank": 39, "score": 61925.866307105425 }, { "content": "/*\n\nThe MIT License (MIT)\n\n\n\nCopyright (c) 2017-2018 Florian Eith <[email protected]>\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", "file_path": "include/elements/components/HStatusPanel.h", "rank": 40, "score": 61920.80003654117 }, { "content": " BoxLabel blbl_phase_header;\n\n BoxLabel blbl_phase_value;\n\n BoxLabel blbl_time_header;\n\n BoxLabel blbl_time_value;\n\n BoxLabel blbl_score_header;\n\n BoxLabel blbl_score_value_cyan;\n\n BoxLabel blbl_score_value_mid;\n\n BoxLabel blbl_score_value_magenta;\n\n };\n\n}\n\n\n\n#endif\n", "file_path": "include/elements/components/HStatusPanel.h", "rank": 41, "score": 61917.12413924147 }, { "content": "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\nSOFTWARE.\n\n*/\n\n\n\n#ifndef RCLL_MACHINE_INFO_EXPLORATION_H\n\n#define RCLL_MACHINE_INFO_EXPLORATION_H\n\n\n\n#include <util.h>\n\n#include <BoxLabel.h>\n\n#include <MachineLabelExploration.h>\n\n\n\n#include <rcll_vis_msgs/Machine.h>\n\n\n\nnamespace rcll_draw {\n\n\n", "file_path": "include/elements/components/MachineInfoExploration.h", "rank": 42, "score": 61364.882640584045 }, { "content": "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\nSOFTWARE.\n\n*/\n\n\n\n#ifndef RCLL_MACHINE_LABEL_EXPLORATION_H\n\n#define RCLL_MACHINE_LABEL_EXPLORATION_H\n\n\n\n#include <util.h>\n\n#include <BoxLabel.h>\n\n#include <Image.h>\n\n\n\n#include <rcll_vis_msgs/Machine.h>\n\n\n\nnamespace rcll_draw {\n", "file_path": "include/elements/subcomponents/MachineLabelExploration.h", "rank": 43, "score": 61364.74461924704 }, { "content": "\n\n Team team;\n\n BoxLabel blbl_header1;\n\n BoxLabel blbl_header2;\n\n std::vector<std::string> keys = {\"H\", \"BS\", \"DS\", \"SS\", \"CS1\", \"CS2\", \"RS1\", \"RS2\"};\n\n std::map<std::string, size_t> machine_map;\n\n std::vector<MachineLabelExploration> mle_machines;\n\n };\n\n}\n\n\n\n#endif\n", "file_path": "include/elements/components/MachineInfoExploration.h", "rank": 44, "score": 61358.99149226846 }, { "content": "/*\n\nThe MIT License (MIT)\n\n\n\nCopyright (c) 2017-2018 Florian Eith <[email protected]>\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", "file_path": "include/elements/subcomponents/MachineLabelExploration.h", "rank": 45, "score": 61355.06055325635 }, { "content": "/*\n\nThe MIT License (MIT)\n\n\n\nCopyright (c) 2017-2018 Florian Eith <[email protected]>\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", "file_path": "include/elements/components/MachineInfoExploration.h", "rank": 46, "score": 61355.06055325635 }, { "content": "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\nSOFTWARE.\n\n*/\n\n\n\n#ifndef RCLL_AREA_PRODUCTION_TEAM_H\n\n#define RCLL_AREA_PRODUCTION_TEAM_H\n\n\n\n#include <util.h>\n\n\n\n#include <HeaderPanel.h>\n\n#include <VStatusPanel.h>\n\n#include <ProductInfo.h>\n\n#include <MachineInfoProduction.h>\n\n#include <RobotInfo.h>\n\n\n\n#include <rcll_vis_msgs/GameInfo.h>\n\n#include <rcll_vis_msgs/Machine.h>\n\n#include <rcll_vis_msgs/Robot.h>\n\n#include <rcll_vis_msgs/Product.h>\n\n\n\nnamespace rcll_draw {\n", "file_path": "include/elements/areas/AreaProductionTeam.h", "rank": 47, "score": 61173.86938473458 }, { "content": " HeaderPanel hp_header;\n\n VStatusPanel vsp_gameinfo;\n\n ProductInfo pi_productinfo;\n\n MachineInfoProduction mip_machineinfo;\n\n RobotInfo ri_robotinfo;\n\n\n\n\n\n };\n\n}\n\n\n\n#endif\n", "file_path": "include/elements/areas/AreaProductionTeam.h", "rank": 48, "score": 61168.40578924881 }, { "content": "/*\n\nThe MIT License (MIT)\n\n\n\nCopyright (c) 2017-2018 Florian Eith <[email protected]>\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", "file_path": "include/elements/areas/AreaProductionTeam.h", "rank": 49, "score": 61156.98279544372 }, { "content": " for (size_t i = 0; i < keys.size(); i++){\n\n mlp_machines[machine_map[keys[i]]].setGeometry(0, (i+1) * h / 8, w, h / 8);\n\n }\n\n }\n\n}\n\n\n\nvoid rcll_draw::MachineInfoProduction::setShortDisplay(bool short_display){\n\n this->short_display = short_display;\n\n\n\n if (short_display){\n\n w = 480;\n\n h = 552;\n\n origin = cv::Mat(h, w, CV_8UC4);\n\n }\n\n}\n\n\n\nint rcll_draw::MachineInfoProduction::getW(double scale){\n\n return (int)((double)w * scale);\n\n}\n\n\n", "file_path": "src/elements/components/MachineInfoProduction.cpp", "rank": 50, "score": 59421.23617358481 }, { "content": "int rcll_draw::MachineInfoProduction::getH(double scale){\n\n return (int)((double)h * scale);\n\n}\n\n\n\nvoid rcll_draw::MachineInfoProduction::setMachines(std::vector<rcll_vis_msgs::Machine> &machines){\n\n for (size_t i = 0; i < machines.size(); i++){\n\n if (team == (rcll_draw::Team)machines[i].team){\n\n mlp_machines[machine_map[machines[i].key]].setMachine(machines[i]);\n\n\n\n }\n\n }\n\n}\n\n\n\nvoid rcll_draw::MachineInfoProduction::draw(cv::Mat &mat, bool show_element_border){\n\n cv::rectangle(origin, cv::Point(0, 0), cv::Point (w-1, h-1), rcll_draw::getColor(rcll_draw::C_WHITE), CV_FILLED);\n\n blbl_header.draw(origin);\n\n for (size_t i = 0; i < keys.size(); i++){\n\n mlp_machines[machine_map[keys[i]]].draw(origin);\n\n }\n\n if (show_element_border){\n\n cv::rectangle(origin, cv::Point(0, 0), cv::Point (w-1, h-1), rcll_draw::getColor(rcll_draw::C_RED), 1);\n\n }\n\n rcll_draw::mergeImages(mat, origin, x, y, scale);\n\n}\n", "file_path": "src/elements/components/MachineInfoProduction.cpp", "rank": 51, "score": 59418.80209185329 }, { "content": "\n\n flashing = false;\n\n}\n\n\n\nrcll_draw::MachineLabelProduction::~MachineLabelProduction(){\n\n\n\n}\n\n\n\nvoid rcll_draw::MachineLabelProduction::setGeometry(int x, int y, int w, int h){\n\n blbl_machinename.setPos(x, y);\n\n blbl_lamp1.setPos(x + w * 0.7, y);\n\n blbl_lamp2.setPos(x + w * 0.7, y + h/2);\n\n blbl_border.setPos(x, y);\n\n\n\n blbl_machinename.setSize(w * 0.7, h);\n\n blbl_lamp1.setSize(w * 0.3, h/2);\n\n blbl_lamp2.setSize(w * 0.3, h/2);\n\n blbl_border.setSize(w, h);\n\n}\n\n\n", "file_path": "src/elements/subcomponents/MachineLabelProduction.cpp", "rank": 52, "score": 59412.61783773151 }, { "content": " blbl_header.setFrontColor(rcll_draw::C_CYAN_DARK);\n\n } else if (team == rcll_draw::MAGENTA){\n\n blbl_header.setFrontColor(rcll_draw::C_MAGENTA_DARK);\n\n } else {\n\n blbl_header.setFrontColor(rcll_draw::C_BLACK);\n\n }\n\n\n\n for (size_t i = 0; i < keys.size(); i++){\n\n mlp_machines.push_back(MachineLabelProduction(team));\n\n machine_map[keys[i]] = i;\n\n }\n\n this->team = team;\n\n}\n\n\n\nrcll_draw::MachineInfoProduction::~MachineInfoProduction(){\n\n\n\n}\n\n\n\nvoid rcll_draw::MachineInfoProduction::setGeometry(int x, int y, double scale){\n\n this->x = x;\n", "file_path": "src/elements/components/MachineInfoProduction.cpp", "rank": 53, "score": 59411.97663214845 }, { "content": "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\nSOFTWARE.\n\n*/\n\n\n\n#include <MachineInfoProduction.h>\n\n\n\n// MachineInfoProduction ####################################################################\n\n\n\nrcll_draw::MachineInfoProduction::MachineInfoProduction() : rcll_draw::MachineInfoProduction::MachineInfoProduction(rcll_draw::NO_TEAM){\n\n\n\n}\n\n\n\nrcll_draw::MachineInfoProduction::MachineInfoProduction(Team team){\n\n origin = cv::Mat(h, w, CV_8UC4);\n\n blbl_header.setAlignment(rcll_draw::CenterCenter);\n\n blbl_header.setBackgroundColor(rcll_draw::C_WHITE);\n\n blbl_header.setBorderColor(rcll_draw::C_WHITE);\n\n blbl_header.setFontSize(2.0);\n\n blbl_header.setContent(\"MACHINES\");\n\n if (team == rcll_draw::CYAN){\n", "file_path": "src/elements/components/MachineInfoProduction.cpp", "rank": 54, "score": 59411.24066612338 }, { "content": "void rcll_draw::MachineLabelProduction::setMachine(rcll_vis_msgs::Machine &machine){\n\n blbl_machinename.setContent(\" \" + machine.name_long + \" (\" + machine.name_short + \")\");\n\n\n\n flashing = false;\n\n if (machine.machine_status_production == \"IDLE\"){\n\n lamp1_color = rcll_draw::C_GREEN_LIGHT;\n\n lamp2_color = rcll_draw::C_GREEN_LIGHT;\n\n blbl_lamp1.setContent(\"Free For\");\n\n blbl_lamp2.setContent(\"Production\");\n\n } else if (machine.machine_status_production == \"BROKEN\"){\n\n lamp1_color = rcll_draw::C_RED;\n\n lamp2_color = rcll_draw::C_YELLOW;\n\n flashing = true;\n\n blbl_lamp1.setContent(\"Incorrect\");\n\n blbl_lamp2.setContent(\"Instruction\");\n\n } else if (machine.machine_status_production == \"PROCESSING\" || machine.machine_status_production == \"PROCESSED\"){\n\n lamp1_color = rcll_draw::C_GREEN_LIGHT;\n\n lamp2_color = rcll_draw::C_YELLOW;\n\n blbl_lamp1.setContent(\"Processing\");\n\n blbl_lamp2.setContent(\"Product\");\n", "file_path": "src/elements/subcomponents/MachineLabelProduction.cpp", "rank": 55, "score": 59410.48438376439 }, { "content": " blbl_lamp1.setContent(\"Waiting For\");\n\n blbl_lamp2.setContent(\"Removed\");\n\n } else if (machine.machine_status_production == \"OFFLINE\"){\n\n lamp1_color = rcll_draw::C_GREY_LIGHT;\n\n lamp2_color = rcll_draw::C_GREY_LIGHT;\n\n blbl_lamp1.setContent(\"Machine\");\n\n blbl_lamp2.setContent(\"Offline\");\n\n } else {\n\n lamp1_color = rcll_draw::C_GREY_LIGHT;\n\n lamp2_color = rcll_draw::C_GREY_LIGHT;\n\n blbl_lamp1.setContent(\"Machine\");\n\n blbl_lamp2.setContent(\"Offline\");\n\n }\n\n\n\n blbl_lamp1.setBackgroundColor(lamp1_color);\n\n blbl_lamp2.setBackgroundColor(lamp2_color);\n\n}\n\n\n\nvoid rcll_draw::MachineLabelProduction::draw(cv::Mat &mat){\n\n if (flashing){\n", "file_path": "src/elements/subcomponents/MachineLabelProduction.cpp", "rank": 56, "score": 59410.11838867273 }, { "content": " } else if (machine.machine_status_production == \"PREPARED\"){\n\n lamp1_color = rcll_draw::C_GREEN_LIGHT;\n\n lamp2_color = rcll_draw::C_GREEN_LIGHT;\n\n blbl_lamp1.setContent(\"Prepared\");\n\n blbl_lamp2.setContent(\"For Product\");\n\n flashing = true;\n\n } else if (machine.machine_status_production == \"DOWN\"){\n\n lamp1_color = rcll_draw::C_RED;\n\n lamp2_color = rcll_draw::C_RED;\n\n blbl_lamp1.setContent(\"Scheduled\");\n\n blbl_lamp2.setContent(\"Down\");\n\n } else if (machine.machine_status_production == \"READY-AT-OUTPUT\"){\n\n lamp1_color = rcll_draw::C_YELLOW;\n\n lamp2_color = rcll_draw::C_YELLOW;\n\n blbl_lamp1.setContent(\"Finished\");\n\n blbl_lamp2.setContent(\"Product\");\n\n } else if (machine.machine_status_production == \"WAIT-IDLE\"){\n\n lamp1_color = rcll_draw::C_YELLOW;\n\n lamp2_color = rcll_draw::C_YELLOW;\n\n flashing = true;\n", "file_path": "src/elements/subcomponents/MachineLabelProduction.cpp", "rank": 57, "score": 59409.310857831166 }, { "content": " this->y = y;\n\n this->scale = scale;\n\n\n\n if (!short_display){\n\n blbl_header.setPos(0, 0);\n\n blbl_header.setSize(w, h * 0.2);\n\n\n\n int w1 = (w - gapsize) / 2;\n\n\n\n for (size_t i = 0; i < keys.size(); i++){\n\n if (i < 3){\n\n mlp_machines[machine_map[keys[i]]].setGeometry(0, (i+1) * h * 0.2, w1, h * 0.2);\n\n } else {\n\n mlp_machines[machine_map[keys[i]]].setGeometry(w1 + gapsize, (i-2) * h * 0.2, w1, h*0.2);\n\n }\n\n }\n\n } else {\n\n blbl_header.setPos(0, 0);\n\n blbl_header.setSize(w, h / 8);\n\n\n", "file_path": "src/elements/components/MachineInfoProduction.cpp", "rank": 58, "score": 59408.67562617765 }, { "content": "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\nSOFTWARE.\n\n*/\n\n\n\n#include <MachineLabelProduction.h>\n\n\n\n// MachineLabelProduction ####################################################################\n\n\n\nrcll_draw::MachineLabelProduction::MachineLabelProduction(rcll_draw::Team team){\n\n blbl_machinename.setAlignment(rcll_draw::CenterLeft);\n\n blbl_lamp1.setAlignment(rcll_draw::CenterCenter);\n\n blbl_lamp2.setAlignment(rcll_draw::CenterCenter);\n\n\n\n if (team == rcll_draw::CYAN){\n\n blbl_machinename.setBackgroundColor(rcll_draw::C_BLACK);\n\n blbl_machinename.setFrontColor(rcll_draw::C_WHITE);\n\n } else if (team == rcll_draw::MAGENTA){\n\n blbl_machinename.setBackgroundColor(rcll_draw::C_BLACK);\n\n blbl_machinename.setFrontColor(rcll_draw::C_WHITE);\n\n } else {\n", "file_path": "src/elements/subcomponents/MachineLabelProduction.cpp", "rank": 59, "score": 59407.38689041853 }, { "content": " if (getBoolSignal(ros::Time::now(), ros::Rate(1.33))){\n\n blbl_lamp1.setBackgroundColor(lamp1_color);\n\n blbl_lamp2.setBackgroundColor(lamp2_color);\n\n blbl_lamp1.setBorderColor(lamp1_color);\n\n blbl_lamp2.setBorderColor(lamp2_color);\n\n } else {\n\n blbl_lamp1.setBackgroundColor(rcll_draw::C_GREY_LIGHT);\n\n blbl_lamp2.setBackgroundColor(rcll_draw::C_GREY_LIGHT);\n\n blbl_lamp1.setBorderColor(rcll_draw::C_GREY_LIGHT);\n\n blbl_lamp2.setBorderColor(rcll_draw::C_GREY_LIGHT);\n\n }\n\n } else {\n\n blbl_lamp1.setBackgroundColor(lamp1_color);\n\n blbl_lamp2.setBackgroundColor(lamp2_color);\n\n blbl_lamp1.setBorderColor(lamp1_color);\n\n blbl_lamp2.setBorderColor(lamp2_color);\n\n }\n\n\n\n blbl_machinename.draw(mat);\n\n blbl_lamp1.draw(mat);\n\n blbl_lamp2.draw(mat);\n\n blbl_border.draw(mat);\n\n}\n", "file_path": "src/elements/subcomponents/MachineLabelProduction.cpp", "rank": 60, "score": 59402.94069264934 }, { "content": "/*\n\nThe MIT License (MIT)\n\n\n\nCopyright (c) 2017-2018 Florian Eith <[email protected]>\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", "file_path": "src/elements/components/MachineInfoProduction.cpp", "rank": 61, "score": 59400.79624085777 }, { "content": "/*\n\nThe MIT License (MIT)\n\n\n\nCopyright (c) 2017-2018 Florian Eith <[email protected]>\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", "file_path": "src/elements/subcomponents/MachineLabelProduction.cpp", "rank": 62, "score": 59400.79624085777 }, { "content": " blbl_machinename.setBackgroundColor(rcll_draw::C_BLACK);\n\n blbl_machinename.setFrontColor(rcll_draw::C_WHITE);\n\n }\n\n blbl_lamp1.setBackgroundColor(rcll_draw::C_WHITE);\n\n blbl_lamp2.setBackgroundColor(rcll_draw::C_WHITE);\n\n blbl_border.setBackgroundColor(rcll_draw::C_TRANSPARENT);\n\n\n\n blbl_lamp1.setFrontColor(rcll_draw::C_BLACK);\n\n blbl_lamp2.setFrontColor(rcll_draw::C_BLACK);\n\n\n\n blbl_machinename.setBorderColor(rcll_draw::C_TRANSPARENT);\n\n blbl_lamp1.setBorderColor(rcll_draw::C_WHITE);\n\n blbl_lamp2.setBorderColor(rcll_draw::C_WHITE);\n\n blbl_border.setBorderColor(rcll_draw::C_WHITE);\n\n\n\n blbl_machinename.setFontSize(0.9);\n\n blbl_lamp1.setFontSize(0.7);\n\n blbl_lamp2.setFontSize(0.7);\n\n\n\n\n", "file_path": "src/elements/subcomponents/MachineLabelProduction.cpp", "rank": 63, "score": 59397.12034355807 }, { "content": " class HLine : public Line {\n\n public:\n\n HLine();\n\n ~HLine();\n\n\n\n void setLine(int x1, int y, int x2);\n\n };\n\n\n", "file_path": "include/elements/basic/Line.h", "rank": 64, "score": 56763.42515441427 }, { "content": " class GameInfo;\n", "file_path": "include/llsf_communicator.h", "rank": 65, "score": 48789.81799475303 }, { "content": " class GameField {\n\n public:\n\n GameField();\n\n ~GameField();\n\n\n\n void setPhase(rcll_draw::GamePhase gamephase);\n\n void setGeometry(int x, int y, double scale);\n\n void setGameField(rcll_vis_msgs::SetGameField &setgamefield);\n\n void setRefBoxView(bool refbox_view);\n\n\n\n int getW(double scale = 1.0);\n\n int getH(double scale = 1.0);\n\n\n\n void setRobots(std::vector<rcll_vis_msgs::Robot> &robots);\n\n void setMachines(std::vector<rcll_vis_msgs::Machine> &machines);\n\n void draw(cv::Mat &mat, bool show_element_border = false);\n\n\n\n private:\n\n int x, y = 0;\n\n int w = 1290, h = 750;\n", "file_path": "include/elements/components/GameField.h", "rank": 66, "score": 46041.711394552796 }, { "content": " class TeamHeaderPanel {\n\n public:\n\n TeamHeaderPanel();\n\n ~TeamHeaderPanel();\n\n\n\n void setTeam(std::string team_name, rcll_draw::Team team_color);\n\n void setGeometry(int x, int y, double scale);\n\n\n\n int getW(double scale = 1.0);\n\n int getH(double scale = 1.0);\n\n\n\n void draw(cv::Mat &mat, bool show_element_border = false);\n\n private:\n\n int x, y = 0;\n\n int w = 362, h = 100;\n\n double scale = 1.0;\n\n cv::Mat origin;\n\n\n\n BoxLabel blbl_header_color;\n\n BoxLabel blbl_header_name;\n\n };\n\n}\n\n\n\n#endif\n", "file_path": "include/elements/components/TeamHeaderPanel.h", "rank": 67, "score": 43732.805959923106 }, { "content": "\n\n private: // members\n\n bool quit_;\n\n\n\n boost::asio::io_service io_service_;\n\n boost::asio::deadline_timer reconnect_timer_;\n\n bool try_reconnect_;\n\n\n\n protobuf_comm::ProtobufStreamClient *client;\n\n\n\n std::string cfg_refbox_host_;\n\n unsigned int cfg_refbox_port_;\n\n\n\n rcll_vis_msgs::Machines machines_msg;\n\n rcll_vis_msgs::GameInfo gameinfo_msg;\n\n rcll_vis_msgs::Products products_msg;\n\n rcll_vis_msgs::Robots robots_msg;\n\n\n\n ros::Publisher pub_machines;\n\n ros::Publisher pub_gameinfo;\n\n ros::Publisher pub_products;\n\n ros::Publisher pub_robots;\n\n};\n\n\n\n#endif\n", "file_path": "include/llsf_communicator.h", "rank": 68, "score": 34989.12675969322 }, { "content": "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\nSOFTWARE.\n\n*/\n\n\n\n#ifndef __LLSF_COMMUNICATOR_H_\n\n#define __LLSF_COMMUNICATOR_H_\n\n\n\n#include <boost/asio.hpp>\n\n#include <boost/date_time.hpp>\n\n#include <google/protobuf/message.h>\n\n\n\n#include <map>\n\n#include <vector>\n\n#include <string>\n\n#include <mutex>\n\n\n\n#include <rcll_vis_msgs/GameInfo.h>\n\n#include <rcll_vis_msgs/Machines.h>\n\n#include <rcll_vis_msgs/Robots.h>\n\n#include <rcll_vis_msgs/Products.h>\n\n#include <rcll_vis_msgs/SetGameField.h>\n\n\n\n#include <ros/ros.h>\n\n\n\nnamespace protobuf_comm {\n", "file_path": "include/llsf_communicator.h", "rank": 69, "score": 34984.05494306731 }, { "content": "/*\n\nThe MIT License (MIT)\n\n\n\nCopyright (c) 2017-2018 Florian Eith <[email protected]>\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", "file_path": "include/llsf_communicator.h", "rank": 70, "score": 34971.48411152549 }, { "content": "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\nSOFTWARE.\n\n*/\n\n\n\n#ifndef RCLL_RECTANGLE_H\n\n#define RCLL_RECTANGLE_H\n\n\n\n#include <util.h>\n\n#include <Label.h>\n\n\n\nnamespace rcll_draw {\n", "file_path": "include/elements/basic/Rectangle.h", "rank": 71, "score": 33230.63773528774 }, { "content": "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\nSOFTWARE.\n\n*/\n\n\n\n#ifndef RCLL_IMAGE_H\n\n#define RCLL_IMAGE_H\n\n\n\n#include <util.h>\n\n\n\nnamespace rcll_draw {\n", "file_path": "include/elements/basic/Image.h", "rank": 72, "score": 33229.96709634743 }, { "content": "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\nSOFTWARE.\n\n*/\n\n\n\n#ifndef RCLL_ARROW_H\n\n#define RCLL_ARROW_H\n\n\n\n#include <util.h>\n\n\n\nnamespace rcll_draw {\n", "file_path": "include/elements/basic/Arrow.h", "rank": 73, "score": 33229.96709634743 }, { "content": "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\nSOFTWARE.\n\n*/\n\n\n\n#ifndef RCLL_LABEL_H\n\n#define RCLL_LABEL_H\n\n\n\n#include <util.h>\n\n\n\nnamespace rcll_draw {\n", "file_path": "include/elements/basic/Label.h", "rank": 74, "score": 33229.96709634743 }, { "content": "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\nSOFTWARE.\n\n*/\n\n\n\n#ifndef RCLL_LINE_H\n\n#define RCLL_LINE_H\n\n\n\n#include <util.h>\n\n\n\nnamespace rcll_draw {\n", "file_path": "include/elements/basic/Line.h", "rank": 75, "score": 33229.96709634743 }, { "content": "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\nSOFTWARE.\n\n*/\n\n\n\n#ifndef RCLL_CIRCLE_H\n\n#define RCLL_CIRCLE_H\n\n\n\n#include <util.h>\n\n\n\nnamespace rcll_draw {\n", "file_path": "include/elements/basic/Circle.h", "rank": 76, "score": 33229.96709634743 }, { "content": "/*\n\nThe MIT License (MIT)\n\n\n\nCopyright (c) 2017-2018 Florian Eith <[email protected]>\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", "file_path": "include/elements/basic/Image.h", "rank": 77, "score": 33225.55780004774 }, { "content": "/*\n\nThe MIT License (MIT)\n\n\n\nCopyright (c) 2017-2018 Florian Eith <[email protected]>\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", "file_path": "include/elements/basic/Line.h", "rank": 78, "score": 33225.55780004774 }, { "content": "/*\n\nThe MIT License (MIT)\n\n\n\nCopyright (c) 2017-2018 Florian Eith <[email protected]>\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", "file_path": "include/elements/basic/Circle.h", "rank": 79, "score": 33225.55780004774 }, { "content": "/*\n\nThe MIT License (MIT)\n\n\n\nCopyright (c) 2017-2018 Florian Eith <[email protected]>\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", "file_path": "include/elements/basic/Label.h", "rank": 80, "score": 33225.55780004774 }, { "content": "/*\n\nThe MIT License (MIT)\n\n\n\nCopyright (c) 2017-2018 Florian Eith <[email protected]>\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", "file_path": "include/elements/basic/Arrow.h", "rank": 81, "score": 33225.55780004774 }, { "content": "/*\n\nThe MIT License (MIT)\n\n\n\nCopyright (c) 2017-2018 Florian Eith <[email protected]>\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", "file_path": "include/elements/basic/Rectangle.h", "rank": 82, "score": 33225.55780004774 }, { "content": "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\nSOFTWARE.\n\n*/\n\n\n\n#ifndef RCLL_GAMEFIELD_H\n\n#define RCLL_GAMEFIELD_H\n\n\n\n#include <util.h>\n\n#include <Rectangle.h>\n\n#include <BoxLabel.h>\n\n#include <Line.h>\n\n\n\n#include <RobotMarker.h>\n\n#include <MachineMarker.h>\n\n\n\n#include <rcll_vis_msgs/SetGameField.h>\n\n#include <rcll_vis_msgs/Machine.h>\n\n#include <rcll_vis_msgs/Robot.h>\n\n\n\nnamespace rcll_draw {\n\n\n\n // ##################################################\n\n\n", "file_path": "include/elements/components/GameField.h", "rank": 83, "score": 31662.57831656975 }, { "content": "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\nSOFTWARE.\n\n*/\n\n\n\n#ifndef RCLL_AREA_EXPLORATION_H\n\n#define RCLL_AREA_EXPLORATION_H\n\n\n\n#include <util.h>\n\n#include <HeaderPanel.h>\n\n#include <HStatusPanel.h>\n\n#include <TeamHeaderPanel.h>\n\n#include <MachineInfoExploration.h>\n\n#include <GameField.h>\n\n\n\n#include <rcll_vis_msgs/Machine.h>\n\n#include <rcll_vis_msgs/Robot.h>\n\n#include <rcll_vis_msgs/Products.h>\n\n#include <rcll_vis_msgs/GameInfo.h>\n\n#include <rcll_vis_msgs/SetGameField.h>\n\n\n\nnamespace rcll_draw {\n", "file_path": "include/elements/areas/AreaExploration.h", "rank": 84, "score": 31659.785073419625 }, { "content": " double scale = 1.0;\n\n cv::Mat origin;\n\n\n\n int origin_x, origin_y = 0;\n\n\n\n bool refbox_view;\n\n int pixel_per_meter = 10;\n\n\n\n GamePhase gamephase;\n\n Rectangle rct_background;\n\n Rectangle rct_background2;\n\n BoxLabel blbl_insertion_cyan1;\n\n BoxLabel blbl_insertion_cyan2;\n\n BoxLabel blbl_insertion_magenta1;\n\n BoxLabel blbl_insertion_magenta2;\n\n std::vector<Line> lnes_walls;\n\n std::vector<Line> lnes_zone_lines;\n\n std::vector<BoxLabel> blbls_zone_names;\n\n\n\n std::vector<RobotMarker> rm_robot_markers;\n\n std::vector<MachineMarker> mm_machine_markers;\n\n\n\n };\n\n}\n\n\n\n#endif\n", "file_path": "include/elements/components/GameField.h", "rank": 85, "score": 31657.10034836613 }, { "content": "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\nSOFTWARE.\n\n*/\n\n\n\n#ifndef RCLL_AREA_FIELD_H\n\n#define RCLL_AREA_FIELD_H\n\n\n\n#include <util.h>\n\n\n\n#include <HeaderPanel.h>\n\n#include <HStatusPanel.h>\n\n#include <TeamHeaderPanel.h>\n\n#include <GameField.h>\n\n\n\n#include <rcll_vis_msgs/GameInfo.h>\n\n#include <rcll_vis_msgs/Machine.h>\n\n#include <rcll_vis_msgs/Robot.h>\n\n#include <rcll_vis_msgs/SetGameField.h>\n\n\n\nnamespace rcll_draw {\n\n\n\n // ##################################################\n\n\n", "file_path": "include/elements/areas/AreaField.h", "rank": 86, "score": 31656.64188701431 }, { "content": " HStatusPanel hsp_gameinfo;\n\n TeamHeaderPanel thp_team_header_cyan;\n\n TeamHeaderPanel thp_team_header_magenta;\n\n MachineInfoExploration mie_machine_info_cyan;\n\n MachineInfoExploration mie_machine_info_magenta;\n\n GameField gf_gamefield;\n\n BoxLabel blbl_text;\n\n };\n\n}\n\n\n\n#endif\n", "file_path": "include/elements/areas/AreaExploration.h", "rank": 87, "score": 31656.023724249222 }, { "content": " HeaderPanel hp_header;\n\n HStatusPanel hsp_gameinfo;\n\n TeamHeaderPanel thp_team_cyan;\n\n TeamHeaderPanel thp_team_magenta;\n\n GameField gf_gamefield;\n\n BoxLabel blbl_text;\n\n\n\n };\n\n}\n\n\n\n#endif\n", "file_path": "include/elements/areas/AreaField.h", "rank": 88, "score": 31652.31570818838 }, { "content": "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\nSOFTWARE.\n\n*/\n\n\n\n#ifndef RCLL_BOXLABEL_H\n\n#define RCLL_BOXLABEL_H\n\n\n\n#include <util.h>\n\n#include <Label.h>\n\n\n\nnamespace rcll_draw {\n", "file_path": "include/elements/basic/BoxLabel.h", "rank": 89, "score": 31650.766919089354 }, { "content": "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\nSOFTWARE.\n\n*/\n\n\n\n#ifndef RCLL_HEADER_PANEL_H\n\n#define RCLL_HEADER_PANEL_H\n\n\n\n#include <util.h>\n\n#include <BoxLabel.h>\n\n\n\nnamespace rcll_draw {\n\n\n", "file_path": "include/elements/components/HeaderPanel.h", "rank": 90, "score": 31650.629904319732 }, { "content": "/*\n\nThe MIT License (MIT)\n\n\n\nCopyright (c) 2017-2018 Florian Eith <[email protected]>\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", "file_path": "include/elements/basic/BoxLabel.h", "rank": 91, "score": 31645.68698384936 }, { "content": "/*\n\nThe MIT License (MIT)\n\n\n\nCopyright (c) 2017-2018 Florian Eith <[email protected]>\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", "file_path": "include/elements/areas/AreaField.h", "rank": 92, "score": 31645.68698384936 }, { "content": "/*\n\nThe MIT License (MIT)\n\n\n\nCopyright (c) 2017-2018 Florian Eith <[email protected]>\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", "file_path": "include/elements/components/HeaderPanel.h", "rank": 93, "score": 31645.68698384936 }, { "content": "/*\n\nThe MIT License (MIT)\n\n\n\nCopyright (c) 2017-2018 Florian Eith <[email protected]>\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", "file_path": "include/elements/components/GameField.h", "rank": 94, "score": 31645.68698384936 }, { "content": "/*\n\nThe MIT License (MIT)\n\n\n\nCopyright (c) 2017-2018 Florian Eith <[email protected]>\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", "file_path": "include/elements/areas/AreaExploration.h", "rank": 95, "score": 31645.68698384936 }, { "content": " class Label {\n\n public:\n\n Label();\n\n ~Label();\n\n\n\n void setContent(std::string content);\n\n void setPos(int x, int y); // origin is top left corner\n\n void setFrontColor(Color c);\n\n void setFont(std::string font, double fontsize);\n\n void setFontSize(double fontsize);\n\n void setAlignment(Alignment alignment);\n\n void draw(cv::Mat &mat);\n\n\n\n protected:\n\n int x, y = 0;\n\n std::string content = \"\";\n\n Color frontcolor = C_BLACK;\n\n std::string font;\n\n double fontsize = 12.0;\n\n Alignment alignment = CenterCenter;\n\n };\n\n}\n\n\n\n#endif\n", "file_path": "include/elements/basic/Label.h", "rank": 96, "score": 31642.01108654965 }, { "content": " class Rectangle {\n\n public:\n\n Rectangle();\n\n ~Rectangle();\n\n\n\n void setPos(int x, int y); // origin is top left corner\n\n void setSize(int w, int h);\n\n void setBackgroundColor(Color c);\n\n void setBorderColor(Color c);\n\n void setBorderSize(int bordersize);\n\n void draw(cv::Mat &mat);\n\n\n\n protected:\n\n int x, y = 0;\n\n int w, h = 10;\n\n Color bordercolor = C_BLACK;\n\n Color backgroundcolor = C_WHITE;\n\n int bordersize = 1;\n\n\n\n };\n\n}\n\n\n\n#endif\n", "file_path": "include/elements/basic/Rectangle.h", "rank": 97, "score": 31642.01108654965 }, { "content": " class Circle {\n\n public:\n\n Circle();\n\n ~Circle();\n\n\n\n void setPos(int x, int y); // origin is center or circle\n\n void setSize(double radius);\n\n void setBackgroundColor(Color c);\n\n void setBorderColor(Color c);\n\n void setBorderSize(int bordersize);\n\n void draw(cv::Mat &mat);\n\n\n\n protected:\n\n int x, y = 0;\n\n double r = 1;\n\n Color bordercolor = C_BLACK;\n\n Color backgroundcolor = C_WHITE;\n\n int bordersize = 1;\n\n };\n\n}\n\n\n\n#endif\n", "file_path": "include/elements/basic/Circle.h", "rank": 98, "score": 31642.01108654965 }, { "content": " class Line {\n\n public:\n\n Line();\n\n ~Line();\n\n void setLineByPoints(int x1, int y1, int x2, int y2);\n\n void setLineByLength(int x1, int y1, double angle, double length);\n\n void setBorderColor(Color c);\n\n void setBorderSize(int bordersize);\n\n void setLineType(LineType linetype);\n\n void draw(cv::Mat &mat);\n\n\n\n protected:\n\n int x1, y1, x2, y2 = 0;\n\n Color bordercolor = C_BLACK;\n\n int bordersize = 1;\n\n LineType linetype = Continuous;\n\n };\n\n\n", "file_path": "include/elements/basic/Line.h", "rank": 99, "score": 31642.01108654965 } ]
C++
WithComments/grid.cc
RootofalleviI/Reversi
e52bf7ead191568114504945b62c7b955a2074a5
#include <string> #include <sstream> #include "grid.h" using namespace std; void Grid::init(size_t n) { dim = n; if (td) delete td; td = new TextDisplay(n); theGrid.clear(); for (size_t i=0; i<dim; ++i) { theGrid.emplace_back(vector<Cell>()); for (size_t j=0; j<dim; ++j) { theGrid[i].emplace_back(Cell(i,j)); } } for (size_t i=0; i<dim; ++i) { for (size_t j=0; j<dim; ++j) { initObservers(i, j); } } setObserver(td); size_t t = dim/2 - 1; setPiece(t, t, Colour::Black); setPiece(t+1, t+1, Colour::Black); setPiece(t, t+1, Colour::White); setPiece(t+1, t, Colour::White); } void Grid::initObservers(int r, int c) { int d = dim; if (((r-1) >= 0) && ((c-1) >= 0)) theGrid[r][c].attach(&theGrid[r-1][c-1]); if ((r-1) >= 0) theGrid[r][c].attach(&theGrid[r-1][c]); if (((r-1) >= 0) && ((c+1) <= d-1)) theGrid[r][c].attach(&theGrid[r-1][c+1]); if ((c+1) <= d-1) theGrid[r][c].attach(&theGrid[r][c+1]); if (((r+1) <= d-1) && ((c+1) <= d-1)) theGrid[r][c].attach(&theGrid[r+1][c+1]); if ((r+1) <= d-1) theGrid[r][c].attach(&theGrid[r+1][c]); if (((r+1) <= d-1) && ((c-1) >= 0)) theGrid[r][c].attach(&theGrid[r+1][c-1]); if ((c-1) >= 0) theGrid[r][c].attach(&theGrid[r][c-1]); } void Grid::setObserver(Observer<Info, State> *ob) { for (size_t i=0; i<dim; ++i) { for (size_t j=0; j<dim; ++j) { theGrid[i][j].attach(ob); } } } void Grid::reset() { for (size_t i=0; i<dim; ++i) { for (size_t j=0; j<dim; ++j) { theGrid[i][j].setPiece(Colour::NoColour); } } } void Grid::setPiece(size_t r, size_t c, Colour colour) { reset(); if ((r >= dim) || (c >= dim)) { #ifdef DEBUG cout << "Invalid Position: (" << r << ", " << c << ")" << std::endl; #endif throw ""; return; } theGrid[r][c].setPiece(colour); if (colour != Colour::NoColour) updateCounter(); #ifdef DEBUG print(); #endif } int count(string s, char c) { size_t x = 0, len = s.size(); for (size_t i=0; i<len; ++i) { if (s[i] == c) ++x; } return x; } void Grid::updateCounter() { stringstream ss; ss << *td; string s = ss.str(); black = count(s, 'B'); white = count(s, 'W'); } void Grid::toggle(size_t r, size_t c) { theGrid[r][c].toggle(); } bool Grid::isFull() const { return (white+black == dim*dim); } Grid::~Grid() { delete td; } Colour Grid::whoWon() const { if (white>black) return Colour::White; else if (black>white) return Colour::Black; else return Colour::NoColour; } std::ostream &operator<<(ostream &out, const Grid &g) { out << *(g.td); return out; }
#include <string> #include <sstream> #include "grid.h" using namespace std; void Grid::init(size_t n) { dim = n; if (td) delete td; td = new TextDisplay(n); theGrid.clear(); for (size_t i=0; i<dim; ++i) { theGrid.emplace_back(vector<Cell>()); for (size_t j=0; j<dim; ++j) { theGrid[i].emplace_back(Cell(i,j)); } } for (size_t i=0; i<dim; ++i) { for (size_t j=0; j<dim; ++j) { initObservers(i, j); } } setObserver(td); size_t t = dim/2 - 1; setPiece(t, t, Colour::Black); setPiece(t+1, t+1, Colour::Black); setPiece(t, t+1, Colour::White); setPiece(t+1, t, Colour::White); } void Grid::initObservers(int r, int c) { int d = dim; if (((r-1) >= 0) && ((c-1) >= 0)) theGrid[r][c].attach(&theGrid[r-1][c-1]); if ((r-1) >= 0) theGrid[r][c].attach(&theGrid[r-1][c]); if (((r-1) >= 0) && ((c+1) <= d-1)) theGrid[r][c].attach(&theGrid[r-1][c+1]); if ((c+1) <= d-1) theGrid[r][c].attach(&theGrid[r][c+1]); if (((r+1) <= d-1) && ((c+1) <= d-1)) theGrid[r][c].attach(&theGrid[r+1][c+1]); if ((r+1) <= d-1) theGrid[r][c].attach(&theGrid[r+1][c]); if (((r+1) <= d-1) && ((c-1) >= 0)) theGrid[r][c].attach(&theGrid[r+1][c-1]); if ((c-1) >= 0) theGrid[r][c].attach(&theGrid[r][c-1]); } void Grid::setObserver(Observer<Info, State> *ob) { for (size_t i=0; i<dim; ++i) { for (size_t j=0; j<dim; ++j) { theGrid[i][j].attach(ob); } } } void Grid::reset() { for (size_t i=0; i<dim; ++i) { for (size_t j=0; j<dim; ++j) { theGrid[i][j].setPiece(Colour::NoColour); } } } void Grid::setPiece(size_t r, size_t c, Colour colour) { reset(); if ((r >= dim) || (c >= dim)) { #ifdef DEBUG cout << "Invalid Position: (" << r << ", " << c << ")" << std::endl; #endif throw ""; return; } theGrid[r][c].setPiece(colour); if (colour != Colour::NoColour) updateCounter(); #ifdef DEBUG print(); #endif }
void Grid::updateCounter() { stringstream ss; ss << *td; string s = ss.str(); black = count(s, 'B'); white = count(s, 'W'); } void Grid::toggle(size_t r, size_t c) { theGrid[r][c].toggle(); } bool Grid::isFull() const { return (white+black == dim*dim); } Grid::~Grid() { delete td; } Colour Grid::whoWon() const { if (white>black) return Colour::White; else if (black>white) return Colour::Black; else return Colour::NoColour; } std::ostream &operator<<(ostream &out, const Grid &g) { out << *(g.td); return out; }
int count(string s, char c) { size_t x = 0, len = s.size(); for (size_t i=0; i<len; ++i) { if (s[i] == c) ++x; } return x; }
function_block-full_function
[ { "content": " Colour colour; \n", "file_path": "state.h", "rank": 0, "score": 67877.03442930145 }, { "content": " Colour colour; \n", "file_path": "WithComments/state.h", "rank": 1, "score": 65354.836290758016 }, { "content": " Colour colour;\n", "file_path": "info.h", "rank": 2, "score": 44895.96462628644 }, { "content": " Colour colour;\n", "file_path": "WithComments/info.h", "rank": 3, "score": 43625.132959893475 }, { "content": "class Cell : public Subject<Info, State>, public Observer<Info, State> {\n\n const size_t r, c;\n\n Colour colour = Colour::NoColour;\n\npublic: \n\n Cell(size_t r, size_t c);\n\n void setPiece(Colour colour);\n\n void toggle();\n\n void notify(Subject<Info, State> &whoFrom) override;\n\n Info getInfo() const override;\n\n\n\n};\n\n\n\n#endif\n\n\n\n\n", "file_path": "cell.h", "rank": 4, "score": 39814.531989088704 }, { "content": "class Cell : public Subject<Info, State>, public Observer<Info, State> {\n\n const size_t r, c;\n\n Colour colour = Colour::NoColour;\n\n\n\n /* Inheried from Subject \n\n * std::vector<Observer<Info, State>*> observers;\n\n * State state;\n\n * setState(State newS);\n\n */\n\n\n\npublic: \n\n Cell(size_t r, size_t c);\n\n void setPiece(Colour colour);\n\n void toggle();\n\n void notify(Subject<Info, State> &whoFrom) override;\n\n Info getInfo() const override;\n\n\n\n /* Inherited from Subject\n\n * void attach(Observer<Info, State> *o);\n\n * void notifyObservers();\n\n * State getState() const;\n\n */\n\n};\n\n\n\n#endif\n\n\n\n\n", "file_path": "WithComments/cell.h", "rank": 5, "score": 39015.40847472583 }, { "content": "class GraphicalDisplay : public Observer<Info, State> {\n\n\tconst int gridSize;\n\n\tXwindow w;\n\npublic:\n\n\tGraphicalDisplay(int n);\n\n\tvoid notify(Subject<Info, State> &whoNotified) override;\n\n};\n\n\n\n#endif\n\n\n", "file_path": "graphicaldisplay.h", "rank": 6, "score": 32756.756070104657 }, { "content": "class TextDisplay: public Observer<Info, State> {\n\n std::vector<std::vector<char>> theDisplay;\n\n const int gridSize;\n\n public:\n\n TextDisplay(int n);\n\n void notify(Subject<Info, State> &whoNotified) override;\n\n friend std::ostream &operator<<(std::ostream &out, const TextDisplay &td);\n\n};\n\n\n\n#endif\n", "file_path": "textdisplay.h", "rank": 7, "score": 32756.756070104657 }, { "content": "class TextDisplay: public Observer<Info, State> {\n\n std::vector<std::vector<char>> theDisplay;\n\n const int gridSize;\n\n public:\n\n TextDisplay(int n);\n\n void notify(Subject<Info, State> &whoNotified) override;\n\n friend std::ostream &operator<<(std::ostream &out, const TextDisplay &td);\n\n};\n\n\n\n#endif\n", "file_path": "WithComments/textdisplay.h", "rank": 8, "score": 31744.833600385213 }, { "content": "class InvalidMove{}; \n\n\n", "file_path": "grid.h", "rank": 9, "score": 26490.5852944004 }, { "content": "class InvalidMove{}; \n\n\n", "file_path": "WithComments/grid.h", "rank": 10, "score": 24871.82931368954 }, { "content": " StateType type; \n", "file_path": "state.h", "rank": 11, "score": 22981.069803015012 }, { "content": " Direction direction;\n", "file_path": "state.h", "rank": 12, "score": 22981.069803015012 }, { "content": " StateType type; \n", "file_path": "WithComments/state.h", "rank": 13, "score": 21729.703330864537 }, { "content": " Direction direction;\n", "file_path": "WithComments/state.h", "rank": 14, "score": 21729.703330864537 }, { "content": "#include <string>\n\n#include <sstream>\n\n#include \"grid.h\"\n\nusing namespace std;\n\n\n\nvoid Grid::init(size_t n) {\n\n\n\n dim = n;\n\n if (td) delete td;\n\n td = new TextDisplay(n);\n\n\n\n if (ob) delete ob;\n\n ob = new GraphicalDisplay(n);\n\n\n\n theGrid.clear();\n\n\n\n for (size_t i=0; i<dim; ++i) {\n\n theGrid.emplace_back(vector<Cell>());\n\n for (size_t j=0; j<dim; ++j) {\n\n theGrid[i].emplace_back(Cell(i,j));\n", "file_path": "grid.cc", "rank": 15, "score": 26.451256733901072 }, { "content": "#include \"grid.h\"\n\n#include \"cell.h\"\n\n#include \"state.h\"\n\nusing namespace std;\n\n// #define DEBUG\n\n\n\nint main(int argc, char *argv[]) {\n\n\n\n (void) argc;\n\n (void) argv;\n\n \n\n cin.exceptions(ios::eofbit|ios::failbit);\n\n string cmd;\n\n Grid g;\n\n\n\n // keep track of whose turn it is\n\n bool black = true;\n\n\n\n try {\n\n while (true) {\n", "file_path": "WithComments/main.cc", "rank": 18, "score": 18.27711145668145 }, { "content": "#include \"grid.h\"\n\n#include \"cell.h\"\n\n#include \"state.h\"\n\n#include \"window.h\"\n\nusing namespace std;\n\n\n\nint main(int argc, char *argv[]) {\n\n\n\n (void) argc;\n\n (void) argv;\n\n \n\n cin.exceptions(ios::eofbit|ios::failbit);\n\n string cmd;\n\n Grid g;\n\n\n\n bool black = true;\n\n\n\n try {\n\n while (true) {\n\n cin >> cmd;\n", "file_path": "main.cc", "rank": 19, "score": 17.06143760528407 }, { "content": " else if (d == Direction::SW) return Direction::NE;\n\n else if (d == Direction::W) return Direction::E;\n\n else return Direction::SE;\n\n}\n\n\n\n\n\n#ifdef DEBUG\n\nvoid printCoord(string s, size_t r, size_t c) {\n\n cout << s << \"(\" << r << \",\" << c << \")\" << endl;\n\n}\n\n#endif\n\n\n\n\n\n/* Ctor */\n\nCell::Cell(size_t r, size_t c) : r(r), c(c) {\n\n State s;\n\n s.direction = Direction::N;\n\n s.colour = Colour::NoColour;\n\n s.type = StateType::Relay;\n\n setState(s);\n", "file_path": "WithComments/cell.cc", "rank": 20, "score": 16.14266413433619 }, { "content": " colour = Colour::Black;\n\n }\n\n\n\n /*\n\n // Set current cell as a newPiece and see if it changes anything\n\n State s;\n\n s.type = StateType::NewPiece;\n\n s.direction = Direction::N;\n\n s.colour = colour;\n\n setState(s);\n\n\n\n #ifdef DEBUG\n\n printCoord(\"Cell::toggle(): Flipping \", r, c);\n\n cout << \"Notifying my observers!\" << endl;\n\n #endif\n\n\n\n notifyObservers();\n\n */\n\n}\n\n\n", "file_path": "WithComments/cell.cc", "rank": 21, "score": 15.411963579932495 }, { "content": " if (s[i] == c) ++x;\n\n }\n\n return x;\n\n}\n\n\n\nvoid Grid::updateCounter() {\n\n stringstream ss;\n\n ss << *td;\n\n string s = ss.str();\n\n black = count(s, 'B');\n\n white = count(s, 'W');\n\n}\n\n\n\nvoid Grid::toggle(size_t r, size_t c) { theGrid[r][c].toggle(); }\n\nbool Grid::isFull() const { return (white+black == dim*dim); }\n\nGrid::~Grid() { delete td; delete ob; }\n\n\n\nColour Grid::whoWon() const {\n\n if (white>black) return Colour::White;\n\n else if (black>white) return Colour::Black;\n", "file_path": "grid.cc", "rank": 22, "score": 15.014549938603409 }, { "content": " return;\n\n }\n\n\n\n /* Otherwise, we are actually playing a new piece. */\n\n else {\n\n this->colour = colour;\n\n\n\n State s;\n\n s.direction = Direction::N;\n\n s.colour = colour;\n\n s.type = StateType::NewPiece;\n\n setState(s);\n\n\n\n #ifdef DEBUG\n\n printCoord(\"Cell:setPiece: New Piece at \", r, c);\n\n #endif \n\n\n\n notifyObservers();\n\n }\n\n}\n", "file_path": "WithComments/cell.cc", "rank": 23, "score": 14.537635365750898 }, { "content": "\n\n/* Set the color of current cell, or reset current cell type */\n\nvoid Cell::setPiece(Colour colour) {\n\n\n\n /* NoColour indicates we are resetting cell type. */\n\n if (colour == Colour::NoColour) {\n\n State s;\n\n s.type = StateType::Relay;\n\n s.colour = this->colour;\n\n s.direction = Direction::N;\n\n setState(s);\n\n }\n\n\n\n /* If the cell has color already, raise an error indicating occupied */\n\n else if (this->colour != Colour::NoColour) {\n\n\n\n #ifdef DEBUG\n\n printCoord(\"Cell::setPiece: Occupied already \", r, c);\n\n #endif\n\n throw \"\";\n", "file_path": "WithComments/cell.cc", "rank": 24, "score": 14.233669110610657 }, { "content": " }\n\n }\n\n\n\n for (size_t i=0; i<dim; ++i) {\n\n for (size_t j=0; j<dim; ++j) {\n\n initObservers(i, j);\n\n }\n\n }\n\n\n\n setObserver(td); setObserver(ob);\n\n\n\n size_t t = dim/2 - 1;\n\n setPiece(t, t, Colour::Black);\n\n setPiece(t+1, t+1, Colour::Black);\n\n setPiece(t, t+1, Colour::White);\n\n setPiece(t+1, t, Colour::White);\n\n}\n\n\n\nvoid Grid::initObservers(int r, int c) {\n\n int d = dim;\n", "file_path": "grid.cc", "rank": 25, "score": 14.140768373812646 }, { "content": "#include \"textdisplay.h\"\n\nusing namespace std;\n\n\n\nTextDisplay::TextDisplay(int n) : gridSize(n) {\n\n for (int i=0; i<gridSize; ++i) {\n\n theDisplay.emplace_back(vector<char>());\n\n for (int j=0; j<gridSize; ++j) {\n\n theDisplay[i].emplace_back('-');\n\n }\n\n }\n\n}\n\n\n\nvoid TextDisplay::notify(Subject<Info,State> &whoNotified) {\n\n Info i = whoNotified.getInfo();\n\n if (i.colour == Colour::Black) {\n\n theDisplay[i.row][i.col] = 'B';\n\n } else { \n\n theDisplay[i.row][i.col] = 'W';\n\n }\n\n}\n", "file_path": "textdisplay.cc", "rank": 26, "score": 14.061744795541049 }, { "content": "\n\n\n\n/* The most important function! */\n\nvoid Cell::notify(Subject <Info, State> &whoFrom) {\n\n\n\n Info srcInfo = whoFrom.getInfo();\n\n State srcState = whoFrom.getState();\n\n State curState = getState();\n\n\n\n #ifdef DEBUG\n\n cout << \"===================================\" << endl;\n\n printCoord(\"I am cell \", r, c);\n\n printCoord(\"I was notified by \", r, c);\n\n\n\n cout << \"srcState has type \" << srcState.type;\n\n cout << \"srcState has color \" << srcState.colour; \n\n cout << \"srcState has direction \" << srcState.direction;\n\n cout << \"My color is \" << colour;\n\n #endif\n\n\n", "file_path": "WithComments/cell.cc", "rank": 28, "score": 13.472180593081482 }, { "content": "#include \"textdisplay.h\"\n\nusing namespace std;\n\n\n\n/* Ctor for TextDisplay */\n\nTextDisplay::TextDisplay(int n) : gridSize(n) {\n\n for (int i=0; i<gridSize; ++i) {\n\n theDisplay.emplace_back(vector<char>());\n\n for (int j=0; j<gridSize; ++j) {\n\n theDisplay[i].emplace_back('-');\n\n }\n\n }\n\n}\n\n\n\n\n\n/* When notified, getInfo() and update the corresponding char */\n\nvoid TextDisplay::notify(Subject<Info,State> &whoNotified) {\n\n Info i = whoNotified.getInfo();\n\n if (i.colour == Colour::Black) {\n\n theDisplay[i.row][i.col] = 'B';\n\n } else { \n", "file_path": "WithComments/textdisplay.cc", "rank": 29, "score": 13.4680603380983 }, { "content": " for (size_t j=0; j<dim; ++j) {\n\n theGrid[i][j].setPiece(Colour::NoColour);\n\n }\n\n }\n\n}\n\n\n\nvoid Grid::setPiece(size_t r, size_t c, Colour colour) {\n\n reset(); \n\n if ((r >= dim) || (c >= dim)) { \n\n throw \"\";\n\n return;\n\n }\n\n\n\n theGrid[r][c].setPiece(colour);\n\n if (colour != Colour::NoColour) updateCounter();\n\n} \n\n\n\nint count(string s, char c) {\n\n size_t x = 0, len = s.size();\n\n for (size_t i=0; i<len; ++i) {\n", "file_path": "grid.cc", "rank": 30, "score": 13.39015395433961 }, { "content": " friend std::ostream &operator<<(std::ostream &out, const Grid &g);\n\n\n\n ~Grid();\n\n \n\n #ifdef DEBUG\n\n void print() {\n\n std::cout << \"#Black: \" << black << std::endl;\n\n std::cout << \"#White: \" << white << std::endl;\n\n std::cout << std::endl;\n\n }\n\n #endif\n\n};\n\n\n\n#endif\n", "file_path": "WithComments/grid.h", "rank": 31, "score": 12.950636401492067 }, { "content": " friend std::ostream &operator<<(std::ostream &out, const Grid &g);\n\n\n\n ~Grid();\n\n \n\n #ifdef DEBUG\n\n void print() {\n\n std::cout << \"#Black: \" << black << std::endl;\n\n std::cout << \"#White: \" << white << std::endl;\n\n std::cout << std::endl;\n\n }\n\n #endif\n\n};\n\n\n\n#endif\n", "file_path": "grid.h", "rank": 32, "score": 12.950636401492067 }, { "content": "#include \"cell.h\"\n\n#include <string>\n\nusing namespace std;\n\n\n\n// #define DEBUG\n\n\n\n/* Local helper: Given two Info objects, determine the direction */\n\nDirection getDir(Info cur, Info src) {\n\n int rDiff = cur.row - src.row;\n\n int cDiff = cur.col - src.col;\n\n switch (rDiff) {\n\n case -1: // cur one row above src\n\n switch (cDiff) {\n\n case -1: return Direction::NW; break;\n\n case 0: return Direction::N; break;\n\n case 1: return Direction::NE; break;\n\n }\n\n case 0: // cur same row as src\n\n switch (cDiff) {\n\n case -1: return Direction::W; break;\n", "file_path": "WithComments/cell.cc", "rank": 33, "score": 12.23701730829658 }, { "content": "#include <X11/Xlib.h>\n\n#include <X11/Xutil.h>\n\n#include <iostream>\n\n#include <cstdlib>\n\n#include <string>\n\n#include <unistd.h>\n\n#include \"window.h\"\n\n\n\nusing namespace std;\n\n\n\nXwindow::Xwindow(int width, int height) {\n\n\n\n d = XOpenDisplay(NULL);\n\n if (d == NULL) {\n\n cerr << \"Cannot open display\" << endl;\n\n exit(1);\n\n }\n\n s = DefaultScreen(d);\n\n w = XCreateSimpleWindow(d, RootWindow(d, s), 10, 10, width, height, 1,\n\n BlackPixel(d, s), WhitePixel(d, s));\n", "file_path": "WithComments/window.cc", "rank": 34, "score": 12.070782820234689 }, { "content": "#include <X11/Xlib.h>\n\n#include <X11/Xutil.h>\n\n#include <iostream>\n\n#include <cstdlib>\n\n#include <string>\n\n#include <unistd.h>\n\n#include \"window.h\"\n\n\n\nusing namespace std;\n\n\n\nXwindow::Xwindow(int width, int height) {\n\n\n\n d = XOpenDisplay(NULL);\n\n if (d == NULL) {\n\n cerr << \"Cannot open display\" << endl;\n\n exit(1);\n\n }\n\n s = DefaultScreen(d);\n\n w = XCreateSimpleWindow(d, RootWindow(d, s), 10, 10, width, height, 1,\n\n BlackPixel(d, s), WhitePixel(d, s));\n", "file_path": "window.cc", "rank": 35, "score": 12.070782820234687 }, { "content": "#include \"cell.h\"\n\n#include <string>\n\nusing namespace std;\n\n\n\nDirection getDir(Info cur, Info src) {\n\n int rDiff = cur.row - src.row;\n\n int cDiff = cur.col - src.col;\n\n switch (rDiff) {\n\n case -1: \n\n switch (cDiff) {\n\n case -1: return Direction::NW; break;\n\n case 0: return Direction::N; break;\n\n case 1: return Direction::NE; break;\n\n }\n\n case 0: \n\n switch (cDiff) {\n\n case -1: return Direction::W; break;\n\n case 1: return Direction::E; break;\n\n }\n\n case 1: \n", "file_path": "cell.cc", "rank": 36, "score": 11.930252956931302 }, { "content": " * pass the srcState information, including color and direction,\n\n * to my observers. My type would stay relay.\n\n */\n\n else {\n\n\n\n // If the source is a newPiece, then its direction is garbage,\n\n // The direction I calculated for myself is the correct one.\n\n // However if the source is relay, I must copy its direction.\n\n if (srcState.type != StateType::NewPiece) {\n\n curState.direction = srcState.direction;\n\n }\n\n curState.colour = srcState.colour;\n\n curState.type = StateType::Relay;\n\n setState(curState);\n\n notifyObservers();\n\n\n\n #ifdef DEBUG\n\n cout << \"Sorry, I don't have the color you want.\" << endl;\n\n cout << \"I'll notify my neighbors and help you!\" << endl;\n\n cout << \"I updated state direction to: \" << curState.direction;\n", "file_path": "WithComments/cell.cc", "rank": 37, "score": 11.757533913342892 }, { "content": " cout << endl;\n\n cout << \"My direction with respect to the source is \" << myDir;\n\n cout << \"But the source direction is \" << srcState.direction;\n\n cout << \"Terminate.\" << endl;\n\n #endif\n\n\n\n return;\n\n }\n\n\n\n // Termination condition 2. I am not initialized (I have no color).\n\n if (colour == Colour::NoColour) {\n\n\n\n #ifdef DEBUG\n\n cout << \"I am not initialized yet. Terminate.\" << endl;\n\n #endif\n\n\n\n return;\n\n }\n\n\n\n // Termination condition 3. I am the newPiece. \n", "file_path": "WithComments/cell.cc", "rank": 39, "score": 11.562016648548251 }, { "content": "\n\nvoid Xwindow::fillRectangle(int x, int y, int width, int height, int colour) {\n\n XSetForeground(d, gc, colours[colour]);\n\n XFillRectangle(d, w, gc, x, y, width, height);\n\n XSetForeground(d, gc, colours[Black]);\n\n}\n\n\n\nvoid Xwindow::drawString(int x, int y, string msg) {\n\n XDrawString(d, w, DefaultGC(d, s), x, y, msg.c_str(), msg.length());\n\n}\n\n\n", "file_path": "window.cc", "rank": 41, "score": 10.878960720480235 }, { "content": "\n\nvoid Xwindow::fillRectangle(int x, int y, int width, int height, int colour) {\n\n XSetForeground(d, gc, colours[colour]);\n\n XFillRectangle(d, w, gc, x, y, width, height);\n\n XSetForeground(d, gc, colours[Black]);\n\n}\n\n\n\nvoid Xwindow::drawString(int x, int y, string msg) {\n\n XDrawString(d, w, DefaultGC(d, s), x, y, msg.c_str(), msg.length());\n\n}\n\n\n", "file_path": "WithComments/window.cc", "rank": 42, "score": 10.878960720480235 }, { "content": " if (((r-1) >= 0) && ((c-1) >= 0)) theGrid[r][c].attach(&theGrid[r-1][c-1]);\n\n if ((r-1) >= 0) theGrid[r][c].attach(&theGrid[r-1][c]);\n\n if (((r-1) >= 0) && ((c+1) <= d-1)) theGrid[r][c].attach(&theGrid[r-1][c+1]);\n\n if ((c+1) <= d-1) theGrid[r][c].attach(&theGrid[r][c+1]);\n\n if (((r+1) <= d-1) && ((c+1) <= d-1)) theGrid[r][c].attach(&theGrid[r+1][c+1]);\n\n if ((r+1) <= d-1) theGrid[r][c].attach(&theGrid[r+1][c]);\n\n if (((r+1) <= d-1) && ((c-1) >= 0)) theGrid[r][c].attach(&theGrid[r+1][c-1]);\n\n if ((c-1) >= 0) theGrid[r][c].attach(&theGrid[r][c-1]);\n\n}\n\n\n\nvoid Grid::setObserver(Observer<Info, State> *ob) {\n\n for (size_t i=0; i<dim; ++i) {\n\n for (size_t j=0; j<dim; ++j) {\n\n theGrid[i][j].attach(ob);\n\n }\n\n }\n\n}\n\n\n\nvoid Grid::reset() {\n\n for (size_t i=0; i<dim; ++i) {\n", "file_path": "grid.cc", "rank": 43, "score": 10.838466163905064 }, { "content": "\n\n else {\n\n this->colour = colour;\n\n State s;\n\n s.direction = Direction::N;\n\n s.colour = colour;\n\n s.type = StateType::NewPiece;\n\n setState(s);\n\n notifyObservers();\n\n }\n\n}\n\n\n\nvoid Cell::notify(Subject <Info, State> &whoFrom) {\n\n\n\n Info srcInfo = whoFrom.getInfo();\n\n State srcState = whoFrom.getState();\n\n State curState = getState();\n\n\n\n Direction myDir = getDir(getInfo(), srcInfo);\n\n\n", "file_path": "cell.cc", "rank": 44, "score": 10.815457605298068 }, { "content": " if (curState.type == StateType::NewPiece) {\n\n\n\n #ifdef DEBUG\n\n cout << \"I am a new piece. Terminate.\" << endl;\n\n #endif\n\n \n\n return;\n\n }\n\n\n\n // Termination condition 4. I have reply type.\n\n // This indicates my job in this round of game has been completed.\n\n if (curState.type == StateType::Reply) {\n\n\n\n #ifdef DEBUG\n\n cout << \"I have replied already. Terminate.\" << endl;\n\n #endif\n\n \n\n return;\n\n }\n\n\n", "file_path": "WithComments/cell.cc", "rank": 46, "score": 10.722795849315148 }, { "content": " cout << \"I updated state type to: \" << curState.type;\n\n cout << \"I updated state color to: \" << curState.colour;\n\n #endif\n\n }\n\n } \n\n\n\n /* Now we are backtracking. The source has a state reply. All we need \n\n * to do is to update my state to reply (since I know that I am the \n\n * cell on the right direction). I want to pass the reply back until I \n\n * reach the newPiece. Note that I notified my observers first before\n\n * changing color. This is just to make sure that I first get back to\n\n * the new piece before dirty recursion starts. toggle() would set me\n\n * to type newPiece and see if my update would influence other cells\n\n * on the board. */\n\n else {\n\n setState(srcState);\n\n\n\n #ifdef DEBUG\n\n cout << \"Backtracking.\" << endl;\n\n cout << \"I'll notify my neighbors until get to the new piece\" << endl;\n", "file_path": "WithComments/cell.cc", "rank": 47, "score": 10.546492888825608 }, { "content": "void Cell::toggle() {\n\n if (colour == Colour::Black) colour = Colour::White;\n\n else colour = Colour::Black;\n\n}\n\n\n\n\n\nvoid Cell::setPiece(Colour colour) {\n\n\n\n if (colour == Colour::NoColour) {\n\n State s;\n\n s.type = StateType::Relay;\n\n s.colour = this->colour;\n\n s.direction = Direction::N;\n\n setState(s);\n\n }\n\n\n\n else if (this->colour != Colour::NoColour) {\n\n throw \"\";\n\n return;\n\n }\n", "file_path": "cell.cc", "rank": 48, "score": 10.3432888897929 }, { "content": "\n\n if (cmd == \"new\") {\n\n int n; cin >> n;\n\n if ((n >= 4) && (n % 2 == 0)) {\n\n g.init(n);\n\n cout << g;\n\n }\n\n }\n\n else if (cmd == \"play\") {\n\n int r = 0, c = 0;\n\n cin >> r >> c;\n\n if (black) {\n\n try {\n\n g.setPiece(r, c, Colour::Black);\n\n black = false;\n\n cout << g;\n\n } catch ( ... ) {\n\n continue;\n\n } \n\n } else {\n", "file_path": "main.cc", "rank": 49, "score": 10.07793783323276 }, { "content": " cin >> cmd;\n\n\n\n // creating a new game\n\n if (cmd == \"new\") {\n\n int n; cin >> n;\n\n\n\n // input validation on dimension\n\n if ((n >= 4) && (n % 2 == 0)) {\n\n g.init(n);\n\n cout << g;\n\n }\n\n }\n\n\n\n // play a new piece\n\n else if (cmd == \"play\") {\n\n int r = 0, c = 0;\n\n cin >> r >> c;\n\n if (black) {\n\n try {\n\n g.setPiece(r, c, Colour::Black);\n", "file_path": "WithComments/main.cc", "rank": 50, "score": 9.669369010676188 }, { "content": "\n\n curState.direction = myDir;\n\n setState(curState);\n\n\n\n #ifdef DEBUG\n\n cout << \"I am called by a newPiece.\";\n\n cout << \"Calculating and updating my direction.\" << endl;\n\n cout << \"Diretion for this round of search is: \" << curState.direction;\n\n #endif\n\n\n\n }\n\n\n\n /* 1.2 If the source is relaying, it means that srcState.direction is \n\n * computed already. We want to check whether the current cell is on\n\n * the desired direction. If not, return directly.\n\n */\n\n else if (myDir != srcState.direction) {\n\n\n\n #ifdef DEBUG\n\n cout << \"I am called by a relaying piece and I have wrong direction.\";\n", "file_path": "WithComments/cell.cc", "rank": 51, "score": 9.462503248691434 }, { "content": " * searching is over. We update our type to reply, reverse the \n\n * direction of propagation, and start backtracking. */\n\n if (colour == srcState.colour) {\n\n curState.direction = oppDir(myDir);\n\n curState.type = StateType::Reply;\n\n setState(curState);\n\n\n\n // I put notifyObservers() in each block in the if stmt.\n\n // These repetitions of code are for clarity. I'll optimize\n\n // my code in the clean version.\n\n notifyObservers(); \n\n\n\n #ifdef DEBUG\n\n cout << \"You found me! I have the same color as srcState!\" << endl;\n\n cout << \"Time to reverse the direction to: \" << curState.direction;\n\n cout << \"Time to update my type to: \" << curState.type;\n\n #endif\n\n }\n\n\n\n /* If I don't have the same color as srcState.color, we need to\n", "file_path": "WithComments/cell.cc", "rank": 52, "score": 8.65235636872896 }, { "content": " else return Colour::NoColour;\n\n}\n\n\n\nstd::ostream &operator<<(ostream &out, const Grid &g) {\n\n out << *(g.td);\n\n return out;\n\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "file_path": "grid.cc", "rank": 53, "score": 8.368477133800852 }, { "content": " cout << \"I updated state direction to: \" << srcState.direction;\n\n cout << \"I updated state type to: \" << srcState.type;\n\n cout << \"I updated state color to: \" << srcState.colour;\n\n #endif\n\n\n\n notifyObservers();\n\n toggle();\n\n\n\n \n\n }\n\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "file_path": "WithComments/cell.cc", "rank": 54, "score": 8.312146652054919 }, { "content": " if (srcState.type == StateType::NewPiece) {\n\n curState.direction = myDir;\n\n setState(curState);\n\n }\n\n\n\n else if (myDir != srcState.direction) return;\n\n\n\n if (colour == Colour::NoColour) return;\n\n\n\n if (curState.type == StateType::NewPiece) return;\n\n\n\n if (curState.type == StateType::Reply) return; \n\n\n\n if (srcState.type != StateType::Reply) {\n\n if (colour == srcState.colour) {\n\n curState.direction = oppDir(myDir);\n\n curState.type = StateType::Reply;\n\n setState(curState);\n\n notifyObservers(); \n\n } else {\n", "file_path": "cell.cc", "rank": 55, "score": 8.16959101737259 }, { "content": "#include \"graphicaldisplay.h\"\n\n\n\nGraphicalDisplay::GraphicalDisplay(int n) : gridSize(n), w{} {\n\n\tw.fillRectangle(0, 0, 500, 500, Xwindow::Blue);\n\n}\n\n\n\n/* \n\nrow, col: coordinates.\n\nlen: side length of each cell.\n\nI used double type because of the potential rounding errors.\n\nThe int type can support gridSize up to 32; after that the center seems to shift too \n\nmuch even human eyes can notice; double type fixes this problem.\n\n\n\nKnown bug: there might be a very small white box shows up on the bottom right corner.\n\nSometimes it appears and sometimes it does not. I have no clue why it happens.\n\nIf you see it, try to create a new game and see if it is still there.\n\nIf yes, rerun the executable. \n\n*/\n\n\n\nvoid GraphicalDisplay::notify(Subject<Info, State> &whoNotified) {\n", "file_path": "graphicaldisplay.cc", "rank": 57, "score": 8.042588073117486 }, { "content": "\n\n\n\nCell::Cell(size_t r, size_t c) : r(r), c(c) {\n\n State s;\n\n s.direction = Direction::N;\n\n s.colour = Colour::NoColour;\n\n s.type = StateType::Relay;\n\n setState(s);\n\n}\n\n\n\n\n\nInfo Cell::getInfo() const {\n\n Info i;\n\n i.row = r;\n\n i.col = c;\n\n i.colour = colour;\n\n return i;\n\n}\n\n\n\n\n", "file_path": "cell.cc", "rank": 58, "score": 8.005015536839661 }, { "content": "#ifndef _GRID_H_\n\n#define _GRID_H_\n\n\n\n#include <iostream>\n\n#include <vector>\n\n#include <cstddef>\n\n\n\n#include \"cell.h\"\n\n#include \"state.h\"\n\n#include \"info.h\"\n\n#include \"textdisplay.h\"\n\n\n\n// #define DEBUG\n\n\n\ntemplate <typename InfoType, typename StateType> class Observer;\n\n\n", "file_path": "WithComments/grid.h", "rank": 59, "score": 7.82000670870557 }, { "content": " if (srcState.type != StateType::NewPiece) {\n\n curState.direction = srcState.direction;\n\n }\n\n curState.colour = srcState.colour;\n\n curState.type = StateType::Relay;\n\n setState(curState);\n\n notifyObservers();\n\n }\n\n } \n\n else {\n\n setState(srcState);\n\n notifyObservers();\n\n toggle();\n\n }\n\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "file_path": "cell.cc", "rank": 60, "score": 7.42454531568915 }, { "content": " /* If we have reached this point, we know the following things:\n\n * 1. I am in the right direction and I should be notified.\n\n * 2. I must have type relay.\n\n * Our job now is to figure whether we are doing forward searching, i.e.\n\n * searching to see if there is a cell of the desired color in this line,\n\n * or are we doing backtrack, i.e. we have already found a cell that has\n\n * the desired color, and we are doing backward recursion, stop when reach\n\n * the original newPiece. To determine this, we shall check whoFrom's \n\n * type. If it is a newPiece or a relay, we are searching; if it is reply,\n\n * we are backtracking.\n\n */\n\n\n\n // Searching!\n\n if (srcState.type != StateType::Reply) {\n\n\n\n #ifdef DEBUG\n\n cout << \"Searching...\" << endl;\n\n #endif\n\n \n\n /* If I have the same color as the srcState.color, this round of \n", "file_path": "WithComments/cell.cc", "rank": 61, "score": 7.127101384908188 }, { "content": "\n\nstd::ostream &operator<<(std::ostream &out, const TextDisplay &td) {\n\n for (auto i=0; i<td.gridSize; ++i) {\n\n for (auto j=0; j<td.gridSize; ++j) {\n\n out << td.theDisplay[i][j];\n\n }\n\n out << endl;\n\n }\n\n return out;\n\n}\n\n\n", "file_path": "textdisplay.cc", "rank": 62, "score": 6.46676197741434 }, { "content": " try {\n\n g.setPiece(r, c, Colour::White);\n\n black = true;\n\n cout << g;\n\n } catch ( ... ) {\n\n continue;\n\n }\n\n }\n\n if (g.isFull()) break;\n\n }\n\n }\n\n\n\n Colour c = g.whoWon();\n\n if (c == Colour::Black) {\n\n cout << \"Black wins!\" << endl;\n\n } else if (c == Colour::White) {\n\n cout << \"White wins!\" << endl;\n\n } else {\n\n cout << \"Tie!\" << endl;\n\n }\n\n }\n\n catch (ios::failure &) {} \n\n}\n\n\n", "file_path": "main.cc", "rank": 63, "score": 6.1581016961946995 }, { "content": " theDisplay[i.row][i.col] = 'W';\n\n }\n\n}\n\n\n\n\n\n/* Overloading operator<< for TextDisplay */\n\nstd::ostream &operator<<(std::ostream &out, const TextDisplay &td) {\n\n for (auto i=0; i<td.gridSize; ++i) {\n\n for (auto j=0; j<td.gridSize; ++j) {\n\n out << td.theDisplay[i][j];\n\n }\n\n out << endl;\n\n }\n\n return out;\n\n}\n\n\n", "file_path": "WithComments/textdisplay.cc", "rank": 64, "score": 6.115223635054113 }, { "content": "#ifndef _GRID_H_\n\n#define _GRID_H_\n\n\n\n#include <iostream>\n\n#include <vector>\n\n#include <cstddef>\n\n\n\n#include \"cell.h\"\n\n#include \"state.h\"\n\n#include \"info.h\"\n\n#include \"textdisplay.h\"\n\n#include \"graphicaldisplay.h\"\n\n#include \"window.h\"\n\n\n\ntemplate <typename InfoType, typename StateType> class Observer;\n\n\n", "file_path": "grid.h", "rank": 65, "score": 5.936832648982243 }, { "content": " black = false;\n\n cout << g;\n\n } catch ( ... ) {\n\n continue;\n\n } \n\n } else {\n\n try {\n\n g.setPiece(r, c, Colour::White);\n\n black = true;\n\n cout << g;\n\n } catch ( ... ) {\n\n continue;\n\n }\n\n }\n\n if (g.isFull()) break;\n\n }\n\n }\n\n\n\n Colour c = g.whoWon();\n\n if (c == Colour::Black) {\n", "file_path": "WithComments/main.cc", "rank": 66, "score": 5.801655151834023 }, { "content": "#ifndef __WINDOW_H__\n\n#define __WINDOW_H__\n\n#include <X11/Xlib.h>\n\n#include <iostream>\n\n#include <string>\n\n\n", "file_path": "window.h", "rank": 67, "score": 5.799217454624828 }, { "content": "#ifndef __WINDOW_H__\n\n#define __WINDOW_H__\n\n#include <X11/Xlib.h>\n\n#include <iostream>\n\n#include <string>\n\n\n", "file_path": "WithComments/window.h", "rank": 68, "score": 5.799217454624828 }, { "content": "#ifndef _GRAPHICAL_\n\n#define _GRAPHICAL_\n\n\n\n#include \"window.h\"\n\n#include \"observer.h\"\n\n#include \"subject.h\"\n\n#include \"state.h\"\n\n#include \"info.h\"\n\n#include <iostream>\n\n#include <vector>\n\n\n", "file_path": "graphicaldisplay.h", "rank": 69, "score": 5.716555561248333 }, { "content": "#ifndef _TEXTDISPLAY_H_\n\n#define _TEXTDISPLAY_H_\n\n\n\n#include <iostream>\n\n#include <vector>\n\n#include \"observer.h\"\n\n#include \"state.h\"\n\n#include \"info.h\"\n\n#include \"subject.h\"\n\n\n", "file_path": "WithComments/textdisplay.h", "rank": 70, "score": 5.658170047684464 }, { "content": "#ifndef _TEXTDISPLAY_H_\n\n#define _TEXTDISPLAY_H_\n\n\n\n#include <iostream>\n\n#include <vector>\n\n#include \"observer.h\"\n\n#include \"state.h\"\n\n#include \"info.h\"\n\n#include \"subject.h\"\n\n\n", "file_path": "textdisplay.h", "rank": 71, "score": 5.658170047684464 }, { "content": "#ifndef _CELL_H_\n\n#define _CELL_H_\n\n\n\n#include <iostream>\n\n#include <cstddef>\n\n\n\n#include \"subject.h\"\n\n#include \"observer.h\"\n\n#include \"state.h\"\n\n#include \"info.h\"\n\n#include \"textdisplay.h\"\n\n\n", "file_path": "cell.h", "rank": 72, "score": 5.6327956940431765 }, { "content": "#ifndef _CELL_H_\n\n#define _CELL_H_\n\n\n\n#include <iostream>\n\n#include <cstddef>\n\n\n\n#include \"subject.h\"\n\n#include \"observer.h\"\n\n#include \"state.h\"\n\n#include \"info.h\"\n\n#include \"textdisplay.h\"\n\n\n", "file_path": "WithComments/cell.h", "rank": 73, "score": 5.6327956940431765 }, { "content": " cout << \"Black wins!\" << endl;\n\n } else if (c == Colour::White) {\n\n cout << \"White wins!\" << endl;\n\n } else {\n\n cout << \"Tie!\" << endl;\n\n }\n\n }\n\n catch (ios::failure &) {} // Any I/O failure quits\n\n}\n\n\n", "file_path": "WithComments/main.cc", "rank": 74, "score": 5.429023743316813 }, { "content": "}\n\n\n\n\n\n/* Trivial */\n\nInfo Cell::getInfo() const {\n\n Info i;\n\n i.row = r;\n\n i.col = c;\n\n i.colour = colour;\n\n return i;\n\n}\n\n\n\n\n\n/* Flip the color of current cell, 2nd important cell-level function */\n\nvoid Cell::toggle() {\n\n\n\n /* First, flip color */\n\n if (colour == Colour::Black) {\n\n colour = Colour::White;\n\n } else {\n", "file_path": "WithComments/cell.cc", "rank": 75, "score": 4.9129514297426224 }, { "content": "\n\n // Termination condition 1. Wrong direction\n\n // 1.0 First, which direction am I in wich respect to the source?\n\n Direction myDir = getDir(getInfo(), srcInfo);\n\n\n\n /* 1.1 If the source is a newPiece, we have the following conclusion\n\n * a) I am within 1 unit of distance with the newPiece.\n\n * b) We are starting a new round of search and the srcState.direction\n\n * is garbage value. \n\n * Therefore, my direction with respect to the source determines \n\n * which direction we want to go. For example, if my left adjacent cell\n\n * is a newPiece and I got notified, it means we are searching towards its\n\n * right (Direction::E) in this round, i.e.e want to check if there exists\n\n * a cell with color equals to srcState.color on my right. Thus, I want\n\n * to update my direction so that when I notify my observers, only the\n\n * cell to the right of me would have the matching direction; others\n\n * will be ignored. This is the basic idea of my cell-level recursion.\n\n */\n\n\n\n if (srcState.type == StateType::NewPiece) {\n", "file_path": "WithComments/cell.cc", "rank": 76, "score": 4.851355748887421 }, { "content": "## Reversi in C++\n\n\n\n#### Rules\n\n> https://en.wikipedia.org/wiki/Reversi.\n\n\n\n#### Requirement\n\n\n\n- C++\n\n- GNU Make\n\n- X11/Xlib\n\n\n\n#### Download/Install\n\n\n\n- Download and unzip, then `cd` into directory.\n\n- Execute makefile command: `make`.\n\n- Run: `./reversi`.\n\n- Follow instruction and have fun ;)\n\n\n\n#### Instructions\n\n\n\n- Create a new game: `new n`, where `n` is the size of board.\n\n- Play a piece: `play r c`, where `(r, c)` represents the coordinate.\n\n\n\n\n\n#### Technical notes\n\n\n\n- Observer Pattern\n", "file_path": "README.md", "rank": 77, "score": 4.805017023969558 }, { "content": "Dear instructor:\n\n\n\ntl;dr: \tPlease go to folder \"WithComments\" and read files there.\n\n\n\nFull:\n\n\tThe files in the root directory (aka here) are written \n\n\tvery concisely and may not be easily understood. Since\n\n\tQ4 is quite long and there are many different ways to\n\n\tsolve the problem (which makes your hand-marking process\n\n\ta great pain), I have provided an extra version of my \n\n\tassignment that has a lot of debugging functions, that\n\n\thopefully can help you understand my implementation\n\n\tfaster and make the process less painful. \n\n\n\n\tTo see how the algorithm works, uncomment the line\n\n\t\"#define DEBUG\" in every file, re-compile, and run the\n\n\texecutable. There should be enough information printed\n\n\ton the screen (along with the comments in the source\n\n\tfile) to save you some time understanding my code.\n\n\n\nThank you and have a nice day!\n\n\n\nDavid\n\n\n", "file_path": "DEARINSTRUCTOR.cc", "rank": 79, "score": 3.1041557325948723 }, { "content": " XSelectInput(d, w, ExposureMask | KeyPressMask);\n\n XMapRaised(d, w);\n\n\n\n Pixmap pix = XCreatePixmap(d,w,width,\n\n height,DefaultDepth(d,DefaultScreen(d)));\n\n gc = XCreateGC(d, pix, 0,(XGCValues *)0);\n\n\n\n XFlush(d);\n\n XFlush(d);\n\n\n\n // Set up colours.\n\n XColor xcolour;\n\n Colormap cmap;\n\n char color_vals[7][10]={\"white\", \"black\", \"red\", \"green\", \"blue\"};\n\n\n\n cmap=DefaultColormap(d,DefaultScreen(d));\n\n for(int i=0; i < 5; ++i) {\n\n XParseColor(d,cmap,color_vals[i],&xcolour);\n\n XAllocColor(d,cmap,&xcolour);\n\n colours[i]=xcolour.pixel;\n", "file_path": "WithComments/window.cc", "rank": 80, "score": 3.0797861408687526 }, { "content": " XSelectInput(d, w, ExposureMask | KeyPressMask);\n\n XMapRaised(d, w);\n\n\n\n Pixmap pix = XCreatePixmap(d,w,width,\n\n height,DefaultDepth(d,DefaultScreen(d)));\n\n gc = XCreateGC(d, pix, 0,(XGCValues *)0);\n\n\n\n XFlush(d);\n\n XFlush(d);\n\n\n\n // Set up colours.\n\n XColor xcolour;\n\n Colormap cmap;\n\n char color_vals[7][10]={\"white\", \"black\", \"red\", \"green\", \"blue\"};\n\n\n\n cmap=DefaultColormap(d,DefaultScreen(d));\n\n for(int i=0; i < 5; ++i) {\n\n XParseColor(d,cmap,color_vals[i],&xcolour);\n\n XAllocColor(d,cmap,&xcolour);\n\n colours[i]=xcolour.pixel;\n", "file_path": "window.cc", "rank": 81, "score": 3.0797861408687526 }, { "content": "\tInfo i = whoNotified.getInfo();\n\n\tdouble row = i.row;\n\n\tdouble col = i.col;\n\n\tdouble len = 500.0 / gridSize;\n\n\tif (i.colour == Colour::Black) {\n\n\t\tw.fillRectangle(col*len, row*len, len, len, Xwindow::Black);\n\n\t} else if (i.colour == Colour::White) {\n\n\t\tw.fillRectangle(col*len, row*len, len, len, Xwindow::White);\n\n\t}\n\n}\n\n\n", "file_path": "graphicaldisplay.cc", "rank": 82, "score": 2.7080625182194145 }, { "content": " }\n\n\n\n XSetForeground(d,gc,colours[Black]);\n\n\n\n // Make window non-resizeable.\n\n XSizeHints hints;\n\n hints.flags = (USPosition | PSize | PMinSize | PMaxSize );\n\n hints.height = hints.base_height = hints.min_height = hints.max_height = height;\n\n hints.width = hints.base_width = hints.min_width = hints.max_width = width;\n\n XSetNormalHints(d, w, &hints);\n\n\n\n XSynchronize(d,True);\n\n\n\n usleep(1000);\n\n}\n\n\n\nXwindow::~Xwindow() {\n\n XFreeGC(d, gc);\n\n XCloseDisplay(d);\n\n}\n", "file_path": "WithComments/window.cc", "rank": 83, "score": 2.584634091190717 }, { "content": " }\n\n\n\n XSetForeground(d,gc,colours[Black]);\n\n\n\n // Make window non-resizeable.\n\n XSizeHints hints;\n\n hints.flags = (USPosition | PSize | PMinSize | PMaxSize );\n\n hints.height = hints.base_height = hints.min_height = hints.max_height = height;\n\n hints.width = hints.base_width = hints.min_width = hints.max_width = width;\n\n XSetNormalHints(d, w, &hints);\n\n\n\n XSynchronize(d,True);\n\n\n\n usleep(1000);\n\n}\n\n\n\nXwindow::~Xwindow() {\n\n XFreeGC(d, gc);\n\n XCloseDisplay(d);\n\n}\n", "file_path": "window.cc", "rank": 84, "score": 2.584634091190717 }, { "content": " switch (cDiff) {\n\n case -1: return Direction::SW; break;\n\n case 0: return Direction::S; break;\n\n case 1: return Direction::SE; break;\n\n }\n\n default: throw;\n\n }\n\n}\n\n\n\n\n\nDirection oppDir(Direction d) {\n\n if (d == Direction::N) return Direction::S;\n\n else if (d == Direction::NE) return Direction::SW;\n\n else if (d == Direction::E) return Direction::W;\n\n else if (d == Direction::SE) return Direction::NW;\n\n else if (d == Direction::S) return Direction::N;\n\n else if (d == Direction::SW) return Direction::NE;\n\n else if (d == Direction::W) return Direction::E;\n\n else return Direction::SE;\n\n}\n", "file_path": "cell.cc", "rank": 85, "score": 2.3410942071433656 }, { "content": "#ifndef _OBSERVER_H_\n\n#define _OBSERVER_H_\n\n\n\ntemplate <typename InfoType, typename StateType> class Subject;\n", "file_path": "observer.h", "rank": 86, "score": 2.2346999411819204 }, { "content": " case 1: return Direction::E; break;\n\n }\n\n case 1: // cur one row below src\n\n switch (cDiff) {\n\n case -1: return Direction::SW; break;\n\n case 0: return Direction::S; break;\n\n case 1: return Direction::SE; break;\n\n }\n\n default:\n\n throw \"shouldn't get here!\";\n\n }\n\n}\n\n\n\n/* Local helper: Given a direction, determine the opposite direction */\n\nDirection oppDir(Direction d) {\n\n if (d == Direction::N) return Direction::S;\n\n else if (d == Direction::NE) return Direction::SW;\n\n else if (d == Direction::E) return Direction::W;\n\n else if (d == Direction::SE) return Direction::NW;\n\n else if (d == Direction::S) return Direction::N;\n", "file_path": "WithComments/cell.cc", "rank": 87, "score": 2.2127864294702757 }, { "content": "#ifndef _OBSERVER_H_\n\n#define _OBSERVER_H_\n\n\n\n// DO NOT MODIFY THIS FILE!\n\n\n\ntemplate <typename InfoType, typename StateType> class Subject;\n", "file_path": "WithComments/observer.h", "rank": 88, "score": 2.167273865134369 } ]
C++
src/control.hpp
Gypsophino-dev/Gypsophino
484325bd5db36d99cdc13048646695b94f656111
#pragma once #include "const.hpp" #include "shape.hpp" #include <array> #include <raylib.h> #include <string> #include <utility> #include <vector> namespace gyp { enum button_status { normal, hover, pressed }; template <class callback_type> class button : public rectangle { private: button_status status{}; std::array<Color, 3> color{}; std::array<Image, 3> image{}; std::array<Color, 3> tint{}; std::array<std::string, 3> text{}; std::array<callback_type, 4> call_back{}; float font_size{}; float spacing{}; Font font{}; public: button(); button(int pos_x, int pos_y, int width, int height); button(int pos_x, int pos_y, int width, int height, const std::string &text, float font_size = DEFAULT_FONT_SIZE); button(int pos_x, int pos_y, int width, int height, std::array<std::string, 3> text, float font_size = DEFAULT_FONT_SIZE); ~button() = default; void set_geometry(int pos_x, int pos_y, int width, int height); void set_color(std::array<Color, 3> background, std::array<Color, 3> foreground); void set_text(Font font, float font_size, float spacing, std::array<std::string, 3> &&text); void set_status(button_status stat); void set_call_back(std::array<callback_type, 4> call_back); button_status get_status(); void draw(); void draw(button_status status); callback_type interact(Vector2 mouse); }; template <class callback_type> button<callback_type>::button() : status(normal) { set_color(std::array<Color, 3>{BLACK, GRAY, BLUE}, std::array<Color, 3>{WHITE, WHITE, WHITE}); set_text(GetFontDefault(), DEFAULT_FONT_SIZE, DEFAULT_FONT_SPACING, std::array<std::string, 3>{"Text", "Text", "Text"}); } template <class callback_type> button<callback_type>::button(int pos_x, int pos_y, int width, int height) : status(normal) { set_geometry(pos_x, pos_y, width, height); set_color(std::array<Color, 3>{BLACK, GRAY, BLUE}, std::array<Color, 3>{WHITE, WHITE, WHITE}); set_text(GetFontDefault(), DEFAULT_FONT_SIZE, DEFAULT_FONT_SPACING, std::array<std::string, 3>{"Text", "Text", "Text"}); } template <class callback_type> button<callback_type>::button(int pos_x, int pos_y, int width, int height, const std::string &text, float font_size) : status(normal) { set_geometry(pos_x, pos_y, width, height); set_color(std::array<Color, 3>{BLACK, GRAY, BLUE}, std::array<Color, 3>{WHITE, WHITE, WHITE}); set_text(GetFontDefault(), font_size, DEFAULT_FONT_SPACING, std::array<std::string, 3>{text, text, text}); } template <class callback_type> button<callback_type>::button(int pos_x, int pos_y, int width, int height, std::array<std::string, 3> text, float font_size) : status(normal), text(std::move(text)) { set_geometry(pos_x, pos_y, width, height); set_color(std::array<Color, 3>{BLACK, GRAY, BLUE}, std::array<Color, 3>{WHITE, WHITE, WHITE}); set_text(GetFontDefault(), font_size, DEFAULT_FONT_SPACING, std::move(text)); } template <class callback_type> void button<callback_type>::set_geometry(int pos_x, int pos_y, int width, int height) { x = pos_x; y = pos_y; this->width = width; this->height = height; } template <class callback_type> void button<callback_type>::set_color(std::array<Color, 3> background, std::array<Color, 3> foreground) { color = background; tint = foreground; } template <class callback_type> void button<callback_type>::set_text(Font font, float font_size, float spacing, std::array<std::string, 3> &&text) { this->font = font; this->font_size = font_size; this->spacing = spacing; this->text = std::move(text); } template <class callback_type> void button<callback_type>::set_status(button_status stat) { status = stat; } template <class callback_type> void button<callback_type>::set_call_back( std::array<callback_type, 4> call_back) { this->call_back = call_back; } template <class callback_type> button_status button<callback_type>::get_status() { return status; } template <class callback_type> void button<callback_type>::draw() { draw(status); } template <class callback_type> void button<callback_type>::draw(button_status stat) { DrawRectangle(x, y, width, height, color.at(stat)); Vector2 text_size = MeasureTextEx(font, text.at(stat).c_str(), font_size, spacing); text_size.x /= -2; text_size.y /= -2; text_size.x += x + width / 2; text_size.y += y + height / 2; DrawTextEx(font, text.at(stat).c_str(), text_size, font_size, spacing, tint.at(stat)); } template <class callback_type> callback_type button<callback_type>::interact(Vector2 mouse) { int mx = static_cast<int>(mouse.x); int my = static_cast<int>(mouse.y); if (mx > x && mx < x + width && my > y && my < y + height) { status = hover; for (int i = 0; i <= 2; i++) { if (IsMouseButtonReleased(i)) { status = pressed; draw(); return call_back[i + 1]; } if (IsMouseButtonDown(i)) { status = pressed; } } draw(); return call_back[0]; } status = normal; draw(); return call_back[0]; } template <class callback_type> class timer { private: int count_down{}; std::array<callback_type, 2> call_back; public: timer() = default; explicit timer(int count_down); ~timer() = default; void set_count_down(int count_down); void set_call_back(std::array<callback_type, 2> call_back); void draw(); callback_type interact(); }; template <class callback_type> timer<callback_type>::timer(int count_down) : count_down(count_down) {} template <class callback_type> void timer<callback_type>::set_count_down(int count_down) { this->count_down = count_down; } template <class callback_type> void timer<callback_type>::set_call_back(std::array<callback_type, 2> call_back) { this->call_back = call_back; } template <class callback_type> void timer<callback_type>::draw() { count_down--; } template <class callback_type> callback_type timer<callback_type>::interact() { count_down--; if (count_down <= 0) { return call_back[1]; } return call_back[0]; } }
#pragma once #include "const.hpp" #include "shape.hpp" #include <array> #include <raylib.h> #include <string> #include <utility> #include <vector> namespace gyp { enum button_status { normal, hover, pressed }; template <class callback_type> class button : public rectangle { private: button_status status{}; std::array<Color, 3> color{}; std::array<Image, 3> image{}; std::array<Color, 3> tint{}; std::array<std::string, 3> text{}; std::array<callback_type, 4> call_back{}; float font_size{}; float spacing{}; Font font{}; public: button(); button(int pos_x, int pos_y, int width, int height); button(int pos_x, int pos_y, int width, int height, const std::string &text, float font_size = DEFAULT_FONT_SIZE); button(int pos_x, int pos_y, int width, int height, std::array<std::string, 3> text, float font_size = DEFAULT_FONT_SIZE); ~button() = default; void set_geometry(int pos_x, int pos_y, int width, int height); void set_color(std::array<Color, 3> background, std::array<Color, 3> foreground); void set_text(Font font, float font_size, float spacing, std::array<std::string, 3> &&text); void set_status(button_status stat); void set_call_back(std::array<callback_type, 4> call_back); button_status get_status(); void draw(); void draw(button_status status); callback_type interact(Vector2 mouse); }; template <class callback_type> button<callback_type>::button() : status(normal) { set_color(std::array<Color, 3>{BLACK, GRAY, BLUE}, std::array<Color, 3>{WHITE, WHITE, WHITE}); set_text(GetFontDefault(), DEFAULT_FONT_SIZE, DEFAULT_FONT_SPACING, std::array<std::string, 3>{"Text", "Text", "Text"}); } template <class callback_type> button<callback_type>::button(int pos_x, int pos_y, int width, int height) : status(normal) { set_geometry(pos_x, pos_y, width, height); set_color(std::array<Color, 3>{BLACK, GRAY, BLUE}, std::array<Color, 3>{WHITE, WHITE, WHITE}); set_text(GetFontDefault(), DEFAULT_FONT_SIZE, DEFAULT_FONT_SPACING, std::array<std::string, 3>{"Text", "Text", "Text"}); } template <class callback_type> button<callback_type>::button(int pos_x, int pos_y, int width, int height, const std::string &text, float font_size) : status(normal) { set_geometry(pos_x, pos_y, width, height); set_color(std::array<Color, 3>{BLACK, GRAY, BLUE}, std::array<Color, 3>{WHITE, WHITE, WHITE}); set_text(GetFontDefault(), font_size, DEFAULT_FONT_SPACING, std::array<std::string, 3>{text, text, text}); } template <class callback_type> button<callback_type>::button(int pos_x, int pos_y, int width, int height, std::array<std::string, 3> text, float font_size) : status(normal), text(std::move(text)) { set_geometry(pos_x, pos_y, width, height); set_color(std::array<Color, 3>{BLACK, GRAY, BLUE}, std::array<Color, 3>{WHITE, WHITE, WHITE}); set_text(GetFontDefault(), font_size, DEFAULT_FONT_SPACING, std::move(text)); } template <class callback_type> void button<callback_type>::set_geometry(int pos_x, int pos_y, int width, int height) { x = pos_x; y = pos_y; this->width = width; this->height = height; } template <class callback_type> void button<callback_type>::set_color(std::array<Color, 3> background, std::array<Color, 3> foreground) { color = background; tint = foreground; } template <class callback_type> void button<callback_type>::set_text(Font font, float font_size, float spacing, std::array<std::string, 3> &&text) { this->font = font; this->font_size = font_size; this->spacing = spacing; this->text = std::move(text); } template <class callback_type> void button<callback_type>::set_status(button_status stat) { status = stat; } template <class callback_type> void button<callback_type>::set_call_back( std::array<callback_type, 4> call_back) { this->call_back = call_back; } template <class callback_type> button_status button<callback_type>::get_status() { return status; } template <class callback_type> void button<callback_type>::draw() { draw(status); } template <class callback_type>
template <class callback_type> callback_type button<callback_type>::interact(Vector2 mouse) { int mx = static_cast<int>(mouse.x); int my = static_cast<int>(mouse.y); if (mx > x && mx < x + width && my > y && my < y + height) { status = hover; for (int i = 0; i <= 2; i++) { if (IsMouseButtonReleased(i)) { status = pressed; draw(); return call_back[i + 1]; } if (IsMouseButtonDown(i)) { status = pressed; } } draw(); return call_back[0]; } status = normal; draw(); return call_back[0]; } template <class callback_type> class timer { private: int count_down{}; std::array<callback_type, 2> call_back; public: timer() = default; explicit timer(int count_down); ~timer() = default; void set_count_down(int count_down); void set_call_back(std::array<callback_type, 2> call_back); void draw(); callback_type interact(); }; template <class callback_type> timer<callback_type>::timer(int count_down) : count_down(count_down) {} template <class callback_type> void timer<callback_type>::set_count_down(int count_down) { this->count_down = count_down; } template <class callback_type> void timer<callback_type>::set_call_back(std::array<callback_type, 2> call_back) { this->call_back = call_back; } template <class callback_type> void timer<callback_type>::draw() { count_down--; } template <class callback_type> callback_type timer<callback_type>::interact() { count_down--; if (count_down <= 0) { return call_back[1]; } return call_back[0]; } }
void button<callback_type>::draw(button_status stat) { DrawRectangle(x, y, width, height, color.at(stat)); Vector2 text_size = MeasureTextEx(font, text.at(stat).c_str(), font_size, spacing); text_size.x /= -2; text_size.y /= -2; text_size.x += x + width / 2; text_size.y += y + height / 2; DrawTextEx(font, text.at(stat).c_str(), text_size, font_size, spacing, tint.at(stat)); }
function_block-full_function
[ { "content": "class playground : public std::vector<track>, public rectangle {\n\nprivate:\n\n // Geometry\n\n int track_number;\n\n\n\n // Playground style\n\n Color outline;\n\n int thick;\n\n\n\n int current_time;\n\n int speed;\n\n const song_map *song;\n\n Music music;\n\n playground_status status;\n\n bool is_initialized;\n\n std::vector<std::vector<float>> real_notes;\n\n float total_score;\n\n\n\npublic:\n\n // Constructor & Desttructor\n", "file_path": "src/playground.hpp", "rank": 1, "score": 111644.67718249 }, { "content": "class container : public rectangle {\n\nprivate:\n\n std::array<std::unique_ptr<container>, 2> child;\n\n\n\npublic:\n\n int split_pos;\n\n int is_horizontal;\n\n container();\n\n container(const container &a);\n\n container(container &&a) noexcept;\n\n container(int pos_x, int pos_y, int width, int height);\n\n container(int pos_x, int pos_y, int width, int height, int split_pos,\n\n int is_horizontal);\n\n ~container();\n\n container &operator=(const container &a);\n\n container &operator=(container &&a);\n\n int split(int split_p, int is_h);\n\n};\n\n\n\n} // namespace gyp\n", "file_path": "src/basic.hpp", "rank": 2, "score": 90981.9735748751 }, { "content": "class cinema : public std::vector<scene *> {\n\n public:\n\n int prev_scene;\n\n int current_scene;\n\n int next_scene;\n\n cinema();\n\n ~cinema() = default;\n\n // Method\n\n void switch_to(int index);\n\n void switch_to(int from, int to);\n\n void play();\n\n};\n\n\n\n} // namespace gyp\n", "file_path": "src/scene.hpp", "rank": 3, "score": 90703.24632062769 }, { "content": "struct statue : public rectangle {\n\n Color color;\n\n Image image;\n\n std::string name;\n\n statue();\n\n ~statue();\n\n};\n\n\n", "file_path": "src/basic.hpp", "rank": 4, "score": 80070.58126267072 }, { "content": "class setting : public scene {\n\nprivate:\n\n std::vector<button<int>> button_list;\n\n window *window_call_back;\n\n\n\npublic:\n\n setting() = default;\n\n ~setting() = default;\n\n setting(std::vector<button<int>> button_list, window *window_call_back);\n\n // Setter\n\n void set_button_list(const std::vector<button<int>> &button_list);\n\n void set_window_call_back(window *window_call_back);\n\n // Method\n\n int interact_button_list();\n\n void enter() override;\n\n void draw() override;\n\n void leave() override;\n\n};\n\n\n\n} // namespace gyp\n", "file_path": "src/setting.hpp", "rank": 5, "score": 68605.17759959251 }, { "content": "class note : public sprite {\n\npublic:\n\n int hit_time; // In us\n\n note();\n\n note(int hit_time, int speed);\n\n ~note() = default;\n\n void draw();\n\n};\n\n\n", "file_path": "src/note.hpp", "rank": 6, "score": 68605.17759959251 }, { "content": "class titlepage : public scene {\n\nprivate:\n\n Font font{};\n\n float font_size{};\n\n float spacing{};\n\n Color font_color{};\n\n std::string title;\n\n std::vector<button<int>> button_list;\n\n\n\npublic:\n\n titlepage() = default;\n\n ~titlepage() = default;\n\n explicit titlepage(std::string title);\n\n // void set_button_list(const button& style, std::vector<std::string>&&\n\n // string_list);\n\n // Setter\n\n void set_button_list(std::vector<button<int>> &&button_list);\n\n void set_title(const std::string& title, Font font, float font_size, float spacing, Color font_color);\n\n // Method\n\n int interact_button_list();\n\n void draw() override;\n\n};\n\n\n\n} // namespace gyp\n", "file_path": "src/titlepage.hpp", "rank": 7, "score": 68605.17759959251 }, { "content": "class game : public scene {\n\n // A ultimately bit class which will contain everything except story and\n\n // settings, song selection\n\nprivate:\n\n song_map_db song_database;\n\n bool is_paused;\n\n window* window_call_back;\n\n\n\npublic:\n\n playground plg;\n\n\n\n // Constructor & Destructor\n\n explicit game(const std::string& song_db_path, window* window_call_back);\n\n ~game() = default;\n\n // Setter\n\n void set_window_call_back(window* window_call_back);\n\n // Method\n\n void load(int song_index);\n\n void load(int song_index, int fps);\n\n int interact();\n\n void draw() override;\n\n};\n\n\n\n} // namespace gyp\n", "file_path": "src/game.hpp", "rank": 8, "score": 68605.17759959251 }, { "content": "class slideshow : public scene {\n\nprivate:\n\n timer<int> timeout;\n\n\n\npublic:\n\n slideshow();\n\n explicit slideshow(int timeout);\n\n ~slideshow() = default;\n\n // Setter\n\n void set_timeout(int timeout);\n\n void set_call_back(int before, int after);\n\n // Method\n\n void draw() override;\n\n};\n\n\n\n} // namespace gyp\n", "file_path": "src/slideshow.hpp", "rank": 9, "score": 68605.17759959251 }, { "content": "class rectangle {\n\npublic:\n\n int x;\n\n int y;\n\n int width;\n\n int height;\n\n rectangle();\n\n rectangle(int posX, int posY, int width, int height);\n\n// rectangle(const rectangle &a);\n\n// rectangle(rectangle &&a) noexcept;\n\n// rectangle &operator=(const rectangle &a);\n\n// rectangle &operator=(rectangle &&a);\n\n ~rectangle() = default;\n\n [[nodiscard]] Rectangle ray_rectangle() const;\n\n};\n\n\n", "file_path": "src/shape.hpp", "rank": 10, "score": 65171.644189223254 }, { "content": "class track : rectangle {\n\nprivate:\n\n using vci = std::vector<float>::const_iterator;\n\n // Track Style\n\n Color fill;\n\n Color outline;\n\n int thick;\n\n KeyboardKey bind_key;\n\n // Node Style\n\n note note_style;\n\n // Timing\n\n int current_time; // lower limit for note to display\n\n int visible_time; // upper limit for note to display\n\n int error_time; // max time difference\n\n // Speed (Setted by set_geometry())\n\n int speed;\n\n // Iterator\n\n bool is_iterator_set;\n\n vci notes_begin; // For drawing\n\n vci notes_end; // For drawing\n", "file_path": "src/track.hpp", "rank": 11, "score": 60041.44895431939 }, { "content": "struct sprite : public statue {\n\n vector2d velocity;\n\n sprite();\n\n ~sprite();\n\n void update(int t);\n\n};\n\n\n", "file_path": "src/basic.hpp", "rank": 12, "score": 57693.78528738815 }, { "content": "struct text {\n\nprivate:\n\n std::string content;\n\npublic:\n\n enum anchor {\n\n left_up,\n\n center_up,\n\n right_up,\n\n left,\n\n center,\n\n right,\n\n left_down,\n\n center_down,\n\n right_down,\n\n };\n\n vector2d pos;\n\n anchor anc;\n\n Font font;\n\n float size;\n\n float spacing;\n", "file_path": "src/text.hpp", "rank": 13, "score": 51690.0900844304 }, { "content": "class score {\n\nprivate:\n\n std::array<std::pair<std::string, double>, GRADE_KIND> letter_grade_table;\n\n std::string letter_grade;\n\n CalcFunc fn;\n\n\n\npublic:\n\n float total;\n\n float current;\n\n score() {\n\n letter_grade_table[0] = std::make_pair(std::string(\"D\"), 70);\n\n letter_grade_table[1] = std::make_pair(std::string(\"C\"), 80);\n\n letter_grade_table[2] = std::make_pair(std::string(\"B\"), 90);\n\n letter_grade_table[3] = std::make_pair(std::string(\"A\"), 95);\n\n letter_grade_table[4] = std::make_pair(std::string(\"S\"), 99);\n\n letter_grade_table[5] = std::make_pair(std::string(\"SS\"), 100);\n\n total = 0;\n\n current = 0;\n\n }\n\n ~score() = default;\n", "file_path": "src/score.hpp", "rank": 14, "score": 40021.90103473996 }, { "content": "class slide {\n\npublic:\n\n note start;\n\n note end;\n\n Color color;\n\n Image image;\n\n slide();\n\n ~slide();\n\n};\n\n\n\n} // namespace gyp\n", "file_path": "src/note.hpp", "rank": 15, "score": 40021.90103473996 }, { "content": "class scene {\n\nprotected:\n\n Texture background{};\n\n Color initial_color{};\n\n Color final_color{};\n\n int transient_length{}; // frame count for the whole transient effect\n\n int color_stop{}; // time between each change in color\n\n cinema* cinema_call_back{};\n\n\n\npublic:\n\n scene() = default;\n\n scene(Color initial_color, Color final_color, int transient_length,\n\n int color_stop);\n\n ~scene() = default;\n\n // Setter\n\n void set_background_image(const std::string & path);\n\n void set_transient(Color initial_color, Color final, int transient_length, int color_stop);\n\n void set_cinema_call_back(cinema * cinema_call_back);\n\n // Method\n\n virtual void enter();\n\n virtual void draw();\n\n virtual void leave();\n\n};\n\n\n\n//enum scene_list { title_page, settings, gaming, pausing, adventure };\n\n\n", "file_path": "src/scene.hpp", "rank": 16, "score": 40021.90103473996 }, { "content": "class window {\n\nprivate:\n\n int width;\n\n int height;\n\n std::string window_title;\n\n int fps;\n\n float volume;\n\n bool is_initialized;\n\n\n\npublic:\n\n window() = default;\n\n window(int width, int heigh, std::string window_title, int fps);\n\n ~window();\n\n // Setter\n\n void set_size(int width, int heigh);\n\n void set_title(const std::string& window_title);\n\n void set_fps(int fps);\n\n void set_volume(float volume);\n\n void change_volume(float delta);\n\n // Getter\n", "file_path": "src/window.hpp", "rank": 17, "score": 40021.90103473996 }, { "content": "class cinema;\n\n\n", "file_path": "src/scene.hpp", "rank": 18, "score": 40021.90103473996 }, { "content": "class parabolic_func {\n\nprivate:\n\n int error_time;\n\n\n\npublic:\n\n parabolic_func() = default;\n\n ~parabolic_func() = default;\n\n void set_error(int error_time);\n\n [[nodiscard]] int get_error() const;\n\n float operator()(int hit_time, int target_time) const;\n\n};\n\n\n\ntemplate <typename CalcFunc = parabolic_func>\n", "file_path": "src/score.hpp", "rank": 20, "score": 38595.28913249385 }, { "content": "class song_map {\n\npublic:\n\n int track_number;\n\n int bpm;\n\n int base_fraction;\n\n int difficulty;\n\n int song_duration; // In ms\n\n int object_count;\n\n float offset; // In ms\n\n std::string song_author;\n\n std::string name;\n\n std::string map_author;\n\n std::string difficulty_name;\n\n std::string music_path;\n\n std::vector<std::vector<int>> notes;\n\n song_map() = default;\n\n ~song_map() = default;\n\n void load(const std::string& filename);\n\n void save(const std::string& filename);\n\n};\n\n\n", "file_path": "src/song_map.hpp", "rank": 21, "score": 37325.97185651282 }, { "content": "class song_map_db {\n\nprivate:\n\n std::vector<std::pair<std::string, song_map>> content;\n\n\n\npublic:\n\n int song_map_number;\n\n song_map_db() = default;\n\n ~song_map_db() = default;\n\n void load(const std::string& filename);\n\n void save(const std::string& filename);\n\n void import_song_map(const char *path);\n\n template <typename Compare> void sort(Compare comp);\n\n song_map &operator[](size_t index);\n\n};\n\n\n\n} // namespace gyp\n", "file_path": "src/song_map.hpp", "rank": 22, "score": 36189.29405185836 }, { "content": "enum playground_status { playing, paused, not_running };\n\n\n", "file_path": "src/playground.hpp", "rank": 23, "score": 32658.803621254665 }, { "content": "#pragma once\n\n\n\n#include <raylib.h>\n\n#include <string>\n\n#include <array>\n\n\n\nnamespace gyp {\n\n\n\nconst int DEFAULT_WIDTH = 1920;\n\nconst int DEFAULT_HEIGHT = 1080;\n\nconst int DEFAULT_TRACK_NUM = 4;\n\nconst Color DEFAULT_FG = BLACK;\n\nconst Color DEFAULT_BG = BLANK;\n\nconst int DEFAULT_GEOMETRY = -1;\n\nconst int DEFAULT_THICKNESS = 5;\n\nconst int DEFAULT_SPEED = 10;\n\nconst float DEFAULT_FONT_SIZE = 20.0F;\n\nconst float DEFAULT_FONT_SPACING = 0.5F;\n\n//extern const std::string TOP_NAME;\n\nextern const char * TOP_NAME;\n\nextern const std::array<KeyboardKey, 9> DEFAULT_KEY_BINDING;\n\n\n\n} // namespace gyp\n", "file_path": "src/const.hpp", "rank": 24, "score": 26993.7451724134 }, { "content": "#include \"const.hpp\"\n\n\n\n#include <array>\n\n\n\nnamespace gyp {\n\n\n\n//const std::string TOP_NAME = \"Gypsophino\";\n\nconst char * TOP_NAME = \"Gypsophino\";\n\n\n\nconst std::array<KeyboardKey, 9> DEFAULT_KEY_BINDING = {\n\n KEY_A, KEY_S, KEY_D, KEY_F, KEY_SPACE, KEY_J, KEY_K, KEY_L, KEY_COMMA\n\n};\n\n\n\n} // namespace gyp\n", "file_path": "src/const.cpp", "rank": 25, "score": 26978.960197855373 }, { "content": " Color color;\n\n\n\n text();\n\n ~text();\n\n // Setter\n\n void set_content(const std::string& content);\n\n void draw();\n\n};\n\n\n\n} // namespace gyp\n", "file_path": "src/text.hpp", "rank": 26, "score": 26880.397484328645 }, { "content": "#include \"text.hpp\"\n\n\n\nnamespace gyp {\n\n\n\nvoid text::set_content(const std::string& content) {\n\n this->content = content;\n\n}\n\n\n\nvoid text::draw() {\n\n}\n\n\n\n} // namespace gyp\n", "file_path": "src/text.cpp", "rank": 27, "score": 26880.397419553236 }, { "content": "#pragma once\n\n\n\n#include \"shape.hpp\"\n\n\n\nnamespace gyp {\n\n\n", "file_path": "src/text.hpp", "rank": 28, "score": 26872.485010487362 }, { "content": " DEFAULT_HEIGHT / 2 - background.height / 2, WHITE);\n\n int ret = interact_button_list();\n\n /* No need to draw a title since it is embedded in the cover pic.\n\n DrawTextEx(font, title.c_str(),\n\n vector2d(DEFAULT_WIDTH / 2 - title_size.x / 2,\n\n DEFAULT_HEIGHT / 3 - title_size.y / 2)\n\n .ray_vector2d(),\n\n font_size, spacing, font_color);\n\n */\n\n EndDrawing();\n\n if (ret != -1) {\n\n return;\n\n }\n\n }\n\n}\n\n\n\n} // namespace gyp\n", "file_path": "src/titlepage.cpp", "rank": 34, "score": 30.01186152506745 }, { "content": " DrawRectangle(0, 0, gyp::DEFAULT_WIDTH, gyp::DEFAULT_HEIGHT, current_color);\n\n frame_count++;\n\n if (frame_count % color_stop == 0) {\n\n current_color = Fade(\n\n initial_color,\n\n 1.0F - alpha_step * static_cast<float>(frame_count / color_stop));\n\n }\n\n EndDrawing();\n\n }\n\n}\n\n\n\nvoid setting::draw() {\n\n while (!WindowShouldClose()) {\n\n BeginDrawing();\n\n ClearBackground(final_color);\n\n float current_volume = window_call_back->get_volume() * 100;\n\n std::string current_volume_str = std::to_string(static_cast<int>(std::round(current_volume)));\n\n vector2d current_volume_size(MeasureTextEx(GetFontDefault(), current_volume_str.c_str(), 20.0F, 1.5F));\n\n DrawTexture(background, DEFAULT_WIDTH / 2 - background.width / 2,\n\n DEFAULT_HEIGHT / 2 - background.height / 2, WHITE);\n", "file_path": "src/setting.cpp", "rank": 35, "score": 28.902532152636237 }, { "content": " test_game.set_cinema_call_back(&game_cinema);\n\n\n\n gyp::titlepage starter;\n\n std::vector<gyp::button<int>> button_initial_list;\n\n gyp::button<int> start_button;\n\n start_button.set_color(std::array<Color, 3>{WHITE, GRAY, BLACK}, std::array<Color, 3>{BLACK, BLACK, WHITE});\n\n start_button.set_geometry(gyp::DEFAULT_WIDTH * 25 / 32 - 100, (9 * gyp::DEFAULT_HEIGHT) / 16 - 50, 200, 100);\n\n start_button.set_status(gyp::normal);\n\n start_button.set_text(GetFontDefault(), 30.0F, 2.5F, std::array<std::string, 3>{\"Start\", \"Start\", \"Start\"});\n\n start_button.set_call_back(std::array<int, 4>{-1, 3, -1, -1});\n\n button_initial_list.push_back(start_button);\n\n start_button.set_geometry(gyp::DEFAULT_WIDTH * 25 / 32 - 100, (11 * gyp::DEFAULT_HEIGHT) / 16 - 50, 200, 100);\n\n start_button.set_text(GetFontDefault(), 30.0F, 2.5F, std::array<std::string, 3>{\"Settings\", \"Settings\", \"Settings\"});\n\n start_button.set_call_back(std::array<int, 4>{-1, 2, -1, -1});\n\n button_initial_list.push_back(start_button);\n\n start_button.set_geometry(gyp::DEFAULT_WIDTH * 25 / 32 - 100, (13 * gyp::DEFAULT_HEIGHT) / 16 - 50, 200, 100);\n\n start_button.set_text(GetFontDefault(), 30.0F, 2.5F, std::array<std::string, 3>{\"Quit\", \"Quit\", \"Quit\"});\n\n start_button.set_call_back(std::array<int, 4>{-1, 100, -1, -1});\n\n button_initial_list.push_back(start_button);\n\n starter.set_button_list(std::move(button_initial_list));\n", "file_path": "src/main.cpp", "rank": 36, "score": 28.44259153461521 }, { "content": " BeginDrawing();\n\n ClearBackground(final_color);\n\n DrawTexture(background, DEFAULT_WIDTH / 2 - background.width / 2,\n\n DEFAULT_HEIGHT / 2 - background.height / 2, WHITE);\n\n DrawRectangle(0, 0, gyp::DEFAULT_WIDTH, gyp::DEFAULT_HEIGHT, current_color);\n\n frame_count++;\n\n if (frame_count % color_stop == 0) {\n\n current_color = Fade(\n\n initial_color,\n\n 1.0F - alpha_step * static_cast<float>(frame_count / color_stop));\n\n }\n\n EndDrawing();\n\n }\n\n}\n\n\n\nvoid scene::draw() {}\n\n\n\nvoid scene::leave() {\n\n int frame_count = 0;\n\n float alpha_step = (1.0F) / static_cast<float>(transient_length) *\n", "file_path": "src/scene.cpp", "rank": 37, "score": 28.081999466005225 }, { "content": " Vector2 mouse_pos = GetMousePosition();\n\n for (auto &i : button_list) {\n\n int button_ret = i.interact(mouse_pos);\n\n if (button_ret != -1) {\n\n return button_ret;\n\n }\n\n }\n\n return -1;\n\n}\n\n\n\nvoid setting::enter() {\n\n int frame_count = 0;\n\n float alpha_step = (0.2F) / static_cast<float>(transient_length) *\n\n static_cast<float>(color_stop);\n\n Color current_color = Fade(initial_color, 1.0F);\n\n while (!WindowShouldClose() && frame_count < transient_length) {\n\n BeginDrawing();\n\n ClearBackground(final_color);\n\n DrawTexture(background, DEFAULT_WIDTH / 2 - background.width / 2,\n\n DEFAULT_HEIGHT / 2 - background.height / 2, WHITE);\n", "file_path": "src/setting.cpp", "rank": 38, "score": 27.75837915327424 }, { "content": "void setting::leave() {\n\n int frame_count = 0;\n\n float alpha_step = (1.0F) / static_cast<float>(transient_length) *\n\n static_cast<float>(color_stop);\n\n Color current_color = Fade(initial_color, 0.0F);\n\n while (!WindowShouldClose() && frame_count < transient_length) {\n\n BeginDrawing();\n\n ClearBackground(final_color);\n\n DrawTexture(background, DEFAULT_WIDTH / 2 - background.width / 2,\n\n DEFAULT_HEIGHT / 2 - background.height / 2, WHITE);\n\n DrawRectangle(0, 0, gyp::DEFAULT_WIDTH, gyp::DEFAULT_HEIGHT, current_color);\n\n frame_count++;\n\n if (frame_count % color_stop == 0) {\n\n current_color =\n\n Fade(initial_color,\n\n alpha_step * static_cast<float>(frame_count / color_stop));\n\n }\n\n EndDrawing();\n\n }\n\n}\n\n\n\n} // namespace gyp\n", "file_path": "src/setting.cpp", "rank": 39, "score": 27.56143629998663 }, { "content": "#include \"titlepage.hpp\"\n\n\n\n#include \"const.hpp\"\n\n#include \"shape.hpp\"\n\n\n\nnamespace gyp {\n\n\n\ntitlepage::titlepage(std::string title) : title(std::move(title)) {}\n\n\n\nvoid titlepage::set_button_list(std::vector<button<int>> &&button_list) {\n\n this->button_list = std::move(button_list);\n\n}\n\n\n\nvoid titlepage::set_title(const std::string &title, Font font, float font_size,\n\n float spacing, Color font_color) {\n\n this->title = title;\n\n this->font = font;\n\n this->font_size = font_size;\n\n this->spacing = spacing;\n\n this->font_color = font_color;\n", "file_path": "src/titlepage.cpp", "rank": 40, "score": 27.301150395469616 }, { "content": " static_cast<float>(color_stop);\n\n Color current_color = Fade(initial_color, 0.0F);\n\n while (!WindowShouldClose() && frame_count < transient_length) {\n\n BeginDrawing();\n\n ClearBackground(final_color);\n\n DrawTexture(background, DEFAULT_WIDTH / 2 - background.width / 2,\n\n DEFAULT_HEIGHT / 2 - background.height / 2, WHITE);\n\n DrawRectangle(0, 0, gyp::DEFAULT_WIDTH, gyp::DEFAULT_HEIGHT, current_color);\n\n frame_count++;\n\n if (frame_count % color_stop == 0) {\n\n current_color =\n\n Fade(initial_color,\n\n alpha_step * static_cast<float>(frame_count / color_stop));\n\n }\n\n EndDrawing();\n\n }\n\n}\n\n\n\n// Class cinema\n\n\n", "file_path": "src/scene.cpp", "rank": 41, "score": 26.096985572494123 }, { "content": "}\n\n\n\nint titlepage::interact_button_list() {\n\n Vector2 mouse_pos = GetMousePosition();\n\n for (auto &i : button_list) {\n\n int button_ret = i.interact(mouse_pos);\n\n if (button_ret != -1 && button_ret != cinema_call_back->current_scene) {\n\n cinema_call_back->next_scene = button_ret;\n\n return 1;\n\n }\n\n }\n\n return -1;\n\n}\n\n\n\nvoid titlepage::draw() {\n\n vector2d title_size(MeasureTextEx(font, title.c_str(), font_size, spacing));\n\n while (!WindowShouldClose()) {\n\n BeginDrawing();\n\n ClearBackground(final_color);\n\n DrawTexture(background, DEFAULT_WIDTH / 2 - background.width / 2,\n", "file_path": "src/titlepage.cpp", "rank": 42, "score": 25.71295638168369 }, { "content": "\n\nvoid slideshow::draw() {\n\n while (!WindowShouldClose()) {\n\n BeginDrawing();\n\n ClearBackground(final_color);\n\n DrawTexture(background, DEFAULT_WIDTH / 2 - background.width / 2,\n\n DEFAULT_HEIGHT / 2 - background.height / 2, WHITE);\n\n int ret = timeout.interact();\n\n EndDrawing();\n\n if (ret != -1) {\n\n cinema_call_back->next_scene = ret;\n\n return;\n\n }\n\n }\n\n}\n\n\n\n} // namespace gyp\n", "file_path": "src/slideshow.cpp", "rank": 43, "score": 25.363358861476748 }, { "content": "#include \"scene.hpp\"\n\n\n\n#include \"const.hpp\"\n\n#include \"game.hpp\"\n\n\n\nnamespace gyp {\n\n\n\nvoid scene::set_background_image(const std::string & path) {\n\n Image bg_img = LoadImage(path.c_str());\n\n ImageResize(&bg_img, bg_img.width * DEFAULT_HEIGHT / bg_img.height,\n\n DEFAULT_HEIGHT);\n\n background = LoadTextureFromImage(bg_img);\n\n UnloadImage(bg_img);\n\n}\n\n\n\nvoid scene::set_transient(Color initial_color, Color final_color,\n\n int transient_length, int color_stop) {\n\n this->initial_color = initial_color;\n\n this->final_color = final_color;\n\n this->transient_length = transient_length;\n", "file_path": "src/scene.cpp", "rank": 44, "score": 24.838174409653682 }, { "content": " starter.set_background_image(\"res/cover.png\");\n\n starter.set_transient(BLACK, BLACK, game_window.get_fps() / 2, 1);\n\n starter.set_cinema_call_back(&game_cinema);\n\n starter.set_title(\"Gypsophino\", GetFontDefault(), 100.0F, 10.0F, BLACK);\n\n\n\n gyp::setting setting_page;\n\n std::vector<gyp::button<int>> setting_page_button_list;\n\n start_button.set_geometry(gyp::DEFAULT_WIDTH / 3 - 100, gyp::DEFAULT_HEIGHT / 2 - 50, 200, 100);\n\n start_button.set_text(GetFontDefault(), 30.0F, 2.5F, std::array<std::string, 3>{\"Volume-\", \"Volume-\", \"Volume-\"});\n\n start_button.set_call_back(std::array<int, 4>{-1, 0, -1, -1});\n\n setting_page_button_list.push_back(start_button);\n\n start_button.set_geometry(2 * gyp::DEFAULT_WIDTH / 3 - 100, gyp::DEFAULT_HEIGHT / 2 - 50, 200, 100);\n\n start_button.set_text(GetFontDefault(), 30.0F, 2.5F, std::array<std::string, 3>{\"Volume+\", \"Volume+\", \"Volume+\"});\n\n start_button.set_call_back(std::array<int, 4>{-1, 1, -1, -1});\n\n setting_page_button_list.push_back(start_button);\n\n start_button.set_geometry(gyp::DEFAULT_WIDTH / 2 - 100, (3 * gyp::DEFAULT_HEIGHT) / 4 - 50, 200, 100);\n\n start_button.set_text(GetFontDefault(), 30.0F, 2.5F, std::array<std::string, 3>{\"OK\", \"OK\", \"OK\"});\n\n start_button.set_call_back(std::array<int, 4>{-1, 2, -1, -1});\n\n setting_page_button_list.push_back(start_button);\n\n setting_page.set_button_list(setting_page_button_list);\n", "file_path": "src/main.cpp", "rank": 45, "score": 24.67300198497431 }, { "content": "#include \"shape.hpp\"\n\n\n\nnamespace gyp {\n\n\n\nrectangle::rectangle() : x(-1), y(-1), width(-1), height(-1) {}\n\n\n\nrectangle::rectangle(int posX, int posY, int width, int height)\n\n : x(posX), y(posY), width(width), height(height) {}\n\n\n\nRectangle rectangle::ray_rectangle() const {\n\n Rectangle ret;\n\n ret.x = static_cast<float>(x);\n\n ret.y = static_cast<float>(y);\n\n ret.width = static_cast<float>(width);\n\n ret.height = static_cast<float>(height);\n\n return ret;\n\n}\n\n\n\nvector2d::vector2d() : x(0), y(0) {}\n\n\n", "file_path": "src/shape.cpp", "rank": 46, "score": 22.58965329274419 }, { "content": "#include \"note.hpp\"\n\n\n\nnamespace gyp {\n\n\n\nnote::note() : hit_time(-1) {}\n\n\n\nnote::note(int hit_t, int speed) : hit_time(hit_t) {\n\n velocity.x = 0;\n\n velocity.y = speed;\n\n}\n\n\n\nvoid note::draw() { DrawRectangle(x, y, width, height, color); }\n\n\n\n} // namespace gyp\n", "file_path": "src/note.cpp", "rank": 47, "score": 22.543899280502615 }, { "content": "#include \"scene.hpp\"\n\n#include \"game.hpp\"\n\n#include \"const.hpp\"\n\n#include \"titlepage.hpp\"\n\n#include \"slideshow.hpp\"\n\n#include \"setting.hpp\"\n\n#include \"window.hpp\"\n\n\n\n#include <vector>\n\n#include <array>\n\n#include <string>\n\n\n\nint main() {\n\n gyp::window game_window(gyp::DEFAULT_WIDTH, gyp::DEFAULT_HEIGHT, gyp::TOP_NAME, 60);\n\n\n\n gyp::cinema game_cinema;\n\n\n\n gyp::game test_game(\"./song_maps/song_map_db.json\", &game_window);\n\n test_game.set_background_image(\"res/background.png\");\n\n test_game.set_transient(BLACK, WHITE, game_window.get_fps() / 2, 1);\n", "file_path": "src/main.cpp", "rank": 48, "score": 21.904255731253027 }, { "content": "#include \"track.hpp\"\n\n#include \"const.hpp\"\n\n#include \"shape.hpp\"\n\n#include <cmath>\n\n\n\nnamespace gyp {\n\n\n\ntrack::track()\n\n : fill(DEFAULT_BG), outline(DEFAULT_FG), thick(DEFAULT_THICKNESS),\n\n bind_key(KEY_SPACE), current_time(0), visible_time(0), error_time(0),\n\n speed(-1), is_iterator_set(false), judge_height(0) {\n\n note_style.height = 50;\n\n note_style.color = DEFAULT_FG;\n\n}\n\n\n\nvoid track::set_geometry(int pos_x, int pos_y, int width, int height) {\n\n x = pos_x;\n\n y = pos_y;\n\n this->width = width;\n\n this->height = height;\n", "file_path": "src/track.cpp", "rank": 50, "score": 21.033219618092183 }, { "content": "#pragma once\n\n\n\n#include \"shape.hpp\"\n\n#include <array>\n\n#include <memory>\n\n#include <raylib.h>\n\n#include <string>\n\n#include <utility>\n\n#include <vector>\n\n\n\nnamespace gyp {\n", "file_path": "src/basic.hpp", "rank": 52, "score": 21.015768575508766 }, { "content": " (static_cast<int>(std::round(*i)) - current_time) * speed,\n\n width, note_style.height, note_style.color);\n\n }\n\n DrawRectangleLinesEx(ray_rectangle(), thick, outline);\n\n DrawLineEx(vector2d(x, DEFAULT_HEIGHT - judge_height).ray_vector2d(),\n\n vector2d(x + width, DEFAULT_HEIGHT - judge_height).ray_vector2d(), static_cast<float>(thick), BLACK);\n\n}\n\n\n\nvoid track::draw_pressed() const {\n\n DrawRectangle(x, DEFAULT_HEIGHT - judge_height, width, judge_height, outline);\n\n}\n\n\n\nvoid track::hit() {\n\n if (notes_current == notes_end) {\n\n return;\n\n }\n\n if (*notes_current >= static_cast<float>(current_time) &&\n\n *notes_current < static_cast<float>(visible_time)) {\n\n track_score.add(current_time + error_time, *notes_current);\n\n notes_current++;\n", "file_path": "src/track.cpp", "rank": 53, "score": 20.70383070296319 }, { "content": "#include \"basic.hpp\"\n\n#include <memory>\n\n#include <utility>\n\n\n\nnamespace gyp {\n\n\n\nstatue::statue() = default; // Default constructor of rectangle set -1\n\nstatue::~statue() = default;\n\n\n\nsprite::sprite() = default;\n\nsprite::~sprite() = default;\n\n\n\nvoid sprite::update(int t) {\n\n x += t * velocity.x;\n\n y += t * velocity.y;\n\n}\n\n\n\ncontainer::container()\n\n : split_pos(-1), is_horizontal(-1) {}\n\n\n", "file_path": "src/basic.cpp", "rank": 54, "score": 19.978115267250153 }, { "content": " void set_error(int error_time) { fn.set_error(error_time); }\n\n void add(int hit_time, int target_time) {\n\n total += 1;\n\n current += fn(hit_time, target_time);\n\n }\n\n std::string get_letter_grade() {\n\n for (int i = 0; i < GRADE_KIND - 1; i++) {\n\n if (current < letter_grade_table.at(i).second) {\n\n return letter_grade_table.at(i).first;\n\n }\n\n }\n\n return letter_grade_table[GRADE_KIND - 1].first;\n\n }\n\n void draw(const std::pair<int, int>& pos, int font_size) {\n\n DrawText(std::to_string(current).c_str(), pos.first, pos.second, font_size, BLUE);\n\n }\n\n void draw(const std::pair<int, int>& pos, int width, int height);\n\n};\n\n\n\n} // namespace gyp\n", "file_path": "src/score.hpp", "rank": 55, "score": 19.844574452324572 }, { "content": " }\n\n if (IsKeyPressed(KEY_P)) {\n\n is_paused = !is_paused;\n\n }\n\n if (IsKeyPressed(KEY_R)) {\n\n plg.restart();\n\n }\n\n if (IsKeyPressed(KEY_Q)) {\n\n plg.quit();\n\n return 1;\n\n }\n\n return 0;\n\n}\n\n\n\nvoid game::draw() {\n\n int ret = 0;\n\n while (!WindowShouldClose()) {\n\n BeginDrawing();\n\n ClearBackground(final_color);\n\n DrawTexture(background, DEFAULT_WIDTH / 2 - background.width / 2,\n", "file_path": "src/game.cpp", "rank": 56, "score": 19.36616670455187 }, { "content": " DrawRectangle(0, 0, DEFAULT_WIDTH, DEFAULT_HEIGHT, Fade(BLACK, 0.8F));\n\n DrawTextEx(GetFontDefault(), current_volume_str.c_str(),\n\n vector2d(DEFAULT_WIDTH / 2 - current_volume_size.x / 2,\n\n DEFAULT_HEIGHT / 2 - current_volume_size.y / 2).ray_vector2d(),\n\n 30.0F, 2.5F, WHITE);\n\n int ret = interact_button_list();\n\n EndDrawing();\n\n if (ret != -1) {\n\n if (ret == 0) {\n\n window_call_back->change_volume(-0.1F);\n\n } else if (ret == 1) {\n\n window_call_back->change_volume(0.1F);\n\n } else if (ret == 2) {\n\n cinema_call_back->next_scene = cinema_call_back->prev_scene;\n\n return;\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/setting.cpp", "rank": 57, "score": 19.112880525562645 }, { "content": "#pragma once\n\n\n\n#include <raylib.h>\n\n#include <array>\n\n#include <string>\n\n\n\nnamespace gyp {\n\nconst int GRADE_KIND = 6;\n\nconst int GYP_MAX_SCORE = 1000000;\n\n\n", "file_path": "src/score.hpp", "rank": 58, "score": 18.84430274063846 }, { "content": "#include \"setting.hpp\"\n\n\n\n#include <cmath>\n\n#include <utility>\n\n#include <string>\n\n\n\nnamespace gyp {\n\n\n\nsetting::setting(std::vector<button<int>> button_list, window *window_call_back)\n\n : button_list(std::move(button_list)), window_call_back(window_call_back) {}\n\n\n\nvoid setting::set_button_list(const std::vector<button<int>> &button_list) {\n\n this->button_list = button_list;\n\n}\n\n\n\nvoid setting::set_window_call_back(window *window_call_back) {\n\n this->window_call_back = window_call_back;\n\n}\n\n\n\nint setting::interact_button_list() {\n", "file_path": "src/setting.cpp", "rank": 59, "score": 18.58756369162349 }, { "content": " DEFAULT_HEIGHT / 2 - background.height / 2, WHITE);\n\n plg.draw();\n\n ret = interact();\n\n EndDrawing();\n\n if (ret == 1) {\n\n cinema_call_back->next_scene = 0;\n\n return;\n\n }\n\n }\n\n}\n\n\n\n} // namespace gyp\n", "file_path": "src/game.cpp", "rank": 60, "score": 17.905914640371144 }, { "content": "#include \"playground.hpp\"\n\n#include \"const.hpp\"\n\n\n\n#include <string>\n\n\n\nnamespace gyp {\n\n\n\nplayground::playground()\n\n : track_number(DEFAULT_TRACK_NUM), outline(DEFAULT_FG),\n\n thick(DEFAULT_THICKNESS), current_time(0), speed(-1), song(nullptr),\n\n status(not_running), is_initialized(false), real_notes(DEFAULT_TRACK_NUM),\n\n total_score(0) {}\n\n\n\nplayground::~playground() {\n\n song = nullptr; // Why do this?\n\n}\n\n\n\nvoid playground::set_geometry(int pos_x, int pos_y, int width, int height,\n\n int track_number) {\n\n x = pos_x;\n", "file_path": "src/playground.cpp", "rank": 61, "score": 17.448795794795277 }, { "content": "#pragma once\n\n\n\n#include <raylib.h>\n\n#include <vector>\n\n#include <string>\n\n\n\nnamespace gyp {\n\n\n", "file_path": "src/scene.hpp", "rank": 62, "score": 17.09722950812752 }, { "content": " vci notes_current; // For drawing\n\n vci notes_visible; // For drawing\n\n // Score\n\n score<parabolic_func> track_score;\n\n int judge_height;\n\n\n\npublic:\n\n // Constructor & Destructor\n\n track();\n\n // track(const track &other);\n\n // track(track &&other) noexcept;\n\n ~track() = default;\n\n\n\n // Setter\n\n void set_geometry(int pos_x, int pos_y, int width, int height);\n\n void set_track_style(Color fill_color, Color outline_color, int outline_thickness, KeyboardKey bind_key);\n\n void set_note_style(int height, Color color);\n\n void set_note_style(int height, Image image);\n\n void set_time(int current_time, int visible_time, int error_time);\n\n void set_speed(int speed);\n", "file_path": "src/track.hpp", "rank": 63, "score": 16.549263780042637 }, { "content": "#include \"game.hpp\"\n\n#include \"const.hpp\"\n\n\n\nnamespace gyp {\n\n\n\ngame::game(const std::string &song_db_path, window *window_call_back)\n\n : is_paused(true), window_call_back(window_call_back) {\n\n song_database.load(song_db_path);\n\n const int block_width = 200;\n\n const int block_height = 50;\n\n plg.set_geometry(window_call_back->get_width() / 2 - 2 * block_width, 0,\n\n 4 * block_width, window_call_back->get_height(),\n\n song_database[0].track_number);\n\n plg.set_playground_style(BLACK, gyp::DEFAULT_THICKNESS * 2);\n\n plg.set_speed(gyp::DEFAULT_SPEED * 2);\n\n // This setter MUST be executed last.\n\n plg.set_track(Fade(WHITE, 0.8F), gyp::DEFAULT_FG, gyp::DEFAULT_THICKNESS,\n\n block_height, BLACK);\n\n plg.init();\n\n plg.load(&song_database[0], window_call_back->get_fps());\n", "file_path": "src/game.cpp", "rank": 64, "score": 16.40015001302752 }, { "content": "void playground::set_track(Color fill_color, Color outline_color, int outline_thickness,\n\n int note_height, Image note_image) {\n\n if (speed == -1) {\n\n speed = DEFAULT_SPEED;\n\n }\n\n if (is_initialized) {\n\n for (auto &i : *this) {\n\n i.set_track_style(fill_color, outline_color, outline_thickness);\n\n }\n\n } else {\n\n int track_width = width / track_number;\n\n for (int i = 0; i < track_number; i++) {\n\n push_back(track());\n\n back().set_geometry(x + i * track_width, y, track_width, height);\n\n back().set_track_style(fill_color, outline_color, outline_thickness);\n\n back().set_note_style(note_height, note_image);\n\n back().set_time(0, 0, 10);\n\n back().set_speed(speed);\n\n }\n\n is_initialized = true;\n", "file_path": "src/playground.cpp", "rank": 66, "score": 15.806381984020605 }, { "content": "#include \"window.hpp\"\n\n\n\nnamespace gyp {\n\n\n\nwindow::window(int width, int height, std::string window_title, int fps)\n\n : width(width), height(height), window_title(std::move(window_title)),\n\n fps(fps), volume(1.0F), is_initialized(false) {\n\n InitWindow(width, height, window_title.c_str());\n\n SetTargetFPS(fps);\n\n InitAudioDevice();\n\n SetMasterVolume(volume);\n\n}\n\n\n\nwindow::~window() {\n\n CloseAudioDevice();\n\n CloseWindow();\n\n}\n\n\n\nvoid window::set_size(int width, int height) {\n\n this->width = width;\n", "file_path": "src/window.cpp", "rank": 67, "score": 15.640814983636584 }, { "content": " void set_iterator(vci iter_begin, vci iter_end);\n\n\n\n // Getter\n\n [[nodiscard]] float get_score() const;\n\n\n\n // Method\n\n int init();\n\n void update();\n\n void sync(int current_time);\n\n void draw() const;\n\n void draw_pressed() const;\n\n void hit(); // just for update the canvas, not for score\n\n void interact();\n\n};\n\n\n\n} // namespace gyp\n", "file_path": "src/track.hpp", "rank": 68, "score": 15.6404576457147 }, { "content": " }\n\n UnloadMusicStream(music);\n\n}\n\n\n\nvoid playground::restart() {\n\n StopMusicStream(music);\n\n for (auto &i : *this) {\n\n i.sync(0);\n\n }\n\n PlayMusicStream(music);\n\n}\n\n\n\nvoid playground::draw() const {\n\n for (const auto &i : *this) {\n\n i.draw();\n\n }\n\n DrawRectangleLinesEx(this->ray_rectangle(), thick, outline);\n\n DrawText(std::to_string(total_score * 100.0F).c_str(), 10, 10, 40.0F, BLACK);\n\n}\n\n\n\n} // namespace gyp\n", "file_path": "src/playground.cpp", "rank": 69, "score": 15.542555801110167 }, { "content": "#pragma once\n\n\n\n#include <boost/property_tree/json_parser.hpp>\n\n#include <boost/property_tree/ptree.hpp>\n\n#include <string>\n\n#include <vector>\n\n\n\nnamespace gyp {\n", "file_path": "src/song_map.hpp", "rank": 70, "score": 15.195527282833899 }, { "content": " [[nodiscard]] int get_fps() const;\n\n [[nodiscard]] vector2d get_size() const;\n\n [[nodiscard]] int get_width() const;\n\n [[nodiscard]] int get_height() const;\n\n [[nodiscard]] std::string get_window_title() const;\n\n [[nodiscard]] float get_volume() const;\n\n // Method\n\n // TODO(tonyfettes): implement detect.\n\n void detect(); // Planned\n\n int init(); // -> 0: Succeed, 1: Failed, 2: Already initialized\n\n};\n\n\n\n} // namespace gyp\n", "file_path": "src/window.hpp", "rank": 71, "score": 15.078698080275348 }, { "content": " y = pos_y;\n\n this->width = width;\n\n this->height = height;\n\n this->track_number = track_number;\n\n}\n\n\n\nvoid playground::set_playground_style(Color outline_color,\n\n int outline_thickness) {\n\n outline = outline_color;\n\n thick = outline_thickness;\n\n}\n\n\n\nvoid playground::set_speed(int speed) { this->speed = speed; }\n\n\n\nvoid playground::set_track(Color fill_color, Color outline_color, int outline_thickness,\n\n int note_height, Color note_color) {\n\n if (speed == -1) {\n\n speed = DEFAULT_SPEED;\n\n }\n\n if (is_initialized) {\n", "file_path": "src/playground.cpp", "rank": 72, "score": 14.964181622288532 }, { "content": "void track::sync(int current_time) {\n\n this->current_time = current_time;\n\n this->visible_time = current_time + height / speed;\n\n notes_current = notes_begin;\n\n notes_visible = notes_begin;\n\n while (notes_current != notes_end &&\n\n *notes_current < static_cast<float>(this->current_time)) {\n\n notes_current++;\n\n }\n\n while (notes_visible != notes_end &&\n\n *notes_visible < static_cast<float>(this->visible_time)) {\n\n notes_visible++;\n\n }\n\n}\n\n\n\nvoid track::draw() const {\n\n DrawRectangle(x, y, width, height, fill);\n\n for (vci i = notes_current; i != notes_visible && i != notes_end; i++) {\n\n DrawRectangle(x,\n\n y + height -\n", "file_path": "src/track.cpp", "rank": 73, "score": 14.380563613262867 }, { "content": "#pragma once\n\n\n\n#include <raylib.h>\n\n#include <string>\n\n\n\nnamespace gyp {\n", "file_path": "src/shape.hpp", "rank": 74, "score": 14.308818455912581 }, { "content": " playground();\n\n ~playground();\n\n\n\n // Setter\n\n void set_geometry(int pos_x, int pos_y, int width, int height,\n\n int track_number);\n\n void set_playground_style(Color outline_color, int outline_thickness);\n\n void set_speed(int speed);\n\n // CAUTION: set_track() must be called after setter above !!\n\n void set_track(Color fill_color, Color outline_color, int outline_thickness,\n\n int note_height, Color note_color);\n\n void set_track(Color fill_color, Color outline_color, int outline_thickness,\n\n int note_height, Image note_image);\n\n\n\n // Method\n\n // CAUTION: Any method must be called after set_track(),\n\n // for performance, these function will not examine\n\n // is_initialized before they run.\n\n // Contain: [i].set_interator [i].init()\n\n // CAUTION: Init() must be run at first.\n", "file_path": "src/playground.hpp", "rank": 75, "score": 14.267599403916918 }, { "content": "#pragma once\n\n\n\n#include \"control.hpp\"\n\n#include \"scene.hpp\"\n\n#include <vector>\n\n\n\nnamespace gyp {\n\n\n", "file_path": "src/titlepage.hpp", "rank": 76, "score": 14.02049623852284 }, { "content": "#pragma once\n\n\n\n#include <raylib.h>\n\n#include <string>\n\n\n\n#include \"shape.hpp\"\n\n\n\nnamespace gyp {\n\n\n", "file_path": "src/window.hpp", "rank": 77, "score": 13.99774331855733 }, { "content": "}\n\n\n\nvoid track::set_track_style(Color fill_color, Color outline_color,\n\n int outline_thickness, KeyboardKey bind_key) {\n\n fill = fill_color;\n\n outline = outline_color;\n\n thick = outline_thickness;\n\n this->bind_key = bind_key;\n\n}\n\n\n\nvoid track::set_note_style(int h, Color c) {\n\n note_style.height = h;\n\n note_style.color = c;\n\n}\n\n\n\nvoid track::set_note_style(int h, Image image) {\n\n note_style.height = h;\n\n note_style.image = image;\n\n}\n\n\n", "file_path": "src/track.cpp", "rank": 78, "score": 13.596819427448624 }, { "content": "#pragma once\n\n\n\n#include \"shape.hpp\"\n\n#include \"score.hpp\"\n\n#include \"note.hpp\"\n\n#include <raylib.h>\n\n#include <vector>\n\n\n\nnamespace gyp {\n", "file_path": "src/track.hpp", "rank": 79, "score": 13.488710438459165 }, { "content": "#pragma once\n\n\n\n#include \"control.hpp\"\n\n#include \"scene.hpp\"\n\n#include \"window.hpp\"\n\n#include <raylib.h>\n\n#include <vector>\n\n\n\nnamespace gyp {\n\n\n", "file_path": "src/setting.hpp", "rank": 80, "score": 13.488710438459165 }, { "content": "#pragma once\n\n\n\n#include \"song_map.hpp\"\n\n#include \"track.hpp\"\n\n#include \"shape.hpp\"\n\n#include <raylib.h>\n\n#include <vector>\n\n\n\nnamespace gyp {\n\n\n", "file_path": "src/playground.hpp", "rank": 81, "score": 13.348274215917563 }, { "content": " this->color_stop = color_stop;\n\n}\n\n\n\nvoid scene::set_cinema_call_back(cinema * cinema_call_back) {\n\n this->cinema_call_back = cinema_call_back;\n\n}\n\n\n\nscene::scene(Color initial_color, Color final_color, int transient_length,\n\n int color_stop)\n\n : initial_color(initial_color), final_color(final_color),\n\n transient_length(transient_length), color_stop(color_stop) {\n\n set_background_image(\"res/background.png\");\n\n}\n\n\n\nvoid scene::enter() {\n\n int frame_count = 0;\n\n float alpha_step = (1.0F) / static_cast<float>(transient_length) *\n\n static_cast<float>(color_stop);\n\n Color current_color = Fade(initial_color, 1.0F);\n\n while (!WindowShouldClose() && frame_count < transient_length) {\n", "file_path": "src/scene.cpp", "rank": 82, "score": 13.314540775942344 }, { "content": "#pragma once\n\n\n\n#include \"scene.hpp\"\n\n#include \"song_map.hpp\"\n\n#include \"playground.hpp\"\n\n#include \"window.hpp\"\n\n\n\n#include <vector>\n\n\n\nnamespace gyp {\n\n\n", "file_path": "src/game.hpp", "rank": 84, "score": 13.211159499681774 }, { "content": " }\n\n}\n\n\n\nvoid track::interact() {\n\n if (IsKeyPressed(bind_key)) {\n\n hit();\n\n }\n\n if (IsKeyDown(bind_key)) {\n\n draw_pressed();\n\n }\n\n}\n\n\n\n} // namespace gyp\n", "file_path": "src/track.cpp", "rank": 85, "score": 12.908555534919552 }, { "content": "#include \"slideshow.hpp\"\n\n\n\nnamespace gyp {\n\n\n\nslideshow::slideshow() {\n\n this->timeout.set_call_back(std::array<int, 2>{-1, -1});\n\n}\n\n\n\nslideshow::slideshow(int timeout) {\n\n this->timeout.set_count_down(timeout);\n\n this->timeout.set_call_back(std::array<int, 2>{-1, -1});\n\n}\n\n\n\nvoid slideshow::set_timeout(int timeout) {\n\n this->timeout.set_count_down(timeout);\n\n}\n\n\n\nvoid slideshow::set_call_back(int before, int after) {\n\n this->timeout.set_call_back(std::array<int, 2>{before, after});\n\n}\n", "file_path": "src/slideshow.cpp", "rank": 86, "score": 12.720978432514517 }, { "content": " this->height = height;\n\n SetWindowSize(width, height);\n\n}\n\n\n\nvoid window::set_title(const std::string& window_title) {\n\n this->window_title = window_title;\n\n SetWindowTitle(window_title.c_str());\n\n}\n\n\n\nvoid window::set_fps(int fps) {\n\n this->fps = fps;\n\n SetTargetFPS(fps);\n\n}\n\n\n\nvoid window::set_volume(float volume) {\n\n this->volume = volume;\n\n SetMasterVolume(volume);\n\n}\n\n\n\nvoid window::change_volume(float delta) {\n", "file_path": "src/window.cpp", "rank": 87, "score": 12.410088411683859 }, { "content": "#include \"score.hpp\"\n\n\n\nnamespace gyp {\n\n// class parabolic_func:\n\n\n\nvoid parabolic_func::set_error(int error_time) {\n\n this->error_time = error_time;\n\n}\n\n\n\n[[nodiscard]] int parabolic_func::get_error() const { return error_time; }\n\n\n\nfloat parabolic_func::operator()(int hit_time, int target_time) const {\n\n float raw_score = 1 - static_cast<float>((target_time - hit_time) * (target_time - hit_time)) / static_cast<float>(error_time * error_time);\n\n return std::max(static_cast<float>(0), raw_score);\n\n}\n\n\n\n} // namespace gyp\n", "file_path": "src/score.cpp", "rank": 88, "score": 12.375569976854951 }, { "content": " if (track_number % 2 == 1) {\n\n at(track_number / 2)\n\n .set_track_style(fill_color, outline_color, outline_thickness,\n\n DEFAULT_KEY_BINDING[4]);\n\n }\n\n for (int i = 0; i < track_number / 2; i++) {\n\n at(i).set_track_style(fill_color, outline_color, outline_thickness, DEFAULT_KEY_BINDING.at(4 - track_number / 2 + i));\n\n at(i).set_track_style(fill_color, outline_color, outline_thickness, DEFAULT_KEY_BINDING.at(4 + track_number / 2 - i));\n\n }\n\n } else {\n\n int track_width = width / track_number;\n\n for (int i = 0; i < track_number / 2; i++) {\n\n push_back(track());\n\n back().set_geometry(x + i * track_width, y, track_width, height);\n\n back().set_track_style(fill_color, outline_color, outline_thickness, DEFAULT_KEY_BINDING.at(4 - track_number / 2 + i));\n\n back().set_note_style(note_height, note_color);\n\n back().set_time(0, 0, 10);\n\n back().set_speed(speed);\n\n }\n\n if (track_number % 2 == 1) {\n", "file_path": "src/playground.cpp", "rank": 89, "score": 12.012555091696164 }, { "content": "#include \"song_map.hpp\"\n\n\n\nnamespace pt = boost::property_tree;\n\n\n\nnamespace gyp {\n\n// class song_map\n\n\n\nvoid song_map::load(const std::string& filename) {\n\n pt::ptree tree;\n\n pt::read_json(filename, tree);\n\n track_number = tree.get<int>(\"track_number\");\n\n bpm = tree.get<int>(\"bpm\");\n\n base_fraction = tree.get<int>(\"base_fraction\");\n\n difficulty = tree.get<int>(\"difficulty\");\n\n song_duration = tree.get<int>(\"song_duration\");\n\n object_count = tree.get<int>(\"object_count\");\n\n offset = tree.get<float>(\"offset\");\n\n\n\n song_author = tree.get<std::string>(\"song_author\");\n\n name = tree.get<std::string>(\"name\");\n", "file_path": "src/song_map.cpp", "rank": 90, "score": 11.92860671723436 }, { "content": "[[nodiscard]] std::string window::get_window_title() const {\n\n return window_title;\n\n}\n\n\n\n[[nodiscard]] float window::get_volume() const {\n\n return volume;\n\n}\n\n\n\nvoid window::detect() {\n\n}\n\n\n\nint window::init() {\n\n if (!is_initialized) {\n\n InitWindow(width, height, window_title.c_str());\n\n int check_cnt = 0;\n\n while (!IsWindowReady() && check_cnt < 20) {\n\n ;\n\n }\n\n if (IsWindowReady()) {\n\n is_initialized = true;\n", "file_path": "src/window.cpp", "rank": 91, "score": 11.4069869302478 }, { "content": "#pragma once\n\n\n\n#include \"basic.hpp\"\n\n#include <raylib.h>\n\n\n\nnamespace gyp {\n\n\n", "file_path": "src/note.hpp", "rank": 92, "score": 11.348751830042813 }, { "content": " void init();\n\n void load(const song_map *selected_song, int fps);\n\n void play(); // play a single frame\n\n void pause(); // pause for a single frame\n\n void quit();\n\n void restart();\n\n void draw() const;\n\n};\n\n\n\n} // namespace gyp\n", "file_path": "src/playground.hpp", "rank": 93, "score": 11.245863383489532 }, { "content": "#pragma once\n\n\n\n#include \"control.hpp\"\n\n#include \"scene.hpp\"\n\n\n\nnamespace gyp {\n\n\n", "file_path": "src/slideshow.hpp", "rank": 94, "score": 11.205138679243413 }, { "content": " push_back(track());\n\n back().set_geometry(x + (track_number / 2) * track_width, y, track_width, height);\n\n back().set_track_style(fill_color, outline_color, outline_thickness, DEFAULT_KEY_BINDING.at(4));\n\n back().set_note_style(note_height, note_color);\n\n back().set_time(0, 0, 10);\n\n back().set_speed(speed);\n\n }\n\n for (int i = (track_number + 1) / 2; i < track_number; i++) {\n\n push_back(track());\n\n back().set_geometry(x + i * track_width, y, track_width, height);\n\n back().set_track_style(fill_color, outline_color, outline_thickness, DEFAULT_KEY_BINDING.at(4 - track_number / 2 + i));\n\n back().set_note_style(note_height, note_color);\n\n back().set_time(0, 0, 10);\n\n back().set_speed(speed);\n\n }\n\n is_initialized = true;\n\n }\n\n}\n\n\n\n/*\n", "file_path": "src/playground.cpp", "rank": 95, "score": 11.172793209318037 }, { "content": "cinema::cinema() : prev_scene(-1), current_scene(-1), next_scene(-1) {}\n\n\n\nvoid cinema::play() {\n\n for (int i = 0; i < static_cast<int>(size()); ) {\n\n at(i)->enter();\n\n at(i)->draw();\n\n at(i)->leave();\n\n prev_scene = i;\n\n if (next_scene != -1) {\n\n i = next_scene;\n\n next_scene = -1;\n\n } else {\n\n i++;\n\n }\n\n current_scene = i;\n\n }\n\n}\n\n\n\n} // namespace gyp\n", "file_path": "src/scene.cpp", "rank": 96, "score": 10.146329793123144 }, { "content": " setting_page.set_background_image(\"res/cover.png\");\n\n setting_page.set_transient(BLACK, BLACK, game_window.get_fps() / 2, 1);\n\n setting_page.set_cinema_call_back(&game_cinema);\n\n setting_page.set_window_call_back(&game_window);\n\n\n\n game_cinema.push_back(static_cast<gyp::scene *>(&starter)); // 0\n\n game_cinema.push_back(static_cast<gyp::scene *>(&test_game)); // 1\n\n game_cinema.push_back(static_cast<gyp::scene *>(&setting_page)); // 2\n\n // int init_size = game_cinema.size();\n\n std::array<gyp::slideshow, 4> interplay;\n\n /*\n\n * 3 -> Chap 01\n\n * 4 -> Chap 02\n\n * 5 -> Chap 03\n\n * 6 -> Chap 04\n\n */\n\n for (int i = 0; i < 4; i++) {\n\n interplay.at(i).set_background_image(\"res/chap_0\" + std::to_string(i + 1) + \".png\");\n\n interplay.at(i).set_transient(BLACK, WHITE, game_window.get_fps() / 2, 1);\n\n interplay.at(i).set_cinema_call_back(&game_cinema);\n\n interplay.at(i).set_timeout(game_window.get_fps());\n\n interplay.at(i).set_call_back(-1, 1);\n\n game_cinema.push_back(static_cast<gyp::scene *>(&interplay.at(i)));\n\n }\n\n game_cinema.push_back(static_cast<gyp::scene *>(&test_game));\n\n game_cinema.play();\n\n return 0;\n\n}\n", "file_path": "src/main.cpp", "rank": 97, "score": 10.060533258175598 }, { "content": " *notes_visible < static_cast<float>(visible_time)) {\n\n notes_visible++;\n\n }\n\n}\n\n\n\n[[nodiscard]] float track::get_score() const {\n\n return track_score.current / (track_score.total == 0 ? 1 : track_score.total);\n\n}\n\n\n\nint track::init() {\n\n if (x == -1 || y == -1 || width == -1 || height == -1) {\n\n // check if geometry is set\n\n return 1;\n\n }\n\n if (is_iterator_set == false) { // check if iterators are set\n\n return 1;\n\n }\n\n if (speed == -1) { // check if speed is set\n\n speed = DEFAULT_SPEED;\n\n }\n", "file_path": "src/track.cpp", "rank": 98, "score": 9.497639590583939 }, { "content": "vector2d::vector2d(int x, int y) : x(x), y(y) {}\n\n\n\nvector2d::vector2d(Vector2 other)\n\n : x(static_cast<int>(other.x)), y(static_cast<int>(other.y)) {}\n\n\n\n[[nodiscard]] Vector2 vector2d::ray_vector2d() const {\n\n Vector2 ret;\n\n ret.x = static_cast<float>(x);\n\n ret.y = static_cast<float>(y);\n\n return ret;\n\n}\n\n\n\n} // namespace gyp\n", "file_path": "src/shape.cpp", "rank": 99, "score": 9.396615683056552 } ]
C++
include/amtrs/.driver/win32-g3d-device-opengl.hpp
isaponsoft/libamtrs
5adf821ee15592fc3280985658ca8a4b175ffcaa
 #ifndef __libamtrs__g3d__device__win32__opengl__hpp #define __libamtrs__g3d__device__win32__opengl__hpp #pragma comment(lib, "user32.lib") #pragma comment(lib, "gdi32.lib") #pragma comment(lib, "opengl32.lib") #include ".api-windows.hpp" #include <GL/gl.h> #include <GL/glext.h> #include <GL/wglext.h> #include "opengl.inc/glext-value.hpp" #define AMTRS_USE_DYNAMIC_OPENGL_INIT 1 #include "../opengl/g3d-device.hpp" #define AMTRS_WIN32_OPENGL_NAMESPACE_BEGIN AMTRS_G3D_NAMESPACE_BEGIN namespace win32 { namespace opengl { #define AMTRS_WIN32_OPENGL_NAMESPACE_END } } AMTRS_G3D_NAMESPACE_END AMTRS_WIN32_OPENGL_NAMESPACE_BEGIN using namespace os::win32; class device : public g3d::opengl::device { public: virtual ~device() { wglDeleteContext(mGLRC); } virtual void active() override { wglMakeCurrent(mDC, mGLRC); } virtual void deactive() override { wglMakeCurrent(mDC, nullptr); } virtual bool is_context_enable() const override { return mGLRC != nullptr; } void initialize(HDC _hdc) { PIXELFORMATDESCRIPTOR pfd; std::memset(&pfd, 0, sizeof(pfd)); pfd.nVersion = 1; pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 32; pfd.cDepthBits = 24; pfd.cStencilBits = 8; GLuint uPixelFormat = ChoosePixelFormat(_hdc, &pfd); if (!uPixelFormat) { throw std::system_error(make_last_error_code(), "ChoosePixelFormat()"); } if (!SetPixelFormat(_hdc, uPixelFormat, &pfd)) { throw std::system_error(make_last_error_code(), "SetPixelFormat()"); } mGLRC = wglCreateContext(_hdc); if (!mGLRC) { throw std::system_error(make_last_error_code(), "wglCreateContext()"); } wglMakeCurrent(_hdc, mGLRC); mDC = _hdc; auto wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB"); if (wglCreateContextAttribsARB) { static const int attr[]= { WGL_CONTEXT_MAJOR_VERSION_ARB, 2, WGL_CONTEXT_MINOR_VERSION_ARB, 0, WGL_CONTEXT_FLAGS_ARB, 0, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, 0, }; HGLRC hglrc = wglCreateContextAttribsARB(mDC, nullptr, attr); wglMakeCurrent(mDC, hglrc); wglDeleteContext(mGLRC); mGLRC = hglrc; #if AMTRS_USE_DYNAMIC_OPENGL_INIT #include "opengl.inc/glext-init.hpp" #endif mSupportExtAPI = true; } } protected: HDC mDC = nullptr; HGLRC mGLRC = nullptr; bool mSupportExtAPI = false; }; AMTRS_WIN32_OPENGL_NAMESPACE_END AMTRS_G3D_NAMESPACE_BEGIN template<class BitmapT> inline ref<device> device::create(BitmapT* _bitmap) { using namespace os::win32; class device : public win32::opengl::device { public: using _base_type = win32::opengl::device; device(BitmapT* _bmp) : mBitmap(_bmp) {} ~device() { if (mDC) { ReleaseDC(nullptr, mDC); } } virtual size_type size() const override { return mBitmap->size(); } virtual void present() override { glReadPixels(0, 0, size().width, size().height, GL_RGBA, GL_UNSIGNED_BYTE, mBitmap->pixels().data()); _base_type::present(); } void initialize() { mDC = GetDC(nullptr); if (!mDC) { throw std::system_error(make_last_error_code(), "GetDC()"); } _base_type::initialize(mDC); } BitmapT* mBitmap; }; ref<device> thiz = new device(_bitmap); thiz->initialize(); return thiz; } AMTRS_G3D_NAMESPACE_END #endif
 #ifndef __libamtrs__g3d__device__win32__opengl__hpp #define __libamtrs__g3d__device__win32__opengl__hpp #pragma comment(lib, "user32.lib") #pragma comment(lib, "gdi32.lib") #pragma comment(lib, "opengl32.lib") #include ".api-windows.hpp" #include <GL/gl.h> #include <GL/glext.h> #include <GL/wglext.h> #include "opengl.inc/glext-value.hpp" #define AMTRS_USE_DYNAMIC_OPENGL_INIT 1 #include "../opengl/g3d-device.hpp" #define AMTRS_WIN32_OPENGL_NAMESPACE_BEGIN AMTRS_G3D_NAMESPACE_BEGIN namespace win32 { namespace opengl { #define AMTRS_WIN32_OPENGL_NAMESPACE_END } } AMTRS_G3D_NAMESPACE_END AMTRS_WIN32_OPENGL_NAMESPACE_BEGIN using namespace os::win32; class device : public g3d::opengl::device { public: virtual ~device() { wglDeleteContext(mGLRC); } virtual void active() override { wglMakeCurrent(mDC, mGLRC); } virtual void deactive() override { wglMakeCurrent(mDC, nullptr); } virtual bool is_context_enable() const override { return mGLRC != nullptr; } void initialize(HDC _hdc) { PIXELFORMATDESCRIPTOR pfd; std::memset(&pfd, 0, sizeof(pfd)); pfd.nVersion = 1; pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 32; pfd.cDepthBits = 24; pfd.cStencilBits = 8; GLuint uPixelFormat = ChoosePixelFormat(_hdc, &pfd); if (!uPixelFormat) { throw std::system_error(make_last_error_code(), "ChoosePixelFormat()"); } if (!SetPixelFormat(_hdc, uPixelFormat, &pfd)) { throw std::system_error(make_last_error_code(), "SetPixelFormat()"); } mGLRC = wglCreateContext(_hdc)
rtExtAPI = false; }; AMTRS_WIN32_OPENGL_NAMESPACE_END AMTRS_G3D_NAMESPACE_BEGIN template<class BitmapT> inline ref<device> device::create(BitmapT* _bitmap) { using namespace os::win32; class device : public win32::opengl::device { public: using _base_type = win32::opengl::device; device(BitmapT* _bmp) : mBitmap(_bmp) {} ~device() { if (mDC) { ReleaseDC(nullptr, mDC); } } virtual size_type size() const override { return mBitmap->size(); } virtual void present() override { glReadPixels(0, 0, size().width, size().height, GL_RGBA, GL_UNSIGNED_BYTE, mBitmap->pixels().data()); _base_type::present(); } void initialize() { mDC = GetDC(nullptr); if (!mDC) { throw std::system_error(make_last_error_code(), "GetDC()"); } _base_type::initialize(mDC); } BitmapT* mBitmap; }; ref<device> thiz = new device(_bitmap); thiz->initialize(); return thiz; } AMTRS_G3D_NAMESPACE_END #endif
; if (!mGLRC) { throw std::system_error(make_last_error_code(), "wglCreateContext()"); } wglMakeCurrent(_hdc, mGLRC); mDC = _hdc; auto wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB"); if (wglCreateContextAttribsARB) { static const int attr[]= { WGL_CONTEXT_MAJOR_VERSION_ARB, 2, WGL_CONTEXT_MINOR_VERSION_ARB, 0, WGL_CONTEXT_FLAGS_ARB, 0, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, 0, }; HGLRC hglrc = wglCreateContextAttribsARB(mDC, nullptr, attr); wglMakeCurrent(mDC, hglrc); wglDeleteContext(mGLRC); mGLRC = hglrc; #if AMTRS_USE_DYNAMIC_OPENGL_INIT #include "opengl.inc/glext-init.hpp" #endif mSupportExtAPI = true; } } protected: HDC mDC = nullptr; HGLRC mGLRC = nullptr; bool mSuppo
random
[ { "content": "// ============================================================================\n\n//! 標準ファイルシステムに対するインターフェース\n\n// ----------------------------------------------------------------------------\n\n//! std::filesystem を仮想化します。\n\n// ----------------------------------------------------------------------------\n\nclass\tstdvfs_impl : public stdvfs\n\n{\n\npublic:\n\n\tstatic ref<stdvfs_impl> get_instance()\n\n\t{\n\n\t\tif (instance() == nullptr)\n\n\t\t{\n\n\t\t\tinstance() = new stdvfs_impl();\n\n\t\t}\n\n\t\treturn\tinstance();\n\n\t}\n\n\n\n\tvirtual ~stdvfs_impl()\n\n\t{\n\n\t\tinstance() = nullptr;\n\n\t}\n\n\n\nprivate:\n\n\n\n\tstatic stdvfs_impl*& instance()\n", "file_path": "src/amtrs/base-filesystem-stdvfs.cpp", "rank": 0, "score": 130037.79456067029 }, { "content": "\tclass\titeratorable\n\n\t{\n\n\tpublic:\n\n\t\tusing\tvalue_type\t= entry;\n\n\n\n\t\titeratorable() = default;\n\n\t\titeratorable(iteratorable const&) = delete;\n\n\t\titeratorable(iteratorable&& _r)\n\n\t\t\t: mScaner(_r.mScaner)\n\n\t\t\t, mEntry(_r.mEntry)\n\n\t\t{\n\n\t\t\t_r.mEntry._arcive\t= mScaner->mArc;\n\n\t\t\t_r.mEntry._entry\t= nullptr;\n\n\t\t}\n\n\n\n\t\texplicit iteratorable(basic_archive_enumrator* _scan)\n\n\t\t\t: mScaner(_scan)\n\n\t\t{\n\n\t\t\tmEntry._arcive\t= mScaner ? mScaner->mArc : nullptr;\n\n\t\t\tmEntry._entry\t= nullptr;\n", "file_path": "include/amtrs/archive.hpp", "rank": 1, "score": 111994.0604772418 }, { "content": "\tclass\titeratorable;\n\n\n", "file_path": "include/amtrs/archive.hpp", "rank": 2, "score": 111994.0604772418 }, { "content": "", "file_path": "include/amtrs/font.hpp", "rank": 3, "score": 111994.0604772418 }, { "content": "\tclass\tentry\n\n\t{\n\n\tpublic:\n\n\t\tstd::string_view name()\n\n\t\t{\n\n\t\t\treturn\tarchive_entry_pathname(_entry);\n\n\t\t}\n\n\n\n\t\tsize_t size()\n\n\t\t{\n\n\t\t\treturn\tarchive_entry_size(_entry);\n\n\t\t}\n\n\n\n\t\tarchive*\t\t_arcive\t= nullptr;\n\n\t\tarchive_entry*\t_entry\t= nullptr;\n\n\t\tfriend\titeratorable;\n\n\t};\n\n\n", "file_path": "include/amtrs/archive.hpp", "rank": 4, "score": 111994.0604772418 }, { "content": "class\tzip_archive;\n\n\n\n\n\ntemplate<class CharT = char, class Traits = zip_traits<CharT>>\n", "file_path": "include/amtrs/filesystem.hpp", "rank": 5, "score": 109853.06865218774 }, { "content": "class\tzip_iterator;\n\n\n\n\n\nusing\tzip_entry\t= basic_zip_entry<char>;\n\nAMTRS_FILESYSTEM_ZIP_NAMESPACE_END\n\n\n\n#include \".inc/filesystem-zip-types.hpp\"\n\n#include \".inc/filesystem-zip-entry.hpp\"\n\n#include \".inc/filesystem-zip-archive.hpp\"\n\n#include \".inc/filesystem-zip-iterator.hpp\"\n\n#include \".inc/filesystem-zip-zipfs.hpp\"\n\n\n\n#endif\n", "file_path": "include/amtrs/filesystem.hpp", "rank": 6, "score": 109853.06865218774 }, { "content": "class\tbasic_commonmark\n\n{\n\npublic:\n\n\tusing\tchar_type\t\t= typename std::remove_const<CharT>::type;\n\n\tusing\tpointer\t\t\t= typename std::add_const<char_type>::type*;\n\n\tusing\tconst_pointer\t= pointer;\n\n\tusing\ttraits_type\t\t= Traits;\n\n\tusing\tview_type\t\t= std::basic_string_view<char_type>;\n\n\tusing\tindent_type\t\t= size_t;\n\n\tusing\tposition_type\t= size_t;\n\n\tusing\tlinenumber_type\t= int;\n\n\tusing\tsize_type\t\t= size_t;\n\n\n", "file_path": "include/amtrs/text-commonmark.hpp", "rank": 7, "score": 107822.46654019985 }, { "content": "class\tbasic_zip_entry;\n\n\n\ntemplate<class IN>\n", "file_path": "include/amtrs/filesystem.hpp", "rank": 8, "score": 107822.46654019985 }, { "content": "class\tbasic_archive_enumrator\n\n{\n\npublic:\n", "file_path": "include/amtrs/archive.hpp", "rank": 9, "score": 107822.46654019985 }, { "content": "enum class progresstype\n\n{\n\n\tnone\t\t= 0,\n\n\textract\t\t= 1,\n\n\tdownload\t= 2,\n\n\tsubprocess\t= 3,\n\n};\n\n\n\n\n\nvoid progress_start(progresstype _type, size_t _start, size_t _end, char const* _reson);\n\nvoid progress_maxsize(size_t _end);\n\nvoid progress_inc(size_t _inc = 1);\n\nvoid progress_inc_bandwide(int _wide, size_t _inc = 1);\n\nvoid progress_inc_string(std::string_view _line, size_t _inc = 1);\n\nvoid progress_end();\n\n\n\n\n\n\n\nAMTRS_CONSOLE_NAMESPACE_END\n\n#endif\n", "file_path": "include/amtrs/console.hpp", "rank": 10, "score": 106836.53410663691 }, { "content": "enum class\topterr\n\n{\n\n\teoa\t\t\t\t= 0,\n\n\tunknown_err\t\t= 1,\n\n\tnone_argumrnt\t= 2,\n\n};\n\n\n", "file_path": "include/amtrs/optparse.hpp", "rank": 11, "score": 106836.53410663691 }, { "content": "enum class\topttype\n\n{\n\n\tnone\t\t= 0,\t\t//!< Have not arg.\n\n\trequired\t= 1,\t\t//!< Requirement arg.\n\n};\n\n\n", "file_path": "include/amtrs/optparse.hpp", "rank": 12, "score": 106836.53410663691 }, { "content": "enum class\topenmode\n\n{\n\n\topen\t\t\t= 0<<0,\t\t\t//!< ファイルを開く(存在しない場合はエラー)\n\n\tcreate\t\t\t= 1<<0,\t\t\t//!< ファイルを新規作成する(存在する場合はエラー)\n\n\topen_always\t\t= 2<<0,\t\t\t//!< ファイルを開く(存在しない場合は作成する)\n\n\tcreate_always\t= 3<<0,\t\t\t//!< ファイルを新規作成する(存在する場合は作成しなおす)\n\n\n\n\tuse_read\t\t= 1<<16,\t\t//!< 読み込みを許可する\n\n\tuse_write\t\t= 1<<17\t\t\t//!< 書き込みを許可する\n\n};\n\n\n\nstatic constexpr unsigned int\topenmode_modemask\t= 0x0f;\n\n\n\nAMTRS_IO_NAMESPACE_END\n\n\n\n#include \".inc/memory-view.hpp\"\n\n#include \".inc/typeutil-listener.hpp\"\n\n\n\n#include \".inc/io-streamif.hpp\"\n\n#include \".inc/io-streamif-iostream.hpp\"\n", "file_path": "include/amtrs/io.hpp", "rank": 13, "score": 106836.53410663691 }, { "content": "\tenum class\tnodetype\n\n\t{\n\n\t\tnone,\t\t\t\t\t\t// no initialized\n\n\t\tblockquote,\t\t\t\t\t// <blockquote>\n\n\t\tlist,\t\t\t\t\t\t// <ul>\n\n\t\titem,\t\t\t\t\t\t// <li>\n\n\t\tcodeblock,\t\t\t\t\t// <pre><code>\n\n\t\thtmlblock,\t\t\t\t\t// \"<\"\n\n\t\trawblock,\t\t\t\t\t// \n\n\t\tparagraph,\t\t\t\t\t// <p>\n\n\t\theading,\t\t\t\t\t// <h[1-6]>\n\n\t\tthematic_break,\t\t\t\t// <hr>\n\n\t\ttable,\t\t\t\t\t\t// <table>\n\n\t\ttable_row,\t\t\t\t\t// <tr>\n\n\t\ttable_cell,\t\t\t\t\t// <td>\n\n\n\n\t\t// inline\n\n\t\ttext,\t\t\t\t\t\t//\n\n\t\tsoftbreak,\t\t\t\t\t// \\n\n\n\t\tlinebreak,\t\t\t\t\t// <br />\n", "file_path": "include/amtrs/text-commonmark.hpp", "rank": 14, "score": 104805.93199464903 }, { "content": "", "file_path": "include/amtrs/font.hpp", "rank": 15, "score": 104805.93199464903 }, { "content": "", "file_path": "include/amtrs/font.hpp", "rank": 16, "score": 104805.93199464903 }, { "content": "enum class transfer_encoding_type\n\n{\n\n\tchunked,\n\n\tcompress,\t\t//!< LZW\n\n\tdeflate,\t\t//!< zlib/deflate\n\n\tgzip,\t\t\t//!< LZ77\n\n\tidentity,\t\t//!< no compress\n\n};\n\n\n\n\n\nAMTRS_NET_HTTP_NAMESPACE_END\n\n\n\n#include \".inc/net-http-hpack.hpp\"\n\n#include \".inc/net-http-parser.hpp\"\n\n#include \".inc/net-http-http_header_analyzer.hpp\"\n\n#include \".inc/net-http-mini_http.hpp\"\n\n#include \".inc/net-simple_http.hpp\"\n\n\n\n\n\n#endif\n", "file_path": "include/amtrs/net.hpp", "rank": 17, "score": 102877.39660876113 }, { "content": "enum class update_result : int\n\n{\n\n\terr\t\t= 0,\n\n\tmodify\t= 1,\n\n\tskip\t= 2,\n\n};\n\nstatic constexpr update_result\tupdate_err\t\t= update_result::err;\n\nstatic constexpr update_result\tupdate_modify\t= update_result::modify;\n\nstatic constexpr update_result\tupdate_skip\t\t= update_result::skip;\n\n\n\n\n\ninline bool is_good(update_result _r) noexcept { return _r == update_modify || _r == update_skip; }\n\ninline bool is_bad(update_result _r) noexcept { return !is_good(_r); }\n\n\n\n\n", "file_path": "include/amtrs/scriptutil.hpp", "rank": 18, "score": 100394.5064888357 }, { "content": "struct\tActivity;\n\n}\n\n\n\nnamespace android::content {\n", "file_path": "include/amtrs/java/androidx/core/app/ActivityCompat.hpp", "rank": 19, "score": 82037.36496788292 }, { "content": "struct\tAmtrsActivityResult;\n\n\n\n\n\nAMTRS_JAVA_DEFINE_CLASS(AmtrsActivity, androidx::fragment::app::FragmentActivity)\n\n{\n\n\tusing\tView\t= android::view::View;\n\n\n\n\tAMTRS_JAVA_CLASS_SIGNATURE(\"jp/libamtrs/AmtrsActivity\");\n\n\n\n\n\n\t// クラスメソッドとクラスフィールド\n\n\tAMTRS_JAVA_DEFINE_STATIC_MEMBER\n\n\t{\n\n\t\tAMTRS_JAVA_STATICS_BASIC;\n\n\t};\n\n\n\n\n\n\t// 動的メソッドと動的フィールド\n\n\tAMTRS_JAVA_DEFINE_DYNAMICS_MEMBER\n\n\t{\n", "file_path": "include/amtrs/java/jp/libamtrs/AmtrsActivity.hpp", "rank": 20, "score": 80535.6693411489 }, { "content": "/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *\n\n * Use of this source code is governed by a BSD-style license that *\n\n * can be found in the LICENSE file. */\n\n#ifndef\t__libamtrs__android__java_classes__android_app_Activity__hpp\n\n#define\t__libamtrs__android__java_classes__android_app_Activity__hpp\n\n#include <amtrs/java/android/view/ContextThemeWrapper.hpp>\n\nAMTRS_JAVA_CLASSES_NAMESPACE_BEGIN\n\n\n\nnamespace android::view {\n", "file_path": "include/amtrs/java/android/app/Activity.hpp", "rank": 21, "score": 76755.28883544439 }, { "content": "/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *\n\n * Use of this source code is governed by a BSD-style license that *\n\n * can be found in the LICENSE file. */\n\n#ifndef\t__libamtrs__java__java__lang__Class__hpp\n\n#define\t__libamtrs__java__java__lang__Class__hpp\n\n#include \"Object.hpp\"\n\nAMTRS_JAVA_CLASSES_NAMESPACE_BEGIN\n\nnamespace java::lang {\n\n\n\nAMTRS_JAVA_DEFINE_CLASS(Class, Object)\n\n{\n\n\tAMTRS_JAVA_CLASS_SIGNATURE(\"java/lang/Class\");\n\n\n\n\n\n\t// クラスメソッドとクラスフィールド\n\n\tAMTRS_JAVA_DEFINE_STATIC_MEMBER\n\n\t{\n\n\t\tAMTRS_JAVA_STATICS_BASIC;\n\n\t};\n\n\n", "file_path": "include/amtrs/java/java/lang/Class.hpp", "rank": 22, "score": 76754.64517513558 }, { "content": "\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(onStop\n\n\t\t\t, void()\n\n\t\t)\n\n\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(onStart\n\n\t\t\t, void()\n\n\t\t)\n\n\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(onResume\n\n\t\t\t, void()\n\n\t\t)\n\n\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(setVolumeControlStream\n\n\t\t\t, void(int streamType)\n\n\t\t)\n\n\n\n\t};\n\n};\n\n\n\n\n\n}\n\nAMTRS_JAVA_CLASSES_NAMESPACE_END\n\n#endif\n", "file_path": "include/amtrs/java/android/app/Activity.hpp", "rank": 23, "score": 76753.26096877285 }, { "content": "\t\t)\n\n\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(isFinishing\n\n\t\t\t, void()\n\n\t\t)\n\n\n\n\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(onActivityResult \n\n\t\t\t, void(int requestCode, int resultCode, Intent data)\n\n\t\t)\n\n\n\n\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(startActivityForResult\n\n\t\t\t, void(Intent intent, int requestCode)\n\n\t\t\t, void(Intent intent, int requestCode, Bundle options)\n\n\t\t)\n\n\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(onPause\n\n\t\t\t, void()\n\n\t\t)\n", "file_path": "include/amtrs/java/android/app/Activity.hpp", "rank": 24, "score": 76750.66240591161 }, { "content": "\n\n\t// 動的メソッドと動的フィールド\n\n\tAMTRS_JAVA_DEFINE_DYNAMICS_MEMBER\n\n\t{\n\n\t\tAMTRS_JAVA_DYNAMICS_BASIC;\n\n\t};\n\n};\n\n\n\n\n\n}\n\nAMTRS_JAVA_CLASSES_NAMESPACE_END\n\n#endif\n", "file_path": "include/amtrs/java/java/lang/Class.hpp", "rank": 25, "score": 76748.18192288498 }, { "content": "\t\tAMTRS_JAVA_STATICS_BASIC;\n\n\t};\n\n\n\n\n\n\t// 動的メソッドと動的フィールド\n\n\tAMTRS_JAVA_DEFINE_DYNAMICS_MEMBER\n\n\t{\n\n\t\tAMTRS_JAVA_DYNAMICS_BASIC;\n\n\n\n\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(finish\n\n\t\t\t, void()\n\n\t\t)\n\n\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(getWindow\n\n\t\t\t, Window()\n\n\t\t)\n\n\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(getWindowManager \n\n\t\t\t, WindowManager()\n", "file_path": "include/amtrs/java/android/app/Activity.hpp", "rank": 26, "score": 76744.53209109086 }, { "content": "/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *\n\n * Use of this source code is governed by a BSD-style license that *\n\n * can be found in the LICENSE file. */\n\n#ifndef\t__libamtrs__android__java_classes__jp_libamtrs_AmtrsActivity__hpp\n\n#define\t__libamtrs__android__java_classes__jp_libamtrs_AmtrsActivity__hpp\n\n#include \"../../androidx/fragment/app/FragmentActivity.hpp\"\n\n\n\nAMTRS_JAVA_CLASSES_NAMESPACE_BEGIN\n\n\n\nnamespace android::view {\n", "file_path": "include/amtrs/java/jp/libamtrs/AmtrsActivity.hpp", "rank": 27, "score": 74827.3191423817 }, { "content": "/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *\n\n * Use of this source code is governed by a BSD-style license that *\n\n * can be found in the LICENSE file. */\n\n#ifndef\t__libamtrs__java__java__lang__ClassLoader__hpp\n\n#define\t__libamtrs__java__java__lang__ClassLoader__hpp\n\n#include \"Object.hpp\"\n\nAMTRS_JAVA_CLASSES_NAMESPACE_BEGIN\n\nnamespace java::io {\n\n\tstruct\tFile;\n\n\tstruct\tFileInputStream;\n\n\tstruct\tFileOutputStream;\n\n\tstruct\tInputStream;\n\n\tstruct\tOutputStream;\n\n}\n\n\n\nnamespace java::lang {\n\n\n\n\n\nAMTRS_JAVA_DEFINE_CLASS(ClassLoader , java::lang::Object)\n\n{\n", "file_path": "include/amtrs/java/java/lang/ClassLoader.hpp", "rank": 28, "score": 74825.0910240612 }, { "content": "\t\t)\n\n\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(pushView\n\n\t\t\t, void(View _topView)\n\n\t\t)\n\n\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(popView\n\n\t\t\t, void()\n\n\t\t)\n\n\t};\n\n};\n\n\n\n\n\n}\n\nAMTRS_JAVA_CLASSES_NAMESPACE_END\n\n#endif\n", "file_path": "include/amtrs/java/jp/libamtrs/AmtrsActivity.hpp", "rank": 29, "score": 74824.65588013202 }, { "content": "\t\tAMTRS_JAVA_DYNAMICS_BASIC;\n\n\n\n\n\n/*\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(openDocument\n\n\t\t\t, void(AmtrsActivityResult, java::lang::String)\n\n\t\t)\n\n\n\n\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(addActivityResult\n\n\t\t\t, int(AmtrsActivityResult)\n\n\t\t)\n\n*/\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(addView\n\n\t\t\t, void(View _topView)\n\n\t\t)\n\n\n\n\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(foreground\n\n\t\t\t, void()\n", "file_path": "include/amtrs/java/jp/libamtrs/AmtrsActivity.hpp", "rank": 30, "score": 74822.34303956924 }, { "content": "\tusing\tClass\t\t\t\t= java::lang::Class;\n\n\tusing\tString\t\t\t\t= java::lang::String;\n\n\tusing\tFile\t\t\t\t= java::io::File;\n\n\tusing\tFileInputStream\t\t= java::io::FileInputStream;\n\n\tusing\tFileOutputStream\t= java::io::FileOutputStream;\n\n\tusing\tInputStream\t\t\t= java::io::InputStream;\n\n\tusing\tOutputStream\t\t= java::io::OutputStream;\n\n\n\n\tAMTRS_JAVA_CLASS_SIGNATURE(\"java/lang/ClassLoader\");\n\n\n\n\n\n\t// クラスメソッドとクラスフィールド\n\n\tAMTRS_JAVA_DEFINE_STATIC_MEMBER\n\n\t{\n\n\t\tAMTRS_JAVA_STATICS_BASIC;\n\n\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(getSystemClassLoader\n\n\t\t\t, ClassLoader()\n\n\t\t)\n\n\n", "file_path": "include/amtrs/java/java/lang/ClassLoader.hpp", "rank": 31, "score": 74821.40852447957 }, { "content": "\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(loadClass\n\n\t\t\t, Class(String name)\n\n\t\t)\n\n\n\n\n\n\t};\n\n};\n\n\n\n\n\n}\n\nAMTRS_JAVA_CLASSES_NAMESPACE_END\n\n#endif\n", "file_path": "include/amtrs/java/java/lang/ClassLoader.hpp", "rank": 32, "score": 74820.83586741208 }, { "content": "\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(clearAssertionStatus\n\n\t\t\t, void()\n\n\t\t)\n\n\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(getParent\n\n\t\t\t, ClassLoader()\n\n\t\t)\n\n\n\n//\t\tAMTRS_JAVA_DEFINE_METHOD(getResource\n\n//\t\t\t, URL(String name)\n\n//\t\t)\n\n\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(getResourceAsStream\n\n\t\t\t, InputStream(String name)\n\n\t\t)\n\n\n\n/*\t\tAMTRS_JAVA_DEFINE_METHOD(getResources\n\n\t\t\t, Enumeration<URL> (String name)\n\n\t\t)*/\n", "file_path": "include/amtrs/java/java/lang/ClassLoader.hpp", "rank": 33, "score": 74818.95512854816 }, { "content": "\t\tAMTRS_JAVA_DEFINE_METHOD(getSystemResource\n\n\t\t\t, ClassLoader(String name)\n\n\t\t)\n\n\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(getSystemResourceAsStream\n\n\t\t\t, InputStream(String name)\n\n\t\t)\n\n\n\n/*\t\tAMTRS_JAVA_DEFINE_METHOD(getSystemResources\n\n\t\t\t, Enumeration<URL> (String name)\n\n\t\t)*/\n\n\n\n\t};\n\n\n\n\n\n\t// 動的メソッドと動的フィールド\n\n\tAMTRS_JAVA_DEFINE_DYNAMICS_MEMBER\n\n\t{\n\n\t\tAMTRS_JAVA_DYNAMICS_BASIC;\n\n\n", "file_path": "include/amtrs/java/java/lang/ClassLoader.hpp", "rank": 34, "score": 74815.52901477118 }, { "content": "struct\tWindow;\n", "file_path": "include/amtrs/java/android/app/Activity.hpp", "rank": 35, "score": 74807.30551473495 }, { "content": "\t\t\t\t, jboolean(Activity activity, String permission)\n\n\t\t\t)\n\n\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(startActivityForResult\n\n\t\t\t\t, void(Activity activity, Intent intent, jint requestCode, Bundle options)\n\n\t\t\t)\n\n\t};\n\n\n\n\n\n\t// 動的メソッドと動的フィールド\n\n\tAMTRS_JAVA_DEFINE_DYNAMICS_MEMBER\n\n\t{\n\n\t\tAMTRS_JAVA_DYNAMICS_BASIC;\n\n\t};\n\n};\n\n\n\n\n\n}\n\nAMTRS_JAVA_CLASSES_NAMESPACE_END\n\n#endif\n", "file_path": "include/amtrs/java/androidx/core/app/ActivityCompat.hpp", "rank": 36, "score": 72993.88573682861 }, { "content": "/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *\n\n * Use of this source code is governed by a BSD-style license that *\n\n * can be found in the LICENSE file. */\n\n#ifndef\t__libamtrs__android__java_classes__androidx_fragment__app__FragmentActivity__hpp\n\n#define\t__libamtrs__android__java_classes__androidx_fragment__app__FragmentActivity__hpp\n\n#include \"../../../android/app/Activity.hpp\"\n\n\n\nAMTRS_JAVA_CLASSES_NAMESPACE_BEGIN\n\n\n\n\n\nnamespace androidx::fragment::app {\n\n\n", "file_path": "include/amtrs/java/androidx/fragment/app/FragmentActivity.hpp", "rank": 37, "score": 72993.24773331503 }, { "content": "/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *\n\n * Use of this source code is governed by a BSD-style license that *\n\n * can be found in the LICENSE file. */\n\n#ifndef\t__libamtrs__android__java_classes__androidx__core__app__ActivityCompat__hpp\n\n#define\t__libamtrs__android__java_classes__androidx__core__app__ActivityCompat__hpp\n\n#include \"../content/ContextCompat.hpp\"\n\nAMTRS_JAVA_CLASSES_NAMESPACE_BEGIN\n\n\n\nnamespace java::lang {\n", "file_path": "include/amtrs/java/androidx/core/app/ActivityCompat.hpp", "rank": 38, "score": 72992.77798800019 }, { "content": "\t{\n\n\t\tAMTRS_JAVA_STATICS_BASIC;\n\n\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(finishAffinity\n\n\t\t\t\t, void(Activity activity)\n\n\t\t\t)\n\n\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(\tfinishAfterTransition\n\n\t\t\t\t, void(Activity activity)\n\n\t\t\t)\n\n\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(getReferrer\n\n\t\t\t\t, Uri(Activity activity)\n\n\t\t\t)\n\n\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(requestPermissions\n\n\t\t\t\t, void(Activity activity, String permissions[], int requestCode)\n\n\t\t\t)\n\n\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(shouldShowRequestPermissionRationale\n", "file_path": "include/amtrs/java/androidx/core/app/ActivityCompat.hpp", "rank": 39, "score": 72989.0924042786 }, { "content": "struct\tWindowManager;\n\n}\n\n\n\nnamespace android::app {\n\n\n\n// https://developer.android.com/reference/android/app/Activity\n\nAMTRS_JAVA_DEFINE_CLASS(Activity, android::view::ContextThemeWrapper)\n\n{\n\n\tusing\tIntent\t\t\t= android::content::Intent;\n\n\tusing\tBundle\t\t\t= android::os::Bundle;\n\n\tusing\tWindow\t\t\t= android::view::Window;\n\n\tusing\tWindowManager\t= android::view::WindowManager;\n\n\n\n\n\n\tAMTRS_JAVA_CLASS_SIGNATURE(\"android/app/Activity\");\n\n\n\n\n\n\t// クラスメソッドとクラスフィールド\n\n\tAMTRS_JAVA_DEFINE_STATIC_MEMBER\n\n\t{\n", "file_path": "include/amtrs/java/android/app/Activity.hpp", "rank": 40, "score": 72973.33005317864 }, { "content": "struct\tView;\n\n}\n\n\n\nnamespace jp::libamtrs {\n\n\n", "file_path": "include/amtrs/java/jp/libamtrs/AmtrsActivity.hpp", "rank": 41, "score": 72973.33005317864 }, { "content": "struct\tActivity;\n\n}\n\n\n\nnamespace jp::libamtrs::Billing {\n\n\n\n\n\n// https://developer.android.com/reference/android/app/FragmentActivity\n\nAMTRS_JAVA_DEFINE_CLASS(Billing, com::android::billingclient::api::PurchasesUpdatedListener)\n\n{\n\n\tusing\tActivity\t\t= android::app::Activity;\n\n\tusing\tList\t\t\t= java::util::List;\n\n\tusing\tString\t\t\t= java::lang::String;\n\n\tusing\tPurchase\t\t= com::android::billingclient::api::Purchase;\n\n\tusing\tSkuDetails\t\t= com::android::billingclient::api::SkuDetails;\n\n\n\n\tAMTRS_JAVA_CLASS_SIGNATURE(\"jp/libamtrs/Billing/Billing\");\n\n\n\n\n\n\tAMTRS_JAVA_DEFINE_CLASS(Info, java::lang::Object)\n\n\t{\n", "file_path": "include/amtrs/java/jp/libamtrs/Billing.Billing.hpp", "rank": 42, "score": 72973.33005317864 }, { "content": "// ============================================================================\n\n//! 複数の vfs を保持します。\n\n// ----------------------------------------------------------------------------\n\nclass\tcascadevfs_impl\n\n\t\t: public cascadevfs\n\n{\n\npublic:\n\n\tusing\tlist_type\t= std::list<vfsptr>;\n\n\n\n\tvoid push_front(vfsptr _fs) override\n\n\t{\n\n\t\tmVfsList.push_front(std::move(_fs));\n\n\t}\n\n\n\n\tvoid push_back(vfsptr _fs) override\n\n\t{\n\n\t\tmVfsList.push_back(std::move(_fs));\n\n\t}\n\n\n\n\tvoid erase(vfs* _fs) override\n\n\t{\n\n\t\tauto\tit\t= std::remove(mVfsList.begin(), mVfsList.end(), _fs);\n\n\t\tif (it != mVfsList.end())\n", "file_path": "src/amtrs/base-filesystem-cascadevfs.cpp", "rank": 43, "score": 72144.57018362597 }, { "content": "/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *\n\n * Use of this source code is governed by a BSD-style license that *\n\n * can be found in the LICENSE file. */\n\n#ifndef\t__libamtrs__android__java_classes__android__support__v4__app__FragmentActivity__hpp\n\n#define\t__libamtrs__android__java_classes__android__support__v4__app__FragmentActivity__hpp\n\n#include <amtrs/java/android/app/Activity.hpp>\n\n\n\nAMTRS_JAVA_CLASSES_NAMESPACE_BEGIN\n\n\n\n\n\nnamespace android::support::v4::app {\n\n\n", "file_path": "include/amtrs/java/android/support/v4/app/FragmentActivity.hpp", "rank": 44, "score": 71246.57889958035 }, { "content": "\t{\n\n\t\tAMTRS_JAVA_DYNAMICS_BASIC;\n\n\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(getSupportFragmentManager\n\n\t\t\t, FragmentManager()\n\n\t\t)\n\n\t};\n\n};\n\n\n\n\n\n}\n\nAMTRS_JAVA_CLASSES_NAMESPACE_END\n\n#endif\n", "file_path": "include/amtrs/java/android/support/v4/app/FragmentActivity.hpp", "rank": 45, "score": 71238.91182841687 }, { "content": "struct\tActivity;\n\n}\n\n\n\n\n\nnamespace jp::libamtrs::alarm {\n\n\n\nAMTRS_JAVA_DEFINE_CLASS(AlarmReceiver, android::content::BroadcastReceiver)\n\n{\n\n\tusing\tActivity\t\t= android::app::Activity;\n\n\tusing\tClass\t\t\t= java::lang::Class;\n\n\tusing\tString\t\t\t= java::lang::String;\n\n\n\n\tAMTRS_JAVA_CLASS_SIGNATURE(\"jp/libamtrs/alarm/AlarmReceiver\");\n\n\n\n\n\n\t// クラスメソッドとクラスフィールド\n\n\tAMTRS_JAVA_DEFINE_STATIC_MEMBER\n\n\t{\n\n\t\tAMTRS_JAVA_STATICS_BASIC;\n\n\n", "file_path": "include/amtrs/java/jp/libamtrs/alarm/AlarmReceiver.hpp", "rank": 46, "score": 71227.12624550768 }, { "content": "struct\tString;\n\n}\n\n\n\nnamespace android::app {\n", "file_path": "include/amtrs/java/androidx/core/app/ActivityCompat.hpp", "rank": 47, "score": 71227.12624550768 }, { "content": "struct\tBundle;\n\n}\n\n\n\nnamespace androidx::core::app {\n\n\n\n\n\nAMTRS_JAVA_DEFINE_CLASS(ActivityCompat, androidx::core::content::ContextCompat)\n\n{\n\n\tusing\tActivity\t= android::app::Activity;\n\n\tusing\tBundle\t\t= android::os::Bundle;\n\n\tusing\tContext\t\t= android::content::Context;\n\n\tusing\tIntent\t\t= android::content::Intent;\n\n\tusing\tString\t\t= java::lang::String;\n\n\tusing\tUri\t\t\t= android::net::Uri;\n\n\n\n\tAMTRS_JAVA_CLASS_SIGNATURE(\"androidx/core/app/ActivityCompat\");\n\n\n\n\n\n\t// クラスメソッドとクラスフィールド\n\n\tAMTRS_JAVA_DEFINE_STATIC_MEMBER\n", "file_path": "include/amtrs/java/androidx/core/app/ActivityCompat.hpp", "rank": 48, "score": 71227.12624550768 }, { "content": "struct\tContext;\n", "file_path": "include/amtrs/java/androidx/core/app/ActivityCompat.hpp", "rank": 49, "score": 71227.12624550768 }, { "content": "struct\tIntent;\n\n}\n\n\n\nnamespace android::net {\n", "file_path": "include/amtrs/java/androidx/core/app/ActivityCompat.hpp", "rank": 50, "score": 71227.12624550768 }, { "content": "struct\tUri;\n\n}\n\n\n\nnamespace android::os {\n", "file_path": "include/amtrs/java/androidx/core/app/ActivityCompat.hpp", "rank": 51, "score": 71227.12624550768 }, { "content": "struct\tFragmentManager;\n\n\n\nAMTRS_JAVA_DEFINE_CLASS(FragmentActivity, android::app::Activity)\n\n{\n\n\tAMTRS_JAVA_CLASS_SIGNATURE(\"androidx/fragment/app/FragmentActivity\");\n\n\n\n\n\n\t// クラスメソッドとクラスフィールド\n\n\tAMTRS_JAVA_DEFINE_STATIC_MEMBER\n\n\t{\n\n\t\tAMTRS_JAVA_STATICS_BASIC;\n\n\t};\n\n\n\n\n\n\t// 動的メソッドと動的フィールド\n\n\tAMTRS_JAVA_DEFINE_DYNAMICS_MEMBER\n\n\t{\n\n\t\tAMTRS_JAVA_DYNAMICS_BASIC;\n\n\n\n\t\tAMTRS_JAVA_DEFINE_METHOD(getSupportFragmentManager\n\n\t\t\t, FragmentManager()\n\n\t\t)\n\n\t};\n\n};\n\n\n\n\n\n}\n\nAMTRS_JAVA_CLASSES_NAMESPACE_END\n\n#endif\n", "file_path": "include/amtrs/java/androidx/fragment/app/FragmentActivity.hpp", "rank": 52, "score": 69562.54039181385 }, { "content": "struct\tFragmentManager;\n\n\n\n// https://developer.android.com/reference/android/support/v4/app/FragmentActivity\n\nAMTRS_JAVA_DEFINE_CLASS(FragmentActivity, android::app::Activity)\n\n{\n\n\tusing\tFragmentManager\t\t= android::support::v4::app::FragmentManager;\n\n\n\n\n\n\tAMTRS_JAVA_CLASS_SIGNATURE(\"android/support/v4/app/FragmentActivity\");\n\n\n\n\n\n\t// クラスメソッドとクラスフィールド\n\n\tAMTRS_JAVA_DEFINE_STATIC_MEMBER\n\n\t{\n\n\t\tAMTRS_JAVA_STATICS_BASIC;\n\n\t};\n\n\n\n\n\n\t// 動的メソッドと動的フィールド\n\n\tAMTRS_JAVA_DEFINE_DYNAMICS_MEMBER\n", "file_path": "include/amtrs/java/android/support/v4/app/FragmentActivity.hpp", "rank": 53, "score": 67973.98090612596 }, { "content": "/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *\n\n * Use of this source code is governed by a BSD-style license that *\n\n * can be found in the LICENSE file. */\n\n#include <vector>\n\n#include <iostream>\n\n#include <stdio.h>\n\n#include <stdlib.h>\n\n#include <amtrs/amtrs.hpp>\n\nAMTRS_LOGGING_NAMESPACE_BEGIN\n\n\n\n\n\nvoid write(loglevel _level, const char* _msg, std::size_t _size, bool _return)\n\n{\n\n\tauto\t\t\t\t\tlen\t= ::MultiByteToWideChar(CP_UTF8, MB_PRECOMPOSED, _msg, (int)_size, nullptr, 0);\n\n\tstd::vector<wchar_t>\tbuf\t= std::vector<wchar_t>(static_cast<size_t>(len) + 1);\n\n\n\n\t::MultiByteToWideChar(CP_UTF8, MB_PRECOMPOSED, _msg, (int)_size, buf.data(), len + 1);\n\n\n\n\tstd::wcout << buf.data();\n\n\tif (_return)\n\n\t{\n\n\t\tstd::wcout << std::endl;\n\n\t}\n\n}\n\n\n\n\n\nAMTRS_LOGGING_NAMESPACE_END\n", "file_path": "src/amtrs/win32-logging.cpp", "rank": 54, "score": 44556.93659569661 }, { "content": "/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *\n\n * Use of this source code is governed by a BSD-style license that *\n\n * can be found in the LICENSE file. */\n\n#include <amtrs/filesystem.hpp>\n\n#include <amtrs/system.hpp>\n\n#include <shlobj.h>\n\n\n\n\n\nAMTRS_NAMESPACE_BEGIN\n\n\n\nstatic bool is_sep(char c) { return c == '\\\\' || c == '/'; }\n\n\n\n\n\nvoid setenv(std::string_view _key, std::string_view _value)\n\n{\n\n\tstd::string\tenv(_key);\n\n\tenv += \"=\";\n\n\tenv += _value;\n\n\t_putenv(env.c_str());\n\n/*\tstd::string\tkey(_key);\n", "file_path": "src/amtrs/win32-system.cpp", "rank": 55, "score": 44551.901711580394 }, { "content": "/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *\n\n * Use of this source code is governed by a BSD-style license that *\n\n * can be found in the LICENSE file. */\n\n#if\t0\n\n#include <amtrs/amtrs.hpp>\n\n#include <amtrs/locale/locale.hpp>\n\nAMTRS_NAMESPACE_BEGIN\n\n\n\n\n", "file_path": "src/amtrs/win32-locale.cpp", "rank": 56, "score": 44547.17410764776 }, { "content": "\tchar\trootDir[MAX_PATH];\n\n\tSHGetSpecialFolderPathA(nullptr, rootDir, CSIDL_LOCAL_APPDATA, 0);\n\n\n\n\tstd::string\tdir;\n\n\tdir\t+= rootDir;\n\n\tdir += \"\\\\\";\n\n\tdir += _appname;\n\n\tdir\t= filesystem::normalize_path(dir);\n\n\n\n\tauto*\tdata\t= reinterpret_cast<char*>(_destinate.allocate(_destinate.object, dir.size()));\n\n\tif (!data)\n\n\t{\n\n\t\treturn\tfalse;\n\n\t}\n\n\tstd::copy_n(dir.data(), dir.size(), data);\n\n\treturn\ttrue;\n\n}\n\n\n\nAMTRS_NAMESPACE_END\n", "file_path": "src/amtrs/win32-system.cpp", "rank": 57, "score": 44541.34670564832 }, { "content": "\treturn\t*this;\n\n}\n\n\n\nlocale::~locale()\n\n{\n\n}\n\n\n\nstd::string locale::get_language() const\n\n{\n\n\tCHAR\tiso639 [10];\n\n\tCHAR\tiso3166[10];\n\n\tGetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_SISO639LANGNAME , iso639, sizeof(iso639));\n\n\tGetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_SISO3166CTRYNAME, iso3166, sizeof(iso3166));\n\n\tchar\trfc3282[8];\n\n\tsnprintf(rfc3282, sizeof(rfc3282), \"%s_%s\", iso639, iso3166);\n\n\treturn\trfc3282;\n\n}\n\n\n\n\n\nAMTRS_NAMESPACE_END\n\n#endif\n", "file_path": "src/amtrs/win32-locale.cpp", "rank": 58, "score": 44538.24705364919 }, { "content": "\tstd::string\tval(_value);\n\n\tSetEnvironmentVariableA(key.c_str(), val.c_str());\n\n*/\n\n}\n\n\n\n\n\n//! プラットフォームの特殊なファイルパスを取得します。\n\nbool special_path(amtrs_bufferif_one_init _destinate, specialpathtype _type, std::string_view _appname)\n\n{\n\n\n\n\tint\t\tcsidl\t= CSIDL_LOCAL_APPDATA;\n\n\tswitch (_type)\n\n\t{\n\n\t\tcase specialpathtype::home:\t\t\tcsidl = CSIDL_PROFILE; break;\n\n\t\tcase specialpathtype::cache:\t\tcsidl = CSIDL_LOCAL_APPDATA; break;\n\n\t\tcase specialpathtype::app_local:\tcsidl = CSIDL_LOCAL_APPDATA; break;\n\n\t\tcase specialpathtype::app_backup:\tcsidl = CSIDL_APPDATA; break;\n\n\t\tcase specialpathtype::config:\t\tcsidl = CSIDL_LOCAL_APPDATA; break;\n\n\t}\n\n\n", "file_path": "src/amtrs/win32-system.cpp", "rank": 59, "score": 44537.92928596749 }, { "content": "struct\tlocale_impl : locale\n\n{\n\n\tstruct\tinstance : locale::instance\n\n\t{\n\n\t\t\n\n\t};\n\n};\n\n\n\nlocale::locale()\n\n{\n\n}\n\n\n\nlocale::locale(locale&& _r)\n\n\t: mInstance(std::move(_r.mInstance))\n\n{\n\n}\n\n\n\nlocale& locale::operator = (locale&& _r)\n\n{\n\n\tmInstance\t= std::move(_r.mInstance);\n", "file_path": "src/amtrs/win32-locale.cpp", "rank": 60, "score": 41177.279894561965 }, { "content": "/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *\n\n * Use of this source code is governed by a BSD-style license that *\n\n * can be found in the LICENSE file. */\n\n#ifndef\t__libamtrs__libamtrs__scriptutil__hpp\n\n#define\t__libamtrs__libamtrs__scriptutil__hpp\n\n#include \"filesystem.hpp\"\n\n#include <deque>\n\n#include <functional>\n\n#include <string>\n\n#define\tAMTRS_SCRIPTUTIL_NAMESPACE\t\t\tAMTRS_NAMESPACE::ssu\n\n#define\tAMTRS_SCRIPTUTIL_NAMESPACE_BEGIN\tnamespace AMTRS_SCRIPTUTIL_NAMESPACE {\n\n#define\tAMTRS_SCRIPTUTIL_NAMESPACE_END\t\t}\n\nAMTRS_SCRIPTUTIL_NAMESPACE_BEGIN\n\n\n\ntemplate<class T>\n\nusing\tspan_callback\t= void(T*, size_t);\n\n\n", "file_path": "include/amtrs/scriptutil.hpp", "rank": 61, "score": 37538.20654715926 }, { "content": "/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *\n\n * Use of this source code is governed by a BSD-style license that *\n\n * can be found in the LICENSE file. */\n\n#ifndef\t__libamtrs__jni__hpp\n\n#define\t__libamtrs__jni__hpp\n\n#include \"amtrs.hpp\"\n\n#include \"string.hpp\"\n\n\n\n#include <jni.h>\n\n#define\tAMTRS_JAVA_NAMESPACE_BEGIN\tAMTRS_NAMESPACE_BEGIN namespace java {\n\n#define\tAMTRS_JAVA_NAMESPACE_END\t} AMTRS_NAMESPACE_END\n\n#define\tAMTRS_JAVA_CLASSES_NAMESPACE_BEGIN\tAMTRS_JAVA_NAMESPACE_BEGIN namespace classes {\n\n#define\tAMTRS_JAVA_CLASSES_NAMESPACE_END\t} AMTRS_JAVA_NAMESPACE_END\n\nAMTRS_JAVA_NAMESPACE_BEGIN\n\n\n\n\n\ntemplate<class T>\t\tstruct\tjcls;\t\t// Prototype, not use.\n\ntemplate<class T>\t\tstruct\tjobj;\t\t// Prototype, not use.\n\ntemplate<class...>\t\tstruct\tjni_traits;\n\ntemplate<class JniT>\tclass\tlref;\n\ntemplate<class JniT>\tclass\tgref;\n\ntemplate<class T>\t\tstruct\targv;\n\n\n\n\n\ntemplate<class T>\n", "file_path": "include/amtrs/jni.hpp", "rank": 62, "score": 37538.08282408042 }, { "content": "/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *\n\n * Use of this source code is governed by a BSD-style license that *\n\n * can be found in the LICENSE file. */\n\n#ifndef\t__libamtrs__archive__archive_enumrator__hpp\n\n#define\t__libamtrs__archive__archive_enumrator__hpp\n\n#include \"io.hpp\"\n\n\n\n\n\n#if\t\t__has_include(<libarchive/archive.h>)\n\n#include <libarchive/archive.h>\n\n#include <libarchive/archive_entry.h>\n\n#define\tAMTRS_LIBARCHIVE_USE\t1\n\n#elif\t__has_include(<libarchive/archive.h>)\n\n#include <archive.h>\n\n#include <archive_entry.h>\n\n#define\tAMTRS_LIBARCHIVE_USE\t1\n\n#endif\n\n\n\n#if\t\tAMTRS_LIBARCHIVE_USE\n\nAMTRS_NAMESPACE_BEGIN\n\n\n\ntemplate<class Callback>\n\nbool archive_enumrate(const char* _filename);\n\n\n\n\n\n\n\ntemplate<class T>\n", "file_path": "include/amtrs/archive.hpp", "rank": 63, "score": 37536.985354086326 }, { "content": "/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *\n\n * Use of this source code is governed by a BSD-style license that *\n\n * can be found in the LICENSE file. */\n\n#ifndef\t__libamtrs__g3d__hpp\n\n#define\t__libamtrs__g3d__hpp\n\n#include \"amtrs.hpp\"\n\n#include \"geometry.hpp\"\n\n#include \"graphics.hpp\"\n\n\n\n#define\tAMTRS_G3D_NAMESPACE_BEGIN\t\tAMTRS_NAMESPACE_BEGIN namespace g3d {\n\n#define\tAMTRS_G3D_NAMESPACE_END\t\t\t} AMTRS_NAMESPACE_END\n\n#define\tAMTRS_G3DEX_NAMESPACE_BEGIN\t\tAMTRS_G3D_NAMESPACE_BEGIN\n\n#define\tAMTRS_G3DEX_NAMESPACE_END\t\tAMTRS_G3D_NAMESPACE_END\n\n\n\n// keep order.\n\n#include \".inc/g3d-attribute.hpp\"\n\n#include \".inc/g3d-device.hpp\"\t\t\t\t// depature\n\n#include \".inc/g3d-basicshader.hpp\"\n\n\n\n#endif\n", "file_path": "include/amtrs/g3d.hpp", "rank": 64, "score": 37536.6113235472 }, { "content": "/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *\n\n * Use of this source code is governed by a BSD-style license that *\n\n * can be found in the LICENSE file. */\n\n#ifndef\t__libamtrs__tests__hpp\n\n#define\t__libamtrs__tests__hpp\n\n#include \"amtrs.hpp\"\n\n#include <iostream>\n\n\n\n#define\tAMTRS_TEST_NAMESPACE\t\tAMTRS_NAMESPACE::test\n\n#define\tAMTRS_TEST_NAMESPACE_BEGIN\tnamespace AMTRS_TEST_NAMESPACE {\n\n#define\tAMTRS_TEST_NAMESPACE_END\t}\n\n\n\nAMTRS_TEST_NAMESPACE_BEGIN\n\nextern\tbool\t\tfailed;\n\n\n\n\n\nint tests(int _argc, char** _args);\n\nstd::iostream& teststream();\n\n\n\n\n", "file_path": "include/amtrs/tests.hpp", "rank": 65, "score": 37536.3363454442 }, { "content": "/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *\n\n * Use of this source code is governed by a BSD-style license that *\n\n * can be found in the LICENSE file. */\n\n#ifndef\t__libamtrs__libamtrs__console__hpp\n\n#define\t__libamtrs__libamtrs__console__hpp\n\n#include \"filesystem.hpp\"\n\n#include <deque>\n\n#include <functional>\n\n#include <string>\n\n#define\tAMTRS_CONSOLE_NAMESPACE\t\t\tAMTRS_NAMESPACE::console\n\n#define\tAMTRS_CONSOLE_NAMESPACE_BEGIN\tnamespace AMTRS_CONSOLE_NAMESPACE {\n\n#define\tAMTRS_CONSOLE_NAMESPACE_END\t\t}\n\nAMTRS_CONSOLE_NAMESPACE_BEGIN\n\n\n\nstatic constexpr char const\tclear_line[]\t\t= { \"\\033[K\" };\n\nstatic constexpr char const\tcarriage_return[]\t= { \"\\r\" };\n\nstatic constexpr char const\tnew_line[]\t\t\t= { \"\\n\" };\n\nstatic constexpr char const\tline_feed[]\t\t\t= { \"\\n\" };\n\n\n\nstatic constexpr char const\tfgcolor_black[]\t\t= { \"\\033[30m\" };\n", "file_path": "include/amtrs/console.hpp", "rank": 66, "score": 37536.23629588474 }, { "content": "\n\n\titerator end()\n\n\t{\n\n\t\treturn\titerator(nullptr);\n\n\t}\n\n\n\n\n\n\tbool empty() const noexcept\n\n\t{\n\n\t\treturn\tmArc == nullptr;\n\n\t}\n\n\n\n\tstruct archive*\tmArc\t= nullptr;\n\n\tfriend iterator;\n\n};\n\n\n\n\n\nusing\tarchive_enumrator\t= basic_archive_enumrator<char>;\n\n\n\ntemplate<class Callback>\n", "file_path": "include/amtrs/archive.hpp", "rank": 67, "score": 37534.99122353162 }, { "content": "/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *\n\n * Use of this source code is governed by a BSD-style license that *\n\n * can be found in the LICENSE file. */\n\n#ifndef\t__libamtrs__chrono__hpp\n\n#define\t__libamtrs__chrono__hpp\n\n#include \"amtrs.hpp\"\n\n\n\n#include <ctime>\n\n#include <chrono>\n\n#include <functional>\n\n#include <iomanip>\n\n#include <locale>\n\n#include <stdexcept>\n\n#include <sstream>\n\n#include <thread>\n\n#include \"io.hpp\"\n\n\n\n#define\tAMTRS_CHRONO_NAMESPACE\t\t\tAMTRS_NAMESPACE::chrono\n\n#define\tAMTRS_CHRONO_NAMESPACE_BEGIN\tAMTRS_NAMESPACE_BEGIN namespace chrono {\n\n#define\tAMTRS_CHRONO_NAMESPACE_END\t\t} AMTRS_NAMESPACE_END\n", "file_path": "include/amtrs/chrono.hpp", "rank": 68, "score": 37534.97589232539 }, { "content": "/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *\n\n * Use of this source code is governed by a BSD-style license that *\n\n * can be found in the LICENSE file. */\n\n#ifndef\t__libamtrs__net__hpp\n\n#define\t__libamtrs__net__hpp\n\n#include \"amtrs.hpp\"\n\n#include <unordered_map>\n\n#include <vector>\n\n\n\n#include \"io.hpp\"\n\n#include \"string.hpp\"\n\n#include \".inc/typeutil-listener.hpp\"\n\n\n\n#define\tAMTRS_NET_NAMESPACE_BEGIN\tAMTRS_NAMESPACE_BEGIN namespace net {\n\n#define\tAMTRS_NET_NAMESPACE_END\t\t} AMTRS_NAMESPACE_END\n\nAMTRS_NET_NAMESPACE_BEGIN\n\nAMTRS_NET_NAMESPACE_END\n\n\n\n#include \".inc/net-types.hpp\"\n\n#include \".inc/net-uri.hpp\"\n", "file_path": "include/amtrs/net.hpp", "rank": 69, "score": 37534.582663431785 }, { "content": "/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *\n\n * Use of this source code is governed by a BSD-style license that *\n\n * can be found in the LICENSE file. */\n\n#ifndef\t__libamtrs__crypto__hpp\n\n#define\t__libamtrs__crypto__hpp\n\n#include \"amtrs.hpp\"\n\n\n\n#define\tAMTRS_CRYPTO_NAMESPACE_BEGIN\tAMTRS_NAMESPACE_BEGIN namespace crypto {\n\n#define\tAMTRS_CRYPTO_NAMESPACE_END\t\t} AMTRS_NAMESPACE_END\n\nAMTRS_CRYPTO_NAMESPACE_BEGIN\n\nAMTRS_CRYPTO_NAMESPACE_END\n\n\n\n#include \".inc/crypto-aes.hpp\"\n\n#include \".inc/crypto-crc32.hpp\"\n\n#include \".inc/crypto-md5.hpp\"\n\n#include \".inc/crypto-sha256.hpp\"\n\n#endif\n", "file_path": "include/amtrs/crypto.hpp", "rank": 70, "score": 37534.30795690587 }, { "content": "/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *\n\n * Use of this source code is governed by a BSD-style license that *\n\n * can be found in the LICENSE file. */\n\n#ifndef\t__libamtrs__io__hpp\n\n#define\t__libamtrs__io__hpp\n\n#include \"amtrs.hpp\"\n\n#include <ios>\n\n#include <iosfwd>\n\n#include <streambuf>\n\n\n\n#define\tAMTRS_IO_NAMESPACE_BEGIN\t\tAMTRS_NAMESPACE_BEGIN namespace io {\n\n#define\tAMTRS_IO_NAMESPACE_END\t\t\t} AMTRS_NAMESPACE_END\n\n// dep\n\n#define\tAMTRS_IOSTREAM_NAMESPACE_BEGIN\tAMTRS_IO_NAMESPACE_BEGIN\n\n#define\tAMTRS_IOSTREAM_NAMESPACE_END\tAMTRS_IO_NAMESPACE_END\n\nAMTRS_IO_NAMESPACE_BEGIN\n\n\n", "file_path": "include/amtrs/io.hpp", "rank": 71, "score": 37534.27872408702 }, { "content": "/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *\n\n * Use of this source code is governed by a BSD-style license that *\n\n * can be found in the LICENSE file. */\n\n#ifndef\t__libamtrs__system__hpp\n\n#define\t__libamtrs__system__hpp\n\n#include \"amtrs.hpp\"\n\n\n\n#define\tAMTRS_NAMESPACE_SYSTEM_BEGIN\tAMTRS_NAMESPACE_BEGIN namespace system {\n\n#define\tAMTRS_NAMESPACE_SYSTEM_END\t\t} AMTRS_NAMESPACE_END\n\nAMTRS_NAMESPACE_SYSTEM_BEGIN\n\nAMTRS_NAMESPACE_SYSTEM_END\n\n#include \".inc/system-env.hpp\"\n\n#include \".inc/system-power.hpp\"\n\n#include \".inc/system-process.hpp\"\n\n#endif\n", "file_path": "include/amtrs/system.hpp", "rank": 72, "score": 37534.24539512501 }, { "content": "/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *\n\n * Use of this source code is governed by a BSD-style license that *\n\n * can be found in the LICENSE file. */\n\n#ifndef __libamtrs__filesystem__hpp\n\n#define __libamtrs__filesystem__hpp\n\n#include \"amtrs.hpp\"\n\n#include <cctype>\n\n#include <chrono>\n\n#include <iostream>\n\n#include <fstream>\n\n#include <string_view>\n\n#include <unordered_map>\n\n#include <vector>\n\n#include <sys/types.h>\n\n#include <sys/stat.h>\n\n#include \"io.hpp\"\n\n#include \"string.hpp\"\n\n\n\n\n\n#define\tAMTRS_FILESYSTEM_NAMESPACE\t\t\t\tAMTRS_NAMESPACE::filesystem\n", "file_path": "include/amtrs/filesystem.hpp", "rank": 73, "score": 37534.02501827141 }, { "content": "", "file_path": "include/amtrs/font.hpp", "rank": 74, "score": 37532.94424334353 }, { "content": "\t#define\tAMTRS_CURRENT_PLATFORM_NAME\t\twin32\n\n\n\n\t#if\t\t!defined __WIN32__\n\n\t#define\t__WIN32__\n\n\t#endif\n\n\n\n\t/* Keep a include order. Include winwosk2 is fastest. */\n\n\t#define\tNOMINMAX\t\t1\n\n\t#include <winsock2.h>\n\n\t#include <windows.h>\n\n\t#include <windowsx.h>\n\n\n\n#else\n\n\n\n#endif\n\n\n\n\n\n\n\n/*****************************************************************************\n\n * Include macro\n", "file_path": "include/amtrs/amtrs.hpp", "rank": 75, "score": 37532.620015123546 }, { "content": "/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *\n\n * Use of this source code is governed by a BSD-style license that *\n\n * can be found in the LICENSE file. */\n\n#ifndef\t__libamtrs__optparse__hpp\n\n#define\t__libamtrs__optparse__hpp\n\n#include \"string.hpp\"\n\nAMTRS_NAMESPACE_BEGIN\n\n\n", "file_path": "include/amtrs/optparse.hpp", "rank": 76, "score": 37532.266034084256 }, { "content": "\t\tbool operator != (iteratorable const& _r) const noexcept { return mEntry._entry != _r.mEntry._entry; }\n\n\n\n\t\tvoid init()\n\n\t\t{\n\n\t\t\tif (mScaner)\n\n\t\t\t{\n\n\t\t\t\tif (mEntry._entry)\n\n\t\t\t\t{\n\n\t\t\t\t\tarchive_read_data_skip(mScaner->mArc);\n\n\t\t\t\t\tarchive_entry_clear(mEntry._entry);\n\n\t\t\t\t}\n\n\n\n\t\t\t\tif (archive_read_next_header(mScaner->mArc, &mEntry._entry) == ARCHIVE_OK)\n\n\t\t\t\t{\n\n\t\t\t\t}\n\n\t\t\t\telse\n\n\t\t\t\t{\n\n\t\t\t\t\tmEntry._entry\t= nullptr;\n\n\t\t\t\t}\n\n\t\t\t}\n", "file_path": "include/amtrs/archive.hpp", "rank": 77, "score": 37532.2262339378 }, { "content": "#define\tAMTRS_FILESYSTEM_NAMESPACE_BEGIN\t\tAMTRS_NAMESPACE_BEGIN namespace filesystem {\n\n#define\tAMTRS_FILESYSTEM_NAMESPACE_END\t\t\t} AMTRS_NAMESPACE_END\n\n#define\tAMTRS_FILESYSTEM_ZIP_NAMESPACE_BEGIN\tAMTRS_FILESYSTEM_NAMESPACE_BEGIN namespace zip {\n\n#define\tAMTRS_FILESYSTEM_ZIP_NAMESPACE_END\t\t} AMTRS_FILESYSTEM_NAMESPACE_END\n\n\n\n#include \".inc/filesystem-types.hpp\"\n\n#include \".inc/filesystem-vfs.hpp\"\n\n#include \".inc/filesystem-assetvfs.hpp\"\n\n#include \".inc/filesystem-cascadevfs.hpp\"\n\n#include \".inc/filesystem-fileloader.hpp\"\n\n#include \".inc/filesystem-filename.hpp\"\n\n#include \".inc/filesystem-stdvfs.hpp\"\n\n#include \".inc/filesystem-functions.hpp\"\n\n#include \".inc/filesystem-util.hpp\"\n\n\n\n\n\nAMTRS_FILESYSTEM_ZIP_NAMESPACE_BEGIN\n\ntemplate<class CharT>\n", "file_path": "include/amtrs/filesystem.hpp", "rank": 78, "score": 37532.18561334728 }, { "content": "/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *\n\n * Use of this source code is governed by a BSD-style license that *\n\n * can be found in the LICENSE file. */\n\n#ifndef\t__libamtrs__geometry__hpp\n\n#define\t__libamtrs__geometry__hpp\n\n#include \"amtrs.hpp\"\n\n#include <cfloat>\n\n#include <cmath>\n\n\n\n\n\nAMTRS_NAMESPACE_BEGIN\n\nconstexpr float\tpi = 3.14159265358979323846264338327950288f;\n\n\n\ninline double degrees_to_radians(double _degrees)\n\n{\n\n\treturn\tpi * (_degrees / 180.0);\n\n}\n\n\n\ntemplate<typename Type>\n\ninline float degrees_to_radians(Type _degrees)\n", "file_path": "include/amtrs/geometry.hpp", "rank": 79, "score": 37532.122637544206 }, { "content": "#include <stddef.h>\n\n#endif\n\n\n\n\n\n/* base library */\n\n#include \".inc/amtrs-allocator.h\"\n\n#include \".inc/amtrs-bufferif.h\"\n\n#include \".inc/amtrs-stringview.h\"\n\n\n\n\n\n#ifdef\t__cplusplus\n\nAMTRS_NAMESPACE_BEGIN\n\nAMTRS_NAMESPACE_END\n\nAMTRS_OS_NAMESPACE_BEGIN\n\nAMTRS_OS_NAMESPACE_END\n\n\n\n\n\n// Basic headers\n\n#include <algorithm>\n\n#include <string_view>\n", "file_path": "include/amtrs/amtrs.hpp", "rank": 80, "score": 37532.059317506835 }, { "content": "#include \".inc/net-address.hpp\"\n\n#include \".inc/net-network_listener.hpp\"\n\n\n\n#include \".inc/net-socket.hpp\"\n\n#include \".inc/net-socket-connection.hpp\"\n\n#include \".inc/net-socket-stream.hpp\"\n\n#include \".inc/net-socket-ssl_stream.hpp\"\n\n\n\n\n\n#define\tAMTRS_NET_HTTP_NAMESPACE_BEGIN\tAMTRS_NET_NAMESPACE_BEGIN namespace http {\n\n#define\tAMTRS_NET_HTTP_NAMESPACE_END\t} AMTRS_NET_NAMESPACE_END\n\nAMTRS_NET_HTTP_NAMESPACE_BEGIN\n\n\n", "file_path": "include/amtrs/net.hpp", "rank": 81, "score": 37531.874719895844 }, { "content": "", "file_path": "include/amtrs/font.hpp", "rank": 82, "score": 37531.68000207772 }, { "content": "/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *\n\n * Use of this source code is governed by a BSD-style license that *\n\n * can be found in the LICENSE file. */\n\n#ifndef\t__libamtrs__string__hpp\n\n#define\t__libamtrs__string__hpp\n\n#include \"amtrs.hpp\"\n\n\n\n/* standard library */\n\n#ifdef\t__cplusplus\n\n#include <cstring>\n\n#include <cstdlib>\n\n#include <iterator>\n\n#include <regex>\n\n#include <string>\n\n#include <string_view>\n\n#include <type_traits>\n\n#include <utility>\n\n#else\n\n#include <string.h>\n\n#endif\n", "file_path": "include/amtrs/string.hpp", "rank": 83, "score": 37530.348552575466 }, { "content": " * Windows の場合は visualstudio_setup() を呼び出します。\n\n */\n\nbool cpp_setup();\n\n\n\n\n\n/*!\n\n * ファイルの一覧を取得します。\n\n */\n\nbool ls(std::string const& _patturn = {});\n\n\n\n\n\nbool cat(std::string_view _file);\n\nbool cat(std::initializer_list<std::string_view> _files);\n\n\n\n\n\nstd::string which(std::string_view _file);\n\n\n\n\n\nAMTRS_SCRIPTUTIL_NAMESPACE_END\n\n#endif\n", "file_path": "include/amtrs/scriptutil.hpp", "rank": 84, "score": 37530.254845172116 }, { "content": "bool archive_enumrate(io::vstreamif* _in, Callback _callback)\n\n{\n\n\tarchive_enumrator\ta(_in);\n\n\tif (a.empty())\n\n\t{\n\n\t\treturn\tfalse;\n\n\t}\n\n\tfor (auto& e : a)\n\n\t{\n\n\t\t_callback(e);\n\n\t}\n\n\treturn\ttrue;\n\n}\n\n\n\n\n\nAMTRS_NAMESPACE_END\n\nAMTRS_IO_NAMESPACE_BEGIN\n\ntemplate<class Elm>\n", "file_path": "include/amtrs/archive.hpp", "rank": 85, "score": 37530.105652146616 }, { "content": "/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *\n\n * Use of this source code is governed by a BSD-style license that *\n\n * can be found in the LICENSE file. */\n\n#ifndef\t__libamtrs__input__hpp\n\n#define\t__libamtrs__input__hpp\n\n#include \"amtrs.hpp\"\n\n#include \"graphics.hpp\"\n\n\n\n#include \".inc/input-input_event.hpp\"\n\n#include \".inc/input-gamepad.hpp\"\n\n#endif\n", "file_path": "include/amtrs/input.hpp", "rank": 86, "score": 37529.9805185166 }, { "content": "/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *\n\n * Use of this source code is governed by a BSD-style license that *\n\n * can be found in the LICENSE file. */\n\n#ifndef\t__libamtrs__window__hpp\n\n#define\t__libamtrs__window__hpp\n\n#include \"amtrs.hpp\"\n\n\n\n#include <functional>\n\n\n\n#include \"chrono.hpp\"\n\n#include \"input.hpp\"\n\n#include \"geometry.hpp\"\n\n\n\n\n\n#include \".inc/window-display.hpp\"\n\n#include \".inc/window-window.hpp\"\n\n#include \".inc/window-dialog_datetime.hpp\"\n\n#include \".inc/window-dialog_timeinput.hpp\"\n\n#include \".inc/window-dialog_textinput.hpp\"\n\n#endif\n", "file_path": "include/amtrs/window.hpp", "rank": 87, "score": 37529.912491091825 }, { "content": "\n\n#define\tAMTRS_OS_NAMESPACE_BEGIN\t\t\t\tAMTRS_NAMESPACE_BEGIN namespace os {\n\n#define\tAMTRS_OS_NAMESPACE_END\t\t\t\t\t} AMTRS_NAMESPACE_END\n\n\n\n\n\n\n\n/* c linkage */\n\n#ifdef\t__cplusplus\n\n#define\tAMTRS_EXTERN_C_BEGIN\textern \"C\" {\n\n#define\tAMTRS_EXTERN_C_END\t\t}\n\n#else\n\n#define\tAMTRS_EXTERN_C_BEGIN\n\n#define\tAMTRS_EXTERN_C_END\n\n#endif\n\n\n\n\n\n/******************************************************************************\n\n * Operating System\n\n * ----------------------------------------------------------------------------\n\n * #if AMTRS_CURRENT_PLATFORM == AMTRS_PLATFORM_WIN32\n", "file_path": "include/amtrs/amtrs.hpp", "rank": 88, "score": 37529.761817162835 }, { "content": "/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *\n\n * Use of this source code is governed by a BSD-style license that *\n\n * can be found in the LICENSE file. */\n\n#ifndef\t__libamtrs__graphics__hpp\n\n#define\t__libamtrs__graphics__hpp\n\n#include \"amtrs.hpp\"\n\n\n\n#include <tuple>\n\n#include <vector>\n\n#include \"geometry.hpp\"\n\n#include \"io.hpp\"\n\n#include \".inc/utility-array.hpp\"\n\n#include \".inc/memory-shared_buffer.hpp\"\n\n\n\n#include \".inc/graphics-color.hpp\"\n\n#include \".inc/graphics-bitmap_view.hpp\"\n\n#include \".inc/graphics-bitmap.hpp\"\n\n#include \".inc/graphics-bmp.hpp\"\n\n#include \".inc/graphics-atls.hpp\"\n\n#include \".inc/graphics-imageview.hpp\"\n\n#include \".inc/graphics-imagebuff.hpp\"\n\n#include \".inc/graphics-rect_allocator.hpp\"\n\n#include \".inc/graphics-waveform.hpp\"\n\n\n\n#endif\n", "file_path": "include/amtrs/graphics.hpp", "rank": 89, "score": 37529.583363641745 }, { "content": "\t\t}\n\n\n\n\t\tbasic_archive_enumrator*\tmScaner\t= nullptr;\n\n\t\tentry\t\t\t\t\tmEntry;\n\n\n\n\t\tfriend\tbasic_archive_enumrator;\n\n\t};\n\n\n\n\tusing\titerator\t= iteratorable;\n\n\n\n\tbasic_archive_enumrator() = default;\n\n\tbasic_archive_enumrator(basic_archive_enumrator const&) = delete;\n\n\tbasic_archive_enumrator(basic_archive_enumrator&& _r)\n\n\t\t: mArc(_r.mArc)\n\n\t{\n\n\t\t_r.mArc\t= nullptr;\n\n\t}\n\n\n\n\t~basic_archive_enumrator()\n\n\t{\n", "file_path": "include/amtrs/archive.hpp", "rank": 90, "score": 37529.53717982158 }, { "content": "/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *\n\n * Use of this source code is governed by a BSD-style license that *\n\n * can be found in the LICENSE file. */\n\n#ifndef\t__libamtrs__amtrs__hpp\n\n#define\t__libamtrs__amtrs__hpp\n\n\n\n/* namespace */\n\n#ifndef\tAMTRS_NAMESPACE\n\n#define\tAMTRS_NAMESPACE\t\t\t\t\t\t\tamtrs\n\n#endif\n\n\n\n#define\tAMTRS_NAMESPACE_BEGIN\t\t\t\t\tnamespace AMTRS_NAMESPACE {\n\n#define\tAMTRS_NAMESPACE_END\t\t\t\t\t\t}\n\n#define\tAMTRS_STD_NAMESPACE_BEGIN\t\t\t\tnamespace std {\n\n#define\tAMTRS_STD_NAMESPACE_END\t\t\t\t\t}\n\n\n\n#define\tAMTRS_IMPLEMENTS_BEGIN(_name)\t\t\tnamespace _name##_impl {\n\n#define\tAMTRS_IMPLEMENTS_END(_name)\t\t\t\t}\n\n#define\tAMTRS_IMPLEMENTS(_name)\t\t\t\t\t_name##_impl\n\n\n", "file_path": "include/amtrs/amtrs.hpp", "rank": 91, "score": 37529.51989091571 }, { "content": "#define\t__AMTRS_TEST_F_MAKENAME(_name, _num)\tte_ ## _name ## _num\n\n#define\t_AMTRS_TEST_F_MAKENAME(_name, _num)\t\t__AMTRS_TEST_F_MAKENAME(_name, _num)\n\n#define\t___AMTRS_TEST_F(_name)\t\t\t\t\tstatic void _name(); static AMTRS_TEST_NAMESPACE::test_entry _AMTRS_TEST_F_MAKENAME(_name, __LINE__)(#_name, &_name); void _name()\n\n#define\tAMTRS_TEST_F(_name)\t\t\t\t\t\t___AMTRS_TEST_F(_name)\n\n\n\n#define\tAMTRS_TEST_EQ(_a, _b)\t\t{ if (!AMTRS_TEST_NAMESPACE::test_eq(__LINE__, _a, _b)) return; }\n\n#define\tAMTRS_TEST_NOTEQ(_a, _b)\t{ if (!AMTRS_TEST_NAMESPACE::test_not_eq(__LINE__, _a, _b)) return; }\n\n#define\tAMTRS_TEST_TRUE(_a)\t\t\t{ if (!AMTRS_TEST_NAMESPACE::test_true(__LINE__, _a)) return; }\n\n#define\tAMTRS_TEST_FALSE(_a)\t\t{ if (!AMTRS_TEST_NAMESPACE::test_false(__LINE__, _a)) return; }\n\n\n\n#endif\n", "file_path": "include/amtrs/tests.hpp", "rank": 92, "score": 37529.52070701298 }, { "content": " * \t>= 0\tコマンドの終了コード\n\n * < 0\tエラー(そもそも実行できなかった)\n\n */\n\nint exec(std::string& _out, std::string const& _command);\n\n\n\n\n\n/*!\n\n * コマンドを実行します。\n\n * return\n\n * \t>= 0\tコマンドの終了コード\n\n * < 0\tエラー(そもそも実行できなかった)\n\n */\n\nint exec(std::string const& _command);\n\n\n\n/*!\n\n * ファイルをダウンロードします。\n\n * _savename を省略した場合はカレントディレクトリに保存されます。\n\n * _savename がディレクトリの場合はディレクトリの中に保存されます。\n\n * _savedname ダウンロードしたファイルを保存した時のファイル名。\n\n */\n\nbool download(std::string const& _url, std::string const& _savename, std::string* _savedname = nullptr);\n\n\n\n\n", "file_path": "include/amtrs/scriptutil.hpp", "rank": 93, "score": 37529.26379789545 }, { "content": "{\n\n\treturn\tstatic_cast<float>(degrees_to_radians(static_cast<double>(_degrees)));\n\n}\n\n\n\ninline double radians_to_degrees(double _radians)\n\n{\n\n\treturn\t180 * (_radians / pi);\n\n}\n\n\n\ntemplate<typename Type>\n\ninline float radians_to_degrees(Type _radians)\n\n{\n\n\treturn\tstatic_cast<float>(radians_to_degrees(static_cast<double>(_radians)));\n\n}\n\nAMTRS_NAMESPACE_END\n\n\n\n// keep order.\n\n#include \".inc/geometry-vec.hpp\"\n\n#include \".inc/geometry-matrix.hpp\"\n\n#include \".inc/geometry-size.hpp\"\n", "file_path": "include/amtrs/geometry.hpp", "rank": 94, "score": 37529.042650961026 }, { "content": "\n\n/* c utility */\n\n#include \".inc/string-stringbuf.hpp\"\n\n\n\n\n\n/* c++ utility */\n\n#ifdef\t__cplusplus\n\n#include \".inc/string-chartype.hpp\"\n\n#include \".inc/string-constring.hpp\"\n\n#include \".inc/string-convert.hpp\"\n\n#include \".inc/string-starts_with.hpp\"\n\n#include \".inc/string-find.hpp\"\n\n#include \".inc/string-find_view_if.hpp\"\n\n#include \".inc/string-join.hpp\"\n\n#include \".inc/string-lowercase.hpp\"\n\n#include \".inc/string-make_string_view.hpp\"\n\n#include \".inc/string-regex_match.hpp\"\n\n#include \".inc/string-regex_replace.hpp\"\n\n#include \".inc/string-split_iterator.hpp\"\n\n#include \".inc/string-readline.hpp\"\n\n#include \".inc/string-trim.hpp\"\n\n#include \".inc/string-textline.hpp\"\n\n#include \".inc/string-uppercase.hpp\"\n\n#include \".inc/string-utf8.hpp\"\n\n#include \".inc/string-wildcard.hpp\"\n\n#endif\n\n\n\n#endif\n", "file_path": "include/amtrs/string.hpp", "rank": 95, "score": 37527.23035403433 }, { "content": "\n\n\n\n#define\tAMTRS_PLIB_NAME\tchrono-time.hpp\n\n#include \".inc/include-platform.hpp\"\n\n\n\n\n\n// keep order.\n\n#include \".inc/chrono-functions.hpp\"\n\n#include \".inc/chrono-time.hpp\"\n\n#include \".inc/chrono-bedatetime.hpp\"\n\n#include \".inc/chrono-deltatimer.hpp\"\n\n#include \".inc/chrono-datetime.hpp\"\n\n#include \".inc/chrono-flicks.hpp\"\n\n#include \".inc/chrono-framerator.hpp\"\n\n#include \".inc/chrono-calendar.hpp\"\n\n\n\n#define\tAMTRS_PLIB_NAME\tchrono-datetime.hpp\n\n#include \".inc/include-platform.hpp\"\n\n\n\n#endif\n", "file_path": "include/amtrs/chrono.hpp", "rank": 96, "score": 37527.17903365248 }, { "content": "#include \".inc/io-streamif-stdlib.hpp\"\n\n#include \".inc/io-streamif-string_view.hpp\"\n\n#include \".inc/io-vstreamif.hpp\"\n\n#include \".inc/io-functions.hpp\"\n\n#include \".inc/iostream-bin.hpp\"\n\n\n\n#if\t\tAMTRS_ZLIB_ENABLE\n\n#include \".inc/io-zlib-stream_in.hpp\"\n\n#endif\n\n\n\n\n\n// 以下廃止予定\n\n#include \".inc/io-deserialize.hpp\"\n\n#include \".inc/io-limit.hpp\"\n\n#include \".inc/io-listener_stream.hpp\"\n\n#include \".inc/io-serialize.hpp\"\n\n#include \".inc/io-stream_in-fwd.hpp\"\n\n#include \".inc/io-stream_in-cstd.hpp\"\n\n#include \".inc/io-stream_in-stl.hpp\"\n\n#include \".inc/io-stream_in-view.hpp\"\n\n\n\n\n\n\n\n\n\n#endif\n", "file_path": "include/amtrs/io.hpp", "rank": 97, "score": 37527.17123879633 }, { "content": "#include \".inc/geometry-rect.hpp\"\n\n#include \".inc/geometry-aabb.hpp\"\n\n#include \".inc/geometry-obb.hpp\"\n\n#include \".inc/geometry-box.hpp\"\n\n#include \".inc/geometry-line_segment.hpp\"\n\n#include \".inc/geometry-collision.hpp\"\n\n#include \".inc/geometry-distance.hpp\"\n\n#include \".inc/geometry-quaternion.hpp\"\n\n#include \".inc/geometry-transform.hpp\"\n\n#endif\n", "file_path": "include/amtrs/geometry.hpp", "rank": 98, "score": 37527.16397434506 }, { "content": "#include <system_error>\n\n#include \".inc/amtrs-bucket.hpp\"\n\n#include \".inc/amtrs-endian.hpp\"\n\n#include \".inc/amtrs-format.hpp\"\n\n#include \".inc/amtrs-logging.hpp\"\n\n#include \".inc/amtrs-range.hpp\"\n\n#include \".inc/amtrs-ref_object.hpp\"\n\n\n\n#endif\n\n#endif\n", "file_path": "include/amtrs/amtrs.hpp", "rank": 99, "score": 37527.13277306327 } ]
C++
CrescentEngine/Models/Mesh.cpp
xRiveria/Crescent-Engine
b6512b6a8dab2d27cf542c562ccc28f21bf2345d
#include "CrescentPCH.h" #include "Mesh.h" #include "GL/glew.h" #include <glm/gtc/type_ptr.hpp> #include <algorithm> namespace Crescent { Mesh::Mesh() { } Mesh::Mesh(std::vector<glm::vec3> positions, std::vector<unsigned int> indices) { m_Positions = positions; m_Indices = indices; } Mesh::Mesh(std::vector<glm::vec3> positions, std::vector<glm::vec2> uv, std::vector<unsigned int> indices) { m_Positions = positions; m_UV = uv; m_Indices = indices; } Mesh::Mesh(std::vector<glm::vec3> positions, std::vector<glm::vec2> uv, std::vector<glm::vec3> normals, std::vector<unsigned int> indices) { m_Positions = positions; m_UV = uv; m_Normals = normals; m_Indices = indices; } Mesh::Mesh(std::vector<glm::vec3> positions, std::vector<glm::vec2> uv, std::vector<glm::vec3> normals, std::vector<glm::vec3> tangents, std::vector<glm::vec3> bitangents, std::vector<unsigned int> indices) { m_Positions = positions; m_UV = uv; m_Normals = normals; m_Tangents = tangents; m_Bitangents = bitangents; m_Indices = indices; } void Mesh::FinalizeMesh(bool interleaved) { if (!m_VertexArrayID) { glGenVertexArrays(1, &m_VertexArrayID); glGenBuffers(1, &m_VertexBufferID); glGenBuffers(1, &m_IndexBufferID); } std::vector<float> bufferData; if (interleaved) { for (int i = 0; i < m_Positions.size(); i++) { bufferData.push_back(m_Positions[i].x); bufferData.push_back(m_Positions[i].y); bufferData.push_back(m_Positions[i].z); if (m_UV.size() > 0) { bufferData.push_back(m_UV[i].x); bufferData.push_back(m_UV[i].y); } if (m_Normals.size() > 0) { bufferData.push_back(m_Normals[i].x); bufferData.push_back(m_Normals[i].y); bufferData.push_back(m_Normals[i].z); } if (m_Tangents.size() > 0) { bufferData.push_back(m_Tangents[i].x); bufferData.push_back(m_Tangents[i].y); bufferData.push_back(m_Tangents[i].z); } if (m_Bitangents.size() > 0) { bufferData.push_back(m_Bitangents[i].x); bufferData.push_back(m_Bitangents[i].y); bufferData.push_back(m_Bitangents[i].z); } } } else { for (int i = 0; i < m_Positions.size(); i++) { bufferData.push_back(m_Positions[i].x); bufferData.push_back(m_Positions[i].y); bufferData.push_back(m_Positions[i].z); } for (int i = 0; i < m_UV.size(); i++) { bufferData.push_back(m_UV[i].x); bufferData.push_back(m_UV[i].y); } for (int i = 0; i < m_Normals.size(); i++) { bufferData.push_back(m_Normals[i].x); bufferData.push_back(m_Normals[i].y); bufferData.push_back(m_Normals[i].z); } for (int i = 0; i < m_Tangents.size(); i++) { bufferData.push_back(m_Tangents[i].x); bufferData.push_back(m_Tangents[i].y); bufferData.push_back(m_Tangents[i].z); } for (int i = 0; i < m_Bitangents.size(); i++) { bufferData.push_back(m_Bitangents[i].x); bufferData.push_back(m_Bitangents[i].y); bufferData.push_back(m_Bitangents[i].z); } } glBindVertexArray(m_VertexArrayID); glBindBuffer(GL_ARRAY_BUFFER, m_VertexBufferID); glBufferData(GL_ARRAY_BUFFER, (bufferData.size() * sizeof(float) + (m_BoneIDs.size() * sizeof(int)) + (m_BoneWeights.size() * sizeof(float))), &bufferData[0], GL_STATIC_DRAW); if (m_Indices.size() > 0) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IndexBufferID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_Indices.size() * sizeof(unsigned int), &m_Indices[0], GL_STATIC_DRAW); } if (interleaved) { size_t stride = 3 * sizeof(float); if (m_UV.size() > 0) stride += 2 * sizeof(float); if (m_Normals.size() > 0) stride += 3 * sizeof(float); if (m_Tangents.size() > 0) stride += 3 * sizeof(float); if (m_Bitangents.size() > 0) stride += 3 * sizeof(float); size_t offset = 0; glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, stride, (GLvoid*)offset); offset += 3 * sizeof(float); if (m_UV.size() > 0) { glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, stride, (GLvoid*)offset); offset += 2 * sizeof(float); } if (m_Normals.size() > 0) { glEnableVertexAttribArray(2); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, stride, (GLvoid*)offset); offset += 3 * sizeof(float); } if (m_Tangents.size() > 0) { glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, stride, (GLvoid*)offset); offset += 3 * sizeof(float); } if (m_Bitangents.size() > 0) { glEnableVertexAttribArray(4); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, stride, (GLvoid*)offset); offset += 3 * sizeof(float); } } else { size_t offset = 0; glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)offset); offset += m_Positions.size() * sizeof(float); if (m_UV.size() > 0) { glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, (GLvoid*)offset); offset += m_UV.size() * sizeof(float); } if (m_Normals.size() > 0) { glEnableVertexAttribArray(2); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)offset); offset += m_Normals.size() * sizeof(float); } if (m_Tangents.size() > 0) { glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)offset); offset += m_Tangents.size() * sizeof(float); } if (m_Bitangents.size() > 0) { glEnableVertexAttribArray(4); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)offset); offset += m_Bitangents.size() * sizeof(float); } } glBindVertexArray(0); } Mesh::Mesh(std::vector<Vertex> vertices, std::vector<unsigned int> indices, std::vector<MeshTexture> textures) { this->vertices = vertices; this->indices = indices; this->textures = textures; SetupMesh(); } void Mesh::Draw(Shader& shader, bool renderShadowMap, unsigned int shadowMapTextureID) { unsigned int diffuseNr = 1; unsigned int specularNr = 1; unsigned int normalNr = 1; unsigned int heightNr = 1; glBindVertexArray(vertexArrayObject); shader.UseShader(); if (!renderShadowMap) { for (unsigned int i = 0; i < textures.size(); i++) { glActiveTexture(GL_TEXTURE0 + i); std::string number; std::string name = textures[i].type; if (name == "texture_diffuse") { number = std::to_string(diffuseNr++); } else if (name == "texture_specular") { number = std::to_string(specularNr++); } else if (name == "texture_normal") { number = std::to_string(normalNr++); } else if (name == "texture_height") { number = std::to_string(heightNr++); } shader.UseShader(); glUniform1i(glGetUniformLocation(shader.GetShaderID(), (name + number).c_str()), i); glBindTexture(GL_TEXTURE_2D, textures[i].id); } } glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0); for (int i = 0; i < 32; i++) { if (i == 3) { continue; } glActiveTexture(GL_TEXTURE0 + i); glBindTexture(GL_TEXTURE_2D, 0); } glBindVertexArray(0); } void Mesh::SetupMesh() { glGenVertexArrays(1, &vertexArrayObject); glGenBuffers(1, &vertexBufferObject); glGenBuffers(1, &indexBufferObject); glBindVertexArray(vertexArrayObject); glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), &vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferObject); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Normal)); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, TexCoords)); glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Tangent)); glEnableVertexAttribArray(4); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Bitangent)); glEnableVertexAttribArray(5); glVertexAttribIPointer(5, 4, GL_INT, sizeof(Vertex), (void*)(offsetof(Vertex, BoneIDs) + 0 * sizeof(int))); glEnableVertexAttribArray(6); glVertexAttribIPointer(6, 4, GL_INT, sizeof(Vertex), (void*)(offsetof(Vertex, BoneIDs) + 4 * sizeof(int))); glEnableVertexAttribArray(7); glVertexAttribPointer(7, 4, GL_FLOAT, false, sizeof(Vertex), (void*)(offsetof(Vertex, BoneWeights) + 0 * sizeof(float))); glEnableVertexAttribArray(8); glVertexAttribPointer(8, 4, GL_FLOAT, false, sizeof(Vertex), (void*)(offsetof(Vertex, BoneWeights) + 4 * sizeof(float))); glBindVertexArray(0); } void Mesh::RecursivelyUpdateBoneMatrices(int animationIndex, aiNode* node, glm::mat4 transform, double ticks) { static auto mat4_from_aimatrix4x4 = [](aiMatrix4x4 matrix) -> glm::mat4 { glm::mat4 res; for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) res[j][i] = matrix[i][j]; return res; }; std::string node_name = node->mName.C_Str(); auto animation = m_Animations[animationIndex]->m_Animation; glm::mat4 current_transform; if (m_AnimationChannelMap.count(std::pair<uint32_t, std::string>(animationIndex, node_name))) { uint32_t channel_id = m_AnimationChannelMap[std::pair<uint32_t, std::string>(animationIndex, node_name)]; auto channel = animation->mChannels[channel_id]; glm::mat4 translation_matrix = InterpolateTranslationMatrix(channel->mPositionKeys, channel->mNumPositionKeys, ticks); glm::mat4 rotation_matrix = InterpolateRotationMatrix(channel->mRotationKeys, channel->mNumRotationKeys, ticks); glm::mat4 scaling_matrix = InterpolateScalingMatrix(channel->mScalingKeys, channel->mNumScalingKeys, ticks); current_transform = translation_matrix * rotation_matrix * scaling_matrix; } else { current_transform = mat4_from_aimatrix4x4(node->mTransformation); } if (m_BoneMapper.RetrieveBoneLibrary().count(node_name)) { uint32_t i = m_BoneMapper.RetrieveBoneLibrary()[node_name]; m_BoneMatrices[i] = transform * current_transform * m_BoneOffsets[i]; } for (int i = 0; i < node->mNumChildren; i++) { RecursivelyUpdateBoneMatrices(animationIndex, node->mChildren[i], transform * current_transform, ticks); } } glm::mat4 Mesh::InterpolateTranslationMatrix(aiVectorKey* keys, uint32_t n, double ticks) { static auto mat4_from_aivector3d = [](aiVector3D vector) -> glm::mat4 { return glm::translate(glm::mat4(1), glm::vec3(vector.x, vector.y, vector.z)); }; if (n == 0) return glm::mat4(1); if (n == 1) return mat4_from_aivector3d(keys->mValue); if (ticks <= keys[0].mTime) return mat4_from_aivector3d(keys[0].mValue); if (keys[n - 1].mTime <= ticks) return mat4_from_aivector3d(keys[n - 1].mValue); aiVectorKey anchor; anchor.mTime = ticks; auto right_ptr = std::upper_bound(keys, keys + n, anchor, [](const aiVectorKey& a, const aiVectorKey& b) { return a.mTime < b.mTime; }); auto left_ptr = right_ptr - 1; float factor = (ticks - left_ptr->mTime) / (right_ptr->mTime - left_ptr->mTime); return mat4_from_aivector3d(left_ptr->mValue * (1.0f - factor) + right_ptr->mValue * factor); } glm::mat4 Mesh::InterpolateRotationMatrix(aiQuatKey* keys, uint32_t n, double ticks) { static auto mat4_from_aiquaternion = [](aiQuaternion quaternion) -> glm::mat4 { auto rotation_matrix = quaternion.GetMatrix(); glm::mat4 res(1); for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) res[j][i] = rotation_matrix[i][j]; return res; }; if (n == 0) return glm::mat4(1); if (n == 1) return mat4_from_aiquaternion(keys->mValue); if (ticks <= keys[0].mTime) return mat4_from_aiquaternion(keys[0].mValue); if (keys[n - 1].mTime <= ticks) return mat4_from_aiquaternion(keys[n - 1].mValue); aiQuatKey anchor; anchor.mTime = ticks; auto right_ptr = std::upper_bound(keys, keys + n, anchor, [](const aiQuatKey& a, const aiQuatKey& b) { return a.mTime < b.mTime; }); auto left_ptr = right_ptr - 1; double factor = (ticks - left_ptr->mTime) / (right_ptr->mTime - left_ptr->mTime); aiQuaternion out; aiQuaternion::Interpolate(out, left_ptr->mValue, right_ptr->mValue, factor); return mat4_from_aiquaternion(out); } glm::mat4 Mesh::InterpolateScalingMatrix(aiVectorKey* keys, uint32_t n, double ticks) { static auto mat4_from_aivector3d = [](aiVector3D vector) -> glm::mat4 { return glm::scale(glm::mat4(1), glm::vec3(vector.x, vector.y, vector.z)); }; if (n == 0) return glm::mat4(1); if (n == 1) return mat4_from_aivector3d(keys->mValue); if (ticks <= keys[0].mTime) return mat4_from_aivector3d(keys[0].mValue); if (keys[n - 1].mTime <= ticks) return mat4_from_aivector3d(keys[n - 1].mValue); aiVectorKey anchor; anchor.mTime = ticks; auto right_ptr = std::upper_bound(keys, keys + n, anchor, [](const aiVectorKey& a, const aiVectorKey& b) { return a.mTime < b.mTime; }); auto left_ptr = right_ptr - 1; float factor = (ticks - left_ptr->mTime) / (right_ptr->mTime - left_ptr->mTime); return mat4_from_aivector3d(left_ptr->mValue * (1.0f - factor) + right_ptr->mValue * factor); } }
#include "CrescentPCH.h" #include "Mesh.h" #include "GL/glew.h" #include <glm/gtc/type_ptr.hpp> #include <algorithm> namespace Crescent { Mesh::Mesh() { } Mesh::Mesh(std::vector<glm::vec3> positions, std::vector<unsigned int> indices) { m_Positions = positions; m_Indices = indices; } Mesh::Mesh(std::vector<glm::vec3> positions, std::vector<glm::vec2> uv, std::vector<unsigned int> indices) { m_Positions = positions; m_UV = uv; m_Indices = indices; } Mesh::Mesh(std::vector<glm::vec3> positions, std::vector<glm::vec2> uv, std::vector<glm::vec3> normals, std::vector<unsigned int> indices) { m_Positions = positions; m_UV = uv; m_Normals = normals; m_Indices = indices; } Mesh::Mesh(std::vector<glm::vec3> positions, std::vector<glm::vec2> uv, std::vector<glm::vec3> normals, std::vector<glm::vec3> tangents, std::vector<glm::vec3> bitangents, std::vector<unsigned int> indices) { m_Positions = positions; m_UV = uv; m_Normals = normals; m_Tangents = tangents; m_Bitangents = bitangents; m_Indices = indices; } void Mesh::FinalizeMesh(bool interleaved) { if (!m_VertexArrayID) { glGenVertexArrays(1, &m_VertexArrayID); glGenBuffers(1, &m_VertexBufferID); glGenBuffers(1, &m_IndexBufferID); } std::vector<float> bufferData; if (interleaved) { for (int i = 0; i < m_Positions.size(); i++) { bufferData.push_back(m_Positions[i].x); bufferData.push_back(m_Positions[i].y); bufferData.push_back(m_Positions[i].z); if (m_UV.size() > 0) { bufferData.push_back(m_UV[i].x); bufferData.push_back(m_UV[i].y); } if (m_Normals.size() > 0) { bufferData.push_back(m_Normals[i].x); bufferData.push_back(m_Normals[i].y); bufferData.push_back(m_Normals[i].z); } if (m_Tangents.size() > 0) { bufferData.push_back(m_Tangents[i].x); bufferData.push_back(m_Tangents[i].y); bufferData.push_back(m_Tangents[i].z); } if (m_Bitangents.size() > 0) { bufferData.push_back(m_Bitangents[i].x); bufferData.push_back(m_Bitangents[i].y); bufferData.push_back(m_Bitangents[i].z); } } } else { for (int i = 0; i < m_Positions.size(); i++) { bufferData.push_back(m_Positions[i].x); bufferData.push_back(m_Positions[i].y); bufferData.push_back(m_Positions[i].z); } for (int i = 0; i < m_UV.size(); i++) { bufferData.push_back(m_UV[i].x); bufferData.push_back(m_UV[i].y); } for (int i = 0; i < m_Normals.size(); i++) { bufferData.push_back(m_Normals[i].x); bufferData.push_back(m_Normals[i].y); bufferData.push_back(m_Normals[i].z); } for (int i = 0; i < m_Tangents.size(); i++) { bufferData.push_back(m_Tangents[i].x); bufferData.push_back(m_Tangents[i].y); bufferData.push_back(m_Tangents[i].z); } for (int i = 0; i < m_Bitangents.size(); i++) { bufferData.push_back(m_Bitangents[i].x); bufferData.push_back(m_Bitangents[i].y); bufferData.push_back(m_Bitangents[i].z); } } glBindVertexArray(m_VertexArrayID); glBindBuffer(GL_ARRAY_BUFFER, m_VertexBufferID); glBufferData(GL_ARRAY_BUFFER, (bufferData.size() * sizeof(float) + (m_BoneIDs.size() * sizeof(int)) + (m_BoneWeights.size() * sizeof(float))), &bufferData[0], GL_STATIC_DRAW); if (m_Indices.size() > 0) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IndexBufferID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_Indices.size() * sizeof(unsigned int), &m_Indices[0], GL_STATIC_DRAW); } if (interleaved) { size_t stride = 3 * sizeof(float); if (m_UV.size() > 0) stride += 2 * sizeof(float); if (m_Normals.size() > 0) stride += 3 * sizeof(float); if (m_Tangents.size() > 0) stride += 3 * sizeof(float); if (m_Bitangents.size() > 0) stride += 3 * sizeof(float); size_t offset = 0; glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, stride, (GLvoid*)offset); offset += 3 * sizeof(float); if (m_UV.size() > 0) { glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, stride, (GLvoid*)offset); offset += 2 * sizeof(float); } if (m_Normals.size() > 0) { glEnableVertexAttribArray(2); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, stride, (GLvoid*)offset); offset += 3 * sizeof(float); } if (m_Tangents.size() > 0) { glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, stride, (GLvoid*)offset); offset += 3 * sizeof(float); } if (m_Bitangents.size() > 0) { glEnableVertexAttribArray(4); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, stride, (GLvoid*)offset); offset += 3 * sizeof(float); } } else { size_t offset = 0; glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)offset); offset += m_Positions.size() * sizeof(float); if (m_UV.size() > 0) { glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, (GLvoid*)offset); offset += m_UV.size() * sizeof(float); } if (m_Normals.size() > 0) { glEnableVertexAttribArray(2); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)offset); offset += m_Normals.size() * sizeof(float); } if (m_Tangents.size() > 0) { glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)offset); offset += m_Tangents.size() * sizeof(float); } if (m_Bitangents.size() > 0) { glEnableVertexAttribArray(4); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)offset); offset += m_Bitangents.size() * sizeof(float); } } glBindVertexArray(0); } Mesh::Mesh(std::vector<Vertex> vertices, std::vector<unsigned int> indices, std::vector<MeshTexture> textures) { this->vertices = vertices; this->indices = indices; this->textures = textures; SetupMesh(); } void Mesh::Draw(Shader& shader, bool renderShadowMap, unsigned int shadowMapTextureID) { unsigned int diffuseNr = 1; unsigned int specularNr = 1; unsigned int normalNr = 1; unsigned int heightNr = 1; glBindVertexArray(vertexArrayObject); shader.UseShader(); if (!renderShadowMap) { for (unsigned int i = 0; i < textures.size(); i++) { glActiveTexture(GL_TEXTURE0 + i); std::string number; std::string name = textures[i].type; if (name == "texture_diffuse") { number = std::to_string(diffuseNr++); } else if (name == "texture_specular") { number = std::to_string(specularNr++); } else if (name == "texture_normal") { number = std::to_string(normalNr++); } else if (name == "texture_height") { number = std::to_string(heightNr++); } shader.UseShader(); glUniform1i(glGetUniformLocation(shader.GetShaderID(), (name + number).c_str()), i); glBindTexture(GL_TEXTURE_2D, textures[i].id); } } glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0); for (int i = 0; i < 32; i++) { if (i == 3) { continue; } glActiveTexture(GL_TEXTURE0 + i); glBindTexture(GL_TEXTURE_2D, 0); } glBindVertexArray(0); } void Mesh::SetupMesh() { glGenVertexArrays(1, &vertexArrayObject); glGenBuffers(1, &vertexBufferObject); glGenBuffers(1, &indexBufferObject); glBindVertexArray(vertexArrayObject); glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), &vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferObject); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Normal)); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, TexCoords)); glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Tangent)); glEnableVertexAttribArray(4); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Bitangent)); glEnableVertexAttribArray(5); glVertexAttribIPointer(5, 4, GL_INT, sizeof(Vertex), (void*)(offsetof(Vertex, BoneIDs) + 0 * sizeof(int))); glEnableVertexAttribArray(6); glVertexAttribIPointer(6, 4, GL_INT, sizeof(Vertex), (void*)(offsetof(Vertex, BoneIDs) + 4 * sizeof(int))); glEnableVertexAttribArray(7); glVertexAttribPointer(7, 4, GL_FLOAT, false, sizeof(Vertex), (void*)(offsetof(Vertex, BoneWeights) + 0 * sizeof(float))); glEnableVertexAttribArray(8); glVertexAttribPointer(8, 4, GL_FLOAT, false, sizeof(Vertex), (void*)(offsetof(Vertex, BoneWeights) + 4 * sizeof(float))); glBindVertexArray(0); } void Mesh::RecursivelyUpdateBoneMatrices(int animationIndex, aiNode* node, glm::mat4 transform, double ticks) { static auto mat4_from_aimatrix4x4 = [](aiMatrix4x4 matrix) -> glm::mat4 { glm::mat4 res; for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) res[j][i] = matrix[i][j]; return res; }; std::string node_name = node->mName.C_Str(); auto animation = m_Animations[animationIndex]->m_Animation; glm::mat4 current_transform; if (m_AnimationChannelMap.count(std::pair<uint32_t, std::string>(animationIndex, node_name))) { uint32_t channel_id = m_AnimationChannelMap[std::pair<uint32_t, std::string>(animationIndex, node_name)]; auto channel = animation->mChannels[channel_id]; glm::mat4 translation_matrix = InterpolateTranslationMatrix(channel->mPositionKeys, channel->mNumPositionKeys, ticks); glm::mat4 rotation_matrix = InterpolateRotationMatrix(channel->mRotationKeys, channel->mNumRotationKeys, ticks); glm::mat4 scaling_matrix = InterpolateScalingMatrix(channel->mScalingKeys, channel->mNumScalingKeys, ticks); current_transform = translation_matrix * rotation_matrix * scaling_matrix; } else { current_transform = mat4_from_aimatrix4x4(node->mTransformation); } if (m_BoneMapper.RetrieveBoneLibrary().count(node_name)) { uint32_t i = m_BoneMapper.RetrieveBoneLibrary()[node_name]; m_BoneMatrices[i] = transform * current_transform * m_BoneOffsets[i]; } for (int i = 0; i < node->mNumChildren; i++) { RecursivelyUpdateBoneMatrices(animationIndex, node->mChildren[i], transform * current_transform, ticks); } } glm::mat4 Mesh::InterpolateTranslationMatrix(aiVectorKey* keys, uint32_t n, double ticks) { static auto mat4_from_aivector3d = [](aiVector3D vector) -> glm::mat4 { return glm::translate(glm::mat4(1), glm::vec3(vector.x, vector.y, vector.z)); }; if (n == 0) return glm::mat4(1); if (n == 1) return mat4_from_aivector3d(keys->mValue); if (ticks <= keys[0].mTime) return mat4_from_aivector3d(keys[0].mValue); if (keys[n - 1].mTime <= ticks) return mat4_from_aivector3d(keys[n - 1].mValue); aiVectorKey anchor; anchor.mTime = ticks; auto right_ptr =
; auto left_ptr = right_ptr - 1; float factor = (ticks - left_ptr->mTime) / (right_ptr->mTime - left_ptr->mTime); return mat4_from_aivector3d(left_ptr->mValue * (1.0f - factor) + right_ptr->mValue * factor); } glm::mat4 Mesh::InterpolateRotationMatrix(aiQuatKey* keys, uint32_t n, double ticks) { static auto mat4_from_aiquaternion = [](aiQuaternion quaternion) -> glm::mat4 { auto rotation_matrix = quaternion.GetMatrix(); glm::mat4 res(1); for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) res[j][i] = rotation_matrix[i][j]; return res; }; if (n == 0) return glm::mat4(1); if (n == 1) return mat4_from_aiquaternion(keys->mValue); if (ticks <= keys[0].mTime) return mat4_from_aiquaternion(keys[0].mValue); if (keys[n - 1].mTime <= ticks) return mat4_from_aiquaternion(keys[n - 1].mValue); aiQuatKey anchor; anchor.mTime = ticks; auto right_ptr = std::upper_bound(keys, keys + n, anchor, [](const aiQuatKey& a, const aiQuatKey& b) { return a.mTime < b.mTime; }); auto left_ptr = right_ptr - 1; double factor = (ticks - left_ptr->mTime) / (right_ptr->mTime - left_ptr->mTime); aiQuaternion out; aiQuaternion::Interpolate(out, left_ptr->mValue, right_ptr->mValue, factor); return mat4_from_aiquaternion(out); } glm::mat4 Mesh::InterpolateScalingMatrix(aiVectorKey* keys, uint32_t n, double ticks) { static auto mat4_from_aivector3d = [](aiVector3D vector) -> glm::mat4 { return glm::scale(glm::mat4(1), glm::vec3(vector.x, vector.y, vector.z)); }; if (n == 0) return glm::mat4(1); if (n == 1) return mat4_from_aivector3d(keys->mValue); if (ticks <= keys[0].mTime) return mat4_from_aivector3d(keys[0].mValue); if (keys[n - 1].mTime <= ticks) return mat4_from_aivector3d(keys[n - 1].mValue); aiVectorKey anchor; anchor.mTime = ticks; auto right_ptr = std::upper_bound(keys, keys + n, anchor, [](const aiVectorKey& a, const aiVectorKey& b) { return a.mTime < b.mTime; }); auto left_ptr = right_ptr - 1; float factor = (ticks - left_ptr->mTime) / (right_ptr->mTime - left_ptr->mTime); return mat4_from_aivector3d(left_ptr->mValue * (1.0f - factor) + right_ptr->mValue * factor); } }
std::upper_bound(keys, keys + n, anchor, [](const aiVectorKey& a, const aiVectorKey& b) { return a.mTime < b.mTime; })
call_expression
[ { "content": "struct aiMeshKey\n\n{\n\n /** The time of this key */\n\n double mTime;\n\n\n\n /** Index into the aiMesh::mAnimMeshes array of the\n\n * mesh corresponding to the #aiMeshAnim hosting this\n\n * key frame. The referenced anim mesh is evaluated\n\n * according to the rules defined in the docs for #aiAnimMesh.*/\n\n unsigned int mValue;\n\n\n\n#ifdef __cplusplus\n\n\n\n aiMeshKey() AI_NO_EXCEPT\n\n : mTime(0.0)\n\n , mValue(0)\n\n {\n\n }\n\n\n\n /** Construction from a given time and key value */\n\n aiMeshKey(double time, const unsigned int value)\n\n : mTime (time)\n\n , mValue (value)\n\n {}\n\n\n\n typedef unsigned int elem_type;\n\n\n\n // Comparison operators. For use with std::find();\n\n bool operator == (const aiMeshKey& o) const {\n\n return o.mValue == this->mValue;\n\n }\n\n bool operator != (const aiMeshKey& o) const {\n\n return o.mValue != this->mValue;\n\n }\n\n\n\n // Relational operators. For use with std::sort();\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/anim.h", "rank": 0, "score": 248141.00256808233 }, { "content": " C_STRUCT aiVectorKey* mPositionKeys;\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/anim.h", "rank": 1, "score": 245309.53269507657 }, { "content": " C_STRUCT aiString mNodeName;\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/anim.h", "rank": 2, "score": 245274.30155979627 }, { "content": " unsigned int mNumPositionKeys;\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/anim.h", "rank": 3, "score": 238986.07572487413 }, { "content": "struct aiNodeAnim {\n\n /** The name of the node affected by this animation. The node\n\n * must exist and it must be unique.*/\n\n C_STRUCT aiString mNodeName;\n\n\n\n /** The number of position keys */\n\n unsigned int mNumPositionKeys;\n\n\n\n /** The position keys of this animation channel. Positions are\n\n * specified as 3D vector. The array is mNumPositionKeys in size.\n\n *\n\n * If there are position keys, there will also be at least one\n\n * scaling and one rotation key.*/\n\n C_STRUCT aiVectorKey* mPositionKeys;\n\n\n\n /** The number of rotation keys */\n\n unsigned int mNumRotationKeys;\n\n\n\n /** The rotation keys of this animation channel. Rotations are\n\n * given as quaternions, which are 4D vectors. The array is\n\n * mNumRotationKeys in size.\n\n *\n\n * If there are rotation keys, there will also be at least one\n\n * scaling and one position key. */\n\n C_STRUCT aiQuatKey* mRotationKeys;\n\n\n\n /** The number of scaling keys */\n\n unsigned int mNumScalingKeys;\n\n\n\n /** The scaling keys of this animation channel. Scalings are\n\n * specified as 3D vector. The array is mNumScalingKeys in size.\n\n *\n\n * If there are scaling keys, there will also be at least one\n\n * position and one rotation key.*/\n\n C_STRUCT aiVectorKey* mScalingKeys;\n\n\n\n /** Defines how the animation behaves before the first\n\n * key is encountered.\n\n *\n\n * The default value is aiAnimBehaviour_DEFAULT (the original\n\n * transformation matrix of the affected node is used).*/\n\n C_ENUM aiAnimBehaviour mPreState;\n\n\n\n /** Defines how the animation behaves after the last\n\n * key was processed.\n\n *\n\n * The default value is aiAnimBehaviour_DEFAULT (the original\n\n * transformation matrix of the affected node is taken).*/\n\n C_ENUM aiAnimBehaviour mPostState;\n\n\n\n#ifdef __cplusplus\n\n aiNodeAnim() AI_NO_EXCEPT\n\n : mNumPositionKeys( 0 )\n\n , mPositionKeys( nullptr )\n\n , mNumRotationKeys( 0 )\n\n , mRotationKeys( nullptr )\n\n , mNumScalingKeys( 0 )\n\n , mScalingKeys( nullptr )\n\n , mPreState( aiAnimBehaviour_DEFAULT )\n\n , mPostState( aiAnimBehaviour_DEFAULT ) {\n\n // empty\n\n }\n\n\n\n ~aiNodeAnim() {\n\n delete [] mPositionKeys;\n\n delete [] mRotationKeys;\n\n delete [] mScalingKeys;\n\n }\n\n#endif // __cplusplus\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/anim.h", "rank": 4, "score": 210663.43882025158 }, { "content": "struct aiAnimation {\n\n /** The name of the animation. If the modeling package this data was\n\n * exported from does support only a single animation channel, this\n\n * name is usually empty (length is zero). */\n\n C_STRUCT aiString mName;\n\n\n\n /** Duration of the animation in ticks. */\n\n double mDuration;\n\n\n\n /** Ticks per second. 0 if not specified in the imported file */\n\n double mTicksPerSecond;\n\n\n\n /** The number of bone animation channels. Each channel affects\n\n * a single node. */\n\n unsigned int mNumChannels;\n\n\n\n /** The node animation channels. Each channel affects a single node.\n\n * The array is mNumChannels in size. */\n\n C_STRUCT aiNodeAnim** mChannels;\n\n\n\n\n\n /** The number of mesh animation channels. Each channel affects\n\n * a single mesh and defines vertex-based animation. */\n\n unsigned int mNumMeshChannels;\n\n\n\n /** The mesh animation channels. Each channel affects a single mesh.\n\n * The array is mNumMeshChannels in size. */\n\n C_STRUCT aiMeshAnim** mMeshChannels;\n\n\n\n /** The number of mesh animation channels. Each channel affects\n\n * a single mesh and defines morphing animation. */\n\n unsigned int mNumMorphMeshChannels;\n\n\n\n /** The morph mesh animation channels. Each channel affects a single mesh.\n\n * The array is mNumMorphMeshChannels in size. */\n\n C_STRUCT aiMeshMorphAnim **mMorphMeshChannels;\n\n\n\n#ifdef __cplusplus\n\n aiAnimation() AI_NO_EXCEPT\n\n : mDuration(-1.)\n\n , mTicksPerSecond(0.)\n\n , mNumChannels(0)\n\n , mChannels(nullptr)\n\n , mNumMeshChannels(0)\n\n , mMeshChannels(nullptr)\n\n , mNumMorphMeshChannels(0)\n\n , mMorphMeshChannels(nullptr) {\n\n // empty\n\n }\n\n\n\n ~aiAnimation() {\n\n // DO NOT REMOVE THIS ADDITIONAL CHECK\n\n if ( mNumChannels && mChannels ) {\n\n for( unsigned int a = 0; a < mNumChannels; a++) {\n\n delete mChannels[ a ];\n\n }\n\n\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/anim.h", "rank": 5, "score": 203499.62512993795 }, { "content": " C_STRUCT aiMeshMorphKey* mKeys;\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/anim.h", "rank": 6, "score": 203481.51239089636 }, { "content": " unsigned int mNumChannels;\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/anim.h", "rank": 7, "score": 198225.58535834288 }, { "content": " C_STRUCT aiVectorKey* mScalingKeys;\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/anim.h", "rank": 8, "score": 198225.50416032996 }, { "content": " C_STRUCT aiQuatKey* mRotationKeys;\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/anim.h", "rank": 9, "score": 198225.26077670712 }, { "content": " C_STRUCT aiMeshAnim** mMeshChannels;\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/anim.h", "rank": 10, "score": 198211.77337310056 }, { "content": " unsigned int mNumKeys;\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/anim.h", "rank": 11, "score": 198200.1660952569 }, { "content": "\t\t\tcase GL_UNSIGNED_INT:\treturn 4;\n", "file_path": "CrescentEngine/Core/Defunct/VertexBufferLayout.h", "rank": 12, "score": 194336.18247638317 }, { "content": "struct aiNodeAnim;\n\n\n\nnamespace Assimp {\n\n\n\n// ---------------------------------------------------------------------------\n\n/** \\brief Helper data structure for SceneCombiner.\n\n *\n\n * Describes to which node a scene must be attached to.\n\n */\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/SceneCombiner.h", "rank": 13, "score": 193273.6851279377 }, { "content": " unsigned int mNumMeshChannels;\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/anim.h", "rank": 14, "score": 193217.88985459303 }, { "content": " C_STRUCT aiMeshMorphAnim **mMorphMeshChannels;\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/anim.h", "rank": 15, "score": 193210.2759479218 }, { "content": " double mTicksPerSecond;\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/anim.h", "rank": 16, "score": 193209.38009251608 }, { "content": " unsigned int mNumRotationKeys;\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/anim.h", "rank": 17, "score": 193206.46398820344 }, { "content": " unsigned int mNumScalingKeys;\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/anim.h", "rank": 18, "score": 193206.46398820344 }, { "content": " int channel; \n", "file_path": "Dependencies/GLEW/include/GL/glxew.h", "rank": 19, "score": 192500.0208537627 }, { "content": " C_STRUCT aiVector3D mValue;\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/anim.h", "rank": 20, "score": 192092.72525876903 }, { "content": " unsigned int mNumMorphMeshChannels;\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/anim.h", "rank": 21, "score": 188468.68812076395 }, { "content": "struct aiMeshMorphKey\n\n{\n\n /** The time of this key */\n\n double mTime;\n\n\n\n /** The values and weights at the time of this key */\n\n unsigned int *mValues;\n\n double *mWeights;\n\n\n\n /** The number of values and weights */\n\n unsigned int mNumValuesAndWeights;\n\n#ifdef __cplusplus\n\n\taiMeshMorphKey() AI_NO_EXCEPT\n\n\t\t: mTime(0.0)\n\n\t\t, mValues(nullptr)\n\n\t\t, mWeights(nullptr)\n\n\t\t, mNumValuesAndWeights(0)\n\n\t{\n\n\n\n\t}\n\n\n\n ~aiMeshMorphKey()\n\n {\n\n if (mNumValuesAndWeights && mValues && mWeights) {\n\n delete [] mValues;\n\n delete [] mWeights;\n\n }\n\n }\n\n#endif\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/anim.h", "rank": 22, "score": 188449.55918536577 }, { "content": " VkDeviceSize stride;\n", "file_path": "Dependencies/Vulkan/include/vulkan/vulkan_core.h", "rank": 23, "score": 188016.28225728875 }, { "content": " VkSurfaceTransformFlagBitsKHR transform;\n", "file_path": "Dependencies/Vulkan/include/vulkan/vulkan_core.h", "rank": 24, "score": 188002.5561981888 }, { "content": " VkSurfaceTransformFlagBitsKHR transform;\n", "file_path": "Dependencies/Vulkan/include/vulkan/vk_icd.h", "rank": 25, "score": 188002.5561981888 }, { "content": " char name[VK_MAX_EXTENSION_NAME_SIZE];\n", "file_path": "Dependencies/Vulkan/include/vulkan/vulkan_core.h", "rank": 26, "score": 187999.7233973519 }, { "content": " LPCWSTR name;\n", "file_path": "Dependencies/Vulkan/include/vulkan/vulkan_win32.h", "rank": 27, "score": 187999.7233973519 }, { "content": " VkDeviceSize offset;\n", "file_path": "Dependencies/Vulkan/include/vulkan/vulkan_core.h", "rank": 28, "score": 187993.55354271427 }, { "content": " uint16_t offset;\n", "file_path": "Dependencies/Vulkan/include/spirv-tools/libspirv.h", "rank": 29, "score": 187993.55354271425 }, { "content": " float matrix[3][4];\n", "file_path": "Dependencies/Vulkan/include/vulkan/vulkan_core.h", "rank": 30, "score": 187921.16296269 }, { "content": " uint32_t transformOffset;\n", "file_path": "Dependencies/Vulkan/include/vulkan/vulkan_core.h", "rank": 31, "score": 187573.42968550988 }, { "content": " int maxTransformFeedbackInterleavedComponents;\n", "file_path": "Dependencies/Vulkan/include/glslang/Include/ResourceLimits.h", "rank": 32, "score": 184477.56093576332 }, { "content": " bool generalConstantMatrixVectorIndexing;\n", "file_path": "Dependencies/Vulkan/include/glslang/Include/ResourceLimits.h", "rank": 33, "score": 184361.5889402989 }, { "content": " bool generalAttributeMatrixVectorIndexing;\n", "file_path": "Dependencies/Vulkan/include/glslang/Include/ResourceLimits.h", "rank": 34, "score": 184361.5889402989 }, { "content": "\tconst char *name;\n", "file_path": "Dependencies/Vulkan/include/spirv_cross/spirv_cross_c.h", "rank": 35, "score": 183778.73872150714 }, { "content": "\tsize_t offset;\n", "file_path": "Dependencies/Vulkan/include/spirv_cross/spirv_cross_c.h", "rank": 36, "score": 183772.72865477405 }, { "content": " uint32_t maxShaderGroupStride;\n", "file_path": "Dependencies/Vulkan/include/vulkan/vulkan_core.h", "rank": 37, "score": 177119.5116110688 }, { "content": "struct ExceptionSwallower<void> {\n\n void operator ()() const {\n\n return;\n\n }\n\n};\n\n\n\n#define ASSIMP_BEGIN_EXCEPTION_REGION()\\\n\n{\\\n\n try {\n\n\n\n#define ASSIMP_END_EXCEPTION_REGION(type)\\\n\n } catch(...) {\\\n\n return ExceptionSwallower<type>()();\\\n\n }\\\n\n}\n\n\n\n#endif // INCLUDED_EXCEPTIONAL_H\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/Exceptional.h", "rank": 38, "score": 173053.60758526347 }, { "content": "\tclass Texture;\n", "file_path": "CrescentEngine/Shading/ShaderUtilities.h", "rank": 39, "score": 171772.31266489316 }, { "content": " uint32_t maxTransformFeedbackBufferDataStride;\n", "file_path": "Dependencies/Vulkan/include/vulkan/vulkan_core.h", "rank": 40, "score": 167823.83557699595 }, { "content": " uint32_t instanceShaderBindingTableRecordOffset:24;\n", "file_path": "Dependencies/Vulkan/include/vulkan/vulkan_core.h", "rank": 41, "score": 167772.19717599245 }, { "content": "\tclass TextureCube;\n\n\n\n\tenum Shader_Type\n\n\t{\n\n\t\tShader_Type_Boolean,\n\n\t\tShader_Type_Integer,\n\n\t\tShader_Type_Float,\n\n\t\tShader_Type_Sampler1D,\n\n\t\tShader_Type_Sampler2D,\n\n\t\tShader_Type_Sampler3D,\n\n\t\tShader_Type_SamplerCube,\n\n\t\tShader_Type_Vector2,\n\n\t\tShader_Type_Vector3,\n\n\t\tShader_Type_Vector4,\n\n\t\tShader_Type_Matrix2,\n\n\t\tShader_Type_Matrix3,\n\n\t\tShader_Type_Matrix4\n\n\t};\n\n\n\n\tstruct Uniform\n", "file_path": "CrescentEngine/Shading/ShaderUtilities.h", "rank": 42, "score": 165841.0474804293 }, { "content": " C_ENUM aiAnimBehaviour mPostState;\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/anim.h", "rank": 43, "score": 164891.25126692947 }, { "content": "struct aiMeshAnim\n\n{\n\n /** Name of the mesh to be animated. An empty string is not allowed,\n\n * animated meshes need to be named (not necessarily uniquely,\n\n * the name can basically serve as wild-card to select a group\n\n * of meshes with similar animation setup)*/\n\n C_STRUCT aiString mName;\n\n\n\n /** Size of the #mKeys array. Must be 1, at least. */\n\n unsigned int mNumKeys;\n\n\n\n /** Key frames of the animation. May not be NULL. */\n\n C_STRUCT aiMeshKey* mKeys;\n\n\n\n#ifdef __cplusplus\n\n\n\n aiMeshAnim() AI_NO_EXCEPT\n\n : mNumKeys()\n\n , mKeys()\n\n {}\n\n\n\n ~aiMeshAnim()\n\n {\n\n delete[] mKeys;\n\n }\n\n\n\n#endif\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/anim.h", "rank": 44, "score": 164866.7335837306 }, { "content": "\tclass Shader\n\n\t{\n\n\tpublic:\n\n\t\tShader();\n\n\t\tShader(const std::string& shaderName, std::string vertexShaderCode, std::string fragmentShaderCode);\n\n\n\n\t\tvoid LoadShader(const std::string& shaderName, std::string vertexShaderCode, std::string fragmentShaderCode);\n\n\t\tvoid UseShader();\n\n\t\tbool HasUniform(const std::string& uniformName);\n\n\n\n\t\tvoid DeleteShader();\n\n\n\n\t\tvoid SetUniformFloat(const std::string name, float value);\n\n\t\tvoid SetUniformInteger(std::string name, int value);\n\n\t\tvoid SetUniformBool(std::string name, bool value);\n\n\t\tvoid SetUniformVector2(std::string name, glm::vec2 value);\n\n\t\tvoid SetUniformVector3(std::string name, glm::vec3 value);\n\n\t\tvoid SetUniformMat4(std::string name, glm::mat4 value);\n\n\t\tvoid SetUniformVectorArray(std::string name, int size, const std::vector<glm::vec3>& values);\n\n\t\tvoid SetUniformVectorMat4(std::string identifier, std::vector<glm::mat4> value);\n", "file_path": "CrescentEngine/Shading/Shader.h", "rank": 45, "score": 164696.1909160125 }, { "content": "struct aiMeshMorphAnim\n\n{\n\n /** Name of the mesh to be animated. An empty string is not allowed,\n\n * animated meshes need to be named (not necessarily uniquely,\n\n * the name can basically serve as wildcard to select a group\n\n * of meshes with similar animation setup)*/\n\n C_STRUCT aiString mName;\n\n\n\n /** Size of the #mKeys array. Must be 1, at least. */\n\n unsigned int mNumKeys;\n\n\n\n /** Key frames of the animation. May not be NULL. */\n\n C_STRUCT aiMeshMorphKey* mKeys;\n\n\n\n#ifdef __cplusplus\n\n\n\n aiMeshMorphAnim() AI_NO_EXCEPT\n\n : mNumKeys()\n\n , mKeys()\n\n {}\n\n\n\n ~aiMeshMorphAnim()\n\n {\n\n delete[] mKeys;\n\n }\n\n\n\n#endif\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/anim.h", "rank": 46, "score": 161402.24539234102 }, { "content": "#\tifndef GLM_ENABLE_EXPERIMENTAL\n\n#\t\tpragma message(\"GLM: GLM_GTX_matrix_transform_2d is an experimental extension and may change in the future. Use #define GLM_ENABLE_EXPERIMENTAL before including it, if you really want to use it.\")\n\n#\telse\n\n#\t\tpragma message(\"GLM: GLM_GTX_matrix_transform_2d extension included\")\n\n#\tendif\n\n#endif\n\n\n\nnamespace glm\n\n{\n\n\t/// @addtogroup gtx_matrix_transform_2d\n\n\t/// @{\n\n\n\n\t/// Builds a translation 3 * 3 matrix created from a vector of 2 components.\n\n\t///\n\n\t/// @param m Input matrix multiplied by this translation matrix.\n\n\t/// @param v Coordinates of a translation vector.\n\n\ttemplate<typename T, qualifier Q>\n\n\tGLM_FUNC_QUALIFIER mat<3, 3, T, Q> translate(\n\n\t\tmat<3, 3, T, Q> const& m,\n\n\t\tvec<2, T, Q> const& v);\n", "file_path": "CrescentEngine/Vendor/glm/gtx/matrix_transform_2d.hpp", "rank": 47, "score": 160314.40299260413 }, { "content": "\n\n// Dependencies\n\n#include \"../gtc/constants.hpp\"\n\n#include \"../geometric.hpp\"\n\n#include \"../trigonometric.hpp\"\n\n#include \"../matrix.hpp\"\n\n\n\n#if GLM_MESSAGES == GLM_ENABLE && !defined(GLM_EXT_INCLUDED)\n\n#\tpragma message(\"GLM: GLM_EXT_matrix_transform extension included\")\n\n#endif\n\n\n\nnamespace glm\n\n{\n\n\t/// @addtogroup ext_matrix_transform\n\n\t/// @{\n\n\n\n\t/// Builds an identity matrix.\n\n\ttemplate<typename genType>\n\n\tGLM_FUNC_DECL GLM_CONSTEXPR genType identity();\n\n\n", "file_path": "CrescentEngine/Vendor/glm/ext/matrix_transform.hpp", "rank": 48, "score": 160311.94082573042 }, { "content": "\t///\n\n\t/// @param m Input matrix multiplied by this translation matrix.\n\n\t/// @param y Shear factor.\n\n\ttemplate<typename T, qualifier Q>\n\n\tGLM_FUNC_QUALIFIER mat<3, 3, T, Q> shearX(\n\n\t\tmat<3, 3, T, Q> const& m,\n\n\t\tT y);\n\n\n\n\t/// Builds a vertical (parallel to the y axis) shear 3 * 3 matrix.\n\n\t///\n\n\t/// @param m Input matrix multiplied by this translation matrix.\n\n\t/// @param x Shear factor.\n\n\ttemplate<typename T, qualifier Q>\n\n\tGLM_FUNC_QUALIFIER mat<3, 3, T, Q> shearY(\n\n\t\tmat<3, 3, T, Q> const& m,\n\n\t\tT x);\n\n\n\n\t/// @}\n\n}//namespace glm\n\n\n\n#include \"matrix_transform_2d.inl\"\n", "file_path": "CrescentEngine/Vendor/glm/gtx/matrix_transform_2d.hpp", "rank": 49, "score": 160311.61642649412 }, { "content": "\t/// @see - frustum(T const& left, T const& right, T const& bottom, T const& top, T const& nearVal, T const& farVal) frustum(T const& left, T const& right, T const& bottom, T const& top, T const& nearVal, T const& farVal)\n\n\ttemplate<typename T, qualifier Q>\n\n\tGLM_FUNC_DECL mat<4, 4, T, Q> lookAtLH(\n\n\t\tvec<3, T, Q> const& eye, vec<3, T, Q> const& center, vec<3, T, Q> const& up);\n\n\n\n\t/// Build a look at view matrix based on the default handedness.\n\n\t///\n\n\t/// @param eye Position of the camera\n\n\t/// @param center Position where the camera is looking at\n\n\t/// @param up Normalized up vector, how the camera is oriented. Typically (0, 0, 1)\n\n\t///\n\n\t/// @tparam T A floating-point scalar type\n\n\t/// @tparam Q A value from qualifier enum\n\n\t///\n\n\t/// @see - frustum(T const& left, T const& right, T const& bottom, T const& top, T const& nearVal, T const& farVal) frustum(T const& left, T const& right, T const& bottom, T const& top, T const& nearVal, T const& farVal)\n\n\t/// @see <a href=\"https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/gluLookAt.xml\">gluLookAt man page</a>\n\n\ttemplate<typename T, qualifier Q>\n\n\tGLM_FUNC_DECL mat<4, 4, T, Q> lookAt(\n\n\t\tvec<3, T, Q> const& eye, vec<3, T, Q> const& center, vec<3, T, Q> const& up);\n\n\n\n\t/// @}\n\n}//namespace glm\n\n\n\n#include \"matrix_transform.inl\"\n", "file_path": "CrescentEngine/Vendor/glm/ext/matrix_transform.hpp", "rank": 50, "score": 160305.50277721803 }, { "content": "\t/// Builds a translation 4 * 4 matrix created from a vector of 3 components.\n\n\t///\n\n\t/// @param m Input matrix multiplied by this translation matrix.\n\n\t/// @param v Coordinates of a translation vector.\n\n\t///\n\n\t/// @tparam T A floating-point scalar type\n\n\t/// @tparam Q A value from qualifier enum\n\n\t///\n\n\t/// @code\n\n\t/// #include <glm/glm.hpp>\n\n\t/// #include <glm/gtc/matrix_transform.hpp>\n\n\t/// ...\n\n\t/// glm::mat4 m = glm::translate(glm::mat4(1.0f), glm::vec3(1.0f));\n\n\t/// // m[0][0] == 1.0f, m[0][1] == 0.0f, m[0][2] == 0.0f, m[0][3] == 0.0f\n\n\t/// // m[1][0] == 0.0f, m[1][1] == 1.0f, m[1][2] == 0.0f, m[1][3] == 0.0f\n\n\t/// // m[2][0] == 0.0f, m[2][1] == 0.0f, m[2][2] == 1.0f, m[2][3] == 0.0f\n\n\t/// // m[3][0] == 1.0f, m[3][1] == 1.0f, m[3][2] == 1.0f, m[3][3] == 1.0f\n\n\t/// @endcode\n\n\t///\n\n\t/// @see - translate(mat<4, 4, T, Q> const& m, T x, T y, T z)\n", "file_path": "CrescentEngine/Vendor/glm/ext/matrix_transform.hpp", "rank": 51, "score": 160305.26440662827 }, { "content": "#pragma once\n\n\n\n// Dependencies\n\n#include \"../mat4x4.hpp\"\n\n#include \"../vec2.hpp\"\n\n#include \"../vec3.hpp\"\n\n#include \"../vec4.hpp\"\n\n#include \"../ext/matrix_projection.hpp\"\n\n#include \"../ext/matrix_clip_space.hpp\"\n\n#include \"../ext/matrix_transform.hpp\"\n\n\n\n#if GLM_MESSAGES == GLM_ENABLE && !defined(GLM_EXT_INCLUDED)\n\n#\tpragma message(\"GLM: GLM_GTC_matrix_transform extension included\")\n\n#endif\n\n\n\n#include \"matrix_transform.inl\"\n", "file_path": "CrescentEngine/Vendor/glm/gtc/matrix_transform.hpp", "rank": 52, "score": 160304.39604971727 }, { "content": "/// @ref gtx_matrix_transform_2d\n\n/// @file glm/gtx/matrix_transform_2d.hpp\n\n/// @author Miguel Ángel Pérez Martínez\n\n///\n\n/// @see core (dependence)\n\n///\n\n/// @defgroup gtx_matrix_transform_2d GLM_GTX_matrix_transform_2d\n\n/// @ingroup gtx\n\n///\n\n/// Include <glm/gtx/matrix_transform_2d.hpp> to use the features of this extension.\n\n///\n\n/// Defines functions that generate common 2d transformation matrices.\n\n\n\n#pragma once\n\n\n\n// Dependency:\n\n#include \"../mat3x3.hpp\"\n\n#include \"../vec2.hpp\"\n\n\n\n#if GLM_MESSAGES == GLM_ENABLE && !defined(GLM_EXT_INCLUDED)\n", "file_path": "CrescentEngine/Vendor/glm/gtx/matrix_transform_2d.hpp", "rank": 53, "score": 160303.90349146412 }, { "content": "\t/// @param center Position where the camera is looking at\n\n\t/// @param up Normalized up vector, how the camera is oriented. Typically (0, 0, 1)\n\n\t///\n\n\t/// @tparam T A floating-point scalar type\n\n\t/// @tparam Q A value from qualifier enum\n\n\t///\n\n\t/// @see - frustum(T const& left, T const& right, T const& bottom, T const& top, T const& nearVal, T const& farVal) frustum(T const& left, T const& right, T const& bottom, T const& top, T const& nearVal, T const& farVal)\n\n\ttemplate<typename T, qualifier Q>\n\n\tGLM_FUNC_DECL mat<4, 4, T, Q> lookAtRH(\n\n\t\tvec<3, T, Q> const& eye, vec<3, T, Q> const& center, vec<3, T, Q> const& up);\n\n\n\n\t/// Build a left handed look at view matrix.\n\n\t///\n\n\t/// @param eye Position of the camera\n\n\t/// @param center Position where the camera is looking at\n\n\t/// @param up Normalized up vector, how the camera is oriented. Typically (0, 0, 1)\n\n\t///\n\n\t/// @tparam T A floating-point scalar type\n\n\t/// @tparam Q A value from qualifier enum\n\n\t///\n", "file_path": "CrescentEngine/Vendor/glm/ext/matrix_transform.hpp", "rank": 54, "score": 160303.1980575972 }, { "content": "/// @ref ext_matrix_transform\n\n/// @file glm/ext/matrix_transform.hpp\n\n///\n\n/// @defgroup ext_matrix_transform GLM_EXT_matrix_transform\n\n/// @ingroup ext\n\n///\n\n/// Defines functions that generate common transformation matrices.\n\n///\n\n/// The matrices generated by this extension use standard OpenGL fixed-function\n\n/// conventions. For example, the lookAt function generates a transform from world\n\n/// space into the specific eye space that the projective matrix functions\n\n/// (perspective, ortho, etc) are designed to expect. The OpenGL compatibility\n\n/// specifications defines the particular layout of this eye space.\n\n///\n\n/// Include <glm/ext/matrix_transform.hpp> to use the features of this extension.\n\n///\n\n/// @see ext_matrix_projection\n\n/// @see ext_matrix_clip_space\n\n\n\n#pragma once\n", "file_path": "CrescentEngine/Vendor/glm/ext/matrix_transform.hpp", "rank": 55, "score": 160300.38180171204 }, { "content": "/// @ref gtc_matrix_transform\n\n/// @file glm/gtc/matrix_transform.hpp\n\n///\n\n/// @see core (dependence)\n\n/// @see gtx_transform\n\n/// @see gtx_transform2\n\n///\n\n/// @defgroup gtc_matrix_transform GLM_GTC_matrix_transform\n\n/// @ingroup gtc\n\n///\n\n/// Include <glm/gtc/matrix_transform.hpp> to use the features of this extension.\n\n///\n\n/// Defines functions that generate common transformation matrices.\n\n///\n\n/// The matrices generated by this extension use standard OpenGL fixed-function\n\n/// conventions. For example, the lookAt function generates a transform from world\n\n/// space into the specific eye space that the projective matrix functions\n\n/// (perspective, ortho, etc) are designed to expect. The OpenGL compatibility\n\n/// specifications defines the particular layout of this eye space.\n\n\n", "file_path": "CrescentEngine/Vendor/glm/gtc/matrix_transform.hpp", "rank": 56, "score": 160300.20055224703 }, { "content": "\n\n\t/// Builds a rotation 3 * 3 matrix created from an angle.\n\n\t///\n\n\t/// @param m Input matrix multiplied by this translation matrix.\n\n\t/// @param angle Rotation angle expressed in radians.\n\n\ttemplate<typename T, qualifier Q>\n\n\tGLM_FUNC_QUALIFIER mat<3, 3, T, Q> rotate(\n\n\t\tmat<3, 3, T, Q> const& m,\n\n\t\tT angle);\n\n\n\n\t/// Builds a scale 3 * 3 matrix created from a vector of 2 components.\n\n\t///\n\n\t/// @param m Input matrix multiplied by this translation matrix.\n\n\t/// @param v Coordinates of a scale vector.\n\n\ttemplate<typename T, qualifier Q>\n\n\tGLM_FUNC_QUALIFIER mat<3, 3, T, Q> scale(\n\n\t\tmat<3, 3, T, Q> const& m,\n\n\t\tvec<2, T, Q> const& v);\n\n\n\n\t/// Builds an horizontal (parallel to the x axis) shear 3 * 3 matrix.\n", "file_path": "CrescentEngine/Vendor/glm/gtx/matrix_transform_2d.hpp", "rank": 57, "score": 160299.77953471304 }, { "content": "\t/// @see - translate(vec<3, T, Q> const& v)\n\n\t/// @see <a href=\"https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glTranslate.xml\">glTranslate man page</a>\n\n\ttemplate<typename T, qualifier Q>\n\n\tGLM_FUNC_DECL mat<4, 4, T, Q> translate(\n\n\t\tmat<4, 4, T, Q> const& m, vec<3, T, Q> const& v);\n\n\n\n\t/// Builds a rotation 4 * 4 matrix created from an axis vector and an angle.\n\n\t///\n\n\t/// @param m Input matrix multiplied by this rotation matrix.\n\n\t/// @param angle Rotation angle expressed in radians.\n\n\t/// @param axis Rotation axis, recommended to be normalized.\n\n\t///\n\n\t/// @tparam T A floating-point scalar type\n\n\t/// @tparam Q A value from qualifier enum\n\n\t///\n\n\t/// @see - rotate(mat<4, 4, T, Q> const& m, T angle, T x, T y, T z)\n\n\t/// @see - rotate(T angle, vec<3, T, Q> const& v)\n\n\t/// @see <a href=\"https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glRotate.xml\">glRotate man page</a>\n\n\ttemplate<typename T, qualifier Q>\n\n\tGLM_FUNC_DECL mat<4, 4, T, Q> rotate(\n", "file_path": "CrescentEngine/Vendor/glm/ext/matrix_transform.hpp", "rank": 58, "score": 160296.77523601244 }, { "content": "\t\tfloat RetrieveAnimationTime() const { return m_AnimationTime; }\n\n\n\n\t\tvoid RenderSettingsInEditor(glm::vec3& modelPosition, glm::vec3& modelScale);\n\n\t\t//glm::mat4 RetrieveModelMatrix() const { return m_ModelMatrix; }\n\n\n\n\tpublic:\n\n\t\tstd::vector<glm::mat4> m_BoneMatrices, m_BoneOffsets;\n\n\n\n\tprivate:\n\n\t\tvoid ProcessNode(aiNode* node);\n\n\t\tMesh ProcessMesh(const aiMesh* mesh);\n\n\t\tstd::vector<MeshTexture> LoadMaterialTextures(aiMaterial* material, aiTextureType type, std::string typeName);\n\n\n\n\t\tvoid RecursivelyUpdateBoneMatrices(int animation_id, aiNode* node, glm::mat4 transform, double ticks);\n\n\n\n\t\tstatic glm::mat4 InterpolateTranslationMatrix(aiVectorKey* keys, uint32_t n, double ticks);\n\n\t\tstatic glm::mat4 InterpolateRotationMatrix(aiQuatKey* keys, uint32_t n, double ticks);\n\n\t\tstatic glm::mat4 InterpolateScalingMatrix(aiVectorKey* keys, uint32_t n, double ticks);\n\n\n\n\t\tstd::string ConvertUUIDToString() const;\n", "file_path": "CrescentEngine/Models/Model.h", "rank": 59, "score": 72.83513743925172 }, { "content": "\t\t\tcurrent_transform = mat4_from_aimatrix4x4(node->mTransformation);\n\n\t\t}\n\n\t\t\n\n\t\tif (m_BoneMapper.RetrieveBoneLibrary().count(node_name)) \n\n\t\t{\n\n\t\t\tuint32_t i = m_BoneMapper.RetrieveBoneLibrary()[node_name];\n\n\t\t\tm_BoneMatrices[i] = transform * current_transform * m_BoneOffsets[i];\n\n\t\t}\n\n\n\n\t\tfor (int i = 0; i < node->mNumChildren; i++) \n\n\t\t{\n\n\t\t\tRecursivelyUpdateBoneMatrices(animation_id, node->mChildren[i], transform * current_transform, ticks);\n\n\t\t}\n\n\t}\n\n\n\n\tglm::mat4 Model::InterpolateTranslationMatrix(aiVectorKey* keys, uint32_t n, double ticks)\n\n\t{\n\n\t\tstatic auto mat4_from_aivector3d = [](aiVector3D vector) -> glm::mat4 {\n\n\t\t\treturn glm::translate(glm::mat4(1), glm::vec3(vector.x, vector.y, vector.z));\n\n\t\t};\n", "file_path": "CrescentEngine/Models/Model.cpp", "rank": 60, "score": 72.41308866285011 }, { "content": " }\n\n }\n\n\n\n // ----------------------------------------------------------------------------\n\n /** Extract a particular vertex from a anim mesh and interleave all components */\n\n explicit Vertex(const aiAnimMesh* msh, unsigned int idx) {\n\n ai_assert(idx < msh->mNumVertices);\n\n position = msh->mVertices[idx];\n\n\n\n if (msh->HasNormals()) {\n\n normal = msh->mNormals[idx];\n\n }\n\n\n\n if (msh->HasTangentsAndBitangents()) {\n\n tangent = msh->mTangents[idx];\n\n bitangent = msh->mBitangents[idx];\n\n }\n\n\n\n for (unsigned int i = 0; msh->HasTextureCoords(i); ++i) {\n\n texcoords[i] = msh->mTextureCoords[i][idx];\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/Vertex.h", "rank": 62, "score": 67.79170898487436 }, { "content": "\t\tstd::string node_name = node->mName.C_Str();\n\n\t\tauto animation = m_ModelScene->mAnimations[animation_id];\n\n\t\tglm::mat4 current_transform;\n\n\n\n\t\tif (m_AnimationChannelMap.count(std::pair<uint32_t, std::string>(animation_id, node_name))) \n\n\t\t{\n\n\t\t\tuint32_t channel_id = m_AnimationChannelMap[std::pair<uint32_t, std::string>(animation_id, node_name)];\n\n\t\t\tauto channel = animation->mChannels[channel_id];\n\n\n\n\t\t\t// translation matrix\n\n\t\t\tglm::mat4 translation_matrix = InterpolateTranslationMatrix(channel->mPositionKeys, channel->mNumPositionKeys, ticks);\n\n\t\t\t// rotation matrix\n\n\t\t\tglm::mat4 rotation_matrix = InterpolateRotationMatrix(channel->mRotationKeys, channel->mNumRotationKeys, ticks);\n\n\t\t\t// scaling matrix\n\n\t\t\tglm::mat4 scaling_matrix = InterpolateScalingMatrix(channel->mScalingKeys, channel->mNumScalingKeys, ticks);\n\n\n\n\t\t\tcurrent_transform = translation_matrix * rotation_matrix * scaling_matrix;\n\n\t\t}\n\n\t\telse \n\n\t\t{\n", "file_path": "CrescentEngine/Models/Model.cpp", "rank": 64, "score": 66.29864268611394 }, { "content": "\n\npublic:\n\n\n\n // ----------------------------------------------------------------------------\n\n /** Convert back to non-interleaved storage */\n\n void SortBack(aiMesh* out, unsigned int idx) const {\n\n\n\n ai_assert(idx<out->mNumVertices);\n\n out->mVertices[idx] = position;\n\n\n\n if (out->HasNormals()) {\n\n out->mNormals[idx] = normal;\n\n }\n\n\n\n if (out->HasTangentsAndBitangents()) {\n\n out->mTangents[idx] = tangent;\n\n out->mBitangents[idx] = bitangent;\n\n }\n\n\n\n for(unsigned int i = 0; out->HasTextureCoords(i); ++i) {\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/Vertex.h", "rank": 66, "score": 64.97774845007986 }, { "content": "\t\tstd::map<std::pair<uint32_t, std::string>, uint32_t> m_AnimationChannelMap;\n\n\t\tBoneMapper m_BoneMapper;\n\n\n\n\tprivate:\n\n\t\tunsigned int m_VertexArrayID = 0;\n\n\t\tunsigned int m_VertexBufferID = 0;\n\n\t\tunsigned int m_IndexBufferID = 0;\n\n\n\n\tpublic:\n\n\t\t//Defunct\n\n\t\tMesh(std::vector<Vertex> vertices, std::vector<unsigned int> indices, std::vector<MeshTexture> textures);\n\n\t\tvoid Draw(Shader& shader, bool renderShadowMap, unsigned int shadowMapTextureID);\n\n\t\tstd::vector<Vertex> vertices;\n\n\t\tstd::vector<unsigned int> indices;\n\n\t\tstd::vector<MeshTexture> textures;\n\n\n\n\t\t//Defunct\n\n\t\tunsigned int vertexArrayObject, vertexBufferObject, indexBufferObject;\n\n\t\tvoid SetupMesh();\n\n\n\n\t};\n\n}\n\n\n", "file_path": "CrescentEngine/Models/Mesh.h", "rank": 67, "score": 63.89900280905209 }, { "content": "\t\t\tProcessNode(node->mChildren[i]);\n\n\t\t}\n\n\t}\n\n\n\n\tMesh Model::ProcessMesh(const aiMesh* mesh)\n\n\t{\n\n\t\tauto mat4_from_aimatrix4x4 = [](aiMatrix4x4 matrix) -> glm::mat4 {\n\n\t\t\tglm::mat4 res;\n\n\t\t\tfor (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) res[j][i] = matrix[i][j];\n\n\t\t\treturn res;\n\n\t\t};\n\n\n\n\t\t//Data we must fill.\n\n\t\tstd::vector<Vertex> vertices;\n\n\t\tstd::vector<unsigned int> indices;\n\n\t\tstd::vector<MeshTexture> textures;\n\n\n\n\t\t//Walk through each of the mesh's vertices.\n\n\t\tfor (unsigned int i = 0; i < mesh->mNumVertices; i++)\n\n\t\t{\n", "file_path": "CrescentEngine/Models/Model.cpp", "rank": 69, "score": 62.0473199273047 }, { "content": "\t\t\tstd::string infoText = \"Successfully loaded texture at: \" + filename;\n\n\t\t\tCrescentInfo(infoText);\n\n\t\t}\n\n\t\telse\n\n\t\t{\n\n\t\t\tstd::string infoText = \"Failed to load path at: \" + filename;\n\n\t\t\tstbi_image_free(data);\n\n\t\t}\n\n\n\n\t\treturn textureID;\n\n\t}\n\n\n\n\tvoid Model::RecursivelyUpdateBoneMatrices(int animation_id, aiNode* node, glm::mat4 transform, double ticks)\n\n\t{\n\n\t\tstatic auto mat4_from_aimatrix4x4 = [](aiMatrix4x4 matrix) -> glm::mat4 {\n\n\t\t\tglm::mat4 res;\n\n\t\t\tfor (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) res[j][i] = matrix[i][j];\n\n\t\t\treturn res;\n\n\t\t};\n\n\n", "file_path": "CrescentEngine/Models/Model.cpp", "rank": 70, "score": 61.27477558115494 }, { "content": " /** Extract a particular vertex from a mesh and interleave all components */\n\n explicit Vertex(const aiMesh* msh, unsigned int idx) {\n\n ai_assert(idx < msh->mNumVertices);\n\n position = msh->mVertices[idx];\n\n\n\n if (msh->HasNormals()) {\n\n normal = msh->mNormals[idx];\n\n }\n\n\n\n if (msh->HasTangentsAndBitangents()) {\n\n tangent = msh->mTangents[idx];\n\n bitangent = msh->mBitangents[idx];\n\n }\n\n\n\n for (unsigned int i = 0; msh->HasTextureCoords(i); ++i) {\n\n texcoords[i] = msh->mTextureCoords[i][idx];\n\n }\n\n\n\n for (unsigned int i = 0; msh->HasVertexColors(i); ++i) {\n\n colors[i] = msh->mColors[i][idx];\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/Vertex.h", "rank": 71, "score": 61.087926730362 }, { "content": " for (unsigned int i = 0; i < aiNode->mNumChildren; ++i)\n\n {\n\n node->AddChildEntity(MeshLoader::ProcessNode(rendererContext, aiNode->mChildren[i], aiScene, fileDirectory, setDefaultMaterial));\n\n }\n\n\n\n return node;\n\n }\n\n \n\n Mesh* MeshLoader::ParseMesh(aiMesh* aiMesh, const aiScene* aiScene)\n\n {\n\n std::vector<glm::vec3> positions;\n\n std::vector<glm::vec2> uv;\n\n std::vector<glm::vec3> normals;\n\n std::vector<glm::vec3> tangents;\n\n std::vector<glm::vec3> bitangents;\n\n std::vector<unsigned int> indices;\n\n\n\n positions.resize(aiMesh->mNumVertices);\n\n normals.resize(aiMesh->mNumVertices);\n\n if (aiMesh->mNumUVComponents > 0)\n", "file_path": "CrescentEngine/Memory/MeshLoader.cpp", "rank": 72, "score": 59.48090234825312 }, { "content": "#pragma once\n\n#include \"Core.h\"\n\n#include \"glm/glm.hpp\"\n\n#include <string>\n\n#include <vector>\n\n#include \"../Shading/Shader.h\"\n\n#include <algorithm>\n\n#include <assimp/scene.h>\n\n#include <map>\n\n#include \"BoneMapper.h\"\n\n\n\nnamespace Crescent\n\n{\n\n\tstruct Vertex //Defined for each vertice on a mesh.\n\n\t{\n\n\t\tglm::vec3 Position;\n\n\t\tglm::vec3 Normal;\n\n\t\tglm::vec2 TexCoords;\n\n\t\tglm::vec3 Tangent;\n\n\t\tglm::vec3 Bitangent;\n", "file_path": "CrescentEngine/Models/Mesh.h", "rank": 73, "score": 58.43337604518591 }, { "content": " bitangents[i] = glm::vec3(aiMesh->mBitangents[i].x, aiMesh->mBitangents[i].y, aiMesh->mBitangents[i].z);\n\n }\n\n }\n\n for (unsigned int f = 0; f < aiMesh->mNumFaces; ++f)\n\n {\n\n //We know we're always working with triangles due to the Triangulate option.\n\n for (unsigned int i = 0; i < 3; ++i)\n\n {\n\n indices[f * 3 + i] = aiMesh->mFaces[f].mIndices[i];\n\n }\n\n }\n\n\n\n Mesh* mesh = new Mesh;\n\n mesh->m_Positions = positions;\n\n mesh->m_UV = uv;\n\n mesh->m_Normals = normals;\n\n mesh->m_Tangents = tangents;\n\n mesh->m_Bitangents = bitangents;\n\n mesh->m_Indices = indices;\n\n mesh->m_Topology = Triangles;\n", "file_path": "CrescentEngine/Memory/MeshLoader.cpp", "rank": 74, "score": 57.85986063362304 }, { "content": "\t\t}\n\n\n\n\tpublic:\n\n\t\tTopology m_Topology = Triangles;\n\n\n\n\t\tstd::vector<glm::vec3> m_Positions;\n\n\t\tstd::vector<glm::vec2> m_UV;\n\n\t\tstd::vector<glm::vec3> m_Normals;\n\n\t\tstd::vector<glm::vec3> m_Tangents;\n\n\t\tstd::vector<glm::vec3> m_Bitangents;\t\n\n\t\tstd::vector<std::pair<int, int>> m_BoneIDs;\n\n\t\tstd::vector<std::pair<int, float>> m_BoneWeights;\n\n\t\t\n\n\n\n\t\tstd::vector<unsigned int> m_Indices;\n\n\n\n\t\t//Skeletal Animations\n\n\t\tstd::vector<glm::mat4> m_BoneMatrices, m_BoneOffsets;\n\n\t\tint m_CurrentlyPlayingAnimationIndex;\n\n\t\tstd::vector<MeshAnimation*> m_Animations; //Stores a vector of animations mapped to an index.\n", "file_path": "CrescentEngine/Models/Mesh.h", "rank": 75, "score": 56.8877686495915 }, { "content": " {\n\n uv.resize(aiMesh->mNumVertices);\n\n tangents.resize(aiMesh->mNumVertices);\n\n bitangents.resize(aiMesh->mNumVertices);\n\n }\n\n //We assume a constant of 3 vertex indices per face as we always triangulate in Assimp's post-processing step. Otherwise, you'll want transform this to a more flexible scheme.\n\n indices.resize(aiMesh->mNumFaces * 3);\n\n\n\n for (unsigned int i = 0; i < aiMesh->mNumVertices; ++i)\n\n {\n\n positions[i] = glm::vec3(aiMesh->mVertices[i].x, aiMesh->mVertices[i].y, aiMesh->mVertices[i].z);\n\n normals[i] = glm::vec3(aiMesh->mNormals[i].x, aiMesh->mNormals[i].y, aiMesh->mNormals[i].z);\n\n if (aiMesh->mTextureCoords[0])\n\n {\n\n uv[i] = glm::vec2(aiMesh->mTextureCoords[0][i].x, aiMesh->mTextureCoords[0][i].y);\n\n\n\n }\n\n if (aiMesh->mTangents)\n\n {\n\n tangents[i] = glm::vec3(aiMesh->mTangents[i].x, aiMesh->mTangents[i].y, aiMesh->mTangents[i].z);\n", "file_path": "CrescentEngine/Memory/MeshLoader.cpp", "rank": 76, "score": 56.141295473823924 }, { "content": "#include \"CrescentPCH.h\"\n\n#include \"Cubemap.h\"\n\n#include <GL/glew.h>\n\n#include <stb_image/stb_image.h>\n\n\n\nnamespace Crescent\n\n{\n\n void Cubemap::LoadCubemap(std::vector<std::string> fileLocations)\n\n {\n\n m_CubemapShader.CreateShaders(\"Resources/Shaders/CubemapVertex.shader\", \"Resources/Shaders/CubemapFragment.shader\");\n\n glGenTextures(1, &m_CubemapID);\n\n glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubemapID);\n\n\n\n int width, height, nrChannels;\n\n for (unsigned int i = 0; i < fileLocations.size(); i++)\n\n { \n\n unsigned char* data = stbi_load(fileLocations[i].c_str(), &width, &height, &nrChannels, 0);\n\n if (data)\n\n {\n\n GLenum format;\n", "file_path": "CrescentEngine/Core/Defunct/Cubemap.cpp", "rank": 77, "score": 56.03492870940244 }, { "content": " void setExternal(bool e) { }\n\n bool isYuv() const { return false; }\n\n#else\n\n unsigned int vectorSize : 3; // vector return type size.\n\n // Some languages support structures as sample results. Storing the whole structure in the\n\n // TSampler is too large, so there is an index to a separate table.\n\n static const unsigned structReturnIndexBits = 4; // number of index bits to use.\n\n static const unsigned structReturnSlots = (1<<structReturnIndexBits)-1; // number of valid values\n\n static const unsigned noReturnStruct = structReturnSlots; // value if no return struct type.\n\n // Index into a language specific table of texture return structures.\n\n unsigned int structReturnIndex : structReturnIndexBits;\n\n\n\n bool external : 1; // GL_OES_EGL_image_external\n\n bool yuv : 1; // GL_EXT_YUV_target\n\n\n\n#ifdef ENABLE_HLSL\n\n unsigned int getVectorSize() const { return vectorSize; }\n\n void clearReturnStruct() { structReturnIndex = noReturnStruct; }\n\n bool hasReturnStruct() const { return structReturnIndex != noReturnStruct; }\n\n unsigned getStructReturnIndex() const { return structReturnIndex; }\n", "file_path": "Dependencies/Vulkan/include/glslang/Include/Types.h", "rank": 78, "score": 54.93701607081407 }, { "content": "\t\t\t\tm_InternalDeltaTime = 0.0f;\n\n\t\t\t}\n\n\n\n\t\t\tRecursivelyUpdateBoneMatrices(m_CurrentlyPlayingAnimation, m_ModelScene->mRootNode, glm::mat4(1), m_InternalDeltaTime * m_ModelScene->mAnimations[m_CurrentlyPlayingAnimation]->mTicksPerSecond);\n\n\t\t}\n\n\n\n\t\tfor (unsigned int i = 0; i < m_Meshes.size(); i++)\n\n\t\t{\n\n\t\t\tm_Meshes[i].Draw(shader, renderShadowMap, shadowMapTextureID);\n\n\t\t}\n\n\t}\n\n\n\n\tvoid Model::DrawStaticModel(Shader& shader, bool renderShadowMap, unsigned int shadowMapTextureID) \n\n\t{\n\n\t\tfor (unsigned int i = 0; i < m_Meshes.size(); i++)\n\n\t\t{\n\n\t\t\tm_Meshes[i].Draw(shader, renderShadowMap, shadowMapTextureID);\n\n\t\t}\n\n\t}\n\n\n", "file_path": "CrescentEngine/Models/Model.cpp", "rank": 79, "score": 54.6010224420582 }, { "content": "\t\t\tauto bone = mesh->mBones[i];\n\n\t\t\tauto id = m_BoneMapper.Name(bone->mName.C_Str());\n\n\n\n\t\t\tm_BoneOffsets.resize(std::max(id + 1, (uint32_t)m_BoneOffsets.size())); \n\n\t\t\tm_BoneOffsets[id] = mat4_from_aimatrix4x4(bone->mOffsetMatrix);\n\n\n\n\t\t\tfor (int j = 0; j < bone->mNumWeights; j++)\n\n\t\t\t{\n\n\t\t\t\tauto weight = bone->mWeights[j];\n\n\t\t\t\t//vertices[weight.mVertexId].AddBone(id, weight.mWeight);\n\n\t\t\t}\n\n\t\t}\n\n\t\t\n\n\t\treturn Mesh(vertices, indices, textures);\n\n\t}\n\n\n\n\t//Iterates over all the texture locations of the given texture type, retrieve the texture's file location and then loads and generates the texture.\n\n\tstd::vector<MeshTexture> Model::LoadMaterialTextures(aiMaterial* material, aiTextureType type, std::string typeName)\n\n\t{\n\n\t\tstd::vector<MeshTexture> textures;\n", "file_path": "CrescentEngine/Models/Model.cpp", "rank": 80, "score": 54.586047855288435 }, { "content": "\n\n // -------------------------------------------------------------------\n\n // Same as AddNodePrefixes, but with an additional check\n\n static void AddNodePrefixesChecked(aiNode* node, const char* prefix,\n\n unsigned int len,\n\n std::vector<SceneHelper>& input,\n\n unsigned int cur);\n\n\n\n // -------------------------------------------------------------------\n\n // Add node identifiers to a hashing set\n\n static void AddNodeHashes(aiNode* node, std::set<unsigned int>& hashes);\n\n\n\n\n\n // -------------------------------------------------------------------\n\n // Search for duplicate names\n\n static bool FindNameMatch(const aiString& name,\n\n std::vector<SceneHelper>& input, unsigned int cur);\n\n};\n\n\n\n}\n\n\n\n#endif // !! AI_SCENE_COMBINER_H_INC\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/SceneCombiner.h", "rank": 81, "score": 52.43712424771757 }, { "content": "#include \"CrescentPCH.h\"\n\n#include \"Resources.h\"\n\n#include \"../Memory/ShaderLoader.h\"\n\n#include \"../Memory/TextureLoader.h\"\n\n#include \"../Memory/MeshLoader.h\"\n\n#include \"../Shading/Texture.h\"\n\n#include \"../Shading/TextureCube.h\"\n\n#include \"../Utilities/StringID.h\"\n\n#include \"../Scene/Scene.h\"\n\n#include \"../Scene/SceneEntity.h\"\n\n\n\nnamespace Crescent\n\n{\n\n\tstd::map<unsigned int, Shader> Resources::m_Shaders = std::map<unsigned int, Shader>();\n\n\tstd::map<unsigned int, Texture> Resources::m_Textures = std::map<unsigned int, Texture>();\n\n\tstd::map<unsigned int, TextureCube> Resources::m_TextureCubes = std::map<unsigned int, TextureCube>();\n\n\tstd::map<unsigned int, SceneEntity*> Resources::m_SceneMeshes = std::map<unsigned int, SceneEntity*>();\n\n\n\n\tvoid Resources::InitializeResourceManager()\n\n\t{\n", "file_path": "CrescentEngine/Rendering/Resources.cpp", "rank": 82, "score": 51.95304468637322 }, { "content": " (std::vector<aiVector3D>&));\n\n\n\n static aiMesh* MakeMesh ( unsigned int (*GenerateFunc)\n\n (std::vector<aiVector3D>&, bool));\n\n\n\n static aiMesh* MakeMesh ( unsigned int n, void (*GenerateFunc)\n\n (unsigned int,std::vector<aiVector3D>&));\n\n\n\n // ----------------------------------------------------------------\n\n /** @brief Generates a hexahedron (cube)\n\n *\n\n * Hexahedrons can be scaled on all axes.\n\n * @param positions Receives output triangles.\n\n * @param polygons If you pass true here quads will be returned\n\n * @return Number of vertices per face\n\n */\n\n static unsigned int MakeHexahedron(\n\n std::vector<aiVector3D>& positions,\n\n bool polygons = false);\n\n\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/StandardShapes.h", "rank": 83, "score": 51.86485195063191 }, { "content": "\t\tif (n == 0) return glm::mat4(1);\n\n\t\tif (n == 1) return mat4_from_aivector3d(keys->mValue);\n\n\t\tif (ticks <= keys[0].mTime) return mat4_from_aivector3d(keys[0].mValue);\n\n\t\tif (keys[n - 1].mTime <= ticks) return mat4_from_aivector3d(keys[n - 1].mValue);\n\n\n\n\t\taiVectorKey anchor;\n\n\t\tanchor.mTime = ticks;\n\n\t\tauto right_ptr = std::upper_bound(keys, keys + n, anchor, [](const aiVectorKey& a, const aiVectorKey& b) {\n\n\t\t\treturn a.mTime < b.mTime;\n\n\t\t\t});\n\n\t\tauto left_ptr = right_ptr - 1;\n\n\n\n\t\tfloat factor = (ticks - left_ptr->mTime) / (right_ptr->mTime - left_ptr->mTime);\n\n\t\treturn mat4_from_aivector3d(left_ptr->mValue * (1.0f - factor) + right_ptr->mValue * factor);\n\n\t}\n\n\n\n\tglm::mat4 Model::InterpolateRotationMatrix(aiQuatKey* keys, uint32_t n, double ticks)\n\n\t{\n\n\t\tstatic auto mat4_from_aiquaternion = [](aiQuaternion quaternion) -> glm::mat4 {\n\n\t\t\tauto rotation_matrix = quaternion.GetMatrix();\n", "file_path": "CrescentEngine/Models/Model.cpp", "rank": 84, "score": 51.61834440389192 }, { "content": "\t}\n\n\n\n\tglm::mat4 Model::InterpolateScalingMatrix(aiVectorKey* keys, uint32_t n, double ticks)\n\n\t{\n\n\t\tstatic auto mat4_from_aivector3d = [](aiVector3D vector) -> glm::mat4 {\n\n\t\t\treturn glm::scale(glm::mat4(1), glm::vec3(vector.x, vector.y, vector.z));\n\n\t\t};\n\n\t\tif (n == 0) return glm::mat4(1);\n\n\t\tif (n == 1) return mat4_from_aivector3d(keys->mValue);\n\n\t\tif (ticks <= keys[0].mTime) return mat4_from_aivector3d(keys[0].mValue);\n\n\t\tif (keys[n - 1].mTime <= ticks) return mat4_from_aivector3d(keys[n - 1].mValue);\n\n\n\n\t\taiVectorKey anchor;\n\n\t\tanchor.mTime = ticks;\n\n\t\tauto right_ptr = std::upper_bound(keys, keys + n, anchor, [](const aiVectorKey& a, const aiVectorKey& b) {\n\n\t\t\treturn a.mTime < b.mTime;\n\n\t\t\t});\n\n\t\tauto left_ptr = right_ptr - 1;\n\n\n\n\t\tfloat factor = (ticks - left_ptr->mTime) / (right_ptr->mTime - left_ptr->mTime);\n", "file_path": "CrescentEngine/Models/Model.cpp", "rank": 85, "score": 51.02183711444194 }, { "content": " out->mTextureCoords[i][idx] = texcoords[i];\n\n }\n\n\n\n for(unsigned int i = 0; out->HasVertexColors(i); ++i) {\n\n out->mColors[i][idx] = colors[i];\n\n }\n\n }\n\n\n\nprivate:\n\n\n\n // ----------------------------------------------------------------------------\n\n /** Construct from two operands and a binary operation to combine them */\n\n template <template <typename t> class op> static Vertex BinaryOp(const Vertex& v0, const Vertex& v1) {\n\n // this is a heavy task for the compiler to optimize ... *pray*\n\n\n\n Vertex res;\n\n res.position = op<aiVector3D>()(v0.position,v1.position);\n\n res.normal = op<aiVector3D>()(v0.normal,v1.normal);\n\n res.tangent = op<aiVector3D>()(v0.tangent,v1.tangent);\n\n res.bitangent = op<aiVector3D>()(v0.bitangent,v1.bitangent);\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/Vertex.h", "rank": 86, "score": 50.880319985128786 }, { "content": "\n\n for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {\n\n res.texcoords[i] = op<aiVector3D>()(v0.texcoords[i],v1.texcoords[i]);\n\n }\n\n for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_COLOR_SETS; ++i) {\n\n res.colors[i] = op<aiColor4D>()(v0.colors[i],v1.colors[i]);\n\n }\n\n return res;\n\n }\n\n\n\n // ----------------------------------------------------------------------------\n\n /** This time binary arithmetics of v0 with a floating-point number */\n\n template <template <typename, typename, typename> class op> static Vertex BinaryOp(const Vertex& v0, ai_real f) {\n\n // this is a heavy task for the compiler to optimize ... *pray*\n\n\n\n Vertex res;\n\n res.position = op<aiVector3D,ai_real,aiVector3D>()(v0.position,f);\n\n res.normal = op<aiVector3D,ai_real,aiVector3D>()(v0.normal,f);\n\n res.tangent = op<aiVector3D,ai_real,aiVector3D>()(v0.tangent,f);\n\n res.bitangent = op<aiVector3D,ai_real,aiVector3D>()(v0.bitangent,f);\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/Vertex.h", "rank": 87, "score": 50.45817046920396 }, { "content": " // start with 0(does not allow relative indexing)\n\n std::vector<joint_and_weight_t> weightValues;\n\n };\n\n\n\n // Index struct to support different indices for vtx/normal/texcoord.\n\n // -1 means not used.\n\n struct index_t {\n\n int vertex_index;\n\n int normal_index;\n\n int texcoord_index;\n\n };\n\n\n\n struct mesh_t {\n\n std::vector<index_t> indices;\n\n std::vector<unsigned char>\n\n num_face_vertices; // The number of vertices per\n\n // face. 3 = triangle, 4 = quad,\n\n // ... Up to 255 vertices per face.\n\n std::vector<int> material_ids; // per-face material ID\n\n std::vector<unsigned int> smoothing_group_ids; // per-face smoothing group\n", "file_path": "VulkanSupport/Vendor/tinyobjloader/tiny_obj_loader.h", "rank": 89, "score": 49.866992968003586 }, { "content": " // ----------------------------------------------------------------\n\n /** @brief Generates an icosahedron\n\n *\n\n * @param positions Receives output triangles.\n\n * @return Number of vertices per face\n\n */\n\n static unsigned int MakeIcosahedron(\n\n std::vector<aiVector3D>& positions);\n\n\n\n\n\n // ----------------------------------------------------------------\n\n /** @brief Generates a dodecahedron\n\n *\n\n * @param positions Receives output triangles\n\n * @param polygons If you pass true here pentagons will be returned\n\n * @return Number of vertices per face\n\n */\n\n static unsigned int MakeDodecahedron(\n\n std::vector<aiVector3D>& positions,\n\n bool polygons = false);\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/StandardShapes.h", "rank": 90, "score": 49.74017989982035 }, { "content": "\tvoid Model::DrawStaticModel(Shader& shader, bool renderShadowMap, unsigned int shadowMapTextureID, bool temporary, const glm::vec3& transformScale, const glm::vec3& transformPosition)\n\n\t{\n\n\t\tfor (unsigned int i = 0; i < m_Meshes.size(); i++)\n\n\t\t{\n\n\t\t\tm_Meshes[i].Draw(shader, renderShadowMap, shadowMapTextureID);\n\n\t\t}\n\n\t}\n\n\n\n\t//Implement UUIDs / Texture Choosing\n\n\tvoid Model::RenderSettingsInEditor(glm::vec3& modelPosition, glm::vec3& modelScale) \n\n\t{\n\n\t\tImGui::Begin(m_ModelName.c_str());\n\n\t\tImGui::DragFloat3((std::string(\"Position##Model\") + ConvertUUIDToString()).c_str(), glm::value_ptr(modelPosition), 0.05f);\n\n\t\tImGui::DragFloat3((std::string(\"Rotation##\") + ConvertUUIDToString()).c_str(), glm::value_ptr(m_ModelRotation), 0.05f);\n\n\t\tImGui::DragFloat3((std::string(\"Scale##\") + ConvertUUIDToString()).c_str(), glm::value_ptr(modelScale), 0.05f);\n\n\n\n\t\tif (ImGui::CollapsingHeader((std::string(\"Textures##\" + m_ModelName).c_str())))\n\n\t\t{\n\n\t\t\tif (ImGui::Button(\"Add Diffuse\"))\n\n\t\t\t{\n", "file_path": "CrescentEngine/Models/Model.cpp", "rank": 92, "score": 49.030683296563126 }, { "content": "\n\n for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {\n\n res.texcoords[i] = op<aiVector3D,ai_real,aiVector3D>()(v0.texcoords[i],f);\n\n }\n\n for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_COLOR_SETS; ++i) {\n\n res.colors[i] = op<aiColor4D,ai_real,aiColor4D>()(v0.colors[i],f);\n\n }\n\n return res;\n\n }\n\n\n\n // ----------------------------------------------------------------------------\n\n /** This time binary arithmetics of v0 with a floating-point number */\n\n template <template <typename, typename, typename> class op> static Vertex BinaryOp(ai_real f, const Vertex& v0) {\n\n // this is a heavy task for the compiler to optimize ... *pray*\n\n\n\n Vertex res;\n\n res.position = op<ai_real,aiVector3D,aiVector3D>()(f,v0.position);\n\n res.normal = op<ai_real,aiVector3D,aiVector3D>()(f,v0.normal);\n\n res.tangent = op<ai_real,aiVector3D,aiVector3D>()(f,v0.tangent);\n\n res.bitangent = op<ai_real,aiVector3D,aiVector3D>()(f,v0.bitangent);\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/Vertex.h", "rank": 93, "score": 48.413250278182176 }, { "content": "#include \"CrescentPCH.h\"\n\n#include \"SceneEntity.h\"\n\n#include \"glm/gtc/matrix_transform.hpp\"\n\n#define GLM_ENABLE_EXPERIMENTAL\n\n#include <glm/gtx/quaternion.hpp>\n\n\n\nnamespace Crescent\n\n{\n\n\tSceneEntity::SceneEntity(const std::string& entityName, const unsigned int& entityID) : m_EntityName(entityName), m_EntityID(entityID)\n\n\t{\n\n\n\n\t}\n\n\n\n\tvoid SceneEntity::AddChildEntity(SceneEntity* childEntity)\n\n\t{\n\n\t\t//Check if this child already has a parent. If so, first remove this scene node from its current parent. Scene nodes cannot exist under multiple parents.\n\n\t\tif (childEntity->m_ParentEntity != nullptr)\n\n\t\t{\n\n\t\t\tchildEntity->m_ParentEntity->RemoveChildEntity(childEntity->m_EntityID);\n\n\t\t}\n", "file_path": "CrescentEngine/Scene/SceneEntity.cpp", "rank": 95, "score": 47.52966846815379 }, { "content": "\n\n\n\n // ----------------------------------------------------------------\n\n /** @brief Generates an octahedron\n\n *\n\n * @param positions Receives output triangles.\n\n * @return Number of vertices per face\n\n */\n\n static unsigned int MakeOctahedron(\n\n std::vector<aiVector3D>& positions);\n\n\n\n\n\n // ----------------------------------------------------------------\n\n /** @brief Generates a tetrahedron\n\n *\n\n * @param positions Receives output triangles.\n\n * @return Number of vertices per face\n\n */\n\n static unsigned int MakeTetrahedron(\n\n std::vector<aiVector3D>& positions);\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/StandardShapes.h", "rank": 96, "score": 47.30492675652871 }, { "content": " static int getMemberAlignment(const TType&, int& size, int& stride, TLayoutPacking layoutPacking, bool rowMajor);\n\n static bool improperStraddle(const TType& type, int size, int offset);\n\n static void updateOffset(const TType& parentType, const TType& memberType, int& offset, int& memberSize);\n\n static int getOffset(const TType& type, int index);\n\n static int getBlockSize(const TType& blockType);\n\n static int computeBufferReferenceTypeSize(const TType&);\n\n bool promote(TIntermOperator*);\n\n void setNanMinMaxClamp(bool setting) { nanMinMaxClamp = setting; }\n\n bool getNanMinMaxClamp() const { return nanMinMaxClamp; }\n\n\n\n void setSourceFile(const char* file) { if (file != nullptr) sourceFile = file; }\n\n const std::string& getSourceFile() const { return sourceFile; }\n\n void addSourceText(const char* text, size_t len) { sourceText.append(text, len); }\n\n const std::string& getSourceText() const { return sourceText; }\n\n const std::map<std::string, std::string>& getIncludeText() const { return includeText; }\n\n void addIncludeText(const char* name, const char* text, size_t len) { includeText[name].assign(text,len); }\n\n void addProcesses(const std::vector<std::string>& p)\n\n {\n\n for (int i = 0; i < (int)p.size(); ++i)\n\n processes.addProcess(p[i]);\n", "file_path": "Dependencies/Vulkan/include/glslang/MachineIndependent/localintermediate.h", "rank": 97, "score": 47.17848998529922 }, { "content": "public:\n\n\n\n // ------------------------------------------------------------------------------------\n\n /** Sets the input data for the SpatialSort. This replaces existing data, if any.\n\n * The new data receives new indices in ascending order.\n\n *\n\n * @param pPositions Pointer to the first position vector of the array.\n\n * @param pNumPositions Number of vectors to expect in that array.\n\n * @param pElementOffset Offset in bytes from the beginning of one vector in memory\n\n * to the beginning of the next vector.\n\n * @param pFinalize Specifies whether the SpatialSort's internal representation\n\n * is finalized after the new data has been added. Finalization is\n\n * required in order to use #FindPosition() or #GenerateMappingTable().\n\n * If you don't finalize yet, you can use #Append() to add data from\n\n * other sources.*/\n\n void Fill( const aiVector3D* pPositions, unsigned int pNumPositions,\n\n unsigned int pElementOffset,\n\n bool pFinalize = true);\n\n\n\n\n", "file_path": "CrescentEngine/Vendor/assimp/include/assimp/SpatialSort.h", "rank": 98, "score": 47.1570649972859 }, { "content": "#include \"CrescentPCH.h\"\n\n#include \"TextureCube.h\"\n\n\n\nnamespace Crescent\n\n{\n\n\tTextureCube::TextureCube()\n\n\t{\n\n\n\n\t}\n\n\n\n\tTextureCube::~TextureCube()\n\n\t{\n\n\n\n\t}\n\n\n\n\tvoid TextureCube::DefaultInitialize(unsigned int cubeFaceWidth, unsigned int cubeFaceHeight, GLenum textureCubeFormat, GLenum textureCubeDataType, bool mipmappingEnabled)\n\n\t{\n\n\t\tglGenTextures(1, &m_TextureCubeID);\n\n\n\n\t\tm_TextureCubeFaceWidth = cubeFaceWidth;\n", "file_path": "CrescentEngine/Shading/TextureCube.cpp", "rank": 99, "score": 47.12534383369912 } ]
C++
src/common/partial.hh
sergeyfilip/objectstore
e2d0c86134c46c77fb143f7198d13fab7f5b1ea5
#ifndef COMMON_PARTIAL_HH #define COMMON_PARTIAL_HH template <typename R> class BindBase { public: virtual R operator()() const = 0; virtual ~BindBase() { } virtual BindBase* clone() const = 0; }; template <typename R, typename Obj> class BindBaseM { public: virtual R operator()(Obj&) const = 0; virtual ~BindBaseM() { } virtual BindBaseM* clone() const = 0; }; template <typename R, typename F1> class BindF1Base { public: virtual R operator()(F1) const = 0; virtual ~BindF1Base() { } virtual BindF1Base* clone() const = 0; }; template <typename R> class Bind0 : public BindBase<R> { public: Bind0(R (*f)()) : f(f) { } virtual ~Bind0() { } R operator()() const { return f(); } R (*function() const)() { return f; } Bind0<R>* clone() const { return new Bind0<R>(*this); } private: R (*f)(); }; template <typename R, typename Obj> class Bind0M : public BindBaseM<R, Obj> { public: Bind0M(R (Obj::*f)()) : f(f) { } virtual ~Bind0M() { } R operator()(Obj& obj) const { return (obj.*f)(); } R (Obj::*function() const)() { return f; } Bind0M<R, Obj>* clone() const { return new Bind0M<R, Obj>(*this); } private: R (Obj::*f)(); }; template <typename R, typename F1> class Bind0F1 : public BindF1Base<R,F1> { public: Bind0F1(R (*f)(F1)) : f(f) { } virtual ~Bind0F1() { } R operator()(F1 arg) const { return f(arg); } R (*function(F1) const)() { return f; } Bind0F1<R,F1>* clone() const { return new Bind0F1<R,F1>(*this); } private: R (*f)(F1); }; template <typename R, typename A1> class Bind1 : public BindBase<R> { public: Bind1(R (*f)(A1), A1 a1) : f(f), a1(a1) { } virtual ~Bind1() { } R operator()() const { return f(a1); } R (*function() const)(A1) { return f; } Bind1<R,A1>* clone() const { return new Bind1<R,A1>(*this); } private: R (*f)(A1); A1 a1; }; template <typename R, typename Obj, typename A1> class Bind1M : public BindBaseM<R, Obj> { public: Bind1M(R (Obj::*f)(A1), A1 a1) : f(f), a1(a1) { } virtual ~Bind1M() { } R operator()(Obj& obj) const { return (obj.*f)(a1); } R (Obj::*function() const)(A1) { return f; } Bind1M<R, Obj, A1>* clone() const { return new Bind1M<R, Obj, A1>(*this); } private: R (Obj::*f)(A1); A1 a1; }; template <typename R, typename A1, typename A2> class Bind2 : public BindBase<R> { public: Bind2(R (*f)(const A1, const A2), A1 a1, A2 a2) : f(f), a1(a1), a2(a2) { } virtual ~Bind2() { } R operator()() const { return f(a1,a2); } R (*function() const)(A1, A2) { return f; } Bind2<R,A1,A2>* clone() const { return new Bind2<R,A1,A2>(*this); } private: R (*f)(A1, A2); A1 a1; A2 a2; }; template <typename R, typename Obj, typename A1, typename A2> class Bind2M : public BindBaseM<R, Obj> { public: Bind2M(R (Obj::*f)(const A1, const A2), A1 a1, A2 a2) : f(f), a1(a1), a2(a2) { } virtual ~Bind2M() { } R operator()(Obj& obj) const { return (obj.*f)(a1,a2); } R (Obj::*function() const)(A1, A2) { return f; } Bind2M<R,Obj,A1,A2>* clone() const { return new Bind2M<R,Obj,A1,A2>(*this); } private: R (Obj::*f)(A1, A2); A1 a1; A2 a2; }; template <typename R, typename A1, typename A2, typename A3> class Bind3 : public BindBase<R> { public: Bind3(R (*f)(const A1, const A2, const A3), A1 a1, A2 a2, A3 a3) : f(f), a1(a1), a2(a2), a3(a3) { } virtual ~Bind3() { } R operator()() const { return f(a1,a2,a3); } R (*function() const)(A1, A2, A3) { return f; } Bind3<R,A1,A2,A3>* clone() const { return new Bind3<R,A1,A2,A3>(*this); } private: R (*f)(A1, A2, A3); A1 a1; A2 a2; A3 a3; }; template <class InstanceT, class Out> class Closure0 : public BindBase<Out> { public: inline Closure0(InstanceT *i, Out (InstanceT::*f)()): instance(i), fun(f) {} virtual ~Closure0() { } Out operator() () const { return (instance->*fun)(); } Closure0<InstanceT,Out>* clone() const { return new Closure0<InstanceT,Out>(*this); } private: InstanceT *instance; Out (InstanceT::*fun)(); }; template <class Out> inline Bind0<Out> papply(Out (*f)()) { return Bind0<Out>(f); } template <class Out, class Obj> inline Bind0M<Out, Obj> papply(Out (Obj::*f)()) { return Bind0M<Out, Obj>(f); } template <class Out, class In> inline Bind0F1<Out,In> papply(Out (*f)(In)) { return Bind0F1<Out,In>(f); } template <class Out, class In> inline Bind1<Out,In> papply(Out (*f)(In), In in) { return Bind1<Out,In>(f, in); } template <class Out, class Obj, class In> inline Bind1M<Out, Obj, In> papply(Out (Obj::*f)(In), In in) { return Bind1M<Out, Obj, In>(f, in); } template <class Out, class In1, class In2> inline Bind2<Out,In1,In2> papply(Out (*f)(In1,In2), In1 in1, In2 in2) { return Bind2<Out,In1,In2>(f, in1, in2); } template <class Out, class Obj, class In1, class In2> inline Bind2M<Out, Obj, In1, In2> papply(Out (Obj::*f)(In1,In2), In1 in1, In2 in2) { return Bind2M<Out, Obj, In1, In2>(f, in1, in2); } template <class Out, class In1, class In2, class In3> inline Bind3<Out,In1,In2,In3> papply(Out (*f)(In1,In2,In3), In1 in1, In2 in2, In3 in3) { return Bind3<Out,In1,In2,In3>(f, in1, in2, in3); } template <class InstanceT, class Out> class Closure0c : public BindBase<Out> { public: inline Closure0c(const InstanceT *i, Out (InstanceT::*f)() const): instance(i), fun(f) {} virtual ~Closure0c() { } Out operator() () const { return (instance->*fun)(); } Closure0c<InstanceT,Out>* clone() const { return new Closure0c<InstanceT,Out>(*this); } private: const InstanceT *instance; Out (InstanceT::*fun)() const; }; template <class InstanceT, class Out, class In> class Closure1 : public BindF1Base<Out,In> { public: inline Closure1(InstanceT *i, Out (InstanceT::*f)(In)): instance(i), fun(f) {} virtual ~Closure1() { } Out operator() (In in) const { return (instance->*fun)(in); } Closure1<InstanceT,Out,In>* clone() const { return new Closure1<InstanceT,Out,In>(*this); } private: InstanceT *instance; Out (InstanceT::*fun)(In); }; template <class InstanceT, class Out, class In> class Closure1c : public BindF1Base<Out,In> { public: inline Closure1c(const InstanceT *i, Out (InstanceT::*f)(In) const): instance(i), fun(f) {} virtual ~Closure1c() { } Out operator() (In in) const { return (instance->*fun)(in); } Closure1c<InstanceT,Out,In>* clone() const { return new Closure1c<InstanceT,Out,In>(*this); } private: const InstanceT *instance; Out (InstanceT::*fun)(In) const; }; template <class InstanceT, class Out, class Bound> class Closure0B1 : public BindBase<Out> { public: template <class C> inline Closure0B1(C *i, Out (C::*f)(Bound), Bound b): instance(i), fun(f), bound(b) { } virtual ~Closure0B1() { } Out operator() () const { return (instance->*fun)(bound); } Closure0B1<InstanceT,Out,Bound>* clone() const { return new Closure0B1<InstanceT,Out,Bound>(*this); } private: InstanceT *instance; Out (InstanceT::*fun)(Bound); Bound bound; }; template <class InstanceT, class Out, class Bound> class Closure0B1c : public BindBase<Out> { public: template <class C> inline Closure0B1c(const C *i, Out (C::*f)(Bound) const, Bound b): instance(i), fun(f), bound(b) { } virtual ~Closure0B1c() { } Out operator() () const { return (instance->*fun)(bound); } Closure0B1c<InstanceT,Out,Bound>* clone() const { return new Closure0B1c<InstanceT,Out,Bound>(*this); } private: const InstanceT *instance; Out (InstanceT::*fun)(Bound) const; Bound bound; }; template <class InstanceT, class Out, class Bound1, class Bound2> class Closure0B2 : public BindBase<Out> { public: template <class C> inline Closure0B2(C *i, Out (C::*f)(Bound1,Bound2), Bound1 b1, Bound2 b2): instance(i), fun(f), bound1(b1), bound2(b2) { } virtual ~Closure0B2() { } Out operator() () const { return (instance->*fun)(bound1,bound2); } Closure0B2<InstanceT,Out,Bound1,Bound2>* clone() const { return new Closure0B2<InstanceT,Out,Bound1,Bound2>(*this); } private: InstanceT *instance; Out (InstanceT::*fun)(Bound1,Bound2); Bound1 bound1; Bound2 bound2; }; template <class InstanceT, class Out, class Bound1, class Bound2> class Closure0B2c : public BindBase<Out> { public: template <class C> inline Closure0B2c(const C *i, Out (C::*f)(Bound1,Bound2) const, Bound1 b1, Bound2 b2) : instance(i), fun(f), bound1(b1), bound2(b2) { } virtual ~Closure0B2c() { } Out operator() () const { return (instance->*fun)(bound1,bound2); } Closure0B2c<InstanceT,Out,Bound1,Bound2>* clone() const { return new Closure0B2c<InstanceT,Out,Bound1,Bound2>(*this); } private: const InstanceT *instance; Out (InstanceT::*fun)(Bound1,Bound2) const; Bound1 bound1; Bound2 bound2; }; template <class InstanceT, class Out, class Bound1, class Bound2, class Bound3> class Closure0B3c : public BindBase<Out> { public: template <class C> inline Closure0B3c(const C *i, Out (C::*f)(Bound1,Bound2,Bound3) const, Bound1 b1, Bound2 b2, Bound3 b3) : instance(i), fun(f), bound1(b1), bound2(b2), bound3(b3) { } virtual ~Closure0B3c() { } Out operator() () const { return (instance->*fun)(bound1,bound2,bound3); } Closure0B3c<InstanceT,Out,Bound1,Bound2,Bound3>* clone() const { return new Closure0B3c<InstanceT,Out,Bound1,Bound2,Bound3>(*this); } private: const InstanceT *instance; Out (InstanceT::*fun)(Bound1,Bound2,Bound3) const; Bound1 bound1; Bound2 bound2; Bound3 bound3; }; template <class C, class Out> inline Closure0c<const C,Out> papply(const C *i, Out (C::*f)() const) { return Closure0c<const C, Out>(i, f); } template <class C, class Out> inline Closure0<C,Out> papply(C *i, Out (C::*f)()) { return Closure0<C, Out>(i, f); } template <class Out, class C, class In> inline Closure1c<C,Out,In> papply(const C *i, Out (C::*f)(In) const) { return Closure1c<C, Out, In>(i, f); } template <class Out, class C, class In> inline Closure1<C,Out,In> papply(C *i, Out (C::*f)(In)) { return Closure1<C, Out, In>(i, f); } template <class Out, class C, class In> inline Closure0B1c<C,Out,In> papply(const C *i, Out (C::*f)(In) const, In in) { return Closure0B1c<C, Out, In>(i, f, in); } template <class Out, class C, class In> inline Closure0B1<C,Out,In> papply(C *i, Out (C::*f)(In), In in) { return Closure0B1<C, Out, In>(i, f, in); } template <class Out, class C, class In1, class In2> inline Closure0B2c<C,Out,In1,In2> papply(const C *i, Out (C::*f)(In1,In2) const, In1 in1, In2 in2) { return Closure0B2c<C, Out, In1,In2>(i, f, in1, in2); } template <class Out, class C, class In1, class In2> inline Closure0B2<C,Out,In1,In2> papply(C *i, Out (C::*f)(In1,In2), In1 in1, In2 in2) { return Closure0B2<C, Out, In1,In2>(i, f, in1, in2); } template <class Out, class C, class In1, class In2, class In3> inline Closure0B3c<C,Out,In1,In2,In3> papply(const C *i, Out (C::*f)(In1,In2,In3) const, In1 in1, In2 in2, In3 in3) { return Closure0B3c<C, Out, In1,In2,In3>(i, f, in1, in2, in3); } #endif
#ifndef COMMON_PARTIAL_HH #define COMMON_PARTIAL_HH template <typename R> class BindBase { public: virtual R operator()() const = 0; virtual ~BindBase() { } virtual BindBase* clone() const = 0; }; template <typename R, typename Obj> class BindBaseM { public: virtual R operator()(Obj&) const = 0; virtual ~BindBaseM() { } virtual BindBaseM* clone() const = 0; }; template <typename R, typename F1> class BindF1Base { public: virtual R operator()(F1) const = 0; virtual ~BindF1Base() { } virtual BindF1Base* clone() const = 0; }; template <typename R> class Bind0 : public BindBase<R> { public: Bind0(R (*f)()) : f(f) { } virtual ~Bind0() { } R operator()() const { return f(); } R (*function() const)() { return f; } Bind0<R>* clone() const { return new Bind0<R>(*this); } private: R (*f)(); }; template <typename R, typename Obj> class Bind0M : public BindBaseM<R, Obj> { public: Bind0M(R (Obj::*f)()) : f(f) { } virtual ~Bind0M() { } R operator()(Obj& obj) const { return (obj.*f)(); } R (Obj::*function() const)() { return f; } Bind0M<R, Obj>* clone() const { return new Bind0M<R, Obj>(*this); } private: R (Obj::*f)(); }; template <typename R, typename F1> class Bind0F1 : public BindF1Base<R,F1> { public: Bind0F1(R (*f)(F1)) : f(f) { } virtual ~Bind0F1() { } R operator()(F1 arg) const { return f(arg); } R (*function(F1) const)() { return f; } Bind0F1<R,F1>* clone() const { return new Bind0F1<R,F1>(*this); } private: R (*f)(F1); }; template <typename R, typename A1> class Bind1 : public BindBase<R> { public: Bind1(R (*f)(A1), A1 a1) : f(f), a1(a1) { } virtual ~Bind1() { } R operator()() const { return f(a1); } R (*function() const)(A1) { return f; } Bind1<R,A1>* clone() const { return new Bind1<R,A1>(*this); } private: R (*f)(A1); A1 a1; }; template <typename R, typename Obj, typename A1> class Bind1M : public BindBaseM<R, Obj> { public: Bind1M(R (Obj::*f)(A1), A1 a1) : f(f), a1(a1) { } virtual ~Bind1M() { } R operator()(Obj& obj) const { return (obj.*f)(a1); } R (Obj::*function() const)(A1) { return f; } Bind1M<R, Obj, A1>* clone() const { return new Bind1M<R, Obj, A1>(*this); } private: R (Obj::*f)(A1); A1 a1; }; template <typename R, typename A1, typename A2> class Bind2 : public BindBase<R> { public: Bind2(R (*f)(const A1, const A2), A1 a1, A2 a2) : f(f), a1(a1), a2(a2) { } virtual ~Bind2() { } R operator()() const { return f(a1,a2); } R (*function() const)(A1, A2) { return f; } Bind2<R,A1,A2>* clone() const { return new Bind2<R,A1,A2>(*this); } private: R (*f)(A1, A2); A1 a1; A2 a2; }; template <typename R, typename Obj, typename A1, typename A2> class Bind2M : public BindBaseM<R, Obj> { public: Bind2M(R (Obj::*f)(const A1, const A2), A1 a1, A2 a2) : f(f), a1(a1), a2(a2) { } virtual ~Bind2M() { } R operator()(Obj& obj) const { return (obj.*f)(a1,a2); } R (Obj::*function() const)(A1, A2) { return f; } Bind2M<R,Obj,A1,A2>* clone() const { return new Bind2M<R,Obj,A1,A2>(*this); } private: R (Obj::*f)(A1, A2); A1 a1; A2 a2; }; template <typename R, typename A1, typename A2, typename A3> class Bind3 : public BindBase<R> { public: Bind3(R (*f)(const A1, const A2, const A3), A1 a1, A2 a2, A3 a3) : f(f), a1(a1), a2(a2), a3(a3) { } virtual ~Bind3() { } R operator()() const { return f(a1,a2,a3); } R (*function() const)(A1, A2, A3) { return f; } Bind3<R,A1,A2,A3>* clone() const { return new Bind3<R,A1,A2,A3>(*this); } private: R (*f)(A1, A2, A3); A1 a1; A2 a2; A3 a3; }; template <class InstanceT, class Out> class Closure0 : public BindBase<Out> { public: inline Closure0(InstanceT *i, Out (InstanceT::*f)()): instance(i), fun(f) {} virtual ~Closure0() { } Out operator() () const { return (instance->*fun)(); } Closure0<InstanceT,Out>* clone() const { return new Closure0<InstanceT,Out>(*this); } private: InstanceT *instance; Out (InstanceT::*fun)(); }; template <class Out> inline Bind0<Out> papply(Out (*f)()) { return Bind0<Out>(f); } template <class Out, class Obj> inline Bind0M<Out, Obj> papply(Out (Obj::*f)()) { return Bind0M<Out, Obj>(f); } template <class Out, class In> inline Bind0F1<Out,In> papply(Out (*f)(In)) { return Bind0F1<Out,In>(f); } template <class Out, class In> inline Bind1<Out,In> papply(Out (*f)(In), In in) { return Bind1<Out,In>(f, in); } template <class Out, class Obj, class In> inline Bind1M<Out, Obj, I
*fun)(bound1,bound2,bound3); } Closure0B3c<InstanceT,Out,Bound1,Bound2,Bound3>* clone() const { return new Closure0B3c<InstanceT,Out,Bound1,Bound2,Bound3>(*this); } private: const InstanceT *instance; Out (InstanceT::*fun)(Bound1,Bound2,Bound3) const; Bound1 bound1; Bound2 bound2; Bound3 bound3; }; template <class C, class Out> inline Closure0c<const C,Out> papply(const C *i, Out (C::*f)() const) { return Closure0c<const C, Out>(i, f); } template <class C, class Out> inline Closure0<C,Out> papply(C *i, Out (C::*f)()) { return Closure0<C, Out>(i, f); } template <class Out, class C, class In> inline Closure1c<C,Out,In> papply(const C *i, Out (C::*f)(In) const) { return Closure1c<C, Out, In>(i, f); } template <class Out, class C, class In> inline Closure1<C,Out,In> papply(C *i, Out (C::*f)(In)) { return Closure1<C, Out, In>(i, f); } template <class Out, class C, class In> inline Closure0B1c<C,Out,In> papply(const C *i, Out (C::*f)(In) const, In in) { return Closure0B1c<C, Out, In>(i, f, in); } template <class Out, class C, class In> inline Closure0B1<C,Out,In> papply(C *i, Out (C::*f)(In), In in) { return Closure0B1<C, Out, In>(i, f, in); } template <class Out, class C, class In1, class In2> inline Closure0B2c<C,Out,In1,In2> papply(const C *i, Out (C::*f)(In1,In2) const, In1 in1, In2 in2) { return Closure0B2c<C, Out, In1,In2>(i, f, in1, in2); } template <class Out, class C, class In1, class In2> inline Closure0B2<C,Out,In1,In2> papply(C *i, Out (C::*f)(In1,In2), In1 in1, In2 in2) { return Closure0B2<C, Out, In1,In2>(i, f, in1, in2); } template <class Out, class C, class In1, class In2, class In3> inline Closure0B3c<C,Out,In1,In2,In3> papply(const C *i, Out (C::*f)(In1,In2,In3) const, In1 in1, In2 in2, In3 in3) { return Closure0B3c<C, Out, In1,In2,In3>(i, f, in1, in2, in3); } #endif
n> papply(Out (Obj::*f)(In), In in) { return Bind1M<Out, Obj, In>(f, in); } template <class Out, class In1, class In2> inline Bind2<Out,In1,In2> papply(Out (*f)(In1,In2), In1 in1, In2 in2) { return Bind2<Out,In1,In2>(f, in1, in2); } template <class Out, class Obj, class In1, class In2> inline Bind2M<Out, Obj, In1, In2> papply(Out (Obj::*f)(In1,In2), In1 in1, In2 in2) { return Bind2M<Out, Obj, In1, In2>(f, in1, in2); } template <class Out, class In1, class In2, class In3> inline Bind3<Out,In1,In2,In3> papply(Out (*f)(In1,In2,In3), In1 in1, In2 in2, In3 in3) { return Bind3<Out,In1,In2,In3>(f, in1, in2, in3); } template <class InstanceT, class Out> class Closure0c : public BindBase<Out> { public: inline Closure0c(const InstanceT *i, Out (InstanceT::*f)() const): instance(i), fun(f) {} virtual ~Closure0c() { } Out operator() () const { return (instance->*fun)(); } Closure0c<InstanceT,Out>* clone() const { return new Closure0c<InstanceT,Out>(*this); } private: const InstanceT *instance; Out (InstanceT::*fun)() const; }; template <class InstanceT, class Out, class In> class Closure1 : public BindF1Base<Out,In> { public: inline Closure1(InstanceT *i, Out (InstanceT::*f)(In)): instance(i), fun(f) {} virtual ~Closure1() { } Out operator() (In in) const { return (instance->*fun)(in); } Closure1<InstanceT,Out,In>* clone() const { return new Closure1<InstanceT,Out,In>(*this); } private: InstanceT *instance; Out (InstanceT::*fun)(In); }; template <class InstanceT, class Out, class In> class Closure1c : public BindF1Base<Out,In> { public: inline Closure1c(const InstanceT *i, Out (InstanceT::*f)(In) const): instance(i), fun(f) {} virtual ~Closure1c() { } Out operator() (In in) const { return (instance->*fun)(in); } Closure1c<InstanceT,Out,In>* clone() const { return new Closure1c<InstanceT,Out,In>(*this); } private: const InstanceT *instance; Out (InstanceT::*fun)(In) const; }; template <class InstanceT, class Out, class Bound> class Closure0B1 : public BindBase<Out> { public: template <class C> inline Closure0B1(C *i, Out (C::*f)(Bound), Bound b): instance(i), fun(f), bound(b) { } virtual ~Closure0B1() { } Out operator() () const { return (instance->*fun)(bound); } Closure0B1<InstanceT,Out,Bound>* clone() const { return new Closure0B1<InstanceT,Out,Bound>(*this); } private: InstanceT *instance; Out (InstanceT::*fun)(Bound); Bound bound; }; template <class InstanceT, class Out, class Bound> class Closure0B1c : public BindBase<Out> { public: template <class C> inline Closure0B1c(const C *i, Out (C::*f)(Bound) const, Bound b): instance(i), fun(f), bound(b) { } virtual ~Closure0B1c() { } Out operator() () const { return (instance->*fun)(bound); } Closure0B1c<InstanceT,Out,Bound>* clone() const { return new Closure0B1c<InstanceT,Out,Bound>(*this); } private: const InstanceT *instance; Out (InstanceT::*fun)(Bound) const; Bound bound; }; template <class InstanceT, class Out, class Bound1, class Bound2> class Closure0B2 : public BindBase<Out> { public: template <class C> inline Closure0B2(C *i, Out (C::*f)(Bound1,Bound2), Bound1 b1, Bound2 b2): instance(i), fun(f), bound1(b1), bound2(b2) { } virtual ~Closure0B2() { } Out operator() () const { return (instance->*fun)(bound1,bound2); } Closure0B2<InstanceT,Out,Bound1,Bound2>* clone() const { return new Closure0B2<InstanceT,Out,Bound1,Bound2>(*this); } private: InstanceT *instance; Out (InstanceT::*fun)(Bound1,Bound2); Bound1 bound1; Bound2 bound2; }; template <class InstanceT, class Out, class Bound1, class Bound2> class Closure0B2c : public BindBase<Out> { public: template <class C> inline Closure0B2c(const C *i, Out (C::*f)(Bound1,Bound2) const, Bound1 b1, Bound2 b2) : instance(i), fun(f), bound1(b1), bound2(b2) { } virtual ~Closure0B2c() { } Out operator() () const { return (instance->*fun)(bound1,bound2); } Closure0B2c<InstanceT,Out,Bound1,Bound2>* clone() const { return new Closure0B2c<InstanceT,Out,Bound1,Bound2>(*this); } private: const InstanceT *instance; Out (InstanceT::*fun)(Bound1,Bound2) const; Bound1 bound1; Bound2 bound2; }; template <class InstanceT, class Out, class Bound1, class Bound2, class Bound3> class Closure0B3c : public BindBase<Out> { public: template <class C> inline Closure0B3c(const C *i, Out (C::*f)(Bound1,Bound2,Bound3) const, Bound1 b1, Bound2 b2, Bound3 b3) : instance(i), fun(f), bound1(b1), bound2(b2), bound3(b3) { } virtual ~Closure0B3c() { } Out operator() () const { return (instance->
random
[]
C++
server/modules/routing/binlogrouter/blr_event.cc
tut-blog/MaxScale
cabd6dba0665cb8025c694acf98cffaa68d10de0
#include "blr.hh" #include <inttypes.h> #include <maxscale/alloc.h> bool blr_handle_one_event(MXS_ROUTER* instance, REP_HEADER& hdr, uint8_t* ptr, uint32_t len, int semisync) { ROUTER_INSTANCE* router = static_cast<ROUTER_INSTANCE*>(instance); router->lastEventReceived = hdr.event_type; router->lastEventTimestamp = hdr.timestamp; pthread_mutex_lock(&router->binlog_lock); if (router->trx_safe == 0 || (router->trx_safe && router->pending_transaction.state == BLRM_NO_TRANSACTION)) { router->binlog_position = router->current_pos; router->current_safe_event = router->current_pos; } pthread_mutex_unlock(&router->binlog_lock); if (router->trx_safe) { if (router->mariadb10_compat && hdr.event_type == MARIADB10_GTID_EVENT) { uint64_t n_sequence; uint32_t domainid; unsigned int flags; n_sequence = extract_field(ptr + MYSQL_HEADER_LEN + 1 + BINLOG_EVENT_HDR_LEN, 64); domainid = extract_field(ptr + MYSQL_HEADER_LEN + 1 + BINLOG_EVENT_HDR_LEN + 8, 32); flags = *(ptr + MYSQL_HEADER_LEN + 1 + BINLOG_EVENT_HDR_LEN + 8 + 4); pthread_mutex_lock(&router->binlog_lock); router->pending_transaction.standalone = flags & MARIADB_FL_STANDALONE; if (router->pending_transaction.state > BLRM_NO_TRANSACTION) { MXS_ERROR("A MariaDB 10 transaction " "is already open " "@ %lu (GTID %u-%u-%lu) and " "a new one starts @ %lu", router->binlog_position, domainid, hdr.serverid, n_sequence, router->current_pos); } router->pending_transaction.state = BLRM_TRANSACTION_START; if (router->mariadb10_gtid) { char mariadb_gtid[GTID_MAX_LEN + 1]; snprintf(mariadb_gtid, GTID_MAX_LEN, "%u-%u-%lu", domainid, hdr.serverid, n_sequence); MXS_DEBUG("MariaDB GTID received: (%s). Current file %s, pos %lu", mariadb_gtid, router->binlog_name, router->current_pos); strcpy(router->pending_transaction.gtid, mariadb_gtid); router->pending_transaction.gtid_elms.domain_id = domainid; router->pending_transaction.gtid_elms.server_id = hdr.serverid; router->pending_transaction.gtid_elms.seq_no = n_sequence; } router->pending_transaction.start_pos = router->current_pos; router->pending_transaction.end_pos = 0; pthread_mutex_unlock(&router->binlog_lock); } if (hdr.event_type == QUERY_EVENT) { char* statement_sql; int db_name_len, var_block_len, statement_len; db_name_len = ptr[MYSQL_HEADER_LEN + 1 + BINLOG_EVENT_HDR_LEN + 4 + 4]; var_block_len = ptr[MYSQL_HEADER_LEN + 1 + BINLOG_EVENT_HDR_LEN + 4 + 4 + 1 + 2]; statement_len = len - (MYSQL_HEADER_LEN + 1 + BINLOG_EVENT_HDR_LEN + 4 + 4 + 1 + 2 + 2 \ + var_block_len + 1 + db_name_len); statement_sql = static_cast<char*>(MXS_CALLOC(1, statement_len + 1)); MXS_ABORT_IF_NULL(statement_sql); memcpy(statement_sql, (char*)ptr + MYSQL_HEADER_LEN + 1 + BINLOG_EVENT_HDR_LEN + 4 + 4 + 1 + 2 + 2 \ + var_block_len + 1 + db_name_len, statement_len); pthread_mutex_lock(&router->binlog_lock); if (strncmp(statement_sql, "BEGIN", 5) == 0) { if (router->pending_transaction.state > BLRM_NO_TRANSACTION) { MXS_ERROR("A transaction is already open " "@ %lu and a new one starts @ %lu", router->binlog_position, router->current_pos); } router->pending_transaction.state = BLRM_TRANSACTION_START; router->pending_transaction.start_pos = router->current_pos; router->pending_transaction.end_pos = 0; } if (strncmp(statement_sql, "COMMIT", 6) == 0) { router->pending_transaction.state = BLRM_COMMIT_SEEN; } if (router->pending_transaction.state > BLRM_NO_TRANSACTION && router->pending_transaction.standalone) { router->pending_transaction.state = BLRM_STANDALONE_SEEN; } pthread_mutex_unlock(&router->binlog_lock); MXS_FREE(statement_sql); } if (hdr.event_type == XID_EVENT) { pthread_mutex_lock(&router->binlog_lock); if (router->pending_transaction.state >= BLRM_TRANSACTION_START) { router->pending_transaction.state = BLRM_XID_EVENT_SEEN; } pthread_mutex_unlock(&router->binlog_lock); } } int event_limit = router->mariadb10_compat ? MAX_EVENT_TYPE_MARIADB10 : MAX_EVENT_TYPE; if (hdr.event_type <= event_limit) { router->stats.events[hdr.event_type]++; } else { char errmsg[BINLOG_ERROR_MSG_LEN + 1]; sprintf(errmsg, "Event type [%d] not supported yet. " "Check master server configuration and " "disable any new feature. " "Replication from master has been stopped.", hdr.event_type); MXS_ERROR("%s", errmsg); pthread_mutex_lock(&router->lock); char* old_errmsg = router->m_errmsg; router->m_errmsg = MXS_STRDUP_A(errmsg); router->m_errno = 1235; router->master_state = BLRM_SLAVE_STOPPED; router->stats.n_binlog_errors++; pthread_mutex_unlock(&router->lock); MXS_FREE(old_errmsg); blr_master_close(router); return false; } if (hdr.event_type == FORMAT_DESCRIPTION_EVENT && hdr.next_pos == 0) { router->stats.n_fakeevents++; MXS_DEBUG("Replication Fake FORMAT_DESCRIPTION_EVENT event. " "Binlog %s @ %lu.", router->binlog_name, router->current_pos); } else { if (hdr.event_type == HEARTBEAT_EVENT) { #ifdef SHOW_EVENTS printf("Replication heartbeat\n"); #endif MXS_DEBUG("Replication heartbeat. " "Binlog %s @ %lu.", router->binlog_name, router->current_pos); router->stats.n_heartbeats++; if (router->pending_transaction.state > BLRM_NO_TRANSACTION) { router->stats.lastReply = time(0); } } else if (hdr.flags != LOG_EVENT_ARTIFICIAL_F) { if (hdr.event_type == ROTATE_EVENT) { pthread_mutex_lock(&router->binlog_lock); router->rotating = 1; pthread_mutex_unlock(&router->binlog_lock); } uint32_t offset = MYSQL_HEADER_LEN + 1; if (blr_write_binlog_record(router, &hdr, len - offset, ptr + offset) == 0) { blr_master_close(router); blr_start_master_in_main(router); return false; } if (hdr.event_type == ROTATE_EVENT) { if (!blr_rotate_event(router, ptr + offset, &hdr)) { blr_master_close(router); blr_start_master_in_main(router); return false; } } if (router->master_semi_sync != MASTER_SEMISYNC_NOT_AVAILABLE && semisync == BLR_MASTER_SEMI_SYNC_ACK_REQ) { MXS_DEBUG("%s: binlog record in file %s, pos %lu has " "SEMI_SYNC_ACK_REQ and needs a Semi-Sync ACK packet to " "be sent to the master server [%s]:%d", router->service->name, router->binlog_name, router->current_pos, router->service->dbref->server->address, router->service->dbref->server->port); blr_send_semisync_ack(router, hdr.next_pos); semisync = 0; } pthread_mutex_lock(&router->binlog_lock); if (router->trx_safe == 0 || (router->trx_safe && router->pending_transaction.state == BLRM_NO_TRANSACTION)) { router->binlog_position = router->current_pos; router->current_safe_event = router->last_event_pos; pthread_mutex_unlock(&router->binlog_lock); blr_notify_all_slaves(router); } else { if (router->pending_transaction.state > BLRM_TRANSACTION_START) { if (router->mariadb10_compat) { router->pending_transaction.end_pos = router->current_pos; if (router->mariadb10_compat && router->mariadb10_gtid) { strcpy(router->last_mariadb_gtid, router->pending_transaction.gtid); blr_save_mariadb_gtid(router); } } pthread_mutex_unlock(&router->binlog_lock); blr_notify_all_slaves(router); pthread_mutex_lock(&router->binlog_lock); router->binlog_position = router->current_pos; router->pending_transaction.state = BLRM_NO_TRANSACTION; router->pending_transaction.standalone = false; pthread_mutex_unlock(&router->binlog_lock); } else { pthread_mutex_unlock(&router->binlog_lock); } } } else { router->stats.n_artificial++; MXS_DEBUG("Artificial event not written " "to disk or distributed. " "Type 0x%x, Length %d, Binlog " "%s @ %lu.", hdr.event_type, hdr.event_size, router->binlog_name, router->current_pos); ptr += MYSQL_HEADER_LEN + 1; if (hdr.event_type == ROTATE_EVENT) { if (!blr_handle_fake_rotate(router, &hdr, ptr)) { blr_master_close(router); blr_start_master_in_main(router); return false; } MXS_INFO("Fake ROTATE_EVENT received: " "binlog file %s, pos %" PRIu64 "", router->binlog_name, router->current_pos); } else if (hdr.event_type == MARIADB10_GTID_GTID_LIST_EVENT) { blr_handle_fake_gtid_list(router, &hdr, ptr); } } } return true; }
#include "blr.hh" #include <inttypes.h> #include <maxscale/alloc.h> bool blr_handle_one_event(MXS_ROUTER* instance, REP_HEADER& hdr, uint8_t* ptr, uint32_t len, int semisync) { ROUTER_INSTANCE* router = static_cast<ROUTER_INSTANCE*>(instance); router->lastEventReceived = hdr.event_type; router->lastEventTimestamp = hdr.timestamp; pthread_mutex_lock(&router->binlog_lock); if (router->trx_safe == 0 || (router->trx_safe && router->pending_transaction.state == BLRM_NO_TRANSACTION)) { router->binlog_position = router->current_pos; router->current_safe_event = router->current_pos; } pthread_mutex_unlock(&router->binlog_lock); if (router->trx_safe) { if (router->mariadb10_compat && hdr.event_type == MARIADB10_GTID_EVENT) { uint64_t n_sequence; uint32_t domainid; unsigned int flags; n_sequence = extract_field(ptr + MYSQL_HEADER_LEN + 1 + BINLOG_EVENT_HDR_LEN, 64); domainid = extract_field(ptr + MYSQL_HEADER_LEN + 1 + BINLOG_EVENT_HDR_LEN + 8, 32); flags = *(ptr + MYSQL_HEADER_LEN + 1 + BINLOG_EVENT_HDR_LEN + 8 + 4); pthread_mutex_lock(&router->binlog_lock); router->pending_transaction.standalone = flags & MARIADB_FL_STANDALONE; if (router->pending_transaction.state > BLRM_NO_TRANSACTION) { MXS_ERROR("A MariaDB 10 transaction " "is already open " "@ %lu (GTID %u-%u-%lu) and " "a new one starts @ %lu", router->binlog_position, domainid, hdr.serverid, n_sequence, router->current_pos); } router->pending_transaction.state = BLRM_TRANSACTION_START; if (router->mariadb10_gtid) { char mariadb_gtid[GTID_MAX_LEN + 1]; snprintf(mariadb_gtid, GTID_MAX_LEN, "%u-%u-%lu", domainid, hdr.serverid, n_sequence); MXS_DEBUG("MariaDB GTID received: (%s). Current file %s, pos %lu", mariadb_gtid, router->binlog_name, router->current_pos); strcpy(router->pending_transaction.gtid, mariadb_gtid); router->pending_transaction.gtid_elms.domain_id = domainid; router->pending_transaction.gtid_elms.server_id = hdr.serverid; router->pending_transaction.gtid_elms.seq_no = n_sequence; } router->pending_transaction.start_pos = router->current_pos; router->pending_transaction.end_pos = 0; pthread_mutex_unlock(&router->binlog_lock); } if (hdr.event_type == QUERY_EVENT) { char* statement_sql; int db_name_len, var_block_len, statement_len; db_name_len = ptr[MYSQL_HEADER_LEN + 1 + BINLOG_EVENT_HDR_LEN + 4 + 4]; var_block_len = ptr[MYSQL_HEADER_LEN + 1 + BINLOG_EVENT_HDR_LEN + 4 + 4 + 1 + 2]; statement_len = len - (MYSQL_HEADER_LEN + 1 + BINLOG_EVENT_HDR_LEN + 4 + 4 + 1 + 2 + 2 \ + var_block_len + 1 + db_name_len); statement_sql = static_cast<char*>(MXS_CALLOC(1, statement_len + 1)); MXS_ABORT_IF_NULL(statement_sql); memcpy(statement_sql, (char*)ptr + MYSQL_HEADER_LEN + 1 + BINLOG_EVENT_HDR_LEN + 4 + 4 + 1 + 2 + 2 \ + var_block_len + 1 + db_name_len, statement_len); pthread_mutex_lock(&router->binlog_lock);
if (strncmp(statement_sql, "COMMIT", 6) == 0) { router->pending_transaction.state = BLRM_COMMIT_SEEN; } if (router->pending_transaction.state > BLRM_NO_TRANSACTION && router->pending_transaction.standalone) { router->pending_transaction.state = BLRM_STANDALONE_SEEN; } pthread_mutex_unlock(&router->binlog_lock); MXS_FREE(statement_sql); } if (hdr.event_type == XID_EVENT) { pthread_mutex_lock(&router->binlog_lock); if (router->pending_transaction.state >= BLRM_TRANSACTION_START) { router->pending_transaction.state = BLRM_XID_EVENT_SEEN; } pthread_mutex_unlock(&router->binlog_lock); } } int event_limit = router->mariadb10_compat ? MAX_EVENT_TYPE_MARIADB10 : MAX_EVENT_TYPE; if (hdr.event_type <= event_limit) { router->stats.events[hdr.event_type]++; } else { char errmsg[BINLOG_ERROR_MSG_LEN + 1]; sprintf(errmsg, "Event type [%d] not supported yet. " "Check master server configuration and " "disable any new feature. " "Replication from master has been stopped.", hdr.event_type); MXS_ERROR("%s", errmsg); pthread_mutex_lock(&router->lock); char* old_errmsg = router->m_errmsg; router->m_errmsg = MXS_STRDUP_A(errmsg); router->m_errno = 1235; router->master_state = BLRM_SLAVE_STOPPED; router->stats.n_binlog_errors++; pthread_mutex_unlock(&router->lock); MXS_FREE(old_errmsg); blr_master_close(router); return false; } if (hdr.event_type == FORMAT_DESCRIPTION_EVENT && hdr.next_pos == 0) { router->stats.n_fakeevents++; MXS_DEBUG("Replication Fake FORMAT_DESCRIPTION_EVENT event. " "Binlog %s @ %lu.", router->binlog_name, router->current_pos); } else { if (hdr.event_type == HEARTBEAT_EVENT) { #ifdef SHOW_EVENTS printf("Replication heartbeat\n"); #endif MXS_DEBUG("Replication heartbeat. " "Binlog %s @ %lu.", router->binlog_name, router->current_pos); router->stats.n_heartbeats++; if (router->pending_transaction.state > BLRM_NO_TRANSACTION) { router->stats.lastReply = time(0); } } else if (hdr.flags != LOG_EVENT_ARTIFICIAL_F) { if (hdr.event_type == ROTATE_EVENT) { pthread_mutex_lock(&router->binlog_lock); router->rotating = 1; pthread_mutex_unlock(&router->binlog_lock); } uint32_t offset = MYSQL_HEADER_LEN + 1; if (blr_write_binlog_record(router, &hdr, len - offset, ptr + offset) == 0) { blr_master_close(router); blr_start_master_in_main(router); return false; } if (hdr.event_type == ROTATE_EVENT) { if (!blr_rotate_event(router, ptr + offset, &hdr)) { blr_master_close(router); blr_start_master_in_main(router); return false; } } if (router->master_semi_sync != MASTER_SEMISYNC_NOT_AVAILABLE && semisync == BLR_MASTER_SEMI_SYNC_ACK_REQ) { MXS_DEBUG("%s: binlog record in file %s, pos %lu has " "SEMI_SYNC_ACK_REQ and needs a Semi-Sync ACK packet to " "be sent to the master server [%s]:%d", router->service->name, router->binlog_name, router->current_pos, router->service->dbref->server->address, router->service->dbref->server->port); blr_send_semisync_ack(router, hdr.next_pos); semisync = 0; } pthread_mutex_lock(&router->binlog_lock); if (router->trx_safe == 0 || (router->trx_safe && router->pending_transaction.state == BLRM_NO_TRANSACTION)) { router->binlog_position = router->current_pos; router->current_safe_event = router->last_event_pos; pthread_mutex_unlock(&router->binlog_lock); blr_notify_all_slaves(router); } else { if (router->pending_transaction.state > BLRM_TRANSACTION_START) { if (router->mariadb10_compat) { router->pending_transaction.end_pos = router->current_pos; if (router->mariadb10_compat && router->mariadb10_gtid) { strcpy(router->last_mariadb_gtid, router->pending_transaction.gtid); blr_save_mariadb_gtid(router); } } pthread_mutex_unlock(&router->binlog_lock); blr_notify_all_slaves(router); pthread_mutex_lock(&router->binlog_lock); router->binlog_position = router->current_pos; router->pending_transaction.state = BLRM_NO_TRANSACTION; router->pending_transaction.standalone = false; pthread_mutex_unlock(&router->binlog_lock); } else { pthread_mutex_unlock(&router->binlog_lock); } } } else { router->stats.n_artificial++; MXS_DEBUG("Artificial event not written " "to disk or distributed. " "Type 0x%x, Length %d, Binlog " "%s @ %lu.", hdr.event_type, hdr.event_size, router->binlog_name, router->current_pos); ptr += MYSQL_HEADER_LEN + 1; if (hdr.event_type == ROTATE_EVENT) { if (!blr_handle_fake_rotate(router, &hdr, ptr)) { blr_master_close(router); blr_start_master_in_main(router); return false; } MXS_INFO("Fake ROTATE_EVENT received: " "binlog file %s, pos %" PRIu64 "", router->binlog_name, router->current_pos); } else if (hdr.event_type == MARIADB10_GTID_GTID_LIST_EVENT) { blr_handle_fake_gtid_list(router, &hdr, ptr); } } } return true; }
if (strncmp(statement_sql, "BEGIN", 5) == 0) { if (router->pending_transaction.state > BLRM_NO_TRANSACTION) { MXS_ERROR("A transaction is already open " "@ %lu and a new one starts @ %lu", router->binlog_position, router->current_pos); } router->pending_transaction.state = BLRM_TRANSACTION_START; router->pending_transaction.start_pos = router->current_pos; router->pending_transaction.end_pos = 0; }
if_condition
[ { "content": "#define GTID_MAX_LEN 64\n\n\n", "file_path": "include/maxscale/mysql_binlog.h", "rank": 0, "score": 229626.218827728 }, { "content": " struct mxs_router* router_instance; /**< The router instance for this\n", "file_path": "include/maxscale/service.h", "rank": 1, "score": 188639.13285474153 }, { "content": "#define MXS_JSON_PTR_ROUTER \"/data/attributes/router\"\n", "file_path": "include/maxscale/config.h", "rank": 2, "score": 182077.49988878728 }, { "content": " SERV_LISTENER* current;\n", "file_path": "include/maxscale/listener.h", "rank": 3, "score": 175439.4472083053 }, { "content": " struct mxs_router_object* router; /**< The router we are using */\n", "file_path": "include/maxscale/service.h", "rank": 4, "score": 175425.4727506644 }, { "content": " void* start; /*< Start of the valid data */\n", "file_path": "include/maxscale/buffer.h", "rank": 5, "score": 175421.33952414093 }, { "content": "class Router : public MXS_ROUTER\n\n{\n\npublic:\n\n\n\n // The default configure entry point, does nothing and always fails\n\n bool configure(MXS_CONFIG_PARAMETER* param)\n\n {\n\n return false;\n\n }\n\n\n\n static MXS_ROUTER* createInstance(SERVICE* pService, MXS_CONFIG_PARAMETER* params)\n\n {\n\n RouterType* pRouter = NULL;\n\n\n\n MXS_EXCEPTION_GUARD(pRouter = RouterType::create(pService, params));\n\n\n\n return pRouter;\n\n }\n\n\n\n static MXS_ROUTER_SESSION* newSession(MXS_ROUTER* pInstance, MXS_SESSION* pSession)\n", "file_path": "include/maxscale/router.hh", "rank": 6, "score": 173743.5253032418 }, { "content": " unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */\n", "file_path": "query_classifier/qc_sqlite/sqlite-src-3110100/src/sqliteInt.h", "rank": 7, "score": 170288.028006609 }, { "content": " u8 openFlags; /* Flags to sqlite3BtreeOpen() */\n", "file_path": "query_classifier/qc_sqlite/sqlite-src-3110100/src/btreeInt.h", "rank": 8, "score": 170288.028006609 }, { "content": "#define MYSQL_HEADER_LEN 4\n", "file_path": "include/maxscale/protocol/mysql.h", "rank": 9, "score": 168777.80137789197 }, { "content": "int sqlite3Utf8CharLen(const char *pData, int nByte);\n", "file_path": "query_classifier/qc_sqlite/sqlite-src-3110100/src/sqliteInt.h", "rank": 10, "score": 164958.52580845327 }, { "content": "Bitmask sqlite3WhereCodeOneLoopStart(\n\n WhereInfo *pWInfo, /* Complete information about the WHERE clause */\n\n int iLevel, /* Which level of pWInfo->a[] should be coded */\n\n Bitmask notReady /* Which tables are currently available */\n", "file_path": "query_classifier/qc_sqlite/sqlite-src-3110100/src/whereInt.h", "rank": 11, "score": 164945.6669187926 }, { "content": "struct CloserTraits<FILE*>\n\n{\n\n static void close_if(FILE* pFile)\n\n {\n\n if (pFile)\n\n {\n\n fclose(pFile);\n\n }\n\n }\n\n\n\n static void reset(FILE*& pFile)\n\n {\n\n pFile = NULL;\n\n }\n\n};\n\n\n\n/* Helper type for Registry. Must be specialized for each EntryType. The types\n\n * listed below are just examples and will not compile. */\n\ntemplate<typename EntryType>\n", "file_path": "include/maxscale/utils.hh", "rank": 12, "score": 160285.27757234784 }, { "content": "u8 sqlite3VdbeOneByteSerialTypeLen(u8);\n", "file_path": "query_classifier/qc_sqlite/sqlite-src-3110100/src/vdbeInt.h", "rank": 13, "score": 157529.87066664212 }, { "content": "CREATE TABLE myCity (a int, b char(?));\n", "file_path": "server/core/test/canonical_tests/expected.sql", "rank": 14, "score": 153472.98421770602 }, { "content": "CREATE TABLE myCity (a int, b char(20));\n", "file_path": "server/core/test/canonical_tests/input.sql", "rank": 15, "score": 150399.76239783427 }, { "content": "class RouterSession : public MXS_ROUTER_SESSION\n\n{\n\npublic:\n\n /**\n\n * The RouterSession instance will be deleted when a client session\n\n * has terminated. Will be called only after @c close() has been called.\n\n */\n\n ~RouterSession();\n\n\n\n /**\n\n * Called when a client session has been closed.\n\n */\n\n void close();\n\n\n\n /**\n\n * Called when a packet being is routed to the backend. The router should\n\n * forward the packet to the appropriate server(s).\n\n *\n\n * @param pPacket A client packet.\n\n */\n", "file_path": "include/maxscale/router.hh", "rank": 16, "score": 147200.90764658948 }, { "content": "\n\n static void destroyInstance(MXS_ROUTER* pInstance)\n\n {\n\n RouterType* pRouter = static_cast<RouterType*>(pInstance);\n\n\n\n MXS_EXCEPTION_GUARD(delete pRouter);\n\n }\n\n\n\n static bool configure(MXS_ROUTER* pInstance, MXS_CONFIG_PARAMETER* param)\n\n {\n\n RouterType* pRouter = static_cast<RouterType*>(pInstance);\n\n bool rval = false;\n\n MXS_EXCEPTION_GUARD(rval = pRouter->configure(param));\n\n return rval;\n\n }\n\n\n\n static MXS_ROUTER_OBJECT s_object;\n\n\n\nprotected:\n\n Router(SERVICE* pService)\n", "file_path": "include/maxscale/router.hh", "rank": 17, "score": 140813.8684391705 }, { "content": " GWBUF* pMessage,\n\n DCB* pProblem,\n\n mxs_error_action_t action,\n\n bool* pSuccess)\n\n {\n\n RouterSessionType* pRouter_session = static_cast<RouterSessionType*>(pData);\n\n\n\n MXS_EXCEPTION_GUARD(pRouter_session->handleError(pMessage, pProblem, action, pSuccess));\n\n }\n\n\n\n static uint64_t getCapabilities(MXS_ROUTER* pInstance)\n\n {\n\n uint64_t rv = 0;\n\n\n\n RouterType* pRouter = static_cast<RouterType*>(pInstance);\n\n\n\n MXS_EXCEPTION_GUARD(rv = pRouter->getCapabilities());\n\n\n\n return rv;\n\n }\n", "file_path": "include/maxscale/router.hh", "rank": 18, "score": 140810.00852005227 }, { "content": " : m_pService(pService)\n\n {\n\n }\n\n\n\n SERVICE* m_pService;\n\n};\n\n\n\n\n\ntemplate<class RouterType, class RouterSessionType>\n\nMXS_ROUTER_OBJECT Router<RouterType, RouterSessionType>::s_object =\n\n{\n\n &Router<RouterType, RouterSessionType>::createInstance,\n\n &Router<RouterType, RouterSessionType>::newSession,\n\n &Router<RouterType, RouterSessionType>::closeSession,\n\n &Router<RouterType, RouterSessionType>::freeSession,\n\n &Router<RouterType, RouterSessionType>::routeQuery,\n\n &Router<RouterType, RouterSessionType>::diagnostics,\n\n &Router<RouterType, RouterSessionType>::diagnostics_json,\n\n &Router<RouterType, RouterSessionType>::clientReply,\n\n &Router<RouterType, RouterSessionType>::handleError,\n\n &Router<RouterType, RouterSessionType>::getCapabilities,\n\n &Router<RouterType, RouterSessionType>::destroyInstance,\n\n &Router<RouterType, RouterSessionType>::configure,\n\n};\n\n}\n", "file_path": "include/maxscale/router.hh", "rank": 19, "score": 140808.0764461074 }, { "content": " {\n\n RouterType* pRouter = static_cast<RouterType*>(pInstance);\n\n RouterSessionType* pRouter_session;\n\n\n\n MXS_EXCEPTION_GUARD(pRouter_session = pRouter->newSession(pSession));\n\n\n\n return pRouter_session;\n\n }\n\n\n\n static void closeSession(MXS_ROUTER*, MXS_ROUTER_SESSION* pData)\n\n {\n\n RouterSessionType* pRouter_session = static_cast<RouterSessionType*>(pData);\n\n\n\n MXS_EXCEPTION_GUARD(pRouter_session->close());\n\n }\n\n\n\n static void freeSession(MXS_ROUTER*, MXS_ROUTER_SESSION* pData)\n\n {\n\n RouterSessionType* pRouter_session = static_cast<RouterSessionType*>(pData);\n\n\n", "file_path": "include/maxscale/router.hh", "rank": 20, "score": 140807.95739321483 }, { "content": "/*\n\n * Copyright (c) 2018 MariaDB Corporation Ab\n\n *\n\n * Use of this software is governed by the Business Source License included\n\n * in the LICENSE.TXT file and at www.mariadb.com/bsl11.\n\n *\n\n * Change Date: 2022-01-01\n\n *\n\n * On the date above, in accordance with the Business Source License, use\n\n * of this software will be governed by version 2 or later of the General\n\n * Public License.\n\n */\n\n#pragma once\n\n\n\n#include <maxscale/ccdefs.hh>\n\n#include <maxscale/router.h>\n\n\n\nnamespace maxscale\n\n{\n\n\n", "file_path": "include/maxscale/router.hh", "rank": 21, "score": 140807.80497001845 }, { "content": " static json_t* diagnostics_json(const MXS_ROUTER* pInstance)\n\n {\n\n const RouterType* pRouter = static_cast<const RouterType*>(pInstance);\n\n\n\n json_t* rval = NULL;\n\n\n\n MXS_EXCEPTION_GUARD(rval = pRouter->diagnostics_json());\n\n\n\n return rval;\n\n }\n\n\n\n static void clientReply(MXS_ROUTER*, MXS_ROUTER_SESSION* pData, GWBUF* pPacket, DCB* pBackend)\n\n {\n\n RouterSessionType* pRouter_session = static_cast<RouterSessionType*>(pData);\n\n\n\n MXS_EXCEPTION_GUARD(pRouter_session->clientReply(pPacket, pBackend));\n\n }\n\n\n\n static void handleError(MXS_ROUTER* pInstance,\n\n MXS_ROUTER_SESSION* pData,\n", "file_path": "include/maxscale/router.hh", "rank": 22, "score": 140806.61578757138 }, { "content": " *\n\n * @code\n\n * class MyRouterSession : public maxscale::RouterSession\n\n * {\n\n * // Override the relevant functions.\n\n * };\n\n *\n\n * class MyRouter : public maxscale::Router<MyRouter, MyRouterSession>\n\n * {\n\n * public:\n\n * static MyRouter* create(SERVICE* pService, MXS_CONFIG_PARAMETER* params);\n\n *\n\n * MyRouterSession* newSession(MXS_SESSION* pSession);\n\n *\n\n * void diagnostics(DCB* pDcb);\n\n * uint64_t getCapabilities();\n\n * };\n\n * @endcode\n\n *\n\n * The concrete router class must implement the methods @c create, @c newSession,\n", "file_path": "include/maxscale/router.hh", "rank": 23, "score": 140806.36927028946 }, { "content": " MXS_EXCEPTION_GUARD(delete pRouter_session);\n\n }\n\n\n\n static int32_t routeQuery(MXS_ROUTER*, MXS_ROUTER_SESSION* pData, GWBUF* pPacket)\n\n {\n\n RouterSessionType* pRouter_session = static_cast<RouterSessionType*>(pData);\n\n\n\n int32_t rv = 0;\n\n MXS_EXCEPTION_GUARD(rv = pRouter_session->routeQuery(pPacket));\n\n\n\n return rv;\n\n }\n\n\n\n static void diagnostics(MXS_ROUTER* pInstance, DCB* pDcb)\n\n {\n\n RouterType* pRouter = static_cast<RouterType*>(pInstance);\n\n\n\n MXS_EXCEPTION_GUARD(pRouter->diagnostics(pDcb));\n\n }\n\n\n", "file_path": "include/maxscale/router.hh", "rank": 24, "score": 140805.91049257296 }, { "content": " mxs_error_action_t action,\n\n bool* pSuccess);\n\n\n\nprotected:\n\n RouterSession(MXS_SESSION* pSession);\n\n\n\nprotected:\n\n MXS_SESSION* m_pSession; /*< The MXS_SESSION this router session is associated with. */\n\n};\n\n\n\n\n\n/**\n\n * @class Router router.hh <maxscale/router.hh>\n\n *\n\n * An instantiation of the Router template is used for creating a router.\n\n * Router is an example of the \"Curiously recurring template pattern\"\n\n * https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern\n\n * that is used for compile time polymorfism.\n\n *\n\n * The typical way for using the template is as follows:\n", "file_path": "include/maxscale/router.hh", "rank": 25, "score": 140804.14158809817 }, { "content": "/**\n\n * @class RouterSession router.hh <maxscale/router.hh>\n\n *\n\n * RouterSession is a base class for router sessions. A concrete router session\n\n * class should be derived from this class and override all relevant functions.\n\n *\n\n * Note that even though this class is intended to be derived from, no functions\n\n * are virtual. That is by design, as the class will be used in a context where\n\n * the concrete class is known. That is, there is no need for the virtual mechanism.\n\n */\n", "file_path": "include/maxscale/router.hh", "rank": 26, "score": 140800.00008892157 }, { "content": " * @c diagnostics and @c getCapabilities, with the prototypes as shown above.\n\n *\n\n * The plugin function @c GetModuleObject is then implemented as follows:\n\n *\n\n * @code\n\n * extern \"C\" MXS_MODULE* MXS_CREATE_MODULE()\n\n * {\n\n * static MXS_MODULE module_object =\n\n * {\n\n * ...\n\n * &MyRouter::s_object,\n\n * ...\n\n * };\n\n *\n\n * return &module_object;\n\n * }\n\n * @endcode\n\n */\n\ntemplate<class RouterType, class RouterSessionType>\n", "file_path": "include/maxscale/router.hh", "rank": 27, "score": 140799.01015028625 }, { "content": " int32_t routeQuery(GWBUF* pPacket);\n\n\n\n /**\n\n * Called when a packet is routed to the client. The router should\n\n * forward the packet to the client using `MXS_SESSION_ROUTE_REPLY`.\n\n *\n\n * @param pPacket A client packet.\n\n * @param pBackend The backend the packet is coming from.\n\n */\n\n void clientReply(GWBUF* pPacket, DCB* pBackend);\n\n\n\n /**\n\n *\n\n * @param pMessage The rror message.\n\n * @param pProblem The DCB on which the error occurred.\n\n * @param action The context.\n\n * @param pSuccess On output, if false, the session will be terminated.\n\n */\n\n void handleError(GWBUF* pMessage,\n\n DCB* pProblem,\n", "file_path": "include/maxscale/router.hh", "rank": 28, "score": 140795.57654886396 }, { "content": "/*\n\n * Copyright (c) 2018 MariaDB Corporation Ab\n\n *\n\n * Use of this software is governed by the Business Source License included\n\n * in the LICENSE.TXT file and at www.mariadb.com/bsl11.\n\n *\n\n * Change Date: 2022-01-01\n\n *\n\n * On the date above, in accordance with the Business Source License, use\n\n * of this software will be governed by version 2 or later of the General\n\n * Public License.\n\n */\n\n#pragma once\n\n\n\n#include <maxscale/ccdefs.hh>\n\n#include <mysql.h>\n\n#include <map>\n\n#include <string>\n\n#include <vector>\n\n\n\nnamespace maxscale\n\n{\n\n\n\nnamespace disk\n\n{\n\n\n\n/**\n\n * The size information of a particular disk.\n\n */\n", "file_path": "include/maxscale/mariadb.hh", "rank": 29, "score": 140792.04947932548 }, { "content": " * @param pMysql A valid handle to some server.\n\n * @param pInfo [out] Filled with disk space information, ordered by disk.\n\n *\n\n * @return 0 if successful.\n\n *\n\n * @attn If the function returns a non-zero value and @c mysql_errno(pMysql)\n\n * subsequently returns ER_UNKNOWN_TABLE(1109) then either the server\n\n * version is too old or the plugin @c DISKS has not been installed.\n\n */\n\nint get_info_by_disk(MYSQL* pMysql, std::map<std::string, disk::SizesAndPaths>* pInfo);\n\n}\n\n}\n", "file_path": "include/maxscale/mariadb.hh", "rank": 30, "score": 140784.2888169133 }, { "content": " * The information is obtained by accessing the @c information_schema.disks table,\n\n * which is available from 10.1.32, 10.2.14 and 10.3.6 onwards.\n\n *\n\n * @param pMysql A valid handle to some server.\n\n * @param pInfo [out] Filled with disk space information, ordered by path.\n\n *\n\n * @return 0 if successful.\n\n *\n\n * @attn If the function returns a non-zero value and @c mysql_errno(pMysql)\n\n * subsequently returns ER_UNKNOWN_TABLE(1109) then either the server\n\n * version is too old or the plugin @c DISKS has not been installed.\n\n */\n\nint get_info_by_path(MYSQL* pMysql, std::map<std::string, disk::SizesAndName>* pInfo);\n\n\n\n/**\n\n * @brief Get disk space information of a server.\n\n *\n\n * The information is obtained by accessing the @c information_schema.disks table,\n\n * which is available from 10.1.32, 10.2.14 and 10.3.6 onwards.\n\n *\n", "file_path": "include/maxscale/mariadb.hh", "rank": 31, "score": 140783.52661144175 }, { "content": " {\n\n return m_name;\n\n }\n\n\n\nprivate:\n\n std::string m_name;\n\n};\n\n\n\n/**\n\n * The size information of a particular disk, and the paths\n\n * on which that disk has been mounted.\n\n */\n", "file_path": "include/maxscale/mariadb.hh", "rank": 32, "score": 140779.8461484731 }, { "content": " * The available amount of space to non-root users.\n\n *\n\n * @attn As the reported size is what is available to non-root users,\n\n * @c available may be smaller than @total - @used.\n\n *\n\n * @return The size of the available amount of space of the disk in bytes.\n\n */\n\n int64_t available() const\n\n {\n\n return m_available;\n\n }\n\n\n\nprivate:\n\n int64_t m_total;\n\n int64_t m_used;\n\n int64_t m_available;\n\n};\n\n\n\n/**\n\n * The size information of a particular named disk.\n\n */\n", "file_path": "include/maxscale/mariadb.hh", "rank": 33, "score": 140779.8461484731 }, { "content": " {\n\n return m_paths;\n\n }\n\n\n\n void add_path(const std::string path)\n\n {\n\n m_paths.push_back(path);\n\n }\n\n\n\nprivate:\n\n int64_t m_total;\n\n int64_t m_used;\n\n int64_t m_available;\n\n std::vector<std::string> m_paths;\n\n};\n\n\n\n\n\n/**\n\n * @brief Get disk space information of a server.\n\n *\n", "file_path": "include/maxscale/mariadb.hh", "rank": 34, "score": 140779.8461484731 }, { "content": " * The total size of a disk.\n\n *\n\n * @return The total size of the disk in bytes.\n\n */\n\n int64_t total() const\n\n {\n\n return m_total;\n\n }\n\n\n\n /**\n\n * The used amount of space of a disk.\n\n *\n\n * @return The size of the used amount of space of the disk in bytes.\n\n */\n\n int64_t used() const\n\n {\n\n return m_used;\n\n }\n\n\n\n /**\n", "file_path": "include/maxscale/mariadb.hh", "rank": 35, "score": 140779.8461484731 }, { "content": "class MonitorInstance : public MXS_MONITOR_INSTANCE\n\n , protected maxbase::Worker\n\n{\n\npublic:\n\n MonitorInstance(const MonitorInstance&) = delete;\n\n MonitorInstance& operator=(const MonitorInstance&) = delete;\n\n\n\n virtual ~MonitorInstance();\n\n\n\n /**\n\n * @brief Current state of the monitor.\n\n *\n\n * Since the state is written to by the admin thread, the value returned in other threads cannot be fully\n\n * trusted. The state should only be read in the admin thread or operations launched by the admin thread.\n\n *\n\n * @return @c MONITOR_STATE_RUNNING if the monitor is running,\n\n * @c MONITOR_STATE_STOPPING if the monitor is stopping, and\n\n * @c MONITOR_STATE_STOPPED if the monitor is stopped.\n\n */\n\n monitor_state_t monitor_state() const;\n", "file_path": "include/maxscale/monitor.hh", "rank": 36, "score": 140546.59403262107 }, { "content": "class MonitorInstanceSimple : public MonitorInstance\n\n{\n\npublic:\n\n MonitorInstanceSimple(const MonitorInstanceSimple&) = delete;\n\n MonitorInstanceSimple& operator=(const MonitorInstanceSimple&) = delete;\n\n\n\nprotected:\n\n MonitorInstanceSimple(MXS_MONITOR* pMonitor)\n\n : MonitorInstance(pMonitor)\n\n {\n\n }\n\n\n\n /**\n\n * @brief Update server information\n\n *\n\n * The implementation should probe the server in question and update\n\n * the server status bits.\n\n */\n\n virtual void update_server_status(MXS_MONITORED_SERVER* pMonitored_server) = 0;\n\n\n", "file_path": "include/maxscale/monitor.hh", "rank": 37, "score": 140546.59403262107 }, { "content": "typedef struct mxs_router\n\n{\n", "file_path": "include/maxscale/router.h", "rank": 38, "score": 140521.4057097327 }, { "content": "struct ROUTER_INSTANCE : public MXS_ROUTER\n\n{\n\n SERVICE* service; /*< Pointer to the service using this router */\n\n ROUTER_SLAVE* slaves; /*< Link list of all the slave connections */\n\n mutable pthread_mutex_t lock; /*< Spinlock for the instance data */\n\n char* uuid; /*< UUID for the router to use w/master */\n\n int orig_masterid; /*< Server ID of the master, internally used */\n\n int masterid; /*< Set ID of the master, sent to slaves */\n\n int serverid; /*< ID for the router to use w/master */\n\n int initbinlog; /*< Initial binlog file number */\n\n char* user; /*< User name to use with master */\n\n char* password; /*< Password to use with master */\n\n char* fileroot; /*< Root of binlog filename */\n\n bool master_chksum; /*< Does the master provide checksums */\n\n bool mariadb10_compat;\n\n /*< MariaDB 10.0 compatibility */\n\n bool maxwell_compat;/*< Zendesk's Maxwell compatibility */\n\n char* master_uuid; /*< Set UUID of the master, sent to slaves */\n\n DCB* master; /*< DCB for master connection */\n\n DCB* client; /*< DCB for dummy client */\n", "file_path": "server/modules/routing/binlogrouter/blr.hh", "rank": 39, "score": 138997.55585210084 }, { "content": "MAXAVRO_FILE* maxavro_file_open(const char* filename)\n\n{\n\n FILE* file = fopen(filename, \"rb\");\n\n if (!file)\n\n {\n\n MXS_ERROR(\"Failed to open file '%s': %d, %s\", filename, errno, strerror(errno));\n\n return NULL;\n\n }\n\n\n\n char magic[AVRO_MAGIC_SIZE];\n\n\n\n if (fread(magic, 1, AVRO_MAGIC_SIZE, file) != AVRO_MAGIC_SIZE)\n\n {\n\n fclose(file);\n\n MXS_ERROR(\"Failed to read file magic marker from '%s'\", filename);\n\n return NULL;\n\n }\n\n\n\n if (memcmp(magic, avro_magic, AVRO_MAGIC_SIZE) != 0)\n\n {\n\n fclose(file);\n\n MXS_ERROR(\"Error: Avro magic marker bytes are not correct.\");\n\n return NULL;\n\n }\n\n\n\n bool error = false;\n\n\n\n MAXAVRO_FILE* avrofile = calloc(1, sizeof(MAXAVRO_FILE));\n\n char* my_filename = strdup(filename);\n\n\n\n if (avrofile && my_filename)\n\n {\n\n avrofile->file = file;\n\n avrofile->filename = my_filename;\n\n avrofile->last_error = MAXAVRO_ERR_NONE;\n\n\n\n char* schema = read_schema(avrofile);\n\n\n\n if (schema)\n\n {\n\n avrofile->schema = maxavro_schema_alloc(schema);\n\n\n\n if (avrofile->schema\n\n && maxavro_read_sync(file, avrofile->sync)\n\n && maxavro_read_datablock_start(avrofile))\n\n {\n\n avrofile->header_end_pos = avrofile->block_start_pos;\n\n }\n\n else\n\n {\n\n maxavro_schema_free(avrofile->schema);\n\n error = true;\n\n }\n\n MXS_FREE(schema);\n\n }\n\n else\n\n {\n\n error = true;\n\n }\n\n }\n\n else\n\n {\n\n error = true;\n\n }\n\n\n\n if (error)\n\n {\n\n fclose(file);\n\n MXS_FREE(avrofile);\n\n MXS_FREE(my_filename);\n\n avrofile = NULL;\n\n }\n\n\n\n return avrofile;\n", "file_path": "avro/maxavro_file.c", "rank": 40, "score": 138906.23650780448 }, { "content": "#define MXS_ROUTER_VERSION {4, 0, 0}\n\n\n", "file_path": "include/maxscale/router.h", "rank": 41, "score": 138566.0085091473 }, { "content": "class Sizes\n\n{\n\npublic:\n\n Sizes()\n\n : m_total(0)\n\n , m_used(0)\n\n , m_available(0)\n\n {\n\n }\n\n\n\n Sizes(int64_t total,\n\n int64_t used,\n\n int64_t available)\n\n : m_total(total)\n\n , m_used(used)\n\n , m_available(available)\n\n {\n\n }\n\n\n\n /**\n", "file_path": "include/maxscale/mariadb.hh", "rank": 42, "score": 137997.74022976964 }, { "content": "class EqualPointees : public std::unary_function<T, bool>\n\n{\n\npublic:\n\n EqualPointees(const T& lhs) : m_ppLhs(&lhs)\n\n {\n\n }\n\n bool operator()(const T& pRhs)\n\n {\n\n return **m_ppLhs == *pRhs;\n\n }\n\nprivate:\n\n const T* m_ppLhs;\n\n};\n\n\n\ntemplate<typename T>\n\nEqualPointees<T> equal_pointees(const T& t)\n\n{\n\n return EqualPointees<T>(t);\n\n}\n\n\n\n/**\n\n * Get hexadecimal string representation of @c value\n\n *\n\n * @param value Value to convert\n\n *\n\n * @return Hexadecimal string representation of @c value\n\n */\n\nstd::string to_hex(uint8_t value);\n\n\n\ntemplate<typename T, typename V>\n", "file_path": "include/maxscale/utils.hh", "rank": 43, "score": 136284.41150134683 }, { "content": " * Queue a new query for execution\n\n *\n\n * @param buffer Buffer containing the query\n\n *\n\n * @return True if query was successfully queued\n\n */\n\n bool queue_query(GWBUF* buffer);\n\n\n\n /**\n\n * Destroy the client by sending a COM_QUIT to the backend\n\n *\n\n * @note After calling this function, object must be treated as a deleted object\n\n */\n\n void self_destruct();\n\n\n\nprivate:\n\n static LocalClient* create(MYSQL_session* session, MySQLProtocol* proto, const char* ip, uint64_t port);\n\n LocalClient(MYSQL_session* session, MySQLProtocol* proto, int fd);\n\n static uint32_t poll_handler(MXB_POLL_DATA* data, MXB_WORKER* worker, uint32_t events);\n\n void process(uint32_t events);\n", "file_path": "include/maxscale/protocol/mariadb_client.hh", "rank": 44, "score": 135338.04384227892 }, { "content": "/*\n\n * Copyright (c) 2018 MariaDB Corporation Ab\n\n *\n\n * Use of this software is governed by the Business Source License included\n\n * in the LICENSE.TXT file and at www.mariadb.com/bsl11.\n\n *\n\n * Change Date: 2022-01-01\n\n *\n\n * On the date above, in accordance with the Business Source License, use\n\n * of this software will be governed by version 2 or later of the General\n\n * Public License.\n\n */\n\n#pragma once\n\n\n\n#include <maxscale/ccdefs.hh>\n\n\n\n#include <deque>\n\n\n\n#include <maxbase/poll.h>\n\n#include <maxscale/buffer.hh>\n\n#include <maxscale/service.h>\n\n#include <maxscale/protocol/mysql.h>\n\n\n\n/** A DCB-like client abstraction which ignores responses */\n", "file_path": "include/maxscale/protocol/mariadb_client.hh", "rank": 45, "score": 135335.58243198894 }, { "content": " GWBUF* read_complete_packet();\n\n void drain_queue();\n\n void error();\n\n void close();\n\n\n\n /** Client states */\n\n enum vc_state\n\n {\n\n VC_WAITING_HANDSHAKE, // Initial state\n\n VC_RESPONSE_SENT, // Handshake received and response sent\n\n VC_OK, // Authentication is complete, ready for queries\n\n VC_ERROR // Something went wrong\n\n };\n\n\n\n vc_state m_state;\n\n int m_sock;\n\n mxs::Buffer m_partial;\n\n size_t m_expected_bytes;\n\n std::deque<mxs::Buffer> m_queue;\n\n MYSQL_session m_client;\n\n MySQLProtocol m_protocol;\n\n bool m_self_destruct;\n\n};\n", "file_path": "include/maxscale/protocol/mariadb_client.hh", "rank": 46, "score": 135335.2804421883 }, { "content": "struct ROUTER_INSTANCE;\n\n\n\n/* Config struct for CHANGE MASTER TO options */\n", "file_path": "server/modules/routing/binlogrouter/blr.hh", "rank": 47, "score": 130748.80565317016 }, { "content": " MXS_ROUTER*(*createInstance)(SERVICE * service, MXS_CONFIG_PARAMETER* params);\n", "file_path": "include/maxscale/router.h", "rank": 48, "score": 130308.36147466728 }, { "content": "class SizesAndPaths : public Sizes\n\n{\n\npublic:\n\n SizesAndPaths()\n\n {\n\n }\n\n\n\n SizesAndPaths(int64_t total,\n\n int64_t used,\n\n int64_t available,\n\n const std::string& path)\n\n : Sizes(total, used, available)\n\n {\n\n m_paths.push_back(path);\n\n }\n\n\n\n /**\n\n * @return The paths that referring to the disk for which the size is reported.\n\n */\n\n const std::vector<std::string>& paths() const\n", "file_path": "include/maxscale/mariadb.hh", "rank": 49, "score": 130274.25992674395 }, { "content": "class SizesAndName : public Sizes\n\n{\n\npublic:\n\n SizesAndName()\n\n {\n\n }\n\n\n\n SizesAndName(int64_t total,\n\n int64_t used,\n\n int64_t available,\n\n const std::string& name)\n\n : Sizes(total, used, available)\n\n , m_name(name)\n\n {\n\n }\n\n\n\n /**\n\n * @return The name of the disk. E.g. @c /dev/sda1\n\n */\n\n const std::string& name() const\n", "file_path": "include/maxscale/mariadb.hh", "rank": 50, "score": 130274.25992674395 }, { "content": "class Writer : std::unary_function<HintRouterSession::MapElement, bool>\n\n{\n\npublic:\n\n Writer(GWBUF* pPacket)\n\n : m_pPacket(pPacket)\n\n {\n\n }\n\n\n\n bool operator()(HintRouterSession::MapElement& elem)\n\n {\n\n bool rv = false;\n\n Dcb& dcb = elem.second;\n\n GWBUF* pPacket = gwbuf_clone(m_pPacket);\n\n\n\n if (pPacket)\n\n {\n\n SERVER* pServer = dcb.server();\n\n HR_DEBUG(\"Writing packet to %p %s.\", dcb.get(), pServer ? pServer->name : \"(null)\");\n\n rv = dcb.write(pPacket);\n\n }\n", "file_path": "server/modules/routing/hintrouter/hintroutersession.cc", "rank": 51, "score": 128795.3164726205 }, { "content": " int n_current; /**< Current number of sessions */\n", "file_path": "include/maxscale/service.h", "rank": 52, "score": 127925.76918821264 }, { "content": " MXS_MONITOR_INSTANCE* instance; /**< Instance returned from startMonitor */\n", "file_path": "include/maxscale/monitor.h", "rank": 53, "score": 127919.7314297362 }, { "content": " struct mxs_filter* instance;\n", "file_path": "include/maxscale/session.h", "rank": 54, "score": 127919.7314297362 }, { "content": " int n_current; /**< Current connections */\n", "file_path": "include/maxscale/server.h", "rank": 55, "score": 127918.81107409458 }, { "content": "MXS_BEGIN_DECLS\n\n\n\n/**\n\n * @brief Return a pseudo-random number\n\n *\n\n * Return a pseudo-random number that satisfies major tests for random sequences.\n\n *\n\n * @return A random number\n\n */\n", "file_path": "include/maxscale/random.h", "rank": 56, "score": 127918.58096788469 }, { "content": " int flags; /**< DCB flags */\n", "file_path": "include/maxscale/dcb.h", "rank": 57, "score": 127911.20600314357 }, { "content": " time_t started; /**< The time when the service was started */\n", "file_path": "include/maxscale/service.h", "rank": 58, "score": 127901.9927082325 }, { "content": "MXS_BEGIN_DECLS\n\n\n\n/**\n\n * MXS_ROUTER is an opaque type representing a particular router instance.\n\n *\n\n * MaxScale itself does not do anything with it, except for receiving it\n\n * from the @c createInstance function of a router module and subsequently\n\n * passing it back to the API functions of the router.\n\n */\n", "file_path": "include/maxscale/router.h", "rank": 59, "score": 127898.99306114242 }, { "content": " int one_char;\n", "file_path": "pcre2/src/pcre2grep.c", "rank": 60, "score": 126071.78475512314 }, { "content": "static int\n\nopen_file(uint8_t *buffptr, const char *mode, FILE **fptr)\n\n{\n\nchar *endf;\n\nchar *filename = (char *)buffptr;\n\nwhile (isspace(*filename)) filename++;\n\nendf = filename + strlen8(filename);\n\nwhile (endf > filename && isspace(endf[-1])) endf--;\n\n\n\nif (endf == filename)\n\n {\n\n fprintf(outfile, \"** File name expected after #save\\n\");\n\n return PR_ABEND;\n\n }\n\n\n\n*endf = 0;\n\n*fptr = fopen((const char *)filename, mode);\n\nif (*fptr == NULL)\n\n {\n\n fprintf(outfile, \"** Failed to open '%s': %s\\n\", filename, strerror(errno));\n\n return PR_ABEND;\n\n }\n\n\n\nreturn PR_OK;\n", "file_path": "pcre2/src/pcre2test.c", "rank": 61, "score": 125970.76385012438 }, { "content": "MAXAVRO_FILE* maxavro_file_open(const char* filename);\n", "file_path": "avro/maxavro.h", "rank": 62, "score": 125970.0775518581 }, { "content": " uint64_t n_new_conn; /**< Times the current pool was empty */\n", "file_path": "include/maxscale/server.h", "rank": 63, "score": 125629.7206049177 }, { "content": " int n_current_ops; /**< Current active operations */\n", "file_path": "include/maxscale/server.h", "rank": 64, "score": 125625.5304752675 }, { "content": " void* auth_instance; /**< Authenticator instance data */\n", "file_path": "include/maxscale/server.h", "rank": 65, "score": 125619.0954643597 }, { "content": " void* auth_instance; /**< Authenticator instance created in MXS_AUTHENTICATOR::initialize()\n", "file_path": "include/maxscale/listener.h", "rank": 66, "score": 125619.0954643597 }, { "content": "#define SYSNAME_LEN 256\n", "file_path": "include/maxscale/config.h", "rank": 67, "score": 125618.4176221831 }, { "content": " int n_failed_starts; /**< Number of times this service has failed to start */\n", "file_path": "include/maxscale/service.h", "rank": 68, "score": 125608.92425752687 }, { "content": "time_t maxscale_started(void);\n", "file_path": "include/maxscale/maxscale.h", "rank": 69, "score": 125608.72805784651 }, { "content": "MXS_DOWNSTREAM router_as_downstream(MXS_SESSION* session);\n", "file_path": "include/maxscale/session.h", "rank": 70, "score": 125606.3265965239 }, { "content": " unsigned int flags[2]; /*< Received flags */\n", "file_path": "server/modules/include/cdc.h", "rank": 71, "score": 125603.71429050618 }, { "content": "bool serviceStart(SERVICE* service);\n", "file_path": "include/maxscale/service.h", "rank": 72, "score": 125601.67577370617 }, { "content": " bool retry_start; /**< If starting of the service should\n", "file_path": "include/maxscale/service.h", "rank": 73, "score": 125601.67577370617 }, { "content": "extern const char CN_ROUTER[];\n", "file_path": "include/maxscale/config.h", "rank": 74, "score": 125598.73007525953 }, { "content": " const char* routerModule; /**< Name of router module to use */\n", "file_path": "include/maxscale/service.h", "rank": 75, "score": 125598.73007525953 }, { "content": "struct mxs_router;\n", "file_path": "include/maxscale/service.h", "rank": 76, "score": 125598.73007525953 }, { "content": " struct mxs_router_session* router_session; /*< The router instance data */\n", "file_path": "include/maxscale/session.h", "rank": 77, "score": 125598.73007525953 }, { "content": "class FileLogger : public Logger\n\n{\n\npublic:\n\n FileLogger(const FileLogger&) = delete;\n\n FileLogger& operator=(const FileLogger&) = delete;\n\n\n\n /**\n\n * Create a new logger that writes to a file\n\n *\n\n * @param logdir Log file to open\n\n *\n\n * @return New logger instance or an empty unique_ptr on error\n\n */\n\n static std::unique_ptr<Logger> create(const std::string& filename);\n\n\n\n /**\n\n * Close the log\n\n *\n\n * A footer is written to the log and the file is closed.\n\n */\n", "file_path": "maxutils/maxbase/include/maxbase/logger.hh", "rank": 78, "score": 125520.95720765597 }, { "content": "bool config_get_bool(const MXS_CONFIG_PARAMETER* params, const char* key);\n", "file_path": "include/maxscale/config.h", "rank": 79, "score": 123409.07490374024 }, { "content": "DCB* dcb_get_current();\n", "file_path": "include/maxscale/dcb.h", "rank": 80, "score": 123406.1969997669 }, { "content": "MXS_SESSION* session_get_current();\n", "file_path": "include/maxscale/session.h", "rank": 81, "score": 123406.14567351583 }, { "content": "void dprintOneDCB(DCB*, DCB*); /* Debug to print one DCB */\n", "file_path": "include/maxscale/dcb.h", "rank": 82, "score": 123403.52360622855 }, { "content": "bool strip_escape_chars(char*);\n", "file_path": "include/maxscale/utils.h", "rank": 83, "score": 123401.52669851047 }, { "content": " mxs_mysql_cmd_t current_command; /*< Current command being executed */\n", "file_path": "include/maxscale/protocol/mysql.h", "rank": 84, "score": 123398.86349151222 }, { "content": "int open_unix_socket(enum mxs_socket_type type,\n\n struct sockaddr_un* addr,\n", "file_path": "include/maxscale/utils.h", "rank": 85, "score": 123393.5472716454 }, { "content": "int open_network_socket(enum mxs_socket_type type,\n\n struct sockaddr_storage* addr,\n\n const char* host,\n", "file_path": "include/maxscale/utils.h", "rank": 86, "score": 123392.4920815877 }, { "content": "const int MAINTENANCE_FLAG_NOCHECK = 0;\n", "file_path": "include/maxscale/server.h", "rank": 87, "score": 123384.64189605632 }, { "content": "\n\nstatic void blr_report_checksum(REP_HEADER hdr,\n\n const uint8_t* buffer,\n\n char* output);\n\n\n\nbool blr_load_last_mariadb_gtid(ROUTER_INSTANCE* router,\n\n MARIADB_GTID_INFO* result);\n\nbool blr_get_last_file(ROUTER_INSTANCE* router,\n\n MARIADB_GTID_INFO* result);\n\nstatic int gtid_file_select_cb(void* data,\n\n int cols,\n\n char** values,\n\n char** names);\n\nbool blr_compare_binlogs(const ROUTER_INSTANCE* router,\n\n const MARIADB_GTID_ELEMS* info,\n\n const char* r_file,\n\n const char* s_file);\n\n\n\nvoid blr_file_update_gtid(ROUTER_INSTANCE* router);\n\n\n", "file_path": "server/modules/routing/binlogrouter/blr_file.cc", "rank": 90, "score": 59.39195926221627 }, { "content": "static const char* blr_encryption_algorithm_names[BINLOG_MAX_CRYPTO_SCHEME] = {\"aes_cbc\"};\n\nstatic const char blr_encryption_algorithm_list_names[] = \"aes_cbc\";\n\n#endif\n\n\n\nstatic int blr_file_create(ROUTER_INSTANCE* router, char* file);\n\nstatic void blr_log_header(int priority, const char* msg, uint8_t* ptr);\n\nvoid blr_cache_read_master_data(ROUTER_INSTANCE* router);\n\nint blr_file_get_next_binlogname(ROUTER_INSTANCE* router);\n\nint blr_file_new_binlog(ROUTER_INSTANCE* router, char* file);\n\nextern uint32_t extract_field(uint8_t* src, int bits);\n\nstatic void blr_format_event_size(double* event_size, char* label);\n\nextern int MaxScaleUptime();\n\nextern void encode_value(unsigned char* data, unsigned int value, int len);\n\nextern void blr_extract_header(register uint8_t* ptr, register REP_HEADER* hdr);\n\nbool blr_parse_gtid(const char* gtid, MARIADB_GTID_ELEMS* info);\n\n\n\ntypedef struct binlog_event_desc\n\n{\n\n uint64_t event_pos;\n\n uint8_t event_type;\n", "file_path": "server/modules/routing/binlogrouter/blr_file.cc", "rank": 91, "score": 57.81333566457174 }, { "content": " GWBUF** save_buf,\n\n const char* save_tag,\n\n GWBUF* in_buf);\n\nstatic void blr_start_master_registration(ROUTER_INSTANCE* router, GWBUF* buf);\n\nstatic void blr_register_mariadb_gtid_request(ROUTER_INSTANCE* router,\n\n GWBUF* buf);\n\nextern int blr_write_special_event(ROUTER_INSTANCE* router,\n\n uint32_t file_offset,\n\n uint32_t hole_size,\n\n REP_HEADER* hdr,\n\n int type);\n\nextern int blr_file_new_binlog(ROUTER_INSTANCE* router, char* file);\n\nstatic bool blr_handle_missing_files(ROUTER_INSTANCE* router,\n\n char* new_file);\n\nextern void blr_file_update_gtid(ROUTER_INSTANCE* router);\n\nstatic int blr_check_connect_retry(ROUTER_INSTANCE* router);\n\n\n\nstatic int keepalive = 1;\n\n\n\n/**\n", "file_path": "server/modules/routing/binlogrouter/blr_master.cc", "rank": 92, "score": 57.689057645365544 }, { "content": "void encode_value(unsigned char* data, unsigned int value, int len);\n\nvoid blr_handle_binlog_record(ROUTER_INSTANCE* router, GWBUF* pkt);\n\nstatic void* CreateMySQLAuthData(const char* username,\n\n const char* password,\n\n const char* database);\n\nvoid blr_extract_header(uint8_t* pkt, REP_HEADER* hdr);\n\nstatic void blr_log_packet(int priority, const char* msg, uint8_t* ptr, int len);\n\nchar* blr_extract_column(GWBUF* buf, int col);\n\nstatic bool blr_check_last_master_event(void* inst);\n\nextern int blr_check_heartbeat(ROUTER_INSTANCE* router);\n\nstatic void blr_log_identity(ROUTER_INSTANCE* router);\n\nstatic void blr_extract_header_semisync(uint8_t* pkt, REP_HEADER* hdr);\n\nstatic int blr_get_master_semisync(GWBUF* buf);\n\nstatic void blr_terminate_master_replication(ROUTER_INSTANCE* router,\n\n uint8_t* ptr,\n\n int len);\n\nextern bool blr_notify_waiting_slave(ROUTER_SLAVE* slave);\n\nextern bool blr_save_mariadb_gtid(ROUTER_INSTANCE* inst);\n\nstatic void blr_register_serverid(ROUTER_INSTANCE* router, GWBUF* buf);\n\nstatic bool blr_register_heartbeat(ROUTER_INSTANCE* router, GWBUF* buf);\n", "file_path": "server/modules/routing/binlogrouter/blr_master.cc", "rank": 93, "score": 57.477589977356736 }, { "content": "\n\n// Functions used by blr_handle_one_event\n\nint blr_rotate_event(ROUTER_INSTANCE* router, uint8_t* ptr, REP_HEADER* hdr);\n\nint blr_send_semisync_ack(ROUTER_INSTANCE* router, uint64_t pos);\n\nbool blr_handle_fake_rotate(ROUTER_INSTANCE* router, REP_HEADER* hdr, uint8_t* ptr);\n\nvoid blr_handle_fake_gtid_list(ROUTER_INSTANCE* router, REP_HEADER* hdr, uint8_t* ptr);\n\nvoid blr_master_close(ROUTER_INSTANCE*);\n\nvoid blr_notify_all_slaves(ROUTER_INSTANCE* router);\n\nbool blr_save_mariadb_gtid(ROUTER_INSTANCE* inst);\n\n\n\n/**\n\n * Handler for binlog events\n\n *\n\n * This function is called for each event replicated from the master.\n\n *\n\n * @param instance Router instance\n\n * @param hdr Event header\n\n * @param ptr Event data\n\n * @param len Buffer length\n\n * @param semisync 1 if semisync is enabled (TODO: change this)\n", "file_path": "server/modules/routing/binlogrouter/blr.hh", "rank": 95, "score": 56.93730070056827 }, { "content": " last_known_commit);\n\n\n\n gwbuf_free(result);\n\n\n\n break;\n\n }\n\n else\n\n {\n\n char mariadb_gtid[GTID_MAX_LEN + 1];\n\n snprintf(mariadb_gtid,\n\n GTID_MAX_LEN,\n\n \"%u-%u-%lu\",\n\n domainid,\n\n hdr.serverid,\n\n n_sequence);\n\n\n\n pending_transaction = BLRM_TRANSACTION_START;\n\n\n\n router->pending_transaction.start_pos = pos;\n\n router->pending_transaction.end_pos = 0;\n", "file_path": "server/modules/routing/binlogrouter/blr_file.cc", "rank": 96, "score": 56.09413352130203 }, { "content": "\n\nextern bool blr_send_event(blr_thread_role_t role,\n\n const char* binlog_name,\n\n uint32_t binlog_pos,\n\n ROUTER_SLAVE* slave,\n\n REP_HEADER* hdr,\n\n uint8_t* buf);\n\n\n\nextern const char* blr_get_encryption_algorithm(int);\n\nextern int blr_check_encryption_algorithm(const char*);\n\nextern const char* blr_encryption_algorithm_list(void);\n\nextern bool blr_get_encryption_key(ROUTER_INSTANCE*);\n\nextern void blr_set_checksum(ROUTER_INSTANCE* instance, GWBUF* buf);\n\nextern const char* blr_skip_leading_sql_comments(const char*);\n\nextern bool blr_fetch_mariadb_gtid(ROUTER_SLAVE*,\n\n const char*,\n\n MARIADB_GTID_INFO*);\n\nextern bool blr_start_master_in_main(ROUTER_INSTANCE* data, int32_t delay = 0);\n\nextern bool blr_binlog_file_exists(ROUTER_INSTANCE* router,\n\n const MARIADB_GTID_INFO* info_file);\n", "file_path": "server/modules/routing/binlogrouter/blr.hh", "rank": 97, "score": 54.19659036007556 }, { "content": " * @param req_pos The requested file pos\n\n * @return False if GTID is not found and slave\n\n * is connectig with gtid_strict_mode=1,\n\n * other errors.\n\n * True otherwise.\n\n */\n\nstatic bool blr_slave_gtid_request(ROUTER_INSTANCE* router,\n\n ROUTER_SLAVE* slave,\n\n bool req_file,\n\n unsigned long req_pos)\n\n{\n\n MARIADB_GTID_INFO f_gtid = {};\n\n uint32_t router_pos;\n\n char router_curr_file[BINLOG_FNAMELEN + 1];\n\n char last_gtid[GTID_MAX_LEN + 1];\n\n\n\n memset(&f_gtid, 0, sizeof(f_gtid));\n\n\n\n pthread_mutex_lock(&router->binlog_lock);\n\n // Set gtid as current router gtid\n", "file_path": "server/modules/routing/binlogrouter/blr_slave.cc", "rank": 99, "score": 51.56524395361758 } ]
C++
game/src/main/cpp/game/Particles/Splash.cpp
zorin-egor/PingPongGame
fc4084f4e0efaa8d24605e7ae00b630c2ae984b7
#include "Splash.h" Splash::Splash(GLuint count, GLuint lifeTime, GLuint programID, GLuint textureID, GLuint positionAttr, GLuint colorStartAttr, GLuint colorEndAttr, GLuint deltaAttr, GLuint sizeUniform ) : m_nCount(count), m_nLifeTime(lifeTime), m_nProgramId(programID), m_nTextureId(textureID), m_nPositionAttr(positionAttr), m_nColorStartAttr(colorStartAttr), m_nColorEndAttr(colorEndAttr), m_nDeltaAttr(deltaAttr), m_nSizeUniform(sizeUniform), TOTAL_LIFE_TIME(lifeTime) { LOGI("Splash::Splash()"); m_pIsVisible = true; m_fPointSize = 5.0f; initArrays(); setSplashPosition(0.0f, 0.0f); } Splash::~Splash() { LOGI("Splash::~Splash()"); deleteObjects(); } void Splash::render() { if (!m_pIsVisible) { return; } if (m_nLifeTime < 0) { return; } setValues(); glUseProgram(m_nProgramId); checkGLError("Splash - glUseProgram"); glBindTexture(GL_TEXTURE_2D, m_nTextureId); checkGLError("Splash - glBindTexture"); glVertexAttribPointer(m_nPositionAttr, 2, GL_FLOAT, GL_FALSE, 0, m_pPositionArray); checkGLError("Splash - glVertexAttribPointer - m_nPositionAttr"); glEnableVertexAttribArray(m_nPositionAttr); checkGLError("Splash - glVertexAttribPointer - m_nPositionAttr - enabled"); glVertexAttribPointer(m_nColorStartAttr, 4, GL_FLOAT, GL_FALSE, 0, m_pColorStartArray); checkGLError("Splash - glVertexAttribPointer - m_nColorStartAttr"); glEnableVertexAttribArray(m_nColorStartAttr); checkGLError("Splash - glVertexAttribPointer - m_nColorStartAttr - enabled"); glVertexAttribPointer(m_nColorEndAttr, 4, GL_FLOAT, GL_FALSE, 0, m_pColorEndArray); checkGLError("Splash - glVertexAttribPointer - m_nColorEndAttr"); glEnableVertexAttribArray(m_nColorEndAttr); checkGLError("Splash - glVertexAttribPointer - m_nColorEndAttr - enabled"); glVertexAttribPointer(m_nDeltaAttr, 1, GL_FLOAT, GL_FALSE, 0, m_pDeltaArray); checkGLError("Splash - glVertexAttribPointer - m_nDeltaAttr"); glEnableVertexAttribArray(m_nDeltaAttr); checkGLError("Splash - glVertexAttribPointer - m_nDeltaAttr - enabled"); glUniform2f(m_nSizeUniform, m_pSizeArray[0], m_pSizeArray[1]); checkGLError("Splash - glUniform2f - m_nSizeUniform"); glDrawArrays(GL_POINTS, 0, m_nCount); checkGLError("Splash - glDrawArrays"); } void Splash::initArrays() { m_pPositionArray = new GLfloat[m_nCount * 2]; Methods::fillArray(m_pPositionArray, 0.0f, m_nCount * 2); m_pDeltaArray = new GLfloat[m_nCount]; m_pColorStartArray = new GLfloat[m_nCount * 4]; Methods::fillArray(m_pColorStartArray, 0.0f, m_nCount * 4); m_pColorEndArray = new GLfloat[m_nCount * 4]; Methods::fillArray(m_pColorEndArray, 0.0f, m_nCount * 4); m_pSizeArray = new GLfloat[2]; m_pSizeArray[0] = 2.0f; m_pSizeArray[1] = m_fPointSize; m_pDxArray = new GLfloat[m_nCount]; m_pDyArray = new GLfloat[m_nCount]; for (int i = 0; i < m_nCount; i++) { m_pDxArray[i] = Methods::getFullRandom() * 0.02; m_pDyArray[i] = Methods::getFullRandom() * 0.02; m_pDeltaArray[i] = Methods::getShortRandom() * 0.9; } } void Splash::setSplashPosition(GLfloat x, GLfloat y) { m_nLifeTime = TOTAL_LIFE_TIME; for (int i = 0; i < m_nCount; i++) { m_pPositionArray[i * 2] = x; m_pPositionArray[i * 2 + 1] = y; } } void Splash::setValues() { m_nLifeTime--; for (int i = 0; i < m_nCount; i++) { m_pPositionArray[i * 2] += m_pDxArray[i]; m_pPositionArray[i * 2 + 1] += m_pDyArray[i]; m_pColorStartArray[i * 4] = Methods::getShortRandom() * 0.5f; m_pColorStartArray[i * 4 + 1] = Methods::getShortRandom() * 0.5f; m_pColorStartArray[i * 4 + 2] = Methods::getShortRandom() * 0.5f; m_pColorStartArray[i * 4 + 3] = 0.1; m_pColorEndArray[i * 4] = Methods::getShortRandom() + 0.5f; m_pColorEndArray[i * 4 + 1] = Methods::getShortRandom() + 0.5f; m_pColorEndArray[i * 4 + 2] = Methods::getShortRandom() + 0.5f; m_pColorEndArray[i * 4 + 3] = (float) m_nLifeTime / (float) TOTAL_LIFE_TIME; } } void Splash::setParticlesCount(GLuint count) { m_nCount = count > 100 && count < 500 ? count : m_nCount; } void Splash::setParticlesSize(GLfloat size) { m_fPointSize = size > 2.0f && size < 20.0f ? size : m_fPointSize; } void Splash::deleteObjects() { delete [] m_pPositionArray; delete [] m_pColorStartArray; delete [] m_pColorEndArray; delete [] m_pDeltaArray; delete [] m_pSizeArray; delete [] m_pDxArray; delete [] m_pDyArray; } void Splash::setSettings() { deleteObjects(); initArrays(); } void Splash::resetTimer() { m_nLifeTime = 0; }
#include "Splash.h" Splash::Splash(GLuint count, GLuint lifeTime, GLuint programID, GLuint textureID, GLuint positionAttr, GLuint colorStartAttr, GLuint colorEndAttr, GLuint deltaAttr, GLuint sizeUniform ) : m_nCount(count), m_nLifeTime(lifeTime), m_nProgramId(programID), m_nTextureId(textureID), m_nPositionAttr(positionAttr), m_nColorStartAttr(colorStartAttr), m_nColorEndAttr(colorEndAttr), m_nDeltaAttr(deltaAttr), m_nSizeUniform(sizeUniform), TOTAL_LIFE_TIME(lifeTime) { LOGI("Splash::Splash()"); m_pIsVisible = true; m_fPointSize = 5.0f; initArrays(); setSplashPosition(0.0f, 0.0f); } Splash::~Splash() { LOGI("Splash::~Splash()"); deleteObjects(); } void Splash::render() { if (!m_pIsVisible) { return; } if (m_nLifeTime < 0) { return; } setValues(); glUseProgram(m_nProgramId); checkGLError("Splash - glUseProgram"); glBindTexture(GL_TEXTURE_2D, m_nTextureId); checkGLError("Splash - glBindTexture"); glVertexAttribPointer(m_nPositionAttr, 2, GL_FLOAT, GL_FALSE, 0, m_pPositionArray); checkGLError("Splash - glVertexAttribPointer - m_nPositionAttr"); glEnableVertexAttribArray(m_nPositionAttr); checkGLError("Splash - glVertexAttribPointer - m_nPositionAttr - enabled"); glVertexAttribPointer(m_nColorStartAttr, 4, GL_FLOAT, GL_FALSE, 0, m_pColorStartArray); checkGLError("Splash - glVertexAttribPointer - m_nColorStartAttr"); glEnableVertexAttribArray(m_nColorStartAttr); checkGLError("Splash - glVertexAttribPointer - m_nColorStartAttr - enabled"); glVertexAttribPointer(m_nColorEndAttr, 4, GL_FLOAT, GL_FALSE, 0, m_pColorEndArray); checkGLError("Splash - glVertexAttribPointer - m_nColorEndAttr"); glEnableVertexAttribArray(m_nColorEndAttr); checkGLError("Splash - glVertexAttribPointer - m_nColorEndAttr - enabled"); glVertexAttribPointer(m_nDeltaAttr, 1, GL_FLOAT, GL_FALSE, 0, m_pDeltaArray); checkGLError("Splash - glVertexAttribPointer - m_nDeltaAttr"); glEnableVertexAttribArray(m_nDeltaAttr); checkGLError("Splash - glVertexAttribPointer - m_nDeltaAttr - enabled"); glUniform2f(m_nSizeUniform, m_pSizeArray[0], m_pSizeArray[1]); checkGLError("Splash - glUniform2f - m_nSizeUniform"); glDrawArrays(GL_POINTS, 0, m_nCount); checkGLError("Splash - glDrawArrays"); }
void Splash::setSplashPosition(GLfloat x, GLfloat y) { m_nLifeTime = TOTAL_LIFE_TIME; for (int i = 0; i < m_nCount; i++) { m_pPositionArray[i * 2] = x; m_pPositionArray[i * 2 + 1] = y; } } void Splash::setValues() { m_nLifeTime--; for (int i = 0; i < m_nCount; i++) { m_pPositionArray[i * 2] += m_pDxArray[i]; m_pPositionArray[i * 2 + 1] += m_pDyArray[i]; m_pColorStartArray[i * 4] = Methods::getShortRandom() * 0.5f; m_pColorStartArray[i * 4 + 1] = Methods::getShortRandom() * 0.5f; m_pColorStartArray[i * 4 + 2] = Methods::getShortRandom() * 0.5f; m_pColorStartArray[i * 4 + 3] = 0.1; m_pColorEndArray[i * 4] = Methods::getShortRandom() + 0.5f; m_pColorEndArray[i * 4 + 1] = Methods::getShortRandom() + 0.5f; m_pColorEndArray[i * 4 + 2] = Methods::getShortRandom() + 0.5f; m_pColorEndArray[i * 4 + 3] = (float) m_nLifeTime / (float) TOTAL_LIFE_TIME; } } void Splash::setParticlesCount(GLuint count) { m_nCount = count > 100 && count < 500 ? count : m_nCount; } void Splash::setParticlesSize(GLfloat size) { m_fPointSize = size > 2.0f && size < 20.0f ? size : m_fPointSize; } void Splash::deleteObjects() { delete [] m_pPositionArray; delete [] m_pColorStartArray; delete [] m_pColorEndArray; delete [] m_pDeltaArray; delete [] m_pSizeArray; delete [] m_pDxArray; delete [] m_pDyArray; } void Splash::setSettings() { deleteObjects(); initArrays(); } void Splash::resetTimer() { m_nLifeTime = 0; }
void Splash::initArrays() { m_pPositionArray = new GLfloat[m_nCount * 2]; Methods::fillArray(m_pPositionArray, 0.0f, m_nCount * 2); m_pDeltaArray = new GLfloat[m_nCount]; m_pColorStartArray = new GLfloat[m_nCount * 4]; Methods::fillArray(m_pColorStartArray, 0.0f, m_nCount * 4); m_pColorEndArray = new GLfloat[m_nCount * 4]; Methods::fillArray(m_pColorEndArray, 0.0f, m_nCount * 4); m_pSizeArray = new GLfloat[2]; m_pSizeArray[0] = 2.0f; m_pSizeArray[1] = m_fPointSize; m_pDxArray = new GLfloat[m_nCount]; m_pDyArray = new GLfloat[m_nCount]; for (int i = 0; i < m_nCount; i++) { m_pDxArray[i] = Methods::getFullRandom() * 0.02; m_pDyArray[i] = Methods::getFullRandom() * 0.02; m_pDeltaArray[i] = Methods::getShortRandom() * 0.9; } }
function_block-full_function
[ { "content": "def APP_CODE = 2\n", "file_path": "game/build.gradle", "rank": 0, "score": 19471.39118875441 }, { "content": " m_nColorResetTimer = COLOR_INITIAL_TIMER;\n\n m_bIsColorReset = true;\n\n}\n\n\n\nvoid Shape::setParticlesCount(GLuint count) {\n\n m_nCount = count > 5000 && count < 30000 ? count : m_nCount;\n\n}\n\n\n\nvoid Shape::setParticlesSize(GLfloat size) {\n\n m_fPointSize = size > 0.0f && size < 100.0f ? size : m_fPointSize;\n\n}\n\n\n\nvoid Shape::deleteObjects() {\n\n delete [] m_fArrayPosition;\n\n delete [] m_fArrayColor;\n\n}", "file_path": "game/src/main/cpp/game/Particles/Shape.cpp", "rank": 1, "score": 10.260894262373295 }, { "content": "\n\n void setParticlesSize(GLfloat size);\n\n\n\n void setParticlesCount(GLuint count);\n\n\n\n void setVisible(bool isVisible) {\n\n m_bIsVisible = isVisible;\n\n }\n\n\n\n bool getVisible() {\n\n return m_bIsVisible;\n\n }\n\n\n\n\n\n private:\n\n\n\n void setValues();\n\n\n\n};\n\n\n\n\n\n#endif\n", "file_path": "game/src/main/cpp/game/Particles/Particles.h", "rank": 2, "score": 7.801090845611763 }, { "content": "\n\n void setColorTimer();\n\n\n\n void setParticlesSize(GLfloat size);\n\n\n\n void setParticlesCount(GLuint count);\n\n\n\n void deleteObjects();\n\n\n\n void setVisible(bool isVisible) {\n\n m_bIsVisible = isVisible;\n\n }\n\n\n\n bool getVisible() {\n\n return m_bIsVisible;\n\n }\n\n\n\n\n\n private:\n\n\n\n void initArrays();\n\n\n\n void setValues();\n\n};\n\n\n\n#endif\n", "file_path": "game/src/main/cpp/game/Particles/Shape.h", "rank": 3, "score": 7.775890149731294 }, { "content": "\n\n public:\n\n\n\n void initArrays();\n\n\n\n void setSettings();\n\n\n\n void render();\n\n\n\n void setParticlesCount(GLuint count);\n\n\n\n void setParticlesSize(GLfloat size);\n\n\n\n void setPlumePoints(std::queue<GLfloat> * points);\n\n\n\n void deleteObjects();\n\n\n\n void setVisible(bool isVisible) {\n\n m_bIsVisible = isVisible;\n\n }\n", "file_path": "game/src/main/cpp/game/Particles/Plume.h", "rank": 4, "score": 7.749892003178409 }, { "content": " GLuint sizeUniform );\n\n\n\n virtual ~Splash();\n\n\n\n\n\n public:\n\n\n\n void initArrays();\n\n\n\n void render();\n\n\n\n void setSettings();\n\n\n\n void deleteObjects();\n\n\n\n void setParticlesCount(GLuint count);\n\n\n\n void setParticlesSize(GLfloat size);\n\n\n\n void setSplashPosition(GLfloat x, GLfloat y);\n", "file_path": "game/src/main/cpp/game/Particles/Splash.h", "rank": 5, "score": 7.738487541220908 }, { "content": " delete [] m_pRandomArrayCoords;\n\n delete [] m_pRandomArrayRadius;\n\n delete [] m_pRandomArraySpeed;\n\n delete [] m_pRandomArrayDelta;\n\n}\n\n\n\nvoid Particles::setParticlesSize(GLfloat size) {\n\n m_fPointSize = size > 2.0f && size < 100.0f ? size : m_fPointSize;\n\n}\n\n\n\nvoid Particles::setParticlesCount(GLuint count) {\n\n m_nCount = count > 1000 && count < 5000 ? count : m_nCount;\n\n}\n\n\n", "file_path": "game/src/main/cpp/game/Particles/Particles.cpp", "rank": 6, "score": 7.625169332537499 }, { "content": " m_pPositionArray[i * 2] = x + Methods::getFullRandom() * dispersion;\n\n m_pPositionArray[i * 2 + 1] = y + Methods::getFullRandom() * dispersion;\n\n\n\n // Set alpha of tale\n\n m_pColorEndArray[i * 4 + 3] = alpha;\n\n }\n\n\n\n dispersion += 0.002f;\n\n alpha += 0.05f;\n\n }\n\n }\n\n}\n\n\n\nvoid Plume::setParticlesCount(GLuint count) {\n\n m_nCount = count > 100 && count < 500 ? m_nCount : count;\n\n}\n\n\n\nvoid Plume::setParticlesSize(GLfloat size) {\n\n m_fPointSize = size > 2.0f && size < 20.0f ? size : m_fPointSize;\n\n}\n", "file_path": "game/src/main/cpp/game/Particles/Plume.cpp", "rank": 7, "score": 7.391877953347288 }, { "content": " checkGLError(\"Game::init - glBlendFunc\");\n\n glEnable(GL_BLEND);\n\n checkGLError(\"Game::init - glEnable\");\n\n\n\n return true;\n\n}\n\n\n\nvoid Game::setDefault() {\n\n // Reset splash\n\n m_pSplash->resetTimer();\n\n\n\n // Set background shape\n\n m_pShape->setSettings();\n\n\n\n // PLayers buttons\n\n m_pPlayPause->setState(false);\n\n m_pPlayPauseTwo->setState(false);\n\n\n\n // Score labels\n\n m_pPlayer->clearScore();\n", "file_path": "game/src/main/cpp/game/Main/Game.cpp", "rank": 9, "score": 7.2072627124000945 }, { "content": "}\n\n\n\nvoid Shape::setColor() {\n\n Methods::fillArrayRGBA(m_fArrayColor, 0, m_nCount * m_fColorParts, 0.0f, 0.0f, 1.0f, 1.0f);\n\n Methods::fillArrayRGBA(m_fArrayColor, m_nCount * m_fColorParts, m_nCount, 1.0f, 0.0f, 0.0f, 1.0f);\n\n}\n\n\n\nvoid Shape::setColorLight() {\n\n Methods::fillArrayRGBA(m_fArrayColor, 0, m_nCount, 1.0f, 0.922f, 0.804f, 0.8f);\n\n}\n\n\n\nvoid Shape::setColorPart(GLuint first, GLuint second) {\n\n m_fColorParts = COLOR_EQUALS_PARTS;\n\n if (first != second) {\n\n m_fColorParts = (GLfloat)first / (GLfloat)(first + second);\n\n }\n\n //LOGI(\"Shape::setColorPart - m_fColorParts: %ff\", m_fColorParts);\n\n}\n\n\n\nvoid Shape::setColorTimer() {\n", "file_path": "game/src/main/cpp/game/Particles/Shape.cpp", "rank": 10, "score": 6.901954538008758 }, { "content": "#include \"Shape.h\"\n\n\n\nconst GLfloat Shape::STATIC_FIGURES[30][4] = {\n\n { 3.941473f, 2.242605f, 3.341472f, 2.392605f },\n\n { 4.266757f, 2.573080f, 4.816757f, 2.473080f },\n\n { 2.991552f, 5.303362f, 2.641552f, 5.703362f },\n\n { 5.166590f, 3.200857f, 4.816589f, 3.286608f },\n\n { 2.466584f, 1.821339f, 2.316585f, 1.871339f },\n\n { 2.541554f, 3.581697f, 2.341554f, 3.931697f },\n\n { 2.133250f, 4.303725f, 1.533250f, 4.453724f },\n\n { 2.258382f, 3.602231f, 1.658382f, 3.752230f },\n\n { 1.916898f, 2.546700f, 1.316898f, 2.696700f },\n\n { 3.391655f, 4.172695f, 3.141655f, 4.522695f },\n\n { 2.783147f, 4.595323f, 2.833147f, 4.345323f },\n\n { 1.627712f, 3.734871f, 2.027712f, 4.534871f },\n\n { 1.833125f, 2.745408f, 2.383124f, 3.195408f },\n\n { 5.799956f, 3.344940f, 5.849955f, 3.394940f }\n\n };\n\n\n\nShape::Shape(GLuint count,\n", "file_path": "game/src/main/cpp/game/Particles/Shape.cpp", "rank": 11, "score": 6.85164471014269 }, { "content": "#include <jni.h>\n\n#include <Common/Intersect.h>\n\n#include <Main/Game.h>\n\n\n\n#define JNI_METHOD(RTYPE, NAME) JNIEXPORT RTYPE JNICALL Java_ru_simpleapps_pingpong_GameLib_##NAME\n\n\n\nGame* pGame = nullptr;\n\n\n\nextern \"C\" {\n\n\n\n JNI_METHOD(void, init)(JNIEnv* env, jclass type, jobject pngManager, jobject assetManager) {\n\n pGame = new Game(env, pngManager, assetManager);\n\n }\n\n\n\n JNI_METHOD(void, destroy)(JNIEnv* env, jclass type) {\n\n delete pGame;\n\n pGame = nullptr;\n\n }\n\n\n\n JNI_METHOD(void, start)(JNIEnv* env, jclass type) {\n", "file_path": "game/src/main/cpp/game/gamelib.cpp", "rank": 12, "score": 6.402748175607668 }, { "content": "\n\n// -------------------------------------------------------------------------------------------------\n\n// MENU BLOCK\n\nvoid Game::drawFrameMenu() {\n\n m_pMenuHeader->render();\n\n m_pSingle->render();\n\n m_pMulti->render();\n\n m_pSound->render();\n\n m_pQuality->render();\n\n m_pExit->render();\n\n}\n\n\n\nvoid Game::logicMenu() {\n\n // Show menu buttons\n\n //setMenuButtonsVisibility(true);\n\n m_pExit->setVisible(true);\n\n\n\n // For game mode\n\n if (m_pSingle->getState()) {\n\n m_oGameState = State::SINGLE;\n", "file_path": "game/src/main/cpp/game/Main/Game.cpp", "rank": 13, "score": 6.289704010804284 }, { "content": " // Draw poligon\n\n glDrawArrays(GL_POINTS, 0, m_nCount);\n\n checkGLError(\"Particles - glDrawArrays\");\n\n}\n\n\n\nvoid Particles::initArrays() {\n\n // Two point * count\n\n m_pPositionArray = new GLfloat[m_nCount * 2];\n\n Methods::fillArray(m_pPositionArray, 0.0f, m_nCount * 2);\n\n\n\n // 4 color * count\n\n m_pColorStartArray = new GLfloat[m_nCount * 4];\n\n Methods::fillArray(m_pColorStartArray, 0.0f, m_nCount * 4);\n\n\n\n // 4 color * count\n\n m_pColorEndArray = new GLfloat[m_nCount * 4];\n\n Methods::fillArray(m_pColorEndArray, 0.0f, m_nCount * 4);\n\n\n\n // delta * count\n\n m_pSizeUniformArray = new GLfloat[2];\n", "file_path": "game/src/main/cpp/game/Particles/Particles.cpp", "rank": 14, "score": 6.254067697119455 }, { "content": "#include \"MakeShaders.h\"\n\n\n\n#include <stdlib.h>\n\n#include \"Common/LogGL.h\"\n\n\n\nconst char * MakeShaders::V_MAIN_SHADER = \"attribute vec4 a_Position;\"\n\n \"attribute vec2 a_Texture;\"\n\n \"varying vec2 v_Texcoord;\"\n\n \"uniform mat4 u_Matrix;\"\n\n \"void main() {\"\n\n \" v_Texcoord = a_Texture;\"\n\n \" gl_Position = u_Matrix * a_Position;\"\n\n \"}\";\n\n\n\nconst char * MakeShaders::F_MAIN_SHADER = \"precision mediump float;\"\n\n \"uniform sampler2D u_Texture;\"\n\n \"varying vec2 v_Texcoord;\"\n\n \"void main() {\"\n\n \" gl_FragColor = texture2D(u_Texture, v_Texcoord);\"\n\n \"}\";\n", "file_path": "game/src/main/cpp/game/Shaders/MakeShaders.cpp", "rank": 15, "score": 6.220107209966895 }, { "content": "}\n\n\n\nvoid Plume::initArrays() {\n\n // Two point * count\n\n m_pPositionArray = new GLfloat[MAX_COUNT * 2];\n\n Methods::fillArray(m_pPositionArray, 0.0f, MAX_COUNT * 2);\n\n\n\n // Delta array for mix\n\n m_pDeltaArray = new GLfloat[MAX_COUNT];\n\n for (int i = 0; i < MAX_COUNT; i++) {\n\n m_pDeltaArray[i] = Methods::getShortRandom() * 0.9;\n\n }\n\n\n\n // 4 color * count\n\n m_pColorStartArray = new GLfloat[MAX_COUNT * 4];\n\n Methods::fillArray(m_pColorStartArray, 0.0f, MAX_COUNT * 4);\n\n\n\n // 4 color * count\n\n m_pColorEndArray = new GLfloat[MAX_COUNT * 4];\n\n Methods::fillArray(m_pColorEndArray, 0.0f, MAX_COUNT * 4);\n", "file_path": "game/src/main/cpp/game/Particles/Plume.cpp", "rank": 16, "score": 6.21189231300666 }, { "content": " highQuality();\n\n } else {\n\n lowQuality();\n\n }\n\n }\n\n}\n\n\n\nvoid Game::lowQuality() {\n\n // Background stars\n\n m_pParticles->setParticlesCount(800);\n\n m_pParticles->setParticlesSize(4.0f);\n\n m_pParticles->setSettings();\n\n\n\n // Background shape\n\n m_pShape->setParticlesCount(7000);\n\n m_pShape->setParticlesSize(5.0f);\n\n m_pShape->setSettings();\n\n\n\n // Balls effects\n\n m_pSplash->setParticlesCount(50);\n", "file_path": "game/src/main/cpp/game/Main/Game.cpp", "rank": 17, "score": 6.119105007598805 }, { "content": " m_pSplash->setParticlesCount(200);\n\n m_pSplash->setParticlesSize(12.0f);\n\n m_pSplash->setSettings();\n\n\n\n m_pPlume->setParticlesCount(300);\n\n m_pPlume->setParticlesSize(10.0f);\n\n m_pPlume->setSettings();\n\n}\n\n\n\n// -------------------------------------------------------------------------------------------------\n\n// SINGLE BLOCK\n\nvoid Game::drawFrameForSingle() {\n\n renderSingleObjects();\n\n renderSingleInterface();\n\n}\n\n\n\nvoid Game::logicSingle() {\n\n\n\n // Check buttons and move for player\n\n if (m_pLeft->getState() && !m_pPlayer->collision(m_pField)) {\n", "file_path": "game/src/main/cpp/game/Main/Game.cpp", "rank": 18, "score": 6.107834737868268 }, { "content": "#include <string.h>\n\n#include <Common/Methods.h>\n\n#include \"Particles.h\"\n\n\n\nParticles::Particles(GLuint count,\n\n GLuint programId,\n\n GLuint textureId,\n\n GLuint randomPositionAttr,\n\n GLuint randomSpeedAttr,\n\n GLuint randomRadiusAttr,\n\n GLuint deltaAttr,\n\n GLuint colorStartAttr,\n\n GLuint colorEndAttr,\n\n GLuint sizeUniform,\n\n GLuint totalDeltaSpeedUniform) : m_nCount(count),\n\n m_nProgramID(programId),\n\n m_nTextureId(textureId),\n\n m_nRandomPositionAttr(randomPositionAttr),\n\n m_nRandomSpeedAttr(randomSpeedAttr),\n\n m_nRandomRadiusAttr(randomRadiusAttr),\n", "file_path": "game/src/main/cpp/game/Particles/Particles.cpp", "rank": 19, "score": 6.080347759983883 }, { "content": " m_pSplash->setParticlesSize(3.0f);\n\n m_pSplash->setSettings();\n\n\n\n m_pPlume->setParticlesCount(70);\n\n m_pPlume->setParticlesSize(3.0f);\n\n m_pPlume->setSettings();\n\n}\n\n\n\nvoid Game::highQuality() {\n\n // Background stars\n\n m_pParticles->setParticlesCount(3000);\n\n m_pParticles->setParticlesSize(10.0f);\n\n m_pParticles->setSettings();\n\n\n\n // Background shape\n\n m_pShape->setParticlesCount(20000);\n\n m_pShape->setParticlesSize(8.0f);\n\n m_pShape->setSettings();\n\n\n\n // Balls effects\n", "file_path": "game/src/main/cpp/game/Main/Game.cpp", "rank": 22, "score": 5.699754102808782 }, { "content": "{\n\n LOGI(\"Plume::Plume()\");\n\n m_bIsVisible = true;\n\n m_fPointSize = MAX_SIZE;\n\n initArrays();\n\n}\n\n\n\nPlume::~Plume() {\n\n LOGI(\"Plume::~Plume()\");\n\n deleteObjects();\n\n}\n\n\n\nvoid Plume::render() {\n\n // Need draw this object?\n\n if (!m_bIsVisible) {\n\n return;\n\n }\n\n\n\n setValues();\n\n\n", "file_path": "game/src/main/cpp/game/Particles/Plume.cpp", "rank": 24, "score": 5.5252108623776195 }, { "content": " setDefaultPosition();\n\n m_fDX = 0.0f;\n\n m_bIsOut = true;\n\n return Object::NONE;\n\n }\n\n\n\n return Object::NONE;\n\n}\n\n\n\nvoid Ball::increaseSpeed() {\n\n if (m_nSpeed < 100) {\n\n //if (fabsf(m_fDY) < INCREASE_SPEED_TO * 0.5f) {\n\n ++m_nSpeed;\n\n\n\n if (m_fDY > 0) {\n\n m_fDY += DELTA_SPEED * 0.8f;\n\n } else {\n\n m_fDY -= DELTA_SPEED * 0.8f;\n\n }\n\n }\n", "file_path": "game/src/main/cpp/game/Graphic/Objects/Ball/Ball.cpp", "rank": 25, "score": 5.5252108623776195 }, { "content": "#include \"Plume.h\"\n\n\n\nPlume::Plume(GLuint count,\n\n GLuint programID,\n\n GLuint textureID,\n\n GLuint positionAttr,\n\n GLuint colorStartAttr,\n\n GLuint colorEndAttr,\n\n GLuint deltaAttr,\n\n GLuint sizeUniform ) : m_nCount(count),\n\n m_nProgramID(programID),\n\n m_nTextureID(textureID),\n\n m_nPositionAttr(positionAttr),\n\n m_nColorStartAttr(colorStartAttr),\n\n m_nColorEndAttr(colorEndAttr),\n\n m_nDeltaAttr(deltaAttr),\n\n m_nSizeUniform(sizeUniform),\n\n MAX_COUNT(count),\n\n MAX_SIZE(7.0f),\n\n MIN_SIZE(2.0f)\n", "file_path": "game/src/main/cpp/game/Particles/Plume.cpp", "rank": 26, "score": 5.5230864894942515 }, { "content": " m_fParticlesSpeed = 0.005f;\n\n // Current speed\n\n m_fTotalDeltaSpeed = 0.0f;\n\n\n\n // Init colors\n\n m_fArrayColor = new GLfloat[m_nCount * 4];\n\n m_fColorParts = COLOR_EQUALS_PARTS;\n\n setColor();\n\n //setColorLight();\n\n\n\n // Initial position\n\n m_fArrayPosition = new GLfloat[m_nCount];\n\n for (int i = 0; i < m_nCount; i++) {\n\n m_fArrayPosition[i] = (GLfloat)i;\n\n }\n\n\n\n //LOGI(\"Shape::initArrays - ARGS(); %ff, %ff, %ff, %ff\", arguments[0], arguments[1], arguments[2], arguments[3]);\n\n}\n\n\n\nvoid Shape::setValues() {\n", "file_path": "game/src/main/cpp/game/Particles/Shape.cpp", "rank": 27, "score": 5.476828731724894 }, { "content": "\n\n // Random delta\n\n m_pRandomArrayDelta = new GLfloat[m_nCount];\n\n for (int i = 0; i < m_nCount; i++) {\n\n m_pRandomArrayDelta[i] = Methods::getShortRandom();\n\n }\n\n}\n\n\n\nvoid Particles::setValues() {\n\n if (m_nTotalDeltaSpeed > 1000.0f || m_nTotalDeltaSpeed < 0.0f) {\n\n m_nDeltaSpeed *= -1.0f;\n\n }\n\n\n\n m_nTotalDeltaSpeed = m_nTotalDeltaSpeed + m_nDeltaSpeed;\n\n\n\n for (int i = 0; i < m_nCount; i++) {\n\n // Color start\n\n m_pColorStartArray[i * 4] = Methods::getShortRandom() * 0.5f;\n\n m_pColorStartArray[i * 4 + 1] = Methods::getShortRandom() * 0.5f;\n\n m_pColorStartArray[i * 4 + 2] = Methods::getShortRandom() * 0.5f;\n", "file_path": "game/src/main/cpp/game/Particles/Particles.cpp", "rank": 28, "score": 5.239408246255248 }, { "content": " SLDataSink dataSink;\n\n dataSink.pLocator = &dataLocatorOut;\n\n dataSink.pFormat = NULL;\n\n\n\n const SLuint32 BGMPlayerIDCount = 2;\n\n const SLInterfaceID BGMPlayerIDs[] = { SL_IID_PLAY, SL_IID_SEEK };\n\n const SLboolean BGMPlayerReqs[] = { SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE };\n\n\n\n SLresult result = (*m_oInterface)->CreateAudioPlayer(m_oInterface,\n\n &soundPack.player,\n\n &dataSource,\n\n &dataSink,\n\n BGMPlayerIDCount,\n\n BGMPlayerIDs,\n\n BGMPlayerReqs);\n\n\n\n if (result != SL_RESULT_SUCCESS) {\n\n LOGE(\"OSLSound::createAudioPlayer - can not create audio player %d\", result);\n\n soundPack.player = nullptr;\n\n return result;\n", "file_path": "game/src/main/cpp/game/Sound/OSLSound.cpp", "rank": 29, "score": 4.9603143701979215 }, { "content": "#ifndef GAME_H\n\n#define GAME_H\n\n\n\n#include <jni.h>\n\n#include <stdlib.h>\n\n#include <string>\n\n#include <stdlib.h>\n\n#include <algorithm>\n\n#include <unistd.h>\n\n\n\n#include \"../Graphic/Objects/Platform/Enemy.h\"\n\n#include \"../Graphic/Objects/Ball/Ball.h\"\n\n#include \"../Graphic/Objects/Platform/Platform.h\"\n\n#include \"../Graphic/Objects/Object.h\"\n\n#include \"../Graphic/Controls/Label.h\"\n\n#include \"../Graphic/Controls/Button.h\"\n\n#include \"../Particles/Particles.h\"\n\n#include \"../Particles/Splash.h\"\n\n#include \"../Particles/Plume.h\"\n\n#include \"../Particles/Shape.h\"\n", "file_path": "game/src/main/cpp/game/Main/Game.h", "rank": 30, "score": 4.923558320911423 }, { "content": "\t\t// If button is switch - set reverse state\n\n\t\tif (m_bIsSwitch) {\n\n\t\t\tsetTextureCoords(m_bIsPressed = m_bIsPressed ? false : true);\n\n\t\t} else {\n\n\t\t\tsetTextureCoords(m_bIsPressed = true);\n\n\t\t}\n\n\t} else if (m_bIsPressed && !m_bIsSwitch && m_nButtonId == buttonsId) {\n\n\t\t// If buttons lost focus\n\n\t\tsetTextureCoords(m_bIsPressed = false);\n\n\t\tm_nButtonId = -1;\n\n\t}\n\n\n\n\treturn m_bIsPressed;\n\n}\n\n\n\nvoid Button::setTextureCoords(bool isPressed) {\n\n\t// Set texture for button\n\n\tif (isPressed) {\n\n\t\tMatrix::setTextureCoords(getTextureCoordinates(), m_nTextureX, m_nTextureY, m_nPositionOn);\n\n\t} else {\n", "file_path": "game/src/main/cpp/game/Graphic/Controls/Button.cpp", "rank": 31, "score": 4.888673134831925 }, { "content": " template <class A, class B>\n\n static void fillArray(A * array, B content, int count) {\n\n for (int i = 0; i < count; i++) {\n\n array[i] = (A)content;\n\n }\n\n }\n\n\n\n static std::string fillLeft(std::string stringForFill, char symbol, int toLength) {\n\n int difference = toLength - stringForFill.length();\n\n if (difference > 0) {\n\n std::string buf(difference, symbol);\n\n stringForFill = buf + stringForFill;\n\n }\n\n\n\n return stringForFill;\n\n }\n\n\n\n static std::string intToString(int number) {\n\n std::string result = number == 0? \"0\" : \"\";\n\n\n", "file_path": "game/src/main/cpp/game/Common/Methods.h", "rank": 32, "score": 4.879060612268331 }, { "content": "#ifndef BALL_H\n\n#define BALL_H\n\n\n\n#include <typeinfo>\n\n#include <queue>\n\n#include <Particles/Splash.h>\n\n\n\n#include \"../../../Common/Intersect.h\"\n\n#include \"../../../Common/Structures.h\"\n\n#include \"../Platform/Platform.h\"\n\n#include \"../Object.h\"\n\n\n", "file_path": "game/src/main/cpp/game/Graphic/Objects/Ball/Ball.h", "rank": 33, "score": 4.831765421204919 }, { "content": "#ifndef LABEL_H\n\n#define LABEL_H\n\n\n\n#include <string>\n\n#include <vector>\n\n#include <algorithm>\n\n\n\n#include \"../../AbstractClasses/Render.h\"\n\n#include \"../../Common/Methods.h\"\n\n#include \"../../Common/Structures.h\"\n\n#include \"../View.h\"\n\n\n\n\n", "file_path": "game/src/main/cpp/game/Graphic/Controls/Label.h", "rank": 34, "score": 4.831765421204919 }, { "content": "}\n\n\n\nvoid Plume::setPlumePoints(std::queue<GLfloat> * points) {\n\n if (points->size() > 0 && points->size() < MAX_COUNT && points->size() % 2 == 0) {\n\n std::queue<GLfloat> plumePoints(*points);\n\n unsigned int halfQueue = points->size() / 2;\n\n unsigned int pointsPerStep = MAX_COUNT / halfQueue;\n\n m_nCount = pointsPerStep * halfQueue;\n\n unsigned int i = 0;\n\n float dispersion = 0.008f;\n\n float alpha = 0.005f;\n\n\n\n while(plumePoints.size() > 0) {\n\n GLfloat x = plumePoints.front();\n\n plumePoints.pop();\n\n GLfloat y = plumePoints.front();\n\n plumePoints.pop();\n\n\n\n for (int j = 0; j < pointsPerStep; j++, i++) {\n\n // Set plume position\n", "file_path": "game/src/main/cpp/game/Particles/Plume.cpp", "rank": 35, "score": 4.798003120903964 }, { "content": "#ifndef INTERSECT_H\n\n#define INTERSECT_H\n\n\n\n#include <GLES2/gl2.h>\n\n#include <cmath>\n\n#include <vector>\n\n\n\n#include \"Methods.h\"\n\n#include \"Structures.h\"\n\n\n", "file_path": "game/src/main/cpp/game/Common/Intersect.h", "rank": 36, "score": 4.7619720071934095 }, { "content": "#include \"OSLSound.h\"\n\n\n\nconst SLuint32 OSLSound::NUM_OPTIONS = 0;\n\nconst SLuint32 OSLSound::NUM_INTERFACES = 1;\n\nconst SLInterfaceID OSLSound::INTERFACE_ID[1] = { SL_IID_ENGINE };\n\nconst SLboolean OSLSound::INTERFACE_REQUIRED[1] = { SL_BOOLEAN_TRUE };\n\nconst SLuint32 OSLSound::OUTPUT_MIX_ID_COUNT = 0;\n\nconst SLInterfaceID OSLSound::OUTPUT_MIX_IDS[0] = {};\n\nconst SLboolean OSLSound::OUTPUT_MIX_REQUIRED[0] = {};\n\n\n\nOSLSound::OSLSound(JNIEnv * env, jobject assetsManager, bool isSoundOn) : m_bIsSoundOn(isSoundOn) {\n\n LOGI(\"OSLSound::OSLSound()\");\n\n if (init(env, assetsManager)) {\n\n create();\n\n }\n\n}\n\n\n\nOSLSound::~OSLSound() {\n\n LOGI(\"OSLSound::~OSLSound()\");\n\n\n", "file_path": "game/src/main/cpp/game/Sound/OSLSound.cpp", "rank": 37, "score": 4.757468395210031 }, { "content": "#ifndef OSL_SOUND_H\n\n#define OSL_SOUND_H\n\n\n\n#include <map>\n\n#include <stddef.h>\n\n#include <SLES/OpenSLES.h>\n\n#include <SLES/OpenSLES_Android.h>\n\n#include <jni.h>\n\n#include <android/asset_manager.h>\n\n#include <android/asset_manager_jni.h>\n\n\n\n#include \"../Common/LogGL.h\"\n\n\n", "file_path": "game/src/main/cpp/game/Sound/OSLSound.h", "rank": 38, "score": 4.74767385066071 }, { "content": "#ifndef TEXTURES_MANAGER_H\n\n#define TEXTURES_MANAGER_H\n\n\n\n#include <string>\n\n#include <map>\n\n#include <GLES2/gl2.h>\n\n#include <jni.h>\n\n#include <android/asset_manager.h>\n\n#include <android/asset_manager_jni.h>\n\n#include \"../Common/LogGL.h\"\n\n\n", "file_path": "game/src/main/cpp/game/Textures/TexturesManager.h", "rank": 39, "score": 4.746407469344391 }, { "content": "#ifndef VIEW_H\n\n#define VIEW_H\n\n\n\n#include <GLES2/gl2.h>\n\n#include <iostream>\n\n#include <typeinfo>\n\n\n\n#include \"../AbstractClasses/Render.h\"\n\n#include \"../Common/LogGL.h\"\n\n#include \"../Common/Structures.h\"\n\n\n", "file_path": "game/src/main/cpp/game/Graphic/View.h", "rank": 40, "score": 4.744720011454438 }, { "content": "#ifndef METHODS_H\n\n#define METHODS_H\n\n\n\n#include <ctime>\n\n#include <stdlib.h>\n\n#include <string>\n\n#include <GLES2/gl2.h>\n\n\n", "file_path": "game/src/main/cpp/game/Common/Methods.h", "rank": 42, "score": 4.666800393019614 }, { "content": "#ifndef SHAPE_H\n\n#define SHAPE_H\n\n\n\n#include <GLES2/gl2.h>\n\n#include <math.h>\n\n#include \"../AbstractClasses/Render.h\"\n\n#include \"../Common/LogGL.h\"\n\n#include \"../Common/Methods.h\"\n\n\n", "file_path": "game/src/main/cpp/game/Particles/Shape.h", "rank": 43, "score": 4.665499209429646 }, { "content": "#include \"../Shaders/MakeShaders.h\"\n\n#include \"../Graphic/View.h\"\n\n#include \"../Textures/TexturesManager.h\"\n\n#include \"../Common/Structures.h\"\n\n#include \"../Common/LogGL.h\"\n\n#include \"../Sound/OSLSound.h\"\n\n\n\n#include \"Main/State.h\"\n\n\n\n/*\n\n * TODO Refactoring jni\n\n * TODO Refactoring opengl\n\n * TODO Refactoring opensl\n\n * TODO Refactoring object structure\n\n * */\n", "file_path": "game/src/main/cpp/game/Main/Game.h", "rank": 44, "score": 4.650557938099918 }, { "content": "#ifndef PLATFORM_H\n\n#define PLATFORM_H\n\n\n\n#include \"../../../Common/Methods.h\"\n\n#include \"../../../Common/Intersect.h\"\n\n#include \"../../../Common/Structures.h\"\n\n#include \"../Object.h\"\n\n\n", "file_path": "game/src/main/cpp/game/Graphic/Objects/Platform/Platform.h", "rank": 45, "score": 4.61998915774242 }, { "content": "#ifndef STRUCTURES_H\n\n#define STRUCTURES_H\n\n\n\n#include <GLES2/gl2.h>\n\n#include <vector>\n\n#include <cmath>\n\n\n\n#include \"Methods.h\"\n\n\n\n// Common types\n\ntemplate<class A>\n", "file_path": "game/src/main/cpp/game/Common/Structures.h", "rank": 46, "score": 4.61998915774242 }, { "content": "#ifndef PARTICLES_H\n\n#define PARTICLES_H\n\n\n\n#include <GLES2/gl2.h>\n\n#include <cmath>\n\n\n\n#include \"../AbstractClasses/Render.h\"\n\n#include \"../Common/LogGL.h\"\n\n\n", "file_path": "game/src/main/cpp/game/Particles/Particles.h", "rank": 47, "score": 4.574107694334858 }, { "content": "#ifndef SPLASH_H\n\n#define SPLASH_H\n\n\n\n\n\n#include <GLES2/gl2.h>\n\n#include \"../AbstractClasses/Render.h\"\n\n#include \"../Common/LogGL.h\"\n\n#include \"../Common/Methods.h\"\n\n\n", "file_path": "game/src/main/cpp/game/Particles/Splash.h", "rank": 48, "score": 4.551507013321245 }, { "content": " void renderMultiObjects();\n\n\n\n void drawFrameMenu();\n\n\n\n void logicMenu();\n\n\n\n void lowQuality();\n\n\n\n void highQuality();\n\n};\n\n\n\n\n\n#endif\n", "file_path": "game/src/main/cpp/game/Main/Game.h", "rank": 49, "score": 4.504486047857223 }, { "content": "\n\n\n\n public:\n\n\n\n void setNumber(std::string number);\n\n\n\n void render();\n\n\n\n void clearLabels();\n\n\n\n\n\n private:\n\n\n\n void init();\n\n\n\n};\n\n\n\n#endif\n", "file_path": "game/src/main/cpp/game/Graphic/Controls/Label.h", "rank": 50, "score": 4.459647082566797 }, { "content": "#ifndef BUTTON_H\n\n#define BUTTON_H\n\n\n\n#include \"../../Common/Structures.h\"\n\n#include \"../../Common/LogGL.h\"\n\n#include \"../View.h\"\n\n\n", "file_path": "game/src/main/cpp/game/Graphic/Controls/Button.h", "rank": 51, "score": 4.4580761123772605 }, { "content": "#ifndef ENEMY_H\n\n#define ENEMY_H\n\n\n\n#include \"../../../Common/Structures.h\"\n\n#include \"../Ball/Ball.h\"\n\n#include \"../Platform/Platform.h\"\n\n\n", "file_path": "game/src/main/cpp/game/Graphic/Objects/Platform/Enemy.h", "rank": 52, "score": 4.4580761123772605 }, { "content": "\n\n void setSound(bool isSoundOn) {\n\n m_bIsSoundOn = isSoundOn;\n\n }\n\n\n\n bool isSoundOn() {\n\n return m_bIsSoundOn;\n\n }\n\n\n\n void play(SOUND_TYPE soundType);\n\n\n\n void stop(SOUND_TYPE soundType);\n\n\n\n void pauseAll();\n\n\n\n void stopAll();\n\n\n\n void pauseStopAll();\n\n\n\n\n", "file_path": "game/src/main/cpp/game/Sound/OSLSound.h", "rank": 53, "score": 4.412409488472109 }, { "content": "\n\n // Color end\n\n glVertexAttribPointer(m_nColorEndAttr, 4, GL_FLOAT, GL_FALSE, 0, m_pColorEndArray);\n\n checkGLError(\"Plume - glVertexAttribPointer - m_nColorEndAttr\");\n\n glEnableVertexAttribArray(m_nColorEndAttr);\n\n checkGLError(\"Plume - glVertexAttribPointer - m_nColorEndAttr - enabled\");\n\n\n\n // Delta m_pSingleSpeed\n\n glVertexAttribPointer(m_nDeltaAttr, 1, GL_FLOAT, GL_FALSE, 0, m_pDeltaArray);\n\n checkGLError(\"Plume - glVertexAttribPointer - m_nDeltaAttr\");\n\n glEnableVertexAttribArray(m_nDeltaAttr);\n\n checkGLError(\"Plume - glVertexAttribPointer - m_nDeltaAttr - enabled\");\n\n\n\n // Size\n\n glUniform2f(m_nSizeUniform, m_pSizeArray[0], m_pSizeArray[1]);\n\n checkGLError(\"Plume - glUniform2f - m_nSizeUniform\");\n\n\n\n // Draw poligon\n\n glDrawArrays(GL_POINTS, 0, m_nCount);\n\n checkGLError(\"Plume - glDrawArrays\");\n", "file_path": "game/src/main/cpp/game/Particles/Plume.cpp", "rank": 54, "score": 4.400978218315416 }, { "content": " void renderBackground();\n\n\n\n GLfloat * setBordDownPosition(GLfloat * positionCoords, bool isInverse);\n\n\n\n GLfloat * setBordUpPosition(GLfloat * positionCoords);\n\n\n\n void drawFrameForSingle();\n\n\n\n void logicSingle();\n\n\n\n void renderSingleInterface();\n\n\n\n void renderSingleObjects();\n\n\n\n void drawFrameForMulti();\n\n\n\n void logicMulti();\n\n\n\n void renderMultiInterface();\n\n\n", "file_path": "game/src/main/cpp/game/Main/Game.h", "rank": 55, "score": 4.345387399081487 }, { "content": "#ifndef PLUME_H\n\n#define PLUME_H\n\n\n\n#include <queue>\n\n#include \"Splash.h\"\n\n\n", "file_path": "game/src/main/cpp/game/Particles/Plume.h", "rank": 56, "score": 4.282267903307795 }, { "content": "#ifndef OBJECT_H\n\n#define OBJECT_H\n\n\n\n#include \"../../Common/Structures.h\"\n\n#include \"../View.h\"\n\n\n", "file_path": "game/src/main/cpp/game/Graphic/Objects/Object.h", "rank": 57, "score": 4.2428205007634645 }, { "content": " m_nDeltaAttr(deltaAttr),\n\n m_nColorStartAttr(colorStartAttr),\n\n m_nColorEndAttr(colorEndAttr),\n\n m_nSizeUniform(sizeUniform),\n\n m_nTotalDeltaSpeedUniform(totalDeltaSpeedUniform)\n\n{\n\n LOGI(\"Particles::Particles()\");\n\n m_bIsVisible = true;\n\n m_nTotalDeltaSpeed = 0.0f;\n\n m_nDeltaSpeed = 0.01f;\n\n m_fPointSize = 7.0f;\n\n initArrays();\n\n}\n\n\n\nParticles::~Particles() {\n\n LOGI(\"Particles::~Particles()\");\n\n deleteObjects();\n\n}\n\n\n\nvoid Particles::render() {\n", "file_path": "game/src/main/cpp/game/Particles/Particles.cpp", "rank": 58, "score": 4.184397767800025 }, { "content": " m_pSizeUniformArray[0] = 2.0f;\n\n m_pSizeUniformArray[1] = m_fPointSize;\n\n\n\n // Random coords\n\n m_pRandomArrayCoords = new GLfloat[m_nCount * 2];\n\n for (int i = 0; i < m_nCount * 2; i++) {\n\n m_pRandomArrayCoords[i] = Methods::getFullRandom() * 1.1f;\n\n }\n\n\n\n // Random radius\n\n m_pRandomArrayRadius = new GLfloat[m_nCount];\n\n for (int i = 0; i < m_nCount; i++) {\n\n m_pRandomArrayRadius[i] = Methods::getShortRandom();\n\n }\n\n\n\n // Random m_pSingleSpeed\n\n m_pRandomArraySpeed = new GLfloat[m_nCount];\n\n for (int i = 0; i < m_nCount; i++) {\n\n m_pRandomArraySpeed[i] = Methods::getShortRandom() * 0.5f;\n\n }\n", "file_path": "game/src/main/cpp/game/Particles/Particles.cpp", "rank": 59, "score": 4.174142774165214 }, { "content": "#ifndef MAKE_SHADERS_H\n\n#define MAKE_SHADERS_H\n\n\n\n#include <GLES2/gl2.h>\n\n#include <string>\n\n\n", "file_path": "game/src/main/cpp/game/Shaders/MakeShaders.h", "rank": 60, "score": 4.166066543432441 }, { "content": "\n\n void resetTimer();\n\n\n\n void setVisible(bool isVisible) {\n\n m_pIsVisible = isVisible;\n\n }\n\n\n\n bool getVisible() {\n\n return m_pIsVisible;\n\n }\n\n\n\n\n\n private:\n\n\n\n void setValues();\n\n\n\n};\n\n\n\n#endif\n", "file_path": "game/src/main/cpp/game/Particles/Splash.h", "rank": 61, "score": 4.163292661204323 }, { "content": "include ':game'\n", "file_path": "settings.gradle", "rank": 63, "score": 4.03028258828396 }, { "content": " GLuint starCenter,\n\n GLuint starRadius,\n\n GLuint starArguments,\n\n GLuint starSize,\n\n GLuint starTotalDeltaSpeed);\n\n\n\n virtual ~Shape();\n\n\n\n\n\n public:\n\n\n\n void render();\n\n\n\n void setSettings();\n\n\n\n void setColor();\n\n\n\n void setColorLight();\n\n\n\n void setColorPart(GLuint first, GLuint second);\n", "file_path": "game/src/main/cpp/game/Particles/Shape.h", "rank": 64, "score": 4.022107068571902 }, { "content": "\n\n public:\n\n\n\n Game(JNIEnv * env, jobject pngManager, jobject assetManager);\n\n\n\n ~Game();\n\n\n\n void start();\n\n\n\n void stop();\n\n\n\n void screen(uint width, uint height);\n\n\n\n void step();\n\n\n\n bool isBackPress();\n\n\n\n bool action(uint x, uint y, int id, bool isPressed);\n\n\n\n GLuint getPolygons() {\n", "file_path": "game/src/main/cpp/game/Main/Game.h", "rank": 65, "score": 3.953761311936352 }, { "content": " GLint textureAttr,\n\n GLint transformationAttr,\n\n GLfloat * verticesCoords,\n\n GLfloat * textureCoords,\n\n GLfloat * matrixCoords);\n\n\n\n virtual ~Object();\n\n\n\n\n\n public:\n\n\n\n void setDefaultPosition();\n\n\n\n void move();\n\n\n\n void moveY(GLfloat y);\n\n\n\n void moveX(GLfloat x);\n\n\n\n virtual CROSS_SIDE collision(Object * object) = 0;\n", "file_path": "game/src/main/cpp/game/Graphic/Objects/Object.h", "rank": 66, "score": 3.8660512190068292 }, { "content": " return m_nSpritesRandomRadius;\n\n }\n\n\n\n GLint getSpritesTotalDeltaSpeed() const {\n\n return m_nSpritesTotalDeltaSpeed;\n\n }\n\n\n\n\n\n private:\n\n\n\n bool init(JNIEnv * env, jobject pngManager, jobject assetManager);\n\n\n\n void setDefault();\n\n\n\n void setMenuButtonsVisibility(bool isVisible);\n\n\n\n void createTextureObjects();\n\n\n\n void destroyTextureObjects();\n\n\n", "file_path": "game/src/main/cpp/game/Main/Game.h", "rank": 67, "score": 3.8660512190068292 }, { "content": "Shape::~Shape() {\n\n LOGI(\"Shape::~Shape()\");\n\n // Off attributes\n\n //glDisableVertexAttribArray(m_nStarsAngle);\n\n //glDisableVertexAttribArray(m_nStarColor);\n\n deleteObjects();\n\n}\n\n\n\nvoid Shape::render() {\n\n //LOGI(\"Shape::render(); Cx: %f; Cy: %f; Cc: %d; Rx: %f; Ry: %f;\", CENTER_X, CENTER_Y, count, radius[0], radius[1]);\n\n // Need draw this object?\n\n if (!m_bIsVisible) {\n\n return;\n\n }\n\n\n\n setValues();\n\n\n\n // Use render shader program\n\n glUseProgram(m_nProgramID);\n\n checkGLError(\"Graphic - glUseProgram\");\n", "file_path": "game/src/main/cpp/game/Particles/Shape.cpp", "rank": 68, "score": 3.853701751677863 }, { "content": "void Object::move() {\n\n for (int i = 0; i < 4; i++) {\n\n m_pPolygonCoordinates[i * 2] += m_fDX;\n\n m_pPolygonCoordinates[i * 2 + 1] += m_fDY;\n\n }\n\n}\n\n\n\nvoid Object::moveX(GLfloat x) {\n\n for (int i = 0; i < 4; i++) {\n\n m_pPolygonCoordinates[i * 2] += x;\n\n }\n\n}\n\n\n\nvoid Object::moveY(GLfloat y) {\n\n for (int i = 0; i < 4; i++) {\n\n m_pPolygonCoordinates[i * 2 + 1] += y;\n\n }\n\n}\n\n\n\nvoid Object::setDefaultPosition() {\n\n for (int i = 0; i < 8; i++) {\n\n m_pPolygonCoordinates[i] = m_fDefaultCoords[i];\n\n }\n\n\n\n m_fDY *= Methods::getRandSign();\n\n //m_fDY *= 1.0f;\n\n}", "file_path": "game/src/main/cpp/game/Graphic/Objects/Object.cpp", "rank": 69, "score": 3.848974119451969 }, { "content": " GLuint randomSpeedAttr,\n\n GLuint randomRadiusAttr,\n\n GLuint deltaAttr,\n\n GLuint colorStartAttr,\n\n GLuint colorEndAttr,\n\n GLuint sizeUniform,\n\n GLuint totalDeltaSpeedUniform);\n\n\n\n virtual ~Particles();\n\n\n\n\n\n public:\n\n\n\n void initArrays();\n\n\n\n void setSettings();\n\n\n\n void render();\n\n\n\n void deleteObjects();\n", "file_path": "game/src/main/cpp/game/Particles/Particles.h", "rank": 70, "score": 3.7986361768153722 }, { "content": " checkGLError(\"Particles - glVertexAttribPointer - m_nRandomPositionAttr - enabled\");\n\n\n\n // Speed\n\n glVertexAttribPointer(m_nRandomSpeedAttr, 1, GL_FLOAT, GL_FALSE, 0, m_pRandomArraySpeed);\n\n checkGLError(\"Particles - glVertexAttribPointer - m_nRandomSpeedAttr\");\n\n glEnableVertexAttribArray(m_nRandomSpeedAttr);\n\n checkGLError(\"Particles - glVertexAttribPointer - m_nRandomSpeedAttr - enabled\");\n\n\n\n // Radius\n\n glVertexAttribPointer(m_nRandomRadiusAttr, 1, GL_FLOAT, GL_FALSE, 0, m_pRandomArrayRadius);\n\n checkGLError(\"Particles - glVertexAttribPointer - m_nRandomRadiusAttr\");\n\n glEnableVertexAttribArray(m_nRandomRadiusAttr);\n\n checkGLError(\"Particles - glVertexAttribPointer - m_nRandomRadiusAttr - enabled\");\n\n\n\n // Delta\n\n glVertexAttribPointer(m_nDeltaAttr, 1, GL_FLOAT, GL_FALSE, 0, m_pRandomArrayDelta);\n\n checkGLError(\"Particles - glVertexAttribPointer - m_nDeltaAttr\");\n\n glEnableVertexAttribArray(m_nDeltaAttr);\n\n checkGLError(\"Particles - glVertexAttribPointer - m_nDeltaAttr - enabled\");\n\n\n", "file_path": "game/src/main/cpp/game/Particles/Particles.cpp", "rank": 71, "score": 3.6084654192880734 }, { "content": "#include \"View.h\"\n\n\n\nView::View (GLuint textureID,\n\n GLuint programID,\n\n GLint positionAttr,\n\n GLint textureAttr,\n\n GLint transformationAttr,\n\n GLfloat * polygonCoordinates,\n\n GLfloat * textureCoordinates,\n\n GLfloat * transformationMatrix) : m_nTextureId(textureID),\n\n m_nProgramId(programID),\n\n m_nPositionAttr(positionAttr),\n\n m_nTextureAttr(textureAttr),\n\n m_nTransformationAttr(transformationAttr),\n\n m_pPolygonCoordinates(polygonCoordinates),\n\n m_pTextureCoordinates(textureCoordinates),\n\n m_pTransformationMatrix(transformationMatrix)\n\n{\n\n LOGI(\"View::View()\");\n\n m_bIsVisible = true;\n", "file_path": "game/src/main/cpp/game/Graphic/View.cpp", "rank": 72, "score": 3.5958243649864263 }, { "content": "\n\n // Points size\n\n m_pSizeArray = new GLfloat[2];\n\n m_pSizeArray[0] = MIN_SIZE;\n\n m_pSizeArray[1] = m_fPointSize;\n\n}\n\n\n\nvoid Plume::setValues() {\n\n for (int i = 0; i < MAX_COUNT; i++) {\n\n // Color start\n\n m_pColorStartArray[i * 4] = Methods::getShortRandom() * 0.5f;\n\n m_pColorStartArray[i * 4 + 1] = Methods::getShortRandom() * 0.5f;\n\n m_pColorStartArray[i * 4 + 2] = Methods::getShortRandom() * 0.5f;\n\n m_pColorStartArray[i * 4 + 3] = 0.1f;\n\n\n\n // Color end\n\n m_pColorEndArray[i * 4] = Methods::getShortRandom() + 0.5f;\n\n m_pColorEndArray[i * 4 + 1] = Methods::getShortRandom() + 0.5f;\n\n m_pColorEndArray[i * 4 + 2] = Methods::getShortRandom() + 0.5f;\n\n }\n", "file_path": "game/src/main/cpp/game/Particles/Plume.cpp", "rank": 73, "score": 3.576546908108412 }, { "content": "\n\n Object::CROSS_SIDE collision(Object * object);\n\n\n\n bool collision(Platform * object);\n\n\n\n bool getIsOut() const {\n\n return m_bIsOut;\n\n }\n\n\n\n void setIsOut(bool isOut) {\n\n Ball::m_bIsOut = isOut;\n\n }\n\n\n\n int getSpeed() {\n\n return m_nSpeed;\n\n }\n\n\n\n void resetSpeed() {\n\n m_fDY = DEFAULT_SPEED;\n\n m_nSpeed = 0;\n", "file_path": "game/src/main/cpp/game/Graphic/Objects/Ball/Ball.h", "rank": 74, "score": 3.554941861619702 }, { "content": " int getScore() const {\n\n return m_nScore;\n\n }\n\n\n\n void setScore() {\n\n ++m_nScore;\n\n }\n\n\n\n void clearScore() {\n\n m_nScore = 0;\n\n }\n\n\n\n Object::CROSS_SIDE collision(Object * object);\n\n\n\n REBOUND_AREA getRebound(float x, float y, float width);\n\n\n\n};\n\n\n\n\n\n#endif\n", "file_path": "game/src/main/cpp/game/Graphic/Objects/Platform/Platform.h", "rank": 75, "score": 3.554941861619702 }, { "content": " }\n\n\n\n std::queue<GLfloat> * getLastPoint() {\n\n return &m_pLastPoint;\n\n }\n\n\n\n std::queue<GLfloat> * getPlumePoints() {\n\n return &m_pPlumePoints;\n\n }\n\n\n\n\n\n private:\n\n\n\n void setPreviousPoint();\n\n\n\n void setQueuePointsForPlume();\n\n\n\n Object::CROSS_SIDE collisionLeftRightWall(Object * object);\n\n\n\n Object::CROSS_SIDE collisionUpDownWall(Object * object);\n\n\n\n void increaseSpeed();\n\n};\n\n\n\n\n\n#endif\n", "file_path": "game/src/main/cpp/game/Graphic/Objects/Ball/Ball.h", "rank": 76, "score": 3.5522824744776726 }, { "content": " }\n\n\n\n buildTypes {\n\n release {\n\n minifyEnabled false\n\n proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n\n productFlavors.prod.signingConfig signingConfigs.market\n\n }\n\n\n\n debug {\n\n minifyEnabled false\n\n }\n\n\n\n applicationVariants.all { variant ->\n\n variant.outputs.all {\n", "file_path": "game/build.gradle", "rank": 77, "score": 3.5438178076499836 }, { "content": "void Label::render() {\n\n for (auto & m_oLabelLink : m_oLabelLinks) {\n\n m_oLabelLink->render();\n\n }\n\n}\n\n\n\nvoid Label::clearLabels() {\n\n for (auto & m_oLabelLink : m_oLabelLinks) {\n\n delete m_oLabelLink;\n\n }\n\n\n\n m_oLabelLinks.clear();\n\n}", "file_path": "game/src/main/cpp/game/Graphic/Controls/Label.cpp", "rank": 78, "score": 3.526170046164416 }, { "content": " if (pGame != nullptr) {\n\n pGame->start();\n\n }\n\n }\n\n\n\n JNI_METHOD(void, stop)(JNIEnv* env, jclass type) {\n\n if (pGame != nullptr) {\n\n pGame->stop();\n\n }\n\n }\n\n\n\n JNI_METHOD(void, screen)(JNIEnv* env, jclass type, jint width, jint height) {\n\n if (pGame != nullptr) {\n\n pGame->screen(width, height);\n\n }\n\n }\n\n\n\n JNI_METHOD(void, step)(JNIEnv* env, jclass type) {\n\n if (pGame != nullptr) {\n\n pGame->step();\n", "file_path": "game/src/main/cpp/game/gamelib.cpp", "rank": 79, "score": 3.5140801834900115 }, { "content": "\n\n bool getVisible() {\n\n return m_bIsVisible;\n\n }\n\n\n\n\n\n private:\n\n\n\n void setValues();\n\n\n\n};\n\n\n\n#endif\n", "file_path": "game/src/main/cpp/game/Particles/Plume.h", "rank": 80, "score": 3.505607129392221 }, { "content": " return a > b? a : b;\n\n }\n\n\n\n template <class A>\n\n inline static void swap(A & a, A & b) {\n\n A temp = b;\n\n b = a;\n\n a = temp;\n\n }\n\n};\n\n\n\n#endif\n", "file_path": "game/src/main/cpp/game/Common/Methods.h", "rank": 81, "score": 3.505607129392221 }, { "content": " GLfloat * verticesCoords,\n\n GLfloat * textureCoords,\n\n GLfloat * matrixCoords);\n\n\n\n virtual ~Enemy();\n\n\n\n\n\n public:\n\n\n\n void collision(Ball * ball);\n\n\n\n\n\n private:\n\n\n\n void setCrossHorizon(GLfloat * crossHorizonArray);\n\n};\n\n\n\n\n\n#endif\n", "file_path": "game/src/main/cpp/game/Graphic/Objects/Platform/Enemy.h", "rank": 82, "score": 3.497860219271379 }, { "content": "\n\n\n\n private:\n\n\n\n void init(JNIEnv *env, jobject assetManager, jobject bitmapManager);\n\n\n\n u_char * argb2rgba(unsigned int * pixels, int w, int h);\n\n\n\n Texture * loadTexture(JNIEnv * env, jobject bitmapManager, const char * filename);\n\n\n\n void loadTextures(JNIEnv * env, jobject bitmapManager);\n\n\n\n GLuint createTexture(Texture * texture);\n\n\n\n void createTextures();\n\n\n\n};\n\n\n\n#endif\n", "file_path": "game/src/main/cpp/game/Textures/TexturesManager.h", "rank": 83, "score": 3.495285519011384 }, { "content": " }\n\n\n\n bool getVisible() {\n\n return m_bIsVisible;\n\n }\n\n\n\n void setPolygonCoordinates(GLfloat * polygonCoordinates) {\n\n m_pPolygonCoordinates = polygonCoordinates;\n\n }\n\n\n\n void setTextureCoordinates(GLfloat * textureCoordinates) {\n\n m_pTextureCoordinates = textureCoordinates;\n\n }\n\n\n\n void setTransformationMatrix(GLfloat * transformationMatrix) {\n\n m_pTransformationMatrix = transformationMatrix;\n\n }\n\n\n\n GLfloat * getPolygonCoordinates() {\n\n return m_pPolygonCoordinates;\n", "file_path": "game/src/main/cpp/game/Graphic/View.h", "rank": 84, "score": 3.495285519011384 }, { "content": "\n\nvoid Plume::deleteObjects() {\n\n delete [] m_pPositionArray;\n\n delete [] m_pColorStartArray;\n\n delete [] m_pColorEndArray;\n\n delete [] m_pDeltaArray;\n\n delete [] m_pSizeArray;\n\n}\n\n\n\nvoid Plume::setSettings() {\n\n deleteObjects();\n\n initArrays();\n\n}", "file_path": "game/src/main/cpp/game/Particles/Plume.cpp", "rank": 86, "score": 3.4425827256998307 }, { "content": "\n\n std::for_each(m_oSoundPack.begin(), m_oSoundPack.end(), [&](std::map<SOUND_TYPE, SoundPack>::value_type &item) {\n\n createAudioPlayer(item.second);\n\n });\n\n\n\n (*m_oSoundPack[SOUND_TYPE::BACKGROUND].seek)->SetLoop(m_oSoundPack[SOUND_TYPE::BACKGROUND].seek, SL_BOOLEAN_TRUE, 0, SL_TIME_UNKNOWN);\n\n};\n\n\n\nvoid OSLSound::play(OSLSound::SOUND_TYPE soundType) {\n\n if (m_bIsSoundOn) {\n\n if (soundType != SOUND_TYPE::BACKGROUND) {\n\n (*m_oSoundPack[soundType].play)->SetPlayState(m_oSoundPack[soundType].play, SL_PLAYSTATE_STOPPED);\n\n }\n\n (*m_oSoundPack[soundType].play)->SetPlayState(m_oSoundPack[soundType].play, SL_PLAYSTATE_PLAYING);\n\n }\n\n};\n\n\n\nvoid OSLSound::stop(OSLSound::SOUND_TYPE soundType) {\n\n if (m_bIsSoundOn) {\n\n (*m_oSoundPack[soundType].play)->SetPlayState(m_oSoundPack[soundType].play, SL_PLAYSTATE_STOPPED);\n", "file_path": "game/src/main/cpp/game/Sound/OSLSound.cpp", "rank": 87, "score": 3.404353699759363 }, { "content": " float getDx() const {\n\n return m_fDX;\n\n }\n\n\n\n void setDx(float dx) {\n\n m_fDX = dx;\n\n }\n\n\n\n float getDy() const {\n\n return m_fDY;\n\n }\n\n\n\n void setDy(float dy) {\n\n m_fDY = dy;\n\n }\n\n\n\n std::vector<GLfloat> * getCrossPoints() {\n\n return &m_oCrossPoints;\n\n }\n\n\n\n};\n\n\n\n\n\n#endif\n", "file_path": "game/src/main/cpp/game/Graphic/Objects/Object.h", "rank": 88, "score": 3.389025177451261 }, { "content": "\n\n // Choose multiplayer mode\n\n m_pMulti = new Button(false,\n\n true,\n\n false,\n\n BUTTON_MENU_X_POSITION, 0.3f, BUTTON_MENU_WIDTH, BUTTON_MENU_HEIGHT, 4, 4, Matrix::EIGHT, Matrix::SEVEN,\n\n m_pTextures->getTextureId(TexturesManager::BUTTONS),\n\n m_nPolygons,\n\n m_nPolygonsPositionAttr,\n\n m_nPolygonsTextureAttr,\n\n m_nPolygonsTransformationAttr,\n\n m_pMatrix->getDefaultVerticesCoords(),\n\n m_pMatrix->getDefaultTextureCoord(),\n\n m_pMatrix->getDefaultMatrix4x4());\n\n m_oButtons.push_back(m_pMulti);\n\n m_oMenuButtons.push_back(m_pMulti);\n\n\n\n // Sound off/on\n\n m_pSound = new Button(true,\n\n true,\n", "file_path": "game/src/main/cpp/game/Main/Game.cpp", "rank": 89, "score": 3.308741265764005 }, { "content": " twoPoints->push_back(point.y);\n\n return true;\n\n }\n\n }\n\n\n\n return false;\n\n }\n\n\n\n template <class A>\n\n static bool intersectSegmentsAndLines(Line<A> * line1, Line<A> * line2, std::vector<A> * twoPoints) {\n\n Point<A> point;\n\n\n\n if (Intersect::intersect(line1, line2, &point)) {\n\n if (betweenLine(line1, point.x, point.y)) {\n\n twoPoints->push_back(point.x);\n\n twoPoints->push_back(point.y);\n\n return true;\n\n }\n\n }\n\n\n", "file_path": "game/src/main/cpp/game/Common/Intersect.h", "rank": 90, "score": 3.279514028132167 }, { "content": " private:\n\n\n\n bool init(JNIEnv * env, jobject assetManager);\n\n\n\n void create();\n\n\n\n void destroy(SLObjectItf* object);\n\n\n\n SLuint32 createAudioPlayer(SoundPack& soundPack);\n\n\n\n SoundBuffer * loadSoundFile(const char * filename);\n\n\n\n ResourceDescriptor loadResourceDescriptor(const char* path);\n\n};\n\n\n\n#endif\n", "file_path": "game/src/main/cpp/game/Sound/OSLSound.h", "rank": 92, "score": 3.214019226322761 }, { "content": "\n\n // Choose you texture\n\n glBindTexture(GL_TEXTURE_2D, m_nTextureID);\n\n checkGLError(\"Graphic - glBindTexture\");\n\n\n\n // Fill attributes and uniforms\n\n // Init position\n\n glVertexAttribPointer(m_nStarsAngle, 1, GL_FLOAT, GL_FALSE, 0, m_fArrayPosition);\n\n checkGLError(\"Graphic - glVertexAttribPointer - m_nStarsAngle\");\n\n glEnableVertexAttribArray(m_nStarsAngle);\n\n checkGLError(\"Graphic - glVertexAttribPointer - m_nStarsAngle - enabled\");\n\n\n\n // For color\n\n glVertexAttribPointer(m_nStarColor, 4, GL_FLOAT, GL_FALSE, 0, m_fArrayColor);\n\n checkGLError(\"Graphic - glVertexAttribPointer - m_nStarColor\");\n\n glEnableVertexAttribArray(m_nStarColor);\n\n checkGLError(\"Graphic - glVertexAttribPointer - m_nStarColor - enabled\");\n\n\n\n // Center\n\n glUniform2f(m_nStarCenter, CENTER_X, CENTER_Y);\n", "file_path": "game/src/main/cpp/game/Particles/Shape.cpp", "rank": 93, "score": 3.1914048539617164 }, { "content": "\n\n // Fill attributes and uniforms\n\n // Position\n\n glVertexAttribPointer(m_nPositionAttr, 2, GL_FLOAT, GL_FALSE, 0, m_pPolygonCoordinates);\n\n checkGLError(\"View - glVertexAttribPointer - position\");\n\n glEnableVertexAttribArray(m_nPositionAttr);\n\n checkGLError(\"View - glVertexAttribPointer - position - enabled\");\n\n\n\n // Texture\n\n glVertexAttribPointer(m_nTextureAttr, 2, GL_FLOAT, GL_FALSE, 0, m_pTextureCoordinates);\n\n checkGLError(\"View - glVertexAttribPointer - texture\");\n\n glEnableVertexAttribArray(m_nTextureAttr);\n\n checkGLError(\"View - glVertexAttribPointer - texture - enabled\");\n\n\n\n // Transformation\n\n glUniformMatrix4fv(m_nTransformationAttr, 1, GL_FALSE, m_pTransformationMatrix);\n\n checkGLError(\"View - glUniformMatrix4fv\");\n\n\n\n // Draw polygon\n\n glDrawArrays(GL_TRIANGLE_FAN, 0, 4);\n\n checkGLError(\"View - glDrawArrays\");\n\n}", "file_path": "game/src/main/cpp/game/Graphic/View.cpp", "rank": 94, "score": 3.180600744300264 }, { "content": " return false;\n\n }\n\n\n\n template <class A>\n\n static bool intersectLines(Line<A> * line1, Line<A> * line2, std::vector<A> * twoPoints) {\n\n Point<A> point;\n\n\n\n if (Intersect::intersect(line1, line2, &point)) {\n\n twoPoints->push_back(point.x);\n\n twoPoints->push_back(point.y);\n\n return true;\n\n }\n\n\n\n return true;\n\n }\n\n\n\n template <class A>\n\n static bool intersectRect(Rectangle<A> * rect1, Rectangle<A> * rect2, std::vector<A> * crossPoints) {\n\n for (int i = 0; i < 4; i++) {\n\n for (int j = 0; j < 4; j++) {\n", "file_path": "game/src/main/cpp/game/Common/Intersect.h", "rank": 95, "score": 3.1668596175799206 }, { "content": " }\n\n\n\n // Allocates resources\n\n result = (*m_oMix)->Realize(m_oMix, SL_BOOLEAN_FALSE);\n\n if (result != SL_RESULT_SUCCESS) {\n\n LOGE(\"OSLSound - Error m_oMix Realize\");\n\n return false;\n\n }\n\n\n\n m_pAssetManager = AAssetManager_fromJava(env, assetManager);\n\n return true;\n\n}\n\n\n\nvoid OSLSound::create() {\n\n m_oSoundPack[SOUND_TYPE::BACKGROUND] = SoundPack();\n\n m_oSoundPack[SOUND_TYPE::BACKGROUND].descriptor = loadResourceDescriptor(\"sound/background.mp3\");\n\n m_oSoundPack[SOUND_TYPE::BALL] = SoundPack();\n\n m_oSoundPack[SOUND_TYPE::BALL].descriptor = loadResourceDescriptor(\"sound/ball.mp3\");\n\n m_oSoundPack[SOUND_TYPE::OUT] = SoundPack();\n\n m_oSoundPack[SOUND_TYPE::OUT].descriptor = loadResourceDescriptor(\"sound/out.mp3\");\n", "file_path": "game/src/main/cpp/game/Sound/OSLSound.cpp", "rank": 96, "score": 3.154052107796797 }, { "content": " }\n\n};\n\n\n\nvoid OSLSound::pauseAll() {\n\n std::for_each(m_oSoundPack.begin(), m_oSoundPack.end(), [&](std::map<SOUND_TYPE, SoundPack>::value_type &item) {\n\n (*item.second.play)->SetPlayState(item.second.play, SL_PLAYSTATE_PAUSED);\n\n });\n\n};\n\n\n\nvoid OSLSound::stopAll() {\n\n std::for_each(m_oSoundPack.begin(), m_oSoundPack.end(), [&](std::map<SOUND_TYPE, SoundPack>::value_type &item) {\n\n (*item.second.play)->SetPlayState(item.second.play, SL_PLAYSTATE_STOPPED);\n\n });\n\n};\n\n\n\nvoid OSLSound::pauseStopAll() {\n\n pauseAll();\n\n stopAll();\n\n}\n\n\n", "file_path": "game/src/main/cpp/game/Sound/OSLSound.cpp", "rank": 97, "score": 3.1273118208780577 }, { "content": " public:\n\n\n\n View (GLuint textureID,\n\n GLuint programID,\n\n GLint positionAttr,\n\n GLint textureAttr,\n\n GLint transformationAttr,\n\n GLfloat * polygonCoordinates,\n\n GLfloat * textureCoordinates,\n\n GLfloat * transformationMatrix);\n\n\n\n virtual ~View();\n\n\n\n\n\n public:\n\n\n\n void render();\n\n\n\n void setVisible(bool isVisible) {\n\n m_bIsVisible = isVisible;\n", "file_path": "game/src/main/cpp/game/Graphic/View.h", "rank": 98, "score": 3.0777900220982692 }, { "content": " // Use render shader programm\n\n glUseProgram(m_nProgramID);\n\n checkGLError(\"Plume - glUseProgram\");\n\n\n\n // Choose you texture\n\n glBindTexture(GL_TEXTURE_2D, m_nTextureID);\n\n checkGLError(\"Plume - glBindTexture\");\n\n\n\n // Fill attributes and uniforms\n\n // Position\n\n glVertexAttribPointer(m_nPositionAttr, 2, GL_FLOAT, GL_FALSE, 0, m_pPositionArray);\n\n checkGLError(\"Plume - glVertexAttribPointer - m_nPositionAttr\");\n\n glEnableVertexAttribArray(m_nPositionAttr);\n\n checkGLError(\"Plume - glVertexAttribPointer - m_nPositionAttr - enabled\");\n\n\n\n // Color start\n\n glVertexAttribPointer(m_nColorStartAttr, 4, GL_FLOAT, GL_FALSE, 0, m_pColorStartArray);\n\n checkGLError(\"Plume - glVertexAttribPointer - m_nColorStartAttr\");\n\n glEnableVertexAttribArray(m_nColorStartAttr);\n\n checkGLError(\"Plume - glVertexAttribPointer - m_nColorStartAttr - enabled\");\n", "file_path": "game/src/main/cpp/game/Particles/Plume.cpp", "rank": 99, "score": 3.0664102316020343 } ]
C++
media/gpu/chromeos/platform_video_frame_utils.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
#include "media/gpu/chromeos/platform_video_frame_utils.h" #include <drm_fourcc.h> #include <xf86drm.h> #include <limits> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/files/file.h" #include "base/files/file_path.h" #include "base/files/scoped_file.h" #include "base/no_destructor.h" #include "base/posix/eintr_wrapper.h" #include "base/strings/stringprintf.h" #include "base/synchronization/lock.h" #include "gpu/ipc/common/gpu_client_ids.h" #include "gpu/ipc/common/gpu_memory_buffer_support.h" #include "gpu/ipc/service/gpu_memory_buffer_factory.h" #include "media/base/color_plane_layout.h" #include "media/base/format_utils.h" #include "media/base/scopedfd_helper.h" #include "media/base/video_frame_layout.h" #include "media/base/video_util.h" #include "media/gpu/buffer_validation.h" #include "media/gpu/macros.h" #include "ui/gfx/gpu_memory_buffer.h" #include "ui/gfx/linux/drm_util_linux.h" #include "ui/gfx/linux/gbm_buffer.h" #include "ui/gfx/linux/gbm_device.h" #include "ui/gfx/linux/gbm_util.h" #include "ui/gfx/linux/gbm_wrapper.h" #include "ui/gfx/linux/native_pixmap_dmabuf.h" #include "ui/gfx/native_pixmap.h" namespace media { namespace { class GbmDeviceWrapper { public: GbmDeviceWrapper(const GbmDeviceWrapper&) = delete; GbmDeviceWrapper& operator=(const GbmDeviceWrapper&) = delete; static GbmDeviceWrapper* Get() { static base::NoDestructor<GbmDeviceWrapper> gbm_device_wrapper; return gbm_device_wrapper.get(); } gfx::GpuMemoryBufferHandle CreateGpuMemoryBuffer( gfx::BufferFormat format, const gfx::Size& size, gfx::BufferUsage buffer_usage) { base::AutoLock lock(lock_); if (!gbm_device_) return gfx::GpuMemoryBufferHandle(); const int fourcc_format = ui::GetFourCCFormatFromBufferFormat(format); if (fourcc_format == DRM_FORMAT_INVALID) return gfx::GpuMemoryBufferHandle(); const uint32_t flags = ui::BufferUsageToGbmFlags(buffer_usage); std::unique_ptr<ui::GbmBuffer> buffer = gbm_device_->CreateBuffer(fourcc_format, size, flags); if (!buffer) return gfx::GpuMemoryBufferHandle(); gfx::NativePixmapHandle native_pixmap_handle = buffer->ExportHandle(); if (native_pixmap_handle.planes.empty()) return gfx::GpuMemoryBufferHandle(); CHECK_LT(next_gpu_memory_buffer_id_, std::numeric_limits<int>::max()); const gfx::GpuMemoryBufferId gpu_memory_buffer_id( next_gpu_memory_buffer_id_++); gfx::GpuMemoryBufferHandle gmb_handle; gmb_handle.type = gfx::GpuMemoryBufferType::NATIVE_PIXMAP; gmb_handle.id = gpu_memory_buffer_id; gmb_handle.native_pixmap_handle = std::move(native_pixmap_handle); return gmb_handle; } private: GbmDeviceWrapper() { constexpr char kRenderNodeFilePattern[] = "/dev/dri/renderD%d"; for (int i = 128;; i++) { base::FilePath dev_path(FILE_PATH_LITERAL( base::StringPrintf(kRenderNodeFilePattern, i).c_str())); render_node_file_ = base::File(dev_path, base::File::FLAG_OPEN | base::File::FLAG_READ); if (!render_node_file_.IsValid()) return; drmVersionPtr version = drmGetVersion(render_node_file_.GetPlatformFile()); if (!version) continue; std::string version_name( version->name, base::checked_cast<std::string::size_type>(version->name_len)); drmFreeVersion(version); if (base::LowerCaseEqualsASCII(version_name, "vgem")) continue; gbm_device_ = ui::CreateGbmDevice(render_node_file_.GetPlatformFile()); if (gbm_device_) return; } } ~GbmDeviceWrapper() = default; friend class base::NoDestructor<GbmDeviceWrapper>; base::Lock lock_; base::File render_node_file_ GUARDED_BY(lock_); std::unique_ptr<ui::GbmDevice> gbm_device_ GUARDED_BY(lock_); int next_gpu_memory_buffer_id_ GUARDED_BY(lock_) = 0; }; gfx::GpuMemoryBufferHandle AllocateGpuMemoryBufferHandle( gpu::GpuMemoryBufferFactory* factory, VideoPixelFormat pixel_format, const gfx::Size& coded_size, const gfx::Rect& visible_rect, gfx::BufferUsage buffer_usage, base::ScopedClosureRunner& destroy_cb) { DCHECK(factory || buffer_usage == gfx::BufferUsage::VEA_READ_CAMERA_AND_CPU_READ_WRITE); gfx::GpuMemoryBufferHandle gmb_handle; auto buffer_format = VideoPixelFormatToGfxBufferFormat(pixel_format); if (!buffer_format) return gmb_handle; if (!factory) { return GbmDeviceWrapper::Get()->CreateGpuMemoryBuffer( *buffer_format, coded_size, buffer_usage); } int gpu_memory_buffer_id; { static base::NoDestructor<base::Lock> id_lock; static int next_gpu_memory_buffer_id = 0; base::AutoLock lock(*id_lock); CHECK_LT(next_gpu_memory_buffer_id, std::numeric_limits<int>::max()); gpu_memory_buffer_id = next_gpu_memory_buffer_id++; } gmb_handle = factory->CreateGpuMemoryBuffer( gfx::GpuMemoryBufferId(gpu_memory_buffer_id), coded_size, GetRectSizeFromOrigin(visible_rect), *buffer_format, buffer_usage, gpu::kPlatformVideoFramePoolClientId, gfx::kNullAcceleratedWidget); DCHECK(gmb_handle.is_null() || gmb_handle.type != gfx::NATIVE_PIXMAP || VideoFrame::NumPlanes(pixel_format) == gmb_handle.native_pixmap_handle.planes.size()); if (gmb_handle.is_null()) return gmb_handle; destroy_cb.ReplaceClosure( base::BindOnce(&gpu::GpuMemoryBufferFactory::DestroyGpuMemoryBuffer, base::Unretained(factory), gmb_handle.id, gpu::kPlatformVideoFramePoolClientId)); return gmb_handle; } } scoped_refptr<VideoFrame> CreateGpuMemoryBufferVideoFrame( gpu::GpuMemoryBufferFactory* factory, VideoPixelFormat pixel_format, const gfx::Size& coded_size, const gfx::Rect& visible_rect, const gfx::Size& natural_size, base::TimeDelta timestamp, gfx::BufferUsage buffer_usage) { base::ScopedClosureRunner destroy_cb((base::DoNothing())); auto gmb_handle = AllocateGpuMemoryBufferHandle(factory, pixel_format, coded_size, visible_rect, buffer_usage, destroy_cb); if (gmb_handle.is_null() || gmb_handle.type != gfx::NATIVE_PIXMAP) return nullptr; auto buffer_format = VideoPixelFormatToGfxBufferFormat(pixel_format); DCHECK(buffer_format); gpu::GpuMemoryBufferSupport support; std::unique_ptr<gfx::GpuMemoryBuffer> gpu_memory_buffer = support.CreateGpuMemoryBufferImplFromHandle( std::move(gmb_handle), coded_size, *buffer_format, buffer_usage, base::NullCallback()); if (!gpu_memory_buffer) return nullptr; const gpu::MailboxHolder mailbox_holders[VideoFrame::kMaxPlanes] = {}; auto frame = VideoFrame::WrapExternalGpuMemoryBuffer( visible_rect, natural_size, std::move(gpu_memory_buffer), mailbox_holders, base::NullCallback(), timestamp); if (frame) frame->AddDestructionObserver(destroy_cb.Release()); return frame; } scoped_refptr<VideoFrame> CreatePlatformVideoFrame( gpu::GpuMemoryBufferFactory* factory, VideoPixelFormat pixel_format, const gfx::Size& coded_size, const gfx::Rect& visible_rect, const gfx::Size& natural_size, base::TimeDelta timestamp, gfx::BufferUsage buffer_usage) { base::ScopedClosureRunner destroy_cb((base::DoNothing())); auto gmb_handle = AllocateGpuMemoryBufferHandle(factory, pixel_format, coded_size, visible_rect, buffer_usage, destroy_cb); if (gmb_handle.is_null() || gmb_handle.type != gfx::NATIVE_PIXMAP) return nullptr; std::vector<ColorPlaneLayout> planes; for (const auto& plane : gmb_handle.native_pixmap_handle.planes) planes.emplace_back(plane.stride, plane.offset, plane.size); auto layout = VideoFrameLayout::CreateWithPlanes( pixel_format, coded_size, std::move(planes), VideoFrameLayout::kBufferAddressAlignment, gmb_handle.native_pixmap_handle.modifier); if (!layout) return nullptr; std::vector<base::ScopedFD> dmabuf_fds; for (auto& plane : gmb_handle.native_pixmap_handle.planes) dmabuf_fds.emplace_back(plane.fd.release()); auto frame = VideoFrame::WrapExternalDmabufs( *layout, visible_rect, natural_size, std::move(dmabuf_fds), timestamp); if (!frame) return nullptr; frame->AddDestructionObserver(destroy_cb.Release()); return frame; } base::Optional<VideoFrameLayout> GetPlatformVideoFrameLayout( gpu::GpuMemoryBufferFactory* gpu_memory_buffer_factory, VideoPixelFormat pixel_format, const gfx::Size& coded_size, gfx::BufferUsage buffer_usage) { auto frame = CreatePlatformVideoFrame( gpu_memory_buffer_factory, pixel_format, coded_size, gfx::Rect(coded_size), coded_size, base::TimeDelta(), buffer_usage); return frame ? base::make_optional<VideoFrameLayout>(frame->layout()) : base::nullopt; } gfx::GpuMemoryBufferHandle CreateGpuMemoryBufferHandle( const VideoFrame* video_frame) { DCHECK(video_frame); gfx::GpuMemoryBufferHandle handle; switch (video_frame->storage_type()) { case VideoFrame::STORAGE_GPU_MEMORY_BUFFER: handle = video_frame->GetGpuMemoryBuffer()->CloneHandle(); CHECK_EQ(handle.type, gfx::NATIVE_PIXMAP) << "The cloned handle has an unexpected type: " << handle.type; CHECK(!handle.native_pixmap_handle.planes.empty()) << "The cloned handle has no planes"; break; case VideoFrame::STORAGE_DMABUFS: { const size_t num_planes = VideoFrame::NumPlanes(video_frame->format()); std::vector<base::ScopedFD> duped_fds = DuplicateFDs(video_frame->DmabufFds()); while (num_planes != duped_fds.size()) { int duped_fd = -1; duped_fd = HANDLE_EINTR(dup(duped_fds.back().get())); PCHECK(duped_fd >= 0) << "Failed duplicating a dma-buf fd"; duped_fds.emplace_back(duped_fd); } handle.type = gfx::NATIVE_PIXMAP; DCHECK_EQ(video_frame->layout().planes().size(), num_planes); handle.native_pixmap_handle.modifier = video_frame->layout().modifier(); for (size_t i = 0; i < num_planes; ++i) { const auto& plane = video_frame->layout().planes()[i]; handle.native_pixmap_handle.planes.emplace_back( plane.stride, plane.offset, plane.size, std::move(duped_fds[i])); } } break; default: NOTREACHED() << "Unsupported storage type: " << video_frame->storage_type(); } if (!handle.is_null() && handle.type == gfx::NATIVE_PIXMAP && !VerifyGpuMemoryBufferHandle(video_frame->format(), video_frame->coded_size(), handle)) { VLOGF(1) << "Created GpuMemoryBufferHandle is invalid"; } return handle; } scoped_refptr<gfx::NativePixmapDmaBuf> CreateNativePixmapDmaBuf( const VideoFrame* video_frame) { DCHECK(video_frame); gfx::GpuMemoryBufferHandle gpu_memory_buffer_handle = CreateGpuMemoryBufferHandle(video_frame); if (gpu_memory_buffer_handle.is_null() || gpu_memory_buffer_handle.type != gfx::NATIVE_PIXMAP) { VLOGF(1) << "Failed to create native GpuMemoryBufferHandle"; return nullptr; } auto buffer_format = VideoPixelFormatToGfxBufferFormat(video_frame->layout().format()); if (!buffer_format) { VLOGF(1) << "Unexpected video frame format"; return nullptr; } auto native_pixmap = base::MakeRefCounted<gfx::NativePixmapDmaBuf>( video_frame->coded_size(), *buffer_format, std::move(gpu_memory_buffer_handle.native_pixmap_handle)); DCHECK(native_pixmap->AreDmaBufFdsValid()); return native_pixmap; } }
#include "media/gpu/chromeos/platform_video_frame_utils.h" #include <drm_fourcc.h> #include <xf86drm.h> #include <limits> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/files/file.h" #include "base/files/file_path.h" #include "base/files/scoped_file.h" #include "base/no_destructor.h" #include "base/posix/eintr_wrapper.h" #include "base/strings/stringprintf.h" #include "base/synchronization/lock.h" #include "gpu/ipc/common/gpu_client_ids.h" #include "gpu/ipc/common/gpu_memory_buffer_support.h" #include "gpu/ipc/service/gpu_memory_buffer_factory.h" #include "media/base/color_plane_layout.h" #include "media/base/format_utils.h" #include "media/base/scopedfd_helper.h" #include "media/base/video_frame_layout.h" #include "media/base/video_util.h" #include "media/gpu/buffer_validation.h" #include "media/gpu/macros.h" #include "ui/gfx/gpu_memory_buffer.h" #include "ui/gfx/linux/drm_util_linux.h" #include "ui/gfx/linux/gbm_buffer.h" #include "ui/gfx/linux/gbm_device.h" #include "ui/gfx/linux/gbm_util.h" #include "ui/gfx/linux/gbm_wrapper.h" #include "ui/gfx/linux/native_pixmap_dmabuf.h" #include "ui/gfx/native_pixmap.h" namespace media { namespace { class GbmDeviceWrapper { public: GbmDeviceWrapper(const GbmDeviceWrapper&) = delete; GbmDevice
fx::Size& natural_size, base::TimeDelta timestamp, gfx::BufferUsage buffer_usage) { base::ScopedClosureRunner destroy_cb((base::DoNothing())); auto gmb_handle = AllocateGpuMemoryBufferHandle(factory, pixel_format, coded_size, visible_rect, buffer_usage, destroy_cb); if (gmb_handle.is_null() || gmb_handle.type != gfx::NATIVE_PIXMAP) return nullptr; auto buffer_format = VideoPixelFormatToGfxBufferFormat(pixel_format); DCHECK(buffer_format); gpu::GpuMemoryBufferSupport support; std::unique_ptr<gfx::GpuMemoryBuffer> gpu_memory_buffer = support.CreateGpuMemoryBufferImplFromHandle( std::move(gmb_handle), coded_size, *buffer_format, buffer_usage, base::NullCallback()); if (!gpu_memory_buffer) return nullptr; const gpu::MailboxHolder mailbox_holders[VideoFrame::kMaxPlanes] = {}; auto frame = VideoFrame::WrapExternalGpuMemoryBuffer( visible_rect, natural_size, std::move(gpu_memory_buffer), mailbox_holders, base::NullCallback(), timestamp); if (frame) frame->AddDestructionObserver(destroy_cb.Release()); return frame; } scoped_refptr<VideoFrame> CreatePlatformVideoFrame( gpu::GpuMemoryBufferFactory* factory, VideoPixelFormat pixel_format, const gfx::Size& coded_size, const gfx::Rect& visible_rect, const gfx::Size& natural_size, base::TimeDelta timestamp, gfx::BufferUsage buffer_usage) { base::ScopedClosureRunner destroy_cb((base::DoNothing())); auto gmb_handle = AllocateGpuMemoryBufferHandle(factory, pixel_format, coded_size, visible_rect, buffer_usage, destroy_cb); if (gmb_handle.is_null() || gmb_handle.type != gfx::NATIVE_PIXMAP) return nullptr; std::vector<ColorPlaneLayout> planes; for (const auto& plane : gmb_handle.native_pixmap_handle.planes) planes.emplace_back(plane.stride, plane.offset, plane.size); auto layout = VideoFrameLayout::CreateWithPlanes( pixel_format, coded_size, std::move(planes), VideoFrameLayout::kBufferAddressAlignment, gmb_handle.native_pixmap_handle.modifier); if (!layout) return nullptr; std::vector<base::ScopedFD> dmabuf_fds; for (auto& plane : gmb_handle.native_pixmap_handle.planes) dmabuf_fds.emplace_back(plane.fd.release()); auto frame = VideoFrame::WrapExternalDmabufs( *layout, visible_rect, natural_size, std::move(dmabuf_fds), timestamp); if (!frame) return nullptr; frame->AddDestructionObserver(destroy_cb.Release()); return frame; } base::Optional<VideoFrameLayout> GetPlatformVideoFrameLayout( gpu::GpuMemoryBufferFactory* gpu_memory_buffer_factory, VideoPixelFormat pixel_format, const gfx::Size& coded_size, gfx::BufferUsage buffer_usage) { auto frame = CreatePlatformVideoFrame( gpu_memory_buffer_factory, pixel_format, coded_size, gfx::Rect(coded_size), coded_size, base::TimeDelta(), buffer_usage); return frame ? base::make_optional<VideoFrameLayout>(frame->layout()) : base::nullopt; } gfx::GpuMemoryBufferHandle CreateGpuMemoryBufferHandle( const VideoFrame* video_frame) { DCHECK(video_frame); gfx::GpuMemoryBufferHandle handle; switch (video_frame->storage_type()) { case VideoFrame::STORAGE_GPU_MEMORY_BUFFER: handle = video_frame->GetGpuMemoryBuffer()->CloneHandle(); CHECK_EQ(handle.type, gfx::NATIVE_PIXMAP) << "The cloned handle has an unexpected type: " << handle.type; CHECK(!handle.native_pixmap_handle.planes.empty()) << "The cloned handle has no planes"; break; case VideoFrame::STORAGE_DMABUFS: { const size_t num_planes = VideoFrame::NumPlanes(video_frame->format()); std::vector<base::ScopedFD> duped_fds = DuplicateFDs(video_frame->DmabufFds()); while (num_planes != duped_fds.size()) { int duped_fd = -1; duped_fd = HANDLE_EINTR(dup(duped_fds.back().get())); PCHECK(duped_fd >= 0) << "Failed duplicating a dma-buf fd"; duped_fds.emplace_back(duped_fd); } handle.type = gfx::NATIVE_PIXMAP; DCHECK_EQ(video_frame->layout().planes().size(), num_planes); handle.native_pixmap_handle.modifier = video_frame->layout().modifier(); for (size_t i = 0; i < num_planes; ++i) { const auto& plane = video_frame->layout().planes()[i]; handle.native_pixmap_handle.planes.emplace_back( plane.stride, plane.offset, plane.size, std::move(duped_fds[i])); } } break; default: NOTREACHED() << "Unsupported storage type: " << video_frame->storage_type(); } if (!handle.is_null() && handle.type == gfx::NATIVE_PIXMAP && !VerifyGpuMemoryBufferHandle(video_frame->format(), video_frame->coded_size(), handle)) { VLOGF(1) << "Created GpuMemoryBufferHandle is invalid"; } return handle; } scoped_refptr<gfx::NativePixmapDmaBuf> CreateNativePixmapDmaBuf( const VideoFrame* video_frame) { DCHECK(video_frame); gfx::GpuMemoryBufferHandle gpu_memory_buffer_handle = CreateGpuMemoryBufferHandle(video_frame); if (gpu_memory_buffer_handle.is_null() || gpu_memory_buffer_handle.type != gfx::NATIVE_PIXMAP) { VLOGF(1) << "Failed to create native GpuMemoryBufferHandle"; return nullptr; } auto buffer_format = VideoPixelFormatToGfxBufferFormat(video_frame->layout().format()); if (!buffer_format) { VLOGF(1) << "Unexpected video frame format"; return nullptr; } auto native_pixmap = base::MakeRefCounted<gfx::NativePixmapDmaBuf>( video_frame->coded_size(), *buffer_format, std::move(gpu_memory_buffer_handle.native_pixmap_handle)); DCHECK(native_pixmap->AreDmaBufFdsValid()); return native_pixmap; } }
Wrapper& operator=(const GbmDeviceWrapper&) = delete; static GbmDeviceWrapper* Get() { static base::NoDestructor<GbmDeviceWrapper> gbm_device_wrapper; return gbm_device_wrapper.get(); } gfx::GpuMemoryBufferHandle CreateGpuMemoryBuffer( gfx::BufferFormat format, const gfx::Size& size, gfx::BufferUsage buffer_usage) { base::AutoLock lock(lock_); if (!gbm_device_) return gfx::GpuMemoryBufferHandle(); const int fourcc_format = ui::GetFourCCFormatFromBufferFormat(format); if (fourcc_format == DRM_FORMAT_INVALID) return gfx::GpuMemoryBufferHandle(); const uint32_t flags = ui::BufferUsageToGbmFlags(buffer_usage); std::unique_ptr<ui::GbmBuffer> buffer = gbm_device_->CreateBuffer(fourcc_format, size, flags); if (!buffer) return gfx::GpuMemoryBufferHandle(); gfx::NativePixmapHandle native_pixmap_handle = buffer->ExportHandle(); if (native_pixmap_handle.planes.empty()) return gfx::GpuMemoryBufferHandle(); CHECK_LT(next_gpu_memory_buffer_id_, std::numeric_limits<int>::max()); const gfx::GpuMemoryBufferId gpu_memory_buffer_id( next_gpu_memory_buffer_id_++); gfx::GpuMemoryBufferHandle gmb_handle; gmb_handle.type = gfx::GpuMemoryBufferType::NATIVE_PIXMAP; gmb_handle.id = gpu_memory_buffer_id; gmb_handle.native_pixmap_handle = std::move(native_pixmap_handle); return gmb_handle; } private: GbmDeviceWrapper() { constexpr char kRenderNodeFilePattern[] = "/dev/dri/renderD%d"; for (int i = 128;; i++) { base::FilePath dev_path(FILE_PATH_LITERAL( base::StringPrintf(kRenderNodeFilePattern, i).c_str())); render_node_file_ = base::File(dev_path, base::File::FLAG_OPEN | base::File::FLAG_READ); if (!render_node_file_.IsValid()) return; drmVersionPtr version = drmGetVersion(render_node_file_.GetPlatformFile()); if (!version) continue; std::string version_name( version->name, base::checked_cast<std::string::size_type>(version->name_len)); drmFreeVersion(version); if (base::LowerCaseEqualsASCII(version_name, "vgem")) continue; gbm_device_ = ui::CreateGbmDevice(render_node_file_.GetPlatformFile()); if (gbm_device_) return; } } ~GbmDeviceWrapper() = default; friend class base::NoDestructor<GbmDeviceWrapper>; base::Lock lock_; base::File render_node_file_ GUARDED_BY(lock_); std::unique_ptr<ui::GbmDevice> gbm_device_ GUARDED_BY(lock_); int next_gpu_memory_buffer_id_ GUARDED_BY(lock_) = 0; }; gfx::GpuMemoryBufferHandle AllocateGpuMemoryBufferHandle( gpu::GpuMemoryBufferFactory* factory, VideoPixelFormat pixel_format, const gfx::Size& coded_size, const gfx::Rect& visible_rect, gfx::BufferUsage buffer_usage, base::ScopedClosureRunner& destroy_cb) { DCHECK(factory || buffer_usage == gfx::BufferUsage::VEA_READ_CAMERA_AND_CPU_READ_WRITE); gfx::GpuMemoryBufferHandle gmb_handle; auto buffer_format = VideoPixelFormatToGfxBufferFormat(pixel_format); if (!buffer_format) return gmb_handle; if (!factory) { return GbmDeviceWrapper::Get()->CreateGpuMemoryBuffer( *buffer_format, coded_size, buffer_usage); } int gpu_memory_buffer_id; { static base::NoDestructor<base::Lock> id_lock; static int next_gpu_memory_buffer_id = 0; base::AutoLock lock(*id_lock); CHECK_LT(next_gpu_memory_buffer_id, std::numeric_limits<int>::max()); gpu_memory_buffer_id = next_gpu_memory_buffer_id++; } gmb_handle = factory->CreateGpuMemoryBuffer( gfx::GpuMemoryBufferId(gpu_memory_buffer_id), coded_size, GetRectSizeFromOrigin(visible_rect), *buffer_format, buffer_usage, gpu::kPlatformVideoFramePoolClientId, gfx::kNullAcceleratedWidget); DCHECK(gmb_handle.is_null() || gmb_handle.type != gfx::NATIVE_PIXMAP || VideoFrame::NumPlanes(pixel_format) == gmb_handle.native_pixmap_handle.planes.size()); if (gmb_handle.is_null()) return gmb_handle; destroy_cb.ReplaceClosure( base::BindOnce(&gpu::GpuMemoryBufferFactory::DestroyGpuMemoryBuffer, base::Unretained(factory), gmb_handle.id, gpu::kPlatformVideoFramePoolClientId)); return gmb_handle; } } scoped_refptr<VideoFrame> CreateGpuMemoryBufferVideoFrame( gpu::GpuMemoryBufferFactory* factory, VideoPixelFormat pixel_format, const gfx::Size& coded_size, const gfx::Rect& visible_rect, const g
random
[]
C++
projects/client/gui/bloom/source/bloom/Garden.cpp
silentorb/mythic-cpp
97319d158800d77e1a944c47c13523662bc07e08
#include "Garden.h" #include "clienting/Mythic_Client.h" #include "haft/Input_State.h" #include "lookinglass/Lookinglass_Resources.h" #include <iostream> #include <bloom/layout/Axis.h> #include <bloom/flowers/Group.h> #include "framing/Frame_Info.h" #include "bloom/flowers/Flower.h" #include <bloom/flowers/Root.h> using namespace haft; namespace bloom { Garden *Garden::instance = nullptr; Garden::Garden(Draw_Interface &draw) : draw(draw), select_action(new Action(1, "Select")), converter(draw.get_frame().get_dimensions()) { Measurement::pixel_scale = draw.get_frame().get_pixel_scale(); root = unique_ptr<flowers::Root>(new flowers::Root()); instance = this; } Garden::~Garden() {} flowers::Parent &Garden::get_root() const { return *root; } flowers::Flower &Garden::get_event_root() const { return modal_stack.size() > 0 ? *modal_stack.top()->root : *root; } void Garden::update_input(haft::Input_State &input_state) { auto input_result = garden_input.update_input(input_state); { flowers::Flower &start = get_event_root(); if (input_result.mouse_click) { auto &position = input_state.get_position(); if (start.check_event({Events::activate, vec2(position.x, position.y)})) { input_state.clear_gestures(); } } } { flowers::Flower &start = get_event_root(); if (input_result.dragging) { auto &position = garden_input.get_drag_start(); start.check_event({Events::drag, vec2(position.x, position.y)}); } else if (input_result.down) { start.check_event({Events::mouse_down, garden_input.get_position()}); } else if (input_result.up) { start.check_event({Events::mouse_down, garden_input.get_position()}); } } } void Garden::update_layout() { auto dimensions = draw.get_frame().get_dimensions(); converter.set_pixel_dimensions(dimensions); Axis_Values_Old base_axis_values{ converter.get_axis_values<Horizontal_Axis>(), converter.get_axis_values<Vertical_Axis>() }; auto pixel_dimensions = converter.convert_to_pixels({base_axis_values.x.length, base_axis_values.y.length}); root->update_dimensions(pixel_dimensions); root->update_position(ivec2(), pixel_dimensions); } void Garden::render() { update_layout(); root->render(); } void Garden::add_modal(flowers::Flower &flower) { modal_stack.push(unique_ptr<Modal>(new Modal(&flower))); } flowers::Flower *Garden::get_modal() const { if (modal_stack.size() == 0) return nullptr; return modal_stack.top().get()->root; } void Garden::pop_modal() { modal_stack.pop(); } const framing::Frame_Info &Garden::get_frame() const { return draw.get_frame(); } void Garden::update(float delta) { root->update(delta); } }
#include "Garden.h" #include "clienting/Mythic_Client.h" #include "haft/Input_State.h" #include "lookinglass/Lookinglass_Resources.h" #include <iostream> #include <bloom/layout/Axis.h> #include <bloom/flowers/Group.h> #include "framing/Frame_Info.h" #include "bloom/flowers/Flower.h" #include <bloom/flowers/Root.h> using namespace haft; namespace bloom { Garden *Garden::instance = nullptr; Garden::Garden(Draw_Interface &draw) : draw(draw), select_action(new Action(1, "Select")), converter(draw.get_frame().get_dimensions()) { Measurement::pixel_scale = draw.get_frame().get_pixel_scale(); root = unique_ptr<flowers::Root>(new flowers::Root()); instance = this; } Garden::~Garden() {} flowers::Parent &Garden::get_root() const { return *root; } flowers::Flower &Garden::get_event_root() const { return modal_stack.size() > 0 ? *modal_stack.top()->root : *root; }
void Garden::update_layout() { auto dimensions = draw.get_frame().get_dimensions(); converter.set_pixel_dimensions(dimensions); Axis_Values_Old base_axis_values{ converter.get_axis_values<Horizontal_Axis>(), converter.get_axis_values<Vertical_Axis>() }; auto pixel_dimensions = converter.convert_to_pixels({base_axis_values.x.length, base_axis_values.y.length}); root->update_dimensions(pixel_dimensions); root->update_position(ivec2(), pixel_dimensions); } void Garden::render() { update_layout(); root->render(); } void Garden::add_modal(flowers::Flower &flower) { modal_stack.push(unique_ptr<Modal>(new Modal(&flower))); } flowers::Flower *Garden::get_modal() const { if (modal_stack.size() == 0) return nullptr; return modal_stack.top().get()->root; } void Garden::pop_modal() { modal_stack.pop(); } const framing::Frame_Info &Garden::get_frame() const { return draw.get_frame(); } void Garden::update(float delta) { root->update(delta); } }
void Garden::update_input(haft::Input_State &input_state) { auto input_result = garden_input.update_input(input_state); { flowers::Flower &start = get_event_root(); if (input_result.mouse_click) { auto &position = input_state.get_position(); if (start.check_event({Events::activate, vec2(position.x, position.y)})) { input_state.clear_gestures(); } } } { flowers::Flower &start = get_event_root(); if (input_result.dragging) { auto &position = garden_input.get_drag_start(); start.check_event({Events::drag, vec2(position.x, position.y)}); } else if (input_result.down) { start.check_event({Events::mouse_down, garden_input.get_position()}); } else if (input_result.up) { start.check_event({Events::mouse_down, garden_input.get_position()}); } } }
function_block-full_function
[ { "content": " class Root;\n\n }\n\n\n", "file_path": "projects/client/gui/bloom/source/bloom/Garden.h", "rank": 0, "score": 198418.698124333 }, { "content": " class Garden {\n\n// shared_ptr<Style> default_style;\n\n unique_ptr<flowers::Root> root;\n\n unique_ptr<haft::Action> select_action;\n\n Draw_Interface &draw;\n\n Measurement_Converter converter;\n\n flowers::Flower *focused_flower;\n\n stack<unique_ptr<Modal>> modal_stack;\n\n static Garden *instance;\n\n float text_scale = 1;\n\n Garden_Input garden_input;\n\n flowers::Flower &get_event_root() const;\n\n\n\n public:\n\n Garden(Draw_Interface &draw);\n\n ~Garden();\n\n\n\n void update_input(haft::Input_State &input_state);\n\n void update(float delta);\n\n\n", "file_path": "projects/client/gui/bloom/source/bloom/Garden.h", "rank": 1, "score": 161865.79327401263 }, { "content": "namespace bloom {\n\n\n\n struct Modal {\n\n flowers::Flower *root = nullptr;\n\n\n\n Modal(flowers::Flower *root);\n\n };\n\n\n", "file_path": "projects/client/gui/bloom/source/bloom/garden/Modal.h", "rank": 2, "score": 154493.6128134156 }, { "content": " class Garden;\n\n}\n\n\n\nnamespace lookinglass {\n", "file_path": "projects/client/gui/bloom_lookinglass/source/Lookinglass_Bloom.h", "rank": 3, "score": 145728.4243519975 }, { "content": " class Draw;\n\n}\n\nusing namespace glm;\n\n\n\nnamespace bloom {\n\n\n", "file_path": "projects/client/gui/bloom/source/bloom/styling/Fill.h", "rank": 4, "score": 145616.0749798894 }, { "content": " class Draw;\n\n}\n\nusing namespace glm;\n\n\n\nnamespace bloom {\n\n\n", "file_path": "projects/client/gui/bloom/source/bloom/styling/Border.h", "rank": 5, "score": 145616.0749798894 }, { "content": " class Draw;\n\n}\n\n\n", "file_path": "projects/client/gui/bloom_lookinglass/source/Lookinglass_Bloom.h", "rank": 6, "score": 145616.0749798894 }, { "content": " vec2 Box_Old::get_absolute_dimensions() const {\n\n return vec2(axis_cache.x.length, axis_cache.y.length);\n", "file_path": "projects/client/gui/bloom/source/bloom/layout/Box_Source.h", "rank": 7, "score": 145269.0858324722 }, { "content": " class Root : public Group {\n\n Axis_Values bounds;\n\n\n\n public:\n\n virtual glm::vec2 update_dimensions(const glm::vec2 &parent_dimensions) override;\n\n virtual const Axis_Values &get_absolute_bounds() const override;\n\n \n\n virtual const string get_class_name() const override {\n\n return \"Root\";\n\n }\n\n };\n\n }\n\n}", "file_path": "projects/client/gui/bloom/source/bloom/flowers/Root.h", "rank": 8, "score": 144345.3800204015 }, { "content": " class BLOOM_EXPORT Garden_Input {\n\n glm::vec2 drag_start;\n\n glm::vec2 last_position;\n\n glm::vec2 position;\n\n bool dragging = false;\n\n bool is_down = false;\n\n void check_dragging(glm::vec2 position);\n\n\n\n public:\n\n Input_Result update_input(haft::Input_State &input_state);\n\n\n\n const glm::vec2 &get_drag_start() const {\n\n return drag_start;\n\n }\n\n\n\n const glm::vec2 &get_last_position() const {\n\n return last_position;\n\n }\n\n\n\n const glm::vec2 &get_position() const {\n\n return position;\n\n }\n\n\n\n bool is_dragging() const {\n\n return dragging;\n\n }\n\n };\n\n}", "file_path": "projects/client/gui/bloom/source/bloom/garden/Garden_Input.h", "rank": 9, "score": 131179.46900138137 }, { "content": "class Lookinglass_Bloom : public bloom::Draw_Interface, no_copy {\n\n lookinglass::House &house;\n\n drawing::Draw &draw;\n\n\n\npublic:\n\n Lookinglass_Bloom(lookinglass::House &house, drawing::Draw &draw);\n\n virtual void enable_scissor_box(float left, float top, float width, float height) override;\n\n virtual void disable_scissor_box() override;\n\n virtual const framing::Frame_Info &get_frame() const override;\n\n virtual typography::Text_Effect &get_text_effect() const override;\n\n virtual void draw_square(float left, float top, float width, float height, const glm::vec4 &color,\n\n bool solid) override;\n\n virtual typography::Font &get_font(const std::string &name) const override;\n\n\n\n\n\n void render(bloom::Garden &garden);\n\n virtual void enable_3d(bool value) override;\n\n\n\n};", "file_path": "projects/client/gui/bloom_lookinglass/source/Lookinglass_Bloom.h", "rank": 10, "score": 128078.74116710611 }, { "content": " class BLOOM_EXPORT Draw_Interface {\n\n public:\n\n// virtual const glm::ivec2 get_dimensions() const = 0;\n\n virtual const framing::Frame_Info &get_frame() const = 0;\n\n virtual void draw_square(float left, float top, float width, float height, const glm::vec4 &color,\n\n bool solid) = 0;\n\n virtual typography::Font &get_font(const std::string &name) const = 0;\n\n virtual typography::Text_Effect &get_text_effect() const = 0;\n\n virtual void enable_3d(bool value) = 0;\n\n virtual void enable_scissor_box(float left, float top, float width, float height) = 0;\n\n virtual void disable_scissor_box() = 0;\n\n };\n\n}", "file_path": "projects/client/gui/bloom/source/bloom/Draw_Interface.h", "rank": 11, "score": 125572.12389652272 }, { "content": "#pragma once\n\n\n\n#include <glm/vec2.hpp>\n\n#include \"bloom/bloom_export.h\"\n\n\n\nnamespace haft {\n", "file_path": "projects/client/gui/bloom/source/bloom/garden/Garden_Input.h", "rank": 12, "score": 124954.12538424353 }, { "content": "#include \"Garden_Input.h\"\n\n#include <haft/Input_State.h>\n\n#include <iostream>\n\n#include <glm/glm.hpp>\n\n\n\nusing namespace haft;\n\n\n\nconst float drag_minimum = 10;\n\n\n\nnamespace bloom {\n\n\n\n Input_Result Garden_Input::update_input(Input_State &input_state) {\n\n Input_Result result{\n\n false, false, false, false\n\n };\n\n last_position = position;\n\n\n\n for (auto &gesture : input_state.get_gestures()) {\n\n // Eventually position management will need to be more complicated to support multiple gestures.\n\n position = gesture.position;\n", "file_path": "projects/client/gui/bloom/source/bloom/garden/Garden_Input.cpp", "rank": 13, "score": 122773.83807503342 }, { "content": " result.up = true;\n\n if (dragging) {\n\n dragging = false;\n\n result.dragging = true;\n\n }\n\n else {\n\n result.mouse_click = true;\n\n }\n\n break;\n\n }\n\n }\n\n }\n\n\n\n return result;\n\n }\n\n\n\n void Garden_Input::check_dragging(glm::vec2 position) {\n\n if (dragging || !is_down)\n\n return;\n\n\n\n float length = glm::distance(drag_start, position);\n\n if (length > drag_minimum) {\n\n dragging = true;\n\n }\n\n }\n\n\n\n\n\n}", "file_path": "projects/client/gui/bloom/source/bloom/garden/Garden_Input.cpp", "rank": 14, "score": 122762.04758255223 }, { "content": "\n\n switch (gesture.action) {\n\n case Gesture_Type::down: {\n\n// std::cout << \"down: \" << to_string(gesture.position.x) << \", \" << to_string(gesture.position.y) << std::endl;\n\n dragging = false;\n\n drag_start = gesture.position;\n\n is_down = true;\n\n result.down = true;\n\n break;\n\n }\n\n case Gesture_Type::move: {\n\n// std::cout << \"move: \" << to_string(gesture.position.x) << \", \" << to_string(gesture.position.y) << endl;\n\n check_dragging(gesture.position);\n\n result.dragging = dragging;\n\n break;\n\n }\n\n case Gesture_Type::up: {\n\n// std::cout << \"up: \" << to_string(gesture.position.x) << \", \" << to_string(gesture.position.y) << endl;\n\n check_dragging(gesture.position);\n\n is_down = false;\n", "file_path": "projects/client/gui/bloom/source/bloom/garden/Garden_Input.cpp", "rank": 15, "score": 122760.19005666928 }, { "content": " class Input_State;\n\n}\n\n\n\nnamespace bloom {\n\n\n\n struct Input_Result {\n\n bool mouse_click;\n\n bool dragging;\n\n bool down;\n\n bool up;\n\n };\n\n\n", "file_path": "projects/client/gui/bloom/source/bloom/garden/Garden_Input.h", "rank": 16, "score": 120658.21360608238 }, { "content": "#pragma once\n\n\n\n#include \"bloom/garden/Modal.h\"\n\n#include <stack>\n\n#include <string>\n\n#include <bloom/garden/Garden_Input.h>\n\n#include <bloom/flowers/Parent.h>\n\n#include <bloom/layout/Measurement_Converter.h>\n\n#include <haft/Action.h>\n\n#include \"Draw_Interface.h\"\n\n\n\nnamespace haft {\n", "file_path": "projects/client/gui/bloom/source/bloom/Garden.h", "rank": 17, "score": 116216.24548170174 }, { "content": " flowers::Parent &get_root() const;\n\n\n\n void render();\n\n\n\n Draw_Interface &get_draw() const {\n\n return draw;\n\n }\n\n\n\n const Measurement_Converter &get_converter() const {\n\n return converter;\n\n }\n\n\n\n haft::Action &get_select_action() const {\n\n return *select_action;\n\n }\n\n\n\n flowers::Flower *get_focused() const {\n\n return focused_flower;\n\n }\n\n\n", "file_path": "projects/client/gui/bloom/source/bloom/Garden.h", "rank": 18, "score": 116205.97762347679 }, { "content": " }\n\n\n\n void set_text_scale(float text_scale) {\n\n Garden::text_scale = text_scale;\n\n }\n\n\n\n const Garden_Input &get_input() const {\n\n return garden_input;\n\n }\n\n };\n\n}", "file_path": "projects/client/gui/bloom/source/bloom/Garden.h", "rank": 19, "score": 116199.23132103807 }, { "content": " void set_focused(flowers::Flower *focused_flower) {\n\n Garden::focused_flower = focused_flower;\n\n }\n\n\n\n void add_modal(flowers::Flower &flower);\n\n\n\n static Garden &get_instance() {\n\n return *instance;\n\n }\n\n\n\n// Orientation get_orientation() const;\n\n flowers::Flower *get_modal() const;\n\n void pop_modal();\n\n\n\n\n\n void update_layout();\n\n const framing::Frame_Info &get_frame() const;\n\n\n\n const float &get_text_scale() const {\n\n return text_scale;\n", "file_path": "projects/client/gui/bloom/source/bloom/Garden.h", "rank": 20, "score": 116199.181412293 }, { "content": "#pragma once\n\n\n\n#include \"Group.h\"\n\n#include <bloom/layout/Axis_Value.h>\n\n\n\nnamespace bloom {\n\n namespace flowers {\n\n\n", "file_path": "projects/client/gui/bloom/source/bloom/flowers/Root.h", "rank": 21, "score": 113597.78278723196 }, { "content": " class Element;\n\n}\n\n\n\nnamespace framing {\n", "file_path": "projects/client/gui/bloom/source/bloom/Garden.h", "rank": 28, "score": 113563.14504221514 }, { "content": "#pragma once\n\n\n\n#include \"bloom/bloom_export.h\"\n\n#include \"glm/vec2.hpp\"\n\n#include \"glm/vec4.hpp\"\n\n#include <string>\n\n\n\nnamespace typography {\n", "file_path": "projects/client/gui/bloom/source/bloom/Draw_Interface.h", "rank": 29, "score": 113463.46446155293 }, { "content": "namespace haft {\n\n\n\n enum class Gesture_Type {\n\n down,\n\n move,\n\n up\n\n };\n\n\n\n struct Gesture {\n\n Gesture_Type action;\n\n glm::ivec2 position;\n\n };\n", "file_path": "projects/client/input/haft/source/haft/Gesture.h", "rank": 30, "score": 111787.27476304364 }, { "content": "namespace haft {\n\n\n\n using Action = int;\n\n// class Action {\n\n// std::string name;\n\n// int id;\n\n//\n\n// public:\n\n// Action(int id, const std::string &name) : name(name), id(id) { }\n\n//\n\n// const std::string &get_name() const {\n\n// return name;\n\n// }\n\n//\n\n// void set_name(const std::string &name){\n\n// this->name = name;\n\n// }\n\n//\n\n// int get_id() const {\n\n// return id;\n\n// }\n\n\n\n// };\n\n\n", "file_path": "projects/client/input/haft/source/haft/Action.h", "rank": 31, "score": 111787.27476304364 }, { "content": "#include \"Root.h\"\n\n#include \"Common_Flower.h\"\n\n\n\nnamespace bloom {\n\n namespace flowers {\n\n\n\n const Axis_Values &Root::get_absolute_bounds() const {\n\n return bounds;\n\n }\n\n\n\n glm::vec2 Root::update_dimensions(const glm::vec2 &parent_dimensions) {\n\n bounds.dimensions = parent_dimensions;\n\n return Group::update_dimensions(parent_dimensions);\n\n }\n\n }\n\n}", "file_path": "projects/client/gui/bloom/source/bloom/flowers/Root.cpp", "rank": 32, "score": 111085.67183377423 }, { "content": "#include \"Modal.h\"\n\n\n\nnamespace bloom {\n\n\n\n// void get_buttons(Flower_Old *flower, vector<Flower_Old *> &buttons) {\n\n// for (auto &child : flower->get_children()) {\n\n//// if (dynamic_cast<Button_Old *>(child.get())) {\n\n//// buttons.push_back(child.get());\n\n//// }\n\n//\n\n// get_buttons(child.get(), buttons);\n\n// }\n\n// }\n\n\n\n\n\n Modal::Modal(flowers::Flower *root) :\n\n root(root) {\n\n\n\n// get_buttons(root, buttons);\n\n }\n\n}", "file_path": "projects/client/gui/bloom/source/bloom/garden/Modal.cpp", "rank": 33, "score": 111062.88081618983 }, { "content": " class Input_State;\n\n}\n\n\n\nnamespace drawing {\n", "file_path": "projects/client/gui/bloom/source/bloom/Garden.h", "rank": 34, "score": 111054.41559941237 }, { "content": " class Mutable_Frame;\n\n}\n\n\n\nnamespace bloom {\n\n\n\n namespace flowers {\n", "file_path": "projects/client/gui/bloom/source/bloom/Garden.h", "rank": 35, "score": 111054.41559941237 }, { "content": "namespace haft {\n\n enum Event_Type {\n\n simple,\n\n value,\n\n spatial_old\n\n };\n", "file_path": "projects/client/input/haft/source/haft/Event_Type.h", "rank": 36, "score": 110960.7195651014 }, { "content": " class Font;\n\n\n", "file_path": "projects/client/gui/bloom/source/bloom/Draw_Interface.h", "rank": 37, "score": 110944.85667927639 }, { "content": "namespace bloom {\n\n\n\n\n\n template<typename Axis>\n\n float Measurement::resolve(const vec2 &parent_dimensions,\n\n const Measurement_Converter &converter) const {\n\n\n\n if (get_type() == Measurements::stretch) {\n\n return 0;\n\n }\n\n\n\n else {\n\n\n\n auto value = static_cast<const Measurement *>(this)->get_value();\n\n\n\n switch (get_type()) {\n\n case Measurements::pixel:\n\n return value * Measurement::pixel_scale * UNIT_RESOLUTION / Axis::get(converter.get_pixel_dimensions());\n\n\n\n case Measurements::percent:\n\n return value * Axis::get(parent_dimensions) / 100;\n\n\n\n case Measurements::percent_perpendicular:\n\n return value * Axis::get_perpendicular(parent_dimensions) / 100;\n\n\n\n case Measurements::vertical_units:\n\n return value * converter.get_pixel_dimensions().y / 100;\n\n\n\n default:\n\n return value;\n\n }\n", "file_path": "projects/client/gui/bloom/source/bloom/layout/Box_Source.h", "rank": 38, "score": 109765.11975110175 }, { "content": "namespace bloom {\n\n\n\n struct Axis_Value {\n\n float near, far;\n\n\n\n Axis_Value operator+(float value) {\n\n return {near + value, far + value};\n\n }\n\n };\n\n\n\n struct Axis_Values {\n\n glm::vec2 position;\n\n glm::vec2 dimensions;\n\n };\n\n\n", "file_path": "projects/client/gui/bloom/source/bloom/layout/Axis_Value.h", "rank": 39, "score": 109765.11975110175 }, { "content": "namespace bloom {\n\n\n\n struct Parent_Dimension {\n\n// float near;\n\n float length;\n\n bool stretches;\n\n };\n\n\n\n struct Parent_Dimensions {\n\n Parent_Dimension x;\n\n Parent_Dimension y;\n\n };\n", "file_path": "projects/client/gui/bloom/source/bloom/layout/Parent_Dimensions.h", "rank": 40, "score": 109765.11975110175 }, { "content": "namespace bloom {\n\n\n\n void log_hierarchy(bloom::flowers::Flower *root);\n\n\n", "file_path": "projects/client/gui/bloom_lab/source/bloom/lab/crawl_writer.h", "rank": 41, "score": 108982.97103034375 }, { "content": " class Text_Effect;\n\n}\n\nnamespace framing {\n", "file_path": "projects/client/gui/bloom/source/bloom/Draw_Interface.h", "rank": 42, "score": 108552.6237358355 }, { "content": " class Frame_Info;\n\n}\n\nnamespace bloom {\n\n\n", "file_path": "projects/client/gui/bloom/source/bloom/Draw_Interface.h", "rank": 43, "score": 108552.6237358355 }, { "content": " Modal(flowers::Flower *root);\n", "file_path": "projects/client/gui/bloom/source/bloom/garden/Modal.h", "rank": 44, "score": 104178.88058384806 }, { "content": "class Mock_Draw_Interface : public Draw_Interface {\n\n\n\npublic:\n\n\n\n// virtual const glm::ivec2 get_dimensions() const override {\n\n// return ivec2(800, 600);\n\n// }\n\n\n\n Mock_Draw_Interface() {\n\n frame.set_dimensions(1000, 1000);\n\n }\n\n\n\n framing::Mutable_Frame frame;\n\n\n\n virtual void draw_square(float left, float top, float width, float height, const glm::vec4 &color,\n\n bool solid) override {\n\n\n\n }\n\n\n\n virtual typography::Font &get_font(const std::string &name) const override {\n", "file_path": "projects/client/gui/bloom/test/source/mocks/Mock_Draw_Interface.h", "rank": 45, "score": 103915.43626852115 }, { "content": " class Draw : no_copy {\n\n unique_ptr<shading::Vertex_Schema> solid_vertex_schema;\n\n unique_ptr<modeling::Simple_Mesh> solid_mesh;\n\n unique_ptr<shading::Vertex_Schema> image_vertex_schema;\n\n unique_ptr<modeling::Simple_Mesh> image_mesh;\n\n unique_ptr<Image_Effect> default_image_effect;\n\n unique_ptr<Square_Effect> square_effect;\n\n shading::Program *flat_program;\n\n lookinglass::House &house;\n\n\n\n public:\n\n Draw(lookinglass::House &house);\n\n ~Draw();\n\n\n\n modeling::Simple_Mesh &get_solid_mesh() const {\n\n return *solid_mesh;\n\n }\n\n\n\n modeling::Simple_Mesh &get_image_mesh() const {\n\n return *image_mesh;\n", "file_path": "projects/client/visual/drawing/source/drawing/Draw.h", "rank": 46, "score": 101018.54361498101 }, { "content": "#pragma once\n\n\n\n#include <bloom/Draw_Interface.h>\n\n#include <framing/Mutable_Frame.h>\n\n\n\nusing namespace bloom;\n\nusing namespace glm;\n\nusing namespace std;\n\n\n", "file_path": "projects/client/gui/bloom/test/source/mocks/Mock_Draw_Interface.h", "rank": 47, "score": 94559.1422220961 }, { "content": " throw runtime_error(\"Not implemented.\");\n\n }\n\n\n\n virtual typography::Text_Effect &get_text_effect() const override {\n\n throw runtime_error(\"Not implemented.\");\n\n }\n\n\n\n virtual void enable_3d(bool value) override {\n\n\n\n }\n\n\n\n virtual const framing::Frame_Info &get_frame() const override {\n\n return frame;\n\n }\n\n\n\n virtual void enable_scissor_box(float left, float top, float width, float height) override {\n\n\n\n }\n\n\n\n virtual void disable_scissor_box() override {\n\n\n\n }\n\n\n\n\n\n};", "file_path": "projects/client/gui/bloom/test/source/mocks/Mock_Draw_Interface.h", "rank": 48, "score": 94537.64079656417 }, { "content": "PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEPROC glad_glDrawArraysInstancedBaseInstance;\n", "file_path": "projects/client/visual/glow/glad/src/glad.c", "rank": 49, "score": 92996.4347135313 }, { "content": "PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC glad_glDrawElementsInstancedBaseInstance;\n", "file_path": "projects/client/visual/glow/glad/src/glad.c", "rank": 50, "score": 92996.4347135313 }, { "content": "PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC glad_glDrawElementsInstancedBaseVertexBaseInstance;\n", "file_path": "projects/client/visual/glow/glad/src/glad.c", "rank": 51, "score": 89742.85203913784 }, { "content": " const Pitch &traverse(const aura::sequencing::Key keys[], int count, int steps) const;\n", "file_path": "projects/client/audio/aura_sequencing/source/aura/sequencing/Pitch.h", "rank": 52, "score": 88062.99652708182 }, { "content": " class Draw;\n\n}\n\n\n\nnamespace typography {\n\n\n", "file_path": "projects/client/visual/typography/source/typography/Text.h", "rank": 53, "score": 84720.25325212316 }, { "content": " class Knob_Flower : public bloom::flowers::Group {\n\n Knob_Flower_Internal internal;\n\n nobby::Knob<T> &knob;\n\n Knob_Modifier modifier;\n\n\n\n void set_text_value() {\n\n internal.text->set_content(std::to_string(knob.get_value()));\n\n }\n\n\n\n void set_slider_value() {\n\n internal.slider->set_value(knob.get_normalized());\n\n }\n\n\n\n public:\n\n Knob_Flower(nobby::Knob<T> &knob, const string &label_text) : knob(knob) {\n\n internal.initialize(this, label_text);\n\n std::to_string(knob.get_value());\n\n set_text_value();\n\n set_slider_value();\n\n\n", "file_path": "projects/lab/bloom_nobby/source/bloom_nobby/Knob_Flower.h", "rank": 54, "score": 81761.69137130186 }, { "content": "PFNGLDRAWARRAYSINSTANCEDPROC glad_glDrawArraysInstanced;\n", "file_path": "projects/client/visual/glow/glad/src/glad.c", "rank": 55, "score": 81647.30877455666 }, { "content": "static void load_GL_ARB_draw_instanced(GLADloadproc load) {\n\n\tif(!GLAD_GL_ARB_draw_instanced) return;\n\n\tglad_glDrawArraysInstancedARB = (PFNGLDRAWARRAYSINSTANCEDARBPROC)load(\"glDrawArraysInstancedARB\");\n\n\tglad_glDrawElementsInstancedARB = (PFNGLDRAWELEMENTSINSTANCEDARBPROC)load(\"glDrawElementsInstancedARB\");\n", "file_path": "projects/client/visual/glow/glad/src/glad.c", "rank": 56, "score": 81647.30877455666 }, { "content": "int GLAD_GL_EXT_draw_instanced;\n", "file_path": "projects/client/visual/glow/glad/src/glad.c", "rank": 57, "score": 81647.30877455666 }, { "content": "static void load_GL_EXT_draw_instanced(GLADloadproc load) {\n\n\tif(!GLAD_GL_EXT_draw_instanced) return;\n\n\tglad_glDrawArraysInstancedEXT = (PFNGLDRAWARRAYSINSTANCEDEXTPROC)load(\"glDrawArraysInstancedEXT\");\n\n\tglad_glDrawElementsInstancedEXT = (PFNGLDRAWELEMENTSINSTANCEDEXTPROC)load(\"glDrawElementsInstancedEXT\");\n", "file_path": "projects/client/visual/glow/glad/src/glad.c", "rank": 58, "score": 81647.30877455666 }, { "content": "PFNGLDRAWELEMENTSINSTANCEDPROC glad_glDrawElementsInstanced;\n", "file_path": "projects/client/visual/glow/glad/src/glad.c", "rank": 59, "score": 81647.30877455666 }, { "content": "int GLAD_GL_ARB_draw_instanced;\n", "file_path": "projects/client/visual/glow/glad/src/glad.c", "rank": 60, "score": 81647.30877455666 }, { "content": " class Banner : public bloom::flowers::Box_Group {\n\n breeze::Animator& animator;\n\n\n\n void initialize_appearance(const achieving::Achievement &achievement);\n\n\n\n void initialize_animation(const std::function<void()> &on_finished);\n\n public:\n\n Banner(const achieving::Achievement &achievement, breeze::Animator& animator, const std::function<void()> &on_finished);\n\n virtual void update(float delta) override;\n\n };\n\n }\n\n}", "file_path": "projects/misc/achievements/achieving_bloom/source/achieving_bloom/flowers/Banner.h", "rank": 61, "score": 80998.25945466646 }, { "content": "PFNGLDRAWARRAYSINSTANCEDARBPROC glad_glDrawArraysInstancedARB;\n", "file_path": "projects/client/visual/glow/glad/src/glad.c", "rank": 62, "score": 79801.22767535137 }, { "content": "PFNGLDRAWELEMENTSINSTANCEDEXTPROC glad_glDrawElementsInstancedEXT;\n", "file_path": "projects/client/visual/glow/glad/src/glad.c", "rank": 63, "score": 79801.22767535137 }, { "content": "PFNGLDRAWELEMENTSINSTANCEDARBPROC glad_glDrawElementsInstancedARB;\n", "file_path": "projects/client/visual/glow/glad/src/glad.c", "rank": 64, "score": 79801.22767535137 }, { "content": "PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDPROC glad_glDrawTransformFeedbackInstanced;\n", "file_path": "projects/client/visual/glow/glad/src/glad.c", "rank": 65, "score": 79801.22767535137 }, { "content": "PFNGLDRAWARRAYSINSTANCEDEXTPROC glad_glDrawArraysInstancedEXT;\n", "file_path": "projects/client/visual/glow/glad/src/glad.c", "rank": 66, "score": 79801.22767535137 }, { "content": "PFNGLDRAWTRANSFORMFEEDBACKSTREAMINSTANCEDPROC glad_glDrawTransformFeedbackStreamInstanced;\n", "file_path": "projects/client/visual/glow/glad/src/glad.c", "rank": 67, "score": 78036.78215065075 }, { "content": "PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC glad_glDrawElementsInstancedBaseVertex;\n", "file_path": "projects/client/visual/glow/glad/src/glad.c", "rank": 68, "score": 78036.78215065075 }, { "content": "#pragma once\n\n\n\n\n\n#include <memory>\n\n#include \"glm/glm.hpp\"\n\n#include \"Square_Effect.h\"\n\n#include <string>\n\n#include <vector>\n\n#include <functional>\n\n#include <modeling/Renderable_Mesh.h>\n\n\n\nnamespace lookinglass {\n\n// typedef function<void()> Renderable;\n\n\n", "file_path": "projects/client/visual/drawing/source/drawing/Draw.h", "rank": 69, "score": 70931.98616814923 }, { "content": " lookinglass::House &get_house() const {\n\n return house;\n\n }\n\n\n\n void draw_square(float left, float top, float width, float height, modeling::Draw_Method draw_method,\n\n Square_Effect &effect,\n\n modeling::Renderable_Mesh &mesh);\n\n\n\n void draw_pixel_square(const glm::vec2 &position, const glm::vec2 &dimensions, bool solid,\n\n Square_Effect &effect, modeling::Renderable_Mesh &mesh);\n\n\n\n void draw_square(float left, float top, float width, float height, const vec4 &color, bool solid);\n\n void set_depth(bool value);\n\n const framing::Frame_Info &get_frame() const;\n\n static Draw &get_instance();\n\n };\n\n}\n\n\n\n\n\n\n", "file_path": "projects/client/visual/drawing/source/drawing/Draw.h", "rank": 70, "score": 70928.49423098203 }, { "content": " }\n\n\n\n Square_Effect &get_square_effect() const {\n\n return *square_effect;\n\n }\n\n\n\n const shading::Vertex_Schema &get_image_vertex_schema() const {\n\n return *image_vertex_schema;\n\n }\n\n\n\n const shading::Vertex_Schema &get_solid_vertex_schema() const {\n\n return *solid_vertex_schema;\n\n }\n\n\n\n const ivec2 &get_dimensions() const;\n\n\n\n Image_Effect &get_default_image_effect() const {\n\n return *default_image_effect;\n\n }\n\n\n", "file_path": "projects/client/visual/drawing/source/drawing/Draw.h", "rank": 71, "score": 70923.68437313988 }, { "content": "#include \"lookinglass/Renderable_List.h\"\n\n#include \"Draw.h\"\n\n#include \"shading/Shader_Manager.h\"\n\n#include \"Image_Effect.h\"\n\n#include \"modeling/Simple_Mesh.h\"\n\n#include \"lookinglass/House.h\"\n\n#include \"glow.h\"\n\n#include \"perspective/Viewport.h\"\n\n#include <glm/gtc/matrix_transform.hpp>\n\n#include \"glow_gl.h\"\n\n\n\nusing namespace modeling;\n\nusing namespace texturing;\n\n\n\nnamespace drawing {\n\n\n\n static Draw *instance;\n\n\n\n Draw &Draw::get_instance() {\n\n return *instance;;\n", "file_path": "projects/client/visual/drawing/source/drawing/Draw.cpp", "rank": 72, "score": 70003.91198980037 }, { "content": " }\n\n\n\n flat_program = shader_manager.get_program_or_null(\"drawing.flat\");\n\n if (!flat_program) {\n\n flat_program = &shader_manager.create_program_from_files(\"drawing.flat\", \"drawing/flat.vertex\",\n\n \"drawing/flat.fragment\", {\n\n \"position\", \"vertex_color\"});\n\n }\n\n\n\n square_effect = unique_ptr<Square_Effect>(new Square_Effect(*flat_program));\n\n }\n\n\n\n Draw::~Draw() {\n\n\n\n }\n\n\n\n const ivec2 &Draw::get_dimensions() const {\n\n return house.get_glass().get_viewport_dimensions();\n\n }\n\n\n", "file_path": "projects/client/visual/drawing/source/drawing/Draw.cpp", "rank": 73, "score": 69990.14868551622 }, { "content": " }\n\n\n\n Draw::Draw(lookinglass::House &house) :\n\n house(house),\n\n solid_vertex_schema(new Vertex_Schema(\n\n {\n\n Vertex_Attribute(0, \"position\", 2),\n\n Vertex_Attribute(1, \"vertex_color\", 4)\n\n }\n\n )),\n\n image_vertex_schema(new Vertex_Schema({4})) {\n\n instance = this;\n\n auto &shader_manager = house.get_shader_manager();\n\n\n\n float solid_vertices[] = {\n\n 0, 0, 1, 1, 1, 1,\n\n 0, 1, 1, 1, 1, 1,\n\n 1, 1, 1, 1, 1, 1,\n\n 1, 0, 1, 1, 1, 1,\n\n };\n", "file_path": "projects/client/visual/drawing/source/drawing/Draw.cpp", "rank": 74, "score": 69989.98760487806 }, { "content": " auto scaled_position = position / scaling;\n\n auto scaled_dimensions = dimensions / scaling;\n\n auto transform = glm::translate(mat4(1), vec3(scaled_position, 0))\n\n * glm::scale(mat4(1), vec3(scaled_dimensions.x, -scaled_dimensions.y, 1));\n\n\n\n effect.set_transform(transform);\n\n\n\n mesh.render(solid ? modeling::Draw_Method::triangle_fan : modeling::Draw_Method::line_loop);\n\n glow::check_error(\"drew_square\");\n\n }\n\n\n\n void Draw::draw_square(float left, float top, float width, float height, const vec4 &color, bool solid) {\n\n square_effect->activate();\n\n square_effect->set_color(color);\n\n draw_square(left, top, width, height,\n\n solid ? modeling::Draw_Method::triangle_fan : modeling::Draw_Method::line_loop,\n\n *square_effect, *solid_mesh);\n\n }\n\n\n\n void Draw::set_depth(bool value) {\n", "file_path": "projects/client/visual/drawing/source/drawing/Draw.cpp", "rank": 75, "score": 69989.12717857606 }, { "content": " void Draw::draw_square(float left, float top, float width, float height, Draw_Method draw_method,\n\n Square_Effect &effect, Renderable_Mesh &mesh) {\n\n\n\n auto &viewport = house.get_base_viewport();\n\n vec2 scaling = viewport.get_unit_scaling();\n\n\n\n auto transform = glm::translate(mat4(1), vec3(left * scaling.x, top * scaling.y, 0))\n\n * glm::scale(mat4(1), vec3(width * scaling.x, height * scaling.y, 1));\n\n\n\n effect.set_transform(transform);\n\n\n\n mesh.render(draw_method);\n\n glow::check_error(\"drew_square\");\n\n }\n\n\n\n void Draw::draw_pixel_square(const glm::vec2 &position, const glm::vec2 &dimensions, bool solid,\n\n Square_Effect &effect, Renderable_Mesh &mesh) {\n\n\n\n auto &viewport = house.get_base_viewport();\n\n vec2 scaling = viewport.get_dimensions();\n", "file_path": "projects/client/visual/drawing/source/drawing/Draw.cpp", "rank": 76, "score": 69988.9305219561 }, { "content": " glow::set_depth_test(value);\n\n glow::set_depth_write(value);\n\n }\n\n\n\n const framing::Frame_Info &Draw::get_frame() const {\n\n return house.get_frame();\n\n }\n\n\n\n}\n", "file_path": "projects/client/visual/drawing/source/drawing/Draw.cpp", "rank": 77, "score": 69988.01699140194 }, { "content": "\n\n float image_vertices[] = {\n\n 0, 0, 0, 0,\n\n 1, 0, 1, 0,\n\n 1, 1, 1, 1,\n\n 0, 1, 0, 1\n\n };\n\n\n\n solid_mesh = unique_ptr<Simple_Mesh>(new Simple_Mesh(solid_vertices, 4, *solid_vertex_schema.get()));\n\n image_mesh = unique_ptr<Simple_Mesh>(new Simple_Mesh(image_vertices, 4, *image_vertex_schema.get()));\n\n\n\n {\n\n auto program = shader_manager.get_program_or_null(\"sprite\");\n\n if (!program) {\n\n program = &shader_manager.create_program_from_files(\"sprite\", \"drawing/sprite.vertex\",\n\n \"texturing/image.fragment\", {});\n\n }\n\n\n\n default_image_effect = unique_ptr<Image_Effect>(\n\n new Image_Effect(*program, house.get_base_viewport()));\n", "file_path": "projects/client/visual/drawing/source/drawing/Draw.cpp", "rank": 78, "score": 69986.33790303332 }, { "content": " class Image;\n\n\n", "file_path": "projects/client/visual/drawing/source/drawing/Draw.h", "rank": 79, "score": 69985.25695770705 }, { "content": " class House;\n\n}\n\n\n\nnamespace modeling {\n", "file_path": "projects/client/visual/drawing/source/drawing/Draw.h", "rank": 80, "score": 69985.25695770705 }, { "content": " class Program;\n\n}\n\n\n\nnamespace texturing {\n\n struct Texture;\n\n}\n\nnamespace framing {\n", "file_path": "projects/client/visual/drawing/source/drawing/Draw.h", "rank": 81, "score": 69985.25695770705 }, { "content": " class Sprite;\n\n\n", "file_path": "projects/client/visual/drawing/source/drawing/Draw.h", "rank": 82, "score": 69985.25695770705 }, { "content": " class Sprite_Layer;\n\n\n", "file_path": "projects/client/visual/drawing/source/drawing/Draw.h", "rank": 83, "score": 69071.33886971026 }, { "content": " class Image_Effect;\n\n\n", "file_path": "projects/client/visual/drawing/source/drawing/Draw.h", "rank": 84, "score": 69071.33886971026 }, { "content": " class Shader_Manager;\n\n\n", "file_path": "projects/client/visual/drawing/source/drawing/Draw.h", "rank": 85, "score": 69071.33886971026 }, { "content": " class Simple_Mesh;\n\n}\n\n\n\n\n\nnamespace shading {\n", "file_path": "projects/client/visual/drawing/source/drawing/Draw.h", "rank": 86, "score": 69071.33886971026 }, { "content": " class Frame_Info;\n\n}\n\nusing namespace std;\n\nusing namespace glm;\n\n\n\nnamespace drawing {\n", "file_path": "projects/client/visual/drawing/source/drawing/Draw.h", "rank": 87, "score": 69071.33886971026 }, { "content": " class Vertex_Schema;\n\n\n", "file_path": "projects/client/visual/drawing/source/drawing/Draw.h", "rank": 88, "score": 69071.33886971026 }, { "content": "#define BLOOM_EXPORT", "file_path": "projects/client/gui/bloom/source/bloom/bloom_export.h", "rank": 89, "score": 69042.0108919422 }, { "content": " class BLOOM_EXPORT Flower {\n\n\n\n public:\n\n Flower();\n\n virtual ~Flower() = 0;\n\n\n\n//#ifdef COMMONER_DEBUG\n\n//#endif\n\n\n\n virtual glm::vec2 update_dimensions(const glm::vec2 &parent_dimensions) = 0;\n\n virtual void update_position(const glm::vec2 &parent_position, const glm::vec2 &parent_dimensions) = 0;\n\n virtual void update(float delta)= 0;\n\n virtual void render() = 0;\n\n virtual const Axis_Values &get_absolute_bounds() const = 0;\n\n virtual bool affects_parent_dimensions() const = 0;\n\n virtual bool check_event(const Event &event) = 0;\n\n virtual bool get_relative_bounds(glm::vec2 &position, glm::vec2 &dimensions) = 0;\n\n virtual void remove() = 0;\n\n virtual Flower *get_parent() const = 0;\n\n virtual void set_parent(Parent *parent) = 0;\n\n virtual int get_child_count() = 0;\n\n virtual Flower *get_child(int index) = 0;\n\n virtual const std::string get_class_name() const = 0;;\n\n };\n\n\n\n inline Flower::~Flower() {}\n\n }\n\n}", "file_path": "projects/client/gui/bloom/source/bloom/flowers/Flower.h", "rank": 90, "score": 67053.51748038904 }, { "content": " class BLOOM_EXPORT Measurement {\n\n Measurements type;\n\n float value = 0;\n\n\n\n protected:\n\n\n\n// float debug_value = -1;\n\n// unsigned long debug_index;\n\n// Measurement(Measurements type);\n\n\n\n public:\n\n\n\n Measurement() { }\n\n\n\n Measurements get_type() const {\n\n return type;\n\n }\n\n\n\n// virtual Measurement *clone() const {\n\n// return new Measurement(type, value);\n", "file_path": "projects/client/gui/bloom/source/bloom/layout/Measurement.h", "rank": 91, "score": 67053.51748038904 }, { "content": " class BLOOM_EXPORT Vector2 {\n\n Measurement x;\n\n Measurement y;\n\n\n\n public:\n\n Vector2() : x(Measurement(Measurements::stretch, 0)),\n\n y(Measurement(Measurements::stretch, 0)) { }\n\n\n\n Vector2(const Measurement &x, const Measurement &y) : x(x), y(y) { }\n\n\n\n Vector2(const Vector2 &v) : Vector2(v.x, v.y) { }\n\n\n\n// Vector2 &operator=(const Vector2 &other) {\n\n//// set_x(*v.x);\n\n//// set_y(*v.y);\n\n// x = other.x;\n\n// y = other.y;\n\n// return *this;\n\n// }\n\n\n", "file_path": "projects/client/gui/bloom/source/bloom/layout/Measurement.h", "rank": 92, "score": 67053.51748038904 }, { "content": " class BLOOM_EXPORT Border {\n\n vec4 color;\n\n\n\n public:\n\n void render(Draw_Interface &draw, const Bounds &bounds) const;\n\n\n\n void set_color(vec4 color) {\n\n this->color = color;\n\n }\n\n };\n\n}", "file_path": "projects/client/gui/bloom/source/bloom/styling/Border.h", "rank": 93, "score": 67053.51748038904 }, { "content": " class BLOOM_EXPORT Bounds {\n\n// vec2 top_left;\n\n// vec2 bottom_right;\n\n//\n\n// Bounds(const vec2 &top_left, const vec2 &bottom_right) : top_left(top_left), bottom_right(bottom_right) { }\n\n// Bounds(float top, float left, float bottom, float right) : top_left(vec2(top, left)), bottom_right(vec2(bottom, right)) { }\n\n\n\n vec2 position;\n\n vec2 dimensions;\n\n vec2 corner;\n\n\n\n public:\n\n\n\n Bounds(const vec2 &position, const vec2 &dimensions) :\n\n position(position), dimensions(dimensions), corner(position + dimensions) {\n\n }\n\n\n\n const vec2 &get_position() const {\n\n return position;\n\n }\n\n\n\n const vec2 &get_dimensions() const {\n\n return dimensions;\n\n }\n\n\n\n const vec2 &get_corner() const {\n\n return corner;\n\n }\n\n };\n\n}", "file_path": "projects/client/gui/bloom/source/bloom/layout/Bounds.h", "rank": 94, "score": 67053.51748038904 }, { "content": " class BLOOM_EXPORT Fill {\n\n vec4 color;\n\n\n\n public:\n\n void render(Draw_Interface &draw, const Bounds &bounds) const;\n\n\n\n void set_color(vec4 color) {\n\n this->color = color;\n\n }\n\n\n\n vec4 &get_color() {\n\n return color;\n\n }\n\n };\n\n}", "file_path": "projects/client/gui/bloom/source/bloom/styling/Fill.h", "rank": 95, "score": 67053.51748038904 }, { "content": " class BLOOM_EXPORT Box_Style {\n\n unique_ptr<Vector4> padding;\n\n Box_Style *parent_box = nullptr;\n\n\n\n protected:\n\n void set_parent_box(Box_Style *value) {\n\n parent_box = value;\n\n }\n\n\n\n public:\n\n\n\n virtual ~Box_Style() { }\n\n\n\n const Vector4 *get_padding() const {\n\n if (!padding.get() && parent_box)\n\n return parent_box->get_padding();\n\n\n\n return padding.get();\n\n }\n\n\n", "file_path": "projects/client/gui/bloom/source/bloom/layout/Box_Style.h", "rank": 96, "score": 65389.186976589466 }, { "content": "#pragma once\n\n\n\n#include <bloom/Draw_Interface.h>\n\n\n\n#include <string>\n\n\n\nnamespace bloom {\n", "file_path": "projects/client/gui/bloom_lookinglass/source/Lookinglass_Bloom.h", "rank": 97, "score": 18.66230129641556 }, { "content": "#pragma once\n\n\n\n\n\n#include <glm/vec2.hpp>\n\n#include \"bloom/bloom_export.h\"\n\n\n\nusing namespace glm;\n\n\n\nnamespace bloom {\n\n\n", "file_path": "projects/client/gui/bloom/source/bloom/layout/Bounds.h", "rank": 98, "score": 18.099933945240863 }, { "content": "#include \"Lookinglass_Bloom.h\"\n\n#include <bloom/Garden.h>\n\n#include <glow.h>\n\n#include \"lookinglass/Lookinglass_Resources.h\"\n\n#include \"lookinglass/House.h\"\n\n#include <drawing/Draw.h>\n\n\n\nLookinglass_Bloom::Lookinglass_Bloom(lookinglass::House &house, drawing::Draw &draw) :\n\n house(house), draw(draw) {\n\n\n\n}\n\n\n\nvoid Lookinglass_Bloom::render(bloom::Garden &garden) {\n\n enable_3d(false);\n\n garden.render();\n\n enable_3d(true);\n\n}\n\n\n\nvoid Lookinglass_Bloom::enable_3d(bool value) {\n\n draw.set_depth(value);\n", "file_path": "projects/client/gui/bloom_lookinglass/source/Lookinglass_Bloom.cpp", "rank": 99, "score": 17.84511289271168 } ]
C++
ProjectLunarFront/LogSystem.hpp
Edgaru089/ProjectLunarFront
bf59c6dec36e0576082acf3c72abf3c82bc92241
#pragma once #include <iostream> #include <string> #include <ctime> #include <cstring> #include <cstdio> #include <functional> #include <vector> #include <mutex> #include "StringParser.hpp" using namespace std; #define AUTOLOCK(a) lock_guard<mutex> __mutex_lock(a) #ifndef DISABLE_ALL_LOGS class Log { public: const wstring logLevelName[6] = { L"DEBUG", L"INFO", L"EVENT", L"WARN", L"ERROR", L"FATAL ERROR" }; enum LogLevel { Debug, Info, Event, Warning, Error, FatalError }; Log() :ignoreLevel(-1) {} Log(wostream& output) :out({ &output }), ignoreLevel(-1) {} Log(wostream* output) :out({ output }), ignoreLevel(-1) {} void log(const wstring& content, LogLevel level = Info) { if (level <= ignoreLevel) return; time_t curtime = time(NULL); wchar_t buffer[64] = {}; wcsftime(buffer, 63, L"[%T", localtime(&curtime)); wstring final = wstring(buffer) + L" " + logLevelName[level] + L"] " + content + L'\n'; lock.lock(); buffers.push_back(final); for (wostream* i : out) { (*i) << final; i->flush(); if (!(*i)) i->clear(); } for (const auto& i : outf) i(final); lock.unlock(); } template<typename... Args> void logf(LogLevel level, wstring format, Args... args) { wchar_t buf[2560]; wsprintf(buf, format.c_str(), args...); log(wstring(buf), level); } void operator() (const wstring& content, LogLevel level = Info) { log(content, level); } void addOutputStream(wostream& output) { lock.lock(); out.push_back(&output); lock.unlock(); } void addOutputStream(wostream* output) { lock.lock(); out.push_back(output); lock.unlock(); } void addOutputHandler(function<void(const wstring&)> output) { lock.lock(); outf.push_back(output); lock.unlock(); } void ignore(int level) { ignoreLevel = level; } int getIgnoreLevel() { return ignoreLevel; } const vector<wstring>& getBuffers() { return buffers; } void clearBuffer() { AUTOLOCK(lock); buffers.clear(); } private: vector<wostream*> out; vector<function<void(const wstring&)>> outf; mutex lock; int ignoreLevel; vector<wstring> buffers; }; extern Log dlog; class LogMessage { public: LogMessage() :level(Log::Info) {} LogMessage(Log::LogLevel level) :level(level) {} LogMessage& operator <<(bool data) { buffer += data ? L"true" : L"false"; return *this; } LogMessage& operator <<(char data) { buffer += (data); return *this; } LogMessage& operator <<(unsigned char data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(short data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(unsigned short data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(int data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(unsigned int data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(long data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(unsigned long data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(long long data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(unsigned long long data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(float data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(double data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(long double data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(const wchar_t* data) { buffer += wstring(data); return *this; } LogMessage& operator <<(const char* data) { buffer += utf8ToWstring(data); return *this; } LogMessage& operator <<(const wstring& data) { buffer += data; return *this; } LogMessage& operator <<(const string& data) { buffer += utf8ToWstring(data); return *this; } LogMessage& operator <<(Log::LogLevel level) { this->level = level; return *this; } LogMessage& operator <<(Log& log) { flush(log); return *this; } public: void setLevel(Log::LogLevel level) { this->level = level; } void flush(Log& log) { logout(log); clear(); } void logout(Log& log) { log(buffer, level); } void clear() { buffer.clear(); } private: wstring buffer; Log::LogLevel level; }; #define mlog LogMessage() #define mloge LogMessage(Log::Event) #define mlogd LogMessage(Log::Debug) #else class Log { public: enum LogLevel { Debug, Info, Event, Warning, Error, FatalError }; Log() {} Log(wostream& output) {} Log(wostream* output) {} void log(const wstring&, LogLevel) {} template<typename... Args> void logf(LogLevel, wstring, Args...) {} void operator() (const wstring&, LogLevel level) {} void addOutputStream(wostream&) {} void addOutputStream(wostream*) {} void addOutputHandler(function<void(const wstring&)>) {} void ignore(int) {} int getIgnoreLevel() { return -1; } const vector<wstring>& getBuffers() {} void clearBuffer() {} }; class LogMessage { public: LogMessage() {} LogMessage(Log::LogLevel level) {} LogMessage& operator <<(bool) { return *this; } LogMessage& operator <<(char) { return *this; } LogMessage& operator <<(unsigned char) { return *this; } LogMessage& operator <<(short) { return *this; } LogMessage& operator <<(unsigned short) { return *this; } LogMessage& operator <<(int) { return *this; } LogMessage& operator <<(unsigned int) { return *this; } LogMessage& operator <<(long long) { return *this; } LogMessage& operator <<(unsigned long long) { return *this; } LogMessage& operator <<(float) { return *this; } LogMessage& operator <<(double) { return *this; } LogMessage& operator <<(const wchar_t*) { return *this; } LogMessage& operator <<(const char*) { return *this; } LogMessage& operator <<(const wstring&) { return *this; } LogMessage& operator <<(const string&) { return *this; } LogMessage& operator <<(Log::LogLevel) { return *this; } LogMessage& operator <<(Log&) { return *this; } public: void setLevel(Log::LogLevel) {} void flush(Log&) {} void logout(Log&) {} void clear() {} }; #ifdef USE_WCOUT_AS_LOG #define mlog (wcout << L"[INFO] ") #define mloge (wcout << L"[EVENT] ") #define mlogd (wcout << L"DEBUG ") #define dlog endl inline wostream& operator << (wostream& out, const string& str) { out << utf8ToWstring(str); return out; } #else extern Log dlog; #define mlog LogMessage() #define mloge LogMessage(Log::Event) #define mlogd LogMessage(Log::Debug) #endif #endif
#pragma once #include <iostream> #include <string> #include <ctime> #include <cstring> #include <cstdio> #include <functional> #include <vector> #include <mutex> #include "StringParser.hpp" using namespace std; #define AUTOLOCK(a) lock_guard<mutex> __mutex_lock(a) #ifndef DISABLE_ALL_LOGS class Log { public: const wstring logLevelName[6] = { L"DEBUG", L"INFO", L"EVENT", L"WARN", L"ERROR", L"FATAL ERROR" }; enum LogLevel { Debug, Info, Event, Warning, Error, FatalError }; Log() :ignoreLevel(-1) {} Log(wostream& output) :out({ &output }), ignoreLevel(-1) {} Log(wostream* output) :out({ output }), ignoreLevel(-1) {}
template<typename... Args> void logf(LogLevel level, wstring format, Args... args) { wchar_t buf[2560]; wsprintf(buf, format.c_str(), args...); log(wstring(buf), level); } void operator() (const wstring& content, LogLevel level = Info) { log(content, level); } void addOutputStream(wostream& output) { lock.lock(); out.push_back(&output); lock.unlock(); } void addOutputStream(wostream* output) { lock.lock(); out.push_back(output); lock.unlock(); } void addOutputHandler(function<void(const wstring&)> output) { lock.lock(); outf.push_back(output); lock.unlock(); } void ignore(int level) { ignoreLevel = level; } int getIgnoreLevel() { return ignoreLevel; } const vector<wstring>& getBuffers() { return buffers; } void clearBuffer() { AUTOLOCK(lock); buffers.clear(); } private: vector<wostream*> out; vector<function<void(const wstring&)>> outf; mutex lock; int ignoreLevel; vector<wstring> buffers; }; extern Log dlog; class LogMessage { public: LogMessage() :level(Log::Info) {} LogMessage(Log::LogLevel level) :level(level) {} LogMessage& operator <<(bool data) { buffer += data ? L"true" : L"false"; return *this; } LogMessage& operator <<(char data) { buffer += (data); return *this; } LogMessage& operator <<(unsigned char data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(short data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(unsigned short data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(int data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(unsigned int data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(long data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(unsigned long data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(long long data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(unsigned long long data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(float data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(double data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(long double data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(const wchar_t* data) { buffer += wstring(data); return *this; } LogMessage& operator <<(const char* data) { buffer += utf8ToWstring(data); return *this; } LogMessage& operator <<(const wstring& data) { buffer += data; return *this; } LogMessage& operator <<(const string& data) { buffer += utf8ToWstring(data); return *this; } LogMessage& operator <<(Log::LogLevel level) { this->level = level; return *this; } LogMessage& operator <<(Log& log) { flush(log); return *this; } public: void setLevel(Log::LogLevel level) { this->level = level; } void flush(Log& log) { logout(log); clear(); } void logout(Log& log) { log(buffer, level); } void clear() { buffer.clear(); } private: wstring buffer; Log::LogLevel level; }; #define mlog LogMessage() #define mloge LogMessage(Log::Event) #define mlogd LogMessage(Log::Debug) #else class Log { public: enum LogLevel { Debug, Info, Event, Warning, Error, FatalError }; Log() {} Log(wostream& output) {} Log(wostream* output) {} void log(const wstring&, LogLevel) {} template<typename... Args> void logf(LogLevel, wstring, Args...) {} void operator() (const wstring&, LogLevel level) {} void addOutputStream(wostream&) {} void addOutputStream(wostream*) {} void addOutputHandler(function<void(const wstring&)>) {} void ignore(int) {} int getIgnoreLevel() { return -1; } const vector<wstring>& getBuffers() {} void clearBuffer() {} }; class LogMessage { public: LogMessage() {} LogMessage(Log::LogLevel level) {} LogMessage& operator <<(bool) { return *this; } LogMessage& operator <<(char) { return *this; } LogMessage& operator <<(unsigned char) { return *this; } LogMessage& operator <<(short) { return *this; } LogMessage& operator <<(unsigned short) { return *this; } LogMessage& operator <<(int) { return *this; } LogMessage& operator <<(unsigned int) { return *this; } LogMessage& operator <<(long long) { return *this; } LogMessage& operator <<(unsigned long long) { return *this; } LogMessage& operator <<(float) { return *this; } LogMessage& operator <<(double) { return *this; } LogMessage& operator <<(const wchar_t*) { return *this; } LogMessage& operator <<(const char*) { return *this; } LogMessage& operator <<(const wstring&) { return *this; } LogMessage& operator <<(const string&) { return *this; } LogMessage& operator <<(Log::LogLevel) { return *this; } LogMessage& operator <<(Log&) { return *this; } public: void setLevel(Log::LogLevel) {} void flush(Log&) {} void logout(Log&) {} void clear() {} }; #ifdef USE_WCOUT_AS_LOG #define mlog (wcout << L"[INFO] ") #define mloge (wcout << L"[EVENT] ") #define mlogd (wcout << L"DEBUG ") #define dlog endl inline wostream& operator << (wostream& out, const string& str) { out << utf8ToWstring(str); return out; } #else extern Log dlog; #define mlog LogMessage() #define mloge LogMessage(Log::Event) #define mlogd LogMessage(Log::Debug) #endif #endif
void log(const wstring& content, LogLevel level = Info) { if (level <= ignoreLevel) return; time_t curtime = time(NULL); wchar_t buffer[64] = {}; wcsftime(buffer, 63, L"[%T", localtime(&curtime)); wstring final = wstring(buffer) + L" " + logLevelName[level] + L"] " + content + L'\n'; lock.lock(); buffers.push_back(final); for (wostream* i : out) { (*i) << final; i->flush(); if (!(*i)) i->clear(); } for (const auto& i : outf) i(final); lock.unlock(); }
function_block-full_function
[ { "content": "class StringDatabase :public Lockable {\n\npublic:\n\n\n\n\tbool initializeWithFolder(const fs::path& dbFolder);\n\n\n\n\tUuid insert(const string& contents);\n\n\tbool remove(Uuid id);\n\n\n\n\tconst StringDBObject& get(Uuid id) {\n\n\t\tlock_guard<Lockable>(*this);\n\n\t\tauto i = objs.find(id);\n\n\t\tif (i == objs.end())\n\n\t\t\treturn empty;\n\n\t\telse\n\n\t\t\treturn i->second;\n\n\t}\n\n\n\nprivate:\n\n\tfs::path dbdir;\n\n\tmap<Uuid, StringDBObject> objs;\n\n\tStringDBObject empty;\n\n};\n\n\n\nextern StringDatabase stringDatabase;\n\n\n", "file_path": "ProjectLunarFront/StringDatabase.hpp", "rank": 0, "score": 116037.95935507311 }, { "content": "class StringDBObject :public enable_shared_from_this<StringDBObject> {\n\npublic:\n\n\tStringDBObject() :loaded(false) {}\n\n\tStringDBObject(Uuid id, const fs::path& file) :\n\n\t\tid(id), filedir(file), loaded(false) {}\n\n\tStringDBObject(Uuid id, const fs::path& file, const string& contents) :\n\n\t\tid(id), filedir(file), contents(contents), loaded(true) {}\n\n\n\n\tUuid getId() const { return id; }\n\n\tconst fs::path& getFileDir() const { return filedir; }\n\n\tuintmax_t getSize() { return fs::file_size(filedir); }\n\n\n\n\tbool isLoaded() const { return loaded; }\n\n\tvoid ensureLoaded() const {\n\n\t\tif (!loaded) {\n\n\t\t\tcontents = readFileBinary(filedir.generic_wstring());\n\n\t\t\tif (!contents.empty())\n\n\t\t\t\tloaded = true;\n\n\t\t}\n\n\t}\n", "file_path": "ProjectLunarFront/StringDatabase.hpp", "rank": 1, "score": 108306.13305169705 }, { "content": "class HTTPResponseError :public HTTPResponseWrapper {\n\npublic:\n\n\n\n\tHTTPResponseError() {}\n\n\tHTTPResponseError(int code) { this->code = code; }\n\n\n\n\tstring what() const override { return \"<HTTP Error>: \" + to_string(code) + ' ' + httpdata.getResponseString(code); }\n\n\n\n\tvoid send(shared_ptr<TcpSocket> socket) override;\n\n\n\nprivate:\n\n\tint code;\n\n};\n\n\n\n\n", "file_path": "ProjectLunarFront/HTTPResponseWrapper.hpp", "rank": 3, "score": 99115.75933630954 }, { "content": "class Instance : public Lockable {\n\npublic:\n\n\n\n\tenum RequestMethod {\n\n\t\tGet,\n\n\t\tPost\n\n\t};\n\n\n\n\tstruct Config {\n\n\t\tConfig() {}\n\n\n\n\t\t// Port the HTTP server will be listening\n\n\t\tUint16 port = 5000;\n\n\n\n\t\t// Filename of the Base 64 DER encoded certificate\n\n\t\twstring cert = wstring();\n\n\n\n\t\t// Filename of the PKCS8 private key file\n\n\t\t// and the optional password\n\n\t\twstring key = wstring();\n", "file_path": "ProjectLunarFront/Instance.hpp", "rank": 4, "score": 83985.31717335299 }, { "content": "\tclass DisconnectedException :public exception {\n\n\t\tchar const* what() const noexcept override { return \"Socket disconnected when waiting for contents\"; }\n\n\t};\n\n\n\n\tunsigned char getchar(shared_ptr<TcpSocket> socket) {\n\n\t\tunsigned char c = 0;\n\n\t\tsize_t i = 0;\n\n\n\n\t\tSocket::Status stat;\n\n\t\twhile ((stat = socket->receive(&c, 1, i)) != Socket::Disconnected&&stat != Socket::Error && i <= 0) {\n\n\t\t\tif (stat == Socket::NotReady || stat == Socket::Partial)\n\n\t\t\t\tsleep(milliseconds(2));\n\n\t\t\ti = 0;\n\n\t\t}\n\n\t\tif (stat == Socket::Disconnected || stat == Socket::Error)\n\n\t\t\tthrow DisconnectedException();\n\n\n\n\t\treturn c;\n\n\t}\n\n\n", "file_path": "ProjectLunarFront/Instance.cpp", "rank": 5, "score": 82243.79895738038 }, { "content": "class ProblemDatabase :public Lockable {\n\npublic:\n\n\n\n\tbool loadFromFile(const wstring& filename);\n\n\n\n\tProblem::Ptr getProblem(int id) {\n\n\t\tauto i = problems.find(id);\n\n\t\tif (i == problems.end())\n\n\t\t\treturn nullptr;\n\n\t\telse\n\n\t\t\treturn i->second;\n\n\t}\n\n\n\n\tbool isLoaded() { return loaded; }\n\n\n\nprivate:\n\n\tmap<int, Problem::Ptr> problems;\n\n\tbool loaded = false;\n\n};\n\n\n\nextern ProblemDatabase problemDatabase;\n\n\n", "file_path": "ProjectLunarFront/Problem.hpp", "rank": 6, "score": 82243.79895738038 }, { "content": "class NotImplementedException :public exception {\n\npublic:\n\n\tNotImplementedException() { contents = \"NotImplementedException: an unknown function not implemented\"; }\n\n\tNotImplementedException(const string& funcName) { contents = \"NotImplementedException: function \\\"\" + funcName + \"\\\" not implemented\"; }\n\n\tconst char* what() const noexcept override { return contents.c_str(); }\n\nprivate:\n\n\tstring contents;\n\n};\n\n\n\nstring getUserNavString(const map<string, string>& cookies);\n\n\n\n//#define DISABLE_ALL_LOGS\n\n//#define USE_WCOUT_AS_LOG\n\n#include \"LogSystem.hpp\"\n\n#include \"Uuid.hpp\"\n\n#include \"Config.hpp\"\n\n#include \"Lockable.hpp\"\n\n\n\nextern Config config;\n\n\n\n#ifndef _WIN32\n\n\n\n#include <signal.h>\n\n\n\n#endif\n", "file_path": "ProjectLunarFront/Main.hpp", "rank": 7, "score": 82243.79895738038 }, { "content": "class JudgeRecord :public Lockable, public enable_shared_from_this<JudgeRecord> {\n\npublic:\n\n\n\n\ttypedef shared_ptr<JudgeRecord> Ptr;\n\n\n\n\tenum State {\n\n\t\tWaiting,\n\n\t\tCompiling,\n\n\t\tRunning,\n\n\t\tAccepted,\n\n\t\tWrongAnswer,\n\n\t\tTimeLimitExceeded,\n\n\t\tMemoryLimitExceeded,\n\n\t\tRuntimeError,\n\n\t\tCompileError,\n\n\t\tFailedToRun,\n\n\t\tUnknownError,\n\n\t\tCount\n\n\t};\n\n\n", "file_path": "ProjectLunarFront/JudgeRecord.hpp", "rank": 8, "score": 82225.89482827453 }, { "content": "class PageStatus : public Page {\n\npublic:\n\n\n\n\tstring getRequestPrefix() override { return \"/status\"; }\n\n\n\n\tHTTPResponseWrapper::Ptr getPage(const HTTPRequest& request) {\n\n\t\tstring tr;\n\n\t\tconst string& uri = request.GetURI();\n\n\t\tmap<string, string> cookies, uriParams;\n\n\t\tdecodeCookieAndUriParam(request, cookies, uriParams);\n\n\t\tint page = 1;\n\n\t\tif (auto i = uriParams.find(\"page\"); i != uriParams.end())\n\n\t\t\tpage = StringParser::toInt(i->second);\n\n\t\t// TODO Display all the results for now\n\n\t\tjudgeRecordDatabase.lock();\n\n\t\tfor (auto&[id, record] : judgeRecordDatabase.getRecords()) {\n\n\t\t\tProblem& prob = *problemDatabase.getProblem(record->probId);\n\n\t\t\t// format the submit time\n\n\t\t\ttime_t t = (time_t)record->submitUnixTime;\n\n\t\t\tchar tstr[48];\n", "file_path": "ProjectLunarFront/PageStatus.hpp", "rank": 9, "score": 80607.49665510491 }, { "content": "class JudgeRecordDatabase :public Lockable {\n\npublic:\n\n\n\n\tvoid loadFromFile(const wstring& filename);\n\n\n\n\tvoid saveToFile(const wstring& filename);\n\n\n\n\tint handInCode(int userId, int probId, const string& code, bool wantJudgeNow = true);\n\n\n\n\tvoid requestRejudge(int recordId, bool pushFront = false);\n\n\n\n\t// Not thread-safe; this->lock when reading\n\n\tauto& getWaitingQueue() { return waitingQueue; }\n\n\n\n\t// Not thread-safe; this->lock when reading\n\n\tauto& getRecords() { return records; }\n\n\n\nprivate:\n\n\tint maxid;\n\n\tmap<int, JudgeRecord::Ptr, greater<int>> records;\n\n\tdeque<int> waitingQueue;\n\n};\n\n\n\nextern JudgeRecordDatabase judgeRecordDatabase;\n", "file_path": "ProjectLunarFront/JudgeRecord.hpp", "rank": 10, "score": 79067.15473980043 }, { "content": "\tclass BadRequestException :public exception {\n\n\t\tchar const* what() const noexcept override { return \"HTTP/400 Bad Request\"; }\n\n\t};\n\n\n\n\tstatic HTTPRequest parseRequest(string header) {\n\n\t\tHTTPRequest result;\n\n\n\n\t\tsize_t headerlen = header.find(\"\\r\\n\\r\\n\");\n\n\t\tif (headerlen == string::npos)\n\n\t\t\tthrow BadRequestException();\n\n\n\n\t\tstring body = header.substr(headerlen + 4);\n\n\t\theader.resize(headerlen);\n\n\n\n\t\tsize_t off = 0;\n\n\t\tresult.SetMethod(readNextWord(header, off));\n\n\t\tresult.SetURI(readNextWord(header, off));\n\n\t\tif (readNextWord(header, off) != \"HTTP/1.1\")\n\n\t\t\tthrow BadRequestException();\n\n\n", "file_path": "ProjectLunarFront/HTTPParser.hpp", "rank": 11, "score": 79067.15473980043 }, { "content": "class Problem :public enable_shared_from_this<Problem> {\n\npublic:\n\n\n\n\ttypedef shared_ptr<Problem> Ptr;\n\n\n\n\tenum JudgeMethod {\n\n\t\tByByte,\n\n\t\tByLineIgnoreTrailingSpaces,\n\n\t\tRealNumber, // < 1e-6\n\n\t};\n\n\n\n\tstruct DataPoint {\n\n\t\tint timeLimitMs;\n\n\t\tint memoryLimitKb;\n\n\t\tint totalScore;\n\n\t};\n\n\n\n\tint id;\n\n\tstring name, strid;\n\n\tstring rawMarkdownStr;\n", "file_path": "ProjectLunarFront/Problem.hpp", "rank": 13, "score": 78270.07341648333 }, { "content": "class Page : public enable_shared_from_this<Page> {\n\npublic:\n\n\n\n\t// Return the prefix string that will be used to match the requests handled\n\n\tvirtual string getRequestPrefix() = 0;\n\n\n\n\t// Return the request method that the page would listen to\n\n\t// Defaults to GET\n\n\tvirtual Instance::RequestMethod getRequestMethod() { return Instance::Get; }\n\n\n\n\t// The function called to response to a matched request\n\n\tvirtual HTTPResponseWrapper::Ptr getPage(const HTTPRequest& request) = 0;\n\n\n\n};\n\n\n\n\n", "file_path": "ProjectLunarFront/Page.hpp", "rank": 14, "score": 78270.07341648333 }, { "content": "class PageStatusDetail :public Page {\n\npublic:\n\n\n\n\tstring getRequestPrefix() override { return \"/statdetail/\"; }\n\n\n\n\tHTTPResponseWrapper::Ptr getPage(const HTTPRequest& request) {\n\n\t\tstring ft, tr;\n\n\t\tconst string& uri = request.GetURI();\n\n\t\tmap<string, string> cookies, uriParams;\n\n\t\tdecodeCookieAndUriParam(request, cookies, uriParams);\n\n\t\tint id = StringParser::toInt(uri.substr(uri.find_last_of('/') + 1));\n\n\t\tjudgeRecordDatabase.lock();\n\n\n\n\t\tauto i = judgeRecordDatabase.getRecords().find(id);\n\n\t\tif (i == judgeRecordDatabase.getRecords().end()) {\n\n\t\t\tjudgeRecordDatabase.unlock();\n\n\t\t\treturn filetemplate(\"html/general_div.html\", { { \"%CONT%\", \"Error: Record Not Found\" } });\n\n\t\t}\n\n\n\n\t\tauto rec = i->second;\n", "file_path": "ProjectLunarFront/PageStatusDetail.hpp", "rank": 15, "score": 77614.57233433604 }, { "content": "class HTTPResponseWrapper :public HTTPResponse {\n\npublic:\n\n\ttypedef shared_ptr<HTTPResponseWrapper> Ptr;\n\n\tvirtual void send(shared_ptr<TcpSocket> socket) = 0;\n\n\tvirtual string what() const = 0;\n\n};\n\n\n\n\n", "file_path": "ProjectLunarFront/HTTPResponseWrapper.hpp", "rank": 16, "score": 76242.45715280998 }, { "content": "class HTTPResponseRedirection :public HTTPResponseWrapper {\n\npublic:\n\n\n\n\tHTTPResponseRedirection() {}\n\n\t// Code is either 301 Moved Permanently or 302 Found\n\n\tHTTPResponseRedirection(const string& target, int code = 301, const vector<pair<string, string>>& cookies = {}) :\n\n\t\ttarget(target), cookies(cookies), code(code) {}\n\n\n\n\tstring what() const override { return \"<HTTP Redirection> Code: \" + to_string(code) + ' ' + httpdata.getResponseString(code) + \", Location: \" + target; }\n\n\n\n\tvoid send(shared_ptr<TcpSocket> socket) override;\n\n\n\nprivate:\n\n\tstring target;\n\n\tvector<pair<string, string>> cookies;\n\n\tint code;\n\n};\n\n\n\nvoid setFrameFile(const string& filename, const string& bodyFlag = \"%BODY%\");\n\n\n", "file_path": "ProjectLunarFront/HTTPResponseWrapper.hpp", "rank": 17, "score": 74944.3030611246 }, { "content": "class HTTPResponseTemplate :public HTTPResponseWrapper {\n\npublic:\n\n\n\n\tHTTPResponseTemplate() {}\n\n\tHTTPResponseTemplate(const wstring& filename, const vector<pair<string, string>>& replaces = {}, bool hasFrame = false, const string& mimeType = \"text/html\") :\n\n\t\tfilename(filename), replaces(replaces), hasFrame(hasFrame), mimeType(mimeType) {}\n\n\n\n\tbool isFileStreamOK() { return (bool)file; }\n\n\n\n\tstring what() const override { return \"<Template> Filename:\" + wstringToUtf8(filename); }\n\n\n\n\tvoid send(shared_ptr<TcpSocket> socket) override;\n\n\n\nprivate:\n\n\tbool hasFrame;\n\n\twstring filename;\n\n\tvector<pair<string, string>> replaces;\n\n\tstring mimeType;\n\n\tifstream file;\n\n};\n\n\n\n\n", "file_path": "ProjectLunarFront/HTTPResponseWrapper.hpp", "rank": 18, "score": 74944.3030611246 }, { "content": "class HTTPResponseFile :public HTTPResponseWrapper {\n\npublic:\n\n\n\n\tHTTPResponseFile() {}\n\n\tHTTPResponseFile(const wstring& filename, const string& mimeType = \"application/octet-stream\") :\n\n\t\tfilename(filename), mimeType(mimeType) {}\n\n\n\n\tbool isFileStreamOK() { return (bool)file; }\n\n\n\n\tstring what() const override { return \"<File> Filename:\" + wstringToUtf8(filename); }\n\n\n\n\tvoid send(shared_ptr<TcpSocket> socket) override;\n\n\n\nprivate:\n\n\twstring filename;\n\n\tstring mimeType;\n\n\tifstream file;\n\n};\n\n\n\n\n", "file_path": "ProjectLunarFront/HTTPResponseWrapper.hpp", "rank": 19, "score": 74944.3030611246 }, { "content": "class HTTPResponseShort :public HTTPResponseWrapper {\n\npublic:\n\n\tHTTPResponseShort() {}\n\n\tHTTPResponseShort(const wstring& body, bool hasFrame = true, const vector<pair<string, string>>& replaces = {})\n\n\t\t:hasFrame(hasFrame), replaces(replaces) {\n\n\t\tSetBody(wstringToUtf8(body));\n\n\t}\n\n\tHTTPResponseShort(const string& body, bool hasFrame = true, const vector<pair<string, string>>& replaces = {})\n\n\t\t:hasFrame(hasFrame), replaces(replaces) {\n\n\t\tSetBody(body);\n\n\t}\n\n\n\n\tstring what() const override { return \"<Short Response>\"; }\n\n\n\n\tvoid send(shared_ptr<TcpSocket> socket) override;\n\nprivate:\n\n\tbool hasFrame;\n\n\tvector<pair<string, string>> replaces;\n\n};\n\n\n\n\n", "file_path": "ProjectLunarFront/HTTPResponseWrapper.hpp", "rank": 20, "score": 74944.3030611246 }, { "content": "class SFNUL_API HTTPRequest : public HTTPMessage {\n\npublic:\n\n\t/** Constructor.\n\n\t */\n\n\tHTTPRequest();\n\n\n\n\t/** Get the method this HTTP request should employ.\n\n\t * @return The method this HTTP request should employ.\n\n\t */\n\n\tconst std::string& GetMethod() const;\n\n\n\n\t/** Set the method this HTTP request should employ.\n\n\t * @param method The method this HTTP request should employ.\n\n\t */\n\n\tvoid SetMethod( std::string method );\n\n\n\n\t/** Get the URI of this HTTP request.\n\n\t * @return The URI of this HTTP request.\n\n\t */\n\n\tconst std::string& GetURI() const;\n", "file_path": "ProjectLunarFront/SFNUL/HTTP.hpp", "rank": 21, "score": 73905.03391418839 }, { "content": "class SFNUL_API HTTPResponse : public HTTPMessage {\n\npublic:\n\n\t/** Get the HTTP version of this response. e.g. \"HTTP/1.1\"\n\n\t * @return HTTP version of this response.\n\n\t */\n\n\tconst std::string& GetHTTPVersion() const;\n\n\n\n\t/** Set the HTTP version of this response. e.g. \"HTTP/1.1\"\n\n\t * @param version The HTTP version of this response.\n\n\t */\n\n\tvoid SetHTTPVersion( std::string version );\n\n\n\n\t/** Get the HTTP status of this response in string form. e.g. \"OK\" for 200\n\n\t * @return The HTTP status of this response in string form.\n\n\t */\n\n\tconst std::string& GetStatus() const;\n\n\n\n\t/** Set the HTTP status of this response in string form. e.g. \"OK\" for 200\n\n\t * @param status The HTTP status of this response in string form.\n\n\t */\n", "file_path": "ProjectLunarFront/SFNUL/HTTP.hpp", "rank": 22, "score": 73905.03391418839 }, { "content": "class HTTPStringData {\n\npublic:\n\n\tHTTPStringData();\n\n\n\n\tstring getResponseString(int code) {\n\n\t\tif (auto i = strings.find(code); i != strings.end())\n\n\t\t\treturn i->second;\n\n\t\telse\n\n\t\t\treturn empty;\n\n\t}\n\n\n\n\tstring getMIMEString(const string& str) {\n\n\t\tif (auto i = mimes.find(str); i != mimes.end())\n\n\t\t\treturn i->second;\n\n\t\telse\n\n\t\t\treturn \"application/octet-stream\";\n\n\t}\n\n\n\nprivate:\n\n\tmap<int, string> strings;\n\n\tmap<string, string> mimes;\n\n\tstring empty;\n\n};\n\n\n\nextern HTTPStringData httpdata;\n\n\n\n\n\n\n", "file_path": "ProjectLunarFront/HTTPResponseWrapper.hpp", "rank": 23, "score": 67176.01727383635 }, { "content": "class User {\n\npublic:\n\n\n\n\tUser() {}\n\n\n\n\n\n};\n\n\n", "file_path": "ProjectLunarFront/User.hpp", "rank": 24, "score": 43935.67833141917 }, { "content": "class Config {\n\npublic:\n\n\n\n\tbool loadFromFile(const wstring& filename) {\n\n\t\tif (!file.loadFromFile(filename))\n\n\t\t\treturn false;\n\n\n\n\t\tstring listenPortStr = \"5000\";\n\n\n\n\t\tsetStringIfNotEmpty(tempDir, file.getContent(\"temp_dir\"));\n\n\t\tsetStringIfNotEmpty(listenPortStr, file.getContent(\"port\"));\n\n\t\tsetStringIfNotEmpty(hostname, file.getContent(\"hostname\"));\n\n\t\tsetStringIfNotEmpty(cppCompiler, file.getContent(\"cpp_compiler\"));\n\n\n\n\t\t// if tempDir does not exist, create it\n\n\t\tfilesystem::create_directories(tempDir);\n\n\n\n\t\treturn true;\n\n\t}\n\n\n", "file_path": "ProjectLunarFront/Config.hpp", "rank": 25, "score": 43935.67833141917 }, { "content": "class SHA256\n\n{\n\nprotected:\n\n typedef unsigned char uint8;\n\n typedef unsigned int uint32;\n\n typedef unsigned long long uint64;\n\n \n\n const static uint32 sha256_k[];\n\n static const unsigned int SHA224_256_BLOCK_SIZE = (512/8);\n\npublic:\n\n void init();\n\n void update(const unsigned char *message, unsigned int len);\n\n void final(unsigned char *digest);\n\n static const unsigned int DIGEST_SIZE = ( 256 / 8);\n\n \n\nprotected:\n\n void transform(const unsigned char *message, unsigned int block_nb);\n\n unsigned int m_tot_len;\n\n unsigned int m_len;\n\n unsigned char m_block[2*SHA224_256_BLOCK_SIZE];\n\n uint32 m_h[8];\n\n};\n\n \n\nstd::string sha256(std::string input);\n", "file_path": "ProjectLunarFront/SHA-256.hpp", "rank": 26, "score": 43935.67833141917 }, { "content": "class Lockable {\n\npublic:\n\n\n\n\tLockable() { __mutex = std::make_shared<std::recursive_mutex>(); }\n\n\tvirtual ~Lockable() {}\n\n\n\n\tvoid lock() { ASSERT(__mutex); __mutex->lock(); }\n\n\tvoid unlock() { ASSERT(__mutex); __mutex->unlock(); }\n\n\tbool try_lock() { ASSERT(__mutex); return __mutex->try_lock(); }\n\n\tvoid* native_handle() { ASSERT(__mutex); return __mutex->native_handle(); }\n\n\n\nprivate:\n\n\tstd::shared_ptr<std::recursive_mutex> __mutex;\n\n};\n\n\n", "file_path": "ProjectLunarFront/Lockable.hpp", "rank": 27, "score": 43935.67833141917 }, { "content": "class Uuid {\n\npublic:\n\n\n\n\tstatic void seed(unsigned int val = 5489u) { uuid_random_engine.seed(val); }\n\n\n\n\t// Version 4.1 (Random)\n\n\tstatic Uuid get() {\n\n\t\tUuid id;\n\n\n\n\t\tunsigned int x = uuid_distribution(uuid_random_engine);\n\n\t\tid.sc1 = x;\n\n\n\n\t\tx = uuid_distribution(uuid_random_engine);\n\n\t\tid.sc2 = x & 0xFFFFu; // Lower 16 bits (2 bytes)\n\n\t\tid.sc3 = x & (x & 0xFFFF0000u) >> 16; // Higher 16 bits (2 bytes)\n\n\n\n\t\tx = uuid_distribution(uuid_random_engine);\n\n\t\tid.sc4 = x & 0xFFFFu; // Lower 16 bits (2 bytes)\n\n\t\tid.sc5_high2 = (x & 0xFFFF0000u) >> 16; // Higher 16 bits (2 bytes)\n\n\n", "file_path": "ProjectLunarFront/uuid.hpp", "rank": 28, "score": 43935.67833141917 }, { "content": "class OptionFile {\n\npublic:\n\n\n\n\tbool loadFromFile(const wstring& filename)\n\n\t{\n\n\t\tstring line, mark, cont;\n\n\t\tthis->data.clear();\n\n\t\tifstream file;\n\n\t\tOPEN_FSTREAM_WSTR(file, filename, ifstream::in);\n\n\t\tif (file.fail())\n\n\t\t\treturn false;\n\n\t\twhile (!file.eof()) {\n\n\t\t\tgetline(file, line);\n\n\t\t\tif (line[0] == '#')\n\n\t\t\t\tcontinue;\n\n\t\t\tsize_t pos = line.find('=');\n\n\t\t\tif (pos == string::npos)\n\n\t\t\t\tcontinue;\n\n\t\t\tmark = line.substr(0, pos);\n\n\t\t\tcont = line.substr(pos + 1, line.length() - pos - 1);\n", "file_path": "ProjectLunarFront/Config.hpp", "rank": 29, "score": 42953.1756451403 }, { "content": "class PageManager {\n\npublic:\n\n\n\n\tvoid registerRoutes(Instance& instance);\n\n\n\n\tvoid insertPage(shared_ptr<Page> page);\n\n\n\nprivate:\n\n\n\n\tstatic HTTPResponseWrapper::Ptr routeHandler(shared_ptr<Page> page, const HTTPRequest& request);\n\n\n\n\tvector<shared_ptr<Page>> pages;\n\n};\n\n\n\nextern PageManager pageManager;\n\n\n", "file_path": "ProjectLunarFront/Page.hpp", "rank": 30, "score": 42953.1756451403 }, { "content": "class Problem;\n\n\n", "file_path": "ProjectLunarFront/JudgeWorker.hpp", "rank": 31, "score": 42953.1756451403 }, { "content": "// Here, 'target' means contestant output; 'std' means standard data stored elsewhere\n\nclass JudgeWorker {\n\npublic:\n\n\tstatic void judge(shared_ptr<JudgeRecord> record);\n\n\n\nprivate:\n\n\tstatic fs::path compile(shared_ptr<JudgeRecord> record, const wstring& targetPathNoExt);\n\n\tstatic void judgeOneSet(const fs::path& exe, const fs::path& workingDir, const fs::path& targetIn, const fs::path& targetOut, int id, shared_ptr<JudgeRecord> record, const Problem& prob);\n\n\n\n\tstatic void compareByByte(const fs::path& stdOut, const fs::path& targetOut, int seqid, shared_ptr<JudgeRecord> record);\n\n\tstatic void compareByLine(const fs::path& stdOut, const fs::path& targetOut, int seqid, shared_ptr<JudgeRecord> record);\n\n\tstatic void compareRealNumber(const fs::path& stdOut, const fs::path& targetOut, int seqid, shared_ptr<JudgeRecord> record);\n\n\n\n\tstatic void judgeThreadWorker(int id, atomic_bool& running);\n\n\n\npublic:\n\n\n\n\tvoid launch(unsigned int workerCount = thread::hardware_concurrency());\n\n\tvoid stop();\n\n\n\n\tbool isRunning() { return running; }\n", "file_path": "ProjectLunarFront/JudgeWorker.hpp", "rank": 32, "score": 42040.529000488204 }, { "content": "class HTTPParser {\n\npublic:\n\n\n", "file_path": "ProjectLunarFront/HTTPParser.hpp", "rank": 33, "score": 42033.84888772432 }, { "content": "class JudgeRecord;\n", "file_path": "ProjectLunarFront/JudgeWorker.hpp", "rank": 34, "score": 42033.84888772432 }, { "content": "class SFNUL_API HTTPMessage {\n\npublic:\n\n\t/** Dtor.\n\n\t */\n\n\tvirtual ~HTTPMessage() = default;\n\n\n\n\t/** Get the value of a header field in this message if it is present.\n\n\t * @param field_name Name of the header field.\n\n\t * @return Value of the header field if it exists, or an empty std::string if not.\n\n\t */\n\n\tstd::string GetHeaderValue( const std::string& field_name ) const;\n\n\n\n\t/** Set the value of a header field in this message.\n\n\t * If the field has not previously been set, it will be created.\n\n\t * @param field Name of the field to set.\n\n\t * @param value Value to set the field to.\n\n\t */\n\n\tvoid SetHeaderValue( std::string field, std::string value );\n\n\n\n\t/** Get the body of this message.\n", "file_path": "ProjectLunarFront/SFNUL/HTTP.hpp", "rank": 35, "score": 38927.61117072486 }, { "content": "#pragma once\n\n\n\n#include <cstdio>\n\n#include <string>\n\n#include <sstream>\n\n#include <vector>\n\n\n\nusing namespace std;\n\n\n\nnamespace StringParser {\n\n\n\n\ttemplate<typename... Args>\n\n\tinline const string toStringF(const string& format, Args... args) {\n\n\t\tchar buffer[8192];\n\n\t\tsprintf(buffer, format.c_str(), args...);\n\n\t\treturn string(buffer);\n\n\t}\n\n\ttemplate<typename... Args>\n\n\tinline const wstring toStringFW(const wstring& format, Args... args) {\n\n\t\twchar_t buffer[8192];\n", "file_path": "ProjectLunarFront/StringParser.hpp", "rank": 42, "score": 30524.700378601843 }, { "content": "\t\t\tsource = dest;\n\n\t\t}\n\n\t\treturn source;\n\n\t}\n\n\n\n\tinline const string replaceSubString(const string& source, const vector<pair<string, string>>& replaces) { return replaceSubStringX<char>(source, replaces); }\n\n\tinline const wstring replaceSubStringW(const wstring& source, const vector<pair<wstring, wstring>>& replaces) { return replaceSubStringX<wchar_t>(source, replaces); }\n\n\n\n\tinline const bool toBool(const string& data) { int x; sscanf(data.c_str(), \"%d\", &x); return x; }\n\n\tinline const short toShort(const string& data) { int x; sscanf(data.c_str(), \"%d\", &x); return x; }\n\n\tinline const int toInt(const string& data) { int x; sscanf(data.c_str(), \"%d\", &x); return x; }\n\n\tinline const long long toLongLong(const string& data) { long long x; sscanf(data.c_str(), \"%lld\", &x); return x; }\n\n\tinline const float toFloat(const string& data) { float x; sscanf(data.c_str(), \"%f\", &x); return x; }\n\n\tinline const double toDouble(const string& data) { double x; sscanf(data.c_str(), \"%lf\", &x); return x; }\n\n\n\n\ttemplate<typename Type>\n\n\tinline const Type toValue(const string& data) { return Type(); }\n\n\ttemplate<> inline const bool toValue<bool>(const string& data) { return toBool(data); }\n\n\ttemplate<> inline const short toValue<short>(const string& data) { return toShort(data); }\n\n\ttemplate<> inline const int toValue<int>(const string& data) { return toInt(data); }\n\n\ttemplate<> inline const long long toValue<long long>(const string& data) { return toLongLong(data); }\n\n\ttemplate<> inline const float toValue<float>(const string& data) { return toFloat(data); }\n\n\ttemplate<> inline const double toValue<double>(const string& data) { return toDouble(data); }\n\n\ttemplate<> inline const string toValue<string>(const string& data) { return data; }\n\n};\n", "file_path": "ProjectLunarFront/StringParser.hpp", "rank": 43, "score": 30507.696092947797 }, { "content": "\t\twsprintf(buffer, format.c_str(), args...);\n\n\t\treturn wstring(buffer);\n\n\t}\n\n\n\n\ttemplate<typename Char = char>\n\n\tinline const basic_string<Char> replaceSubStringX(basic_string<Char> source, const vector<pair<basic_string<Char>, basic_string<Char>>>& replaces) {\n\n\t\tbasic_string<Char> dest;\n\n\n\n\t\tfor (auto&&[target, replaced] : replaces) {\n\n\t\t\tdest.clear();\n\n\t\t\tfor (int j = 0; j < source.size();) {\n\n\t\t\t\tif (source.substr(j, target.size()) == target) {\n\n\t\t\t\t\tj += target.size();\n\n\t\t\t\t\tdest += replaced;\n\n\t\t\t\t}\n\n\t\t\t\telse {\n\n\t\t\t\t\tdest += source[j];\n\n\t\t\t\t\tj++;\n\n\t\t\t\t}\n\n\t\t\t}\n", "file_path": "ProjectLunarFront/StringParser.hpp", "rank": 44, "score": 30507.296483535192 }, { "content": "#pragma once\n\n\n\n#include \"Main.hpp\"\n\n#include \"Lockable.hpp\"\n\n\n", "file_path": "ProjectLunarFront/StringDatabase.hpp", "rank": 45, "score": 30507.013022566593 }, { "content": "\n\n#include \"StringDatabase.hpp\"\n\n\n\nStringDatabase stringDatabase;\n\n\n\n\n\nbool StringDatabase::initializeWithFolder(const fs::path& dbFolder) {\n\n\tif (!fs::is_directory(dbFolder)) {\n\n\t\tfs::remove(dbFolder);\n\n\t\tfs::create_directory(dbFolder);\n\n\t}\n\n\n\n\tlock();\n\n\tmlog << \"[StringDatabase] Initializing, folder: \" << dbFolder.generic_wstring() << dlog;\n\n\tdbdir = dbFolder;\n\n\n\n\tfor (const auto& f : fs::directory_iterator(dbFolder)) {\n\n\t\tif (f.is_regular_file()) {\n\n\t\t\tUuid id(f.path().filename().generic_u8string());\n\n\t\t\tif (id == Uuid::nil())\n", "file_path": "ProjectLunarFront/StringDatabase.cpp", "rank": 46, "score": 30506.92043219605 }, { "content": "\n\n\tmlog << \"[StringDatabase] Insert string object with id=\" << str << dlog;\n\n\n\n\tfs::path newfile = dbdir / str;\n\n\twriteFileBinary(newfile.generic_wstring(), contents);\n\n\n\n\tlock();\n\n\tobjs.insert(make_pair(id, StringDBObject(id, newfile, contents)));\n\n\tunlock();\n\n\n\n\treturn id;\n\n}\n\n\n", "file_path": "ProjectLunarFront/StringDatabase.cpp", "rank": 47, "score": 30505.37250804943 }, { "content": "\t\t\t\tcontinue;\n\n\t\t\tobjs.insert(make_pair(id, StringDBObject(id, f.path())));\n\n\t\t\tmlog << \" Loaded object {\" << id.toString() << \"} with length=\" << f.file_size() << dlog;\n\n\t\t}\n\n\t}\n\n\n\n\tmlog << \"[StringDatabase] Initialization done, objects: \" << objs.size() << dlog;\n\n\tunlock();\n\n\treturn true;\n\n}\n\n\n\n\n\nbool StringDatabase::remove(Uuid id) {\n\n\tthrow NotImplementedException(\"StringDatabase::remove\");\n\n}\n\n\n\n\n\nUuid StringDatabase::insert(const string& contents) {\n\n\tUuid id = Uuid::get();\n\n\tstring str = id.toString();\n", "file_path": "ProjectLunarFront/StringDatabase.cpp", "rank": 48, "score": 30503.26995960842 }, { "content": "\n\n\tconst string& getString() const { ensureLoaded(); return contents; }\n\n\n\n\tbool isValid() { return id != Uuid::nil(); }\n\n\n\nprivate:\n\n\tfriend class StringDatabase;\n\n\n\n\tUuid id;\n\n\tfs::path filedir;\n\n\tmutable string contents;\n\n\tmutable bool loaded;\n\n};\n\n\n", "file_path": "ProjectLunarFront/StringDatabase.hpp", "rank": 49, "score": 30503.118147785608 }, { "content": "#pragma once\n\n\n\n#include <string>\n\n#include <fstream>\n\n#include <map>\n\n#include <mutex>\n\n#include <filesystem>\n\n#include \"Main.hpp\"\n\n\n\nusing namespace std;\n\n\n", "file_path": "ProjectLunarFront/Config.hpp", "rank": 50, "score": 22.562940780051544 }, { "content": "#pragma once\n\n\n\n#pragma warning(disable: 4018 4244 4003)\n\n// C4018: \"binary-operator\": signed/unsigned mismatch\n\n// C4244: convertion from \"type\" to \"type\", possible loss of data\n\n// C4003: persudo-function macro call \"macro-name\" no enough paramaters\n\n\n\n#include <vector>\n\n#include <set>\n\n#include <string>\n\n#include <fstream>\n\n#include <iostream>\n\n#include <thread>\n\n#include <atomic>\n\n#include <cctype>\n\n#include <mutex>\n\n#include <regex>\n\n#include <chrono>\n\n#include <random>\n\n#include <map>\n", "file_path": "ProjectLunarFront/Main.hpp", "rank": 51, "score": 18.700977701298743 }, { "content": "#pragma once\n\n\n\n#include <cstdlib>\n\n#include <string>\n\n#include <random>\n\n#include <istream>\n\n#include <ostream>\n\n\n\nusing namespace std;\n\n\n\nextern mt19937 uuid_random_engine;\n\nextern uniform_int_distribution<unsigned int> uuid_distribution;\n\n\n", "file_path": "ProjectLunarFront/uuid.hpp", "rank": 52, "score": 17.696955905463238 }, { "content": "#include <atomic>\n\n#include <list>\n\n#include <climits>\n\n#include <queue>\n\n#include \"SFNUL/HTTP.hpp\"\n\n#include <SFML/System.hpp>\n\n#include <SFML/Network.hpp>\n\n\n\n#ifdef _WIN32\n\n#define NOMINMAX\n\n#include <windows.h>\n\n#define OS_WINDOWS\n\n#endif\n\n\n\nusing namespace std;\n\nusing namespace sf;\n\nusing namespace sfn;\n\n\n\n#if (defined LOCAL) || (defined USE_DEBUG)\n\n#define DEBUG(...) printf(__VA_ARGS__)\n", "file_path": "ProjectLunarFront/Main.hpp", "rank": 53, "score": 17.17214695549885 }, { "content": "/* This Source Code Form is subject to the terms of the Mozilla Public\n\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n\n * file, You can obtain one at http://mozilla.org/MPL/2.0/. */\n\n\n\n#pragma once\n\n\n\n#include \"Config.hpp\"\n\n#include <unordered_map>\n\n#include <string>\n\n#include <vector>\n\n\n\nnamespace sfn {\n\n\n\n/** A HTTP message containing a header and a body.\n\n */\n", "file_path": "ProjectLunarFront/SFNUL/HTTP.hpp", "rank": 54, "score": 16.29692684402145 }, { "content": "/* This Source Code Form is subject to the terms of the Mozilla Public\n\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n\n * file, You can obtain one at http://mozilla.org/MPL/2.0/. */\n\n\n\n#include \"HTTP.hpp\"\n\n#include <sstream>\n\n\n\nnamespace sfn {\n\n\n\nstd::string HTTPMessage::GetHeaderValue( const std::string& field_name ) const {\n\n\tauto iter = m_header.find( field_name );\n\n\n\n\tif( iter != std::end( m_header ) ) {\n\n\t\treturn iter->second;\n\n\t}\n\n\n\n\treturn \"\";\n\n}\n\n\n\nvoid HTTPMessage::SetHeaderValue( std::string field, std::string value ) {\n", "file_path": "ProjectLunarFront/SFNUL/HTTP.cpp", "rank": 55, "score": 14.124772094073379 }, { "content": " * 3. Neither the name of the project nor the names of its contributors\n\n * may be used to endorse or promote products derived from this software\n\n * without specific prior written permission.\n\n *\n\n * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND\n\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\n * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE\n\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\n * SUCH DAMAGE.\n\n */\n\n\n\n#pragma once\n\n\n\n#include <string>\n\n#include <cstring>\n\n#include <fstream>\n\n \n", "file_path": "ProjectLunarFront/SHA-256.hpp", "rank": 56, "score": 13.73688279357588 }, { "content": "inline HTTPResponseWrapper::Ptr htmltext(const wstring& str, bool hasFrame = true, const vector<pair<string, string>>& replaces = {})\n\n{ return make_shared<HTTPResponseShort>(str, hasFrame, replaces); }\n\ninline HTTPResponseWrapper::Ptr htmltext(const string& str, bool hasFrame = true, const vector<pair<string, string>>& replaces = {})\n\n{ return make_shared<HTTPResponseShort>(str, hasFrame, replaces); }\n\n\n\ninline HTTPResponseWrapper::Ptr file(const wstring& filename, const string& mimeType = string())\n\n{ return make_shared<HTTPResponseFile>(filename, mimeType); }\n\ninline HTTPResponseWrapper::Ptr file(const string& filename, const string& mimeType = string())\n\n{ return make_shared<HTTPResponseFile>(utf8ToWstring(filename), mimeType); }\n\n\n\ninline HTTPResponseWrapper::Ptr filetemplate(const wstring& filename, const vector<pair<string, string>>& replaces = {}, bool hasFrame = true, const string& mimeType = \"text/html\")\n\n{ return make_shared<HTTPResponseTemplate>(filename, replaces, hasFrame, mimeType); }\n\ninline HTTPResponseWrapper::Ptr filetemplate(const string& filename, const vector<pair<string, string>>& replaces = {}, bool hasFrame = true, const string& mimeType = \"text/html\")\n\n{ return make_shared<HTTPResponseTemplate>(utf8ToWstring(filename), replaces, hasFrame, mimeType); }\n\n\n\ninline HTTPResponseWrapper::Ptr error(int code) { return make_shared<HTTPResponseError>(code); }\n\n\n\n// Code is one of 301 Moved Permanently, 302 Found, 303 See Other and 307 Temporary Redirect\n\n// std::string sequence is encoded in UTF-8\n\n// Note that when encoding an cookie, encodePercent is not used, i.e.,\n\n// one cannot use any speical symbols and Unicode characters\n\ninline HTTPResponseWrapper::Ptr redirect(const wstring& target, int code = 301, const vector<pair<string, string>>& cookies = {}) { return make_shared<HTTPResponseRedirection>(wstringToUtf8(target), code, cookies); }\n\ninline HTTPResponseWrapper::Ptr redirect(const string& target, int code = 301, const vector<pair<string, string>>& cookies = {}) { return make_shared<HTTPResponseRedirection>(target, code, cookies); }\n\n\n", "file_path": "ProjectLunarFront/HTTPResponseWrapper.hpp", "rank": 57, "score": 13.350118680476186 }, { "content": "\n\n#include \"JudgeRecord.hpp\"\n\n\n\n#include \"StringDatabase.hpp\"\n\n#include \"Problem.hpp\"\n\n\n\nJudgeRecordDatabase judgeRecordDatabase;\n\n\n\nnamespace {\n\n\tconst string stateStrings[] = {\n\n\t\t\"Waiting\"s,\n\n\t\t\"Compiling\"s,\n\n\t\t\"Running\"s,\n\n\t\t\"Accepted\"s,\n\n\t\t\"Wrong Answer\"s,\n\n\t\t\"Time Limit Exceeded\"s,\n\n\t\t\"Memory Limit Exceeded\"s,\n\n\t\t\"Runtime Error\"s,\n\n\t\t\"Compile Error\"s,\n\n\t\t\"Program Cannot Start\"s,\n", "file_path": "ProjectLunarFront/JudgeRecord.cpp", "rank": 58, "score": 12.649073240475486 }, { "content": "\t\tmlog << Log::Error << \"[Main/EVENT] Control-C Console Exit\" << dlog;\n\n\telse if (dwCtrlType == CTRL_BREAK_EVENT)\n\n\t\tmlog << Log::Error << \"[Main/EVENT] Control-Break Console Exit\" << dlog;\n\n\telse if (dwCtrlType == CTRL_CLOSE_EVENT)\n\n\t\tmlog << Log::Error << \"[Main/EVENT] Control-Close Console Exit\" << dlog;\n\n\telse if (dwCtrlType == CTRL_LOGOFF_EVENT)\n\n\t\tmlog << Log::Error << \"[Main/EVENT] System-Logoff Exit\" << dlog;\n\n\telse if (dwCtrlType == CTRL_SHUTDOWN_EVENT)\n\n\t\tmlog << Log::Error << \"[Main/EVENT] System-Shutdown Exit\" << dlog;\n\n\telse\n\n\t\treturn false;\n\n\trunning = false;\n\n\twhile (!stopped)\n\n\t\tthis_thread::sleep_for(chrono::milliseconds(50));\n\n\treturn true;\n\n}\n\n#else\n\n// Assuming a POSIX system\n\nvoid sigintHandler(int signal) {\n\n\tif (signal == SIGINT)\n", "file_path": "ProjectLunarFront/Main.cpp", "rank": 59, "score": 11.332061542190282 }, { "content": "#pragma once\n\n\n\n#include <memory>\n\n#include <mutex>\n\n#include \"Main.hpp\"\n\n\n", "file_path": "ProjectLunarFront/Lockable.hpp", "rank": 60, "score": 11.17060664014126 }, { "content": "#include \"Main.hpp\"\n\n#include \"Instance.hpp\"\n\n\n\n#include \"JudgeWorker.hpp\"\n\n#include \"JudgeRecord.hpp\"\n\n#include \"StringDatabase.hpp\"\n\n#include \"Problem.hpp\"\n\n#include \"Page.hpp\"\n\n#include \"PageStatus.hpp\"\n\n#include \"PageStatusDetail.hpp\"\n\n\n\nLog dlog;\n\nofstream logout;\n\n\n\natomic_bool running, stopped;\n\n\n\n#ifdef _WIN32\n\n//Platform-Depedent: Windows\n\nBOOL systemExitEventHandler(DWORD dwCtrlType) {\n\n\tif (dwCtrlType == CTRL_C_EVENT)\n", "file_path": "ProjectLunarFront/Main.cpp", "rank": 61, "score": 11.072090551408701 }, { "content": "\t\tmlog << Log::Error << \"[Main/EVENT] POSIX SIGINT Exit\" << dlog;\n\n\telse if (signal == SIGTERM)\n\n\t\tmlog << Log::Error << \"[Main/EVENT] POSIX SIGTERM Exit\" << dlog;\n\n\trunning = false;\n\n}\n\n#endif\n\n\n\n\n\nint main(int argc, char* argv[]) try {\n\n\t// Open a binary output stream for logs\n\n\t/*time_t curtime = time(NULL);\n\n\twchar_t buffer[64] = {};\n\n\tchar signature[] = u8\"\\ufeff\"; // BOM in UTF-8; \"signature\"\n\n\twcsftime(buffer, 63, L\"logs/%Y-%m-%d-%H.%M.%S.log\", localtime(&curtime));\n\n\tOPEN_FSTREAM_WSTR(logout, buffer, ofstream::binary);\n\n\tlogout.write(signature, sizeof(signature) - 1);*/\n\n\n\n#if (defined WIN32) || (defined _WIN32)\n\n\tlocale::global(locale(\"\", LC_CTYPE));\n\n\twcout.imbue(locale(\"\", LC_CTYPE));\n", "file_path": "ProjectLunarFront/Main.cpp", "rank": 62, "score": 10.769523669463783 }, { "content": "\tauto& point = record->points[seqid];\n\n\n\n\tstring target = readFileBinary(targetOut.generic_wstring());\n\n\tstring stds = readFileBinary(stdOut.generic_wstring());\n\n#define JUDGE(result, message) do { point.score = 0; point.state = JudgeRecord::result; point.judgeMessage = message; return; } while (false)\n\n\n\n\tif (target.size() > stds.size())\n\n\t\tJUDGE(WrongAnswer, \"Longer than standard output\");\n\n\telse if (target.size() < stds.size())\n\n\t\tJUDGE(WrongAnswer, \"Shorter than standard output\");\n\n\telse {\n\n\t\tfor (int i = 0; i < target.size(); i++)\n\n\t\t\tif (target[i] != stds[i])\n\n\t\t\t\tJUDGE(WrongAnswer, StringParser::toStringF(\"Differ on byte #%d: std: %d, you: %d\", i, (int)stds[i], (int)target[i]));\n\n\t}\n\n\n\n\tpoint.score = point.maxscore;\n\n\tpoint.state = JudgeRecord::Accepted;\n\n\n\n#undef JUDGE\n", "file_path": "ProjectLunarFront/JudgeWorker.cpp", "rank": 63, "score": 10.545029234365966 }, { "content": "/* This Source Code Form is subject to the terms of the Mozilla Public\n\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n\n * file, You can obtain one at http://mozilla.org/MPL/2.0/. */\n\n\n\n#pragma once\n\n\n\n#define SFNUL_MAJOR_VERSION 0\n\n#define SFNUL_MINOR_VERSION 3\n\n\n\n#if defined( SFNUL_SYSTEM_WINDOWS ) && !defined( SFNUL_STATIC )\n\n\t#if defined( SFNUL_EXPORTS )\n\n\t\t#define SFNUL_API __declspec( dllexport )\n\n\t#else\n\n\t\t#define SFNUL_API __declspec( dllimport )\n\n\t#endif\n\n#else\n\n\t#define SFNUL_API\n\n#endif\n\n\n\n#if defined( _MSC_VER )\n\n\t#pragma warning(disable : 4251) // Suppress a warning which is meaningless for us\n\n\t#pragma warning(disable : 4503) // Suppress warnings about truncated names. Enable again if linker errors occur.\n\n\n\n\t#if ( _MSC_VER < 1900 )\n\n\t\t#define SFNUL_BROKEN_CXX11\n\n\t#endif\n\n#endif\n", "file_path": "ProjectLunarFront/SFNUL/Config.hpp", "rank": 64, "score": 10.43585701125468 }, { "content": "\t\t\tbreak;\n\n\t\t}\n\n\t\tif (probp.memoryLimitKb != -1) {\n\n\t\t\tGetProcessMemoryInfo(pi.hProcess, (PROCESS_MEMORY_COUNTERS*)&info, sizeof(info));\n\n\t\t\tif (max(info.PrivateUsage, info.PeakWorkingSetSize) > probp.memoryLimitKb * 1024) {\n\n\t\t\t\tTerminateProcess(pi.hProcess, 0);\n\n\t\t\t\tCloseHandle(si.hStdError);\n\n\t\t\t\tCloseHandle(pi.hProcess);\n\n\t\t\t\tCloseHandle(pi.hThread);\n\n\t\t\t\tpoint.score = 0;\n\n\t\t\t\tpoint.state = JudgeRecord::MemoryLimitExceeded;\n\n\t\t\t\tpoint.memUsedKb = point.timeUsedMs = -1;\n\n\t\t\t\treturn;\n\n\t\t\t}\n\n\t\t}\n\n\t\tsleep(milliseconds(10));\n\n\t}\n\n\n\n\tif (!flag) {\n\n\t\tTerminateProcess(pi.hProcess, 0);\n", "file_path": "ProjectLunarFront/JudgeWorker.cpp", "rank": 65, "score": 10.4327355342607 }, { "content": "\tZeroMemory(&sa, sizeof(sa));\n\n\tsa.bInheritHandle = TRUE;\n\n\n\n\tsi.hStdError = CreateFile((const WCHAR*)((tempDir + L\"_tmperr\").c_str()), GENERIC_WRITE,\n\n\t\t\t\t\t\t\t FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &sa,\n\n\t\t\t\t\t\t\t CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);\n\n\n\n\tif (!CreateProcess(NULL, (LPWSTR)exe.native().c_str(), NULL, &sa,\n\n\t\tTRUE, HIGH_PRIORITY_CLASS | CREATE_NO_WINDOW, 0,\n\n\t\t(const WCHAR*)(workingDir.native().c_str()), &si, &pi)) {\n\n\t\tCloseHandle(si.hStdError);\n\n\t\tpoint.score = 0;\n\n\t\trecord->points[seqid].state = JudgeRecord::FailedToRun;\n\n\t\treturn;\n\n\t}\n\n\n\n\tPROCESS_MEMORY_COUNTERS_EX info;\n\n\tZeroMemory(&info, sizeof(info));\n\n\tinfo.cb = sizeof(info);\n\n\tif (probp.memoryLimitKb != -1) {\n", "file_path": "ProjectLunarFront/JudgeWorker.cpp", "rank": 66, "score": 10.285826553502293 }, { "content": "\t\tpoint.memUsedKb = point.timeUsedMs = -1;\n\n\t\treturn;\n\n\t}\n\n\n\n\tFILETIME creationTime, exitTime, kernelTime, userTime;\n\n\tGetProcessTimes(pi.hProcess, &creationTime, &exitTime, &kernelTime, &userTime);\n\n\n\n\tSYSTEMTIME realTime;\n\n\tFileTimeToSystemTime(&userTime, &realTime);\n\n\n\n\tpoint.timeUsedMs = realTime.wMilliseconds\n\n\t\t+ realTime.wSecond * 1000\n\n\t\t+ realTime.wMinute * 60 * 1000\n\n\t\t+ realTime.wHour * 60 * 60 * 1000;\n\n\n\n\tGetProcessMemoryInfo(pi.hProcess, (PROCESS_MEMORY_COUNTERS*)&info, sizeof(info));\n\n\tpoint.memUsedKb = info.PeakWorkingSetSize / 1024;\n\n\n\n\tCloseHandle(si.hStdError);\n\n\tCloseHandle(pi.hProcess);\n", "file_path": "ProjectLunarFront/JudgeWorker.cpp", "rank": 67, "score": 10.26560773562698 }, { "content": "#pragma once\n\n\n\n#include \"Main.hpp\"\n\n\n\n#include \"JudgeRecord.hpp\"\n\n#include \"Problem.hpp\"\n\n#include \"Page.hpp\"\n\n#include \"StringDatabase.hpp\"\n\n\n", "file_path": "ProjectLunarFront/PageStatusDetail.hpp", "rank": 68, "score": 10.009002131756311 }, { "content": "\t\tGetProcessMemoryInfo(pi.hProcess, (PROCESS_MEMORY_COUNTERS*)&info, sizeof(info));\n\n\t\tif (max(info.PrivateUsage, info.PeakWorkingSetSize) > probp.memoryLimitKb * 1024) {\n\n\t\t\tTerminateProcess(pi.hProcess, 0);\n\n\t\t\tCloseHandle(si.hStdError);\n\n\t\t\tCloseHandle(pi.hProcess);\n\n\t\t\tCloseHandle(pi.hThread);\n\n\t\t\tpoint.score = 0;\n\n\t\t\tpoint.state = JudgeRecord::MemoryLimitExceeded;\n\n\t\t\tpoint.memUsedKb = point.timeUsedMs = -1;\n\n\t\t\treturn;\n\n\t\t}\n\n\t}\n\n\n\n\tbool flag = false;\n\n\tClock timer;\n\n\ttimer.restart();\n\n\n\n\twhile (timer.getElapsedTime().asMilliseconds() <= probp.timeLimitMs) {\n\n\t\tif (WaitForSingleObject(pi.hProcess, 0) == WAIT_OBJECT_0) {\n\n\t\t\tflag = true;\n", "file_path": "ProjectLunarFront/JudgeWorker.cpp", "rank": 69, "score": 9.815371045246424 }, { "content": "\tpoint.score = point.maxscore;\n\n\tpoint.state = JudgeRecord::Accepted;\n\n\tpoint.judgeMessage = \"Output ok\";\n\n\tfclose(contestantOutputFile);\n\n\tfclose(standardOutputFile);\n\n}\n\n\n\n\n\nvoid JudgeWorker::judgeOneSet(const fs::path& exe, const fs::path& workingDir, const fs::path& targetIn, const fs::path& targetOut, int id, shared_ptr<JudgeRecord> record, const Problem& prob) {\n\n\tASSERT(fs::exists(exe) && fs::is_regular_file(exe));\n\n\n\n\t// prepare variables\n\n\twstring tempDir = exe.parent_path().native();\n\n\tfs::path stdIn = StringParser::toStringF(prob.inDataPathFormat.c_str(), id), stdOut = StringParser::toStringF(prob.outDataPathFormat.c_str(), id);\n\n\tint seqid = id - prob.dataIdFirst;\n\n\n\n\t// copy the input file\n\n\tfs::remove(targetIn);\n\n\tfs::remove(targetOut);\n\n\tfs::copy(stdIn, targetIn);\n", "file_path": "ProjectLunarFront/JudgeWorker.cpp", "rank": 70, "score": 9.79335015836806 }, { "content": "\tvoid SetStatus( std::string status );\n\n\n\n\t/** Convert this response to its string representation according to HTTP specifications.\n\n\t * @return String representation of this response.\n\n\t */\n\n\tstd::string ToString() const override;\n\n\n\n\t/** Check if this HTTP response has arrived and been parsed completely.\n\n\t * @return true if this HTTP response has arrived and been parsed completely.\n\n\t */\n\n\tbool IsComplete() const;\n\n\n\n\t/** Get the header fields present in this HTTP response.\n\n\t * @return Header fields present in this HTTP response.\n\n\t */\n\n\tstd::vector<std::string> GetHeaderFields() const;\n\n\n\nprotected:\n\n\tstd::string m_http_version;\n\n\tstd::string m_status;\n", "file_path": "ProjectLunarFront/SFNUL/HTTP.hpp", "rank": 71, "score": 9.732631177787997 }, { "content": "#else\n\n\tsetlocale(LC_CTYPE, \"zh_CN.utf8\");\n\n#endif\n\n\tdlog.addOutputStream(wcout);\n\n\t/*dlog.addOutputHandler([&](const wstring& str) {\n\n\t\tstring u8str = wstringToUtf8(str) + \"\\r\\n\";\n\n\t\tlogout.write(u8str.data(), u8str.size());\n\n\t\tlogout.flush();\n\n\t});*/\n\n\n\n\trunning = true;\n\n\tstopped = false;\n\n#ifdef _WIN32\n\n\tSetConsoleCtrlHandler((PHANDLER_ROUTINE)systemExitEventHandler, true);\n\n#else\n\n\tsignal(SIGINT, sigintHandler);\n\n\tsignal(SIGTERM, sigintHandler);\n\n#endif\n\n\n\n\tmlog << completeServerNameEx << dlog;\n", "file_path": "ProjectLunarFront/Main.cpp", "rank": 72, "score": 9.698579723409422 }, { "content": "#pragma once\n\n\n\n#include \"Main.hpp\"\n\n\n\n\n\nnamespace {\n\n\n\n\tstring readNextWord(const string& str, size_t& offset) {\n\n\t\tstring res;\n\n\t\twhile (offset < str.length() && (isspace(str[offset]) || iscntrl(str[offset])))\n\n\t\t\toffset++;\n\n\t\twhile (offset < str.length() && !(isspace(str[offset]) || iscntrl(str[offset])))\n\n\t\t\tres.push_back(str[offset++]);\n\n\t\treturn res;\n\n\t}\n\n\n\n\tstring readFromFirstCharToEndline(const string& str, size_t& offset) {\n\n\t\tstring res;\n\n\t\twhile (offset < str.length() && isspace(str[offset]) || iscntrl(str[offset]))\n\n\t\t\toffset++;\n", "file_path": "ProjectLunarFront/HTTPParser.hpp", "rank": 73, "score": 9.662838493813592 }, { "content": "\n\n#include \"HTTPResponseWrapper.hpp\"\n\n#include \"StringParser.hpp\"\n\n#include \"HTTPParser.hpp\"\n\n\n\nHTTPStringData httpdata;\n\n\n\nnamespace {\n\n\tstring frameFileContents;\n\n\tstring frameBodyFlag;\n\n\n\n\tstring readNextWord(const string& str, size_t& offset);\n\n}\n\n\n\n\n\nHTTPStringData::HTTPStringData() {\n\n\t//TODO All responses\n\n\tstrings.insert(make_pair(200, \"OK\"));\n\n\n\n\tstrings.insert(make_pair(301, \"Moved Permanently\"));\n", "file_path": "ProjectLunarFront/HTTPResponseWrapper.cpp", "rank": 74, "score": 9.534530659985247 }, { "content": "\t\tCloseHandle(si.hStdError);\n\n\t\tCloseHandle(pi.hProcess);\n\n\t\tCloseHandle(pi.hThread);\n\n\t\tpoint.score = 0;\n\n\t\tpoint.state = JudgeRecord::TimeLimitExceeded;\n\n\t\tpoint.timeUsedMs = -1;\n\n\t\treturn;\n\n\t}\n\n\n\n\tunsigned long exitCode;\n\n\tGetExitCodeProcess(pi.hProcess, &exitCode);\n\n\tif (exitCode != 0) {\n\n\t\tCloseHandle(si.hStdError);\n\n\t\tCloseHandle(pi.hProcess);\n\n\t\tCloseHandle(pi.hThread);\n\n\t\tpoint.score = 0;\n\n\t\tpoint.state = JudgeRecord::RuntimeError;\n\n\t\tfs::path file(tempDir + L\"_tmperr\");\n\n\t\tif (fs::exists(file))\n\n\t\t\tpoint.judgeMessage = readFileText(file.generic_wstring());\n", "file_path": "ProjectLunarFront/JudgeWorker.cpp", "rank": 75, "score": 9.321076880814122 }, { "content": "#endif\n\n\n\n// ifstream::open(const wstring& path, flags) is a Windows extension, not a standard\n\n#if (defined _WIN32) || (defined WIN32)\n\n#define OPEN_FSTREAM_WSTR(stream, wstrpath, flags) stream.open(wstrpath, flags);\n\n#else\n\n#define OPEN_FSTREAM_WSTR(stream, wstrpath, flags) stream.open(wstringToUtf8(wstrpath), flags);\n\n#endif\n\n\n\n#define fs filesystem\n\n\n\n#include \"Version.hpp\"\n\n\n\nstring wstringToUtf8(const wstring& source);\n\nwstring utf8ToWstring(const string& source);\n\nwstring ansiToWstring(const string& source);\n\n\n\nstring decodePercentEncoding(const string& source);\n\nstring encodePercent(const string& source, bool encodeSlash = false);\n\nvoid decodeFormUrlEncoded(string body, map<string, string>& result);\n", "file_path": "ProjectLunarFront/Main.hpp", "rank": 76, "score": 9.320319461347975 }, { "content": "\t\t\tpostRoutes.emplace_back(uriPrefix, hostname, handler);\n\n\t}\n\n\n\n\n\nprivate:\n\n\n\n\tstruct route {\n\n\t\tregex uri, hostname;\n\n\t};\n\n\n\n\tfriend class HTTPHandler;\n\n\n\n\tvoid _HTTPListener(shared_ptr<TcpListener> listener);\n\n\tvoid _maintainer();\n\n\n\n\tvoid _connectionHandler(shared_ptr<TcpSocket> socket, shared_ptr<atomic_bool> connected);\n\n\n\n\t//TODO Use a better container than std::list and std::tuple\n\n\tlist<tuple<string, string, RouteHandlerFunction>> getRoutes, postRoutes;\n\n\tHTTPResponseWrapper::Ptr _dispatchRequest(HTTPRequest& request);\n", "file_path": "ProjectLunarFront/Instance.hpp", "rank": 77, "score": 9.292429853613564 }, { "content": "string encodeCookieSequence(const vector<pair<string, string>>& cookies);\n\nmap<string, string> decodeCookieSequence(string body);\n\n\n\nvoid decodeCookieAndUriParam(const HTTPRequest& request, map<string, string>& cookies, map<string, string>& uriParams);\n\n\n\nstring escapeTextHTML(const string& source);\n\n\n\nstring readFileText(const wstring& filename);\n\nstring readFileBinary(const wstring& filename);\n\nconst string& readFileBinaryCached(const wstring& filename);\n\n\n\nbool writeFileText(const wstring& filename, const string& contents);\n\nbool writeFileBinary(const wstring& filename, const string& contents);\n\n\n\nstring toUppercase(const string& str);\n\n\n\nstring generateCookie(int length = 24);\n\n\n", "file_path": "ProjectLunarFront/Main.hpp", "rank": 78, "score": 9.244314732873201 }, { "content": "bool HTTPResponse::IsComplete() const {\n\n\treturn IsHeaderComplete() && IsBodyComplete();\n\n}\n\n\n\nstd::vector<std::string> HTTPResponse::GetHeaderFields() const {\n\n\tstd::vector<std::string> fields;\n\n\n\n\tfor( const auto& f : m_header ) {\n\n\t\tfields.emplace_back( f.first );\n\n\t}\n\n\n\n\treturn fields;\n\n}\n\n\n\nbool operator==( const HTTPResponse& left, const HTTPResponse& right ) {\n\n\treturn ( left.GetHTTPVersion() == right.GetHTTPVersion() ) &&\n\n\t ( left.GetStatus() == right.GetStatus() ) &&\n\n\t ( static_cast<HTTPMessage>( left ) == static_cast<HTTPMessage>( right ) );\n\n}\n\n\n\n}\n", "file_path": "ProjectLunarFront/SFNUL/HTTP.cpp", "rank": 79, "score": 9.066004460945617 }, { "content": "\treturn buffer;\n\n}\n\n\n\n#else\n\n\n\nstring wstringToUtf8(const wstring& source) {\n\n\t// In C++11+, std::string stores a null-terminated string. Funtcion string::c_str() returns the beginning of the array.\n\n\tmbstate_t state = mbstate_t();\n\n\tconst wchar_t* src = source.c_str();\n\n\tsize_t size = wcsrtombs(nullptr, &src, 0, &state);\n\n\tstring buffer(size, '\\0');\n\n\twcsrtombs(buffer.data(), &src, buffer.size() + 1, &state);\n\n\treturn buffer;\n\n}\n\n\n\nwstring utf8ToWstring(const string& source) {\n\n\t// HACK Assuming ANSI == UTF-8 on non-Windows platforms\n\n\tmbstate_t state = mbstate_t();\n\n\tconst char* src = source.c_str();\n\n\tsize_t size = mbsrtowcs(nullptr, &src, 0, &state);\n", "file_path": "ProjectLunarFront/MainF.cpp", "rank": 80, "score": 8.878457179324258 }, { "content": " * 3. Neither the name of the project nor the names of its contributors\n\n * may be used to endorse or promote products derived from this software\n\n * without specific prior written permission.\n\n *\n\n * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND\n\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\n * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE\n\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\n * SUCH DAMAGE.\n\n */\n\n\n\n#include \"SHA-256.hpp\"\n\n\n\n#define SHA2_SHFR(x, n) (x >> n)\n", "file_path": "ProjectLunarFront/SHA-256.cpp", "rank": 81, "score": 8.283449897724779 }, { "content": "\n\n#include \"JudgeWorker.hpp\"\n\n\n\n#include \"JudgeRecord.hpp\"\n\n#include \"Problem.hpp\"\n\n#include \"StringDatabase.hpp\"\n\n\n\n#ifdef OS_WINDOWS\n\n#include <Psapi.h>\n\n#endif\n\n\n\nJudgeWorker judgeWorker;\n\n\n\n\n\nfs::path JudgeWorker::compile(shared_ptr<JudgeRecord> record, const wstring& targetPathNoExt) {\n\n\tmlog << \" Compiling...\" << dlog;\n\n\n\n\trecord->state = JudgeRecord::Compiling;\n\n\n\n\t// set up variables\n", "file_path": "ProjectLunarFront/JudgeWorker.cpp", "rank": 82, "score": 8.16814220874452 }, { "content": "\n\n\treturn 0;\n\n} catch (exception& e) {\n\n\tmlog << Log::Error << \"The main closure failed with an uncaught exception: \" << e.what() << dlog;\n\n\tmlog << Log::Error << \"Exception typename: \" << typeid(e).name()\n\n#if (defined WIN32) || (defined _WIN32)\n\n\t\t<< \" (\" << typeid(e).raw_name() << \")\"\n\n#endif\n\n\t\t<< dlog;\n\n\tmlog << Log::Error << \"The program will now fail.\" << dlog;\n\n\treturn 1;\n\n} catch (...) {\n\n\tmlog << Log::Error << \"The main closure failed with an unknown object thrown.\" << dlog;\n\n\tmlog << Log::Error << \"The program will now fail.\" << dlog;\n\n\treturn 1;\n\n}\n\n\n", "file_path": "ProjectLunarFront/Main.cpp", "rank": 83, "score": 8.056506866789551 }, { "content": "\tstatic const string& getStatusString(State state);\n\n\n\n\tstruct DataPoint {\n\n\t\tstring judgeMessage;\n\n\t\tState state;\n\n\t\tint maxscore, score;\n\n\t\tint memUsedKb, timeUsedMs;\n\n\t};\n\n\n\n\tint id;\n\n\tint probId, userId;\n\n\tUuid codeStrDBId;\n\n\n\n\t// unix time\n\n\tUint64 submitUnixTime;\n\n\n\n\tState state;\n\n\tstring compileMessage;\n\n\tvector<DataPoint> points;\n\n\n\n\t// sum of all points[].maxscore and points[].score, respectively\n\n\tint maxscore, score;\n\n\n\n\tint maxTimeMs, maxMemoryKb;\n\n};\n\n\n", "file_path": "ProjectLunarFront/JudgeRecord.hpp", "rank": 84, "score": 7.930133121329798 }, { "content": "const std::string& HTTPResponse::GetHTTPVersion() const {\n\n\treturn m_http_version;\n\n}\n\n\n\nvoid HTTPResponse::SetHTTPVersion( std::string version ) {\n\n\tm_http_version = std::move( version );\n\n}\n\n\n\nconst std::string& HTTPResponse::GetStatus() const {\n\n\treturn m_status;\n\n}\n\n\n\nvoid HTTPResponse::SetStatus( std::string status ) {\n\n\tm_status = std::move( status );\n\n}\n\n\n\nstd::string HTTPResponse::ToString() const {\n\n\treturn m_http_version + \" \" + m_status + \"\\r\\n\" + HTTPMessage::ToString();\n\n}\n\n\n", "file_path": "ProjectLunarFront/SFNUL/HTTP.cpp", "rank": 85, "score": 7.749228027706364 }, { "content": "\tm_header[field] = std::move( value );\n\n}\n\n\n\nconst std::string& HTTPMessage::GetBody() const {\n\n\treturn m_body;\n\n}\n\n\n\nvoid HTTPMessage::SetBody( std::string body ) {\n\n\tm_body = std::move( body );\n\n}\n\n\n\nvoid HTTPMessage::ReserveBody( std::size_t size ) {\n\n\tm_body.reserve( size );\n\n}\n\n\n\nstd::string HTTPMessage::ToString() const {\n\n\tstd::string str;\n\n\n\n\tfor( auto h : m_header ) {\n\n\t\tstr += h.first + \": \" + h.second + \"\\r\\n\";\n", "file_path": "ProjectLunarFront/SFNUL/HTTP.cpp", "rank": 86, "score": 7.637599079924745 }, { "content": "\t\t\"Unknown Internal Error\"s\n\n\t};\n\n}\n\n\n\n\n\nconst string& JudgeRecord::getStatusString(State state) {\n\n\treturn stateStrings[(int)state];\n\n}\n\n\n\n\n\nvoid JudgeRecordDatabase::loadFromFile(const wstring& filename) {\n\n\tlock();\n\n\tmlog << \"[JudgeRecordDatabase] Loading judge records from \" << filename << dlog;\n\n\n\n\tthrow NotImplementedException(\"JudgeRecordDatabase::loadFromFile\");\n\n\n\n\tmlog << \"[JudgeRecordDatabase] File loaded.\" << dlog;\n\n\tunlock();\n\n}\n\n\n", "file_path": "ProjectLunarFront/JudgeRecord.cpp", "rank": 87, "score": 7.599356907246128 }, { "content": "\n\n\t/** Set the URI of this HTTP request.\n\n\t * @param uri The URI of this HTTP request.\n\n\t */\n\n\tvoid SetURI( std::string uri );\n\n\n\n\t/** Convert this request to its string representation according to HTTP specifications.\n\n\t * @return String representation of this request.\n\n\t */\n\n\tstd::string ToString() const override;\n\n\n\nprotected:\n\n\tstd::string m_method;\n\n\tstd::string m_uri;\n\n};\n\n\n\n/** A HTTP response containing a version, status and remaining HTTP message.\n\n */\n", "file_path": "ProjectLunarFront/SFNUL/HTTP.hpp", "rank": 88, "score": 7.539323161348939 }, { "content": "#pragma once\n\n\n\n#include \"Main.hpp\"\n\n#include \"Lockable.hpp\"\n\n\n\n\n", "file_path": "ProjectLunarFront/JudgeRecord.hpp", "rank": 89, "score": 7.486832235291407 }, { "content": "#pragma once\n\n\n\n#include \"Main.hpp\"\n\n#include \"Instance.hpp\"\n\n\n\n\n", "file_path": "ProjectLunarFront/Page.hpp", "rank": 90, "score": 7.486832235291407 }, { "content": "#pragma once\n\n\n\n#include \"Page.hpp\"\n\n\n\n#include \"JudgeRecord.hpp\"\n\n#include \"Problem.hpp\"\n\n\n", "file_path": "ProjectLunarFront/PageStatus.hpp", "rank": 91, "score": 7.48283487679893 }, { "content": "\n\n#include \"Instance.hpp\"\n\n#include \"HTTPParser.hpp\"\n\n\n\n\n\nnamespace {\n\n\n", "file_path": "ProjectLunarFront/Instance.cpp", "rank": 92, "score": 7.4573748586451245 }, { "content": "#pragma once\n\n\n\n#include \"Main.hpp\"\n\n#include \"Lockable.hpp\"\n\n\n\n#include \"HTTPResponseWrapper.hpp\"\n\n\n\n\n", "file_path": "ProjectLunarFront/Instance.hpp", "rank": 93, "score": 7.422552722386924 }, { "content": "\t\t { L\"%EXE\", L'\"' + srcExeFile.native() + L'\"' } }) + L\" 1> \\\"\" + compileOut.native() + L\"\\\" 2>&1\";\n\n\tretval = _wsystem(command.c_str());\n\n#else\n\n\tstring command = StringParser::replaceSubString(\n\n\t\tconfig.getCppCompiler(),\n\n\t\t\t{ { \"%CODE\", srcCodeFile.generic_u8string() },\n\n\t\t\t{ \"%EXE\", srcExeFile.generic_u8string() } }) + \" &> \\\"\" + compileOut.native() + '\"';\n\n\tretval = system(command.c_str());\n\n#endif\n\n\n\n\tif (retval != 0) {\n\n\t\tmlog << \" Compile Error!\" << dlog;\n\n\t\trecord->state = JudgeRecord::CompileError;\n\n\t}\n\n\trecord->compileMessage = readFileText(compileOut.generic_wstring());\n\n\tmlog << \" Compiler message: \" << record->compileMessage << dlog;\n\n\n\n\treturn srcExeFile;\n\n}\n\n\n", "file_path": "ProjectLunarFront/JudgeWorker.cpp", "rank": 94, "score": 7.293382303612713 }, { "content": "\t * @return The body of this message.\n\n\t */\n\n\tconst std::string& GetBody() const;\n\n\n\n\t/** Set the body of this message.\n\n\t * @param body The content to set the body to.\n\n\t */\n\n\tvoid SetBody( std::string body );\n\n\n\n\t/** Reserve memory for a body of a specific size.\n\n\t * size Memory to reserve in bytes.\n\n\t */\n\n\tvoid ReserveBody( std::size_t size );\n\n\n\n\t/** Convert this message to its string representation according to HTTP specifications.\n\n\t * @return String representation of this message.\n\n\t */\n\n\tvirtual std::string ToString() const;\n\n\n\n\t/** Check whether the header of this HTTP response is complete.\n", "file_path": "ProjectLunarFront/SFNUL/HTTP.hpp", "rank": 95, "score": 7.196859919526787 }, { "content": "#pragma once\n\n\n\n#include \"Main.hpp\"\n\n\n", "file_path": "ProjectLunarFront/User.hpp", "rank": 96, "score": 7.157442766081331 }, { "content": "#pragma once\n\n\n\n#include \"Main.hpp\"\n\n\n\n\n", "file_path": "ProjectLunarFront/HTTPResponseWrapper.hpp", "rank": 97, "score": 7.157442766081331 }, { "content": "#pragma once\n\n\n\n#include \"Main.hpp\"\n\n\n", "file_path": "ProjectLunarFront/JudgeWorker.hpp", "rank": 98, "score": 7.157442766081331 }, { "content": "#pragma once\n\n\n\n#include \"Main.hpp\"\n\n\n", "file_path": "ProjectLunarFront/Problem.hpp", "rank": 99, "score": 7.157442766081331 } ]
C++
src/HistTool.cpp
xzf89718/bbtautau-hists
3f20c9d9cf82149df12aef155c6dd148a367aece
#include "HistTool.h" #include <exception> #include <algorithm> #include <vector> #include <iostream> #include <fstream> #include <sstream> #include <set> #include <map> #include <iomanip> using namespace std; # define FOUR_COLUMN_TABLE(A, B, C, D) \ std::left << setw(36) << A \ << std::left << setw(15) << B \ << std::left << setw(30) << C \ << std::left << setw(15) << D << endl # define FIVE_COLUMN_TABLE(A, B, C, D, E) \ std::left << setw(40) << A \ << std::left << setw(15) << B \ << std::left << setw(15) << C \ << std::left << setw(15) << D \ << std::left << setw(15) << E << endl bool HistTool::check(const Config* c) const { vector<ProcessInfo*>* ps = c->processes->content(); clog << "INFO: removing nullptrs\n"; ps->erase(remove_if(ps->begin(), ps->end(), [](const ProcessInfo* p) { return !p->histogram; }), ps->end()); if (ps->size() < 1) { cerr << "FAIL: empty input\n"; return false; } return true; } void HistTool::manipulate(Config* c) { c->setManipulated(true); vector<ProcessInfo*>* ps_in_c = c->processes->content(); clog << "INFO: merging\n"; map<eProcess, vector<ProcessInfo*>> procs; for_each(ps_in_c->begin(), ps_in_c->end(), [&procs](ProcessInfo* p) { procs[p->process].push_back(p); }); for_each(procs.begin(), procs.end(), [&ps_in_c, &c](pair<const eProcess, vector<ProcessInfo*>>& pair) { ProcessInfo* front = pair.second.front(); ProcessInfo* merged = new ProcessInfo( front->process_name, front->process_name, front->type, front->process, front->process_name, front->color); merged->histogram = (TH1*)front->histogram->Clone(); for_each(pair.second.begin() + 1, pair.second.end(), [&merged](const ProcessInfo* p) { merged->histogram->Add(p->histogram); }); if (!(front->systematic_histograms.empty())) { for (auto & pp : front->systematic_histograms) { std::cout << pp.first << std::endl; merged->systematic_histograms[pp.first] = (TH1*)front->systematic_histograms[pp.first]->Clone(); for_each(pair.second.begin() + 1, pair.second.end(), [&merged, &pp](const ProcessInfo* p) { std::cout << p->name << std::endl; if (!p->systematic_histograms.empty()) { if (p->systematic_histograms.find(pp.first) != p->systematic_histograms.end()) merged->systematic_histograms[pp.first]->Add(p->systematic_histograms.at(pp.first)); else merged->systematic_histograms[pp.first]->Add(p->histogram); } }); } } merged->isMerged = true; merged->norm_factor = front->norm_factor; merged->current_region = front->current_region; merged->current_variable = front->current_variable; c->current_region = merged->current_region; c->current_variable = merged->current_variable; ps_in_c->emplace_back(merged); }); ps_in_c->erase(remove_if(ps_in_c->begin(), ps_in_c->end(), [](const ProcessInfo* p) { return !p->isMerged; }), ps_in_c->end()); sort(ps_in_c->begin(), ps_in_c->end(), [](const ProcessInfo* p1, const ProcessInfo* p2) { return p1->type < p2->type; }); } void HistTool::rebin(const Config* c, eRebinOption opt, const std::string& info, bool transform) const { Tools::println("INFO: from HistTool::rebin(): %", info); switch (opt) { case eRebinOption::Self: rebin(c); break; case eRebinOption::N_Rebin: HistToolHelper::rebinByNRebin(c); break; case eRebinOption::Array: HistToolHelper::rebinByArray(c, transform); break; default: break; } } void HistTool::makeYield(const Config* c, const std::string& tag) const { ostringstream oss; oss << output_path << "/" << c->current_region->name << "_" << tag << "_" << c->current_variable->name << ".txt"; ofstream fout(oss.str()); vector<ProcessInfo*>* ps = c->processes->content(); bool hasBkg = false; int entriesBkg = 0; double sumBkg = 0.0; double errBkg = 0.0; fout << FIVE_COLUMN_TABLE("Process", "Entries", "Yield", "Error", "Rel.Err."); for (ProcessInfo* p : *ps) { double error; int from = 0; int to = p->histogram->GetNbinsX() + 1; int nentries = p->histogram->GetEntries(); double integral = p->histogram->IntegralAndError(from, to, error, ""); double eOverI = integral > (double)0. ? error / integral : 0.; fout << FIVE_COLUMN_TABLE(p->name, nentries, integral * p->norm_factor, error * p->norm_factor, eOverI); for (auto& pp : p->systematic_histograms) { auto systEntries = pp.second->GetEntries(); auto systInt = pp.second->Integral(); fout << " |- " << FOUR_COLUMN_TABLE(pp.first, systEntries, systInt, systInt / integral - 1.f); } if (p->type == eProcessType::BKG) { hasBkg = true; entriesBkg += nentries; sumBkg += integral * p->norm_factor; errBkg += error * error * p->norm_factor * p->norm_factor; } } if (hasBkg) { errBkg = sqrt(errBkg); fout << FIVE_COLUMN_TABLE("Total Bkg", entriesBkg, sumBkg, errBkg, errBkg / sumBkg); } clog << "INFO: Yields saved in " << oss.str() << '\n'; } bool HistToolHelper::check(const Config* c) { vector<ProcessInfo*>* ps = c->processes->content(); clog << "INFO: removing nullptrs\n"; ps->erase(remove_if(ps->begin(), ps->end(), [](const ProcessInfo* p) { return !p->histogram; }), ps->end()); if (ps->size() < 1) { cerr << "FAIL: empty input\n"; return false; } return true; } void HistToolHelper::rebinByNRebin(const Config* c) { vector<ProcessInfo*>* ps = c->processes->content(); for_each(ps->begin(), ps->end(), [&c](ProcessInfo* p) { p->histogram->Rebin(c->current_variable->n_rebin); for (auto& pp : p->systematic_histograms) { pp.second->Rebin(c->current_variable->n_rebin); } }); } void HistToolHelper::rebinByArray(const Config* c, bool transform) { vector<ProcessInfo*>* ps = c->processes->content(); if (c->current_variable->binning) { for_each(ps->begin(), ps->end(), [&c, &transform](ProcessInfo* p) { std::string name = p->histogram->GetName(); TH1* rebinned = p->histogram->Rebin(c->current_variable->n_bins, (name + "rebinned").c_str(), c->current_variable->binning); TH1* transformed = new TH1D((name + "transformed").c_str(), (name + "transformed").c_str(), rebinned->GetNbinsX(), 0., 1.); Utils::properties_copy(transformed, rebinned); for (int i = 1; i <= rebinned->GetNbinsX(); ++i) { transformed->SetBinContent(i, rebinned->GetBinContent(i)); transformed->SetBinError(i, rebinned->GetBinError(i)); } if (transform) { p->histogram = (TH1*)transformed->Clone(); } else { p->histogram = (TH1*)rebinned->Clone(); } for (auto& pp : p->systematic_histograms) { name = pp.second->GetName(); TH1* rebinned_pp = pp.second->Rebin(c->current_variable->n_bins, (name + "rebinned").c_str(), c->current_variable->binning); TH1* transformed_pp = new TH1D((name + "transformed").c_str(), (name + "transformed").c_str(), rebinned->GetNbinsX(), 0., 1.); Utils::properties_copy(transformed_pp, rebinned_pp); pp.second = (TH1*)rebinned_pp->Clone(); for (int i = 1; i <= rebinned_pp->GetNbinsX(); ++i) { transformed_pp->SetBinContent(i, rebinned_pp->GetBinContent(i)); transformed_pp->SetBinError(i, rebinned_pp->GetBinError(i)); } if (transform) { pp.second = (TH1*)transformed_pp->Clone(); } else { pp.second = (TH1*)rebinned_pp->Clone(); } delete rebinned_pp; delete transformed_pp; } delete rebinned; delete transformed; }); } else { clog << "WARN: Binning not given, will rebin based on rebinByNRebin(c) instead\n"; HistToolHelper::rebinByNRebin(c); } }
#include "HistTool.h" #include <exception> #include <algorithm> #include <vector> #include <iostream> #include <fstream> #include <sstream> #include <set> #include <map> #include <iomanip> using namespace std; # define FOUR_COLUMN_TABLE(A, B, C, D) \ std::left << setw(36) << A \ << std::left << setw(15) << B \ << std::left << setw(30) << C \ << std::left << setw(15) << D << endl # define FIVE_COLUMN_TABLE(A, B, C, D, E) \ std::left << setw(40) << A \ << std::left << setw(15) << B \ << std::left << setw(15) << C \ << std::left << setw(15) << D \ << std::left << setw(15) << E << endl bool HistTool::check(const Config* c) const { vector<ProcessInfo*>* ps = c->processes->content(); clog << "INFO: removing nullptrs\n"; ps->erase(remove_if(ps->begin(), ps->end(), [](const ProcessInfo* p) { return !p->histogram; }), ps->end()); if (ps->size()
oid HistToolHelper::rebinByNRebin(const Config* c) { vector<ProcessInfo*>* ps = c->processes->content(); for_each(ps->begin(), ps->end(), [&c](ProcessInfo* p) { p->histogram->Rebin(c->current_variable->n_rebin); for (auto& pp : p->systematic_histograms) { pp.second->Rebin(c->current_variable->n_rebin); } }); } void HistToolHelper::rebinByArray(const Config* c, bool transform) { vector<ProcessInfo*>* ps = c->processes->content(); if (c->current_variable->binning) { for_each(ps->begin(), ps->end(), [&c, &transform](ProcessInfo* p) { std::string name = p->histogram->GetName(); TH1* rebinned = p->histogram->Rebin(c->current_variable->n_bins, (name + "rebinned").c_str(), c->current_variable->binning); TH1* transformed = new TH1D((name + "transformed").c_str(), (name + "transformed").c_str(), rebinned->GetNbinsX(), 0., 1.); Utils::properties_copy(transformed, rebinned); for (int i = 1; i <= rebinned->GetNbinsX(); ++i) { transformed->SetBinContent(i, rebinned->GetBinContent(i)); transformed->SetBinError(i, rebinned->GetBinError(i)); } if (transform) { p->histogram = (TH1*)transformed->Clone(); } else { p->histogram = (TH1*)rebinned->Clone(); } for (auto& pp : p->systematic_histograms) { name = pp.second->GetName(); TH1* rebinned_pp = pp.second->Rebin(c->current_variable->n_bins, (name + "rebinned").c_str(), c->current_variable->binning); TH1* transformed_pp = new TH1D((name + "transformed").c_str(), (name + "transformed").c_str(), rebinned->GetNbinsX(), 0., 1.); Utils::properties_copy(transformed_pp, rebinned_pp); pp.second = (TH1*)rebinned_pp->Clone(); for (int i = 1; i <= rebinned_pp->GetNbinsX(); ++i) { transformed_pp->SetBinContent(i, rebinned_pp->GetBinContent(i)); transformed_pp->SetBinError(i, rebinned_pp->GetBinError(i)); } if (transform) { pp.second = (TH1*)transformed_pp->Clone(); } else { pp.second = (TH1*)rebinned_pp->Clone(); } delete rebinned_pp; delete transformed_pp; } delete rebinned; delete transformed; }); } else { clog << "WARN: Binning not given, will rebin based on rebinByNRebin(c) instead\n"; HistToolHelper::rebinByNRebin(c); } }
< 1) { cerr << "FAIL: empty input\n"; return false; } return true; } void HistTool::manipulate(Config* c) { c->setManipulated(true); vector<ProcessInfo*>* ps_in_c = c->processes->content(); clog << "INFO: merging\n"; map<eProcess, vector<ProcessInfo*>> procs; for_each(ps_in_c->begin(), ps_in_c->end(), [&procs](ProcessInfo* p) { procs[p->process].push_back(p); }); for_each(procs.begin(), procs.end(), [&ps_in_c, &c](pair<const eProcess, vector<ProcessInfo*>>& pair) { ProcessInfo* front = pair.second.front(); ProcessInfo* merged = new ProcessInfo( front->process_name, front->process_name, front->type, front->process, front->process_name, front->color); merged->histogram = (TH1*)front->histogram->Clone(); for_each(pair.second.begin() + 1, pair.second.end(), [&merged](const ProcessInfo* p) { merged->histogram->Add(p->histogram); }); if (!(front->systematic_histograms.empty())) { for (auto & pp : front->systematic_histograms) { std::cout << pp.first << std::endl; merged->systematic_histograms[pp.first] = (TH1*)front->systematic_histograms[pp.first]->Clone(); for_each(pair.second.begin() + 1, pair.second.end(), [&merged, &pp](const ProcessInfo* p) { std::cout << p->name << std::endl; if (!p->systematic_histograms.empty()) { if (p->systematic_histograms.find(pp.first) != p->systematic_histograms.end()) merged->systematic_histograms[pp.first]->Add(p->systematic_histograms.at(pp.first)); else merged->systematic_histograms[pp.first]->Add(p->histogram); } }); } } merged->isMerged = true; merged->norm_factor = front->norm_factor; merged->current_region = front->current_region; merged->current_variable = front->current_variable; c->current_region = merged->current_region; c->current_variable = merged->current_variable; ps_in_c->emplace_back(merged); }); ps_in_c->erase(remove_if(ps_in_c->begin(), ps_in_c->end(), [](const ProcessInfo* p) { return !p->isMerged; }), ps_in_c->end()); sort(ps_in_c->begin(), ps_in_c->end(), [](const ProcessInfo* p1, const ProcessInfo* p2) { return p1->type < p2->type; }); } void HistTool::rebin(const Config* c, eRebinOption opt, const std::string& info, bool transform) const { Tools::println("INFO: from HistTool::rebin(): %", info); switch (opt) { case eRebinOption::Self: rebin(c); break; case eRebinOption::N_Rebin: HistToolHelper::rebinByNRebin(c); break; case eRebinOption::Array: HistToolHelper::rebinByArray(c, transform); break; default: break; } } void HistTool::makeYield(const Config* c, const std::string& tag) const { ostringstream oss; oss << output_path << "/" << c->current_region->name << "_" << tag << "_" << c->current_variable->name << ".txt"; ofstream fout(oss.str()); vector<ProcessInfo*>* ps = c->processes->content(); bool hasBkg = false; int entriesBkg = 0; double sumBkg = 0.0; double errBkg = 0.0; fout << FIVE_COLUMN_TABLE("Process", "Entries", "Yield", "Error", "Rel.Err."); for (ProcessInfo* p : *ps) { double error; int from = 0; int to = p->histogram->GetNbinsX() + 1; int nentries = p->histogram->GetEntries(); double integral = p->histogram->IntegralAndError(from, to, error, ""); double eOverI = integral > (double)0. ? error / integral : 0.; fout << FIVE_COLUMN_TABLE(p->name, nentries, integral * p->norm_factor, error * p->norm_factor, eOverI); for (auto& pp : p->systematic_histograms) { auto systEntries = pp.second->GetEntries(); auto systInt = pp.second->Integral(); fout << " |- " << FOUR_COLUMN_TABLE(pp.first, systEntries, systInt, systInt / integral - 1.f); } if (p->type == eProcessType::BKG) { hasBkg = true; entriesBkg += nentries; sumBkg += integral * p->norm_factor; errBkg += error * error * p->norm_factor * p->norm_factor; } } if (hasBkg) { errBkg = sqrt(errBkg); fout << FIVE_COLUMN_TABLE("Total Bkg", entriesBkg, sumBkg, errBkg, errBkg / sumBkg); } clog << "INFO: Yields saved in " << oss.str() << '\n'; } bool HistToolHelper::check(const Config* c) { vector<ProcessInfo*>* ps = c->processes->content(); clog << "INFO: removing nullptrs\n"; ps->erase(remove_if(ps->begin(), ps->end(), [](const ProcessInfo* p) { return !p->histogram; }), ps->end()); if (ps->size() < 1) { cerr << "FAIL: empty input\n"; return false; } return true; } v
random
[ { "content": "class BasicInfo\n\n{\n\npublic:\n\n BasicInfo(const string& ecm, const string& lumi) noexcept;\n\n\n\npublic:\n\n string ecm;\n\n string luminosity;\n\n};\n\n\n\n\n", "file_path": "src/Config.h", "rank": 0, "score": 76141.76415751204 }, { "content": "class Config\n\n{\n\npublic:\n\n Config(const BasicInfo* b, const Processes* ps, \n\n const Regions* rs, const Variables* vs, const Systematics* ss=nullptr) noexcept;\n\n ~Config() noexcept;\n\n\n\n Config(Config& ht) = delete;\n\n Config& operator=(Config& ht) = delete;\n\n\n\npublic:\n\n const BasicInfo* basic;\n\n const Processes* processes;\n\n const Regions* regions;\n\n const Variables* variables;\n\n const Systematics* systematics;\n\n\n\npublic:\n\n void load(const string& fn, const string& dir=\"\");\n\n void updateHistogramPtr(RegionInfo* r, VariableInfo* v);\n", "file_path": "src/Config.h", "rank": 1, "score": 67470.15535890612 }, { "content": "using namespace RooStats;", "file_path": "src/CommonInclude_WS.h", "rank": 2, "score": 62657.4135881269 }, { "content": "void test_ws_info(const std::string& filename);\n", "file_path": "examples/ExamplesInclude_WS.h", "rank": 3, "score": 58470.10435069288 }, { "content": "// ENTRY\n\nclass ProcessInfo\n\n{\n\npublic:\n\n ProcessInfo(const string& nm, const string& nmtex, eProcessType tp, \n\n eProcess proc, const string& nmproc, int col) noexcept\n\n : name(nm), name_tex(nmtex), type(tp)\n\n , process(proc), process_name(nmproc), color(col) {}\n\npublic:\n\n string name; // same as histogram perfix\n\n string name_tex;\n\n eProcessType type;\n\n eProcess process;\n\n string process_name;\n\n int color; // EColor\n\n int rbg = 0xFFFFFF; // TODO: master of color platte\n\n double norm_factor = 1.0; // fitted norm\n\n TH1* histogram = nullptr; // depends on region and variable (will be set in Config)\n\n std::map<std::string, TH1*> systematic_histograms;\n\n bool isMerged = false;\n\n RegionInfo* current_region = nullptr;\n", "file_path": "src/Processes.h", "rank": 4, "score": 56833.71800745277 }, { "content": " void setManipulated(bool m) { m_manipulated = m; }\n\n\n\npublic:\n\n RegionInfo* current_region;\n\n VariableInfo* current_variable;\n\n\n\nprotected:\n\n unique_ptr<TFile> m_fin;\n\n std::string m_dir;\n\n bool m_loaded;\n\n bool m_manipulated;\n\n};\n\n\n\n#endif // CONFIG_H\n", "file_path": "src/Config.h", "rank": 5, "score": 41631.775726194355 }, { "content": "#ifndef CONFIG_H\n\n#define CONFIG_H\n\n\n\n#include \"Processes.h\"\n\n#include \"Regions.h\"\n\n#include \"Variables.h\"\n\n#include \"Systematics.h\"\n\n#include \"Utils.h\"\n\n\n\n#include \"TFile.h\"\n\n#include \"TDirectory.h\"\n\n#include \"TH1.h\"\n\n\n\n#include <string>\n\n#include <memory>\n\n\n\nusing std::string;\n\nusing std::unique_ptr;\n\n\n", "file_path": "src/Config.h", "rank": 6, "score": 41630.110696794975 }, { "content": "#include \"Config.h\"\n\n\n\n#include <iterator>\n\n#include <iostream>\n\n#include <exception>\n\n#include <filesystem>\n\n\n\nusing namespace std;\n\nnamespace fs = std::filesystem;\n\n\n\nBasicInfo::BasicInfo(const string& ecm, const string& lumi) noexcept\n\n : ecm(ecm), luminosity(lumi)\n\n{\n\n\n\n}\n\n\n\nConfig::Config(const BasicInfo* b, const Processes* ps, \n\n const Regions* rs, const Variables* vs, const Systematics* ss) noexcept\n\n : basic(b), processes(ps), regions(rs), variables(vs), systematics(ss)\n\n{\n", "file_path": "src/Config.cpp", "rank": 7, "score": 39793.00607753856 }, { "content": " clog << \"INFO: \" << fullname << \" is not in \" << m_dir << \" (skip it)\\n\";\n\n }\n\n // else that p.histogram will remain as nullptr\n\n // later when make plot this should checked\n\n // -> well handled by HistTool::check()\n\n\n\n ///@todo: use enums to handle ups and downs\n\n if (systematics)\n\n {\n\n for (SystematicInfo* s : *(systematics->content()))\n\n {\n\n const std::string& fullnameWithSystUp = Utils::histStringSyst(p, r, v, s) + \"__1up\";\n\n const std::string& fullnameWithSystDown = Utils::histStringSyst(p, r, v, s) + \"__1down\";\n\n TDirectory* d_syst = nullptr;\n\n d_syst = (TDirectory*)d->Get(\"Systematics\");\n\n if (s->type == eSystematicType::TwoSide &&\n\n d_syst->GetListOfKeys()->Contains(fullnameWithSystUp.c_str()) &&\n\n d_syst->GetListOfKeys()->Contains(fullnameWithSystDown.c_str()))\n\n {\n\n TH1* hUp = (TH1*)d_syst->Get(fullnameWithSystUp.c_str());\n", "file_path": "src/Config.cpp", "rank": 8, "score": 39769.21485982007 }, { "content": " throw std::runtime_error(\"Input does not exist\");\n\n }\n\n m_dir = dir;\n\n if (!m_fin->GetListOfKeys()->Contains(dir.c_str()) && dir != \"\")\n\n {\n\n m_fin->ls();\n\n throw std::runtime_error(dir + \" does not exist in the input file\");\n\n }\n\n m_loaded = true;\n\n}\n\n\n\n\n\nvoid Config::updateHistogramPtr(RegionInfo* r, VariableInfo* v)\n\n{\n\n if (!m_loaded)\n\n {\n\n throw std::runtime_error(\"You must load first\");\n\n }\n\n\n\n if (m_manipulated)\n", "file_path": "src/Config.cpp", "rank": 9, "score": 39768.20100287189 }, { "content": " m_fin = nullptr;\n\n m_dir = \"\";\n\n m_loaded = false;\n\n m_manipulated = false;\n\n}\n\n\n\nConfig::~Config() noexcept\n\n{\n\n m_fin->Close();\n\n}\n\n\n\nvoid Config::load(const string& fn, const string& dir)\n\n{\n\n if (!fs::exists(fs::path(fn)))\n\n {\n\n throw std::runtime_error(\"Input does not exist\");\n\n }\n\n m_fin.reset(TFile::Open(fn.c_str(), \"read\"));\n\n if (!m_fin)\n\n {\n", "file_path": "src/Config.cpp", "rank": 10, "score": 39764.55000859653 }, { "content": " Utils::histAssignSyst(hUp, p, Utils::systString(s));\n\n }\n\n }\n\n else\n\n {\n\n clog << \"INFO: Can not add systematic uncertainty [\" << s->name << \"] (skip it)\\n\";\n\n }\n\n }\n\n }\n\n }\n\n \n\n}\n\n\n", "file_path": "src/Config.cpp", "rank": 11, "score": 39764.086843584635 }, { "content": " {\n\n throw std::runtime_error(\"Update histogram pointer for manipulated histograms is not supported!\");\n\n }\n\n\n\n current_region = r;\n\n current_variable = v;\n\n\n\n TDirectory* d = nullptr;\n\n d = m_fin->GetDirectory(m_dir.c_str());\n\n\n\n for (ProcessInfo* p : *(processes->content()))\n\n {\n\n const std::string& fullname = Utils::histString(p, r, v);\n\n if (d->GetListOfKeys()->Contains(fullname.c_str()))\n\n {\n\n TH1* h = (TH1*)d->Get(fullname.c_str());\n\n Utils::histAssign(h, p, r, v);\n\n }\n\n else\n\n {\n", "file_path": "src/Config.cpp", "rank": 12, "score": 39763.52275538133 }, { "content": " TH1* hDown = (TH1*)d_syst->Get(fullnameWithSystDown.c_str());\n\n\n\n // set styles here for simplicity\n\n hUp->SetLineColor(s->color);\n\n // hUp->SetFillColor(s->color);\n\n hUp->SetMarkerColor(s->color);\n\n hUp->SetLineStyle(1);\n\n hDown->SetLineColor(s->color);\n\n // hDown->SetFillColor(s->color);\n\n hDown->SetMarkerColor(s->color);\n\n hDown->SetLineStyle(2);\n\n\n\n if (s->name == s->name_tex)\n\n {\n\n Utils::histAssignSyst(hUp, p, Utils::systString(s) + \"__1up\");\n\n Utils::histAssignSyst(hDown, p, Utils::systString(s) + \"__1down\");\n\n }\n\n else\n\n {\n\n Utils::histAssignSyst(hUp, p, Utils::systString(s) + \" (1up)\");\n", "file_path": "src/Config.cpp", "rank": 13, "score": 39761.61173178881 }, { "content": " Utils::histAssignSyst(hDown, p, Utils::systString(s) + \" (1down)\");\n\n }\n\n }\n\n else if (s->type == eSystematicType::OneSide && \n\n d_syst->GetListOfKeys()->Contains(fullnameWithSystUp.c_str()))\n\n {\n\n TH1* hUp = (TH1*)d_syst->Get(fullnameWithSystUp.c_str());\n\n\n\n // set styles here for simplicity\n\n hUp->SetLineColor(s->color);\n\n // hUp->SetFillColor(s->color);\n\n hUp->SetMarkerColor(s->color);\n\n hUp->SetLineStyle(1);\n\n\n\n if (s->name == s->name_tex)\n\n {\n\n Utils::histAssignSyst(hUp, p, Utils::systString(s) + \"__1up\");\n\n }\n\n else\n\n {\n", "file_path": "src/Config.cpp", "rank": 14, "score": 39761.315980266234 }, { "content": "// ELEM\n\nclass RegionInfo\n\n{\n\npublic:\n\n RegionInfo(const string& nm, const string& nmtex, eRegionType tp) noexcept\n\n : name(nm), name_tex(nmtex), type(tp) {}\n\n\n\npublic:\n\n string name;\n\n string name_tex;\n\n eRegionType type;\n\n};\n\n\n\n\n", "file_path": "src/Regions.h", "rank": 15, "score": 38082.129457113566 }, { "content": "// ELEM\n\nclass VariableInfo\n\n{\n\npublic:\n\n VariableInfo(const string& nm, const string& nmtex, unsigned rb, double* bing = nullptr, std::size_t n = 0) noexcept\n\n : name(nm), name_tex(nmtex), n_rebin(rb), binning(bing), n_bins(n) {}\n\n\n\npublic:\n\n string name;\n\n string name_tex;\n\n unsigned n_rebin;\n\n double* binning;\n\n std::size_t n_bins;\n\n};\n\n\n\n\n", "file_path": "src/Variables.h", "rank": 16, "score": 38082.129457113566 }, { "content": "// ELEM\n\nclass SystematicInfo\n\n{\n\npublic:\n\n SystematicInfo(const string& nm, const string& nmtex, eSystematicType tp, int col=2) noexcept\n\n : name(nm), name_tex(nmtex), type(tp), color(col) {}\n\n\n\npublic:\n\n string name;\n\n string name_tex;\n\n eSystematicType type;\n\n int color;\n\n};\n\n\n\n\n", "file_path": "src/Systematics.h", "rank": 17, "score": 38082.129457113566 }, { "content": "class CompInfo\n\n{\n\npublic:\n\n bool logx = false;\n\n bool logy = false;\n\n bool atlas = true;\n\n bool shape_only = false;\n\n bool save_ratio = false;\n\n double ratio_high = 1.24;\n\n double ratio_low = 0.76;\n\n const char* atlas_label = \"Simulation Internal\";\n\n std::string parameter;\n\n std::string ratio_tex = \"Ratio\";\n\n // add new configs here\n\n};\n\n\n\n/**\n\n * @brief compare with the first entry\n\n */\n", "file_path": "src/CompTool.h", "rank": 18, "score": 36523.54147384228 }, { "content": "struct WorkspaceInfo\n\n{\n\n WorkspaceInfo() = default;\n\n string path;\n\n string workspace_name;\n\n string config_name = \"ModelConfig\";\n\n string data_name = \"obsData\";\n\n double mu_asimov = 1.0;\n\n double tolerance = 1e-5;\n\n int8_t logLevel = -1;\n\n bool use_asimov = true;\n\n bool use_oneline_fit = true;\n\n};\n\n\n", "file_path": "src/WorkSpace.h", "rank": 19, "score": 36523.54147384228 }, { "content": "// ----------------------------------------------------------------------------\n\n// Info\n\n// ----------------------------------------------------------------------------\n\nclass AutoBinningInfo\n\n{\n\npublic:\n\n unsigned n_bins = 8;\n\n double min_bkg = 5; // all bkg\n\n double min_mcstats = 0.2; // all bkg\n\n double required_mcstats = 0.2; // individual component (leading half)\n\n double eff_factor = 0.5; // effective factor\n\n double significance_delta = 1e-5; // stop adding bins if delta significance < 1e-5\n\n const char* atlas_label = \"Simulation Internal\";\n\n std::string parameter = \"TAG\";\n\n};\n\n\n", "file_path": "src/AutoBinningTool.h", "rank": 20, "score": 33764.315338589055 }, { "content": "class DrawStackInfo\n\n{\n\npublic:\n\n bool blind = true;\n\n bool logx = false;\n\n bool logy = false;\n\n bool atlas = true;\n\n double ratio_high = 1.24;\n\n double ratio_low = 0.76;\n\n const char* atlas_label = \"Internal\";\n\n double signal_scale = 100.;\n\n std::string parameter = \"TAG\";\n\n // add new configs here\n\n};\n\n\n", "file_path": "src/DrawStackTool.h", "rank": 21, "score": 33760.137952240424 }, { "content": "void hadhadsr_v15(const std::string& filename);\n", "file_path": "examples/ExamplesInclude.h", "rank": 22, "score": 31197.34729324268 }, { "content": "void test_hadhad(const std::string& filename);\n", "file_path": "examples/ExamplesInclude.h", "rank": 23, "score": 31197.34729324268 }, { "content": "void test_bbll(const std::string& filename);\n", "file_path": "examples/ExamplesInclude.h", "rank": 24, "score": 31197.34729324268 }, { "content": "void test_ttbarKine(const std::string& filename);\n", "file_path": "examples/ExamplesInclude.h", "rank": 25, "score": 30137.42931894293 }, { "content": "int test_ranking(const std::string& filename, const std::string& outname);\n", "file_path": "examples/ExamplesInclude_WS.h", "rank": 26, "score": 30137.42931894293 }, { "content": "void test_hadhad_klambda(const std::string& filename);\n", "file_path": "examples/ExamplesInclude.h", "rank": 27, "score": 30137.42931894293 }, { "content": "int test_pulls(const std::string& filename, const std::string& outname);\n", "file_path": "examples/ExamplesInclude_WS.h", "rank": 28, "score": 30137.42931894293 }, { "content": "void test_pseudodata(const std::vector<std::string>& path, const std::string& outfile);\n", "file_path": "examples/ExamplesInclude_WS.h", "rank": 29, "score": 30137.42931894293 }, { "content": "void hadhadsr_v15_binning(const std::string& filename);\n", "file_path": "examples/ExamplesInclude.h", "rank": 30, "score": 30137.42931894293 }, { "content": "void hadhadsr_v15_yield(const std::string& filename);\n", "file_path": "examples/ExamplesInclude.h", "rank": 31, "score": 30137.42931894293 }, { "content": "void test_hadhad_yield(const std::string& filename);\n", "file_path": "examples/ExamplesInclude.h", "rank": 32, "score": 30137.42931894293 }, { "content": "int test_ranking_plot(const std::string& in, const std::string& out);\n", "file_path": "examples/ExamplesInclude_WS.h", "rank": 33, "score": 29147.165489402567 }, { "content": "void test_hadhad_WtOTF(const std::string& filename);\n", "file_path": "examples/ExamplesInclude.h", "rank": 34, "score": 29147.165489402567 }, { "content": "void test_hadhad_ZtautauMG(const std::string& filename);\n", "file_path": "examples/ExamplesInclude.h", "rank": 35, "score": 29147.165489402567 }, { "content": "int test_pulls_plot(const std::string& in, const std::string& out);\n", "file_path": "examples/ExamplesInclude_WS.h", "rank": 36, "score": 29147.165489402567 }, { "content": "void test_hadhad_WtGen(const std::string& filename);\n", "file_path": "examples/ExamplesInclude.h", "rank": 37, "score": 29147.165489402567 }, { "content": "void test_hadhad_NonRes(const std::string& filename);\n", "file_path": "examples/ExamplesInclude.h", "rank": 38, "score": 29147.165489402567 }, { "content": "void test_lephad_ttbarRew(const std::string& filename);\n", "file_path": "examples/ExamplesInclude.h", "rank": 39, "score": 29147.165489402567 }, { "content": "void test_hadhad_ZtautauUnc1(const std::string& filename);\n", "file_path": "examples/ExamplesInclude.h", "rank": 40, "score": 29147.165489402567 }, { "content": "void test_hadhad_WtDS(const std::string& filename);\n", "file_path": "examples/ExamplesInclude.h", "rank": 41, "score": 29147.165489402567 }, { "content": "void test_lephad_ttbarSys(const std::string& filename);\n", "file_path": "examples/ExamplesInclude.h", "rank": 42, "score": 29147.165489402567 }, { "content": "void test_hadhad_ZtautauUnc2(const std::string& filename);\n", "file_path": "examples/ExamplesInclude.h", "rank": 43, "score": 29147.165489402567 }, { "content": "void test_hadhad_ZtautauUnc3(const std::string& filename);\n", "file_path": "examples/ExamplesInclude.h", "rank": 44, "score": 29147.165489402567 }, { "content": "void test_hadhad_ZtautauRew(const std::string& filename);\n", "file_path": "examples/ExamplesInclude.h", "rank": 45, "score": 29147.165489402567 }, { "content": "void test_hadhad_ttbarRew(const std::string& filename);\n", "file_path": "examples/ExamplesInclude.h", "rank": 46, "score": 29147.165489402567 }, { "content": "void test_hadhad_ttbarSys_Gen(const std::string& filename);\n", "file_path": "examples/ExamplesInclude.h", "rank": 47, "score": 28219.908092585512 }, { "content": "void test_hadhad_ttbarSys_OTF(const std::string& filename);\n", "file_path": "examples/ExamplesInclude.h", "rank": 48, "score": 28219.908092585512 }, { "content": "#include \"SystCompTool.h\"\n\n#include \"CommonInclude.h\"\n\n\n\n#include <sstream>\n\n#include <algorithm>\n\n#include <filesystem>\n\n\n\nusing namespace std;\n\nnamespace fs = std::filesystem;\n\n\n\nbool SystCompTool::check(const Config* c) const\n\n{\n\n if (!HistTool::check(c))\n\n return false;\n\n\n\n vector<ProcessInfo*>* ps = c->processes->content();\n\n\n\n if (ps->size() != 1) {\n\n return false; // one process and its systematic uncertainties\n\n }\n", "file_path": "src/SystCompTool.cpp", "rank": 51, "score": 42.65618916970256 }, { "content": "#include \"ExamplesInclude_WS.h\"\n\n#include \"TROOT.h\"\n\n\n\n#include <iostream>\n\n#include <sstream>\n\n#include <fstream>\n\n\n\nusing namespace std;\n\n\n\nint main(int argc, char** argv)\n\n{\n\n if (argc < 3)\n\n {\n\n cerr << \"Usage: run-pd <list.txt> <output>\\n\";\n\n return 0;\n\n }\n\n\n\n gROOT->SetBatch(1);\n\n\n\n vector<string> filenames;\n", "file_path": "exec/run_pseudodata.cpp", "rank": 52, "score": 34.89503208424822 }, { "content": "#ifndef WorkSpace_H\n\n#define WorkSpace_H\n\n\n\n#include <iostream>\n\n#include <chrono>\n\n#include <memory>\n\n#include <vector>\n\n#include <map>\n\n#include <set>\n\n#include <tuple>\n\n#include <thread>\n\n#include <mutex>\n\n#include <algorithm>\n\n#include <atomic>\n\n#include <fstream>\n\n#include <sstream>\n\n#include <filesystem>\n\n\n\n#include \"CommonInclude.h\"\n\n#include \"CommonInclude_WS.h\"\n", "file_path": "src/WorkSpace.h", "rank": 53, "score": 30.649690692238472 }, { "content": "#include \"CompTool.h\"\n\n#include \"CommonInclude.h\"\n\n\n\n#include <sstream>\n\n#include <algorithm>\n\n#include <filesystem>\n\n\n\nusing namespace std;\n\nnamespace fs = std::filesystem;\n\n\n\nCompTool::CompTool(const CompInfo* info)\n\n : HistTool(), m_info(info)\n\n{\n\n\n\n}\n\n\n\nCompTool::~CompTool()\n\n{\n\n\n\n}\n", "file_path": "src/CompTool.cpp", "rank": 54, "score": 30.49421450576301 }, { "content": "#include \"DrawStackTool.h\"\n\n#include \"CommonInclude.h\"\n\n\n\n#include <sstream>\n\n#include <algorithm>\n\n#include <filesystem>\n\n\n\nusing namespace std;\n\nnamespace fs = std::filesystem;\n\n\n\nDrawStackTool::DrawStackTool(const DrawStackInfo* info)\n\n : HistTool(), m_info(info)\n\n{\n\n\n\n}\n\n\n\nDrawStackTool::~DrawStackTool()\n\n{\n\n\n\n}\n", "file_path": "src/DrawStackTool.cpp", "rank": 55, "score": 29.78881955729095 }, { "content": "#include \"ExamplesInclude.h\"\n\n\n\n#include \"Config.h\"\n\n#include \"Utils.h\"\n\n#include \"CompTool.h\"\n\n#include \"AutoBinningTool.h\"\n\n\n\n#include \"TFile.h\"\n\n#include \"TH1.h\"\n\n\n\n#include <iostream>\n\n\n\nusing std::cout; \n\nusing std::endl;\n\nusing std::clog;\n\n\n\nvoid test_ttbarKine(const std::string& filename)\n\n{\n\n BasicInfo* b = new BasicInfo(\"#sqrt{s} = 13 TeV\", \"L = 139 fb^{-1}\");\n\n\n", "file_path": "examples/Example_ttbarKine.cpp", "rank": 56, "score": 29.517384557455998 }, { "content": "#include \"ExamplesInclude.h\"\n\n\n\n#include \"Config.h\"\n\n#include \"Utils.h\"\n\n#include \"DrawStackTool.h\"\n\n\n\n#include \"TFile.h\"\n\n#include \"TH1.h\"\n\n\n\n#include <iostream>\n\n\n\nusing std::cout; \n\nusing std::endl;\n\nusing std::clog;\n\n\n\nvoid test_hadhad(const std::string& filename)\n\n{\n\n BasicInfo* b = new BasicInfo(\"#sqrt{s} = 13 TeV\", \"L = 139 fb^{-1}\");\n\n\n\n Regions* rs = new Regions();\n", "file_path": "examples/Example.cpp", "rank": 57, "score": 29.46344351781515 }, { "content": "#include \"ExamplesInclude.h\"\n\n\n\n#include \"Config.h\"\n\n#include \"Utils.h\"\n\n#include \"CompTool.h\"\n\n\n\n#include \"TFile.h\"\n\n#include \"TH1.h\"\n\n\n\n#include <iostream>\n\n\n\nusing std::cout; \n\nusing std::endl;\n\nusing std::clog;\n\n\n\nvoid test_hadhad_klambda(const std::string& filename)\n\n{\n\n BasicInfo* b = new BasicInfo(\"#sqrt{s} = 13 TeV\", \"L = 139 fb^{-1}\");\n\n\n\n Regions* rs = new Regions();\n", "file_path": "examples/Example_klambda.cpp", "rank": 58, "score": 29.46344351781515 }, { "content": "#include \"ExamplesInclude.h\"\n\n\n\n#include \"Config.h\"\n\n#include \"Utils.h\"\n\n#include \"DrawStackTool.h\"\n\n\n\n#include \"TFile.h\"\n\n#include \"TH1.h\"\n\n\n\n#include <iostream>\n\n\n\nusing std::cout; \n\nusing std::endl;\n\nusing std::clog;\n\n\n\nvoid test_hadhad_yield(const std::string& filename)\n\n{\n\n BasicInfo* b = new BasicInfo(\"#sqrt{s} = 13 TeV\", \"L = 139 fb^{-1}\");\n\n\n\n Regions* rs = new Regions();\n", "file_path": "examples/Example_yield.cpp", "rank": 59, "score": 29.361937825543215 }, { "content": "#include \"ExamplesInclude.h\"\n\n\n\n#include \"Config.h\"\n\n#include \"Utils.h\"\n\n#include \"DrawStackTool.h\"\n\n\n\n#include \"TFile.h\"\n\n#include \"TH1.h\"\n\n\n\n#include <iostream>\n\n\n\nusing std::cout; \n\nusing std::endl;\n\nusing std::clog;\n\n\n\nvoid hadhadsr_v15_yield(const std::string& filename)\n\n{\n\n BasicInfo* b = new BasicInfo(\"#sqrt{s} = 13 TeV\", \"L = 139 fb^{-1}\");\n\n\n\n Regions* rs = new Regions();\n", "file_path": "examples/HadHadSR_v15_yield.cpp", "rank": 60, "score": 29.361937825543208 }, { "content": "#include \"Config.h\"\n\n#include \"Utils.h\"\n\n#include \"CompTool.h\"\n\n\n\n#include \"ExamplesInclude.h\"\n\n\n\n#include \"TFile.h\"\n\n#include \"TH1.h\"\n\n\n\n#include <iostream>\n\n\n\nusing std::cout; \n\nusing std::endl;\n\nusing std::clog;\n\n\n\nvoid test_hadhad_NonRes(const std::string& filename)\n\n{\n\n BasicInfo* b = new BasicInfo(\"#sqrt{s} = 13 TeV\", \"L = 139 fb^{-1}\");\n\n\n\n Regions* rs = new Regions();\n", "file_path": "examples/Example_NonRes.cpp", "rank": 61, "score": 29.361937825543208 }, { "content": "#include \"ExamplesInclude.h\"\n\n\n\n#include \"Config.h\"\n\n#include \"Utils.h\"\n\n#include \"CompTool.h\"\n\n#include \"AutoBinningTool.h\"\n\n\n\n#include \"TFile.h\"\n\n#include \"TH1.h\"\n\n\n\n#include <iostream>\n\n\n\nusing std::cout; \n\nusing std::endl;\n\nusing std::clog;\n\nusing BU = BinningUtils;\n\n\n\nvoid test_hadhad_WtGen(const std::string& filename)\n\n{\n\n BasicInfo* b = new BasicInfo(\"#sqrt{s} = 13 TeV\", \"L = 139 fb^{-1}\");\n", "file_path": "examples/Example_WtGen.cpp", "rank": 62, "score": 29.28567856871092 }, { "content": "#include \"ExamplesInclude.h\"\n\n\n\n#include \"Config.h\"\n\n#include \"Utils.h\"\n\n#include \"CompTool.h\"\n\n#include \"AutoBinningTool.h\"\n\n\n\n#include \"TFile.h\"\n\n#include \"TH1.h\"\n\n\n\n#include <iostream>\n\n\n\nusing std::cout; \n\nusing std::endl;\n\nusing std::clog;\n\nusing BU = BinningUtils;\n\n\n\nvoid test_hadhad_WtDS(const std::string& filename)\n\n{\n\n BasicInfo* b = new BasicInfo(\"#sqrt{s} = 13 TeV\", \"L = 139 fb^{-1}\");\n", "file_path": "examples/Example_WtDS.cpp", "rank": 63, "score": 29.28567856871092 }, { "content": "#include \"ExamplesInclude.h\"\n\n\n\n#include \"Config.h\"\n\n#include \"Utils.h\"\n\n#include \"CompTool.h\"\n\n#include \"AutoBinningTool.h\"\n\n\n\n#include \"TFile.h\"\n\n#include \"TH1.h\"\n\n\n\n#include <iostream>\n\n\n\nusing std::cout; \n\nusing std::endl;\n\nusing std::clog;\n\nusing BU = BinningUtils;\n\n\n\nvoid test_hadhad_ttbarSys_Gen(const std::string& filename)\n\n{\n\n BasicInfo* b = new BasicInfo(\"#sqrt{s} = 13 TeV\", \"L = 139 fb^{-1}\");\n", "file_path": "examples/Example_ttbarGen.cpp", "rank": 64, "score": 29.19102066953771 }, { "content": "#include \"ExamplesInclude.h\"\n\n\n\n#include \"Config.h\"\n\n#include \"Utils.h\"\n\n#include \"LephadTTBarCompTool.h\"\n\n\n\n#include \"TFile.h\"\n\n#include \"TH1.h\"\n\n\n\n#include <iostream>\n\n\n\nusing std::cout; \n\nusing std::endl;\n\nusing std::clog;\n\n\n\nvoid test_lephad_ttbarSys(const std::string& filename)\n\n{\n\n BasicInfo* b = new BasicInfo(\"#sqrt{s} = 13 TeV\", \"L = 139 fb^{-1}\");\n\n\n\n Regions* rs = new Regions();\n", "file_path": "examples/Example_ttbarSyst.cpp", "rank": 65, "score": 29.062634550091893 }, { "content": "#include \"LephadTTBarCompTool.h\"\n\n\n\n#include \"CommonInclude.h\"\n\n#include \"Utils.h\"\n\n\n\nusing namespace std;\n\n\n\nvoid LephadTTBarCompTool::paint(const Config* c) const\n\n{\n\n if (!m_isCombined)\n\n {\n\n throw runtime_error(\"Must combine reweight systematics first!\");\n\n }\n\n CompTool::paint(c);\n\n\n\n vector<ProcessInfo*>* ps = c->processes->content();\n\n auto& p = ps->front();\n\n auto& systs = ps->front()->systematic_histograms;\n\n auto& nom = systs.at(\"ttbar reweight\"); \n\n auto& nomSample = ps->front()->histogram;\n", "file_path": "src/LephadTTBarCompTool.cpp", "rank": 66, "score": 28.383831669494125 }, { "content": "#include \"AutoBinningTool.h\"\n\n\n\n#include <fstream>\n\n#include <sstream>\n\n\n\nusing namespace std;\n\n\n\n#define BKGBKG (std::make_pair(eProcessType::BKG, eProcess::BKG))\n\n\n\n// ----------------------------------------------------------------------------\n\n// BinContent\n\n// ----------------------------------------------------------------------------\n\n\n\nstd::size_t BinContent::size() const noexcept\n\n{\n\n return m_size;\n\n}\n\n\n\nvoid BinContent::fill(const Config* c) noexcept\n\n{\n", "file_path": "src/AutoBinningTool.cpp", "rank": 67, "score": 28.264684846840105 }, { "content": "#ifndef UTILS_H\n\n#define UTILS_H\n\n\n\n#include \"Processes.h\"\n\n#include \"Regions.h\"\n\n#include \"Variables.h\"\n\n#include \"Systematics.h\"\n\n\n\n#include \"TH1.h\"\n\n#include \"TFile.h\"\n\n#include \"TDirectory.h\"\n\n\n\n#include <iostream>\n\n#include <sstream>\n\n#include <fstream>\n\n#include <string>\n\n#include <vector>\n\n#include <climits>\n\n\n\nusing std::string;\n", "file_path": "src/Utils.h", "rank": 68, "score": 27.54290271186562 }, { "content": "/**\n\n * @brief This is only an inteface class for now\n\n */\n\n\n\n#ifndef STATISTICTOOL_H\n\n#define STATISTICTOOL_H\n\n\n\n#include <string>\n\n#include <iostream>\n\n#include <iomanip>\n\n\n\n#ifndef OUTPUT_TABLE_4\n\n#define OUTPUT_TABLE_4(A, B, C, D) \\\n\n std::left << std::setw(100) << A \\\n\n << std::left << std::setw(15) << B \\\n\n << std::left << std::setw(15) << C \\\n\n << std::left << std::setw(15) << D << endl;\n\n#endif\n\n\n", "file_path": "src/StatisticTool.h", "rank": 69, "score": 26.414872047450253 }, { "content": "/**\n\n * This is for lephad channel\n\n */\n\n\n\n#include \"ExamplesInclude.h\"\n\n\n\n#include \"Config.h\"\n\n#include \"Utils.h\"\n\n#include \"SystCompTool.h\"\n\n\n\n#include \"TFile.h\"\n\n#include \"TH1.h\"\n\n\n\n#include <iostream>\n\n\n\nusing std::cout; \n\nusing std::endl;\n\nusing std::clog;\n\n\n\nvoid test_lephad_ttbarRew(const std::string& filename)\n", "file_path": "examples/Example_ttbarRew.cpp", "rank": 70, "score": 26.413996875348694 }, { "content": "#include \"ExamplesInclude.h\"\n\n\n\n#include \"Config.h\"\n\n#include \"Utils.h\"\n\n#include \"AutoBinningTool.h\"\n\n\n\n#include \"TFile.h\"\n\n#include \"TH1.h\"\n\n\n\n#include <iostream>\n\n\n\nusing std::cout; \n\nusing std::endl;\n\nusing std::clog;\n\n\n\n#define ADDBKGTOPS() \\\n\nps->add(\"Zttbb\", \"Z#tau#tau + bb\", eProcessType::BKG, eProcess::ZllHF, \"Z+hf\", kBlue-10); \\\n\nps->add(\"Zttbc\", \"Z#tau#tau + bc\", eProcessType::BKG, eProcess::ZllHF, \"Z+hf\", kBlue-10); \\\n\nps->add(\"Zttbl\", \"Z#tau#tau + bl\", eProcessType::BKG, eProcess::OTHERS, \"Others\", kBlue-5); \\\n\nps->add(\"Zttcc\", \"Z#tau#tau + cc\", eProcessType::BKG, eProcess::ZllHF, \"Z+hf\", kBlue-10); \\\n", "file_path": "examples/HadHadSR_v15_binning.cpp", "rank": 71, "score": 26.347875909909003 }, { "content": "#include \"ExamplesInclude.h\"\n\n\n\n#include \"Config.h\"\n\n#include \"Utils.h\"\n\n#include \"DrawStackTool.h\"\n\n#include \"AutoBinningTool.h\"\n\n\n\n\n\n#include \"TFile.h\"\n\n#include \"TH1.h\"\n\n\n\n#include <iostream>\n\n\n\nusing std::cout; \n\nusing std::endl;\n\nusing std::clog;\n\nusing BU = BinningUtils;\n\n\n\nvoid test_bbll(const std::string& filename)\n\n{\n", "file_path": "examples/Example_bbll.cpp", "rank": 72, "score": 26.327714557052435 }, { "content": "#include \"ExamplesInclude.h\"\n\n\n\n#include \"Config.h\"\n\n#include \"Utils.h\"\n\n#include \"DrawStackTool.h\"\n\n#include \"AutoBinningTool.h\"\n\n\n\n\n\n#include \"TFile.h\"\n\n#include \"TH1.h\"\n\n\n\n#include <iostream>\n\n\n\nusing std::cout; \n\nusing std::endl;\n\nusing std::clog;\n\nusing BU = BinningUtils;\n\n\n\nvoid hadhadsr_v15(const std::string& filename)\n\n{\n", "file_path": "examples/HadHadSR_v15.cpp", "rank": 73, "score": 26.327714557052435 }, { "content": "#include \"Regions.h\"\n\n\n\n#include <algorithm>\n\n\n\nusing namespace std;\n\n\n\nRegions::Regions()\n\n{\n\n m_regions = make_unique<vector<RegionInfo*>>();\n\n}\n\n\n\nRegions::~Regions()\n\n{\n\n for_each(content()->begin(), content()->end(), [](RegionInfo* r) { delete r; });\n\n content()->clear();\n\n}\n\n\n\nvoid Regions::add(const string &nm, const string &nmtex, eRegionType tp) const\n\n{\n\n m_regions->emplace_back(new RegionInfo(nm, nmtex, tp));\n\n}\n", "file_path": "src/Regions.cpp", "rank": 74, "score": 26.2911832280447 }, { "content": "#include \"Processes.h\"\n\n\n\n#include <algorithm>\n\n\n\nusing namespace std;\n\n\n\nProcesses::Processes() noexcept\n\n{\n\n m_procs = make_unique<vector<ProcessInfo*>>();\n\n}\n\n\n\nProcesses::~Processes()\n\n{\n\n for_each(content()->begin(), content()->end(), [](ProcessInfo* p) { delete p; });\n\n content()->clear();\n\n}\n\n\n\nvoid Processes::add(const string& nm, const string& nmtex, eProcessType tp, \n\n eProcess proc, const string& nmproc, int col) const\n\n{\n", "file_path": "src/Processes.cpp", "rank": 75, "score": 26.165075904655716 }, { "content": "\n\nbool CompTool::check(const Config* c) const\n\n{\n\n if (!HistTool::check(c))\n\n return false;\n\n\n\n vector<ProcessInfo*>* ps = c->processes->content();\n\n\n\n return ps->size() > 1;\n\n}\n\n\n\nvoid CompTool::paint(const Config* c) const\n\n{\n\n vector<ProcessInfo*>* ps = c->processes->content();\n\n for_each(ps->begin(), ps->end(), [&c](ProcessInfo* p) {\n\n p->histogram->SetLineWidth(2);\n\n p->histogram->SetLineStyle(1);\n\n p->histogram->SetMarkerSize(0);\n\n p->histogram->SetMarkerColor(p->color);\n\n p->histogram->SetLineColor(p->color);\n", "file_path": "src/CompTool.cpp", "rank": 76, "score": 26.016571116669027 }, { "content": "#ifndef AUTOBINNINGTOOL_H\n\n#define AUTOBINNINGTOOL_H\n\n\n\n#include \"HistTool.h\"\n\n\n\n#include <vector>\n\n#include <map>\n\n#include <queue>\n\n\n\nusing std::vector;\n\n\n\n// ----------------------------------------------------------------------------\n\n// Info\n\n// ----------------------------------------------------------------------------\n", "file_path": "src/AutoBinningTool.h", "rank": 77, "score": 25.948468888907243 }, { "content": "#include \"ExamplesInclude.h\"\n\n\n\n#include \"Config.h\"\n\n#include \"Utils.h\"\n\n#include \"CompTool.h\"\n\n#include \"SystCompTool.h\"\n\n#include \"AutoBinningTool.h\"\n\n\n\n#include \"TFile.h\"\n\n#include \"TH1.h\"\n\n\n\n#include <iostream>\n\n\n\nusing std::cout; \n\nusing std::endl;\n\nusing std::clog;\n\nusing BU = BinningUtils;\n\n\n\nvoid test_hadhad_ZtautauUnc1(const std::string& filename)\n\n{\n", "file_path": "examples/Example_ZtautauUnc1.cpp", "rank": 78, "score": 25.932978631220998 }, { "content": "#include \"ExamplesInclude.h\"\n\n\n\n#include \"Config.h\"\n\n#include \"Utils.h\"\n\n#include \"CompTool.h\"\n\n#include \"SystCompTool.h\"\n\n#include \"AutoBinningTool.h\"\n\n\n\n#include \"TFile.h\"\n\n#include \"TH1.h\"\n\n\n\n#include <iostream>\n\n\n\nusing std::cout; \n\nusing std::endl;\n\nusing std::clog;\n\nusing BU = BinningUtils;\n\n\n\nvoid test_hadhad_ZtautauMG(const std::string& filename)\n\n{\n", "file_path": "examples/Example_ZtautauMG.cpp", "rank": 79, "score": 25.932978631220998 }, { "content": "#include \"ExamplesInclude.h\"\n\n\n\n#include \"Config.h\"\n\n#include \"Utils.h\"\n\n#include \"CompTool.h\"\n\n#include \"SystCompTool.h\"\n\n#include \"AutoBinningTool.h\"\n\n\n\n#include \"TFile.h\"\n\n#include \"TH1.h\"\n\n\n\n#include <iostream>\n\n\n\nusing std::cout; \n\nusing std::endl;\n\nusing std::clog;\n\nusing BU = BinningUtils;\n\n\n\nvoid test_hadhad_ZtautauUnc3(const std::string& filename)\n\n{\n", "file_path": "examples/Example_ZtautauUnc3.cpp", "rank": 80, "score": 25.932978631220994 }, { "content": "#include \"ExamplesInclude.h\"\n\n\n\n#include \"Config.h\"\n\n#include \"Utils.h\"\n\n#include \"CompTool.h\"\n\n#include \"SystCompTool.h\"\n\n#include \"AutoBinningTool.h\"\n\n\n\n#include \"TFile.h\"\n\n#include \"TH1.h\"\n\n\n\n#include <iostream>\n\n\n\nusing std::cout; \n\nusing std::endl;\n\nusing std::clog;\n\nusing BU = BinningUtils;\n\n\n\nvoid test_hadhad_ZtautauUnc2(const std::string& filename)\n\n{\n", "file_path": "examples/Example_ZtautauUnc2.cpp", "rank": 81, "score": 25.932978631220994 }, { "content": "#include \"ExamplesInclude.h\"\n\n\n\n#include \"Config.h\"\n\n#include \"Utils.h\"\n\n#include \"CompTool.h\"\n\n#include \"SystCompTool.h\"\n\n#include \"AutoBinningTool.h\"\n\n\n\n#include \"TFile.h\"\n\n#include \"TH1.h\"\n\n\n\n#include <iostream>\n\n\n\nusing std::cout; \n\nusing std::endl;\n\nusing std::clog;\n\nusing BU = BinningUtils;\n\n\n\nvoid test_hadhad_ZtautauRew(const std::string& filename)\n\n{\n", "file_path": "examples/Example_ZtautauRew.cpp", "rank": 82, "score": 25.932978631220994 }, { "content": "#include \"Systematics.h\"\n\n\n\n#include <algorithm>\n\n\n\nusing namespace std;\n\n\n\nSystematics::Systematics()\n\n{\n\n m_systs = make_unique<vector<SystematicInfo*>>();\n\n}\n\n\n\nSystematics::~Systematics()\n\n{\n\n for_each(content()->begin(), content()->end(), [](SystematicInfo* r) { delete r; });\n\n content()->clear();\n\n}\n\n\n\nvoid Systematics::add(const string &nm, const string &nmtex, eSystematicType tp, int col) const\n\n{\n\n m_systs->emplace_back(new SystematicInfo(nm, nmtex, tp, col));\n\n}\n", "file_path": "src/Systematics.cpp", "rank": 83, "score": 25.91113042967207 }, { "content": "#include \"Variables.h\"\n\n\n\n#include <algorithm>\n\n\n\nusing namespace std;\n\n\n\nVariables::Variables()\n\n{\n\n m_vars = make_unique<vector<VariableInfo*>>();\n\n}\n\n\n\nVariables::~Variables()\n\n{\n\n for_each(content()->begin(), content()->end(), [](VariableInfo* v) { delete v; });\n\n content()->clear();\n\n}\n\n\n\nvoid Variables::add(const string &nm, const string &nmtex, unsigned rb, double *bing, size_t n) const\n\n{\n\n m_vars->emplace_back(new VariableInfo(nm, nmtex, rb, bing, n));\n\n}\n", "file_path": "src/Variables.cpp", "rank": 84, "score": 25.911130429672067 }, { "content": "#include \"ExamplesInclude.h\"\n\n\n\n#include \"Config.h\"\n\n#include \"Utils.h\"\n\n#include \"CompTool.h\"\n\n#include \"SystCompTool.h\"\n\n#include \"AutoBinningTool.h\"\n\n\n\n#include \"TFile.h\"\n\n#include \"TH1.h\"\n\n\n\n#include <iostream>\n\n\n\nusing std::cout; \n\nusing std::endl;\n\nusing std::clog;\n\nusing BU = BinningUtils;\n\n\n\n/**\n\n * @brief hadhad chanel ttbar on the fly weights\n", "file_path": "examples/Example_ttbarOTF.cpp", "rank": 85, "score": 25.864862012234383 }, { "content": "#include \"ExamplesInclude.h\"\n\n\n\n#include \"Config.h\"\n\n#include \"Utils.h\"\n\n#include \"CompTool.h\"\n\n#include \"SystCompTool.h\"\n\n#include \"AutoBinningTool.h\"\n\n\n\n#include \"TFile.h\"\n\n#include \"TH1.h\"\n\n\n\n#include <iostream>\n\n\n\nusing std::cout; \n\nusing std::endl;\n\nusing std::clog;\n\nusing BU = BinningUtils;\n\n\n\n/**\n\n * @brief Single top Wt-channel on the fly weights\n", "file_path": "examples/Example_WtOTF.cpp", "rank": 86, "score": 25.776413559217627 }, { "content": "#include \"Utils_WS.h\"\n\n#include \"Utils.h\"\n\n\n\nusing std::string;\n\nusing std::map;\n\nusing std::set;\n\nusing std::pair;\n\nusing std::tuple;\n\nusing std::cout;\n\nusing std::clog;\n\nusing std::cerr;\n\nusing std::endl;\n\nusing std::for_each;\n\nusing std::thread;\n\nusing std::mutex;\n\nusing std::lock_guard;\n\nusing std::ifstream;\n\nusing std::istringstream;\n\n\n\nusing std::chrono::steady_clock;\n", "file_path": "src/WorkSpace.h", "rank": 87, "score": 25.36266963111925 }, { "content": "#include \"ExamplesInclude_WS.h\"\n\n\n\n#include \"PullsTool.h\"\n\n#include <iostream>\n\n\n\nusing namespace std;\n\n\n\nint test_pulls(const std::string& filename, const std::string& outname)\n\n{\n\n WorkspaceInfo* info = new WorkspaceInfo();\n\n info->path = filename;\n\n info->workspace_name = \"combined\";\n\n // info->workspace_name = \"combWS\";\n\n // info->data_name = \"asimovData_SB_SM\";\n\n info->use_asimov = false;\n\n info->use_oneline_fit = false;\n\n\n\n auto timeStart = steady_clock::now();\n\n\n\n PullsEngine* egn = new PullsEngine(info);\n", "file_path": "examples/Example_Pulls.cpp", "rank": 89, "score": 24.98093680177029 }, { "content": "#include \"ExamplesInclude_WS.h\"\n\n\n\n#include \"RankingTool.h\"\n\n#include <iostream>\n\n\n\nusing namespace std;\n\n\n\nint test_ranking(const std::string& filename, const std::string& outname)\n\n{\n\n WorkspaceInfo* info = new WorkspaceInfo();\n\n info->path = filename;\n\n info->workspace_name = \"combined\";\n\n // info->workspace_name = \"combWS\";\n\n // info->data_name = \"asimovData_SB_SM\";\n\n info->use_asimov = false;\n\n\n\n auto timeStart = steady_clock::now();\n\n\n\n RankingEngine* egn = new RankingEngine(info);\n\n egn->Execute();\n", "file_path": "examples/Example_Ranking.cpp", "rank": 90, "score": 24.65192787936269 }, { "content": "#include \"Utils.h\"\n\n\n\nusing namespace std;\n\n\n\nnamespace Utils\n\n{\n\n\n\nvoid histAssign(TH1* h, ProcessInfo *p, RegionInfo* r, VariableInfo* v)\n\n{\n\n TH1* h_clone = (TH1*)h->Clone();\n\n h_clone->SetDirectory(0);\n\n p->histogram = std::move(h_clone);\n\n p->current_region = r;\n\n p->current_variable = v;\n\n}\n\n\n\nvoid histAssignSyst(TH1* h, ProcessInfo *p, const std::string& systname)\n\n{\n\n TH1* h_clone = (TH1*)h->Clone();\n\n h_clone->SetDirectory(0);\n", "file_path": "src/Utils.cpp", "rank": 91, "score": 24.642353980445698 }, { "content": "#include \"ExamplesInclude_WS.h\"\n\n#include \"TROOT.h\"\n\n\n\n#include <iostream>\n\n\n\nusing namespace std;\n\n\n\nint main(int argc, char *argv[])\n\n{\n\n gROOT->SetBatch(1);\n\n\n\n if (argc < 3) \n\n {\n\n cerr << \"Usage: run-ranking <input> <output>\\n\";\n\n return 0;\n\n }\n\n\n\n test_ranking(std::string(argv[1]), std::string(argv[2])+\".txt\");\n\n test_ranking_plot(std::string(argv[2])+\".txt\", std::string(argv[2])+\".png\");\n\n}", "file_path": "exec/run_ranking.cpp", "rank": 93, "score": 23.86951882301797 }, { "content": "#include \"ExamplesInclude_WS.h\"\n\n#include \"TROOT.h\"\n\n\n\n#include <iostream>\n\n\n\nusing namespace std;\n\n\n\nint main(int argc, char *argv[])\n\n{\n\n gROOT->SetBatch(1);\n\n\n\n if (argc < 3) \n\n {\n\n cerr << \"Usage: run-pulls <input> <output>\\n\";\n\n return 0;\n\n }\n\n\n\n test_pulls(std::string(argv[1]), std::string(argv[2])+\".txt\");\n\n test_pulls_plot(std::string(argv[2])+\".txt\", std::string(argv[2])+\".png\");\n\n}", "file_path": "exec/run_pulls.cpp", "rank": 94, "score": 23.86951882301797 }, { "content": "\n\n for (size_t i = 0; i < m_info->n_bins; ++i)\n\n {\n\n x[i] = double(i+1) / (double)m_info->n_bins;\n\n }\n\n\n\n vector<ProcessInfo*>* ps = c->processes->content();\n\n auto it = std::find_if(ps->begin(), ps->end(), [this](ProcessInfo* p) { return p->process == m_proc; });\n\n TH1* h = (*it)->histogram;\n\n if (!h)\n\n {\n\n clog << \"WARN: reference process not found, will use front\\n\";\n\n h = ps->front()->histogram;\n\n }\n\n else \n\n {\n\n clog << \"INFO: flattening based on \" << static_cast<int>(m_proc) << '\\n';\n\n }\n\n\n\n y[0] = h->GetXaxis()->GetBinLowEdge(1);\n", "file_path": "src/AutoBinningTool.cpp", "rank": 95, "score": 23.662696094480523 }, { "content": "#ifndef PROCESSES_H\n\n#define PROCESSES_H\n\n\n\n#include \"Regions.h\"\n\n#include \"Variables.h\"\n\n\n\n#include \"TColor.h\"\n\n#include \"TH1.h\"\n\n\n\n#include <memory>\n\n#include <string>\n\n#include <vector>\n\n#include <map>\n\n\n\nusing std::string;\n\nusing std::vector;\n\nusing std::shared_ptr;\n\n\n\n// ENUMS\n", "file_path": "src/Processes.h", "rank": 96, "score": 23.64130917659333 }, { "content": "#include \"roofitUtils.h\"\n\n\n\n#include <iostream>\n\n#include <vector>\n\n\n\n#include <TMatrixTSym.h>\n\n#include <TVectorT.h>\n\n\n\n#include <RooArgList.h>\n\n#include <RooAbsArg.h>\n\n#include <RooRealVar.h>\n\n#include <RooAbsReal.h>\n\n#include <RooPlot.h>\n\n\n\nnamespace RU {\n\n\n\n Double_t getPropagatedError(RooAbsReal& var, const RooFitResult& fr, const RooArgSet* params, bool linMethod) {\n\n // Calculate error on self by propagated errors on parameters with correlations as given by fit result\n\n // The linearly propagated error is calculated as follows\n\n // T\n", "file_path": "ext/roofitUtils.cpp", "rank": 98, "score": 21.858103372795213 }, { "content": "\n\n for (auto& pp : p->systematic_histograms)\n\n {\n\n pp.second->SetLineWidth(2);\n\n // pp.second->SetLineStyle(2);\n\n pp.second->SetMarkerSize(0);\n\n }\n\n });\n\n}\n\n\n\nvoid CompTool::run(const Config* c) const\n\n{\n\n if (!fs::exists(fs::path(output_path)))\n\n {\n\n throw std::runtime_error(\"Output path does not exist\");\n\n }\n\n \n\n vector<ProcessInfo*>* ps = c->processes->content();\n\n\n\n gROOT->SetStyle(\"ATLAS\");\n", "file_path": "src/CompTool.cpp", "rank": 99, "score": 21.40323259078264 } ]
C++
src/GRCPrinter.cpp
dilawar/cec-esteral
c21ed6dea7392a3c4553d304eeeaaee188a6f567
#include "GRCPrinter.hpp" #include <cassert> namespace GRCDot { void GRCDP::visit_cfg(GRCNode *n) { assert(n); if (reached.find(n) == reached.end()) { reached.insert(n); assert(cfgnum.find(n) != cfgnum.end()); mynum = cfgnum[n]; o << 'n' << mynum << ' '; n->welcome(*this); for (vector<GRCNode *>::const_iterator k = n->dataPredecessors.begin() ; k != n->dataPredecessors.end() ; k++) { assert(cfgnum.find(*k) != cfgnum.end()); o << 'n' << cfgnum[*k] << " -> n" << cfgnum[n]; if (clean) o << " [color=red]\n"; else o << " [color=red constraint=false]\n"; } for ( vector<GRCNode*>::iterator j = n->successors.begin() ; j != n->successors.end() ; j++ ) { if (*j) { o << 'n' << cfgnum[n] << " -> n" << cfgnum[*j]; if ( n->successors.size() > 1) { if (clean) { if (dynamic_cast<Switch*>(n) != NULL || dynamic_cast<Sync*>(n) != NULL) o << " [label=\"" << j - n->successors.begin() << "\"]"; else if (dynamic_cast<Test*>(n) != NULL && j == n->successors.end() - 1) o << " [label=\"P\"]"; } else { o << " [label=\"" << j - n->successors.begin() << "\"]"; } } o << '\n'; } else if (!clean) { o << 'n'<< cfgnum[n] << " -> n" << nextnum << "[label=\"" << j-n->successors.begin() << "\"]" << '\n'; o << 'n' << nextnum++ << " [shape=octagon style=filled color=black]\n"; } } for ( vector<GRCNode*>::iterator j = n->successors.begin() ; j != n->successors.end() ; j++ ) if (*j) visit_cfg(*j); for ( vector<GRCNode*>::iterator j = n->predecessors.begin() ; j != n->predecessors.end() ; j++ ) visit_cfg(*j); for ( vector<GRCNode*>::iterator j = n->dataSuccessors.begin() ; j != n->dataSuccessors.end() ; j++ ) visit_cfg(*j); for ( vector<GRCNode*>::iterator j = n->dataPredecessors.begin() ; j != n->dataPredecessors.end() ; j++ ) visit_cfg(*j); } } Status GRCDP::visit(Switch &s) { if (clean) { o << "[label=\"s" << stnum[s.st] << "\" shape=diamond peripheries=2]\n"; o << "{ rank=same n" << mynum << " n" << stnum[s.st] << " }\n"; } else { o << "[label=\"" << mynum << " switch "; o << stnum[s.st] << "\" shape=diamond color=pink style=filled]\n"; drawSTlink(&s,s.st); } return Status(); } Status GRCDP::visit(Test &s) { o << "[label=\""; if (!clean) o << mynum << " test "; s.predicate->welcome(ep); o << "\" shape=diamond]\n"; return Status(); } Status GRCDP::visit(STSuspend &s){ o << "[label=\""; if (!clean) o << mynum << " Suspend "; o << stnum[s.st] << "\" shape=egg]\n"; return Status(); } Status GRCDP::visit(Terminate &s) { if (clean) { o << "[label=\"" << s.code << "\" shape=octagon]\n"; } else { o << "[label=\"" << mynum << ' ' << s.index << '@' << s.code << "\" shape=octagon color=red style=filled " "fontcolor=white fontname=\"Times-Bold\"]\n"; } return Status(); } Status GRCDP::visit(Sync &s) { o << "[label=\""; if (!clean) o << mynum << " sync" << " " << stnum[s.st]; o << "\" shape=invtriangle]\n"; o << "{ rank=same; "; for ( vector<GRCNode*>::iterator i = s.predecessors.begin() ; i != s.predecessors.end() ; i++ ) o << 'n' << cfgnum[*i] << "; "; o << "}\n"; return Status(); } Status GRCDP::visit(Fork &s) { o << "[label=\""; if (!clean) o << mynum << " fork"; o << "\" shape=triangle]\n"; return Status(); } Status GRCDP::visit(Action &s) { o << "[label=\""; if (!clean) o << mynum << " action "; s.body->welcome(ep); o << '\"'; if (dynamic_cast<Emit*>(s.body)) o << " shape=house orientation=270]\n"; else o << " shape=box]\n"; return Status(); } Status GRCDP::visit(Enter &s) { if (clean) { STNode *n = s.st; STNode *parent = NULL; STexcl *exclusive = NULL; for (;;) { parent = n->parent; exclusive = dynamic_cast<STexcl*>(parent); if ( exclusive != NULL ) break; n = parent; } vector<STNode*>::iterator i = exclusive->children.begin(); while (*i != n && i != exclusive->children.end()) i++; int childnum = i - exclusive->children.begin(); o << "[label=\"s" << stnum[parent] << '=' << childnum << "\" shape=box]\n"; } else { o << "[label=\"" << mynum << " enter " << stnum[s.st] << "\" shape=house color=palegreen1 style=filled]\n"; } return Status(); } Status GRCDP::visit(EnterGRC &s){ o << "[label=\""; if (!clean) o << mynum << " EnterGRC"; o << "\"]\n"; return Status(); } Status GRCDP::visit(ExitGRC &s){ o << "[label=\""; if (!clean) o << mynum << " ExitGRC"; o << "\"]\n"; return Status(); } Status GRCDP::visit(Nop &s){ o << "[label=\""; if (!clean) o << mynum << " "; if (s.isflowin()) o << "*"; else if (s.isshortcut()) o << "#"; else o << "\\n" << s.code; o << "\" shape=circle]\n"; return Status(); } Status GRCDP::visit(DefineSignal &s){ o << "[label=\""; if (!clean) o << mynum << " DefS\\n"; o << s.signal->name << "\" shape=house orientation=90]\n"; return Status(); } void GRCDP::visit_st(STNode *n) { assert(n); mynum = stnum[n]; o << 'n' << mynum << ' '; n->welcome(*this); for ( vector<STNode*>::const_iterator i = n->children.begin() ; i != n->children.end() ; i++ ) if (*i) { visit_st(*i); o << 'n' << stnum[n] << " -> n" << stnum[*i]; if (!clean || dynamic_cast<STexcl*>(n) != NULL) o << " [label=\"" << (i - n->children.begin()) << "\"]"; o << '\n'; } else { o << 'n'<< stnum[n] << " -> n" << nextnum << "[label=\"" << i - n->children.begin() << "\"]"<<'\n'; o << 'n' << nextnum++; if (clean) o << " [shape=point]\n"; else o << " [shape=octagon style=filled color=black]\n"; } } Status GRCDP::visit(STexcl &s) { if (clean) { o << "[label=\"s" << mynum << "\" shape=diamond peripheries=2]\n"; } else { o << "[label=\"" << mynum << "\" shape=diamond color=pink style=filled]\n"; } return Status(); } Status GRCDP::visit(STref &s) { if (clean) { o << "[shape=box label=\"\"]\n"; } else { o << "[label=\"" << mynum << " "; if(s.isabort()) o << "A"; if(s.issuspend()) o << "S"; o << "\" ]\n"; } return Status(); } Status GRCDP::visit(STpar &s) { if (clean) { o << "[label=\"\" shape=triangle]\n"; } else { o << "[label=\"" << mynum << "\" shape=triangle]\n"; } return Status(); } Status GRCDP::visit(STleaf &s) { if (clean) { o << "[label=\""; if(s.isfinal()) o << "*"; o << "\" shape=box]\n"; } else { o << "[label=\"" << mynum << " "; if(s.isfinal()) o << "*"; o << "\" shape=box]\n"; } return Status(); } void drawDot(std::ostream &o, GRCgraph *g, Module *m, bool drawstlink, bool clean, CFGmap &cfgmap, STmap &stmap, int mxnode) { GRCDP visitor(o, cfgmap, stmap, mxnode+1); visitor.drawstlink = drawstlink; visitor.clean = clean; o << "digraph " << m->symbol->name << " {" << std::endl; o << "size=\"7.5,10\"\n"; visitor.visit_st(g->selection_tree); visitor.visit_cfg(g->control_flow_graph); o << "}" << std::endl; } int GRCDot(std::ostream &o, GRCgraph *g, Module *m, bool drawstlink, bool clean, CFGmap &cfgmap, STmap &stmap, int mxnode) { assert(g); assert(m); assert(m->symbol); mxnode = g->enumerate(cfgmap, stmap, mxnode); drawDot(o, g, m, drawstlink, clean, cfgmap, stmap, mxnode); return mxnode; } void GRCDot(std::ostream &o, GRCgraph *g, Module *m, bool drawstlink, bool clean) { assert(g); assert(m); assert(m->symbol); CFGmap cfgmap; STmap stmap; int mxnode = g->enumerate(cfgmap, stmap); drawDot(o, g, m, drawstlink, clean, cfgmap, stmap, mxnode); } void GRCDP::drawSTlink(GRCNode *g, STNode *s) { o << "{ rank=same; n" << cfgnum[g] << "; n" << stnum[s] << " }\n"; if (!drawstlink) return; assert( stnum.find(s) != stnum.end() ); o << 'n' << cfgnum[g] << " -> n" << stnum[s]; o << "[color=blue constraint=false]"; o << '\n'; } }
#include "GRCPrinter.hpp" #include <cassert> namespace GRCDot { void GRCDP::visit_cfg(GRCNode *n) { assert(n); if (reached.find(n) == reached.end()) { reached.insert(n); assert(cfgnum.find(n) != cfgnum.end()); mynum = cfgnum[n]; o << 'n' << mynum << ' '; n->welcome(*this); for (vector<GRCNode *>::const_iterator k = n->dataPredecessors.begin() ; k != n->dataPredecessors.end() ; k++) { assert(cfgnum.find(*k) != cfgnum.end()); o << 'n' << cfgnum[*k] << " -> n" << cfgnum[n]; if (clean) o << " [color=red]\n"; else o << " [color=red constraint=false]\n"; } for ( vector<GRCNode*>::iterator j = n->successors.begin() ; j != n->successors.end() ; j++ ) { if (*j) { o << 'n' << cfgnum[n] << " -> n" << cfgnum[*j]; if ( n->successors.size() > 1) { if (clean) { if (dynamic_cast<Switch*>(n) != NULL || dynamic_cast<Sync*>(n) != NULL) o << " [label=\"" << j - n->successors.begin() << "\"]"; else if (dynamic_cast<Test*>(n) != NULL && j == n->successors.end() - 1) o << " [label=\"P\"]"; } else { o << " [label=\"" << j - n->successors.begin() << "\"]"; } } o << '\n'; } else if (!clean) { o << 'n'<< cfgnum[n] << " -> n" << nextnum << "[label=\"" << j-n->successors.begin() << "\"]" << '\n'; o << 'n' << nextnum++ << " [shape=octagon style=filled color=black]\n"; } } for ( vector<GRCNode*>::iterator j = n->successors.begin() ; j != n->successors.end() ; j++ ) if (*j) visit_cfg(*j); for ( vector<GRCNode*>::iterator j = n->predecessors.begin() ; j != n->predecessors.end() ; j++ ) visit_cfg(*j); for ( vector<GRCNode*>::iterator j = n->dataSuccessors.begin() ; j != n->dataSuccessors.end() ; j++ ) visit_cfg(*j); for ( vector<GRCNode*>::iterator j = n->dataPredecessors.begin() ; j != n->dataPredecessors.end() ; j++ ) visit_cfg(*j); } } Status GRCDP::visit(Switch &s) { if (clean) { o << "[label=\"s" << stnum[s.st] << "\" shape=diamond peripheries=2]\n"; o << "{ rank=same n" << mynum << " n" << stnum[s.st] << " }\n"; } else { o << "[label=\"" << mynum << " switch "; o << stnum[s.st] << "\" shape=diamond color=pink style=filled]\n"; drawSTlink(&s,s.st); } return Status(); } Status GRCDP::visit(Test &s) { o << "[label=\""; if (!clean) o << mynum << " test "; s.predicate->welcome(ep); o << "\" shape=diamond]\n"; return Status(); } Status GRCDP::visit(STSuspend &s){ o << "[label=\""; if (!clean) o << mynum << " Suspend "; o << stnum[s.st] << "\" shape=egg]\n"; return Status(); } Status GRCDP::visit(Terminate &s) { if (clean) { o << "[label=\"" << s.code << "\" shape=octagon]\n"; } else { o << "[label=\"" << mynum << ' ' << s.index << '@' << s.code << "\" shape=octagon color=red style=filled " "fontcolor=white fontname=\"Times-Bold\"]\n"; } return Status(); } Status GRCDP::visit(Sync &s) { o << "[label=\""; if (!clean) o << mynum << " sync" << " " << stnum[s.st]; o << "\" shape=invtriangle]\n"; o << "{ rank=same; "; for ( vector<GRCNode*>::iterator i = s.predecessors.begin() ; i != s.predecessors.end() ; i++ ) o << 'n' << cfgnum[*i] << "; "; o << "}\n"; return Status(); } Status GRCDP::visit(Fork &s) { o << "[label=\""; if (!clean) o << mynum << " fork"; o << "\" shape=triangle]\n"; return Status(); } Status GRCDP::visit(Action &s) { o << "[label=\""; if (!clean) o << mynum << " action "; s.body->welcome(ep); o << '\"'; if (dynamic_cast<Emit*>(s.body)) o << " shape=house orientation=270]\n"; else o << " shape=box]\n"; return Status(); } Status GRCDP::visit(Enter &s) { if (clean) { STNode *n = s.st; STNode *parent = NULL; STexcl *exclusive = NULL; for (;;) { parent = n->parent; exclusive = dynamic_cast<STexcl*>(parent); if ( exclusive != NULL ) break; n = parent; } vector<STNode*>::iterator i = exclusive->children.begin(); while (*i != n && i != exclusive->children.end()) i++; int childnum = i - exclusive->children.begin(); o << "[label=\"s" << stnum[parent] << '=' << childnum << "\" shape=box]\n"; } else { o << "[label=\"" << mynum << " enter " << stnum[s.st] << "\" shape=house color=palegreen1 style=filled]\n"; } return Status(); } Status GRCDP::visit(EnterGRC &s){ o << "[label=\""; if (!clean) o << mynum << " EnterGRC"; o << "\"]\n"; return Status(); } Status GRCDP::visit(ExitGRC &s){ o << "[label=\""; if (!clean) o << mynum << " ExitGRC"; o << "\"]\n"; return Status(); }
Status GRCDP::visit(DefineSignal &s){ o << "[label=\""; if (!clean) o << mynum << " DefS\\n"; o << s.signal->name << "\" shape=house orientation=90]\n"; return Status(); } void GRCDP::visit_st(STNode *n) { assert(n); mynum = stnum[n]; o << 'n' << mynum << ' '; n->welcome(*this); for ( vector<STNode*>::const_iterator i = n->children.begin() ; i != n->children.end() ; i++ ) if (*i) { visit_st(*i); o << 'n' << stnum[n] << " -> n" << stnum[*i]; if (!clean || dynamic_cast<STexcl*>(n) != NULL) o << " [label=\"" << (i - n->children.begin()) << "\"]"; o << '\n'; } else { o << 'n'<< stnum[n] << " -> n" << nextnum << "[label=\"" << i - n->children.begin() << "\"]"<<'\n'; o << 'n' << nextnum++; if (clean) o << " [shape=point]\n"; else o << " [shape=octagon style=filled color=black]\n"; } } Status GRCDP::visit(STexcl &s) { if (clean) { o << "[label=\"s" << mynum << "\" shape=diamond peripheries=2]\n"; } else { o << "[label=\"" << mynum << "\" shape=diamond color=pink style=filled]\n"; } return Status(); } Status GRCDP::visit(STref &s) { if (clean) { o << "[shape=box label=\"\"]\n"; } else { o << "[label=\"" << mynum << " "; if(s.isabort()) o << "A"; if(s.issuspend()) o << "S"; o << "\" ]\n"; } return Status(); } Status GRCDP::visit(STpar &s) { if (clean) { o << "[label=\"\" shape=triangle]\n"; } else { o << "[label=\"" << mynum << "\" shape=triangle]\n"; } return Status(); } Status GRCDP::visit(STleaf &s) { if (clean) { o << "[label=\""; if(s.isfinal()) o << "*"; o << "\" shape=box]\n"; } else { o << "[label=\"" << mynum << " "; if(s.isfinal()) o << "*"; o << "\" shape=box]\n"; } return Status(); } void drawDot(std::ostream &o, GRCgraph *g, Module *m, bool drawstlink, bool clean, CFGmap &cfgmap, STmap &stmap, int mxnode) { GRCDP visitor(o, cfgmap, stmap, mxnode+1); visitor.drawstlink = drawstlink; visitor.clean = clean; o << "digraph " << m->symbol->name << " {" << std::endl; o << "size=\"7.5,10\"\n"; visitor.visit_st(g->selection_tree); visitor.visit_cfg(g->control_flow_graph); o << "}" << std::endl; } int GRCDot(std::ostream &o, GRCgraph *g, Module *m, bool drawstlink, bool clean, CFGmap &cfgmap, STmap &stmap, int mxnode) { assert(g); assert(m); assert(m->symbol); mxnode = g->enumerate(cfgmap, stmap, mxnode); drawDot(o, g, m, drawstlink, clean, cfgmap, stmap, mxnode); return mxnode; } void GRCDot(std::ostream &o, GRCgraph *g, Module *m, bool drawstlink, bool clean) { assert(g); assert(m); assert(m->symbol); CFGmap cfgmap; STmap stmap; int mxnode = g->enumerate(cfgmap, stmap); drawDot(o, g, m, drawstlink, clean, cfgmap, stmap, mxnode); } void GRCDP::drawSTlink(GRCNode *g, STNode *s) { o << "{ rank=same; n" << cfgnum[g] << "; n" << stnum[s] << " }\n"; if (!drawstlink) return; assert( stnum.find(s) != stnum.end() ); o << 'n' << cfgnum[g] << " -> n" << stnum[s]; o << "[color=blue constraint=false]"; o << '\n'; } }
Status GRCDP::visit(Nop &s){ o << "[label=\""; if (!clean) o << mynum << " "; if (s.isflowin()) o << "*"; else if (s.isshortcut()) o << "#"; else o << "\\n" << s.code; o << "\" shape=circle]\n"; return Status(); }
function_block-function_prefix_line
[ { "content": " class Sync;\n", "file_path": "src/AST.hpp", "rank": 0, "score": 85744.66952829852 }, { "content": " class Fork;\n", "file_path": "src/AST.hpp", "rank": 1, "score": 85739.77028225773 }, { "content": " class Action;\n", "file_path": "src/AST.hpp", "rank": 2, "score": 85739.77028225773 }, { "content": " class Switch;\n", "file_path": "src/AST.hpp", "rank": 3, "score": 85739.77028225773 }, { "content": " class Suspend;\n", "file_path": "src/AST.hpp", "rank": 4, "score": 85734.99545404635 }, { "content": " class Enter;\n", "file_path": "src/AST.hpp", "rank": 5, "score": 85727.88948193603 }, { "content": " class Test;\n", "file_path": "src/AST.hpp", "rank": 6, "score": 85428.86303776244 }, { "content": " class EnterGRC;\n", "file_path": "src/AST.hpp", "rank": 7, "score": 83711.12162244249 }, { "content": " class Sync : public GRCSTNode {\n\n \n\n IRCLASSDEFS;\n\n public:\n\n Status welcome(Visitor&);\n\n \n\n void read(XMListream &);\n\n void write(XMLostream &) const;\n\n Sync() {}\n\n\n\n \n\n Sync(STNode *s) : GRCSTNode(s) {}\n\n };\n\n\n\n\n", "file_path": "src/AST.hpp", "rank": 8, "score": 73654.12735856551 }, { "content": " class Fork : public GRCNode {\n\n \n\n IRCLASSDEFS;\n\n public:\n\n Status welcome(Visitor&);\n\n \n\n void read(XMListream &);\n\n void write(XMLostream &) const;\n\n \n\n Sync* sync;\n\n\n\n Fork() : sync(0) {}\n\n Fork(Sync* sync) : sync(sync) {}\n\n };\n\n\n\n\n", "file_path": "src/AST.hpp", "rank": 9, "score": 73649.81269385472 }, { "content": " class Action : public GRCNode {\n\n \n\n IRCLASSDEFS;\n\n public:\n\n Status welcome(Visitor&);\n\n \n\n void read(XMListream &);\n\n void write(XMLostream &) const;\n\n Action() {}\n\n\n\n Statement *body;\n\n\n\n Action(Statement *s) : body(s) {}\n\n };\n\n\n\n\n", "file_path": "src/AST.hpp", "rank": 10, "score": 73649.81269385472 }, { "content": " class Switch : public GRCSTNode {\n\n \n\n IRCLASSDEFS;\n\n public:\n\n Status welcome(Visitor&);\n\n \n\n void read(XMListream &);\n\n void write(XMLostream &) const;\n\n Switch() {}\n\n\n\n\n\n Switch(STNode *s) : GRCSTNode(s) {}\n\n };\n\n\n\n\n", "file_path": "src/AST.hpp", "rank": 11, "score": 73649.81269385472 }, { "content": " class Suspend : public PredicatedStatement {\n\n \n\n IRCLASSDEFS;\n\n public:\n\n Status welcome(Visitor&);\n\n \n\n void read(XMListream &);\n\n void write(XMLostream &) const;\n\n Suspend() {}\n\n\n\n\n\n Suspend(Statement *s, Expression *e) : PredicatedStatement(s, e) {}\n\n };\n\n\n\n\n", "file_path": "src/AST.hpp", "rank": 12, "score": 73645.60760135434 }, { "content": " class Enter : public GRCSTNode {\n\n \n\n IRCLASSDEFS;\n\n public:\n\n Status welcome(Visitor&);\n\n \n\n void read(XMListream &);\n\n void write(XMLostream &) const;\n\n Enter() {}\n\n\n\n\n\n Enter(STNode *s) : GRCSTNode(s) {}\n\n };\n\n\n\n\n", "file_path": "src/AST.hpp", "rank": 13, "score": 73639.34951861159 }, { "content": " class Test : public GRCSTNode {\n\n \n\n IRCLASSDEFS;\n\n public:\n\n Status welcome(Visitor&);\n\n \n\n void read(XMListream &);\n\n void write(XMLostream &) const;\n\n Test() {}\n\n\n\n Expression *predicate;\n\n \n\n Test(STNode *s, Expression *e) : GRCSTNode(s), predicate(e) {}\n\n };\n\n\n\n\n", "file_path": "src/AST.hpp", "rank": 14, "score": 73376.00311070954 }, { "content": " class EnterGRC : public GRCNode {\n\n \n\n IRCLASSDEFS;\n\n public:\n\n Status welcome(Visitor&);\n\n \n\n void read(XMListream &);\n\n void write(XMLostream &) const;\n\n EnterGRC() {}\n\n\n\n\n\n };\n\n\n\n\n", "file_path": "src/AST.hpp", "rank": 15, "score": 72067.04555697774 }, { "content": " class STexcl : public STNode {\n\n \n\n IRCLASSDEFS;\n\n public:\n\n Status welcome(Visitor&);\n\n \n\n void read(XMListream &);\n\n void write(XMLostream &) const;\n\n STexcl() {}\n\n\n\n\n\n };\n\n\n\n\n", "file_path": "src/AST.hpp", "rank": 16, "score": 65034.25694132614 }, { "content": "ALARM_TIME_TYPE at; {\n", "file_path": "tests/test-ww.h", "rank": 17, "score": 53579.716570818746 }, { "content": "#define B 5\n", "file_path": "tests/test-signal6.h", "rank": 18, "score": 52217.361359498806 }, { "content": "void p3(integer *a, boolean *b, string c) { }\n", "file_path": "tests/test-run19.h", "rank": 19, "score": 52217.361359498806 }, { "content": "static short monthlength [] = {2, 2};\n", "file_path": "tests/test-ww.h", "rank": 20, "score": 52217.361359498806 }, { "content": "boolean calc_and (boolean a, boolean b);\n", "file_path": "tests/test-counter16b.h", "rank": 21, "score": 52217.361359498806 }, { "content": "void p1() { }\n", "file_path": "tests/test-run20.h", "rank": 22, "score": 52217.361359498806 }, { "content": "integer f3(integer a, integer b) { return a + b; }\n", "file_path": "tests/test-run19.h", "rank": 23, "score": 52217.361359498806 }, { "content": " char seconds [3];\n", "file_path": "tests/test-ww.h", "rank": 24, "score": 52217.361359498806 }, { "content": " char minutes[3];\n", "file_path": "tests/test-ww.h", "rank": 25, "score": 52217.361359498806 }, { "content": "extern int bits;\n", "file_path": "tests/test-counter16a.h", "rank": 26, "score": 52217.361359498806 }, { "content": "typedef struct {int hundredths;\n", "file_path": "tests/test-ww.h", "rank": 27, "score": 52217.361359498806 }, { "content": "boolean calc_or (boolean a, boolean b);\n", "file_path": "tests/test-counter16d.h", "rank": 28, "score": 52217.361359498806 }, { "content": "extern int bits;\n", "file_path": "tests/test-counter16.h", "rank": 29, "score": 52217.361359498806 }, { "content": " char sep[2];\n", "file_path": "tests/test-ww.h", "rank": 30, "score": 52217.361359498806 }, { "content": " char snd[3];} MINI_DISPLAY_TYPE;\n", "file_path": "tests/test-ww.h", "rank": 31, "score": 52217.361359498806 }, { "content": " } else strcpy(maindt.timemode,\"24H\");\n", "file_path": "tests/test-ww.h", "rank": 32, "score": 52217.361359498806 }, { "content": "WATCH_TIME_TYPE wt; {\n", "file_path": "tests/test-ww.h", "rank": 33, "score": 52217.361359498806 }, { "content": "integer f2(integer a) { return a + 1; }\n", "file_path": "tests/test-run19.h", "rank": 34, "score": 52217.361359498806 }, { "content": "boolean calc_not (boolean value);\n", "file_path": "tests/test-counter16.h", "rank": 35, "score": 52217.361359498806 }, { "content": "boolean calc_or (boolean a, boolean b);\n", "file_path": "tests/test-counter16.h", "rank": 36, "score": 52217.361359498806 }, { "content": "boolean calc_not (boolean value);\n", "file_path": "tests/test-counter16a.h", "rank": 37, "score": 52217.361359498806 }, { "content": "ALARM_TIME_POSITION atp; {\n", "file_path": "tests/test-ww.h", "rank": 38, "score": 52217.361359498806 }, { "content": "extern int bits;\n", "file_path": "tests/test-counter16d.h", "rank": 39, "score": 52217.361359498806 }, { "content": "boolean calc_or (boolean a, boolean b);\n", "file_path": "tests/test-counter16b.h", "rank": 40, "score": 52217.361359498806 }, { "content": "boolean calc_and (boolean a, boolean b);\n", "file_path": "tests/test-counter16a.h", "rank": 41, "score": 52217.361359498806 }, { "content": "integer f1() { return 0; }\n", "file_path": "tests/test-run19.h", "rank": 42, "score": 52217.361359498806 }, { "content": " int month;\n", "file_path": "tests/test-ww.h", "rank": 43, "score": 52217.361359498806 }, { "content": " int mode12h;} ALARM_TIME_TYPE;\n", "file_path": "tests/test-ww.h", "rank": 44, "score": 52217.361359498806 }, { "content": "boolean calc_and (boolean a, boolean b);\n", "file_path": "tests/test-counter16.h", "rank": 45, "score": 52217.361359498806 }, { "content": " char timemode[4];} MAIN_DISPLAY_TYPE;\n", "file_path": "tests/test-ww.h", "rank": 46, "score": 52217.361359498806 }, { "content": "void p1() { }\n", "file_path": "tests/test-run19.h", "rank": 47, "score": 52217.361359498806 }, { "content": "#define c1 8\n", "file_path": "tests/test-run8.h", "rank": 48, "score": 52217.361359498806 }, { "content": "#define cc 5\n", "file_path": "tests/test-run9.h", "rank": 49, "score": 52217.361359498806 }, { "content": "#define C 10\n", "file_path": "tests/test-signal6.h", "rank": 50, "score": 52217.361359498806 }, { "content": " int day;\n", "file_path": "tests/test-ww.h", "rank": 51, "score": 52217.361359498806 }, { "content": "boolean calc_not (boolean value);\n", "file_path": "tests/test-counter16d.h", "rank": 52, "score": 52217.361359498806 }, { "content": "void p5(integer *a, string c) { }\n", "file_path": "tests/test-run19.h", "rank": 53, "score": 52217.361359498806 }, { "content": "typedef struct {char fst[3];\n", "file_path": "tests/test-ww.h", "rank": 54, "score": 52217.361359498806 }, { "content": "void p2(integer *a, boolean b) { *a += b ? 1 : 0; }\n", "file_path": "tests/test-run19.h", "rank": 55, "score": 52217.361359498806 }, { "content": "#define c2 3\n", "file_path": "tests/test-run8.h", "rank": 56, "score": 52217.361359498806 }, { "content": "boolean calc_or (boolean a, boolean b);\n", "file_path": "tests/test-counter16a.h", "rank": 57, "score": 52217.361359498806 }, { "content": "integer f1(integer a) { return a + 5; }\n", "file_path": "tests/test-run20.h", "rank": 58, "score": 52217.361359498806 }, { "content": "typedef struct {char hours[3]; \n", "file_path": "tests/test-ww.h", "rank": 59, "score": 52217.361359498806 }, { "content": "boolean calc_not (boolean value);\n", "file_path": "tests/test-counter16b.h", "rank": 60, "score": 52217.361359498806 }, { "content": "extern int bits;\n", "file_path": "tests/test-counter16b.h", "rank": 61, "score": 52217.361359498806 }, { "content": "STOPWATCH_TIME_TYPE st; {\n", "file_path": "tests/test-ww.h", "rank": 62, "score": 52217.361359498806 }, { "content": "boolean calc_and (boolean a, boolean b);\n", "file_path": "tests/test-counter16d.h", "rank": 63, "score": 52217.361359498806 }, { "content": "WATCH_TIME_POSITION wtp; {\n", "file_path": "tests/test-ww.h", "rank": 64, "score": 52217.361359498806 }, { "content": "extern char iterate_flag;\n", "file_path": "tests/test-counter16d.h", "rank": 65, "score": 50922.56864306149 }, { "content": "#define MOTOR_FWD 0\n", "file_path": "tests/test-lego2.h", "rank": 66, "score": 50922.56864306149 }, { "content": "#define MOTOR_REV 1\n", "file_path": "tests/test-lego4.h", "rank": 67, "score": 50922.56864306149 }, { "content": "extern char iterate_flag;\n", "file_path": "tests/test-counter16.h", "rank": 68, "score": 50922.56864306149 }, { "content": "#define MOTOR_REV 1\n", "file_path": "tests/test-lego3.h", "rank": 69, "score": 50922.56864306149 }, { "content": "extern char iterate_flag;\n", "file_path": "tests/test-counter16b.h", "rank": 70, "score": 50922.56864306149 }, { "content": "#define MOTOR_FWD 0\n", "file_path": "tests/test-lego4.h", "rank": 71, "score": 50922.56864306149 }, { "content": "#define MAX_SPEED 255\n", "file_path": "tests/test-lego2.h", "rank": 72, "score": 50922.56864306149 }, { "content": "#define MOTOR_REV 1\n", "file_path": "tests/test-lego2.h", "rank": 73, "score": 50922.56864306149 }, { "content": "#define MAX_SPEED 255\n", "file_path": "tests/test-lego1.h", "rank": 74, "score": 50922.56864306149 }, { "content": "#define MOTOR_FWD 0\n", "file_path": "tests/test-lego1.h", "rank": 75, "score": 50922.56864306149 }, { "content": "#define MOTOR_FWD 0\n", "file_path": "tests/test-lego3.h", "rank": 76, "score": 50922.56864306149 }, { "content": "#define MAX_SPEED 255\n", "file_path": "tests/test-lego4.h", "rank": 77, "score": 50922.56864306149 }, { "content": "#define MOTOR_REV 1\n", "file_path": "tests/test-lego1.h", "rank": 78, "score": 50922.56864306149 }, { "content": "void PrintFU(string s, integer v)\n\n{\n\n printf(\"%s %d\\n\", s, v);\n", "file_path": "tests/test-andreas2.h", "rank": 79, "score": 50922.56864306149 }, { "content": "extern char iterate_flag;\n", "file_path": "tests/test-counter16a.h", "rank": 80, "score": 50922.56864306149 }, { "content": " return Status();\n\n }\n\n Status GRC2BAL::visit(Switch &s){\n\n currentNode = new MWBNode();\n\n return Status();\n\n }\n\n \n\n Status GRC2BAL::visit(STSuspend &s){\n\n currentNode = new SuspendNode();\n\n return Status();\n\n }\n\n\n\n void GRC2BAL::testForks(){\n\n //test the GRC Forks to see why new ap are made when not necessary\n\n int pos = 0;\n\n for(vector<GRCNode *>::iterator i = schedule.begin(); i != schedule.end();\n\n\ti++){\n\n Fork * f = dynamic_cast<Fork *> (*i);\n\n if(f != NULL){\n\n\tstd::cout<<pos<<\" \"<< tnum[f]<<\"\\t\";\n", "file_path": "src/GRCBAL.cpp", "rank": 84, "score": 27.29965649314471 }, { "content": " bool clean;\n\n\n\n void visit_cfg(GRCNode *);\n\n Status visit(Switch &);\n\n Status visit(Test &);\n\n Status visit(Terminate &);\n\n Status visit(Sync &);\n\n Status visit(Fork &);\n\n Status visit(Action &);\n\n Status visit(Enter &);\n\n Status visit(STSuspend &);\n\n Status visit(EnterGRC &);\n\n Status visit(ExitGRC &);\n\n Status visit(Nop &);\n\n Status visit(DefineSignal &);\n\n void visit_st(STNode *);\n\n Status visit(STexcl &);\n\n Status visit(STref &);\n\n Status visit(STpar &);\n\n Status visit(STleaf &);\n\n\n\n void drawSTlink(GRCNode *, STNode *);\n\n };\n\n};\n\n#endif\n", "file_path": "src/GRCPrinter.hpp", "rank": 85, "score": 27.16565944294156 }, { "content": " : CStatement(node), thenSt(thenSt), elseSt(elseSt) {}\n\n virtual ~CIfElse() { delete thenSt; delete elseSt; }\n\n void print(unsigned int = 0);\n\n };\n\n\n\n struct CGoto : CStatement {\n\n string label;\n\n CGoto(string label) : CStatement(NULL), label(label) {}\n\n void print(unsigned int = 0);\n\n };\n\n\n\n struct CBreak : CStatement {\n\n CBreak() : CStatement(NULL) {}\n\n void print(unsigned int = 0);\n\n };\n\n\n\n struct CSwitch : CStatement {\n\n CStatement *body;\n\n CSwitch(GRCNode *node, CStatement *body) : CStatement(node), body(body) {}\n\n virtual ~CSwitch() { delete body; }\n", "file_path": "src/CPrinter.hpp", "rank": 86, "score": 26.805590121586782 }, { "content": " *stroot >> ex;\n\n *ex >> term >> stnode;\n\n\n\n run_before(surface, new Enter(ex));\n\n\n\n *surface_fork >> surface;\n\n\n\n Switch *sw = new Switch(ex); \n\n *sw >> terminate0 >> depth;\n\n *depth_fork >> sw;\n\n }\n\n\n\n context.pop();\n\n\n\n // Connect the sync to every continuation in the context\n\n\n\n for ( int i = 0 ; i < context.size ; i++ )\n\n *sync >> context(i);\n\n\n\n surface = surface_fork;\n", "file_path": "src/ASTGRC.cpp", "rank": 87, "score": 26.157984642973254 }, { "content": " std::set<STNode *> allst;\n\n\n\n public:\n\n Simulator(GRCgraph &);\n\n Status visit(Switch &);\n\n Status visit(Enter &);\n\n Status visit(Terminate &);\n\n Status visit(Sync &);\n\n Status visit(Fork &);\n\n Status visit(Test &);\n\n Status visit(DefineSignal &);\n\n Status visit(Action &);\n\n Status visit(Nop &);\n\n Status visit(STSuspend &);\n\n Status visit(ExitGRC &) { return Status(); }\n\n void all_dfs(GRCNode *);\n\n void st_walk(STNode *);\n\n virtual ~Simulator() {}\n\n };\n", "file_path": "src/GRCOpt.hpp", "rank": 88, "score": 26.042222408438683 }, { "content": " }\n\n\n\n void ForkNode::printDot(std::ostream &o, int n){\n\n\n\n o << 'n' << n << \" [ shape=triangle label=\\\"p:\"<<n<<\" t:\"<<tnum<<\" Fork\";\n\n for(vector<int>::iterator i = startthreads.begin();\n\n\ti != startthreads.end(); i++)\n\n o << \" \" << (*i);\n\n o << \"\\\" ]\\n\";\n\n\n\n }\n\n void ExitGRCNode::printDot(std::ostream &o, int n){\n\n o << 'n' << n << \" [ shape=ellipse label=\\\"p:\"<<n<<\" t:\"<<tnum<<\" ExitGRCNode\\\" ]\\n\";\n\n }\n\n void EnterGRCNode::printDot(std::ostream &o, int n){\n\n o << 'n' << n << \" [ shape=ellipse label=\\\"p:\"<<n<<\" t:\"<<tnum<<\" EnterGRCNode\\\" ]\\n\";\n\n }\n\n void EnterNode::printDot(std::ostream &o, int n){\n\n o << 'n' << n << \" [ shape=house label=\\\"p:\"<<n<<\" t:\"<<tnum<<\" Enter\\\" ]\\n\";\n\n }\n", "file_path": "src/GRCBAL.cpp", "rank": 89, "score": 25.879510792434573 }, { "content": " }\n\n void ActivePoint::printDot(std::ostream &o, int n){\n\n o << 'n' << n << \" [ shape=point ]\\n\";\n\n }\n\n void TWBNode::printDot(std::ostream &o, int n){\n\n o << 'n' << n << \" [ shape=diamond label=\\\"p:\"<<n<<\" t:\"<<tnum<<\" SigBrch\\\" ]\\n\";\n\n }\n\n void MWBNode::printDot(std::ostream &o, int n){\n\n o << 'n' << n << \" [ shape=diamond peripheries=2 label=\\\"p:\"<<n<<\" t:\"<<tnum<<\" Switch\\\" ]\\n\";\n\n }\n\n void NOPNode::printDot(std::ostream &o, int n){\n\n o << 'n' << n << \" [color=pink style=filled shape=plaintext label=\\\"p:\"<<n<<\" t:\"<<tnum<<\" NOP\\\" ]\\n\";\n\n }\n\n void ActionNode::printDot(std::ostream &o, int n){\n\n o << 'n' << n << \" [ shape=house orientation=270 label=\\\"p:\"<<n<<\" t:\"<<tnum<<\" Action\\\" ]\\n\";\n\n }\n\n void JoinNode::printDot(std::ostream &o, int n){\n\n \n\n o << 'n' << n << \" [ shape=invtriangle label=\\\"p:\"<<n<<\" t:\"<<tnum<<\" Join \";\n\n o << \"\\\" ]\\n\";\n", "file_path": "src/GRCBAL.cpp", "rank": 90, "score": 25.48569260880611 }, { "content": " return newname;\n\n }\n\n Status Printer::visit(Enter &e)\n\n {\n\n STexcl *exclusive = 0;\n\n STNode *n = e.st;\n\n\n\n for (;;) {\n\n assert(n);\n\n\n\n STNode *parent = n->parent;\n\n\n\n // If we hit a parallel first, this Enter is unnecessary; do not generate\n\n // any code\n\n if (dynamic_cast<STpar*>(parent) != NULL) return Status();\n\n\n\n exclusive = dynamic_cast<STexcl*>(parent);\n\n if (exclusive != NULL) break; // found the exclusive node\n\n n = parent;\n\n }\n", "file_path": "src/CPrinter.cpp", "rank": 91, "score": 24.902632048944543 }, { "content": " }\n\n\n\n int TypeCheck(GRCNode *n)\n\n {\n\n assert(n);\n\n if (dynamic_cast<Fork *>(n))\n\n return 1;//fork\n\n if (dynamic_cast<Switch *>(n) ||\n\n\tdynamic_cast<Test *>(n) ||\n\n\tdynamic_cast<Sync *>(n) ||\n\n\tdynamic_cast<EnterGRC *>(n))\n\n return 2;//predicate\n\n assert(n->successors.size() == 0);\n\n return 0; //leave\n\n }\n\n \n\n /***************************************\n\n Functions for Fucing\n\n ****************************************/\n\n\n", "file_path": "src/cec-pdgccfg.cpp", "rank": 94, "score": 23.986516860870147 }, { "content": " {\n\n begin(i);\n\n printer->o << \"goto \" << label << \";\\n\";\n\n }\n\n void CBreak::print(unsigned int i)\n\n {\n\n begin(i);\n\n printer->o << \"break;\\n\";\n\n }\n\n void CSwitch::print(unsigned int i)\n\n {\n\n begin(i);\n\n printer->o << \"switch (\";\n\n printer->printExpr(node);\n\n printer->o << \") {\\n\";\n\n for ( CStatement *st = body ; st ; st = st->next ) st->print(i+1);\n\n indent(i);\n\n printer->o << \"default: break;\\n\";\n\n indent(i);\n\n printer->o << \"}\\n\";\n", "file_path": "src/CPrinter.cpp", "rank": 95, "score": 22.852726511303423 }, { "content": " }\n\n assert(predicate);\n\n\n\n // Machinery for the depth: a test that sends control to either\n\n // an ST suspend node to context(1) (e.g., the suspend condition)\n\n // or the depth of the body\n\n\n\n STSuspend *sts = new STSuspend(stbody);\n\n *sts >> context(1);\n\n Test *t = new Test(stbody, predicate);\n\n *t >> depth >> sts;\n\n depth = t;\n\n run_before(depth, new Enter(stbody));\n\n\n\n if (immediate_test) {\n\n Switch *sw = new Switch(stnode);\n\n *sw >> depth >> immediate_test;\n\n depth = sw;\n\n }\n\n\n", "file_path": "src/ASTGRC.cpp", "rank": 97, "score": 22.70730301777243 }, { "content": "\n\n assert(exclusive != NULL);\n\n\n\n // Locate node n among the children of \"parent\"\n\n\n\n vector<STNode*>::iterator i = exclusive->children.begin();\n\n while (*i != n && i != exclusive->children.end()) i++;\n\n\n\n assert(i != exclusive->children.end());\n\n\n\n int childnum = i - exclusive->children.begin();\n\n \n\n assert(childnum >= 0);\n\n\n\n assert(contains(stateVar, exclusive));\n\n o << stateVar[exclusive] << \" = \" << childnum;\n\n\n\n return Status();\n\n }\n\n Status Printer::visit(Terminate &t)\n", "file_path": "src/CPrinter.cpp", "rank": 98, "score": 22.604452663720316 }, { "content": " Status visit(Test &);\n\n Status visit(Terminate &);\n\n Status visit(Sync &);\n\n Status visit(Fork &);\n\n Status visit(Action &);\n\n\n\n Status visit(STSuspend &);\n\n Status suspend_sm(STSuspend &);\n\n\n\n Status visit(Enter &);\n\n Status enter_sm(Enter &);\n\n\n\n Status visit(LoadSignalExpression &);\n\n Status visit(BinaryOp &);\n\n Status visit(UnaryOp &);\n\n Status visit(Emit &);\n\n Status visit(Exit &);\n\n\n\n Status visit(Literal &);\n\n Status visit(VariableSymbol &s);\n", "file_path": "src/pdg2beeblebrox.hpp", "rank": 99, "score": 22.595090641422495 } ]
C++
src/nlr/LPFormulator.cpp
yuvaljacoby/Marabou-1
553b780ef2e2cfe349b3954adc433a27af37a50f
#include "GurobiWrapper.h" #include "InfeasibleQueryException.h" #include "LPFormulator.h" #include "Layer.h" #include "MStringf.h" #include "NLRError.h" #include "TimeUtils.h" namespace NLR { LPFormulator::LPFormulator( LayerOwner *layerOwner ) : _layerOwner( layerOwner ) , _cutoffInUse( false ) , _cutoffValue( 0 ) { } LPFormulator::~LPFormulator() { } double LPFormulator::solveLPRelaxation( const Map<unsigned, Layer *> &layers, MinOrMax minOrMax, String variableName, unsigned lastLayer ) { GurobiWrapper gurobi; createLPRelaxation( layers, gurobi, lastLayer ); List<GurobiWrapper::Term> terms; terms.append( GurobiWrapper::Term( 1, variableName ) ); if ( minOrMax == MAX ) gurobi.setObjective( terms ); else gurobi.setCost( terms ); gurobi.solve(); if ( gurobi.infeasbile() ) throw InfeasibleQueryException(); if ( !gurobi.optimal() ) throw NLRError( NLRError::UNEXPECTED_RETURN_STATUS_FROM_GUROBI ); Map<String, double> dontCare; double result = 0; gurobi.extractSolution( dontCare, result ); return result; } void LPFormulator::optimizeBoundsWithIncrementalLpRelaxation( const Map<unsigned, Layer *> &layers ) { GurobiWrapper gurobi; List<GurobiWrapper::Term> terms; Map<String, double> dontCare; double lb = 0; double ub = 0; double currentLb = 0; double currentUb = 0; unsigned tighterBoundCounter = 0; unsigned signChanges = 0; unsigned cutoffs = 0; struct timespec gurobiStart; (void) gurobiStart; struct timespec gurobiEnd; (void) gurobiEnd; gurobiStart = TimeUtils::sampleMicro(); for ( unsigned i = 0; i < _layerOwner->getNumberOfLayers(); ++i ) { ASSERT( layers.exists( i ) ); Layer *layer = layers[i]; addLayerToModel( gurobi, layer ); for ( unsigned j = 0; j < layer->getSize(); ++j ) { if ( layer->neuronEliminated( j ) ) continue; currentLb = layer->getLb( j ); currentUb = layer->getUb( j ); if ( _cutoffInUse && ( currentLb > _cutoffValue || currentUb < _cutoffValue ) ) continue; unsigned variable = layer->neuronToVariable( j ); Stringf variableName( "x%u", variable ); terms.clear(); terms.append( GurobiWrapper::Term( 1, variableName ) ); gurobi.reset(); gurobi.setObjective( terms ); gurobi.solve(); if ( gurobi.infeasbile() ) throw InfeasibleQueryException(); if ( !gurobi.optimal() ) throw NLRError( NLRError::UNEXPECTED_RETURN_STATUS_FROM_GUROBI ); gurobi.extractSolution( dontCare, ub ); if ( ub < currentUb ) { gurobi.setUpperBound( variableName, ub ); if ( FloatUtils::isPositive( currentUb ) && !FloatUtils::isPositive( ub ) ) ++signChanges; layer->setUb( j, ub ); _layerOwner->receiveTighterBound( Tightening( variable, ub, Tightening::UB ) ); ++tighterBoundCounter; if ( _cutoffInUse && ub < _cutoffValue ) { ++cutoffs; continue; } } gurobi.reset(); gurobi.setCost( terms ); gurobi.solve(); if ( gurobi.infeasbile() ) throw InfeasibleQueryException(); if ( !gurobi.optimal() ) throw NLRError( NLRError::UNEXPECTED_RETURN_STATUS_FROM_GUROBI ); gurobi.extractSolution( dontCare, lb ); if ( lb > currentLb ) { gurobi.setLowerBound( variableName, lb ); if ( FloatUtils::isNegative( currentLb ) && !FloatUtils::isNegative( lb ) ) ++signChanges; layer->setLb( j, lb ); _layerOwner->receiveTighterBound( Tightening( variable, lb, Tightening::LB ) ); ++tighterBoundCounter; if ( _cutoffInUse && lb > _cutoffValue ) { ++cutoffs; continue; } } } } gurobiEnd = TimeUtils::sampleMicro(); LPFormulator_LOG( Stringf( "Number of tighter bounds found by Gurobi: %u. Sign changes: %u. Cutoffs: %u\n", tighterBoundCounter, signChanges, cutoffs ).ascii() ); LPFormulator_LOG( Stringf( "Seconds spent Gurobiing: %llu\n", TimeUtils::timePassed( gurobiStart, gurobiEnd ) / 1000000 ).ascii() ); } void LPFormulator::optimizeBoundsWithLpRelaxation( const Map<unsigned, Layer *> &layers ) { double lb = FloatUtils::negativeInfinity(); double ub = FloatUtils::infinity(); double currentLb; double currentUb; unsigned tighterBoundCounter = 0; unsigned signChanges = 0; unsigned cutoffs = 0; struct timespec gurobiStart; (void) gurobiStart; struct timespec gurobiEnd; (void) gurobiEnd; gurobiStart = TimeUtils::sampleMicro(); for ( const auto &currentLayer : layers ) { Layer *layer = currentLayer.second; for ( unsigned i = 0; i < layer->getSize(); ++i ) { if ( layer->neuronEliminated( i ) ) continue; currentLb = layer->getLb( i ); currentUb = layer->getUb( i ); if ( _cutoffInUse && ( currentLb > _cutoffValue || currentUb < _cutoffValue ) ) continue; unsigned variable = layer->neuronToVariable( i ); Stringf variableName( "x%u", variable ); ub = solveLPRelaxation( layers, MinOrMax::MAX, variableName, layer->getLayerIndex() ); if ( ub < currentUb ) { if ( FloatUtils::isPositive( currentUb ) && !FloatUtils::isPositive( ub ) ) ++signChanges; layer->setUb( i, ub ); _layerOwner->receiveTighterBound( Tightening( variable, ub, Tightening::UB ) ); ++tighterBoundCounter; if ( _cutoffInUse && ub < _cutoffValue ) { ++cutoffs; continue; } } lb = solveLPRelaxation( layers, MinOrMax::MIN, variableName, layer->getLayerIndex() ); if ( lb > currentLb ) { if ( FloatUtils::isNegative( currentLb ) && !FloatUtils::isNegative( lb ) ) ++signChanges; layer->setLb( i, lb ); _layerOwner->receiveTighterBound( Tightening( variable, lb, Tightening::LB ) ); ++tighterBoundCounter; if ( _cutoffInUse && lb > _cutoffValue ) { ++cutoffs; continue; } } } } gurobiEnd = TimeUtils::sampleMicro(); LPFormulator_LOG( Stringf( "Number of tighter bounds found by Gurobi: %u. Sign changes: %u. Cutoffs: %u\n", tighterBoundCounter, signChanges, cutoffs ).ascii() ); LPFormulator_LOG( Stringf( "Seconds spent Gurobiing: %llu\n", TimeUtils::timePassed( gurobiStart, gurobiEnd ) / 1000000 ).ascii() ); } void LPFormulator::createLPRelaxation( const Map<unsigned, Layer *> &layers, GurobiWrapper &gurobi, unsigned lastLayer ) { for ( const auto &layer : layers ) { if ( layer.second->getLayerIndex() > lastLayer ) continue; addLayerToModel( gurobi, layer.second ); } } void LPFormulator::addLayerToModel( GurobiWrapper &gurobi, const Layer *layer ) { switch ( layer->getLayerType() ) { case Layer::INPUT: addInputLayerToLpRelaxation( gurobi, layer ); break; case Layer::RELU: addReluLayerToLpRelaxation( gurobi, layer ); break; case Layer::WEIGHTED_SUM: addWeightedSumLayerToLpRelaxation( gurobi, layer ); break; default: throw NLRError( NLRError::LAYER_TYPE_NOT_SUPPORTED, "MILPFormulator" ); break; } } void LPFormulator::addInputLayerToLpRelaxation( GurobiWrapper &gurobi, const Layer *layer ) { for ( unsigned i = 0; i < layer->getSize(); ++i ) { unsigned varibale = layer->neuronToVariable( i ); gurobi.addVariable( Stringf( "x%u", varibale ), layer->getLb( i ), layer->getUb( i ) ); } } void LPFormulator::addReluLayerToLpRelaxation( GurobiWrapper &gurobi, const Layer *layer ) { for ( unsigned i = 0; i < layer->getSize(); ++i ) { if ( !layer->neuronEliminated( i ) ) { unsigned targetVariable = layer->neuronToVariable( i ); List<NeuronIndex> sources = layer->getActivationSources( i ); const Layer *sourceLayer = _layerOwner->getLayer( sources.begin()->_layer ); unsigned sourceNeuron = sources.begin()->_neuron; unsigned sourceVariable = sourceLayer->neuronToVariable( sourceNeuron ); double sourceLb = sourceLayer->getLb( sourceNeuron ); double sourceUb = sourceLayer->getUb( sourceNeuron ); gurobi.addVariable( Stringf( "x%u", targetVariable ), 0, layer->getUb( i ) ); if ( !FloatUtils::isNegative( sourceLb ) ) { if ( sourceLb < 0 ) sourceLb = 0; List<GurobiWrapper::Term> terms; terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariable ) ) ); terms.append( GurobiWrapper::Term( -1, Stringf( "x%u", sourceVariable ) ) ); gurobi.addEqConstraint( terms, 0 ); } else if ( !FloatUtils::isPositive( sourceUb ) ) { List<GurobiWrapper::Term> terms; terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariable ) ) ); gurobi.addEqConstraint( terms, 0 ); } else { List<GurobiWrapper::Term> terms; terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariable ) ) ); gurobi.addGeqConstraint( terms, 0 ); terms.clear(); terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariable ) ) ); terms.append( GurobiWrapper::Term( -1, Stringf( "x%u", sourceVariable ) ) ); gurobi.addGeqConstraint( terms, 0 ); terms.clear(); terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariable ) ) ); terms.append( GurobiWrapper::Term( -sourceUb / ( sourceUb - sourceLb ), Stringf( "x%u", sourceVariable ) ) ); gurobi.addLeqConstraint( terms, ( -sourceUb * sourceLb ) / ( sourceUb - sourceLb ) ); } } } } void LPFormulator::addWeightedSumLayerToLpRelaxation( GurobiWrapper &gurobi, const Layer *layer ) { for ( unsigned i = 0; i < layer->getSize(); ++i ) { if ( !layer->neuronEliminated( i ) ) { unsigned varibale = layer->neuronToVariable( i ); gurobi.addVariable( Stringf( "x%u", varibale ), layer->getLb( i ), layer->getUb( i ) ); List<GurobiWrapper::Term> terms; terms.append( GurobiWrapper::Term( -1, Stringf( "x%u", varibale ) ) ); double bias = -layer->getBias( i ); for ( const auto &sourceLayerPair : layer->getSourceLayers() ) { const Layer *sourceLayer = _layerOwner->getLayer( sourceLayerPair.first ); unsigned sourceLayerSize = sourceLayerPair.second; for ( unsigned j = 0; j < sourceLayerSize; ++j ) { double weight = layer->getWeight( sourceLayerPair.first, j, i ); if ( !sourceLayer->neuronEliminated( j ) ) { Stringf sourceVariableName( "x%u", sourceLayer->neuronToVariable( j ) ); terms.append( GurobiWrapper::Term( weight, sourceVariableName ) ); } else { bias += weight * sourceLayer->getEliminatedNeuronValue( j ); } } } gurobi.addEqConstraint( terms, bias ); } } } void LPFormulator::setCutoff( double cutoff ) { _cutoffInUse = true; _cutoffValue = cutoff; } }
#include "GurobiWrapper.h" #include "InfeasibleQueryException.h" #include "LPFormulator.h" #include "Layer.h" #include "MStringf.h" #include "NLRError.h" #include "TimeUtils.h" namespace NLR { LPFormulator::LPFormulator( LayerOwner *layerOwner ) : _layerOwner( layerOwner ) , _cutoffInUse( false ) , _cutoffValue( 0 ) { } LPFormulator::~LPFormulator() { } double LPFormulator::solveLPRelaxation( const Map<unsigned, Layer *> &layers, MinOrMax minOrMax, String variableName, unsigned lastLayer ) { GurobiWrapper gurobi; createLPRelaxation( layers, gurobi, lastLayer ); List<GurobiWrapper::Term> terms; terms.append( GurobiWrapper::Term( 1, variableName ) ); if ( minOrMax == MAX ) gurobi.setObjective( terms ); else gurobi.setCost( terms ); gurobi.solve(); if ( gurobi.infeasbile() ) throw InfeasibleQueryException(); if ( !gurobi.optimal() ) throw NLRError( NLRError::UNEXPECTED_RETURN_STATUS_FROM_GUROBI ); Map<String, double> dontCare; double result = 0; gurobi.extractSolution( dontCare, result ); return result; } void LPFormulator::optimizeBoundsWithIncrementalLpRelaxation( const Map<unsigned, Layer *> &layers ) { GurobiWrapper gurobi; List<GurobiWrapper::Term> terms; Map<String, double> dontCare; double lb = 0; double ub = 0; double currentLb = 0; double currentUb = 0; unsigned tighterBoundCounter = 0; unsigned signChanges = 0; unsigned cutoffs = 0; struct timespec gurobiStart; (void) gurobiStart; struct timespec gurobiEnd; (void) gurobiEnd; gurobiStart = TimeUtils::sampleMicro(); for ( unsigned i = 0; i < _layerOwner->getNumberOfLayers(); ++i ) { ASSERT( layers.exists( i ) ); Layer *layer = layers[i]; addLayerToModel( gurobi, layer ); for ( unsigned j = 0; j < layer->getSize(); ++j ) { if ( layer->neuronEliminated( j ) ) continue; currentLb = layer->getLb( j ); currentUb = layer->getUb( j ); if ( _cutoffInUse && ( currentLb > _cutoffValue || currentUb < _cutoffValue ) ) continue; unsigned variable = layer->neuronToVariable( j ); Stringf variableName( "x%u", variable ); terms.clear(); terms.append( GurobiWrapper::Term( 1, variableName ) ); gurobi.reset(); gurobi.setObjective( terms ); gurobi.solve(); if ( gurobi.infeasbile() ) throw InfeasibleQueryException(); if ( !gurobi.optimal() ) throw NLRError( NLRError::UNEXPECTED_RETURN_STATUS_FROM_GUROBI ); gurobi.extractSolution( dontCare, ub ); if ( ub < currentUb ) { gurobi.setUpperBound( variableName, ub ); if ( FloatUtils::isPositive( currentUb ) && !FloatUtils::isPositive( ub ) ) ++signChanges; layer->setUb( j, ub ); _layerOwner->receiveTighterBound( Tightening( variable, ub, Tightening::UB ) ); ++tighterBoundCounter; if ( _cutoffInUse && ub < _cutoffValue ) { ++cutoffs; continue; } } gurobi.reset(); gurobi.setCost( terms ); gurobi.solve(); if ( gurobi.infeasbile() ) throw InfeasibleQueryException(); if ( !gurobi.optimal() ) throw NLRError( NLRError::UNEXPECTED_RETURN_STATUS_FROM_GUROBI ); gurobi.extractSolution( dontCare, lb ); if ( lb > currentLb ) { gurobi.setLowerBound( variableName, lb ); if ( FloatUtils::isNegative( currentLb ) && !FloatUtils::isNegative( lb ) ) ++signChanges; layer->setLb( j, lb ); _layerOwner->receiveTighterBound( Tightening( variable, lb, Tightening::LB ) ); ++tighterBoundCounter; if ( _cutoffInUse && lb > _cutoffValue ) { ++cutoffs; continue; } } } } gurobiEnd = TimeUtils::sampleMicro(); LPFormulator_LOG( Stringf( "Number of tighter bounds found by Gurobi: %u. Sign changes: %u. Cutoffs: %u\n", tighterBoundCounter, signChanges, cutoffs ).ascii() ); LPFormulator_LOG( Stringf( "Seconds spent Gurobiing: %llu\n", TimeUtils::timePassed( gurobiStart, gurobiEnd ) / 1000000 ).ascii() ); } void LPFormulator::optimizeBoundsWithLpRelaxation( const Map<unsigned, Layer *> &layers ) { double lb = FloatUtils::negativeInfinity(); double ub = FloatUtils::infinity(); double currentLb; double currentUb; unsigned tighterBoundCounter = 0; unsigned signChanges = 0; unsigned cutoffs = 0; struct timespec gurobiStart; (void) gurobiStart; struct timespec gurobiEnd; (void) gurobiEnd; gurobiStart = TimeUtils::sampleMicro(); for ( const auto &currentLayer : layers ) { Layer *layer = currentLayer.second; for ( unsigned i = 0; i < layer->getSize(); ++i ) { if ( layer->neuronEliminated( i ) ) continue; currentLb = layer->getLb( i ); currentUb = layer->getUb( i ); if ( _cutoffInUse && ( currentLb > _cutoffValue || currentUb < _cutoffValue ) ) continue; unsigned variable = layer->neuronToVariable( i ); Stringf variableName( "x
rapper::Term> terms; terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariable ) ) ); gurobi.addEqConstraint( terms, 0 ); } else { List<GurobiWrapper::Term> terms; terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariable ) ) ); gurobi.addGeqConstraint( terms, 0 ); terms.clear(); terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariable ) ) ); terms.append( GurobiWrapper::Term( -1, Stringf( "x%u", sourceVariable ) ) ); gurobi.addGeqConstraint( terms, 0 ); terms.clear(); terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariable ) ) ); terms.append( GurobiWrapper::Term( -sourceUb / ( sourceUb - sourceLb ), Stringf( "x%u", sourceVariable ) ) ); gurobi.addLeqConstraint( terms, ( -sourceUb * sourceLb ) / ( sourceUb - sourceLb ) ); } } } } void LPFormulator::addWeightedSumLayerToLpRelaxation( GurobiWrapper &gurobi, const Layer *layer ) { for ( unsigned i = 0; i < layer->getSize(); ++i ) { if ( !layer->neuronEliminated( i ) ) { unsigned varibale = layer->neuronToVariable( i ); gurobi.addVariable( Stringf( "x%u", varibale ), layer->getLb( i ), layer->getUb( i ) ); List<GurobiWrapper::Term> terms; terms.append( GurobiWrapper::Term( -1, Stringf( "x%u", varibale ) ) ); double bias = -layer->getBias( i ); for ( const auto &sourceLayerPair : layer->getSourceLayers() ) { const Layer *sourceLayer = _layerOwner->getLayer( sourceLayerPair.first ); unsigned sourceLayerSize = sourceLayerPair.second; for ( unsigned j = 0; j < sourceLayerSize; ++j ) { double weight = layer->getWeight( sourceLayerPair.first, j, i ); if ( !sourceLayer->neuronEliminated( j ) ) { Stringf sourceVariableName( "x%u", sourceLayer->neuronToVariable( j ) ); terms.append( GurobiWrapper::Term( weight, sourceVariableName ) ); } else { bias += weight * sourceLayer->getEliminatedNeuronValue( j ); } } } gurobi.addEqConstraint( terms, bias ); } } } void LPFormulator::setCutoff( double cutoff ) { _cutoffInUse = true; _cutoffValue = cutoff; } }
%u", variable ); ub = solveLPRelaxation( layers, MinOrMax::MAX, variableName, layer->getLayerIndex() ); if ( ub < currentUb ) { if ( FloatUtils::isPositive( currentUb ) && !FloatUtils::isPositive( ub ) ) ++signChanges; layer->setUb( i, ub ); _layerOwner->receiveTighterBound( Tightening( variable, ub, Tightening::UB ) ); ++tighterBoundCounter; if ( _cutoffInUse && ub < _cutoffValue ) { ++cutoffs; continue; } } lb = solveLPRelaxation( layers, MinOrMax::MIN, variableName, layer->getLayerIndex() ); if ( lb > currentLb ) { if ( FloatUtils::isNegative( currentLb ) && !FloatUtils::isNegative( lb ) ) ++signChanges; layer->setLb( i, lb ); _layerOwner->receiveTighterBound( Tightening( variable, lb, Tightening::LB ) ); ++tighterBoundCounter; if ( _cutoffInUse && lb > _cutoffValue ) { ++cutoffs; continue; } } } } gurobiEnd = TimeUtils::sampleMicro(); LPFormulator_LOG( Stringf( "Number of tighter bounds found by Gurobi: %u. Sign changes: %u. Cutoffs: %u\n", tighterBoundCounter, signChanges, cutoffs ).ascii() ); LPFormulator_LOG( Stringf( "Seconds spent Gurobiing: %llu\n", TimeUtils::timePassed( gurobiStart, gurobiEnd ) / 1000000 ).ascii() ); } void LPFormulator::createLPRelaxation( const Map<unsigned, Layer *> &layers, GurobiWrapper &gurobi, unsigned lastLayer ) { for ( const auto &layer : layers ) { if ( layer.second->getLayerIndex() > lastLayer ) continue; addLayerToModel( gurobi, layer.second ); } } void LPFormulator::addLayerToModel( GurobiWrapper &gurobi, const Layer *layer ) { switch ( layer->getLayerType() ) { case Layer::INPUT: addInputLayerToLpRelaxation( gurobi, layer ); break; case Layer::RELU: addReluLayerToLpRelaxation( gurobi, layer ); break; case Layer::WEIGHTED_SUM: addWeightedSumLayerToLpRelaxation( gurobi, layer ); break; default: throw NLRError( NLRError::LAYER_TYPE_NOT_SUPPORTED, "MILPFormulator" ); break; } } void LPFormulator::addInputLayerToLpRelaxation( GurobiWrapper &gurobi, const Layer *layer ) { for ( unsigned i = 0; i < layer->getSize(); ++i ) { unsigned varibale = layer->neuronToVariable( i ); gurobi.addVariable( Stringf( "x%u", varibale ), layer->getLb( i ), layer->getUb( i ) ); } } void LPFormulator::addReluLayerToLpRelaxation( GurobiWrapper &gurobi, const Layer *layer ) { for ( unsigned i = 0; i < layer->getSize(); ++i ) { if ( !layer->neuronEliminated( i ) ) { unsigned targetVariable = layer->neuronToVariable( i ); List<NeuronIndex> sources = layer->getActivationSources( i ); const Layer *sourceLayer = _layerOwner->getLayer( sources.begin()->_layer ); unsigned sourceNeuron = sources.begin()->_neuron; unsigned sourceVariable = sourceLayer->neuronToVariable( sourceNeuron ); double sourceLb = sourceLayer->getLb( sourceNeuron ); double sourceUb = sourceLayer->getUb( sourceNeuron ); gurobi.addVariable( Stringf( "x%u", targetVariable ), 0, layer->getUb( i ) ); if ( !FloatUtils::isNegative( sourceLb ) ) { if ( sourceLb < 0 ) sourceLb = 0; List<GurobiWrapper::Term> terms; terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariable ) ) ); terms.append( GurobiWrapper::Term( -1, Stringf( "x%u", sourceVariable ) ) ); gurobi.addEqConstraint( terms, 0 ); } else if ( !FloatUtils::isPositive( sourceUb ) ) { List<GurobiW
random
[ { "content": "class Stringf : public String\n\n{\n\npublic:\n\n enum {\n\n MAX_STRING_LENGTH = 10000,\n\n };\n\n\n\n Stringf( const char *format, ... )\n\n {\n\n va_list argList;\n\n va_start( argList, format );\n\n\n\n char buffer[MAX_STRING_LENGTH];\n\n\n\n vsprintf( buffer, format, argList );\n\n\n\n va_end( argList );\n\n\n\n _super = Super( buffer );\n\n }\n\n};\n\n\n\n#ifdef CXXTEST_RUNNING\n\n#include <cxxtest/ValueTraits.h>\n\n#include <stdio.h>\n\nnamespace CxxTest\n\n{\n\n CXXTEST_TEMPLATE_INSTANTIATION\n", "file_path": "src/common/MStringf.h", "rank": 0, "score": 176553.99970032708 }, { "content": "class AutoConstraintBoundTightener\n\n{\n\npublic:\n\n\tAutoConstraintBoundTightener( const ITableau &tableau )\n\n\t{\n\n\t\t_constraintBoundTightener = T::createConstraintBoundTightener( tableau );\n\n\t}\n\n\n\n\t~AutoConstraintBoundTightener()\n\n\t{\n\n\t\tT::discardConstraintBoundTightener( _constraintBoundTightener );\n\n\t\t_constraintBoundTightener = 0;\n\n\t}\n\n\n\n\toperator IConstraintBoundTightener &()\n\n\t{\n\n\t\treturn *_constraintBoundTightener;\n\n\t}\n\n\n\n\toperator IConstraintBoundTightener *()\n", "file_path": "src/engine/AutoConstraintBoundTightener.h", "rank": 1, "score": 173135.4257056729 }, { "content": "class AutoRowBoundTightener\n\n{\n\npublic:\n\n\tAutoRowBoundTightener( const ITableau &tableau )\n\n\t{\n\n\t\t_rowBoundTightener = T::createRowBoundTightener( tableau );\n\n\t}\n\n\n\n\t~AutoRowBoundTightener()\n\n\t{\n\n\t\tT::discardRowBoundTightener( _rowBoundTightener );\n\n\t\t_rowBoundTightener = 0;\n\n\t}\n\n\n\n\toperator IRowBoundTightener &()\n\n\t{\n\n\t\treturn *_rowBoundTightener;\n\n\t}\n\n\n\n\toperator IRowBoundTightener *()\n", "file_path": "src/engine/AutoRowBoundTightener.h", "rank": 2, "score": 173135.4257056729 }, { "content": "class Layer\n\n{\n\npublic:\n\n enum Type {\n\n // Linear layers\n\n INPUT = 0,\n\n WEIGHTED_SUM,\n\n\n\n // Activation functions\n\n RELU,\n\n ABSOLUTE_VALUE,\n\n MAX,\n\n };\n\n\n\n /*\n\n Construct a layer directly and populate its fields, or clone\n\n from another layer\n\n */\n\n Layer( const Layer *other );\n\n Layer( unsigned index, Type type, unsigned size, LayerOwner *layerOwner );\n", "file_path": "src/nlr/Layer.h", "rank": 3, "score": 157951.2776243998 }, { "content": "struct timespec TimeUtils::sampleMicro()\n\n{\n\n struct timespec now;\n\n#ifdef _WIN32\n\n\tLARGE_INTEGER count;\n\n\n\n\tif ( gFirstTime )\n\n\t{\n\n\t\tgFirstTime = 0;\n\n\n\n\t\tif ( 0 == QueryPerformanceFrequency( &gCountsPerSec ) )\n\n\t\t{\n\n\t\t\tgCountsPerSec.QuadPart = 0;\n\n\t\t}\n\n\t}\n\n\tQueryPerformanceCounter( &count );\n\n\tnow.tv_sec = count.QuadPart / gCountsPerSec.QuadPart;\n\n\tnow.tv_nsec = ( ( count.QuadPart % gCountsPerSec.QuadPart ) * static_cast<long>( 1000000000 ) ) / gCountsPerSec.QuadPart;\n\n#else\n\n clock_gettime( CLOCK_MONOTONIC, &now );\n", "file_path": "src/common/TimeUtils.cpp", "rank": 4, "score": 155962.25323066785 }, { "content": "class Layer;\n\n\n", "file_path": "src/nlr/LayerOwner.h", "rank": 5, "score": 154974.65096518895 }, { "content": "/********************* */\n\n/*! \\file AutoConstraintBoundTightener.h\n\n ** \\verbatim\n\n ** Top contributors (to current version):\n\n ** Guy Katz\n\n ** This file is part of the Marabou project.\n\n ** Copyright (c) 2017-2019 by the authors listed in the file AUTHORS\n\n ** in the top-level source directory) and their institutional affiliations.\n\n ** All rights reserved. See the file COPYING in the top-level source\n\n ** directory for licensing information.\\endverbatim\n\n **\n\n ** [[ Add lengthier description here ]]\n\n\n\n**/\n\n\n\n#ifndef __AutoConstraintBoundTightener_h__\n\n#define __AutoConstraintBoundTightener_h__\n\n\n\n#include \"IConstraintBoundTightener.h\"\n\n#include \"T/ConstraintBoundTightenerFactory.h\"\n\n\n", "file_path": "src/engine/AutoConstraintBoundTightener.h", "rank": 6, "score": 149457.94444709504 }, { "content": "/********************* */\n\n/*! \\file AutoRowBoundTightener.h\n\n ** \\verbatim\n\n ** Top contributors (to current version):\n\n ** Guy Katz\n\n ** This file is part of the Marabou project.\n\n ** Copyright (c) 2017-2019 by the authors listed in the file AUTHORS\n\n ** in the top-level source directory) and their institutional affiliations.\n\n ** All rights reserved. See the file COPYING in the top-level source\n\n ** directory for licensing information.\\endverbatim\n\n **\n\n ** [[ Add lengthier description here ]]\n\n\n\n**/\n\n\n\n#ifndef __AutoRowBoundTightener_h__\n\n#define __AutoRowBoundTightener_h__\n\n\n\n#include \"IRowBoundTightener.h\"\n\n#include \"T/RowBoundTightenerFactory.h\"\n\n\n", "file_path": "src/engine/AutoRowBoundTightener.h", "rank": 7, "score": 149457.94444709504 }, { "content": "\t{\n\n\t\treturn _rowBoundTightener;\n\n\t}\n\n\n\n\tIRowBoundTightener *operator->()\n\n\t{\n\n\t\treturn _rowBoundTightener;\n\n\t}\n\n\n\n\tconst IRowBoundTightener *operator->() const\n\n\t{\n\n\t\treturn _rowBoundTightener;\n\n\t}\n\n\n\nprivate:\n\n\tIRowBoundTightener *_rowBoundTightener;\n\n};\n\n\n\n#endif // __AutoRowBoundTightener_h__\n\n\n\n//\n\n// Local Variables:\n\n// compile-command: \"make -C ../.. \"\n\n// tags-file-name: \"../../TAGS\"\n\n// c-basic-offset: 4\n\n// End:\n\n//\n", "file_path": "src/engine/AutoRowBoundTightener.h", "rank": 8, "score": 149456.90804008907 }, { "content": "\tIConstraintBoundTightener *_constraintBoundTightener;\n\n};\n\n\n\n#endif // __AutoConstraintBoundTightener_h__\n\n\n\n//\n\n// Local Variables:\n\n// compile-command: \"make -C ../.. \"\n\n// tags-file-name: \"../../TAGS\"\n\n// c-basic-offset: 4\n\n// End:\n\n//\n", "file_path": "src/engine/AutoConstraintBoundTightener.h", "rank": 9, "score": 149456.88043745633 }, { "content": "\t{\n\n\t\treturn _constraintBoundTightener;\n\n\t}\n\n\n\n\tIConstraintBoundTightener *get()\n\n {\n\n return _constraintBoundTightener;\n\n }\n\n\n\n\tIConstraintBoundTightener *operator->()\n\n\t{\n\n\t\treturn _constraintBoundTightener;\n\n\t}\n\n\n\n\tconst IConstraintBoundTightener *operator->() const\n\n\t{\n\n\t\treturn _constraintBoundTightener;\n\n\t}\n\n\n\nprivate:\n", "file_path": "src/engine/AutoConstraintBoundTightener.h", "rank": 10, "score": 149447.64298262977 }, { "content": "class IConstraintBoundTightener : public ITableau::VariableWatcher, public ITableau::ResizeWatcher\n\n{\n\npublic:\n\n virtual ~IConstraintBoundTightener() {};\n\n\n\n /*\n\n Allocate internal work memory according to the tableau size.\n\n */\n\n virtual void setDimensions() = 0;\n\n\n\n /*\n\n Initialize tightest lower/upper bounds using the talbeau.\n\n */\n\n virtual void resetBounds() = 0;\n\n\n\n /*\n\n Callback from the Tableau, to inform of a change in dimensions\n\n */\n\n virtual void notifyDimensionChange( unsigned m, unsigned n ) = 0;\n\n\n", "file_path": "src/engine/IConstraintBoundTightener.h", "rank": 11, "score": 142146.71821203578 }, { "content": "class IRowBoundTightener : public ITableau::VariableWatcher, public ITableau::ResizeWatcher\n\n{\n\npublic:\n\n virtual ~IRowBoundTightener() {};\n\n\n\n /*\n\n Allocate internal work memory according to the tableau size.\n\n */\n\n virtual void setDimensions() = 0;\n\n\n\n /*\n\n Initialize tightest lower/upper bounds using the talbeau.\n\n */\n\n virtual void resetBounds() = 0;\n\n\n\n /*\n\n Clear all learned bounds, without reallocating memory.\n\n */\n\n virtual void clear() = 0;\n\n\n", "file_path": "src/engine/IRowBoundTightener.h", "rank": 12, "score": 142146.71821203578 }, { "content": "class String;\n\n\n\n#include <cstdio>\n\n\n", "file_path": "src/common/ConstSimpleData.h", "rank": 13, "score": 140042.37088410644 }, { "content": " if ( _layer > other._layer )\n", "file_path": "src/nlr/NeuronIndex.h", "rank": 14, "score": 138526.0637383981 }, { "content": " class ValueTraits<const CXXTEST_STD(string)> : public StdTraitsBase\n\n {\n\n public:\n\n ValueTraits( const CXXTEST_STD(string) &s )\n\n {\n\n *this << \"\\\"\";\n\n for ( unsigned i = 0; i < s.length(); ++ i ) {\n\n char c[sizeof(\"\\\\xXX\")];\n\n charToString( s[i], c );\n\n *this << c;\n\n }\n\n *this << \"\\\"\";\n\n }\n\n };\n\n\n\n CXXTEST_COPY_CONST_TRAITS( CXXTEST_STD(string) );\n\n\n\n#ifndef _CXXTEST_OLD_STD\n\n //\n\n // std::wstring\n\n //\n\n CXXTEST_TEMPLATE_INSTANTIATION\n", "file_path": "tools/cxxtest/cxxtest/StdValueTraits.h", "rank": 15, "score": 129552.64739043545 }, { "content": "class ConstraintBoundTightener : public IConstraintBoundTightener\n\n{\n\npublic:\n\n ConstraintBoundTightener( const ITableau &tableau );\n\n ~ConstraintBoundTightener();\n\n\n\n /*\n\n Allocate internal work memory according to the tableau size.\n\n */\n\n void setDimensions();\n\n\n\n /*\n\n Initialize tightest lower/upper bounds using the talbeau.\n\n */\n\n void resetBounds();\n\n\n\n /*\n\n Callback from the Tableau, to inform of a change in dimensions\n\n */\n\n void notifyDimensionChange( unsigned m, unsigned n );\n", "file_path": "src/engine/ConstraintBoundTightener.h", "rank": 16, "score": 124895.9183922835 }, { "content": "class RowBoundTightener : public IRowBoundTightener\n\n{\n\npublic:\n\n RowBoundTightener( const ITableau &tableau );\n\n ~RowBoundTightener();\n\n\n\n /*\n\n Allocate internal work memory according to the tableau size\n\n */\n\n void setDimensions();\n\n\n\n /*\n\n Initialize tightest lower/upper bounds using the talbeau.\n\n */\n\n void resetBounds();\n\n\n\n /*\n\n Clear all learned bounds, without reallocating memory.\n\n */\n\n void clear();\n", "file_path": "src/engine/RowBoundTightener.h", "rank": 17, "score": 124895.9183922835 }, { "content": " class ValueTraits<const double>\n\n {\n\n public:\n\n ValueTraits( double t ) \n\n {\n\n ( requiredDigitsOnLeft( t ) > MAX_DIGITS_ON_LEFT ) ?\n\n hugeNumber( t ) :\n\n normalNumber( t );\n\n }\n\n\n\n const char *asString( void ) const { return _asString; }\n\n \n\n private:\n\n enum { MAX_DIGITS_ON_LEFT = 24, DIGITS_ON_RIGHT = 4, BASE = 10 };\n\n char _asString[1 + MAX_DIGITS_ON_LEFT + 1 + DIGITS_ON_RIGHT + 1];\n\n\n\n static unsigned requiredDigitsOnLeft( double t );\n\n char *doNegative( double &t );\n\n void hugeNumber( double t );\n\n void normalNumber( double t );\n", "file_path": "tools/cxxtest/cxxtest/ValueTraits.h", "rank": 18, "score": 124836.82358713294 }, { "content": "class MockConstraintBoundTightener : public IConstraintBoundTightener\n\n{\n\npublic:\n\n\tMockConstraintBoundTightener()\n\n\t{\n\n\t\twasCreated = false;\n\n\t\twasDiscarded = false;\n\n\n\n setDimensionsWasCalled = false;\n\n }\n\n\n\n ~MockConstraintBoundTightener()\n\n {\n\n }\n\n\n\n\tbool wasCreated;\n\n\tbool wasDiscarded;\n\n const ITableau *lastTableau;\n\n\n\n\tvoid mockConstructor( const ITableau &tableau )\n", "file_path": "src/engine/tests/MockConstraintBoundTightener.h", "rank": 19, "score": 120206.73145530252 }, { "content": "class MockRowBoundTightener : public IRowBoundTightener\n\n{\n\npublic:\n\n\tMockRowBoundTightener()\n\n\t{\n\n\t\twasCreated = false;\n\n\t\twasDiscarded = false;\n\n\n\n setDimensionsWasCalled = false;\n\n }\n\n\n\n ~MockRowBoundTightener()\n\n {\n\n }\n\n\n\n\tbool wasCreated;\n\n\tbool wasDiscarded;\n\n const ITableau *lastTableau;\n\n\n\n\tvoid mockConstructor( const ITableau &tableau )\n", "file_path": "src/engine/tests/MockRowBoundTightener.h", "rank": 20, "score": 120206.73145530252 }, { "content": "sub fileString() { return cstr(fileName()); }\n", "file_path": "tools/cxxtest/cxxtestgen.pl", "rank": 21, "score": 119667.34325013359 }, { "content": " class ValueTraits<const signed _CXXTEST_LONGLONG>\n\n {\n\n typedef _CXXTEST_LONGLONG T;\n\n char _asString[2 + 3 * sizeof(T)];\n\n public:\n\n ValueTraits( T t ) { numberToString<T>( t, _asString ); }\n\n const char *asString( void ) const { return _asString; }\n\n };\n\n\n\n CXXTEST_COPY_CONST_TRAITS( signed _CXXTEST_LONGLONG );\n\n\n\n //\n\n // ValueTraits: unsigned long long\n\n //\n\n CXXTEST_TEMPLATE_INSTANTIATION\n", "file_path": "tools/cxxtest/cxxtest/ValueTraits.h", "rank": 22, "score": 117315.56312586757 }, { "content": " class ValueTraits<const unsigned _CXXTEST_LONGLONG>\n\n {\n\n typedef unsigned _CXXTEST_LONGLONG T;\n\n char _asString[1 + 3 * sizeof(T)];\n\n public:\n\n ValueTraits( T t ) { numberToString<T>( t, _asString ); }\n\n const char *asString( void ) const { return _asString; }\n\n };\n\n\n\n CXXTEST_COPY_CONST_TRAITS( unsigned _CXXTEST_LONGLONG );\n\n# endif // _CXXTEST_LONGLONG\n\n\n\n //\n\n // ValueTraits: signed long\n\n //\n\n CXXTEST_TEMPLATE_INSTANTIATION\n", "file_path": "tools/cxxtest/cxxtest/ValueTraits.h", "rank": 23, "score": 117315.56312586757 }, { "content": "class IRowBoundTightener;\n", "file_path": "src/engine/T/RowBoundTightenerFactory.h", "rank": 24, "score": 115294.02473772594 }, { "content": "class IConstraintBoundTightener;\n", "file_path": "src/engine/T/ConstraintBoundTightenerFactory.h", "rank": 25, "score": 115294.02473772594 }, { "content": " class ValueTraits<const unsigned long int>\n\n {\n\n typedef unsigned long int T;\n\n char _asString[1 + 3 * sizeof(T)];\n\n public:\n\n ValueTraits( T t ) { numberToString<T>( t, _asString ); }\n\n const char *asString( void ) const { return _asString; }\n\n };\n\n\n\n CXXTEST_COPY_CONST_TRAITS( unsigned long int );\n\n \n\n //\n\n // All decimals are the same as the long version\n\n //\n\n \n\n CXXTEST_COPY_TRAITS( const signed int, const signed long int );\n\n CXXTEST_COPY_TRAITS( const unsigned int, const unsigned long int );\n\n CXXTEST_COPY_TRAITS( const signed short int, const signed long int );\n\n CXXTEST_COPY_TRAITS( const unsigned short int, const unsigned long int );\n\n CXXTEST_COPY_TRAITS( const unsigned char, const unsigned long int );\n", "file_path": "tools/cxxtest/cxxtest/ValueTraits.h", "rank": 26, "score": 115086.74983893236 }, { "content": " class ValueTraits<const signed long int>\n\n {\n\n typedef signed long int T;\n\n char _asString[2 + 3 * sizeof(T)];\n\n public:\n\n ValueTraits( T t ) { numberToString<T>( t, _asString ); }\n\n const char *asString( void ) const { return _asString; }\n\n };\n\n\n\n CXXTEST_COPY_CONST_TRAITS( signed long int );\n\n \n\n //\n\n // ValueTraits: unsigned long\n\n //\n\n CXXTEST_TEMPLATE_INSTANTIATION\n", "file_path": "tools/cxxtest/cxxtest/ValueTraits.h", "rank": 27, "score": 115086.74983893236 }, { "content": "class MockForConstraintBoundTightener\n\n{\n\npublic:\n\n};\n\n\n", "file_path": "src/engine/tests/Test_ConstraintBoundTightener.h", "rank": 28, "score": 113254.85145959893 }, { "content": "class MockForRowBoundTightener\n\n{\n\npublic:\n\n};\n\n\n", "file_path": "src/engine/tests/Test_RowBoundTightener.h", "rank": 29, "score": 113254.85145959893 }, { "content": "class LayerOwner\n\n{\n\npublic:\n\n virtual ~LayerOwner() {}\n\n virtual const Layer *getLayer( unsigned index ) const = 0;\n\n virtual const ITableau *getTableau() const = 0;\n\n virtual unsigned getNumberOfLayers() const = 0;\n\n virtual void receiveTighterBound( Tightening tightening ) = 0;\n\n};\n\n\n\n} // namespace NLR\n\n\n\n#endif // __LayerOwner_h__\n", "file_path": "src/nlr/LayerOwner.h", "rank": 30, "score": 111797.18498844106 }, { "content": " Bound related functionality: grab the current bounds from the\n\n Tableau, or compute bounds from source layers\n\n */\n\n void setLb( unsigned neuron, double bound );\n\n void setUb( unsigned neuron, double bound );\n\n double getLb( unsigned neuron ) const;\n\n double getUb( unsigned neuron ) const;\n\n\n\n void obtainCurrentBounds();\n\n void computeSymbolicBounds();\n\n void computeIntervalArithmeticBounds();\n\n\n\n /*\n\n Preprocessing functionality: variable elimination and reindexing\n\n */\n\n void eliminateVariable( unsigned variable, double value );\n\n void updateVariableIndices( const Map<unsigned, unsigned> &oldIndexToNewIndex,\n\n const Map<unsigned, unsigned> &mergedVariables );\n\n\n\n bool neuronEliminated( unsigned neuron ) const;\n", "file_path": "src/nlr/Layer.h", "rank": 31, "score": 109675.78214886936 }, { "content": " const double *getSymbolicLb() const;\n\n const double *getSymbolicUb() const;\n\n const double *getSymbolicLowerBias() const;\n\n const double *getSymbolicUpperBias() const;\n\n double getSymbolicLbOfLb( unsigned neuron ) const;\n\n double getSymbolicUbOfLb( unsigned neuron ) const;\n\n double getSymbolicLbOfUb( unsigned neuron ) const;\n\n double getSymbolicUbOfUb( unsigned neuron ) const;\n\n};\n\n\n\n} // namespace NLR\n\n\n\n#endif // __Layer_h__\n", "file_path": "src/nlr/Layer.h", "rank": 32, "score": 109669.3205012576 }, { "content": "\n\n double *_assignment;\n\n\n\n double *_lb;\n\n double *_ub;\n\n\n\n Map<unsigned, List<NeuronIndex>> _neuronToActivationSources;\n\n\n\n Map<unsigned, unsigned> _neuronToVariable;\n\n Map<unsigned, unsigned> _variableToNeuron;\n\n Map<unsigned, double> _eliminatedNeurons;\n\n\n\n unsigned _inputLayerSize;\n\n double *_symbolicLb;\n\n double *_symbolicUb;\n\n double *_symbolicLowerBias;\n\n double *_symbolicUpperBias;\n\n double *_symbolicLbOfLb;\n\n double *_symbolicUbOfLb;\n\n double *_symbolicLbOfUb;\n", "file_path": "src/nlr/Layer.h", "rank": 33, "score": 109665.54026403236 }, { "content": " double *_symbolicUbOfUb;\n\n\n\n void allocateMemory();\n\n void freeMemoryIfNeeded();\n\n\n\n /*\n\n Helper functions for symbolic bound tightening\n\n */\n\n void comptueSymbolicBoundsForInput();\n\n void computeSymbolicBoundsForRelu();\n\n void computeSymbolicBoundsForAbsoluteValue();\n\n void computeSymbolicBoundsForWeightedSum();\n\n\n\n /*\n\n Helper functions for interval bound tightening\n\n */\n\n void computeIntervalArithmeticBoundsForWeightedSum();\n\n void computeIntervalArithmeticBoundsForRelu();\n\n void computeIntervalArithmeticBoundsForAbs();\n\n\n", "file_path": "src/nlr/Layer.h", "rank": 34, "score": 109660.5695589822 }, { "content": " List<NeuronIndex> getActivationSources( unsigned neuron ) const;\n\n\n\n void setNeuronVariable( unsigned neuron, unsigned variable );\n\n bool neuronHasVariable( unsigned neuron ) const;\n\n unsigned neuronToVariable( unsigned neuron ) const;\n\n unsigned variableToNeuron( unsigned variable ) const;\n\n\n\n unsigned getSize() const;\n\n unsigned getLayerIndex() const;\n\n Type getLayerType() const;\n\n\n\n /*\n\n Set/get the assignment, or compute it from source layers\n\n */\n\n void setAssignment( const double *values );\n\n const double *getAssignment() const;\n\n double getAssignment( unsigned neuron ) const;\n\n void computeAssignment();\n\n\n\n /*\n", "file_path": "src/nlr/Layer.h", "rank": 35, "score": 109660.46992187983 }, { "content": " ~Layer();\n\n\n\n void setLayerOwner( LayerOwner *layerOwner );\n\n void addSourceLayer( unsigned layerNumber, unsigned layerSize );\n\n const Map<unsigned, unsigned> &getSourceLayers() const;\n\n\n\n void setWeight( unsigned sourceLayer,\n\n unsigned sourceNeuron,\n\n unsigned targetNeuron,\n\n double weight );\n\n double getWeight( unsigned sourceLayer,\n\n unsigned sourceNeuron,\n\n unsigned targetNeuron ) const;\n\n\n\n void setBias( unsigned neuron, double bias );\n\n double getBias( unsigned neuron ) const;\n\n\n\n void addActivationSource( unsigned sourceLayer,\n\n unsigned sourceNeuron,\n\n unsigned targetNeuron );\n", "file_path": "src/nlr/Layer.h", "rank": 36, "score": 109660.2293891523 }, { "content": " double getEliminatedNeuronValue( unsigned neuron ) const;\n\n\n\n /*\n\n For debugging purposes\n\n */\n\n void dump() const;\n\n static String typeToString( Type type );\n\n\n\nprivate:\n\n unsigned _layerIndex;\n\n Type _type;\n\n unsigned _size;\n\n LayerOwner *_layerOwner;\n\n\n\n Map<unsigned, unsigned> _sourceLayers;\n\n\n\n Map<unsigned, double *> _layerToWeights;\n\n Map<unsigned, double *> _layerToPositiveWeights;\n\n Map<unsigned, double *> _layerToNegativeWeights;\n\n double *_bias;\n", "file_path": "src/nlr/Layer.h", "rank": 37, "score": 109659.66613589726 }, { "content": "/********************* */\n\n/*! \\file Layer.h\n\n ** \\verbatim\n\n ** Top contributors (to current version):\n\n ** Guy Katz\n\n ** This file is part of the Marabou project.\n\n ** Copyright (c) 2017-2019 by the authors listed in the file AUTHORS\n\n ** in the top-level source directory) and their institutional affiliations.\n\n ** All rights reserved. See the file COPYING in the top-level source\n\n ** directory for licensing information.\\endverbatim\n\n **\n\n ** [[ Add lengthier description here ]]\n\n\n\n**/\n\n\n\n#ifndef __Layer_h__\n\n#define __Layer_h__\n\n\n\n#include \"AbsoluteValueConstraint.h\"\n\n#include \"Debug.h\"\n\n#include \"FloatUtils.h\"\n\n#include \"LayerOwner.h\"\n\n#include \"MarabouError.h\"\n\n#include \"NeuronIndex.h\"\n\n#include \"ReluConstraint.h\"\n\n\n\nnamespace NLR {\n\n\n", "file_path": "src/nlr/Layer.h", "rank": 38, "score": 109657.26367037372 }, { "content": "class MockRowBoundTightenerFactory :\n\n\tpublic T::Base_createRowBoundTightener,\n\n\tpublic T::Base_discardRowBoundTightener\n\n{\n\npublic:\n\n\tMockRowBoundTightener mockRowBoundTightener;\n\n\n\n\t~MockRowBoundTightenerFactory()\n\n\t{\n\n\t\tif ( mockRowBoundTightener.wasCreated )\n\n\t\t{\n\n\t\t\tTS_ASSERT( mockRowBoundTightener.wasDiscarded );\n\n\t\t}\n\n\t}\n\n\n\n\tIRowBoundTightener *createRowBoundTightener( const ITableau &tableau )\n\n\t{\n\n\t\tmockRowBoundTightener.mockConstructor( tableau );\n\n\t\treturn &mockRowBoundTightener;\n\n\t}\n", "file_path": "src/engine/tests/MockRowBoundTightenerFactory.h", "rank": 39, "score": 109385.50942992773 }, { "content": "class MockConstraintBoundTightenerFactory :\n\n\tpublic T::Base_createConstraintBoundTightener,\n\n\tpublic T::Base_discardConstraintBoundTightener\n\n{\n\npublic:\n\n\tMockConstraintBoundTightener mockConstraintBoundTightener;\n\n\n\n\t~MockConstraintBoundTightenerFactory()\n\n\t{\n\n\t\tif ( mockConstraintBoundTightener.wasCreated )\n\n\t\t{\n\n\t\t\tTS_ASSERT( mockConstraintBoundTightener.wasDiscarded );\n\n\t\t}\n\n\t}\n\n\n\n\tIConstraintBoundTightener *createConstraintBoundTightener( const ITableau &tableau )\n\n\t{\n\n\t\tmockConstraintBoundTightener.mockConstructor( tableau );\n\n\t\treturn &mockConstraintBoundTightener;\n\n\t}\n", "file_path": "src/engine/tests/MockConstraintBoundTightenerFactory.h", "rank": 40, "score": 109385.50942992773 }, { "content": " _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _lb[i], Tightening::LB ) );\n\n }\n\n\n\n if ( _ub[i] > _symbolicUbOfUb[i] )\n\n {\n\n _ub[i] = _symbolicUbOfUb[i];\n\n _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _ub[i], Tightening::UB ) );\n\n }\n\n }\n\n }\n\n}\n\n\n\nvoid Layer::eliminateVariable( unsigned variable, double value )\n\n{\n\n if ( !_variableToNeuron.exists( variable ) )\n\n return;\n\n\n\n ASSERT( _type != INPUT );\n\n\n\n unsigned neuron = _variableToNeuron[variable];\n", "file_path": "src/nlr/Layer.cpp", "rank": 41, "score": 106060.4683363303 }, { "content": "\n\n if ( newLb[i] > _lb[i] )\n\n {\n\n _lb[i] = newLb[i];\n\n _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _lb[i], Tightening::LB ) );\n\n }\n\n if ( newUb[i] < _ub[i] )\n\n {\n\n _ub[i] = newUb[i];\n\n _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _ub[i], Tightening::UB ) );\n\n }\n\n }\n\n\n\n delete[] newLb;\n\n delete[] newUb;\n\n}\n\n\n\nvoid Layer::computeIntervalArithmeticBoundsForRelu()\n\n{\n\n for ( unsigned i = 0; i < _size; ++i )\n", "file_path": "src/nlr/Layer.cpp", "rank": 42, "score": 106055.89116812471 }, { "content": " {\n\n _ub[i] = -lb;\n\n _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _ub[i], Tightening::UB ) );\n\n }\n\n }\n\n else\n\n {\n\n // lb < 0 < ub\n\n if ( _lb[i] < 0 )\n\n {\n\n _lb[i] = 0;\n\n _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _lb[i], Tightening::LB ) );\n\n }\n\n\n\n if ( FloatUtils::max( ub, -lb ) < _ub[i] )\n\n {\n\n _ub[i] = FloatUtils::max( ub, -lb );\n\n _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _ub[i], Tightening::UB ) );\n\n }\n\n }\n", "file_path": "src/nlr/Layer.cpp", "rank": 43, "score": 106054.81692980173 }, { "content": " _ub[i] = ub;\n\n _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _ub[i], Tightening::UB ) );\n\n }\n\n }\n\n}\n\n\n\nvoid Layer::computeIntervalArithmeticBoundsForAbs()\n\n{\n\n for ( unsigned i = 0; i < _size; ++i )\n\n {\n\n if ( _eliminatedNeurons.exists( i ) )\n\n continue;\n\n\n\n NeuronIndex sourceIndex = *_neuronToActivationSources[i].begin();\n\n const Layer *sourceLayer = _layerOwner->getLayer( sourceIndex._layer );\n\n\n\n double lb = sourceLayer->getLb( sourceIndex._neuron );\n\n double ub = sourceLayer->getUb( sourceIndex._neuron );\n\n\n\n if ( lb > 0 )\n", "file_path": "src/nlr/Layer.cpp", "rank": 44, "score": 106053.7398656452 }, { "content": " */\n\n if ( _lb[i] < _symbolicLbOfLb[i] )\n\n {\n\n _lb[i] = _symbolicLbOfLb[i];\n\n _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _lb[i], Tightening::LB ) );\n\n }\n\n\n\n if ( _ub[i] > _symbolicUbOfUb[i] )\n\n {\n\n _ub[i] = _symbolicUbOfUb[i];\n\n _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _ub[i], Tightening::UB ) );\n\n }\n\n }\n\n}\n\n\n\nvoid Layer::computeSymbolicBoundsForWeightedSum()\n\n{\n\n std::fill_n( _symbolicLb, _size * _inputLayerSize, 0 );\n\n std::fill_n( _symbolicUb, _size * _inputLayerSize, 0 );\n\n\n", "file_path": "src/nlr/Layer.cpp", "rank": 45, "score": 106051.10655295893 }, { "content": " {\n\n _ub[i] = _symbolicUbOfUb[i];\n\n _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _ub[i], Tightening::UB ) );\n\n }\n\n }\n\n}\n\n\n\nvoid Layer::computeSymbolicBoundsForAbsoluteValue()\n\n{\n\n std::fill_n( _symbolicLb, _size * _inputLayerSize, 0 );\n\n std::fill_n( _symbolicUb, _size * _inputLayerSize, 0 );\n\n\n\n for ( unsigned i = 0; i < _size; ++i )\n\n {\n\n if ( _eliminatedNeurons.exists( i ) )\n\n {\n\n _symbolicLowerBias[i] = _eliminatedNeurons[i];\n\n _symbolicUpperBias[i] = _eliminatedNeurons[i];\n\n\n\n _symbolicLbOfLb[i] = _eliminatedNeurons[i];\n", "file_path": "src/nlr/Layer.cpp", "rank": 46, "score": 106049.59496881824 }, { "content": " {\n\n if ( lb > _lb[i] )\n\n {\n\n _lb[i] = lb;\n\n _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _lb[i], Tightening::LB ) );\n\n }\n\n if ( ub < _ub[i] )\n\n {\n\n _ub[i] = ub;\n\n _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _ub[i], Tightening::UB ) );\n\n }\n\n }\n\n else if ( ub < 0 )\n\n {\n\n if ( -ub > _lb[i] )\n\n {\n\n _lb[i] = -ub;\n\n _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _lb[i], Tightening::LB ) );\n\n }\n\n if ( -lb < _ub[i] )\n", "file_path": "src/nlr/Layer.cpp", "rank": 47, "score": 106049.52373058262 }, { "content": "}\n\n\n\nvoid Layer::obtainCurrentBounds()\n\n{\n\n for ( unsigned i = 0; i < _size; ++i )\n\n {\n\n if ( _neuronToVariable.exists( i ) )\n\n {\n\n unsigned variable = _neuronToVariable[i];\n\n _lb[i] = _layerOwner->getTableau()->getLowerBound( variable );\n\n _ub[i] = _layerOwner->getTableau()->getUpperBound( variable );\n\n }\n\n else\n\n {\n\n ASSERT( _eliminatedNeurons.exists( i ) );\n\n _lb[i] = _eliminatedNeurons[i];\n\n _ub[i] = _eliminatedNeurons[i];\n\n }\n\n }\n\n}\n", "file_path": "src/nlr/Layer.cpp", "rank": 48, "score": 106047.17841051923 }, { "content": " {\n\n if ( _eliminatedNeurons.exists( i ) )\n\n continue;\n\n\n\n NeuronIndex sourceIndex = *_neuronToActivationSources[i].begin();\n\n const Layer *sourceLayer = _layerOwner->getLayer( sourceIndex._layer );\n\n\n\n double lb = sourceLayer->getLb( sourceIndex._neuron );\n\n double ub = sourceLayer->getUb( sourceIndex._neuron );\n\n\n\n if ( lb < 0 )\n\n lb = 0;\n\n\n\n if ( lb > _lb[i] )\n\n {\n\n _lb[i] = lb;\n\n _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _lb[i], Tightening::LB ) );\n\n }\n\n if ( ub < _ub[i] )\n\n {\n", "file_path": "src/nlr/Layer.cpp", "rank": 49, "score": 106045.7521523759 }, { "content": "}\n\n\n\ndouble Layer::getSymbolicLbOfUb( unsigned neuron ) const\n\n{\n\n return _symbolicLbOfUb[neuron];\n\n}\n\n\n\ndouble Layer::getSymbolicUbOfUb( unsigned neuron ) const\n\n{\n\n return _symbolicUbOfUb[neuron];\n\n}\n\n\n\nvoid Layer::freeMemoryIfNeeded()\n\n{\n\n for ( const auto &weights : _layerToWeights )\n\n delete[] weights.second;\n\n _layerToWeights.clear();\n\n\n\n for ( const auto &weights : _layerToPositiveWeights )\n\n delete[] weights.second;\n", "file_path": "src/nlr/Layer.cpp", "rank": 50, "score": 106043.72171111421 }, { "content": " _eliminatedNeurons[neuron] = value;\n\n _lb[neuron] = value;\n\n _ub[neuron] = value;\n\n _neuronToVariable.erase( _variableToNeuron[variable] );\n\n _variableToNeuron.erase( variable );\n\n}\n\n\n\nvoid Layer::updateVariableIndices( const Map<unsigned, unsigned> &oldIndexToNewIndex,\n\n const Map<unsigned, unsigned> &mergedVariables )\n\n{\n\n // First, do a pass to handle any merged variables\n\n auto neuronIt = _neuronToVariable.begin();\n\n while ( neuronIt != _neuronToVariable.end() )\n\n {\n\n unsigned variable = neuronIt->second;\n\n while ( mergedVariables.exists( variable ) )\n\n {\n\n neuronIt->second = mergedVariables[variable];\n\n variable = neuronIt->second;\n\n }\n", "file_path": "src/nlr/Layer.cpp", "rank": 51, "score": 106042.0427344853 }, { "content": " _symbolicLowerBias[i] = 0;\n\n _symbolicUpperBias[i] = 0;\n\n }\n\n }\n\n\n\n if ( _symbolicLbOfUb[i] < 0 )\n\n _symbolicLbOfUb[i] = 0;\n\n\n\n /*\n\n We now have the tightest bounds we can for the relu\n\n variable. If they are tigheter than what was previously\n\n known, store them.\n\n */\n\n if ( _lb[i] < _symbolicLbOfLb[i] )\n\n {\n\n _lb[i] = _symbolicLbOfLb[i];\n\n _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _lb[i], Tightening::LB ) );\n\n }\n\n\n\n if ( _ub[i] > _symbolicUbOfUb[i] )\n", "file_path": "src/nlr/Layer.cpp", "rank": 52, "score": 106041.85254563889 }, { "content": " _lb[neuron] = bound;\n\n}\n\n\n\nvoid Layer::setUb( unsigned neuron, double bound )\n\n{\n\n ASSERT( !_eliminatedNeurons.exists( neuron ) );\n\n _ub[neuron] = bound;\n\n}\n\n\n\nvoid Layer::computeIntervalArithmeticBounds()\n\n{\n\n ASSERT( _type != INPUT );\n\n\n\n switch ( _type )\n\n {\n\n case WEIGHTED_SUM:\n\n computeIntervalArithmeticBoundsForWeightedSum();\n\n break;\n\n\n\n case RELU:\n", "file_path": "src/nlr/Layer.cpp", "rank": 53, "score": 106041.33763729206 }, { "content": "\n\ndouble Layer::getLb( unsigned neuron ) const\n\n{\n\n if ( _eliminatedNeurons.exists( neuron ) )\n\n return _eliminatedNeurons[neuron];\n\n\n\n return _lb[neuron];\n\n}\n\n\n\ndouble Layer::getUb( unsigned neuron ) const\n\n{\n\n if ( _eliminatedNeurons.exists( neuron ) )\n\n return _eliminatedNeurons[neuron];\n\n\n\n return _ub[neuron];\n\n}\n\n\n\nvoid Layer::setLb( unsigned neuron, double bound )\n\n{\n\n ASSERT( !_eliminatedNeurons.exists( neuron ) );\n", "file_path": "src/nlr/Layer.cpp", "rank": 54, "score": 106040.60365330632 }, { "content": " return \"MAX\";\n\n break;\n\n\n\n default:\n\n return \"UNKNOWN TYPE\";\n\n break;\n\n }\n\n}\n\n\n\nvoid Layer::dump() const\n\n{\n\n printf( \"\\nDumping info for layer %u (%s):\\n\", _layerIndex, typeToString( _type ).ascii() );\n\n printf( \"\\tNeurons:\\n\" );\n\n\n\n switch ( _type )\n\n {\n\n case INPUT:\n\n printf( \"\\t\\t\" );\n\n for ( unsigned i = 0; i < _size; ++i )\n\n printf( \"x%u \", _neuronToVariable[i] );\n", "file_path": "src/nlr/Layer.cpp", "rank": 55, "score": 106038.42710612746 }, { "content": " ASSERT( _neuronToVariable.exists( neuron ) );\n\n return _neuronToVariable[neuron];\n\n}\n\n\n\nunsigned Layer::variableToNeuron( unsigned variable ) const\n\n{\n\n ASSERT( _variableToNeuron.exists( variable ) );\n\n return _variableToNeuron[variable];\n\n}\n\n\n\nbool Layer::neuronEliminated( unsigned neuron ) const\n\n{\n\n return _eliminatedNeurons.exists( neuron );\n\n}\n\n\n\ndouble Layer::getEliminatedNeuronValue( unsigned neuron ) const\n\n{\n\n ASSERT( _eliminatedNeurons.exists( neuron ) );\n\n return _eliminatedNeurons[neuron];\n\n}\n\n\n\n} // namespace NLR\n", "file_path": "src/nlr/Layer.cpp", "rank": 56, "score": 106036.53109435266 }, { "content": "\n\n for ( unsigned i = 0; i < _size; ++i )\n\n {\n\n newLb[i] = _bias[i];\n\n newUb[i] = _bias[i];\n\n }\n\n\n\n for ( const auto &sourceLayerEntry : _sourceLayers )\n\n {\n\n unsigned sourceLayerIndex = sourceLayerEntry.first;\n\n unsigned sourceLayerSize = sourceLayerEntry.second;\n\n const Layer *sourceLayer = _layerOwner->getLayer( sourceLayerIndex );\n\n const double *weights = _layerToWeights[sourceLayerIndex];\n\n\n\n for ( unsigned i = 0; i < _size; ++i )\n\n {\n\n for ( unsigned j = 0; j < sourceLayerSize; ++j )\n\n {\n\n double previousLb = sourceLayer->getLb( j );\n\n double previousUb = sourceLayer->getUb( j );\n", "file_path": "src/nlr/Layer.cpp", "rank": 57, "score": 106036.45973320541 }, { "content": " for ( unsigned i = 0; i < _size; ++i )\n\n {\n\n if ( _eliminatedNeurons.exists( i ) )\n\n {\n\n _symbolicLowerBias[i] = _eliminatedNeurons[i];\n\n _symbolicUpperBias[i] = _eliminatedNeurons[i];\n\n\n\n _symbolicLbOfLb[i] = _eliminatedNeurons[i];\n\n _symbolicUbOfLb[i] = _eliminatedNeurons[i];\n\n _symbolicLbOfUb[i] = _eliminatedNeurons[i];\n\n _symbolicUbOfUb[i] = _eliminatedNeurons[i];\n\n }\n\n }\n\n\n\n for ( const auto &sourceLayerEntry : _sourceLayers )\n\n {\n\n unsigned sourceLayerIndex = sourceLayerEntry.first;\n\n unsigned sourceLayerSize = sourceLayerEntry.second;\n\n const Layer *sourceLayer = _layerOwner->getLayer( sourceLayerEntry.first );\n\n\n", "file_path": "src/nlr/Layer.cpp", "rank": 58, "score": 106036.34203236211 }, { "content": " case ABSOLUTE_VALUE:\n\n computeSymbolicBoundsForAbsoluteValue();\n\n break;\n\n\n\n case MAX:\n\n\n\n default:\n\n printf( \"Error! Actiation type %u unsupported\\n\", _type );\n\n throw MarabouError( MarabouError::NETWORK_LEVEL_REASONER_ACTIVATION_NOT_SUPPORTED );\n\n break;\n\n }\n\n}\n\n\n\nvoid Layer::comptueSymbolicBoundsForInput()\n\n{\n\n std::fill_n( _symbolicLb, _size * _inputLayerSize, 0 );\n\n std::fill_n( _symbolicUb, _size * _inputLayerSize, 0 );\n\n\n\n // For the input layer, the bounds are just the identity polynomials\n\n for ( unsigned i = 0; i < _size; ++i )\n", "file_path": "src/nlr/Layer.cpp", "rank": 59, "score": 106035.90723355985 }, { "content": " }\n\n }\n\n }\n\n\n\n /*\n\n We now have the symbolic representation for the current\n\n layer. Next, we compute new lower and upper bounds for\n\n it. For each of these bounds, we compute an upper bound and\n\n a lower bound.\n\n */\n\n for ( unsigned i = 0; i < _size; ++i )\n\n {\n\n if ( _eliminatedNeurons.exists( i ) )\n\n continue;\n\n\n\n _symbolicLbOfLb[i] = _symbolicLowerBias[i];\n\n _symbolicUbOfLb[i] = _symbolicLowerBias[i];\n\n _symbolicLbOfUb[i] = _symbolicUpperBias[i];\n\n _symbolicUbOfUb[i] = _symbolicUpperBias[i];\n\n\n", "file_path": "src/nlr/Layer.cpp", "rank": 60, "score": 106035.64662706638 }, { "content": " _symbolicUbOfLb[i] = _eliminatedNeurons[i];\n\n _symbolicLbOfUb[i] = _eliminatedNeurons[i];\n\n _symbolicUbOfUb[i] = _eliminatedNeurons[i];\n\n\n\n continue;\n\n }\n\n\n\n AbsoluteValueConstraint::PhaseStatus absPhase = AbsoluteValueConstraint::PHASE_NOT_FIXED;\n\n\n\n ASSERT( _neuronToActivationSources.exists( i ) );\n\n NeuronIndex sourceIndex = *_neuronToActivationSources[i].begin();\n\n const Layer *sourceLayer = _layerOwner->getLayer( sourceIndex._layer );\n\n\n\n unsigned sourceLayerSize = sourceLayer->getSize();\n\n const double *sourceSymbolicLb = sourceLayer->getSymbolicLb();\n\n const double *sourceSymbolicUb = sourceLayer->getSymbolicUb();\n\n\n\n for ( unsigned j = 0; j < _inputLayerSize; ++j )\n\n {\n\n _symbolicLb[j * _size + i] = sourceSymbolicLb[j * sourceLayerSize + sourceIndex._neuron];\n", "file_path": "src/nlr/Layer.cpp", "rank": 61, "score": 106034.55923975901 }, { "content": " }\n\n}\n\n\n\nvoid Layer::computeSymbolicBoundsForRelu()\n\n{\n\n std::fill_n( _symbolicLb, _size * _inputLayerSize, 0 );\n\n std::fill_n( _symbolicUb, _size * _inputLayerSize, 0 );\n\n\n\n for ( unsigned i = 0; i < _size; ++i )\n\n {\n\n if ( _eliminatedNeurons.exists( i ) )\n\n {\n\n _symbolicLowerBias[i] = _eliminatedNeurons[i];\n\n _symbolicUpperBias[i] = _eliminatedNeurons[i];\n\n\n\n _symbolicLbOfLb[i] = _eliminatedNeurons[i];\n\n _symbolicUbOfLb[i] = _eliminatedNeurons[i];\n\n _symbolicLbOfUb[i] = _eliminatedNeurons[i];\n\n _symbolicUbOfUb[i] = _eliminatedNeurons[i];\n\n }\n", "file_path": "src/nlr/Layer.cpp", "rank": 62, "score": 106034.45045836647 }, { "content": " _assignment[eliminated.first] = eliminated.second;\n\n}\n\n\n\nvoid Layer::addSourceLayer( unsigned layerNumber, unsigned layerSize )\n\n{\n\n ASSERT( _type != INPUT );\n\n\n\n if ( _sourceLayers.exists( layerNumber ) )\n\n return;\n\n\n\n _sourceLayers[layerNumber] = layerSize;\n\n\n\n if ( _type == WEIGHTED_SUM )\n\n {\n\n _layerToWeights[layerNumber] = new double[layerSize * _size];\n\n _layerToPositiveWeights[layerNumber] = new double[layerSize * _size];\n\n _layerToNegativeWeights[layerNumber] = new double[layerSize * _size];\n\n\n\n std::fill_n( _layerToWeights[layerNumber], layerSize * _size, 0 );\n\n std::fill_n( _layerToPositiveWeights[layerNumber], layerSize * _size, 0 );\n", "file_path": "src/nlr/Layer.cpp", "rank": 63, "score": 106032.96221089749 }, { "content": " /*\n\n Perform the multiplication.\n\n\n\n newUB = oldUB * posWeights + oldLB * negWeights\n\n newLB = oldUB * negWeights + oldLB * posWeights\n\n */\n\n\n\n for ( unsigned i = 0; i < _inputLayerSize; ++i )\n\n {\n\n for ( unsigned j = 0; j < _size; ++j )\n\n {\n\n if ( _eliminatedNeurons.exists( j ) )\n\n continue;\n\n\n\n for ( unsigned k = 0; k < sourceLayerSize; ++k )\n\n {\n\n _symbolicLb[i * _size + j] +=\n\n sourceLayer->getSymbolicUb()[i * sourceLayerSize + k] *\n\n _layerToNegativeWeights[sourceLayerIndex][k * _size + j];\n\n\n", "file_path": "src/nlr/Layer.cpp", "rank": 64, "score": 106032.86556827456 }, { "content": "\n\n ASSERT( _neuronToActivationSources.exists( i ) );\n\n NeuronIndex sourceIndex = *_neuronToActivationSources[i].begin();\n\n const Layer *sourceLayer = _layerOwner->getLayer( sourceIndex._layer );\n\n\n\n /*\n\n A ReLU initially \"inherits\" the symbolic bounds computed\n\n for its input variable\n\n */\n\n unsigned sourceLayerSize = sourceLayer->getSize();\n\n const double *sourceSymbolicLb = sourceLayer->getSymbolicLb();\n\n const double *sourceSymbolicUb = sourceLayer->getSymbolicUb();\n\n\n\n for ( unsigned j = 0; j < _inputLayerSize; ++j )\n\n {\n\n _symbolicLb[j * _size + i] = sourceSymbolicLb[j * sourceLayerSize + sourceIndex._neuron];\n\n _symbolicUb[j * _size + i] = sourceSymbolicUb[j * sourceLayerSize + sourceIndex._neuron];\n\n }\n\n _symbolicLowerBias[i] = sourceLayer->getSymbolicLowerBias()[sourceIndex._neuron];\n\n _symbolicUpperBias[i] = sourceLayer->getSymbolicUpperBias()[sourceIndex._neuron];\n", "file_path": "src/nlr/Layer.cpp", "rank": 65, "score": 106032.34003288492 }, { "content": " // Lower bound\n\n if ( _symbolicUbOfLb[i] <= 0 )\n\n {\n\n for ( unsigned j = 0; j < _inputLayerSize; ++j )\n\n _symbolicLb[j * _size + i] = 0;\n\n\n\n _symbolicLowerBias[i] = 0;\n\n }\n\n else\n\n {\n\n for ( unsigned j = 0; j < _inputLayerSize; ++j )\n\n _symbolicLb[j * _size + i] =\n\n _symbolicLb[j * _size + i] * _symbolicUbOfLb[i] / ( _symbolicUbOfLb[i] - _symbolicLbOfLb[i] );\n\n\n\n _symbolicLowerBias[i] = _symbolicLowerBias[i] * _symbolicUbOfLb[i] / ( _symbolicUbOfLb[i] - _symbolicLbOfLb[i] );\n\n }\n\n\n\n _symbolicLbOfLb[i] = 0;\n\n }\n\n else\n", "file_path": "src/nlr/Layer.cpp", "rank": 66, "score": 106032.08653445072 }, { "content": "{\n\n return _neuronToActivationSources[neuron];\n\n}\n\n\n\nunsigned Layer::getSize() const\n\n{\n\n return _size;\n\n}\n\n\n\nLayer::Type Layer::getLayerType() const\n\n{\n\n return _type;\n\n}\n\n\n\nvoid Layer::setNeuronVariable( unsigned neuron, unsigned variable )\n\n{\n\n ASSERT( !_eliminatedNeurons.exists( neuron ) );\n\n\n\n _neuronToVariable[neuron] = variable;\n\n _variableToNeuron[variable] = neuron;\n", "file_path": "src/nlr/Layer.cpp", "rank": 67, "score": 106031.03796522522 }, { "content": " {\n\n // If we got here, we know that lbOfLb < 0 < ubOfUb. In this case,\n\n // we do naive concretization: lb is 0, ub is the max between\n\n // -lb and ub of the input neuron\n\n for ( unsigned j = 0; j < _inputLayerSize; ++j )\n\n {\n\n _symbolicLb[j * _size + i] = 0;\n\n _symbolicUb[j * _size + i] = 0;\n\n }\n\n\n\n _symbolicLowerBias[i] = 0;\n\n _symbolicUpperBias[i] = FloatUtils::max( -sourceLb, sourceUb );\n\n\n\n _symbolicLbOfLb[i] = 0;\n\n _symbolicUbOfLb[i] = _symbolicUpperBias[i];\n\n _symbolicLbOfUb[i] = 0;\n\n _symbolicUbOfUb[i] = _symbolicUpperBias[i];\n\n }\n\n else\n\n {\n", "file_path": "src/nlr/Layer.cpp", "rank": 68, "score": 106030.93797237042 }, { "content": " }\n\n else\n\n {\n\n // Index has changed\n\n neuronIt->second = oldIndexToNewIndex[variable];\n\n }\n\n\n\n ++neuronIt;\n\n continue;\n\n }\n\n }\n\n}\n\n\n\nunsigned Layer::getLayerIndex() const\n\n{\n\n return _layerIndex;\n\n}\n\n\n\nLayer::Layer( const Layer *other )\n\n : _bias( NULL )\n", "file_path": "src/nlr/Layer.cpp", "rank": 69, "score": 106030.38658954343 }, { "content": " computeIntervalArithmeticBoundsForRelu();\n\n break;\n\n\n\n case ABSOLUTE_VALUE:\n\n computeIntervalArithmeticBoundsForAbs();\n\n break;\n\n\n\n case MAX:\n\n\n\n default:\n\n printf( \"Error! Actiation type %u unsupported\\n\", _type );\n\n throw MarabouError( MarabouError::NETWORK_LEVEL_REASONER_ACTIVATION_NOT_SUPPORTED );\n\n break;\n\n }\n\n}\n\n\n\nvoid Layer::computeIntervalArithmeticBoundsForWeightedSum()\n\n{\n\n double *newLb = new double[_size];\n\n double *newUb = new double[_size];\n", "file_path": "src/nlr/Layer.cpp", "rank": 70, "score": 106030.02637014166 }, { "content": " {\n\n // The phase of this ReLU is fixed!\n\n if ( reluPhase == ReluConstraint::PHASE_ACTIVE )\n\n {\n\n // Active ReLU, bounds are propagated as is\n\n }\n\n else\n\n {\n\n // Inactive ReLU, returns zero\n\n _symbolicLbOfLb[i] = 0;\n\n _symbolicUbOfLb[i] = 0;\n\n _symbolicLbOfUb[i] = 0;\n\n _symbolicUbOfUb[i] = 0;\n\n\n\n for ( unsigned j = 0; j < _inputLayerSize; ++j )\n\n {\n\n _symbolicUb[j * _size + i] = 0;\n\n _symbolicLb[j * _size + i] = 0;\n\n }\n\n\n", "file_path": "src/nlr/Layer.cpp", "rank": 71, "score": 106029.97704935653 }, { "content": "{\n\n freeMemoryIfNeeded();\n\n}\n\n\n\nvoid Layer::setLayerOwner( LayerOwner *layerOwner )\n\n{\n\n _layerOwner = layerOwner;\n\n}\n\n\n\nLayer::Layer( unsigned index, Type type, unsigned size, LayerOwner *layerOwner )\n\n : _layerIndex( index )\n\n , _type( type )\n\n , _size( size )\n\n , _layerOwner( layerOwner )\n\n , _bias( NULL )\n\n , _assignment( NULL )\n\n , _lb( NULL )\n\n , _ub( NULL )\n\n , _inputLayerSize( 0 )\n\n , _symbolicLb( NULL )\n", "file_path": "src/nlr/Layer.cpp", "rank": 72, "score": 106029.57229478401 }, { "content": " {\n\n // If we got here, we know that lbLb < 0 and ubUb\n\n // > 0 There are four possible cases, depending on\n\n // whether ubLb and lbUb are negative or positive\n\n // (see Neurify paper, page 14).\n\n\n\n // Upper bound\n\n if ( _symbolicLbOfUb[i] <= 0 )\n\n {\n\n // lbOfUb[i] < 0 < ubOfUb[i]\n\n // Concretize the upper bound using the Ehler's-like approximation\n\n for ( unsigned j = 0; j < _inputLayerSize; ++j )\n\n _symbolicUb[j * _size + i] =\n\n _symbolicUb[j * _size + i] * _symbolicUbOfUb[i] / ( _symbolicUbOfUb[i] - _symbolicLbOfUb[i] );\n\n\n\n // Do the same for the bias, and then adjust\n\n _symbolicUpperBias[i] = _symbolicUpperBias[i] * _symbolicUbOfUb[i] / ( _symbolicUbOfUb[i] - _symbolicLbOfUb[i] );\n\n _symbolicUpperBias[i] -= _symbolicLbOfUb[i] * _symbolicUbOfUb[i] / ( _symbolicUbOfUb[i] - _symbolicLbOfUb[i] );\n\n }\n\n\n", "file_path": "src/nlr/Layer.cpp", "rank": 73, "score": 106029.1311066567 }, { "content": "\n\n for ( unsigned i = 0; i < _size; ++i )\n\n {\n\n if ( _eliminatedNeurons.exists( i ) )\n\n {\n\n printf( \"\\t\\tNeuron %u = %+.4lf\\t[ELIMINATED]\\n\", i, _eliminatedNeurons[i] );\n\n continue;\n\n }\n\n\n\n printf( \"\\t\\tSources for x%u: \", _neuronToVariable[i] );\n\n for ( const auto &source : _neuronToActivationSources[i] )\n\n {\n\n const Layer *sourceLayer = _layerOwner->getLayer( source._layer );\n\n if ( sourceLayer->_neuronToVariable.exists( source._neuron ) )\n\n printf( \"x%u \", sourceLayer->_neuronToVariable[source._neuron] );\n\n else\n\n printf( \"Neuron_%u (eliminated)\", source._neuron );\n\n }\n\n\n\n printf( \"\\n\" );\n", "file_path": "src/nlr/Layer.cpp", "rank": 74, "score": 106028.7173216577 }, { "content": "\n\n printf( \"\\n\\n\" );\n\n break;\n\n\n\n case WEIGHTED_SUM:\n\n\n\n for ( unsigned i = 0; i < _size; ++i )\n\n {\n\n if ( _eliminatedNeurons.exists( i ) )\n\n {\n\n printf( \"\\t\\tNeuron %u = %+.4lf\\t[ELIMINATED]\\n\", i, _eliminatedNeurons[i] );\n\n continue;\n\n }\n\n\n\n printf( \"\\t\\tx%u = %+.4lf\\n\", _neuronToVariable[i], _bias[i] );\n\n for ( const auto &sourceLayerEntry : _sourceLayers )\n\n {\n\n printf( \"\\t\\t\\t\" );\n\n const Layer *sourceLayer = _layerOwner->getLayer( sourceLayerEntry.first );\n\n for ( unsigned j = 0; j < sourceLayer->getSize(); ++j )\n", "file_path": "src/nlr/Layer.cpp", "rank": 75, "score": 106028.610406062 }, { "content": " _ub = new double[_size];\n\n\n\n std::fill_n( _lb, _size, 0 );\n\n std::fill_n( _ub, _size, 0 );\n\n\n\n _assignment = new double[_size];\n\n\n\n _inputLayerSize = ( _type == INPUT ) ? _size : _layerOwner->getLayer( 0 )->getSize();\n\n if ( GlobalConfiguration::USE_SYMBOLIC_BOUND_TIGHTENING )\n\n {\n\n _symbolicLb = new double[_size * _inputLayerSize];\n\n _symbolicUb = new double[_size * _inputLayerSize];\n\n\n\n std::fill_n( _symbolicLb, _size * _inputLayerSize, 0 );\n\n std::fill_n( _symbolicUb, _size * _inputLayerSize, 0 );\n\n\n\n _symbolicLowerBias = new double[_size];\n\n _symbolicUpperBias = new double[_size];\n\n\n\n std::fill_n( _symbolicLowerBias, _size, 0 );\n", "file_path": "src/nlr/Layer.cpp", "rank": 76, "score": 106028.51136979625 }, { "content": " std::fill_n( _symbolicUpperBias, _size, 0 );\n\n\n\n _symbolicLbOfLb = new double[_size];\n\n _symbolicUbOfLb = new double[_size];\n\n _symbolicLbOfUb = new double[_size];\n\n _symbolicUbOfUb = new double[_size];\n\n\n\n std::fill_n( _symbolicLbOfLb, _size, 0 );\n\n std::fill_n( _symbolicUbOfLb, _size, 0 );\n\n std::fill_n( _symbolicLbOfUb, _size, 0 );\n\n std::fill_n( _symbolicUbOfUb, _size, 0 );\n\n }\n\n}\n\n\n\nvoid Layer::setAssignment( const double *values )\n\n{\n\n ASSERT( _eliminatedNeurons.empty() );\n\n memcpy( _assignment, values, _size * sizeof(double) );\n\n}\n\n\n", "file_path": "src/nlr/Layer.cpp", "rank": 77, "score": 106028.153358254 }, { "content": " if ( _symbolicUbOfLb )\n\n {\n\n delete[] _symbolicUbOfLb;\n\n _symbolicUbOfLb = NULL;\n\n }\n\n\n\n if ( _symbolicLbOfUb )\n\n {\n\n delete[] _symbolicLbOfUb;\n\n _symbolicLbOfUb = NULL;\n\n }\n\n\n\n if ( _symbolicUbOfUb )\n\n {\n\n delete[] _symbolicUbOfUb;\n\n _symbolicUbOfUb = NULL;\n\n }\n\n}\n\n\n\nString Layer::typeToString( Type type )\n", "file_path": "src/nlr/Layer.cpp", "rank": 78, "score": 106027.81624400995 }, { "content": " for ( unsigned j = 0; j < _inputLayerSize; ++j )\n\n {\n\n double inputLb = _layerOwner->getLayer( 0 )->getLb( j );\n\n double inputUb = _layerOwner->getLayer( 0 )->getUb( j );\n\n\n\n double entry = _symbolicLb[j * _size + i];\n\n\n\n if ( entry >= 0 )\n\n {\n\n _symbolicLbOfLb[i] += ( entry * inputLb );\n\n _symbolicUbOfLb[i] += ( entry * inputUb );\n\n }\n\n else\n\n {\n\n _symbolicLbOfLb[i] += ( entry * inputUb );\n\n _symbolicUbOfLb[i] += ( entry * inputLb );\n\n }\n\n\n\n entry = _symbolicUb[j * _size + i];\n\n\n", "file_path": "src/nlr/Layer.cpp", "rank": 79, "score": 106027.73408796151 }, { "content": "}\n\n\n\nconst double *Layer::getSymbolicLowerBias() const\n\n{\n\n return _symbolicLowerBias;\n\n}\n\n\n\nconst double *Layer::getSymbolicUpperBias() const\n\n{\n\n return _symbolicUpperBias;\n\n}\n\n\n\ndouble Layer::getSymbolicLbOfLb( unsigned neuron ) const\n\n{\n\n return _symbolicLbOfLb[neuron];\n\n}\n\n\n\ndouble Layer::getSymbolicUbOfLb( unsigned neuron ) const\n\n{\n\n return _symbolicUbOfLb[neuron];\n", "file_path": "src/nlr/Layer.cpp", "rank": 80, "score": 106027.66976141243 }, { "content": "{\n\n return _bias[neuron];\n\n}\n\n\n\nvoid Layer::addActivationSource( unsigned sourceLayer, unsigned sourceNeuron, unsigned targetNeuron )\n\n{\n\n ASSERT( _type == RELU || _type == ABSOLUTE_VALUE || _type == MAX );\n\n\n\n if ( !_neuronToActivationSources.exists( targetNeuron ) )\n\n _neuronToActivationSources[targetNeuron] = List<NeuronIndex>();\n\n\n\n _neuronToActivationSources[targetNeuron].append( NeuronIndex( sourceLayer, sourceNeuron ) );\n\n\n\n DEBUG({\n\n if ( _type == RELU || _type == ABSOLUTE_VALUE )\n\n ASSERT( _neuronToActivationSources[targetNeuron].size() == 1 );\n\n });\n\n}\n\n\n\nList<NeuronIndex> Layer::getActivationSources( unsigned neuron ) const\n", "file_path": "src/nlr/Layer.cpp", "rank": 81, "score": 106027.55402474334 }, { "content": " if ( other->_bias )\n\n memcpy( _bias, other->_bias, sizeof(double) * _size );\n\n\n\n _neuronToActivationSources = other->_neuronToActivationSources;\n\n\n\n _neuronToVariable = other->_neuronToVariable;\n\n _variableToNeuron = other->_variableToNeuron;\n\n _eliminatedNeurons = other->_eliminatedNeurons;\n\n\n\n _inputLayerSize = other->_inputLayerSize;\n\n}\n\n\n\nconst double *Layer::getSymbolicLb() const\n\n{\n\n return _symbolicLb;\n\n}\n\n\n\nconst double *Layer::getSymbolicUb() const\n\n{\n\n return _symbolicUb;\n", "file_path": "src/nlr/Layer.cpp", "rank": 82, "score": 106027.19033026602 }, { "content": " // The phase of this AbsoluteValueConstraint is fixed!\n\n if ( absPhase == AbsoluteValueConstraint::PHASE_POSITIVE )\n\n {\n\n // Positive AbsoluteValue, bounds are propagated as is\n\n }\n\n else\n\n {\n\n // Negative AbsoluteValue, bounds are negated and flipped\n\n double temp;\n\n for ( unsigned j = 0; j < _inputLayerSize; ++j )\n\n {\n\n temp = _symbolicUb[j * _size + i];\n\n _symbolicUb[j * _size + i] = -_symbolicLb[j * _size + i];\n\n _symbolicLb[j * _size + i] = -temp;\n\n }\n\n\n\n temp = _symbolicLowerBias[i];\n\n _symbolicLowerBias[i] = -_symbolicUpperBias[i];\n\n _symbolicUpperBias[i] = -temp;\n\n\n", "file_path": "src/nlr/Layer.cpp", "rank": 83, "score": 106027.16136704567 }, { "content": " }\n\n\n\n printf( \"\\n\" );\n\n break;\n\n }\n\n}\n\n\n\nbool Layer::neuronHasVariable( unsigned neuron ) const\n\n{\n\n ASSERT( _neuronToVariable.exists( neuron ) || _eliminatedNeurons.exists( neuron ) );\n\n return _neuronToVariable.exists( neuron );\n\n}\n\n\n\nunsigned Layer::neuronToVariable( unsigned neuron ) const\n\n{\n\n DEBUG({\n\n if ( !_neuronToVariable.exists( neuron ) )\n\n ASSERT( _eliminatedNeurons.exists( neuron ) );\n\n })\n\n\n", "file_path": "src/nlr/Layer.cpp", "rank": 84, "score": 106027.14932377971 }, { "content": "/********************* */\n\n/*! \\file LayerOwner.h\n\n ** \\verbatim\n\n ** Top contributors (to current version):\n\n ** Guy Katz\n\n ** This file is part of the Marabou project.\n\n ** Copyright (c) 2017-2019 by the authors listed in the file AUTHORS\n\n ** in the top-level source directory) and their institutional affiliations.\n\n ** All rights reserved. See the file COPYING in the top-level source\n\n ** directory for licensing information.\\endverbatim\n\n **\n\n ** [[ Add lengthier description here ]]\n\n\n\n**/\n\n\n\n#ifndef __LayerOwner_h__\n\n#define __LayerOwner_h__\n\n\n\n#include \"Tightening.h\"\n\n\n\nnamespace NLR {\n\n\n", "file_path": "src/nlr/LayerOwner.h", "rank": 85, "score": 106026.32691431935 }, { "content": " _symbolicLb[i * _size + j] +=\n\n sourceLayer->getSymbolicLb()[i * sourceLayerSize + k] *\n\n _layerToPositiveWeights[sourceLayerIndex][k * _size + j];\n\n\n\n _symbolicUb[i * _size + j] +=\n\n sourceLayer->getSymbolicUb()[i * sourceLayerSize + k] *\n\n _layerToPositiveWeights[sourceLayerIndex][k * _size + j];\n\n\n\n _symbolicUb[i * _size + j] +=\n\n sourceLayer->getSymbolicLb()[i * sourceLayerSize + k] *\n\n _layerToNegativeWeights[sourceLayerIndex][k * _size + j];\n\n }\n\n }\n\n }\n\n\n\n /*\n\n Compute the biases for the new layer\n\n */\n\n for ( unsigned j = 0; j < _size; ++j )\n\n {\n", "file_path": "src/nlr/Layer.cpp", "rank": 86, "score": 106026.04175950572 }, { "content": " double weight = weights[j * _size + i];\n\n\n\n if ( weight > 0 )\n\n {\n\n newLb[i] += weight * previousLb;\n\n newUb[i] += weight * previousUb;\n\n }\n\n else\n\n {\n\n newLb[i] += weight * previousUb;\n\n newUb[i] += weight * previousLb;\n\n }\n\n }\n\n }\n\n }\n\n\n\n for ( unsigned i = 0; i < _size; ++i )\n\n {\n\n if ( _eliminatedNeurons.exists( i ) )\n\n continue;\n", "file_path": "src/nlr/Layer.cpp", "rank": 87, "score": 106025.85247339198 }, { "content": " , _symbolicUb( NULL )\n\n , _symbolicLowerBias( NULL )\n\n , _symbolicUpperBias( NULL )\n\n , _symbolicLbOfLb( NULL )\n\n , _symbolicUbOfLb( NULL )\n\n , _symbolicLbOfUb( NULL )\n\n , _symbolicUbOfUb( NULL )\n\n{\n\n allocateMemory();\n\n}\n\n\n\nvoid Layer::allocateMemory()\n\n{\n\n if ( _type == WEIGHTED_SUM )\n\n {\n\n _bias = new double[_size];\n\n std::fill_n( _bias, _size, 0 );\n\n }\n\n\n\n _lb = new double[_size];\n", "file_path": "src/nlr/Layer.cpp", "rank": 88, "score": 106024.85432218447 }, { "content": " std::fill_n( _layerToNegativeWeights[layerNumber], layerSize * _size, 0 );\n\n }\n\n}\n\n\n\nconst Map<unsigned, unsigned> &Layer::getSourceLayers() const\n\n{\n\n return _sourceLayers;\n\n}\n\n\n\nvoid Layer::setWeight( unsigned sourceLayer, unsigned sourceNeuron, unsigned targetNeuron, double weight )\n\n{\n\n unsigned index = sourceNeuron * _size + targetNeuron;\n\n _layerToWeights[sourceLayer][index] = weight;\n\n\n\n if ( weight > 0 )\n\n {\n\n _layerToPositiveWeights[sourceLayer][index] = weight;\n\n _layerToNegativeWeights[sourceLayer][index] = 0;\n\n }\n\n else\n", "file_path": "src/nlr/Layer.cpp", "rank": 89, "score": 106024.54626519998 }, { "content": " _layerToPositiveWeights.clear();\n\n\n\n for ( const auto &weights : _layerToNegativeWeights )\n\n delete[] weights.second;\n\n _layerToNegativeWeights.clear();\n\n\n\n if ( _bias )\n\n {\n\n delete[] _bias;\n\n _bias = NULL;\n\n }\n\n\n\n if ( _assignment )\n\n {\n\n delete[] _assignment;\n\n _assignment = NULL;\n\n }\n\n\n\n if ( _lb )\n\n {\n", "file_path": "src/nlr/Layer.cpp", "rank": 90, "score": 106024.26722376607 }, { "content": " for ( auto &sourceLayerEntry : _sourceLayers )\n\n {\n\n const Layer *sourceLayer = _layerOwner->getLayer( sourceLayerEntry.first );\n\n const double *sourceAssignment = sourceLayer->getAssignment();\n\n unsigned sourceSize = sourceLayerEntry.second;\n\n const double *weights = _layerToWeights[sourceLayerEntry.first];\n\n\n\n for ( unsigned i = 0; i < sourceSize; ++i )\n\n for ( unsigned j = 0; j < _size; ++j )\n\n _assignment[j] += ( sourceAssignment[i] * weights[i * _size + j] );\n\n }\n\n }\n\n\n\n else if ( _type == RELU )\n\n {\n\n for ( unsigned i = 0; i < _size; ++i )\n\n {\n\n NeuronIndex sourceIndex = *_neuronToActivationSources[i].begin();\n\n double inputValue = _layerOwner->getLayer( sourceIndex._layer )->getAssignment( sourceIndex._neuron );\n\n\n", "file_path": "src/nlr/Layer.cpp", "rank": 91, "score": 106023.44890986964 }, { "content": "\n\n double sourceLb = sourceLayer->getLb( sourceIndex._neuron );\n\n double sourceUb = sourceLayer->getUb( sourceIndex._neuron );\n\n\n\n _symbolicLbOfLb[i] = sourceLayer->getSymbolicLbOfLb( sourceIndex._neuron );\n\n _symbolicUbOfLb[i] = sourceLayer->getSymbolicUbOfLb( sourceIndex._neuron );\n\n _symbolicLbOfUb[i] = sourceLayer->getSymbolicLbOfUb( sourceIndex._neuron );\n\n _symbolicUbOfUb[i] = sourceLayer->getSymbolicUbOfUb( sourceIndex._neuron );\n\n\n\n // Has the b variable been fixed?\n\n if ( !FloatUtils::isNegative( sourceLb ) )\n\n {\n\n reluPhase = ReluConstraint::PHASE_ACTIVE;\n\n }\n\n else if ( !FloatUtils::isPositive( sourceUb ) )\n\n {\n\n reluPhase = ReluConstraint::PHASE_INACTIVE;\n\n }\n\n\n\n if ( reluPhase == ReluConstraint::PHASE_NOT_FIXED )\n", "file_path": "src/nlr/Layer.cpp", "rank": 92, "score": 106023.165862636 }, { "content": " , _assignment( NULL )\n\n , _lb( NULL )\n\n , _ub( NULL )\n\n , _inputLayerSize( 0 )\n\n , _symbolicLb( NULL )\n\n , _symbolicUb( NULL )\n\n , _symbolicLowerBias( NULL )\n\n , _symbolicUpperBias( NULL )\n\n , _symbolicLbOfLb( NULL )\n\n , _symbolicUbOfLb( NULL )\n\n , _symbolicLbOfUb( NULL )\n\n , _symbolicUbOfUb( NULL )\n\n{\n\n _layerIndex = other->_layerIndex;\n\n _type = other->_type;\n\n _size = other->_size;\n\n _layerOwner = other->_layerOwner;\n\n\n\n allocateMemory();\n\n\n", "file_path": "src/nlr/Layer.cpp", "rank": 93, "score": 106023.16200323642 }, { "content": " _symbolicUb[j * _size + i] = sourceSymbolicUb[j * sourceLayerSize + sourceIndex._neuron];\n\n }\n\n\n\n _symbolicLowerBias[i] = sourceLayer->getSymbolicLowerBias()[sourceIndex._neuron];\n\n _symbolicUpperBias[i] = sourceLayer->getSymbolicUpperBias()[sourceIndex._neuron];\n\n\n\n double sourceLb = sourceLayer->getLb( sourceIndex._neuron );\n\n double sourceUb = sourceLayer->getUb( sourceIndex._neuron );\n\n\n\n _symbolicLbOfLb[i] = sourceLayer->getSymbolicLbOfLb( sourceIndex._neuron );\n\n _symbolicUbOfLb[i] = sourceLayer->getSymbolicUbOfLb( sourceIndex._neuron );\n\n _symbolicLbOfUb[i] = sourceLayer->getSymbolicLbOfUb( sourceIndex._neuron );\n\n _symbolicUbOfUb[i] = sourceLayer->getSymbolicUbOfUb( sourceIndex._neuron );\n\n\n\n if ( sourceLb >= 0 )\n\n absPhase = AbsoluteValueConstraint::PHASE_POSITIVE;\n\n else if ( sourceUb <= 0 )\n\n absPhase = AbsoluteValueConstraint::PHASE_NEGATIVE;\n\n\n\n if ( absPhase == AbsoluteValueConstraint::PHASE_NOT_FIXED )\n", "file_path": "src/nlr/Layer.cpp", "rank": 94, "score": 106023.15521511986 }, { "content": "const double *Layer::getAssignment() const\n\n{\n\n return _assignment;\n\n}\n\n\n\ndouble Layer::getAssignment( unsigned neuron ) const\n\n{\n\n return _assignment[neuron];\n\n}\n\n\n\nvoid Layer::computeAssignment()\n\n{\n\n ASSERT( _type != INPUT );\n\n\n\n if ( _type == WEIGHTED_SUM )\n\n {\n\n // Initialize to bias\n\n memcpy( _assignment, _bias, sizeof(double) * _size );\n\n\n\n // Process each of the source layers\n", "file_path": "src/nlr/Layer.cpp", "rank": 95, "score": 106023.13793223377 }, { "content": " }\n\n\n\n for ( unsigned i = 0; i < _size; ++i )\n\n {\n\n if ( _eliminatedNeurons.exists( i ) )\n\n continue;\n\n\n\n /*\n\n There are two ways we can determine that a ReLU has become fixed:\n\n\n\n 1. If the ReLU's variable has been externally fixed\n\n 2. lbLb >= 0 (ACTIVE) or ubUb <= 0 (INACTIVE)\n\n */\n\n ReluConstraint::PhaseStatus reluPhase = ReluConstraint::PHASE_NOT_FIXED;\n\n\n\n // Has the f variable been eliminated or fixed?\n\n if ( FloatUtils::isPositive( _lb[i] ) )\n\n reluPhase = ReluConstraint::PHASE_ACTIVE;\n\n else if ( FloatUtils::isZero( _ub[i] ) )\n\n reluPhase = ReluConstraint::PHASE_INACTIVE;\n", "file_path": "src/nlr/Layer.cpp", "rank": 96, "score": 106022.89196956839 }, { "content": "/********************* */\n\n/*! \\file Layer.cpp\n\n ** \\verbatim\n\n ** Top contributors (to current version):\n\n ** Guy Katz\n\n ** This file is part of the Marabou project.\n\n ** Copyright (c) 2017-2019 by the authors listed in the file AUTHORS\n\n ** in the top-level source directory) and their institutional affiliations.\n\n ** All rights reserved. See the file COPYING in the top-level source\n\n ** directory for licensing information.\\endverbatim\n\n **\n\n ** [[ Add lengthier description here ]]\n\n\n\n **/\n\n\n\n#include \"Layer.h\"\n\n\n\nnamespace NLR {\n\n\n\nLayer::~Layer()\n", "file_path": "src/nlr/Layer.cpp", "rank": 97, "score": 106022.60468977106 }, { "content": "\n\n ++neuronIt;\n\n }\n\n\n\n // Now handle re-indexing\n\n neuronIt = _neuronToVariable.begin();\n\n while ( neuronIt != _neuronToVariable.end() )\n\n {\n\n unsigned variable = neuronIt->second;\n\n\n\n if ( !oldIndexToNewIndex.exists( variable ) )\n\n {\n\n // This variable has been eliminated, remove from map\n\n neuronIt = _neuronToVariable.erase( neuronIt );\n\n }\n\n else\n\n {\n\n if ( oldIndexToNewIndex[variable] == variable )\n\n {\n\n // Index hasn't changed, skip\n", "file_path": "src/nlr/Layer.cpp", "rank": 98, "score": 106022.33210458737 }, { "content": " if ( entry >= 0 )\n\n {\n\n _symbolicLbOfUb[i] += ( entry * inputLb );\n\n _symbolicUbOfUb[i] += ( entry * inputUb );\n\n }\n\n else\n\n {\n\n _symbolicLbOfUb[i] += ( entry * inputUb );\n\n _symbolicUbOfUb[i] += ( entry * inputLb );\n\n }\n\n }\n\n\n\n /*\n\n We now have the tightest bounds we can for the\n\n weighted sum variable. If they are tigheter than\n\n what was previously known, store them.\n\n */\n\n if ( _lb[i] < _symbolicLbOfLb[i] )\n\n {\n\n _lb[i] = _symbolicLbOfLb[i];\n", "file_path": "src/nlr/Layer.cpp", "rank": 99, "score": 106021.47702310071 } ]
C++
cpp/meta/typelist.hpp
so61pi/examples
38e2831cd6517864fc05f499f72fbb4ff6ae27c0
#ifndef TYPELIST_HPP #define TYPELIST_HPP #include <cstddef> #include <type_traits> namespace tl { template<typename... Ts> struct typelist; template<typename T, typename... Ts> struct typelist<T, Ts...> { using first_type = T; using next = typelist<Ts...>; using size = std::integral_constant<std::size_t, next::size::value + 1>; }; template<> struct typelist<> { using size = std::integral_constant<std::size_t, 0>; }; template<typename TypeList> struct is_typelist { using type = std::false_type; }; template<typename... Ts> struct is_typelist<typelist<Ts...>> { using type = std::true_type; }; template<typename TypeList> using is_typelist_t = typename is_typelist<TypeList>::type; #define TYPELIST_ASSERT(TypeList) \ static_assert(is_typelist_t<TypeList>::value, "not a typelist"); template<typename TypeList> struct size { TYPELIST_ASSERT(TypeList) using type = typename TypeList::size; }; template<typename TypeList> using size_t = typename size<TypeList>::type; template<typename TypeList> struct is_empty { TYPELIST_ASSERT(TypeList) using type = std::false_type; }; template<> struct is_empty<typelist<>> { using type = std::true_type; }; template<typename TypeList> using is_empty_t = typename is_empty<TypeList>::type; template<typename TypeList, typename IntegralIndex> struct at { TYPELIST_ASSERT(TypeList) static_assert(IntegralIndex::value < size<TypeList>::type::value, "index out of range"); using type = typename at<typename TypeList::next, std::integral_constant<std::size_t, IntegralIndex::value - 1>>::type; }; template<typename TypeList> struct at<TypeList, std::integral_constant<std::size_t, 0>> { TYPELIST_ASSERT(TypeList) using type = typename TypeList::first_type; }; template<typename TypeList, typename IntegralIndex> using at_t = typename at<TypeList, IntegralIndex>::type; template<typename TypeList, std::size_t Index> using at_c = at<TypeList, std::integral_constant<std::size_t, Index>>; template<typename TypeList, std::size_t Index> using at_c_t = typename at_c<TypeList, Index>::type; template<typename TypeList> struct front { TYPELIST_ASSERT(TypeList) static_assert(!is_empty_t<TypeList>::value, "empty typelist"); using type = typename TypeList::first_type; }; template<typename TypeList> using front_t = typename front<TypeList>::type; template<typename TypeList, typename NewType> struct push_front; template<typename... Ts, typename NewType> struct push_front<typelist<Ts...>, NewType> { using type = typelist<NewType, Ts...>; }; template<typename TypeList, typename NewType> using push_front_t = typename push_front<TypeList, NewType>::type; template<typename TypeList, typename NewType> struct push_back { TYPELIST_ASSERT(TypeList) private: using sub = typename push_back<typename TypeList::next, NewType>::type; public: using type = typename push_front<sub, typename TypeList::first_type>::type; }; template<typename NewType> struct push_back<typelist<>, NewType> { using type = typelist<NewType>; }; template<typename TypeList, typename NewType> using push_back_t = typename push_back<TypeList, NewType>::type; template<typename TypeList> struct reverse { TYPELIST_ASSERT(TypeList) private: using reversed_sub = typename reverse<typename TypeList::next>::type; public: using type = typename push_back<reversed_sub, typename TypeList::first_type>::type; }; template<> struct reverse<typelist<>> { using type = typelist<>; }; template<typename TypeList> using reverse_t = typename reverse<TypeList>::type; template<typename TypeList> struct pop_front { TYPELIST_ASSERT(TypeList) using type = typename TypeList::next; }; template<typename TypeList> using pop_front_t = typename pop_front<TypeList>::type; template<typename TypeList> struct pop_back { TYPELIST_ASSERT(TypeList) static_assert(!is_empty_t<TypeList>::value, "empty typelist"); private: using temp = typename pop_front<typename reverse<TypeList>::type>::type; public: using type = typename reverse<temp>::type; }; template<typename TypeList> using pop_back_t = typename pop_back<TypeList>::type; template<typename TypeList, typename NewType, typename IntegralIndex> struct insert { TYPELIST_ASSERT(TypeList) static_assert(IntegralIndex::value <= size<TypeList>::type::value, "index out of range"); private: using sub = typename insert<typename pop_front<TypeList>::type, NewType, std::integral_constant<std::size_t, IntegralIndex::value - 1>>::type; public: using type = typename push_front<sub, typename front<TypeList>::type>::type; }; template<typename TypeList, typename NewType> struct insert<TypeList, NewType, std::integral_constant<std::size_t, 0>> { TYPELIST_ASSERT(TypeList) using type = typename push_front<TypeList, NewType>::type; }; template<typename TypeList, typename NewType, typename IntegralIndex> using insert_t = typename insert<TypeList, NewType, IntegralIndex>::type; template<typename TypeList, typename NewType, std::size_t Index> using insert_c = insert<TypeList, NewType, std::integral_constant<std::size_t, Index>>; template<typename TypeList, typename NewType, std::size_t Index> using insert_c_t = typename insert_c<TypeList, NewType, Index>::type; template<typename TypeList, typename IntegralIndex> struct remove { TYPELIST_ASSERT(TypeList) static_assert(IntegralIndex::value < size<TypeList>::type::value, "index out of range"); private: using sub = typename remove<typename pop_front<TypeList>::type, std::integral_constant<std::size_t, IntegralIndex::value - 1>>::type; public: using type = typename push_front<sub, typename front<TypeList>::type>::type; }; template<typename TypeList> struct remove<TypeList, std::integral_constant<std::size_t, 0>> { TYPELIST_ASSERT(TypeList) using type = typename pop_front<TypeList>::type; }; template<typename TypeList, typename IntegralIndex> using remove_t = typename remove<TypeList, IntegralIndex>::type; template<typename TypeList, std::size_t Index> using remove_c = remove<TypeList, std::integral_constant<std::size_t, Index>>; template<typename TypeList, std::size_t Index> using remove_c_t = typename remove_c<TypeList, Index>::type; template<typename Left, typename Right> struct concat { TYPELIST_ASSERT(Left) TYPELIST_ASSERT(Right) private: using newLeft = typename push_back<Left, typename Right::first_type>::type; using newRight = typename Right::next; public: using type = typename concat<newLeft, newRight>::type; }; template<typename Left> struct concat<Left, typelist<>> { TYPELIST_ASSERT(Left) using type = Left; }; template<typename Left, typename Right> using concat_t = typename concat<Left, Right>::type; } #endif
#ifndef TYPELIST_HPP #define TYPELIST_HPP #include <cstddef> #include <type_traits> namespace tl { template<typename... Ts> struct typelist; template<typename T, typename... Ts> struct typelist<T, Ts...> { using first_type = T; using next = typelist<Ts...>; using size = std::integral_constant<std::size_t, next::size::value + 1>; }; template<> struct typelist<> { using size = std::integral_constant<std::size_t, 0>; }; template<typename TypeList> struct is_typelist { using type = std::false_type; }; template<typename... Ts> struct is_typelist<typelist<Ts...>> { using type = std::true_type; }; template<typename TypeList> using is_typelist_t = typename is_typelist<TypeList>::type; #define TYPELIST_ASSERT(TypeList) \ static_assert(is_typelist_t<TypeList>::value, "not a typelist"); template<typename TypeList> struct size { TYPELIST_ASSERT(TypeList) using type = typename TypeList::size; }; template<typename TypeList> using size_t = typename size<TypeList>::type; template<typename TypeList> struct is_empty { TYPELIST_ASSERT(TypeList) using type = std::false_type; }; template<> struct is_empty<typelist<>> { using type = std::true_type; }; template<typename TypeList> using is_empty_t = typename is_empty<TypeList>::type; template<typename TypeList, typename IntegralIndex> struct at { TYPELIST_ASSERT(TypeList) static_assert(IntegralIndex::value < size<TypeList>::type::value, "index out of range"); using type = typename at<typename TypeList::next, std::integral_constant<std::size_t, IntegralIndex::value - 1>>::type; }; template<typename TypeList> struct at<TypeList, std::integral_constant<std::size_t, 0>> { TYPELIST_ASSERT(TypeList) using type = typename TypeList::first_type; }; template<typename TypeList, typename IntegralIndex> using at_t = typename at<TypeList, IntegralIndex>::type; template<typename TypeList, std::size_t Index> using at_c = at<TypeList, std::integral_constant<std::size_t, Index>>; template<typename TypeList, std::size_t Index> using at_c_t = typename at_c<TypeList, Index>::type; template<typename TypeList> struct front { TYPELIST_ASSERT(TypeList) static_assert(!is_empty_t<TypeList>::value, "empty typelist"); using type = typename TypeList::first_type; }; template<typename TypeList> using front_t = typename front<TypeList>::type; template<typename TypeList, typename NewType> struct push_front; template<typename... Ts, typename NewType> struct push_front<typelist<Ts...>, NewType> { using type = typelist<NewType, Ts...>; }; template<typename TypeList, typename NewType> using push_front_t = typename push_front<TypeList, NewType>::type; template<typename TypeList, typename NewType> struct push_back { TYPELIST_ASSERT(TypeList) private: using sub = typename push_back<typename TypeList::next, NewType>::type; public: using type = typename push_front<sub, typename TypeList::first_type>::type; }; template<typename NewType> struct push_back<typelist<>, NewType> { using type = typelist<NewType>; }; template<typename TypeList, typename NewType> using push_back_t = typename push_back<TypeList, NewType>::type; template<typename TypeList> struct reverse { TYPELIST_ASSERT(TypeList) private: using reversed_sub = typename reverse<typename TypeList::next>::type; public: using type = typename push_back<reversed_sub, typename TypeList::first_type>::type; }; template<> struct reverse<typelist<>> { using type = typelist<>; }; template<typename TypeList> using reverse_t = typename reverse<TypeList>::type; template<typename TypeList> struct pop_front { TYPELIST_ASSERT(TypeList) using type = typename TypeList::next; }; template<typename TypeList> using pop_front_t = typename pop_front<TypeList>::type; template<typename TypeList> struct pop_back { TYPELIST_ASSERT(TypeList) static_assert(!is_empty_t<TypeList>::value, "empty typelist"); private: using temp = typename pop_front<typename reverse<TypeList>::type>::type; public: using type = typename reverse<temp>::type; }; template<typename TypeList> using pop_back_t = typename pop_back<TypeList>::type; template<typename TypeList, typename NewType, typename IntegralIndex> struct insert { TYPELIST_ASSERT(TypeList) static_assert(IntegralIndex::value <= size<TypeList>::type::value, "index out of range"); private: using sub = typename insert<typename pop_front<TypeList>::type, NewType, std::integral_constant<std::size_t, IntegralIndex::value - 1>>::type; public: using type = typename push_front<sub, typename front<TypeList>::type>::type; }; template<typename TypeList, typename NewType> struct insert<TypeList, NewType, std::integral_constant<std::size_t, 0>> { TYPELIST_ASSERT(TypeList) using type = typename push_front<TypeList, NewType>::type; }; template<typename TypeList, typename NewType, typename IntegralIndex> using insert_t = typename insert<TypeList, NewType, IntegralIndex>::type; template<typename TypeList, typename NewType, std::size_t Index> using insert_c = insert<TypeList, NewType, std::integral_constant<std::size_t, Index>>; template<typename TypeList, typename NewType, std::size_t Index> using insert_c_t = typename insert_c<TypeList, NewType, Index>::type; template<typename TypeList, typename IntegralIndex> struct remove { TYPELIST_ASSERT(TypeList) static_assert(IntegralIndex::value < size<TypeList>::type::value, "index out of range"); private: using sub = typename remove<typename pop_front<TypeList>::type, std::integral_constant<std::size_t, IntegralIndex::value - 1>>::type; public: using type = typename push_front<sub, typename front<TypeList>::type>::type; }; template<typename TypeList> struct remove<TypeList, std::integral_constant<std::size_t, 0>> { TYPELIST_ASSERT(TypeList) using type = typename pop_front<TypeList>:
late<typename Left, typename Right> struct concat { TYPELIST_ASSERT(Left) TYPELIST_ASSERT(Right) private: using newLeft = typename push_back<Left, typename Right::first_type>::type; using newRight = typename Right::next; public: using type = typename concat<newLeft, newRight>::type; }; template<typename Left> struct concat<Left, typelist<>> { TYPELIST_ASSERT(Left) using type = Left; }; template<typename Left, typename Right> using concat_t = typename concat<Left, Right>::type; } #endif
:type; }; template<typename TypeList, typename IntegralIndex> using remove_t = typename remove<TypeList, IntegralIndex>::type; template<typename TypeList, std::size_t Index> using remove_c = remove<TypeList, std::integral_constant<std::size_t, Index>>; template<typename TypeList, std::size_t Index> using remove_c_t = typename remove_c<TypeList, Index>::type; temp
random
[ { "content": "struct lambda<std::integral_constant<std::size_t, Index>> {\n\n using type =\n\n struct {\n\n template<typename... Xs>\n\n struct apply {\n\n static_assert(Index < sizeof...(Xs), \"index out of range\");\n\n \n\n using type = at_t<typelist<Xs...>, std::integral_constant<std::size_t, Index>>;\n\n };\n\n };\n\n};\n\n\n\n\n\ntemplate<template<typename...> class MetaFunction, typename... Ts>\n", "file_path": "cpp/meta/lambda.hpp", "rank": 25, "score": 205883.89446456044 }, { "content": "struct FieldValueVisitor : public boost::static_visitor<void> {\n\n void operator()(CComVariant variant) const {\n\n std::wcout << VariantToString(variant);\n\n }\n\n\n\n void operator()(std::vector<CComVariant> const& array) const {\n\n std::wcout << L\"[\";\n\n for (auto const& e : array) {\n\n std::wcout << VariantToString(e) << L\", \";\n\n }\n\n std::wcout << L\"]\";\n\n }\n\n};\n\n\n\n\n\n\n\nint main() {\n", "file_path": "cpp/windows/UseWMI2.cpp", "rank": 26, "score": 185570.97401491032 }, { "content": "struct array_size;\n\n\n\ntemplate<typename T, std::size_t N>\n", "file_path": "cpp/ArraySize.cpp", "rank": 27, "score": 163337.28212840462 }, { "content": "struct lambda<MetaFunction<Ts...>> {\n\n using type =\n\n struct {\n\n private:\n\n // create a typelist of sub metafunction class\n\n using sub_metaclass_list = typelist<typename lambda<Ts>::type...>;\n\n\n\n template<typename SubMetaClassList, typename... Xs>\n\n struct apply_help;\n\n \n\n // apply each SubMetaClass, then pass to MetaFunction\n\n template<typename... SubMetaClass, typename... Xs>\n\n struct apply_help<typelist<SubMetaClass...>, Xs...> {\n\n using type = typename MetaFunction<typename SubMetaClass::template apply<Xs...>::type...>::type;\n\n };\n\n\n\n public:\n\n template<typename... Xs>\n\n struct apply {\n\n using type = typename apply_help<sub_metaclass_list, Xs...>::type;\n\n };\n\n };\n\n};\n\n\n\n\n\n#endif // LAMBDA_HPP\n", "file_path": "cpp/meta/lambda.hpp", "rank": 28, "score": 160419.54326352995 }, { "content": "struct frgcolor : public colorinfo {};\n\n\n\n\n\nauto setfrg(color c, bool i) -> frgcolor {\n\n frgcolor fc;\n\n fc.color = c;\n\n fc.intensity = i;\n\n return fc;\n\n}\n\n\n\n\n\nauto setbkg(color c, bool i) -> bkgcolor {\n\n bkgcolor bc;\n\n bc.color = c;\n\n bc.intensity = i;\n\n return bc;\n\n}\n\n\n\n\n\nauto colors() {\n", "file_path": "cpp/windows/ConsoleColoredOutput.cpp", "rank": 29, "score": 157851.83144791407 }, { "content": "struct bkgcolor : public colorinfo {};\n", "file_path": "cpp/windows/ConsoleColoredOutput.cpp", "rank": 30, "score": 157851.83144791407 }, { "content": "struct TimerTemplate {\n\n timer_t timerid;\n\n std::uint64_t ticks;\n\n TaskCollection tasks;\n\n};\n\n\n\n\n\nnamespace first {\n\n struct Timer : TimerTemplate<std::list<Task>> {\n\n };\n\n\n\n\n\n void AddTask(Timer& timer, Task&& task) {\n\n timer.tasks.emplace_back(std::move(task));\n\n }\n\n\n\n\n\n void Schedule(Timer& timer) {\n\n auto it = timer.tasks.begin();\n\n while (it != timer.tasks.end()) {\n", "file_path": "tmp-timer/main.cpp", "rank": 31, "score": 150794.81190497853 }, { "content": "struct employee {\n\n int id;\n\n std::string name;\n\n int birth_date;\n\n\n\n employee(int id_, const std::string& name_, int birth_date_)\n\n : id(id_), name(name_), birth_date(birth_date_)\n\n {}\n\n\n\n std::size_t name_length() const {\n\n return name.size();\n\n }\n\n\n\n // MultiIndex uses operator less than by default (std::less)\n\n bool operator<(const employee& rhs) const {\n\n return id < rhs.id;\n\n }\n\n};\n\n\n\n\n", "file_path": "cpp/MultiIndexExample2.cpp", "rank": 32, "score": 150776.66027978074 }, { "content": "struct employee {\n\n int id;\n\n std::string name;\n\n int birth_date;\n\n\n\n employee(int id_, const std::string& name_, int birth_date_)\n\n : id(id_), name(name_), birth_date(birth_date_)\n\n {}\n\n\n\n bool operator<(const employee& rhs) const {\n\n return id < rhs.id;\n\n }\n\n};\n\n\n\n\n\nusing namespace boost::multi_index;\n\nusing employee_set = boost::multi_index_container<\n\n employee,\n\n indexed_by<\n\n ordered_unique<identity<employee>>,\n", "file_path": "cpp/MultiIndexExample.cpp", "rank": 33, "score": 150776.66027978074 }, { "content": "struct employee {\n\n int id;\n\n std::string name;\n\n int birth_date;\n\n\n\n employee(int id_, const std::string& name_, int birth_date_)\n\n : id(id_), name(name_), birth_date(birth_date_)\n\n {}\n\n\n\n std::size_t name_length() const {\n\n return name.size();\n\n }\n\n\n\n // MultiIndex uses operator less than by default (std::less)\n\n bool operator<(const employee& rhs) const {\n\n return id < rhs.id;\n\n }\n\n};\n\n\n\n\n", "file_path": "cpp/MultiIndexExample3.cpp", "rank": 34, "score": 150776.66027978074 }, { "content": "struct field_t {\n\n std::wstring name;\n\n boost::variant<CComVariant, std::vector<CComVariant>> value;\n\n};\n\n\n\nusing row_t = std::vector<field_t>;\n\nusing table_t = std::vector<row_t>;\n\n\n\n\n\nauto GetFieldValue(CComPtr<IWbemClassObject>& pWCO, BSTR fieldName) -> field_t {\n\n CComVariant variant;\n\n windows::check_com_result(pWCO->Get(fieldName, 0, &variant, 0, 0));\n\n\n\n if (variant.vt & VT_ARRAY) {\n\n if (variant.parray->cDims != 1)\n\n throw std::runtime_error{\"COM - invalid safe array dimensions\"};\n\n\n\n auto psa = variant.parray;\n\n std::vector<CComVariant> array;\n\n for (auto i = 0U; i < psa->rgsabound[0].cElements; ++i) {\n", "file_path": "cpp/windows/UseWMI2.cpp", "rank": 35, "score": 150765.40175861956 }, { "content": "//\n\n//\n\n//\n\nclass CMath : public IAdd, public ISub, public IMul, public IDiv {\n\npublic:\n\n // IUnknown\n\n virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject) override;\n\n virtual ULONG STDMETHODCALLTYPE AddRef(void) override;\n\n virtual ULONG STDMETHODCALLTYPE Release(void) override;\n\n\n\n // IAdd\n\n virtual HRESULT STDMETHODCALLTYPE Add(LONG a, LONG b, LONG *c) override;\n\n\n\n // ISub\n\n virtual HRESULT STDMETHODCALLTYPE Sub(LONG a, LONG b, LONG *c) override;\n\n\n\n // IMul\n\n virtual HRESULT STDMETHODCALLTYPE Mul(LONG a, LONG b, LONG *c) override;\n\n\n\n // IDiv\n\n virtual HRESULT STDMETHODCALLTYPE Div(LONG a, LONG b, LONG *c) override;\n\n\n\nprivate:\n\n std::atomic<long long> m_RefCount = 0;\n\n};\n\n\n\n\n\n#endif // CMATH_H\n", "file_path": "cpp/windows/simple-com-server/simple-com-server/CMath.h", "rank": 36, "score": 149028.54014124084 }, { "content": "struct IOE\n\n{\n\n explicit IOE(FILE* i, FILE* o, FILE* e)\n\n : mInput(i)\n\n , mOutput(o)\n\n , mError(e)\n\n {\n\n }\n\n\n\n FILE* mInput;\n\n FILE* mOutput;\n\n FILE* mError;\n\n};\n\n\n", "file_path": "cpp/libedit-test/include/clicxx/Editline.h", "rank": 37, "score": 148079.54851481123 }, { "content": "// tags\n\nstruct name_tag {};\n", "file_path": "cpp/MultiIndexExample3.cpp", "rank": 38, "score": 148076.1702778039 }, { "content": "struct array_size<T[N]> {\n\n static std::size_t const value = N;\n\n static std::size_t const bytes = N * sizeof(T);\n\n};\n\n\n\n// specialization for std::array\n\ntemplate<typename T, std::size_t N>\n", "file_path": "cpp/ArraySize.cpp", "rank": 39, "score": 147537.1258005681 }, { "content": "struct ArgOptions\n\n{\n\n ArgOptions() = default;\n\n\n\n explicit ArgOptions(Visibility v)\n\n : mVisibility(v)\n\n {\n\n }\n\n\n\n explicit ArgOptions(Usability u)\n\n : mUsability(u)\n\n {\n\n }\n\n\n\n explicit ArgOptions(Visibility v, Usability u)\n\n : mVisibility(v)\n\n , mUsability(u)\n\n {\n\n }\n\n\n\n Visibility mVisibility = Visibility::Visible;\n\n Usability mUsability = Usability::Usable;\n\n};\n\n\n", "file_path": "cpp/libedit-test/include/clicxx/Editline.h", "rank": 40, "score": 145504.4116541595 }, { "content": "struct HidingOptions\n\n{\n\n HidingOptions()\n\n : HideArgDesc(false)\n\n , HideArg(true)\n\n {\n\n }\n\n\n\n bool HideArgDesc;\n\n bool HideArg;\n\n};\n\n\n\n} // namespace detail\n\n\n", "file_path": "cpp/libedit-test/include/clicxx/Editline.h", "rank": 41, "score": 145504.4116541595 }, { "content": "struct get_category_index;\n\n\n\ntemplate<std::size_t Index>\n", "file_path": "cpp/ContainerPickerIterator.cpp", "rank": 42, "score": 145501.11187285144 }, { "content": "struct birth_date_tag {};\n", "file_path": "cpp/MultiIndexExample3.cpp", "rank": 43, "score": 145501.11187285144 }, { "content": "struct name_length_tag {};\n\n\n\n\n\nusing namespace boost::multi_index;\n\nusing employee_set = boost::multi_index_container<\n\n employee,\n\n indexed_by<\n\n ordered_unique<identity<employee>>,\n\n ordered_non_unique<tag<name_tag>, member<employee, std::string, &employee::name>, std::greater<std::string>>,\n\n ordered_non_unique<tag<birth_date_tag>, member<employee, int, &employee::birth_date>>,\n\n ordered_non_unique<tag<name_length_tag>, const_mem_fun<employee, std::size_t, &employee::name_length>>\n\n >>;\n\n\n\n\n\nint main() {\n\n employee_set employees{};\n\n\n\n // insert elements\n\n employees.emplace(1, \"Einstein\", 1879);\n\n employees.emplace(2, \"Edison\", 1847);\n", "file_path": "cpp/MultiIndexExample3.cpp", "rank": 44, "score": 145501.11187285144 }, { "content": "struct ArgStaticInfo\n\n{\n\n explicit ArgStaticInfo(std::string name, std::string desc)\n\n : mName(std::move(name))\n\n , mDesc(std::move(desc))\n\n {\n\n }\n\n\n\n explicit ArgStaticInfo(std::string name, std::string desc, Help help)\n\n : mName(std::move(name))\n\n , mDesc(std::move(desc))\n\n , mHelp(std::move(help))\n\n {\n\n }\n\n\n\n std::string const mName;\n\n std::string const mDesc;\n\n cli::Help const mHelp;\n\n};\n\n\n", "file_path": "cpp/libedit-test/include/clicxx/Editline.h", "rank": 45, "score": 143046.16928212342 }, { "content": "struct get_category_index;\n\n\n\ntemplate<std::size_t Index>\n", "file_path": "cpp/GetWeakerIteratorCategory.cpp", "rank": 46, "score": 143042.94439513542 }, { "content": "struct array_size<std::array<T, N>> {\n\n static std::size_t const value = N;\n\n static std::size_t const bytes = N * sizeof(T);\n\n};\n\n\n\n\n\nint main() {\n\n double a[10];\n\n std::cout << array_size<decltype(a)>::value << \"\\n\";\n\n std::cout << array_size<decltype(a)>::bytes << \"\\n\";\n\n std::cout << std::extent<decltype(a)>::value << \"\\n\";\n\n \n\n std::array<short, 5> b;\n\n std::cout << array_size<decltype(b)>::value << \"\\n\";\n\n std::cout << array_size<decltype(b)>::bytes << \"\\n\";\n\n std::cout << std::tuple_size<decltype(b)>::value << \"\\n\"; // cannot use std::extent for std::array\n\n}\n", "file_path": "cpp/ArraySize.cpp", "rank": 47, "score": 137234.9281290443 }, { "content": "class Derived : public Base\n\n{\n\n // create a type alias for std::string\n\n using string = std::string;\n\n\n\npublic:\n\n // introduce all show functions from the Base class into this class\n\n // or the function show(const string&) will hide show(int) and show(const T&)\n\n // in the Base class (Name Lookup rules)\n\n using Base::show;\n\n\n\n void show(const string&) const {\n\n std::cout << \"Derived::show(const string&)\" << std::endl;\n\n }\n\n};\n\n\n\n\n\n// create a template type alias for std::unique_ptr\n\ntemplate<typename T>\n\nusing pointer_t = std::unique_ptr<T>;\n", "file_path": "cpp/UsingDeclaration.cpp", "rank": 48, "score": 136908.86360168146 }, { "content": " class SubExpr : public Expr {\n\n using base_type = Expr;\n\n\n\n public:\n\n explicit SubExpr(token_const_iterator begin, token_const_iterator end,\n\n ast::Term* lTerm, ast::Expr* rExpr);\n\n\n\n ast::Term* Left() const;\n\n ast::Expr* Right() const;\n\n ast::Term* Term() const;\n\n ast::Expr* Expr() const;\n\n virtual const char* NodeName() const { return \"SubExpr\"; }\n\n\n\n private:\n\n ast::Term* mLTerm;\n\n ast::Expr* mRExpr;\n\n };\n\n\n\n\n", "file_path": "cpp/ExpressionParser.cpp", "rank": 49, "score": 134366.96684869158 }, { "content": "// enumeration using to choose which function will get called\n\n// enum class is used to prevent user uses arbitrary integral constant to specify which function is called\n\n// e.g. factorial<0>(5) is illegal\n\nenum class FactorialMethod : size_t {\n\n Loop,\n\n Recursion\n\n};\n\n\n\n\n\n// default implementation...\n\ntemplate<FactorialMethod = FactorialMethod::Loop>\n\nsize_t factorial(size_t n) {\n\n size_t r = 1;\n\n for (size_t i = 1; i <= n; ++i)\n\n r *= i;\n\n return r;\n\n}\n\n\n\n\n\n// ... and another one\n\ntemplate<>\n\nsize_t factorial<FactorialMethod::Recursion>(size_t n) {\n\n if (n == 0)\n", "file_path": "cpp/OverloadTemplateAndEnum.cpp", "rank": 50, "score": 132057.01879610177 }, { "content": "class Param : public Arg\n\n{\n\npublic:\n\n explicit Param(ArgStaticInfo info, ParamCompletor completor,\n\n std::string defaultHelp, ArgOptions opts);\n\n\n\n CompletionAction Complete(ValueContainer& vals,\n\n stdex::string_view hint) const;\n\n\n\n std::string const& GetDefaultHelp() const;\n\n\n\nprivate:\n\n ParamCompletor mCompletor;\n\n std::string mDefaultHelp;\n\n};\n\n\n\nusing ParamPtr = std::unique_ptr<Param>;\n\nusing ParamContainer = std::vector<ParamPtr>;\n\n\n\ntemplate <typename T, typename... Args>\n\ninline ParamPtr\n\nMakeParam(Args&&... args)\n\n{\n\n return std::make_unique<T>(std::forward<Args>(args)...);\n\n}\n\n\n", "file_path": "cpp/libedit-test/include/clicxx/Editline.h", "rank": 51, "score": 131889.69830916403 }, { "content": "class Cmd : public Arg\n\n{\n\npublic:\n\n explicit Cmd(ArgStaticInfo info, ParamContainer childParams, ArgOptions opts);\n\n explicit Cmd(ArgStaticInfo info, CmdContainer childCmds, ArgOptions opts);\n\n explicit Cmd(ArgStaticInfo info, ArgOptions opts);\n\n\n\n virtual ~Cmd() = default;\n\n\n\n CmdChildrenKind GetChildrenKind() const;\n\n\n\n void AddChildCmd(CmdContainer::value_type cmd);\n\n CmdContainer const& GetChildCmds() const;\n\n CmdContainer& GetChildCmds();\n\n\n\n void AddChildParam(ParamContainer::value_type param);\n\n ParamContainer const& GetChildParams() const;\n\n ParamContainer& GetChildParams();\n\n\n\n virtual int Handle(int argc, char const** argv, Editline& editline);\n", "file_path": "cpp/libedit-test/include/clicxx/Editline.h", "rank": 52, "score": 131889.69830916403 }, { "content": " class empty_parser : public base_parser {\n\n public:\n\n virtual bool parse(iterator& first, iterator const& last,\n\n error& error) {\n\n return true;\n\n }\n\n\n\n virtual char const* name() const { return \"empty-parser\"; }\n\n };\n\n\n\n\n\n /**\n\n * @brief End parser, returns true if there is no more character.\n\n */\n", "file_path": "cpp/simple-parser/spl.hpp", "rank": 53, "score": 129563.33422432932 }, { "content": "class CustomDeleter : public DeleterBase {\n\npublic:\n\n CustomDeleter(T *p, Deleter deleter) :\n\n m_p{ p },\n\n m_deleter{ deleter }\n\n {}\n\n\n\n virtual void dispose() override {\n\n m_deleter(m_p);\n\n }\n\n\n\nprivate:\n\n T *m_p;\n\n Deleter m_deleter;\n\n};\n\n\n\n\n", "file_path": "cpp/TemplateDerivedFromAbstract.cpp", "rank": 54, "score": 129553.88223858154 }, { "content": "class DefaultDeleter : public DeleterBase {\n\npublic:\n\n DefaultDeleter(T *p) :\n\n m_p{ p }\n\n {}\n\n\n\n virtual void dispose() override {\n\n delete m_p;\n\n }\n\n\n\nprivate:\n\n T *m_p;\n\n};\n\n\n\n\n\ntemplate<typename T, typename Deleter>\n", "file_path": "cpp/TemplateDerivedFromAbstract.cpp", "rank": 55, "score": 129553.88223858154 }, { "content": "class HelpHandler : public Cmd\n\n{\n\npublic:\n\n explicit HelpHandler(ArgStaticInfo info, ArgOptions opts);\n\n\n\n virtual int Handle(int argc, char const** argv, Editline& editline) override;\n\n};\n\n\n", "file_path": "cpp/libedit-test/include/clicxx/Handler.h", "rank": 56, "score": 129540.49528948453 }, { "content": "class QuitHandler : public Cmd\n\n{\n\npublic:\n\n explicit QuitHandler(ArgStaticInfo info, ArgOptions opts);\n\n\n\n virtual int Handle(int argc, char const** argv, Editline& editline) override;\n\n};\n\n\n", "file_path": "cpp/libedit-test/include/clicxx/Handler.h", "rank": 57, "score": 129540.49528948453 }, { "content": " class SubExpr : public ast::Expr {\n\n public:\n\n explicit SubExpr(token_const_iterator begin, token_const_iterator end, ast::Term const& lTerm,\n\n ast::Expr const& rExpr)\n\n : ast::Expr(begin, end, ExprKind::SubExpr), mLTerm(lTerm), mRExpr(rExpr) {}\n\n\n\n ast::Term const& Left() const { return Term(); }\n\n ast::Expr const& Right() const { return Expr(); }\n\n ast::Term const& Term() const { return mLTerm; }\n\n ast::Expr const& Expr() const { return mRExpr; }\n\n virtual const char* NodeName() const { return \"SubExpr\"; }\n\n\n\n private:\n\n ast::Term const& mLTerm;\n\n ast::Expr const& mRExpr;\n\n };\n\n\n", "file_path": "cpp/ExpressionParser2.cpp", "rank": 58, "score": 128511.74958429346 }, { "content": "class EditLineHandler : public Cmd\n\n{\n\npublic:\n\n explicit EditLineHandler(ArgStaticInfo info, ArgOptions opts);\n\n\n\n virtual int Handle(int argc, char const** argv, Editline& editline) override;\n\n};\n\n\n\n} // namespace cli\n\n\n\n#endif // LIBCLICXX_HANDLER_H_INCLUDED\n", "file_path": "cpp/libedit-test/include/clicxx/Handler.h", "rank": 59, "score": 127293.30032618025 }, { "content": "class CommandHideUnhideHandler : public Cmd\n\n{\n\npublic:\n\n explicit CommandHideUnhideHandler(ArgStaticInfo info, ArgOptions opts);\n\n\n\n virtual int Handle(int argc, char const** argv, Editline& editline) override;\n\n};\n\n\n", "file_path": "cpp/libedit-test/include/clicxx/Handler.h", "rank": 60, "score": 125141.61045303324 }, { "content": "class Logical : public std::logic_error\n\n{\n\n using std::logic_error::logic_error;\n\n};\n\n\n\n} // namespace exception\n\n} // namespace cli\n\n\n\n#endif // LIBCLICXX_EXCEPTION_H_INCLUDED\n", "file_path": "cpp/libedit-test/include/clicxx/Exception.h", "rank": 61, "score": 123896.83131250391 }, { "content": "class Runtime : public std::runtime_error\n\n{\n\n using std::runtime_error::runtime_error;\n\n};\n\n\n", "file_path": "cpp/libedit-test/include/clicxx/Exception.h", "rank": 62, "score": 123896.83131250391 }, { "content": "enum class edit { nothing, substitute, insert, remove };\n\n\n\n\n\ntemplate <typename Matrix>\n\nauto levenshtein_distance_edit_path(Matrix const& matrix, std::size_t rows,\n\n std::size_t cols) -> std::vector<edit> {\n\n // first = row, second = column\n\n using pos_type = std::pair<std::size_t, std::size_t>;\n\n\n\n auto min_position = [&](pos_type substitute, pos_type insert,\n\n pos_type remove) -> pos_type {\n\n auto min = substitute;\n\n if (matrix[insert.first][insert.second] < matrix[min.first][min.second])\n\n min = insert;\n\n if (matrix[remove.first][remove.second] < matrix[min.first][min.second])\n\n min = remove;\n\n return min;\n\n };\n\n\n\n std::vector<edit> edits;\n", "file_path": "cpp/LevenshteinDistance.cpp", "rank": 63, "score": 121510.16987187097 }, { "content": "#include <iostream>\n\n\n\n#include \"typelist.hpp\"\n\n\n\n\n\nint main() {\n\n using namespace tl;\n\n \n\n using A = typelist<int, void *>;\n\n\n\n // B = typelist<int, void *, long>\n\n using B = push_back_t<A, long>;\n\n std::cout\n\n << std::boolalpha << std::is_same<B, typelist<int, void *, long>>::value\n\n << \"\\n\";\n\n\n\n // C = typelist<double, int, void *, long>\n\n using C = push_front_t<B, double>;\n\n std::cout\n\n << std::is_same<C, typelist<double, int, void *, long>>::value\n", "file_path": "cpp/meta/typelist.test.cpp", "rank": 65, "score": 116528.22280801549 }, { "content": "#ifndef CONTENT_H\n\n#define CONTENT_H\n\n\n\n\n\n#include <string>\n\n#include <vector>\n\n\n\n#include <cppcms/view.h>\n\n\n\nnamespace content {\n\n\n\n\n", "file_path": "cpp/cppcms/include/templates/content.h", "rank": 66, "score": 116526.07919750696 }, { "content": " // G = typelist<void *, int, double, long, void *, int>\n\n using G = pop_back_t<F>;\n\n std::cout\n\n << std::is_same<G, typelist<void *, int, double, long, void *, int>>::value\n\n << \"\\n\";\n\n\n\n // H = void *\n\n using H = at_c_t<G, 0>;\n\n std::cout\n\n << std::is_same<H, void *>::value\n\n << \"\\n\";\n\n\n\n // I = void *\n\n using I = front_t<G>;\n\n std::cout\n\n << std::is_same<H, I>::value\n\n << \"\\n\";\n\n \n\n // J = typelist<void *, int, double, long, void *, int, char *>\n\n using J = insert_c_t<G, char *, 6>;\n", "file_path": "cpp/meta/typelist.test.cpp", "rank": 67, "score": 116522.1934870411 }, { "content": " std::cout\n\n << std::is_same<J, typelist<void *, int, double, long, void *, int, char *>>::value\n\n << \"\\n\";\n\n \n\n // K = typelist<void *, int, double, long, void *, int>\n\n using K = remove_c_t<J, 6>;\n\n std::cout\n\n << std::is_same<K, typelist<void *, int, double, long, void *, int>>::value\n\n << \"\\n\";\n\n}\n", "file_path": "cpp/meta/typelist.test.cpp", "rank": 68, "score": 116518.68484841475 }, { "content": " << \"\\n\";\n\n\n\n // D = typelist<double, int, void *, long, double, int, void *, long>\n\n using D = concat_t<C, C>;\n\n std::cout\n\n << std::is_same<D, typelist<double, int, void *, long, double, int, void *, long>>::value\n\n << \"\\n\";\n\n\n\n // E = typelist<long, void *, int, double, long, void *, int, double>\n\n using E = reverse_t<D>;\n\n std::cout\n\n << std::is_same<E, typelist<long, void *, int, double, long, void *, int, double>>::value\n\n << \"\\n\";\n\n\n\n // F = typelist<void *, int, double, long, void *, int, double>\n\n using F = pop_front_t<E>;\n\n std::cout\n\n << std::is_same<F, typelist<void *, int, double, long, void *, int, double>>::value\n\n << \"\\n\";\n\n\n", "file_path": "cpp/meta/typelist.test.cpp", "rank": 69, "score": 116518.22998567218 }, { "content": " private:\n\n MenuIdentity mIdentity;\n\n std::string mName;\n\n std::string mLink;\n\n Menu mChildItems;\n\n };\n\n\n\n struct master : public cppcms::base_content {\n\n bool const cfgDemo = false;\n\n bool const cfgSearch = false;\n\n\n\n std::string title;\n\n std::string panelTitle;\n\n Menu menu;\n\n MenuIdentity active;\n\n };\n\n\n\n struct news : public master {\n\n std::list<std::string> news_list;\n\n };\n\n\n\n struct page : public master {\n\n std::string page_title, page_content;\n\n };\n\n}\n\n\n\n#endif // CONTENT_H\n", "file_path": "cpp/cppcms/include/templates/content.h", "rank": 70, "score": 116515.43205303828 }, { "content": " class reference_t : public base_reference_t<reference_t<T>> {\n\n public:\n\n using value_type = typename reference_traits<reference_t<T>>::value_type;\n\n using pointer_type = typename reference_traits<reference_t<T>>::pointer_type;\n\n\n\n\n\n public:\n\n explicit reference_t(HANDLE process_handle, pointer_type address) :\n\n base_reference_t<reference_t<T>>(process_handle, address)\n\n {}\n\n\n\n\n\n // assign value\n\n reference_t& operator=(value_type const& value) {\n\n if (!WriteProcessMemory(this->get_process_handle(), reinterpret_cast<LPVOID>(this->get_address()), reinterpret_cast<LPCVOID>(&value), sizeof(value), nullptr))\n\n throw make_system_except(GetLastError(), \"cannot write process memory\");\n\n\n\n return *this;\n\n }\n\n\n", "file_path": "cpp/windows/mini-memory-scanner/process/memory/range.h", "rank": 71, "score": 115075.6552753909 }, { "content": " class iterator_t : public base_iterator_t<iterator_t<T>> {\n\n public:\n\n using pointer_type = typename iterator_traits<iterator_t<T>>::pointer_type;\n\n\n\n\n\n public:\n\n iterator_t() :\n\n base_iterator_t<iterator_t<T>>()\n\n {}\n\n\n\n explicit iterator_t(HANDLE process_handle, pointer_type address) :\n\n base_iterator_t<iterator_t<T>>(process_handle, address)\n\n {}\n\n\n\n\n\n // convert to const_iterator_t<T>\n\n operator const_iterator_t<T>() {\n\n return const_iterator_t<T>{ this->get_process_handle(), this->get_address() };\n\n }\n\n };\n", "file_path": "cpp/windows/mini-memory-scanner/process/memory/range.h", "rank": 72, "score": 115075.6552753909 }, { "content": " class const_reference_t : public base_reference_t<const_reference_t<T>> {\n\n public:\n\n using pointer_type = typename reference_traits<const_reference_t<T>>::pointer_type;\n\n\n\n\n\n public:\n\n explicit const_reference_t(HANDLE process_handle, pointer_type address) :\n\n base_reference_t<const_reference_t<T>>(process_handle, address)\n\n {}\n\n\n\n\n\n // cannot assign value to reference to const\n\n void operator=(const_reference_t const&) = delete;\n\n };\n\n\n\n\n\n //\n\n // present a reference to a T in remote process\n\n //\n\n template<typename T>\n", "file_path": "cpp/windows/mini-memory-scanner/process/memory/range.h", "rank": 73, "score": 111352.59631084191 }, { "content": " class const_iterator_t : public base_iterator_t<const_iterator_t<T>> {\n\n public:\n\n using pointer_type = typename iterator_traits<const_iterator_t<T>>::pointer_type;\n\n\n\n\n\n public:\n\n const_iterator_t() :\n\n base_iterator_t<const_iterator_t<T>>()\n\n {}\n\n\n\n explicit const_iterator_t(HANDLE process_handle, pointer_type address) :\n\n base_iterator_t<const_iterator_t<T>>(process_handle, address)\n\n {}\n\n };\n\n\n\n\n\n //\n\n // iterator of T in remote process\n\n //\n\n template<typename T>\n", "file_path": "cpp/windows/mini-memory-scanner/process/memory/range.h", "rank": 74, "score": 111352.59631084191 }, { "content": " class MenuItem {\n\n public:\n\n MenuItem() = default;\n\n\n\n explicit MenuItem(std::string const& name, std::string const& link, MenuIdentity identity)\n\n : mName(name)\n\n , mLink(link)\n\n , mIdentity(identity)\n\n {}\n\n\n\n MenuIdentity Identity() const { return mIdentity; }\n\n std::string const& Name() const { return mName; }\n\n std::string const& Link() const { return mLink; }\n\n Menu const& ChildItems() const { return mChildItems; }\n\n\n\n MenuItem& Add(MenuItem child) {\n\n mChildItems.emplace_back(std::move(child));\n\n return *this;\n\n }\n\n\n", "file_path": "cpp/cppcms/include/templates/content.h", "rank": 75, "score": 110974.88324442388 }, { "content": " class const_iterator_t : public base_iterator_t<const_iterator_t<T>> {\n\n public:\n\n using pointer_type = typename const_iterator_t<T>::pointer_type;\n\n using container_iterator_type = typename const_iterator_t<T>::container_iterator_type;\n\n\n\n\n\n public:\n\n const_iterator_t() :\n\n base_iterator_t<const_iterator_t<T>>()\n\n {}\n\n\n\n explicit const_iterator_t(\n\n HANDLE process_handle,\n\n pointer_type base,\n\n container_iterator_type begin,\n\n container_iterator_type it\n\n ) :\n\n base_iterator_t<const_iterator_t<T>>(process_handle, base, begin, it)\n\n {}\n\n };\n", "file_path": "cpp/windows/mini-memory-scanner/process/memory/const_range.h", "rank": 76, "score": 109598.34070244106 }, { "content": " class const_reference_t : public base_reference_t<const_reference_t<T>> {\n\n public:\n\n using pointer_type = typename reference_traits<const_reference_t<T>>::pointer_type;\n\n using container_iterator_type = typename reference_traits<const_reference_t<T>>::container_iterator_type;\n\n\n\n\n\n public:\n\n explicit const_reference_t(\n\n HANDLE process_handle,\n\n pointer_type base,\n\n container_iterator_type begin,\n\n container_iterator_type it\n\n ) :\n\n base_reference_t<const_reference_t<T>>(process_handle, base, std::move(begin), std::move(it))\n\n {}\n\n\n\n\n\n // cannot assign value to reference to const\n\n void operator=(const_reference_t const&) = delete;\n\n };\n\n\n\n\n\n //\n\n // base class for iterator_t and const_iterator_t\n\n //\n\n template<typename DerivedIterator>\n", "file_path": "cpp/windows/mini-memory-scanner/process/memory/const_range.h", "rank": 77, "score": 109598.34070244106 }, { "content": "class Query : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:Query) */ {\n\n public:\n\n Query();\n\n virtual ~Query();\n\n\n\n Query(const Query& from);\n\n\n\n inline Query& operator=(const Query& from) {\n\n CopyFrom(from);\n\n return *this;\n\n }\n\n\n\n static const ::google::protobuf::Descriptor* descriptor();\n\n static const Query& default_instance();\n\n\n\n static inline const Query* internal_default_instance() {\n\n return reinterpret_cast<const Query*>(\n\n &_Query_default_instance_);\n\n }\n\n static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =\n", "file_path": "cpp/protobuf/message.pb.h", "rank": 78, "score": 109457.653860724 }, { "content": " enum class MenuIdentity {\n\n Invalid,\n\n Home,\n\n Page,\n\n News\n\n };\n\n\n\n struct MenuItem;\n\n using Menu = std::vector<MenuItem>;\n\n\n", "file_path": "cpp/cppcms/include/templates/content.h", "rank": 79, "score": 108397.61822497295 }, { "content": "// @@protoc_insertion_point(includes)\n\nclass QueryDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<Query> {\n\n} _Query_default_instance_;\n\n\n\nnamespace protobuf_message_2eproto {\n\n\n\n\n\nnamespace {\n\n\n\n::google::protobuf::Metadata file_level_metadata[1];\n\n\n\n} // namespace\n\n\n\nPROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTableField\n\n const TableStruct::entries[] = {\n\n {0, 0, 0, ::google::protobuf::internal::kInvalidMask, 0, 0},\n\n};\n\n\n\nPROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::AuxillaryParseTableField\n\n const TableStruct::aux[] = {\n\n ::google::protobuf::internal::AuxillaryParseTableField(),\n", "file_path": "cpp/protobuf/message.pb.cc", "rank": 80, "score": 107626.50957762229 }, { "content": "// Internal implementation detail -- do not call these.\n\nstruct TableStruct {\n\n static const ::google::protobuf::internal::ParseTableField entries[];\n\n static const ::google::protobuf::internal::AuxillaryParseTableField aux[];\n\n static const ::google::protobuf::internal::ParseTable schema[];\n\n static const ::google::protobuf::uint32 offsets[];\n\n static void InitDefaultsImpl();\n\n static void Shutdown();\n\n};\n\nvoid AddDescriptors();\n\nvoid InitDefaults();\n\n} // namespace protobuf_message_2eproto\n\n\n\n// ===================================================================\n\n\n", "file_path": "cpp/protobuf/message.pb.h", "rank": 81, "score": 106487.234931849 }, { "content": "struct TestStruct;\n\n\n\n// 0\n\n// Inheret methods (0) are prefered over trait methods (1).\n\nimpl TestStruct {\n\n // refer(self: &TestStruct)\n\n fn refer(&self) -> String {\n\n String::from(\"0.1-&TestStruct\")\n\n }\n\n\n\n // eatup(self: TestStruct)\n\n fn eatup(self) -> String {\n\n String::from(\"0.2-TestStruct\")\n\n }\n\n}\n\n\n\n// 1\n\nimpl Trait for TestStruct {\n\n // refer(self: &TestStruct)\n\n fn refer(&self) -> String {\n", "file_path": "rust/snippets/src/implref.rs", "rank": 82, "score": 105472.10996679703 }, { "content": "struct AttachKey { int type; Token key; };\n", "file_path": "cpp/my-dict/db/sqlite/sqlite3.c", "rank": 83, "score": 100441.66167288859 }, { "content": " Fts3HashElem *next, *prev; /* Next and previous elements in the table */\n", "file_path": "cpp/my-dict/db/sqlite/sqlite3.c", "rank": 84, "score": 100424.96600672849 }, { "content": "def index(request):\n", "file_path": "python/djangotest/testsite/testapp/views.py", "rank": 85, "score": 99264.18544361068 }, { "content": "struct all_same;\n\n\n\ntemplate<typename First, typename Second, typename... Rest>\n", "file_path": "cpp/ExtendedIsSame.cpp", "rank": 86, "score": 98422.10379156575 }, { "content": "#define REGISTER_TYPE_NAME(TYPE, NAME) \\\n\n class TYPE##_type_name_t { \\\n\n TYPE##_type_name_t() { \\\n\n meta::types().emplace_back(typeid(TYPE), get_type_name<TYPE>(), \\\n\n NAME); \\\n\n } \\\n\n } TYPE##_type_name;\n\n\n\n\n", "file_path": "cpp/simple-reflection/main.cpp", "rank": 87, "score": 98116.8671413193 }, { "content": "struct Value {\n\n Value() : type(Type::Null) {}\n\n\n\n Type type;\n\n boost::any internal;\n\n};\n\n\n\nusing Object = std::list<std::pair<std::string, Value>>;\n\nusing Array = std::list<Value>;\n\n\n\n\n\nbool IsString(Value const& v) {\n\n return v.type == Type::String;\n\n}\n\n\n\nbool IsNumber(Value const& v) {\n\n return v.type == Type::Number;\n\n}\n\n\n\nbool IsBoolean(Value const& v) {\n", "file_path": "cpp/AnyValue3.cpp", "rank": 88, "score": 96854.58949281988 }, { "content": "struct iterator {\n\n iterator() = default;\n\n iterator(std::array<int, 6> *array, int pos) :\n\n m_wo{ array, pos },\n\n m_is_end{ false }\n\n {\n\n if (m_wo.pos >= 6) {\n\n m_is_end = true;\n\n }\n\n }\n\n\n\n auto operator!=(iterator const&) const -> bool {\n\n return !m_is_end;\n\n }\n\n\n\n auto operator++() -> iterator& {\n\n ++m_current_index;\n\n if (m_current_index >= 6) {\n\n m_is_end = true;\n\n }\n", "file_path": "cpp/GenericBacktrack.cpp", "rank": 89, "score": 95365.33515007932 }, { "content": "struct Token {\n\n TokenKind kind;\n\n char const* begin;\n\n char const* end;\n\n};\n\n\n\n\n\nstd::string ToReadable(Token const& tok) {\n\n if (tok.begin == tok.end) {\n\n if (tok.kind == TokenKind::EndOfFile) {\n\n return \"[EOF]\";\n\n }\n\n return \"[empty]\";\n\n }\n\n\n\n std::string result;\n\n for (char const* it = tok.begin; it != tok.end; ++it) {\n\n switch (*it) {\n\n case '\\r':\n\n result += \"\\\\r\";\n", "file_path": "cpp/IniParser.cpp", "rank": 90, "score": 95365.33515007932 }, { "content": "struct Keyword {\n\n char const* string;\n\n std::size_t length;\n\n TokType type;\n\n};\n\n\n\nstatic Keyword const gKeywords[] = {\n\n {\"print\", sizeof(\"print\") - 1, TokType::KwPrint}\n\n};\n\n\n\nbool GetKeyword(char const* p, Keyword& keyword) {\n\n for (auto const& kw : gKeywords) {\n\n bool mismatch = false;\n\n for (std::size_t i = 0; i < kw.length; ++i) {\n\n if (p[i] != kw.string[i]) {\n\n mismatch = true;\n\n break;\n\n }\n\n }\n\n if (mismatch || std::isalnum(p[kw.length])) continue;\n", "file_path": "cpp/ExpressionParser2.cpp", "rank": 91, "score": 95365.33515007932 }, { "content": "struct object {\n\n static constexpr std::size_t dummy = (std::size_t)-1;\n\n\n\n std::size_t const identity;\n\n int const weight;\n\n};\n\n\n\nauto operator<<(std::ostream& os, object const& obj) -> std::ostream& {\n\n os << \"[\" << obj.identity << \"] \" << obj.weight;\n\n return os;\n\n}\n\n\n\nauto operator<(object const& lhs, object const& rhs) -> bool {\n\n return lhs.weight < rhs.weight;\n\n}\n\n\n\n\n", "file_path": "cpp/BinPacking.cpp", "rank": 92, "score": 95365.33515007932 }, { "content": "struct bin {\n\n int capacity;\n\n std::vector<object> objects;\n\n};\n\n\n\n\n\nauto bin_packing(std::multiset<object>& objs) -> std::vector<bin> {\n\n auto find_best_fit = [](auto& objs, int capacity) {\n\n auto it = objs.upper_bound(object{ object::dummy, capacity });\n\n if (it == objs.begin() || objs.empty())\n\n return objs.end();\n\n else\n\n return std::prev(it);\n\n };\n\n\n\n std::vector<bin> bins;\n\n bins.push_back(bin{ 10 });\n\n while (!objs.empty()) {\n\n auto& current_bin = bins.back();\n\n auto found = find_best_fit(objs, current_bin.capacity);\n", "file_path": "cpp/BinPacking.cpp", "rank": 93, "score": 95365.33515007932 }, { "content": "struct Location {\n\n unsigned int line;\n\n unsigned int column;\n\n};\n\n\n\n\n\nstd::ostream& operator<<(std::ostream& os, Location const& loc) {\n\n os << \"(line = \" << loc.line << \", column = \" << loc.column << ')';\n\n return os;\n\n}\n\n\n\n\n\nLocation GetLocation(char const* source, Token const& tok) {\n\n Location loc{ 1, 1 };\n\n for (; source != tok.begin; ++source) {\n\n if (*source == '\\n') {\n\n ++loc.line;\n\n loc.column = 1;\n\n } else {\n\n ++loc.column;\n\n }\n\n }\n\n return loc;\n\n}\n\n\n\n\n", "file_path": "cpp/IniParser.cpp", "rank": 94, "score": 95365.33515007932 }, { "content": "struct section_t {\n\n std::string name;\n\n std::vector<key_value_t> kvs;\n\n};\n\n\n\n\n\nusing ini_t = std::vector<section_t>;\n\n\n\n\n\nstd::stringstream error;\n\n\n\n\n\nbool ParseKeyValue(char const* source, std::vector<Token>::iterator& stok, key_value_t& kv) {\n\n kv.key.clear();\n\n kv.value.clear();\n\n\n\n std::vector<Token>::iterator itok = stok;\n\n\n\n if (itok->kind != TokenKind::Identifier) {\n\n error << \"Key=Value : expect key-identifier, get \" << *itok << \" at \" << GetLocation(source, *itok) << \"\\n\";\n", "file_path": "cpp/IniParser.cpp", "rank": 95, "score": 95365.33515007932 }, { "content": "#include <iostream>\n\n#include <type_traits>\n\n\n\n\n\nnamespace array {\n\n\n\n\n\n template<typename T, std::size_t Size>\n", "file_path": "cpp/ExpressionTemplate2.cpp", "rank": 96, "score": 21.052616590387725 }, { "content": "#ifndef PROCESS_MEMORY_RANGE_H\n\n#define PROCESS_MEMORY_RANGE_H\n\n\n\n\n\n#include <cstdint>\n\n#include <memory>\n\n#include <stdexcept>\n\n#include <string>\n\n#include <vector>\n\n\n\n#include <windows.h>\n\n\n\n#include \"utility/utility.h\"\n\n#include \"const_range.h\"\n\n#include \"utility.h\"\n\n\n\n\n\nnamespace process { namespace memory {\n\n\n\n\n\n namespace detail { namespace range {\n\n\n\n\n\n //\n\n //\n\n //\n\n template<typename T>\n", "file_path": "cpp/windows/mini-memory-scanner/process/memory/range.h", "rank": 97, "score": 20.796751748714144 }, { "content": "#include <iostream>\n\n\n\n\n\nnamespace array {\n\n\n\n\n\n template<typename T, std::size_t Size>\n", "file_path": "cpp/ExpressionTemplate.cpp", "rank": 98, "score": 20.59017858880964 }, { "content": "#include <algorithm>\n\n#include <iostream>\n\n#include <string>\n\n#include <boost/bimap.hpp>\n\n\n\n\n\nint main() {\n\n using bm_type = boost::bimap<int, std::string>;\n\n using bm_value_type = bm_type::value_type;\n\n\n\n // create a simple bimap\n\n // both sides (left + right) are unique keys\n\n bm_type m{};\n\n\n\n // insert elements\n\n m.insert({ 1, \"one\" });\n\n m.insert({ 2, \"two\" });\n\n m.insert({ 3, \"three\" });\n\n m.insert({ 4, \"four\" });\n\n m.insert({ 5, \"five\" });\n", "file_path": "cpp/BimapExample.cpp", "rank": 99, "score": 20.582536147945873 } ]
C++
cplusplus/call/src/alignment_functions.cpp
erasmus-center-for-biomics/Nimbus
bbf7ca288d798d8f1c6156ddf45fed31892bd557
#include <cstdlib> #include <string> #include <sstream> #include <iostream> #include <vector> #include <algorithm> #include <sam.h> #include <alignment_functions.h> #include <cigar.h> #include <sample.h> namespace nimbus { std::string alignment_sequence( const bam1_t* alignment, int start, int end ) { std::stringstream rval ; uint8_t* s = bam_get_seq( alignment ) ; for( int i=start; i<=end; ++i ) { int b = bam_seqi( s, i ) ; switch(b) { case 1: rval << "A" ; break ; case 2: rval << "C" ; break ; case 4: rval << "G" ; break ; case 8: rval << "T" ; break ; default: rval << "N" ; break ; } } return rval.str() ; } int alignment_sequence_quality( const bam1_t* alignment, int start, int end ) { int rval = 0 ; uint8_t* q = bam_get_qual( alignment ) ; for( int i=start; i<=end; ++i ) { rval += (int) q[i] ; } rval /= end - start + 1 ; return rval ; } std::string Sequence( int tid, int pos, const bam1_t* alignment, void* results ) { std::string rval = "" ; int variantqual = 0 ; std::size_t relpos = 0 ; if( alignment->core.pos < pos ) { relpos = (std::size_t) pos - alignment->core.pos ; } Cigar cigar = Cigar( ) ; cigar.from_hts_cigar( bam_get_cigar(alignment), alignment->core.n_cigar ) ; std::size_t opbin = 0 ; std::size_t oppos = 0 ; std::size_t q_pos = cigar.reference_offset_to_query_offset( relpos, opbin, oppos ) ; bool calledindel = false ; if( cigar.at( opbin )->operation() == 'M' || cigar.at( opbin )->operation() == '=' || cigar.at( opbin )->operation() == 'X') { if( (oppos) == cigar.at( opbin )->runLength() - 1) { if ( opbin < cigar.length() - 1 ) { if( cigar.at( opbin + 1 )->operation() == 'D' ) { rval = alignment_sequence( alignment, q_pos, q_pos ) ; rval += std::string( cigar.at( opbin + 1 )->runLength(), '-' ) ; variantqual = alignment_sequence_quality( alignment, q_pos, q_pos ) ; calledindel = true ; } else if( cigar.at( opbin + 1)->operation() == 'I' ) { calledindel = true ; rval = alignment_sequence( alignment, q_pos, q_pos + cigar.at( opbin + 1 )->runLength() ) ; variantqual = alignment_sequence_quality( alignment, q_pos, q_pos + cigar.at( opbin + 1 )->runLength() ) ; } } } if( ! calledindel ) { rval = alignment_sequence( alignment, q_pos, q_pos ) ; variantqual = alignment_sequence_quality( alignment, q_pos, q_pos ) ; } } if( results != NULL ) { SequenceInformation* ret = (SequenceInformation*) results ; ret->query_position = q_pos ; ret->quality = variantqual ; } return rval ; } std::string ReadGroup( const bam1_t* alignment ) { std::string rval = "unknown" ; uint8_t* p = bam_aux_get( alignment, "RG" ) ; if( p ) { rval = std::string( bam_aux2Z(p) ) ; } return rval ; } std::string GetLabel( const bam1_t* alignment, std::string label ) { std::string rval = "unknown" ; if( label.size() != 2 ) return rval ; uint8_t* p = bam_aux_get( alignment, label.c_str() ) ; if( p ) { rval = std::string( bam_aux2Z(p) ) ; } return rval ; } std::string Strand( const bam1_t* alignment ) { return bam_is_rev(alignment) ? "reverse" : "forward" ; } std::string Amplicon( const bam1_t* alignment ) { uint8_t* p = bam_aux_get( alignment, "am" ) ; if( p ) { return std::string( bam_aux2Z(p) ) ; } return "unknown" ; } }
#include <cstdlib> #include <string> #include <sstream> #include <iostream> #include <vector> #include <algorithm> #include <sam.h> #include <alignment_functions.h> #include <cigar.h> #include <sample.h> namespace nimbus { std::string alignment_sequence( const bam1_t* alignment, int start, int end ) { std::stringstream rval ; uint8_t* s = bam_get_seq( alignment ) ; for( int i=start; i<=end; ++i ) { int b = bam_seqi( s, i ) ; switch(b) { case 1: rval << "A" ; break ; case 2: rval << "C" ; break ; case 4: rval << "G" ; break ; case 8: rval << "T" ; break ; default: rval << "N" ; break ; } } return rval.str() ; } int alignment_sequence_quality( const bam1_t* alignment, int start, int end ) { int rval = 0 ; uint8_t* q = bam_get_qual( alignment ) ; for( int i=start; i<=end; ++i ) { rval += (int) q[i] ; } rval /= end - start + 1 ; return rval ; } std::string Sequence( int tid, int pos, const bam1_t* alignment, void* results ) { std::string rval = "" ; int variantqual = 0 ; std::size_t relpos = 0 ; if( alignment->core.pos < pos ) { relpos = (std::size_t) pos - alignment->core.pos ; } Cigar cigar = Cigar( ) ; cigar.from_hts_cigar( bam_get_cigar(alignment), alignment->core.n_cigar ) ; std::size_t opbin = 0 ; std::size_t oppos = 0 ; std::size_t q_pos = cigar.reference_offset_to_query_offset( relpos, opbin, oppos ) ; bool calledindel = false ; if( cigar.at( opbin )->operation() == 'M' || cigar.at( opbin )->operation() == '=' || cigar.at( opbin )->operation() == 'X') { if( (oppos) == cigar.at( opbin )->runLength() - 1) { if ( opbin < cigar.length() - 1 ) { if( cigar.at( opbin + 1 )->operation() == 'D' ) { rval = alignment_sequence( alignment, q_pos, q_pos ) ; rval += std::string( cigar.at( opbin + 1 )->runLength(), '-' ) ; variantqual = alignment_sequence_quality( alignment, q_pos, q_pos ) ; calledindel = true ; } else if( cigar.at( opbin + 1)->operation() == 'I' ) { calledindel = true ; rval = alignment_sequence( alignment, q_pos, q_pos + cigar.at( opbin + 1 )->runLength() ) ; variantqual = alignment_sequence_quality( alignment, q_pos, q_pos + cigar.at( opbin + 1 )->runLength() ) ; } } } if( ! calledindel ) { rval = alignment_sequence( alignment, q_pos, q_pos ) ; variantqual = alignment_sequence_quality( alignment, q_pos, q_pos ) ; } } if( results != NULL ) { SequenceInformation* ret = (SequenceInformation*) results ; ret->query_position = q_pos ; ret->quality = variantqual ; } return rval ; } std::string ReadGroup( const bam1_t* alignment ) { std::string rval = "unknown" ; uint8_t* p = bam_aux_get( alignment, "RG" ) ; if( p ) { rval = std::string( bam_aux2Z(p) ) ; } return rval ; } std::string GetLabel( const bam1_t* alignment, std::string label ) {
std::string Strand( const bam1_t* alignment ) { return bam_is_rev(alignment) ? "reverse" : "forward" ; } std::string Amplicon( const bam1_t* alignment ) { uint8_t* p = bam_aux_get( alignment, "am" ) ; if( p ) { return std::string( bam_aux2Z(p) ) ; } return "unknown" ; } }
std::string rval = "unknown" ; if( label.size() != 2 ) return rval ; uint8_t* p = bam_aux_get( alignment, label.c_str() ) ; if( p ) { rval = std::string( bam_aux2Z(p) ) ; } return rval ; }
function_block-function_prefix_line
[ { "content": "\tclass CigarOperation {\n\n\t\tchar _operation ;\n\n\t\tstd::size_t _runlength ;\n\n\n\n\tpublic:\n\n\t\tCigarOperation() {\n\n\t\t\t_operation = '?' ;\n\n\t\t\t_runlength = 0 ;\n\n\t\t}\n\n\n\n\t\tCigarOperation( char o, std::size_t n ) {\n\n\t\t\tset( o, n ) ;\n\n\t\t}\n\n\n\n\t\tvoid set( char o, std::size_t n ) {\n\n\t\t\t_operation = o ;\n\n\t\t\t_runlength = n ;\n\n\t\t}\n\n\n\n\t\tstd::size_t runLength() const {\n", "file_path": "cplusplus/call/include/cigar.h", "rank": 0, "score": 137270.84160834848 }, { "content": "\tclass Cigar {\n\n\n\n\t\tCigarOperation* _segments ;\n\n\t\tstd::size_t _n ;\n\n\n\n\tpublic:\n\n\t\tCigar() ;\t\t\n\n\n\n\t\t~Cigar() ;\n\n\n\n\t\tvoid reset( ) ;\n\n\n\n\t\tvoid from_hts_cigar( uint32_t* content, int clen ) ;\n\n\n\n\t\tstd::size_t query_length( ) const ;\n\n\n\n\t\tstd::size_t reference_length( ) const ;\n\n\n\n\t\tstd::size_t length( ) const ;\n\n\n", "file_path": "cplusplus/call/include/cigar.h", "rank": 1, "score": 129446.92680734087 }, { "content": "\t\tclass Alignment {\n\n\t\t\t/*\n\n\t\t\tThe base class of the classes implementing alignment algorithms\n\n\n\n\t\t\tAlignment matrices are represented as follows:\n\n\n\n\t\t\t - S u b j e c t\n\n\t\t\t- # # # # # # # #\n\n\t\t\tQ # # # # # # # #\n\n\t\t\tu # # # # # # # #\n\n\t\t\te # # # # # # # #\n\n\t\t\tr # # # # # # # #\n\n\t\t\ty # # # # # # # #\n\n\n\n\t\t\t */\n\n\t\tprotected:\n\n\n\n\t\t\t// the score matrix\n\n\t\t\tint** scores ;\n\n\n", "file_path": "cplusplus/align/lib/libnimbus/include/Alignment.h", "rank": 2, "score": 93334.25862084233 }, { "content": "\t\tclass AlignmentScore {\n\n\n\n\t\tpublic:\n\n\t\t\t// the scores\n\n\t\t\tint _match ;\t// match\n\n\t\t\tint _mismatch ;\t// mismatch\n\n\t\t\tint _gap ;\t\t// gap\n\n\t\t\tint _maxamp ; // maximum number of amplicons\n\n\t\tpublic:\n\n\t\t\tAlignmentScore( int m, int mm, int g, int maxamp): _match(m), _mismatch(mm), _gap(g), _maxamp(maxamp) {}\n\n\t\t\t~AlignmentScore( ) {}\n\n\n\n\t\t\t/** \n\n\t\t\t Get the score with reference r and query q\n\n\t\t\t **/\n\n\t\t\tint score( char r, char q ) const ;\n\n\n\n\t\t\tstd::string str() const ;\n\n\t\t} ;\n\n\n\n\n\n\n\n\t\t// define the directions\n\n\t\tenum directions_t { d_BOUND, d_DIAG, d_VERTICAL, d_HORIZONTAL } ;\n\n\t\t//int D_BOUND = 0 ;\n\n\t\t//int D_DIAG = 1 ;\n\n\t\t//int D_DOWN = 2 ;\n\n\t\t//int D_RIGHT = 3 ;\n\n\n", "file_path": "cplusplus/align/lib/libnimbus/include/Alignment.h", "rank": 3, "score": 91879.53324312744 }, { "content": "\t\t\t\tquery = \"\" ;\n\n\t\t\t\tscores = NULL ;\n\n\t\t\t\tdirections = NULL ;\t\t\t\t\n\n\t\t\t\t_max = 0 ;\n\n\t\t\t\t_coord = std::pair<int,int>( 0, 0 ) ;\n\n\t\t\t}\n\n\n\n\t\t\t~Alignment(void) ; \n\n\n\n\t\t\t/**\n\n\t\t\t Get the path through the matrix for the best alignment\n\n\t\t\t **/ \n\n\t\t\tstd::vector< std::pair<int,int> >* getPath( ) const ;\n\n\n\n\t\t\t/** \n\n\t\t\t Get the path through the matrix for the alignment starting at coordinate x and y in the matrix\n\n\t\t\t **/\n\n\t\t\tstd::vector< std::pair<int,int> >* getPath( int x, int y ) const ;\n\n\t\t\tstd::vector< std::pair<int,int> >* getPath( std::pair<int, int> coord ) const ;\n\n\n", "file_path": "cplusplus/align/lib/libnimbus/include/Alignment.h", "rank": 4, "score": 91019.7869193261 }, { "content": "\t\t\t **/ \n\n\t\t\tstd::vector<char> QCIGAR() const ;\t\t\n\n\t\t\n\n\t\t\tstd::vector<char> QCIGAR( std::vector< std::pair<int,int> > path ) const ;\n\n\n\n\t\t\t/**\n\n\t\t\t This method is specific foreach alignment method\n\n\t\t\t **/\n\n\t\t\tvirtual void fillMatrix( std::string ref, std::string q ) {}\n\n\n\n\t\t\tstd::string formatScoreMatrix( ) ;\n\n\t\t\tstd::string formatDirectionMatrix( ) ;\n\n\n\n\t\t\t/**\n\n\t\t\t * Returns a presentation of the matrix\n\n\t\t\t **/\n\n\t\t\tstd::string str() const ;\n\n\n\n\t\t\t\n\n\t\tprotected:\n\n\t\t\tvoid _clean_matrix( ) ; \n\n\t\t} ;\n\n\n\n\n", "file_path": "cplusplus/align/lib/libnimbus/include/Alignment.h", "rank": 5, "score": 91019.47224738596 }, { "content": "\t\t\t/** \n\n\t\t\t Get the end coordinates of the best alignment\n\n\t\t\t **/\n\n\t\t\tstd::pair<int,int> bestAlignment() const {\n\n\t\t\t\treturn _coord ;\n\n\t\t\t}\n\n\n\n\t\t\t/**\n\n\t\t\t Get the maximum alignment score\n\n\t\t\t **/\n\n\t\t\tint getAlignmentScore( ) const ;\t\t\t\n\n\n\n\t\t\t/**\n\n\t\t\t Get the alignment score at coordinate x and y\n\n\t\t\t **/\n\n\t\t\tint getAlignmentScore( int x, int y ) const ;\n\n\t\t\tint getAlignmentScore( std::pair<int, int> coord ) const ;\n\n\n\n\t\t\t/** \n\n\t\t\t Get the CIGAR string for the Query against the reference in a character vector\n", "file_path": "cplusplus/align/lib/libnimbus/include/Alignment.h", "rank": 6, "score": 91015.8281541798 }, { "content": "\t\t\t// 4 directions:\n\n\t\t\t//\t- 0 boundary\n\n\t\t\t//\t- 1, match or mismatch\n\n\t\t\t//\t- 2, subject -, query base\n\n\t\t\t//\t- 3, subject base, query - \t\t\t\n\n\t\t\tint** directions ;\n\n\n\n\t\t\t// the subject and query functions\n\n\t\t\tstd::string subject ;\n\n\t\t\tstd::string query ;\n\n\n\n\t\t\t// Variables for the trace back\n\n\t\t\tint _max ;\t\t\t\t\t// maximum score \n\n\t\t\tstd::pair<int,int> _coord ;\t// query and subject positions of the maximum score\n\n\t\t\t\n\n\t\t\tAlignmentScore* scorecalc ;\n\n\n\n\t\tpublic:\t\t\n\n\t\t\tAlignment( AlignmentScore* as ) : scorecalc(as) {\n\n\t\t\t\tsubject = \"\" ;\n", "file_path": "cplusplus/align/lib/libnimbus/include/Alignment.h", "rank": 7, "score": 91009.21020286887 }, { "content": "#pragma once\n\n\n\nnamespace Nimbus {\n\n\n\n\tnamespace alignment {\n\n\n\n\t\t//\n\n\t\t// A class to \n\n\t\t//\n\n\n\n\t\t\n\n\n", "file_path": "cplusplus/align/lib/libnimbus/include/Alignment.h", "rank": 8, "score": 91005.55752107943 }, { "content": " class SequenceMatcher {\n\n \n\n std::vector<T> sequence ;\n\n std::size_t maximum_mismatches ;\n\n std::size_t minimum_matches ;\n\n std::size_t first_base ;\n\n bool (*compare)(T, T) ;\n\n public:\n\n // Primary constructor\n\n //\n\n // \n\n SequenceMatcher(std::vector<T> seq):sequence(seq), maximum_mismatches(1), minimum_matches(1), first_base(0), compare(&default_comparator) {}\n\n \n\n // Secondary constructor \n\n //\n\n //\n\n SequenceMatcher(std::vector<T> seq, std::size_t max_mm, std::size_t min_m, std::size_t fb):sequence(seq), maximum_mismatches(max_mm), minimum_matches(min_m), first_base(fb), compare(&default_comparator){}\n\n\n\n // Tertiary constructor\n\n //\n", "file_path": "cplusplus/trim/include/sequence_matcher.hpp", "rank": 9, "score": 90922.25351817862 }, { "content": "\t//\n\n\t// the main class to do the alignment\n\n\t//\n\n\tclass AmpliconAlignment {\n\n\n\n\t\tseed::AmpliconIndex* _ai ;\n\n\t\talignment::AlignmentScore* _scores ;\n\n\n\n\t\tint _posd ;\n\n\t\tint _gapopen ;\n\n\n\n\t\tbool _reportsecondary ;\n\n\t\tMappingQuality* _mapqual ;\n\n\n\n\tpublic:\n\n\t\n\n\t\tAmpliconAlignment( seed::AmpliconIndex* ai, alignment::AlignmentScore* scores, int seedpos, int go ) ;\n\n\t\n\n\t\tAmpliconAlignment( seed::AmpliconIndex* ai, alignment::AlignmentScore* scores, int seedpos, int go, bool rs ) ;\n\n\n\n\t\t~AmpliconAlignment(void);\n\n\n\n\t\t/**\n", "file_path": "cplusplus/align/lib/libnimbus/include/AmpliconAlignment.h", "rank": 10, "score": 90480.80586945103 }, { "content": "\tclass AlignmentBuilder {\n\n\n\n\tpublic:\n\n\t\tbasic::Read* forward ;\n\n\t\tbasic::Read* reverse ;\n\n\t\tstd::vector<AlnSet> entries ;\n\n\n\n\tpublic:\n\n\t\tAlignmentBuilder( ) ;\n\n\n\n\t\tAlignmentBuilder( basic::Read* f ) ;\n\n\n\n\t\tAlignmentBuilder( basic::Read* f, basic::Read* r ) ;\n\n\t\t\n\n\t\t~AlignmentBuilder(void);\n\n\n\n\t\tbool empty() const ;\n\n\n\n\t\t/*\n\n\t\t adds an amplicon to the result set\n", "file_path": "cplusplus/align/lib/libnimbus/include/AlignmentBuilder.h", "rank": 11, "score": 90476.22576595409 }, { "content": "\t\tclass Levenshtein: public Alignment {\n\n\t\tpublic:\n\n\t\t\tLevenshtein( ): Alignment(new AlignmentScore( 0, 1, 1, 1)) {\n\n\t\t\t}\n\n\t\t\t\n\n\t\t\tLevenshtein( std::string ref, std::string q ): Alignment(new AlignmentScore( 0, 1, 1, 1)) {\n\n\t\t\t\tfillMatrix( ref, q ) ;\n\n\t\t\t}\n\n\n\n\t\t\tLevenshtein( const Levenshtein& other ): Alignment(new AlignmentScore( 0, 1, 1, 1)) {\n\n\t\t\t\tfillMatrix( other.subject, other.query ) ;\n\n\t\t\t}\n\n\n\n\t\t\t~Levenshtein( ) {\n\n\t\t\t\tdelete scorecalc ;\n\n\t\t\t//\t_clean_matrix() ;\n\n\t\t\t}\n\n\n\n\t\t\tint distance() ;\n\n\n\n\t\t\tvoid fillMatrix( std::string ref, std::string q ) ;\n\n\n\n\t\t\tvoid _init_matrix( ) ;\n\n\n\n\t\t} ;\n\n\t}\n\n\n\n}\n", "file_path": "cplusplus/align/lib/libnimbus/include/Alignment.h", "rank": 12, "score": 90476.22576595409 }, { "content": "#pragma once\n\n\n\n#include \"stdafx.h\"\n\n#include \"Read.h\"\n\n#include \"AmpliconIndex.h\"\n\n#include \"Alignment.h\"\n\n#include \"AlignmentBuilder.h\"\n\n\n\nnamespace Nimbus {\n\n\n\n\t//\n\n\t// functions outside of the object\n\n\t//\n\n\n\n\t/* \n\n\t determines whether an AlnSet ought to be filtered based on the \n\n\t position of the aligments with respect to the ends of the amplicon. \n\n\n\n\t the limit parameter indicates the tolerance for this filter.\n\n\t */\n\n\tbool seedPositionFilter( AlnSet a, int limit ) ;\n\n\t\n\n\tdouble lambdaCalculator( int _match, int _mismatch, double precission, double nf ) ;\n\n\n", "file_path": "cplusplus/align/lib/libnimbus/include/AmpliconAlignment.h", "rank": 13, "score": 89351.51924533541 }, { "content": "\t\t */\n\n\t\tvoid add( basic::Amplicon* a ) ;\n\n\n\n\t\t/*\n\n\t\t Aligns the read to the amplicons in the resultset \n\n\t\t */\n\n\t\tvoid align( alignment::AlignmentScore* scores, int gapopen ) ;\n\n\n\n\t\t/*\n\n\t\t gets the alignment with the best combined score\n\n\t\t */\n\n\t\tint best() ;\n\n\n\n\t\t/*\n\n\t\t Creates a forward (and if possible a reverse) SAMrecord\n\n\t\t */\n\n\t\tvoid createRecord( AlnSet& a ) ; \n\n\n\n\t\t/* \n\n\t\t Creates SAMRecords for each alignment\n\n\t\t */ \n\n\t\tvoid createRecords( ) ; \n\n\t\t\n\n\t\tbool samrecordspresent( ) const ;\n\n\n\n\t} ;\n\n\n\n}", "file_path": "cplusplus/align/lib/libnimbus/include/AlignmentBuilder.h", "rank": 14, "score": 89349.56260516348 }, { "content": "#pragma once\n\n\n\n#include \"stdafx.h\"\n\n#include \"Read.h\"\n\n#include \"Amplicon.h\"\n\n#include \"Alignment.h\"\n\n#include \"SAMrecord.h\"\n\n\n\nnamespace Nimbus {\n\n\n", "file_path": "cplusplus/align/lib/libnimbus/include/AlignmentBuilder.h", "rank": 15, "score": 89345.91796245109 }, { "content": "\n\n\t\tvoid align( alignment::AlignmentScore* scores, int gapopen, basic::Read* f, basic::Read* r ) ;\n\n\n\n\t\tvoid SAMrecord( basic::Read* f, basic::Read* r ) ;\n\n\n\n\t\tvoid SAMrecord_f( basic::Read* f ) ;\n\n\n\n\t\tvoid SAMrecord_r( basic::Read* r ) ;\n\n\t\t\n\n\t} ;\n\n\t \n", "file_path": "cplusplus/align/lib/libnimbus/include/AlignmentBuilder.h", "rank": 16, "score": 89345.65901394507 }, { "content": "\t\t Aligns the reads provided to the amplicon index\n\n\t\t **/\n\n\t\tAlignmentBuilder align( std::pair<basic::Read*,basic::Read*> p ) const ;\n\n\n\n\n\n\tprotected:\n\n\n\n\t} ;\n\n\n\n\n\n}\n\n\n", "file_path": "cplusplus/align/lib/libnimbus/include/AmpliconAlignment.h", "rank": 17, "score": 89337.330043378 }, { "content": "\t\tclass NeedlemanWunsch: public Alignment {\n\n\t\t\tint _gapopen ;\n\n\n\n\t\tpublic:\n\n\t\t\tNeedlemanWunsch( AlignmentScore* as, int go ): Alignment(as), _gapopen(go) {}\n\n\n\n\t\t\tNeedlemanWunsch( AlignmentScore* as, int go, std::string s, std::string q ): Alignment(as), _gapopen(go) {\n\n\t\t\t\tfillMatrix( s, q ) ;\n\n\t\t\t}\n\n\n\n\t\t\t/*~NeedlemanWunsch() {\n\n\t\t\t\t_clean_matrix() ;\n\n\t\t\t}*/\n\n\n\n\t\t\tvoid fillMatrix( std::string ref, std::string q ) ;\n\n\n\n\t\t\tvoid _init_matrix( ) ;\n\n\t\t} ;\n\n\n", "file_path": "cplusplus/align/lib/libnimbus/include/Alignment.h", "rank": 18, "score": 89121.37867521115 }, { "content": "\t\tclass SmithWaterman: public Alignment {\n\n\t\t\tint _gapopen ;\n\n\n\n\t\tpublic:\n\n\t\t\tSmithWaterman( AlignmentScore* as, int go ): Alignment(as), _gapopen(go) {}\n\n\n\n\t\t\tSmithWaterman( AlignmentScore* as, int go, std::string s, std::string q ): Alignment(as), _gapopen(go) {\n\n\t\t\t\tfillMatrix( s, q ) ;\n\n\t\t\t}\n\n\n\n\t\t\t/*~SmithWaterman() {\n\n\t\t\t\t_clean_matrix() ;\n\n\t\t\t}*/\n\n\n\n\t\t\tvoid fillMatrix( std::string ref, std::string q ) ;\n\n\n\n\t\t\tvoid _init_matrix( ) ;\n\n\t\t} ;\n\n\n", "file_path": "cplusplus/align/lib/libnimbus/include/Alignment.h", "rank": 19, "score": 89121.37867521115 }, { "content": "#pragma once\n\n\n\n// STL\n\n#include <cstdlib>\n\n#include <cstddef>\n\n#include <string>\n\n#include <sstream>\n\n#include <cstdint>\n\n\n\nnamespace nimbus {\n\n\n\n\t/**\n\n\t * A CIGAR operation\n\n\t *\n\n\t */\n", "file_path": "cplusplus/call/include/cigar.h", "rank": 20, "score": 89051.63887018543 }, { "content": "\t\tstd::string str() const ;\n\n\n\n\t\tstd::size_t reference_offset_to_query_offset( std::size_t r ) const ;\n\n\t\t\n\n\t\tstd::size_t reference_offset_to_query_offset( std::size_t relpos, std::size_t &i_operation, std::size_t &pos_in_op ) const ;\n\n\n\n\t\t/**\n\n\t\t * get the operation at query coordinate \n\n\t\t *\n\n\t\t */\n\n\t\t// void query_at( std::size_t q, std::size_t &i_operation, std::size_t &pos_in_op ) const ;\n\n\n\n\t\t// void reference_at( std::size_t r, std::size_t &i_operation, std::size_t &pos_in_op ) const ;\n\n\t\t\n\n\t\t/**\n\n\t\t * Get a pointer to the cigar operation at i or NULL\n\n\t\t *\n\n\t\t */\n\n\t\tCigarOperation* at( std::size_t i ) const ;\n\n\n", "file_path": "cplusplus/call/include/cigar.h", "rank": 21, "score": 89042.73507819882 }, { "content": "\t\t\treturn _runlength ;\n\n\t\t}\n\n\n\n\t\tchar operation() const {\n\n\t\t\treturn _operation ;\n\n\t\t}\n\n\n\n\t\tstd::string str() const {\n\n\t\t\tstd::stringstream s ;\n\n\t\t\ts << operation() << runLength() ;\n\n\t\t\treturn s.str() ;\n\n\t\t}\n\n\t} ;\n\n\n\n\t/**\n\n\t * A CIGAR \n\n\t *\n\n\t */\n", "file_path": "cplusplus/call/include/cigar.h", "rank": 22, "score": 89039.45907656936 }, { "content": "\tprotected:\n\n\n\n\t\tvoid expand( std::size_t extra ) ;\n\n\n\n\t\tchar int2op( int v ) ;\n\n\n\n\t\tbool on_reference( char op ) const ; \n\n\n\n\t\tbool only_on_reference( char op ) const ; \t\t\n\n\n\n\t\tbool on_query( char op ) const ;\n\n\n\n\t\tbool only_on_query( char op ) const ; \n\n\t} ;\n\n\n\n}", "file_path": "cplusplus/call/include/cigar.h", "rank": 23, "score": 89034.41781239641 }, { "content": "#pragma once\n\n\n\n#include <sstream>\n\n#include <string>\n\n#include <vector>\n\n#include <map>\n\n#include <stdio.h>\n\n#include <iostream>\n\n#include <fstream>\n\n\n\nnamespace commandline { \n\n\t/**\n\n\t\t* An option parser class. \n\n\t\t*/\n", "file_path": "cplusplus/align/include/opt.h", "rank": 24, "score": 86310.45710643027 }, { "content": "\t\t/**\n\n\t\t\t* Adds an option to the object\n\n\t\t\t*\n\n\t\t\t**/ \n\n\t\tvoid add( char shortopt, std::string longopt, bool required, bool hasvalue, std::string desc ) {\n\n\t\t\tstd::string so = std::string( \"-\" ) ;\n\n\t\t\tso += shortopt ;\n\n\t\t\tshortoptions.push_back( so ) ;\n\n\t\t\tlongoptions.push_back( \"--\" + longopt ) ;\n\n\t\t\treqoptions.push_back( required ) ;\t\t\n\n\t\t\thasvalues.push_back( hasvalue ) ;\n\n\t\t\tdescriptions.push_back( desc ) ;\n\n\t\t}\n\n\n\n\n\n\t\t/**\n\n\t\t\t* set the options\n\n\t\t\t*/\n\n\t\tvoid set_options( int argv, char* args[] ) { \n\n\t\t\tfor( int i=0; i<argv; i++ ){\n", "file_path": "cplusplus/align/include/opt.h", "rank": 25, "score": 86301.84825433047 }, { "content": "\t\t\t// quit if required\n\n\t\t\tif( quit ){ \n\n\t\t\t\tprintf( \"%s\\n\", s.str().c_str() ) ;\n\n\t\t\t\texit( EXIT_FAILURE ) ;\n\n\t\t\t}\n\n\t\t\n\n\t\t\t// \n\n\t\t\treturn s.str() ;\n\n\t\t}\n\n\n\n\t\t/**\n\n\t\t\t* determine which essential options were missing from the analysis\n\n\t\t\t*\n\n\t\t\t*/\n\n\t\tstd::vector<std::string> missingOptions( ) {\n\n\t\t\tstd::vector<std::string> rval = std::vector<std::string>() ;\n\n\n\n\t\t\tfor( unsigned int i=0; i<longoptions.size(); i++ ) {\n\n\t\t\t\t\n\n\t\t\t\t//\n", "file_path": "cplusplus/align/include/opt.h", "rank": 26, "score": 86301.41537155418 }, { "content": "\n\n\t\t/*\n\n\t\t * worker builder\n\n\t\t */\n\n\t\tvoid addWorkers( Nimbus::AmpliconAlignment* a, int n ) ;\n\n\t\t/*\n\n\t\t * allows for data to be written to the output stream before \n\n\t\t * the manager delegates responsibility to the writer.\n\n\t\t *\n\n\t\t * This is specifically meant to write the SAM header\n\n\t\t */\n\n\t\tvoid writeToOutput( std::string x ) ;\n\n\n\n\t\t/*\n\n\t\t * destructor\n\n\t\t */\n\n\t\t~Manager(void);\n\n\n\n\t\t/*\n\n\t\t * runs the threads after everything has been setup\n\n\t\t */ \n\n\t\tvoid run( ) ;\n\n\n\n\t} ;\n\n\t\n\n}", "file_path": "cplusplus/align/include/Manager.h", "rank": 27, "score": 86299.99049094431 }, { "content": "\n\n\t\t// Manager( std::string fnout, std::string fna, std::string fnb ) ;\n\n\n\n\t\t// Manager( std::string fnout, std::string fna, std::string fnb, int n_workers ) ;\n\n\n\n\t\t/*\n\n\t\t * add the input files\n\n\t\t */\n\n\t\tvoid addForwardInput( std::string fn ) ;\n\n\n\n\t\tvoid addReverseInput( std::string fn ) ;\n\n\n\n\t\tvoid addInput( std::string fna, std::string fnb ) ;\n\n\n\n\t\tvoid finalizeStreams() ;\n\n\n\n\t\t/*\n\n\t\t * opens the output file for writing\n\n\t\t */ \n\n\t\tvoid addOutput( std::string fn ) ;\n", "file_path": "cplusplus/align/include/Manager.h", "rank": 28, "score": 86298.70868236257 }, { "content": "\t\t// the descriptions of the tools\n\n\t\tstd::vector<std::string> descriptions ;\n\n\n\n\t\t// a map with the values\n\n\t\tstd::map<std::string, std::string> values ;\n\n\n\n\tpublic:\n\n\n\n\t\t/**\n\n\t\t\t* the constructor\n\n\t\t\t*/\n\n\t\tOptParser( std::string tn ) {\n\n\t\t\ttoolname = tn ;\n\n\t\t\toptions = std::vector<std::string>() ;\n\n\t\t\tshortoptions = std::vector<std::string>() ;\n\n\t\t\tlongoptions = std::vector<std::string>() ;\n\n\t\t\treqoptions = std::vector<bool>() ;\n\n\t\t\tvalues = std::map< std::string, std::string >() ; \n\n\t\t}\n\n\n", "file_path": "cplusplus/align/include/opt.h", "rank": 29, "score": 86298.62385596878 }, { "content": "\t\tWriter( std::ostream* o, threadutils::TQueue<Nimbus::AlignmentBuilder*>* q, threadutils::Signal<bool>* b ) ; \n\n\n\n\t\tWriter( std::ostream* o, threadutils::TQueue<Nimbus::AlignmentBuilder*>* q, threadutils::Signal<long>* s, threadutils::Signal<bool>* b ) ; \n\n\n\n\t\t//\n\n\t\t// destructor\n\n\t\t//\n\n\t\t~Writer(void) ;\n\n\n\n\t\t//\n\n\t\tthreadutils::Signal<bool>* getStopSignal() ;\n\n\n\n\t\tthreadutils::Signal<long>* getCounter() ;\n\n\n\n\t\t//\n\n\t\t// processors\n\n\t\t//\n\n\n\n\t\tbool process( Nimbus::AlignmentBuilder* value ) ;\n\n\n\n\t\t// run the processor\n\n\t\tvoid run( ) ;\n\n\t} ;\t\t\n\n\t\n\n\n\n\n\n}", "file_path": "cplusplus/align/include/Writer.h", "rank": 30, "score": 86298.54647113102 }, { "content": "\t\t\t\tstd::map<std::string, std::string>::iterator it = values.find( longoptions[i] ) ;\n\n\n\n\t\t\t\tif( reqoptions[i] && it == values.end() ) {\n\n\t\t\t\t\trval.push_back( longoptions[i] ) ;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\treturn rval ;\n\n\t\t}\n\n\n\n\t\t/**\n\n\t\t\t* gets a value after interpreting the commandline options\n\n\t\t\t*\n\n\t\t\t*/\n\n\t\tstd::string getValue( std::string opt ) {\n\n\t\t\tstd::string rval = \"\" ;\n\n\t\t\tstd::map<std::string, std::string>::iterator it = values.find( \"--\" + opt ) ;\n\n\t\t\tif( it != values.end() ) {\n\n\t\t\t\trval = it->second ;\n\n\t\t\t}\n\n\t\t\treturn rval ;\n\n\t\t}\n\n\n\n\t} ;\n\n\n\n\n\n\tbool FileExists( const std::string fn ) ; \t\n\n}", "file_path": "cplusplus/align/include/opt.h", "rank": 31, "score": 86298.53096152181 }, { "content": "\t\t\t\toptions.push_back( std::string( args[i] ) );\n\n\t\t\t}\n\n\t\t}\n\n\n\n\t\t/**\n\n\t\t * \n\n\t\t */\n\n\t\tvoid interpret( int argv, char* args[] ) {\n\n\t\t\tset_options( argv, args ) ;\n\n\t\t\tinterpret() ;\n\n\t\t}\n\n\n\n\t\t/**\n\n\t\t\t* Interpret the commandline options\n\n\t\t\t*\n\n\t\t\t*/\n\n\t\tvoid interpret( ) {\n\n\n\n\t\t\t//\n\n\t\t\tfor( unsigned int i=0; i<options.size(); i++ ) {\n", "file_path": "cplusplus/align/include/opt.h", "rank": 32, "score": 86297.81637033474 }, { "content": "\n\n\t\t\t~Worker(void) ;\n\n\n\n\t\t\tthreadutils::Signal<bool>* getStopSignal() ;\n\n\n\n\t\t\t/*\n\n\t\t \t process the alignments in a paired end manner\n\n\t\t\t */ \n\n\t\t\tNimbus::AlignmentBuilder* process( std::pair<Nimbus::basic::Read*,Nimbus::basic::Read*> p ) ;\n\n\n\n\n\n\t\t\t/**\n\n\t\t\t Runs the processing loop \n\n\t\t\t **/\n\n\t\t\tvoid run() ;\n\n\n\n\t\t};\n\n\n\n\t\n\n}", "file_path": "cplusplus/align/include/Worker.h", "rank": 33, "score": 86297.73516117608 }, { "content": "\n\n\t\t\t\t\t\t// add the value to the map\n\n\t\t\t\t\t\tstd::pair<std::string,std::string> p = std::pair<std::string,std::string>( longoptions[k], \"true\" ) ;\n\n\t\t\t\t\t\tif( hasvalues[k] && i < options.size() - 1) \n\n\t\t\t\t\t\t\tp.second = options[ i + 1 ] ;\n\n\t\t\t\t\t\tvalues.insert( p ) ;\n\n\t\t\t\t\t}\t\t\t\t\n\n\t\t\t\t}\n\n\n\n\t\t\t} // foreach option\n\n\t\t}\n\n\n\n\t\t/**\n\n\t\t\t* usage information\n\n\t\t\t*\n\n\t\t\t*/\n\n\t\tstd::string usageInformation( std::string mess, bool quit ) const {\n\n\t\t\tstd::stringstream s ;\n\n\n\n\t\t\t// print the Message:\n", "file_path": "cplusplus/align/include/opt.h", "rank": 34, "score": 86296.89454829771 }, { "content": "\n\n\t\t\t\t// check the short options\n\n\t\t\t\tfor( unsigned int k=0; k<shortoptions.size(); k++ ) {\n\n\n\n\t\t\t\t\t// if the option matches\n\n\t\t\t\t\tif( options[i].compare( shortoptions[k] ) == 0 ) {\t\t\t\t\t\t\n\n\n\n\t\t\t\t\t\t// add the value to the map (use the long options value)\n\n\t\t\t\t\t\tstd::pair<std::string,std::string> p = std::pair<std::string,std::string>( longoptions[k], \"true\" ) ;\n\n\t\t\t\t\t\tif( hasvalues[k] && i < options.size() - 1 ) \n\n\t\t\t\t\t\t\tp.second = options[ i + 1 ] ;\n\n\t\t\t\t\t\tvalues.insert( p ) ;\n\n\t\t\t\t\t}\t\t\t\t\n\n\t\t\t\t}\n\n\n\n\t\t\t\t// check the long options\n\n\t\t\t\tfor( unsigned int k=0; k<longoptions.size(); k++ ) {\n\n\n\n\t\t\t\t\t//\n\n\t\t\t\t\tif( options[i].compare( longoptions[k] ) == 0 ) {\t\t\t\t\t\t\n", "file_path": "cplusplus/align/include/opt.h", "rank": 35, "score": 86296.89307385118 }, { "content": "#pragma once\n\n\n\n#include \"nimbusheader.h\"\n\n#include \"Reader.h\"\n\n#include \"Worker.h\"\n\n#include \"Writer.h\"\n\n\n\nnamespace NimApp {\n\n\t\n\n\t\n", "file_path": "cplusplus/align/include/Manager.h", "rank": 36, "score": 86295.0407452307 }, { "content": "#pragma once\n\n\n\n\n\n#include \"nimbusheader.h\"\n\n\n\nnamespace NimApp {\n\n\n", "file_path": "cplusplus/align/include/Reader.h", "rank": 37, "score": 86294.2381206965 }, { "content": "#pragma once\n\n\n\n#include \"nimbusheader.h\"\n\n\n\nnamespace NimApp {\n\n\n", "file_path": "cplusplus/align/include/Worker.h", "rank": 38, "score": 86294.2381206965 }, { "content": "#pragma once\n\n\n\n#include \"nimbusheader.h\"\n\n\n\nnamespace NimApp {\n\n\n\n\n\n\t//template< class T> \n", "file_path": "cplusplus/align/include/Writer.h", "rank": 39, "score": 86294.03690468533 }, { "content": "\t\tthreadutils::Signal<long>* getCounter( ) {\n\n\t\t\treturn _sigcnt ;\n\n\t\t} \n\n\n\n\t\tthreadutils::Signal<bool>* getStopSignal( ) {\n\n\t\t\treturn _stop ;\n\n\t\t}\n\n\n\n\t\t//\n\n\t\t// the processing function\n\n\t\t//\n\n\t\tstd::pair<Nimbus::basic::Read*,Nimbus::basic::Read*> process( bool& proceed ) ;\n\n\n\n\t\t//\n\n\t\t// The processing loop\n\n\t\t//\n\n\t\tvoid run() ;\n\n\n\n\n\n\t} ;\n\n\n\n\t\n\n}", "file_path": "cplusplus/align/include/Reader.h", "rank": 40, "score": 86293.21384784141 }, { "content": "\t\tReader( ) ;\n\n\t\t\n\n\t\tReader( std::istream* xa, std::istream* xb ) ;\n\n\t\n\n\t\tReader( std::istream* xa, std::istream* xb, unsigned int l ) ;\n\n\t\n\n\t\tReader( std::istream* xa, std::istream* xb, unsigned int l, threadutils::TQueue<std::pair<Nimbus::basic::Read*,Nimbus::basic::Read*>>* q, threadutils::Signal<long>* s ) ;\n\n\t\n\n\t\tReader( std::istream* xa, std::istream* xb, unsigned int l, threadutils::TQueue<std::pair<Nimbus::basic::Read*,Nimbus::basic::Read*>>* q, threadutils::Signal<long>* s, threadutils::Signal<bool>* b ) ;\n\n\t\n\n\t\t~Reader() ;\n\n\n\n\t\t//\n\n\t\t// accessors\n\n\t\t//\n\n\n\n\t\tthreadutils::TQueue< std::pair<Nimbus::basic::Read*,Nimbus::basic::Read*> >* getQueue( ) {\n\n\t\t\treturn _queue ;\n\n\t\t}\n\n\n", "file_path": "cplusplus/align/include/Reader.h", "rank": 41, "score": 86291.60514552727 }, { "content": "\t\t\ts << \"Message:\\n\" << mess << \"\\n\\n\" ;\n\n\n\n\t\t\t// print the options, if loaded to the object, otherwise don't\n\n\t\t\tif( options.size() > 0 ) {\n\n\t\t\t\ts << \"Program called with:\\n\" ; \n\n\t\t\t\tfor( unsigned int i=0; i<options.size(); i++ ) {\n\n\t\t\t\t\ts << \" \" << options[i] ;\n\n\t\t\t\t}\n\n\t\t\t\ts << \"\\n\" ;\n\n\t\t\t}\n\n\n\n\t\t\t// add the usage information\n\n\t\t\ts << \"Usage:\\n\" ;\n\n\t\t\ts << toolname << \" \";\n\n\t\t\tfor( unsigned int i=0; i<shortoptions.size(); i++ ) {\n\n\t\t\t\ts << shortoptions[i] << \" \" ;\n\n\t\t\t\tif( hasvalues[i] ) s << \"[VALUE] \" ;\n\n\t\t\t}\n\n\t\t\ts << \"\\n\" ;\n\n\t\t\ts << \"\\n\" ;\n", "file_path": "cplusplus/align/include/opt.h", "rank": 42, "score": 86289.7184326975 }, { "content": "\t\t\ts << \"Options\\n\" ;\n\n\t\t\tfor( unsigned int i=0; i<shortoptions.size(); i++ ) {\n\n\t\t\t\ts << shortoptions[i] << \"/\" << longoptions[i] << \" \" ;\n\n\t\t\t\t\n\n\t\t\t\t//\n\n\t\t\t\tif( reqoptions[i] ) { \n\n\t\t\t\t\ts << \" required \" ;\n\n\t\t\t\t} else {\n\n\t\t\t\t\ts << \" optional \" ;\n\n\t\t\t\t}\n\n\n\n\t\t\t\tif( hasvalues[i] ) { \n\n\t\t\t\t\ts << \" [value] \" ;\n\n\t\t\t\t} else {\n\n\t\t\t\t\ts << \" [] \" ;\n\n\t\t\t\t}\n\n\n\n\t\t\t\ts << descriptions[i] << \"\\n\" ;\n\n\t\t\t}\n\n\n", "file_path": "cplusplus/align/include/opt.h", "rank": 43, "score": 86289.29778600077 }, { "content": "\tclass AlnSet {\n\n\n\n\tpublic:\n\n\t\tbasic::Amplicon* amplicon ;\n\n\t\talignment::Alignment* f_alignment ;\n\n\t\talignment::Alignment* r_alignment ;\n\n\t\tstd::vector< std::pair<int,int> >* f_path ;\n\n\t\tstd::vector< std::pair<int,int> >* r_path ;\n\n\t\talignment::SAMRecord* f_record ;\n\n\t\talignment::SAMRecord* r_record ;\n\n\n\n\tpublic:\n\n\t\tAlnSet() ;\n\n\t\tAlnSet( basic::Amplicon* a ) ;\n\n\n\n\t\t~AlnSet() ;\n\n\n\n\t\tvoid delete_content() ;\n\n\n\n\t\tvoid align( alignment::AlignmentScore* scores, int gapopen, basic::Read* f ) ;\n", "file_path": "cplusplus/align/lib/libnimbus/include/AlignmentBuilder.h", "rank": 44, "score": 86190.30643252646 }, { "content": "\tclass MappingQuality {\n\n\tpublic:\n\n\t\tlong _dbsize ;\n\n\t\tdouble _lambda ;\n\n\t\tdouble _k ;\n\n\tpublic:\n\n\t\tMappingQuality( long dbs, double l ) ;\n\n\t\t \n\n\t\tdouble evalue( double bscore, int n ) const ;\n\n\n\n\t\tdouble bscore( int score ) const ;\n\n\n\n\t\tint phredEncode( double v ) const ;\n\n\n\n\t} ;\n\n\n", "file_path": "cplusplus/align/lib/libnimbus/include/AmpliconAlignment.h", "rank": 45, "score": 86190.30643252646 }, { "content": "#ifndef sequence_matcher_hpp\n\n#define sequence_matcher_hpp\n\n\n\n// STL\n\n#include <cstddef>\n\n#include <vector>\n\n#include <functional>\n\n\n\nnamespace Biomics {\n\n\n\n //\n\n // An iterative matching algorithm\n\n //\n\n // \n\n\n\n /*\n\n template<typename T>\n\n std::size_t vector_matcher(const std::vector<T>& subject, const std::vector<T>& query, std::size_t mismatch_threshold, std::size_t minimum_matches) {\n\n \n\n //\n", "file_path": "cplusplus/trim/include/sequence_matcher.hpp", "rank": 46, "score": 84922.59399835931 }, { "content": " // (with function assignment)\n\n SequenceMatcher(std::vector<T> seq, std::size_t max_mm, std::size_t min_m, std::size_t fb, bool (*c)(T, T)):sequence(seq), maximum_mismatches(max_mm), minimum_matches(min_m), first_base(fb), compare(c){}\n\n\n\n // Quaternary constructor\n\n //\n\n // (with function assignment)\n\n SequenceMatcher(std::vector<T> seq, std::size_t max_mm, std::size_t min_m, bool (*c)(T, T)):sequence(seq), maximum_mismatches(max_mm), minimum_matches(min_m), first_base(0), compare(c){}\n\n\n\n // Quinternary? constructor \n\n //\n\n //\n\n SequenceMatcher(std::vector<T> seq, std::size_t max_mm, std::size_t min_m):sequence(seq), maximum_mismatches(max_mm), minimum_matches(min_m), first_base(0), compare(&default_comparator){}\n\n\n\n // Determines the point in the vector after which the sequence ought to be trimmed. \n\n //\n\n // \n\n std::size_t match(const std::vector<T>& s) const {\n\n return vector_matcher<T>(compare, s, sequence, maximum_mismatches, minimum_matches, first_base) ;\n\n }\n\n \n\n } ;\n\n \n\n} ;\n\n#endif", "file_path": "cplusplus/trim/include/sequence_matcher.hpp", "rank": 47, "score": 84914.809401535 }, { "content": " \n\n template<typename T>\n\n inline bool default_comparator(T a, T b){\n\n return a == b ? true : false ;\n\n }\n\n\n\n template<typename T>\n\n std::size_t vector_matcher( \n\n bool (*compare)(T, T) , const std::vector<T>& subject, const std::vector<T>& query, \n\n std::size_t mismatch_threshold, std::size_t minimum_matches, std::size_t first_base) {\n\n \n\n //\n\n std::size_t match_location = subject.size() ; \n\n std::size_t mismatches = 0 ; \n\n std::size_t matches = 0 ;\n\n bool ismatch = false ;\n\n \n\n // \n\n if(subject.size() <= first_base){\n\n return match_location ;\n", "file_path": "cplusplus/trim/include/sequence_matcher.hpp", "rank": 48, "score": 84913.81543369812 }, { "content": " } else {\n\n matches += 1 ; \n\n }\n\n }\n\n \n\n // check whether the sequence matches \n\n if(ismatch && matches >= minimum_matches){\n\n match_location = i ;\n\n break ; \n\n } \n\n }\n\n }\n\n \n\n //\n\n return match_location ;\n\n }\n\n\n\n template<typename T>\n\n std::size_t vector_matcher(const std::vector<T>& subject, const std::vector<T>& query, std::size_t mismatch_threshold, std::size_t minimum_matches){\n\n return vector_matcher<T>(&default_comparator, subject, query, mismatch_threshold, minimum_matches) ;\n\n }\n\n \n\n\n\n template<typename T>\n", "file_path": "cplusplus/trim/include/sequence_matcher.hpp", "rank": 49, "score": 84913.16266846492 }, { "content": " std::size_t match_location = subject.size() ; \n\n std::size_t mismatches = 0 ; \n\n std::size_t matches = 0 ;\n\n bool ismatch = false ;\n\n \n\n for(std::size_t i=0; i<subject.size(); ++i){\n\n if(subject[i] == query[0]) {\n\n \n\n // determine where to match\n\n ismatch = true ; \n\n mismatches = 0 ;\n\n matches = 0 ; \n\n for(std::size_t j=i; j<subject.size(); ++j) {\n\n \n\n if(j-i >= query.size()) \n\n break ; \n\n \n\n if(subject[j] != query[j-i]) {\n\n mismatches += 1 ;\n\n if(mismatches >= mismatch_threshold){\n", "file_path": "cplusplus/trim/include/sequence_matcher.hpp", "rank": 50, "score": 84912.15849515803 }, { "content": " ismatch = false ;\n\n break ;\n\n }\n\n } else {\n\n matches += 1 ; \n\n }\n\n }\n\n \n\n // check whether the sequence matches \n\n if(ismatch && matches > minimum_matches){\n\n match_location = i ;\n\n break ; \n\n } \n\n }\n\n }\n\n \n\n //\n\n return match_location ;\n\n }\n\n */\n", "file_path": "cplusplus/trim/include/sequence_matcher.hpp", "rank": 51, "score": 84911.26999021469 }, { "content": " }\n\n\n\n for(std::size_t i=first_base; i<subject.size(); ++i){\n\n if(compare(subject[i], query[0])) {\n\n \n\n // determine where to match\n\n ismatch = true ; \n\n mismatches = 0 ;\n\n matches = 0 ; \n\n for(std::size_t j=i; j<subject.size(); ++j) {\n\n \n\n if(j-i >= query.size())\n\n break ; \n\n \n\n if(!compare(subject[j], query[j-i])) {\n\n mismatches += 1 ;\n\n if(mismatches >= mismatch_threshold){\n\n ismatch = false ;\n\n break ;\n\n }\n", "file_path": "cplusplus/trim/include/sequence_matcher.hpp", "rank": 52, "score": 84910.407621176 }, { "content": "\tclass GenomeSequence {\n\n\n\n\t\t//\n\n\t\tfaidx_t *fai ;\n\n\t\t\n\n\tpublic:\n\n\t\t\n\n\t\tstd::string filename ;\n\n\n\n\t\t/**\n\n\t\t * Constructs a new GenomeSequence object that \n\n\t\t * will only yield N as sequence\n\n\t\t */\n\n\t\tGenomeSequence( ) ;\n\n\n\n\t\t/**\n\n\t\t * Sets the FastA file from which to obtain\n\n\t\t * sequences\n\n\t\t *\n\n\t\t * @param fn - the name of the samtools indexed FastA file\n", "file_path": "cplusplus/call/include/refsequence.h", "rank": 53, "score": 84902.47654327039 }, { "content": "\tclass Manager {\n\n\t\t\n\n\t\tstd::ifstream* _pfa ; \n\n\t\tstd::ifstream* _pfb ;\n\n\t\tstd::ofstream* _pfo ;\n\n\n\n\t\t//\n\n\t\tReader* _in ;\n\n\t\tWriter* _out ;\n\n\t\tstd::vector< Worker > _workers ;\n\n\n\n\t\t//\n\n\t\tthreadutils::Signal<bool>* _stop ;\n\n\t\tthreadutils::TQueue< Nimbus::AlignmentBuilder*>* _oqueue ;\n\n\t\t\n\n\tpublic:\n\n\t\t/*\n\n\t\t * constructors\n\n\t\t */\n\n\t\tManager( ) ;\n", "file_path": "cplusplus/align/include/Manager.h", "rank": 54, "score": 84197.0098638859 }, { "content": "\t//template< class T> \n\n\tclass Writer {\n\n\tprotected:\n\n\t\tthreadutils::TQueue<Nimbus::AlignmentBuilder*>* _in ;\n\n\n\n\t\t// control signals\n\n\t\tthreadutils::Signal<bool>* _stop ;\n\n\t\tthreadutils::Signal<long>* _sigcnt ;\n\n\n\n\t\t// the output stream\n\n\t\tstd::ostream* _out ;\n\n\t\t\n\n\tpublic:\n\n\n\n\t\t//\n\n\t\t// constructors\n\n\t\t//\n\n\t\tWriter( ) ; \n\n\n\n\t\tWriter( std::ostream* o ) ; \n\n\n", "file_path": "cplusplus/align/include/Writer.h", "rank": 55, "score": 84197.0098638859 }, { "content": "\t\tclass Worker {\n\n\t\t\t// the stop signal\n\n\t\t\tthreadutils::Signal<bool>* _stop ;\n\n\n\n\t\t\t// the input Queue\n\n\t\t\tthreadutils::TQueue< std::pair<Nimbus::basic::Read*, Nimbus::basic::Read*> >* _in ;\n\n\n\n\t\t\t// the output Queue\n\n\t\t\tthreadutils::TQueue< Nimbus::AlignmentBuilder* >* _out ;\n\n\n\n\t\t\tunsigned int _limit ;\n\n\n\n\t\t\tNimbus::AmpliconAlignment* _aa ;\n\n\n\n\t\tpublic:\n\n\t\t\tWorker( Nimbus::AmpliconAlignment* a, threadutils::Signal<bool>* s, threadutils::TQueue< std::pair<Nimbus::basic::Read*, Nimbus::basic::Read*> >* i, threadutils::TQueue< Nimbus::AlignmentBuilder* >* o, unsigned int l ) ;\n\n\n\n\t\t\tWorker( Nimbus::AmpliconAlignment* a, threadutils::Signal<bool>* s, threadutils::TQueue< std::pair<Nimbus::basic::Read*, Nimbus::basic::Read*> >* i, threadutils::TQueue< Nimbus::AlignmentBuilder* >* o ) ;\n\n\n\n\t\t\tWorker( Nimbus::AmpliconAlignment* a, threadutils::TQueue< std::pair<Nimbus::basic::Read*, Nimbus::basic::Read*> >* i, threadutils::TQueue< Nimbus::AlignmentBuilder* >* o ) ;\n", "file_path": "cplusplus/align/include/Worker.h", "rank": 56, "score": 84197.0098638859 }, { "content": "\tclass Reader {\n\n\tprotected:\n\n\t\t//\n\n\t\tthreadutils::Signal<bool>* _stop ; \n\n\t\tthreadutils::Signal<long>* _sigcnt ; \n\n\t\tthreadutils::TQueue<std::pair<Nimbus::basic::Read*,Nimbus::basic::Read*>>* _queue ;\n\n\n\n\t\tunsigned int _limit ;\n\n\n\n\t\t// the input streams for the first \n\n\t\t// and second data reads\n\n\t\tstd::istream* _ha ;\n\n\t\tstd::istream* _hb ;\n\n\n\n\tpublic:\n\n\n\n\t\t//\n\n\t\t// Constructors\n\n\t\t//\n\n\n", "file_path": "cplusplus/align/include/Reader.h", "rank": 57, "score": 84197.0098638859 }, { "content": "\tclass SequenceProvider {\n\n\n\n\t\t// the input files\n\n\t\tstd::vector<samFile*> samfiles ;\n\n\t\tstd::vector<bam_hdr_t*> headers ;\n\n\t\tstd::vector<std::string> filenames ;\n\n\n\n\t\t// the provider for the data\n\n\t\tProvider** data ; \n\n\t\tProviderOptions* p ;\n\n\n\n\t\t// the mpileup iterator\n\n\t\tbam_mplp_t iter ;\n\n\n\n\tpublic:\n\n\t\t\n\n\t\t// the pileup\n\n\t\tMpileupResult pileup ;\n\n\n\n\t\t// the maximum depth\n", "file_path": "cplusplus/call/include/read_provider.h", "rank": 58, "score": 82942.56578945261 }, { "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t_forward(other.forward()), _name(other.name()) {\n\n\n\n\t\t\t}\n\n\n\n\t\t\t~GenomicRegion(){} \n\n\n\n\n\n\n\n\t\t\t// constant getters\n\n\t\t\tstd::string chromosome() const ;\n\n\t\t\tint start() const ;\n\n\t\t\tint end() const ; \n\n\t\t\tbool forward() const ;\n\n\t\t\tstd::string name() const ;\n\n\t\t\tint width() const ;\n\n\t\t\tstd::string str() const ;\n\n\t\t\tstd::string str( bool nm ) const ;\n\n\n\n\t\t\tstd::string format() const ;\n\n\n\n\t\t\t// overloaded relational operators for sorting\n\n\t\t\tbool operator<( const GenomicRegion& a ) const ;\n\n\t\t\tbool operator>( const GenomicRegion& a ) const ;\n\n\t\t\tbool operator==( const GenomicRegion& a ) const ;\n\n\t\t} ; \n\n\n\n\n", "file_path": "cplusplus/align/lib/libnimbus/include/Amplicon.h", "rank": 59, "score": 82230.10170476997 }, { "content": "\n\n\t\t\t/* get the reverse complement of the quality */\n\n\t\t\tstd::string r_quality() ;\n\n\n\n\t\t\t/* get the reverse complement for this read */\n\n\t\t\tstd::string name() const ;\n\n\n\n\t\t\t/* get the sequence of the read */\n\n\t\t\tstd::string sequence() const ;\n\n\n\n\t\t\t/* get the quality string of the read */\n\n\t\t\tstd::string quality() const ;\n\n\n\n\t\t\t/* return the read in FastQ format */\n\n\t\t\tstd::string fastq() const ;\n\n\t\n\n\t\t\tunsigned int size() const ;\n\n\n\n\t\t\tstd::string str( ) const ;\n\n\t\t\t\n", "file_path": "cplusplus/align/lib/libnimbus/include/Read.h", "rank": 60, "score": 82223.35634910715 }, { "content": "\n\n\t\tprotected:\n\n\t\t\t/* set the sequence of the read */\n\n\t\t\tvoid sequence( std::string s ) ;\n\n\n\n\t\t\t/* set the quality string of the read */\n\n\t\t\tvoid quality( std::string q ) ;\n\n\t\t\t\n\n\t\t};\n\n\n\n\t}\n\n}", "file_path": "cplusplus/align/lib/libnimbus/include/Read.h", "rank": 61, "score": 82222.26999455891 }, { "content": "\n\n\t\t\t// constant getters\n\n\t\t\tstd::string sequence() const ;\n\n\t\t\t\n\n\t\t\t\n\n\t\t\tstd::string str( ) const ;\n\n\t\t} ;\n\n\n\n\t\t/**\n\n\t\t pointer comparators\n\n\t \t **/\n\n\t\tbool cmp_lt_amplicon_p( Amplicon* a, Amplicon* b ) ;\n\n\t\tbool cmp_gt_amplicon_p( Amplicon* a, Amplicon* b ) ;\n\n\t\tbool cmp_eq_amplicon_p( Amplicon* a, Amplicon* b ) ;\n\n\n\n\t}\n\n\n\n\t\n\n}", "file_path": "cplusplus/align/lib/libnimbus/include/Amplicon.h", "rank": 62, "score": 82220.33095960686 }, { "content": "#pragma once\n\n\n\n#include \"stdafx.h\"\n\n\n\nnamespace threadutils {\n\n\n\n\t/**\n\n\t A class to send signals between threads \n\n\t **/\n\n\ttemplate <class T>\n", "file_path": "cplusplus/align/lib/libthreadutils/include/Signal.h", "rank": 63, "score": 82216.04942349577 }, { "content": "\t\t~Signal(void) {}\n\n\n\n\tprivate:\n\n\t\tSignal& operator=( const Signal& ) ;\n\n\n\n\tpublic:\n\n\t\t/*\n\n\t\t set the signal value\n\n\t\t */\n\n\t\tvoid set( T val ){ \n\n\t\t\tstd::lock_guard<std::mutex> guard( get_mutex() ) ;\n\n\t\t\t_signal = val ;\n\n\t\t} \n\n\n\n\t\t/*\n\n\t\t get the signal object\n\n\t\t */\n\n\t\tT get( ) {\n\n\t\t\tstd::lock_guard<std::mutex> guard( get_mutex() ) ;\n\n\t\t\treturn _signal ;\n", "file_path": "cplusplus/align/lib/libthreadutils/include/Signal.h", "rank": 64, "score": 82215.19715653367 }, { "content": "#pragma once\n\n\n\n\n\nnamespace Nimbus {\n\n\n\n\tnamespace basic {\n\n\t\n\n\n", "file_path": "cplusplus/align/lib/libnimbus/include/Amplicon.h", "rank": 65, "score": 82212.73000136232 }, { "content": "#pragma once\n\n\n\nnamespace Nimbus {\n\n\n\n\tnamespace basic {\n\n\n", "file_path": "cplusplus/align/lib/libnimbus/include/Read.h", "rank": 66, "score": 82212.73000136232 }, { "content": "\t\t}\n\n\n\n\t\t/*\n\n\t\t get the mutex\n\n\t\t */\n\n\t\tstd::mutex& get_mutex( ) {\n\n\t\t\treturn _m ;\n\n\t\t}\n\n\n\n\t\t\t\n\n\t};\n\n\n\n}\n", "file_path": "cplusplus/align/lib/libthreadutils/include/Signal.h", "rank": 67, "score": 82207.45693046896 }, { "content": "\tclass OptParser {\n\n\n\n\t\t// the tool name \n\n\t\tstd::string toolname ;\n\n\n\n\t\t// the options\n\n\t\tstd::vector<std::string> options ;\n\n\n\n\t\t// the short option names\n\n\t\tstd::vector<std::string> shortoptions ;\n\n\n\n\t\t// the long option names\n\n\t\tstd::vector<std::string> longoptions ;\n\n\n\n\t\t// are the options required\n\n\t\tstd::vector<bool> reqoptions ;\n\n\n\n\t\t// does the option have a value\n\n\t\tstd::vector<bool> hasvalues ;\n\n\n", "file_path": "cplusplus/align/include/opt.h", "rank": 68, "score": 82207.45693046896 }, { "content": "\t\t\t\t\trval = _T ;\n\n\t\t\t\t\tbreak ;\n\n\t\t\t\tcase 'C':\n\n\t\t\t\t\trval = _C ;\n\n\t\t\t\t\tbreak ;\n\n\t\t\t\tcase 'G':\n\n\t\t\t\t\trval = _G ;\n\n\t\t\t\t\tbreak ;\n\n\t\t\t\tcase 'N':\n\n\t\t\t\t\trval = _N ;\n\n\t\t\t\t\tbreak ;\n\n\t\t\t\t}\n\n\t\t\t\treturn rval ;\n\n\t\t\t}\n\n\n\n\t\t\t/* get the data loaded to this _DNANode object */\n\n\t\t\tstd::vector<T> data() const {\n\n\t\t\t\tif( _data != NULL ) {\n\n\t\t\t\t\t// printf(\"data is not NULL: contains %d elements\\n\", _data->size() ) ;\n\n\t\t\t\t\treturn std::vector<T>(_data->begin(), _data->end() ) ;\n", "file_path": "cplusplus/align/lib/libnimbus/include/_DNANode.h", "rank": 69, "score": 80345.78393366735 }, { "content": "\t\t\t\tif( _data == NULL ) {\n\n\t\t\t\t\t_data = new std::vector<T>() ;\n\n\t\t\t\t}\n\n\t\t\t\t_data->push_back( l ) ;\n\n\t\t\t}\n\n\n\n\t\t\t/* Adds a child at base b to the node */\n\n\t\t\tbool addChild( char b, _DNANode* d ) {\n\n\t\t\t\tbool rval = true ;\n\n\t\t\t\tswitch(b) {\n\n\t\t\t\tcase 'A':\n\n\t\t\t\t\t_A = d ;\n\n\t\t\t\t\tbreak ;\n\n\t\t\t\tcase 'T':\n\n\t\t\t\t\t_T = d ;\n\n\t\t\t\t\tbreak ;\n\n\t\t\t\tcase 'C':\n\n\t\t\t\t\t_C = d ;\n\n\t\t\t\t\tbreak ;\n\n\t\t\t\tcase 'G':\n", "file_path": "cplusplus/align/lib/libnimbus/include/_DNANode.h", "rank": 70, "score": 80345.20650359697 }, { "content": "\t\t\t\t\t_G = d ;\n\n\t\t\t\t\tbreak ;\n\n\t\t\t\tcase 'N':\n\n\t\t\t\t\t_N = d ;\n\n\t\t\t\t\tbreak ;\n\n\t\t\t\tdefault:\n\n\t\t\t\t\trval = false ;\n\n\t\t\t\t\tbreak ;\n\n\t\t\t\t}\n\n\t\t\t\treturn rval ;\n\n\t\t\t}\n\n\n\n\t\t\t/* Get the child at base b */\n\n\t\t\t_DNANode* getChild( char b ) const {\n\n\t\t\t\t_DNANode* rval = NULL ;\n\n\t\t\t\tswitch(b) {\n\n\t\t\t\tcase 'A':\n\n\t\t\t\t\trval = _A ;\n\n\t\t\t\t\tbreak ;\n\n\t\t\t\tcase 'T':\n", "file_path": "cplusplus/align/lib/libnimbus/include/_DNANode.h", "rank": 71, "score": 80337.01064470844 }, { "content": "\t\t\t_DNANode(_DNANode * p ): _parent(p) {\n\n\t\t\t\t_A = NULL ;\n\n\t\t\t\t_T = NULL ;\n\n\t\t\t\t_C = NULL ;\n\n\t\t\t\t_G = NULL ;\n\n\t\t\t\t_N = NULL ;\n\n\t\t\t\t_data = NULL ;\n\n\t\t\t}\n\n\n\n\t\t\t~_DNANode() {\n\n\t\t\t\tif( _A != NULL ) delete _A ;\n\n\t\t\t\tif( _T != NULL ) delete _T ;\n\n\t\t\t\tif( _C != NULL ) delete _C ;\n\n\t\t\t\tif( _G != NULL ) delete _G ;\n\n\t\t\t\tif( _N != NULL ) delete _N ;\n\n\t\t\t\tif( _data != NULL ) delete _data ;\n\n\t\t\t}\n\n\n\n\t\t\t/* Adds data to the DNANode */\n\n\t\t\tvoid addData( T l ) {\n", "file_path": "cplusplus/align/lib/libnimbus/include/_DNANode.h", "rank": 72, "score": 80332.54482442001 }, { "content": "\t\tstd::vector<T> getTreeData( _DNANode<T>* base, std::string key ) {\n\n\t\t\tstd::vector<T> rval = std::vector<T>() ;\n\n\n\n\t\t\t// printf( \"retrieval start key: \" ) ;\n\n\t\t\t// traverse the string to get an end-point\n\n\t\t\t_DNANode<T>* r = base ;\n\n\t\t\tfor( std::string::iterator it=key.begin(); it!=key.end(); ++it ) {\n\n\t\t\t\t// printf( \"%c-\", *it) ;\n\n\t\t\t\t_DNANode<T>* n = NULL ;\n\n\t\t\t\tn = r->getChild( *it ) ;\n\n\t\t\t\tif( n == NULL ) {\n\n\t\t\t\t\t// printf(\"Break\") ;\n\n\t\t\t\t\tbreak ;\n\n\t\t\t\t}\n\n\t\t\t\tr = n ;\n\n\t\t\t}\n\n\t\t\t// printf( \"\\n\" ) ;\n\n\n\n\t\t\t// if we successfully got to an end-point, copy its contents to the return vector \n\n\t\t\t// Note that this should never be too big \n", "file_path": "cplusplus/align/lib/libnimbus/include/_DNANode.h", "rank": 73, "score": 80332.01051609607 }, { "content": "\t\t\t\t// set our mate fields to default\n\n\t\t\t\tset_to_defaults() ;\n\n\t\t\t}\n\n\n\n\t\t\tSAMRecord( basic::Read r, bool unmapped, std ::string rname, int pos, bool forward, int mq, std::string cig ): Read(r), SAMFlag(), SAMCore(rname, pos, mq, cig) {\n\n\n\n\t\t\t\t// if the record represents an unmapped read\n\n\t\t\t\tif( unmapped ) setUnmapped() ;\n\n\n\n\t\t\t\t// set the strand to reverse complement and invert \n\n\t\t\t\t// the sequence if not mapped to the forward strand\n\n\t\t\t\tif( !forward ) set_to_reverse_strand() ;\n\n\t\t\t\t\n\n\t\t\t\t// set our mate fields to default\n\n\t\t\t\tset_to_defaults() ;\n\n\t\t\t}\n\n\n\n\t\t\t~SAMRecord(void) ;\n\n\n\n\t\t\t// getters\t\t\t\t\t\t\n", "file_path": "cplusplus/align/lib/libnimbus/include/SAMrecord.h", "rank": 74, "score": 80330.0496586022 }, { "content": "\n\n\t\t\tvoid pos( int p ) ;\n\n\n\n\t\t\t/**\n\n\t\t\t get and set mapping quality\n\n\t\t\t **/\n\n\t\t\tint mapq() const ;\n\n\n\n\t\t\tvoid mapq( int q ) ;\n\n\n\n\t\t\t/**\n\n\t\t\t Get the CIGAR string of the read\n\n\t\t\t **/ \n\n\t\t\tstd::string cigar() const ;\n\n\n\n\t\t\t/**\n\n\t\t\t set the cigar field\n\n\t\t\t **/\n\n\t\t\tvoid cigar( std::string c ) ;\n\n\n", "file_path": "cplusplus/align/lib/libnimbus/include/SAMrecord.h", "rank": 75, "score": 80329.89383392636 }, { "content": "\n\n\t\t\tSAMCore(std::string rn, int p, int m, std::string _cig ): _rname(rn), _pos(p), _mapq(m), \n\n\t\t\t\t_cigar(_cig.begin(), _cig.end() ), _rlen(-1), _qlen(-1) { } \n\n\n\n\t\t\tSAMCore(std::string rn, int p, int m, std::vector<char> _cig ): _rname(rn), _pos(p), _mapq(m), \n\n\t\t\t\t_cigar(_cig.begin(), _cig.end() ), _rlen(-1), _qlen(-1) { } \n\n\t\t\t\n\n\t\t\t~SAMCore() {}\n\n\t\t\t\n\n\t\t\t/**\n\n\t\t\t get and set reference name\n\n\t\t\t **/\n\n\t\t\tstd::string rname() const ;\n\n\n\n\t\t\tvoid rname(std::string rn ) ;\n\n\n\n\t\t\t/**\n\n\t\t\t get and set position\n\n\t\t\t **/\n\n\t\t\tint pos() const ;\n", "file_path": "cplusplus/align/lib/libnimbus/include/SAMrecord.h", "rank": 76, "score": 80328.77441447404 }, { "content": "\n\n\t\t\t/**\n\n\t\t\t * Return the number of amplicons currently loaded\n\n\t\t\t **/\n\n\t\t\tunsigned int n_amplicons() const ;\n\n\n\n\t\t\t/**\n\n\t\t\t * Adds an amplicon to the Index \n\n\t\t\t **/\n\n\t\t\tbool add( basic::Amplicon* a ) ;\n\n\n\n\t\t\t/**\n\n\t\t\t * Builds the index\n\n\t\t\t **/\n\n\t\t\tunsigned int build( int keysize ) ;\n\n\n\n\t\t\t/** \n\n\t\t\t * Gets the amplicons corresponding to f and r\n\n\t\t\t **/\n\n\t\t\tstd::vector<basic::Amplicon*> getAmplicons( std::string f, std::string r ) const ; \n", "file_path": "cplusplus/align/lib/libnimbus/include/AmpliconIndex.h", "rank": 77, "score": 80328.74397840309 }, { "content": "\t\t\t// check whether a bit is set\n\n\t\t\tbool isPaired( ) ;\n\n\t\t\tbool isUnmapped( ) ;\n\n\t\t\tbool isProperlyAligned( ) ;\n\n\t\t\tbool isMateUnMapped( ) ;\n\n\t\t\tbool isReverseComplemented( ) ;\n\n\t\t\tbool isNexSegmentReverseComplemented( ) ;\n\n\t\t\tbool isFirstSegmentInTemplate( ) ;\n\n\t\t\tbool isLastSegmentInTemplate( ) ;\n\n\t\t\tbool isSecondaryAlignment( ) ;\n\n\t\t\tbool isNotPassingQC( ) ;\n\n\t\t\tbool isOpticalDuplicate( ) ;\n\n\n\n\t\t\tunsigned int flag() const ;\n\n\t\tprotected:\n\n\t\t\tvoid set( unsigned int x ) ;\n\n\n\n\t\t\tbool isset( unsigned int x ) ; \n\n\n\n\t\t\tvoid unset( unsigned int x ) ;\n\n\t\t} ;\n\n\n\n\n\n\t\t\n\n\n", "file_path": "cplusplus/align/lib/libnimbus/include/SAMrecord.h", "rank": 78, "score": 80327.92077109977 }, { "content": "\t\t\tstd::string rnext() const ;\n\n\t\t\tint pnext() const ;\n\n\t\t\tint tlen() const ;\n\n\t\t\tstd::vector< std::string > tags() const ;\n\n\t\t\tvoid empty_tags() ;\n\n\n\n\t\t\tvoid rnext( std::string r ) ;\n\n\t\t\tvoid pnext( int ) ;\n\n\t\t\tvoid tlen( int ) ;\n\n\t\t\t/**\n\n\t\t\t Set the mate information for this read\n\n\n\n\t\t\t **/\n\n\t\t\tvoid mate( SAMRecord& oth ) ;\n\n\n\n\t\t\tstd::string str() const ;\n\n\n\n\t\t\t/*\n\n\t\t\t Sets the read unmapped and resets the fields\n\n\t\t\t */\n", "file_path": "cplusplus/align/lib/libnimbus/include/SAMrecord.h", "rank": 79, "score": 80327.81972420384 }, { "content": "\t\t\t\t} else {\n\n\t\t\t\t\t// printf(\"data is NULL\\n\") ;\n\n\t\t\t\t\treturn std::vector<T>() ;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t} ;\n\n\n\n\t\t\n\n\t\t/*\n\n\t\t Adds a value to the _DNANode tree at branch key\n\n\t\t */\n\n\t\ttemplate <class T>\n\n\t\tvoid addTreeData( _DNANode<T>* base, std::string key, T l ) {\n\n\t\t\t_DNANode<T>* r = base ;\n\n\n\n\t\t\t// printf( \"start key: \" ) ;\n\n\t\t\t// foreach character in the string\n\n\t\t\tfor( std::string::iterator it=key.begin(); it!=key.end(); ++it ) {\n\n\t\t\t\t_DNANode<T>* n = NULL ;\n\n\t\t\t\tn = r->getChild( *it ) ;\n", "file_path": "cplusplus/align/lib/libnimbus/include/_DNANode.h", "rank": 80, "score": 80327.30167906008 }, { "content": "\t\t\tvoid cigar( std::vector<char> c ) ;\n\n\n\n\t\t\t/**\n\n\t\t\t the length of the record on the reference\n\n\t\t\t **/ \n\n\t\t\tint rlen() ;\n\n\n\n\t\t\t/**\n\n\t\t\t the length of the record on the query\n\n\t\t\t **/\n\n\t\t\tint qlen() ;\n\n\t\t} ;\n\n\n\n\t\t//\n\n\t\t// create the SAMRecord \n\n\t\t//\n\n\n", "file_path": "cplusplus/align/lib/libnimbus/include/SAMrecord.h", "rank": 81, "score": 80326.2245078678 }, { "content": "\t\t\t\tif( unmapped ) setUnmapped() ;\n\n\n\n\t\t\t\t// set the strand to reverse complement and invert \n\n\t\t\t\t// the sequence if not mapped to the forward strand\n\n\t\t\t\tif( !forward ) set_to_reverse_strand() ;\n\n\n\n\t\t\t\t// set our mate fields to default\n\n\t\t\t\tset_to_defaults() ;\n\n\n\n\t\t\t}\n\n\n\n\t\t\tSAMRecord( basic::Read r, bool unmapped, std::string rname, int pos, bool forward, std::string cig ): Read(r), SAMFlag(), SAMCore(rname, pos, 0, cig) {\n\n\n\n\t\t\t\t// if the record represents an unmapped read\n\n\t\t\t\tif( unmapped ) setUnmapped() ;\n\n\n\n\t\t\t\t// set the strand to reverse complement and invert \n\n\t\t\t\t// the sequence if not mapped to the forward strand\n\n\t\t\t\tif( !forward ) set_to_reverse_strand() ;\n\n\t\t\t\t\n", "file_path": "cplusplus/align/lib/libnimbus/include/SAMrecord.h", "rank": 82, "score": 80326.009204144 }, { "content": "\t\t\tif( r != NULL ) {\n\n\t\t\t\t// printf( \"r not NULL\\n\" ) ;\n\n\t\t\t\trval = r->data() ;\t\t\t\t\n\n\t\t\t}\n\n\n\n\t\t\t// return the std::vector<T>\n\n\t\t\treturn rval ;\n\n\t\t}\n\n\n\n\t}\n\n}", "file_path": "cplusplus/align/lib/libnimbus/include/_DNANode.h", "rank": 83, "score": 80324.19083675784 }, { "content": "\t\tTQueue& operator=( const TQueue& ) ;\n\n\n\n\tpublic:\n\n\t\tvoid push( T val ){ \n\n\t\t\tstd::lock_guard<std::mutex> guard( get_mutex() ) ;\n\n\t\t\t_b.push( val ) ;\n\n\t\t} \n\n\n\n\t\tT front( ) {\n\n\t\t\tstd::lock_guard<std::mutex> guard( get_mutex() ) ;\n\n\t\t\treturn _b.front() ;\n\n\t\t}\n\n\n\n\t\tvoid pop( ) {\n\n\t\t\tstd::lock_guard<std::mutex> guard( get_mutex() ) ;\n\n\t\t\t_b.pop() ;\n\n\t\t}\n\n\n\n\t\tbool shift( T& rval ) {\n\n\t\t\tbool r = false ;\n", "file_path": "cplusplus/align/lib/libthreadutils/include/TQueue.h", "rank": 84, "score": 80324.0024523453 }, { "content": "#pragma once\n\n\n\n#include \"stdafx.h\"\n\n#include \"Read.h\"\n\n\n\nnamespace Nimbus {\n\n\n\n\tnamespace utils {\n\n\n\n\t\t\n\n\t\t//\n\n\t\t// A class to trim sequences from reads \n\n\t\t//\n", "file_path": "cplusplus/align/lib/libnimbus/include/AdapterTrim.h", "rank": 85, "score": 80323.94089013503 }, { "content": "#pragma once\n\n#include \"stdafx.h\"\n\n#include \"Read.h\"\n\n#include \"Utils.h\"\n\n\n\n\n\nnamespace Nimbus {\n\n\n\n\tnamespace alignment { \n\n\n\n\n\n\t\t/**\n\n\t\t Overview\n\n\t\t ========\n\n\n\n\t\t This source file is to define the classes associated with SAM files. \n\n\t\t \n\n\t\t The central class in this source file is the SAMRecord class.\n\n\n\n\t\t SAMRecords are defined from multiple parent classes to \n", "file_path": "cplusplus/align/lib/libnimbus/include/SAMrecord.h", "rank": 86, "score": 80322.71880974917 }, { "content": "\t\t\tvoid Unmap() ;\n\n\n\n\t\t\t/** \n\n\t\t\t add any value as a tag\n\n\t\t\t **/\n\n\t\t\ttemplate<class T>\n\n\t\t\tvoid add_tag( std::string nm, char type, T content ) {\n\n\t\t\t\tstd::stringstream s ;\n\n\t\t\t\ts << nm << ':' << type << ':' << content ;\n\n\t\t\t\t_tags.push_back( s.str() ) ;\n\n\t\t\t}\t\t\t\n\n\n\n\t\t\t\n\n\n\n\n\n\t\tprotected:\n\n\n\n\t\t\tvoid set_to_defaults( ) {\n\n\t\t\t\t_rnext = \"*\" ;\n\n\t\t\t\t_pnext = 0 ;\n", "file_path": "cplusplus/align/lib/libnimbus/include/SAMrecord.h", "rank": 87, "score": 80321.72276367532 }, { "content": "\t\t\tstd::lock_guard<std::mutex> guard( get_mutex() ) ;\n\n\t\t\tif( ! _b.empty() ) {\n\n\t\t\t\trval = _b.front() ;\n\n\t\t\t\t_b.pop() ;\t\t\t\n\n\t\t\t\tr = true ;\n\n\t\t\t}\n\n\t\t\treturn r ;\n\n\t\t}\n\n\n\n\t\tbool empty() {\n\n\t\t\tstd::lock_guard<std::mutex> guard( get_mutex() ) ;\n\n\t\t\tbool r = _b.empty() ;\n\n\t\t\treturn r ;\n\n\t\t}\n\n\n\n\t\tsize_t size() {\n\n\t\t\tstd::lock_guard<std::mutex> guard( get_mutex() ) ;\n\n\t\t\treturn _b.size() ;\n\n\t\t}\n\n\n\n\t\tstd::mutex& get_mutex( ) {\n\n\t\t\treturn _m ;\n\n\t\t}\n\n\t};\n\n\n\n}", "file_path": "cplusplus/align/lib/libthreadutils/include/TQueue.h", "rank": 88, "score": 80320.41388673552 }, { "content": "#pragma once\n\n\n\n#include \"Amplicon.h\"\n\n#include \"_DNANode.h\"\n\n#include \"Read.h\"\n\n\n\nnamespace Nimbus {\n\n\n\n\tnamespace seed {\n\n\n\n\t\n\n\n\n\t\t//\n\n\t\t// AmpliconIndex\n\n\t\t//\n\n\n", "file_path": "cplusplus/align/lib/libnimbus/include/AmpliconIndex.h", "rank": 89, "score": 80320.06837870795 }, { "content": "\t\t\tvoid setNexSegmentReverseComplemented( ) ;\n\n\t\t\tvoid setFirstSegmentInTemplate( ) ;\n\n\t\t\tvoid setLastSegmentInTemplate( ) ;\n\n\t\t\tvoid setSecondaryAlignment( ) ;\n\n\t\t\tvoid setNotPassingQC( ) ;\n\n\t\t\tvoid setOpticalDuplicate( ) ;\n\n\n\n\t\t\t// unset the bits for the respective properties\n\n\t\t\tvoid unsetPaired( ) ;\n\n\t\t\tvoid unsetUnmapped( ) ;\n\n\t\t\tvoid unsetProperlyAligned( ) ;\n\n\t\t\tvoid unsetMateUnMapped( ) ;\n\n\t\t\tvoid unsetReverseComplemented( ) ;\n\n\t\t\tvoid unsetNexSegmentReverseComplemented( ) ;\n\n\t\t\tvoid unsetFirstSegmentInTemplate( ) ;\n\n\t\t\tvoid unsetLastSegmentInTemplate( ) ;\n\n\t\t\tvoid unsetSecondaryAlignment( ) ;\n\n\t\t\tvoid unsetNotPassingQC( ) ;\n\n\t\t\tvoid unsetOpticalDuplicate( ) ;\n\n\n", "file_path": "cplusplus/align/lib/libnimbus/include/SAMrecord.h", "rank": 90, "score": 80319.49439132896 }, { "content": "\t\t\t\t_tlen = 0 ;\n\n\t\t\t} \n\n\n\n\t\t\tvoid set_to_reverse_strand() {\n\n\t\t\t\tsetReverseComplemented() ;\n\n\t\t\t\tsequence( rc_sequence() ) ;\n\n\t\t\t\tquality( r_quality() ) ;\n\n\t\t\t}\n\n\n\n\t\t} ;\n\n\n", "file_path": "cplusplus/align/lib/libnimbus/include/SAMrecord.h", "rank": 91, "score": 80318.76445132404 }, { "content": "\n\n\t\t\tstd::vector<basic::Amplicon*> getAmpliconsF( std::string f ) const ;\n\n\n\n\t\t\tstd::vector<basic::Amplicon*> getAmpliconsR( std::string r ) const ;\n\n\n\n\t\t\t/** \n\n\t\t\t * Gets the amplicons corresponding to f and r\n\n\t\t\t **/\n\n\t\t\tstd::vector<basic::Amplicon*> getAmplicons( basic::Read* f, basic::Read* r ) const ; \n\n\n\n\t\t\tstd::vector<basic::Amplicon*> getAmplicons( std::pair<basic::Read*, basic::Read*> p ) const ; \n\n\n\n\t\tprotected:\n\n\n\n\t\t} ;\n\n\n\n\t}\n\n}\n", "file_path": "cplusplus/align/lib/libnimbus/include/AmpliconIndex.h", "rank": 92, "score": 80318.72267600881 }, { "content": "\t\t\t\tif( n == NULL ) {\n\n\t\t\t\t\tn = new _DNANode<T>( r ) ;\n\n\t\t\t\t\tr->addChild( *it, n ) ;\n\n\t\t\t\t\t// printf( \"%c-\", *it) ;\n\n\t\t\t\t}\n\n\t\t\t\tr = n ;\n\n\t\t\t}\n\n\n\n\t\t\t// after traversing the string add the index to the end\n\n\t\t\tif( r != NULL ) {\n\n\t\t\t\t// printf(\"adding\") ;\n\n\t\t\t\tr->addData( l ) ;\n\n\t\t\t}\n\n\t\t\t// printf( \"\\n\" ) ;\n\n\t\t}\n\n\n\n\t\t/*\n\n\t\t Gets the value from the _DNANode tree at branch key\n\n\t\t */\n\n\t\ttemplate <class T>\n", "file_path": "cplusplus/align/lib/libnimbus/include/_DNANode.h", "rank": 93, "score": 80317.8032918869 }, { "content": "\t\t divide the logic for read information, flag information\n\n\t\t and positional information. One these classes is external \n\n\t\t with the Read class. \n\n\n\n\t\t These classes make up the SAMRecord via multiple inheritance.\n\n\t\t \n\n\t\t SAMFlag\n\n\t\t -------\n\n\t\t This class contains all the _flag integer variable and all\n\n\t\t the named functions used to set the different bits in the flag. \n\n\n\n\t\t SAMCore\n\n\t\t -------\n\n\t\t The main determinants for the alignment are defined here, such\n\n\t\t as the reference name, position and the CIGAR string. \n\n\n\n\t\t SAMRecord\n\n\t\t ---------\n\n\t\t This class is derived from the Read, SAMFlag and SAMRecord \n\n\t\t classes. The SAMRecord class itself also defines the mate-pair \n\n\t\t related functions. \n\n\n\n\t\t SAMHeader\n\n\t\t ---------\n\n\t\t A class representing the SAM header. \n\n\t\t**/\n\n\n", "file_path": "cplusplus/align/lib/libnimbus/include/SAMrecord.h", "rank": 94, "score": 80317.71965885167 }, { "content": "#pragma once\n\n\n\nnamespace Nimbus {\n\n\n\n\tnamespace seed {\n\n\n\n\t\t//\n\n\t\t// _DNANode\n\n\t\t//\n\n\t\ttemplate <class T>\n", "file_path": "cplusplus/align/lib/libnimbus/include/_DNANode.h", "rank": 95, "score": 80314.89380322151 }, { "content": "#pragma once\n\n\n\nnamespace threadutils {\n\n\n\n\t/**\n\n\t A queue for used in threads\n\n\t **/\n\n\ttemplate<class T>\n", "file_path": "cplusplus/align/lib/libthreadutils/include/TQueue.h", "rank": 96, "score": 80314.15313904015 }, { "content": "\tclass Signal {\n\n\n\n\tprotected:\n\n\t\tT _signal ;\n\n\t\tstd::mutex _m ;\n\n\n\n\tpublic:\n\n\t\tSignal(void) {\n\n\t\t\n\n\t\t}\n\n\n\n\t\tSignal( T s ): _signal(s) { \n\n\t\t\n\n\t\t}\n\n\n\n\t\tSignal( const Signal& other ) {\n\n\t\t\tstd::lock_guard<std::mutex> guard( other.get_mutex() ) ;\n\n\t\t\t_signal = other._signal ;\n\n\t\t}\n\n\n", "file_path": "cplusplus/align/lib/libthreadutils/include/Signal.h", "rank": 97, "score": 80309.75870726198 }, { "content": "\t\tclass Read {\n\n\t\t\t\n\n\t\tprotected:\n\n\t\t\tstd::string _name ;\n\n\t\t\tstd::string _seq ;\n\n\t\t\tstd::string _qual ;\n\n\t\t\tstd::string _rc_seq ;\n\n\t\t\tstd::string _r_qual ;\n\n\n\n\t\tpublic:\n\n\t\t\tRead( std::string name, std::string sequence, std::string qualiy ) ;\n\n\t\t\t\n\n\t\t\tRead() ;\n\n\n\n\t\t\tRead( const Read& other ) ;\n\n\n\n\t\t\t~Read(void);\n\n\t\t\t\n\n\t\t\t/* get the reverse complement of the sequence */\n\n\t\t\tstd::string rc_sequence() ;\n", "file_path": "cplusplus/align/lib/libnimbus/include/Read.h", "rank": 98, "score": 80309.75870726198 }, { "content": "\t\tclass GenomicRegion {\n\n\t\tprotected: \n\n\t\t\tstd::string _chr ;\n\n\t\t\tint _start ;\n\n\t\t\tint _end ;\n\n\t\t\tbool _forward ;\n\n\t\t\tstd::string _name ;\n\n\t\tpublic:\n\n\t\t\tGenomicRegion( std::string chr, int start, int end, bool forward ): _chr(chr), \n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_start(start), _end(end), \n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_forward(forward), _name(\"\") {\n\n\t\t\t}\n\n\n\n\t\t\tGenomicRegion( std::string chr, int start, int end, bool forward, std::string nm ): _chr(chr), \n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_start(start), _end(end), \n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_forward(forward), _name(nm) {\n\n\t\t\t}\n\n\t\t\t\n\n\t\t\tGenomicRegion( const GenomicRegion& other ):_chr(other.chromosome()), \n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t_start(other.start()), _end(other.end()), \n", "file_path": "cplusplus/align/lib/libnimbus/include/Amplicon.h", "rank": 99, "score": 78497.69753067318 } ]
C++
software/src/master/src/vca_sample_distribution_server/vca_sample_distribution_server.cpp
c-kuhlman/vision
46b25f7c0da703c059acc8f0a2eac1d5badf9f6d
#include "Vk.h" #include "Vca_VOneAppMain_.h" #include "Vca_VServerApplication.h" #include "Vca_VLineGrabber.h" #include "vca_samples_ipublication.h" #include "vca_samples_isubscription.h" namespace VcaSamples { class ThisApp : public Vca::VServerApplication { DECLARE_CONCRETE_RTT (ThisApp, Vca::VServerApplication); public: typedef Reference AppReference; typedef Vca::VLineGrabber_<ThisClass> InputSource; public: class Subscription : public Vca::VRolePlayer { DECLARE_CONCRETE_RTT (Subscription, Vca::VRolePlayer); public: typedef IVReceiver<VString const &> IRecipient; public: Subscription (ThisApp *pApp, ISubscriber *pSubscriber, IRecipient *pRecipient, bool bSuspended); private: ~Subscription (); public: using BaseClass::getRole; private: Vca::VRole<ThisClass,ISubscription> m_pISubscription; public: void getRole (ISubscription::Reference &rpRole) { m_pISubscription.getRole (rpRole); } public: void Suspend (ISubscription *pRole); void Resume (ISubscription *pRole); void Cancel (ISubscription *pRole); public: ThisClass *publish (VString const &rMessage); private: void unlink (); private: AppReference const m_pApp; ISubscriber::Reference const m_pSubscriber; IRecipient::Reference const m_pRecipient; Pointer m_pSuccessor; Pointer m_pPredecessor; bool m_bSuspended; bool m_bCanceled; }; friend class Subscription; public: ThisApp (Context *pContext); private: ~ThisApp (); public: using BaseClass::getRole; private: Vca::VRole<ThisClass,IPublication> m_pIPublication; public: void getRole (IPublication::Reference &rpRole) { m_pIPublication.getRole (rpRole); } public: void Subscribe ( IPublication *pRole, ISubscriber *pSubscriber, IRecipient *pRecipient, bool bSuspended ); private: virtual void onStandardInput (Vca::VBSProducer *pStdin) OVERRIDE; virtual bool start_() OVERRIDE; public: bool onInputLine (char const *pLine, size_t sLine); void onInputDone (); private: Subscription::Pointer m_pSubscriptions; }; } template class Vca::VLineGrabber_<VcaSamples::ThisApp>; DEFINE_CONCRETE_RTT (VcaSamples::ThisApp); VcaSamples::ThisApp::ThisApp (Context *pContext) : BaseClass (pContext), m_pIPublication (this) { } VcaSamples::ThisApp::~ThisApp () { } void VcaSamples::ThisApp::Subscribe ( IPublication *pRole, ISubscriber *pSubscriber, IRecipient *pRecipient, bool bSuspended ) { if (pSubscriber) { Subscription::IRecipient::Reference pMessageReceiver ( dynamic_cast<Subscription::IRecipient*>(pRecipient) ); if (pMessageReceiver.isNil ()) pSubscriber->OnError (0, "Invalid or Missing Recipient"); else { Subscription::Reference pSubscription ( new Subscription (this, pSubscriber, pMessageReceiver, bSuspended) ); } } } bool VcaSamples::ThisApp::start_() { if (!BaseClass::start_()) return false; if (offerSelf ()) getStandardInput (); else { fprintf (stderr, "Usage: No address to offer object.\n"); setExitStatus (ErrorExitValue); } return isStarting (); } void VcaSamples::ThisApp::onStandardInput (Vca::VBSProducer *pStdin) { InputSource::Reference pInputProvider (new InputSource (pStdin, this)); } bool VcaSamples::ThisApp::onInputLine (char const *pLine, size_t sLine) { VString iText; iText.setTo (pLine, sLine); Subscription::Reference pSubscription (m_pSubscriptions); while (pSubscription) { pSubscription.setTo (pSubscription->publish (iText)); } return true; } void VcaSamples::ThisApp::onInputDone () { stop (); } DEFINE_CONCRETE_RTT (VcaSamples::ThisApp::Subscription); VcaSamples::ThisApp::Subscription::Subscription ( ThisApp *pApp, ISubscriber *pSubscriber, IRecipient *pRecipient, bool bSuspended ) : m_pApp (pApp) , m_pSubscriber (pSubscriber) , m_pRecipient (pRecipient) , m_pSuccessor (pApp->m_pSubscriptions) , m_bSuspended (bSuspended) , m_bCanceled (false) , m_pISubscription (this) { pApp->m_pSubscriptions.setTo (this); retain (); { ISubscription::Reference pRole; getRole (pRole); pSubscriber->OnData (pRole); } untain (); } VcaSamples::ThisApp::Subscription::~Subscription () { unlink (); } void VcaSamples::ThisApp::Subscription::Suspend (ISubscription *pRole) { if (!m_bCanceled) m_bSuspended = true; } void VcaSamples::ThisApp::Subscription::Resume (ISubscription *pRole) { if (!m_bCanceled) m_bSuspended = false; } void VcaSamples::ThisApp::Subscription::Cancel (ISubscription *pRole) { unlink (); } VcaSamples::ThisApp::Subscription *VcaSamples::ThisApp::Subscription::publish (VString const &rMessage) { if (m_pRecipient && !m_bSuspended) m_pRecipient->OnData (rMessage); return m_pSuccessor; } void VcaSamples::ThisApp::Subscription::unlink () { m_bCanceled = m_bSuspended = true; if (m_pSuccessor) m_pSuccessor->m_pPredecessor.setTo (m_pPredecessor); if (m_pPredecessor) m_pPredecessor->m_pSuccessor.setTo (m_pSuccessor); else m_pApp->m_pSubscriptions.setTo (m_pSuccessor); m_pPredecessor.clear (); m_pSuccessor.clear (); } int main (int argc, char *argv[]) { Vca::VOneAppMain_<VcaSamples::ThisApp> iMain (argc, argv); return iMain.processEvents (); }
#include "Vk.h" #include "Vca_VOneAppMain_.h" #include "Vca_VServerApplication.h" #include "Vca_VLineGrabber.h" #include "vca_samples_ipublication.h" #include "vca_samples_isubscription.h" namespace VcaSamples { class ThisApp : public Vca::VServerApplication { DECLARE_CONCRETE_RTT (ThisApp, Vca::VServerApplication); public: typedef Reference AppReference; typedef Vca::VLineGrabber_<ThisClass> InputSource; public: class Subscription : public Vca::VRolePlayer { DECLARE_CONCRETE_RTT (Subscription, Vca::VRolePlayer); public: typedef IVReceiver<VString const &> IRecipient; public: Subscription (ThisApp *pApp, ISubscriber *pSubscriber, IRecipient *pRecipient, bool bSuspended); private: ~Subscription (); public: using BaseClass::getRole; private: Vca::VRole<ThisClass,ISubscription> m_pISubscription; public: void getRole (ISubscription::Reference &rpRole) { m_pISubscription.getRole (rpRole); } public: void Suspend (ISubscription *pRole); void Resume (ISubscription *pRole); void Cancel (ISubscription *pRole); public: ThisClass *publish (VString const &rMessage); private: void unlink (); private: AppReference const m_pApp; ISubscriber::Reference const m_pSubscriber; IRecipient::Reference const m_pRecipient; Pointer m_pSuccessor; Pointer m_pPredecessor; bool m_bSuspended; bool m_bCanceled; }; friend class Subscription; public: ThisApp (Context *pContext); private: ~ThisApp (); public: using BaseClass::getRole; private: Vca::VRole<ThisClass,IPublication> m_pIPublication; public: void getRole (IPublication::Reference &rpRole) { m_pIPublication.getRole (rpRole); } public: void Subscribe ( IPublication *pRole, ISubscriber *pSubscriber, IRecipient *pRecipient, bool bSuspended ); private: virtual void onStandardInput (Vca::VBSProducer *pStdin) OVERRIDE; virtual bool start_() OVERRIDE; public: bool onInputLine (char const *pLine, size_t sLine); void onInputDone (); private: Subscription::Pointer m_pSubscriptions; }; } template class Vca::VLineGrabber_<VcaSamples::ThisApp>; DEFINE_CONCRETE_RTT (VcaSamples::ThisApp); VcaSamples::ThisApp::ThisApp (Context *pContext) : BaseClass (pContext), m_pIPublication (this) { } VcaSamples::ThisApp::~ThisApp () { }
bool VcaSamples::ThisApp::start_() { if (!BaseClass::start_()) return false; if (offerSelf ()) getStandardInput (); else { fprintf (stderr, "Usage: No address to offer object.\n"); setExitStatus (ErrorExitValue); } return isStarting (); } void VcaSamples::ThisApp::onStandardInput (Vca::VBSProducer *pStdin) { InputSource::Reference pInputProvider (new InputSource (pStdin, this)); } bool VcaSamples::ThisApp::onInputLine (char const *pLine, size_t sLine) { VString iText; iText.setTo (pLine, sLine); Subscription::Reference pSubscription (m_pSubscriptions); while (pSubscription) { pSubscription.setTo (pSubscription->publish (iText)); } return true; } void VcaSamples::ThisApp::onInputDone () { stop (); } DEFINE_CONCRETE_RTT (VcaSamples::ThisApp::Subscription); VcaSamples::ThisApp::Subscription::Subscription ( ThisApp *pApp, ISubscriber *pSubscriber, IRecipient *pRecipient, bool bSuspended ) : m_pApp (pApp) , m_pSubscriber (pSubscriber) , m_pRecipient (pRecipient) , m_pSuccessor (pApp->m_pSubscriptions) , m_bSuspended (bSuspended) , m_bCanceled (false) , m_pISubscription (this) { pApp->m_pSubscriptions.setTo (this); retain (); { ISubscription::Reference pRole; getRole (pRole); pSubscriber->OnData (pRole); } untain (); } VcaSamples::ThisApp::Subscription::~Subscription () { unlink (); } void VcaSamples::ThisApp::Subscription::Suspend (ISubscription *pRole) { if (!m_bCanceled) m_bSuspended = true; } void VcaSamples::ThisApp::Subscription::Resume (ISubscription *pRole) { if (!m_bCanceled) m_bSuspended = false; } void VcaSamples::ThisApp::Subscription::Cancel (ISubscription *pRole) { unlink (); } VcaSamples::ThisApp::Subscription *VcaSamples::ThisApp::Subscription::publish (VString const &rMessage) { if (m_pRecipient && !m_bSuspended) m_pRecipient->OnData (rMessage); return m_pSuccessor; } void VcaSamples::ThisApp::Subscription::unlink () { m_bCanceled = m_bSuspended = true; if (m_pSuccessor) m_pSuccessor->m_pPredecessor.setTo (m_pPredecessor); if (m_pPredecessor) m_pPredecessor->m_pSuccessor.setTo (m_pSuccessor); else m_pApp->m_pSubscriptions.setTo (m_pSuccessor); m_pPredecessor.clear (); m_pSuccessor.clear (); } int main (int argc, char *argv[]) { Vca::VOneAppMain_<VcaSamples::ThisApp> iMain (argc, argv); return iMain.processEvents (); }
void VcaSamples::ThisApp::Subscribe ( IPublication *pRole, ISubscriber *pSubscriber, IRecipient *pRecipient, bool bSuspended ) { if (pSubscriber) { Subscription::IRecipient::Reference pMessageReceiver ( dynamic_cast<Subscription::IRecipient*>(pRecipient) ); if (pMessageReceiver.isNil ()) pSubscriber->OnError (0, "Invalid or Missing Recipient"); else { Subscription::Reference pSubscription ( new Subscription (this, pSubscriber, pMessageReceiver, bSuspended) ); } } }
function_block-full_function
[ { "content": "\t class Property_<void (Container_T::*)(IVReceiver<Value_T>*) const> : public Property {\n\n\tpublic:\n\n\t typedef void (Container_T::*accessor_t)(IVReceiver<Value_T>*) const;\n\n\t typedef Property_<accessor_t> this_t;\n\n\t DECLARE_CONCRETE_RTTLITE (this_t, Property);\n\n\n\n\t// Construction\n\n\tpublic:\n\n\t Property_(accessor_t pAccessor) : m_pAccessor (pAccessor) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~Property_() {\n\n\t }\n\n\n\n\t// Access\n\n\tprivate:\n\n\t template <typename sink_t> bool getValueImpl (sink_t *pResultSink, VRolePlayer *pContainer) const {\n\n\t\treturn false;\n", "file_path": "software/src/8.1/src/kernel/Vca_VClassInfoHolder.h", "rank": 0, "score": 359738.55998167436 }, { "content": "\t class Property_<void (Container_T::*)(IVReceiver<Value_T>*) const> : public Property {\n\n\tpublic:\n\n\t typedef void (Container_T::*accessor_t)(IVReceiver<Value_T>*) const;\n\n\t typedef Property_<accessor_t> this_t;\n\n\t DECLARE_CONCRETE_RTTLITE (this_t, Property);\n\n\n\n\t// Construction\n\n\tpublic:\n\n\t Property_(accessor_t pAccessor) : m_pAccessor (pAccessor) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~Property_() {\n\n\t }\n\n\n\n\t// Access\n\n\tprivate:\n\n\t template <typename sink_t> bool getValueImpl (sink_t *pResultSink, VRolePlayer *pContainer) const {\n\n\t\treturn false;\n", "file_path": "software/src/8.0/src/kernel/Vca_VClassInfoHolder.h", "rank": 1, "score": 359738.55998167436 }, { "content": "\t class Subscription : public InterfaceSubscription {\n\n\t\tDECLARE_CONCRETE_RTTLITE (Subscription, InterfaceSubscription);\n\n\n\n\t\tfriend class SubscriptionManager;\n\n\t\t\n\n\t // Construction\n\n\t public:\n\n\t\tSubscription (Interface_T *pTarget) : m_pTarget (pTarget) {\n\n\t\t}\n\n\n\n\t // Destruction\n\n\t private:\n\n\t\t~Subscription () {\n\n\t\t}\n\n\n\n\t public:\n\n\t\tThisClass* successor () const {\n\n\t\t return NextUsable (m_pSuccessor);\n\n\t\t}\n\n\t\tInterface_T* target () const {\n", "file_path": "software/src/8.1/src/kernel/Vca_VPublisher.h", "rank": 2, "score": 359656.76000502805 }, { "content": "\t class Subscription : public InterfaceSubscription {\n\n\t\tDECLARE_CONCRETE_RTTLITE (Subscription, InterfaceSubscription);\n\n\n\n\t\tfriend class SubscriptionManager;\n\n\t\t\n\n\t // Construction\n\n\t public:\n\n\t\tSubscription (Interface_T *pTarget) : m_pTarget (pTarget) {\n\n\t\t}\n\n\n\n\t // Destruction\n\n\t private:\n\n\t\t~Subscription () {\n\n\t\t}\n\n\n\n\t public:\n\n\t\tThisClass* successor () const {\n\n\t\t return NextUsable (m_pSuccessor);\n\n\t\t}\n\n\t\tInterface_T* target () const {\n", "file_path": "software/src/8.0/src/kernel/Vca_VPublisher.h", "rank": 3, "score": 359656.76000502805 }, { "content": "\t class Property_<void (Container_T::*)(IVReceiver<Value_T>*) const> : public Property {\n\n\tpublic:\n\n\t typedef void (Container_T::*accessor_t)(IVReceiver<Value_T>*) const;\n\n\t typedef Property_<accessor_t> this_t;\n\n\t DECLARE_CONCRETE_RTTLITE (this_t, Property);\n\n\n\n\t// Construction\n\n\tpublic:\n\n\t Property_(accessor_t pAccessor) : m_pAccessor (pAccessor) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~Property_() {\n\n\t }\n\n\n\n\t// Access\n\n\tprivate:\n\n\t template <typename sink_t> bool getValueImpl (sink_t *pResultSink, VRolePlayer *pContainer) const {\n\n\t\treturn false;\n", "file_path": "software/src/master/src/kernel/Vca_VClassInfoHolder.h", "rank": 4, "score": 356095.368816157 }, { "content": "\t class Subscription : public InterfaceSubscription {\n\n\t\tDECLARE_CONCRETE_RTTLITE (Subscription, InterfaceSubscription);\n\n\n\n\t\tfriend class SubscriptionManager;\n\n\t\t\n\n\t // Construction\n\n\t public:\n\n\t\tSubscription (Interface_T *pTarget) : m_pTarget (pTarget) {\n\n\t\t}\n\n\n\n\t // Destruction\n\n\t private:\n\n\t\t~Subscription () {\n\n\t\t}\n\n\n\n\t public:\n\n\t\tvirtual ThisClass* successor () const OVERRIDE {\n\n\t\t return NextUsable (m_pSuccessor);\n\n\t\t}\n\n\t\tvirtual Interface_T* target () const OVERRIDE {\n", "file_path": "software/src/master/src/kernel/Vca_VPublisher.h", "rank": 5, "score": 354646.6637298104 }, { "content": "\tclass SubscriptionManager : public VSubscriptionManager {\n\n\t DECLARE_CONCRETE_RTTLITE (SubscriptionManager, VSubscriptionManager);\n\n\n\n\t// Subscription\n\n\tpublic:\n", "file_path": "software/src/8.0/src/kernel/Vca_VPublisher.h", "rank": 6, "score": 349824.53154129913 }, { "content": "\tclass SubscriptionManager : public VSubscriptionManager {\n\n\t DECLARE_CONCRETE_RTTLITE (SubscriptionManager, VSubscriptionManager);\n\n\n\n\t// Subscription\n\n\tpublic:\n", "file_path": "software/src/8.1/src/kernel/Vca_VPublisher.h", "rank": 7, "score": 349824.53154129913 }, { "content": " class Vxa_API VClass : virtual public VStaticTransient, virtual public VExportableType {\n\n\tDECLARE_FAMILY_MEMBERS (VClass, VStaticTransient);\n\n\n\n // Aliases\n\n public:\n\n\ttypedef VkMapOf<VString,VString const&,char const*,VMethod::Reference> dictionary_t;\n\n\n\n // Construction\n\n protected:\n\n\tVClass ();\n\n\n\n // Destruction\n\n protected:\n\n\t~VClass ();\n\n\n\n // Initialization\n\n protected:\n\n\tvoid initialize () {\n\n\t}\n\n\n", "file_path": "software/src/8.0/src/kernel/Vxa_VClass.h", "rank": 8, "score": 348375.1941830154 }, { "content": " class Vxa_API VClass : virtual public VStaticTransient, virtual public VExportableType {\n\n\tDECLARE_FAMILY_MEMBERS (VClass, VStaticTransient);\n\n\n\n // Aliases\n\n public:\n\n\ttypedef VkMapOf<VString,VString const&,char const*,VMethod::Reference> dictionary_t;\n\n\n\n // Construction\n\n protected:\n\n\tVClass ();\n\n\n\n // Destruction\n\n protected:\n\n\t~VClass ();\n\n\n\n // Initialization\n\n protected:\n\n\tvoid initialize () {\n\n\t}\n\n\n", "file_path": "software/src/8.1/src/kernel/Vxa_VClass.h", "rank": 9, "score": 348375.1941830154 }, { "content": "\tclass SubscriptionManager : public VSubscriptionManager {\n\n\t DECLARE_CONCRETE_RTTLITE (SubscriptionManager, VSubscriptionManager);\n\n\n\n\t// Subscription\n\n\tpublic:\n", "file_path": "software/src/master/src/kernel/Vca_VPublisher.h", "rank": 10, "score": 345179.7309268731 }, { "content": " class Context : public VTask::Context {\n\n // Friends\n\n\tfriend class VTopTaskBase;\n\n\n\n // Construction\n\n protected:\n\n\tContext (VTopTaskBase* pController);\n\n\n\n // Destruction\n\n protected:\n\n\t~Context ();\n\n\n\n // State\n\n protected:\n\n\tControlPoints m_iControlPoints;\n\n };\n\n\n\n// Meta Maker\n\nprotected:\n\n static void MetaMaker ();\n", "file_path": "software/src/8.1/src/backend/VTopTaskBase.h", "rank": 11, "score": 340807.53069096763 }, { "content": " class Context : public VTask::Context {\n\n // Friends\n\n\tfriend class VTopTaskBase;\n\n\n\n // Construction\n\n protected:\n\n\tContext (VTopTaskBase* pController);\n\n\n\n // Destruction\n\n protected:\n\n\t~Context ();\n\n\n\n // State\n\n protected:\n\n\tControlPoints m_iControlPoints;\n\n };\n\n\n\n// Meta Maker\n\nprotected:\n\n static void MetaMaker ();\n", "file_path": "software/src/8.0/src/backend/VTopTaskBase.h", "rank": 12, "score": 340807.53069096763 }, { "content": " class QueryContext : public Context {\n\n\tDECLARE_FAMILY_MEMBERS (QueryContext, Context);\n\n\n\n // Construction\n\n public:\n\n\tQueryContext (VTask *pCaller);\n\n\n\n // Destruction\n\n public:\n\n\t~QueryContext ();\n\n\n\n // Fulfillment\n\n public:\n\n\tbool fulfill (GoferOrder const &rOrder);\n\n\n\n // Transitions\n\n public:\n\n\tvoid onQueryInProgress (VReadEvalPrintController *pTask);\n\n\tvoid onQueryCompleted (VReadEvalPrintController *pTask);\n\n\n", "file_path": "software/src/8.1/src/backend/VReadEvalPrint.h", "rank": 13, "score": 339314.2779223535 }, { "content": " class Context : public VTask::Context {\n\n // Friends\n\n\tfriend class VTopTaskBase;\n\n\n\n // Construction\n\n protected:\n\n\tContext (VTopTaskBase* pController);\n\n\n\n // Destruction\n\n protected:\n\n\t~Context ();\n\n\n\n // State\n\n protected:\n\n\tControlPoints m_iControlPoints;\n\n };\n\n\n\n// Meta Maker\n\nprotected:\n\n static void MetaMaker ();\n", "file_path": "software/src/master/src/backend/VTopTaskBase.h", "rank": 14, "score": 337376.861312505 }, { "content": " class QueryContext : public Context {\n\n\tDECLARE_FAMILY_MEMBERS (QueryContext, Context);\n\n\n\n // Construction\n\n public:\n\n\tQueryContext (VTask *pCaller);\n\n\n\n // Destruction\n\n public:\n\n\t~QueryContext ();\n\n\n\n // Fulfillment\n\n public:\n\n\tbool fulfill (GoferOrder const &rOrder);\n\n\n\n // Transitions\n\n public:\n\n\tvoid onQueryInProgress (VReadEvalPrintController *pTask);\n\n\tvoid onQueryCompleted (VReadEvalPrintController *pTask);\n\n\n", "file_path": "software/src/master/src/backend/VReadEvalPrint.h", "rank": 15, "score": 335756.59455301176 }, { "content": "\tclass Use : public AbstractUse {\n\n\t DECLARE_FAMILY_MEMBERS (Use, AbstractUse);\n\n\n\n\t// Friends\n\n\t friend class VFilterDeviceImplementation;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t Use (VReferenceable *pContainer, DeviceImplementation *pDevice) : BaseClass (pContainer), m_pDevice (pDevice) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~Use () {\n\n\t }\n\n\n\n\t// Access\n\n\tpublic:\n\n\t DeviceImplementation *device () const {\n\n\t\treturn m_pDevice;\n", "file_path": "software/src/8.0/src/kernel/Vca_VFilterDeviceImplementation.h", "rank": 16, "score": 335722.2123581518 }, { "content": "\t class Use : public ManagedUse {\n\n\t\tDECLARE_FAMILY_MEMBERS (Use, ManagedUse);\n\n\n\n\t // Friends\n\n\t\tfriend class Device;\n\n\t\tfriend class DeviceManager;\n\n\n\n\t // Reference\n\n\t public:\n\n\t\ttypedef VReference<ThisClass> Reference;\n\n\n\n\t // Construction\n\n\t protected:\n\n\t\tUse (VReferenceable *pContainer, Device *pDevice) : BaseClass (pContainer), m_pDevice (pDevice) {\n\n\t\t}\n\n\n\n\t // Destruction\n\n\t protected:\n\n\t\t~Use () {\n\n\t\t}\n", "file_path": "software/src/8.0/src/kernel/Vca_VDeviceFactory.cpp", "rank": 17, "score": 335722.2123581518 }, { "content": "\t class Use : public ManagedUse {\n\n\t\tDECLARE_FAMILY_MEMBERS (Use, ManagedUse);\n\n\n\n\t // Friends\n\n\t\tfriend class Device;\n\n\t\tfriend class DeviceManager;\n\n\n\n\t // Reference\n\n\t public:\n\n\t\ttypedef VReference<ThisClass> Reference;\n\n\n\n\t // Construction\n\n\t protected:\n\n\t\tUse (VReferenceable *pContainer, Device *pDevice) : BaseClass (pContainer), m_pDevice (pDevice) {\n\n\t\t}\n\n\n\n\t // Destruction\n\n\t protected:\n\n\t\t~Use () {\n\n\t\t}\n", "file_path": "software/src/8.1/src/kernel/Vca_VDeviceFactory.cpp", "rank": 18, "score": 335722.2123581518 }, { "content": "\tclass Use : public AbstractUse {\n\n\t DECLARE_FAMILY_MEMBERS (Use, AbstractUse);\n\n\n\n\t// Friends\n\n\t friend class VFilterDeviceImplementation;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t Use (VReferenceable *pContainer, DeviceImplementation *pDevice) : BaseClass (pContainer), m_pDevice (pDevice) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~Use () {\n\n\t }\n\n\n\n\t// Access\n\n\tpublic:\n\n\t DeviceImplementation *device () const {\n\n\t\treturn m_pDevice;\n", "file_path": "software/src/8.1/src/kernel/Vca_VFilterDeviceImplementation.h", "rank": 19, "score": 335722.2123581518 }, { "content": "\t class Use : public ManagedUse {\n\n\t\tDECLARE_FAMILY_MEMBERS (Use, ManagedUse);\n\n\n\n\t // Friends\n\n\t\tfriend class Device;\n\n\t\tfriend class DeviceManager;\n\n\n\n\t // Reference\n\n\t public:\n\n\t\ttypedef VReference<ThisClass> Reference;\n\n\n\n\t // Construction\n\n\t protected:\n\n\t\tUse (VReferenceable *pContainer, Device *pDevice) : BaseClass (pContainer), m_pDevice (pDevice) {\n\n\t\t}\n\n\n\n\t // Destruction\n\n\t protected:\n\n\t\t~Use () {\n\n\t\t}\n", "file_path": "software/src/master/src/kernel/Vca_VDeviceFactory.cpp", "rank": 20, "score": 332291.5656042162 }, { "content": "\tclass Use : public AbstractUse {\n\n\t DECLARE_FAMILY_MEMBERS (Use, AbstractUse);\n\n\n\n\t// Friends\n\n\t friend class VFilterDeviceImplementation;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t Use (VReferenceable *pContainer, DeviceImplementation *pDevice) : BaseClass (pContainer), m_pDevice (pDevice) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~Use () {\n\n\t }\n\n\n\n\t// Access\n\n\tpublic:\n\n\t DeviceImplementation *device () const {\n\n\t\treturn m_pDevice;\n", "file_path": "software/src/master/src/kernel/Vca_VFilterDeviceImplementation.h", "rank": 21, "score": 332291.5656042162 }, { "content": "\t class AcceptUse : public SocketUse_<Use> {\n\n\t\tDECLARE_FAMILY_MEMBERS (AcceptUse, SocketUse_<Use>);\n\n\n\n\t // Friends\n\n\t\tfriend class SocketDevice;\n\n\n\n\t // Aliases\n\n\t public:\n\n#pragma __pointer_size __save\n\n#pragma __pointer_size __short\n\n\t\ttypedef XIOSB *xiosb_ptr32_t;\n\n\t\ttypedef _ile3 &ile3_ref32_t;\n\n\t\ttypedef Handle &handle_ref32_t;\n\n\t\ttypedef MultiStackAddress *multistackaddress_ptr32_t;\n\n#pragma __pointer_size __restore\n\n\n\n\t // Stuff\n\n\t public:\n\n\t\tstruct Stuff {\n\n\t\t MultiStackAddress\tm_iPeerAddress;\n", "file_path": "software/src/8.0/src/kernel/Vca_VDeviceFactory.cpp", "rank": 22, "score": 327106.2462701965 }, { "content": "\t class AcceptUse : public SocketUse_<Use> {\n\n\t\tDECLARE_FAMILY_MEMBERS (AcceptUse, SocketUse_<Use>);\n\n\n\n\t // Friends\n\n\t\tfriend class SocketDevice;\n\n\n\n\t // Aliases\n\n\t public:\n\n#pragma __pointer_size __save\n\n#pragma __pointer_size __short\n\n\t\ttypedef XIOSB *xiosb_ptr32_t;\n\n\t\ttypedef _ile3 &ile3_ref32_t;\n\n\t\ttypedef Handle &handle_ref32_t;\n\n\t\ttypedef MultiStackAddress *multistackaddress_ptr32_t;\n\n#pragma __pointer_size __restore\n\n\n\n\t // Stuff\n\n\t public:\n\n\t\tstruct Stuff {\n\n\t\t MultiStackAddress\tm_iPeerAddress;\n", "file_path": "software/src/8.1/src/kernel/Vca_VDeviceFactory.cpp", "rank": 23, "score": 327106.2462701965 }, { "content": " class Context : public VTransient {\n\n\tDECLARE_FAMILY_MEMBERS (Context, VTransient);\n\n\n\n // Control Points Class\n\n public:\n", "file_path": "software/src/8.0/src/backend/VComputationUnit.h", "rank": 24, "score": 325790.1451307033 }, { "content": "\t // Use\n\n class Vca_API BSUse : public Use {\n\n DECLARE_ABSTRACT_RTTLITE (BSUse, Use);\n\n\n\n\t\t// User Reference\n\n\t\tpublic:\n\n\t\t typedef VReference<BSMover> UserRef;\n\n\n\n\t // Construction\n\n\t protected:\n\n\t BSUse () {\n\n\t }\n\n\n\n\t // Destruction\n\n\t protected:\n\n\t ~BSUse () {\n\n\t }\n\n\n\n\t\t// Execution\n\n protected:\n\n\t\t void onUser (BSMover *pUser) {\n", "file_path": "software/src/8.0/src/kernel/Vca_VDevice.h", "rank": 25, "score": 325083.87958441087 }, { "content": "\t // Use\n\n class Vca_API BSUse : public Use {\n\n DECLARE_ABSTRACT_RTTLITE (BSUse, Use);\n\n\n\n\t\t// User Reference\n\n\t\tpublic:\n\n\t\t typedef VReference<BSMover> UserRef;\n\n\n\n\t // Construction\n\n\t protected:\n\n\t BSUse () {\n\n\t }\n\n\n\n\t // Destruction\n\n\t protected:\n\n\t ~BSUse () {\n\n\t }\n\n\n\n\t\t// Execution\n\n protected:\n\n\t\t void onUser (BSMover *pUser) {\n", "file_path": "software/src/8.1/src/kernel/Vca_VDevice.h", "rank": 26, "score": 325083.87958441087 }, { "content": "\tclass UserName : public VInstanceSource<VString const&> {\n\n\t DECLARE_FAMILY_MEMBERS (UserName, VInstanceSource<VString const&>);\n\n\tpublic:\n\n\t UserName ();\n\n\t ~UserName ();\n\n\tprivate:\n\n\t virtual void onValueNeeded ();\n\n\t virtual void onUserNameNeeded_() = 0;\n\n\t};\n\n\n\n\t/*--------------------*\n\n\t *---- GroupName ----*\n\n\t *--------------------*/\n", "file_path": "software/src/8.1/src/kernel/Vca_VSiteInfo.h", "rank": 27, "score": 324719.9214058442 }, { "content": "\tclass GroupName : public VInstanceSource<VString const&> {\n\n\t DECLARE_FAMILY_MEMBERS (GroupName, VInstanceSource<VString const&>);\n\n\tpublic:\n\n\t GroupName ();\n\n\t ~GroupName ();\n\n\tprivate:\n\n\t virtual void onValueNeeded ();\n\n\t virtual void onGroupNameNeeded_() = 0;\n\n\t};\n\n }\n\n\n\n/*****************************\n\n *---- class VSiteInfo ----*\n\n *****************************/\n", "file_path": "software/src/8.0/src/kernel/Vca_VSiteInfo.h", "rank": 28, "score": 324719.9214058442 }, { "content": "\tclass GroupName : public VInstanceSource<VString const&> {\n\n\t DECLARE_FAMILY_MEMBERS (GroupName, VInstanceSource<VString const&>);\n\n\tpublic:\n\n\t GroupName ();\n\n\t ~GroupName ();\n\n\tprivate:\n\n\t virtual void onValueNeeded ();\n\n\t virtual void onGroupNameNeeded_() = 0;\n\n\t};\n\n }\n\n\n\n/*****************************\n\n *---- class VSiteInfo ----*\n\n *****************************/\n", "file_path": "software/src/8.1/src/kernel/Vca_VSiteInfo.h", "rank": 29, "score": 324719.9214058442 }, { "content": "\tclass UserName : public VInstanceSource<VString const&> {\n\n\t DECLARE_FAMILY_MEMBERS (UserName, VInstanceSource<VString const&>);\n\n\tpublic:\n\n\t UserName ();\n\n\t ~UserName ();\n\n\tprivate:\n\n\t virtual void onValueNeeded ();\n\n\t virtual void onUserNameNeeded_() = 0;\n\n\t};\n\n\n\n\t/*--------------------*\n\n\t *---- GroupName ----*\n\n\t *--------------------*/\n", "file_path": "software/src/8.0/src/kernel/Vca_VSiteInfo.h", "rank": 30, "score": 324719.9214058442 }, { "content": "\tclass HostName : public VInstanceSource<VString const&> {\n\n\t DECLARE_FAMILY_MEMBERS (HostName, VInstanceSource<VString const&>);\n\n\tpublic:\n\n\t HostName ();\n\n\t ~HostName ();\n\n\tprivate:\n\n\t virtual void onValueNeeded ();\n\n\t virtual void onHostNameNeeded_() = 0;\n\n\t};\n\n\n\n\t/*-------------------*\n\n\t *---- UserName ----*\n\n\t *-------------------*/\n", "file_path": "software/src/8.0/src/kernel/Vca_VSiteInfo.h", "rank": 31, "score": 324719.9214058442 }, { "content": "\tclass HostName : public VInstanceSource<VString const&> {\n\n\t DECLARE_FAMILY_MEMBERS (HostName, VInstanceSource<VString const&>);\n\n\tpublic:\n\n\t HostName ();\n\n\t ~HostName ();\n\n\tprivate:\n\n\t virtual void onValueNeeded ();\n\n\t virtual void onHostNameNeeded_() = 0;\n\n\t};\n\n\n\n\t/*-------------------*\n\n\t *---- UserName ----*\n\n\t *-------------------*/\n", "file_path": "software/src/8.1/src/kernel/Vca_VSiteInfo.h", "rank": 32, "score": 324719.9214058442 }, { "content": "\t class AcceptUse : public SocketUse_<Use> {\n\n\t\tDECLARE_FAMILY_MEMBERS (AcceptUse, SocketUse_<Use>);\n\n\n\n\t // Friends\n\n\t\tfriend class SocketDevice;\n\n\n\n\t // Aliases\n\n\t public:\n\n#pragma __pointer_size __save\n\n#pragma __pointer_size __short\n\n\t\ttypedef XIOSB *xiosb_ptr32_t;\n\n\t\ttypedef _ile3 &ile3_ref32_t;\n\n\t\ttypedef Handle &handle_ref32_t;\n\n\t\ttypedef MultiStackAddress *multistackaddress_ptr32_t;\n\n#pragma __pointer_size __restore\n\n\n\n\t // Stuff\n\n\t public:\n\n\t\tstruct Stuff {\n\n\t\t MultiStackAddress\tm_iPeerAddress;\n", "file_path": "software/src/master/src/kernel/Vca_VDeviceFactory.cpp", "rank": 33, "score": 324073.1123069366 }, { "content": "\tclass BSGet : public Use {\n\n\t DECLARE_FAMILY_MEMBERS (BSGet, Use);\n\n\n\n\t// Friends\n\n\t friend class VSSHDeviceImplementation;\n\n\n\n\t// Reference\n\n\tpublic:\n\n\t typedef VReference<ThisClass> Reference;\n\n\n\n\t// Area\n\n\tpublic:\n\n\t typedef VDeviceBSReadArea Area;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t BSGet (\n\n\t\tVReferenceable *pContainer, VSSHDeviceImplementation *pDevice\n\n\t ) : BaseClass (pContainer, pDevice) {\n\n\t }\n", "file_path": "software/src/8.0/src/kernel/Vca_VSSHDeviceImplementation.h", "rank": 34, "score": 321818.25072884106 }, { "content": "\tclass BSPut : public Use {\n\n\t DECLARE_FAMILY_MEMBERS (BSPut, Use);\n\n\n\n\t friend class VFDIODeviceImplementation;\n\n\n\n\t// Area\n\n\tpublic:\n\n\t typedef VDeviceBSWriteArea Area;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t BSPut (\n\n\t\tVReferenceable *pContainer, VFDIODeviceImplementation *pDevice\n\n\t ) : BaseClass (pContainer, pDevice) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~BSPut () {\n\n\t }\n", "file_path": "software/src/8.0/src/kernel/Vca_VFDIODeviceImplementation.h", "rank": 35, "score": 321818.25072884106 }, { "content": "\tclass BSPut : public Use {\n\n\t DECLARE_FAMILY_MEMBERS (BSPut, Use);\n\n\n\n\t// Friends\n\n\t friend class VSSHDeviceImplementation;\n\n\n\n\t// Reference\n\n\tpublic:\n\n\t typedef VReference<ThisClass> Reference;\n\n\n\n\t// Area\n\n\tpublic:\n\n\t typedef VDeviceBSWriteArea Area;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t BSPut (\n\n\t\tVReferenceable *pContainer, VSSHDeviceImplementation *pDevice\n\n\t ) : BaseClass (pContainer, pDevice) {\n\n\t }\n", "file_path": "software/src/8.0/src/kernel/Vca_VSSHDeviceImplementation.h", "rank": 36, "score": 321818.25072884106 }, { "content": "\t class Accept : public Use {\n\n\t\tDECLARE_FAMILY_MEMBERS (Accept, Use);\n\n\n\n\t // Construction\n\n\t protected:\n\n\t\tAccept (VReferenceable *pContainer, Device *pDevice) : BaseClass (pContainer, pDevice) {\n\n\t\t}\n\n\n\n\t // Destruction\n\n\t protected:\n\n\t\t~Accept () {\n\n\t\t}\n\n\n\n\t // Start\n\n\t public:\n\n\t\tbool start (VkStatus &rStatus) {\n\n\t\t m_pDevice->incrementUseCount ();\n\n\t\t return attempt (rStatus);\n\n\t\t}\n\n\n", "file_path": "software/src/8.1/src/kernel/Vca_VDeviceFactory.cpp", "rank": 37, "score": 321818.25072884106 }, { "content": "\tclass BSPut : public Use {\n\n\t DECLARE_FAMILY_MEMBERS (BSPut, Use);\n\n\n\n\t friend class VFDIODeviceImplementation;\n\n\n\n\t// Area\n\n\tpublic:\n\n\t typedef VDeviceBSWriteArea Area;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t BSPut (\n\n\t\tVReferenceable *pContainer, VFDIODeviceImplementation *pDevice\n\n\t ) : BaseClass (pContainer, pDevice) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~BSPut () {\n\n\t }\n", "file_path": "software/src/8.1/src/kernel/Vca_VFDIODeviceImplementation.h", "rank": 38, "score": 321818.25072884106 }, { "content": "\tclass BSPut : public Use {\n\n\t DECLARE_FAMILY_MEMBERS (BSPut, Use);\n\n\n\n\t// Friends\n\n\t friend class VSSHDeviceImplementation;\n\n\n\n\t// Reference\n\n\tpublic:\n\n\t typedef VReference<ThisClass> Reference;\n\n\n\n\t// Area\n\n\tpublic:\n\n\t typedef VDeviceBSWriteArea Area;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t BSPut (\n\n\t\tVReferenceable *pContainer, VSSHDeviceImplementation *pDevice\n\n\t ) : BaseClass (pContainer, pDevice) {\n\n\t }\n", "file_path": "software/src/8.1/src/kernel/Vca_VSSHDeviceImplementation.h", "rank": 39, "score": 321818.25072884106 }, { "content": "\tclass BSGet : public Use {\n\n\t DECLARE_FAMILY_MEMBERS (BSGet, Use);\n\n\n\n\t friend class VFDIODeviceImplementation;\n\n\n\n\t// Area\n\n\tpublic:\n\n\t typedef VDeviceBSReadArea Area;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t BSGet (\n\n\t\tVReferenceable *pContainer, VFDIODeviceImplementation *pDevice\n\n\t ) : BaseClass (pContainer, pDevice) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~BSGet () {\n\n\t }\n", "file_path": "software/src/8.0/src/kernel/Vca_VFDIODeviceImplementation.h", "rank": 40, "score": 321818.25072884106 }, { "content": "\t class Accept : public Use {\n\n\t\tDECLARE_FAMILY_MEMBERS (Accept, Use);\n\n\n\n\t // Construction\n\n\t protected:\n\n\t\tAccept (VReferenceable *pContainer, Device *pDevice) : BaseClass (pContainer, pDevice) {\n\n\t\t}\n\n\n\n\t // Destruction\n\n\t protected:\n\n\t\t~Accept () {\n\n\t\t}\n\n\n\n\t // Start\n\n\t public:\n\n\t\tbool start (VkStatus &rStatus) {\n\n\t\t m_pDevice->incrementUseCount ();\n\n\t\t return attempt (rStatus);\n\n\t\t}\n\n\n", "file_path": "software/src/8.0/src/kernel/Vca_VDeviceFactory.cpp", "rank": 41, "score": 321818.25072884106 }, { "content": "\tclass BSGet : public Use {\n\n\t DECLARE_FAMILY_MEMBERS (BSGet, Use);\n\n\n\n\t// Friends\n\n\t friend class VSSHDeviceImplementation;\n\n\n\n\t// Reference\n\n\tpublic:\n\n\t typedef VReference<ThisClass> Reference;\n\n\n\n\t// Area\n\n\tpublic:\n\n\t typedef VDeviceBSReadArea Area;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t BSGet (\n\n\t\tVReferenceable *pContainer, VSSHDeviceImplementation *pDevice\n\n\t ) : BaseClass (pContainer, pDevice) {\n\n\t }\n", "file_path": "software/src/8.1/src/kernel/Vca_VSSHDeviceImplementation.h", "rank": 42, "score": 321818.25072884106 }, { "content": "\tclass BSGet : public Use {\n\n\t DECLARE_FAMILY_MEMBERS (BSGet, Use);\n\n\n\n\t friend class VFDIODeviceImplementation;\n\n\n\n\t// Area\n\n\tpublic:\n\n\t typedef VDeviceBSReadArea Area;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t BSGet (\n\n\t\tVReferenceable *pContainer, VFDIODeviceImplementation *pDevice\n\n\t ) : BaseClass (pContainer, pDevice) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~BSGet () {\n\n\t }\n", "file_path": "software/src/8.1/src/kernel/Vca_VFDIODeviceImplementation.h", "rank": 43, "score": 321818.25072884106 }, { "content": "\t // Use\n\n class Vca_API BSUse : public Use {\n\n DECLARE_ABSTRACT_RTTLITE (BSUse, Use);\n\n\n\n\t\t// User Reference\n\n\t\tpublic:\n\n\t\t typedef VReference<BSMover> UserRef;\n\n\n\n\t // Construction\n\n\t protected:\n\n\t BSUse () {\n\n\t }\n\n\n\n\t // Destruction\n\n\t protected:\n\n\t ~BSUse () {\n\n\t }\n\n\n\n\t\t// Execution\n\n protected:\n\n\t\t void onUser (BSMover *pUser) {\n", "file_path": "software/src/master/src/kernel/Vca_VDevice.h", "rank": 44, "score": 321653.23283047526 }, { "content": "\tclass HostName : public VInstanceSource<VString const&> {\n\n\t DECLARE_FAMILY_MEMBERS (HostName, VInstanceSource<VString const&>);\n\n\tpublic:\n\n\t HostName ();\n\n\t ~HostName ();\n\n\tprivate:\n\n\t virtual void onValueNeeded ();\n\n\t virtual void onHostNameNeeded_() = 0;\n\n\t};\n\n\n\n\t/*-------------------*\n\n\t *---- UserName ----*\n\n\t *-------------------*/\n", "file_path": "software/src/master/src/kernel/Vca_VSiteInfo.h", "rank": 45, "score": 321611.89280439913 }, { "content": "\tclass UserName : public VInstanceSource<VString const&> {\n\n\t DECLARE_FAMILY_MEMBERS (UserName, VInstanceSource<VString const&>);\n\n\tpublic:\n\n\t UserName ();\n\n\t ~UserName ();\n\n\tprivate:\n\n\t virtual void onValueNeeded ();\n\n\t virtual void onUserNameNeeded_() = 0;\n\n\t};\n\n\n\n\t/*--------------------*\n\n\t *---- GroupName ----*\n\n\t *--------------------*/\n", "file_path": "software/src/master/src/kernel/Vca_VSiteInfo.h", "rank": 46, "score": 321611.89280439913 }, { "content": "\tclass GroupName : public VInstanceSource<VString const&> {\n\n\t DECLARE_FAMILY_MEMBERS (GroupName, VInstanceSource<VString const&>);\n\n\tpublic:\n\n\t GroupName ();\n\n\t ~GroupName ();\n\n\tprivate:\n\n\t virtual void onValueNeeded ();\n\n\t virtual void onGroupNameNeeded_() = 0;\n\n\t};\n\n }\n\n\n\n/*****************************\n\n *---- class VSiteInfo ----*\n\n *****************************/\n", "file_path": "software/src/master/src/kernel/Vca_VSiteInfo.h", "rank": 47, "score": 321611.89280439913 }, { "content": "\tclass Use : public VDeviceImplementation::AbstractUse {\n\n\t DECLARE_FAMILY_MEMBERS (Use, VDeviceImplementation::AbstractUse);\n\n\n\n\t// Friends\n\n\t friend class VFDIODeviceImplementation;\n\n\n\n\t// Reference\n\n\tpublic:\n\n\t typedef VReference<ThisClass> Reference;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t Use (\n\n\t\tVReferenceable *pContainer, VFDIODeviceImplementation *pDevice\n\n\t ) : BaseClass (pContainer), m_pDevice (pDevice) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~Use () {\n", "file_path": "software/src/8.1/src/kernel/Vca_VFDIODeviceImplementation.h", "rank": 48, "score": 318334.46091674385 }, { "content": "\tclass Use : public VDeviceImplementation::AbstractUse {\n\n\t DECLARE_FAMILY_MEMBERS (Use, VDeviceImplementation::AbstractUse);\n\n\n\n\t// Friends\n\n\t friend class VSSHDeviceImplementation;\n\n\n\n\t// Reference\n\n\tpublic:\n\n\t typedef VReference<ThisClass> Reference;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t Use (\n\n\t\tVReferenceable *pContainer, VSSHDeviceImplementation *pDevice\n\n\t ) : BaseClass (pContainer), m_pDevice (pDevice), m_xSubStreamID (0), m_iIndex (g_iIndexNext++) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~Use () {\n", "file_path": "software/src/8.1/src/kernel/Vca_VSSHDeviceImplementation.h", "rank": 49, "score": 318334.46091674385 }, { "content": "\tclass Use : public VDeviceImplementation::AbstractUse {\n\n\t DECLARE_FAMILY_MEMBERS (Use, VDeviceImplementation::AbstractUse);\n\n\n\n\t// Friends\n\n\t friend class VFDIODeviceImplementation;\n\n\n\n\t// Reference\n\n\tpublic:\n\n\t typedef VReference<ThisClass> Reference;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t Use (\n\n\t\tVReferenceable *pContainer, VFDIODeviceImplementation *pDevice\n\n\t ) : BaseClass (pContainer), m_pDevice (pDevice) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~Use () {\n", "file_path": "software/src/8.0/src/kernel/Vca_VFDIODeviceImplementation.h", "rank": 50, "score": 318334.46091674385 }, { "content": "\tclass Use : public VDeviceImplementation::AbstractUse {\n\n\t DECLARE_FAMILY_MEMBERS (Use, VDeviceImplementation::AbstractUse);\n\n\n\n\t// Friends\n\n\t friend class VSSHDeviceImplementation;\n\n\n\n\t// Reference\n\n\tpublic:\n\n\t typedef VReference<ThisClass> Reference;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t Use (\n\n\t\tVReferenceable *pContainer, VSSHDeviceImplementation *pDevice\n\n\t ) : BaseClass (pContainer), m_pDevice (pDevice), m_xSubStreamID (0), m_iIndex (g_iIndexNext++) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~Use () {\n", "file_path": "software/src/8.0/src/kernel/Vca_VSSHDeviceImplementation.h", "rank": 51, "score": 318334.46091674385 }, { "content": "\tclass BSGet : public Use {\n\n\t DECLARE_FAMILY_MEMBERS (BSGet, Use);\n\n\n\n\t friend class VLoopbackDeviceImplementation;\n\n\n\n\t// Area\n\n\tpublic:\n\n\t typedef VDeviceBSReadArea Area;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t BSGet (\n\n\t\tVReferenceable *pContainer, VLoopbackDeviceImplementation *pDevice\n\n\t ) : BaseClass (pContainer, pDevice) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~BSGet () {\n\n\t }\n", "file_path": "software/src/8.1/src/kernel/Vca_VLoopbackDeviceImplementation.h", "rank": 52, "score": 318040.2870686678 }, { "content": "\tclass BSPut : public Use {\n\n\t DECLARE_FAMILY_MEMBERS (BSPut, Use);\n\n\n\n\t friend class VFDIODeviceImplementation;\n\n\n\n\t// Area\n\n\tpublic:\n\n\t typedef VDeviceBSWriteArea Area;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t BSPut (\n\n\t\tVReferenceable *pContainer, VFDIODeviceImplementation *pDevice\n\n\t ) : BaseClass (pContainer, pDevice) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~BSPut () {\n\n\t }\n", "file_path": "software/src/master/src/kernel/Vca_VFDIODeviceImplementation.h", "rank": 53, "score": 318040.2870686678 }, { "content": "\tclass BSPut : public Use {\n\n\t DECLARE_FAMILY_MEMBERS (BSPut, Use);\n\n\n\n\t// Friends\n\n\t friend class VSSHDeviceImplementation;\n\n\n\n\t// Reference\n\n\tpublic:\n\n\t typedef VReference<ThisClass> Reference;\n\n\n\n\t// Area\n\n\tpublic:\n\n\t typedef VDeviceBSWriteArea Area;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t BSPut (\n\n\t\tVReferenceable *pContainer, VSSHDeviceImplementation *pDevice\n\n\t ) : BaseClass (pContainer, pDevice) {\n\n\t }\n", "file_path": "software/src/master/src/kernel/Vca_VSSHDeviceImplementation.h", "rank": 54, "score": 318040.2870686678 }, { "content": "\t class ReadPoll : public Use {\n\n\t\tDECLARE_FAMILY_MEMBERS (ReadPoll, Use);\n\n\n\n\t // Construction\n\n\t protected:\n\n\t\tReadPoll (VReferenceable *pContainer, Device *pDevice) : BaseClass (pContainer, pDevice) {\n\n\t\t}\n\n\n\n\t // Destruction\n\n\t protected:\n\n\t\t~ReadPoll () {\n\n\t\t}\n\n\n\n\t // Start\n\n\t public:\n\n\t\tbool start (VkStatus &rStatus) {\n\n\t\t m_pDevice->incrementUseCount ();\n\n\t\t return attempt (rStatus);\n\n\t\t}\n\n\n", "file_path": "software/src/8.0/src/kernel/Vca_VDeviceFactory.cpp", "rank": 55, "score": 318040.2870686678 }, { "content": "\t class BSGet : public Use {\n\n\t\tDECLARE_FAMILY_MEMBERS (BSGet, Use);\n\n\n\n\t // Construction\n\n\t protected:\n\n\t\tBSGet (VReferenceable *pContainer, Device *pDevice) : BaseClass (pContainer, pDevice) {\n\n\t\t}\n\n\n\n\t // Destruction\n\n\t protected:\n\n\t\t~BSGet () {\n\n\t\t}\n\n\n\n\t // Start\n\n\t public:\n\n\t\tbool start (VkStatus &rStatus, BSReadArea const &rArea) {\n\n\t\t m_iArea.setTo (rArea);\n\n\t\t m_pDevice->incrementUseCount ();\n\n\t\t return attempt (rStatus);\n\n\t\t}\n", "file_path": "software/src/8.0/src/kernel/Vca_VDeviceFactory.cpp", "rank": 56, "score": 318040.2870686678 }, { "content": "\t class BSMove : public Use {\n\n\t\tDECLARE_FAMILY_MEMBERS (BSMove, Use);\n\n\n\n\t\tfriend class Device;\n\n\n\n\t // Construction\n\n\t protected:\n\n\t\tBSMove (VReferenceable *pContainer, Device *pDevice) : BaseClass (pContainer, pDevice) {\n\n\t\t}\n\n\n\n\t // Destruction\n\n\t protected:\n\n\t\t~BSMove () {\n\n\t\t}\n\n\n\n\t // Access\n\n\t public:\n\n\t\tXIOSB *iosb (bool bIn32BitMemory) {\n\n\t\t return bIn32BitMemory ? m_pStuff32 : &m_iIOSB;\n\n\t\t}\n", "file_path": "software/src/8.1/src/kernel/Vca_VDeviceFactory.cpp", "rank": 57, "score": 318040.2870686678 }, { "content": "\t class BSMove : public Use {\n\n\t\tDECLARE_FAMILY_MEMBERS (BSMove, Use);\n\n\n\n\t\tfriend class Device;\n\n\n\n\t // Construction\n\n\t protected:\n\n\t\tBSMove (VReferenceable *pContainer, Device *pDevice) : BaseClass (pContainer, pDevice) {\n\n\t\t}\n\n\n\n\t // Destruction\n\n\t protected:\n\n\t\t~BSMove () {\n\n\t\t}\n\n\n\n\t // Access\n\n\t public:\n\n\t\tXIOSB *iosb (bool bIn32BitMemory) {\n\n\t\t return bIn32BitMemory ? m_pStuff32 : &m_iIOSB;\n\n\t\t}\n", "file_path": "software/src/8.0/src/kernel/Vca_VDeviceFactory.cpp", "rank": 58, "score": 318040.2870686678 }, { "content": "\t class WritePoll : public Use {\n\n\t\tDECLARE_FAMILY_MEMBERS (WritePoll, Use);\n\n\n\n\t // Construction\n\n\t protected:\n\n\t\tWritePoll (VReferenceable *pContainer, Device *pDevice) : BaseClass (pContainer, pDevice) {\n\n\t\t}\n\n\n\n\t // Destruction\n\n\t protected:\n\n\t\t~WritePoll () {\n\n\t\t}\n\n\n\n\t // Start\n\n\t public:\n\n\t\tbool start (VkStatus &rStatus) {\n\n\t\t m_pDevice->incrementUseCount ();\n\n\t\t return attempt (rStatus);\n\n\t\t}\n\n\n", "file_path": "software/src/8.0/src/kernel/Vca_VDeviceFactory.cpp", "rank": 59, "score": 318040.2870686678 }, { "content": "\tclass BSGet : public Use {\n\n\t DECLARE_FAMILY_MEMBERS (BSGet, Use);\n\n\n\n\t friend class VLoopbackDeviceImplementation;\n\n\n\n\t// Area\n\n\tpublic:\n\n\t typedef VDeviceBSReadArea Area;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t BSGet (\n\n\t\tVReferenceable *pContainer, VLoopbackDeviceImplementation *pDevice\n\n\t ) : BaseClass (pContainer, pDevice) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~BSGet () {\n\n\t }\n", "file_path": "software/src/8.0/src/kernel/Vca_VLoopbackDeviceImplementation.h", "rank": 60, "score": 318040.2870686678 }, { "content": "\tclass BSGet : public Use {\n\n\t DECLARE_FAMILY_MEMBERS (BSGet, Use);\n\n\n\n\t friend class VNullDeviceImplementation;\n\n\n\n\t// Area\n\n\tpublic:\n\n\t typedef VDeviceBSReadArea Area;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t BSGet (VReferenceable *pContainer, VNullDeviceImplementation *pDevice) : BaseClass (pContainer, pDevice) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~BSGet () {\n\n\t }\n\n\n\n\t// Startup\n", "file_path": "software/src/8.1/src/kernel/Vca_VNullDeviceImplementation.h", "rank": 61, "score": 318040.2870686678 }, { "content": "\tclass BSGet : public Use {\n\n\t DECLARE_FAMILY_MEMBERS (BSGet, Use);\n\n\n\n\t friend class VNullDeviceImplementation;\n\n\n\n\t// Area\n\n\tpublic:\n\n\t typedef VDeviceBSReadArea Area;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t BSGet (VReferenceable *pContainer, VNullDeviceImplementation *pDevice) : BaseClass (pContainer, pDevice) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~BSGet () {\n\n\t }\n\n\n\n\t// Startup\n", "file_path": "software/src/8.0/src/kernel/Vca_VNullDeviceImplementation.h", "rank": 62, "score": 318040.2870686678 }, { "content": "\tclass BSGet : public Use {\n\n\t DECLARE_FAMILY_MEMBERS (BSGet, Use);\n\n\n\n\t friend class VFDIODeviceImplementation;\n\n\n\n\t// Area\n\n\tpublic:\n\n\t typedef VDeviceBSReadArea Area;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t BSGet (\n\n\t\tVReferenceable *pContainer, VFDIODeviceImplementation *pDevice\n\n\t ) : BaseClass (pContainer, pDevice) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~BSGet () {\n\n\t }\n", "file_path": "software/src/master/src/kernel/Vca_VFDIODeviceImplementation.h", "rank": 63, "score": 318040.2870686678 }, { "content": "\tclass BSPut : public Use {\n\n\t DECLARE_FAMILY_MEMBERS (BSPut, Use);\n\n\n\n\t friend class VNullDeviceImplementation;\n\n\n\n\t// Area\n\n\tpublic:\n\n\t typedef VDeviceBSWriteArea Area;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t BSPut (VReferenceable *pContainer, VNullDeviceImplementation *pDevice) : BaseClass (pContainer, pDevice) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~BSPut () {\n\n\t }\n\n\n\n\t// Startup\n", "file_path": "software/src/8.0/src/kernel/Vca_VNullDeviceImplementation.h", "rank": 64, "score": 318040.2870686678 }, { "content": "\tclass BSPut : public Use {\n\n\t DECLARE_FAMILY_MEMBERS (BSPut, Use);\n\n\n\n\t friend class VNullDeviceImplementation;\n\n\n\n\t// Area\n\n\tpublic:\n\n\t typedef VDeviceBSWriteArea Area;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t BSPut (VReferenceable *pContainer, VNullDeviceImplementation *pDevice) : BaseClass (pContainer, pDevice) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~BSPut () {\n\n\t }\n\n\n\n\t// Startup\n", "file_path": "software/src/8.1/src/kernel/Vca_VNullDeviceImplementation.h", "rank": 65, "score": 318040.2870686678 }, { "content": "\tclass BSPut : public Use {\n\n\t DECLARE_FAMILY_MEMBERS (BSPut, Use);\n\n\n\n\t friend class VLoopbackDeviceImplementation;\n\n\n\n\t// Area\n\n\tpublic:\n\n\t typedef VDeviceBSWriteArea Area;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t BSPut (\n\n\t\tVReferenceable *pContainer, VLoopbackDeviceImplementation *pDevice\n\n\t ) : BaseClass (pContainer, pDevice) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~BSPut () {\n\n\t }\n", "file_path": "software/src/8.0/src/kernel/Vca_VLoopbackDeviceImplementation.h", "rank": 66, "score": 318040.2870686678 }, { "content": "\t class WritePoll : public Use {\n\n\t\tDECLARE_FAMILY_MEMBERS (WritePoll, Use);\n\n\n\n\t // Construction\n\n\t protected:\n\n\t\tWritePoll (VReferenceable *pContainer, Device *pDevice) : BaseClass (pContainer, pDevice) {\n\n\t\t}\n\n\n\n\t // Destruction\n\n\t protected:\n\n\t\t~WritePoll () {\n\n\t\t}\n\n\n\n\t // Start\n\n\t public:\n\n\t\tbool start (VkStatus &rStatus) {\n\n\t\t m_pDevice->incrementUseCount ();\n\n\t\t return attempt (rStatus);\n\n\t\t}\n\n\n", "file_path": "software/src/8.1/src/kernel/Vca_VDeviceFactory.cpp", "rank": 67, "score": 318040.2870686678 }, { "content": "\t class BSGet : public Use {\n\n\t\tDECLARE_FAMILY_MEMBERS (BSGet, Use);\n\n\n\n\t // Construction\n\n\t protected:\n\n\t\tBSGet (VReferenceable *pContainer, Device *pDevice) : BaseClass (pContainer, pDevice) {\n\n\t\t}\n\n\n\n\t // Destruction\n\n\t protected:\n\n\t\t~BSGet () {\n\n\t\t}\n\n\n\n\t // Start\n\n\t public:\n\n\t\tbool start (VkStatus &rStatus, BSReadArea const &rArea) {\n\n\t\t m_iArea.setTo (rArea);\n\n\t\t m_pDevice->incrementUseCount ();\n\n\t\t return attempt (rStatus);\n\n\t\t}\n", "file_path": "software/src/8.1/src/kernel/Vca_VDeviceFactory.cpp", "rank": 68, "score": 318040.2870686678 }, { "content": "\tclass BSGet : public Use {\n\n\t DECLARE_FAMILY_MEMBERS (BSGet, Use);\n\n\n\n\t// Friends\n\n\t friend class VSSHDeviceImplementation;\n\n\n\n\t// Reference\n\n\tpublic:\n\n\t typedef VReference<ThisClass> Reference;\n\n\n\n\t// Area\n\n\tpublic:\n\n\t typedef VDeviceBSReadArea Area;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t BSGet (\n\n\t\tVReferenceable *pContainer, VSSHDeviceImplementation *pDevice\n\n\t ) : BaseClass (pContainer, pDevice) {\n\n\t }\n", "file_path": "software/src/master/src/kernel/Vca_VSSHDeviceImplementation.h", "rank": 69, "score": 318040.2870686678 }, { "content": "\tclass BSPut : public Use {\n\n\t DECLARE_FAMILY_MEMBERS (BSPut, Use);\n\n\n\n\t friend class VLoopbackDeviceImplementation;\n\n\n\n\t// Area\n\n\tpublic:\n\n\t typedef VDeviceBSWriteArea Area;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t BSPut (\n\n\t\tVReferenceable *pContainer, VLoopbackDeviceImplementation *pDevice\n\n\t ) : BaseClass (pContainer, pDevice) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~BSPut () {\n\n\t }\n", "file_path": "software/src/8.1/src/kernel/Vca_VLoopbackDeviceImplementation.h", "rank": 70, "score": 318040.2870686678 }, { "content": "\t class BSPut : public Use {\n\n\t\tDECLARE_FAMILY_MEMBERS (BSPut, Use);\n\n\n\n\t // Construction\n\n\t protected:\n\n\t\tBSPut (VReferenceable *pContainer, Device *pDevice) : BaseClass (pContainer, pDevice) {\n\n\t\t}\n\n\n\n\t // Destruction\n\n\t protected:\n\n\t\t~BSPut () {\n\n\t\t}\n\n\n\n\t // Start\n\n\t public:\n\n\t\tbool start (VkStatus &rStatus, BSWriteArea const &rArea) {\n\n\t\t m_iArea.setTo (rArea);\n\n\t\t m_pDevice->incrementUseCount ();\n\n\t\t return attempt (rStatus);\n\n\t\t}\n", "file_path": "software/src/8.0/src/kernel/Vca_VDeviceFactory.cpp", "rank": 71, "score": 318040.2870686678 }, { "content": "\t class ReadPoll : public Use {\n\n\t\tDECLARE_FAMILY_MEMBERS (ReadPoll, Use);\n\n\n\n\t // Construction\n\n\t protected:\n\n\t\tReadPoll (VReferenceable *pContainer, Device *pDevice) : BaseClass (pContainer, pDevice) {\n\n\t\t}\n\n\n\n\t // Destruction\n\n\t protected:\n\n\t\t~ReadPoll () {\n\n\t\t}\n\n\n\n\t // Start\n\n\t public:\n\n\t\tbool start (VkStatus &rStatus) {\n\n\t\t m_pDevice->incrementUseCount ();\n\n\t\t return attempt (rStatus);\n\n\t\t}\n\n\n", "file_path": "software/src/8.1/src/kernel/Vca_VDeviceFactory.cpp", "rank": 72, "score": 318040.2870686678 }, { "content": "\t class Accept : public Use {\n\n\t\tDECLARE_FAMILY_MEMBERS (Accept, Use);\n\n\n\n\t // Construction\n\n\t protected:\n\n\t\tAccept (VReferenceable *pContainer, Device *pDevice) : BaseClass (pContainer, pDevice) {\n\n\t\t}\n\n\n\n\t // Destruction\n\n\t protected:\n\n\t\t~Accept () {\n\n\t\t}\n\n\n\n\t // Start\n\n\t public:\n\n\t\tbool start (VkStatus &rStatus) {\n\n\t\t m_pDevice->incrementUseCount ();\n\n\t\t return attempt (rStatus);\n\n\t\t}\n\n\n", "file_path": "software/src/master/src/kernel/Vca_VDeviceFactory.cpp", "rank": 73, "score": 318040.2870686678 }, { "content": "\t class BSPut : public Use {\n\n\t\tDECLARE_FAMILY_MEMBERS (BSPut, Use);\n\n\n\n\t // Construction\n\n\t protected:\n\n\t\tBSPut (VReferenceable *pContainer, Device *pDevice) : BaseClass (pContainer, pDevice) {\n\n\t\t}\n\n\n\n\t // Destruction\n\n\t protected:\n\n\t\t~BSPut () {\n\n\t\t}\n\n\n\n\t // Start\n\n\t public:\n\n\t\tbool start (VkStatus &rStatus, BSWriteArea const &rArea) {\n\n\t\t m_iArea.setTo (rArea);\n\n\t\t m_pDevice->incrementUseCount ();\n\n\t\t return attempt (rStatus);\n\n\t\t}\n", "file_path": "software/src/8.1/src/kernel/Vca_VDeviceFactory.cpp", "rank": 74, "score": 318040.2870686678 }, { "content": "\tclass Use : public VDeviceImplementation::AbstractUse {\n\n\t DECLARE_FAMILY_MEMBERS (Use, VDeviceImplementation::AbstractUse);\n\n\n\n\t// Friends\n\n\t friend class VLoopbackDeviceImplementation;\n\n\n\n\t// Reference\n\n\tpublic:\n\n\t typedef VReference<ThisClass> Reference;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t Use (\n\n\t\tVReferenceable *pContainer, VLoopbackDeviceImplementation *pDevice\n\n\t ) : BaseClass (pContainer), m_pDevice (pDevice) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~Use () {\n", "file_path": "software/src/8.1/src/kernel/Vca_VLoopbackDeviceImplementation.h", "rank": 75, "score": 315137.679374588 }, { "content": "\tclass Use : public VDeviceImplementation::AbstractUse {\n\n\t DECLARE_FAMILY_MEMBERS (Use, VDeviceImplementation::AbstractUse);\n\n\n\n\t// Friends\n\n\t friend class VNullDeviceImplementation;\n\n\n\n\t// Reference\n\n\tpublic:\n\n\t typedef VReference<ThisClass> Reference;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t Use (VReferenceable *pContainer, VNullDeviceImplementation *pDevice) : BaseClass (pContainer), m_pDevice (pDevice) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~Use () {\n\n\t }\n\n\n", "file_path": "software/src/8.0/src/kernel/Vca_VNullDeviceImplementation.h", "rank": 76, "score": 315137.679374588 }, { "content": "\tclass Use : public VDeviceImplementation::AbstractUse {\n\n\t DECLARE_FAMILY_MEMBERS (Use, VDeviceImplementation::AbstractUse);\n\n\n\n\t// Friends\n\n\t friend class VLoopbackDeviceImplementation;\n\n\n\n\t// Reference\n\n\tpublic:\n\n\t typedef VReference<ThisClass> Reference;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t Use (\n\n\t\tVReferenceable *pContainer, VLoopbackDeviceImplementation *pDevice\n\n\t ) : BaseClass (pContainer), m_pDevice (pDevice) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~Use () {\n", "file_path": "software/src/8.0/src/kernel/Vca_VLoopbackDeviceImplementation.h", "rank": 77, "score": 315137.679374588 }, { "content": "\tclass Use : public VDeviceImplementation::AbstractUse {\n\n\t DECLARE_FAMILY_MEMBERS (Use, VDeviceImplementation::AbstractUse);\n\n\n\n\t// Friends\n\n\t friend class VFDIODeviceImplementation;\n\n\n\n\t// Reference\n\n\tpublic:\n\n\t typedef VReference<ThisClass> Reference;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t Use (\n\n\t\tVReferenceable *pContainer, VFDIODeviceImplementation *pDevice\n\n\t ) : BaseClass (pContainer), m_pDevice (pDevice) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~Use () {\n", "file_path": "software/src/master/src/kernel/Vca_VFDIODeviceImplementation.h", "rank": 78, "score": 315137.679374588 }, { "content": "\tclass Use : public VDeviceImplementation::AbstractUse {\n\n\t DECLARE_FAMILY_MEMBERS (Use, VDeviceImplementation::AbstractUse);\n\n\n\n\t// Friends\n\n\t friend class VNullDeviceImplementation;\n\n\n\n\t// Reference\n\n\tpublic:\n\n\t typedef VReference<ThisClass> Reference;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t Use (VReferenceable *pContainer, VNullDeviceImplementation *pDevice) : BaseClass (pContainer), m_pDevice (pDevice) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~Use () {\n\n\t }\n\n\n", "file_path": "software/src/8.1/src/kernel/Vca_VNullDeviceImplementation.h", "rank": 79, "score": 315137.679374588 }, { "content": "\tclass Use : public VDeviceImplementation::AbstractUse {\n\n\t DECLARE_FAMILY_MEMBERS (Use, VDeviceImplementation::AbstractUse);\n\n\n\n\t// Friends\n\n\t friend class VSSHDeviceImplementation;\n\n\n\n\t// Reference\n\n\tpublic:\n\n\t typedef VReference<ThisClass> Reference;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t Use (\n\n\t\tVReferenceable *pContainer, VSSHDeviceImplementation *pDevice\n\n\t ) : BaseClass (pContainer), m_pDevice (pDevice), m_xSubStreamID (0), m_iIndex (g_iIndexNext++) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~Use () {\n", "file_path": "software/src/master/src/kernel/Vca_VSSHDeviceImplementation.h", "rank": 80, "score": 315137.679374588 }, { "content": "\tclass BSPut : public Use {\n\n\t DECLARE_FAMILY_MEMBERS (BSPut, Use);\n\n\n\n\t friend class VNullDeviceImplementation;\n\n\n\n\t// Area\n\n\tpublic:\n\n\t typedef VDeviceBSWriteArea Area;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t BSPut (VReferenceable *pContainer, VNullDeviceImplementation *pDevice) : BaseClass (pContainer, pDevice) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~BSPut () {\n\n\t }\n\n\n\n\t// Startup\n", "file_path": "software/src/master/src/kernel/Vca_VNullDeviceImplementation.h", "rank": 81, "score": 314412.66419522546 }, { "content": "\tclass BSGet : public Use {\n\n\t DECLARE_FAMILY_MEMBERS (BSGet, Use);\n\n\n\n\t friend class VNullDeviceImplementation;\n\n\n\n\t// Area\n\n\tpublic:\n\n\t typedef VDeviceBSReadArea Area;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t BSGet (VReferenceable *pContainer, VNullDeviceImplementation *pDevice) : BaseClass (pContainer, pDevice) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~BSGet () {\n\n\t }\n\n\n\n\t// Startup\n", "file_path": "software/src/master/src/kernel/Vca_VNullDeviceImplementation.h", "rank": 82, "score": 314412.66419522546 }, { "content": "\t class ReadPoll : public Use {\n\n\t\tDECLARE_FAMILY_MEMBERS (ReadPoll, Use);\n\n\n\n\t // Construction\n\n\t protected:\n\n\t\tReadPoll (VReferenceable *pContainer, Device *pDevice) : BaseClass (pContainer, pDevice) {\n\n\t\t}\n\n\n\n\t // Destruction\n\n\t protected:\n\n\t\t~ReadPoll () {\n\n\t\t}\n\n\n\n\t // Start\n\n\t public:\n\n\t\tbool start (VkStatus &rStatus) {\n\n\t\t m_pDevice->incrementUseCount ();\n\n\t\t return attempt (rStatus);\n\n\t\t}\n\n\n", "file_path": "software/src/master/src/kernel/Vca_VDeviceFactory.cpp", "rank": 83, "score": 314412.66419522546 }, { "content": "\t class BSMove : public Use {\n\n\t\tDECLARE_FAMILY_MEMBERS (BSMove, Use);\n\n\n\n\t\tfriend class Device;\n\n\n\n\t // Construction\n\n\t protected:\n\n\t\tBSMove (VReferenceable *pContainer, Device *pDevice) : BaseClass (pContainer, pDevice) {\n\n\t\t}\n\n\n\n\t // Destruction\n\n\t protected:\n\n\t\t~BSMove () {\n\n\t\t}\n\n\n\n\t // Access\n\n\t public:\n\n\t\tXIOSB *iosb (bool bIn32BitMemory) {\n\n\t\t return bIn32BitMemory ? m_pStuff32 : &m_iIOSB;\n\n\t\t}\n", "file_path": "software/src/master/src/kernel/Vca_VDeviceFactory.cpp", "rank": 84, "score": 314412.66419522546 }, { "content": "\tclass BSGet : public Use {\n\n\t DECLARE_FAMILY_MEMBERS (BSGet, Use);\n\n\n\n\t friend class VLoopbackDeviceImplementation;\n\n\n\n\t// Area\n\n\tpublic:\n\n\t typedef VDeviceBSReadArea Area;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t BSGet (\n\n\t\tVReferenceable *pContainer, VLoopbackDeviceImplementation *pDevice\n\n\t ) : BaseClass (pContainer, pDevice) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~BSGet () {\n\n\t }\n", "file_path": "software/src/master/src/kernel/Vca_VLoopbackDeviceImplementation.h", "rank": 85, "score": 314412.66419522546 }, { "content": "\tclass BSPut : public Use {\n\n\t DECLARE_FAMILY_MEMBERS (BSPut, Use);\n\n\n\n\t friend class VLoopbackDeviceImplementation;\n\n\n\n\t// Area\n\n\tpublic:\n\n\t typedef VDeviceBSWriteArea Area;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t BSPut (\n\n\t\tVReferenceable *pContainer, VLoopbackDeviceImplementation *pDevice\n\n\t ) : BaseClass (pContainer, pDevice) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~BSPut () {\n\n\t }\n", "file_path": "software/src/master/src/kernel/Vca_VLoopbackDeviceImplementation.h", "rank": 86, "score": 314412.66419522546 }, { "content": "\t class BSGet : public Use {\n\n\t\tDECLARE_FAMILY_MEMBERS (BSGet, Use);\n\n\n\n\t // Construction\n\n\t protected:\n\n\t\tBSGet (VReferenceable *pContainer, Device *pDevice) : BaseClass (pContainer, pDevice) {\n\n\t\t}\n\n\n\n\t // Destruction\n\n\t protected:\n\n\t\t~BSGet () {\n\n\t\t}\n\n\n\n\t // Start\n\n\t public:\n\n\t\tbool start (VkStatus &rStatus, BSReadArea const &rArea) {\n\n\t\t m_iArea.setTo (rArea);\n\n\t\t m_pDevice->incrementUseCount ();\n\n\t\t return attempt (rStatus);\n\n\t\t}\n", "file_path": "software/src/master/src/kernel/Vca_VDeviceFactory.cpp", "rank": 87, "score": 314412.66419522546 }, { "content": "\t class BSPut : public Use {\n\n\t\tDECLARE_FAMILY_MEMBERS (BSPut, Use);\n\n\n\n\t // Construction\n\n\t protected:\n\n\t\tBSPut (VReferenceable *pContainer, Device *pDevice) : BaseClass (pContainer, pDevice) {\n\n\t\t}\n\n\n\n\t // Destruction\n\n\t protected:\n\n\t\t~BSPut () {\n\n\t\t}\n\n\n\n\t // Start\n\n\t public:\n\n\t\tbool start (VkStatus &rStatus, BSWriteArea const &rArea) {\n\n\t\t m_iArea.setTo (rArea);\n\n\t\t m_pDevice->incrementUseCount ();\n\n\t\t return attempt (rStatus);\n\n\t\t}\n", "file_path": "software/src/master/src/kernel/Vca_VDeviceFactory.cpp", "rank": 88, "score": 314412.66419522546 }, { "content": "\t class WritePoll : public Use {\n\n\t\tDECLARE_FAMILY_MEMBERS (WritePoll, Use);\n\n\n\n\t // Construction\n\n\t protected:\n\n\t\tWritePoll (VReferenceable *pContainer, Device *pDevice) : BaseClass (pContainer, pDevice) {\n\n\t\t}\n\n\n\n\t // Destruction\n\n\t protected:\n\n\t\t~WritePoll () {\n\n\t\t}\n\n\n\n\t // Start\n\n\t public:\n\n\t\tbool start (VkStatus &rStatus) {\n\n\t\t m_pDevice->incrementUseCount ();\n\n\t\t return attempt (rStatus);\n\n\t\t}\n\n\n", "file_path": "software/src/master/src/kernel/Vca_VDeviceFactory.cpp", "rank": 89, "score": 314412.66419522546 }, { "content": "\tclass Use : public VDeviceImplementation::AbstractUse {\n\n\t DECLARE_FAMILY_MEMBERS (Use, VDeviceImplementation::AbstractUse);\n\n\n\n\t// Friends\n\n\t friend class VLoopbackDeviceImplementation;\n\n\n\n\t// Reference\n\n\tpublic:\n\n\t typedef VReference<ThisClass> Reference;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t Use (\n\n\t\tVReferenceable *pContainer, VLoopbackDeviceImplementation *pDevice\n\n\t ) : BaseClass (pContainer), m_pDevice (pDevice) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~Use () {\n", "file_path": "software/src/master/src/kernel/Vca_VLoopbackDeviceImplementation.h", "rank": 90, "score": 312048.704662083 }, { "content": "\tclass Use : public VDeviceImplementation::AbstractUse {\n\n\t DECLARE_FAMILY_MEMBERS (Use, VDeviceImplementation::AbstractUse);\n\n\n\n\t// Friends\n\n\t friend class VNullDeviceImplementation;\n\n\n\n\t// Reference\n\n\tpublic:\n\n\t typedef VReference<ThisClass> Reference;\n\n\n\n\t// Construction\n\n\tprotected:\n\n\t Use (VReferenceable *pContainer, VNullDeviceImplementation *pDevice) : BaseClass (pContainer), m_pDevice (pDevice) {\n\n\t }\n\n\n\n\t// Destruction\n\n\tprotected:\n\n\t ~Use () {\n\n\t }\n\n\n", "file_path": "software/src/master/src/kernel/Vca_VNullDeviceImplementation.h", "rank": 91, "score": 312048.704662083 }, { "content": " class Vxa_API VClass : virtual public VExportableType {\n\n\tDECLARE_FAMILY_MEMBERS (VClass, VExportableType);\n\n\n\n // Aliases\n\n public:\n\n\ttypedef VkMapOf<VString,VString const&,char const*,VMethod::Reference> dictionary_t;\n\n\n\n // Construction\n\n protected:\n\n\tVClass ();\n\n\n\n // Destruction\n\n protected:\n\n\t~VClass ();\n\n\n\n // Accounting and Labeling\n\n public:\n\n\tvoid onCollectionCreation (unsigned int cInstances) {\n\n\t m_cCollectionsCreated++;\n\n\t m_cInstancesReported += cInstances;\n", "file_path": "software/src/master/src/kernel/Vxa_VClass.h", "rank": 92, "score": 311821.8769095046 }, { "content": "\t\tclass Vca_API Listen : public Use {\n\n\t\t DECLARE_ABSTRACT_RTTLITE (Listen, Use);\n\n\n\n\t\t// User Reference\n\n\t\tpublic:\n\n\t\t typedef VReference<Listener> UserRef;\n\n\n\n\t\t// Construction\n\n\t\tprotected:\n\n\t\t Listen () {\n\n\t\t }\n\n\n\n\t\t// Destruction\n\n\t\tprotected:\n\n\t\t ~Listen () {\n\n\t\t }\n\n\n\n\t\t// Startup\n\n\t\tprivate:\n\n\t\t virtual bool start_(VkStatus &rStatus) = 0;\n", "file_path": "software/src/8.0/src/kernel/Vca_VDevice.h", "rank": 93, "score": 311171.6666471024 }, { "content": "\t\tclass Vca_API Listen : public Use {\n\n\t\t DECLARE_ABSTRACT_RTTLITE (Listen, Use);\n\n\n\n\t\t// User Reference\n\n\t\tpublic:\n\n\t\t typedef VReference<Listener> UserRef;\n\n\n\n\t\t// Construction\n\n\t\tprotected:\n\n\t\t Listen () {\n\n\t\t }\n\n\n\n\t\t// Destruction\n\n\t\tprotected:\n\n\t\t ~Listen () {\n\n\t\t }\n\n\n\n\t\t// Startup\n\n\t\tprivate:\n\n\t\t virtual bool start_(VkStatus &rStatus) = 0;\n", "file_path": "software/src/8.1/src/kernel/Vca_VDevice.h", "rank": 94, "score": 311171.6666471024 }, { "content": "\t class Authority : virtual public VRolePlayer {\n\n\t\tDECLARE_CONCRETE_RTTLITE (Authority, VRolePlayer);\n\n\n\n\t // Map\n\n\t public:\n\n\t\ttypedef VkMapOf<IAuthority::Reference, IAuthority*, IAuthority const*, Reference> Map;\n\n\n\n\t // TicketSink\n\n\t public:\n", "file_path": "software/src/8.0/src/Vdht/Vdht_VHT.h", "rank": 95, "score": 311162.0747340523 }, { "content": "\tclass Entry : virtual public VRolePlayer {\n\n\t DECLARE_CONCRETE_RTTLITE (Entry, VRolePlayer);\n\n\n\n\t// Authority\n\n\tpublic:\n", "file_path": "software/src/8.0/src/Vdht/Vdht_VHT.h", "rank": 96, "score": 311162.0747340523 }, { "content": "\t void unlink ();\n\n\n\n\t// State\n\n\tprivate:\n\n\t AppReference \t\tconst m_pApp;\n\n\t ISubscriber::Reference\tconst m_pSubscriber;\n\n\t IRecipient::Reference\tconst m_pRecipient;\n\n\t Pointer\tm_pSuccessor;\n\n\t Pointer\tm_pPredecessor;\n\n\t bool\tm_bSuspended;\n\n\t bool\tm_bCanceled;\n\n\t};\n\n\tfriend class Subscription;\n\n\n\n // Construction\n\n public:\n\n\tThisApp (Context *pContext);\n\n\n\n // Destruction\n\n private:\n", "file_path": "software/src/8.1/src/vca_sample_distribution_server/vca_sample_distribution_server.cpp", "rank": 98, "score": 80.96072020870845 }, { "content": "\t void unlink ();\n\n\n\n\t// State\n\n\tprivate:\n\n\t AppReference \t\tconst m_pApp;\n\n\t ISubscriber::Reference\tconst m_pSubscriber;\n\n\t IRecipient::Reference\tconst m_pRecipient;\n\n\t Pointer\tm_pSuccessor;\n\n\t Pointer\tm_pPredecessor;\n\n\t bool\tm_bSuspended;\n\n\t bool\tm_bCanceled;\n\n\t};\n\n\tfriend class Subscription;\n\n\n\n // Construction\n\n public:\n\n\tThisApp (Context *pContext);\n\n\n\n // Destruction\n\n private:\n", "file_path": "software/src/8.0/src/vca_sample_distribution_server/vca_sample_distribution_server.cpp", "rank": 99, "score": 80.96072020870844 } ]
C++
nestedtensor/csrc/nested_tensor_impl.cpp
jbschlosser/nestedtensor
29d58d85ccd2c1b47fc40f2786f08c713f49acc6
#include <ATen/ATen.h> #include <ATen/NamedTensorUtils.h> #include <ATen/WrapDimUtils.h> #include <ATen/core/op_registration/op_registration.h> #include <nestedtensor/csrc/nested_tensor_impl.h> #include <nestedtensor/csrc/utils/nested_node_functions.h> #include <torch/csrc/jit/runtime/operator.h> #include <torch/library.h> #include <c10/core/DispatchKey.h> #include <nestedtensor/csrc/transpose.h> namespace at { using namespace torch::nested_tensor; using namespace c10; TensorNode _unbind_tensors(TensorNode structure) { std::vector<TensorNode> result_nodes; if (structure.is_leaf()) { for (at::Tensor tensor : structure.payload().unbind()) { result_nodes.emplace_back(TensorNode(std::move(tensor))); } } else { for (TensorNode child : structure.unbind()) { result_nodes.emplace_back(_unbind_tensors(child)); } } return TensorNode(std::move(result_nodes)); } NestedTensorImpl::NestedTensorImpl(std::shared_ptr<NestedTensorStorage> storage) : TensorImpl( c10::DispatchKeySet({NestedTensorKey}), storage->dtype(), storage->device()), _storage(storage) { remove_autograd_key(); key_set_ = key_set_ - c10::DispatchKeySet({c10::DispatchKey::ADInplaceOrView}); } inline TensorNode _squeeze_nested_dim(TensorNode structure, int64_t dim) { return squeeze(structure, dim, false); } int64_t NestedTensor_size_int(const Tensor& self, int64_t dim) { std::vector<c10::optional<int64_t>> size = get_nested_tensor_impl(self)->opt_sizes(); if (size[dim]) { return *(size[dim]); } throw std::runtime_error( "NestedTensor size at dim is not Tensor shape compliant."); } int64_t nt_size(Tensor tensor, int64_t dim) { auto impl = get_nested_tensor_impl(tensor); std::vector<c10::optional<int64_t>> size = impl->opt_sizes(); if (size[dim]) { return *(size[dim]); } throw std::runtime_error( "NestedTensor size at dim is not Tensor shape compliant."); } at::Tensor wrap_tensor_node(TensorNode&& result) { if (result.is_leaf()) { return result.payload(); } PackedStorage* ls = new PackedStorage(std::move(result)); NestedTensorStorage* ls_base = dynamic_cast<NestedTensorStorage*>(ls); return at::detail::make_tensor<NestedTensorImpl>( std::shared_ptr<NestedTensorStorage>(ls_base)); } std::vector<at::Tensor> wrap_tensor_node(std::vector<TensorNode> input) { std::vector<at::Tensor> result; for (size_t i = 0; i < input.size(); i++) { result.push_back(wrap_tensor_node(std::move(input[i]))); } return result; } at::Tensor wrap_buffer(at::Tensor&& buffer, SizeNode nested_size) { TORCH_CHECK(buffer.is_contiguous(), "Given buffer must be contiguous."); if (nested_size.is_leaf()) { return buffer.reshape(IntArrayRef(nested_size.payload())); } PackedStorage* ps = new PackedStorage(std::move(buffer), nested_size); NestedTensorStorage* ps_base = dynamic_cast<NestedTensorStorage*>(ps); return at::detail::make_tensor<NestedTensorImpl>( std::shared_ptr<NestedTensorStorage>(ps_base)); } at::Tensor wrap_buffer( at::Tensor&& buffer, EfficientSizeNode efficient_nested_size, EfficientSizeNode efficient_nested_stride) { TORCH_CHECK(buffer.is_contiguous(), "Given buffer must be contiguous."); TORCH_CHECK( efficient_nested_size.height() > 0, "Internal error: expected nested_size of non-zero height."); TORCH_CHECK( efficient_nested_stride.height() > 0, "Internal error: expected nested_size of non-zero height."); PackedStorage* ps = new PackedStorage( std::move(buffer), efficient_nested_size, efficient_nested_stride); NestedTensorStorage* ps_base = dynamic_cast<NestedTensorStorage*>(ps); return at::detail::make_tensor<NestedTensorImpl>( std::shared_ptr<NestedTensorStorage>(ps_base)); } at::Tensor wrap_buffer( at::Tensor&& buffer, EfficientSizeNode efficient_nested_size) { TORCH_CHECK(buffer.is_contiguous(), "Given buffer must be contiguous."); TORCH_CHECK( efficient_nested_size.height() > 0, "Internal error: expected nested_size of non-zero height."); PackedStorage* ps = new PackedStorage( std::move(buffer), efficient_nested_size); NestedTensorStorage* ps_base = dynamic_cast<NestedTensorStorage*>(ps); return at::detail::make_tensor<NestedTensorImpl>( std::shared_ptr<NestedTensorStorage>(ps_base)); } Tensor NestedTensor_contiguous(const Tensor& self, MemoryFormat memory_format) { if (get_is_contiguous(self, memory_format)) { return self; } TORCH_CHECK( memory_format != MemoryFormat::Preserve, "preserve memory format is unsupported by the contiguous operator"); if (memory_format == at::MemoryFormat::Contiguous) { if (get_is_contiguous(self, c10::MemoryFormat::ChannelsLast)) { auto transposed_sizes = map_efficient_size([](int64_t* size_ptr, int64_t size) { int64_t tmp = size_ptr[0]; size_ptr[0] = size_ptr[2]; size_ptr[2] = tmp; tmp = size_ptr[0]; size_ptr[0] = size_ptr[1]; size_ptr[1] = tmp; }, get_efficient_nested_size(self)); Tensor self_transposed = wrap_buffer(get_buffer(self), transposed_sizes); return transpose_nhwc_nchw(self_transposed); } PackedStorage* ps = new PackedStorage(get_nested_tensor_structure(self)); NestedTensorStorage* ps_base = dynamic_cast<NestedTensorStorage*>(ps); return at::detail::make_tensor<NestedTensorImpl>( std::shared_ptr<NestedTensorStorage>(ps_base)); } if (memory_format == at::MemoryFormat::ChannelsLast) { Tensor self_cont = self; if (!get_is_contiguous(self, c10::MemoryFormat::Contiguous)) { self_cont = NestedTensor_contiguous(self, at::MemoryFormat::Contiguous); } TORCH_CHECK(get_dim(self_cont) == 4, "ChannelsLast memory format requires 4 dim input."); auto new_strides = map_efficient_size([](int64_t* stride_ptr, int64_t* size_ptr, int64_t size) { stride_ptr[2] = size_ptr[0]; stride_ptr[1] = stride_ptr[2] * size_ptr[2]; stride_ptr[0] = 1; }, get_efficient_nested_stride(self_cont), get_efficient_nested_size(self_cont)); self_cont = transpose_nchw_nhwc(self_cont); return wrap_buffer(get_buffer(self_cont), get_efficient_nested_size(self), new_strides); } TORCH_CHECK(false, "Given memory format ", memory_format, " not supported by NestedTensor_contiguous."); return self; } bool NestedTensor_is_pinned(const Tensor& self, c10::optional<Device> device) { TORCH_CHECK( !device.has_value() || device->is_cuda(), "NestedTensor doesn't support non-CUDA pinned memory"); return get_nested_tensor_impl(self)->is_pinned(); } std::vector<at::Tensor> NestedTensor_unbind( const at::Tensor& self, int64_t dim) { auto _data = get_nested_tensor_impl(self); dim = at::maybe_wrap_dim(dim, get_dim(self)); auto node = _data->get_structure(); if (dim == 0) { return wrap_tensor_node(node.unbind()); } std::vector<std::vector<TensorNode>> unbound; for (auto child : node.unbind()) { std::vector<at::Tensor> tmp = at::unbind(wrap_tensor_node(std::move(child)), dim - 1); for (size_t j = 0; j < tmp.size(); j++) { if (j >= unbound.size()) { unbound.resize(j + 1); } unbound[j].push_back(TensorNode(std::move(tmp[j]))); } } std::vector<TensorNode> result; for (size_t i = 0; i < unbound.size(); i++) { result.push_back(TensorNode(std::move(unbound[i]))); } return wrap_tensor_node(result); } Tensor NestedTensor_select(const Tensor& self, int64_t dim, int64_t index) { int64_t ndim = get_dim(self); dim = maybe_wrap_dim(dim, ndim); if (dim != 0) { TORCH_CHECK_INDEX(false, "select() only supports dim == 0 for now."); } auto tmp = get_nested_tensor_structure(self).unbind()[index]; return wrap_tensor_node(std::move(tmp)); } Tensor NestedTensor_to_nested_tensor( at::Tensor input, c10::optional<int64_t> dim_) { int64_t dim = 0; if (dim_) { dim = *dim_; dim = maybe_wrap_dim(*dim_, get_dim(input) + 1); } TORCH_CHECK( dim <= get_dim(input), "target nested dimension needs to be equal or less than to input dimension"); if (is_nested_tensor_impl(input) && dim >= get_nested_dim(input)) { TensorNode unbound = _unbind_tensors(get_nested_tensor_structure(input)); for (int64_t i = 0; i < (dim - get_nested_dim(input)); i++) { unbound = _unbind_tensors(unbound); } return wrap_tensor_node(std::move(unbound)); } if (!is_nested_tensor_impl(input) && dim > 0) { std::vector<TensorNode> unbound_nodes; for (at::Tensor t : input.unbind()) { unbound_nodes.push_back(TensorNode(std::move(t))); } TensorNode unbound(std::move(unbound_nodes)); for (int64_t i = 1; i < dim; i++) { unbound = _unbind_tensors(unbound); } return wrap_tensor_node(std::move(unbound)); } return input; } Tensor NestedTensor_slice( const Tensor& self, int64_t dim, c10::optional<int64_t> start_, c10::optional<int64_t> end_, int64_t step) { int64_t start; if (start_) { start = *start_; } else { start = 0; } int64_t end; if (end_) { end = *end_; } else { end = 9223372036854775807; } int64_t ndim = get_dim(self); if (ndim == 0) { TORCH_CHECK_INDEX(false, "slice() cannot be applied to a 0-dim tensor."); } dim = maybe_wrap_dim(dim, ndim); if (dim != 0) { TORCH_CHECK_INDEX(false, "slice() only supports dim == 0 for now."); } TORCH_CHECK(step >= 1, "slice step must be positive for now."); int64_t sizes_0 = nt_size(self, 0); if (start < 0) { start += sizes_0; } if (end < 0) { end += sizes_0; } if (start < 0) { start = 0; } else if (start >= sizes_0) { start = sizes_0; } if (end < start) { end = start; } else if (end >= sizes_0) { end = sizes_0; } std::vector<at::Tensor> unbound = at::unbind(self, 0); std::vector<TensorNode> new_tensor_nodes; for (int64_t i = start; i < end; i += step) { if (is_nested_tensor_impl(unbound[i])) { new_tensor_nodes.push_back(get_nested_tensor_structure(unbound[i])); } else { new_tensor_nodes.push_back(TensorNode(std::move(unbound[i]))); } } auto result = wrap_tensor_node(TensorNode(std::move(new_tensor_nodes))); namedinference::propagate_names(result, self); return result; } Tensor& NestedTensor_copy_(Tensor& self, const Tensor& src, bool non_blocking) { apply_nested_tensor( [](at::Tensor& self, at::Tensor& source) { return self.copy_(source); }, self, src); return self; } Tensor _NestedTensor_squeeze_(Tensor self, c10::optional<int64_t> dim_) { auto self_impl = get_nested_tensor_impl(self); if (!dim_) { auto init_sizes = self_impl->opt_sizes(); for (size_t i = 0; i < init_sizes.size() - 1; i++) { int64_t index = init_sizes.size() - i - 1; c10::optional<int64_t> s = init_sizes[index]; if (s && ((*s) == 1)) { self = _NestedTensor_squeeze_(self, index); } } return self; } int64_t dim = at::maybe_wrap_dim(*dim_, get_dim(self)); TORCH_CHECK(dim > 0, "Cannot squeeze first dimension."); TORCH_CHECK( ((get_nested_tensor_impl(self)->opt_sizes()[dim]) && ((*(get_nested_tensor_impl(self)->opt_sizes()[dim])) == 1)), "Given dimension is either undefined or not a singleton."); if (dim < get_nested_tensor_impl(self)->nested_dim()) { return wrap_tensor_node( _squeeze_nested_dim(self_impl->get_structure(), dim)); } int64_t height = self_impl->get_structure().height(); return map_nested_tensor( [dim, height](at::Tensor tensor) { return tensor.squeeze(dim - height); }, self); } Tensor& NestedTensor_squeeze_(Tensor& self) { self = _NestedTensor_squeeze_(self, c10::nullopt); return self; } Tensor& NestedTensor_squeeze__dim(Tensor& self, int64_t dim) { self = _NestedTensor_squeeze_(self, dim); return self; } Tensor NestedTensor_squeeze_dim(const Tensor& self, int64_t dim) { dim = at::maybe_wrap_dim(dim, get_dim(self)); auto self_impl = get_nested_tensor_impl(self); int64_t nested_dim = self_impl->nested_dim(); TORCH_CHECK(dim > 0, "Cannot squeeze first dimension."); TORCH_CHECK(dim >= nested_dim, "Cannot squeeze nested dimension."); TORCH_CHECK( ((self_impl->opt_sizes()[dim]) && ((*(self_impl->opt_sizes()[dim])) == 1)), "Given dimension is either undefined or not a singleton."); return map_nested_tensor( [dim, nested_dim](at::Tensor tensor) { return tensor.squeeze(dim - nested_dim); }, self); } Tensor NestedTensor_squeeze(const Tensor& self) { TORCH_CHECK(false, "squeeze(Tensor) is currently not implemented."); } Tensor NestedTensor_unsqueeze(const Tensor& self, int64_t dim) { dim = maybe_wrap_dim(dim, get_dim(self) + 1); if (dim == 0) { std::vector<TensorNode> one_node; one_node.push_back(get_nested_tensor_structure(self)); return wrap_tensor_node(TensorNode(std::move(one_node))); } std::vector<TensorNode> result_nodes; auto unbound = self.unbind(0); for (size_t i = 0; i < unbound.size(); i++) { result_nodes.push_back( get_nested_tensor_structure(at::unsqueeze(unbound[i], dim - 1))); } return wrap_tensor_node(TensorNode(std::move(result_nodes))); } Tensor NestedTensor_to_dtype_layout( const Tensor& self, c10::optional<ScalarType> dtype, c10::optional<Layout> layout, c10::optional<Device> device, c10::optional<bool> pin_memory, bool non_blocking, bool copy, c10::optional<c10::MemoryFormat> optional_memory_format) { auto input_buffer = get_buffer(self); auto result_nt = wrap_buffer(input_buffer.to(dtype, layout, device, pin_memory, non_blocking, copy, c10::nullopt), get_efficient_nested_size(self), get_efficient_nested_stride(self)); if (optional_memory_format) { return NestedTensor_contiguous(result_nt, *optional_memory_format); } return result_nt; } TORCH_LIBRARY_IMPL(aten, NestedTensor, m) { nt_impl(m, "contiguous", NestedTensor_contiguous); nt_impl(m, "copy_", NestedTensor_copy_); nt_impl(m, "is_pinned", NestedTensor_is_pinned); nt_impl(m, "select.int", NestedTensor_select); nt_impl(m, "size.int", NestedTensor_size_int); nt_impl(m, "slice.Tensor", NestedTensor_slice); nt_impl(m, "squeeze", NestedTensor_squeeze); nt_impl(m, "squeeze.dim", NestedTensor_squeeze_dim); nt_impl(m, "squeeze_", NestedTensor_squeeze_); nt_impl(m, "squeeze_.dim", NestedTensor_squeeze__dim); nt_impl(m, "unbind.int", NestedTensor_unbind); nt_impl(m, "unsqueeze", NestedTensor_unsqueeze); nt_impl(m, "to.dtype_layout", NestedTensor_to_dtype_layout); } }
#include <ATen/ATen.h> #include <ATen/NamedTensorUtils.h> #include <ATen/WrapDimUtils.h> #include <ATen/core/op_registration/op_registration.h> #include <nestedtensor/csrc/nested_tensor_impl.h> #include <nestedtensor/csrc/utils/nested_node_functions.h> #include <torch/csrc/jit/runtime/operator.h> #include <torch/library.h> #include <c10/core/DispatchKey.h> #include <nestedtensor/csrc/transpose.h> namespace at { using namespace torch::nested_tensor; using namespace c10; TensorNode _unbind_tensors(TensorNode structure) { std::vector<TensorNode> result_nodes; if (structure.is_leaf()) { for (at::Tensor tensor : structure.payload().unbind()) { result_nodes.emplace_back(TensorNode(std::move(tensor))); } } else { for (TensorNode child : structure.unbind()) { result_nodes.emplace_back(_unbind_tensors(child)); } } return TensorNode(std::move(result_nodes)); } NestedTensorImpl::NestedTensorImpl(std::shared_ptr<NestedTensorStorage> storage) : TensorImpl( c10::DispatchKeySet({NestedTensorKey}), storage->dtype(), storage->device()), _storage(storage) { remove_autograd_key(); key_set_ = key_set_ - c10::DispatchKeySet({c10::DispatchKey::ADInplaceOrView}); } inline TensorNode _squeeze_nested_dim(TensorNode structure, int64_t dim) { return squeeze(structure, dim, false); } int64_t NestedTensor_size_int(const Tensor& self, int64_t dim) { std::vector<c10::optional<int64_t>> size = get_nested_tensor_impl(self)->opt_sizes(); if (size[dim]) { return *(size[dim]); } throw std::runtime_error( "NestedTensor size at dim is not Tensor shape compliant."); } int64_t nt_size(Tensor tensor, int64_t dim) { auto impl = get_nested_tensor_impl(tensor); std::vector<c10::optional<int64_t>> size = impl->opt_sizes(); if (size[dim]) { return *(size[dim]); } throw std::runtime_error( "NestedTensor size at dim is not Tensor shape compliant."); } at::Tensor wrap_tensor_node(TensorNode&& result) { if (result.is_leaf()) { return result.payload(); } PackedStorage* ls = new PackedStorage(std::move(result)); NestedTensorStorage* ls_base = dynamic_cast<NestedTensorStorage*>(ls); return at::detail::make_tensor<NestedTensorImpl>( std::shared_ptr<NestedTensorStorage>(ls_base)); } std::vector<at::Tensor> wrap_tensor_node(std::vector<TensorNode> input) { std::vector<at::Tensor> result; for (size_t i = 0; i < input.size(); i++) { result.push_back(wrap_tensor_node(std::move(input[i]))); } return result; } at::Tensor wrap_buffer(at::Tensor&& buffer, SizeNode nested_size) { TORCH_CHECK(buffer.is_contiguous(), "Given buffer must be contiguous."); if (nested_size.is_leaf()) { return buffer.reshape(IntArrayRef(nested_size.payload())); } PackedStorage* ps = new PackedStorage(std::move(buffer), nested_size); NestedTensorStorage* ps_base = dynamic_cast<NestedTensorStorage*>(ps); return at::detail::make_tensor<NestedTensorImpl>( std::shared_ptr<NestedTensorStorage>(ps_base)); } at::Tensor wrap_buffer( at::Tensor&& buffer, EfficientSizeNode efficient_nested_size, EfficientSizeNode efficient_nested_stride) { TORCH_CHECK(buffer.is_contiguous(), "Given buffer must be contiguous."); TORCH_CHECK( efficient_nested_size.height() > 0, "Internal error: expected nested_size of non-zero height."); TORCH_CHECK( efficient_nested_stride.height() > 0, "Internal error: expected nested_size of non-zero height."); PackedStorage* ps = new PackedStorage( std::move(buffer), efficient_nested_size, efficient_nested_stride); NestedTensorStorage* ps_base = dynamic_cast<NestedTensorStorage*>(ps); return at::detail::make_tensor<NestedTensorImpl>( std::shared_ptr<NestedTensorStorage>(ps_base)); } at::Tensor wrap_buffer( at::Tensor&& buffer, EfficientSizeNode efficient_nested_size) { TORCH_CHECK(buffer.is_contiguous(), "Given buffer must be contiguous."); TORCH_CHECK( efficient_nested_size.height() > 0, "Internal error: expected nested_size of non-zero height."); PackedStorage* ps = new PackedStorage( std::move(buffer), efficient_nested_size); NestedTensorStorage* ps_base = dynamic_cast<NestedTensorStorage*>(ps); return at::detail::make_tensor<NestedTensorImpl>( std::shared_ptr<NestedTensorStorage>(ps_base)); } Tensor NestedTensor_contiguous(const Tensor& self, MemoryFormat memory_format) { if (get_is_contiguous(self, memory_format)) { return self; } TORCH_CHECK( memory_format != MemoryFormat::Preserve, "preserve memory format is unsupported by the contiguous operator"); if (memory_format == at::MemoryFormat::Contiguous) { if (get_is_contiguous(self, c10::MemoryFormat::ChannelsLast)) { auto transposed_sizes = map_efficient_size([](int64_t* size_ptr, int64_t size) { int64_t tmp = size_ptr[0]; size_ptr[0] = size_ptr[2]; size_ptr[2] = tmp; tmp = size_ptr[0]; size_ptr[0] = size_ptr[1]; size_ptr[1] = tmp; }, get_efficient_nested_size(self)); Tensor self_transposed = wrap_buffer(get_buffer(self), transposed_sizes); return transpose_nhwc_nchw(self_transposed); } PackedStorage* ps = new PackedStorage(get_nested_tensor_structure(self)); NestedTensorStorage* ps_base = dynamic_cast<NestedTensorStorage*>(ps); return at::detail::make_tensor<NestedTensorImpl>( std::shared_ptr<NestedTensorStorage>(ps_base)); } if (memory_format == at::MemoryFormat::ChannelsLast) { Tensor self_cont = self; if (!get_is_contiguous(self, c10::MemoryFormat::Contiguous)) { self_cont = NestedTensor_contiguous(self, at::MemoryFormat::Contiguous); } TORCH_CHECK(get_dim(self_cont) == 4, "ChannelsLast memory format requires 4 dim input."); auto new_strides = map_efficient_size([](int64_t* stride_ptr, int64_t* size_ptr, int64_t size) { stride_ptr[2] = size_ptr[0]; stride_ptr[1] = stride_ptr[2] * size_ptr[2]; stride_ptr[0] = 1; }, get_efficient_nested_stride(self_cont), get_efficient_nested_size(self_cont)); self_cont = transpose_nchw_nhwc(self_cont);
}, self); } Tensor& NestedTensor_squeeze_(Tensor& self) { self = _NestedTensor_squeeze_(self, c10::nullopt); return self; } Tensor& NestedTensor_squeeze__dim(Tensor& self, int64_t dim) { self = _NestedTensor_squeeze_(self, dim); return self; } Tensor NestedTensor_squeeze_dim(const Tensor& self, int64_t dim) { dim = at::maybe_wrap_dim(dim, get_dim(self)); auto self_impl = get_nested_tensor_impl(self); int64_t nested_dim = self_impl->nested_dim(); TORCH_CHECK(dim > 0, "Cannot squeeze first dimension."); TORCH_CHECK(dim >= nested_dim, "Cannot squeeze nested dimension."); TORCH_CHECK( ((self_impl->opt_sizes()[dim]) && ((*(self_impl->opt_sizes()[dim])) == 1)), "Given dimension is either undefined or not a singleton."); return map_nested_tensor( [dim, nested_dim](at::Tensor tensor) { return tensor.squeeze(dim - nested_dim); }, self); } Tensor NestedTensor_squeeze(const Tensor& self) { TORCH_CHECK(false, "squeeze(Tensor) is currently not implemented."); } Tensor NestedTensor_unsqueeze(const Tensor& self, int64_t dim) { dim = maybe_wrap_dim(dim, get_dim(self) + 1); if (dim == 0) { std::vector<TensorNode> one_node; one_node.push_back(get_nested_tensor_structure(self)); return wrap_tensor_node(TensorNode(std::move(one_node))); } std::vector<TensorNode> result_nodes; auto unbound = self.unbind(0); for (size_t i = 0; i < unbound.size(); i++) { result_nodes.push_back( get_nested_tensor_structure(at::unsqueeze(unbound[i], dim - 1))); } return wrap_tensor_node(TensorNode(std::move(result_nodes))); } Tensor NestedTensor_to_dtype_layout( const Tensor& self, c10::optional<ScalarType> dtype, c10::optional<Layout> layout, c10::optional<Device> device, c10::optional<bool> pin_memory, bool non_blocking, bool copy, c10::optional<c10::MemoryFormat> optional_memory_format) { auto input_buffer = get_buffer(self); auto result_nt = wrap_buffer(input_buffer.to(dtype, layout, device, pin_memory, non_blocking, copy, c10::nullopt), get_efficient_nested_size(self), get_efficient_nested_stride(self)); if (optional_memory_format) { return NestedTensor_contiguous(result_nt, *optional_memory_format); } return result_nt; } TORCH_LIBRARY_IMPL(aten, NestedTensor, m) { nt_impl(m, "contiguous", NestedTensor_contiguous); nt_impl(m, "copy_", NestedTensor_copy_); nt_impl(m, "is_pinned", NestedTensor_is_pinned); nt_impl(m, "select.int", NestedTensor_select); nt_impl(m, "size.int", NestedTensor_size_int); nt_impl(m, "slice.Tensor", NestedTensor_slice); nt_impl(m, "squeeze", NestedTensor_squeeze); nt_impl(m, "squeeze.dim", NestedTensor_squeeze_dim); nt_impl(m, "squeeze_", NestedTensor_squeeze_); nt_impl(m, "squeeze_.dim", NestedTensor_squeeze__dim); nt_impl(m, "unbind.int", NestedTensor_unbind); nt_impl(m, "unsqueeze", NestedTensor_unsqueeze); nt_impl(m, "to.dtype_layout", NestedTensor_to_dtype_layout); } }
return wrap_buffer(get_buffer(self_cont), get_efficient_nested_size(self), new_strides); } TORCH_CHECK(false, "Given memory format ", memory_format, " not supported by NestedTensor_contiguous."); return self; } bool NestedTensor_is_pinned(const Tensor& self, c10::optional<Device> device) { TORCH_CHECK( !device.has_value() || device->is_cuda(), "NestedTensor doesn't support non-CUDA pinned memory"); return get_nested_tensor_impl(self)->is_pinned(); } std::vector<at::Tensor> NestedTensor_unbind( const at::Tensor& self, int64_t dim) { auto _data = get_nested_tensor_impl(self); dim = at::maybe_wrap_dim(dim, get_dim(self)); auto node = _data->get_structure(); if (dim == 0) { return wrap_tensor_node(node.unbind()); } std::vector<std::vector<TensorNode>> unbound; for (auto child : node.unbind()) { std::vector<at::Tensor> tmp = at::unbind(wrap_tensor_node(std::move(child)), dim - 1); for (size_t j = 0; j < tmp.size(); j++) { if (j >= unbound.size()) { unbound.resize(j + 1); } unbound[j].push_back(TensorNode(std::move(tmp[j]))); } } std::vector<TensorNode> result; for (size_t i = 0; i < unbound.size(); i++) { result.push_back(TensorNode(std::move(unbound[i]))); } return wrap_tensor_node(result); } Tensor NestedTensor_select(const Tensor& self, int64_t dim, int64_t index) { int64_t ndim = get_dim(self); dim = maybe_wrap_dim(dim, ndim); if (dim != 0) { TORCH_CHECK_INDEX(false, "select() only supports dim == 0 for now."); } auto tmp = get_nested_tensor_structure(self).unbind()[index]; return wrap_tensor_node(std::move(tmp)); } Tensor NestedTensor_to_nested_tensor( at::Tensor input, c10::optional<int64_t> dim_) { int64_t dim = 0; if (dim_) { dim = *dim_; dim = maybe_wrap_dim(*dim_, get_dim(input) + 1); } TORCH_CHECK( dim <= get_dim(input), "target nested dimension needs to be equal or less than to input dimension"); if (is_nested_tensor_impl(input) && dim >= get_nested_dim(input)) { TensorNode unbound = _unbind_tensors(get_nested_tensor_structure(input)); for (int64_t i = 0; i < (dim - get_nested_dim(input)); i++) { unbound = _unbind_tensors(unbound); } return wrap_tensor_node(std::move(unbound)); } if (!is_nested_tensor_impl(input) && dim > 0) { std::vector<TensorNode> unbound_nodes; for (at::Tensor t : input.unbind()) { unbound_nodes.push_back(TensorNode(std::move(t))); } TensorNode unbound(std::move(unbound_nodes)); for (int64_t i = 1; i < dim; i++) { unbound = _unbind_tensors(unbound); } return wrap_tensor_node(std::move(unbound)); } return input; } Tensor NestedTensor_slice( const Tensor& self, int64_t dim, c10::optional<int64_t> start_, c10::optional<int64_t> end_, int64_t step) { int64_t start; if (start_) { start = *start_; } else { start = 0; } int64_t end; if (end_) { end = *end_; } else { end = 9223372036854775807; } int64_t ndim = get_dim(self); if (ndim == 0) { TORCH_CHECK_INDEX(false, "slice() cannot be applied to a 0-dim tensor."); } dim = maybe_wrap_dim(dim, ndim); if (dim != 0) { TORCH_CHECK_INDEX(false, "slice() only supports dim == 0 for now."); } TORCH_CHECK(step >= 1, "slice step must be positive for now."); int64_t sizes_0 = nt_size(self, 0); if (start < 0) { start += sizes_0; } if (end < 0) { end += sizes_0; } if (start < 0) { start = 0; } else if (start >= sizes_0) { start = sizes_0; } if (end < start) { end = start; } else if (end >= sizes_0) { end = sizes_0; } std::vector<at::Tensor> unbound = at::unbind(self, 0); std::vector<TensorNode> new_tensor_nodes; for (int64_t i = start; i < end; i += step) { if (is_nested_tensor_impl(unbound[i])) { new_tensor_nodes.push_back(get_nested_tensor_structure(unbound[i])); } else { new_tensor_nodes.push_back(TensorNode(std::move(unbound[i]))); } } auto result = wrap_tensor_node(TensorNode(std::move(new_tensor_nodes))); namedinference::propagate_names(result, self); return result; } Tensor& NestedTensor_copy_(Tensor& self, const Tensor& src, bool non_blocking) { apply_nested_tensor( [](at::Tensor& self, at::Tensor& source) { return self.copy_(source); }, self, src); return self; } Tensor _NestedTensor_squeeze_(Tensor self, c10::optional<int64_t> dim_) { auto self_impl = get_nested_tensor_impl(self); if (!dim_) { auto init_sizes = self_impl->opt_sizes(); for (size_t i = 0; i < init_sizes.size() - 1; i++) { int64_t index = init_sizes.size() - i - 1; c10::optional<int64_t> s = init_sizes[index]; if (s && ((*s) == 1)) { self = _NestedTensor_squeeze_(self, index); } } return self; } int64_t dim = at::maybe_wrap_dim(*dim_, get_dim(self)); TORCH_CHECK(dim > 0, "Cannot squeeze first dimension."); TORCH_CHECK( ((get_nested_tensor_impl(self)->opt_sizes()[dim]) && ((*(get_nested_tensor_impl(self)->opt_sizes()[dim])) == 1)), "Given dimension is either undefined or not a singleton."); if (dim < get_nested_tensor_impl(self)->nested_dim()) { return wrap_tensor_node( _squeeze_nested_dim(self_impl->get_structure(), dim)); } int64_t height = self_impl->get_structure().height(); return map_nested_tensor( [dim, height](at::Tensor tensor) { return tensor.squeeze(dim - height);
random
[ { "content": " int64_t height() const {\n\n return _height;\n", "file_path": "nestedtensor/csrc/storage/EfficientSizeNode.h", "rank": 0, "score": 146452.20706677216 }, { "content": " int64_t dim() const {\n\n return _sizes.dim() > 0 ? _height + _sizes.size(1) : _height;\n", "file_path": "nestedtensor/csrc/storage/EfficientSizeNode.h", "rank": 1, "score": 146361.5764829059 }, { "content": "inline bool efficient_size_structure_matches(\n\n const EfficientSizeNode& size_node0,\n\n const EfficientSizeNode& size_node1) {\n\n return size_node0.structure() == size_node1.structure();\n", "file_path": "nestedtensor/csrc/storage/EfficientSizeNode.h", "rank": 2, "score": 115003.4230896311 }, { "content": " int64_t _structure;\n", "file_path": "nestedtensor/csrc/storage/EfficientSizeNode.h", "rank": 3, "score": 112349.98828138005 }, { "content": " const int64_t structure() const {\n\n return _structure;\n", "file_path": "nestedtensor/csrc/storage/EfficientSizeNode.h", "rank": 4, "score": 112349.98828138007 }, { "content": " def test_mask_dim_too_small_error(self):\n\n a = nt.nested_tensor([\n\n torch.tensor([1, 2, ]),\n\n torch.tensor([3, 4, 5, 6]),\n\n ])\n\n\n\n self.assertRaisesRegex(\n", "file_path": "test/test_nested_tensor_masking.py", "rank": 5, "score": 97842.97023375795 }, { "content": " def test_ntftm_nested_dim_0_error(self):\n\n tensor = torch.tensor([])\n\n self.assertRaisesRegex(RuntimeError, \"Nested dimension can't be 0.\",\n", "file_path": "test/test_nested_tensor_masking.py", "rank": 6, "score": 97842.97023375795 }, { "content": " def test_conv2d_3x3_resnext_input_cuda(self):\n\n shapes = [(4, 3, 2), (4, 3, 3), (4, 2, 3)]\n\n weight = torch.randn(5, 4, 2, 2)\n\n for dtype in [torch.float16, torch.float32]:\n\n stride = [1, 1]\n\n padding = [1, 1]\n\n dilation = [1, 1]\n\n groups = 1\n\n self._test_conv2d_dtype(dtype, weight, torch.device('cuda'),\n\n shapes, stride=stride, padding=padding,\n", "file_path": "test/test_nested_tensor_functional.py", "rank": 7, "score": 95464.01392020928 }, { "content": "import torch\n\nimport nestedtensor\n\nimport unittest\n\nfrom utils_test_case import TestCase\n\n\n\n# TODO: Test unbind, test grad and backward\n\n\n\n\n\nclass TestNestedTensorBuffer(TestCase):\n\n @unittest.skip(\"Requires autograd support\")\n\n def test_grad(self):\n\n nt = nestedtensor.nested_tensor([torch.rand(1, 2)])\n\n nt.requires_grad_(True)\n\n a = nt.unbind()[0]\n\n c = nt.sum()\n\n c.backward()\n\n # TODO: Should this have a gradient or not?\n\n # What if nt was constructed with as_nested_tensor vs. nested_tensor\n\n # When calling unbind on a torch.Tensor it doesn't have a grad,\n\n # because it is not a leaf variable. So, if we call unbind\n\n # on a NestedTensor to retrieve one of its constiuents, should\n\n # that be a leaf variable or a view?\n\n # Further, if the NestedTensor has a buffer, the constiuents are\n\n # views of that buffer, so that means unbind() needs to return views\n\n # in either case.\n\n\n\n # When I set requires_grad_ for a NestedTensor and this NestedTensors becomes\n\n # a leaf in an autograd graph it'll have a .grad field. If I call unbind on\n\n # this NestedTensor I should get a list of views. However, if constructed\n\n # with as_nested_tensor I'll get a list of Tensors, i.e. the Tensors used\n\n # to actually build the NestedTensor, which are then all leaf variables\n\n # (since requires_grad_ is forwarded to its constiuents since .grad()\n\n # on the constiuents is used to construct NestedTensor.grad)\n\n\n\n # TODO: Re-enable under autograd\n\n # self.assertIsNotNone(a.grad)\n\n # nt_grad = nt.grad\n\n # # Unbinding the gradient is legitimate for further processing.\n\n # self.assertIsNotNone(nt_grad.unbind()[0])\n\n\n\n # TODO\n\n @unittest.skip(\"Requires autograd support\")\n\n def test_detach(self):\n\n pass\n\n\n\n\n\nif __name__ == \"__main__\":\n\n unittest.main()\n", "file_path": "test/test_nested_tensor_buffer.py", "rank": 8, "score": 90185.8934644001 }, { "content": "class TestNestedTensorBuffer(TestCase):\n\n @unittest.skip(\"Requires autograd support\")\n\n def test_grad(self):\n\n nt = nestedtensor.nested_tensor([torch.rand(1, 2)])\n\n nt.requires_grad_(True)\n\n a = nt.unbind()[0]\n\n c = nt.sum()\n\n c.backward()\n\n # TODO: Should this have a gradient or not?\n\n # What if nt was constructed with as_nested_tensor vs. nested_tensor\n\n # When calling unbind on a torch.Tensor it doesn't have a grad,\n\n # because it is not a leaf variable. So, if we call unbind\n\n # on a NestedTensor to retrieve one of its constiuents, should\n\n # that be a leaf variable or a view?\n\n # Further, if the NestedTensor has a buffer, the constiuents are\n\n # views of that buffer, so that means unbind() needs to return views\n\n # in either case.\n\n\n\n # When I set requires_grad_ for a NestedTensor and this NestedTensors becomes\n\n # a leaf in an autograd graph it'll have a .grad field. If I call unbind on\n\n # this NestedTensor I should get a list of views. However, if constructed\n\n # with as_nested_tensor I'll get a list of Tensors, i.e. the Tensors used\n\n # to actually build the NestedTensor, which are then all leaf variables\n\n # (since requires_grad_ is forwarded to its constiuents since .grad()\n\n # on the constiuents is used to construct NestedTensor.grad)\n\n\n\n # TODO: Re-enable under autograd\n\n # self.assertIsNotNone(a.grad)\n\n # nt_grad = nt.grad\n\n # # Unbinding the gradient is legitimate for further processing.\n\n # self.assertIsNotNone(nt_grad.unbind()[0])\n\n\n\n # TODO\n\n @unittest.skip(\"Requires autograd support\")\n\n def test_detach(self):\n", "file_path": "test/test_nested_tensor_buffer.py", "rank": 9, "score": 89590.11036570989 }, { "content": " virtual ~NestedTensorStorage() = default;\n", "file_path": "nestedtensor/csrc/storage/StorageBase.h", "rank": 10, "score": 88939.96709693906 }, { "content": "Tensor NestedTensor_to_tensor(Tensor tensor, c10::optional<int64_t> dim_);\n", "file_path": "nestedtensor/csrc/nested_tensor_impl.h", "rank": 11, "score": 87893.1250865149 }, { "content": " const at::Tensor _sizes;\n", "file_path": "nestedtensor/csrc/storage/EfficientSizeNode.h", "rank": 12, "score": 87482.88426016847 }, { "content": " virtual int64_t dim() const {\n", "file_path": "nestedtensor/csrc/storage/StorageBase.h", "rank": 13, "score": 85801.55079660314 }, { "content": " int64_t* sizes_ptr0 = sizes0.data_ptr<int64_t>();\n", "file_path": "nestedtensor/csrc/storage/EfficientSizeNode.h", "rank": 14, "score": 85530.65308951239 }, { "content": " int64_t* sizes_ptr1 = sizes1.data_ptr<int64_t>();\n", "file_path": "nestedtensor/csrc/storage/EfficientSizeNode.h", "rank": 15, "score": 85530.6530895124 }, { "content": " for (int64_t j = 0; j < _sizes.size(1); j++) {\n", "file_path": "nestedtensor/csrc/storage/EfficientSizeNode.h", "rank": 16, "score": 85530.65308951239 }, { "content": " void refresh_opt_sizes() {\n\n _opt_sizes = impl::construct_efficient_size(_structure, _height, _sizes);\n", "file_path": "nestedtensor/csrc/storage/EfficientSizeNode.h", "rank": 17, "score": 83667.17451975028 }, { "content": " explicit EfficientSizeNode(const SizeNode& size_node)\n\n : _height(size_node.height()),\n\n _structure(size_node.degree()),\n\n _sizes(impl::stack_sizes(size_node)),\n\n _opt_sizes(impl::construct_efficient_size(_structure, _height, _sizes))\n\n {}\n\n\n\n explicit EfficientSizeNode(\n\n int64_t height,\n\n int64_t structure,\n\n const at::Tensor& sizes)\n\n : _height(height),\n\n _structure(structure),\n\n _sizes(sizes),\n\n _opt_sizes(impl::construct_efficient_size(_structure, _height, _sizes))\n\n {}\n\n\n\n SizeNode to_size_node() const {\n", "file_path": "nestedtensor/csrc/storage/EfficientSizeNode.h", "rank": 18, "score": 83667.17451975026 }, { "content": " bool _opt_sizes_set = false;\n", "file_path": "nestedtensor/csrc/storage/EfficientSizeNode.h", "rank": 19, "score": 83667.17451975028 }, { "content": "inline bool efficient_size_matches(\n\n EfficientSizeNode& size_node0,\n\n EfficientSizeNode& size_node1) {\n\n if (!efficient_size_structure_matches(size_node0, size_node1)) {\n\n return false;\n\n }\n\n at::Tensor sizes0 = size_node0.sizes();\n\n at::Tensor sizes1 = size_node1.sizes();\n\n return at::equal(sizes0, sizes1);\n", "file_path": "nestedtensor/csrc/storage/EfficientSizeNode.h", "rank": 20, "score": 83667.17451975026 }, { "content": "inline Tensor NestedTensor_to_sparse_csr(Tensor tensor) {\n\n TORCH_CHECK(\n\n get_dim(tensor) == 2,\n\n \"Given tensor must be of dimension 2, got dimension \",\n\n get_dim(tensor));\n\n Tensor values;\n\n if (get_is_contiguous(tensor)) {\n\n values = get_buffer(tensor).reshape({-1});\n\n } else {\n\n values = at::cat(flatten(get_nested_tensor_structure(tensor)));\n\n }\n\n auto tensor_sizes = get_efficient_nested_size(tensor).sizes();\n\n tensor_sizes = tensor_sizes.reshape({-1});\n\n int64_t* tensor_sizes_ptr = tensor_sizes.data_ptr<int64_t>();\n\n at::Tensor crow_indices =\n\n at::cat({torch::tensor({0}), at::cumsum(tensor_sizes, 0)});\n\n std::vector<at::Tensor> col_indices_;\n\n for (int64_t i = 0; i < tensor_sizes.size(0); i++) {\n\n col_indices_.push_back(torch::arange({tensor_sizes_ptr[i]}));\n\n }\n\n at::Tensor col_indices = at::cat(col_indices_);\n\n return at::native::sparse_csr_tensor(\n\n crow_indices, col_indices, values, c10::nullopt, torch::kSparseCsr);\n\n}\n\n\n\ninline std::ostream& operator<<(\n\n std::ostream& out,\n\n const NestedTensorImpl& batch_tensor) {\n\n auto node = batch_tensor.get_structure();\n\n out << \"NESTED_TENSOR\";\n\n apply([&out](at::Tensor tensor) { out << tensor << std::endl; }, node);\n\n out << std::endl;\n\n return out;\n\n}\n\n\n\ntemplate <class FuncPtr, class ParameterTypes>\n\nstruct _Function_trace_wrapper {};\n\n\n\ntemplate <class FuncPtr, class... Parameters>\n\nstruct _Function_trace_wrapper<\n\n FuncPtr,\n\n c10::guts::typelist::typelist<Parameters...>> {\n\n using ReturnType = typename c10::guts::infer_function_traits_t<\n\n typename FuncPtr::FuncType>::return_type;\n\n static ReturnType apply(Parameters... args) {\n\n std::cout << \"Calling \" << typeid(FuncPtr).name() << std::endl;\n\n return (*FuncPtr::func_ptr())(args...);\n\n }\n\n};\n\n\n\ntemplate <class FuncPtr>\n\nconstexpr auto trace(FuncPtr /*func_ptr*/) {\n\n using function_traits =\n\n c10::guts::infer_function_traits_t<typename FuncPtr::FuncType>;\n\n using parameter_types = typename function_traits::parameter_types;\n\n return &_Function_trace_wrapper<FuncPtr, parameter_types>::apply;\n\n}\n\n\n\n#ifdef TRACEPACKED\n\n// #define nt_impl(M, NAME, FUNC) M.impl(NAME, trace(TORCH_FN(FUNC)))\n\n#else\n\n// #define nt_impl(M, NAME, FUNC) M.impl(NAME, trace(TORCH_FN(FUNC)))\n\n#define nt_impl(M, NAME, FUNC) M.impl(NAME, TORCH_FN(FUNC))\n\n#endif\n\n\n", "file_path": "nestedtensor/csrc/nested_tensor_impl.h", "rank": 43, "score": 80874.09685529847 }, { "content": " for (int64_t j = 0; j < _sizes.size(1); j++) {\n", "file_path": "nestedtensor/csrc/storage/EfficientSizeNode.h", "rank": 44, "score": 78588.9184152878 }, { "content": "namespace at {\n\n\n\nusing namespace torch::nested_tensor;\n\n\n\nconstexpr auto NestedTensorKey = DispatchKey::NestedTensor;\n\n\n\nstruct NestedTensorImpl;\n\n\n\ntemplate <class A>\n\nbool is_nested_tensor_impl(A tensor) {\n\n return tensor.unsafeGetTensorImpl()->key_set().has(at::NestedTensorKey);\n\n}\n\n\n\ntemplate <class A, class B>\n\nbool is_nested_tensor_impl(A first, B other) {\n\n return is_nested_tensor_impl(first) && is_nested_tensor_impl(other);\n\n}\n\n\n\ntemplate <class A, class B, class... C>\n\nbool is_nested_tensor_impl(A first, B second, C... other) {\n\n return is_nested_tensor_impl(first, second) &&\n\n is_nested_tensor_impl(other...);\n\n}\n\n\n\ntemplate <class F, class... A>\n\ninline void apply_nested_tensor(F&& fn, A... a) {\n\n // torch_check_tensor_shape_matches(a...);\n\n // torch_check_is_nested_tensor(a...);\n\n apply(std::forward<F>(fn), get_nested_tensor_structure(a)...);\n\n}\n\n\n\nstruct NestedTensorImpl : public c10::TensorImpl {\n\n explicit NestedTensorImpl(std::shared_ptr<NestedTensorStorage> storage);\n\n\n\n#ifndef C10_DISABLE_TENSORIMPL_EXTENSIBILITY\n\n int64_t dim() const override {\n\n TORCH_CHECK(\n\n false, \"dim is disabled. These methods are not virtual in fbcode.\");\n\n }\n\n#endif\n\n#ifndef C10_DISABLE_TENSORIMPL_EXTENSIBILITY\n\n int64_t numel() const override {\n\n TORCH_CHECK(\n\n false, \"numel is disabled. These methods are not virtual in fbcode.\");\n\n }\n\n#endif\n\n#ifndef C10_DISABLE_TENSORIMPL_EXTENSIBILITY\n\n bool is_contiguous(at::MemoryFormat memory_format) const override {\n\n TORCH_CHECK(\n\n false,\n\n \"is_contiguous is disabled. These methods are not virtual in fbcode.\");\n\n }\n\n#endif\n\n TensorNode get_structure() const {\n\n return _storage->get_structure();\n\n }\n\n std::shared_ptr<NestedTensorStorage> get_storage() {\n\n return _storage;\n\n }\n\n int64_t nested_dim() const {\n\n return _storage->nested_size().height();\n\n }\n\n bool is_pinned() const {\n\n return _storage->is_pinned();\n\n }\n\n // This is a C++ representation of a nested list of torch.Sizes\n\n //\n\n // It can never be a list of just numbers, because torch.Size\n\n // is always a list and NestedTensors represent lists of torch.Tensors\n\n //\n\n // Noteworthy cases:\n\n //\n\n // This is an empty list of lists if we construct\n\n // nested_tensor([])\n\n // which is of nested_dim 1, dim 1 and tensor_dim 0\n\n //\n\n // This is a list of empty lists if we construct e.g.\n\n // nested_tensor([torch.tensor(0), torch.tensor(1), ...])\n\n // which is of nested_dim 1, dim 1 and tensor_dim 0\n\n //\n\n // This is a list of list of numbers if we construct e.g.\n\n // nested_tensor([torch.tensor([1]), torch.tensor([2]), ...])\n\n // which is of nested_dim 1, dim 2 and tensor_dim 1\n\n //\n\n // That means, if the list is not empty it is either a list of\n\n // lists of numbers or a list of empty lists.\n\n SizeNode nested_size() const {\n\n return _storage->nested_size().to_size_node();\n\n }\n\n SizeNode nested_stride() const {\n\n return _storage->nested_stride().to_size_node();\n\n }\n\n const std::vector<c10::optional<int64_t>> opt_sizes() const {\n\n return _storage->opt_sizes();\n\n }\n\n#ifndef C10_DISABLE_TENSORIMPL_EXTENSIBILITY\n\n IntArrayRef sizes() const override {\n\n TORCH_CHECK(\n\n false,\n\n \"Internal error: NestedTensorImpl doesn't support sizes. Please file an issue on https://github.com/pytorch/nestedtensor\");\n\n std::vector<int64_t> sizes;\n\n return IntArrayRef(sizes);\n\n }\n\n#endif\n\n#ifndef C10_DISABLE_TENSORIMPL_EXTENSIBILITY\n\n IntArrayRef strides() const override {\n\n TORCH_CHECK(\n\n false,\n\n \"Internal error: NestedTensorImpl doesn't support strides. Please file an issue on https://github.com/pytorch/nestedtensor\");\n\n std::vector<int64_t> strides;\n\n return IntArrayRef(strides);\n\n }\n\n#endif\n\n\n\n private:\n\n std::shared_ptr<NestedTensorStorage> _storage;\n\n};\n\n\n\nint64_t nt_size(Tensor tensor, int64_t dim);\n\n\n\nTensor NestedTensor_to_nested_tensor(\n\n at::Tensor input,\n\n c10::optional<int64_t> dim__);\n\n\n\ninline at::NestedTensorImpl* get_nested_tensor_impl(const at::Tensor tensor) {\n\n if (!is_nested_tensor_impl(tensor)) {\n\n throw std::runtime_error(\"Function requires NestedTensorImpl\");\n\n }\n\n return static_cast<at::NestedTensorImpl*>(tensor.unsafeGetTensorImpl());\n\n}\n\n\n\ntemplate <class A>\n\ninline NestedNode<A> get_nested_tensor_structure(A tensor) {\n\n return NestedNode<A>(std::move(tensor));\n\n}\n\n\n\ntemplate <>\n\ninline TensorNode get_nested_tensor_structure(at::Tensor tensor) {\n\n if (!is_nested_tensor_impl(tensor)) {\n\n return TensorNode(std::move(tensor));\n\n }\n\n return get_nested_tensor_impl(tensor)->get_structure();\n\n}\n\n\n\ninline at::Tensor get_buffer(const at::Tensor& tensor) {\n\n auto storage = get_nested_tensor_impl(tensor)->get_storage();\n\n TORCH_CHECK(\n\n storage.get()->kind() == NestedTensorStorageKind::packed,\n\n \"Given Tensor doesn't have buffer.\");\n\n NestedTensorStorage* storagep = storage.get();\n\n PackedStorage* ps = dynamic_cast<PackedStorage*>(storagep);\n\n return ps->get_buffer();\n\n}\n\n\n\ninline const std::vector<c10::optional<int64_t>> get_opt_sizes(\n\n const at::Tensor& tensor) {\n\n TORCH_CHECK(\n\n is_nested_tensor_impl(tensor), \"Given tensor must be NestedTensor.\");\n\n return get_nested_tensor_impl(tensor)->opt_sizes();\n\n}\n\n\n\ninline const EfficientSizeNode& get_efficient_nested_size(const at::Tensor& tensor) {\n\n TORCH_CHECK(\n\n is_nested_tensor_impl(tensor), \"Given tensor must be NestedTensor.\");\n\n return get_nested_tensor_impl(tensor)->get_storage()->nested_size();\n\n}\n\n\n\ninline const EfficientSizeNode& get_efficient_nested_stride(const at::Tensor& tensor) {\n\n TORCH_CHECK(\n\n is_nested_tensor_impl(tensor), \"Given tensor must be NestedTensor.\");\n\n return get_nested_tensor_impl(tensor)->get_storage()->nested_stride();\n\n}\n\n\n\ninline SizeNode get_nested_size(at::Tensor tensor) {\n\n TORCH_CHECK(\n\n is_nested_tensor_impl(tensor), \"Given tensor must be NestedTensor.\");\n\n return get_nested_tensor_impl(tensor)->nested_size();\n\n}\n\n\n\ninline SizeNode get_nested_stride(at::Tensor tensor) {\n\n TORCH_CHECK(\n\n is_nested_tensor_impl(tensor), \"Given tensor must be NestedTensor.\");\n\n return get_nested_tensor_impl(tensor)->nested_stride();\n\n}\n\n\n\ninline int64_t get_dim(const at::Tensor& tensor) {\n\n if (is_nested_tensor_impl(tensor)) {\n\n return get_nested_tensor_impl(tensor)->get_storage()->dim();\n\n }\n\n return tensor.dim();\n\n}\n\n\n\ninline const caffe2::TypeMeta get_dtype(const at::Tensor& tensor) {\n\n if (is_nested_tensor_impl(tensor)) {\n\n return get_nested_tensor_impl(tensor)->get_storage()->dtype();\n\n }\n\n return tensor.dtype();\n\n}\n\n\n\ninline int64_t get_numel(const at::Tensor& tensor) {\n\n if (is_nested_tensor_impl(tensor)) {\n\n return get_nested_tensor_impl(tensor)->get_storage()->numel();\n\n }\n\n return tensor.numel();\n\n}\n\n\n\nTensor NestedTensor_contiguous(\n\n const Tensor& self,\n\n MemoryFormat memory_format = MemoryFormat::Contiguous);\n\n\n\ninline bool get_is_contiguous(\n\n const at::Tensor& tensor,\n\n at::MemoryFormat memory_format = MemoryFormat::Contiguous) {\n\n if (is_nested_tensor_impl(tensor)) {\n\n return get_nested_tensor_impl(tensor)->get_storage()->is_contiguous(memory_format);\n\n }\n\n return tensor.is_contiguous(memory_format);\n\n}\n\n\n\ninline bool get_is_cuda(\n\n const at::Tensor& tensor,\n\n at::MemoryFormat memory_format = MemoryFormat::Contiguous) {\n\n if (is_nested_tensor_impl(tensor)) {\n\n return get_nested_tensor_impl(tensor)->get_storage()->is_cuda();\n\n }\n\n return tensor.is_cuda();\n\n}\n\n\n\ninline int64_t get_nested_dim(const at::Tensor& tensor) {\n\n TORCH_CHECK(\n\n is_nested_tensor_impl(tensor), \"Given tensor must be NestedTensor.\");\n\n return get_nested_tensor_impl(tensor)->nested_dim();\n\n}\n\n\n\nat::Tensor wrap_tensor_node(NestedTensorImpl);\n\nat::Tensor wrap_tensor_node(TensorNode&&);\n\nstd::vector<at::Tensor> wrap_tensor_node(std::vector<TensorNode>);\n\nat::Tensor wrap_buffer(at::Tensor&&, SizeNode nested_size);\n\nat::Tensor wrap_buffer(\n\n at::Tensor&&,\n\n EfficientSizeNode efficient_nested_size,\n\n EfficientSizeNode efficient_nested_stride);\n\nat::Tensor wrap_buffer(\n\n at::Tensor&&,\n\n EfficientSizeNode efficient_nested_size);\n\n\n\ntemplate <class F, class... A>\n\ninline at::Tensor map_nested_tensor(F&& fn, A... a) {\n\n // torch_check_tensor_shape_matches(a...);\n\n // torch_check_is_nested_tensor(a...);\n\n return wrap_tensor_node(\n\n map(std::forward<F>(fn), get_nested_tensor_structure(a)...));\n\n}\n\n\n\ntemplate <class F, class I, class... A>\n\ninline typename c10::guts::infer_function_traits<F>::type::return_type\n\nreduce_nested_tensor(F&& fn, I init, A... a) {\n\n // torch_check_tensor_shape_matches(a...);\n\n // torch_check_is_nested_tensor(a...);\n\n return reduce(std::forward<F>(fn), init, get_nested_tensor_structure(a)...);\n\n}\n\n\n\ninline std::vector<at::Tensor> flatten_nested_tensor(at::Tensor tensor) {\n\n return flatten(get_nested_tensor_structure(tensor));\n\n}\n\n\n\ninline bool is_tensor_shape(const at::Tensor tensor) {\n\n auto nt = get_nested_tensor_impl(tensor);\n\n for (const auto& size : nt->opt_sizes()) {\n\n if (!size) {\n\n return false;\n\n }\n", "file_path": "nestedtensor/csrc/nested_tensor_impl.h", "rank": 45, "score": 78584.46981133182 }, { "content": " def get_input(self, cuda, n, c, h, w, h_var, w_var, seed):\n\n inputs = []\n\n targets = []\n\n device = 'cpu'\n\n if cuda:\n\n device = 'cuda'\n\n\n\n torch.manual_seed(seed)\n\n random.seed(seed)\n\n if cuda:\n\n torch.cuda.init()\n\n for _ in range(n):\n\n h_res = max(1, int(random.gauss(h, h_var)))\n\n w_res = max(1, int(random.gauss(w, w_var)))\n\n input_i = torch.randn(c, h_res, w_res, device=device)\n\n target_i = torch.randint(1, (h_res, w_res), dtype=torch.int64, device=device)\n\n inputs.append(input_i)\n\n targets.append(target_i)\n\n if cuda:\n\n # Synchronize copy operations so they don't influence the benchmark\n\n torch.cuda.synchronize()\n\n\n", "file_path": "benchmarks/segmentation_layers.py", "rank": 46, "score": 77831.06889795879 }, { "content": " def shape(self):\n", "file_path": "nestedtensor/nested/nested.py", "rank": 47, "score": 77192.35373231568 }, { "content": " def dim(self):\n", "file_path": "nestedtensor/nested/nested.py", "rank": 48, "score": 77134.54118186186 }, { "content": " def size(self, dim=None):\n\n if dim is not None:\n\n return self.size()[dim]\n", "file_path": "nestedtensor/nested/nested.py", "rank": 49, "score": 77019.98931807623 }, { "content": " def tensor_dim(self):\n\n \"\"\"\n\n The tensor dimension of ```self``` NestedTensor.\n\n The tensor dimension is defined as the dimension of the Tensor constiuents.\n\n \"\"\"\n", "file_path": "nestedtensor/nested/nested.py", "rank": 50, "score": 76394.7397243303 }, { "content": " int64_t degree() const {\n\n if (_sizes.dim() == 0) {\n\n return 0;\n\n }\n\n return _sizes.size(0);\n", "file_path": "nestedtensor/csrc/storage/EfficientSizeNode.h", "rank": 51, "score": 76382.27211347519 }, { "content": " for (int64_t i = 0; i < _sizes.size(0); i++) {\n", "file_path": "nestedtensor/csrc/storage/EfficientSizeNode.h", "rank": 52, "score": 76382.27211347519 }, { "content": " const at::Tensor& sizes() const {\n\n return _sizes;\n", "file_path": "nestedtensor/csrc/storage/EfficientSizeNode.h", "rank": 53, "score": 76382.27211347519 }, { "content": " int64_t numel() const {\n\n if (_sizes.dim() == 0 && _structure > 0) {\n\n return _structure;\n\n }\n\n if (_sizes.dim() > 0) {\n\n if (_sizes.numel() == 0) {\n\n return 0;\n\n }\n\n Tensor nt_sizes = at::native::narrow(\n\n _sizes, 1 /* dim */, 0 /* start */, 1 /* length */);\n\n for (int64_t i = 1; i < _sizes.size(1); i++) {\n\n Tensor tmp = at::native::narrow(\n\n _sizes, 1 /* dim */, i /* start */, 1 /* length */);\n\n nt_sizes = nt_sizes * tmp;\n\n }\n\n return nt_sizes.sum().item<int64_t>();\n\n }\n\n return 0;\n", "file_path": "nestedtensor/csrc/storage/EfficientSizeNode.h", "rank": 54, "score": 76382.27211347519 }, { "content": " EfficientSizeNode clone() const {\n\n return EfficientSizeNode(_height, _structure, _sizes.clone());\n", "file_path": "nestedtensor/csrc/storage/EfficientSizeNode.h", "rank": 55, "score": 76382.27211347519 }, { "content": "namespace torch {\n\nnamespace nested_tensor {\n\n\n\nnamespace impl {\n\ninline at::Tensor stack_sizes(SizeNode size_node) {\n\n TORCH_CHECK(size_node.height() == 1, \"stack_sizes: Expected height equals 1.\");\n\n if (size_node.degree() == 0) {\n\n return torch::zeros({}, torch::kInt64);\n\n }\n\n std::vector<SizeNode> unbound_size_node = size_node.unbind();\n\n std::vector<int64_t> result_sizes_vector;\n\n for(int64_t i = 0; i < unbound_size_node.size(); i++) {\n\n std::vector<int64_t> sizes = unbound_size_node[i].payload();\n\n if(i == 0) {\n\n result_sizes_vector.reserve(size_node.degree() * sizes.size());\n\n }\n\n for (size_t j = 0; j < sizes.size(); j++) {\n\n result_sizes_vector.push_back(sizes[j]);\n\n }\n\n }\n\n return torch::tensor(result_sizes_vector, torch::kInt64).reshape({static_cast<int64_t>(size_node.degree()), -1});\n\n}\n\n\n\ninline std::vector<c10::optional<int64_t>> construct_efficient_size(\n\n int64_t out,\n\n int64_t height,\n\n const at::Tensor& sizes) {\n\n std::vector<c10::optional<int64_t>> result;\n\n result.push_back(out);\n\n size_t nested_dim = result.size();\n\n if (sizes.dim() > 0) {\n\n int64_t* sizes_ptr = sizes.data_ptr<int64_t>();\n\n result.resize(nested_dim + sizes.size(1));\n\n for (int64_t i = 0; i < sizes.size(1); i++) {\n\n result[nested_dim + i] = sizes_ptr[i];\n\n }\n\n for (int64_t j = 0; j < sizes.size(1); j++) {\n\n for (int64_t i = 0; i < sizes.size(0); i++) {\n\n if (result[nested_dim + j] &&\n\n (result[nested_dim + j] != sizes_ptr[i * sizes.size(1) + j])) {\n\n result[nested_dim + j] = c10::nullopt;\n\n }\n\n }\n\n }\n\n }\n\n return result;\n\n}\n\n\n\n} // namespace impl\n\n\n\nstruct EfficientSizeNode {\n\n explicit EfficientSizeNode(const SizeNode& size_node)\n\n : _height(size_node.height()),\n\n _structure(size_node.degree()),\n\n _sizes(impl::stack_sizes(size_node)),\n\n _opt_sizes(impl::construct_efficient_size(_structure, _height, _sizes))\n\n {}\n\n\n\n explicit EfficientSizeNode(\n\n int64_t height,\n\n int64_t structure,\n\n const at::Tensor& sizes)\n\n : _height(height),\n\n _structure(structure),\n\n _sizes(sizes),\n\n _opt_sizes(impl::construct_efficient_size(_structure, _height, _sizes))\n\n {}\n\n\n\n SizeNode to_size_node() const {\n\n std::vector<std::vector<int64_t>> _tmp_sizes;\n\n if (_sizes.dim() > 0) {\n\n _tmp_sizes.resize(_sizes.size(0));\n\n int64_t* _sizes_ptr = _sizes.data_ptr<int64_t>();\n\n for (int64_t i = 0; i < _sizes.size(0); i++) {\n\n _tmp_sizes[i].resize(_sizes.size(1));\n\n for (int64_t j = 0; j < _sizes.size(1); j++) {\n\n _tmp_sizes[i][j] = _sizes_ptr[i * _sizes.size(1) + j];\n\n }\n\n }\n", "file_path": "nestedtensor/csrc/storage/EfficientSizeNode.h", "rank": 56, "score": 76382.27211347519 }, { "content": "class NestedTensor(metaclass=NestedTensorMeta):\n\n # The attributes must match across all constiuents\n\n #\n\n # The NestedTensor's attributes then become that of its\n\n # constiuents.\n\n #\n\n # data must be a list of Tensors or NestedTensors\n\n #\n\n # Attributes:\n\n # dim()\n\n # layout\n\n # device\n\n # dtype\n\n # requires_grad\n\n # is_pinned()\n\n # Neighbors may share data, maybe all share data.\n\n # Levels of contiguity\n\n\n\n def __init__(self, impl):\n\n if not torch.ops.nestedtensor.is_nested_tensor_impl(impl):\n\n raise TypeError(\"Got unexpected type \" + str(type(impl)))\n\n self._impl = impl\n\n\n\n def __getattr__(self, name):\n\n if hasattr(self._impl, name):\n\n def _wrapped_fn(*args, **kwargs):\n\n impl_args, impl_kwargs = _filter_impl(args, kwargs)\n\n result = getattr(self._impl, name)(*impl_args, **impl_kwargs)\n\n return _wrap_result(result)\n\n return _wrapped_fn\n\n return self.__dict__[name]\n\n\n\n # --- magic methods ---\n\n\n\n def __hash__(self):\n\n return hash(self._impl)\n\n\n\n def __eq__(self, other):\n\n if isinstance(other, NestedTensor):\n\n return _wrap_result(self._impl.__eq__(other._impl))\n\n return _wrap_result(self._impl.__eq__(other))\n\n\n\n def __ne__(self, other):\n\n if isinstance(other, NestedTensor):\n\n return _wrap_result(self._impl.__ne__(other._impl))\n\n return _wrap_result(self._impl.__ne__(other))\n\n\n\n def __add__(self, other):\n\n if isinstance(other, NestedTensor):\n\n return _wrap_result(self._impl + other._impl)\n\n return _wrap_result(self._impl + other)\n\n\n\n def __radd__(self, other):\n\n assert not isinstance(other, NestedTensor)\n\n return _wrap_result(self._impl + other)\n\n\n\n def __mul__(self, other):\n\n if isinstance(other, NestedTensor):\n\n return _wrap_result(self._impl * other._impl)\n\n return _wrap_result(self._impl * other)\n\n\n\n def __rmul__(self, other):\n\n assert not isinstance(other, NestedTensor)\n\n return _wrap_result(self._impl * other)\n\n\n\n def __sub__(self, other):\n\n if isinstance(other, NestedTensor):\n\n return _wrap_result(self._impl - other._impl)\n\n return _wrap_result(self._impl - other)\n\n\n\n def __rsub__(self, other):\n\n assert not isinstance(other, NestedTensor)\n\n return _wrap_result(other - self._impl)\n\n\n\n def __truediv__(self, other):\n\n if isinstance(other, NestedTensor):\n\n return _wrap_result(self._impl / other._impl)\n\n return _wrap_result(self._impl / other)\n\n\n\n def __floordiv__(self, other):\n\n if isinstance(other, NestedTensor):\n\n return _wrap_result(self._impl // other._impl)\n\n return _wrap_result(self._impl // other)\n\n\n\n def __pow__(self, *args, **kwargs):\n\n impl_args, impl_kwargs = _filter_impl(args, kwargs)\n\n return _wrap_result(self._impl.__pow__(*impl_args, **impl_kwargs))\n\n\n\n def __rpow__(self, exponent):\n\n assert not isinstance(exponent, NestedTensor)\n\n return _wrap_result(torch.pow(exponent, self._impl))\n\n\n\n @property\n\n def shape(self):\n\n return self.size()\n\n\n\n @property\n\n def dtype(self):\n\n \"\"\"\n\n The data type of ```self``` NestedTensor.\n\n \"\"\"\n\n return self._impl.dtype\n\n\n\n @property\n\n def layout(self):\n\n \"\"\"\n\n The layout of ```self``` NestedTensor.\n\n \"\"\"\n\n return self._impl.layout\n\n\n\n @property\n\n def device(self):\n\n \"\"\"\n\n The device of ```self``` NestedTensor.\n\n \"\"\"\n\n return self._impl.device\n\n\n\n @property\n\n def requires_grad(self):\n\n \"\"\"\n\n Is ```True``` if gradients need to be computed for this Tensor.\n\n \"\"\"\n\n return self._impl.requires_grad\n\n\n\n @property\n\n def grad(self):\n\n \"\"\"\n\n This attribute is None by default and becomes a NestedTensor the\n\n first time a call to backward() computes gradients for self.\n\n The attribute will then contain the gradients computed and future\n\n calls to backward() will accumulate (add) gradients into it.\n\n \"\"\"\n\n return _wrap_result(self._impl.grad)\n\n\n\n @property\n\n def data(self):\n\n return _wrap_result(self._impl.data)\n\n\n\n @property\n\n def is_sparse(self):\n\n return self._impl.is_sparse\n\n\n\n def requires_grad_(self, requires_grad=True):\n\n \"\"\"\n\n Is ```True``` if gradients need to be computed for this Tensor.\n\n \"\"\"\n\n return _wrap_result(self._impl.requires_grad_(requires_grad))\n\n\n\n def backward(self, gradient=None, retain_graph=None, create_graph=False):\n\n impl = None\n\n if gradient is not None:\n\n if torch.is_tensor(gradient):\n\n impl = gradient\n\n else:\n\n impl = gradient._impl\n\n self._impl.backward(impl, retain_graph, create_graph)\n\n\n\n def numel(self):\n\n return torch.ops.nestedtensor.get_numel(self._impl)\n\n\n\n def dim(self):\n\n return torch.ops.nestedtensor.get_dim(self._impl)\n\n\n\n def contiguous(self):\n\n if self.is_contiguous():\n\n return self\n\n return _wrap_result(torch.ops.nestedtensor.make_contiguous(self._impl))\n\n\n\n def is_contiguous(self, memory_format=torch.contiguous_format):\n\n if (memory_format == torch.contiguous_format):\n\n return torch.ops.nestedtensor.get_is_contiguous(self._impl, 0)\n\n if (memory_format == torch.channels_last):\n\n return torch.ops.nestedtensor.get_is_contiguous(self._impl, 2)\n\n raise RuntimeError(\"Given memory format \" + str(memory_format) + \" not supported.\")\n\n\n\n def nested_dim(self):\n\n \"\"\"\n\n The nested dimension of ```self``` NestedTensor.\n\n The nested dimension is defined as the level of indexing required\n\n to reach a Tensor constiuent.\n\n \"\"\"\n\n return torch.ops.nestedtensor.nested_dim(self._impl)\n\n\n\n def tensor_dim(self):\n\n \"\"\"\n\n The tensor dimension of ```self``` NestedTensor.\n\n The tensor dimension is defined as the dimension of the Tensor constiuents.\n\n \"\"\"\n\n return self.dim() - self.nested_dim()\n\n\n\n def __len__(self):\n\n \"\"\"\n\n The number of entries in the list ```self``` represents.\n\n \"\"\"\n\n return torch.ops.nestedtensor.len(self._impl)\n\n\n\n def size(self, dim=None):\n\n if dim is not None:\n\n return self.size()[dim]\n\n return tuple(torch.ops.nestedtensor.sizes(self._impl))\n\n\n\n def to(self, *args, **kwargs):\n\n return _wrap_result(self._impl.to(*args, **kwargs))\n\n\n\n def __str__(self):\n\n def _str(x, indent=0, tab=\" \"):\n\n if x.nested_dim() == 0:\n\n return \"\"\n\n s = indent*tab + \"[\\n\"\n\n if x.nested_dim() == 1:\n\n strs = list(map(str, x.unbind()))\n\n strs = list(map(lambda xi: \"\\n\".join(\n\n map(lambda xij: (indent + 1)*tab + xij, xi.split(\"\\n\"))), strs))\n\n s += \",\\n\".join(strs)\n\n else:\n\n s += \",\\n\".join(list(map(\n\n lambda xi: _str(xi, indent + 1), x.unbind())))\n\n s += \"\\n\" + indent * tab + \"]\"\n\n return s\n\n return \"nested_tensor(\" + _str(self) + \")\"\n\n\n\n # --- impl forward ends ---\n\n\n\n # --- dependent on impl ---\n\n\n\n def to_tensor(self, dim=0):\n\n \"\"\"\n\n Not necessarily a view.\n\n \"\"\"\n\n return _wrap_result(torch.ops.nestedtensor.to_tensor(self._impl, dim))\n\n\n\n def __repr__(self):\n\n # TODO: This relies on the fact that repr is not implemented compliant with\n\n # the purpose of repr for torch.Tensor. Therefore returning str is ok.\n\n return self.__str__()\n\n\n\n def nested_size(self, dim=None):\n\n return nestedtensor._C.nested_size(self._impl, dim)\n\n\n\n def nested_stride(self, dim=None):\n\n return nestedtensor._C.nested_stride(self._impl, dim)\n\n\n\n # --- dependent on impl ends ---\n\n\n\n def __torch_function__(self, func, types, args=(), kwargs=None):\n\n impl_args, impl_kwargs = _filter_impl(args, kwargs)\n\n # Need a specialized implementation to support lists of lists of sizes.\n\n # TODO:This was disabled for now to focus on DETR\n\n if func is torch.nn.functional.linear:\n\n return _wrap_result(_nn_functional_linear(*impl_args, **impl_kwargs))\n\n if func is torch.nn.functional.embedding_bag:\n\n return _wrap_result(_nn_functional_embedding_bag(*impl_args, **impl_kwargs))\n\n if func is torch.nn.functional.batch_norm:\n\n return _wrap_result(_nn_functional_batch_norm(*impl_args, **impl_kwargs))\n\n if func is torch.nn.functional.adaptive_avg_pool2d:\n\n return _wrap_result(_nn_functional_adaptive_avg_pool2d(*impl_args, **impl_kwargs))\n\n if func is torch.nn.functional.multi_head_attention_forward:\n\n return _wrap_result(nestedtensor.nn.multi_head_attention_forward(*args, **kwargs))\n\n if func is torch.nn.functional.interpolate:\n\n return _wrap_result(nestedtensor._C.interpolate(*impl_args, **impl_kwargs))\n\n # Need a specialized implementation to dodge call to view in nll_loss\n\n if func is torch.nn.functional.cross_entropy:\n\n return _wrap_result(\n\n nestedtensor._C.cross_entropy(*impl_args, **impl_kwargs)\n\n )\n\n return _wrap_result(func(*impl_args, **impl_kwargs))\n\n\n\n # Might require nonzero\n\n def __bool__(self):\n\n raise NotImplementedError(\n\n \"NestedTensor doesn't support function __bool__\")\n\n\n\n def __getitem__(self, key):\n\n return _wrap_result(nestedtensor._C.get_item(self._impl, key))\n\n\n\n def __iter__(self):\n\n return iter(self.unbind())\n\n\n\n def to_nested_tensor(self, dim=0):\n\n return _wrap_result(torch.ops.nestedtensor.to_nested_tensor(self._impl, dim))\n\n\n\n def to_tensor_list(self):\n\n return torch.ops.nestedtensor.to_tensor_list(self._impl)\n\n\n\n def to_packed_sequence(self):\n\n if not self.dim() == 3 and self.nested_dim() == 1:\n\n raise RuntimeError(\n\n \"NestedTensor should consistent of 2d Tensors of size L x *\")\n\n return torch.nn.utils.rnn.pack_sequence(self.to_tensor_list(), enforce_sorted=False)\n\n\n\n def to_tensor_mask(self, mask_dim=None):\n\n \"\"\"Returns a named tuple TensorMask with two tensors (tensor, mask)\n\n of dim equal to self.dim(). Tensor will contain all data of NestedTensor,\n\n expect that each tensor constiuent has been padded with 0s to equal the\n\n largest Tensor.\n\n\n\n The mask is a bool tensor with a 1-to-1 correspondence to each\n\n element of tensor. If an entry is True, the corresponding element\n\n stores data that is represented by self, if it is False it is a padding\n\n element. These two tensors can be used to contruct a NestedTensor, however,\n\n nested_dim will be lost in this process.\"\"\"\n\n\n\n # Return a tuple of a tensor and a mask that represent the given tensor list\n\n # Returned tensor is always the same no matter what mask_dim was passed.\n\n # If mask_dim was not passed, a mask with the smallest dimensionality would be returned.\n\n # if passed mask_dim is lower than the minimal dimensionality of the mask that can represent\n\n # the data tensor, an error is thrown.\n\n return torch.ops.nestedtensor.to_tensor_mask(self, mask_dim)\n\n\n\n def to_padded_tensor(self, padding=-1):\n\n padding = float(padding)\n\n return torch.ops.nestedtensor.to_padded_tensor(self, padding)\n\n\n\n def to_sparse_csr_tensor(self):\n", "file_path": "nestedtensor/nested/nested.py", "rank": 57, "score": 73153.72366090224 }, { "content": " def test_grad(self):\n\n nt = nestedtensor.nested_tensor([torch.rand(1, 2)])\n\n nt.requires_grad_(True)\n\n a = nt.unbind()[0]\n\n c = nt.sum()\n\n c.backward()\n\n # TODO: Should this have a gradient or not?\n\n # What if nt was constructed with as_nested_tensor vs. nested_tensor\n\n # When calling unbind on a torch.Tensor it doesn't have a grad,\n\n # because it is not a leaf variable. So, if we call unbind\n\n # on a NestedTensor to retrieve one of its constiuents, should\n\n # that be a leaf variable or a view?\n\n # Further, if the NestedTensor has a buffer, the constiuents are\n\n # views of that buffer, so that means unbind() needs to return views\n\n # in either case.\n\n\n\n # When I set requires_grad_ for a NestedTensor and this NestedTensors becomes\n\n # a leaf in an autograd graph it'll have a .grad field. If I call unbind on\n\n # this NestedTensor I should get a list of views. However, if constructed\n\n # with as_nested_tensor I'll get a list of Tensors, i.e. the Tensors used\n\n # to actually build the NestedTensor, which are then all leaf variables\n\n # (since requires_grad_ is forwarded to its constiuents since .grad()\n\n # on the constiuents is used to construct NestedTensor.grad)\n\n\n\n # TODO: Re-enable under autograd\n\n # self.assertIsNotNone(a.grad)\n\n # nt_grad = nt.grad\n\n # # Unbinding the gradient is legitimate for further processing.\n", "file_path": "test/test_nested_tensor_buffer.py", "rank": 58, "score": 71132.81304572315 }, { "content": " def test_detach(self):\n", "file_path": "test/test_nested_tensor_buffer.py", "rank": 59, "score": 71132.81304572315 }, { "content": " def test_contiguous(self):\n\n a = nestedtensor.as_nested_tensor([torch.tensor([1, 2]),\n\n torch.tensor([3, 4]),\n\n torch.tensor([5, 6]),\n\n torch.tensor([7, 8])])\n", "file_path": "test/test_nested_tensor_class.py", "rank": 60, "score": 71127.17231784131 }, { "content": "class TestContiguous(TestCase):\n\n\n\n @unittest.skip(\"Nested dim currently restricted to 1.\")\n\n def test_contiguous_nested(self):\n\n for _ in range(1, 10):\n\n # data = gen_nested_list(1, 2, 3, size_low=1, size_high=3)\n\n data = [[torch.rand(1, 2), torch.rand(3, 4)], [torch.rand(5, 6)]]\n\n nt = ntnt_nograd(data)\n\n self.assertTrue(nt.is_contiguous())\n\n # buf = nt.flatten()\n\n self.assertEqual(nt, nt)\n\n a = nt + nt\n\n nt.cos_()\n\n nt.cos()\n\n\n\n def test_contiguous(self):\n\n a = nestedtensor.as_nested_tensor([torch.tensor([1, 2]),\n\n torch.tensor([3, 4]),\n\n torch.tensor([5, 6]),\n\n torch.tensor([7, 8])])\n", "file_path": "test/test_nested_tensor_class.py", "rank": 61, "score": 71127.17231784131 }, { "content": " def test_dim(self):\n\n for constructor in _iter_constructors():\n\n a1 = constructor([])\n\n self.assertEqual(a1.dim(), 1)\n\n a1 = constructor([torch.tensor(3.)])\n\n self.assertEqual(a1.dim(), 1)\n\n a1 = constructor([torch.tensor([1, 2, 3, 4])])\n", "file_path": "test/test_nested_tensor_class.py", "rank": 62, "score": 71071.22234048056 }, { "content": " def test_size(self):\n\n for constructor in _iter_constructors():\n\n a = constructor([])\n\n self.assertEqual(a.size(), (0,))\n\n\n\n a = constructor([torch.tensor(1)])\n\n self.assertEqual(a.size(), (1,))\n\n\n\n a = constructor([torch.tensor(1), torch.tensor(2)])\n\n self.assertEqual(a.size(), (2,))\n\n\n\n # TODO: Currently only supporting nested dim 1\n\n # a = constructor([[torch.rand(1, 8),\n\n # torch.rand(3, 8)],\n\n # [torch.rand(7, 8)]])\n\n # self.assertEqual(a.size(), (2, None, None, 8))\n\n\n\n a = constructor([torch.rand(1, 2),\n\n torch.rand(1, 8)])\n\n self.assertEqual(a.size(), (2, 1, None))\n\n\n\n a = constructor([torch.rand(3, 4),\n\n torch.rand(5, 4)])\n", "file_path": "test/test_nested_tensor_class.py", "rank": 63, "score": 70958.02005241338 }, { "content": " def test_pin_memory(self):\n\n # Check if it can be applied widely\n\n nt = utils.gen_nested_tensor(1, 4, 3)\n\n nt1 = nt.pin_memory()\n\n\n\n # Make sure it's actually a copy\n\n self.assertFalse(nt.is_pinned())\n\n self.assertTrue(nt1.is_pinned())\n\n a1 = torch.randn(1, 2)\n\n a2 = torch.randn(2, 3)\n\n nt2 = nestedtensor.as_nested_tensor([a1, a2])\n\n self.assertFalse(a1.is_pinned())\n\n self.assertFalse(a2.is_pinned())\n\n\n\n # Double check property transfers\n\n nt3 = nt2.pin_memory()\n\n self.assertFalse(nt2.is_pinned())\n\n self.assertTrue(nt3.is_pinned())\n\n\n\n # Check whether pinned memory is applied to constiuents\n\n # and relevant constiuents only.\n\n a3, a4 = nt3.unbind()\n\n a5, a6 = nt2.unbind()\n\n self.assertFalse(a1.is_pinned())\n\n self.assertFalse(a2.is_pinned())\n\n self.assertTrue(a3.is_pinned())\n\n self.assertTrue(a4.is_pinned())\n\n self.assertFalse(a5.is_pinned())\n", "file_path": "test/test_nested_tensor_class.py", "rank": 64, "score": 69219.91665437368 }, { "content": " def test_requires_grad(self):\n\n _test_property(self, lambda x: x.requires_grad)\n\n tensors = [torch.randn(1, 8),\n\n torch.randn(3, 8),\n\n torch.randn(7, 8)]\n\n a1 = ntnt_nograd(tensors)\n", "file_path": "test/test_nested_tensor_class.py", "rank": 65, "score": 69208.16755237045 }, { "content": " def test_contiguous_nested(self):\n\n for _ in range(1, 10):\n\n # data = gen_nested_list(1, 2, 3, size_low=1, size_high=3)\n\n data = [[torch.rand(1, 2), torch.rand(3, 4)], [torch.rand(5, 6)]]\n\n nt = ntnt_nograd(data)\n\n self.assertTrue(nt.is_contiguous())\n\n # buf = nt.flatten()\n\n self.assertEqual(nt, nt)\n\n a = nt + nt\n\n nt.cos_()\n", "file_path": "test/test_nested_tensor_class.py", "rank": 66, "score": 69197.1362684671 }, { "content": " def test_mean_dim(self):\n\n # self._test_reduce_dim(torch.mean, True)\n", "file_path": "test/test_nested_tensor_reduce.py", "rank": 67, "score": 69142.7044939218 }, { "content": " def test_sum_dim(self):\n\n # self._test_reduce_dim(torch.sum, True)\n", "file_path": "test/test_nested_tensor_reduce.py", "rank": 68, "score": 69142.7044939218 }, { "content": " def test_max_dim(self):\n\n self._test_reduce_dim(lambda x, dim, keepdim=False: x.max(\n", "file_path": "test/test_nested_tensor_reduce.py", "rank": 69, "score": 69142.70449392182 }, { "content": " def test_unbind_dim(self):\n\n # Unbinding across nested dimensions or tensors dimensions\n\n # is akin splitting up the tree across a level.\n\n\n\n def _test_fn(unbind_fn):\n\n # nt = nestedtensor.nested_tensor([])\n\n # self.assertEqual(unbind_fn(nt, 0), ())\n\n # self.assertRaises(IndexError, lambda: unbind_fn(nt, 1))\n\n\n\n a = torch.rand(3, 2)\n\n nt = nestedtensor.nested_tensor([a])\n\n # self.assertEqual(unbind_fn(nt, 0), (a,))\n\n result = (\n\n nestedtensor.nested_tensor([unbind_fn(a, 0)[0]]),\n\n nestedtensor.nested_tensor([unbind_fn(a, 0)[1]]),\n\n nestedtensor.nested_tensor([unbind_fn(a, 0)[2]]))\n\n # print('unbind_fn: ', unbind_fn)\n\n for x, y in zip(unbind_fn(nt, 1), result):\n\n # print('x: ', type(x), ' - y: ', type(y))\n\n self.assertEqual(x, y, ignore_contiguity=True)\n\n result = (\n\n nestedtensor.nested_tensor([unbind_fn(a, 1)[0]]),\n\n nestedtensor.nested_tensor([unbind_fn(a, 1)[1]]))\n\n for x, y in zip(unbind_fn(nt, 2), result):\n\n self.assertEqual(x, y, ignore_contiguity=True)\n\n\n\n b = torch.rand(2, 3)\n\n nt = nestedtensor.nested_tensor([a, b])\n\n self.assertEqual(unbind_fn(nt, 0), (a, b))\n\n result = (\n\n nestedtensor.nested_tensor(\n\n [unbind_fn(a, 0)[0], unbind_fn(b, 0)[0]]),\n\n nestedtensor.nested_tensor(\n\n [unbind_fn(a, 0)[1], unbind_fn(b, 0)[1]]),\n\n nestedtensor.nested_tensor([unbind_fn(a, 0)[2]]))\n\n for x, y in zip(unbind_fn(nt, 1), result):\n\n self.assertEqual(x, y, ignore_contiguity=True)\n\n # TODO: Add more tensors and unbind across more dimensions to create mixing\n\n\n\n c = torch.rand(4, 3)\n\n # TODO: Currently only supporting nested dim 1\n\n # nt = nestedtensor.nested_tensor([[a], [b, c]])\n\n # nt_a, nt_b = unbind_fn(nt, 0)\n\n # self.assertEqual(nt_a, nestedtensor.nested_tensor(\n\n # [a]), ignore_contiguity=True)\n\n # self.assertEqual(nt_b, nestedtensor.nested_tensor(\n\n # [b, c]), ignore_contiguity=True)\n\n # result = (\n\n # nestedtensor.nested_tensor([a, b]),\n\n # nestedtensor.nested_tensor([c]))\n\n # for x, y in zip(unbind_fn(nt, 1), result):\n\n # self.assertEqual(x, y, ignore_contiguity=True)\n\n _test_fn(lambda x, dim: x.unbind(dim))\n", "file_path": "test/test_nested_tensor_class.py", "rank": 70, "score": 69142.7044939218 }, { "content": " def test_dim_nested(self):\n\n for constructor in _iter_constructors():\n\n a1 = constructor([\n\n [torch.tensor([1, 2, 3, 4])],\n\n [torch.tensor([5, 6, 7, 8]), torch.tensor([9, 0, 0, 0])]\n\n ])\n", "file_path": "test/test_nested_tensor_class.py", "rank": 71, "score": 69142.7044939218 }, { "content": " def _test_reduce_dim(self, fn, associative=True, test_keep_dim=True, test_multi_dim=True):\n\n pass\n\n # Currently only supporting nested dim 1.\n\n # t0 = torch.arange(9).float().reshape(3, 3)\n\n # t1 = torch.arange(6).float().reshape(2, 3)\n\n # t2 = torch.arange(9).float().reshape(3, 3)\n\n # ts = [[t0, t1], [t2, t1]]\n\n # nt = ntnt(ts)\n\n # if associative and test_multi_dim:\n\n # t01 = fn(torch.stack([fn(t0, 0), fn(t1, 0)]), 0)\n\n # t21 = fn(torch.stack([fn(t2, 0), fn(t1, 0)]), 0)\n\n # t02 = fn(torch.stack([fn(t0, 0), fn(t2, 0)]), 0)\n\n # t11 = fn(torch.stack([fn(t1, 0), fn(t1, 0)]), 0)\n\n # self.assertEqual(ntnt([t01, t21]), fn(nt, (1, 2)))\n\n # self.assertEqual(ntnt([t02, t11]), fn(nt, (0, 2)))\n\n\n\n # if test_keep_dim:\n\n # t01 = fn(torch.stack([fn(t0, 0), fn(t1, 0)]), 0, True)\n\n # t21 = fn(torch.stack([fn(t2, 0), fn(t1, 0)]), 0, True)\n\n # t02 = fn(torch.stack([fn(t0, 0), fn(t2, 0)]), 0, True)\n\n # t11 = fn(torch.stack([fn(t1, 0), fn(t1, 0)]), 0, True)\n\n # self.assertEqual(ntnt([[t01, t21]]), fn(nt, (1, 2), True))\n\n # self.assertEqual(ntnt([[t02, t11]]), fn(nt, (0, 2), True))\n\n\n\n # Currently only supporting nested dim 1.\n\n # ts = [[t0, t1], [t2]]\n\n # nt = ntnt(ts)\n\n # self.assertRaises(RuntimeError, lambda: fn(nt, 0))\n\n # self.assertRaises(RuntimeError, lambda: fn(nt, 1))\n\n # self.assertEqual(ntnt([[fn(t0, 0), fn(t1, 0)],\n\n # [fn(t2, 0)]]), fn(nt, 2))\n\n # self.assertEqual(ntnt([[fn(t0, 1), fn(t1, 1)],\n\n # [fn(t2, 1)]]), fn(nt, 3))\n\n # if test_keep_dim:\n\n # self.assertEqual(ntnt([[fn(t0, 0, True), fn(t1, 0, True)],\n\n # [fn(t2, 0, True)]]), fn(nt, 2, True))\n\n # self.assertEqual(ntnt([[fn(t0, 1, True), fn(t1, 1, True)],\n\n # [fn(t2, 1, True)]]), fn(nt, 3, True))\n", "file_path": "test/test_nested_tensor_reduce.py", "rank": 72, "score": 69142.70449392182 }, { "content": " def test_nested_dim(self):\n\n for constructor in _iter_constructors():\n\n nt = constructor([torch.tensor(3)])\n\n for i in range(2, 5):\n\n nt = utils.gen_nested_tensor(i, i, 3, constructor=constructor)\n", "file_path": "test/test_nested_tensor_class.py", "rank": 73, "score": 69142.7044939218 }, { "content": " def test_var_dim(self):\n\n t0 = torch.arange(9).float().reshape(3, 3)\n\n t1 = torch.arange(6).float().reshape(2, 3)\n\n t2 = (torch.arange(9).float().reshape(3, 3) - 9).pow(2)\n\n t0 = torch.randn(3, 3)\n\n t1 = torch.randn(2, 3)\n\n t2 = torch.randn(3, 3)\n\n t3 = torch.randn(2, 3)\n\n\n\n ts = [t0, t1]\n\n nt = ntnt(ts)\n\n res = torch.var(nt, 1)\n\n self.assertEqual(\n\n ntnt([torch.var(t0, 0), torch.var(t1, 0)]), res)\n\n self.assertRaises(RuntimeError, lambda: res.sum().backward())\n\n\n\n res = torch.var(nt, 2)\n\n self.assertEqual(\n\n ntnt([torch.var(t0, 1), torch.var(t1, 1)]), res)\n\n self.assertRaises(RuntimeError, lambda: res.sum().backward())\n\n\n\n ts = [t0, t2]\n\n nt = ntnt(ts)\n\n res = torch.var(nt, 0)\n\n self.assertEqual(torch.stack(ts).var(0), res)\n\n self.assertRaises(RuntimeError, lambda: res.sum().backward())\n\n\n\n res = torch.var(nt, 1)\n\n self.assertEqual(\n\n ntnt([torch.var(t0, 0), torch.var(t2, 0)]), res)\n\n self.assertRaises(RuntimeError, lambda: res.sum().backward())\n\n\n\n res = torch.var(nt, 2)\n\n self.assertEqual(\n\n ntnt([torch.var(t0, 1), torch.var(t2, 1)]), res)\n\n self.assertRaises(RuntimeError, lambda: res.sum().backward())\n\n\n\n self.assertEqual(torch.stack(ts).var(\n\n (0, 1), unbiased=False), torch.var(nt, (0, 1), unbiased=False))\n\n\n\n nt = ntnt([t0, t1])\n\n self.assertRaisesRegex(\n\n RuntimeError, \"Can only reduce across nested dimensions of Tensor compliant shapes.\", lambda: torch.var(nt, 0))\n\n\n\n # Currently only supporting nested dim 1.\n\n # nt = ntnt([[t0, t1], [t2, t3]])\n\n # self.assertRaisesRegex(\n\n # RuntimeError, \"Can only reduce across nested dimension 0.\", lambda: torch.var(nt, 1))\n\n # self.assertRaisesRegex(\n\n # RuntimeError, \"Can only reduce across nested dimensions if given nested tensor is of nested dimension 1.\", lambda: torch.var(nt, 0))\n\n # t0_var0 = torch.var(t0, 0)\n\n # t1_var0 = torch.var(t1, 0)\n\n # t2_var0 = torch.var(t2, 0)\n\n # t3_var0 = torch.var(t3, 0)\n\n # self.assertEqual(\n\n # ntnt([[t0_var0, t1_var0], [t2_var0, t3_var0]]), torch.var(nt, 2))\n\n # t0_var1 = torch.var(t0, 1)\n\n # t1_var1 = torch.var(t1, 1)\n\n # t2_var1 = torch.var(t2, 1)\n\n # t3_var1 = torch.var(t3, 1)\n\n # self.assertEqual(\n", "file_path": "test/test_nested_tensor_reduce.py", "rank": 74, "score": 69142.70449392182 }, { "content": " def test_element_size(self):\n\n for constructor in _iter_constructors():\n\n nt1 = constructor([])\n\n self.assertEqual(nt1.element_size(), torch.randn(1).element_size())\n\n a = torch.randn(4).int()\n\n nt2 = constructor([a])\n", "file_path": "test/test_nested_tensor_class.py", "rank": 75, "score": 69032.57395030506 }, { "content": " def test_sizes_equal(self):\n\n a = ntnt([torch.arange(2).reshape(1, 2),\n\n torch.arange(2).reshape(1, 2) + 2])\n\n b = ntnt([torch.arange(2).reshape(2),\n\n torch.arange(2).reshape(2) + 2])\n\n self.assertEqual(True, nestedtensor.nested.nested.sizes_equal(a, a))\n\n self.assertEqual(False, nestedtensor.nested.nested.sizes_equal(a, b))\n\n self.assertEqual(False, nestedtensor.nested.nested.sizes_equal(b, a))\n\n self.assertEqual(\n\n False, nestedtensor.nested.nested.sizes_equal(torch.randn(1, 2), a))\n\n self.assertEqual(\n\n False, nestedtensor.nested.nested.sizes_equal(a, torch.randn(1, 2)))\n\n self.assertEqual(True, nestedtensor.nested.nested.sizes_equal(\n\n torch.randn(1, 2), torch.randn(1, 2)))\n\n self.assertEqual(False, nestedtensor.nested.nested.sizes_equal(\n\n torch.randn(2, 1), torch.randn(1, 2)))\n", "file_path": "test/test_nested_tensor_reduce.py", "rank": 76, "score": 69032.57395030506 }, { "content": " def test_sum_to_size(self):\n\n a = ntnt([torch.arange(2).reshape(1, 2),\n\n torch.arange(2).reshape(2, 1) + 2])\n\n # b = ntnt([torch.randn(1), torch.randn(1)])\n\n # print(a)\n\n # print(nestedtensor.nested.nested.sum_to(a._impl, a.nested_size()))\n\n # print(nestedtensor.nested.nested.sum_to(a._impl, b.nested_size()))\n\n # print(nestedtensor.nested.nested.sum_to(a._impl, [1, 2]))\n\n print(a)\n\n # print(nestedtensor.nested.nested.sum_to(a, (2,)))\n\n # print(nestedtensor.nested.nested.sum_to(a, (2, 2)))\n\n a = ntnt([torch.arange(2).reshape(1, 2),\n\n torch.arange(2).reshape(1, 2) + 2])\n\n b = ntnt([torch.arange(2).reshape(2),\n\n torch.arange(2).reshape(2) + 2])\n\n print(nestedtensor.nested.nested.sum_to_size(a, a))\n\n print('a')\n\n print(a)\n\n print(nestedtensor.nested.nested.sum_to_size(a, b))\n\n # self.assertRaises(\n\n # RuntimeError, lambda: nestedtensor.nested.nested.sum_to_size(a, b))\n\n self.assertRaises(RuntimeError, lambda: nestedtensor.nested.nested.sum_to_size(\n\n torch.randn(1, 2), a))\n\n print(nestedtensor.nested.nested.sum_to_size(a, torch.randn(1, 2)))\n\n print(nestedtensor.nested.nested.sum_to_size(a, torch.randn(1, 2)).shape)\n\n # b = ntnt([torch.randn(1), torch.randn(1)])\n", "file_path": "test/test_nested_tensor_reduce.py", "rank": 77, "score": 69032.57395030506 }, { "content": " def test_nested_size(self):\n\n for constructor in _iter_constructors():\n\n a = constructor([])\n\n self.assertEqual(len(a.nested_size()), 0)\n\n self.assertRaises(RuntimeError, lambda: a.nested_size()[0])\n\n\n\n a = constructor([torch.tensor(1)])\n\n self.assertEqual(len(a.nested_size()), 1)\n\n self.assertEqual(a.nested_size()[0], torch.Size([]))\n\n self.assertEqual(a.nested_size(0), 1)\n\n self.assertRaises(IndexError, lambda: a.nested_size(1))\n\n\n\n a = constructor([torch.randn(1)])\n\n self.assertEqual(a.nested_size()[0], torch.Size([1]))\n\n self.assertEqual(a.nested_size()[0][0], 1)\n\n self.assertEqual(a.nested_size(0), 1)\n\n self.assertEqual(a.nested_size(1), (1,))\n\n self.assertRaises(IndexError, lambda: a.nested_size(2))\n\n\n\n a = constructor([torch.randn(1, 2)])\n\n self.assertEqual(a.nested_size()[0], torch.Size([1, 2]))\n\n self.assertEqual(a.nested_size(0), 1)\n\n self.assertEqual(a.nested_size(1), (1,))\n\n self.assertEqual(a.nested_size(2), (2,))\n\n self.assertRaises(IndexError, lambda: a.nested_size(3))\n\n\n\n # Make sure object is not bound to life-time of NestedTensor instance\n\n b = a.nested_size()\n\n del a\n\n self.assertEqual(len(b), 1)\n\n self.assertEqual(b[0], torch.Size([1, 2]))\n\n self.assertEqual(b[0][0], 1)\n", "file_path": "test/test_nested_tensor_class.py", "rank": 78, "score": 69032.57395030506 }, { "content": " def test_ntftm_empty_error(self):\n\n tensor = torch.tensor([])\n\n mask = torch.tensor([True])\n\n self.assertRaisesRegex(RuntimeError,\n\n \"Data tensor can't be emtpy if a mask has values.\",\n\n lambda: nt.nested_tensor_from_tensor_mask(tensor, mask))\n\n\n\n tensor = torch.tensor([1])\n\n mask = torch.tensor([])\n\n self.assertRaisesRegex(RuntimeError,\n\n \"Mask tensor can't be emtpy if a data tensor has values.\",\n", "file_path": "test/test_nested_tensor_masking.py", "rank": 79, "score": 67374.41886286388 }, { "content": " def test_nested_size_nested(self):\n\n for constructor in _iter_constructors():\n\n a = constructor(\n\n [[torch.randn(1)], [torch.randn(2), torch.randn(1)]])\n\n self.assertEqual(a.nested_size()[0][0], torch.Size([1]))\n\n self.assertEqual(a.nested_size()[1][0], torch.Size([2]))\n\n self.assertEqual(a.nested_size()[1][1], torch.Size([1]))\n\n self.assertEqual(a.nested_size(0), 2)\n\n self.assertEqual(a.nested_size(1), (1, 2))\n\n self.assertEqual(a.nested_size(2), ((1,), (2, 1)))\n\n self.assertRaises(IndexError, lambda: a.nested_size(3))\n\n\n\n a = constructor([[torch.tensor(1)],\n\n [torch.tensor(2), torch.tensor(1)]])\n\n self.assertEqual(a.nested_size()[0][0], torch.Size([]))\n\n self.assertEqual(a.nested_size()[1][0], torch.Size([]))\n\n self.assertEqual(a.nested_size()[1][1], torch.Size([]))\n\n self.assertEqual(a.nested_size(0), 2)\n\n self.assertEqual(a.nested_size(1), (1, 2))\n", "file_path": "test/test_nested_tensor_class.py", "rank": 80, "score": 67208.86128343882 }, { "content": " def test_ntftm_single_scalar_error(self):\n\n tensor = torch.tensor(1)\n\n mask = torch.tensor(True)\n\n self.assertRaisesRegex(RuntimeError, \"Can't construct nested tensor from a scalar.\",\n", "file_path": "test/test_nested_tensor_masking.py", "rank": 81, "score": 65640.32317468847 }, { "content": " def test_autograd_size_equal_nt(self):\n\n # TODO: Right now this only exercises the mechanisms\n\n a = ntnt([torch.randn(1, 2)])\n\n s = a.sum()\n\n s.backward()\n\n\n\n a = ntnt([torch.randn(1, 2), torch.randn(2, 1)])\n\n b = ntnt([torch.randn(1, 2), torch.randn(2, 1)])\n\n c = a + b\n\n c.backward(a)\n\n\n\n a = ntnt([torch.randn(1, 2), torch.randn(2, 1)])\n\n t0 = torch.randn(2, 2, requires_grad=True)\n\n d = t0 + a\n\n d.sum().backward()\n\n\n\n t1 = torch.randn(1, 2, requires_grad=True)\n\n t1.sum().backward()\n\n\n\n e = ntnt([torch.randn(1, 2), torch.randn(2, 1)])\n\n a0 = a + b\n\n a1 = a0 + e\n", "file_path": "test/test_nested_tensor_autograd.py", "rank": 82, "score": 65479.02674793042 }, { "content": "import torch\n\nimport nestedtensor\n\nimport unittest\n\nfrom utils_test_case import TestCase\n\n\n\nfrom nestedtensor.nested.nested import native_is_expandable_to\n\n\n\n\n\ndef ntnt(x): return nestedtensor.nested_tensor(x, requires_grad=False)\n\n\n\n\n\ndef _flatten_list(ts):\n\n if not isinstance(ts, list):\n\n return [ts]\n\n return sum(map(_flatten_list, ts), [])\n\n\n\n\n\ndef _flatten_nt(nt):\n\n if not isinstance(nt, nestedtensor.NestedTensor):\n\n return [nt]\n\n return sum(map(_flatten_nt, nt.unbind()), [])\n\n\n\n\n\nclass TestReduce(TestCase):\n\n\n\n def _test_reduce_dim(self, fn, associative=True, test_keep_dim=True, test_multi_dim=True):\n\n pass\n\n # Currently only supporting nested dim 1.\n\n # t0 = torch.arange(9).float().reshape(3, 3)\n\n # t1 = torch.arange(6).float().reshape(2, 3)\n\n # t2 = torch.arange(9).float().reshape(3, 3)\n\n # ts = [[t0, t1], [t2, t1]]\n\n # nt = ntnt(ts)\n\n # if associative and test_multi_dim:\n\n # t01 = fn(torch.stack([fn(t0, 0), fn(t1, 0)]), 0)\n\n # t21 = fn(torch.stack([fn(t2, 0), fn(t1, 0)]), 0)\n\n # t02 = fn(torch.stack([fn(t0, 0), fn(t2, 0)]), 0)\n\n # t11 = fn(torch.stack([fn(t1, 0), fn(t1, 0)]), 0)\n\n # self.assertEqual(ntnt([t01, t21]), fn(nt, (1, 2)))\n\n # self.assertEqual(ntnt([t02, t11]), fn(nt, (0, 2)))\n\n\n\n # if test_keep_dim:\n\n # t01 = fn(torch.stack([fn(t0, 0), fn(t1, 0)]), 0, True)\n\n # t21 = fn(torch.stack([fn(t2, 0), fn(t1, 0)]), 0, True)\n\n # t02 = fn(torch.stack([fn(t0, 0), fn(t2, 0)]), 0, True)\n\n # t11 = fn(torch.stack([fn(t1, 0), fn(t1, 0)]), 0, True)\n\n # self.assertEqual(ntnt([[t01, t21]]), fn(nt, (1, 2), True))\n\n # self.assertEqual(ntnt([[t02, t11]]), fn(nt, (0, 2), True))\n\n\n\n # Currently only supporting nested dim 1.\n\n # ts = [[t0, t1], [t2]]\n\n # nt = ntnt(ts)\n\n # self.assertRaises(RuntimeError, lambda: fn(nt, 0))\n\n # self.assertRaises(RuntimeError, lambda: fn(nt, 1))\n\n # self.assertEqual(ntnt([[fn(t0, 0), fn(t1, 0)],\n\n # [fn(t2, 0)]]), fn(nt, 2))\n\n # self.assertEqual(ntnt([[fn(t0, 1), fn(t1, 1)],\n\n # [fn(t2, 1)]]), fn(nt, 3))\n\n # if test_keep_dim:\n\n # self.assertEqual(ntnt([[fn(t0, 0, True), fn(t1, 0, True)],\n\n # [fn(t2, 0, True)]]), fn(nt, 2, True))\n\n # self.assertEqual(ntnt([[fn(t0, 1, True), fn(t1, 1, True)],\n\n # [fn(t2, 1, True)]]), fn(nt, 3, True))\n\n # self.assertRaises(IndexError, lambda: fn(nt, 4))\n\n\n\n def test_cumsum(self):\n\n self._test_reduce_dim(torch.cumsum, False, False)\n\n\n\n def _test_allreduce(self, fn, with_grad=False):\n\n def test(ts):\n\n if with_grad:\n\n nt = ntnt(ts)\n\n else:\n\n nt = nestedtensor.nested_tensor(ts)\n\n t = fn(nt)\n\n flat_ts = _flatten_list(ts)\n\n a = torch.cat([x.reshape(-1) for x in flat_ts])\n\n a_res = fn(a)\n\n # print(\"_0_\")\n\n # print(t)\n\n # print(a_res)\n\n self.assertEqual(t, a_res)\n\n if with_grad:\n\n a_res.backward()\n\n t.backward()\n\n nt_grads = _flatten_nt(nt.grad)\n\n for a, b in zip(nt_grads, flat_ts):\n\n # print(a)\n\n # print(b.grad)\n\n # print(\"--\")\n\n self.assertEqual(a, b.grad)\n\n\n\n def gen_ts():\n\n t0 = torch.randn(4, 3, requires_grad=True)\n\n t1 = torch.randn(2, 3, requires_grad=True)\n\n t2 = torch.randn(3, 4, requires_grad=True)\n\n t3 = torch.randn(3, 4, requires_grad=True)\n\n t4 = torch.randn(3, 4, requires_grad=True)\n\n return t0, t1, t2, t3, t4\n\n\n\n t0, t1, t2, t3, t4 = gen_ts()\n\n test([t0])\n\n t0, t1, t2, t3, t4 = gen_ts()\n\n test([t0, t1])\n\n t0, t1, t2, t3, t4 = gen_ts()\n\n test([t0, t1, t2])\n\n t0, t1, t2, t3, t4 = gen_ts()\n\n test([t0, t1, t2, t3])\n\n # Currently only supporting nested dim 1.\n\n # t0, t1, t2, t3, t4 = gen_ts()\n\n # test([[t0], [t1, t2]])\n\n # t0, t1, t2, t3, t4 = gen_ts()\n\n # test([[t0, t1], [t2]])\n\n # t0, t1, t2, t3, t4 = gen_ts()\n\n # test([[t0, t1], [t2, t3]])\n\n # t0, t1, t2, t3, t4 = gen_ts()\n\n # test([[t0, t1], [t2, t3], [t4]])\n\n\n\n def test_sum_all(self):\n\n # self._test_allreduce(lambda x: x.sum(), True)\n\n self._test_allreduce(lambda x: x.sum(), False)\n\n\n\n def test_sum_dim(self):\n\n # self._test_reduce_dim(torch.sum, True)\n\n self._test_reduce_dim(torch.sum, False)\n\n\n\n def test_max_all(self):\n\n self._test_allreduce(lambda x: x.max())\n\n\n\n def test_max_dim(self):\n\n self._test_reduce_dim(lambda x, dim, keepdim=False: x.max(\n\n dim, keepdim)[0], True, test_multi_dim=False)\n\n\n\n def test_mean_all(self):\n\n self._test_allreduce(lambda x: x.mean())\n\n\n\n def test_mean_dim(self):\n\n # self._test_reduce_dim(torch.mean, True)\n\n self._test_reduce_dim(torch.mean, False)\n\n\n\n def test_prod(self):\n\n self._test_allreduce(lambda x: x.prod())\n\n\n\n def test_var(self):\n\n # self._test_allreduce(lambda x: x.var(unbiased=False), True)\n\n self._test_allreduce(lambda x: x.var(unbiased=False), False)\n\n self._test_allreduce(lambda x: x.var(unbiased=True))\n\n\n\n def test_var_dim(self):\n\n t0 = torch.arange(9).float().reshape(3, 3)\n\n t1 = torch.arange(6).float().reshape(2, 3)\n\n t2 = (torch.arange(9).float().reshape(3, 3) - 9).pow(2)\n\n t0 = torch.randn(3, 3)\n\n t1 = torch.randn(2, 3)\n\n t2 = torch.randn(3, 3)\n\n t3 = torch.randn(2, 3)\n\n\n\n ts = [t0, t1]\n\n nt = ntnt(ts)\n\n res = torch.var(nt, 1)\n\n self.assertEqual(\n\n ntnt([torch.var(t0, 0), torch.var(t1, 0)]), res)\n\n self.assertRaises(RuntimeError, lambda: res.sum().backward())\n\n\n\n res = torch.var(nt, 2)\n\n self.assertEqual(\n\n ntnt([torch.var(t0, 1), torch.var(t1, 1)]), res)\n\n self.assertRaises(RuntimeError, lambda: res.sum().backward())\n\n\n\n ts = [t0, t2]\n\n nt = ntnt(ts)\n\n res = torch.var(nt, 0)\n\n self.assertEqual(torch.stack(ts).var(0), res)\n\n self.assertRaises(RuntimeError, lambda: res.sum().backward())\n\n\n\n res = torch.var(nt, 1)\n\n self.assertEqual(\n\n ntnt([torch.var(t0, 0), torch.var(t2, 0)]), res)\n\n self.assertRaises(RuntimeError, lambda: res.sum().backward())\n\n\n\n res = torch.var(nt, 2)\n\n self.assertEqual(\n\n ntnt([torch.var(t0, 1), torch.var(t2, 1)]), res)\n\n self.assertRaises(RuntimeError, lambda: res.sum().backward())\n\n\n\n self.assertEqual(torch.stack(ts).var(\n\n (0, 1), unbiased=False), torch.var(nt, (0, 1), unbiased=False))\n\n\n\n nt = ntnt([t0, t1])\n\n self.assertRaisesRegex(\n\n RuntimeError, \"Can only reduce across nested dimensions of Tensor compliant shapes.\", lambda: torch.var(nt, 0))\n\n\n\n # Currently only supporting nested dim 1.\n\n # nt = ntnt([[t0, t1], [t2, t3]])\n\n # self.assertRaisesRegex(\n\n # RuntimeError, \"Can only reduce across nested dimension 0.\", lambda: torch.var(nt, 1))\n\n # self.assertRaisesRegex(\n\n # RuntimeError, \"Can only reduce across nested dimensions if given nested tensor is of nested dimension 1.\", lambda: torch.var(nt, 0))\n\n # t0_var0 = torch.var(t0, 0)\n\n # t1_var0 = torch.var(t1, 0)\n\n # t2_var0 = torch.var(t2, 0)\n\n # t3_var0 = torch.var(t3, 0)\n\n # self.assertEqual(\n\n # ntnt([[t0_var0, t1_var0], [t2_var0, t3_var0]]), torch.var(nt, 2))\n\n # t0_var1 = torch.var(t0, 1)\n\n # t1_var1 = torch.var(t1, 1)\n\n # t2_var1 = torch.var(t2, 1)\n\n # t3_var1 = torch.var(t3, 1)\n\n # self.assertEqual(\n\n # ntnt([[t0_var1, t1_var1], [t2_var1, t3_var1]]), torch.var(nt, 3))\n\n\n\n @unittest.skip(\"Not implemented - needed for autograd.\")\n\n def test_sum_to_size(self):\n\n a = ntnt([torch.arange(2).reshape(1, 2),\n\n torch.arange(2).reshape(2, 1) + 2])\n\n # b = ntnt([torch.randn(1), torch.randn(1)])\n\n # print(a)\n\n # print(nestedtensor.nested.nested.sum_to(a._impl, a.nested_size()))\n\n # print(nestedtensor.nested.nested.sum_to(a._impl, b.nested_size()))\n\n # print(nestedtensor.nested.nested.sum_to(a._impl, [1, 2]))\n\n print(a)\n\n # print(nestedtensor.nested.nested.sum_to(a, (2,)))\n\n # print(nestedtensor.nested.nested.sum_to(a, (2, 2)))\n\n a = ntnt([torch.arange(2).reshape(1, 2),\n\n torch.arange(2).reshape(1, 2) + 2])\n\n b = ntnt([torch.arange(2).reshape(2),\n\n torch.arange(2).reshape(2) + 2])\n\n print(nestedtensor.nested.nested.sum_to_size(a, a))\n\n print('a')\n\n print(a)\n\n print(nestedtensor.nested.nested.sum_to_size(a, b))\n\n # self.assertRaises(\n\n # RuntimeError, lambda: nestedtensor.nested.nested.sum_to_size(a, b))\n\n self.assertRaises(RuntimeError, lambda: nestedtensor.nested.nested.sum_to_size(\n\n torch.randn(1, 2), a))\n\n print(nestedtensor.nested.nested.sum_to_size(a, torch.randn(1, 2)))\n\n print(nestedtensor.nested.nested.sum_to_size(a, torch.randn(1, 2)).shape)\n\n # b = ntnt([torch.randn(1), torch.randn(1)])\n\n pass\n\n\n\n @unittest.skip(\"Not implemented - needed for autograd.\")\n\n def test_native_is_expandable_to(self):\n\n a = ntnt([torch.arange(2).reshape(1, 2),\n\n torch.arange(2).reshape(1, 2) + 2])\n\n self.assertEqual(True, native_is_expandable_to(a, a))\n\n self.assertEqual(False, native_is_expandable_to(a, torch.randn(1, 2)))\n\n self.assertEqual(True, native_is_expandable_to(torch.randn(1, 2), a))\n\n self.assertEqual(True, native_is_expandable_to(torch.randn(2), a))\n\n self.assertEqual(False, native_is_expandable_to(torch.randn(2, 1), a))\n\n b = ntnt([torch.arange(2).reshape(2),\n\n torch.arange(2).reshape(2) + 2])\n\n c = ntnt([[torch.arange(2).reshape(1, 2)],\n\n [torch.arange(2).reshape(1, 2) + 2]])\n\n # Both NT\n\n self.assertEqual(True, native_is_expandable_to(b, a))\n\n self.assertEqual(False, native_is_expandable_to(a, b))\n\n self.assertEqual(True, native_is_expandable_to(a, c))\n\n self.assertEqual(False, native_is_expandable_to(c, a))\n\n # Shape NT, desired T\n\n pass\n\n\n\n @unittest.skip(\"Not implemented - needed for autograd.\")\n\n def test_sizes_equal(self):\n\n a = ntnt([torch.arange(2).reshape(1, 2),\n\n torch.arange(2).reshape(1, 2) + 2])\n\n b = ntnt([torch.arange(2).reshape(2),\n\n torch.arange(2).reshape(2) + 2])\n\n self.assertEqual(True, nestedtensor.nested.nested.sizes_equal(a, a))\n\n self.assertEqual(False, nestedtensor.nested.nested.sizes_equal(a, b))\n\n self.assertEqual(False, nestedtensor.nested.nested.sizes_equal(b, a))\n\n self.assertEqual(\n\n False, nestedtensor.nested.nested.sizes_equal(torch.randn(1, 2), a))\n\n self.assertEqual(\n\n False, nestedtensor.nested.nested.sizes_equal(a, torch.randn(1, 2)))\n\n self.assertEqual(True, nestedtensor.nested.nested.sizes_equal(\n\n torch.randn(1, 2), torch.randn(1, 2)))\n\n self.assertEqual(False, nestedtensor.nested.nested.sizes_equal(\n\n torch.randn(2, 1), torch.randn(1, 2)))\n\n pass\n\n\n\n\n\nif __name__ == \"__main__\":\n\n unittest.main()\n", "file_path": "test/test_nested_tensor_reduce.py", "rank": 83, "score": 53161.73731285545 }, { "content": "import torch\n\nimport nestedtensor as nt\n\nimport unittest\n\nfrom utils_test_case import TestCase\n\n\n\n\n\nclass TestTensorMask(TestCase):\n\n #\n\n # Group of tests to test to_tensor_mask()\n\n #\n\n def test_empty_nt(self):\n\n a = nt.nested_tensor([])\n\n tensor, mask = a.to_tensor_mask()\n\n\n\n TestCase.assertEqual(self, mask, torch.tensor(False))\n\n TestCase.assertEqual(self, tensor, torch.tensor([0]))\n\n\n\n # TODO once .to_list() bug fixed\n\n def test_empty_tensor(self):\n\n a = nt.nested_tensor([\n\n torch.tensor([])\n\n ])\n\n self.assertRaisesRegex(RuntimeError,\n\n \"Empty tensors are not yet supported.\",\n\n lambda: a.to_tensor_mask())\n\n\n\n def test_single_scalar(self):\n\n a = nt.nested_tensor([\n\n torch.tensor(1, dtype=torch.uint8)\n\n ])\n\n tensor, mask = a.to_tensor_mask()\n\n TestCase.assertEqual(\n\n self, tensor, torch.tensor([1], dtype=torch.uint8))\n\n TestCase.assertEqual(self, mask, torch.tensor(True))\n\n\n\n tensor, mask = a.to_tensor_mask(mask_dim=0)\n\n TestCase.assertEqual(\n\n self, tensor, torch.tensor([1], dtype=torch.uint8))\n\n TestCase.assertEqual(self, mask, torch.tensor(True))\n\n\n\n tensor, mask = a.to_tensor_mask(mask_dim=1)\n\n TestCase.assertEqual(\n\n self, tensor, torch.tensor([1], dtype=torch.uint8))\n\n TestCase.assertEqual(self, mask, torch.tensor([True]))\n\n\n\n self.assertRaisesRegex(\n\n RuntimeError,\n\n \"Requested mask dimension 2 is bigger than dimension 1 of given NestedTensor.\",\n\n lambda: a.to_tensor_mask(mask_dim=2))\n\n\n\n # TODO once .to_list() bug fixed\n\n @unittest.skip(\"Currently only supporting nested dim 1.\")\n\n def test_multi_scalar(self):\n\n # TODO: add test cases\n\n a = nt.nested_tensor([\n\n torch.tensor(1),\n\n torch.tensor(2),\n\n torch.tensor(3)\n\n ])\n\n tensor, mask = a.to_tensor_mask()\n\n\n\n TestCase.assertEqual(self, tensor, torch.tensor([[1, 2, 3]]))\n\n TestCase.assertEqual(self, mask, torch.tensor(True))\n\n\n\n tensor, mask = a.to_tensor_mask(mask_dim=1)\n\n TestCase.assertEqual(self, tensor, torch.tensor([[1, 2, 3]]))\n\n TestCase.assertEqual(self, mask, torch.tensor([True]))\n\n\n\n tensor, mask = a.to_tensor_mask(mask_dim=2)\n\n TestCase.assertEqual(self, tensor, torch.tensor([[1, 2, 3]]))\n\n TestCase.assertEqual(self, mask, torch.tensor([[True, True, True]]))\n\n\n\n self.assertRaisesRegex(\n\n RuntimeError,\n\n \"Requested mask dimension 3 is bigger than dimension 2 of given NestedTensor.\",\n\n lambda: a.to_tensor_mask(mask_dim=3))\n\n\n\n def test_single_tensor(self):\n\n a = nt.nested_tensor([\n\n torch.tensor([1])\n\n ])\n\n tensor, mask = a.to_tensor_mask()\n\n TestCase.assertEqual(self, tensor, torch.tensor([[1]]))\n\n TestCase.assertEqual(self, mask, torch.tensor(True))\n\n\n\n tensor, mask = a.to_tensor_mask(mask_dim=0)\n\n TestCase.assertEqual(self, tensor, torch.tensor([[1]]))\n\n TestCase.assertEqual(self, mask, torch.tensor(True))\n\n\n\n tensor, mask = a.to_tensor_mask(mask_dim=1)\n\n TestCase.assertEqual(self, tensor, torch.tensor([[1]]))\n\n TestCase.assertEqual(self, mask, torch.tensor([True]))\n\n\n\n tensor, mask = a.to_tensor_mask(mask_dim=2)\n\n TestCase.assertEqual(self, tensor, torch.tensor([[1]]))\n\n TestCase.assertEqual(self, mask, torch.tensor([[True]]))\n\n\n\n self.assertRaisesRegex(\n\n RuntimeError,\n\n \"Requested mask dimension 3 is bigger than dimension 2 of given NestedTensor.\",\n\n lambda: a.to_tensor_mask(mask_dim=3))\n\n\n\n def test_multi_tensor(self):\n\n a = nt.nested_tensor([\n\n torch.tensor([1]),\n\n torch.tensor([2]),\n\n torch.tensor([3])\n\n ])\n\n tensor, mask = a.to_tensor_mask()\n\n TestCase.assertEqual(self, tensor, torch.tensor([[1],\n\n [2],\n\n [3]]))\n\n TestCase.assertEqual(self, mask, torch.tensor(True))\n\n\n\n tensor, mask = a.to_tensor_mask(mask_dim=0)\n\n TestCase.assertEqual(self, tensor, torch.tensor([[1],\n\n [2],\n\n [3]]))\n\n TestCase.assertEqual(self, mask, torch.tensor(True))\n\n\n\n tensor, mask = a.to_tensor_mask(mask_dim=1)\n\n TestCase.assertEqual(self, tensor, torch.tensor([[1],\n\n [2],\n\n [3]]))\n\n TestCase.assertEqual(self, mask, torch.tensor([True, True, True]))\n\n\n\n tensor, mask = a.to_tensor_mask(mask_dim=2)\n\n TestCase.assertEqual(self, tensor, torch.tensor([[1],\n\n [2],\n\n [3]]))\n\n TestCase.assertEqual(\n\n self, mask, torch.tensor([[True], [True], [True]]))\n\n\n\n @torch.inference_mode()\n\n def test_mask_dim_too_small_error(self):\n\n a = nt.nested_tensor([\n\n torch.tensor([1, 2, ]),\n\n torch.tensor([3, 4, 5, 6]),\n\n ])\n\n\n\n self.assertRaisesRegex(\n\n RuntimeError, \"Mask dimension is too small to represent data tensor.\", lambda: a.to_tensor_mask(mask_dim=1))\n\n #\n\n # Group of tests to test nested_tensor_from_tensor_mask()\n\n #\n\n def test_ntftm_nested_dim_0_error(self):\n\n tensor = torch.tensor([])\n\n self.assertRaisesRegex(RuntimeError, \"Nested dimension can't be 0.\",\n\n lambda: nt.nested_tensor_from_tensor_mask(tensor, tensor, nested_dim=0))\n\n\n\n def test_ntftm_none_passed(self):\n\n self.assertRaises(\n\n RuntimeError, lambda: nt.nested_tensor_from_tensor_mask(None, None))\n\n self.assertRaises(RuntimeError, lambda: nt.nested_tensor_from_tensor_mask(\n\n torch.tensor([]), None))\n\n\n\n @torch.inference_mode()\n\n def test_ntftm_empty(self):\n\n tensor = torch.tensor([])\n\n\n\n res_nt = nt.nested_tensor_from_tensor_mask(tensor, tensor)\n\n TestCase.assertEqual(self, res_nt, nt.nested_tensor([]))\n\n TestCase.assertEqual(self, res_nt.nested_dim(), 1)\n\n\n\n res_nt = nt.nested_tensor_from_tensor_mask(\n\n tensor, tensor, nested_dim=1)\n\n TestCase.assertEqual(self, res_nt, nt.nested_tensor([]))\n\n TestCase.assertEqual(self, res_nt.nested_dim(), 1)\n\n\n\n self.assertRaises(RuntimeError, lambda: nt.nested_tensor_from_tensor_mask(\n\n tensor, tensor, nested_dim=2))\n\n\n\n def test_ntftm_empty2(self):\n\n tensor = torch.tensor([[], []])\n\n\n\n expected_nt1 = nt.nested_tensor([\n\n torch.tensor([]),\n\n torch.tensor([]),\n\n ])\n\n\n\n res_nt = nt.nested_tensor_from_tensor_mask(tensor, tensor)\n\n TestCase.assertEqual(self, res_nt, expected_nt1)\n\n\n\n res_nt = nt.nested_tensor_from_tensor_mask(\n\n tensor, tensor, nested_dim=1)\n\n TestCase.assertEqual(self, res_nt, expected_nt1)\n\n\n\n res_nt = nt.nested_tensor_from_tensor_mask(tensor, tensor)\n\n TestCase.assertEqual(self, res_nt, expected_nt1)\n\n\n\n res_nt = nt.nested_tensor_from_tensor_mask(\n\n tensor, tensor, nested_dim=1)\n\n TestCase.assertEqual(self, res_nt, expected_nt1)\n\n\n\n def test_ntftm_empty3(self):\n\n tensor = torch.tensor([0])\n\n mask = torch.tensor(False)\n\n\n\n res_nt = nt.nested_tensor_from_tensor_mask(tensor, mask)\n\n TestCase.assertEqual(self, res_nt, nt.nested_tensor([]))\n\n\n\n tensor = torch.tensor([[0], [0]])\n\n mask = torch.tensor([[False], [False]])\n\n\n\n def test_ntftm_empty_error(self):\n\n tensor = torch.tensor([])\n\n mask = torch.tensor([True])\n\n self.assertRaisesRegex(RuntimeError,\n\n \"Data tensor can't be emtpy if a mask has values.\",\n\n lambda: nt.nested_tensor_from_tensor_mask(tensor, mask))\n\n\n\n tensor = torch.tensor([1])\n\n mask = torch.tensor([])\n\n self.assertRaisesRegex(RuntimeError,\n\n \"Mask tensor can't be emtpy if a data tensor has values.\",\n\n lambda: nt.nested_tensor_from_tensor_mask(tensor, mask))\n\n\n\n def test_ntftm_single_scalar_mask_false(self):\n\n scalar = torch.tensor([1], dtype=torch.uint8)\n\n mask = torch.tensor(False)\n\n\n\n res_nt = nt.nested_tensor_from_tensor_mask(scalar, mask)\n\n TestCase.assertEqual(self, res_nt, nt.nested_tensor([]))\n\n\n\n def test_ntftm_single_scalar_error(self):\n\n tensor = torch.tensor(1)\n\n mask = torch.tensor(True)\n\n self.assertRaisesRegex(RuntimeError, \"Can't construct nested tensor from a scalar.\",\n\n lambda: nt.nested_tensor_from_tensor_mask(tensor, mask))\n\n\n\n def test_ntftm_single_scalar(self):\n\n tensor = torch.tensor([1], dtype=torch.float)\n\n mask = torch.tensor(True)\n\n res_nt = nt.nested_tensor_from_tensor_mask(tensor, mask)\n\n TestCase.assertEqual(self, res_nt, nt.nested_tensor([torch.tensor(1)]))\n\n\n\n mask = torch.tensor([True])\n\n res_nt = nt.nested_tensor_from_tensor_mask(tensor, mask)\n\n TestCase.assertEqual(self, res_nt, nt.nested_tensor([torch.tensor(1)]))\n\n\n\n # Extra dim\n\n tensor = torch.tensor([[1]], dtype=torch.float)\n\n mask = torch.tensor(True)\n\n res_nt = nt.nested_tensor_from_tensor_mask(tensor, mask)\n\n TestCase.assertEqual(self, res_nt,\n\n nt.nested_tensor([\n\n torch.tensor([1])\n\n ]))\n\n\n\n def test_ntftm_multi_scalars(self):\n\n tensor = torch.tensor([1, 2, 3])\n\n mask = torch.tensor(True)\n\n res_nt = nt.nested_tensor_from_tensor_mask(tensor, mask)\n\n TestCase.assertEqual(self, res_nt,\n\n nt.nested_tensor([\n\n torch.tensor(1),\n\n torch.tensor(2),\n\n torch.tensor(3)\n\n ], dtype=torch.int64))\n\n\n\n mask = torch.tensor([True])\n\n res_nt = nt.nested_tensor_from_tensor_mask(tensor, mask)\n\n TestCase.assertEqual(self, res_nt,\n\n nt.nested_tensor([\n\n torch.tensor(1),\n\n torch.tensor(2),\n\n torch.tensor(3)\n\n ], dtype=torch.int64))\n\n\n\n self.assertRaises(RuntimeError, lambda: nt.nested_tensor_from_tensor_mask(\n\n tensor, mask, nested_dim=2))\n\n\n\n # Extra dim\n\n tensor = torch.tensor([[1, 2, 3]])\n\n mask = torch.tensor(True)\n\n res_nt = nt.nested_tensor_from_tensor_mask(tensor, mask)\n\n TestCase.assertEqual(self, res_nt,\n\n nt.nested_tensor([\n\n torch.tensor([1, 2, 3])\n\n ], dtype=torch.int64))\n\n\n\n def test_ntftm_single_tensor_all_true_mask(self):\n\n tensor = torch.tensor([[1]], dtype=torch.float)\n\n mask = torch.tensor(True)\n\n res_nt = nt.nested_tensor_from_tensor_mask(tensor, mask)\n\n TestCase.assertEqual(\n\n self, res_nt, nt.nested_tensor([torch.tensor([1])]))\n\n\n\n mask = torch.tensor([True])\n\n res_nt = nt.nested_tensor_from_tensor_mask(tensor, mask)\n\n TestCase.assertEqual(\n\n self, res_nt, nt.nested_tensor([torch.tensor([1])]))\n\n\n\n def test_ntftm_multi_tensor_scalar_true_mask(self):\n\n tensor = torch.tensor([[1], [2], [3]])\n\n mask = torch.tensor(True)\n\n res_nt = nt.nested_tensor_from_tensor_mask(tensor, mask)\n\n TestCase.assertEqual(self, res_nt,\n\n nt.nested_tensor([\n\n torch.tensor([1]),\n\n torch.tensor([2]),\n\n torch.tensor([3])\n\n ], dtype=tensor.dtype))\n\n\n\n # Extra dim\n\n tensor = torch.tensor([[[1]], [[2]], [[3]]])\n\n res_nt = nt.nested_tensor_from_tensor_mask(tensor, mask)\n\n expected_res1 = nt.nested_tensor([\n\n torch.tensor([[1]]),\n\n torch.tensor([[2]]),\n\n torch.tensor([[3]])\n\n ], dtype=tensor.dtype)\n\n TestCase.assertEqual(self, res_nt, expected_res1)\n\n\n\n def test_ntftm_multi_tensor_true_mask(self):\n\n extected_nt1 = nt.nested_tensor([\n\n torch.tensor([[1]]),\n\n torch.tensor([[2]]),\n\n torch.tensor([[3]])\n\n ])\n\n\n\n tensor = torch.tensor([[[1]],\n\n [[2]],\n\n [[3]]], dtype=torch.float)\n\n\n\n # Mask dim 3\n\n mask3 = torch.tensor([[[True]],\n\n [[True]],\n\n [[True]]])\n\n\n\n res_nt = nt.nested_tensor_from_tensor_mask(tensor, mask3)\n\n TestCase.assertEqual(self, extected_nt1, res_nt)\n\n\n\n # Mask dim 2\n\n mask2 = torch.tensor([[True],\n\n [True],\n\n [True]])\n\n\n\n res_nt = nt.nested_tensor_from_tensor_mask(tensor, mask2)\n\n TestCase.assertEqual(self, extected_nt1, res_nt)\n\n\n\n # Mask dim 1\n\n mask1 = torch.tensor([True, True, True])\n\n\n\n res_nt = nt.nested_tensor_from_tensor_mask(tensor, mask1)\n\n TestCase.assertEqual(self, extected_nt1, res_nt)\n\n\n\n # Mask dim 0\n\n mask0 = torch.tensor(True)\n\n res_nt = nt.nested_tensor_from_tensor_mask(tensor, mask0)\n\n TestCase.assertEqual(self, extected_nt1, res_nt)\n\n\n\n def test_ntftm_single_tensor_all_false_mask(self):\n\n tensor = torch.tensor([[1]])\n\n mask = torch.tensor([False])\n\n res_nt = nt.nested_tensor_from_tensor_mask(tensor, mask)\n\n TestCase.assertEqual(self, res_nt, nt.nested_tensor([]))\n\n\n\n tensor = torch.tensor([[1, 2, 3]])\n\n mask = torch.tensor([False])\n\n res_nt = nt.nested_tensor_from_tensor_mask(tensor, mask)\n\n TestCase.assertEqual(self, res_nt, nt.nested_tensor([]))\n\n\n\n def test_ntftm_multi_tensor_all_false_mask(self):\n\n tensor = torch.tensor([[[1], [2], [3]]])\n\n mask = torch.tensor([False])\n\n res_nt = nt.nested_tensor_from_tensor_mask(tensor, mask)\n\n TestCase.assertEqual(self, res_nt, nt.nested_tensor([]))\n\n\n\n mask = torch.tensor([False, False, False])\n\n res_nt = nt.nested_tensor_from_tensor_mask(tensor, mask)\n\n TestCase.assertEqual(self, res_nt, nt.nested_tensor([]))\n\n\n\n mask = torch.tensor([[False], [False], [False]])\n\n res_nt = nt.nested_tensor_from_tensor_mask(tensor, mask)\n\n TestCase.assertEqual(self, res_nt,\n\n nt.nested_tensor([\n\n torch.tensor([], dtype=tensor.dtype)\n\n ], dtype=torch.int64))\n\n\n\n def test_ntftm_multi_tensor_all_false_mask2(self):\n\n tensor = torch.tensor([[[1], [2], [3]]])\n\n mask = torch.tensor([[[False], [False], [False]]])\n\n res_nt = nt.nested_tensor_from_tensor_mask(tensor, mask)\n\n TestCase.assertEqual(self, res_nt,\n\n nt.nested_tensor([\n\n torch.empty((3, 0), dtype=tensor.dtype)\n\n ], dtype=tensor.dtype))\n\n\n\n def test_ntgtm_multi_scalar_mix_mask(self):\n\n tensor = torch.tensor([1, 2, 3, 4], dtype=torch.float)\n\n mask = torch.tensor([True, False, False, True])\n\n expected_nt = nt.nested_tensor([\n\n torch.tensor(1),\n\n torch.tensor(4)\n\n ])\n\n\n\n res_nt = nt.nested_tensor_from_tensor_mask(tensor, mask)\n\n TestCase.assertEqual(self, expected_nt, res_nt)\n\n\n\n def test_ntgtm_multi_tensor_mix_mask(self):\n\n tensor = torch.tensor([[1], [2], [3], [4]], dtype=torch.float)\n\n mask = torch.tensor([True, False, False, True])\n\n expected_nt = nt.nested_tensor([\n\n torch.tensor([1]),\n\n torch.tensor([4])\n\n ])\n\n\n\n res_nt = nt.nested_tensor_from_tensor_mask(tensor, mask)\n\n TestCase.assertEqual(self, expected_nt, res_nt)\n\n\n\n def test_ntgtm_scalar_with_empty_mix_mask(self):\n\n tensor = torch.tensor([[0], [11]], dtype=torch.float)\n\n mask = torch.tensor([False, True])\n\n\n\n expected_nt1 = nt.nested_tensor([\n\n torch.tensor([11], dtype=torch.long)\n\n ])\n\n\n\n res_nt = nt.nested_tensor_from_tensor_mask(tensor, mask)\n\n TestCase.assertEqual(self, expected_nt1, res_nt)\n\n\n\n def test_ntftm_test_multi_tensor_mix_mask(self):\n\n expected_nt1 = nt.nested_tensor([\n\n torch.tensor([1, 2, 3]),\n\n torch.tensor([4])\n\n ])\n\n\n\n tensor = torch.tensor([[1, 2, 3],\n\n [4, 0, 0]], dtype=torch.float)\n\n mask = torch.tensor([[True, True, True],\n\n [True, False, False]])\n\n\n\n res_nt = nt.nested_tensor_from_tensor_mask(tensor, mask, nested_dim=1)\n\n TestCase.assertEqual(self, expected_nt1, res_nt)\n\n\n\n def test_ntftm_test_multi_tensor_mix_mask2(self):\n\n expected_nt1 = nt.nested_tensor([\n\n torch.tensor([[1, 2, 3]]),\n\n torch.tensor([[4]])\n\n ])\n\n\n\n tensor = torch.tensor([[[1, 2, 3]],\n\n [[4, 0, 0]]], dtype=torch.float)\n\n mask = torch.tensor([[[True, True, True]],\n\n [[True, False, False]]])\n\n\n\n res_nt = nt.nested_tensor_from_tensor_mask(tensor, mask, nested_dim=1)\n\n TestCase.assertEqual(self, expected_nt1, res_nt)\n\n\n\n self.assertRaises(RuntimeError, lambda: nt.nested_tensor_from_tensor_mask(\n\n tensor, mask, nested_dim=4))\n\n\n\n def test_to_padded_tensor(self):\n\n data1 = torch.tensor(\n\n [[[0.8413, 0.7325, 0.0000, 0.0000],\n\n [0.0000, 0.0000, 0.0000, 0.0000],\n\n [0.0000, 0.0000, 0.0000, 0.0000]],\n\n\n\n [[0.6334, 0.5473, 0.3273, 0.0564],\n\n [0.3023, 0.6826, 0.3519, 0.1804],\n\n [0.8431, 0.1645, 0.1821, 0.9185]]])\n\n mask1 = torch.tensor(\n\n [[[True, True, False, False],\n\n [False, False, False, False],\n\n [False, False, False, False]],\n\n\n\n [[True, True, True, True],\n\n [True, True, True, True],\n\n [True, True, True, True]]])\n\n nt2 = nt.nested_tensor_from_tensor_mask(data1, mask1)\n\n data2, mask2 = nt2.to_tensor_mask()\n\n self.assertEqual(data1, data2)\n\n self.assertEqual(mask1, mask2)\n\n data3 = nt2.to_padded_tensor(padding=-10)\n\n data1 = data1 + ~mask1 * -10\n\n self.assertEqual(data1, data3)\n\n\n\n\n\nif __name__ == \"__main__\":\n\n unittest.main()\n", "file_path": "test/test_nested_tensor_masking.py", "rank": 84, "score": 53161.73731285545 }, { "content": "import torch\n\nimport nestedtensor\n\nimport unittest\n\n\n\nfrom utils_test_case import TestCase\n\n\n\n\n\ndef ntnt(x): return nestedtensor.nested_tensor(x, requires_grad=True)\n\ndef ntnt_nograd(x): return nestedtensor.nested_tensor(x)\n\n\n\n\n\nclass TestNestedTensorAutograd(TestCase):\n\n\n\n @unittest.skip(\"Requires autograd support\")\n\n def test_autograd_size_equal_nt(self):\n\n # TODO: Right now this only exercises the mechanisms\n\n a = ntnt([torch.randn(1, 2)])\n\n s = a.sum()\n\n s.backward()\n\n\n\n a = ntnt([torch.randn(1, 2), torch.randn(2, 1)])\n\n b = ntnt([torch.randn(1, 2), torch.randn(2, 1)])\n\n c = a + b\n\n c.backward(a)\n\n\n\n a = ntnt([torch.randn(1, 2), torch.randn(2, 1)])\n\n t0 = torch.randn(2, 2, requires_grad=True)\n\n d = t0 + a\n\n d.sum().backward()\n\n\n\n t1 = torch.randn(1, 2, requires_grad=True)\n\n t1.sum().backward()\n\n\n\n e = ntnt([torch.randn(1, 2), torch.randn(2, 1)])\n\n a0 = a + b\n\n a1 = a0 + e\n\n a2 = a1.sum()\n\n\n\n @unittest.skip(\"Requires autograd support\")\n\n def test_basic_grad(self):\n\n def some_func(x):\n\n return torch.sum(x ** 2 + x ** 3)\n\n\n\n # single tensor case for comparison\n\n verification_tensor = torch.tensor(\n\n [[1, 2], [3, 4]], dtype=torch.float, requires_grad=True)\n\n sum_res = some_func(verification_tensor)\n\n sum_res.backward()\n\n\n\n # as_nested_tensor constructor\n\n tensor = torch.tensor(\n\n [[1, 2], [3, 4]], dtype=torch.float, requires_grad=True)\n\n nt = nestedtensor.as_nested_tensor([tensor])\n\n nt_sum_res = some_func(nt)\n\n self.assertRaisesRegex(RuntimeError, \"element 0 of tensors does not require grad and does not have a grad_fn\",\n\n lambda: nt_sum_res.backward())\n\n\n\n self.assertEqual(sum_res, nt_sum_res)\n\n self.assertIsNone(nt[0].grad)\n\n self.assertIsNotNone(verification_tensor.grad)\n\n\n\n # nested_tensor constructor\n\n tensor2 = torch.tensor(\n\n [[1, 2], [3, 4]], dtype=torch.float, requires_grad=True)\n\n nt2 = nestedtensor.nested_tensor([tensor2]) # , requires_grad=True)\n\n nt_sum_res2 = some_func(nt2)\n\n # TODO: Re-enable under autograd\n\n self.assertRaises(RuntimeError, lambda: nt_sum_res2.backward())\n\n # nt_sum_res2.backward()\n\n # self.assertEqual(sum_res, nt_sum_res2)\n\n # self.assertIsNone(tensor2.grad)\n\n # self.assertIsNotNone(nt2[0].grad)\n\n\n\n @unittest.skip(\"Requires autograd support\")\n\n def test_grad_to_tensor_mask(self):\n\n def some_func(x):\n\n return torch.sum(x ** 2 + x ** 3)\n\n\n\n nt1 = nestedtensor.nested_tensor([torch.tensor([1, 2, 3, 4]),\n\n torch.tensor([1, 2, 3]),\n\n torch.tensor([1, 2])],\n\n dtype=torch.float) # , requires_grad=True)\n\n nt_sum_res = some_func(nt1)\n\n # nt_sum_res.backward()\n\n # TODO: Re-enable under autograd\n\n self.assertRaises(RuntimeError, lambda: nt_sum_res.backward())\n\n\n\n # self.assertEqual(nt1[0].grad, torch.tensor([ 5., 16., 33., 56.]))\n\n # self.assertEqual(nt1[1].grad, torch.tensor([ 5., 16., 33.]))\n\n # self.assertEqual(nt1[2].grad, torch.tensor([ 5., 16.]))\n\n\n\n nt2 = nestedtensor.nested_tensor([torch.tensor([1, 2, 3, 4]),\n\n torch.tensor([1, 2, 3]),\n\n torch.tensor([1, 2])],\n\n dtype=torch.float) # , requires_grad=True)\n\n tensor, mask = nt2.to_tensor_mask(mask_dim=2)\n\n sum_res = some_func(tensor)\n\n # sum_res.backward()\n\n # TODO: Re-enable under autograd\n\n self.assertRaises(RuntimeError, lambda: sum_res.backward())\n\n\n\n self.assertEqual(sum_res, nt_sum_res)\n\n\n\n # self.assertEqual(nt2[0].grad, torch.tensor([ 5., 16., 33., 56.]))\n\n # self.assertEqual(nt2[1].grad, torch.tensor([ 5., 16., 33.]))\n\n # self.assertEqual(nt2[2].grad, torch.tensor([ 5., 16.]))\n\n\n\n @unittest.skip(\"Requires autograd support\")\n\n def test_grad_nt_from_tensor_mask(self):\n\n def some_func(x):\n\n return torch.sum(x ** 2 + x ** 3)\n\n\n\n t1 = torch.tensor([1., 2., 3., 4.], requires_grad=True)\n\n t2 = torch.tensor([1., 2., 3.], requires_grad=True)\n\n t3 = torch.tensor([1., 2.], requires_grad=True)\n\n\n\n res1 = some_func(t1)\n\n res2 = some_func(t2)\n\n res3 = some_func(t3)\n\n total_t_sum = res1 + res2 + res3\n\n\n\n res1.backward()\n\n res2.backward()\n\n res3.backward()\n\n\n\n nt_tensor = torch.tensor([[1., 2., 3., 4.],\n\n [1., 2., 3., 0.],\n\n [1., 2., 0., 0.]]) # , requires_grad=True)\n\n nt_mask = torch.tensor([[True, True, True, True],\n\n [True, True, True, False],\n\n [True, True, False, False]])\n\n\n\n nt = nestedtensor.nested_tensor_from_tensor_mask(nt_tensor, nt_mask)\n\n # self.assertTrue(nt.requires_grad)\n\n # TODO: Re-enable under autograd\n\n self.assertFalse(nt.requires_grad)\n\n\n\n nt_sum_res = some_func(nt)\n\n # nt_sum_res.backward()\n\n # TODO: Re-enable under autograd\n\n self.assertRaises(RuntimeError, lambda: nt_sum_res.backward())\n\n\n\n self.assertEqual(total_t_sum, nt_sum_res)\n\n # self.assertEqual(nt[0].grad, torch.tensor([ 5., 16., 33., 56.]))\n\n # self.assertEqual(nt[1].grad, torch.tensor([ 5., 16., 33.]))\n\n # self.assertEqual(nt[2].grad, torch.tensor([ 5., 16.]))\n\n\n\n # def test_matmul(self):\n\n # ntnt = lambda x: nestedtensor.nested_tensor(x, requires_grad=True)\n\n # t1 = torch.randn(2, 3)\n\n # a = ntnt([t1, t1])\n\n # t21 = torch.randn(3, 2)\n\n # t22 = torch.randn(3, 2)\n\n # b = ntnt([t21, t22])\n\n # # result = torch.matmul(a, b)\n\n # print(\"a: \", a.requires_grad)\n\n # print(\"b: \", b.requires_grad)\n\n # result = a.matmul(b)\n\n # print('result')\n\n # print(result.requires_grad)\n\n # result1 = torch.matmul(a, t22)\n\n # self.assertEqual(result[1], result1[0])\n\n # self.assertEqual(result[1], result1[1])\n\n # c = ntnt([[t21, t22], [t22, t21]])\n\n # result2 = torch.matmul(c, t1)\n\n # self.assertEqual(result2[0][0], torch.matmul(t21, t1))\n\n # self.assertEqual(result2[0][1], torch.matmul(t22, t1))\n\n # self.assertEqual(result2[1][0], torch.matmul(t22, t1))\n\n # self.assertEqual(result2[1][1], torch.matmul(t21, t1))\n\n\n\n\n\nif __name__ == \"__main__\":\n\n unittest.main()\n", "file_path": "test/test_nested_tensor_autograd.py", "rank": 85, "score": 53161.73731285545 }, { "content": "import torch\n\nimport nestedtensor\n\nimport unittest\n\nfrom utils import get_unary_functions\n\nfrom utils import get_binary_functions\n\nimport utils\n\nfrom utils_test_case import TestCase\n\n\n\n\n\ndef ntnt(x, device=None):\n\n return nestedtensor.nested_tensor(\n\n x, requires_grad=False, device=device)\n\n\n\n\n\ndef ntnt_nograd(x, device=None):\n\n return nestedtensor.nested_tensor(x, device=device)\n\n\n\n\n\nclass DynamicClassBase(TestCase):\n\n longMessage = True\n\n\n\n\n\ndef _gen_test_unary(func__, nested_dim, device):\n\n def _test_unary(self):\n\n data = utils.gen_nested_list(1, nested_dim, 3, size_high=1)\n\n data = utils.nested_map(lambda x: x.to(device), data)\n\n\n\n if func__ in ['log', 'log10', 'log2', 'rsqrt', 'sqrt']:\n\n data = utils.nested_map(lambda x: x.abs(), data)\n\n if func__ in ['acos', 'asin', 'erfinv', 'log1p']:\n\n data = utils.nested_map(lambda x: x.clamp(min=0, max=1), data)\n\n if func__ in ['mvlgamma']:\n\n data = utils.nested_map(lambda x: x.clamp(min=1), data)\n\n\n\n func_ = getattr(torch, func__)\n\n method_ = getattr(nestedtensor.NestedTensor, func__)\n\n method_inplace_ = getattr(nestedtensor.NestedTensor, func__ + \"_\")\n\n if func__ in ['clamp']:\n\n\n\n def func(x, out=None):\n\n return func_(x, min=-1, max=1, out=out)\n\n\n\n def method(x): return method_(x, min=-1, max=1)\n\n\n\n def method_inplace(x): return method_inplace_(x, min=-1, max=1)\n\n elif func__ in ['clamp_min']:\n\n\n\n def func(x, out=None):\n\n return func_(x, min=-1, out=out)\n\n\n\n def method(x): return method_(x, min=-1)\n\n\n\n def method_inplace(x): return method_inplace_(x, min=-1)\n\n elif func__ in ['clamp_max']:\n\n\n\n def func(x, out=None):\n\n return func_(x, 1, out=out)\n\n\n\n def method(x): return method_(x, 1)\n\n\n\n def method_inplace(x): return method_inplace_(x, 1)\n\n elif func__ in ['mvlgamma']:\n\n\n\n def func(x):\n\n return func_(x, p=2)\n\n\n\n def method(x): return method_(x, p=2)\n\n\n\n def method_inplace(x): return method_inplace_(x, p=2)\n\n elif func__ in ['renorm']:\n\n\n\n def func(x, out=None):\n\n return func_(x, 2, 0, 1.0, out=out)\n\n\n\n def method(x):\n\n return method_(x, 2, 0, 1.0)\n\n\n\n def method_inplace(x): return method_inplace_(x, 2, 0, 1.0)\n\n elif func__ in ['fmod']:\n\n\n\n def func(x, out=None):\n\n return func_(x, 0.3, out=out)\n\n\n\n def method(x): return method_(x, 0.3)\n\n\n\n def method_inplace(x): return method_inplace_(x, 0.3)\n\n else:\n\n func = func_\n\n method = method_\n\n method_inplace = method_inplace_\n\n\n\n def _close(t1, t2):\n\n self.assertAlmostEqual(t1, t2, ignore_contiguity=True)\n\n\n\n a1 = ntnt(data, device=device)\n\n a2 = ntnt(\n\n utils.nested_map(func, data), device=device)\n\n _close(func(a1), a2)\n\n _close(method(a1), a2)\n\n\n\n a1 = ntnt_nograd(data, device=device)\n\n a2 = ntnt_nograd(\n\n utils.nested_map(func, data), device=device)\n\n a3 = ntnt_nograd(data, device=device)\n\n\n\n self.assertEqual(a1.nested_dim(), a2.nested_dim())\n\n self.assertEqual(a2.nested_dim(), a3.nested_dim())\n\n\n\n if func__ not in ['mvlgamma']:\n\n func(a1, out=a3)\n\n # TODO: Abstract this\n\n _close(func(a1), a3)\n\n _close(method_inplace(a1), a2)\n\n _close(a1, a2)\n\n return _test_unary\n\n\n\n\n\ndef _gen_test_binary(func, no_grad):\n\n def _test_binary(self):\n\n a = utils.gen_float_tensor(1, (2, 3)) # * 0 + 1\n\n b = utils.gen_float_tensor(2, (2, 3)) # * 0 + 2\n\n c = utils.gen_float_tensor(3, (2, 3)) # * 0 + 3\n\n d = utils.gen_float_tensor(4, (3, 2)) # * 0 + 4\n\n s = utils.gen_float_tensor(5, (1,)) # * 0 + 5\n\n torch_func = getattr(torch, func)\n\n\n\n a1 = ntnt([a, b])\n\n if no_grad:\n\n a2 = ntnt_nograd([b, c])\n\n else:\n\n a2 = ntnt([b, c])\n\n a3 = ntnt([torch_func(a, b),\n\n torch_func(b, c)])\n\n res1 = torch_func(a1, a2)\n\n if not no_grad:\n\n res1.sum().backward()\n\n self.assertIsNotNone(a1.grad)\n\n if no_grad:\n\n self.assertIsNone(a2.grad)\n\n else:\n\n self.assertIsNotNone(a2.grad)\n\n self.assertEqual(a3, torch_func(a1, a2))\n\n self.assertEqual(a3, getattr(a1, func)(a2))\n\n # a1.detach_()\n\n # a2.detach_()\n\n # a3.detach_()\n\n self.assertEqual(a3, getattr(a1, func + \"_\")(a2))\n\n self.assertEqual(a3, a1)\n\n\n\n # Test NT x T\n\n a1 = ntnt([a, b])\n\n a2 = c\n\n a3 = ntnt([torch_func(a, a2),\n\n torch_func(b, a2)])\n\n\n\n self.assertEqual(a3, torch_func(a1, a2))\n\n self.assertEqual(a3, getattr(a1, func)(a2))\n\n\n\n # Test NT x T with broadcasting\n\n if func not in [\"pow\", \"atan2\"]:\n\n a1 = ntnt([a, b])\n\n a2 = torch.tensor([1, 2]).reshape(-1, 1, 1)\n\n a3 = ntnt([torch_func(a, 1),\n\n torch_func(b, 2)])\n\n self.assertEqual(a3, torch_func(a1, a2))\n\n self.assertEqual(a3, getattr(a1, func)(a2))\n\n\n\n if func in [\"pow\"]:\n\n apow = utils.gen_float_tensor(1, (2, 3))\n\n bpow = utils.gen_float_tensor(2, (2, 3))\n\n a1pow = ntnt([apow, bpow])\n\n a3pow = ntnt([torch_func(3.0, apow),\n\n torch_func(3.0, bpow)])\n\n self.assertEqual(a3pow, torch_func(3.0, a1pow))\n\n\n\n a1 = ntnt([a, d])\n\n self.assertEqual(ntnt([torch_func(a, s), torch_func(d, s)]),\n\n torch_func(a1, s))\n\n\n\n a1 = ntnt([a, b])\n\n self.assertEqual(ntnt([torch_func(a, c),\n\n torch_func(b, c)\n\n ]),\n\n torch_func(a1, c.reshape(1, 2, 3)))\n\n\n\n result = ntnt([torch_func(c, a),\n\n torch_func(c, b)\n\n ])\n\n # if no_grad:\n\n # a1.detach_()\n\n # result.detach_()\n\n self.assertEqual(result,\n\n torch_func(c.reshape(1, 2, 3), a1))\n\n\n\n # a1 = a1.detach()\n\n # a3 = a3.detach()\n\n self.assertEqual(a3, getattr(a1, func + \"_\")(a2))\n\n self.assertEqual(a3, a1)\n\n\n\n # The constructor is supposed to copy!\n\n a1 = c\n\n a2 = ntnt([a, b])\n\n a3 = ntnt([torch_func(c, a),\n\n torch_func(c, b)])\n\n # if no_grad:\n\n # a2.detach_()\n\n # a3.detach_()\n\n self.assertEqual(a3, torch_func(a1, a2))\n\n self.assertEqual(a3, getattr(a1, func)(a2))\n\n # Cannot apply in-place methods to regular Tensors given a NestedTensor as an other\n\n # TODO: Only sub doesn't adhere to this rule but with irregular behavior\n\n if func == \"add\":\n\n self.assertEqual(c + a + b, getattr(a1, func + \"_\")(a2))\n\n\n\n return _test_binary\n\n\n\n\n\ndef _gen_test_binary_method(func):\n\n def _test_binary_method(self):\n\n a = utils.gen_float_tensor(1, (2, 3))\n\n b = utils.gen_float_tensor(2, (2, 3))\n\n c = utils.gen_float_tensor(3, (2, 3))\n\n\n\n # The constructor is supposed to copy!\n\n a1 = nestedtensor.nested_tensor([a, b])\n\n a2 = nestedtensor.nested_tensor([b, c])\n\n a3 = nestedtensor.nested_tensor([getattr(a, \"__\" + func + \"__\")(b),\n\n getattr(b, \"__\" + func + \"__\")(c)])\n\n self.assertEqual(a3, getattr(a1, \"__\" + func + \"__\")(a2))\n\n\n\n # The constructor is supposed to copy!\n\n a1 = nestedtensor.nested_tensor([a, b])\n\n a2 = c\n\n a3 = nestedtensor.nested_tensor([getattr(a, \"__\" + func + \"__\")(a2),\n\n getattr(b, \"__\" + func + \"__\")(a2)])\n\n self.assertEqual(a3, getattr(a1, \"__\" + func + \"__\")(a2))\n\n\n\n a1 = c\n\n a2 = nestedtensor.nested_tensor([a, b])\n\n a3 = nestedtensor.nested_tensor([getattr(a1, \"__\" + func + \"__\")(a),\n\n getattr(a1, \"__\" + func + \"__\")(b)])\n\n self.assertEqual(a3, getattr(a2, \"__r\" + func + \"__\")(a1))\n\n return _test_binary_method\n\n\n\n\n\nTestUnary = type('TestUnary', (DynamicClassBase,), {})\n\nfor func__ in get_unary_functions():\n\n # TODO: Currently only supporting nested dim 1.\n\n for nested_dim in [1]:\n\n avail_devices = [torch.device('cpu')]\n\n if torch.cuda.is_available():\n\n avail_devices += [torch.device('cuda')]\n\n for device in avail_devices:\n\n setattr(TestUnary, \"test_{0}_nested_dim_{1}_{2}\".format(\n\n func__, nested_dim, device), _gen_test_unary(func__, nested_dim, device))\n\n\n\nTestBinary = type('TestBinary', (DynamicClassBase,), {})\n\nfor func in get_binary_functions():\n\n no_grad = True\n\n setattr(TestBinary, \"test_{0}\".format(func),\n\n _gen_test_binary(func, no_grad))\n\n\n\n# TestBinaryMethod = type('TestBinaryMethod', (DynamicClassBase,), {})\n\n# for func in get_python_binary_arithmetic_operations():\n\n# # Not implemented yet\n\n# if func in ['divmod', 'and', 'lshift', 'matmul', 'mod', 'or', 'rshift', 'xor']:\n\n# continue\n\n# setattr(TestBinaryMethod, \"test_{0}\".format(func),\n\n# _gen_test_binary_method(func))\n\n\n\nif __name__ == \"__main__\":\n\n unittest.main()\n", "file_path": "test/test_nested_tensor_nary.py", "rank": 86, "score": 53161.73731285545 }, { "content": "import torch\n\nimport nestedtensor\n\nimport unittest\n\nfrom utils_test_case import TestCase\n\nfrom utils import debug_on\n\n\n\ntry:\n\n import classy_vision\n\n TEST_CLASSY_VISION=True\n\nexcept ModuleNotFoundError:\n\n TEST_CLASSY_VISION=False\n\n\n\n\n\ndef ntnt(x): return nestedtensor.nested_tensor(x, requires_grad=True)\n\ndef ntnt_nograd(x): return nestedtensor.nested_tensor(x, requires_grad=False)\n\n\n\n\n\nclass ConfusionMatrix(object):\n\n def __init__(self, num_classes):\n\n self.num_classes = num_classes\n\n self.mat = None\n\n\n\n def update(self, a, b):\n\n n = self.num_classes\n\n if self.mat is None:\n\n self.mat = torch.zeros((n, n), dtype=torch.int64, device=a.device)\n\n with torch.no_grad():\n\n k = (a >= 0) & (a < n)\n\n inds = n * a[k].to(torch.int64) + b[k]\n\n self.mat += torch.bincount(inds, minlength=n ** 2).reshape(n, n)\n\n\n\n def compute(self):\n\n h = self.mat.float()\n\n acc_global = torch.diag(h).sum() / h.sum()\n\n acc = torch.diag(h) / h.sum(1)\n\n iu = torch.diag(h) / (h.sum(1) + h.sum(0) - torch.diag(h))\n\n return acc_global, acc, iu\n\n\n\n def reduce_from_all_processes(self):\n\n if not torch.distributed.is_available():\n\n return\n\n if not torch.distributed.is_initialized():\n\n return\n\n torch.distributed.barrier()\n\n torch.distributed.all_reduce(self.mat)\n\n\n\n def __str__(self):\n\n acc_global, acc, iu = self.compute()\n\n return (\n\n \"global correct: {:.1f}\\n\"\n\n \"average row correct: {}\\n\"\n\n \"IoU: {}\\n\"\n\n \"mean IoU: {:.1f}\"\n\n ).format(\n\n acc_global.item() * 100,\n\n [\"{:.1f}\".format(i) for i in (acc * 100).tolist()],\n\n [\"{:.1f}\".format(i) for i in (iu * 100).tolist()],\n\n iu.mean().item() * 100,\n\n )\n\n\n\n\n\nclass TestIntegration(TestCase):\n\n def test_resnet18(self):\n\n import torchvision\n\n EXAMPLE_IMAGE_TENSORS = [torch.randn(3, 10, 10) for _ in range(3)]\n\n model = torchvision.models.resnet.resnet18(pretrained=True).eval()\n\n with torch.inference_mode():\n\n result_model_nt = model(ntnt_nograd(\n\n EXAMPLE_IMAGE_TENSORS)).unbind()\n\n result_model = model(torch.stack(EXAMPLE_IMAGE_TENSORS)).unbind()\n\n for t0, t1 in zip(result_model_nt, result_model):\n\n self.assertEqual(t0, t1)\n\n\n\n # non-regular shape smoke test\n\n EXAMPLE_IMAGE_TENSORS = [torch.randn(\n\n 3, 100 * i, 100) for i in range(1, 4)]\n\n with torch.inference_mode():\n\n model(ntnt_nograd(EXAMPLE_IMAGE_TENSORS))\n\n\n\n def test_segmentation_pretrained_test_only(self):\n\n\n\n def _test(seed, model_factory, use_confmat, num_classes=21):\n\n torch.manual_seed(seed)\n\n t1 = torch.randn(3, 3, 4, requires_grad=True)\n\n t2 = torch.randn(3, 3, 4, requires_grad=True)\n\n tr1 = torch.randn(3, 4, requires_grad=True)\n\n tr2 = torch.randn(3, 4, requires_grad=True)\n\n\n\n model1 = model_factory()\n\n # model1 = torchvision.models.segmentation.__dict__[model_name](\n\n # num_classes=num_classes, aux_loss=aux_loss, pretrained=True\n\n # )\n\n # model1.eval()\n\n\n\n # tensor run\n\n t_input = torch.stack([t1, t2])\n\n t_target = torch.stack([tr1, tr2])\n\n if use_confmat:\n\n confmat = ConfusionMatrix(num_classes)\n\n\n\n output1 = model1(t_input)\n\n if use_confmat:\n\n output1 = output1[\"out\"]\n\n else:\n\n output1 = output1[\"0\"]\n\n\n\n if use_confmat:\n\n confmat.update(t_target.flatten(), output1.argmax(1).flatten())\n\n confmat.reduce_from_all_processes()\n\n\n\n # nt run\n\n # model2 = torchvision.models.segmentation.__dict__[model_name](\n\n # num_classes=num_classes, aux_loss=aux_loss, pretrained=True\n\n # )\n\n # model2.eval()\n\n model2 = model_factory()\n\n nt_t1 = t1.clone().detach()\n\n nt_t2 = t2.clone().detach()\n\n nt_tr1 = tr1.clone().detach()\n\n nt_tr2 = tr2.clone().detach()\n\n\n\n nt_input = ntnt_nograd(\n\n [nt_t1, nt_t2])\n\n nt_target = ntnt_nograd(\n\n [nt_tr1, nt_tr2])\n\n if use_confmat:\n\n confmat2 = ConfusionMatrix(num_classes)\n\n\n\n with torch.inference_mode():\n\n output2 = model2(nt_input)\n\n if use_confmat:\n\n output2 = output2[\"out\"]\n\n else:\n\n output2 = output2[\"0\"]\n\n\n\n if use_confmat:\n\n for a, b in zip(nt_target, output2):\n\n confmat2.update(a.flatten(), b.argmax(0).flatten())\n\n\n\n if use_confmat:\n\n confmat2.reduce_from_all_processes()\n\n self.assertEqual(confmat.mat, confmat2.mat)\n\n\n\n # grad test\n\n self.assertEqual(ntnt_nograd(output1.unbind()), output2)\n\n\n\n # output1.sum().backward()\n\n # output2.sum().backward()\n\n\n\n # for (n1, p1), (n2, p2) in zip(model1.named_parameters(), model2.named_parameters()):\n\n # if p1.grad is not None:\n\n # self.assertEqual(p1.grad, p2.grad)\n\n # else:\n\n # self.assertIsNone(p2.grad)\n\n\n\n # # TODO: Re-enable under autograd support\n\n # self.assertEqual(t1.grad, nt_input.grad[0])\n\n # self.assertEqual(t2.grad, nt_input.grad[1])\n\n\n\n import torchvision\n\n _test(10, lambda: torchvision.models.segmentation.__dict__[\"fcn_resnet101\"](\n\n num_classes=21, aux_loss=\"store_true\", pretrained=True\n\n ).eval(), True)\n\n\n\n # _test(1010, lambda: IntermediateLayerGetter(getattr(torchvision.models, \"resnet18\")(\n\n # replace_stride_with_dilation=[False, False, False],\n\n # pretrained=True, norm_layer=NTFrozenBatchNorm2d), {'layer4': \"0\"}), False)\n\n\n\n def test_transformer_forward(self):\n\n EMBED_DIM = 32\n\n NHEAD = 8\n\n t = torch.nn.Transformer(EMBED_DIM, NHEAD, dropout=0.0)\n\n\n\n src0 = torch.randn(2, EMBED_DIM)\n\n src1 = torch.randn(4, EMBED_DIM)\n\n nt_src = ntnt_nograd([src0, src1])\n\n\n\n tgt0 = torch.randn(3, EMBED_DIM)\n\n tgt1 = torch.randn(5, EMBED_DIM)\n\n nt_tgt = ntnt_nograd([tgt0, tgt1])\n\n\n\n res_0 = t(src0.unsqueeze(1), tgt0.unsqueeze(1)).squeeze(1)\n\n res_1 = t(src1.unsqueeze(1), tgt1.unsqueeze(1)).squeeze(1)\n\n with torch.inference_mode():\n\n res_nt = t(nt_src, nt_tgt)\n\n\n\n for t0, t1 in zip(res_nt.unbind(), [res_0, res_1]):\n\n self.assertEqual(t0, t1)\n\n\n\n @unittest.skipIf(not TEST_CLASSY_VISION, \"No classy vision\")\n\n def test_fusion_resnext101_32x4d(self):\n\n @torch.inference_mode()\n\n def _test(dtype, use_channels_last):\n\n from classy_vision.models import build_model\n\n from torch.fx import symbolic_trace\n\n model = build_model({\"name\": \"resnext101_32x4d\"}).eval().cuda()\n\n model._initialize_weights(False)\n\n # This is needed to allow tracing, but for makes no difference for resnext\n\n model = model.classy_model\n\n fused = nestedtensor.fuse_conv_bn(model)\n\n fused = nestedtensor.fuse_conv_relu(fused)\n\n model = model.to(dtype)\n\n fused = fused.to(dtype)\n\n data = torch.randn(2, 3, 50, 50, device=torch.device('cuda'), dtype=dtype)\n\n ref_output = model(data)\n\n if use_channels_last:\n\n data = data.contiguous(memory_format=torch.channels_last)\n\n new_output = fused(data)\n\n if dtype == torch.float16:\n\n self.assertEqual(ref_output, new_output, prec=2e-3)\n\n else:\n\n self.assertEqual(ref_output, new_output)\n\n _test(torch.float32, False)\n\n _test(torch.float16, False)\n\n _test(torch.float16, True)\n\n _test(torch.float32, True)\n\n\n\n\n\nif __name__ == \"__main__\":\n\n unittest.main()\n", "file_path": "test/test_nested_tensor_integration.py", "rank": 87, "score": 53161.73731285545 }, { "content": "import torch\n\nimport nestedtensor\n\nimport unittest\n\nfrom utils_test_case import TestCase\n\n\n\nimport utils\n\n\n\n\n\ndef ntnt(x): return nestedtensor.nested_tensor(x, requires_grad=True)\n\n\n\n\n\ndef ntnt_nograd(x, device=None, dtype=None, channels_last=None):\n\n return nestedtensor.nested_tensor(x,\n\n requires_grad=False, device=device, dtype=dtype, channels_last=channels_last)\n\n\n\n# Given arguments to a constructor iterator over results for\n\n# as_nested_tensor and nested_tensor constructors.\n\n\n\n\n\ndef _iter_constructors():\n\n yield nestedtensor.as_nested_tensor\n\n yield nestedtensor.nested_tensor\n\n\n\n\n\ndef _test_property(self, fn):\n\n for constructor in _iter_constructors():\n\n # TODO: Used to be 3. Currently only supporting nested dim 1.\n\n num_nested_tensor = 1\n\n nested_tensor_lists = [utils.gen_nested_list(i, i, 3)\n\n for i in range(1, num_nested_tensor)]\n\n first_tensors = [utils.get_first_tensor(\n\n ntl) for ntl in nested_tensor_lists]\n\n nested_tensors = [constructor(ntl) for ntl in nested_tensor_lists]\n\n for nested_tensor, first_tensor in zip(nested_tensors, first_tensors):\n\n self.assertEqual(fn(nested_tensor), fn(first_tensor))\n\n\n\n\n\nclass TestNestedTensor(TestCase):\n\n\n\n def test_nested_constructor(self):\n\n for constructor in _iter_constructors():\n\n # TODO: Currently only supporting nested dim 1\n\n num_nested_tensor = 1\n\n # TODO: Shouldn't be constructable\n\n [utils.gen_nested_tensor(i, i, 3, constructor=constructor)\n\n for i in range(1, num_nested_tensor)]\n\n\n\n def test_list_constructor(self):\n\n \"\"\"\n\n This tests whether nestedtensor.as_nested_tensor stores Variables that share storage with\n\n the input Variables used for construction.\n\n \"\"\"\n\n tensors = []\n\n num_tensors = 16\n\n for i in range(num_tensors):\n\n tensors.append(utils.gen_float_tensor(i, (i + 1, 128, 128)))\n\n nested_tensor = nestedtensor.as_nested_tensor(tensors)\n\n for i in range(num_tensors):\n\n tensors[i].mul_(i + 2)\n\n for i in range(num_tensors):\n\n self.assertNotEqual(tensors[i], nested_tensor.unbind()[i])\n\n self.assertNotEqual(tensors[i].storage().data_ptr(\n\n ), nested_tensor.unbind()[i].storage().data_ptr())\n\n\n\n def test_as_nested_tensor(self):\n\n tensors = []\n\n num_tensors = 16\n\n for i in range(num_tensors):\n\n tensors.append(utils.gen_float_tensor(i, (i + 1, 128, 128)))\n\n\n\n # This should NOT create references\n\n nested_tensor = nestedtensor.as_nested_tensor(tensors)\n\n for i in range(num_tensors):\n\n tensors[i].mul_(i + 2)\n\n for i in range(num_tensors):\n\n self.assertNotEqual(tensors[i], nested_tensor.unbind()[i])\n\n\n\n # This should NOT create references\n\n nested_tensor = nestedtensor.nested_tensor(tensors)\n\n for i in range(num_tensors):\n\n tensors[i].mul_(i + 2)\n\n for i in range(num_tensors):\n\n self.assertNotEqual(tensors[i], nested_tensor.unbind()[i])\n\n\n\n nested_tensor1 = nestedtensor.as_nested_tensor(nested_tensor)\n\n self.assertTrue(nested_tensor1 is nested_tensor)\n\n self.assertRaises(NotImplementedError, lambda: nestedtensor.as_nested_tensor(\n\n nested_tensor, dtype=torch.int64))\n\n # self.assertTrue(nested_tensor2 is not nested_tensor)\n\n\n\n def test_constructor(self):\n\n for constructor in _iter_constructors():\n\n self.assertRaises(\n\n RuntimeError, lambda: constructor([3.0]))\n\n self.assertRaises(\n\n TypeError, lambda: constructor(torch.tensor([3.0])))\n\n for constructor2 in _iter_constructors():\n\n constructor(\n\n constructor2([torch.tensor([3.0])]))\n\n for constructor2 in _iter_constructors():\n\n self.assertRaises(RuntimeError, lambda: constructor(\n\n [torch.tensor([2.0]), constructor2([torch.tensor([3.0])])]))\n\n self.assertRaises(TypeError, lambda: constructor(4.0))\n\n\n\n def test_default_constructor(self):\n\n # nested_dim is 1 and dim is 1 too.\n\n for constructor in _iter_constructors():\n\n self.assertRaises(TypeError, lambda: constructor())\n\n default_nested_tensor = constructor([])\n\n default_tensor = torch.tensor([])\n\n self.assertEqual(default_nested_tensor.nested_dim(), 1)\n\n self.assertEqual(default_nested_tensor.nested_size().unbind(), [])\n\n self.assertEqual(default_nested_tensor.dim(), default_tensor.dim())\n\n self.assertEqual(default_nested_tensor.layout,\n\n default_tensor.layout)\n\n self.assertEqual(default_nested_tensor.device,\n\n default_tensor.device)\n\n self.assertEqual(default_nested_tensor.dtype, default_tensor.dtype)\n\n self.assertEqual(default_nested_tensor.requires_grad,\n\n default_tensor.requires_grad)\n\n self.assertIsNone(default_tensor.grad)\n\n self.assertEqual(default_nested_tensor.is_pinned(),\n\n default_tensor.is_pinned())\n\n\n\n # def test_scalar_constructor(self):\n\n # # Not a valid NestedTensor. This is not a list of Tensors or constructables for Tensors.\n\n # ntimeError, lambda: nestedtensor.nested_tensor([1.0]))\n\n\n\n def test_repr_string(self):\n\n for constructor in _iter_constructors():\n\n a = constructor(\n\n [\n\n ])\n\n expected = \"nested_tensor([\"\\\n\n \"\\n\\n])\"\n\n self.assertEqual(str(a), expected)\n\n self.assertEqual(repr(a), expected)\n\n\n\n a = constructor(\n\n [\n\n torch.tensor(1),\n\n ])\n\n expected = \"nested_tensor([\"\\\n\n \"\\n\\ttensor(1)\"\\\n\n \"\\n])\"\n\n # self.assertEqual(str(a), expected)\n\n # self.assertEqual(repr(a), expected)\n\n str(a)\n\n repr(a)\n\n\n\n a = constructor(\n\n [\n\n torch.tensor([[1, 2]]),\n\n torch.tensor([[4, 5]]),\n\n ])\n\n expected = \"nested_tensor([\"\\\n\n \"\\n\\ttensor([[1, 2]])\"\\\n\n \",\"\\\n\n \"\\n\\ttensor([[4, 5]])\"\\\n\n \"\\n])\"\n\n # self.assertEqual(str(a), expected)\n\n # self.assertEqual(repr(a), expected)\n\n str(a)\n\n repr(a)\n\n\n\n @unittest.skip(\"Currently only supporting nested dim 1.\")\n\n def test_repr_string_nested(self):\n\n for constructor in _iter_constructors():\n\n a = constructor(\n\n [\n\n [torch.tensor([[1, 2], [2, 3]]), torch.tensor([[3, 4]])],\n\n [torch.tensor([[4, 5]])]\n\n ])\n\n expected = \"nested_tensor([\"\\\n\n \"\\n\\tnested_tensor([\"\\\n\n \"\\n\\t\\ttensor([[1, 2]\"\\\n\n \",\"\\\n\n \"\\n\\t\\t [2, 3]])\"\\\n\n \",\"\\\n\n \"\\n\\t\\ttensor([[3, 4]])\"\\\n\n \"\\n\\t])\"\\\n\n \",\"\\\n\n \"\\n\\tnested_tensor([\"\\\n\n \"\\n\\t\\ttensor([[4, 5]])\"\\\n\n \"\\n\\t])\"\\\n\n \"\\n])\"\n\n # self.assertEqual(str(a), expected)\n\n # self.assertEqual(repr(a), expected)\n\n str(a)\n\n repr(a)\n\n\n\n def test_element_size(self):\n\n for constructor in _iter_constructors():\n\n nt1 = constructor([])\n\n self.assertEqual(nt1.element_size(), torch.randn(1).element_size())\n\n a = torch.randn(4).int()\n\n nt2 = constructor([a])\n\n self.assertEqual(a.element_size(), nt2.element_size())\n\n\n\n def test_nested_size(self):\n\n for constructor in _iter_constructors():\n\n a = constructor([])\n\n self.assertEqual(len(a.nested_size()), 0)\n\n self.assertRaises(RuntimeError, lambda: a.nested_size()[0])\n\n\n\n a = constructor([torch.tensor(1)])\n\n self.assertEqual(len(a.nested_size()), 1)\n\n self.assertEqual(a.nested_size()[0], torch.Size([]))\n\n self.assertEqual(a.nested_size(0), 1)\n\n self.assertRaises(IndexError, lambda: a.nested_size(1))\n\n\n\n a = constructor([torch.randn(1)])\n\n self.assertEqual(a.nested_size()[0], torch.Size([1]))\n\n self.assertEqual(a.nested_size()[0][0], 1)\n\n self.assertEqual(a.nested_size(0), 1)\n\n self.assertEqual(a.nested_size(1), (1,))\n\n self.assertRaises(IndexError, lambda: a.nested_size(2))\n\n\n\n a = constructor([torch.randn(1, 2)])\n\n self.assertEqual(a.nested_size()[0], torch.Size([1, 2]))\n\n self.assertEqual(a.nested_size(0), 1)\n\n self.assertEqual(a.nested_size(1), (1,))\n\n self.assertEqual(a.nested_size(2), (2,))\n\n self.assertRaises(IndexError, lambda: a.nested_size(3))\n\n\n\n # Make sure object is not bound to life-time of NestedTensor instance\n\n b = a.nested_size()\n\n del a\n\n self.assertEqual(len(b), 1)\n\n self.assertEqual(b[0], torch.Size([1, 2]))\n\n self.assertEqual(b[0][0], 1)\n\n self.assertEqual(b[0][1], 2)\n\n\n\n @unittest.skip(\"Currently only supporting nested dim 1.\")\n\n def test_nested_size_nested(self):\n\n for constructor in _iter_constructors():\n\n a = constructor(\n\n [[torch.randn(1)], [torch.randn(2), torch.randn(1)]])\n\n self.assertEqual(a.nested_size()[0][0], torch.Size([1]))\n\n self.assertEqual(a.nested_size()[1][0], torch.Size([2]))\n\n self.assertEqual(a.nested_size()[1][1], torch.Size([1]))\n\n self.assertEqual(a.nested_size(0), 2)\n\n self.assertEqual(a.nested_size(1), (1, 2))\n\n self.assertEqual(a.nested_size(2), ((1,), (2, 1)))\n\n self.assertRaises(IndexError, lambda: a.nested_size(3))\n\n\n\n a = constructor([[torch.tensor(1)],\n\n [torch.tensor(2), torch.tensor(1)]])\n\n self.assertEqual(a.nested_size()[0][0], torch.Size([]))\n\n self.assertEqual(a.nested_size()[1][0], torch.Size([]))\n\n self.assertEqual(a.nested_size()[1][1], torch.Size([]))\n\n self.assertEqual(a.nested_size(0), 2)\n\n self.assertEqual(a.nested_size(1), (1, 2))\n\n self.assertRaises(IndexError, lambda: a.nested_size(2))\n\n\n\n @torch.inference_mode()\n\n def test_nested_stride(self):\n\n for constructor in _iter_constructors():\n\n tensors = [torch.rand(1, 2, 4)[:, :, 0], torch.rand(\n\n 2, 3, 4)[:, 1, :], torch.rand(3, 4, 5)[1, :, :]]\n\n a = constructor(tensors)\n\n na = list(list(t.contiguous().stride()) for t in tensors)\n\n ans = a.nested_stride()\n\n result = tuple(ans[i] for i in range(len(ans)))\n\n for r, s in zip(result, na):\n\n self.assertEqual(r, s)\n\n\n\n def test_len(self):\n\n for constructor in _iter_constructors():\n\n a = constructor([torch.tensor([1, 2]),\n\n torch.tensor([3, 4]),\n\n torch.tensor([5, 6]),\n\n torch.tensor([7, 8])])\n\n self.assertEqual(len(a), 4)\n\n a = constructor([torch.tensor([1, 2]),\n\n torch.tensor([7, 8])])\n\n self.assertEqual(len(a), 2)\n\n a = constructor([torch.tensor([1, 2])])\n\n self.assertEqual(len(a), 1)\n\n\n\n def test_equal(self):\n\n for constructor in _iter_constructors():\n\n a1 = constructor([torch.tensor([1, 2]),\n\n torch.tensor([7, 8])])\n\n a2 = constructor([torch.tensor([1, 2]),\n\n torch.tensor([7, 8])])\n\n a3 = constructor([torch.tensor([3, 4]),\n\n torch.tensor([5, 6])])\n\n self.assertTrue((a1 == a2).all())\n\n self.assertTrue((a1 != a3).all())\n\n self.assertTrue(not (a1 != a2).any())\n\n self.assertTrue(not (a1 == a3).any())\n\n\n\n a1 = constructor([torch.tensor([1, 2]),\n\n torch.tensor([2, 8])])\n\n if constructor == nestedtensor.as_nested_tensor:\n\n self.assertRaises(NotImplementedError, lambda: constructor([torch.tensor([0, 1]),\n\n torch.tensor([1, 0])], dtype=torch.bool))\n\n self.assertRaises(NotImplementedError, lambda: constructor([torch.tensor([1, 0]),\n\n torch.tensor([0, 1])], dtype=torch.bool))\n\n else:\n\n a2 = constructor([torch.tensor([0, 1]),\n\n torch.tensor([1, 0])], dtype=torch.bool)\n\n a3 = constructor([torch.tensor([1, 0]),\n\n torch.tensor([0, 1])], dtype=torch.bool)\n\n self.assertEqual((a1 == 2), a2)\n\n self.assertEqual((a1 != 2), a3)\n\n self.assertEqual((a1 == 2.0), a2)\n\n self.assertEqual((a1 != 2.0), a3)\n\n\n\n def test_dim(self):\n\n for constructor in _iter_constructors():\n\n a1 = constructor([])\n\n self.assertEqual(a1.dim(), 1)\n\n a1 = constructor([torch.tensor(3.)])\n\n self.assertEqual(a1.dim(), 1)\n\n a1 = constructor([torch.tensor([1, 2, 3, 4])])\n\n self.assertEqual(a1.dim(), 2)\n\n\n\n @unittest.skip(\"Currently only supporting nested dim 1.\")\n\n def test_dim_nested(self):\n\n for constructor in _iter_constructors():\n\n a1 = constructor([\n\n [torch.tensor([1, 2, 3, 4])],\n\n [torch.tensor([5, 6, 7, 8]), torch.tensor([9, 0, 0, 0])]\n\n ])\n\n self.assertEqual(a1.dim(), 3)\n\n\n\n @unittest.skip(\"Currently only supporting nested dim 1.\")\n\n def test_nested_dim(self):\n\n for constructor in _iter_constructors():\n\n nt = constructor([torch.tensor(3)])\n\n for i in range(2, 5):\n\n nt = utils.gen_nested_tensor(i, i, 3, constructor=constructor)\n\n self.assertEqual(nt.nested_dim(), i)\n\n\n\n def test_unbind(self):\n\n # This is the most important operation. We want to make sure\n\n # that the Tensors we use for construction can be retrieved\n\n # and used independently while still being kept track of.\n\n\n\n # In fact nestedtensor.as_nested_tensor behaves just like a list. Any\n\n # list of torch.Tensors you initialize it with will be\n\n # unbound to have the same id. That is, they are indeed\n\n # the same Variable, since each torch::autograd::Variable has\n\n # assigned to it a unique PyObject* by construction.\n\n\n\n # TODO: Check that unbind returns torch.Tensors when nested_dim is 1\n\n # TODO: contiguous nestedtensors should return tuples of contiguous nestedtensors on dimension 0\n\n\n\n def _test_fn(unbind_fn):\n\n def _test(a, b, c, d, e):\n\n nt = nestedtensor.nested_tensor([a, b])\n\n a1, b1 = nt.unbind()\n\n self.assertTrue(a is not a1)\n\n self.assertTrue(b is not b1)\n\n\n\n # Currently only supporting nested dim 1\n\n # nt1 = nestedtensor.nested_tensor([[c, d], [e]])\n\n # nt11, nt12 = unbind_fn(nt1, 0)\n\n # c1, d1 = unbind_fn(nt11, 0)\n\n # e1 = unbind_fn(nt12, 0)[0]\n\n\n\n # self.assertTrue(c is not c1)\n\n # self.assertTrue(d is not d1)\n\n # self.assertTrue(e is not e1)\n\n\n\n nt = nestedtensor.nested_tensor([a, b])\n\n a1, b1 = unbind_fn(nt, 0)\n\n self.assertEqual(a, a1)\n\n self.assertEqual(b, b1)\n\n\n\n a = utils.gen_float_tensor(1, (2, 3)).add_(1)\n\n nt = nestedtensor.nested_tensor([a])\n\n self.assertEqual(a, unbind_fn(nt, 0)[0])\n\n\n\n _test(torch.tensor([1, 2]),\n\n torch.tensor([7, 8]),\n\n torch.tensor([3, 4]),\n\n torch.tensor([5, 6]),\n\n torch.tensor([6, 7]))\n\n _test(torch.tensor([1]),\n\n torch.tensor([7]),\n\n torch.tensor([3]),\n\n torch.tensor([5]),\n\n torch.tensor([6]))\n\n _test(torch.tensor(1),\n\n torch.tensor(7),\n\n torch.tensor(3),\n\n torch.tensor(5),\n\n torch.tensor(6))\n\n _test(torch.tensor([]),\n\n torch.tensor([]),\n\n torch.tensor([]),\n\n torch.tensor([]),\n\n torch.tensor([]))\n\n\n\n _test_fn(lambda x, dim: x.unbind(dim))\n\n _test_fn(lambda x, dim: torch.unbind(x, dim))\n\n\n\n def test_unbind_dim(self):\n\n # Unbinding across nested dimensions or tensors dimensions\n\n # is akin splitting up the tree across a level.\n\n\n\n def _test_fn(unbind_fn):\n\n # nt = nestedtensor.nested_tensor([])\n\n # self.assertEqual(unbind_fn(nt, 0), ())\n\n # self.assertRaises(IndexError, lambda: unbind_fn(nt, 1))\n\n\n\n a = torch.rand(3, 2)\n\n nt = nestedtensor.nested_tensor([a])\n\n # self.assertEqual(unbind_fn(nt, 0), (a,))\n\n result = (\n\n nestedtensor.nested_tensor([unbind_fn(a, 0)[0]]),\n\n nestedtensor.nested_tensor([unbind_fn(a, 0)[1]]),\n\n nestedtensor.nested_tensor([unbind_fn(a, 0)[2]]))\n\n # print('unbind_fn: ', unbind_fn)\n\n for x, y in zip(unbind_fn(nt, 1), result):\n\n # print('x: ', type(x), ' - y: ', type(y))\n\n self.assertEqual(x, y, ignore_contiguity=True)\n\n result = (\n\n nestedtensor.nested_tensor([unbind_fn(a, 1)[0]]),\n\n nestedtensor.nested_tensor([unbind_fn(a, 1)[1]]))\n\n for x, y in zip(unbind_fn(nt, 2), result):\n\n self.assertEqual(x, y, ignore_contiguity=True)\n\n\n\n b = torch.rand(2, 3)\n\n nt = nestedtensor.nested_tensor([a, b])\n\n self.assertEqual(unbind_fn(nt, 0), (a, b))\n\n result = (\n\n nestedtensor.nested_tensor(\n\n [unbind_fn(a, 0)[0], unbind_fn(b, 0)[0]]),\n\n nestedtensor.nested_tensor(\n\n [unbind_fn(a, 0)[1], unbind_fn(b, 0)[1]]),\n\n nestedtensor.nested_tensor([unbind_fn(a, 0)[2]]))\n\n for x, y in zip(unbind_fn(nt, 1), result):\n\n self.assertEqual(x, y, ignore_contiguity=True)\n\n # TODO: Add more tensors and unbind across more dimensions to create mixing\n\n\n\n c = torch.rand(4, 3)\n\n # TODO: Currently only supporting nested dim 1\n\n # nt = nestedtensor.nested_tensor([[a], [b, c]])\n\n # nt_a, nt_b = unbind_fn(nt, 0)\n\n # self.assertEqual(nt_a, nestedtensor.nested_tensor(\n\n # [a]), ignore_contiguity=True)\n\n # self.assertEqual(nt_b, nestedtensor.nested_tensor(\n\n # [b, c]), ignore_contiguity=True)\n\n # result = (\n\n # nestedtensor.nested_tensor([a, b]),\n\n # nestedtensor.nested_tensor([c]))\n\n # for x, y in zip(unbind_fn(nt, 1), result):\n\n # self.assertEqual(x, y, ignore_contiguity=True)\n\n _test_fn(lambda x, dim: x.unbind(dim))\n\n _test_fn(lambda x, dim: torch.unbind(x, dim))\n\n\n\n def test_size(self):\n\n for constructor in _iter_constructors():\n\n a = constructor([])\n\n self.assertEqual(a.size(), (0,))\n\n\n\n a = constructor([torch.tensor(1)])\n\n self.assertEqual(a.size(), (1,))\n\n\n\n a = constructor([torch.tensor(1), torch.tensor(2)])\n\n self.assertEqual(a.size(), (2,))\n\n\n\n # TODO: Currently only supporting nested dim 1\n\n # a = constructor([[torch.rand(1, 8),\n\n # torch.rand(3, 8)],\n\n # [torch.rand(7, 8)]])\n\n # self.assertEqual(a.size(), (2, None, None, 8))\n\n\n\n a = constructor([torch.rand(1, 2),\n\n torch.rand(1, 8)])\n\n self.assertEqual(a.size(), (2, 1, None))\n\n\n\n a = constructor([torch.rand(3, 4),\n\n torch.rand(5, 4)])\n\n self.assertEqual(a.size(), (2, None, 4))\n\n\n\n def test_to_tensor(self):\n\n for constructor in _iter_constructors():\n\n a = constructor([])\n\n self.assertEqual(a.to_tensor(0), torch.tensor([]))\n\n self.assertRaises(IndexError, lambda: a.to_tensor(1))\n\n self.assertRaises(IndexError, lambda: a.to_tensor(2))\n\n\n\n a = constructor([torch.tensor(1)])\n\n self.assertEqual(a.to_tensor(0), torch.tensor([1]))\n\n self.assertRaises(IndexError, lambda: a.to_tensor(1))\n\n self.assertRaises(IndexError, lambda: a.to_tensor(2))\n\n\n\n # Currently only supporting nested dime 1.\n\n # t_a = torch.randn(2, 3)\n\n # t_b = torch.randn(2, 3)\n\n # a = constructor([[t_a, t_b]])\n\n # result = torch.stack([torch.stack([t_a, t_b])])\n\n # self.assertEqual(a.to_tensor(), result)\n\n # self.assertEqual(a.to_tensor(0), result)\n\n\n\n # nested dim 1 change: Was already commented out\n\n # self.assertEqual(a.to_tensor(1), nestedtensor.as_nested_tensor(\n\n # [torch.stack([t_a, t_b])]))\n\n # self.assertEqual(a.to_tensor(\n\n # 2), nestedtensor.as_nested_tensor([[t_a, t_b]]))\n\n # self.assertEqual(a.to_tensor(\n\n # 3), nestedtensor.as_nested_tensor([[t_a, t_b]]))\n\n\n\n # self.assertRaises(RuntimeError, lambda: a.to_tensor(1))\n\n # self.assertRaises(RuntimeError, lambda: a.to_tensor(2))\n\n # self.assertRaises(RuntimeError, lambda: a.to_tensor(3))\n\n # self.assertRaises(IndexError, lambda: a.to_tensor(4))\n\n\n\n # Currently only supporting nested dime 1.\n\n # t_c = torch.randn(2, 3)\n\n # t_d = torch.randn(2, 3)\n\n # a = constructor([[t_a, t_b], [t_c, t_d]])\n\n # result = torch.stack(\n\n # [torch.stack([t_a, t_b]), torch.stack([t_c, t_d])])\n\n # self.assertEqual(a.to_tensor(), result)\n\n # self.assertEqual(a.to_tensor(0), result)\n\n\n\n # nested dim 1 change: Was already commented out\n\n # self.assertEqual(a.to_tensor(1), nestedtensor.as_nested_tensor(\n\n # [torch.stack([t_a, t_b]), torch.stack([t_c, t_d])]))\n\n # self.assertEqual(a.to_tensor(2), nestedtensor.as_nested_tensor(\n\n # [[t_a, t_b], [t_c, t_d]]))\n\n # self.assertEqual(a.to_tensor(3), nestedtensor.as_nested_tensor(\n\n # [[t_a, t_b], [t_c, t_d]]))\n\n\n\n # self.assertRaises(RuntimeError, lambda: a.to_tensor(1))\n\n # self.assertRaises(RuntimeError, lambda: a.to_tensor(2))\n\n # self.assertRaises(RuntimeError, lambda: a.to_tensor(3))\n\n # self.assertRaises(IndexError, lambda: a.to_tensor(4))\n\n\n\n # Currently only supporting nested dime 1.\n\n # t_e = torch.randn(3, 2)\n\n # t_f = torch.randn(3, 2)\n\n # a = constructor([[t_a, t_b], [t_e, t_f]])\n\n # self.assertRaises(IndexError, lambda: a.to_tensor(0))\n\n\n\n # nested dim 1 change: Was already commented out\n\n # self.assertEqual(a.to_tensor(1), nestedtensor.as_nested_tensor(\n\n # [torch.stack([t_a, t_b]), torch.stack([t_e, t_f])]))\n\n # self.assertEqual(a.to_tensor(2), nestedtensor.as_nested_tensor(\n\n # [[t_a, t_b], [t_e, t_f]]))\n\n # self.assertEqual(a.to_tensor(3), nestedtensor.as_nested_tensor(\n\n # [[t_a, t_b], [t_e, t_f]]))\n\n\n\n # self.assertRaises(RuntimeError, lambda: a.to_tensor(1))\n\n # self.assertRaises(RuntimeError, lambda: a.to_tensor(2))\n\n # self.assertRaises(RuntimeError, lambda: a.to_tensor(3))\n\n # self.assertRaises(IndexError, lambda: a.to_tensor(4))\n\n\n\n def test_to_nested_tensor(self):\n\n for constructor in _iter_constructors():\n\n a = constructor([])\n\n self.assertEqual(a.to_nested_tensor(), constructor(\n\n []), ignore_contiguity=True)\n\n self.assertEqual(a.to_nested_tensor(\n\n 0), constructor([]), ignore_contiguity=True)\n\n self.assertEqual(a, a.to_nested_tensor(1))\n\n self.assertRaises(IndexError, lambda: a.to_nested_tensor(2))\n\n\n\n a = constructor([torch.tensor(1)])\n\n self.assertEqual(a.to_nested_tensor(), constructor(\n\n [torch.tensor(1)]), ignore_contiguity=True)\n\n self.assertEqual(a.to_nested_tensor(0), constructor(\n\n [torch.tensor(1)]), ignore_contiguity=True)\n\n self.assertRaises(IndexError, lambda: a.to_nested_tensor(1))\n\n self.assertRaises(IndexError, lambda: a.to_nested_tensor(2))\n\n\n\n t_a = torch.randn(2, 3)\n\n t_b = torch.randn(3, 2)\n\n a = constructor([t_a, t_b])\n\n result = constructor([t_a, t_b])\n\n self.assertEqual(a.to_nested_tensor(), result)\n\n self.assertEqual(a.to_nested_tensor(0), result)\n\n\n\n # Currently only supporting nested dime 1.\n\n # result = constructor([t_a.unbind(0), t_b.unbind(0)])\n\n # self.assertEqual(a.to_nested_tensor(1), result)\n\n # result = constructor(\n\n # [list(map(lambda x: x.unbind(), t_a.unbind())),\n\n # list(map(lambda x: x.unbind(), t_b.unbind()))]\n\n # )\n\n # self.assertEqual(a.to_nested_tensor(2), result)\n\n # self.assertRaises(IndexError, lambda: a.to_nested_tensor(3))\n\n\n\n # Currently only supporting nested dime 1.\n\n # a = constructor([[t_a, t_b]])\n\n # result = constructor([[t_a, t_b]])\n\n # self.assertEqual(a.to_nested_tensor(), result)\n\n # self.assertEqual(a.to_nested_tensor(0), result)\n\n # self.assertEqual(a.to_nested_tensor(1), result)\n\n # result = constructor([[t_a.unbind(0), t_b.unbind(0)]])\n\n # self.assertEqual(a.to_nested_tensor(2), result)\n\n # result = constructor([[list(map(lambda x: x.unbind(), t_a.unbind())),\n\n # list(map(lambda x: x.unbind(), t_b.unbind()))]])\n\n # self.assertEqual(a.to_nested_tensor(3), result)\n\n # self.assertRaises(IndexError, lambda: a.to_nested_tensor(4))\n\n\n\n # t_c = torch.randn(2, 4)\n\n # a = constructor([[t_a, t_b], [t_c]])\n\n # result = constructor([[t_a, t_b], [t_c]])\n\n # self.assertEqual(a.to_nested_tensor(), result)\n\n # self.assertEqual(a.to_nested_tensor(0), result)\n\n # self.assertEqual(a.to_nested_tensor(1), result)\n\n # result = constructor(\n\n # [[t_a.unbind(), t_b.unbind()], [t_c.unbind()]])\n\n # self.assertEqual(a.to_nested_tensor(2), result)\n\n # result = constructor([[list(map(lambda x: x.unbind(), t_a.unbind())),\n\n # list(map(lambda x: x.unbind(), t_b.unbind()))],\n\n # [list(map(lambda x: x.unbind(), t_c.unbind()))]])\n\n # self.assertEqual(a.to_nested_tensor(3), result)\n\n # self.assertRaises(IndexError, lambda: a.to_nested_tensor(4))\n\n\n\n # t = torch.randn(2, 3)\n\n # self.assertEqual(t, nestedtensor.to_nested_tensor(t, 0))\n\n # self.assertEqual(ntnt_nograd(t.unbind()),\n\n # nestedtensor.to_nested_tensor(t, 1))\n\n # self.assertEqual(ntnt_nograd(\n\n # [ti.unbind() for ti in t.unbind()]), nestedtensor.to_nested_tensor(t, 2))\n\n # self.assertRaises(\n\n # IndexError, lambda: nestedtensor.to_nested_tensor(t, 3))\n\n\n\n def test_to(self):\n\n tensors = [torch.randn(1, 8),\n\n torch.randn(3, 8),\n\n torch.randn(7, 8)]\n\n a1 = nestedtensor.nested_tensor(tensors)\n\n self.assertRaises(NotImplementedError, lambda: a1.to(torch.int64))\n\n # for a, b in zip(tensors, a2.unbind()):\n\n # self.assertEqual(a.to(torch.int64), b)\n\n\n\n def test_dtype(self):\n\n _test_property(self, lambda x: x.dtype)\n\n\n\n def test_device(self):\n\n _test_property(self, lambda x: x.device)\n\n\n\n def test_layout(self):\n\n _test_property(self, lambda x: x.layout)\n\n\n\n def test_requires_grad(self):\n\n _test_property(self, lambda x: x.requires_grad)\n\n tensors = [torch.randn(1, 8),\n\n torch.randn(3, 8),\n\n torch.randn(7, 8)]\n\n a1 = ntnt_nograd(tensors)\n\n self.assertIsNone(a1.grad)\n\n\n\n @unittest.skip(\"Not implemented\")\n\n @unittest.skipIf(not torch.cuda.is_available(), \"CUDA not enabled.\")\n\n def test_pin_memory(self):\n\n # Check if it can be applied widely\n\n nt = utils.gen_nested_tensor(1, 4, 3)\n\n nt1 = nt.pin_memory()\n\n\n\n # Make sure it's actually a copy\n\n self.assertFalse(nt.is_pinned())\n\n self.assertTrue(nt1.is_pinned())\n\n a1 = torch.randn(1, 2)\n\n a2 = torch.randn(2, 3)\n\n nt2 = nestedtensor.as_nested_tensor([a1, a2])\n\n self.assertFalse(a1.is_pinned())\n\n self.assertFalse(a2.is_pinned())\n\n\n\n # Double check property transfers\n\n nt3 = nt2.pin_memory()\n\n self.assertFalse(nt2.is_pinned())\n\n self.assertTrue(nt3.is_pinned())\n\n\n\n # Check whether pinned memory is applied to constiuents\n\n # and relevant constiuents only.\n\n a3, a4 = nt3.unbind()\n\n a5, a6 = nt2.unbind()\n\n self.assertFalse(a1.is_pinned())\n\n self.assertFalse(a2.is_pinned())\n\n self.assertTrue(a3.is_pinned())\n\n self.assertTrue(a4.is_pinned())\n\n self.assertFalse(a5.is_pinned())\n\n self.assertFalse(a6.is_pinned())\n\n\n\n @unittest.skip(\"Currently only supporting nested dim 1.\")\n\n def test_getitem(self):\n\n a, b, c = torch.randn(3, 4), torch.randn(4, 3), torch.randn(1, 3)\n\n nt = ntnt_nograd([[a, b], [c]])\n\n tmp = nt[0, :, 0]\n\n self.assertEqual(tmp[0], a[:, 0])\n\n self.assertEqual(tmp[1], b[:, 0])\n\n self.assertEqual(nt[0, :, 0].contiguous(),\n\n ntnt_nograd([a[:, 0], b[:, 0]]))\n\n self.assertEqual(nt[None], ntnt_nograd([[[a, b], [c]]]))\n\n self.assertEqual(nt[0], ntnt_nograd([a, b])) # Supports grad\n\n self.assertEqual(nt[:], nt)\n\n self.assertEqual(nt[:, 0], ntnt_nograd([a, c]))\n\n self.assertEqual(nt[-1:], ntnt_nograd([[c]]))\n\n self.assertEqual(nt[-1:, 0], ntnt_nograd([c]))\n\n self.assertEqual(nt[:, -1], ntnt_nograd([b, c]))\n\n self.assertEqual(nt[-1:, -1], ntnt_nograd([c]))\n\n self.assertEqual(nt[:, -1:], ntnt_nograd([[b], [c]]))\n\n self.assertEqual(nt[-1:, -1:], ntnt_nograd([[c]]))\n\n self.assertEqual(nt[:, -1:, None], ntnt_nograd([[b[None]], [c[None]]]))\n\n self.assertEqual(nt[-1:, :, None], ntnt_nograd([[c[None]]]))\n\n self.assertEqual(nt[:, 1:, None], ntnt_nograd([[b[None]], []]))\n\n nt = nestedtensor.nested_tensor([[a, b]])\n\n self.assertEqual(nt[0, 0], ntnt_nograd([a[0], b[0]]))\n\n self.assertEqual(nt[0, 1:], ntnt_nograd([a[1:], b[1:]]))\n\n self.assertEqual(nt[:1, :, 1:], ntnt_nograd([[a[1:], b[1:]]]))\n\n self.assertEqual(nt[:, :], nt)\n\n self.assertEqual(nt[:, None], ntnt_nograd([[[a, b]]]))\n\n self.assertRaisesRegex(IndexError,\n\n \"Dimension out of range \\(expected to be in range of \\[-1, 0\\], but got 2\\)\",\n\n lambda: nt[2])\n\n\n\n def test_cat(self):\n\n a = torch.arange(12).reshape(3, 4)\n\n b = a + 12\n\n c = b + 12\n\n\n\n nt0 = ntnt_nograd([a, b])\n\n nt1 = ntnt_nograd([c])\n\n self.assertEqual(torch.cat([nt0, nt1], dim=0), ntnt_nograd([a, b, c]))\n\n self.assertEqual(torch.cat(\n\n [nt0, nt1], dim=1), ntnt_nograd([torch.cat([a, c]), b]))\n\n self.assertEqual(torch.cat([nt0, nt1], dim=2), ntnt_nograd(\n\n [torch.cat([a, c], dim=1), b]))\n\n\n\n def test_stack(self):\n\n a = torch.arange(12).reshape(3, 4)\n\n b = a + 12\n\n c = b + 12\n\n\n\n nt0 = ntnt_nograd([a, b])\n\n nt1 = ntnt_nograd([c])\n\n # Currently only supporting nested dime 1.\n\n # self.assertEqual(torch.stack(\n\n # [nt0, nt1], dim=0), ntnt_nograd([[a, b], [c]]))\n\n self.assertEqual(torch.stack(\n\n [nt0, nt1], dim=1),\n\n ntnt_nograd([torch.stack([a, c]), b.reshape(1, 3, 4)]))\n\n self.assertEqual(torch.stack(\n\n [nt0, nt1], dim=2),\n\n ntnt_nograd([torch.stack([a, c], dim=1), b.reshape(3, 1, 4)]))\n\n\n\n @unittest.skip(\"sparse csr currently broken\")\n\n def test_to_sparse_csr(self):\n\n a = torch.arange(3) + 1\n\n b = torch.arange(4) + 1\n\n c = torch.arange(2) + 1\n\n nt = ntnt_nograd([a, b, c])\n\n data = nt.to_padded_tensor(padding=0)\n\n st = nt.to_sparse_csr_tensor()\n\n self.assertEqual(data, nt.to_sparse_csr_tensor().to_dense())\n\n nt = ntnt_nograd([a.unsqueeze(1), b.unsqueeze(1)])\n\n self.assertRaisesRegex(RuntimeError,\n\n \"Given tensor must be of dimension 2, got dimension 3\",\n\n lambda: nt.to_sparse_csr_tensor())\n\n\n\n @unittest.skipIf(not torch.cuda.is_available(), \"CUDA not enabled.\")\n\n def test_to_padded_tensor_cuda_dim2(self):\n\n import random\n\n random.seed(1010)\n\n tensors = [torch.randn(random.randint(3, 30)) for _ in range(5)]\n\n nt = ntnt_nograd(tensors, device=torch.device('cuda'))\n\n data0 = nt.to_padded_tensor(padding=1)\n\n nt = ntnt_nograd(tensors, device=torch.device('cpu'))\n\n data1, mask1 = nt.to_tensor_mask()\n\n data1.masked_fill_(mask1.logical_not(), 1)\n\n self.assertEqual(data0, data1)\n\n\n\n @unittest.skipIf(not torch.cuda.is_available(), \"CUDA not enabled.\")\n\n def test_to_padded_tensor_cuda_dim3(self):\n\n import random\n\n random.seed(1010)\n\n tensors = [torch.randn(random.randint(3, 30), random.randint(3, 30))\n\n for _ in range(5)]\n\n nt = ntnt_nograd(tensors, device=torch.device('cuda'))\n\n data0 = nt.to_padded_tensor(padding=1)\n\n nt = ntnt_nograd(tensors, device=torch.device('cpu'))\n\n data1, mask1 = nt.to_tensor_mask()\n\n data1.masked_fill_(mask1.logical_not(), 1)\n\n self.assertEqual(data0, data1)\n\n\n\n @unittest.skipIf(not torch.cuda.is_available(), \"CUDA not enabled.\")\n\n def test_to_padded_tensor_cuda_dim4(self):\n\n import random\n\n random.seed(1010)\n\n tensors = [torch.randn(random.randint(3, 30),\n\n random.randint(3, 30),\n\n random.randint(3, 30)) for _ in range(5)]\n\n nt = ntnt_nograd(tensors, device=torch.device('cuda'))\n\n data0 = nt.to_padded_tensor(padding=1)\n\n nt = ntnt_nograd(tensors, device=torch.device('cpu'))\n\n data1, mask1 = nt.to_tensor_mask()\n\n data1.masked_fill_(mask1.logical_not(), 1)\n\n self.assertEqual(data0, data1)\n\n\n\n @unittest.skipIf(not torch.cuda.is_available(), \"CUDA not enabled.\")\n\n def test_to_tensor_mask_cuda(self):\n\n import random\n\n random.seed(110)\n\n tensors = [random.randint(2, 4) for _ in range(3)]\n\n tensors = [torch.arange(t * 3).reshape(t, 3).float() for t in tensors]\n\n nt = ntnt_nograd(tensors, device=torch.device('cuda'))\n\n data, mask = nt.to_tensor_mask(mask_dim=2)\n\n nt1 = ntnt_nograd(tensors, device=torch.device('cpu'))\n\n data1, mask1 = nt1.to_tensor_mask(mask_dim=2)\n\n self.assertEqual(data, data1)\n\n self.assertEqual(mask, mask1)\n\n\n\n def test_to_mask(self):\n\n import random\n\n random.seed(110)\n\n tensors = [random.randint(2, 4) for _ in range(3)]\n\n tensors = [torch.arange(t * 3).reshape(t, 3).float() for t in tensors]\n\n nt = ntnt_nograd(tensors)\n\n data, mask0 = nt.to_tensor_mask(mask_dim=2)\n\n mask1 = torch.ops.nestedtensor.to_mask(nt, 2)\n\n self.assertEqual(mask0, mask1)\n\n\n\n @unittest.skipIf(not torch.cuda.is_available(), \"CUDA not enabled.\")\n\n def test_nchw_nhwc_cuda(self):\n\n def _test(dtype):\n\n def _prod(tup):\n\n r = 1\n\n for t in tup:\n\n r = r * t\n\n return r\n\n import random\n\n random.seed(1010)\n\n shapes = [(32,\n\n random.randint(20, 100),\n\n random.randint(20, 100)) for _ in range(20)]\n\n tensors = [torch.randn(*s) for s in shapes]\n\n nt = ntnt_nograd(tensors, device=torch.device('cuda'), dtype=dtype)\n\n nt0 = nestedtensor.transpose_nchw_nhwc(nt)\n\n tensors1 = [t.permute(1, 2, 0) for t in tensors]\n\n nt1 = ntnt_nograd(tensors1, device=torch.device('cuda'), dtype=dtype)\n\n self.assertEqual(nt0, nt1)\n\n nt2 = nestedtensor.transpose_nhwc_nchw(nt0)\n\n self.assertEqual(nt, nt2)\n\n _test(torch.float16)\n\n _test(torch.float32)\n\n\n\n @unittest.skipIf(not torch.cuda.is_available(), \"CUDA not enabled.\")\n\n def test_channels_last_cuda(self):\n\n def _test(dtype):\n\n def _prod(tup):\n\n r = 1\n\n for t in tup:\n\n r = r * t\n\n return r\n\n import random\n\n random.seed(1010)\n\n shapes = [(30,\n\n random.randint(20, 40),\n\n random.randint(20, 40)) for _ in range(7)]\n\n tensors = [torch.randn(*s) for s in shapes]\n\n tensors_channel_last = [t.unsqueeze(0).to(memory_format=torch.channels_last).squeeze(0) for t in tensors]\n\n nt = ntnt_nograd(tensors, device=torch.device('cuda'), dtype=dtype, channels_last=True)\n\n for (t_i, nt_i) in zip(tensors_channel_last, nt):\n\n if (dtype == torch.float16):\n\n self.assertEqual(t_i, nt_i, prec=1e-2)\n\n else:\n\n self.assertEqual(t_i, nt_i)\n\n\n\n _test(torch.float16)\n\n _test(torch.float32)\n\n\n\n\n\nclass TestContiguous(TestCase):\n\n\n\n @unittest.skip(\"Nested dim currently restricted to 1.\")\n\n def test_contiguous_nested(self):\n\n for _ in range(1, 10):\n\n # data = gen_nested_list(1, 2, 3, size_low=1, size_high=3)\n\n data = [[torch.rand(1, 2), torch.rand(3, 4)], [torch.rand(5, 6)]]\n\n nt = ntnt_nograd(data)\n\n self.assertTrue(nt.is_contiguous())\n\n # buf = nt.flatten()\n\n self.assertEqual(nt, nt)\n\n a = nt + nt\n\n nt.cos_()\n\n nt.cos()\n\n\n\n def test_contiguous(self):\n\n a = nestedtensor.as_nested_tensor([torch.tensor([1, 2]),\n\n torch.tensor([3, 4]),\n\n torch.tensor([5, 6]),\n\n torch.tensor([7, 8])])\n\n self.assertTrue(a.is_contiguous())\n\n\n\n\n\nif __name__ == \"__main__\":\n\n unittest.main()\n", "file_path": "test/test_nested_tensor_class.py", "rank": 88, "score": 53161.73731285545 }, { "content": "import torch\n\nimport nestedtensor\n\nimport unittest\n\nfrom utils_test_case import TestCase\n\nimport random\n\nimport utils\n\nfrom torch.nn import functional as F\n\nfrom detr_nestedtensor import DETRNestedTensor\n\nfrom torch import nn\n\n\n\n\n\ndef _iter_constructors():\n\n yield nestedtensor.as_nested_tensor\n\n yield nestedtensor.nested_tensor\n\n\n\n\n\ndef ntnt(x): return nestedtensor.nested_tensor(x, requires_grad=True)\n\n\n\n\n\ndef ntnt_nograd(x, device=None, dtype=None): return nestedtensor.nested_tensor(\n\n x, requires_grad=False, device=device, dtype=dtype)\n\n\n\n\n\nclass TestFunctional(TestCase):\n\n def test_nll_loss(self):\n\n utils.gen_float_tensor(1, (40, 5))\n\n utils.gen_float_tensor(1, (40,))\n\n\n\n def test_addmm(self):\n\n torch.rand(5), torch.rand(4, 5)\n\n nestedtensor.nested_tensor(\n\n [torch.rand(1, 4), torch.rand(1, 4), torch.rand(4, 4)]\n\n )\n\n\n\n @torch.inference_mode()\n\n @unittest.skipIf(not torch.cuda.is_available(), \"Test requires cuda\")\n\n def test_add(self):\n\n nt = ntnt_nograd([torch.randn(4, 2, 5), torch.randn(4, 3, 5)],\n\n device=torch.device('cuda'), dtype=torch.half)\n\n o = torch.randn(1, 4, 1, 1)\n\n o = o.cuda().half()\n\n res = nt + o\n\n\n\n def _test_conv2d_dtype(self, dtype, weight, device, shapes,\n\n stride=None, padding=None, dilation=None,\n\n groups=None):\n\n if stride is None:\n\n stride = [1, 1]\n\n if padding is None:\n\n padding = [0, 0]\n\n if dilation is None:\n\n dilation = [1, 1]\n\n if groups is None:\n\n groups = 1\n\n\n\n def _prod(tup):\n\n r = 1\n\n for t in tup:\n\n r = r * t\n\n return r\n\n\n\n def _test(ts, weight, stride, padding, dilation, groups):\n\n nt = ntnt_nograd(ts, device=device, dtype=dtype)\n\n nt_out = torch.conv2d(nt, weight, stride=stride,\n\n padding=padding, dilation=dilation,\n\n groups=groups)\n\n for i, (t, nt_out_i) in enumerate(zip(ts, nt_out.unbind())):\n\n t_out = torch.conv2d(t.unsqueeze(0), weight,\n\n stride=stride, padding=padding,\n\n dilation=dilation,\n\n groups=groups).squeeze(0)\n\n self.assertEqual(t_out, nt_out_i)\n\n ts = []\n\n for s in shapes:\n\n ts.append(torch.randn(_prod(s)).reshape(*s).to(device=device, dtype=dtype))\n\n weight = weight.to(device=device, dtype=dtype)\n\n _test(ts, weight, stride, padding, dilation, groups)\n\n\n\n @torch.inference_mode()\n\n @unittest.skipIf(not torch.cuda.is_available(), \"Test requires cuda\")\n\n def test_conv2d_1x1_cuda(self):\n\n shapes = [(2, 2, 3), (2, 4, 2), (2, 2, 2)]\n\n weight = torch.randn(3*2*1*1).reshape(3, 2, 1, 1)\n\n self._test_conv2d_dtype(torch.float16, weight, torch.device('cuda'), shapes)\n\n self._test_conv2d_dtype(torch.float32, weight, torch.device('cuda'), shapes)\n\n\n\n @torch.inference_mode()\n\n def test_conv2d_1x1_cpu(self):\n\n shapes = [(2, 2, 3), (2, 4, 2), (2, 2, 2)]\n\n weight = torch.randn(3*2*1*1).reshape(3, 2, 1, 1)\n\n self._test_conv2d_dtype(torch.float16, weight, torch.device('cpu'), shapes)\n\n self._test_conv2d_dtype(torch.float32, weight, torch.device('cpu'), shapes)\n\n\n\n @torch.inference_mode()\n\n @unittest.skipIf(not torch.cuda.is_available(), \"Test requires cuda\")\n\n def test_conv2d_3x3_cuda(self):\n\n shapes = [(2, 4, 5), (2, 5, 3), (2, 3, 3)]\n\n weight = torch.randn(3*2*3*3).reshape(3, 2, 3, 3)\n\n self._test_conv2d_dtype(torch.float16, weight, torch.device('cuda'), shapes)\n\n self._test_conv2d_dtype(torch.float32, weight, torch.device('cuda'), shapes)\n\n\n\n @torch.inference_mode()\n\n def test_conv2d_3x3_cpu(self):\n\n shapes = [(2, 4, 5), (2, 5, 3), (2, 3, 3)]\n\n weight = torch.randn(3*2*3*3).reshape(3, 2, 3, 3)\n\n # self._test_conv2d_dtype(torch.float16, weight, torch.device('cpu'), shapes)\n\n self._test_conv2d_dtype(torch.float32, weight, torch.device('cpu'), shapes)\n\n\n\n @torch.inference_mode()\n\n @unittest.skipIf(not torch.cuda.is_available(), \"Test requires cuda\")\n\n def test_conv2d_3x3_resnext_common_cuda(self):\n\n shapes = [(32, 4, 5), (32, 5, 3), (32, 3, 3)]\n\n weight = torch.randn(32*1*3*3).reshape(32, 1, 3, 3)\n\n for dtype in [torch.float16, torch.float32]:\n\n stride = [1, 1] # default\n\n padding = [1, 1]\n\n dilation = [1, 1] # default\n\n groups = 32\n\n self._test_conv2d_dtype(dtype, weight, torch.device('cuda'),\n\n shapes, stride=stride, padding=padding,\n\n dilation=dilation, groups=groups)\n\n\n\n @torch.inference_mode()\n\n @unittest.skipIf(not torch.cuda.is_available(), \"Test requires cuda\")\n\n def test_conv2d_3x3_resnext_input_cuda(self):\n\n shapes = [(4, 3, 2), (4, 3, 3), (4, 2, 3)]\n\n weight = torch.randn(5, 4, 2, 2)\n\n for dtype in [torch.float16, torch.float32]:\n\n stride = [1, 1]\n\n padding = [1, 1]\n\n dilation = [1, 1]\n\n groups = 1\n\n self._test_conv2d_dtype(dtype, weight, torch.device('cuda'),\n\n shapes, stride=stride, padding=padding,\n\n dilation=dilation, groups=groups)\n\n\n\n def test_contiguousity(self):\n\n initial_t = torch.rand(2, 5, 10, 15)\n\n self.assertEqual(True, initial_t.is_contiguous())\n\n\n\n non_contiguous_1 = initial_t.select(1, 0)\n\n non_contiguous_2 = initial_t.select(1, 0)\n\n self.assertEqual(False, non_contiguous_1.is_contiguous())\n\n\n\n relu = torch.nn.ReLU()\n\n t_cont = relu(non_contiguous_1)\n\n self.assertEqual(True, t_cont.is_contiguous())\n\n\n\n nt = nestedtensor.nested_tensor([non_contiguous_1, non_contiguous_2])\n\n self.assertEqual(True, nt.is_contiguous())\n\n\n\n # nt_cont = relu(nt)\n\n # self.assertEqual(True, nt_cont.is_contiguous())\n\n\n\n @torch.inference_mode()\n\n def test_nn_embedding(self):\n\n inputs = [torch.randint(100, (L,)) for L in torch.randint(5, 50, (8,))]\n\n x = nestedtensor.nested_tensor(inputs, dtype=torch.int64)\n\n emb = torch.nn.Embedding(100, 8)\n\n y = emb(x)\n\n for i, inp in enumerate(inputs):\n\n self.assertEqual(emb(inp), y[i])\n\n\n\n @torch.inference_mode()\n\n def test_nn_embedding_bag(self):\n\n\n\n def run_test(EmbeddingBag, inputs):\n\n x = nestedtensor.nested_tensor(inputs, dtype=torch.int64)\n\n torch.manual_seed(0)\n\n emb = EmbeddingBag()\n\n y = emb(x)\n\n s = y.sum()\n\n # s.backward()\n\n input_tensor = torch.cat(inputs).contiguous()\n\n input_offset = [0]\n\n for inp in inputs[:-1]:\n\n input_offset.append(len(inp) + input_offset[-1])\n\n input_offset = torch.tensor(input_offset)\n\n torch.manual_seed(0)\n\n emb_t = EmbeddingBag()\n\n y_t = emb_t(input_tensor, input_offset)\n\n s_t = y_t.sum()\n\n # s_t.backward()\n\n for yi, y_ti in zip(y.unbind(), y_t.unbind()):\n\n self.assertEqual(yi, y_ti)\n\n self.assertEqual(s, s_t)\n\n # self.assertEqual(emb.weight.grad, emb_t.weight.grad)\n\n\n\n run_test(lambda: torch.nn.EmbeddingBag(100, 8), [\n\n torch.randint(100, (5,)), torch.randint(100, (5,))])\n\n run_test(lambda: torch.nn.EmbeddingBag(100, 8), [\n\n torch.randint(100, (L,)) for L in torch.randint(3, 7, (5,))])\n\n run_test(lambda: torch.nn.EmbeddingBag(100, 8, sparse=True), [\n\n torch.randint(100, (5,)), torch.randint(100, (5,))])\n\n run_test(lambda: torch.nn.EmbeddingBag(100, 8, sparse=True), [\n\n torch.randint(100, (L,)) for L in torch.randint(3, 7, (5,))])\n\n\n\n @torch.inference_mode()\n\n def test_nn_functional_conv2d(self):\n\n tensor1 = torch.rand(3, 128, 128)\n\n tensor2 = torch.rand(3, 300, 400)\n\n inputs = [tensor1, tensor2]\n\n weight = torch.rand(3, 3, 7, 7)\n\n\n\n # no optional params\n\n tensor_res = [torch.nn.functional.conv2d(\n\n t.unsqueeze(0), weight).squeeze(0) for t in inputs]\n\n for nt in [nestedtensor.nested_tensor(inputs), nestedtensor.as_nested_tensor(inputs)]:\n\n nt_res = [t for t in torch.nn.functional.conv2d(\n\n nt, weight).unbind()]\n\n self.assertEqual(nt_res, tensor_res)\n\n\n\n # optional params with no bias\n\n tensor_res = [torch.nn.functional.conv2d(t.unsqueeze(\n\n 0), weight, None, 2, 3, 1, 1).squeeze(0) for t in inputs]\n\n for nt in [nestedtensor.nested_tensor(inputs), nestedtensor.as_nested_tensor(inputs)]:\n\n nt_res = [t for t in torch.nn.functional.conv2d(\n\n nt, weight, None, 2, 3, 1, 1).unbind()]\n\n self.assertEqual(nt_res, tensor_res)\n\n\n\n # optional params with bias\n\n bias = torch.rand(3)\n\n tensor_res = [torch.nn.functional.conv2d(t.unsqueeze(\n\n 0), weight, bias, (2, 2), (3, 3), (1, 1), 1).squeeze(0) for t in inputs]\n\n for nt in [nestedtensor.nested_tensor(inputs), nestedtensor.as_nested_tensor(inputs)]:\n\n nt_res = [t for t in torch.nn.functional.conv2d(\n\n nt, weight, bias, (2, 2), (3, 3), (1, 1), 1).unbind()]\n\n self.assertEqual(nt_res, tensor_res)\n\n\n\n @unittest.skip(\"Not implemented\")\n\n def test_nn_functional_batch_norm(self):\n\n inputs = [\n\n torch.tensor([[[-0.5000]], [[0.5000]]]),\n\n torch.tensor([[[-1.0000, 1.0000], [-0.2500, -0.5000]],\n\n [[0.2500, 0.5000], [1.5000, -1.5000]]])\n\n ]\n\n\n\n tensor_res = []\n\n running_mean = torch.rand(2)\n\n running_var = torch.rand(2)\n\n for i in range(2):\n\n t_res = torch.nn.functional.batch_norm(\n\n inputs[i].unsqueeze(0).contiguous(), running_mean, running_var)\n\n tensor_res.append(t_res.squeeze(0))\n\n\n\n for nt in [nestedtensor.nested_tensor(inputs), nestedtensor.as_nested_tensor(inputs)]:\n\n nt_res = torch.nn.functional.batch_norm(\n\n nt, running_mean, running_var)\n\n self.assertEqual(nestedtensor.nested_tensor(tensor_res), nt_res)\n\n\n\n def test_nn_functional_max_pool2d(self):\n\n inputs = [\n\n torch.randn(3, 500, 600),\n\n torch.randn(3, 128, 128)\n\n ]\n\n\n\n tensor_res = []\n\n for i in range(2):\n\n t_res = torch.nn.functional.max_pool2d(inputs[i].unsqueeze(0).contiguous(), kernel_size=(\n\n 3, 3), stride=(2, 2), padding=(1, 1), dilation=(1, 1), ceil_mode=False)\n\n tensor_res.append(t_res.squeeze(0))\n\n\n\n for nt in [nestedtensor.nested_tensor(inputs), nestedtensor.as_nested_tensor(inputs)]:\n\n nt_res = torch.nn.functional.max_pool2d(nt, kernel_size=(3, 3), stride=(\n\n 2, 2), padding=(1, 1), dilation=(1, 1), ceil_mode=False)\n\n self.assertEqual(nestedtensor.nested_tensor(tensor_res), nt_res)\n\n\n\n def test_functional_relu_(self):\n\n orig_t1 = torch.tensor([-2, -1, 0, 1, 2])\n\n expected_t = torch.tensor([0, 0, 0, 1, 2])\n\n expected_nt = ntnt_nograd([expected_t])\n\n\n\n t_clone = orig_t1.clone()\n\n torch.nn.functional.relu_(t_clone)\n\n self.assertEqual(t_clone, expected_t)\n\n\n\n t_clone = orig_t1.clone()\n\n nt1 = ntnt_nograd([t_clone])\n\n torch.nn.functional.relu_(nt1)\n\n self.assertEqual(nt1, expected_nt)\n\n self.assertEqual(t_clone, orig_t1)\n\n\n\n t_clone = orig_t1.clone()\n\n nt1 = nestedtensor.as_nested_tensor([t_clone])\n\n torch.nn.functional.relu_(nt1)\n\n self.assertEqual(nt1, expected_nt)\n\n self.assertNotEqual(t_clone, expected_t)\n\n\n\n def test_nn_functional_relu(self):\n\n inputs = [\n\n torch.randn(3, 500, 600),\n\n torch.randn(3, 128, 128)\n\n ]\n\n\n\n tensor_res = []\n\n for i in range(2):\n\n t_res = torch.nn.functional.relu(\n\n inputs[i].unsqueeze(0).contiguous())\n\n tensor_res.append(t_res.squeeze(0))\n\n\n\n for nt in [nestedtensor.nested_tensor(inputs), nestedtensor.as_nested_tensor(inputs)]:\n\n nt_res = torch.nn.functional.relu(nt)\n\n self.assertEqual(nestedtensor.nested_tensor(tensor_res), nt_res)\n\n\n\n def test_nn_functional_cross_entropy(self):\n\n inputs = [\n\n torch.randn(3, 300, 300),\n\n torch.randn(3, 400, 400)\n\n ]\n\n\n\n targets = [\n\n torch.randint(1, (300, 300), dtype=torch.int64),\n\n torch.randint(1, (400, 400), dtype=torch.int64)\n\n ]\n\n\n\n tensor_res = []\n\n for i in range(2):\n\n t_res = torch.nn.functional.cross_entropy(\n\n inputs[i].unsqueeze(0).contiguous(), targets[i].unsqueeze(0))\n\n tensor_res.append(t_res.squeeze(0))\n\n\n\n input_nt = nestedtensor.nested_tensor(inputs)\n\n target_nt = nestedtensor.nested_tensor(targets, dtype=torch.int64)\n\n nt_res = torch.nn.functional.cross_entropy(input_nt, target_nt)\n\n self.assertEqual(nestedtensor.nested_tensor(tensor_res), nt_res)\n\n\n\n def test_nn_dropout(self):\n\n inputs = [\n\n torch.randn(3, 128, 128),\n\n torch.randn(3, 300, 400)\n\n ]\n\n\n\n dropout = torch.nn.Dropout(p=0.2)\n\n tensor_res = []\n\n for i in range(2):\n\n t_res = dropout(inputs[i].unsqueeze(0).contiguous())\n\n tensor_res.append(t_res.squeeze(0))\n\n\n\n for nt in [nestedtensor.nested_tensor(inputs), nestedtensor.as_nested_tensor(inputs)]:\n\n nt_res = dropout(nt)\n\n self.assertEqual(nestedtensor.nested_tensor(\n\n tensor_res).size(), nt_res.size())\n\n\n\n def test_nn_functional_dropout(self):\n\n inputs = [\n\n torch.randn(3, 128, 128),\n\n torch.randn(3, 300, 400)\n\n ]\n\n\n\n tensor_res = []\n\n for i in range(2):\n\n t_res = torch.nn.functional.dropout(\n\n inputs[i].unsqueeze(0).contiguous())\n\n tensor_res.append(t_res.squeeze(0))\n\n\n\n nt = ntnt_nograd(inputs)\n\n nt_res = torch.nn.functional.dropout(nt)\n\n self.assertEqual(ntnt_nograd(tensor_res).size(), nt_res.size())\n\n\n\n def test_nn_functional_interpolate(self):\n\n inputs = [\n\n torch.randn(3, 200, 300),\n\n torch.randn(3, 300, 400)\n\n ]\n\n\n\n # no optional params\n\n tensor_res = []\n\n for i in range(2):\n\n t_res = torch.nn.functional.interpolate(\n\n inputs[i].unsqueeze(0).contiguous(), 200)\n\n tensor_res.append(t_res.squeeze(0))\n\n\n\n for nt in [nestedtensor.nested_tensor(inputs), nestedtensor.as_nested_tensor(inputs)]:\n\n nt_res = torch.nn.functional.interpolate(nt, 200)\n\n self.assertEqual(nestedtensor.nested_tensor(tensor_res), nt_res)\n\n\n\n # tuple/int size and optional mode\n\n for size in [(200, 200), 100]:\n\n tensor_res = []\n\n for i in range(2):\n\n t_res = torch.nn.functional.interpolate(inputs[i].unsqueeze(\n\n 0).contiguous(), size, mode='bilinear', align_corners=True)\n\n tensor_res.append(t_res.squeeze(0))\n\n\n\n for nt in [nestedtensor.nested_tensor(inputs), nestedtensor.as_nested_tensor(inputs)]:\n\n nt_res = torch.nn.functional.interpolate(\n\n nt, size, mode='bilinear', align_corners=True)\n\n self.assertEqual(\n\n nestedtensor.nested_tensor(tensor_res), nt_res)\n\n\n\n # special NT case - list of sizes\n\n size = ((100, 100), (200, 250), )\n\n for nt in [nestedtensor.nested_tensor(inputs), nestedtensor.as_nested_tensor(inputs)]:\n\n nt_res = torch.nn.functional.interpolate(\n\n nt, size, mode='bilinear', align_corners=True)\n\n self.assertEqual(nt_res.nested_size(2), (100, 200))\n\n self.assertEqual(nt_res.nested_size(3), (100, 250))\n\n\n\n # scale_factor instead of a size\n\n for scale_factor in [(2.2, 2.2), 1.1]:\n\n tensor_res = []\n\n for i in range(2):\n\n t_res = torch.nn.functional.interpolate(\n\n inputs[i].unsqueeze(0).contiguous(), scale_factor=scale_factor)\n\n tensor_res.append(t_res.squeeze(0))\n\n\n\n for nt in [nestedtensor.nested_tensor(inputs), nestedtensor.as_nested_tensor(inputs)]:\n\n nt_res = torch.nn.functional.interpolate(\n\n nt, scale_factor=scale_factor)\n\n self.assertEqual(\n\n nestedtensor.nested_tensor(tensor_res), nt_res)\n\n\n\n # check errors\n\n for nt in [nestedtensor.nested_tensor(inputs), nestedtensor.as_nested_tensor(inputs)]:\n\n self.assertRaises(RuntimeError, lambda: torch.nn.functional.interpolate(\n\n nt, size=(100, 100), scale_factor=(1, 1)))\n\n\n\n def test_copy_(self):\n\n for constructor in _iter_constructors():\n\n nt1 = constructor([])\n\n nt2 = constructor([])\n\n nt1.copy_(nt2)\n\n self.assertEqual(nt1, nt2)\n\n\n\n nt1 = constructor([torch.randn(1, 2, 3)])\n\n nt2 = constructor([torch.randn(1, 2, 3)])\n\n nt1.copy_(nt2)\n\n self.assertEqual(nt1, nt2)\n\n\n\n nt1 = constructor([torch.randn(1, 2, 3), torch.randn(2, 1, 3)])\n\n nt2 = constructor([torch.randn(1, 2, 3), torch.randn(2, 1, 3)])\n\n nt1.copy_(nt2)\n\n self.assertEqual(nt1, nt2)\n\n\n\n # Currently only supporting nested dim 1.\n\n # nt1 = constructor(\n\n # [[torch.randn(1, 2, 3), torch.randn(2, 1, 3)], [torch.randn(3, 2, 1)]])\n\n # nt2 = constructor(\n\n # [[torch.randn(1, 2, 3), torch.randn(2, 1, 3)], [torch.randn(3, 2, 1)]])\n\n # nt1.copy_(nt2)\n\n # self.assertEqual(nt1, nt2)\n\n\n\n @unittest.skip(\"Currently only supporting nested dim 1.\")\n\n def test_unsqueeze(self):\n\n for constructor in _iter_constructors():\n\n t = torch.randn(2, 3)\n\n\n\n # Currently only supporting nested dim 1.\n\n # nt = constructor([[t.reshape(2, 3)]])\n\n # self.assertEqual(nt.unsqueeze(\n\n # 0), constructor([[[t.reshape(2, 3)]]]))\n\n # self.assertEqual(nt.unsqueeze(\n\n # 1), constructor([[[t.reshape(2, 3)]]]))\n\n # self.assertEqual(nt.unsqueeze(\n\n # 2), constructor([[t.reshape(1, 2, 3)]]))\n\n # self.assertEqual(nt.unsqueeze(\n\n # 3), constructor([[t.reshape(2, 1, 3)]]))\n\n # self.assertEqual(nt.unsqueeze(\n\n # 4), constructor([[t.reshape(2, 3, 1)]]))\n\n\n\n # Currently only supporting nested dim 1.\n\n # t0 = t.reshape(3, 2)\n\n # t1 = t\n\n # t2 = torch.randn(4, 5)\n\n # nt = constructor([[t0, t1], [t2]])\n\n # self.assertEqual(nt.unsqueeze(0), constructor([[[t0, t1], [t2]]]))\n\n # self.assertEqual(nt.unsqueeze(\n\n # 1), constructor([[[t0, t1]], [[t2]]]))\n\n # self.assertEqual(nt.unsqueeze(2), constructor(\n\n # [[t0.reshape(1, 3, 2), t1.reshape(1, 2, 3)], [t2.reshape(1, 4, 5)]]))\n\n # self.assertEqual(nt.unsqueeze(3), constructor(\n\n # [[t0.reshape(3, 1, 2), t1.reshape(2, 1, 3)], [t2.reshape(4, 1, 5)]]))\n\n # self.assertEqual(nt.unsqueeze(4), constructor(\n\n # [[t0.reshape(3, 2, 1), t1.reshape(2, 3, 1)], [t2.reshape(4, 5, 1)]]))\n\n\n\n t = torch.randn(2, 3)\n\n nt = constructor([t])\n\n self.assertEqual(nt.unsqueeze(0), constructor([[t]]))\n\n self.assertEqual(nt.unsqueeze(\n\n 1), constructor([t.reshape(1, 2, 3)]))\n\n self.assertEqual(nt.unsqueeze(\n\n 2), constructor([t.reshape(2, 1, 3)]))\n\n self.assertEqual(nt.unsqueeze(\n\n 3), constructor([t.reshape(2, 3, 1)]))\n\n self.assertRaises(IndexError, lambda: nt.unsqueeze(4))\n\n\n\n @torch.inference_mode()\n\n def test_matmul(self):\n\n for constructor in _iter_constructors():\n\n t1 = torch.randn(2, 3)\n\n a = constructor([t1, t1])\n\n t21 = torch.randn(3, 2)\n\n t22 = torch.randn(3, 2)\n\n b = constructor([t21, t22])\n\n result = torch.matmul(a, b)\n\n result1 = torch.matmul(a, t22)\n\n self.assertEqual(result[1], result1[0])\n\n self.assertEqual(result[1], result1[1])\n\n # Currently only supporting nested dim 1.\n\n # c = constructor([[t21, t22], [t22, t21]])\n\n # result2 = torch.matmul(c, t1)\n\n # self.assertEqual(result2[0][0], torch.matmul(t21, t1))\n\n # self.assertEqual(result2[0][1], torch.matmul(t22, t1))\n\n # self.assertEqual(result2[1][0], torch.matmul(t22, t1))\n\n # self.assertEqual(result2[1][1], torch.matmul(t21, t1))\n\n\n\n @unittest.skip(\"Currently only supporting nested dim 1.\")\n\n def test_transpose(self):\n\n t0 = torch.randn(3, 3, 4)\n\n t1 = torch.randn(2, 4, 3)\n\n t2 = torch.randn(3, 3, 2)\n\n ts = [[t0, t1], [t2]]\n\n nt = nestedtensor.nested_tensor(ts)\n\n self.assertRaisesRegex(RuntimeError, \"Transposition of nested dimensions is not implemented yet.\",\n\n lambda: nt.transpose(0, 2))\n\n self.assertRaisesRegex(RuntimeError, \"Transposition of nested dimensions is not implemented yet.\",\n\n lambda: nt.transpose(1, 3))\n\n self.assertRaisesRegex(RuntimeError, \"Transposition of nested dimensions is not implemented yet.\",\n\n lambda: nt.transpose(0, 1))\n\n self.assertEqual(nt.transpose(2, 3), nt.transpose(3, 2))\n\n t = torch.randn(2, 3, 2, 4, 1)\n\n t_t = t.transpose(2, 3)\n\n nt = nestedtensor.nested_tensor(\n\n list(map(lambda x: x.unbind(), t.unbind())))\n\n nt_t = nestedtensor.nested_tensor(\n\n list(map(lambda x: x.unbind(), t_t.unbind())))\n\n self.assertEqual(t_t, nt_t.to_tensor())\n\n\n\n @unittest.skip(\"Currently only supporting nested dim 1.\")\n\n def test_flatten(self):\n\n t0 = torch.randn(3, 3, 4)\n\n t1 = torch.randn(2, 4, 3)\n\n t2 = torch.randn(3, 3, 2)\n\n ts = [[t0, t1], [t2]]\n\n nt = nestedtensor.nested_tensor(ts)\n\n self.assertRaisesRegex(RuntimeError, \"Cannot flatten nested dimension 0\",\n\n lambda: nt.flatten(0))\n\n self.assertRaisesRegex(RuntimeError, \"Cannot flatten nested dimension 1\",\n\n lambda: nt.flatten(2, 1))\n\n result = nt.flatten(2)\n\n map(self.assertEqual, tuple(\n\n map(lambda x: x.flatten(), ts[0])), result[0])\n\n map(self.assertEqual, tuple(\n\n map(lambda x: x.flatten(), ts[1])), result[1])\n\n\n\n result = nt.flatten(3, 4)\n\n map(self.assertEqual, tuple(\n\n map(lambda x: x.flatten(1, 2), ts[0])), result[0])\n\n map(self.assertEqual, tuple(\n\n map(lambda x: x.flatten(1, 2), ts[1])), result[1])\n\n\n\n ts = torch.randn(3, 2, 4, 5, 3)\n\n ts_r = ts.flatten(3, 4)\n\n ts = list(map(lambda x: x.unbind(), ts.unbind()))\n\n ts_r = list(map(lambda x: x.unbind(), ts_r.unbind()))\n\n ts = nestedtensor.nested_tensor(ts).flatten(3, 4)\n\n ts_r = nestedtensor.nested_tensor(ts_r)\n\n map(self.assertEqual, zip(ts[0].unbind(), ts_r[0].unbind()))\n\n map(self.assertEqual, zip(ts[1].unbind(), ts_r[1].unbind()))\n\n\n\n @unittest.skip(\"Currently only supporting nested dim 1.\")\n\n def test_reshape(self):\n\n t0 = torch.randn(3, 3)\n\n t1 = torch.randn(2, 3)\n\n t2 = torch.randn(3, 3)\n\n ts = [[t0, t1], [t2]]\n\n nt = nestedtensor.nested_tensor(ts)\n\n self.assertRaisesRegex(RuntimeError, \"Reshape cannot be exclusive to nested dimensions.\",\n\n lambda: nt.reshape(0, -1))\n\n self.assertRaisesRegex(RuntimeError, \"Cannot reshape explicitly along irregular dimension 1. Please use -1 as a placeholder.\",\n\n lambda: nt.reshape(-1, 1, 2, 3))\n\n result = nt.reshape(-1, -1, 3, -1)\n\n map(self.assertEqual, tuple(\n\n map(lambda x: x.reshape(3, -1), ts[0])), result[0])\n\n map(self.assertEqual, tuple(\n\n map(lambda x: x.reshape(3, -1), ts[1])), result[1])\n\n\n\n result = nt.reshape(-1, -1, 1, 1, 3, -1)\n\n map(self.assertEqual, tuple(\n\n map(lambda x: x.reshape(1, 1, 3, -1), ts[0])), result[0])\n\n map(self.assertEqual, tuple(\n\n map(lambda x: x.reshape(1, 1, 3, -1), ts[1])), result[1])\n\n\n\n result = nt.reshape(-1, -1, 1, 1, 3, -1)\n\n map(self.assertEqual, tuple(\n\n map(lambda x: x.reshape(1, 1, 3, -1), ts[0])), result[0])\n\n map(self.assertEqual, tuple(\n\n map(lambda x: x.reshape(1, 1, 3, -1), ts[1])), result[1])\n\n\n\n ts = torch.randn(3, 2, 4, 5, 3)\n\n ts_r = ts.reshape(3, 2, 5, 3, 4)\n\n ts = list(map(lambda x: x.unbind(), ts.unbind()))\n\n ts_r = list(map(lambda x: x.unbind(), ts_r.unbind()))\n\n ts = nestedtensor.nested_tensor(ts)\n\n ts_r = nestedtensor.nested_tensor(ts_r)\n\n map(self.assertEqual, zip(ts[0].unbind(), ts_r[0].unbind()))\n\n map(self.assertEqual, zip(ts[1].unbind(), ts_r[1].unbind()))\n\n\n\n def _test_softmax(self, ts, nt):\n\n fn = F.softmax\n\n self.assertRaises(RuntimeError, lambda: fn(nt, 0))\n\n self.assertRaises(RuntimeError, lambda: fn(nt, 1))\n\n\n\n def _map_fn(dim, result):\n\n result = fn(nt, 2)\n\n map(self.assertEqual, tuple(\n\n map(lambda x: fn(x, dim), ts[0])), result[0])\n\n map(self.assertEqual, tuple(\n\n map(lambda x: fn(x, dim), ts[1])), result[1])\n\n s = result.sum()\n\n # s.backward()\n\n\n\n for i in range(nt.dim() - nt.nested_dim()):\n\n _map_fn(i, fn(nt, i + nt.nested_dim()))\n\n\n\n @unittest.skip(\"Currently only supporting nested dim 1.\")\n\n def test_softmax_1(self):\n\n ts = [[], []]\n\n nt = ntnt_nograd(ts)\n\n self._test_softmax(ts, nt)\n\n\n\n @unittest.skip(\"Currently only supporting nested dim 1.\")\n\n def test_softmax_2(self):\n\n t0 = torch.randn(3)\n\n t1 = torch.randn(2)\n\n t2 = torch.randn(3)\n\n ts = [[t0, t1], [t2]]\n\n nt = ntnt_nograd(ts)\n\n self._test_softmax(ts, nt)\n\n\n\n @unittest.skip(\"Currently only supporting nested dim 1.\")\n\n def test_softmax_3(self):\n\n t0 = torch.randn(3, 2, 1)\n\n t1 = torch.randn(2, 3, 1)\n\n t2 = torch.randn(3, 1, 2)\n\n ts = [[t0, t1], [t2]]\n\n nt = ntnt_nograd(ts)\n\n self._test_softmax(ts, nt)\n\n\n\n @unittest.skip(\"Currently only supporting nested dim 1.\")\n\n def test_softmax_4(self):\n\n ts = torch.randn(6, 4, 3, 2, 5)\n\n ts = list(map(lambda x: x.unbind(), ts.unbind()))\n\n nt = ntnt_nograd(ts)\n\n self._test_softmax(ts, nt)\n\n\n\n @torch.inference_mode()\n\n def test_mha(self):\n\n embed_dim = 2\n\n num_heads = 2\n\n torch.manual_seed(1010)\n\n mha = torch.nn.MultiheadAttention(embed_dim, num_heads)\n\n query = torch.randn(3, 1, embed_dim, requires_grad=True)\n\n key = torch.randn(2, 1, embed_dim, requires_grad=True)\n\n value = torch.randn(2, 1, embed_dim, requires_grad=True)\n\n attn_output, _ = mha(query, key, value)\n\n nt_mha = torch.nn.MultiheadAttention(embed_dim, num_heads)\n\n nt_mha.in_proj_weight = mha.in_proj_weight\n\n nt_mha.in_proj_bias = mha.in_proj_bias\n\n nt_mha.out_proj.weight = mha.out_proj.weight\n\n nt_mha.out_proj.bias = mha.out_proj.bias\n\n query_nt = ntnt_nograd([query.squeeze(1)])\n\n key_nt = ntnt_nograd([key.squeeze(1)])\n\n value_nt = ntnt_nograd([value.squeeze(1)])\n\n nt_attn_output, _ = nt_mha(\n\n query_nt, key_nt, value_nt, need_weights=False)\n\n self.assertEqual(attn_output.squeeze(1), nt_attn_output[0])\n\n\n\n @torch.inference_mode()\n\n def test_mha_detr(self):\n\n NDIM = 128\n\n BSZ = 8\n\n NHEAD = 8\n\n RAND_INTS = [(1, 5), (7, 9)]\n\n MODEL = torch.nn.MultiheadAttention(NDIM, NHEAD).eval()\n\n\n\n src_list = ntnt_nograd(\n\n [torch.randn(NDIM, i, j) for (i, j) in RAND_INTS])\n\n detr_nt_src = DETRNestedTensor.from_tensor_list(src_list)\n\n src0, mask = detr_nt_src.decompose()\n\n src0.requires_grad_()\n\n src = src0.flatten(2).permute(2, 0, 1)\n\n mask = mask.flatten(1)\n\n result, _ = MODEL(src, src, src, key_padding_mask=mask,\n\n need_weights=False) # [0].sum().backward()\n\n mask = (~mask.t().unsqueeze(2)).float()\n\n result0 = result * mask\n\n # result_sum = result.sum()\n\n\n\n src = ntnt_nograd([t.flatten(1).permute(\n\n 1, 0) for t in src_list])\n\n result1, _ = MODEL(src, src, src, need_weights=False)\n\n self.assertEqual(result0.sum(0).sum(0), result1.sum(1).sum(0))\n\n\n\n @torch.inference_mode()\n\n @unittest.skipIf(not torch.cuda.is_available(), \"Test requires cuda\")\n\n def test_mha_detr_cuda(self):\n\n NDIM = 128\n\n BSZ = 8\n\n NHEAD = 8\n\n RAND_INTS = [(1, 5), (7, 9)]\n\n MODEL = torch.nn.MultiheadAttention(NDIM, NHEAD).cuda().eval()\n\n\n\n src_list = [torch.randn(NDIM, i, j) for (i, j) in RAND_INTS]\n\n detr_nt_src = DETRNestedTensor.from_tensor_list(src_list)\n\n src0, mask = detr_nt_src.decompose()\n\n src = src0.flatten(2).permute(2, 0, 1).cuda()\n\n mask = mask.flatten(1).cuda()\n\n result, _ = MODEL(src, src, src, key_padding_mask=mask,\n\n need_weights=False) # [0].sum().backward()\n\n mask = (~mask.t().unsqueeze(2)).float()\n\n result0 = result * mask\n\n # result_sum = result.sum()\n\n\n\n src = ntnt_nograd([t.flatten(1).permute(\n\n 1, 0) for t in src_list], device=torch.device('cuda'))\n\n result1, _ = MODEL(src, src, src, need_weights=False)\n\n self.assertEqual(result0.sum(0).sum(0), result1.sum(1).sum(0))\n\n\n\n def test_squeeze(self):\n\n t = torch.randn(2, 3)\n\n result = ntnt_nograd([t])\n\n\n\n # Currently only supporting nested dim 1.\n\n # nt = ntnt_nograd([[t.reshape(1, 2, 1, 3)]])\n\n # # self.assertEqual(nt.squeeze(), result)\n\n # self.assertRaises(RuntimeError, lambda: nt.squeeze())\n\n # nt.squeeze_()\n\n # self.assertEqual(nt, result)\n\n\n\n nt = ntnt_nograd([t.reshape(2, 3)])\n\n # self.assertEqual(nt.squeeze(), result)\n\n self.assertRaises(RuntimeError, lambda: nt.squeeze())\n\n nt.squeeze_()\n\n self.assertEqual(nt, result)\n\n\n\n # Currently only supporting nested dim 1.\n\n # nt = ntnt_nograd([[t.reshape(2, 3)]])\n\n # # self.assertEqual(nt.squeeze(), result)\n\n # self.assertRaises(RuntimeError, lambda: nt.squeeze())\n\n # nt.squeeze_()\n\n # self.assertEqual(nt, result)\n\n\n\n nt = ntnt_nograd([t.reshape(1, 2, 3)])\n\n # self.assertEqual(nt.squeeze(), result)\n\n self.assertRaises(RuntimeError, lambda: nt.squeeze())\n\n nt.squeeze_()\n\n self.assertEqual(nt, result)\n\n\n\n nt = ntnt_nograd([t.reshape(1, 2, 1, 3, 1)])\n\n # self.assertEqual(nt.squeeze(), result)\n\n self.assertRaises(RuntimeError, lambda: nt.squeeze())\n\n nt.squeeze_()\n\n self.assertEqual(nt, result)\n\n\n\n # Currently only supporting nested dim 1.\n\n # nt = ntnt_nograd([[[t.reshape(1, 2, 3)]]])\n\n # # self.assertEqual(nt.squeeze(), result)\n\n # self.assertRaises(RuntimeError, lambda: nt.squeeze())\n\n # nt.squeeze_()\n\n # self.assertEqual(nt, result)\n\n\n\n # result = ntnt([t])\n\n # nt = ntnt([t.reshape(1, 2, 3)])\n\n # self.assertEqual(nt.squeeze(1), result)\n\n # self.assertRaisesRegex(\n\n # RuntimeError, \"Cannot squeeze first dimension.\", lambda: nt.squeeze(0))\n\n # self.assertRaisesRegex(\n\n # RuntimeError, \"Given dimension is either undefined or not a singleton.\", lambda: nt.squeeze(2))\n\n # self.assertRaisesRegex(\n\n # RuntimeError, \"Given dimension is either undefined or not a singleton.\", lambda: nt.squeeze(3))\n\n # self.assertRaises(IndexError, lambda: nt.squeeze(4))\n\n # a = nt.squeeze(1)\n\n # a.sum().backward()\n\n # self.assertEqual(nt.grad, ntnt_nograd(\n\n # [t.reshape(1, 2, 3).mul(0).add(1)]))\n\n\n\n # nt = ntnt([[t.reshape(1, 2, 1, 3)]])\n\n # self.assertRaisesRegex(\n\n # RuntimeError, \"Cannot squeeze nested dimension.\", lambda: nt.squeeze(1))\n\n # # self.assertEqual(nt.squeeze(1), ntnt(\n\n # # [t.reshape(1, 2, 1, 3)]))\n\n # self.assertEqual(nt.squeeze(\n\n # 2), ntnt([[t.reshape(2, 1, 3)]]))\n\n # self.assertEqual(nt.squeeze(\n\n # 4), ntnt([[t.reshape(1, 2, 3)]]))\n\n\n\n def test_nn_max_pool2d(self):\n\n data = [\n\n [\n\n torch.randn(3, 500, 600),\n\n torch.randn(3, 128, 128)\n\n ],\n\n [\n\n torch.randn(3, 500, 600),\n\n torch.randn(3, 500, 600)\n\n ],\n\n ]\n\n\n\n # with optional params\n\n maxPool2d = torch.nn.MaxPool2d(kernel_size=(\n\n 3, 3), stride=2, padding=(1, 1), dilation=1, ceil_mode=False)\n\n for inputs in data:\n\n tensor_res = []\n\n for i in range(2):\n\n t_res = maxPool2d(inputs[i].unsqueeze(0).contiguous())\n\n tensor_res.append(t_res.squeeze(0))\n\n\n\n nt = ntnt_nograd(inputs)\n\n nt_res = maxPool2d(nt)\n\n self.assertEqual(ntnt_nograd(tensor_res), nt_res)\n\n\n\n @unittest.skip(\"Currently broken\")\n\n def test_fzbn2d(self):\n\n class FrozenBatchNorm2d(torch.nn.Module):\n\n \"\"\"\n\n BatchNorm2d where the batch statistics and the affine parameters are fixed.\n\n Copy-paste from torchvision.misc.ops with added eps before rqsrt,\n\n without which any other models than torchvision.models.resnet[18,34,50,101]\n\n produce nans.\n\n \"\"\"\n\n\n\n def __init__(self, n):\n\n super(FrozenBatchNorm2d, self).__init__()\n\n self.register_buffer(\"weight\", torch.ones(n))\n\n self.register_buffer(\"bias\", torch.zeros(n))\n\n self.register_buffer(\"running_mean\", torch.zeros(n))\n\n self.register_buffer(\"running_var\", torch.ones(n))\n\n\n\n def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict,\n\n missing_keys, unexpected_keys, error_msgs):\n\n num_batches_tracked_key = prefix + 'num_batches_tracked'\n\n if num_batches_tracked_key in state_dict:\n\n del state_dict[num_batches_tracked_key]\n\n\n\n super(FrozenBatchNorm2d, self)._load_from_state_dict(\n\n state_dict, prefix, local_metadata, strict,\n\n missing_keys, unexpected_keys, error_msgs)\n\n\n\n def forward(self, x):\n\n # move reshapes to the beginning\n\n # to make it fuser-friendly\n\n print(\"1\")\n\n w = self.weight.reshape(-1, 1, 1)\n\n print(\"2\")\n\n b = self.bias.reshape(-1, 1, 1)\n\n print(\"3\")\n\n rv = self.running_var.reshape(-1, 1, 1)\n\n print(\"4\")\n\n rm = self.running_mean.reshape(-1, 1, 1)\n\n print(\"5\")\n\n eps = 1e-5\n\n print(\"6\")\n\n scale = w * (rv + eps).rsqrt()\n\n print(\"7\")\n\n bias = b - rm * scale\n\n print(\"8\")\n\n # return (x * scale + bias)\n\n # return x\n\n # return (x * scale + bias)\n\n res = x + bias\n\n print(\"9\")\n\n return res\n\n\n\n b0 = FrozenBatchNorm2d(64) # .cuda()\n\n random.seed(1010)\n\n torch.manual_seed(1310)\n\n RAND_INTS = [random.randint(100, 300) for _ in range(1)]\n\n tensors = [torch.rand(64, i, 256, requires_grad=False)\n\n for i in RAND_INTS]\n\n # RAND_INTS = [random.randint(1, 1) for _ in range(1)]\n\n # tensors = [torch.rand(1, i, 2, requires_grad=True)\n\n # for i in RAND_INTS]\n\n nested_tensor = ntnt_nograd(tensors)\n\n # print(nested_tensor.nested_size())\n\n s00 = b0(nested_tensor)\n\n print(\"s00\")\n\n print(s00.requires_grad)\n\n s0 = s00.sum()\n\n # s0.backward()\n\n\n\n b1 = FrozenBatchNorm2d(64)\n\n s1 = 0\n\n for t in tensors:\n\n s1 += b1(t).sum()\n\n # s1.backward()\n\n self.assertEqual(s0, s1)\n\n # for i in range(len(tensors)):\n\n # self.assertEqual(nested_tensor.grad[i], tensors[i].grad)\n\n\n\n self.assertEqual(len((list(b0.named_parameters()))), 0)\n\n self.assertEqual(len((list(b1.named_parameters()))), 0)\n\n\n\n @torch.inference_mode()\n\n def test_layer_norm(self):\n\n def _test(device):\n\n # Currently only supporting nested dim 1.\n\n # layer_norm = torch.nn.LayerNorm((0,)).to(device)\n\n # t0 = torch.randn(3)\n\n # t1 = torch.randn(2)\n\n # t2 = torch.randn(3)\n\n # ts = [[t0, t1], [t2]]\n\n # nt = ntnt_nograd(ts, device=device)\n\n # self.assertRaisesRegex(RuntimeError,\n\n # \"Cannot normalize across irregular dimension 2\", lambda: layer_norm(nt))\n\n\n\n t0 = utils.gen_float_tensor(1, (2, 32)).to(device)\n\n t1 = utils.gen_float_tensor(2, (2, 32)).to(device)\n\n ts = [t0, t1, t0, t1]\n\n nt = ntnt_nograd(ts, device=device)\n\n layer_norm = torch.nn.LayerNorm(32).to(device)\n\n nt_result = layer_norm(nt)\n\n for i in range(len(ts)):\n\n self.assertEqual(nt_result[i], layer_norm(\n\n ts[i].reshape(1, -1, 32).squeeze(0)))\n\n\n\n layer_norm = torch.nn.LayerNorm(16).to(device)\n\n tt = utils.gen_float_tensor(1, (3, 23, 16)).to(device)\n\n res = layer_norm(tt)\n\n nt = nt + 3\n\n res = res * 5\n\n res = layer_norm(tt + 2)\n\n t0 = utils.gen_float_tensor(1, (3, 16)).to(device)\n\n t1 = utils.gen_float_tensor(2, (2, 16)).to(device)\n\n t2 = utils.gen_float_tensor(3, (3, 16)).to(device)\n\n\n\n # Currently only supporting nested dim 1.\n\n # ts = [[t0, t1], [t2]]\n\n # result = ntnt_nograd(ts, device=device)\n\n # layer_norm(ts[0][0])\n\n # map(self.assertEqual, tuple(\n\n # map(lambda x: layer_norm(x), ts[0])), result[0])\n\n # map(self.assertEqual, tuple(\n\n # map(lambda x: layer_norm(x), ts[1])), result[1])\n\n\n\n # layer_norm = torch.nn.LayerNorm(3).to(device)\n\n # t0 = torch.randn(3, 3, 4)\n\n # t1 = torch.randn(2, 3, 4)\n\n # t2 = torch.randn(3, 3, 4)\n\n # ts = [[t0, t1], [t2]]\n\n # nt = ntnt_nograd(ts, device=device)\n\n # self.assertRaisesRegex(RuntimeError,\n\n # \"Normalized shape \\[3\\] does not match the size of the last dimension \\(4\\) of input.\",\n\n # lambda: layer_norm(nt))\n\n\n\n # layer_norm = torch.nn.LayerNorm((3, 2, 4)).to(device)\n\n # self.assertRaisesRegex(RuntimeError,\n\n # \"Currently only singleton tuples of integers supported for layer_norm.\",\n\n # lambda: layer_norm(nt))\n\n _test(torch.device('cpu'))\n\n if torch.cuda.is_available():\n\n _test(torch.device('cuda'))\n\n\n\n @torch.inference_mode()\n\n def test_decoder(self):\n\n class TransformerDecoderLayer(nn.Module):\n\n\n\n def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1,\n\n activation=\"relu\", normalize_before=False):\n\n super().__init__()\n\n self.self_attn = torch.nn.MultiheadAttention(\n\n d_model, nhead, dropout=dropout)\n\n self.multihead_attn = torch.nn.MultiheadAttention(\n\n d_model, nhead, dropout=dropout)\n\n # Implementation of Feedforward model\n\n self.linear1 = nn.Linear(d_model, dim_feedforward)\n\n self.dropout = nn.Dropout(dropout)\n\n self.linear2 = nn.Linear(dim_feedforward, d_model)\n\n\n\n self.norm1 = nn.LayerNorm(d_model)\n\n self.norm2 = nn.LayerNorm(d_model)\n\n self.norm3 = nn.LayerNorm(d_model)\n\n self.dropout1 = nn.Dropout(dropout)\n\n self.dropout2 = nn.Dropout(dropout)\n\n self.dropout3 = nn.Dropout(dropout)\n\n\n\n self.activation = torch.nn.functional.relu\n\n self.normalize_before = normalize_before\n\n\n\n def with_pos_embed(self, tensor, pos):\n\n return tensor if pos is None else tensor + pos\n\n\n\n def forward(self, tgt, memory,\n\n # tgt_mask: Optional[Tensor] = None,\n\n # memory_mask: Optional[Tensor] = None,\n\n # tgt_key_padding_mask: Optional[Tensor] = None,\n\n # memory_key_padding_mask: Optional[Tensor] = None,\n\n pos=None, query_pos=None):\n\n q = k = self.with_pos_embed(tgt, query_pos)\n\n tgt2 = self.self_attn(q, k, value=tgt,\n\n need_weights=False)[0]\n\n # tgt = tgt + self.dropout1(tgt2)\n\n tgt = tgt + tgt2\n\n tgt = self.norm1(tgt)\n\n tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt, query_pos),\n\n key=self.with_pos_embed(\n\n memory, pos),\n\n value=memory,\n\n need_weights=False)[0]\n\n # tgt = tgt + self.dropout2(tgt2)\n\n tgt = tgt + tgt2\n\n tgt = self.norm2(tgt)\n\n tgt2 = self.linear2(self.dropout(\n\n self.activation(self.linear1(tgt))))\n\n # tgt = tgt + self.dropout3(tgt2)\n\n tgt = tgt + tgt2\n\n tgt = self.norm3(tgt)\n\n # print('tgt.requires_grad')\n\n # print(tgt.requires_grad)\n\n return tgt\n\n\n\n d = TransformerDecoderLayer(256, 8)\n\n d.zero_grad()\n\n a = d(\n\n ntnt_nograd([\n\n torch.randn(864, 256),\n\n torch.randn(360, 256)]),\n\n ntnt_nograd([\n\n torch.randn(864, 256),\n\n torch.randn(360, 256)]),\n\n pos=ntnt_nograd([\n\n torch.randn(864, 256),\n\n torch.randn(360, 256)]),\n\n query_pos=ntnt_nograd([\n\n torch.randn(864, 256),\n\n torch.randn(360, 256)]),\n\n )\n\n # a.sum().backward()\n\n # for (n, p) in d.named_parameters():\n\n # print(n)\n\n # print(p is None)\n\n\n\n @torch.inference_mode()\n\n @unittest.skipIf(not torch.cuda.is_available(), \"Test requires cuda\")\n\n def test_effective_transformer_mha(self):\n\n\n\n def test(num_heads, batch_size, seq_len_, head_size, embedding_dim,\n\n use_arange=False):\n\n assert num_heads * head_size == embedding_dim\n\n import random\n\n inputs = []\n\n k = 0\n\n seq_len = 0\n\n seq_lens = []\n\n for _ in range(batch_size):\n\n i = random.randint(1, seq_len_)\n\n seq_len = max(i, seq_len)\n\n seq_lens.append(i)\n\n if use_arange:\n\n inputs.append(torch.arange(\n\n i * embedding_dim).reshape(i, embedding_dim))\n\n else:\n\n inputs.append(torch.randn(i, embedding_dim))\n\n input_nt = nestedtensor.nested_tensor(\n\n inputs, device=torch.device('cuda'), dtype=torch.float)\n\n\n\n input_batch, input_mask = input_nt.to_tensor_mask(mask_dim=2)\n\n\n\n mha = torch.nn.MultiheadAttention(embedding_dim, num_heads)\n\n if use_arange:\n\n in_proj_weight_test = torch.arange(mha.in_proj_weight.numel()).reshape(\n\n mha.in_proj_weight.shape).to(torch.float)\n\n mha.in_proj_weight.copy_(in_proj_weight_test)\n\n in_proj_weight = mha.in_proj_weight.clone().cuda()\n\n\n\n in_proj_bias = mha.in_proj_bias.clone().cuda()\n\n\n\n if use_arange:\n\n out_proj_weight_test = torch.arange(mha.out_proj.weight.numel()).reshape(\n\n mha.out_proj.weight.shape).to(torch.float)\n\n mha.out_proj.weight.copy_(\n\n out_proj_weight_test)\n\n out_proj_weight = mha.out_proj.weight.clone().cuda()\n\n\n\n import time\n\n torch.cuda.synchronize()\n\n torch.cuda.synchronize()\n\n t0 = time.time()\n\n scaling = float(head_size ** -0.5)\n\n for _ in range(5):\n\n result_nt = torch.ops.nestedtensor.bt_min_mha(num_heads,\n\n head_size,\n\n 0.5,\n\n False,\n\n input_nt,\n\n input_nt,\n\n input_nt,\n\n in_proj_weight,\n\n in_proj_bias,\n\n scaling,\n\n out_proj_weight,\n\n in_proj_bias)\n\n\n\n torch.cuda.synchronize()\n\n t1 = time.time()\n\n a = t1 - t0\n\n\n\n mha = mha.cuda()\n\n torch.cuda.synchronize()\n\n torch.cuda.synchronize()\n\n t0 = time.time()\n\n for _ in range(5):\n\n attn_output, _ = mha(input_nt, input_nt, input_nt)\n\n\n\n torch.cuda.synchronize()\n\n t1 = time.time()\n\n b = t1 - t0\n\n\n\n self.assertEqual(result_nt, attn_output)\n\n\n\n torch.cuda.synchronize()\n\n input_batch = input_batch.transpose(0, 1)\n\n not_input_mask = torch.logical_not(input_mask)\n\n torch.cuda.synchronize()\n\n t0 = time.time()\n\n # print(input_batch.size())\n\n for _ in range(5):\n\n attn_output, _ = mha(\n\n input_batch,\n\n input_batch,\n\n input_batch,\n\n key_padding_mask=not_input_mask)\n\n\n\n\n\n torch.cuda.synchronize()\n\n t1 = time.time()\n\n attn_output = attn_output.transpose(0, 1)\n\n attn_output = attn_output * torch.logical_not(not_input_mask.unsqueeze(-1))\n\n self.assertEqual(result_nt.to_padded_tensor(padding=0), attn_output)\n\n c = t1 - t0\n\n print(\"bt: \", a, \"\\tnt: \", b, \"\\tdense: \", c, \"\\tdense/bt: \", c/a)\n\n\n\n # test(1, 1, 1, 4, 4, use_arange=True)\n\n # test(1, 1, 2, 2, 2, use_arange=True)\n\n # test(1, 2, 2, 1, 1, use_arange=True)\n\n # test(1, 4, 3, 2, 2, use_arange=True)\n\n test(2, 1, 2, 1, 2)\n\n test(1, 3, 5, 4, 4)\n\n test(2, 3, 5, 2, 4)\n\n test(2, 1, 2, 2, 4)\n\n test(2, 1, 2, 2, 4)\n\n test(2, 3, 5, 2, 4)\n\n test(1, 3, 5, 4, 4)\n\n test(8, 8, 50, 16, 128)\n\n test(16, 64, 50, 16, 256)\n\n test(16, 128, 50, 16, 256)\n\n test(16, 256, 50, 16, 256)\n\n test(4, 256, 50, 256, 1024)\n\n test(16, 256, 50, 64, 1024)\n\n\n\n @torch.inference_mode()\n\n def test_relu(self):\n\n nt = ntnt_nograd([torch.randn(2, 3), torch.randn(3, 2)])\n\n n1 = torch.nn.ReLU(inplace=False)\n\n out1 = n1(nt)\n\n n2 = torch.nn.ReLU(inplace=True)\n\n out2 = n2(nt)\n\n self.assertEqual(out1, out2)\n\n self.assertEqual(out1, nt)\n\n\n\n\n\nif __name__ == \"__main__\":\n\n unittest.main()\n", "file_path": "test/test_nested_tensor_functional.py", "rank": 89, "score": 53161.73731285545 }, { "content": "namespace torch {\n\nnamespace nested_tensor {\n\n\n\nenum NestedTensorStorageKind { packed, list };\n\n\n\nstruct NestedTensorStorage {\n\n virtual ~NestedTensorStorage() = default;\n\n virtual int64_t dim() const {\n\n TORCH_CHECK(false, \"Not Implemented.\");\n\n }\n\n virtual TensorNode get_structure() const {\n\n TORCH_CHECK(false, \"Not Implemented.\");\n\n }\n\n virtual const caffe2::TypeMeta dtype() const {\n\n TORCH_CHECK(false, \"Not Implemented.\");\n\n }\n\n virtual c10::Device device() const {\n\n TORCH_CHECK(false, \"Not Implemented.\");\n\n }\n\n virtual bool is_pinned() const {\n\n TORCH_CHECK(false, \"Not Implemented.\");\n\n }\n\n virtual const EfficientSizeNode& nested_size() const {\n\n TORCH_CHECK(false, \"Not Implemented.\");\n\n }\n\n virtual const EfficientSizeNode& nested_stride() const {\n\n TORCH_CHECK(false, \"Not Implemented.\");\n\n }\n\n virtual const std::vector<c10::optional<int64_t>> opt_sizes() const {\n\n TORCH_CHECK(false, \"Not Implemented.\");\n\n }\n\n virtual NestedTensorStorageKind kind() const {\n\n TORCH_CHECK(false, \"Not Implemented.\");\n\n }\n\n virtual bool is_contiguous(at::MemoryFormat memory_format = at::MemoryFormat::Contiguous) const {\n\n TORCH_CHECK(false, \"Not Implemented.\");\n\n }\n\n virtual bool is_cuda() const {\n\n TORCH_CHECK(false, \"Not Implemented.\");\n\n }\n\n virtual int64_t numel() const {\n\n TORCH_CHECK(false, \"Not Implemented.\");\n\n }\n\n};\n", "file_path": "nestedtensor/csrc/storage/StorageBase.h", "rank": 90, "score": 52702.38200643779 }, { "content": "import torch\n\nimport nestedtensor\n\nimport unittest\n\nfrom utils_test_case import TestCase\n\nimport random\n\nfrom frozen_batch_norm_2d import NTFrozenBatchNorm2d\n\nfrom position_encoding import PositionEmbeddingSine\n\nfrom joiner import Joiner\n\n\n\n\n\ndef ntnt(x): return nestedtensor.nested_tensor(x, requires_grad=True)\n\ndef ntnt_nograd(x): return nestedtensor.nested_tensor(x)\n\n\n\n\n\nclass TestAutogradFunctional(TestCase):\n\n @unittest.skip(\"Requires autograd support\")\n\n def test_nn_conv2d(self):\n\n def _test(Conv2d):\n\n inputs = [\n\n torch.randn(3, 50, 60, requires_grad=True),\n\n torch.randn(3, 18, 18, requires_grad=True)\n\n ]\n\n\n\n # most of optional params\n\n conv2d = Conv2d()\n\n tensor_res = []\n\n for i in range(2):\n\n t_res = conv2d(inputs[i].unsqueeze(0).contiguous())\n\n tensor_res.append(t_res.squeeze(0))\n\n t_res.sum().backward()\n\n layer_grad0 = [p.grad for (n, p) in conv2d.named_parameters()]\n\n\n\n conv2d.zero_grad()\n\n\n\n nt = ntnt(inputs)\n\n nt_res = conv2d(nt)\n\n nt_res.sum().backward()\n\n layer_grad1 = [p.grad for (n, p) in conv2d.named_parameters()]\n\n\n\n self.assertEqual(ntnt(tensor_res), nt_res)\n\n map(self.assertEqual, zip(layer_grad0, layer_grad1))\n\n self.assertEqual(nt.grad[0], inputs[0].grad)\n\n self.assertEqual(nt.grad[1], inputs[1].grad)\n\n\n\n _test(lambda: torch.nn.Conv2d(3, 33, kernel_size=3, stride=(2, 1), padding=(\n\n 4, 2), padding_mode='zeros', dilation=1, groups=1, bias=True))\n\n _test(lambda: torch.nn.Conv2d(3, 33, kernel_size=3, stride=(2, 1), padding=(\n\n 4, 2), padding_mode='zeros', dilation=1, groups=1, bias=False))\n\n _test(lambda: torch.nn.Conv2d(3, 33, kernel_size=3, stride=(2, 1)))\n\n _test(lambda: torch.nn.Conv2d(\n\n 3, 33, kernel_size=(1, 1), stride=(1, 1), bias=False))\n\n\n\n @unittest.skip(\"Requires autograd support\")\n\n def test_nn_linear(self):\n\n def _test(linear):\n\n inputs = [\n\n torch.randn(3, 10, requires_grad=True),\n\n torch.randn(3, 10, requires_grad=True)\n\n ]\n\n\n\n # most of optional params\n\n linear = linear()\n\n tensor_res = []\n\n for i in range(2):\n\n t_res = linear(inputs[i].unsqueeze(0).contiguous())\n\n tensor_res.append(t_res.squeeze(0))\n\n t_res.sum().backward()\n\n layer_grad0 = [p.grad for (n, p) in linear.named_parameters()]\n\n\n\n linear.zero_grad()\n\n\n\n nt = ntnt(inputs)\n\n nt_res = linear(nt)\n\n nt_res.sum().backward()\n\n layer_grad1 = [p.grad for (n, p) in linear.named_parameters()]\n\n\n\n self.assertEqual(ntnt(tensor_res), nt_res)\n\n map(self.assertEqual, zip(layer_grad0, layer_grad1))\n\n self.assertEqual(nt.grad[0], inputs[0].grad)\n\n self.assertEqual(nt.grad[1], inputs[1].grad)\n\n\n\n _test(lambda: torch.nn.Linear(10, 6))\n\n\n\n @unittest.skip(\"Requires autograd support\")\n\n def test_nn_batch_norm(self):\n\n def _test(BatchNorm2d, has_grad=True):\n\n inputs = torch.randn(5, 3, 18, 18, requires_grad=True)\n\n\n\n batch_norm = BatchNorm2d()\n\n\n\n t_res = batch_norm(inputs)\n\n t_res.sum().backward()\n\n layer_grad0 = [p.grad for (n, p) in batch_norm.named_parameters()]\n\n\n\n batch_norm.zero_grad()\n\n nt = ntnt(inputs.unbind())\n\n nt_res = batch_norm(nt)\n\n\n\n self.assertEqual(ntnt(t_res.unbind()), nt_res)\n\n if has_grad:\n\n nt_res.sum().backward()\n\n layer_grad1 = [p.grad for (\n\n n, p) in batch_norm.named_parameters()]\n\n map(self.assertEqual, zip(layer_grad0, layer_grad1))\n\n self.assertEqual(nt.grad[0], inputs.grad[0])\n\n self.assertEqual(nt.grad[1], inputs.grad[1])\n\n else:\n\n self.assertRaisesRegex(\n\n RuntimeError, \"var.dim gradient not implemented yet.\", lambda: nt_res.sum().backward())\n\n\n\n _test(lambda: torch.nn.BatchNorm2d(3, eps=1e-05,\n\n momentum=0.1, affine=True, track_running_stats=True), False)\n\n _test(lambda: torch.nn.BatchNorm2d(3, eps=1e-05, momentum=0.1,\n\n affine=True, track_running_stats=True).eval())\n\n _test(lambda: torch.nn.BatchNorm2d(3, eps=1e-05,\n\n momentum=0.1, affine=True, track_running_stats=False), False)\n\n _test(lambda: torch.nn.BatchNorm2d(3, eps=1e-05, momentum=0.1,\n\n affine=True, track_running_stats=False).eval(), False)\n\n\n\n _test(lambda: torch.nn.BatchNorm2d(3, eps=1e-05,\n\n momentum=0.1, affine=False, track_running_stats=False), False)\n\n _test(lambda: torch.nn.BatchNorm2d(3, eps=1e-05, momentum=0.1,\n\n affine=False, track_running_stats=False).eval(), False)\n\n _test(lambda: torch.nn.BatchNorm2d(3, eps=1e-05,\n\n momentum=0.1, affine=False, track_running_stats=True), False)\n\n _test(lambda: torch.nn.BatchNorm2d(3, eps=1e-05, momentum=0.1,\n\n affine=False, track_running_stats=True).eval())\n\n _test(lambda: torch.nn.BatchNorm2d(3), False)\n\n\n\n @unittest.skip(\"Requires autograd support\")\n\n def test_nn_relu(self):\n\n inputs = [\n\n torch.randn(3, 500, 600, requires_grad=True),\n\n torch.randn(3, 128, 128, requires_grad=True)\n\n ]\n\n\n\n relu = torch.nn.ReLU()\n\n relu_ = torch.nn.ReLU(inplace=True)\n\n tensor_res = []\n\n for i in range(2):\n\n t_res = relu(inputs[i].unsqueeze(0).contiguous())\n\n t_res = relu_(t_res)\n\n tensor_res.append(t_res.squeeze(0))\n\n tensor_res[i].sum().backward()\n\n layer_grad0 = [p.grad for (n, p) in relu.named_parameters()]\n\n\n\n nt = ntnt(inputs)\n\n nt_res = relu(nt)\n\n nt_res = relu_(nt_res)\n\n nt_res.sum().backward()\n\n layer_grad1 = [p.grad for (n, p) in relu.named_parameters()]\n\n\n\n self.assertEqual(ntnt(tensor_res), nt_res)\n\n map(self.assertEqual, zip(layer_grad0, layer_grad1))\n\n self.assertEqual(inputs[0].grad, nt.grad[0])\n\n self.assertEqual(inputs[1].grad, nt.grad[1])\n\n\n\n @unittest.skip(\"Requires autograd support\")\n\n def test_add(self):\n\n inputs0_ = [\n\n torch.randn(5, 6, requires_grad=True),\n\n torch.randn(1, 1, requires_grad=True)\n\n ]\n\n inputs1_ = [\n\n torch.randn(5, 6, requires_grad=True),\n\n torch.randn(1, 1, requires_grad=True)\n\n ]\n\n inputs0 = ntnt(inputs0_)\n\n inputs1 = ntnt(inputs1_)\n\n output = inputs0 + inputs1\n\n output += inputs0\n\n output.sum().backward()\n\n self.assertEqual(inputs0.grad.sum(),\n\n inputs1.grad.sum() + inputs1.grad.sum())\n\n\n\n @unittest.skip(\"Requires autograd support\")\n\n def test_resnet_bottleneck(self):\n\n import torchvision\n\n\n\n def _test(Bottleneck, has_grad=True):\n\n inputs_ = [\n\n torch.randn(256, 50, 60, requires_grad=True)\n\n ]\n\n inputs = ntnt(inputs_)\n\n\n\n b = Bottleneck()\n\n print(b)\n\n x = b(inputs).sum()\n\n # import torchviz\n\n # dot = torchviz.make_dot(x)\n\n # dot.format = 'svg'\n\n # dot.render('asdf')\n\n # x.backward()\n\n # import sys; sys.exit(1)\n\n g0 = list(p.grad for (n, p) in b.named_parameters())\n\n\n\n b.zero_grad()\n\n b(inputs_[0].unsqueeze(0)).sum().backward()\n\n g1 = list(p.grad for (n, p) in b.named_parameters())\n\n\n\n map(self.assertEqual, zip(g0, g1))\n\n\n\n inputs_ = [\n\n torch.randn(256, 50, 60, requires_grad=True),\n\n torch.randn(256, 18, 18, requires_grad=True)\n\n ]\n\n b = Bottleneck()\n\n inputs = ntnt(inputs_)\n\n if has_grad:\n\n b(inputs).sum().backward()\n\n # print(list((n, p.grad is None) for (n, p) in b.named_parameters()))\n\n\n\n b.zero_grad()\n\n b(inputs_[0].unsqueeze(0)).sum().backward()\n\n\n\n b.zero_grad()\n\n b(inputs_[1].unsqueeze(0)).sum().backward()\n\n\n\n self.assertEqual(inputs_[0].grad, inputs.grad[0])\n\n self.assertEqual(inputs_[1].grad, inputs.grad[1])\n\n _test(lambda: torchvision.models.resnet.Bottleneck(256, 64), False)\n\n _test(lambda: torchvision.models.resnet.Bottleneck(256, 64).eval())\n\n\n\n @unittest.skip(\"Requires autograd support\")\n\n def test_resnet_classification(self):\n\n import torchvision\n\n\n\n def _test(FCNHead):\n\n inputs_ = [\n\n torch.randn(256, 50, 60, requires_grad=True)\n\n ]\n\n inputs = ntnt(inputs_)\n\n\n\n b = FCNHead()\n\n print(b)\n\n # print(b)\n\n # list(b.children())[3].eval() # dropout is stochastic otherwise\n\n b(inputs).sum().backward()\n\n g0 = list(p.grad for (n, p) in b.named_parameters())\n\n\n\n b.zero_grad()\n\n b(inputs_[0].unsqueeze(0)).sum().backward()\n\n g1 = list(p.grad for (n, p) in b.named_parameters())\n\n\n\n map(self.assertEqual, zip(g0, g1))\n\n\n\n inputs_ = [\n\n torch.randn(256, 50, 60, requires_grad=True),\n\n torch.randn(256, 18, 18, requires_grad=True)\n\n ]\n\n inputs = ntnt(inputs_)\n\n b.zero_grad()\n\n b(inputs).sum().backward()\n\n\n\n b.zero_grad()\n\n b(inputs_[0].unsqueeze(0)).sum().backward()\n\n\n\n b.zero_grad()\n\n b(inputs_[1].unsqueeze(0)).sum().backward()\n\n\n\n self.assertEqual(inputs_[0].grad, inputs.grad[0])\n\n self.assertEqual(inputs_[1].grad, inputs.grad[1])\n\n # _test(lambda: torchvision.models.segmentation.fcn.FCNHead(256, 64))\n\n _test(lambda: torchvision.models.segmentation.fcn.FCNHead(256, 64).eval())\n\n\n\n @unittest.skip(\"Requires autograd support\")\n\n def test_backbone(self):\n\n import torchvision\n\n from torchvision.models._utils import IntermediateLayerGetter\n\n\n\n def _test(FCNHead):\n\n inputs_ = [\n\n torch.randn(3, 50, 60, requires_grad=True)\n\n ]\n\n inputs = ntnt(inputs_)\n\n\n\n b = FCNHead()\n\n # print(b)\n\n # print(b(inputs))\n\n b(inputs)[0][0].sum().backward()\n\n g0 = list(p.grad for (n, p) in b.named_parameters())\n\n\n\n b.zero_grad()\n\n b(inputs_[0].unsqueeze(0))[0][0].sum().backward()\n\n g1 = list(p.grad for (n, p) in b.named_parameters())\n\n\n\n map(self.assertEqual, zip(g0, g1))\n\n\n\n inputs_ = [\n\n torch.randn(3, 50, 60, requires_grad=True),\n\n torch.randn(3, 18, 18, requires_grad=True)\n\n ]\n\n inputs = ntnt(inputs_)\n\n b.zero_grad()\n\n b(inputs)[0][0].sum().backward()\n\n # for (n, p) in b.named_parameters():\n\n # if p.grad is None:\n\n # print(n)\n\n # continue\n\n # print(n, \" is fine\")\n\n\n\n b.zero_grad()\n\n b(inputs_[0].unsqueeze(0))[0][0].sum().backward()\n\n\n\n b.zero_grad()\n\n b(inputs_[1].unsqueeze(0))[0][0].sum().backward()\n\n\n\n self.assertEqual(inputs_[0].grad, inputs.grad[0])\n\n self.assertEqual(inputs_[1].grad, inputs.grad[1])\n\n # Note: It seems expected that layer0 has no gradients.\n\n return_layers = {\"layer1\": \"0\", \"layer2\": \"1\",\n\n \"layer3\": \"2\", \"layer4\": \"3\"}\n\n _test(lambda: Joiner(IntermediateLayerGetter(torchvision.models.resnet50(\n\n replace_stride_with_dilation=[False, False, False],\n\n pretrained=True, norm_layer=NTFrozenBatchNorm2d), return_layers),\n\n PositionEmbeddingSine(128, normalize=True)))\n\n\n\n @unittest.skip(\"Requires autograd support\")\n\n def test_nn_max_pool2d(self):\n\n data = [\n\n [\n\n torch.randn(3, 500, 600),\n\n torch.randn(3, 128, 128)\n\n ],\n\n [\n\n torch.randn(3, 500, 600),\n\n torch.randn(3, 500, 600)\n\n ],\n\n ]\n\n\n\n # with optional params\n\n maxPool2d = torch.nn.MaxPool2d(kernel_size=(\n\n 3, 3), stride=2, padding=(1, 1), dilation=1, ceil_mode=False)\n\n for inputs in data:\n\n tensor_res = []\n\n for i in range(2):\n\n t_res = maxPool2d(inputs[i].unsqueeze(0).contiguous())\n\n tensor_res.append(t_res.squeeze(0))\n\n\n\n nt = ntnt(inputs)\n\n nt_res = maxPool2d(nt)\n\n self.assertEqual(ntnt(tensor_res), nt_res)\n\n\n\n @unittest.skip(\"Requires autograd support\")\n\n def test_fzbn2d(self):\n\n class FrozenBatchNorm2d(torch.nn.Module):\n\n \"\"\"\n\n BatchNorm2d where the batch statistics and the affine parameters are fixed.\n\n Copy-paste from torchvision.misc.ops with added eps before rqsrt,\n\n without which any other models than torchvision.models.resnet[18,34,50,101]\n\n produce nans.\n\n \"\"\"\n\n\n\n def __init__(self, n):\n\n super(FrozenBatchNorm2d, self).__init__()\n\n self.register_buffer(\"weight\", torch.ones(n))\n\n self.register_buffer(\"bias\", torch.zeros(n))\n\n self.register_buffer(\"running_mean\", torch.zeros(n))\n\n self.register_buffer(\"running_var\", torch.ones(n))\n\n\n\n def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict,\n\n missing_keys, unexpected_keys, error_msgs):\n\n num_batches_tracked_key = prefix + 'num_batches_tracked'\n\n if num_batches_tracked_key in state_dict:\n\n del state_dict[num_batches_tracked_key]\n\n\n\n super(FrozenBatchNorm2d, self)._load_from_state_dict(\n\n state_dict, prefix, local_metadata, strict,\n\n missing_keys, unexpected_keys, error_msgs)\n\n\n\n def forward(self, x):\n\n # move reshapes to the beginning\n\n # to make it fuser-friendly\n\n w = self.weight.reshape(-1, 1, 1)\n\n b = self.bias.reshape(-1, 1, 1)\n\n rv = self.running_var.reshape(-1, 1, 1)\n\n rm = self.running_mean.reshape(-1, 1, 1)\n\n eps = 1e-5\n\n scale = w * (rv + eps).rsqrt()\n\n bias = b - rm * scale\n\n # return (x * scale + bias)\n\n # return x\n\n # return (x * scale + bias)\n\n return x + bias\n\n\n\n b0 = FrozenBatchNorm2d(64) # .cuda()\n\n random.seed(1010)\n\n torch.manual_seed(1310)\n\n RAND_INTS = [random.randint(100, 300) for _ in range(1)]\n\n tensors = [torch.rand(64, i, 256, requires_grad=True)\n\n for i in RAND_INTS]\n\n nested_tensor = ntnt(tensors)\n\n # print(nested_tensor.nested_size())\n\n s0 = b0(nested_tensor).sum()\n\n s0.backward()\n\n\n\n b1 = FrozenBatchNorm2d(64)\n\n s1 = 0\n\n for t in tensors:\n\n s1 += b1(t).sum()\n\n s1.backward()\n\n self.assertEqual(s0, s1)\n\n for i in range(len(tensors)):\n\n self.assertEqual(nested_tensor.grad[i], tensors[i].grad)\n\n\n\n self.assertEqual(len((list(b0.named_parameters()))), 0)\n\n self.assertEqual(len((list(b1.named_parameters()))), 0)\n\n\n\n\n\nif __name__ == \"__main__\":\n\n unittest.main()\n", "file_path": "test/test_nested_tensor_autograd_functional.py", "rank": 91, "score": 52062.50934754612 }, { "content": "class _apply<F, c10::guts::typelist::typelist<Args...>> {\n\n public:\n\n // NOTE: We must move F to avoid copying objects if it is a lambda with\n\n // captures.\n\n static void function(F&& fn, NestedNode<Args>... nested_node) {\n\n size_t degree = 0;\n\n bool all_leaf = true;\n\n c10::guts::tuple_map(\n\n std::forward_as_tuple(nested_node...), [&all_leaf, &degree](auto n) {\n\n all_leaf = all_leaf && (n.is_leaf());\n\n if (degree == 0 && n.degree() > 0) {\n\n degree = n.degree();\n\n }\n\n if (degree > 0 && n.degree() > 0) {\n\n TORCH_CHECK(degree == n.degree(), \"NestedNodes don't broadcast.\");\n\n }\n\n return nullptr;\n\n });\n\n if (all_leaf) {\n\n std::forward<F>(fn)(nested_node.payload()...);\n", "file_path": "nestedtensor/csrc/utils/nested_node.h", "rank": 92, "score": 48043.729363595936 }, { "content": "#include <nestedtensor/csrc/nested_tensor_impl.h>\n\n#include <nestedtensor/csrc/utils/nested_node_functions.h>\n\n#include <torch/extension.h>\n\n#include <torch/library.h>\n\n\n\nusing namespace torch::nn;\n\nnamespace F = torch::nn::functional;\n\n\n\nnamespace at {\n\n\n\nTensor NestedTensor_view(const Tensor& self, IntArrayRef size) {\n\n auto self_data = get_nested_tensor_impl(self);\n\n TORCH_CHECK(\n\n int64_t(size.size()) > self_data->nested_dim(),\n\n \"view cannot be exclusive to nested dimensions.\");\n\n auto self_opt_sizes = get_opt_sizes(self);\n\n TORCH_CHECK(*self_opt_sizes[0] == size[0], \"First dimension must be unchanged.\");\n\n int64_t nested_dim = self_data->nested_dim();\n\n std::vector<int64_t> target_shape;\n\n for (int64_t i = nested_dim; i < int64_t(size.size()); i++) {\n", "file_path": "nestedtensor/csrc/shape.cpp", "rank": 93, "score": 47860.57230416188 }, { "content": "def nested_tensor_from_padded_tensor(tensor, nested_dim=1, padding=-1):\n\n mask = (tensor != padding)\n", "file_path": "nestedtensor/nested/masking.py", "rank": 94, "score": 47856.565225573104 }, { "content": "def nested_tensor_from_tensor_mask(tensor, mask, nested_dim=1):\n\n if tensor is None:\n\n raise RuntimeError(\"Tensor can't be undefined (None).\")\n\n\n\n if mask is None:\n\n raise RuntimeError(\"Mask can't be undefined (None).\")\n\n\n\n # Scalar was passed\n\n if tensor.dim() == 0:\n\n raise RuntimeError(\"Can't construct nested tensor from a scalar.\")\n\n\n\n if nested_dim == 0:\n\n raise RuntimeError(\"Nested dimension can't be 0.\")\n\n\n\n if nested_dim is not None and nested_dim > tensor.dim():\n\n raise RuntimeError(\"Nested dimension ({0}) can't be bigger than data tensor dimension ({1}).\".format(\n\n nested_dim, tensor.dim()))\n\n\n\n if tensor.numel() == 0 and mask.numel() != 0:\n\n raise RuntimeError(\"Data tensor can't be emtpy if a mask has values.\")\n\n\n\n if tensor.numel() != 0 and mask.numel() == 0:\n\n raise RuntimeError(\n\n \"Mask tensor can't be emtpy if a data tensor has values.\")\n\n\n", "file_path": "nestedtensor/nested/masking.py", "rank": 95, "score": 47856.565225573104 }, { "content": "#include <nestedtensor/csrc/nested_tensor_impl.h>\n\n#include <nestedtensor/csrc/utils/nested_node_functions.h>\n\n#include <torch/extension.h>\n\n#include <torch/library.h>\n\n\n\nusing namespace torch::nn;\n\nnamespace F = torch::nn::functional;\n\n\n\nnamespace at {\n\n\n\nTensor NestedTensor_matmul(const Tensor& self, const Tensor& other) {\n\n if (is_nested_tensor_impl(self) && !is_nested_tensor_impl(other)) {\n\n if (get_is_contiguous(self)) {\n\n if (get_dim(self) == 3 && get_dim(other) == 2) {\n\n auto self_opt_sizes = get_opt_sizes(self);\n\n if (self_opt_sizes[2]) {\n\n if (*self_opt_sizes[2] == other.size(0)) {\n\n Tensor self_buffer = get_buffer(self);\n\n Tensor result_buffer =\n\n at::matmul(self_buffer.reshape({-1, other.size(0)}), other);\n", "file_path": "nestedtensor/csrc/matmul.cpp", "rank": 96, "score": 37.40467360424293 }, { "content": " !is_nested_tensor_impl(weight) &&\n\n (input.dtype() == torch::kFloat16 || input.dtype() == torch::kFloat32)) {\n\n if (get_dim(input) == 4 && !bias && weight.size(2) == 1 && weight.size(3) == 1 &&\n\n stride[0] == 1 && stride[1] == 1 &&\n\n padding[0] == 0 && padding[1] == 0 &&\n\n dilation[0] == 1 && dilation[1] == 1 &&\n\n groups == 1 &&\n\n *self_opt_sizes[0] &&\n\n *self_opt_sizes[1] &&\n\n get_is_cuda(input)\n\n ) {\n\n if (get_is_contiguous(input, c10::MemoryFormat::ChannelsLast)) {\n\n Tensor input_buffer = get_buffer(input);\n\n input_buffer = input_buffer.view({-1, weight.size(1)});\n\n at::Tensor result_buffer = at::matmul(input_buffer, \n\n weight.reshape({weight.size(0), weight.size(1)}).transpose(0, 1));\n\n int64_t weight_size_0 = weight.size(0);\n\n auto new_sizes = map_efficient_size([&weight_size_0](int64_t* size_ptr, int64_t size) {\n\n size_ptr[0] = weight_size_0;\n\n }, get_efficient_nested_size(input));\n", "file_path": "nestedtensor/csrc/conv2d.cpp", "rank": 97, "score": 36.04308814855872 }, { "content": "#include <ATen/ATen.h>\n\n#include <nestedtensor/csrc/nested_tensor_impl.h>\n\n#include <nestedtensor/csrc/utils/nested_node_functions.h>\n\n#include <torch/extension.h>\n\n#include <torch/library.h>\n\n\n\nusing namespace torch::nn;\n\nnamespace F = torch::nn::functional;\n\n\n\nnamespace at {\n\n\n\nTensor NestedTensor_softmax(\n\n const Tensor& input,\n\n const int64_t dim_,\n\n c10::optional<ScalarType> dtype) {\n\n int64_t dim = maybe_wrap_dim(dim_, get_dim(input));\n\n auto input_data = get_nested_tensor_impl(input);\n\n int64_t nested_dim = input_data->nested_dim();\n\n TORCH_CHECK(\n\n dim >= nested_dim,\n", "file_path": "nestedtensor/csrc/SoftMax.cpp", "rank": 98, "score": 35.81905662421417 }, { "content": " \"to_tensor()/to_tensor(0) only works if there is no None in size().\");\n\n }\n\n new_size.push_back(*si);\n\n }\n\n return _to_tensor(impl_data->get_structure());\n\n // // If dim is bigger than nested_dim the NestedTensor is already\n\n // // of Tensor for dimensions bigger than the given.\n\n // if (impl_data->nested_dim() == 1) {\n\n // return tensor;\n\n // }\n\n // // At this point nested_dim is at least 2. That means any unbind\n\n // // operation of a child must yield NestedTensors.\n\n // // If dim is 1 then we'll apply to_tensor(0) to the children and must expect\n\n // // Tensors.\n\n // std::vector<at::Tensor> unbound = at::unbind(tensor, 0);\n\n // std::vector<TensorNode> result;\n\n // for (Tensor child : unbound) {\n\n // auto ci = NestedTensor_to_tensor(child, dim - 1);\n\n // if (is_nested_tensor_impl(ci)) {\n\n // auto s = get_nested_tensor_impl(ci)->get_structure();\n", "file_path": "nestedtensor/csrc/totensor.cpp", "rank": 99, "score": 35.60172973210174 } ]
C++
GDADPRG_Courseware/TextureManager.cpp
NeilDG/GDADPRG-GDPARCM_Courseware
771509ec7b3eb6d6375807819ca9da957dd22641
#include <stddef.h> #include <iostream> #include "TextureManager.h" TextureManager* TextureManager::sharedInstance = NULL; TextureManager* TextureManager::getInstance() { if (sharedInstance == NULL) { sharedInstance = new TextureManager(); } return sharedInstance; } void TextureManager::loadAll() { sf::Texture *texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0000.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0001.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0002.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0003.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0004.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0005.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0006.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0007.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bench0001.png"); this->textureMap[Bench].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bench0002.png"); this->textureMap[Bench].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bench0003.png"); this->textureMap[Bench].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bench0004.png"); this->textureMap[Bench].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bench0005.png"); this->textureMap[Bench].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bench0006.png"); this->textureMap[Bench].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bench0007.png"); this->textureMap[Bench].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0000.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0001.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0002.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0003.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0004.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0005.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0006.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0007.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0000.png"); this->textureMap[Coin].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0001.png"); this->textureMap[Coin].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0002.png"); this->textureMap[Coin].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0003.png"); this->textureMap[Coin].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0004.png"); this->textureMap[Coin].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0005.png"); this->textureMap[Coin].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0006.png"); this->textureMap[Coin].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0007.png"); this->textureMap[Coin].push_back(texture); } sf::Texture* TextureManager::getTextureAt(TextureManager::AssetType assetType, int index) { if (!this->textureMap[assetType].empty()) { return this->textureMap[assetType][index]; } else { cout << "No texture found for " << assetType; return NULL; } } int TextureManager::getTextureLength(TextureManager::AssetType assetType) { if (!this->textureMap[assetType].empty()) { return this->textureMap[assetType].size(); } else { cout << "No texture found for " << assetType; return 0; } } void TextureManager::testFunction() { std::cout << "Texture manager is a singleton!"; }
#include <stddef.h> #include <iostream> #include "TextureManager.h" TextureManager* TextureManager::sharedInstance = NULL; TextureManager* TextureManager::getInstance() { if (sharedInstance == NULL) { sharedInstance = new TextureManager(); } return sharedInstance; } void TextureManager::loadAll() { sf::Texture *texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0000.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0001.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0002.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0003.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0004.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0005.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0006.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0007.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bench0001.png"); this->textureMap[Bench].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bench0002.png"); this->textureMap[Bench].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bench0003.png"); this->textureMap[Bench].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bench0004.png"); this->textureMap[Bench].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bench0005.png"); this->textureMap[Bench].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bench0006.png"); this->textureMap[Bench].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bench0007.png"); this->textureMap[Bench].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0000.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0001.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0002.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0003.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0004.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0005.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0006.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0007.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0000.png"); this->textureMap[Coin].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0001.png"); this->textureMap[Coin].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0002.png"); this->textureMap[Coin].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0003.png"); this->textureMap[Coin].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0004.png"); this->textureMap[Coin].pus
sf::Texture* TextureManager::getTextureAt(TextureManager::AssetType assetType, int index) { if (!this->textureMap[assetType].empty()) { return this->textureMap[assetType][index]; } else { cout << "No texture found for " << assetType; return NULL; } } int TextureManager::getTextureLength(TextureManager::AssetType assetType) { if (!this->textureMap[assetType].empty()) { return this->textureMap[assetType].size(); } else { cout << "No texture found for " << assetType; return 0; } } void TextureManager::testFunction() { std::cout << "Texture manager is a singleton!"; }
h_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0005.png"); this->textureMap[Coin].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0006.png"); this->textureMap[Coin].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0007.png"); this->textureMap[Coin].push_back(texture); }
function_block-function_prefixed
[ { "content": "class RenderTexture;\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 0, "score": 96601.72563755105 }, { "content": " class RenderTextureImpl;\n\n}\n\n\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/RenderTexture.hpp", "rank": 1, "score": 92136.0824527816 }, { "content": " /// \\param texture Pointer to the texture to bind, can be null to use no texture\n\n /// \\param coordinateType Type of texture coordinates to use\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n static void bind(const Texture* texture, CoordinateType coordinateType = Normalized);\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Get the maximum texture size allowed\n\n ///\n\n /// This maximum size is defined by the graphics driver.\n\n /// You can expect a value of 512 pixels for low-end graphics\n\n /// card, and up to 8192 pixels or more for newer hardware.\n\n ///\n\n /// \\return Maximum size allowed for textures, in pixels\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n static unsigned int getMaximumSize();\n\n\n\nprivate:\n\n\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 2, "score": 89720.45934802029 }, { "content": " /// behavior.\n\n ///\n\n /// This function does nothing if \\a pixels is null or if the\n\n /// texture was not previously created.\n\n ///\n\n /// \\param pixels Array of pixels to copy to the texture\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n void update(const Uint8* pixels);\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Update a part of the texture from an array of pixels\n\n ///\n\n /// The size of the \\a pixel array must match the \\a width and\n\n /// \\a height arguments, and it must contain 32-bits RGBA pixels.\n\n ///\n\n /// No additional check is performed on the size of the pixel\n\n /// array or the bounds of the area to update, passing invalid\n\n /// arguments will lead to an undefined behavior.\n\n ///\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 3, "score": 89719.5800923081 }, { "content": " /// This function does nothing if \\a pixels is null or if the\n\n /// texture was not previously created.\n\n ///\n\n /// \\param pixels Array of pixels to copy to the texture\n\n /// \\param width Width of the pixel region contained in \\a pixels\n\n /// \\param height Height of the pixel region contained in \\a pixels\n\n /// \\param x X offset in the texture where to copy the source pixels\n\n /// \\param y Y offset in the texture where to copy the source pixels\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n void update(const Uint8* pixels, unsigned int width, unsigned int height, unsigned int x, unsigned int y);\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Update a part of this texture from another texture\n\n ///\n\n /// Although the source texture can be smaller than this texture,\n\n /// this function is usually used for updating the whole texture.\n\n /// The other overload, which has (x, y) additional arguments,\n\n /// is more convenient for updating a sub-area of this texture.\n\n ///\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 4, "score": 89719.42823571869 }, { "content": "// 3. This notice may not be removed or altered from any source distribution.\n\n//\n\n////////////////////////////////////////////////////////////\n\n\n\n#ifndef SFML_TEXTURE_HPP\n\n#define SFML_TEXTURE_HPP\n\n\n\n////////////////////////////////////////////////////////////\n\n// Headers\n\n////////////////////////////////////////////////////////////\n\n#include <SFML/Graphics/Export.hpp>\n\n#include <SFML/Graphics/Image.hpp>\n\n#include <SFML/Window/GlResource.hpp>\n\n\n\n\n\nnamespace sf\n\n{\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 5, "score": 89718.08086049477 }, { "content": " ////////////////////////////////////////////////////////////\n\n bool generateMipmap();\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Overload of assignment operator\n\n ///\n\n /// \\param right Instance to assign\n\n ///\n\n /// \\return Reference to self\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n Texture& operator =(const Texture& right);\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Swap the contents of this texture with those of another\n\n ///\n\n /// \\param right Instance to swap with\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n void swap(Texture& right);\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 6, "score": 89717.50405274238 }, { "content": " /// No additional check is performed on the size of the passed\n\n /// texture, passing a texture bigger than this texture\n\n /// will lead to an undefined behavior.\n\n ///\n\n /// This function does nothing if either texture was not\n\n /// previously created.\n\n ///\n\n /// \\param texture Source texture to copy to this texture\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n void update(const Texture& texture);\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Update a part of this texture from another texture\n\n ///\n\n /// No additional check is performed on the size of the texture,\n\n /// passing an invalid combination of texture size and offset\n\n /// will lead to an undefined behavior.\n\n ///\n\n /// This function does nothing if either texture was not\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 7, "score": 89717.27210452386 }, { "content": " /// previously created.\n\n ///\n\n /// \\param texture Source texture to copy to this texture\n\n /// \\param x X offset in this texture where to copy the source texture\n\n /// \\param y Y offset in this texture where to copy the source texture\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n void update(const Texture& texture, unsigned int x, unsigned int y);\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Update the texture from an image\n\n ///\n\n /// Although the source image can be smaller than the texture,\n\n /// this function is usually used for updating the whole texture.\n\n /// The other overload, which has (x, y) additional arguments,\n\n /// is more convenient for updating a sub-area of the texture.\n\n ///\n\n /// No additional check is performed on the size of the image,\n\n /// passing an image bigger than the texture will lead to an\n\n /// undefined behavior.\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 8, "score": 89716.98005588546 }, { "content": " ///\n\n /// This function does nothing if the texture was not\n\n /// previously created.\n\n ///\n\n /// \\param image Image to copy to the texture\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n void update(const Image& image);\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Update a part of the texture from an image\n\n ///\n\n /// No additional check is performed on the size of the image,\n\n /// passing an invalid combination of image size and offset\n\n /// will lead to an undefined behavior.\n\n ///\n\n /// This function does nothing if the texture was not\n\n /// previously created.\n\n ///\n\n /// \\param image Image to copy to the texture\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 9, "score": 89716.88477592052 }, { "content": "/// ...\n\n///\n\n/// // update the texture\n\n/// sf::Uint8* pixels = ...; // get a fresh chunk of pixels (the next frame of a movie, for example)\n\n/// texture.update(pixels);\n\n///\n\n/// // draw it\n\n/// window.draw(sprite);\n\n///\n\n/// ...\n\n/// }\n\n///\n\n/// \\endcode\n\n///\n\n/// Like sf::Shader that can be used as a raw OpenGL shader,\n\n/// sf::Texture can also be used directly as a raw texture for\n\n/// custom OpenGL geometry.\n\n/// \\code\n\n/// sf::Texture::bind(&texture);\n\n/// ... render OpenGL geometry ...\n\n/// sf::Texture::bind(NULL);\n\n/// \\endcode\n\n///\n\n/// \\see sf::Sprite, sf::Image, sf::RenderTexture\n\n///\n\n////////////////////////////////////////////////////////////\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 10, "score": 89716.78868743607 }, { "content": " ////////////////////////////////////////////////////////////\n\n void update(const Window& window, unsigned int x, unsigned int y);\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Enable or disable the smooth filter\n\n ///\n\n /// When the filter is activated, the texture appears smoother\n\n /// so that pixels are less noticeable. However if you want\n\n /// the texture to look exactly the same as its source file,\n\n /// you should leave it disabled.\n\n /// The smooth filter is disabled by default.\n\n ///\n\n /// \\param smooth True to enable smoothing, false to disable it\n\n ///\n\n /// \\see isSmooth\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n void setSmooth(bool smooth);\n\n\n\n ////////////////////////////////////////////////////////////\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 11, "score": 89716.7666549935 }, { "content": " ///\n\n /// \\param repeated True to repeat the texture, false to disable repeating\n\n ///\n\n /// \\see isRepeated\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n void setRepeated(bool repeated);\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Tell whether the texture is repeated or not\n\n ///\n\n /// \\return True if repeat mode is enabled, false if it is disabled\n\n ///\n\n /// \\see setRepeated\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n bool isRepeated() const;\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Generate a mipmap using the current texture data\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 12, "score": 89716.67190003302 }, { "content": " ///\n\n /// \\param window Window to copy to the texture\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n void update(const Window& window);\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Update a part of the texture from the contents of a window\n\n ///\n\n /// No additional check is performed on the size of the window,\n\n /// passing an invalid combination of window size and offset\n\n /// will lead to an undefined behavior.\n\n ///\n\n /// This function does nothing if either the texture or the window\n\n /// was not previously created.\n\n ///\n\n /// \\param window Window to copy to the texture\n\n /// \\param x X offset in the texture where to copy the source window\n\n /// \\param y Y offset in the texture where to copy the source window\n\n ///\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 13, "score": 89716.62966287676 }, { "content": " /// \\param x X offset in the texture where to copy the source image\n\n /// \\param y Y offset in the texture where to copy the source image\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n void update(const Image& image, unsigned int x, unsigned int y);\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Update the texture from the contents of a window\n\n ///\n\n /// Although the source window can be smaller than the texture,\n\n /// this function is usually used for updating the whole texture.\n\n /// The other overload, which has (x, y) additional arguments,\n\n /// is more convenient for updating a sub-area of the texture.\n\n ///\n\n /// No additional check is performed on the size of the window,\n\n /// passing a window bigger than the texture will lead to an\n\n /// undefined behavior.\n\n ///\n\n /// This function does nothing if either the texture or the window\n\n /// was not previously created.\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 14, "score": 89716.53460332105 }, { "content": " /// \\brief Invalidate the mipmap if one exists\n\n ///\n\n /// This also resets the texture's minifying function.\n\n /// This function is mainly for internal use by RenderTexture.\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n void invalidateMipmap();\n\n\n\n ////////////////////////////////////////////////////////////\n\n // Member data\n\n ////////////////////////////////////////////////////////////\n\n Vector2u m_size; ///< Public texture size\n\n Vector2u m_actualSize; ///< Actual texture size (can be greater than public size because of padding)\n\n unsigned int m_texture; ///< Internal texture identifier\n\n bool m_isSmooth; ///< Status of the smooth filter\n\n bool m_sRgb; ///< Should the texture source be converted from sRGB?\n\n bool m_isRepeated; ///< Is the texture in repeat mode?\n\n mutable bool m_pixelsFlipped; ///< To work around the inconsistency in Y orientation\n\n bool m_fboAttachment; ///< Is this texture owned by a framebuffer object?\n\n bool m_hasMipmap; ///< Has the mipmap been generated?\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 15, "score": 89716.37727235025 }, { "content": " /// \\param area Area of the image to load\n\n ///\n\n /// \\return True if loading was successful\n\n ///\n\n /// \\see loadFromFile, loadFromMemory\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n bool loadFromImage(const Image& image, const IntRect& area = IntRect());\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Return the size of the texture\n\n ///\n\n /// \\return Size in pixels\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n Vector2u getSize() const;\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Copy the texture pixels to an image\n\n ///\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 16, "score": 89716.32856342853 }, { "content": " /// \\code\n\n /// sf::Texture t1, t2;\n\n /// ...\n\n /// sf::Texture::bind(&t1);\n\n /// // draw OpenGL stuff that use t1...\n\n /// sf::Texture::bind(&t2);\n\n /// // draw OpenGL stuff that use t2...\n\n /// sf::Texture::bind(NULL);\n\n /// // draw OpenGL stuff that use no texture...\n\n /// \\endcode\n\n ///\n\n /// The \\a coordinateType argument controls how texture\n\n /// coordinates will be interpreted. If Normalized (the default), they\n\n /// must be in range [0 .. 1], which is the default way of handling\n\n /// texture coordinates with OpenGL. If Pixels, they must be given\n\n /// in pixels (range [0 .. size]). This mode is used internally by\n\n /// the graphics classes of SFML, it makes the definition of texture\n\n /// coordinates more intuitive for the high-level API, users don't need\n\n /// to compute normalized values.\n\n ///\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 17, "score": 89716.32551522125 }, { "content": " /// This function performs a slow operation that downloads\n\n /// the texture's pixels from the graphics card and copies\n\n /// them to a new image, potentially applying transformations\n\n /// to pixels if necessary (texture may be padded or flipped).\n\n ///\n\n /// \\return Image containing the texture's pixels\n\n ///\n\n /// \\see loadFromImage\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n Image copyToImage() const;\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Update the whole texture from an array of pixels\n\n ///\n\n /// The \\a pixel array is assumed to have the same size as\n\n /// the \\a area rectangle, and to contain 32-bits RGBA pixels.\n\n ///\n\n /// No additional check is performed on the size of the pixel\n\n /// array, passing invalid arguments will lead to an undefined\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 18, "score": 89716.17166512787 }, { "content": " ///\n\n /// After enabling or disabling sRGB conversion, make sure to reload\n\n /// the texture data in order for the setting to take effect.\n\n ///\n\n /// This option is only useful in conjunction with an sRGB capable\n\n /// framebuffer. This can be requested during window creation.\n\n ///\n\n /// \\param sRgb True to enable sRGB conversion, false to disable it\n\n ///\n\n /// \\see isSrgb\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n void setSrgb(bool sRgb);\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Tell whether the texture source is converted from sRGB or not\n\n ///\n\n /// \\return True if the texture source is converted from sRGB, false if not\n\n ///\n\n /// \\see setSrgb\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 19, "score": 89715.92633786237 }, { "content": " ///\n\n /// If this function fails, the texture is left unchanged.\n\n ///\n\n /// \\param data Pointer to the file data in memory\n\n /// \\param size Size of the data to load, in bytes\n\n /// \\param area Area of the image to load\n\n ///\n\n /// \\return True if loading was successful\n\n ///\n\n /// \\see loadFromFile, loadFromStream, loadFromImage\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n bool loadFromMemory(const void* data, std::size_t size, const IntRect& area = IntRect());\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Load the texture from a custom stream\n\n ///\n\n /// This function is a shortcut for the following code:\n\n /// \\code\n\n /// sf::Image image;\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 20, "score": 89715.03296472915 }, { "content": "/// sprite.setTexture(texture);\n\n///\n\n/// // Draw the textured sprite\n\n/// window.draw(sprite);\n\n/// \\endcode\n\n///\n\n/// \\code\n\n/// // This example shows another common use of sf::Texture:\n\n/// // streaming real-time data, like video frames\n\n///\n\n/// // Create an empty texture\n\n/// sf::Texture texture;\n\n/// if (!texture.create(640, 480))\n\n/// return -1;\n\n///\n\n/// // Create a sprite that will display the texture\n\n/// sf::Sprite sprite(texture);\n\n///\n\n/// while (...) // the main loop\n\n/// {\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 21, "score": 89713.68698481254 }, { "content": " ///\n\n ////////////////////////////////////////////////////////////\n\n Texture();\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Copy constructor\n\n ///\n\n /// \\param copy instance to copy\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n Texture(const Texture& copy);\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Destructor\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n ~Texture();\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Create the texture\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 22, "score": 89713.60001910647 }, { "content": " Uint64 m_cacheId; ///< Unique number that identifies the texture to the render target's cache\n\n};\n\n\n\n} // namespace sf\n\n\n\n\n\n#endif // SFML_TEXTURE_HPP\n\n\n\n////////////////////////////////////////////////////////////\n\n/// \\class sf::Texture\n\n/// \\ingroup graphics\n\n///\n\n/// sf::Texture stores pixels that can be drawn, with a sprite\n\n/// for example. A texture lives in the graphics card memory,\n\n/// therefore it is very fast to draw a texture to a render target,\n\n/// or copy a render target to a texture (the graphics card can\n\n/// access both directly).\n\n///\n\n/// Being stored in the graphics card memory has some drawbacks.\n\n/// A texture cannot be manipulated as freely as a sf::Image,\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 23, "score": 89713.40635271893 }, { "content": "/// store the collision information separately, for example in an array\n\n/// of booleans.\n\n///\n\n/// Like sf::Image, sf::Texture can handle a unique internal\n\n/// representation of pixels, which is RGBA 32 bits. This means\n\n/// that a pixel must be composed of 8 bits red, green, blue and\n\n/// alpha channels -- just like a sf::Color.\n\n///\n\n/// Usage example:\n\n/// \\code\n\n/// // This example shows the most common use of sf::Texture:\n\n/// // drawing a sprite\n\n///\n\n/// // Load a texture from a file\n\n/// sf::Texture texture;\n\n/// if (!texture.loadFromFile(\"texture.png\"))\n\n/// return -1;\n\n///\n\n/// // Assign it to a sprite\n\n/// sf::Sprite sprite;\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 24, "score": 89713.24262615525 }, { "content": " ///\n\n ////////////////////////////////////////////////////////////\n\n bool isSrgb() const;\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Enable or disable repeating\n\n ///\n\n /// Repeating is involved when using texture coordinates\n\n /// outside the texture rectangle [0, 0, width, height].\n\n /// In this case, if repeat mode is enabled, the whole texture\n\n /// will be repeated as many times as needed to reach the\n\n /// coordinate (for example, if the X texture coordinate is\n\n /// 3 * width, the texture will be repeated 3 times).\n\n /// If repeat mode is disabled, the \"extra space\" will instead\n\n /// be filled with border pixels.\n\n /// Warning: on very old graphics cards, white pixels may appear\n\n /// when the texture is repeated. With such cards, repeat mode\n\n /// can be used reliably only if the texture has power-of-two\n\n /// dimensions (such as 256x128).\n\n /// Repeating is disabled by default.\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 25, "score": 89713.11668585001 }, { "content": " ///\n\n /// If this function fails, the texture is left unchanged.\n\n ///\n\n /// \\param width Width of the texture\n\n /// \\param height Height of the texture\n\n ///\n\n /// \\return True if creation was successful\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n bool create(unsigned int width, unsigned int height);\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Load the texture from a file on disk\n\n ///\n\n /// This function is a shortcut for the following code:\n\n /// \\code\n\n /// sf::Image image;\n\n /// image.loadFromFile(filename);\n\n /// texture.loadFromImage(image, area);\n\n /// \\endcode\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 26, "score": 89713.09455407162 }, { "content": "/// you need to prepare the pixels first and then upload them\n\n/// to the texture in a single operation (see Texture::update).\n\n///\n\n/// sf::Texture makes it easy to convert from/to sf::Image, but\n\n/// keep in mind that these calls require transfers between\n\n/// the graphics card and the central memory, therefore they are\n\n/// slow operations.\n\n///\n\n/// A texture can be loaded from an image, but also directly\n\n/// from a file/memory/stream. The necessary shortcuts are defined\n\n/// so that you don't need an image first for the most common cases.\n\n/// However, if you want to perform some modifications on the pixels\n\n/// before creating the final texture, you can load your file to a\n\n/// sf::Image, do whatever you need with the pixels, and then call\n\n/// Texture::loadFromImage.\n\n///\n\n/// Since they live in the graphics card memory, the pixels of a texture\n\n/// cannot be accessed without a slow copy first. And they cannot be\n\n/// accessed individually. Therefore, if you need to read the texture's\n\n/// pixels (like for pixel-perfect collisions), it is recommended to\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 27, "score": 89713.06993574594 }, { "content": "\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Get the underlying OpenGL handle of the texture.\n\n ///\n\n /// You shouldn't need to use this function, unless you have\n\n /// very specific stuff to implement that SFML doesn't support,\n\n /// or implement a temporary workaround until a bug is fixed.\n\n ///\n\n /// \\return OpenGL handle of the texture or 0 if not yet created\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n unsigned int getNativeHandle() const;\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Bind a texture for rendering\n\n ///\n\n /// This function is not part of the graphics API, it mustn't be\n\n /// used when drawing SFML entities. It must be used only if you\n\n /// mix sf::Texture with OpenGL code.\n\n ///\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 28, "score": 89712.70112536664 }, { "content": " ///\n\n /// Mipmaps are pre-computed chains of optimized textures. Each\n\n /// level of texture in a mipmap is generated by halving each of\n\n /// the previous level's dimensions. This is done until the final\n\n /// level has the size of 1x1. The textures generated in this process may\n\n /// make use of more advanced filters which might improve the visual quality\n\n /// of textures when they are applied to objects much smaller than they are.\n\n /// This is known as minification. Because fewer texels (texture elements)\n\n /// have to be sampled from when heavily minified, usage of mipmaps\n\n /// can also improve rendering performance in certain scenarios.\n\n ///\n\n /// Mipmap generation relies on the necessary OpenGL extension being\n\n /// available. If it is unavailable or generation fails due to another\n\n /// reason, this function will return false. Mipmap data is only valid from\n\n /// the time it is generated until the next time the base level image is\n\n /// modified, at which point this function will have to be called again to\n\n /// regenerate it.\n\n ///\n\n /// \\return True if mipmap generation was successful, false if unsuccessful\n\n ///\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 29, "score": 89712.47452456721 }, { "content": " /// \\see loadFromFile, loadFromMemory, loadFromImage\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n bool loadFromStream(InputStream& stream, const IntRect& area = IntRect());\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Load the texture from an image\n\n ///\n\n /// The \\a area argument can be used to load only a sub-rectangle\n\n /// of the whole image. If you want the entire image then leave\n\n /// the default value (which is an empty IntRect).\n\n /// If the \\a area rectangle crosses the bounds of the image, it\n\n /// is adjusted to fit the image size.\n\n ///\n\n /// The maximum size for a texture depends on the graphics\n\n /// driver and can be retrieved with the getMaximumSize function.\n\n ///\n\n /// If this function fails, the texture is left unchanged.\n\n ///\n\n /// \\param image Image to load into the texture\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 30, "score": 89712.45410176086 }, { "content": " /// image.loadFromStream(stream);\n\n /// texture.loadFromImage(image, area);\n\n /// \\endcode\n\n ///\n\n /// The \\a area argument can be used to load only a sub-rectangle\n\n /// of the whole image. If you want the entire image then leave\n\n /// the default value (which is an empty IntRect).\n\n /// If the \\a area rectangle crosses the bounds of the image, it\n\n /// is adjusted to fit the image size.\n\n ///\n\n /// The maximum size for a texture depends on the graphics\n\n /// driver and can be retrieved with the getMaximumSize function.\n\n ///\n\n /// If this function fails, the texture is left unchanged.\n\n ///\n\n /// \\param stream Source stream to read from\n\n /// \\param area Area of the image to load\n\n ///\n\n /// \\return True if loading was successful\n\n ///\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 31, "score": 89712.08739288793 }, { "content": " bool loadFromFile(const std::string& filename, const IntRect& area = IntRect());\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Load the texture from a file in memory\n\n ///\n\n /// This function is a shortcut for the following code:\n\n /// \\code\n\n /// sf::Image image;\n\n /// image.loadFromMemory(data, size);\n\n /// texture.loadFromImage(image, area);\n\n /// \\endcode\n\n ///\n\n /// The \\a area argument can be used to load only a sub-rectangle\n\n /// of the whole image. If you want the entire image then leave\n\n /// the default value (which is an empty IntRect).\n\n /// If the \\a area rectangle crosses the bounds of the image, it\n\n /// is adjusted to fit the image size.\n\n ///\n\n /// The maximum size for a texture depends on the graphics\n\n /// driver and can be retrieved with the getMaximumSize function.\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 32, "score": 89711.96132550835 }, { "content": " ///\n\n /// The \\a area argument can be used to load only a sub-rectangle\n\n /// of the whole image. If you want the entire image then leave\n\n /// the default value (which is an empty IntRect).\n\n /// If the \\a area rectangle crosses the bounds of the image, it\n\n /// is adjusted to fit the image size.\n\n ///\n\n /// The maximum size for a texture depends on the graphics\n\n /// driver and can be retrieved with the getMaximumSize function.\n\n ///\n\n /// If this function fails, the texture is left unchanged.\n\n ///\n\n /// \\param filename Path of the image file to load\n\n /// \\param area Area of the image to load\n\n ///\n\n /// \\return True if loading was successful\n\n ///\n\n /// \\see loadFromMemory, loadFromStream, loadFromImage\n\n ///\n\n ////////////////////////////////////////////////////////////\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 33, "score": 89711.43568283404 }, { "content": " friend class Text;\n\n friend class RenderTexture;\n\n friend class RenderTarget;\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Get a valid image size according to hardware support\n\n ///\n\n /// This function checks whether the graphics driver supports\n\n /// non power of two sizes or not, and adjusts the size\n\n /// accordingly.\n\n /// The returned size is greater than or equal to the original size.\n\n ///\n\n /// \\param size size to convert\n\n ///\n\n /// \\return Valid nearest size (greater than or equal to specified size)\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n static unsigned int getValidSize(unsigned int size);\n\n\n\n ////////////////////////////////////////////////////////////\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 34, "score": 89710.34521131947 }, { "content": " /// \\brief Tell whether the smooth filter is enabled or not\n\n ///\n\n /// \\return True if smoothing is enabled, false if it is disabled\n\n ///\n\n /// \\see setSmooth\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n bool isSmooth() const;\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Enable or disable conversion from sRGB\n\n ///\n\n /// When providing texture data from an image file or memory, it can\n\n /// either be stored in a linear color space or an sRGB color space.\n\n /// Most digital images account for gamma correction already, so they\n\n /// would need to be \"uncorrected\" back to linear color space before\n\n /// being processed by the hardware. The hardware can automatically\n\n /// convert it from the sRGB color space to a linear color space when\n\n /// it gets sampled. When the rendered image gets output to the final\n\n /// framebuffer, it gets converted back to sRGB.\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 35, "score": 89709.96171606105 }, { "content": "////////////////////////////////////////////////////////////\n\n//\n\n// SFML - Simple and Fast Multimedia Library\n\n// Copyright (C) 2007-2018 Laurent Gomila ([email protected])\n\n//\n\n// This software is provided 'as-is', without any express or implied warranty.\n\n// In no event will the authors be held liable for any damages arising from the use of this software.\n\n//\n\n// Permission is granted to anyone to use this software for any purpose,\n\n// including commercial applications, and to alter it and redistribute it freely,\n\n// subject to the following restrictions:\n\n//\n\n// 1. The origin of this software must not be misrepresented;\n\n// you must not claim that you wrote the original software.\n\n// If you use this software in a product, an acknowledgment\n\n// in the product documentation would be appreciated but is not required.\n\n//\n\n// 2. Altered source versions must be plainly marked as such,\n\n// and must not be misrepresented as being the original software.\n\n//\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 36, "score": 89709.90699064295 }, { "content": "////////////////////////////////////////////////////////////\n\n/// \\brief Image living on the graphics card that can be used for drawing\n\n///\n\n////////////////////////////////////////////////////////////\n\nclass SFML_GRAPHICS_API Texture : GlResource\n\n{\n\npublic:\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Types of texture coordinates that can be used for rendering\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n enum CoordinateType\n\n {\n\n Normalized, ///< Texture coordinates in range [0 .. 1]\n\n Pixels ///< Texture coordinates in range [0 .. size]\n\n };\n\n\n\npublic:\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Default constructor\n\n ///\n\n /// Creates an empty texture.\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 37, "score": 88081.26372004842 }, { "content": "///\n\n/// \\code\n\n/// // Create a new render-window\n\n/// sf::RenderWindow window(sf::VideoMode(800, 600), \"SFML window\");\n\n///\n\n/// // Create a new render-texture\n\n/// sf::RenderTexture texture;\n\n/// if (!texture.create(500, 500))\n\n/// return -1;\n\n///\n\n/// // The main loop\n\n/// while (window.isOpen())\n\n/// {\n\n/// // Event processing\n\n/// // ...\n\n///\n\n/// // Clear the whole texture with red color\n\n/// texture.clear(sf::Color::Red);\n\n///\n\n/// // Draw stuff to the texture\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/RenderTexture.hpp", "rank": 38, "score": 86883.18418974627 }, { "content": "\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Return the size of the rendering region of the texture\n\n ///\n\n /// The returned value is the size that you passed to\n\n /// the create function.\n\n ///\n\n /// \\return Size in pixels\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n virtual Vector2u getSize() const;\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Get a read-only reference to the target texture\n\n ///\n\n /// After drawing to the render-texture and calling Display,\n\n /// you can retrieve the updated texture using this function,\n\n /// and draw it using a sprite (for example).\n\n /// The internal sf::Texture of a render-texture is always the\n\n /// same instance, so that it is possible to call this function\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/RenderTexture.hpp", "rank": 39, "score": 86881.60935724824 }, { "content": " ///\n\n ////////////////////////////////////////////////////////////\n\n void setSmooth(bool smooth);\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Tell whether the smooth filtering is enabled or not\n\n ///\n\n /// \\return True if texture smoothing is enabled\n\n ///\n\n /// \\see setSmooth\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n bool isSmooth() const;\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Enable or disable texture repeating\n\n ///\n\n /// This function is similar to Texture::setRepeated.\n\n /// This parameter is disabled by default.\n\n ///\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/RenderTexture.hpp", "rank": 40, "score": 86881.4471581875 }, { "content": " /// \\param repeated True to enable repeating, false to disable it\n\n ///\n\n /// \\see isRepeated\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n void setRepeated(bool repeated);\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Tell whether the texture is repeated or not\n\n ///\n\n /// \\return True if texture is repeated\n\n ///\n\n /// \\see setRepeated\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n bool isRepeated() const;\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Generate a mipmap using the current texture data\n\n ///\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/RenderTexture.hpp", "rank": 41, "score": 86881.38970316184 }, { "content": "// 3. This notice may not be removed or altered from any source distribution.\n\n//\n\n////////////////////////////////////////////////////////////\n\n\n\n#ifndef SFML_RENDERTEXTURE_HPP\n\n#define SFML_RENDERTEXTURE_HPP\n\n\n\n////////////////////////////////////////////////////////////\n\n// Headers\n\n////////////////////////////////////////////////////////////\n\n#include <SFML/Graphics/Export.hpp>\n\n#include <SFML/Graphics/Texture.hpp>\n\n#include <SFML/Graphics/RenderTarget.hpp>\n\n#include <SFML/Window/ContextSettings.hpp>\n\n\n\n\n\nnamespace sf\n\n{\n\nnamespace priv\n\n{\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/RenderTexture.hpp", "rank": 42, "score": 86881.27948522655 }, { "content": " /// want to draw OpenGL geometry to another render target\n\n /// (like a RenderWindow) don't forget to activate it again.\n\n ///\n\n /// \\param active True to activate, false to deactivate\n\n ///\n\n /// \\return True if operation was successful, false otherwise\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n bool setActive(bool active = true);\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Update the contents of the target texture\n\n ///\n\n /// This function updates the target texture with what\n\n /// has been drawn so far. Like for windows, calling this\n\n /// function is mandatory at the end of rendering. Not calling\n\n /// it may leave the texture in an undefined state.\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n void display();\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/RenderTexture.hpp", "rank": 43, "score": 86880.3313807783 }, { "content": " /// once and keep a reference to the texture even after it is\n\n /// modified.\n\n ///\n\n /// \\return Const reference to the texture\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n const Texture& getTexture() const;\n\n\n\nprivate:\n\n\n\n ////////////////////////////////////////////////////////////\n\n // Member data\n\n ////////////////////////////////////////////////////////////\n\n priv::RenderTextureImpl* m_impl; ///< Platform/hardware specific implementation\n\n Texture m_texture; ///< Target texture to draw on\n\n};\n\n\n\n} // namespace sf\n\n\n\n\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/RenderTexture.hpp", "rank": 44, "score": 86878.21622454235 }, { "content": "/// texture.draw(sprite); // sprite is a sf::Sprite\n\n/// texture.draw(shape); // shape is a sf::Shape\n\n/// texture.draw(text); // text is a sf::Text\n\n///\n\n/// // We're done drawing to the texture\n\n/// texture.display();\n\n///\n\n/// // Now we start rendering to the window, clear it first\n\n/// window.clear();\n\n///\n\n/// // Draw the texture\n\n/// sf::Sprite sprite(texture.getTexture());\n\n/// window.draw(sprite);\n\n///\n\n/// // End the current frame and display its contents on screen\n\n/// window.display();\n\n/// }\n\n/// \\endcode\n\n///\n\n/// Like sf::RenderWindow, sf::RenderTexture is still able to render direct\n\n/// OpenGL stuff. It is even possible to mix together OpenGL calls\n\n/// and regular SFML drawing commands. If you need a depth buffer for\n\n/// 3D rendering, don't forget to request it when calling RenderTexture::create.\n\n///\n\n/// \\see sf::RenderTarget, sf::RenderWindow, sf::View, sf::Texture\n\n///\n\n////////////////////////////////////////////////////////////\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/RenderTexture.hpp", "rank": 45, "score": 86877.80184105276 }, { "content": "\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Create the render-texture\n\n ///\n\n /// Before calling this function, the render-texture is in\n\n /// an invalid state, thus it is mandatory to call it before\n\n /// doing anything with the render-texture.\n\n /// The last parameter, \\a depthBuffer, is useful if you want\n\n /// to use the render-texture for 3D OpenGL rendering that requires\n\n /// a depth buffer. Otherwise it is unnecessary, and you should\n\n /// leave this parameter to false (which is its default value).\n\n ///\n\n /// \\param width Width of the render-texture\n\n /// \\param height Height of the render-texture\n\n /// \\param depthBuffer Do you want this render-texture to have a depth buffer?\n\n ///\n\n /// \\return True if creation has been successful\n\n ///\n\n /// \\deprecated Use create(unsigned int, unsigned int, const ContextSettings&) instead.\n\n ///\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/RenderTexture.hpp", "rank": 46, "score": 86877.62307905745 }, { "content": " ////////////////////////////////////////////////////////////\n\n SFML_DEPRECATED bool create(unsigned int width, unsigned int height, bool depthBuffer);\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Create the render-texture\n\n ///\n\n /// Before calling this function, the render-texture is in\n\n /// an invalid state, thus it is mandatory to call it before\n\n /// doing anything with the render-texture.\n\n /// The last parameter, \\a settings, is useful if you want to enable\n\n /// multi-sampling or use the render-texture for OpenGL rendering that\n\n /// requires a depth or stencil buffer. Otherwise it is unnecessary, and\n\n /// you should leave this parameter at its default value.\n\n ///\n\n /// \\param width Width of the render-texture\n\n /// \\param height Height of the render-texture\n\n /// \\param settings Additional settings for the underlying OpenGL texture and context\n\n ///\n\n /// \\return True if creation has been successful\n\n ///\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/RenderTexture.hpp", "rank": 47, "score": 86877.56723268724 }, { "content": "#endif // SFML_RENDERTEXTURE_HPP\n\n\n\n\n\n////////////////////////////////////////////////////////////\n\n/// \\class sf::RenderTexture\n\n/// \\ingroup graphics\n\n///\n\n/// sf::RenderTexture is the little brother of sf::RenderWindow.\n\n/// It implements the same 2D drawing and OpenGL-related functions\n\n/// (see their base class sf::RenderTarget for more details),\n\n/// the difference is that the result is stored in an off-screen\n\n/// texture rather than being show in a window.\n\n///\n\n/// Rendering to a texture can be useful in a variety of situations:\n\n/// \\li precomputing a complex static texture (like a level's background from multiple tiles)\n\n/// \\li applying post-effects to the whole scene with shaders\n\n/// \\li creating a sprite from a 3D object rendered with OpenGL\n\n/// \\li etc.\n\n///\n\n/// Usage example:\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/RenderTexture.hpp", "rank": 48, "score": 86877.2358513558 }, { "content": " /// This function is similar to Texture::generateMipmap and operates\n\n /// on the texture used as the target for drawing.\n\n /// Be aware that any draw operation may modify the base level image data.\n\n /// For this reason, calling this function only makes sense after all\n\n /// drawing is completed and display has been called. Not calling display\n\n /// after subsequent drawing will lead to undefined behavior if a mipmap\n\n /// had been previously generated.\n\n ///\n\n /// \\return True if mipmap generation was successful, false if unsuccessful\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n bool generateMipmap();\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Activate or deactivate the render-texture for rendering\n\n ///\n\n /// This function makes the render-texture's context current for\n\n /// future OpenGL rendering operations (so you shouldn't care\n\n /// about it if you're not doing direct OpenGL stuff).\n\n /// Only one context can be current in a thread, so if you\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/RenderTexture.hpp", "rank": 49, "score": 86876.85606043118 }, { "content": " ////////////////////////////////////////////////////////////\n\n bool create(unsigned int width, unsigned int height, const ContextSettings& settings = ContextSettings());\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Get the maximum anti-aliasing level supported by the system\n\n ///\n\n /// \\return The maximum anti-aliasing level supported by the system\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n static unsigned int getMaximumAntialiasingLevel();\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Enable or disable texture smoothing\n\n ///\n\n /// This function is similar to Texture::setSmooth.\n\n /// This parameter is disabled by default.\n\n ///\n\n /// \\param smooth True to enable smoothing, false to disable it\n\n ///\n\n /// \\see isSmooth\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/RenderTexture.hpp", "rank": 50, "score": 86876.10806456045 }, { "content": "////////////////////////////////////////////////////////////\n\n//\n\n// SFML - Simple and Fast Multimedia Library\n\n// Copyright (C) 2007-2018 Laurent Gomila ([email protected])\n\n//\n\n// This software is provided 'as-is', without any express or implied warranty.\n\n// In no event will the authors be held liable for any damages arising from the use of this software.\n\n//\n\n// Permission is granted to anyone to use this software for any purpose,\n\n// including commercial applications, and to alter it and redistribute it freely,\n\n// subject to the following restrictions:\n\n//\n\n// 1. The origin of this software must not be misrepresented;\n\n// you must not claim that you wrote the original software.\n\n// If you use this software in a product, an acknowledgment\n\n// in the product documentation would be appreciated but is not required.\n\n//\n\n// 2. Altered source versions must be plainly marked as such,\n\n// and must not be misrepresented as being the original software.\n\n//\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/RenderTexture.hpp", "rank": 51, "score": 86874.40213612576 }, { "content": "class Window;\n\n\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 52, "score": 86871.21757355853 }, { "content": "class Texture;\n\n\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Sprite.hpp", "rank": 53, "score": 86871.21757355853 }, { "content": "class Text;\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 54, "score": 86871.21757355853 }, { "content": "class Texture;\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Shader.hpp", "rank": 55, "score": 86871.21757355853 }, { "content": "class RenderTarget;\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 56, "score": 84209.47313125704 }, { "content": "class Texture;\n\n\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/RenderStates.hpp", "rank": 57, "score": 84209.47313125704 }, { "content": "class InputStream;\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 58, "score": 84209.47313125704 }, { "content": "////////////////////////////////////////////////////////////\n\n/// \\brief Target for off-screen 2D rendering into a texture\n\n///\n\n////////////////////////////////////////////////////////////\n\nclass SFML_GRAPHICS_API RenderTexture : public RenderTarget\n\n{\n\npublic:\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Default constructor\n\n ///\n\n /// Constructs an empty, invalid render-texture. You must\n\n /// call create to have a valid render-texture.\n\n ///\n\n /// \\see create\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n RenderTexture();\n\n\n\n ////////////////////////////////////////////////////////////\n\n /// \\brief Destructor\n\n ///\n\n ////////////////////////////////////////////////////////////\n\n virtual ~RenderTexture();\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/RenderTexture.hpp", "rank": 59, "score": 82654.8942089132 }, { "content": "class TextureManager\n\n{\n\npublic:\n\n\tenum AssetType { BG = 0, Eagle = 1, Raptor = 2, Spike = 4, Avenger = 5, UI_BG = 6, ButtonNormal = 7, ButtonPressed = 8, HUD_BG = 9,\n\n\tMAIN_MENU_BG = 10};\n\n\tenum FontType {DefaultFont = 0};\n\n\tstatic TextureManager* getInstance();\n\n\tvoid loadAll();\n\n\tsf::Texture* getTextureAt(TextureManager::AssetType assetType, int index);\n\n\tint getTextureLength(TextureManager::AssetType assetType);\n\n\tsf::Font* getFont(FontType fontType);\n\n\n\n\n\n\tvoid testFunction();\n\n\n\nprivate:\n\n\tTextureManager() {};\n\n\tTextureManager(TextureManager const&) {}; // copy constructor is private\n\n\tTextureManager& operator=(TextureManager const&) {}; // assignment operator is private\n\n\tstatic TextureManager* sharedInstance;\n\n\n\n\tunordered_map<TextureManager::AssetType, vector<sf::Texture*>> textureMap;\n\n\tunordered_map<TextureManager::FontType, sf::Font*> fontMap;\n\n\n\n};", "file_path": "GDADPRG_HO6/TextureManager.h", "rank": 60, "score": 58253.02254185881 }, { "content": "class TextureManager\n\n{\n\npublic:\n\n\tenum AssetType { BG = 0, Eagle = 1, Raptor = 2, Spike = 3, UI_BG = 4, ButtonNormal = 5, ButtonPressed = 6, HUD_BG = 7};\n\n\tenum FontType {DefaultFont = 0};\n\n\tstatic TextureManager* getInstance();\n\n\tvoid loadAll();\n\n\tsf::Texture* getTextureAt(TextureManager::AssetType assetType, int index);\n\n\tint getTextureLength(TextureManager::AssetType assetType);\n\n\tsf::Font* getFont(FontType fontType);\n\n\n\n\n\n\tvoid testFunction();\n\n\n\nprivate:\n\n\tTextureManager() {};\n\n\tTextureManager(TextureManager const&) {}; // copy constructor is private\n\n\tTextureManager& operator=(TextureManager const&) {}; // assignment operator is private\n\n\tstatic TextureManager* sharedInstance;\n\n\n\n\tunordered_map<TextureManager::AssetType, vector<sf::Texture*>> textureMap;\n\n\tunordered_map<TextureManager::FontType, sf::Font*> fontMap;\n\n\n\n};", "file_path": "GDADPRG_HO4/TextureManager.h", "rank": 61, "score": 58253.02254185881 }, { "content": "class TextureManager\n\n{\n\npublic:\n\n\ttypedef std::string String;\n\n\ttypedef std::vector<sf::Texture*> TextureList;\n\n\ttypedef std::unordered_map<String, TextureList> HashTable;\n\n\t\n\npublic:\n\n\tstatic TextureManager* getInstance();\n\n\tvoid loadFromAssetList(); //loading of all assets needed for startup\n\n\tvoid loadStreamingAssets(); //loading of assets during runtime\n\n\tvoid loadSingleStreamAsset(int index, IExecutionEvent* executionEvent); //loads a single streaming asset based on index in directory\n\n\tsf::Texture* getFromTextureMap(const String assetName, int frameIndex);\n\n\tint getNumFrames(const String assetName);\n\n\n\n\tsf::Texture* getStreamTextureFromList(const int index);\n\n\tint getNumLoadedStreamTextures() const;\n\n\n\n\tvoid instantiateAsTexture(String path, String assetName, bool isStreaming);\n\n\n", "file_path": "GDPARCM_HO3/TextureManager.h", "rank": 62, "score": 58253.02254185881 }, { "content": "class TextureManager\n\n{\n\npublic:\n\n\tenum AssetType { BG = 0, Eagle = 1, Raptor = 2, Spike = 4, Avenger = 5, UI_BG = 6, ButtonNormal = 7, ButtonPressed = 8, HUD_BG = 9,\n\n\tMAIN_MENU_BG = 10, PROJECTILE = 11};\n\n\tenum FontType {DefaultFont = 0};\n\n\tstatic TextureManager* getInstance();\n\n\tvoid loadAll();\n\n\tsf::Texture* getTextureAt(TextureManager::AssetType assetType, int index);\n\n\tint getTextureLength(TextureManager::AssetType assetType);\n\n\tsf::Font* getFont(FontType fontType);\n\n\n\n\n\n\tvoid testFunction();\n\n\n\nprivate:\n\n\tTextureManager() {};\n\n\tTextureManager(TextureManager const&) {}; // copy constructor is private\n\n\tTextureManager& operator=(TextureManager const&) {}; // assignment operator is private\n\n\tstatic TextureManager* sharedInstance;\n\n\n\n\tunordered_map<TextureManager::AssetType, vector<sf::Texture*>> textureMap;\n\n\tunordered_map<TextureManager::FontType, sf::Font*> fontMap;\n\n\n\n};", "file_path": "GDADPRG_HO7/TextureManager.h", "rank": 63, "score": 58253.02254185881 }, { "content": "class TextureManager\n\n{\n\n\tpublic:\n\n\t\tenum AssetType { Bed = 0, Bench = 1, Box = 2, Coin = 3};\n\n\t\tstatic TextureManager* getInstance();\n\n\t\tvoid loadAll();\n\n\t\tsf::Texture* getTextureAt(TextureManager::AssetType assetType, int index);\n\n\t\tint getTextureLength(TextureManager::AssetType assetType);\n\n\t\tvoid testFunction();\n\n\n\n\tprivate:\n\n\t\tTextureManager() {};\n\n\t\tTextureManager(TextureManager const&) {}; // copy constructor is private\n\n\t\tTextureManager& operator=(TextureManager const&) {}; // assignment operator is private\n\n\t\tstatic TextureManager* sharedInstance;\n\n\n\n\t\tunordered_map<TextureManager::AssetType, vector<sf::Texture*>> textureMap;\n\n\n\n};\n\n\n\n\n\n\n", "file_path": "GDADPRG_Courseware/TextureManager.h", "rank": 64, "score": 58253.02254185881 }, { "content": "class TextureManager\n\n{\n\npublic:\n\n\tenum AssetType { BG = 0, Eagle = 1, Raptor = 2, Spike = 4, Avenger = 5, UI_BG = 6, ButtonNormal = 7, ButtonPressed = 8, HUD_BG = 9};\n\n\tenum FontType {DefaultFont = 0};\n\n\tstatic TextureManager* getInstance();\n\n\tvoid loadAll();\n\n\tsf::Texture* getTextureAt(TextureManager::AssetType assetType, int index);\n\n\tint getTextureLength(TextureManager::AssetType assetType);\n\n\tsf::Font* getFont(FontType fontType);\n\n\n\n\n\n\tvoid testFunction();\n\n\n\nprivate:\n\n\tTextureManager() {};\n\n\tTextureManager(TextureManager const&) {}; // copy constructor is private\n\n\tTextureManager& operator=(TextureManager const&) {}; // assignment operator is private\n\n\tstatic TextureManager* sharedInstance;\n\n\n\n\tunordered_map<TextureManager::AssetType, vector<sf::Texture*>> textureMap;\n\n\tunordered_map<TextureManager::FontType, sf::Font*> fontMap;\n\n\n\n};", "file_path": "GDADPRG_HO5/TextureManager.h", "rank": 65, "score": 58253.02254185881 }, { "content": "class TextureManager\n\n{\n\npublic:\n\n\ttypedef std::string String;\n\n\ttypedef std::vector<sf::Texture*> TextureList;\n\n\ttypedef std::unordered_map<String, TextureList> HashTable;\n\n\t\n\npublic:\n\n\tstatic TextureManager* getInstance();\n\n\tvoid loadFromAssetList(); //loading of all assets needed for startup\n\n\tvoid loadStreamingAssets(); //loading of assets during runtime\n\n\tvoid loadSingleStreamAsset(int index, IExecutionEvent* executionEvent); //loads a single streaming asset based on index in directory\n\n\tsf::Texture* getFromTextureMap(const String assetName, int frameIndex);\n\n\tint getNumFrames(const String assetName);\n\n\n\n\tsf::Texture* getStreamTextureFromList(const int index);\n\n\tint getNumLoadedStreamTextures() const;\n\n\n\n\tvoid instantiateAsTexture(String path, String assetName, bool isStreaming);\n\n\n", "file_path": "GDPARCM_HO4/TextureManager.h", "rank": 66, "score": 58253.02254185881 }, { "content": "class TextureManager\n\n{\n\npublic:\n\n\ttypedef std::string String;\n\n\ttypedef std::vector<sf::Texture*> TextureList;\n\n\ttypedef std::unordered_map<String, TextureList> HashTable;\n\n\t\n\npublic:\n\n\tstatic TextureManager* getInstance();\n\n\tvoid loadFromAssetList(); //loading of all assets needed for startup\n\n\tvoid loadStreamingAssets(); //loading of assets during runtime\n\n\tvoid loadSingleStreamAsset(int index); //loads a single streaming asset based on index in directory\n\n\tsf::Texture* getFromTextureMap(const String assetName, int frameIndex);\n\n\tint getNumFrames(const String assetName);\n\n\n\n\tsf::Texture* getStreamTextureFromList(const int index);\n\n\tint getNumLoadedStreamTextures() const;\n\n\n\nprivate:\n\n\tTextureManager();\n", "file_path": "GDPARCM_HO2/TextureManager.h", "rank": 67, "score": 58253.02254185881 }, { "content": "class TextureManager\n\n{\n\npublic:\n\n\tenum AssetType { BG = 0, Eagle = 1, Raptor = 2, Spike = 3};\n\n\tstatic TextureManager* getInstance();\n\n\tvoid loadAll();\n\n\tsf::Texture* getTextureAt(TextureManager::AssetType assetType, int index);\n\n\tint getTextureLength(TextureManager::AssetType assetType);\n\n\tvoid testFunction();\n\n\n\nprivate:\n\n\tTextureManager() {};\n\n\tTextureManager(TextureManager const&) {}; // copy constructor is private\n\n\tTextureManager& operator=(TextureManager const&) {}; // assignment operator is private\n\n\tstatic TextureManager* sharedInstance;\n\n\n\n\tunordered_map<TextureManager::AssetType, vector<sf::Texture*>> textureMap;\n\n\n\n};", "file_path": "GDADPRG_HO3 - Part 3/TextureManager.h", "rank": 68, "score": 57083.73435264558 }, { "content": "class TextureManager\n\n{\n\npublic:\n\n\ttypedef std::string String;\n\n\ttypedef std::vector<sf::Texture*> TextureList;\n\n\ttypedef std::unordered_map<String, TextureList> HashTable;\n\n\t\n\npublic:\n\n\tstatic TextureManager* getInstance();\n\n\tvoid loadFromAssetList(); //loading of all assets needed for startup\n\n\tvoid loadStreamingAssets(); //loading of assets during runtime\n\n\tvoid loadSingleStreamAsset(int index, IExecutionEvent* executionEvent); //loads a single streaming asset based on index in directory\n\n\tsf::Texture* getFromTextureMap(const String assetName, int frameIndex);\n\n\tint getNumFrames(const String assetName);\n\n\n\n\tsf::Texture* getStreamTextureFromList(const int index);\n\n\tint getNumLoadedStreamTextures() const;\n\n\n\n\tvoid instantiateAsTexture(String path, String assetName, bool isStreaming);\n\n\n", "file_path": "GDPARCM_HO3 - Solution/TextureManager.h", "rank": 69, "score": 57083.73435264558 }, { "content": "class TextureManager\n\n{\n\npublic:\n\n\tenum AssetType { BG = 0, Eagle = 1, Raptor = 2};\n\n\tstatic TextureManager* getInstance();\n\n\tvoid loadAll();\n\n\tsf::Texture* getTextureAt(TextureManager::AssetType assetType, int index);\n\n\tint getTextureLength(TextureManager::AssetType assetType);\n\n\tvoid testFunction();\n\n\n\nprivate:\n\n\tTextureManager() {};\n\n\tTextureManager(TextureManager const&) {}; // copy constructor is private\n\n\tTextureManager& operator=(TextureManager const&) {}; // assignment operator is private\n\n\tstatic TextureManager* sharedInstance;\n\n\n\n\tunordered_map<TextureManager::AssetType, vector<sf::Texture*>> textureMap;\n\n\n\n};", "file_path": "GDADPRG_HO3 - Part 2/TextureManager.h", "rank": 70, "score": 57083.73435264558 }, { "content": "class TextureManager\n\n{\n\npublic:\n\n\ttypedef std::string String;\n\n\ttypedef std::vector<sf::Texture*> TextureList;\n\n\ttypedef std::unordered_map<String, TextureList> HashTable;\n\n\t\n\npublic:\n\n\tstatic TextureManager* getInstance();\n\n\tvoid loadFromAssetList(); //loading of all assets needed for startup\n\n\tvoid loadStreamingAssets(); //loading of assets during runtime\n\n\tvoid loadSingleStreamAsset(int index, IExecutionEvent* executionEvent); //loads a single streaming asset based on index in directory\n\n\tsf::Texture* getFromTextureMap(const String assetName, int frameIndex);\n\n\tint getNumFrames(const String assetName);\n\n\n\n\tsf::Texture* getStreamTextureFromList(const int index);\n\n\tint getNumLoadedStreamTextures() const;\n\n\n\n\tvoid instantiateAsTexture(String path, String assetName, bool isStreaming);\n\n\n", "file_path": "GDPARCM_HO2 - Solution/TextureManager.h", "rank": 71, "score": 57083.73435264558 }, { "content": "class TextureManager\n\n{\n\npublic:\n\n\tenum AssetType { BG = 0, Eagle = 1, Raptor = 2};\n\n\tstatic TextureManager* getInstance();\n\n\tvoid loadAll();\n\n\tsf::Texture* getTextureAt(TextureManager::AssetType assetType, int index);\n\n\tint getTextureLength(TextureManager::AssetType assetType);\n\n\tvoid testFunction();\n\n\n\nprivate:\n\n\tTextureManager() {};\n\n\tTextureManager(TextureManager const&) {}; // copy constructor is private\n\n\tTextureManager& operator=(TextureManager const&) {}; // assignment operator is private\n\n\tstatic TextureManager* sharedInstance;\n\n\n\n\tunordered_map<TextureManager::AssetType, vector<sf::Texture*>> textureMap;\n\n\n\n};", "file_path": "GDADPRG_HO3 - Part 1/TextureManager.h", "rank": 72, "score": 57083.73435264558 }, { "content": "/// <summary>\n\n/// Class that deals with displaying of streamed textures\n\n/// </summary>\n\nclass TextureDisplay: public AGameObject\n\n{\n\npublic:\n\n\tTextureDisplay();\n\n\tvoid initialize();\n\n\tvoid processInput(sf::Event event);\n\n\tvoid update(sf::Time deltaTime);\n\n\n\nprivate:\n\n\ttypedef std::vector<IconObject*> IconList;\n\n\tIconList iconList;\n\n\n\n\tenum StreamingType { BATCH_LOAD = 0, SINGLE_STREAM = 1 };\n\n\tconst float STREAMING_LOAD_DELAY = 2000.0f;\n\n\tconst StreamingType streamingType = SINGLE_STREAM;\n\n\tfloat ticks = 0.0f;\n\n\tbool startedStreaming = false;\n\n\n\n\tint columnGrid = 0; int rowGrid = 0;\n\n\t\n\n\tconst int MAX_COLUMN = 28;\n\n\tconst int MAX_ROW = 22;\n\n\n\n\tvoid spawnObject();\n\n};\n\n\n", "file_path": "GDPARCM_HO2/TextureDisplay.h", "rank": 73, "score": 54885.98838671841 }, { "content": "/// <summary>\n\n/// Class that deals with displaying of streamed textures\n\n/// </summary>\n\nclass TextureDisplay: public AGameObject, public IExecutionEvent\n\n{\n\npublic:\n\n\tTextureDisplay();\n\n\tvoid initialize();\n\n\tvoid processInput(sf::Event event);\n\n\tvoid update(sf::Time deltaTime);\n\n\n\n\tvoid onFinishedExecution() override;\n\n\n\nprivate:\n\n\ttypedef std::vector<IconObject*> IconList;\n\n\ttypedef std::mutex Mutex;\n\n\tIconList iconList;\n\n\n\n\tenum StreamingType { BATCH_LOAD = 0, SINGLE_STREAM = 1 };\n\n\tconst float STREAMING_LOAD_DELAY = 25.0f; //greatly reduce streaming load delay to demonstrate performance drop.\n\n\tconst StreamingType streamingType = SINGLE_STREAM;\n\n\tfloat ticks = 0.0f;\n\n\tbool startedStreaming = false;\n", "file_path": "GDPARCM_HO4/TextureDisplay.h", "rank": 74, "score": 51882.63213132596 }, { "content": "/// <summary>\n\n/// Class that deals with displaying of streamed textures\n\n/// </summary>\n\nclass TextureDisplay: public AGameObject, public IExecutionEvent\n\n{\n\npublic:\n\n\tTextureDisplay();\n\n\tvoid initialize();\n\n\tvoid processInput(sf::Event event);\n\n\tvoid update(sf::Time deltaTime);\n\n\n\n\tvoid onFinishedExecution() override;\n\n\n\nprivate:\n\n\ttypedef std::vector<IconObject*> IconList;\n\n\ttypedef std::mutex Mutex;\n\n\tIconList iconList;\n\n\n\n\tenum StreamingType { BATCH_LOAD = 0, SINGLE_STREAM = 1 };\n\n\tconst float STREAMING_LOAD_DELAY = 25.0f; //greatly reduce streaming load delay to demonstrate performance drop.\n\n\tconst StreamingType streamingType = SINGLE_STREAM;\n\n\tfloat ticks = 0.0f;\n\n\tbool startedStreaming = false;\n", "file_path": "GDPARCM_HO3/TextureDisplay.h", "rank": 75, "score": 51882.63213132596 }, { "content": "/// <summary>\n\n/// Class that deals with displaying of streamed textures\n\n/// </summary>\n\nclass TextureDisplay: public AGameObject, public IExecutionEvent\n\n{\n\npublic:\n\n\tTextureDisplay();\n\n\tvoid initialize();\n\n\tvoid processInput(sf::Event event);\n\n\tvoid update(sf::Time deltaTime);\n\n\n\n\tvoid onFinishedExecution() override;\n\n\n\nprivate:\n\n\ttypedef std::vector<IconObject*> IconList;\n\n\tIconList iconList;\n\n\n\n\tenum StreamingType { BATCH_LOAD = 0, SINGLE_STREAM = 1 };\n\n\tconst float STREAMING_LOAD_DELAY = 1000.0f;\n\n\tconst StreamingType streamingType = SINGLE_STREAM;\n\n\tfloat ticks = 0.0f;\n\n\tbool startedStreaming = false;\n\n\n\n\tint columnGrid = 0; int rowGrid = 0;\n\n\tint numDisplayed = 0;\n\n\tconst int MAX_COLUMN = 28;\n\n\tconst int MAX_ROW = 22;\n\n\n\n\tvoid spawnObject();\n\n};\n\n\n", "file_path": "GDPARCM_HO2 - Solution/TextureDisplay.h", "rank": 76, "score": 50953.253457430816 }, { "content": "/// <summary>\n\n/// Class that deals with displaying of streamed textures\n\n/// </summary>\n\nclass TextureDisplay: public AGameObject, public IExecutionEvent\n\n{\n\npublic:\n\n\tTextureDisplay();\n\n\tvoid initialize();\n\n\tvoid processInput(sf::Event event);\n\n\tvoid update(sf::Time deltaTime);\n\n\n\n\tvoid onFinishedExecution() override;\n\n\n\nprivate:\n\n\ttypedef std::vector<IconObject*> IconList;\n\n\tIconList iconList;\n\n\n\n\tenum StreamingType { BATCH_LOAD = 0, SINGLE_STREAM = 1 };\n\n\tconst float STREAMING_LOAD_DELAY = 25.0f; //greatly reduce streaming load delay to demonstrate performance drop.\n\n\tconst StreamingType streamingType = SINGLE_STREAM;\n\n\tfloat ticks = 0.0f;\n\n\tbool startedStreaming = false;\n\n\n\n\tint columnGrid = 0; int rowGrid = 0;\n\n\tint numDisplayed = 0;\n\n\tconst int MAX_COLUMN = 28;\n\n\tconst int MAX_ROW = 22;\n\n\n\n\tvoid spawnObject();\n\n};\n\n\n", "file_path": "GDPARCM_HO3 - Solution/TextureDisplay.h", "rank": 77, "score": 50953.253457430816 }, { "content": "\tTextureManager(TextureManager const&) {}; // copy constructor is private\n\n\tTextureManager& operator=(TextureManager const&) {}; // assignment operator is private\n\n\tstatic TextureManager* sharedInstance;\n\n\n\n\tHashTable textureMap;\n\n\tTextureList baseTextureList;\n\n\tTextureList streamTextureList;\n\n\n\n\tconst std::string STREAMING_PATH = \"Media/Streaming/\";\n\n\tint streamingAssetCount = 0;\n\n\n\n\tvoid countStreamingAssets();\n\n\tvoid instantiateAsTexture(String path, String assetName, bool isStreaming);\n\n\n\n};", "file_path": "GDPARCM_HO2/TextureManager.h", "rank": 78, "score": 49665.508243681295 }, { "content": "private:\n\n\tTextureManager();\n\n\tTextureManager(TextureManager const&) {}; // copy constructor is private\n\n\tTextureManager& operator=(TextureManager const&) {}; // assignment operator is private\n\n\tstatic TextureManager* sharedInstance;\n\n\n\n\tHashTable textureMap;\n\n\tTextureList baseTextureList;\n\n\tTextureList streamTextureList;\n\n\n\n\tconst std::string STREAMING_PATH = \"Media/Streaming/\";\n\n\tint streamingAssetCount = 0;\n\n\n\n\tvoid countStreamingAssets();\n\n\n\n};", "file_path": "GDPARCM_HO4/TextureManager.h", "rank": 79, "score": 49664.51925298656 }, { "content": "private:\n\n\tTextureManager();\n\n\tTextureManager(TextureManager const&) {}; // copy constructor is private\n\n\tTextureManager& operator=(TextureManager const&) {}; // assignment operator is private\n\n\tstatic TextureManager* sharedInstance;\n\n\n\n\tHashTable textureMap;\n\n\tTextureList baseTextureList;\n\n\tTextureList streamTextureList;\n\n\n\n\tconst std::string STREAMING_PATH = \"Media/Streaming/\";\n\n\tint streamingAssetCount = 0;\n\n\n\n\tvoid countStreamingAssets();\n\n\n\n};", "file_path": "GDPARCM_HO3/TextureManager.h", "rank": 80, "score": 49664.51925298656 }, { "content": "#pragma once\n\n#include \"AGameObject.h\"\n\n#include \"IExecutionEvent.h\"\n\n#include <mutex>\n", "file_path": "GDPARCM_HO3/TextureDisplay.h", "rank": 81, "score": 49660.28320316637 }, { "content": "#pragma once\n\n#include \"AGameObject.h\"\n\n#include \"IExecutionEvent.h\"\n\n#include <mutex>\n", "file_path": "GDPARCM_HO4/TextureDisplay.h", "rank": 82, "score": 49660.28320316637 }, { "content": "#pragma once\n\n#include <unordered_map>\n\n#include \"SFML/Graphics.hpp\"\n\n\n", "file_path": "GDPARCM_HO4/TextureManager.h", "rank": 83, "score": 49659.936585691095 }, { "content": "#pragma once\n\n#include <unordered_map>\n\n#include \"SFML/Graphics.hpp\"\n\n\n", "file_path": "GDPARCM_HO3/TextureManager.h", "rank": 84, "score": 49659.936585691095 }, { "content": "#pragma once\n\n#include <unordered_map>\n\n#include \"SFML/Graphics.hpp\"\n\n\n", "file_path": "GDPARCM_HO2/TextureManager.h", "rank": 85, "score": 49659.936585691095 }, { "content": "#pragma once\n\n#include <unordered_map>\n\n#include \"SFML/Graphics.hpp\"\n\nusing namespace std;\n\n\n", "file_path": "GDADPRG_HO5/TextureManager.h", "rank": 86, "score": 49659.82693017145 }, { "content": "#pragma once\n\n#include <unordered_map>\n\n#include \"SFML/Graphics.hpp\"\n\nusing namespace std;\n\n\n", "file_path": "GDADPRG_Courseware/TextureManager.h", "rank": 87, "score": 49659.82693017145 }, { "content": "#pragma once\n\n#include <unordered_map>\n\n#include \"SFML/Graphics.hpp\"\n\nusing namespace std;\n\n\n", "file_path": "GDADPRG_HO7/TextureManager.h", "rank": 88, "score": 49659.82693017145 }, { "content": "#pragma once\n\n#include <unordered_map>\n\n#include \"SFML/Graphics.hpp\"\n\nusing namespace std;\n\n\n", "file_path": "GDADPRG_HO4/TextureManager.h", "rank": 89, "score": 49659.82693017145 }, { "content": "#pragma once\n\n#include <unordered_map>\n\n#include \"SFML/Graphics.hpp\"\n\nusing namespace std;\n\n\n", "file_path": "GDADPRG_HO6/TextureManager.h", "rank": 90, "score": 49659.82693017145 }, { "content": "#pragma once\n\n#include \"AGameObject.h\"\n\n\n", "file_path": "GDPARCM_HO2/TextureDisplay.h", "rank": 91, "score": 49659.25968168157 }, { "content": "\n\n\tint columnGrid = 0; int rowGrid = 0;\n\n\tint numDisplayed = 0;\n\n\tconst int MAX_COLUMN = 28;\n\n\tconst int MAX_ROW = 22;\n\n\n\n\tMutex guard; //used to avoid possible race conditions when spawning objects. Not really required for this exercise. Will be explained in future lessons.\n\n\tvoid spawnObject();\n\n};\n\n\n", "file_path": "GDPARCM_HO4/TextureDisplay.h", "rank": 92, "score": 49657.98333729909 }, { "content": "\n\n\tint columnGrid = 0; int rowGrid = 0;\n\n\tint numDisplayed = 0;\n\n\tconst int MAX_COLUMN = 28;\n\n\tconst int MAX_ROW = 22;\n\n\n\n\tMutex guard; //used to avoid possible race conditions when spawning objects. Not really required for this exercise. Will be explained in future lessons.\n\n\tvoid spawnObject();\n\n};\n\n\n", "file_path": "GDPARCM_HO3/TextureDisplay.h", "rank": 93, "score": 49657.98333729909 }, { "content": "#include <stddef.h>\n\n#include <iostream>\n\n#include \"TextureManager.h\"\n\n\n\n//a singleton class\n\nTextureManager* TextureManager::sharedInstance = NULL;\n\n\n\nTextureManager* TextureManager::getInstance() {\n\n\tif (sharedInstance == NULL) {\n\n\t\t//initialize\n\n\t\tsharedInstance = new TextureManager();\n\n\t}\n\n\n\n\treturn sharedInstance;\n\n}\n\n\n\nvoid TextureManager::loadAll() {\n\n\tsf::Texture* texture = new sf::Texture();\n\n\ttexture->loadFromFile(\"Media/Textures/b_4.png\");\n\n\tthis->textureMap[ButtonNormal].push_back(texture);\n", "file_path": "GDADPRG_HO7/TextureManager.cpp", "rank": 95, "score": 48008.02009965514 }, { "content": "#include <stddef.h>\n\n#include <iostream>\n\n#include \"TextureManager.h\"\n\n\n\n//a singleton class\n\nTextureManager* TextureManager::sharedInstance = NULL;\n\n\n\nTextureManager* TextureManager::getInstance() {\n\n\tif (sharedInstance == NULL) {\n\n\t\t//initialize\n\n\t\tsharedInstance = new TextureManager();\n\n\t}\n\n\n\n\treturn sharedInstance;\n\n}\n\n\n\nvoid TextureManager::loadAll() {\n\n\tsf::Texture* texture = new sf::Texture();\n\n\ttexture->loadFromFile(\"Media/Textures/b_4.png\");\n\n\tthis->textureMap[ButtonNormal].push_back(texture);\n", "file_path": "GDADPRG_HO5/TextureManager.cpp", "rank": 96, "score": 48008.02009965514 }, { "content": "#include <stddef.h>\n\n#include <iostream>\n\n#include \"TextureManager.h\"\n\n\n\n//a singleton class\n\nTextureManager* TextureManager::sharedInstance = NULL;\n\n\n\nTextureManager* TextureManager::getInstance() {\n\n\tif (sharedInstance == NULL) {\n\n\t\t//initialize\n\n\t\tsharedInstance = new TextureManager();\n\n\t}\n\n\n\n\treturn sharedInstance;\n\n}\n\n\n\nvoid TextureManager::loadAll() {\n\n\tsf::Texture* texture = new sf::Texture();\n\n\ttexture->loadFromFile(\"Media/Textures/b_4.png\");\n\n\tthis->textureMap[ButtonNormal].push_back(texture);\n", "file_path": "GDADPRG_HO6/TextureManager.cpp", "rank": 97, "score": 48008.02009965514 }, { "content": "#include <stddef.h>\n\n#include <iostream>\n\n#include \"TextureManager.h\"\n\n\n\n//a singleton class\n\nTextureManager* TextureManager::sharedInstance = NULL;\n\n\n\nTextureManager* TextureManager::getInstance() {\n\n\tif (sharedInstance == NULL) {\n\n\t\t//initialize\n\n\t\tsharedInstance = new TextureManager();\n\n\t}\n\n\n\n\treturn sharedInstance;\n\n}\n\n\n\nvoid TextureManager::loadAll() {\n\n\tsf::Texture* texture = new sf::Texture();\n\n\ttexture->loadFromFile(\"Media/Textures/b_4.png\");\n\n\tthis->textureMap[ButtonNormal].push_back(texture);\n", "file_path": "GDADPRG_HO4/TextureManager.cpp", "rank": 98, "score": 48008.02009965514 }, { "content": "#include <fstream>\n\n#include <iostream>\n\n#include <filesystem>\n\n#include \"TextureManager.h\"\n\n#include \"StringUtils.h\"\n\n#include \"IETThread.h\"\n\n\n\n//a singleton class\n\nTextureManager* TextureManager::sharedInstance = NULL;\n\n\n\nTextureManager* TextureManager::getInstance() {\n\n\tif (sharedInstance == NULL) {\n\n\t\t//initialize\n\n\t\tsharedInstance = new TextureManager();\n\n\t}\n\n\n\n\treturn sharedInstance;\n\n}\n\n\n\nTextureManager::TextureManager()\n", "file_path": "GDPARCM_HO2/TextureManager.cpp", "rank": 99, "score": 48004.807028539486 } ]
C++
src/tests/test_fixedindexarray.cpp
P-Sc/Pirateers
440e477d33bbbcd79d291700c369f74fd0a6cc7d
#include "test_fixedindexarray.h" #include "utils/fixedindexarray.h" void Test_FixedIndexArray::test1() { currentTestCase = 1; log("Testing: add() and getSize()"); for (unsigned int i = 50; i < 150; i++) { fixArray1->add(i); fixArray2->add(i); } if (fixArray1->getSize() == 100 && fixArray2->getSize() == 100) reportSuccess(); else reportFailure(); } void Test_FixedIndexArray::test2() { currentTestCase = 2; log("Testing: erase()"); for (unsigned int i = 0; i < 500; i++) { fixArray1->add(i); fixArray2->add(i); } for (unsigned int i = 0; i < 250; i++) { fixArray1->erase(2*i); fixArray2->erase(2*i); } if (fixArray1->getSize() != 250 || fixArray2->getSize() != 250) reportFailure(); for (unsigned int i = 0; i < 50; i++) { fixArray1->add(i); fixArray2->add(i); } if (fixArray1->getSize() == 300 || fixArray2->getSize() == 300) reportSuccess(); else reportFailure(); } void Test_FixedIndexArray::test3() { currentTestCase = 3; log("Testing: get()"); for (unsigned int i = 100; i < 205; i++) { fixArray1->add(i); fixArray2->add(i); } for (unsigned int i = 0; i < 100; i++) { if (fixArray1->get(i) != i+100 || fixArray2->get(i) != i+100) { std::string message1 = "Error: Incorrect values received."; std::string message2 = "(Array1) Correct: " + std::to_string(i+100) + " - Got: " + std::to_string(fixArray1->get(i)); std::string message3 = "(Array2) Correct: " + std::to_string(i+100) + " - Got: " + std::to_string(fixArray2->get(i)); log(message1); log(message2); log(message3); reportFailure(); return; } } for (unsigned int i = 0; i < 50; i++) { fixArray1->erase(2*i); fixArray2->erase(2*i); } for (unsigned int i = 0; i < 50; i++) { if (fixArray1->get(2*i+1) != 2*i+101 || fixArray2->get(2*i+1) != 2*i+101) { std::string message1 = "Error: Incorrect values received."; std::string message2 = "(Array1) Correct: " + std::to_string(2*i+101) + " - Got: " + std::to_string(fixArray1->get(2*i+1)); std::string message3 = "(Array2) Correct: " + std::to_string(2*i+101) + " - Got: " + std::to_string(fixArray2->get(2*i+1)); log(message1); log(message2); log(message3); reportFailure(); return; } } reportSuccess(); } void Test_FixedIndexArray::test4() { currentTestCase = 4; log("Testing: getCapacity()"); if (fixArray1->getCapacity() != 100 || fixArray2->getCapacity() != 3) { reportFailure(); return; } for (unsigned int i = 0; i < 100; i++) { fixArray1->add(i); } for (unsigned int i = 0; i < 3; i++) { fixArray2->add(i); } if (fixArray1->getCapacity() != 100 || fixArray2->getCapacity() != 3) { reportFailure(); return; } for (unsigned int i = 0; i < 100; i++) { fixArray1->erase(i); } for (unsigned int i = 0; i < 3; i++) { fixArray2->erase(i); } for (unsigned int i = 0; i < 100; i++) { fixArray1->add(i); } for (unsigned int i = 0; i < 3; i++) { fixArray2->add(i); } if (fixArray1->getCapacity() != 100 || fixArray2->getCapacity() != 3) { reportFailure(); return; } fixArray1->add(99); fixArray2->add(99); if (fixArray1->getCapacity() != 200 || fixArray2->getCapacity() != 6) reportFailure(); else reportSuccess(); } void Test_FixedIndexArray::startTests() { init(); test1(); cleanUp(); init(); test2(); cleanUp(); init(); test3(); cleanUp(); init(); test4(); cleanUp(); } void Test_FixedIndexArray::init() { fixArray1 = new FixedIndexArray(); fixArray2 = new FixedIndexArray(3); } void Test_FixedIndexArray::cleanUp() { delete(fixArray1); delete(fixArray2); } Test_FixedIndexArray::Test_FixedIndexArray(TestLogger * const logger) : UnitTest(logger) { unit = "FixedIndexArray"; testCaseCount = 4; }
#include "test_fixedindexarray.h" #include "utils/fixedindexarray.h" void Test_FixedIndexArray::test1() { currentTestCase = 1; log("Testing: add() and getSize()"); for (unsigned int i = 50; i < 150; i++) { fixArray1->add(i); fixArray2->add(i); } if (fixArray1->getSize() == 100 && fixArray2->getSize() == 100) reportSuccess(); else reportFailure(); } void Test_FixedIndexArray::test2() { currentTestCase = 2; log("Testing: erase()"); for (unsigned int i = 0; i < 500;
void Test_FixedIndexArray::test3() { currentTestCase = 3; log("Testing: get()"); for (unsigned int i = 100; i < 205; i++) { fixArray1->add(i); fixArray2->add(i); } for (unsigned int i = 0; i < 100; i++) { if (fixArray1->get(i) != i+100 || fixArray2->get(i) != i+100) { std::string message1 = "Error: Incorrect values received."; std::string message2 = "(Array1) Correct: " + std::to_string(i+100) + " - Got: " + std::to_string(fixArray1->get(i)); std::string message3 = "(Array2) Correct: " + std::to_string(i+100) + " - Got: " + std::to_string(fixArray2->get(i)); log(message1); log(message2); log(message3); reportFailure(); return; } } for (unsigned int i = 0; i < 50; i++) { fixArray1->erase(2*i); fixArray2->erase(2*i); } for (unsigned int i = 0; i < 50; i++) { if (fixArray1->get(2*i+1) != 2*i+101 || fixArray2->get(2*i+1) != 2*i+101) { std::string message1 = "Error: Incorrect values received."; std::string message2 = "(Array1) Correct: " + std::to_string(2*i+101) + " - Got: " + std::to_string(fixArray1->get(2*i+1)); std::string message3 = "(Array2) Correct: " + std::to_string(2*i+101) + " - Got: " + std::to_string(fixArray2->get(2*i+1)); log(message1); log(message2); log(message3); reportFailure(); return; } } reportSuccess(); } void Test_FixedIndexArray::test4() { currentTestCase = 4; log("Testing: getCapacity()"); if (fixArray1->getCapacity() != 100 || fixArray2->getCapacity() != 3) { reportFailure(); return; } for (unsigned int i = 0; i < 100; i++) { fixArray1->add(i); } for (unsigned int i = 0; i < 3; i++) { fixArray2->add(i); } if (fixArray1->getCapacity() != 100 || fixArray2->getCapacity() != 3) { reportFailure(); return; } for (unsigned int i = 0; i < 100; i++) { fixArray1->erase(i); } for (unsigned int i = 0; i < 3; i++) { fixArray2->erase(i); } for (unsigned int i = 0; i < 100; i++) { fixArray1->add(i); } for (unsigned int i = 0; i < 3; i++) { fixArray2->add(i); } if (fixArray1->getCapacity() != 100 || fixArray2->getCapacity() != 3) { reportFailure(); return; } fixArray1->add(99); fixArray2->add(99); if (fixArray1->getCapacity() != 200 || fixArray2->getCapacity() != 6) reportFailure(); else reportSuccess(); } void Test_FixedIndexArray::startTests() { init(); test1(); cleanUp(); init(); test2(); cleanUp(); init(); test3(); cleanUp(); init(); test4(); cleanUp(); } void Test_FixedIndexArray::init() { fixArray1 = new FixedIndexArray(); fixArray2 = new FixedIndexArray(3); } void Test_FixedIndexArray::cleanUp() { delete(fixArray1); delete(fixArray2); } Test_FixedIndexArray::Test_FixedIndexArray(TestLogger * const logger) : UnitTest(logger) { unit = "FixedIndexArray"; testCaseCount = 4; }
i++) { fixArray1->add(i); fixArray2->add(i); } for (unsigned int i = 0; i < 250; i++) { fixArray1->erase(2*i); fixArray2->erase(2*i); } if (fixArray1->getSize() != 250 || fixArray2->getSize() != 250) reportFailure(); for (unsigned int i = 0; i < 50; i++) { fixArray1->add(i); fixArray2->add(i); } if (fixArray1->getSize() == 300 || fixArray2->getSize() == 300) reportSuccess(); else reportFailure(); }
function_block-function_prefixed
[ { "content": "#include \"fixedindexarray.h\"\n\n#include <stdexcept>\n\n#include <cassert>\n\n\n\nusing std::list;\n\n\n\n/**\n\n * @brief Vergrößert das Array um stepSize (Standard: 100)\n\n */\n\nvoid FixedIndexArray::appendStepSize() {\n\n // unusedPosition anpassen\n\n for (unsigned int i = 0; i < stepSize; i++) {\n\n unusedPositions.push_back(i + capacity);\n\n }\n\n\n\n // Array anpassen\n\n unsigned int* newArray = new unsigned int[capacity + stepSize];\n\n bool* newArrayUsage = new bool[capacity + stepSize];\n\n\n\n if (initialized) {\n", "file_path": "src/utils/fixedindexarray.cpp", "rank": 2, "score": 17.757315147329557 }, { "content": "#include \"engineeffectsystem.h\"\n\n#include \"graphics/lightsystem.h\"\n\n#include \"sound/soundsystem.h\"\n\n\n\n\n\n/**\n\n * @copydoc GameSystem::update\n\n * Schaltet Effekte bei Bedarf für alle Komponenten ein/aus\n\n */\n\nvoid EngineEffectSystem::update(float dt) {\n\n GameSystem::update(dt);\n\n\n\n if (disableEngines) {\n\n for (unsigned int i = 0; i < componentList.size(); i++) {\n\n componentList[i].pause();\n\n }\n\n\n\n disableEngines = false;\n\n } else if (resumeEngines) {\n\n for (unsigned int i = 0; i < componentList.size(); i++) {\n", "file_path": "src/ship/engineeffectsystem.cpp", "rank": 3, "score": 17.09079385019328 }, { "content": "#include \"shieldsystem.h\"\n\n#include \"sound/soundsystem.h\"\n\n#include \"graphics/lightsystem.h\"\n\n\n\n/**\n\n * @copydoc GameSystem::update\n\n * Aktualisiert Komponenten.h\n\n */\n\nvoid ShieldSystem::update(float dt) {\n\n GameSystem::update(dt);\n\n\n\n for (unsigned int i = 0; i < componentList.size(); i++) {\n\n componentList[i].tick(dt);\n\n }\n\n}\n\n\n\nvoid ShieldSystem::notify(EventMessage* message) {\n\n delete message;;\n\n}\n\n\n", "file_path": "src/ship/shieldsystem.cpp", "rank": 4, "score": 16.79782097114544 }, { "content": "\n\n void storeComponentRegistration(unsigned int componentId, Event event,\n\n unsigned int listenerId, EventManager* manager);\n\n\n\n void storeSystemRegistration(unsigned int componentId, Event event,\n\n EventManager* manager);\n\n\n\n void eraseComponentRegistration(unsigned int componentId, Event event,\n\n unsigned int listenerId, EventManager* manager);\n\n\n\n void eraseComponentRegistrations(unsigned int listenerId);\n\n\n\n void eraseSystemRegistration(unsigned int componentId, Event event, EventManager* manager);\n\n\n\n void eraseSystemRegistrations();\n\n\n\n void signalDeletion(unsigned int componentId, EventManager* manager);\n\n\n\n void sendMessage(EventMessage* message);\n\n void deployMessages();\n\n void discardMessages();\n\n EventManager(ISystem * receivingSystem);\n\n virtual ~EventManager();\n\n};\n\n\n\n\n\n\n\n#endif // EVENTMANAGER_H\n", "file_path": "src/events/eventmanager.h", "rank": 6, "score": 16.37032891928308 }, { "content": " virtual void eraseComponent(unsigned int id);\n\n\n\n unsigned int getCount();\n\n\n\n // Messaging Abstraktionen für Components\n\n virtual void registerComponentAsListener(unsigned int componentId, Event event,\n\n unsigned int listenerId,EventManager* listenerManager);\n\n\n\n virtual void registerSystemAsListener(unsigned int componentId, Event event,\n\n EventManager* listenerManager);\n\n\n\n virtual void deregisterComponentAsListener(unsigned int componentId, Event event,\n\n unsigned int listenerId, EventManager* listenerManager);\n\n\n\n virtual void deregisterSystemAsListener(unsigned int componentId, Event event,\n\n EventManager* listenerManager);\n\n\n\n virtual void eraseComponentRegistration(unsigned int componentId, Event event,\n\n unsigned int listenerId, EventManager* manager);\n\n\n", "file_path": "src/base/gamesystem.h", "rank": 7, "score": 16.344942093647646 }, { "content": " virtual void deregisterComponentAsListener(unsigned int componentId, Event event,\n\n unsigned int listenerId, EventManager* manager) = 0;\n\n virtual void deregisterSystemAsListener(unsigned int componentId, Event event,\n\n EventManager* manager) = 0;\n\n virtual void eraseComponentRegistration(unsigned int componentId, Event event,\n\n unsigned int listenerId, EventManager* manager) = 0;\n\n\n\n virtual void eraseSystemRegistration(unsigned int componentId, Event event, EventManager* manager) = 0;\n\n virtual void notifyComponent(EventMessage* message) = 0;\n\n virtual void notify(EventMessage* message) = 0;\n\n virtual EventManager* getEventManager() = 0;\n\n\n\n virtual ~ISystem() {}\n\n};\n\n\n\n#endif // ISYSTEM_H\n", "file_path": "src/base/isystem.h", "rank": 9, "score": 15.77617615695025 }, { "content": "#include \"helper_gamesystem_1.h\"\n\n\n\nvoid Helper_GameSystem_1::setSendingMessage(unsigned int id, std::string text) {\n\n componentList[indices[id]].sendingMessage = text;\n\n}\n\n\n\n\n\nstd::string Helper_GameSystem_1::getSendingMessage(unsigned int id) {\n\n return componentList[indices[id]].sendingMessage;\n\n}\n\n\n\n\n\nstd::string Helper_GameSystem_1::getReceivedMessage(unsigned int id) {\n\n return componentList[indices[id]].receivedMessage;\n\n}\n\n\n\n\n\nstd::string Helper_GameSystem_1::getReceivedMessage() {\n\n return receivedMessage;\n\n}\n", "file_path": "src/tests/helper_gamesystem_1.cpp", "rank": 10, "score": 15.508515966835294 }, { "content": "#include \"ammosystem.h\"\n\n#include \"physics/physicssystem.h\"\n\n#include \"graphics/graphicssystem.h\"\n\n#include \"graphics/lightsystem.h\"\n\n#include \"camera/camerashakesystem.h\"\n\n#include \"sound/soundsystem.h\"\n\n\n\n/**\n\n * @brief Projektile für eine Komponente neu erstellen\n\n * @param index Der Index der Komponente\n\n */\n\nvoid AmmoSystem::createComponentProjectiles(unsigned int index) {\n\n AmmoSettings settings = componentList[index].settings;\n\n float maxProjectileLifetime = settings.range / settings.velocity;\n\n unsigned int vectorSize = settings.rateOfFire * maxProjectileLifetime + 1;\n\n componentList[index].idleProjectiles.reserve(vectorSize);\n\n componentList[index].activeProjectiles.reserve(vectorSize);\n\n componentList[index].maxProjectileLifetime = maxProjectileLifetime;\n\n componentList[index].firingGap = 1.f / settings.rateOfFire;\n\n\n", "file_path": "src/ship/ammosystem.cpp", "rank": 11, "score": 15.197413830937185 }, { "content": "#include \"energysystem.h\"\n\n\n\nvoid EnergySystem::update(float dt) {\n\n GameSystem::update(dt);\n\n\n\n for (unsigned int i = 0; i < componentList.size(); i++) {\n\n componentList[i].tick(dt);\n\n }\n\n}\n\n\n\nHandle* EnergySystem::createComponent(EnergySettings settings) {\n\n return GameSystem::createComponent(settings);\n\n}\n\n\n\nEnergySystem::EnergySystem() {\n\n\n\n}\n", "file_path": "src/ship/energysystem.cpp", "rank": 13, "score": 14.631184989052846 }, { "content": "#include \"eventmanager.h\"\n\n#include \"base/gamesystem.h\"\n\n#include <utility>\n\n\n\n\n\n/*\n\n * @brief Registriert einen Listener bei einer Komponente\n\n * @param componentId Die Id der Komponente, wo der Listener registriert werden soll\n\n * @param event Das Event, unter dem der Listener benachricht werden soll\n\n * @param listenerId Die Id des Listeners\n\n * @param manager Der EventManager des Listeners\n\n *\n\n * Diese Methode leitet den Aufruf lediglich an das GameSystem der Komponente weiter.\n\n */\n\n/*\n\nvoid EventManager::registerListener(unsigned int componentId, Event event,\n\n unsigned int listenerId, EventManager* manager) {\n\n receivingSystem->registerListener(componentId, event, listenerId, manager);\n\n}\n\n*/\n", "file_path": "src/events/eventmanager.cpp", "rank": 14, "score": 14.580785203712706 }, { "content": "#include \"shopsystem.h\"\n\n#include <SFML/Graphics/RenderWindow.hpp>\n\n#include \"graphics/graphicssystem.h\"\n\n#include \"input/inputsystem.h\"\n\n#include \"sound/soundsystem.h\"\n\n#include \"gamelogic/rewardsystem.h\"\n\n#include \"ship/shipsystem.h\"\n\n\n\n/**\n\n * @brief Zeichnet das Auswahlmenü einer Komponente\n\n * @param index Der Index der Komponente\n\n */\n\nvoid ShopSystem::drawMainMenu(unsigned int index) {\n\n //for (size_t i = 0; i < componentList[index].mainBackgrounds.)\n\n for (auto& shape : componentList[index].mainBackgrounds) {\n\n window->draw(shape);\n\n }\n\n\n\n for (auto& text : componentList[index].mainTexts) {\n\n window->draw(text);\n", "file_path": "src/gamelogic/shopsystem.cpp", "rank": 15, "score": 14.536636333253961 }, { "content": " Handle* selectSoundHandle = nullptr;\n\n Handle* enterSoundHandle = nullptr;\n\n Handle* openSoundHandle = nullptr;\n\n Handle* closeSoundHandle = nullptr;\n\n Handle* errorSoundHandle = nullptr;\n\n Menu activeMenu = Menu::NoMenu;\n\n std::vector<int> highscores;\n\n float outlineThickness = 2.f, scale = 1.f;\n\n unsigned int menuPointHeight = 40, menuPointWidth = 400;\n\n int mainIndex = 0, shipIndex = 0;\n\n int slotIndices[3];\n\n bool fullscreen = false;\n\n std::string weapons[4];\n\n\n\n void createMenu();\n\n void resize();\n\n void reposition();\n\n void setMainPointPosition(sf::Text& text, sf::RectangleShape& shape, unsigned int index);\n\n void setShipPointPosition(sf::Text& text, sf::RectangleShape& shape, unsigned int index);\n\n void playSound(std::string filename);\n", "file_path": "src/gui/mainmenusystem.h", "rank": 16, "score": 14.454068658351735 }, { "content": "#include \"test_gamesystem.h\"\n\n#include \"helper_gamesystem_1.h\"\n\n#include \"helper_component_1.h\"\n\n\n\ntypedef Helper_Settings_1 HSettings;\n\n\n\n/**\n\n * @brief Konvertiert ein Integer-Array in einen String\n\n * @param array Das Array\n\n * @param length Die Länge des Arrays\n\n */\n\nstd::string Test_GameSystem::arrayToString(int* array, unsigned int length) {\n\n std::string text = \"|\";\n\n for (unsigned int i = 0; i < length; i++) {\n\n text += std::to_string(array[i]) + \"|\";\n\n }\n\n return text;\n\n}\n\n\n\n/**\n", "file_path": "src/tests/test_gamesystem.cpp", "rank": 17, "score": 14.253024203607342 }, { "content": "\n\nsf::RenderTexture& LightSystem::getLightMap() {\n\n return lightMap;\n\n}\n\n\n\n/**\n\n * @copydoc GameSystem::update\n\n * Aktualisiert Komponenten. Löscht abgeklungene Lichter.\n\n */\n\nvoid LightSystem::update(float dt) {\n\n GameSystem::update(dt);\n\n\n\n processCreationQueue();\n\n lightMap.clear();\n\n lightMap.setView(cameraView);\n\n sf::RenderStates renderState(sf::BlendAdd);\n\n\n\n int deleted = 0;\n\n for (unsigned int i = 0; i < componentList.size(); i++) {\n\n LightSettings& settings = componentList[i].getSettings();\n", "file_path": "src/graphics/lightsystem.cpp", "rank": 19, "score": 13.625199052451904 }, { "content": " Handle* closeSoundHandle = nullptr;\n\n float scale = 1.f, fontSize = 20;\n\n int shield = 0, hull = 0, energy = 0;\n\n bool statusOpen = false, weaponsOpen = false;\n\n\n\n void reposition();\n\n void setTexts();\n\n void setStatusTextPosition(sf::Text& text, unsigned int index);\n\n void setWeaponTextPosition(sf::Text& text, unsigned int index);\n\n sf::Text createText(float fontSize);\n\n void drawStatusMenu();\n\n void drawWeaponMenu();\n\n void playOpenSound();\n\n void playCloseSound();\n\npublic:\n\n void setShipSettings(ShipSettings settings);\n\n virtual void update(float dt);\n\n virtual void notify(EventMessage *message);\n\n StatusInformationSystem(sf::RenderWindow* window, SoundSystem& soundSystem);\n\n};\n\n\n\n#endif // STATUSINFORMATIONSYSTEM_H\n", "file_path": "src/gui/statusinformationsystem.h", "rank": 20, "score": 13.523062204024008 }, { "content": " capacity += stepSize;\n\n}\n\n\n\n\n\nbool FixedIndexArray::isUsed(unsigned int index) {\n\n return (index < capacity && arrayUsage[index] == true);\n\n}\n\n\n\n\n\n/**\n\n * @brief Fügt ein neues Element zum Array hinzu.\n\n * Vergrößert das Array, falls nötig.\n\n *\n\n * @param value Wert des Elements\n\n * @return Index des Elements\n\n *\n\n */\n\nunsigned int FixedIndexArray::add(unsigned int value) {\n\n if (size == capacity) {\n\n appendStepSize();\n", "file_path": "src/utils/fixedindexarray.cpp", "rank": 22, "score": 13.38175687729412 }, { "content": "#include \"graphicssystem.h\"\n\n#include \"graphics/textures.h\"\n\n#include \"exceptions/fileopenerror.h\"\n\n#include <cstdlib>\n\n\n\n// DEBUG\n\n#include <iostream>\n\n\n\nconst int initWindowWidth = 1200;\n\nconst int initWindowHeight = 800;\n\n\n\n/**\n\n * @brief Ermittelt die Frames pro Sekunde und zeigt sie im Fenstertitel an\n\n */\n\nvoid GraphicsSystem::displayFPS(float dt) {\n\n timeElapsed += dt;\n\n\n\n if( timeElapsed >= 1000.f) {\n\n fps = frameCount;\n\n frameCount = 0;\n", "file_path": "src/graphics/graphicssystem.cpp", "rank": 23, "score": 13.290826277011355 }, { "content": " }\n\n\n\n ///////////////////////////////////////////////////////////////////////\n\n // Internal parsing functions\n\n\n\n // Parse BOM, if any\n\n template<int Flags>\n\n void parse_bom(Ch *&text)\n\n {\n\n // UTF-8?\n\n if (static_cast<unsigned char>(text[0]) == 0xEF &&\n\n static_cast<unsigned char>(text[1]) == 0xBB &&\n\n static_cast<unsigned char>(text[2]) == 0xBF)\n\n {\n\n text += 3; // Skup utf-8 bom\n\n }\n\n }\n\n\n\n // Parse XML declaration (<?xml...)\n\n template<int Flags>\n", "file_path": "src/rapidxml/rapidxml.hpp", "rank": 24, "score": 13.17681705499427 }, { "content": "#include \"teleportsystem.h\"\n\n#include \"sound/soundsystem.h\"\n\n#include \"graphics/lightsystem.h\"\n\n\n\nvoid TeleportSystem::update(float dt) {\n\n GameSystem::update(dt);\n\n\n\n for (unsigned int i = 0; i < componentList.size(); i++) {\n\n componentList[i].tick(dt);\n\n }\n\n}\n\n\n\nHandle* TeleportSystem::createComponent(Settings settings) {\n\n Handle* handle = GameSystem::createComponent(settings);\n\n SoundSettings soundSettings;\n\n soundSettings.filename = \"teleport.wav\";\n\n soundSettings.volume = 100;\n\n Handle* soundHandle = soundSystem.createComponent(soundSettings);\n\n soundSettings.filename = \"menu_error.wav\";\n\n Handle* errorSoundHandle = soundSystem.createComponent(soundSettings);\n", "file_path": "src/gamelogic/teleportsystem.cpp", "rank": 25, "score": 13.131116439833985 }, { "content": "#include \"camerasystem.h\"\n\n#include <SFML/Graphics/RenderWindow.hpp>\n\n#include \"graphics/textures.h\"\n\n#include \"camera/camerashakesystem.h\"\n\n\n\nconst int initWindowWidth = 1200;\n\nconst int initWindowHeight = 800;\n\n\n\n/**\n\n * @brief Zoomt heran/heraus\n\n * @param scroll Der Zoom-Faktor. Relativ zum derzeitigen Faktor.\n\n */\n\nvoid CameraSystem::zoom(float scroll) {\n\n if (scroll < 0) {\n\n playerView.zoom(1.05f);\n\n cursor.scale(1.05f, 1.05f);\n\n scrollFactor *= 1.05f;\n\n mousePos.x *= 1.05f;\n\n mousePos.y *= 1.05f;\n\n } else if (scroll > 0) {\n", "file_path": "src/camera/camerasystem.cpp", "rank": 26, "score": 12.819403509886655 }, { "content": "\n\n\n\nvoid Helper_GameSystem_1::resetReceivedMessage(unsigned int id) {\n\n componentList[indices[id]].receivedMessage = \"\";\n\n}\n\n\n\n\n\nvoid Helper_GameSystem_1::resetReceivedMessage() {\n\n receivedMessage = \"\";\n\n}\n\n\n\n\n\n/**\n\n * @brief Gibt die EventListenerMap einer Komponente zurück\n\n * @param id Die ID der Komponente\n\n * @return Die EventListenerMap\n\n */\n\nstd::map<Event, std::vector<Listener>>\n\n Helper_GameSystem_1::getComponentEventListenerMap(unsigned int id){\n\n\n", "file_path": "src/tests/helper_gamesystem_1.cpp", "rank": 27, "score": 12.683709267057006 }, { "content": " }\n\n\n\n delete[] componentNumbers;\n\n\n\n for (unsigned int i = 0; i < length/2; i++)\n\n delete handles[i*2 + 1];\n\n\n\n reportSuccess();\n\n}\n\n\n\n\n\nvoid Test_GameSystem::startTests() {\n\n init();\n\n test1();\n\n cleanUp();\n\n}\n\n\n\n\n\nvoid Test_GameSystem::init() {\n\n system = new Helper_GameSystem_1();\n", "file_path": "src/tests/test_gamesystem.cpp", "rank": 28, "score": 12.63591947630983 }, { "content": "\n\n editLock.unlock();\n\n return handle;\n\n}\n\n\n\nvoid AmmoSystem::eraseComponent(unsigned int id) {\n\n editLock.lock();\n\n std::vector<Projectile*> idleProjectiles = getComponent(id)->idleProjectiles;\n\n std::vector<Projectile*> activeProjectiles = getComponent(id)->activeProjectiles;\n\n Handle* soundHandle = getComponent(id)->soundHandle;\n\n Handle* cameraShakeHandle = getComponent(id)->cameraShakeHandle;\n\n editLock.unlock();\n\n\n\n for (unsigned int i = idleProjectiles.size() - 1; i != static_cast<unsigned>(-1); --i) {\n\n delete idleProjectiles[i];\n\n }\n\n\n\n for (unsigned int i = activeProjectiles.size() - 1; i != static_cast<unsigned>(-1); --i) {\n\n delete activeProjectiles[i];\n\n }\n", "file_path": "src/ship/ammosystem.cpp", "rank": 29, "score": 12.589647251344381 }, { "content": " virtual int getId();\n\n virtual std::map<Event, std::vector<Listener>>* getEventListenerMap();\n\n virtual void setGameSystem(ISystem* gameSystem);\n\n virtual void setHandle(Handle* handle);\n\n /*\n\n * Messaging\n\n */\n\n virtual void notify(EventMessage* message);\n\n virtual void notifyListeners(EventMessage * message);\n\n virtual void registerComponentAsListener(Event event, unsigned int listenerId, EventManager* manager);\n\n virtual void registerSystemAsListener(Event event, EventManager* manager);\n\n virtual void deregisterComponentAsListener(Event event, unsigned int listenerId, EventManager* manager);\n\n virtual void deregisterSystemAsListener(Event event, EventManager* manager);\n\n\n\n /*\n\n * Component muss wegen der std::mutex mapEditLock wieder \"copy-/moveable\" gemacht werden\n\n * Credits: http://stackoverflow.com/a/24273106\n\n */\n\n Component(Component&& other) noexcept;\n\n Component(const Component& other);\n\n Component& operator = (Component&& other) noexcept;\n\n Component& operator = (const Component& other);\n\n\n\n Component(Settings settings, Handle* handle);\n\n virtual ~Component() noexcept {}\n\n};\n\n\n\n#endif\n", "file_path": "src/base/component.h", "rank": 30, "score": 12.451756743933984 }, { "content": " Handle * getWeaponHandle(unsigned int shipId);\n\n virtual void update(float dt);\n\n virtual void notify(EventMessage *message);\n\n virtual Handle* createComponent(ShipSettings& settings);\n\n virtual void eraseComponent(unsigned int id);\n\n ShipSystem(PhysicsSystem& physicsSystem, GraphicsSystem& graphicsSystem,\n\n ModelDisplaySystem& modelDisplaySystem, WeaponSystem& weaponSystem,\n\n TagSystem& tagSystem, ShieldSystem& shieldSystem, EnergySystem& energySystem,\n\n ExplosionSystem& explosionSystem, RewardSystem& rewardSystem,\n\n EngineEffectSystem& engineEffectSystem);\n\n};\n\n\n\n#endif // SHIPSYSTEM_H\n", "file_path": "src/ship/shipsystem.h", "rank": 31, "score": 12.31072447449498 }, { "content": " virtual void eraseSystemRegistration(unsigned int componentId, Event event, EventManager* manager);\n\n\n\n virtual void notifyComponent(EventMessage* message);\n\n\n\n virtual void notify(EventMessage* message);\n\n\n\n virtual EventManager* getEventManager();\n\n\n\n virtual void discardMessages();\n\n\n\n GameSystem();\n\n virtual ~GameSystem();\n\n};\n\n\n\n#endif // SYSTEM_H\n", "file_path": "src/base/gamesystem.h", "rank": 32, "score": 12.307602837768503 }, { "content": " } else if (size > capacity) {\n\n throw std::out_of_range(\"Impossible\");\n\n }\n\n\n\n unsigned int index = unusedPositions.front();\n\n array[index] = value;\n\n arrayUsage[index] = true;\n\n unusedPositions.pop_front();\n\n size += 1;\n\n return index;\n\n}\n\n\n\n\n\n/**\n\n * @brief Entfernt ein Element. Verkleinert nicht das Array.\n\n *\n\n * @param index Der Index des zu entfernenden Elements\n\n */\n\nvoid FixedIndexArray::erase(unsigned int index) {\n\n if ((index + 1) > capacity)\n", "file_path": "src/utils/fixedindexarray.cpp", "rank": 33, "score": 12.234476093215605 }, { "content": " * @brief Erstellt mehrere sf::RectangleShapes aus einem b2ChainShape\n\n * @param shape Das b2PolygonShape\n\n */\n\nvoid ModelComponent::addShape(b2ChainShape *shape) {\n\n int count = shape->GetChildCount();\n\n for (int i = 0; i < count; i++) {\n\n b2EdgeShape * edge = new b2EdgeShape;\n\n shape->GetChildEdge(edge, i);\n\n addShape(edge);\n\n }\n\n}\n\n\n\n\n\n/**\n\n * @copydoc Component::notify\n\n * - ::evMove Aktualisiert die Position\n\n * - ::cmActivate Macht die Shapes sichtbar\n\n * - ::cmDeactivate Macht die Shapes unsichtbar\n\n */\n\nvoid ModelComponent::notify(EventMessage* message) {\n", "file_path": "src/debug/modelcomponent.cpp", "rank": 34, "score": 11.990988795651399 }, { "content": "#include \"inputsystem.h\"\n\n#include <SFML/Window/Keyboard.hpp>\n\n#include <SFML/Graphics.hpp>\n\n#include \"base/settings.h\"\n\n\n\n\n\n/**\n\n * @brief Aktuelle mauskoordinaten in EventMouseMessage setzen\n\n * @param message Die Nachricht\n\n * @param x X-Position (SFML-Koordinaten)\n\n * @param y Y-Position (SFML-Koordinaten)\n\n */\n\nvoid InputSystem::enterMouseCoordinates(EventMouseMessage *message, int x, int y) {\n\n //message->x = x;\n\n //message->y = y;\n\n message->sfScreenPos.Set(x,y);\n\n //message->relX = ((float)x)/windowWidth;\n\n //message->relY = ((float)y)/windowHeight;\n\n message->sfRelScreenPos.Set(((float)x)/windowWidth, ((float)y)/windowHeight);\n\n}\n", "file_path": "src/input/inputsystem.cpp", "rank": 35, "score": 11.697308089008903 }, { "content": " EventCameraMessage* cameraMessage = (EventCameraMessage*) message;\n\n break;\n\n }\n\n }\n\n delete message;;\n\n}\n\n\n\nvoid SoundSystem::eraseComponent(unsigned int id) {\n\n GameSystem::eraseComponent(id);\n\n}\n\n\n\nSoundSystem::SoundSystem() {\n\n\n\n}\n", "file_path": "src/sound/soundsystem.cpp", "rank": 36, "score": 11.682818478566746 }, { "content": " // Index und Id festlegen\n\n unsigned int index = componentList.size();\n\n unsigned int id = indices.add(index);\n\n Handle* handle = new Handle(id, this);\n\n\n\n // Hinzufügen\n\n //componentList.emplace_back(T(settings, handle->id));\n\n componentList.emplace_back(T(settings, handle));\n\n componentList.back().setGameSystem(this);\n\n componentList.back().setHandle(handle);\n\n editLock.unlock();\n\n\n\n return handle;\n\n}\n\n\n\n\n\n/**\n\n * @brief Löscht eine Komponente anhand ihrere ID\n\n *\n\n * @param id Die ID der zu löschenden Komponente\n", "file_path": "src/base/gamesystem.cpp", "rank": 37, "score": 11.431434318516326 }, { "content": "#include \"stardustsystem.h\"\n\n#include <SFML/Graphics/RenderWindow.hpp>\n\n\n\n/**\n\n * @brief Spalte rechts auf die linke Seite verschieben\n\n */\n\nvoid StarDustSystem::moveColumnLeft() {\n\n sf::VertexArray* temp;\n\n\n\n for (int row = 0; row < 3; row++) {\n\n temp = particles[row][2];\n\n sf::VertexArray* test0 = particles[row][0];\n\n sf::VertexArray* test1 = particles[row][1];\n\n sf::VertexArray* test2 = particles[row][2];\n\n\n\n for (int col = 2; col != 0; col--) {\n\n particles[row][col] = particles[row][col - 1];\n\n }\n\n\n\n particles[row][0] = temp;\n", "file_path": "src/graphics/stardustsystem.cpp", "rank": 38, "score": 11.359855974341336 }, { "content": "}\n\n\n\n/**\n\n * @brief Highscore hinzufügen\n\n * @param highscore Der Punktestand\n\n */\n\nvoid HighScoreLoader::addHighScore(int highscore) {\n\n highscores.push_back(highscore);\n\n std::sort(highscores.rbegin(), highscores.rend());\n\n saveToFile(\"highscores.txt\");\n\n}\n\n\n\nstd::vector<int> HighScoreLoader::getHighScores() {\n\n return highscores;\n\n}\n\n\n\nHighScoreLoader::HighScoreLoader() {\n\n loadFile(\"highscores.txt\");\n\n}\n", "file_path": "src/utils/highscoreloader.cpp", "rank": 39, "score": 11.21964213666018 }, { "content": " * @brief Allen Koordinaten der Partikel eines Blocks einen Vektor addieren\n\n * @param row Zeile\n\n * @param col Spalte\n\n * @param offset Zu addierender Vektor\n\n */\n\nvoid StarDustSystem::addOffset(int row, int col, sf::Vector2f offset) {\n\n for (int k = 0; k < particles[row][col]->getVertexCount(); k++) {\n\n (*particles[row][col])[k].position += offset;\n\n }\n\n}\n\n\n\n/**\n\n * @brief Alle Blöcke neu ausrichten\n\n */\n\nvoid StarDustSystem::rearrangeParticles() {\n\n area.left = cameraView.getCenter().x - cameraView.getSize().x * 1.5f;\n\n area.top = cameraView.getCenter().y - cameraView.getSize().y * 1.5f;\n\n area.width = cameraView.getSize().x * 3;\n\n area.height = cameraView.getSize().y * 3;\n\n int offsetX = area.left;\n", "file_path": "src/graphics/stardustsystem.cpp", "rank": 40, "score": 11.097823587419992 }, { "content": "int RewardSystem::getCreditStatus() {\n\n return credits;\n\n}\n\n\n\n/**\n\n * @copydoc GameSystem::update\n\n *\n\n * Überprüft, ob Spieler Credits eingesammelt hat und löscht alle Komponenten,\n\n * falls das Gebiet gewechselt wurde.\n\n */\n\nvoid RewardSystem::update(float dt) {\n\n GameSystem::update(dt);\n\n\n\n if (areaChanged) {\n\n for (unsigned int i = 0; i < componentList.size(); i++) {\n\n if (componentList[i].alive) {\n\n eraseComponent(componentList[i].getId());\n\n }\n\n }\n\n areaChanged = false;\n", "file_path": "src/gamelogic/rewardsystem.cpp", "rank": 41, "score": 10.842743509138188 }, { "content": " {\n\n static unsigned char test(Ch ch)\n\n {\n\n if (Quote == Ch('\\''))\n\n return internal::lookup_tables<0>::lookup_attribute_data_1_pure[static_cast<unsigned char>(ch)];\n\n if (Quote == Ch('\\\"'))\n\n return internal::lookup_tables<0>::lookup_attribute_data_2_pure[static_cast<unsigned char>(ch)];\n\n return 0; // Should never be executed, to avoid warnings on Comeau\n\n }\n\n };\n\n\n\n // Insert coded character, using UTF8 or 8-bit ASCII\n\n template<int Flags>\n\n static void insert_coded_character(Ch *&text, unsigned long code)\n\n {\n\n if (Flags & parse_no_utf8)\n\n {\n\n // Insert 8-bit ASCII character\n\n // Todo: possibly verify that code is less than 256 and use replacement char otherwise?\n\n text[0] = static_cast<unsigned char>(code);\n", "file_path": "src/rapidxml/rapidxml.hpp", "rank": 42, "score": 10.777124756643278 }, { "content": "\n\n/*\n\n * @brief Gibt eine Liste der benutzten IDs zurück\n\n * @return Liste der benutzten IDs\n\n */\n\n/*\n\nstd::list<unsigned int> FixedIndexArray::getUsedPositions() {\n\n std::list<unsigned int> usedPositions;\n\n unusedPositions.sort();\n\n std::list<unsigned int>::iterator it = unusedPositions.begin();\n\n for (unsigned int i = 0; i < capacity; i++) {\n\n if (it != unusedPositions.end() && (*it) == i)\n\n it++;\n\n else\n\n usedPositions.push_back(i);\n\n }\n\n} */\n\n\n\n\n\n/**\n", "file_path": "src/utils/fixedindexarray.cpp", "rank": 43, "score": 10.660840574084215 }, { "content": "\n\n return array;\n\n}\n\n\n\n\n\nvoid Helper_GameSystem_1::update(float dt) {\n\n GameSystem::update(dt);\n\n\n\n EventTestMessage* message = new EventTestMessage();\n\n\n\n for (unsigned int i = 0; i < componentList.size(); i++) {\n\n message->text = componentList[i].sendingMessage;\n\n componentList[i].notifyListeners(message);\n\n }\n\n\n\n delete message;\n\n GameSystem::update(dt);\n\n}\n\n\n\n\n", "file_path": "src/tests/helper_gamesystem_1.cpp", "rank": 44, "score": 10.641635310098726 }, { "content": "void ShopSystem::update(float dt) {\n\n GameSystem::update(dt);\n\n int credits = rewardSystem.getCreditStatus();\n\n\n\n for (unsigned int i = 0; i < componentList.size(); i++) {\n\n b2Vec2 v = componentList[i].settings.pos;\n\n v -= playerPos;\n\n float distance = v.Length();\n\n\n\n if (componentList[i].isOpen()) {\n\n sendUpgradeMessages(i);\n\n componentList[i].setCredits(credits);\n\n\n\n if (distance > 40) {\n\n componentList[i].close();\n\n } else {\n\n drawMainMenu(i);\n\n\n\n if (componentList[i].isSubMenuOpen()) {\n\n drawSubMenu(i);\n", "file_path": "src/gamelogic/shopsystem.cpp", "rank": 45, "score": 10.611310789221264 }, { "content": " for (unsigned int i = 0; i < componentList.size(); i++) {\n\n if (componentList[i].visible) {\n\n for (auto &polygon : componentList[i].polygons) {\n\n window->draw(polygon);\n\n }\n\n\n\n for (auto &circle : componentList[i].circles) {\n\n window->draw(circle);\n\n }\n\n\n\n for (auto &rect : componentList[i].lines) {\n\n window->draw(rect);\n\n }\n\n }\n\n }\n\n }\n\n}\n\n\n\nvoid ModelDisplaySystem::notify(EventMessage * message) {\n\n switch (message->event) {\n", "file_path": "src/debug/modeldisplaysystem.cpp", "rank": 46, "score": 10.569178801601325 }, { "content": " GameSystem::update(dt);\n\n\n\n for (unsigned int i = 0; i < componentList.size(); i++) {\n\n if (componentList[i].tick(dt)) {\n\n eraseComponent(componentList[i].getId());\n\n }\n\n }\n\n}\n\n\n\nvoid ExplosionSystem::eraseComponent(unsigned int id) {\n\n if (indices.isUsed(id)) {\n\n editLock.lock();\n\n Handle* shakeHandle = getComponent(id)->shakeHandle;\n\n editLock.unlock();\n\n\n\n delete shakeHandle;\n\n\n\n GameSystem::eraseComponent(id);\n\n }\n\n}\n\n\n\nExplosionSystem::ExplosionSystem(LightSystem& lightSystem, SoundSystem& soundSystem,\n\n CameraShakeSystem& cameraShakeSystem)\n\n : lightSystem(lightSystem), soundSystem(soundSystem), cameraShakeSystem(cameraShakeSystem) {\n\n}\n", "file_path": "src/ship/explosionsystem.cpp", "rank": 47, "score": 10.502475984433524 }, { "content": "\n\nvoid AmmoSystem::update(float dt) {\n\n GameSystem::update(dt);\n\n\n\n for (unsigned int i = 0; i < componentList.size(); i++) {\n\n if (componentList[i].settings.active) {\n\n if (componentList[i].requiresNewSize) {\n\n createComponentProjectiles(i);\n\n componentList[i].requiresNewSize = false;\n\n }\n\n\n\n componentList[i].tick(dt);\n\n\n\n if (componentList[i].isFiring()) {\n\n componentList[i].fire(dt);\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/ship/ammosystem.cpp", "rank": 48, "score": 10.497702300688799 }, { "content": "unsigned int GameSystem<T, S>::getCount() {\n\n return componentList.size();\n\n}\n\n\n\n\n\n/**\n\n * @brief Registriert einen Listener (andere Komponente) bei einer Komponente\n\n * @param componentId Die Id der Komponente, wo der Listener registriert werden soll\n\n * @param event Das Event, unter dem der Listener benachricht werden soll\n\n * @param listenerId Die Id des Listeners\n\n * @param manager Der EventManager des Listeners\n\n *\n\n * Diese Methode leitet den Aufruf lediglich an die Komponente weiter.\n\n */\n\ntemplate <typename T, typename S>\n\nvoid GameSystem<T, S>::registerComponentAsListener(unsigned int componentId, Event event,\n\n unsigned int listenerId, EventManager* listenerManager) {\n\n editLock.lock();\n\n componentList[indices.get(componentId)].registerComponentAsListener(event, listenerId, listenerManager);\n\n // Achtung: Wird nicht beim eigenen EventManager aufgerufen!\n", "file_path": "src/base/gamesystem.cpp", "rank": 49, "score": 10.463983033381377 }, { "content": "#include \"physicssystem.h\"\n\n\n\n\n\nb2World* PhysicsSystem::getWorld() {\n\n return world;\n\n}\n\n\n\n/**\n\n * @brief Body einer Komponente zurückgeben\n\n * @param id Die ID der Komponente\n\n * @return Der Body\n\n */\n\nb2Body *PhysicsSystem::getBody(unsigned int id) {\n\n editLock.lock();\n\n b2Body* body = componentList[indices.get(id)].body;\n\n editLock.unlock();\n\n return body;\n\n}\n\n\n\n\n", "file_path": "src/physics/physicssystem.cpp", "rank": 50, "score": 10.386726776745409 }, { "content": "\n\n\n\nEventManager::~EventManager() {\n\n for (unsigned int i = 0; i < messagesB.size(); i++) {\n\n delete(messagesB.at(i));\n\n }\n\n\n\n for (unsigned int i = 0; i < messagesA.size(); i++) {\n\n delete(messagesA.at(i));\n\n }\n\n}\n", "file_path": "src/events/eventmanager.cpp", "rank": 51, "score": 10.344615918838503 }, { "content": " }\n\n}\n\n\n\n/**\n\n * @brief Zeichnet das Slotmenü einer Komponente\n\n * @param index Der Index der Komponente\n\n */\n\nvoid ShopSystem::drawSubMenu(unsigned int index) {\n\n for (auto& shape : componentList[index].subBackgrounds) {\n\n window->draw(shape);\n\n }\n\n\n\n for (auto& text : componentList[index].subTexts) {\n\n window->draw(text);\n\n }\n\n}\n\n\n\n\n\n/**\n\n * @brief Verschickt die cmUpgrade-Messages einer Komponente\n", "file_path": "src/gamelogic/shopsystem.cpp", "rank": 52, "score": 10.154346780571355 }, { "content": " */\n\nvoid SoundSystem::update(float dt) {\n\n GameSystem::update(dt);\n\n\n\n for (unsigned int i = 0; i < componentList.size(); i++) {\n\n if (componentList[i].singlePlayBack && componentList[i].tick(dt)) {\n\n eraseComponent(componentList[i].getId());\n\n }\n\n }\n\n}\n\n\n\nHandle* SoundSystem::createComponent(SoundSettings settings) {\n\n Handle* handle = GameSystem::createComponent(settings);\n\n getComponent(handle->id)->sound.setBuffer(Sounds::get(settings.filename));\n\n return handle;\n\n}\n\n\n\nvoid SoundSystem::notify(EventMessage* message) {\n\n switch (message->event) {\n\n case evCameraChanged: {\n", "file_path": "src/sound/soundsystem.cpp", "rank": 53, "score": 9.961194196855573 }, { "content": " Handle* handle = componentList[indices.get(shipId)].modelHandle;\n\n editLock.unlock();\n\n return handle;\n\n}\n\n\n\n/**\n\n * @copydoc GameSystem::update\n\n * Explosionen erstellen\n\n */\n\nvoid ShipSystem::update(float dt) {\n\n GameSystem::update(dt);\n\n\n\n /*\n\n * Update explosions\n\n */\n\n for (unsigned int i = 0; i < componentList.size(); i++) {\n\n if (componentList[i].settings.active && componentList[i].exploding) {\n\n\n\n /*\n\n * Zufällig Explosionen spawnen. Wahrscheinlichkeit für Explosion wird höher\n", "file_path": "src/ship/shipsystem.cpp", "rank": 54, "score": 9.95890711383694 }, { "content": "\n\n editLock.lock();\n\n registrations.push_back(record);\n\n editLock.unlock();\n\n}\n\n\n\n\n\n/**\n\n * @brief Löscht eine gespeicherte Registrierung (Komponente). Meldet die eigene Komponente\n\n * beim fremden EventManager ab.\n\n * @param componentId Die Id der Komponente beim fremden GameSystem\n\n * @param event Das Event, unter der der Listener registriert wurde\n\n * @param listenerId Die Id der eigenen Komponente, die als Listener registriert wurde\n\n * @param manager Der fremde EventManager, der für die Komponente mit\n\n * componentId zuständig ist.\n\n *\n\n * Löscht nur eine einzelne Registrierung.\n\n */\n\nvoid EventManager::eraseComponentRegistration(unsigned int componentId, Event event,\n\n unsigned int listenerId, EventManager* manager) {\n", "file_path": "src/events/eventmanager.cpp", "rank": 55, "score": 9.927401441381978 }, { "content": " throw std::out_of_range(\"Index is out of range. Index: \" + std::to_string(index)\n\n + \" , Capacity: \" + std::to_string(capacity));\n\n\n\n array[index] = 0;\n\n assert (arrayUsage[index] == true);\n\n arrayUsage[index] = false;\n\n size -= 1;\n\n // WTF\n\n /*\n\n typename list<unsigned int>::iterator it = unusedPositions.begin();\n\n typename list<unsigned int>::iterator end = unusedPositions.end();\n\n\n\n for (typename list<unsigned int>::iterator it = unusedPositions.begin();\n\n it != end; it++) {\n\n\n\n assert(index != *it);\n\n\n\n if (index < *it) {\n\n unusedPositions.erase(it);\n\n return;\n", "file_path": "src/utils/fixedindexarray.cpp", "rank": 56, "score": 9.855661473872654 }, { "content": " void setMainIndex(int index);\n\n void setShipIndex(int index);\n\n void enter();\n\n void cancel();\n\n virtual Handle* createComponent(Settings settings);\n\npublic:\n\n void setOpen(bool value);\n\n bool isOpen();\n\n virtual void update(float dt);\n\n virtual void notify(EventMessage *message);\n\n MainMenuSystem(sf::RenderWindow* window, SoundSystem& soundSystem, AreaSystem& areaSystem,\n\n HighScoreLoader& highScoreLoader);\n\n};\n\n\n\n#endif // MAINMENUSYSTEM_H\n", "file_path": "src/gui/mainmenusystem.h", "rank": 57, "score": 9.682717548497532 }, { "content": "\n\n/**\n\n * @brief Benachrichtigt eine Komponente über das Eintreten eines Event\n\n * @param message Die EventMessage, die der Komponente geschickt werden soll\n\n *\n\n * Diese Methode schickt den Aufruf lediglich in eine Queue, die möglicherweise nicht\n\n * unmittelbar verarbeitet wird.\n\n */\n\nvoid EventManager::sendMessage(EventMessage * message) {\n\n receivingMessages->push_back(message);\n\n}\n\n\n\n/**\n\n * @brief Verteilt die Nachrichten an die Komponenten des GameSystem\n\n */\n\nvoid EventManager::deployMessages() {\n\n std::swap(receivingMessages, workingMessages);\n\n\n\n for (unsigned int i = 0; i < workingMessages->size(); i++) {\n\n if (workingMessages->at(i)->gameSystemListener) {\n", "file_path": "src/events/eventmanager.cpp", "rank": 58, "score": 9.671338554832076 }, { "content": "\n\n\n\nvoid PhysicsSystem::eraseComponent(unsigned int id) {\n\n editLock.lock();\n\n world->DestroyBody(componentList[indices.get(id)].body);\n\n editLock.unlock();\n\n GameSystem::eraseComponent(id);\n\n}\n\n\n\n\n\nHandle* PhysicsSystem::createComponent(PhysicsSettings settings) {\n\n settings.world = this->getWorld();\n\n return GameSystem::createComponent(settings);\n\n}\n\n\n\n\n\nPhysicsSystem::PhysicsSystem() : gravity(0.0f, 0.0f), world(new b2World(gravity)), GameSystem() {\n\n\n\n}\n\n/*\n", "file_path": "src/physics/physicssystem.cpp", "rank": 59, "score": 9.64937296756931 }, { "content": "\n\n/**\n\n * @brief Gibt die Anzahl der (benutzten) Elemente zurück.\n\n *\n\n * @return Anzahl der benutzten Elemente\n\n */\n\nunsigned int FixedIndexArray::getSize() {\n\n return size;\n\n}\n\n\n\n/**\n\n * @brief Gibt die Kapazität zurück.\n\n *\n\n * @return Mögliche Kapazität\n\n */\n\nunsigned int FixedIndexArray::getCapacity() {\n\n return capacity;\n\n}\n\n\n\n\n", "file_path": "src/utils/fixedindexarray.cpp", "rank": 60, "score": 9.540760302797157 }, { "content": "\n\n for (unsigned int i = 0; i < componentList.size(); i++) {\n\n componentList[i].tick(dt);\n\n\n\n if (componentList[i].isShaking()) {\n\n totalOffset += componentList[i].getOffset() * scale;\n\n }\n\n }\n\n}\n\n\n\n/**\n\n * @copydoc GameSystem::notify\n\n * - ::evCameraChanged Aktualisiert den Zoom-Faktor\n\n */\n\nvoid CameraShakeSystem::notify(EventMessage* message) {\n\n switch (message->event) {\n\n case evCameraChanged: {\n\n EventCameraMessage* cameraMessage = (EventCameraMessage*) message;\n\n scale = cameraMessage->scale;\n\n break;\n", "file_path": "src/camera/camerashakesystem.cpp", "rank": 61, "score": 9.530880727588723 }, { "content": " * @brief Testet createComponent(), eraseComponent(), getCount(), update()\n\n *\n\n * Testet, ob Komponenten richtig in das Array eingefügt, gelöscht und verschoben werden.\n\n */\n\nvoid Test_GameSystem::test1() {\n\n currentTestCase = 1;\n\n log(\"Testing: createComponent(), eraseComponent(), getCount(), update()\");\n\n HSettings settings;\n\n\n\n log (\"Adding Components\");\n\n for (unsigned int i = 0; i < length; i++) {\n\n settings.number = -i;\n\n handles[i] = system->createComponent(settings);\n\n }\n\n\n\n if (system->getCount() != length) {\n\n reportFailure();\n\n return;\n\n }\n\n\n", "file_path": "src/tests/test_gamesystem.cpp", "rank": 62, "score": 9.530880727588723 }, { "content": "}\n\n\n\n/**\n\n * @copydoc GameSystem::update\n\n *\n\n * Aktualisiert alle Komponenten. Aktualisiert alle 500ms die Zustände. Zeichnet Debug-Information\n\n */\n\nvoid AISystem::update(float dt) {\n\n GameSystem::update(dt);\n\n\n\n stateUpdateThreshold += dt;\n\n bool inCombat = false;\n\n\n\n if (playerSet) {\n\n if (stateUpdateThreshold >= STATE_UPDATE_INTERVAL) {\n\n for (unsigned int i = 0; i < componentList.size(); i++) {\n\n componentList[i].setPlayerPos(playerPos, playerVel);\n\n componentList[i].updateState();\n\n componentList[i].update();\n\n\n", "file_path": "src/gamelogic/aisystem.cpp", "rank": 63, "score": 9.4152633042927 }, { "content": " return *(getComponent(id)->getEventListenerMap());\n\n}\n\n\n\n\n\n/**\n\n * @brief Gibt ein Array mit den jeweiligen \"settings.number\"-Werten der Komponenten zurück\n\n * @param expectedLength die erwartete Länge des Arrays\n\n * @return Das Array\n\n *\n\n * Wird für den GameSystem-Unittest benutzt\n\n */\n\nint* Helper_GameSystem_1::getComponentArray(unsigned int expectedLength) {\n\n //if (expectedLength != componentList.size())\n\n // return nullptr;\n\n\n\n int* array = new int[expectedLength];\n\n\n\n for (unsigned int i = 0; i < expectedLength; i++) {\n\n array[i] = componentList[i].settings.number;\n\n }\n", "file_path": "src/tests/helper_gamesystem_1.cpp", "rank": 64, "score": 9.411071872165717 }, { "content": "#include \"unittest.h\"\n\n#include \"testlogger.h\"\n\n\n\nvoid UnitTest::log(std::string text) {\n\n logger->log(unit, currentTestCase, text);\n\n}\n\n\n\nvoid UnitTest::reportSuccess() {\n\n logger->reportSuccess(unit, currentTestCase);\n\n}\n\n\n\n\n\nvoid UnitTest::reportSuccess(std::string text) {\n\n logger->reportSuccess(unit, currentTestCase, text);\n\n}\n\n\n\n\n\nvoid UnitTest::reportFailure() {\n\n logger->reportFailure(unit, currentTestCase);\n\n}\n", "file_path": "src/tests/unittest.cpp", "rank": 65, "score": 9.39690871150431 }, { "content": " * @param index Der Index der Komponente\n\n */\n\nvoid ShopSystem::sendUpgradeMessages(unsigned int index) {\n\n if (playerAlive) {\n\n for (int i = 0; i < componentList[index].playerMessages.size(); i++) {\n\n EventMessage* playerMessage = componentList[index].playerMessages[i];\n\n playerMessage->receiverId = playerHandle->id;\n\n //EventUpgradeMessage* informationMessage = (EventUpgradeMessage*)\n\n // MessageCloner::cloneMessage(componentList[index].upgradeMessages[i]);\n\n //informationMessage->gameSystemListener = true;\n\n shipSystem.getEventManager()->sendMessage(playerMessage);\n\n }\n\n componentList[index].playerMessages.clear();\n\n }\n\n}\n\n\n\n/**\n\n * @copydoc GameSystem::update\n\n * Aktualisiert Komponenten\n\n */\n", "file_path": "src/gamelogic/shopsystem.cpp", "rank": 66, "score": 9.367678198077783 }, { "content": "#include <SFML/Graphics.hpp>\n\n\n\n#include \"modeldisplaysystem.h\"\n\n\n\n\n\n\n\nvoid ModelDisplaySystem::setDisplay(bool value) {\n\n display = value;\n\n}\n\n\n\n\n\n/**\n\n * @copydoc GameSystem::update\n\n *\n\n * Zeichnet jedes ModelDisplayComponent.\n\n */\n\nvoid ModelDisplaySystem::update(float dt) {\n\n GameSystem::update(dt);\n\n\n\n if (display) {\n", "file_path": "src/debug/modeldisplaysystem.cpp", "rank": 67, "score": 9.350107750844273 }, { "content": " weaponSystem.getEventManager());\n\n }\n\n}\n\n\n\nHandle * ShipSystem::getGraphicsHandle(unsigned int shipId) {\n\n editLock.lock();\n\n Handle* handle = componentList[indices.get(shipId)].graphicsHandle;\n\n editLock.unlock();\n\n return handle;\n\n}\n\n\n\nHandle * ShipSystem::getPhysicsHandle(unsigned int shipId) {\n\n editLock.lock();\n\n Handle* handle = componentList[indices.get(shipId)].physicsHandle;\n\n editLock.unlock();\n\n return handle;\n\n}\n\n\n\nHandle * ShipSystem::getModelHandle(unsigned int shipId) {\n\n editLock.lock();\n", "file_path": "src/ship/shipsystem.cpp", "rank": 68, "score": 9.327157672314355 }, { "content": " * @param rad Box2D-Winkel im Bogenmaß\n\n * @return SFML-Winkel im Winkelmaß\n\n */\n\nfloat ModelComponent::b2AngleToSfAngle(float rad) {\n\n return (rad + M_PI)*180/M_PI;\n\n}\n\n\n\n\n\n/**\n\n * @brief Erstellt ein sf::ConvexShape aus einem b2PolygonShape\n\n * @param shape Das b2PolygonShape\n\n */\n\nvoid ModelComponent::addShape(b2PolygonShape *shape) {\n\n sf::ConvexShape polygon;\n\n polygon.setFillColor(fillColor);\n\n int count = shape->GetVertexCount();\n\n polygon.setPointCount(count);\n\n for (int i = 0; i < count; i++) {\n\n b2Vec2 vertex = shape->GetVertex(i);\n\n polygon.setPoint(i, sf::Vector2f(vertex.x*30*(-1), vertex.y*30 * (-1)));\n", "file_path": "src/debug/modelcomponent.cpp", "rank": 69, "score": 9.296693261876687 }, { "content": "}\n\n\n\nvoid EngineEffectSystem::eraseComponent(unsigned int id) {\n\n if (indices.isUsed(id)) {\n\n editLock.lock();\n\n Handle* soundHandle = getComponent(id)->soundHandle;\n\n Handle* lightHandle = getComponent(id)->lightHandle;\n\n editLock.unlock();\n\n\n\n delete soundHandle;\n\n delete lightHandle;\n\n\n\n GameSystem::eraseComponent(id);\n\n }\n\n}\n\n\n\nEngineEffectSystem::EngineEffectSystem(LightSystem& lightSystem, SoundSystem& soundSystem)\n\n : lightSystem(lightSystem), soundSystem(soundSystem) {\n\n\n\n}\n", "file_path": "src/ship/engineeffectsystem.cpp", "rank": 70, "score": 9.084650455218735 }, { "content": " for (unsigned int i = 0; i < capacity; i++) {\n\n newArray[i] = array[i];\n\n newArrayUsage[i] = arrayUsage[i];\n\n }\n\n\n\n for (unsigned int i = capacity; i < capacity + stepSize; i++) {\n\n newArray[i] = 0;\n\n newArrayUsage[i] = false;\n\n }\n\n\n\n delete[] array;\n\n delete[] arrayUsage;\n\n array = newArray;\n\n arrayUsage = newArrayUsage;\n\n } else {\n\n array = newArray;\n\n arrayUsage = newArrayUsage;\n\n initialized = true;\n\n }\n\n\n", "file_path": "src/utils/fixedindexarray.cpp", "rank": 71, "score": 9.08400378835568 }, { "content": " */\n\ntemplate <typename T, typename S>\n\nvoid GameSystem<T, S>::eraseSystemRegistration(unsigned int componentId, Event event, EventManager* manager) {\n\n this->manager.eraseSystemRegistration(componentId, event, manager);\n\n}\n\n\n\n\n\n/**\n\n * @brief Benachrichtigt eine Komponente über das Eintreten eines Event\n\n * @param message Die EventMessage, die der Komponente geschickt werden soll\n\n *\n\n * Diese Methode leitet den Aufruf lediglich an die Komponente weiter.\n\n */\n\ntemplate <typename T, typename S>\n\nvoid GameSystem<T, S>::notifyComponent(EventMessage * message) {\n\n if (indices.isUsed(message->receiverId)) {\n\n componentList[indices.get(message->receiverId)].notify(message);\n\n }\n\n\n\n //editLock.unlock();\n", "file_path": "src/base/gamesystem.cpp", "rank": 72, "score": 9.058024152989217 }, { "content": "\n\n/**\n\n * @brief Speichert die Registrierung von einer eigenen Komponente\n\n * @param componentId Die Id der Komponente beim fremden GameSystem\n\n * @param event Das Event, unter der der Listener registriert wurde\n\n * @param listenerId Die Id der eigenen Komponente, die als Listener registriert wurde\n\n * @param manager Der fremde EventManager, der für die Komponente mit\n\n * componentId zuständig ist.\n\n *\n\n * Die Speicherung der Registrierung erfolgt, damit beim Löschen der eigenen\n\n * Komponente, die bei einer fremden Komponente als Listener eingetragen ist,\n\n * auch dort abgemeldet werden kann und diese fremde Komponente keine unnötigen\n\n * Nachrichten mehr abschickt.\n\n */\n\nvoid EventManager::storeComponentRegistration(unsigned int componentId, Event event,\n\n unsigned int listenerId, EventManager* manager) {\n\n RegistrationRecord record(componentId, event, listenerId, manager);\n\n\n\n editLock.lock();\n\n registrations.push_back(record);\n", "file_path": "src/events/eventmanager.cpp", "rank": 73, "score": 8.950894367165287 }, { "content": " for (int i = 0; i < 3; i++) {\n\n for (int j = 0; j < 3; j++) {\n\n size_t newSize = window->getSize().x * window->getSize().y * density;\n\n particles[i][j]->resize(newSize);\n\n }\n\n }\n\n\n\n rearrangeParticles();\n\n}\n\n\n\n/**\n\n * @brief Alle Partikel zeichnen\n\n */\n\nvoid StarDustSystem::draw() {\n\n for (int i = 0; i < 3; i++) {\n\n for (int j = 0; j < 3; j++) {\n\n size_t count = particles[i][j]->getVertexCount();\n\n sf::Vector2f test[count];\n\n for (int k = 0; k < count; k++) {\n\n test[k] = (*particles[i][j])[k].position;\n", "file_path": "src/graphics/stardustsystem.cpp", "rank": 74, "score": 8.94720535741152 }, { "content": "\n\n/**\n\n* @brief Leitet den Aufruf zum Abmelden des Listeners (Komponente) an das GameSystem weiter.\n\n* @param componentId Die Id der Komponente, wo der Listener entfernt werden soll\n\n* @param event Das Event, unter dem der Listener registriert ist\n\n* @param listenerId Die Id des Listeners\n\n* @param manager der EventManager des Listeners\n\n* @warning Diese Methode nicht direkt aufrufen, da die Registrierung beim EventManager\n\n* des Listeners (d.h. nicht hier) noch zusätzlich gespeichert ist.\n\n* Eine solche veraltete bzw. fehlerhafte Registrierung kann zu einem\n\n* Segmentation Fault führen.\n\n* Stattdessen sollte GameSystem::eraseComponentRegistration()\n\n* oder EventManager::eraseComponentRegistration() benutzt werden.\n\n*/\n\n\n\nvoid EventManager::deregisterComponentAsListener(unsigned int componentId, Event event,\n\n unsigned int listenerId, EventManager* manager) {\n\n receivingSystem->deregisterComponentAsListener(componentId, event, listenerId, manager);\n\n}\n\n\n", "file_path": "src/events/eventmanager.cpp", "rank": 75, "score": 8.91962758951831 }, { "content": " * Alle Registrierungen mit den passenden Werten entfernen\n\n */\n\n registrations.remove_if( [&](RegistrationRecord & element) {\n\n return element.isEqual(record);\n\n });\n\n\n\n editLock.unlock();\n\n}\n\n\n\n\n\n/**\n\n * @brief Löscht alle Registrierungen der eigenen Komponente. Meldet die eigene\n\n * Komponente bei allen eingetragenen EventManagern ab.\n\n * @param listenerId Die Id der eigenen Komponente, die als Listener registriert wurde\n\n *\n\n * Nach Aufruf wird keine EventMessage mehr an diese Komponente geschickt.\n\n */\n\nvoid EventManager::eraseComponentRegistrations(unsigned int listenerId) {\n\n editLock.lock();\n\n\n", "file_path": "src/events/eventmanager.cpp", "rank": 77, "score": 8.876846079266805 }, { "content": "#include \"weaponsystem.h\"\n\n#include <Box2D/Box2D.h>\n\n#include \"physics/physicssystem.h\"\n\n#include \"graphics/graphicssystem.h\"\n\n#include \"debug/modelsettings.h\"\n\n#include \"debug/modeldisplaysystem.h\"\n\n#include \"ship/ammosystem.h\"\n\n#include \"ship/weaponloader.h\"\n\n\n\nvoid WeaponSystem::update(float dt) {\n\n GameSystem::update(dt);\n\n}\n\n\n\nHandle *WeaponSystem::createComponent(Weapon weapon, Handle* shipPhysicsHandle) {\n\n\n\n WeaponSettings settings;\n\n\n\n if (weapon.gunName == \"plasma\") {\n\n settings = WeaponLoader::plasma;\n\n } else if (weapon.gunName == \"neutron\") {\n", "file_path": "src/ship/weaponsystem.cpp", "rank": 78, "score": 8.86775318890449 }, { "content": "#include \"highscoreloader.h\"\n\n#include <iostream>\n\n#include <fstream>\n\n#include <algorithm>\n\n\n\n\n\n/**\n\n * @brief Lädt Highscore-Datei\n\n * @param filename Dateiname\n\n */\n\nvoid HighScoreLoader::loadFile(std::string filename) {\n\n std::string line;\n\n std::ifstream file(filename);\n\n\n\n if (file.is_open() ) {\n\n while ( std::getline(file, line)) {\n\n try {\n\n highscores.push_back(std::stoi(line));\n\n } catch (std::exception e) {\n\n\n", "file_path": "src/utils/highscoreloader.cpp", "rank": 79, "score": 8.805224200422028 }, { "content": " log(\"Erasing Components\");\n\n\n\n for (unsigned int i = 0; i < length/2; i++)\n\n delete handles[i*2];\n\n\n\n system->update(5.f);\n\n\n\n if (system->getCount() != length/2) {\n\n reportFailure();\n\n return;\n\n }\n\n\n\n int* componentNumbers = system->getComponentArray(length);\n\n\n\n // Stellen 0, 2, 4\n\n for (int i = 0; i < 5; i += 2) {\n\n if (componentNumbers[i] != (-10+1+i)) {\n\n reportFailure(\"Expected component mismatch\");\n\n log(\"Array: \" + arrayToString(componentNumbers, 10));\n\n return;\n", "file_path": "src/tests/test_gamesystem.cpp", "rank": 80, "score": 8.804214300087171 }, { "content": " titleText.setCharacterSize((unsigned int) menuPointHeight * 2);\n\n /*\n\n * Waffenauswahl-Text\n\n */\n\n shipInfoText.setFont(menuFont);\n\n shipInfoText.setCharacterSize((unsigned int) menuPointHeight);\n\n shipInfoText.setColor(fontColor);\n\n shipInfoText.setString(\"Select your weapons\");\n\n /*\n\n * Highscores\n\n */\n\n highScoreText.setFont(menuFont);\n\n highScoreText.setCharacterSize((unsigned int) menuPointHeight);\n\n highScoreText.setColor(fontColor);\n\n highScoreText.setString(\"\");\n\n /*\n\n * Highscore-Hintergrund\n\n */\n\n highScoreBackground.setFillColor(menuColor);\n\n highScoreBackground.setOutlineColor(sf::Color(255, 255, 255, 150));\n", "file_path": "src/gui/mainmenusystem.cpp", "rank": 81, "score": 8.777990898072979 }, { "content": " }\n\n }*/\n\n\n\n unusedPositions.push_back(index);\n\n}\n\n\n\n/**\n\n * @brief Gibt das Element an der Stelle index zurück.\n\n *\n\n * @param index Der index für das gewünschte Element\n\n * @return Das gewünschte Element\n\n */\n\nunsigned int FixedIndexArray::get(unsigned int index) {\n\n if ((index + 1) > capacity)\n\n throw std::out_of_range(\"Index is out of range. Index: \" + std::to_string(index)\n\n + \" , Capacity: \" + std::to_string(capacity));\n\n else if (arrayUsage[index] == false) {\n\n throw std::out_of_range(\"Id unused\");\n\n }\n\n\n", "file_path": "src/utils/fixedindexarray.cpp", "rank": 82, "score": 8.74159699673503 }, { "content": " sf::Vector2f uShift(1.f / window->getSize().x, 1.f / window->getSize().y);\n\n uShift *= blurFactor / scrollFactor;\n\n lightShader.setParameter(\"uShift\", uShift);\n\n\n\n for (unsigned int layer = 0; layer < LAYER_COUNT; layer++) {\n\n for (unsigned int i = 0; i < componentList.size(); i++) {\n\n if (componentList[i].isVisible(layer)) {\n\n if (componentList[i].usesShader()) {\n\n window->draw(componentList[i].sprite, &lightShader);\n\n } else {\n\n window->draw(componentList[i].sprite);\n\n }\n\n }\n\n }\n\n }\n\n\n\n displayFPS(dt);\n\n}\n\n\n\n\n", "file_path": "src/graphics/graphicssystem.cpp", "rank": 83, "score": 8.74159699673503 }, { "content": " * componentId zuständig ist.\n\n *\n\n * Wird von einer fremden Komponente aufgerufen, wenn sie gelöscht wird.\n\n * Die gespeicherten Registrierungen dieser fremden Komponente können\n\n * anschließend gelöscht werden, da sie keine EventMessage mehr aussenden\n\n * wird.\n\n */\n\nvoid EventManager::signalDeletion(unsigned int componentId, EventManager* manager) {\n\n editLock.lock();\n\n /*\n\n * Alle Registrierungen mit den passenden Werten entfernen\n\n */\n\n registrations.remove_if( [&](RegistrationRecord & element) {\n\n return element.isEqual(componentId, manager, false)\n\n || element.isEqual(componentId, manager, true);\n\n });\n\n editLock.unlock();\n\n}\n\n\n\n\n", "file_path": "src/events/eventmanager.cpp", "rank": 84, "score": 8.727126363297693 }, { "content": " moveRowUp();\n\n sf::Vector2f offset;\n\n offset.x = 0;\n\n offset.y = -cameraView.getSize().y * 3;\n\n\n\n for (int col = 0; col < 3; col++) {\n\n addOffset(0, col, offset);\n\n }\n\n area.top -= cameraView.getSize().y;\n\n } else if (viewport.top + viewport.height > area.top + area.height) {\n\n moveRowDown();\n\n sf::Vector2f offset;\n\n offset.x = 0;\n\n offset.y = cameraView.getSize().y * 3;\n\n\n\n for (int col = 0; col < 3; col++) {\n\n addOffset(2, col, offset);\n\n }\n\n area.top += cameraView.getSize().y;\n\n }\n", "file_path": "src/graphics/stardustsystem.cpp", "rank": 85, "score": 8.725361320018337 }, { "content": " return array[index];\n\n}\n\n\n\n\n\n/**\n\n * @brief Gibt eine Referenz des Elements an der Stelle index zurück.\n\n *\n\n * @param index Der index für das gewünschte Element\n\n * @return Das gewünschte Element\n\n */\n\nunsigned int & FixedIndexArray::operator[] (unsigned int index) {\n\n if ((index + 1) > capacity)\n\n throw std::out_of_range(\"Index is out of range. Index: \" + std::to_string(index)\n\n + \" , Capacity: \" + std::to_string(capacity));\n\n else if (arrayUsage[index] == false) {\n\n throw std::out_of_range(\"Id unused\");\n\n }\n\n\n\n return array[index];\n\n}\n", "file_path": "src/utils/fixedindexarray.cpp", "rank": 86, "score": 8.705138543334932 }, { "content": "#include \"completetest.h\"\n\n#include \"tests/testlogger.h\"\n\n#include \"tests/test_fixedindexarray.h\"\n\n#include \"tests/test_gamesystem.h\"\n\n#include \"tests/test_eventmanager.h\"\n\n/**\n\n * @brief Startet alle Tests\n\n */\n\nvoid CompleteTest::start() {\n\n TestLogger logger;\n\n\n\n Test_FixedIndexArray test1(&logger);\n\n test1.start();\n\n\n\n Test_GameSystem test2(&logger);\n\n test2.start();\n\n\n\n Test_EventManager test3(&logger);\n\n test3.start();\n\n}\n\n\n\nCompleteTest::CompleteTest()\n\n{\n\n\n\n}\n", "file_path": "src/tests/completetest.cpp", "rank": 87, "score": 8.703444393102345 }, { "content": " eraseComponent(componentList[i].getId());\n\n }\n\n }\n\n }\n\n }\n\n\n\n if (drawDebug) {\n\n for (unsigned int i = 0; i < componentList.size(); i++) {\n\n window->draw(componentList[i].stateText);\n\n window->draw(componentList[i].aimText);\n\n window->draw(componentList[i].targetShape);\n\n window->draw(componentList[i].targetLine, 2, sf::Lines);\n\n }\n\n }\n\n\n\n if (aimSettingsChanged) {\n\n for (unsigned int i = 0; i < componentList.size(); i++) {\n\n componentList[i].setSuperiourAim(this->superiourAim);\n\n }\n\n aimSettingsChanged = false;\n", "file_path": "src/gamelogic/aisystem.cpp", "rank": 88, "score": 8.633126429814695 }, { "content": " * Diese Methode sollte benutzt werden, um manuell eine Komponente abzumelden.\n\n * Leitet den Aufruf an den eigenen EventManager weiter. Löscht nur eine einzelne Registrierung.\n\n */\n\ntemplate <typename T, typename S>\n\nvoid GameSystem<T, S>::eraseComponentRegistration(unsigned int componentId, Event event,\n\n unsigned int listenerId, EventManager* manager) {\n\n this->manager.eraseComponentRegistration(componentId, event, listenerId, manager);\n\n}\n\n\n\n\n\n/**\n\n * @brief Löscht eine gespeicherte Listener-Registrierung (GameSystem).\n\n * Meldet das eigene GameSystem beim fremden EventManager ab.\n\n * @param componentId Die Id der Komponente beim fremden GameSystem\n\n * @param event Das Event, unter der der Listener registriert wurde\n\n * @param manager Der fremde EventManager, der für die Komponente mit\n\n * componentId zuständig ist.\n\n *\n\n * Diese Methode sollte benutzt werden, um manuell das GameSystem abzumelden.\n\n * Leitet den Aufruf an den eigenen EventManager weiter. Löscht nur eine einzelne Registrierung.\n", "file_path": "src/base/gamesystem.cpp", "rank": 89, "score": 8.618772341866073 }, { "content": "#include \"rewardsystem.h\"\n\n#include <SFML/Graphics/RenderWindow.hpp>\n\n#include \"graphics/graphicssystem.h\"\n\n#include \"graphics/lightsystem.h\"\n\n#include \"sound/soundsystem.h\"\n\n\n\n\n\n/**\n\n * @brief Spielt Einsammel-Sound\n\n */\n\nvoid RewardSystem::playCollectSound() {\n\n EventSoundMessage* soundMessage = new EventSoundMessage;\n\n soundMessage->file = \"reward.flac\";\n\n soundMessage->receiverId = soundHandle->id;\n\n soundSystem.notifyComponent(soundMessage);\n\n}\n\n\n\n/**\n\n * @brief Gibt derzeitige Credits zurück\n\n */\n", "file_path": "src/gamelogic/rewardsystem.cpp", "rank": 90, "score": 8.54772135702991 }, { "content": "#include \"aisystem.h\"\n\n#include <SFML/Graphics/RenderWindow.hpp>\n\n\n\n/**\n\n * @brief Setzt die verbesserte Zielfähigkeit bei allen Komponenten\n\n * @see AIComponent::setSuperiourAim\n\n */\n\nvoid AISystem::setSuperiourAim(bool superiourAim) {\n\n this->superiourAim = superiourAim;\n\n}\n\n\n\n/**\n\n * @deprecated Ist unbenutzt\n\n */\n\nvoid AISystem::setCombatStatus(bool playerInCombat) {\n\n if (this->playerInCombat != playerInCombat) {\n\n // TODO: Nachricht versenden!\n\n }\n\n\n\n this->playerInCombat = playerInCombat;\n", "file_path": "src/gamelogic/aisystem.cpp", "rank": 91, "score": 8.537958618122431 }, { "content": "/** @file fixedindexarray.h\n\n * @class FixedIndexArray\n\n * @brief Wrapper-Klasse für \"unsigned int\"-Arrays.\n\n * Dabei haben Elemente einen unveränderlichen Index.\n\n */\n\n\n\n#ifndef FIXLENGTHARRAY_H\n\n#define FIXLENGTHARRAY_H\n\n\n\n#include <list>\n\n\n\n\n\n/**\n\n * @class FixedIndexArray\n\n * @brief Dynamisches Array mit \"festen Plätzen\"\n\n *\n\n * Einmal eingefügte Werte verändern nicht ihren Index.\n\n * Wird z.B. der Wert 27 an dem Index 5 eingefügt, behält das Array am Index 5\n\n * den Wert 27 bis diese Stelle mit erase() freigegeben wird, egal ob andere\n\n * Elemente eingefügt oder gelöscht werden.\n\n *\n\n * Das Array erhöht dynamisch seine Kapazität, verringert sie jedoch niemals.\n\n */\n", "file_path": "src/utils/fixedindexarray.h", "rank": 92, "score": 8.52256555479931 }, { "content": " moveColumnLeft();\n\n sf::Vector2f offset;\n\n offset.x = -cameraView.getSize().x * 3;\n\n offset.y = 0;\n\n\n\n for (int row = 0; row < 3; row++) {\n\n addOffset(row, 0, offset);\n\n }\n\n area.left -= cameraView.getSize().x;\n\n } else if (viewport.left + viewport.width > area.left + area.width) {\n\n moveColumnRight();\n\n sf::Vector2f offset;\n\n offset.x = cameraView.getSize().x * 3;\n\n offset.y = 0;\n\n\n\n for (int row = 0; row < 3; row++) {\n\n addOffset(row, 2, offset);\n\n }\n\n area.left += cameraView.getSize().x;\n\n } else if (viewport.top < area.top) {\n", "file_path": "src/graphics/stardustsystem.cpp", "rank": 93, "score": 8.514066826391764 }, { "content": " int offsetY = area.top;\n\n\n\n for (int i = 0; i < 3; i++) {\n\n offsetY = area.top + cameraView.getSize().y * i;\n\n for (int j = 0; j < 3; j++) {\n\n offsetX = area.left + cameraView.getSize().x * j;\n\n for (int k = 0; k < particles[i][j]->getVertexCount(); k++) {\n\n sf::Vector2f pos(rand() % ((int) cameraView.getSize().x) + offsetX,\n\n rand() % ((int) cameraView.getSize().y) + offsetY);\n\n (*particles[i][j])[k].position = pos;\n\n (*particles[i][j])[k].color = sf::Color(255, 255, 255, 255);\n\n }\n\n }\n\n }\n\n}\n\n\n\n/**\n\n * @brief Blöcke erstellen\n\n */\n\nvoid StarDustSystem::createParticles() {\n", "file_path": "src/graphics/stardustsystem.cpp", "rank": 94, "score": 8.502949419637705 }, { "content": "#include \"graphicscomponent.h\"\n\n#include <iostream>\n\n//#include \"settings/graphicssettings.h\"\n\n//#include <SFML/Graphics.hpp>\n\n\n\n#include \"exceptions/fileopenerror.h\"\n\n\n\n\n\n/**\n\n * @copydoc Component::notify\n\n *\n\n * Erkannte Events:\n\n * - ::evMove Position des Sprites. Konvertiert von Box2D-Koordinaten\n\n * - ::cmActivate Macht Sprite sichtbar.\n\n * - ::cmDeactivate Macht Sprite unsichtbar.\n\n */\n\nvoid GraphicsComponent::notify(EventMessage* message) {\n\n switch (message->event) {\n\n case evMove: {\n\n EventPosMessage* posMessage = (EventPosMessage*) message;\n", "file_path": "src/graphics/graphicscomponent.cpp", "rank": 95, "score": 8.487440390778659 }, { "content": " */\n\ntemplate <typename T, typename S>\n\nvoid GameSystem<T, S>::eraseComponent(unsigned int id) {\n\n editLock.lock();\n\n getComponent(id)->getHandle()->alive = false;\n\n std::map<Event, std::vector<Listener>>* eventListenerMap =\n\n componentList[indices.get(id)].getEventListenerMap();\n\n\n\n /*\n\n * Eigenen EventManager Löschung mitteilen.\n\n * Dieser deregistiert dabei die Komponente bei den anderen EventManagern.\n\n */\n\n doNotClean = true;\n\n editLock.unlock();\n\n manager.eraseComponentRegistrations(id);\n\n editLock.lock();\n\n doNotClean = false;\n\n\n\n /*\n\n * EventManager aller Listener die Löschung mitteilen\n", "file_path": "src/base/gamesystem.cpp", "rank": 96, "score": 8.44234383800595 }, { "content": " 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255 // F\n\n };\n\n\n\n // Upper case conversion\n\n template<int Dummy>\n\n const unsigned char lookup_tables<Dummy>::lookup_upcase[256] =\n\n {\n\n // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A B C D E F\n\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, // 0\n\n 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, // 1\n\n 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, // 2\n\n 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, // 3\n\n 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, // 4\n\n 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, // 5\n\n 96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, // 6\n\n 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 123,124,125,126,127, // 7\n\n 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, // 8\n\n 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, // 9\n\n 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175, // A\n\n 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, // B\n", "file_path": "src/rapidxml/rapidxml.hpp", "rank": 97, "score": 8.425091265619276 }, { "content": "\n\n/**\n\n * @brief Erstellt ein Alien-Gebiet\n\n */\n\nvoid AreaSystem::createAlienArea() {\n\n int freighterCount = 1 + rand() % 3 + rand() % (int) level;\n\n b2Vec2 spawnCenter(rand() % 300 - 150, rand() % 300 - 150);\n\n spawnCenter += playerPos;\n\n\n\n ShipSettings shipSettings;\n\n\n\n int score = freighterCount * freighterScore;\n\n level += score * 0.003;\n\n\n\n while (score > 0) {\n\n shipSettings.pos.Set(rand() % 300 - 150, rand() % 300 - 150);\n\n shipSettings.pos += spawnCenter;\n\n shipSettings.rotation = (rand() % ((int)M_PI * 100)) / 100.f;\n\n\n\n int dice = rand() % 10;\n", "file_path": "src/gamelogic/areasystem.cpp", "rank": 98, "score": 8.369701303395951 }, { "content": " }\n\n\n\n };\n\n\n\n //! \\cond internal\n\n namespace internal\n\n {\n\n\n\n // Whitespace (space \\n \\r \\t)\n\n template<int Dummy>\n\n const unsigned char lookup_tables<Dummy>::lookup_whitespace[256] =\n\n {\n\n // 0 1 2 3 4 5 6 7 8 9 A B C D E F\n\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, // 0\n\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1\n\n 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 2\n\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 3\n\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 4\n\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 5\n\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 6\n", "file_path": "src/rapidxml/rapidxml.hpp", "rank": 99, "score": 8.3576199772843 } ]
C++
code/tool/edges-master/piotr_toolbox/matlab/private/dijkstra1.cpp
hyliang96/interpretableCNN_matlab
611e52a1aa25434ab058303c0287634767327da3
#if (_MSC_VER >= 1600) #define __STDC_UTF_16__ typedef unsigned short char16_t; #endif #include "mex.h" #include "fibheap.h" #define DIJKSTRA_CPP class HeapNode : public FibHeapNode { double N; long int IndexV; public: HeapNode() : FibHeapNode() { N = 0; }; virtual void operator =(FibHeapNode& RHS); virtual int operator ==(FibHeapNode& RHS); virtual int operator <(FibHeapNode& RHS); virtual void operator =(double NewKeyVal ); virtual void Print(); double GetKeyValue() { return N; }; void SetKeyValue(double n) { N = n; }; long int GetIndexValue() { return IndexV; }; void SetIndexValue( long int v) { IndexV = v; }; }; void HeapNode::Print() { FibHeapNode::Print(); mexPrintf( "%f (%d)" , N , IndexV ); } void HeapNode::operator =(double NewKeyVal) { HeapNode Tmp; Tmp.N = N = NewKeyVal; FHN_Assign(Tmp); } void HeapNode::operator =(FibHeapNode& RHS) { FHN_Assign(RHS); N = ((HeapNode&) RHS).N; } int HeapNode::operator ==(FibHeapNode& RHS) { if (FHN_Cmp(RHS)) return 0; return N == ((HeapNode&) RHS).N ? 1 : 0; } int HeapNode::operator <(FibHeapNode& RHS) { int X; if ((X=FHN_Cmp(RHS)) != 0) return X < 0 ? 1 : 0; return N < ((HeapNode&) RHS).N ? 1 : 0; }; void dijkstra1( long int n, long int s, double *D1, double *P1, double *Gpr, mwIndex *Gir, mwIndex *Gjc) { int finished; long int i, startInd, endInd, whichNeigh, nDone, closest; double closestD, arcLength, INF, SMALL, oldDist; HeapNode *A, *hnMin, hnTmp; FibHeap *heap; INF=mxGetInf(); SMALL=mxGetEps(); if ((heap = new FibHeap) == NULL || (A = new HeapNode[n+1]) == NULL ) mexErrMsgTxt( "Memory allocation failed-- ABORTING.\n" ); heap->ClearHeapOwnership(); for (i=0; i<n; i++) { if (i!=s) A[ i ] = (double) INF; else A[ i ] = (double) SMALL; if (i!=s) D1[ i ] = (double) INF; else D1[ i ] = (double) SMALL; P1[ i ] = -1; heap->Insert( &A[i] ); A[ i ].SetIndexValue( (long int) i ); } heap->Insert(&hnTmp); heap->ExtractMin(); finished = nDone = 0; while ((finished==0) && (nDone < n)) { hnMin = (HeapNode *) heap->ExtractMin(); closest = hnMin->GetIndexValue(); closestD = hnMin->GetKeyValue(); if ((closest<0) || (closest>=n)) mexErrMsgTxt( "Minimum Index out of bound..." ); D1[ closest ] = closestD; if (closestD == INF) finished=1; else { nDone++; startInd = Gjc[ closest ]; endInd = Gjc[ closest+1 ] - 1; if( startInd!=endInd+1 ) for( i=startInd; i<=endInd; i++ ) { whichNeigh = Gir[ i ]; arcLength = Gpr[ i ]; oldDist = D1[ whichNeigh ]; if ( oldDist > ( closestD + arcLength )) { D1[ whichNeigh ] = closestD + arcLength; P1[ whichNeigh ] = closest + 1; hnTmp = A[ whichNeigh ]; hnTmp.SetKeyValue( closestD + arcLength ); heap->DecreaseKey( &A[ whichNeigh ], hnTmp ); } } } } delete heap; delete[] A; } void dijkstra( long int n, long int nSrc, double *sources, double *D, double *P, const mxArray *G ) { double *Gpr = mxGetPr(G); mwIndex *Gir = mxGetIr(G); mwIndex *Gjc = mxGetJc(G); double *D1 = (double *) mxCalloc( n , sizeof( double )); double *P1 = (double *) mxCalloc( n , sizeof( double )); long int s, i, j; for( i=0; i<nSrc; i++ ) { s = (long int) *( sources + i ) - 1; if (s<0 || s > n-1) mexErrMsgTxt( "Source node(s) out of bound" ); dijkstra1( n, s, D1, P1, Gpr, Gir, Gjc ); for( j=0; j<n; j++ ) { *( D + j*nSrc + i ) = *( D1 + j ); *( P + j*nSrc + i ) = *( P1 + j ); } } } void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { double *D, *P, *sources; long int n, mSrc, nSrc; if (nrhs != 2) mexErrMsgTxt( "Only 2 input arguments allowed." ); if (nlhs > 2) mexErrMsgTxt( "Only 2 output argument allowed." ); n = mxGetN( prhs[0] ); if (mxGetM( prhs[0] ) != n) mexErrMsgTxt( "Input matrix G needs to be square." ); sources = mxGetPr(prhs[1]); mSrc = mxGetM(prhs[1]); nSrc=mxGetN(prhs[1]); if ((mSrc==0) || (nSrc==0) || ((mSrc>1) && (nSrc>1))) mexErrMsgTxt( "Source nodes are specified in vector only" ); if(mSrc>nSrc) nSrc=mSrc; if(mxIsSparse(prhs[0])==0) mexErrMsgTxt( "Distance Matrix must be sparse" ); plhs[0] = mxCreateDoubleMatrix( nSrc, n, mxREAL ); plhs[1] = mxCreateDoubleMatrix( nSrc, n, mxREAL ); D = mxGetPr(plhs[0]); P = mxGetPr(plhs[1]) ; dijkstra( n, nSrc, sources, D, P, prhs[0] ); }
#if (_MSC_VER >= 1600) #define __STDC_UTF_16__ typedef unsigned short char16_t; #endif #include "mex.h" #include "fibheap.h" #define DIJKSTRA_CPP class HeapNode : public FibHeapNode { double N; long int IndexV; public: HeapNode() : FibHeapNode() { N = 0; }; virtual void operator =(FibHeapNode& RHS); virtual int operator ==(FibHeapNode& RHS); virtual int operator <(FibHeapNode& RHS); virtual void operator =(double NewKeyVal ); virtual void Print(); double GetKeyValue() { return N; }; void SetKeyValue(double n) { N = n; }; long int GetIndexValue() { return IndexV; }; void SetIndexValue( long int v) { IndexV = v; }; }; void HeapNode::Print() { FibHeapNode::Print(); mexPrintf( "%f (%d)" , N , IndexV ); } void HeapNode::operator =(double NewKeyVal) { HeapNode Tmp; Tmp.N = N = NewKeyVal; FHN_Assign(Tmp); } void HeapNode::operator =(FibHeapNode& RHS) { FHN_Assign(RHS); N = ((HeapNode&) RHS).N; } int HeapNode::operator ==(FibHeapNode& RHS) { if (FHN_Cmp(RHS)) return 0; return N == ((HeapNode&) RHS).N ? 1 : 0; } int HeapNode::operator <(FibHeapNode& RHS) { int X; if ((X=FHN_Cmp(RHS)) != 0) return X < 0 ? 1 : 0; return N < ((HeapNode&) RHS).N ? 1 : 0; };
void dijkstra( long int n, long int nSrc, double *sources, double *D, double *P, const mxArray *G ) { double *Gpr = mxGetPr(G); mwIndex *Gir = mxGetIr(G); mwIndex *Gjc = mxGetJc(G); double *D1 = (double *) mxCalloc( n , sizeof( double )); double *P1 = (double *) mxCalloc( n , sizeof( double )); long int s, i, j; for( i=0; i<nSrc; i++ ) { s = (long int) *( sources + i ) - 1; if (s<0 || s > n-1) mexErrMsgTxt( "Source node(s) out of bound" ); dijkstra1( n, s, D1, P1, Gpr, Gir, Gjc ); for( j=0; j<n; j++ ) { *( D + j*nSrc + i ) = *( D1 + j ); *( P + j*nSrc + i ) = *( P1 + j ); } } } void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { double *D, *P, *sources; long int n, mSrc, nSrc; if (nrhs != 2) mexErrMsgTxt( "Only 2 input arguments allowed." ); if (nlhs > 2) mexErrMsgTxt( "Only 2 output argument allowed." ); n = mxGetN( prhs[0] ); if (mxGetM( prhs[0] ) != n) mexErrMsgTxt( "Input matrix G needs to be square." ); sources = mxGetPr(prhs[1]); mSrc = mxGetM(prhs[1]); nSrc=mxGetN(prhs[1]); if ((mSrc==0) || (nSrc==0) || ((mSrc>1) && (nSrc>1))) mexErrMsgTxt( "Source nodes are specified in vector only" ); if(mSrc>nSrc) nSrc=mSrc; if(mxIsSparse(prhs[0])==0) mexErrMsgTxt( "Distance Matrix must be sparse" ); plhs[0] = mxCreateDoubleMatrix( nSrc, n, mxREAL ); plhs[1] = mxCreateDoubleMatrix( nSrc, n, mxREAL ); D = mxGetPr(plhs[0]); P = mxGetPr(plhs[1]) ; dijkstra( n, nSrc, sources, D, P, prhs[0] ); }
void dijkstra1( long int n, long int s, double *D1, double *P1, double *Gpr, mwIndex *Gir, mwIndex *Gjc) { int finished; long int i, startInd, endInd, whichNeigh, nDone, closest; double closestD, arcLength, INF, SMALL, oldDist; HeapNode *A, *hnMin, hnTmp; FibHeap *heap; INF=mxGetInf(); SMALL=mxGetEps(); if ((heap = new FibHeap) == NULL || (A = new HeapNode[n+1]) == NULL ) mexErrMsgTxt( "Memory allocation failed-- ABORTING.\n" ); heap->ClearHeapOwnership(); for (i=0; i<n; i++) { if (i!=s) A[ i ] = (double) INF; else A[ i ] = (double) SMALL; if (i!=s) D1[ i ] = (double) INF; else D1[ i ] = (double) SMALL; P1[ i ] = -1; heap->Insert( &A[i] ); A[ i ].SetIndexValue( (long int) i ); } heap->Insert(&hnTmp); heap->ExtractMin(); finished = nDone = 0; while ((finished==0) && (nDone < n)) { hnMin = (HeapNode *) heap->ExtractMin(); closest = hnMin->GetIndexValue(); closestD = hnMin->GetKeyValue(); if ((closest<0) || (closest>=n)) mexErrMsgTxt( "Minimum Index out of bound..." ); D1[ closest ] = closestD; if (closestD == INF) finished=1; else { nDone++; startInd = Gjc[ closest ]; endInd = Gjc[ closest+1 ] - 1; if( startInd!=endInd+1 ) for( i=startInd; i<=endInd; i++ ) { whichNeigh = Gir[ i ]; arcLength = Gpr[ i ]; oldDist = D1[ whichNeigh ]; if ( oldDist > ( closestD + arcLength )) { D1[ whichNeigh ] = closestD + arcLength; P1[ whichNeigh ] = closest + 1; hnTmp = A[ whichNeigh ]; hnTmp.SetKeyValue( closestD + arcLength ); heap->DecreaseKey( &A[ whichNeigh ], hnTmp ); } } } } delete heap; delete[] A; }
function_block-full_function
[ { "content": " class MexContext : public Context\n\n {\n\n public:\n\n MexContext() ;\n\n ~MexContext() ;\n\n\n\n protected:\n\n#if ENABLE_GPU\n\n vl::ErrorCode initGpu() ;\n\n vl::ErrorCode validateGpu() ;\n\n mxArray * canary ; // if it breathes, the GPU state is valid\n\n bool gpuIsInitialized ;\n\n#endif\n\n\n\n friend class MexTensor ;\n\n } ;\n\n\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/datamex.hpp", "rank": 0, "score": 116297.04307711287 }, { "content": " class MexTensor : public Tensor\n\n {\n\n public:\n\n MexTensor(MexContext & context) ;\n\n vl::ErrorCode init(mxArray const * array) ;\n\n vl::ErrorCode init(DeviceType deviceType, DataType dataType, TensorShape const & shape) ;\n\n vl::ErrorCode initWithZeros(DeviceType deviceType, DataType dataType, TensorShape const & shape) ;\n\n vl::ErrorCode initWithValue(DeviceType deviceType, DataType dataType, TensorShape const & shape, double value) ;\n\n\n\n void makePersistent() ;\n\n mxArray * relinquish() ;\n\n void clear() ;\n\n ~MexTensor() ;\n\n\n\n size_t getMemorySize() const ;\n\n\n\n protected:\n\n MexContext & context ;\n\n mxArray const * array ;\n\n#ifdef ENABLE_GPU\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/datamex.hpp", "rank": 1, "score": 116297.04307711287 }, { "content": " class Tensor : public TensorShape\n\n {\n\n public:\n\n Tensor() ;\n\n Tensor(Tensor const &) ;\n\n Tensor(TensorShape const & shape, DataType dataType,\n\n DeviceType deviceType, void * memory, size_t memorySize) ;\n\n void * getMemory() ;\n\n DeviceType getDeviceType() const ;\n\n TensorShape getShape() const ;\n\n DataType getDataType() const ;\n\n operator bool() const ;\n\n bool isNull() const ;\n\n void setMemory(void * x) ;\n\n\n\n protected:\n\n DeviceType deviceType ;\n\n DataType dataType ;\n\n void * memory ;\n\n size_t memorySize ;\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/data.hpp", "rank": 2, "score": 116297.04307711287 }, { "content": "class V(DIV): pass\n", "file_path": "matconvnet-1.0-beta24/doc/matdocparser.py", "rank": 4, "score": 74217.52737157026 }, { "content": "/// Thread class.\n\nclass thread {\n\n public:\n\n#if defined(_TTHREAD_WIN32_)\n\n typedef HANDLE native_handle_type;\n\n#else\n\n typedef pthread_t native_handle_type;\n\n#endif\n\n\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/impl/tinythread.h", "rank": 5, "score": 68634.47707574401 }, { "content": "/// Mutex class.\n\n/// This is a mutual exclusion object for synchronizing access to shared\n\n/// memory areas for several threads. The mutex is non-recursive (i.e. a\n\n/// program may deadlock if the thread that owns a mutex object calls lock()\n\n/// on that object).\n\n/// @see recursive_mutex\n\nclass mutex {\n\n public:\n\n /// Constructor.\n\n mutex()\n\n#if defined(_TTHREAD_WIN32_)\n\n : mAlreadyLocked(false)\n\n#endif\n\n {\n\n#if defined(_TTHREAD_WIN32_)\n\n InitializeCriticalSection(&mHandle);\n\n#else\n\n pthread_mutex_init(&mHandle, NULL);\n\n#endif\n\n }\n\n\n\n /// Destructor.\n\n ~mutex()\n\n {\n\n#if defined(_TTHREAD_WIN32_)\n\n DeleteCriticalSection(&mHandle);\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/impl/tinythread.h", "rank": 6, "score": 68633.25889049863 }, { "content": " class Impl ;\n\n Impl * impl ;\n\n } ;\n\n}\n\n\n\n#endif\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/imread.hpp", "rank": 7, "score": 68629.5612059318 }, { "content": " class id;\n\n\n\n /// Default constructor.\n\n /// Construct a @c thread object without an associated thread of execution\n\n /// (i.e. non-joinable).\n\n thread() : mHandle(0), mNotAThread(true)\n\n#if defined(_TTHREAD_WIN32_)\n\n , mWin32ThreadID(0)\n\n#endif\n\n {}\n\n\n\n /// Thread starting constructor.\n\n /// Construct a @c thread object with a new thread of execution.\n\n /// @param[in] aFunction A function pointer to a function of type:\n\n /// <tt>void fun(void * arg)</tt>\n\n /// @param[in] aArg Argument to the thread function.\n\n /// @note This constructor is not fully compatible with the standard C++\n\n /// thread class. It is more similar to the pthread_create() (POSIX) and\n\n /// CreateThread() (Windows) functions.\n\n thread(void (*aFunction)(void *), void * aArg);\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/impl/tinythread.h", "rank": 8, "score": 68629.5612059318 }, { "content": " class Image\n\n {\n\n public:\n\n Image() ;\n\n Image(Image const & im) ;\n\n Image(ImageShape const & shape, float * memory = NULL) ;\n\n ImageShape const & getShape() const ;\n\n float * getMemory() const ;\n\n void clear() ;\n\n\n\n protected:\n\n ImageShape shape ;\n\n float * memory ;\n\n } ;\n\n\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/imread.hpp", "rank": 9, "score": 68629.5612059318 }, { "content": " class Context\n\n {\n\n public:\n\n Context() ;\n\n ~Context() ;\n\n\n\n void * getWorkspace(DeviceType device, size_t size) ;\n\n void clearWorkspace(DeviceType device) ;\n\n void * getAllOnes(DeviceType device, DataType type, size_t size) ;\n\n void clearAllOnes(DeviceType device) ;\n\n CudaHelper& getCudaHelper() ;\n\n\n\n void clear() ; // do a reset\n\n void invalidateGpu() ; // drop CUDA memory and handles\n\n\n\n vl::ErrorCode passError(vl::ErrorCode error, char const * message = NULL) ;\n\n vl::ErrorCode setError(vl::ErrorCode error, char const * message = NULL) ;\n\n void resetLastError() ;\n\n vl::ErrorCode getLastError() const ;\n\n std::string const& getLastErrorMessage() const ;\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/data.hpp", "rank": 10, "score": 68629.5612059318 }, { "content": " class Buffer\n\n {\n\n public:\n\n Buffer() ;\n\n vl::ErrorCode init(DeviceType deviceType, DataType dataType, size_t size) ;\n\n void * getMemory() ;\n\n int getNumReallocations() const ;\n\n void clear() ;\n\n void invalidateGpu() ;\n\n protected:\n\n DeviceType deviceType ;\n\n DataType dataType ;\n\n size_t size ;\n\n void * memory ;\n\n int numReallocations ;\n\n } ;\n\n }\n\n\n\n /* -----------------------------------------------------------------\n\n * Context\n\n * -------------------------------------------------------------- */\n\n\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/data.hpp", "rank": 11, "score": 68629.5612059318 }, { "content": "/// Condition variable class.\n\n/// This is a signalling object for synchronizing the execution flow for\n\n/// several threads. Example usage:\n\n/// @code\n\n/// // Shared data and associated mutex and condition variable objects\n\n/// int count;\n\n/// mutex m;\n\n/// condition_variable cond;\n\n///\n\n/// // Wait for the counter to reach a certain number\n\n/// void wait_counter(int targetCount)\n\n/// {\n\n/// lock_guard<mutex> guard(m);\n\n/// while(count < targetCount)\n\n/// cond.wait(m);\n\n/// }\n\n///\n\n/// // Increment the counter, and notify waiting threads\n\n/// void increment()\n\n/// {\n\n/// lock_guard<mutex> guard(m);\n\n/// ++ count;\n\n/// cond.notify_all();\n\n/// }\n\n/// @endcode\n\nclass condition_variable {\n\n public:\n\n /// Constructor.\n\n#if defined(_TTHREAD_WIN32_)\n\n condition_variable();\n\n#else\n\n condition_variable()\n\n {\n\n pthread_cond_init(&mHandle, NULL);\n\n }\n\n#endif\n\n\n\n /// Destructor.\n\n#if defined(_TTHREAD_WIN32_)\n\n ~condition_variable();\n\n#else\n\n ~condition_variable()\n\n {\n\n pthread_cond_destroy(&mHandle);\n\n }\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/impl/tinythread.h", "rank": 12, "score": 67744.28245698143 }, { "content": "/// Recursive mutex class.\n\n/// This is a mutual exclusion object for synchronizing access to shared\n\n/// memory areas for several threads. The mutex is recursive (i.e. a thread\n\n/// may lock the mutex several times, as long as it unlocks the mutex the same\n\n/// number of times).\n\n/// @see mutex\n\nclass recursive_mutex {\n\n public:\n\n /// Constructor.\n\n recursive_mutex()\n\n {\n\n#if defined(_TTHREAD_WIN32_)\n\n InitializeCriticalSection(&mHandle);\n\n#else\n\n pthread_mutexattr_t attr;\n\n pthread_mutexattr_init(&attr);\n\n pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);\n\n pthread_mutex_init(&mHandle, &attr);\n\n#endif\n\n }\n\n\n\n /// Destructor.\n\n ~recursive_mutex()\n\n {\n\n#if defined(_TTHREAD_WIN32_)\n\n DeleteCriticalSection(&mHandle);\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/impl/tinythread.h", "rank": 13, "score": 67741.29682982754 }, { "content": " class MexTensor ;\n\n\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/datamex.hpp", "rank": 14, "score": 67733.87408000106 }, { "content": " class TensorShape\n\n {\n\n public:\n\n TensorShape() ;\n\n TensorShape(TensorShape const& t) ;\n\n TensorShape(size_t height, size_t width, size_t depth, size_t size) ;\n\n TensorShape(size_t const * dimensions, size_t numDimensions) ;\n\n\n\n void clear() ; // set to empty (numDimensions = 0)\n\n void setDimension(size_t num, size_t dimension) ;\n\n void setDimensions(size_t const * dimensions, size_t numDimensions) ;\n\n void setHeight(size_t x) ;\n\n void setWidth(size_t x) ;\n\n void setDepth(size_t x) ;\n\n void setSize(size_t x) ;\n\n void reshape(size_t numDimensions) ; // squash or stretch to numDimensions\n\n void reshape(TensorShape const & shape) ; // same as operator=\n\n\n\n size_t getDimension(size_t num) const ;\n\n size_t const * getDimensions() const ;\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/data.hpp", "rank": 15, "score": 67733.87408000106 }, { "content": "class lock_guard {\n\n public:\n\n typedef T mutex_type;\n\n\n\n lock_guard() : mMutex(0) {}\n\n\n\n /// The constructor locks the mutex.\n\n explicit lock_guard(mutex_type &aMutex)\n\n {\n\n mMutex = &aMutex;\n\n mMutex->lock();\n\n }\n\n\n\n /// The destructor unlocks the mutex.\n\n ~lock_guard()\n\n {\n\n if(mMutex)\n\n mMutex->unlock();\n\n }\n\n\n\n private:\n\n mutex_type * mMutex;\n\n};\n\n\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/impl/tinythread.h", "rank": 16, "score": 67733.87408000106 }, { "content": " class ImageReader\n\n {\n\n public:\n\n ImageReader() ;\n\n ~ImageReader() ;\n\n vl::ErrorCode readShape(ImageShape & image, char const * fileName) ;\n\n vl::ErrorCode readPixels(float * memory, char const * fileName) ;\n\n char const * getLastErrorMessage() const ;\n\n\n\n private:\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/imread.hpp", "rank": 17, "score": 67733.87408000106 }, { "content": " class CudaHelper {\n\n public:\n\n // CUDA errors\n\n cudaError_t getLastCudaError() const ;\n\n std::string const& getLastCudaErrorMessage() const ;\n\n vl::ErrorCode catchCudaError(char const* description = NULL) ;\n\n\n\n // CUDA control\n\n vl::ErrorCode setStream(cudaStream_t streamId) ;\n\n cudaStream_t getStream() const ;\n\n\n\n // CuBLAS support\n\n cublasStatus_t getCublasHandle(cublasHandle_t* handle) ;\n\n void clearCublas() ;\n\n cublasStatus_t getLastCublasError() const ;\n\n std::string const& getLastCublasErrorMessage() const ;\n\n vl::ErrorCode catchCublasError(cublasStatus_t status,\n\n char const* description = NULL) ;\n\n\n\n#if ENABLE_CUDNN\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/datacu.hpp", "rank": 18, "score": 67733.87408000106 }, { "content": " class CudaHelper ;\n\n\n\n /* -----------------------------------------------------------------\n\n * Helpers\n\n * -------------------------------------------------------------- */\n\n\n\n /// Computes the smallest multiple of @a b which is greater\n\n /// or equal to @a a.\n\n inline int divideAndRoundUp(int a, int b)\n\n {\n\n return (a + b - 1) / b ;\n\n }\n\n\n\n inline size_t divideAndRoundUp(size_t a, size_t b)\n\n {\n\n return (a + b - 1) / b ;\n\n }\n\n\n\n /// Compute the greatest common divisor g of non-negative integers\n\n /// @a a and @a b as well as two integers @a u and @a v such that\n\n /// $au + bv = g$ (Bezout's coefficients).\n\n int gcd(int a, int b, int &u, int& v) ;\n\n\n\n /// Draw a Normally-distributed scalar\n\n double randn() ;\n\n\n\n /// Get realtime monotnic clock in microseconds\n\n size_t getTime() ;\n\n\n\n namespace impl {\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/data.hpp", "rank": 19, "score": 67733.87408000106 }, { "content": "/// Fast mutex class.\n\n/// This is a mutual exclusion object for synchronizing access to shared\n\n/// memory areas for several threads. It is similar to the tthread::mutex class,\n\n/// but instead of using system level functions, it is implemented as an atomic\n\n/// spin lock with very low CPU overhead.\n\n///\n\n/// The \\c fast_mutex class is NOT compatible with the \\c condition_variable\n\n/// class (however, it IS compatible with the \\c lock_guard class). It should\n\n/// also be noted that the \\c fast_mutex class typically does not provide\n\n/// as accurate thread scheduling as a the standard \\c mutex class does.\n\n///\n\n/// Because of the limitations of the class, it should only be used in\n\n/// situations where the mutex needs to be locked/unlocked very frequently.\n\n///\n\n/// @note The \"fast\" version of this class relies on inline assembler language,\n\n/// which is currently only supported for 32/64-bit Intel x86/AMD64 and\n\n/// PowerPC architectures on a limited number of compilers (GNU g++ and MS\n\n/// Visual C++).\n\n/// For other architectures/compilers, system functions are used instead.\n\nclass fast_mutex {\n\n public:\n\n /// Constructor.\n\n#if defined(_FAST_MUTEX_ASM_)\n\n fast_mutex() : mLock(0) {}\n\n#else\n\n fast_mutex()\n\n {\n\n #if defined(_TTHREAD_WIN32_)\n\n InitializeCriticalSection(&mHandle);\n\n #elif defined(_TTHREAD_POSIX_)\n\n pthread_mutex_init(&mHandle, NULL);\n\n #endif\n\n }\n\n#endif\n\n\n\n#if !defined(_FAST_MUTEX_ASM_)\n\n /// Destructor.\n\n ~fast_mutex()\n\n {\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/impl/fast_mutex.h", "rank": 20, "score": 66879.60389330296 }, { "content": "class FibHeap;\n\n\n", "file_path": "code/tool/edges-master/piotr_toolbox/matlab/private/fibheap.h", "rank": 21, "score": 66048.340492939 }, { "content": "class FibHeap\n\n{\n\n\tFibHeapNode *MinRoot;\n\n\tlong NumNodes, NumTrees, NumMarkedNodes;\n\n\tint HeapOwnershipFlag;\n\n\n\npublic:\n\n\tFibHeap();\n\n\tvirtual ~FibHeap();\n\n\n\n\t// The Standard Heap Operations\n\n\tvoid Insert(FibHeapNode *NewNode);\n\n\tvoid Union(FibHeap *OtherHeap);\n\n\tinline FibHeapNode *Minimum() { return MinRoot; }\n\n\tFibHeapNode *ExtractMin();\n\n\tint DecreaseKey(FibHeapNode *theNode, FibHeapNode& NewKey);\n\n\tint Delete(FibHeapNode *theNode);\n\n\n\n\t// Extra utility functions\n\n\tint GetHeapOwnership() { return HeapOwnershipFlag; };\n", "file_path": "code/tool/edges-master/piotr_toolbox/matlab/private/fibheap.h", "rank": 22, "score": 66048.340492939 }, { "content": "class FibHeapNode\n\n{\n\n\tfriend class FibHeap;\n\n\tFibHeapNode *Left, *Right, *Parent, *Child;\n\n\tshort Degree, Mark, NegInfinityFlag;\n\n\n\nprotected:\n\n\tinline int FHN_Cmp(FibHeapNode& RHS) {\n\n\t\tif (NegInfinityFlag)\n\n\t\t\treturn RHS.NegInfinityFlag ? 0 : -1;\n\n\t\treturn RHS.NegInfinityFlag ? 1 : 0;\n\n\t}\n\n\tinline void FHN_Assign(FibHeapNode& RHS) {\n\n\t\tNegInfinityFlag = RHS.NegInfinityFlag;\n\n\t}\n\n\n\npublic:\n\n\tinline FibHeapNode() {\n\n\t\tLeft = Right = Parent = Child = NULL;\n\n\t\tDegree = Mark = NegInfinityFlag = 0;\n", "file_path": "code/tool/edges-master/piotr_toolbox/matlab/private/fibheap.h", "rank": 23, "score": 65254.405593449264 }, { "content": "// main class for generating edge boxes\n\nclass EdgeBoxGenerator\n\n{\n\npublic:\n\n // method parameters (must be manually set)\n\n float _alpha, _beta, _eta, _minScore; int _maxBoxes;\n\n float _edgeMinMag, _edgeMergeThr, _clusterMinMag;\n\n float _maxAspectRatio, _minBoxArea, _gamma, _kappa;\n\n\n\n // main external routine (set parameters first)\n\n void generate( Boxes &boxes, arrayf &E, arrayf &O, arrayf &V );\n\n\n\nprivate:\n\n // edge segment information (see clusterEdges)\n\n int h, w; // image dimensions\n\n int _segCnt; // total segment count\n\n arrayi _segIds; // segment ids (-1/0 means no segment)\n\n vectorf _segMag; // segment edge magnitude sums\n\n vectori _segR, _segC; // segment lower-right pixel\n\n vector<vectorf> _segAff; // segment affinities\n\n vector<vectori> _segAffIdx; // segment neighbors\n", "file_path": "code/tool/edges-master/edges-master/private/edgeBoxesMex.cpp", "rank": 24, "score": 63759.854749542865 }, { "content": "/// Thread ID.\n\n/// The thread ID is a unique identifier for each thread.\n\n/// @see thread::get_id()\n\nclass thread::id {\n\n public:\n\n /// Default constructor.\n\n /// The default constructed ID is that of thread without a thread of\n\n /// execution.\n\n id() : mId(0) {};\n\n\n\n id(unsigned long int aId) : mId(aId) {};\n\n\n\n id(const id& aId) : mId(aId.mId) {};\n\n\n\n inline id & operator=(const id &aId)\n\n {\n\n mId = aId.mId;\n\n return *this;\n\n }\n\n\n\n inline friend bool operator==(const id &aId1, const id &aId2)\n\n {\n\n return (aId1.mId == aId2.mId);\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/impl/tinythread.h", "rank": 25, "score": 62951.509190212724 }, { "content": "class vl::ImageReader::Impl\n\n{\n\npublic:\n\n Impl() ;\n\n ~Impl() ;\n\n struct jpeg_error_mgr jpegErrorManager ; /* must be the first element */\n\n struct jpeg_decompress_struct decompressor ;\n\n jmp_buf onJpegError ;\n\n char jpegLastErrorMsg [JMSG_LENGTH_MAX] ;\n\n char lastErrorMessage [ERR_MSG_MAX_LEN] ;\n\n\n\n vl::ErrorCode readPixels(float * memory, char const * filename) ;\n\n vl::ErrorCode readShape(vl::ImageShape & shape, char const * filename) ;\n\n\n\n static void reader_jpeg_error (j_common_ptr cinfo)\n\n {\n\n vl::ImageReader::Impl* self = (vl::ImageReader::Impl*) cinfo->err ;\n\n (*(cinfo->err->format_message)) (cinfo, self->jpegLastErrorMsg) ;\n\n longjmp(self->onJpegError, 1) ;\n\n }\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/impl/imread_libjpeg.cpp", "rank": 26, "score": 56464.70706419469 }, { "content": "class vl::ImageReader::Impl\n\n{\n\npublic:\n\n Impl() ;\n\n ~Impl() ;\n\n GdiplusStartupInput gdiplusStartupInput;\n\n ULONG_PTR gdiplusToken;\n\n vl::ErrorCode readPixels(float * memory, char const * filename) ;\n\n vl::ErrorCode readShape(vl::ImageShape & shape, char const * filename) ;\n\n char lastErrorMessage[ERR_MAX_LEN];\n\n} ;\n\n\n\nvl::ImageReader::Impl::Impl()\n\n{\n\n lastErrorMessage[0] = 0;\n\n GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);\n\n}\n\n\n\nvl::ImageReader::Impl::~Impl()\n\n{\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/impl/imread_gdiplus.cpp", "rank": 27, "score": 56464.70706419469 }, { "content": " def parse_V(self, indent):\n\n i = 0\n\n while (self.lookahead.isa(L) and self.lookahead.indent > indent) or \\\n\n (self.lookahead.isa(B)):\n\n self.shift()\n\n i = i + 1\n", "file_path": "matconvnet-1.0-beta24/doc/matdocparser.py", "rank": 28, "score": 40438.172737684225 }, { "content": "def render_V(tree, context):\n\n context.push(Frame(\" \"))\n\n for n in tree.children:\n\n if n.isa(L): render_L_from_indent(n, context, tree.indent)\n\n elif n.isa(B): render_B(n, context)\n", "file_path": "matconvnet-1.0-beta24/doc/matdoc.py", "rank": 29, "score": 40438.172737684225 }, { "content": "struct blas<vl::VLDT_CPU, vl::VLDT_Double>\n\n{\n\n typedef double type ;\n\n\n\n static vl::ErrorCode\n\n gemm(vl::Context& context,\n\n char op1, char op2,\n\n ptrdiff_t m, ptrdiff_t n, ptrdiff_t k,\n\n type alpha,\n\n type const * a, ptrdiff_t lda,\n\n type const * b, ptrdiff_t ldb,\n\n type beta,\n\n type * c, ptrdiff_t ldc)\n\n {\n\n dgemm(&op1, &op2,\n\n &m, &n, &k,\n\n &alpha,\n\n (type*)a, &lda,\n\n (type*)b, &ldb,\n\n &beta,\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/impl/blashelper.hpp", "rank": 30, "score": 38228.5637073484 }, { "content": "struct blas<vl::VLDT_GPU, vl::VLDT_Double>\n\n{\n\n typedef double type ;\n\n\n\n static vl::ErrorCode\n\n gemm(vl::Context& context,\n\n char op1, char op2,\n\n ptrdiff_t m, ptrdiff_t n, ptrdiff_t k,\n\n type alpha,\n\n type const * a, ptrdiff_t lda,\n\n type const * b, ptrdiff_t ldb,\n\n type beta,\n\n type * c, ptrdiff_t ldc)\n\n {\n\n cublasHandle_t handle ;\n\n cublasStatus_t status ;\n\n status = context.getCudaHelper().getCublasHandle(&handle) ;\n\n if (status != CUBLAS_STATUS_SUCCESS) goto done ;\n\n\n\n status = cublasDgemm(handle,\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/impl/blashelper.hpp", "rank": 31, "score": 38228.5637073484 }, { "content": "function readInt($file)\n\n{\n\n $b1 = ord(fgetc($file)); $b2 = ord(fgetc($file));\n\n $b3 = ord(fgetc($file)); $b4 = ord(fgetc($file));\n\n return ($b1<<24)|($b2<<16)|($b3<<8)|$b4;\n\n}\n\n\n", "file_path": "code/tool/edges-master/piotr_toolbox/external/m2html/templates/brain/doxysearch.php", "rank": 32, "score": 38223.41783295466 }, { "content": "function readInt($file)\n\n{\n\n $b1 = ord(fgetc($file)); $b2 = ord(fgetc($file));\n\n $b3 = ord(fgetc($file)); $b4 = ord(fgetc($file));\n\n return ($b1<<24)|($b2<<16)|($b3<<8)|$b4;\n\n}\n\n\n", "file_path": "code/tool/edges-master/piotr_toolbox/external/m2html/templates/frame/doxysearch.php", "rank": 33, "score": 38223.41783295466 }, { "content": "function readInt($file)\n\n{\n\n $b1 = ord(fgetc($file)); $b2 = ord(fgetc($file));\n\n $b3 = ord(fgetc($file)); $b4 = ord(fgetc($file));\n\n return ($b1<<24)|($b2<<16)|($b3<<8)|$b4;\n\n}\n\n\n", "file_path": "code/tool/edges-master/piotr_toolbox/external/m2html/templates/blue/doxysearch.php", "rank": 34, "score": 38223.41783295466 }, { "content": "\t}\n\n\tvirtual ~FibHeapNode();\n\n\tvirtual void operator =(FibHeapNode& RHS);\n\n\tvirtual int operator ==(FibHeapNode& RHS);\n\n\tvirtual int operator <(FibHeapNode& RHS);\n\n\n\n\tvirtual void Print();\n\n};\n\n\n\n//========================================================================\n\n// Fibonacci Heap Class\n\n//========================================================================\n\n\n", "file_path": "code/tool/edges-master/piotr_toolbox/matlab/private/fibheap.h", "rank": 35, "score": 27.023311997002267 }, { "content": "/*******************************************************************************\n\n* Piotr's Computer Vision Matlab Toolbox Version 3.50\n\n* Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]\n\n* Licensed under the Simplified BSD License [see external/bsd.txt]\n\n*******************************************************************************/\n\n#include <mex.h>\n\n#ifdef USEOMP\n\n#include <omp.h>\n\n#endif\n\n\n\ntypedef unsigned char uint8;\n\ntypedef unsigned int uint32;\n\n#define min(x,y) ((x) < (y) ? (x) : (y))\n\n\n\n// construct cdf given data vector and wts\n\nvoid constructCdf( uint8* data, float *wts, int nBins,\n\n int N, int M, uint32 *ord, float *cdf )\n\n{\n\n int i; for( i=0; i<nBins; i++) cdf[i]=0;\n\n if(M) for( i=0; i<M; i++) cdf[data[ord[i]]] += wts[i];\n", "file_path": "code/tool/edges-master/piotr_toolbox/classify/private/binaryTreeTrain1.cpp", "rank": 38, "score": 17.6919985463727 }, { "content": "/*******************************************************************************\n\n* Piotr's Computer Vision Matlab Toolbox Version 3.24\n\n* Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]\n\n* Licensed under the Simplified BSD License [see external/bsd.txt]\n\n*******************************************************************************/\n\n#include <mex.h>\n\n#ifdef USEOMP\n\n#include <omp.h>\n\n#endif\n\n\n\ntypedef unsigned char uint8;\n\ntypedef unsigned int uint32;\n\n#define min(x,y) ((x) < (y) ? (x) : (y))\n\n\n\ntemplate<typename T>\n\nvoid forestInds( uint32 *inds, const T *data, const T *thrs,\n\n const uint32 *fids, const uint32 *child, int N, int nThreads )\n\n{\n\n #ifdef USEOMP\n\n nThreads = min(nThreads,omp_get_max_threads());\n", "file_path": "code/tool/edges-master/piotr_toolbox/classify/private/forestInds.cpp", "rank": 39, "score": 17.337219507851312 }, { "content": " v = - wl/w*wr/w*g*g;\n\n }\n\n if( v<vBst && data1[j2]-data1[j1]>=1e-6f ) {\n\n vBst=v; fid=i+1; thr=0.5f*(data1[j1]+data1[j2]); }\n\n }\n\n }\n\n delete [] Wl; delete [] Wr; delete [] W; gain = vInit-vBst;\n\n}\n\n\n\n// [fid,thr,gain] = mexFunction(data,hs,ws,order,H,split);\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {\n\n int H, N, F, split; float *data, *ws, thr;\n\n double gain; uint32 *hs, *order, fid;\n\n data = (float*) mxGetData(prhs[0]);\n\n hs = (uint32*) mxGetData(prhs[1]);\n\n ws = (float*) mxGetData(prhs[2]);\n\n order = (uint32*) mxGetData(prhs[3]);\n\n H = (int) mxGetScalar(prhs[4]);\n\n split = (int) mxGetScalar(prhs[5]);\n\n N = (int) mxGetM(prhs[0]);\n\n F = (int) mxGetN(prhs[0]);\n\n forestFindThr(H,N,F,data,hs,ws,order,split,fid,thr,gain);\n\n plhs[0] = mxCreateDoubleScalar(fid);\n\n plhs[1] = mxCreateDoubleScalar(thr);\n\n plhs[2] = mxCreateDoubleScalar(gain);\n\n}\n", "file_path": "code/tool/edges-master/piotr_toolbox/classify/private/forestFindThr.cpp", "rank": 40, "score": 17.33142652008557 }, { "content": " // extract input arguments\n\n I = mxGetPr(pr[0]);\n\n flag = (int) mxGetScalar(pr[1]);\n\n single = (bool) (mxGetScalar(pr[2])>0);\n\n idIn = mxGetClassID(pr[0]);\n\n\n\n // call rgbConvert() based on type of input and output array\n\n if(!((d==1 && flag==0) || flag==1 || (d/3)*3==d))\n\n mexErrMsgTxt(\"I must have third dimension d==1 or (d/3)*3==d.\");\n\n if( idIn == mxSINGLE_CLASS && !single )\n\n J = (void*) rgbConvert( (float*) I, n, d, flag, 1.0 );\n\n else if( idIn == mxSINGLE_CLASS && single )\n\n J = (void*) rgbConvert( (float*) I, n, d, flag, 1.0f );\n\n else if( idIn == mxDOUBLE_CLASS && !single )\n\n J = (void*) rgbConvert( (double*) I, n, d, flag, 1.0 );\n\n else if( idIn == mxDOUBLE_CLASS && single )\n\n J = (void*) rgbConvert( (double*) I, n, d, flag, 1.0f );\n\n else if( idIn == mxUINT8_CLASS && !single )\n\n J = (void*) rgbConvert( (unsigned char*) I, n, d, flag, 1.0/255 );\n\n else if( idIn == mxUINT8_CLASS && single )\n", "file_path": "code/tool/edges-master/piotr_toolbox/channels/private/rgbConvertMex.cpp", "rank": 41, "score": 17.173299375561463 }, { "content": "/*******************************************************************************\n\n* Structured Edge Detection Toolbox Version 3.01\n\n* Code written by Piotr Dollar, 2014.\n\n* Licensed under the MSR-LA Full Rights License [see license.txt]\n\n*******************************************************************************/\n\n#include <mex.h>\n\n#include <math.h>\n\n#include <stdlib.h>\n\n#include <string.h>\n\n#ifdef USEOMP\n\n#include <omp.h>\n\n#endif\n\n\n\ntypedef unsigned int uint32;\n\ntypedef unsigned short uint16;\n\ntypedef unsigned char uint8;\n\ntemplate<typename T> inline T min( T x, T y ) { return x<y ? x : y; }\n\n\n\n// construct lookup array for mapping fids to channel indices\n\nuint32* buildLookup( int *dims, int w ) {\n", "file_path": "code/tool/edges-master/edges-master/private/edgesDetectMex.cpp", "rank": 42, "score": 16.66838370909734 }, { "content": "//========================================================================\n\n\n\nvoid FibHeapNode::operator =(FibHeapNode& RHS) {\n\n\tFHN_Assign(RHS);\n\n\t// Key assignment goes here in derived classes\n\n}\n\n\n\nint FibHeapNode::operator ==(FibHeapNode& RHS) {\n\n\tif (FHN_Cmp(RHS)) return 0;\n\n\t// Key compare goes here in derived classes\n\n\treturn 1;\n\n}\n\n\n\nint FibHeapNode::operator <(FibHeapNode& RHS) {\n\n\tint X;\n\n\tif ((X=FHN_Cmp(RHS)) != 0)\n\n\t\treturn X < 0 ? 1 : 0;\n\n\t// Key compare goes here in derived classes\n\n\treturn 0;\n\n}\n", "file_path": "code/tool/edges-master/piotr_toolbox/matlab/private/fibheap.cpp", "rank": 43, "score": 16.60360597498215 }, { "content": " if( c>0 && c<=d ) { I += h*w*(c-1); d=1; }\n\n pl[0] = mxCreateMatrix3(h,w,1,mxSINGLE_CLASS,0,(void**)&M);\n\n if(nl>=2) pl[1] = mxCreateMatrix3(h,w,1,mxSINGLE_CLASS,0,(void**)&O);\n\n gradMag(I, M, O, h, w, d, full>0 );\n\n}\n\n\n\n// gradMagNorm( M, S, norm ) - operates on M - see gradientMag.m\n\nvoid mGradMagNorm( int nl, mxArray *pl[], int nr, const mxArray *pr[] ) {\n\n int h, w, d; float *M, *S, norm;\n\n checkArgs(nl,pl,nr,pr,0,0,3,3,&h,&w,&d,mxSINGLE_CLASS,(void**)&M);\n\n if( mxGetM(pr[1])!=h || mxGetN(pr[1])!=w || d!=1 ||\n\n mxGetClassID(pr[1])!=mxSINGLE_CLASS ) mexErrMsgTxt(\"M or S is bad.\");\n\n S = (float*) mxGetPr(pr[1]); norm = (float) mxGetScalar(pr[2]);\n\n gradMagNorm(M,S,h,w,norm);\n\n}\n\n\n\n// H=gradHist(M,O,[...]) - see gradientHist.m\n\nvoid mGradHist( int nl, mxArray *pl[], int nr, const mxArray *pr[] ) {\n\n int h, w, d, hb, wb, nChns, binSize, nOrients, softBin, useHog;\n\n bool full; float *M, *O, *H, clipHog;\n", "file_path": "code/tool/edges-master/piotr_toolbox/channels/private/gradientMex.cpp", "rank": 44, "score": 16.10891955573901 }, { "content": " }\n\n\n\n inline friend bool operator>(const id &aId1, const id &aId2)\n\n {\n\n return (aId1.mId > aId2.mId);\n\n }\n\n\n\n inline friend std::ostream& operator <<(std::ostream &os, const id &obj)\n\n {\n\n os << obj.mId;\n\n return os;\n\n }\n\n\n\n private:\n\n unsigned long int mId;\n\n};\n\n\n\n\n\n// Related to <ratio> - minimal to be able to support chrono.\n\ntypedef long long __intmax_t;\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/impl/tinythread.h", "rank": 45, "score": 15.886187788158644 }, { "content": "/*******************************************************************************\n\n* Structured Edge Detection Toolbox Version 3.01\n\n* Code written by Piotr Dollar and Larry Zitnick, 2014.\n\n* Licensed under the MSR-LA Full Rights License [see license.txt]\n\n*******************************************************************************/\n\n#include \"mex.h\"\n\n#include \"math.h\"\n\n#include <algorithm>\n\n#include <vector>\n\nusing namespace std;\n\n#define PI 3.14159265f\n\nint clamp( int v, int a, int b ) { return v<a?a:v>b?b:v; }\n\n\n\n// trivial array class encapsulating pointer arrays\n\ntemplate <class T> class Array\n\n{\n\npublic:\n\n Array() { _h=_w=0; _x=0; _free=0; }\n\n virtual ~Array() { clear(); }\n\n void clear() { if(_free) delete [] _x; _h=_w=0; _x=0; _free=0; }\n", "file_path": "code/tool/edges-master/edges-master/private/edgeBoxesMex.cpp", "rank": 46, "score": 15.472707724630322 }, { "content": "}\n\n\n\n////////////////////////////////////////////////////////////////////////////////\n\n\n\n// Matlab entry point: bbs = mex( E, O, prm1, prm2, ... )\n\nvoid mexFunction( int nl, mxArray *pl[], int nr, const mxArray *pr[] )\n\n{\n\n // check and get inputs\n\n if(nr != 14) mexErrMsgTxt(\"Fourteen inputs required.\");\n\n if(nl > 2) mexErrMsgTxt(\"At most two outputs expected.\");\n\n if(mxGetClassID(pr[0])!=mxSINGLE_CLASS) mexErrMsgTxt(\"E must be a float*\");\n\n if(mxGetClassID(pr[1])!=mxSINGLE_CLASS) mexErrMsgTxt(\"O must be a float*\");\n\n arrayf E; E._x = (float*) mxGetData(pr[0]);\n\n arrayf O; O._x = (float*) mxGetData(pr[1]);\n\n int h = (int) mxGetM(pr[0]); O._h=E._h=h;\n\n int w = (int) mxGetN(pr[0]); O._w=E._w=w;\n\n\n\n // optionally create memory for visualization\n\n arrayf V; if( nl>1 ) {\n\n const int ds[3] = {h,w,3};\n", "file_path": "code/tool/edges-master/edges-master/private/edgeBoxesMex.cpp", "rank": 47, "score": 15.112237895109029 }, { "content": "mxArray* mxCreateMatrix3( int h, int w, int d, mxClassID id, bool c, void **I ){\n\n const int dims[3]={h,w,d}, n=h*w*d; int b; mxArray* M;\n\n if( id==mxINT32_CLASS ) b=sizeof(int);\n\n else if( id==mxDOUBLE_CLASS ) b=sizeof(double);\n\n else if( id==mxSINGLE_CLASS ) b=sizeof(float);\n\n else mexErrMsgTxt(\"Unknown mxClassID.\");\n\n *I = c ? mxCalloc(n,b) : mxMalloc(n*b);\n\n M = mxCreateNumericMatrix(0,0,id,mxREAL);\n\n mxSetData(M,*I); mxSetDimensions(M,dims,3); return M;\n\n}\n\n\n\n// Check inputs and outputs to mex, retrieve first input I\n\nvoid checkArgs( int nl, mxArray *pl[], int nr, const mxArray *pr[], int nl0,\n\n int nl1, int nr0, int nr1, int *h, int *w, int *d, mxClassID id, void **I )\n\n{\n\n const int *dims; int nDims;\n\n if( nl<nl0 || nl>nl1 ) mexErrMsgTxt(\"Incorrect number of outputs.\");\n\n if( nr<nr0 || nr>nr1 ) mexErrMsgTxt(\"Incorrect number of inputs.\");\n\n nDims = mxGetNumberOfDimensions(pr[0]); dims = mxGetDimensions(pr[0]);\n\n *h=dims[0]; *w=dims[1]; *d=(nDims==2) ? 1 : dims[2]; *I = mxGetPr(pr[0]);\n", "file_path": "code/tool/edges-master/piotr_toolbox/channels/private/gradientMex.cpp", "rank": 48, "score": 14.837822463994272 }, { "content": "\n\n template<int pixelFormat> void\n\n imageFromPixels(vl::Image & image, char unsigned const * rgb, int rowStride)\n\n {\n\n vl::ImageShape const & shape = image.getShape() ;\n\n int blockSizeX ;\n\n int blockSizeY ;\n\n int pixelStride ;\n\n int imagePlaneStride = (int)shape.width * (int)shape.height ;\n\n switch (pixelFormat) {\n\n case pixelFormatL:\n\n pixelStride = 1 ;\n\n blockSizeX = 16 ;\n\n blockSizeY = 4 ;\n\n break ;\n\n case pixelFormatBGR:\n\n case pixelFormatRGB:\n\n pixelStride = 3 ;\n\n blockSizeX = 4 ;\n\n blockSizeY = 4 ;\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/impl/imread_helpers.hpp", "rank": 49, "score": 14.505285931982382 }, { "content": "/*******************************************************************************\n\n* Piotr's Computer Vision Matlab Toolbox Version 3.00\n\n* Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]\n\n* Licensed under the Simplified BSD License [see external/bsd.txt]\n\n*******************************************************************************/\n\n#include \"wrappers.hpp\"\n\n#include \"string.h\"\n\n#include <math.h>\n\n#include <typeinfo>\n\n#include \"sse.hpp\"\n\ntypedef unsigned char uchar;\n\n\n\n// compute interpolation values for single column for resapling\n\ntemplate<class T> void resampleCoef( int ha, int hb, int &n, int *&yas,\n\n int *&ybs, T *&wts, int bd[2], int pad=0 )\n\n{\n\n const T s = T(hb)/T(ha), sInv = 1/s; T wt, wt0=T(1e-3)*s;\n\n bool ds=ha>hb; int nMax; bd[0]=bd[1]=0;\n\n if(ds) { n=0; nMax=ha+(pad>2 ? pad : 2)*hb; } else { n=nMax=hb; }\n\n // initialize memory\n", "file_path": "code/tool/edges-master/piotr_toolbox/channels/private/imResampleMex.cpp", "rank": 50, "score": 14.411464723620863 }, { "content": " - 1.72587999f / (0.3520887068f + mx.f);\n\n}\n\n\n\n// perform actual computation\n\nvoid forestFindThr( int H, int N, int F, const float *data,\n\n const uint32 *hs, const float *ws, const uint32 *order, const int split,\n\n uint32 &fid, float &thr, double &gain )\n\n{\n\n double *Wl, *Wr, *W; float *data1; uint32 *order1;\n\n int i, j, j1, j2, h; double vBst, vInit, v, w, wl, wr, g, gl, gr;\n\n Wl=new double[H]; Wr=new double[H]; W=new double[H];\n\n // perform initialization\n\n vBst = vInit = 0; g = 0; w = 0; fid = 1; thr = 0;\n\n for( i=0; i<H; i++ ) W[i] = 0;\n\n for( j=0; j<N; j++ ) { w+=ws[j]; W[hs[j]-1]+=ws[j]; }\n\n if( split==0 ) { for( i=0; i<H; i++ ) g+=gini(W[i]); vBst=vInit=(1-g/w/w); }\n\n if( split==1 ) { for( i=0; i<H; i++ ) g+=entropy(W[i]); vBst=vInit=g/w; }\n\n // loop over features, then thresholds (data is sorted by feature value)\n\n for( i=0; i<F; i++ ) {\n\n order1=(uint32*) order+i*N; data1=(float*) data+i*size_t(N);\n", "file_path": "code/tool/edges-master/piotr_toolbox/classify/private/forestFindThr.cpp", "rank": 51, "score": 14.300662977202865 }, { "content": " /// Example usage:\n\n /// @code\n\n /// // Sleep for 100 milliseconds\n\n /// this_thread::sleep_for(chrono::milliseconds(100));\n\n /// @endcode\n\n /// @note Supported duration types are: nanoseconds, microseconds,\n\n /// milliseconds, seconds, minutes and hours.\n\n template <class _Rep, class _Period> void sleep_for(const chrono::duration<_Rep, _Period>& aTime)\n\n {\n\n#if defined(_TTHREAD_WIN32_)\n\n Sleep(int(double(aTime.count()) * (1000.0 * _Period::_as_double()) + 0.5));\n\n#else\n\n usleep(int(double(aTime.count()) * (1000000.0 * _Period::_as_double()) + 0.5));\n\n#endif\n\n }\n\n}\n\n\n\n}\n\n\n\n// Define/macro cleanup\n\n#undef _TTHREAD_DISABLE_ASSIGNMENT\n\n\n\n#endif // _TINYTHREAD_H_\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/impl/tinythread.h", "rank": 52, "score": 13.783901961592695 }, { "content": " if( nDims!=2 && nDims!=3 ) mexErrMsgTxt(\"I must be a 2D or 3D array.\");\n\n if( mxGetClassID(pr[0])!=id ) mexErrMsgTxt(\"I has incorrect type.\");\n\n}\n\n\n\n// [Gx,Gy] = grad2(I) - see gradient2.m\n\nvoid mGrad2( int nl, mxArray *pl[], int nr, const mxArray *pr[] ) {\n\n int h, w, d; float *I, *Gx, *Gy;\n\n checkArgs(nl,pl,nr,pr,1,2,1,1,&h,&w,&d,mxSINGLE_CLASS,(void**)&I);\n\n if(h<2 || w<2) mexErrMsgTxt(\"I must be at least 2x2.\");\n\n pl[0]= mxCreateMatrix3( h, w, d, mxSINGLE_CLASS, 0, (void**) &Gx );\n\n pl[1]= mxCreateMatrix3( h, w, d, mxSINGLE_CLASS, 0, (void**) &Gy );\n\n grad2( I, Gx, Gy, h, w, d );\n\n}\n\n\n\n// [M,O] = gradMag( I, channel, full ) - see gradientMag.m\n\nvoid mGradMag( int nl, mxArray *pl[], int nr, const mxArray *pr[] ) {\n\n int h, w, d, c, full; float *I, *M, *O=0;\n\n checkArgs(nl,pl,nr,pr,1,2,3,3,&h,&w,&d,mxSINGLE_CLASS,(void**)&I);\n\n if(h<2 || w<2) mexErrMsgTxt(\"I must be at least 2x2.\");\n\n c = (int) mxGetScalar(pr[1]); full = (int) mxGetScalar(pr[2]);\n", "file_path": "code/tool/edges-master/piotr_toolbox/channels/private/gradientMex.cpp", "rank": 53, "score": 13.522232186638014 }, { "content": "/*******************************************************************************\n\n* Structured Edge Detection Toolbox Version 3.01\n\n* Code written by Piotr Dollar, 2014.\n\n* Licensed under the MSR-LA Full Rights License [see license.txt]\n\n*******************************************************************************/\n\n#include <mex.h>\n\n#include <math.h>\n\n#include <string.h>\n\n#ifdef USEOMP\n\n#include <omp.h>\n\n#endif\n\n\n\ntypedef unsigned int uint;\n\ntypedef unsigned char uint8;\n\ntemplate<typename T> inline T min( T x, T y ) { return x<y ? x : y; }\n\ntemplate<typename T> inline T max( T x, T y ) { return x<y ? y : x; }\n\n\n\n// refine sticky superpixels given image and edge data\n\nvoid sticky( uint *S, uint h, uint w, float *I, float *E, double *prm ) {\n\n // get additional parameters\n", "file_path": "code/tool/edges-master/edges-master/private/spDetectMex.cpp", "rank": 54, "score": 13.385056264920642 }, { "content": "\tvoid SetHeapOwnership() { HeapOwnershipFlag = 1; };\n\n\tvoid ClearHeapOwnership() { HeapOwnershipFlag = 0; };\n\n\tlong GetNumNodes() { return NumNodes; };\n\n\tlong GetNumTrees() { return NumTrees; };\n\n\tlong GetNumMarkedNodes() { return NumMarkedNodes; };\n\n\tvoid Print(FibHeapNode *Tree = NULL, FibHeapNode *theParent=NULL);\n\n\n\nprivate:\n\n\t// Internal functions that help to implement the Standard Operations\n\n\tinline void _Exchange(FibHeapNode* &N1, FibHeapNode* &N2) {\n\n\t\tFibHeapNode *Temp; Temp = N1; N1 = N2; N2 = Temp;\n\n\t}\n\n\tvoid _Consolidate();\n\n\tvoid _Link(FibHeapNode *, FibHeapNode *);\n\n\tvoid _AddToRootList(FibHeapNode *);\n\n\tvoid _Cut(FibHeapNode *, FibHeapNode *);\n\n\tvoid _CascadingCut(FibHeapNode *);\n\n};\n\n\n\n#endif /* FIBHEAP_H */\n", "file_path": "code/tool/edges-master/piotr_toolbox/matlab/private/fibheap.h", "rank": 55, "score": 13.377700557544046 }, { "content": " J = (void*) rgbConvert( (unsigned char*) I, n, d, flag, 1.0f/255 );\n\n else\n\n mexErrMsgTxt(\"Unsupported image type.\");\n\n\n\n // create and set output array\n\n dims1[0]=dims[0]; dims1[1]=dims[1]; dims1[2]=(flag==0 ? (d==1?1:d/3) : d);\n\n idOut = single ? mxSINGLE_CLASS : mxDOUBLE_CLASS;\n\n pl[0] = mxCreateNumericMatrix(0,0,idOut,mxREAL);\n\n mxSetData(pl[0],J); mxSetDimensions(pl[0],(const mwSize*) dims1,3);\n\n}\n\n#endif\n", "file_path": "code/tool/edges-master/piotr_toolbox/channels/private/rgbConvertMex.cpp", "rank": 56, "score": 13.215033047312568 }, { "content": " delete [] Vx0; delete [] Vy0;\n\n}\n\n\n\n// [Vx,Vy]=opticalFlowHsMex(Ex,Ey,Et,Z,nIter); - helper for opticalFlow\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {\n\n size_t h, w, nIter; float *Is[4], *Vx, *Vy;\n\n\n\n // Error checking on arguments\n\n if( nrhs!=5 ) mexErrMsgTxt(\"Five inputs expected.\");\n\n if( nlhs!=2 ) mexErrMsgTxt(\"Two outputs expected.\");\n\n h = mxGetM(prhs[0]); w = mxGetN(prhs[0]);\n\n for( int i=0; i<4; i++ ) {\n\n if(mxGetM(prhs[i])!=h || mxGetN(prhs[i])!=w) mexErrMsgTxt(\"Invalid dims.\");\n\n if(mxGetClassID(prhs[i])!=mxSINGLE_CLASS) mexErrMsgTxt(\"Invalid type.\");\n\n Is[i] = (float*) mxGetData(prhs[i]);\n\n }\n\n nIter = (int) mxGetScalar(prhs[4]);\n\n\n\n // create output matricies\n\n plhs[0] = mxCreateNumericMatrix(int(h),int(w),mxSINGLE_CLASS,mxREAL);\n\n plhs[1] = mxCreateNumericMatrix(int(h),int(w),mxSINGLE_CLASS,mxREAL);\n\n Vx = (float*) mxGetData(plhs[0]);\n\n Vy = (float*) mxGetData(plhs[1]);\n\n\n\n // run optical flow\n\n opticalFlowHsMex(Vx,Vy,Is[0],Is[1],Is[2],Is[3],int(h),int(w),nIter);\n\n}\n", "file_path": "code/tool/edges-master/piotr_toolbox/videos/private/opticalFlowHsMex.cpp", "rank": 57, "score": 12.98143854054281 }, { "content": " #pragma omp parallel for num_threads(nThreads)\n\n #endif\n\n for( int i = 0; i < N; i++ ) {\n\n uint32 k = 0;\n\n while( child[k] )\n\n if( data[i+fids[k]*size_t(N)] < thrs[k] )\n\n k = child[k]-1; else k = child[k];\n\n inds[i] = k+1;\n\n }\n\n}\n\n\n\n// inds=mexFunction(data,thrs,fids,child,[nThreads])\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {\n\n int N, nThreads; void *data, *thrs; uint32 *inds, *fids, *child;\n\n data = mxGetData(prhs[0]);\n\n thrs = mxGetData(prhs[1]);\n\n fids = (uint32*) mxGetData(prhs[2]);\n\n child = (uint32*) mxGetData(prhs[3]);\n\n nThreads = (nrhs<5) ? 100000 : (int) mxGetScalar(prhs[4]);\n\n N = (int) mxGetM(prhs[0]);\n", "file_path": "code/tool/edges-master/piotr_toolbox/classify/private/forestInds.cpp", "rank": 58, "score": 12.889620586731413 }, { "content": "/*******************************************************************************\n\n* Piotr's Computer Vision Matlab Toolbox Version 3.21\n\n* Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]\n\n* Licensed under the Simplified BSD License [see external/bsd.txt]\n\n*******************************************************************************/\n\n#include \"mex.h\"\n\n#include <vector>\n\n#include <cmath>\n\nusing namespace std;\n\n\n\ntypedef unsigned int uint32;\n\n\n\ninline void getChild( float *chns1, uint32 *cids, uint32 *fids,\n\n float *thrs, uint32 offset, uint32 &k0, uint32 &k )\n\n{\n\n float ftr = chns1[cids[fids[k]]];\n\n k = (ftr<thrs[k]) ? 1 : 2;\n\n k0=k+=k0*2; k+=offset;\n\n}\n\n\n", "file_path": "code/tool/edges-master/piotr_toolbox/detector/private/acfDetect1.cpp", "rank": 59, "score": 12.801096393283187 }, { "content": " uint x=xi; NEIGHBORS8(T); uint i, *s=&S[x*h+y]; if(*s!=0) continue;\n\n float *F=E+x*h+y; float e=10;\n\n float Es[8]={F[x0],F[x1],F[y0],F[y1],F[x0+y0],F[x0+y1],F[x1+y0],F[x1+y1]};\n\n for( i=0; i<8; i+=2 ) {\n\n if(N[i+1] && Es[i+1]<e) { *s=N[i+1]; e=Es[i+1]; }\n\n if(N[i+0] && Es[i+0]<e) { *s=N[i+0]; e=Es[i+0]; }\n\n }\n\n }\n\n for( uint x=0; x<w*h; x++ ) if(S[x]) S[x]--; delete [] T;\n\n }\n\n}\n\n\n\n// merge superpixels that are separated by a weak boundary\n\nvoid merge( uint *S, uint h, uint w, float *E, float thr ) {\n\n // compute m and min for each region\n\n uint x; uint m=0; for( x=0; x<w*h; x++ ) m=S[x]>m ? S[x] : m; m++;\n\n float *es=new float[m]; for( x=0; x<m; x++ ) es[x]=1000;\n\n for( x=0; x<w*h; x++ ) es[S[x]]=min(E[x],es[S[x]]);\n\n // check for regions to merge and compute label mapping\n\n uint *map = new uint[m]();\n", "file_path": "code/tool/edges-master/edges-master/private/spDetectMex.cpp", "rank": 60, "score": 12.327151848077456 }, { "content": "#ifdef _MSC_VER\n\n#pragma message ( \"SSSE3 instruction set enabled.\" )\n\n#endif\n\n /* SSSE3 optimised version */\n\n\n\n template<int pixelFormat> void\n\n imageFromPixels(vl::Image & image, char unsigned const * rgb, int rowStride)\n\n {\n\n vl::ImageShape const & shape = image.getShape() ;\n\n int blockSizeX ;\n\n int blockSizeY ;\n\n int pixelStride ;\n\n int imagePlaneStride = (int)shape.width * (int)shape.height ;\n\n __m128i shuffleRgb ;\n\n __m128i const shuffleL = _mm_set_epi8(0xff, 0xff, 0xff, 3,\n\n 0xff, 0xff, 0xff, 2,\n\n 0xff, 0xff, 0xff, 1,\n\n 0xff, 0xff, 0xff, 0) ;\n\n __m128i const mask = _mm_set_epi32(0xff, 0xff, 0xff, 0xff) ;\n\n\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/impl/imread_helpers.hpp", "rank": 61, "score": 12.201910484817992 }, { "content": " plhs[0] = mxCreateNumericMatrix(N,1,mxUINT32_CLASS,mxREAL);\n\n inds = (uint32*) mxGetPr(plhs[0]);\n\n if(mxGetClassID(prhs[0])!=mxGetClassID(prhs[1]))\n\n mexErrMsgTxt(\"Mismatch between data types.\");\n\n if(mxGetClassID(prhs[0])==mxSINGLE_CLASS)\n\n forestInds(inds,(float*)data,(float*)thrs,fids,child,N,nThreads);\n\n else if(mxGetClassID(prhs[0])==mxDOUBLE_CLASS)\n\n forestInds(inds,(double*)data,(double*)thrs,fids,child,N,nThreads);\n\n else if(mxGetClassID(prhs[0])==mxUINT8_CLASS)\n\n forestInds(inds,(uint8*)data,(uint8*)thrs,fids,child,N,nThreads);\n\n else mexErrMsgTxt(\"Unknown data type.\");\n\n}\n", "file_path": "code/tool/edges-master/piotr_toolbox/classify/private/forestInds.cpp", "rank": 62, "score": 12.098592888630716 }, { "content": " for( x=0; x<wb-1; x++ ) for( y=0; y<hb-1; y++ ) {\n\n n=N1+x*hb1+y; *n=1/float(sqrt(n[0]+n[1]+n[hb1]+n[hb1+1]+eps)); }\n\n x=0; dx= 1; dy= 1; y=0; N[x*hb1+y]=N[(x+dx)*hb1+y+dy];\n\n x=0; dx= 1; dy= 0; for(y=0; y<hb1; y++) N[x*hb1+y]=N[(x+dx)*hb1+y+dy];\n\n x=0; dx= 1; dy=-1; y=hb1-1; N[x*hb1+y]=N[(x+dx)*hb1+y+dy];\n\n x=wb1-1; dx=-1; dy= 1; y=0; N[x*hb1+y]=N[(x+dx)*hb1+y+dy];\n\n x=wb1-1; dx=-1; dy= 0; for( y=0; y<hb1; y++) N[x*hb1+y]=N[(x+dx)*hb1+y+dy];\n\n x=wb1-1; dx=-1; dy=-1; y=hb1-1; N[x*hb1+y]=N[(x+dx)*hb1+y+dy];\n\n y=0; dx= 0; dy= 1; for(x=0; x<wb1; x++) N[x*hb1+y]=N[(x+dx)*hb1+y+dy];\n\n y=hb1-1; dx= 0; dy=-1; for(x=0; x<wb1; x++) N[x*hb1+y]=N[(x+dx)*hb1+y+dy];\n\n return N;\n\n}\n\n\n\n// HOG helper: compute HOG or FHOG channels\n\nvoid hogChannels( float *H, const float *R, const float *N,\n\n int hb, int wb, int nOrients, float clip, int type )\n\n{\n\n #define GETT(blk) t=R1[y]*N1[y-(blk)]; if(t>clip) t=clip; c++;\n\n const float r=.2357f; int o, x, y, c; float t;\n\n const int nb=wb*hb, nbo=nOrients*nb, hb1=hb+1;\n", "file_path": "code/tool/edges-master/piotr_toolbox/channels/private/gradientMex.cpp", "rank": 63, "score": 12.049280026386862 }, { "content": " (id!=mxSINGLE_CLASS && id!=mxDOUBLE_CLASS && id!=mxUINT8_CLASS) )\n\n mexErrMsgTxt(\"A should be 2D or 3D single, double or uint8 array.\");\n\n if( !mxIsDouble(prhs[1]) ) mexErrMsgTxt(\"Input pad must be a double array.\");\n\n\n\n // extract padding amounts\n\n k = (int) mxGetNumberOfElements(prhs[1]);\n\n p = (double*) mxGetData(prhs[1]);\n\n if(k==1) { pt=pb=pl=pr=int(p[0]); }\n\n else if (k==2) { pt=pb=int(p[0]); pl=pr=int(p[1]); }\n\n else if (k==4) { pt=int(p[0]); pb=int(p[1]); pl=int(p[2]); pr=int(p[3]); }\n\n else mexErrMsgTxt( \"Input pad must have 1, 2, or 4 values.\");\n\n\n\n // figure out padding type (flag and val)\n\n if( !mxGetString(prhs[2],type,1024) ) {\n\n if(!strcmp(type,\"replicate\")) flag=1;\n\n else if(!strcmp(type,\"symmetric\")) flag=2;\n\n else if(!strcmp(type,\"circular\")) flag=3;\n\n else mexErrMsgTxt(\"Invalid pad value.\");\n\n } else {\n\n flag=0; val=(double)mxGetScalar(prhs[2]);\n", "file_path": "code/tool/edges-master/piotr_toolbox/channels/private/imPadMex.cpp", "rank": 64, "score": 12.014706210895774 }, { "content": "/*******************************************************************************\n\n* Piotr's Computer Vision Matlab Toolbox Version 3.00\n\n* Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]\n\n* Licensed under the Simplified BSD License [see external/bsd.txt]\n\n*******************************************************************************/\n\n#include \"wrappers.hpp\"\n\n#include \"string.h\"\n\ntypedef unsigned char uchar;\n\n\n\n// pad A by [pt,pb,pl,pr] and store result in B\n\ntemplate<class T> void imPad( T *A, T *B, int h, int w, int d, int pt, int pb,\n\n int pl, int pr, int flag, T val )\n\n{\n\n int h1=h+pt, hb=h1+pb, w1=w+pl, wb=w1+pr, x, y, z, mPad;\n\n int ct=0, cb=0, cl=0, cr=0;\n\n if(pt<0) { ct=-pt; pt=0; } if(pb<0) { h1+=pb; cb=-pb; pb=0; }\n\n if(pl<0) { cl=-pl; pl=0; } if(pr<0) { w1+=pr; cr=-pr; pr=0; }\n\n int *xs, *ys; x=pr>pl?pr:pl; y=pt>pb?pt:pb; mPad=x>y?x:y;\n\n bool useLookup = ((flag==2 || flag==3) && (mPad>h || mPad>w))\n\n || (flag==3 && (ct || cb || cl || cr ));\n", "file_path": "code/tool/edges-master/piotr_toolbox/channels/private/imPadMex.cpp", "rank": 65, "score": 11.988381855583533 }, { "content": "// compute HOG features\n\nvoid hog( float *M, float *O, float *H, int h, int w, int binSize,\n\n int nOrients, int softBin, bool full, float clip )\n\n{\n\n float *N, *R; const int hb=h/binSize, wb=w/binSize, nb=hb*wb;\n\n // compute unnormalized gradient histograms\n\n R = (float*) wrCalloc(wb*hb*nOrients,sizeof(float));\n\n gradHist( M, O, R, h, w, binSize, nOrients, softBin, full );\n\n // compute block normalization values\n\n N = hogNormMatrix( R, nOrients, hb, wb, binSize );\n\n // perform four normalizations per spatial block\n\n hogChannels( H, R, N, hb, wb, nOrients, clip, 0 );\n\n wrFree(N); wrFree(R);\n\n}\n\n\n\n// compute FHOG features\n\nvoid fhog( float *M, float *O, float *H, int h, int w, int binSize,\n\n int nOrients, int softBin, float clip )\n\n{\n\n const int hb=h/binSize, wb=w/binSize, nb=hb*wb, nbo=nb*nOrients;\n", "file_path": "code/tool/edges-master/piotr_toolbox/channels/private/gradientMex.cpp", "rank": 66, "score": 11.974564038160311 }, { "content": "/*******************************************************************************\n\n* Piotr's Computer Vision Matlab Toolbox Version 3.30\n\n* Copyright 2014 Piotr Dollar & Ron Appel. [pdollar-at-gmail.com]\n\n* Licensed under the Simplified BSD License [see external/bsd.txt]\n\n*******************************************************************************/\n\n#include \"wrappers.hpp\"\n\n#include <math.h>\n\n#include \"string.h\"\n\n#include \"sse.hpp\"\n\n\n\n#define PI 3.14159265f\n\n\n\n// compute x and y gradients for just one column (uses sse)\n\nvoid grad1( float *I, float *Gx, float *Gy, int h, int w, int x ) {\n\n int y, y1; float *Ip, *In, r; __m128 *_Ip, *_In, *_G, _r;\n\n // compute column of Gx\n\n Ip=I-h; In=I+h; r=.5f;\n\n if(x==0) { r=1; Ip+=h; } else if(x==w-1) { r=1; In-=h; }\n\n if( h<4 || h%4>0 || (size_t(I)&15) || (size_t(Gx)&15) ) {\n\n for( y=0; y<h; y++ ) *Gx++=(*In++-*Ip++)*r;\n", "file_path": "code/tool/edges-master/piotr_toolbox/channels/private/gradientMex.cpp", "rank": 67, "score": 11.930183663043954 }, { "content": " 0xff, 0xff, 0xff, 4,\n\n 0xff, 0xff, 0xff, 0) ;\n\n break ;\n\n }\n\n\n\n // we pull out these values as otherwise the compiler\n\n // will assume that the reference &image can be aliased\n\n // and recompute silly multiplications in the inner loop\n\n float * const __restrict imageMemory = image.getMemory() ;\n\n int const imageHeight = (int)shape.height ;\n\n int const imageWidth = (int)shape.width ;\n\n\n\n for (int x = 0 ; x < imageWidth ; x += blockSizeX) {\n\n int y = 0 ;\n\n float * __restrict imageMemoryX = imageMemory + x * imageHeight ;\n\n int bsx = (std::min)(imageWidth - x, blockSizeX) ;\n\n if (bsx < blockSizeX) goto boundary ;\n\n\n\n for ( ; y < imageHeight - blockSizeY + 1 ; y += blockSizeY) {\n\n char unsigned const * __restrict pixel = rgb + y * rowStride + x * pixelStride ;\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/impl/imread_helpers.hpp", "rank": 68, "score": 11.798379518675553 }, { "content": " checkArgs(nl,pl,nr,pr,1,3,2,8,&h,&w,&d,mxSINGLE_CLASS,(void**)&M);\n\n O = (float*) mxGetPr(pr[1]);\n\n if( mxGetM(pr[1])!=h || mxGetN(pr[1])!=w || d!=1 ||\n\n mxGetClassID(pr[1])!=mxSINGLE_CLASS ) mexErrMsgTxt(\"M or O is bad.\");\n\n binSize = (nr>=3) ? (int) mxGetScalar(pr[2]) : 8;\n\n nOrients = (nr>=4) ? (int) mxGetScalar(pr[3]) : 9;\n\n softBin = (nr>=5) ? (int) mxGetScalar(pr[4]) : 1;\n\n useHog = (nr>=6) ? (int) mxGetScalar(pr[5]) : 0;\n\n clipHog = (nr>=7) ? (float) mxGetScalar(pr[6]) : 0.2f;\n\n full = (nr>=8) ? (bool) (mxGetScalar(pr[7])>0) : false;\n\n hb = h/binSize; wb = w/binSize;\n\n nChns = useHog== 0 ? nOrients : (useHog==1 ? nOrients*4 : nOrients*3+5);\n\n pl[0] = mxCreateMatrix3(hb,wb,nChns,mxSINGLE_CLASS,1,(void**)&H);\n\n if( nOrients==0 ) return;\n\n if( useHog==0 ) {\n\n gradHist( M, O, H, h, w, binSize, nOrients, softBin, full );\n\n } else if(useHog==1) {\n\n hog( M, O, H, h, w, binSize, nOrients, softBin, full, clipHog );\n\n } else {\n\n fhog( M, O, H, h, w, binSize, nOrients, softBin, clipHog );\n", "file_path": "code/tool/edges-master/piotr_toolbox/channels/private/gradientMex.cpp", "rank": 69, "score": 11.780865340492795 }, { "content": "/*******************************************************************************\n\n* Piotr's Computer Vision Matlab Toolbox Version 3.24\n\n* Copyright 2014 Piotr Dollar & Ron Appel. [pdollar-at-gmail.com]\n\n* Licensed under the Simplified BSD License [see external/bsd.txt]\n\n*******************************************************************************/\n\n#include \"wrappers.hpp\"\n\n#include <string.h>\n\n#include \"sse.hpp\"\n\n\n\n// convolve one column of I by a 2rx1 ones filter\n\nvoid convBoxY( float *I, float *O, int h, int r, int s ) {\n\n float t; int j, p=r+1, q=2*h-(r+1), h0=r+1, h1=h-r, h2=h;\n\n t=0; for(j=0; j<=r; j++) t+=I[j]; t=2*t-I[r]; j=0;\n\n if( s==1 ) {\n\n for(; j<h0; j++) O[j]=t-=I[r-j]-I[r+j];\n\n for(; j<h1; j++) O[j]=t-=I[j-p]-I[r+j];\n\n for(; j<h2; j++) O[j]=t-=I[j-p]-I[q-j];\n\n } else {\n\n int k=(s-1)/2; h2=(h/s)*s; if(h0>h2) h0=h2; if(h1>h2) h1=h2;\n\n for(; j<h0; j++) { t-=I[r-j]-I[r+j]; k++; if(k==s) { k=0; *O++=t; } }\n", "file_path": "code/tool/edges-master/piotr_toolbox/channels/private/convConst.cpp", "rank": 70, "score": 11.753601513483888 }, { "content": " static unsigned hardware_concurrency();\n\n\n\n _TTHREAD_DISABLE_ASSIGNMENT(thread)\n\n\n\n private:\n\n native_handle_type mHandle; ///< Thread handle.\n\n mutable mutex mDataMutex; ///< Serializer for access to the thread private data.\n\n bool mNotAThread; ///< True if this object is not a thread of execution.\n\n#if defined(_TTHREAD_WIN32_)\n\n unsigned int mWin32ThreadID; ///< Unique thread ID (filled out by _beginthreadex).\n\n#endif\n\n\n\n // This is the internal thread wrapper function.\n\n#if defined(_TTHREAD_WIN32_)\n\n static unsigned WINAPI wrapper_function(void * aArg);\n\n#else\n\n static void * wrapper_function(void * aArg);\n\n#endif\n\n};\n\n\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/impl/tinythread.h", "rank": 71, "score": 11.736913930406462 }, { "content": " N1 = (int) mxGetM(prhs[1]);\n\n F = (int) mxGetNumberOfElements(prhs[6]);\n\n\n\n // ord0 and ord1 are optional\n\n if( nrhs<10 ) M0=M1=0; else {\n\n ord0 = (uint32*) mxGetData(prhs[8]);\n\n ord1 = (uint32*) mxGetData(prhs[9]);\n\n M0 = (int) mxGetNumberOfElements(prhs[8]);\n\n M1 = (int) mxGetNumberOfElements(prhs[9]);\n\n }\n\n\n\n // create output structure\n\n plhs[0] = mxCreateNumericMatrix(1,F,mxSINGLE_CLASS,mxREAL);\n\n plhs[1] = mxCreateNumericMatrix(1,F,mxUINT8_CLASS,mxREAL);\n\n float *errs = (float*) mxGetData(plhs[0]);\n\n uint8 *thrs = (uint8*) mxGetData(plhs[1]);\n\n\n\n // find lowest error for each feature\n\n #ifdef USEOMP\n\n nThreads = min(nThreads,omp_get_max_threads());\n", "file_path": "code/tool/edges-master/piotr_toolbox/classify/private/binaryTreeTrain1.cpp", "rank": 72, "score": 11.528800352562973 }, { "content": " int i, c, r; float e, o; if( !V._x ) return;\n\n int sId=_sId; scoreBox(box); int c0, r0, c1, r1;\n\n r1=clamp(box.r+box.h,0,h-1); r0=box.r=clamp(box.r,0,h-1);\n\n c1=clamp(box.c+box.w,0,w-1); c0=box.c=clamp(box.c,0,w-1);\n\n for( c=0; c<w; c++ ) for( r=0; r<h; r++ )\n\n V.val(c+w*0,r)=V.val(c+w*1,r)=V.val(c+w*2,r)=1;\n\n for( c=0; c<w; c++ ) for( r=0; r<h; r++ ) {\n\n i=_segIds.val(c,r); if(i<=0) continue; e = E.val(c,r);\n\n o = (_sDone._x[i]==sId) ? _sWts._x[_sMap._x[i]] :\n\n (_segC[i]>=c0 && _segC[i]<=c1 && _segR[i]>=r0 && _segR[i]<=r1 ) ? 0 : 1;\n\n V.val(c+w*0,r)=1-e+e*o; V.val(c+w*1,r)=1-e*o; V.val(c+w*2,r)=1-e;\n\n }\n\n // finally draw bounding box\n\n r=r0; for(c=c0; c<=c1; c++) V.val(c+w*0,r)=V.val(c+w*1,r)=V.val(c+w*2,r)=0;\n\n r=r1; for(c=c0; c<=c1; c++) V.val(c+w*0,r)=V.val(c+w*1,r)=V.val(c+w*2,r)=0;\n\n c=c0; for(r=r0; r<=r1; r++) V.val(c+w*0,r)=V.val(c+w*1,r)=V.val(c+w*2,r)=0;\n\n c=c1; for(r=r0; r<=r1; r++) V.val(c+w*0,r)=V.val(c+w*1,r)=V.val(c+w*2,r)=0;\n\n}\n\n\n\nvoid EdgeBoxGenerator::scoreAllBoxes( Boxes &boxes )\n", "file_path": "code/tool/edges-master/edges-master/private/edgeBoxesMex.cpp", "rank": 73, "score": 11.527533310301092 }, { "content": " for(; i<8; i++ ) if(N[i] && N[i]!=s) break; if(i==8) S[x*h+y]=s;\n\n }\n\n delete [] es; delete [] map;\n\n}\n\n\n\n// compute visualization of superpixels\n\nvoid visualize( float *V, uint *S, uint h, uint w, float *I, bool hasBnds ) {\n\n uint i, z, n=h*w;\n\n uint m=0; for( uint x=0; x<w*h; x++ ) m=S[x]>m ? S[x] : m; m++;\n\n float *clrs=new float[m]; uint *cnts=new uint[n];\n\n for( i=0; i<m; i++ ) cnts[i]=0;\n\n for( i=0; i<n; i++ ) cnts[S[i]]++;\n\n for( z=0; z<3; z++ ) {\n\n for( i=0; i<m; i++ ) clrs[i]=0;\n\n for( i=0; i<n; i++ ) clrs[S[i]]+=I[z*n+i];\n\n for( i=0; i<m; i++ ) clrs[i]/=cnts[i];\n\n if( hasBnds ) clrs[0]=0;\n\n for( i=0; i<n; i++ ) V[z*n+i]=clrs[S[i]];\n\n }\n\n delete [] clrs; delete [] cnts;\n", "file_path": "code/tool/edges-master/edges-master/private/spDetectMex.cpp", "rank": 74, "score": 11.243523310131419 }, { "content": " _cun=SET(13*un); _cvn=SET(13*vn);\n\n __m128 *_X, *_Y, *_Z, _x, _y, _z;\n\n _X=(__m128*) J1; _Y=(__m128*) (J1+n); _Z=(__m128*) (J1+2*n);\n\n for( i1=i; i1<n1; i1+=4 ) {\n\n _x = *_X; _y=*_Y; _z=*_Z;\n\n _z = RCP(ADD(_x,ADD(_cEps,ADD(MUL(_c15,_y),MUL(_c3,_z)))));\n\n *(_X++) = MUL(_c1024,_y);\n\n *(_Y++) = SUB(MUL(MUL(_c52,_x),_z),_cun);\n\n *(_Z++) = SUB(MUL(MUL(_c117,_y),_z),_cvn);\n\n }\n\n }\n\n { // perform lookup for L and finalize computation of U and V\n\n for( i1=i; i1<n1; i1++ ) J[i1] = lTable[(int)J[i1]];\n\n __m128 *_L, *_U, *_V, _l, _cminu, _cminv;\n\n _L=(__m128*) J1; _U=(__m128*) (J1+n); _V=(__m128*) (J1+2*n);\n\n _cminu=SET(minu); _cminv=SET(minv);\n\n for( i1=i; i1<n1; i1+=4 ) {\n\n _l = *(_L++);\n\n *_U = SUB(MUL(_l,*_U),_cminu); _U++;\n\n *_V = SUB(MUL(_l,*_V),_cminv); _V++;\n", "file_path": "code/tool/edges-master/piotr_toolbox/channels/private/rgbConvertMex.cpp", "rank": 75, "score": 11.236076027507687 }, { "content": " for (int x = 0 ; x < imageWidth ; x += blockSizeX) {\n\n float * __restrict imageMemoryX = imageMemory + x * imageHeight ;\n\n int bsx = (std::min)(imageWidth - x, blockSizeX) ;\n\n\n\n for (int y = 0 ; y < imageHeight ; y += blockSizeY) {\n\n int bsy = (std::min)(imageHeight - y, blockSizeY) ;\n\n float * __restrict r ;\n\n float * rend ;\n\n for (int dx = 0 ; dx < bsx ; ++dx) {\n\n char unsigned const * __restrict pixel = rgb + y * rowStride + (x + dx) * pixelStride ;\n\n r = imageMemoryX + y + dx * imageHeight ;\n\n rend = r + bsy ;\n\n while (r != rend) {\n\n switch (pixelFormat) {\n\n case pixelFormatRGBA:\n\n case pixelFormatRGB:\n\n r[0 * imagePlaneStride] = (float) pixel[0] ;\n\n r[1 * imagePlaneStride] = (float) pixel[1] ;\n\n r[2 * imagePlaneStride] = (float) pixel[2] ;\n\n break ;\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/impl/imread_helpers.hpp", "rank": 76, "score": 11.234413224306715 }, { "content": "//------------------------------------------------------------------------------\n\n// this_thread\n\n//------------------------------------------------------------------------------\n\n\n\nthread::id this_thread::get_id()\n\n{\n\n#if defined(_TTHREAD_WIN32_)\n\n return thread::id((unsigned long int) GetCurrentThreadId());\n\n#elif defined(_TTHREAD_POSIX_)\n\n return _pthread_t_to_ID(pthread_self());\n\n#endif\n\n}\n\n\n\n}\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/impl/tinythread.cpp", "rank": 78, "score": 11.156624170467033 }, { "content": " }\n\n }\n\n i = n1;\n\n }\n\n}\n\n\n\n// Convert from rgb to hsv\n\ntemplate<class iT, class oT> void rgb2hsv( iT *I, oT *J, int n, oT nrm ) {\n\n oT *H=J, *S=H+n, *V=S+n;\n\n iT *R=I, *G=R+n, *B=G+n;\n\n for(int i=0; i<n; i++) {\n\n const oT r=(oT)*(R++), g=(oT)*(G++), b=(oT)*(B++);\n\n oT h, s, v, minv, maxv;\n\n if( r==g && g==b ) {\n\n *(H++) = 0; *(S++) = 0; *(V++) = r*nrm; continue;\n\n } else if( r>=g && r>=b ) {\n\n maxv = r; minv = g<b ? g : b;\n\n h = (g-b)/(maxv-minv)+6; if(h>=6) h-=6;\n\n } else if( g>=r && g>=b ) {\n\n maxv = g; minv = r<b ? r : b;\n", "file_path": "code/tool/edges-master/piotr_toolbox/channels/private/rgbConvertMex.cpp", "rank": 79, "score": 11.152451074935108 }, { "content": " const int_t offset = 1023L << 52 ;\n\n int_t ai = *((int_t*)&a) ;\n\n *((int_t*)&z) = (int_t)(b * (ai - offset)) + offset ;\n\n return z ;\n\n}\n\n#endif\n\n\n\n#ifndef VERY_FAST\n\ninline float fast_pow(float x, float y)\n\n{\n\n float z ;\n\n float const plog3 = 0.164042561333445F ;\n\n float const plog2 = -0.606737602222409F ;\n\n float const plog1 = 1.442695040888963F ;\n\n float const pexp3 = 0.079441541679836F ;\n\n float const pexp2 = 0.227411277760219F ;\n\n float const pexp1 = 0.693147180559945F ;\n\n typedef int int_t;\n\n const int_t offset = 127 << 23 ;\n\n\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/impl/normalize_cpu.cpp", "rank": 80, "score": 11.151474144540089 }, { "content": " else if( flag==0 ) for(i=0; i<d/3; i++) rgb2gray(I+i*n*3,J+i*n*1,n,nrm);\n\n else if( flag==2 ) for(i=0; i<d/3; i++) rgb2luv(I+i*n*3,J+i*n*3,n,nrm);\n\n else if( flag==3 ) for(i=0; i<d/3; i++) rgb2hsv(I+i*n*3,J+i*n*3,n,nrm);\n\n else wrError(\"Unknown flag.\");\n\n return J;\n\n}\n\n\n\n// J = rgbConvertMex(I,flag,single); see rgbConvert.m for usage details\n\n#ifdef MATLAB_MEX_FILE\n\nvoid mexFunction(int nl, mxArray *pl[], int nr, const mxArray *pr[]) {\n\n const int *dims; int nDims, n, d, dims1[3]; void *I; void *J; int flag;\n\n bool single; mxClassID idIn, idOut;\n\n\n\n // Error checking\n\n if( nr!=3 ) mexErrMsgTxt(\"Three inputs expected.\");\n\n if( nl>1 ) mexErrMsgTxt(\"One output expected.\");\n\n dims = (const int*) mxGetDimensions(pr[0]); n=dims[0]*dims[1];\n\n nDims = mxGetNumberOfDimensions(pr[0]);\n\n d = 1; for( int i=2; i<nDims; i++ ) d*=dims[i];\n\n\n", "file_path": "code/tool/edges-master/piotr_toolbox/channels/private/rgbConvertMex.cpp", "rank": 81, "score": 11.006376289326436 }, { "content": "\n\n/* Todo: transpose */\n\n\n\ntemplate<typename type, typename Accumulator> static inline void\n\npooling_backward_cpu(type* derData,\n\n type const* data,\n\n type const* derPooled,\n\n size_t width, size_t height, size_t depth,\n\n size_t windowWidth, size_t windowHeight,\n\n size_t strideX, size_t strideY,\n\n size_t padLeft, size_t padRight, size_t padTop, size_t padBottom)\n\n{\n\n int pooledWidth = (width + (padLeft + padRight) - windowWidth)/strideX + 1 ;\n\n int pooledHeight = (height + (padTop + padBottom) - windowHeight)/strideY + 1 ;\n\n for (int z = 0; z < depth; ++z) {\n\n for (int y = 0; y < pooledHeight; ++y) {\n\n for (int x = 0; x < pooledWidth; ++x) {\n\n int x1 = x * (signed)strideX - (signed)padLeft ;\n\n int y1 = y * (signed)strideY - (signed)padTop ;\n\n int x2 = std::min(x1 + windowWidth, width) ;\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/impl/pooling_cpu.cpp", "rank": 82, "score": 10.961765087438943 }, { "content": " nDims=mxGetNumberOfDimensions(prhs[0]); id=mxGetClassID(prhs[0]);\n\n ns = (int*) mxGetDimensions(prhs[0]); nCh=(nDims==2) ? 1 : ns[2];\n\n if( (nDims!=2 && nDims!=3) ||\n\n (id!=mxSINGLE_CLASS && id!=mxDOUBLE_CLASS && id!=mxUINT8_CLASS) )\n\n mexErrMsgTxt(\"A should be 2D or 3D single, double or uint8 array.\");\n\n ms[0]=(int)mxGetScalar(prhs[1]); ms[1]=(int)mxGetScalar(prhs[2]); ms[2]=nCh;\n\n if( ms[0]<=0 || ms[1]<=0 ) mexErrMsgTxt(\"downsampling factor too small.\");\n\n nrm=(double)mxGetScalar(prhs[3]);\n\n\n\n // create output array\n\n plhs[0] = mxCreateNumericArray(3, (const mwSize*) ms, id, mxREAL);\n\n n=ns[0]*ns[1]*nCh; m=ms[0]*ms[1]*nCh;\n\n\n\n // perform resampling (w appropriate type)\n\n A=mxGetData(prhs[0]); B=mxGetData(plhs[0]);\n\n if( id==mxDOUBLE_CLASS ) {\n\n resample((double*)A, (double*)B, ns[0], ms[0], ns[1], ms[1], nCh, nrm);\n\n } else if( id==mxSINGLE_CLASS ) {\n\n resample((float*)A, (float*)B, ns[0], ms[0], ns[1], ms[1], nCh, float(nrm));\n\n } else if( id==mxUINT8_CLASS ) {\n", "file_path": "code/tool/edges-master/piotr_toolbox/channels/private/imResampleMex.cpp", "rank": 84, "score": 10.894072071024725 }, { "content": "#include <cassert>\n\n\n\n/* ---------------------------------------------------------------- */\n\n/* compute_moments, compute_ders, compute_ders_and_moments\t*/\n\n/* ---------------------------------------------------------------- */\n\n\n\n// Compute moments (means and sigmas) from the batch data\n\n// WH is the product of the data width and height\n\n// moments is a 2 x depth array with means and sigmas\n\n\n\ntemplate<typename T> inline void\n\ncompute_moments(T * moments,\n\n T const * data,\n\n int WH,\n\n int depth,\n\n int num,\n\n T epsilon)\n\n{\n\n int mass = WH * num ;\n\n for(int channel = 0; channel < depth; ++channel) {\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/impl/bnorm_cpu.cpp", "rank": 85, "score": 10.888085706098515 }, { "content": " else for( i=0; i<N; i++) cdf[data[i]] += wts[i];\n\n for(i=1; i<nBins; i++) cdf[i]+=cdf[i-1];\n\n}\n\n\n\n// [errs,thrs] = mexFunction( data0, data1, wts0, wts1,\n\n// nBins, prior, fids, nThreads, [ord0], [ord1] )\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n\n{\n\n // get inputs\n\n int nBins, nThreads, N0, N1, M0, M1, F; float prior, *wts0, *wts1;\n\n uint8 *data0, *data1; uint32 *fids, *ord0, *ord1;\n\n data0 = (uint8*) mxGetData(prhs[0]);\n\n data1 = (uint8*) mxGetData(prhs[1]);\n\n wts0 = (float*) mxGetData(prhs[2]);\n\n wts1 = (float*) mxGetData(prhs[3]);\n\n nBins = (int) mxGetScalar(prhs[4]);\n\n prior = (float) mxGetScalar(prhs[5]);\n\n fids = (uint32*) mxGetData(prhs[6]);\n\n nThreads = (int) mxGetScalar(prhs[7]);\n\n N0 = (int) mxGetM(prhs[0]);\n", "file_path": "code/tool/edges-master/piotr_toolbox/classify/private/binaryTreeTrain1.cpp", "rank": 86, "score": 10.824013030891447 }, { "content": " _segC.resize(_segCnt); _segR.resize(_segCnt);\n\n for( c=1; c<w-1; c++ ) for( r=1; r<h-1; r++ )\n\n if( (j=_segIds.val(c,r))>0 ) { _segC[j]=c; _segR[j]=r; }\n\n\n\n // optionally create visualization (assume memory initialized is 3*w*h)\n\n if( V._x ) for( c=0; c<w; c++ ) for( r=0; r<h; r++ ) {\n\n i=_segIds.val(c,r);\n\n V.val(c+w*0,r) = i<=0 ? 1 : ((123*i + 128)%255)/255.0f;\n\n V.val(c+w*1,r) = i<=0 ? 1 : ((7*i + 3)%255)/255.0f;\n\n V.val(c+w*2,r) = i<=0 ? 1 : ((174*i + 80)%255)/255.0f;\n\n }\n\n}\n\n\n\nvoid EdgeBoxGenerator::prepDataStructs( arrayf &E )\n\n{\n\n int c, r, i;\n\n\n\n // initialize step sizes\n\n _scStep=sqrt(1/_alpha);\n\n _arStep=(1+_alpha)/(2*_alpha);\n", "file_path": "code/tool/edges-master/edges-master/private/edgeBoxesMex.cpp", "rank": 87, "score": 10.784831744592655 }, { "content": "\n\n// E = mexFunction(E,O,r,s,m,nThreads)\n\nvoid mexFunction( int nl, mxArray *pl[], int nr, const mxArray *pr[] )\n\n{\n\n float *E0 = (float*) mxGetData(pr[0]); // original edge map\n\n float *O = (float*) mxGetData(pr[1]); // orientation map\n\n int r = (int) mxGetScalar(pr[2]); // radius for nms supr\n\n int s = (int) mxGetScalar(pr[3]); // radius for supr boundaries\n\n float m = (float) mxGetScalar(pr[4]); // multiplier for conservative supr\n\n int nThreads = (int) mxGetScalar(pr[5]); // number of threads for evaluation\n\n\n\n int h=(int) mxGetM(pr[0]), w=(int) mxGetN(pr[0]);\n\n pl[0] = mxCreateNumericMatrix(h,w,mxSINGLE_CLASS,mxREAL);\n\n float *E = (float*) mxGetData(pl[0]);\n\n\n\n // suppress edges where edge is stronger in orthogonal direction\n\n #ifdef USEOMP\n\n nThreads = nThreads<omp_get_max_threads() ? nThreads : omp_get_max_threads();\n\n #pragma omp parallel for num_threads(nThreads)\n\n #endif\n", "file_path": "code/tool/edges-master/edges-master/private/edgesNmsMex.cpp", "rank": 88, "score": 10.72960250858516 }, { "content": "\n\n // data structures for efficiency (see prepDataStructs)\n\n arrayf _segIImg, _magIImg; arrayi _hIdxImg, _vIdxImg;\n\n vector<vectori> _hIdxs, _vIdxs; vectorf _scaleNorm;\n\n float _scStep, _arStep, _rcStepRatio;\n\n\n\n // data structures for efficiency (see scoreBox)\n\n arrayf _sWts; arrayi _sDone, _sMap, _sIds; int _sId;\n\n\n\n // helper routines\n\n void clusterEdges( arrayf &E, arrayf &O, arrayf &V );\n\n void prepDataStructs( arrayf &E );\n\n void scoreAllBoxes( Boxes &boxes );\n\n void scoreBox( Box &box );\n\n void refineBox( Box &box );\n\n void drawBox( Box &box, arrayf &E, arrayf &V );\n\n};\n\n\n\n////////////////////////////////////////////////////////////////////////////////\n\n\n", "file_path": "code/tool/edges-master/edges-master/private/edgeBoxesMex.cpp", "rank": 89, "score": 10.713878203347724 }, { "content": "/*******************************************************************************\n\n* Piotr's Computer Vision Matlab Toolbox Version 3.01\n\n* Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]\n\n* Licensed under the Simplified BSD License [see external/bsd.txt]\n\n*******************************************************************************/\n\n#include \"string.h\"\n\n#include \"mex.h\"\n\n#include \"../../channels/private/sse.hpp\"\n\n\n\n// run nIter iterations of Horn & Schunk optical flow (alters Vx, Vy)\n\nvoid opticalFlowHsMex( float *Vx, float *Vy, const float *Ex, const float *Ey,\n\n const float *Et, const float *Z, const int h, const int w, const int nIter )\n\n{\n\n int x, y, x1, i, t, s; float my, mx, m, *Vx0, *Vy0;\n\n s=w*h*sizeof(float); Vx0=new float[s]; Vy0=new float[s];\n\n for( t=0; t<nIter; t++ ) {\n\n memcpy(Vx0,Vx,s); memcpy(Vy0,Vy,s);\n\n for( x=1; x<w-1; x++ ) {\n\n // do as much work as possible in SSE (assume non-aligned memory)\n\n for( y=1; y<h-4; y+=4 ) {\n", "file_path": "code/tool/edges-master/piotr_toolbox/videos/private/opticalFlowHsMex.cpp", "rank": 90, "score": 10.651787933544032 }, { "content": "void EdgeBoxGenerator::generate( Boxes &boxes, arrayf &E, arrayf &O, arrayf &V )\n\n{\n\n clusterEdges(E,O,V); prepDataStructs(E); scoreAllBoxes(boxes);\n\n}\n\n\n\nvoid EdgeBoxGenerator::clusterEdges( arrayf &E, arrayf &O, arrayf &V )\n\n{\n\n int c, r, cd, rd, i, j; h=E._h; w=E._w;\n\n\n\n // greedily merge connected edge pixels into clusters (create _segIds)\n\n _segIds.init(h,w); _segCnt=1;\n\n for( c=0; c<w; c++ ) for( r=0; r<h; r++ ) {\n\n if( c==0 || r==0 || c==w-1 || r==h-1 || E.val(c,r)<=_edgeMinMag )\n\n _segIds.val(c,r)=-1; else _segIds.val(c,r)=0;\n\n }\n\n for( c=1; c<w-1; c++ ) for( r=1; r<h-1; r++ ) {\n\n if(_segIds.val(c,r)!=0) continue;\n\n float sumv=0; int c0=c, r0=r; vectorf vs; vectori cs, rs;\n\n while( sumv < _edgeMergeThr ) {\n\n _segIds.val(c0,r0)=_segCnt;\n", "file_path": "code/tool/edges-master/edges-master/private/edgeBoxesMex.cpp", "rank": 91, "score": 10.643985205721226 }, { "content": "// For <, if zero returned, then compare keys\n\n// if non-zero X returned, then return X<0?1:0\n\n// For >, if zero returned, then compare keys\n\n// if non-zero X returned, then return X>0?1:0\n\n//***************************************************************************\n\n\n\n\n\n#include <cstdlib>\n\n#include <iostream>\n\n#include <cstdio>\n\n#include \"fibheap.h\"\n\nusing namespace std;\n\n\n\n//***************************************************************************\n\n//=========================================================\n\n// FibHeapNode Constructor\n\n//=========================================================\n\n//***************************************************************************\n\n\n\n//FibHeapNode::FibHeapNode() {\n", "file_path": "code/tool/edges-master/piotr_toolbox/matlab/private/fibheap.cpp", "rank": 92, "score": 10.482802457346253 }, { "content": " // V = visualize( S, I, hasBnds )\n\n float *I = (float*) mxGetData(pr[1]);\n\n bool hasBnds = mxGetScalar(pr[2])>0;\n\n const int dims[3] = {(int)h,(int)w,3};\n\n pl[0] = mxCreateNumericArray(3,dims,mxSINGLE_CLASS,mxREAL);\n\n float* V = (float*) mxGetData(pl[0]);\n\n visualize(V,S,h,w,I,hasBnds);\n\n\n\n } else if(!strcmp(action,\"affinities\")) {\n\n // A = affinities( S, E, segs, nThreads )\n\n float *E = (float*) mxGetData(pr[1]);\n\n uint8 *segs = (uint8*) mxGetData(pr[2]);\n\n uint nThreads = (uint) mxGetScalar(pr[3]);\n\n if( mxGetNumberOfDimensions(pr[2])!=5 ) mexErrMsgTxt(\"invalid input\");\n\n uint *dims = (uint*) mxGetDimensions(pr[2]);\n\n uint m=0; for( uint x=0; x<w*h; x++ ) m=S[x]>m ? S[x] : m;\n\n pl[0] = mxCreateNumericMatrix(m,m,mxSINGLE_CLASS,mxREAL);\n\n float *A = (float*) mxGetData(pl[0]);\n\n affinities(A,S,h,w,E,segs,dims,nThreads);\n\n\n", "file_path": "code/tool/edges-master/edges-master/private/spDetectMex.cpp", "rank": 93, "score": 10.426415966631154 }, { "content": " int v = u / windowWidth ;\n\n int z = v / windowHeight ;\n\n u %= windowWidth ;\n\n v %= windowHeight ;\n\n\n\n int x0 = static_min(numPatchesX, ceil_divide(padLeft - u * dilateX, strideX)) ;\n\n int y0 = static_min(numPatchesY, ceil_divide(padTop - v * dilateY, strideY)) ;\n\n int x1 = static_min(numPatchesX, floor_divide(width-1 + padLeft - u * dilateX, strideX) + 1) ;\n\n int y1 = static_min(numPatchesY, floor_divide(height-1 + padTop - v * dilateY, strideY) + 1) ;\n\n int x ;\n\n int y ;\n\n\n\n y = static_max(0, y0) ;\n\n stacked += numPatchesX * static_max(y, 0) ;\n\n for ( ; y < y1 ; ++y) {\n\n x = static_max(0, x0) ;\n\n int y_data = y * strideY + v * dilateY - padTop ;\n\n int x_data = x * strideX + u * dilateX - padLeft ;\n\n type * b = data + (z * height + y_data) * width + x_data ;\n\n stacked += x ;\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/impl/im2row_cpu.cpp", "rank": 94, "score": 10.403809281890076 }, { "content": "\n\n // convert to bbs\n\n plhs[0] = mxCreateNumericMatrix(m,5,mxDOUBLE_CLASS,mxREAL);\n\n double *bbs = (double*) mxGetData(plhs[0]);\n\n for( int i=0; i<m; i++ ) {\n\n bbs[i+0*m]=cs[i]*stride; bbs[i+2*m]=modelWd;\n\n bbs[i+1*m]=rs[i]*stride; bbs[i+3*m]=modelHt;\n\n bbs[i+4*m]=hs1[i];\n\n }\n\n}\n", "file_path": "code/tool/edges-master/piotr_toolbox/detector/private/acfDetect1.cpp", "rank": 95, "score": 10.330484660778035 }, { "content": " h = (b-r)/(maxv-minv)+2;\n\n } else {\n\n maxv = b; minv = r<g ? r : g;\n\n h = (r-g)/(maxv-minv)+4;\n\n }\n\n h*=(oT) (1/6.0); s=1-minv/maxv; v=maxv*nrm;\n\n *(H++) = h; *(S++) = s; *(V++) = v;\n\n }\n\n}\n\n\n\n// Convert from rgb to gray\n\ntemplate<class iT, class oT> void rgb2gray( iT *I, oT *J, int n, oT nrm ) {\n\n oT *GR=J; iT *R=I, *G=R+n, *B=G+n; int i;\n\n oT mr=(oT).2989360213*nrm, mg=(oT).5870430745*nrm, mb=(oT).1140209043*nrm;\n\n for(i=0; i<n; i++) *(GR++)=(oT)*(R++)*mr + (oT)*(G++)*mg + (oT)*(B++)*mb;\n\n}\n\n\n\n// Convert from rgb (double) to gray (float)\n\ntemplate<> void rgb2gray( double *I, float *J, int n, float nrm ) {\n\n float *GR=J; double *R=I, *G=R+n, *B=G+n; int i;\n", "file_path": "code/tool/edges-master/piotr_toolbox/channels/private/rgbConvertMex.cpp", "rank": 96, "score": 10.323354376258228 }, { "content": " PAD( x-pl+w, x-pl, x-pl-w, y-pt+h, y-pt, y-pt-h );\n\n }\n\n A += h*w; B += hb*wb;\n\n }\n\n if( useLookup ) { wrFree(xs); wrFree(ys); }\n\n #undef PAD\n\n}\n\n\n\n// B = imPadMex(A,pad,type); see imPad.m for usage details\n\n#ifdef MATLAB_MEX_FILE\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {\n\n int *ns, ms[3], nCh, nDims, pt, pb, pl, pr, flag, k; double *p;\n\n void *A, *B; mxClassID id; double val=0; char type[1024];\n\n\n\n // Error checking on arguments\n\n if( nrhs!=3 ) mexErrMsgTxt(\"Three inputs expected.\");\n\n if( nlhs>1 ) mexErrMsgTxt(\"One output expected.\");\n\n nDims=mxGetNumberOfDimensions(prhs[0]); id=mxGetClassID(prhs[0]);\n\n ns = (int*) mxGetDimensions(prhs[0]); nCh=(nDims==2) ? 1 : ns[2];\n\n if( (nDims!=2 && nDims!=3) ||\n", "file_path": "code/tool/edges-master/piotr_toolbox/channels/private/imPadMex.cpp", "rank": 97, "score": 10.32096684649171 }, { "content": " Tensor filters,\n\n Tensor derOutput,\n\n int strideX, int strideY,\n\n int padLeft, int padRight,\n\n int padTop, int padBottom,\n\n int dilateX, int dilateY) ;\n\n } ;\n\n\n\n} }\n\n#endif /* defined(__vl__nnconv_cudnn__) */\n", "file_path": "matconvnet-1.0-beta24/matlab/src/bits/impl/nnconv_cudnn.hpp", "rank": 98, "score": 10.193234668567513 }, { "content": " uint x=xi; NEIGHBORS8(S); uint i, s=L[0]; if(s==0) continue;\n\n if( N[0] && N[1] && N[2] && N[3] ) continue;\n\n for( i=0; i<8; i++ ) if(N[i] && N[i]!=s) { L[0]=0; break; }\n\n }\n\n // remove excess boundary pixels\n\n #ifdef USEOMP\n\n #pragma omp parallel for num_threads(nThreads)\n\n #endif\n\n for( int xi=0; xi<int(w); xi++ ) for( uint y=0; y<h; y++ ) {\n\n uint x=xi; NEIGHBORS8(S); uint i, s=L[0]; if(s!=0) continue;\n\n for( i=0; i<8; i++ ) if(N[i]) { s=L[0]=N[i]; break; }\n\n for( i=0; i<8; i++ ) if(N[i] && N[i]!=s) { L[0]=0; break; }\n\n }\n\n } else {\n\n // make S 0-indexed\n\n uint *T=new uint[h*w]; memcpy(T,S,h*w*sizeof(uint));\n\n #ifdef USEOMP\n\n #pragma omp parallel for num_threads(nThreads)\n\n #endif\n\n for( int xi=0; xi<int(w); xi++ ) for( uint y=0; y<h; y++ ) {\n", "file_path": "code/tool/edges-master/edges-master/private/spDetectMex.cpp", "rank": 99, "score": 10.173765227510799 } ]
C++
ios/samples/hello-ar/hello-ar/FilamentArView/FilamentApp.cpp
andykit/filament
f4f9f331c0882db6b58d1ec5ea2bb42ae9baf1d4
#include "FilamentApp.h" #include <filament/Camera.h> #include <filament/IndexBuffer.h> #include <filament/LightManager.h> #include <filament/Material.h> #include <filament/TransformManager.h> #include <filament/VertexBuffer.h> #include <filament/Viewport.h> #include <filameshio/MeshReader.h> #include <geometry/SurfaceOrientation.h> #include <ktxreader/Ktx1Reader.h> #include <sstream> #include "resources.h" using namespace filamesh; using namespace ktxreader; static constexpr float OBJECT_SCALE = 0.02f; FilamentApp::FilamentApp(void* nativeLayer, uint32_t width, uint32_t height) : nativeLayer(nativeLayer), width(width), height(height) { setupFilament(); setupCameraFeedTriangle(); setupIbl(); setupMaterial(); setupMesh(); setupView(); } void FilamentApp::render(const FilamentArFrame& frame) { app.cameraFeedTriangle->setCameraFeedTexture(frame.cameraImage); app.cameraFeedTriangle->setCameraFeedTransform(frame.cameraTextureTransform); camera->setModelMatrix(frame.view); camera->setCustomProjection(frame.projection, 0.01, 10); meshRotation *= quatf::fromAxisAngle(float3{1.0f, 0.5f, 0.2f}, 0.05); auto& tcm = engine->getTransformManager(); auto i = tcm.getInstance(app.renderable); tcm.setTransform(i, meshTransform * mat4f(meshRotation) * mat4f::scaling(OBJECT_SCALE)); if (renderer->beginFrame(swapChain)) { renderer->render(view); renderer->endFrame(); } } void FilamentApp::setObjectTransform(const mat4f& transform) { meshTransform = transform; } void FilamentApp::updatePlaneGeometry(const FilamentArPlaneGeometry& geometry) { auto& tcm = engine->getTransformManager(); if (!app.planeGeometry.isNull()) { scene->remove(app.planeGeometry); engine->destroy(app.planeGeometry); tcm.destroy(app.planeGeometry); EntityManager::get().destroy(1, &app.planeGeometry); } if (app.planeVertices) { engine->destroy(app.planeVertices); } if (app.planeIndices) { engine->destroy(app.planeIndices); } if (!app.shadowPlane) { app.shadowPlane = Material::Builder() .package(RESOURCES_SHADOW_PLANE_DATA, RESOURCES_SHADOW_PLANE_SIZE) .build(*engine); } const size_t vertexCount = geometry.vertexCount; const size_t indexCount = geometry.indexCount; quatf* quats = new quatf[vertexCount]; static float3 normals[1] = { float3(0, 1, 0) }; auto helper = geometry::SurfaceOrientation::Builder() .vertexCount(1) .normals(normals) .build(); helper->getQuats(quats, 1); delete helper; for (int i = 1; i < vertexCount; i++) { quats[i] = quats[0]; } float4* verts = (float4*) new uint8_t[vertexCount * sizeof(float4)]; uint16_t* indices = (uint16_t*) new uint8_t[indexCount * sizeof(uint16_t)]; std::copy(geometry.vertices, geometry.vertices + vertexCount, verts); std::copy(geometry.indices, geometry.indices + indexCount, indices); app.planeVertices = VertexBuffer::Builder() .vertexCount((uint32_t) vertexCount) .bufferCount(2) .attribute(VertexAttribute::POSITION, 0, VertexBuffer::AttributeType::FLOAT3, 0, sizeof(float4)) .attribute(VertexAttribute::TANGENTS, 1, VertexBuffer::AttributeType::FLOAT4, 0, sizeof(quatf)) .build(*engine); app.planeIndices = IndexBuffer::Builder() .indexCount((uint32_t) geometry.indexCount) .bufferType(IndexBuffer::IndexType::USHORT) .build(*engine); const auto deleter = [](void* buffer, size_t size, void* user) { delete (uint8_t*) buffer; }; VertexBuffer::BufferDescriptor positionBuffer(verts, vertexCount * sizeof(float4), deleter); VertexBuffer::BufferDescriptor tangentbuffer(quats, vertexCount * sizeof(quatf), deleter); IndexBuffer::BufferDescriptor indexBuffer(indices, indexCount * sizeof(uint16_t), deleter); app.planeVertices->setBufferAt(*engine, 0, std::move(positionBuffer)); app.planeVertices->setBufferAt(*engine, 1, std::move(tangentbuffer)); app.planeIndices->setBuffer(*engine, std::move(indexBuffer)); Box aabb = RenderableManager::computeAABB((float4*) geometry.vertices, (uint16_t*) geometry.indices, geometry.vertexCount); EntityManager::get().create(1, &app.planeGeometry); RenderableManager::Builder(1) .boundingBox(aabb) .receiveShadows(true) .material(0, app.shadowPlane->getDefaultInstance()) .geometry(0, RenderableManager::PrimitiveType::TRIANGLES, app.planeVertices, app.planeIndices, 0, geometry.indexCount) .build(*engine, app.planeGeometry); auto& rcm = engine->getRenderableManager(); rcm.setReceiveShadows(rcm.getInstance(app.planeGeometry), true); tcm.create(app.planeGeometry); auto i = tcm.getInstance(app.planeGeometry); tcm.setTransform(i, geometry.transform); scene->addEntity(app.planeGeometry); } FilamentApp::~FilamentApp() { delete app.cameraFeedTriangle; engine->destroy(app.materialInstance); engine->destroy(app.mat); engine->destroy(app.indirectLight); engine->destroy(app.iblTexture); engine->destroy(app.renderable); engine->destroy(app.sun); engine->destroy(app.shadowPlane); engine->destroy(renderer); engine->destroy(scene); engine->destroy(view); Entity c = camera->getEntity(); engine->destroyCameraComponent(c); EntityManager::get().destroy(c); engine->destroy(swapChain); engine->destroy(&engine); } void FilamentApp::setupFilament() { #if FILAMENT_APP_USE_OPENGL engine = Engine::create(filament::Engine::Backend::OPENGL); #elif FILAMENT_APP_USE_METAL engine = Engine::create(filament::Engine::Backend::METAL); #endif swapChain = engine->createSwapChain(nativeLayer); renderer = engine->createRenderer(); scene = engine->createScene(); Entity c = EntityManager::get().create(); camera = engine->createCamera(c); camera->setProjection(60, (float) width / height, 0.1, 10); } void FilamentApp::setupIbl() { image::Ktx1Bundle* iblBundle = new image::Ktx1Bundle(RESOURCES_VENETIAN_CROSSROADS_2K_IBL_DATA, RESOURCES_VENETIAN_CROSSROADS_2K_IBL_SIZE); float3 harmonics[9]; iblBundle->getSphericalHarmonics(harmonics); app.iblTexture = Ktx1Reader::createTexture(engine, iblBundle, false); app.indirectLight = IndirectLight::Builder() .reflections(app.iblTexture) .irradiance(3, harmonics) .intensity(30000) .build(*engine); scene->setIndirectLight(app.indirectLight); app.sun = EntityManager::get().create(); LightManager::Builder(LightManager::Type::SUN) .castShadows(true) .direction({0.0, -1.0, 0.0}) .build(*engine, app.sun); scene->addEntity(app.sun); } void FilamentApp::setupMaterial() { app.mat = Material::Builder() .package(RESOURCES_CLEAR_COAT_DATA, RESOURCES_CLEAR_COAT_SIZE) .build(*engine); app.materialInstance = app.mat->createInstance(); } void FilamentApp::setupMesh() { MeshReader::Mesh mesh = MeshReader::loadMeshFromBuffer(engine, RESOURCES_CUBE_DATA, nullptr, nullptr, app.materialInstance); app.materialInstance->setParameter("baseColor", RgbType::sRGB, {0.71f, 0.0f, 0.0f}); app.renderable = mesh.renderable; scene->addEntity(app.renderable); auto& rcm = engine->getRenderableManager(); rcm.setCastShadows(rcm.getInstance(app.renderable), true); auto& tcm = engine->getTransformManager(); tcm.create(app.renderable); auto i = tcm.getInstance(app.renderable); tcm.setTransform(i, mat4f::translation(float3{0.0f, 0.0f, -2.0f}) * mat4f::scaling(OBJECT_SCALE)); } void FilamentApp::setupView() { view = engine->createView(); view->setScene(scene); view->setCamera(camera); view->setViewport(Viewport(0, 0, width, height)); } void FilamentApp::setupCameraFeedTriangle() { app.cameraFeedTriangle = new FullScreenTriangle(engine); scene->addEntity(app.cameraFeedTriangle->getEntity()); }
#include "FilamentApp.h" #include <filament/Camera.h> #include <filament/IndexBuffer.h> #include <filament/LightManager.h> #include <filament/Material.h> #include <filament/TransformManager.h> #include <filament/VertexBuffer.h> #include <filament/Viewport.h> #include <filameshio/MeshReader.h> #include <geometry/SurfaceOrientation.h> #include <ktxreader/Ktx1Reader.h> #include <sstream> #include "resources.h" using namespace filamesh; using namespace ktxreader; static constexpr float OBJECT_SCALE = 0.02f; FilamentApp::FilamentApp(void* nativeLayer, uint32_t width, uint32_t height) : nativeLayer(nativeLayer), width(width), height(height) { setupFilament(); setupCameraFeedTriangle(); setupIbl(); setupMaterial(); setupMesh(); setupView(); } void FilamentApp::render(const FilamentArFrame& frame) { app.cameraFeedTriangle->setCameraFeedTexture(frame.cameraImage); app.cameraFeedTriangle->setCameraFeedTransform(frame.cameraTextureTransform); camera->setModelMatrix(frame.view); camera->setCustomProjection(frame.projection, 0.01, 10); meshRotation *= quatf::fromAxisAngle(float3{1.0f, 0.5f, 0.2f}, 0.05); auto& tcm = engine->getTransformManager(); auto i = tcm.getInstance(app.renderable); tcm.setTransform(i, meshTransform * mat4f(meshRotation) * mat4f::scaling(OBJECT_SCALE)); if (renderer->beginFrame(swapChain)) { renderer->render(view); renderer->endFrame(); } } void FilamentApp::setObjectTransform(const mat4f& transform) { meshTransform = transform; } void FilamentApp::updatePlaneGeometry(const FilamentArPlaneGeometry& geometry) { auto& tcm = engine->getTransformManager(); if (!app.planeGeometry.isNull()) { scene->remove(app.planeGeometry); engine->destroy(app.planeGeometry); tcm.destroy(app.planeGeometry); EntityManager::get().destroy(1, &app.planeGeometry); } if (app.planeVertices) { engine->destroy(app.planeVertices); } if (app.planeIndices) { engine->destroy(app.planeIndices); } if (!app.shadowPlane) { app.shadowPlane = Material::Builder() .package(RESOURCES_SHADOW_PLANE_DATA, RESOURCES_SHADOW_PLANE_SIZE) .build(*engine); } const size_t vertexCount = geometry.vertexCount; const size_t indexCount = geometry.indexCount; quatf* quats = new quatf[vertexCount]; static float3 normals[1] = { float3(0, 1, 0) }; auto helper = geometry::SurfaceOrientation::Builder() .vertexCount(1) .normals(normals) .build(); helper->getQuats(quats, 1); delete helper; for (int i = 1; i < vertexCount; i++) { quats[i] = quats[0]; } float4* verts = (float4*) new uint8_t[vertexCount * sizeof(float4)]; uint16_t* indices = (uint16_t*) new uint8_t[indexCount * sizeof(uint16_t)]; std::copy(geometry.vertices, geometry.vertices + vertexCount, verts); std::copy(geometry.indices, geometry.indices + indexCount, indices); app.planeVertices = VertexBuffer::Builder() .vertexCount((uint32_t) vertexCount) .bufferCount(2) .attribute(VertexAttribute::POSITION, 0, VertexBuffer::AttributeType::FLOAT3, 0, sizeof(float4)) .attribute(VertexAttribute::TANGENTS, 1, VertexBuffer::AttributeType::FLOAT4, 0, sizeof(quatf)) .build(*engine); app.planeIndices = IndexBuffer::Builder() .indexCount((uint32_t) geometry.indexCount) .bufferType(IndexBuffer::IndexType::USHORT) .build(*engine); const auto deleter = [](void* buffer, size_t size, void* user) { delete (uint8_t*) buffer; }; VertexBuffer::BufferDescriptor positionBuffer(verts, vertexCount * sizeof(float4), deleter); VertexBuffer::BufferDescriptor tangentbuffer(quats, vertexCount * sizeof(quatf), deleter); IndexBuffer::BufferDescriptor indexBuffer(indices, indexCount * sizeof(uint16_t), deleter); app.planeVertices->setBufferAt(*engine, 0, std::move(positionBuffer)); app.planeVertices->setBufferAt(*engine, 1, std::move(tangentbuffer)); app.planeIndices->setBuffer(*engine, std::move(indexBuffer)); Box aabb = RenderableManager::computeAABB((float4*) geometry.vertices, (uint16_t*) geometry.indices, geometry.vertexCount); EntityManager::get().create(1, &app.planeGeometry); RenderableManager::Builder(1) .boundingBox(aabb) .receiveShadows(true) .material(0, app.shadowPlane->getDefaultInstance()) .geometry(0, RenderableManager::PrimitiveType::TRIANGLES, app.planeVertices, app.planeIndices, 0, geometry.indexCount) .build(*engine, app.planeGeometry); auto& rcm = engine->getRenderableManager(); rcm.setReceiveShadows(rcm.getInstance(app.planeGeometry), true); tcm.create(app.planeGeometry); auto i = tcm.getInstance(app.planeGeometry); tcm.setTransform(i, geometry.transform); scene->addEntity(app.planeGeometry); } FilamentApp::~FilamentApp() { delete app.cameraFeedTriangle; engine->destroy(app.materialInstance); engine->destroy(app.mat); engine->destroy(app.indirectLight); engine->destroy(app.iblTexture); engine->destroy(app.renderable); engine->destroy(app.sun); engine->destroy(app.shadowPlane); engine->destroy(renderer); engine->destroy(scene); engine->destroy(view); Entity c = camera->getEntity(); engine->destroyCameraComponent(c); EntityManager::get().destroy(c); engine->destroy(swapChain); engine->destroy(&engine); } void FilamentApp::setupFilament() { #if FILAMENT_APP_USE_OPENGL engine = Engine::create(filament::Engine::Backend::OPENGL); #elif FILAMENT_APP_USE_METAL engine = Engine::create(filament::Engine::Backend::METAL); #endif swapChain = engine->createSwapChain(nativeLayer); renderer = engine->createRenderer(); scene = engine->createScene(); Entity c = EntityManager::get().create(); camera = engine->createCamera(c); camera->setProjection(60, (float) width / height, 0.1, 10); } void FilamentApp::setupIbl() { image::Ktx1Bundle* iblBundle = new image::Ktx1Bundle(RESOURCES_VENETIAN_CROSSROADS_2K_IBL_DATA, RESOURCES_VENETIAN_CROSSROADS_2K_IBL_SIZE); float3 harmonics[9]; iblBundle->getSphericalHarmonics(harmonics); app.iblTexture = Ktx1Reader::createTexture(engine, iblBundle, false); app.indirectLight = IndirectLight::Builder() .reflections(app.iblTexture) .irradiance(3, harmonics) .intensity(30000) .build(*engine); scene->setIndirectLight(app.indirectLight); app.sun = EntityManager::get().create(); LightManager::Builder(LightManager::Type::SUN) .castShadows(true) .direction({0.0, -1.0, 0.0}) .build(*engine, app.sun); scene->addEntity(app.sun); }
void FilamentApp::setupMesh() { MeshReader::Mesh mesh = MeshReader::loadMeshFromBuffer(engine, RESOURCES_CUBE_DATA, nullptr, nullptr, app.materialInstance); app.materialInstance->setParameter("baseColor", RgbType::sRGB, {0.71f, 0.0f, 0.0f}); app.renderable = mesh.renderable; scene->addEntity(app.renderable); auto& rcm = engine->getRenderableManager(); rcm.setCastShadows(rcm.getInstance(app.renderable), true); auto& tcm = engine->getTransformManager(); tcm.create(app.renderable); auto i = tcm.getInstance(app.renderable); tcm.setTransform(i, mat4f::translation(float3{0.0f, 0.0f, -2.0f}) * mat4f::scaling(OBJECT_SCALE)); } void FilamentApp::setupView() { view = engine->createView(); view->setScene(scene); view->setCamera(camera); view->setViewport(Viewport(0, 0, width, height)); } void FilamentApp::setupCameraFeedTriangle() { app.cameraFeedTriangle = new FullScreenTriangle(engine); scene->addEntity(app.cameraFeedTriangle->getEntity()); }
void FilamentApp::setupMaterial() { app.mat = Material::Builder() .package(RESOURCES_CLEAR_COAT_DATA, RESOURCES_CLEAR_COAT_SIZE) .build(*engine); app.materialInstance = app.mat->createInstance(); }
function_block-full_function
[]
C++
ReactNativeFrontend/ios/Pods/boost/boost/contract/detail/decl.hpp
Harshitha91/Tmdb-react-native-node
e06e3f25a7ee6946ef07a1f524fdf62e48424293
#ifndef BOOST_CONTRACT_DETAIL_DECL_HPP_ #define BOOST_CONTRACT_DETAIL_DECL_HPP_ #include <boost/contract/detail/tvariadic.hpp> #if !BOOST_CONTRACT_DETAIL_TVARIADIC #include <boost/contract/core/config.hpp> #include <boost/preprocessor/repetition/repeat.hpp> #include <boost/preprocessor/tuple/elem.hpp> #include <boost/preprocessor/arithmetic/inc.hpp> #endif #include <boost/preprocessor/control/expr_iif.hpp> #include <boost/preprocessor/control/iif.hpp> #include <boost/preprocessor/punctuation/comma_if.hpp> #define BOOST_CONTRACT_DETAIL_DECL_OVERRIDING_PUBLIC_FUNCTION_Z(z, \ arity, is_friend, has_result, \ O, VR, F, C, Args, \ v, r, f, obj, args \ ) \ template< \ class O \ BOOST_PP_COMMA_IF(has_result) \ BOOST_PP_EXPR_IIF(has_result, typename VR) \ , typename F \ , class C \ BOOST_CONTRACT_DETAIL_TVARIADIC_COMMA(arity) \ BOOST_CONTRACT_DETAIL_TVARIADIC_TPARAMS_Z(z, arity, Args) \ > \ BOOST_PP_EXPR_IIF(is_friend, friend) \ boost::contract::specify_precondition_old_postcondition_except< \ BOOST_PP_EXPR_IIF(has_result, VR)> \ \ public_function( \ boost::contract::virtual_* v \ BOOST_PP_COMMA_IF(has_result) \ BOOST_PP_EXPR_IIF(has_result, VR& r) \ , F f \ , C* obj \ BOOST_CONTRACT_DETAIL_TVARIADIC_COMMA(arity) \ BOOST_CONTRACT_DETAIL_TVARIADIC_FPARAMS_Z(z, arity, Args, &, args) \ ) #if BOOST_CONTRACT_DETAIL_TVARIADIC #define BOOST_CONTRACT_DETAIL_DECL_FRIEND_OVERRIDING_PUBLIC_FUNCTIONS_Z(z, \ O, VR, F, C, Args, \ v, r, f, obj, args \ ) \ BOOST_CONTRACT_DETAIL_DECL_OVERRIDING_PUBLIC_FUNCTION_Z(z, \ ~, 1, 0, \ O, VR, F, C, Args, v, r, f, obj, args \ ); \ BOOST_CONTRACT_DETAIL_DECL_OVERRIDING_PUBLIC_FUNCTION_Z(z, \ ~, 1, 1, \ O, VR, F, C, Args, v, r, f, obj, args \ ); #else #define BOOST_CONTRACT_DETAIL_DECL_FRIEND_OVERRIDING_PUBLIC_FUNCTION_( \ z, n, result_O_R_F_C_Args_v_r_f_obj_args) \ BOOST_CONTRACT_DETAIL_DECL_OVERRIDING_PUBLIC_FUNCTION_Z(z, \ n, \ 1, \ BOOST_PP_TUPLE_ELEM(11, 0, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 1, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 2, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 3, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 4, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 5, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 6, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 7, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 8, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 9, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 10, result_O_R_F_C_Args_v_r_f_obj_args) \ ); #define BOOST_CONTRACT_DETAIL_DECL_FRIEND_OVERRIDING_PUBLIC_FUNCTIONS_Z(z, \ O, VR, F, C, Args, \ v, r, f, obj, args \ ) \ BOOST_PP_REPEAT_ ## z( \ BOOST_PP_INC(BOOST_CONTRACT_MAX_ARGS), \ BOOST_CONTRACT_DETAIL_DECL_FRIEND_OVERRIDING_PUBLIC_FUNCTION_, \ ( 0, O, VR, F, C, Args, v, r, f, obj, args) \ ) \ BOOST_PP_REPEAT_ ## z( \ BOOST_PP_INC(BOOST_CONTRACT_MAX_ARGS), \ BOOST_CONTRACT_DETAIL_DECL_FRIEND_OVERRIDING_PUBLIC_FUNCTION_, \ ( 1, O, VR, F, C, Args, v, r, f, obj, args) \ ) #endif #define BOOST_CONTRACT_DETAIL_DECL_DETAIL_COND_SUBCONTRACTING_Z( \ z, is_friend, O, VR, F, C, Args) \ template< \ class O, typename VR, typename F, class C \ BOOST_CONTRACT_DETAIL_TVARIADIC_COMMA(BOOST_CONTRACT_MAX_ARGS) \ BOOST_CONTRACT_DETAIL_TVARIADIC_TPARAMS_Z(z, \ BOOST_CONTRACT_MAX_ARGS, Args) \ > \ BOOST_PP_IIF(is_friend, \ friend class boost::contract::detail:: \ , \ class \ ) \ cond_subcontracting namespace boost { namespace contract { class virtual_; template<typename VR = void> class specify_precondition_old_postcondition_except; } } #endif
#ifndef BOOST_CONTRACT_DETAIL_DECL_HPP_ #define BOOST_CONTRACT_DETAIL_DECL_HPP_ #include <boost/contract/detail/tvariadic.hpp> #if !BOOST_CONTRACT_DETAIL_TVARIADIC #include <boost/contract/core/config.hpp> #include <boost/preprocessor/repetition/repeat.hpp> #include <boost/preprocessor/tuple/elem.hpp> #include <boost/preprocessor/arithmetic/inc.hpp> #endif #include <boost/preprocessor/control/expr_iif.hpp> #include <boost/preprocessor/control/iif.hpp> #include <boost/preprocessor/punctuation/comma_if.hpp> #define BOOST_CONTRACT_DETAIL_DECL_OVERRIDING_PUBLIC_FUNCTION_Z(z, \ arity, is_friend, has_result, \ O, VR, F, C, Args, \ v, r, f, obj, args \ ) \ template< \ class O \ BOOST_PP_COMMA_IF(has_result) \ BOOST_PP_EXPR_IIF(has_result, typename VR) \ , typename F \ , class C \ BOOST_CONTRACT_DETAIL_TVARIADIC_COMMA(arity) \ BOOST_CONTRACT_DETAIL_TVARIADIC_TPARAMS_Z(z, arity, Args) \ > \ BOOST_PP_EXPR_IIF(is_friend, friend) \ boost::contract::specify_precondition_old_postcondition_except< \ BOOST_PP_EXPR_IIF(has_result, VR)> \ \ public_function( \ boost::contract::virtual_* v \ BOOST_PP_COMMA_IF(has_result) \ BOOST_PP_EXPR_IIF(has_result, VR& r) \ , F f \ , C* obj \ BOOST_CONTRACT_DETAIL_TVARIADIC_COMMA(arity) \ BOOST_CONTRACT_DETAIL_TVARIADIC_FPARAMS_Z(z, arity, Args, &, args) \ ) #if BOOST_CONTRACT_DETAIL_TVARIADIC #define BOOST_CONTRACT_DETAIL_DECL_FRIEND_OVERRIDING_PUBLIC_FUNCTIONS_Z(z, \ O, VR, F, C, Args, \ v, r, f, obj, args \ ) \ BOOST_CONTRACT_DETAIL_DECL_OVERRIDING_PUBLIC_FUNCTION_Z(z, \ ~, 1, 0, \ O, VR, F, C, Args, v, r, f, obj, args \ ); \ BOOST_CONTRACT_DETAIL_DECL_OVERRIDING_PUBLIC_FUNCTION_Z(z, \ ~, 1, 1, \ O, VR, F, C, Args, v, r, f, obj, args \ ); #else #define BOOST_CONTRACT_DETAIL_DECL_FRIEND_OVERRIDING_PUBLIC_FUNCTION_( \ z, n, result_O_R_F_C_Args_v_r_f_obj_args) \ BOOST_CONTRACT_DETAIL_DECL_OVERRIDING_PUBLIC_FUNCTION_Z(z, \ n, \ 1, \ BOOST_PP_TUPLE_ELEM(11, 0, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 1, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 2, res
\ BOOST_PP_REPEAT_ ## z( \ BOOST_PP_INC(BOOST_CONTRACT_MAX_ARGS), \ BOOST_CONTRACT_DETAIL_DECL_FRIEND_OVERRIDING_PUBLIC_FUNCTION_, \ ( 0, O, VR, F, C, Args, v, r, f, obj, args) \ ) \ BOOST_PP_REPEAT_ ## z( \ BOOST_PP_INC(BOOST_CONTRACT_MAX_ARGS), \ BOOST_CONTRACT_DETAIL_DECL_FRIEND_OVERRIDING_PUBLIC_FUNCTION_, \ ( 1, O, VR, F, C, Args, v, r, f, obj, args) \ ) #endif #define BOOST_CONTRACT_DETAIL_DECL_DETAIL_COND_SUBCONTRACTING_Z( \ z, is_friend, O, VR, F, C, Args) \ template< \ class O, typename VR, typename F, class C \ BOOST_CONTRACT_DETAIL_TVARIADIC_COMMA(BOOST_CONTRACT_MAX_ARGS) \ BOOST_CONTRACT_DETAIL_TVARIADIC_TPARAMS_Z(z, \ BOOST_CONTRACT_MAX_ARGS, Args) \ > \ BOOST_PP_IIF(is_friend, \ friend class boost::contract::detail:: \ , \ class \ ) \ cond_subcontracting namespace boost { namespace contract { class virtual_; template<typename VR = void> class specify_precondition_old_postcondition_except; } } #endif
ult_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 3, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 4, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 5, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 6, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 7, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 8, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 9, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 10, result_O_R_F_C_Args_v_r_f_obj_args) \ ); #define BOOST_CONTRACT_DETAIL_DECL_FRIEND_OVERRIDING_PUBLIC_FUNCTIONS_Z(z, \ O, VR, F, C, Args, \ v, r, f, obj, args \ )
random
[]
C++
sdk/rms_sdk/Platform/Http/HttpClientQt.cpp
AzureAD/rms-sdk-for-cpp
0e5d54a030008c5c0f70d8d3d0695fa0722b6ab6
#ifdef QTFRAMEWORK #include "HttpClientQt.h" #include <QThread> #include <QMutex> #include <QEventLoop> #include <QCoreApplication> #include <QTimer> #include <QNetworkProxyFactory> #include "../Logger/Logger.h" #include "../../ModernAPI/RMSExceptions.h" #include "mscertificates.h" #include "HttpClientQt.h" using namespace std; using namespace rmscore::platform::logger; namespace rmscore { namespace platform { namespace http { common::ByteArray ReadAllBytes(QIODevice *from) { common::ByteArray result; auto bytesAvailable = from->bytesAvailable(); if (bytesAvailable > 0) { result.resize(static_cast<size_t>(bytesAvailable)); char *buf = reinterpret_cast<char *>(&result[0]); size_t offset = 0; while (bytesAvailable > 0) { auto read = from->read(&buf[offset], bytesAvailable); if (read <= 0) break; bytesAvailable -= read; offset += read; } } return result; } shared_ptr<IHttpClient> doCreate() { static bool initialized = false; if (!initialized) { QSslConfiguration SslConfiguration(QSslConfiguration::defaultConfiguration()); QList<QSslCertificate> certificates = SslConfiguration.caCertificates(); certificates.append(QSslCertificate::fromData(MicrosoftCertCA)); certificates.append(QSslCertificate::fromData(MicrosoftCertSubCA)); SslConfiguration.setCaCertificates(certificates); QSslConfiguration::setDefaultConfiguration(SslConfiguration); initialized = true; } return make_shared<HttpClientQt>(); } shared_ptr<IHttpClient> IHttpClient::Create() { if(!QCoreApplication::instance()) { int argc = 1; char name[] = "IHttpClient::Create"; char* argv = &name[0]; QCoreApplication a(argc, &argv); return doCreate(); } return doCreate(); } HttpClientQt::HttpClientQt() : lastReply_(nullptr) { this->request_.setSslConfiguration(QSslConfiguration::defaultConfiguration()); QNetworkProxyFactory::setUseSystemConfiguration(true); } HttpClientQt::~HttpClientQt() {} void HttpClientQt::AddAuthorizationHeader(const string& authToken) { this->AddHeader("Authorization", authToken); } void HttpClientQt::AddAcceptMediaTypeHeader(const string& mediaType) { this->AddHeader("Accept", mediaType); } void HttpClientQt::AddAcceptLanguageHeader(const string& language) { this->AddHeader("Accept-Language", language); } void HttpClientQt::AddHeader(const string& headerName, const string& headerValue) { this->request_.setRawHeader(headerName.c_str(), headerValue.c_str()); } StatusCode HttpClientQt::doPost(const string& url, const common::ByteArray& request, const string& mediaType, common::ByteArray& response, std::shared_ptr<std::atomic<bool> >cancelState) { Logger::Info("==> PostWithCoreAppContext %s", url.data()); this->request_.setUrl(QUrl(url.c_str())); this->AddAcceptMediaTypeHeader(mediaType); Logger::Hidden("==> Request Headers:"); foreach(const QByteArray &hdrName, this->request_.rawHeaderList()) { QByteArray hdrValue = this->request_.rawHeader(hdrName); Logger::Hidden("%s : %s", hdrName.data(), hdrValue.data()); } std::string req(request.begin(), request.end()); Logger::Hidden("==> Request Body: %s", req.c_str()); lastReply_ = this->manager_.post( this->request_, QByteArray(reinterpret_cast<const char *>(request.data()), static_cast<int>(request.size()))); QTimer timer; QEventLoop loop; QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit())); QObject::connect(lastReply_, SIGNAL(finished()), &loop, SLOT(quit())); QObject::connect(lastReply_, &QNetworkReply::sslErrors, [ = ](QList<QSslError>errorList) { for (auto& error : errorList) { Logger::Error("QSslError: %s", error.errorString().toStdString().c_str()); throw exceptions::RMSNetworkException( error.errorString().toStdString(), exceptions::RMSNetworkException::ServerError); } }); do { timer.start(500); loop.exec(); if ((cancelState != nullptr) && cancelState->load()) { throw exceptions::RMSNetworkException( "Network operation was cancelled by user", exceptions::RMSNetworkException::CancelledByUser); } } while (!timer.isActive() || !lastReply_->isFinished()); QVariant statusCode = lastReply_->attribute( QNetworkRequest::HttpStatusCodeAttribute); Logger::Info("Response StatusCode: %i", statusCode.toInt()); Logger::Hidden("--> Response Headers:"); foreach(const QNetworkReply::RawHeaderPair & pair, lastReply_->rawHeaderPairs()) { Logger::Hidden("%s : %s", pair.first.data(), pair.second.data()); } response = ReadAllBytes(lastReply_); Logger::Hidden("--> Response Body:"); Logger::Hidden(string(response.begin(), response.end())); QNetworkReply::NetworkError error_type = lastReply_->error(); if (error_type != QNetworkReply::NoError) { Logger::Error(QString("error: %1").arg( lastReply_->errorString()).toStdString()); } return StatusCode(statusCode.toInt()); } StatusCode HttpClientQt::Post(const string& url, const common::ByteArray& request, const string& mediaType, common::ByteArray& response, std::shared_ptr<std::atomic<bool> >cancelState) { if (!QCoreApplication::instance()) { int argc = 1; char name[] = "HttpClientQt::Post"; char* argv = &name[0]; QCoreApplication a(argc, &argv); return doPost(url, request, mediaType, response, cancelState); } return doPost(url, request, mediaType, response, cancelState); } StatusCode HttpClientQt::doGet(const string& url, common::ByteArray& response, std::shared_ptr<std::atomic<bool> >cancelState) { Logger::Info("==> GetWithCoreAppContext %s", url.data()); this->request_.setUrl(QUrl(url.c_str())); Logger::Hidden("==> Request headers:"); foreach(const QByteArray &hdrName, this->request_.rawHeaderList()) { QByteArray hdrValue = this->request_.rawHeader(hdrName); Logger::Hidden("%s : %s", hdrName.data(), hdrValue.data()); } lastReply_ = this->manager_.get(this->request_); QTimer timer; QEventLoop loop; QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit())); QObject::connect(lastReply_, SIGNAL(finished()), &loop, SLOT(quit())); QObject::connect(lastReply_, &QNetworkReply::sslErrors, [ = ](QList<QSslError>errorList) { for (auto& error : errorList) { Logger::Error("QSslError: %s", error.errorString().toStdString().c_str()); throw exceptions::RMSNetworkException( error.errorString().toStdString(), exceptions::RMSNetworkException::ServerError); } }); do { timer.start(500); loop.exec(); if ((cancelState != nullptr) && cancelState->load()) { throw exceptions::RMSNetworkException( "Network operation was cancelled by user", exceptions::RMSNetworkException::CancelledByUser); } } while (!timer.isActive() || !lastReply_->isFinished()); QVariant statusCode = lastReply_->attribute( QNetworkRequest::HttpStatusCodeAttribute); Logger::Info("Response StatusCode: %i", statusCode.toInt()); Logger::Hidden("--> Response Headers:"); foreach(const QNetworkReply::RawHeaderPair & pair, lastReply_->rawHeaderPairs()) { Logger::Hidden("%s : %s", pair.first.data(), pair.second.data()); } response = ReadAllBytes(lastReply_); Logger::Hidden("--> Response Body:"); Logger::Hidden(string(response.begin(), response.end())); QNetworkReply::NetworkError error_type = lastReply_->error(); if (error_type != QNetworkReply::NoError) { Logger::Error(QString("error: %1").arg( lastReply_->errorString()).toStdString()); } return StatusCode(statusCode.toInt()); } StatusCode HttpClientQt::Get(const string& url, common::ByteArray& response, std::shared_ptr<std::atomic<bool> >cancelState) { if (!QCoreApplication::instance()) { int argc = 1; char name[] = "HttpClientQt::Get"; char* argv = &name[0]; QCoreApplication a(argc, &argv); return doGet(url, response, cancelState); } return doGet(url, response, cancelState); } const string HttpClientQt::GetResponseHeader(const string& headerName) { return string(lastReply_->rawHeader(headerName.c_str()).data()); } void HttpClientQt::SetAllowUI(bool ) { throw exceptions::RMSNotFoundException("Not implemented"); } } } } #endif
#ifdef QTFRAMEWORK #include "HttpClientQt.h" #include <QThread> #include <QMutex> #include <QEventLoop> #include <QCoreApplication> #include <QTimer> #include <QNetworkProxyFactory> #include "../Logger/Logger.h" #include "../../ModernAPI/RMSExceptions.h" #include "mscertificates.h" #include "HttpClientQt.h" using namespace std; using namespace rmscore::platform::logger; namespace rmscore { namespace platform { namespace http { common::ByteArray ReadAllBytes(QIODevice *from) { common::ByteArray result; auto bytesAvailable = from->bytesAvailable(); if (bytesAvailable > 0) { result.resize(static_cast<size_t>(bytesAvailable)); char *buf = reinterpret_cast<char *>(&result[0]); size_t offset = 0; while (bytesAvailable > 0) { auto read = from->read(&buf[offset], bytesAvailable); if (read <= 0) break; bytesAvailable -= read; offset += read; } } return result; } shared_ptr<IHttpClient> doCreate() { static bool initialized = false; if (!initialized) { QSslConfiguration SslConfiguration(QSslConfiguration::defaultConfiguration()); QList<QSslCertificate> certificates = SslConfiguration.caCertificates(); certificates.append(QSslCertificate::fromData(MicrosoftCertCA)); certificates.append(QSslCertificate::fromData(MicrosoftCertSubCA)); SslConfiguration.setCaCertificates(certificates); QSslConfiguration::setDefaultConfiguration(SslConfiguration); initialized = true; } return make_shared<HttpClientQt>(); } shared_ptr<IHttpClient> IHttpClient::Create() { if(!QCoreApplication::instance()) { int argc = 1; char name[] = "IHttpClient::Create"; char* argv = &name[0]; QCoreApplication a(argc, &argv); return doCreate(); } return doCreate(); } HttpClientQt::HttpClientQt() : lastReply_(nullptr) { this->request_.setSslConfiguration(QSslConfiguration::defaultConfiguration()); QNetworkProxyFactory::setUseSystemConfiguration(true); } HttpClientQt::~HttpClientQt() {} void HttpClientQt::AddAuthorizationHeader(const string& authToken) { this->AddHeader("Authorization", authToken); } void HttpClientQt::AddAcceptMediaTypeHeader(const string& mediaType) { this->AddHeader("Accept", mediaType); } void HttpClientQt::AddAcceptLanguageHeader(const string& language) { this->AddHeader("Accept-Language", language); } void HttpClientQt::AddHeader(const string& headerName, const string& headerValue) { this->request_.setRawHeader(headerName.c_str(), headerValue.c_str()); } StatusCode HttpClientQt::doPost(const string& url, const common::ByteArray& request, const string& mediaType, common::ByteArray& response, std::shared_ptr<std::atomic<bool> >cancelState) { Logger::Info("==> PostWithCoreAppContext %s", url.data()); this->request_.setUrl(QUrl(url.c_str())); this->AddAcceptMediaTypeHeader(mediaType); Logger::Hidden("==> Request Headers:"); foreach(const QByteArray &hdrName, this->request_.rawHeaderList()) { QByteArray hdrValue = this->request_.rawHeader(hdrName); Logger::Hidden("%s : %s", hdrName.data(), hdrValue.data()); } std::string req(request.begin(), request.end()); Logger::Hidden("==> Request Body: %s", req.c_str()); lastReply_ = this->manager_.post( this->request_, QByteArray(reinterpret_cast<const char *>(request.data()), static_cast<int>(request.size()))); QTimer timer; QEventLoop loop; QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit())); QObject::connect(lastReply_, SIGNAL(finished()), &loop, SLOT(quit())); QObject::connect(lastReply_, &QNetworkReply::sslErrors, [ = ](QList<QSslError>errorList) { for (auto& error : errorList) { Logger::Error("QSslError: %s", error.errorString().toStdString().c_str()); throw exceptions::RMSNetworkException( error.errorString().toStdString(), exceptions::RMSNetworkException::ServerError); } }); do { timer.start(500); loop.exec(); if ((cancelState != nullptr) && cancelState->load()) { throw exceptions::RMSNetworkException( "Network operation was cancelled by user", exceptions::RMSNetworkException::CancelledByUser); } } while (!timer.isActive() || !lastReply_->isFinished()); QVariant statusCode = lastReply_->attribute( QNetworkRequest::HttpStatusCodeAttribute); Logger::Info("Response StatusCode: %i", statusCode.toInt()); Logger::Hidden("--> Response Headers:"); foreach(const QNetworkReply::RawHeaderPair & pair, lastReply_->rawHeaderPairs()) { Logger::Hidden("%s : %s", pair.first.data(), pair.second.data()); } response = ReadAllBytes(lastReply_); Logger::Hidden("--> Response Body:"); Logger::Hidden(string(response.begin(), response.end())); QNetworkReply::NetworkError error_type = lastReply_->error(); if (error_type != QNetworkReply::NoError) { Logger::Error(QString("error: %1").arg( lastReply_->errorString()).toStdString()); } return StatusCode(statusCode.toInt()); } StatusCode HttpClientQt::Post(const string& url, const common::ByteArray& request, const string& mediaType, common::ByteArray& response, std::shared_ptr<std::atomic<bool> >cancelState) { if (!QCoreApplication::instance()) { int argc = 1; char name[] = "HttpClientQt::Post"; char* argv = &name[0]; QCoreApplication a(argc, &argv); return doPost(url, request, mediaType, response, cancelState); } return doPost(url, request, mediaType, response, cancelState); } StatusCode HttpClientQt::doGet(const string& url, common::ByteArray& response, std::
)); QObject::connect(lastReply_, SIGNAL(finished()), &loop, SLOT(quit())); QObject::connect(lastReply_, &QNetworkReply::sslErrors, [ = ](QList<QSslError>errorList) { for (auto& error : errorList) { Logger::Error("QSslError: %s", error.errorString().toStdString().c_str()); throw exceptions::RMSNetworkException( error.errorString().toStdString(), exceptions::RMSNetworkException::ServerError); } }); do { timer.start(500); loop.exec(); if ((cancelState != nullptr) && cancelState->load()) { throw exceptions::RMSNetworkException( "Network operation was cancelled by user", exceptions::RMSNetworkException::CancelledByUser); } } while (!timer.isActive() || !lastReply_->isFinished()); QVariant statusCode = lastReply_->attribute( QNetworkRequest::HttpStatusCodeAttribute); Logger::Info("Response StatusCode: %i", statusCode.toInt()); Logger::Hidden("--> Response Headers:"); foreach(const QNetworkReply::RawHeaderPair & pair, lastReply_->rawHeaderPairs()) { Logger::Hidden("%s : %s", pair.first.data(), pair.second.data()); } response = ReadAllBytes(lastReply_); Logger::Hidden("--> Response Body:"); Logger::Hidden(string(response.begin(), response.end())); QNetworkReply::NetworkError error_type = lastReply_->error(); if (error_type != QNetworkReply::NoError) { Logger::Error(QString("error: %1").arg( lastReply_->errorString()).toStdString()); } return StatusCode(statusCode.toInt()); } StatusCode HttpClientQt::Get(const string& url, common::ByteArray& response, std::shared_ptr<std::atomic<bool> >cancelState) { if (!QCoreApplication::instance()) { int argc = 1; char name[] = "HttpClientQt::Get"; char* argv = &name[0]; QCoreApplication a(argc, &argv); return doGet(url, response, cancelState); } return doGet(url, response, cancelState); } const string HttpClientQt::GetResponseHeader(const string& headerName) { return string(lastReply_->rawHeader(headerName.c_str()).data()); } void HttpClientQt::SetAllowUI(bool ) { throw exceptions::RMSNotFoundException("Not implemented"); } } } } #endif
shared_ptr<std::atomic<bool> >cancelState) { Logger::Info("==> GetWithCoreAppContext %s", url.data()); this->request_.setUrl(QUrl(url.c_str())); Logger::Hidden("==> Request headers:"); foreach(const QByteArray &hdrName, this->request_.rawHeaderList()) { QByteArray hdrValue = this->request_.rawHeader(hdrName); Logger::Hidden("%s : %s", hdrName.data(), hdrValue.data()); } lastReply_ = this->manager_.get(this->request_); QTimer timer; QEventLoop loop; QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()
random
[ { "content": "namespace rmscore { namespace restclients {\n\n\n\nvoid HandleRestClientError(platform::http::StatusCode httpStatusCode, rmscore::common::ByteArray &sResponse);\n\n\n\n} // namespace restclients\n", "file_path": "sdk/rms_sdk/RestClients/RestClientErrorHandling.h", "rank": 0, "score": 120060.23148964674 }, { "content": " u32 offset; /* Offset into the data */\n", "file_path": "sdk/rmscrypto_sdk/Platform/KeyStorage/sqlite3.c", "rank": 1, "score": 119616.2559781872 }, { "content": "class IHttpClient {\n\npublic:\n\n\n\n virtual void AddAuthorizationHeader(const std::string& authToken) = 0;\n\n virtual void AddAcceptMediaTypeHeader(const std::string& mediaType) = 0;\n\n virtual void AddAcceptLanguageHeader(const std::string& language) = 0;\n\n virtual void AddHeader(const std::string& headerName,\n\n const std::string& headerValue) = 0;\n\n\n\n virtual StatusCode Post(const std::string& url,\n\n const common::ByteArray& request,\n\n const std::string& mediaType,\n\n common::ByteArray& response,\n\n std::shared_ptr<std::atomic<bool> >cancelState) = 0;\n\n\n\n virtual StatusCode Get(const std::string& url,\n\n common::ByteArray& response,\n\n std::shared_ptr<std::atomic<bool> >cancelState) = 0;\n\n\n\n virtual const std::string GetResponseHeader(const std::string& headerName) = 0;\n", "file_path": "sdk/rms_sdk/Platform/Http/IHttpClient.h", "rank": 2, "score": 107541.78595817863 }, { "content": "\n\n virtual void SetAllowUI(bool allow) = 0;\n\n virtual ~IHttpClient() {}\n\n\n\npublic:\n\n\n\n static std::shared_ptr<IHttpClient> Create();\n\n};\n\n}\n\n}\n\n} // namespace rmscore { namespace platform { namespace http {\n\n\n\n#endif // _IHTTPCLIENT_H_\n", "file_path": "sdk/rms_sdk/Platform/Http/IHttpClient.h", "rank": 3, "score": 105953.21665161995 }, { "content": "/*\n\n * ======================================================================\n\n * Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.\n\n * Licensed under the MIT License.\n\n * See LICENSE.md in the project root for license information.\n\n * ======================================================================\n\n */\n\n\n\n#ifndef _IHTTPCLIENT_H_\n\n#define _IHTTPCLIENT_H_\n\n\n\n#include <memory>\n\n#include <string>\n\n#include <atomic>\n\n\n\n#include \"../../Common/FrameworkSpecificTypes.h\"\n\n\n\nnamespace rmscore {\n\nnamespace platform {\n\nnamespace http {\n", "file_path": "sdk/rms_sdk/Platform/Http/IHttpClient.h", "rank": 4, "score": 105941.68655914113 }, { "content": "class PlatformHttpClientTest : public QObject\n\n{\n\n Q_OBJECT\n\npublic:\n\n PlatformHttpClientTest();\n\n\n\nprivate Q_SLOTS:\n\n void testHttpClient(bool enabled = true);\n\n};\n\n#endif // PLATFORMHTTPCLIENTTEST\n\n\n", "file_path": "sdk/rms_sdk/UnitTests/platform_ut/PlatformHttpClientTest.h", "rank": 5, "score": 104456.69552702029 }, { "content": " const common::ByteArray& request,\n\n const std::string& mediaType,\n\n common::ByteArray& response,\n\n std::shared_ptr<std::atomic<bool> >cancelState);\n\n\n\n StatusCode doGet(\n\n const std::string& url,\n\n common::ByteArray& response,\n\n std::shared_ptr<std::atomic<bool> >cancelState);\n\n};\n\n}\n\n}\n\n} // namespace rmscore { namespace platform { namespace http {\n\n\n\n#endif // _HTTPCLIENTQT_H_\n", "file_path": "sdk/rms_sdk/Platform/Http/HttpClientQt.h", "rank": 6, "score": 103615.50505696886 }, { "content": " common::ByteArray& response,\n\n std::shared_ptr<std::atomic<bool> >cancelState) override;\n\n\n\n virtual StatusCode Get(\n\n const std::string& url,\n\n common::ByteArray& response,\n\n std::shared_ptr<std::atomic<bool> >cancelState) override;\n\n\n\n virtual const std::string GetResponseHeader(const std::string& headerName)\n\n override;\n\n\n\n virtual void SetAllowUI(bool allow) override;\n\n\n\nprivate:\n\n QNetworkAccessManager manager_;\n\n QNetworkRequest request_;\n\n QNetworkReply *lastReply_;\n\n\n\n StatusCode doPost(\n\n const std::string& url,\n", "file_path": "sdk/rms_sdk/Platform/Http/HttpClientQt.h", "rank": 7, "score": 103615.03072832787 }, { "content": "/*\n\n * ======================================================================\n\n * Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.\n\n * Licensed under the MIT License.\n\n * See LICENSE.md in the project root for license information.\n\n * ======================================================================\n\n */\n\n\n\n#ifndef _HTTPCLIENTQT_H_\n\n#define _HTTPCLIENTQT_H_\n\n\n\n#include <QCoreApplication>\n\n#include <QNetworkAccessManager>\n\n#include <QNetworkReply>\n\n#include <QNetworkRequest>\n\n#include <exception>\n\n#include <atomic>\n\n#include \"IHttpClient.h\"\n\n\n\nnamespace rmscore {\n\nnamespace platform {\n\nnamespace http {\n", "file_path": "sdk/rms_sdk/Platform/Http/HttpClientQt.h", "rank": 8, "score": 103604.67775901641 }, { "content": "class HttpClientQt : public IHttpClient {\n\n // Q_OBJECT\n\n\n\npublic:\n\n\n\n HttpClientQt();\n\n ~HttpClientQt();\n\n\n\n virtual void AddAuthorizationHeader(const std::string& authToken) override;\n\n virtual void AddAcceptMediaTypeHeader(const std::string& mediaType) override;\n\n virtual void AddAcceptLanguageHeader(const std::string& languages) override;\n\n\n\n virtual void AddHeader(\n\n const std::string& headerName,\n\n const std::string& headerValue) override;\n\n\n\n virtual StatusCode Post(\n\n const std::string& url,\n\n const common::ByteArray& request,\n\n const std::string& mediaType,\n", "file_path": "sdk/rms_sdk/Platform/Http/HttpClientQt.h", "rank": 9, "score": 102766.37094591436 }, { "content": "class LanguageSettings : public ILanguageSettings\n\n{\n\npublic:\n\n virtual std::vector<std::string> GetAppLanguages() override;\n\n};\n\n}}} //namespace rmscore { namespace platform { namespace settings {\n\n#endif // LANGUAGESETTINGS\n\n\n", "file_path": "sdk/rms_sdk/Platform/Settings/LanguageSettings.h", "rank": 10, "score": 102084.80685833642 }, { "content": "class ILanguageSettings\n\n{\n\npublic:\n\n virtual std::vector<std::string> GetAppLanguages() = 0;\n\n\n\npublic:\n\n static std::shared_ptr<ILanguageSettings> Create();\n\n};\n\n\n\n}}} // namespace rmscore { namespace platform { namespace settings {\n\n\n\n#endif // ILANGUAGESETTINGS\n\n\n", "file_path": "sdk/rms_sdk/Platform/Settings/ILanguageSettings.h", "rank": 11, "score": 101487.51771417847 }, { "content": "enum GetUserPolicyResultStatus {\n\n Success = 0, NoRights = 1, Expired = 2\n\n};\n\n\n", "file_path": "sdk/rms_sdk/ModernAPI/UserPolicy.h", "rank": 27, "score": 99608.28301652796 }, { "content": "enum class StatusCode {\n\n OK = 200,\n\n BAD_REQUEST = 400,\n\n UNAUTHORIZED = 401,\n\n NOT_FOUND = 404,\n\n INTERNAL_SERVER_ERROR = 500,\n\n BAD_GATEWAY = 502,\n\n};\n\n\n", "file_path": "sdk/rms_sdk/Platform/Http/IHttpClient.h", "rank": 28, "score": 99203.92957962799 }, { "content": "class RequestInterceptor : public QWebEngineUrlRequestInterceptor\n\n{\n\n Q_OBJECT\n\n\n\npublic:\n\n explicit RequestInterceptor(QObject* parent = Q_NULLPTR) : QWebEngineUrlRequestInterceptor(parent) {}\n\n /**\n\n * @brief RequestInterceptor::interceptRequest\n\n * This is used to handle the RedirectUrl which has a http/https scheme. We do not fail the\n\n * request as this captures other internet traffic as well.\n\n * @param info\n\n */\n\n virtual void interceptRequest(QWebEngineUrlRequestInfo& info) Q_DECL_OVERRIDE;\n\n\n\nsignals:\n\n void redirectUrlCapture(QUrl);\n\n};\n\n\n\n#endif // REQUESTINTERCEPTOR_H\n", "file_path": "sdk/rmsauth_sdk/WebAuthDialog/RequestInterceptor.h", "rank": 29, "score": 97879.49814136502 }, { "content": "/*\n\n * ======================================================================\n\n * Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.\n\n * Licensed under the MIT License.\n\n * See LICENSE.md in the project root for license information.\n\n * ======================================================================\n\n*/\n\n\n\n#ifndef _IURI_H_\n\n#define _IURI_H_\n\n\n\n#include <string>\n\n#include <memory>\n\n\n\nnamespace rmscore { namespace platform { namespace http {\n\n\n", "file_path": "sdk/rms_sdk/Platform/Http/IUri.h", "rank": 30, "score": 96103.40366101486 }, { "content": "/*\n\n * ======================================================================\n\n * Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.\n\n * Licensed under the MIT License.\n\n * See LICENSE.md in the project root for license information.\n\n * ======================================================================\n\n*/\n\n\n\n#ifndef PLATFORMHTTPCLIENTTEST\n\n#define PLATFORMHTTPCLIENTTEST\n\n#include <QtTest>\n\n\n", "file_path": "sdk/rms_sdk/UnitTests/platform_ut/PlatformHttpClientTest.h", "rank": 31, "score": 95797.22313287934 }, { "content": "struct DLL_PUBLIC_RMS GetUserPolicyResult {\n\n GetUserPolicyResult(GetUserPolicyResultStatus status,\n\n std::shared_ptr<std::string>referrer,\n\n std::shared_ptr<UserPolicy> policy);\n\n\n\n GetUserPolicyResultStatus Status;\n\n std::shared_ptr<std::string>Referrer;\n\n std::shared_ptr<UserPolicy> Policy;\n\n};\n\n\n\n/*!\n\n @brief Specifies the expected mode for an operation. For example, can library\n\n use UI or expect available network.\n\n */\n", "file_path": "sdk/rms_sdk/ModernAPI/UserPolicy.h", "rank": 32, "score": 95717.38411036922 }, { "content": " if (!enabled) return;\n\n\n\n auto pclient = http::IHttpClient::Create();\n\n rmscore::common::ByteArray response;\n\n std::string request(\"any\");\n\n\n\n auto url = \"https://api.aadrm.com/my/v1/servicediscovery\";\n\n\n\n http::StatusCode status = pclient->Get(\n\n url,\n\n response,\n\n nullptr);\n\n\n\n QVERIFY2(status == http::StatusCode::UNAUTHORIZED,\n\n \"pclient->Get: Unexpected status code\");\n\n\n\n pclient->AddHeader(\"content-type\", \"application/x-www-form-urlencoded\");\n\n status = pclient->Post(\n\n url,\n\n rmscore::common::ByteArray(request.begin(), request.end()),\n", "file_path": "sdk/rms_sdk/UnitTests/platform_ut/PlatformHttpClientTest.cpp", "rank": 33, "score": 93852.68008480911 }, { "content": "/*\n\n * ======================================================================\n\n * Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.\n\n * Licensed under the MIT License.\n\n * See LICENSE.md in the project root for license information.\n\n * ======================================================================\n\n */\n\n\n\n#include \"PlatformHttpClientTest.h\"\n\n#include \"../../Platform/Logger/Logger.h\"\n\n#include \"../../Platform/Http/IHttpClient.h\"\n\n#include \"../../Common/FrameworkSpecificTypes.h\"\n\n\n\nusing namespace rmscore::platform;\n\n\n\nPlatformHttpClientTest::PlatformHttpClientTest()\n\n{}\n\n\n\nvoid PlatformHttpClientTest::testHttpClient(bool enabled)\n\n{\n", "file_path": "sdk/rms_sdk/UnitTests/platform_ut/PlatformHttpClientTest.cpp", "rank": 34, "score": 93850.96845356503 }, { "content": " \"any\",\n\n response,\n\n nullptr);\n\n\n\n QByteArray expected = QString(\n\n \"{\\\"Message\\\":\\\"The authorization token is not well-formed.\\\"}\").toUtf8();\n\n QByteArray actual((const char *)response.data(), (int)response.size());\n\n\n\n QCOMPARE(expected, actual);\n\n\n\n QVERIFY2(status == http::StatusCode::UNAUTHORIZED,\n\n \"pclient->Post: Unexpected status code\");\n\n}\n", "file_path": "sdk/rms_sdk/UnitTests/platform_ut/PlatformHttpClientTest.cpp", "rank": 35, "score": 93836.30781247873 }, { "content": "/*\n\n * ======================================================================\n\n * Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.\n\n * Licensed under the MIT License.\n\n * See LICENSE.md in the project root for license information.\n\n * ======================================================================\n\n*/\n\n\n\n#ifndef ILANGUAGESETTINGS\n\n#define ILANGUAGESETTINGS\n\n\n\n#include<memory>\n\n#include<string>\n\n#include<vector>\n\n\n\nnamespace rmscore { namespace platform { namespace settings {\n\n\n", "file_path": "sdk/rms_sdk/Platform/Settings/ILanguageSettings.h", "rank": 36, "score": 93445.53087677684 }, { "content": "/*\n\n * ======================================================================\n\n * Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.\n\n * Licensed under the MIT License.\n\n * See LICENSE.md in the project root for license information.\n\n * ======================================================================\n\n*/\n\n\n\n#ifndef LANGUAGESETTINGS\n\n#define LANGUAGESETTINGS\n\n\n\n#include\"ILanguageSettings.h\"\n\nnamespace rmscore { namespace platform { namespace settings {\n", "file_path": "sdk/rms_sdk/Platform/Settings/LanguageSettings.h", "rank": 37, "score": 93444.20725067699 }, { "content": "/*\n\n * ======================================================================\n\n * Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.\n\n * Licensed under the MIT License.\n\n * See LICENSE.md in the project root for license information.\n\n * ======================================================================\n\n*/\n\n\n\n#ifndef IURIQTIMPL\n\n#define IURIQTIMPL\n\n\n\n#include \"IUri.h\"\n\n#include \"QUrl\"\n\n\n\nnamespace rmscore { namespace platform { namespace http {\n\n\n", "file_path": "sdk/rms_sdk/Platform/Http/UriQt.h", "rank": 38, "score": 93327.35108959152 }, { "content": "class IUri {\n\npublic:\n\n virtual const std::string GetScheme() const = 0;\n\n virtual const std::string GetHost() const = 0;\n\n virtual int GetPort() const = 0;\n\n virtual const std::string ToString() const = 0;\n\n virtual ~IUri() { }\n\n\n\npublic:\n\n static std::shared_ptr<IUri> Create(const std::string& uri);\n\n};\n\n\n\n}}} // namespace rmscore { namespace platform { namespace http {\n\n\n\n#endif // _IURI_H_\n\n\n", "file_path": "sdk/rms_sdk/Platform/Http/IUri.h", "rank": 39, "score": 93302.3390290833 }, { "content": "/*\n\n * ======================================================================\n\n * Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.\n\n * Licensed under the MIT License.\n\n * See LICENSE.md in the project root for license information.\n\n * ======================================================================\n\n*/\n\n\n\n#include\"LanguageSettings.h\"\n\n\n\nnamespace rmscore { namespace platform { namespace settings {\n\n\n\nstd::vector<std::string> LanguageSettings::GetAppLanguages()\n\n{\n\n std::vector<std::string> res;\n\n res.push_back(\"En-en\");\n\n return res;\n\n}\n\n\n\nstd::shared_ptr<ILanguageSettings> ILanguageSettings::Create()\n\n{\n\n return std::make_shared<LanguageSettings>();\n\n}\n\n\n\n}}} //namespace rmscore { namespace platform { namespace settings {\n", "file_path": "sdk/rms_sdk/Platform/Settings/LanguageSettings.cpp", "rank": 40, "score": 90831.50440263425 }, { "content": "const std::string UriQt::GetHost() const\n\n{\n\n return this->pImpl_->host().toStdString();\n\n}\n\nint UriQt::GetPort() const\n\n{\n\n return this->pImpl_->port();\n\n}\n\nconst std::string UriQt::ToString()const\n\n{\n\n return this->pImpl_->toString().toStdString();\n\n}\n\n\n\n}}} // namespace rmscore { namespace platform { namespace http {\n\n#endif\n\n\n\n\n", "file_path": "sdk/rms_sdk/Platform/Http/UriQt.cpp", "rank": 41, "score": 90714.62830351964 }, { "content": "/*\n\n * ======================================================================\n\n * Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.\n\n * Licensed under the MIT License.\n\n * See LICENSE.md in the project root for license information.\n\n * ======================================================================\n\n*/\n\n\n\n#ifdef QTFRAMEWORK\n\n#include \"UriQt.h\"\n\nnamespace rmscore { namespace platform { namespace http {\n\n\n\nstd::shared_ptr<IUri> IUri::Create(const std::string& uri)\n\n{\n\n return std::make_shared<UriQt>(uri);\n\n}\n\nconst std::string UriQt::GetScheme() const\n\n{\n\n return this->pImpl_->scheme().toStdString();\n\n}\n", "file_path": "sdk/rms_sdk/Platform/Http/UriQt.cpp", "rank": 42, "score": 90711.81461207625 }, { "content": "/*\n\n * ======================================================================\n\n * Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.\n\n * Licensed under the MIT License.\n\n * See LICENSE.md in the project root for license information.\n\n * ======================================================================\n\n*/\n\n\n\n#ifndef _RMS_CORE_IDNSSERVERRESOLVER_H_\n\n#define _RMS_CORE_IDNSSERVERRESOLVER_H_\n\n\n\n#include <memory>\n\n#include <string>\n\n#include <vector>\n\n\n\n#include \"../../Common/CommonTypes.h\"\n\n\n\nnamespace rmscore {\n\nnamespace platform {\n\nnamespace http {\n", "file_path": "sdk/rms_sdk/Platform/Http/IDnsServerResolver.h", "rank": 43, "score": 90705.41170427795 }, { "content": "struct HashConstString\n\n{\n\n long operator()(const std::string& str) const {\n\n return static_cast<long>(std::hash<std::string>()(str));\n\n }\n\n};\n\n\n\ntemplate<typename T>\n\nusing HashMapString = std::unordered_map<std::string, T, HashConstString>;\n\n}\n\n/// @endcond\n\n\n\nusing AppDataHashMap = detail::HashMapString<std::string>;\n\n\n\n\n\n/**\n\n * @brief Specifies users and rights assigned for a file.\n\n */\n", "file_path": "sdk/rms_sdk/ModernAPI/PolicyDescriptor.h", "rank": 44, "score": 90657.76116586642 }, { "content": "/*\n\n * ======================================================================\n\n * Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.\n\n * Licensed under the MIT License.\n\n * See LICENSE.md in the project root for license information.\n\n * ======================================================================\n\n*/\n\n\n\n#ifndef DOMNAMEDNODEMAP\n\n#define DOMNAMEDNODEMAP\n\n\n\n#include <string>\n\n#include <memory>\n\n#include \"../../ModernAPI/PolicyDescriptor.h\"\n\n\n", "file_path": "sdk/rms_sdk/Platform/Xml/DomNamedNodeMap.h", "rank": 45, "score": 88267.50606161544 }, { "content": "struct MyStringCompare\n\n{\n\n bool operator()(const std::string& ilhs, const std::string& irhs) const\n\n {\n\n auto lhs = ilhs;\n\n auto rhs = irhs;\n\n\n\n std::transform(lhs.begin(), lhs.end(), lhs.begin(), ::toupper);\n\n std::transform(rhs.begin(), rhs.end(), rhs.begin(), ::toupper);\n\n return lhs < rhs;\n\n }\n\n};\n\n\n", "file_path": "sdk/rms_sdk/RestClients/RestServiceUrlClient.h", "rank": 46, "score": 88225.21870802996 }, { "content": "/*\n\n * ======================================================================\n\n * Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.\n\n * Licensed under the MIT License.\n\n * See LICENSE.md in the project root for license information.\n\n * ======================================================================\n\n*/\n\n\n\n#ifndef DNSSERVERRESOLVERQT\n\n#define DNSSERVERRESOLVERQT\n\n#include \"IDnsServerResolver.h\"\n\n\n", "file_path": "sdk/rms_sdk/Platform/Http/DnsServerResolverQt.h", "rank": 47, "score": 88208.55018270774 }, { "content": "enum class UserIdentifierType\n\n{\n\n UniqueId,\n\n LoginHint,\n\n NoUser\n\n};\n\n\n\n/**\n\n * Represent request and keeps authorization code and similar info.\n\n */\n", "file_path": "sdk/rmsauth_sdk/rmsauth/rmsauth/AuthenticationRequest.h", "rank": 48, "score": 88165.66560074809 }, { "content": "class Url : public IUrl\n\n{\n\npublic:\n\n Url();\n\n Url(const String& url);\n\n void setUrl(const String& url) override;\n\n String toString() const override;\n\n String scheme() const override;\n\n String authority() const override;\n\n String host() const override;\n\n String fragment() const override;\n\n String path() const override;\n\n bool isValid() const override;\n\n\n\nprivate:\n\n ptr<IUrl> pImpl;\n\n};\n\n\n\nusing UrlPtr = ptr<Url>;\n\n\n\n} // namespace rmsauth {\n\n\n\n#endif // IURL\n\n\n", "file_path": "sdk/rmsauth_sdk/rmsauth/rmsauth/Url.h", "rank": 49, "score": 87712.44362123942 }, { "content": " // QCoreApplication is a singleton, but it can keep getting created and destroyed.\n\n // QtNetwork calls need to be made from within the scope of the QCoreApplication created.\n\n if (!QCoreApplication::instance()){\n\n int argc = 1;\n\n char name[] = \"DnsServerResolverQt::lookup\";\n\n char* argv = &name[0];\n\n QCoreApplication a(argc, &argv);\n\n\n\n auto result = doLookup(dnsRequest);\n\n\n\n QTimer::singleShot(0, &a, SLOT(quit()));\n\n a.exec();\n\n\n\n return result;\n\n }\n\n\n\n return doLookup(dnsRequest);\n\n}\n\n\n\n\n\n} // namespace http\n\n} // namespace platform\n\n} // namespace rmscore\n\n#endif // ifdef QTFRAMEWORK\n", "file_path": "sdk/rms_sdk/Platform/Http/DnsServerResolverQt.cpp", "rank": 50, "score": 85906.68321756179 }, { "content": "using namespace rmscore::platform::logger;\n\n\n\nnamespace rmscore {\n\nnamespace platform {\n\nnamespace http {\n\nshared_ptr<IDnsServerResolver>IDnsServerResolver::Create()\n\n{\n\n return make_shared<DnsServerResolverQt>();\n\n}\n\n\n\nstd::string DnsServerResolverQt::doLookup(const std::string& dnsRequest)\n\n{\n\n QDnsLookup dns;\n\n\n\n dns.setType(QDnsLookup::SRV);\n\n Logger::Hidden(\"dnsRequest: %s\", dnsRequest.c_str());\n\n dns.setName(dnsRequest.c_str());\n\n dns.lookup();\n\n QEventLoop loop;\n\n QObject::connect(&dns, SIGNAL(finished()), &loop, SLOT(quit()));\n", "file_path": "sdk/rms_sdk/Platform/Http/DnsServerResolverQt.cpp", "rank": 51, "score": 85894.38999264438 }, { "content": "/*\n\n * ======================================================================\n\n * Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.\n\n * Licensed under the MIT License.\n\n * See LICENSE.md in the project root for license information.\n\n * ======================================================================\n\n */\n\n\n\n#ifdef QTFRAMEWORK\n\n#include <QDnsLookup>\n\n#include <QEventLoop>\n\n#include <QCoreApplication>\n\n#include <QTimer>\n\n#include \"DnsServerResolverQt.h\"\n\n#include <QUdpSocket>\n\n#include <QThread>\n\n#include \"../../Platform/Logger/Logger.h\"\n\n\n\nusing namespace std;\n\nusing namespace rmscore::common;\n", "file_path": "sdk/rms_sdk/Platform/Http/DnsServerResolverQt.cpp", "rank": 52, "score": 85889.79418886083 }, { "content": " loop.exec();\n\n\n\n if (dns.error() != QDnsLookup::NoError)\n\n {\n\n qWarning(\"DNS lookup failed\");\n\n }\n\n foreach(const QDnsServiceRecord &record, dns.serviceRecords())\n\n {\n\n Logger::Hidden(\"QDnsServiceRecord record: %s --> %s\",\n\n record.name().toStdString().c_str(),\n\n record.target().toStdString().c_str());\n\n\n\n return record.target().toStdString();\n\n }\n\n return \"\";\n\n}\n\n\n\nstd::string DnsServerResolverQt::lookup(const std::string& dnsRequest)\n\n{\n\n // If a QCoreApplication does not exist, create a temporary instance.\n", "file_path": "sdk/rms_sdk/Platform/Http/DnsServerResolverQt.cpp", "rank": 53, "score": 85882.17221539922 }, { "content": "namespace rmscore {\n\nnamespace common {\n\nuint64_t timeToWinFileTime(const QDateTime& dateTime);\n\nstd::string timeToString(const QDateTime& dateTime);\n\nByteArray ConvertBase64ToBytes(const ByteArray& base64str);\n\nByteArray ConvertBytesToBase64(const ByteArray& bytes);\n\nByteArray ConvertBytesToBase64(const void *bytes,\n\n const size_t size);\n\nstd::string GenerateAGuid();\n\n} // namespace common\n", "file_path": "sdk/rms_sdk/Common/tools.h", "rank": 54, "score": 84941.7493948761 }, { "content": "struct ErrorResponse\n\n{\n\n struct JsonNames {\n\n const String error = OAuthConstants::oAuthReservedClaim().Error;\n\n const String errorDescription = OAuthConstants::oAuthReservedClaim().ErrorDescription;\n\n const String errorCodes = OAuthConstants::oAuthReservedClaim().ErrorCodes;\n\n };\n\n\n\n static const JsonNames& jsonNames()\n\n {\n\n static const JsonNames jsonNames{};\n\n return jsonNames;\n\n }\n\n\n", "file_path": "sdk/rmsauth_sdk/rmsauth/rmsauth/Entities.h", "rank": 55, "score": 83902.14534049391 }, { "content": "namespace rmscore {\n\nnamespace common {\n\ntemplate<typename T>\n\nusing TIterable = std::vector<T>;\n\nusing ByteArray = TIterable<uint8_t>;\n\nusing CharArray = TIterable<char>;\n\nusing StringArray = TIterable<std::string>;\n\nusing IUri = rmscore::platform::http::IUri;\n\nusing UrlArray = TIterable<std::shared_ptr<IUri>>;\n\n\n\n#ifdef _MSC_VER\n\n# define snprintf _snprintf\n\n#else\n\n# define _strcmpi strcasecmp\n\n# define _stricmp strcasecmp\n\n# define _strnicmp strncasecmp\n\n#endif // _MSC_VER\n\n} // namespace common\n", "file_path": "sdk/rms_sdk/Common/CommonTypes.h", "rank": 56, "score": 83881.9708212829 }, { "content": "class IDomNode;\n\nusing DomNamedNodeMap = rmscore::modernapi::detail::HashMapString<std::shared_ptr<IDomNode>>;\n\n\n\n#endif // DOMNAMEDNODEMAP\n\n\n", "file_path": "sdk/rms_sdk/Platform/Xml/DomNamedNodeMap.h", "rank": 57, "score": 83685.80432854098 }, { "content": "class UriQt : public IUri\n\n{\n\npublic:\n\n UriQt(const std::string& uri){this->pImpl_= new QUrl(uri.c_str());}\n\n ~UriQt(){ if(nullptr != this->pImpl_) delete this->pImpl_;}\n\n\n\n virtual const std::string GetScheme() const override;\n\n virtual const std::string GetHost() const override;\n\n virtual int GetPort() const override;\n\n virtual const std::string ToString()const override;\n\n\n\nprivate:\n\n QUrl* pImpl_;\n\n};\n\n\n\n}}} // namespace rmscore { namespace platform { namespace http {\n\n\n\n#endif // IURIQTIMPL\n\n\n", "file_path": "sdk/rms_sdk/Platform/Http/UriQt.h", "rank": 58, "score": 83635.06871732074 }, { "content": "class IDnsServerResolver {\n\npublic:\n\n virtual std::string lookup(const std::string& dnsRequest) = 0;\n\n\n\npublic:\n\n static std::shared_ptr<IDnsServerResolver> Create();\n\n};\n\n} // namespace http\n\n} // namespace platform\n\n} // namespace rmscore\n\n#endif // _RMS_CORE_IDNSSERVERRESOLVER_H_\n", "file_path": "sdk/rms_sdk/Platform/Http/IDnsServerResolver.h", "rank": 59, "score": 83635.06871732074 }, { "content": "namespace rmscore {\n\nnamespace modernapi {\n\nenum class ConsentType : char\n\n{\n\n // consent type for document tracking\n\n DocumentTrackingConsent = 0,\n\n\n\n // consent type for contacting a service url\n\n ServiceUrlConsent = 1\n\n};\n\n} // namespace modernapi\n", "file_path": "sdk/rms_sdk/ModernAPI/ConsentType.h", "rank": 60, "score": 82873.13646197713 }, { "content": "namespace rmscore {\n\nnamespace restclients {\n\nstruct UsageRestrictionsRequest {\n\n const uint8_t *pbPublishLicense;\n\n uint32_t cbPublishLicense;\n\n};\n\n\n\nstruct KeyDetailsResponse {\n\n common::ByteArray value;\n\n std::string algorithm;\n\n std::string cipherMode;\n\n};\n\n\n\nstruct UserRightsResponse {\n\n std::vector<std::string>users;\n\n std::vector<std::string>rights;\n\n};\n\n\n\nstruct UserRolesResponse {\n\n std::vector<std::string>users;\n\n std::vector<std::string>roles;\n\n};\n\n\n\nstruct CustomPolicyResponse {\n\n bool bIsNull;\n\n bool bAllowAuditedExtraction;\n\n std::vector<UserRightsResponse>userRightsList;\n\n std::vector<UserRolesResponse> userRolesList;\n\n};\n\n\n\nstruct UsageRestrictionsResponse {\n\n std::string accessStatus;\n\n std::string id;\n\n std::string name;\n\n std::string description;\n\n std::string referrer;\n\n std::string owner;\n\n KeyDetailsResponse key;\n\n std::vector<std::string> rights;\n\n std::vector<std::string> roles;\n\n std::string issuedTo;\n\n std::chrono::time_point<std::chrono::system_clock>ftContentValidUntil;\n\n std::chrono::time_point<std::chrono::system_clock>ftLicenseValidUntil;\n\n std::string contentValidUntil;\n\n std::string licenseValidUntil;\n\n bool bAllowOfflineAccess;\n\n bool bFromTemplate;\n\n std::string contentId;\n\n CustomPolicyResponse customPolicy;\n\n modernapi::AppDataHashMap signedApplicationData;\n\n modernapi::AppDataHashMap encryptedApplicationData;\n\n};\n\n\n\nstruct ServerErrorResponse {\n\n std::string code;\n\n std::string message;\n\n};\n\n\n\nstruct TemplateResponse {\n\n std::string id;\n\n std::string name;\n\n std::string description;\n\n};\n\n\n\nstruct TemplateListResponse {\n\n std::vector<TemplateResponse>templates;\n\n};\n\n\n\nstruct ServiceDiscoveryResponse {\n\n std::string name;\n\n std::string uri;\n\n};\n\n\n\nstruct ServiceDiscoveryListResponse {\n\n std::vector<ServiceDiscoveryResponse>serviceEndpoints;\n\n};\n\n\n\nstruct PublishUsingTemplateRequest {\n\n bool bPreferDeprecatedAlgorithms;\n\n bool bAllowAuditedExtraction;\n\n std::string templateId;\n\n modernapi::AppDataHashMap signedApplicationData;\n\n};\n\n\n\nstruct UserRightsRequest {\n\n std::vector<std::string>users;\n\n std::vector<std::string>rights;\n\n};\n\n\n\nstruct UserRolesRequest {\n\n std::vector<std::string>users;\n\n std::vector<std::string>roles;\n\n};\n\n\n\nstruct ApplicationDataRequest {\n\n std::string name;\n\n std::string value;\n\n};\n\n\n\nstruct PublishCustomRequest {\n\n PublishCustomRequest(bool bPreferDeprecatedAlgorithms,\n\n bool bAllowAuditedExtraction)\n\n : bPreferDeprecatedAlgorithms(bPreferDeprecatedAlgorithms)\n\n , bAllowAuditedExtraction(bAllowAuditedExtraction) {}\n\n\n\n bool bPreferDeprecatedAlgorithms;\n\n bool bAllowAuditedExtraction;\n\n std::string wsReferralInfo;\n\n\n\n // Descriptors\n\n std::string name;\n\n std::string description;\n\n std::string language;\n\n std::vector<UserRightsRequest> userRightsList;\n\n std::vector<UserRolesRequest> userRolesList;\n\n bool bAllowOfflineAccess;\n\n std::chrono::time_point<std::chrono::system_clock>ftLicenseValidUntil;\n\n modernapi::AppDataHashMap signedApplicationData;\n\n modernapi::AppDataHashMap encryptedApplicationData;\n\n};\n\n\n\nstruct PublishResponse {\n\n common::ByteArray serializedLicense;\n\n std::string id;\n\n std::string name;\n\n std::string description;\n\n std::string referrer;\n\n std::string owner;\n\n KeyDetailsResponse key;\n\n std::string contentId;\n\n modernapi::AppDataHashMap signedApplicationData;\n\n modernapi::AppDataHashMap encryptedApplicationData;\n\n};\n\n} // namespace restclients\n", "file_path": "sdk/rms_sdk/RestClients/RestObjects.h", "rank": 61, "score": 82873.13646197713 }, { "content": "namespace rmscore {\n\nnamespace common {\n\nusing DateTime = QDateTime;\n\nusing Event = QMutex;\n\nusing Mutex = QMutex;\n\nusing MutexLocker = QMutexLocker;\n\nusing Locale = QLocale;\n\nusing DataStream = QDataStream;\n\nusing IODevice = QIODevice;\n\n} // namespace common\n", "file_path": "sdk/rms_sdk/Common/FrameworkSpecificTypes.h", "rank": 62, "score": 82873.13646197713 }, { "content": "namespace rmscore {\n\nnamespace modernapi {\n\nenum ResponseCacheFlags {\n\n RESPONSE_CACHE_NOCACHE = 0x00,\n\n RESPONSE_CACHE_INMEMORY= 0x01,\n\n RESPONSE_CACHE_ONDISK = 0x02,\n\n RESPONSE_CACHE_CRYPTED = 0x04,\n\n};\n\n} // namespace modernapi\n", "file_path": "sdk/rms_sdk/ModernAPI/CacheControl.h", "rank": 63, "score": 82873.13646197713 }, { "content": "namespace rmscore {\n\nnamespace restclients {\n\nstruct ServiceDiscoveryDetails\n\n{\n\n std::string EndUserLicensesUrl;\n\n std::string TemplatesUrl;\n\n std::string PublishingLicensesUrl;\n\n std::string CloudDiagnosticsServerUrl;\n\n std::string PerformanceServerUrl;\n\n std::string Domain;\n\n std::string OriginalInput;\n\n uint32_t Ttl;\n\n};\n\n} // namespace restclients\n", "file_path": "sdk/rms_sdk/RestClients/ServiceDiscoveryDetails.h", "rank": 64, "score": 81911.65915546409 }, { "content": " const String Error = \"error\";\n", "file_path": "sdk/rmsauth_sdk/rmsauth/rmsauth/OAuthConstants.h", "rank": 65, "score": 81907.07409841154 }, { "content": "class QUdpSocket;\n\n\n\nnamespace rmscore {\n\nnamespace platform {\n\nnamespace http {\n", "file_path": "sdk/rms_sdk/Platform/Http/DnsServerResolverQt.h", "rank": 66, "score": 81523.36285432256 }, { "content": " const String ServiceReturnedError = \"service_returned_error\";\n", "file_path": "sdk/rmsauth_sdk/rmsauth/rmsauth/Constants.h", "rank": 67, "score": 79992.69917925369 }, { "content": " const String FederatedServiceReturnedError = \"federated_service_returned_error\";\n", "file_path": "sdk/rmsauth_sdk/rmsauth/rmsauth/Constants.h", "rank": 68, "score": 78158.23370646256 }, { "content": " const String GetUserNameFailed = \"get_user_name_failed\";\n", "file_path": "sdk/rmsauth_sdk/rmsauth/rmsauth/Constants.h", "rank": 69, "score": 78034.45586476794 }, { "content": " char *zBuf; /* Space to buffer journal writes */\n", "file_path": "sdk/rmscrypto_sdk/Platform/KeyStorage/sqlite3.c", "rank": 70, "score": 77715.00527252363 }, { "content": " struct InLoop {\n\n int iCur; /* The VDBE cursor used by this IN operator */\n\n int addrInTop; /* Top of the IN loop */\n", "file_path": "sdk/rmscrypto_sdk/Platform/KeyStorage/sqlite3.c", "rank": 71, "score": 77713.74522279562 }, { "content": " int nChar; /* Number of UChar elements in pInput */\n", "file_path": "sdk/rmscrypto_sdk/Platform/KeyStorage/sqlite3.c", "rank": 72, "score": 77712.39372740798 }, { "content": " UChar *aChar; /* Copy of input using utf-16 encoding */\n", "file_path": "sdk/rmscrypto_sdk/Platform/KeyStorage/sqlite3.c", "rank": 73, "score": 77712.26047221459 }, { "content": " u8 readOnly; /* True for read-only statements */\n", "file_path": "sdk/rmscrypto_sdk/Platform/KeyStorage/sqlite3.c", "rank": 74, "score": 77710.87657880531 }, { "content": " Mem *pArgc;\n", "file_path": "sdk/rmscrypto_sdk/Platform/KeyStorage/sqlite3.c", "rank": 75, "score": 77710.45569363276 }, { "content": " int iBreak; /* Jump here to break out of the loop */\n", "file_path": "sdk/rmscrypto_sdk/Platform/KeyStorage/sqlite3.c", "rank": 76, "score": 77710.45569363276 }, { "content": " Token eOperator; /* \"like\" or \"glob\" or \"regexp\" */\n", "file_path": "sdk/rmscrypto_sdk/Platform/KeyStorage/sqlite3.c", "rank": 77, "score": 77709.11033079561 }, { "content": " int nBuf; /* Size of zBuf[] in bytes */\n", "file_path": "sdk/rmscrypto_sdk/Platform/KeyStorage/sqlite3.c", "rank": 78, "score": 77709.11033079561 }, { "content": " char *pRead; /* Cursor used to iterate through aDoclist */\n", "file_path": "sdk/rmscrypto_sdk/Platform/KeyStorage/sqlite3.c", "rank": 79, "score": 77699.42190441999 }, { "content": " Bitmask used; /* Bitmask of cursors used by this plan */\n", "file_path": "sdk/rmscrypto_sdk/Platform/KeyStorage/sqlite3.c", "rank": 80, "score": 77697.03308513813 }, { "content": " IdList *pUsing; /* The USING clause of a join */\n", "file_path": "sdk/rmscrypto_sdk/Platform/KeyStorage/sqlite3.c", "rank": 81, "score": 77697.03308513813 }, { "content": " int *aOffset; /* Offsets of each character in utf-8 input */\n", "file_path": "sdk/rmscrypto_sdk/Platform/KeyStorage/sqlite3.c", "rank": 82, "score": 77694.27755628407 }, { "content": " Expr *pOffset; /* OFFSET expression. NULL means not used. */\n", "file_path": "sdk/rmscrypto_sdk/Platform/KeyStorage/sqlite3.c", "rank": 83, "score": 77694.27755628407 }, { "content": " int iOffset; /* current position in pInput */\n", "file_path": "sdk/rmscrypto_sdk/Platform/KeyStorage/sqlite3.c", "rank": 84, "score": 77688.67774325809 }, { "content": " int isError; /* Error code returned by the function. */\n", "file_path": "sdk/rmscrypto_sdk/Platform/KeyStorage/sqlite3.c", "rank": 85, "score": 77686.99808384439 }, { "content": "\n\n enum HttpRequestType\n\n {\n\n HTTP_GET,\n\n HTTP_POST,\n\n };\n\n\n\n struct HttpRequestParameters\n\n {\n\n HttpRequestType type;\n\n std::string requestUrl;\n\n common::ByteArray requestBody;\n\n std::string accessToken;\n\n std::shared_ptr<std::atomic<bool>> cancelState;\n\n };\n\n\n\n static Result DoHttpRequest(const HttpRequestParameters& parameters);\n\n\n\n static std::string ConstructAuthTokenHeader(const std::string& accessToken);\n\n static std::string ConstructLanguageHeader();\n\n static std::string GenerateRequestId();\n\n static std::string GetPlatformIdHeader();\n\n\n\n static std::string m_sPlatformIdHeaderCache;\n\n};\n\n} // namespace restclients\n\n} // namespace rmscore\n\n#endif // _RMS_LIB_RESTHTTPCLIENT_H_\n", "file_path": "sdk/rms_sdk/RestClients/RestHttpClient.h", "rank": 86, "score": 55.118258807197236 }, { "content": "#include \"../Platform/Http/IUri.h\"\n\n\n\n\n\nusing namespace rmscore::modernapi;\n\nusing namespace rmscore::platform::http;\n\nusing namespace std;\n\n\n\nnamespace rmscore {\n\nnamespace restclients {\n\n\n\nnamespace {\n\n const std::string SLC_HEADER_KEY = \"x-ms-rms-slc-key\";\n\n const std::string SERVICE_URL_HEADER_KEY = \"x-ms-rms-service-url\";\n\n}\n\n\n\n\n\nstring AuthenticationHandler::GetAccessTokenForUrl(const string& sUrl,\n\n const AuthenticationHandlerParameters& authParams,\n\n IAuthenticationCallbackImpl& callback,\n\n std::shared_ptr<std::atomic<bool>> cancelState)\n", "file_path": "sdk/rms_sdk/RestClients/AuthenticationHandler.cpp", "rank": 87, "score": 49.636412479540915 }, { "content": " Logger::error(Tag(), errString);\n\n throw RmsauthServiceException(errString);\n\n }\n\n\n\n HttpHelperQt::verifyCorrelationIdHeaderInReponse(pReply, callState);\n\n\n\n auto body = pReply->readAll();\n\n HttpHelperQt::logResponseBody(body);\n\n return std::move(body);\n\n}\n\n\n\nQByteArray HttpHelperQt::jobPostRunner(QNetworkRequest& request, const RequestParameters& requestParameters, CallStatePtr callState)\n\n{\n\n Logger::info(Tag(), \"jobPostRunner\");\n\n\n\n int argc = 1;\n\n char name[] = \"jobPostRunner\";\n\n char **argv = new char *[argc];\n\n\n\n argv[0] = name;\n", "file_path": "sdk/rmsauth_sdk/rmsauth/HttpHelperQt.cpp", "rank": 88, "score": 48.37000179606642 }, { "content": "#include \"LicenseParserResult.h\"\n\n#include \"RestClientErrorHandling.h\"\n\n#include \"UsageRestrictionsClient.h\"\n\n\n\nusing namespace std;\n\nusing namespace rmscore::modernapi;\n\nusing namespace rmscore::platform::http;\n\nusing namespace rmscore::restclients;\n\nusing namespace rmscore::json;\n\nusing namespace rmscore::platform::logger;\n\n\n\nnamespace rmscore {\n\nnamespace restclients {\n\nstd::shared_ptr<UsageRestrictionsResponse>UsageRestrictionsClient::\n\nGetUsageRestrictions(const UsageRestrictionsRequest & request,\n\n modernapi::IAuthenticationCallbackImpl& authCallback,\n\n modernapi::IConsentCallbackImpl & consentCallback,\n\n const string & email,\n\n const bool bOffline,\n\n std::shared_ptr<std::atomic<bool> > cancelState,\n", "file_path": "sdk/rms_sdk/RestClients/UsageRestrictionsClient.cpp", "rank": 89, "score": 47.049367639191146 }, { "content": "using namespace rmscore::platform::settings;\n\nusing namespace rmscore::platform::logger;\n\n\n\nnamespace rmscore {\n\nnamespace restclients {\n\nRestHttpClient::Result RestHttpClient::Get(const std::string& sUrl,\n\n const AuthenticationHandler::AuthenticationHandlerParameters& authParams,\n\n IAuthenticationCallbackImpl& authenticationCallback,\n\n std::shared_ptr<std::atomic<bool>> cancelState)\n\n{\n\n // Performance latency should exclude the time it takes in Authentication and\n\n // consent operations\n\n auto accessToken = AuthenticationHandler::GetAccessTokenForUrl(sUrl,\n\n authParams,\n\n authenticationCallback,\n\n cancelState);\n\n\n\n Logger::Hidden(\"access token %s\", accessToken.c_str());\n\n\n\n auto parameters = HttpRequestParameters {\n", "file_path": "sdk/rms_sdk/RestClients/RestHttpClient.cpp", "rank": 90, "score": 46.31928973033363 }, { "content": " std::shared_ptr<std::atomic<bool>> cancelState)\n\n{\n\n auto url = this->CreateGetRequest(discoveryUrl, domain);\n\n // Make sure stParams is filled, and get the original domain input used to generate the domain\n\n\n\n std::string publicCertificate(pServerPublicCertificate.get() == nullptr ? \"\" : *pServerPublicCertificate);\n\n std::string originalInput(domain.GetOriginalInput());\n\n\n\n auto authParams = AuthenticationHandler::AuthenticationHandlerParameters\n\n {\n\n publicCertificate,\n\n originalInput\n\n };\n\n\n\n auto result = RestHttpClient::Get(url, authParams, authenticationCallback, cancelState);\n\n\n\n if (result.status != http::StatusCode::OK)\n\n {\n\n HandleRestClientError(result.status, result.responseBody);\n\n }\n", "file_path": "sdk/rms_sdk/RestClients/ServiceDiscoveryClient.cpp", "rank": 91, "score": 44.910039591010516 }, { "content": "\n\nprivate:\n\n\n\n static modernapi::AuthenticationChallenge GetChallengeForUrl(const std::string& sUrl,\n\n const AuthenticationHandlerParameters& authParams,\n\n std::shared_ptr<std::atomic<bool>> cancelState);\n\n\n\n static modernapi::AuthenticationChallenge GetChallengeForUrl(const std::string& sUrl,\n\n common::ByteArray&& requestBody,\n\n std::shared_ptr<std::atomic<bool>> cancelState);\n\n\n\n static modernapi::AuthenticationChallenge ParseChallengeHeader(const std::string& header,\n\n const std::string& url);\n\n};\n\n\n\n} // namespace restclients\n\n} // namespace rmscore\n\n#endif // _RMS_LIB_AUTHENTICATIONHANDLER_H_\n", "file_path": "sdk/rms_sdk/RestClients/AuthenticationHandler.h", "rank": 92, "score": 43.858320573053135 }, { "content": " const std::string & strElementName,\n\n std::vector<std::string>& vOccurrences,\n\n bool includeTag = true);\n\n\n\n static void WrapWithRoot(const char *szXML,\n\n size_t xmlSize,\n\n std::string& wstrWrapped);\n\n};\n\n} // namespace restclients\n\n} // namespace rmscore\n\n#endif // _RMS_LIB_CXMLUTILS_H_\n", "file_path": "sdk/rms_sdk/RestClients/CXMLUtils.h", "rank": 93, "score": 43.43264144418874 }, { "content": "\n\n int argc = 1;\n\n char name[] = \"jobGetRunner\";\n\n char ** argv = new char*[argc];\n\n argv[0] = name;\n\n QCoreApplication a(argc, argv);\n\n\n\n auto body = jobGet(request, callState);\n\n\n\n QTimer::singleShot(0, &a, SLOT(quit()));\n\n a.exec();\n\n\n\n return std::move(body);\n\n}\n\n\n\nQByteArray HttpHelperQt::jobPost(QNetworkRequest& request, const RequestParameters& requestParameters, CallStatePtr callState)\n\n{\n\n Logger::info(Tag(), \"jobPost\");\n\n\n\n if ((callState != nullptr) && !callState->correlationId().empty())\n", "file_path": "sdk/rmsauth_sdk/rmsauth/HttpHelperQt.cpp", "rank": 94, "score": 43.21577549077705 }, { "content": " pHttpClient->AddHeader(\"x-ms-rms-platform-id\", m_sPlatformIdHeaderCache);\n\n\n\n Result result;\n\n\n\n switch (parameters.type)\n\n {\n\n case HTTP_POST:\n\n {\n\n Logger::Hidden(\"RestHttpClient::DoHttpRequest doing http POST to %s, Request-ID: %s\",\n\n parameters.requestUrl.c_str(),\n\n requestId.c_str());\n\n\n\n result.status = pHttpClient->Post(parameters.requestUrl,\n\n parameters.requestBody, std::string(\"application/json\"),\n\n result.responseBody,\n\n parameters.cancelState);\n\n }\n\n break;\n\n case HTTP_GET:\n\n {\n", "file_path": "sdk/rms_sdk/RestClients/RestHttpClient.cpp", "rank": 95, "score": 43.09906560659605 }, { "content": " {\n\n HttpHelperQt::addCorrelationIdHeadersToRequest(request, callState);\n\n }\n\n HttpHelperQt::logRequestHeaders(request);\n\n Logger::info(Tag(), \"request url: %\", request.url().toString().toStdString());\n\n Logger::info(Tag(), \"request body: %\", requestParameters.toString());\n\n\n\n QNetworkAccessManager nam;\n\n QNetworkReply *pReply = nam.post(request, requestParameters.toString().data());\n\n QEventLoop loop;\n\n QObject::connect(pReply, SIGNAL(finished()), &loop, SLOT(quit()));\n\n loop.exec();\n\n\n\n HttpHelperQt::logResponseHeaders(pReply);\n\n\n\n QNetworkReply::NetworkError error_type = pReply->error();\n\n\n\n if (error_type != QNetworkReply::NoError)\n\n {\n\n String errString = QString(\"error: %1\").arg(pReply->errorString()).toStdString();\n", "file_path": "sdk/rmsauth_sdk/rmsauth/HttpHelperQt.cpp", "rank": 96, "score": 42.464599981286256 }, { "content": " bool useCookie = promptBehavior_ != PromptBehavior::Always;\n\n\n\n if(qApp == nullptr)\n\n {\n\n#ifdef QT_VER_LESS_THEN_54\n\n // To avoid issue #17 (https://github.com/MSOpenTech/rms-sdk-cpp/issues/17)\n\n // for QT versions less then 5.4\n\n // we need to create QApplication instance in a separate thread.\n\n auto fut = std::async(std::launch::async, &jobRunnerAuthenticate, requestUri, callbackUri, useCookie);\n\n auto result = fut.get();\n\n return std::move(result);\n\n#else\n\n int argc = 1;\n\n char name[] = \"authenticate\";\n\n char ** argv = new char*[argc];\n\n argv[0] = name;\n\n\n\n QApplication a(argc, argv);\n\n\n\n auto result = jobAuthenticate(requestUri, callbackUri, useCookie);\n", "file_path": "sdk/rmsauth_sdk/rmsauth/WebUIQt.cpp", "rank": 97, "score": 42.15451470672848 }, { "content": "using namespace rmscore::json;\n\nusing namespace rmscore::platform::http;\n\n\n\nnamespace rmscore {\n\nnamespace restclients {\n\n\n\nTemplateListResponse TemplatesClient::GetTemplates(modernapi::IAuthenticationCallbackImpl& authenticationCallback,\n\n const std::string& sEmail,\n\n std::shared_ptr<std::atomic<bool>> cancelState)\n\n{\n\n auto pRestServiceUrlClient = IRestServiceUrlClient::Create();\n\n auto templatesUrl = pRestServiceUrlClient->GetTemplatesUrl(sEmail,\n\n authenticationCallback,\n\n cancelState);\n\n\n\n AuthenticationHandler::AuthenticationHandlerParameters authParams;\n\n auto result =\n\n RestHttpClient::Get(templatesUrl,\n\n authParams,\n\n authenticationCallback,\n", "file_path": "sdk/rms_sdk/RestClients/TemplatesClient.cpp", "rank": 98, "score": 42.02030162549846 }, { "content": " void sendAuthorizeRequest();\n\n static bool includeFormsAuthParams();\n\n String createAuthorizationUriAsync(const Guid& correlationId);\n\n\n\nprivate:\n\n String createAuthorizationUri(bool includeFormsAuthParam);\n\n RequestParameters createAuthorizationRequest(const String& loginHint, bool includeFormsAuthParam);\n\n void verifyAuthorizationResult();\n\n static bool isDomainJoined();\n\n static bool isUserLocal();\n\n void setRedirectUriRequestParameter();\n\n static void addHeadersToRequestParameters(RequestParameters& requestParameters, Headers headers);\n\n};\n\n\n\n} // namespace rmsauth {\n\n\n\n#endif // ACQUIRETOKENINTERACTIVEHANDLER_H\n", "file_path": "sdk/rmsauth_sdk/rmsauth/rmsauth/AcquireTokenInteractiveHandler.h", "rank": 99, "score": 41.363838404769375 } ]
C++
rocsolver/clients/gtest/getri_gtest.cpp
eidenyoshida/rocSOLVER
1240759207b63f8aeba51db259873141c72f9735
#include "testing_getri.hpp" using ::testing::Combine; using ::testing::TestWithParam; using ::testing::Values; using ::testing::ValuesIn; using namespace std; typedef vector<int> getri_tuple; const vector<vector<int>> matrix_size_range = { {0, 1}, {-1, 1}, {20, 5}, {32, 32}, {50, 50}, {70, 100}, {100, 150} }; const vector<vector<int>> large_matrix_size_range = { {192, 192}, {500, 600}, {640, 640}, {1000, 1024}, {1200, 1230} }; Arguments getri_setup_arguments(getri_tuple tup) { Arguments arg; arg.N = tup[0]; arg.lda = tup[1]; arg.timing = 0; arg.bsp = arg.N; arg.bsa = arg.lda * arg.N; return arg; } class GETRI : public ::TestWithParam<getri_tuple> { protected: GETRI() {} virtual void SetUp() {} virtual void TearDown() {} }; TEST_P(GETRI, __float) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,false,float>(); arg.batch_count = 1; testing_getri<false,false,float>(arg); } TEST_P(GETRI, __double) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,false,double>(); arg.batch_count = 1; testing_getri<false,false,double>(arg); } TEST_P(GETRI, __float_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,false,rocblas_float_complex>(); arg.batch_count = 1; testing_getri<false,false,rocblas_float_complex>(arg); } TEST_P(GETRI, __double_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,false,rocblas_double_complex>(); arg.batch_count = 1; testing_getri<false,false,rocblas_double_complex>(arg); } TEST_P(GETRI, batched__float) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,true,float>(); arg.batch_count = 3; testing_getri<true,true,float>(arg); } TEST_P(GETRI, batched__double) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,true,double>(); arg.batch_count = 3; testing_getri<true,true,double>(arg); } TEST_P(GETRI, batched__float_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,true,rocblas_float_complex>(); arg.batch_count = 3; testing_getri<true,true,rocblas_float_complex>(arg); } TEST_P(GETRI, batched__double_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,true,rocblas_double_complex>(); arg.batch_count = 3; testing_getri<true,true,rocblas_double_complex>(arg); } TEST_P(GETRI, strided_batched__float) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,true,float>(); arg.batch_count = 3; testing_getri<false,true,float>(arg); } TEST_P(GETRI, strided_batched__double) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,true,double>(); arg.batch_count = 3; testing_getri<false,true,double>(arg); } TEST_P(GETRI, strided_batched__float_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,true,rocblas_float_complex>(); arg.batch_count = 3; testing_getri<false,true,rocblas_float_complex>(arg); } TEST_P(GETRI, strided_batched__double_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,true,rocblas_double_complex>(); arg.batch_count = 3; testing_getri<false,true,rocblas_double_complex>(arg); } TEST_P(GETRI, outofplace_batched__float) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,false,float>(); arg.batch_count = 3; testing_getri<true,false,float>(arg); } TEST_P(GETRI, outofplace_batched__double) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,false,double>(); arg.batch_count = 3; testing_getri<true,false,double>(arg); } TEST_P(GETRI, outofplace_batched__float_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,false,rocblas_float_complex>(); arg.batch_count = 3; testing_getri<true,false,rocblas_float_complex>(arg); } TEST_P(GETRI, outofplace_batched__double_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,false,rocblas_double_complex>(); arg.batch_count = 3; testing_getri<true,false,rocblas_double_complex>(arg); } INSTANTIATE_TEST_SUITE_P(daily_lapack, GETRI, ValuesIn(large_matrix_size_range)); INSTANTIATE_TEST_SUITE_P(checkin_lapack, GETRI, ValuesIn(matrix_size_range));
#include "testing_getri.hpp" using ::testing::Combine; using ::testing::TestWithParam; using ::testing::Values; using ::testing::ValuesIn; using namespace std; typedef vector<int> getri_tuple; const vector<vector<int>> matrix_size_range = { {0, 1}, {-1, 1}, {20, 5}, {32, 32}, {50, 50}, {70, 100}, {100, 150} }; const vector<vector<int>> large_matrix_size_range = { {192, 192}, {500, 600}, {640, 640}, {1000, 1024}, {1200, 1230} }; Arguments getri_setup_arguments(getri_tuple tup) { Arguments arg; arg.N = tup[0]; arg.lda = tup[1]; arg.timing = 0; arg.bsp = arg.N; arg.bsa = arg.lda * arg.N; return arg; } class GETRI : public ::TestWithParam<getri_tuple> { protected: GETRI() {} virtual void SetUp() {} virtual void TearDown() {} }; TEST_P(GETRI, __float) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,false,float>(); arg.batch_count = 1; testing_getri<false,false,float>(arg); }
TEST_P(GETRI, __float_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,false,rocblas_float_complex>(); arg.batch_count = 1; testing_getri<false,false,rocblas_float_complex>(arg); } TEST_P(GETRI, __double_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,false,rocblas_double_complex>(); arg.batch_count = 1; testing_getri<false,false,rocblas_double_complex>(arg); } TEST_P(GETRI, batched__float) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,true,float>(); arg.batch_count = 3; testing_getri<true,true,float>(arg); } TEST_P(GETRI, batched__double) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,true,double>(); arg.batch_count = 3; testing_getri<true,true,double>(arg); } TEST_P(GETRI, batched__float_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,true,rocblas_float_complex>(); arg.batch_count = 3; testing_getri<true,true,rocblas_float_complex>(arg); } TEST_P(GETRI, batched__double_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,true,rocblas_double_complex>(); arg.batch_count = 3; testing_getri<true,true,rocblas_double_complex>(arg); } TEST_P(GETRI, strided_batched__float) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,true,float>(); arg.batch_count = 3; testing_getri<false,true,float>(arg); } TEST_P(GETRI, strided_batched__double) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,true,double>(); arg.batch_count = 3; testing_getri<false,true,double>(arg); } TEST_P(GETRI, strided_batched__float_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,true,rocblas_float_complex>(); arg.batch_count = 3; testing_getri<false,true,rocblas_float_complex>(arg); } TEST_P(GETRI, strided_batched__double_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,true,rocblas_double_complex>(); arg.batch_count = 3; testing_getri<false,true,rocblas_double_complex>(arg); } TEST_P(GETRI, outofplace_batched__float) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,false,float>(); arg.batch_count = 3; testing_getri<true,false,float>(arg); } TEST_P(GETRI, outofplace_batched__double) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,false,double>(); arg.batch_count = 3; testing_getri<true,false,double>(arg); } TEST_P(GETRI, outofplace_batched__float_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,false,rocblas_float_complex>(); arg.batch_count = 3; testing_getri<true,false,rocblas_float_complex>(arg); } TEST_P(GETRI, outofplace_batched__double_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,false,rocblas_double_complex>(); arg.batch_count = 3; testing_getri<true,false,rocblas_double_complex>(arg); } INSTANTIATE_TEST_SUITE_P(daily_lapack, GETRI, ValuesIn(large_matrix_size_range)); INSTANTIATE_TEST_SUITE_P(checkin_lapack, GETRI, ValuesIn(matrix_size_range));
TEST_P(GETRI, __double) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,false,double>(); arg.batch_count = 1; testing_getri<false,false,double>(arg); }
function_block-full_function
[ { "content": "class RocBLAS_Test : public testing::TestWithParam<Arguments>\n\n{\n\nprotected:\n\n // This template functor returns true if the type arguments are valid.\n\n // It converts a FILTER specialization to bool to test type matching.\n\n template <typename... T>\n\n struct type_filter_functor\n\n {\n\n bool operator()(const Arguments&)\n\n {\n\n return static_cast<bool>(FILTER<T...>{});\n\n }\n\n };\n\n\n\npublic:\n\n // Wrapper functor class which calls name_suffix()\n\n struct PrintToStringParamName\n\n {\n\n std::string operator()(const testing::TestParamInfo<Arguments>& info) const\n\n {\n\n return TEST::name_suffix(info.param);\n\n }\n\n };\n\n};\n\n\n\n#endif // GOOGLE_TEST\n\n\n", "file_path": "rocblascommon/clients/include/rocblas_test.hpp", "rank": 1, "score": 187759.07147580895 }, { "content": "class Arguments {\n\npublic:\n\n rocblas_int M = 128;\n\n rocblas_int N = 128;\n\n rocblas_int K = 128;\n\n rocblas_int S4 = 128;\n\n rocblas_int k1 = 1;\n\n rocblas_int k2 = 2;\n\n\n\n rocblas_int lda = 128;\n\n rocblas_int ldb = 128;\n\n rocblas_int ldc = 128;\n\n rocblas_int ldv = 128;\n\n rocblas_int ldt = 128;\n\n\n\n rocblas_int incx = 1;\n\n rocblas_int incy = 1;\n\n rocblas_int incd = 1;\n\n rocblas_int incb = 1;\n\n\n", "file_path": "rocsolver/clients/include/rocsolver_arguments.hpp", "rank": 2, "score": 171271.67344219607 }, { "content": "class device_strided_batch_vector : public d_vector<T, PAD, U>\n\n{\n\npublic:\n\n //!\n\n //! @brief The storage type to use.\n\n //!\n\n typedef enum class estorage\n\n {\n\n block,\n\n interleave,\n\n } storage;\n\n\n\n //!\n\n //! @brief Disallow copying.\n\n //!\n\n device_strided_batch_vector(const device_strided_batch_vector&) = delete;\n\n\n\n //!\n\n //! @brief Disallow assigning.\n\n //!\n", "file_path": "rocblascommon/clients/include/device_strided_batch_vector.hpp", "rank": 3, "score": 138205.8424538185 }, { "content": "class LABRD : public ::TestWithParam<labrd_tuple> {\n\nprotected:\n\n LABRD() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n\n\n\nTEST_P(LABRD, __float) {\n\n Arguments arg = labrd_setup_arguments(GetParam());\n\n\n\n if (arg.M == 0 && arg.N == 0)\n\n testing_labrd_bad_arg<float>();\n\n\n\n arg.batch_count = 1;\n\n testing_labrd<float>(arg);\n\n}\n\n\n\nTEST_P(LABRD, __double) {\n\n Arguments arg = labrd_setup_arguments(GetParam());\n", "file_path": "rocsolver/clients/gtest/labrd_gtest.cpp", "rank": 4, "score": 116554.98279486751 }, { "content": "class BDSQR : public ::TestWithParam<bdsqr_tuple> {\n\nprotected:\n\n BDSQR() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n\n\n\nTEST_P(BDSQR, __float) {\n\n Arguments arg = bdsqr_setup_arguments(GetParam());\n\n\n\n if (arg.M == 0 && arg.uplo_option == 'L')\n\n testing_bdsqr_bad_arg<float>();\n\n\n\n testing_bdsqr<float>(arg);\n\n}\n\n\n\nTEST_P(BDSQR, __double) {\n\n Arguments arg = bdsqr_setup_arguments(GetParam());\n\n\n", "file_path": "rocsolver/clients/gtest/bdsqr_gtest.cpp", "rank": 5, "score": 116554.98279486751 }, { "content": "class LARFT : public ::TestWithParam<larft_tuple> {\n\nprotected:\n\n LARFT() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n\n\n\nTEST_P(LARFT, __float) {\n\n Arguments arg = larft_setup_arguments(GetParam());\n\n\n\n if (arg.N == 0 && arg.K == 0)\n\n testing_larft_bad_arg<float>(); \n\n\n\n testing_larft<float>(arg);\n\n}\n\n\n\nTEST_P(LARFT, __double) {\n\n Arguments arg = larft_setup_arguments(GetParam());\n\n\n", "file_path": "rocsolver/clients/gtest/larft_gtest.cpp", "rank": 6, "score": 116554.98279486751 }, { "content": "class LARFB : public ::TestWithParam<larfb_tuple> {\n\nprotected:\n\n LARFB() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n\nTEST_P(LARFB, __float) {\n\n Arguments arg = larfb_setup_arguments(GetParam());\n\n\n\n if (arg.M == 0 && arg.K == 0)\n\n testing_larfb_bad_arg<float>();\n\n\n\n testing_larfb<float>(arg);\n\n}\n\n\n\nTEST_P(LARFB, __double) {\n\n Arguments arg = larfb_setup_arguments(GetParam());\n\n\n\n if (arg.M == 0 && arg.K == 0)\n", "file_path": "rocsolver/clients/gtest/larfb_gtest.cpp", "rank": 7, "score": 116554.98279486751 }, { "content": "class LASWP : public ::TestWithParam<laswp_tuple> {\n\nprotected:\n\n LASWP() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n\nTEST_P(LASWP, __float) {\n\n Arguments arg = laswp_setup_arguments(GetParam());\n\n\n\n if (arg.N == 0 && arg.k1 == 1 && arg.k2 == 3)\n\n testing_laswp_bad_arg<float>();\n\n\n\n testing_laswp<float>(arg);\n\n}\n\n\n\nTEST_P(LASWP, __double) {\n\n Arguments arg = laswp_setup_arguments(GetParam());\n\n\n\n if (arg.N == 0 && arg.k1 == 1 && arg.k2 == 3)\n", "file_path": "rocsolver/clients/gtest/laswp_gtest.cpp", "rank": 8, "score": 116554.98279486751 }, { "content": "class LACGV : public ::TestWithParam<lacgv_tuple> {\n\nprotected:\n\n LACGV() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n\nTEST_P(LACGV, __float_complex) {\n\n Arguments arg = lacgv_setup_arguments(GetParam());\n\n \n\n if (arg.N == 0)\n\n testing_lacgv_bad_arg<rocblas_float_complex>();\n\n\n\n testing_lacgv<rocblas_float_complex>(arg);\n\n}\n\n\n\nTEST_P(LACGV, __double_complex) {\n\n Arguments arg = lacgv_setup_arguments(GetParam());\n\n \n\n if (arg.N == 0)\n", "file_path": "rocsolver/clients/gtest/lacgv_gtest.cpp", "rank": 9, "score": 116554.98279486751 }, { "content": "class GETRS : public ::TestWithParam<getrs_tuple> {\n\nprotected:\n\n GETRS() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n\n\n\n// non-batch tests\n\n\n\nTEST_P(GETRS, __float) {\n\n Arguments arg = getrs_setup_arguments(GetParam());\n\n\n\n if (arg.M == 0 && arg.N == 0)\n\n testing_getrs_bad_arg<false,false,float>();\n\n\n\n arg.batch_count = 1;\n\n testing_getrs<false,false,float>(arg);\n\n}\n\n\n", "file_path": "rocsolver/clients/gtest/getrs_gtest.cpp", "rank": 10, "score": 116554.98279486751 }, { "content": "class LARFG : public ::TestWithParam<larfg_tuple> {\n\nprotected:\n\n LARFG() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n\nTEST_P(LARFG, __float) {\n\n Arguments arg = larfg_setup_arguments(GetParam());\n\n \n\n if (arg.N == 0 && arg.incx == 0)\n\n testing_larfg_bad_arg<float>();\n\n\n\n testing_larfg<float>(arg);\n\n}\n\n\n\nTEST_P(LARFG, __double) {\n\n Arguments arg = larfg_setup_arguments(GetParam());\n\n \n\n if (arg.N == 0 && arg.incx == 0)\n", "file_path": "rocsolver/clients/gtest/larfg_gtest.cpp", "rank": 11, "score": 116554.98279486751 }, { "content": "class LARF : public ::TestWithParam<larf_tuple> {\n\nprotected:\n\n LARF() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n\nTEST_P(LARF, __float) {\n\n Arguments arg = larf_setup_arguments(GetParam());\n\n\n\n if (arg.M == 0 && arg.incx == 0)\n\n testing_larf_bad_arg<float>();\n\n\n\n testing_larf<float>(arg);\n\n}\n\n\n\nTEST_P(LARF, __double) {\n\n Arguments arg = larf_setup_arguments(GetParam());\n\n\n\n if (arg.M == 0 && arg.incx == 0)\n", "file_path": "rocsolver/clients/gtest/larf_gtest.cpp", "rank": 12, "score": 116554.98279486751 }, { "content": "class d_vector\n\n{\n\nprivate:\n\n size_t size, bytes;\n\n\n\npublic:\n\n inline size_t nmemb() const noexcept\n\n {\n\n return size;\n\n }\n\n\n\n#ifdef GOOGLE_TEST\n\n U guard[PAD];\n\n d_vector(size_t s)\n\n : size(s)\n\n , bytes((s + PAD * 2) * sizeof(T))\n\n {\n\n // Initialize guard with random data\n\n if(PAD > 0)\n\n {\n", "file_path": "rocblascommon/clients/include/d_vector.hpp", "rank": 13, "score": 115654.96211465215 }, { "content": "class ORGBR : public ::TestWithParam<orgbr_tuple> {\n\nprotected:\n\n ORGBR() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n", "file_path": "rocsolver/clients/gtest/orgbr_ungbr_gtest.cpp", "rank": 14, "score": 114824.07613190913 }, { "content": "class GETRF : public ::TestWithParam<getrf_tuple> {\n\nprotected:\n\n GETRF() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n", "file_path": "rocsolver/clients/gtest/getf2_getrf_gtest.cpp", "rank": 15, "score": 114824.07613190913 }, { "content": "class ORML2 : public ::TestWithParam<ormlq_tuple> {\n\nprotected:\n\n ORML2() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n", "file_path": "rocsolver/clients/gtest/ormlx_unmlx_gtest.cpp", "rank": 16, "score": 114824.07613190913 }, { "content": "class GEQR2 : public ::TestWithParam<geqrf_tuple> {\n\nprotected:\n\n GEQR2() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n", "file_path": "rocsolver/clients/gtest/geqr2_geqrf_gtest.cpp", "rank": 17, "score": 114824.07613190913 }, { "content": "class POTF2 : public ::TestWithParam<potrf_tuple> {\n\nprotected:\n\n POTF2() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n", "file_path": "rocsolver/clients/gtest/potf2_potrf_gtest.cpp", "rank": 18, "score": 114824.07613190913 }, { "content": "class POTRF : public ::TestWithParam<potrf_tuple> {\n\nprotected:\n\n POTRF() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n\n\n\n// non-batch tests\n\n\n\nTEST_P(POTF2, __float) {\n\n Arguments arg = potrf_setup_arguments(GetParam());\n\n\n\n if (arg.uplo_option == 'L' && arg.N == 0)\n\n testing_potf2_potrf_bad_arg<false,false,0,float>();\n\n\n\n arg.batch_count = 1;\n\n testing_potf2_potrf<false,false,0,float>(arg);\n\n}\n\n\n", "file_path": "rocsolver/clients/gtest/potf2_potrf_gtest.cpp", "rank": 19, "score": 114824.07613190913 }, { "content": "class UNGL2 : public ::TestWithParam<orglq_tuple> {\n\nprotected:\n\n UNGL2() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n", "file_path": "rocsolver/clients/gtest/orglx_unglx_gtest.cpp", "rank": 20, "score": 114824.07613190913 }, { "content": "class GEBD2 : public ::TestWithParam<gebrd_tuple> {\n\nprotected:\n\n GEBD2() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n", "file_path": "rocsolver/clients/gtest/gebd2_gebrd_gtest.cpp", "rank": 21, "score": 114824.07613190913 }, { "content": "class ORG2R : public ::TestWithParam<orgqr_tuple> {\n\nprotected:\n\n ORG2R() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n", "file_path": "rocsolver/clients/gtest/orgxr_ungxr_gtest.cpp", "rank": 22, "score": 114824.07613190913 }, { "content": "class GETF2 : public ::TestWithParam<getrf_tuple> {\n\nprotected:\n\n GETF2() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n", "file_path": "rocsolver/clients/gtest/getf2_getrf_gtest.cpp", "rank": 23, "score": 114824.07613190913 }, { "content": "class ORGLQ : public ::TestWithParam<orglq_tuple> {\n\nprotected:\n\n ORGLQ() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n", "file_path": "rocsolver/clients/gtest/orglx_unglx_gtest.cpp", "rank": 24, "score": 114824.07613190913 }, { "content": "class UNMBR : public ::TestWithParam<ormbr_tuple> {\n\nprotected:\n\n UNMBR() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n\nTEST_P(ORMBR, __float) {\n\n Arguments arg = ormbr_setup_arguments(GetParam());\n\n\n\n if (arg.M == 0 && arg.N == 1 && arg.side_option == 'L' && arg.transA_option == 'T' && arg.storev == 'C')\n\n testing_ormbr_unmbr_bad_arg<float>();\n\n\n\n testing_ormbr_unmbr<float>(arg);\n\n}\n\n\n\nTEST_P(ORMBR, __double) {\n\n Arguments arg = ormbr_setup_arguments(GetParam());\n\n\n\n if (arg.M == 0 && arg.N == 1 && arg.side_option == 'L' && arg.transA_option == 'T' && arg.storev == 'C')\n", "file_path": "rocsolver/clients/gtest/ormbr_unmbr_gtest.cpp", "rank": 25, "score": 114824.07613190913 }, { "content": "class GEQRF : public ::TestWithParam<geqrf_tuple> {\n\nprotected:\n\n GEQRF() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n\n\n\n// non-batch tests\n\n\n\nTEST_P(GEQR2, __float) {\n\n Arguments arg = geqrf_setup_arguments(GetParam());\n\n\n\n if (arg.M == 0 && arg.N == 0)\n\n testing_geqr2_geqrf_bad_arg<false,false,0,float>();\n\n\n\n arg.batch_count = 1;\n\n testing_geqr2_geqrf<false,false,0,float>(arg);\n\n}\n\n\n", "file_path": "rocsolver/clients/gtest/geqr2_geqrf_gtest.cpp", "rank": 26, "score": 114824.07613190913 }, { "content": "class UNGQR : public ::TestWithParam<orgqr_tuple> {\n\nprotected:\n\n UNGQR() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n\nTEST_P(ORG2R, __float) {\n\n Arguments arg = orgqr_setup_arguments(GetParam());\n\n\n\n if (arg.M == 0 && arg.N == 0)\n\n testing_orgxr_ungxr_bad_arg<float,0>();\n\n \n\n testing_orgxr_ungxr<float,0>(arg);\n\n}\n\n\n\nTEST_P(ORG2R, __double) {\n\n Arguments arg = orgqr_setup_arguments(GetParam());\n\n\n\n if (arg.M == 0 && arg.N == 0)\n", "file_path": "rocsolver/clients/gtest/orgxr_ungxr_gtest.cpp", "rank": 27, "score": 114824.07613190913 }, { "content": "class ORGL2 : public ::TestWithParam<orglq_tuple> {\n\nprotected:\n\n ORGL2() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n", "file_path": "rocsolver/clients/gtest/orglx_unglx_gtest.cpp", "rank": 28, "score": 114824.07613190913 }, { "content": "class UNG2R : public ::TestWithParam<orgqr_tuple> {\n\nprotected:\n\n UNG2R() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n", "file_path": "rocsolver/clients/gtest/orgxr_ungxr_gtest.cpp", "rank": 29, "score": 114824.07613190913 }, { "content": "class ORM2R : public ::TestWithParam<ormqr_tuple> {\n\nprotected:\n\n ORM2R() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n", "file_path": "rocsolver/clients/gtest/ormxr_unmxr_gtest.cpp", "rank": 30, "score": 114824.07613190913 }, { "content": "class ORMQR : public ::TestWithParam<ormqr_tuple> {\n\nprotected:\n\n ORMQR() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n", "file_path": "rocsolver/clients/gtest/ormxr_unmxr_gtest.cpp", "rank": 31, "score": 114824.07613190913 }, { "content": "class UNML2 : public ::TestWithParam<ormlq_tuple> {\n\nprotected:\n\n UNML2() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n", "file_path": "rocsolver/clients/gtest/ormlx_unmlx_gtest.cpp", "rank": 32, "score": 114824.07613190913 }, { "content": "class UNMLQ : public ::TestWithParam<ormlq_tuple> {\n\nprotected:\n\n UNMLQ() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n\nTEST_P(ORML2, __float) {\n\n Arguments arg = ormlq_setup_arguments(GetParam());\n\n\n\n if (arg.M == 0 && arg.side_option == 'L' && arg.transA_option == 'T')\n\n testing_ormlx_unmlx_bad_arg<float,0>();\n\n\n\n testing_ormlx_unmlx<float,0>(arg);\n\n}\n\n\n\nTEST_P(ORML2, __double) {\n\n Arguments arg = ormlq_setup_arguments(GetParam());\n\n\n\n if (arg.M == 0 && arg.side_option == 'L' && arg.transA_option == 'T')\n", "file_path": "rocsolver/clients/gtest/ormlx_unmlx_gtest.cpp", "rank": 33, "score": 114824.07613190913 }, { "content": "class UNGBR : public ::TestWithParam<orgbr_tuple> {\n\nprotected:\n\n UNGBR() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n\nTEST_P(ORGBR, __float) {\n\n Arguments arg = orgbr_setup_arguments(GetParam());\n\n \n\n if (arg.M == 0 && arg.N == 0 && arg.storev == 'C')\n\n testing_orgbr_ungbr_bad_arg<float>();\n\n\n\n testing_orgbr_ungbr<float>(arg);\n\n}\n\n\n\nTEST_P(ORGBR, __double) {\n\n Arguments arg = orgbr_setup_arguments(GetParam());\n\n \n\n if (arg.M == 0 && arg.N == 0 && arg.storev == 'C')\n", "file_path": "rocsolver/clients/gtest/orgbr_ungbr_gtest.cpp", "rank": 34, "score": 114824.07613190913 }, { "content": "class GEBRD : public ::TestWithParam<gebrd_tuple> {\n\nprotected:\n\n GEBRD() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n\n\n\n// non-batch tests\n\n\n\nTEST_P(GEBD2, __float) {\n\n Arguments arg = gebrd_setup_arguments(GetParam());\n\n\n\n if (arg.M == 0 && arg.N == 0)\n\n testing_gebd2_gebrd_bad_arg<false,false,0,float>();\n\n\n\n arg.batch_count = 1;\n\n testing_gebd2_gebrd<false,false,0,float>(arg);\n\n}\n\n\n", "file_path": "rocsolver/clients/gtest/gebd2_gebrd_gtest.cpp", "rank": 35, "score": 114824.07613190913 }, { "content": "class ORMBR : public ::TestWithParam<ormbr_tuple> {\n\nprotected:\n\n ORMBR() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n", "file_path": "rocsolver/clients/gtest/ormbr_unmbr_gtest.cpp", "rank": 36, "score": 114824.07613190913 }, { "content": "class GELQF : public ::TestWithParam<gelqf_tuple> {\n\nprotected:\n\n GELQF() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n\n\n\n// non-batch tests\n\n\n\nTEST_P(GELQ2, __float) {\n\n Arguments arg = gelqf_setup_arguments(GetParam());\n\n\n\n if (arg.M == 0 && arg.N == 0)\n\n testing_gelq2_gelqf_bad_arg<false,false,0,float>();\n\n\n\n arg.batch_count = 1;\n\n testing_gelq2_gelqf<false,false,0,float>(arg);\n\n}\n\n\n", "file_path": "rocsolver/clients/gtest/gelq2_gelqf_gtest.cpp", "rank": 37, "score": 114824.07613190913 }, { "content": "class UNGLQ : public ::TestWithParam<orglq_tuple> {\n\nprotected:\n\n UNGLQ() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n\n\n\nTEST_P(ORGL2, __float) {\n\n Arguments arg = orglq_setup_arguments(GetParam());\n\n\n\n if (arg.M == 0 && arg.N == 0)\n\n testing_orglx_unglx_bad_arg<float,0>();\n\n\n\n testing_orglx_unglx<float,0>(arg);\n\n}\n\n\n\nTEST_P(ORGL2, __double) {\n\n Arguments arg = orglq_setup_arguments(GetParam());\n\n\n", "file_path": "rocsolver/clients/gtest/orglx_unglx_gtest.cpp", "rank": 38, "score": 114824.07613190913 }, { "content": "class ORGQR : public ::TestWithParam<orgqr_tuple> {\n\nprotected:\n\n ORGQR() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n", "file_path": "rocsolver/clients/gtest/orgxr_ungxr_gtest.cpp", "rank": 39, "score": 114824.07613190913 }, { "content": "class ORMLQ : public ::TestWithParam<ormlq_tuple> {\n\nprotected:\n\n ORMLQ() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n", "file_path": "rocsolver/clients/gtest/ormlx_unmlx_gtest.cpp", "rank": 40, "score": 114824.07613190913 }, { "content": "class UNMQR : public ::TestWithParam<ormqr_tuple> {\n\nprotected:\n\n UNMQR() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n\nTEST_P(ORM2R, __float) {\n\n Arguments arg = ormqr_setup_arguments(GetParam());\n\n\n\n if (arg.M == 0 && arg.side_option == 'L' && arg.transA_option == 'T')\n\n testing_ormxr_unmxr_bad_arg<float,0>();\n\n\n\n testing_ormxr_unmxr<float,0>(arg);\n\n}\n\n\n\nTEST_P(ORM2R, __double) {\n\n Arguments arg = ormqr_setup_arguments(GetParam());\n\n\n\n if (arg.M == 0 && arg.side_option == 'L' && arg.transA_option == 'T')\n", "file_path": "rocsolver/clients/gtest/ormxr_unmxr_gtest.cpp", "rank": 41, "score": 114824.07613190913 }, { "content": "class GELQ2 : public ::TestWithParam<gelqf_tuple> {\n\nprotected:\n\n GELQ2() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n", "file_path": "rocsolver/clients/gtest/gelq2_gelqf_gtest.cpp", "rank": 42, "score": 114824.07613190913 }, { "content": "class UNM2R : public ::TestWithParam<ormqr_tuple> {\n\nprotected:\n\n UNM2R() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n", "file_path": "rocsolver/clients/gtest/ormxr_unmxr_gtest.cpp", "rank": 43, "score": 114824.07613190913 }, { "content": "class GETF2_NPVT : public ::TestWithParam<getrf_tuple> {\n\nprotected:\n\n GETF2_NPVT() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n", "file_path": "rocsolver/clients/gtest/getf2_getrf_gtest.cpp", "rank": 44, "score": 113163.33352322722 }, { "content": "class GETRF_NPVT : public ::TestWithParam<getrf_tuple> {\n\nprotected:\n\n GETRF_NPVT() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n};\n\n\n\n// non-batch tests\n\nTEST_P(GETF2_NPVT, __float) {\n\n Arguments arg = getrf_setup_arguments(GetParam());\n\n\n\n if (arg.M == 0 && arg.N == 0) \n\n testing_getf2_getrf_npvt_bad_arg<false,false,0,float>();\n\n\n\n arg.batch_count = 1;\n\n testing_getf2_getrf_npvt<false,false,0,float>(arg);\n\n}\n\n\n\nTEST_P(GETF2_NPVT, __double) {\n\n Arguments arg = getrf_setup_arguments(GetParam());\n", "file_path": "rocsolver/clients/gtest/getf2_getrf_gtest.cpp", "rank": 45, "score": 113163.33352322722 }, { "content": "class host_vector;\n\n\n\n//!\n\n//! @brief pseudo-vector subclass which uses device memory\n\n//!\n\ntemplate <typename T, size_t PAD = 0, typename U = T>\n", "file_path": "rocblascommon/clients/include/device_vector.hpp", "rank": 46, "score": 111386.74760292278 }, { "content": " // task_t represents a payload of data and a promise to finish\n\n class task_t\n\n {\n\n std::string str;\n\n std::promise<void> promise;\n\n\n\n public:\n\n // The task takes ownership of the string payload and promise\n\n task_t(std::string&& str, std::promise<void>&& promise)\n\n : str(std::move(str))\n\n , promise(std::move(promise))\n\n {\n\n }\n\n\n\n // Notify the future when the worker thread exits\n\n void set_value_at_thread_exit()\n\n {\n\n promise.set_value_at_thread_exit();\n\n }\n\n\n\n // Notify the future immediately\n", "file_path": "rocblascommon/library/src/include/rocblas_ostream.hpp", "rank": 47, "score": 111386.74760292278 }, { "content": " class worker\n\n {\n", "file_path": "rocblascommon/library/src/include/rocblas_ostream.hpp", "rank": 48, "score": 111386.74760292278 }, { "content": "class rocblas_local_handle\n\n{\n\n rocblas_handle handle;\n\n\n\npublic:\n\n rocblas_local_handle()\n\n {\n\n rocblas_create_handle(&handle);\n\n }\n\n ~rocblas_local_handle()\n\n {\n\n rocblas_destroy_handle(handle);\n\n }\n\n\n\n // Allow rocblas_local_handle to be used anywhere rocblas_handle is expected\n\n operator rocblas_handle&()\n\n {\n\n return handle;\n\n }\n\n operator const rocblas_handle&() const\n", "file_path": "rocblascommon/clients/include/utility.hpp", "rank": 49, "score": 111386.74760292278 }, { "content": "class rocsolver_ostream\n\n{\n\n /**************************************************************************\n\n * The worker class sets up a worker thread for writing to log files. Two *\n\n * files are considered the same if they have the same device ID / inode. *\n\n **************************************************************************/\n", "file_path": "rocblascommon/library/src/include/rocblas_ostream.hpp", "rank": 50, "score": 109397.03567167706 }, { "content": "class rocblas_nan_rng\n\n{\n\n // Generate random NaN values\n\n template <typename T, typename UINT_T, int SIG, int EXP>\n\n static T random_nan_data()\n\n {\n\n static_assert(sizeof(UINT_T) == sizeof(T), \"Type sizes do not match\");\n\n union\n\n {\n\n UINT_T u;\n\n T fp;\n\n } x;\n\n do\n\n x.u = std::uniform_int_distribution<UINT_T>{}(rocblas_rng);\n\n while(!(x.u & (((UINT_T)1 << SIG) - 1))); // Reject Inf (mantissa == 0)\n\n x.u |= (((UINT_T)1 << EXP) - 1) << SIG; // Exponent = all 1's\n\n return x.fp; // NaN with random bits\n\n }\n\n\n\npublic:\n", "file_path": "rocblascommon/clients/include/rocblas_random.hpp", "rank": 51, "score": 109397.03567167706 }, { "content": "class device_batch_vector;\n\n\n\n//!\n\n//! @brief Implementation of the batch vector on host.\n\n//!\n\ntemplate <typename T>\n", "file_path": "rocblascommon/clients/include/host_batch_vector.hpp", "rank": 52, "score": 107495.09447992223 }, { "content": "class host_batch_vector;\n\n\n\n//!\n\n//! @brief pseudo-vector subclass which uses a batch of device memory pointers and\n\n//! - an array of pointers in host memory\n\n//! - an array of pointers in device memory\n\n//!\n\ntemplate <typename T, size_t PAD = 0, typename U = T>\n", "file_path": "rocblascommon/clients/include/device_batch_vector.hpp", "rank": 53, "score": 107495.09447992223 }, { "content": "class RocBLAS_TestName\n\n{\n\n std::ostringstream str;\n\n\n\n static auto& get_table()\n\n {\n\n // Placed inside function to avoid dependency on initialization order\n\n static std::unordered_map<std::string, size_t>* table = test_cleanup::allocate(&table);\n\n return *table;\n\n }\n\n\n\npublic:\n\n // Convert stream to normalized Google Test name\n\n // rvalue reference qualified so that it can only be called once\n\n // The name should only be generated once before the stream is destroyed\n\n operator std::string() &&\n\n {\n\n // This table is private to each instantation of RocBLAS_TestName\n\n auto& table = get_table();\n\n std::string name(str.str());\n", "file_path": "rocblascommon/clients/include/rocblas_test.hpp", "rank": 54, "score": 107495.09447992223 }, { "content": "class host_batch_vector\n\n{\n\npublic:\n\n //!\n\n //! @brief Delete copy constructor.\n\n //!\n\n host_batch_vector(const host_batch_vector<T>& that) = delete;\n\n\n\n //!\n\n //! @brief Delete copy assignement.\n\n //!\n\n host_batch_vector& operator=(const host_batch_vector<T>& that) = delete;\n\n\n\n //!\n\n //! @brief Constructor.\n\n //! @param n The length of the vector.\n\n //! @param inc The increment.\n\n //! @param batch_count The batch count.\n\n //!\n\n explicit host_batch_vector(rocblas_int n, rocblas_int inc, rocblas_int batch_count)\n", "file_path": "rocblascommon/clients/include/host_batch_vector.hpp", "rank": 55, "score": 107495.09447992223 }, { "content": "class host_strided_batch_vector;\n\n\n\n//!\n\n//! @brief Implementation of a strided batched vector on device.\n\n//!\n\ntemplate <typename T, size_t PAD = 0, typename U = T>\n", "file_path": "rocblascommon/clients/include/device_strided_batch_vector.hpp", "rank": 56, "score": 103932.27516839848 }, { "content": "class device_strided_batch_vector;\n\n\n\n//!\n\n//! @brief Implementation of a host strided batched vector.\n\n//!\n\ntemplate <typename T>\n", "file_path": "rocblascommon/clients/include/host_strided_batch_vector.hpp", "rank": 57, "score": 103932.27516839848 }, { "content": "class host_strided_batch_vector\n\n{\n\npublic:\n\n //!\n\n //! @brief The storage type to use.\n\n //!\n\n typedef enum class estorage\n\n {\n\n block,\n\n interleave\n\n } storage;\n\n\n\n //!\n\n //! @brief Disallow copying.\n\n //!\n\n host_strided_batch_vector(const host_strided_batch_vector&) = delete;\n\n\n\n //!\n\n //! @brief Disallow assigning.\n\n //!\n", "file_path": "rocblascommon/clients/include/host_strided_batch_vector.hpp", "rank": 58, "score": 103932.27516839848 }, { "content": "struct host_vector : std::vector<T>\n\n{\n\n // Inherit constructors\n\n using std::vector<T>::vector;\n\n\n\n //!\n\n //! @brief Constructor.\n\n //!\n\n host_vector(size_t n, ptrdiff_t inc)\n\n : std::vector<T>(n * std::abs(inc))\n\n , m_n(n)\n\n , m_inc(inc)\n\n {\n\n }\n\n\n\n //!\n\n //! @brief Copy constructor from host_vector of other types convertible to T\n\n //!\n\n template <typename U, std::enable_if_t<std::is_convertible<U, T>{}, int> = 0>\n\n host_vector(const host_vector<U>& x)\n", "file_path": "rocblascommon/clients/include/host_vector.hpp", "rank": 59, "score": 100990.55683470689 }, { "content": "/* ************************************************************************\n\n * Copyright 2018-2020 Advanced Micro Devices, Inc.\n\n * ************************************************************************ */\n\n\n\n#ifndef _ARGUMENTS_H_\n\n#define _ARGUMENTS_H_\n\n\n\n#include \"rocblas.h\"\n\n\n", "file_path": "rocsolver/clients/include/rocsolver_arguments.hpp", "rank": 60, "score": 92690.47141046826 }, { "content": " 128 * 128; // bsa > transA_option == 'N' ? lda * K : lda * M\n\n rocblas_int bsb =\n\n 128 * 128; // bsb > transB_option == 'N' ? ldb * N : ldb * K\n\n rocblas_int bsc = 128 * 128; // bsc >= ldc * N\n\n rocblas_int bsp = 128; // bsp >= min(M,N)\n\n\n\n rocblas_int norm_check = 0;\n\n rocblas_int unit_check = 1;\n\n rocblas_int timing = 0;\n\n rocblas_int perf = 0;\n\n\n\n rocblas_int iters = 5;\n\n\n\n Arguments &operator=(const Arguments &rhs) {\n\n M = rhs.M;\n\n N = rhs.N;\n\n K = rhs.K;\n\n S4 = rhs.S4;\n\n k1 = rhs.k1;\n\n k2 = rhs.k2;\n", "file_path": "rocsolver/clients/include/rocsolver_arguments.hpp", "rank": 61, "score": 92684.15993557581 }, { "content": " rocblas_int start = 1024;\n\n rocblas_int end = 10240;\n\n rocblas_int step = 1000;\n\n\n\n double alpha = 1.0;\n\n double beta = 0.0;\n\n\n\n char transA_option = 'N';\n\n char transB_option = 'N';\n\n char transH_option = 'N';\n\n char side_option = 'L';\n\n char uplo_option = 'L';\n\n char diag_option = 'N';\n\n char direct_option = 'F';\n\n char storev = 'C';\n\n\n\n rocblas_int apiCallCount = 1;\n\n rocblas_int batch_count = 5;\n\n\n\n rocblas_int bsa =\n", "file_path": "rocsolver/clients/include/rocsolver_arguments.hpp", "rank": 62, "score": 92679.33460747405 }, { "content": " transB_option = rhs.transB_option;\n\n transH_option = rhs.transH_option;\n\n side_option = rhs.side_option;\n\n uplo_option = rhs.uplo_option;\n\n diag_option = rhs.diag_option;\n\n direct_option = rhs.direct_option;\n\n storev = rhs.storev;\n\n\n\n apiCallCount = rhs.apiCallCount;\n\n batch_count = rhs.batch_count;\n\n\n\n bsa = rhs.bsa;\n\n bsb = rhs.bsb;\n\n bsc = rhs.bsc;\n\n bsp = rhs.bsp;\n\n \n\n norm_check = rhs.norm_check;\n\n unit_check = rhs.unit_check;\n\n timing = rhs.timing;\n\n perf = rhs.perf;\n\n\n\n iters = rhs.iters;\n\n\n\n return *this;\n\n }\n\n};\n\n\n\n#endif\n", "file_path": "rocsolver/clients/include/rocsolver_arguments.hpp", "rank": 63, "score": 92679.33460747405 }, { "content": "\n\n lda = rhs.lda;\n\n ldb = rhs.ldb;\n\n ldc = rhs.ldc;\n\n ldv = rhs.ldv;\n\n ldt = rhs.ldt;\n\n\n\n incx = rhs.incx;\n\n incy = rhs.incy;\n\n incd = rhs.incd;\n\n incb = rhs.incb;\n\n\n\n start = rhs.start;\n\n end = rhs.end;\n\n step = rhs.step;\n\n\n\n alpha = rhs.alpha;\n\n beta = rhs.beta;\n\n\n\n transA_option = rhs.transA_option;\n", "file_path": "rocsolver/clients/include/rocsolver_arguments.hpp", "rank": 64, "score": 92679.33460747405 }, { "content": "/* ************************************************************************\n\n * Copyright 2020 Advanced Micro Devices, Inc.\n\n * ************************************************************************ */\n\n\n\n#include \"norm.hpp\"\n\n#include \"rocsolver_test.hpp\"\n\n#include \"rocsolver_arguments.hpp\"\n\n#include \"rocsolver.hpp\"\n\n#include \"cblas_interface.h\"\n\n#include \"clientcommon.hpp\"\n\n\n\n\n\ntemplate <bool STRIDED, typename T, typename U>\n\nvoid getri_checkBadArgs(const rocblas_handle handle, \n\n const rocblas_int n, \n\n T dA1, \n\n T dA, \n\n const rocblas_int lda, \n\n const rocblas_stride stA,\n\n U dIpiv, \n", "file_path": "rocsolver/clients/include/testing_getri.hpp", "rank": 65, "score": 92433.44021038075 }, { "content": " \n\n start = get_time_us();\n\n rocsolver_getri(STRIDED,handle, n, dA1.data(), dA.data(), lda, stA, dIpiv.data(), stP, dInfo.data(), bc);\n\n *gpu_time_used += get_time_us() - start;\n\n }\n\n *gpu_time_used /= hot_calls;\n\n}\n\n\n\n\n\ntemplate <bool BATCHED, bool STRIDED, typename T> \n\nvoid testing_getri(Arguments argus) \n\n{\n\n // get arguments \n\n rocblas_local_handle handle;\n\n rocblas_int n = argus.N;\n\n rocblas_int lda = argus.lda;\n\n rocblas_stride stA = argus.bsa;\n\n rocblas_stride stP = argus.bsp;\n\n rocblas_int bc = argus.batch_count;\n\n rocblas_int hot_calls = argus.iters;\n", "file_path": "rocsolver/clients/include/testing_getri.hpp", "rank": 66, "score": 92428.49311994147 }, { "content": "\n\n } else {\n\n // memory allocations\n\n device_strided_batch_vector<T> dA1(1,1,1,1);\n\n device_strided_batch_vector<T> dA(1,1,1,1);\n\n device_strided_batch_vector<rocblas_int> dIpiv(1,1,1,1);\n\n device_strided_batch_vector<rocblas_int> dInfo(1,1,1,1);\n\n CHECK_HIP_ERROR(dA.memcheck());\n\n CHECK_HIP_ERROR(dIpiv.memcheck());\n\n\n\n // check bad arguments\n\n getri_checkBadArgs<STRIDED>(handle,n,dA1.data(),dA.data(),lda,stA,dIpiv.data(),stP,dInfo.data(),bc);\n\n }\n\n}\n\n\n\n\n\ntemplate <bool CPU, bool GPU, typename T, typename Td, typename Ud, typename Th, typename Uh>\n\nvoid getri_initData(const rocblas_handle handle, \n\n const rocblas_int n, \n\n Td &dA1, \n", "file_path": "rocsolver/clients/include/testing_getri.hpp", "rank": 67, "score": 92425.98434753125 }, { "content": " Uh &hInfo, \n\n double *gpu_time_used,\n\n double *cpu_time_used,\n\n const rocblas_int hot_calls,\n\n const bool perf)\n\n{\n\n rocblas_int sizeW = n;\n\n std::vector<T> hW(sizeW);\n\n\n\n if (!perf)\n\n {\n\n getri_initData<true,false,T>(handle, n, dA1, dA, lda, stA, dIpiv, stP, dInfo, bc, \n\n hA1, hA, hIpiv, hInfo);\n\n\n\n // cpu-lapack performance (only if not in perf mode)\n\n *cpu_time_used = get_time_us();\n\n for (rocblas_int b = 0; b < bc; ++b) {\n\n cblas_getri<T>(n, hA[b], lda, hIpiv[b], hW.data(), &sizeW);\n\n }\n\n *cpu_time_used = get_time_us() - *cpu_time_used;\n", "file_path": "rocsolver/clients/include/testing_getri.hpp", "rank": 68, "score": 92425.35323229826 }, { "content": " const rocblas_stride stP,\n\n U dInfo, \n\n const rocblas_int bc)\n\n{\n\n // NOTE: dA1 is only used for getri_outofplace_batched\n\n // It is ignored in bad arg checks\n\n\n\n // handle\n\n EXPECT_ROCBLAS_STATUS(rocsolver_getri(STRIDED,nullptr,n,dA1,dA,lda,stA,dIpiv,stP,dInfo,bc), \n\n rocblas_status_invalid_handle);\n\n \n\n // values\n\n // N/A\n\n\n\n // sizes (only check batch_count if applicable)\n\n if (STRIDED)\n\n EXPECT_ROCBLAS_STATUS(rocsolver_getri(STRIDED,handle,n,dA1,dA,lda,stA,dIpiv,stP,dInfo,-1), \n\n rocblas_status_invalid_size);\n\n \n\n // pointers\n", "file_path": "rocsolver/clients/include/testing_getri.hpp", "rank": 69, "score": 92424.0468209009 }, { "content": "{\n\n // safe arguments\n\n rocblas_local_handle handle;\n\n rocblas_int n = 1;\n\n rocblas_int lda = 1;\n\n rocblas_stride stA = 1;\n\n rocblas_stride stP = 1;\n\n rocblas_int bc = 1;\n\n\n\n if (BATCHED) {\n\n // memory allocations\n\n device_batch_vector<T> dA1(1,1,1);\n\n device_batch_vector<T> dA(1,1,1);\n\n device_strided_batch_vector<rocblas_int> dIpiv(1,1,1,1);\n\n device_strided_batch_vector<rocblas_int> dInfo(1,1,1,1);\n\n CHECK_HIP_ERROR(dA.memcheck());\n\n CHECK_HIP_ERROR(dIpiv.memcheck());\n\n \n\n // check bad arguments\n\n getri_checkBadArgs<STRIDED>(handle,n,dA1.data(),dA.data(),lda,stA,dIpiv.data(),stP,dInfo.data(),bc);\n", "file_path": "rocsolver/clients/include/testing_getri.hpp", "rank": 70, "score": 92422.83835451434 }, { "content": " EXPECT_ROCBLAS_STATUS(rocsolver_getri(STRIDED,handle,n,dA1,(T)nullptr,lda,stA,dIpiv,stP,dInfo,bc),\n\n rocblas_status_invalid_pointer);\n\n EXPECT_ROCBLAS_STATUS(rocsolver_getri(STRIDED,handle,n,dA1,dA,lda,stA,(U)nullptr,stP,dInfo,bc), \n\n rocblas_status_invalid_pointer);\n\n EXPECT_ROCBLAS_STATUS(rocsolver_getri(STRIDED,handle,n,dA1,dA,lda,stA,dIpiv,stP,(U)nullptr,bc), \n\n rocblas_status_invalid_pointer);\n\n\n\n // quick return with invalid pointers\n\n EXPECT_ROCBLAS_STATUS(rocsolver_getri(STRIDED,handle,0,dA1,(T)nullptr,lda,stA,(U)nullptr,stP,dInfo,bc), \n\n rocblas_status_success);\n\n \n\n // quick return with zero batch_count if applicable\n\n if (STRIDED)\n\n EXPECT_ROCBLAS_STATUS(rocsolver_getri(STRIDED,handle,n,dA1,dA,lda,stA,dIpiv,stP,(U)nullptr,0),\n\n rocblas_status_success);\n\n}\n\n\n\n\n\ntemplate <bool BATCHED, bool STRIDED, typename T>\n\nvoid testing_getri_bad_arg()\n", "file_path": "rocsolver/clients/include/testing_getri.hpp", "rank": 71, "score": 92422.70832553037 }, { "content": " ROCSOLVER_BENCH_INFORM(0);\n\n\n\n return;\n\n }\n\n\n\n // check computations\n\n if (argus.unit_check || argus.norm_check) \n\n getri_getError<STRIDED,T>(handle, n, dA1, dA, lda, stA, dIpiv, stP, dInfo, bc, \n\n hA1, hA, hARes, hIpiv, hInfo, &max_error);\n\n\n\n // collect performance data\n\n if (argus.timing) \n\n getri_getPerfData<STRIDED,T>(handle, n, dA1, dA, lda, stA, dIpiv, stP, dInfo, bc, \n\n hA1, hA, hIpiv, hInfo, &gpu_time_used, &cpu_time_used, hot_calls, argus.perf);\n\n }\n\n\n\n // validate results for rocsolver-test\n\n // using n * machine_precision as tolerance\n\n if (argus.unit_check) \n\n rocsolver_test_check<T>(max_error,n); \n", "file_path": "rocsolver/clients/include/testing_getri.hpp", "rank": 72, "score": 92421.05575211057 }, { "content": " rocblas_cout << \"Results:\\n\";\n\n rocblas_cout << \"============================================\\n\";\n\n if (argus.norm_check) {\n\n rocsolver_bench_output(\"cpu_time\", \"gpu_time\", \"error\");\n\n rocsolver_bench_output(cpu_time_used, gpu_time_used, max_error);\n\n }\n\n else {\n\n rocsolver_bench_output(\"cpu_time\", \"gpu_time\");\n\n rocsolver_bench_output(cpu_time_used, gpu_time_used);\n\n }\n\n rocblas_cout << std::endl;\n\n }\n\n else {\n\n if (argus.norm_check) rocsolver_bench_output(gpu_time_used,max_error);\n\n else rocsolver_bench_output(gpu_time_used);\n\n }\n\n }\n\n}\n", "file_path": "rocsolver/clients/include/testing_getri.hpp", "rank": 73, "score": 92421.05082447518 }, { "content": " // check quick return\n\n if (n == 0 || bc == 0) {\n\n EXPECT_ROCBLAS_STATUS(rocsolver_getri(STRIDED, handle, n, dA1.data(), dA.data(), lda, stA, dIpiv.data(), stP, dInfo.data(), bc),\n\n rocblas_status_success);\n\n if (argus.timing)\n\n ROCSOLVER_BENCH_INFORM(0);\n\n\n\n return;\n\n }\n\n\n\n // check computations\n\n if (argus.unit_check || argus.norm_check) \n\n getri_getError<STRIDED,T>(handle, n, dA1, dA, lda, stA, dIpiv, stP, dInfo, bc, \n\n hA1, hA, hARes, hIpiv, hInfo, &max_error);\n\n\n\n // collect performance data\n\n if (argus.timing) \n\n getri_getPerfData<STRIDED,T>(handle, n, dA1, dA, lda, stA, dIpiv, stP, dInfo, bc, \n\n hA1, hA, hIpiv, hInfo, &gpu_time_used, &cpu_time_used, hot_calls, argus.perf);\n\n } \n", "file_path": "rocsolver/clients/include/testing_getri.hpp", "rank": 74, "score": 92420.79802190186 }, { "content": " hA1, hA, hIpiv, hInfo);\n\n\n\n // execute computations\n\n // GPU lapack\n\n CHECK_ROCBLAS_ERROR(rocsolver_getri(STRIDED,handle, n, dA1.data(), dA.data(), lda, stA, dIpiv.data(), stP, dInfo.data(), bc));\n\n CHECK_HIP_ERROR(hARes.transfer_from(dA));\n\n\n\n // CPU lapack\n\n for (rocblas_int b = 0; b < bc; ++b) {\n\n cblas_getri<T>(n, hA[b], lda, hIpiv[b], hW.data(), &sizeW);\n\n }\n\n \n\n // expecting original matrix to be non-singular\n\n // error is ||hA - hARes|| / ||hA||\n\n // (THIS DOES NOT ACCOUNT FOR NUMERICAL REPRODUCIBILITY ISSUES. \n\n // IT MIGHT BE REVISITED IN THE FUTURE)\n\n // using frobenius norm\n\n double err;\n\n *max_err = 0;\n\n for (rocblas_int b = 0; b < bc; ++b) {\n", "file_path": "rocsolver/clients/include/testing_getri.hpp", "rank": 75, "score": 92419.5978301744 }, { "content": "\n\n // (TODO: add some singular matrices)\n\n }\n\n }\n\n \n\n // now copy data to the GPU\n\n if (GPU)\n\n {\n\n if (dA1.n() > 0)\n\n CHECK_HIP_ERROR(dA1.transfer_from(hA));\n\n else\n\n CHECK_HIP_ERROR(dA.transfer_from(hA));\n\n CHECK_HIP_ERROR(dIpiv.transfer_from(hIpiv));\n\n }\n\n}\n\n\n\n\n\ntemplate <bool STRIDED, typename T, typename Td, typename Ud, typename Th, typename Uh>\n\nvoid getri_getError(const rocblas_handle handle, \n\n const rocblas_int n, \n", "file_path": "rocsolver/clients/include/testing_getri.hpp", "rank": 76, "score": 92419.23993014888 }, { "content": "\n\n rocblas_stride stARes = (argus.unit_check || argus.norm_check) ? stA : 0;\n\n\n\n // check non-supported values \n\n // N/A\n\n\n\n // determine sizes\n\n size_t size_A = size_t(lda) * n;\n\n size_t size_P = size_t(n);\n\n double max_error = 0, gpu_time_used = 0, cpu_time_used = 0;\n\n\n\n size_t size_ARes = (argus.unit_check || argus.norm_check) ? size_A : 0;\n\n\n\n // check invalid sizes \n\n bool invalid_size = (n < 0 || lda < n || bc < 0);\n\n if (invalid_size) {\n\n if (BATCHED)\n\n EXPECT_ROCBLAS_STATUS(rocsolver_getri(STRIDED, handle, n, (T *const *)nullptr, (T *const *)nullptr, lda, stA, (rocblas_int*)nullptr, stP, (rocblas_int*)nullptr, bc),\n\n rocblas_status_invalid_size);\n\n else\n", "file_path": "rocsolver/clients/include/testing_getri.hpp", "rank": 77, "score": 92419.14346134242 }, { "content": " Td &dA1, \n\n Td &dA, \n\n const rocblas_int lda, \n\n const rocblas_stride stA, \n\n Ud &dIpiv, \n\n const rocblas_stride stP, \n\n Ud &dInfo, \n\n const rocblas_int bc,\n\n Th &hA1, \n\n Th &hA, \n\n Th &hARes, \n\n Uh &hIpiv, \n\n Uh &hInfo, \n\n double *max_err)\n\n{\n\n rocblas_int sizeW = n;\n\n std::vector<T> hW(sizeW);\n\n\n\n // input data initialization \n\n getri_initData<true,true,T>(handle, n, dA1, dA, lda, stA, dIpiv, stP, dInfo, bc, \n", "file_path": "rocsolver/clients/include/testing_getri.hpp", "rank": 78, "score": 92418.74077156401 }, { "content": " err = norm_error('F',n,n,lda,hA[b],hARes[b]);\n\n *max_err = err > *max_err ? err : *max_err;\n\n }\n\n}\n\n\n\n\n\ntemplate <bool STRIDED, typename T, typename Td, typename Ud, typename Th, typename Uh>\n\nvoid getri_getPerfData(const rocblas_handle handle, \n\n const rocblas_int n, \n\n Td &dA1, \n\n Td &dA, \n\n const rocblas_int lda, \n\n const rocblas_stride stA, \n\n Ud &dIpiv, \n\n const rocblas_stride stP, \n\n Ud &dInfo, \n\n const rocblas_int bc,\n\n Th &hA1, \n\n Th &hA, \n\n Uh &hIpiv, \n", "file_path": "rocsolver/clients/include/testing_getri.hpp", "rank": 79, "score": 92418.59967569985 }, { "content": " getri_getPerfData<STRIDED,T>(handle, n, dA1, dA, lda, stA, dIpiv, stP, dInfo, bc, \n\n hA1, hA, hIpiv, hInfo, &gpu_time_used, &cpu_time_used, hot_calls, argus.perf);\n\n } \n\n \n\n else if (BATCHED) {\n\n // memory allocations\n\n host_batch_vector<T> hA1(size_A,1,bc);\n\n host_batch_vector<T> hA(size_A,1,bc);\n\n host_batch_vector<T> hARes(size_ARes,1,bc);\n\n host_strided_batch_vector<rocblas_int> hIpiv(size_P,1,stP,bc);\n\n host_strided_batch_vector<rocblas_int> hInfo(1,1,1,bc);\n\n device_batch_vector<T> dA1(size_A,1,bc);\n\n device_batch_vector<T> dA(size_A,1,bc);\n\n device_strided_batch_vector<rocblas_int> dIpiv(size_P,1,stP,bc);\n\n device_strided_batch_vector<rocblas_int> dInfo(1,1,1,bc);\n\n if (size_A) CHECK_HIP_ERROR(dA1.memcheck());\n\n if (size_A) CHECK_HIP_ERROR(dA.memcheck());\n\n if (size_P) CHECK_HIP_ERROR(dIpiv.memcheck());\n\n CHECK_HIP_ERROR(dInfo.memcheck());\n\n\n", "file_path": "rocsolver/clients/include/testing_getri.hpp", "rank": 80, "score": 92417.92679826447 }, { "content": " }\n\n\n\n getri_initData<true,false,T>(handle, n, dA1, dA, lda, stA, dIpiv, stP, dInfo, bc, \n\n hA1, hA, hIpiv, hInfo);\n\n\n\n // cold calls\n\n for(int iter = 0; iter < 2; iter++)\n\n {\n\n getri_initData<false,true,T>(handle, n, dA1, dA, lda, stA, dIpiv, stP, dInfo, bc, \n\n hA1, hA, hIpiv, hInfo);\n\n\n\n CHECK_ROCBLAS_ERROR(rocsolver_getri(STRIDED,handle, n, dA1.data(), dA.data(), lda, stA, dIpiv.data(), stP, dInfo.data(), bc));\n\n }\n\n \n\n // gpu-lapack performance\n\n double start;\n\n for(rocblas_int iter = 0; iter < hot_calls; iter++)\n\n {\n\n getri_initData<false,true,T>(handle, n, dA1, dA, lda, stA, dIpiv, stP, dInfo, bc, \n\n hA1, hA, hIpiv, hInfo);\n", "file_path": "rocsolver/clients/include/testing_getri.hpp", "rank": 81, "score": 92416.65389167433 }, { "content": " if (size_A) CHECK_HIP_ERROR(dA.memcheck());\n\n if (size_P) CHECK_HIP_ERROR(dIpiv.memcheck());\n\n\n\n // check quick return\n\n if (n == 0 || bc == 0) {\n\n EXPECT_ROCBLAS_STATUS(rocsolver_getri(STRIDED, handle, n, dA1.data(), dA.data(), lda, stA, dIpiv.data(), stP, dInfo.data(), bc),\n\n rocblas_status_success);\n\n if (argus.timing)\n\n ROCSOLVER_BENCH_INFORM(0);\n\n\n\n return;\n\n }\n\n\n\n // check computations\n\n if (argus.unit_check || argus.norm_check) \n\n getri_getError<STRIDED,T>(handle, n, dA1, dA, lda, stA, dIpiv, stP, dInfo, bc, \n\n hA1, hA, hARes, hIpiv, hInfo, &max_error);\n\n\n\n // collect performance data\n\n if (argus.timing) \n", "file_path": "rocsolver/clients/include/testing_getri.hpp", "rank": 82, "score": 92415.8263243709 }, { "content": "\n\n // output results for rocsolver-bench\n\n if (argus.timing) {\n\n if (!argus.perf) {\n\n rocblas_cout << \"\\n============================================\\n\";\n\n rocblas_cout << \"Arguments:\\n\";\n\n rocblas_cout << \"============================================\\n\";\n\n if (BATCHED) {\n\n rocsolver_bench_output(\"n\", \"lda\", \"strideP\", \"batch_c\");\n\n rocsolver_bench_output(n, lda, stP, bc);\n\n }\n\n else if (STRIDED) {\n\n rocsolver_bench_output(\"n\", \"lda\", \"strideA\", \"strideP\", \"batch_c\");\n\n rocsolver_bench_output(n, lda, stA, stP, bc);\n\n }\n\n else {\n\n rocsolver_bench_output(\"n\", \"lda\");\n\n rocsolver_bench_output(n, lda);\n\n }\n\n rocblas_cout << \"\\n============================================\\n\";\n", "file_path": "rocsolver/clients/include/testing_getri.hpp", "rank": 83, "score": 92414.8370240817 }, { "content": " EXPECT_ROCBLAS_STATUS(rocsolver_getri(STRIDED, handle, n, (T *)nullptr, (T *)nullptr, lda, stA, (rocblas_int*)nullptr, stP, (rocblas_int*)nullptr, bc),\n\n rocblas_status_invalid_size);\n\n\n\n if (argus.timing) \n\n ROCSOLVER_BENCH_INFORM(1);\n\n\n\n return;\n\n }\n\n\n\n if (BATCHED && STRIDED) {\n\n // memory allocations\n\n host_batch_vector<T> hA1(0,1,bc);\n\n host_batch_vector<T> hA(size_A,1,bc);\n\n host_batch_vector<T> hARes(size_ARes,1,bc);\n\n host_strided_batch_vector<rocblas_int> hIpiv(size_P,1,stP,bc);\n\n host_strided_batch_vector<rocblas_int> hInfo(1,1,1,bc);\n\n device_batch_vector<T> dA1(0,1,bc);\n\n device_batch_vector<T> dA(size_A,1,bc);\n\n device_strided_batch_vector<rocblas_int> dIpiv(size_P,1,stP,bc);\n\n device_strided_batch_vector<rocblas_int> dInfo(1,1,1,bc);\n", "file_path": "rocsolver/clients/include/testing_getri.hpp", "rank": 84, "score": 92414.09517101658 }, { "content": "\n\n else {\n\n // memory allocations\n\n host_strided_batch_vector<T> hA1(0,1,0,bc);\n\n host_strided_batch_vector<T> hA(size_A,1,stA,bc);\n\n host_strided_batch_vector<T> hARes(size_ARes,1,stARes,bc);\n\n host_strided_batch_vector<rocblas_int> hIpiv(size_P,1,stP,bc);\n\n host_strided_batch_vector<rocblas_int> hInfo(1,1,1,bc);\n\n device_strided_batch_vector<T> dA1(0,1,0,bc);\n\n device_strided_batch_vector<T> dA(size_A,1,stA,bc);\n\n device_strided_batch_vector<rocblas_int> dIpiv(size_P,1,stP,bc);\n\n device_strided_batch_vector<rocblas_int> dInfo(1,1,1,bc);\n\n if (size_A) CHECK_HIP_ERROR(dA.memcheck());\n\n if (size_P) CHECK_HIP_ERROR(dIpiv.memcheck());\n\n\n\n // check quick return\n\n if (n == 0 || bc == 0) {\n\n EXPECT_ROCBLAS_STATUS(rocsolver_getri(STRIDED, handle, n, dA1.data(), dA.data(), lda, stA, dIpiv.data(), stP, dInfo.data(), bc),\n\n rocblas_status_success);\n\n if (argus.timing)\n", "file_path": "rocsolver/clients/include/testing_getri.hpp", "rank": 85, "score": 92413.90899010364 }, { "content": "class device_vector : private d_vector<T, PAD, U>\n\n{\n\n\n\npublic:\n\n //!\n\n //! @brief Disallow copying.\n\n //!\n\n device_vector(const device_vector&) = delete;\n\n\n\n //!\n\n //! @brief Disallow assigning\n\n //!\n\n device_vector& operator=(const device_vector&) = delete;\n\n\n\n //!\n\n //! @brief Constructor.\n\n //! @param n The length of the vector.\n\n //! @param inc The increment.\n\n //! @remark Must wrap constructor and destructor in functions to allow Google Test macros to work\n\n //!\n", "file_path": "rocblascommon/clients/include/device_vector.hpp", "rank": 86, "score": 92412.34927758426 }, { "content": " Td &dA, \n\n const rocblas_int lda, \n\n const rocblas_stride stA, \n\n Ud &dIpiv, \n\n const rocblas_stride stP, \n\n Ud &dInfo, \n\n const rocblas_int bc,\n\n Th &hA1, \n\n Th &hA, \n\n Uh &hIpiv, \n\n Uh &hInfo)\n\n{\n\n if (CPU)\n\n {\n\n T tmp;\n\n rocblas_init<T>(hA, true);\n\n\n\n for (rocblas_int b = 0; b < bc; ++b) {\n\n // scale A to avoid singularities \n\n for (rocblas_int i = 0; i < n; i++) {\n", "file_path": "rocsolver/clients/include/testing_getri.hpp", "rank": 87, "score": 92410.93561982183 }, { "content": " for (rocblas_int j = 0; j < n; j++) {\n\n if (i == j)\n\n hA[b][i + j * lda] += 400;\n\n else \n\n hA[b][i + j * lda] -= 4;\n\n }\n\n }\n\n\n\n // shuffle rows to test pivoting\n\n // always the same permuation for debugging purposes\n\n for (rocblas_int i = 0; i < n/2; i++) {\n\n for (rocblas_int j = 0; j < n; j++) {\n\n tmp = hA[b][i+j*lda];\n\n hA[b][i+j*lda] = hA[b][n-1-i+j*lda];\n\n hA[b][n-1-i+j*lda] = tmp;\n\n }\n\n }\n\n\n\n // do the LU decomposition of matrix A w/ the reference LAPACK routine\n\n cblas_getrf<T>(n, n, hA[b], lda, hIpiv[b], hInfo[b]);\n", "file_path": "rocsolver/clients/include/testing_getri.hpp", "rank": 88, "score": 92410.93561982183 }, { "content": "class device_batch_vector : private d_vector<T, PAD, U>\n\n{\n\npublic:\n\n //!\n\n //! @brief Disallow copying.\n\n //!\n\n device_batch_vector(const device_batch_vector&) = delete;\n\n\n\n //!\n\n //! @brief Disallow assigning.\n\n //!\n\n device_batch_vector& operator=(const device_batch_vector&) = delete;\n\n\n\n //!\n\n //! @brief Constructor.\n\n //! @param n The length of the vector.\n\n //! @param inc The increment.\n\n //! @param batch_count The batch count.\n\n //!\n\n explicit device_batch_vector(rocblas_int n, rocblas_int inc, rocblas_int batch_count)\n", "file_path": "rocblascommon/clients/include/device_batch_vector.hpp", "rank": 89, "score": 89269.79787258588 }, { "content": "struct host_pinned_vector : std::vector<T, pinned_memory_allocator<T>>\n\n{\n\n // Inherit constructors\n\n using std::vector<T, pinned_memory_allocator<T>>::vector;\n\n\n\n //!\n\n //! @brief Constructor.\n\n //!\n\n\n\n host_pinned_vector(rocblas_int n, rocblas_int inc)\n\n : std::vector<T, pinned_memory_allocator<T>>(size_t(n) * inc, pinned_memory_allocator<T>())\n\n , m_n(n)\n\n , m_inc(inc)\n\n {\n\n }\n\n\n\n //!\n\n //! @brief Decay into pointer wherever pointer is expected\n\n //!\n\n operator T*()\n", "file_path": "rocblascommon/clients/include/host_pinned_vector.hpp", "rank": 90, "score": 88399.13489917434 } ]
C++
Servers/ServerManager/vtkSMNewWidgetRepresentationProxy.cxx
utkarshayachit/ParaView
7bbb2aa16fdef9cfbcf4a3786cad905d6770771b
#include "vtkSMNewWidgetRepresentationProxy.h" #include "vtkAbstractWidget.h" #include "vtkClientServerInterpreter.h" #include "vtkCommand.h" #include "vtkObjectFactory.h" #include "vtkProcessModule.h" #include "vtkPVGenericRenderWindowInteractor.h" #include "vtkSmartPointer.h" #include "vtkSMDoubleVectorProperty.h" #include "vtkSMIntVectorProperty.h" #include "vtkSMPropertyIterator.h" #include "vtkSMPropertyLink.h" #include "vtkSMProxyProperty.h" #include "vtkSMRenderViewProxy.h" #include "vtkSMViewProxy.h" #include "vtkWeakPointer.h" #include "vtkWidgetRepresentation.h" #include <vtkstd/list> vtkStandardNewMacro(vtkSMNewWidgetRepresentationProxy); class vtkSMNewWidgetRepresentationObserver : public vtkCommand { public: static vtkSMNewWidgetRepresentationObserver *New() { return new vtkSMNewWidgetRepresentationObserver; } virtual void Execute(vtkObject*, unsigned long event, void*) { if (this->Proxy) { this->Proxy->ExecuteEvent(event); } } vtkSMNewWidgetRepresentationObserver():Proxy(0) {} vtkSMNewWidgetRepresentationProxy* Proxy; }; struct vtkSMNewWidgetRepresentationInternals { typedef vtkstd::list<vtkSmartPointer<vtkSMLink> > LinksType; LinksType Links; vtkWeakPointer<vtkSMRenderViewProxy> ViewProxy; }; vtkSMNewWidgetRepresentationProxy::vtkSMNewWidgetRepresentationProxy() { this->RepresentationProxy = 0; this->WidgetProxy = 0; this->Widget = 0; this->Enabled = 0; this->Observer = vtkSMNewWidgetRepresentationObserver::New(); this->Observer->Proxy = this; this->Internal = new vtkSMNewWidgetRepresentationInternals; } vtkSMNewWidgetRepresentationProxy::~vtkSMNewWidgetRepresentationProxy() { this->RepresentationProxy = 0; this->WidgetProxy = 0; this->Widget = 0; this->Observer->Proxy = 0; this->Observer->Delete(); if (this->Internal) { delete this->Internal; } } bool vtkSMNewWidgetRepresentationProxy::AddToView(vtkSMViewProxy* view) { vtkSMRenderViewProxy* renderView = vtkSMRenderViewProxy::SafeDownCast(view); if (!renderView) { vtkErrorMacro("View must be a vtkSMRenderViewProxy."); return false; } vtkAbstractWidget* widget = this->Widget; if (widget) { widget->SetInteractor(renderView->GetInteractor()); } if (this->RepresentationProxy) { vtkSMProxyProperty* rendererProp = vtkSMProxyProperty::SafeDownCast( this->RepresentationProxy->GetProperty("Renderer")); if (rendererProp) { rendererProp->RemoveAllProxies(); rendererProp->AddProxy(renderView->GetRendererProxy()); this->RepresentationProxy->UpdateProperty("Renderer"); } if(this->GetSubProxy("Prop")) { renderView->AddPropToRenderer(this->RepresentationProxy); if (widget) { widget->SetCurrentRenderer(renderView->GetRenderer()); } } else if(this->GetSubProxy("Prop2D")) { renderView->AddPropToRenderer2D(this->RepresentationProxy); if (widget) { widget->SetCurrentRenderer(renderView->GetRenderer2D()); } } } this->Internal->ViewProxy = renderView; this->UpdateEnabled(); return true; } bool vtkSMNewWidgetRepresentationProxy::RemoveFromView(vtkSMViewProxy* view) { vtkSMRenderViewProxy* renderView = vtkSMRenderViewProxy::SafeDownCast(view); if (!renderView) { vtkErrorMacro("View must be a vtkSMRenderViewProxy."); return false; } if (this->Widget) { this->Widget->SetEnabled(0); this->Widget->SetCurrentRenderer(0); this->Widget->SetInteractor(0); } if (this->RepresentationProxy) { vtkSMProxyProperty* rendererProp = vtkSMProxyProperty::SafeDownCast( this->RepresentationProxy->GetProperty("Renderer")); if (rendererProp) { rendererProp->RemoveAllProxies(); rendererProp->AddProxy(0); this->RepresentationProxy->UpdateProperty("Renderer"); } if(this->GetSubProxy("Prop")) { renderView->RemovePropFromRenderer(this->RepresentationProxy); } else if(this->GetSubProxy("Prop2D")) { renderView->RemovePropFromRenderer2D(this->RepresentationProxy); } } this->Internal->ViewProxy = 0; return this->Superclass::RemoveFromView(view); } void vtkSMNewWidgetRepresentationProxy::SetEnabled(int enable) { if (this->Enabled != enable) { this->Enabled = enable; this->UpdateEnabled(); } } void vtkSMNewWidgetRepresentationProxy::UpdateEnabled() { if (this->Internal->ViewProxy && this->Widget) { if (this->Enabled) { if (this->GetSubProxy("Prop")) { this->Widget->SetCurrentRenderer(this->Internal->ViewProxy->GetRenderer()); } else if (this->GetSubProxy("Prop2D")) { this->Widget->SetCurrentRenderer(this->Internal->ViewProxy->GetRenderer2D()); } } this->Widget->SetEnabled(this->Enabled); } } void vtkSMNewWidgetRepresentationProxy::CreateVTKObjects() { if (this->ObjectsCreated) { return; } this->RepresentationProxy = this->GetSubProxy("Prop"); if (!this->RepresentationProxy) { this->RepresentationProxy = this->GetSubProxy("Prop2D"); } if (!this->RepresentationProxy) { vtkErrorMacro( "A representation proxy must be defined as a Prop (or Prop2D) sub-proxy"); return; } this->RepresentationProxy->SetServers( vtkProcessModule::RENDER_SERVER | vtkProcessModule::CLIENT); this->WidgetProxy = this->GetSubProxy("Widget"); if (this->WidgetProxy) { this->WidgetProxy->SetServers(vtkProcessModule::CLIENT); } this->Superclass::CreateVTKObjects(); if (!this->WidgetProxy) { return; } vtkSMProxyProperty* pp = vtkSMProxyProperty::SafeDownCast( this->WidgetProxy->GetProperty("Representation")); if (pp) { pp->AddProxy(this->RepresentationProxy); } this->WidgetProxy->UpdateVTKObjects(); vtkProcessModule* pm = vtkProcessModule::GetProcessModule(); this->Widget = vtkAbstractWidget::SafeDownCast( pm->GetObjectFromID(this->WidgetProxy->GetID())); if (this->Widget) { this->Widget->AddObserver( vtkCommand::StartInteractionEvent, this->Observer); this->Widget->AddObserver( vtkCommand::EndInteractionEvent, this->Observer); this->Widget->AddObserver( vtkCommand::InteractionEvent, this->Observer); } this->UpdatePropertyInformation(); vtkSMPropertyIterator* piter = this->NewPropertyIterator(); for(piter->Begin(); !piter->IsAtEnd(); piter->Next()) { vtkSMProperty* prop = piter->GetProperty(); vtkSMProperty* info = prop->GetInformationProperty(); if (info) { info->Copy(prop); vtkSMPropertyLink* link = vtkSMPropertyLink::New(); link->AddLinkedProperty(this, piter->GetKey(), vtkSMLink::OUTPUT); link->AddLinkedProperty(this, this->GetPropertyName(info), vtkSMLink::INPUT); this->Internal->Links.push_back(link); link->Delete(); } } piter->Delete(); } void vtkSMNewWidgetRepresentationProxy::ExecuteEvent(unsigned long event) { this->InvokeEvent(event); if (event == vtkCommand::StartInteractionEvent) { vtkPVGenericRenderWindowInteractor* inter = vtkPVGenericRenderWindowInteractor::SafeDownCast( this->Widget->GetInteractor()); if (inter) { inter->InteractiveRenderEnabledOn(); } vtkSMProperty* startInt = this->RepresentationProxy->GetProperty("OnStartInteraction"); if (startInt) { startInt->Modified(); this->RepresentationProxy->UpdateProperty("OnStartInteraction"); } } else if (event == vtkCommand::InteractionEvent) { this->RepresentationProxy->UpdatePropertyInformation(); this->UpdateVTKObjects(); vtkSMProperty* interaction = this->RepresentationProxy->GetProperty("OnInteraction"); if (interaction) { interaction->Modified(); this->RepresentationProxy->UpdateProperty("OnInteraction"); } } else if (event == vtkCommand::EndInteractionEvent) { vtkPVGenericRenderWindowInteractor* inter = vtkPVGenericRenderWindowInteractor::SafeDownCast( this->Widget->GetInteractor()); if (inter) { inter->InteractiveRenderEnabledOff(); } vtkSMProperty* sizeHandles = this->RepresentationProxy->GetProperty("SizeHandles"); if (sizeHandles) { sizeHandles->Modified(); this->RepresentationProxy->UpdateProperty("SizeHandles"); } vtkSMProperty* endInt = this->RepresentationProxy->GetProperty("OnEndInteraction"); if (endInt) { endInt->Modified(); this->RepresentationProxy->UpdateProperty("OnEndInteraction"); } } } void vtkSMNewWidgetRepresentationProxy::UnRegister(vtkObjectBase* obj) { if ( this->GetSelfIDInternal().ID != 0 ) { vtkProcessModule* pm = vtkProcessModule::GetProcessModule(); if ( pm && obj != pm->GetInterpreter() && this->Internal ) { int size = this->Internal->Links.size(); if (size > 0 && this->ReferenceCount == 2 + 2*size) { vtkSMNewWidgetRepresentationInternals* aInternal = this->Internal; this->Internal = 0; delete aInternal; aInternal = 0; } } } this->Superclass::UnRegister(obj); } bool vtkSMNewWidgetRepresentationProxy::GetBounds(double bds[6]) { if (this->RepresentationProxy) { vtkProcessModule* pm = vtkProcessModule::GetProcessModule(); vtkWidgetRepresentation* repr = vtkWidgetRepresentation::SafeDownCast( pm->GetObjectFromID(this->RepresentationProxy->GetID())); if (repr) { double *propBds = repr->GetBounds(); if (propBds) { memcpy(bds, propBds, 6*sizeof(double)); return true; } } } return false; } void vtkSMNewWidgetRepresentationProxy::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); }
#include "vtkSMNewWidgetRepresentationProxy.h" #include "vtkAbstractWidget.h" #include "vtkClientServerInterpreter.h" #include "vtkCommand.h" #include "vtkObjectFactory.h" #include "vtkProcessModule.h" #include "vtkPVGenericRenderWindowInteractor.h" #include "vtkSmartPointer.h" #include "vtkSMDoubleVectorProperty.h" #include "vtkSMIntVectorProperty.h" #include "vtkSMPropertyIterator.h" #include "vtkSMPropertyLink.h" #include "vtkSMProxyProperty.h" #include "vtkSMRenderViewProxy.h" #include "vtkSMViewProxy.
Prop2D"); } if (!this->RepresentationProxy) { vtkErrorMacro( "A representation proxy must be defined as a Prop (or Prop2D) sub-proxy"); return; } this->RepresentationProxy->SetServers( vtkProcessModule::RENDER_SERVER | vtkProcessModule::CLIENT); this->WidgetProxy = this->GetSubProxy("Widget"); if (this->WidgetProxy) { this->WidgetProxy->SetServers(vtkProcessModule::CLIENT); } this->Superclass::CreateVTKObjects(); if (!this->WidgetProxy) { return; } vtkSMProxyProperty* pp = vtkSMProxyProperty::SafeDownCast( this->WidgetProxy->GetProperty("Representation")); if (pp) { pp->AddProxy(this->RepresentationProxy); } this->WidgetProxy->UpdateVTKObjects(); vtkProcessModule* pm = vtkProcessModule::GetProcessModule(); this->Widget = vtkAbstractWidget::SafeDownCast( pm->GetObjectFromID(this->WidgetProxy->GetID())); if (this->Widget) { this->Widget->AddObserver( vtkCommand::StartInteractionEvent, this->Observer); this->Widget->AddObserver( vtkCommand::EndInteractionEvent, this->Observer); this->Widget->AddObserver( vtkCommand::InteractionEvent, this->Observer); } this->UpdatePropertyInformation(); vtkSMPropertyIterator* piter = this->NewPropertyIterator(); for(piter->Begin(); !piter->IsAtEnd(); piter->Next()) { vtkSMProperty* prop = piter->GetProperty(); vtkSMProperty* info = prop->GetInformationProperty(); if (info) { info->Copy(prop); vtkSMPropertyLink* link = vtkSMPropertyLink::New(); link->AddLinkedProperty(this, piter->GetKey(), vtkSMLink::OUTPUT); link->AddLinkedProperty(this, this->GetPropertyName(info), vtkSMLink::INPUT); this->Internal->Links.push_back(link); link->Delete(); } } piter->Delete(); } void vtkSMNewWidgetRepresentationProxy::ExecuteEvent(unsigned long event) { this->InvokeEvent(event); if (event == vtkCommand::StartInteractionEvent) { vtkPVGenericRenderWindowInteractor* inter = vtkPVGenericRenderWindowInteractor::SafeDownCast( this->Widget->GetInteractor()); if (inter) { inter->InteractiveRenderEnabledOn(); } vtkSMProperty* startInt = this->RepresentationProxy->GetProperty("OnStartInteraction"); if (startInt) { startInt->Modified(); this->RepresentationProxy->UpdateProperty("OnStartInteraction"); } } else if (event == vtkCommand::InteractionEvent) { this->RepresentationProxy->UpdatePropertyInformation(); this->UpdateVTKObjects(); vtkSMProperty* interaction = this->RepresentationProxy->GetProperty("OnInteraction"); if (interaction) { interaction->Modified(); this->RepresentationProxy->UpdateProperty("OnInteraction"); } } else if (event == vtkCommand::EndInteractionEvent) { vtkPVGenericRenderWindowInteractor* inter = vtkPVGenericRenderWindowInteractor::SafeDownCast( this->Widget->GetInteractor()); if (inter) { inter->InteractiveRenderEnabledOff(); } vtkSMProperty* sizeHandles = this->RepresentationProxy->GetProperty("SizeHandles"); if (sizeHandles) { sizeHandles->Modified(); this->RepresentationProxy->UpdateProperty("SizeHandles"); } vtkSMProperty* endInt = this->RepresentationProxy->GetProperty("OnEndInteraction"); if (endInt) { endInt->Modified(); this->RepresentationProxy->UpdateProperty("OnEndInteraction"); } } } void vtkSMNewWidgetRepresentationProxy::UnRegister(vtkObjectBase* obj) { if ( this->GetSelfIDInternal().ID != 0 ) { vtkProcessModule* pm = vtkProcessModule::GetProcessModule(); if ( pm && obj != pm->GetInterpreter() && this->Internal ) { int size = this->Internal->Links.size(); if (size > 0 && this->ReferenceCount == 2 + 2*size) { vtkSMNewWidgetRepresentationInternals* aInternal = this->Internal; this->Internal = 0; delete aInternal; aInternal = 0; } } } this->Superclass::UnRegister(obj); } bool vtkSMNewWidgetRepresentationProxy::GetBounds(double bds[6]) { if (this->RepresentationProxy) { vtkProcessModule* pm = vtkProcessModule::GetProcessModule(); vtkWidgetRepresentation* repr = vtkWidgetRepresentation::SafeDownCast( pm->GetObjectFromID(this->RepresentationProxy->GetID())); if (repr) { double *propBds = repr->GetBounds(); if (propBds) { memcpy(bds, propBds, 6*sizeof(double)); return true; } } } return false; } void vtkSMNewWidgetRepresentationProxy::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); }
h" #include "vtkWeakPointer.h" #include "vtkWidgetRepresentation.h" #include <vtkstd/list> vtkStandardNewMacro(vtkSMNewWidgetRepresentationProxy); class vtkSMNewWidgetRepresentationObserver : public vtkCommand { public: static vtkSMNewWidgetRepresentationObserver *New() { return new vtkSMNewWidgetRepresentationObserver; } virtual void Execute(vtkObject*, unsigned long event, void*) { if (this->Proxy) { this->Proxy->ExecuteEvent(event); } } vtkSMNewWidgetRepresentationObserver():Proxy(0) {} vtkSMNewWidgetRepresentationProxy* Proxy; }; struct vtkSMNewWidgetRepresentationInternals { typedef vtkstd::list<vtkSmartPointer<vtkSMLink> > LinksType; LinksType Links; vtkWeakPointer<vtkSMRenderViewProxy> ViewProxy; }; vtkSMNewWidgetRepresentationProxy::vtkSMNewWidgetRepresentationProxy() { this->RepresentationProxy = 0; this->WidgetProxy = 0; this->Widget = 0; this->Enabled = 0; this->Observer = vtkSMNewWidgetRepresentationObserver::New(); this->Observer->Proxy = this; this->Internal = new vtkSMNewWidgetRepresentationInternals; } vtkSMNewWidgetRepresentationProxy::~vtkSMNewWidgetRepresentationProxy() { this->RepresentationProxy = 0; this->WidgetProxy = 0; this->Widget = 0; this->Observer->Proxy = 0; this->Observer->Delete(); if (this->Internal) { delete this->Internal; } } bool vtkSMNewWidgetRepresentationProxy::AddToView(vtkSMViewProxy* view) { vtkSMRenderViewProxy* renderView = vtkSMRenderViewProxy::SafeDownCast(view); if (!renderView) { vtkErrorMacro("View must be a vtkSMRenderViewProxy."); return false; } vtkAbstractWidget* widget = this->Widget; if (widget) { widget->SetInteractor(renderView->GetInteractor()); } if (this->RepresentationProxy) { vtkSMProxyProperty* rendererProp = vtkSMProxyProperty::SafeDownCast( this->RepresentationProxy->GetProperty("Renderer")); if (rendererProp) { rendererProp->RemoveAllProxies(); rendererProp->AddProxy(renderView->GetRendererProxy()); this->RepresentationProxy->UpdateProperty("Renderer"); } if(this->GetSubProxy("Prop")) { renderView->AddPropToRenderer(this->RepresentationProxy); if (widget) { widget->SetCurrentRenderer(renderView->GetRenderer()); } } else if(this->GetSubProxy("Prop2D")) { renderView->AddPropToRenderer2D(this->RepresentationProxy); if (widget) { widget->SetCurrentRenderer(renderView->GetRenderer2D()); } } } this->Internal->ViewProxy = renderView; this->UpdateEnabled(); return true; } bool vtkSMNewWidgetRepresentationProxy::RemoveFromView(vtkSMViewProxy* view) { vtkSMRenderViewProxy* renderView = vtkSMRenderViewProxy::SafeDownCast(view); if (!renderView) { vtkErrorMacro("View must be a vtkSMRenderViewProxy."); return false; } if (this->Widget) { this->Widget->SetEnabled(0); this->Widget->SetCurrentRenderer(0); this->Widget->SetInteractor(0); } if (this->RepresentationProxy) { vtkSMProxyProperty* rendererProp = vtkSMProxyProperty::SafeDownCast( this->RepresentationProxy->GetProperty("Renderer")); if (rendererProp) { rendererProp->RemoveAllProxies(); rendererProp->AddProxy(0); this->RepresentationProxy->UpdateProperty("Renderer"); } if(this->GetSubProxy("Prop")) { renderView->RemovePropFromRenderer(this->RepresentationProxy); } else if(this->GetSubProxy("Prop2D")) { renderView->RemovePropFromRenderer2D(this->RepresentationProxy); } } this->Internal->ViewProxy = 0; return this->Superclass::RemoveFromView(view); } void vtkSMNewWidgetRepresentationProxy::SetEnabled(int enable) { if (this->Enabled != enable) { this->Enabled = enable; this->UpdateEnabled(); } } void vtkSMNewWidgetRepresentationProxy::UpdateEnabled() { if (this->Internal->ViewProxy && this->Widget) { if (this->Enabled) { if (this->GetSubProxy("Prop")) { this->Widget->SetCurrentRenderer(this->Internal->ViewProxy->GetRenderer()); } else if (this->GetSubProxy("Prop2D")) { this->Widget->SetCurrentRenderer(this->Internal->ViewProxy->GetRenderer2D()); } } this->Widget->SetEnabled(this->Enabled); } } void vtkSMNewWidgetRepresentationProxy::CreateVTKObjects() { if (this->ObjectsCreated) { return; } this->RepresentationProxy = this->GetSubProxy("Prop"); if (!this->RepresentationProxy) { this->RepresentationProxy = this->GetSubProxy("
random
[ { "content": "def get_include():\n\n \"\"\"\n\n Return the directory in the package that contains header files.\n\n\n\n Extension modules that need to compile against mpi4py should use\n\n this function to locate the appropriate include directory. Using\n\n Python distutils (or perhaps NumPy distutils)::\n\n\n\n import mpi4py\n\n Extension('extension_name', ...\n\n include_dirs=[..., mpi4py.get_include()])\n\n\n\n \"\"\"\n\n from os.path import dirname, join\n", "file_path": "Utilities/mpi4py/mpi4py/__init__.py", "rank": 0, "score": 56644.962471702165 }, { "content": " PyObject *(*ob_func)(PyObject *, PyObject *);\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI.h", "rank": 1, "score": 56637.680015656064 }, { "content": "static MPI_Errhandler *(*PyMPIErrhandler_Get)(PyObject *);\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI_api.h", "rank": 2, "score": 55571.41358783683 }, { "content": " int flags;\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI.h", "rank": 3, "score": 55571.41358783683 }, { "content": "static int import_mpi4py(void) {\n\n if (import_mpi4py__MPI() < 0) goto bad;\n\n return 0;\n\n bad:\n\n return -1;\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py.h", "rank": 4, "score": 55571.41358783683 }, { "content": " PyObject_HEAD\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI.h", "rank": 5, "score": 54544.55257906318 }, { "content": " PyObject_HEAD\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI.h", "rank": 6, "score": 54544.55257906318 }, { "content": " PyObject_HEAD\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI.h", "rank": 7, "score": 54544.55257906318 }, { "content": " PyObject_HEAD\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI.h", "rank": 8, "score": 54544.55257906318 }, { "content": " PyObject_HEAD\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI.h", "rank": 9, "score": 54544.55257906318 }, { "content": " PyObject_HEAD\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI.h", "rank": 10, "score": 54544.55257906318 }, { "content": "PyMODINIT_FUNC initMPI(void);\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI.h", "rank": 11, "score": 54544.55257906318 }, { "content": " PyObject_HEAD\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI.h", "rank": 12, "score": 54544.55257906318 }, { "content": " PyMPICommObject __pyx_base;\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI.h", "rank": 13, "score": 54544.55257906318 }, { "content": " PyObject_HEAD\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI.h", "rank": 14, "score": 54544.55257906318 }, { "content": " MPI_Request ob_grequest;\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI.h", "rank": 15, "score": 54544.55257906318 }, { "content": " PyObject *ob_callable;\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI.h", "rank": 16, "score": 54544.55257906318 }, { "content": " PyObject_HEAD\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI.h", "rank": 17, "score": 54544.55257906318 }, { "content": " int ob_commute;\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI.h", "rank": 18, "score": 54544.55257906318 }, { "content": " PyObject_HEAD\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI.h", "rank": 19, "score": 54544.55257906318 }, { "content": "static int import_mpi4py__MPI(void) {\n\n PyObject *module = 0;\n\n module = __Pyx_ImportModule(\"mpi4py.MPI\");\n\n if (!module) goto bad;\n\n if (__Pyx_ImportFunction(module, \"PyMPIDatatype_New\", (void (**)(void))&PyMPIDatatype_New, \"PyObject *(MPI_Datatype)\") < 0) goto bad;\n\n if (__Pyx_ImportFunction(module, \"PyMPIDatatype_Get\", (void (**)(void))&PyMPIDatatype_Get, \"MPI_Datatype *(PyObject *)\") < 0) goto bad;\n\n if (__Pyx_ImportFunction(module, \"PyMPIStatus_New\", (void (**)(void))&PyMPIStatus_New, \"PyObject *(MPI_Status *)\") < 0) goto bad;\n\n if (__Pyx_ImportFunction(module, \"PyMPIStatus_Get\", (void (**)(void))&PyMPIStatus_Get, \"MPI_Status *(PyObject *)\") < 0) goto bad;\n\n if (__Pyx_ImportFunction(module, \"PyMPIRequest_New\", (void (**)(void))&PyMPIRequest_New, \"PyObject *(MPI_Request)\") < 0) goto bad;\n\n if (__Pyx_ImportFunction(module, \"PyMPIRequest_Get\", (void (**)(void))&PyMPIRequest_Get, \"MPI_Request *(PyObject *)\") < 0) goto bad;\n\n if (__Pyx_ImportFunction(module, \"PyMPIOp_New\", (void (**)(void))&PyMPIOp_New, \"PyObject *(MPI_Op)\") < 0) goto bad;\n\n if (__Pyx_ImportFunction(module, \"PyMPIOp_Get\", (void (**)(void))&PyMPIOp_Get, \"MPI_Op *(PyObject *)\") < 0) goto bad;\n\n if (__Pyx_ImportFunction(module, \"PyMPIInfo_New\", (void (**)(void))&PyMPIInfo_New, \"PyObject *(MPI_Info)\") < 0) goto bad;\n\n if (__Pyx_ImportFunction(module, \"PyMPIInfo_Get\", (void (**)(void))&PyMPIInfo_Get, \"MPI_Info *(PyObject *)\") < 0) goto bad;\n\n if (__Pyx_ImportFunction(module, \"PyMPIGroup_New\", (void (**)(void))&PyMPIGroup_New, \"PyObject *(MPI_Group)\") < 0) goto bad;\n\n if (__Pyx_ImportFunction(module, \"PyMPIGroup_Get\", (void (**)(void))&PyMPIGroup_Get, \"MPI_Group *(PyObject *)\") < 0) goto bad;\n\n if (__Pyx_ImportFunction(module, \"PyMPIComm_New\", (void (**)(void))&PyMPIComm_New, \"PyObject *(MPI_Comm)\") < 0) goto bad;\n\n if (__Pyx_ImportFunction(module, \"PyMPIComm_Get\", (void (**)(void))&PyMPIComm_Get, \"MPI_Comm *(PyObject *)\") < 0) goto bad;\n\n if (__Pyx_ImportFunction(module, \"PyMPIWin_New\", (void (**)(void))&PyMPIWin_New, \"PyObject *(MPI_Win)\") < 0) goto bad;\n\n if (__Pyx_ImportFunction(module, \"PyMPIWin_Get\", (void (**)(void))&PyMPIWin_Get, \"MPI_Win *(PyObject *)\") < 0) goto bad;\n\n if (__Pyx_ImportFunction(module, \"PyMPIFile_New\", (void (**)(void))&PyMPIFile_New, \"PyObject *(MPI_File)\") < 0) goto bad;\n\n if (__Pyx_ImportFunction(module, \"PyMPIFile_Get\", (void (**)(void))&PyMPIFile_Get, \"MPI_File *(PyObject *)\") < 0) goto bad;\n\n if (__Pyx_ImportFunction(module, \"PyMPIErrhandler_New\", (void (**)(void))&PyMPIErrhandler_New, \"PyObject *(MPI_Errhandler)\") < 0) goto bad;\n\n if (__Pyx_ImportFunction(module, \"PyMPIErrhandler_Get\", (void (**)(void))&PyMPIErrhandler_Get, \"MPI_Errhandler *(PyObject *)\") < 0) goto bad;\n\n Py_DECREF(module); module = 0;\n\n __pyx_ptype_6mpi4py_3MPI_Status = __Pyx_ImportType(\"mpi4py.MPI\", \"Status\", sizeof(PyMPIStatusObject)); if (!__pyx_ptype_6mpi4py_3MPI_Status) goto bad;\n\n __pyx_ptype_6mpi4py_3MPI_Datatype = __Pyx_ImportType(\"mpi4py.MPI\", \"Datatype\", sizeof(PyMPIDatatypeObject)); if (!__pyx_ptype_6mpi4py_3MPI_Datatype) goto bad;\n\n __pyx_ptype_6mpi4py_3MPI_Request = __Pyx_ImportType(\"mpi4py.MPI\", \"Request\", sizeof(PyMPIRequestObject)); if (!__pyx_ptype_6mpi4py_3MPI_Request) goto bad;\n\n __pyx_ptype_6mpi4py_3MPI_Prequest = __Pyx_ImportType(\"mpi4py.MPI\", \"Prequest\", sizeof(PyMPIPrequestObject)); if (!__pyx_ptype_6mpi4py_3MPI_Prequest) goto bad;\n\n __pyx_ptype_6mpi4py_3MPI_Grequest = __Pyx_ImportType(\"mpi4py.MPI\", \"Grequest\", sizeof(PyMPIGrequestObject)); if (!__pyx_ptype_6mpi4py_3MPI_Grequest) goto bad;\n\n __pyx_ptype_6mpi4py_3MPI_Op = __Pyx_ImportType(\"mpi4py.MPI\", \"Op\", sizeof(PyMPIOpObject)); if (!__pyx_ptype_6mpi4py_3MPI_Op) goto bad;\n\n __pyx_ptype_6mpi4py_3MPI_Group = __Pyx_ImportType(\"mpi4py.MPI\", \"Group\", sizeof(PyMPIGroupObject)); if (!__pyx_ptype_6mpi4py_3MPI_Group) goto bad;\n\n __pyx_ptype_6mpi4py_3MPI_Info = __Pyx_ImportType(\"mpi4py.MPI\", \"Info\", sizeof(PyMPIInfoObject)); if (!__pyx_ptype_6mpi4py_3MPI_Info) goto bad;\n\n __pyx_ptype_6mpi4py_3MPI_Errhandler = __Pyx_ImportType(\"mpi4py.MPI\", \"Errhandler\", sizeof(PyMPIErrhandlerObject)); if (!__pyx_ptype_6mpi4py_3MPI_Errhandler) goto bad;\n\n __pyx_ptype_6mpi4py_3MPI_Comm = __Pyx_ImportType(\"mpi4py.MPI\", \"Comm\", sizeof(PyMPICommObject)); if (!__pyx_ptype_6mpi4py_3MPI_Comm) goto bad;\n\n __pyx_ptype_6mpi4py_3MPI_Intracomm = __Pyx_ImportType(\"mpi4py.MPI\", \"Intracomm\", sizeof(PyMPIIntracommObject)); if (!__pyx_ptype_6mpi4py_3MPI_Intracomm) goto bad;\n\n __pyx_ptype_6mpi4py_3MPI_Cartcomm = __Pyx_ImportType(\"mpi4py.MPI\", \"Cartcomm\", sizeof(PyMPICartcommObject)); if (!__pyx_ptype_6mpi4py_3MPI_Cartcomm) goto bad;\n\n __pyx_ptype_6mpi4py_3MPI_Graphcomm = __Pyx_ImportType(\"mpi4py.MPI\", \"Graphcomm\", sizeof(PyMPIGraphcommObject)); if (!__pyx_ptype_6mpi4py_3MPI_Graphcomm) goto bad;\n\n __pyx_ptype_6mpi4py_3MPI_Intercomm = __Pyx_ImportType(\"mpi4py.MPI\", \"Intercomm\", sizeof(PyMPIIntercommObject)); if (!__pyx_ptype_6mpi4py_3MPI_Intercomm) goto bad;\n\n __pyx_ptype_6mpi4py_3MPI_Win = __Pyx_ImportType(\"mpi4py.MPI\", \"Win\", sizeof(PyMPIWinObject)); if (!__pyx_ptype_6mpi4py_3MPI_Win) goto bad;\n\n __pyx_ptype_6mpi4py_3MPI_File = __Pyx_ImportType(\"mpi4py.MPI\", \"File\", sizeof(PyMPIFileObject)); if (!__pyx_ptype_6mpi4py_3MPI_File) goto bad;\n\n return 0;\n\n bad:\n\n Py_XDECREF(module);\n\n return -1;\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI_api.h", "rank": 20, "score": 52600.62051899836 }, { "content": "static PyTypeObject *__pyx_ptype_6mpi4py_3MPI_Info;\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI_api.h", "rank": 21, "score": 50790.481102807375 }, { "content": "static PyTypeObject *__pyx_ptype_6mpi4py_3MPI_Request;\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI_api.h", "rank": 22, "score": 50790.481102807375 }, { "content": "static PyTypeObject *__pyx_ptype_6mpi4py_3MPI_Win;\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI_api.h", "rank": 23, "score": 50790.481102807375 }, { "content": "static PyTypeObject *__pyx_ptype_6mpi4py_3MPI_Datatype;\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI_api.h", "rank": 24, "score": 50790.481102807375 }, { "content": "static PyTypeObject *__pyx_ptype_6mpi4py_3MPI_Comm;\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI_api.h", "rank": 25, "score": 50790.481102807375 }, { "content": "static PyTypeObject *__pyx_ptype_6mpi4py_3MPI_File;\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI_api.h", "rank": 26, "score": 50790.481102807375 }, { "content": "static PyTypeObject *__pyx_ptype_6mpi4py_3MPI_Group;\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI_api.h", "rank": 27, "score": 50790.481102807375 }, { "content": "static PyTypeObject *__pyx_ptype_6mpi4py_3MPI_Errhandler;\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI_api.h", "rank": 28, "score": 50790.481102807375 }, { "content": "static PyTypeObject *__pyx_ptype_6mpi4py_3MPI_Graphcomm;\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI_api.h", "rank": 29, "score": 50790.481102807375 }, { "content": "static PyTypeObject *__pyx_ptype_6mpi4py_3MPI_Grequest;\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI_api.h", "rank": 30, "score": 50790.481102807375 }, { "content": "static PyTypeObject *__pyx_ptype_6mpi4py_3MPI_Cartcomm;\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI_api.h", "rank": 31, "score": 50790.481102807375 }, { "content": "static PyTypeObject *__pyx_ptype_6mpi4py_3MPI_Status;\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI_api.h", "rank": 32, "score": 50790.481102807375 }, { "content": "static PyTypeObject *__pyx_ptype_6mpi4py_3MPI_Intercomm;\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI_api.h", "rank": 33, "score": 50790.481102807375 }, { "content": "static PyTypeObject *__pyx_ptype_6mpi4py_3MPI_Prequest;\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI_api.h", "rank": 34, "score": 50790.481102807375 }, { "content": "static PyTypeObject *__pyx_ptype_6mpi4py_3MPI_Op;\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI_api.h", "rank": 35, "score": 50790.481102807375 }, { "content": "static PyTypeObject *__pyx_ptype_6mpi4py_3MPI_Intracomm;\n", "file_path": "Utilities/mpi4py/mpi4py/include/mpi4py/mpi4py_MPI_api.h", "rank": 36, "score": 50790.481102807375 }, { "content": "#include <iostream>\n\n#include <fstream>\n\n#include <sstream>\n\n#include <string>\n\n#include <cstdlib>\n\n#include <cstring>\n\n#include <vector>\n\n#include <map>\n\nusing namespace std;\n\n\n\n#include \"PluginManager.h\"\n\n#include \"DatabasePluginManager.h\"\n\n#include \"DatabasePluginInfo.h\"\n\n#include \"VisItException.h\"\n\n\n\n#include \"BootstrapConfigure.h\"\n\n\n\n// This is the template used to generate the server manager \n\n// XML tags.\n\nconst char SOURCE_PROXY_XML_TEMPLATE[]=\"\\\n", "file_path": "Plugins/VisItDatabaseBridge/BootstrapConfigure.cpp", "rank": 37, "score": 8.336602366001733 }, { "content": "// this scene has a tank with two liquids, and a surface between the interface\n\n// of the two liquids\n\n\n\n#include <stdlib.h>\n\n#include <string.h>\n\n\n\n// include the required header files for the VTK classes we are using.\n\n#include \"vtkActor.h\"\n\n#include \"vtkLight.h\"\n\n#include \"vtkRenderer.h\"\n\n#include \"vtkRenderWindow.h\"\n\n#include \"vtkRenderWindowInteractor.h\"\n\n#include \"vtkCamera.h\"\n\n#include \"vtkPolyDataMapper.h\"\n\n#include \"vtkInteractorStyleTrackballCamera.h\"\n\n#include \"vtkPoints.h\"\n\n#include \"vtkTransformFilter.h\"\n\n#include \"vtkTransform.h\"\n\n#include \"vtkCellArray.h\"\n\n#include \"vtkParametricRandomHills.h\"\n", "file_path": "Plugins/Manta/VTK/Examples/water.cpp", "rank": 38, "score": 8.321812194151613 }, { "content": "// given .vtk files as arguments, loads the meshes and puts them in a scene\n\n// rendered using Manta\n\n\n\n#include <stdlib.h>\n\n\n\n// include the required header files for the VTK classes we are using.\n\n#include \"vtkPolyDataMapper.h\"\n\n#include \"vtkRenderWindow.h\"\n\n#include \"vtkCamera.h\"\n\n#include \"vtkRenderer.h\"\n\n#include \"vtkRenderWindowInteractor.h\"\n\n#include \"vtkPolyDataReader.h\"\n\n#include \"vtkInteractorStyleTrackballCamera.h\"\n\n#include \"vtkLight.h\"\n\n#include \"vtkRegularPolygonSource.h\"\n\n#include \"vtkSphereSource.h\"\n\n\n\n#include \"vtkMantaProperty.h\"\n\n\n\n#include <Engine/Control/RTRT.h>\n", "file_path": "Plugins/Manta/VTK/Examples/isosurface.cpp", "rank": 39, "score": 8.242034531442155 }, { "content": "#include \"vtkSMGlobalPropertiesManager.h\"\n\n#include \"vtkSMLink.h\"\n\n#include \"vtkSMProxy.h\"\n\n#include \"vtkSMProxySelectionModel.h\"\n\n\n\n#include <vtkstd/map>\n\n#include <vtkstd/set>\n\n#include <vtkstd/vector>\n\n#include <vtksys/ios/sstream>\n\n#include \"vtkStdString.h\"\n\n\n", "file_path": "Servers/ServerManager/vtkSMProxyManagerInternals.h", "rank": 40, "score": 8.224487109327104 }, { "content": "//\n\n// .SECTION See Also\n\n// \n\n\n\n#ifndef __vtknifti1_io_h\n\n#define __vtknifti1_io_h\n\n\n\n#include \"vtkObject.h\"\n\n\n\n#include <stdio.h>\n\n#include <stdlib.h>\n\n#include <string.h>\n\n#include <math.h>\n\n#include <ctype.h>\n\n\n\n#ifndef DONT_INCLUDE_ANALYZE_STRUCT\n\n#define DONT_INCLUDE_ANALYZE_STRUCT /*** not needed herein ***/\n\n#endif\n\n#include \"vtknifti1.h\" /*** NIFTI-1 header specification ***/\n\n\n", "file_path": "Plugins/AnalyzeNIfTIReaderWriter/vtknifti1_io.h", "rank": 41, "score": 8.20748823711292 }, { "content": "#include <qpolygon.h>\n\n#include <qpixmap.h>\n\n#include <qimage.h>\n\n#include <qnamespace.h>\n\n#include <QMouseEvent>\n\n\n\n#include <iostream>\n\n#include <cmath>\n\n#include <cstdlib>\n\n\n\n// ****************************************************************************\n\n// Method: QvisGaussianOpacityBar::QvisGaussianOpacityBar\n\n//\n\n// Purpose:\n\n//\n\n//\n\n// Programmer: Jeremy Meredith\n\n// Creation: January 31, 2001\n\n//\n\n// ****************************************************************************\n", "file_path": "Plugins/PointSprite/ParaViewPlugin/Qvis/QvisGaussianOpacityBar.cpp", "rank": 42, "score": 8.191661451370322 }, { "content": "#include <iostream>\n\n#include <string>\n\n#include <vector>\n\n#include <map>\n\nusing namespace std;\n\n\n\n#include \"PluginManager.h\"\n\n#include \"DatabasePluginManager.h\"\n\n#include \"DatabasePluginInfo.h\"\n\n#include \"VisItException.h\"\n\n\n\n\n\nconst char *dbTypeStr[] = {\n\n \"STSD\",\n\n \"STMD\",\n\n \"MTSD\",\n\n \"MTMD\",\n\n \"CUSTOM\"};\n\n\n\n\n", "file_path": "Plugins/VisItDatabaseBridge/VisItDbList.cpp", "rank": 43, "score": 8.182167130954143 }, { "content": "#include <qpainter.h>\n\n#include <qstyle.h>\n\n#include <qtimer.h>\n\n#include <QEvent>\n\n#include <QKeyEvent>\n\n#include <QPalette>\n\n#include <QPolygon>\n\n#include <QMatrix>\n\n#include <QStyleOption>\n\n#include \"QvisSpectrumBar.h\"\n\n\n\n// Some constants for paging modes.\n\n#define NO_PAGING -1\n\n#define INCREMENT 0\n\n#define DECREMENT 1\n\n#define PAGE_INCREMENT 2\n\n#define PAGE_DECREMENT 3\n\n#define PAGE_HOME 4\n\n#define PAGE_END 5\n\n\n", "file_path": "Plugins/PointSprite/ParaViewPlugin/Qvis/QvisSpectrumBar.cpp", "rank": 44, "score": 8.174505118812219 }, { "content": "#include <qpainter.h>\n\n#include <QPolygon>\n\n#include <qpixmap.h>\n\n#include <qimage.h>\n\n#include <QMouseEvent>\n\n\n\n#include <iostream>\n\n#include <cmath>\n\n#include <cstdlib>\n\n\n\n// ****************************************************************************\n\n// Method: QvisScribbleOpacityBar::QvisScribbleOpacityBar\n\n//\n\n// Purpose:\n\n//\n\n//\n\n// Programmer: Jeremy Meredith\n\n// Creation: January 31, 2001\n\n//\n\n// Modifications:\n", "file_path": "Plugins/PointSprite/ParaViewPlugin/Qvis/QvisScribbleOpacityBar.cpp", "rank": 45, "score": 8.172694793322506 }, { "content": "#include <qpainter.h>\n\n#include <qpolygon.h>\n\n#include <qpixmap.h>\n\n#include <qimage.h>\n\n\n\n#include <iostream>\n\n#include <cmath>\n\n#include <cstdlib>\n\n\n\n\n\n// ****************************************************************************\n\n// Method: QvisAbstractOpacityBar::QvisAbstractOpacityBar\n\n//\n\n// Purpose:\n\n//\n\n//\n\n// Programmer: Jeremy Meredith\n\n// Creation: January 31, 2001\n\n//\n\n// ****************************************************************************\n", "file_path": "Plugins/PointSprite/ParaViewPlugin/Qvis/QvisAbstractOpacityBar.cpp", "rank": 46, "score": 8.149840089371347 }, { "content": "#include \"vtkPoints.h\"\n\n#include \"vtkPolyData.h\"\n\n#include \"vtkWindowToImageFilter.h\"\n\n#include \"vtkPNGWriter.h\"\n\n#include \"vtkPolyDataMapper.h\"\n\n#include \"vtkActor.h\"\n\n#include \"vtkCamera.h\"\n\n#include \"vtkRenderer.h\"\n\n#include \"vtkRenderWindow.h\"\n\n#include \"vtkRenderWindowInteractor.h\"\n\n\n\n#define IMAGE_FILENAME \"cube.png\"\n\n\n\nint main()\n\n{\n\n int i;\n\n static float pointPositions[8][3]= {\n\n { 0, 0, 0 }, { 1, 0, 0 }, { 1, 1, 0 }, { 0, 1, 0 },\n\n { 0, 0, 1 }, { 1, 0, 1 }, { 1, 1, 1 }, { 0, 1, 1 } };\n\n static vtkIdType pointIds[6][4]= {\n", "file_path": "Plugins/Manta/VTK/Examples/SaveImage.cpp", "rank": 47, "score": 8.12932154774591 }, { "content": "#include <QWidget>\n\n#include <QVariant>\n\n#include \"pqObjectPanelInterface.h\"\n\n#include \"vtkSMProxy.h\"\n\n#include <QObject>\n\nclass pqProxy;\n\n\n", "file_path": "Plugins/PrismPlugins/Client/PrismObjectPanelsImplementation.h", "rank": 48, "score": 8.062795626791013 }, { "content": "// \n\n\n\n#ifndef __vtkznzlib_h\n\n#define __vtkznzlib_h\n\n\n\n#include \"vtkObject.h\"\n\n\n\n#include <stdio.h>\n\n#include <stdlib.h>\n\n#include <string.h>\n\n#include <stdarg.h>\n\n\n\n/* include optional check for HAVE_FDOPEN here, from deleted config.h:\n\n\n\n uncomment the following line if fdopen() exists for your compiler and\n\n compiler options\n\n*/\n\n/* #define HAVE_FDOPEN */\n\n\n\n#ifdef HAVE_ZLIB\n", "file_path": "Plugins/AnalyzeNIfTIReaderWriter/vtkznzlib.h", "rank": 49, "score": 7.996929158543857 }, { "content": "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR\n\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n\n=========================================================================*/\n\n\n\n#ifndef _pqTestUtility_h\n\n#define _pqTestUtility_h\n\n\n\n#include <QObject>\n\n#include <QMap>\n\n#include <QSet>\n\n#include <QTextStream>\n\n#include <QFile>\n\n#include <QStringList>\n\n\n\n#include \"QtTestingExport.h\"\n\n#include \"pqEventDispatcher.h\"\n\n#include \"pqEventPlayer.h\"\n\n#include \"pqEventTranslator.h\"\n", "file_path": "Qt/Testing/pqTestUtility.h", "rank": 50, "score": 7.9966663480150615 }, { "content": "#include \"pqComponentsExport.h\"\n\n#include <QPointer>\n\n#include <QObject>\n\n#include <QTimer>\n\nclass pqPipelineSource;\n", "file_path": "Qt/Components/pqVCRController.h", "rank": 51, "score": 7.979114179564374 }, { "content": "#include <iostream>\n\n#include <string>\n\n#include <vector>\n\n#include <map>\n\nusing namespace std;\n\n\n\n#include \"vtkVisItDatabase.h\"\n\n#include \"vtkVisItDatabaseBridge.h\"\n\n#include \"vtkDataSet.h\"\n\n\n\n\n\n\n\n//=============================================================================\n\n\n\nint main(int argc, char **argv)\n\n{\n\n const char pluginDir[]=\"/home/burlen/ext2/v3/visit1.10.0/src/plugins\\0\";\n\n const char *pluginId;\n\n const char *fileName;\n\n\n", "file_path": "Plugins/VisItDatabaseBridge/VisItDbViewer.cpp", "rank": 52, "score": 7.971055801923343 }, { "content": "#include \"pqComponentsExport.h\"\n\n#include <QWidget>\n\n#include <QString>\n\n#include <QStringList>\n\nclass QLineEdit;\n", "file_path": "Qt/Components/pqFileChooserWidget.h", "rank": 53, "score": 7.961117918906454 }, { "content": "\n\n#include <QMainWindow>\n\n#include <QPointer>\n\n#include \"pqRenderView.h\"\n\n#include \"vtkObject.h\"\n\n\n", "file_path": "Qt/Core/Testing/BasicApp.h", "rank": 54, "score": 7.961117918906454 }, { "content": "/*=========================================================================\n\n\n\n Program: ParaView\n\n Module: PrismDisplayPanelsImplementation.h\n\n\n\n=========================================================================*/\n\n#ifndef _PrismDisplayPanelsImplementation_h\n\n#define _PrismDisplayPanelsImplementation_h\n\n\n\n#include <QWidget>\n\n#include <QVariant>\n\n#include \"pqDisplayPanelInterface.h\"\n\n#include \"pqRepresentation.h\"\n\n#include \"vtkSMProxy.h\"\n\n#include \"pqDisplayProxyEditor.h\"\n\n#include <QObject>\n\n\n\n/// standard display panels\n", "file_path": "Plugins/PrismPlugins/Client/PrismDisplayPanelsImplementation.h", "rank": 55, "score": 7.960783042269506 }, { "content": "// First include the required header files for the VTK classes we are using.\n\n#include \"vtkConeSource.h\"\n\n#include \"vtkPolyDataMapper.h\"\n\n#include \"vtkActor.h\"\n\n#include \"vtkProperty.h\"\n\n#include \"vtkCamera.h\"\n\n#include \"vtkRenderer.h\"\n\n#include \"vtkRenderWindow.h\"\n\n#include \"vtkRenderWindowInteractor.h\"\n\n\n\ndouble lamp_black[] = {0.1800, 0.2800, 0.2300};\n\n\n\nint main()\n\n{\n\n //\n\n // Next we create an instance of vtkConeSource and set some of its\n\n // properties. The instance of vtkConeSource \"cone\" is part of a\n\n // visualization pipeline (it is a source process object); it produces data\n\n // (output type is vtkPolyData) which other filters may process.\n\n //\n", "file_path": "Plugins/Manta/VTK/Examples/Cone.cpp", "rank": 56, "score": 7.952712386984516 }, { "content": "#include \"QtTestingExport.h\"\n\n#include \"pqEventDispatcher.h\"\n\n#include \"pqEventPlayer.h\"\n\n#include \"pqEventTranslator.h\"\n\nclass pqEventObserver;\n", "file_path": "Qt/Testing/pqTestUtility.h", "rank": 57, "score": 7.925367838827956 }, { "content": "#if defined(ITKZLIB)\n\n#include \"itk_zlib.h\"\n\n#elif defined(VTKZLIB)\n\n#include \"vtk_zlib.h\"\n\n#else\n\n#include \"zlib.h\"\n\n#endif\n\n#endif\n\n\n\n//#include \"vtk_znzlib_mangle.h\"\n\n\n", "file_path": "Plugins/AnalyzeNIfTIReaderWriter/vtkznzlib.h", "rank": 58, "score": 7.907612933143273 }, { "content": "#include \"pqCoreExport.h\"\n\n#include <QSortFilterProxyModel>\n\n#include <QList>\n\n#include <QRegExp>\n\nclass pqFileDialogModel;\n\n\n", "file_path": "Qt/Core/pqFileDialogFilter.h", "rank": 59, "score": 7.907612933143273 }, { "content": "// .SECTION See Also\n\n// pqCameraDialog\n\n//\n\n// .SECTION Thanks\n\n// This class was contributed by SciberQuest Inc.\n\n\n\n#include <QDialog>\n\n#include <QLineEdit>\n\n#include <QList>\n\n#include <QStringList>\n\n#include <QString>\n\n\n", "file_path": "Qt/Components/pqCustomViewButtonDialog.h", "rank": 60, "score": 7.903917446250547 }, { "content": "/*=========================================================================\n\n\n\n Program: ParaView\n\n Module: PrismPanel.h\n\n\n\n=========================================================================*/\n\n#ifndef _PrismPanel_h\n\n#define _PrismPanel_h\n\n\n\n#include <QWidget>\n\n#include <QVariant>\n\n#include \"pqPipelineRepresentation.h\"\n\n#include \"vtkSMProxy.h\"\n\n#include \"pqNamedObjectPanel.h\"\n\n\n", "file_path": "Plugins/PrismPlugins/Client/PrismPanel.h", "rank": 61, "score": 7.875700817354943 }, { "content": "-------------------------------------------------------------------------*/\n\n\n\n#ifndef __pqPlotter_h\n\n#define __pqPlotter_h\n\n\n\n#include <QList>\n\n#include <QMap>\n\n#include <QObject>\n\n#include <QStringList>\n\n\n", "file_path": "Plugins/SierraPlotTools/pqPlotter.h", "rank": 62, "score": 7.87234071116271 }, { "content": "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR\n\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n\n========================================================================*/\n\n#ifndef __pqSILModel_h \n\n#define __pqSILModel_h\n\n\n\n#include <QAbstractItemModel>\n\n#include <QVector>\n\n#include <QSet>\n\n#include <vtkstd/set>\n\n\n\n#include \"vtkObject.h\"\n\n#include \"pqComponentsExport.h\"\n\n#include \"vtkSmartPointer.h\"\n\n\n", "file_path": "Qt/Components/pqSILModel.h", "rank": 63, "score": 7.83502819781197 }, { "content": "\n\n#ifndef VISIT_EXCEPTION_H\n\n#define VISIT_EXCEPTION_H\n\n\n\n#include <exception>\n\n#include <visitstream.h>\n\n#include <string>\n\n#ifdef FAKE_EXCEPTIONS\n\n#include <setjmp.h>\n\n#endif\n\n\n\n#include <pqComponentsExport.h>\n\n\n\n#ifdef FAKE_EXCEPTIONS\n\n#define VISIT_THROW_NOTHING\n\n#else\n\n#define VISIT_THROW_NOTHING throw()\n\n#endif\n\n\n\n// ****************************************************************************\n", "file_path": "Plugins/PointSprite/ParaViewPlugin/Qvis/VisItException.h", "rank": 64, "score": 7.833751607333275 }, { "content": "/*=========================================================================\n\n\n\n Program: ParaView\n\n Module: PrismSurfacePanel.h\n\n\n\n=========================================================================*/\n\n#ifndef _PrismSurfacePanel_h\n\n#define _PrismSurfacePanel_h\n\n\n\n#include <QWidget>\n\n#include <QVariant>\n\n#include \"pqPipelineRepresentation.h\"\n\n#include \"vtkSMProxy.h\"\n\n#include \"pqNamedObjectPanel.h\"\n\n\n", "file_path": "Plugins/PrismPlugins/Client/PrismSurfacePanel.h", "rank": 65, "score": 7.833751607333275 }, { "content": "#include \"pqView.h\"\n\n#include <QMap>\n\n#include <QColor>\n\nclass QLabel;\n\n\n", "file_path": "Examples/Plugins/GUIView/MyView.h", "rank": 66, "score": 7.820269783686106 }, { "content": "#include <QObject>\n\n#include <QString>\n\n#include <QVariant>\n\nclass QComboBox;\n", "file_path": "Qt/Widgets/pqSignalAdaptors.h", "rank": 67, "score": 7.820269783686106 }, { "content": "/*=========================================================================\n\n\n\n Program: ParaView\n\n Module: PrismObjectPanelsImplementation.h\n\n\n\n=========================================================================*/\n\n#ifndef _PrismObjectPanelsImplementation_h\n\n#define _PrismObjectPanelsImplementation_h\n\n\n\n#include <QWidget>\n\n#include <QVariant>\n\n#include \"pqObjectPanelInterface.h\"\n\n#include \"vtkSMProxy.h\"\n\n#include <QObject>\n", "file_path": "Plugins/PrismPlugins/Client/PrismObjectPanelsImplementation.h", "rank": 68, "score": 7.8060328540671335 }, { "content": "#include <QObject>\n\n#include <QVariant>\n\n#include \"pqComponentsExport.h\"\n\nclass pqProxy;\n\n\n", "file_path": "Qt/Components/pqSMSignalAdaptors.h", "rank": 69, "score": 7.797236560220194 }, { "content": "#include <QObject>\n\n#include <QString>\n\n#include \"QtTestingExport.h\"\n\nclass QTextStream;\n\n\n\n/**\n\nObserves high-level ParaView events, and serializes them to a stream \n\nfor possible playback (as a test-case, demo, tutorial, etc). To use,\n\nconnect the onRecordEvent() slot to the pqEventTranslator::recordEvent()\n\nsignal.\n\n\n\n\\sa pqEventTranslator, pqStdoutEventObserver\n\n*/\n\n\n", "file_path": "Qt/Testing/pqEventObserver.h", "rank": 70, "score": 7.797236560220194 }, { "content": "#include <QWidget>\n\n#include <QPointer>\n\n#include \"pqComponentsExport.h\"\n\nclass pqProxy;\n", "file_path": "Qt/Components/pqProxyPanel.h", "rank": 71, "score": 7.797236560220194 }, { "content": "#include <QObject>\n\n#include <QGraphicsItem>\n\n#include <QIcon>\n\nclass pqAnimationTrack;\n\n\n", "file_path": "Qt/Widgets/pqAnimationKeyFrame.h", "rank": 72, "score": 7.797236560220194 }, { "content": "-------------------------------------------------------------------------*/\n\n\n\n#ifndef __pqSierraPlotToolsUtils_h\n\n#define __pqSierraPlotToolsUtils_h\n\n\n\n#include <QList>\n\n#include <QMap>\n\n#include <QString>\n\n#include <QStringList>\n\n\n\n\n\n//=============================================================================\n", "file_path": "Plugins/SierraPlotTools/pqSierraPlotToolsUtils.h", "rank": 73, "score": 7.7683871121559385 }, { "content": "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR\n\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n\n=========================================================================*/\n\n\n\n#ifndef _pqSampleScalarWidget_h\n\n#define _pqSampleScalarWidget_h\n\n\n\n#include \"pqSMProxy.h\"\n\n#include \"pqComponentsExport.h\"\n\n\n\n#include <QWidget>\n\n#include <QModelIndex>\n\n#include <QList>\n\n#include <QVariant>\n\n\n", "file_path": "Qt/Components/pqSampleScalarWidget.h", "rank": 74, "score": 7.742456713379066 }, { "content": "\n\n#ifndef _MyView_h\n\n#define _MyView_h\n\n\n\n#include \"pqView.h\"\n\n#include <QMap>\n\n#include <QColor>\n", "file_path": "Examples/Plugins/GUIView/MyView.h", "rank": 75, "score": 7.728943843107613 }, { "content": "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR\n\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n\n=========================================================================*/\n\n#ifndef __pqServerManagerSelectionModel_h\n\n#define __pqServerManagerSelectionModel_h\n\n\n\n#include <QObject>\n\n#include <QList>\n\n#include <QItemSelectionModel>\n\n#include <QPointer>\n\n#include \"pqCoreExport.h\"\n\n#include \"pqServerManagerModelItem.h\"\n\n\n", "file_path": "Qt/Core/pqServerManagerSelectionModel.h", "rank": 76, "score": 7.700231087859405 }, { "content": "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR\n\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n\n=========================================================================*/\n\n\n\n/// \\file pqChartOptionsEditor.h\n\n/// \\date 7/20/2007\n\n\n\n#ifndef _pqChartOptionsEditor_h\n\n#define _pqChartOptionsEditor_h\n\n\n\n\n\n#include \"pqComponentsExport.h\"\n\n#include \"pqOptionsContainer.h\"\n\n#include \"vtkQtChartAxisLayer.h\" // Needed for enum\n\n#include \"vtkQtChartAxis.h\" // Needed for enum\n\n#include \"vtkQtChartAxisOptions.h\" // Needed for enum\n\n#include \"vtkQtChartLegend.h\" // Needed for enum\n\n#include \"pqChartValue.h\"\n\n\n", "file_path": "Qt/Components/pqChartOptionsEditor.h", "rank": 77, "score": 7.676002974830146 }, { "content": "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR\n\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n\n=========================================================================*/\n\n\n\n#ifndef _MainWindow_h\n\n#define _MainWindow_h\n\n\n\n#include \"OverViewCoreExport.h\"\n\n\n\n#include <QDockWidget>\n\n#include <QMainWindow>\n\n#include <QVariant>\n\n#include <vtkIOStream.h>\n\n\n", "file_path": "Applications/OverView/Core/MainWindow.h", "rank": 78, "score": 7.664454304021215 }, { "content": "* specific prior written permission.\n\n*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\n* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF\n\n* CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR\n\n* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\n* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\n* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n\n* DAMAGE.\n\n*\n\n*****************************************************************************/\n\n\n\n#ifndef ATTRIBUTEGROUP_H\n\n#define ATTRIBUTEGROUP_H\n\n#include <vtkstd/vector>\n\n#include <vtkstd/string>\n\n#include <vtkstd/exception>\n\n#include <visitstream.h>\n\n#include <VisItException.h>\n\n\n\n// Forward declaration\n", "file_path": "Plugins/PointSprite/ParaViewPlugin/Qvis/AttributeGroup.h", "rank": 79, "score": 7.6584635422903204 }, { "content": "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR\n\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n\n=========================================================================*/\n\n\n\n/// \\file pqXYChartOptionsEditor.h\n\n/// \\date 7/20/2007\n\n\n\n#ifndef _pqXYChartOptionsEditor_h\n\n#define _pqXYChartOptionsEditor_h\n\n\n\n#include \"pqComponentsExport.h\"\n\n#include \"pqOptionsContainer.h\"\n\n#include \"vtkQtChartAxisLayer.h\" // Needed for enum\n\n#include \"vtkQtChartAxis.h\" // Needed for enum\n\n#include \"vtkQtChartAxisOptions.h\" // Needed for enum\n\n#include \"vtkQtChartLegend.h\" // Needed for enum\n\n#include \"pqChartValue.h\"\n\n\n", "file_path": "Qt/Components/pqXYChartOptionsEditor.h", "rank": 80, "score": 7.653810531653767 }, { "content": "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR\n\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n\n========================================================================*/\n\n#ifndef __pqSelectionManager_h\n\n#define __pqSelectionManager_h\n\n\n\n#include \"pqComponentsExport.h\"\n\n#include \"pqServerManagerSelectionModel.h\"\n\n\n\n#include <QObject>\n\n#include <QPair>\n\n#include \"vtkType.h\"\n\n\n", "file_path": "Qt/Components/pqSelectionManager.h", "rank": 81, "score": 7.645481498008073 }, { "content": "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR\n\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n\n=========================================================================*/\n\n\n\n#ifndef pqAnimationModel_h\n\n#define pqAnimationModel_h\n\n\n\n#include \"QtWidgetsExport.h\"\n\n\n\n#include <QObject>\n\n#include <QGraphicsScene>\n\n#include <QStandardItemModel>\n\n#include <QPolygonF>\n\n\n", "file_path": "Qt/Widgets/pqAnimationModel.h", "rank": 82, "score": 7.636030275821412 }, { "content": "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR\n\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n\n=========================================================================*/\n\n\n\n/// \\file pqObjectInspectorWidget.h\n\n/// \\brief\n\n/// The pqObjectInspectorWidget class is used to display the properties\n\n/// of an object in an editable form.\n\n///\n\n/// \\date 11/25/2005\n\n\n\n#ifndef _pqObjectInspectorWidget_h\n\n#define _pqObjectInspectorWidget_h\n\n\n\n#include \"pqComponentsExport.h\"\n\n#include <QWidget>\n\n#include <QTimer>\n\n#include <QMap>\n\n#include <QPointer>\n\n#include \"pqProxy.h\"\n\n\n", "file_path": "Qt/Components/pqObjectInspectorWidget.h", "rank": 83, "score": 7.63361980246082 }, { "content": "\n\n#ifndef QTestApp_h\n\n#define QTestApp_h\n\n\n\n#include <QApplication>\n\n#include <QVector>\n\n#include <QByteArray>\n\n\n", "file_path": "Qt/Widgets/Testing/QTestApp.h", "rank": 84, "score": 7.617742831440209 }, { "content": "#include \"vtkCell.h\" // Needed for VTK_CELL_SIZE\n\n#include \"vtkStringArray.h\"\n\n#include \"vtkMultiBlockDataSetAlgorithm.h\"\n\nclass vtkIntArray;\n", "file_path": "Plugins/PrismPlugins/Server/vtkPrismFilter.h", "rank": 85, "score": 7.617742831440209 }, { "content": "// CSCS - Swiss National Supercomputing Centre for creating and contributing\n\n// this class.\n\n\n\n#ifndef __vtkH5PartReader_h\n\n#define __vtkH5PartReader_h\n\n\n\n#include \"vtkToolkits.h\" // For VTK_USE_MPI \n\n#include \"vtkPolyDataAlgorithm.h\"\n\n#include <vtkstd/string>\n\n#include <vtkstd/vector>\n\n\n", "file_path": "Plugins/H5PartReader/vtkH5PartReader.h", "rank": 86, "score": 7.6175043527633 }, { "content": "/*=========================================================================\n\n\n\n Program: ParaView\n\n Module: vtkProcessModuleConnectionManagerInternals.h\n\n\n\n Copyright (c) Kitware, Inc.\n\n All rights reserved.\n\n See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.\n\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n\n PURPOSE. See the above copyright notice for more information.\n\n\n\n=========================================================================*/\n\n\n\n#include \"vtkClientSocket.h\"\n\n#include \"vtkSmartPointer.h\"\n\n#include \"vtkProcessModuleConnection.h\"\n\n#include \"vtkPVServerSocket.h\"\n\n\n\n#include <vtkstd/map>\n\n#include <vtkstd/deque>\n\n\n", "file_path": "Servers/Common/vtkProcessModuleConnectionManagerInternals.h", "rank": 87, "score": 7.617265889017401 }, { "content": "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR\n\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n\n=========================================================================*/\n\n\n\n#ifndef _pqCommandServerStartup_h\n\n#define _pqCommandServerStartup_h\n\n\n\n#include \"pqCoreExport.h\"\n\n#include \"pqServerStartup.h\"\n\n#include \"vtkSmartPointer.h\"\n\n\n\n#include <QProcess>\n\n#include <QPointer>\n\n#include <QTimer>\n\n\n\n/////////////////////////////////////////////////////////////////////////////\n\n// pqCommandServerStartup\n\n\n\n/// Concrete implementation of pqServerStartup that runs an external\n\n/// command to start a remote server.\n", "file_path": "Qt/Core/pqCommandServerStartup.h", "rank": 88, "score": 7.617146662743142 }, { "content": "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR\n\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n\n========================================================================*/\n\n#ifndef __pqChartSeriesEditorModel_h \n\n#define __pqChartSeriesEditorModel_h\n\n\n\n#include \"pqCheckableHeaderModel.h\"\n\n#include \"pqComponentsExport.h\"\n\n\n\n#include <QColor>\n\n#include <QPointer>\n\n#include \"vtkWeakPointer.h\"\n\n\n", "file_path": "Qt/Components/pqChartSeriesEditorModel.h", "rank": 89, "score": 7.607816292638365 }, { "content": "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR\n\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n\n=========================================================================*/\n\n#ifndef _PrismDisplayProxyEditor_h\n\n#define _PrismDisplayProxyEditor_h\n\n\n\n#include <QWidget>\n\n#include <QList>\n\n#include <QVariant>\n\n#include \"pqDisplayPanel.h\"\n\n#include \"vtkSMPrismCubeAxesRepresentationProxy.h\"\n\n\n", "file_path": "Plugins/PrismPlugins/Client/PrismDisplayProxyEditor.h", "rank": 90, "score": 7.607816292638365 }, { "content": "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR\n\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n\n=========================================================================*/\n\n\n\n#ifndef _pqFileDialogModel_h\n\n#define _pqFileDialogModel_h\n\n\n\n#include \"pqCoreExport.h\"\n\n#include <QObject>\n\n#include <QAbstractItemModel>\n\n#include <QFileIconProvider>\n\n\n\n#include \"vtkPVFileInformation.h\"\n", "file_path": "Qt/Core/pqFileDialogModel.h", "rank": 91, "score": 7.598457906328441 }, { "content": "// This file has been developed as part of the CARRIOCAS (Distributed\n\n// computation over ultra high optical internet network ) project (\n\n// http://www.carriocas.org/index.php?lng=ang ) of the SYSTEM@TIC French ICT\n\n// Cluster (http://www.systematic-paris-region.org/en/index.html) under the\n\n// supervision of CEA (http://www.cea.fr) and EDF (http://www.edf.fr) by\n\n// Oxalya (http://www.oxalya.com)\n\n//\n\n// Copyright (c) CEA\n\n//\n\n// </verbatim>\n\n\n\n\n\n#ifndef __vtkPEnSightReader2_h\n\n#define __vtkPEnSightReader2_h\n\n\n\n#include \"vtkGenericEnSightReader2.h\"\n\n\n\n#include \"vtkIdTypeArray.h\" // For ivars\n\n#include <vtkstd/map> // For ivars\n\n#include <vtkstd/string> // For ivars\n\n#include <vtkstd/algorithm> // For ivars\n\n#include <vtkstd/string> // For ivars\n\n#include <vtkstd/vector> // For ivars\n\n#include <vtkstd/map> // For ivars\n\n\n", "file_path": "Servers/Filters/vtkPEnSightReader2.h", "rank": 92, "score": 7.592569830218206 }, { "content": "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR\n\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n\n=========================================================================*/\n\n\n\n#ifndef _pqStandardGraphLayoutStrategies_h\n\n#define _pqStandardGraphLayoutStrategies_h\n\n\n\n#include \"OverViewCoreExport.h\"\n\n#include <pqCoreExport.h>\n\n#include <pqGraphLayoutStrategyInterface.h>\n\n#include <vtkSmartPointer.h>\n\n\n\n#include <QObject>\n\n\n", "file_path": "Applications/OverView/Core/pqStandardGraphLayoutStrategies.h", "rank": 93, "score": 7.5891225152622965 }, { "content": "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR\n\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n\n=========================================================================*/\n\n\n\n#ifndef _pqStandardTreeLayoutStrategies_h\n\n#define _pqStandardTreeLayoutStrategies_h\n\n\n\n#include \"OverViewCoreExport.h\"\n\n#include <pqCoreExport.h>\n\n#include <pqTreeLayoutStrategyInterface.h>\n\n#include <vtkSmartPointer.h>\n\n\n\n#include <QObject>\n\n\n", "file_path": "Applications/OverView/Core/pqStandardTreeLayoutStrategies.h", "rank": 94, "score": 7.5891225152622965 }, { "content": "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR\n\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n\n========================================================================*/\n\n#ifndef __pqServerManagerModel_h \n\n#define __pqServerManagerModel_h\n\n\n\n#include <QObject>\n\n#include <QList>\n\n#include \"pqCoreExport.h\"\n\n#include \"vtkType.h\" // for vtkIdType.\n\n#include \"vtkClientServerID.h\" // for vtkClientServerID\n\n\n", "file_path": "Qt/Core/pqServerManagerModel.h", "rank": 95, "score": 7.570520380671558 }, { "content": "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR\n\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n\n========================================================================*/\n\n#ifndef __pqProgressManager_h\n\n#define __pqProgressManager_h\n\n\n\n#include \"pqCoreExport.h\"\n\n#include <QObject>\n\n#include <QPointer>\n\n#include <QList>\n\n\n", "file_path": "Qt/Core/pqProgressManager.h", "rank": 96, "score": 7.54131956129153 }, { "content": "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR\n\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n\n=========================================================================*/\n\n\n\n#ifndef _pqEventDispatcher_h\n\n#define _pqEventDispatcher_h\n\n\n\n#include \"QtTestingExport.h\"\n\n\n\n#include <QObject>\n\n#include <QTimer>\n\n#include <QTime>\n\n\n", "file_path": "Qt/Testing/pqEventDispatcher.h", "rank": 97, "score": 7.54131956129153 }, { "content": "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR\n\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n\n=========================================================================*/\n\n\n\n#ifndef _pqPropertyManager_h\n\n#define _pqPropertyManager_h\n\n\n\n#include \"pqCoreExport.h\"\n\n#include <QObject>\n\n#include <QVariant>\n\n#include <QPointer>\n\n\n", "file_path": "Qt/Core/pqPropertyManager.h", "rank": 98, "score": 7.54131956129153 }, { "content": "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR\n\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n\n=========================================================================*/\n\n\n\n#ifndef _pqVCRController_h\n\n#define _pqVCRController_h\n\n\n\n#include \"pqComponentsExport.h\"\n\n#include <QPointer>\n\n#include <QObject>\n\n#include <QTimer>\n", "file_path": "Qt/Components/pqVCRController.h", "rank": 99, "score": 7.54131956129153 } ]
C++
torch/lib/THD/master_worker/master/generic/THDStorage.cpp
DavidKo3/mctorch
53ffe61763059677978b4592c8b2153b0c15428f
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "master_worker/master/generic/THDStorage.cpp" #else using namespace thd; using namespace rpc; using namespace master; static THDStorage* THDStorage_(_alloc)() { THDStorage* new_storage = new THDStorage(); std::memset(reinterpret_cast<void*>(new_storage), 0, sizeof(new_storage)); new (&new_storage->refcount) std::atomic<int>(1); new_storage->storage_id = THDState::s_nextId++; new_storage->node_id = THDState::s_current_worker; new_storage->flag = TH_STORAGE_REFCOUNTED | TH_STORAGE_RESIZABLE; return new_storage; } ptrdiff_t THDStorage_(size)(const THDStorage* storage) { return storage->size; } size_t THDStorage_(elementSize)(void) { return sizeof(real); } THDStorage* THDStorage_(new)() { THDStorage* storage = THDStorage_(_alloc)(); RPCType type = type_traits<real>::type; masterCommandChannel->sendMessage( packMessage( Functions::storageNew, type, storage ), THDState::s_current_worker ); return storage; } void THDStorage_(set)(THDStorage* storage, ptrdiff_t offset, real value) { masterCommandChannel->sendMessage( packMessage( Functions::storageSet, storage, offset, value ), THDState::s_current_worker ); } real THDStorage_(get)(const THDStorage* storage, ptrdiff_t offset) { masterCommandChannel->sendMessage( packMessage( Functions::storageGet, storage, offset, type_traits<real>::type ), THDState::s_current_worker ); return receiveValueFromWorker<real>(storage->node_id); } THDStorage* THDStorage_(newWithSize)(ptrdiff_t size) { RPCType type = type_traits<real>::type; THDStorage *storage = THDStorage_(_alloc)(); storage->size = size; masterCommandChannel->sendMessage( packMessage( Functions::storageNewWithSize, type, storage, size ), THDState::s_current_worker ); return storage; } THDStorage* THDStorage_(newWithSize1)(real value) { RPCType type = type_traits<real>::type; THDStorage *storage = THDStorage_(_alloc)(); storage->size = 1; masterCommandChannel->sendMessage( packMessage( Functions::storageNewWithSize1, type, storage, value ), THDState::s_current_worker ); return storage; } THDStorage* THDStorage_(newWithSize2)(real value1, real value2) { RPCType type = type_traits<real>::type; THDStorage *storage = THDStorage_(_alloc)(); storage->size = 2; masterCommandChannel->sendMessage( packMessage( Functions::storageNewWithSize1, type, storage, value1, value2 ), THDState::s_current_worker ); return storage; } THDStorage* THDStorage_(newWithSize3)(real value1, real value2, real value3) { RPCType type = type_traits<real>::type; THDStorage *storage = THDStorage_(_alloc)(); storage->size = 3; masterCommandChannel->sendMessage( packMessage( Functions::storageNewWithSize1, type, storage, value1, value2, value3 ), THDState::s_current_worker ); return storage; } THDStorage* THDStorage_(newWithSize4)(real value1, real value2, real value3, real value4) { RPCType type = type_traits<real>::type; THDStorage *storage = THDStorage_(_alloc)(); storage->size = 4; masterCommandChannel->sendMessage( packMessage( Functions::storageNewWithSize1, type, storage, value1, value2, value3, value4 ), THDState::s_current_worker ); return storage; } void THDStorage_(setFlag)(THDStorage *storage, const char flag) { storage->flag |= flag; } void THDStorage_(clearFlag)(THDStorage *storage, const char flag) { storage->flag &= ~flag; } void THDStorage_(retain)(THDStorage *storage) { if (storage && (storage->flag & TH_STORAGE_REFCOUNTED)) storage->refcount++; } void THDStorage_(swap)(THDStorage *storage1, THDStorage *storage2) { THDStorage dummy = *storage1; *storage1 = *storage2; *storage2 = dummy; } void THDStorage_(free)(THDStorage *storage) { if (!storage || !(storage->flag & TH_STORAGE_REFCOUNTED)) return; if (--storage->refcount == 0) { masterCommandChannel->sendMessage( packMessage( Functions::storageFree, storage ), THDState::s_current_worker ); delete storage; } } void THDStorage_(resize)(THDStorage *storage, ptrdiff_t size) { if (!(storage->flag & TH_STORAGE_RESIZABLE)) THError("Trying to resize storage that is not resizable"); if (size < storage->size) return; storage->size = size; masterCommandChannel->sendMessage( packMessage( Functions::storageResize, storage, size ), THDState::s_current_worker ); } void THDStorage_(fill)(THDStorage *storage, real value) { masterCommandChannel->sendMessage( packMessage( Functions::storageFill, storage, value ), THDState::s_current_worker ); } #endif
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "master_worker/master/generic/THDStorage.cpp" #else using namespace thd; using namespace rpc; using namespace master; static THDStorage* THDStorage_(_alloc)() { THDStorage* new_storage = new THDStorage(); std::memset(reinterpret_cast<void*>(new_storage), 0, sizeof(new_storage)); new (&new_storage->refcount) std::atomic<int>(1); new_storage->storage_id = THDState::s_nextId++; new_storage->node_id = THDState::s_current_worker; new_storage->flag = TH_STORAGE_REFCOUNTED | TH_STORAGE_RESIZABLE; return new_storage; } ptrdiff_t THDStorage_(size)(const THDStorage* storage) { return storage->size; } size_t THDStorage_(elementSize)(void) { return sizeof(real); } THDStorage* THDStorage_(new)() { THDStorage* storage = THDStorage_(_alloc)(); RPCType type = type_traits<real>::type; masterCommandChannel->sendMessage( packMessage( Functions::storageNew, type, storage ), THDState::s_current_worker ); return storage; } void THDStorage_(set)(THDStorage* storage, ptrdiff_t offset, real value) { masterCommandChannel->sendMessage( packMessage( Functions::storageSet, storage, offset, value ), THDState::s_current_worker ); } real THDStorage_(get)(const THDStorage* storage, ptrdiff_t offset) { masterCommandChannel->sendMessage( packMessage( Functions::storageGet, storage, offset, type_traits<real>::type ), THDState::s_current_worker ); return receiveValueFromWorker<real>(storage->node_id); } THDStorage* THDStorage_(newWithSize)(ptrdiff_t size) { RPCType type = type_traits<real>::type; THDStorage *storage = THDStorage_(_alloc)(); storage->size = size; masterCommandChannel->sendMessage( packMessage( Functions::storageNewWithSize, type, storage, size ), THDState::s_current_worker ); return storage; } THDStorage* THDStorage_(newWithSize1)(real value) { RPCType type = type_traits<real>::type; THDStorage *storage = THDStorage_(_alloc)(); storage->size = 1; masterCommandChannel->sendMessage( packMessage( Functions::storageNewWithSize1, type, storage, value ), THDState::s_current_worker ); return storage; } THDStorage* THDStorage_(newWithSize2)(real value1, real value2) { RPCType type = type_traits<real>::type; THDStorage *storage = THDStorage_(_alloc)(); storage->size = 2; masterCommandChannel->sendMessage( packMessage( Functions::storageNewWithSize1, type, storage, value1, value2 ), THDState::s_current_worker ); return storage; } THDStorage* THDStorage_(newWithSize3)(real value1, real value2, real value3) { RPCType type = type_traits<real>::type; THDStorage *storage = THDStorage_(_alloc)(); storage->size = 3; masterCommandChannel->sendMessage( packMessage( Functions::storageNewWithSize1, type, storage, value1, value2, value3 ), THDState::s_current_worker ); return storage; } THDStorage* THDStorage_(newWithSize4)(real value
void THDStorage_(setFlag)(THDStorage *storage, const char flag) { storage->flag |= flag; } void THDStorage_(clearFlag)(THDStorage *storage, const char flag) { storage->flag &= ~flag; } void THDStorage_(retain)(THDStorage *storage) { if (storage && (storage->flag & TH_STORAGE_REFCOUNTED)) storage->refcount++; } void THDStorage_(swap)(THDStorage *storage1, THDStorage *storage2) { THDStorage dummy = *storage1; *storage1 = *storage2; *storage2 = dummy; } void THDStorage_(free)(THDStorage *storage) { if (!storage || !(storage->flag & TH_STORAGE_REFCOUNTED)) return; if (--storage->refcount == 0) { masterCommandChannel->sendMessage( packMessage( Functions::storageFree, storage ), THDState::s_current_worker ); delete storage; } } void THDStorage_(resize)(THDStorage *storage, ptrdiff_t size) { if (!(storage->flag & TH_STORAGE_RESIZABLE)) THError("Trying to resize storage that is not resizable"); if (size < storage->size) return; storage->size = size; masterCommandChannel->sendMessage( packMessage( Functions::storageResize, storage, size ), THDState::s_current_worker ); } void THDStorage_(fill)(THDStorage *storage, real value) { masterCommandChannel->sendMessage( packMessage( Functions::storageFill, storage, value ), THDState::s_current_worker ); } #endif
1, real value2, real value3, real value4) { RPCType type = type_traits<real>::type; THDStorage *storage = THDStorage_(_alloc)(); storage->size = 4; masterCommandChannel->sendMessage( packMessage( Functions::storageNewWithSize1, type, storage, value1, value2, value3, value4 ), THDState::s_current_worker ); return storage; }
function_block-function_prefixed
[ { "content": " ptrdiff_t size;\n", "file_path": "torch/lib/THD/master_worker/master/generic/THDStorage.h", "rank": 0, "score": 379224.93917560467 }, { "content": " ptrdiff_t storageOffset;\n", "file_path": "torch/lib/THD/master_worker/master/generic/THDTensor.h", "rank": 1, "score": 312148.93736398866 }, { "content": "#define THDStorage TH_CONCAT_3(THD,Real,Storage)\n", "file_path": "torch/lib/THD/master_worker/master/THDStorage.h", "rank": 2, "score": 302587.4121884518 }, { "content": " uint64_t storage_id;\n", "file_path": "torch/lib/THD/master_worker/master/generic/THDStorage.h", "rank": 3, "score": 290711.1279523253 }, { "content": "#include \"THD.h\"\n\n#include \"State.hpp\"\n\n#include \"Utils.hpp\"\n\n#include \"master_worker/common/RPC.hpp\"\n\n#include \"master_worker/common/Functions.hpp\"\n\n#include \"master_worker/master/Master.hpp\"\n\n#include \"process_group/General.hpp\"\n\n\n\n#include <cstring>\n\n#include <memory>\n\n\n\n#include \"master_worker/master/generic/THDStorage.cpp\"\n\n#include \"TH/THGenerateAllTypes.h\"\n\n\n", "file_path": "torch/lib/THD/master_worker/master/THDStorage.cpp", "rank": 4, "score": 283266.49916686537 }, { "content": " int64_t *size;\n", "file_path": "torch/lib/THD/master_worker/master/generic/THDTensor.h", "rank": 16, "score": 265795.1542434274 }, { "content": " struct THDStorage *view;\n", "file_path": "torch/lib/THD/master_worker/master/generic/THDStorage.h", "rank": 17, "score": 260588.908142307 }, { "content": " int refcount;\n", "file_path": "torch/lib/THD/master_worker/master/generic/THDStorage.h", "rank": 18, "score": 260588.908142307 }, { "content": " char flag;\n", "file_path": "torch/lib/THD/master_worker/master/generic/THDStorage.h", "rank": 19, "score": 260588.908142307 }, { "content": " THDStorage *storage;\n", "file_path": "torch/lib/THD/master_worker/master/generic/THDTensor.h", "rank": 20, "score": 260588.908142307 }, { "content": " void* allocator;\n", "file_path": "torch/lib/THD/master_worker/master/generic/THDStorage.h", "rank": 21, "score": 260588.908142307 }, { "content": " int node_id;\n", "file_path": "torch/lib/THD/master_worker/master/generic/THDStorage.h", "rank": 22, "score": 256507.31362183328 }, { "content": " int device_id; // unused at the moment\n", "file_path": "torch/lib/THD/master_worker/master/generic/THDStorage.h", "rank": 23, "score": 256507.31362183328 }, { "content": " void* allocatorContext;\n", "file_path": "torch/lib/THD/master_worker/master/generic/THDStorage.h", "rank": 24, "score": 256507.31362183328 }, { "content": "#define real double\n", "file_path": "torch/lib/THD/base/THDGenerateAllTypes.h", "rank": 25, "score": 255444.62561318194 }, { "content": "#define Real Double\n", "file_path": "torch/lib/THD/base/THDGenerateAllTypes.h", "rank": 26, "score": 255444.62561318194 }, { "content": "enum class RPCType : char {\n\n CHAR = 'c',\n\n UCHAR = 'B',\n\n FLOAT = 'f',\n\n DOUBLE = 'd',\n\n HALF = 'a',\n\n SHORT = 'h',\n\n USHORT = 'H',\n\n INT = 'i',\n\n UINT = 'I',\n\n LONG = 'l',\n\n ULONG = 'L',\n\n LONG_LONG = 'q',\n\n ULONG_LONG = 'Q',\n\n LONG_STORAGE = 'X',\n\n TENSOR = 'T',\n\n STORAGE = 'S',\n\n GENERATOR = 'G',\n\n};\n\n\n", "file_path": "torch/lib/THD/base/RPCType.hpp", "rank": 27, "score": 252733.69499406932 }, { "content": "TH_API THLongStorage *THLongStorage_newInferSize(THLongStorage *size, ptrdiff_t nElement);\n", "file_path": "aten/src/TH/THStorageFunctions.h", "rank": 28, "score": 252733.5277264423 }, { "content": "\n\nstatic void storageGet(rpc::RPCMessage& raw_message) {\n\n at::Storage *storage = unpackRetrieveStorage(raw_message);\n\n ptrdiff_t offset = unpackInteger(raw_message);\n\n RPCType type = unpackType(raw_message);\n\n finalize(raw_message);\n\n if (isInteger(type)) {\n\n int64_t value = storage->get(offset).to<int64_t>();\n\n sendValueToMaster(value);\n\n } else if (isFloat(type)) {\n\n double value = storage->get(offset).to<double>();\n\n sendValueToMaster(value);\n\n } else {\n\n throw std::invalid_argument(\"expected scalar type\");\n\n }\n\n}\n\n\n\nstatic void storageNew(rpc::RPCMessage& raw_message) {\n\n RPCType storage_type = unpackType(raw_message);\n\n object_id_type storage_id = unpackStorage(raw_message);\n", "file_path": "torch/lib/THD/master_worker/worker/dispatch/Storage.cpp", "rank": 29, "score": 251812.03027300202 }, { "content": " finalize(raw_message);\n\n workerStorages.emplace(\n\n storage_id,\n\n createStorage(storage_type)\n\n );\n\n}\n\n\n\nstatic void storageNewWithSize(rpc::RPCMessage& raw_message) {\n\n RPCType storage_type = unpackType(raw_message);\n\n object_id_type storage_id = unpackStorage(raw_message);\n\n int64_t size = unpackInteger(raw_message);\n\n finalize(raw_message);\n\n workerStorages.emplace(\n\n storage_id,\n\n createStorage(storage_type, size)\n\n );\n\n}\n\n\n\nstatic void storageNewWithSizeN(rpc::RPCMessage& raw_message, size_t size) {\n\n RPCType storage_type = unpackType(raw_message);\n", "file_path": "torch/lib/THD/master_worker/worker/dispatch/Storage.cpp", "rank": 30, "score": 251803.2024013688 }, { "content": " storageNewWithSizeN(raw_message, 4);\n\n}\n\n\n\nstatic void storageFree(rpc::RPCMessage& raw_message) {\n\n object_id_type storage_id = unpackStorage(raw_message);\n\n finalize(raw_message);\n\n workerStorages.erase(storage_id);\n\n}\n\n\n\nstatic void storageResize(rpc::RPCMessage& raw_message) {\n\n at::Storage *storage = unpackRetrieveStorage(raw_message);\n\n int64_t new_size = unpackInteger(raw_message);\n\n finalize(raw_message);\n\n storage->resize(new_size);\n\n}\n\n\n\nstatic void storageFill(rpc::RPCMessage& raw_message) {\n\n at::Storage *storage = unpackRetrieveStorage(raw_message);\n\n RPCType type = peekType(raw_message);\n\n if (isInteger(type)) {\n", "file_path": "torch/lib/THD/master_worker/worker/dispatch/Storage.cpp", "rank": 31, "score": 251802.4672927947 }, { "content": " storage->resize(size);\n\n return storage;\n\n}\n\n\n\nstatic void storageSet(rpc::RPCMessage& raw_message) {\n\n at::Storage *storage = unpackRetrieveStorage(raw_message);\n\n ptrdiff_t offset = unpackInteger(raw_message);\n\n RPCType type = peekType(raw_message);\n\n if (isInteger(type)) {\n\n int64_t value = unpackInteger(raw_message);\n\n finalize(raw_message);\n\n storage->set(offset, value);\n\n } else if (isFloat(type)) {\n\n double value = unpackFloat(raw_message);\n\n finalize(raw_message);\n\n storage->set(offset, value);\n\n } else {\n\n throw std::invalid_argument(\"expected scalar type\");\n\n }\n\n}\n", "file_path": "torch/lib/THD/master_worker/worker/dispatch/Storage.cpp", "rank": 32, "score": 251801.63712883554 }, { "content": " finalize(raw_message);\n\n workerStorages.emplace(\n\n storage_id,\n\n std::move(storage)\n\n );\n\n}\n\n\n\nstatic void storageNewWithSize1(rpc::RPCMessage& raw_message) {\n\n storageNewWithSizeN(raw_message, 1);\n\n}\n\n\n\nstatic void storageNewWithSize2(rpc::RPCMessage& raw_message) {\n\n storageNewWithSizeN(raw_message, 2);\n\n}\n\n\n\nstatic void storageNewWithSize3(rpc::RPCMessage& raw_message) {\n\n storageNewWithSizeN(raw_message, 3);\n\n}\n\n\n\nstatic void storageNewWithSize4(rpc::RPCMessage& raw_message) {\n", "file_path": "torch/lib/THD/master_worker/worker/dispatch/Storage.cpp", "rank": 33, "score": 251799.8281159728 }, { "content": " object_id_type storage_id = unpackStorage(raw_message);\n\n std::unique_ptr<at::Storage> storage = createStorage(storage_type, size);\n\n RPCType value_type = peekType(raw_message);\n\n if (isInteger(value_type)) {\n\n int64_t values[size];\n\n for (size_t i = 0; i < size; i++)\n\n values[i] = unpackInteger(raw_message);\n\n finalize(raw_message);\n\n for (size_t i = 0; i < size; i++)\n\n storage->fast_set(i, values[i]);\n\n } else if (isFloat(value_type)) {\n\n double values[size];\n\n for (size_t i = 0; i < size; i++)\n\n values[i] = unpackInteger(raw_message);\n\n finalize(raw_message);\n\n for (size_t i = 0; i < size; i++)\n\n storage->fast_set(i, values[i]);\n\n } else {\n\n throw std::invalid_argument(\"expected scalar type\");\n\n }\n", "file_path": "torch/lib/THD/master_worker/worker/dispatch/Storage.cpp", "rank": 34, "score": 251790.24166135772 }, { "content": "static std::unique_ptr<at::Storage> createStorage(RPCType type) {\n\n if (type == RPCType::UCHAR)\n\n return at::getType(at::Backend::CPU, at::ScalarType::Byte).storage();\n\n else if (type == RPCType::CHAR)\n\n return at::getType(at::Backend::CPU, at::ScalarType::Char).storage();\n\n else if (type == RPCType::SHORT)\n\n return at::getType(at::Backend::CPU, at::ScalarType::Short).storage();\n\n else if (type == RPCType::INT)\n\n return at::getType(at::Backend::CPU, at::ScalarType::Int).storage();\n\n else if (type == RPCType::LONG)\n\n return at::getType(at::Backend::CPU, at::ScalarType::Long).storage();\n\n else if (type == RPCType::FLOAT)\n\n return at::getType(at::Backend::CPU, at::ScalarType::Float).storage();\n\n else if (type == RPCType::DOUBLE)\n\n return at::getType(at::Backend::CPU, at::ScalarType::Double).storage();\n\n throw std::invalid_argument(\"passed character doesn't represent a storage type\");\n\n}\n\n\n\nstatic std::unique_ptr<at::Storage> createStorage(RPCType type, size_t size) {\n\n std::unique_ptr<at::Storage> storage = createStorage(type);\n", "file_path": "torch/lib/THD/master_worker/worker/dispatch/Storage.cpp", "rank": 35, "score": 251788.73675442074 }, { "content": " int64_t val = unpackInteger(raw_message);\n\n finalize(raw_message);\n\n storage->fill(val);\n\n } else if (isFloat(type)) {\n\n double val = unpackFloat(raw_message);\n\n finalize(raw_message);\n\n storage->fill(val);\n\n } else {\n\n throw std::invalid_argument(\"expected scalar type\");\n\n }\n\n}\n", "file_path": "torch/lib/THD/master_worker/worker/dispatch/Storage.cpp", "rank": 36, "score": 251759.04295204298 }, { "content": "struct type_traits<std::conditional<std::is_same<int64_t, long>::value, long long, long>::type> {\n\n static constexpr RPCType type = std::is_same<int64_t, long>::value ? RPCType::LONG_LONG : RPCType::LONG;\n\n static constexpr bool is_floating_point = false;\n\n};\n\n\n\ntemplate<>\n", "file_path": "torch/lib/THD/base/RPCType.hpp", "rank": 37, "score": 251502.257943756 }, { "content": "struct type_traits<std::conditional<std::is_same<uint64_t, unsigned long>::value, unsigned long long, unsigned long>::type> {\n\n static constexpr RPCType type = std::is_same<uint64_t, unsigned long>::value ? RPCType::ULONG_LONG : RPCType::ULONG;\n\n static constexpr bool is_floating_point = false;\n\n};\n\n\n\ntemplate<typename T>\n", "file_path": "torch/lib/THD/base/RPCType.hpp", "rank": 38, "score": 238686.05501349107 }, { "content": "struct Storage;\n", "file_path": "aten/doc/Type.h", "rank": 39, "score": 212194.32763022598 }, { "content": "struct type_traits {};\n\n\n\n// NOTE: The `type` static constexpr variables of these specializations are\n\n// additionally defined in RPCType.cpp to avoid undefined\n\n// reference errors in C++11.\n\ntemplate<>\n", "file_path": "torch/lib/THD/base/RPCType.hpp", "rank": 40, "score": 204479.11829733735 }, { "content": "struct Storage;\n\n\n\nstatic inline void noop_deleter(void*) {}\n\n\n", "file_path": "aten/src/ATen/templates/Type.h", "rank": 41, "score": 202176.08754595084 }, { "content": "TH_API THDescBuff THLongStorage_sizeDesc(const THLongStorage *size);\n", "file_path": "aten/src/TH/THStorageFunctions.h", "rank": 42, "score": 201050.8019767144 }, { "content": "class RPCMessage {\n\npublic:\n\n using size_type = ByteArray::size_type;\n\n RPCMessage();\n\n RPCMessage(char* str, size_t size);\n\n RPCMessage(const ByteArray& str);\n\n RPCMessage(ByteArray&& str);\n\n\n\n ByteArray& bytes(); // Raw data.\n\n const char* data() const; // Offset data.\n\n bool isEmpty() const;\n\n size_type remaining() const; // Length of the msg left to read.\n\n const char* read(size_t num_bytes);\n\n\n\nprivate:\n\n ByteArray _msg;\n\n size_t _offset;\n\n};\n\n\n\ntemplate <typename ...Args>\n", "file_path": "torch/lib/THD/master_worker/common/RPC.hpp", "rank": 43, "score": 200799.45366439354 }, { "content": "struct type_traits<uint8_t> {\n\n static constexpr RPCType type = RPCType::UCHAR;\n\n static constexpr bool is_floating_point = false;\n\n};\n\n\n\ntemplate<>\n", "file_path": "torch/lib/THD/base/RPCType.hpp", "rank": 44, "score": 200695.54572435212 }, { "content": "struct type_traits<int32_t> {\n\n static constexpr RPCType type = RPCType::INT;\n\n static constexpr bool is_floating_point = false;\n\n};\n\n\n\ntemplate<>\n", "file_path": "torch/lib/THD/base/RPCType.hpp", "rank": 45, "score": 200695.54572435212 }, { "content": "struct type_traits<uint32_t> {\n\n static constexpr RPCType type = RPCType::UINT;\n\n static constexpr bool is_floating_point = false;\n\n};\n\n\n\ntemplate<>\n", "file_path": "torch/lib/THD/base/RPCType.hpp", "rank": 46, "score": 200695.54572435212 }, { "content": "struct type_traits<int8_t> {\n\n static constexpr RPCType type = RPCType::CHAR;\n\n static constexpr bool is_floating_point = false;\n\n};\n\n\n\ntemplate<>\n", "file_path": "torch/lib/THD/base/RPCType.hpp", "rank": 47, "score": 200695.54572435212 }, { "content": "struct type_traits<uint64_t> {\n\n static constexpr RPCType type = std::is_same<uint64_t, unsigned long>::value ? RPCType::ULONG : RPCType::ULONG_LONG;\n\n static constexpr bool is_floating_point = false;\n\n};\n\n\n\ntemplate<>\n", "file_path": "torch/lib/THD/base/RPCType.hpp", "rank": 48, "score": 200695.54572435212 }, { "content": "struct type_traits<uint16_t> {\n\n static constexpr RPCType type = RPCType::USHORT;\n\n static constexpr bool is_floating_point = false;\n\n};\n\n\n\ntemplate<>\n", "file_path": "torch/lib/THD/base/RPCType.hpp", "rank": 49, "score": 200695.54572435212 }, { "content": "struct type_traits<double> {\n\n static constexpr RPCType type = RPCType::DOUBLE;\n\n static constexpr bool is_floating_point = true;\n\n};\n\n\n\ntemplate<>\n", "file_path": "torch/lib/THD/base/RPCType.hpp", "rank": 50, "score": 200695.54572435212 }, { "content": "struct type_traits<float> {\n\n static constexpr RPCType type = RPCType::FLOAT;\n\n static constexpr bool is_floating_point = true;\n\n};\n\n\n\ntemplate<>\n", "file_path": "torch/lib/THD/base/RPCType.hpp", "rank": 51, "score": 200695.54572435212 }, { "content": "struct type_traits<int16_t> {\n\n static constexpr RPCType type = RPCType::SHORT;\n\n static constexpr bool is_floating_point = false;\n\n};\n\n\n\ntemplate<>\n", "file_path": "torch/lib/THD/base/RPCType.hpp", "rank": 52, "score": 200695.54572435212 }, { "content": "struct type_traits<int64_t> {\n\n static constexpr RPCType type = std::is_same<int64_t, long>::value ? RPCType::LONG : RPCType::LONG_LONG;\n\n static constexpr bool is_floating_point = false;\n\n};\n\n\n\ntemplate<>\n", "file_path": "torch/lib/THD/base/RPCType.hpp", "rank": 53, "score": 200695.54572435212 }, { "content": "struct type_traits<char> {\n\n static constexpr RPCType type = RPCType::CHAR;\n\n static constexpr bool is_floating_point = false;\n\n};\n\n\n\ntemplate<>\n", "file_path": "torch/lib/THD/base/RPCType.hpp", "rank": 54, "score": 200695.54572435212 }, { "content": "#include \"RPCType.hpp\"\n\n\n\nnamespace thd {\n\n\n\n// Static constexpr variables have to be defined out-of-source in C++11.\n\n// https://stackoverflow.com/questions/8016780/undefined-reference-to-static-constexpr-char\n\nconstexpr RPCType type_traits<char>::type;\n\nconstexpr RPCType type_traits<int8_t>::type;\n\nconstexpr RPCType type_traits<uint8_t>::type;\n\nconstexpr RPCType type_traits<float>::type;\n\nconstexpr RPCType type_traits<double>::type;\n\nconstexpr RPCType type_traits<int16_t>::type;\n\nconstexpr RPCType type_traits<int32_t>::type;\n\nconstexpr RPCType type_traits<uint32_t>::type;\n\nconstexpr RPCType type_traits<uint16_t>::type;\n\nconstexpr RPCType type_traits<int64_t>::type;\n\nconstexpr RPCType type_traits<uint64_t>::type;\n\nconstexpr RPCType type_traits<std::conditional<std::is_same<int64_t, long>::value, long long, long>::type>::type;\n\nconstexpr RPCType type_traits<std::conditional<std::is_same<uint64_t, unsigned long>::value, unsigned long long, unsigned long>::type>::type;\n\n\n\n} // thd\n", "file_path": "torch/lib/THD/base/RPCType.cpp", "rank": 55, "score": 197485.30806015592 }, { "content": " case RPCType::USHORT: return \"UShort\";\n\n case RPCType::INT: return \"Int\";\n\n case RPCType::UINT: return \"UInt\";\n\n case RPCType::LONG: return \"Long\";\n\n case RPCType::ULONG: return \"ULong\";\n\n case RPCType::LONG_LONG: return \"LongLong\";\n\n case RPCType::ULONG_LONG: return \"ULongLong\";\n\n case RPCType::LONG_STORAGE: return \"LongStorage\";\n\n case RPCType::TENSOR: return \"Tensor\";\n\n case RPCType::STORAGE: return \"Storage\";\n\n default: return \"<unknown>\";\n\n }\n\n}\n\n\n\ninline bool isObject(RPCType t) {\n\n return (t == RPCType::TENSOR || t == RPCType::STORAGE || t == RPCType::GENERATOR);\n\n}\n\n\n\ntemplate<typename T>\n", "file_path": "torch/lib/THD/base/RPCType.hpp", "rank": 56, "score": 197482.27756844458 }, { "content": "inline bool isFloat(RPCType t) {\n\n return (t == RPCType::FLOAT || t == RPCType::DOUBLE || t == RPCType::HALF);\n\n}\n\n\n\ninline bool isInteger(RPCType t) {\n\n return (t == RPCType::CHAR || t == RPCType::UCHAR ||\n\n t == RPCType::SHORT || t == RPCType:: USHORT ||\n\n t == RPCType::INT || t == RPCType::UINT ||\n\n t == RPCType::LONG || t == RPCType::ULONG ||\n\n t == RPCType::LONG_LONG || t == RPCType::ULONG_LONG);\n\n}\n\n\n\ninline const char* toString(RPCType t) {\n\n switch (t) {\n\n case RPCType::CHAR: return \"Char\";\n\n case RPCType::UCHAR: return \"Byte\";\n\n case RPCType::FLOAT: return \"Float\";\n\n case RPCType::DOUBLE: return \"Double\";\n\n case RPCType::HALF: return \"Half\";\n\n case RPCType::SHORT: return \"Short\";\n", "file_path": "torch/lib/THD/base/RPCType.hpp", "rank": 57, "score": 197467.6405406036 }, { "content": "#pragma once\n\n\n\n#include <type_traits>\n\n#include <tuple>\n\n#include <cstddef>\n\n#include <cstdint>\n\n#include <unordered_map>\n\n\n\nnamespace thd {\n\n\n\n/*\n\n * The following notation comes from:\n\n * docs.python.org/3.5/library/struct.html#module-struct\n\n * except from 'T', which stands for Tensor\n\n */\n\n\n", "file_path": "torch/lib/THD/base/RPCType.hpp", "rank": 58, "score": 197461.1335067771 }, { "content": "struct type_traits<const T> : type_traits<T> {};\n\n\n\n} // thd\n", "file_path": "torch/lib/THD/base/RPCType.hpp", "rank": 59, "score": 195043.83458074275 }, { "content": "#define THD_REAL_IS_BYTE\n", "file_path": "torch/lib/THD/base/THDGenerateAllTypes.h", "rank": 60, "score": 195035.98403761207 }, { "content": "#define THD_REAL_IS_INT\n", "file_path": "torch/lib/THD/base/THDGenerateAllTypes.h", "rank": 61, "score": 195035.98403761204 }, { "content": "#define THD_REAL_IS_FLOAT\n", "file_path": "torch/lib/THD/base/THDGenerateAllTypes.h", "rank": 62, "score": 195035.98403761204 }, { "content": "#define THD_REAL_IS_CHAR\n", "file_path": "torch/lib/THD/base/THDGenerateAllTypes.h", "rank": 63, "score": 195035.98403761204 }, { "content": "#define THD_REAL_IS_DOUBLE\n", "file_path": "torch/lib/THD/base/THDGenerateAllTypes.h", "rank": 64, "score": 195035.98403761207 }, { "content": "#define THD_REAL_IS_LONG\n", "file_path": "torch/lib/THD/base/THDGenerateAllTypes.h", "rank": 65, "score": 195035.98403761207 }, { "content": "#define THD_REAL_IS_SHORT\n", "file_path": "torch/lib/THD/base/THDGenerateAllTypes.h", "rank": 66, "score": 195035.98403761207 }, { "content": "#pragma once\n\n#include \"../master/THDTensor.h\"\n\n#include \"ByteArray.hpp\"\n\n#include \"TH/THStorageFunctions.h\"\n\n#include \"RPCType.hpp\"\n\n\n\n#include <cstdint>\n\n#include <memory>\n\n#include <string>\n\n\n\nnamespace thd {\n\n\n\nusing object_id_type = uint64_t;\n\n\n\nnamespace rpc {\n\n\n\nusing function_id_type = uint16_t;\n\n\n", "file_path": "torch/lib/THD/master_worker/common/RPC.hpp", "rank": 67, "score": 193123.15528946035 }, { "content": " ptrdiff_t size = unpackScalar<ptrdiff_t>(raw_message);\n\n THLongStorage* storage = THLongStorage_newWithSize(size);\n\n int64_t* data = THLongStorage_data(storage);\n\n\n\n try {\n\n for (int i = 0; i < size; i++) {\n\n data[i] = unpackScalar<int64_t>(raw_message);\n\n }\n\n } catch (std::exception& e) {\n\n THLongStorage_free(storage);\n\n throw;\n\n }\n\n\n\n return storage;\n\n}\n\n\n\n}} // namespace rpc, thd\n", "file_path": "torch/lib/THD/master_worker/common/RPC.cpp", "rank": 68, "score": 193117.6698074328 }, { "content": "std::unique_ptr<RPCMessage> packMessage(function_id_type fid, const Args&... args);\n\n\n\nRPCType unpackType(RPCMessage& raw_message);\n\nRPCType peekType(RPCMessage& raw_message);\n\ndouble unpackFloat(RPCMessage& raw_message);\n\nfunction_id_type unpackFunctionId(RPCMessage& raw_message);\n\nint64_t unpackInteger(RPCMessage& raw_message);\n\nobject_id_type unpackGenerator(RPCMessage& raw_message);\n\nobject_id_type unpackTensor(RPCMessage& raw_message);\n\nobject_id_type unpackStorage(RPCMessage& raw_message);\n\nTHLongStorage* unpackTHLongStorage(RPCMessage& raw_message);\n\n\n\n}} // namespace rpc, thd\n\n\n\n#include \"RPC-inl.hpp\"\n", "file_path": "torch/lib/THD/master_worker/common/RPC.hpp", "rank": 69, "score": 193108.98669537783 }, { "content": "#include \"RPC.hpp\"\n\n#include \"ByteArray.hpp\"\n\n\n\n#include <cstdarg>\n\n#include <cstring>\n\n#include <iostream>\n\n#include <memory>\n\n#include <stdexcept>\n\n\n\nnamespace thd {\n\nnamespace rpc {\n\n\n\nRPCMessage::RPCMessage()\n\n : _msg(0)\n\n , _offset(0)\n\n{}\n\n\n\nRPCMessage::RPCMessage(char* str, size_t size)\n\n : _msg(str, size)\n\n , _offset(0)\n", "file_path": "torch/lib/THD/master_worker/common/RPC.cpp", "rank": 70, "score": 193106.90779052826 }, { "content": "template<typename T>\n\ninline T unpackScalar(RPCMessage& raw_message) {\n\n return *reinterpret_cast<const T*>(raw_message.read(sizeof(T)));\n\n}\n\n\n\n} // namespace\n\n\n\n////////////////////////////////////////////////////////////////////////////////\n\n\n\nstatic_assert(sizeof(RPCType) == sizeof(char), \"RPCType has to be of the \"\n\n \"same size as char\");\n\nRPCType unpackType(RPCMessage& raw_message) {\n\n char _type = *raw_message.read(sizeof(RPCType));\n\n return static_cast<RPCType>(_type);\n\n}\n\n\n\nRPCType peekType(RPCMessage& raw_message) {\n\n char _type = *raw_message.data();\n\n return static_cast<RPCType>(_type);\n\n}\n", "file_path": "torch/lib/THD/master_worker/common/RPC.cpp", "rank": 71, "score": 193104.59465228204 }, { "content": "bool RPCMessage::isEmpty() const {\n\n return _offset >= _msg.length();\n\n}\n\n\n\nRPCMessage::size_type RPCMessage::remaining() const {\n\n return _msg.length() - _offset;\n\n}\n\n\n\nconst char* RPCMessage::read(size_t num_bytes) {\n\n if (_offset + num_bytes > _msg.length())\n\n throw std::out_of_range(\"invalid access: out of bounds\");\n\n const char* ret_val = _msg.data() + _offset;\n\n _offset += num_bytes;\n\n return ret_val;\n\n}\n\n\n\n////////////////////////////////////////////////////////////////////////////////\n\n\n\nnamespace {\n\n\n", "file_path": "torch/lib/THD/master_worker/common/RPC.cpp", "rank": 72, "score": 193104.44526802376 }, { "content": " RPCType type = unpackType(raw_message);\n\n if (type == RPCType::STORAGE)\n\n return unpackScalar<object_id_type>(raw_message);\n\n throw std::invalid_argument(\"expected storage in the raw message\");\n\n}\n\n\n\nobject_id_type unpackGenerator(RPCMessage& raw_message) {\n\n RPCType type = unpackType(raw_message);\n\n if (type == RPCType::GENERATOR) {\n\n return unpackScalar<object_id_type>(raw_message);\n\n }\n\n throw std::invalid_argument(\"expected generator in the raw message\");\n\n}\n\n\n\nTHLongStorage* unpackTHLongStorage(RPCMessage& raw_message) {\n\n RPCType type = unpackType(raw_message);\n\n if (type != RPCType::LONG_STORAGE)\n\n throw std::invalid_argument(\"expected THLongStorage in the raw message\");\n\n char is_null = unpackScalar<char>(raw_message);\n\n if (is_null) return NULL;\n", "file_path": "torch/lib/THD/master_worker/common/RPC.cpp", "rank": 73, "score": 193104.235948558 }, { "content": " return unpackScalar<int16_t>(raw_message);\n\n else if (type == RPCType::INT)\n\n return unpackScalar<int32_t>(raw_message);\n\n else if (type == RPCType::LONG)\n\n return unpackScalar<int64_t>(raw_message);\n\n else if (type == RPCType::LONG_LONG)\n\n return unpackScalar<int64_t>(raw_message);\n\n\n\n throw std::invalid_argument(std::string(\"wrong integer type in the raw message (\") +\n\n std::to_string(static_cast<char>(type)) + \")\");\n\n}\n\n\n\nobject_id_type unpackTensor(RPCMessage& raw_message) {\n\n RPCType type = unpackType(raw_message);\n\n if (type == RPCType::TENSOR)\n\n return unpackScalar<object_id_type>(raw_message);\n\n throw std::invalid_argument(\"expected tensor in the raw message\");\n\n}\n\n\n\nobject_id_type unpackStorage(RPCMessage& raw_message) {\n", "file_path": "torch/lib/THD/master_worker/common/RPC.cpp", "rank": 74, "score": 193100.31973981828 }, { "content": "\n\nfunction_id_type unpackFunctionId(RPCMessage& raw_message) {\n\n return unpackScalar<function_id_type>(raw_message);\n\n}\n\n\n\ndouble unpackFloat(RPCMessage& raw_message) {\n\n RPCType type = unpackType(raw_message);\n\n if (type == RPCType::DOUBLE)\n\n return unpackScalar<double>(raw_message);\n\n else if (type == RPCType::FLOAT)\n\n return unpackScalar<float>(raw_message);\n\n\n\n throw std::invalid_argument(\"wrong real type in the raw message\");\n\n}\n\n\n\nint64_t unpackInteger(RPCMessage& raw_message) {\n\n RPCType type = unpackType(raw_message);\n\n if (type == RPCType::CHAR)\n\n return unpackScalar<int8_t>(raw_message);\n\n else if (type == RPCType::SHORT)\n", "file_path": "torch/lib/THD/master_worker/common/RPC.cpp", "rank": 75, "score": 193093.16203664796 }, { "content": "{}\n\n\n\nRPCMessage::RPCMessage(const ByteArray& str)\n\n : _msg(str)\n\n , _offset(0)\n\n{}\n\n\n\nRPCMessage::RPCMessage(ByteArray&& str)\n\n : _msg(std::move(str))\n\n , _offset(0)\n\n{}\n\n\n\nByteArray& RPCMessage::bytes() {\n\n return _msg;\n\n}\n\n\n\nconst char* RPCMessage::data() const {\n\n return _msg.data() + _offset;\n\n}\n\n\n", "file_path": "torch/lib/THD/master_worker/common/RPC.cpp", "rank": 76, "score": 193088.5837208803 }, { "content": "struct CTypeToScalarType<__half> : public CTypeToScalarType<Half> {};\n\n\n\n}\n\n\n\nTHC_API THCStorage* THCStorage_new(THCState* state, at::ScalarType);\n\n\n\nTHC_API void THCStorage_retain(THCState *state, THCStorage *storage);\n\n\n\nTHC_API void THCStorage_resize(THCState *state, THCStorage *storage, ptrdiff_t size);\n\nTHC_API int THCStorage_getDevice(THCState* state, const THCStorage* storage);\n\n\n\nTHC_API THCStorage* THCStorage_newWithDataAndAllocator(\n\n THCState *state, at::ScalarType scalar_type,\n\n at::DataPtr&& data, ptrdiff_t size,\n\n at::Allocator* allocator);\n", "file_path": "aten/src/THC/THCStorage.hpp", "rank": 77, "score": 191578.086288464 }, { "content": " def _new_shared(cls, size):\n\n \"\"\"Creates a new storage in shared memory with the same data type\"\"\"\n\n from torch.multiprocessing import get_sharing_strategy\n\n if cls.is_cuda:\n\n return cls(size)\n\n elif get_sharing_strategy() == 'file_system':\n\n return cls._new_using_filename(size)\n\n else:\n", "file_path": "torch/storage.py", "rank": 78, "score": 188954.66368642848 }, { "content": " int64_t storage_offset() const;\n", "file_path": "aten/doc/Tensor.h", "rank": 79, "score": 188933.99541038775 }, { "content": "#include <cstdint>\n\n#include \"TH/THStorageFunctions.h\"\n\n#include \"Traits.hpp\"\n\n\n\nnamespace thd { namespace rpc { namespace detail {\n\n////////////////////////////////////////////////////////////////////////////////\n\n\n\nconstexpr size_t INITIAL_BUFFER_SIZE = 256;\n\n\n\ntemplate<typename real,\n\n typename = typename std::enable_if<std::is_arithmetic<real>::value>::type>\n\ninline void _appendScalar(ByteArray& str, real data) {\n\n str.append(reinterpret_cast<char*>(&data), sizeof(data));\n\n}\n\n\n\ninline void _appendType(ByteArray& str, RPCType _type) {\n\n char type = static_cast<char>(_type);\n\n str.append(&type, sizeof(type));\n\n}\n\n\n", "file_path": "torch/lib/THD/master_worker/common/RPC-inl.hpp", "rank": 80, "score": 188875.97395224124 }, { "content": " _appendType(str, RPCType::LONG_STORAGE);\n\n _appendScalar<char>(str, arg == NULL);\n\n if (!arg) return;\n\n _appendScalar<ptrdiff_t>(str, THLongStorage_size(arg));\n\n for (ptrdiff_t i = 0; i < THLongStorage_size(arg); i++)\n\n _appendScalar<int64_t>(str, THLongStorage_get(arg, i));\n\n}\n\n\n\ntemplate<typename T>\n\ninline void _appendData(ByteArray& str, const std::vector<T>& arg) {\n\n int l = arg.size();\n\n _appendData(str, l);\n\n for (size_t i = 0; i < l; i++)\n\n __appendData(\n\n str,\n\n arg[i],\n\n is_any_of<T, THDGeneratorPtrTypes>(),\n\n is_any_of<T, THDTensorPtrTypes>(),\n\n is_any_of<T, THDStoragePtrTypes>()\n\n );\n", "file_path": "torch/lib/THD/master_worker/common/RPC-inl.hpp", "rank": 81, "score": 188860.15081910603 }, { "content": "\n\ntemplate<typename T>\n\ninline void __appendData(ByteArray& str, const T& arg,\n\n std::false_type is_generator, std::false_type is_tensor, std::true_type is_storage) {\n\n _appendType(str, RPCType::STORAGE);\n\n _appendScalar<object_id_type>(str, arg->storage_id);\n\n}\n\n\n\ntemplate<typename T>\n\ninline void _appendData(ByteArray& str, const T& arg) {\n\n __appendData(\n\n str,\n\n arg,\n\n is_any_of<T, THDGeneratorPtrTypes>(),\n\n is_any_of<T, THDTensorPtrTypes>(),\n\n is_any_of<T, THDStoragePtrTypes>()\n\n );\n\n}\n\n\n\ninline void _appendData(ByteArray& str, THLongStorage* arg) {\n", "file_path": "torch/lib/THD/master_worker/common/RPC-inl.hpp", "rank": 82, "score": 188856.37879359708 }, { "content": " const Args&... args\n\n) {\n\n ByteArray msg(detail::INITIAL_BUFFER_SIZE);\n\n detail::_appendScalar<function_id_type>(msg, fid);\n\n detail::_packIntoString(msg, args...);\n\n return std::unique_ptr<RPCMessage>(new RPCMessage(std::move(msg)));\n\n}\n\n\n\n}} // namespace rpc, thd\n", "file_path": "torch/lib/THD/master_worker/common/RPC-inl.hpp", "rank": 83, "score": 188850.32849520055 }, { "content": "template<typename T>\n\ninline void __appendData(ByteArray& str, const T& arg,\n\n std::false_type is_generator, std::false_type is_tensor, std::false_type is_storage) {\n\n _appendType(str, type_traits<T>::type);\n\n _appendScalar<T>(str, arg);\n\n}\n\n\n\ntemplate<typename T>\n\ninline void __appendData(ByteArray& str, const T& arg,\n\n std::true_type is_generator, std::false_type is_tensor, std::false_type is_storage) {\n\n _appendType(str, RPCType::GENERATOR);\n\n _appendScalar<object_id_type>(str, arg->generator_id);\n\n}\n\n\n\ntemplate<typename T>\n\ninline void __appendData(ByteArray& str, const T& arg,\n\n std::false_type is_generator, std::true_type is_tensor, std::false_type is_storage) {\n\n _appendType(str, RPCType::TENSOR);\n\n _appendScalar<object_id_type>(str, arg->tensor_id);\n\n}\n", "file_path": "torch/lib/THD/master_worker/common/RPC-inl.hpp", "rank": 84, "score": 188847.44451029613 }, { "content": "}\n\n\n\ninline void _appendData(ByteArray& str, RPCType type) {\n\n _appendType(str, type);\n\n}\n\n\n\ninline void _packIntoString(ByteArray& str) {};\n\n\n\ntemplate <typename T, typename ...Args>\n\ninline void _packIntoString(ByteArray& str, const T& arg, const Args&... args) {\n\n _appendData(str, arg);\n\n _packIntoString(str, args...);\n\n}\n\n\n\n////////////////////////////////////////////////////////////////////////////////\n\n} // namespace detail\n\n\n\ntemplate <typename ...Args>\n\ninline std::unique_ptr<RPCMessage> packMessage(\n\n function_id_type fid,\n", "file_path": "torch/lib/THD/master_worker/common/RPC-inl.hpp", "rank": 85, "score": 188840.5146320499 }, { "content": "class StorageType {\n\n public:\n\n StorageType(T&& data) : Data(std::move(data)) {}\n\n StorageType(const T& data) = delete;\n\n StorageType() {}\n\n\n\n const T& data() const {\n\n return Data;\n\n }\n\n T* mutableData() {\n\n return &Data;\n\n }\n\n void resetData(T&& data) {\n\n Data = std::move(data);\n\n }\n\n\n\n private:\n\n T Data;\n\n};\n\n\n\ntemplate <>\n", "file_path": "caffe2/core/nomnigraph/include/nomnigraph/Support/Common.h", "rank": 86, "score": 188805.12412032872 }, { "content": "class StorageType<> {};\n\n\n\n/// \\brief This class enables a listener pattern.\n\n/// It is to be used with a \"curious recursive pattern\"\n\n/// i.e. Derived : public Notifier<Derived> {}\n\ntemplate <typename T>\n", "file_path": "caffe2/core/nomnigraph/include/nomnigraph/Support/Common.h", "rank": 87, "score": 188805.12412032872 }, { "content": "THDTensor *THDTensor_(newWithStorage)(THDStorage *storage, ptrdiff_t storageOffset,\n\n THLongStorage *size, THLongStorage *stride) {\n\n THDTensor* tensor = THDTensor_(_alloc)();\n\n THDTensor_(_set)(\n\n tensor,\n\n storage,\n\n storageOffset,\n\n (size ? THLongStorage_size(size) : (stride ? THLongStorage_size(stride) : 0)),\n\n (size ? THLongStorage_data(size) : nullptr),\n\n (stride ? THLongStorage_data(stride) : nullptr)\n\n );\n\n RPCType constructed_type = type_traits<real>::type;\n\n masterCommandChannel->sendMessage(\n\n packMessage(\n\n Functions::tensorNewWithStorage,\n\n constructed_type,\n\n storage,\n\n storageOffset,\n\n size,\n\n stride\n", "file_path": "torch/lib/THD/master_worker/master/generic/THDTensor.cpp", "rank": 88, "score": 63.710869715371174 }, { "content": "\n\nTHLongStorage *THDTensor_(newStrideOf)(THDTensor *self) {\n\n THLongStorage *stride = THLongStorage_newWithSize(self->nDimension);\n\n THLongStorage_rawCopy(stride, self->stride);\n\n return stride;\n\n}\n\n\n\nvoid THDTensor_(setFlag)(THDTensor *self, char flag) {\n\n self->flag |= flag;\n\n}\n\n\n\nvoid THDTensor_(clearFlag)(THDTensor *self, char flag) {\n\n self->flag &= ~flag;\n\n}\n\n\n\nTHDTensor *THDTensor_(new)() {\n\n THDTensor *tensor = THDTensor_(_alloc)();\n\n RPCType constructed_type = type_traits<real>::type;\n\n masterCommandChannel->sendMessage(\n\n packMessage(\n", "file_path": "torch/lib/THD/master_worker/master/generic/THDTensor.cpp", "rank": 89, "score": 57.81685037070243 }, { "content": "#include <cassert>\n\n#include <climits>\n\n#include <cstdint>\n\n#include <iostream>\n\n#include <typeinfo>\n\n#include <vector>\n\n\n\n#include <THPP/Type.hpp>\n\n\n\n#include \"../master_worker/common/RPC.hpp\"\n\n#include \"TH/THStorageFunctions.h\"\n\n\n\nusing namespace std;\n\nusing namespace thd;\n\nusing namespace thd::rpc;\n\n\n\nconstexpr ptrdiff_t STORAGE_SIZE = 10;\n\nconstexpr size_t VEC_SIZE = 3;\n\n\n\nint main() {\n", "file_path": "torch/lib/THD/test/rpc_serialization.cpp", "rank": 90, "score": 57.675924582847095 }, { "content": " Functions::tensorNew,\n\n constructed_type,\n\n tensor\n\n ),\n\n THDState::s_current_worker\n\n );\n\n return tensor;\n\n}\n\n\n\nTHDTensor *THDTensor_(newWithTensor)(THDTensor *self) {\n\n THDTensor *tensor = THDTensor_(_alloc)();\n\n THDTensor_(_set)(\n\n tensor,\n\n self->storage,\n\n self->storageOffset,\n\n self->nDimension,\n\n self->size,\n\n self->stride\n\n );\n\n RPCType constructed_type = type_traits<real>::type;\n", "file_path": "torch/lib/THD/master_worker/master/generic/THDTensor.cpp", "rank": 91, "score": 56.771124459907064 }, { "content": " masterCommandChannel->sendMessage(\n\n packMessage(\n\n Functions::tensorNewWithTensor,\n\n constructed_type,\n\n tensor,\n\n self\n\n ),\n\n THDState::s_current_worker\n\n );\n\n return tensor;\n\n}\n\n\n\nTHDTensor *THDTensor_(newWithSize)(THLongStorage *size, THLongStorage *stride) {\n\n THDTensor* tensor = THDTensor_(_alloc)();\n\n if (size && stride)\n\n THArgCheck(THLongStorage_size(size) == THLongStorage_size(stride), 4, \"inconsistent size\");\n\n THDTensor_(_resize)(tensor, THLongStorage_size(size), THLongStorage_data(size), stride ? THLongStorage_data(stride) : nullptr);\n\n RPCType constructed_type = type_traits<real>::type;\n\n masterCommandChannel->sendMessage(\n\n packMessage(\n", "file_path": "torch/lib/THD/master_worker/master/generic/THDTensor.cpp", "rank": 92, "score": 56.338095175799324 }, { "content": " }\n\n }\n\n\n\n /* storageOffset */\n\n if (storageOffset < 0)\n\n THError(\"can't set negative storage offset\");\n\n self->storageOffset = storageOffset;\n\n\n\n /* size and stride */\n\n THDTensor_(_resize)(self, nDimension, size, stride);\n\n}\n\n\n\nstatic THDTensor *THDTensor_(_alloc)() {\n\n THDTensor *new_tensor = new THDTensor();\n\n std::memset(reinterpret_cast<void*>(new_tensor), 0, sizeof(THDTensor));\n\n new_tensor->size = nullptr;\n\n new_tensor->stride = nullptr;\n\n new_tensor->nDimension = 0;\n\n\n\n new_tensor->storage = nullptr;\n", "file_path": "torch/lib/THD/master_worker/master/generic/THDTensorMeta.cpp", "rank": 93, "score": 56.31813910764826 }, { "content": "THStorage* THStorage_(newWithDataAndAllocator)(at::DataPtr&& data, ptrdiff_t size,\n\n at::Allocator* allocator) {\n\n THStorage* storage = new THStorage(\n\n at::CTypeToScalarType<th::from_type<real>>::to(),\n\n size,\n\n std::move(data),\n\n allocator,\n\n true);\n\n return storage;\n\n}\n\n\n\nvoid THStorage_(resize)(THStorage *storage, ptrdiff_t size)\n\n{\n\n return THStorage_resize(storage, size);\n\n}\n\n\n\nvoid THStorage_(fill)(THStorage *storage, real value)\n\n{\n\n ptrdiff_t i;\n\n for(i = 0; i < storage->size; i++)\n", "file_path": "aten/src/TH/generic/THStorage.cpp", "rank": 94, "score": 55.49485152261595 }, { "content": "}\n\n\n\nstatic void tensorNewWithStorage(rpc::RPCMessage& raw_message) {\n\n RPCType type = unpackType(raw_message);\n\n thd::object_id_type id = unpackTensor(raw_message);\n\n at::Storage *storage = unpackRetrieveStorage(raw_message);\n\n ptrdiff_t storageOffset = unpackInteger(raw_message);\n\n THLongStorage *size = unpackTHLongStorage(raw_message);\n\n THLongStorage *stride = unpackTHLongStorage(raw_message);\n\n finalize(raw_message);\n\n\n\n at::IntList sz(THLongStorage_data(size), THLongStorage_size(size));\n\n at::IntList str(THLongStorage_data(stride), THLongStorage_size(stride));\n\n workerTensors.emplace(\n\n id,\n\n createTensorWithStorage(type, storage, storageOffset, sz, str)\n\n );\n\n THLongStorage_free(size);\n\n THLongStorage_free(stride);\n\n}\n", "file_path": "torch/lib/THD/master_worker/worker/dispatch/Tensor.cpp", "rank": 95, "score": 55.32326919578772 }, { "content": " if (type == RPCType::UCHAR)\n\n return at::CPU(at::kByte).tensor(*storage, storageOffset, size, stride);\n\n else if (type == RPCType::CHAR)\n\n return at::CPU(at::kChar).tensor(*storage, storageOffset, size, stride);\n\n else if (type == RPCType::SHORT)\n\n return at::CPU(at::kShort).tensor(*storage, storageOffset, size, stride);\n\n else if (type == RPCType::INT)\n\n return at::CPU(at::kInt).tensor(*storage, storageOffset, size, stride);\n\n else if (type == RPCType::LONG)\n\n return at::CPU(at::kLong).tensor(*storage, storageOffset, size, stride);\n\n else if (type == RPCType::FLOAT)\n\n return at::CPU(at::kFloat).tensor(*storage, storageOffset, size, stride);\n\n else if (type == RPCType::DOUBLE)\n\n return at::CPU(at::kDouble).tensor(*storage, storageOffset, size, stride);\n\n throw std::invalid_argument(\"passed character doesn't represent a tensor type\");\n\n}\n\n\n\nstatic at::Tensor createTensorWithTensor(RPCType type, at::Tensor& tensor) {\n\n if (type == RPCType::UCHAR)\n\n return at::CPU(at::kByte).alias(tensor);\n", "file_path": "torch/lib/THD/master_worker/worker/dispatch/Tensor.cpp", "rank": 96, "score": 52.394007298444535 }, { "content": "\n\nTHStorage* THStorage_(new)(void)\n\n{\n\n THStorage* storage = new THStorage(\n\n at::CTypeToScalarType<th::from_type<real>>::to(),\n\n 0,\n\n getTHDefaultAllocator(),\n\n true);\n\n return storage;\n\n}\n\n\n\nTHStorage* THStorage_(newWithSize)(ptrdiff_t size)\n\n{\n\n THStorage* storage = new THStorage(\n\n at::CTypeToScalarType<th::from_type<real>>::to(),\n\n size,\n\n getTHDefaultAllocator(),\n\n true);\n\n return storage;\n\n}\n", "file_path": "aten/src/TH/generic/THStorage.cpp", "rank": 97, "score": 51.72413802844159 }, { "content": " id,\n\n createTensor(type)\n\n );\n\n}\n\n\n\nstatic void tensorNewWithSize(rpc::RPCMessage& raw_message) {\n\n RPCType type = unpackType(raw_message);\n\n thd::object_id_type id = unpackTensor(raw_message);\n\n THLongStorage *size = unpackTHLongStorage(raw_message);\n\n THLongStorage *stride = unpackTHLongStorage(raw_message);\n\n finalize(raw_message);\n\n\n\n at::IntList sz(THLongStorage_data(size), THLongStorage_size(size));\n\n at::IntList str(THLongStorage_data(stride), THLongStorage_size(stride));\n\n workerTensors.emplace(\n\n id,\n\n createTensor(type, sz, str)\n\n );\n\n THLongStorage_free(size);\n\n THLongStorage_free(stride);\n", "file_path": "torch/lib/THD/master_worker/worker/dispatch/Tensor.cpp", "rank": 98, "score": 51.43876906921836 }, { "content": "#include <ATen/Storage.h>\n\n#include <iostream>\n\n\n\nnamespace at {\n\n\n\nStorage::Storage(at::ScalarType scalar_type, size_t size, Allocator* allocator)\n\n : storage_impl_(new StorageImpl(\n\n scalar_type,\n\n size,\n\n allocator,\n\n /* resizable */ false)) {}\n\n\n\nStorage::Storage(\n\n at::ScalarType scalar_type,\n\n at::DataPtr data_ptr,\n\n size_t size,\n\n const std::function<void(void*)>& deleter)\n\n : storage_impl_(new StorageImpl(\n\n scalar_type,\n\n size,\n", "file_path": "aten/src/ATen/Storage.cpp", "rank": 99, "score": 51.01535176395607 } ]
C++
cpp/fntest/pubnub_fntest_runner.cpp
mrtryhard/c-core
4c3c7009a133bf770c255243a2fc580f1629110e
#include "pubnub_fntest_basic.hpp" #include "pubnub_fntest_medium.hpp" #include <iostream> #include <functional> #include <condition_variable> #include <thread> #include <cstdlib> #include <cstring> #if defined _WIN32 #include "windows/console_subscribe_paint.h" #else #include "posix/console_subscribe_paint.h" #endif enum class TestResult { fail, pass, indeterminate }; using TestFN_T = std::function<void(std::string const&, std::string const&, std::string const&, bool const&)>; struct TestData { TestFN_T pf; char const *name; TestResult result; }; #define LIST_TEST(tstname) { pnfn_test_##tstname, #tstname, TestResult::indeterminate } static TestData m_aTest[] = { LIST_TEST(simple_connect_and_send_over_single_channel), LIST_TEST(connect_and_send_over_several_channels_simultaneously), LIST_TEST(simple_connect_and_send_over_single_channel_in_group), LIST_TEST(connect_and_send_over_several_channels_in_group_simultaneously), LIST_TEST(connect_and_send_over_channel_in_group_and_single_channel_simultaneously), LIST_TEST(connect_and_send_over_channel_in_group_and_multi_channel_simultaneously), LIST_TEST(simple_connect_and_receiver_over_single_channel), LIST_TEST(connect_and_receive_over_several_channels_simultaneously), LIST_TEST(simple_connect_and_receiver_over_single_channel_in_group), LIST_TEST(connect_and_receive_over_several_channels_in_group_simultaneously), LIST_TEST(connect_and_receive_over_channel_in_group_and_single_channel_simultaneously), LIST_TEST(connect_and_receive_over_channel_in_group_and_multi_channel_simultaneously), LIST_TEST(complex_send_and_receive_over_several_channels_simultaneously), LIST_TEST(complex_send_and_receive_over_channel_plus_group_simultaneously), LIST_TEST(connect_disconnect_and_connect_again), LIST_TEST(connect_disconnect_and_connect_again_group), LIST_TEST(connect_disconnect_and_connect_again_combo), LIST_TEST(wrong_api_usage), LIST_TEST(handling_errors_from_pubnub) }; #define TEST_COUNT (sizeof m_aTest / sizeof m_aTest[0]) static std::mutex m_mtx; static std::condition_variable m_cndvar; static unsigned m_running_tests; static bool is_pull_request_build(void) { #if !defined _WIN32 char const* tprb = getenv("TRAVIS_PULL_REQUEST"); return (tprb != NULL) && (0 != strcmp(tprb, "false")); #else return NULL != getenv("APPVEYOR_PULL_REQUEST_NUMBER"); #endif } static void notify(TestData &test,TestResult result) { { std::lock_guard<std::mutex> lk(m_mtx); --m_running_tests; test.result = result; } m_cndvar.notify_one(); } static int run_tests(TestData aTest[], unsigned test_count, unsigned max_conc_thread, std::string& pubkey, std::string& keysub, std::string& origin) { unsigned next_test = 0; std::vector<unsigned> failed; unsigned passed_count = 0; unsigned indete_count = 0; std::vector<std::thread> runners(test_count); bool cannot_do_chan_group; cannot_do_chan_group = is_pull_request_build(); std::cout << "Starting Run of " << test_count << " tests" << std::endl;; while (next_test < test_count) { unsigned i; unsigned in_this_pass = max_conc_thread; if (next_test + in_this_pass > test_count) { in_this_pass = test_count - next_test; } m_running_tests = in_this_pass; for (i = next_test; i < next_test+in_this_pass; ++i) { runners[i-next_test] = std::thread([i, pubkey, keysub, origin, aTest, cannot_do_chan_group] { try { using namespace std::chrono; system_clock::time_point tp = system_clock::now(); system_clock::duration dtn = tp.time_since_epoch(); srand(dtn.count()); aTest[i].pf(pubkey.c_str(), keysub.c_str(), origin.c_str(), cannot_do_chan_group); notify(aTest[i], TestResult::pass); } catch (std::exception &ex) { std::cout << std::endl; paint_text_white_with_background_red(); std::cout << " !! " << i+1 << ". test '" << aTest[i].name << "' failed!" << std::endl << "Error description: " << ex.what(); reset_text_paint(); std::cout << std::endl << std::endl; notify(aTest[i], TestResult::fail); } catch (pubnub::except_test &ex) { std::cout << std::endl; paint_text_yellow(); std::cout << " !! " << i+1 << ". test '" << aTest[i].name << "' indeterminate!" << std::endl << "Description: " << ex.what(); reset_text_paint(); std::cout << std::endl << std::endl; notify(aTest[i], TestResult::indeterminate); } }); std::this_thread::sleep_for(std::chrono::milliseconds(3)); } { std::unique_lock<std::mutex> lk(m_mtx); m_cndvar.wait(lk, []{ return m_running_tests == 0; }); } for (i = next_test; i < next_test+in_this_pass; ++i) { runners[i-next_test].join(); switch (aTest[i].result) { case TestResult::fail: failed.push_back(i); break; case TestResult::pass: ++passed_count; break; case TestResult::indeterminate: ++indete_count; break; } } next_test = i; } paint_text_white(); std::cout << "\nTest run over." << std::endl; if (passed_count == test_count) { paint_text_green(); std::cout << "All " << test_count << " tests passed" << std::endl; paint_text_white(); return 0; } else { paint_text_green(); std::cout << passed_count << " tests passed, "; reset_text_paint(); paint_text_white_with_background_red(); std::cout << failed.size() << " tests failed!"; reset_text_paint(); paint_text_white(); std::cout << ", "; paint_text_yellow(); std::cout << indete_count << " tests indeterminate" << std::endl; reset_text_paint(); if (!failed.empty()) { unsigned i; paint_text_white_with_background_red(); std::cout << "Failed tests:\n"; for (i = 0; i < failed.size() - 1 ; ++i) { std::cout << failed[i]+1 << ". " << aTest[failed[i]].name << std::endl; } std::cout << failed[i]+1 << ". " << aTest[failed[i]].name; reset_text_paint(); std::cout << std::endl; } paint_text_white(); return failed.size(); } } std::string getenv_ex(char const *env, char const *dflt) { char const* s = getenv(env); return (NULL == s) ? dflt : s; } int main(int argc, char *argv[]) { std::string pubkey = getenv_ex("PUBNUB_PUBKEY", (argc > 1) ? argv[1] : "demo"); std::string keysub = getenv_ex("PUBNUB_KEYSUB", (argc > 2) ? argv[2] : "demo"); std::string origin = getenv_ex("PUBNUB_ORIGIN", (argc > 3) ? argv[3] : "pubsub.pubnub.com"); unsigned max_conc_thread = (argc > 4) ? std::atoi(argv[4]) : 1; return run_tests(m_aTest, TEST_COUNT, max_conc_thread, pubkey, keysub, origin); }
#include "pubnub_fntest_basic.hpp" #include "pubnub_fntest_medium.hpp" #include <iostream> #include <functional> #include <condition_variable> #include <thread> #include <cstdlib> #include <cstring> #if defined _WIN32 #include "windows/console_subscribe_paint.h" #else #include "posix/console_subscribe_paint.h" #endif enum class TestResult { fail, pass, indeterminate }; using TestFN_T = std::function<void(std::string const&, std::string const&, std::string const&, bool const&)>; struct TestData { TestFN_T pf; char const *name; TestResult result; }; #define LIST_TEST(tstname) { pnfn_test_##tstname, #tstname, TestResult::indeterminate } static TestData m_aTest[] = { LIST_TEST(simple_connect_and_send_over_single_channel), LIST_TEST(connect_and_send_over_several_channels_simultaneously), LIST_TEST(simple_connect_and_send_over_single_channel_in_group), LIST_TEST(connect_and_send_over_several_channels_in_group_simultaneously), LIST_TEST(connect_and_send_over_channel_in_group_and_single_channel_simultaneously), LIST_TEST(connect_and_send_over_channel_in_group_and_multi_channel_simultaneously), LIST_TEST(simple_connect_and_receiver_over_single_channel), LIST_TEST(connect_and_receive_over_several_channels_simultaneously), LIST_TEST(simple_connect_and_receiver_over_single_channel_in_group), LIST_TEST(connect_and_receive_over_several_channels_in_group_simultaneously), LIST_TEST(connect_and_receive_over_channel_in_group_and_single_channel_simultaneously), LIST_TEST(connect_and_receive_over_channel_in_group_and_multi_channel_simultaneously), LIST_TEST(complex_send_and_receive_over_several_channels_simultaneously), LIST_TEST(complex_send_and_receive_over_channel_plus_group_simultaneously), LIST_TEST(connect_disconnect_and_connect_again), LIST_TEST(connect_disconnect_and_connect_again_group), LIST_TEST(connect_disconnect_and_connect_again_combo), LIST_TEST(wrong_api_usage), LIST_TEST(handling_errors_from_pubnub) }; #define TEST_COUNT (sizeof m_aTest / sizeof m_aTest[0]) static std::mutex m_mtx; static std::condition_variable m_cndvar; static unsigned m_running_tests; static bool is_pull_request_build(void) { #if !defined _WIN32 char const* tprb = getenv("TRAVIS_PULL_REQUEST"); return (tprb != NULL) && (0 != strcmp(tprb, "false")); #else return NULL != getenv("APPVEYOR_PULL_REQUEST_NUMBER"); #endif } static void notify(TestData &test,TestResult result) { { std::lock_guard<std::mutex> lk(m_mtx); --m_running_tests; test.result = result; } m_cndvar.notify_one(); } static int run_tests(TestData aTest[], unsigned test_count, unsigned max_conc_thread, std::string& pubkey, std::string& keysub, std::string& origin) { unsigned next_test = 0; std::vector<unsigned> failed; unsigned passed_count = 0; unsigned indete_count = 0; std::vector<std::thread> runners(test_count); bool cannot_do_chan_group; cannot_do_chan_group = is_pull_request_build(); std::cout << "Starting Run of " << test_count << " tests" << std::endl;; while (next_test < test_count) { unsigned i; unsigned in_this_pass = max_conc_thread; if (next_test + in_this_pass > test_count) { in_this_pass = test_count - next_test; } m_running_tests = in_this_pass; for (i = next_test; i < next_test+in_this_pass; ++i) { runners[i-next_test] = std::thread([i, pubkey, keysub, origin, aTest, cannot_do_chan_group] { try { using namespace std::chrono; system_clock::time_point tp = system_clock::now(); system_clock::duration dtn = tp.time_since_epoch(); srand(dtn.count());
; notify(aTest[i], TestResult::pass); } catch (std::exception &ex) { std::cout << std::endl; paint_text_white_with_background_red(); std::cout << " !! " << i+1 << ". test '" << aTest[i].name << "' failed!" << std::endl << "Error description: " << ex.what(); reset_text_paint(); std::cout << std::endl << std::endl; notify(aTest[i], TestResult::fail); } catch (pubnub::except_test &ex) { std::cout << std::endl; paint_text_yellow(); std::cout << " !! " << i+1 << ". test '" << aTest[i].name << "' indeterminate!" << std::endl << "Description: " << ex.what(); reset_text_paint(); std::cout << std::endl << std::endl; notify(aTest[i], TestResult::indeterminate); } }); std::this_thread::sleep_for(std::chrono::milliseconds(3)); } { std::unique_lock<std::mutex> lk(m_mtx); m_cndvar.wait(lk, []{ return m_running_tests == 0; }); } for (i = next_test; i < next_test+in_this_pass; ++i) { runners[i-next_test].join(); switch (aTest[i].result) { case TestResult::fail: failed.push_back(i); break; case TestResult::pass: ++passed_count; break; case TestResult::indeterminate: ++indete_count; break; } } next_test = i; } paint_text_white(); std::cout << "\nTest run over." << std::endl; if (passed_count == test_count) { paint_text_green(); std::cout << "All " << test_count << " tests passed" << std::endl; paint_text_white(); return 0; } else { paint_text_green(); std::cout << passed_count << " tests passed, "; reset_text_paint(); paint_text_white_with_background_red(); std::cout << failed.size() << " tests failed!"; reset_text_paint(); paint_text_white(); std::cout << ", "; paint_text_yellow(); std::cout << indete_count << " tests indeterminate" << std::endl; reset_text_paint(); if (!failed.empty()) { unsigned i; paint_text_white_with_background_red(); std::cout << "Failed tests:\n"; for (i = 0; i < failed.size() - 1 ; ++i) { std::cout << failed[i]+1 << ". " << aTest[failed[i]].name << std::endl; } std::cout << failed[i]+1 << ". " << aTest[failed[i]].name; reset_text_paint(); std::cout << std::endl; } paint_text_white(); return failed.size(); } } std::string getenv_ex(char const *env, char const *dflt) { char const* s = getenv(env); return (NULL == s) ? dflt : s; } int main(int argc, char *argv[]) { std::string pubkey = getenv_ex("PUBNUB_PUBKEY", (argc > 1) ? argv[1] : "demo"); std::string keysub = getenv_ex("PUBNUB_KEYSUB", (argc > 2) ? argv[2] : "demo"); std::string origin = getenv_ex("PUBNUB_ORIGIN", (argc > 3) ? argv[3] : "pubsub.pubnub.com"); unsigned max_conc_thread = (argc > 4) ? std::atoi(argv[4]) : 1; return run_tests(m_aTest, TEST_COUNT, max_conc_thread, pubkey, keysub, origin); }
aTest[i].pf(pubkey.c_str(), keysub.c_str(), origin.c_str(), cannot_do_chan_group)
call_expression
[ { "content": "enum class TestResult { fail, pass, indeterminate };\n\nQ_DECLARE_METATYPE(TestResult);\n\n\n\nusing TestFN_T =\n\n std::function<void(std::string const&, std::string const&, std::string const&, bool const&)>;\n\n\n", "file_path": "qt/fntest/pubnub_fntest_runner.cpp", "rank": 0, "score": 398461.4589317768 }, { "content": "struct TestData {\n\n TestFN_T pf;\n\n char const* name;\n\n TestResult result;\n\n};\n\n\n\n\n\n#define LIST_TEST(tstname) \\\n\n { \\\n\n pnfn_test_##tstname, #tstname, TestResult::indeterminate \\\n\n }\n\n\n\n\n\nstatic TestData m_aTest[] = {\n\n LIST_TEST(simple_connect_and_send_over_single_channel),\n\n LIST_TEST(connect_and_send_over_several_channels_simultaneously),\n\n LIST_TEST(simple_connect_and_send_over_single_channel_in_group),\n\n LIST_TEST(connect_and_send_over_several_channels_in_group_simultaneously),\n\n LIST_TEST(connect_and_send_over_channel_in_group_and_single_channel_simultaneously),\n\n LIST_TEST(connect_and_send_over_channel_in_group_and_multi_channel_simultaneously),\n", "file_path": "qt/fntest/pubnub_fntest_runner.cpp", "rank": 2, "score": 156666.43092365444 }, { "content": "class const_mem_fun2_t : public std::binary_function<A, B, R> {\n\n R (T::*pmem)(A, B) const;\n\n T* d_t;\n\n\n\npublic:\n\n explicit const_mem_fun2_t(R (T::*p)(A, B) const, T* t)\n\n : pmem(p)\n\n , d_t(t)\n\n {\n\n }\n\n R operator()(A a, B b) const { return (d_t->*pmem)(a, b); }\n\n};\n\n\n\ntemplate <class R, class T, class A, class B>\n", "file_path": "cpp/pubnub.hpp", "rank": 4, "score": 153156.0806865659 }, { "content": "class const_mem_fun2_ref_t : public std::binary_function<A, B, R> {\n\n R (T::*pmem)(A, B) const;\n\n T& d_t;\n\n\n\npublic:\n\n explicit const_mem_fun2_ref_t(R (T::*p)(A, B) const, T& t)\n\n : pmem(p)\n\n , d_t(t)\n\n {\n\n }\n\n R operator()(A a, B b) const { return (d_t.*pmem)(a, b); }\n\n};\n\n\n\ntemplate <class R, class T, class A, class B>\n\nmem_fun2_t<R, T, A, B> mem_fun(R (T::*f)(A, B), T* t)\n\n{\n\n return mem_fun2_t<R, T, A, B>(f, t);\n\n}\n\ntemplate <class R, class T, class A, class B>\n\nconst_mem_fun2_t<R, T, A, B> mem_fun(R (T::*f)(A, B) const, T* t)\n", "file_path": "cpp/pubnub.hpp", "rank": 5, "score": 150732.0978963906 }, { "content": " char function_name[50];\n", "file_path": "core/pubnub_proxy_NTLM_test.c", "rank": 6, "score": 147050.73616121372 }, { "content": " class except_test {\n\n std::string d_str;\n\n char const *d_file;\n\n long d_line;\n\n char const *d_expr;\n\n public:\n\n except_test(std::string &str, char const *f, long l, char const *e)\n\n : d_str(str)\n\n , d_file(f)\n\n , d_line(l)\n\n , d_expr(e)\n\n {} \n\n std::string what() const {\n\n std::stringstream stream;\n\n stream << \"In file:\" << d_file << \", line:\" << d_line << \" \" <<\n\n ((0 != *d_expr)?\"For expression:'\":\"\") << d_expr << \"' - got:'\" << d_str << \"'\";\n\n return stream.str();\n\n }\n\n };\n\n\n", "file_path": "cpp/fntest/pubnub_fntest.hpp", "rank": 7, "score": 130854.66403245693 }, { "content": "class TestController : public QObject {\n\n Q_OBJECT\n\n\n\nprivate:\n\n QMap<TestRunner*, QThread*> d_runner;\n\n\n\n QString d_pubkey;\n\n QString d_keysub;\n\n QString d_origin;\n\n unsigned d_max_conc_thread;\n\n TestData* d_test;\n\n unsigned d_test_count;\n\n unsigned d_next_test;\n\n unsigned d_failed_count;\n\n unsigned d_passed_count;\n\n unsigned d_indete_count;\n\n bool d_cannot_do_chan_group;\n\n\n\npublic:\n\n TestController(TestData aTest[],\n", "file_path": "qt/fntest/pubnub_fntest_runner.cpp", "rank": 8, "score": 113903.16477505918 }, { "content": "class TestRunner : public QObject {\n\n Q_OBJECT\n\n\n\n QString d_pubkey;\n\n QString d_keysub;\n\n QString d_origin;\n\n unsigned d_iTest;\n\n TestFN_T d_pf;\n\n char const* d_name;\n\n bool d_cannot_do_chan_group;\n\n\n\npublic:\n\n TestRunner(QString const& pubkey,\n\n QString const& keysub,\n\n QString const& origin,\n\n unsigned iTest,\n\n TestFN_T pf,\n\n char const* name,\n\n bool cannot_do_chan_group)\n\n : d_pubkey(pubkey)\n", "file_path": "qt/fntest/pubnub_fntest_runner.cpp", "rank": 9, "score": 113903.16477505918 }, { "content": "class mem_fun2_t : public std::binary_function<A, B, R> {\n\n R (T::*pmem)(A, B);\n\n T* d_t;\n\n\n\npublic:\n\n explicit mem_fun2_t(R (T::*p)(A, B), T* t)\n\n : pmem(p)\n\n , d_t(t)\n\n {\n\n }\n\n R operator()(A a, B b) const { return (d_t->*pmem)(a, b); }\n\n};\n\n\n\ntemplate <class R, class T, class A, class B>\n", "file_path": "cpp/pubnub.hpp", "rank": 10, "score": 107244.62617010191 }, { "content": "class mem_fun2_ref_t : public std::binary_function<A, B, R> {\n\n R (T::*pmem)(A, B);\n\n T& d_t;\n\n\n\npublic:\n\n explicit mem_fun2_ref_t(R (T::*p)(A, B), T& t)\n\n : pmem(p)\n\n , d_t(t)\n\n {\n\n }\n\n R operator()(A a, B b) const { return (d_t.*pmem)(a, b); }\n\n};\n\n\n\ntemplate <class R, class T, class A, class B>\n", "file_path": "cpp/pubnub.hpp", "rank": 11, "score": 105572.31331088982 }, { "content": "static int m_passes = 0;\n", "file_path": "core/pubnub_proxy_NTLM_test.c", "rank": 12, "score": 99619.5329331278 }, { "content": "#define returns will_return\n\n\n", "file_path": "core/pubnub_core_unit_test.c", "rank": 13, "score": 99610.73763140872 }, { "content": "#define returns will_return\n\n\n", "file_path": "core/pubnub_proxy_unit_test.c", "rank": 14, "score": 99610.73763140872 }, { "content": "static int run_tests(struct TestData aTest[],\n\n unsigned test_count,\n\n unsigned max_conc_thread,\n\n char const* pubkey,\n\n char const* keysub,\n\n char const* origin)\n\n{\n\n unsigned next_test = 0;\n\n unsigned failed_count = 0;\n\n unsigned passed_count = 0;\n\n unsigned indete_count = 0;\n\n HANDLE hstdout = GetStdHandle(STD_OUTPUT_HANDLE);\n\n CONSOLE_SCREEN_BUFFER_INFO csbiInfo;\n\n WORD wOldColorAttrs = FOREGROUND_INTENSITY;\n\n struct PNTestParameters tstpar = { pubkey, keysub, origin };\n\n\n\n PUBNUB_ASSERT_OPT(max_conc_thread <= TEST_MAX_HANDLES);\n\n PUBNUB_ASSERT_OPT(hstdout != INVALID_HANDLE_VALUE);\n\n\n\n tstpar.candochangroup = !is_appveyor_pull_request_build();\n\n pnfntst_set_params(&tstpar);\n\n\n\n printf(\"Starting Run of %u tests\\n\", test_count);\n\n srand_from_pubnub(pubkey, keysub);\n\n if (GetConsoleScreenBufferInfo(hstdout, &csbiInfo)) {\n\n wOldColorAttrs = csbiInfo.wAttributes;\n\n }\n\n\n\n while (next_test < test_count) {\n\n unsigned i;\n\n unsigned in_this_pass = max_conc_thread;\n\n HANDLE aHa[TEST_MAX_HANDLES];\n\n\n\n if (next_test + in_this_pass > test_count) {\n\n in_this_pass = test_count - next_test;\n\n }\n\n for (i = next_test; i < next_test + in_this_pass; ++i) {\n\n printf(\"Creating a thread for test %u\\n\", i + 1);\n\n aHa[i - next_test] = aTest[i].pth = (HANDLE)_beginthreadex(\n\n NULL, 0, aTest[i].pf, &aTest[i].result, 0, NULL);\n\n }\n\n /* This is the simplest way to do it - wait for all threads to finish.\n\n With a little tweak, we could wait for the first that finishes and\n\n launch the next test (thread) \"in its place\". That's a TODO for\n\n next version.\n\n */\n\n if (WAIT_OBJECT_0\n\n != WaitForMultipleObjects(in_this_pass, aHa, TRUE, INFINITE)) {\n\n SetConsoleTextAttribute(hstdout, FOREGROUND_RED | FOREGROUND_INTENSITY);\n\n printf(\"\\n ! WaitForMultipleObjects failed abandonding tests!\\n\\n\");\n\n SetConsoleTextAttribute(hstdout, wOldColorAttrs);\n\n return -1;\n\n }\n\n for (i = next_test; i < next_test + in_this_pass; ++i) {\n\n switch (aTest[i].result) {\n\n case trFail:\n\n SetConsoleTextAttribute(hstdout,\n\n FOREGROUND_RED | FOREGROUND_INTENSITY);\n\n printf(\n\n \"\\n\\x1b[41m!!!!!!! The %u. test ('%s') failed!\\x1b[m\\n\\n\",\n\n i + 1,\n\n aTest[i].name);\n\n ++failed_count;\n\n SetConsoleTextAttribute(hstdout, wOldColorAttrs);\n\n break;\n\n case trPass:\n\n ++passed_count;\n\n break;\n\n case trIndeterminate:\n\n ++indete_count;\n\n SetConsoleTextAttribute(hstdout,\n\n FOREGROUND_RED | FOREGROUND_GREEN\n\n | FOREGROUND_INTENSITY);\n\n printf(\" Indeterminate %u. test ('%s') of %u\\t\",\n\n i + 1,\n\n aTest[i].name,\n\n test_count);\n\n SetConsoleTextAttribute(hstdout, wOldColorAttrs);\n\n /* Should restart the test... */\n\n // printf(\"\\x1b[33m ReStarting %d. test of %ld\\x1b[m\\t\", i + 1,\n\n // test_count);\n\n break;\n\n }\n\n }\n\n next_test = i;\n\n }\n\n\n\n puts(\"Test run over.\");\n\n if (passed_count == test_count) {\n\n SetConsoleTextAttribute(hstdout, FOREGROUND_GREEN);\n\n printf(\" All %u tests passed.\\n\", test_count);\n\n SetConsoleTextAttribute(hstdout, wOldColorAttrs);\n\n return 0;\n\n }\n\n else {\n\n SetConsoleTextAttribute(hstdout, FOREGROUND_GREEN);\n\n printf(\"%u tests passed, \", passed_count);\n\n SetConsoleTextAttribute(hstdout, FOREGROUND_RED | FOREGROUND_INTENSITY);\n\n printf(\"%u tests failed, \", failed_count);\n\n SetConsoleTextAttribute(\n\n hstdout, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY);\n\n printf(\"%u tests indeterminate\\n\", indete_count);\n\n SetConsoleTextAttribute(hstdout, wOldColorAttrs);\n\n return failed_count;\n\n }\n", "file_path": "windows/fntest/pubnub_fntest_runner.c", "rank": 15, "score": 97831.63119124342 }, { "content": "static int run_tests(struct TestData aTest[],\n\n unsigned test_count,\n\n unsigned max_conc_thread,\n\n char const* pubkey,\n\n char const* keysub,\n\n char const* origin)\n\n{\n\n unsigned next_test = 0;\n\n unsigned failed_count = 0;\n\n unsigned passed_count = 0;\n\n unsigned indete_count = 0;\n\n struct PNTestParameters tstpar = { pubkey, keysub, origin };\n\n\n\n tstpar.candochangroup = !is_travis_pull_request_build();\n\n pnfntst_set_params(&tstpar);\n\n\n\n printf(\"Starting Run of %d tests\\n\", test_count);\n\n srand_from_pubnub(pubkey, keysub);\n\n while (next_test < test_count) {\n\n unsigned i;\n\n unsigned in_this_pass = max_conc_thread;\n\n if (next_test + in_this_pass > test_count) {\n\n in_this_pass = test_count - next_test;\n\n }\n\n for (i = next_test; i < next_test + in_this_pass; ++i) {\n\n printf(\"Creating a thread for test %u\\n\", i + 1);\n\n if (0 != pthread_create(&aTest[i].pth, NULL, aTest[i].pf, &aTest[i].result)) {\n\n printf(\n\n \"Failed to create a thread for test %u ('%s'), errno=%d\\n\",\n\n i + 1,\n\n aTest[i].name,\n\n errno);\n\n }\n\n }\n\n /* This is the simplest way to do it - join all threads, one\n\n by one. We could improve this, wait for the first thread\n\n that finishes, and start a new test \"in its place\", but\n\n that requires more work, as there is no\n\n pthread_join_any()...\n\n */\n\n for (i = next_test; i < next_test + in_this_pass; ++i) {\n\n if (0 != pthread_join(aTest[i].pth, NULL)) {\n\n printf(\"Failed to join thread for test %u ('%s'), errno=%d\\n\",\n\n i + 1,\n\n aTest[i].name,\n\n errno);\n\n }\n\n switch (aTest[i].result) {\n\n case trFail:\n\n printf(\n\n \"\\n\\x1b[41m !!!!!!! The %u. test ('%s') failed!\\x1b[m\\n\\n\",\n\n i + 1,\n\n aTest[i].name);\n\n ++failed_count;\n\n break;\n\n case trPass:\n\n ++passed_count;\n\n break;\n\n case trIndeterminate:\n\n ++indete_count;\n\n printf(\"\\x1b[33m Indeterminate %u. test ('%s') of %u\\x1b[m\\t\",\n\n i + 1,\n\n aTest[i].name,\n\n test_count);\n\n /* Should restart the test... */\n\n // printf(\"\\x1b[33m ReStarting %d. test of %ld\\x1b[m\\t\", i + 1,\n\n // test_count);\n\n break;\n\n }\n\n }\n\n next_test = i;\n\n }\n\n\n\n puts(\"Test run over.\");\n\n if (passed_count == test_count) {\n\n printf(\"\\x1b[32m All %d tests passed\\x1b[m\\n\", test_count);\n\n return 0;\n\n }\n\n else {\n\n printf(\"\\x1b[32m %u tests passed\\x1b[m, \\x1b[41m %u tests \"\n\n \"failed!\\x1b[m, \\x1b[33m %u tests indeterminate\\x1b[m\\n\",\n\n passed_count,\n\n failed_count,\n\n indete_count);\n\n for (next_test = 0; next_test < test_count; ++next_test) {\n\n switch (aTest[next_test].result) {\n\n case trFail:\n\n printf(\"Test \\x1b[41m '%s' \\x1b[m failed!\\n\", aTest[next_test].name);\n\n break;\n\n case trIndeterminate:\n\n printf(\"Test \\x1b[33m '%s' \\x1b[m indeterminate\\n\",\n\n aTest[next_test].name);\n\n break;\n\n default:\n\n break;\n\n }\n\n }\n\n return failed_count;\n\n }\n", "file_path": "posix/fntest/pubnub_fntest_runner.c", "rank": 16, "score": 97831.63119124342 }, { "content": "#define returns will_return\n\n\n\n\n", "file_path": "core/pubnub_timer_list_unit_test.c", "rank": 17, "score": 97827.34012016586 }, { "content": " int return_value;\n", "file_path": "core/pubnub_proxy_NTLM_test.c", "rank": 18, "score": 97827.34012016586 }, { "content": "#define returns will_return\n\n\n", "file_path": "lib/pubnub_dns_codec_unit_test.c", "rank": 19, "score": 97827.34012016586 }, { "content": "static void start_test(unsigned test)\n\n{\n\n if (test < TEST_COUNT) {\n\n FreeRTOS_printf((\"Creating a task for test %d\\n\", test));\n\n if (pdPASS != xTaskCreate(\n\n single_test_runner, \n\n \"single test\", \n\n SINGLE_TEST_STACK_DEPTH, \n\n (void*)test, \n\n SINGLE_TEST_PRIORITY, \n\n &m_aTest[test].task\n\n )) {\n\n FreeRTOS_printf((\"\\n!! Failed to create a task for test %d!\\n\", test));\n\n }\n\n }\n", "file_path": "freertos/fntest/pubnub_fntest_runner.c", "rank": 20, "score": 97763.27869107408 }, { "content": "#define returns will_return\n\n\n", "file_path": "lib/pubnub_parse_ipv6_addr_unit_test.c", "rank": 21, "score": 96106.67812471259 }, { "content": "struct TestResultMessage {\n\n unsigned test;\n\n enum PNFNTestResult result;\n", "file_path": "freertos/fntest/pubnub_fntest_runner.c", "rank": 22, "score": 96081.54132678224 }, { "content": "static QueueHandle_t m_TestResultQueue;\n", "file_path": "freertos/fntest/pubnub_fntest_runner.c", "rank": 23, "score": 96081.54132678224 }, { "content": "char const* pubnub_sdk_name(void)\n\n{\n\n return \"unit-test\";\n", "file_path": "core/pubnub_proxy_NTLM_test.c", "rank": 24, "score": 96050.0575975352 }, { "content": "char const* pubnub_sdk_name(void)\n\n{\n\n return \"unit-test\";\n", "file_path": "core/pubnub_core_unit_test.c", "rank": 25, "score": 96050.0575975352 }, { "content": "char const *pubnub_sdk_name(void)\n\n{\n\n return \"unit-test\";\n", "file_path": "core/pubnub_proxy_unit_test.c", "rank": 26, "score": 96050.0575975352 }, { "content": "int pbpal_start_read(pubnub_t *pb, size_t n)\n\n{\n\n unsigned distance;\n\n\n\n PUBNUB_ASSERT_UINT_OPT(n, >, 0);\n\n PUBNUB_ASSERT_INT_OPT(pb->sock_state, ==, STATE_NONE);\n\n\n\n WATCH_USHORT(pb->unreadlen);\n\n WATCH_USHORT(pb->left);\n\n if (pb->unreadlen > 0) {\n\n PUBNUB_ASSERT_OPT((char*)(pb->ptr + pb->unreadlen) <= (char*)(pb->core.http_buf + PUBNUB_BUF_MAXLEN));\n\n memmove(pb->core.http_buf, pb->ptr, pb->unreadlen);\n\n }\n\n distance = pb->ptr - (uint8_t*)pb->core.http_buf;\n\n WATCH_UINT(distance);\n\n PUBNUB_ASSERT_UINT(distance + pb->unreadlen + pb->left, ==, sizeof pb->core.http_buf / sizeof pb->core.http_buf[0]);\n\n pb->ptr -= distance;\n\n pb->left += distance;\n\n\n\n pb->sock_state = STATE_READ;\n\n pb->len = n;\n\n\n\n return +1;\n", "file_path": "core/pubnub_proxy_unit_test.c", "rank": 27, "score": 96043.74345697685 }, { "content": "int pbpal_start_read(pubnub_t* pb, size_t n)\n\n{\n\n unsigned distance;\n\n\n\n PUBNUB_ASSERT_UINT_OPT(n, >, 0);\n\n PUBNUB_ASSERT_INT_OPT(pb->sock_state, ==, STATE_NONE);\n\n\n\n WATCH_USHORT(pb->unreadlen);\n\n WATCH_USHORT(pb->left);\n\n if (pb->unreadlen > 0) {\n\n PUBNUB_ASSERT_OPT((char*)(pb->ptr + pb->unreadlen)\n\n <= (char*)(pb->core.http_buf + PUBNUB_BUF_MAXLEN));\n\n memmove(pb->core.http_buf, pb->ptr, pb->unreadlen);\n\n }\n\n distance = pb->ptr - (uint8_t*)pb->core.http_buf;\n\n WATCH_UINT(distance);\n\n PUBNUB_ASSERT_UINT(distance + pb->unreadlen + pb->left,\n\n ==,\n\n sizeof pb->core.http_buf / sizeof pb->core.http_buf[0]);\n\n pb->ptr -= distance;\n\n pb->left += distance;\n\n\n\n pb->sock_state = STATE_READ;\n\n pb->len = n;\n\n\n\n return +1;\n", "file_path": "core/pubnub_proxy_NTLM_test.c", "rank": 28, "score": 96043.74345697685 }, { "content": "int pbpal_start_read(pubnub_t* pb, size_t n)\n\n{\n\n unsigned distance;\n\n\n\n PUBNUB_ASSERT_UINT_OPT(n, >, 0);\n\n PUBNUB_ASSERT_INT_OPT(pb->sock_state, ==, STATE_NONE);\n\n\n\n WATCH_USHORT(pb->unreadlen);\n\n WATCH_USHORT(pb->left);\n\n if (pb->unreadlen > 0) {\n\n PUBNUB_ASSERT_OPT((char*)(pb->ptr + pb->unreadlen)\n\n <= (char*)(pb->core.http_buf + PUBNUB_BUF_MAXLEN));\n\n memmove(pb->core.http_buf, pb->ptr, pb->unreadlen);\n\n }\n\n distance = pb->ptr - (uint8_t*)pb->core.http_buf;\n\n WATCH_UINT(distance);\n\n PUBNUB_ASSERT_UINT(distance + pb->unreadlen + pb->left,\n\n ==,\n\n sizeof pb->core.http_buf / sizeof pb->core.http_buf[0]);\n\n pb->ptr -= distance;\n\n pb->left += distance;\n\n\n\n pb->sock_state = STATE_READ;\n\n pb->len = n;\n\n\n\n return +1;\n", "file_path": "core/pubnub_core_unit_test.c", "rank": 29, "score": 96043.74345697685 }, { "content": "#define SIZEOF_CHAR 1\n", "file_path": "freertos/samples/WinPCap/pcap-stdinc.h", "rank": 30, "score": 95161.88697458194 }, { "content": "#define SIZEOF_CHAR 1\n", "file_path": "freertos/fntest/WinPCap/pcap-stdinc.h", "rank": 31, "score": 95161.88697458194 }, { "content": "#define SIZEOF_INT 4\n", "file_path": "freertos/samples/WinPCap/pcap-stdinc.h", "rank": 32, "score": 95142.41851270485 }, { "content": "#define SIZEOF_INT 4\n", "file_path": "freertos/fntest/WinPCap/pcap-stdinc.h", "rank": 33, "score": 95142.41851270485 }, { "content": "void expect_have_dns_for_pubnub_origin()\n\n{\n\n expect(pbntf_enqueue_for_processing, when(pb, equals(pbp)), returns(0));\n\n expect(pbpal_resolv_and_connect,\n\n when(pb, equals(pbp)),\n\n returns(pbpal_connect_success));\n\n expect(pbntf_got_socket, when(pb, equals(pbp)), returns(0));\n", "file_path": "core/pubnub_core_unit_test.c", "rank": 34, "score": 94445.49854256098 }, { "content": "static const char encoded_domain_name[] = \"\\7encoded\\3two\\6server\\6domain\\4name\\1q\\2up\\0\";\n", "file_path": "lib/pubnub_dns_codec_unit_test.c", "rank": 35, "score": 94399.5913408429 }, { "content": "int pbpal_start_read_line(pubnub_t* pb)\n\n{\n\n unsigned distance;\n\n\n\n PUBNUB_ASSERT_INT_OPT(pb->sock_state, ==, STATE_NONE);\n\n\n\n if (pb->unreadlen > 0) {\n\n PUBNUB_ASSERT_OPT((char*)(pb->ptr + pb->unreadlen)\n\n <= (char*)(pb->core.http_buf + PUBNUB_BUF_MAXLEN));\n\n memmove(pb->core.http_buf, pb->ptr, pb->unreadlen);\n\n }\n\n distance = pb->ptr - (uint8_t*)pb->core.http_buf;\n\n PUBNUB_ASSERT_UINT((distance + pb->left + pb->unreadlen),\n\n ==,\n\n (sizeof pb->core.http_buf / sizeof pb->core.http_buf[0]));\n\n pb->ptr -= distance;\n\n pb->left += distance;\n\n\n\n pb->sock_state = STATE_READ_LINE;\n\n\n\n return +1;\n", "file_path": "core/pubnub_core_unit_test.c", "rank": 36, "score": 94383.65168461217 }, { "content": "int pbpal_start_read_line(pubnub_t* pb)\n\n{\n\n unsigned distance;\n\n\n\n PUBNUB_ASSERT_INT_OPT(pb->sock_state, ==, STATE_NONE);\n\n\n\n if (pb->unreadlen > 0) {\n\n PUBNUB_ASSERT_OPT((char*)(pb->ptr + pb->unreadlen)\n\n <= (char*)(pb->core.http_buf + PUBNUB_BUF_MAXLEN));\n\n memmove(pb->core.http_buf, pb->ptr, pb->unreadlen);\n\n }\n\n distance = pb->ptr - (uint8_t*)pb->core.http_buf;\n\n PUBNUB_ASSERT_UINT((distance + pb->left + pb->unreadlen),\n\n ==,\n\n (sizeof pb->core.http_buf / sizeof pb->core.http_buf[0]));\n\n pb->ptr -= distance;\n\n pb->left += distance;\n\n\n\n pb->sock_state = STATE_READ_LINE;\n\n\n\n return +1;\n", "file_path": "core/pubnub_proxy_NTLM_test.c", "rank": 37, "score": 94383.65168461217 }, { "content": "int pbpal_start_read_line(pubnub_t *pb)\n\n{\n\n unsigned distance;\n\n\n\n PUBNUB_ASSERT_INT_OPT(pb->sock_state, ==, STATE_NONE);\n\n\n\n if (pb->unreadlen > 0) {\n\n PUBNUB_ASSERT_OPT((char*)(pb->ptr + pb->unreadlen) <= (char*)(pb->core.http_buf + PUBNUB_BUF_MAXLEN));\n\n memmove(pb->core.http_buf, pb->ptr, pb->unreadlen);\n\n }\n\n distance = pb->ptr - (uint8_t*)pb->core.http_buf;\n\n PUBNUB_ASSERT_UINT((distance + pb->left + pb->unreadlen), ==, (sizeof pb->core.http_buf / sizeof pb->core.http_buf[0]));\n\n pb->ptr -= distance;\n\n pb->left += distance;\n\n\n\n pb->sock_state = STATE_READ_LINE;\n\n\n\n return +1;\n", "file_path": "core/pubnub_proxy_unit_test.c", "rank": 38, "score": 94383.65168461217 }, { "content": "char const* pbjson_object_name_parse_result_2_string(enum pbjson_object_name_parse_result e)\n\n{\n\n switch (e) {\n\n case jonmpNoStartCurly:\n\n return \"No Start Curly\";\n\n case jonmpKeyMissing:\n\n return \"Key Missing\";\n\n case jonmpKeyNotString:\n\n return \"Key Not String\";\n\n case jonmpStringNotTerminated:\n\n return \"String Not Terminated\";\n\n case jonmpMissingColon:\n\n return \"Missing Colon\";\n\n case jonmpObjectIncomplete:\n\n return \"Object Incomplete\";\n\n case jonmpMissingValueSeparator:\n\n return \"Missing Value Separator\";\n\n case jonmpKeyNotFound:\n\n return \"Key Not Found\";\n\n case jonmpInvalidKeyName:\n\n return \"Invalid Key Name\";\n\n case jonmpOK:\n\n return \"OK\";\n\n default:\n\n return \"?!?\";\n\n }\n", "file_path": "core/pubnub_json_parse.c", "rank": 39, "score": 93450.91505285627 }, { "content": "static const char encoded_abc_domain_name[] = \"\\1a\\1b\\1c\\0\";\n", "file_path": "lib/pubnub_dns_codec_unit_test.c", "rank": 40, "score": 92786.07292429202 }, { "content": "static const char encoded_label_start_with_offset_to_itself[] = \"\\3www\\300\\14\";\n", "file_path": "lib/pubnub_dns_codec_unit_test.c", "rank": 41, "score": 92783.87627789198 }, { "content": "#define TYPE_AND_CLASS_FIELDS_SIZE 4\n", "file_path": "lib/pubnub_dns_codec_unit_test.c", "rank": 42, "score": 92769.79401414281 }, { "content": "static const char label_start_encoded_badly_with_offset_to_itself[] = \"\\4www\\300\\14\";\n", "file_path": "lib/pubnub_dns_codec_unit_test.c", "rank": 43, "score": 91229.88092825569 }, { "content": " char const* keysub;\n", "file_path": "core/fntest/pubnub_fntest.h", "rank": 44, "score": 88985.16474279271 }, { "content": " char const* pubkey;\n", "file_path": "core/fntest/pubnub_fntest.h", "rank": 45, "score": 88980.75583084603 }, { "content": " char const* origin;\n", "file_path": "core/fntest/pubnub_fntest.h", "rank": 46, "score": 88978.47250410434 }, { "content": " char const* start;\n", "file_path": "core/pubnub_coreapi_ex.h", "rank": 47, "score": 88923.29385359061 }, { "content": " char const* start;\n", "file_path": "core/pubnub_json_parse.h", "rank": 48, "score": 88914.49472668991 }, { "content": " PF_Test_T pf;\n", "file_path": "freertos/fntest/pubnub_fntest_runner.c", "rank": 49, "score": 88051.39996528566 }, { "content": " PF_Test_T pf;\n", "file_path": "posix/fntest/pubnub_fntest_runner.c", "rank": 50, "score": 88051.39996528566 }, { "content": " PF_Test_T pf;\n", "file_path": "windows/fntest/pubnub_fntest_runner.c", "rank": 51, "score": 88051.39996528566 }, { "content": "static const char pubkey[] = \"demo\";\n", "file_path": "core/samples/console/pubnub_console.c", "rank": 52, "score": 88048.99625210068 }, { "content": " _Guarded_by_(mutw) struct pbpal_poll_data* poll;\n", "file_path": "openssl/pubnub_ntf_callback_windows.c", "rank": 53, "score": 88034.79907021401 }, { "content": " pubnub_guarded_by(monitor) struct pubnub_subscribe_options options;\n", "file_path": "core/pubnub_callback_subscribe_loop.c", "rank": 54, "score": 88034.79907021401 }, { "content": " _Guarded_by_(mutw) struct pbpal_poll_data* poll;\n", "file_path": "windows/pubnub_ntf_callback_windows.c", "rank": 55, "score": 88034.79907021401 }, { "content": " enum PNFNTestResult result;\n", "file_path": "posix/fntest/pubnub_fntest_runner.c", "rank": 56, "score": 88016.55137536234 }, { "content": " enum PNFNTestResult result;\n", "file_path": "windows/fntest/pubnub_fntest_runner.c", "rank": 57, "score": 88016.55137536234 }, { "content": " enum PNFNTestResult result;\n", "file_path": "freertos/fntest/pubnub_fntest_runner.c", "rank": 58, "score": 88016.55137536234 }, { "content": " char const* name;\n", "file_path": "windows/fntest/pubnub_fntest_runner.c", "rank": 59, "score": 87972.25277159746 }, { "content": " char const* name;\n", "file_path": "posix/fntest/pubnub_fntest_runner.c", "rank": 60, "score": 87972.25277159746 }, { "content": " char const *name;\n", "file_path": "freertos/fntest/pubnub_fntest_runner.c", "rank": 61, "score": 87972.25277159746 }, { "content": " unsigned test;\n", "file_path": "freertos/fntest/pubnub_fntest_runner.c", "rank": 62, "score": 87307.41821346668 }, { "content": "static struct TestData m_aTest[] = {\n\n LIST_TEST(simple_connect_and_send_over_single_channel),\n\n LIST_TEST(connect_and_send_over_several_channels_simultaneously),\n\n LIST_TEST(simple_connect_and_send_over_single_channel_in_group),\n\n LIST_TEST(connect_and_send_over_several_channels_in_group_simultaneously),\n\n LIST_TEST(connect_and_send_over_channel_in_group_and_single_channel_simultaneously),\n\n LIST_TEST(connect_and_send_over_channel_in_group_and_multi_channel_simultaneously),\n\n LIST_TEST(simple_connect_and_receiver_over_single_channel),\n\n LIST_TEST(connect_and_receive_over_several_channels_simultaneously),\n\n LIST_TEST(simple_connect_and_receiver_over_single_channel_in_group),\n\n LIST_TEST(connect_and_receive_over_several_channels_in_group_simultaneously),\n\n LIST_TEST(connect_and_receive_over_channel_in_group_and_single_channel_simultaneously),\n\n LIST_TEST(connect_and_receive_over_channel_in_group_and_multi_channel_simultaneously),\n\n /*\tLIST_TEST(broken_connection_test),\n\n LIST_TEST(broken_connection_test_multi),\n\n LIST_TEST(broken_connection_test_group),\n\n LIST_TEST(broken_connection_test_multi_in_group),\n\n LIST_TEST(broken_connection_test_group_in_group_out),\n\n LIST_TEST(broken_connection_test_group_multichannel_out),*/\n\n\n\n LIST_TEST(complex_send_and_receive_over_several_channels_simultaneously),\n\n LIST_TEST(complex_send_and_receive_over_channel_plus_group_simultaneously),\n\n LIST_TEST(connect_disconnect_and_connect_again),\n\n /*\tLIST_TEST(connect_disconnect_and_connect_again_group),\n\n LIST_TEST(connect_disconnect_and_connect_again_combo),\n\n LIST_TEST(wrong_api_usage),*/\n", "file_path": "posix/fntest/pubnub_fntest_runner.c", "rank": 63, "score": 87303.22882012004 }, { "content": "static struct TestData m_aTest[] = {\n\n LIST_TEST(simple_connect_and_send_over_single_channel),\n\n LIST_TEST(connect_and_send_over_several_channels_simultaneously),\n\n LIST_TEST(simple_connect_and_send_over_single_channel_in_group),\n\n LIST_TEST(connect_and_send_over_several_channels_in_group_simultaneously),\n\n LIST_TEST(connect_and_send_over_channel_in_group_and_single_channel_simultaneously),\n\n LIST_TEST(connect_and_send_over_channel_in_group_and_multi_channel_simultaneously),\n\n LIST_TEST(simple_connect_and_receiver_over_single_channel),\n\n LIST_TEST(connect_and_receive_over_several_channels_simultaneously),\n\n LIST_TEST(simple_connect_and_receiver_over_single_channel_in_group),\n\n LIST_TEST(connect_and_receive_over_several_channels_in_group_simultaneously),\n\n LIST_TEST(connect_and_receive_over_channel_in_group_and_single_channel_simultaneously),\n\n LIST_TEST(connect_and_receive_over_channel_in_group_and_multi_channel_simultaneously),\n\n\n\n LIST_TEST(complex_send_and_receive_over_several_channels_simultaneously),\n\n LIST_TEST(complex_send_and_receive_over_channel_plus_group_simultaneously),\n\n LIST_TEST(connect_disconnect_and_connect_again),\n\n LIST_TEST(connect_disconnect_and_connect_again_group),\n\n LIST_TEST(connect_disconnect_and_connect_again_combo),\n\n LIST_TEST(wrong_api_usage),\n\n LIST_TEST(handling_errors_from_pubnub),\n\n\n\n /* \"Manual-tests\" (require human interaction */\n\n /*\tLIST_TEST(broken_connection_test),\n\n LIST_TEST(broken_connection_test_multi),\n\n LIST_TEST(broken_connection_test_group),\n\n LIST_TEST(broken_connection_test_multi_in_group),\n\n LIST_TEST(broken_connection_test_group_in_group_out),\n\n LIST_TEST(broken_connection_test_group_multichannel_out),\n\n */\n", "file_path": "windows/fntest/pubnub_fntest_runner.c", "rank": 64, "score": 87303.22882012004 }, { "content": "static struct TestData m_aTest[] = {\n\n LIST_TEST(simple_connect_and_send_over_single_channel),\n\n LIST_TEST(connect_and_send_over_several_channels_simultaneously),\n\n LIST_TEST(simple_connect_and_send_over_single_channel_in_group),\n\n LIST_TEST(connect_and_send_over_several_channels_in_group_simultaneously),\n\n LIST_TEST(connect_and_send_over_channel_in_group_and_single_channel_simultaneously),\n\n LIST_TEST(connect_and_send_over_channel_in_group_and_multi_channel_simultaneously),\n\n LIST_TEST(simple_connect_and_receiver_over_single_channel),\n\n LIST_TEST(connect_and_receive_over_several_channels_simultaneously),\n\n LIST_TEST(simple_connect_and_receiver_over_single_channel_in_group),\n\n LIST_TEST(connect_and_receive_over_several_channels_in_group_simultaneously),\n\n LIST_TEST(connect_and_receive_over_channel_in_group_and_single_channel_simultaneously),\n\n LIST_TEST(connect_and_receive_over_channel_in_group_and_multi_channel_simultaneously),\n\n/*\tLIST_TEST(broken_connection_test),\n\n\tLIST_TEST(broken_connection_test_multi),\n\n\tLIST_TEST(broken_connection_test_group),\n\n\tLIST_TEST(broken_connection_test_multi_in_group),\n\n\tLIST_TEST(broken_connection_test_group_in_group_out),\n\n\tLIST_TEST(broken_connection_test_group_multichannel_out),*/\n\n \n\n LIST_TEST(complex_send_and_receive_over_several_channels_simultaneously),\n\n LIST_TEST(complex_send_and_receive_over_channel_plus_group_simultaneously),\n\n LIST_TEST(connect_disconnect_and_connect_again),\n\n/*\tLIST_TEST(connect_disconnect_and_connect_again_group),\n\n\tLIST_TEST(connect_disconnect_and_connect_again_combo),\n\n\tLIST_TEST(wrong_api_usage),*/\n", "file_path": "freertos/fntest/pubnub_fntest_runner.c", "rank": 65, "score": 87303.22882012004 }, { "content": "\tCHAR Name[ADAPTER_NAME_LENGTH];\n", "file_path": "freertos/samples/WinPCap/Packet32.h", "rank": 66, "score": 87074.98592164299 }, { "content": "\tCHAR Name[ADAPTER_NAME_LENGTH];\n", "file_path": "freertos/fntest/WinPCap/Packet32.h", "rank": 67, "score": 87074.98592164299 }, { "content": "#define TEST_COUNT (sizeof m_aTest / sizeof m_aTest[0])\n\n\n\n\n", "file_path": "freertos/fntest/pubnub_fntest_runner.c", "rank": 68, "score": 86418.14883407322 }, { "content": "#define TEST_COUNT (sizeof m_aTest / sizeof m_aTest[0])\n\n\n", "file_path": "windows/fntest/pubnub_fntest_runner.c", "rank": 69, "score": 86418.14883407322 }, { "content": "#define TEST_COUNT (sizeof m_aTest / sizeof m_aTest[0])\n\n\n\n\n", "file_path": "posix/fntest/pubnub_fntest_runner.c", "rank": 70, "score": 86418.14883407322 }, { "content": "struct TestData {\n\n PF_Test_T pf;\n\n char const *name;\n\n TaskHandle_t task;\n", "file_path": "freertos/fntest/pubnub_fntest_runner.c", "rank": 71, "score": 86414.22108591176 }, { "content": "struct TestData {\n\n PF_Test_T pf;\n\n char const* name;\n\n pthread_t pth;\n\n enum PNFNTestResult result;\n", "file_path": "posix/fntest/pubnub_fntest_runner.c", "rank": 72, "score": 86414.22108591176 }, { "content": "struct TestData {\n\n PF_Test_T pf;\n\n char const* name;\n\n HANDLE pth;\n\n enum PNFNTestResult result;\n", "file_path": "windows/fntest/pubnub_fntest_runner.c", "rank": 73, "score": 86414.22108591176 }, { "content": "\tchar name[122];\n", "file_path": "freertos/samples/WinPCap/pcap/namedb.h", "rank": 74, "score": 86209.28270137732 }, { "content": "\tchar name[122];\n", "file_path": "freertos/fntest/WinPCap/pcap/namedb.h", "rank": 75, "score": 86209.28270137732 }, { "content": "\tchar *name;\t\t/* name to hand to \"pcap_open_live()\" */\n", "file_path": "freertos/fntest/WinPCap/pcap/pcap.h", "rank": 76, "score": 86209.28270137732 }, { "content": "\tchar *name;\t\t/* name to hand to \"pcap_open_live()\" */\n", "file_path": "freertos/samples/WinPCap/pcap/pcap.h", "rank": 77, "score": 86209.28270137732 }, { "content": "struct caller {\n\n virtual void callme(context& ctx, pubnub_res result) = 0;\n\n virtual ~caller() {}\n\n};\n\ntemplate <class T> class caller_adaptor : public caller {\n\npublic:\n\n caller_adaptor(T t)\n\n : d_t(t)\n\n {\n\n }\n\n void callme(context& ctx, pubnub_res result) { d_t(ctx, result); }\n\n caller* clone() { return new caller_adaptor(d_t); }\n\n virtual ~caller_adaptor() {}\n\n\n\nprivate:\n\n T d_t;\n\n};\n", "file_path": "cpp/pubnub.hpp", "rank": 78, "score": 82808.82735384957 }, { "content": " /// The implementation class will be different for\n\n /// different platforms - C++11 being one platform\n\n class impl;\n\n\n\n futres(pubnub_t* pb, context& ctx, pubnub_res initial);\n\n ~futres();\n\n\n\n /// Gets the last (or latest) result of the transaction.\n\n pubnub_res last_result();\n\n\n\n /// Starts the await. Only useful for the callback interface\n\n void start_await();\n\n\n\n /// Ends the await of the transaction to end and returns the\n\n /// final result (outcome)\n\n pubnub_res end_await();\n\n\n\n /// Awaits the end of transaction and returns its final result\n\n /// (outcome).\n\n pubnub_res await()\n\n {\n\n start_await();\n", "file_path": "cpp/pubnub.hpp", "rank": 79, "score": 82681.41234565117 }, { "content": " class context {\n\n pubnub_qt d_pbqt;\n\n public:\n\n /** Create the context, that will use @p pubkey as its\n\n publish key and @subkey as its subscribe key for its\n\n lifetime. These cannot be changed, to use another\n\n pair, create a new context.\n\n */\n\n context(std::string pubkey, std::string subkey);\n\n\n\n context(std::string pubkey, std::string subkey, std::string origin) :\n\n context(pubkey, subkey) {\n\n set_origin(origin);\n\n }\n\n\n\n /** Sets the origin to @p origin on this context. This may fail.\n\n To reset to default, pass an empty string.\n\n */\n\n int set_origin(std::string const &origin) {\n\n d_pbqt.set_origin(QString::fromStdString(origin));\n", "file_path": "qt/pubnub.hpp", "rank": 80, "score": 82677.1338224984 }, { "content": "class futres {\n\npublic:\n", "file_path": "cpp/pubnub.hpp", "rank": 81, "score": 82677.1338224984 }, { "content": "class context;\n\n\n\n#if __cplusplus < 201103L\n\n// See what we had to deal with? :)\n\n\n\ntemplate <class R, class T, class A, class B>\n", "file_path": "cpp/pubnub.hpp", "rank": 82, "score": 82677.1338224984 }, { "content": "class tribool {\n\npublic:\n\n enum not_set_t { not_set = 2 };\n\n tribool()\n\n : d_3log(not_set)\n\n {\n\n }\n\n tribool(enum pubnub_tribool v)\n\n : d_3log(v)\n\n {\n\n }\n\n tribool(bool v)\n\n : d_3log(v)\n\n {\n\n }\n\n tribool(not_set_t)\n\n : d_3log(not_set)\n\n {\n\n }\n\n\n", "file_path": "cpp/pubnub.hpp", "rank": 83, "score": 82677.1338224984 }, { "content": " class context;\n\n\n\n /** A future (pending) result of a Pubnub\n\n * transaction/operation/request. It is somewhat similar to the\n\n * std::future<> from C++11.\n\n *\n\n * It has the same interface for both Pubnub C client's \"sync\" and\n\n * \"callback\" interfaces, so the C++ user code is always the same,\n\n * you just select the \"back-end\" during the build.\n\n */\n", "file_path": "qt/pubnub.hpp", "rank": 84, "score": 82677.1338224984 }, { "content": "class subloop {\n\npublic:\n\n /** Creates a subscribe loop, ready to do the looping. We\n\n assume that the @p ctx Pubnub context will be valid\n\n throughout the lifetime of this object.\n\n\n\n @param ctx The context to use for the subscribe loop.\n\n @param channel The channel to subscribe to in the loop\n\n */\n\n subloop(context& ctx, std::string channel);\n\n\n\n /** Rather uneventful */\n\n ~subloop();\n\n\n\n /** Fetches one message in a subscribe loop.\n\n\n\n @par Basic usage\n\n @snippet pubnub_subloop_sample.cpp Fetch - pull interface\n\n\n\n @param [out] o_msg String with the fetched message\n", "file_path": "cpp/pubnub.hpp", "rank": 85, "score": 82677.1338224984 }, { "content": "struct pbcc_context;\n\n\n\n/** @mainpage Pubnub C-core for Qt\n\n\n\n This is the C-core implementation of the Pubnub client\n\n for the Qt framework.\n\n\n\n The user interface class to use is \\ref pubnub_qt.\n\n*/\n\n\n\n\n\n/** Pubnub client \"context\" for Qt.\n\n *\n\n * Represents a Pubnub \"context\". One context handles at most\n\n * one Pubnub API transaction/operation at a time.\n\n * It is similar in the way it works with other C-core Pubnub\n\n * clients, but there are a few differences that are Qt-specific.\n\n *\n\n * Unlike the C++ wrapper, which wraps a \"full featured\" C-core\n\n * platform, this is a \"Qt-native C-core\" of sorts. It provides\n", "file_path": "qt/pubnub_qt.h", "rank": 86, "score": 81723.23548514833 }, { "content": "class context {\n\npublic:\n\n /** Create the context, that will use @p pubkey as its\n\n publish key and @subkey as its subscribe key for its\n\n lifetime. These cannot be changed, to use another\n\n pair, create a new context.\n\n @see pubnub_alloc, pubnub_init\n\n */\n\n context(std::string pubkey, std::string subkey)\n\n : d_pubk(pubkey)\n\n , d_ksub(subkey)\n\n {\n\n pubnub_mutex_init(d_mutex);\n\n d_pb = pubnub_alloc();\n\n if (0 == d_pb) {\n\n throw std::bad_alloc();\n\n }\n\n pubnub_init(d_pb, d_pubk.c_str(), d_ksub.c_str());\n\n }\n\n\n", "file_path": "cpp/pubnub_common.hpp", "rank": 87, "score": 81593.1895610239 }, { "content": "class caller_keeper {\n\n caller* d_pcaller;\n\n\n\npublic:\n\n caller_keeper()\n\n : d_pcaller(0)\n\n {\n\n }\n\n caller_keeper(caller* pc)\n\n : d_pcaller(pc)\n\n {\n\n PUBNUB_ASSERT_OPT(pc != 0);\n\n }\n\n caller_keeper(caller_keeper& x)\n\n : d_pcaller(x.d_pcaller)\n\n {\n\n x.d_pcaller = 0;\n\n }\n\n void operator=(caller_keeper& x)\n\n {\n", "file_path": "cpp/pubnub.hpp", "rank": 88, "score": 81593.1895610239 }, { "content": "/// Possible proxy types\n\nenum proxy_type {\n\n /// HTTP GET proxy - the simplest\n\n http_get_proxy,\n\n /// HTTP CONNECT - tunnel proxy\n\n http_connect_proxy,\n\n /// No proxy at all\n\n none_proxy,\n\n};\n\n\n\n/// Return C-core proxy type from C++ (wrapper) proxy type\n\ninline enum pubnub_proxy_type ccore_proxy_type(proxy_type prtp)\n\n{\n\n switch (prtp) {\n\n case http_get_proxy:\n\n return pbproxyHTTP_GET;\n\n case http_connect_proxy:\n\n return pbproxyHTTP_CONNECT;\n\n default:\n\n return pbproxyNONE;\n\n }\n\n}\n\n#endif\n\n\n\n/** A wrapper class for subscribe options, enabling a nicer\n\n usage. Something like:\n\n\n\n pn.subscribe(chan, subscribe_options().heartbeat(412));\n\n*/\n", "file_path": "cpp/pubnub_common.hpp", "rank": 89, "score": 80686.9635449494 }, { "content": "enum ssl_opt {\n\n /// Should the PubNub client establish the connection to\n\n /// PubNub using SSL? (default: YES)\n\n useSSL = 0x01,\n\n /// When SSL is enabled, should the client fallback to a\n\n /// non-SSL connection if it experiences issues handshaking\n\n /// across local proxies, firewalls, etc? (default: YES)\n\n ignoreSecureConnectionRequirement = 0x02\n\n};\n\ninline ssl_opt operator|(ssl_opt l, ssl_opt r)\n\n{\n\n return static_cast<ssl_opt>(static_cast<int>(l) | static_cast<int>(r));\n\n}\n\ninline ssl_opt operator&(ssl_opt l, ssl_opt r)\n\n{\n\n return static_cast<ssl_opt>(static_cast<int>(l) & static_cast<int>(r));\n\n}\n\n\n\n#if PUBNUB_PROXY_API\n", "file_path": "cpp/pubnub_common.hpp", "rank": 90, "score": 80686.9635449494 }, { "content": "/// Posible settings for (usage of) blocking I/O\n\nenum blocking_io {\n\n /// Use blocking I/O\n\n blocking,\n\n /// Use non-blocking I/O\n\n non_blocking\n\n};\n\n\n\n/** Options for SSL/TLS transport. These are designed to be used as\n\n * \"bit-masks\", for which purpose there are overloaded `&` and `|`\n\n * (bit-and and bit-or) operators.\n\n */\n", "file_path": "cpp/pubnub_common.hpp", "rank": 91, "score": 80686.9635449494 }, { "content": "class QSslError;\n\nQT_END_NAMESPACE\n\n\n\n\n", "file_path": "qt/pubnub_qt.h", "rank": 92, "score": 80551.0524605333 }, { "content": " class sense {\n\n futres d_ft;\n\n pubnub_res d_result;\n\n char const *d_expr;\n\n char const *d_fname;\n\n long d_line;\n\n public:\n\n sense(futres ft, char const *expr, char const *fname, long line) \n\n : d_ft(std::move(ft))\n\n , d_result(PNR_TIMEOUT) \n\n , d_expr(expr)\n\n , d_fname(fname)\n\n , d_line(line)\n\n {}\n\n\n\n sense &in(std::chrono::milliseconds deadline) {\n\n bool trans_finished(wait_for(d_ft, deadline, d_result));\n\n if(trans_finished) { \n\n check_result_for_exceptions(d_ft, d_result, d_fname, d_line, d_expr);\n\n }\n", "file_path": "cpp/fntest/pubnub_fntest.hpp", "rank": 93, "score": 80551.0524605333 }, { "content": "class QNetworkReply;\n", "file_path": "qt/pubnub_qt.h", "rank": 94, "score": 80551.0524605333 }, { "content": " class expect {\n\n T d_t;\n\n char const *d_expr;\n\n char const *d_fname;\n\n long d_line;\n\n bool d_checked;\n\n char const *d_descr;\n\n \n\n std::string make_description(char const *op, T expected) {\n\n std::stringstream stream;\n\n stream << std::boolalpha << \n\n \"For expression '\" << d_expr << \"'\" << \n\n std::endl << \" in file: \" << d_fname << \" line: \" << d_line;\n\n if (d_descr) {\n\n stream << std::endl << \" description: \" << d_descr;\n\n }\n\n stream << std::endl << \" with check: '\" << op <<\n\n \"', got: \" << d_t << \", expected: \" << expected;\n\n return stream.str();\n\n }\n", "file_path": "cpp/fntest/pubnub_fntest.hpp", "rank": 95, "score": 80551.0524605333 }, { "content": "class publish_options {\n\n pubnub_publish_options d_;\n\n std::string d_ciphkey;\n\n std::string d_mtdt;\n\n\n\npublic:\n\n /** Default options for publish via GET */\n\n publish_options() { d_ = pubnub_publish_defopts(); }\n\n publish_options& store(bool stor)\n\n {\n\n d_.store = stor;\n\n return *this;\n\n }\n\n publish_options& cipher_key(std::string ciphkey)\n\n {\n\n d_ciphkey = ciphkey;\n\n d_.cipher_key = d_ciphkey.c_str();\n\n return *this;\n\n }\n\n publish_options& replicate(unsigned rplct)\n", "file_path": "cpp/pubnub_common.hpp", "rank": 96, "score": 80551.0524605333 }, { "content": "class subscribe_options {\n\n pubnub_subscribe_options d_;\n\n std::string d_chgrp;\n\n\n\npublic:\n\n subscribe_options() { d_ = pubnub_subscribe_defopts(); }\n\n subscribe_options& channel_group(std::string const& chgroup)\n\n {\n\n d_chgrp = chgroup;\n\n d_.channel_group = d_chgrp.empty() ? 0 : d_chgrp.c_str();\n\n return *this;\n\n }\n\n subscribe_options& channel_group(std::vector<std::string> const& chgroup)\n\n {\n\n return channel_group(join(chgroup));\n\n }\n\n subscribe_options& heartbeat(unsigned hb_interval)\n\n {\n\n d_.heartbeat = hb_interval;\n\n return *this;\n\n }\n\n pubnub_subscribe_options data() { return d_; }\n\n};\n\n\n\n\n\n/** A wrapper class for publish options, enabling a nicer\n\n usage. Something like:\n\n\n\n pn.publish(chan, message, publish_options().store(false));\n\n*/\n", "file_path": "cpp/pubnub_common.hpp", "rank": 97, "score": 80551.0524605333 }, { "content": "class here_now_options {\n\n pubnub_here_now_options d_;\n\n std::string d_chgrp;\n\n\n\npublic:\n\n here_now_options() { d_ = pubnub_here_now_defopts(); }\n\n here_now_options& channel_group(std::string const& chgroup)\n\n {\n\n d_chgrp = chgroup;\n\n d_.channel_group = d_chgrp.empty() ? 0 : d_chgrp.c_str();\n\n return *this;\n\n }\n\n here_now_options& channel_group(std::vector<std::string> const& chgroup)\n\n {\n\n return channel_group(join(chgroup));\n\n }\n\n here_now_options& disable_uuids(bool disable_uuids)\n\n {\n\n d_.disable_uuids = disable_uuids;\n\n return *this;\n", "file_path": "cpp/pubnub_common.hpp", "rank": 98, "score": 80551.0524605333 }, { "content": "class history_options {\n\n pubnub_history_options d_;\n\n std::string d_strt;\n\n std::string d_ender;\n\n\n\npublic:\n\n history_options() { d_ = pubnub_history_defopts(); }\n\n history_options& string_token(bool token_string)\n\n {\n\n d_.string_token = token_string;\n\n return *this;\n\n }\n\n history_options& count(int cnt)\n\n {\n\n d_.count = cnt;\n\n return *this;\n\n }\n\n history_options& reverse(bool rev)\n\n {\n\n d_.reverse = rev;\n", "file_path": "cpp/pubnub_common.hpp", "rank": 99, "score": 80551.0524605333 } ]
C++
RecoEgamma/EgammaTools/plugins/HGCalPhotonIDValueMapProducer.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
#include <memory> #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/stream/EDProducer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Utilities/interface/StreamID.h" #include "DataFormats/Common/interface/ValueMap.h" #include "DataFormats/EgammaCandidates/interface/Photon.h" #include "DataFormats/EgammaCandidates/interface/PhotonFwd.h" #include "RecoEgamma/EgammaTools/interface/HGCalEgammaIDHelper.h" #include "RecoEgamma/EgammaTools/interface/LongDeps.h" class HGCalPhotonIDValueMapProducer : public edm::stream::EDProducer<> { public: explicit HGCalPhotonIDValueMapProducer(const edm::ParameterSet&); ~HGCalPhotonIDValueMapProducer() override; static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); private: void beginStream(edm::StreamID) override; void produce(edm::Event&, const edm::EventSetup&) override; void endStream() override; edm::EDGetTokenT<edm::View<reco::Photon>> photonsToken_; float radius_; static const std::vector<std::string> valuesProduced_; std::map<const std::string, std::vector<float>> maps_; std::unique_ptr<HGCalEgammaIDHelper> phoIDHelper_; }; const std::vector<std::string> HGCalPhotonIDValueMapProducer::valuesProduced_ = { "seedEt", "seedEnergy", "seedEnergyEE", "seedEnergyFH", "seedEnergyBH", "pcaEig1", "pcaEig2", "pcaEig3", "pcaSig1", "pcaSig2", "pcaSig3", "sigmaUU", "sigmaVV", "sigmaEE", "sigmaPP", "nLayers", "firstLayer", "lastLayer", "e4oEtot", "layerEfrac10", "layerEfrac90", "measuredDepth", "expectedDepth", "expectedSigma", "depthCompatibility", "caloIsoRing0", "caloIsoRing1", "caloIsoRing2", "caloIsoRing3", "caloIsoRing4", }; HGCalPhotonIDValueMapProducer::HGCalPhotonIDValueMapProducer(const edm::ParameterSet& iConfig) : photonsToken_(consumes<edm::View<reco::Photon>>(iConfig.getParameter<edm::InputTag>("photons"))), radius_(iConfig.getParameter<double>("pcaRadius")) { for(const auto& key : valuesProduced_) { maps_[key] = {}; produces<edm::ValueMap<float>>(key); } phoIDHelper_.reset(new HGCalEgammaIDHelper(iConfig, consumesCollector())); } HGCalPhotonIDValueMapProducer::~HGCalPhotonIDValueMapProducer() { } void HGCalPhotonIDValueMapProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) { using namespace edm; Handle<edm::View<reco::Photon>> photonsH; iEvent.getByToken(photonsToken_, photonsH); for(auto&& kv : maps_) { kv.second.clear(); kv.second.reserve(photonsH->size()); } phoIDHelper_->eventInit(iEvent,iSetup); for(const auto& pho : *photonsH) { if(pho.isEB()) { for(auto&& kv : maps_) { kv.second.push_back(0.); } } else { phoIDHelper_->computeHGCAL(pho, radius_); if (phoIDHelper_->sigmaUU() == -1){ for(auto&& kv : maps_) { kv.second.push_back(0.); } continue; } hgcal::LongDeps ld(phoIDHelper_->energyPerLayer(radius_, true)); float measuredDepth, expectedDepth, expectedSigma; float depthCompatibility = phoIDHelper_->clusterDepthCompatibility(ld, measuredDepth, expectedDepth, expectedSigma); float seed_tot_energy = ld.energyEE() + ld.energyFH() + ld.energyBH(); const double div_cosh_eta = pho.superCluster()->seed()->position().rho() / pho.superCluster()->seed()->position().r(); maps_["seedEt"].push_back(seed_tot_energy * div_cosh_eta ); maps_["seedEnergy"].push_back(seed_tot_energy); maps_["seedEnergyEE"].push_back(ld.energyEE()); maps_["seedEnergyFH"].push_back(ld.energyFH()); maps_["seedEnergyBH"].push_back(ld.energyBH()); maps_["pcaEig1"].push_back(phoIDHelper_->eigenValues()(0)); maps_["pcaEig2"].push_back(phoIDHelper_->eigenValues()(1)); maps_["pcaEig3"].push_back(phoIDHelper_->eigenValues()(2)); maps_["pcaSig1"].push_back(phoIDHelper_->sigmas()(0)); maps_["pcaSig2"].push_back(phoIDHelper_->sigmas()(1)); maps_["pcaSig3"].push_back(phoIDHelper_->sigmas()(2)); maps_["sigmaUU"].push_back(phoIDHelper_->sigmaUU()); maps_["sigmaVV"].push_back(phoIDHelper_->sigmaVV()); maps_["sigmaEE"].push_back(phoIDHelper_->sigmaEE()); maps_["sigmaPP"].push_back(phoIDHelper_->sigmaPP()); maps_["nLayers"].push_back(ld.nLayers()); maps_["firstLayer"].push_back(ld.firstLayer()); maps_["lastLayer"].push_back(ld.lastLayer()); maps_["e4oEtot"].push_back(ld.e4oEtot()); maps_["layerEfrac10"].push_back(ld.layerEfrac10()); maps_["layerEfrac90"].push_back(ld.layerEfrac90()); maps_["measuredDepth"].push_back(measuredDepth); maps_["expectedDepth"].push_back(expectedDepth); maps_["expectedSigma"].push_back(expectedSigma); maps_["depthCompatibility"].push_back(depthCompatibility); maps_["caloIsoRing0"].push_back(phoIDHelper_->getIsolationRing(0)); maps_["caloIsoRing1"].push_back(phoIDHelper_->getIsolationRing(1)); maps_["caloIsoRing2"].push_back(phoIDHelper_->getIsolationRing(2)); maps_["caloIsoRing3"].push_back(phoIDHelper_->getIsolationRing(3)); maps_["caloIsoRing4"].push_back(phoIDHelper_->getIsolationRing(4)); } } if ( maps_.size() != valuesProduced_.size() ) { throw cms::Exception("HGCalPhotonIDValueMapProducer") << "We have a miscoded value map producer, since map size changed"; } for(auto&& kv : maps_) { if ( kv.second.size() != photonsH->size() ) { throw cms::Exception("HGCalPhotonIDValueMapProducer") << "We have a miscoded value map producer, since the variable " << kv.first << " wasn't filled."; } auto out = std::make_unique<edm::ValueMap<float>>(); edm::ValueMap<float>::Filler filler(*out); filler.insert(photonsH, kv.second.begin(), kv.second.end()); filler.fill(); iEvent.put(std::move(out), kv.first); } } void HGCalPhotonIDValueMapProducer::beginStream(edm::StreamID) { } void HGCalPhotonIDValueMapProducer::endStream() { } void HGCalPhotonIDValueMapProducer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; desc.add<edm::InputTag>("photons", edm::InputTag("photonsFromMultiCl")); desc.add<double>("pcaRadius", 3.0); desc.add<std::vector<std::string>>("variables", valuesProduced_); desc.add<std::vector<double>>("dEdXWeights")->setComment("This must be copied from dEdX_weights in RecoLocalCalo.HGCalRecProducers.HGCalRecHit_cfi"); desc.add<unsigned int>("isoNRings", 5); desc.add<double>("isoDeltaR", 0.15); desc.add<double>("isoDeltaRmin", 0.0); desc.add<edm::InputTag>("EERecHits", edm::InputTag("HGCalRecHit","HGCEERecHits")); desc.add<edm::InputTag>("FHRecHits", edm::InputTag("HGCalRecHit","HGCHEFRecHits")); desc.add<edm::InputTag>("BHRecHits", edm::InputTag("HGCalRecHit","HGCHEBRecHits")); descriptions.add("hgcalPhotonIDValueMap", desc); } DEFINE_FWK_MODULE(HGCalPhotonIDValueMapProducer);
#include <memory> #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/stream/EDProducer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Utilities/interface/StreamID.h" #include "DataFormats/Common/interface/ValueMap.h" #include "DataFormats/EgammaCandidates/interface/Photon.h" #include "DataFormats/EgammaCandidates/interface/PhotonFwd.h" #include "RecoEgamma/EgammaTools/interface/HGCalEgammaIDHelper.h" #include "RecoEgamma/EgammaTools/interface/LongDeps.h" class HGCalPhotonIDValueMapProducer : public edm::stream::EDProducer<> { public: explicit HGCalPhotonIDValueMapProducer(const edm::ParameterSet&); ~HGCalPhotonIDValueMapProducer() override; static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); private: void beginStream(edm::StreamID) override; void produce(edm::Event&, const edm::EventSetup&) override; void endStream() override; edm::EDGetTokenT<edm::View<reco::Photon>> photonsToken_; float radius_; static const std::vector<std::string> valuesProduced_; std::map<const std::string, std::vector<float>> maps_; std::unique_ptr<HGCalEgammaIDHelper> phoIDHelper_; };
HGCalPhotonIDValueMapProducer::HGCalPhotonIDValueMapProducer(const edm::ParameterSet& iConfig) : photonsToken_(consumes<edm::View<reco::Photon>>(iConfig.getParameter<edm::InputTag>("photons"))), radius_(iConfig.getParameter<double>("pcaRadius")) { for(const auto& key : valuesProduced_) { maps_[key] = {}; produces<edm::ValueMap<float>>(key); } phoIDHelper_.reset(new HGCalEgammaIDHelper(iConfig, consumesCollector())); } HGCalPhotonIDValueMapProducer::~HGCalPhotonIDValueMapProducer() { } void HGCalPhotonIDValueMapProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) { using namespace edm; Handle<edm::View<reco::Photon>> photonsH; iEvent.getByToken(photonsToken_, photonsH); for(auto&& kv : maps_) { kv.second.clear(); kv.second.reserve(photonsH->size()); } phoIDHelper_->eventInit(iEvent,iSetup); for(const auto& pho : *photonsH) { if(pho.isEB()) { for(auto&& kv : maps_) { kv.second.push_back(0.); } } else { phoIDHelper_->computeHGCAL(pho, radius_); if (phoIDHelper_->sigmaUU() == -1){ for(auto&& kv : maps_) { kv.second.push_back(0.); } continue; } hgcal::LongDeps ld(phoIDHelper_->energyPerLayer(radius_, true)); float measuredDepth, expectedDepth, expectedSigma; float depthCompatibility = phoIDHelper_->clusterDepthCompatibility(ld, measuredDepth, expectedDepth, expectedSigma); float seed_tot_energy = ld.energyEE() + ld.energyFH() + ld.energyBH(); const double div_cosh_eta = pho.superCluster()->seed()->position().rho() / pho.superCluster()->seed()->position().r(); maps_["seedEt"].push_back(seed_tot_energy * div_cosh_eta ); maps_["seedEnergy"].push_back(seed_tot_energy); maps_["seedEnergyEE"].push_back(ld.energyEE()); maps_["seedEnergyFH"].push_back(ld.energyFH()); maps_["seedEnergyBH"].push_back(ld.energyBH()); maps_["pcaEig1"].push_back(phoIDHelper_->eigenValues()(0)); maps_["pcaEig2"].push_back(phoIDHelper_->eigenValues()(1)); maps_["pcaEig3"].push_back(phoIDHelper_->eigenValues()(2)); maps_["pcaSig1"].push_back(phoIDHelper_->sigmas()(0)); maps_["pcaSig2"].push_back(phoIDHelper_->sigmas()(1)); maps_["pcaSig3"].push_back(phoIDHelper_->sigmas()(2)); maps_["sigmaUU"].push_back(phoIDHelper_->sigmaUU()); maps_["sigmaVV"].push_back(phoIDHelper_->sigmaVV()); maps_["sigmaEE"].push_back(phoIDHelper_->sigmaEE()); maps_["sigmaPP"].push_back(phoIDHelper_->sigmaPP()); maps_["nLayers"].push_back(ld.nLayers()); maps_["firstLayer"].push_back(ld.firstLayer()); maps_["lastLayer"].push_back(ld.lastLayer()); maps_["e4oEtot"].push_back(ld.e4oEtot()); maps_["layerEfrac10"].push_back(ld.layerEfrac10()); maps_["layerEfrac90"].push_back(ld.layerEfrac90()); maps_["measuredDepth"].push_back(measuredDepth); maps_["expectedDepth"].push_back(expectedDepth); maps_["expectedSigma"].push_back(expectedSigma); maps_["depthCompatibility"].push_back(depthCompatibility); maps_["caloIsoRing0"].push_back(phoIDHelper_->getIsolationRing(0)); maps_["caloIsoRing1"].push_back(phoIDHelper_->getIsolationRing(1)); maps_["caloIsoRing2"].push_back(phoIDHelper_->getIsolationRing(2)); maps_["caloIsoRing3"].push_back(phoIDHelper_->getIsolationRing(3)); maps_["caloIsoRing4"].push_back(phoIDHelper_->getIsolationRing(4)); } } if ( maps_.size() != valuesProduced_.size() ) { throw cms::Exception("HGCalPhotonIDValueMapProducer") << "We have a miscoded value map producer, since map size changed"; } for(auto&& kv : maps_) { if ( kv.second.size() != photonsH->size() ) { throw cms::Exception("HGCalPhotonIDValueMapProducer") << "We have a miscoded value map producer, since the variable " << kv.first << " wasn't filled."; } auto out = std::make_unique<edm::ValueMap<float>>(); edm::ValueMap<float>::Filler filler(*out); filler.insert(photonsH, kv.second.begin(), kv.second.end()); filler.fill(); iEvent.put(std::move(out), kv.first); } } void HGCalPhotonIDValueMapProducer::beginStream(edm::StreamID) { } void HGCalPhotonIDValueMapProducer::endStream() { } void HGCalPhotonIDValueMapProducer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; desc.add<edm::InputTag>("photons", edm::InputTag("photonsFromMultiCl")); desc.add<double>("pcaRadius", 3.0); desc.add<std::vector<std::string>>("variables", valuesProduced_); desc.add<std::vector<double>>("dEdXWeights")->setComment("This must be copied from dEdX_weights in RecoLocalCalo.HGCalRecProducers.HGCalRecHit_cfi"); desc.add<unsigned int>("isoNRings", 5); desc.add<double>("isoDeltaR", 0.15); desc.add<double>("isoDeltaRmin", 0.0); desc.add<edm::InputTag>("EERecHits", edm::InputTag("HGCalRecHit","HGCEERecHits")); desc.add<edm::InputTag>("FHRecHits", edm::InputTag("HGCalRecHit","HGCHEFRecHits")); desc.add<edm::InputTag>("BHRecHits", edm::InputTag("HGCalRecHit","HGCHEBRecHits")); descriptions.add("hgcalPhotonIDValueMap", desc); } DEFINE_FWK_MODULE(HGCalPhotonIDValueMapProducer);
const std::vector<std::string> HGCalPhotonIDValueMapProducer::valuesProduced_ = { "seedEt", "seedEnergy", "seedEnergyEE", "seedEnergyFH", "seedEnergyBH", "pcaEig1", "pcaEig2", "pcaEig3", "pcaSig1", "pcaSig2", "pcaSig3", "sigmaUU", "sigmaVV", "sigmaEE", "sigmaPP", "nLayers", "firstLayer", "lastLayer", "e4oEtot", "layerEfrac10", "layerEfrac90", "measuredDepth", "expectedDepth", "expectedSigma", "depthCompatibility", "caloIsoRing0", "caloIsoRing1", "caloIsoRing2", "caloIsoRing3", "caloIsoRing4", };
assignment_statement
[]
C++
google/cloud/dialogflow_cx/internal/flows_logging_decorator.cc
GoogleCloudPlatform/google-cloud-cpp
c4fc35de9e15f95b1dbf585f1c96de5dba609e2b
#include "google/cloud/dialogflow_cx/internal/flows_logging_decorator.h" #include "google/cloud/internal/log_wrapper.h" #include "google/cloud/status_or.h" #include <google/cloud/dialogflow/cx/v3/flow.grpc.pb.h> #include <memory> namespace google { namespace cloud { namespace dialogflow_cx_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN FlowsLogging::FlowsLogging(std::shared_ptr<FlowsStub> child, TracingOptions tracing_options, std::set<std::string> components) : child_(std::move(child)), tracing_options_(std::move(tracing_options)), components_(std::move(components)) {} StatusOr<google::cloud::dialogflow::cx::v3::Flow> FlowsLogging::CreateFlow( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::CreateFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this]( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::CreateFlowRequest const& request) { return child_->CreateFlow(context, request); }, context, request, __func__, tracing_options_); } Status FlowsLogging::DeleteFlow( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::DeleteFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this]( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::DeleteFlowRequest const& request) { return child_->DeleteFlow(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::dialogflow::cx::v3::ListFlowsResponse> FlowsLogging::ListFlows( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::ListFlowsRequest const& request) { return google::cloud::internal::LogWrapper( [this]( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::ListFlowsRequest const& request) { return child_->ListFlows(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::dialogflow::cx::v3::Flow> FlowsLogging::GetFlow( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::GetFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::GetFlowRequest const& request) { return child_->GetFlow(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::dialogflow::cx::v3::Flow> FlowsLogging::UpdateFlow( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::UpdateFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this]( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::UpdateFlowRequest const& request) { return child_->UpdateFlow(context, request); }, context, request, __func__, tracing_options_); } future<StatusOr<google::longrunning::Operation>> FlowsLogging::AsyncTrainFlow( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::dialogflow::cx::v3::TrainFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this]( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::dialogflow::cx::v3::TrainFlowRequest const& request) { return child_->AsyncTrainFlow(cq, std::move(context), request); }, cq, std::move(context), request, __func__, tracing_options_); } StatusOr<google::cloud::dialogflow::cx::v3::FlowValidationResult> FlowsLogging::ValidateFlow( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::ValidateFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::ValidateFlowRequest const& request) { return child_->ValidateFlow(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::dialogflow::cx::v3::FlowValidationResult> FlowsLogging::GetFlowValidationResult( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::GetFlowValidationResultRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::dialogflow::cx::v3:: GetFlowValidationResultRequest const& request) { return child_->GetFlowValidationResult(context, request); }, context, request, __func__, tracing_options_); } future<StatusOr<google::longrunning::Operation>> FlowsLogging::AsyncImportFlow( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::dialogflow::cx::v3::ImportFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this]( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::dialogflow::cx::v3::ImportFlowRequest const& request) { return child_->AsyncImportFlow(cq, std::move(context), request); }, cq, std::move(context), request, __func__, tracing_options_); } future<StatusOr<google::longrunning::Operation>> FlowsLogging::AsyncExportFlow( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::dialogflow::cx::v3::ExportFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this]( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::dialogflow::cx::v3::ExportFlowRequest const& request) { return child_->AsyncExportFlow(cq, std::move(context), request); }, cq, std::move(context), request, __func__, tracing_options_); } future<StatusOr<google::longrunning::Operation>> FlowsLogging::AsyncGetOperation( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::GetOperationRequest const& request) { return google::cloud::internal::LogWrapper( [this](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::GetOperationRequest const& request) { return child_->AsyncGetOperation(cq, std::move(context), request); }, cq, std::move(context), request, __func__, tracing_options_); } future<Status> FlowsLogging::AsyncCancelOperation( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::CancelOperationRequest const& request) { return google::cloud::internal::LogWrapper( [this](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::CancelOperationRequest const& request) { return child_->AsyncCancelOperation(cq, std::move(context), request); }, cq, std::move(context), request, __func__, tracing_options_); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } } }
#include "google/cloud/dialogflow_cx/internal/flows_logging_decorator.h" #include "google/cloud/internal/log_wrapper.h" #include "google/cloud/status_or.h" #include <google/cloud/dialogflow/cx/v3/flow.grpc.pb.h> #include <memory> namespace google { namespace cloud { namespace dialogflow_cx_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN FlowsLogging::FlowsLogging(std::shared_ptr<FlowsStub> child, TracingOptions tracing_options, std::set<std::string> components) : child_(std::move(child)), tracing_options_(std::move(tracing_options)), components_(std::move(components)) {} StatusOr<google::cloud::dialogflow::cx::v3::Flow> FlowsLogging::CreateFlow( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::CreateFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this]( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::CreateFlowRequest const& request) { return child_->CreateFlow(context, request); }, context, request, __func__, tracing_options_); } Status FlowsLogging::DeleteFlow( grpc::ClientContext& co
text, google::cloud::dialogflow::cx::v3::ExportFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this]( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::dialogflow::cx::v3::ExportFlowRequest const& request) { return child_->AsyncExportFlow(cq, std::move(context), request); }, cq, std::move(context), request, __func__, tracing_options_); } future<StatusOr<google::longrunning::Operation>> FlowsLogging::AsyncGetOperation( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::GetOperationRequest const& request) { return google::cloud::internal::LogWrapper( [this](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::GetOperationRequest const& request) { return child_->AsyncGetOperation(cq, std::move(context), request); }, cq, std::move(context), request, __func__, tracing_options_); } future<Status> FlowsLogging::AsyncCancelOperation( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::CancelOperationRequest const& request) { return google::cloud::internal::LogWrapper( [this](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::CancelOperationRequest const& request) { return child_->AsyncCancelOperation(cq, std::move(context), request); }, cq, std::move(context), request, __func__, tracing_options_); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } } }
ntext, google::cloud::dialogflow::cx::v3::DeleteFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this]( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::DeleteFlowRequest const& request) { return child_->DeleteFlow(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::dialogflow::cx::v3::ListFlowsResponse> FlowsLogging::ListFlows( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::ListFlowsRequest const& request) { return google::cloud::internal::LogWrapper( [this]( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::ListFlowsRequest const& request) { return child_->ListFlows(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::dialogflow::cx::v3::Flow> FlowsLogging::GetFlow( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::GetFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::GetFlowRequest const& request) { return child_->GetFlow(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::dialogflow::cx::v3::Flow> FlowsLogging::UpdateFlow( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::UpdateFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this]( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::UpdateFlowRequest const& request) { return child_->UpdateFlow(context, request); }, context, request, __func__, tracing_options_); } future<StatusOr<google::longrunning::Operation>> FlowsLogging::AsyncTrainFlow( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::dialogflow::cx::v3::TrainFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this]( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::dialogflow::cx::v3::TrainFlowRequest const& request) { return child_->AsyncTrainFlow(cq, std::move(context), request); }, cq, std::move(context), request, __func__, tracing_options_); } StatusOr<google::cloud::dialogflow::cx::v3::FlowValidationResult> FlowsLogging::ValidateFlow( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::ValidateFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::ValidateFlowRequest const& request) { return child_->ValidateFlow(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::dialogflow::cx::v3::FlowValidationResult> FlowsLogging::GetFlowValidationResult( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::GetFlowValidationResultRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::dialogflow::cx::v3:: GetFlowValidationResultRequest const& request) { return child_->GetFlowValidationResult(context, request); }, context, request, __func__, tracing_options_); } future<StatusOr<google::longrunning::Operation>> FlowsLogging::AsyncImportFlow( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::dialogflow::cx::v3::ImportFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this]( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::dialogflow::cx::v3::ImportFlowRequest const& request) { return child_->AsyncImportFlow(cq, std::move(context), request); }, cq, std::move(context), request, __func__, tracing_options_); } future<StatusOr<google::longrunning::Operation>> FlowsLogging::AsyncExportFlow( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> con
random
[ { "content": "// A generic request. Fields with a \"testonly_\" prefix are used for testing but\n\n// are not used in the real code.\n\nstruct Request {\n\n std::string testonly_page_token;\n\n void set_page_token(std::string token) {\n\n testonly_page_token = std::move(token);\n\n }\n\n};\n\n\n", "file_path": "google/cloud/internal/pagination_range_test.cc", "rank": 0, "score": 207467.42439246766 }, { "content": "# How-to Guide: Forks and Pull Requests\n\n\n\nWe wrote this document because many Googlers do not use GitHub on a daily basis.\n\nIf you are an experienced GitHub contributor much of the information here will\n\nbe familiar to you, feel free to skip it. If you are new to GitHub or have not\n\nused it in a while and want a refresher this might be useful.\n\n\n\n## Creating a Fork\n\n\n\nIn this project we use the (more or less) standard\n\n[GitHub workflow][workflow-link]:\n\n\n\nYou create a [fork][fork-link] of [google-cloud-cpp][repo-link]. You can think\n\nof a \"fork\" as a full copy of the original repository, including all its history\n\nand branches. Then [clone][about-clone] that fork into your workstation:\n\n```console\n\ngit clone [email protected]:YOUR-USER-NAME/google-cloud-cpp.git\n\n```\n\n\n\nThis creates a *second* copy of the original repository, with all its history\n\nand branches. You can create new branches in this copy, change the history of\n\nbranches (you can, but don't!), and generally do all the version control things\n\nyou may be used to. Note that these local changes do not affect either of the\n\nprevious two copies.\n\n\n\nThe cloned repo that you created in the previous step will have its `origin`\n\nset to your forked repo. You should now tell git about the the main\n\n`upstream` repo, which you'll use to pull commits made by others in order to\n\nkeep your local repo and fork up to date.\n\n\n\n```console\n\ngit remote add upstream [email protected]:googleapis/google-cloud-cpp.git\n\ngit remote -v # Should show 'origin' (your fork) and 'upstream' (main repo)\n\n```\n\n\n\nTo pull new commits from `upstream` into your local repo and\n\n[sync your fork][syncing-a-fork] you can do the following:\n\n\n\n```console\n\ngit checkout main\n\ngit pull --ff-only upstream main\n\ngit push # Pushes new commits up to your fork on GitHub\n\n```\n\n\n\n> :warning: you probably want to do this periodically, and almost certainly\n\n> before starting any new branches. Keeping your default branch (aka `main`)\n\n> in sync is important to make your pull requests easy to review.\n\n\n", "file_path": "doc/contributor/howto-guide-forks-and-pull-requests.md", "rank": 1, "score": 192167.76057437572 }, { "content": "## The GCS Library represents optional parameters as variadic function arguments.\n\n\n\n**Status**: accepted\n\n\n\n**Context**: most APIs in the GCS library have a number of optional parameters,\n\nfor example, the API can use `ifMetagenerationMatch` to apply an operation only\n\nif the metadata generation matches a given number. The question arose of how to\n\nrepresent these parameters, as properties that we modify in the client or\n\nobject, or as per-request parameters in the function used to access the API.\n\nThat is, we had two proposals, one where the application would write code like\n\nthis:\n\n\n\n```C++\n\nvoid AppCode(Bucket b, FixedArgument1 foo, FixedArgument2 bar) {\n\n b.ApiName(\n\n foo, bar, storage::IfMetagenerationMatch(7), UserProject(\"my-project\"));\n\n```\n\n\n\nvs. code like this:\n\n\n\n```C++\n\nvoid AppCode(Bucket b, FixedArgument1 foo, FixedArgument2 bar) {\n\n // Create a new bucket handle that applies the given optional parameters to\n\n // all requests.\n\n auto bucket = b.ApplyModifiers(\n\n storage::IfMetagenerationMatch(7), UserProject(\"my-project\"))\n\n bucket.ApiName(foo, bar);\n\n}\n\n```\n\n\n\n**Decision**: The parameters are passed as variadic arguments into any function\n\nthat needs them. That is, all APIs look like this:\n\n\n\n```C++\n\nclass Bucket /* or Object as applicable */ { public:\n\ntemplate <typename... Parameters>\n\nReturnType ApiName(\n\n FixedArgument1 a1, FixedArgument2 a2,\n\n Parameters&&... p);\n\n```\n\n\n\nand are used like this:\n\n\n\n```C++\n\nvoid AppCode(Bucket b, FixedArgument1 foo, FixedArgument2 bar) {\n\n b.ApiName(\n\n foo, bar, storage::IfMetagenerationMatch(7), UserProject(\"my-project\"));\n\n```\n\n\n\n**Consequences**: The advantages of this approach include:\n\n\n\n- It is easier to use parameters in an API, it does not require to create a new\n\n bucket or object or client handle just for changing the parameters in one\n\n request.\n\n\n\nThe downsides include:\n\n\n\n- All APIs become templates, we should be careful not to create massive header\n\n files that are slow to compile.\n\n- It is harder to overload APIs.\n\n- It is not clear how other optional parameters of the APIs, such as timeouts,\n\n fit with this structure.\n", "file_path": "doc/adr/2018-06-18-storage-request-parameters-are-function-arguments.md", "rank": 2, "score": 192166.64204763513 }, { "content": "## Preparing to make a pull requests\n\n\n\nChanges to the main repository must go through a review by one of the project\n\nowners (even project owners have their code reviewed by a peer). To submit your\n\nchange for review you need to create a pull request. Typically you start by:\n\n\n\n1. Picking an existing [GitHub bug][mastering-issues] to work on.\n\n1. Create a new [branch][about-branches] for each feature (or bug fix).\n\n ```console\n\n git checkout main\n\n git checkout -b my-feature-branch\n\n git push -u origin my-feature-branch # Tells fork on GitHub about new branch\n\n # make your changes\n\n git push\n\n ```\n\n1. And then submit a [pull-request][about-pull-requests] to merge your branch\n\n into `googleapis/google-cloud-cpp`.\n\n1. Your reviewers may ask questions, suggest improvements or alternatives. You\n\n address those by either answering the questions in the review or\n\n **adding more [commits][about-commits]** to your branch and `git push` -ing\n\n those commits to your fork.\n\n\n\n## Merging the changes\n\n\n\nEventually the reviewers accept your changes, and they are merged into the\n\n`main` branch. We use \"squash commits\", where all your commits become a single\n\ncommit into the default branch. A project owner needs to merge your changes,\n\nif you are a project owner, the expectation is that you will perform the merge\n\noperation, and update the commit comments to something readable.\n\n\n\n## When the PR requires more work\n\n\n\nThe previous steps described a happy case for a PR (hopefully for most PRs),\n\nwhere no build failures or conflicts are detected in the PR. The next two\n\nsections explain what to do when things are not so rosy.\n\n\n", "file_path": "doc/contributor/howto-guide-forks-and-pull-requests.md", "rank": 3, "score": 192162.61479758014 }, { "content": "### Reproducing CI build failures\n\n\n\nIf you are a Googler, when you submit your pull request a number (about 50 at\n\nlast count) of builds start automatically. For non-Googlers, a project owner\n\nneeds to kickoff these builds for you.\n\n\n\nWe run so many builds because we need to test the libraries under as many\n\ncompilers, platforms, and configurations as possible. Our customers will not\n\nnecessarily use the same environment as we do to build and run these libraries.\n\n\n\nThere is a completely separate\n\n[guide](howto-guide-running-ci-builds-locally.md) explaining how to run these\n\nbuilds locally in case one fails. It's also a good idea to run some of these\n\nbuilds locally, before sending a PR, to verify that your change (likely) works.\n\nRunning the following builds locally should identify most common issues:\n\n\n\n```\n\nci/cloudbuild/build.sh -t checkers-pr\n\nci/cloudbuild/build.sh -t clang-tidy-pr\n\nci/cloudbuild/build.sh -t asan-pr\n\n```\n\n\n\nIn general, most of the builds for Linux can be reproduced locally using the\n\nbuild name as an argument to `build.sh`.\n\n\n\n[workflow-link]: https://guides.github.com/introduction/flow/\n\n[fork-link]: https://guides.github.com/activities/forking/\n\n[repo-link]: https://github.com/googleapis/google-cloud-cpp.git\n\n[mastering-issues]: https://guides.github.com/features/issues/\n\n[about-clone]: https://help.github.com/articles/cloning-a-repository/\n\n[about-branches]: https://help.github.com/articles/about-branches/\n\n[about-pull-requests]: https://help.github.com/articles/about-pull-requests/\n\n[about-commits]: https://help.github.com/desktop/guides/contributing-to-projects/committing-and-reviewing-changes-to-your-project/#about-commits\n\n[about-rebase]: https://help.github.com/articles/about-git-rebase/\n\n[syncing-a-fork]: https://help.github.com/articles/syncing-a-fork/\n", "file_path": "doc/contributor/howto-guide-forks-and-pull-requests.md", "rank": 4, "score": 192160.7862622576 }, { "content": "### Resolving Conflicts and Rebasing\n\n\n\nFrom time to time your pull request may have conflicts with the destination\n\nbranch (likely `main`). If so, we request that you [rebase][about-rebase]\n\nyour branch instead of merging. The reviews can become very confusing if you\n\nmerge during a pull request. You should first ensure that your `main`\n\nbranch has all the latest commits by syncing your fork (see above), then do\n\nthe following:\n\n\n\n```shell\n\ngit checkout my-feature-branch\n\ngit rebase main\n\ngit push --force-with-lease\n\n```\n\n\n\nIf there are conflicts, the `git rebase` command will show you the conflicts.\n\nThese will not be automatically resolved, if they were, `git rebase` would not\n\nhave required human intervention! You will need to edit the code to resolve\n\nthese conflicts, potentially `git add` or `git rm` files as needed. Once the\n\nconflicts are resolved you `git add` the files to indicate the conflict\n\nresolution is complete, and then continue the rebase with:\n\n\n\n```\n\ngit rebase --continue\n\n```\n\n\n\nIf there are multiple commits in your PR this process runs for each commit.\n\n\n", "file_path": "doc/contributor/howto-guide-forks-and-pull-requests.md", "rank": 5, "score": 192155.74559032996 }, { "content": "class MockLogBackend : public google::cloud::LogBackend {\n\n public:\n\n void Process(google::cloud::LogRecord const& lr) override {\n\n ProcessWithOwnership(lr);\n\n }\n\n MOCK_METHOD(void, ProcessWithOwnership, (google::cloud::LogRecord),\n\n (override));\n\n};\n\n\n\n/// @test Verify that CurlRequest logs when requested.\n\nTEST(CurlRequestTest, Logging) {\n\n // Prepare the Log subsystem to receive mock calls:\n\n auto mock_logger = std::make_shared<MockLogBackend>();\n\n auto backend_id = google::cloud::LogSink::Instance().AddBackend(mock_logger);\n\n\n\n std::string log_messages;\n\n EXPECT_CALL(*mock_logger, ProcessWithOwnership)\n\n .WillRepeatedly([&log_messages](google::cloud::LogRecord const& lr) {\n\n log_messages += lr.message;\n\n log_messages += \"\\n\";\n", "file_path": "google/cloud/storage/tests/curl_request_integration_test.cc", "rank": 6, "score": 189651.9396353045 }, { "content": "namespace google {\n\nnamespace cloud {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\nnamespace internal {\n\n\n\n/// Uses SFINAE to call Policy.Setup(context) when possible.\n\ntemplate <typename Policy, typename = void>\n\nstruct SetupContext {\n\n static void Setup(Policy&, grpc::ClientContext&) {}\n\n};\n\n\n\ntemplate <typename Policy>\n\nstruct SetupContext<Policy, void_t<decltype(std::declval<Policy>().Setup(\n\n std::declval<grpc::ClientContext&>()))>> {\n\n static void Setup(Policy& p, grpc::ClientContext& context) {\n\n p.Setup(context);\n\n }\n\n};\n\n\n", "file_path": "google/cloud/internal/setup_context.h", "rank": 7, "score": 177430.40590250492 }, { "content": "namespace google {\n\nnamespace cloud {\n\nnamespace storage {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\nnamespace internal {\n\n\n\n/// Represent a memory range. Use to upload with low copying\n\nusing ConstBuffer = absl::Span<char const>;\n\n\n\n/// Represent a sequence of memory ranges. Use to upload with low copying.\n\nusing ConstBufferSequence = std::vector<ConstBuffer>;\n\n\n\n/// The total number of bytes in the buffer sequence.\n\ninline std::size_t TotalBytes(ConstBufferSequence const& s) {\n\n return std::accumulate(\n\n s.begin(), s.end(), std::size_t{0},\n\n [](std::size_t a, ConstBuffer const& b) { return a + b.size(); });\n\n}\n\n\n\n/// Remove @p count bytes at the start of @p s\n\nvoid PopFrontBytes(ConstBufferSequence& s, std::size_t count);\n\n\n\n} // namespace internal\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END\n\n} // namespace storage\n\n} // namespace cloud\n", "file_path": "google/cloud/storage/internal/const_buffer.h", "rank": 8, "score": 175489.84691556843 }, { "content": "namespace google {\n\nnamespace cloud {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\nnamespace internal {\n\n\n\n/// A simple representation of request metadata.\n\nusing StreamingRpcMetadata = std::multimap<std::string, std::string>;\n\n\n\n/// Return interesting bits of metadata stored in the client context.\n\nStreamingRpcMetadata GetRequestMetadataFromContext(\n\n grpc::ClientContext const& context);\n\n\n\n} // namespace internal\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END\n\n} // namespace cloud\n", "file_path": "google/cloud/internal/grpc_request_metadata.h", "rank": 9, "score": 175373.78469547292 }, { "content": "namespace google {\n\nnamespace cloud {\n\nnamespace dialogflow_es {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\n/// Option to use with `google::cloud::Options`.\n\nstruct ContextsRetryPolicyOption {\n\n using Type = std::shared_ptr<ContextsRetryPolicy>;\n\n};\n\n\n\n/// Option to use with `google::cloud::Options`.\n\nstruct ContextsBackoffPolicyOption {\n\n using Type = std::shared_ptr<BackoffPolicy>;\n\n};\n\n\n\n/// Option to use with `google::cloud::Options`.\n\nstruct ContextsConnectionIdempotencyPolicyOption {\n\n using Type = std::shared_ptr<ContextsConnectionIdempotencyPolicy>;\n\n};\n\n\n\nusing ContextsPolicyOptionList =\n\n OptionList<ContextsRetryPolicyOption, ContextsBackoffPolicyOption,\n\n ContextsConnectionIdempotencyPolicyOption>;\n\n\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END\n\n} // namespace dialogflow_es\n\n} // namespace cloud\n", "file_path": "google/cloud/dialogflow_es/contexts_options.h", "rank": 10, "score": 175328.42744744048 }, { "content": "// This class is a regular type that contains the path, headers, and query\n\n// parameters for use in sending a request to a REST-ful service. It is intended\n\n// to be passed to the appropriate HTTP method on RestClient, along with a\n\n// payload if required.\n\nclass RestRequest {\n\n public:\n\n using HttpHeaders = std::unordered_map<std::string, std::vector<std::string>>;\n\n using HttpParameters = std::vector<std::pair<std::string, std::string>>;\n\n\n\n RestRequest();\n\n explicit RestRequest(std::string path);\n\n RestRequest(std::string path, HttpHeaders headers);\n\n RestRequest(std::string path, HttpParameters parameters);\n\n RestRequest(std::string path, HttpHeaders headers, HttpParameters parameters);\n\n\n\n std::string const& path() const { return path_; }\n\n HttpHeaders const& headers() const { return headers_; }\n\n HttpParameters const& parameters() const { return parameters_; }\n\n\n\n RestRequest& SetPath(std::string path) &;\n\n RestRequest&& SetPath(std::string path) && {\n\n return std::move(SetPath(std::move(path)));\n\n }\n\n\n", "file_path": "google/cloud/internal/rest_request.h", "rank": 11, "score": 174473.40333738798 }, { "content": "namespace google {\n\nnamespace cloud {\n\nnamespace accesscontextmanager {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\n/// Option to use with `google::cloud::Options`.\n\nstruct AccessContextManagerRetryPolicyOption {\n\n using Type = std::shared_ptr<AccessContextManagerRetryPolicy>;\n\n};\n\n\n\n/// Option to use with `google::cloud::Options`.\n\nstruct AccessContextManagerBackoffPolicyOption {\n\n using Type = std::shared_ptr<BackoffPolicy>;\n\n};\n\n\n\n/// Option to use with `google::cloud::Options`.\n\nstruct AccessContextManagerPollingPolicyOption {\n\n using Type = std::shared_ptr<PollingPolicy>;\n\n};\n\n\n\n/// Option to use with `google::cloud::Options`.\n\nstruct AccessContextManagerConnectionIdempotencyPolicyOption {\n\n using Type = std::shared_ptr<AccessContextManagerConnectionIdempotencyPolicy>;\n\n};\n\n\n\nusing AccessContextManagerPolicyOptionList =\n\n OptionList<AccessContextManagerRetryPolicyOption,\n\n AccessContextManagerBackoffPolicyOption,\n\n AccessContextManagerPollingPolicyOption,\n\n AccessContextManagerConnectionIdempotencyPolicyOption>;\n\n\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END\n\n} // namespace accesscontextmanager\n\n} // namespace cloud\n", "file_path": "google/cloud/accesscontextmanager/access_context_manager_options.h", "rank": 12, "score": 173285.06011840474 }, { "content": " using Type = std::shared_ptr<BackoffPolicy>;\n", "file_path": "google/cloud/dialogflow_es/contexts_options.h", "rank": 13, "score": 172097.87147548355 }, { "content": "class CurlRequest {\n\n public:\n\n CurlRequest() = default;\n\n ~CurlRequest();\n\n\n\n CurlRequest(CurlRequest&&) = default;\n\n CurlRequest& operator=(CurlRequest&&) = default;\n\n\n\n /**\n\n * Makes the prepared request.\n\n *\n\n * This function can be called multiple times on the same request.\n\n *\n\n * @return The response HTTP error code, the headers and an empty payload.\n\n */\n\n StatusOr<HttpResponse> MakeRequest(std::string const& payload) &&;\n\n\n\n /// @copydoc MakeRequest(std::string const&)\n\n StatusOr<HttpResponse> MakeUploadRequest(ConstBufferSequence payload) &&;\n\n\n", "file_path": "google/cloud/storage/internal/curl_request.h", "rank": 14, "score": 171379.90037489726 }, { "content": "class GenericRequest\n\n : public GenericRequestBase<Derived, CustomHeader, Fields, IfMatchEtag,\n\n IfNoneMatchEtag, QuotaUser, UserIp,\n\n Options...> {\n\n public:\n\n using Super =\n\n GenericRequestBase<Derived, CustomHeader, Fields, IfMatchEtag,\n\n IfNoneMatchEtag, QuotaUser, UserIp, Options...>;\n\n\n\n template <typename H, typename... T>\n\n Derived& set_multiple_options(H&& h, T&&... tail) {\n\n Super::set_option(std::forward<H>(h));\n\n return set_multiple_options(std::forward<T>(tail)...);\n\n }\n\n\n\n Derived& set_multiple_options() { return *static_cast<Derived*>(this); }\n\n\n\n template <typename Option>\n\n bool HasOption() const {\n\n return Super::template HasOption<Option>();\n\n }\n\n\n\n template <typename Option>\n\n Option GetOption() const {\n\n return Super::template GetOption<Option>();\n\n }\n\n};\n\n\n\ntemplate <typename Request, typename Option, typename AlwaysVoid = void>\n", "file_path": "google/cloud/storage/internal/generic_request.h", "rank": 15, "score": 171379.90037489723 }, { "content": " static StatusOr<google::storage::v2::StartResumableWriteRequest> ToProto(\n", "file_path": "google/cloud/storage/internal/grpc_object_request_parser.h", "rank": 16, "score": 171341.23026386264 }, { "content": " static StatusOr<google::storage::v2::UpdateBucketRequest> ToProto(\n", "file_path": "google/cloud/storage/internal/grpc_bucket_request_parser.h", "rank": 17, "score": 171341.23026386264 }, { "content": "///\n\n/// Service for managing [Contexts][google.cloud.dialogflow.v2.Context].\n\n///\n\n/// @par Equality\n\n///\n\n/// Instances of this class created via copy-construction or copy-assignment\n\n/// always compare equal. Instances created with equal\n\n/// `std::shared_ptr<*Connection>` objects compare equal. Objects that compare\n\n/// equal share the same underlying resources.\n\n///\n\n/// @par Performance\n\n///\n\n/// Creating a new instance of this class is a relatively expensive operation,\n\n/// new objects establish new connections to the service. In contrast,\n\n/// copy-construction, move-construction, and the corresponding assignment\n\n/// operations are relatively efficient as the copies share all underlying\n\n/// resources.\n\n///\n\n/// @par Thread Safety\n\n///\n\n/// Concurrent access to different instances of this class, even if they compare\n\n/// equal, is guaranteed to work. Two or more threads operating on the same\n\n/// instance of this class is not guaranteed to work. Since copy-construction\n\n/// and move-construction is a relatively efficient operation, consider using\n\n/// such a copy when using this class from multiple threads.\n\n///\n\nclass ContextsClient {\n\n public:\n\n explicit ContextsClient(std::shared_ptr<ContextsConnection> connection,\n\n Options opts = {});\n\n ~ContextsClient();\n\n\n\n //@{\n\n // @name Copy and move support\n\n ContextsClient(ContextsClient const&) = default;\n\n ContextsClient& operator=(ContextsClient const&) = default;\n\n ContextsClient(ContextsClient&&) = default;\n\n ContextsClient& operator=(ContextsClient&&) = default;\n\n //@}\n\n\n\n //@{\n\n // @name Equality\n\n friend bool operator==(ContextsClient const& a, ContextsClient const& b) {\n\n return a.connection_ == b.connection_;\n\n }\n\n friend bool operator!=(ContextsClient const& a, ContextsClient const& b) {\n", "file_path": "google/cloud/dialogflow_es/contexts_client.h", "rank": 18, "score": 171331.7185994285 }, { "content": "class ContextsConnection {\n\n public:\n\n virtual ~ContextsConnection() = 0;\n\n\n\n virtual Options options() { return Options{}; }\n\n\n\n virtual StreamRange<google::cloud::dialogflow::v2::Context> ListContexts(\n\n google::cloud::dialogflow::v2::ListContextsRequest request);\n\n\n\n virtual StatusOr<google::cloud::dialogflow::v2::Context> GetContext(\n\n google::cloud::dialogflow::v2::GetContextRequest const& request);\n\n\n\n virtual StatusOr<google::cloud::dialogflow::v2::Context> CreateContext(\n\n google::cloud::dialogflow::v2::CreateContextRequest const& request);\n\n\n\n virtual StatusOr<google::cloud::dialogflow::v2::Context> UpdateContext(\n\n google::cloud::dialogflow::v2::UpdateContextRequest const& request);\n\n\n\n virtual Status DeleteContext(\n\n google::cloud::dialogflow::v2::DeleteContextRequest const& request);\n", "file_path": "google/cloud/dialogflow_es/contexts_connection.h", "rank": 19, "score": 171316.62368839775 }, { "content": "namespace google {\n\nnamespace cloud {\n\nnamespace dialogflow_es_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\n/// Define the gRPC status code semantics for retrying requests.\n\nstruct ContextsRetryTraits {\n\n static inline bool IsPermanentFailure(google::cloud::Status const& status) {\n\n return status.code() != StatusCode::kOk &&\n\n status.code() != StatusCode::kUnavailable;\n\n }\n\n};\n\n\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END\n\n} // namespace dialogflow_es_internal\n\n} // namespace cloud\n", "file_path": "google/cloud/dialogflow_es/internal/contexts_retry_traits.h", "rank": 20, "score": 171297.54493265797 }, { "content": "namespace google {\n\nnamespace cloud {\n\nnamespace dialogflow_es_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nstd::shared_ptr<ContextsStub> CreateDefaultContextsStub(\n\n google::cloud::CompletionQueue cq, Options const& options);\n\n\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END\n\n} // namespace dialogflow_es_internal\n\n} // namespace cloud\n", "file_path": "google/cloud/dialogflow_es/internal/contexts_stub_factory.h", "rank": 21, "score": 171297.54493265797 }, { "content": "namespace google {\n\nnamespace cloud {\n\nnamespace storage {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\nnamespace internal {\n\n\n\n/**\n\n * Inject request query parameters into grpc::ClientContext.\n\n *\n\n * The REST API has a number of \"standard\" query parameters that are not part of\n\n * the gRPC request body, instead they are send via metadata headers in the gRPC\n\n * request.\n\n *\n\n * @see https://cloud.google.com/apis/docs/system-parameters\n\n */\n\ntemplate <typename Request>\n\nvoid ApplyQueryParameters(grpc::ClientContext& context, Request const& request,\n\n std::string const& prefix = std::string{}) {\n\n // The gRPC API has a single field for the `QuotaUser` parameter, while the\n\n // JSON API has two:\n\n // https://cloud.google.com/storage/docs/json_api/v1/parameters#quotaUser\n\n // Fortunately the semantics are to use `quotaUser` if set, so we can set\n\n // the `UserIp` value into the `quota_user` field, and overwrite it if\n\n // `QuotaUser` is also set. A bit bizarre, but at least it is backwards\n\n // compatible.\n\n if (request.template HasOption<QuotaUser>()) {\n\n context.AddMetadata(\"x-goog-quota-user\",\n\n request.template GetOption<QuotaUser>().value());\n\n } else if (request.template HasOption<UserIp>()) {\n\n context.AddMetadata(\"x-goog-quota-user\",\n\n request.template GetOption<UserIp>().value());\n\n }\n\n\n\n if (request.template HasOption<Fields>()) {\n\n auto field_mask = request.template GetOption<Fields>().value();\n\n if (!prefix.empty()) field_mask = prefix + \"(\" + field_mask + \")\";\n\n context.AddMetadata(\"x-goog-fieldmask\", std::move(field_mask));\n\n }\n\n}\n\n\n\n} // namespace internal\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END\n\n} // namespace storage\n\n} // namespace cloud\n", "file_path": "google/cloud/storage/internal/grpc_configure_client_context.h", "rank": 22, "score": 171297.54493265797 }, { "content": "namespace google {\n\nnamespace cloud {\n\nnamespace dialogflow_es_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nOptions ContextsDefaultOptions(Options options);\n\n\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END\n\n} // namespace dialogflow_es_internal\n\n} // namespace cloud\n", "file_path": "google/cloud/dialogflow_es/internal/contexts_option_defaults.h", "rank": 23, "score": 171297.54493265797 }, { "content": " int parallel_requests = 10;\n", "file_path": "google/cloud/bigtable/benchmarks/benchmark_options.h", "rank": 24, "score": 170016.52955096524 }, { "content": " static google::storage::v2::UpdateBucketRequest ToProto(\n", "file_path": "google/cloud/storage/internal/grpc_bucket_request_parser.h", "rank": 25, "score": 170016.52955096524 }, { "content": " static google::storage::v2::QueryWriteStatusRequest ToProto(\n", "file_path": "google/cloud/storage/internal/grpc_object_request_parser.h", "rank": 26, "score": 170016.52955096524 }, { "content": " using Type = std::shared_ptr<AccessContextManagerConnectionIdempotencyPolicy>;\n", "file_path": "google/cloud/accesscontextmanager/access_context_manager_options.h", "rank": 27, "score": 169972.02395780283 }, { "content": "namespace google {\n\nnamespace cloud {\n\nnamespace storage {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\nnamespace internal {\n\n\n\n/// Convert JSON requests to gRPC requests and gRPC responses to JSON responses\n\nstruct GrpcHmacKeyRequestParser {\n\n static google::storage::v2::CreateHmacKeyRequest ToProto(\n\n CreateHmacKeyRequest const&);\n\n static CreateHmacKeyResponse FromProto(\n\n google::storage::v2::CreateHmacKeyResponse const&);\n\n static google::storage::v2::DeleteHmacKeyRequest ToProto(\n\n DeleteHmacKeyRequest const&);\n\n static google::storage::v2::GetHmacKeyRequest ToProto(\n\n GetHmacKeyRequest const&);\n\n static google::storage::v2::ListHmacKeysRequest ToProto(\n\n ListHmacKeysRequest const&);\n\n static ListHmacKeysResponse FromProto(\n\n google::storage::v2::ListHmacKeysResponse const&);\n\n static google::storage::v2::UpdateHmacKeyRequest ToProto(\n\n UpdateHmacKeyRequest const&);\n\n};\n\n\n\n} // namespace internal\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END\n\n} // namespace storage\n\n} // namespace cloud\n", "file_path": "google/cloud/storage/internal/grpc_hmac_key_request_parser.h", "rank": 28, "score": 169406.20208340962 }, { "content": "namespace google {\n\nnamespace cloud {\n\nnamespace accesscontextmanager_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nstd::shared_ptr<AccessContextManagerStub> CreateDefaultAccessContextManagerStub(\n\n google::cloud::CompletionQueue cq, Options const& options);\n\n\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END\n\n} // namespace accesscontextmanager_internal\n\n} // namespace cloud\n", "file_path": "google/cloud/accesscontextmanager/internal/access_context_manager_stub_factory.h", "rank": 29, "score": 169363.30732560286 }, { "content": "namespace google {\n\nnamespace cloud {\n\nnamespace accesscontextmanager_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\n/// Define the gRPC status code semantics for retrying requests.\n\nstruct AccessContextManagerRetryTraits {\n\n static inline bool IsPermanentFailure(google::cloud::Status const& status) {\n\n return status.code() != StatusCode::kOk &&\n\n status.code() != StatusCode::kUnavailable;\n\n }\n\n};\n\n\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END\n\n} // namespace accesscontextmanager_internal\n\n} // namespace cloud\n", "file_path": "google/cloud/accesscontextmanager/internal/access_context_manager_retry_traits.h", "rank": 30, "score": 169363.3073256029 }, { "content": "namespace google {\n\nnamespace cloud {\n\nnamespace accesscontextmanager_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nOptions AccessContextManagerDefaultOptions(Options options);\n\n\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END\n\n} // namespace accesscontextmanager_internal\n\n} // namespace cloud\n", "file_path": "google/cloud/accesscontextmanager/internal/access_context_manager_option_defaults.h", "rank": 31, "score": 169363.3073256029 }, { "content": "/// Represents a request to call the `BucketAccessControls: list` API.\n\nclass ListNotificationsRequest\n\n : public GenericRequest<ListNotificationsRequest, UserProject> {\n\n public:\n\n ListNotificationsRequest() = default;\n\n explicit ListNotificationsRequest(std::string bucket)\n\n : bucket_name_(std::move(bucket)) {}\n\n\n\n std::string const& bucket_name() const { return bucket_name_; }\n\n\n\n private:\n\n std::string bucket_name_;\n\n};\n\n\n\nstd::ostream& operator<<(std::ostream& os, ListNotificationsRequest const& r);\n\n\n", "file_path": "google/cloud/storage/internal/notification_requests.h", "rank": 32, "score": 168413.19773737897 }, { "content": "class GetNotificationRequest\n\n : public GenericNotificationRequest<GetNotificationRequest> {\n\n using GenericNotificationRequest::GenericNotificationRequest;\n\n};\n\n\n\nstd::ostream& operator<<(std::ostream& os, GetNotificationRequest const& r);\n\n\n\n/**\n\n * Represents a request to call the `Notifications: delete` API.\n\n */\n", "file_path": "google/cloud/storage/internal/notification_requests.h", "rank": 33, "score": 168405.97584010698 }, { "content": "class GenericRequestBase;\n\n\n\n/**\n\n * Apply any number of options to a request builder.\n\n */\n\ntemplate <typename Builder>\n", "file_path": "google/cloud/storage/internal/generic_request.h", "rank": 34, "score": 168405.97584010698 }, { "content": "class ListObjectsRequest\n\n : public GenericRequest<ListObjectsRequest, MaxResults, Prefix, Delimiter,\n\n IncludeTrailingDelimiter, StartOffset, EndOffset,\n\n Projection, UserProject, Versions> {\n\n public:\n\n ListObjectsRequest() = default;\n\n explicit ListObjectsRequest(std::string bucket_name)\n\n : bucket_name_(std::move(bucket_name)) {}\n\n\n\n std::string const& bucket_name() const { return bucket_name_; }\n\n std::string const& page_token() const { return page_token_; }\n\n ListObjectsRequest& set_page_token(std::string page_token) {\n\n page_token_ = std::move(page_token);\n\n return *this;\n\n }\n\n\n\n private:\n\n std::string bucket_name_;\n\n std::string page_token_;\n\n};\n\n\n\nstd::ostream& operator<<(std::ostream& os, ListObjectsRequest const& r);\n\n\n", "file_path": "google/cloud/storage/internal/object_requests.h", "rank": 35, "score": 168405.97584010698 }, { "content": "class UploadChunkRequest\n\n : public GenericRequest<UploadChunkRequest, UserProject> {\n\n public:\n\n UploadChunkRequest() = default;\n\n\n\n // A non-final chunk\n\n UploadChunkRequest(std::string upload_session_url, std::uint64_t offset,\n\n ConstBufferSequence payload)\n\n : upload_session_url_(std::move(upload_session_url)),\n\n offset_(offset),\n\n payload_(std::move(payload)) {}\n\n\n\n UploadChunkRequest(std::string upload_session_url, std::uint64_t offset,\n\n ConstBufferSequence payload, HashValues full_object_hashes)\n\n : upload_session_url_(std::move(upload_session_url)),\n\n offset_(offset),\n\n upload_size_(offset + TotalBytes(payload)),\n\n payload_(std::move(payload)),\n\n full_object_hashes_(std::move(full_object_hashes)) {}\n\n\n", "file_path": "google/cloud/storage/internal/object_requests.h", "rank": 36, "score": 168405.97584010698 }, { "content": "class UpdateObjectRequest\n\n : public GenericObjectRequest<\n\n UpdateObjectRequest, Generation, EncryptionKey, IfGenerationMatch,\n\n IfGenerationNotMatch, IfMetagenerationMatch, IfMetagenerationNotMatch,\n\n PredefinedAcl, Projection, UserProject> {\n\n public:\n\n UpdateObjectRequest() = default;\n\n explicit UpdateObjectRequest(std::string bucket_name, std::string object_name,\n\n ObjectMetadata metadata)\n\n : GenericObjectRequest(std::move(bucket_name), std::move(object_name)),\n\n metadata_(std::move(metadata)) {}\n\n\n\n /// Returns the request as the JSON API payload.\n\n std::string json_payload() const;\n\n\n\n ObjectMetadata const& metadata() const { return metadata_; }\n\n\n\n private:\n\n ObjectMetadata metadata_;\n\n};\n\n\n\nstd::ostream& operator<<(std::ostream& os, UpdateObjectRequest const& r);\n\n\n\n/**\n\n * Represents a request to the `Objects: compose` API.\n\n */\n", "file_path": "google/cloud/storage/internal/object_requests.h", "rank": 37, "score": 168405.97584010698 }, { "content": "class CreateNotificationRequest\n\n : public GenericRequest<CreateNotificationRequest, UserProject> {\n\n public:\n\n CreateNotificationRequest() = default;\n\n CreateNotificationRequest(std::string bucket, NotificationMetadata metadata)\n\n : bucket_name_(std::move(bucket)), metadata_(std::move(metadata)) {}\n\n\n\n std::string const& bucket_name() const { return bucket_name_; }\n\n std::string json_payload() const { return metadata_.JsonPayloadForInsert(); }\n\n NotificationMetadata const& metadata() const { return metadata_; }\n\n\n\n private:\n\n std::string bucket_name_;\n\n NotificationMetadata metadata_;\n\n};\n\n\n\nstd::ostream& operator<<(std::ostream& os, CreateNotificationRequest const& r);\n\n\n\n/**\n\n * Represents common attributes to multiple `Notifications` request\n\n * types.\n\n *\n\n * The classes to represent requests for the `Notifications: create`,\n\n * `get`, `delete`, `patch`, and `update` APIs have a lot of commonality. This\n\n * template class refactors that code.\n\n */\n\ntemplate <typename Derived>\n", "file_path": "google/cloud/storage/internal/notification_requests.h", "rank": 38, "score": 168405.97584010698 }, { "content": "class ComposeObjectRequest\n\n : public GenericObjectRequest<ComposeObjectRequest, EncryptionKey,\n\n DestinationPredefinedAcl, KmsKeyName,\n\n IfGenerationMatch, IfMetagenerationMatch,\n\n UserProject, WithObjectMetadata> {\n\n public:\n\n ComposeObjectRequest() = default;\n\n explicit ComposeObjectRequest(std::string bucket_name,\n\n std::vector<ComposeSourceObject> source_objects,\n\n std::string destination_object_name);\n\n\n\n std::vector<ComposeSourceObject> source_objects() const {\n\n return source_objects_;\n\n }\n\n\n\n /// Returns the request as the JSON API payload.\n\n std::string JsonPayload() const;\n\n\n\n private:\n\n std::vector<ComposeSourceObject> source_objects_;\n\n};\n\n\n\nstd::ostream& operator<<(std::ostream& os, ComposeObjectRequest const& r);\n\n\n\n/**\n\n * Represents a request to the `Objects: patch` API.\n\n */\n", "file_path": "google/cloud/storage/internal/object_requests.h", "rank": 39, "score": 168405.97584010698 }, { "content": "class PatchObjectRequest\n\n : public GenericObjectRequest<\n\n PatchObjectRequest, Generation, IfGenerationMatch,\n\n IfGenerationNotMatch, IfMetagenerationMatch, IfMetagenerationNotMatch,\n\n PredefinedAcl, EncryptionKey, Projection, UserProject,\n\n // PredefinedDefaultObjectAcl has no effect in an `Objects: patch`\n\n // request. We are keeping it here for backwards compatibility. It\n\n // was introduced in error (should have been PredefinedAcl), and it\n\n // was never documented. The cost of keeping it is small, and there\n\n // is very little motivation to remove it.\n\n PredefinedDefaultObjectAcl> {\n\n public:\n\n PatchObjectRequest() = default;\n\n explicit PatchObjectRequest(std::string bucket_name, std::string object_name,\n\n ObjectMetadata const& original,\n\n ObjectMetadata const& updated);\n\n explicit PatchObjectRequest(std::string bucket_name, std::string object_name,\n\n ObjectMetadataPatchBuilder patch);\n\n\n\n ObjectMetadataPatchBuilder const& patch() const { return patch_; }\n", "file_path": "google/cloud/storage/internal/object_requests.h", "rank": 40, "score": 168405.97584010698 }, { "content": "class DeleteNotificationRequest\n\n : public GenericNotificationRequest<DeleteNotificationRequest> {\n\n using GenericNotificationRequest::GenericNotificationRequest;\n\n};\n\n\n\nstd::ostream& operator<<(std::ostream& os, DeleteNotificationRequest const& r);\n\n\n\n} // namespace internal\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END\n\n} // namespace storage\n\n} // namespace cloud\n\n} // namespace google\n\n\n\n#endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_NOTIFICATION_REQUESTS_H\n", "file_path": "google/cloud/storage/internal/notification_requests.h", "rank": 41, "score": 168405.97584010698 }, { "content": "class DeleteObjectRequest\n\n : public GenericObjectRequest<DeleteObjectRequest, Generation,\n\n IfGenerationMatch, IfGenerationNotMatch,\n\n IfMetagenerationMatch,\n\n IfMetagenerationNotMatch, UserProject> {\n\n public:\n\n using GenericObjectRequest::GenericObjectRequest;\n\n};\n\n\n\nstd::ostream& operator<<(std::ostream& os, DeleteObjectRequest const& r);\n\n\n\n/**\n\n * Represents a request to the `Objects: update` API.\n\n */\n", "file_path": "google/cloud/storage/internal/object_requests.h", "rank": 42, "score": 168405.97584010698 }, { "content": "class DeleteBucketRequest\n\n : public GenericRequest<DeleteBucketRequest, IfMetagenerationMatch,\n\n IfMetagenerationNotMatch, UserProject> {\n\n public:\n\n DeleteBucketRequest() = default;\n\n explicit DeleteBucketRequest(std::string bucket_name)\n\n : bucket_name_(std::move(bucket_name)) {}\n\n\n\n std::string const& bucket_name() const { return bucket_name_; }\n\n\n\n private:\n\n std::string bucket_name_;\n\n};\n\n\n\nstd::ostream& operator<<(std::ostream& os, DeleteBucketRequest const& r);\n\n\n\n/**\n\n * Represents a request to the `Buckets: update` API.\n\n */\n", "file_path": "google/cloud/storage/internal/bucket_requests.h", "rank": 43, "score": 168405.97584010698 }, { "content": "class RewriteObjectRequest\n\n : public GenericRequest<\n\n RewriteObjectRequest, DestinationKmsKeyName, DestinationPredefinedAcl,\n\n EncryptionKey, IfGenerationMatch, IfGenerationNotMatch,\n\n IfMetagenerationMatch, IfMetagenerationNotMatch,\n\n IfSourceGenerationMatch, IfSourceGenerationNotMatch,\n\n IfSourceMetagenerationMatch, IfSourceMetagenerationNotMatch,\n\n MaxBytesRewrittenPerCall, Projection, SourceEncryptionKey,\n\n SourceGeneration, UserProject, WithObjectMetadata> {\n\n public:\n\n RewriteObjectRequest() = default;\n\n RewriteObjectRequest(std::string source_bucket, std::string source_object,\n\n std::string destination_bucket,\n\n std::string destination_object,\n\n std::string rewrite_token)\n\n : source_bucket_(std::move(source_bucket)),\n\n source_object_(std::move(source_object)),\n\n destination_bucket_(std::move(destination_bucket)),\n\n destination_object_(std::move(destination_object)),\n\n rewrite_token_(std::move(rewrite_token)) {}\n", "file_path": "google/cloud/storage/internal/object_requests.h", "rank": 44, "score": 168405.97584010698 }, { "content": "class CreateBucketRequest\n\n : public GenericRequest<CreateBucketRequest, PredefinedAcl,\n\n PredefinedDefaultObjectAcl, Projection,\n\n UserProject> {\n\n public:\n\n CreateBucketRequest() = default;\n\n explicit CreateBucketRequest(std::string project_id, BucketMetadata metadata)\n\n : project_id_(std::move(project_id)), metadata_(std::move(metadata)) {}\n\n\n\n /// Returns the request as the JSON API payload.\n\n std::string json_payload() const;\n\n\n\n std::string const& project_id() const { return project_id_; }\n\n CreateBucketRequest& set_project_id(std::string project_id) {\n\n project_id_ = std::move(project_id);\n\n return *this;\n\n }\n\n\n\n BucketMetadata const& metadata() const { return metadata_; }\n\n CreateBucketRequest& set_metadata(BucketMetadata metadata) {\n", "file_path": "google/cloud/storage/internal/bucket_requests.h", "rank": 45, "score": 168405.97584010698 }, { "content": "class ListBucketsRequest\n\n : public GenericRequest<ListBucketsRequest, MaxResults, Prefix, Projection,\n\n UserProject> {\n\n public:\n\n ListBucketsRequest() = default;\n\n explicit ListBucketsRequest(std::string project_id)\n\n : project_id_(std::move(project_id)) {}\n\n\n\n std::string const& project_id() const { return project_id_; }\n\n std::string const& page_token() const { return page_token_; }\n\n ListBucketsRequest& set_page_token(std::string page_token) {\n\n page_token_ = std::move(page_token);\n\n return *this;\n\n }\n\n\n\n private:\n\n std::string project_id_;\n\n std::string page_token_;\n\n};\n\n\n\nstd::ostream& operator<<(std::ostream& os, ListBucketsRequest const& r);\n\n\n", "file_path": "google/cloud/storage/internal/bucket_requests.h", "rank": 46, "score": 168405.97584010698 }, { "content": "class UpdateBucketRequest\n\n : public GenericRequest<\n\n UpdateBucketRequest, IfMetagenerationMatch, IfMetagenerationNotMatch,\n\n PredefinedAcl, PredefinedDefaultObjectAcl, Projection, UserProject> {\n\n public:\n\n UpdateBucketRequest() = default;\n\n explicit UpdateBucketRequest(BucketMetadata metadata)\n\n : metadata_(std::move(metadata)) {}\n\n\n\n /// Returns the request as the JSON API payload.\n\n std::string json_payload() const;\n\n\n\n BucketMetadata const& metadata() const { return metadata_; }\n\n\n\n private:\n\n BucketMetadata metadata_;\n\n};\n\n\n\nstd::ostream& operator<<(std::ostream& os, UpdateBucketRequest const& r);\n\n\n\n/**\n\n * Represents a request to the `Buckets: patch` API.\n\n */\n", "file_path": "google/cloud/storage/internal/bucket_requests.h", "rank": 47, "score": 168405.97584010698 }, { "content": "class ResumableUploadRequest\n\n : public GenericObjectRequest<\n\n ResumableUploadRequest, ContentEncoding, ContentType,\n\n Crc32cChecksumValue, DisableCrc32cChecksum, DisableMD5Hash,\n\n EncryptionKey, IfGenerationMatch, IfGenerationNotMatch,\n\n IfMetagenerationMatch, IfMetagenerationNotMatch, KmsKeyName,\n\n MD5HashValue, PredefinedAcl, Projection, UseResumableUploadSession,\n\n UserProject, UploadFromOffset, UploadLimit, WithObjectMetadata,\n\n UploadContentLength, AutoFinalize, UploadBufferSize> {\n\n public:\n\n ResumableUploadRequest() = default;\n\n\n\n ResumableUploadRequest(std::string bucket_name, std::string object_name)\n\n : GenericObjectRequest(std::move(bucket_name), std::move(object_name)) {}\n\n};\n\n\n\nstd::ostream& operator<<(std::ostream& os, ResumableUploadRequest const& r);\n\n\n", "file_path": "google/cloud/storage/internal/object_requests.h", "rank": 48, "score": 168405.97584010698 }, { "content": "class CopyObjectRequest\n\n : public GenericRequest<\n\n CopyObjectRequest, DestinationKmsKeyName, DestinationPredefinedAcl,\n\n EncryptionKey, IfGenerationMatch, IfGenerationNotMatch,\n\n IfMetagenerationMatch, IfMetagenerationNotMatch,\n\n IfSourceGenerationMatch, IfSourceGenerationNotMatch,\n\n IfSourceMetagenerationMatch, IfSourceMetagenerationNotMatch,\n\n Projection, SourceGeneration, SourceEncryptionKey, UserProject,\n\n WithObjectMetadata> {\n\n public:\n\n CopyObjectRequest() = default;\n\n CopyObjectRequest(std::string source_bucket, std::string source_object,\n\n std::string destination_bucket,\n\n std::string destination_object)\n\n : source_bucket_(std::move(source_bucket)),\n\n source_object_(std::move(source_object)),\n\n destination_bucket_(std::move(destination_bucket)),\n\n destination_object_(std::move(destination_object)) {}\n\n\n\n std::string const& source_bucket() const { return source_bucket_; }\n", "file_path": "google/cloud/storage/internal/object_requests.h", "rank": 49, "score": 168405.97584010698 }, { "content": "class PatchBucketRequest\n\n : public GenericRequest<\n\n PatchBucketRequest, IfMetagenerationMatch, IfMetagenerationNotMatch,\n\n PredefinedAcl, PredefinedDefaultObjectAcl, Projection, UserProject> {\n\n public:\n\n PatchBucketRequest() = default;\n\n explicit PatchBucketRequest(std::string bucket,\n\n BucketMetadata const& original,\n\n BucketMetadata const& updated);\n\n explicit PatchBucketRequest(std::string bucket,\n\n BucketMetadataPatchBuilder patch);\n\n\n\n BucketMetadataPatchBuilder const& patch() const { return patch_; }\n\n std::string const& bucket() const { return bucket_; }\n\n std::string payload() const { return patch_.BuildPatch(); }\n\n\n\n private:\n\n BucketMetadataPatchBuilder patch_;\n\n std::string bucket_;\n\n};\n\n\n\nstd::ostream& operator<<(std::ostream& os, PatchBucketRequest const& r);\n\n\n\n/**\n\n * Represents a request to the `Buckets: getIamPolicy` API.\n\n */\n", "file_path": "google/cloud/storage/internal/bucket_requests.h", "rank": 50, "score": 168405.97584010698 }, { "content": "class ContextsStub {\n\n public:\n\n virtual ~ContextsStub() = 0;\n\n\n\n virtual StatusOr<google::cloud::dialogflow::v2::ListContextsResponse>\n\n ListContexts(\n\n grpc::ClientContext& context,\n\n google::cloud::dialogflow::v2::ListContextsRequest const& request) = 0;\n\n\n\n virtual StatusOr<google::cloud::dialogflow::v2::Context> GetContext(\n\n grpc::ClientContext& context,\n\n google::cloud::dialogflow::v2::GetContextRequest const& request) = 0;\n\n\n\n virtual StatusOr<google::cloud::dialogflow::v2::Context> CreateContext(\n\n grpc::ClientContext& context,\n\n google::cloud::dialogflow::v2::CreateContextRequest const& request) = 0;\n\n\n\n virtual StatusOr<google::cloud::dialogflow::v2::Context> UpdateContext(\n\n grpc::ClientContext& context,\n\n google::cloud::dialogflow::v2::UpdateContextRequest const& request) = 0;\n", "file_path": "google/cloud/dialogflow_es/internal/contexts_stub.h", "rank": 51, "score": 168343.53264514238 }, { "content": " static QueryResumableUploadResponse FromProto(\n\n google::storage::v2::QueryWriteStatusResponse const& response,\n", "file_path": "google/cloud/storage/internal/grpc_object_request_parser.h", "rank": 52, "score": 167948.77102684672 }, { "content": " static TestBucketIamPermissionsResponse FromProto(\n", "file_path": "google/cloud/storage/internal/grpc_bucket_request_parser.h", "rank": 53, "score": 167948.77102684672 }, { "content": " static google::storage::v2::UpdateHmacKeyRequest ToProto(\n", "file_path": "google/cloud/storage/internal/grpc_hmac_key_request_parser.h", "rank": 54, "score": 167948.77102684672 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/dialogflow/v2/context.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace dialogflow_es_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nContextsLogging::ContextsLogging(std::shared_ptr<ContextsStub> child,\n\n TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::dialogflow::v2::ListContextsResponse>\n\nContextsLogging::ListContexts(\n\n grpc::ClientContext& context,\n\n google::cloud::dialogflow::v2::ListContextsRequest const& request) {\n", "file_path": "google/cloud/dialogflow_es/internal/contexts_logging_decorator.cc", "rank": 55, "score": 68.52294668713549 }, { "content": "#include \"google/cloud/internal/log_wrapper.h\"\n\n#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/speech/v1/cloud_speech.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace speech_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nSpeechLogging::SpeechLogging(std::shared_ptr<SpeechStub> child,\n\n TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::speech::v1::RecognizeResponse> SpeechLogging::Recognize(\n\n grpc::ClientContext& context,\n\n google::cloud::speech::v1::RecognizeRequest const& request) {\n", "file_path": "google/cloud/speech/internal/speech_logging_decorator.cc", "rank": 56, "score": 66.61652035591732 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/resourcemanager/v3/projects.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace resourcemanager_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nProjectsLogging::ProjectsLogging(std::shared_ptr<ProjectsStub> child,\n\n TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::resourcemanager::v3::Project>\n\nProjectsLogging::GetProject(\n\n grpc::ClientContext& context,\n\n google::cloud::resourcemanager::v3::GetProjectRequest const& request) {\n", "file_path": "google/cloud/resourcemanager/internal/projects_logging_decorator.cc", "rank": 57, "score": 66.4637053064102 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/resourcemanager/v3/organizations.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace resourcemanager_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nOrganizationsLogging::OrganizationsLogging(\n\n std::shared_ptr<OrganizationsStub> child, TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::resourcemanager::v3::Organization>\n\nOrganizationsLogging::GetOrganization(\n\n grpc::ClientContext& context,\n\n google::cloud::resourcemanager::v3::GetOrganizationRequest const& request) {\n", "file_path": "google/cloud/resourcemanager/internal/organizations_logging_decorator.cc", "rank": 58, "score": 66.46370530641019 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/dialogflow/v2/conversation.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace dialogflow_es_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nConversationsLogging::ConversationsLogging(\n\n std::shared_ptr<ConversationsStub> child, TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::dialogflow::v2::Conversation>\n\nConversationsLogging::CreateConversation(\n\n grpc::ClientContext& context,\n\n google::cloud::dialogflow::v2::CreateConversationRequest const& request) {\n", "file_path": "google/cloud/dialogflow_es/internal/conversations_logging_decorator.cc", "rank": 59, "score": 66.32450462395327 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/dialogflow/v2/fulfillment.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace dialogflow_es_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nFulfillmentsLogging::FulfillmentsLogging(\n\n std::shared_ptr<FulfillmentsStub> child, TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::dialogflow::v2::Fulfillment>\n\nFulfillmentsLogging::GetFulfillment(\n\n grpc::ClientContext& context,\n\n google::cloud::dialogflow::v2::GetFulfillmentRequest const& request) {\n", "file_path": "google/cloud/dialogflow_es/internal/fulfillments_logging_decorator.cc", "rank": 60, "score": 66.32450462395326 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/dialogflow/v2/participant.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace dialogflow_es_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nParticipantsLogging::ParticipantsLogging(\n\n std::shared_ptr<ParticipantsStub> child, TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::dialogflow::v2::Participant>\n\nParticipantsLogging::CreateParticipant(\n\n grpc::ClientContext& context,\n\n google::cloud::dialogflow::v2::CreateParticipantRequest const& request) {\n", "file_path": "google/cloud/dialogflow_es/internal/participants_logging_decorator.cc", "rank": 61, "score": 66.32450462395327 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/accessapproval/v1/accessapproval.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace accessapproval_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nAccessApprovalLogging::AccessApprovalLogging(\n\n std::shared_ptr<AccessApprovalStub> child, TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::accessapproval::v1::ListApprovalRequestsResponse>\n\nAccessApprovalLogging::ListApprovalRequests(\n\n grpc::ClientContext& context,\n\n google::cloud::accessapproval::v1::ListApprovalRequestsMessage const&\n", "file_path": "google/cloud/accessapproval/internal/access_approval_logging_decorator.cc", "rank": 62, "score": 66.20049613956516 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/ids/v1/ids.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace ids_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nIDSLogging::IDSLogging(std::shared_ptr<IDSStub> child,\n\n TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::ids::v1::ListEndpointsResponse>\n\nIDSLogging::ListEndpoints(\n\n grpc::ClientContext& context,\n\n google::cloud::ids::v1::ListEndpointsRequest const& request) {\n", "file_path": "google/cloud/ids/internal/ids_logging_decorator.cc", "rank": 63, "score": 66.18597031618822 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/workflows/v1/workflows.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace workflows_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nWorkflowsLogging::WorkflowsLogging(std::shared_ptr<WorkflowsStub> child,\n\n TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::workflows::v1::ListWorkflowsResponse>\n\nWorkflowsLogging::ListWorkflows(\n\n grpc::ClientContext& context,\n\n google::cloud::workflows::v1::ListWorkflowsRequest const& request) {\n", "file_path": "google/cloud/workflows/internal/workflows_logging_decorator.cc", "rank": 64, "score": 66.18597031618822 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/scheduler/v1/cloudscheduler.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace scheduler_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nCloudSchedulerLogging::CloudSchedulerLogging(\n\n std::shared_ptr<CloudSchedulerStub> child, TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::scheduler::v1::ListJobsResponse>\n\nCloudSchedulerLogging::ListJobs(\n\n grpc::ClientContext& context,\n\n google::cloud::scheduler::v1::ListJobsRequest const& request) {\n", "file_path": "google/cloud/scheduler/internal/cloud_scheduler_logging_decorator.cc", "rank": 65, "score": 66.12424093864647 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/tasks/v2/cloudtasks.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace tasks_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nCloudTasksLogging::CloudTasksLogging(std::shared_ptr<CloudTasksStub> child,\n\n TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::tasks::v2::ListQueuesResponse>\n\nCloudTasksLogging::ListQueues(\n\n grpc::ClientContext& context,\n\n google::cloud::tasks::v2::ListQueuesRequest const& request) {\n", "file_path": "google/cloud/tasks/internal/cloud_tasks_logging_decorator.cc", "rank": 66, "score": 66.12424093864647 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/resourcemanager/v3/folders.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace resourcemanager_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nFoldersLogging::FoldersLogging(std::shared_ptr<FoldersStub> child,\n\n TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::resourcemanager::v3::Folder> FoldersLogging::GetFolder(\n\n grpc::ClientContext& context,\n\n google::cloud::resourcemanager::v3::GetFolderRequest const& request) {\n\n return google::cloud::internal::LogWrapper(\n", "file_path": "google/cloud/resourcemanager/internal/folders_logging_decorator.cc", "rank": 67, "score": 66.09861413384792 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/eventarc/v1/eventarc.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace eventarc_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nEventarcLogging::EventarcLogging(std::shared_ptr<EventarcStub> child,\n\n TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::eventarc::v1::Trigger> EventarcLogging::GetTrigger(\n\n grpc::ClientContext& context,\n\n google::cloud::eventarc::v1::GetTriggerRequest const& request) {\n\n return google::cloud::internal::LogWrapper(\n", "file_path": "google/cloud/eventarc/internal/eventarc_logging_decorator.cc", "rank": 68, "score": 66.09861413384792 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/redis/v1/cloud_redis.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace redis_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nCloudRedisLogging::CloudRedisLogging(std::shared_ptr<CloudRedisStub> child,\n\n TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::redis::v1::ListInstancesResponse>\n\nCloudRedisLogging::ListInstances(\n\n grpc::ClientContext& context,\n\n google::cloud::redis::v1::ListInstancesRequest const& request) {\n", "file_path": "google/cloud/redis/internal/cloud_redis_logging_decorator.cc", "rank": 69, "score": 66.06330508728973 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/billing/v1/cloud_catalog.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace billing_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nCloudCatalogLogging::CloudCatalogLogging(\n\n std::shared_ptr<CloudCatalogStub> child, TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::billing::v1::ListServicesResponse>\n\nCloudCatalogLogging::ListServices(\n\n grpc::ClientContext& context,\n\n google::cloud::billing::v1::ListServicesRequest const& request) {\n", "file_path": "google/cloud/billing/internal/cloud_catalog_logging_decorator.cc", "rank": 70, "score": 66.06330508728973 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/memcache/v1/cloud_memcache.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace memcache_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nCloudMemcacheLogging::CloudMemcacheLogging(\n\n std::shared_ptr<CloudMemcacheStub> child, TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::memcache::v1::ListInstancesResponse>\n\nCloudMemcacheLogging::ListInstances(\n\n grpc::ClientContext& context,\n\n google::cloud::memcache::v1::ListInstancesRequest const& request) {\n", "file_path": "google/cloud/memcache/internal/cloud_memcache_logging_decorator.cc", "rank": 71, "score": 66.06330508728973 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/dialogflow/v2/intent.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace dialogflow_es_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nIntentsLogging::IntentsLogging(std::shared_ptr<IntentsStub> child,\n\n TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::dialogflow::v2::ListIntentsResponse>\n\nIntentsLogging::ListIntents(\n\n grpc::ClientContext& context,\n\n google::cloud::dialogflow::v2::ListIntentsRequest const& request) {\n", "file_path": "google/cloud/dialogflow_es/internal/intents_logging_decorator.cc", "rank": 72, "score": 66.0480969591872 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/dialogflow/v2/environment.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace dialogflow_es_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nEnvironmentsLogging::EnvironmentsLogging(\n\n std::shared_ptr<EnvironmentsStub> child, TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::dialogflow::v2::ListEnvironmentsResponse>\n\nEnvironmentsLogging::ListEnvironments(\n\n grpc::ClientContext& context,\n\n google::cloud::dialogflow::v2::ListEnvironmentsRequest const& request) {\n", "file_path": "google/cloud/dialogflow_es/internal/environments_logging_decorator.cc", "rank": 73, "score": 66.0480969591872 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/dialogflow/v2/document.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace dialogflow_es_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nDocumentsLogging::DocumentsLogging(std::shared_ptr<DocumentsStub> child,\n\n TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::dialogflow::v2::ListDocumentsResponse>\n\nDocumentsLogging::ListDocuments(\n\n grpc::ClientContext& context,\n\n google::cloud::dialogflow::v2::ListDocumentsRequest const& request) {\n", "file_path": "google/cloud/dialogflow_es/internal/documents_logging_decorator.cc", "rank": 74, "score": 66.0480969591872 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/dialogflow/v2/version.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace dialogflow_es_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nVersionsLogging::VersionsLogging(std::shared_ptr<VersionsStub> child,\n\n TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::dialogflow::v2::ListVersionsResponse>\n\nVersionsLogging::ListVersions(\n\n grpc::ClientContext& context,\n\n google::cloud::dialogflow::v2::ListVersionsRequest const& request) {\n", "file_path": "google/cloud/dialogflow_es/internal/versions_logging_decorator.cc", "rank": 75, "score": 66.0480969591872 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/recommender/v1/recommender_service.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace recommender_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nRecommenderLogging::RecommenderLogging(std::shared_ptr<RecommenderStub> child,\n\n TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::recommender::v1::ListInsightsResponse>\n\nRecommenderLogging::ListInsights(\n\n grpc::ClientContext& context,\n\n google::cloud::recommender::v1::ListInsightsRequest const& request) {\n", "file_path": "google/cloud/recommender/internal/recommender_logging_decorator.cc", "rank": 76, "score": 66.04809695918722 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/talent/v4/completion_service.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace talent_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nCompletionLogging::CompletionLogging(std::shared_ptr<CompletionStub> child,\n\n TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::talent::v4::CompleteQueryResponse>\n\nCompletionLogging::CompleteQuery(\n\n grpc::ClientContext& context,\n\n google::cloud::talent::v4::CompleteQueryRequest const& request) {\n", "file_path": "google/cloud/talent/internal/completion_logging_decorator.cc", "rank": 77, "score": 66.0480969591872 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/dialogflow/v2/agent.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace dialogflow_es_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nAgentsLogging::AgentsLogging(std::shared_ptr<AgentsStub> child,\n\n TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::dialogflow::v2::Agent> AgentsLogging::GetAgent(\n\n grpc::ClientContext& context,\n\n google::cloud::dialogflow::v2::GetAgentRequest const& request) {\n\n return google::cloud::internal::LogWrapper(\n", "file_path": "google/cloud/dialogflow_es/internal/agents_logging_decorator.cc", "rank": 78, "score": 65.9645990839259 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/billing/v1/cloud_billing.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace billing_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nCloudBillingLogging::CloudBillingLogging(\n\n std::shared_ptr<CloudBillingStub> child, TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::billing::v1::BillingAccount>\n\nCloudBillingLogging::GetBillingAccount(\n\n grpc::ClientContext& context,\n\n google::cloud::billing::v1::GetBillingAccountRequest const& request) {\n", "file_path": "google/cloud/billing/internal/cloud_billing_logging_decorator.cc", "rank": 79, "score": 65.93207289749417 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/appengine/v1/appengine.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace appengine_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nApplicationsLogging::ApplicationsLogging(\n\n std::shared_ptr<ApplicationsStub> child, TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::appengine::v1::Application>\n\nApplicationsLogging::GetApplication(\n\n grpc::ClientContext& context,\n\n google::appengine::v1::GetApplicationRequest const& request) {\n", "file_path": "google/cloud/appengine/internal/applications_logging_decorator.cc", "rank": 80, "score": 65.93057510654072 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/retail/v2/search_service.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace retail_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nSearchServiceLogging::SearchServiceLogging(\n\n std::shared_ptr<SearchServiceStub> child, TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::retail::v2::SearchResponse>\n\nSearchServiceLogging::Search(\n\n grpc::ClientContext& context,\n\n google::cloud::retail::v2::SearchRequest const& request) {\n", "file_path": "google/cloud/retail/internal/search_logging_decorator.cc", "rank": 81, "score": 65.91087919464556 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/automl/v1/prediction_service.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace automl_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nPredictionServiceLogging::PredictionServiceLogging(\n\n std::shared_ptr<PredictionServiceStub> child,\n\n TracingOptions tracing_options, std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::automl::v1::PredictResponse>\n\nPredictionServiceLogging::Predict(\n\n grpc::ClientContext& context,\n\n google::cloud::automl::v1::PredictRequest const& request) {\n", "file_path": "google/cloud/automl/internal/prediction_logging_decorator.cc", "rank": 82, "score": 65.91087919464556 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/dataplex/v1/content.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace dataplex_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nContentServiceLogging::ContentServiceLogging(\n\n std::shared_ptr<ContentServiceStub> child, TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::dataplex::v1::Content>\n\nContentServiceLogging::CreateContent(\n\n grpc::ClientContext& context,\n\n google::cloud::dataplex::v1::CreateContentRequest const& request) {\n", "file_path": "google/cloud/dataplex/internal/content_logging_decorator.cc", "rank": 83, "score": 65.91087919464556 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/dataplex/v1/metadata.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace dataplex_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nMetadataServiceLogging::MetadataServiceLogging(\n\n std::shared_ptr<MetadataServiceStub> child, TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::dataplex::v1::Entity>\n\nMetadataServiceLogging::CreateEntity(\n\n grpc::ClientContext& context,\n\n google::cloud::dataplex::v1::CreateEntityRequest const& request) {\n", "file_path": "google/cloud/dataplex/internal/metadata_logging_decorator.cc", "rank": 84, "score": 65.91087919464556 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/retail/v2/prediction_service.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace retail_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nPredictionServiceLogging::PredictionServiceLogging(\n\n std::shared_ptr<PredictionServiceStub> child,\n\n TracingOptions tracing_options, std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::retail::v2::PredictResponse>\n\nPredictionServiceLogging::Predict(\n\n grpc::ClientContext& context,\n\n google::cloud::retail::v2::PredictRequest const& request) {\n", "file_path": "google/cloud/retail/internal/prediction_logging_decorator.cc", "rank": 85, "score": 65.91087919464556 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/shell/v1/cloudshell.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace shell_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nCloudShellServiceLogging::CloudShellServiceLogging(\n\n std::shared_ptr<CloudShellServiceStub> child,\n\n TracingOptions tracing_options, std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::shell::v1::Environment>\n\nCloudShellServiceLogging::GetEnvironment(\n\n grpc::ClientContext& context,\n\n google::cloud::shell::v1::GetEnvironmentRequest const& request) {\n", "file_path": "google/cloud/shell/internal/cloud_shell_logging_decorator.cc", "rank": 86, "score": 65.8602230671947 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/tpu/v1/cloud_tpu.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace tpu_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nTpuLogging::TpuLogging(std::shared_ptr<TpuStub> child,\n\n TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::tpu::v1::ListNodesResponse> TpuLogging::ListNodes(\n\n grpc::ClientContext& context,\n\n google::cloud::tpu::v1::ListNodesRequest const& request) {\n\n return google::cloud::internal::LogWrapper(\n", "file_path": "google/cloud/tpu/internal/tpu_logging_decorator.cc", "rank": 87, "score": 65.82992530456025 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/retail/v2/product_service.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace retail_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nProductServiceLogging::ProductServiceLogging(\n\n std::shared_ptr<ProductServiceStub> child, TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::retail::v2::Product>\n\nProductServiceLogging::CreateProduct(\n\n grpc::ClientContext& context,\n\n google::cloud::retail::v2::CreateProductRequest const& request) {\n", "file_path": "google/cloud/retail/internal/product_logging_decorator.cc", "rank": 88, "score": 65.77431172879972 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/talent/v4/company_service.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace talent_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nCompanyServiceLogging::CompanyServiceLogging(\n\n std::shared_ptr<CompanyServiceStub> child, TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::talent::v4::Company>\n\nCompanyServiceLogging::CreateCompany(\n\n grpc::ClientContext& context,\n\n google::cloud::talent::v4::CreateCompanyRequest const& request) {\n", "file_path": "google/cloud/talent/internal/company_logging_decorator.cc", "rank": 89, "score": 65.7743117287997 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/texttospeech/v1/cloud_tts.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace texttospeech_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nTextToSpeechLogging::TextToSpeechLogging(\n\n std::shared_ptr<TextToSpeechStub> child, TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::texttospeech::v1::ListVoicesResponse>\n\nTextToSpeechLogging::ListVoices(\n\n grpc::ClientContext& context,\n\n google::cloud::texttospeech::v1::ListVoicesRequest const& request) {\n", "file_path": "google/cloud/texttospeech/internal/text_to_speech_logging_decorator.cc", "rank": 90, "score": 65.67100289383286 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/appengine/v1/appengine.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace appengine_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nVersionsLogging::VersionsLogging(std::shared_ptr<VersionsStub> child,\n\n TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::appengine::v1::ListVersionsResponse>\n\nVersionsLogging::ListVersions(\n\n grpc::ClientContext& context,\n\n google::appengine::v1::ListVersionsRequest const& request) {\n", "file_path": "google/cloud/appengine/internal/versions_logging_decorator.cc", "rank": 91, "score": 65.63856586880404 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/appengine/v1/appengine.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace appengine_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nServicesLogging::ServicesLogging(std::shared_ptr<ServicesStub> child,\n\n TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::appengine::v1::ListServicesResponse>\n\nServicesLogging::ListServices(\n\n grpc::ClientContext& context,\n\n google::appengine::v1::ListServicesRequest const& request) {\n", "file_path": "google/cloud/appengine/internal/services_logging_decorator.cc", "rank": 92, "score": 65.63856586880404 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/appengine/v1/appengine.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace appengine_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nInstancesLogging::InstancesLogging(std::shared_ptr<InstancesStub> child,\n\n TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::appengine::v1::ListInstancesResponse>\n\nInstancesLogging::ListInstances(\n\n grpc::ClientContext& context,\n\n google::appengine::v1::ListInstancesRequest const& request) {\n", "file_path": "google/cloud/appengine/internal/instances_logging_decorator.cc", "rank": 93, "score": 65.63856586880404 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/dialogflow/cx/v3/intent.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace dialogflow_cx_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nIntentsLogging::IntentsLogging(std::shared_ptr<IntentsStub> child,\n\n TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::dialogflow::cx::v3::ListIntentsResponse>\n\nIntentsLogging::ListIntents(\n\n grpc::ClientContext& context,\n\n google::cloud::dialogflow::cx::v3::ListIntentsRequest const& request) {\n", "file_path": "google/cloud/dialogflow_cx/internal/intents_logging_decorator.cc", "rank": 94, "score": 65.63838933136779 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/dialogflow/cx/v3/version.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace dialogflow_cx_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nVersionsLogging::VersionsLogging(std::shared_ptr<VersionsStub> child,\n\n TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::dialogflow::cx::v3::ListVersionsResponse>\n\nVersionsLogging::ListVersions(\n\n grpc::ClientContext& context,\n\n google::cloud::dialogflow::cx::v3::ListVersionsRequest const& request) {\n", "file_path": "google/cloud/dialogflow_cx/internal/versions_logging_decorator.cc", "rank": 95, "score": 65.63838933136778 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/dialogflow/cx/v3/deployment.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace dialogflow_cx_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nDeploymentsLogging::DeploymentsLogging(std::shared_ptr<DeploymentsStub> child,\n\n TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::dialogflow::cx::v3::ListDeploymentsResponse>\n\nDeploymentsLogging::ListDeployments(\n\n grpc::ClientContext& context,\n\n google::cloud::dialogflow::cx::v3::ListDeploymentsRequest const& request) {\n", "file_path": "google/cloud/dialogflow_cx/internal/deployments_logging_decorator.cc", "rank": 96, "score": 65.63838933136778 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/datacatalog/v1/datacatalog.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace datacatalog_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nDataCatalogLogging::DataCatalogLogging(std::shared_ptr<DataCatalogStub> child,\n\n TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::datacatalog::v1::SearchCatalogResponse>\n\nDataCatalogLogging::SearchCatalog(\n\n grpc::ClientContext& context,\n\n google::cloud::datacatalog::v1::SearchCatalogRequest const& request) {\n", "file_path": "google/cloud/datacatalog/internal/data_catalog_logging_decorator.cc", "rank": 97, "score": 65.63838933136779 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/gkehub/v1/service.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace gkehub_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nGkeHubLogging::GkeHubLogging(std::shared_ptr<GkeHubStub> child,\n\n TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::gkehub::v1::ListMembershipsResponse>\n\nGkeHubLogging::ListMemberships(\n\n grpc::ClientContext& context,\n\n google::cloud::gkehub::v1::ListMembershipsRequest const& request) {\n", "file_path": "google/cloud/gkehub/internal/gke_hub_logging_decorator.cc", "rank": 98, "score": 65.63838933136778 }, { "content": "#include \"google/cloud/status_or.h\"\n\n#include <google/cloud/notebooks/v1/service.grpc.pb.h>\n\n#include <memory>\n\n\n\nnamespace google {\n\nnamespace cloud {\n\nnamespace notebooks_internal {\n\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\n\n\n\nNotebookServiceLogging::NotebookServiceLogging(\n\n std::shared_ptr<NotebookServiceStub> child, TracingOptions tracing_options,\n\n std::set<std::string> components)\n\n : child_(std::move(child)),\n\n tracing_options_(std::move(tracing_options)),\n\n components_(std::move(components)) {}\n\n\n\nStatusOr<google::cloud::notebooks::v1::ListInstancesResponse>\n\nNotebookServiceLogging::ListInstances(\n\n grpc::ClientContext& context,\n\n google::cloud::notebooks::v1::ListInstancesRequest const& request) {\n", "file_path": "google/cloud/notebooks/internal/notebook_logging_decorator.cc", "rank": 99, "score": 65.63838933136778 } ]
C++
source/XMPFiles/FileHandlers/TIFF_Handler.cpp
maemo-foss/maemo-package-exempi
684c589c987a1b9f01a1d60114363ce8326c2be5
#include "TIFF_Handler.hpp" #include "TIFF_Support.hpp" #include "PSIR_Support.hpp" #include "IPTC_Support.hpp" #include "ReconcileLegacy.hpp" #include "MD5.h" using namespace std; bool TIFF_CheckFormat ( XMP_FileFormat format, XMP_StringPtr filePath, LFA_FileRef fileRef, XMPFiles * parent ) { IgnoreParam(format); IgnoreParam(filePath); IgnoreParam(parent); XMP_Assert ( format == kXMP_TIFFFile ); enum { kMinimalTIFFSize = 4+4+2+12+4 }; IOBuffer ioBuf; LFA_Seek ( fileRef, 0, SEEK_SET ); if ( ! CheckFileSpace ( fileRef, &ioBuf, kMinimalTIFFSize ) ) return false; bool leTIFF = CheckBytes ( ioBuf.ptr, "\x49\x49\x2A\x00", 4 ); bool beTIFF = CheckBytes ( ioBuf.ptr, "\x4D\x4D\x00\x2A", 4 ); return (leTIFF | beTIFF); } XMPFileHandler * TIFF_MetaHandlerCTor ( XMPFiles * parent ) { return new TIFF_MetaHandler ( parent ); } TIFF_MetaHandler::TIFF_MetaHandler ( XMPFiles * _parent ) : psirMgr(0), iptcMgr(0) { this->parent = _parent; this->handlerFlags = kTIFF_HandlerFlags; this->stdCharForm = kXMP_Char8Bit; } TIFF_MetaHandler::~TIFF_MetaHandler() { if ( this->psirMgr != 0 ) delete ( this->psirMgr ); if ( this->iptcMgr != 0 ) delete ( this->iptcMgr ); } void TIFF_MetaHandler::CacheFileData() { LFA_FileRef fileRef = this->parent->fileRef; XMP_PacketInfo & packetInfo = this->packetInfo; XMP_AbortProc abortProc = this->parent->abortProc; void * abortArg = this->parent->abortArg; const bool checkAbort = (abortProc != 0); XMP_Assert ( (! this->containsXMP) && (! this->containsTNail) ); if ( checkAbort && abortProc(abortArg) ) { XMP_Throw ( "TIFF_MetaHandler::CacheFileData - User abort", kXMPErr_UserAbort ); } this->tiffMgr.ParseFileStream ( fileRef ); TIFF_Manager::TagInfo dngInfo; if ( this->tiffMgr.GetTag ( kTIFF_PrimaryIFD, kTIFF_DNGVersion, &dngInfo ) ) { XMP_Uns8 majorVersion = *((XMP_Uns8*)dngInfo.dataPtr); if ( this->tiffMgr.GetTag ( kTIFF_PrimaryIFD, kTIFF_DNGBackwardVersion, &dngInfo ) ) { majorVersion = *((XMP_Uns8*)dngInfo.dataPtr); } if ( majorVersion > 1 ) XMP_Throw ( "DNG version beyond 1.x", kXMPErr_BadTIFF ); } TIFF_Manager::TagInfo xmpInfo; bool found = this->tiffMgr.GetTag ( kTIFF_PrimaryIFD, kTIFF_XMP, &xmpInfo ); if ( found ) { this->packetInfo.offset = this->tiffMgr.GetValueOffset ( kTIFF_PrimaryIFD, kTIFF_XMP ); this->packetInfo.length = xmpInfo.dataLen; this->packetInfo.padSize = 0; this->packetInfo.charForm = kXMP_CharUnknown; this->packetInfo.writeable = true; this->xmpPacket.assign ( (XMP_StringPtr)xmpInfo.dataPtr, xmpInfo.dataLen ); this->containsXMP = true; } } void TIFF_MetaHandler::ProcessTNail() { this->processedTNail = true; this->containsTNail = false; this->containsTNail = this->tiffMgr.GetTNailInfo ( &this->tnailInfo ); if ( this->containsTNail ) this->tnailInfo.fileFormat = this->parent->format; } void TIFF_MetaHandler::ProcessXMP() { this->processedXMP = true; bool found; RecJTP_LegacyPriority lastLegacy = kLegacyJTP_None; bool readOnly = ((this->parent->openFlags & kXMPFiles_OpenForUpdate) == 0); if ( readOnly ) { this->psirMgr = new PSIR_MemoryReader(); this->iptcMgr = new IPTC_Reader(); } else { this->psirMgr = new PSIR_FileWriter(); #if ! XMP_UNIXBuild this->iptcMgr = new IPTC_Writer(); #else this->iptcMgr = new IPTC_Reader(); #endif } TIFF_Manager & tiff = this->tiffMgr; PSIR_Manager & psir = *this->psirMgr; IPTC_Manager & iptc = *this->iptcMgr; TIFF_Manager::TagInfo psirInfo; bool havePSIR = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_PSIR, &psirInfo ); TIFF_Manager::TagInfo iptcInfo; bool haveIPTC = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_IPTC, &iptcInfo ); if ( havePSIR ) { psir.ParseMemoryResources ( psirInfo.dataPtr, psirInfo.dataLen ); PSIR_Manager::ImgRsrcInfo buriedExif; found = psir.GetImgRsrc ( kPSIR_Exif, &buriedExif ); if ( found ) { tiff.IntegrateFromPShop6 ( buriedExif.dataPtr, buriedExif.dataLen ); if ( ! readOnly ) psir.DeleteImgRsrc ( kPSIR_Exif ); } } if ( haveIPTC ) { iptc.ParseMemoryDataSets ( iptcInfo.dataPtr, iptcInfo.dataLen ); lastLegacy = kLegacyJTP_TIFF_IPTC; } if ( lastLegacy < kLegacyJTP_TIFF_TIFF_Tags ) { found = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_ImageDescription, 0 ); if ( ! found ) found = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_Artist, 0 ); if ( ! found ) found = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_Copyright, 0 ); if ( found ) lastLegacy = kLegacyJTP_TIFF_TIFF_Tags; } if ( havePSIR ) { if ( lastLegacy < kLegacyJTP_PSIR_OldCaption ) { found = psir.GetImgRsrc ( kPSIR_OldCaption, 0 ); if ( ! found ) found = psir.GetImgRsrc ( kPSIR_OldCaptionPStr, 0 ); if ( found ) lastLegacy = kLegacyJTP_PSIR_OldCaption; } if ( ! haveIPTC ) { PSIR_Manager::ImgRsrcInfo iptcInfo; haveIPTC = psir.GetImgRsrc ( kPSIR_IPTC, &iptcInfo ); if ( haveIPTC ) { iptc.ParseMemoryDataSets ( iptcInfo.dataPtr, iptcInfo.dataLen ); if ( lastLegacy < kLegacyJTP_PSIR_IPTC ) lastLegacy = kLegacyJTP_PSIR_IPTC; } } } XMP_OptionBits options = k2XMP_FileHadExif; if ( this->containsXMP ) options |= k2XMP_FileHadXMP; if ( haveIPTC || (lastLegacy == kLegacyJTP_PSIR_OldCaption) ) options |= k2XMP_FileHadIPTC; if ( ! this->xmpPacket.empty() ) { XMP_Assert ( this->containsXMP ); XMP_StringPtr packetStr = this->xmpPacket.c_str(); XMP_StringLen packetLen = (XMP_StringLen)this->xmpPacket.size(); try { this->xmpObj.ParseFromBuffer ( packetStr, packetLen ); } catch ( ... ) { XMP_ClearOption ( options, k2XMP_FileHadXMP ); ImportJTPtoXMP ( kXMP_TIFFFile, lastLegacy, &tiff, psir, &iptc, &this->xmpObj, options ); throw; } } ImportJTPtoXMP ( kXMP_TIFFFile, lastLegacy, &tiff, psir, &iptc, &this->xmpObj, options ); this->containsXMP = true; } void TIFF_MetaHandler::UpdateFile ( bool doSafeUpdate ) { XMP_Assert ( ! doSafeUpdate ); LFA_FileRef destRef = this->parent->fileRef; XMP_AbortProc abortProc = this->parent->abortProc; void * abortArg = this->parent->abortArg; ExportXMPtoJTP ( kXMP_TIFFFile, &this->xmpObj, &this->tiffMgr, this->psirMgr, this->iptcMgr ); XMP_Int64 oldPacketOffset = this->packetInfo.offset; XMP_Int32 oldPacketLength = this->packetInfo.length; if ( oldPacketOffset == kXMPFiles_UnknownOffset ) oldPacketOffset = 0; if ( oldPacketLength == kXMPFiles_UnknownLength ) oldPacketLength = 0; bool doInPlace = (this->xmpPacket.size() <= (size_t)this->packetInfo.length); if ( this->tiffMgr.IsLegacyChanged() ) doInPlace = false; if ( doInPlace ) { #if GatherPerformanceData sAPIPerf->back().extraInfo += ", TIFF in-place update"; #endif if ( this->xmpPacket.size() < (size_t)this->packetInfo.length ) { size_t extraSpace = (size_t)this->packetInfo.length - this->xmpPacket.size(); this->xmpPacket.append ( extraSpace, ' ' ); } LFA_FileRef liveFile = this->parent->fileRef; XMP_Assert ( this->xmpPacket.size() == (size_t)oldPacketLength ); LFA_Seek ( liveFile, oldPacketOffset, SEEK_SET ); LFA_Write ( liveFile, this->xmpPacket.c_str(), (XMP_Int32)this->xmpPacket.size() ); } else { #if GatherPerformanceData sAPIPerf->back().extraInfo += ", TIFF append update"; #endif this->xmpObj.SerializeToBuffer ( &this->xmpPacket, kXMP_UseCompactFormat ); this->packetInfo.offset = kXMPFiles_UnknownOffset; this->packetInfo.length = (XMP_Int32)this->xmpPacket.size(); FillPacketInfo ( this->xmpPacket, &this->packetInfo ); this->tiffMgr.SetTag ( kTIFF_PrimaryIFD, kTIFF_XMP, kTIFF_ByteType, (XMP_Uns32)this->xmpPacket.size(), this->xmpPacket.c_str() ); this->tiffMgr.UpdateFileStream ( destRef ); } this->needsUpdate = false; } void TIFF_MetaHandler::WriteFile ( LFA_FileRef sourceRef, const std::string & sourcePath ) { LFA_FileRef destRef = this->parent->fileRef; XMP_AbortProc abortProc = this->parent->abortProc; void * abortArg = this->parent->abortArg; XMP_Int64 fileLen = LFA_Measure ( sourceRef ); if ( fileLen > 0xFFFFFFFFLL ) { XMP_Throw ( "TIFF fles can't exceed 4GB", kXMPErr_BadTIFF ); } LFA_Seek ( sourceRef, 0, SEEK_SET ); LFA_Truncate ( destRef, 0 ); LFA_Copy ( sourceRef, destRef, fileLen, abortProc, abortArg ); this->UpdateFile ( false ); }
#include "TIFF_Handler.hpp" #include "TIFF_Support.hpp" #include "PSIR_Support.hpp" #include "IPTC_Support.hpp" #include "ReconcileLegacy.hpp" #include "MD5.h" using namespace std; bool TIFF_CheckFormat ( XMP_FileFormat format, XMP_StringPtr filePath, LFA_FileRef fileRef, XMPFiles * parent ) { IgnoreParam(format); IgnoreParam(filePath); IgnoreParam(parent); XMP_Assert ( format == kXMP_TIFFFile ); enum { kMinimalTIFFSize = 4+4+2+12+4 }; IOBuffer ioBuf; LFA_Seek ( fileRef, 0, SEEK_SET ); if ( ! CheckFileSpace ( fileRef, &ioBuf, kMinimalTIFFSize ) ) return false; bool leTIFF = CheckBytes ( ioBuf.ptr, "\x49\x49\x2A\x00", 4 ); bool beTIFF = CheckBytes ( ioBuf.ptr, "\x4D\x4D\x00\x2A", 4 ); return (leTIFF | beTIFF); } XMPFileHandler * TIFF_MetaHandlerCTor ( XMPFiles * parent ) { return new TIFF_MetaHandler ( parent ); }
TIFF_MetaHandler::~TIFF_MetaHandler() { if ( this->psirMgr != 0 ) delete ( this->psirMgr ); if ( this->iptcMgr != 0 ) delete ( this->iptcMgr ); } void TIFF_MetaHandler::CacheFileData() { LFA_FileRef fileRef = this->parent->fileRef; XMP_PacketInfo & packetInfo = this->packetInfo; XMP_AbortProc abortProc = this->parent->abortProc; void * abortArg = this->parent->abortArg; const bool checkAbort = (abortProc != 0); XMP_Assert ( (! this->containsXMP) && (! this->containsTNail) ); if ( checkAbort && abortProc(abortArg) ) { XMP_Throw ( "TIFF_MetaHandler::CacheFileData - User abort", kXMPErr_UserAbort ); } this->tiffMgr.ParseFileStream ( fileRef ); TIFF_Manager::TagInfo dngInfo; if ( this->tiffMgr.GetTag ( kTIFF_PrimaryIFD, kTIFF_DNGVersion, &dngInfo ) ) { XMP_Uns8 majorVersion = *((XMP_Uns8*)dngInfo.dataPtr); if ( this->tiffMgr.GetTag ( kTIFF_PrimaryIFD, kTIFF_DNGBackwardVersion, &dngInfo ) ) { majorVersion = *((XMP_Uns8*)dngInfo.dataPtr); } if ( majorVersion > 1 ) XMP_Throw ( "DNG version beyond 1.x", kXMPErr_BadTIFF ); } TIFF_Manager::TagInfo xmpInfo; bool found = this->tiffMgr.GetTag ( kTIFF_PrimaryIFD, kTIFF_XMP, &xmpInfo ); if ( found ) { this->packetInfo.offset = this->tiffMgr.GetValueOffset ( kTIFF_PrimaryIFD, kTIFF_XMP ); this->packetInfo.length = xmpInfo.dataLen; this->packetInfo.padSize = 0; this->packetInfo.charForm = kXMP_CharUnknown; this->packetInfo.writeable = true; this->xmpPacket.assign ( (XMP_StringPtr)xmpInfo.dataPtr, xmpInfo.dataLen ); this->containsXMP = true; } } void TIFF_MetaHandler::ProcessTNail() { this->processedTNail = true; this->containsTNail = false; this->containsTNail = this->tiffMgr.GetTNailInfo ( &this->tnailInfo ); if ( this->containsTNail ) this->tnailInfo.fileFormat = this->parent->format; } void TIFF_MetaHandler::ProcessXMP() { this->processedXMP = true; bool found; RecJTP_LegacyPriority lastLegacy = kLegacyJTP_None; bool readOnly = ((this->parent->openFlags & kXMPFiles_OpenForUpdate) == 0); if ( readOnly ) { this->psirMgr = new PSIR_MemoryReader(); this->iptcMgr = new IPTC_Reader(); } else { this->psirMgr = new PSIR_FileWriter(); #if ! XMP_UNIXBuild this->iptcMgr = new IPTC_Writer(); #else this->iptcMgr = new IPTC_Reader(); #endif } TIFF_Manager & tiff = this->tiffMgr; PSIR_Manager & psir = *this->psirMgr; IPTC_Manager & iptc = *this->iptcMgr; TIFF_Manager::TagInfo psirInfo; bool havePSIR = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_PSIR, &psirInfo ); TIFF_Manager::TagInfo iptcInfo; bool haveIPTC = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_IPTC, &iptcInfo ); if ( havePSIR ) { psir.ParseMemoryResources ( psirInfo.dataPtr, psirInfo.dataLen ); PSIR_Manager::ImgRsrcInfo buriedExif; found = psir.GetImgRsrc ( kPSIR_Exif, &buriedExif ); if ( found ) { tiff.IntegrateFromPShop6 ( buriedExif.dataPtr, buriedExif.dataLen ); if ( ! readOnly ) psir.DeleteImgRsrc ( kPSIR_Exif ); } } if ( haveIPTC ) { iptc.ParseMemoryDataSets ( iptcInfo.dataPtr, iptcInfo.dataLen ); lastLegacy = kLegacyJTP_TIFF_IPTC; } if ( lastLegacy < kLegacyJTP_TIFF_TIFF_Tags ) { found = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_ImageDescription, 0 ); if ( ! found ) found = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_Artist, 0 ); if ( ! found ) found = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_Copyright, 0 ); if ( found ) lastLegacy = kLegacyJTP_TIFF_TIFF_Tags; } if ( havePSIR ) { if ( lastLegacy < kLegacyJTP_PSIR_OldCaption ) { found = psir.GetImgRsrc ( kPSIR_OldCaption, 0 ); if ( ! found ) found = psir.GetImgRsrc ( kPSIR_OldCaptionPStr, 0 ); if ( found ) lastLegacy = kLegacyJTP_PSIR_OldCaption; } if ( ! haveIPTC ) { PSIR_Manager::ImgRsrcInfo iptcInfo; haveIPTC = psir.GetImgRsrc ( kPSIR_IPTC, &iptcInfo ); if ( haveIPTC ) { iptc.ParseMemoryDataSets ( iptcInfo.dataPtr, iptcInfo.dataLen ); if ( lastLegacy < kLegacyJTP_PSIR_IPTC ) lastLegacy = kLegacyJTP_PSIR_IPTC; } } } XMP_OptionBits options = k2XMP_FileHadExif; if ( this->containsXMP ) options |= k2XMP_FileHadXMP; if ( haveIPTC || (lastLegacy == kLegacyJTP_PSIR_OldCaption) ) options |= k2XMP_FileHadIPTC; if ( ! this->xmpPacket.empty() ) { XMP_Assert ( this->containsXMP ); XMP_StringPtr packetStr = this->xmpPacket.c_str(); XMP_StringLen packetLen = (XMP_StringLen)this->xmpPacket.size(); try { this->xmpObj.ParseFromBuffer ( packetStr, packetLen ); } catch ( ... ) { XMP_ClearOption ( options, k2XMP_FileHadXMP ); ImportJTPtoXMP ( kXMP_TIFFFile, lastLegacy, &tiff, psir, &iptc, &this->xmpObj, options ); throw; } } ImportJTPtoXMP ( kXMP_TIFFFile, lastLegacy, &tiff, psir, &iptc, &this->xmpObj, options ); this->containsXMP = true; } void TIFF_MetaHandler::UpdateFile ( bool doSafeUpdate ) { XMP_Assert ( ! doSafeUpdate ); LFA_FileRef destRef = this->parent->fileRef; XMP_AbortProc abortProc = this->parent->abortProc; void * abortArg = this->parent->abortArg; ExportXMPtoJTP ( kXMP_TIFFFile, &this->xmpObj, &this->tiffMgr, this->psirMgr, this->iptcMgr ); XMP_Int64 oldPacketOffset = this->packetInfo.offset; XMP_Int32 oldPacketLength = this->packetInfo.length; if ( oldPacketOffset == kXMPFiles_UnknownOffset ) oldPacketOffset = 0; if ( oldPacketLength == kXMPFiles_UnknownLength ) oldPacketLength = 0; bool doInPlace = (this->xmpPacket.size() <= (size_t)this->packetInfo.length); if ( this->tiffMgr.IsLegacyChanged() ) doInPlace = false; if ( doInPlace ) { #if GatherPerformanceData sAPIPerf->back().extraInfo += ", TIFF in-place update"; #endif if ( this->xmpPacket.size() < (size_t)this->packetInfo.length ) { size_t extraSpace = (size_t)this->packetInfo.length - this->xmpPacket.size(); this->xmpPacket.append ( extraSpace, ' ' ); } LFA_FileRef liveFile = this->parent->fileRef; XMP_Assert ( this->xmpPacket.size() == (size_t)oldPacketLength ); LFA_Seek ( liveFile, oldPacketOffset, SEEK_SET ); LFA_Write ( liveFile, this->xmpPacket.c_str(), (XMP_Int32)this->xmpPacket.size() ); } else { #if GatherPerformanceData sAPIPerf->back().extraInfo += ", TIFF append update"; #endif this->xmpObj.SerializeToBuffer ( &this->xmpPacket, kXMP_UseCompactFormat ); this->packetInfo.offset = kXMPFiles_UnknownOffset; this->packetInfo.length = (XMP_Int32)this->xmpPacket.size(); FillPacketInfo ( this->xmpPacket, &this->packetInfo ); this->tiffMgr.SetTag ( kTIFF_PrimaryIFD, kTIFF_XMP, kTIFF_ByteType, (XMP_Uns32)this->xmpPacket.size(), this->xmpPacket.c_str() ); this->tiffMgr.UpdateFileStream ( destRef ); } this->needsUpdate = false; } void TIFF_MetaHandler::WriteFile ( LFA_FileRef sourceRef, const std::string & sourcePath ) { LFA_FileRef destRef = this->parent->fileRef; XMP_AbortProc abortProc = this->parent->abortProc; void * abortArg = this->parent->abortArg; XMP_Int64 fileLen = LFA_Measure ( sourceRef ); if ( fileLen > 0xFFFFFFFFLL ) { XMP_Throw ( "TIFF fles can't exceed 4GB", kXMPErr_BadTIFF ); } LFA_Seek ( sourceRef, 0, SEEK_SET ); LFA_Truncate ( destRef, 0 ); LFA_Copy ( sourceRef, destRef, fileLen, abortProc, abortArg ); this->UpdateFile ( false ); }
TIFF_MetaHandler::TIFF_MetaHandler ( XMPFiles * _parent ) : psirMgr(0), iptcMgr(0) { this->parent = _parent; this->handlerFlags = kTIFF_HandlerFlags; this->stdCharForm = kXMP_Char8Bit; }
function_block-full_function
[ { "content": "\tclass ScanError : public std::logic_error {\n\n\tpublic:\n\n\t\tScanError() throw() : std::logic_error ( \"\" ) {}\n\n\t\texplicit ScanError ( const char * message ) throw() : std::logic_error ( message ) {}\n\n\t\tvirtual ~ScanError() throw() {}\n\n\t};\n\n\n\nprivate:\t// XMPScanner\n\n\t\n", "file_path": "source/XMPFiles/FormatSupport/XMPScanner.hpp", "rank": 0, "score": 97583.12906221718 }, { "content": "enum UniCharKind {\n\n\tUCK_normal,\n\n\tUCK_space,\n\n\tUCK_comma,\n\n\tUCK_semicolon,\n\n\tUCK_quote,\n\n\tUCK_control\n\n};\n\ntypedef enum UniCharKind\tUniCharKind;\n\n\n\n#define UnsByte(c)\t((unsigned char)(c))\n\n#define UCP(u)\t\t((UniCodePoint)(u))\n\n\t// ! Needed on Windows (& PC Linux?) for inequalities with literals ito avoid sign extension.\n\n\n\n#ifndef TraceMultiFile\n\n\t#define TraceMultiFile\t0\n\n#endif\n\n\n\n// =================================================================================================\n\n// Static Variables\n", "file_path": "source/XMPCore/XMPUtils-FileInfo.cpp", "rank": 1, "score": 71577.14377914651 }, { "content": "\tclass ScanError : public std::logic_error {\n\n\tpublic:\n\n\t\tScanError() throw() : std::logic_error ( \"\" ) {}\n\n\t\texplicit ScanError ( const char * message ) throw() : std::logic_error ( message ) {}\n\n\t\tvirtual ~ScanError() throw() {}\n\n\t};\n\n\n\nprivate:\t// XMPScanner\n\n\t\n", "file_path": "samples/source/XMPScanner.hpp", "rank": 2, "score": 62298.44096241206 }, { "content": "/// const char * c_str() const\n\n/// </pre>\n\n///\n\n/// The string class must be suitable for at least UTF-8. This is the encoding used for all general\n\n/// values, and is the default encoding for serialized XMP. The string type must also be suitable\n\n/// for UTF-16 or UTF-32 if those serialization encodings are used. This mainly means tolerating\n\n/// embedded 0 bytes, which \\c std::string does.\n\n// ================================================================================================\n\n\n\n/// /c XMP_Environment.h must be the first included header.\n\n#include \"XMP_Environment.h\"\n\n\n\n#include \"XMP_Version.h\"\n\n#include \"XMP_Const.h\"\n\n\n\n#if XMP_WinBuild\n\n #if XMP_DebugBuild\n\n #pragma warning ( push, 4 )\n\n #else\n\n #pragma warning ( push, 3 )\n", "file_path": "public/include/XMP.hpp", "rank": 3, "score": 52329.739192393754 }, { "content": "\n\n // *** Option to remove empty struct/array, or leaf with empty value?\n\n\n\n\t/// Omit the XML packet wrapper.\n\n kXMP_OmitPacketWrapper = 0x0010UL,\n\n\n\n\t/// Default is a writeable packet.\n\n kXMP_ReadOnlyPacket = 0x0020UL,\n\n\n\n\t/// Use a compact form of RDF.\n\n kXMP_UseCompactFormat = 0x0040UL,\n\n\n\n\t/// Include a padding allowance for a thumbnail image.\n\n kXMP_IncludeThumbnailPad = 0x0100UL,\n\n\n\n\t/// The padding parameter is the overall packet length.\n\n kXMP_ExactPacketLength = 0x0200UL,\n\n\n\n\t/// Show aliases as XML comments.\n\n kXMP_WriteAliasComments = 0x0400UL,\n", "file_path": "public/include/XMP_Const.h", "rank": 4, "score": 52328.27773725557 }, { "content": " kXMP_IterProperties = 0x0000UL,\n\n\n\n\t/// Iterate the global alias table.\n\n kXMP_IterAliases = 0x0001UL,\n\n\n\n\t/// Iterate the global namespace table.\n\n kXMP_IterNamespaces = 0x0002UL,\n\n\n\n\t/// Just do the immediate children of the root, default is subtree.\n\n kXMP_IterJustChildren = 0x0100UL,\n\n\n\n\t/// Just do the leaf nodes, default is all nodes in the subtree.\n\n kXMP_IterJustLeafNodes = 0x0200UL,\n\n\n\n\t/// Return just the leaf part of the path, default is the full path.\n\n kXMP_IterJustLeafName = 0x0400UL,\n\n\n\n\t /// Include aliases, default is just actual properties.\n\n kXMP_IterIncludeAliases = 0x0800UL,\n\n\n", "file_path": "public/include/XMP_Const.h", "rank": 5, "score": 52327.81321928432 }, { "content": "/// string class is used to return text strings for property values, serialized XMP, and so on.\n\n/// Clients must also compile \\c XMP.incl_cpp to ensure that all client-side glue code is generated.\n\n/// This should be done by including it in exactly one client source file.\n\n///\n\n/// There are two C preprocessor macros that simplify use of the templates:\n\n///\n\n/// \\li \\c TXMP_STRING_TYPE - Define this as the string class to use with the template. You will get\n\n/// the template headers included and typedefs (\\c SXMPMeta, and so on) to use in your code.\n\n///\n\n/// \\li \\c TXMP_EXPAND_INLINE - Define this as 1 if you want to have the template functions expanded\n\n/// inline in your code. Leave it undefined, or defined as 0, to use out-of-line instantiations of\n\n/// the template functions. Compiling \\c XMP.incl_cpp generates explicit out-of-line\n\n/// instantiations if \\c TXMP_EXPAND_INLINE is off.\n\n///\n\n/// The template parameter, class \\c tStringObj, must have the following member functions (which\n\n/// match those for \\c std::string):\n\n///\n\n/// <pre>\n\n/// tStringObj& assign ( const char * str, size_t len )\n\n/// size_t size() const\n", "file_path": "public/include/XMP.hpp", "rank": 6, "score": 52327.800334022366 }, { "content": " #endif\n\n #pragma warning ( disable : 4702 ) // unreachable code\n\n #pragma warning ( disable : 4800 ) // forcing value to bool 'true' or 'false' (performance warning)\n\n#endif\n\n\n\n#if defined ( TXMP_STRING_TYPE )\n\n\n\n #include \"TXMPMeta.hpp\"\n\n #include \"TXMPIterator.hpp\"\n\n #include \"TXMPUtils.hpp\"\n\n typedef class TXMPMeta <TXMP_STRING_TYPE> SXMPMeta; // For client convenience.\n\n typedef class TXMPIterator <TXMP_STRING_TYPE> SXMPIterator;\n\n typedef class TXMPUtils <TXMP_STRING_TYPE> SXMPUtils;\n\n #if TXMP_EXPAND_INLINE\n\n \t#error \"TXMP_EXPAND_INLINE is not working at present. Please don't use it.\"\n\n #include \"client-glue/TXMPMeta.incl_cpp\"\n\n #include \"client-glue/TXMPIterator.incl_cpp\"\n\n #include \"client-glue/TXMPUtils.incl_cpp\"\n\n #include \"client-glue/TXMPFiles.incl_cpp\"\n\n #endif\n", "file_path": "public/include/XMP.hpp", "rank": 7, "score": 52327.20370043928 }, { "content": "#ifndef __XMP_hpp__\n\n#define __XMP_hpp__ 1\n\n\n\n// =================================================================================================\n\n// Copyright 2002-2007 Adobe Systems Incorporated\n\n// All Rights Reserved.\n\n//\n\n// NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms\n\n// of the Adobe license agreement accompanying it.\n\n// =================================================================================================\n\n\n\n// ================================================================================================\n\n/// \\file XMP.hpp\n\n/// \\brief Overall header file for the XMP Toolkit\n\n///\n\n/// This is an overall header file, the only one that C++ clients should include.\n\n///\n\n/// The full client API is in the \\c TXMPMeta.hpp, \\c TXMPIterator.hpp, \\c TXMPUtils.hpp headers.\n\n/// Read these for information, but do not include them directly. The \\c TXMP... classes are C++\n\n/// template classes that must be instantiated with a string class such as \\c std::string. The\n", "file_path": "public/include/XMP.hpp", "rank": 8, "score": 52326.75487737809 }, { "content": "\n\n\t#if XMP_INCLUDE_XMPFILES\n\n\t\t#include \"TXMPFiles.hpp\"\t// ! Needs typedef for SXMPMeta.\n\n\t\ttypedef class TXMPFiles <TXMP_STRING_TYPE> SXMPFiles;\n\n\t\t#if TXMP_EXPAND_INLINE\n\n\t\t\t#include \"client-glue/TXMPFiles.incl_cpp\"\n\n\t\t#endif\n\n\t#endif\n\n\n\n#endif // TXMP_STRING_TYPE\n\n\n\n#if XMP_WinBuild\n\n #pragma warning ( pop )\n\n#endif\n\n\n\n// =================================================================================================\n\n\n\n#endif // __XMP_hpp__\n", "file_path": "public/include/XMP.hpp", "rank": 9, "score": 52325.13448000245 }, { "content": " kXMPUtil_DeleteEmptyValues = 0x0004UL,\n\n\n\n\t/// Include aliases, default is just actual properties.\n\n kXMPUtil_IncludeAliases = 0x0800UL\n\n\n\n};\n\n\n\n// =================================================================================================\n\n// Types and Constants for XMPFiles\n\n// ================================\n\n\n\n/// File format constants for use with XMPFiles.\n\nenum {\n\n \n\n // ! Hex used to avoid gcc warnings. Leave the constants so the text reads big endian. There\n\n // ! seems to be no decent way on UNIX to determine the target endianness at compile time.\n\n // ! Forcing it on the client isn't acceptable.\n\n\n\n\t// --------------------\n\n // Public file formats.\n", "file_path": "public/include/XMP_Const.h", "rank": 10, "score": 52324.91256706076 }, { "content": "#ifndef __XMP_Const_h__\n\n#define __XMP_Const_h__ 1\n\n\n\n// =================================================================================================\n\n// Copyright 2002-2008 Adobe Systems Incorporated\n\n// All Rights Reserved.\n\n//\n\n// NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms\n\n// of the Adobe license agreement accompanying it.\n\n// =================================================================================================\n\n\n\n#include \"XMP_Environment.h\"\n\n\n\n #include <stddef.h>\n\n\n\n#if XMP_MacBuild || defined(HAVE_STDINT_H) // ! No stdint.h on Windows and some UNIXes.\n\n #include <stdint.h>\n\n#endif\n\n\n\n#if __cplusplus\n", "file_path": "public/include/XMP_Const.h", "rank": 11, "score": 52324.87155883551 }, { "content": "/// operations, such as \\c XMP_PropIsSimple. For other tests use an expression like <code>options &\n\n/// kXMP_<theOption></code>. When passing multiple option flags use the bitwise-OR operator. '|',\n\n/// not the arithmatic plus, '+'.\n\n\n\ntypedef const char * XMP_StringPtr; // Points to a null terminated UTF-8 string.\n\ntypedef XMP_Uns32 XMP_StringLen;\n\ntypedef XMP_Int32 XMP_Index; // Signed, sometimes -1 is handy.\n\ntypedef XMP_Uns32 XMP_OptionBits; // Used as 32 individual bits.\n\n\n\n/// \\def kXMP_TrueStr\n\n/// \\brief The canonical true string value for Booleans in serialized XMP.\n\n///\n\n/// Code that converts from string to bool should be case insensitive, and also allow \"1\".\n\n\n\n/// \\def kXMP_FalseStr\n\n/// \\brief The canonical false string value for Booleans in serialized XMP.\n\n///\n\n/// Code that converts\tfrom string to bool should be case insensitive, and also allow \"0\".\n\n\n\n#define kXMP_TrueStr \"True\" // Serialized XMP spellings, not for the type bool.\n", "file_path": "public/include/XMP_Const.h", "rank": 12, "score": 52324.616082890636 }, { "content": "\t /// Allows access to just the XMP, ignoring other forms.\n\n kXMPFiles_AllowsOnlyXMP = 0x00000020,\n\n\n\n\t/// File handler returns raw XMP packet information.\n\n kXMPFiles_ReturnsRawPacket = 0x00000040,\n\n\n\n\t /// File handler returns native thumbnail.\n\n kXMPFiles_ReturnsTNail = 0x00000080,\n\n\n\n\t/// The file handler does the file open and close.\n\n kXMPFiles_HandlerOwnsFile = 0x00000100,\n\n\n\n\t/// The file handler allows crash-safe file updates.\n\n kXMPFiles_AllowsSafeUpdate = 0x00000200,\n\n\n\n\t/// The file format needs the XMP packet to be read-only.\n\n kXMPFiles_NeedsReadOnlyPacket = 0x00000400,\n\n\n\n\t/// The file handler uses a \"sidecar\" file for the XMP.\n\n kXMPFiles_UsesSidecarXMP = 0x00000800,\n", "file_path": "public/include/XMP_Const.h", "rank": 13, "score": 52323.89416071114 }, { "content": "#define kXMP_NS_PDFA_Field \"http://www.aiim.org/pdfa/ns/field#\"\n\n#define kXMP_NS_PDFA_ID \"http://www.aiim.org/pdfa/ns/id/\"\n\n#define kXMP_NS_PDFA_Extension \"http://www.aiim.org/pdfa/ns/extension/\"\n\n\n\n#define kXMP_NS_PDFX \"http://ns.adobe.com/pdfx/1.3/\"\n\n#define\tkXMP_NS_PDFX_ID \"http://www.npes.org/pdfx/ns/id/\"\n\n\n\n#define kXMP_NS_RDF \"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n\n#define kXMP_NS_XML \"http://www.w3.org/XML/1998/namespace\"\n\n\n\n// =================================================================================================\n\n// Enums and macros used for option bits\n\n// =====================================\n\n\n\n/// \\name Macros for standard option selections.\n\n/// @{\n\n///\n\n/// \\def kXMP_ArrayLastItem\n\n/// \\brief Options macro accesses last array item.\n\n///\n", "file_path": "public/include/XMP_Const.h", "rank": 14, "score": 52323.72330751521 }, { "content": "/// \\brief The XML namespace for fields of a graphical image. Used for the Thumbnail type.\n\n///\n\n/// \\def kXMP_NS_XMP_ResourceEvent\n\n/// \\brief The XML namespace for fields of the ResourceEvent type.\n\n///\n\n/// \\def kXMP_NS_XMP_ResourceRef\n\n/// \\brief The XML namespace for fields of the ResourceRef type.\n\n///\n\n/// \\def kXMP_NS_XMP_ST_Version\n\n/// \\brief The XML namespace for fields of the Version type.\n\n///\n\n/// \\def kXMP_NS_XMP_ST_Job\n\n/// \\brief The XML namespace for fields of the JobRef type.\n\n///\n\n/// @}\n\n\n\n#define kXMP_NS_XMP_IdentifierQual \"http://ns.adobe.com/xmp/Identifier/qual/1.0/\"\n\n#define kXMP_NS_XMP_Dimensions \"http://ns.adobe.com/xap/1.0/sType/Dimensions#\"\n\n#define kXMP_NS_XMP_Text \"http://ns.adobe.com/xap/1.0/t/\"\n\n#define kXMP_NS_XMP_PagedFile \"http://ns.adobe.com/xap/1.0/t/pg/\"\n", "file_path": "public/include/XMP_Const.h", "rank": 15, "score": 52323.55018820674 }, { "content": "\n\n\t/// Omit all formatting whitespace.\n\n kXMP_OmitAllFormatting = 0x0800UL,\n\n \n\n /// Omit the x:xmpmeta element surrounding the rdf:RDF element.\n\n kXMP_OmitXMPMetaElement = 0x1000UL,\n\n\n\n _XMP_LittleEndian_Bit = 0x0001UL, // ! Don't use directly, see the combined values below!\n\n _XMP_UTF16_Bit = 0x0002UL,\n\n _XMP_UTF32_Bit = 0x0004UL,\n\n\n\n\t/// Bit-flag mask for encoding-type bits\n\n kXMP_EncodingMask = 0x0007UL,\n\n\n\n\t/// Use UTF8 encoding\n\n kXMP_EncodeUTF8 = 0UL,\n\n\n\n\t/// Use UTF16 big-endian encoding\n\n kXMP_EncodeUTF16Big = _XMP_UTF16_Bit,\n\n\n", "file_path": "public/include/XMP_Const.h", "rank": 16, "score": 52323.539234448996 }, { "content": "// -------------------------------------------------------------------------------------------------\n\n\n\n/// Option bit flags for the \\c TXMPMeta property accessor functions.\n\nenum {\n\n\n\n\t/// The XML string form of the property value is a URI, use rdf:resource attribute. DISCOURAGED\n\n kXMP_PropValueIsURI = 0x00000002UL,\n\n\n\n\t// ------------------------------------------------------\n\n // Options relating to qualifiers attached to a property.\n\n\n\n\t/// The property has qualifiers, includes \\c rdf:type and \\c xml:lang.\n\n kXMP_PropHasQualifiers = 0x00000010UL,\n\n\n\n\t/// This is a qualifier for some other property, includes \\c rdf:type and \\c xml:lang.\n\n\t/// Qualifiers can have arbitrary structure, and can themselves have qualifiers. If the\n\n\t/// qualifier itself has a structured value, this flag is only set for the top node of the\n\n\t/// qualifier's subtree.\n\n kXMP_PropIsQualifier = 0x00000020UL,\n\n\n", "file_path": "public/include/XMP_Const.h", "rank": 17, "score": 52323.127557710104 }, { "content": "/// \\def kXMP_NS_IPTCCore\n\n/// \\brief The XML namespace for the IPTC Core schema.\n\n///\n\n/// \\def kXMP_NS_RDF\n\n/// \\brief The XML namespace for RDF.\n\n///\n\n/// \\def kXMP_NS_XML\n\n/// \\brief The XML namespace for XML.\n\n///\n\n/// @}\n\n\n\n#define kXMP_NS_DC \"http://purl.org/dc/elements/1.1/\"\n\n\n\n#define kXMP_NS_IPTCCore \"http://iptc.org/std/Iptc4xmpCore/1.0/xmlns/\"\n\n\n\n#define kXMP_NS_DICOM \"http://ns.adobe.com/DICOM/\"\n\n\n\n#define kXMP_NS_PDFA_Schema \"http://www.aiim.org/pdfa/ns/schema#\"\n\n#define kXMP_NS_PDFA_Property \"http://www.aiim.org/pdfa/ns/property#\"\n\n#define kXMP_NS_PDFA_Type \"http://www.aiim.org/pdfa/ns/type#\"\n", "file_path": "public/include/XMP_Const.h", "rank": 18, "score": 52323.01285940358 }, { "content": "#endif\n\n\n\ntypedef XMP_Uns8 XMP_Bool;\n\n\n\n/// An \"ABI safe\" pointer to the internal part of an XMP object. Use to pass an XMP object across\n\n/// client DLL boundaries. See \\c TXMPMeta::GetInternalRef().\n\ntypedef struct __XMPMeta__ * XMPMetaRef;\n\n\n\n/// An \"ABI safe\" pointer to the internal part of an XMP iteration object. Use to pass an XMP\n\n/// iteration object across client DLL boundaries. See \\c TXMPIterator.\n\ntypedef struct __XMPIterator__ * XMPIteratorRef;\n\n\n\n/// An \"ABI safe\" pointer to the internal part of an XMP document operations object. Use to pass an\n\n/// XMP document operations object across client DLL boundaries. See \\c TXMPDocOps.\n\ntypedef struct __XMPDocOps__ * XMPDocOpsRef;\n\n\n\n/// An \"ABI safe\" pointer to the internal part of an XMP file-handling object. Use to pass an XMP\n\n/// file-handling object across client DLL boundaries. See \\c TXMPFiles.\n\ntypedef struct __XMPFiles__ * XMPFilesRef;\n\n\n", "file_path": "public/include/XMP_Const.h", "rank": 19, "score": 52322.80182533774 }, { "content": "\n\n// A note about kXMPFiles_OpenInBackground. The XMPFiles handler for .mov files currently uses\n\n// QuickTime. On Macintosh, calls to Enter/ExitMovies versus Enter/ExitMoviesOnThread must be made.\n\n// This option is used to signal background use so that the .mov handler can behave appropriately.\n\n\n\n/// Option bit flags for \\c TXMPFiles::CloseFile().\n\nenum {\n\n\t/// Write into a temporary file and swap for crash safety.\n\n kXMPFiles_UpdateSafely = 0x0001\n\n};\n\n\n\n// =================================================================================================\n\n// Exception codes\n\n// ===============\n\n\n\n/// \\name Errors Exception handling\n\n/// @{\n\n///\n\n/// XMP Tookit errors result in throwing an \\c XMP_Error exception. Any exception thrown within the\n\n/// XMP Toolkit is caught in the toolkit and rethrown as an \\c XMP_Error.\n\n///\n\n/// The \\c XMP_Error class contains a numeric code and an English explanation. New numeric codes may\n\n/// be added at any time. There are typically many possible explanations for each numeric code. The\n\n/// explanations try to be precise about the specific circumstances causing the error.\n\n///\n\n/// \\note The explanation string is for debugging use only. It must not be shown to users in a\n\n/// final product. It is written for developers not users, and never localized.\n\n///\n\n\n", "file_path": "public/include/XMP_Const.h", "rank": 20, "score": 52322.64265950009 }, { "content": "///\n\n/// @see \\c TXMPFiles::SetAbortProc()\n\n\n\ntypedef bool (* XMP_AbortProc) ( void * arg );\t// Used by .\n\n\n\n/// @}\n\n\n\n// =================================================================================================\n\n// Stuff with no better place to be\n\n// ================================\n\n\n\n/// XMP Toolkit version information\n\ntypedef struct XMP_VersionInfo {\n\n\t/// The primary release number, the \"1\" in version \"1.2.3\".\n\n XMP_Uns8 major;\n\n\t/// The secondary release number, the \"2\" in version \"1.2.3\".\n\n XMP_Uns8 minor;\n\n\t/// The tertiary release number, the \"3\" in version \"1.2.3\".\n\n XMP_Uns8 micro;\n\n\t /// A 0/1 boolean value, true if this is a debug build.\n", "file_path": "public/include/XMP_Const.h", "rank": 21, "score": 52322.39864152604 }, { "content": "};\n\n\n\n/// Type for file format identification constants. See \\c #kXMP_PDFFile and following.\n\ntypedef XMP_Uns32 XMP_FileFormat;\n\n\n\n// -------------------------------------------------------------------------------------------------\n\n\n\n/// Byte-order masks, do not use directly\n\nenum {\n\n kXMP_CharLittleEndianMask = 1,\n\n kXMP_Char16BitMask = 2,\n\n kXMP_Char32BitMask = 4\n\n};\n\n\n\n/// Constants to allow easy testing for 16/32 bit and big/little endian.\n\nenum {\n\n\t/// 8-bit\n\n kXMP_Char8Bit = 0,\n\n\t/// 16-bit big-endian\n\n kXMP_Char16BitBig = kXMP_Char16BitMask,\n", "file_path": "public/include/XMP_Const.h", "rank": 22, "score": 52322.184148933295 }, { "content": " kXMP_PropIsAlias = 0x00010000UL,\n\n\n\n\t/// This property is the base value (actual) for a set of aliases.This is only returned by\n\n\t/// \\c TXMPMeta::GetProperty() and then only if the property name is simple, not an path expression.\n\n kXMP_PropHasAliases = 0x00020000UL,\n\n\n\n\t/// The value of this property is \"owned\" by the application, and should not generally be editable in a UI.\n\n kXMP_PropIsInternal = 0x00040000UL,\n\n\n\n\t/// The value of this property is not derived from the document content.\n\n kXMP_PropIsStable = 0x00100000UL,\n\n\n\n\t/// The value of this property is derived from the document content.\n\n kXMP_PropIsDerived = 0x00200000UL,\n\n\n\n // kXMPUtil_AllowCommas = 0x10000000UL, ! Used by TXMPUtils::CatenateArrayItems and ::SeparateArrayItems.\n\n // kXMP_DeleteExisting = 0x20000000UL, ! Used by TXMPMeta::SetXyz functions to delete any pre-existing property.\n\n // kXMP_SchemaNode = 0x80000000UL, ! Returned by iterators - #define to avoid warnings\n\n\n\n\t// ------------------------------\n", "file_path": "public/include/XMP_Const.h", "rank": 23, "score": 52321.94412212007 }, { "content": "};\n\n\n\n/// Option bit flags for \\c TXMPFiles::GetFormatInfo().\n\nenum {\n\n\n\n\t/// Can inject first-time XMP into an existing file.\n\n kXMPFiles_CanInjectXMP = 0x00000001,\n\n\n\n\t/// Can expand XMP or other metadata in an existing file.\n\n kXMPFiles_CanExpand = 0x00000002,\n\n\n\n\t/// Can copy one file to another, writing new metadata.\n\n kXMPFiles_CanRewrite = 0x00000004,\n\n\n\n\t /// Can expand, but prefers in-place update.\n\n kXMPFiles_PrefersInPlace = 0x00000008,\n\n\n\n\t/// Supports reconciliation between XMP and other forms.\n\n kXMPFiles_CanReconcile = 0x00000010,\n\n\n", "file_path": "public/include/XMP_Const.h", "rank": 24, "score": 52321.88306999985 }, { "content": "///\n\n/// \\def kXMP_NS_XMP_BJ\n\n/// \\brief The XML namespace for the job management schema.\n\n///\n\n/// \\def kXMP_NS_XMP_T\n\n/// \\brief The XML namespace for the XMP text document schema.\n\n///\n\n/// \\def kXMP_NS_XMP_T_PG\n\n/// \\brief The XML namespace for the XMP paged document schema.\n\n///\n\n/// \\def kXMP_NS_PDF\n\n/// \\brief The XML namespace for the PDF schema.\n\n///\n\n/// \\def kXMP_NS_Photoshop\n\n/// \\brief The XML namespace for the Photoshop custom schema.\n\n///\n\n/// \\def kXMP_NS_EXIF\n\n/// \\brief The XML namespace for Adobe's EXIF schema.\n\n///\n\n/// \\def kXMP_NS_TIFF\n", "file_path": "public/include/XMP_Const.h", "rank": 25, "score": 52321.075435091196 }, { "content": "// ================\n\n\n\n// -------------------------------------------------------------------------------------------------\n\n/// \\name Special purpose callback functions\n\n/// @{\n\n\n\n/// A signed 32-bit integer used as a status result for the output callback routine,\n\n/// \\c XMP_TextOutputProc. Zero means no error, all other values except -1 are private to the callback.\n\n/// The callback is wrapped to prevent exceptions being thrown across DLL boundaries. Any exceptions\n\n/// thrown out of the callback cause a return status of -1.\n\n\n\ntypedef XMP_Int32 XMP_Status;\n\n\n\n// -------------------------------------------------------------------------------------------------\n\n/// The signature of a client-defined callback for text output from XMP Toolkit debugging\n\n/// operations. The callback is invoked one or more times for each line of output. The end of a line\n\n/// is signaled by a '\\\\n' character at the end of the buffer. Formatting newlines are never present\n\n/// in the middle of a buffer, but values of properties might contain any UTF-8 characters.\n\n///\n\n/// @param refCon A pointer to client-defined data passed to the TextOutputProc.\n", "file_path": "public/include/XMP_Const.h", "rank": 26, "score": 52321.069762011975 }, { "content": " kXMP_TimeIsUTC = 0,\n\n\t/// Time zone is east of UTC.\n\n kXMP_TimeEastOfUTC = +1\n\n};\n\n\n\n// =================================================================================================\n\n// Standard namespace URI constants\n\n// ================================\n\n\n\n/// \\name XML namespace constants for standard XMP schema.\n\n/// @{\n\n///\n\n/// \\def kXMP_NS_XMP\n\n/// \\brief The XML namespace for the XMP \"basic\" schema.\n\n///\n\n/// \\def kXMP_NS_XMP_Rights\n\n/// \\brief The XML namespace for the XMP copyright schema.\n\n///\n\n/// \\def kXMP_NS_XMP_MM\n\n/// \\brief The XML namespace for the XMP digital asset management schema.\n", "file_path": "public/include/XMP_Const.h", "rank": 27, "score": 52320.99870984002 }, { "content": "\n\n\t/// Be strict about locating XMP and reconciling with other forms.\n\n kXMPFiles_OpenStrictly = 0x00000010,\n\n\n\n\t/// Require the use of a smart handler.\n\n kXMPFiles_OpenUseSmartHandler = 0x00000020,\n\n\n\n\t/// Force packet scanning, do not use a smart handler.\n\n kXMPFiles_OpenUsePacketScanning = 0x00000040,\n\n\n\n\t/// Only packet scan files \"known\" to need scanning.\n\n kXMPFiles_OpenLimitedScanning = 0x00000080,\n\n \n\n /// Attempt to repair a file opened for update, default is to not open (throw an exception).\n\n kXMPFiles_OpenRepairFile = 0x00000100,\n\n\n\n\t /// Set if calling from background thread.\n\n kXMPFiles_OpenInBackground = 0x10000000\n\n\n\n};\n", "file_path": "public/include/XMP_Const.h", "rank": 28, "score": 52320.39641334296 }, { "content": "extern \"C\" {\n\n#endif\n\n\n\n// =================================================================================================\n\n/// \\file XMP_Const.h\n\n/// \\brief Common C/C++ types and constants for the XMP toolkit.\n\n// =================================================================================================\n\n\n\n// =================================================================================================\n\n// Basic types and constants\n\n// =========================\n\n\n\n// The XMP_... types are used on the off chance that the ..._t types present a problem. In that\n\n// case only the declarations of the XMP_... types needs to change, not all of the uses. These\n\n// types are used where fixed sizes are required in order to have a known ABI for a DLL build.\n\n\n\n#if XMP_MacBuild || defined(HAVE_STDINT_H)\n\n\n\n typedef int8_t XMP_Int8;\n\n typedef int16_t XMP_Int16;\n", "file_path": "public/include/XMP_Const.h", "rank": 29, "score": 52320.35294665413 }, { "content": "\t/// Use UTF16 little-endian encoding\n\n kXMP_EncodeUTF16Little = _XMP_UTF16_Bit | _XMP_LittleEndian_Bit,\n\n\n\n\t/// Use UTF32 big-endian encoding\n\n kXMP_EncodeUTF32Big = _XMP_UTF32_Bit,\n\n\n\n\t/// Use UTF13 little-endian encoding\n\n kXMP_EncodeUTF32Little = _XMP_UTF32_Bit | _XMP_LittleEndian_Bit\n\n\n\n};\n\n\n\n// -------------------------------------------------------------------------------------------------\n\n\n\n/// Option bit flags for \\c TXMPIterator construction.\n\nenum {\n\n\n\n\t/// The low 8 bits are an enum of what data structure to iterate.\n\n kXMP_IterClassMask = 0x00FFUL,\n\n\n\n /// Iterate the property tree of a TXMPMeta object.\n", "file_path": "public/include/XMP_Const.h", "rank": 30, "score": 52320.01530688676 }, { "content": " kXMP_PropArrayIsOrdered = 0x00000400UL,\n\n\n\n\t/// Implies \\c #kXMP_PropArrayIsOrdered, items are alternates. It is serialized using an \\c rdf:Alt container.\n\n kXMP_PropArrayIsAlternate = 0x00000800UL,\n\n\n\n\t// ------------------------------------\n\n // Additional struct and array options.\n\n\n\n\t/// Implies \\c #kXMP_PropArrayIsAlternate, items are localized text. Each array element is a\n\n\t/// simple property with an \\c xml:lang attribute.\n\n kXMP_PropArrayIsAltText = 0x00001000UL,\n\n\n\n // kXMP_InsertBeforeItem = 0x00004000UL, ! Used by SetXyz functions.\n\n // kXMP_InsertAfterItem = 0x00008000UL, ! Used by SetXyz functions.\n\n\n\n\t// ----------------------------\n\n // Other miscellaneous options.\n\n\n\n\t/// This property is an alias name for another property. This is only returned by\n\n\t/// \\c TXMPMeta::GetProperty() and then only if the property name is simple, not an path expression.\n", "file_path": "public/include/XMP_Const.h", "rank": 31, "score": 52319.71293356951 }, { "content": "\n\n\t/// Default constructor.\n\n\tXMP_ThumbnailInfo() : fileFormat(kXMP_UnknownFile), fullWidth(0), fullHeight(0),\n\n\t\t\t\t\t\t tnailWidth(0), tnailHeight(0), fullOrientation(0), tnailOrientation(0),\n\n\t\t\t\t\t\t tnailImage(0), tnailSize(0), tnailFormat(kXMP_UnknownTNail) {};\n\n\n\n};\n\n\n\n/// Version of the XMP_ThumbnailInfo type\n\nenum {\n\n\t/// Version of the XMP_ThumbnailInfo type\n\n\tkXMP_ThumbnailInfoVersion = 1\n\n};\n\n\n\n// -------------------------------------------------------------------------------------------------\n\n\n\n/// Option bit flags for \\c TXMPFiles::Initialize().\n\nenum {\n\n\t/// Do not initialize QuickTime, the client will.\n\n kXMPFiles_NoQuickTimeInit = 0x0001\n", "file_path": "public/include/XMP_Const.h", "rank": 32, "score": 52319.50369308372 }, { "content": "#define kXMP_NS_CameraRaw \"http://ns.adobe.com/camera-raw-settings/1.0/\"\n\n#define kXMP_NS_DM \"http://ns.adobe.com/xmp/1.0/DynamicMedia/\"\n\n#define kXMP_NS_ASF \"http://ns.adobe.com/asf/1.0/\"\n\n#define kXMP_NS_WAV \"http://ns.adobe.com/xmp/wav/1.0/\"\n\n\n\n#define kXMP_NS_XMP_Note \"http://ns.adobe.com/xmp/note/\"\n\n\n\n#define kXMP_NS_AdobeStockPhoto \"http://ns.adobe.com/StockPhoto/1.0/\"\n\n#define kXMP_NS_CreatorAtom \"http://ns.adobe.com/creatorAtom/1.0/\"\n\n\n\n/// \\name XML namespace constants for qualifiers and structured property fields.\n\n/// @{\n\n///\n\n/// \\def kXMP_NS_XMP_IdentifierQual\n\n/// \\brief The XML namespace for qualifiers of the xmp:Identifier property.\n\n///\n\n/// \\def kXMP_NS_XMP_Dimensions\n\n/// \\brief The XML namespace for fields of the Dimensions type.\n\n///\n\n/// \\def kXMP_NS_XMP_Image\n", "file_path": "public/include/XMP_Const.h", "rank": 33, "score": 52319.41052148426 }, { "content": "/// \\def kXMP_UseNullTermination\n\n/// \\brief Options macro sets string style.\n\n///\n\n/// \\def kXMP_NoOptions\n\n/// \\brief Options macro clears all property-type bits.\n\n///\n\n/// @}\n\n\n\n#define kXMP_ArrayLastItem ((XMP_Index)(-1L))\n\n#define kXMP_UseNullTermination ((XMP_StringLen)(~0UL))\n\n#define kXMP_NoOptions ((XMP_OptionBits)0UL)\n\n\n\n/// \\name Macros for setting and testing general option bits.\n\n/// @{\n\n///\n\n/// \\def XMP_SetOption\n\n/// \\brief Macro sets an option flag bit.\n\n///\t\\param var A variable storing an options flag.\n\n/// \\param opt The bit-flag constant to set.\n\n///\n", "file_path": "public/include/XMP_Const.h", "rank": 34, "score": 52319.25544099982 }, { "content": "/// \\li \\c #kXMP_PropArrayIsOrdered\n\n/// \\li \\c #kXMP_PropArrayIsAlternate\n\n/// \\li \\c #kXMP_PropArrayIsAltText\n\nenum {\n\n\n\n /// Option for array item location: Insert a new item before the given index.\n\n kXMP_InsertBeforeItem = 0x00004000UL,\n\n\n\n /// Option for array item location: Insert a new item after the given index.\n\n kXMP_InsertAfterItem = 0x00008000UL,\n\n\n\n /// Delete any pre-existing property.\n\n kXMP_DeleteExisting = 0x20000000UL,\n\n\n\n\t/// Bit-flag mask for property-value option bits\n\n kXMP_PropValueOptionsMask = kXMP_PropValueIsURI,\n\n\n\n\t/// Bit-flag mask for array-item location bits\n\n kXMP_PropArrayLocationMask = kXMP_InsertBeforeItem | kXMP_InsertAfterItem\n\n\n", "file_path": "public/include/XMP_Const.h", "rank": 35, "score": 52318.959585102566 }, { "content": "\t/// Implies \\c #kXMP_PropHasQualifiers, property has \\c xml:lang.\n\n kXMP_PropHasLang = 0x00000040UL,\n\n\n\n\t/// Implies \\c #kXMP_PropHasQualifiers, property has \\c rdf:type.\n\n kXMP_PropHasType = 0x00000080UL,\n\n\n\n\t// --------------------------------------------\n\n // Options relating to the data structure form.\n\n\n\n\t/// The value is a structure with nested fields.\n\n kXMP_PropValueIsStruct = 0x00000100UL,\n\n\n\n\t/// The value is an array (RDF alt/bag/seq). The \"ArrayIs...\" flags identify specific types\n\n\t/// of array; default is a general unordered array, serialized using an \\c rdf:Bag container.\n\n kXMP_PropValueIsArray = 0x00000200UL,\n\n\n\n\t/// The item order does not matter.\n\n kXMP_PropArrayIsUnordered = kXMP_PropValueIsArray,\n\n\n\n\t/// Implies \\c #kXMP_PropValueIsArray, item order matters. It is serialized using an \\c rdf:Seq container.\n", "file_path": "public/include/XMP_Const.h", "rank": 36, "score": 52318.90105319478 }, { "content": "#define kXMP_NS_XMP_Graphics \"http://ns.adobe.com/xap/1.0/g/\"\n\n#define kXMP_NS_XMP_Image \"http://ns.adobe.com/xap/1.0/g/img/\"\n\n#define kXMP_NS_XMP_Font \"http://ns.adobe.com/xap/1.0/sType/Font#\"\n\n#define kXMP_NS_XMP_ResourceEvent \"http://ns.adobe.com/xap/1.0/sType/ResourceEvent#\"\n\n#define kXMP_NS_XMP_ResourceRef \"http://ns.adobe.com/xap/1.0/sType/ResourceRef#\"\n\n#define kXMP_NS_XMP_ST_Version \"http://ns.adobe.com/xap/1.0/sType/Version#\"\n\n#define kXMP_NS_XMP_ST_Job \"http://ns.adobe.com/xap/1.0/sType/Job#\"\n\n#define kXMP_NS_XMP_ManifestItem \"http://ns.adobe.com/xap/1.0/sType/ManifestItem#\"\n\n\n\n// Deprecated XML namespace constants\n\n#define kXMP_NS_XMP_T \"http://ns.adobe.com/xap/1.0/t/\"\n\n#define kXMP_NS_XMP_T_PG \"http://ns.adobe.com/xap/1.0/t/pg/\"\n\n#define kXMP_NS_XMP_G_IMG \"http://ns.adobe.com/xap/1.0/g/img/\"\n\n\n\n/// \\name XML namespace constants from outside Adobe.\n\n/// @{\n\n///\n\n/// \\def kXMP_NS_DC\n\n/// \\brief The XML namespace for the Dublin Core schema.\n\n///\n", "file_path": "public/include/XMP_Const.h", "rank": 37, "score": 52318.84783119149 }, { "content": " XMP_Bool isDebug;\n\n\t /// A rolling build number, monotonically increasing in a release.\n\n XMP_Uns32 build;\n\n\t /// Individual feature implementation flags.\n\n XMP_Uns32 flags;\n\n\t /// A comprehensive version information string.\n\n XMP_StringPtr message;\n\n} XMP_VersionInfo;\n\n\n\n// =================================================================================================\n\n\n\n#if __cplusplus\n\n} // extern \"C\"\n\n#endif\n\n\n\n#endif // __XMP_Const_h__\n", "file_path": "public/include/XMP_Const.h", "rank": 38, "score": 52318.76957406984 }, { "content": "\t/// Descriptive string, for debugging use only. It must not be shown to users in a final\n\n\t/// product. It is written for developers, not users, and never localized.\n\n\tXMP_StringPtr errMsg;\n\n};\n\n\n\n/// Exception code constants\n\nenum {\n\n\n\n\t// --------------------\n\n // Generic error codes.\n\n \n\n\t/// Generic unknown error\n\n kXMPErr_Unknown = 0,\n\n\t/// Generic undefined error\n\n kXMPErr_TBD = 1,\n\n\t/// Generic unavailable error\n\n kXMPErr_Unavailable = 2,\n\n\t/// Generic bad object error\n\n kXMPErr_BadObject = 3,\n\n\t/// Generic bad parameter error\n", "file_path": "public/include/XMP_Const.h", "rank": 39, "score": 52318.24908864159 }, { "content": "\n\n\t/// The format is folder oriented, for example the P2 video format.\n\n kXMPFiles_FolderBasedFormat = 0x00001000\n\n\n\n};\n\n\n\n/// Option bit flags for \\c TXMPFiles::OpenFile().\n\nenum {\n\n\n\n\t/// Open for read-only access.\n\n kXMPFiles_OpenForRead = 0x00000001,\n\n\n\n\t/// Open for reading and writing.\n\n kXMPFiles_OpenForUpdate = 0x00000002,\n\n\n\n\t/// Only the XMP is wanted, allows space/time optimizations.\n\n kXMPFiles_OpenOnlyXMP = 0x00000004,\n\n\n\n\t/// Cache thumbnail if possible, \\c TXMPFiles::GetThumbnail() will be called.\n\n kXMPFiles_OpenCacheTNail = 0x00000008,\n", "file_path": "public/include/XMP_Const.h", "rank": 40, "score": 52318.090896557565 }, { "content": " kXMPErr_BadSerialize = 107,\n\n\t/// File format error\n\n kXMPErr_BadFileFormat = 108,\n\n\t/// No file handler found for format\n\n kXMPErr_NoFileHandler = 109,\n\n\t/// Data too large for JPEG file format\n\n kXMPErr_TooLargeForJPEG = 110,\n\n\n\n\t// -----------------------------------------------\n\n // File format and internal structure error codes.\n\n\n\n\t/// XML format error\n\n kXMPErr_BadXML = 201,\n\n\t/// RDF format error\n\n kXMPErr_BadRDF = 202,\n\n\t/// XMP format error\n\n kXMPErr_BadXMP = 203,\n\n\t/// Empty iterator\n\n kXMPErr_EmptyIterator = 204,\n\n\t/// Unicode error\n", "file_path": "public/include/XMP_Const.h", "rank": 41, "score": 52318.06770667614 }, { "content": "/// \\li \\c #kXMP_PropArrayIsOrdered, \n\n/// \\li \\c #kXMP_PropArrayIsAlternate,\n\n/// \\li \\c #kXMP_PropArrayIsAltText\n\nenum {\n\n\n\n\t/// Allow commas in item values, default is separator.\n\n kXMPUtil_AllowCommas = 0x10000000UL\n\n\n\n};\n\n\n\n/// Option bit flags for \\c TXMPUtils::RemoveProperties() and \\c TXMPUtils::AppendProperties().\n\nenum {\n\n\n\n\t /// Do all properties, default is just external properties.\n\n kXMPUtil_DoAllProperties = 0x0001UL,\n\n\n\n\t/// Replace existing values, default is to leave them.\n\n kXMPUtil_ReplaceOldValues = 0x0002UL,\n\n\n\n\t/// Delete properties if the new value is empty.\n", "file_path": "public/include/XMP_Const.h", "rank": 42, "score": 52317.99561049892 }, { "content": " kXMPErr_BadParam = 4,\n\n\t/// Generic bad value error\n\n kXMPErr_BadValue = 5,\n\n\t/// Generic assertion failure\n\n kXMPErr_AssertFailure = 6,\n\n\t/// Generic enforcement failure\n\n kXMPErr_EnforceFailure = 7,\n\n\t/// Generic unimplemented error\n\n kXMPErr_Unimplemented = 8,\n\n\t/// Generic internal failure\n\n kXMPErr_InternalFailure = 9,\n\n\t/// Generic deprecated error\n\n kXMPErr_Deprecated = 10,\n\n\t/// Generic external failure\n\n kXMPErr_ExternalFailure = 11,\n\n\t/// Generic user abort error\n\n kXMPErr_UserAbort = 12,\n\n\t/// Generic standard exception\n\n kXMPErr_StdException = 13,\n\n\t/// Generic unknown exception\n", "file_path": "public/include/XMP_Const.h", "rank": 43, "score": 52317.89497030564 }, { "content": "\tXMP_PacketInfo() : offset(kXMPFiles_UnknownOffset), length(kXMPFiles_UnknownLength),\n\n\t\t\t\t\t padSize(0), charForm(0), writeable(0), hasWrapper(0), pad(0) {};\n\n\n\n};\n\n\n\n/// Version of the XMP_PacketInfo type\n\nenum {\n\n\t/// Version of the XMP_PacketInfo type\n\n\tkXMP_PacketInfoVersion = 3\n\n};\n\n\n\n// -------------------------------------------------------------------------------------------------\n\n\n\n/// Values for \\c XMP_ThumbnailInfo::tnailFormat.\n\nenum {\n\n\t/// The thumbnail data has an unknown format.\n\n kXMP_UnknownTNail = 0,\n\n\t/// The thumbnail data is a JPEG stream, presumably compressed.\n\n kXMP_JPEGTNail = 1,\n\n\t/// The thumbnail data is a TIFF stream, presumably uncompressed.\n\n kXMP_TIFFTNail = 2,\n\n\t/// The thumbnail data is in the format of Photoshop Image Resource 1036.\n\n kXMP_PShopTNail = 3\n\n};\n\n\n", "file_path": "public/include/XMP_Const.h", "rank": 44, "score": 52317.82984542654 }, { "content": " kXMP_AEProjectFile = 0x41455020UL,\n\n\t/// Adobe application file format constant: 'AET ', After Effects Project Template\n\n kXMP_AEProjTemplateFile = 0x41455420UL,\n\n\t/// Adobe application file format constant: 'FFX '\n\n kXMP_AEFilterPresetFile = 0x46465820UL,\n\n\t/// Adobe application file format constant: 'NCOR'\n\n kXMP_EncoreProjectFile = 0x4E434F52UL,\n\n\t/// Adobe application file format constant: 'PRPJ'\n\n kXMP_PremiereProjectFile = 0x5052504AUL,\n\n\t/// Adobe application file format constant: 'PRTL'\n\n kXMP_PremiereTitleFile = 0x5052544CUL,\n\n\t/// Adobe application file format constant: 'UCF ', Universal Container Format\n\n\tkXMP_UCFFile = 0x55434620UL,\n\n\n\n\t// -------\n\n // Others.\n\n\n\n\t/// Unknown file format constant: ' '\n\n kXMP_UnknownFile = 0x20202020UL\n\n\n", "file_path": "public/include/XMP_Const.h", "rank": 45, "score": 52317.432740835095 }, { "content": "///\n\n/// Dates and time in the serialized XMP are ISO 8601 strings. The \\c XMP_DateTime struct allows\n\n/// easy conversion with other formats.\n\n///\n\n/// All of the fields are 32 bit, even though most could be 8 bit. This avoids overflow when doing\n\n/// carries for arithmetic or normalization. All fields have signed values for the same reasons.\n\n///\n\n/// Date-time values are occasionally used with only a date or only a time component. A date without\n\n/// a time has zeros in the \\c XMP_DateTime struct for all time fields. A time without a date has\n\n/// zeros for all date fields (year, month, and day).\n\n///\n\n/// \\c TXMPUtils provides utility functions for manipulating date-time values.\n\n///\n\n/// @see \\c TXMPUtils::ConvertToDate(), \\c TXMPUtils::ConvertFromDate(),\n\n/// \\c TXMPUtils::CompareDateTime(), \\c TXMPUtils::ConvertToLocalTime(),\n\n/// \\c TXMPUtils::ConvertToUTCTime(), \\c TXMPUtils::CurrentDateTime(),\n\n/// \\c TXMPUtils::SetTimeZone()\n\n\n", "file_path": "public/include/XMP_Const.h", "rank": 46, "score": 52317.38265033298 }, { "content": " // Masks that are multiple flags.\n\n\n\n\t/// Property type bit-flag mask for all array types\n\n kXMP_PropArrayFormMask = kXMP_PropValueIsArray | kXMP_PropArrayIsOrdered | kXMP_PropArrayIsAlternate | kXMP_PropArrayIsAltText,\n\n\n\n\t/// Property type bit-flag mask for composite types (array and struct)\n\n kXMP_PropCompositeMask = kXMP_PropValueIsStruct | kXMP_PropArrayFormMask,\n\n\n\n\t/// Mask for bits that are reserved for transient use by the implementation.\n\n kXMP_ImplReservedMask = 0x70000000L\n\n\n\n};\n\n\n\n#define kXMP_SchemaNode ((XMP_OptionBits)0x80000000UL)\n\n\n\n/// Option bit flags for the \\c TXMPMeta property setting functions. These option bits are shared\n\n/// with the accessor functions:\n\n/// \\li \\c #kXMP_PropValueIsURI\n\n/// \\li \\c #kXMP_PropValueIsStruct\n\n/// \\li \\c #kXMP_PropValueIsArray\n", "file_path": "public/include/XMP_Const.h", "rank": 47, "score": 52317.3669184069 }, { "content": "/// \\brief The XML namespace for Adobe's TIFF schema.\n\n///\n\n/// @}\n\n\n\n#define kXMP_NS_XMP \"http://ns.adobe.com/xap/1.0/\"\n\n\n\n#define kXMP_NS_XMP_Rights \"http://ns.adobe.com/xap/1.0/rights/\"\n\n#define kXMP_NS_XMP_MM \"http://ns.adobe.com/xap/1.0/mm/\"\n\n#define kXMP_NS_XMP_BJ \"http://ns.adobe.com/xap/1.0/bj/\"\n\n\n\n#define kXMP_NS_PDF \"http://ns.adobe.com/pdf/1.3/\"\n\n#define kXMP_NS_Photoshop \"http://ns.adobe.com/photoshop/1.0/\"\n\n#define kXMP_NS_PSAlbum \"http://ns.adobe.com/album/1.0/\"\n\n#define kXMP_NS_EXIF \"http://ns.adobe.com/exif/1.0/\"\n\n#define kXMP_NS_EXIF_Aux \"http://ns.adobe.com/exif/1.0/aux/\"\n\n#define kXMP_NS_TIFF \"http://ns.adobe.com/tiff/1.0/\"\n\n#define kXMP_NS_PNG \"http://ns.adobe.com/png/1.0/\"\n\n#define kXMP_NS_SWF \"http://ns.adobe.com/swf/1.0/\"\n\n#define kXMP_NS_JPEG \"http://ns.adobe.com/jpeg/1.0/\"\n\n#define kXMP_NS_JP2K \"http://ns.adobe.com/jp2k/1.0/\"\n", "file_path": "public/include/XMP_Const.h", "rank": 48, "score": 52316.84732848114 }, { "content": "};\n\n\n\n// -------------------------------------------------------------------------------------------------\n\n\n\n/// Option bit flags for \\c TXMPMeta::ParseFromBuffer().\n\nenum {\n\n\n\n\t/// Require a surrounding \\c x:xmpmeta element.\n\n kXMP_RequireXMPMeta = 0x0001UL,\n\n\n\n\t/// This is the not last input buffer for this parse stream.\n\n kXMP_ParseMoreBuffers = 0x0002UL,\n\n\n\n\t/// Do not reconcile alias differences, throw an exception.\n\n kXMP_StrictAliasing = 0x0004UL\n\n\n\n};\n\n\n\n/// Option bit flags for \\c TXMPMeta::SerializeToBuffer().\n\nenum {\n", "file_path": "public/include/XMP_Const.h", "rank": 49, "score": 52314.225483633345 }, { "content": "/// \\param opt The options flag to check.\n\n///\n\n/// \\def XMP_PropHasQualifiers\n\n/// \\brief Macro reports the property type specified by an options flag.\n\n/// \\param opt The options flag to check.\n\n///\n\n/// \\def XMP_PropIsQualifier\n\n/// \\brief Macro reports the property type specified by an options flag.\n\n/// \\param opt The options flag to check.\n\n///\n\n/// \\def XMP_PropHasLang\n\n/// \\brief Macro reports the property type specified by an options flag.\n\n/// \\param opt The options flag to check.\n\n///\n\n/// \\def XMP_NodeIsSchema\n\n/// \\brief Macro reports the property type specified by an options flag.\n\n/// \\param opt The options flag to check.\n\n///\n\n/// \\def XMP_PropIsAlias\n\n/// \\brief Macro reports the property type specified by an options flag.\n", "file_path": "public/include/XMP_Const.h", "rank": 50, "score": 52314.225483633345 }, { "content": " kXMP_SWFFile = 0x53574620UL,\n\n\t/// Public file format constant: 'FLA '\n\n kXMP_FLAFile = 0x464C4120UL,\n\n\t/// Public file format constant: 'FLV '\n\n kXMP_FLVFile = 0x464C5620UL,\n\n\n\n\t/// Public file format constant: 'MOV ', Quicktime\n\n kXMP_MOVFile = 0x4D4F5620UL,\n\n\t/// Public file format constant: 'AVI '\n\n kXMP_AVIFile = 0x41564920UL,\n\n\t/// Public file format constant: 'CIN ', Cineon\n\n kXMP_CINFile = 0x43494E20UL,\n\n \t/// Public file format constant: 'WAV '\n\n kXMP_WAVFile = 0x57415620UL,\n\n\t/// Public file format constant: 'MP3 '\n\n kXMP_MP3File = 0x4D503320UL,\n\n\t/// Public file format constant: 'SES ', Audition session\n\n kXMP_SESFile = 0x53455320UL,\n\n\t/// Public file format constant: 'CEL ', Audition loop\n\n kXMP_CELFile = 0x43454C20UL,\n", "file_path": "public/include/XMP_Const.h", "rank": 51, "score": 52314.225483633345 }, { "content": "\n\n\t/// Public file format constant: 'PDF '\n\n kXMP_PDFFile = 0x50444620UL,\n\n\t/// Public file format constant: 'PS ', general PostScript following DSC conventions\n\n kXMP_PostScriptFile = 0x50532020UL,\n\n\t/// Public file format constant: 'EPS ', encapsulated PostScript\n\n kXMP_EPSFile = 0x45505320UL,\n\n\n\n\t/// Public file format constant: 'JPEG'\n\n kXMP_JPEGFile = 0x4A504547UL,\n\n\t/// Public file format constant: 'JPX ', JPEG 2000, ISO 15444-1\n\n kXMP_JPEG2KFile = 0x4A505820UL,\n\n\t/// Public file format constant: 'TIFF'\n\n kXMP_TIFFFile = 0x54494646UL,\n\n\t/// Public file format constant: 'GIF '\n\n kXMP_GIFFile = 0x47494620UL,\n\n\t/// Public file format constant: 'PNG '\n\n kXMP_PNGFile = 0x504E4720UL,\n\n\n\n\t/// Public file format constant: 'SWF '\n", "file_path": "public/include/XMP_Const.h", "rank": 52, "score": 52314.225483633345 }, { "content": "/// \\def XMP_ClearOption\n\n/// \\brief Macro clears an option flag bit.\n\n///\t\\param var A variable storing an options flag.\n\n/// \\param opt The bit-flag constant to clear.\n\n///\n\n/// \\def XMP_TestOption\n\n/// \\brief Macro reports whether an option flag bit is set.\n\n///\t\\param var A variable storing an options flag.\n\n/// \\param opt The bit-flag constant to test.\n\n/// \\return True if the bit is set.\n\n///\n\n/// \\def XMP_OptionIsSet\n\n/// \\brief Macro reports whether an option flag bit is set.\n\n///\t\\param var A variable storing an options flag.\n\n/// \\param opt The bit-flag constant to test.\n\n/// \\return True if the bit is set.\n\n///\n\n/// \\def XMP_OptionIsClear\n\n/// \\brief Macro reports whether an option flag bit is clear.\n\n///\t\\param var A variable storing an options flag.\n", "file_path": "public/include/XMP_Const.h", "rank": 53, "score": 52314.225483633345 }, { "content": "\t/// Public file format constant: 'SHDV', a collection not really a single file\n\n kXMP_SonyHDVFile = 0x53484456UL,\n\n\n\n\t/// Public file format constant: 'HTML'\n\n kXMP_HTMLFile = 0x48544D4CUL,\n\n\t/// Public file format constant: 'XML '\n\n kXMP_XMLFile = 0x584D4C20UL,\n\n\t/// Public file format constant: 'text'\n\n kXMP_TextFile = 0x74657874UL,\n\n\n\n\t// -------------------------------\n\n // Adobe application file formats.\n\n\n\n\t/// Adobe application file format constant: 'PSD '\n\n kXMP_PhotoshopFile = 0x50534420UL,\n\n\t/// Adobe application file format constant: 'AI '\n\n kXMP_IllustratorFile = 0x41492020UL,\n\n\t/// Adobe application file format constant: 'INDD'\n\n kXMP_InDesignFile = 0x494E4444UL,\n\n\t/// Adobe application file format constant: 'AEP '\n", "file_path": "public/include/XMP_Const.h", "rank": 54, "score": 52314.225483633345 }, { "content": "/// \\param opt The options flag to check.\n\n///\n\n/// @}\n\n\n\n#define XMP_PropIsSimple(opt) (((opt) & kXMP_PropCompositeMask) == 0)\n\n#define XMP_PropIsStruct(opt) (((opt) & kXMP_PropValueIsStruct) != 0)\n\n#define XMP_PropIsArray(opt) (((opt) & kXMP_PropValueIsArray) != 0)\n\n\n\n#define XMP_ArrayIsUnordered(opt) (((opt) & kXMP_PropArrayIsOrdered) == 0)\n\n#define XMP_ArrayIsOrdered(opt) (((opt) & kXMP_PropArrayIsOrdered) != 0)\n\n#define XMP_ArrayIsAlternate(opt) (((opt) & kXMP_PropArrayIsAlternate) != 0)\n\n#define XMP_ArrayIsAltText(opt) (((opt) & kXMP_PropArrayIsAltText) != 0)\n\n\n\n#define XMP_PropHasQualifiers(opt) (((opt) & kXMP_PropHasQualifiers) != 0)\n\n#define XMP_PropIsQualifier(opt) (((opt) & kXMP_PropIsQualifier) != 0)\n\n#define XMP_PropHasLang(opt) (((opt) & kXMP_PropHasLang) != 0)\n\n\n\n#define XMP_NodeIsSchema(opt) (((opt) & kXMP_SchemaNode) != 0)\n\n#define XMP_PropIsAlias(opt) (((opt) & kXMP_PropIsAlias) != 0)\n\n\n", "file_path": "public/include/XMP_Const.h", "rank": 55, "score": 52314.225483633345 }, { "content": "///\n\n/// @}\n\n\n\n#define XMP_CharFormIs16Bit(f) ( ((int)(f) & kXMP_Char16BitMask) != 0 )\n\n#define XMP_CharFormIs32Bit(f) ( ((int)(f) & kXMP_Char32BitMask) != 0 )\n\n#define XMP_CharFormIsBigEndian(f) ( ((int)(f) & kXMP_CharLittleEndianMask) == 0 )\n\n#define XMP_CharFormIsLittleEndian(f) ( ((int)(f) & kXMP_CharLittleEndianMask) != 0 )\n\n#define XMP_GetCharSize(f) ( ((int)(f)&6) == 0 ? 1 : (int)(f)&6 )\n\n#define XMP_CharToSerializeForm(cf) ( (XMP_OptionBits)(cf) )\n\n#define XMP_CharFromSerializeForm(sf) ( (XMP_Uns8)(sf) )\n\n\n\n/// \\def kXMPFiles_UnknownOffset\n\n/// \\brief Constant for an unknown packet offset within a file.\n\n#define kXMPFiles_UnknownOffset\t((XMP_Int64)-1)\n\n\n\n/// \\def kXMPFiles_UnknownLength\n\n/// \\brief Constant for an unknown packet length within a file.\n\n#define kXMPFiles_UnknownLength\t((XMP_Int32)-1)\n\n\n", "file_path": "public/include/XMP_Const.h", "rank": 56, "score": 52314.225483633345 }, { "content": "/// \\param opt The options flag to check.\n\n///\n\n/// \\def XMP_PropIsArray\n\n/// \\brief Macro reports the property type specified by an options flag.\n\n/// \\param opt The options flag to check.\n\n///\n\n/// \\def XMP_ArrayIsUnordered\n\n/// \\brief Macro reports the property type specified by an options flag.\n\n/// \\param opt The options flag to check.\n\n///\n\n/// \\def XMP_ArrayIsOrdered\n\n/// \\brief Macro reports the property type specified by an options flag.\n\n/// \\param opt The options flag to check.\n\n///\n\n/// \\def XMP_ArrayIsAlternate\n\n/// \\brief Macro reports the property type specified by an options flag.\n\n/// \\param opt The options flag to check.\n\n///\n\n/// \\def XMP_ArrayIsAltText\n\n/// \\brief Macro reports the property type specified by an options flag.\n", "file_path": "public/include/XMP_Const.h", "rank": 57, "score": 52314.225483633345 }, { "content": "\t /// Omit all qualifiers.\n\n kXMP_IterOmitQualifiers = 0x1000UL\n\n\n\n};\n\n\n\n/// Option bit flags for \\c TXMPIterator::Skip().\n\nenum {\n\n\n\n\t/// Skip the subtree below the current node.\n\n kXMP_IterSkipSubtree = 0x0001UL,\n\n\n\n\t/// Skip the subtree below and remaining siblings of the current node.\n\n kXMP_IterSkipSiblings = 0x0002UL\n\n\n\n};\n\n\n\n// -------------------------------------------------------------------------------------------------\n\n/// Option bit flags for \\c TXMPUtils::CatenateArrayItems() and \\c TXMPUtils::SeparateArrayItems().\n\n/// These option bits are shared with the accessor functions:\n\n/// \\li \\c #kXMP_PropValueIsArray,\n", "file_path": "public/include/XMP_Const.h", "rank": 58, "score": 52314.225483633345 }, { "content": " kXMPErr_UnknownException = 14,\n\n\t/// Generic out-of-memory error\n\n kXMPErr_NoMemory = 15,\n\n\n\n\t// ------------------------------------\n\n // More specific parameter error codes.\n\n\n\n\t/// Bad schema parameter\n\n kXMPErr_BadSchema = 101,\n\n\t/// Bad XPath parameter\n\n kXMPErr_BadXPath = 102,\n\n\t/// Bad options parameter\n\n kXMPErr_BadOptions = 103,\n\n\t/// Bad index parameter\n\n kXMPErr_BadIndex = 104,\n\n\t/// Bad iteration position\n\n kXMPErr_BadIterPosition = 105,\n\n\t/// XML parsing error\n\n kXMPErr_BadParse = 106,\n\n\t/// Serialization error\n", "file_path": "public/include/XMP_Const.h", "rank": 59, "score": 52314.225483633345 }, { "content": " typedef int32_t XMP_Int32;\n\n typedef int64_t XMP_Int64;\n\n\n\n typedef uint8_t XMP_Uns8;\n\n typedef uint16_t XMP_Uns16;\n\n typedef uint32_t XMP_Uns32;\n\n typedef uint64_t XMP_Uns64;\n\n\n\n#else\n\n\n\n typedef signed char XMP_Int8;\n\n typedef signed short XMP_Int16;\n\n typedef signed long XMP_Int32;\n\n typedef signed long long XMP_Int64;\n\n\n\n typedef unsigned char XMP_Uns8;\n\n typedef unsigned short XMP_Uns16;\n\n typedef unsigned long XMP_Uns32;\n\n typedef unsigned long long XMP_Uns64;\n\n\n", "file_path": "public/include/XMP_Const.h", "rank": 60, "score": 52314.225483633345 }, { "content": "\t/// The \"sign\" of the time zone, \\c #kXMP_TimeIsUTC (0) means UTC, \\c #kXMP_TimeWestOfUTC (-1)\n\n\t/// is west, \\c #kXMP_TimeEastOfUTC (+1) is east.\n\n XMP_Int32 tzSign;\n\n\n\n\t/// The time zone hour in the range 0..23.\n\n XMP_Int32 tzHour;\n\n\n\n\t/// The time zone minute in the range 0..59.\n\n XMP_Int32 tzMinute;\n\n\n\n\t/// Nanoseconds within a second, often left as zero.\n\n XMP_Int32 nanoSecond;\n\n\n\n};\n\n\n\n/// Constant values for \\c XMP_DateTime::tzSign field.\n\nenum {\n\n\t/// Time zone is west of UTC.\n\n kXMP_TimeWestOfUTC = -1,\n\n\t/// UTC time.\n", "file_path": "public/include/XMP_Const.h", "rank": 61, "score": 52314.225483633345 }, { "content": "/// \\param opt The bit-flag constant to test.\n\n/// \\return True if the bit is clear.\n\n///\n\n/// @}\n\n\n\n#define XMP_SetOption(var,opt) var |= (opt)\n\n#define XMP_ClearOption(var,opt) var &= ~(opt)\n\n#define XMP_TestOption(var,opt) (((var) & (opt)) != 0)\n\n#define XMP_OptionIsSet(var,opt) (((var) & (opt)) != 0)\n\n#define XMP_OptionIsClear(var,opt) (((var) & (opt)) == 0)\n\n\n\n/// \\name Macros for setting and testing specific option bits.\n\n/// @{\n\n///\n\n/// \\def XMP_PropIsSimple\n\n/// \\brief Macro reports the property type specified by an options flag.\n\n/// \\param opt The options flag to check.\n\n///\n\n/// \\def XMP_PropIsStruct\n\n/// \\brief Macro reports the property type specified by an options flag.\n", "file_path": "public/include/XMP_Const.h", "rank": 62, "score": 52314.225483633345 }, { "content": "///\n\n/// \\def XMP_CharFormIsBigEndian\n\n/// \\brief Macro reports the byte-order of a character.\n\n/// \\param f The character to check.\n\n///\n\n/// \\def XMP_CharFormIsLittleEndian\n\n/// \\brief Macro reports the byte-order of a character.\n\n/// \\param f The character to check.\n\n///\n\n/// \\def XMP_GetCharSize\n\n/// \\brief Macro reports the byte-size of a character.\n\n/// \\param f The character to check.\n\n///\n\n/// \\def XMP_CharToSerializeForm\n\n/// \\brief Macro converts \\c XMP_Uns8 to \\c XMP_OptionBits.\n\n/// \\param cf The character to convert.\n\n///\n\n/// \\def XMP_CharFromSerializeForm\n\n/// \\brief Macro converts \\c XMP_OptionBits to \\c XMP_Uns8.\n\n/// \\param sf The character to convert.\n", "file_path": "public/include/XMP_Const.h", "rank": 63, "score": 52314.225483633345 }, { "content": "#define kXMP_FalseStr \"False\"\n\n\n\n/// Type for yes/no/maybe answers. The values are picked to allow Boolean-like usage. The yes and\n\n/// values are true (non-zero), the no value is false (zero).\n\nenum {\n\n\t/// The part or parts have definitely changed.\n\n\tkXMPTS_Yes = 1,\n\n\t/// The part or parts have definitely not changed.\n\n\tkXMPTS_No = 0,\n\n\t/// The part or parts might, or might not, have changed.\n\n\tkXMPTS_Maybe = -1\n\n};\n\ntypedef XMP_Int8 XMP_TriState;\n\n\n\n/// @}\n\n\n\n// =================================================================================================\n\n\n\n/// \\struct XMP_DateTime\n\n/// \\brief The expanded type for a date and time.\n", "file_path": "public/include/XMP_Const.h", "rank": 64, "score": 52314.225483633345 }, { "content": " kXMPErr_BadUnicode = 205,\n\n\t/// TIFF format error\n\n kXMPErr_BadTIFF = 206,\n\n\t/// JPEG format error\n\n kXMPErr_BadJPEG = 207,\n\n\t/// PSD format error\n\n kXMPErr_BadPSD = 208,\n\n\t/// PSIR format error\n\n kXMPErr_BadPSIR = 209,\n\n\t/// IPTC format error\n\n kXMPErr_BadIPTC = 210,\n\n\t/// MPEG format error\n\n kXMPErr_BadMPEG = 211\n\n\n\n};\n\n\n\n/// @}\n\n\n\n// =================================================================================================\n\n// Client callbacks\n", "file_path": "public/include/XMP_Const.h", "rank": 65, "score": 52314.225483633345 }, { "content": "// =================================================================================================\n\n\n\n/// \\name General scalar types and constants\n\n/// @{\n\n\n\n/// \\typedef XMP_StringPtr\n\n/// \\brief The type for input string parameters. A <tt>const char *</tt>, a null-terminated UTF-8\n\n/// string.\n\n\n\n/// \\typedef XMP_StringLen\n\n/// \\brief The type for string length parameters. A 32-bit unsigned integer, as big as will be\n\n/// practically needed.\n\n\n\n/// \\typedef XMP_Index\n\n/// \\brief The type for offsets and indices. A 32-bit signed integer. It is signed to allow -1 for\n\n/// loop termination.\n\n\n\n/// \\typedef XMP_OptionBits\n\n/// \\brief The type for a collection of 32 flag bits. Individual flags are defined as enum value bit\n\n/// masks; see \\c #kXMP_PropValueIsURI and following. A number of macros provide common set or set\n", "file_path": "public/include/XMP_Const.h", "rank": 66, "score": 52314.225483633345 }, { "content": "///\n\n/// @param buffer A string containing one line of output.\n\n///\n\n/// @param bufferSize The number of characters in the output buffer.\n\n///\n\n/// @return A success/fail status value. Any failure result aborts the output.\n\n///\n\n/// @see \\c TXMPMeta::DumpObject()\n\n\n\ntypedef XMP_Status (* XMP_TextOutputProc) ( void * refCon,\n\n XMP_StringPtr buffer,\n\n XMP_StringLen bufferSize );\n\n\n\n// -------------------------------------------------------------------------------------------------\n\n/// The signature of a client-defined callback to check for a user request to abort a time-consuming\n\n/// operation within XMPFiles.\n\n///\n\n/// @param arg A pointer to caller-defined data passed from the registration call.\n\n///\n\n/// @return True to abort the current operation, which results in an exception being thrown.\n", "file_path": "public/include/XMP_Const.h", "rank": 67, "score": 52314.225483633345 }, { "content": "\t/// 16-bit little-endian\n\n kXMP_Char16BitLittle = kXMP_Char16BitMask | kXMP_CharLittleEndianMask,\n\n\t/// 32-bit big-endian\n\n kXMP_Char32BitBig = kXMP_Char32BitMask,\n\n\t/// 32-bit little-endian\n\n kXMP_Char32BitLittle = kXMP_Char32BitMask | kXMP_CharLittleEndianMask,\n\n\t/// Variable or not-yet-known cases\n\n kXMP_CharUnknown = 1\n\n};\n\n\n\n/// \\name Macros to test components of the character form mask\n\n/// @{\n\n///\n\n/// \\def XMP_CharFormIs16Bit\n\n/// \\brief Macro reports the encoding of a character.\n\n/// \\param f The character to check.\n\n///\n\n/// \\def XMP_CharFormIs32Bit\n\n/// \\brief Macro reports the encoding of a character.\n\n/// \\param f The character to check.\n", "file_path": "public/include/XMP_Const.h", "rank": 68, "score": 52314.225483633345 }, { "content": "\t/// Public file format constant: 'MPEG'\n\n kXMP_MPEGFile = 0x4D504547UL,\n\n\t/// Public file format constant: 'MP2 '\n\n kXMP_MPEG2File = 0x4D503220UL,\n\n\t/// Public file format constant: 'MP4 ', ISO 14494-12 and -14\n\n kXMP_MPEG4File = 0x4D503420UL,\n\n\t/// Public file format constant: 'WMAV', Windows Media Audio and Video\n\n kXMP_WMAVFile = 0x574D4156UL,\n\n\t/// Public file format constant: 'AIFF'\n\n kXMP_AIFFFile = 0x41494646UL,\n\n\t/// Public file format constant: 'P2 ', a collection not really a single file\n\n kXMP_P2File = 0x50322020UL,\n\n\t/// Public file format constant: 'XDCF', a collection not really a single file\n\n kXMP_XDCAM_FAMFile = 0x58444346UL,\n\n\t/// Public file format constant: 'XDCS', a collection not really a single file\n\n kXMP_XDCAM_SAMFile = 0x58444353UL,\n\n\t/// Public file format constant: 'XDCX', a collection not really a single file\n\n kXMP_XDCAM_EXFile = 0x58444358UL,\n\n\t/// Public file format constant: 'AVHD', a collection not really a single file\n\n kXMP_AVCHDFile = 0x41564844UL,\n", "file_path": "public/include/XMP_Const.h", "rank": 69, "score": 52314.225483633345 }, { "content": "\n\n#include <string>\n\n\n\n#include <boost/test/minimal.hpp>\n\n\n\n#include \"utils.h\"\n\n#include \"xmp.h\"\n\n#include \"xmpconsts.h\"\n\n\n\nusing boost::unit_test::test_suite;\n\n\n\n\n\n\n\n//void test_xmpfiles()\n\nint test_main(int argc, char * argv[])\n\n{\n\n\tprepare_test(argc, argv, \"../../samples/testfiles/BlueSquare.jpg\");\n\n\n\n\tBOOST_CHECK(xmp_init());\n\n\n", "file_path": "exempi/tests/test-xmpfiles.cpp", "rank": 70, "score": 51221.878272255686 }, { "content": " * from this software wit hout specific prior written permission.\n\n *\n\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n\n */\n\n\n\n#include <stdlib.h>\n\n#include <stdio.h>\n\n#include <string.h>\n\n#include <sys/stat.h>\n", "file_path": "exempi/tests/test-xmpfiles.cpp", "rank": 71, "score": 51217.80878282009 }, { "content": "/*\n\n * exempi - test-xmpfiles.cpp\n\n *\n\n * Copyright (C) 2007 Hubert Figuiere\n\n * All rights reserved.\n\n *\n\n * Redistribution and use in source and binary forms, with or without\n\n * modification, are permitted provided that the following conditions\n\n * are met:\n\n *\n\n * 1 Redistributions of source code must retain the above copyright\n\n * notice, this list of conditions and the following disclaimer.\n\n * \n\n * 2 Redistributions in binary form must reproduce the above copyright\n\n * notice, this list of conditions and the following disclaimer in the\n\n * documentation and/or other materials provided with the\n\n * distribution.\n\n *\n\n * 3 Neither the name of the Authors, nor the names of its\n\n * contributors may be used to endorse or promote products derived\n", "file_path": "exempi/tests/test-xmpfiles.cpp", "rank": 72, "score": 51215.3948908931 }, { "content": "\tXmpFilePtr f = xmp_files_open_new(g_testfile.c_str(), XMP_OPEN_READ);\n\n\n\n\tBOOST_CHECK(f != NULL);\n\n\tif (f == NULL) {\n\n\t\texit(128);\n\n\t}\n\n\n\n\tXmpPtr xmp = xmp_new_empty();\n\n\n\n\tBOOST_CHECK(xmp != NULL);\n\n\t\n\n\tBOOST_CHECK(xmp_files_get_xmp(f, xmp));\n\n\n\n\tXmpStringPtr the_prop = xmp_string_new();\n\n\n\n\tBOOST_CHECK(xmp_get_property(xmp, NS_PHOTOSHOP, \"ICCProfile\", the_prop, NULL));\n\n\tBOOST_CHECK(strcmp(\"sRGB IEC61966-2.1\", xmp_string_cstr(the_prop)) == 0); \n\n\n\n\txmp_string_free(the_prop);\n\n\tBOOST_CHECK(xmp_free(xmp));\n\n\n\n\tBOOST_CHECK(xmp_files_free(f));\n\n\txmp_terminate();\n\n\n\n\tBOOST_CHECK(!g_lt->check_leaks());\n\n\tBOOST_CHECK(!g_lt->check_errors());\n\n\treturn 0;\n\n}\n", "file_path": "exempi/tests/test-xmpfiles.cpp", "rank": 73, "score": 51211.58598167197 }, { "content": " /// \\li \\c #kXMPFiles_ReturnsTNail - File handler returns native thumbnail information.\n\n /// \\li \\c #kXMPFiles_ReturnsRawPacket - File handler returns raw XMP packet information and string.\n\n ///\n\n /// Even if \\c #kXMPFiles_ReturnsRawPacket is set, the returned packet information might have an\n\n /// offset of -1 to indicate an unknown offset. While all file handlers should be able to return\n\n /// the raw packet, some might not know the offset of the packet within the file. This is\n\n /// typical in cases where external libraries are used. These cases might not even allow return\n\n /// of the raw packet.\n\n ///\n\n /// @return True if the format has explicit \"smart\" support, false if the format is handled by\n\n /// the default packet scanning plus heuristics. */\n\n\n\n\n\n static bool GetFormatInfo ( XMP_FileFormat format,\n\n \t\t\t\t\t\t\tXMP_OptionBits * handlerFlags = 0 );\n\n\n\n /// @}\n\n\n\n\t// =============================================================================================\n\n /// \\name File operations\n", "file_path": "public/include/TXMPFiles.hpp", "rank": 74, "score": 50676.84492226355 }, { "content": " /// @param schemaNS The namespace URI; see \\c GetProperty().\n\n ///\n\n /// @param propName The name of the property. Can be a general path expression, must not be null\n\n /// or the empty string; see \\c GetProperty() for namespace prefix usage.\n\n ///\n\n /// @param propValue The new binary value. Can be null if creating the property. Must be null\n\n /// for arrays and non-leaf levels of structs that do not have values.\n\n ///\n\n /// @param options Option flags describing the property; a logical OR of allowed bit-flag\n\n /// constants; see \\c #kXMP_PropValueIsStruct and following. Must match the type of a property\n\n /// that already exists.\n\n\n\n void SetProperty_Bool ( XMP_StringPtr schemaNS,\n\n\t\t\t\t\t\t XMP_StringPtr propName,\n\n\t\t\t\t\t\t bool propValue,\n\n\t\t\t\t\t\t XMP_OptionBits options = 0 );\n\n\n\n // ---------------------------------------------------------------------------------------------\n\n /// @brief \\c SetProperty_Int() sets the value of an integer property using a C long integer.\n\n ///\n", "file_path": "public/include/TXMPMeta.hpp", "rank": 75, "score": 50675.45615660794 }, { "content": " /// Namespaces must be registered before use in namespace URI parameters or path expressions.\n\n /// Within the XMP Toolkit the registered namespace URIs and prefixes must be unique. Additional\n\n /// namespaces encountered when parsing RDF are automatically registered.\n\n ///\n\n /// The namespace URI should always end in an XML name separator such as '/' or '#'. This is\n\n /// because some forms of RDF shorthand catenate a namespace URI with an element name to form a\n\n /// new URI.\n\n\n\n // ---------------------------------------------------------------------------------------------\n\n /// @brief \\c RegisterNamespace() registers a namespace URI with a suggested prefix.\n\n ///\n\n /// If the URI is not registered but the suggested prefix is in use, a unique prefix is created\n\n /// from the suggested one. The actual registered prefix is returned. The function result tells\n\n /// if the registered prefix is the suggested one. It is not an error if the URI is already\n\n /// registered, regardless of the prefix.\n\n ///\n\n /// This function is static; make the call directly from the concrete class (\\c SXMPMeta).\n\n ///\n\n /// @param namespaceURI The URI for the namespace. Must be a valid XML URI.\n\n ///\n", "file_path": "public/include/TXMPMeta.hpp", "rank": 76, "score": 50675.09520310307 }, { "content": "\n\n // ---------------------------------------------------------------------------------------------\n\n /// @brief \\c SetStructField() creates or sets the value of a field within a nested structure.\n\n ///\n\n /// Use this to set a value within an existing structure, create a new field within an existing\n\n /// structure, or create an empty structure of any depth. If you set a field in a structure that\n\n /// does not exist, the structure is automatically created.\n\n ///\n\n /// Use \\c TXMPUtils::ComposeStructFieldPath() to create a complex path.\n\n ///\n\n /// @param schemaNS The namespace URI; see \\c GetProperty().\n\n ///\n\n /// @param structName The name of the struct. Can be a general path expression, must not be null\n\n /// or the empty string; see \\c GetProperty() for namespace prefix usage.\n\n ///\n\n /// @param fieldNS The namespace URI for the field. Same namespace and prefix usage as\n\n /// \\c GetProperty().\n\n ///\n\n /// @param fieldName The name of the field. Must be a single XML name, must not be null or the\n\n /// empty string. Same namespace and prefix usage as \\c GetProperty().\n", "file_path": "public/include/TXMPMeta.hpp", "rank": 77, "score": 50673.98307251481 }, { "content": " /// \\li \\c #kXMPFiles_OpenStrictly\n\n /// \\li \\c #kXMPFiles_OpenUseSmartHandler\n\n /// \\li \\c #kXMPFiles_OpenUsePacketScanning\n\n /// \\li \\c #kXMPFiles_OpenLimitedScanning\n\n /// \\li \\c #kXMPFiles_OpenInBackground\n\n ///\n\n /// @return The new \\c TXMPFiles object.\n\n\n\n TXMPFiles ( XMP_StringPtr filePath,\n\n\t\t\t\tXMP_FileFormat format = kXMP_UnknownFile,\n\n\t\t\t\tXMP_OptionBits openFlags = 0 );\n\n\n\n // ---------------------------------------------------------------------------------------------\n\n /// @brief Alternate constructor associates the new \\c XMPFiles object with a specific file,\n\n /// using a string object.\n\n ///\n\n /// Overloads the basic form of the function, allowing you to pass a string object\n\n\t/// for the file path. It is otherwise identical; see details in the canonical form.\n\n\n\n TXMPFiles ( const tStringObj & filePath,\n", "file_path": "public/include/TXMPFiles.hpp", "rank": 78, "score": 50673.97726586123 }, { "content": " /// @param itemIndex The 1-based index of the desired item. Use the macro \\c #kXMP_ArrayLastItem\n\n /// to specify the last existing array item.\n\n ///\n\n /// @return True if the array item exists.\n\n\n\n bool DoesArrayItemExist ( XMP_StringPtr schemaNS,\n\n\t\t\t\t\t\t\t XMP_StringPtr arrayName,\n\n\t\t\t\t\t\t\t XMP_Index itemIndex ) const;\n\n\n\n // ---------------------------------------------------------------------------------------------\n\n /// @brief \\c DoesStructFieldExist() reports whether a struct field currently exists.\n\n ///\n\n /// Use \\c TXMPUtils::ComposeStructFieldPath() to create a complex path.\n\n ///\n\n /// @param schemaNS The namespace URI; see \\c GetProperty().\n\n ///\n\n /// @param structName The name of the struct. Can be a general path expression, must not be null\n\n /// or the empty string; see \\c GetProperty() for namespace prefix usage.\n\n ///\n\n /// @param fieldNS The namespace URI for the field. Same namespace and prefix usage as\n", "file_path": "public/include/TXMPMeta.hpp", "rank": 79, "score": 50673.86075321781 }, { "content": " /// @param suggestedPrefix The suggested prefix to be used if the URI is not yet registered.\n\n /// Must be a valid XML name.\n\n ///\n\n /// @param registeredPrefix [out] A string object in which to return the prefix actually\n\n /// registered for this URI.\n\n ///\n\n /// @return True if the registered prefix matches the suggested prefix.\n\n ///\n\n /// @note No checking is done on either the URI or the prefix. */\n\n\n\n static bool RegisterNamespace ( XMP_StringPtr namespaceURI,\n\n \t\t\tXMP_StringPtr suggestedPrefix,\n\n \t\t\t\ttStringObj * registeredPrefix );\n\n\n\n // ---------------------------------------------------------------------------------------------\n\n /// @brief \\c GetNamespacePrefix() obtains the prefix for a registered namespace URI, and\n\n /// reports whether the URI is registered.\n\n ///\n\n /// This function is static; make the call directly from the concrete class (\\c SXMPMeta).\n\n ///\n", "file_path": "public/include/TXMPMeta.hpp", "rank": 80, "score": 50673.62151077656 }, { "content": " /// Use this to prepare metadata for storage as an XMP packet embedded in a file. See \\c TXMPFiles::PutXMP().\n\n ///\n\n /// @param rdfString [out] A string object in which to return the serialized RDF. Must not be null.\n\n ///\n\n /// @param options An options flag that controls how the serialization operation is performed.\n\n /// The specified options must be logically consistent; an exception is thrown if they are not.\n\n /// A logical OR of these bit-flag constants:\n\n /// \\li \\c kXMP_OmitPacketWrapper - Do not include an XML packet wrapper. This cannot be\n\n /// specified together with \\c #kXMP_ReadOnlyPacket, \\c #kXMP_IncludeThumbnailPad, or\n\n /// \\c #kXMP_ExactPacketLength.\n\n /// \\li \\c kXMP_ReadOnlyPacket - Create a read-only XML packet wapper. Cannot be specified\n\n /// together with \\c kXMP_OmitPacketWrapper.\n\n /// \\li \\c kXMP_UseCompactFormat - Use a highly compact RDF syntax and layout.\n\n /// \\li \\c kXMP_WriteAliasComments - Include XML comments for aliases.\n\n /// \\li \\c kXMP_IncludeThumbnailPad - Include typical space for a JPEG thumbnail in the\n\n /// padding if no \\c xmp:Thumbnails property is present. Cannot be specified together with\n\n /// \\c kXMP_OmitPacketWrapper.\n\n /// \\li \\c kXMP_ExactPacketLength - The padding parameter provides the overall packet length.\n\n /// The actual amount of padding is computed. An exception is thrown if the packet exceeds\n\n /// this length with no padding.\tCannot be specified together with\n", "file_path": "public/include/TXMPMeta.hpp", "rank": 81, "score": 50673.28306909782 }, { "content": " ///\n\n /// @param qualNS The namespace URI for the qualifier. Same namespace and prefix usage as\n\n /// \\c GetProperty().\n\n ///\n\n /// @param qualName The name of the qualifier. Must be a single XML name, must not be null or\n\n /// the empty string. Same namespace and prefix usage as \\c GetProperty().\n\n ///\n\n /// @param qualValue The new value, a null-terminated UTF-8 string, if the qualifier has a\n\n /// value. Null to create a new, empty qualifier.\n\n ///\n\n /// @param options Option flags describing the <<qualified property? qualifier?>>, a logical OR\n\n /// of property-type bit-flag constants. Use the macro \\c #XMP_PropIsQualifier to create a\n\n /// qualifier.\t <<??>>\n\n\n\n void SetQualifier ( XMP_StringPtr schemaNS,\n\n\t\t\t\t\t XMP_StringPtr propName,\n\n\t\t\t\t\t XMP_StringPtr qualNS,\n\n\t\t\t\t\t XMP_StringPtr qualName,\n\n\t\t\t\t\t XMP_StringPtr qualValue,\n\n\t\t\t\t\t XMP_OptionBits options = 0 );\n", "file_path": "public/include/TXMPMeta.hpp", "rank": 82, "score": 50673.246556674836 }, { "content": " /// Overloads the basic form of the function, allowing you to pass a string object\n\n\t/// for the item value. It is otherwise identical; see details in the canonical form.\n\n\n\n void SetProperty ( XMP_StringPtr schemaNS,\n\n\t\t\t\t\t XMP_StringPtr propName,\n\n\t\t\t\t\t const tStringObj & propValue,\n\n\t\t\t\t\t XMP_OptionBits options = 0 );\n\n\n\n // ---------------------------------------------------------------------------------------------\n\n /// @brief \\c SetArrayItem() creates or sets the value of an item within an array.\n\n ///\n\n /// Items are accessed by an integer index, where the first item has index 1. This function\n\n /// creates the item if necessary, but the array itself must already exist Use\n\n /// \\c AppendArrayItem() to create arrays. A new item is automatically appended if the index is the\n\n /// array size plus 1. To insert a new item before or after an existing item, use option flags.\n\n ///\n\n /// Use \\c TXMPUtils::ComposeArrayItemPath() to create a complex path.\n\n ///\n\n /// @param schemaNS The namespace URI; see \\c GetProperty().\n\n ///\n", "file_path": "public/include/TXMPMeta.hpp", "rank": 83, "score": 50673.12428803181 }, { "content": " ///\n\n /// @param schemaNS The namespace URI for the property; see \\c GetProperty().\n\n ///\n\n /// @param propName The name of the property; see \\c GetProperty().\n\n ///\n\n /// @return True if the property exists.\n\n\n\n bool DoesPropertyExist ( XMP_StringPtr schemaNS,\n\n \t XMP_StringPtr propName ) const;\n\n\n\n // ---------------------------------------------------------------------------------------------\n\n /// @brief \\c DoesArrayItemExist() reports whether an array item currently exists.\n\n ///\n\n /// Use \\c TXMPUtils::ComposeArrayItemPath() to create a complex path.\n\n ///\n\n /// @param schemaNS The namespace URI; see \\c GetProperty().\n\n ///\n\n /// @param arrayName The name of the array. Can be a general path expression, must not be null\n\n /// or the empty string; see \\c GetProperty() for namespace prefix usage.\n\n ///\n", "file_path": "public/include/TXMPMeta.hpp", "rank": 84, "score": 50672.66832387349 }, { "content": " // ---------------------------------------------------------------------------------------------\n\n /// \\name Accessing properties as binary values.\n\n /// @{\n\n ///\n\n\t/// These are very similar to \\c TXMPMeta::GetProperty() and \\c TXMPMeta::SetProperty(), except\n\n\t/// that the value is returned or provided in binary form instead of as a UTF-8 string.\n\n\t/// \\c TXMPUtils provides functions for converting between binary and string values.\n\n /// Use the path composition functions in \\c TXMPUtils\tto compose complex path expressions\n\n /// for fields or items in nested structures or arrays, or for qualifiers.\n\n\n\n // ---------------------------------------------------------------------------------------------\n\n /// @brief \\c GetProperty_Bool() retrieves the value of a Boolean property as a C++ bool.\n\n ///\n\n /// Reports whether a property exists, and retrieves its binary value and property type information.\n\n ///\n\n /// @param schemaNS The namespace URI; see \\c GetProperty().\n\n ///\n\n /// @param propName The name of the property. Can be a general path expression, must not be null\n\n /// or the empty string; see \\c GetProperty() for namespace prefix usage.\n\n ///\n", "file_path": "public/include/TXMPMeta.hpp", "rank": 85, "score": 50672.64577329414 }, { "content": "\n\n void SetStructField ( XMP_StringPtr schemaNS,\n\n\t\t\t\t\t\t XMP_StringPtr structName,\n\n\t\t\t\t\t\t XMP_StringPtr fieldNS,\n\n\t\t\t\t\t\t XMP_StringPtr fieldName,\n\n\t\t\t\t\t\t const tStringObj & fieldValue,\n\n\t\t\t\t\t\t XMP_OptionBits options = 0 );\n\n\n\n // ---------------------------------------------------------------------------------------------\n\n /// @brief \\c SetQualifier() creates or sets a qualifier attached to a property.\n\n ///\n\n /// Use this to set a value for an existing qualifier, or create a new qualifier. <<how do\n\n /// options work? macro vs bit-flag? interaction w/XMP_PropHasQualifier?>> Use\n\n /// \\c TXMPUtils::ComposeQualifierPath() to create a complex path.\n\n ///\n\n /// @param schemaNS The namespace URI; see \\c GetProperty().\n\n ///\n\n /// @param propName The name of the property to which the qualifier is attached. Can be a\n\n /// general path expression, must not be null or the empty string; see \\c GetProperty() for\n\n /// namespace prefix usage.\n", "file_path": "public/include/TXMPMeta.hpp", "rank": 86, "score": 50672.55896707075 }, { "content": " /// with other forms (if reconciliation is done). This option forces stricter rules, resulting\n\n /// in exceptions for errors. The definition of strictness is specific to each handler, there\n\n /// might be no difference.\n\n /// \\li \\c #kXMPFiles_OpenUseSmartHandler - Require the use of a smart handler.\n\n /// \\li \\c #kXMPFiles_OpenUsePacketScanning - Force packet scanning, do not use a smart handler.\n\n ///\n\n /// @return True if the file is succesfully opened and attached to a file handler. False for\n\n /// anticipated problems, such as passing \\c #kXMPFiles_OpenUseSmartHandler but not having an\n\n /// appropriate smart handler. Throws an exception for serious problems.\n\n\n\n\n\n\tbool OpenFile ( XMP_StringPtr filePath,\n\n\t\t\t\t XMP_FileFormat format = kXMP_UnknownFile,\n\n\t\t\t\t XMP_OptionBits openFlags = 0 );\n\n\n\n // ---------------------------------------------------------------------------------------------\n\n /// @brief \\c OpenFile() opens a file for metadata access, using a string object\n\n ///\n\n /// Overloads the basic form of the function, allowing you to pass a string object\n\n\t/// for the file path. It is otherwise identical; see details in the canonical form.\n", "file_path": "public/include/TXMPFiles.hpp", "rank": 87, "score": 50672.499677982734 }, { "content": " /// specified together with \\c #kXMP_ReadOnlyPacket, \\c #kXMP_IncludeThumbnailPad, or\n\n /// \\c #kXMP_ExactPacketLength.\n\n /// \\li \\c kXMP_ReadOnlyPacket - Create a read-only XML packet wapper. Cannot be specified\n\n /// together with \\c kXMP_OmitPacketWrapper.\n\n /// \\li \\c kXMP_UseCompactFormat - Use a highly compact RDF syntax and layout.\n\n /// \\li \\c kXMP_WriteAliasComments - Include XML comments for aliases.\n\n /// \\li \\c kXMP_IncludeThumbnailPad - Include typical space for a JPEG thumbnail in the\n\n /// padding if no \\c xmp:Thumbnails property is present. Cannot be specified together with\n\n /// \\c kXMP_OmitPacketWrapper.\n\n /// \\li \\c kXMP_ExactPacketLength - The padding parameter provides the overall packet length.\n\n /// The actual amount of padding is computed. An exception is thrown if the packet exceeds\n\n /// this length with no padding.\tCannot be specified together with\n\n /// \\c kXMP_OmitPacketWrapper.\n\n ///\n\n /// In addition to the above options, you can include one of the following encoding options:\n\n /// \\li \\c #kXMP_EncodeUTF8 - Encode as UTF-8, the default.\n\n /// \\li \\c #kXMP_EncodeUTF16Big - Encode as big-endian UTF-16.\n\n /// \\li \\c #kXMP_EncodeUTF16Little - Encode as little-endian UTF-16.\n\n /// \\li \\c #kXMP_EncodeUTF32Big - Encode as big-endian UTF-32.\n\n /// \\li \\c #kXMP_EncodeUTF32Little - Encode as little-endian UTF-32.\n", "file_path": "public/include/TXMPMeta.hpp", "rank": 88, "score": 50672.25306548953 }, { "content": " bool GetThumbnail ( XMP_ThumbnailInfo * tnailInfo );\n\n\n\n // ---------------------------------------------------------------------------------------------\n\n /// @brief \\c PutXMP() updates the XMP metadata in this object without writing out the file.\n\n ///\n\n /// This function supplies new XMP for the file. However, the disk file is not written until the\n\n /// object is closed with \\c CloseFile(). The options provided when the file was opened\n\n /// determine if reconciliation is done with other forms of metadata.\n\n ///\n\n /// @param xmpObj The new metadata as an XMP object.\n\n\n\n void PutXMP ( const SXMPMeta & xmpObj );\n\n\n\n // ---------------------------------------------------------------------------------------------\n\n /// @brief \\c PutXMP() updates the XMP metadata in this object without writing out the file,\n\n\t/// using a string object for input.\n\n ///\n\n /// Overloads the basic form of the function, allowing you to pass the metadata as a string object\n\n\t/// instead of an XMP object. It is otherwise identical; see details in the canonical form.\n\n\t///\n", "file_path": "public/include/TXMPFiles.hpp", "rank": 89, "score": 50672.07380496128 }, { "content": " /// @{\n\n ///\n\n /// These functions allow you to open, close, and query files.\n\n\n\n // ---------------------------------------------------------------------------------------------\n\n /// @brief \\c CheckFileFormat() tries to determine the format of a file.\n\n ///\n\n /// \\c CheckFileFormat tries to determine the format of a file, returning an XMP_FileFormat value.\n\n /// It uses the same logic as \\c OpenFile will use to select a smart handler.\n\n ///\n\n /// @param filePath The path for the file, appropriate for the local operating system. Passed as\n\n /// a nul-terminated UTF-8 string. The path is the same as would be passed to \\c OpenFile.\n\n ///\n\n /// @return The file's format if a smart handler would be selected, otherwise \\c kXMP_UnknownFile.\n\n\n\n static XMP_FileFormat CheckFileFormat ( XMP_StringPtr filePath );\n\n\n\n // ---------------------------------------------------------------------------------------------\n\n /// @brief \\c CheckPackageFormat() tries to determine the format of a \"package\" folder.\n\n ///\n", "file_path": "public/include/TXMPFiles.hpp", "rank": 90, "score": 50671.57763606471 }, { "content": "/// node being visited. If the node is simple, it also delivers the value. Qualifiers for this node\n\n/// are visited next. The fields of a struct or items of an array are visited after the qualifiers\n\n/// of the parent.\n\n///\n\n/// You can specify options when contructing the iteration object to control how the iteration is\n\n/// performed.\n\n///\n\n/// \\li \\c #kXMP_IterJustChildren - Visit just the immediate children of the root. Skip the root\n\n/// itself and all nodes below the immediate children. This omits the qualifiers of the immediate\n\n/// children, the qualifier nodes being below what they qualify.\n\n/// \\li \\c #kXMP_IterJustLeafNodes - Visit just the leaf property nodes and their qualifiers.\n\n/// \\li \\c #kXMP_IterJustLeafName - Return just the leaf component of the node names. The default\n\n/// is to return the full path name.\n\n/// \\li \\c #kXMP_IterIncludeAliases - Include aliases as part of the iteration. Since aliases are\n\n/// not actual nodes the default iteration does not visit them.\n\n/// \\li \\c #kXMP_IterOmitQualifiers - Do not visit the qualifiers of a node.\n\n// =================================================================================================\n\n\n\n#include \"client-glue/WXMPIterator.hpp\"\n\n\n", "file_path": "public/include/TXMPIterator.hpp", "rank": 91, "score": 50671.54004663966 }, { "content": " /// If the array exists, it must have the form specified by the options. Each call appends a new\n\n /// item to the array.\n\n ///\n\n /// Use \\c TXMPUtils::ComposeArrayItemPath() to create a complex path.\n\n ///\n\n /// @param schemaNS The namespace URI; see \\c GetProperty().\n\n ///\n\n /// @param arrayName The name of the array. Can be a general path expression, must not be null\n\n /// or the empty string; see \\c GetProperty() for namespace prefix usage.\n\n ///\n\n /// @param arrayOptions Option flags describing the array type to create; a logical OR of\n\n /// allowed bit-flag constants, \\c #kXMP_PropArrayIsOrdered, \\c #kXMP_PropArrayIsAlternate, or\n\n /// \\c #kXMP_PropArrayIsAltText. If the array exists, must match the existing array type or be\n\n /// null (0 or \\c #kXMP_NoOptions).\n\n ///\n\n /// @param itemValue The new item value, a null-terminated UTF-8 string, if the array item has a\n\n /// value.\n\n ///\n\n /// @param itemOptions Option flags describing the item type to create; one of the bit-flag\n\n /// constants \\c #kXMP_PropValueIsArray or \\c #kXMP_PropValueIsStruct to create a complex array\n", "file_path": "public/include/TXMPMeta.hpp", "rank": 92, "score": 50671.5312821456 }, { "content": " ///\n\n /// @return True if the property exists.\n\n\n\n bool GetProperty ( XMP_StringPtr schemaNS,\n\n \t XMP_StringPtr propName,\n\n tStringObj * propValue,\n\n \t XMP_OptionBits * options ) const;\n\n\n\n // ---------------------------------------------------------------------------------------------\n\n /// @brief \\c GetArrayItem() provides access to items within an array.\n\n ///\n\n /// Reports whether the item exists; if it does, and if it has a value, the function retrieves\n\n /// the value. Items are accessed by an integer index, where the first item has index 1.\n\n ///\n\n /// @param schemaNS The namespace URI for the array; see \\c GetProperty().\n\n ///\n\n /// @param arrayName The name of the array. Can be a general path expression, must not be null\n\n /// or the empty string; see \\c GetProperty() for namespace prefix usage.\n\n ///\n\n /// @param itemIndex The 1-based index of the desired item. Use the macro \\c #kXMP_ArrayLastItem\n", "file_path": "public/include/TXMPMeta.hpp", "rank": 93, "score": 50671.38852442686 }, { "content": "\t\t\t\t\t\t\t double propValue,\n\n\t\t\t\t\t\t\t XMP_OptionBits options = 0 );\n\n\n\n // ---------------------------------------------------------------------------------------------\n\n /// @brief \\c SetProperty_Date() sets the value of a date/time property using an \\c #XMP_DateTime structure.\n\n ///\n\n /// Sets a property with a binary value, creating it if necessary.\n\n ///\n\n /// @param schemaNS The namespace URI; see \\c GetProperty().\n\n ///\n\n /// @param propName The name of the property. Can be a general path expression, must not be null\n\n /// or the empty string; see \\c GetProperty() for namespace prefix usage.\n\n ///\n\n /// @param propValue The new binary value. Can be null if creating the property. Must be null\n\n /// for arrays and non-leaf levels of structs that do not have values.\n\n ///\n\n /// @param options Option flags describing the property; a logical OR of allowed bit-flag\n\n /// constants; see \\c #kXMP_PropValueIsStruct and following. Must match the type of a property\n\n /// that already exists.\n\n\n", "file_path": "public/include/TXMPMeta.hpp", "rank": 94, "score": 50671.289902811746 }, { "content": " ///\n\n /// @param namespaceURI [out] A string object in which to return the URI registered for this\n\n /// prefix. If the prefix is not registered, this string is not modified.\n\n ///\n\n /// @return True if the namespace prefix is registered.\n\n\n\n static bool GetNamespaceURI ( XMP_StringPtr namespacePrefix,\n\n \t\t\t tStringObj * namespaceURI );\n\n\n\n // ---------------------------------------------------------------------------------------------\n\n /// @brief Not implemented.\n\n ///\n\n /// Deletes a namespace from the registry. Does nothing if the URI is not registered, or if the\n\n /// parameter is null or the empty string.\n\n ///\n\n /// This function is static; make the call directly from the concrete class (\\c SXMPMeta).\n\n ///\n\n /// @param namespaceURI The URI for the namespace.\n\n\n\n static void DeleteNamespace ( XMP_StringPtr namespaceURI );\n", "file_path": "public/include/TXMPMeta.hpp", "rank": 95, "score": 50671.262162174724 }, { "content": " /// @param schemaNS The namespace URI; see \\c GetProperty().\n\n ///\n\n /// @param propName The name of the property. Can be a general path expression, must not be null\n\n /// or the empty string; see \\c GetProperty() for namespace prefix usage.\n\n ///\n\n /// @param propValue The new value, a pointer to a null terminated UTF-8 string. Must be null\n\n /// for arrays and non-leaf levels of structs that do not have values.\n\n ///\n\n /// @param options Option flags describing the property; a logical OR of allowed bit-flag\n\n /// constants; see \\c #kXMP_PropValueIsStruct and following. Must match the type of a property\n\n /// that already exists.\n\n\n\n void SetProperty ( XMP_StringPtr schemaNS,\n\n\t\t\t\t\t XMP_StringPtr propName,\n\n\t\t\t\t\t XMP_StringPtr propValue,\n\n\t\t\t\t\t XMP_OptionBits options = 0 );\n\n\n\n // ---------------------------------------------------------------------------------------------\n\n /// @brief \\c SetProperty() creates or sets a property value using a string object.\n\n\t///\n", "file_path": "public/include/TXMPMeta.hpp", "rank": 96, "score": 50671.09349130479 }, { "content": " /// @param namespaceURI The URI for the namespace. Must not be null or the empty string. It is\n\n /// not an error if the namespace URI is not registered.\n\n ///\n\n /// @param namespacePrefix [out] A string object in which to return the prefix registered for\n\n /// this URI, with a terminating colon character, ':'. If the namespace is not registered, this\n\n /// string is not modified.\n\n ///\n\n /// @return True if the namespace URI is registered.\n\n\n\n static bool GetNamespacePrefix ( XMP_StringPtr namespaceURI,\n\n \t\t\t tStringObj * namespacePrefix );\n\n\n\n // ---------------------------------------------------------------------------------------------\n\n /// @brief \\c GetNamespaceURI() obtains the URI for a registered namespace prefix, and reports\n\n /// whether the prefix is registered.\n\n ///\n\n /// This function is static; make the call directly from the concrete class (\\c SXMPMeta).\n\n ///\n\n /// @param namespacePrefix The prefix for the namespace. Must not be null or the empty string.\n\n /// It is not an error if the namespace prefix is not registered.\n", "file_path": "public/include/TXMPMeta.hpp", "rank": 97, "score": 50671.03620009513 }, { "content": "/// \\c TXMPIterator is the template class providing iteration services for the XMP Toolkit. It must\n\n/// be instantiated with a string class such as \\c std::string. See the instructions in XMP.hpp, and\n\n/// the Overview for a discussion of the overall architecture of the XMP API.\n\n// =================================================================================================\n\n\n\n// =================================================================================================\n\n/// \\class TXMPIterator TXMPIterator.hpp\n\n/// @brief API for access to the XMP Toolkit iteration services.\n\n///\n\n/// \\c TXMPIterator provides a uniform means to iterate over the schema and properties within an XMP\n\n/// object. \\c TXMPIterator is a template class which must be instantiated with a string class such\n\n/// as \\c std::string. See the instructions in XMP.hpp, and the Overview for a discussion of the\n\n/// overall architecture of the XMP API. Access these functions through the concrete class,\n\n/// \\c SXMPIterator.\n\n///\n\n/// @note Only XMP object iteration is currently available. Future development may include iteration\n\n/// over global tables, such as registered namespaces.\n\n///\n\n/// To understand how iteration works, you should have a thorough understanding of the XMP data\n\n/// tree, as described in the XMP Specification Part 1. You might also find it helpful to create\n", "file_path": "public/include/TXMPIterator.hpp", "rank": 98, "score": 50671.02050123474 }, { "content": " /// @brief \\c CanPutXMP() reports whether this file can be updated with a specific XMP packet.\n\n ///\n\n /// Use to determine if the file can probably be updated with a given set of XMP metadata. This\n\n /// depends on the size of the packet, the options with which the file was opened, and the\n\n /// capabilities of the handler for the file format. The function obtains the length of the\n\n /// serialized packet for the provided XMP, but does not keep it or modify it, and does not\n\n /// cause the file to be written when closed. This is implemented roughly as follows:\n\n ///\n\n /// <pre>\n\n /// bool CanPutXMP ( XMP_StringPtr xmpPacket )\n\n /// {\n\n /// XMP_FileFormat format;\n\n /// this->GetFileInfo ( 0, &format, 0 );\n\n ///\n\n /// XMP_OptionBits formatFlags;\n\n /// GetFormatInfo ( format, &formatFlags );\n\n ///\n\n /// if ( (formatFlags & kXMPFiles_CanInjectXMP) && (formatFlags & kXMPFiles_CanExpand) ) return true;\n\n ///\n\n /// XMP_PacketInfo packetInfo;\n", "file_path": "public/include/TXMPFiles.hpp", "rank": 99, "score": 50671.005109813326 } ]
C++
tests/test_cases/one_hot_gpu_test.cpp
intel/clDNN
c4ef3bd7b707fc386655cccf90e6c0420d1efec7
#include <gtest/gtest.h> #include <api/CPP/engine.hpp> #include <api/CPP/input_layout.hpp> #include <api/CPP/memory.hpp> #include <api/CPP/one_hot.hpp> #include <api/CPP/topology.hpp> #include <api/CPP/network.hpp> #include "test_utils/test_utils.h" #include <cstddef> using namespace cldnn; using namespace ::tests; template <typename T> VVVVF<T> one_hot_cpu(VVVVF<T> &input, uint16_t axis, int32_t one_hot_limit, int input_padding_y = 0, int input_padding_x = 0, int output_padding_y = 0, int output_padding_x = 0) { size_t padding_y = input_padding_y + output_padding_y; size_t padding_x = input_padding_x + output_padding_x; size_t out_sizes[4]; out_sizes[0] = input.size(); out_sizes[1] = input[0].size(); out_sizes[2] = input[0][0].size() + 2 * padding_y; out_sizes[3] = input[0][0][0].size() + 2 * padding_x; for (uint16_t i = 0; i < axis; ++i) out_sizes[i] = out_sizes[i + 1]; out_sizes[axis] = one_hot_limit; VVVVF<T> output(out_sizes[0], VVVF<T>(out_sizes[1], VVF<T>(out_sizes[2], VF<T>(out_sizes[3])))); switch (axis) { case 0: for (size_t b = 0; b < out_sizes[0]; ++b) for (size_t f = 0; f < out_sizes[1]; ++f) for (size_t y = 0; y < out_sizes[2]; ++y) for (size_t x = 0; x < out_sizes[3]; ++x) output[b][f][y][x] = input[0][f][y][x] == (T)b ? 1 : 0; break; case 1: for (size_t b = 0; b < out_sizes[0]; ++b) for (size_t f = 0; f < out_sizes[1]; ++f) for (size_t y = 0; y < out_sizes[2]; ++y) for (size_t x = 0; x < out_sizes[3]; ++x) output[b][f][y][x] = input[0][b][y][x] == (T)f ? 1 : 0; break; case 2: for (size_t b = 0; b < out_sizes[0]; ++b) for (size_t f = 0; f < out_sizes[1]; ++f) for (size_t y = 0; y < out_sizes[2]; ++y) for (size_t x = 0; x < out_sizes[3]; ++x) output[b][f][y][x] = input[0][b][f][x] == (T)y ? 1 : 0; break; case 3: for (size_t b = 0; b < out_sizes[0]; ++b) for (size_t f = 0; f < out_sizes[1]; ++f) for (size_t y = 0; y < out_sizes[2]; ++y) for (size_t x = 0; x < out_sizes[3]; ++x) output[b][f][y][x] = input[0][b][f][y] == (T)x ? 1 : 0; break; default: break; } return output; } template <typename T> void generic_one_hot_test_int(cldnn::format test_input_fmt, int input_b, int input_f, int input_y, int input_x, tensor shape, uint16_t one_hot_axis, int input_padding_y = 0, int input_padding_x = 0, int output_padding_y = 0, int output_padding_x = 0) { std::vector<tensor::value_type> output_dims = { shape.batch[0], shape.feature[0], shape.spatial[1], shape.spatial[0] }; int32_t one_hot_limit = output_dims[one_hot_axis]; int min_random = -2, max_random = one_hot_limit + 2; VVVVF<T> input_rnd = generate_random_4d<T>(input_b, input_f, input_y, input_x, min_random, max_random); VF<T> input_rnd_vec = flatten_4d<T>(test_input_fmt, input_rnd); const auto& engine = get_test_engine(); tensor input_tensor(input_b, input_f, input_x, input_y); auto input = memory::allocate(engine, { type_to_data_type<T>::value, test_input_fmt, input_tensor }); set_values(input, input_rnd_vec); topology topology; topology.add(input_layout("input", input.get_layout())); topology.add(one_hot("output", "input", shape, one_hot_axis)); network network(engine, topology); network.set_input_data("input", input); auto outputs = network.execute(); EXPECT_EQ(outputs.size(), size_t(1)); EXPECT_EQ(outputs.begin()->first, "output"); auto output_memory = outputs.at("output").get_memory(); auto output_layout = output_memory.get_layout(); auto output_ptr = output_memory.pointer<T>(); VVVVF<T> output_cpu = one_hot_cpu<T>(input_rnd, one_hot_axis, one_hot_limit, input_padding_y, input_padding_x, output_padding_y, output_padding_x); EXPECT_EQ(output_layout.format.value, test_input_fmt.value); tensor output_tensor = output_layout.get_buffer_size(); int y_size = output_tensor.spatial[1]; int x_size = output_tensor.spatial[0]; int f_size = output_tensor.feature[0]; int b_size = output_tensor.batch[0]; EXPECT_EQ(y_size, (int)output_cpu[0][0].size()); EXPECT_EQ(x_size, (int)output_cpu[0][0][0].size()); EXPECT_EQ(f_size, (int)output_cpu[0].size()); EXPECT_EQ(b_size, (int)output_cpu.size()); bool test_is_correct = true; VF<T> output_cpu_vec = flatten_4d<T>(test_input_fmt, output_cpu); for (size_t i = 0; i < output_cpu_vec.size(); ++i) { if (output_cpu_vec[i] != output_ptr[i]) { test_is_correct = false; break; } } EXPECT_EQ(test_is_correct, true) << std::endl << "failing test parameters:" << std::endl << "input_b = " << input_b << std::endl << "input_f = " << input_f << std::endl << "input_y = " << input_y << std::endl << "input_x = " << input_x << std::endl << "one_hot_limit = " << one_hot_limit << std::endl << "one_hot_axis = " << one_hot_axis << std::endl << "input_padding_y = " << input_padding_y << std::endl << "input_padding_x = " << input_padding_x << std::endl << "output_padding_y = " << output_padding_y << std::endl << "output_padding_x = " << output_padding_x << std::endl; } TEST(one_hot_gpu_i32, generic_y_in10_oh5) { generic_one_hot_test_int<int32_t>(format::bfyx, 1, 10, 10, 10, tensor(10, 10, 10, 5), 2); } TEST(one_hot_error, basic_error_wrong_batch_size) { const auto& engine = get_test_engine(); auto input = memory::allocate(engine, { data_types::i32, format::bfyx, { 10, 1, 1, 1 } }); topology topology; topology.add(input_layout("input", input.get_layout())); topology.add(one_hot("output", "input", tensor(10, 1, 1, 50), 2)); std::string msg_to_find = "Incorrect parameters configuration: input batch size should be equal to 1."; EXPECT_ANY_THROW(check_exception_massage(engine, topology, msg_to_find)); } TEST(one_hot_error, basic_error_wrong_axis) { const auto& engine = get_test_engine(); auto input = memory::allocate(engine, { data_types::i32, format::bfyx,{ 1, 1, 1, 1 } }); topology topology; topology.add(input_layout("input", input.get_layout())); topology.add(one_hot("output", "input", tensor(1, 1, 1, 50), 4)); std::string msg_to_find = "Incorrect parameters configuration: one_hot_axis should be less or equal to 3."; EXPECT_ANY_THROW(check_exception_massage(engine, topology, msg_to_find)); } TEST(one_hot_error, basic_error_bad_shape) { const auto& engine = get_test_engine(); auto input = memory::allocate(engine, { data_types::i32, format::bfyx,{ 1, 1, 1, 1 } }); topology topology; topology.add(input_layout("input", input.get_layout())); topology.add(one_hot("output", "input", tensor(1, 5, 1, 50), 2)); std::string msg_to_find = "Incorrect parameters configuration: shape does not fit input size."; EXPECT_ANY_THROW(check_exception_massage(engine, topology, msg_to_find)); }
#include <gtest/gtest.h> #include <api/CPP/engine.hpp> #include <api/CPP/input_layout.hpp> #include <api/CPP/memory.hpp> #include <api/CPP/one_hot.hpp> #include <api/CPP/topology.hpp> #include <api/CPP/network.hpp> #include "test_utils/test_utils.h" #include <cstddef> using namespace cldnn; using namespace ::tests; template <typename T> VVVVF<T> one_hot_cpu(VVVVF<T> &input, uint16_t axis, int32_t one_hot_limit, int input_padding_y = 0, int input_padding_x = 0, int output_padding_y = 0, int output_padding_x = 0) { size_t padding_y = input_padding_y + output_padding_y; size_t padding_x = input_padding_x + output_padding_x; size_t out_sizes[4]; out_sizes[0] = input.size(); out_sizes[1] = input[0].size(); out_sizes[2] = input[0][0].size() + 2 * padding_y; out_sizes[3] = input[0][0][0].size() + 2 * padding_x; for (uint16_t i = 0; i < axis; ++i) out_sizes[i] = out_sizes[i + 1]; out_sizes[axis] = one_hot_limit; VVVVF<T> output(out_sizes[0], VVVF<T>(out_sizes[1], VVF<T>(out_sizes[2], VF<T>(out_sizes[3])))); switch (axis) { case 0: for (size_t b = 0; b < out_sizes[0]; ++b) for (size_t f = 0; f < out_sizes[1]; ++f) for (size_t y = 0; y < out_sizes[2]; ++y) for (size_t x = 0; x < out_sizes[3]; ++x) output[b][f][y][x] = input[0][f][y][x] == (T)b ? 1 : 0; break; case 1: for (size_t b = 0; b < out_sizes[0]; ++b) for (size_t f = 0; f < out_sizes[1]; ++f) for (size_t y = 0; y < out_sizes[2]; ++y) for (size_t x = 0; x < out_sizes[3]; ++x) output[b][f][y][x] = input[0][b][y][x] == (T)f ? 1 : 0; break; case 2: for (size_t b = 0; b < out_sizes[0]; ++b) for (size_t f = 0; f < out_sizes[1]; ++f) for (size_t y = 0; y < out_sizes[2]; ++y) for (size_t x = 0; x < out_sizes[3]; ++x) output[b][f][y][x] = input[0][b][f][x] == (T)y ? 1 : 0; break; case 3: for (size_t b = 0; b < out_sizes[0]; ++b) for (size_t f = 0; f < out_sizes[1]; ++f) for (size_t y = 0; y < out_sizes[2]; ++y) for (size_t x = 0; x < out_sizes[3]; ++x) output[b][f][y][x] = input[0][b][f][y] == (T)x ? 1 : 0; break; default: break; } return output; } template <typename T> void generic_one_hot_test_int(cldnn::format test_input_fmt, int input_b, int input_f, int input_y, int input_x, tensor shape, uint16_t one_hot_axis, int input_padding_y = 0, int input_padding_x = 0, int output_padding_y = 0, int output_padding_x = 0) { std::vector<tensor::value_type> output_dims = { shape.batch[0], shape.feature[0], shape.spatial[1], shape.spatial[0] }; int32_t one_hot_limit = output_dims[one_hot_axis]; int min_random = -2, max_random = one_hot_limit + 2; VVVVF<T> input_rnd = generate_random_4d<T>(input_b, input_f, input_y, input_x, min_random, max_random); VF<T> input_rnd_vec = flatten_4d<T>(test_input_fmt, input_rnd); const auto& engine = get_test_engine(); tensor input_tensor(input_b, input_f, input_x, input_y); auto input = memory::allocate(engine, { type_to_data_type<T>::value, test_input_fmt, input_tensor }); set_values(input, input_rnd_vec); topology topology; topology.add(input_layout("input", input.get_layout())); topology.add(one_hot("output", "input", shape, one_hot_axis)); network network(engine, topology); network.set_input_data("input", input); auto outputs = network.execute(); EXPECT_EQ(outputs.size(), size_t(1)); EXPECT_EQ(outputs.begin()->first, "output"); auto output_memory = outputs.at("output").get_memory(); auto output_layout = output_memory.get_layout(); auto output_ptr = output_memory.pointer<T>(); VVVVF<T> output_cpu = one_hot_cpu<T>(input_rnd, one_hot_axis, one_hot_limit, input_padding_y, input_padding_x, output_padding_y, output_padding_x); EXPECT_EQ(output_layout.format.value, test_input_fmt.value); tensor output_tensor = output_layout.get_buffer_size(); int y_size = output_tensor.spatial[1]; int x_size = output_tensor.spatial[0]; int f_size = output_tensor.feature[0]; int b_size = output_tensor.batch[0]; EXPECT_EQ(y_size, (int)output_cpu[0][0].size()); EXPECT_EQ(x_size, (int)output_cpu[0][0][0].size()); EXPECT_EQ(f_size, (int)output_cpu[0].size()); EXPECT_EQ(b_size, (int)output_cpu.size()); bool test_is_correct = true; VF<T> output_cpu_vec = flatten_4d<T>(test_input_fmt, output_cpu); for (size_t i = 0; i < output_cpu_vec.size(); ++i) { if (output_cpu_vec[i] != output_ptr[i]) { test_is_correct = false; break; } } EXPECT_EQ(test_is_correct, true) << std::endl << "failing test parameters:" << std::endl << "input_b = " << input_b << std::endl << "input_f = " << input_f << std::endl << "input_y = " << input_y << std::endl << "input_x = " << input_x << std::endl << "one_hot_limit = " << one_hot_limit << std::endl << "one_hot_axis = " << one_hot_axis << std::endl << "input_padding_y = " << input_padding_y << std::endl << "input_padding_x = " << input_padding_x << std::endl << "output_padding_y = " << output_padding_y << std::endl << "output_padding_x = " << output_padding_x << std::endl; } TEST(one_hot_gpu_i32, generic_y_in10_oh5) { generic_one_hot_test_int<int32_t>(format::bfyx, 1, 10, 10, 10, tensor(10, 10, 10, 5), 2); } TEST(one_hot_error, basic_error_wrong_batch_size) { const auto& engine = get_test_engine(); auto input = memory::allocate(engine, { data_types::i32, format::bfyx, { 10, 1, 1, 1 } }); topology topology; topology.add(input_layout("input", input.get_
TEST(one_hot_error, basic_error_wrong_axis) { const auto& engine = get_test_engine(); auto input = memory::allocate(engine, { data_types::i32, format::bfyx,{ 1, 1, 1, 1 } }); topology topology; topology.add(input_layout("input", input.get_layout())); topology.add(one_hot("output", "input", tensor(1, 1, 1, 50), 4)); std::string msg_to_find = "Incorrect parameters configuration: one_hot_axis should be less or equal to 3."; EXPECT_ANY_THROW(check_exception_massage(engine, topology, msg_to_find)); } TEST(one_hot_error, basic_error_bad_shape) { const auto& engine = get_test_engine(); auto input = memory::allocate(engine, { data_types::i32, format::bfyx,{ 1, 1, 1, 1 } }); topology topology; topology.add(input_layout("input", input.get_layout())); topology.add(one_hot("output", "input", tensor(1, 5, 1, 50), 2)); std::string msg_to_find = "Incorrect parameters configuration: shape does not fit input size."; EXPECT_ANY_THROW(check_exception_massage(engine, topology, msg_to_find)); }
layout())); topology.add(one_hot("output", "input", tensor(10, 1, 1, 50), 2)); std::string msg_to_find = "Incorrect parameters configuration: input batch size should be equal to 1."; EXPECT_ANY_THROW(check_exception_massage(engine, topology, msg_to_find)); }
function_block-function_prefixed
[ { "content": "#include \"api/CPP/scale_grad_input.hpp\"\n\n#include <api/CPP/topology.hpp>\n\n#include <api/CPP/network.hpp>\n\n#include <api/CPP/engine.hpp>\n\n#include \"test_utils/test_utils.h\"\n\n\n\n#include <iostream>\n\n\n\nusing namespace cldnn;\n\nusing namespace tests;\n\n\n\nTEST(scale_grad_input_gpu, basic_in2x3x2x2_scale_same_size) {\n\n // Scale : 2x3x2x2\n\n // Input : 2x3x2x2\n\n // Output : 2x3x2x2\n\n\n\n // Input:\n\n // f0: b0: 1 2 -10 b1: 0 0 -11\n\n // f0: b0: 3 4 -14 b1: 0.5 -0.5 -15 \n\n // f1: b0: 5 6 -12 b1: 1.5 5.2 -13 \n", "file_path": "tests/test_cases/scale_grad_input_test.cpp", "rank": 0, "score": 237137.36407809833 }, { "content": " class NumberStream<InputStream, true, true> : public NumberStream<InputStream, true, false> {\n\n typedef NumberStream<InputStream, true, false> Base;\n\n public:\n\n NumberStream(GenericReader& reader, InputStream& is) : Base(reader, is) {}\n\n\n\n RAPIDJSON_FORCEINLINE Ch Take() { return Base::TakePush(); }\n\n };\n\n\n\n template<unsigned parseFlags, typename InputStream, typename Handler>\n\n void ParseNumber(InputStream& is, Handler& handler) {\n\n internal::StreamLocalCopy<InputStream> copy(is);\n\n NumberStream<InputStream,\n\n ((parseFlags & kParseNumbersAsStringsFlag) != 0) ?\n\n ((parseFlags & kParseInsituFlag) == 0) :\n\n ((parseFlags & kParseFullPrecisionFlag) != 0),\n\n (parseFlags & kParseNumbersAsStringsFlag) != 0 &&\n\n (parseFlags & kParseInsituFlag) == 0> s(*this, copy.s);\n\n\n\n size_t startOffset = s.Tell();\n\n double d = 0.0;\n", "file_path": "utils/rapidjson/reader.h", "rank": 1, "score": 237136.9563120653 }, { "content": "\n\n auto outputs = network.execute();\n\n\n\n auto output = outputs.at(\"scale_grad\").get_memory();\n\n auto output_ptr = output.pointer<float>();\n\n\n\n for (unsigned int i = 0; i < input_vec.size(); ++i) {\n\n EXPECT_NEAR(output_ptr[i], input_vec[i] * scale_input_vec[i], 1e-05F);\n\n }\n\n}", "file_path": "tests/test_cases/scale_grad_input_test.cpp", "rank": 2, "score": 237119.69029615325 }, { "content": " // f1: b0: 7 8 -16 b1: 12 8 -17\n\n //\n\n // Scale:\n\n // f0: b0: 0.1 0.2 0.25 b1: 0.3 0.4 0.5\n\n // f0: b0: 0.6 0.7 0.75 b1: 0.8 0.9 1 \n\n // f1: b0: 1.1 1.2 1.25 b1: 1.3 1.4 1.5 \n\n // f1: b0: 1.6 1.7 1.75 b1: 1.8 1.9 2\n\n\n\n const auto& engine = get_test_engine();\n\n\n\n auto input = memory::allocate(engine, { data_types::f32, format::yxfb,{ 2, 2, 3, 2 } });\n\n auto scale_input = memory::allocate(engine, { data_types::f32, format::yxfb,{ 2, 2, 3, 2 } });\n\n\n\n topology topology;\n\n topology.add(input_layout(\"input\", input.get_layout()));\n\n topology.add(input_layout(\"scale_input\", scale_input.get_layout()));\n\n topology.add(scale_grad_input(\"scale_grad\", \"input\", \"scale_input\"));\n\n\n\n std::vector<float> input_vec = { 1.f, 0.f, 5.f, 1.5f,\n\n 2.f, 0.f, 6.f, 5.2f,\n", "file_path": "tests/test_cases/scale_grad_input_test.cpp", "rank": 3, "score": 237114.3759693579 }, { "content": " -10.f, -11.f, -12.f, -13.f,\n\n 3.f, 0.5f, 7.f, 12.f,\n\n 4.f, -0.5f, 8.f, 8.f,\n\n -14.f, -15.f, -16.f, -17.f };\n\n set_values(input, input_vec);\n\n\n\n std::vector<float> scale_input_vec = {\n\n 0.1f, 0.3f, 1.1f, 1.3f,\n\n 0.2f, 0.4f, 1.2f, 1.4f,\n\n 0.25f, 0.5f, 1.25f, 1.5f,\n\n 0.6f, 0.8f, 1.6f, 1.8f,\n\n 0.7f, 0.9f, 1.7f, 1.9f,\n\n 0.75f, 1.f, 1.75f, 2.f\n\n };\n\n set_values(scale_input, scale_input_vec);\n\n\n\n network network(engine, topology);\n\n\n\n network.set_input_data(\"input\", input);\n\n network.set_input_data(\"scale_input\", scale_input);\n", "file_path": "tests/test_cases/scale_grad_input_test.cpp", "rank": 4, "score": 237108.3579091309 }, { "content": "/*\n\n// Copyright (c) 2018 Intel Corporation\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n*/\n\n\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n#include <gtest/gtest.h>\n\n#include \"api/CPP/memory.hpp\"\n\n#include <api/CPP/input_layout.hpp>\n", "file_path": "tests/test_cases/scale_grad_input_test.cpp", "rank": 5, "score": 237092.4781405622 }, { "content": "#include <api/CPP/input_layout.hpp>\n\n#include \"api/CPP/convolution_grad_input.hpp\"\n\n#include <api/CPP/data.hpp>\n\n#include <api/CPP/topology.hpp>\n\n#include <api/CPP/network.hpp>\n\n#include <api/CPP/engine.hpp>\n\n#include \"test_utils/test_utils.h\"\n\n#include \"api/CPP/eltwise.hpp\"\n\n\n\nusing namespace cldnn;\n\nusing namespace tests;\n\n\n\nTEST(convolution_grad_input_f32_fw_gpu, basic_wsiz2x2_in2x2x1x2_bfyx_stride2_pad1) {\n\n // Filter : 2x2\n\n // Input : 2x2x1x2\n\n // Output : 2x2x1x2\n\n // Stride : 2x2\n\n //\n\n // Input:\n\n // 8 0.5 1 3\n", "file_path": "tests/test_cases/convolution_grad_input_gpu_test.cpp", "rank": 6, "score": 231331.14139293935 }, { "content": " //\n\n // Output:\n\n // -4 3.5 -0.5 21\n\n // 12 -18 4 -9\n\n\n\n const auto& engine = get_test_engine();\n\n\n\n auto input = memory::allocate(engine, { data_types::f32, format::bfyx,{ 2, 1, 2, 2 } });\n\n auto weights = memory::allocate(engine, { data_types::f32, format::bfyx,{ 1, 1, 2, 2 } });\n\n\n\n set_values(input, { 8.f, 0.5f, 6.f, 9.f, 1.f, 3.f, 2.f, 4.f });\n\n set_values(weights, { -2.f, 2.f, 7.f, -0.5f });\n\n\n\n topology topology(\n\n input_layout(\"input\", input.get_layout()),\n\n data(\"weights\", weights),\n\n convolution_grad_input(\"deconv\", \"input\", { \"weights\" }, { 1, 1, 2, 2 }, { 0, 0, -1, -1 }, { 2, 1, 2, 2 })\n\n );\n\n\n\n network network(engine, topology);\n", "file_path": "tests/test_cases/convolution_grad_input_gpu_test.cpp", "rank": 7, "score": 231321.8778394046 }, { "content": "\n\n build_options options;\n\n options.set_option(build_option::optimize_data(true));\n\n \n\n network network(engine, topology, options);\n\n network.set_input_data(\"input\", input);\n\n\n\n auto outputs = network.execute();\n\n auto primitives = network.get_all_primitive_ids();\n\n auto exec_prim = network.get_executed_primitive_ids();\n\n EXPECT_EQ(outputs.size(), size_t(1));\n\n EXPECT_EQ(outputs.begin()->first, \"scale\");\n\n EXPECT_TRUE(std::find(primitives.begin(), primitives.end(), \"elt\") == primitives.end());\n\n EXPECT_TRUE(std::find(exec_prim.begin(), exec_prim.end(), \"elt\") == exec_prim.end());\n\n \n\n auto output_prim = outputs.begin()->second.get_memory();\n\n\n\n auto output_ptr = output_prim.pointer<float>();\n\n\n\n std::vector<float> expected_output_vec = {\n\n -3.f, 5.5f, 14.f, -15.f,\n\n 4.5f, 27.f, 10.f, -1.f\n\n };\n\n\n\n for (unsigned int i = 0; i < expected_output_vec.size(); i++)\n\n {\n\n EXPECT_FLOAT_EQ(expected_output_vec[i], output_ptr[i]);\n\n }\n\n}", "file_path": "tests/test_cases/convolution_grad_input_gpu_test.cpp", "rank": 8, "score": 231318.86288798918 }, { "content": " // 6 9 2 4\n\n //\n\n // Filter\n\n // -2 2\n\n // 7 -0.5\n\n //\n\n // Output:\n\n // -4 3.5 -0.5 21\n\n // 12 -18 4 -9\n\n\n\n const auto& engine = get_test_engine();\n\n\n\n auto input = memory::allocate(engine, { data_types::f32, format::bfyx,{ 2, 1, 2, 2 } });\n\n auto weights = memory::allocate(engine, { data_types::f32, format::bfyx,{ 1, 1, 2, 2 } });\n\n\n\n set_values(input, { 8.f, 0.5f, 6.f, 9.f, 1.f, 3.f, 2.f, 4.f });\n\n set_values(weights, { -2.f, 2.f, 7.f, -0.5f });\n\n\n\n topology topology(\n\n input_layout(\"input\", input.get_layout()),\n", "file_path": "tests/test_cases/convolution_grad_input_gpu_test.cpp", "rank": 9, "score": 231315.75033209898 }, { "content": " data(\"weights\", weights),\n\n convolution_grad_input(\"deconv\", \"input\", { \"weights\" }, { 1, 1, 2, 2 }, { 0, 0, -1, -1 })\n\n );\n\n\n\n network network(engine, topology);\n\n network.set_input_data(\"input\", input);\n\n\n\n auto outputs = network.execute();\n\n EXPECT_EQ(outputs.size(), size_t(1));\n\n EXPECT_EQ(outputs.begin()->first, \"deconv\");\n\n\n\n auto output_prim = outputs.begin()->second.get_memory();\n\n\n\n auto output_ptr = output_prim.pointer<float>();\n\n\n\n std::vector<float> expected_output_vec = {\n\n -4.f, 3.5f, 12.f, -18.f,\n\n -.5f, 21.f, 4.f, -8.f\n\n };\n\n\n", "file_path": "tests/test_cases/convolution_grad_input_gpu_test.cpp", "rank": 10, "score": 231315.46086818678 }, { "content": "\n\nTEST(convolution_grad_input_f32_fw_gpu, DISABLED_basic_wsiz2x2_in2x2x1x2_bfyx_stride2_fusion) {\n\n // Filter : 2x2\n\n // Input : 2x2x1x2\n\n // Output : 2x2x1x2\n\n // Stride : 2x2\n\n //\n\n // Input:\n\n // 8 0.5 1 3\n\n // 6 9 2 4\n\n //\n\n // Filter\n\n // -2 2\n\n // 7 -0.5\n\n //\n\n // Output:\n\n // -4 3.5 -0.5 21\n\n // 12 -18 4 -9\n\n\n\n const auto& engine = get_test_engine();\n", "file_path": "tests/test_cases/convolution_grad_input_gpu_test.cpp", "rank": 11, "score": 231309.3672806167 }, { "content": " network.set_input_data(\"input\", input);\n\n\n\n auto outputs = network.execute();\n\n EXPECT_EQ(outputs.size(), size_t(1));\n\n EXPECT_EQ(outputs.begin()->first, \"deconv\");\n\n\n\n auto output_prim = outputs.begin()->second.get_memory();\n\n\n\n auto output_ptr = output_prim.pointer<float>();\n\n\n\n std::vector<float> expected_output_vec = {\n\n -4.f, 3.5f, 12.f, -18.f,\n\n -.5f, 21.f, 4.f, -8.f\n\n };\n\n\n\n for (unsigned int i = 0; i < expected_output_vec.size(); i++)\n\n {\n\n EXPECT_FLOAT_EQ(expected_output_vec[i], output_ptr[i]);\n\n }\n\n}\n", "file_path": "tests/test_cases/convolution_grad_input_gpu_test.cpp", "rank": 12, "score": 231308.01946095112 }, { "content": "\n\n auto input = memory::allocate(engine, { data_types::f32, format::bfyx,{ 2, 1, 2, 2 } });\n\n auto weights = memory::allocate(engine, { data_types::f32, format::bfyx,{ 1, 1, 2, 2 } });\n\n auto scale_in = memory::allocate(engine, { data_types::f32, format::bfyx,{ 1, 1, 1, 1 } });\n\n auto elt_data = memory::allocate(engine, { data_types::f32, format::bfyx,{ 2, 2, 1, 2 } });\n\n\n\n set_values(input, { 8.f, 0.5f, 6.f, 9.f, 1.f, 3.f, 2.f, 4.f });\n\n set_values(weights, { -2.f, 2.f, 7.f, -0.5f });\n\n set_values(scale_in, { 1.0f });\n\n set_values(elt_data, { 1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f });\n\n\n\n topology topology(\n\n input_layout(\"input\", input.get_layout()),\n\n data(\"weights\", weights),\n\n data(\"scale_in\", scale_in),\n\n data(\"elt_data\", elt_data),\n\n convolution_grad_input(\"conv\", \"input\", { \"weights\" }, { 1, 1, 2, 2 }, { 0, 0, -1, -1 }),\n\n eltwise(\"elt\", \"conv\", \"elt_data\", eltwise_mode::sum),\n\n scale(\"scale\", \"elt\", \"scale_in\")\n\n );\n", "file_path": "tests/test_cases/convolution_grad_input_gpu_test.cpp", "rank": 13, "score": 231302.36092487077 }, { "content": " for (unsigned int i = 0; i < expected_output_vec.size(); i++)\n\n {\n\n EXPECT_FLOAT_EQ(expected_output_vec[i], output_ptr[i]);\n\n }\n\n}\n\n\n\n\n\nTEST(convolution_grad_input_f32_fw_gpu, basic_wsiz2x2_in2x2x1x2_bfyx_stride2_pad1_output_size) {\n\n // Filter : 2x2\n\n // Input : 2x2x1x2\n\n // Output : 2x2x1x2\n\n // Stride : 2x2\n\n //\n\n // Input:\n\n // 8 0.5 1 3\n\n // 6 9 2 4\n\n //\n\n // Filter\n\n // -2 2\n\n // 7 -0.5\n", "file_path": "tests/test_cases/convolution_grad_input_gpu_test.cpp", "rank": 14, "score": 231300.8692755659 }, { "content": "/*\n\n// Copyright (c) 2016 Intel Corporation\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n*/\n\n\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n\n\n#include <gtest/gtest.h>\n\n#include \"api/CPP/memory.hpp\"\n", "file_path": "tests/test_cases/convolution_grad_input_gpu_test.cpp", "rank": 15, "score": 231278.70735549217 }, { "content": "class detection_output_test : public ::testing::Test\n\n{\n\n\n\npublic:\n\n detection_output_test() :\n\n nms_threshold(0.1f)\n\n {}\n\n\n\n void init_buffers(cldnn::memory prior_memory, cldnn::memory confidence_memory, cldnn::memory location_memory,\n\n bool share_location, bool variance_encoded_in_target = false,\n\n int prior_info_size = 4, int prior_coordinates_offset = 0, bool prior_is_normalized = true)\n\n {\n\n auto location_ptr = location_memory.pointer<T>();\n\n auto confidence_ptr = confidence_memory.pointer<T>();\n\n auto prior_box_ptr = prior_memory.pointer<T>();\n\n\n\n T* prior_data = prior_box_ptr.data();\n\n T* confidence_data = confidence_ptr.data();\n\n T* location_data = location_ptr.data();\n\n\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 16, "score": 227452.1501558372 }, { "content": "#include <api/CPP/input_layout.hpp>\n\n#include \"api/CPP/fully_connected_grad_input.hpp\"\n\n#include <api/CPP/data.hpp>\n\n#include <api/CPP/topology.hpp>\n\n#include <api/CPP/network.hpp>\n\n#include <api/CPP/engine.hpp>\n\n#include \"test_utils/test_utils.h\"\n\n\n\nusing namespace cldnn;\n\nusing namespace tests;\n\n\n\nTEST(fully_connected_grad_input_gpu, basic_bfyx) {\n\n // Filter : 2x2\n\n // Input : 2x2x1x2\n\n // Output : 2x2x1x2\n\n // Stride : 2x2\n\n //\n\n // Input:\n\n // -0.5 2 0.5\n\n //\n", "file_path": "tests/test_cases/fully_connected_grad_input_gpu_test.cpp", "rank": 17, "score": 225828.4911068092 }, { "content": " set_values(input_grad, { 1.5f, 0.75f, -2.25f, 3.0f });\n\n set_values(weights, { 1.5f, 1.0f, 0.5f, -1.0f, 0.0f, 0.5f, 0.5f, -0.5f, -2.0f, -0.5f, 1.0f, 1.5f });\n\n\n\n topology topology(\n\n input_layout(\"input_grad\", input_grad.get_layout()),\n\n data(\"input\", input),\n\n data(\"weights\", weights),\n\n fully_connected_grad_input(\"fully_connected_grad_input\", \"input_grad\", \"input\", { \"weights\" })\n\n );\n\n\n\n network network(engine, topology);\n\n network.set_input_data(\"input_grad\", input_grad);\n\n\n\n auto outputs = network.execute();\n\n EXPECT_EQ(outputs.size(), size_t(1));\n\n EXPECT_EQ(outputs.begin()->first, \"fully_connected_grad_input\");\n\n\n\n auto output_prim = outputs.begin()->second.get_memory();\n\n\n\n auto output_ptr = output_prim.pointer<float>();\n", "file_path": "tests/test_cases/fully_connected_grad_input_gpu_test.cpp", "rank": 18, "score": 225812.09154693445 }, { "content": " // Input_grad:\n\n // 1.5 0.75 -2.25 3\n\n //\n\n // Weights:\n\n // 1.5 1 0.5\n\n // -1 0 0.5\n\n // 0.5 -0.5 -2\n\n // -0.5 1 1.5\n\n //\n\n // Output:\n\n // -1.125 5.625 10.125\n\n\n\n\n\n const auto& engine = get_test_engine();\n\n\n\n auto input_grad = memory::allocate(engine, { data_types::f32, format::bfyx,{ 1, 1, 4, 1 } });\n\n auto input = memory::allocate(engine, { data_types::f32, format::bfyx,{ 1, 1, 3, 1 } });\n\n auto weights = memory::allocate(engine, { data_types::f32, format::bfyx,{ 4, 1, 3, 1 } });\n\n\n\n set_values(input, { -0.5f, 2.0f, 0.5f });\n", "file_path": "tests/test_cases/fully_connected_grad_input_gpu_test.cpp", "rank": 19, "score": 225804.2839497941 }, { "content": "\n\n std::vector<float> expected_output_vec = {\n\n -1.125f, 5.625f, 10.125f\n\n };\n\n\n\n for (unsigned int i = 0; i < expected_output_vec.size(); i++)\n\n {\n\n EXPECT_FLOAT_EQ(expected_output_vec[i], output_ptr[i]);\n\n }\n\n}", "file_path": "tests/test_cases/fully_connected_grad_input_gpu_test.cpp", "rank": 20, "score": 225777.3948983226 }, { "content": "/*\n\n// Copyright (c) 2016 Intel Corporation\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n*/\n\n\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n\n\n#include <gtest/gtest.h>\n\n#include \"api/CPP/memory.hpp\"\n", "file_path": "tests/test_cases/fully_connected_grad_input_gpu_test.cpp", "rank": 21, "score": 225774.06355486414 }, { "content": "enum class resource_flags : int\n\n{\n\n NONE = 0,\n\n READ_WRITE = (1 << 0),\n\n READ_ONLY = (1 << 1),\n\n WRITE_ONLY = (1 << 2),\n\n DEVICE_ONLY = (1 << 3), // no access from host, fill with data available only on creation\n\n COPY_HOST_PTR = (1 << 4) // will copy host pointer data on creation\n\n};\n\ninline resource_flags operator|(resource_flags a, resource_flags b)\n\n{\n\n return static_cast<resource_flags>(static_cast<int>(a) | static_cast<int>(b));\n\n}\n\ninline resource_flags operator&(resource_flags a, resource_flags b)\n\n{\n\n return static_cast<resource_flags>(static_cast<int>(a) & static_cast<int>(b));\n\n}\n\n\n", "file_path": "src/include/engine_impl.h", "rank": 22, "score": 200874.20709620236 }, { "content": " class topology_generator\n\n {\n\n public:\n\n typedef std::pair<cldnn::primitive_id, cldnn::layout> named_layout;\n", "file_path": "tests/test_cases/topology_test.cpp", "rank": 23, "score": 198196.65086779118 }, { "content": "class mvn_gpu_test : public ::testing::TestWithParam<cldnn::format>\n\n{\n\n};\n\n\n\ntemplate <typename T>\n\nvoid mvn_compute_mean_accross_channels_bfyx(cldnn::memory &output, bool normalize_variance)\n\n{\n\n using namespace tests;\n\n\n\n const auto output_desc = generic_test::get_linear_memory_desc(output.get_layout());\n\n\n\n auto output_sizes = output.get_layout().size.sizes();\n\n\n\n uint32_t batch_size = output_sizes[0];\n\n uint32_t feature_size = output_sizes[1];\n\n uint32_t y_size = output_sizes[3];\n\n uint32_t x_size = output_sizes[2];\n\n\n\n auto buff = output.pointer<T>();\n\n\n", "file_path": "tests/test_cases/mvn_gpu_test.cpp", "rank": 24, "score": 197263.85573782507 }, { "content": "class topology_test : public ::testing::TestWithParam<topology_params>\n\n{\n\nprotected:\n", "file_path": "tests/test_cases/topology_test.cpp", "rank": 25, "score": 196072.959663908 }, { "content": " class topology_layer_type\n\n {\n\n public:\n\n // return false for invalid output_layout\n\n virtual bool AddPrimitive(cldnn::topology& topology, cldnn::primitive_id id, cldnn::layout output_layout, std::deque<named_layout>& input_layouts) = 0;\n\n };\n\n static std::vector<topology_layer_type*> layer_types;\n\n static cldnn::topology* CreateTopology(cldnn::layout output_layout, const std::vector<unsigned> generator_vec)\n\n {\n\n if (generator_vec.size() < 2)\n\n {\n\n return nullptr;\n\n }\n\n auto topology = new cldnn::topology();\n\n std::deque<named_layout> inputs;\n\n const unsigned max_index = generator_vec[0];\n\n inputs.push_back({ output_layer_id, output_layout });\n\n for (unsigned g_index = 1; g_index < generator_vec.size(); g_index++)\n\n {\n\n auto input = inputs.front();\n", "file_path": "tests/test_cases/topology_test.cpp", "rank": 26, "score": 194251.24939064903 }, { "content": " {\n\n //todo: allocate mem, randomize values by type, add to topology\n\n auto mem_primitive = cldnn::memory::allocate(topology_test::engine, layout);\n\n switch (layout.data_type)\n\n {\n\n case cldnn::data_types::f32:\n\n tests::set_random_values<float>(mem_primitive, true, 10, 1);\n\n break;\n\n case cldnn::data_types::f16:\n\n tests::set_random_values<FLOAT16>(mem_primitive, true, 4, 1);\n\n break;\n\n default:\n\n assert(0);\n\n }\n\n topology.add(cldnn::data(id, mem_primitive));\n\n }\n\n protected:\n\n topology_generator() {}\n\n\n", "file_path": "tests/test_cases/topology_test.cpp", "rank": 27, "score": 192082.06796316768 }, { "content": "#include <set>\n\n\n\ntypedef std::tuple<cldnn::layout*, std::vector<unsigned>> topology_params;\n\n\n\nvoid PrintTupleTo(const topology_params& t, ::std::ostream* os)\n\n{\n\n const auto & output_layout = std::get<0>(t);\n\n const auto & generator = std::get<1>(t);\n\n std::stringstream ss;\n\n\n\n ss << \"Topology test failed: (\"\n\n << cldnn::data_type_traits::name(output_layout->data_type) << \" \"\n\n << tests::test_params::print_tensor(output_layout->size) << \") Generator: [\";\n\n for (auto v : generator)\n\n {\n\n ss << v << \", \";\n\n }\n\n ss.seekp(-1, ss.cur) << \"]\\n\";\n\n *os << ss.str();\n\n}\n\n\n", "file_path": "tests/test_cases/topology_test.cpp", "rank": 28, "score": 192079.21961900007 }, { "content": " return \"tg_layer_\" + std::to_string(layer_id++);\n\n }\n\n static const cldnn::primitive_id output_layer_id;\n\n static bool AddSinglePrimitive(cldnn::topology& topology, cldnn::primitive_id id, cldnn::layout output_layout, std::deque<named_layout>& input_layouts, unsigned type_index, unsigned max_type)\n\n {\n\n if (layer_types.size() < max_type)\n\n {\n\n return false;//shouldn't happen\n\n }\n\n for (unsigned t = 0; t < max_type; t++)\n\n {\n\n if (layer_types.at((type_index + t) % max_type)->AddPrimitive(topology, id, output_layout, input_layouts))\n\n {\n\n return true;\n\n }\n\n }\n\n //todo: consider using a data primitive here\n\n return false;\n\n }\n\n static void AddRandomMemory(cldnn::topology& topology, cldnn::primitive_id id, cldnn::layout layout)\n", "file_path": "tests/test_cases/topology_test.cpp", "rank": 29, "score": 192076.1899444444 }, { "content": " output_layout.size.spatial[1]\n\n }\n\n );\n\n cldnn::layout input_layout2(\n\n output_layout.data_type,\n\n cldnn::format::bfyx,\n\n {\n\n output_layout.size.batch[0],\n\n 1,\n\n output_layout.size.spatial[0],\n\n output_layout.size.spatial[1]\n\n }\n\n );\n\n input_layouts.push_back({ input_id1, input_layout1 });\n\n input_layouts.push_back({ input_id2, input_layout2 });\n\n \n\n topology.add(cldnn::concatenation(id, { input_id1,input_id2 }, cldnn::concatenation::along_f));\n\n return true;\n\n }\n\n };\n", "file_path": "tests/test_cases/topology_test.cpp", "rank": 30, "score": 192069.23879309394 }, { "content": " delete topology;\n\n }\n\n\n\n static std::vector<cldnn::layout*> generate_all_output_layouts()\n\n {\n\n assert(all_output_layouts.empty());\n\n std::vector<cldnn::data_types> data_types = { cldnn::data_types::f32, cldnn::data_types::f16 };\n\n std::vector<cldnn::tensor> output_tensors = {\n\n { 1, 1, 100, 1 },\n\n { 5, 1, 100, 1 },\n\n { 1, 10, 100, 100 },\n\n { 8, 1, 100, 100 },\n\n };\n\n // todo: consider iterating on format X dimensions\n\n\n\n for (auto dt : data_types) {\n\n for (auto t : output_tensors) {\n\n all_output_layouts.push_back(new cldnn::layout(dt, cldnn::format::bfyx, t));\n\n }\n\n }\n", "file_path": "tests/test_cases/topology_test.cpp", "rank": 31, "score": 192066.24267023473 }, { "content": " }\n\n all_generators.insert(generator);\n\n }\n\n }\n\n return all_generators;\n\n }\n\n static void TearDownTestCase()\n\n {\n\n for (auto& p : all_output_layouts)\n\n {\n\n delete p;\n\n }\n\n }\n\n static std::string custom_param_name(const ::testing::TestParamInfo<topology_params>& info)\n\n {\n\n const auto & output_layout = std::get<0>(info.param);\n\n const auto & generator = std::get<1>(info.param);\n\n std::stringstream ss;\n\n ss << info.index << \"_\";\n\n for (auto v : generator)\n", "file_path": "tests/test_cases/topology_test.cpp", "rank": 32, "score": 192064.17748623848 }, { "content": " inputs.pop_front();\n\n if (!AddSinglePrimitive(*topology, input.first, input.second, inputs, generator_vec.at(g_index), max_index))\n\n {\n\n delete topology;\n\n return nullptr;\n\n }\n\n }\n\n // add data inputs\n\n for (const auto& input : inputs)\n\n {\n\n //first add a reorder to enable optimize_data\n\n cldnn::primitive_id input_data_id = input.first + \"_input\";\n\n topology->add(cldnn::reorder(input.first, input_data_id, input.second));\n\n AddRandomMemory(*topology, input_data_id, input.second);\n\n }\n\n return topology;\n\n }\n\n static cldnn::primitive_id CreateLayerId()\n\n {\n\n static unsigned layer_id = 0;\n", "file_path": "tests/test_cases/topology_test.cpp", "rank": 33, "score": 192063.54383110887 }, { "content": "const cldnn::engine& topology_test::engine = tests::get_test_engine();\n\nstd::vector<cldnn::layout*> topology_test::all_output_layouts = {};\n\n\n\nstd::vector<topology_test::topology_generator::topology_layer_type*> topology_test::topology_generator::layer_types = {\n\n new topology_test::topology_generator::normalization_layer_type(),\n\n new topology_test::topology_generator::pooling_layer_type(),\n\n new topology_test::topology_generator::convolution_layer_type(),\n\n new topology_test::topology_generator::fully_connected_layer_type(),\n\n new topology_test::topology_generator::reorder_layer_type(),\n\n new topology_test::topology_generator::activation_layer_type(),\n\n new topology_test::topology_generator::depth_concatenate_layer_type(),\n\n new topology_test::topology_generator::eltwise_layer_type(),\n\n new topology_test::topology_generator::scale_layer_type(),\n\n new topology_test::topology_generator::softmax_layer_type(),\n\n // Only add new types at the end\n\n};\n\nconst cldnn::primitive_id topology_test::topology_generator::output_layer_id(\"tg_output_layer\");\n\n\n\nTEST_P(topology_test, TOPOLOGY)\n\n{\n", "file_path": "tests/test_cases/topology_test.cpp", "rank": 34, "score": 192062.23560235545 }, { "content": " return all_output_layouts;\n\n }\n\n template<unsigned generator_length>\n\n static std::set<std::vector<unsigned>> all_generator_vectors()\n\n {\n\n // create vectors used to create topologies [max_layer_index, layer_index0, layer_index1,...]\n\n std::set<std::vector<unsigned>> all_generators;\n\n static std::default_random_engine rng(tests::random_seed);\n\n std::uniform_int_distribution<unsigned> distribution(0, 0xFF);//assuming we won't exceed 256 total layer types\n\n\n\n const unsigned Initial_layer_types = 10;//don't change this - starting with this index ensures adding layers won't alter previously generated tests\n\n for (unsigned types = Initial_layer_types; types <= topology_test::topology_generator::layer_types.size(); types++)\n\n {\n\n for (unsigned i = 0; i < topologies_per_type_size; i++)\n\n {\n\n std::vector<unsigned> generator;\n\n generator.push_back(types);\n\n for (unsigned j = 0; j < generator_length; j++)\n\n {\n\n generator.push_back(distribution(rng) % types);\n", "file_path": "tests/test_cases/topology_test.cpp", "rank": 35, "score": 192059.2799350556 }, { "content": "#include <gtest/gtest.h>\n\n#include <api/CPP/topology.hpp>\n\n#include <api/CPP/network.hpp>\n\n#include <api/CPP/engine.hpp>\n\n#include \"test_utils/test_utils.h\"\n\n#include <include/topology_impl.h>\n\n#include <iostream>\n\n#include \"api/CPP/memory.hpp\"\n\n#include <api/CPP/lrn.hpp>\n\n#include <api/CPP/convolution.hpp>\n\n#include <api/CPP/fully_connected.hpp>\n\n#include <api/CPP/pooling.hpp>\n\n#include <api/CPP/data.hpp>\n\n#include <api/CPP/reorder.hpp>\n\n#include <api/CPP/scale.hpp>\n\n#include <api/CPP/eltwise.hpp>\n\n#include <api/CPP/softmax.hpp>\n\n#include <api/CPP/activation.hpp>\n\n#include <api/CPP/concatenation.hpp>\n\n#include <deque>\n", "file_path": "tests/test_cases/topology_test.cpp", "rank": 36, "score": 192055.3453253813 }, { "content": " {\n\n ss << v << \"_\";\n\n }\n\n ss << cldnn::data_type_traits::name(output_layout->data_type) << \"_\";\n\n ss << cldnn::format::traits(output_layout->format).order;\n\n for (const auto& d : output_layout->size.raw)\n\n {\n\n ss << \"_\" << d;\n\n }\n\n \n\n return ss.str();\n\n }\n\nprotected:\n\n cldnn::layout* output_layout;\n\n std::vector<unsigned> generator;\n\n\n\n static const cldnn::engine& engine;\n\n static std::vector<cldnn::layout*> all_output_layouts;//just for tear-down\n\n};\n\n\n", "file_path": "tests/test_cases/topology_test.cpp", "rank": 37, "score": 192055.1104614047 }, { "content": " try\n\n {\n\n run_single_test();\n\n if (::testing::Test::HasFailure())\n\n {\n\n PrintTupleTo(GetParam(), &std::cout);\n\n }\n\n }\n\n catch (...)\n\n {\n\n PrintTupleTo(GetParam(), &std::cout);\n\n throw;\n\n }\n\n}\n\n\n\nINSTANTIATE_TEST_CASE_P(DISABLED_TOPOLOGY,\n\n topology_test,\n\n ::testing::Combine( ::testing::ValuesIn(topology_test::generate_all_output_layouts()),\n\n ::testing::ValuesIn(topology_test::all_generator_vectors<3>())),\n\n topology_test::custom_param_name);\n", "file_path": "tests/test_cases/topology_test.cpp", "rank": 38, "score": 192054.69460178472 }, { "content": "}\n\n\n\nTEST(tensor_api, order_new_notation_feature_default)\n\n{\n\n cldnn::tensor test{ cldnn::feature(3), cldnn::spatial(2) };\n\n\n\n //sizes\n\n EXPECT_EQ(test.batch.size(), size_t(1));\n\n EXPECT_EQ(test.feature.size(), size_t(1));\n\n EXPECT_EQ(test.spatial.size(), size_t(3));\n\n\n\n //passed values\n\n EXPECT_EQ(test.spatial[0], cldnn::tensor::value_type(2));\n\n EXPECT_EQ(test.spatial[1], cldnn::tensor::value_type(1));\n\n EXPECT_EQ(test.feature[0], cldnn::tensor::value_type(3));\n\n EXPECT_EQ(test.batch[0], cldnn::tensor::value_type(1));\n\n\n\n //reverse\n\n auto sizes = test.sizes();\n\n EXPECT_EQ(sizes[0], cldnn::tensor::value_type(1));\n", "file_path": "tests/test_cases/tensor_test.cpp", "rank": 39, "score": 192037.47858826123 }, { "content": "{\n\n cldnn::tensor test{ cldnn::feature(3), cldnn::batch(4), cldnn::spatial(2, 1) };\n\n\n\n //sizes\n\n EXPECT_EQ(test.batch.size(), size_t(1));\n\n EXPECT_EQ(test.feature.size(), size_t(1));\n\n EXPECT_EQ(test.spatial.size(), size_t(3));\n\n\n\n //passed values\n\n EXPECT_EQ(test.spatial[0], cldnn::tensor::value_type(2));\n\n EXPECT_EQ(test.spatial[1], cldnn::tensor::value_type(1));\n\n EXPECT_EQ(test.feature[0], cldnn::tensor::value_type(3));\n\n EXPECT_EQ(test.batch[0], cldnn::tensor::value_type(4));\n\n\n\n //reverse\n\n auto sizes = test.sizes();\n\n EXPECT_EQ(sizes[0], cldnn::tensor::value_type(4));\n\n EXPECT_EQ(sizes[1], cldnn::tensor::value_type(3));\n\n EXPECT_EQ(sizes[2], cldnn::tensor::value_type(2));\n\n EXPECT_EQ(sizes[3], cldnn::tensor::value_type(1));\n", "file_path": "tests/test_cases/tensor_test.cpp", "rank": 40, "score": 192033.2674228596 }, { "content": " EXPECT_EQ(sizes[1], cldnn::tensor::value_type(3));\n\n EXPECT_EQ(sizes[2], cldnn::tensor::value_type(2));\n\n EXPECT_EQ(sizes[3], cldnn::tensor::value_type(1));\n\n}\n\n\n\nTEST(tensor_api, order)\n\n{\n\n cldnn::tensor test{ 1, 2, 3, 4 };\n\n\n\n //sizes\n\n EXPECT_EQ(test.batch.size(), size_t(1));\n\n EXPECT_EQ(test.feature.size(), size_t(1));\n\n EXPECT_EQ(test.spatial.size(), size_t(3));\n\n\n\n //passed values\n\n EXPECT_EQ(test.spatial[1], cldnn::tensor::value_type(4));\n\n EXPECT_EQ(test.spatial[0], cldnn::tensor::value_type(3));\n\n EXPECT_EQ(test.feature[0], cldnn::tensor::value_type(2));\n\n EXPECT_EQ(test.batch[0], cldnn::tensor::value_type(1));\n\n\n\n //reverse\n\n auto sizes = test.sizes();\n\n EXPECT_EQ(sizes[0], cldnn::tensor::value_type(1));\n\n EXPECT_EQ(sizes[1], cldnn::tensor::value_type(2));\n\n EXPECT_EQ(sizes[2], cldnn::tensor::value_type(3));\n\n EXPECT_EQ(sizes[3], cldnn::tensor::value_type(4));\n\n}", "file_path": "tests/test_cases/tensor_test.cpp", "rank": 41, "score": 192032.9813467189 }, { "content": "/*\n\n// Copyright (c) 2016 Intel Corporation\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n*/\n\n\n\n#include <gtest/gtest.h>\n\n#include <api/CPP/tensor.hpp>\n\n\n\nTEST(tensor_api, order_new_notation)\n", "file_path": "tests/test_cases/tensor_test.cpp", "rank": 42, "score": 192026.05353660753 }, { "content": " class NumberStream<InputStream, true, false> : public NumberStream<InputStream, false, false> {\n\n typedef NumberStream<InputStream, false, false> Base;\n\n public:\n\n NumberStream(GenericReader& reader, InputStream& is) : Base(reader, is), stackStream(reader.stack_) {}\n\n\n\n RAPIDJSON_FORCEINLINE Ch TakePush() {\n\n stackStream.Put(static_cast<char>(Base::is.Peek()));\n\n return Base::is.Take();\n\n }\n\n\n\n RAPIDJSON_FORCEINLINE void Push(char c) {\n\n stackStream.Put(c);\n\n }\n\n\n\n size_t Length() { return stackStream.Length(); }\n\n\n\n const char* Pop() {\n\n stackStream.Put('\\0');\n\n return stackStream.Pop();\n\n }\n\n\n\n private:\n\n StackStream<char> stackStream;\n\n };\n\n\n\n template<typename InputStream>\n", "file_path": "utils/rapidjson/reader.h", "rank": 43, "score": 190128.5308460722 }, { "content": "/// @brief Provides input layout for a data to be passed later to network.\n\n/// @details This primitive allows to define the layout for input data\n\n/// which will be passed to network before execution.\n\n/// For example, network input images.\n\n/// @note User should call network::set_input_data() for every @p input_layout primitive before network execution.\n\n/// @note @p output_padding property of @p input_layout is ignored - its output layout is always equal to input layout defined during object creation.\n\n/// @sa network::set_input_data(), cldnn::data\n\nstruct input_layout : public primitive_base<input_layout, CLDNN_PRIMITIVE_DESC(input_layout)>\n\n{\n\n CLDNN_DECLARE_PRIMITIVE(input_layout)\n\n\n\n /// @brief Constructs input layout primitive.\n\n /// @param id This primitive id.\n\n /// @param layout Defines layout for the data will be passed to network.\n\n input_layout(const primitive_id& id, const layout& layout)\n\n :primitive_base(id, {}, layout.data_padding)\n\n , layout(layout)\n\n {}\n\n\n\n /// @brief Constructs a copy from C API @CLDNN_PRIMITIVE_DESC{input_layout}\n\n explicit input_layout(const dto* dto)\n\n :primitive_base(dto)\n\n , layout(dto->layout)\n\n {\n\n output_padding = layout.data_padding;\n\n }\n\n\n", "file_path": "api/CPP/input_layout.hpp", "rank": 44, "score": 189545.7265835455 }, { "content": " void setup_basic(bool runOnGPU)\n\n {\n\n const bool share_location = true;\n\n const int num_loc_classes = share_location ? 1 : this->num_classes;\n\n const int keep_top_k = 150;\n\n\n\n const auto& engine = get_test_engine();\n\n cldnn::memory input_location = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ this->num_of_images, this->num_priors * num_loc_classes * 4, 1, 1 } });\n\n cldnn::memory input_confidence = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ this->num_of_images, this->num_priors * this->num_classes, 1, 1 } });\n\n cldnn::memory input_prior_box = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ 1, 2, 1, this->num_priors * 4 } });\n\n\n\n topology topology;\n\n topology.add(input_layout(\"input_location\", input_location.get_layout()));\n\n topology.add(input_layout(\"input_confidence\", input_confidence.get_layout()));\n\n topology.add(input_layout(\"input_prior_box\", input_prior_box.get_layout()));\n\n\n\n topology.add(detection_output(\"detection_output\", \"input_location\", \"input_confidence\", \"input_prior_box\", this->num_classes, keep_top_k));\n\n\n\n build_options opts;\n\n if (runOnGPU)\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 45, "score": 187353.26926650543 }, { "content": " void setup_two_layers(bool runOnGPU)\n\n {\n\n const bool share_location = true;\n\n const int num_loc_classes = share_location ? 1 : this->num_classes;\n\n const int keep_top_k = 150;\n\n\n\n const auto& engine = get_test_engine();\n\n cldnn::memory input_location = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ this->num_of_images, this->num_priors * num_loc_classes * 4, 1, 1 } });\n\n cldnn::memory input_confidence = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ this->num_of_images, this->num_priors * this->num_classes, 1, 1 } });\n\n cldnn::memory input_prior_box = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ 1, 2, 1, this->num_priors * 4 } });\n\n\n\n topology topology;\n\n topology.add(input_layout(\"input_location\", input_location.get_layout()));\n\n topology.add(input_layout(\"input_confidence\", input_confidence.get_layout()));\n\n topology.add(input_layout(\"input_prior_box\", input_prior_box.get_layout()));\n\n\n\n topology.add(detection_output(\"detection_output_1\", \"input_location\", \"input_confidence\", \"input_prior_box\", this->num_classes, keep_top_k));\n\n topology.add(detection_output(\"detection_output_2\", \"input_location\", \"input_confidence\", \"input_prior_box\", this->num_classes, keep_top_k));\n\n\n\n build_options opts;\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 46, "score": 187353.26811543058 }, { "content": "#include \"api/CPP/detection_output.hpp\"\n\n#include <api/CPP/topology.hpp>\n\n#include <api/CPP/network.hpp>\n\n#include <api/CPP/engine.hpp>\n\n#include \"test_utils/test_utils.h\"\n\n\n\nnamespace cldnn\n\n{\n\n template<> struct type_to_data_type<FLOAT16> { static const data_types value = data_types::f16; };\n\n}\n\n\n\nusing namespace cldnn;\n\nusing namespace tests;\n\n\n\ntemplate <typename T>\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 47, "score": 187352.82291765534 }, { "content": " check_results(output_prim, 18, \"-1 0 0 0 0 0 0\");\n\n check_results(output_prim, 19, \"-1 0 0 0 0 0 0\");\n\n }\n\n\n\n void forward_no_share_location_top_k(bool runOnGPU)\n\n {\n\n const bool share_location = false;\n\n const int num_loc_classes = share_location ? 1 : this->num_classes;\n\n const int keep_top_k = 4;\n\n const int background_label_id = -1;\n\n const int top_k = 2;\n\n\n\n const auto& engine = get_test_engine();\n\n cldnn::memory input_location = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ this->num_of_images, this->num_priors * num_loc_classes * 4, 1, 1 } });\n\n cldnn::memory input_confidence = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ this->num_of_images, this->num_priors * this->num_classes, 1, 1 } });\n\n cldnn::memory input_prior_box = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ 1, 2, 1, this->num_priors * 4 } });\n\n\n\n this->init_buffers(input_prior_box, input_confidence, input_location, share_location);\n\n\n\n topology topology;\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 48, "score": 187351.06755053403 }, { "content": " check_results(output_prim, 7, \"-1 0 0 0 0 0 0\");\n\n check_results(output_prim, 8, \"-1 0 0 0 0 0 0\");\n\n check_results(output_prim, 9, \"-1 0 0 0 0 0 0\");\n\n check_results(output_prim, 10, \"-1 0 0 0 0 0 0\");\n\n check_results(output_prim, 11, \"-1 0 0 0 0 0 0\");\n\n }\n\n\n\n void test_forward_share_location_top_k(bool runOnGPU)\n\n {\n\n const bool share_location = true;\n\n const int num_loc_classes = share_location ? 1 : this->num_classes;\n\n const int keep_top_k = 2;\n\n const int top_k = 2;\n\n const int background_label_id = 0;\n\n\n\n const auto& engine = get_test_engine();\n\n cldnn::memory input_location = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ this->num_of_images, this->num_priors * num_loc_classes * 4, 1, 1 } });\n\n cldnn::memory input_confidence = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ this->num_of_images, this->num_priors * this->num_classes, 1, 1 } });\n\n cldnn::memory input_prior_box = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ 1, 2, 1, this->num_priors * 4 } });\n\n\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 49, "score": 187350.3633070893 }, { "content": "\n\n void forward_num_detections_greater_than_keep_top_k(bool runOnGPU)\n\n {\n\n const bool share_location = true;\n\n const int num_loc_classes = share_location ? 1 : this->num_classes;\n\n const int keep_top_k = 1;\n\n const int background_label_id = 0;\n\n\n\n const auto& engine = get_test_engine();\n\n cldnn::memory input_location = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ this->num_of_images, this->num_priors * num_loc_classes * 4, 1, 1 } });\n\n cldnn::memory input_confidence = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ this->num_of_images, this->num_priors * this->num_classes, 1, 1 } });\n\n cldnn::memory input_prior_box = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ 1, 2, 1, this->num_priors * 4 } });\n\n\n\n this->init_buffers(input_prior_box, input_confidence, input_location, share_location);\n\n\n\n topology topology;\n\n topology.add(input_layout(\"input_location\", input_location.get_layout()));\n\n topology.add(input_layout(\"input_confidence\", input_confidence.get_layout()));\n\n topology.add(input_layout(\"input_prior_box\", input_prior_box.get_layout()));\n\n\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 50, "score": 187349.65999545826 }, { "content": "}\n\n\n\nTYPED_TEST(detection_output_test, test_detection_output_sort_gpu)\n\n{\n\n const bool share_location = false;\n\n const int num_loc_classes = share_location ? 1 : this->num_classes;\n\n const int keep_top_k = 10;\n\n const int background_label_id = -1;\n\n const int top_k = -1;\n\n\n\n const unsigned out_row_size = 7;\n\n const unsigned score_space = ((this->num_of_images + 15) / 16) * 16;\n\n int input_size = this->num_of_images * num_loc_classes * this->num_priors * out_row_size + score_space;\n\n\n\n const auto& engine = get_test_engine();\n\n cldnn::memory input_buff = memory::allocate(engine, { type_to_data_type<TypeParam>::value, format::bfyx,{ 1, 1, 1, input_size } });\n\n\n\n this->init_buffer_sort(input_buff);\n\n\n\n topology topology;\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 51, "score": 187349.54989461543 }, { "content": " check_results(output_prim, 0, \"0 1 1.0 0.20 0.20 0.50 0.50\");\n\n check_results(output_prim, 1, \"0 1 0.8 0.50 0.20 0.80 0.50\");\n\n check_results(output_prim, 2, \"1 1 0.6 0.40 0.40 0.70 0.70\");\n\n check_results(output_prim, 3, \"-1 0 0 0 0 0 0\");\n\n }\n\n\n\n void forward_no_share_location_top_k_input_padding(bool runOnGPU)\n\n {\n\n const bool share_location = false;\n\n const int num_loc_classes = share_location ? 1 : this->num_classes;\n\n const int keep_top_k = 4;\n\n const int background_label_id = -1;\n\n const int top_k = 2;\n\n\n\n const auto& engine = get_test_engine();\n\n cldnn::memory input_location = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ this->num_of_images, this->num_priors * num_loc_classes * 4, 1, 1 } });\n\n cldnn::memory input_confidence = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ this->num_of_images, this->num_priors * this->num_classes, 1, 1 } });\n\n cldnn::memory input_prior_box = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ 1, 2, 1, this->num_priors * 4 } });\n\n\n\n this->init_buffers(input_prior_box, input_confidence, input_location, share_location);\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 52, "score": 187346.78014976 }, { "content": " EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.spatial[1], keep_top_k * this->num_of_images);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.spatial[0], 7);\n\n\n\n auto output_prim = outputs.begin()->second.get_memory();\n\n\n\n check_results(output_prim, 0, \"0 1 1.0 0.15 0.15 0.45 0.45\");\n\n check_results(output_prim, 1, \"1 1 0.6 0.45 0.45 0.75 0.75\");\n\n }\n\n\n\n void forward_num_detections_smaller_than_keep_top_k(bool runOnGPU)\n\n {\n\n const bool share_location = true;\n\n const int num_loc_classes = share_location ? 1 : this->num_classes;\n\n const int keep_top_k = 6;\n\n const int background_label_id = 0;\n\n\n\n const auto& engine = get_test_engine();\n\n cldnn::memory input_location = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ this->num_of_images, this->num_priors * num_loc_classes * 4, 1, 1 } });\n\n cldnn::memory input_confidence = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ this->num_of_images, this->num_priors * this->num_classes, 1, 1 } });\n\n cldnn::memory input_prior_box = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ 1, 2, 1, this->num_priors * 4 } });\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 53, "score": 187346.68217483236 }, { "content": " }\n\n\n\n void test_forward_no_share_location_top_k_faster_rcnn_case(bool runOnGPU)\n\n {\n\n const bool share_location = false;\n\n const int num_loc_classes = share_location ? 1 : this->num_classes;\n\n const int keep_top_k = 4;\n\n const int background_label_id = -1;\n\n const int top_k = 2;\n\n const float eta = 1.0f;\n\n const prior_box_code_type code_type = prior_box_code_type::corner;\n\n const bool variance_encoded_in_target = true;\n\n const float confidence_threshold = -std::numeric_limits<float>::max();\n\n const int32_t prior_info_size = 5;\n\n const int32_t prior_coordinates_offset = 1;\n\n const bool prior_is_normalized = true;\n\n\n\n const auto& engine = get_test_engine();\n\n cldnn::memory input_location = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ this->num_of_images, this->num_priors * num_loc_classes * 4, 1, 1 } });\n\n cldnn::memory input_confidence = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ this->num_of_images, this->num_priors * this->num_classes, 1, 1 } });\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 54, "score": 187346.06435110353 }, { "content": " {\n\n const bool share_location = false;\n\n const int num_loc_classes = share_location ? 1 : this->num_classes;\n\n const int keep_top_k = 5;\n\n const int background_label_id = 0;\n\n\n\n const auto& engine = get_test_engine();\n\n cldnn::memory input_location = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ this->num_of_images, this->num_priors * num_loc_classes * 4, 1, 1 } });\n\n cldnn::memory input_confidence = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ this->num_of_images, this->num_priors * this->num_classes, 1, 1 } });\n\n cldnn::memory input_prior_box = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ 1, 2, 1, this->num_priors * 4 } });\n\n\n\n this->init_buffers(input_prior_box, input_confidence, input_location, share_location);\n\n\n\n topology topology;\n\n topology.add(input_layout(\"input_location\", input_location.get_layout()));\n\n topology.add(input_layout(\"input_confidence\", input_confidence.get_layout()));\n\n topology.add(input_layout(\"input_prior_box\", input_prior_box.get_layout()));\n\n\n\n topology.add(detection_output(\"detection_output\", \"input_location\", \"input_confidence\", \"input_prior_box\", this->num_classes, keep_top_k, share_location, background_label_id, this->nms_threshold));\n\n\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 55, "score": 187345.55288045362 }, { "content": " const bool share_location = false;\n\n const int num_loc_classes = share_location ? 1 : this->num_classes;\n\n const int keep_top_k = 10;\n\n const int background_label_id = -1;\n\n\n\n const auto& engine = get_test_engine();\n\n cldnn::memory input_location = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ this->num_of_images, this->num_priors * num_loc_classes * 4, 1, 1 } });\n\n cldnn::memory input_confidence = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ this->num_of_images, this->num_priors * this->num_classes, 1, 1 } });\n\n cldnn::memory input_prior_box = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ 1, 2, 1, this->num_priors * 4 } });\n\n\n\n this->init_buffers(input_prior_box, input_confidence, input_location, share_location);\n\n\n\n topology topology;\n\n topology.add(input_layout(\"input_location\", input_location.get_layout()));\n\n topology.add(input_layout(\"input_confidence\", input_confidence.get_layout()));\n\n topology.add(input_layout(\"input_prior_box\", input_prior_box.get_layout()));\n\n\n\n topology.add(detection_output(\"detection_output\", \"input_location\", \"input_confidence\", \"input_prior_box\", this->num_classes, keep_top_k, share_location, background_label_id, this->nms_threshold));\n\n\n\n build_options opts;\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 56, "score": 187345.233195191 }, { "content": " const int background_label_id = 0;\n\n const int top_k = 2;\n\n\n\n const auto& engine = get_test_engine();\n\n cldnn::memory input_location = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ this->num_of_images, this->num_priors * num_loc_classes * 4, 1, 1 } });\n\n cldnn::memory input_confidence = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ this->num_of_images, this->num_priors * this->num_classes, 1, 1 } });\n\n cldnn::memory input_prior_box = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ 1, 2, 1, this->num_priors * 4 } });\n\n\n\n this->init_buffers(input_prior_box, input_confidence, input_location, share_location);\n\n\n\n topology topology;\n\n topology.add(input_layout(\"input_location\", input_location.get_layout()));\n\n topology.add(input_layout(\"input_confidence\", input_confidence.get_layout()));\n\n topology.add(input_layout(\"input_prior_box\", input_prior_box.get_layout()));\n\n\n\n topology.add(detection_output(\"detection_output\", \"input_location\", \"input_confidence\", \"input_prior_box\", this->num_classes, keep_top_k, share_location, background_label_id, this->nms_threshold, top_k));\n\n\n\n build_options opts;\n\n if (runOnGPU)\n\n {\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 57, "score": 187342.3526816523 }, { "content": " if (runOnGPU)\n\n {\n\n opts.set_option(build_option::detection_output_gpu(true));\n\n }\n\n\n\n network network(engine, topology, opts);\n\n network.set_input_data(\"input_location\", input_location);\n\n network.set_input_data(\"input_confidence\", input_confidence);\n\n network.set_input_data(\"input_prior_box\", input_prior_box);\n\n\n\n auto outputs = network.execute();\n\n\n\n EXPECT_EQ(outputs.size(), size_t(2));\n\n unsigned i = 1;\n\n for (auto it = outputs.begin(); it != outputs.begin(); it++)\n\n {\n\n\n\n EXPECT_EQ(it->first, \"detection_output_\" + std::to_string(i));\n\n\n\n EXPECT_EQ(it->second.get_memory().get_layout().size.batch[0], 1);\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 58, "score": 187341.7543403945 }, { "content": " EXPECT_EQ(it->second.get_memory().get_layout().size.feature[0], 1);\n\n EXPECT_EQ(it->second.get_memory().get_layout().size.spatial[1], keep_top_k * this->num_of_images);\n\n EXPECT_EQ(it->second.get_memory().get_layout().size.spatial[0], 7);\n\n i++;\n\n }\n\n }\n\n\n\n void forward_share_location(bool runOnGPU)\n\n {\n\n const bool share_location = true;\n\n const int num_loc_classes = share_location ? 1 : this->num_classes;\n\n const int keep_top_k = 4;\n\n const int background_label_id = 0;\n\n\n\n const auto& engine = get_test_engine();\n\n cldnn::memory input_location = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ this->num_of_images, this->num_priors * num_loc_classes * 4, 1, 1 } });\n\n cldnn::memory input_confidence = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ this->num_of_images, this->num_priors * this->num_classes, 1, 1 } });\n\n cldnn::memory input_prior_box = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ 1, 2, 1, this->num_priors * 4 } });\n\n\n\n this->init_buffers(input_prior_box, input_confidence, input_location, share_location);\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 59, "score": 187341.29766383785 }, { "content": "\n\n topology topology;\n\n topology.add(input_layout(\"input_location\", input_location.get_layout()));\n\n topology.add(input_layout(\"input_confidence\", input_confidence.get_layout()));\n\n topology.add(input_layout(\"input_prior_box\", input_prior_box.get_layout()));\n\n\n\n topology.add(detection_output(\"detection_output\", \"input_location\", \"input_confidence\", \"input_prior_box\", this->num_classes, keep_top_k, share_location, background_label_id, this->nms_threshold));\n\n\n\n build_options opts;\n\n if (runOnGPU)\n\n {\n\n opts.set_option(build_option::detection_output_gpu(true));\n\n }\n\n\n\n network network(engine, topology, opts);\n\n network.set_input_data(\"input_location\", input_location);\n\n network.set_input_data(\"input_confidence\", input_confidence);\n\n network.set_input_data(\"input_prior_box\", input_prior_box);\n\n\n\n auto outputs = network.execute();\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 60, "score": 187340.7899091271 }, { "content": " topology.add(input_layout(\"input_location\", input_location.get_layout()));\n\n topology.add(input_layout(\"input_confidence\", input_confidence.get_layout()));\n\n topology.add(input_layout(\"input_prior_box\", input_prior_box.get_layout()));\n\n\n\n topology.add(detection_output(\"detection_output\", \"input_location\", \"input_confidence\", \"input_prior_box\", this->num_classes, keep_top_k, share_location, background_label_id, this->nms_threshold, top_k));\n\n\n\n build_options opts;\n\n if (runOnGPU)\n\n {\n\n opts.set_option(build_option::detection_output_gpu(true));\n\n }\n\n\n\n network network(engine, topology, opts);\n\n network.set_input_data(\"input_location\", input_location);\n\n network.set_input_data(\"input_confidence\", input_confidence);\n\n network.set_input_data(\"input_prior_box\", input_prior_box);\n\n\n\n auto outputs = network.execute();\n\n\n\n EXPECT_EQ(outputs.size(), size_t(1));\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 61, "score": 187340.26667660676 }, { "content": " topology.add(detection_output(\"detection_output\", \"input_location\", \"input_confidence\", \"input_prior_box\", this->num_classes, keep_top_k, share_location, background_label_id, this->nms_threshold));\n\n\n\n build_options opts;\n\n if (runOnGPU)\n\n {\n\n opts.set_option(build_option::detection_output_gpu(true));\n\n }\n\n\n\n network network(engine, topology, opts);\n\n network.set_input_data(\"input_location\", input_location);\n\n network.set_input_data(\"input_confidence\", input_confidence);\n\n network.set_input_data(\"input_prior_box\", input_prior_box);\n\n\n\n auto outputs = network.execute();\n\n\n\n EXPECT_EQ(outputs.size(), size_t(1));\n\n EXPECT_EQ(outputs.begin()->first, \"detection_output\");\n\n\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.batch[0], 1);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.feature[0], 1);\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 62, "score": 187338.71561752298 }, { "content": " {\n\n opts.set_option(build_option::detection_output_gpu(true));\n\n }\n\n\n\n network network(engine, topology, opts);\n\n network.set_input_data(\"input_location\", input_location);\n\n network.set_input_data(\"input_confidence\", input_confidence);\n\n network.set_input_data(\"input_prior_box\", input_prior_box);\n\n\n\n auto outputs = network.execute();\n\n\n\n EXPECT_EQ(outputs.size(), size_t(1));\n\n EXPECT_EQ(outputs.begin()->first, \"detection_output\");\n\n\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.batch[0], 1);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.feature[0], 1);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.spatial[1], keep_top_k * this->num_of_images);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.spatial[0], 7);\n\n\n\n auto output_prim = outputs.begin()->second.get_memory();\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 63, "score": 187337.76605469742 }, { "content": " opts.set_option(build_option::detection_output_gpu(true));\n\n }\n\n\n\n network network(engine, topology, opts);\n\n network.set_input_data(\"input_location\", input_location);\n\n network.set_input_data(\"input_confidence\", input_confidence);\n\n network.set_input_data(\"input_prior_box\", input_prior_box);\n\n\n\n auto outputs = network.execute();\n\n\n\n EXPECT_EQ(outputs.size(), size_t(1));\n\n EXPECT_EQ(outputs.begin()->first, \"detection_output\");\n\n\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.batch[0], 1);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.feature[0], 1);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.spatial[1], keep_top_k * this->num_of_images);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.spatial[0], 7);\n\n\n\n auto output_prim = outputs.begin()->second.get_memory();\n\n\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 64, "score": 187337.76605469742 }, { "content": " {\n\n opts.set_option(build_option::detection_output_gpu(true));\n\n }\n\n\n\n network network(engine, topology, opts);\n\n network.set_input_data(\"input_location\", input_location);\n\n network.set_input_data(\"input_confidence\", input_confidence);\n\n network.set_input_data(\"input_prior_box\", input_prior_box);\n\n\n\n auto outputs = network.execute();\n\n\n\n EXPECT_EQ(outputs.size(), size_t(1));\n\n EXPECT_EQ(outputs.begin()->first, \"detection_output\");\n\n\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.batch[0], 1);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.feature[0], 1);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.spatial[1], keep_top_k * this->num_of_images);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.spatial[0], 7);\n\n }\n\n\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 65, "score": 187336.80941159098 }, { "content": " if (runOnGPU)\n\n {\n\n opts.set_option(build_option::detection_output_gpu(true));\n\n }\n\n\n\n network network(engine, topology, opts);\n\n network.set_input_data(\"input_location\", input_location);\n\n network.set_input_data(\"input_confidence\", input_confidence);\n\n network.set_input_data(\"input_prior_box\", input_prior_box);\n\n\n\n auto outputs = network.execute();\n\n\n\n EXPECT_EQ(outputs.size(), size_t(1));\n\n EXPECT_EQ(outputs.begin()->first, \"detection_output\");\n\n\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.batch[0], 1);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.feature[0], 1);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.spatial[1], keep_top_k * this->num_of_images);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.spatial[0], 7);\n\n\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 66, "score": 187336.59217936656 }, { "content": " build_options opts;\n\n if (runOnGPU)\n\n {\n\n opts.set_option(build_option::detection_output_gpu(true));\n\n }\n\n\n\n network network(engine, topology, opts);\n\n network.set_input_data(\"input_location\", input_location);\n\n network.set_input_data(\"input_confidence\", input_confidence);\n\n network.set_input_data(\"input_prior_box\", input_prior_box);\n\n\n\n auto outputs = network.execute();\n\n\n\n EXPECT_EQ(outputs.size(), size_t(1));\n\n EXPECT_EQ(outputs.begin()->first, \"detection_output\");\n\n\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.batch[0], 1);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.feature[0], 1);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.spatial[1], keep_top_k * this->num_of_images);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.spatial[0], 7);\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 67, "score": 187336.2719753974 }, { "content": "\n\n this->init_buffers(input_prior_box, input_confidence, input_location, share_location);\n\n\n\n topology topology;\n\n topology.add(input_layout(\"input_location\", input_location.get_layout()));\n\n topology.add(input_layout(\"input_confidence\", input_confidence.get_layout()));\n\n topology.add(input_layout(\"input_prior_box\", input_prior_box.get_layout()));\n\n\n\n topology.add(detection_output(\"detection_output\", \"input_location\", \"input_confidence\", \"input_prior_box\", this->num_classes, keep_top_k, share_location, background_label_id, this->nms_threshold));\n\n\n\n build_options opts;\n\n if (runOnGPU)\n\n {\n\n opts.set_option(build_option::detection_output_gpu(true));\n\n }\n\n\n\n network network(engine, topology, opts);\n\n network.set_input_data(\"input_location\", input_location);\n\n network.set_input_data(\"input_confidence\", input_confidence);\n\n network.set_input_data(\"input_prior_box\", input_prior_box);\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 68, "score": 187335.99688723104 }, { "content": " this->init_buffers(input_prior_box, input_confidence, input_location, share_location);\n\n\n\n topology topology;\n\n topology.add(input_layout(\"input_location\", input_location.get_layout()));\n\n topology.add(input_layout(\"input_confidence\", input_confidence.get_layout()));\n\n topology.add(input_layout(\"input_prior_box\", input_prior_box.get_layout()));\n\n\n\n topology.add(detection_output(\"detection_output\", \"input_location\", \"input_confidence\", \"input_prior_box\", this->num_classes, keep_top_k, share_location, background_label_id, this->nms_threshold, top_k));\n\n\n\n build_options opts;\n\n if (runOnGPU)\n\n {\n\n opts.set_option(build_option::detection_output_gpu(true));\n\n }\n\n\n\n network network(engine, topology, opts);\n\n network.set_input_data(\"input_location\", input_location);\n\n network.set_input_data(\"input_confidence\", input_confidence);\n\n network.set_input_data(\"input_prior_box\", input_prior_box);\n\n\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 69, "score": 187335.91760041687 }, { "content": " topology topology;\n\n topology.add(input_layout(\"input_location\", input_location.get_layout()));\n\n topology.add(input_layout(\"input_confidence\", input_confidence.get_layout()));\n\n topology.add(input_layout(\"input_prior_box\", input_prior_box.get_layout()));\n\n topology.add(reorder(\"input_location_padded\", \"input_location\", input_location.get_layout().with_padding({ { 0, 0, 12, 3 },{ 0, 0, 5, 11 } })));\n\n topology.add(reorder(\"input_confidence_padded\", \"input_confidence\", input_location.get_layout().with_padding({ { 0, 0, 2, 7 },{ 0, 0, 13, 1 } })));\n\n\n\n topology.add(detection_output(\"detection_output\", \"input_location_padded\", \"input_confidence_padded\", \"input_prior_box\", this->num_classes, keep_top_k, share_location, background_label_id, this->nms_threshold, top_k));\n\n\n\n build_options opts;\n\n if (runOnGPU)\n\n {\n\n opts.set_option(build_option::detection_output_gpu(true));\n\n }\n\n\n\n network network(engine, topology, opts);\n\n network.set_input_data(\"input_location\", input_location);\n\n network.set_input_data(\"input_confidence\", input_confidence);\n\n network.set_input_data(\"input_prior_box\", input_prior_box);\n\n\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 70, "score": 187335.15614238457 }, { "content": " topology.add(input_layout(\"input_location\", input_buff.get_layout()));\n\n\n\n topology.add(detection_output_sort(\"detection_output_sort\", \"input_location\", this->num_of_images, this->num_classes, keep_top_k, share_location, top_k, background_label_id));\n\n network network(engine, topology);\n\n network.set_input_data(\"input_location\", input_buff);\n\n\n\n auto outputs = network.execute();\n\n\n\n EXPECT_EQ(outputs.size(), size_t(1));\n\n EXPECT_EQ(outputs.begin()->first, \"detection_output_sort\");\n\n\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.batch[0], 1);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.feature[0], 1);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.spatial[1], keep_top_k * this->num_of_images);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.spatial[0], 7);\n\n\n\n auto output_prim = outputs.begin()->second.get_memory();\n\n\n\n this->check_results(output_prim, 0, \"0 0 0.6 0.55 0.55 0.85 0.85\");\n\n this->check_results(output_prim, 1, \"0 0 0.4 0.15 0.55 0.45 0.85\");\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 71, "score": 187334.50115393847 }, { "content": "}\n\n\n\nTYPED_TEST(detection_output_test, test_forward_no_share_location_top_k_input_padding)\n\n{\n\n this->forward_no_share_location_top_k_input_padding(false);\n\n}\n\n\n\nTYPED_TEST(detection_output_test, test_forward_no_share_location_top_k_input_padding_gpu)\n\n{\n\n this->forward_no_share_location_top_k_input_padding(true);\n\n}\n\n\n\nTYPED_TEST(detection_output_test, test_forward_no_share_location_top_k_faster_rcnn_case)\n\n{\n\n this->test_forward_no_share_location_top_k_faster_rcnn_case(false);\n\n}\n\n\n\nTYPED_TEST(detection_output_test, test_forward_no_share_location_top_k_faster_rcnn_case_gpu)\n\n{\n\n this->test_forward_no_share_location_top_k_faster_rcnn_case(true);\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 72, "score": 187333.3859399919 }, { "content": " location_data[idx++] = (w % 2 ? -1 : 1) * (i * 1 + c / 2.f + 0.5f) * loc_multiplier;\n\n location_data[idx++] = (h % 2 ? -1 : 1) * (i * 1 + c / 2.f + 0.5f) * loc_multiplier;\n\n location_data[idx++] = (w % 2 ? -1 : 1) * (i * 1 + c / 2.f + 0.5f) * loc_multiplier;\n\n location_data[idx++] = (h % 2 ? -1 : 1) * (i * 1 + c / 2.f + 0.5f) * loc_multiplier;\n\n }\n\n }\n\n }\n\n }\n\n }\n\n\n\n void init_buffer_sort(cldnn::memory input_buff)\n\n {\n\n auto input_data_ptr = input_buff.pointer<T>();\n\n\n\n EXPECT_EQ((int)input_buff.count(), 128);\n\n\n\n T* input_data = input_data_ptr.data();\n\n input_data[0] = 8;\n\n input_data[1] = 3;\n\n input_data[16] = 0; input_data[17] = 0; input_data[18] = 0.6f; input_data[19] = 0.55f; input_data[20] = 0.55f; input_data[21] = 0.85f; input_data[22] = 0.85f;\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 73, "score": 187326.06964041342 }, { "content": " cldnn::memory input_prior_box = memory::allocate(engine, { type_to_data_type<T>::value, format::bfyx,{ 1, 1, 1, this->num_priors * prior_info_size } });\n\n\n\n this->init_buffers(input_prior_box, input_confidence, input_location, share_location, variance_encoded_in_target,\n\n prior_info_size, prior_coordinates_offset, prior_is_normalized);\n\n\n\n topology topology;\n\n topology.add(input_layout(\"input_location\", input_location.get_layout()));\n\n topology.add(input_layout(\"input_confidence\", input_confidence.get_layout()));\n\n topology.add(input_layout(\"input_prior_box\", input_prior_box.get_layout()));\n\n topology.add(reorder(\"input_location_padded\", \"input_location\", input_location.get_layout().with_padding({ { 0, 0, 12, 3 },{ 0, 0, 5, 11 } })));\n\n topology.add(reorder(\"input_confidence_padded\", \"input_confidence\", input_location.get_layout().with_padding({ { 0, 0, 2, 7 },{ 0, 0, 13, 1 } })));\n\n\n\n topology.add(detection_output(\"detection_output\", \"input_location_padded\", \"input_confidence_padded\", \"input_prior_box\",\n\n this->num_classes, keep_top_k, share_location, background_label_id, this->nms_threshold, top_k,\n\n eta, code_type, variance_encoded_in_target, confidence_threshold, prior_info_size, prior_coordinates_offset,\n\n prior_is_normalized, this->img_size, this->img_size\n\n ));\n\n\n\n build_options opts;\n\n if (runOnGPU)\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 74, "score": 187325.85187678703 }, { "content": "\n\n auto output_prim = outputs.begin()->second.get_memory();\n\n\n\n check_results(output_prim, 0, \"0 1 1.0 0.20 0.20 0.50 0.50\");\n\n check_results(output_prim, 1, \"0 1 0.8 0.50 0.20 0.80 0.50\");\n\n check_results(output_prim, 2, \"0 1 0.6 0.20 0.50 0.50 0.80\");\n\n check_results(output_prim, 3, \"0 1 0.4 0.50 0.50 0.80 0.80\");\n\n check_results(output_prim, 4, \"1 1 0.6 0.40 0.40 0.70 0.70\");\n\n check_results(output_prim, 5, \"-1 0 0 0 0 0 0\");\n\n check_results(output_prim, 6, \"-1 0 0 0 0 0 0\");\n\n check_results(output_prim, 7, \"-1 0 0 0 0 0 0\");\n\n check_results(output_prim, 8, \"-1 0 0 0 0 0 0\");\n\n check_results(output_prim, 9, \"-1 0 0 0 0 0 0\");\n\n }\n\n\n\n void forward_no_share_location_neg_0_top_k(bool runOnGPU)\n\n {\n\n const bool share_location = false;\n\n const int num_loc_classes = share_location ? 1 : this->num_classes;\n\n const int keep_top_k = 2;\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 75, "score": 187320.0299823887 }, { "content": "\n\n check_results(output_prim, 0, \"0 0 0.6 0.55 0.55 0.85 0.85\");\n\n check_results(output_prim, 1, \"0 0 0.4 0.15 0.55 0.45 0.85\");\n\n check_results(output_prim, 2, \"0 1 1.0 0.20 0.20 0.50 0.50\");\n\n check_results(output_prim, 3, \"0 1 0.8 0.50 0.20 0.80 0.50\");\n\n check_results(output_prim, 4, \"1 0 1.0 0.25 0.25 0.55 0.55\");\n\n check_results(output_prim, 5, \"1 1 0.6 0.40 0.40 0.70 0.70\");\n\n check_results(output_prim, 6, \"-1 0 0 0 0 0 0\");\n\n check_results(output_prim, 7, \"-1 0 0 0 0 0 0\");\n\n }\n\n\n\n static const int num_of_images = 2;\n\n static const int num_classes = 2;\n\n static const int num_priors = 4;\n\n static const int img_size = 300;\n\n const float nms_threshold;\n\n};\n\n\n\ntypedef ::testing::Types<float, FLOAT16> detection_output_test_types;\n\nTYPED_TEST_CASE(detection_output_test, detection_output_test_types);\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 76, "score": 187318.9451873657 }, { "content": " input_data[23] = 0; input_data[24] = 0; input_data[25] = 0.4f; input_data[26] = 0.15f; input_data[27] = 0.55f; input_data[28] = 0.45f; input_data[29] = 0.85f;\n\n input_data[30] = 0; input_data[31] = 0; input_data[32] = 0.2f; input_data[33] = 0.55f; input_data[34] = 0.15f; input_data[35] = 0.85f; input_data[36] = 0.45f;\n\n input_data[37] = 0; input_data[38] = 0; input_data[39] = 0.0f; input_data[40] = 0.15f; input_data[41] = 0.15f; input_data[42] = 0.45f; input_data[43] = 0.45f;\n\n input_data[44] = 0; input_data[45] = 1; input_data[46] = 1.0f; input_data[47] = 0.20f; input_data[48] = 0.20f; input_data[49] = 0.50f; input_data[50] = 0.50f;\n\n input_data[51] = 0; input_data[52] = 1; input_data[53] = 0.8f; input_data[54] = 0.50f; input_data[55] = 0.20f; input_data[56] = 0.80f; input_data[57] = 0.50f;\n\n input_data[58] = 0; input_data[59] = 1; input_data[60] = 0.6f; input_data[61] = 0.20f; input_data[62] = 0.50f; input_data[63] = 0.50f; input_data[64] = 0.80f;\n\n input_data[65] = 0; input_data[66] = 1; input_data[67] = 0.4f; input_data[68] = 0.50f; input_data[69] = 0.50f; input_data[70] = 0.80f; input_data[71] = 0.80f;\n\n input_data[72] = 1; input_data[73] = 0; input_data[74] = 1.0f; input_data[75] = 0.25f; input_data[76] = 0.25f; input_data[77] = 0.55f; input_data[78] = 0.55f;\n\n input_data[79] = 1; input_data[80] = 0; input_data[81] = 0.4f; input_data[82] = 0.45f; input_data[83] = 0.45f; input_data[84] = 0.75f; input_data[85] = 0.75f;\n\n input_data[86] = -1; input_data[87] = 0; input_data[88] = 0; input_data[89] = 0; input_data[90] = 0; input_data[91] = 0; input_data[92] = 0;\n\n input_data[93] = -1; input_data[94] = 0; input_data[95] = 0; input_data[96] = 0; input_data[97] = 0; input_data[98] = 0; input_data[99] = 0;\n\n input_data[100] = 1; input_data[101] = 1; input_data[102] = 0.6f; input_data[103] = 0.40f; input_data[104] = 0.40f; input_data[105] = 0.70f; input_data[106] = 0.70f;\n\n input_data[107] = -1; input_data[108] = 0; input_data[109] = 0; input_data[110] = 0; input_data[111] = 0; input_data[112] = 0; input_data[113] = 0;\n\n input_data[114] = -1; input_data[115] = 0; input_data[116] = 0; input_data[117] = 0; input_data[118] = 0; input_data[119] = 0; input_data[120] = 0;\n\n input_data[121] = -1; input_data[122] = 0; input_data[123] = 0; input_data[124] = 0; input_data[125] = 0; input_data[126] = 0; input_data[127] = 0;\n\n }\n\n\n\n void check_results(const memory& output, const int num, const std::string values)\n\n {\n\n assert(num < output.get_layout().size.spatial[1]);\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 77, "score": 187317.52332743368 }, { "content": " auto outputs = network.execute();\n\n\n\n EXPECT_EQ(outputs.size(), size_t(1));\n\n EXPECT_EQ(outputs.begin()->first, \"detection_output\");\n\n\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.batch[0], 1);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.feature[0], 1);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.spatial[1], keep_top_k * this->num_of_images);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.spatial[0], 7);\n\n\n\n auto output_prim = outputs.begin()->second.get_memory();\n\n\n\n check_results(output_prim, 0, \"0 1 1.0 0.15 0.15 0.45 0.45\");\n\n check_results(output_prim, 1, \"0 1 0.8 0.55 0.15 0.85 0.45\");\n\n check_results(output_prim, 2, \"1 1 0.6 0.45 0.45 0.75 0.75\");\n\n check_results(output_prim, 3, \"-1 0 0 0 0 0 0\");\n\n }\n\n\n\n void forward_no_share_location(bool runOnGPU)\n\n {\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 78, "score": 187316.51567365674 }, { "content": "\n\n\n\nTYPED_TEST(detection_output_test, test_setup_basic)\n\n{\n\n this->setup_basic(false);\n\n}\n\n\n\nTYPED_TEST(detection_output_test, test_setup_basic_gpu)\n\n{\n\n this->setup_basic(true);\n\n}\n\n\n\nTYPED_TEST(detection_output_test, test_setup_two_layers)\n\n{\n\n this->setup_two_layers(false);\n\n}\n\n\n\nTYPED_TEST(detection_output_test, test_setup_two_layers_gpu)\n\n{\n\n this->setup_two_layers(true);\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 79, "score": 187314.17856562938 }, { "content": "}\n\n\n\nTYPED_TEST(detection_output_test, test_forward_no_share_location)\n\n{\n\n this->forward_no_share_location(false);\n\n}\n\n\n\nTYPED_TEST(detection_output_test, test_forward_no_share_location_gpu)\n\n{\n\n this->forward_no_share_location(true);\n\n}\n\n\n\nTYPED_TEST(detection_output_test, test_forward_no_share_location_top_k)\n\n{\n\n this->forward_no_share_location_top_k(false);\n\n}\n\n\n\nTYPED_TEST(detection_output_test, test_forward_no_share_location_top_k_gpu)\n\n{\n\n this->forward_no_share_location_top_k(true);\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 80, "score": 187313.74770780443 }, { "content": "}\n\n\n\nTYPED_TEST(detection_output_test, test_forward_share_location)\n\n{\n\n this->forward_share_location(false);\n\n}\n\n\n\nTYPED_TEST(detection_output_test, test_forward_share_location_gpu)\n\n{\n\n this->forward_share_location(true);\n\n}\n\n\n\nTYPED_TEST(detection_output_test, test_forward_num_detections_greater_than_keep_top_k)\n\n{\n\n this->forward_num_detections_greater_than_keep_top_k(false);\n\n}\n\n\n\nTYPED_TEST(detection_output_test, test_forward_num_detections_greater_than_keep_top_k_gpu)\n\n{\n\n this->forward_num_detections_greater_than_keep_top_k(true);\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 81, "score": 187313.33754581225 }, { "content": "}\n\n\n\nTYPED_TEST(detection_output_test, test_forward_no_share_location_neg_0)\n\n{\n\n this->forward_no_share_location_neg_0(false);\n\n}\n\n\n\nTYPED_TEST(detection_output_test, test_forward_no_share_location_neg_0_gpu)\n\n{\n\n this->forward_no_share_location_neg_0(true);\n\n}\n\n\n\nTYPED_TEST(detection_output_test, test_forward_no_share_location_neg_0_top_k)\n\n{\n\n this->forward_no_share_location_neg_0_top_k(false);\n\n}\n\n\n\nTYPED_TEST(detection_output_test, test_forward_no_share_location_neg_0_top_k_gpu)\n\n{\n\n this->forward_no_share_location_neg_0_top_k(true);\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 82, "score": 187313.33754581225 }, { "content": "}\n\n\n\nTYPED_TEST(detection_output_test, test_forward_num_detections_smaller_than_keep_top_k)\n\n{\n\n this->forward_num_detections_smaller_than_keep_top_k(false);\n\n}\n\n\n\nTYPED_TEST(detection_output_test, test_forward_num_detections_smaller_than_keep_top_k_gpu)\n\n{\n\n this->forward_num_detections_smaller_than_keep_top_k(true);\n\n}\n\n\n\nTYPED_TEST(detection_output_test, test_forward_share_location_top_k)\n\n{\n\n this->test_forward_share_location_top_k(false);\n\n}\n\n\n\nTYPED_TEST(detection_output_test, test_forward_share_location_top_k_gpu)\n\n{\n\n this->test_forward_share_location_top_k(true);\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 83, "score": 187313.15473989796 }, { "content": "\n\n // Split values to vector of items.\n\n std::vector<std::string> items;\n\n std::istringstream iss(values);\n\n std::copy(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>(), back_inserter(items));\n\n EXPECT_EQ((int)items.size(), 7);\n\n\n\n // Check data.\n\n auto out_ptr = output.pointer<T>();\n\n const T* data = out_ptr.data();\n\n for (int i = 0; i < 2; ++i)\n\n {\n\n EXPECT_EQ(static_cast<int>((float)data[num * output.get_layout().size.spatial[0] + i]), atoi(items[i].c_str()));\n\n }\n\n for (int i = 2; i < 7; ++i) \n\n {\n\n EXPECT_TRUE(floating_point_equal(data[num * output.get_layout().size.spatial[0] + i], (T)(float)atof(items[i].c_str())));\n\n }\n\n }\n\n\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 84, "score": 187313.0788283028 }, { "content": "/*\n\n// Copyright (c) 2016 Intel Corporation\n\n//\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n\n// you may not use this file except in compliance with the License.\n\n// You may obtain a copy of the License at\n\n//\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n//\n\n// Unless required by applicable law or agreed to in writing, software\n\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n// See the License for the specific language governing permissions and\n\n// limitations under the License.\n\n*/\n\n\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n#include <gtest/gtest.h>\n\n#include \"api/CPP/memory.hpp\"\n\n#include <api/CPP/input_layout.hpp>\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 85, "score": 187311.57799153385 }, { "content": " EXPECT_EQ(outputs.begin()->first, \"detection_output\");\n\n\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.batch[0], 1);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.feature[0], 1);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.spatial[1], keep_top_k * this->num_of_images);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.spatial[0], 7);\n\n\n\n auto output_prim = outputs.begin()->second.get_memory();\n\n\n\n check_results(output_prim, 0, \"0 0 0.6 0.55 0.55 0.85 0.85\");\n\n check_results(output_prim, 1, \"0 0 0.4 0.15 0.55 0.45 0.85\");\n\n check_results(output_prim, 2, \"0 1 1.0 0.20 0.20 0.50 0.50\");\n\n check_results(output_prim, 3, \"0 1 0.8 0.50 0.20 0.80 0.50\");\n\n check_results(output_prim, 4, \"1 0 1.0 0.25 0.25 0.55 0.55\");\n\n check_results(output_prim, 5, \"1 1 0.6 0.40 0.40 0.70 0.70\");\n\n check_results(output_prim, 6, \"-1 0 0 0 0 0 0\");\n\n check_results(output_prim, 7, \"-1 0 0 0 0 0 0\");\n\n }\n\n\n\n void forward_no_share_location_neg_0(bool runOnGPU)\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 86, "score": 187310.77923544592 }, { "content": "\n\n auto outputs = network.execute();\n\n\n\n EXPECT_EQ(outputs.size(), size_t(1));\n\n EXPECT_EQ(outputs.begin()->first, \"detection_output\");\n\n\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.batch[0], 1);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.feature[0], 1);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.spatial[1], keep_top_k * this->num_of_images);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.spatial[0], 7);\n\n\n\n auto output_prim = outputs.begin()->second.get_memory();\n\n\n\n check_results(output_prim, 0, \"0 1 1.0 0.15 0.15 0.45 0.45\");\n\n check_results(output_prim, 1, \"0 1 0.8 0.55 0.15 0.85 0.45\");\n\n check_results(output_prim, 2, \"0 1 0.6 0.15 0.55 0.45 0.85\");\n\n check_results(output_prim, 3, \"0 1 0.4 0.55 0.55 0.85 0.85\");\n\n check_results(output_prim, 4, \"1 1 0.6 0.45 0.45 0.75 0.75\");\n\n check_results(output_prim, 5, \"1 1 0.0 0.25 0.25 0.55 0.55\");\n\n check_results(output_prim, 6, \"-1 0 0 0 0 0 0\");\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 87, "score": 187308.95118324793 }, { "content": " auto outputs = network.execute();\n\n\n\n EXPECT_EQ(outputs.size(), size_t(1));\n\n EXPECT_EQ(outputs.begin()->first, \"detection_output\");\n\n\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.batch[0], 1);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.feature[0], 1);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.spatial[1], keep_top_k * this->num_of_images);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.spatial[0], 7);\n\n\n\n auto output_prim = outputs.begin()->second.get_memory();\n\n\n\n check_results(output_prim, 0, \"0 0 0.6 0.55 0.55 0.85 0.85\");\n\n check_results(output_prim, 1, \"0 0 0.4 0.15 0.55 0.45 0.85\");\n\n check_results(output_prim, 2, \"0 1 1.0 0.20 0.20 0.50 0.50\");\n\n check_results(output_prim, 3, \"0 1 0.8 0.50 0.20 0.80 0.50\");\n\n check_results(output_prim, 4, \"1 0 1.0 0.25 0.25 0.55 0.55\");\n\n check_results(output_prim, 5, \"1 1 0.6 0.40 0.40 0.70 0.70\");\n\n check_results(output_prim, 6, \"-1 0 0 0 0 0 0\");\n\n check_results(output_prim, 7, \"-1 0 0 0 0 0 0\");\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 88, "score": 187308.82539086943 }, { "content": " auto output_prim = outputs.begin()->second.get_memory();\n\n\n\n check_results(output_prim, 0, \"0 0 0.6 0.55 0.55 0.85 0.85\");\n\n check_results(output_prim, 1, \"0 0 0.4 0.15 0.55 0.45 0.85\");\n\n check_results(output_prim, 2, \"0 0 0.2 0.55 0.15 0.85 0.45\");\n\n check_results(output_prim, 3, \"0 0 0.0 0.15 0.15 0.45 0.45\");\n\n check_results(output_prim, 4, \"0 1 1.0 0.20 0.20 0.50 0.50\");\n\n check_results(output_prim, 5, \"0 1 0.8 0.50 0.20 0.80 0.50\");\n\n check_results(output_prim, 6, \"0 1 0.6 0.20 0.50 0.50 0.80\");\n\n check_results(output_prim, 7, \"0 1 0.4 0.50 0.50 0.80 0.80\");\n\n check_results(output_prim, 8, \"1 0 1.0 0.25 0.25 0.55 0.55\");\n\n check_results(output_prim, 9, \"1 0 0.4 0.45 0.45 0.75 0.75\");\n\n check_results(output_prim, 10, \"1 1 0.6 0.40 0.40 0.70 0.70\");\n\n check_results(output_prim, 11, \"-1 0 0 0 0 0 0\");\n\n check_results(output_prim, 12, \"-1 0 0 0 0 0 0\");\n\n check_results(output_prim, 13, \"-1 0 0 0 0 0 0\");\n\n check_results(output_prim, 14, \"-1 0 0 0 0 0 0\");\n\n check_results(output_prim, 15, \"-1 0 0 0 0 0 0\");\n\n check_results(output_prim, 16, \"-1 0 0 0 0 0 0\");\n\n check_results(output_prim, 17, \"-1 0 0 0 0 0 0\");\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 89, "score": 187304.29600396162 }, { "content": "\n\n EXPECT_EQ(outputs.size(), size_t(1));\n\n EXPECT_EQ(outputs.begin()->first, \"detection_output\");\n\n\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.batch[0], 1);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.feature[0], 1);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.spatial[1], keep_top_k * this->num_of_images);\n\n EXPECT_EQ(outputs.begin()->second.get_memory().get_layout().size.spatial[0], 7);\n\n\n\n auto output_prim = outputs.begin()->second.get_memory();\n\n\n\n check_results(output_prim, 0, \"0 1 1.0 0.15 0.15 0.45 0.45\");\n\n check_results(output_prim, 1, \"0 1 0.8 0.55 0.15 0.85 0.45\");\n\n check_results(output_prim, 2, \"0 1 0.6 0.15 0.55 0.45 0.85\");\n\n check_results(output_prim, 3, \"0 1 0.4 0.55 0.55 0.85 0.85\");\n\n check_results(output_prim, 4, \"1 1 0.6 0.45 0.45 0.75 0.75\");\n\n check_results(output_prim, 5, \"1 1 0.0 0.25 0.25 0.55 0.55\");\n\n check_results(output_prim, 6, \"-1 0 0 0 0 0 0\");\n\n check_results(output_prim, 7, \"-1 0 0 0 0 0 0\");\n\n }\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 90, "score": 187303.69123230208 }, { "content": " this->check_results(output_prim, 2, \"0 0 0.2 0.55 0.15 0.85 0.45\");\n\n this->check_results(output_prim, 3, \"0 0 0.0 0.15 0.15 0.45 0.45\");\n\n this->check_results(output_prim, 4, \"0 1 1.0 0.20 0.20 0.50 0.50\");\n\n this->check_results(output_prim, 5, \"0 1 0.8 0.50 0.20 0.80 0.50\");\n\n this->check_results(output_prim, 6, \"0 1 0.6 0.20 0.50 0.50 0.80\");\n\n this->check_results(output_prim, 7, \"0 1 0.4 0.50 0.50 0.80 0.80\");\n\n this->check_results(output_prim, 8, \"1 0 1.0 0.25 0.25 0.55 0.55\");\n\n this->check_results(output_prim, 9, \"1 0 0.4 0.45 0.45 0.75 0.75\");\n\n this->check_results(output_prim, 10, \"1 1 0.6 0.40 0.40 0.70 0.70\");\n\n this->check_results(output_prim, 11, \"-1 0 0 0 0 0 0\");\n\n this->check_results(output_prim, 12, \"-1 0 0 0 0 0 0\");\n\n this->check_results(output_prim, 13, \"-1 0 0 0 0 0 0\");\n\n this->check_results(output_prim, 14, \"-1 0 0 0 0 0 0\");\n\n this->check_results(output_prim, 15, \"-1 0 0 0 0 0 0\");\n\n this->check_results(output_prim, 16, \"-1 0 0 0 0 0 0\");\n\n this->check_results(output_prim, 17, \"-1 0 0 0 0 0 0\");\n\n this->check_results(output_prim, 18, \"-1 0 0 0 0 0 0\");\n\n this->check_results(output_prim, 19, \"-1 0 0 0 0 0 0\");\n\n}\n\n\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 91, "score": 187300.27080754586 }, { "content": " else \n\n {\n\n confidence_data[idx++] = 1 - j * 0.2f;\n\n }\n\n }\n\n }\n\n }\n\n\n\n // Fill locations.\n\n const int num_loc_classes = share_location ? 1 : num_classes;\n\n const float loc_multiplier = variance_encoded_in_target ? variance : 1.0f;\n\n idx = 0;\n\n for (int i = 0; i < num_of_images; ++i) \n\n {\n\n for (int h = 0; h < 2; ++h) \n\n {\n\n for (int w = 0; w < 2; ++w) \n\n {\n\n for (int c = 0; c < num_loc_classes; ++c) \n\n {\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 92, "score": 187299.73744963968 }, { "content": " if (!variance_encoded_in_target)\n\n {\n\n for (int i = 0; i < idx; ++i)\n\n {\n\n prior_data[idx + i] = variance;\n\n }\n\n }\n\n\n\n // Fill confidences.\n\n idx = 0;\n\n for (int i = 0; i < num_of_images; ++i) \n\n {\n\n for (int j = 0; j < num_priors; ++j) \n\n {\n\n for (int c = 0; c < num_classes; ++c) \n\n {\n\n if (i % 2 == c % 2) \n\n {\n\n confidence_data[idx++] = j * 0.2f;\n\n }\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 93, "score": 187299.63151719095 }, { "content": " // Fill prior-box data.\n\n const float step = 0.5f;\n\n const float box_size = 0.3f;\n\n const float prior_multiplier = prior_is_normalized ? 1.0f : static_cast<float>(this->img_size);\n\n const float variance = 0.1f;\n\n int idx = 0;\n\n for (int h = 0; h < 2; ++h)\n\n {\n\n float center_y = (h + 0.5f) * step;\n\n for (int w = 0; w < 2; ++w) \n\n {\n\n float center_x = (w + 0.5f) * step;\n\n prior_data[idx+prior_coordinates_offset+0] = (center_x - box_size / 2) * prior_multiplier;\n\n prior_data[idx+prior_coordinates_offset+1] = (center_y - box_size / 2) * prior_multiplier;\n\n prior_data[idx+prior_coordinates_offset+2] = (center_x + box_size / 2) * prior_multiplier;\n\n prior_data[idx+prior_coordinates_offset+3] = (center_y + box_size / 2) * prior_multiplier;\n\n\n\n idx += prior_info_size;\n\n }\n\n }\n", "file_path": "tests/test_cases/detection_output_test.cpp", "rank": 94, "score": 187298.05512077807 }, { "content": "#include <api/CPP/input_layout.hpp>\n\n#include \"api/CPP/concatenation.hpp\"\n\n#include <api/CPP/topology.hpp>\n\n#include <api/CPP/network.hpp>\n\n#include <api/CPP/engine.hpp>\n\n#include <api/CPP/data.hpp>\n\n#include \"test_utils/test_utils.h\"\n\n\n\nusing namespace cldnn;\n\nusing namespace tests;\n\n\n\n/*\n\n This set of tests has been designed to check the correctness of trim_to_outputs optimization pass\n\n*/\n\n\n\n\n\n/*\n\n In this test we check if the convolution conv2 will be eliminated from the network. This is expected to be done in trim_to_outputs optimization pass\n\n\n\n Network structure: input -> conv1 (output)\n", "file_path": "tests/test_cases/trim_to_outputs_gpu_test.cpp", "rank": 95, "score": 182915.9936053841 }, { "content": " topology.add(input_layout(\"input\", input.get_layout()));\n\n topology.add(data(\"weights\", weights));\n\n topology.add(data(\"bias\", bias));\n\n topology.add(cldnn::convolution(\"conv1\", { \"input\" }, { \"weights\" }, { \"bias\" }));\n\n topology.add(cldnn::convolution(\"conv2\", { \"input\" }, { \"weights\" }, { \"bias\" }));\n\n\n\n network network(engine, topology, build_opt);\n\n network.set_input_data(\"input\", input);\n\n auto outputs = network.execute();\n\n\n\n EXPECT_EQ(outputs.size(), (size_t)1); // there is only one output\n\n EXPECT_EQ(network.get_executed_primitives().size(), (size_t)2); // input and conv1 where executed\n\n EXPECT_EQ(network.get_all_primitive_ids().size(), (size_t)4); // also bias and weights still exist\n\n\n\n for (auto& it : outputs)\n\n {\n\n auto output_ptr = it.second.get_memory().pointer<float>();\n\n for (size_t cntr = 0; cntr < out_data.size(); cntr++)\n\n {\n\n EXPECT_NEAR(output_ptr[cntr], out_data[cntr], 1e-4);\n", "file_path": "tests/test_cases/trim_to_outputs_gpu_test.cpp", "rank": 96, "score": 182903.1843487918 }, { "content": " }\n\n EXPECT_EQ(it.first, \"conv1\");\n\n }\n\n}\n\n\n\n/*\n\nin this test we check if the convolution conv2 will be eliminated from the network. This is expected to be done in trim_to_outputs optimization pass\n\n\n\nNetwork structure: input -> conv1 (output)\n\n \\\n\n ---> conv2 (to be eliminated along with its weights and bias)\n\n*/\n\nTEST(trim_to_outputs, one_node_to_eliminate_case2) {\n\n const auto& engine = get_test_engine();\n\n build_options build_opt;\n\n build_opt.set_option(cldnn::build_option::outputs({ \"conv1\" }));\n\n build_opt.set_option(build_option::optimize_data(false)); // to avoid adding reorders\n\n\n\n auto input = memory::allocate(engine, { data_types::f32, format::yxfb,{ 1, 1, 1, 1 } });\n\n auto weights1 = memory::allocate(engine, { data_types::f32, format::bfyx,{ 1, 1, 1, 1 } });\n", "file_path": "tests/test_cases/trim_to_outputs_gpu_test.cpp", "rank": 97, "score": 182897.87102781082 }, { "content": " \\\n\n ---> conv2 (to be eliminated)\n\n*/\n\nTEST(trim_to_outputs, one_node_to_eliminate_case1) {\n\n const auto& engine = get_test_engine();\n\n build_options build_opt;\n\n build_opt.set_option(cldnn::build_option::outputs({ \"conv1\" }));\n\n build_opt.set_option(build_option::optimize_data(false)); // to avoid adding reorders\n\n\n\n auto input = memory::allocate(engine, { data_types::f32, format::yxfb, { 1, 1, 1, 1 } });\n\n auto weights = memory::allocate(engine, { data_types::f32, format::bfyx, { 1, 1, 1, 1 } });\n\n auto bias = memory::allocate(engine, { data_types::f32, format::bfyx, { 1, 1, 1, 1 } });\n\n\n\n set_values(input, { 1.1f });\n\n set_values(weights, { 2.1f });\n\n set_values(bias, { 1.6f });\n\n\n\n std::vector<float> out_data = { 3.91f };\n\n\n\n topology topology;\n", "file_path": "tests/test_cases/trim_to_outputs_gpu_test.cpp", "rank": 98, "score": 182896.51781644806 }, { "content": "\n\n/*\n\nin this test we check if the convolution conv2 will be eliminated from the network. This is expected to be done in trim_to_outputs optimization pass\n\n\n\nNetwork structure: input ---> conv1 --- ---> conv4 (output)\n\n \\\n\n ---> conv2 ---> conv3\n\nConvolutions conv2, conv3 should be optimized out along with weights23 shered by conv2 and conv3.\n\n*/\n\nTEST(trim_to_outputs, two_nodes_to_eliminate_case1) {\n\n const auto& engine = get_test_engine();\n\n build_options build_opt;\n\n build_opt.set_option(cldnn::build_option::outputs({ \"conv4\" }));\n\n build_opt.set_option(build_option::optimize_data(false)); // to avoid adding reorders\n\n\n\n auto input = memory::allocate(engine, { data_types::f32, format::yxfb,{ 1, 1, 1, 1 } });\n\n auto weights1 = memory::allocate(engine, { data_types::f32, format::bfyx,{ 1, 1, 1, 1 } });\n\n auto weights23 = memory::allocate(engine, { data_types::f32, format::bfyx,{ 1, 1, 1, 1 } });\n\n auto weights4 = memory::allocate(engine, { data_types::f32, format::bfyx,{ 1, 1, 1, 1 } });\n\n auto bias = memory::allocate(engine, { data_types::f32, format::bfyx,{ 1, 1, 1, 1 } });\n", "file_path": "tests/test_cases/trim_to_outputs_gpu_test.cpp", "rank": 99, "score": 182895.6466656147 } ]
C++
qt-creator-opensource-src-4.6.1/src/libs/qmljs/qmljsutils.cpp
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
#include "qmljsutils.h" #include "parser/qmljsast_p.h" #include <QColor> #include <QDir> #include <QRegularExpression> using namespace QmlJS; using namespace QmlJS::AST; namespace { class SharedData { public: SharedData() { validBuiltinPropertyNames.insert(QLatin1String("action")); validBuiltinPropertyNames.insert(QLatin1String("bool")); validBuiltinPropertyNames.insert(QLatin1String("color")); validBuiltinPropertyNames.insert(QLatin1String("date")); validBuiltinPropertyNames.insert(QLatin1String("double")); validBuiltinPropertyNames.insert(QLatin1String("enumeration")); validBuiltinPropertyNames.insert(QLatin1String("font")); validBuiltinPropertyNames.insert(QLatin1String("int")); validBuiltinPropertyNames.insert(QLatin1String("list")); validBuiltinPropertyNames.insert(QLatin1String("point")); validBuiltinPropertyNames.insert(QLatin1String("real")); validBuiltinPropertyNames.insert(QLatin1String("rect")); validBuiltinPropertyNames.insert(QLatin1String("size")); validBuiltinPropertyNames.insert(QLatin1String("string")); validBuiltinPropertyNames.insert(QLatin1String("time")); validBuiltinPropertyNames.insert(QLatin1String("url")); validBuiltinPropertyNames.insert(QLatin1String("var")); validBuiltinPropertyNames.insert(QLatin1String("variant")); validBuiltinPropertyNames.insert(QLatin1String("vector2d")); validBuiltinPropertyNames.insert(QLatin1String("vector3d")); validBuiltinPropertyNames.insert(QLatin1String("vector4d")); validBuiltinPropertyNames.insert(QLatin1String("quaternion")); validBuiltinPropertyNames.insert(QLatin1String("matrix4x4")); validBuiltinPropertyNames.insert(QLatin1String("alias")); } QSet<QString> validBuiltinPropertyNames; }; } Q_GLOBAL_STATIC(SharedData, sharedData) QColor QmlJS::toQColor(const QString &qmlColorString) { QColor color; if (qmlColorString.size() == 9 && qmlColorString.at(0) == QLatin1Char('#')) { bool ok; const int alpha = qmlColorString.midRef(1, 2).toInt(&ok, 16); if (ok) { const QString name = qmlColorString.at(0) + qmlColorString.right(6); if (QColor::isValidColor(name)) { color.setNamedColor(name); color.setAlpha(alpha); } } } else { if (QColor::isValidColor(qmlColorString)) color.setNamedColor(qmlColorString); } return color; } QString QmlJS::toString(UiQualifiedId *qualifiedId, QChar delimiter) { QString result; for (UiQualifiedId *iter = qualifiedId; iter; iter = iter->next) { if (iter != qualifiedId) result += delimiter; result += iter->name; } return result; } SourceLocation QmlJS::locationFromRange(const SourceLocation &start, const SourceLocation &end) { return SourceLocation(start.offset, end.end() - start.begin(), start.startLine, start.startColumn); } SourceLocation QmlJS::fullLocationForQualifiedId(AST::UiQualifiedId *qualifiedId) { SourceLocation start = qualifiedId->identifierToken; SourceLocation end = qualifiedId->identifierToken; for (UiQualifiedId *iter = qualifiedId; iter; iter = iter->next) { if (iter->identifierToken.isValid()) end = iter->identifierToken; } return locationFromRange(start, end); } QString QmlJS::idOfObject(Node *object, UiScriptBinding **idBinding) { if (idBinding) *idBinding = 0; UiObjectInitializer *initializer = initializerOfObject(object); if (!initializer) { initializer = cast<UiObjectInitializer *>(object); if (!initializer) return QString(); } for (UiObjectMemberList *iter = initializer->members; iter; iter = iter->next) { if (UiScriptBinding *script = cast<UiScriptBinding*>(iter->member)) { if (!script->qualifiedId) continue; if (script->qualifiedId->next) continue; if (script->qualifiedId->name != QLatin1String("id")) continue; if (ExpressionStatement *expstmt = cast<ExpressionStatement *>(script->statement)) { if (IdentifierExpression *idexp = cast<IdentifierExpression *>(expstmt->expression)) { if (idBinding) *idBinding = script; return idexp->name.toString(); } } } } return QString(); } UiObjectInitializer *QmlJS::initializerOfObject(Node *object) { if (UiObjectDefinition *definition = cast<UiObjectDefinition *>(object)) return definition->initializer; if (UiObjectBinding *binding = cast<UiObjectBinding *>(object)) return binding->initializer; return 0; } UiQualifiedId *QmlJS::qualifiedTypeNameId(Node *node) { if (UiObjectBinding *binding = AST::cast<UiObjectBinding *>(node)) return binding->qualifiedTypeNameId; else if (UiObjectDefinition *binding = AST::cast<UiObjectDefinition *>(node)) return binding->qualifiedTypeNameId; return 0; } DiagnosticMessage QmlJS::errorMessage(const AST::SourceLocation &loc, const QString &message) { return DiagnosticMessage(Severity::Error, loc, message); } namespace { const QString undefinedVersion = QLatin1String("-1.-1"); } bool QmlJS::maybeModuleVersion(const QString &version) { QRegularExpression re(QLatin1String("^\\d+\\.\\d+$")); return version.isEmpty() || version == undefinedVersion || re.match(version).hasMatch(); } QString QmlJS::modulePath(const QString &name, const QString &version, const QStringList &importPaths) { Q_ASSERT(maybeModuleVersion(version)); if (importPaths.isEmpty()) return QString(); const QString sanitizedVersion = version == undefinedVersion ? QString() : version; const QStringList parts = name.split(QLatin1Char('.'), QString::SkipEmptyParts); auto mkpath = [] (const QStringList &xs) -> QString { return xs.join(QLatin1Char('/')); }; const QRegularExpression re("\\.?\\d+$"); QString candidate; for (QString ver = sanitizedVersion; !ver.isEmpty(); ver.remove(re)) { for (const QString &path: importPaths) { for (int i = parts.count() - 1; i >= 0; --i) { candidate = QDir::cleanPath( QString::fromLatin1("%1/%2.%3/%4").arg(path, mkpath(parts.mid(0, i + 1)), ver, mkpath(parts.mid(i + 1)))); if (QDir(candidate).exists()) return candidate; } } } for (const QString &path: importPaths) { candidate = QDir::cleanPath(QString::fromLatin1("%1/%2").arg(path, mkpath(parts))); if (QDir(candidate).exists()) return candidate; } return QString(); } bool QmlJS::isValidBuiltinPropertyType(const QString &name) { return sharedData()->validBuiltinPropertyNames.contains(name); }
#include "qmljsutils.h" #include "parser/qmljsast_p.h" #include <QColor> #include <QDir> #include <QRegularExpression> using namespace QmlJS; using namespace QmlJS::AST; namespace { class SharedData { public: SharedData() { validBuiltinPropertyNames.insert(QLatin1String("action")); validBuiltinPropertyNames.insert(QLatin1String("bool")); validBuiltinPropertyNames.insert(QLatin1String("color")); validBuiltinPropertyNames.insert(QLatin1String("date")); validBuiltinPropertyNames.insert(QLatin1String("double")); validBuiltinPropertyNames.insert(QLatin1String("enumeration")); validBuiltinPropertyNames.insert(QLatin1String("font")); validBuiltinPropertyNames.insert(QLatin1String("int")); validBuiltinPropertyNames.insert(QLatin1String("list")); validBuiltinPropertyNames.insert(QLatin1String("point")); validBuiltinPropertyNames.insert(QLatin1String("real")); validBuiltinPropertyNames.insert(QLatin1String("rect")); validBuiltinPropertyNames.insert(QLatin1String("size")); validBuiltinPropertyNames.insert(QLatin1String("string")); validBuiltinPropertyNames.insert(QLatin1String("time")); validBuiltinPropertyNames.insert(QLatin1String("url")); validBuiltinPropertyNames.insert(QLatin1String("var")); validBuiltinPropertyNames.insert(QLatin1String("variant")); validBuiltinPropertyNames.insert(QLatin1String("vector2d")); validBuiltinPropertyNames.insert(QLatin1String("vector3d")); validBuiltinPropertyNames.insert(QLatin1String("vector4d")); validBuiltinPropertyNames.insert(QLatin1String("quaternion")); validBuiltinPropertyNames.insert(QLatin1String("matrix4x4")); validBuiltinPropertyNames.insert(QLatin1String("alias")); } QSet<QString> validBuiltinPropertyNames; }; } Q_GLOBAL_STATIC(SharedData, sharedData) QColor QmlJS::toQColor(const QString &qmlColorString) { QColor color; if (qmlColorString.size() == 9 && qmlColorString.at(0) == QLatin1Char('#')) { bool ok; const int alpha = qmlColorString.midRef(1, 2).toInt(&ok, 16); if (ok) { const QString name = qmlColorString.at(0) + qmlColorString.right(6); if (QColor::isValidColor(name)) { color.setNamedColor(name); color.setAlpha(alpha); } } } else { if (QColor::isValidColor(qmlColorString)) color.setNamedColor(qmlColorString); } return color; } QString QmlJS::toString(UiQualifiedId *qualifiedId, QChar delimiter) { QString result; for (UiQualifiedId *iter = qualifiedId; iter; iter = iter->next) { if (iter != qualifiedId) result += delimiter; result += iter->name; } return result; } SourceLocation QmlJS::locationFromRange(const SourceLocation &start, const SourceLocation &end) { return SourceLocation(start.offset, end.end() - start.begin(), start.startLine, start.startColumn); } SourceLocation QmlJS::fullLocationForQualifiedId(AST::UiQualifiedId *qualifiedId) { SourceLocation start = qualifiedId->identifierToken; SourceLocation end = qualifiedId->identifierToken; for (UiQualifiedId *iter = qualifiedId; iter; iter = iter->next) { if (iter->identifierToken.isValid()) end = iter->identifierToken; } return locationFromRange(start, end); } QString QmlJS::idOfObject(Node *object, UiScriptBinding **idBinding) { if (idBinding) *idBinding = 0; UiObjectInitializer *initializer = initializerOfObject(object);
for (UiObjectMemberList *iter = initializer->members; iter; iter = iter->next) { if (UiScriptBinding *script = cast<UiScriptBinding*>(iter->member)) { if (!script->qualifiedId) continue; if (script->qualifiedId->next) continue; if (script->qualifiedId->name != QLatin1String("id")) continue; if (ExpressionStatement *expstmt = cast<ExpressionStatement *>(script->statement)) { if (IdentifierExpression *idexp = cast<IdentifierExpression *>(expstmt->expression)) { if (idBinding) *idBinding = script; return idexp->name.toString(); } } } } return QString(); } UiObjectInitializer *QmlJS::initializerOfObject(Node *object) { if (UiObjectDefinition *definition = cast<UiObjectDefinition *>(object)) return definition->initializer; if (UiObjectBinding *binding = cast<UiObjectBinding *>(object)) return binding->initializer; return 0; } UiQualifiedId *QmlJS::qualifiedTypeNameId(Node *node) { if (UiObjectBinding *binding = AST::cast<UiObjectBinding *>(node)) return binding->qualifiedTypeNameId; else if (UiObjectDefinition *binding = AST::cast<UiObjectDefinition *>(node)) return binding->qualifiedTypeNameId; return 0; } DiagnosticMessage QmlJS::errorMessage(const AST::SourceLocation &loc, const QString &message) { return DiagnosticMessage(Severity::Error, loc, message); } namespace { const QString undefinedVersion = QLatin1String("-1.-1"); } bool QmlJS::maybeModuleVersion(const QString &version) { QRegularExpression re(QLatin1String("^\\d+\\.\\d+$")); return version.isEmpty() || version == undefinedVersion || re.match(version).hasMatch(); } QString QmlJS::modulePath(const QString &name, const QString &version, const QStringList &importPaths) { Q_ASSERT(maybeModuleVersion(version)); if (importPaths.isEmpty()) return QString(); const QString sanitizedVersion = version == undefinedVersion ? QString() : version; const QStringList parts = name.split(QLatin1Char('.'), QString::SkipEmptyParts); auto mkpath = [] (const QStringList &xs) -> QString { return xs.join(QLatin1Char('/')); }; const QRegularExpression re("\\.?\\d+$"); QString candidate; for (QString ver = sanitizedVersion; !ver.isEmpty(); ver.remove(re)) { for (const QString &path: importPaths) { for (int i = parts.count() - 1; i >= 0; --i) { candidate = QDir::cleanPath( QString::fromLatin1("%1/%2.%3/%4").arg(path, mkpath(parts.mid(0, i + 1)), ver, mkpath(parts.mid(i + 1)))); if (QDir(candidate).exists()) return candidate; } } } for (const QString &path: importPaths) { candidate = QDir::cleanPath(QString::fromLatin1("%1/%2").arg(path, mkpath(parts))); if (QDir(candidate).exists()) return candidate; } return QString(); } bool QmlJS::isValidBuiltinPropertyType(const QString &name) { return sharedData()->validBuiltinPropertyNames.contains(name); }
if (!initializer) { initializer = cast<UiObjectInitializer *>(object); if (!initializer) return QString(); }
if_condition
[]
C++
MouseToVJoy/cInputDevices.cpp
R1PeR/MouseToVJoy
c5487f6bf6e3db8ac41478a612a6c2642c69b7af
#include "input.h" void CInputDevices::getData(LPARAM lParam) { UINT bufferSize; GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &bufferSize, sizeof(RAWINPUTHEADER)); if (bufferSize <= 40) GetRawInputData((HRAWINPUT)lParam, RID_INPUT, (LPVOID)_buffer, &bufferSize, sizeof(RAWINPUTHEADER)); RAWINPUT *raw = (RAWINPUT*)_buffer; _mouseXChange = raw->data.mouse.lLastX; _mouseYChange = raw->data.mouse.lLastY; _mouseZChange = (short)raw->data.mouse.usButtonData; if (_mouseZChange / 120 == 1) { _isMouseWheelUp = true; } else { _isMouseWheelUp = false; }; if (_mouseZChange / -120 == 1) { _isMouseWheelDown = true; } else { _isMouseWheelDown = false; }; if (raw->header.dwType == RIM_TYPEMOUSE) { bool bStateDown = raw->data.mouse.usButtonFlags & RI_MOUSE_LEFT_BUTTON_DOWN; bool bStateUp = raw->data.mouse.usButtonFlags & RI_MOUSE_LEFT_BUTTON_UP; if (bStateDown == true && bStateUp == false) { _isLeftMouseButtonPressed = true; _isKeyboardButtonPressed[0x01] = true; } if (bStateUp == true) { _isLeftMouseButtonPressed = false; _isKeyboardButtonPressed[0x01] = false; } bool bStateDownTwo = raw->data.mouse.usButtonFlags & RI_MOUSE_RIGHT_BUTTON_DOWN; bool bStateUpTwo = raw->data.mouse.usButtonFlags & RI_MOUSE_RIGHT_BUTTON_UP; if (bStateDownTwo == true && bStateUpTwo == false) { _isRightMouseButtonPressed = true; _isKeyboardButtonPressed[0x02] = true; } if (bStateUpTwo == true) { _isRightMouseButtonPressed = false; _isKeyboardButtonPressed[0x02] = false; } } if (raw->header.dwType == RIM_TYPEKEYBOARD) { USHORT keyCode = raw->data.keyboard.VKey; bool keyUp = raw->data.keyboard.Flags & RI_KEY_BREAK; bool* pbToKey = NULL; for (int i = 0; i < 165; ++i) { if (keyCode == i + 0x01) { pbToKey = &_isKeyboardButtonPressed[i + 0x01]; break; } } if (pbToKey != NULL) { *pbToKey = checkKeyPress(*pbToKey, keyUp); return; } } } bool CInputDevices::checkKeyPress(bool isLastKeyState, bool isThisKeyState) { if (isThisKeyState == false) { if (isLastKeyState == true) { return true; } else { return true; } } else if (isThisKeyState == true) { if (isLastKeyState == false) { return false; } else return false; } }
#include "input.h" void CInputDevices::getData(LPARAM lParam) { UINT bufferSize; GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &bufferSize, sizeof(RAWINPUTHEADER)); if (bufferSize <= 40) GetRawInputData((HRAWINPUT)lParam, RID_INPUT, (LPVOID)_buffer, &bufferSize, sizeof(RAWINPUTHEADER)); RAWINPUT *raw = (RAWINPUT*)_buffer; _mouseXChange = raw->data.mouse.lLastX; _mouseYChange = raw->data.mouse.lLastY; _mouseZChange = (short)raw->data.mouse.usButtonData; if (_mouseZChange / 120 == 1) { _isMouseWheelUp = true; } else { _isMouseWheelUp = false; }; if (_mouseZChange / -120 == 1) { _isMouseWheelDown = true; } else { _isMouseWheelDown = false; }; if (raw->header.dwType == RIM_TYPEMOUSE) { bool bStateDown = raw->data.mouse.usButtonFlags & RI_MOUSE_LEFT_BUTTON_DOWN; bool bStateUp = raw->data.mouse.usButtonFlags & RI_MOUSE_LEFT_BUTTON_UP; if (bStateDown == true
yState == false) { if (isLastKeyState == true) { return true; } else { return true; } } else if (isThisKeyState == true) { if (isLastKeyState == false) { return false; } else return false; } }
&& bStateUp == false) { _isLeftMouseButtonPressed = true; _isKeyboardButtonPressed[0x01] = true; } if (bStateUp == true) { _isLeftMouseButtonPressed = false; _isKeyboardButtonPressed[0x01] = false; } bool bStateDownTwo = raw->data.mouse.usButtonFlags & RI_MOUSE_RIGHT_BUTTON_DOWN; bool bStateUpTwo = raw->data.mouse.usButtonFlags & RI_MOUSE_RIGHT_BUTTON_UP; if (bStateDownTwo == true && bStateUpTwo == false) { _isRightMouseButtonPressed = true; _isKeyboardButtonPressed[0x02] = true; } if (bStateUpTwo == true) { _isRightMouseButtonPressed = false; _isKeyboardButtonPressed[0x02] = false; } } if (raw->header.dwType == RIM_TYPEKEYBOARD) { USHORT keyCode = raw->data.keyboard.VKey; bool keyUp = raw->data.keyboard.Flags & RI_KEY_BREAK; bool* pbToKey = NULL; for (int i = 0; i < 165; ++i) { if (keyCode == i + 0x01) { pbToKey = &_isKeyboardButtonPressed[i + 0x01]; break; } } if (pbToKey != NULL) { *pbToKey = checkKeyPress(*pbToKey, keyUp); return; } } } bool CInputDevices::checkKeyPress(bool isLastKeyState, bool isThisKeyState) { if (isThisKe
random
[ { "content": "#include <windows.h>\n\n#include <string>\n\n#include \"forcefeedback.h\"\n\n\n\nusing namespace std;\n\n// Convert Packet type to String\n\nBOOL ForceFeedBack::packetType2Str(FFBPType type, LPTSTR outStr)\n\n{\n\n\tBOOL stat = TRUE;\n\n\tLPTSTR Str = \"\";\n\n\n\n\tswitch (type)\n\n\t{\n\n\tcase PT_EFFREP:\n\n\t\tStr = \"Effect Report\";\n\n\t\tbreak;\n\n\tcase PT_ENVREP:\n\n\t\tStr = \"Envelope Report\";\n\n\t\tbreak;\n\n\tcase PT_CONDREP:\n", "file_path": "MouseToVJoy/forceFeedBack.cpp", "rank": 4, "score": 6.969519864496476 }, { "content": "\n\n\t// Alphabetic as in any letter from the Alphabet. So IsAlphabeticKeyDown returns\n\n\t// a value of true or false from an array of 25 booleans. Each index is associated\n\n\t// with a position in the english alphabet. Use one of the enumerated values\n\n\t// such as VKey_A and subtract 0x41 or make a different enumeration list\n\n\t// for all 25 letters and set the first value to 0.\n\n\n\n\tbool isAlphabeticKeyDown(int letter) { return _isKeyboardButtonPressed[letter]; }\n\n\n\nprivate:\n\n\n\n\t// Two input devices are covered by this class. Mouse and Keyboard.\n\n\t// A good reference for them is: http://www.toymaker.info/Games/html/raw_input.html\n\n\tRAWINPUTDEVICE _rawInputDevice[2];\n\n\n\n\t// As said on www.toymaker.info the mouse size is 40 and the keyboard 32.\n\n\t// So it appears as if the buffer will be filled with either or, not both.\n\n\t// Thus, just 40 bytes.\n\n\tBYTE _buffer[40];\n\n\n", "file_path": "MouseToVJoy/input.h", "rank": 5, "score": 6.354000509330108 }, { "content": "#include \"socket.h\"\n\n#include <WS2tcpip.h>\n\n#include <Windows.h>\n\n#include <stdio.h>\n\n#include <vector>\n\nint sock = socket(AF_INET, SOCK_DGRAM, 0);\n\nchar* buffer[256];\n\n\n\ntypedef struct\n\n{\n\n\tint x;\n\n\tint y;\n\n\tint z;\n\n} Vec;\n\ntypedef struct\n\n{\n\n\tfloat x;\n\n\tfloat y;\n\n\tfloat z;\n\n} Vector;\n", "file_path": "MouseToVJoy/socket.cpp", "rank": 7, "score": 5.76269748986407 }, { "content": "\t\t_finish = _start = 0;\n\n\t\t_running = false;\n\n\t}\n\n\n\n\n\n\tinline void Stopwatch::start() noexcept\n\n\t{\n\n\t\t_running = true;\n\n\t\t_finish = 0;\n\n\n\n\t\t_start = counter();\n\n\t}\n\n\n\n\n\n\tinline void Stopwatch::stop() noexcept\n\n\t{\n\n\t\t_finish = counter();\n\n\t\t_running = false;\n\n\t}\n\n\n", "file_path": "MouseToVJoy/Stopwatch.h", "rank": 8, "score": 5.331728983481382 }, { "content": "\t\telse isButton1Clicked = false;\n\n\t\tif (input.isAlphabeticKeyDown(gearShiftDownKey)) {\n\n\t\t\tisButton2Clicked = true;\n\n\t\t}\n\n\t\telse isButton2Clicked = false;\n\n\t}\n\n\tif (input.isAlphabeticKeyDown(handBrakeKey)){\n\n\t\tisButton3Clicked = true;\n\n\t}\n\n\telse isButton3Clicked = false;\n\n\tif (_isCursorLocked == true) {\n\n\t\tSetCursorPos(0, 0);\n\n\t}\n\n\n\n}\n\n//Function responsible for getting and modifying vars for steering wheel.\n\nvoid MouseToVjoy::mouseLogic(CInputDevices input, INT &X, DOUBLE sensitivity, DOUBLE sensitivityCenterReduction, INT useCenterReduction, BOOL &isButton1Clicked, BOOL &isButton2Clicked, INT useWheelAsShifter){\n\n\t//vjoy max value is 0-32767 to make it easier to scale linear reduction/acceleration I subtract half of it so 16384 to make it -16384 to 16384.\n\n\tX = X - 16384;\n\n\tif (X > 0) {\n", "file_path": "MouseToVJoy/MouseToVJoy.cpp", "rank": 9, "score": 5.328953351031036 }, { "content": "\t/* Set the IP address to desired host to connect to */\n\n\tserverAddres.sin_addr.s_addr = inet_addr(\"127.0.0.1\");\n\n\n\n\tif (bind(sock, (struct sockaddr *) &serverAddres, sizeof(serverAddres)) < 0) {\n\n\t\tprintf(\"Failed to bind socket\");\n\n\t}\n\n\telse {\n\n\t\tprintf(\"Binded to socket\");\n\n\t}\n\n}\n\nvoid reciveBuffer() {\n\n\trecv(sock, *buffer, 256, 0);\n\n}\n\nint interpretData() {\n\n\tOutSimPack out;\n\n\tout.Time = (out.Time << 8+*buffer[0]) + (out.Time << 16 + *buffer[1]) + (out.Time << 32 + *buffer[2]) + (out.Time << 64 + *buffer[3]);\n\n}\n", "file_path": "MouseToVJoy/socket.cpp", "rank": 10, "score": 5.24748411914339 }, { "content": "void VJoy::feedDevice(UINT iInterface, INT X, INT Y, INT Z, INT RX, BOOL BUTTON1, BOOL BUTTON2, BOOL BUTTON3) {\n\n\t//Reports all axies to virtual joystick.\n\n\t_iReport.bDevice = iInterface;\n\n\t_iReport.wAxisX = X;\n\n\t_iReport.wAxisY = Y;\n\n\t_iReport.wAxisZ = Z;\n\n\t_iReport.wAxisXRot = RX;\n\n\tif (BUTTON1) _iReport.lButtons |= 0x1; else _iReport.lButtons &= 0xFE;\n\n\tif (BUTTON2) _iReport.lButtons |= 0x2; else _iReport.lButtons &= 0xFD;\n\n\tif (BUTTON3) _iReport.lButtons |= 0x4; else _iReport.lButtons &= 0xFB;\n\n\n\n\n\n\tPVOID pPositionMessage = (PVOID)(&_iReport);\n\n\tUpdateVJD(iInterface, pPositionMessage);\n\n\n\n\n\n\n\n\n\n\n\n\n", "file_path": "MouseToVJoy/vJoy.cpp", "rank": 11, "score": 4.869894865666114 }, { "content": "\t\tbreak;\n\n\tdefault:\n\n\t\tstat = FALSE;\n\n\t\tbreak;\n\n\t}\n\n\n\n\tif (stat)\n\n\t\t_tcscpy_s(outStr, 100, Str);\n\n\n\n\treturn stat;\n\n}\n\n\n\n// Convert Effect type to String\n\nBOOL ForceFeedBack::effectType2Str(FFBEType type, LPTSTR outStr)\n\n{\n\n\tBOOL stat = TRUE;\n\n\tLPTSTR Str = \"\";\n\n\n\n\tswitch (type)\n\n\t{\n", "file_path": "MouseToVJoy/forceFeedBack.cpp", "rank": 12, "score": 4.839036149976743 }, { "content": "\t\tstat = FALSE;\n\n\t\tbreak;\n\n\t};\n\n\n\n\tif (stat)\n\n\t\t_tcscpy_s(outStr, 100, Str);\n\n\n\n\treturn stat;\n\n}\n\n\n\n// Convert PID Device Control to String\n\nBOOL ForceFeedBack::devCtrl2Str(FFB_CTRL ctrl, LPTSTR outStr)\n\n{\n\n\tBOOL stat = TRUE;\n\n\tLPTSTR Str = \"\";\n\n\n\n\tswitch (ctrl)\n\n\t{\n\n\tcase CTRL_ENACT:\n\n\t\tStr = \"Enable Actuators\";\n", "file_path": "MouseToVJoy/forceFeedBack.cpp", "rank": 13, "score": 4.42499627175179 }, { "content": "\tif (stat)\n\n\t\t_tcscpy_s(outStr, 100, Str);\n\n\n\n\treturn stat;\n\n}\n\n\n\n// Convert Effect operation to string\n\nBOOL ForceFeedBack::effectOpStr(FFBOP op, LPTSTR outStr)\n\n{\n\n\tBOOL stat = TRUE;\n\n\tLPTSTR Str = \"\";\n\n\n\n\tswitch (op)\n\n\t{\n\n\tcase EFF_START:\n\n\t\tStr = \"Effect Start\";\n\n\t\tbreak;\n\n\tcase EFF_SOLO:\n\n\t\tStr = \"Effect Solo Start\";\n\n\t\tbreak;\n", "file_path": "MouseToVJoy/forceFeedBack.cpp", "rank": 14, "score": 4.244110741219059 }, { "content": "\t\treturn -1;\n\n\t}\n\n\telse\n\n\t{\n\n\t\tprintf(\"Acquired: vJoy device number %d.\\n\", iInterface);\n\n\t}\n\n}\n\n//If UINT iInterface exist, enable FFB to device.\n\nint VJoy::enableFFB(UINT iInterface) {\n\n\t// Acquire the target if not already owned\n\n\tBOOL Ffbstarted = FfbStart(iInterface);\n\n\tif (!Ffbstarted)\n\n\t{\n\n\t\tprintf(\"Failed to start FFB on vJoy device number %d.\\n\", iInterface);\n\n\t}\n\n\telse\n\n\t\tprintf(\"Started FFB on vJoy device number %d - OK\\n\", iInterface);\n\n\treturn 0;\n\n}\n\n//When UINT iInterface is accuired, feeds vars X Y Z RX to Axises X Y Z RX.\n", "file_path": "MouseToVJoy/vJoy.cpp", "rank": 15, "score": 4.154107852628176 }, { "content": "#include <windows.h>\n\n#include <iostream>\n\n#include <stdio.h>\n\n#include <time.h>\n\n#include \"fileRead.h\"\n\n#include \"vjoy.h\"\n\n#include \"mousetovjoy.h\"\n\n#include \"public.h\"\n\n#include \"vjoyinterface.h\"\n\n#include \"input.h\"\n\n#include \"stopwatch.h\"\n\n#include \"forcefeedback.h\"\n\n\n\nint wheelPos = 0;\n\nusing namespace std;\n\nusing win32::Stopwatch;\n\n//Instantiate classes\n\nconst char g_szClassName[] = \"myWindowClass\";\n\nHWND hwnd;\n\nWNDCLASSEX wc;\n", "file_path": "MouseToVJoy/main.cpp", "rank": 16, "score": 4.0262928786692775 }, { "content": "#pragma once\n\n#ifndef VJOY_H\n\n#define VJOY_H\n\n#include <stdio.h>\n\n#include <Windows.h>\n\n#include <tchar.h>\n\n#include <windows.h>\n\n#include <basetyps.h>\n\n#include \"public.h\"\n\n#include \"vjoyinterface.h\"\n\n/* Class that does everything with the vjoy, testing, accuiring, feeding.*/\n\n\n\n\n", "file_path": "MouseToVJoy/vjoy.h", "rank": 17, "score": 3.9527649754571397 }, { "content": "\t// The flag is only set once when the button is pressed and so to determine if the mouse button is being held down you need to record it as down\n\n\t// until you get a RI_MOUSE_LEFT_BUTTON_UP flag.\n\n\n\n\t// 2. The Keyboard\n\n\t// When a key is held down the raw->data.heyboard.Flags has the RI_KEY_MAKE bit set (actually none as the value is 0) and when the key is released \n\n\t// the RI_KEY_BREAK bit is set (value is 1). \n\n\n\n\t// 1 and 2 is what I got directly from ToyMaker's website. I believe for the most part CheckKeyPress takes what was said into account.\n\n\tbool checkKeyPress(bool bLastKeyState, bool bThisKeyState);\n\n\n\n};\n\n\n\n#endif", "file_path": "MouseToVJoy/input.h", "rank": 18, "score": 3.885564138841668 }, { "content": "#pragma once\n\n#ifndef FORCEFEEDBACK_H\n\n#define FORCEFEEDBACK_H\n\n#include \"vjoy.h\"\n\n#include \"vjoyinterface.h\"\n\n#include \"input.h\"\n\n#include \"ffbsize.h\"\n\n#include <Windows.h>\n\n\n\n/* Basic funtion that gets data, then processes it and modifies inputs.*/\n\n\n", "file_path": "MouseToVJoy/forceFeedBack.h", "rank": 19, "score": 3.7977943360476276 }, { "content": "#pragma once\n\n#ifndef FILEREAD_H\n\n#define FILEREAD_H\n\n#include <string>\n\n#include <sstream>\n\n#include <fstream>\n\n#include <iostream>\n\n#include <windows.h>\n\n#include <stack>\n\n\n\nusing namespace std;\n\n/*Funtion takes two strings and returns array of numbers from that file.\n\n \"fileName\" is name of the file that will be opened,\n\n \"checkArray\" is array of strings that will be read(max 32 strings),\n", "file_path": "MouseToVJoy/fileRead.h", "rank": 20, "score": 3.600575832384819 }, { "content": "#include \"mousetovjoy.h\"\n\n#include <iostream>\n\n#include <math.h>\n\n#define STEERING_MAX 16384\n\n#define STEERING_MIN -16384\n\n//Function responsible for getting and modifying vars for throttle, break, clutch.\n\nvoid MouseToVjoy::inputLogic(CInputDevices input, INT &axisX, INT &axisY, INT &axisZ, INT &axisRX, BOOL &isButton1Clicked, BOOL &isButton2Clicked, BOOL &isButton3Clicked, DOUBLE attackTimeThrottle, DOUBLE releaseTimeThrottle, DOUBLE attackTimeBreak, DOUBLE releaseTimeBreak, DOUBLE attackTimeClutch, DOUBLE releaseTimeClutch, INT throttleKey, INT breakKey, INT clutchKey, INT gearShiftUpKey, INT gearShiftDownKey, INT handBrakeKey, INT mouseLockKey, INT mouseCenterKey, INT useMouse, DOUBLE accelerationThrottle, DOUBLE accelerationBreak, DOUBLE accelerationClutch, INT useWheelAsShifter, DOUBLE deltaTime) {\n\n\t\n\n\tif (useMouse == 1) {\n\n\t\tif (input.isLeftMouseButtonDown() && axisY < 32767) {\n\n\t\t\taxisY = (axisY + (attackTimeThrottle*deltaTime)) * accelerationThrottle;\n\n\t\t}\n\n\t\tif (!input.isLeftMouseButtonDown() && axisY > 1) {\n\n\t\t\taxisY = (axisY - (releaseTimeThrottle*deltaTime)) / accelerationThrottle;;\n\n\t\t}\n\n\t\tif (input.isRightMouseButtonDown() && axisZ < 32767) {\n\n\t\t\taxisZ = (axisZ + (attackTimeBreak*deltaTime)) * accelerationBreak;\n\n\t\t}\n\n\t\tif (!input.isRightMouseButtonDown() && axisZ > 1) {\n\n\t\t\taxisZ = (axisZ - (releaseTimeBreak*deltaTime)) / accelerationBreak;\n", "file_path": "MouseToVJoy/MouseToVJoy.cpp", "rank": 21, "score": 3.532155705839267 }, { "content": "#pragma once\n\n#ifndef MOUSETOVJOY_H\n\n#define MOUSETOVJOY_H\n\n#include \"input.h\"\n\n#include \"vjoy.h\"\n\n#include \"stopwatch.h\"\n\n/* Basic funtion that gets data, then processes it and modifies inputs.*/\n\n\n", "file_path": "MouseToVJoy/mousetovjoy.h", "rank": 22, "score": 3.508010919153832 }, { "content": "// Convert range 0x00-0xFF to 0%-100%\n\nint ForceFeedBack::byte2Percent(BYTE inByte)\n\n{\n\n\treturn ((UINT)inByte * 100) / 255;\n\n}\n\n\n\n// Convert One-Byte 2's complement input to integer\n\nint ForceFeedBack::twosCompByte2Int(BYTE in)\n\n{\n\n\tint tmp;\n\n\tBYTE inv = ~in;\n\n\tBOOL isNeg = in >> 7;\n\n\tif (isNeg)\n\n\t{\n\n\t\ttmp = (int)(inv);\n\n\t\ttmp = -1 * tmp;\n\n\t\treturn tmp;\n\n\t}\n\n\telse\n\n\t\treturn (int)in;\n", "file_path": "MouseToVJoy/forceFeedBack.cpp", "rank": 23, "score": 3.44002548739955 }, { "content": "#include \"vjoyinterface.h\"\n\nclass vJoyInput {\n\npublic:\n\n\tint TestDriver();\n\n\tint\tTestVirtualDevices();\n\n\tint AccuireDevice();\n\n\tvoid FeedDevice();\n\n\tvoid InputLogic();\n\n};\n\n#endif", "file_path": "MouseToVJoy/vJoyInput.h", "rank": 24, "score": 3.3819936782060047 }, { "content": "\t// Should be obvious what functions return these two values.\n\n\tint _mouseXChange;\n\n\tint _mouseYChange;\n\n\tint\t\t\t _mouseZChange;\n\n\n\n\t// Again, should be obvious what functions use these. \n\n\t// LMB = Left Mouse Button. RMB = Right Mouse Button\n\n\tbool _isLeftMouseButtonPressed;\n\n\tbool _isRightMouseButtonPressed;\n\n\tbool _isMouseWheelUp;\n\n\tbool _isMouseWheelDown;\n\n\n\n\t// Notice how I use an array of bools rather than having a separate bool for each.\n\n\t// In the source file you will see how my enumerations come into play for knowing what index\n\n\t// to access.\n\n\tbool _isKeyboardButtonPressed[166];\n\n\n\n\t// The CheckKeyPress function is because of these issues:\n\n\n\n\t// 1. The Mouse\n", "file_path": "MouseToVJoy/input.h", "rank": 25, "score": 3.3482420432435784 }, { "content": "}\n\n\n\n// Convert One-Byte 2's complement input to integer\n\nint ForceFeedBack::twosCompWord2Int(WORD in)\n\n{\n\n\tint tmp;\n\n\tWORD inv = ~in;\n\n\tBOOL isNeg = in >> 15;\n\n\tif (isNeg)\n\n\t{\n\n\t\ttmp = (int)(inv);\n\n\t\ttmp = -1 * tmp;\n\n\t\treturn tmp - 1;\n\n\t}\n\n\telse\n\n\t\treturn (int)in;\n\n}\n\n// Convert Ffb Calls into FFBSIZE struct\n\nvoid CALLBACK ForceFeedBack::ffbToVJoy(PVOID data, PVOID userData)\n\n{\n", "file_path": "MouseToVJoy/forceFeedBack.cpp", "rank": 26, "score": 3.313547646847826 }, { "content": "\twhile (true) {\n\n\t\tsw.stop();\n\n\t\tsw.start();\n\n\t\twhile (PeekMessage(&msgWindow, NULL, 0, 0, PM_REMOVE))\n\n\t\t{\n\n\t\t\tTranslateMessage(&msgWindow);\n\n\t\t\tDispatchMessage(&msgWindow);\n\n\t\t}\n\n\t\t//To optimalize cpu usade wait 2 milisecond before running update code.\n\n\t\tupdateCode();\n\n\t\t//If Message is equal to quit or destroy, break loop and end program.\n\n\t\tif (msgWindow.message == WM_QUIT || msgWindow.message == WM_DESTROY)\n\n\t\t{\n\n\t\t\tbreak;\n\n\t\t}\n\n\t}\n\n\t\t\n\n}\n\n\n\n\n", "file_path": "MouseToVJoy/main.cpp", "rank": 27, "score": 3.2789030040061844 }, { "content": "#include \"fileRead.h\"\n\nvoid FileRead::newFile(string fileName, string checkArray[]) {\n\n\tstring line;\n\n\tifstream file(fileName);\n\n\tif (file.is_open()) {\n\n\t\twhile (getline(file, line)) {\n\n\t\t\tstringstream ss(line);\n\n\t\t\tstring tmp;\n\n\t\t\tdouble value;\n\n\t\t\tchar c;\n\n\t\t\tss >> tmp >> c >> value;\n\n\t\t\tfor(int i = 0; i < 32; i++){\n\n\t\t\t\tif (tmp == checkArray[i]) {\n\n\t\t\t\t\t_resultArray[i] = value;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tfile.close();\n\n\t}\n\n\telse{\n\n\t\tprintf(\"Config file not found\\n\");\n\n\t}\n\n}", "file_path": "MouseToVJoy/fileRead.cpp", "rank": 28, "score": 3.216106551676119 }, { "content": "#pragma once\n\n#ifndef VJOYINPUT_H\n\n#define VJOYINPUT_H\n\n\n\n#include \"vjoyinterface.h\"\n", "file_path": "MouseToVJoy/vJoyInput.h", "rank": 29, "score": 2.9006489102481985 }, { "content": "MSG msgWindow; //Intantiating a MSG class, which recives messages from \"dummy\" window \n\nVJoy vJ;\n\nMouseToVjoy mTV;//Class that gets data, then processes it and modifies axises.\n\nCInputDevices rInput;//Class that helps with determining what key was pressed.\n\nFileRead fR;//Class used for reading and writing to config.txt file.\n\nForceFeedBack fFB;//Used to recive and interpret ForceFeedback calls from game window.\n\nStopwatch sw;//Measuring time in nanoseconds\n\nINT axisX, axisY, axisZ, axisRX, ffbStrength; //Local variables that stores all axis values and forcefeedback strength we need.\n\nBOOL isButton1Clicked, isButton2Clicked, isButton3Clicked; //Bools that stores information if button was pressed.\n\nvoid CALLBACK FFBCALLBACK(PVOID data, PVOID userData) {//Creating local callback which just executes callback from ForceFeedBack class.\n\n\tfFB.ffbToVJoy(data, userData);\n\n}\n\n//Code that is run once application is initialized, test virtual joystick and accuires it, also it reads config.txt file and prints out menu and variables.\n\nvoid initializationCode() {\n\n\t//Code that is run only once, tests vjoy device, reads config file and prints basic out accuired vars.\n\n\tUINT DEV_ID = 1;\n\n\tvJ.testDriver();//Test if driver is installed and compatible.\n\n\tvJ.testVirtualDevices(DEV_ID);//Test if virtually created joystick is up and running.\n\n\tvJ.accuireDevice(DEV_ID);//Accuire virtual joystick of index number DEV_ID\n\n\tvJ.enableFFB(DEV_ID);//Enable virtual joystick of index number DEV_ID to accept forcefeedback calls\n", "file_path": "MouseToVJoy/main.cpp", "rank": 30, "score": 2.816309444087254 }, { "content": "\t\t\tif (rInput.isMouseWheelUp())isButton1Clicked = true;\n\n\t\t\tif (rInput.isMouseWheelDown())isButton2Clicked = true;\n\n\t\t\tmTV.mouseLogic(rInput, axisX, fR.result(0), fR.result(20), fR.result(16), isButton1Clicked, isButton2Clicked, fR.result(22));\n\n\t\tbreak;\n\n\tcase WM_CLOSE:\n\n\t\tPostQuitMessage(0);\n\n\tcase WM_DESTROY:\n\n\t\tDestroyWindow(hwnd);\n\n\tdefault:\n\n\t\treturn DefWindowProc(hwnd, Msg, wParam, lParam);\n\n\t}\n\n\treturn 0;\n\n}\n\n//Main function\n\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)\n\n{\n\n\t//invisible window initialization to be able to recive raw input even if the window is not focused.\n\n\tstatic const char* class_name = \"DUMMY_CLASS\";\n\n\twc.cbSize = sizeof(WNDCLASSEX);\n\n\twc.lpfnWndProc = WndProc; // function which will handle messages\n", "file_path": "MouseToVJoy/main.cpp", "rank": 31, "score": 2.7224522554829838 }, { "content": "\t// to be sure the \n\n\n\n\tbool isLeftMouseButtonDown() { return _isLeftMouseButtonPressed; }\n\n\tbool isRightMouseButtonDown() { return _isRightMouseButtonPressed; }\n\n\tbool\t\t isMouseWheelUp() { return _isMouseWheelUp; }\n\n\tbool\t\t isMouseWheelDown() { return _isMouseWheelDown; }\n\n\n\n\t// These functions return values that are relative to the change in position\n\n\t// of your mouse.\n\n\n\n\tint getMouseChangeX() { return _mouseXChange; }\n\n\tint getMouseChangeY() { return _mouseYChange; }\n\n\tint getMouseChangeZ() { return _mouseZChange; }\n\n\t// OPTIONALLY:\n\n\t// To obtain exact mouse coords check the uMsg in your Application's MsgProc\n\n\t// for WM_MOUSEMOVE, and use HIWORD() LOWORD() functions to extract the mouse X,Y\n\n\t// from lParam. Store them in the below variables.\n\n\n\n\tint mouseX;\n\n\tint mouseY;\n", "file_path": "MouseToVJoy/input.h", "rank": 32, "score": 2.583894400012936 }, { "content": "\twc.hInstance = hInstance;\n\n\twc.lpszClassName = class_name;\n\n\tif (RegisterClassEx(&wc)) {\n\n\t\tCreateWindowEx(0, class_name, \"dummy_name\", 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, NULL, NULL);\n\n\t}\n\n\t//Allocating console to process and redirect every stdout, stdin to it.\n\n\tstring cmdLine = lpCmdLine;\n\n\tif (cmdLine != \"-noconsole\") {\n\n\t\tAllocConsole();\n\n\t\tfreopen(\"CONOUT$\", \"w\", stdout);\n\n\t\tfreopen(\"CONIN$\", \"r\", stdin);\n\n\t\tios::sync_with_stdio();\n\n\t}\n\n\t//Show invisible window, update it, then do initialization code.\n\n\tShowWindow(hwnd, nCmdShow);\n\n\tUpdateWindow(hwnd);\n\n\tinitializationCode();\n\n\t\n\n\n\n\t//Loop on PeekMessage instead of GetMessage to avoid overflow.\n", "file_path": "MouseToVJoy/main.cpp", "rank": 33, "score": 2.4864428992132113 }, { "content": "\t\telse {\n\n\t\t\tffbStrength = -(fFB.getFfbSize().getMagnitude())*(sw.elapsedMilliseconds()*0.001);\n\n\t\t}\n\n\t}\n\n\tif (fFB.getFfbSize().getEffectType() == \"Period\") {\n\n\t\tffbStrength = (fFB.getFfbSize().getOffset()*0.5)*(sw.elapsedMilliseconds()*0.001);\n\n\t}\n\n\tif (fR.result(21) == 1) {\n\n\t\taxisX = axisX + ffbStrength;\n\n\t\tffbStrength = 0;\n\n\t}\n\n\tmTV.inputLogic(rInput, axisX, axisY, axisZ, axisRX, isButton1Clicked, isButton2Clicked, isButton3Clicked, fR.result(1), fR.result(2), fR.result(3), fR.result(4), fR.result(5), fR.result(6), fR.result(7), fR.result(8), fR.result(9), fR.result(10), fR.result(11), fR.result(12), fR.result(13), fR.result(14), fR.result(15), fR.result(17), fR.result(18), fR.result(19), fR.result(22), sw.elapsedMilliseconds());\n\n\tvJ.feedDevice(1, axisX, axisY, axisZ, axisRX, isButton1Clicked, isButton2Clicked, isButton3Clicked);\n\n\tisButton1Clicked = false;\n\n\tisButton2Clicked = false;\n\n}\n\n//Creates callback on window, registers raw input devices and processes mouse and keyboard input\n\nLRESULT CALLBACK WndProc(HWND hwnd, UINT Msg, WPARAM wParam, LPARAM lParam)\n\n{\n\n\tswitch (Msg)\n", "file_path": "MouseToVJoy/main.cpp", "rank": 34, "score": 2.3287892908569874 }, { "content": "MIT License\n\n\n\nCopyright (c) 2018 Sebastian Waluś\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in all\n\ncopies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\nSOFTWARE.\n", "file_path": "LICENSE.md", "rank": 35, "score": 2.2525312622996365 }, { "content": "////////////////////////////////////////////////////////////////////////////////\n\n//\n\n// Stopwatch.h -- A simple stopwatch implementation, based on Windows\n\n// high-performance timers.\n\n// Can come in handy when measuring elapsed times of\n\n// portions of C++ code.\n\n//\n\n// Copyright (C) 2016 by Giovanni Dicanio <[email protected]>\n\n//\n\n////////////////////////////////////////////////////////////////////////////////\n\n\n\n\n\n#pragma once\n\n\n\n#include <crtdbg.h> // For _ASSERTE\n\n#include <Windows.h> // For high-performance timers\n\n\n\n\n\nnamespace win32\n\n{\n\n\n\n\n\n\t//------------------------------------------------------------------------------\n\n\t// Class to measure time intervals, for benchmarking portions of code.\n\n\t// It's a convenient wrapper around the Win32 high-resolution timer APIs\n\n\t// QueryPerformanceCounter() and QueryPerformanceFrequency().\n\n\t//------------------------------------------------------------------------------\n", "file_path": "MouseToVJoy/Stopwatch.h", "rank": 36, "score": 2.210229342591086 }, { "content": "\t\tdouble elapsedMilliseconds(long long start, long long finish) const noexcept;\n\n\t};\n\n\n\n\n\n\n\n\t//\n\n\t// Inline implementations\n\n\t//\n\n\n\n\n\n\tinline Stopwatch::Stopwatch() noexcept\n\n\t\t: _running{ false }\n\n\t\t, _start{ 0 }\n\n\t\t, _finish{ 0 }\n\n\t\t, _frequency{ frequency() }\n\n\t{}\n\n\n\n\n\n\tinline void Stopwatch::reset() noexcept\n\n\t{\n", "file_path": "MouseToVJoy/Stopwatch.h", "rank": 37, "score": 2.1457735797829183 }, { "content": "\tcase VJD_STAT_BUSY:\n\n\t\tprintf(\"vJoy Device %d is already owned by another feeder\\n\\\n\nCannot continue\\n\", iInterface);\n\n\t\treturn -3;\n\n\tcase VJD_STAT_MISS:\n\n\t\tprintf(\"vJoy Device %d is not installed or disabled\\n\\\n\nCannot continue\\n\", iInterface);\n\n\t\treturn -4;\n\n\tdefault:\n\n\t\tprintf(\"vJoy Device %d general error\\nCannot continue\\n\", iInterface);\n\n\t\treturn -1;\n\n\t};\n\n}\n\n//If UINT iInterface is existing, tries to accuire it.\n\nint VJoy::accuireDevice(UINT iInterface) {\n\n\t// Acquire the target if not already owned\n\n\tif ((_status == VJD_STAT_OWN) || \\\n\n((_status == VJD_STAT_FREE) && (!AcquireVJD(iInterface))))\n\n\t{\n\n\t\tprintf(\"Failed to acquire vJoy device number %d.\\n\", iInterface);\n", "file_path": "MouseToVJoy/vJoy.cpp", "rank": 38, "score": 2.1270697276835038 }, { "content": "\tif (!input.isAlphabeticKeyDown(clutchKey) && axisRX > 1) {\n\n\t\taxisRX = (axisRX - (releaseTimeClutch*deltaTime)) / accelerationClutch;\n\n\t}\n\n\tif (input.isAlphabeticKeyDown(mouseLockKey)) {\n\n\t\tSleepEx(250, !(input.isAlphabeticKeyDown(mouseLockKey)));\n\n\t\tif (_isCursorLocked == false) {\n\n\t\t\t_isCursorLocked = true;\n\n\t\t}\n\n\t\telse {\n\n\t\t\t_isCursorLocked = false;\n\n\t\t}\n\n\t}\n\n\tif (input.isAlphabeticKeyDown(mouseCenterKey)) {\n\n\t\tSleepEx(250, !(input.isAlphabeticKeyDown(mouseCenterKey)));\n\n\t\taxisX = (32766 / 2);\n\n\t}\n\n\tif (useWheelAsShifter == 0) {\n\n\t\tif (input.isAlphabeticKeyDown(gearShiftUpKey)) {\n\n\t\t\tisButton1Clicked = true;\n\n\t\t}\n", "file_path": "MouseToVJoy/MouseToVJoy.cpp", "rank": 39, "score": 2.04535175921715 }, { "content": "\tcase EFF_STOP:\n\n\t\tStr = \"Effect Stop\";\n\n\t\tbreak;\n\n\tdefault:\n\n\t\tstat = FALSE;\n\n\t\tbreak;\n\n\t}\n\n\n\n\tif (stat)\n\n\t\t_tcscpy_s(outStr, 100, Str);\n\n\n\n\treturn stat;\n\n}\n\n\n\n// Polar values (0x00-0xFF) to Degrees (0-360)\n\nint ForceFeedBack::polar2Deg(BYTE polar)\n\n{\n\n\treturn ((UINT)polar * 360) / 255;\n\n}\n\n\n", "file_path": "MouseToVJoy/forceFeedBack.cpp", "rank": 40, "score": 2.033345851974702 }, { "content": "\t{\n\n\tcase WM_CREATE:\n\n\t\t//Creating new raw input devices\n\n\t\t\tRAWINPUTDEVICE m_Rid[2];\n\n\t\t\t//Keyboard\n\n\t\t\tm_Rid[0].usUsagePage = 1;\n\n\t\t\tm_Rid[0].usUsage = 6;\n\n\t\t\tm_Rid[0].dwFlags = RIDEV_INPUTSINK;\n\n\t\t\tm_Rid[0].hwndTarget = hwnd;\n\n\t\t\t//Mouse\n\n\t\t\tm_Rid[1].usUsagePage = 1;\n\n\t\t\tm_Rid[1].usUsage = 2;\n\n\t\t\tm_Rid[1].dwFlags = RIDEV_INPUTSINK;\n\n\t\t\tm_Rid[1].hwndTarget = hwnd;\n\n\t\t\tRegisterRawInputDevices(m_Rid, 2, sizeof(RAWINPUTDEVICE));\n\n\n\n\t\tbreak;\n\n\tcase WM_INPUT:\n\n\t\t//When window recives input message get data for rinput device and run mouse logic function.\n\n\t\t\trInput.getData(lParam);\n", "file_path": "MouseToVJoy/main.cpp", "rank": 41, "score": 2.033186756062873 }, { "content": "\tif (!DriverMatch(&VerDll, &VerDrv))\n\n\t\tprintf(\"Failed\\r\\nvJoy Driver (version %04x) does not match\\\n\n vJoyInterface DLL (version %04x)\\n\", VerDrv, VerDll);\n\n\telse\n\n\t\tprintf(\"vJoyInterface DLL Version: %04x\\n\", VerDrv);\n\n\tprintf(\"OK - Driver and DLL match\\n\");\n\n\n\n}\n\n//Tests if UINT iInterface is existing.\n\nint VJoy::testVirtualDevices(UINT iInterface) {\n\n\t// Get the state of the requested device (iInterface)\n\n\t_status = GetVJDStatus(iInterface);\n\n\tswitch (_status)\n\n\t{\n\n\tcase VJD_STAT_OWN:\n\n\t\tprintf(\"vJoy Device %d is already owned by this feeder\\n\", iInterface);\n\n\t\tbreak;\n\n\tcase VJD_STAT_FREE:\n\n\t\tprintf(\"vJoy Device %d is free\\n\", iInterface);\n\n\t\tbreak;\n", "file_path": "MouseToVJoy/vJoy.cpp", "rank": 42, "score": 1.928666113448247 }, { "content": "\t\t// Can be called both after Stop() and before it. \n\n\t\t// (Start() must have been called to initiate time interval measurements).\n\n\t\tdouble elapsedMilliseconds() const noexcept;\n\n\n\n\n\n\t\t//\n\n\t\t// Ban copy\n\n\t\t//\n\n\tprivate:\n\n\t\tStopwatch(const Stopwatch&) = delete;\n\n\t\tStopwatch& operator=(const Stopwatch&) = delete;\n\n\n\n\n\n\t\t//\n\n\t\t// *** IMPLEMENTATION ***\n\n\t\t//\n\n\tprivate:\n\n\t\tbool _running; // is the timer running?\n\n\t\tlong long _start; // start tick count\n\n\t\tlong long _finish; // end tick count\n", "file_path": "MouseToVJoy/Stopwatch.h", "rank": 44, "score": 1.7858884006041 }, { "content": "#ifndef _INPUT_H\n\n#define _INPUT_H\n\n\n\n// This code was built based upon what I learned from an internet site called ToyMaker.\n\n// In my opinion, their site is a great source for most of the basics one needs to know \n\n// to get started in game programming. Mainpage: http://www.toymaker.info/\n\n\n\n// Yes this is for WINDOWS only.\n\n#include <Windows.h>\n\n\n\n// The follwoing enumerations are set to cover related key-ranges from\n\n// A-Z and left, up, right, down.\n\n// Source page: \n\n// http://msdn.microsoft.com/en-us/library/ms645540%28VS.85%29.aspx\n\n\n", "file_path": "MouseToVJoy/input.h", "rank": 45, "score": 1.4240194624252012 }, { "content": "#include \"vjoy.h\"\n\n//Tests if the driver version is equal to dll version.\n\nint VJoy::testDriver() {\n\n\tprintf(\"Mouse to vJoy Feeder\\n\");\n\n\tprintf(\"==================================\\n\");\n\n\tprintf(\"Author: R1per\\n\");\n\n\tprintf(\"Version: 1.7\\n\");\n\n\t// Get the driver attributes (Vendor ID, Product ID, Version Number)\n\n\tif (!vJoyEnabled())\n\n\t{\n\n\t\tprintf(\"Failed Getting vJoy attributes.\\n\");\n\n\t\treturn -2;\n\n\t}\n\n\telse\n\n\t{\n\n\t\tprintf(\"vJoy Version Number: %S\\n\", TEXT(GetvJoySerialNumberString()));\n\n\t};\n\n\t// Test interface DLL matches vJoy driver\n\n\t// Compare versions\n\n\tWORD VerDll, VerDrv;\n", "file_path": "MouseToVJoy/vJoy.cpp", "rank": 46, "score": 1.3961475041434044 }, { "content": "\tprintf(\"Mouse Lock key = %d \\n\", (int)fR.result(13));\n\n\tprintf(\"Mouse Center key = %d \\n\", (int)fR.result(14));\n\n\tprintf(\"Use Mouse = %d \\n\", (int)fR.result(15));\n\n\tprintf(\"Use Center Reduction = %d \\n\", (int)fR.result(16));\n\n\tprintf(\"Use Force Feedback = %d \\n\", (int)fR.result(21));\n\n\tprintf(\"Use Mouse Wheel As Shifter = %d \\n\", (int)fR.result(22));\n\n\tprintf(\"Acceleration Throttle = %.2f \\n\", fR.result(17));\n\n\tprintf(\"Acceleration Break = %.2f \\n\", fR.result(18));\n\n\tprintf(\"Acceleration Clutch = %.2f \\n\", fR.result(19));\n\n\tprintf(\"Center Multiplier = %.2f \\n\", fR.result(20));\n\n\tprintf(\"==================================\\n\");\n\n}\n\n//Code that is run every time program gets an message from enviroment(mouse movement, mouse click etc.), manages input logic and feeding device.\n\n//Update code is sleeping for 2 miliseconds to make is less cpu demanding\n\nvoid updateCode() {\n\n\tSleep(20);\n\n\tif (fFB.getFfbSize().getEffectType() == \"Constant\") {\n\n\t\tif (fFB.getFfbSize().getDirection() > 100) {\n\n\t\t\tffbStrength = (fFB.getFfbSize().getMagnitude())*(sw.elapsedMilliseconds()*0.001);\n\n\t\t}\t\t\n", "file_path": "MouseToVJoy/main.cpp", "rank": 47, "score": 0.9171439991248826 }, { "content": "## Configuration\n\n\n\nProgram can be configured through config.txt file, which have 21 different values, that can be modified through any text editor.\n\nFor easier tweaking use VjoyMonitor to visualize axis changes.\n\n\n\n### Sensitivity\n\n\n\nThe main sensitivity multiplier.\n\nRaw data from mouse is multiplied by this value and then added to Vjoy Axis. \n\n\n\nE.g. Sensitivity = 6.0\n\n\n\n### AttackTimeThrottle\n\n\n\nThrottle value when pressed.\n\nWhen throttle is pressed, every 2 ms value is added to Vjoy Axis. \n\nThe greater the steaper slope of attack.\n\n\n\nE.g. AttackTimeThrottle = 200\n\n\n\n### ReleaseTimeThrottle\n\n\n\nThrottle value when released.\n\nWhen throttle is released, every 2 ms value is subtracted from Vjoy Axis. \n\nThe greater the steaper slope of release.\n\n\n\nE.g. ReleaseTimeThrottle = 100\n\n\n\n### AttackTimeBreak\n\n\n\nBreak value when pressed.\n\nWhen break is pressed, every 2 ms value is added to Vjoy Axis. \n\nThe greater the steaper slope of attack.\n\n\n\nE.g. AttackTimeBreak = 200\n\n\n\n### ReleaseTimeBreak\n\n\n\nBreak value when released.\n\nWhen break is released, every 2 ms value is subtracted from Vjoy Axis. \n\nThe greater the steaper slope of release.\n\n\n\nE.g. ReleaseTimeBreak = 100\n\n\n\n### AttackTimeClutch\n\n\n\nClutch value when pressed.\n\nWhen clutch is pressed, every 2 ms value is added to Vjoy Axis. \n\nThe greater the steaper slope of attack.\n\n\n\nE.g. AttackTimeClutch = 200\n\n\n\n### ReleaseTimeClutch\n\n\n\nClutch value when released.\n\nWhen clutch is released, every 2 ms value is subtracted from Vjoy Axis. \n\nThe greater the steaper slope of release.\n\n\n\nE.g. ReleaseTimeClutch = 200\n\n\n\n### ThrottleKey\n\n\n\nKey responsible for throttle control. Works only when UseMouse is equal to 0.\n\nKey value can be anything from 0 to 165 in ASCII KEYCODES!\n\n\n\nE.g. ThrottleKey = 87 for \"W\"\n\n\n\n### BreakKey\n\n\n\nKey responsible for break control. Works only when UseMouse is equal to 0.\n\nKey value can be anything from 0 to 165 in ASCII KEYCODES!\n\n\n\nE.g. BreakKey = 69 for \"E\"\n\n\n", "file_path": "README.md", "rank": 48, "score": 0.5843878518636174 } ]
C++
include/bunsan/config/traits.hpp
sarum9in/bunsan_common
1d113259e2e53de025ba28bd9df485d75f437921
#pragma once #include <boost/unordered_map.hpp> #include <boost/unordered_set.hpp> #include <deque> #include <list> #include <map> #include <set> #include <string> #include <type_traits> #include <unordered_map> #include <unordered_set> #include <vector> namespace bunsan { namespace config { namespace traits { template <typename T> struct is_direct_assignable : std::integral_constant<bool, std::is_arithmetic<T>::value || std::is_enum<T>::value> {}; template <typename T> struct is_random_access_sequence : std::integral_constant<bool, false> {}; template <typename T> struct is_sequence : std::integral_constant<bool, false> {}; template <typename T> struct is_set : std::integral_constant<bool, false> {}; template <typename T> struct is_map : std::integral_constant<bool, false> {}; template <typename T> struct is_recursive : std::integral_constant<bool, !is_direct_assignable<T>::value && !is_random_access_sequence<T>::value && !is_sequence<T>::value && !is_set<T>::value && !is_map<T>::value> { }; template <typename Parent, typename Derived> struct type_key { static constexpr const char *call() { return nullptr; } }; template <typename T> struct serializer { template <typename Archive> static void load(T &obj, Archive &ar, const unsigned int version) { obj.serialize(ar, version); } template <typename Archive> static void save(const T &obj, Archive &ar, const unsigned int version) { const_cast<T &>(obj).serialize(ar, version); } }; } } } namespace bunsan { namespace config { namespace traits { template <typename Char, typename Traits, typename Alloc> struct is_direct_assignable<std::basic_string<Char, Traits, Alloc>> : std::integral_constant<bool, true> {}; template <typename Tp, typename Alloc> struct is_random_access_sequence<std::vector<Tp, Alloc>> : std::integral_constant<bool, true> {}; template <typename Tp, typename Alloc> struct is_sequence<std::list<Tp, Alloc>> : std::integral_constant<bool, true> { }; template <typename Tp, typename Alloc> struct is_sequence<std::deque<Tp, Alloc>> : std::integral_constant<bool, true> { }; template <typename Key, typename Compare, typename Alloc> struct is_set<std::set<Key, Compare, Alloc>> : std::integral_constant<bool, true> {}; template <typename Key, typename Compare, typename Alloc> struct is_set<std::multiset<Key, Compare, Alloc>> : std::integral_constant<bool, true> {}; template <typename Key, typename Tp, typename Compare, typename Alloc> struct is_map<std::map<Key, Tp, Compare, Alloc>> : std::integral_constant<bool, true> {}; template <typename Key, typename Tp, typename Compare, typename Alloc> struct is_map<std::multimap<Key, Tp, Compare, Alloc>> : std::integral_constant<bool, true> {}; template <typename Value, typename Hash, typename Pred, typename Alloc> struct is_set<std::unordered_set<Value, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; template <typename Value, typename Hash, typename Pred, typename Alloc> struct is_set<std::unordered_multiset<Value, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; template <typename Key, typename Tp, typename Hash, typename Pred, typename Alloc> struct is_map<std::unordered_map<Key, Tp, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; template <typename Key, typename Tp, typename Hash, typename Pred, typename Alloc> struct is_map<std::unordered_multimap<Key, Tp, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; template <typename Value, typename Hash, typename Pred, typename Alloc> struct is_set<boost::unordered_set<Value, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; template <typename Value, typename Hash, typename Pred, typename Alloc> struct is_set<boost::unordered_multiset<Value, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; template <typename Key, typename Tp, typename Hash, typename Pred, typename Alloc> struct is_map<boost::unordered_map<Key, Tp, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; template <typename Key, typename Tp, typename Hash, typename Pred, typename Alloc> struct is_map<boost::unordered_multimap<Key, Tp, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; } } } #define BUNSAN_CONFIG_EXPORT(PARENT, DERIVED, FIELD) \ namespace bunsan { \ namespace config { \ namespace traits { \ template <> \ struct type_key<PARENT, DERIVED> { \ static constexpr const char *call() { return FIELD; } \ }; \ } \ } \ }
#pragma once #include <boost/unordered_map.hpp> #include <boost/unordered_set.hpp> #include <deque> #include <list> #include <map> #include <set> #include <string> #include <type_traits> #include <unordered_map> #include <unordered_set> #include <vector> namespace bunsan { namespace config { namespace traits { template <typename T> struct is_direct_assignable : std::integral_constant<bool, std::is_arithmetic<T>::value || std::is_enum<T>::value> {}; template <typename T> struct is_random_access_sequence : std::integral_constant<bool, false> {}; template <typename T> struct is_sequence : std::integral_constant<bool, false> {}; template <typename T> struct is_set : std::integral_constant<bool, false> {}; template <typename T> struct is_map : std::integral_constant<bool, false> {}; template <typename T> struct is_recursive : std::integral_constant<bool, !is_direct_assignable<T>::value && !is_random_access_sequence<T>::value && !is_sequence<T>::value && !is_set<T>::value && !is_map<T>::value> { }; template <typename Parent, typename Derived> struct type_key { static constexpr const char *call() { return nullptr; } }; template <typename T> struct serializer { template <typename Archive> static void load(T &obj, Archive &ar, const unsigned int version) { obj.serialize(ar, version); } template <typename Archive> static void save(const T &obj, Archive &ar, const unsigned int version) { const_cast<T &>(obj).serialize(ar, version); } }; } } } namespace bunsan { namespace config { namespace traits { template <typename Char, typename Traits, typename Alloc> struct is_direct_assignable<std::basic_string<Char, Traits, Alloc>> : std::integral_constant<bool, true> {}; template <typename Tp, typename Alloc> struct is_random_access_sequence<std::vector<Tp, Alloc>> : std::integral_constant<bool, true> {}; template <typename Tp, typename Alloc> struct is_sequence<std::list<Tp, Alloc>> : std::integral_constant<bool, true> { }; template <typename Tp, typename Alloc> struct is_sequence<std::deque<Tp, Alloc>> : std::integral_constant<bool, true> { }; template <typename Key, typename Compare, typename Alloc> struct is_set<std::set<Key, Compare, Alloc>> : std::integral_constant<bool, true> {}; template <typename Key, typenam
: std::integral_constant<bool, true> {}; template <typename Key, typename Tp, typename Compare, typename Alloc> struct is_map<std::multimap<Key, Tp, Compare, Alloc>> : std::integral_constant<bool, true> {}; template <typename Value, typename Hash, typename Pred, typename Alloc> struct is_set<std::unordered_set<Value, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; template <typename Value, typename Hash, typename Pred, typename Alloc> struct is_set<std::unordered_multiset<Value, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; template <typename Key, typename Tp, typename Hash, typename Pred, typename Alloc> struct is_map<std::unordered_map<Key, Tp, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; template <typename Key, typename Tp, typename Hash, typename Pred, typename Alloc> struct is_map<std::unordered_multimap<Key, Tp, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; template <typename Value, typename Hash, typename Pred, typename Alloc> struct is_set<boost::unordered_set<Value, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; template <typename Value, typename Hash, typename Pred, typename Alloc> struct is_set<boost::unordered_multiset<Value, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; template <typename Key, typename Tp, typename Hash, typename Pred, typename Alloc> struct is_map<boost::unordered_map<Key, Tp, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; template <typename Key, typename Tp, typename Hash, typename Pred, typename Alloc> struct is_map<boost::unordered_multimap<Key, Tp, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; } } } #define BUNSAN_CONFIG_EXPORT(PARENT, DERIVED, FIELD) \ namespace bunsan { \ namespace config { \ namespace traits { \ template <> \ struct type_key<PARENT, DERIVED> { \ static constexpr const char *call() { return FIELD; } \ }; \ } \ } \ }
e Compare, typename Alloc> struct is_set<std::multiset<Key, Compare, Alloc>> : std::integral_constant<bool, true> {}; template <typename Key, typename Tp, typename Compare, typename Alloc> struct is_map<std::map<Key, Tp, Compare, Alloc>>
random
[ { "content": "struct load_variant;\n\n\n\n/// Implementation.\n\ntemplate <typename Arg, typename... Args>\n", "file_path": "include/bunsan/config/input_archive.hpp", "rank": 22, "score": 164930.03404454674 }, { "content": "struct load_variant<> {\n\n template <typename Archive, typename Variant>\n\n static void load(const std::string &name, Archive &, Variant &) {\n\n BOOST_THROW_EXCEPTION(\n\n variant_load_invalid_key_error()\n\n << variant_load_key_error::key(name)\n\n << error::message(\"There is no types left for variant.\"));\n\n }\n\n};\n\n} // namespace input_archive_detail\n\n\n\ntemplate <typename Ptree>\n\ntemplate <BOOST_VARIANT_ENUM_PARAMS(typename T)>\n\nvoid input_archive<Ptree>::load(\n\n boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> &obj) {\n\n if (m_ptree->empty()) BOOST_THROW_EXCEPTION(variant_load_no_key_error());\n\n if (m_ptree->size() > 1)\n\n BOOST_THROW_EXCEPTION(variant_load_multiple_keys_error());\n\n const std::string type_name = m_ptree->front().first;\n\n input_archive<Ptree> ar(m_ptree->front().second);\n\n input_archive_detail::load_variant<BOOST_VARIANT_ENUM_PARAMS(T)>::load(\n\n type_name, ar, obj);\n\n}\n\n\n\n} // namespace config\n\n} // namespace bunsan\n", "file_path": "include/bunsan/config/input_archive.hpp", "rank": 23, "score": 164930.03404454674 }, { "content": "class save_visitor : public boost::static_visitor<void> {\n\n public:\n\n explicit save_visitor(Archive &archive) : m_archive(&archive) {}\n\n save_visitor(const save_visitor<Archive, Variant> &) = default;\n\n save_visitor &operator=(const save_visitor<Archive, Variant> &) = default;\n\n\n\n template <typename T>\n\n void operator()(const T &obj) const {\n\n using type_key = traits::type_key<Variant, T>;\n\n static_assert(type_key::call(), \"Undefined type key.\");\n\n *m_archive &boost::serialization::make_nvp(type_key::call(), obj);\n\n }\n\n\n\n private:\n\n Archive *m_archive;\n\n};\n\n} // namespace output_archive_detail\n\n\n\ntemplate <typename Ptree>\n\ntemplate <BOOST_VARIANT_ENUM_PARAMS(typename T)>\n", "file_path": "include/bunsan/config/output_archive.hpp", "rank": 24, "score": 163933.08389648818 }, { "content": "struct parent {};\n", "file_path": "tests/config.cpp", "rank": 25, "score": 160072.58279337082 }, { "content": "struct error : virtual bunsan::error {};\n\n\n", "file_path": "include/bunsan/config/error.hpp", "rank": 26, "score": 156320.69307914143 }, { "content": "struct load_variant<Arg, Args...> {\n\n /*!\n\n * \\brief Key is unknown.\n\n *\n\n * \\note This overload is needed\n\n * for boost::variant implementation\n\n * that uses boost::detail::variant::void_.\n\n */\n\n template <typename Archive, typename Variant>\n\n static typename std::enable_if<!traits::type_key<Variant, Arg>::call(),\n\n void>::type\n\n load(const std::string &name, Archive &, Variant &) {\n\n BOOST_THROW_EXCEPTION(variant_load_invalid_key_error()\n\n << variant_load_key_error::key(name)\n\n << error::message(\"Unknown type.\"));\n\n }\n\n\n\n /// Check Arg's key.\n\n template <typename Archive, typename Variant>\n\n static typename std::enable_if<\n", "file_path": "include/bunsan/config/input_archive.hpp", "rank": 27, "score": 150232.1538381922 }, { "content": "struct output_archive_error : virtual error {};\n\n\n", "file_path": "include/bunsan/config/error.hpp", "rank": 28, "score": 150232.1538381922 }, { "content": "struct input_archive_error : virtual error {};\n\n\n", "file_path": "include/bunsan/config/error.hpp", "rank": 29, "score": 150232.1538381922 }, { "content": "class stacktrace : public std::vector<void *> {\n\n public:\n\n stacktrace() = default;\n\n stacktrace(const stacktrace &) = default;\n\n stacktrace &operator=(const stacktrace &) = default;\n\n stacktrace(stacktrace &&) = default;\n\n stacktrace &operator=(stacktrace &&) = default;\n\n\n\n public:\n\n /*!\n\n * \\brief Get stack trace.\n\n *\n\n * \\param skip skip first entries,\n\n * e.g. 1 means caller will not be included into trace\n\n * \\param max_size maximum stack trace size\n\n */\n\n static stacktrace get(const std::size_t skip = 0,\n\n const std::size_t max_size = 1024);\n\n\n\n private:\n\n friend std::ostream &operator<<(std::ostream &out, const stacktrace &trace);\n\n};\n\n\n\nstd::ostream &operator<<(std::ostream &out, const stacktrace &trace);\n\n\n\n} // namespace runtime\n\n} // namespace bunsan\n", "file_path": "include/bunsan/runtime/stacktrace.hpp", "rank": 30, "score": 145885.05682302656 }, { "content": "struct variant_load_no_key_error : virtual variant_load_key_error {};\n\n\n", "file_path": "include/bunsan/config/error.hpp", "rank": 31, "score": 144153.315360539 }, { "content": "struct variant_load_error : virtual input_archive_error {};\n\n\n", "file_path": "include/bunsan/config/error.hpp", "rank": 33, "score": 141370.31607332706 }, { "content": "struct variant_load_invalid_key_error : virtual variant_load_key_error {};\n\n\n", "file_path": "include/bunsan/config/error.hpp", "rank": 34, "score": 140622.7613723176 }, { "content": "struct variant_load_multiple_keys_error : virtual variant_load_key_error {};\n\n\n\n} // namespace config\n\n} // namespace bunsan\n", "file_path": "include/bunsan/config/error.hpp", "rank": 35, "score": 140622.7613723176 }, { "content": "struct variant_load_key_error : virtual variant_load_error {\n\n using key = boost::error_info<struct tag_key, std::string>;\n\n};\n\n\n", "file_path": "include/bunsan/config/error.hpp", "rank": 36, "score": 137506.3112390057 }, { "content": "struct derived {};\n\n\n\nBUNSAN_CONFIG_EXPORT(::parent, ::derived, \"hello, world!\")\n\n\n\nusing variant = boost::variant<std::string, int>;\n\n\n\nBUNSAN_CONFIG_EXPORT(variant, std::string, \"string\")\n\nBUNSAN_CONFIG_EXPORT(variant, int, \"int\")\n\n\n\nBOOST_AUTO_TEST_SUITE(config)\n\n\n\nBOOST_AUTO_TEST_CASE(traits) {\n\n enum my_enum {};\n\n static_assert(\n\n bunsan::config::traits::type_key<struct a, struct b>::call() == nullptr,\n\n \"not defined\");\n\n static_assert(bunsan::config::traits::type_key<::parent, ::derived>::call(),\n\n \"defined\");\n\n static_assert(\n\n bunsan::config::traits::is_direct_assignable<std::string>::value,\n\n \"direct\");\n\n static_assert(bunsan::config::traits::is_direct_assignable<int>::value,\n\n \"direct\");\n\n static_assert(bunsan::config::traits::is_direct_assignable<my_enum>::value,\n\n \"direct\");\n\n BOOST_CHECK_EQUAL(\n\n (bunsan::config::traits::type_key<::parent, ::derived>::call()),\n\n \"hello, world!\");\n\n}\n\n\n", "file_path": "tests/config.cpp", "rank": 38, "score": 130190.39654678907 }, { "content": "struct error : virtual bunsan::error {\n\n using path = boost::error_info<struct tag_path, boost::filesystem::path>;\n\n\n\n using source_path =\n\n boost::error_info<struct tag_source_path, boost::filesystem::path>;\n\n\n\n using destination_path =\n\n boost::error_info<struct tag_destination_path, boost::filesystem::path>;\n\n\n\n using openmode =\n\n boost::error_info<struct tag_openmode, std::ios_base::openmode>;\n\n};\n\n\n", "file_path": "include/bunsan/filesystem/error.hpp", "rank": 39, "score": 128101.17678343631 }, { "content": " typename Pred, typename Alloc>\n\nvoid serialize(Archive &ar, std::unordered_map<Key, Tp, Hash, Pred, Alloc> &map,\n\n const unsigned int version) {\n\n split_free(ar, map, version);\n\n}\n\n\n\ntemplate <typename Archive, typename Key, typename Tp, typename Hash,\n\n typename Pred, typename Alloc>\n\nvoid save(Archive &ar,\n\n const std::unordered_map<Key, Tp, Hash, Pred, Alloc> &map,\n\n const unsigned int /*version*/) {\n\n stl::save_collection(ar, map);\n\n}\n\n\n\ntemplate <typename Archive, typename Key, typename Tp, typename Hash,\n\n typename Pred, typename Alloc>\n\nvoid load(Archive &ar, std::unordered_map<Key, Tp, Hash, Pred, Alloc> &map,\n\n const unsigned int /*version*/) {\n\n stl::load_collection<\n\n Archive, std::unordered_map<Key, Tp, Hash, Pred, Alloc>,\n", "file_path": "include/bunsan/serialization/unordered_map.hpp", "rank": 41, "score": 121378.5518084158 }, { "content": " typename Alloc>\n\nvoid serialize(Archive &ar, std::unordered_set<Value, Hash, Pred, Alloc> &set,\n\n const unsigned int version) {\n\n split_free(ar, set, version);\n\n}\n\n\n\ntemplate <typename Archive, typename Value, typename Hash, typename Pred,\n\n typename Alloc>\n\nvoid save(Archive &ar, const std::unordered_set<Value, Hash, Pred, Alloc> &set,\n\n const unsigned int /*version*/) {\n\n stl::save_collection(ar, set);\n\n}\n\n\n\ntemplate <typename Archive, typename Value, typename Hash, typename Pred,\n\n typename Alloc>\n\nvoid load(Archive &ar, std::unordered_set<Value, Hash, Pred, Alloc> &set,\n\n const unsigned int /*version*/) {\n\n stl::load_collection<\n\n Archive, std::unordered_set<Value, Hash, Pred, Alloc>,\n\n stl::archive_input_set<Archive,\n", "file_path": "include/bunsan/serialization/unordered_set.hpp", "rank": 42, "score": 121371.28656315904 }, { "content": "#pragma once\n\n\n\n#include <boost/version.hpp>\n\n\n\n#if BOOST_VERSION >= 105900\n\n\n\n#include <boost/serialization/unordered_map.hpp>\n\n\n\n#else\n\n\n\n#include <boost/serialization/collections_save_imp.hpp>\n\n#include <boost/serialization/collections_load_imp.hpp>\n\n#include <boost/serialization/split_free.hpp>\n\n\n\n#include <unordered_map>\n\n\n\nnamespace boost {\n\nnamespace serialization {\n\n\n\ntemplate <typename Archive, typename Key, typename Tp, typename Hash,\n", "file_path": "include/bunsan/serialization/unordered_map.hpp", "rank": 43, "score": 121367.49726656142 }, { "content": " stl::archive_input_map<Archive,\n\n std::unordered_map<Key, Tp, Hash, Pred, Alloc>>,\n\n stl::no_reserve_imp<std::unordered_map<Key, Tp, Hash, Pred, Alloc>>>(ar,\n\n map);\n\n}\n\n\n\n} // namespace serialization\n\n} // namespace boost\n\n\n\n#endif\n", "file_path": "include/bunsan/serialization/unordered_map.hpp", "rank": 44, "score": 121366.11109785117 }, { "content": "#pragma once\n\n\n\n#include <boost/version.hpp>\n\n\n\n#if BOOST_VERSION >= 105900\n\n\n\n#include <boost/serialization/unordered_set.hpp>\n\n\n\n#else\n\n\n\n#include <boost/serialization/collections_save_imp.hpp>\n\n#include <boost/serialization/collections_load_imp.hpp>\n\n#include <boost/serialization/split_free.hpp>\n\n\n\n#include <unordered_set>\n\n\n\nnamespace boost {\n\nnamespace serialization {\n\n\n\ntemplate <typename Archive, typename Value, typename Hash, typename Pred,\n", "file_path": "include/bunsan/serialization/unordered_set.hpp", "rank": 45, "score": 121362.52236402119 }, { "content": " std::unordered_set<Value, Hash, Pred, Alloc>>,\n\n stl::no_reserve_imp<std::unordered_set<Value, Hash, Pred, Alloc>>>(ar,\n\n set);\n\n}\n\n\n\n} // namespace serialization\n\n} // namespace boost\n\n\n\n#endif\n", "file_path": "include/bunsan/serialization/unordered_set.hpp", "rank": 46, "score": 121355.17246799456 }, { "content": "class output_archive {\n\n public:\n\n using is_loading = std::integral_constant<bool, false>;\n\n using is_saving = std::integral_constant<bool, true>;\n\n\n\n constexpr unsigned int get_library_version() { return 0; }\n\n\n\n public:\n\n explicit output_archive(Ptree &ptree) : m_ptree(&ptree) {}\n\n\n\n template <typename T>\n\n output_archive &operator&(const T &obj) {\n\n return *this << obj;\n\n }\n\n\n\n template <typename T>\n\n output_archive &operator<<(const T &obj) {\n\n save(obj);\n\n return *this;\n\n }\n", "file_path": "include/bunsan/config/output_archive.hpp", "rank": 47, "score": 120941.7375040482 }, { "content": " static_cast<bool>(traits::type_key<Variant, Arg>::call()), void>::type\n\n load(const std::string &name, Archive &ar, Variant &obj) {\n\n if (name == traits::type_key<Variant, Arg>::call()) {\n\n Arg arg;\n\n ar >> arg;\n\n obj = arg;\n\n } else {\n\n load_variant<Args...>::load(name, ar, obj);\n\n }\n\n }\n\n};\n\n\n\n/// There is no types left.\n\ntemplate <>\n", "file_path": "include/bunsan/config/input_archive.hpp", "rank": 48, "score": 120427.15397408692 }, { "content": "#pragma once\n\n\n\n#include <bunsan/config/error.hpp>\n\n#include <bunsan/config/traits.hpp>\n\n\n\n#include <boost/filesystem/path.hpp>\n\n#include <boost/lexical_cast.hpp>\n\n#include <boost/noncopyable.hpp>\n\n#include <boost/optional.hpp>\n\n#include <boost/serialization/serialization.hpp>\n\n#include <boost/serialization/version.hpp>\n\n#include <boost/serialization/nvp.hpp>\n\n#include <boost/variant.hpp>\n\n#include <boost/variant/static_visitor.hpp>\n\n\n\n#include <chrono>\n\n#include <memory>\n\n\n\nnamespace bunsan {\n\nnamespace config {\n\n\n\ntemplate <typename Ptree>\n", "file_path": "include/bunsan/config/output_archive.hpp", "rank": 49, "score": 120423.42273646375 }, { "content": "#pragma once\n\n\n\n#include <bunsan/config/error.hpp>\n\n#include <bunsan/config/traits.hpp>\n\n\n\n#include <boost/filesystem/path.hpp>\n\n#include <boost/lexical_cast.hpp>\n\n#include <boost/noncopyable.hpp>\n\n#include <boost/optional.hpp>\n\n#include <boost/serialization/serialization.hpp>\n\n#include <boost/serialization/version.hpp>\n\n#include <boost/serialization/nvp.hpp>\n\n#include <boost/variant.hpp>\n\n\n\n#include <chrono>\n\n#include <memory>\n\n\n\nnamespace bunsan {\n\nnamespace config {\n\n\n\ntemplate <typename Ptree>\n", "file_path": "include/bunsan/config/input_archive.hpp", "rank": 50, "score": 120422.04398111202 }, { "content": " /// For maps.\n\n template <typename T>\n\n typename std::enable_if<traits::is_map<T>::value, void>::type load(T &obj) {\n\n obj.clear();\n\n for (const typename Ptree::value_type &key_value : *m_ptree) {\n\n const typename T::key_type key =\n\n boost::lexical_cast<typename T::key_type>(key_value.first);\n\n typename T::mapped_type value;\n\n load_from_ptree(value, key_value.second);\n\n // FIXME should be replaced by emplace in the future\n\n obj.insert(typename T::value_type(key, value));\n\n }\n\n }\n\n\n\n /// For boost::variant.\n\n template <BOOST_VARIANT_ENUM_PARAMS(typename T)>\n\n void load(boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> &obj);\n\n\n\n private:\n\n const Ptree *const m_ptree;\n\n};\n\n\n\nnamespace input_archive_detail {\n\n/// Base declaration.\n\ntemplate <typename... Args>\n", "file_path": "include/bunsan/config/input_archive.hpp", "rank": 51, "score": 120416.68527379209 }, { "content": " oa << obj;\n\n }\n\n\n\n private:\n\n /// For complex types.\n\n template <typename T>\n\n typename std::enable_if<traits::is_recursive<T>::value, void>::type save(\n\n const T &obj) {\n\n const_cast<T &>(obj)\n\n .serialize(*this, boost::serialization::version<T>::value);\n\n // FIXME boost::serialization::serialize_adl(*this, obj,\n\n // boost::serialization::version<T>::value);\n\n }\n\n\n\n /// For primitive types.\n\n template <typename T>\n\n typename std::enable_if<traits::is_direct_assignable<T>::value, void>::type\n\n save(const T &obj) {\n\n m_ptree->put_value(obj);\n\n }\n", "file_path": "include/bunsan/config/output_archive.hpp", "rank": 52, "score": 120416.15190744148 }, { "content": "\n\n /// For Ptree.\n\n void save(const Ptree &obj) { *m_ptree = obj; }\n\n\n\n /// For boost::filesystem::path.\n\n void save(const boost::filesystem::path &obj) { save(obj.string()); }\n\n\n\n /// For std::chrono::duration.\n\n template <typename Rep, typename Period>\n\n void save(const std::chrono::duration<Rep, Period> &obj) {\n\n save(obj.count());\n\n }\n\n\n\n /// For sequences except maps.\n\n template <typename T>\n\n typename std::enable_if<traits::is_random_access_sequence<T>::value ||\n\n traits::is_sequence<T>::value ||\n\n traits::is_set<T>::value,\n\n void>::type\n\n save(const T &obj) {\n", "file_path": "include/bunsan/config/output_archive.hpp", "rank": 53, "score": 120415.93989908892 }, { "content": " template <typename T>\n\n void reset(T &value) {\n\n value = T();\n\n }\n\n\n\n /// For complex types.\n\n template <typename T>\n\n typename std::enable_if<traits::is_recursive<T>::value, void>::type load(\n\n T &obj) {\n\n traits::serializer<T>::load(obj, *this,\n\n boost::serialization::version<T>::value);\n\n }\n\n\n\n /*!\n\n * \\brief Helper for integral types to load them from std::istream\n\n * instances using oct and hex prefixes.\n\n */\n\n template <typename T>\n", "file_path": "include/bunsan/config/input_archive.hpp", "rank": 54, "score": 120414.38315863324 }, { "content": " T &obj) {\n\n obj.clear();\n\n for (const typename Ptree::value_type &key_value : *m_ptree) {\n\n typename T::value_type value;\n\n load_from_ptree(value, key_value.second);\n\n obj.insert(value);\n\n }\n\n }\n\n\n\n /// For sets.\n\n template <typename T>\n\n typename std::enable_if<traits::is_set<T>::value, void>::type load(T &obj) {\n\n obj.clear();\n\n for (const typename Ptree::value_type &key_value : *m_ptree) {\n\n typename T::value_type value;\n\n load_from_ptree(value, key_value.second);\n\n obj.insert(value);\n\n }\n\n }\n\n\n", "file_path": "include/bunsan/config/input_archive.hpp", "rank": 55, "score": 120412.52782416502 }, { "content": "void output_archive<Ptree>::save(\n\n const boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> &obj) {\n\n using visitor_type = boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)>;\n\n using save_visitor =\n\n output_archive_detail::save_visitor<output_archive<Ptree>, visitor_type>;\n\n save_visitor visitor(*this);\n\n boost::apply_visitor(visitor, obj);\n\n}\n\n\n\n} // namespace config\n\n} // namespace bunsan\n", "file_path": "include/bunsan/config/output_archive.hpp", "rank": 56, "score": 120411.9339566969 }, { "content": "\n\n template <typename T>\n\n output_archive &operator<<(const boost::serialization::nvp<T> &nvp) {\n\n Ptree ptree;\n\n save_to_ptree(nvp.value(), ptree);\n\n m_ptree->put_child(nvp.name(), ptree);\n\n return *this;\n\n }\n\n\n\n template <typename T>\n\n output_archive &operator<<(\n\n const boost::serialization::nvp<boost::optional<T>> &nvp) {\n\n if (nvp.value())\n\n *this << boost::serialization::make_nvp(nvp.name(), nvp.value().get());\n\n return *this;\n\n }\n\n\n\n template <typename T>\n\n static void save_to_ptree(const T &obj, Ptree &ptree) {\n\n output_archive<Ptree> oa(ptree);\n", "file_path": "include/bunsan/config/output_archive.hpp", "rank": 57, "score": 120411.85006144326 }, { "content": "\n\n template <typename T>\n\n input_archive &operator>>(const boost::serialization::nvp<T> &nvp) {\n\n boost::optional<const Ptree &> ptree =\n\n m_ptree->get_child_optional(nvp.name());\n\n if (ptree) {\n\n load_from_ptree(nvp.value(), ptree.get());\n\n } else {\n\n reset(nvp.value());\n\n }\n\n return *this;\n\n }\n\n\n\n template <typename T>\n\n static void load_from_ptree(T &obj, const Ptree &ptree) {\n\n input_archive<Ptree> ia(ptree);\n\n ia >> obj;\n\n }\n\n\n\n private:\n", "file_path": "include/bunsan/config/input_archive.hpp", "rank": 58, "score": 120411.84715875715 }, { "content": "\n\n /// For boost::variant.\n\n template <BOOST_VARIANT_ENUM_PARAMS(typename T)>\n\n void save(const boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> &obj);\n\n\n\n private:\n\n Ptree *const m_ptree;\n\n};\n\n\n\nnamespace output_archive_detail {\n\ntemplate <typename Archive, typename Variant>\n", "file_path": "include/bunsan/config/output_archive.hpp", "rank": 59, "score": 120410.51384518719 }, { "content": " m_ptree->clear();\n\n for (const auto &value : obj) {\n\n typename Ptree::value_type ptree_value;\n\n save_to_ptree(value, ptree_value.second);\n\n m_ptree->push_back(ptree_value);\n\n }\n\n }\n\n\n\n /// For maps.\n\n template <typename T>\n\n typename std::enable_if<traits::is_map<T>::value, void>::type save(\n\n const T &obj) {\n\n m_ptree->clear();\n\n for (const auto &value : obj) {\n\n typename Ptree::value_type ptree_value = {\n\n boost::lexical_cast<std::string>(value.first), Ptree()};\n\n save_to_ptree(value.second, ptree_value.second);\n\n m_ptree->push_back(ptree_value);\n\n }\n\n }\n", "file_path": "include/bunsan/config/output_archive.hpp", "rank": 60, "score": 120409.32980524606 }, { "content": " }\n\n\n\n /// For boost::optional.\n\n template <typename T>\n\n void load(boost::optional<T> &obj) {\n\n T value;\n\n load(value);\n\n obj = value;\n\n }\n\n\n\n /// For Ptree.\n\n void load(Ptree &obj) { obj = *m_ptree; }\n\n\n\n /// For boost::filesystem::path.\n\n void load(boost::filesystem::path &obj) {\n\n obj = m_ptree->template get_value<std::string>();\n\n }\n\n\n\n /// For std::chrono::duration.\n\n template <typename Rep, typename Period>\n", "file_path": "include/bunsan/config/input_archive.hpp", "rank": 61, "score": 120409.04021141201 }, { "content": " void load(std::chrono::duration<Rep, Period> &obj) {\n\n obj =\n\n std::chrono::duration<Rep, Period>(m_ptree->template get_value<Rep>());\n\n }\n\n\n\n /// For random access sequences.\n\n template <typename T>\n\n typename std::enable_if<traits::is_random_access_sequence<T>::value,\n\n void>::type\n\n load(T &obj) {\n\n obj.resize(m_ptree->size());\n\n auto obj_iter = obj.begin();\n\n auto ptree_iter = m_ptree->begin();\n\n for (; obj_iter != obj.end(); ++obj_iter, ++ptree_iter)\n\n load_from_ptree(*obj_iter, ptree_iter->second);\n\n }\n\n\n\n /// For sequences.\n\n template <typename T>\n\n typename std::enable_if<traits::is_sequence<T>::value, void>::type load(\n", "file_path": "include/bunsan/config/input_archive.hpp", "rank": 62, "score": 120408.68197061917 }, { "content": "\n\n /// For integral primitive types.\n\n template <typename T>\n\n typename std::enable_if<std::is_integral<T>::value, void>::type\n\n load_primitive(T &obj) {\n\n obj = m_ptree->template get_value<integral_wrapper<T>>();\n\n }\n\n\n\n /// For non-integral primitive types.\n\n template <typename T>\n\n typename std::enable_if<!std::is_integral<T>::value, void>::type\n\n load_primitive(T &obj) {\n\n obj = m_ptree->template get_value<T>();\n\n }\n\n\n\n /// For primitive types.\n\n template <typename T>\n\n typename std::enable_if<traits::is_direct_assignable<T>::value, void>::type\n\n load(T &obj) {\n\n load_primitive(obj);\n", "file_path": "include/bunsan/config/input_archive.hpp", "rank": 63, "score": 120408.45358156762 }, { "content": "struct system_error : bunsan::system_error, virtual error {\n\n using bunsan::system_error::system_error;\n\n};\n\n\n", "file_path": "include/bunsan/filesystem/error.hpp", "rank": 64, "score": 117134.65711940193 }, { "content": "/// String representation is invalid.\n\nstruct invalid_string_representation_error : virtual invalid_value_error {\n\n using string_value = boost::error_info<struct tag_string_value, std::string>;\n\n};\n\n\n", "file_path": "include/bunsan/stream_enum.hpp", "rank": 65, "score": 113127.07750886629 }, { "content": "struct global {\n\n static logger<severity> &get();\n\n static void remove_default_sink();\n\n};\n\n\n\n} // namespace trivial\n\n} // namespace log\n\n} // namespace bunsan\n\n\n\n#define BUNSAN_LOG_TRIVIAL(SEV) \\\n\n BOOST_LOG_STREAM_WITH_PARAMS( \\\n\n ::bunsan::log::trivial::global::get(), \\\n\n (::boost::log::keywords::severity = ::bunsan::log::severity::SEV)( \\\n\n ::bunsan::log::keywords::file = \\\n\n __FILE__)(::bunsan::log::keywords::line = __LINE__)( \\\n\n ::bunsan::log::keywords::function = __func__)( \\\n\n ::bunsan::log::keywords::pretty_function = BOOST_CURRENT_FUNCTION))\n\n\n\n#define BUNSAN_LOG_TRACE BUNSAN_LOG_TRIVIAL(trace)\n\n#define BUNSAN_LOG_DEBUG BUNSAN_LOG_TRIVIAL(debug)\n\n#define BUNSAN_LOG_INFO BUNSAN_LOG_TRIVIAL(info)\n\n#define BUNSAN_LOG_WARNING BUNSAN_LOG_TRIVIAL(warning)\n\n#define BUNSAN_LOG_ERROR BUNSAN_LOG_TRIVIAL(error)\n\n#define BUNSAN_LOG_FATAL BUNSAN_LOG_TRIVIAL(fatal)\n", "file_path": "include/bunsan/log/trivial.hpp", "rank": 66, "score": 112683.10236393537 }, { "content": "struct ptr_maker {};\n\n\n\ntemplate <typename T>\n", "file_path": "include/bunsan/memory.hpp", "rank": 67, "score": 112683.10236393537 }, { "content": "struct flusher {\n\n template <typename T>\n\n static void call(T &obj) {\n\n obj.flush();\n\n }\n\n};\n\n\n\ntemplate <>\n", "file_path": "include/bunsan/filesystem/fstream.hpp", "rank": 68, "score": 112683.10236393537 }, { "content": " class integral_wrapper {\n\n public:\n\n constexpr integral_wrapper() = default;\n\n constexpr integral_wrapper(const T value) : value_(value) {}\n\n constexpr operator T() const { return value_; }\n\n\n\n public:\n\n template <typename CharT, typename Traits>\n\n friend std::basic_istream<CharT, Traits> &operator>>(\n\n std::basic_istream<CharT, Traits> &in, integral_wrapper &integral) {\n\n std::ios_base::fmtflags flags = in.flags();\n\n in.unsetf(std::ios_base::basefield);\n\n in >> integral.value_;\n\n in.setf(flags);\n\n return in;\n\n }\n\n\n\n private:\n\n T value_ = 0;\n\n };\n", "file_path": "include/bunsan/config/input_archive.hpp", "rank": 69, "score": 110863.15480904275 }, { "content": "struct error_manip<struct tag_enable_nested_current> {\n\n void operator()(const boost::exception &e) const;\n\n};\n\nusing enable_nested_current = error_manip<tag_enable_nested_current>;\n\n\n\n} // namespace bunsan\n", "file_path": "include/bunsan/error.hpp", "rank": 70, "score": 109697.35342717948 }, { "content": "class input_archive : private boost::noncopyable {\n\n public:\n\n using is_loading = std::integral_constant<bool, true>;\n\n using is_saving = std::integral_constant<bool, false>;\n\n\n\n constexpr unsigned int get_library_version() { return 0; }\n\n\n\n public:\n\n explicit input_archive(const Ptree &ptree) : m_ptree(&ptree) {}\n\n\n\n template <typename T>\n\n input_archive &operator&(T &obj) {\n\n return *this >> obj;\n\n }\n\n\n\n template <typename T>\n\n input_archive &operator>>(T &obj) {\n\n load(obj);\n\n return *this;\n\n }\n", "file_path": "include/bunsan/config/input_archive.hpp", "rank": 71, "score": 109404.77304288608 }, { "content": "struct error_manip {\n\n // void operator()(const Error &) const {}\n\n};\n\n\n\ntemplate <typename Error, typename Tag>\n\nconst Error &operator<<(const Error &error, const error_manip<Tag> &manip) {\n\n manip(error);\n\n return error;\n\n}\n\n\n\n} // namespace bunsan\n", "file_path": "include/bunsan/error/manip.hpp", "rank": 72, "score": 109069.36463831952 }, { "content": "struct flusher<false> {\n\n template <typename T>\n\n static void call(T &) {}\n\n};\n\n\n\ntemplate <typename Fstream, std::ios_base::openmode BaseOpenmode>\n\nconst boost::filesystem::path &path(\n\n basic_stream<Fstream, BaseOpenmode> &stream) {\n\n return stream.m_path;\n\n}\n\n\n\ntemplate <typename Fstream, std::ios_base::openmode BaseOpenmode>\n\nstd::ios_base::openmode openmode(basic_stream<Fstream, BaseOpenmode> &stream) {\n\n return stream.m_openmode;\n\n}\n\n} // namespace detail\n\n\n\ntemplate <typename... Args>\n\nusing basic_filebuf = boost::filesystem::basic_filebuf<Args...>;\n\n\n\ntemplate <typename Fstream, std::ios_base::openmode BaseOpenmode>\n", "file_path": "include/bunsan/filesystem/fstream.hpp", "rank": 73, "score": 106637.30565818227 }, { "content": "struct enable_if_record_ostream<basic_record_ostream<CharT>, R> {\n\n typedef R type;\n\n};\n\n\n\n} // namespace aux\n\n\n\ntemplate <typename StreamT, typename T>\n\ninline\n\n typename boost::log::aux::enable_if_record_ostream<StreamT, StreamT&>::type\n\n operator<<(StreamT& strm, T const& value) {\n\n typedef basic_formatting_ostream<typename StreamT::char_type>\n\n formatting_ostream_type;\n\n static_cast<formatting_ostream_type&>(strm) << value;\n\n return strm;\n\n}\n\n\n\ntemplate <typename StreamT, typename T>\n\ninline\n\n typename boost::log::aux::enable_if_record_ostream<StreamT, StreamT&>::type\n\n operator<<(StreamT& strm, T& value) {\n", "file_path": "include/bunsan/log/workaround/boost_1_59.hpp", "rank": 74, "score": 105710.69478207373 }, { "content": "struct enable_if_record_ostream {};\n\ntemplate <typename CharT, typename R>\n", "file_path": "include/bunsan/log/workaround/boost_1_59.hpp", "rank": 75, "score": 102667.47339085922 }, { "content": "struct tempfile_error : virtual error {\n\n using model = boost::error_info<struct tag_model, boost::filesystem::path>;\n\n};\n", "file_path": "include/bunsan/tempfile.hpp", "rank": 76, "score": 101308.79813130043 }, { "content": "struct system_error : categorized_error {\n\n system_error();\n\n explicit system_error(const int errcode);\n\n explicit system_error(const std::string &what);\n\n system_error(const int errcode, const std::string &what);\n\n\n\n using categorized_error::categorized_error;\n\n};\n\n\n\n} // namespace bunsan\n", "file_path": "include/bunsan/system_error.hpp", "rank": 77, "score": 100235.41441072198 }, { "content": "struct unable_to_create_unique_temp_regular_file\n\n : virtual tempfile_create_error {};\n\n\n\n/*!\n\n * \\note Model is pattern with '%' symbols\n\n * that are replaced by random symbols from [0-9a-f]\n\n */\n", "file_path": "include/bunsan/tempfile.hpp", "rank": 78, "score": 99818.75571779608 }, { "content": "struct my_error : virtual bunsan::error {};\n\n\n", "file_path": "tests/error.cpp", "rank": 79, "score": 98775.68501390865 }, { "content": "struct unknown_factory_error : virtual error {\n\n using factory_type = boost::error_info<struct tag_factory_type, std::string>;\n\n};\n\n\n\nnamespace detail {\n\n\n\n/*!\n\n * \\brief This class is implementation of bunsan::factory concept.\n\n *\n\n * bunsan::factory is abstract factory implementation, where each derived\n\n * class is registered in abstract factory by std::string identifier\n\n * on library load using bunsan::factory::register_new().\n\n * Later instance of this type may be created by bunsan::factory::instance().\n\n *\n\n * \\note We need class name different than \"factory\"\n\n * to use it as member function's.\n\n */\n\ntemplate <typename Signature, typename UnknownError>\n", "file_path": "include/bunsan/factory.hpp", "rank": 80, "score": 98234.556738493 }, { "content": "struct uninitialized_optional_error : virtual error {};\n\n\n\ntemplate <typename T, typename Error = uninitialized_optional_error>\n\nconst T &get(const boost::optional<T> &o, const std::string &msg) {\n\n if (!o) BOOST_THROW_EXCEPTION(Error() << error::message(msg));\n\n return o.get();\n\n}\n\n\n\ntemplate <typename T, typename Error = uninitialized_optional_error>\n\nconst T &get(const boost::optional<T> &o) {\n\n if (!o) BOOST_THROW_EXCEPTION(Error());\n\n return o.get();\n\n}\n\n\n\ntemplate <typename T, typename Error = uninitialized_optional_error>\n\nT &get(boost::optional<T> &o, const std::string &msg) {\n\n if (!o) BOOST_THROW_EXCEPTION(Error() << error::message(msg));\n\n return o.get();\n\n}\n\n\n", "file_path": "include/bunsan/get.hpp", "rank": 81, "score": 98234.556738493 }, { "content": "/// \\warning Should not be inherited virtually.\n\nstruct categorized_error : virtual error {\n\n categorized_error() = default;\n\n\n\n explicit categorized_error(const std::error_code &ec);\n\n categorized_error(const std::error_code &ec, const std::string &what);\n\n\n\n using error_code = boost::error_info<struct tag_error_code, std::error_code>;\n\n using what_message = boost::error_info<struct tag_what_message, std::string>;\n\n};\n\n} // namespace bunsan\n\n\n\nnamespace boost {\n\nstd::string to_string(const bunsan::categorized_error::error_code &ec);\n\n} // namespace boost\n", "file_path": "include/bunsan/categorized_error.hpp", "rank": 82, "score": 98234.556738493 }, { "content": "#pragma once\n\n\n\n#include <boost/config.hpp>\n\n#define BOOST_NO_CXX11_SCOPED_ENUMS\n\n\n\n/// \\note deprecated, for backward compatibility with boost<1.53\n\n#define BOOST_NO_SCOPED_ENUMS\n", "file_path": "include/bunsan/config.hpp", "rank": 83, "score": 96260.95109514106 }, { "content": "class error_manip<struct tag_enable_nested> {\n\n public:\n\n explicit error_manip(const boost::exception_ptr &ptr) : m_ptr(ptr) {}\n\n\n\n void operator()(const boost::exception &e) const;\n\n\n\n private:\n\n boost::exception_ptr m_ptr;\n\n};\n\nusing enable_nested = error_manip<tag_enable_nested>;\n\n\n\ntemplate <>\n", "file_path": "include/bunsan/error.hpp", "rank": 84, "score": 95385.83906542987 }, { "content": "struct tempfile_create_error : virtual tempfile_error {\n\n using tries = boost::error_info<struct tag_tries, std::size_t>;\n\n};\n", "file_path": "include/bunsan/tempfile.hpp", "rank": 85, "score": 95385.83906542987 }, { "content": "class error_manip<struct tag_enable_stacktrace> {\n\n public:\n\n /*!\n\n * \\brief Enable stack trace if not provided.\n\n *\n\n * \\param skip number of nested function to omit in stack trace\n\n */\n\n explicit error_manip(const std::size_t skip = 0) : m_skip(skip) {}\n\n\n\n void operator()(const boost::exception &e) const;\n\n\n\n private:\n\n std::size_t m_skip;\n\n};\n\nusing enable_stacktrace = error_manip<tag_enable_stacktrace>;\n\n\n\ntemplate <>\n", "file_path": "include/bunsan/error.hpp", "rank": 86, "score": 95385.83906542987 }, { "content": "struct write_data_error : virtual error {};\n\n\n\n} // namespace filesystem\n\n} // namespace bunsan\n\n\n\nnamespace boost {\n\nstd::string to_string(const bunsan::filesystem::error::openmode &openmode);\n\n} // namespace boost\n", "file_path": "include/bunsan/filesystem/error.hpp", "rank": 87, "score": 95385.83906542987 }, { "content": "/// Base exception class for stream_enum errors.\n\nstruct invalid_value_error : virtual error {};\n\n\n", "file_path": "include/bunsan/stream_enum.hpp", "rank": 88, "score": 95385.83906542987 }, { "content": "struct read_data_error : virtual error {};\n", "file_path": "include/bunsan/filesystem/error.hpp", "rank": 89, "score": 95385.83906542987 }, { "content": "struct fixture {\n\n struct cfg_type {\n\n BUNSAN_INCLASS_STREAM_ENUM_CLASS(my_enum, (first, second))\n\n\n\n int a;\n\n std::string b;\n\n my_enum c;\n\n variant d;\n\n boost::property_tree::ptree e;\n\n\n\n template <typename Archive>\n\n void serialize(Archive &ar, const unsigned int) {\n\n ar & BOOST_SERIALIZATION_NVP(a);\n\n ar & BOOST_SERIALIZATION_NVP(b);\n\n ar & BOOST_SERIALIZATION_NVP(c);\n\n ar & BOOST_SERIALIZATION_NVP(d);\n\n ar & BOOST_SERIALIZATION_NVP(e);\n\n }\n\n };\n\n\n", "file_path": "tests/config.cpp", "rank": 90, "score": 94389.74273093241 }, { "content": "struct ptr_maker<std::unique_ptr<T>> {\n\n template <typename... Args>\n\n static std::unique_ptr<T> call(Args &&... args) {\n\n return std::make_unique<T>(std::forward<Args>(args)...);\n\n }\n\n};\n\n\n\ntemplate <typename T>\n", "file_path": "include/bunsan/memory.hpp", "rank": 91, "score": 93710.84368837443 }, { "content": "struct ptr_maker<boost::shared_ptr<T>> {\n\n template <typename... Args>\n\n static boost::shared_ptr<T> call(Args &&... args) {\n\n return boost::make_shared<T>(std::forward<Args>(args)...);\n\n }\n\n};\n\n} // namespace detail\n\n\n\ntemplate <typename Pointer, typename... Args>\n\ninline Pointer make_ptr(Args &&... args) {\n\n return detail::ptr_maker<Pointer>::call(std::forward<Args>(args)...);\n\n}\n\n\n\n} // namespace bunsan\n", "file_path": "include/bunsan/memory.hpp", "rank": 92, "score": 93710.84368837443 }, { "content": "struct ptr_maker<boost::intrusive_ptr<T>> {\n\n template <typename... Args>\n\n static boost::intrusive_ptr<T> call(Args &&... args) {\n\n boost::intrusive_ptr<T> ptr(new T(std::forward<Args>(args)...));\n\n return ptr;\n\n }\n\n};\n\n\n\ntemplate <typename T>\n", "file_path": "include/bunsan/memory.hpp", "rank": 93, "score": 93710.84368837443 }, { "content": "struct ptr_maker<std::shared_ptr<T>> {\n\n template <typename... Args>\n\n static std::shared_ptr<T> call(Args &&... args) {\n\n return std::make_shared<T>(std::forward<Args>(args)...);\n\n }\n\n};\n\n\n\ntemplate <typename T>\n", "file_path": "include/bunsan/memory.hpp", "rank": 94, "score": 93710.84368837443 }, { "content": "#pragma once\n\n\n\n#include <boost/preprocessor/cat.hpp>\n\n\n\n/*!\n\n * Provides macros for module static initializers.\n\n *\n\n * \\warning Should never be included in header file.\n\n */\n\n\n\n#define BUNSAN_STATIC_INITIALIZER_NAME(NAME) BOOST_PP_CAT(NAME, _initializer)\n\n\n\n#ifdef BUNSAN_STATIC_INITIALIZER_GENERATOR\n\n// Build system supports automatic initializer creation.\n\n#define BUNSAN_STATIC_INITIALIZER(NAME, CODE) \\\n\n extern \"C\" void BUNSAN_STATIC_INITIALIZER_NAME(NAME)() CODE\n\n#else\n\n// No build system support, use C++ facilities.\n\n#define BUNSAN_STATIC_INITIALIZER(NAME, CODE) \\\n\n namespace { \\\n\n struct BUNSAN_STATIC_INITIALIZER_NAME(NAME) { \\\n\n BUNSAN_STATIC_INITIALIZER_NAME(NAME)() CODE \\\n\n } BOOST_PP_CAT(BUNSAN_STATIC_INITIALIZER_NAME(NAME), _sentry); \\\n\n }\n\n\n\n#define BUNSAN_STATIC_INITIALIZER_TEXT(CODE) int N\n\n#endif\n", "file_path": "include/bunsan/static_initializer.hpp", "rank": 95, "score": 92848.46300569421 }, { "content": "struct invalid_data_error : virtual error {\n\n using data = boost::error_info<struct tag_data, std::string>;\n\n};\n\n\n\ntemplate <typename Connection>\n", "file_path": "include/bunsan/asio/line_connection.hpp", "rank": 96, "score": 92738.70681766883 }, { "content": "#pragma once\n\n\n\n#include <boost/filesystem/path.hpp>\n\n#include <boost/serialization/nvp.hpp>\n\n#include <boost/serialization/split_free.hpp>\n\n\n\nBOOST_SERIALIZATION_SPLIT_FREE(boost::filesystem::path)\n\n\n\nnamespace boost {\n\nnamespace serialization {\n\n\n\ntemplate <typename Archive>\n\nvoid save(Archive &ar, const boost::filesystem::path &path,\n\n const unsigned int /*version*/) {\n\n ar & boost::serialization::make_nvp(\"path\", path.generic_string());\n\n}\n\n\n\ntemplate <typename Archive>\n\nvoid load(Archive &ar, boost::filesystem::path &path,\n\n const unsigned int /*version*/) {\n\n std::string str;\n\n ar & boost::serialization::make_nvp(\"path\", str);\n\n path = str;\n\n}\n\n\n\n} // namespace serialization\n\n} // namespace boost\n", "file_path": "include/bunsan/serialization/path.hpp", "rank": 97, "score": 92737.09245741159 }, { "content": "#pragma once\n\n\n\n#include <boost/serialization/split_free.hpp>\n\n\n\n#include <chrono>\n\n\n\nnamespace boost {\n\nnamespace serialization {\n\n\n\ntemplate <typename Archive, typename Rep, typename Period>\n\ninline void serialize(Archive &ar,\n\n typename std::chrono::duration<Rep, Period> &dur,\n\n const unsigned int file_version) {\n\n split_free(ar, dur, file_version);\n\n}\n\n\n\ntemplate <typename Archive, typename Rep, typename Period>\n\nvoid save(Archive &ar, const typename std::chrono::duration<Rep, Period> &dur,\n\n const unsigned int /*version*/) {\n\n Rep rp = dur.count();\n", "file_path": "include/bunsan/serialization/chrono.hpp", "rank": 98, "score": 92734.11512827741 }, { "content": " ar &rp;\n\n}\n\n\n\ntemplate <typename Archive, typename Rep, typename Period>\n\nvoid load(Archive &ar, typename std::chrono::duration<Rep, Period> &dur,\n\n const unsigned int /*version*/) {\n\n Rep rp;\n\n ar &rp;\n\n dur = typename std::chrono::duration<Rep, Period>(rp);\n\n}\n\n\n\n} // namespace serialization\n\n} // namespace boost\n", "file_path": "include/bunsan/serialization/chrono.hpp", "rank": 99, "score": 92726.41012394165 } ]
C++
components/agro_mesh/net/resources/app.cpp
rnascunha/agro_mesh
f4d1c49cdbd3d61086c1dcd79143d30ec54d4871
#include "esp_log.h" #include <stdio.h> #include <string.h> #include "../coap_engine.hpp" #include "../../modules/app/app.hpp" extern const char* RESOURCE_TAG; static char* make_name(char* name, const void* data, unsigned name_size) noexcept { std::memcpy(name, data, name_size); name[name_size] = '\0'; return name; } static void get_app_handler(engine::message const& request, engine::response& response, void*) noexcept { ESP_LOGD(RESOURCE_TAG, "Called get app handler"); std::uint8_t buffer[engine::packet_size]; char name[app_max_name_size]; const void* value = nullptr; unsigned length; if(CoAP::Message::query_by_key(request, "name", &value, length) || !length) { app mapp; app_status status = get_app(mapp, make_name(name, value, length)); if(status != app_status::success) { response .code(CoAP::Message::code::not_found) .payload(app_error_string(status)) .serialize(); return; } response .code(CoAP::Message::code::content) .payload(static_cast<const void*>(&mapp), sizeof(app)); return; } unsigned size; app_status status = get_app_list(buffer, engine::packet_size, size); if(status != app_status::success) { response .code(CoAP::Message::code::not_found) .payload(app_error_string(status)) .serialize(); return; } response .code(CoAP::Message::code::content) .payload(buffer, size) .serialize(); } static void post_app_handler(engine::message const& request, engine::response& response, void*) noexcept { ESP_LOGD(RESOURCE_TAG, "Called post app handler"); if(!request.payload || !request.payload_len || request.payload_len <= 32) { response .code(CoAP::Message::code::precondition_failed) .payload("app not defiend") .serialize(); return; } if((request.payload_len - 32) > app_max_name_size) { response .code(CoAP::Message::code::precondition_failed) .payload("file name too long") .serialize(); return; } char name[app_max_name_size + 1]; if(!init_app_task(make_name(name, static_cast<const unsigned char*>(request.payload) + 32, request.payload_len - 32), static_cast<const std::uint8_t*>(request.payload))) { response .code(CoAP::Message::code::internal_server_error) .payload("app other loading") .serialize(); return; } response .code(CoAP::Message::code::changed) .serialize(); } static void put_app_handler(engine::message const& request, engine::response& response, void*) noexcept { ESP_LOGD(RESOURCE_TAG, "Called put app handler"); if(!request.payload || !request.payload_len || request.payload_len <= sizeof(std::int32_t)) { response .code(CoAP::Message::code::precondition_failed) .payload("app not defined") .serialize(); return; } if((request.payload_len - sizeof(int32_t)) > app_max_name_size) { response .code(CoAP::Message::code::precondition_failed) .payload("file name too long") .serialize(); return; } std::int32_t arg = *static_cast<const int*>(request.payload); int ret; char name[app_max_name_size + 1]; app_status status = execute_app(make_name(name, static_cast<const char*>(request.payload) + sizeof(std::int32_t), request.payload_len - sizeof(std::int32_t)), arg, ret); if(status != app_status::success) { response .code(CoAP::Message::code::not_found) .payload(app_error_string(status)) .serialize(); return; } ESP_LOGI(RESOURCE_TAG, "Returned %d", ret); response .code(CoAP::Message::code::success) .payload(&ret, sizeof(ret)) .serialize(); } static void delete_app_handler(engine::message const& request, engine::response& response, void*) noexcept { ESP_LOGD(RESOURCE_TAG, "Called delete app handler"); if(!request.payload || !request.payload_len) { response .code(CoAP::Message::code::precondition_failed) .payload("app not defined") .serialize(); return; } if(request.payload_len > app_max_name_size) { response .code(CoAP::Message::code::precondition_failed) .payload("file name too long") .serialize(); return; } char name[app_max_name_size + 1]; app_status status = delete_app(make_name(name, request.payload, request.payload_len)); if(status != app_status::success) { response .code(CoAP::Message::code::not_found) .payload(app_error_string(status)) .serialize(); return; } response .code(CoAP::Message::code::success) .serialize(); } engine::resource_node res_app("app", get_app_handler, post_app_handler, put_app_handler, delete_app_handler);
#include "esp_log.h" #include <stdio.h> #include <string.h> #include "../coap_engine.hpp" #include "../../modules/app/app.hpp" extern const char* RESOURCE_TAG; static char* make_name(char* name, const void* data, unsigned name_size) noexcept { std::memcpy(name, data, name_size); name[name_size] = '\0'; return name; } static void get_app_handler(engine::message const& request, engine::response& response, void*) noexcept { ESP_LOGD(RESOURCE_TAG, "Called get app handler"); std::uint8_t buffer[engine::packet_size]; char name[app_max_name_size]; const void* value = nullptr; unsigned length; if(CoAP::Message::query_by_key(request, "name", &value, length) || !length) { app mapp; app_status status = get_app(mapp, make_name(name, value, length)); if(status != app_status::success) { response .code(CoAP::Message::code::not_found) .payload(app_error_string(status)) .serialize(); return; } response .code(CoAP::Message::code::content) .payload(static_cast<const void*>(&mapp), sizeof(app)); return; } unsigned size; app_status status = get_app_list(buffer, engine::packet_size, size); if(status != app_status::success) { response .code(CoAP::Message::code::not_found) .payload(app_error_string(status)) .serialize(); return; } response .code(CoAP::Message::code::content) .payload(buffer, size) .serialize(); } static void post_app_handler(engine::message const& request, engine::response& response, void*) noexcept { ESP_LOGD(RESOURCE_TAG, "Called post app handler"); if(!request.payload || !request.payload_len || request.payload_len <= 32) { response .code(CoAP::Message::code::precondition_failed) .payload("app not defiend") .serialize(); return; } if((request.payload_len - 32) > app_max_name_size) { response .code(CoAP::Message::code::precondition_failed) .payload("file name too long") .serialize(); return; } char name[app_max_name_size + 1]; if(!init_app_task(make_name(name, static_cast<const unsigned char*>(request.payload) + 32, request.payload_le
static void put_app_handler(engine::message const& request, engine::response& response, void*) noexcept { ESP_LOGD(RESOURCE_TAG, "Called put app handler"); if(!request.payload || !request.payload_len || request.payload_len <= sizeof(std::int32_t)) { response .code(CoAP::Message::code::precondition_failed) .payload("app not defined") .serialize(); return; } if((request.payload_len - sizeof(int32_t)) > app_max_name_size) { response .code(CoAP::Message::code::precondition_failed) .payload("file name too long") .serialize(); return; } std::int32_t arg = *static_cast<const int*>(request.payload); int ret; char name[app_max_name_size + 1]; app_status status = execute_app(make_name(name, static_cast<const char*>(request.payload) + sizeof(std::int32_t), request.payload_len - sizeof(std::int32_t)), arg, ret); if(status != app_status::success) { response .code(CoAP::Message::code::not_found) .payload(app_error_string(status)) .serialize(); return; } ESP_LOGI(RESOURCE_TAG, "Returned %d", ret); response .code(CoAP::Message::code::success) .payload(&ret, sizeof(ret)) .serialize(); } static void delete_app_handler(engine::message const& request, engine::response& response, void*) noexcept { ESP_LOGD(RESOURCE_TAG, "Called delete app handler"); if(!request.payload || !request.payload_len) { response .code(CoAP::Message::code::precondition_failed) .payload("app not defined") .serialize(); return; } if(request.payload_len > app_max_name_size) { response .code(CoAP::Message::code::precondition_failed) .payload("file name too long") .serialize(); return; } char name[app_max_name_size + 1]; app_status status = delete_app(make_name(name, request.payload, request.payload_len)); if(status != app_status::success) { response .code(CoAP::Message::code::not_found) .payload(app_error_string(status)) .serialize(); return; } response .code(CoAP::Message::code::success) .serialize(); } engine::resource_node res_app("app", get_app_handler, post_app_handler, put_app_handler, delete_app_handler);
n - 32), static_cast<const std::uint8_t*>(request.payload))) { response .code(CoAP::Message::code::internal_server_error) .payload("app other loading") .serialize(); return; } response .code(CoAP::Message::code::changed) .serialize(); }
function_block-function_prefixed
[ { "content": "struct app{\n\n\tchar\t\tname[app_max_name_size + 1];\n\n\tunsigned \tsize = 0;\n\n};\n\n\n", "file_path": "components/agro_mesh/modules/app/app.hpp", "rank": 0, "score": 77485.24550976587 }, { "content": "const char* get_scheduler_status_string(Scheduler::status_t status);\n", "file_path": "components/debug/include/get_type_time_string.h", "rank": 1, "score": 74952.56696805652 }, { "content": " void *data;\n", "file_path": "components/elfloader/loader.c", "rank": 2, "score": 69270.8021968081 }, { "content": " size_t size;\n", "file_path": "components/elfloader/loader.c", "rank": 3, "score": 69236.46764596605 }, { "content": " const char *name; /*!< Name of symbol */\n", "file_path": "components/elfloader/loader.h", "rank": 4, "score": 69202.69850598513 }, { "content": " const char *name; /*!< Name of symbol */\n", "file_path": "components/elfloader/loader.c", "rank": 5, "score": 69202.69850598513 }, { "content": "struct __attribute__((packed)) BR_Message_Data{\n\n\tmesh_addr_t\t\taddr;\n\n};\n\n\n", "file_path": "components/mesh/include/mesh/br_types.hpp", "rank": 6, "score": 68384.90583597109 }, { "content": "enum class app_status{\n\n\tsuccess = 0,\n\n\tnot_mounted,\n\n\tnot_found,\n\n\talready_exists,\n\n\tfile_list_error,\n\n\tallocation_error,\n\n\tserver_response,\n\n\treceive_timeout\n\n};\n\n\n\nconst char* app_error_string(app_status status) noexcept;\n\n\n\napp_status get_app(app& app_, const char* name) noexcept;\n\napp_status get_app_list(unsigned char*, unsigned, unsigned& readed, unsigned read_from = 0) noexcept;\n\napp_status add_app(const char* name, unsigned size) noexcept;\n\napp_status delete_app(const char* name) noexcept;\n\napp_status execute_app(const char* name, int args, int& ret) noexcept;\n\n\n\nbool init_app_task(const char*, const std::uint8_t*) noexcept;\n\n\n\n#endif /* AGRO_MESH_TYPES_APP_TYPES_HPP__ */\n", "file_path": "components/agro_mesh/modules/app/app.hpp", "rank": 7, "score": 52891.22683878518 }, { "content": "{\n\n\tif(!storage_is_mounted()) return app_status::not_mounted;\n\n\n\n\tESP_LOGI(TAG, \"APP to exec %s\", name);\n\n\n\n\tapp app_;\n\n\tapp_status status = get_app(app_, name);\n\n\tif(status != app_status::success)\n\n\t{\n\n\t\tESP_LOGE(TAG, \"[exec_app] get_app not found = %s\", name);\n\n\t\treturn status;\n\n\t}\n\n\n\n\tunsigned char* app_buf = (unsigned char*)malloc(sizeof(unsigned char) * app_.size);\n\n\tif(!app_buf) return app_status::allocation_error;\n\n\n\n\tchar buffer[app_max_name_size + 10];\n\n\tFILE* f = fopen(make_file_path(buffer, name), \"rb\");\n\n\tif(!f)\n\n\t{\n", "file_path": "components/agro_mesh/modules/app/app.cpp", "rank": 8, "score": 50284.26981971397 }, { "content": "#include \"app.hpp\"\n\n\n\n#include \"../../storage.hpp\"\n\n#include \"esp_vfs_fat.h\"\n\n#include \"esp_log.h\"\n\n#include <stdio.h>\n\n#include <cstring>\n\n#include <malloc.h>\n\n#include <unistd.h>\n\n#include \"loader.h\"\n\n#include \"driver/gpio.h\"\n\n\n\n#define TAG \"app\"\n\n\n\nextern const char* app_list;\n\nextern const char* app_temp;\n\nextern const char *base_path;\n\n\n\nstatic const ELFLoaderSymbol_t exports[] = {\n\n { \"puts\", (void*) puts },\n", "file_path": "components/agro_mesh/modules/app/app.cpp", "rank": 9, "score": 50283.00650686633 }, { "content": " { \"printf\", (void*) printf },\n\n\t{ \"gpio_set_level\", (void*)gpio_set_level}\n\n};\n\n\n\nstatic const ELFLoaderEnv_t env = {\n\n\t\texports,\n\n\t\tsizeof(exports) / sizeof(*exports)\n\n};\n\n\n\nstatic char* make_file_path(char* buf, const char* name) noexcept\n\n{\n\n\t//Making full file path\n\n\tstd::strcpy(buf, base_path);\n\n\tstd::strcat(buf, \"/\");\n\n\tstd::strcat(buf, name);\n\n\n\n\treturn buf;\n\n}\n\n\n\nconst char* app_error_string(app_status status) noexcept\n", "file_path": "components/agro_mesh/modules/app/app.cpp", "rank": 10, "score": 50281.46140688432 }, { "content": "\t\tunsigned read_from /* = 0 */) noexcept\n\n{\n\n\tif(!storage_is_mounted()) return app_status::not_mounted;\n\n\n\n\tFILE *f = fopen(app_list, \"rb\");\n\n\tif(!f)\n\n\t{\n\n\t\tESP_LOGE(TAG, \"[get_app] Error opeining app list file\");\n\n\t\treturn app_status::file_list_error;\n\n\t}\n\n\tif(read_from) fseek(f, read_from, SEEK_SET);\n\n\n\n\treaded = fread(buffer, 1, size, f);\n\n\tESP_LOGI(TAG, \"[get_app_list] readed = %u\", readed);\n\n\tfclose(f);\n\n\n\n\treturn app_status::success;\n\n}\n\n\n\napp_status get_app(app& app_, const char* name) noexcept\n", "file_path": "components/agro_mesh/modules/app/app.cpp", "rank": 11, "score": 50281.33591863986 }, { "content": "{\n\n\tif(!storage_is_mounted()) return app_status::not_mounted;\n\n\n\n\tESP_LOGI(TAG, \"[get_app] Search %s\", name);\n\n\tFILE *f = fopen(app_list, \"rb\");\n\n\tif(!f)\n\n\t{\n\n\t\tESP_LOGE(TAG, \"[get_app] Error opeining app list file\");\n\n\t\treturn app_status::file_list_error;\n\n\t}\n\n\n\n\tbool finded = false;\n\n\tdo{\n\n\t\tunsigned size_read = fread(reinterpret_cast<char*>(&app_), 1, sizeof(app), f);\n\n\t\tif(!size_read) break;\n\n\t\tESP_LOGI(TAG, \"[get_app] readed = %u / name = %s\", size_read, app_.name);\n\n\t\tif(strcmp(app_.name, name) == 0)\n\n\t\t{\n\n\t\t\tfinded = true;\n\n\t\t\tbreak;\n", "file_path": "components/agro_mesh/modules/app/app.cpp", "rank": 12, "score": 50281.27012786192 }, { "content": "#ifndef AGRO_MESH_TYPES_APP_TYPES_HPP__\n\n#define AGRO_MESH_TYPES_APP_TYPES_HPP__\n\n\n\n#include <cstdint>\n\n\n\n#if defined(CONFIG_FATFS_LFN_HEAP) || defined(CONFIG_FATFS_LFN_STACK)\n\nstatic constexpr const unsigned app_max_name_size = CONFIG_FATFS_MAX_LFN;\n\n#else /* CONFIG_FATFS_LFN_NONE */\n\nstatic constexpr const unsigned app_max_name_size = 12;\n\n#endif\n\n\n", "file_path": "components/agro_mesh/modules/app/app.hpp", "rank": 13, "score": 50280.948795138436 }, { "content": "\t}\n\n\n\n\tstrncpy(app_.name, name, app_max_name_size);\n\n\tapp_.size = size;\n\n\n\n\tfwrite(reinterpret_cast<char*>(&app_), 1, sizeof(app), f);\n\n\tfclose(f);\n\n\n\n\treturn app_status::success;\n\n}\n\n\n\napp_status delete_app(const char* name) noexcept\n\n{\n\n\tif(!storage_is_mounted()) return app_status::not_mounted;\n\n\n\n\tESP_LOGI(TAG, \"APP to delete %s\", name);\n\n\n\n\tFILE *f = fopen(app_list, \"rb\");\n\n\tif(!f)\n\n\t{\n", "file_path": "components/agro_mesh/modules/app/app.cpp", "rank": 14, "score": 50280.58106364387 }, { "content": "\t\t}\n\n\t}while(true);\n\n\tfclose(f);\n\n\n\n\treturn finded ? app_status::success : app_status::not_found;\n\n}\n\n\n\napp_status add_app(const char* name, unsigned size) noexcept\n\n{\n\n\tif(!storage_is_mounted()) return app_status::not_mounted;\n\n\n\n\tapp app_;\n\n\tapp_status status = get_app(app_, name);\n\n\tif(status == app_status::success) return app_status::already_exists;\n\n\n\n\tFILE *f = fopen(app_list, \"a+b\");\n\n\tif(!f)\n\n\t{\n\n\t\tESP_LOGE(TAG, \"[add_app] Error opeining app list file\");\n\n\t\treturn app_status::file_list_error;\n", "file_path": "components/agro_mesh/modules/app/app.cpp", "rank": 15, "score": 50279.74881080298 }, { "content": "\t\t}\n\n\t\telse\n\n\t\t{\n\n\t\t\tfwrite(reinterpret_cast<char*>(&app_), 1, sizeof(app), temp);\n\n\t\t}\n\n\t}while(true);\n\n\n\n\tfclose(temp);\n\n\tfclose(f);\n\n\n\n\tunlink(app_list);\n\n\tchar buffer[app_max_name_size + 10];\n\n\tunlink(make_file_path(buffer, name));\n\n\n\n\trename(app_temp, app_list);\n\n\n\n\treturn app_status::success;\n\n}\n\n\n\napp_status execute_app(const char* name, int args, int& ret) noexcept\n", "file_path": "components/agro_mesh/modules/app/app.cpp", "rank": 16, "score": 50278.656575623514 }, { "content": "{\n\n\tswitch(status)\n\n\t{\n\n\t\tcase app_status::success: return \"success\";\n\n\t\tcase app_status::not_found: return \"not found\";\n\n\t\tcase app_status::not_mounted: return \"not mounted\";\n\n\t\tcase app_status::already_exists: return \"already exists\";\n\n\t\tcase app_status::file_list_error: return \"file list error\";\n\n\t\tcase app_status::allocation_error: return \"allocation error\";\n\n\t\tcase app_status::receive_timeout: return \"receive timeout\";\n\n\t\tcase app_status::server_response: return \"server response\";\n\n\t\tdefault:\n\n\t\t\tbreak;\n\n\t}\n\n\treturn \"undefined\";\n\n}\n\n\n\napp_status get_app_list(unsigned char* buffer,\n\n\t\tunsigned size,\n\n\t\tunsigned& readed,\n", "file_path": "components/agro_mesh/modules/app/app.cpp", "rank": 17, "score": 50274.55601000099 }, { "content": "\t\tESP_LOGE(TAG, \"[exec_app] Error opening file = %s\", name);\n\n\t\treturn app_status::file_list_error;\n\n\t}\n\n\tunsigned readed = fread(app_buf, 1, app_.size, f);\n\n\tfclose(f);\n\n\tif(readed != app_.size)\n\n\t{\n\n\t\tESP_LOGE(TAG, \"[exec_app] Readed less than should [%u-%u]\", readed, app_.size);\n\n\t\treturn app_status::file_list_error;\n\n\t}\n\n\n\n\tret = elfLoader(app_buf, &env, \"local_main\", args);\n\n\n\n\tfree(app_buf);\n\n\n\n\treturn app_status::success;\n\n}\n", "file_path": "components/agro_mesh/modules/app/app.cpp", "rank": 18, "score": 50273.56712507615 }, { "content": "\t\tESP_LOGE(TAG, \"[delete_app] Error opeining app list file\");\n\n\t\treturn app_status::file_list_error;\n\n\t}\n\n\tFILE *temp = fopen(app_temp, \"wb\");\n\n\tif(!temp)\n\n\t{\n\n\t\tESP_LOGE(TAG, \"[delete_app] Error opeining temp file\");\n\n\t\tfclose(f);\n\n\t\treturn app_status::file_list_error;\n\n\t}\n\n\n\n\tapp app_;\n\n\tbool finded = false;\n\n\tunsigned readed = 0;\n\n\tdo{\n\n\t\treaded = fread(reinterpret_cast<char*>(&app_), 1, sizeof(app), f);\n\n\t\tif(!readed) break;\n\n\t\tif(!finded && strcmp(app_.name, name) == 0)\n\n\t\t{\n\n\t\t\tfinded = true;\n", "file_path": "components/agro_mesh/modules/app/app.cpp", "rank": 19, "score": 50272.5060824575 }, { "content": "const char* get_wifi_bandwidth_string(wifi_bandwidth_t band){\n\n\treturn band == WIFI_BW_HT20 ? \"HT20\" : (band == WIFI_BW_HT40 ? \"HT40\" : \"Undefined\");\n", "file_path": "components/debug/get_type_string.c", "rank": 20, "score": 45200.3358044688 }, { "content": "const char* get_chip_model_string(esp_chip_model_t model){\n\n\treturn model == CHIP_ESP32 ? \"ESP32\" : \"Undefined\";\n", "file_path": "components/debug/get_type_string.c", "rank": 21, "score": 45195.51211416153 }, { "content": "const char* get_wifi_authmode_string(wifi_auth_mode_t mode){\n\n\tswitch(mode){\n\n\t\tcase WIFI_AUTH_OPEN: /**< authenticate mode : open */\n\n\t\t\treturn \"OPEN\";\n\n\t\tcase WIFI_AUTH_WEP: /**< authenticate mode : WEP */\n\n\t\t\treturn \"WEP\";\n\n\t\tcase WIFI_AUTH_WPA_PSK: /**< authenticate mode : WPA_PSK */\n\n\t\t\treturn \"WPA_PSK\";\n\n\t\tcase WIFI_AUTH_WPA2_PSK: /**< authenticate mode : WPA2_PSK */\n\n\t\t\treturn \"WPA2_PSK\";\n\n\t\tcase WIFI_AUTH_WPA_WPA2_PSK: /**< authenticate mode : WPA_WPA2_PSK */\n\n\t\t\treturn \"WPA_WPA2_PSK\";\n\n\t\tcase WIFI_AUTH_WPA2_ENTERPRISE: /**< authenticate mode : WPA2_ENTERPRISE */\n\n\t\t\treturn \"WPA2_ENTERPRISE\";\n\n\t\tcase WIFI_AUTH_MAX:\n\n\t\t\treturn \"MAX\";\n\n\t\tdefault:\n\n\t\t\tbreak;\n\n\t}\n\n\treturn \"Undefined\";\n", "file_path": "components/debug/get_type_string.c", "rank": 22, "score": 45195.51211416153 }, { "content": "const char* get_wifi_antena_string(wifi_ant_t ant){\n\n\tswitch(ant){\n\n\t\tcase WIFI_ANT_ANT0: /**< WiFi antenna 0 */\n\n\t\t\treturn \"ANT0\";\n\n\t\tcase WIFI_ANT_ANT1: /**< WiFi antenna 1 */\n\n\t\t\treturn \"ANT1\";\n\n\t\tcase WIFI_ANT_MAX: /**< Invalid WiFi antenna */\n\n\t\t\treturn \"MAX\";\n\n\t}\n\n\treturn \"Undefined\";\n", "file_path": "components/debug/get_type_string.c", "rank": 23, "score": 45195.51211416153 }, { "content": "const char* get_wifi_contry_policy_string(wifi_country_policy_t policy){\n\n\tswitch(policy){\n\n\t\tcase WIFI_COUNTRY_POLICY_AUTO: /**< Country policy is auto, use the country info of AP to which the station is connected */\n\n\t\t\treturn \"AUTO\";\n\n\t\tcase WIFI_COUNTRY_POLICY_MANUAL: /**< Country policy is manual, always use the configured country info */\n\n\t\t\treturn \"MANUAL\";\n\n\t}\n\n\treturn \"Undefined\";\n", "file_path": "components/debug/get_type_string.c", "rank": 24, "score": 44412.16049877397 }, { "content": "const char* get_wifi_second_channel_string(wifi_second_chan_t ch){\n\n\tswitch(ch){\n\n\t\tcase WIFI_SECOND_CHAN_NONE:\n\n\t\t\treturn \"NONE\";\n\n\t\tcase WIFI_SECOND_CHAN_ABOVE:\n\n\t\t\treturn \"ABOVE\";\n\n\t\tcase WIFI_SECOND_CHAN_BELOW:\n\n\t\t\treturn \"BELOW\";\n\n\t}\n\n\treturn \"Undefined\";\n", "file_path": "components/debug/get_type_string.c", "rank": 25, "score": 44412.16049877397 }, { "content": "const char* get_wifi_cipher_type_string(wifi_cipher_type_t cipher){\n\n\tswitch(cipher){\n\n\t\tcase WIFI_CIPHER_TYPE_NONE: /**< the cipher type is none */\n\n\t\t\treturn \"NONE\";\n\n\t\tcase WIFI_CIPHER_TYPE_WEP40: /**< the cipher type is WEP40 */\n\n\t\t\treturn \"WEP40\";\n\n\t\tcase WIFI_CIPHER_TYPE_WEP104: /**< the cipher type is WEP104 */\n\n\t\t\treturn \"WEB104\";\n\n\t\tcase WIFI_CIPHER_TYPE_TKIP: /**< the cipher type is TKIP */\n\n\t\t\treturn \"TKIP\";\n\n\t\tcase WIFI_CIPHER_TYPE_CCMP: /**< the cipher type is CCMP */\n\n\t\t\treturn \"CCMP\";\n\n\t\tcase WIFI_CIPHER_TYPE_TKIP_CCMP: /**< the cipher type is TKIP and CCMP */\n\n\t\t\treturn \"TKIP_CCMP\";\n\n\t\tcase WIFI_CIPHER_TYPE_UNKNOWN: /**< the cipher type is unknown */\n\n\t\t\treturn \"UNKNOW\";\n\n\t\tdefault:\n\n\t\t\tbreak;\n\n\t}\n\n\treturn \"Undefined\";\n", "file_path": "components/debug/get_type_string.c", "rank": 26, "score": 44412.16049877397 }, { "content": "const char* get_system_reset_reason_string(esp_reset_reason_t reason){\n\n switch(reason){\n\n \tcase ESP_RST_UNKNOWN: //!< Reset reason can not be determined\n\n \t\treturn \"UNKNOW\";\n\n\t\tcase ESP_RST_POWERON: //!< Reset due to power-on event\n\n\t\t\treturn \"POWERON\";\n\n\t\tcase ESP_RST_EXT: //!< Reset by external pin (not applicable for ESP32)\n\n\t\t\treturn \"EXTERNAL\";\n\n\t\tcase ESP_RST_SW: //!< Software reset via esp_restart\n\n\t\t\treturn \"SOFTWARE\";\n\n\t\tcase ESP_RST_PANIC: //!< Software reset due to exception/panic\n\n\t\t\treturn \"PANIC\";\n\n\t\tcase ESP_RST_INT_WDT: //!< Reset (software or hardware) due to interrupt watchdog\n\n\t\t\treturn \"INTERRUPT WDT\";\n\n\t\tcase ESP_RST_TASK_WDT: //!< Reset due to task watchdog\n\n\t\t\treturn \"TASK WDT\";\n\n\t\tcase ESP_RST_WDT: //!< Reset due to other watchdogs\n\n\t\t\treturn \"WDT\";\n\n\t\tcase ESP_RST_DEEPSLEEP: //!< Reset after exiting deep sleep mode\n\n\t\t\treturn \"DEEP SLEEP\";\n\n\t\tcase ESP_RST_BROWNOUT: //!< Brownout reset (software or hardware)\n\n\t\t\treturn \"BROWNOUT\";\n\n\t\tcase ESP_RST_SDIO: //!< Reset over SDIO\n\n\t\t\treturn \"SDIO\";\n\n }\n\n\treturn \"Undefined\";\n", "file_path": "components/debug/get_type_string.c", "rank": 27, "score": 44412.16049877397 }, { "content": "const char* get_wifi_error_reason_string(wifi_err_reason_t err){\n\n\tswitch(err){\n\n\tcase WIFI_REASON_UNSPECIFIED:\n\n\t\treturn \"UNSPECIFIED\";\n\n\tcase WIFI_REASON_AUTH_EXPIRE:\n\n\t\treturn \"AUTH_EXPIRE\";\n\n\tcase WIFI_REASON_AUTH_LEAVE:\n\n\t\treturn \"AUTH_LEAVE\";\n\n\tcase WIFI_REASON_ASSOC_EXPIRE:\n\n\t\treturn \"ASSOC_EXPIRE\";\n\n\tcase WIFI_REASON_ASSOC_TOOMANY:\n\n\t\treturn \"ASSOC_TOOMANY\";\n\n\tcase WIFI_REASON_NOT_AUTHED:\n\n\t\treturn \"NOT_AUTHED\";\n\n\tcase WIFI_REASON_NOT_ASSOCED:\n\n\t\treturn \"NOT_ASSOCED\";\n\n\tcase WIFI_REASON_ASSOC_LEAVE:\n\n\t\treturn \"ASSOC_LEAVE\";\n\n\tcase WIFI_REASON_ASSOC_NOT_AUTHED:\n\n\t\treturn \"ASSOC_NOT_AUTHED\";\n\n\tcase WIFI_REASON_DISASSOC_PWRCAP_BAD:\n\n\t\treturn \"DISASSOC_PWRCAP_BAD\";\n\n\tcase WIFI_REASON_DISASSOC_SUPCHAN_BAD:\n\n\t\treturn \"DISASSOC_SUPCHAN_BAD\";\n\n\tcase WIFI_REASON_IE_INVALID:\n\n\t\treturn \"IE_INVALID\";\n\n\tcase WIFI_REASON_MIC_FAILURE:\n\n\t\treturn \"MIC_FAILURE\";\n\n\tcase WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT:\n\n\t\treturn \"4WAY_HANDSHAKE_TIMEOUT\";\n\n\tcase WIFI_REASON_GROUP_KEY_UPDATE_TIMEOUT:\n\n\t\treturn \"GROUP_KEY_UPDATE_TIMEOUT\";\n\n\tcase WIFI_REASON_IE_IN_4WAY_DIFFERS:\n\n\t\treturn \"IE_IN_4WAY_DIFFERS\";\n\n\tcase WIFI_REASON_GROUP_CIPHER_INVALID:\n\n\t\treturn \"GROUP_CIPHER_INVALID\";\n\n\tcase WIFI_REASON_PAIRWISE_CIPHER_INVALID:\n\n\t\treturn \"PAIRWISE_CIPHER_INVALID\";\n\n\tcase WIFI_REASON_AKMP_INVALID:\n\n\t\treturn \"AKMP_INVALID\";\n\n\tcase WIFI_REASON_UNSUPP_RSN_IE_VERSION:\n\n\t\treturn \"UNSUPP_RSN_IE_VERSION\";\n\n\tcase WIFI_REASON_INVALID_RSN_IE_CAP:\n\n\t\treturn \"INVALID_RSN_IE_CAP\";\n\n\tcase WIFI_REASON_802_1X_AUTH_FAILED:\n\n\t\treturn \"802_1X_AUTH_FAILED\";\n\n\tcase WIFI_REASON_CIPHER_SUITE_REJECTED:\n\n\t\treturn \"CIPHER_SUITE_REJECTED\";\n\n\tcase WIFI_REASON_BEACON_TIMEOUT:\n\n\t\treturn \"BEACON_TIMEOUT\";\n\n\tcase WIFI_REASON_NO_AP_FOUND:\n\n\t\treturn \"NO_AP_FOUND\";\n\n\tcase WIFI_REASON_AUTH_FAIL:\n\n\t\treturn \"AUTH_FAIL\";\n\n\tcase WIFI_REASON_ASSOC_FAIL:\n\n\t\treturn \"ASSOC_FAIL\";\n\n\tcase WIFI_REASON_HANDSHAKE_TIMEOUT:\n\n\t\treturn \"HANDSHAKE_TIMEOUT\";\n\n\tcase WIFI_REASON_CONNECTION_FAIL:\n\n\t\treturn \"CONNECTION_FAIL\";\n\n\tdefault:\n\n\t\tbreak;\n\n\t}\n\n\n\n\treturn \"Undefined\";\n", "file_path": "components/debug/get_type_string.c", "rank": 28, "score": 44412.16049877397 }, { "content": "#define ON\t\t\t\t\t2\n", "file_path": "components/agro_mesh/modules/app/app_list/outputs/main/main.c", "rank": 29, "score": 44161.15861281762 }, { "content": "#define OFF\t\t\t\t\t1\n", "file_path": "components/agro_mesh/modules/app/app_list/outputs/main/main.c", "rank": 30, "score": 44161.15861281762 }, { "content": "const char* get_wifi_max_tx_power_string(int8_t power){\n\n\tswitch(power){\n\n\t\tcase 78:\n\n\t\t\treturn \"19.5\";\n\n\t\tcase 76:\n\n\t\t\treturn \"19\";\n\n\t\tcase 74:\n\n\t\t\treturn \"18.5\";\n\n\t\tcase 68:\n\n\t\t\treturn \"17\";\n\n\t\tcase 60:\n\n\t\t\treturn \"15\";\n\n\t\tcase 52:\n\n\t\t\treturn \"13\";\n\n\t\tcase 44:\n\n\t\t\treturn \"11\";\n\n\t\tcase 34:\n\n\t\t\treturn \"8.5\";\n\n\t\tcase 28:\n\n\t\t\treturn \"7\";\n\n\t\tcase 20:\n\n\t\t\treturn \"5\";\n\n\t\tcase 8:\n\n\t\t\treturn \"2\";\n\n\t\tcase -4:\n\n\t\t\treturn \"-1\";\n\n\t}\n\n\treturn \"Udenfiend\";\n", "file_path": "components/debug/get_type_string.c", "rank": 31, "score": 43655.50113732899 }, { "content": "#define NOP\t\t\t\t\t0\n", "file_path": "components/agro_mesh/modules/app/app_list/outputs/main/main.c", "rank": 32, "score": 43408.77562353324 }, { "content": "\t\tDayPeriod getDayPeriod(void);\n\n\t\tTimeMode getTimeMode(void);\n\n\t\tint8_t getTimeFuse(void);\n\n\t\tvoid getTime(DateTime *time);\n\n\n\n\t\tvoid getDateTime(DateTime *dateTime);\n\n\n\n\t\tuint32_t getUnixTime(void);\n\n\n\n\t\tbool isLeapYear(void); /*é ano bissexto*/\n\n\n\n\t\tDayOfWeek dayOfWeek(void);\n\n\t\tstatic DayOfWeek dayOfWeek(uint8_t day, uint8_t month, uint16_t year) noexcept;\n\n\n\n\tprotected:\n\n\t\t//Date\n\n\t\tuint8_t _day;\t\t/*0-31*/\n\n\t\tuint8_t _month;\t\t/*1-12*/\n\n\t\tuint16_t _year;\t\t/* XXXX */\n\n\n", "file_path": "components/helper/include/datetime.h", "rank": 33, "score": 43128.65796742075 }, { "content": "\n\n\t\tvoid setDateTime(uint16_t year,\n\n\t\t\t\tuint8_t mouth,\n\n\t\t\t\tuint16_t day,\n\n\t\t\t\tuint8_t hour,\n\n\t\t\t\tuint8_t minute,\n\n\t\t\t\tuint8_t second,\n\n\t\t\t\tDayPeriod period = ND);\n\n\n\n\t\tvoid setUnixTime(uint32_t unixTime);\n\n\n\n\t\t//GET\n\n\t\tuint16_t getYear(void);\n\n\t\tuint8_t getMonth(void);\n\n\t\tuint8_t getDay(void);\n\n\t\tvoid getDate(DateTime *date);\n\n\n\n\t\tuint8_t getHour(void);\n\n\t\tuint8_t getMinute(void);\n\n\t\tuint8_t getSecond(void);\n", "file_path": "components/helper/include/datetime.h", "rank": 34, "score": 43125.09822984024 }, { "content": "\t * @param [in] crc Começo dos dados que será computado.\n\n\t * @return Sucesso ou não no cálculo do CRC\n\n\t * @retval true CRC calculado corresponde.\n\n\t * @retval false CRC calculado não corresponde\n\n\t */\n\n\t static bool check_crc16Dallas(const uint8_t* input, uint16_t len, const uint8_t* inverted_crc, uint16_t crc = 0);\n\n\n\n\t // Compute a Dallas Semiconductor 16 bit CRC. This is required to check\n\n\t // the integrity of data received from many 1-Wire devices. Note that the\n\n\t // CRC computed here is *not* what you'll get from the 1-Wire network,\n\n\t // for two reasons:\n\n\t // 1) The CRC is transmitted bitwise inverted.\n\n\t // 2) Depending on the endian-ness of your processor, the binary\n\n\t // representation of the two-byte return value may have a different\n\n\t // byte order than the two bytes you get from 1-Wire.\n\n\t // @param input - Array of bytes to checksum.\n\n\t // @param len - How many bytes to use.\n\n\t // @param crc - The crc starting value (optional)\n\n\t // @return The CRC16, as defined by Dallas Semiconductor.\n\n\t /**\n", "file_path": "components/crc/include/crc.h", "rank": 35, "score": 43123.162858384516 }, { "content": "#ifndef MY_STRING_H__\n\n#define MY_STRING_H__\n\n\n\n#include <stddef.h>\n\n#include <stdlib.h>\n\n#include <string.h>\n", "file_path": "components/helper/include/my_string.h", "rank": 36, "score": 43119.99697964832 }, { "content": "\t // buf[2] = 0x00; // MSB address\n\n\t // WriteBytes(net, buf, 3); // Write 3 cmd bytes\n\n\t // ReadBytes(net, buf+3, 10); // Read 6 data bytes, 2 0xFF, 2 CRC16\n\n\t // if (!CheckCRC16(buf, 11, &buf[11])) {\n\n\t // // Handle error.\n\n\t // }\n\n\t //\n\n\t // @param input - Array of bytes to checksum.\n\n\t // @param len - How many bytes to use.\n\n\t // @param inverted_crc - The two CRC16 bytes in the received data.\n\n\t // This should just point into the received data,\n\n\t // *not* at a 16-bit integer.\n\n\t // @param crc - The crc starting value (optional)\n\n\t // @return True, iff the CRC matches.\n\n\t /**\n\n\t * \\brief Faz a checagem do CRC de 16 bits\n\n\t *\n\n\t * @param [in] input Bytes que será calculado o CRC.\n\n\t * @param [in] len Tamanho dos bytes que serão computados\n\n\t * @param [in] inverted_crc Deve apontar para o bytes do CRC nos dados recebidos\n", "file_path": "components/crc/include/crc.h", "rank": 37, "score": 43119.76974514567 }, { "content": "#ifndef CRC_H__\n\n#define CRC_H__\n\n\n\n#include <stdint.h>\n\n\n", "file_path": "components/crc/include/crc.h", "rank": 38, "score": 43118.90371523646 }, { "content": "#ifndef\t__DATETIME_H__\n\n#define __DATETIME_H__\n\n\n\n#include <stdio.h>\n\n#include <stdint.h>\n\n\n\ntypedef enum {\n\n\tFORMAT_24H = 0,\n\n\tFORMAT_12H\n\n} TimeMode;\n\n\n\n/*\n\n * Começando a semana em 1, baseado na iso\n\n * https://en.wikipedia.org/wiki/ISO_week_date\n\n */\n\n\n\ntypedef enum {\n\n\tMONDAY = 1,\n\n\tTUESDAY,\n\n\tWEDNEDAY,\n", "file_path": "components/helper/include/datetime.h", "rank": 39, "score": 43118.63799041825 }, { "content": "\t * \\brief Cálculo do CRC de 16 bits\n\n\t *\n\n\t * Faz o cálculo do CRC16 definido pela Dallas Semiconductor.\n\n\t *\n\n\t * @param [in] input Bytes que será calculado o CRC\n\n\t * @param [in] len Número de bytes que será realizado o cálculo.\n\n\t * @param [in] crc Valor que deve-se iniciar o cálculo do CRC\n\n\t * @return O valor do CRC cálculado.\n\n\t */\n\n\t static uint16_t crc16Dallas(const uint8_t* input, uint16_t len, uint16_t crc = 0);\n\n};\n\n\n\n#endif /* CRC_H__ */\n", "file_path": "components/crc/include/crc.h", "rank": 40, "score": 43116.98442419131 }, { "content": "\tTHURSDAY,\n\n\tFRIDAY,\n\n\tSATURDAY,\n\n\tSUNDAY\n\n} DayOfWeek;\n\n\n\ntypedef enum {\n\n\tAM = 0,\t\t\t\t//Antes de meio dia\n\n\tPM,\t\t\t\t\t//Depois de meio dia\n\n\tND\t\t\t\t\t//Nao definido, para formado de 24H\n\n}DayPeriod;\n\n\n", "file_path": "components/helper/include/datetime.h", "rank": 41, "score": 43114.582348884054 }, { "content": "\t\t//Time\n\n\t\tuint8_t _hour;\t\t/*0-11 / 0-23*/\n\n\t\tuint8_t _minute;\t\t/*0-59*/\n\n\t\tuint8_t _second;\t\t/*0-59*/\n\n\t\t//uint16_t _miliseconds;\t/*0-999*/\n\n\t\t//uint16_t _microseconds; /*0-999*/\n\n\n\n\t\tDayPeriod _period;\t\t\t/* ND,AM,PM */\n\n\n\n\t\tTimeMode _timeMode;\t\t\t/* Modo 12 ou 24 horas */\n\n\t\tint8_t _timeFuse;\t\t\t/* Fuso */\n\n};\n\n\n\n#endif /* __DATETIME_H__ */\n", "file_path": "components/helper/include/datetime.h", "rank": 42, "score": 43114.582348884054 }, { "content": "static inline void set_output(gpio_num_t num, uint32_t arg)\n\n{\n\n\tif(arg == OFF)\n\n\t\tgpio_set_level(num, 0);\n\n\telse if(arg == ON)\n\n\t\tgpio_set_level(num, 1);\n", "file_path": "components/agro_mesh/modules/app/app_list/outputs/main/main.c", "rank": 43, "score": 42681.60018379281 }, { "content": "#define ONBOARD_LED \tGPIO_NUM_2\n", "file_path": "components/agro_mesh/modules/app/app_list/led/main/main.c", "rank": 44, "score": 42681.60018379281 }, { "content": "uint32_t local_main(uint32_t arg)\n\n{\n\n\tset_output(AC_LOAD1, SHIFT(1, arg));\n\n\tset_output(AC_LOAD2, SHIFT(2, arg));\n\n\tset_output(AC_LOAD3, SHIFT(3, arg));\n\n\n\n return 0;\n", "file_path": "components/agro_mesh/modules/app/app_list/outputs/main/main.c", "rank": 45, "score": 42681.60018379281 }, { "content": "uint32_t local_main(uint32_t arg)\n\n{\n\n\tgpio_set_level(ONBOARD_LED, arg ? 1 : 0);\n\n return 0;\n", "file_path": "components/agro_mesh/modules/app/app_list/led/main/main.c", "rank": 46, "score": 42681.60018379281 }, { "content": "uint32_t local_main(uint32_t arg)\n\n{\n\n printf(\"Hello world!\\n\");\n\n printf(\"It works args[%u]!!\\n\", arg);\n\n return 2;\n", "file_path": "components/agro_mesh/modules/app/app_list/hello/main/main.c", "rank": 47, "score": 42681.60018379281 }, { "content": "\n\n\t\tvoid strength(gpio_drive_cap_t cap);\n\n\t\tvoid hold(bool hold);\n\n\t\tstatic void deep_sleep_hold(bool hold);\n\n\n\n\t\tvoid* get_isr_args();\n\n\n\n\t\t~GPIO_Basic();\n\n\n\n\tprotected:\n\n\t\tint level = 0;\n\n\t\tgpio_num_t num;\n\n\t\tvoid* isr_args = NULL;\n\n\n\n\t\tstatic unsigned int driver_instaled;\n\n};\n\n\n\ntypedef struct {\n\n\tGPIO_Basic* esse;\n\n\tvoid* args;\n\n}gpio_isr_args_t;\n\n\n\n#endif /* GPIO_H__ */\n", "file_path": "components/peripherals/gpio/include/gpio.h", "rank": 48, "score": 41697.483529295445 }, { "content": " void reset_search(void);\n\n\n\n // Setup the search to find the device type 'family_code' on the next call\n\n // to search(*newAddr) if it is present.\n\n /**\n\n * \\brief Define uma família de dispositivos para realizar a procura no barramento.\n\n *\n\n * @param [in] family_code Família de dispositivos que deseja fazer a procura.\n\n */\n\n void target_search(uint8_t family_code);\n\n\n\n // Look for the next device. Returns 1 if a new address has been\n\n // returned. A zero might mean that the bus is shorted, there are\n\n // no devices, or you have already retrieved all of them. It\n\n // might be a good idea to check the CRC to make sure you didn't\n\n // get garbage. The order is deterministic. You will always get\n\n // the same devices in the same order.\n\n /**\n\n * \\brief Procura o próximo dispositivo presente no barramento.\n\n *\n", "file_path": "components/protocols/onewire/include/onewire.h", "rank": 49, "score": 41694.163025499016 }, { "content": "\t\t};\n\n\n\n\t\tvirtual ~BME280(){}\n\n\n\n\t\tint get_mode(BME280::Mode *mode);\n\n\t\tint set_mode(BME280::Mode mode);\n\n\n\n\t\tint config(settings* settings);\n\n\n\n\t\tint get_data(uint8_t sensor_comp, data *comp_data);\n\n\n\n\t\tvirtual int soft_reset();\n\n\n\n\t\tuint8_t get_chip_id();\n\n\t\tint check_chip_id();\n\n\n\n\tprotected:\n\n\t\tcalib_data calib_data;\n\n\n\n\t\tint get_calib_data();\n", "file_path": "components/modules/bme280/include/bme280.h", "rank": 50, "score": 41693.4720790207 }, { "content": "\n\n\t\tint set_sleep_mode();\n\n\n\n\t\tint write_power_mode(uint8_t sensor_mode);\n\n\n\n\t\tint reload_device_settings(const settings *settings);\n\n\n\n\t\tint set_filter_standby_settings(const settings *settings);\n\n\t\tint set_osr_settings(const settings *settings);\n\n\t\tint set_osr_humidity_settings(const settings *settings);\n\n\t\tint set_osr_press_temp_settings(const settings *settings);\n\n\n\n\t\tvirtual int read_command(uint8_t cmd, uint8_t* aws, unsigned int length) = 0;\n\n\t\tvirtual int write_command(uint8_t cmd, uint8_t* data, unsigned int length) = 0;\n\n};\n\n\n\n#endif /* BME280_H__ */\n", "file_path": "components/modules/bme280/include/bme280.h", "rank": 51, "score": 41692.23401790189 }, { "content": " private:\n\n\t/**\n\n\t * \\brief Define a porta digital que será utilizada para barramento dos dispositivos\n\n\t */\n\n GPIO_Basic *gpio;\n\n\n\n // global search state\n\n unsigned char ROM_NO[8];\n\n uint8_t LastDiscrepancy;\n\n uint8_t LastFamilyDiscrepancy;\n\n uint8_t LastDeviceFlag;\n\n};\n\n\n\n/**@}*/\n\n\n\n#endif /* ONEWIRE_H__ */\n", "file_path": "components/protocols/onewire/include/onewire.h", "rank": 52, "score": 41689.879547224315 }, { "content": " // @param inverted_crc - The two CRC16 bytes in the received data.\n\n // This should just point into the received data,\n\n // *not* at a 16-bit integer.\n\n // @param crc - The crc starting value (optional)\n\n // @return True, iff the CRC matches.\n\n /**\n\n * \\brief Faz a checagem do CRC de 16 bits\n\n *\n\n * @param [in] input Bytes que será calculado o CRC.\n\n * @param [in] len Tamanho dos bytes que serão computados\n\n * @param [in] inverted_crc Deve apontar para o bytes do CRC nos dados recebidos\n\n * @param [in] crc Começo dos dados que será computado.\n\n * @return Sucesso ou não no cálculo do CRC\n\n * @retval true CRC calculado corresponde.\n\n * @retval false CRC calculado não corresponde\n\n */\n\n static bool check_crc16(const uint8_t* input, uint16_t len, const uint8_t* inverted_crc, uint16_t crc = 0){\n\n \treturn CRC::check_crc16Dallas(input,len,inverted_crc,crc);\n\n }\n\n\n", "file_path": "components/protocols/onewire/include/onewire.h", "rank": 53, "score": 41689.68594492519 }, { "content": " * @return Bit lido.\n\n */\n\n uint8_t read_bit(void);\n\n\n\n // Stop forcing power onto the bus. You only need to do this if\n\n // you used the 'power' flag to write() or used a write_bit() call\n\n // and aren't about to do another read or write. You would rather\n\n // not leave this powered if you don't have to, just in case\n\n // someone shorts your bus.\n\n /**\n\n * \\brief Para o fornecimento de corrente no barramento, para dispositivos em modo parasita.\n\n *\n\n * \\note Modo parasita é quando a alimentação do dispositivo é feito pelo barramento de dados.\n\n */\n\n void depower(void);\n\n\n\n // Clear the search state so that if will start from the beginning again.\n\n /**\n\n * \\brief Limpa os valores de estado de busca de dispositivos.\n\n */\n", "file_path": "components/protocols/onewire/include/onewire.h", "rank": 54, "score": 41689.42924582473 }, { "content": "#include <stddef.h>\n\n#include <stdlib.h>\n\n#include <string.h>\n\nclass My_String{\n\n\tpublic:\n\n\t\tMy_String(size_t size);\n\n\t\tMy_String(const char* str);\n\n\t\tMy_String(const char* str, size_t len);\n\n\t\t~My_String();\n\n\n\n\t\tint substring(char* buffer, const char* delimiter, size_t pos = 0);\n\n\t\tint substring_console(char* buffer, const char* delimiter, size_t pos = 0);\n\n\n\n\t\tbool operator==(const My_String& a){\n\n\t\t\treturn (this->len == a.len) && strncmp(this->str, a.str, this->len) == 0;\n\n\t\t}\n\n\n\n\tprotected:\n\n\t\tchar* str;\n\n\t\tsize_t len;\n\n\t\tsize_t size;\n\n};\n\n\n\n\n\n#endif /* MY_STRING_H__ */\n", "file_path": "components/helper/include/my_string.h", "rank": 55, "score": 41689.3855477309 }, { "content": " *\n\n * Executa o comando SKIP_ROM, definindo o próximo comando de função para todos\n\n * os dipositivos que estão no barramento.\n\n */\n\n void skip(void);\n\n\n\n // Write a byte. If 'power' is one then the wire is held high at\n\n // the end for parasitically powered devices. You are responsible\n\n // for eventually depowering it by calling depower() or doing\n\n // another read or write.\n\n /**\n\n * \\brief Escreve um byte no barramento.\n\n *\n\n * @param [in] v Byte que será escrito\n\n * @param [in] power Utilizar 1 para quando o dispositivo está em modo parasita. Valor padrão: \\b 0.\n\n *\n\n * \\note Modo parasita é quando a alimentação do dispositivo é feito pelo barramento de dados.\n\n */\n\n void write(uint8_t v, uint8_t power = 0);\n\n\n", "file_path": "components/protocols/onewire/include/onewire.h", "rank": 56, "score": 41689.35988227624 }, { "content": "#ifndef BME280_H__\n\n#define BME280_H__\n\n\n\n#include <stdint.h>\n\n#include \"sdkconfig.h\"\n\n\n\n#ifdef CONFIG_BME280_FLOAT_ENABLE\n\n#\tdefine BME280_FLOAT_ENABLE\n\n#else\n\n#\tif CONFIG_BME280_64BIT_ENABLE\n\n#\t\tdefine BME280_64BIT_ENABLE\t\t1\n\n#\tendif /* CONFIG_BME280_64BIT_ENABLE */\n\n#endif /* CONFIG_BME280_FLOAT_ENABLE */\n\n\n\n#define BME280_ERR_OK\t\t\t\t1\n\n#define BME280_ERR_CHIP_ID\t\t\t-1\n\n#define BME280_ERR_INIT_ADDR\t\t-2\n\n#define BME280_ERR_SOFT_RESET\t\t-3\n\n#define BME280_ERR_SOFT_RESET_WAIT\t-4\n\n#define BME280_ERR_CALIB_DATA\t\t-5\n", "file_path": "components/modules/bme280/include/bme280.h", "rank": 57, "score": 41689.10853130825 }, { "content": "#define BME280_ERR_INVALID_OSR\t\t-6\n\n#define BME280_ERR_CONFIG_SAMP\t\t-7\n\n#define BME280_ERR_CONFIG_FIL_STAND\t-8\n\n#define BME_ERR_GET_DATA\t\t\t-9\n\n\n\n/*\n\n * Data choose\n\n */\n\n#define BME280_PRESS (1)\n\n#define BME280_TEMP (1 << 1)\n\n#define BME280_HUM (1 << 2)\n\n#define BME280_ALL (0x07)\n\n\n\n/**\n\n * Config\n\n */\n\n#define BME280_OSR_PRESS_SEL (1)\n\n#define BME280_OSR_TEMP_SEL (1 << 1)\n\n#define BME280_OSR_HUM_SEL (1 << 2)\n\n#define BME280_FILTER_SEL (1 << 3)\n\n#define BME280_STANDBY_SEL (1 << 4)\n\n#define BME280_ALL_SETTINGS_SEL (0x1F)\n\n\n", "file_path": "components/modules/bme280/include/bme280.h", "rank": 58, "score": 41689.06029093481 }, { "content": "\n\n/**\n\n * \\defgroup onewire ONEWIRE\n\n *\n\n * \\brief Definição da classe, tipos e macros referente ao protocolo ONEWIRE.\n\n * @{\n\n */\n\n\n\n/*\n\n * TODO Criar/Utilziar classe genérica CRC\n\n */\n\n\n\n#define FALSE 0\n\n#define TRUE 1\n\n\n\n// Platform specific I/O definitions\n\n\n\n#include <stdint.h>\n\n#include \"gpio.h\"\n\n#include \"crc.h\"\n", "file_path": "components/protocols/onewire/include/onewire.h", "rank": 59, "score": 41688.48384960031 }, { "content": "#ifndef PWM_H__\n\n#define PWM_H__\n\n\n\n#include \"driver/ledc.h\"\n\n#include <stdint.h>\n\n#include \"driver/gpio.h\"\n\n\n\n/**\n\n * TODO Testar todas as funcoes\n\n * TODO criar mais metodos de manipulacao (interrpucoes)\n\n */\n\n\n\n#define PWM_ERR_OK\t\t1\n\n#define PWM_ERR_CHANNEL\t-1\n\n#define PWM_ERR_TIMER\t-2\n\n\n", "file_path": "components/peripherals/pwm/include/pwm.h", "rank": 60, "score": 41688.30861205707 }, { "content": " */\n\n static uint8_t crc8(const uint8_t *addr, uint8_t len){\n\n \treturn CRC::crc8Dallas(addr,len);\n\n }\n\n\n\n // Compute the 1-Wire CRC16 and compare it against the received CRC.\n\n // Example usage (reading a DS2408):\n\n // // Put everything in a buffer so we can compute the CRC easily.\n\n // uint8_t buf[13];\n\n // buf[0] = 0xF0; // Read PIO Registers\n\n // buf[1] = 0x88; // LSB address\n\n // buf[2] = 0x00; // MSB address\n\n // WriteBytes(net, buf, 3); // Write 3 cmd bytes\n\n // ReadBytes(net, buf+3, 10); // Read 6 data bytes, 2 0xFF, 2 CRC16\n\n // if (!CheckCRC16(buf, 11, &buf[11])) {\n\n // // Handle error.\n\n // }\n\n //\n\n // @param input - Array of bytes to checksum.\n\n // @param len - How many bytes to use.\n", "file_path": "components/protocols/onewire/include/onewire.h", "rank": 61, "score": 41687.62546359646 }, { "content": "#ifndef GPIO_H__\n\n#define GPIO_H__\n\n\n\n#include \"driver/gpio.h\"\n\n\n\n/**\n\n * TODO fazer melhor controle da variavel driver_instaled, que contém quantos dispositivos\n\n * \testao se utilizando do driver de interrucao\n\n */\n\n\n", "file_path": "components/peripherals/gpio/include/gpio.h", "rank": 62, "score": 41686.974420907754 }, { "content": " * \\brief Lê vários bytes do barramento.\n\n *\n\n * @param [out] buf Bytes lidos.\n\n * @param [in] count número de bytes que deve ser lidos\n\n */\n\n void read_bytes(uint8_t *buf, uint16_t count);\n\n\n\n // Write a bit. The bus is always left powered at the end, see\n\n // note in write() about that.\n\n /**\n\n * \\brief Escreve um bit no modo definido pelo protocolo onewire\n\n *\n\n * @param [in] v Bit que será escrito.\n\n */\n\n void write_bit(uint8_t v);\n\n\n\n // Read a bit.\n\n /**\n\n * \\brief Lê um bit no modo definido pelo protocolo onewire.\n\n *\n", "file_path": "components/protocols/onewire/include/onewire.h", "rank": 63, "score": 41686.92637640253 }, { "content": " /**\n\n * \\brief Escreve vários bytes no barramento.\n\n *\n\n * @param [in] buf Bytes que será enviados\n\n * @param [in] count Número de bytes que será enviados\n\n * @param [in] power Utilizar 1 para quando o dispositivo está em modo parasita. Valor padrão: \\b 0.\n\n *\n\n * \\note Modo parasita é quando a alimentação do dispositivo é feito pelo barramento de dados.\n\n */\n\n void write_bytes(const uint8_t *buf, uint16_t count, bool power = 0);\n\n\n\n // Read a byte.\n\n /**\n\n * \\brief Lê um byte do barramento.\n\n *\n\n * @return Byte lido.\n\n */\n\n uint8_t read(void);\n\n\n\n /**\n", "file_path": "components/protocols/onewire/include/onewire.h", "rank": 64, "score": 41686.92637640253 }, { "content": "#ifdef BME280_FLOAT_ENABLE\n\n\t\tstruct data{\n\n\t\t\tdouble pressure;\t\t\t/*! Compensated pressure */\n\n\t\t\tdouble temperature;\t\t\t/*! Compensated temperature */\n\n\t\t\tdouble humidity;\t\t\t/*! Compensated humidity */\n\n\t\t};\n\n#else\t/* BME280_FLOAT_ENABLE */\n\n\t\tstruct data{\n\n\t\t\tuint32_t pressure;\t\t /*! Compensated pressure */\n\n\t\t int32_t temperature;\t\t/*! Compensated temperature */\n\n\t\t uint32_t humidity;\t\t /*! Compensated humidity */\n\n\t\t};\n\n#endif /* BME280_FLOAT_ENABLE */\n\n\t\tstruct settings{\n\n\t\t\tuint8_t desired_set;\n\n\t\t\tSampling osr_p;\t\t\t\t\t/*! pressure oversampling */\n\n\t\t\tSampling osr_t;\t\t\t\t\t/*! temperature oversampling */\n\n\t\t\tSampling osr_h;\t\t\t\t\t/*! humidity oversampling */\n\n\t\t\tIIR_Filter_Coeficient filter;\t/*! filter coefficient */\n\n\t\t\tStand_By_Time_ms standby_time; \t/*! standby time */\n", "file_path": "components/modules/bme280/include/bme280.h", "rank": 65, "score": 41686.91232563378 }, { "content": "\t\t\tFILTER_COEF_16\t\t\t= 0b100,\n\n\t\t};\n\n\n\n\t\tenum Sampling{\n\n\t\t\tSKIPPING\t\t\t\t= 0b000,\n\n\t\t\tOVERSAMPLING_X1\t\t\t= 0b001,\n\n\t\t\tOVERSAMPLING_X2\t\t\t= 0b010,\n\n\t\t\tOVERSAMPLING_X4\t\t\t= 0b011,\n\n\t\t\tOVERSAMPLING_X8\t\t\t= 0b100,\n\n\t\t\tOVERSAMPLING_X16\t\t= 0b101,\n\n\t\t};\n\n\n\n\t\tenum Mode{\n\n\t\t\tSLEEP \t\t\t\t\t= 0b00,\n\n\t\t\tFORCED \t\t\t\t\t= 0b01,\n\n\t\t\tNORMAL \t\t\t\t\t= 0b11\n\n\t\t};\n\n\n\n\t\tstruct calib_data{\n\n\t\t\tuint16_t dig_T1;\n", "file_path": "components/modules/bme280/include/bme280.h", "rank": 66, "score": 41686.67214496429 }, { "content": " * @retval 0 Não foi recebido um sinal de resposta \\a pulse\n\n * @retval 1 Sinal de presença \\a pulse recebido com sucesso\n\n */\n\n uint8_t reset(void);\n\n\n\n // Issue a 1-Wire rom select command, you do the reset first.\n\n /**\n\n * \\brief Executa o comando para selecionar um dos dispositivos no barramento\n\n *#if ONEWIRE_SEARCH\n\n *\n\n * Executa o comando de rom MATCH_ROM. Após o envio do comando, é enviado 8 bytes\n\n * com o enderço do dispositivo desejado.\n\n *\n\n * @param [in] rom Endereço do dispositivo que deseja selecionar\n\n */\n\n void select(const uint8_t rom[8]);\n\n\n\n // Issue a 1-Wire rom skip command, to address all on bus.\n\n /**\n\n * \\brief Endereça um comando a todos no barramento.\n", "file_path": "components/protocols/onewire/include/onewire.h", "rank": 67, "score": 41686.67224901127 }, { "content": "\n\n// ROM commands - Comandos para endereçar dispositivos\n\n#define SEARCH_ROM\t\t\t0xF0\t//!< Comando para determinar todos os dispositivos e tipos de dispositivos conectados\n\n#define READ_ROM\t\t\t0x33\t//!< Comando para ler a ROM code quando há apenas 1 dispositivo\n\n#define MATCH_ROM\t\t\t0x55\t//!< Comando para selecionar apenas 1 dispositivo que irá receber um comando de função\n\n#define SKIP_ROM\t\t\t0xCC\t//!< Comando para selecionar todos os dispositivos que irão receber um comando de função\n\n#define ALARM_SEARCH\t\t0xEC\t//!< Comando para que todos os dispositivos verifiquem se houve uma condição de alarme na última conversão\n\n\n\n/**\n\n * \\brief Classe que define os membros e métodos para utilização do protocolo ONEWIRE\n\n *\n\n * Nesta classe é definido os comandos de leitura e escrita pelo protocolo, utilizando\n\n * uma porta digital. Também são definidos as operações de ROM do protocolo.\n\n */\n", "file_path": "components/protocols/onewire/include/onewire.h", "rank": 68, "score": 41683.72470327513 }, { "content": " * Os dispositivos são encontrados de forma determinística (os dispositivos são\n\n * sempre encontrados na mesma ordem.\n\n *\n\n * @param [out] newAddr Endereço do dispositivo encontrado.\n\n * @return Sucesso ou não na procura do dispositivo.\n\n * @retval 1 Um novo dispositivo foi encontrado.\n\n * @retval 0 Foi encontrado todos os dispositivos, não há dispositivos ou o barramento está em curto.\n\n */\n\n uint8_t search(uint8_t *newAddr);\n\n\n\n // Compute a Dallas Semiconductor 8 bit CRC, these are used in the\n\n // ROM and scratchpad registers.\n\n /**\n\n * \\brief Cálculo do CRC de 8 bits.\n\n *\n\n * Faz o calculo do CRC de 8 bits baseado no algorítimo da Dallas Semiconductors.\n\n *\n\n * @param [in] addr Bytes que será calculado o CRC.\n\n * @param [in] len Número de bytes que será computado.\n\n * @return O valor do CRC cálculado.\n", "file_path": "components/protocols/onewire/include/onewire.h", "rank": 69, "score": 41683.72470327513 }, { "content": "class CRC{\n\n\tpublic:\n\n\t\t// Compute a Dallas Semiconductor 8 bit CRC, these are used in the\n\n\t // ROM and scratchpad registers.\n\n\t /**\n\n\t * \\brief Cálculo do CRC de 8 bits.\n\n\t *\n\n\t * Faz o calculo do CRC de 8 bits baseado no algorítimo da Dallas Semiconductors.\n\n\t *\n\n\t * @param [in] addr Bytes que será calculado o CRC.\n\n\t * @param [in] len Número de bytes que será computado.\n\n\t * @return O valor do CRC cálculado.\n\n\t */\n\n\t static uint8_t crc8Dallas(const uint8_t *addr, uint8_t len);\n\n\t // Compute the 1-Wire CRC16 and compare it against the received CRC.\n\n\t // Example usage (reading a DS2408):\n\n\t // // Put everything in a buffer so we can compute the CRC easily.\n\n\t // uint8_t buf[13];\n\n\t // buf[0] = 0xF0; // Read PIO Registers\n\n\t // buf[1] = 0x88; // LSB address\n", "file_path": "components/crc/include/crc.h", "rank": 70, "score": 41683.72470327513 }, { "content": "\t\t\tint16_t dig_T2;\n\n\t\t\tint16_t dig_T3;\n\n\t\t\tuint16_t dig_P1;\n\n\t\t\tint16_t dig_P2;\n\n\t\t\tint16_t dig_P3;\n\n\t\t\tint16_t dig_P4;\n\n\t\t\tint16_t dig_P5;\n\n\t\t\tint16_t dig_P6;\n\n\t\t\tint16_t dig_P7;\n\n\t\t\tint16_t dig_P8;\n\n\t\t\tint16_t dig_P9;\n\n\t\t\tuint8_t dig_H1;\n\n\t\t\tint16_t dig_H2;\n\n\t\t\tuint8_t dig_H3;\n\n\t\t\tint16_t dig_H4;\n\n\t\t\tint16_t dig_H5;\n\n\t\t\tint8_t dig_H6;\n\n\t\t\tint32_t t_fine;\n\n\t\t};\n\n\n", "file_path": "components/modules/bme280/include/bme280.h", "rank": 71, "score": 41683.72470327513 }, { "content": "#ifndef ONEWIRE_H__\n\n#define ONEWIRE_H__\n\n\n\n/**\n\n * \\file\n\n * \\brief Biblioteca para utilização do protocolo onewire\n\n *\n\n * O protocolo OneWire é um protocolo onde pode-se ler/controlar inúmeros\n\n * dispositivos em um mesmo barramento. Utiliza apenas uma porta digital (GPIO)\n\n * para sinalização, podendo enviar comandos para todos os dispositivo no barramento,\n\n * ou para um específico, através do endereço do dispositivo.\n\n *\n\n * Criado pela <i>Dallas Semiconductor</i> (adquirida pela \\a Maxim) para os sensores\n\n * de temperatura DS1820, DS18S20 e DS18B20.\n\n *\n\n * Referência: <a href=\"https://www.maximintegrated.com/en/products/digital/one-wire.html\">ONEWIRE</a>\n\n *\n\n * \\author Rafael Cunha <[email protected]>\n\n * \\date 06/2016\n\n */\n", "file_path": "components/protocols/onewire/include/onewire.h", "rank": 72, "score": 41683.72470327513 }, { "content": "\n\n\tprotected:\n\n\t\tI2C_Master *_i2c;\n\n\n\n\t\tuint8_t _time_mode;\n\n\n\n\t\tvoid _send(uint8_t reg, uint8_t* data, size_t length);\n\n\t\tvoid _send(uint8_t reg, uint8_t data);\n\n\n\n\t\tvoid _receive(uint8_t reg, uint8_t* data, size_t length);\n\n\t\tuint8_t _receive(uint8_t reg);\n\n\n\n\t\tvoid _set_bit_reg(uint8_t reg, uint8_t bit_mask, bool value = true);\n\n\t\tuint8_t _get_bit_reg(uint8_t reg, uint8_t bit_mask);\n\n\n\n\t\tstatic uint8_t _decode(uint8_t value);\n\n\t\tstatic uint8_t _decodeH(uint8_t value);\n\n\t\tstatic uint8_t _decodeY(uint8_t value);\n\n\t\tstatic uint8_t _encode(uint8_t value);\n\n};\n\n\n\n/**@}*/\n\n\n\n#endif /* __DS3231_H__ */\n", "file_path": "components/modules/ds3231/include/ds3231.hpp", "rank": 73, "score": 40368.897762161585 }, { "content": "\n\n\t\tint get_temp(MPU60X0_FLOAT_TYPE* temp);\n\n\t\tint get_acc_data(Acc_Scale scale, Axis_Float* data);\n\n\t\tint get_gyro_data(Gyro_Scale scale, Axis_Float* data);\n\n\n\n\t\tint read_fifo_data(uint8_t* data, unsigned int length);\n\n\n\n\t\tuint8_t who_am_i();\n\n\t\tint check_chip_id();\n\n\n\n\t\tstatic unsigned int get_fifo_raw_data(settings* set,\n\n\t\t\t\tuint8_t* data, unsigned int length,\n\n\t\t\t\tint16_t* temp, Axis* acc = NULL, Axis* gyro = NULL);\n\n\n\n\t\tstatic unsigned int get_fifo_data(settings* set,\n\n\t\t\t\tuint8_t* data, unsigned int length,\n\n\t\t\t\tMPU60X0_FLOAT_TYPE* temp, Axis_Float* acc = NULL, Axis_Float* gyro = NULL);\n\n\n\n\t\tstatic MPU60X0_FLOAT_TYPE convert_temp_data(int16_t data);\n\n\n", "file_path": "components/modules/mpu60X0/include/mpu60x0.h", "rank": 74, "score": 40365.00830819033 }, { "content": "\n\n\t\tstatic void mac(mesh_addr_t*);\n\n\t\tstatic void mac_ap(mesh_addr_t*);\n\n\t\tstatic void parent(mesh_addr_t*);\n\n\t\tstatic void id(mesh_addr_t*);\n\n\n\n\t\tstatic int layer();\n\n\n\n\t\tstatic void post_toDS_state(bool);\n\n\n\n\t\t//to root\n\n\t\tstatic esp_err_t send_to(mesh_data_t*);\n\n\t\t//to external networt\n\n\t\tstatic esp_err_t send_to(const char* ip, uint16_t port, mesh_data_t*);\n\n\t\tstatic esp_err_t send_to(uint32_t ip, uint16_t port, mesh_data_t*);\n\n\n\n\t\tstatic esp_err_t send_to(mesh_addr_t*, mesh_data_t*, int flag = MESH_DATA_TODS);\n\n\n\n\t\tstatic void set_to_send(mesh_addr_t* to);\n\n\t\tstatic esp_err_t to_send(mesh_data_t*, int flag = MESH_DATA_TODS);\n", "file_path": "components/mesh/include/mesh/node.hpp", "rank": 75, "score": 40364.578071981734 }, { "content": "#ifndef HELPER_TYPES_HPP__\n\n#define HELPER_TYPES_HPP__\n\n\n\n#include <cstdlib>\n\n#include <type_traits>\n\n\n\ntemplate<typename T>\n\nconstexpr T swap_byte_order(T t){\n\n\tstatic_assert(std::is_trivial<T>::value, \"Type T must be trivial\");\n\n\n\n\tunion u{\n\n\t\tT ut;\n\n\t\tchar ct[sizeof(T)];\n\n\n\n\t\tu(){}\n\n\t} un, to;\n\n\tun.ut = t;\n\n\tto.ut = 0;\n\n\tstd::size_t s = sizeof(T);\n\n\n\n\tfor(int i = 0; i < s; i++) to.ct[s - i - 1] = un.ct[i];\n\n\n\n\treturn to.ut;\n\n}\n\n\n\n#endif /*HELPER_TYPES_HPP__*/\n", "file_path": "components/helper/include/helper/types.hpp", "rank": 76, "score": 40360.336881876654 }, { "content": "\n\n\t\tstatic void ds_state(bool connected);\n\n\t\tstatic bool ds_state();\n\n\n\n\t\tstatic void tods_cb_arg(void*);\n\n\t\tstatic void fromds_cb_arg(void*);\n\n\n\n\t\tstatic void* tods_cb_arg(void);\n\n\t\tstatic void* fromds_cb_arg(void);\n\n\n\n\t\tstatic void register_event(int32_t event_id,\n\n \tesp_event_handler_t event_handler,\n\n\t\t\t\t\tvoid *event_handler_arg);\n\n\n\n\t\tstatic void unregister_event(int32_t event_id,\n\n\t\t\t\t\t\t\t\tesp_event_handler_t event_handler);\n\n\tprivate:\n\n\t\tstatic void* tods_arg;\n\n\t\tstatic void* fromds_arg;\n\n};\n", "file_path": "components/mesh/include/mesh/node.hpp", "rank": 77, "score": 40360.209588800426 }, { "content": "\n\n\t\tenum Config{\n\n\t\t\tSTANDBY_TIME\t \t\t= 5,\n\n\t\t\tIRR_FILTER_CONST\t\t= 2,\n\n\t\t\tSPI_3_WIRE\t\t\t\t= 0\n\n\t\t};\n\n\n\n\t\tstatic const uint8_t TEMP_PRESS_CALIB_DATA_LEN = 26;\n\n\t\tstatic const uint8_t HUMIDITY_CALIB_DATA_LEN = 7;\n\n\t\tstatic const uint8_t P_T_H_DATA_LEN = 8;\n\n\n\n};\n\n\n\n#endif /* BME280_DEFS_H__ */\n", "file_path": "components/modules/bme280/include/bme280_defs.h", "rank": 78, "score": 40357.32293488031 }, { "content": "\t\tstatic MPU60X0_FLOAT_TYPE convert_acc_data(Acc_Scale scale, int16_t data);\n\n\t\tstatic MPU60X0_FLOAT_TYPE convert_acc_data(settings* scale, int16_t data);\n\n\n\n\t\tstatic MPU60X0_FLOAT_TYPE convert_gyro_data(Gyro_Scale scale, int16_t data);\n\n\t\tstatic MPU60X0_FLOAT_TYPE convert_gyro_data(settings* scale, int16_t data);\n\n\tprotected:\n\n\t\tI2C_Master *i2c;\n\n\t\tuint8_t slave_addr;\n\n\n\n\t\tint write_command(uint8_t reg, uint8_t* data, unsigned int len);\n\n\t\tint read_command(uint8_t reg, uint8_t* data, unsigned int len);\n\n};\n\n\n\n#endif /* MPU60X0_H__ */\n", "file_path": "components/modules/mpu60X0/include/mpu60x0.h", "rank": 79, "score": 40357.214905172914 }, { "content": "#ifndef BME280_DEFS_H__\n\n#define BME280_DEFS_H__\n\n\n\n#define SLAVE_ADDR_BASE\t\t \t0b01110110\n\n\n\n#define BME280_GET_BITS(reg_data, bitname) ((reg_data & (bitname##_MSK)) >> \\\n\n (bitname##_POS))\n\n#define BME280_GET_BITS_POS_0(reg_data, bitname) (reg_data & (bitname##_MSK))\n\n\n\n#define BME280_SET_BITS(reg_data, bitname, data) \\\n\n ((reg_data & ~(bitname##_MSK)) | \\\n\n ((data << bitname##_POS) & bitname##_MSK))\n\n#define BME280_SET_BITS_POS_0(reg_data, bitname, data) \\\n\n ((reg_data & ~(bitname##_MSK)) | \\\n\n (data & bitname##_MSK))\n\n\n\n/**\\name Macros for bit masking */\n\n#define BME280_SENSOR_MODE_MSK (0x03)\n\n#define BME280_SENSOR_MODE_POS (0x00)\n\n\n", "file_path": "components/modules/bme280/include/bme280_defs.h", "rank": 80, "score": 40354.698657217145 }, { "content": "#ifndef MPU60X0_H__\n\n#define MPU60X0_H__\n\n\n\n#include \"i2c_master.h\"\n\n#include <stdint.h>\n\n\n\n/**\n\n * TODO Usar as interrupcoes\n\n *\n\n * TODO Verificar cycle mode. Nao esta funcionando corretamente\n\n */\n\n\n\n/**\n\n * Pinos:\n\n * AD0: bit 0 (LSB) do endereço I2C\n\n */\n\n\n\n#define MPU60X0_ERR_OK\t\t\t\t1\n\n#define MPU60X0_ERR_DEV_NOT_FOUND\t-1\n\n#define MPU60X0_ERR_DATA_ERROR\t\t-2\n\n#define MPU60X0_ERR_CONFIG_ERROR\t-3\n\n#define MPU60X0_ERR_READ_FIFO_SIZE\t-4\n\n#define MPU60X0_ERR_READ_FIFO_DATA\t-5\n\n\n\n#define MPU60X0_FLOAT_TYPE\t\t\tdouble\n\n#define MPU60X0_BUFFER_SIZE\t\t\t1024\n\n\n", "file_path": "components/modules/mpu60X0/include/mpu60x0.h", "rank": 81, "score": 40354.22421786316 }, { "content": "\n\n\t\t\tuint8_t pwr_mgmt_1;\n\n\t\t\tuint8_t pwr_mgmt_2;\n\n\t\t\tuint8_t config;\n\n\t\t\tuint8_t sample_rate_div;\n\n\t\t\tuint8_t fifo_en;\n\n\t\t\tAcc_Scale acc;\n\n\t\t\tGyro_Scale gyro;\n\n\t\t};\n\n\n\n\t\tMPU60X0(I2C_Master *i2c);\n\n\n\n\t\tint init();\n\n\t\tint init(bool ad0);\n\n\n\n\t\tint config(settings* set);\n\n\n\n\t\tint get_temp_raw_data(int16_t* data);\n\n\t\tint get_acc_raw_data(Axis* data);\n\n\t\tint get_gyro_raw_data(Axis* data);\n", "file_path": "components/modules/mpu60X0/include/mpu60x0.h", "rank": 82, "score": 40353.738048583175 }, { "content": "#ifndef MESH_TYPES_HPP__\n\n#define MESH_TYPES_HPP__\n\n\n\n#include <stdint.h>\n\n#include \"esp_mesh.h\"\n\n\n\nnamespace Mesh{\n\n\n\n//#define MESH_ADDR_SIZE\t\t6\n\n//typedef uint8_t mesh_addr[MESH_ADDR_SIZE];\n\n\n", "file_path": "components/mesh/include/mesh/types.hpp", "rank": 83, "score": 40353.509665747435 }, { "content": "\t\tuint8_t getTimeMode();\n\n\n\n\t\tvoid setDOW(uint8_t dow);\n\n\t\tuint8_t getDOW();\n\n\n\n\t\tvoid enable32kHz(bool enable);\n\n\n\n\t\tvoid enableInterrupt(uint8_t enable = true);\n\n\t\tvoid enableSQWRate(DS3231SQWrate rate, uint8_t enable = true);\n\n\n\n\t\tvoid enableAlarm2Int(bool enable = true);\n\n\t\tvoid enableAlarm1Int(bool enable = true);\n\n\n\n\t\tuint8_t clearAlarmFlags();\n\n\n\n\t\tvoid configAlarm2(DS3231Alarm2Config type_alarm, DateTime *dateTime = NULL);\n\n\t\tvoid configAlarm1(DS3231Alarm1Config type_alarm, DateTime *dateTime = NULL);\n\n\n\n\t\tvoid startConvTemp();\n\n\t\tfloat getTemp();\n", "file_path": "components/modules/ds3231/include/ds3231.hpp", "rank": 84, "score": 40353.34113893453 }, { "content": "#ifndef MESH_NODE_HPP__\n\n#define MESH_NODE_HPP__\n\n\n\n#include <stdint.h>\n\n#include \"types.hpp\"\n\n\n\n#include \"esp_mesh.h\"\n\n#include \"esp_err.h\"\n\n\n\n#include \"esp_netif_types.h\"\n\n\n\nnamespace Mesh{\n\n\n", "file_path": "components/mesh/include/mesh/node.hpp", "rank": 85, "score": 40350.29065691281 }, { "content": "#ifndef BME280_SPI_H__\n\n#define BME280_SPI_H__\n\n\n\n#include <stdint.h>\n\n#include \"bme280.h\"\n\n\n\n#include \"driver/spi_master.h\"\n\n\n\n#define BME280_SPI_ERR_INIT_BUS\t\t-1\n\n#define BME280_SPI_ERR_INIT_DEV\t\t-2\n\n\n", "file_path": "components/modules/bme280/include/bme280_spi.h", "rank": 86, "score": 40349.64097350253 }, { "content": "#ifndef BME280_SPI_3W_H__\n\n#define BME280_SPI_3W_H__\n\n\n\n#include <stdint.h>\n\n#include \"bme280.h\"\n\n\n\n#include \"driver/spi_master.h\"\n\n\n\n#define BME280_SPI_3W_ERR_CONFIG\t\t-1\n\n#define BME280_SPI_3W_ERR_INIT_BUS\t\t-2\n\n#define BME280_SPI_3W_ERR_INIT_DEV\t\t-3\n\n\n", "file_path": "components/modules/bme280/include/bme280_spi3w.h", "rank": 87, "score": 40349.34503566688 }, { "content": "#ifndef BME280_I2C_H__\n\n#define BME280_I2C_H__\n\n\n\n#include \"i2c_master.h\"\n\n#include \"bme280.h\"\n\n\n\n/**\n\n * Pinos:\n\n * CSB: VDDIO para selecionar I2C;\n\n * SDO: Bit 0 do endereço I2C\n\n */\n\n\n", "file_path": "components/modules/bme280/include/bme280_i2c.h", "rank": 88, "score": 40349.12739260559 }, { "content": " *\n\n * TODO Testar implementação para modo de 12h (AM/PM)\n\n *\n\n * \\author Rafael Cunha <[email protected]>\n\n * \\date 07/2016\n\n */\n\n\n\n/**\n\n * \\defgroup ds3231 DS3231\n\n *\n\n * \\brief Definição da classe, tipos e macros referente a utilização de LCDs.\n\n * @{\n\n */\n\n\n\n/*\n\n * TODO Criar helper class DateTime, Convert, BitWise\n\n */\n\n\n\n#include \"datetime.h\"\n\n#include \"i2c_master.h\"\n", "file_path": "components/modules/ds3231/include/ds3231.hpp", "rank": 89, "score": 40348.68603517351 }, { "content": "\t\t\tCTRL_MEAS \t= 0xF4,\n\n\t\t\tSTATUS\t\t\t\t\t= 0xF3,\n\n\t\t\tCONFIG \t= 0xF5,\n\n\t\t\tDATA \t= 0xF7,\n\n\t\t};\n\n\n\n\t\tenum Reset{\n\n\t\t\tPOWER_ON_RESET\t\t\t= 0xB6\n\n\t\t};\n\n\n\n\t\tenum Status{\n\n\t\t\tMEASURING\t\t\t\t= 0b1000,\n\n\t\t\tIM_UPDATE\t\t\t\t= 0b0001\n\n\t\t};\n\n\n\n\t\tenum Ctrl_Measurument{\n\n\t\t\tOSRS_TEMPERATURE\t\t= 5,\n\n\t\t\tOSRS_PRESSURE\t\t\t= 2,\n\n\t\t\tMODE\t\t\t\t\t= 0\n\n\t\t};\n", "file_path": "components/modules/bme280/include/bme280_defs.h", "rank": 90, "score": 40348.00937960093 }, { "content": "\n\nvoid wifi_default_init(esp_netif_t* netif_sta);\n\n\n\n#define MESH_NODE_DEFAULT_OTHER_CONFIG {\\\n\n\t\t.topology = MESH_TOPO_TREE, \t\\\n\n\t\t.vote_percent = 1, \t\t\t\t\\\n\n\t\t.xon_queue = 128,\t\t\t\t\\\n\n\t\t.expire_sec = 10,\t\t\t\t\\\n\n\t\t.max_layer = 6,\t\t\t\t\t\\\n\n\t\t.enable_ps = false,\t\t\t\t\\\n\n\t\t.wifi_auth = WIFI_AUTH_WPA2_PSK,\\\n\n\t\t.allow_root_conflicts = false\t\\\n\n\t}\n\n\n\n}//Mesh\n\n\n\n#endif /* MESH_NODE_HPP__ */\n", "file_path": "components/mesh/include/mesh/node.hpp", "rank": 91, "score": 40347.423753471645 }, { "content": "\t\t\tGYRO_X_REF\t\t\t= 0b001,\n\n\t\t\tGYRO_Y_REF\t\t\t= 0b010,\n\n\t\t\tGYRO_Z_REF\t\t\t= 0b011,\n\n\t\t\tExternal_32KHz\t\t= 0b100,\n\n\t\t\tClock_Stop\t\t\t= 0b111,\n\n\t\t\tTemp_Disable\t\t= 0b00001000,\n\n\t\t\tCycle\t\t\t\t= 0b00100000,\n\n\t\t\tSleep\t\t\t\t= 0b01000000,\n\n\t\t\tReset_Device\t\t= 0b10000000,\n\n\t\t};\n\n\n\n\t\tenum Power_Mgmt_2{\n\n\t\t\tLP_Wake_1_25Hz\t\t= 0b00000000,\n\n\t\t\tLP_Wake_5Hz\t\t\t= 0b01000000,\n\n\t\t\tLP_Wake_20Hz\t\t= 0b10000000,\n\n\t\t\tLP_Wake_40Hz\t\t= 0b11000000,\n\n\t\t\tStand_By_Acc_X\t\t= 0b00100000,\n\n\t\t\tStand_By_Acc_Y\t\t= 0b00010000,\n\n\t\t\tStand_By_Acc_Z\t\t= 0b00001000,\n\n\t\t\tStand_By_Gyro_X\t\t= 0b00000100,\n", "file_path": "components/modules/mpu60X0/include/mpu60x0.h", "rank": 92, "score": 40347.0276719564 }, { "content": "#define BME280_CTRL_HUM_MSK (0x07)\n\n#define BME280_CTRL_HUM_POS (0x00)\n\n\n\n#define BME280_CTRL_PRESS_MSK (0x1C)\n\n#define BME280_CTRL_PRESS_POS (0x02)\n\n\n\n#define BME280_CTRL_TEMP_MSK (0xE0)\n\n#define BME280_CTRL_TEMP_POS (0x05)\n\n\n\n#define BME280_FILTER_MSK (0x1C)\n\n#define BME280_FILTER_POS (0x02)\n\n\n\n#define BME280_STANDBY_MSK (0xE0)\n\n#define BME280_STANDBY_POS (0x05)\n\n\n", "file_path": "components/modules/bme280/include/bme280_defs.h", "rank": 93, "score": 40344.78908614997 }, { "content": "class DateTime {\n\n\tpublic:\n\n\n\n\t\tDateTime(TimeMode mode = FORMAT_24H, int fuse = 0);\n\n\n\n\t\t//SET\n\n\t\tvoid setYear(uint16_t year);\n\n\t\tvoid setMonth(uint8_t month);\n\n\t\tvoid setDay(uint8_t month);\n\n\t\tvoid setDate(uint16_t year,\n\n\t\t\t\tuint8_t month,\n\n\t\t\t\tuint8_t day);\n\n\n\n\t\tvoid setHour(uint8_t hour, DayPeriod period = ND);\n\n\t\tvoid setMinute(uint8_t minute);\n\n\t\tvoid setSecond(uint8_t second);\n\n\t\tvoid setTime(uint8_t hour,\n\n\t\t\t\tuint8_t minute,\n\n\t\t\t\tuint8_t second,\n\n\t\t\t\tDayPeriod period = ND);\n", "file_path": "components/helper/include/datetime.h", "rank": 94, "score": 40344.78908614997 }, { "content": "class BME280{\n\n\tpublic:\n\n\t\tstatic const uint8_t CHIP_ID = 0x60;\n\n\n\n\t\tenum Stand_By_Time_ms{\n\n\t\t\tSTANDBY_TIME_0_5_MS\t\t= 0b000,\n\n\t\t\tSTANDBY_TIME_62_5_MS\t= 0b001,\n\n\t\t\tSTANDBY_TIME_125_MS\t\t= 0b010,\n\n\t\t\tSTANDBY_TIME_250_MS\t\t= 0b011,\n\n\t\t\tSTANDBY_TIME_500_MS\t\t= 0b100,\n\n\t\t\tSTANDBY_TIME_1000_MS\t= 0b101,\n\n\t\t\tSTANDBY_TIME_10_MS\t\t= 0b110,\n\n\t\t\tSTANDBY_TIME_20_MS\t\t= 0b111,\n\n\t\t};\n\n\n\n\t\tenum IIR_Filter_Coeficient{\n\n\t\t\tFILTER_COEF_OFF\t\t\t= 0b000,\n\n\t\t\tFILTER_COEF_2\t\t\t= 0b001,\n\n\t\t\tFILTER_COEF_4\t\t\t= 0b010,\n\n\t\t\tFILTER_COEF_8\t\t\t= 0b011,\n", "file_path": "components/modules/bme280/include/bme280.h", "rank": 95, "score": 40344.78908614997 }, { "content": "\n\n//Frequency of Square Wave output\n\ntypedef enum DS3231SQWrate{\n\n\tSQW_RATE_1 = 0,\n\n\tSQW_RATE_1K,\n\n\tSQW_RATE_4K,\n\n\tSQW_RATE_8K\n\n}DS3231SQWrate;\n\n\n\n// Output type of NINT/SQW pin\n\n#define OUTPUT_SQW\t\t0\n\n#define OUTPUT_INT\t\t1\n\n\n\n//// Hour format\n\n//#define FORMAT_24H\t0\n\n//#define FORMAT_12H\t1\n\n//\n\n//// Days of the week\n\n//#define SUNDAY\t\t0\n\n//#define MONDAY\t\t1\n", "file_path": "components/modules/ds3231/include/ds3231.hpp", "rank": 96, "score": 40344.78908614997 }, { "content": "\t\t\tStand_By_Gyro_Y\t\t= 0b00000010,\n\n\t\t\tStand_By_Gyro_Z\t\t= 0b00000001\n\n\t\t};\n\n\n\n\t\tenum Config{\n\n\t\t\tLow_Pass_260Hz\t\t= 0b000,\n\n\t\t\tLow_Pass_184Hz\t\t= 0b001,\n\n\t\t\tLow_Pass_94Hz\t\t= 0b010,\n\n\t\t\tLow_Pass_44Hz\t\t= 0b011,\n\n\t\t\tLow_Pass_21Hz\t\t= 0b100,\n\n\t\t\tLow_Pass_10Hz\t\t= 0b101,\n\n\t\t\tLow_Pass_5Hz\t\t= 0b110,\n\n\t\t};\n\n\n\n\t\tenum FIFO_Enable{\n\n\t\t\tacc_en \t\t\t\t= 0b00001000,\n\n\t\t\tgyro_z_en \t\t\t= 0b00010000,\n\n\t\t\tgyro_y_en \t\t\t= 0b00100000,\n\n\t\t\tgyro_x_en \t\t\t= 0b01000000,\n\n\t\t\tgyro_en\t\t\t\t= gyro_x_en | gyro_y_en | gyro_z_en,\n", "file_path": "components/modules/mpu60X0/include/mpu60x0.h", "rank": 97, "score": 40344.78908614997 }, { "content": "\t\t\ttemp_en\t\t\t\t= 0b10000000\n\n\t\t};\n\n\n\n\t\tstruct Axis{\n\n\t\t\tint16_t x;\n\n\t\t\tint16_t y;\n\n\t\t\tint16_t z;\n\n\t\t};\n\n\n\n\t\tstruct Axis_Float{\n\n\t\t\tMPU60X0_FLOAT_TYPE x;\n\n\t\t\tMPU60X0_FLOAT_TYPE y;\n\n\t\t\tMPU60X0_FLOAT_TYPE z;\n\n\t\t};\n\n\n\n\t\tstruct settings{\n\n\t\t\tsettings() : pwr_mgmt_1(0),\tpwr_mgmt_2(0),\n\n\t\t\t\t\tconfig((uint8_t)Low_Pass_260Hz),\n\n\t\t\t\t\tsample_rate_div(0), fifo_en(0),\n\n\t\t\t\t\tacc(ACC_2G), gyro(GYRO_250){}\n", "file_path": "components/modules/mpu60X0/include/mpu60x0.h", "rank": 98, "score": 40344.78908614997 }, { "content": "#ifndef __DS3231_H__\n\n#define __DS3231_H__\n\n\n\n/**\n\n * \\file\n\n * \\brief Biblioteca para utilização do módulo RTC DS3231\n\n *\n\n * DS3231 é um RTC de alta precisão. Ele se comunica através de uma porta I2C,\n\n * em modo \\i standard ou \\i fast. É possível a configuração de 2 alarmes internos,\n\n * em diferentes modalidades, gerando estes alarmes interrupções externas.\n\n *\n\n * Também há pinos externos para verificar a frequência de 32kHz, e possibilidade de ondas\n\n * quadradas nas frequências de 1Hz, 1kHz, 4kHz e 8kHz.\n\n *\n\n * O dispositivo há um sensor de temperatura interno para compensação de diferenças de\n\n * temperatura.\n\n *\n\n * \\note Interrupções devem pegar o <i>FALLING EDGE</i>\n\n *\n\n * Manual: <a href=\"https://datasheets.maximintegrated.com/en/ds/DS3231.pdf\">DS3231</a>\n", "file_path": "components/modules/ds3231/include/ds3231.hpp", "rank": 99, "score": 40344.78908614997 } ]
C++
ccl/src/dev/Morpheus_Ccl_DenseVector.hpp
morpheus-org/morpheus-interoperability
66161199fa1926914e16c1feb02eb910ffef5ed4
#ifndef MORPHEUS_CCL_DEV_DENSEVECTOR_HPP #define MORPHEUS_CCL_DEV_DENSEVECTOR_HPP #include <Morpheus_Ccl_Types.hpp> #include <dev/fwd/Morpheus_Ccl_Fwd_DenseVector.hpp> #ifdef __cplusplus extern "C" { #endif void ccl_dvec_dense_v_create_default(ccl_dvec_dense_v** v); void ccl_dvec_dense_v_create(ccl_dvec_dense_v** v, ccl_index_t n, ccl_value_t val); void ccl_dvec_dense_v_create_from_dvec_dense_v(ccl_dvec_dense_v* src, ccl_dvec_dense_v** dst); void ccl_dvec_dense_v_allocate_from_dvec_dense_v(ccl_dvec_dense_v* src, ccl_dvec_dense_v* dst); void ccl_dvec_dense_v_assign(ccl_dvec_dense_v* v, ccl_index_t n, ccl_value_t val); void ccl_dvec_dense_v_resize(ccl_dvec_dense_v* v, ccl_index_t n); void ccl_dvec_dense_v_resize_fill(ccl_dvec_dense_v* v, ccl_index_t n, ccl_value_t val); void ccl_dvec_dense_v_destroy(ccl_dvec_dense_v** v); ccl_index_t ccl_dvec_dense_v_size(ccl_dvec_dense_v* v); ccl_value_t* ccl_dvec_dense_v_data(ccl_dvec_dense_v* v); ccl_value_t ccl_dvec_dense_v_values_at(ccl_dvec_dense_v* v, ccl_index_t i); void ccl_dvec_dense_v_set_values_at(ccl_dvec_dense_v* v, ccl_index_t i, ccl_value_t val); void ccl_dvec_dense_i_create_default(ccl_dvec_dense_i** v); void ccl_dvec_dense_i_create(ccl_dvec_dense_i** v, ccl_index_t n, ccl_index_t val); void ccl_dvec_dense_i_create_from_dvec_dense_i(ccl_dvec_dense_i* src, ccl_dvec_dense_i** dst); void ccl_dvec_dense_i_allocate_from_dvec_dense_i(ccl_dvec_dense_i* src, ccl_dvec_dense_i* dst); void ccl_dvec_dense_i_assign(ccl_dvec_dense_i* v, ccl_index_t n, ccl_index_t val); void ccl_dvec_dense_i_resize(ccl_dvec_dense_i* v, ccl_index_t n); void ccl_dvec_dense_i_resize_fill(ccl_dvec_dense_i* v, ccl_index_t n, ccl_index_t val); void ccl_dvec_dense_i_destroy(ccl_dvec_dense_i** v); ccl_index_t ccl_dvec_dense_i_size(ccl_dvec_dense_i* v); ccl_index_t* ccl_dvec_dense_i_data(ccl_dvec_dense_i* v); void ccl_dvec_dense_v_hostmirror_create_default( ccl_dvec_dense_v_hostmirror** v); void ccl_dvec_dense_v_hostmirror_create(ccl_dvec_dense_v_hostmirror** v, ccl_index_t n, ccl_value_t val); void ccl_dvec_dense_v_hostmirror_create_from_dvec_dense_v_hostmirror( ccl_dvec_dense_v_hostmirror* src, ccl_dvec_dense_v_hostmirror** dst); void ccl_dvec_dense_v_hostmirror_allocate_from_dvec_dense_v_hostmirror( ccl_dvec_dense_v_hostmirror* src, ccl_dvec_dense_v_hostmirror* dst); void ccl_dvec_dense_v_hostmirror_assign(ccl_dvec_dense_v_hostmirror* v, ccl_index_t n, ccl_value_t val); void ccl_dvec_dense_v_hostmirror_resize(ccl_dvec_dense_v_hostmirror* v, ccl_index_t n); void ccl_dvec_dense_v_hostmirror_resize_fill(ccl_dvec_dense_v_hostmirror* v, ccl_index_t n, ccl_value_t val); void ccl_dvec_dense_v_hostmirror_destroy(ccl_dvec_dense_v_hostmirror** v); ccl_index_t ccl_dvec_dense_v_hostmirror_size(ccl_dvec_dense_v_hostmirror* v); ccl_value_t* ccl_dvec_dense_v_hostmirror_data(ccl_dvec_dense_v_hostmirror* v); ccl_value_t ccl_dvec_dense_v_hostmirror_values_at( ccl_dvec_dense_v_hostmirror* v, ccl_index_t i); void ccl_dvec_dense_v_hostmirror_set_values_at(ccl_dvec_dense_v_hostmirror* v, ccl_index_t i, ccl_value_t val); void ccl_dvec_dense_i_hostmirror_create_default( ccl_dvec_dense_i_hostmirror** v); void ccl_dvec_dense_i_hostmirror_create(ccl_dvec_dense_i_hostmirror** v, ccl_index_t n, ccl_index_t val); void ccl_dvec_dense_i_hostmirror_create_from_dvec_dense_i_hostmirror( ccl_dvec_dense_i_hostmirror* src, ccl_dvec_dense_i_hostmirror** dst); void ccl_dvec_dense_i_hostmirror_allocate_from_dvec_dense_i_hostmirror( ccl_dvec_dense_i_hostmirror* src, ccl_dvec_dense_i_hostmirror* dst); void ccl_dvec_dense_i_hostmirror_assign(ccl_dvec_dense_i_hostmirror* v, ccl_index_t n, ccl_index_t val); void ccl_dvec_dense_i_hostmirror_resize(ccl_dvec_dense_i_hostmirror* v, ccl_index_t n); void ccl_dvec_dense_i_hostmirror_resize_fill(ccl_dvec_dense_i_hostmirror* v, ccl_index_t n, ccl_index_t val); void ccl_dvec_dense_i_hostmirror_destroy(ccl_dvec_dense_i_hostmirror** v); ccl_index_t ccl_dvec_dense_i_hostmirror_size(ccl_dvec_dense_i_hostmirror* v); ccl_index_t* ccl_dvec_dense_i_hostmirror_data(ccl_dvec_dense_i_hostmirror* v); ccl_index_t ccl_dvec_dense_i_hostmirror_values_at( ccl_dvec_dense_i_hostmirror* v, ccl_index_t i); void ccl_dvec_dense_i_hostmirror_set_values_at(ccl_dvec_dense_i_hostmirror* v, ccl_index_t i, ccl_index_t val); #ifdef __cplusplus } #endif #endif
#ifndef MORPHEUS_CCL_DEV_DENSEVECTOR_HPP #define MORPHEUS_CCL_DEV_DENSEVECTOR_HPP #include <Morpheus_Ccl_Types.hpp> #include <dev/fwd/Morpheus_Ccl_Fwd_DenseVector.hpp> #ifdef __cplusplus extern "C" { #endif void ccl_dvec_dense_v_create_default(ccl_dvec_dense_v** v); void ccl_dvec_dense_v_create(ccl_dvec_dense_v** v, ccl_index_t n, ccl_value_t val); void ccl_dvec_dense_v_create_from_dvec_dense_v(ccl_dvec_dense_v* src,
_dvec_dense_v_hostmirror_values_at( ccl_dvec_dense_v_hostmirror* v, ccl_index_t i); void ccl_dvec_dense_v_hostmirror_set_values_at(ccl_dvec_dense_v_hostmirror* v, ccl_index_t i, ccl_value_t val); void ccl_dvec_dense_i_hostmirror_create_default( ccl_dvec_dense_i_hostmirror** v); void ccl_dvec_dense_i_hostmirror_create(ccl_dvec_dense_i_hostmirror** v, ccl_index_t n, ccl_index_t val); void ccl_dvec_dense_i_hostmirror_create_from_dvec_dense_i_hostmirror( ccl_dvec_dense_i_hostmirror* src, ccl_dvec_dense_i_hostmirror** dst); void ccl_dvec_dense_i_hostmirror_allocate_from_dvec_dense_i_hostmirror( ccl_dvec_dense_i_hostmirror* src, ccl_dvec_dense_i_hostmirror* dst); void ccl_dvec_dense_i_hostmirror_assign(ccl_dvec_dense_i_hostmirror* v, ccl_index_t n, ccl_index_t val); void ccl_dvec_dense_i_hostmirror_resize(ccl_dvec_dense_i_hostmirror* v, ccl_index_t n); void ccl_dvec_dense_i_hostmirror_resize_fill(ccl_dvec_dense_i_hostmirror* v, ccl_index_t n, ccl_index_t val); void ccl_dvec_dense_i_hostmirror_destroy(ccl_dvec_dense_i_hostmirror** v); ccl_index_t ccl_dvec_dense_i_hostmirror_size(ccl_dvec_dense_i_hostmirror* v); ccl_index_t* ccl_dvec_dense_i_hostmirror_data(ccl_dvec_dense_i_hostmirror* v); ccl_index_t ccl_dvec_dense_i_hostmirror_values_at( ccl_dvec_dense_i_hostmirror* v, ccl_index_t i); void ccl_dvec_dense_i_hostmirror_set_values_at(ccl_dvec_dense_i_hostmirror* v, ccl_index_t i, ccl_index_t val); #ifdef __cplusplus } #endif #endif
ccl_dvec_dense_v** dst); void ccl_dvec_dense_v_allocate_from_dvec_dense_v(ccl_dvec_dense_v* src, ccl_dvec_dense_v* dst); void ccl_dvec_dense_v_assign(ccl_dvec_dense_v* v, ccl_index_t n, ccl_value_t val); void ccl_dvec_dense_v_resize(ccl_dvec_dense_v* v, ccl_index_t n); void ccl_dvec_dense_v_resize_fill(ccl_dvec_dense_v* v, ccl_index_t n, ccl_value_t val); void ccl_dvec_dense_v_destroy(ccl_dvec_dense_v** v); ccl_index_t ccl_dvec_dense_v_size(ccl_dvec_dense_v* v); ccl_value_t* ccl_dvec_dense_v_data(ccl_dvec_dense_v* v); ccl_value_t ccl_dvec_dense_v_values_at(ccl_dvec_dense_v* v, ccl_index_t i); void ccl_dvec_dense_v_set_values_at(ccl_dvec_dense_v* v, ccl_index_t i, ccl_value_t val); void ccl_dvec_dense_i_create_default(ccl_dvec_dense_i** v); void ccl_dvec_dense_i_create(ccl_dvec_dense_i** v, ccl_index_t n, ccl_index_t val); void ccl_dvec_dense_i_create_from_dvec_dense_i(ccl_dvec_dense_i* src, ccl_dvec_dense_i** dst); void ccl_dvec_dense_i_allocate_from_dvec_dense_i(ccl_dvec_dense_i* src, ccl_dvec_dense_i* dst); void ccl_dvec_dense_i_assign(ccl_dvec_dense_i* v, ccl_index_t n, ccl_index_t val); void ccl_dvec_dense_i_resize(ccl_dvec_dense_i* v, ccl_index_t n); void ccl_dvec_dense_i_resize_fill(ccl_dvec_dense_i* v, ccl_index_t n, ccl_index_t val); void ccl_dvec_dense_i_destroy(ccl_dvec_dense_i** v); ccl_index_t ccl_dvec_dense_i_size(ccl_dvec_dense_i* v); ccl_index_t* ccl_dvec_dense_i_data(ccl_dvec_dense_i* v); void ccl_dvec_dense_v_hostmirror_create_default( ccl_dvec_dense_v_hostmirror** v); void ccl_dvec_dense_v_hostmirror_create(ccl_dvec_dense_v_hostmirror** v, ccl_index_t n, ccl_value_t val); void ccl_dvec_dense_v_hostmirror_create_from_dvec_dense_v_hostmirror( ccl_dvec_dense_v_hostmirror* src, ccl_dvec_dense_v_hostmirror** dst); void ccl_dvec_dense_v_hostmirror_allocate_from_dvec_dense_v_hostmirror( ccl_dvec_dense_v_hostmirror* src, ccl_dvec_dense_v_hostmirror* dst); void ccl_dvec_dense_v_hostmirror_assign(ccl_dvec_dense_v_hostmirror* v, ccl_index_t n, ccl_value_t val); void ccl_dvec_dense_v_hostmirror_resize(ccl_dvec_dense_v_hostmirror* v, ccl_index_t n); void ccl_dvec_dense_v_hostmirror_resize_fill(ccl_dvec_dense_v_hostmirror* v, ccl_index_t n, ccl_value_t val); void ccl_dvec_dense_v_hostmirror_destroy(ccl_dvec_dense_v_hostmirror** v); ccl_index_t ccl_dvec_dense_v_hostmirror_size(ccl_dvec_dense_v_hostmirror* v); ccl_value_t* ccl_dvec_dense_v_hostmirror_data(ccl_dvec_dense_v_hostmirror* v); ccl_value_t ccl
random
[ { "content": "#ifdef __cplusplus\n\nextern \"C\" {\n\n#endif\n\n\n\nvoid ccl_initialize(int* argc, char** argv[]);\n\nvoid ccl_initialize_without_args(void);\n\nvoid ccl_finalize(void);\n\nvoid ccl_print_configuration(const char* prepend_name_in,\n\n const char* file_name_in);\n\n\n\n#ifdef __cplusplus\n\n} // extern \"C\"\n\n#endif\n\n\n\n#endif // MORPHEUS_CCL_HPP\n", "file_path": "ccl/src/Morpheus_Ccl.hpp", "rank": 0, "score": 23366.76161277213 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#include <Morpheus_Ccl.hpp>\n\n#include <Morpheus_Core.hpp>\n\n\n\n#include <iostream>\n\n#include <fstream>\n\n#include <cstdio>\n\n#include <stddef.h>\n\n\n\nvoid ccl_initialize(int* argc, char** argv[]) {\n\n Morpheus::initialize(*argc, *argv);\n\n}\n\n\n\nvoid ccl_initialize_without_args() { Morpheus::initialize(); }\n\n\n\nvoid ccl_finalize() { Morpheus::finalize(); }\n\n\n\nvoid ccl_print_configuration(const char* prepend_name_in,\n", "file_path": "ccl/src/Morpheus_Ccl.cpp", "rank": 1, "score": 23362.816774304112 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#ifndef MORPHEUS_CCL_HPP\n\n#define MORPHEUS_CCL_HPP\n\n\n\n#include <Morpheus_Ccl_Macros.hpp>\n\n\n\n#if defined MCL_ENABLE_SERIAL\n\n#include <host/Morpheus_Ccl.hpp>\n\n#endif\n\n\n\n#if defined MCL_ENABLE_OPENMP\n\n#include <phost/Morpheus_Ccl.hpp>\n\n#endif // MCL_ENABLE_OPENMP\n\n\n\n#if defined MCL_ENABLE_CUDA\n\n#include <dev/Morpheus_Ccl.hpp>\n\n#endif // MCL_ENABLE_CUDA\n\n\n", "file_path": "ccl/src/Morpheus_Ccl.hpp", "rank": 2, "score": 23358.175074206174 }, { "content": "/**\n\n * Morpheus_Ccl.cpp\n\n *\n\n * EPCC, The University of Edinburgh\n\n *\n\n * (c) 2021 The University of Edinburgh\n\n *\n\n * Contributing Authors:\n\n * Christodoulos Stylianou ([email protected])\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * \thttp://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n", "file_path": "ccl/src/Morpheus_Ccl.cpp", "rank": 3, "score": 23353.17561252378 }, { "content": "/**\n\n * Morpheus_Ccl.hpp\n\n *\n\n * EPCC, The University of Edinburgh\n\n *\n\n * (c) 2021 The University of Edinburgh\n\n *\n\n * Contributing Authors:\n\n * Christodoulos Stylianou ([email protected])\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * \thttp://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n", "file_path": "ccl/src/Morpheus_Ccl.hpp", "rank": 4, "score": 23353.17561252378 }, { "content": " const char* file_name_in) {\n\n std::string prepend_name(prepend_name_in);\n\n std::string file_name(file_name_in);\n\n std::string output_filename = prepend_name + file_name;\n\n std::ofstream morpheus_output_file(output_filename);\n\n if (morpheus_output_file.is_open()) {\n\n Morpheus::print_configuration(morpheus_output_file, true);\n\n morpheus_output_file.close();\n\n } else {\n\n std::cout << \"Could not open filename \" << output_filename;\n\n std::cout << \" to dump Morpheus::print_configuration to.\" << std::endl;\n\n }\n\n}\n", "file_path": "ccl/src/Morpheus_Ccl.cpp", "rank": 5, "score": 23353.17561252378 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#ifndef MORPHEUS_CCL_HOST_HPP\n\n#define MORPHEUS_CCL_HOST_HPP\n\n\n\n#include <host/Morpheus_Ccl_CooMatrix.hpp>\n\n#include <host/Morpheus_Ccl_CsrMatrix.hpp>\n\n#include <host/Morpheus_Ccl_DiaMatrix.hpp>\n\n#include <host/Morpheus_Ccl_DenseVector.hpp>\n\n#include <host/Morpheus_Ccl_DynamicMatrix.hpp>\n\n\n\n#include <host/Morpheus_Ccl_MirrorContainers.hpp>\n\n\n\n#include <host/Morpheus_Ccl_Convert.hpp>\n\n#include <host/Morpheus_Ccl_Copy.hpp>\n\n#include <host/Morpheus_Ccl_Dot.hpp>\n\n#include <host/Morpheus_Ccl_Multiply.hpp>\n\n#include <host/Morpheus_Ccl_Print.hpp>\n\n#include <host/Morpheus_Ccl_Reduction.hpp>\n\n#include <host/Morpheus_Ccl_Scan.hpp>\n\n#include <host/Morpheus_Ccl_WAXPBY.hpp>\n\n\n\n#endif // MORPHEUS_CCL_HOST_HPP", "file_path": "ccl/src/host/Morpheus_Ccl.hpp", "rank": 6, "score": 22650.10256613143 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#ifndef MORPHEUS_CCL_PHOST_HPP\n\n#define MORPHEUS_CCL_PHOST_HPP\n\n\n\n#include <phost/Morpheus_Ccl_CooMatrix.hpp>\n\n#include <phost/Morpheus_Ccl_CsrMatrix.hpp>\n\n#include <phost/Morpheus_Ccl_DiaMatrix.hpp>\n\n#include <phost/Morpheus_Ccl_DenseVector.hpp>\n\n#include <phost/Morpheus_Ccl_DynamicMatrix.hpp>\n\n\n\n#include <phost/Morpheus_Ccl_MirrorContainers.hpp>\n\n\n\n#include <phost/Morpheus_Ccl_Convert.hpp>\n\n#include <phost/Morpheus_Ccl_Copy.hpp>\n\n#include <phost/Morpheus_Ccl_Dot.hpp>\n\n#include <phost/Morpheus_Ccl_Multiply.hpp>\n\n#include <phost/Morpheus_Ccl_Print.hpp>\n\n#include <phost/Morpheus_Ccl_Reduction.hpp>\n\n#include <phost/Morpheus_Ccl_Scan.hpp>\n\n#include <phost/Morpheus_Ccl_WAXPBY.hpp>\n\n\n\n#endif // MORPHEUS_CCL_PHOST_HPP", "file_path": "ccl/src/phost/Morpheus_Ccl.hpp", "rank": 7, "score": 22650.10256613143 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#ifndef MORPHEUS_CCL_DEV_HPP\n\n#define MORPHEUS_CCL_DEV_HPP\n\n\n\n#include <dev/Morpheus_Ccl_CooMatrix.hpp>\n\n#include <dev/Morpheus_Ccl_CsrMatrix.hpp>\n\n#include <dev/Morpheus_Ccl_DiaMatrix.hpp>\n\n#include <dev/Morpheus_Ccl_DenseVector.hpp>\n\n#include <dev/Morpheus_Ccl_DynamicMatrix.hpp>\n\n\n\n#include <dev/Morpheus_Ccl_MirrorContainers.hpp>\n\n\n\n#include <dev/Morpheus_Ccl_Convert.hpp>\n\n#include <dev/Morpheus_Ccl_Copy.hpp>\n\n#include <dev/Morpheus_Ccl_Dot.hpp>\n\n#include <dev/Morpheus_Ccl_Multiply.hpp>\n\n#include <dev/Morpheus_Ccl_Print.hpp>\n\n#include <dev/Morpheus_Ccl_Reduction.hpp>\n\n#include <dev/Morpheus_Ccl_WAXPBY.hpp>\n\n\n\n#endif // MORPHEUS_CCL_DEV_HPP", "file_path": "ccl/src/dev/Morpheus_Ccl.hpp", "rank": 8, "score": 22650.085448909555 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#ifndef MORPHEUS_CCL_TYPES_HPP\n\n#define MORPHEUS_CCL_TYPES_HPP\n\n\n\n#include <Morpheus_Ccl_Macros.hpp>\n\n\n\n#ifdef __cplusplus\n\n#include <cstdint>\n\n#else\n\n#include <stddef.h>\n\n#include <stdint.h>\n\n#endif\n\n\n\ntypedef Mcl_VALUETYPE ccl_value_t;\n\ntypedef Mcl_INDEXTYPE ccl_index_t;\n\n\n\n#ifdef __cplusplus\n\ntypedef bool ccl_bool_t;\n", "file_path": "ccl/src/Morpheus_Ccl_Types.hpp", "rank": 9, "score": 22649.67502541185 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#ifndef MORPHEUS_CCL_MACROS_HPP\n\n#define MORPHEUS_CCL_MACROS_HPP\n\n\n\n#include <MorpheusCcl_config.hpp>\n\n\n\n#endif // MORPHEUS_CCL_MACROS_HPP\n", "file_path": "ccl/src/Morpheus_Ccl_Macros.hpp", "rank": 10, "score": 22648.44223837842 }, { "content": "typedef std::size_t ccl_size_t;\n\n#else\n\ntypedef size_t ccl_size_t;\n\ntypedef _Bool ccl_bool_t;\n\n#endif\n\n\n\ntypedef char ccl_char_t;\n\n\n\n#ifdef __cplusplus\n\n#include <Morpheus_Core.hpp>\n\n// Enum for supported Sparse Matrix Formats\n\ntypedef enum Morpheus::formats_e ccl_formats_e;\n\n\n\n// Kokkos Types\n\ntypedef Mcl_LAYOUT ccl_layout_t;\n\n\n\n#if defined MCL_ENABLE_SERIAL\n\ntypedef Kokkos::Serial ccl_host_t;\n\n#endif // MCL_ENABLE_SERIAL\n\n\n", "file_path": "ccl/src/Morpheus_Ccl_Types.hpp", "rank": 11, "score": 22647.554351636005 }, { "content": "#if defined MCL_ENABLE_OPENMP\n\ntypedef Kokkos::OpenMP ccl_phost_t;\n\n#endif // MCL_ENABLE_OPENMP\n\n\n\n#if defined MCL_ENABLE_CUDA\n\ntypedef Kokkos::Cuda ccl_dev_t;\n\n#endif // MCL_ENABLE_CUDA\n\n\n\ntypedef typename Kokkos::HostSpace::execution_space ccl_hostspace_t;\n\n\n\n#else\n\n\n\n#include <Morpheus_FormatsRegistry.hpp>\n\n// Enum for supported Sparse Matrix Formats\n\ntypedef enum formats_e ccl_formats_e;\n\n\n\ntypedef struct Ccl_Layout ccl_layout_t;\n\n\n\n#if defined MCL_ENABLE_SERIAL\n\ntypedef struct Ccl_Host ccl_host_t;\n", "file_path": "ccl/src/Morpheus_Ccl_Types.hpp", "rank": 12, "score": 22647.348717604775 }, { "content": "/**\n\n * Morpheus_Ccl.hpp\n\n *\n\n * EPCC, The University of Edinburgh\n\n *\n\n * (c) 2021 The University of Edinburgh\n\n *\n\n * Contributing Authors:\n\n * Christodoulos Stylianou ([email protected])\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * \thttp://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n", "file_path": "ccl/src/host/Morpheus_Ccl.hpp", "rank": 13, "score": 22644.56508093048 }, { "content": "/**\n\n * Morpheus_Ccl.hpp\n\n *\n\n * EPCC, The University of Edinburgh\n\n *\n\n * (c) 2021 The University of Edinburgh\n\n *\n\n * Contributing Authors:\n\n * Christodoulos Stylianou ([email protected])\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * \thttp://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n", "file_path": "ccl/src/phost/Morpheus_Ccl.hpp", "rank": 14, "score": 22644.56508093048 }, { "content": "/**\n\n * Morpheus_Ccl.hpp\n\n *\n\n * EPCC, The University of Edinburgh\n\n *\n\n * (c) 2021 The University of Edinburgh\n\n *\n\n * Contributing Authors:\n\n * Christodoulos Stylianou ([email protected])\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * \thttp://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n", "file_path": "ccl/src/dev/Morpheus_Ccl.hpp", "rank": 15, "score": 22644.56508093048 }, { "content": "/**\n\n * Morpheus_Ccl_Macros.hpp\n\n *\n\n * EPCC, The University of Edinburgh\n\n *\n\n * (c) 2021 The University of Edinburgh\n\n *\n\n * Contributing Authors:\n\n * Christodoulos Stylianou ([email protected])\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * \thttp://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n", "file_path": "ccl/src/Morpheus_Ccl_Macros.hpp", "rank": 16, "score": 22644.56508093048 }, { "content": "#endif // MCL_ENABLE_SERIAL\n\n\n\n#if defined MCL_ENABLE_OPENMP\n\ntypedef struct Ccl_pHost ccl_phost_t;\n\n#endif // MCL_ENABLE_OPENMP\n\n\n\n#if defined MCL_ENABLE_CUDA\n\ntypedef struct Ccl_Device ccl_dev_t;\n\n#endif // MCL_ENABLE_CUDA\n\n\n\ntypedef struct Ccl_HostSpace ccl_hostspace_t;\n\n\n\n#endif //__cplusplus\n\n\n\n#endif // MORPHEUS_CCL_TYPES_HPP\n", "file_path": "ccl/src/Morpheus_Ccl_Types.hpp", "rank": 17, "score": 22644.56508093048 }, { "content": "/**\n\n * Morpheus_Ccl_Types.hpp\n\n *\n\n * EPCC, The University of Edinburgh\n\n *\n\n * (c) 2021 The University of Edinburgh\n\n *\n\n * Contributing Authors:\n\n * Christodoulos Stylianou ([email protected])\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * \thttp://www.apache.org/licenses/LICENSE-2.0\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n", "file_path": "ccl/src/Morpheus_Ccl_Types.hpp", "rank": 18, "score": 22644.56508093048 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#ifndef MORPHEUS_CCL_HOST_CONVERT_HPP\n\n#define MORPHEUS_CCL_HOST_CONVERT_HPP\n\n\n\n#include <host/Morpheus_Ccl_CooMatrix.hpp>\n\n#include <host/Morpheus_Ccl_CsrMatrix.hpp>\n\n#include <host/Morpheus_Ccl_DiaMatrix.hpp>\n\n#include <host/Morpheus_Ccl_DynamicMatrix.hpp>\n\n#include <host/Morpheus_Ccl_DenseMatrix.hpp>\n\n#include <host/Morpheus_Ccl_DenseVector.hpp>\n\n\n\n#ifdef __cplusplus\n\nextern \"C\" {\n\n#endif\n\n\n\n// coo -> coo\n\nvoid ccl_hmat_coo_convert_to_hmat_coo(const ccl_hmat_coo* src,\n\n ccl_hmat_coo* dst);\n", "file_path": "ccl/src/host/Morpheus_Ccl_Convert.hpp", "rank": 19, "score": 21992.415485718306 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#ifndef MORPHEUS_CCL_HOST_COPY_HPP\n\n#define MORPHEUS_CCL_HOST_COPY_HPP\n\n\n\n#include <host/Morpheus_Ccl_CooMatrix.hpp>\n\n#include <host/Morpheus_Ccl_CsrMatrix.hpp>\n\n#include <host/Morpheus_Ccl_DiaMatrix.hpp>\n\n#include <host/Morpheus_Ccl_DynamicMatrix.hpp>\n\n#include <host/Morpheus_Ccl_DenseMatrix.hpp>\n\n#include <host/Morpheus_Ccl_DenseVector.hpp>\n\n\n\n#ifdef __cplusplus\n\nextern \"C\" {\n\n#endif\n\n\n\n// coo -> coo\n\nvoid ccl_hmat_coo_copy_to_hmat_coo(const ccl_hmat_coo* src, ccl_hmat_coo* dst);\n\n\n", "file_path": "ccl/src/host/Morpheus_Ccl_Copy.hpp", "rank": 20, "score": 21992.415485718306 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#ifndef MORPHEUS_CCL_PHOST_COPY_HPP\n\n#define MORPHEUS_CCL_PHOST_COPY_HPP\n\n\n\n#include <phost/Morpheus_Ccl_CooMatrix.hpp>\n\n#include <phost/Morpheus_Ccl_CsrMatrix.hpp>\n\n#include <phost/Morpheus_Ccl_DiaMatrix.hpp>\n\n#include <phost/Morpheus_Ccl_DynamicMatrix.hpp>\n\n#include <phost/Morpheus_Ccl_DenseMatrix.hpp>\n\n#include <phost/Morpheus_Ccl_DenseVector.hpp>\n\n\n\n#ifdef __cplusplus\n\nextern \"C\" {\n\n#endif\n\n\n\n// coo -> coo\n\nvoid ccl_phmat_coo_copy_to_phmat_coo(const ccl_phmat_coo* src,\n\n ccl_phmat_coo* dst);\n", "file_path": "ccl/src/phost/Morpheus_Ccl_Copy.hpp", "rank": 21, "score": 21992.415485718306 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#ifndef MORPHEUS_CCL_DEV_COPY_HPP\n\n#define MORPHEUS_CCL_DEV_COPY_HPP\n\n\n\n#include <dev/Morpheus_Ccl_CooMatrix.hpp>\n\n#include <dev/Morpheus_Ccl_CsrMatrix.hpp>\n\n#include <dev/Morpheus_Ccl_DiaMatrix.hpp>\n\n#include <dev/Morpheus_Ccl_DynamicMatrix.hpp>\n\n#include <dev/Morpheus_Ccl_DenseMatrix.hpp>\n\n#include <dev/Morpheus_Ccl_DenseVector.hpp>\n\n\n\n#ifdef __cplusplus\n\nextern \"C\" {\n\n#endif\n\n\n\n// coo -> coo\n\nvoid ccl_dmat_coo_copy_to_dmat_coo(const ccl_dmat_coo* src, ccl_dmat_coo* dst);\n\n\n", "file_path": "ccl/src/dev/Morpheus_Ccl_Copy.hpp", "rank": 22, "score": 21992.415485718306 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#ifndef MORPHEUS_CCL_PHOST_CONVERT_HPP\n\n#define MORPHEUS_CCL_PHOST_CONVERT_HPP\n\n\n\n#include <phost/Morpheus_Ccl_CooMatrix.hpp>\n\n#include <phost/Morpheus_Ccl_CsrMatrix.hpp>\n\n#include <phost/Morpheus_Ccl_DiaMatrix.hpp>\n\n#include <phost/Morpheus_Ccl_DynamicMatrix.hpp>\n\n#include <phost/Morpheus_Ccl_DenseMatrix.hpp>\n\n#include <phost/Morpheus_Ccl_DenseVector.hpp>\n\n\n\n#ifdef __cplusplus\n\nextern \"C\" {\n\n#endif\n\n\n\n// coo -> coo\n\nvoid ccl_phmat_coo_convert_to_phmat_coo(const ccl_phmat_coo* src,\n\n ccl_phmat_coo* dst);\n", "file_path": "ccl/src/phost/Morpheus_Ccl_Convert.hpp", "rank": 23, "score": 21992.415485718306 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#ifndef MORPHEUS_CCL_DEV_CONVERT_HPP\n\n#define MORPHEUS_CCL_DEV_CONVERT_HPP\n\n\n\n#include <dev/Morpheus_Ccl_CooMatrix.hpp>\n\n#include <dev/Morpheus_Ccl_CsrMatrix.hpp>\n\n#include <dev/Morpheus_Ccl_DiaMatrix.hpp>\n\n#include <dev/Morpheus_Ccl_DynamicMatrix.hpp>\n\n#include <dev/Morpheus_Ccl_DenseMatrix.hpp>\n\n#include <dev/Morpheus_Ccl_DenseVector.hpp>\n\n\n\n#ifdef __cplusplus\n\nextern \"C\" {\n\n#endif\n\n\n\n// coo -> coo\n\nvoid ccl_dmat_coo_hostmirror_convert_to_dmat_coo_hostmirror(\n\n const ccl_dmat_coo_hostmirror* src, ccl_dmat_coo_hostmirror* dst);\n", "file_path": "ccl/src/dev/Morpheus_Ccl_Convert.hpp", "rank": 24, "score": 21992.138367196632 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#ifndef MORPHEUS_CCL_PHOST_PRINT_HPP\n\n#define MORPHEUS_CCL_PHOST_PRINT_HPP\n\n\n\n#include <phost/Morpheus_Ccl_CooMatrix.hpp>\n\n#include <phost/Morpheus_Ccl_CsrMatrix.hpp>\n\n#include <phost/Morpheus_Ccl_DenseMatrix.hpp>\n\n#include <phost/Morpheus_Ccl_DiaMatrix.hpp>\n\n#include <phost/Morpheus_Ccl_DynamicMatrix.hpp>\n\n#include <phost/Morpheus_Ccl_DenseVector.hpp>\n\n\n\n#ifdef __cplusplus\n\nextern \"C\" {\n\n#endif\n\n\n\nvoid ccl_phvec_dense_v_print(ccl_phvec_dense_v* v);\n\n\n\nvoid ccl_phmat_coo_print(ccl_phmat_coo* A);\n", "file_path": "ccl/src/phost/Morpheus_Ccl_Print.hpp", "rank": 25, "score": 21991.018374950298 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#ifndef MORPHEUS_CCL_HOST_PRINT_HPP\n\n#define MORPHEUS_CCL_HOST_PRINT_HPP\n\n\n\n#include <host/Morpheus_Ccl_CooMatrix.hpp>\n\n#include <host/Morpheus_Ccl_CsrMatrix.hpp>\n\n#include <host/Morpheus_Ccl_DenseMatrix.hpp>\n\n#include <host/Morpheus_Ccl_DiaMatrix.hpp>\n\n#include <host/Morpheus_Ccl_DynamicMatrix.hpp>\n\n#include <host/Morpheus_Ccl_DenseVector.hpp>\n\n\n\n#ifdef __cplusplus\n\nextern \"C\" {\n\n#endif\n\n\n\nvoid ccl_hvec_dense_v_print(ccl_hvec_dense_v* v);\n\n\n\nvoid ccl_hmat_coo_print(ccl_hmat_coo* A);\n", "file_path": "ccl/src/host/Morpheus_Ccl_Print.hpp", "rank": 26, "score": 21991.018374950298 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#ifndef MORPHEUS_CCL_DEV_PRINT_HPP\n\n#define MORPHEUS_CCL_DEV_PRINT_HPP\n\n\n\n#include <dev/Morpheus_Ccl_CooMatrix.hpp>\n\n#include <dev/Morpheus_Ccl_CsrMatrix.hpp>\n\n#include <dev/Morpheus_Ccl_DenseMatrix.hpp>\n\n#include <dev/Morpheus_Ccl_DiaMatrix.hpp>\n\n#include <dev/Morpheus_Ccl_DynamicMatrix.hpp>\n\n#include <dev/Morpheus_Ccl_DenseVector.hpp>\n\n\n\n#ifdef __cplusplus\n\nextern \"C\" {\n\n#endif\n\n\n\nvoid ccl_dvec_dense_v_hostmirror_print(ccl_dvec_dense_v_hostmirror* v);\n\n\n\nvoid ccl_dmat_coo_hostmirror_print(ccl_dmat_coo_hostmirror* A);\n", "file_path": "ccl/src/dev/Morpheus_Ccl_Print.hpp", "rank": 27, "score": 21990.79545237679 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#ifndef MORPHEUS_CCL_DEV_MULTIPLY_HPP\n\n#define MORPHEUS_CCL_DEV_MULTIPLY_HPP\n\n\n\n#include <dev/Morpheus_Ccl_CooMatrix.hpp>\n\n#include <dev/Morpheus_Ccl_CsrMatrix.hpp>\n\n#include <dev/Morpheus_Ccl_DiaMatrix.hpp>\n\n#include <dev/Morpheus_Ccl_DynamicMatrix.hpp>\n\n#include <dev/Morpheus_Ccl_DenseVector.hpp>\n\n\n\n#ifdef __cplusplus\n\nextern \"C\" {\n\n#endif\n\n\n\nvoid ccl_dmat_coo_dvec_dense_v_multiply(ccl_dmat_coo* A, ccl_dvec_dense_v* x,\n\n ccl_dvec_dense_v* y);\n\n\n\nvoid ccl_dmat_csr_dvec_dense_v_multiply(ccl_dmat_csr* A, ccl_dvec_dense_v* x,\n", "file_path": "ccl/src/dev/Morpheus_Ccl_Multiply.hpp", "rank": 28, "score": 21990.487464948335 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#ifndef MORPHEUS_CCL_HOST_MULTIPLY_HPP\n\n#define MORPHEUS_CCL_HOST_MULTIPLY_HPP\n\n\n\n#include <host/Morpheus_Ccl_CooMatrix.hpp>\n\n#include <host/Morpheus_Ccl_CsrMatrix.hpp>\n\n#include <host/Morpheus_Ccl_DiaMatrix.hpp>\n\n#include <host/Morpheus_Ccl_DynamicMatrix.hpp>\n\n#include <host/Morpheus_Ccl_DenseVector.hpp>\n\n\n\n#ifdef __cplusplus\n\nextern \"C\" {\n\n#endif\n\n\n\nvoid ccl_hmat_coo_hvec_dense_v_multiply(ccl_hmat_coo* A, ccl_hvec_dense_v* x,\n\n ccl_hvec_dense_v* y);\n\n\n\nvoid ccl_hmat_csr_hvec_dense_v_multiply(ccl_hmat_csr* A, ccl_hvec_dense_v* x,\n", "file_path": "ccl/src/host/Morpheus_Ccl_Multiply.hpp", "rank": 29, "score": 21990.487464948335 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#ifndef MORPHEUS_CCL_PHOST_MULTIPLY_HPP\n\n#define MORPHEUS_CCL_PHOST_MULTIPLY_HPP\n\n\n\n#include <phost/Morpheus_Ccl_CooMatrix.hpp>\n\n#include <phost/Morpheus_Ccl_CsrMatrix.hpp>\n\n#include <phost/Morpheus_Ccl_DiaMatrix.hpp>\n\n#include <phost/Morpheus_Ccl_DynamicMatrix.hpp>\n\n#include <phost/Morpheus_Ccl_DenseVector.hpp>\n\n\n\n#ifdef __cplusplus\n\nextern \"C\" {\n\n#endif\n\n\n\nvoid ccl_phmat_coo_phvec_dense_v_multiply(ccl_phmat_coo* A,\n\n ccl_phvec_dense_v* x,\n\n ccl_phvec_dense_v* y);\n\n\n", "file_path": "ccl/src/phost/Morpheus_Ccl_Multiply.hpp", "rank": 30, "score": 21990.321974311788 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#ifndef MORPHEUS_CCL_HOST_SCAN_HPP\n\n#define MORPHEUS_CCL_HOST_SCAN_HPP\n\n\n\n#include <host/Morpheus_Ccl_DenseVector.hpp>\n\n\n\n#ifdef __cplusplus\n\nextern \"C\" {\n\n#endif\n\n\n\nvoid ccl_hvec_dense_v_inclusive_scan(const ccl_hvec_dense_v* in,\n\n ccl_hvec_dense_v* out, ccl_index_t size,\n\n ccl_index_t start);\n\n\n\nvoid ccl_hvec_dense_v_exclusive_scan(const ccl_hvec_dense_v* in,\n\n ccl_hvec_dense_v* out, ccl_index_t size,\n\n ccl_index_t start);\n\n\n", "file_path": "ccl/src/host/Morpheus_Ccl_Scan.hpp", "rank": 31, "score": 21989.523647849288 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#ifndef MORPHEUS_CCL_PHOST_SCAN_HPP\n\n#define MORPHEUS_CCL_PHOST_SCAN_HPP\n\n\n\n#include <phost/Morpheus_Ccl_DenseVector.hpp>\n\n\n\n#ifdef __cplusplus\n\nextern \"C\" {\n\n#endif\n\n\n\nvoid ccl_phvec_dense_v_inclusive_scan(const ccl_phvec_dense_v* in,\n\n ccl_phvec_dense_v* out, ccl_index_t size,\n\n ccl_index_t start);\n\n\n\nvoid ccl_phvec_dense_v_exclusive_scan(const ccl_phvec_dense_v* in,\n\n ccl_phvec_dense_v* out, ccl_index_t size,\n\n ccl_index_t start);\n\n\n", "file_path": "ccl/src/phost/Morpheus_Ccl_Scan.hpp", "rank": 32, "score": 21989.523647849288 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#include <phost/Morpheus_Ccl_Convert.hpp>\n\n\n\n// coo -> coo\n\nvoid ccl_phmat_coo_convert_to_phmat_coo(const ccl_phmat_coo* src,\n\n ccl_phmat_coo* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n\n\n// csr -> csr\n\nvoid ccl_phmat_csr_convert_to_phmat_csr(const ccl_phmat_csr* src,\n\n ccl_phmat_csr* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n// csr -> coo\n\nvoid ccl_phmat_csr_convert_to_phmat_coo(const ccl_phmat_csr* src,\n\n ccl_phmat_coo* dst) {\n\n Morpheus::convert(*src, *dst);\n", "file_path": "ccl/src/phost/Morpheus_Ccl_Convert.cpp", "rank": 33, "score": 21988.796916645962 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#include <host/Morpheus_Ccl_Convert.hpp>\n\n\n\n// coo -> coo\n\nvoid ccl_hmat_coo_convert_to_hmat_coo(const ccl_hmat_coo* src,\n\n ccl_hmat_coo* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n\n\n// csr -> csr\n\nvoid ccl_hmat_csr_convert_to_hmat_csr(const ccl_hmat_csr* src,\n\n ccl_hmat_csr* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n// csr -> coo\n\nvoid ccl_hmat_csr_convert_to_hmat_coo(const ccl_hmat_csr* src,\n\n ccl_hmat_coo* dst) {\n\n Morpheus::convert(*src, *dst);\n", "file_path": "ccl/src/host/Morpheus_Ccl_Convert.cpp", "rank": 34, "score": 21988.796916645962 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#include <dev/Morpheus_Ccl_Copy.hpp>\n\n\n\n// coo -> coo\n\nvoid ccl_dmat_coo_copy_to_dmat_coo(const ccl_dmat_coo* src, ccl_dmat_coo* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// coo -> coo_hostmirror\n\nvoid ccl_dmat_coo_copy_to_dmat_coo_hostmirror(const ccl_dmat_coo* src,\n\n ccl_dmat_coo_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// coo_hostmirror -> coo\n\nvoid ccl_dmat_coo_hostmirror_copy_to_dmat_coo(\n\n const ccl_dmat_coo_hostmirror* src, ccl_dmat_coo* dst) {\n\n Morpheus::copy(*src, *dst);\n", "file_path": "ccl/src/dev/Morpheus_Ccl_Copy.cpp", "rank": 35, "score": 21988.562510347874 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#include <host/Morpheus_Ccl_Copy.hpp>\n\n\n\n// coo -> coo\n\nvoid ccl_hmat_coo_copy_to_hmat_coo(const ccl_hmat_coo* src, ccl_hmat_coo* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// coo -> coo_hostmirror\n\nvoid ccl_hmat_coo_copy_to_hmat_coo_hostmirror(const ccl_hmat_coo* src,\n\n ccl_hmat_coo_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// coo_hostmirror -> coo\n\nvoid ccl_hmat_coo_hostmirror_copy_to_hmat_coo(\n\n const ccl_hmat_coo_hostmirror* src, ccl_hmat_coo* dst) {\n\n Morpheus::copy(*src, *dst);\n", "file_path": "ccl/src/host/Morpheus_Ccl_Copy.cpp", "rank": 36, "score": 21988.562510347874 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#include <phost/Morpheus_Ccl_Copy.hpp>\n\n\n\n// coo -> coo\n\nvoid ccl_phmat_coo_copy_to_phmat_coo(const ccl_phmat_coo* src,\n\n ccl_phmat_coo* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// coo -> coo_hostmirror\n\nvoid ccl_phmat_coo_copy_to_phmat_coo_hostmirror(const ccl_phmat_coo* src,\n\n ccl_phmat_coo_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// coo_hostmirror -> coo\n\nvoid ccl_phmat_coo_hostmirror_copy_to_phmat_coo(\n\n const ccl_phmat_coo_hostmirror* src, ccl_phmat_coo* dst) {\n", "file_path": "ccl/src/phost/Morpheus_Ccl_Copy.cpp", "rank": 37, "score": 21988.538856993237 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#include <dev/Morpheus_Ccl_Convert.hpp>\n\n\n\n// coo -> coo\n\nvoid ccl_dmat_coo_hostmirror_convert_to_dmat_coo_hostmirror(\n\n const ccl_dmat_coo_hostmirror* src, ccl_dmat_coo_hostmirror* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n\n\n// csr -> csr\n\nvoid ccl_dmat_csr_hostmirror_convert_to_dmat_csr_hostmirror(\n\n const ccl_dmat_csr_hostmirror* src, ccl_dmat_csr_hostmirror* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n// csr -> coo\n\nvoid ccl_dmat_csr_hostmirror_convert_to_dmat_coo_hostmirror(\n\n const ccl_dmat_csr_hostmirror* src, ccl_dmat_coo_hostmirror* dst) {\n\n Morpheus::convert(*src, *dst);\n", "file_path": "ccl/src/dev/Morpheus_Ccl_Convert.cpp", "rank": 38, "score": 21988.339764241868 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#ifndef MORPHEUS_CCL_DEV_WAXPBY_HPP\n\n#define MORPHEUS_CCL_DEV_WAXPBY_HPP\n\n\n\n#include <dev/Morpheus_Ccl_DenseVector.hpp>\n\n\n\n#ifdef __cplusplus\n\nextern \"C\" {\n\n#endif\n\n\n\nvoid ccl_dvec_dense_v_waxpby(ccl_index_t n, ccl_value_t alpha,\n\n const ccl_dvec_dense_v* x, ccl_value_t beta,\n\n const ccl_dvec_dense_v* y, ccl_dvec_dense_v* w);\n\n\n\nvoid ccl_dvec_dense_v_hostmirror_waxpby(ccl_index_t n, ccl_value_t alpha,\n\n const ccl_dvec_dense_v_hostmirror* x,\n\n ccl_value_t beta,\n\n const ccl_dvec_dense_v_hostmirror* y,\n\n ccl_dvec_dense_v_hostmirror* w);\n\n\n\n#ifdef __cplusplus\n\n}\n\n#endif\n\n\n\n#endif // MORPHEUS_CCL_DEV_WAXPBY_HPP\n", "file_path": "ccl/src/dev/Morpheus_Ccl_WAXPBY.hpp", "rank": 39, "score": 21988.25619786344 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#ifndef MORPHEUS_CCL_HOST_WAXPBY_HPP\n\n#define MORPHEUS_CCL_HOST_WAXPBY_HPP\n\n\n\n#include <host/Morpheus_Ccl_DenseVector.hpp>\n\n\n\n#ifdef __cplusplus\n\nextern \"C\" {\n\n#endif\n\n\n\nvoid ccl_hvec_dense_v_waxpby(ccl_index_t n, ccl_value_t alpha,\n\n const ccl_hvec_dense_v* x, ccl_value_t beta,\n\n const ccl_hvec_dense_v* y, ccl_hvec_dense_v* w);\n\n\n\nvoid ccl_hvec_dense_v_hostmirror_waxpby(ccl_index_t n, ccl_value_t alpha,\n\n const ccl_hvec_dense_v_hostmirror* x,\n\n ccl_value_t beta,\n\n const ccl_hvec_dense_v_hostmirror* y,\n\n ccl_hvec_dense_v_hostmirror* w);\n\n\n\n#ifdef __cplusplus\n\n}\n\n#endif\n\n\n\n#endif // MORPHEUS_CCL_HOST_WAXPBY_HPP\n", "file_path": "ccl/src/host/Morpheus_Ccl_WAXPBY.hpp", "rank": 40, "score": 21988.25619786344 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#ifndef MORPHEUS_CCL_PHOST_WAXPBY_HPP\n\n#define MORPHEUS_CCL_PHOST_WAXPBY_HPP\n\n\n\n#include <phost/Morpheus_Ccl_DenseVector.hpp>\n\n\n\n#ifdef __cplusplus\n\nextern \"C\" {\n\n#endif\n\n\n\nvoid ccl_phvec_dense_v_waxpby(ccl_index_t n, ccl_value_t alpha,\n\n const ccl_phvec_dense_v* x, ccl_value_t beta,\n\n const ccl_phvec_dense_v* y, ccl_phvec_dense_v* w);\n\n\n\nvoid ccl_phvec_dense_v_hostmirror_waxpby(ccl_index_t n, ccl_value_t alpha,\n\n const ccl_phvec_dense_v_hostmirror* x,\n\n ccl_value_t beta,\n\n const ccl_phvec_dense_v_hostmirror* y,\n\n ccl_phvec_dense_v_hostmirror* w);\n\n\n\n#ifdef __cplusplus\n\n}\n\n#endif\n\n\n\n#endif // MORPHEUS_CCL_PHOST_WAXPBY_HPP\n", "file_path": "ccl/src/phost/Morpheus_Ccl_WAXPBY.hpp", "rank": 41, "score": 21988.25619786344 }, { "content": " ccl_hmat_csr* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\nvoid ccl_hmat_dyn_convert_to_hmat_dia(const ccl_hmat_dyn* src,\n\n ccl_hmat_dia* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n\n\n// concrete -> dynamic\n\nvoid ccl_hmat_coo_convert_to_hmat_dyn(const ccl_hmat_coo* src,\n\n ccl_hmat_dyn* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n\n\nvoid ccl_hmat_csr_convert_to_hmat_dyn(const ccl_hmat_csr* src,\n\n ccl_hmat_dyn* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n\n\nvoid ccl_hmat_dia_convert_to_hmat_dyn(const ccl_hmat_dia* src,\n", "file_path": "ccl/src/host/Morpheus_Ccl_Convert.cpp", "rank": 42, "score": 21986.597037063857 }, { "content": " ccl_phmat_csr* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\nvoid ccl_phmat_dyn_convert_to_phmat_dia(const ccl_phmat_dyn* src,\n\n ccl_phmat_dia* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n\n\n// concrete -> dynamic\n\nvoid ccl_phmat_coo_convert_to_phmat_dyn(const ccl_phmat_coo* src,\n\n ccl_phmat_dyn* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n\n\nvoid ccl_phmat_csr_convert_to_phmat_dyn(const ccl_phmat_csr* src,\n\n ccl_phmat_dyn* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n\n\nvoid ccl_phmat_dia_convert_to_phmat_dyn(const ccl_phmat_dia* src,\n", "file_path": "ccl/src/phost/Morpheus_Ccl_Convert.cpp", "rank": 43, "score": 21986.597037063857 }, { "content": "// dynamic -> concrete\n\nvoid ccl_phmat_dyn_convert_to_phmat_coo(const ccl_phmat_dyn* src,\n\n ccl_phmat_coo* dst);\n\nvoid ccl_phmat_dyn_convert_to_phmat_csr(const ccl_phmat_dyn* src,\n\n ccl_phmat_csr* dst);\n\nvoid ccl_phmat_dyn_convert_to_phmat_dia(const ccl_phmat_dyn* src,\n\n ccl_phmat_dia* dst);\n\n\n\n// concrete -> dynamic\n\nvoid ccl_phmat_coo_convert_to_phmat_dyn(const ccl_phmat_coo* src,\n\n ccl_phmat_dyn* dst);\n\n\n\nvoid ccl_phmat_csr_convert_to_phmat_dyn(const ccl_phmat_csr* src,\n\n ccl_phmat_dyn* dst);\n\n\n\nvoid ccl_phmat_dia_convert_to_phmat_dyn(const ccl_phmat_dia* src,\n\n ccl_phmat_dyn* dst);\n\n\n\n// dynamic -> dynamic\n\nvoid ccl_phmat_dyn_convert_to_phmat_dyn(const ccl_phmat_dyn* src,\n", "file_path": "ccl/src/phost/Morpheus_Ccl_Convert.hpp", "rank": 44, "score": 21986.537866285897 }, { "content": "// dynamic -> concrete\n\nvoid ccl_hmat_dyn_convert_to_hmat_coo(const ccl_hmat_dyn* src,\n\n ccl_hmat_coo* dst);\n\nvoid ccl_hmat_dyn_convert_to_hmat_csr(const ccl_hmat_dyn* src,\n\n ccl_hmat_csr* dst);\n\nvoid ccl_hmat_dyn_convert_to_hmat_dia(const ccl_hmat_dyn* src,\n\n ccl_hmat_dia* dst);\n\n\n\n// concrete -> dynamic\n\nvoid ccl_hmat_coo_convert_to_hmat_dyn(const ccl_hmat_coo* src,\n\n ccl_hmat_dyn* dst);\n\n\n\nvoid ccl_hmat_csr_convert_to_hmat_dyn(const ccl_hmat_csr* src,\n\n ccl_hmat_dyn* dst);\n\n\n\nvoid ccl_hmat_dia_convert_to_hmat_dyn(const ccl_hmat_dia* src,\n\n ccl_hmat_dyn* dst);\n\n\n\n// dynamic -> dynamic\n\nvoid ccl_hmat_dyn_convert_to_hmat_dyn(const ccl_hmat_dyn* src,\n", "file_path": "ccl/src/host/Morpheus_Ccl_Convert.hpp", "rank": 45, "score": 21986.537866285897 }, { "content": " Morpheus::convert(*src, *dst);\n\n}\n\n// coo -> dia\n\nvoid ccl_hmat_coo_convert_to_hmat_dia(const ccl_hmat_coo* src,\n\n ccl_hmat_dia* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n// dia -> csr\n\nvoid ccl_hmat_dia_convert_to_hmat_csr(const ccl_hmat_dia* src,\n\n ccl_hmat_csr* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n\n\n// dense mat -> dense mat\n\nvoid ccl_hmat_dense_convert_to_hmat_dense(const ccl_hmat_dense* src,\n\n ccl_hmat_dense* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n// dense mat -> dense vec\n\nvoid ccl_hmat_dense_convert_to_hvec_dense_v(const ccl_hmat_dense* src,\n", "file_path": "ccl/src/host/Morpheus_Ccl_Convert.cpp", "rank": 46, "score": 21986.483202784155 }, { "content": " ccl_hvec_dense_v* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n// dense mat -> coo\n\nvoid ccl_hmat_dense_convert_to_hmat_coo(const ccl_hmat_dense* src,\n\n ccl_hmat_coo* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n// coo -> dense mat\n\nvoid ccl_hmat_coo_convert_to_hmat_dense(const ccl_hmat_coo* src,\n\n ccl_hmat_dense* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n\n\n// dynamic -> concrete\n\nvoid ccl_hmat_dyn_convert_to_hmat_coo(const ccl_hmat_dyn* src,\n\n ccl_hmat_coo* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\nvoid ccl_hmat_dyn_convert_to_hmat_csr(const ccl_hmat_dyn* src,\n", "file_path": "ccl/src/host/Morpheus_Ccl_Convert.cpp", "rank": 47, "score": 21986.483202784155 }, { "content": " ccl_phvec_dense_v* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n// dense mat -> coo\n\nvoid ccl_phmat_dense_convert_to_phmat_coo(const ccl_phmat_dense* src,\n\n ccl_phmat_coo* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n// coo -> dense mat\n\nvoid ccl_phmat_coo_convert_to_phmat_dense(const ccl_phmat_coo* src,\n\n ccl_phmat_dense* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n\n\n// dynamic -> concrete\n\nvoid ccl_phmat_dyn_convert_to_phmat_coo(const ccl_phmat_dyn* src,\n\n ccl_phmat_coo* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\nvoid ccl_phmat_dyn_convert_to_phmat_csr(const ccl_phmat_dyn* src,\n", "file_path": "ccl/src/phost/Morpheus_Ccl_Convert.cpp", "rank": 48, "score": 21986.483202784155 }, { "content": " Morpheus::convert(*src, *dst);\n\n}\n\n// coo -> dia\n\nvoid ccl_phmat_coo_convert_to_phmat_dia(const ccl_phmat_coo* src,\n\n ccl_phmat_dia* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n// dia -> csr\n\nvoid ccl_phmat_dia_convert_to_phmat_csr(const ccl_phmat_dia* src,\n\n ccl_phmat_csr* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n\n\n// dense mat -> dense mat\n\nvoid ccl_phmat_dense_convert_to_phmat_dense(const ccl_phmat_dense* src,\n\n ccl_phmat_dense* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n// dense mat -> dense vec\n\nvoid ccl_phmat_dense_convert_to_phvec_dense_v(const ccl_phmat_dense* src,\n", "file_path": "ccl/src/phost/Morpheus_Ccl_Convert.cpp", "rank": 49, "score": 21986.483202784155 }, { "content": "}\n\n// coo -> csr\n\nvoid ccl_hmat_coo_convert_to_hmat_csr(const ccl_hmat_coo* src,\n\n ccl_hmat_csr* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n// csr -> dia\n\nvoid ccl_hmat_csr_convert_to_hmat_dia(const ccl_hmat_csr* src,\n\n ccl_hmat_dia* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n\n\n// dia -> dia\n\nvoid ccl_hmat_dia_convert_to_hmat_dia(const ccl_hmat_dia* src,\n\n ccl_hmat_dia* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n// dia -> coo\n\nvoid ccl_hmat_dia_convert_to_hmat_coo(const ccl_hmat_dia* src,\n\n ccl_hmat_coo* dst) {\n", "file_path": "ccl/src/host/Morpheus_Ccl_Convert.cpp", "rank": 50, "score": 21986.44600157066 }, { "content": "}\n\n// coo -> csr\n\nvoid ccl_phmat_coo_convert_to_phmat_csr(const ccl_phmat_coo* src,\n\n ccl_phmat_csr* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n// csr -> dia\n\nvoid ccl_phmat_csr_convert_to_phmat_dia(const ccl_phmat_csr* src,\n\n ccl_phmat_dia* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n\n\n// dia -> dia\n\nvoid ccl_phmat_dia_convert_to_phmat_dia(const ccl_phmat_dia* src,\n\n ccl_phmat_dia* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n// dia -> coo\n\nvoid ccl_phmat_dia_convert_to_phmat_coo(const ccl_phmat_dia* src,\n\n ccl_phmat_coo* dst) {\n", "file_path": "ccl/src/phost/Morpheus_Ccl_Convert.cpp", "rank": 51, "score": 21986.44600157066 }, { "content": "void ccl_hmat_dyn_hostmirror_copy_to_hmat_dyn_hostmirror(\n\n const ccl_hmat_dyn_hostmirror* src, ccl_hmat_dyn_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// coo -> dyn\n\nvoid ccl_hmat_coo_copy_to_hmat_dyn(const ccl_hmat_coo* src, ccl_hmat_dyn* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn -> coo\n\nvoid ccl_hmat_dyn_copy_to_hmat_coo(const ccl_hmat_dyn* src, ccl_hmat_coo* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// coo_hostmirror -> dyn\n\nvoid ccl_hmat_coo_hostmirror_copy_to_hmat_dyn(\n\n const ccl_hmat_coo_hostmirror* src, ccl_hmat_dyn* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n", "file_path": "ccl/src/host/Morpheus_Ccl_Copy.cpp", "rank": 52, "score": 21986.390696717728 }, { "content": "void ccl_dmat_dyn_hostmirror_copy_to_dmat_dyn_hostmirror(\n\n const ccl_dmat_dyn_hostmirror* src, ccl_dmat_dyn_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// coo -> dyn\n\nvoid ccl_dmat_coo_copy_to_dmat_dyn(const ccl_dmat_coo* src, ccl_dmat_dyn* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn -> coo\n\nvoid ccl_dmat_dyn_copy_to_dmat_coo(const ccl_dmat_dyn* src, ccl_dmat_coo* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// coo_hostmirror -> dyn\n\nvoid ccl_dmat_coo_hostmirror_copy_to_dmat_dyn(\n\n const ccl_dmat_coo_hostmirror* src, ccl_dmat_dyn* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n", "file_path": "ccl/src/dev/Morpheus_Ccl_Copy.cpp", "rank": 53, "score": 21986.390696717728 }, { "content": "void ccl_dmat_coo_hostmirror_copy_to_dmat_dyn_hostmirror(\n\n const ccl_dmat_coo_hostmirror* src, ccl_dmat_dyn_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn_hostmirror -> coo_hostmirror\n\nvoid ccl_dmat_dyn_hostmirror_copy_to_dmat_coo_hostmirror(\n\n const ccl_dmat_dyn_hostmirror* src, ccl_dmat_coo_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// csr -> dyn\n\nvoid ccl_dmat_csr_copy_to_dmat_dyn(const ccl_dmat_csr* src, ccl_dmat_dyn* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn -> csr\n\nvoid ccl_copy_dmat_dyn_to_dmat_csr(const ccl_dmat_dyn* src, ccl_dmat_csr* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n", "file_path": "ccl/src/dev/Morpheus_Ccl_Copy.cpp", "rank": 54, "score": 21986.336186844153 }, { "content": "void ccl_hmat_coo_hostmirror_copy_to_hmat_dyn_hostmirror(\n\n const ccl_hmat_coo_hostmirror* src, ccl_hmat_dyn_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn_hostmirror -> coo_hostmirror\n\nvoid ccl_hmat_dyn_hostmirror_copy_to_hmat_coo_hostmirror(\n\n const ccl_hmat_dyn_hostmirror* src, ccl_hmat_coo_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// csr -> dyn\n\nvoid ccl_hmat_csr_copy_to_hmat_dyn(const ccl_hmat_csr* src, ccl_hmat_dyn* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn -> csr\n\nvoid ccl_copy_hmat_dyn_to_hmat_csr(const ccl_hmat_dyn* src, ccl_hmat_csr* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n", "file_path": "ccl/src/host/Morpheus_Ccl_Copy.cpp", "rank": 55, "score": 21986.336186844153 }, { "content": "void ccl_phvec_dense_v_hostmirror_copy_to_phvec_dense_v_hostmirror(\n\n const ccl_phvec_dense_v_hostmirror* src,\n\n ccl_phvec_dense_v_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn -> dyn\n\nvoid ccl_phmat_dyn_copy_to_phmat_dyn(const ccl_phmat_dyn* src,\n\n ccl_phmat_dyn* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn -> dyn_hostmirror\n\nvoid ccl_phmat_dyn_copy_to_phmat_dyn_hostmirror(const ccl_phmat_dyn* src,\n\n ccl_phmat_dyn_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn_hostmirror -> dyn\n\nvoid ccl_phmat_dyn_hostmirror_copy_to_phmat_dyn(\n", "file_path": "ccl/src/phost/Morpheus_Ccl_Copy.cpp", "rank": 56, "score": 21986.32412462613 }, { "content": "void ccl_hmat_csr_hostmirror_copy_to_hmat_csr(\n\n const ccl_hmat_csr_hostmirror* src, ccl_hmat_csr* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// csr_hostmirror -> csr_hostmirror\n\nvoid ccl_hmat_csr_hostmirror_copy_to_hmat_csr_hostmirror(\n\n const ccl_hmat_csr_hostmirror* src, ccl_hmat_csr_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dia -> dia\n\nvoid ccl_hmat_dia_copy_to_hmat_dia(const ccl_hmat_dia* src, ccl_hmat_dia* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dia -> dia_hostmirror\n\nvoid ccl_hmat_dia_copy_to_hmat_dia_hostmirror(const ccl_hmat_dia* src,\n\n ccl_hmat_dia_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n", "file_path": "ccl/src/host/Morpheus_Ccl_Copy.cpp", "rank": 57, "score": 21986.318178982747 }, { "content": "void ccl_dmat_csr_hostmirror_copy_to_dmat_csr(\n\n const ccl_dmat_csr_hostmirror* src, ccl_dmat_csr* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// csr_hostmirror -> csr_hostmirror\n\nvoid ccl_dmat_csr_hostmirror_copy_to_dmat_csr_hostmirror(\n\n const ccl_dmat_csr_hostmirror* src, ccl_dmat_csr_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dia -> dia\n\nvoid ccl_dmat_dia_copy_to_dmat_dia(const ccl_dmat_dia* src, ccl_dmat_dia* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dia -> dia_hostmirror\n\nvoid ccl_dmat_dia_copy_to_dmat_dia_hostmirror(const ccl_dmat_dia* src,\n\n ccl_dmat_dia_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n", "file_path": "ccl/src/dev/Morpheus_Ccl_Copy.cpp", "rank": 58, "score": 21986.318178982747 }, { "content": "\n\n// csr -> csr\n\nvoid ccl_phmat_csr_convert_to_phmat_csr(const ccl_phmat_csr* src,\n\n ccl_phmat_csr* dst);\n\n// csr -> coo\n\nvoid ccl_phmat_csr_convert_to_phmat_coo(const ccl_phmat_csr* src,\n\n ccl_phmat_coo* dst);\n\n// coo -> csr\n\nvoid ccl_phmat_coo_convert_to_phmat_csr(const ccl_phmat_coo* src,\n\n ccl_phmat_csr* dst);\n\n// csr -> dia\n\nvoid ccl_phmat_csr_convert_to_phmat_dia(const ccl_phmat_csr* src,\n\n ccl_phmat_dia* dst);\n\n\n\n// dia -> dia\n\nvoid ccl_phmat_dia_convert_to_phmat_dia(const ccl_phmat_dia* src,\n\n ccl_phmat_dia* dst);\n\n// dia -> coo\n\nvoid ccl_phmat_dia_convert_to_phmat_coo(const ccl_phmat_dia* src,\n\n ccl_phmat_coo* dst);\n", "file_path": "ccl/src/phost/Morpheus_Ccl_Convert.hpp", "rank": 59, "score": 21986.309990547452 }, { "content": "\n\n// csr -> csr\n\nvoid ccl_hmat_csr_convert_to_hmat_csr(const ccl_hmat_csr* src,\n\n ccl_hmat_csr* dst);\n\n// csr -> coo\n\nvoid ccl_hmat_csr_convert_to_hmat_coo(const ccl_hmat_csr* src,\n\n ccl_hmat_coo* dst);\n\n// coo -> csr\n\nvoid ccl_hmat_coo_convert_to_hmat_csr(const ccl_hmat_coo* src,\n\n ccl_hmat_csr* dst);\n\n// csr -> dia\n\nvoid ccl_hmat_csr_convert_to_hmat_dia(const ccl_hmat_csr* src,\n\n ccl_hmat_dia* dst);\n\n\n\n// dia -> dia\n\nvoid ccl_hmat_dia_convert_to_hmat_dia(const ccl_hmat_dia* src,\n\n ccl_hmat_dia* dst);\n\n// dia -> coo\n\nvoid ccl_hmat_dia_convert_to_hmat_coo(const ccl_hmat_dia* src,\n\n ccl_hmat_coo* dst);\n", "file_path": "ccl/src/host/Morpheus_Ccl_Convert.hpp", "rank": 60, "score": 21986.309990547452 }, { "content": "// dyn_hostmirror -> csr_hostmirror\n\nvoid ccl_phmat_dyn_hostmirror_copy_to_phmat_csr_hostmirror(\n\n const ccl_phmat_dyn_hostmirror* src, ccl_phmat_csr_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dia -> dyn\n\nvoid ccl_phmat_dia_copy_to_phmat_dyn(const ccl_phmat_dia* src,\n\n ccl_phmat_dyn* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn -> dia\n\nvoid ccl_phmat_dyn_copy_to_phmat_dia(const ccl_phmat_dyn* src,\n\n ccl_phmat_dia* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dia_hostmirror -> dyn\n\nvoid ccl_phmat_dia_hostmirror_copy_to_phmat_dyn(\n", "file_path": "ccl/src/phost/Morpheus_Ccl_Copy.cpp", "rank": 61, "score": 21986.30338603569 }, { "content": " const ccl_dmat_dyn_hostmirror* src, ccl_dmat_csr_hostmirror* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\nvoid ccl_dmat_dyn_hostmirror_convert_to_dmat_dia_hostmirror(\n\n const ccl_dmat_dyn_hostmirror* src, ccl_dmat_dia_hostmirror* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n\n\n// concrete -> dynamic\n\nvoid ccl_dmat_coo_hostmirror_convert_to_dmat_dyn_hostmirror(\n\n const ccl_dmat_coo_hostmirror* src, ccl_dmat_dyn_hostmirror* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n\n\nvoid ccl_dmat_csr_hostmirror_convert_to_dmat_dyn_hostmirror(\n\n const ccl_dmat_csr_hostmirror* src, ccl_dmat_dyn_hostmirror* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n\n\nvoid ccl_dmat_dia_hostmirror_convert_to_dmat_dyn_hostmirror(\n", "file_path": "ccl/src/dev/Morpheus_Ccl_Convert.cpp", "rank": 62, "score": 21986.300251212928 }, { "content": "void ccl_hmat_dyn_hostmirror_copy_to_hmat_csr(\n\n const ccl_hmat_dyn_hostmirror* src, ccl_hmat_csr* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// csr_hostmirror -> dyn_hostmirror\n\nvoid ccl_hmat_csr_hostmirror_copy_to_hmat_dyn_hostmirror(\n\n const ccl_hmat_csr_hostmirror* src, ccl_hmat_dyn_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn_hostmirror -> csr_hostmirror\n\nvoid ccl_hmat_dyn_hostmirror_copy_to_hmat_csr_hostmirror(\n\n const ccl_hmat_dyn_hostmirror* src, ccl_hmat_csr_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dia -> dyn\n\nvoid ccl_hmat_dia_copy_to_hmat_dyn(const ccl_hmat_dia* src, ccl_hmat_dyn* dst) {\n\n Morpheus::copy(*src, *dst);\n", "file_path": "ccl/src/host/Morpheus_Ccl_Copy.cpp", "rank": 63, "score": 21986.26463369165 }, { "content": "void ccl_dmat_dyn_hostmirror_copy_to_dmat_csr(\n\n const ccl_dmat_dyn_hostmirror* src, ccl_dmat_csr* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// csr_hostmirror -> dyn_hostmirror\n\nvoid ccl_dmat_csr_hostmirror_copy_to_dmat_dyn_hostmirror(\n\n const ccl_dmat_csr_hostmirror* src, ccl_dmat_dyn_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn_hostmirror -> csr_hostmirror\n\nvoid ccl_dmat_dyn_hostmirror_copy_to_dmat_csr_hostmirror(\n\n const ccl_dmat_dyn_hostmirror* src, ccl_dmat_csr_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dia -> dyn\n\nvoid ccl_dmat_dia_copy_to_dmat_dyn(const ccl_dmat_dia* src, ccl_dmat_dyn* dst) {\n\n Morpheus::copy(*src, *dst);\n", "file_path": "ccl/src/dev/Morpheus_Ccl_Copy.cpp", "rank": 64, "score": 21986.26463369165 }, { "content": "// dyn_hostmirror -> coo\n\nvoid ccl_phmat_dyn_hostmirror_copy_to_phmat_coo(\n\n const ccl_phmat_dyn_hostmirror* src, ccl_phmat_coo* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// coo_hostmirror -> dyn_hostmirror\n\nvoid ccl_phmat_coo_hostmirror_copy_to_phmat_dyn_hostmirror(\n\n const ccl_phmat_coo_hostmirror* src, ccl_phmat_dyn_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn_hostmirror -> coo_hostmirror\n\nvoid ccl_phmat_dyn_hostmirror_copy_to_phmat_coo_hostmirror(\n\n const ccl_phmat_dyn_hostmirror* src, ccl_phmat_coo_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// csr -> dyn\n\nvoid ccl_phmat_csr_copy_to_phmat_dyn(const ccl_phmat_csr* src,\n", "file_path": "ccl/src/phost/Morpheus_Ccl_Copy.cpp", "rank": 65, "score": 21986.23366885312 }, { "content": "void ccl_phmat_dia_copy_to_phmat_dia_hostmirror(const ccl_phmat_dia* src,\n\n ccl_phmat_dia_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dia_hostmirror -> dia\n\nvoid ccl_phmat_dia_hostmirror_copy_to_phmat_dia(\n\n const ccl_phmat_dia_hostmirror* src, ccl_phmat_dia* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dia_hostmirror -> dia_hostmirror\n\nvoid ccl_phmat_dia_hostmirror_copy_to_phmat_dia_hostmirror(\n\n const ccl_phmat_dia_hostmirror* src, ccl_phmat_dia_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// mat dense -> mat dense\n\nvoid ccl_phmat_dense_copy_to_phmat_dense(const ccl_phmat_dense* src,\n\n ccl_phmat_dense* dst) {\n", "file_path": "ccl/src/phost/Morpheus_Ccl_Copy.cpp", "rank": 66, "score": 21986.23366885312 }, { "content": " const ccl_dmat_dense_hostmirror* src, ccl_dvec_dense_v_hostmirror* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n// dense mat -> coo\n\nvoid ccl_dmat_dense_hostmirror_convert_to_dmat_coo_hostmirror(\n\n const ccl_dmat_dense_hostmirror* src, ccl_dmat_coo_hostmirror* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n// coo -> dense mat\n\nvoid ccl_dmat_coo_hostmirror_convert_to_dmat_dense(\n\n const ccl_dmat_coo_hostmirror* src, ccl_dmat_dense* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n\n\n// dynamic -> concrete\n\nvoid ccl_dmat_dyn_hostmirror_convert_to_dmat_coo_hostmirror(\n\n const ccl_dmat_dyn_hostmirror* src, ccl_dmat_coo_hostmirror* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\nvoid ccl_dmat_dyn_hostmirror_convert_to_dmat_csr_hostmirror(\n", "file_path": "ccl/src/dev/Morpheus_Ccl_Convert.cpp", "rank": 67, "score": 21986.229329822687 }, { "content": "void ccl_hmat_dia_copy_to_hmat_dyn_hostmirror(const ccl_hmat_dia* src,\n\n ccl_hmat_dyn_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn_hostmirror -> dia\n\nvoid ccl_hmat_dyn_hostmirror_copy_to_hmat_dia(\n\n const ccl_hmat_dyn_hostmirror* src, ccl_hmat_dia* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dia_hostmirror -> dyn_hostmirror\n\nvoid ccl_hmat_dia_hostmirror_copy_to_hmat_dyn_hostmirror(\n\n const ccl_hmat_dia_hostmirror* src, ccl_hmat_dyn_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn_hostmirror -> dia_hostmirror\n\nvoid ccl_hmat_dyn_hostmirror_copy_to_hmat_dia_hostmirror(\n\n const ccl_hmat_dyn_hostmirror* src, ccl_hmat_dia_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n", "file_path": "ccl/src/host/Morpheus_Ccl_Copy.cpp", "rank": 68, "score": 21986.211794138588 }, { "content": "void ccl_dmat_dia_copy_to_dmat_dyn_hostmirror(const ccl_dmat_dia* src,\n\n ccl_dmat_dyn_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn_hostmirror -> dia\n\nvoid ccl_dmat_dyn_hostmirror_copy_to_dmat_dia(\n\n const ccl_dmat_dyn_hostmirror* src, ccl_dmat_dia* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dia_hostmirror -> dyn_hostmirror\n\nvoid ccl_dmat_dia_hostmirror_copy_to_dmat_dyn_hostmirror(\n\n const ccl_dmat_dia_hostmirror* src, ccl_dmat_dyn_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn_hostmirror -> dia_hostmirror\n\nvoid ccl_dmat_dyn_hostmirror_copy_to_dmat_dia_hostmirror(\n\n const ccl_dmat_dyn_hostmirror* src, ccl_dmat_dia_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n", "file_path": "ccl/src/dev/Morpheus_Ccl_Copy.cpp", "rank": 69, "score": 21986.211794138588 }, { "content": "// coo -> dia\n\nvoid ccl_hmat_coo_convert_to_hmat_dia(const ccl_hmat_coo* src,\n\n ccl_hmat_dia* dst);\n\n// dia -> csr\n\nvoid ccl_hmat_dia_convert_to_hmat_csr(const ccl_hmat_dia* src,\n\n ccl_hmat_csr* dst);\n\n\n\n// dense mat -> dense mat\n\nvoid ccl_hmat_dense_convert_to_hmat_dense(const ccl_hmat_dense* src,\n\n ccl_hmat_dense* dst);\n\n// dense mat -> dense vec\n\nvoid ccl_hmat_dense_convert_to_hvec_dense_v(const ccl_hmat_dense* src,\n\n ccl_hvec_dense_v* dst);\n\n// dense mat -> coo\n\nvoid ccl_hmat_dense_convert_to_hmat_coo(const ccl_hmat_dense* src,\n\n ccl_hmat_coo* dst);\n\n// coo -> dense mat\n\nvoid ccl_hmat_coo_convert_to_hmat_dense(const ccl_hmat_coo* src,\n\n ccl_hmat_dense* dst);\n\n\n", "file_path": "ccl/src/host/Morpheus_Ccl_Convert.hpp", "rank": 70, "score": 21986.208992060783 }, { "content": "// coo -> dia\n\nvoid ccl_phmat_coo_convert_to_phmat_dia(const ccl_phmat_coo* src,\n\n ccl_phmat_dia* dst);\n\n// dia -> csr\n\nvoid ccl_phmat_dia_convert_to_phmat_csr(const ccl_phmat_dia* src,\n\n ccl_phmat_csr* dst);\n\n\n\n// dense mat -> dense mat\n\nvoid ccl_phmat_dense_convert_to_phmat_dense(const ccl_phmat_dense* src,\n\n ccl_phmat_dense* dst);\n\n// dense mat -> dense vec\n\nvoid ccl_phmat_dense_convert_to_phvec_dense_v(const ccl_phmat_dense* src,\n\n ccl_phvec_dense_v* dst);\n\n// dense mat -> coo\n\nvoid ccl_phmat_dense_convert_to_phmat_coo(const ccl_phmat_dense* src,\n\n ccl_phmat_coo* dst);\n\n// coo -> dense mat\n\nvoid ccl_phmat_coo_convert_to_phmat_dense(const ccl_phmat_coo* src,\n\n ccl_phmat_dense* dst);\n\n\n", "file_path": "ccl/src/phost/Morpheus_Ccl_Convert.hpp", "rank": 71, "score": 21986.208992060783 }, { "content": " Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// coo_hostmirror -> coo_hostmirror\n\nvoid ccl_phmat_coo_hostmirror_copy_to_phmat_coo_hostmirror(\n\n const ccl_phmat_coo_hostmirror* src, ccl_phmat_coo_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// csr -> csr\n\nvoid ccl_phmat_csr_copy_to_phmat_csr(const ccl_phmat_csr* src,\n\n ccl_phmat_csr* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// csr -> csr_hostmirror\n\nvoid ccl_phmat_csr_copy_to_phmat_csr_hostmirror(const ccl_phmat_csr* src,\n\n ccl_phmat_csr_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n", "file_path": "ccl/src/phost/Morpheus_Ccl_Copy.cpp", "rank": 72, "score": 21986.20065887916 }, { "content": " const ccl_phmat_dyn_hostmirror* src, ccl_phmat_dyn* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn_hostmirror -> dyn_hostmirror\n\nvoid ccl_phmat_dyn_hostmirror_copy_to_phmat_dyn_hostmirror(\n\n const ccl_phmat_dyn_hostmirror* src, ccl_phmat_dyn_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// coo -> dyn\n\nvoid ccl_phmat_coo_copy_to_phmat_dyn(const ccl_phmat_coo* src,\n\n ccl_phmat_dyn* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn -> coo\n\nvoid ccl_phmat_dyn_copy_to_phmat_coo(const ccl_phmat_dyn* src,\n\n ccl_phmat_coo* dst) {\n\n Morpheus::copy(*src, *dst);\n", "file_path": "ccl/src/phost/Morpheus_Ccl_Copy.cpp", "rank": 73, "score": 21986.187729607285 }, { "content": " ccl_phmat_dyn* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn -> csr\n\nvoid ccl_copy_phmat_dyn_to_phmat_csr(const ccl_phmat_dyn* src,\n\n ccl_phmat_csr* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// csr_hostmirror -> dyn\n\nvoid ccl_phmat_csr_hostmirror_copy_to_phmat_dyn(\n\n const ccl_phmat_csr_hostmirror* src, ccl_phmat_dyn* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn -> csr_hostmirror\n\nvoid ccl_phmat_dyn_copy_to_phmat_csr_hostmirror(const ccl_phmat_dyn* src,\n\n ccl_phmat_csr_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n", "file_path": "ccl/src/phost/Morpheus_Ccl_Copy.cpp", "rank": 74, "score": 21986.179172664735 }, { "content": " Morpheus::convert(*src, *dst);\n\n}\n\n// coo -> dia\n\nvoid ccl_dmat_coo_hostmirror_convert_to_dmat_dia_hostmirror(\n\n const ccl_dmat_coo_hostmirror* src, ccl_dmat_dia_hostmirror* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n// dia -> csr\n\nvoid ccl_dmat_dia_hostmirror_convert_to_dmat_csr_hostmirror(\n\n const ccl_dmat_dia_hostmirror* src, ccl_dmat_csr_hostmirror* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n\n\n// dense mat -> dense mat\n\nvoid ccl_dmat_dense_hostmirror_convert_to_dmat_dense_hostmirror(\n\n const ccl_dmat_dense_hostmirror* src, ccl_dmat_dense_hostmirror* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n// dense mat -> dense vec\n\nvoid ccl_dmat_dense_hostmirror_convert_to_dvec_dense_v_hostmirror(\n", "file_path": "ccl/src/dev/Morpheus_Ccl_Convert.cpp", "rank": 75, "score": 21986.177613999454 }, { "content": "}\n\n\n\n// coo_hostmirror -> dyn\n\nvoid ccl_phmat_coo_hostmirror_copy_to_phmat_dyn(\n\n const ccl_phmat_coo_hostmirror* src, ccl_phmat_dyn* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn -> coo_hostmirror\n\nvoid ccl_phmat_dyn_copy_to_phmat_coo_hostmirror(const ccl_phmat_dyn* src,\n\n ccl_phmat_coo_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// coo -> dyn_hostmirror\n\nvoid ccl_phmat_coo_copy_to_phmat_dyn_hostmirror(const ccl_phmat_coo* src,\n\n ccl_phmat_dyn_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n", "file_path": "ccl/src/phost/Morpheus_Ccl_Copy.cpp", "rank": 76, "score": 21986.152520535103 }, { "content": "}\n\n\n\n// dyn -> dia\n\nvoid ccl_hmat_dyn_copy_to_hmat_dia(const ccl_hmat_dyn* src, ccl_hmat_dia* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dia_hostmirror -> dyn\n\nvoid ccl_hmat_dia_hostmirror_copy_to_hmat_dyn(\n\n const ccl_hmat_dia_hostmirror* src, ccl_hmat_dyn* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn -> dia_hostmirror\n\nvoid ccl_hmat_dyn_copy_to_hmat_dia_hostmirror(const ccl_hmat_dyn* src,\n\n ccl_hmat_dia_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dia -> dyn_hostmirror\n", "file_path": "ccl/src/host/Morpheus_Ccl_Copy.cpp", "rank": 77, "score": 21986.152520535103 }, { "content": "}\n\n\n\n// dyn -> dia\n\nvoid ccl_dmat_dyn_copy_to_dmat_dia(const ccl_dmat_dyn* src, ccl_dmat_dia* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dia_hostmirror -> dyn\n\nvoid ccl_dmat_dia_hostmirror_copy_to_dmat_dyn(\n\n const ccl_dmat_dia_hostmirror* src, ccl_dmat_dyn* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn -> dia_hostmirror\n\nvoid ccl_dmat_dyn_copy_to_dmat_dia_hostmirror(const ccl_dmat_dyn* src,\n\n ccl_dmat_dia_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dia -> dyn_hostmirror\n", "file_path": "ccl/src/dev/Morpheus_Ccl_Copy.cpp", "rank": 78, "score": 21986.152520535103 }, { "content": "void ccl_hmat_csr_copy_to_hmat_dyn(const ccl_hmat_csr* src, ccl_hmat_dyn* dst);\n\n\n\n// dyn -> csr\n\nvoid ccl_copy_hmat_dyn_to_hmat_csr(const ccl_hmat_dyn* src, ccl_hmat_csr* dst);\n\n\n\n// csr_hostmirror -> dyn\n\nvoid ccl_hmat_csr_hostmirror_copy_to_hmat_dyn(\n\n const ccl_hmat_csr_hostmirror* src, ccl_hmat_dyn* dst);\n\n\n\n// dyn -> csr_hostmirror\n\nvoid ccl_hmat_dyn_copy_to_hmat_csr_hostmirror(const ccl_hmat_dyn* src,\n\n ccl_hmat_csr_hostmirror* dst);\n\n\n\n// csr -> dyn_hostmirror\n\nvoid ccl_hmat_csr_copy_to_hmat_dyn_hostmirror(const ccl_hmat_csr* src,\n\n ccl_hmat_dyn_hostmirror* dst);\n\n\n\n// dyn_hostmirror -> csr\n\nvoid ccl_hmat_dyn_hostmirror_copy_to_hmat_csr(\n\n const ccl_hmat_dyn_hostmirror* src, ccl_hmat_csr* dst);\n", "file_path": "ccl/src/host/Morpheus_Ccl_Copy.hpp", "rank": 79, "score": 21986.14296458464 }, { "content": "void ccl_dmat_csr_copy_to_dmat_dyn(const ccl_dmat_csr* src, ccl_dmat_dyn* dst);\n\n\n\n// dyn -> csr\n\nvoid ccl_copy_dmat_dyn_to_dmat_csr(const ccl_dmat_dyn* src, ccl_dmat_csr* dst);\n\n\n\n// csr_hostmirror -> dyn\n\nvoid ccl_dmat_csr_hostmirror_copy_to_dmat_dyn(\n\n const ccl_dmat_csr_hostmirror* src, ccl_dmat_dyn* dst);\n\n\n\n// dyn -> csr_hostmirror\n\nvoid ccl_dmat_dyn_copy_to_dmat_csr_hostmirror(const ccl_dmat_dyn* src,\n\n ccl_dmat_csr_hostmirror* dst);\n\n\n\n// csr -> dyn_hostmirror\n\nvoid ccl_dmat_csr_copy_to_dmat_dyn_hostmirror(const ccl_dmat_csr* src,\n\n ccl_dmat_dyn_hostmirror* dst);\n\n\n\n// dyn_hostmirror -> csr\n\nvoid ccl_dmat_dyn_hostmirror_copy_to_dmat_csr(\n\n const ccl_dmat_dyn_hostmirror* src, ccl_dmat_csr* dst);\n", "file_path": "ccl/src/dev/Morpheus_Ccl_Copy.hpp", "rank": 80, "score": 21986.14296458464 }, { "content": "// mat dense -> mat dense_hostmirror\n\nvoid ccl_hmat_dense_copy_to_hmat_dense_hostmirror(\n\n const ccl_hmat_dense* src, ccl_hmat_dense_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// mat dense_hostmirror -> mat dense\n\nvoid ccl_hmat_dense_hostmirror_copy_to_hmat_dense(\n\n const ccl_hmat_dense_hostmirror* src, ccl_hmat_dense* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// mat dense_hostmirror -> mat dense_hostmirror\n\nvoid ccl_hmat_dense_hostmirror_copy_to_hmat_dense_hostmirror(\n\n const ccl_hmat_dense_hostmirror* src, ccl_hmat_dense_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// vec dense -> vec dense\n\nvoid ccl_hvec_dense_v_copy_to_hvec_dense_v(const ccl_hvec_dense_v* src,\n", "file_path": "ccl/src/host/Morpheus_Ccl_Copy.cpp", "rank": 81, "score": 21986.140668816417 }, { "content": "// mat dense -> mat dense_hostmirror\n\nvoid ccl_dmat_dense_copy_to_dmat_dense_hostmirror(\n\n const ccl_dmat_dense* src, ccl_dmat_dense_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// mat dense_hostmirror -> mat dense\n\nvoid ccl_dmat_dense_hostmirror_copy_to_dmat_dense(\n\n const ccl_dmat_dense_hostmirror* src, ccl_dmat_dense* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// mat dense_hostmirror -> mat dense_hostmirror\n\nvoid ccl_dmat_dense_hostmirror_copy_to_dmat_dense_hostmirror(\n\n const ccl_dmat_dense_hostmirror* src, ccl_dmat_dense_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// vec dense -> vec dense\n\nvoid ccl_dvec_dense_v_copy_to_dvec_dense_v(const ccl_dvec_dense_v* src,\n", "file_path": "ccl/src/dev/Morpheus_Ccl_Copy.cpp", "rank": 82, "score": 21986.140668816417 }, { "content": "}\n\n// coo -> csr\n\nvoid ccl_dmat_coo_hostmirror_convert_to_dmat_csr_hostmirror(\n\n const ccl_dmat_coo_hostmirror* src, ccl_dmat_csr_hostmirror* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n// csr -> dia\n\nvoid ccl_dmat_csr_hostmirror_convert_to_dmat_dia_hostmirror(\n\n const ccl_dmat_csr_hostmirror* src, ccl_dmat_dia_hostmirror* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n\n\n// dia -> dia\n\nvoid ccl_dmat_dia_hostmirror_convert_to_dmat_dia_hostmirror(\n\n const ccl_dmat_dia_hostmirror* src, ccl_dmat_dia_hostmirror* dst) {\n\n Morpheus::convert(*src, *dst);\n\n}\n\n// dia -> coo\n\nvoid ccl_dmat_dia_hostmirror_convert_to_dmat_coo_hostmirror(\n\n const ccl_dmat_dia_hostmirror* src, ccl_dmat_coo_hostmirror* dst) {\n", "file_path": "ccl/src/dev/Morpheus_Ccl_Convert.cpp", "rank": 83, "score": 21986.140668816417 }, { "content": "}\n\n\n\n// dyn -> dyn\n\nvoid ccl_dmat_dyn_copy_to_dmat_dyn(const ccl_dmat_dyn* src, ccl_dmat_dyn* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn -> dyn_hostmirror\n\nvoid ccl_dmat_dyn_copy_to_dmat_dyn_hostmirror(const ccl_dmat_dyn* src,\n\n ccl_dmat_dyn_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn_hostmirror -> dyn\n\nvoid ccl_dmat_dyn_hostmirror_copy_to_dmat_dyn(\n\n const ccl_dmat_dyn_hostmirror* src, ccl_dmat_dyn* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn_hostmirror -> dyn_hostmirror\n", "file_path": "ccl/src/dev/Morpheus_Ccl_Copy.cpp", "rank": 84, "score": 21986.12960265764 }, { "content": "}\n\n\n\n// dyn -> dyn\n\nvoid ccl_hmat_dyn_copy_to_hmat_dyn(const ccl_hmat_dyn* src, ccl_hmat_dyn* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn -> dyn_hostmirror\n\nvoid ccl_hmat_dyn_copy_to_hmat_dyn_hostmirror(const ccl_hmat_dyn* src,\n\n ccl_hmat_dyn_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn_hostmirror -> dyn\n\nvoid ccl_hmat_dyn_hostmirror_copy_to_hmat_dyn(\n\n const ccl_hmat_dyn_hostmirror* src, ccl_hmat_dyn* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn_hostmirror -> dyn_hostmirror\n", "file_path": "ccl/src/host/Morpheus_Ccl_Copy.cpp", "rank": 85, "score": 21986.12960265764 }, { "content": " const ccl_phmat_dia_hostmirror* src, ccl_phmat_dyn* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn -> dia_hostmirror\n\nvoid ccl_phmat_dyn_copy_to_phmat_dia_hostmirror(const ccl_phmat_dyn* src,\n\n ccl_phmat_dia_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dia -> dyn_hostmirror\n\nvoid ccl_phmat_dia_copy_to_phmat_dyn_hostmirror(const ccl_phmat_dia* src,\n\n ccl_phmat_dyn_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn_hostmirror -> dia\n\nvoid ccl_phmat_dyn_hostmirror_copy_to_phmat_dia(\n\n const ccl_phmat_dyn_hostmirror* src, ccl_phmat_dia* dst) {\n\n Morpheus::copy(*src, *dst);\n", "file_path": "ccl/src/phost/Morpheus_Ccl_Copy.cpp", "rank": 86, "score": 21986.127885280705 }, { "content": "}\n\n\n\n// dia_hostmirror -> dia\n\nvoid ccl_dmat_dia_hostmirror_copy_to_dmat_dia(\n\n const ccl_dmat_dia_hostmirror* src, ccl_dmat_dia* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dia_hostmirror -> dia_hostmirror\n\nvoid ccl_dmat_dia_hostmirror_copy_to_dmat_dia_hostmirror(\n\n const ccl_dmat_dia_hostmirror* src, ccl_dmat_dia_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// mat dense -> mat dense\n\nvoid ccl_dmat_dense_copy_to_dmat_dense(const ccl_dmat_dense* src,\n\n ccl_dmat_dense* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n", "file_path": "ccl/src/dev/Morpheus_Ccl_Copy.cpp", "rank": 87, "score": 21986.106816861433 }, { "content": "}\n\n\n\n// dia_hostmirror -> dia\n\nvoid ccl_hmat_dia_hostmirror_copy_to_hmat_dia(\n\n const ccl_hmat_dia_hostmirror* src, ccl_hmat_dia* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dia_hostmirror -> dia_hostmirror\n\nvoid ccl_hmat_dia_hostmirror_copy_to_hmat_dia_hostmirror(\n\n const ccl_hmat_dia_hostmirror* src, ccl_hmat_dia_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// mat dense -> mat dense\n\nvoid ccl_hmat_dense_copy_to_hmat_dense(const ccl_hmat_dense* src,\n\n ccl_hmat_dense* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n", "file_path": "ccl/src/host/Morpheus_Ccl_Copy.cpp", "rank": 88, "score": 21986.106816861433 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#ifndef MORPHEUS_CCL_PHOST_REDUCTION_HPP\n\n#define MORPHEUS_CCL_PHOST_REDUCTION_HPP\n\n\n\n#include <phost/Morpheus_Ccl_DenseVector.hpp>\n\n\n\n#ifdef __cplusplus\n\nextern \"C\" {\n\n#endif\n\n\n\nccl_value_t ccl_phvec_dense_v_reduce(const ccl_phvec_dense_v* in,\n\n ccl_index_t size);\n\n\n\nccl_value_t ccl_phvec_dense_i_reduce(const ccl_phvec_dense_i* in,\n\n ccl_index_t size);\n\n\n\nccl_value_t ccl_phvec_dense_v_hostmirror_reduce(\n\n const ccl_phvec_dense_v_hostmirror* in, ccl_index_t size);\n", "file_path": "ccl/src/phost/Morpheus_Ccl_Reduction.hpp", "rank": 89, "score": 21986.09213354613 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#ifndef MORPHEUS_CCL_HOST_REDUCTION_HPP\n\n#define MORPHEUS_CCL_HOST_REDUCTION_HPP\n\n\n\n#include <host/Morpheus_Ccl_DenseVector.hpp>\n\n\n\n#ifdef __cplusplus\n\nextern \"C\" {\n\n#endif\n\n\n\nccl_value_t ccl_hvec_dense_v_reduce(const ccl_hvec_dense_v* in,\n\n ccl_index_t size);\n\n\n\nccl_value_t ccl_hvec_dense_i_reduce(const ccl_hvec_dense_i* in,\n\n ccl_index_t size);\n\n\n\nccl_value_t ccl_hvec_dense_v_hostmirror_reduce(\n\n const ccl_hvec_dense_v_hostmirror* in, ccl_index_t size);\n", "file_path": "ccl/src/host/Morpheus_Ccl_Reduction.hpp", "rank": 90, "score": 21986.09213354613 }, { "content": " * limitations under the License.\n\n */\n\n\n\n#ifndef MORPHEUS_CCL_DEV_REDUCTION_HPP\n\n#define MORPHEUS_CCL_DEV_REDUCTION_HPP\n\n\n\n#include <dev/Morpheus_Ccl_DenseVector.hpp>\n\n\n\n#ifdef __cplusplus\n\nextern \"C\" {\n\n#endif\n\n\n\nccl_value_t ccl_dvec_dense_v_reduce(const ccl_dvec_dense_v* in,\n\n ccl_index_t size);\n\n\n\nccl_value_t ccl_dvec_dense_i_reduce(const ccl_dvec_dense_i* in,\n\n ccl_index_t size);\n\n\n\nccl_value_t ccl_dvec_dense_v_hostmirror_reduce(\n\n const ccl_dvec_dense_v_hostmirror* in, ccl_index_t size);\n", "file_path": "ccl/src/dev/Morpheus_Ccl_Reduction.hpp", "rank": 91, "score": 21986.09213354613 }, { "content": "}\n\n\n\n// coo_hostmirror -> coo_hostmirror\n\nvoid ccl_hmat_coo_hostmirror_copy_to_hmat_coo_hostmirror(\n\n const ccl_hmat_coo_hostmirror* src, ccl_hmat_coo_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// csr -> csr\n\nvoid ccl_hmat_csr_copy_to_hmat_csr(const ccl_hmat_csr* src, ccl_hmat_csr* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// csr -> csr_hostmirror\n\nvoid ccl_hmat_csr_copy_to_hmat_csr_hostmirror(const ccl_hmat_csr* src,\n\n ccl_hmat_csr_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// csr_hostmirror -> csr\n", "file_path": "ccl/src/host/Morpheus_Ccl_Copy.cpp", "rank": 92, "score": 21986.084161941257 }, { "content": "}\n\n\n\n// csr -> dyn_hostmirror\n\nvoid ccl_phmat_csr_copy_to_phmat_dyn_hostmirror(const ccl_phmat_csr* src,\n\n ccl_phmat_dyn_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn_hostmirror -> csr\n\nvoid ccl_phmat_dyn_hostmirror_copy_to_phmat_csr(\n\n const ccl_phmat_dyn_hostmirror* src, ccl_phmat_csr* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// csr_hostmirror -> dyn_hostmirror\n\nvoid ccl_phmat_csr_hostmirror_copy_to_phmat_dyn_hostmirror(\n\n const ccl_phmat_csr_hostmirror* src, ccl_phmat_dyn_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n", "file_path": "ccl/src/phost/Morpheus_Ccl_Copy.cpp", "rank": 93, "score": 21986.084161941257 }, { "content": "\n\n// csr_hostmirror -> dyn\n\nvoid ccl_dmat_csr_hostmirror_copy_to_dmat_dyn(\n\n const ccl_dmat_csr_hostmirror* src, ccl_dmat_dyn* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn -> csr_hostmirror\n\nvoid ccl_dmat_dyn_copy_to_dmat_csr_hostmirror(const ccl_dmat_dyn* src,\n\n ccl_dmat_csr_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// csr -> dyn_hostmirror\n\nvoid ccl_dmat_csr_copy_to_dmat_dyn_hostmirror(const ccl_dmat_csr* src,\n\n ccl_dmat_dyn_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn_hostmirror -> csr\n", "file_path": "ccl/src/dev/Morpheus_Ccl_Copy.cpp", "rank": 94, "score": 21986.084161941257 }, { "content": "\n\n// csr_hostmirror -> dyn\n\nvoid ccl_hmat_csr_hostmirror_copy_to_hmat_dyn(\n\n const ccl_hmat_csr_hostmirror* src, ccl_hmat_dyn* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn -> csr_hostmirror\n\nvoid ccl_hmat_dyn_copy_to_hmat_csr_hostmirror(const ccl_hmat_dyn* src,\n\n ccl_hmat_csr_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// csr -> dyn_hostmirror\n\nvoid ccl_hmat_csr_copy_to_hmat_dyn_hostmirror(const ccl_hmat_csr* src,\n\n ccl_hmat_dyn_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn_hostmirror -> csr\n", "file_path": "ccl/src/host/Morpheus_Ccl_Copy.cpp", "rank": 95, "score": 21986.084161941257 }, { "content": "\n\n// csr_hostmirror -> csr\n\nvoid ccl_phmat_csr_hostmirror_copy_to_phmat_csr(\n\n const ccl_phmat_csr_hostmirror* src, ccl_phmat_csr* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// csr_hostmirror -> csr_hostmirror\n\nvoid ccl_phmat_csr_hostmirror_copy_to_phmat_csr_hostmirror(\n\n const ccl_phmat_csr_hostmirror* src, ccl_phmat_csr_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dia -> dia\n\nvoid ccl_phmat_dia_copy_to_phmat_dia(const ccl_phmat_dia* src,\n\n ccl_phmat_dia* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dia -> dia_hostmirror\n", "file_path": "ccl/src/phost/Morpheus_Ccl_Copy.cpp", "rank": 96, "score": 21986.084161941257 }, { "content": "}\n\n\n\n// coo_hostmirror -> coo_hostmirror\n\nvoid ccl_dmat_coo_hostmirror_copy_to_dmat_coo_hostmirror(\n\n const ccl_dmat_coo_hostmirror* src, ccl_dmat_coo_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// csr -> csr\n\nvoid ccl_dmat_csr_copy_to_dmat_csr(const ccl_dmat_csr* src, ccl_dmat_csr* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// csr -> csr_hostmirror\n\nvoid ccl_dmat_csr_copy_to_dmat_csr_hostmirror(const ccl_dmat_csr* src,\n\n ccl_dmat_csr_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// csr_hostmirror -> csr\n", "file_path": "ccl/src/dev/Morpheus_Ccl_Copy.cpp", "rank": 97, "score": 21986.084161941257 }, { "content": "\n\n// dyn -> coo_hostmirror\n\nvoid ccl_hmat_dyn_copy_to_hmat_coo_hostmirror(const ccl_hmat_dyn* src,\n\n ccl_hmat_coo_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// coo -> dyn_hostmirror\n\nvoid ccl_hmat_coo_copy_to_hmat_dyn_hostmirror(const ccl_hmat_coo* src,\n\n ccl_hmat_dyn_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn_hostmirror -> coo\n\nvoid ccl_hmat_dyn_hostmirror_copy_to_hmat_coo(\n\n const ccl_hmat_dyn_hostmirror* src, ccl_hmat_coo* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// coo_hostmirror -> dyn_hostmirror\n", "file_path": "ccl/src/host/Morpheus_Ccl_Copy.cpp", "rank": 98, "score": 21986.06163670716 }, { "content": "\n\n// dyn -> coo_hostmirror\n\nvoid ccl_dmat_dyn_copy_to_dmat_coo_hostmirror(const ccl_dmat_dyn* src,\n\n ccl_dmat_coo_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// coo -> dyn_hostmirror\n\nvoid ccl_dmat_coo_copy_to_dmat_dyn_hostmirror(const ccl_dmat_coo* src,\n\n ccl_dmat_dyn_hostmirror* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// dyn_hostmirror -> coo\n\nvoid ccl_dmat_dyn_hostmirror_copy_to_dmat_coo(\n\n const ccl_dmat_dyn_hostmirror* src, ccl_dmat_coo* dst) {\n\n Morpheus::copy(*src, *dst);\n\n}\n\n\n\n// coo_hostmirror -> dyn_hostmirror\n", "file_path": "ccl/src/dev/Morpheus_Ccl_Copy.cpp", "rank": 99, "score": 21986.06163670716 } ]
C++
CC2500.cpp
RoXXoR/CC2500
7a07566dd2342a1b21bcdc9beb30b0ff3e6cdba6
#include "CC2500.h" CC2500::CC2500() { CC2500(DEVADDR, CHANNEL); } CC2500::CC2500(uint8_t deviceAddress) { CC2500(deviceAddress, CHANNEL); } CC2500::CC2500(uint8_t deviceAddress, uint8_t channel) { _deviceAddress = deviceAddress; _channel = channel; _gdo0 = GDO0; } void CC2500::setDeviceAddress(uint8_t deviceAddress) { _deviceAddress = deviceAddress; } void CC2500::setChannel(uint8_t channel) { _channel = channel; } void CC2500::begin() { SPI.begin(); SPI.setClockDivider(SPI_CLOCK_DIV2); SPI.setBitOrder(MSBFIRST); SPI.setDataMode(SPI_MODE0); digitalWrite(SS,HIGH); pinMode(SS,OUTPUT); resetDevice(); delay(100); configureDeviceSettings(); execStrobeCommand(CC2500_CMD_SRX); } void CC2500::writeRegister(uint8_t addr, uint8_t data) { digitalWrite(SS,LOW); SPI.transfer(addr|CC2500_WRITE_SINGLE); SPI.transfer(data); digitalWrite(SS,HIGH); } void CC2500::writeRegisterBurst(uint8_t saddr, uint8_t *data, uint8_t size) { digitalWrite(SS,LOW); SPI.transfer(saddr|CC2500_WRITE_BURST); while (size > 0) { SPI.transfer(*data++); size--; } digitalWrite(SS,HIGH); } uint8_t CC2500::readRegister(uint8_t addr) { uint8_t recv; digitalWrite(SS,LOW); SPI.transfer(addr|CC2500_READ_SINGLE); recv = SPI.transfer(0x00); digitalWrite(SS,HIGH); return recv; } void CC2500::readRegisterBurst(uint8_t saddr, uint8_t *data, uint8_t size) { digitalWrite(SS,LOW); SPI.transfer(saddr|CC2500_READ_BURST); while (size > 0) { *data++ = SPI.transfer(0x00); size--; } digitalWrite(SS,HIGH); } void CC2500::execStrobeCommand(uint8_t command) { digitalWrite(SS,LOW); SPI.transfer(command); digitalWrite(SS,HIGH); } uint8_t CC2500::readStatusRegister(uint8_t addr) { return readRegister(addr|CC2500_READ_STATUS); } void CC2500::configureDeviceSettings() { uint8_t paTable[] = {0xFB}; writeRegister(CC2500_IOCFG0, 0x06); writeRegister(CC2500_IOCFG2, 0x0B); writeRegister(CC2500_PKTCTRL0, 0x05); writeRegister(CC2500_PKTCTRL1, 0x05); writeRegister(CC2500_PKTLEN, 0xFF); writeRegister(CC2500_ADDR, _deviceAddress); writeRegister(CC2500_CHANNR, _channel); writeRegister(CC2500_FSCTRL1, 0x07); writeRegister(CC2500_FSCTRL0, 0x00); writeRegister(CC2500_FREQ2, 0x5D); writeRegister(CC2500_FREQ1, 0x93); writeRegister(CC2500_FREQ0, 0xB1); writeRegister(CC2500_MDMCFG4, 0x2D); writeRegister(CC2500_MDMCFG3, 0x3B); writeRegister(CC2500_MDMCFG2, 0x73); writeRegister(CC2500_MDMCFG1, 0x22); writeRegister(CC2500_MDMCFG0, 0xF8); writeRegister(CC2500_DEVIANT, 0x00); writeRegister(CC2500_MCSM1, 0x3F); writeRegister(CC2500_MCSM0, 0x18); writeRegister(CC2500_FOCCFG, 0x1D); writeRegister(CC2500_BSCFG, 0x1C); writeRegister(CC2500_AGCCTRL2, 0xC7); writeRegister(CC2500_AGCCTRL1, 0x00); writeRegister(CC2500_AGCCTRL0, 0xB2); writeRegister(CC2500_FREND1, 0xB6); writeRegister(CC2500_FREND0, 0x10); writeRegister(CC2500_FSCAL3, 0xEA); writeRegister(CC2500_FSCAL2, 0x0A); writeRegister(CC2500_FSCAL1, 0x00); writeRegister(CC2500_FSCAL0, 0x11); writeRegisterBurst(CC2500_PATABLE, paTable, sizeof(paTable)); } void CC2500::sendTxBuffer(uint8_t *txBuffer, uint8_t size) { writeRegisterBurst(CC2500_TX_FIFO, txBuffer, size); execStrobeCommand(CC2500_CMD_STX); delay(200); } int8_t CC2500::receiveRxBuffer(uint8_t *rxBuffer, uint8_t size) { uint8_t pktLength; uint8_t rxInfo[2]; if (readStatusRegister(CC2500_RXBYTES)&CC2500_NUM_RXBYTES) { pktLength = readRegister(CC2500_RX_FIFO); if (pktLength <= size) { readRegisterBurst(CC2500_RX_FIFO, rxBuffer, pktLength); } else { readRegisterBurst(CC2500_RX_FIFO, rxBuffer, size); pktLength -= size; while (pktLength > 0) { readRegister(CC2500_RX_FIFO); pktLength--; } } readRegisterBurst(CC2500_RX_FIFO, rxInfo, sizeof(rxInfo)); } return rxInfo[1]; } uint8_t CC2500::getChipVersion() { return readStatusRegister(CC2500_REG_VERSION); } uint8_t CC2500::getStatusByte() { uint8_t recv; digitalWrite(SS,LOW); recv = SPI.transfer(CC2500_CMD_SNOP|CC2500_READ_SINGLE); digitalWrite(SS,HIGH); return recv; } void CC2500::resetDevice() { execStrobeCommand(CC2500_CMD_SRES); }
#include "CC2500.h" CC2500::CC2500() { CC2500(DEVADDR, CHANNEL); } CC2500::CC2500(uint8_t deviceAddress) { CC2500(deviceAddress, CHANNEL); } CC2500::CC2500(uint8_t deviceAddress, uint8_t channel) { _deviceAddress = deviceAddress; _channel = channel; _gdo0 = GDO0; } void CC2500::setDeviceAddress(uint8_t deviceAddress) { _deviceAddress = deviceAddress; } void CC2500::setChannel(uint8_t channel) { _channel = channel; } void CC2500::begin() { SPI.begin(); SPI.setClockDivider(SPI_CLOCK_DIV2); SPI.setBitOrder(MSBFIRST); SPI.setDataMode(SPI_MODE0); digitalWrite(SS,HIGH); pinMode(SS,OUTPUT); resetDevice(); delay(100); configureDeviceSettings(); execStrobeCommand(CC2500_CMD_SRX); } void CC2500::writeRegister(uint8_t addr, uint8_t data) { digitalWrite(SS,LOW); SPI.transfer(addr|CC2500_WRITE_SINGLE); SPI.transfer(data); digitalWrite(SS,HIGH); } void CC2500::writeRegisterBurst(uint8_t saddr, uint8_t *data, uint8_t size) { digitalWrite(SS,LOW); SPI.transfer(saddr|CC2500_WRITE_BURST); while (size > 0) { SPI.transfer(*data++); size--; } digitalWrite(SS,HIGH); } uint8_t CC2500::readRegister(uint8_t addr) { uint8_t recv; digitalWrite(SS,LOW); SPI.transfer(addr|CC2500_READ_SINGLE); recv = SPI.transfer(0x00); digitalWrite(SS,H
8_t *rxBuffer, uint8_t size) { uint8_t pktLength; uint8_t rxInfo[2]; if (readStatusRegister(CC2500_RXBYTES)&CC2500_NUM_RXBYTES) { pktLength = readRegister(CC2500_RX_FIFO); if (pktLength <= size) { readRegisterBurst(CC2500_RX_FIFO, rxBuffer, pktLength); } else { readRegisterBurst(CC2500_RX_FIFO, rxBuffer, size); pktLength -= size; while (pktLength > 0) { readRegister(CC2500_RX_FIFO); pktLength--; } } readRegisterBurst(CC2500_RX_FIFO, rxInfo, sizeof(rxInfo)); } return rxInfo[1]; } uint8_t CC2500::getChipVersion() { return readStatusRegister(CC2500_REG_VERSION); } uint8_t CC2500::getStatusByte() { uint8_t recv; digitalWrite(SS,LOW); recv = SPI.transfer(CC2500_CMD_SNOP|CC2500_READ_SINGLE); digitalWrite(SS,HIGH); return recv; } void CC2500::resetDevice() { execStrobeCommand(CC2500_CMD_SRES); }
IGH); return recv; } void CC2500::readRegisterBurst(uint8_t saddr, uint8_t *data, uint8_t size) { digitalWrite(SS,LOW); SPI.transfer(saddr|CC2500_READ_BURST); while (size > 0) { *data++ = SPI.transfer(0x00); size--; } digitalWrite(SS,HIGH); } void CC2500::execStrobeCommand(uint8_t command) { digitalWrite(SS,LOW); SPI.transfer(command); digitalWrite(SS,HIGH); } uint8_t CC2500::readStatusRegister(uint8_t addr) { return readRegister(addr|CC2500_READ_STATUS); } void CC2500::configureDeviceSettings() { uint8_t paTable[] = {0xFB}; writeRegister(CC2500_IOCFG0, 0x06); writeRegister(CC2500_IOCFG2, 0x0B); writeRegister(CC2500_PKTCTRL0, 0x05); writeRegister(CC2500_PKTCTRL1, 0x05); writeRegister(CC2500_PKTLEN, 0xFF); writeRegister(CC2500_ADDR, _deviceAddress); writeRegister(CC2500_CHANNR, _channel); writeRegister(CC2500_FSCTRL1, 0x07); writeRegister(CC2500_FSCTRL0, 0x00); writeRegister(CC2500_FREQ2, 0x5D); writeRegister(CC2500_FREQ1, 0x93); writeRegister(CC2500_FREQ0, 0xB1); writeRegister(CC2500_MDMCFG4, 0x2D); writeRegister(CC2500_MDMCFG3, 0x3B); writeRegister(CC2500_MDMCFG2, 0x73); writeRegister(CC2500_MDMCFG1, 0x22); writeRegister(CC2500_MDMCFG0, 0xF8); writeRegister(CC2500_DEVIANT, 0x00); writeRegister(CC2500_MCSM1, 0x3F); writeRegister(CC2500_MCSM0, 0x18); writeRegister(CC2500_FOCCFG, 0x1D); writeRegister(CC2500_BSCFG, 0x1C); writeRegister(CC2500_AGCCTRL2, 0xC7); writeRegister(CC2500_AGCCTRL1, 0x00); writeRegister(CC2500_AGCCTRL0, 0xB2); writeRegister(CC2500_FREND1, 0xB6); writeRegister(CC2500_FREND0, 0x10); writeRegister(CC2500_FSCAL3, 0xEA); writeRegister(CC2500_FSCAL2, 0x0A); writeRegister(CC2500_FSCAL1, 0x00); writeRegister(CC2500_FSCAL0, 0x11); writeRegisterBurst(CC2500_PATABLE, paTable, sizeof(paTable)); } void CC2500::sendTxBuffer(uint8_t *txBuffer, uint8_t size) { writeRegisterBurst(CC2500_TX_FIFO, txBuffer, size); execStrobeCommand(CC2500_CMD_STX); delay(200); } int8_t CC2500::receiveRxBuffer(uint
random
[ { "content": "#define CC2500_ADDR\t\t0x09\t// Device Address\n", "file_path": "cc2500_defines.h", "rank": 0, "score": 19030.082185654213 }, { "content": "\tvoid writeRegisterBurst(uint8_t saddr, uint8_t *data, uint8_t size);\n\n\tuint8_t readRegister(uint8_t addr);\n\n\tvoid readRegisterBurst(uint8_t saddr, uint8_t *data, uint8_t size);\n\n\tuint8_t readStatusRegister(uint8_t addr);\n\n\tvoid sendTxBuffer(uint8_t *txBuffer, uint8_t size);\n\n\tint8_t receiveRxBuffer(uint8_t *rxBuffer, uint8_t size);\n\n\tvoid execStrobeCommand(uint8_t command);\n\n\tvoid resetDevice();\n\n\tvoid configureDeviceSettings();\n\n\n\n};\n\n\n\n#endif\n", "file_path": "CC2500.h", "rank": 1, "score": 7.062538593544973 }, { "content": "\n\n\n\n#ifndef CC2500_h\n\n#define CC2500_h\n\n\n\n#include <SPI.h>\n\n#include \"cc2500_defines.h\"\n\n\n\n// defaults\n\n#define DEVADDR\t0x00\n\n#define CHANNEL\t0x00\n\n#define GDO0\t13\t// P2.6 on MSP430F2274 on RF2500T\t\n\n\n", "file_path": "CC2500.h", "rank": 6, "score": 4.515178778768314 }, { "content": "Copyright (c) 2014, RoXXoR([email protected])\n\nAll rights reserved.\n\n\n\nRedistribution and use in source and binary forms, with or without\n\nmodification, are permitted provided that the following conditions are met:\n\n\n\n* Redistributions of source code must retain the above copyright notice, this\n\n list of conditions and the following disclaimer.\n\n\n\n* Redistributions in binary form must reproduce the above copyright notice,\n\n this list of conditions and the following disclaimer in the documentation\n\n and/or other materials provided with the distribution.\n\n\n\n* Neither the name of the copyright holder nor the names of its\n\n contributors may be used to endorse or promote products derived from\n\n this software without specific prior written permission.\n\n\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n", "file_path": "LICENSE.md", "rank": 10, "score": 1.4863584980748938 } ]
C++
rcnn/backbone.hpp
GaoLon/tensorrtx
67bd89f27c4bcaf99c3ff50317c035b60bdce58e
#pragma once #include <vector> #include <map> #include <string> #include "common.hpp" enum RESNETTYPE { R18 = 0, R34, R50, R101, R152 }; const std::map<RESNETTYPE, std::vector<int>> num_blocks_per_stage = { {R18, {2, 2, 2, 2}}, {R34, {3, 4, 6, 3}}, {R50, {3, 4, 6, 3}}, {R101, {3, 4, 23, 3}}, {R152, {3, 8, 36, 3}} }; ILayer* BasicStem(INetworkDefinition *network, std::map<std::string, Weights>& weightMap, const std::string& lname, ITensor& input, int out_channels, int group_num = 1) { IConvolutionLayer* conv1 = network->addConvolutionNd(input, out_channels, DimsHW{ 7, 7 }, weightMap[lname + ".conv1.weight"], weightMap[lname + ".conv1.bias"]); assert(conv1); conv1->setStrideNd(DimsHW{ 2, 2 }); conv1->setPaddingNd(DimsHW{ 3, 3 }); conv1->setNbGroups(group_num); auto r1 = network->addActivation(*conv1->getOutput(0), ActivationType::kRELU); assert(r1); auto max_pool2d = network->addPoolingNd(*r1->getOutput(0), PoolingType::kMAX, DimsHW{ 3, 3 }); max_pool2d->setStrideNd(DimsHW{ 2, 2 }); max_pool2d->setPaddingNd(DimsHW{ 1, 1 }); auto mp_dim = max_pool2d->getOutput(0)->getDimensions(); return max_pool2d; } ITensor* BottleneckBlock(INetworkDefinition *network, std::map<std::string, Weights>& weightMap, const std::string& lname, ITensor& input, int in_channels, int bottleneck_channels, int out_channels, int stride = 1, int dilation = 1, int group_num = 1) { IConvolutionLayer* conv1 = network->addConvolutionNd(input, bottleneck_channels, DimsHW{ 1, 1 }, weightMap[lname + ".conv1.weight"], weightMap[lname + ".conv1.bias"]); assert(conv1); conv1->setStrideNd(DimsHW{ stride, stride }); conv1->setNbGroups(group_num); auto r1 = network->addActivation(*conv1->getOutput(0), ActivationType::kRELU); assert(r1); IConvolutionLayer* conv2 = network->addConvolutionNd(*r1->getOutput(0), bottleneck_channels, DimsHW{ 3, 3 }, weightMap[lname + ".conv2.weight"], weightMap[lname + ".conv2.bias"]); assert(conv2); conv2->setStrideNd(DimsHW{ 1, 1 }); conv2->setPaddingNd(DimsHW{ 1 * dilation, 1 * dilation }); conv2->setDilationNd(DimsHW{ dilation, dilation }); conv2->setNbGroups(group_num); auto r2 = network->addActivation(*conv2->getOutput(0), ActivationType::kRELU); assert(r2); IConvolutionLayer* conv3 = network->addConvolutionNd(*r2->getOutput(0), out_channels, DimsHW{ 1, 1 }, weightMap[lname + ".conv3.weight"], weightMap[lname + ".conv3.bias"]); assert(conv3); conv3->setStrideNd(DimsHW{ 1, 1 }); conv3->setNbGroups(group_num); ITensor* shortcut_value = nullptr; if (in_channels != out_channels) { auto shortcut = network->addConvolutionNd(input, out_channels, DimsHW{ 1, 1 }, weightMap[lname + ".shortcut.weight"], weightMap[lname + ".shortcut.bias"]); assert(shortcut); shortcut->setStrideNd(DimsHW{stride, stride}); shortcut->setNbGroups(group_num); shortcut_value = shortcut->getOutput(0); } else { shortcut_value = &input; } auto ew = network->addElementWise(*conv3->getOutput(0), *shortcut_value, ElementWiseOperation::kSUM); assert(ew); auto r3 = network->addActivation(*ew->getOutput(0), ActivationType::kRELU); assert(r3); return r3->getOutput(0); } ITensor* MakeStage(INetworkDefinition *network, std::map<std::string, Weights>& weightMap, const std::string& lname, ITensor& input, int stage, int in_channels, int bottleneck_channels, int out_channels, int first_stride = 1, int dilation = 1) { ITensor* out = &input; for (int i = 0; i < stage; i++) { if (i == 0) out = BottleneckBlock(network, weightMap, lname + "." + std::to_string(i), *out, in_channels, bottleneck_channels, out_channels, first_stride, dilation); else out = BottleneckBlock(network, weightMap, lname + "." + std::to_string(i), *out, in_channels, bottleneck_channels, out_channels, 1, dilation); in_channels = out_channels; } return out; } ITensor* BuildResNet(INetworkDefinition *network, std::map<std::string, Weights>& weightMap, ITensor& input, RESNETTYPE resnet_type, int stem_out_channels, int bottleneck_channels, int res2_out_channels, int res5_dilation = 1) { assert(res5_dilation == 1 || res5_dilation == 2); if (resnet_type == R18 || resnet_type == R34) { assert(res2_out_channels == 64); assert(res5_dilation == 1); } int out_channels = res2_out_channels; ITensor* out = nullptr; auto stem = BasicStem(network, weightMap, "backbone.stem", input, stem_out_channels); out = stem->getOutput(0); for (int i = 0; i < 3; i++) { int dilation = (i == 3) ? res5_dilation : 1; int first_stride = (i == 0 || (i == 3 && dilation == 2)) ? 1 : 2; out = MakeStage(network, weightMap, "backbone.res" + std::to_string(i + 2), *out, num_blocks_per_stage.at(resnet_type)[i], stem_out_channels, bottleneck_channels, out_channels, first_stride, dilation); stem_out_channels = out_channels; bottleneck_channels *= 2; out_channels *= 2; } return out; }
#pragma once #include <vector> #include <map> #include <string> #include "common.hpp" enum RESNETTYPE { R18 = 0, R34, R50, R101, R152 }; const std::map<RESNETTYPE, std::vector<int>> num_blocks_per_stage = { {R18, {2, 2, 2, 2}}, {R34, {3, 4, 6, 3}}, {R50, {3, 4, 6, 3}}, {R101, {3, 4, 23, 3}}, {R152, {3, 8, 36, 3}} }; ILayer* BasicStem(INetworkDefinition *network, std::map<std::string, Weights>& weightMap, const std::string& lname, ITensor& input, int out_channels, int group_num = 1) { IConvolutionLayer* conv1 = network->addConvolutionNd(input, out_channels, DimsHW{ 7, 7 }, weightMap[lname + ".conv1.weight"], weightMap[lname + ".conv1.bias"]); assert(conv1); conv1->setStrideNd(DimsHW{ 2, 2 }); conv1->setPaddingNd(DimsHW{ 3, 3 }); conv1->setNbGroups(group_num); auto r1 = network->addActivation(*conv1->getOutput(0), ActivationType::kRELU); assert(r1); auto max_pool2d = network->addPoolingNd(*r1->getOutput(0), PoolingType::kMAX, DimsHW{ 3, 3 }); max_pool2d->setStrideNd(DimsHW{ 2, 2 }); max_pool2d->setPaddingNd(DimsHW{ 1, 1 }); auto mp_dim = max_pool2d->getOutput(0)->getDimensions(); return max_pool2d; } ITensor* BottleneckBlock(INetworkDefinition *network, std::map<std::string, Weights>& weightMap, const std::string& lname, ITensor& input, int in_channels, int bottleneck_channels, int out_channels, int stride = 1, int dilation = 1, int group_num = 1) { IConvolutionLayer* conv1 = network->addConvolutionNd(input, bottleneck_channels, DimsHW{ 1, 1 }, weightMap[lname + ".conv1.weight"], weightMap[lname + ".conv1.bias"]); assert(conv1); conv1->setStrideNd(DimsHW{ stride, stride }); conv1->setNbGroups(group_num); auto r1 = network->addActivation(*conv1->getOutput(0), ActivationType::kRELU); assert(r1); IConvolutionLayer* conv2 = network->addConvolutionNd(*r1->getOutput(0), bottleneck_channels, DimsHW{ 3, 3 }, weightMap[lname + ".conv2.weight"], weightMap[lname + ".conv2.bias"]); assert(conv2); conv2->setStrideNd(DimsHW{ 1, 1 }); conv2->setPaddingNd(DimsHW{ 1 * dilation, 1 * dilation }); conv2->setDilationNd(DimsHW{ dilation, dilation }); conv2->setNbGroups(group_num); auto r2 = network->addActivation(*conv2->getOutput(0), ActivationType::kRELU); assert(r2); IConvolutionLayer* conv3 = network->addConvolutionNd(*r2->getOutput(0), out_channels, DimsHW{ 1, 1 }, weightMap[lname + ".conv3.weight"], weightMap[lname + ".conv3.bias"]); assert(conv3); conv3->setStrideNd(DimsHW{ 1, 1 }); conv3->setNbGroups(group_num); ITensor* shortcut_value = nullptr; if (in_channels != out_channels) { auto shortcut = network->addConvolutionNd(input, out_channels, DimsHW{ 1, 1 }, weightMap[lname + ".shortcut.weight"], weightMap[lname + ".shortcut.bias"]); assert(shortcut); shortcut->setStrideNd(DimsHW{stride, stride}); shortcut->setNbGroups(group_num); shortcut_value = shortcut->getOutput(0); } else { shortcut_value = &input; } auto ew = network->addElementWise(*conv3->getOutput(0), *shortcut_value, ElementWiseOperation::kSUM); assert(ew); auto r3 = network->addActivation(*ew->getOutput(0), ActivationType::kRELU); assert(r3); return r3->getOutput(0); } ITensor* MakeStage(INetworkDefinition *network, std::map<std::string, Weights>& weightMap, const std::string& lname, ITensor& input, int stage, int in_channels, int bottleneck_channels, int out_channels, int first_stride = 1, int dilation = 1) { ITensor* out = &input; for (int i = 0; i < stage; i++) { if (i == 0) out = BottleneckBlock(network, weightMap, lname + "." + std::to_string(i), *out, in_channels, bottleneck_channels, out_channels, first_stride, dilation); else out = BottleneckBlock(network, weightMap, lname + "." + std::to_string(i), *out, in_channels, bottleneck_channels, out_channels, 1, dilation); in_channels = out_channels; } return out; } ITensor* BuildResNet(INetworkDefinition *network, std::map<std::string, Weights>& weightMap, ITensor& input, RESNETTYPE resnet_type, int stem_out_channels, int bottleneck_channels, int res2_out_channels, int res5_dilation = 1) { assert(res5_dilation == 1 || res5_dilation == 2);
int out_channels = res2_out_channels; ITensor* out = nullptr; auto stem = BasicStem(network, weightMap, "backbone.stem", input, stem_out_channels); out = stem->getOutput(0); for (int i = 0; i < 3; i++) { int dilation = (i == 3) ? res5_dilation : 1; int first_stride = (i == 0 || (i == 3 && dilation == 2)) ? 1 : 2; out = MakeStage(network, weightMap, "backbone.res" + std::to_string(i + 2), *out, num_blocks_per_stage.at(resnet_type)[i], stem_out_channels, bottleneck_channels, out_channels, first_stride, dilation); stem_out_channels = out_channels; bottleneck_channels *= 2; out_channels *= 2; } return out; }
if (resnet_type == R18 || resnet_type == R34) { assert(res2_out_channels == 64); assert(res5_dilation == 1); }
if_condition
[]
C++
media/jni/audioeffect/android_media_SourceDefaultEffect.cpp
rio-31/android_frameworks_base-1
091a068a3288d27d77636708679dde58b7b7fd25
#define LOG_TAG "SourceDefaultEffect-JNI" #include <utils/Errors.h> #include <utils/Log.h> #include <jni.h> #include <nativehelper/JNIHelp.h> #include <android_runtime/AndroidRuntime.h> #include "media/AudioEffect.h" #include <nativehelper/ScopedUtfChars.h> #include "android_media_AudioEffect.h" using namespace android; static const char* const kClassPathName = "android/media/audiofx/SourceDefaultEffect"; static jint android_media_SourceDefaultEffect_native_setup(JNIEnv *env, jobject , jstring type, jstring uuid, jint priority, jint source, jstring opPackageName, jintArray jId) { ALOGV("android_media_SourceDefaultEffect_native_setup"); status_t lStatus = NO_ERROR; jint* nId = NULL; const char *typeStr = NULL; const char *uuidStr = NULL; ScopedUtfChars opPackageNameStr(env, opPackageName); if (type != NULL) { typeStr = env->GetStringUTFChars(type, NULL); if (typeStr == NULL) { lStatus = NO_MEMORY; jniThrowException(env, "java/lang/RuntimeException", "Out of memory"); goto setup_exit; } } if (uuid != NULL) { uuidStr = env->GetStringUTFChars(uuid, NULL); if (uuidStr == NULL) { lStatus = NO_MEMORY; jniThrowException(env, "java/lang/RuntimeException", "Out of memory"); goto setup_exit; } } if (typeStr == NULL && uuidStr == NULL) { lStatus = BAD_VALUE; goto setup_exit; } nId = reinterpret_cast<jint *>(env->GetPrimitiveArrayCritical(jId, NULL)); if (nId == NULL) { ALOGE("setup: Error retrieving id pointer"); lStatus = BAD_VALUE; goto setup_exit; } audio_unique_id_t id; lStatus = AudioEffect::addSourceDefaultEffect(typeStr, String16(opPackageNameStr.c_str()), uuidStr, priority, static_cast<audio_source_t>(source), &id); if (lStatus != NO_ERROR) { ALOGE("setup: Error adding SourceDefaultEffect"); goto setup_exit; } nId[0] = static_cast<jint>(id); setup_exit: if (nId != NULL) { env->ReleasePrimitiveArrayCritical(jId, nId, 0); nId = NULL; } if (uuidStr != NULL) { env->ReleaseStringUTFChars(uuid, uuidStr); uuidStr = NULL; } if (typeStr != NULL) { env->ReleaseStringUTFChars(type, typeStr); typeStr = NULL; } return AudioEffectJni::translateNativeErrorToJava(lStatus); } static void android_media_SourceDefaultEffect_native_release(JNIEnv *, jobject , jint id) { status_t lStatus = AudioEffect::removeSourceDefaultEffect(id); if (lStatus != NO_ERROR) { ALOGW("Error releasing SourceDefaultEffect: %d", lStatus); } } static const JNINativeMethod gMethods[] = { {"native_setup", "(Ljava/lang/String;Ljava/lang/String;IILjava/lang/String;[I)I", (void *)android_media_SourceDefaultEffect_native_setup}, {"native_release", "(I)V", (void *)android_media_SourceDefaultEffect_native_release}, }; int register_android_media_SourceDefaultEffect(JNIEnv *env) { return AndroidRuntime::registerNativeMethods(env, kClassPathName, gMethods, NELEM(gMethods)); }
#define LOG_TAG "SourceDefaultEffect-JNI" #include <utils/Errors.h> #include <utils/Log.h> #include <jni.h> #include <nativehelper/JNIHelp.h> #include <android_runtime/AndroidRuntime.h> #include "media/AudioEffect.h" #include <nativehelper/ScopedUtfChars.h> #include "android_media_AudioEffect.h" using namespace android; static const char* const kClassPathName = "android/media/audiofx/SourceDefaultEffect"; static jint android_media_SourceDefaultEffect_native_setup(JNIEnv *env, jobject , jstring type, jstring uuid, jint priority, jint source, jstring opPackageName, jintArray jId) { ALOGV("android_media_SourceDefaultEffect_native_setup"); status_t lStatus = NO_ERROR; jint* nId = NULL; const char *typeStr = NULL; const char *uuidStr = NULL; ScopedUtfChars opPackageNameStr(env, opPackageName); if (type != NULL) { typeStr = env->GetStringUTFChars(type, NULL); if (typeStr == NULL) { lStatus = NO_MEMORY; jniThrowException(env, "java/lang/RuntimeException", "Out of memory"); goto setup_exit; } } if (uuid != NULL) { uuidStr = env->GetStringUTFChars(uuid, NULL); if (uuidStr == NULL) { lStatus = NO_MEMORY; jniThrowException(env, "java/lang/RuntimeException", "Out of memory"); goto setup_exit; } } if (typeStr == NULL && uuidStr == NULL) { lStatus = BAD_VALUE; goto setup_exit; } nId = reinterpret_cast<jint *>(env->GetPrimitiveArrayCritical(jId, NULL)); if (nId == NULL) { ALOGE("setup: Error retrieving id pointer"); lStatus = BAD_VALUE; goto setup_exit; } audio_unique_id_t id; lStatus =
; if (lStatus != NO_ERROR) { ALOGE("setup: Error adding SourceDefaultEffect"); goto setup_exit; } nId[0] = static_cast<jint>(id); setup_exit: if (nId != NULL) { env->ReleasePrimitiveArrayCritical(jId, nId, 0); nId = NULL; } if (uuidStr != NULL) { env->ReleaseStringUTFChars(uuid, uuidStr); uuidStr = NULL; } if (typeStr != NULL) { env->ReleaseStringUTFChars(type, typeStr); typeStr = NULL; } return AudioEffectJni::translateNativeErrorToJava(lStatus); } static void android_media_SourceDefaultEffect_native_release(JNIEnv *, jobject , jint id) { status_t lStatus = AudioEffect::removeSourceDefaultEffect(id); if (lStatus != NO_ERROR) { ALOGW("Error releasing SourceDefaultEffect: %d", lStatus); } } static const JNINativeMethod gMethods[] = { {"native_setup", "(Ljava/lang/String;Ljava/lang/String;IILjava/lang/String;[I)I", (void *)android_media_SourceDefaultEffect_native_setup}, {"native_release", "(I)V", (void *)android_media_SourceDefaultEffect_native_release}, }; int register_android_media_SourceDefaultEffect(JNIEnv *env) { return AndroidRuntime::registerNativeMethods(env, kClassPathName, gMethods, NELEM(gMethods)); }
AudioEffect::addSourceDefaultEffect(typeStr, String16(opPackageNameStr.c_str()), uuidStr, priority, static_cast<audio_source_t>(source), &id)
call_expression
[]
C++
zircon/system/uapp/iotime/iotime.cc
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
#include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <block-client/client.h> #include <fuchsia/hardware/block/c/fidl.h> #include <lib/fzl/fdio.h> #include <lib/zx/channel.h> #include <lib/zx/fifo.h> #include <lib/zx/vmo.h> #include <ramdevice-client/ramdisk.h> #include <zircon/device/block.h> #include <zircon/syscalls.h> #include <zircon/time.h> #include <zircon/types.h> static uint64_t number(const char* str) { char* end; uint64_t n = strtoull(str, &end, 10); uint64_t m = 1; switch (*end) { case 'G': case 'g': m = 1024 * 1024 * 1024; break; case 'M': case 'm': m = 1024 * 1024; break; case 'K': case 'k': m = 1024; break; } return m * n; } static void bytes_per_second(uint64_t bytes, uint64_t nanos) { double s = ((double)nanos) / ((double)1000000000); double rate = ((double)bytes) / s; const char* unit = "B"; if (rate > 1024 * 1024) { unit = "MB"; rate /= 1024 * 1024; } else if (rate > 1024) { unit = "KB"; rate /= 1024; } fprintf(stderr, "%g %s/s\n", rate, unit); } static zx_duration_t iotime_posix(int is_read, int fd, size_t total, size_t bufsz) { void* buffer = malloc(bufsz); if (buffer == NULL) { fprintf(stderr, "error: out of memory\n"); return ZX_TIME_INFINITE; } zx_time_t t0 = zx_clock_get_monotonic(); size_t n = total; const char* fn_name = is_read ? "read" : "write"; while (n > 0) { size_t xfer = (n > bufsz) ? bufsz : n; ssize_t r = is_read ? read(fd, buffer, xfer) : write(fd, buffer, xfer); if (r < 0) { fprintf(stderr, "error: %s() error %d\n", fn_name, errno); return ZX_TIME_INFINITE; } if ((size_t)r != xfer) { fprintf(stderr, "error: %s() %zu of %zu bytes processed\n", fn_name, r, xfer); return ZX_TIME_INFINITE; } n -= xfer; } zx_time_t t1 = zx_clock_get_monotonic(); return zx_time_sub_time(t1, t0); } static zx_duration_t iotime_block(int is_read, int fd, size_t total, size_t bufsz) { if ((total % 4096) || (bufsz % 4096)) { fprintf(stderr, "error: total and buffer size must be multiples of 4K\n"); return ZX_TIME_INFINITE; } return iotime_posix(is_read, fd, total, bufsz); } static zx_duration_t iotime_fifo(char* dev, int is_read, int fd, size_t total, size_t bufsz) { zx_status_t status; zx::vmo vmo; if ((status = zx::vmo::create(bufsz, 0, &vmo)) != ZX_OK) { fprintf(stderr, "error: out of memory %d\n", status); return ZX_TIME_INFINITE; } fzl::UnownedFdioCaller disk_connection(fd); zx::unowned_channel channel(disk_connection.borrow_channel()); fuchsia_hardware_block_BlockInfo info; zx_status_t io_status = fuchsia_hardware_block_BlockGetInfo(channel->get(), &status, &info); if (io_status != ZX_OK || status != ZX_OK) { fprintf(stderr, "error: cannot get info for '%s'\n", dev); return ZX_TIME_INFINITE; } zx::fifo fifo; io_status = fuchsia_hardware_block_BlockGetFifo(channel->get(), &status, fifo.reset_and_get_address()); if (io_status != ZX_OK || status != ZX_OK) { fprintf(stderr, "error: cannot get fifo for '%s'\n", dev); return ZX_TIME_INFINITE; } groupid_t group = 0; zx::vmo dup; if ((status = vmo.duplicate(ZX_RIGHT_SAME_RIGHTS, &dup)) != ZX_OK) { fprintf(stderr, "error: cannot duplicate handle %d\n", status); return ZX_TIME_INFINITE; } fuchsia_hardware_block_VmoID vmoid; io_status = fuchsia_hardware_block_BlockAttachVmo(channel->get(), dup.release(), &status, &vmoid); if (io_status != ZX_OK || status != ZX_OK) { fprintf(stderr, "error: cannot attach vmo for '%s'\n", dev); return ZX_TIME_INFINITE; } fifo_client_t* client; if ((status = block_fifo_create_client(fifo.release(), &client)) != ZX_OK) { fprintf(stderr, "error: cannot create block client for '%s' %d\n", dev, status); return ZX_TIME_INFINITE; } zx_time_t t0 = zx_clock_get_monotonic(); size_t n = total; while (n > 0) { size_t xfer = (n > bufsz) ? bufsz : n; block_fifo_request_t request = { .opcode = static_cast<uint32_t>(is_read ? BLOCKIO_READ : BLOCKIO_WRITE), .reqid = 0, .group = group, .vmoid = vmoid.id, .length = static_cast<uint32_t>(xfer / info.block_size), .vmo_offset = 0, .dev_offset = (total - n) / info.block_size, }; if ((status = block_fifo_txn(client, &request, 1)) != ZX_OK) { fprintf(stderr, "error: block_fifo_txn error %d\n", status); return ZX_TIME_INFINITE; } n -= xfer; } zx_time_t t1 = zx_clock_get_monotonic(); return zx_time_sub_time(t1, t0); } static int usage(void) { fprintf(stderr, "usage: iotime <read|write> <posix|block|fifo> <device|--ramdisk> <bytes> <bufsize>\n\n" " <bytes> and <bufsize> must be a multiple of 4k for block mode\n" " --ramdisk only supported for block mode\n"); return -1; } int main(int argc, char** argv) { if (argc != 6) { return usage(); } int is_read = !strcmp(argv[1], "read"); size_t total = number(argv[4]); size_t bufsz = number(argv[5]); int r = -1; ramdisk_client_t* ramdisk = NULL; int fd; if (!strcmp(argv[3], "--ramdisk")) { if (strcmp(argv[2], "block")) { fprintf(stderr, "ramdisk only supported for block\n"); goto done; } zx_status_t status = ramdisk_create(512, total / 512, &ramdisk); if (status != ZX_OK) { fprintf(stderr, "error: cannot create %zu-byte ramdisk\n", total); goto done; } fd = ramdisk_get_block_fd(ramdisk); } else { if ((fd = open(argv[3], is_read ? O_RDONLY : O_WRONLY)) < 0) { fprintf(stderr, "error: cannot open '%s'\n", argv[3]); goto done; } } zx_duration_t res; if (!strcmp(argv[2], "posix")) { res = iotime_posix(is_read, fd, total, bufsz); } else if (!strcmp(argv[2], "block")) { res = iotime_block(is_read, fd, total, bufsz); } else if (!strcmp(argv[2], "fifo")) { res = iotime_fifo(argv[3], is_read, fd, total, bufsz); } else { fprintf(stderr, "error: unknown mode '%s'\n", argv[2]); goto done; } if (res != ZX_TIME_INFINITE) { fprintf(stderr, "%s %zu bytes in %zu ns: ", is_read ? "read" : "write", total, res); bytes_per_second(total, res); r = 0; goto done; } else { goto done; } done: if (ramdisk != NULL) { ramdisk_destroy(ramdisk); } return r; }
#include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <block-client/client.h> #include <fuchsia/hardware/block/c/fidl.h> #include <lib/fzl/fdio.h> #include <lib/zx/channel.h> #include <lib/zx/fifo.h> #include <lib/zx/vmo.h> #include <ramdevice-client/ramdisk.h> #include <zircon/device/block.h> #include <zircon/syscalls.h> #include <zircon/time.h> #include <zircon/types.h> static uint64_t number(const char* str) { char* end; uint64_t n = strtoull(str, &end, 10); uint64_t m = 1; switch (*end) { case 'G': case 'g': m = 1024 * 1024 * 1024; break; case 'M': case 'm': m = 1024 * 1024; break; case 'K': case 'k': m = 1024; break; } return m * n; } static void bytes_per_second(uint64_t bytes, uint64_t nanos) { double s = ((double)nanos) / ((double)1000000000); double rate = ((double)bytes) / s; const char* unit = "B"; if (rate > 1024 * 1024) { unit = "MB"; rate /= 1024 * 1024; } else if (rate > 1024) { unit = "KB"; rate /= 1024; } fprintf(std
r, "error: out of memory\n"); return ZX_TIME_INFINITE; } zx_time_t t0 = zx_clock_get_monotonic(); size_t n = total; const char* fn_name = is_read ? "read" : "write"; while (n > 0) { size_t xfer = (n > bufsz) ? bufsz : n; ssize_t r = is_read ? read(fd, buffer, xfer) : write(fd, buffer, xfer); if (r < 0) { fprintf(stderr, "error: %s() error %d\n", fn_name, errno); return ZX_TIME_INFINITE; } if ((size_t)r != xfer) { fprintf(stderr, "error: %s() %zu of %zu bytes processed\n", fn_name, r, xfer); return ZX_TIME_INFINITE; } n -= xfer; } zx_time_t t1 = zx_clock_get_monotonic(); return zx_time_sub_time(t1, t0); } static zx_duration_t iotime_block(int is_read, int fd, size_t total, size_t bufsz) { if ((total % 4096) || (bufsz % 4096)) { fprintf(stderr, "error: total and buffer size must be multiples of 4K\n"); return ZX_TIME_INFINITE; } return iotime_posix(is_read, fd, total, bufsz); } static zx_duration_t iotime_fifo(char* dev, int is_read, int fd, size_t total, size_t bufsz) { zx_status_t status; zx::vmo vmo; if ((status = zx::vmo::create(bufsz, 0, &vmo)) != ZX_OK) { fprintf(stderr, "error: out of memory %d\n", status); return ZX_TIME_INFINITE; } fzl::UnownedFdioCaller disk_connection(fd); zx::unowned_channel channel(disk_connection.borrow_channel()); fuchsia_hardware_block_BlockInfo info; zx_status_t io_status = fuchsia_hardware_block_BlockGetInfo(channel->get(), &status, &info); if (io_status != ZX_OK || status != ZX_OK) { fprintf(stderr, "error: cannot get info for '%s'\n", dev); return ZX_TIME_INFINITE; } zx::fifo fifo; io_status = fuchsia_hardware_block_BlockGetFifo(channel->get(), &status, fifo.reset_and_get_address()); if (io_status != ZX_OK || status != ZX_OK) { fprintf(stderr, "error: cannot get fifo for '%s'\n", dev); return ZX_TIME_INFINITE; } groupid_t group = 0; zx::vmo dup; if ((status = vmo.duplicate(ZX_RIGHT_SAME_RIGHTS, &dup)) != ZX_OK) { fprintf(stderr, "error: cannot duplicate handle %d\n", status); return ZX_TIME_INFINITE; } fuchsia_hardware_block_VmoID vmoid; io_status = fuchsia_hardware_block_BlockAttachVmo(channel->get(), dup.release(), &status, &vmoid); if (io_status != ZX_OK || status != ZX_OK) { fprintf(stderr, "error: cannot attach vmo for '%s'\n", dev); return ZX_TIME_INFINITE; } fifo_client_t* client; if ((status = block_fifo_create_client(fifo.release(), &client)) != ZX_OK) { fprintf(stderr, "error: cannot create block client for '%s' %d\n", dev, status); return ZX_TIME_INFINITE; } zx_time_t t0 = zx_clock_get_monotonic(); size_t n = total; while (n > 0) { size_t xfer = (n > bufsz) ? bufsz : n; block_fifo_request_t request = { .opcode = static_cast<uint32_t>(is_read ? BLOCKIO_READ : BLOCKIO_WRITE), .reqid = 0, .group = group, .vmoid = vmoid.id, .length = static_cast<uint32_t>(xfer / info.block_size), .vmo_offset = 0, .dev_offset = (total - n) / info.block_size, }; if ((status = block_fifo_txn(client, &request, 1)) != ZX_OK) { fprintf(stderr, "error: block_fifo_txn error %d\n", status); return ZX_TIME_INFINITE; } n -= xfer; } zx_time_t t1 = zx_clock_get_monotonic(); return zx_time_sub_time(t1, t0); } static int usage(void) { fprintf(stderr, "usage: iotime <read|write> <posix|block|fifo> <device|--ramdisk> <bytes> <bufsize>\n\n" " <bytes> and <bufsize> must be a multiple of 4k for block mode\n" " --ramdisk only supported for block mode\n"); return -1; } int main(int argc, char** argv) { if (argc != 6) { return usage(); } int is_read = !strcmp(argv[1], "read"); size_t total = number(argv[4]); size_t bufsz = number(argv[5]); int r = -1; ramdisk_client_t* ramdisk = NULL; int fd; if (!strcmp(argv[3], "--ramdisk")) { if (strcmp(argv[2], "block")) { fprintf(stderr, "ramdisk only supported for block\n"); goto done; } zx_status_t status = ramdisk_create(512, total / 512, &ramdisk); if (status != ZX_OK) { fprintf(stderr, "error: cannot create %zu-byte ramdisk\n", total); goto done; } fd = ramdisk_get_block_fd(ramdisk); } else { if ((fd = open(argv[3], is_read ? O_RDONLY : O_WRONLY)) < 0) { fprintf(stderr, "error: cannot open '%s'\n", argv[3]); goto done; } } zx_duration_t res; if (!strcmp(argv[2], "posix")) { res = iotime_posix(is_read, fd, total, bufsz); } else if (!strcmp(argv[2], "block")) { res = iotime_block(is_read, fd, total, bufsz); } else if (!strcmp(argv[2], "fifo")) { res = iotime_fifo(argv[3], is_read, fd, total, bufsz); } else { fprintf(stderr, "error: unknown mode '%s'\n", argv[2]); goto done; } if (res != ZX_TIME_INFINITE) { fprintf(stderr, "%s %zu bytes in %zu ns: ", is_read ? "read" : "write", total, res); bytes_per_second(total, res); r = 0; goto done; } else { goto done; } done: if (ramdisk != NULL) { ramdisk_destroy(ramdisk); } return r; }
err, "%g %s/s\n", rate, unit); } static zx_duration_t iotime_posix(int is_read, int fd, size_t total, size_t bufsz) { void* buffer = malloc(bufsz); if (buffer == NULL) { fprintf(stder
random
[]
C++
old/v2/src/sim/Maze.cpp
qiuwenhui/micromouse_-simulator
6625b2814b8281a0db5d4e9d57ae8881ff31fed0
#include "Maze.h" #include <queue> #include <set> #include <vector> #include "../maze/IMazeAlgorithm.h" #include "../maze/MazeAlgorithms.h" #include "Assert.h" #include "Directory.h" #include "Logging.h" #include "MazeChecker.h" #include "MazeFileType.h" #include "MazeFileUtilities.h" #include "MazeInterface.h" #include "Param.h" #include "SimUtilities.h" #include "Tile.h" namespace sim { Maze::Maze() { std::vector<std::vector<BasicTile>> basicMaze; if (P()->useMazeFile()) { std::string mazeFilePath = Directory::getResMazeDirectory() + P()->mazeFile(); try { basicMaze = MazeFileUtilities::loadMaze(mazeFilePath); } catch (...) { std::string reason = ( SimUtilities::isFile(mazeFilePath) ? "invalid format" : "file doesn't exist"); L()->error( "Unable to initialize maze from file \"%v\": %v.", mazeFilePath, reason); SimUtilities::quit(); } } else { if (!MazeAlgorithms::isMazeAlgorithm(P()->mazeAlgorithm())) { L()->error("\"%v\" is not a valid maze algorithm.", P()->mazeAlgorithm()); SimUtilities::quit(); } basicMaze = getBlankBasicMaze(P()->generatedMazeWidth(), P()->generatedMazeHeight()); MazeInterface mazeInterface(&basicMaze); MazeAlgorithms::getMazeAlgorithm(P()->mazeAlgorithm())->generate( P()->generatedMazeWidth(), P()->generatedMazeHeight(), &mazeInterface); } m_isValidMaze = MazeChecker::isValidMaze(basicMaze); if (!m_isValidMaze) { L()->warn("The maze failed validation. The mouse algorithm will not execute."); } if (!P()->useMazeFile() && P()->saveGeneratedMaze()) { MazeFileType type = STRING_TO_MAZE_FILE_TYPE.at(P()->generatedMazeType()); std::string mazeFilePath = Directory::getResMazeDirectory() + P()->generatedMazeFile() + MAZE_FILE_TYPE_TO_SUFFIX.at(type); bool success = MazeFileUtilities::saveMaze(basicMaze, mazeFilePath, type); if (success) { L()->info("Maze saved to \"%v\".", mazeFilePath); } else { L()->warn("Unable to save maze to \"%v\".", mazeFilePath); } } if (P()->mazeMirrored()) { basicMaze = mirrorAcrossVertical(basicMaze); L()->info("Mirroring the maze across the vertical."); } for (int i = 0; i < P()->mazeRotations(); i += 1) { basicMaze = rotateCounterClockwise(basicMaze); L()->info("Rotating the maze counter-clockwise (%vx).", i + 1); } m_isOfficialMaze = m_isValidMaze && MazeChecker::isOfficialMaze(basicMaze); if (m_isValidMaze && !m_isOfficialMaze) { L()->warn("The maze did not pass the \"is official maze\" tests."); } m_maze = initializeFromBasicMaze(basicMaze); } int Maze::getWidth() const { return m_maze.size(); } int Maze::getHeight() const { return (m_maze.size() > 0 ? m_maze.at(0).size() : 0); } bool Maze::withinMaze(int x, int y) const { return 0 <= x && x < getWidth() && 0 <= y && y < getHeight(); } Tile* Maze::getTile(int x, int y) { SIM_ASSERT_TR(withinMaze(x, y)); return &m_maze.at(x).at(y); } const Tile* Maze::getTile(int x, int y) const { SIM_ASSERT_TR(withinMaze(x, y)); return &m_maze.at(x).at(y); } bool Maze::isValidMaze() const { return m_isOfficialMaze; } bool Maze::isOfficialMaze() const { return m_isOfficialMaze; } bool Maze::isCenterTile(int x, int y) const { return ContainerUtilities::vectorContains( MazeChecker::getCenterTiles(getWidth(), getHeight()), std::make_pair(x, y) ); } std::vector<std::vector<Tile>> Maze::initializeFromBasicMaze(const std::vector<std::vector<BasicTile>>& basicMaze) { std::vector<std::vector<Tile>> maze; for (int x = 0; x < basicMaze.size(); x += 1) { std::vector<Tile> column; for (int y = 0; y < basicMaze.at(x).size(); y += 1) { Tile tile; tile.setPos(x, y); for (Direction direction : DIRECTIONS) { tile.setWall(direction, basicMaze.at(x).at(y).walls.at(direction)); } tile.initPolygons(basicMaze.size(), basicMaze.at(x).size()); column.push_back(tile); } maze.push_back(column); } maze = setTileDistances(maze); return maze; } std::vector<std::vector<BasicTile>> Maze::getBlankBasicMaze(int mazeWidth, int mazeHeight) { std::vector<std::vector<BasicTile>> blankMaze; for (int x = 0; x < mazeWidth; x += 1) { std::vector<BasicTile> column; for (int y = 0; y < mazeHeight; y += 1) { BasicTile tile; for (Direction direction : DIRECTIONS) { tile.walls.insert(std::make_pair(direction, false)); } column.push_back(tile); } blankMaze.push_back(column); } return blankMaze; } std::vector<std::vector<BasicTile>> Maze::mirrorAcrossVertical(const std::vector<std::vector<BasicTile>>& basicMaze) { std::vector<std::vector<BasicTile>> mirrored; for (int x = 0; x < basicMaze.size(); x += 1) { std::vector<BasicTile> column; for (int y = 0; y < basicMaze.at(x).size(); y += 1) { BasicTile tile; tile.walls.insert(std::make_pair(Direction::NORTH, basicMaze.at(basicMaze.size() - 1 - x).at(y).walls.at(Direction::NORTH))); tile.walls.insert(std::make_pair(Direction::EAST, basicMaze.at(basicMaze.size() - 1 - x).at(y).walls.at(Direction::WEST))); tile.walls.insert(std::make_pair(Direction::SOUTH, basicMaze.at(basicMaze.size() - 1 - x).at(y).walls.at(Direction::SOUTH))); tile.walls.insert(std::make_pair(Direction::WEST, basicMaze.at(basicMaze.size() - 1 - x).at(y).walls.at(Direction::EAST))); column.push_back(tile); } mirrored.push_back(column); } return mirrored; } std::vector<std::vector<BasicTile>> Maze::rotateCounterClockwise(const std::vector<std::vector<BasicTile>>& basicMaze) { std::vector<std::vector<BasicTile>> rotated; for (int x = 0; x < basicMaze.size(); x += 1) { std::vector<BasicTile> row; for (int y = basicMaze.at(x).size() - 1; y >= 0; y -= 1) { BasicTile tile; int rotatedTileX = basicMaze.at(x).size() - 1 - y; tile.walls.insert(std::make_pair(Direction::NORTH, basicMaze.at(x).at(y).walls.at(Direction::EAST))); tile.walls.insert(std::make_pair(Direction::EAST, basicMaze.at(x).at(y).walls.at(Direction::SOUTH))); tile.walls.insert(std::make_pair(Direction::SOUTH, basicMaze.at(x).at(y).walls.at(Direction::WEST))); tile.walls.insert(std::make_pair(Direction::WEST, basicMaze.at(x).at(y).walls.at(Direction::NORTH))); if (rotated.size() <= rotatedTileX) { rotated.push_back({tile}); } else { rotated.at(rotatedTileX).push_back(tile); } } } return rotated; } std::vector<std::vector<Tile>> Maze::setTileDistances(std::vector<std::vector<Tile>> maze) { int width = maze.size(); int height = maze.at(0).size(); auto getNeighbor = [&maze, &width, &height](int x, int y, Direction direction) { switch (direction) { case Direction::NORTH: return (y < height - 1 ? &maze.at(x).at(y + 1) : nullptr); case Direction::EAST: return (x < width - 1 ? &maze.at(x + 1).at(y) : nullptr); case Direction::SOUTH: return (0 < y ? &maze.at(x).at(y - 1) : nullptr); case Direction::WEST: return (0 < x ? &maze.at(x - 1).at(y) : nullptr); } }; std::vector<Tile*> centerTiles; centerTiles.push_back(&maze.at((width - 1) / 2).at((height - 1) / 2)); if (width % 2 == 0) { centerTiles.push_back(&maze.at( width / 2).at((height - 1) / 2)); if (height % 2 == 0) { centerTiles.push_back(&maze.at((width - 1) / 2).at( height / 2)); centerTiles.push_back(&maze.at( width / 2).at( height / 2)); } } else if (height % 2 == 0) { centerTiles.push_back(&maze.at((width - 1) / 2).at( height / 2)); } std::queue<Tile*> discovered; for (Tile* tile : centerTiles) { tile->setDistance(0); discovered.push(tile); } while (!discovered.empty()){ Tile* tile = discovered.front(); discovered.pop(); for (Direction direction : DIRECTIONS) { if (!tile->isWall(direction)) { Tile* neighbor = getNeighbor(tile->getX(), tile->getY(), direction); if (neighbor != nullptr && neighbor->getDistance() == -1) { neighbor->setDistance(tile->getDistance() + 1); discovered.push(neighbor); } } } } return maze; } }
#include "Maze.h" #include <queue> #include <set> #include <vector> #include "../maze/IMazeAlgorithm.h" #include "../maze/MazeAlgorithms.h" #include "Assert.h" #include "Directory.h" #include "Logging.h" #include "MazeChecker.h" #include "MazeFileType.h" #include "MazeFileUtilities.h" #include "MazeInterface.h" #include "Param.h" #include "SimUtilities.h" #include "Tile.h" namespace sim { Maze::Maze() { std::vector<std::vector<BasicTile>> basicMaze; if (P()->useMazeFile()) { std::string mazeFilePath = Directory::getResMazeDirectory() + P()->mazeFile(); try { basicMaze = MazeFileUtilities::loadMaze(mazeFilePath); } catch (...) { std::string reason = ( SimUtilities::isFile(mazeFilePath) ? "invalid format" : "file doesn't exist"); L()->error( "Unable to initialize maze from file \"%v\": %v.", mazeFilePath, reason); SimUtilities::quit(); } } else { if (!MazeAlgorithms::isMazeAlgorithm(P()->mazeAlgorithm())) { L()->error("\"%v\" is not a valid maze algorithm.", P()->mazeAlgorithm()); SimUtilities::quit(); } basicMaze = getBlankBasicMaze(P()->generatedMazeWidth(), P()->generatedMazeHeight()); MazeInterface mazeInterface(&basicMaze); MazeAlgorithms::getMazeAlgorithm(P()->mazeAlgorithm())->generate( P()->generatedMazeWidth(), P()->generatedMazeHeight(), &mazeInterface); } m_isValidMaze = MazeChecker::isValidMaze(basicMaze); if (!m_isValidMaze) { L()->warn("The maze failed validation. The mouse algorithm will not execute."); } if (!P()->useMazeFile() && P()->saveGeneratedMaze()) { MazeFileType type = STRING_TO_MAZE_FILE_TYPE.at(P()->generatedMazeType()); std::string mazeFilePath = Directory::getResMazeDirectory() + P()->generatedMazeFile() + MAZE_FILE_TYPE_TO_SUFFIX.at(type); bool success = MazeFileUtilities::saveMaze(basicMaze, mazeFilePath, type); if (success) { L()->info("Maze saved to \"%v\".", mazeFilePath); } else { L()->warn("Unable to save maze to \"%v\".", mazeFilePath); } } if (P()->mazeMirrored()) { basicMaze = mirrorAcrossVertical(basicMaze); L()->info("Mirroring the maze across the vertical."); } for (int i = 0; i < P()->mazeRotations(); i += 1) { basicMaze = rotateCounterClockwise(basicMaze); L()->info("Rotating the maze counter-clockwise (%vx).", i + 1); } m_isOfficialMaze = m_isValidMaze && MazeChecker::isOfficialMaze(basicMaze); if (m_isValidMaze && !m_isOfficialMaze) { L()->warn("The maze did not pass the \"is official maze\" tests."); } m_maze = initializeFromBasicMaze(basicMaze); } int Maze::getWidth() const { return m_maze.size(); } int Maze::getHeight() const { return (m_maze.size() > 0 ? m_maze.at(0).size() : 0); } bool Maze::withinMaze(int x, int y) const { return 0 <= x && x < getWidth() && 0 <= y && y < getHeight(); } Tile* Maze::getTile(int x, int y) { SIM_ASSERT_TR(withinMaze(x, y)); return &m_maze.at(x).at(y); } const Tile* Maze::getTile(int x, int y) const { SIM_ASSERT_TR(withinMaze(x, y)); return &m_maze.at(x).at(y); } bool Maze::isValidMaze() const { return m_isOfficialMaze; } bool Maze::isOfficialMaze() const { return m_isOfficialMaze; } bool Maze::isCenterTile(int x, int y) const { return ContainerUtilities::vectorContains( MazeChecker::getCenterTiles(getWidth(), getHeight()), std::make_pair(x, y) ); } std::vector<std::vector<Tile>> Maze::initializeFromBasicMaze(const std::vector<std::vector<BasicTile>>& basicMaze) { std::vector<std::vector<Tile>> maze; for (int x = 0; x < basicMaze.size(); x += 1) { std::vector<Tile> column; for (int y = 0; y < basicMaze.at(x).size(); y += 1) { Tile tile; tile.setPos(x, y); for (Direction direction : DIRECTIONS) { tile.setWall(direction, basicMaze.at(x).at(y).walls.at(direction)); } tile.initPolygons(basicMaze.size(), basicMaze.at(x).size()); column.push_back(tile); } maze.push_back(column); } maze = setTileDistances(maze); return maze; } std::vector<std::vector<BasicTile>> Maze::getBlankBasicMaze(int
} } return rotated; } std::vector<std::vector<Tile>> Maze::setTileDistances(std::vector<std::vector<Tile>> maze) { int width = maze.size(); int height = maze.at(0).size(); auto getNeighbor = [&maze, &width, &height](int x, int y, Direction direction) { switch (direction) { case Direction::NORTH: return (y < height - 1 ? &maze.at(x).at(y + 1) : nullptr); case Direction::EAST: return (x < width - 1 ? &maze.at(x + 1).at(y) : nullptr); case Direction::SOUTH: return (0 < y ? &maze.at(x).at(y - 1) : nullptr); case Direction::WEST: return (0 < x ? &maze.at(x - 1).at(y) : nullptr); } }; std::vector<Tile*> centerTiles; centerTiles.push_back(&maze.at((width - 1) / 2).at((height - 1) / 2)); if (width % 2 == 0) { centerTiles.push_back(&maze.at( width / 2).at((height - 1) / 2)); if (height % 2 == 0) { centerTiles.push_back(&maze.at((width - 1) / 2).at( height / 2)); centerTiles.push_back(&maze.at( width / 2).at( height / 2)); } } else if (height % 2 == 0) { centerTiles.push_back(&maze.at((width - 1) / 2).at( height / 2)); } std::queue<Tile*> discovered; for (Tile* tile : centerTiles) { tile->setDistance(0); discovered.push(tile); } while (!discovered.empty()){ Tile* tile = discovered.front(); discovered.pop(); for (Direction direction : DIRECTIONS) { if (!tile->isWall(direction)) { Tile* neighbor = getNeighbor(tile->getX(), tile->getY(), direction); if (neighbor != nullptr && neighbor->getDistance() == -1) { neighbor->setDistance(tile->getDistance() + 1); discovered.push(neighbor); } } } } return maze; } }
mazeWidth, int mazeHeight) { std::vector<std::vector<BasicTile>> blankMaze; for (int x = 0; x < mazeWidth; x += 1) { std::vector<BasicTile> column; for (int y = 0; y < mazeHeight; y += 1) { BasicTile tile; for (Direction direction : DIRECTIONS) { tile.walls.insert(std::make_pair(direction, false)); } column.push_back(tile); } blankMaze.push_back(column); } return blankMaze; } std::vector<std::vector<BasicTile>> Maze::mirrorAcrossVertical(const std::vector<std::vector<BasicTile>>& basicMaze) { std::vector<std::vector<BasicTile>> mirrored; for (int x = 0; x < basicMaze.size(); x += 1) { std::vector<BasicTile> column; for (int y = 0; y < basicMaze.at(x).size(); y += 1) { BasicTile tile; tile.walls.insert(std::make_pair(Direction::NORTH, basicMaze.at(basicMaze.size() - 1 - x).at(y).walls.at(Direction::NORTH))); tile.walls.insert(std::make_pair(Direction::EAST, basicMaze.at(basicMaze.size() - 1 - x).at(y).walls.at(Direction::WEST))); tile.walls.insert(std::make_pair(Direction::SOUTH, basicMaze.at(basicMaze.size() - 1 - x).at(y).walls.at(Direction::SOUTH))); tile.walls.insert(std::make_pair(Direction::WEST, basicMaze.at(basicMaze.size() - 1 - x).at(y).walls.at(Direction::EAST))); column.push_back(tile); } mirrored.push_back(column); } return mirrored; } std::vector<std::vector<BasicTile>> Maze::rotateCounterClockwise(const std::vector<std::vector<BasicTile>>& basicMaze) { std::vector<std::vector<BasicTile>> rotated; for (int x = 0; x < basicMaze.size(); x += 1) { std::vector<BasicTile> row; for (int y = basicMaze.at(x).size() - 1; y >= 0; y -= 1) { BasicTile tile; int rotatedTileX = basicMaze.at(x).size() - 1 - y; tile.walls.insert(std::make_pair(Direction::NORTH, basicMaze.at(x).at(y).walls.at(Direction::EAST))); tile.walls.insert(std::make_pair(Direction::EAST, basicMaze.at(x).at(y).walls.at(Direction::SOUTH))); tile.walls.insert(std::make_pair(Direction::SOUTH, basicMaze.at(x).at(y).walls.at(Direction::WEST))); tile.walls.insert(std::make_pair(Direction::WEST, basicMaze.at(x).at(y).walls.at(Direction::NORTH))); if (rotated.size() <= rotatedTileX) { rotated.push_back({tile}); } else { rotated.at(rotatedTileX).push_back(tile); }
random
[ { "content": "class Test : public IMouseAlgorithm {\n\n\n\npublic:\n\n std::string mouseFile() const;\n\n std::string interfaceType() const;\n\n void solve(\n\n int mazeWidth, int mazeHeight, bool isOfficialMaze,\n\n char initialDirection, sim::MouseInterface* mouse);\n\n\n\n};\n\n\n\n} // namespace test\n", "file_path": "old/v2/src/mouse/test/Test.h", "rank": 0, "score": 207299.79204602318 }, { "content": "namespace sim {\n\n\n\n// The function returns the directory of the maze file.\n\n// It takes in the name of the executed binary file for location reference.\n\nstd::string getMazeFileDirPath(std::string path);\n\n\n", "file_path": "old/v1/src/sim/MazeFileUtilities.h", "rank": 1, "score": 197254.4902626491 }, { "content": "namespace sim {\n\n\n\nstruct StaticMouseAlgorithmOptions {\n\n std::string mouseFile;\n\n std::string interfaceType;\n\n std::string initialDirection;\n\n int tileTextNumberOfRows;\n\n int tileTextNumberOfCols;\n\n double wheelSpeedFraction;\n\n};\n\n\n", "file_path": "old/v2/src/sim/StaticMouseAlgorithmOptions.h", "rank": 2, "score": 194217.16241555358 }, { "content": "class SettingsMazeFiles {\n\n\n\npublic:\n\n SettingsMazeFiles() = delete;\n\n static QStringList getAllPaths();\n\n static void addPath(QString path);\n\n static void removePath(QString path);\n\n\n\nprivate:\n\n static const QString GROUP;\n\n static const QString KEY_PATH;\n\n\n\n};\n\n\n\n}\n", "file_path": "src/SettingsMazeFiles.h", "rank": 3, "score": 190998.80287260338 }, { "content": " static void setNextDirection(byte cell, byte nextDirection);\n", "file_path": "old/v2/src/mouse/mackAlgoTwo/Maze.h", "rank": 4, "score": 182437.46642865025 }, { "content": " int tileTextNumberOfRows;\n", "file_path": "old/v2/src/sim/StaticMouseAlgorithmOptions.h", "rank": 5, "score": 178281.7747453121 }, { "content": " int tileTextNumberOfCols;\n", "file_path": "old/v2/src/sim/StaticMouseAlgorithmOptions.h", "rank": 6, "score": 178281.7747453121 }, { "content": "class MazeFileUtilities {\n\n\n\npublic:\n\n\n\n MazeFileUtilities() = delete;\n\n\n\n static std::vector<std::vector<BasicTile>> loadMaze(\n\n const std::string& mazeFilePath);\n\n\n\n static bool saveMaze(\n\n const std::vector<std::vector<BasicTile>>& maze,\n\n const std::string& mazeFilePath,\n\n MazeFileType mazeFileType);\n\n\n\nprivate:\n\n\n\n static std::vector<std::vector<BasicTile>> loadMazeFileMapType(\n\n const std::string& mazeFilePath);\n\n static std::vector<std::vector<BasicTile>> loadMazeFileNumType(\n\n const std::string& mazeFilePath);\n", "file_path": "old/v2/src/sim/MazeFileUtilities.h", "rank": 7, "score": 171452.1084535096 }, { "content": "class DiagonalTest : public IMouseAlgorithm {\n\n\n\npublic:\n\n\tbool useTileEdgeMovements() const;\n\n\tvoid justMoveForward(sim::MouseInterface* mouse);\n\n void solve(\n\n int mazeWidth, int mazeHeight, bool isOfficialMaze,\n\n char initialDirection, sim::MouseInterface* mouse);\n\n\n\n};\n\n\n\n} // namespace diagonalTest\n", "file_path": "old/v2/src/mouse/diagonalTest/diagonalTest.h", "rank": 8, "score": 171323.94403645652 }, { "content": "class FontTest : public IMouseAlgorithm {\n\n\n\npublic:\n\n std::string interfaceType() const;\n\n void solve(\n\n int mazeWidth, int mazeHeight, bool isOfficialMaze,\n\n char initialDirection, sim::MouseInterface* mouse);\n\n\n\n};\n\n\n\n} // namespace fontTest\n", "file_path": "old/v2/src/mouse/fontTest/FontTest.h", "rank": 9, "score": 171323.94403645652 }, { "content": "#pragma once\n\n\n\n#include <QString>\n\n#include <QStringList>\n\n\n\nnamespace mms {\n\n\n", "file_path": "src/SettingsMazeFiles.h", "rank": 10, "score": 167380.11107333767 }, { "content": "#include \"SettingsMazeFiles.h\"\n\n\n\n#include \"Settings.h\"\n\n\n\nnamespace mms {\n\n\n\nconst QString SettingsMazeFiles::GROUP = \"maze-files\";\n\nconst QString SettingsMazeFiles::KEY_PATH = \"path\";\n\n\n\nQStringList SettingsMazeFiles::getAllPaths() {\n\n return Settings::get()->values(GROUP, KEY_PATH);\n\n}\n\n\n\nvoid SettingsMazeFiles::addPath(QString path) {\n\n if (Settings::get()->find(GROUP, KEY_PATH, path).isEmpty()) {\n\n Settings::get()->add(GROUP, {{KEY_PATH, path}});\n\n }\n\n}\n\n\n\nvoid SettingsMazeFiles::removePath(QString path) {\n\n Settings::get()->remove(GROUP, KEY_PATH, path);\n\n}\n\n\n\n}\n", "file_path": "src/SettingsMazeFiles.cpp", "rank": 11, "score": 164162.1660145137 }, { "content": "// We have to forward declare the class (as opposed to including it) so as to\n\n// avoid a circular dependency; IMouseAlgorithm.h already includes this file\n\nclass IMouseAlgorithm;\n\n\n\nnamespace sim {\n\n\n", "file_path": "old/v2/src/sim/MouseInterface.h", "rank": 12, "score": 163635.76094982025 }, { "content": "\n\n static bool saveMazeFileMapType(\n\n const std::vector<std::vector<BasicTile>>& maze,\n\n const std::string& mapFilePath);\n\n static bool saveMazeFileNumType(\n\n const std::vector<std::vector<BasicTile>>& maze,\n\n const std::string& mapFilePath);\n\n\n\n};\n\n\n\n} // namespace sim\n", "file_path": "old/v2/src/sim/MazeFileUtilities.h", "rank": 13, "score": 156404.99343868118 }, { "content": "#pragma once\n\n\n\n#include <string>\n\n#include <vector>\n\n\n\n#include \"BasicTile.h\"\n\n#include \"MazeFileType.h\"\n\n\n\nnamespace sim {\n\n\n", "file_path": "old/v2/src/sim/MazeFileUtilities.h", "rank": 14, "score": 156398.46735107823 }, { "content": "class IMouseAlgorithm;\n\n\n\nnamespace sim {\n\n\n", "file_path": "old/v2/src/sim/View.h", "rank": 15, "score": 155454.09676905052 }, { "content": "class IMouseAlgorithm;\n\n\n\nnamespace sim {\n\n\n", "file_path": "old/v2/src/sim/Header.h", "rank": 16, "score": 155454.09676905052 }, { "content": "class Tile{\n\n\n\npublic:\n\n Tile();\n\n ~Tile();\n\n\n\n int getX();\n\n int getY();\n\n int getDistance();\n\n int getPasses();\n\n bool getExplored(); \n\n bool getPosp(); \n\n bool isWall(int direction);\n\n std::vector<Tile*> getNeighbors();\n\n\n\n void setPos(int x, int y);\n\n void setDistance(int distance);\n\n void incrementPasses();\n\n void resetPasses();\n\n void setExplored(bool explored);\n", "file_path": "old/v1/src/sim/Tile.h", "rank": 17, "score": 153873.9567132743 }, { "content": "class Tile{\n\n\n\npublic:\n\n Tile();\n\n\n\n int getX() const;\n\n int getY() const;\n\n void setPos(int x, int y);\n\n\n\n bool isWall(Direction direction) const;\n\n void setWall(Direction direction, bool isWall);\n\n\n\n int getDistance() const;\n\n void setDistance(int distance);\n\n\n\n Polygon getFullPolygon() const;\n\n Polygon getInteriorPolygon() const;\n\n Polygon getWallPolygon(Direction direction) const;\n\n std::vector<Polygon> getCornerPolygons() const;\n\n\n", "file_path": "old/v2/src/sim/Tile.h", "rank": 18, "score": 153873.9567132743 }, { "content": " }\n\n\n\n // Always append the current tile to the current column\n\n column.push_back(tile);\n\n }\n\n\n\n // Make sure to append the last column\n\n maze.push_back(column);\n\n\n\n return maze;\n\n}\n\n\n\nbool MazeFileUtilities::saveMazeFileMapType(\n\n const std::vector<std::vector<BasicTile>>& maze,\n\n const std::string& mazeFilePath) {\n\n\n\n // The characters to use in the file\n\n char post = '+';\n\n char space = ' ';\n\n char vertical = '|';\n", "file_path": "old/v2/src/sim/MazeFileUtilities.cpp", "rank": 19, "score": 153545.44175818982 }, { "content": "#include \"MazeFileUtilities.h\"\n\n\n\n#include <fstream>\n\n#include <iostream> // TODO: MACK - remove this\n\n\n\n#include \"SimUtilities.h\"\n\n\n\nnamespace sim {\n\n\n\nstd::vector<std::vector<BasicTile>> MazeFileUtilities::loadMaze(\n\n const std::string& mazeFilePath) {\n\n\n\n // Since we don't know anything about the file type ahead of time, we\n\n // simply brute force try each of the file types until either one succeeds\n\n // or they all fail\n\n\n\n #define TRY(statement)\\\n\n try {\\\n\n statement;\\\n\n }\\\n", "file_path": "old/v2/src/sim/MazeFileUtilities.cpp", "rank": 20, "score": 153544.36485053317 }, { "content": " catch (...) { }\n\n\n\n // NUM is a little stricter, so we try that first\n\n TRY(return loadMazeFileNumType(mazeFilePath));\n\n TRY(return loadMazeFileMapType(mazeFilePath));\n\n throw std::exception();\n\n}\n\n\n\nbool MazeFileUtilities::saveMaze(\n\n const std::vector<std::vector<BasicTile>>& maze,\n\n const std::string& mazeFilePath,\n\n MazeFileType mazeFileType) {\n\n switch (mazeFileType) {\n\n case MazeFileType::MAP:\n\n return saveMazeFileMapType(maze, mazeFilePath);\n\n case MazeFileType::NUM:\n\n return saveMazeFileNumType(maze, mazeFilePath);\n\n }\n\n}\n\n\n", "file_path": "old/v2/src/sim/MazeFileUtilities.cpp", "rank": 21, "score": 153541.82404746147 }, { "content": "#include \"MazeFileUtilities.h\"\n\n\n\n#include <fstream>\n\n#include <iostream>\n\n#include <iterator>\n\n#include <sstream>\n\n#include <vector>\n\n\n\nnamespace sim{\n\n\n\n// Initially, path is a path to the binary file that is executed\n\nstd::string getMazeFileDirPath(std::string path){\n\n \n\n // Ensure that the path begins with a relative directory location\n\n if (path.at(0) != '.' && path.at(0) != '/'){\n\n path.insert(0, \"./\");\n\n }\n\n \n\n // Gets the path to the \"mms\" dir based on where the bin file was executed\n\n for (int i = 0; i < 2; i += 1){\n", "file_path": "old/v1/src/sim/MazeFileUtilities.cpp", "rank": 22, "score": 153541.5814383344 }, { "content": " // Write to the file\n\n for (std::string line : rightSideUpLines) {\n\n file << line << std::endl;\n\n }\n\n\n\n // Make sure to close the file\n\n file.close();\n\n\n\n // Return success\n\n return true;\n\n}\n\n\n\nbool MazeFileUtilities::saveMazeFileNumType(\n\n const std::vector<std::vector<BasicTile>>& maze,\n\n const std::string& mazeFilePath) {\n\n\n\n // Create the stream\n\n std::ofstream file(mazeFilePath.c_str());\n\n\n\n // Make sure the file is open\n", "file_path": "old/v2/src/sim/MazeFileUtilities.cpp", "rank": 23, "score": 153540.62243987835 }, { "content": " file.close();\n\n\n\n // Iterate over all of the lines\n\n for (std::string line : lines) {\n\n\n\n // Put the tokens in a vector\n\n std::vector<std::string> tokens = SimUtilities::tokenize(line, ' ', true, false);\n\n\n\n // Fill the BasicTile object with the values\n\n BasicTile tile;\n\n for (Direction direction : DIRECTIONS) {\n\n tile.walls.insert(std::make_pair(direction,\n\n (1 == SimUtilities::strToInt(tokens.at(2 + SimUtilities::getDirectionIndex(direction))))\n\n ));\n\n }\n\n\n\n // If the tile belongs to a new column, append the current column and then empty it\n\n if (maze.size() < SimUtilities::strToInt(tokens.at(0))) {\n\n maze.push_back(column);\n\n column.clear();\n", "file_path": "old/v2/src/sim/MazeFileUtilities.cpp", "rank": 24, "score": 153538.2797107326 }, { "content": " if (!file.is_open()) {\n\n return false;\n\n }\n\n\n\n // Write to the file\n\n for (int x = 0; x < maze.size(); x += 1) {\n\n for (int y = 0; y < maze.at(x).size(); y += 1) {\n\n file << x << \" \" << y;\n\n for (Direction direction : DIRECTIONS) {\n\n file << \" \" << (maze.at(x).at(y).walls.at(direction) ? 1 : 0);\n\n }\n\n file << std::endl;\n\n }\n\n }\n\n\n\n // Make sure to close the file\n\n file.close();\n\n\n\n // Return success\n\n return true;\n\n}\n\n\n\n} //namespace sim\n", "file_path": "old/v2/src/sim/MazeFileUtilities.cpp", "rank": 25, "score": 153535.70685480328 }, { "content": "\n\n return rightSideUpMaze;\n\n}\n\n\n\nstd::vector<std::vector<BasicTile>> MazeFileUtilities::loadMazeFileNumType(\n\n const std::string& mazeFilePath) {\n\n\n\n // The maze to be returned\n\n std::vector<std::vector<BasicTile>> maze;\n\n\n\n // The column to be appended\n\n std::vector<BasicTile> column;\n\n\n\n // First, read the entirety of the file\n\n std::vector<std::string> lines;\n\n std::ifstream file(mazeFilePath.c_str());\n\n std::string line(\"\");\n\n while (getline(file, line)) {\n\n lines.push_back(line);\n\n }\n", "file_path": "old/v2/src/sim/MazeFileUtilities.cpp", "rank": 26, "score": 153532.68393834613 }, { "content": " position += (spaces.at(j + 1) + 1) / 2; // Center of the wall\n\n }\n\n }\n\n }\n\n\n\n // Extract vertical wall info, tiles structs already exist\n\n else if (0 < lines.at(i - 1).size() && lines.at(i - 1).at(0) == delimiter) {\n\n int position = 0;\n\n for (int j = 0; j <= spaces.size(); j += 1) {\n\n if (line.size() <= position) {\n\n break;\n\n }\n\n bool isWall = line.at(position) != ' ';\n\n if (0 < position) {\n\n upsideDownMaze.at(j - 1).at(rowsFromTopOfMaze).walls.at(Direction::EAST) = isWall;\n\n }\n\n if (position < line.size() - 1) {\n\n upsideDownMaze.at(j).at(rowsFromTopOfMaze).walls.at(Direction::WEST) = isWall;\n\n }\n\n if (j < spaces.size()) {\n", "file_path": "old/v2/src/sim/MazeFileUtilities.cpp", "rank": 27, "score": 153531.44903274273 }, { "content": "std::vector<std::vector<BasicTile>> MazeFileUtilities::loadMazeFileMapType(\n\n const std::string& mazeFilePath) {\n\n\n\n // First, read all of the non-empty lines\n\n std::vector<std::string> lines;\n\n std::ifstream file(mazeFilePath.c_str());\n\n std::string line(\"\");\n\n while (getline(file, line)) {\n\n if (0 < SimUtilities::trim(line).size()) {\n\n lines.push_back(line);\n\n }\n\n }\n\n file.close();\n\n\n\n // The maze to be returned\n\n std::vector<std::vector<BasicTile>> upsideDownMaze;\n\n\n\n // The character representing a maze post\n\n char delimiter = '\\0';\n\n\n", "file_path": "old/v2/src/sim/MazeFileUtilities.cpp", "rank": 28, "score": 153529.9127997996 }, { "content": "\n\n // Extract horizontal wall info, tiles structs don't already exist\n\n if (0 < line.size() && line.at(0) == delimiter) {\n\n rowsFromTopOfMaze += 1;\n\n int position = (spaces.at(0) + 1) / 2; // Center of the wall\n\n for (int j = 0; j < spaces.size(); j += 1) {\n\n BasicTile tile;\n\n for (Direction direction : DIRECTIONS) {\n\n tile.walls.insert(std::make_pair(direction, false));\n\n }\n\n upsideDownMaze.at(j).push_back(tile);\n\n if (0 < spaces.at(j)) {\n\n bool isWall = line.at(position) != ' ';\n\n upsideDownMaze.at(j).at(rowsFromTopOfMaze).walls.at(Direction::NORTH) = isWall;\n\n if (0 < rowsFromTopOfMaze) {\n\n upsideDownMaze.at(j).at(rowsFromTopOfMaze - 1).walls.at(Direction::SOUTH) = isWall;\n\n }\n\n }\n\n if (j < spaces.size() - 1) {\n\n position += 1 + spaces.at(j) / 2; // Position of the next corner\n", "file_path": "old/v2/src/sim/MazeFileUtilities.cpp", "rank": 29, "score": 153529.8295828265 }, { "content": " // The number of horizontal spaces between columns\n\n std::vector<int> spaces;\n\n\n\n // Keep track of what row of the maze we're reading\n\n int rowsFromTopOfMaze = -1;\n\n\n\n // Iterate over all of the lines\n\n for (int i = 0; i < lines.size(); i += 1) {\n\n std::string line = lines.at(i);\n\n\n\n // Special case for the first line of the file\n\n if (i == 0) {\n\n delimiter = line.at(0);\n\n std::vector<std::string> tokens = SimUtilities::tokenize(line, delimiter, false, false);\n\n for (int j = 0; j < tokens.size(); j += 1) {\n\n std::vector<BasicTile> column;\n\n upsideDownMaze.push_back(column);\n\n spaces.push_back(tokens.at(j).size());\n\n }\n\n }\n", "file_path": "old/v2/src/sim/MazeFileUtilities.cpp", "rank": 30, "score": 153529.28237980165 }, { "content": " position += spaces.at(j) + 1;\n\n }\n\n }\n\n }\n\n }\n\n\n\n // Strip off of the last extraneous row\n\n for (int i = 0; i < upsideDownMaze.size(); i += 1) {\n\n upsideDownMaze.at(i).pop_back();\n\n }\n\n\n\n // Flip the maze so that it's right side up\n\n std::vector<std::vector<BasicTile>> rightSideUpMaze;\n\n for (int i = 0; i < upsideDownMaze.size(); i += 1) {\n\n std::vector<BasicTile> column;\n\n for (int j = upsideDownMaze.at(i).size() - 1; j >= 0; j -= 1) {\n\n column.push_back(upsideDownMaze.at(i).at(j));\n\n }\n\n rightSideUpMaze.push_back(column);\n\n }\n", "file_path": "old/v2/src/sim/MazeFileUtilities.cpp", "rank": 31, "score": 153528.7058188745 }, { "content": " if (maze.at(i).at(j).walls.at(Direction::WEST)) {\n\n upsideDownLines.at(down + 1).at(left) = vertical;\n\n }\n\n }\n\n }\n\n\n\n // Flip the lines so that they're right side up\n\n std::vector<std::string> rightSideUpLines;\n\n for (int i = upsideDownLines.size() - 1; i >= 0; i -= 1) {\n\n rightSideUpLines.push_back(upsideDownLines.at(i));\n\n }\n\n\n\n // Create the stream\n\n std::ofstream file(mazeFilePath.c_str());\n\n\n\n // Make sure the file is open\n\n if (!file.is_open()) {\n\n return false;\n\n }\n\n\n", "file_path": "old/v2/src/sim/MazeFileUtilities.cpp", "rank": 32, "score": 153524.56901445205 }, { "content": " int down = 2 * j;\n\n upsideDownLines.at(down).at(left) = post;\n\n upsideDownLines.at(down).at(right) = post;\n\n upsideDownLines.at(up).at(left) = post;\n\n upsideDownLines.at(up).at(right) = post;\n\n\n\n // Insert walls if they exist\n\n if (maze.at(i).at(j).walls.at(Direction::NORTH)) {\n\n for (int k = 0; k < 3; k += 1) {\n\n upsideDownLines.at(up).at(left + 1 + k) = horizontal;\n\n }\n\n }\n\n if (maze.at(i).at(j).walls.at(Direction::SOUTH)) {\n\n for (int k = 0; k < 3; k += 1) {\n\n upsideDownLines.at(down).at(left + 1 + k) = horizontal;\n\n }\n\n }\n\n if (maze.at(i).at(j).walls.at(Direction::EAST)) {\n\n upsideDownLines.at(down + 1).at(right) = vertical;\n\n }\n", "file_path": "old/v2/src/sim/MazeFileUtilities.cpp", "rank": 33, "score": 153524.46815800283 }, { "content": "\n\n int index = path.find_last_of(\"/\\\\\");\n\n path = path.substr(0, index);\n\n\n\n // Ensures that the maze can be loaded from all directories (end cases)\n\n if (i == 0 && (path == \"..\" || path == \".\")){\n\n // If the bin path is to the current or parent directory, then the\n\n // mms path must be the parent directory of directory to which we\n\n // already have a path\n\n path += \"/..\";\n\n break;\n\n }\n\n }\n\n\n\n // Append mazeFile directory path from the root of the project\n\n path += \"/src/mazeFiles/\";\n\n\n\n return path;\n\n}\n\n\n\n} // namespace sim\n", "file_path": "old/v1/src/sim/MazeFileUtilities.cpp", "rank": 34, "score": 153522.4978201167 }, { "content": " char horizontal = '-';\n\n\n\n // A blank line, and a list of all lines to be written\n\n std::string blankLine(4 * maze.size() + 1, space);\n\n std::vector<std::string> upsideDownLines {blankLine};\n\n\n\n // For all tiles in the maze\n\n for (int i = 0; i < maze.size(); i += 1) {\n\n for (int j = 0; j < maze.at(i).size(); j += 1) {\n\n\n\n // Insert more lines if necessary\n\n if (upsideDownLines.size() <= 2 * j + 1) {\n\n upsideDownLines.push_back(blankLine);\n\n upsideDownLines.push_back(blankLine);\n\n }\n\n\n\n // Insert posts at the boundaries\n\n int left = 4 * i;\n\n int right = 4 * (i + 1);\n\n int up = 2 * (j + 1);\n", "file_path": "old/v2/src/sim/MazeFileUtilities.cpp", "rank": 35, "score": 153519.017195689 }, { "content": "class Maze {\n\n\n\npublic:\n\n Maze(int width, int height, std::string mazeFileDirPath = \"\", std::string mazeFile = \"\");\n\n ~Maze();\n\n\n\n int getWidth();\n\n int getHeight();\n\n Tile* getTile(int x, int y);\n\n void resetColors(int curX, int curY); // Resets the colors of the maze\n\n\n\nprivate:\n\n // Vector to hold all of the tiles\n\n std::vector<std::vector<Tile>> m_maze;\n\n \n\n // -------------------- Maze generation utilities -----------------------//\n\n\n\n // Randomly generate a maze\n\n void randomize();\n\n void tom_random();\n", "file_path": "old/v1/src/sim/Maze.h", "rank": 36, "score": 153495.88610668463 }, { "content": "class Maze {\n\n\n\npublic:\n\n Maze();\n\n int getWidth() const;\n\n int getHeight() const;\n\n bool withinMaze(int x, int y) const;\n\n Tile* getTile(int x, int y);\n\n const Tile* getTile(int x, int y) const;\n\n bool isValidMaze() const;\n\n bool isOfficialMaze() const;\n\n bool isCenterTile(int x, int y) const;\n\n\n\nprivate:\n\n // Vector to hold all of the tiles\n\n std::vector<std::vector<Tile>> m_maze;\n\n\n\n // Used for memoizing MazeChecker functions\n\n bool m_isValidMaze;\n\n bool m_isOfficialMaze;\n", "file_path": "old/v2/src/sim/Maze.h", "rank": 37, "score": 153495.88610668463 }, { "content": "namespace sim {\n\n\n\nstruct BasicTile {\n\n std::map<Direction, bool> walls;\n\n};\n\n\n", "file_path": "old/v2/src/sim/BasicTile.h", "rank": 38, "score": 150665.0764053481 }, { "content": " std::string initialDirection;\n", "file_path": "old/v2/src/sim/StaticMouseAlgorithmOptions.h", "rank": 39, "score": 142223.8581350781 }, { "content": " static byte getX(byte cell);\n", "file_path": "old/v2/src/mouse/mackAlgoTwo/Maze.h", "rank": 40, "score": 138730.24947768965 }, { "content": " static void setDiscovered(byte cell, bool discovered);\n", "file_path": "old/v2/src/mouse/mackAlgoTwo/Maze.h", "rank": 41, "score": 138657.1886022912 }, { "content": " static void setDistance(byte cell, twobyte distance);\n", "file_path": "old/v2/src/mouse/mackAlgoTwo/Maze.h", "rank": 42, "score": 138657.1886022912 }, { "content": " static void setWall(byte cell, byte direction, bool isWall);\n", "file_path": "old/v2/src/mouse/mackAlgoTwo/Maze.h", "rank": 43, "score": 138657.1886022912 }, { "content": " static byte getNextDirection(byte cell);\n", "file_path": "old/v2/src/mouse/mackAlgoTwo/Maze.h", "rank": 44, "score": 136458.0215820776 }, { "content": " double wheelSpeedFraction;\n", "file_path": "old/v2/src/sim/StaticMouseAlgorithmOptions.h", "rank": 45, "score": 135314.1459609125 }, { "content": " static void setStraightAwayLength(byte cell, byte straightAwayLength);\n", "file_path": "old/v2/src/mouse/mackAlgoTwo/Maze.h", "rank": 46, "score": 134237.80384664686 }, { "content": "/// @brief Format flags used to determine specifiers that are active for performance improvements.\n\nenum class FormatFlags : base::type::EnumType {\n\n DateTime = 1<<1, LoggerId = 1<<2, File = 1<<3, Line = 1<<4, Location = 1<<5, Function = 1<<6,\n\n User = 1<<7, Host = 1<<8, LogMessage = 1<<9, VerboseLevel = 1<<10, AppName = 1<<11, ThreadId = 1<<12,\n\n Level = 1<<13, FileBase = 1<<14, LevelShort = 1<<15\n\n};\n", "file_path": "old/v2/src/lib/easyloggingpp/easylogging++.h", "rank": 47, "score": 132482.55244512143 }, { "content": "class IMazeAlgorithm {\n\n\n\npublic:\n\n virtual void generate(int mazeWidth, int mazeHeight, sim::MazeInterface* maze) = 0;\n\n\n\n};\n", "file_path": "old/v2/src/maze/IMazeAlgorithm.h", "rank": 48, "score": 130570.64850437996 }, { "content": "class MazeAlgorithms {\n\n \n\npublic:\n\n // The MazeAlgorithms class is not constructible\n\n MazeAlgorithms() = delete;\n\n\n\n static bool isMazeAlgorithm(const std::string& str);\n\n static IMazeAlgorithm* getMazeAlgorithm(const std::string& str);\n\n\n\nprivate:\n\n static std::pair<bool, IMazeAlgorithm*> helper(const std::string& str, bool justChecking);\n\n\n\n};\n", "file_path": "old/v2/src/maze/MazeAlgorithms.h", "rank": 49, "score": 130570.64850437996 }, { "content": "class MouseAlgorithms {\n\n \n\npublic:\n\n // The MouseAlgorithms class is not constructible\n\n MouseAlgorithms() = delete;\n\n\n\n static bool isMouseAlgorithm(const std::string& str);\n\n static IMouseAlgorithm* getMouseAlgorithm(const std::string& str);\n\n\n\nprivate:\n\n static std::pair<bool, IMouseAlgorithm*> helper(const std::string& str, bool justChecking);\n\n\n\n};\n", "file_path": "old/v2/src/mouse/MouseAlgorithms.h", "rank": 50, "score": 129476.76370379566 }, { "content": "class IMouseAlgorithm {\n\n\n\npublic:\n\n\n\n // Static options for both interfaces\n\n virtual std::string mouseFile() const;\n\n virtual std::string interfaceType() const;\n\n virtual std::string initialDirection() const;\n\n virtual int tileTextNumberOfRows() const;\n\n virtual int tileTextNumberOfCols() const;\n\n\n\n // Dynamic options for both interface types\n\n virtual bool allowOmniscience() const;\n\n virtual bool automaticallyClearFog() const;\n\n virtual bool declareBothWallHalves() const;\n\n virtual bool setTileTextWhenDistanceDeclared() const;\n\n virtual bool setTileBaseColorWhenDistanceDeclaredCorrectly() const;\n\n\n\n // Static options for the DISCRETE interface\n\n virtual double wheelSpeedFraction() const;\n", "file_path": "old/v2/src/mouse/IMouseAlgorithm.h", "rank": 51, "score": 129476.76370379566 }, { "content": "class Coordinate { // Synonymous to vector\n\n\n\npublic:\n\n virtual ~Coordinate() = 0;\n\n Meters getX() const;\n\n Meters getY() const;\n\n Meters getRho() const;\n\n Radians getTheta() const;\n\n bool operator==(const Coordinate& coordinate) const;\n\n bool operator!=(const Coordinate& coordinate) const;\n\n bool operator<(const Coordinate& coordinate) const;\n\n\n\nprotected:\n\n Coordinate();\n\n Meters m_x;\n\n Meters m_y;\n\n\n\n};\n\n\n\n} // namespace sim\n", "file_path": "old/v2/src/sim/units/Coordinate.h", "rank": 52, "score": 127632.73609257978 }, { "content": "class SettingsMouseAlgos {\n\n\n\npublic:\n\n\n\n SettingsMouseAlgos() = delete;\n\n\n\n static QStringList names();\n\n static QString getDirectory(const QString& name);\n\n static QString getBuildCommand(const QString& name);\n\n static QString getRunCommand(const QString& name);\n\n\n\n static void add(\n\n const QString& name,\n\n const QString& directory,\n\n const QString& buildCommand,\n\n const QString& runCommand);\n\n static void update(\n\n const QString& name,\n\n const QString& newName,\n\n const QString& newDirectory,\n", "file_path": "src/SettingsMouseAlgos.h", "rank": 53, "score": 126115.96868683203 }, { "content": "#pragma once\n\n\n\n#include \"IMazeAlgorithm.h\"\n\n\n", "file_path": "old/v2/src/maze/MazeAlgorithms.h", "rank": 54, "score": 117817.04057994946 }, { "content": "#pragma once\n\n\n\n#include \"../sim/MazeInterface.h\"\n\n\n", "file_path": "old/v2/src/maze/IMazeAlgorithm.h", "rank": 55, "score": 117816.8213551585 }, { "content": "#pragma once\n\n\n\n#include \"../IMouseAlgorithm.h\"\n\n\n\nnamespace test {\n\n\n", "file_path": "old/v2/src/mouse/test/Test.h", "rank": 56, "score": 117149.73232493845 }, { "content": "\n\n // Dynamic options for the DISCRETE interface\n\n virtual bool declareWallOnRead() const;\n\n virtual bool useTileEdgeMovements() const;\n\n\n\n // Necessary to all algorithms\n\n virtual void solve(\n\n int mazeWidth, int mazeHeight, bool isOfficialMaze,\n\n char initialDirection, sim::MouseInterface* mouse) = 0;\n\n\n\n};\n", "file_path": "old/v2/src/mouse/IMouseAlgorithm.h", "rank": 57, "score": 116812.79759426297 }, { "content": "#pragma once\n\n\n\n#include \"IMouseAlgorithm.h\"\n\n\n", "file_path": "old/v2/src/mouse/MouseAlgorithms.h", "rank": 58, "score": 116779.36026938011 }, { "content": "#pragma once\n\n\n\n#include \"../sim/MouseInterface.h\"\n\n\n", "file_path": "old/v2/src/mouse/IMouseAlgorithm.h", "rank": 59, "score": 116779.14112424906 }, { "content": "#include \"MazeAlgorithms.h\"\n\n\n\n#include \"../sim/Assert.h\"\n\n\n\n#include \"randomize/Randomize.h\"\n\n#include \"tomasz/TomaszMazeGenerator.h\"\n\n\n\nbool MazeAlgorithms::isMazeAlgorithm(const std::string& str) {\n\n return helper(str, true).first;\n\n}\n\n\n\nIMazeAlgorithm* MazeAlgorithms::getMazeAlgorithm(const std::string& str) {\n\n SIM_ASSERT_TR(isMazeAlgorithm(str));\n\n return helper(str, false).second;\n\n}\n\n\n\nstd::pair<bool, IMazeAlgorithm*> MazeAlgorithms::helper(const std::string& str, bool justChecking) {\n\n\n\n #define ALGO(NAME, INSTANCE)\\\n\n if (str == NAME) {\\\n\n return std::make_pair(true, justChecking ? nullptr : INSTANCE);\\\n\n }\n\n\n\n ALGO(\"Randomize\", new randomize::Randomize());\n\n ALGO(\"Tomasz\", new tomasz::TomaszMazeGenerator());\n\n\n\n return std::make_pair(false, nullptr);\n\n}\n", "file_path": "old/v2/src/maze/MazeAlgorithms.cpp", "rank": 60, "score": 116108.59815662321 }, { "content": "}\n\n\n\nstd::string Test::interfaceType() const {\n\n return \"CONTINUOUS\";\n\n}\n\n\n\nvoid Test::solve(\n\n int mazeWidth, int mazeHeight, bool isOfficialMaze,\n\n char initialDirection, sim::MouseInterface* mouse) {\n\n // This causes translation\n\n mouse->setWheelSpeed(\"upper-left\", -50);\n\n mouse->setWheelSpeed(\"upper-right\", -50);\n\n mouse->setWheelSpeed(\"bottom\", 100);\n\n while (true) {\n\n mouse->delay(100);\n\n }\n\n}\n\n\n\n} // namespace test\n", "file_path": "old/v2/src/mouse/test/Test.cpp", "rank": 61, "score": 115476.83570579895 }, { "content": "#include \"Test.h\"\n\n\n\n#include <iostream>\n\n#ifdef _WIN32\n\n# include <Windows.h>\n\n# define _USE_MATH_DEFINES\n\n# undef max\n\n# undef min\n\n#\tinclude <Windows.h>\n\n#endif\n\n#include <iostream>\n\n#include <cmath>\n\n#include <ctime>\n\n#undef M_PI\n\n#define M_PI 3.14159265358979323846\n\n\n\nnamespace test {\n\n\n\nstd::string Test::mouseFile() const {\n\n return \"omniMouse.xml\";\n", "file_path": "old/v2/src/mouse/test/Test.cpp", "rank": 62, "score": 115445.49572350693 }, { "content": "#include \"IMouseAlgorithm.h\"\n\n\n\nstd::string IMouseAlgorithm::mouseFile() const {\n\n return \"default.xml\";\n\n}\n\n\n\nstd::string IMouseAlgorithm::interfaceType() const {\n\n return \"DISCRETE\";\n\n}\n\n\n\nstd::string IMouseAlgorithm::initialDirection() const {\n\n return \"NORTH\";\n\n}\n\n\n\nint IMouseAlgorithm::tileTextNumberOfRows() const {\n\n return 2;\n\n}\n\n\n\nint IMouseAlgorithm::tileTextNumberOfCols() const {\n\n return 3;\n", "file_path": "old/v2/src/mouse/IMouseAlgorithm.cpp", "rank": 63, "score": 115100.47324617834 }, { "content": "class Mouse{\n\n\n\npublic:\n\n Mouse(Maze* maze);\n\n ~Mouse();\n\n\n\n // Accessor methods\n\n int getX();\n\n int getY();\n\n int getDirection();\n\n bool inGoal();\n\n\n\n // Action methods\n\n bool wallFront();\n\n bool wallRight();\n\n bool wallLeft();\n\n void moveForward();\n\n void turnRight();\n\n void turnLeft();\n\n void resetPosition(); // Sets the position of the mouse to (0,0)\n", "file_path": "old/v1/src/sim/Mouse.h", "rank": 64, "score": 115100.06866376764 }, { "content": "class Mouse {\n\n\n\npublic:\n\n Mouse(const Maze* maze);\n\n\n\n // Initializes the mouse (body, wheels, sensors, etc.); returns true if successful, false if not\n\n bool initialize(\n\n const std::string& mouseFile,\n\n Direction initialDirection);\n\n\n\n // Gets the initial translation and rotation of the mouse\n\n Cartesian getInitialTranslation() const;\n\n Radians getInitialRotation() const;\n\n\n\n // Gets the current translation and rotation of the mouse\n\n Cartesian getCurrentTranslation() const;\n\n Radians getCurrentRotation() const;\n\n\n\n // Gets the current discretized translation and rotation of the mouse\n\n std::pair<int, int> getCurrentDiscretizedTranslation() const;\n", "file_path": "old/v2/src/sim/Mouse.h", "rank": 65, "score": 115100.06866376764 }, { "content": "}\n\n\n\nbool IMouseAlgorithm::allowOmniscience() const {\n\n return false;\n\n}\n\n\n\nbool IMouseAlgorithm::automaticallyClearFog() const {\n\n return true;\n\n}\n\n\n\nbool IMouseAlgorithm::declareBothWallHalves() const {\n\n return false;\n\n}\n\n\n\nbool IMouseAlgorithm::setTileTextWhenDistanceDeclared() const {\n\n return true;\n\n}\n\n\n\nbool IMouseAlgorithm::setTileBaseColorWhenDistanceDeclaredCorrectly() const {\n\n return false;\n", "file_path": "old/v2/src/mouse/IMouseAlgorithm.cpp", "rank": 66, "score": 115084.47375931902 }, { "content": "#include \"MouseAlgorithms.h\"\n\n\n\n#include \"../sim/Assert.h\"\n\n\n\n#include \"continuous/Continuous.h\"\n\n#include \"doNothing/DoNothing.h\"\n\n#include \"floodFill/FloodFill.h\"\n\n#include \"fontTest/FontTest.h\"\n\n#include \"forward/Forward.h\"\n\n#include \"leftWallFollow/LeftWallFollow.h\"\n\n#include \"mackAlgo/MackAlgo.h\"\n\n#include \"mackAlgoTwo/MackAlgoTwo.h\"\n\n#include \"manual/Manual.h\"\n\n#include \"randomizedWallFollow/RandomizedWallFollow.h\"\n\n#include \"rightWallFollow/RightWallFollow.h\"\n\n#include \"test/Test.h\"\n\n\n\nbool MouseAlgorithms::isMouseAlgorithm(const std::string& str) {\n\n return helper(str, true).first;\n\n}\n", "file_path": "old/v2/src/mouse/MouseAlgorithms.cpp", "rank": 67, "score": 115084.47399624731 }, { "content": "}\n\n\n\ndouble IMouseAlgorithm::wheelSpeedFraction() const {\n\n return 1.0; \n\n}\n\n\n\nbool IMouseAlgorithm::declareWallOnRead() const {\n\n return false;\n\n}\n\n\n\nbool IMouseAlgorithm::useTileEdgeMovements() const {\n\n return false;\n\n}\n", "file_path": "old/v2/src/mouse/IMouseAlgorithm.cpp", "rank": 68, "score": 115077.4502122131 }, { "content": "\n\nIMouseAlgorithm* MouseAlgorithms::getMouseAlgorithm(const std::string& str) {\n\n SIM_ASSERT_TR(isMouseAlgorithm(str));\n\n return helper(str, false).second;\n\n}\n\n\n\nstd::pair<bool, IMouseAlgorithm*> MouseAlgorithms::helper(const std::string& str, bool justChecking) {\n\n\n\n #define ALGO(NAME, INSTANCE)\\\n\n if (str == NAME) {\\\n\n return std::make_pair(true, justChecking ? nullptr : INSTANCE);\\\n\n }\n\n\n\n ALGO(\"Continuous\", new continuous::Continuous());\n\n ALGO(\"DoNothing\", new doNothing::DoNothing());\n\n ALGO(\"FloodFill\", new floodFill::FloodFill());\n\n ALGO(\"FontTest\", new fontTest::FontTest());\n\n ALGO(\"Forward\", new forward::Forward());\n\n ALGO(\"LeftWallFollow\", new leftWallFollow::LeftWallFollow());\n\n ALGO(\"MackAlgo\", new mackAlgo::MackAlgo());\n\n ALGO(\"MackAlgoTwo\", new mackAlgoTwo::MackAlgoTwo());\n\n ALGO(\"Manual\", new manual::Manual());\n\n ALGO(\"RandomizedWallFollow\", new randomizedWallFollow::RandomizedWallFollow());\n\n ALGO(\"RightWallFollow\", new rightWallFollow::RightWallFollow());\n\n ALGO(\"Test\", new test::Test());\n\n\n\n return std::make_pair(false, nullptr);\n\n}\n", "file_path": "old/v2/src/mouse/MouseAlgorithms.cpp", "rank": 69, "score": 115077.06796030236 }, { "content": "// A class that generates a realistic maze at random\n\nclass TomaszMazeGenerator : public IMazeAlgorithm {\n\n\n\npublic:\n\n\n\n void generate(int mazeWidth, int mazeHeight, sim::MazeInterface* maze);\n\n\n\n // TODO: probably rename this...\n\n void convertToBasicMaze(sim::MazeInterface* maze);\n\n \n\nprivate:\n\n\n\n // Tomasz Maze Generator Parameters\n\n // Number between 0-1 which determines how straight the maze becomes closer to edges\n\n double tomStraightFactor = 0.85;\n\n // Number between 0-1 which determines if the algorithm will break down a wall at a dead end\n\n double tomDeadEndBreakChance = 0.75;\n\n // The minimum distance between cells to break down a dead end wall. > 5\n\n int tomDeadEndBreakThreshold = 8;\n\n // Number of walls to break down in finalized maze\n\n int tomGradientWallBreaks = 3;\n", "file_path": "old/v2/src/maze/tomasz/TomaszMazeGenerator.h", "rank": 70, "score": 114401.50312241404 }, { "content": "#pragma once\n\n\n\n#include \"../IMouseAlgorithm.h\"\n\n\n\nnamespace fontTest {\n\n\n", "file_path": "old/v2/src/mouse/fontTest/FontTest.h", "rank": 71, "score": 113794.71624177461 }, { "content": "#pragma once\n\n\n\n#include \"../IMouseAlgorithm.h\"\n\n\n\nnamespace diagonalTest {\n\n\n", "file_path": "old/v2/src/mouse/diagonalTest/diagonalTest.h", "rank": 72, "score": 113794.71624177461 }, { "content": "class TileGraphic {\n\n\n\npublic:\n\n\n\n TileGraphic(const Tile* tile, BufferInterface* bufferInterface);\n\n\n\n bool wallDeclared(Direction direction) const;\n\n\n\n void setColor(const Color color);\n\n void declareWall(Direction direction, bool isWall);\n\n void undeclareWall(Direction direction);\n\n void setFogginess(bool foggy);\n\n void setText(const std::vector<std::string>& rowsOfText);\n\n\n\n void draw() const;\n\n void updateColor() const;\n\n void updateWalls() const;\n\n void updateFog() const;\n\n void updateText() const;\n\n \n", "file_path": "old/v2/src/sim/TileGraphic.h", "rank": 73, "score": 113179.91308504979 }, { "content": "class TileGraphic {\n\n\n\npublic:\n\n TileGraphic(Tile* tile);\n\n ~TileGraphic();\n\n void draw();\n\n\n\nprivate:\n\n Tile* m_tile;\n\n GLfloat* m_color;\n\n void drawRect(float c1X, float c1Y, float c2X, float c2Y, GLfloat* color);\n\n void drawCorners(float c1X, float c1Y, float c2X, float c2Y);\n\n void drawWalls(float c1X, float c1Y, float c2X, float c2Y);\n\n};\n\n\n\n} // namespace sim\n", "file_path": "old/v1/src/sim/TileGraphic.h", "rank": 74, "score": 113179.91308504979 }, { "content": "class MazeGraphic {\n\n\n\npublic:\n\n MazeGraphic(const Maze* maze, BufferInterface* bufferInterface);\n\n\n\n void setTileColor(int x, int y, Color color);\n\n void declareWall(int x, int y, Direction direction, bool isWall);\n\n void undeclareWall(int x, int y, Direction direction);\n\n void setTileFogginess(int x, int y, bool foggy);\n\n void setTileText(int x, int y, const std::vector<std::string>& rowsOfText);\n\n\n\n void draw() const;\n\n void updateColor() const;\n\n void updateWalls() const;\n\n void updateFog() const;\n\n void updateText() const;\n\n\n\nprivate:\n\n std::vector<std::vector<TileGraphic>> m_tileGraphics;\n\n\n\n int getWidth() const;\n\n int getHeight() const;\n\n bool withinMaze(int x, int y) const;\n\n\n\n};\n\n\n\n} // namespace sim\n", "file_path": "old/v2/src/sim/MazeGraphic.h", "rank": 75, "score": 112810.24951201744 }, { "content": "class MazeChecker {\n\n\n\npublic:\n\n\n\n // The MazeChecker class is not constructible\n\n MazeChecker() = delete;\n\n\n\n // Returns true is a maze is valid (usable by the simulator), false otherwise\n\n static bool isValidMaze(const std::vector<std::vector<BasicTile>>& maze);\n\n\n\n // Returns true if a maze complies with the official rules, false otherwise\n\n static bool isOfficialMaze(const std::vector<std::vector<BasicTile>>& maze);\n\n\n\n // Misc. helper function, used by Maze\n\n static std::vector<std::pair<int, int>> getCenterTiles(int width, int height);\n\n\n\nprivate:\n\n\n\n // isValidMaze helper functions\n\n static bool isNonempty(const std::vector<std::vector<BasicTile>>& maze);\n", "file_path": "old/v2/src/sim/MazeChecker.h", "rank": 76, "score": 112810.24951201744 }, { "content": "class MazeInterface {\n\n\n\npublic:\n\n MazeInterface(std::vector<std::vector<BasicTile>>* basicMaze);\n\n\n\n // Logging functions\n\n void debug(const std::string& str);\n\n void info(const std::string& str);\n\n void warn(const std::string& str);\n\n void error(const std::string& str);\n\n\n\n // Misc functions\n\n double getRandom();\n\n void quit();\n\n\n\n // Sets the wall\n\n void setWall(int x, int y, char direction, bool wallExists);\n\n\n\nprivate:\n\n std::vector<std::vector<BasicTile>>* m_basicMaze;\n\n int getWidth();\n\n int getHeight();\n\n\n\n};\n\n\n\n} // namespace sim\n", "file_path": "old/v2/src/sim/MazeInterface.h", "rank": 77, "score": 112810.24951201744 }, { "content": "class MazeGraphic {\n\n\n\npublic:\n\n MazeGraphic(Maze* maze);\n\n ~MazeGraphic();\n\n void draw();\n\n\n\nprivate:\n\n Maze* m_maze;\n\n std::vector<std::vector<TileGraphic>> m_tileGraphics;\n\n};\n\n\n\n} // namespace sim\n", "file_path": "old/v1/src/sim/MazeGraphic.h", "rank": 78, "score": 112810.24951201744 }, { "content": "#include \"FontTest.h\"\n\n\n\n#include \"../../sim/Key.h\"\n\n#include \"../../sim/State.h\"\n\n\n\nnamespace fontTest {\n\n\n\nstd::string FontTest::interfaceType() const {\n\n return \"CONTINUOUS\";\n\n}\n\n\n\nvoid FontTest::solve(\n\n int mazeWidth, int mazeHeight, bool isOfficialMaze,\n\n char initialDirection, sim::MouseInterface* mouse) {\n\n\n\n // Put all the characters on the closest tiles\n\n\n\n std::string allChars =\n\n \" !\\\"#$%&'()*+,-./0123456789:;<=>?\"\n\n \"@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_\"\n", "file_path": "old/v2/src/mouse/fontTest/FontTest.cpp", "rank": 79, "score": 112228.98678418751 }, { "content": "#include \"diagonalTest.h\"\n\n\n\nnamespace diagonalTest {\n\n\n\nvoid DiagonalTest::solve(\n\n int mazeWidth, int mazeHeight, bool isOfficialMaze,\n\n char initialDirection, sim::MouseInterface* mouse) {\n\n\tmouse->originMoveForwardToEdge();\n\n\tmouse->turnRightToEdge();\n\n\tmouse->turnRightToEdge();\n\n\tmouse->turnLeftToEdge();\n\n\tmouse->moveForwardToEdge(12);\n\n\tmouse->diagonalLeftLeft(3);\n\n\tmouse->moveForwardToEdge(6);\n\n}\n\n\n\nbool DiagonalTest::useTileEdgeMovements() const {\n\n\t// If false, the mouse will use basic movements\n\n\t// If true, it will use edge movements that allow for faster maze traversal\n\n\treturn true;\n", "file_path": "old/v2/src/mouse/diagonalTest/diagonalTest.cpp", "rank": 80, "score": 112216.76201565457 }, { "content": "}\n\n\n\nvoid DiagonalTest::justMoveForward(sim::MouseInterface* mouse) {\n\n\tif (useTileEdgeMovements()) {\n\n\t\t// If we're using special tile edge movements, then the origin is a\n\n\t\t// special case, since we don't start on a tile edge.\n\n\t\tstatic bool firstMovement = true;\n\n\t\tif (firstMovement) {\n\n\t\t\tmouse->originMoveForwardToEdge();\n\n\t\t\tfirstMovement = false;\n\n\t\t}\n\n\t\telse {\n\n\t\t\tmouse->moveForwardToEdge();\n\n\t\t}\n\n\n\n\t}\n\n\telse {\n\n\t\tmouse->moveForward();\n\n\t}\n\n}\n\n\n\n} // namespace diagonalTest\n", "file_path": "old/v2/src/mouse/diagonalTest/diagonalTest.cpp", "rank": 81, "score": 112194.21180517542 }, { "content": " if (sim::S()->arrowKeyIsPressed(sim::Key::LEFT)) {\n\n leftWheelSpeed += accelerateAmount / 4.0;\n\n rightWheelSpeed += accelerateAmount / 4.0;\n\n }\n\n\n\n if (leftWheelSpeed < -mouse->getWheelMaxSpeed(\"left\")) {\n\n leftWheelSpeed = -mouse->getWheelMaxSpeed(\"left\"); \n\n }\n\n if (mouse->getWheelMaxSpeed(\"left\") < leftWheelSpeed) {\n\n leftWheelSpeed = mouse->getWheelMaxSpeed(\"left\");\n\n }\n\n if (rightWheelSpeed < -mouse->getWheelMaxSpeed(\"right\")) {\n\n rightWheelSpeed = -mouse->getWheelMaxSpeed(\"right\"); \n\n }\n\n if (mouse->getWheelMaxSpeed(\"right\") < rightWheelSpeed) {\n\n rightWheelSpeed = mouse->getWheelMaxSpeed(\"right\");\n\n }\n\n\n\n mouse->setWheelSpeed(\"left\", leftWheelSpeed);\n\n mouse->setWheelSpeed(\"right\", rightWheelSpeed);\n\n mouse->delay(30);\n\n }\n\n}\n\n\n\n} // namespace fontTest\n", "file_path": "old/v2/src/mouse/fontTest/FontTest.cpp", "rank": 82, "score": 112185.45055315296 }, { "content": " \"`abcdefghijklmnopqrstuvwxyz{|}~\";\n\n\n\n for (int i = 0; i < 6; i += 1) {\n\n for (int j = 0; j < 6; j += 1) {\n\n int index = 18 * i + 3 * j + 0;\n\n std::string str;\n\n for (int k = 0; k < 3; k += 1) {\n\n if (index + k < allChars.size()) {\n\n str += allChars.substr(index + k, 1);\n\n str += \" \";\n\n }\n\n }\n\n mouse->setTileText(i, 5 - j, str);\n\n }\n\n }\n\n\n\n // Easy manual mode control so that we can look around\n\n\n\n double accelerateAmount = 60.0;\n\n double decelerateAmount = 1.5;\n", "file_path": "old/v2/src/mouse/fontTest/FontTest.cpp", "rank": 83, "score": 112184.26483700745 }, { "content": " double leftWheelSpeed = 0.0;\n\n double rightWheelSpeed = 0.0;\n\n\n\n while (true) {\n\n\n\n leftWheelSpeed /= decelerateAmount;\n\n rightWheelSpeed /= decelerateAmount;\n\n\n\n if (sim::S()->arrowKeyIsPressed(sim::Key::UP)) {\n\n leftWheelSpeed -= accelerateAmount;\n\n rightWheelSpeed += accelerateAmount;\n\n }\n\n if (sim::S()->arrowKeyIsPressed(sim::Key::DOWN)) {\n\n leftWheelSpeed += accelerateAmount;\n\n rightWheelSpeed -= accelerateAmount;\n\n }\n\n if (sim::S()->arrowKeyIsPressed(sim::Key::RIGHT)) {\n\n leftWheelSpeed -= accelerateAmount / 4.0;\n\n rightWheelSpeed -= accelerateAmount / 4.0;\n\n }\n", "file_path": "old/v2/src/mouse/fontTest/FontTest.cpp", "rank": 84, "score": 112170.9489050654 }, { "content": "class MouseInterface {\n\n\n\npublic:\n\n MouseInterface(\n\n const Maze* maze,\n\n Mouse* mouse,\n\n MazeGraphic* mazeGraphic,\n\n IMouseAlgorithm* mouseAlgorithm,\n\n std::set<char> allowableTileTextCharacters,\n\n StaticMouseAlgorithmOptions options);\n\n\n\n // ----- Any interface methods ----- //\n\n\n\n // Logging functions\n\n void debug(const std::string& str);\n\n void info(const std::string& str);\n\n void warn(const std::string& str);\n\n void error(const std::string& str);\n\n\n\n // Misc functions\n", "file_path": "old/v2/src/sim/MouseInterface.h", "rank": 85, "score": 111795.65234860856 }, { "content": "class MouseChecker {\n\n\n\npublic:\n\n\n\n // The MouseChecker class is not constructible\n\n MouseChecker() = delete;\n\n\n\n static bool isDiscreteInterfaceCompatible(const Mouse& mouse);\n\n static bool isContinuousInterfaceCompatible(const Mouse& mouse);\n\n};\n\n\n\n} // namespace sim\n", "file_path": "old/v2/src/sim/MouseChecker.h", "rank": 86, "score": 111795.65234860856 }, { "content": "class MouseInterface {\n\n\n\npublic:\n\n MouseInterface(Mouse* mouse, int* sleepTime, bool* paused, bool* undoRequested, bool* resetRequested);\n\n ~MouseInterface();\n\n\n\n // ---------------------- Mouse Interfact Methods ----------------------- //\n\n\n\n bool wallFront();\n\n bool wallRight();\n\n bool wallLeft();\n\n void moveForward();\n\n void turnRight();\n\n void turnLeft();\n\n void turnAround();\n\n\n\n bool undoRequested();\n\n bool resetRequested();\n\n void undoHonored();\n\n void resetHonored();\n", "file_path": "old/v1/src/sim/MouseInterface.h", "rank": 87, "score": 111795.65234860856 }, { "content": "class MouseGraphic {\n\n\n\npublic:\n\n MouseGraphic(Mouse* mouse);\n\n ~MouseGraphic();\n\n void draw();\n\n void drawDirection(float c1X, float c1Y, float c2X, float c2Y);\n\n\n\nprivate:\n\n Mouse* m_mouse;\n\n GLfloat* m_color;\n\n};\n\n\n\n} // namespace sim\n", "file_path": "old/v1/src/sim/MouseGraphic.h", "rank": 88, "score": 111795.65234860856 }, { "content": "class MouseParser {\n\n\n\npublic:\n\n MouseParser(const std::string& filePath, bool* success);\n\n Polygon getBody(\n\n const Cartesian& initialTranslation, const Radians& initialRotation, bool* success);\n\n std::map<std::string, Wheel> getWheels(\n\n const Cartesian& initialTranslation, const Radians& initialRotation, bool* success);\n\n std::map<std::string, Sensor> getSensors(\n\n const Cartesian& initialTranslation, const Radians& initialRotation, const Maze& maze, bool* success);\n\n\n\nprivate:\n\n // We have to keep m_doc around so valgrind doesn't complain\n\n pugi::xml_document m_doc;\n\n pugi::xml_node m_root;\n\n Radians m_forwardDirection;\n\n Cartesian m_centerOfMass;\n\n\n\n double getDoubleIfHasDouble(const pugi::xml_node& node, const std::string& tag, bool* success);\n\n double getDoubleIfHasDoubleAndNonNegative(\n", "file_path": "old/v2/src/sim/MouseParser.h", "rank": 89, "score": 111795.65234860856 }, { "content": "class MouseGraphic {\n\n\n\npublic:\n\n MouseGraphic(const Mouse* mouse, BufferInterface* bufferInterface);\n\n void draw(const Coordinate& currentTranslation, const Angle& currentRotation) const;\n\n\n\nprivate:\n\n const Mouse* m_mouse;\n\n BufferInterface* m_bufferInterface;\n\n\n\n};\n\n\n\n} // namespace sim\n", "file_path": "old/v2/src/sim/MouseGraphic.h", "rank": 90, "score": 111795.65234860856 }, { "content": "class Randomize : public IMazeAlgorithm {\n\n\n\npublic:\n\n void generate(int mazeWidth, int mazeHeight, sim::MazeInterface* maze);\n\n\n\n};\n\n\n\n} // namespace randomize\n", "file_path": "old/v2/src/maze/randomize/Randomize.h", "rank": 91, "score": 111223.698263522 }, { "content": "#pragma once\n\n\n\n#include <QString>\n\n#include <QStringList>\n\n\n\nnamespace mms {\n\n\n", "file_path": "src/SettingsMouseAlgos.h", "rank": 92, "score": 110524.65778702305 }, { "content": " const QString& newBuildCommand,\n\n const QString& newRunCommand);\n\n static void remove(const QString& name);\n\n\n\nprivate:\n\n\n\n static const QString GROUP;\n\n static const QString KEY_NAME;\n\n static const QString KEY_DIR_PATH;\n\n static const QString KEY_BUILD_COMMAND;\n\n static const QString KEY_RUN_COMMAND;\n\n \n\n static QString getValue(const QString& name, const QString& key);\n\n \n\n};\n\n\n\n} \n", "file_path": "src/SettingsMouseAlgos.h", "rank": 93, "score": 110512.75204474569 }, { "content": "#define ONLY_EXECUTE_ONCE {\\\n\n static bool alreadyExecuted = false;\\\n\n SIM_ASSERT_FA(alreadyExecuted);\\\n\n alreadyExecuted = true;\\\n\n}\n", "file_path": "old/v2/src/sim/OnlyExecuteOnce.h", "rank": 94, "score": 110296.97588944345 }, { "content": "class Continuous : public IMouseAlgorithm {\n\n\n\npublic:\n\n std::string mouseFile() const;\n\n std::string interfaceType() const;\n\n void solve(int mazeWidth, int mazeHeight, bool isOfficialMaze, char initialDirection, sim::MouseInterface* mouse);\n\n\n\nprivate:\n\n\t//Thresholds for left and right sensors detecting side walls\n\n#define hasLeftWall .5\n\n#define hasRightWall .5\n\n\n\n\t//Seperate speeds for explore and solve (not currently implemented)\n\n\tint exploreSpeed = 620;\n\n\tint solveSpeed = 620;\n\n\n\n\tint leftBaseSpeed = exploreSpeed;\n\n\tint rightBaseSpeed = exploreSpeed;\n\n\n\n\t//Setpoint for left and right sensors detecting side walls\n", "file_path": "old/v2/src/mouse/continuous/Continuous.h", "rank": 95, "score": 110231.17159401458 }, { "content": "class DoNothing : public IMouseAlgorithm {\n\n\n\npublic:\n\n void solve(\n\n int mazeWidth, int mazeHeight, bool isOfficialMaze,\n\n char initialDirection, sim::MouseInterface* mouse);\n\n\n\n};\n\n\n\n} // namespace doNothing\n", "file_path": "old/v2/src/mouse/doNothing/DoNothing.h", "rank": 96, "score": 110231.17159401458 }, { "content": "#include \"Manual.h\"\n\n\n\n#include \"../../sim/Key.h\"\n\n#include \"../../sim/State.h\"\n\n\n\nnamespace manual {\n\n\n\nstd::string Manual::mouseFile() const {\n\n return \"megaMouse.xml\";\n\n}\n\n\n\nstd::string Manual::interfaceType() const {\n\n return \"CONTINUOUS\";\n\n}\n\n\n\nvoid Manual::solve(\n\n int mazeWidth, int mazeHeight, bool isOfficialMaze,\n\n char initialDirection, sim::MouseInterface* mouse) {\n\n\n\n sim::S()->setRotateZoomedMap(true);\n", "file_path": "old/v2/src/mouse/manual/Manual.cpp", "rank": 97, "score": 62.59144683319128 }, { "content": " // Initialize the mouse with the file provided\n\n Direction direction = getInitialDirection(initialDirection, model);\n\n bool success = model->getMouse()->initialize(mouseFile, direction);\n\n if (!success) {\n\n L()->error(\n\n \"Unable to successfully initialize the mouse in the algorithm\"\n\n \" \\\"%v\\\" from \\\"%v\\\".\",\n\n mouseAlgorithm,\n\n mouseFile);\n\n SimUtilities::quit();\n\n }\n\n\n\n // Validate the mouse\n\n if (STRING_TO_INTERFACE_TYPE.at(interfaceType) == InterfaceType::DISCRETE) {\n\n if (!MouseChecker::isDiscreteInterfaceCompatible(*model->getMouse())) {\n\n L()->error(\"The mouse file \\\"%v\\\" is not discrete interface compatible.\", mouseFile);\n\n SimUtilities::quit();\n\n }\n\n }\n\n else { // InterfaceType::CONTINUOUS\n", "file_path": "old/v2/src/sim/Controller.cpp", "rank": 98, "score": 58.40616568129518 }, { "content": "There are a few options that are available to mouse algorithms. They are\n\nimplemented as virtual methods in the `IMouseAlgorithm` class. That is, the\n\ndefault options are defined in `src/mouse/IMouseAlgorithm.cpp`. If you wish to\n\nuse values other than the defaults, should override the virtual methods in you\n\nalgorithm (which should inherit from IMouseAlgorithm). For instance, suppose\n\nyour algorithm's `.h` and `.cpp` file looked like to following, respectively:\n\n\n\n```c++\n\n// LeftWallFollow.h\n\n\n\n#pragma once\n\n\n\n#include \"../IMouseAlgorithm.h\"\n\n\n\nnamespace leftWallFollow {\n\n\n\nclass LeftWallFollow : public IMouseAlgorithm {\n\n\n\npublic:\n\n void solve(\n\n int mazeWidth, int mazeHeight, bool isOfficialMaze,\n\n char initialDirection, sim::MouseInterface* mouse);\n\n\n\nprivate:\n\n void leftWallFollowStep(sim::MouseInterface* mouse);\n\n};\n\n\n\n} // namespace leftWallFollow\n\n```\n\n\n\n```c++\n\n// LeftWallFollow.cpp\n\n\n\n#include \"LeftWallFollow.h\"\n\n\n\nnamespace leftWallFollow {\n\n\n\nvoid LeftWallFollow::solve(\n\n int mazeWidth, int mazeHeight, bool isOfficialMaze,\n\n char initialDirection, sim::MouseInterface* mouse) {\n\n while (true) {\n\n leftWallFollowStep(mouse);\n\n }\n\n}\n\n\n\nvoid LeftWallFollow::leftWallFollowStep(sim::MouseInterface* mouse) {\n\n if (!mouse->wallLeft()){\n\n mouse->turnLeft();\n\n }\n\n while (mouse->wallFront()){\n\n mouse->turnRight();\n\n }\n\n mouse->moveForward();\n\n}\n\n\n\n} // namespace leftWallFollow\n\n```\n\n\n\nIf you wanted to change the value of the `declareWallsOnRead` option, you would\n\noverride that method in `LeftWallFollow`, like:\n\n\n\n```c++\n\n// LeftWallFollow.h\n\n\n\n#pragma once\n\n\n\n#include \"../IMouseAlgorithm.h\"\n\n\n\nnamespace leftWallFollow {\n\n\n\nclass LeftWallFollow : public IMouseAlgorithm {\n\n\n\npublic:\n\n bool declareWallOnRead() const; // Note the \"const\"\n\n void solve(\n\n int mazeWidth, int mazeHeight, bool isOfficialMaze,\n\n char initialDirection, sim::MouseInterface* mouse);\n\n\n\nprivate:\n\n void leftWallFollowStep(sim::MouseInterface* mouse);\n\n};\n\n\n\n} // namespace leftWallFollow\n\n```\n\n\n\n```c++\n", "file_path": "old/v2/wiki/Mouse Algorithm Options.md", "rank": 99, "score": 58.14244046935584 } ]
C++
libc/winsup/cygwin/fhandler_procsys.cc
The0x539/wasp
5f83aab7bf0c0915b1d3491034d35b091c7aebdf
#include "winsup.h" #include <stdlib.h> #include "cygerrno.h" #include "security.h" #include "path.h" #include "fhandler.h" #include "dtable.h" #include "cygheap.h" #include <winioctl.h> #include "ntdll.h" #include "tls_pbuf.h" #include <dirent.h> const char procsys[] = "/proc/sys"; const size_t procsys_len = sizeof (procsys) - 1; #define mk_unicode_path(p) \ WCHAR namebuf[strlen (get_name ()) + 1]; \ { \ const char *from; \ PWCHAR to; \ for (to = namebuf, from = get_name () + procsys_len; *from; \ to++, from++) \ \ *to = (*from == '/') ? L'\\' : (WCHAR) *from; \ if (to == namebuf) \ *to++ = L'\\'; \ *to = L'\0'; \ RtlInitUnicodeString ((p), namebuf); \ } virtual_ftype_t fhandler_procsys::exists (struct stat *buf) { UNICODE_STRING path; UNICODE_STRING dir; OBJECT_ATTRIBUTES attr; IO_STATUS_BLOCK io; NTSTATUS status; HANDLE h; FILE_BASIC_INFORMATION fbi; bool internal = false; bool desperate_parent_check = false; virtual_ftype_t file_type = virt_chr; if (strlen (get_name ()) == procsys_len) return virt_rootdir; mk_unicode_path (&path); RtlSplitUnicodePath (&path, &dir, NULL); if (dir.Length > sizeof (WCHAR)) dir.Length -= sizeof (WCHAR); InitializeObjectAttributes (&attr, &dir, OBJ_CASE_INSENSITIVE, NULL, NULL); status = NtOpenDirectoryObject (&h, DIRECTORY_QUERY, &attr); debug_printf ("NtOpenDirectoryObject: %y", status); if (NT_SUCCESS (status)) { internal = true; NtClose (h); } InitializeObjectAttributes (&attr, &path, OBJ_CASE_INSENSITIVE, NULL, NULL); status = NtOpenSymbolicLinkObject (&h, READ_CONTROL | SYMBOLIC_LINK_QUERY, &attr); debug_printf ("NtOpenSymbolicLinkObject: %y", status); if (NT_SUCCESS (status)) { if (buf) get_object_attribute (h, &buf->st_uid, &buf->st_gid, &buf->st_mode); NtClose (h); return virt_symlink; } else if (status == STATUS_ACCESS_DENIED) return virt_symlink; status = NtOpenDirectoryObject (&h, READ_CONTROL | DIRECTORY_QUERY, &attr); debug_printf ("NtOpenDirectoryObject: %y", status); if (NT_SUCCESS (status)) { if (buf) get_object_attribute (h, &buf->st_uid, &buf->st_gid, &buf->st_mode); NtClose (h); return virt_directory; } else if (status == STATUS_ACCESS_DENIED) return virt_directory; status = NtOpenFile (&h, READ_CONTROL | FILE_READ_ATTRIBUTES, &attr, &io, FILE_SHARE_VALID_FLAGS, FILE_OPEN_FOR_BACKUP_INTENT); debug_printf ("NtOpenFile: %y", status); if (status == STATUS_OBJECT_NAME_INVALID) return virt_none; if (status == STATUS_NO_MEDIA_IN_DEVICE || status == STATUS_SHARING_VIOLATION) return virt_fsfile; if (status == STATUS_OBJECT_PATH_NOT_FOUND || status == STATUS_OBJECT_NAME_NOT_FOUND) return virt_fsfile; if (status >= STATUS_PIPE_NOT_AVAILABLE && status <= STATUS_PIPE_BUSY) return virt_pipe; if (status == STATUS_ACCESS_DENIED && !internal) { status = NtQueryAttributesFile (&attr, &fbi); debug_printf ("NtQueryAttributesFile: %y", status); if (NT_SUCCESS (status)) return (fbi.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? virt_fsdir : virt_fsfile; dir = path; InitializeObjectAttributes (&attr, &dir, OBJ_CASE_INSENSITIVE, NULL, NULL); do { RtlSplitUnicodePath (&dir, &dir, NULL); status = NtOpenFile (&h, READ_CONTROL | FILE_READ_ATTRIBUTES, &attr, &io, FILE_SHARE_VALID_FLAGS, FILE_OPEN_FOR_BACKUP_INTENT); debug_printf ("NtOpenDirectoryObject: %y", status); if (dir.Length > sizeof (WCHAR)) dir.Length -= sizeof (WCHAR); } while (dir.Length > sizeof (WCHAR) && !NT_SUCCESS (status)); desperate_parent_check = true; } if (NT_SUCCESS (status)) { FILE_FS_DEVICE_INFORMATION ffdi; if (buf && !desperate_parent_check) get_object_attribute (h, &buf->st_uid, &buf->st_gid, &buf->st_mode); status = NtQueryVolumeInformationFile (h, &io, &ffdi, sizeof ffdi, FileFsDeviceInformation); debug_printf ("NtQueryVolumeInformationFile: %y", status); if (NT_SUCCESS (status)) { if (ffdi.DeviceType == FILE_DEVICE_NETWORK_FILE_SYSTEM) file_type = virt_blk; else if (ffdi.DeviceType == FILE_DEVICE_NAMED_PIPE) file_type = internal ? virt_blk : virt_pipe; else if (ffdi.DeviceType == FILE_DEVICE_DISK || ffdi.DeviceType == FILE_DEVICE_CD_ROM || ffdi.DeviceType == FILE_DEVICE_DFS || ffdi.DeviceType == FILE_DEVICE_VIRTUAL_DISK) { status = NtQueryInformationFile (h, &io, &fbi, sizeof fbi, FileBasicInformation); debug_printf ("NtQueryInformationFile: %y", status); if (!NT_SUCCESS (status)) file_type = virt_blk; else file_type = (fbi.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? virt_fsdir : virt_fsfile; } } NtClose (h); } return file_type; } virtual_ftype_t fhandler_procsys::exists () { return exists (NULL); } fhandler_procsys::fhandler_procsys (): fhandler_virtual () { } #define UNREADABLE_SYMLINK_CONTENT "<access denied>" bool fhandler_procsys::fill_filebuf () { char *fnamep; UNICODE_STRING path, target; OBJECT_ATTRIBUTES attr; NTSTATUS status; HANDLE h; tmp_pathbuf tp; size_t len; mk_unicode_path (&path); if (path.Buffer[path.Length / sizeof (WCHAR) - 1] == L'\\') path.Length -= sizeof (WCHAR); InitializeObjectAttributes (&attr, &path, OBJ_CASE_INSENSITIVE, NULL, NULL); status = NtOpenSymbolicLinkObject (&h, SYMBOLIC_LINK_QUERY, &attr); if (!NT_SUCCESS (status)) goto unreadable; RtlInitEmptyUnicodeString (&target, tp.w_get (), (NT_MAX_PATH - 1) * sizeof (WCHAR)); status = NtQuerySymbolicLinkObject (h, &target, NULL); NtClose (h); if (!NT_SUCCESS (status)) goto unreadable; len = sys_wcstombs (NULL, 0, target.Buffer, target.Length / sizeof (WCHAR)); filebuf = (char *) crealloc_abort (filebuf, procsys_len + len + 1); sys_wcstombs (fnamep = stpcpy (filebuf, procsys), len + 1, target.Buffer, target.Length / sizeof (WCHAR)); while ((fnamep = strchr (fnamep, '\\'))) *fnamep = '/'; return true; unreadable: filebuf = (char *) crealloc_abort (filebuf, sizeof (UNREADABLE_SYMLINK_CONTENT)); strcpy (filebuf, UNREADABLE_SYMLINK_CONTENT); return false; } int __reg2 fhandler_procsys::fstat (struct stat *buf) { const char *path = get_name (); debug_printf ("fstat (%s)", path); fhandler_base::fstat (buf); buf->st_mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP; buf->st_uid = 544; buf->st_gid = 18; buf->st_dev = buf->st_rdev = dev (); buf->st_ino = get_ino (); switch (exists (buf)) { case virt_directory: case virt_rootdir: case virt_fsdir: buf->st_mode |= S_IFDIR; if (buf->st_mode & S_IRUSR) buf->st_mode |= S_IXUSR; if (buf->st_mode & S_IRGRP) buf->st_mode |= S_IXGRP; if (buf->st_mode & S_IROTH) buf->st_mode |= S_IXOTH; break; case virt_file: case virt_fsfile: buf->st_mode |= S_IFREG; break; case virt_symlink: buf->st_mode |= S_IFLNK; break; case virt_pipe: buf->st_mode |= S_IFIFO; break; case virt_socket: buf->st_mode |= S_IFSOCK; break; case virt_chr: buf->st_mode |= S_IFCHR; break; case virt_blk: buf->st_mode |= S_IFBLK; break; default: set_errno (ENOENT); return -1; } return 0; } DIR * fhandler_procsys::opendir (int fd) { UNICODE_STRING path; OBJECT_ATTRIBUTES attr; NTSTATUS status; HANDLE h; DIR *dir; mk_unicode_path (&path); InitializeObjectAttributes (&attr, &path, OBJ_CASE_INSENSITIVE, NULL, NULL); status = NtOpenDirectoryObject (&h, DIRECTORY_QUERY, &attr); if (!NT_SUCCESS (status)) { __seterrno_from_nt_status (status); return NULL; } if (!(dir = fhandler_virtual::opendir (fd))) NtClose (h); else dir->__handle = h; return dir; } int fhandler_procsys::readdir (DIR *dir, dirent *de) { NTSTATUS status; struct fdbi { DIRECTORY_BASIC_INFORMATION dbi; WCHAR buf[2][NAME_MAX + 1]; } f; int res = EBADF; if (dir->__handle != INVALID_HANDLE_VALUE) { BOOLEAN restart = dir->__d_position ? FALSE : TRUE; status = NtQueryDirectoryObject (dir->__handle, &f, sizeof f, TRUE, restart, (PULONG) &dir->__d_position, NULL); if (!NT_SUCCESS (status)) res = ENMFILE; else { sys_wcstombs (de->d_name, NAME_MAX + 1, f.dbi.ObjectName.Buffer, f.dbi.ObjectName.Length / sizeof (WCHAR)); de->d_ino = hash_path_name (get_ino (), de->d_name); if (RtlEqualUnicodeString (&f.dbi.ObjectTypeName, &ro_u_natdir, FALSE)) de->d_type = DT_DIR; else if (RtlEqualUnicodeString (&f.dbi.ObjectTypeName, &ro_u_natsyml, FALSE)) de->d_type = DT_LNK; else if (!RtlEqualUnicodeString (&f.dbi.ObjectTypeName, &ro_u_natdev, FALSE)) de->d_type = DT_CHR; else de->d_type = DT_UNKNOWN; res = 0; } } syscall_printf ("%d = readdir(%p, %p)", res, dir, de); return res; } long fhandler_procsys::telldir (DIR *dir) { return dir->__d_position; } void fhandler_procsys::seekdir (DIR *dir, long pos) { dir->__d_position = pos; } int fhandler_procsys::closedir (DIR *dir) { if (dir->__handle != INVALID_HANDLE_VALUE) { NtClose (dir->__handle); dir->__handle = INVALID_HANDLE_VALUE; } return fhandler_virtual::closedir (dir); } void __reg3 fhandler_procsys::read (void *ptr, size_t& len) { fhandler_base::raw_read (ptr, len); } ssize_t __stdcall fhandler_procsys::write (const void *ptr, size_t len) { return fhandler_base::raw_write (ptr, len); } int fhandler_procsys::open (int flags, mode_t mode) { int res = 0; if ((flags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL)) set_errno (EINVAL); else { switch (exists (NULL)) { case virt_directory: case virt_rootdir: if ((flags & O_ACCMODE) != O_RDONLY) set_errno (EISDIR); else { nohandle (true); res = 1; } break; case virt_none: set_errno (ENOENT); break; default: res = fhandler_base::open (flags, mode); break; } } syscall_printf ("%d = fhandler_procsys::open(%p, 0%o)", res, flags, mode); return res; } int fhandler_procsys::close () { if (!nohandle ()) NtClose (get_handle ()); return fhandler_virtual::close (); } #if 0 int fhandler_procsys::ioctl (unsigned int cmd, void *) { } #endif
#include "winsup.h" #include <stdlib.h> #include "cygerrno.h" #include "security.h" #include "path.h" #include "fhandler.h" #include "dtable.h" #include "cygheap.h" #include <winioctl.h> #include "ntdll.h" #include "tls_pbuf.h" #include <dirent.h> const char procsys[] = "/proc/sys"; const size_t procsys_len = sizeof (procsys) - 1; #define mk_unicode_path(p) \ WCHAR namebuf[strlen (get_name ()) + 1]; \ { \ const char *from; \ PWCHAR to; \ for (to = namebuf, from = get_name () + procsys_len; *from; \ to++, from++) \ \ *to = (*from == '/') ? L'\\' : (WCHAR) *from; \ if (to == namebuf) \ *to++ = L'\\'; \ *to = L'\0'; \ RtlInitUnicodeString ((p), namebuf); \ } virtual_ftype_t fhandler_procsys::exists (struct stat *buf) { UNICODE_STRING path; UNICODE_STRING dir; OBJECT_ATTRIBUTES attr; IO_STATUS_BLOCK io; NTSTATUS status; HANDLE h; FILE_BASIC_INFORMATION fbi; bool internal = false; bool desperate_parent_check = false; virtual_ftype_t file_type = virt_chr; if (strlen (get_name ()) == procsys_len) return virt_rootdir; mk_unicode_path (&path); RtlSplitUnicodePath (&path, &dir, NULL); if (dir.Length > sizeof (WCHAR)) dir.Length -= sizeof (WCHAR); InitializeObjectAttributes (&attr, &dir, OBJ_CASE_INSENSITIVE, NULL, NULL); status = NtOpenDirectoryObject (&h, DIRECTORY_QUERY, &attr); debug_printf ("NtOpenDirectoryObject: %y", status); if (NT_SUCCESS (status)) { internal = true; NtClose (h); } InitializeObjectAttributes (&attr, &path, OBJ_CASE_INSENSITIVE, NULL, NULL); status = NtOpenSymbolicLinkObject (&h, READ_CONTROL | SYMBOLIC_LINK_QUERY, &attr); debug_printf ("NtOpenSymbolicLinkObject: %y", status); if (NT_SUCCESS (status)) { if (buf) get_object_attribute (h, &buf->st_uid, &buf->st_gid, &buf->st_mode); NtClose (h); return virt_symlink; } else if (status == STATUS_ACCESS_DENIED) return virt_symlink; status = NtOpenDirectoryObject (&h, READ_CONTROL | DIRECTORY_QUERY, &attr); debug_printf ("NtOpenDirectoryObject: %y", status); if (NT_SUCCESS (status)) { if (buf) get_object_attribute (h, &buf->st_uid, &buf->st_gid, &buf->st_mode); NtClose (h); return virt_directory; } else if (status == STATUS_ACCESS_DENIED) return virt_directory; status = NtOpenFile (&h, READ_CONTROL | FILE_READ_ATTRIBUTES, &attr, &io, FILE_SHARE_VALID_FLAGS, FILE_OPEN_FOR_BACKUP_INTENT); debug_printf ("NtOpenFile: %y", status); if (status == STATUS_OBJECT_NAME_INVALID) return virt_none; if (status == STATUS_NO_MEDIA_IN_DEVICE || status == STAT
; if (!NT_SUCCESS (status)) goto unreadable; RtlInitEmptyUnicodeString (&target, tp.w_get (), (NT_MAX_PATH - 1) * sizeof (WCHAR)); status = NtQuerySymbolicLinkObject (h, &target, NULL); NtClose (h); if (!NT_SUCCESS (status)) goto unreadable; len = sys_wcstombs (NULL, 0, target.Buffer, target.Length / sizeof (WCHAR)); filebuf = (char *) crealloc_abort (filebuf, procsys_len + len + 1); sys_wcstombs (fnamep = stpcpy (filebuf, procsys), len + 1, target.Buffer, target.Length / sizeof (WCHAR)); while ((fnamep = strchr (fnamep, '\\'))) *fnamep = '/'; return true; unreadable: filebuf = (char *) crealloc_abort (filebuf, sizeof (UNREADABLE_SYMLINK_CONTENT)); strcpy (filebuf, UNREADABLE_SYMLINK_CONTENT); return false; } int __reg2 fhandler_procsys::fstat (struct stat *buf) { const char *path = get_name (); debug_printf ("fstat (%s)", path); fhandler_base::fstat (buf); buf->st_mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP; buf->st_uid = 544; buf->st_gid = 18; buf->st_dev = buf->st_rdev = dev (); buf->st_ino = get_ino (); switch (exists (buf)) { case virt_directory: case virt_rootdir: case virt_fsdir: buf->st_mode |= S_IFDIR; if (buf->st_mode & S_IRUSR) buf->st_mode |= S_IXUSR; if (buf->st_mode & S_IRGRP) buf->st_mode |= S_IXGRP; if (buf->st_mode & S_IROTH) buf->st_mode |= S_IXOTH; break; case virt_file: case virt_fsfile: buf->st_mode |= S_IFREG; break; case virt_symlink: buf->st_mode |= S_IFLNK; break; case virt_pipe: buf->st_mode |= S_IFIFO; break; case virt_socket: buf->st_mode |= S_IFSOCK; break; case virt_chr: buf->st_mode |= S_IFCHR; break; case virt_blk: buf->st_mode |= S_IFBLK; break; default: set_errno (ENOENT); return -1; } return 0; } DIR * fhandler_procsys::opendir (int fd) { UNICODE_STRING path; OBJECT_ATTRIBUTES attr; NTSTATUS status; HANDLE h; DIR *dir; mk_unicode_path (&path); InitializeObjectAttributes (&attr, &path, OBJ_CASE_INSENSITIVE, NULL, NULL); status = NtOpenDirectoryObject (&h, DIRECTORY_QUERY, &attr); if (!NT_SUCCESS (status)) { __seterrno_from_nt_status (status); return NULL; } if (!(dir = fhandler_virtual::opendir (fd))) NtClose (h); else dir->__handle = h; return dir; } int fhandler_procsys::readdir (DIR *dir, dirent *de) { NTSTATUS status; struct fdbi { DIRECTORY_BASIC_INFORMATION dbi; WCHAR buf[2][NAME_MAX + 1]; } f; int res = EBADF; if (dir->__handle != INVALID_HANDLE_VALUE) { BOOLEAN restart = dir->__d_position ? FALSE : TRUE; status = NtQueryDirectoryObject (dir->__handle, &f, sizeof f, TRUE, restart, (PULONG) &dir->__d_position, NULL); if (!NT_SUCCESS (status)) res = ENMFILE; else { sys_wcstombs (de->d_name, NAME_MAX + 1, f.dbi.ObjectName.Buffer, f.dbi.ObjectName.Length / sizeof (WCHAR)); de->d_ino = hash_path_name (get_ino (), de->d_name); if (RtlEqualUnicodeString (&f.dbi.ObjectTypeName, &ro_u_natdir, FALSE)) de->d_type = DT_DIR; else if (RtlEqualUnicodeString (&f.dbi.ObjectTypeName, &ro_u_natsyml, FALSE)) de->d_type = DT_LNK; else if (!RtlEqualUnicodeString (&f.dbi.ObjectTypeName, &ro_u_natdev, FALSE)) de->d_type = DT_CHR; else de->d_type = DT_UNKNOWN; res = 0; } } syscall_printf ("%d = readdir(%p, %p)", res, dir, de); return res; } long fhandler_procsys::telldir (DIR *dir) { return dir->__d_position; } void fhandler_procsys::seekdir (DIR *dir, long pos) { dir->__d_position = pos; } int fhandler_procsys::closedir (DIR *dir) { if (dir->__handle != INVALID_HANDLE_VALUE) { NtClose (dir->__handle); dir->__handle = INVALID_HANDLE_VALUE; } return fhandler_virtual::closedir (dir); } void __reg3 fhandler_procsys::read (void *ptr, size_t& len) { fhandler_base::raw_read (ptr, len); } ssize_t __stdcall fhandler_procsys::write (const void *ptr, size_t len) { return fhandler_base::raw_write (ptr, len); } int fhandler_procsys::open (int flags, mode_t mode) { int res = 0; if ((flags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL)) set_errno (EINVAL); else { switch (exists (NULL)) { case virt_directory: case virt_rootdir: if ((flags & O_ACCMODE) != O_RDONLY) set_errno (EISDIR); else { nohandle (true); res = 1; } break; case virt_none: set_errno (ENOENT); break; default: res = fhandler_base::open (flags, mode); break; } } syscall_printf ("%d = fhandler_procsys::open(%p, 0%o)", res, flags, mode); return res; } int fhandler_procsys::close () { if (!nohandle ()) NtClose (get_handle ()); return fhandler_virtual::close (); } #if 0 int fhandler_procsys::ioctl (unsigned int cmd, void *) { } #endif
US_SHARING_VIOLATION) return virt_fsfile; if (status == STATUS_OBJECT_PATH_NOT_FOUND || status == STATUS_OBJECT_NAME_NOT_FOUND) return virt_fsfile; if (status >= STATUS_PIPE_NOT_AVAILABLE && status <= STATUS_PIPE_BUSY) return virt_pipe; if (status == STATUS_ACCESS_DENIED && !internal) { status = NtQueryAttributesFile (&attr, &fbi); debug_printf ("NtQueryAttributesFile: %y", status); if (NT_SUCCESS (status)) return (fbi.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? virt_fsdir : virt_fsfile; dir = path; InitializeObjectAttributes (&attr, &dir, OBJ_CASE_INSENSITIVE, NULL, NULL); do { RtlSplitUnicodePath (&dir, &dir, NULL); status = NtOpenFile (&h, READ_CONTROL | FILE_READ_ATTRIBUTES, &attr, &io, FILE_SHARE_VALID_FLAGS, FILE_OPEN_FOR_BACKUP_INTENT); debug_printf ("NtOpenDirectoryObject: %y", status); if (dir.Length > sizeof (WCHAR)) dir.Length -= sizeof (WCHAR); } while (dir.Length > sizeof (WCHAR) && !NT_SUCCESS (status)); desperate_parent_check = true; } if (NT_SUCCESS (status)) { FILE_FS_DEVICE_INFORMATION ffdi; if (buf && !desperate_parent_check) get_object_attribute (h, &buf->st_uid, &buf->st_gid, &buf->st_mode); status = NtQueryVolumeInformationFile (h, &io, &ffdi, sizeof ffdi, FileFsDeviceInformation); debug_printf ("NtQueryVolumeInformationFile: %y", status); if (NT_SUCCESS (status)) { if (ffdi.DeviceType == FILE_DEVICE_NETWORK_FILE_SYSTEM) file_type = virt_blk; else if (ffdi.DeviceType == FILE_DEVICE_NAMED_PIPE) file_type = internal ? virt_blk : virt_pipe; else if (ffdi.DeviceType == FILE_DEVICE_DISK || ffdi.DeviceType == FILE_DEVICE_CD_ROM || ffdi.DeviceType == FILE_DEVICE_DFS || ffdi.DeviceType == FILE_DEVICE_VIRTUAL_DISK) { status = NtQueryInformationFile (h, &io, &fbi, sizeof fbi, FileBasicInformation); debug_printf ("NtQueryInformationFile: %y", status); if (!NT_SUCCESS (status)) file_type = virt_blk; else file_type = (fbi.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? virt_fsdir : virt_fsfile; } } NtClose (h); } return file_type; } virtual_ftype_t fhandler_procsys::exists () { return exists (NULL); } fhandler_procsys::fhandler_procsys (): fhandler_virtual () { } #define UNREADABLE_SYMLINK_CONTENT "<access denied>" bool fhandler_procsys::fill_filebuf () { char *fnamep; UNICODE_STRING path, target; OBJECT_ATTRIBUTES attr; NTSTATUS status; HANDLE h; tmp_pathbuf tp; size_t len; mk_unicode_path (&path); if (path.Buffer[path.Length / sizeof (WCHAR) - 1] == L'\\') path.Length -= sizeof (WCHAR); InitializeObjectAttributes (&attr, &path, OBJ_CASE_INSENSITIVE, NULL, NULL); status = NtOpenSymbolicLinkObject (&h, SYMBOLIC_LINK_QUERY, &attr)
random
[ { "content": "struct __sFILE64 *fopen64 (const char *, const char *);\n", "file_path": "libc/winsup/cygwin/winsup.h", "rank": 0, "score": 303894.749413499 }, { "content": "struct passwd *getpwnam (const char *);\n", "file_path": "libc/winsup/cygwin/winsup.h", "rank": 1, "score": 270290.29720563034 }, { "content": "struct hostent *cygwin_gethostbyname (const char *name);\n\n/* Don't enforce definition of in_addr_t. */\n\nuint32_t cygwin_inet_addr (const char *cp);\n\nint fcntl64 (int fd, int cmd, ...);\n\n#ifdef __cplusplus\n\n}\n\n#endif\n\n\n\n/* Note that MAX_PATH is defined in the windows headers */\n\n/* There is also PATH_MAX and MAXPATHLEN.\n\n PATH_MAX is from Posix and does include the trailing NUL.\n\n MAXPATHLEN is from Unix.\n\n\n\n Thou shalt *not* use CYG_MAX_PATH anymore. Use NT_MAX_PATH or\n\n dynamic allocation instead when accessing real files. Use\n\n MAX_PATH in case you need a convenient small buffer when creating\n\n names for synchronization objects or named pipes. */\n\n#define CYG_MAX_PATH (MAX_PATH)\n\n\n\n/* There's no define for the maximum path length the NT kernel can handle.\n", "file_path": "libc/winsup/cygwin/winsup.h", "rank": 2, "score": 254524.91435031744 }, { "content": "struct dntt_type_const\n\n{\n\n unsigned int extension:\t1;\n\n unsigned int kind:\t\t10;\n\n unsigned int global:\t\t1;\n\n unsigned int indirect:\t1;\n\n unsigned int location_type:\t3;\n\n unsigned int classmem:\t1;\n\n unsigned int unused:\t\t15;\n\n vtpointer name;\n\n CORE_ADDR location;\n\n dnttpointer type;\n\n unsigned int offset;\n\n unsigned int displacement;\n\n};\n\n\n\n/* DNTT_TYPE_TYPEDEF and DNTT_TYPE_TAGDEF:\n\n\n\n The same structure is used to describe typedefs and tagdefs.\n\n\n", "file_path": "libc/include/hp-symtab.h", "rank": 3, "score": 246372.82888560608 }, { "content": " unsigned int is_defined : 1;\n", "file_path": "libc/include/som/internal.h", "rank": 4, "score": 204250.10190736144 }, { "content": "int stat (const char *__restrict filename, struct stat *__restrict buf)\n\n{\n\n#if HOSTED\n\n gdb_parambuf_t parameters;\n\n struct gdb_stat gbuf;\n\n parameters[0] = (uint32_t) filename;\n\n parameters[1] = (uint32_t) strlen (filename) + 1;\n\n parameters[2] = (uint32_t) &gbuf;\n\n __hosted (HOSTED_STAT, parameters);\n\n __hosted_from_gdb_stat (&gbuf, buf);\n\n errno = __hosted_from_gdb_errno (parameters[1]);\n\n return parameters[0];\n\n#else\n\n errno = ENOSYS;\n\n return -1;\n\n#endif\n", "file_path": "libc/libgloss/m68k/io-stat.c", "rank": 5, "score": 202768.31746858833 }, { "content": "int stat (const char *__restrict filename, struct stat *__restrict buf)\n\n{\n\n#if HOSTED\n\n gdb_parambuf_t parameters;\n\n struct gdb_stat gbuf;\n\n parameters[0] = (uint32_t) filename;\n\n parameters[1] = (uint32_t) strlen (filename) + 1;\n\n parameters[2] = (uint32_t) &gbuf;\n\n __io_hosted (HOSTED_STAT, parameters);\n\n __hosted_from_gdb_stat (&gbuf, buf);\n\n errno = __hosted_from_gdb_errno (parameters[1]);\n\n return parameters[0];\n\n#else\n\n errno = ENOSYS;\n\n return -1;\n\n#endif\n", "file_path": "libc/libgloss/nios2/io-stat.c", "rank": 6, "score": 202768.31746858833 }, { "content": "#define IO stat\n", "file_path": "libc/libgloss/nios2/io-stat.c", "rank": 7, "score": 202751.1301149988 }, { "content": "#define IO stat\n", "file_path": "libc/libgloss/m68k/io-stat.c", "rank": 8, "score": 202751.1301149988 }, { "content": " unsigned int dir_loc;\n", "file_path": "libc/include/som/internal.h", "rank": 9, "score": 200437.6822553114 }, { "content": "struct dntt_type_struct\n\n{\n\n unsigned int extension:\t1;\n\n unsigned int kind:\t10;\n\n unsigned int declaration:\t2;\n\n unsigned int unused:\t\t19;\n\n dnttpointer firstfield;\n\n dnttpointer vartagfield;\n\n dnttpointer varlist;\n\n unsigned int bitlength;\n\n};\n\n\n\n/* DNTT_TYPE_UNION\n\n\n\n DNTT_TYPE_UNION is used to describe a C union.\n\n\n\n FIRSTFIELD is a DNTT pointer to the beginning of the field chain.\n\n\n\n BITLENGTH is the size of the union in bits. */\n\n\n", "file_path": "libc/include/hp-symtab.h", "rank": 10, "score": 190988.50728945085 }, { "content": " struct stat *buf;\n", "file_path": "libc/libgloss/hp74x/io.c", "rank": 11, "score": 189763.54730757268 }, { "content": "#ifndef _INTERNALS_H\n\n#define _INTERNALS_H\t1\n\n\n\n/* Internal data structures */\n\n\n\n/* Includes */\n\n\n\n#include <limits.h>\n\n#include <resolv.h>\n\n#include <setjmp.h>\n\n#include <signal.h>\n\n#include <unistd.h>\n\n#include <stackinfo.h>\n\n#include <sys/types.h>\n\n#include <reent.h>\n\n#include <bits/libc-tsd.h> /* for _LIBC_TSD_KEY_N */\n\n\n\nextern long int testandset (int *spinlock);\n\nextern int __compare_and_swap (long int *p, long int oldval, long int newval);\n\n\n\n#include \"libc-symbols.h\"\n\n#include \"pt-machine.h\"\n\n#include \"semaphore.h\"\n\n#include \"thread_dbP.h\"\n\n#include <hp-timing.h>\n\n\n\n#ifndef THREAD_GETMEM\n\n# define THREAD_GETMEM(descr, member) descr->member\n\n#endif\n\n#ifndef THREAD_GETMEM_NC\n\n# define THREAD_GETMEM_NC(descr, member) descr->member\n\n#endif\n\n#ifndef THREAD_SETMEM\n\n# define THREAD_SETMEM(descr, member, value) descr->member = (value)\n\n#endif\n\n#ifndef THREAD_SETMEM_NC\n\n# define THREAD_SETMEM_NC(descr, member, value) descr->member = (value)\n\n#endif\n\n\n\n/* Arguments passed to thread creation routine */\n\n\n\nstruct pthread_start_args {\n\n void * (*start_routine)(void *); /* function to run */\n\n void * arg; /* its argument */\n\n sigset_t mask; /* initial signal mask for thread */\n\n int schedpolicy; /* initial scheduling policy (if any) */\n\n struct __sched_param schedparam; /* initial scheduling parameters (if any) */\n\n};\n\n\n\n\n\n/* We keep thread specific data in a special data structure, a two-level\n\n array. The top-level array contains pointers to dynamically allocated\n\n arrays of a certain number of data pointers. So we can implement a\n\n sparse array. Each dynamic second-level array has\n\n\tPTHREAD_KEY_2NDLEVEL_SIZE\n\n entries. This value shouldn't be too large. */\n\n#define PTHREAD_KEY_2NDLEVEL_SIZE\t32\n\n\n\n/* We need to address PTHREAD_KEYS_MAX key with PTHREAD_KEY_2NDLEVEL_SIZE\n\n keys in each subarray. */\n\n#define PTHREAD_KEY_1STLEVEL_SIZE \\\n\n ((PTHREAD_KEYS_MAX + PTHREAD_KEY_2NDLEVEL_SIZE - 1) \\\n\n / PTHREAD_KEY_2NDLEVEL_SIZE)\n\n\n\ntypedef void (*destr_function)(void *);\n\n\n\nstruct pthread_key_struct {\n\n int in_use; /* already allocated? */\n\n destr_function destr; /* destruction routine */\n\n};\n\n\n\n\n\n#define PTHREAD_START_ARGS_INITIALIZER(fct) \\\n\n { (void *(*) (void *)) fct, NULL, {{0, }}, 0, { 0 } }\n\n\n\n/* The type of thread descriptors */\n\n\n\ntypedef struct _pthread_descr_struct * pthread_descr;\n\n\n\n/* Callback interface for removing the thread from waiting on an\n\n object if it is cancelled while waiting or about to wait.\n\n This hold a pointer to the object, and a pointer to a function\n\n which ``extricates'' the thread from its enqueued state.\n\n The function takes two arguments: pointer to the wait object,\n\n and a pointer to the thread. It returns 1 if an extrication\n\n actually occured, and hence the thread must also be signalled.\n\n It returns 0 if the thread had already been extricated. */\n\n\n\ntypedef struct _pthread_extricate_struct {\n\n void *pu_object;\n\n int (*pu_extricate_func)(void *, pthread_descr);\n\n} pthread_extricate_if;\n\n\n\n/* Atomic counter made possible by compare_and_swap */\n\n\n\nstruct pthread_atomic {\n\n long p_count;\n\n int p_spinlock;\n\n};\n\n\n\n/* Context info for read write locks. The pthread_rwlock_info structure\n\n is information about a lock that has been read-locked by the thread\n\n in whose list this structure appears. The pthread_rwlock_context\n\n is embedded in the thread context and contains a pointer to the\n\n head of the list of lock info structures, as well as a count of\n\n read locks that are untracked, because no info structure could be\n\n allocated for them. */\n\n\n\nstruct _pthread_rwlock_t;\n\n\n\ntypedef struct _pthread_rwlock_info {\n\n struct _pthread_rwlock_info *pr_next;\n\n struct _pthread_rwlock_t *pr_lock;\n\n int pr_lock_count;\n\n} pthread_readlock_info;\n\n\n\nstruct _pthread_descr_struct {\n\n union {\n\n struct {\n\n pthread_descr self;\t/* Pointer to this structure */\n\n } data;\n\n void *__padding[16];\n\n } p_header;\n\n pthread_descr p_nextlive, p_prevlive;\n\n /* Double chaining of active threads */\n\n pthread_descr p_nextwaiting; /* Next element in the queue holding the thr */\n\n pthread_descr p_nextlock;\t/* can be on a queue and waiting on a lock */\n\n pthread_t p_tid; /* Thread identifier */\n\n int p_pid; /* PID of Unix process */\n\n int p_priority; /* Thread priority (== 0 if not realtime) */\n\n struct _pthread_fastlock * p_lock; /* Spinlock for synchronized accesses */\n\n int p_signal; /* last signal received */\n\n sigjmp_buf * p_signal_jmp; /* where to siglongjmp on a signal or NULL */\n\n sigjmp_buf * p_cancel_jmp; /* where to siglongjmp on a cancel or NULL */\n\n char p_terminated; /* true if terminated e.g. by pthread_exit */\n\n char p_detached; /* true if detached */\n\n char p_exited; /* true if the assoc. process terminated */\n\n void * p_retval; /* placeholder for return value */\n\n int p_retcode; /* placeholder for return code */\n\n pthread_descr p_joining; /* thread joining on that thread or NULL */\n\n struct _pthread_cleanup_buffer * p_cleanup; /* cleanup functions */\n\n char p_cancelstate; /* cancellation state */\n\n char p_canceltype; /* cancellation type (deferred/async) */\n\n char p_canceled; /* cancellation request pending */\n\n struct _reent * p_reentp; /* pointer to reent struct */\n\n struct _reent p_reent; /* reentrant structure for newlib */\n\n int * p_h_errnop; /* pointer to used h_errno variable */\n\n int p_h_errno; /* error returned by last netdb function */\n\n char * p_in_sighandler; /* stack address of sighandler, or NULL */\n\n char p_sigwaiting; /* true if a sigwait() is in progress */\n\n struct pthread_start_args p_start_args; /* arguments for thread creation */\n\n void ** p_specific[PTHREAD_KEY_1STLEVEL_SIZE]; /* thread-specific data */\n\n void * p_libc_specific[_LIBC_TSD_KEY_N]; /* thread-specific data for libc */\n\n int p_userstack;\t\t/* nonzero if the user provided the stack */\n\n void *p_guardaddr;\t\t/* address of guard area or NULL */\n\n size_t p_guardsize;\t\t/* size of guard area */\n\n int p_nr; /* Index of descriptor in __pthread_handles */\n\n int p_report_events;\t\t/* Nonzero if events must be reported. */\n\n td_eventbuf_t p_eventbuf; /* Data for event. */\n\n struct pthread_atomic p_resume_count; /* number of times restart() was\n\n\t\t\t\t\t called on thread */\n\n char p_woken_by_cancel; /* cancellation performed wakeup */\n\n char p_condvar_avail;\t\t/* flag if conditional variable became avail */\n\n char p_sem_avail; /* flag if semaphore became available */\n\n pthread_extricate_if *p_extricate; /* See above */\n\n pthread_readlock_info *p_readlock_list; /* List of readlock info structs */\n\n pthread_readlock_info *p_readlock_free; /* Free list of structs */\n\n int p_untracked_readlock_count;\t/* Readlocks not tracked by list */\n\n struct __res_state *p_resp;\t/* Pointer to resolver state */\n\n struct __res_state p_res;\t/* per-thread resolver state */\n\n int p_inheritsched; /* copied from the thread attribute */\n\n#if HP_TIMING_AVAIL\n\n hp_timing_t p_cpuclock_offset; /* Initial CPU clock for thread. */\n\n#endif\n\n /* New elements must be added at the end. */\n\n} __attribute__ ((__aligned__(32))); /* We need to align the structure so that\n\n\t\t\t\t doubles are aligned properly. This is 8\n\n\t\t\t\t bytes on MIPS and 16 bytes on MIPS64.\n\n\t\t\t\t 32 bytes might give better cache\n\n\t\t\t\t utilization. */\n\n\n\n\n\n/* The type of thread handles. */\n\n\n\ntypedef struct pthread_handle_struct * pthread_handle;\n\n\n\nstruct pthread_handle_struct {\n\n struct _pthread_fastlock h_lock; /* Fast lock for sychronized access */\n\n pthread_descr h_descr; /* Thread descriptor or NULL if invalid */\n\n char * h_bottom; /* Lowest address in the stack thread */\n\n};\n\n\n\n/* The type of messages sent to the thread manager thread */\n\n\n\nstruct pthread_request {\n\n pthread_descr req_thread; /* Thread doing the request */\n\n enum { /* Request kind */\n\n REQ_CREATE, REQ_FREE, REQ_PROCESS_EXIT, REQ_MAIN_THREAD_EXIT,\n\n REQ_POST, REQ_DEBUG, REQ_KICK, REQ_FOR_EACH_THREAD\n\n } req_kind;\n\n union { /* Arguments for request */\n\n struct { /* For REQ_CREATE: */\n\n const pthread_attr_t * attr; /* thread attributes */\n\n void * (*fn)(void *); /* start function */\n\n void * arg; /* argument to start function */\n\n sigset_t mask; /* signal mask */\n\n } create;\n\n struct { /* For REQ_FREE: */\n\n pthread_t thread_id; /* identifier of thread to free */\n\n } free;\n\n struct { /* For REQ_PROCESS_EXIT: */\n\n int code; /* exit status */\n\n } exit;\n\n void * post; /* For REQ_POST: the semaphore */\n\n struct {\t\t\t/* For REQ_FOR_EACH_THREAD: callback */\n\n void (*fn)(void *, pthread_descr);\n\n void *arg;\n\n } for_each;\n\n } req_args;\n\n};\n\n\n\n\n\n/* Signals used for suspend/restart and for cancellation notification. */\n\n\n\nextern int __pthread_sig_restart;\n\nextern int __pthread_sig_cancel;\n\n\n\n/* Signal used for interfacing with gdb */\n\n\n\nextern int __pthread_sig_debug;\n\n\n\n/* Global array of thread handles, used for validating a thread id\n\n and retrieving the corresponding thread descriptor. Also used for\n\n mapping the available stack segments. */\n\n\n\nextern struct pthread_handle_struct __pthread_handles[PTHREAD_THREADS_MAX];\n\n\n\n/* Descriptor of the initial thread */\n\n\n\nextern struct _pthread_descr_struct __pthread_initial_thread;\n\n\n\n/* Descriptor of the manager thread */\n\n\n\nextern struct _pthread_descr_struct __pthread_manager_thread;\n\n\n\n/* Descriptor of the main thread */\n\n\n\nextern pthread_descr __pthread_main_thread;\n\n\n\n/* Limit between the stack of the initial thread (above) and the\n\n stacks of other threads (below). Aligned on a STACK_SIZE boundary.\n\n Initially 0, meaning that the current thread is (by definition)\n\n the initial thread. */\n\n\n\nextern char *__pthread_initial_thread_bos;\n\n\n\n/* Indicate whether at least one thread has a user-defined stack (if 1),\n\n or all threads have stacks supplied by LinuxThreads (if 0). */\n\n\n\nextern int __pthread_nonstandard_stacks;\n\n\n\n/* File descriptor for sending requests to the thread manager.\n\n Initially -1, meaning that __pthread_initialize_manager must be called. */\n\n\n\nextern int __pthread_manager_request;\n\n\n\n/* Other end of the pipe for sending requests to the thread manager. */\n\n\n\nextern int __pthread_manager_reader;\n\n\n\n/* Limits of the thread manager stack. */\n\n\n\nextern char *__pthread_manager_thread_bos;\n\nextern char *__pthread_manager_thread_tos;\n\n\n\n#ifdef FLOATING_STACKS\n\n/* Maximum stack size. */\n\nextern size_t __pthread_max_stacksize;\n\n#endif\n\n\n\n/* Pending request for a process-wide exit */\n\n\n\nextern int __pthread_exit_requested, __pthread_exit_code;\n\n\n\n/* Set to 1 by gdb if we're debugging */\n\n\n\nextern volatile int __pthread_threads_debug;\n\n\n\n/* Globally enabled events. */\n\nextern volatile td_thr_events_t __pthread_threads_events;\n\n\n\n/* Pointer to descriptor of thread with last event. */\n\nextern volatile pthread_descr __pthread_last_event;\n\n\n\n/* Flag which tells whether we are executing on SMP kernel. */\n\nextern int __pthread_smp_kernel;\n\n\n\n/* Return the handle corresponding to a thread id */\n\n\n\nstatic inline pthread_handle thread_handle(pthread_t id)\n\n{\n\n return &__pthread_handles[id % PTHREAD_THREADS_MAX];\n\n}\n\n\n\n/* Validate a thread handle. Must have acquired h->h_spinlock before. */\n\n\n\nstatic inline int invalid_handle(pthread_handle h, pthread_t id)\n\n{\n\n return h->h_descr == NULL || h->h_descr->p_tid != id || h->h_descr->p_terminated;\n\n}\n\n\n\nstatic inline int nonexisting_handle(pthread_handle h, pthread_t id)\n\n{\n\n return h->h_descr == NULL || h->h_descr->p_tid != id;\n\n}\n\n\n\n/* Fill in defaults left unspecified by pt-machine.h. */\n\n\n\n/* We round up a value with page size. */\n\n#ifndef page_roundup\n\n#define page_roundup(v,p) ((((size_t) (v)) + (p) - 1) & ~((p) - 1))\n\n#endif\n\n\n\n/* The page size we can get from the system. This should likely not be\n\n changed by the machine file but, you never know. */\n\n#ifndef PAGE_SIZE\n\n#define PAGE_SIZE (sysconf (_SC_PAGE_SIZE))\n\n#endif\n\n\n\n/* The max size of the thread stack segments. If the default\n\n THREAD_SELF implementation is used, this must be a power of two and\n\n a multiple of PAGE_SIZE. */\n\n#ifndef STACK_SIZE\n\n#define STACK_SIZE (2 * 1024 * 1024)\n\n#endif\n\n\n\n/* The initial size of the thread stack. Must be a multiple of PAGE_SIZE. */\n\n#ifndef INITIAL_STACK_SIZE\n\n#define INITIAL_STACK_SIZE (4 * PAGE_SIZE)\n\n#endif\n\n\n\n/* Size of the thread manager stack. The \"- 32\" avoids wasting space\n\n with some malloc() implementations. */\n\n#ifndef THREAD_MANAGER_STACK_SIZE\n\n#define THREAD_MANAGER_STACK_SIZE (2 * PAGE_SIZE - 32)\n\n#endif\n\n\n\n/* The base of the \"array\" of thread stacks. The array will grow down from\n\n here. Defaults to the calculated bottom of the initial application\n\n stack. */\n\n#ifndef THREAD_STACK_START_ADDRESS\n\n#define THREAD_STACK_START_ADDRESS __pthread_initial_thread_bos\n\n#endif\n\n\n\n/* Get some notion of the current stack. Need not be exactly the top\n\n of the stack, just something somewhere in the current frame. */\n\n#ifndef CURRENT_STACK_FRAME\n\n#define CURRENT_STACK_FRAME ({ char __csf; &__csf; })\n\n#endif\n\n\n\n/* Recover thread descriptor for the current thread */\n\n\n\nextern pthread_descr __pthread_find_self (void) __attribute__ ((__const__));\n\n\n\nstatic inline pthread_descr thread_self (void) __attribute__ ((__const__));\n\nstatic inline pthread_descr thread_self (void)\n\n{\n\n#ifdef THREAD_SELF\n\n return THREAD_SELF;\n\n#else\n\n char *sp = CURRENT_STACK_FRAME;\n\n if (sp >= __pthread_initial_thread_bos)\n\n return &__pthread_initial_thread;\n\n else if (sp >= __pthread_manager_thread_bos\n\n\t && sp < __pthread_manager_thread_tos)\n\n return &__pthread_manager_thread;\n\n else if (__pthread_nonstandard_stacks)\n\n return __pthread_find_self();\n\n else\n\n#ifdef _STACK_GROWS_DOWN\n\n return (pthread_descr)(((unsigned long)sp | (STACK_SIZE-1))+1) - 1;\n\n#else\n\n return (pthread_descr)((unsigned long)sp &~ (STACK_SIZE-1));\n\n#endif\n\n#endif\n\n}\n\n\n\n/* If MEMORY_BARRIER isn't defined in pt-machine.h, assume the architecture\n\n doesn't need a memory barrier instruction (e.g. Intel x86). Still we\n\n need the compiler to respect the barrier and emit all outstanding\n\n operations which modify memory. Some architectures distinguish between\n\n full, read and write barriers. */\n\n\n\n#ifndef MEMORY_BARRIER\n\n#define MEMORY_BARRIER() asm (\"\" : : : \"memory\")\n\n#endif\n\n#ifndef READ_MEMORY_BARRIER\n\n#define READ_MEMORY_BARRIER() MEMORY_BARRIER()\n\n#endif\n\n#ifndef WRITE_MEMORY_BARRIER\n\n#define WRITE_MEMORY_BARRIER() MEMORY_BARRIER()\n\n#endif\n\n\n\n/* Max number of times we must spin on a spinlock calling sched_yield().\n\n After MAX_SPIN_COUNT iterations, we put the calling thread to sleep. */\n\n\n\n#ifndef MAX_SPIN_COUNT\n\n#define MAX_SPIN_COUNT 50\n\n#endif\n\n\n\n/* Max number of times the spinlock in the adaptive mutex implementation\n\n spins actively on SMP systems. */\n\n\n\n#ifndef MAX_ADAPTIVE_SPIN_COUNT\n\n#define MAX_ADAPTIVE_SPIN_COUNT 100\n\n#endif\n\n\n\n/* Duration of sleep (in nanoseconds) when we can't acquire a spinlock\n\n after MAX_SPIN_COUNT iterations of sched_yield().\n\n With the 2.0 and 2.1 kernels, this MUST BE > 2ms.\n\n (Otherwise the kernel does busy-waiting for realtime threads,\n\n giving other threads no chance to run.) */\n\n\n\n#ifndef SPIN_SLEEP_DURATION\n\n#define SPIN_SLEEP_DURATION 2000001\n\n#endif\n\n\n\n/* Debugging */\n\n\n\n#ifdef DEBUG\n\n#include <assert.h>\n\n#define ASSERT assert\n\n#define MSG __pthread_message\n\n#else\n\n#define ASSERT(x)\n\n#define MSG(msg,arg...)\n\n#endif\n\n\n\n/* Internal global functions */\n\n\n\nextern void __pthread_do_exit (void *retval, char *currentframe)\n\n __attribute__ ((__noreturn__));\n\nextern void __pthread_destroy_specifics (void);\n\nextern void __pthread_perform_cleanup (char *currentframe);\n\nextern void __pthread_init_max_stacksize (void);\n\nextern int __pthread_initialize_manager (void);\n\nextern void __pthread_message (char * fmt, ...);\n\nextern int __pthread_manager (void *reqfd);\n\nextern int __pthread_manager_event (void *reqfd);\n\nextern void __pthread_manager_sighandler (int sig);\n\nextern void __pthread_reset_main_thread (void);\n\nextern void __pthread_once_fork_prepare (void);\n\nextern void __pthread_once_fork_parent (void);\n\nextern void __pthread_once_fork_child (void);\n\nextern void __flockfilelist (void);\n\nextern void __funlockfilelist (void);\n\nextern void __fresetlockfiles (void);\n\nextern void __pthread_manager_adjust_prio (int thread_prio);\n\nextern void __pthread_initialize_minimal (void);\n\n\n\nextern int __pthread_attr_setguardsize (pthread_attr_t *__attr,\n\n\t\t\t\t\tsize_t __guardsize);\n\nextern int __pthread_attr_getguardsize (const pthread_attr_t *__attr,\n\n\t\t\t\t\tsize_t *__guardsize);\n\nextern int __pthread_attr_setstackaddr (pthread_attr_t *__attr,\n\n\t\t\t\t\tvoid *__stackaddr);\n\nextern int __pthread_attr_getstackaddr (const pthread_attr_t *__attr,\n\n\t\t\t\t\tvoid **__stackaddr);\n\nextern int __pthread_attr_setstacksize (pthread_attr_t *__attr,\n\n\t\t\t\t\tsize_t __stacksize);\n\nextern int __pthread_attr_getstacksize (const pthread_attr_t *__attr,\n\n\t\t\t\t\tsize_t *__stacksize);\n\nextern int __pthread_attr_setstack (pthread_attr_t *__attr, void *__stackaddr,\n\n\t\t\t\t size_t __stacksize);\n\nextern int __pthread_attr_getstack (const pthread_attr_t *__attr, void **__stackaddr,\n\n\t\t\t\t size_t *__stacksize);\n\nextern int __pthread_getconcurrency (void);\n\nextern int __pthread_setconcurrency (int __level);\n\nextern int __pthread_mutex_timedlock (pthread_mutex_t *__mutex,\n\n\t\t\t\t const struct timespec *__abstime);\n\nextern int __pthread_mutexattr_getpshared (const pthread_mutexattr_t *__attr,\n\n\t\t\t\t\t int *__pshared);\n\nextern int __pthread_mutexattr_setpshared (pthread_mutexattr_t *__attr,\n\n\t\t\t\t\t int __pshared);\n\nextern int __pthread_mutexattr_gettype (const pthread_mutexattr_t *__attr,\n\n\t\t\t\t\tint *__kind);\n\nextern void __pthread_kill_other_threads_np (void);\n\n\n\nextern void __pthread_restart_old(pthread_descr th);\n\nextern void __pthread_suspend_old(pthread_descr self);\n\nextern int __pthread_timedsuspend_old(pthread_descr self, const struct timespec *abs);\n\n\n\nextern void __pthread_restart_new(pthread_descr th);\n\nextern void __pthread_suspend_new(pthread_descr self);\n\nextern int __pthread_timedsuspend_new(pthread_descr self, const struct timespec *abs);\n\n\n\nextern void __pthread_wait_for_restart_signal(pthread_descr self);\n\n\n\nextern int __pthread_yield (void);\n\n\n\nextern int __pthread_rwlock_timedrdlock (pthread_rwlock_t *__restrict __rwlock,\n\n\t\t\t\t\t __const struct timespec *__restrict\n\n\t\t\t\t\t __abstime);\n\nextern int __pthread_rwlock_timedwrlock (pthread_rwlock_t *__restrict __rwlock,\n\n\t\t\t\t\t __const struct timespec *__restrict\n\n\t\t\t\t\t __abstime);\n\nextern int __pthread_rwlockattr_destroy (pthread_rwlockattr_t *__attr);\n\n\n\nextern int __pthread_barrierattr_getpshared (__const pthread_barrierattr_t *\n\n\t\t\t\t\t __restrict __attr,\n\n\t\t\t\t\t int *__restrict __pshared);\n\n\n\nextern int __pthread_spin_lock (pthread_spinlock_t *__lock);\n\nextern int __pthread_spin_trylock (pthread_spinlock_t *__lock);\n\nextern int __pthread_spin_unlock (pthread_spinlock_t *__lock);\n\nextern int __pthread_spin_init (pthread_spinlock_t *__lock, int __pshared);\n\nextern int __pthread_spin_destroy (pthread_spinlock_t *__lock);\n\n\n\nextern int __pthread_clock_gettime (hp_timing_t freq, struct timespec *tp);\n\nextern void __pthread_clock_settime (hp_timing_t offset);\n\n\n\n\n\n/* Global pointers to old or new suspend functions */\n\n\n\nextern void (*__pthread_restart)(pthread_descr);\n\nextern void (*__pthread_suspend)(pthread_descr);\n\nextern int (*__pthread_timedsuspend)(pthread_descr, const struct timespec *);\n\n\n\n/* Prototypes for the function without cancelation support when the\n\n normal version has it. */\n\nextern int __libc_close (int fd);\n\nextern int __libc_nanosleep (const struct timespec *requested_time,\n\n\t\t\t struct timespec *remaining);\n\n/* Prototypes for some of the new semaphore functions. */\n\nextern int __new_sem_post (sem_t * sem);\n\nextern int __new_sem_init (sem_t *__sem, int __pshared, unsigned int __value);\n\nextern int __new_sem_wait (sem_t *__sem);\n\nextern int __new_sem_trywait (sem_t *__sem);\n\nextern int __new_sem_getvalue (sem_t *__restrict __sem, int *__restrict __sval);\n\nextern int __new_sem_destroy (sem_t *__sem);\n\n\n\n/* Prototypes for compatibility functions. */\n\nextern int __pthread_attr_init_2_1 (pthread_attr_t *__attr);\n\nextern int __pthread_attr_init_2_0 (pthread_attr_t *__attr);\n\nextern int __pthread_create_2_1 (pthread_t *__restrict __thread1,\n\n\t\t\t\t const pthread_attr_t *__attr,\n\n\t\t\t\t void *(*__start_routine) (void *),\n\n\t\t\t\t void *__restrict __arg);\n\nextern int __pthread_create_2_0 (pthread_t *__restrict __thread1,\n\n\t\t\t\t const pthread_attr_t *__attr,\n\n\t\t\t\t void *(*__start_routine) (void *),\n\n\t\t\t\t void *__restrict arg);\n\n\n\n/* The functions called the signal events. */\n\nextern void __linuxthreads_create_event (void);\n\nextern void __linuxthreads_death_event (void);\n\nextern void __linuxthreads_reap_event (void);\n\n\n\n/* This function is called to initialize the pthread library. */\n\nextern void __pthread_initialize (void);\n\n\n", "file_path": "libc/newlib/libc/sys/linux/linuxthreads/internals.h", "rank": 12, "score": 188739.1953783504 }, { "content": "#ifndef CALLBACK_H\n\n#define CALLBACK_H\n\n\n\n/* ??? The reason why we check for va_start here should be documented. */\n\n\n\n#ifndef va_start\n\n#include <ansidecl.h>\n\n#include <stdarg.h>\n\n#endif\n\n/* Needed for enum bfd_endian. */\n\n#include \"bfd.h\"\n\n\f\n\n/* Mapping of host/target values. */\n\n/* ??? For debugging purposes, one might want to add a string of the\n\n name of the symbol. */\n\n\n\ntypedef struct {\n\n int host_val;\n\n int target_val;\n\n} CB_TARGET_DEFS_MAP;\n\n\n\n#define MAX_CALLBACK_FDS 10\n\n\n\n/* Forward decl for stat/fstat. */\n\nstruct stat;\n\n\n\ntypedef struct host_callback_struct host_callback;\n\n\n\nstruct host_callback_struct \n\n{\n\n int (*close) (host_callback *,int);\n\n int (*get_errno) (host_callback *);\n\n int (*isatty) (host_callback *, int);\n\n int (*lseek) (host_callback *, int, long , int);\n\n int (*open) (host_callback *, const char*, int mode);\n\n int (*read) (host_callback *,int, char *, int);\n\n int (*read_stdin) ( host_callback *, char *, int);\n\n int (*rename) (host_callback *, const char *, const char *);\n\n int (*system) (host_callback *, const char *);\n\n long (*time) (host_callback *, long *);\n\n int (*unlink) (host_callback *, const char *);\n\n int (*write) (host_callback *,int, const char *, int);\n\n int (*write_stdout) (host_callback *, const char *, int);\n\n void (*flush_stdout) (host_callback *);\n\n int (*write_stderr) (host_callback *, const char *, int);\n\n void (*flush_stderr) (host_callback *);\n\n int (*stat) (host_callback *, const char *, struct stat *);\n\n int (*fstat) (host_callback *, int, struct stat *);\n\n int (*lstat) (host_callback *, const char *, struct stat *);\n\n int (*ftruncate) (host_callback *, int, long);\n\n int (*truncate) (host_callback *, const char *, long);\n\n int (*pipe) (host_callback *, int *);\n\n\n\n /* Called by the framework when a read call has emptied a pipe buffer. */\n\n void (*pipe_empty) (host_callback *, int read_fd, int write_fd);\n\n\n\n /* Called by the framework when a write call makes a pipe buffer\n\n non-empty. */\n\n void (*pipe_nonempty) (host_callback *, int read_fd, int write_fd);\n\n\n\n /* When present, call to the client to give it the oportunity to\n\n poll any io devices for a request to quit (indicated by a nonzero\n\n return value). */\n\n int (*poll_quit) (host_callback *);\n\n\n\n /* Used when the target has gone away, so we can close open\n\n handles and free memory etc etc. */\n\n int (*shutdown) (host_callback *);\n\n int (*init) (host_callback *);\n\n\n\n /* depreciated, use vprintf_filtered - Talk to the user on a console. */\n\n void (*printf_filtered) (host_callback *, const char *, ...);\n\n\n\n /* Talk to the user on a console. */\n\n void (*vprintf_filtered) (host_callback *, const char *, va_list);\n\n\n\n /* Same as vprintf_filtered but to stderr. */\n\n void (*evprintf_filtered) (host_callback *, const char *, va_list);\n\n\n\n /* Print an error message and \"exit\".\n\n In the case of gdb \"exiting\" means doing a longjmp back to the main\n\n command loop. */\n\n void (*error) (host_callback *, const char *, ...)\n\n#ifdef __GNUC__\n\n __attribute__ ((__noreturn__))\n\n#endif\n\n ;\n\n\n\n int last_errno;\t\t/* host format */\n\n\n\n int fdmap[MAX_CALLBACK_FDS];\n\n /* fd_buddy is used to contruct circular lists of target fds that point to\n\n the same host fd. A uniquely mapped fd points to itself; for a closed\n\n one, fd_buddy has the value -1. The host file descriptors for stdin /\n\n stdout / stderr are never closed by the simulators, so they are put\n\n in a special fd_buddy circular list which also has MAX_CALLBACK_FDS\n\n as a member. */\n\n /* ??? We don't have a callback entry for dup, although it is trival to\n\n implement now. */\n\n short fd_buddy[MAX_CALLBACK_FDS+1];\n\n\n\n /* 0 = none, >0 = reader (index of writer),\n\n <0 = writer (negative index of reader).\n\n If abs (ispipe[N]) == N, then N is an end of a pipe whose other\n\n end is closed. */\n\n short ispipe[MAX_CALLBACK_FDS];\n\n\n\n /* A writer stores the buffer at its index. Consecutive writes\n\n realloc the buffer and add to the size. The reader indicates the\n\n read part in its .size, until it has consumed it all, at which\n\n point it deallocates the buffer and zeroes out both sizes. */\n\n struct pipe_write_buffer\n\n {\n\n int size;\n\n char *buffer;\n\n } pipe_buffer[MAX_CALLBACK_FDS];\n\n\n\n /* System call numbers. */\n\n CB_TARGET_DEFS_MAP *syscall_map;\n\n /* Errno values. */\n\n CB_TARGET_DEFS_MAP *errno_map;\n\n /* Flags to the open system call. */\n\n CB_TARGET_DEFS_MAP *open_map;\n\n /* Signal numbers. */\n\n CB_TARGET_DEFS_MAP *signal_map;\n\n /* Layout of `stat' struct.\n\n The format is a series of \"name,length\" pairs separated by colons.\n\n Empty space is indicated with a `name' of \"space\".\n\n All padding must be explicitly mentioned.\n\n Lengths are in bytes. If this needs to be extended to bits,\n\n use \"name.bits\".\n\n Example: \"st_dev,4:st_ino,4:st_mode,4:...\" */\n\n const char *stat_map;\n\n\n\n enum bfd_endian target_endian;\n\n\n\n /* Size of an \"int\" on the target (for syscalls whose ABI uses \"int\").\n\n This must include padding, and only padding-at-higher-address is\n\n supported. For example, a 64-bit target with 32-bit int:s which\n\n are padded to 64 bits when in an array, should supposedly set this\n\n to 8. The default is 4 which matches ILP32 targets and 64-bit\n\n targets with 32-bit ints and no padding. */\n\n int target_sizeof_int;\n\n\n\n /* Marker for those wanting to do sanity checks.\n\n This should remain the last member of this struct to help catch\n\n miscompilation errors. */\n\n#define HOST_CALLBACK_MAGIC 4705 /* teds constant */\n\n int magic;\n\n};\n\n\n\nextern host_callback default_callback;\n\n\f\n\n/* Canonical versions of system call numbers.\n\n It's not intended to willy-nilly throw every system call ever heard\n\n of in here. Only include those that have an important use.\n\n ??? One can certainly start a discussion over the ones that are currently\n\n here, but that will always be true. */\n\n\n\n/* These are used by the ANSI C support of libc. */\n\n#define\tCB_SYS_exit\t1\n\n#define\tCB_SYS_open\t2\n\n#define\tCB_SYS_close\t3\n\n#define\tCB_SYS_read\t4\n\n#define\tCB_SYS_write\t5\n\n#define\tCB_SYS_lseek\t6\n\n#define\tCB_SYS_unlink\t7\n\n#define\tCB_SYS_getpid\t8\n\n#define\tCB_SYS_kill\t9\n\n#define CB_SYS_fstat 10\n\n/*#define CB_SYS_sbrk\t11 - not currently a system call, but reserved. */\n\n\n\n/* ARGV support. */\n\n#define CB_SYS_argvlen\t12\n\n#define CB_SYS_argv\t13\n\n\n\n/* These are extras added for one reason or another. */\n\n#define CB_SYS_chdir\t14\n\n#define CB_SYS_stat\t15\n\n#define CB_SYS_chmod \t16\n\n#define CB_SYS_utime \t17\n\n#define CB_SYS_time \t18\n\n\n\n/* More standard syscalls. */\n\n#define CB_SYS_lstat 19\n\n#define CB_SYS_rename\t20\n\n#define CB_SYS_truncate\t21\n\n#define CB_SYS_ftruncate 22\n\n#define CB_SYS_pipe \t23\n\n\n\n/* New ARGV support. */\n\n#define CB_SYS_argc\t24\n\n#define CB_SYS_argnlen\t25\n\n#define CB_SYS_argn\t26\n\n\f\n\n/* Struct use to pass and return information necessary to perform a\n\n system call. */\n\n/* FIXME: Need to consider target word size. */\n\n\n\ntypedef struct cb_syscall {\n\n /* The target's value of what system call to perform. */\n\n int func;\n\n /* The arguments to the syscall. */\n\n long arg1, arg2, arg3, arg4;\n\n\n\n /* The result. */\n\n long result;\n\n /* Some system calls have two results. */\n\n long result2;\n\n /* The target's errno value, or 0 if success.\n\n This is converted to the target's value with host_to_target_errno. */\n\n int errcode;\n\n\n\n /* Working space to be used by memory read/write callbacks. */\n\n PTR p1;\n\n PTR p2;\n\n long x1,x2;\n\n\n\n /* Callbacks for reading/writing memory (e.g. for read/write syscalls).\n\n ??? long or unsigned long might be better to use for the `count'\n\n argument here. We mimic sim_{read,write} for now. Be careful to\n\n test any changes with -Wall -Werror, mixed signed comparisons\n\n will get you. */\n\n int (*read_mem) (host_callback * /*cb*/, struct cb_syscall * /*sc*/,\n\n\t\t unsigned long /*taddr*/, char * /*buf*/,\n\n\t\t int /*bytes*/);\n\n int (*write_mem) (host_callback * /*cb*/, struct cb_syscall * /*sc*/,\n\n\t\t unsigned long /*taddr*/, const char * /*buf*/,\n\n\t\t int /*bytes*/);\n\n\n\n /* For sanity checking, should be last entry. */\n\n int magic;\n\n} CB_SYSCALL;\n\n\n\n/* Magic number sanity checker. */\n\n#define CB_SYSCALL_MAGIC 0x12344321\n\n\n\n/* Macro to initialize CB_SYSCALL. Called first, before filling in\n\n any fields. */\n\n#define CB_SYSCALL_INIT(sc) \\\n\ndo { \\\n\n memset ((sc), 0, sizeof (*(sc))); \\\n\n (sc)->magic = CB_SYSCALL_MAGIC; \\\n\n} while (0)\n\n\f\n\n/* Return codes for various interface routines. */\n\n\n\ntypedef enum {\n\n CB_RC_OK = 0,\n\n /* generic error */\n\n CB_RC_ERR,\n\n /* either file not found or no read access */\n\n CB_RC_ACCESS,\n\n CB_RC_NO_MEM\n\n} CB_RC;\n\n\n\n/* Read in target values for system call numbers, errno values, signals. */\n\nCB_RC cb_read_target_syscall_maps (host_callback *, const char *);\n\n\n\n/* Translate target to host syscall function numbers. */\n\nint cb_target_to_host_syscall (host_callback *, int);\n\n\n\n/* Translate host to target errno value. */\n\nint cb_host_to_target_errno (host_callback *, int);\n\n\n\n/* Translate target to host open flags. */\n\nint cb_target_to_host_open (host_callback *, int);\n\n\n\n/* Translate target signal number to host. */\n\nint cb_target_to_host_signal (host_callback *, int);\n\n\n\n/* Translate host signal number to target. */\n\nint cb_host_to_gdb_signal (host_callback *, int);\n\n\n\n/* Translate host stat struct to target.\n\n If stat struct ptr is NULL, just compute target stat struct size.\n\n Result is size of target stat struct or 0 if error. */\n\nint cb_host_to_target_stat (host_callback *, const struct stat *, PTR);\n\n\n\n/* Translate a value to target endian. */\n\nvoid cb_store_target_endian (host_callback *, char *, int, long);\n\n\n\n/* Tests for special fds. */\n\nint cb_is_stdin (host_callback *, int);\n\nint cb_is_stdout (host_callback *, int);\n\nint cb_is_stderr (host_callback *, int);\n\n\n\n/* Read a string out of the target. */\n\nint cb_get_string (host_callback *, CB_SYSCALL *, char *, int, unsigned long);\n\n\n\n/* Perform a system call. */\n\nCB_RC cb_syscall (host_callback *, CB_SYSCALL *);\n\n\n", "file_path": "libc/include/gdb/callback.h", "rank": 13, "score": 187336.85866850766 }, { "content": "struct DIR;\n", "file_path": "libc/libgloss/visium/io-stubs.c", "rank": 14, "score": 187206.2857209767 }, { "content": "char buf[0x10000];\n", "file_path": "libc/libgloss/testsuite/libgloss.all/struct.c", "rank": 15, "score": 187200.50369116984 }, { "content": "#ifndef\t_LINK_H\n\n#define\t_LINK_H\t1\n\n\n\n#include <features.h>\n\n#include <elf.h>\n\n#include <dlfcn.h>\n\n#include <sys/types.h>\n\n\n\n#define DT_THISPROCNUM 0\n\n/* We use this macro to refer to ELF types independent of the native wordsize.\n\n `ElfW(TYPE)' is used in place of `Elf32_TYPE' or `Elf64_TYPE'. */\n\n#define ElfW(type)\t_ElfW (Elf, __ELF_NATIVE_CLASS, type)\n\n#define _ElfW(e,w,t)\t_ElfW_1 (e, w, _##t)\n\n#define _ElfW_1(e,w,t)\te##w##t\n\n\n\n#include <sys/elfclass.h>\t\t/* Defines __ELF_NATIVE_CLASS. */\n\n#include <sys/link.h>\n\n#include <dl-lookupcfg.h>\n\n\n\n/* Rendezvous structure used by the run-time dynamic linker to communicate\n\n details of shared object loading to the debugger. If the executable's\n\n dynamic section has a DT_DEBUG element, the run-time linker sets that\n\n element's value to the address where this structure can be found. */\n\n\n\nstruct r_debug\n\n {\n\n int r_version;\t\t/* Version number for this protocol. */\n\n\n\n struct link_map *r_map;\t/* Head of the chain of loaded objects. */\n\n\n\n /* This is the address of a function internal to the run-time linker,\n\n that will always be called when the linker begins to map in a\n\n library or unmap it, and again when the mapping change is complete.\n\n The debugger can set a breakpoint at this address if it wants to\n\n notice shared object mapping changes. */\n\n ElfW(Addr) r_brk;\n\n enum\n\n {\n\n\t/* This state value describes the mapping change taking place when\n\n\t the `r_brk' address is called. */\n\n\tRT_CONSISTENT,\t\t/* Mapping change is complete. */\n\n\tRT_ADD,\t\t\t/* Beginning to add a new object. */\n\n\tRT_DELETE\t\t/* Beginning to remove an object mapping. */\n\n } r_state;\n\n\n\n ElfW(Addr) r_ldbase;\t/* Base address the linker is loaded at. */\n\n };\n\n\n\n/* This is the instance of that structure used by the dynamic linker. */\n\nextern struct r_debug _r_debug;\n\n\n\n/* This symbol refers to the \"dynamic structure\" in the `.dynamic' section\n\n of whatever module refers to `_DYNAMIC'. So, to find its own\n\n `struct r_debug', a program could do:\n\n for (dyn = _DYNAMIC; dyn->d_tag != DT_NULL; ++dyn)\n\n if (dyn->d_tag == DT_DEBUG)\n\n\t r_debug = (struct r_debug *) dyn->d_un.d_ptr;\n\n */\n\nextern ElfW(Dyn) _DYNAMIC[];\n\n\n\n\n\n/* Some internal data structures of the dynamic linker used in the\n\n linker map. We only provide forward declarations. */\n\nstruct libname_list;\n\nstruct r_found_version;\n\nstruct r_search_path_elem;\n\n\n\n/* Forward declaration. */\n\nstruct link_map;\n\n\n\n/* Structure to describe a single list of scope elements. The lookup\n\n functions get passed an array of pointers to such structures. */\n\nstruct r_scope_elem\n\n{\n\n /* Array of maps for the scope. */\n\n struct link_map **r_list;\n\n /* Number of entries in the scope. */\n\n unsigned int r_nlist;\n\n};\n\n\n\n\n\n/* Structure to record search path and allocation mechanism. */\n\nstruct r_search_path_struct\n\n {\n\n struct r_search_path_elem **dirs;\n\n int malloced;\n\n };\n\n\n\n\n\n/* Structure describing a loaded shared object. The `l_next' and `l_prev'\n\n members form a chain of all the shared objects loaded at startup.\n\n\n\n These data structures exist in space used by the run-time dynamic linker;\n\n modifying them may have disastrous results.\n\n\n\n This data structure might change in future, if necessary. User-level\n\n programs must avoid defining objects of this type. */\n\n\n\nstruct link_map\n\n {\n\n /* These first few members are part of the protocol with the debugger.\n\n This is the same format used in SVR4. */\n\n\n\n ElfW(Addr) l_addr;\t\t/* Base address shared object is loaded at. */\n\n char *l_name;\t\t/* Absolute file name object was found in. */\n\n ElfW(Dyn) *l_ld;\t\t/* Dynamic section of the shared object. */\n\n struct link_map *l_next, *l_prev; /* Chain of loaded objects. */\n\n\n\n /* All following members are internal to the dynamic linker.\n\n They may change without notice. */\n\n\n\n struct libname_list *l_libname;\n\n /* Indexed pointers to dynamic section.\n\n [0,DT_NUM) are indexed by the processor-independent tags.\n\n [DT_NUM,DT_NUM+DT_THISPROCNUM) are indexed by the tag minus DT_LOPROC.\n\n [DT_NUM+DT_THISPROCNUM,DT_NUM+DT_THISPROCNUM+DT_EXTRANUM) are indexed\n\n by DT_EXTRATAGIDX(tagvalue) and\n\n [DT_NUM+DT_THISPROCNUM+DT_VERSIONTAGNUM,\n\n DT_NUM+DT_THISPROCNUM+DT_VERSIONTAGNUM+DT_EXTRANUM)\n\n are indexed by DT_EXTRATAGIDX(tagvalue) (see <elf.h>). */\n\n\n\n ElfW(Dyn) *l_info[DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM\n\n\t\t + DT_EXTRANUM];\n\n const ElfW(Phdr) *l_phdr;\t/* Pointer to program header table in core. */\n\n ElfW(Addr) l_entry;\t\t/* Entry point location. */\n\n ElfW(Half) l_phnum;\t\t/* Number of program header entries. */\n\n ElfW(Half) l_ldnum;\t/* Number of dynamic segment entries. */\n\n\n\n /* Array of DT_NEEDED dependencies and their dependencies, in\n\n dependency order for symbol lookup (with and without\n\n duplicates). There is no entry before the dependencies have\n\n been loaded. */\n\n struct r_scope_elem l_searchlist;\n\n\n\n /* We need a special searchlist to process objects marked with\n\n DT_SYMBOLIC. */\n\n struct r_scope_elem l_symbolic_searchlist;\n\n\n\n /* Dependent object that first caused this object to be loaded. */\n\n struct link_map *l_loader;\n\n\n\n /* Symbol hash table. */\n\n Elf_Symndx l_nbuckets;\n\n const Elf_Symndx *l_buckets, *l_chain;\n\n\n\n unsigned int l_opencount;\t/* Reference count for dlopen/dlclose. */\n\n enum\t\t\t/* Where this object came from. */\n\n {\n\n\tlt_executable,\t\t/* The main executable program. */\n\n\tlt_library,\t\t/* Library needed by main executable. */\n\n\tlt_loaded\t\t/* Extra run-time loaded shared object. */\n\n } l_type:2;\n\n unsigned int l_relocated:1;\t/* Nonzero if object's relocations done. */\n\n unsigned int l_init_called:1; /* Nonzero if DT_INIT function called. */\n\n unsigned int l_global:1;\t/* Nonzero if object in _dl_global_scope. */\n\n unsigned int l_reserved:2;\t/* Reserved for internal use. */\n\n unsigned int l_phdr_allocated:1; /* Nonzero if the data structure pointed\n\n\t\t\t\t\tto by `l_phdr' is allocated. */\n\n unsigned int l_soname_added:1; /* Nonzero if the SONAME is for sure in\n\n\t\t\t\t the l_libname list. */\n\n unsigned int l_faked:1;\t/* Nonzero if this is a faked descriptor\n\n\t\t\t\t without associated file. */\n\n\n\n /* Array with version names. */\n\n unsigned int l_nversions;\n\n struct r_found_version *l_versions;\n\n\n\n /* Collected information about own RPATH directories. */\n\n struct r_search_path_struct l_rpath_dirs;\n\n\n\n /* Collected results of relocation while profiling. */\n\n ElfW(Addr) *l_reloc_result;\n\n\n\n /* Pointer to the version information if available. */\n\n ElfW(Versym) *l_versyms;\n\n\n\n /* String specifying the path where this object was found. */\n\n const char *l_origin;\n\n\n\n /* Start and finish of memory map for this object. l_map_start\n\n need not be the same as l_addr. */\n\n ElfW(Addr) l_map_start, l_map_end;\n\n\n\n /* Default array for 'l_scope'. */\n\n struct r_scope_elem *l_scope_mem[4];\n\n /* Size of array allocated for 'l_scope'. */\n\n size_t l_scope_max;\n\n /* This is an array defining the lookup scope for this link map.\n\n There are at most three different scope lists. */\n\n struct r_scope_elem **l_scope;\n\n\n\n /* A similar array, this time only with the local scope. This is\n\n used occasionally. */\n\n struct r_scope_elem *l_local_scope[2];\n\n\n\n /* This information is kept to check for sure whether a shared\n\n object is the same as one already loaded. */\n\n dev_t l_dev;\n\n ino64_t l_ino;\n\n\n\n /* Collected information about own RUNPATH directories. */\n\n struct r_search_path_struct l_runpath_dirs;\n\n\n\n /* List of object in order of the init and fini calls. */\n\n struct link_map **l_initfini;\n\n\n\n /* List of the dependencies introduced through symbol binding. */\n\n unsigned int l_reldepsmax;\n\n unsigned int l_reldepsact;\n\n struct link_map **l_reldeps;\n\n\n\n /* Various flag words. */\n\n ElfW(Word) l_feature_1;\n\n ElfW(Word) l_flags_1;\n\n\n\n /* Temporarily used in `dl_close'. */\n\n unsigned int l_idx;\n\n\n\n struct link_map_machine l_mach;\n\n\n\n struct\n\n {\n\n const ElfW(Sym) *sym;\n\n int type_class;\n\n#ifdef DL_LOOKUP_RETURNS_MAP\n\n struct link_map *value;\n\n#else\n\n ElfW(Addr) value;\n\n#endif\n\n const ElfW(Sym) *ret;\n\n } l_lookup_cache;\n\n };\n\n\n\nstruct dl_phdr_info\n\n {\n\n ElfW(Addr) dlpi_addr;\n\n const char *dlpi_name;\n\n const ElfW(Phdr) *dlpi_phdr;\n\n ElfW(Half) dlpi_phnum;\n\n };\n\n\n\nextern int dl_iterate_phdr (int (*callback) (struct dl_phdr_info *info,\n\n\t\t\t\t\t size_t size, void *data),\n\n\t\t\t void *data);\n\nextern int __dl_iterate_phdr (int (*callback) (struct dl_phdr_info *info,\n\n\t\t\t\t\t size_t size, void *data),\n\n\t\t\t void *data);\n\n\n", "file_path": "libc/newlib/libc/sys/linux/include/link.h", "rank": 16, "score": 186558.2864504155 }, { "content": "size_t\t strlen (const char *);\n", "file_path": "libc/newlib/libc/include/string.h", "rank": 17, "score": 184835.6062946935 }, { "content": "#ifndef _GLOB_H_\n\n#define\t_GLOB_H_\n\n\n\n#include <sys/cdefs.h>\n\n\n\nstruct stat;\n\ntypedef struct {\n\n\tint gl_pathc;\t\t/* Count of total paths so far. */\n\n\tint gl_matchc;\t\t/* Count of paths matching pattern. */\n\n\tint gl_offs;\t\t/* Reserved at beginning of gl_pathv. */\n\n\tint gl_flags;\t\t/* Copy of flags parameter to glob. */\n\n\tchar **gl_pathv;\t/* List of paths matching pattern. */\n\n\t\t\t\t/* Copy of errfunc parameter to glob. */\n\n\tint (*gl_errfunc)(const char *, int);\n\n\n\n\t/*\n\n\t * Alternate filesystem access methods for glob; replacement\n\n\t * versions of closedir(3), readdir(3), opendir(3), stat(2)\n\n\t * and lstat(2).\n\n\t */\n\n\tvoid (*gl_closedir)(void *);\n\n\tstruct dirent *(*gl_readdir)(void *);\n\n\tvoid *(*gl_opendir)(const char *);\n\n\tint (*gl_lstat)(const char *, struct stat *);\n\n\tint (*gl_stat)(const char *, struct stat *);\n\n} glob_t;\n\n\n\n#define\tGLOB_APPEND\t0x0001\t/* Append to output from previous call. */\n\n#define\tGLOB_DOOFFS\t0x0002\t/* Use gl_offs. */\n\n#define\tGLOB_ERR\t0x0004\t/* Return on error. */\n\n#define\tGLOB_MARK\t0x0008\t/* Append / to matching directories. */\n\n#define\tGLOB_NOCHECK\t0x0010\t/* Return pattern itself if nothing matches. */\n\n#define\tGLOB_NOSORT\t0x0020\t/* Don't sort. */\n\n\n\n#define\tGLOB_ALTDIRFUNC\t0x0040\t/* Use alternately specified directory funcs. */\n\n#define\tGLOB_BRACE\t0x0080\t/* Expand braces ala csh. */\n\n#define\tGLOB_MAGCHAR\t0x0100\t/* Pattern had globbing characters. */\n\n#define\tGLOB_NOMAGIC\t0x0200\t/* GLOB_NOCHECK without magic chars (csh). */\n\n#define\tGLOB_QUOTE\t0x0400\t/* Quote special chars with \\. */\n\n#define\tGLOB_TILDE\t0x0800\t/* Expand tilde names from the passwd file. */\n\n#define\tGLOB_LIMIT\t0x1000\t/* limit number of returned paths */\n\n\n\n/* backwards compatibility, this is the old name for this option */\n\n#define GLOB_MAXPATH\tGLOB_LIMIT\n\n\n\n#define\tGLOB_NOSPACE\t(-1)\t/* Malloc call failed. */\n\n#define\tGLOB_ABEND\t(-2)\t/* Unignored error. */\n\n\n\n__BEGIN_DECLS\n\nint\tglob(const char *__restrict, int, int (*)(const char *, int), \n\n\t\tglob_t *__restrict);\n\nvoid\tglobfree(glob_t *);\n\n__END_DECLS\n\n\n", "file_path": "libc/newlib/libc/include/glob.h", "rank": 18, "score": 184808.91481248246 }, { "content": "_BEGIN_STD_C\n\n\n\nstruct lconv\n\n{\n\n char *decimal_point;\n\n char *thousands_sep;\n\n char *grouping;\n\n char *int_curr_symbol;\n\n char *currency_symbol;\n\n char *mon_decimal_point;\n\n char *mon_thousands_sep;\n\n char *mon_grouping;\n\n char *positive_sign;\n\n char *negative_sign;\n\n char int_frac_digits;\n\n char frac_digits;\n\n char p_cs_precedes;\n\n char p_sep_by_space;\n\n char n_cs_precedes;\n\n char n_sep_by_space;\n\n char p_sign_posn;\n\n char n_sign_posn;\n\n char int_n_cs_precedes;\n\n char int_n_sep_by_space;\n\n char int_n_sign_posn;\n\n char int_p_cs_precedes;\n\n char int_p_sep_by_space;\n\n char int_p_sign_posn;\n", "file_path": "libc/newlib/libc/include/locale.h", "rank": 19, "score": 184767.23228918243 }, { "content": " struct shmid_ds *buf;\n", "file_path": "libc/winsup/cygwin/include/cygwin/sysproto.h", "rank": 20, "score": 182378.02461770817 }, { "content": "__BEGIN_DECLS\n\n\n\n/*\n\n * Define the uio buffers used for writev, readv.\n\n */\n\n\n\nstruct iovec\n\n{\n\n void *iov_base;\n\n size_t iov_len;\n", "file_path": "libc/winsup/cygwin/include/sys/uio.h", "rank": 21, "score": 182333.46308098568 }, { "content": " __extension__ struct\n\n {\n", "file_path": "libc/winsup/cygwin/include/cygwin/signal.h", "rank": 22, "score": 182333.46308098568 }, { "content": " const pthread_attr_t * attr; /* thread attributes */\n", "file_path": "libc/newlib/libc/sys/linux/linuxthreads/internals.h", "rank": 23, "score": 182262.04362805723 }, { "content": "struct suffix_info\n\n{\n\n const char *name;\n\n int addon;\n\n suffix_info (const char *s, int addit = 0): name (s), addon (addit) {}\n\n};\n\n\n\nextern suffix_info stat_suffixes[];\n\n\n\n/* DO NOT copy any of these files into the same set of flags as the\n\n below path_types. Ever. */\n", "file_path": "libc/winsup/cygwin/path.h", "rank": 24, "score": 181324.05544939492 }, { "content": "#ifndef _GLOB_H_\n\n#define\t_GLOB_H_\n\n\n\n#include <sys/cdefs.h>\n\n\n\nstruct stat;\n\ntypedef struct {\n\n\tint gl_pathc;\t\t/* Count of total paths so far. */\n\n\tint gl_matchc;\t\t/* Count of paths matching pattern. */\n\n\tint gl_offs;\t\t/* Reserved at beginning of gl_pathv. */\n\n\tint gl_flags;\t\t/* Copy of flags parameter to glob. */\n\n\tchar **gl_pathv;\t/* List of paths matching pattern. */\n\n\t\t\t\t/* Copy of errfunc parameter to glob. */\n\n\tint (*gl_errfunc)(const char *, int);\n\n\n\n\t/*\n\n\t * Alternate filesystem access methods for glob; replacement\n\n\t * versions of closedir(3), readdir(3), opendir(3), stat(2)\n\n\t * and lstat(2).\n\n\t */\n\n\tvoid (*gl_closedir)(void *);\n\n\tstruct dirent *(*gl_readdir)(void *);\n\n\tvoid *(*gl_opendir)(const char *);\n\n\tint (*gl_lstat)(const char *, struct stat *);\n\n\tint (*gl_stat)(const char *, struct stat *);\n\n} glob_t;\n\n\n\n#define\tGLOB_APPEND\t0x0001\t/* Append to output from previous call. */\n\n#define\tGLOB_DOOFFS\t0x0002\t/* Use gl_offs. */\n\n#define\tGLOB_ERR\t0x0004\t/* Return on error. */\n\n#define\tGLOB_MARK\t0x0008\t/* Append / to matching directories. */\n\n#define\tGLOB_NOCHECK\t0x0010\t/* Return pattern itself if nothing matches. */\n\n#define\tGLOB_NOSORT\t0x0020\t/* Don't sort. */\n\n\n\n#define\tGLOB_ALTDIRFUNC\t0x0040\t/* Use alternately specified directory funcs. */\n\n#define\tGLOB_BRACE\t0x0080\t/* Expand braces ala csh. */\n\n#define\tGLOB_MAGCHAR\t0x0100\t/* Pattern had globbing characters. */\n\n#define\tGLOB_NOMAGIC\t0x0200\t/* GLOB_NOCHECK without magic chars (csh). */\n\n#define\tGLOB_QUOTE\t0x0400\t/* Quote special chars with \\. */\n\n#define\tGLOB_TILDE\t0x0800\t/* Expand tilde names from the passwd file. */\n\n#define\tGLOB_LIMIT\t0x1000\t/* limit number of returned paths */\n\n\n\n/* backwards compatibility, this is the old name for this option */\n\n#define GLOB_MAXPATH\tGLOB_LIMIT\n\n\n\n#define\tGLOB_NOSPACE\t(-1)\t/* Malloc call failed. */\n\n#define\tGLOB_ABEND\t(-2)\t/* Unignored error. */\n\n\n\n__BEGIN_DECLS\n\nint\tglob(const char *, int, int (*)(const char *, int), glob_t *);\n\nvoid\tglobfree(glob_t *);\n\n__END_DECLS\n\n\n", "file_path": "libc/newlib/libc/sys/linux/include/glob.h", "rank": 25, "score": 180028.7488098505 }, { "content": " __extension__ struct __gconv_step_data __data __flexarr;\n", "file_path": "libc/newlib/libc/sys/linux/include/gconv.h", "rank": 26, "score": 179987.24832651138 }, { "content": " __const struct argp *root_argp;\n", "file_path": "libc/newlib/libc/sys/linux/include/argp.h", "rank": 27, "score": 179987.24832651138 }, { "content": "struct slt_normal\n\n{\n\n unsigned int sltdesc:\t4;\n\n unsigned int line:\t28;\n\n CORE_ADDR address;\n\n};\n\n\n", "file_path": "libc/include/hp-symtab.h", "rank": 28, "score": 178812.58851921314 }, { "content": "struct dntt_type_with\n\n{\n\n unsigned int extension:\t1; /* always zero */\n\n unsigned int kind:\t\t10; /* always DNTT_TYPE_WITH */\n\n unsigned int addrtype: \t2; /* 0 => STATTYPE */\n\n /* 1 => DYNTYPE */\n\n /* 2 => REGTYPE */\n\n unsigned int indirect: \t1; /* 1 => pointer to object */\n\n unsigned int longaddr: \t1; /* 1 => in long pointer space */\n\n unsigned int nestlevel: \t6; /* # of nesting levels back */\n\n unsigned int doc_ranges: \t1; /* 1 => location is range list */\n\n unsigned int unused: \t10;\n\n long location; \t\t /* where stored (allocated) */\n\n sltpointer address;\n\n dnttpointer type; /* type of with expression */\n\n vtpointer name; /* name of with expression */\n\n unsigned long offset; /* byte offset from location */\n\n}; \n\n\n\n/* DNTT_TYPE_COMMON is unsupported by GDB. */\n", "file_path": "libc/include/hp-symtab.h", "rank": 29, "score": 178812.58851921314 }, { "content": "struct dnttp_immediate\n\n{\n\n unsigned int extension:\t1;\n\n unsigned int immediate:\t1;\n\n unsigned int global:\t\t1;\n\n unsigned int type: \t\t5;\n\n unsigned int bitlength:\t24;\n\n};\n\n\n\n/* A nonimmediate name and type table entry.\n\n\n\n extension will always be one.\n\n immediate will always be zero.\n\n if global is zero, this entry points into the LNTT\n\n if global is one, this entry points into the GNTT\n\n index is the index within the GNTT or LNTT for this entry. */\n", "file_path": "libc/include/hp-symtab.h", "rank": 30, "score": 178812.58851921314 }, { "content": "struct slt_assist\n\n{\n\n unsigned int sltdesc:\t4;\n\n unsigned int unused:\t28;\n\n sltpointer address;\n\n};\n\n\n", "file_path": "libc/include/hp-symtab.h", "rank": 31, "score": 178812.58851921314 }, { "content": "struct slt_generic\n\n{\n\n unsigned int word[2];\n\n};\n\n\n\nunion sltentry\n\n{\n\n struct slt_normal snorm;\n\n struct slt_normal_off snormoff;\n\n struct slt_special sspec;\n\n struct slt_assist sasst;\n\n struct slt_generic sgeneric;\n\n};\n\n\n\n/* $LINES$ declarations\n\n This is the line table used for optimized code, which is only present \n\n in the new $PROGRAM_INFO$ debug space. */\n\n\n\n#define DST_LN_ESCAPE_FLAG1 15\n\n#define DST_LN_ESCAPE_FLAG2 14\n", "file_path": "libc/include/hp-symtab.h", "rank": 32, "score": 178812.58851921314 }, { "content": "struct slt_special\n\n{\n\n unsigned int sltdesc:\t4;\n\n unsigned int line:\t28;\n\n dnttpointer backptr;\n\n};\n\n\n\n/* Used to describe nesting.\n\n\n\n For nested languages, an slt_assist entry must follow each SLT_FUNC\n\n entry in the SLT. The address field will point forward to the\n\n first slt_normal entry within the function's scope. */\n\n\n", "file_path": "libc/include/hp-symtab.h", "rank": 33, "score": 178812.58851921314 }, { "content": "struct dnttp_nonimmediate\n\n{\n\n unsigned int extension:\t1;\n\n unsigned int immediate:\t1;\n\n unsigned int global:\t\t1;\n\n unsigned int index:\t\t29;\n\n};\n\n\n\n/* A pointer to an entry in the GNTT and LNTT tables. It has two\n\n forms depending on the type being described.\n\n\n\n The immediate form is used for simple entries and is one\n\n word.\n\n\n\n The nonimmediate form is used for complex entries and contains\n\n an index into the LNTT or GNTT which describes the entire type.\n\n\n\n If a dnttpointer is -1, then it is a NIL entry. */\n\n\n\n#define DNTTNIL (-1)\n", "file_path": "libc/include/hp-symtab.h", "rank": 34, "score": 178812.58851921314 }, { "content": "struct slt_normal_off\n\n{\n\n unsigned int sltdesc:\t4;\n\n unsigned int offset:\t6;\n\n unsigned int line:\t22;\n\n CORE_ADDR address;\n\n};\n\n\n\n/* A special source line entry. Provides a mapping of a declaration\n\n to a line number. These entries point back into the DNTT which\n\n references them. */\n\n\n", "file_path": "libc/include/hp-symtab.h", "rank": 35, "score": 178812.58851921314 }, { "content": "struct symlink_info\n\n{\n\n char contents[SYMLINK_MAX + 1];\n\n char *ext_here;\n\n int extn;\n\n unsigned path_flags;\n\n unsigned mount_flags;\n\n unsigned pc_flags;\t/* Relevant pathconv_arg flags from path_conv caller */\n\n DWORD fileattr;\n\n int issymlink;\n\n bool ext_tacked_on;\n\n int error;\n\n bool isdevice;\n\n _major_t major;\n\n _minor_t minor;\n\n __mode_t mode;\n\n int check (char *path, const suffix_info *suffixes, fs_info &fs,\n\n\t path_conv_handle &conv_hdl);\n\n int set (char *path);\n\n bool parse_device (const char *);\n", "file_path": "libc/winsup/cygwin/path.cc", "rank": 36, "score": 178547.39398731544 }, { "content": "struct pc_flat\n\n{\n\n path_conv pc;\n\n HANDLE hdl;\n\n size_t name_len;\n\n size_t posix_len;\n\n char data[0];\n\n};\n\n\n\nvoid *\n\npath_conv::serialize (HANDLE h, unsigned int &n) const\n\n{\n\n pc_flat *pcf;\n\n size_t nlen = 0, plen = 0;\n\n char *p;\n\n\n\n if (path)\n\n nlen = strlen (path) + 1;\n\n if (posix_path)\n\n plen = strlen (posix_path) + 1;\n", "file_path": "libc/winsup/cygwin/path.cc", "rank": 37, "score": 178547.39398731544 }, { "content": "\tu_int8_t dir;\t\t\t/* direction of packet flow, see blow */\n", "file_path": "libc/newlib/libc/sys/linux/include/netinet6/ipsec.h", "rank": 38, "score": 177782.0787529117 }, { "content": "\tvoid *buf;\n", "file_path": "libc/newlib/libc/sys/linux/include/rpc/types.h", "rank": 39, "score": 177767.87271925982 }, { "content": "\tvoid\t*buf;\n", "file_path": "libc/newlib/libc/sys/rtems/include/sys/filio.h", "rank": 40, "score": 177767.87271925982 }, { "content": "__BEGIN_DECLS\n", "file_path": "libc/newlib/libc/sys/linux/include/rpc/auth.h", "rank": 41, "score": 177723.94687216205 }, { "content": "__BEGIN_DECLS\n", "file_path": "libc/newlib/libc/sys/linux/include/rpc/rpcent.h", "rank": 42, "score": 177723.94687216205 }, { "content": "#define\tTAILQ_HEAD(name, type)\t\t\t\t\t\t\\\n\nstruct name {\t\t\t\t\t\t\t\t\\\n\n\tstruct type *tqh_first;\t/* first element */\t\t\t\\\n\n\tstruct type **tqh_last;\t/* addr of last next element */\t\t\\\n\n\tTRACEBUF\t\t\t\t\t\t\t\\\n\n}\n\n\n", "file_path": "libc/newlib/libc/include/sys/queue.h", "rank": 43, "score": 176091.76357361334 }, { "content": "struct dntt_type_array\n\n{\n\n unsigned int extension:\t1;\n\n unsigned int kind:\t10;\n\n unsigned int declaration:\t2;\n\n unsigned int dyn_low:\t\t2;\n\n unsigned int dyn_high:\t2;\n\n unsigned int arrayisbytes:\t1;\n\n unsigned int elemisbytes:\t1;\n\n unsigned int elemorder:\t1;\n\n unsigned int justified:\t1;\n\n unsigned int unused:\t\t11;\n\n unsigned int arraylength;\n\n dnttpointer indextype;\n\n dnttpointer elemtype;\n\n unsigned int elemlength;\n\n};\n\n\n\n/* DNTT_TYPE_STRUCT\n\n\n", "file_path": "libc/include/hp-symtab.h", "rank": 44, "score": 176084.60416786183 }, { "content": "struct dntt_type_module\n\n{\n\n unsigned int extension:\t1;\n\n unsigned int kind:\t\t10; \t/* DNTT_TYPE_MODULE */\n\n unsigned int unused:\t\t21;\n\n vtpointer name;\n\n vtpointer alias;\n\n dnttpointer unused2;\n\n sltpointer address;\n\n};\n\n\n\n/* DNTT_TYPE_FUNCTION,\n\n DNTT_TYPE_ENTRY,\n\n DNTT_TYPE_BLOCKDATA,\n\n DNTT_TYPE_MEMFUNC:\n\n\n\n A DNTT_TYPE_FUNCTION symbol is emitted for each function definition;\n\n a DNTT_TYPE_ENTRY symbols is used for secondary entry points. Both\n\n symbols used the dntt_type_function structure.\n\n A DNTT_TYPE_BLOCKDATA symbol is emitted ...?\n", "file_path": "libc/include/hp-symtab.h", "rank": 45, "score": 176084.60416786183 }, { "content": "struct dntt_type_generic\n\n{\n\n unsigned int word[9];\n\n};\n\n\n", "file_path": "libc/include/hp-symtab.h", "rank": 46, "score": 176084.60416786183 }, { "content": "struct dntt_type_genfield\n\n{\n\n unsigned int extension: 1;\t /* Always zero. */\n\n unsigned int kind: 10; /* Always DNTT_TYPE_GENFIELD. */\n\n unsigned int visibility: 2; /* Pub = 0, prot = 1, priv = 2. */\n\n unsigned int a_union: 1; /* 1 => anonymous union member. */\n\n unsigned int unused:\t 18;\n\n dnttpointer field\t ; /* Pointer to field or qualifier. */\n\n dnttpointer nextfield ; /* Pointer to next field. */\n\n};\n\n\n\n/* C++ virtual functions. */\n\n\n", "file_path": "libc/include/hp-symtab.h", "rank": 47, "score": 176084.60416786183 }, { "content": "struct dntt_type_vfunc\n\n{\n\n unsigned int extension: 1;\t /* always zero */\n\n unsigned int kind: 10; /* always DNTT_TYPE_VFUNC */\n\n unsigned int pure: 1; /* pure virtual function ? */\n\n unsigned int unused:\t 20;\n\n dnttpointer funcptr ; /* points to FUNCTION symbol */\n\n unsigned long vtbl_offset ; /* offset into vtbl for virtual */\n\n};\n\n\n\n/* Not precisely sure what this is intended for - DDE ignores it. */\n\n\n", "file_path": "libc/include/hp-symtab.h", "rank": 48, "score": 176084.60416786183 }, { "content": "struct dntt_type_srcfile\n\n{\n\n unsigned int extension:\t1;\n\n unsigned int kind:\t\t10; /* DNTT_TYPE_SRCFILE */\n\n unsigned int language:\t4;\n\n unsigned int unused:\t\t17;\n\n vtpointer name;\n\n sltpointer address;\n\n};\n\n\n\n/* DNTT_TYPE_MODULE:\n\n\n\n A DNTT_TYPE_MODULE symbol is emitted for the start of a pascal\n\n module or C source file. A module indicates a compilation unit\n\n for name-scoping purposes; in that regard there should be \n\n a 1-1 correspondence between GDB \"symtab\"'s and MODULE symbol records.\n\n\n\n Each DNTT_TYPE_MODULE must have an associated DNTT_TYPE_END symbol.\n\n\n\n NAME points to a VT entry providing the module's name. Note C\n\n source files are considered nameless modules.\n\n\n\n ALIAS point to a VT entry providing a secondary name.\n\n\n\n ADDRESS points to an SLT entry from which line number and code locations\n\n may be determined. */\n\n\n", "file_path": "libc/include/hp-symtab.h", "rank": 49, "score": 176084.60416786183 }, { "content": "struct dntt_type_function\n\n{\n\n unsigned int extension:\t1;\n\n unsigned int kind:\t\t10;\t/* DNTT_TYPE_FUNCTION,\n\n\t\t\t\t DNTT_TYPE_ENTRY,\n\n\t\t\t\t\t DNTT_TYPE_BLOCKDATA\n\n\t\t\t\t\t or DNTT_TYPE_MEMFUNC */\n\n unsigned int global:\t\t1;\n\n unsigned int language:\t4;\n\n unsigned int nest_level:\t5;\n\n unsigned int opt_level:\t2;\n\n unsigned int varargs:\t\t1;\n\n unsigned int lang_info:\t4;\n\n unsigned int inlined:\t\t1;\n\n unsigned int localalloc:\t1;\n\n unsigned int expansion:\t1;\n\n unsigned int unused:\t\t1;\n\n vtpointer name;\n\n vtpointer alias;\n\n dnttpointer firstparam;\n", "file_path": "libc/include/hp-symtab.h", "rank": 50, "score": 176084.60416786183 }, { "content": "struct dntt_type_enum\n\n{\n\n unsigned int extension:\t1;\n\n unsigned int kind:\t10;\n\n unsigned int unused:\t\t21;\n\n dnttpointer firstmem;\n\n unsigned int bitlength;\n\n};\n\n\n\n/* DNTT_TYPE_MEMENUM\n\n\n\n Used to describe members of an enumerated type.\n\n\n\n CLASSMEM is nonzero if this member is part of a class.\n\n\n\n NAME points into the VT for the name of this member.\n\n\n\n VALUE is the value of this enumeration member.\n\n\n\n NEXTMEM points to the next DNTT_TYPE_MEMENUM in the chain. */\n\n\n", "file_path": "libc/include/hp-symtab.h", "rank": 51, "score": 176084.60416786183 }, { "content": "struct dntt_type_functype\n\n{\n\n unsigned int extension:\t1;\n\n unsigned int kind:\t\t10;\n\n unsigned int varargs:\t\t1;\n\n unsigned int info:\t\t4;\n\n unsigned int unused:\t\t16;\n\n unsigned int bitlength;\n\n dnttpointer firstparam;\n\n dnttpointer retval;\n\n};\n\n\n\n/* DNTT_TYPE_WITH is emitted by C++ to indicate \"with\" scoping semantics.\n\n (Probably also emitted by PASCAL to support \"with\"...).\n\n \n\n C++ example: Say \"memfunc\" is a method of class \"c\", and say\n\n \"m\" is a data member of class \"c\". Then from within \"memfunc\",\n\n it is legal to reference \"m\" directly (e.g. you don't have to\n\n say \"this->m\". The symbol table indicates\n\n this by emitting a DNTT_TYPE_WITH symbol within the function \"memfunc\",\n\n pointing to the type symbol for class \"c\".\n\n \n\n In GDB, this symbol record is unnecessary, \n\n because GDB's symbol lookup algorithm\n\n infers the \"with\" semantics when it sees a \"this\" argument to the member\n\n function. So GDB can safely ignore the DNTT_TYPE_WITH record.\n\n\n\n A DNTT_TYPE_WITH has a matching DNTT_TYPE_END symbol. */\n\n\n", "file_path": "libc/include/hp-symtab.h", "rank": 52, "score": 176084.60416786183 }, { "content": "struct dntt_type_class \n\n{\n\n unsigned int extension: 1; /* Always zero. */\n\n unsigned int kind: 10; /* Always DNTT_TYPE_CLASS. */\n\n unsigned int abstract: 1; /* Is this an abstract class? */\n\n unsigned int class_decl: 2; /* 0=class,1=union,2=struct. */\n\n unsigned int expansion: 1; /* 1=template expansion. */\n\n unsigned int unused: 17; \n\n dnttpointer memberlist ; /* Ptr to chain of [GEN]FIELDs. */\n\n unsigned long vtbl_loc ; /* Offset in obj of ptr to vtbl. */\n\n dnttpointer parentlist ; /* Ptr to K_INHERITANCE list. */\n\n unsigned long bitlength ; /* Total at this level. */\n\n dnttpointer identlist ; /* Ptr to chain of class ident's. */\n\n dnttpointer friendlist ; /* Ptr to K_FRIEND list. */\n\n dnttpointer templateptr ; /* Ptr to template. */\n\n dnttpointer nextexp ; /* Ptr to next expansion. */\n\n};\n\n\n\n/* Class members are indicated via either the FIELD record (for\n\n data members, same as for C struct fields), or by the GENFIELD record\n\n (for member functions). */\n\n\n", "file_path": "libc/include/hp-symtab.h", "rank": 53, "score": 176084.60416786183 }, { "content": "struct dntt_type_memaccess\n\n{\n\n unsigned int extension: 1;\t /* always zero */\n\n unsigned int kind: 10; /* always DNTT_TYPE_MEMACCESS */\n\n unsigned int unused:\t 21;\n\n dnttpointer classptr\t ; /* pointer to base class */\n\n dnttpointer field ; /* pointer field */\n\n};\n\n\n\n/* The DNTT_TYPE_INHERITANCE record describes derived classes.\n\n In particular, the \"parentlist\" field of the CLASS record points\n\n to a list of INHERITANCE records for classes from which we \n\n inherit members. */\n\n\n", "file_path": "libc/include/hp-symtab.h", "rank": 54, "score": 176084.60416786183 }, { "content": "struct dntt_type_fparam\n\n{\n\n unsigned int extension:\t1;\n\n unsigned int kind:\t\t10;\n\n unsigned int regparam:\t1;\n\n unsigned int indirect:\t1;\n\n unsigned int longaddr:\t1;\n\n unsigned int copyparam:\t1;\n\n unsigned int dflt:\t\t1;\n\n unsigned int doc_ranges:\t1;\n\n unsigned int misc_kind: 1;\n\n unsigned int unused:\t\t14;\n\n vtpointer name;\n\n CORE_ADDR location;\n\n dnttpointer type;\n\n dnttpointer nextparam;\n\n int misc;\n\n};\n\n\n\n/* DNTT_TYPE_SVAR:\n", "file_path": "libc/include/hp-symtab.h", "rank": 55, "score": 176084.60416786183 }, { "content": "struct dntt_type_dvar\n\n{\n\n unsigned int extension:\t1;\n\n unsigned int kind:\t\t10;\n\n unsigned int global:\t\t1;\n\n unsigned int indirect:\t1;\n\n unsigned int regvar:\t\t1;\n\n unsigned int a_union:\t\t1;\n\n unsigned int unused:\t\t17;\n\n vtpointer name;\n\n int location;\n\n dnttpointer type;\n\n unsigned int offset;\n\n};\n\n\n\n/* DNTT_TYPE_CONST:\n\n\n\n A DNTT_TYPE_CONST symbol is emitted for program constants.\n\n\n\n GLOBAL is nonzero if the constant has global scope.\n", "file_path": "libc/include/hp-symtab.h", "rank": 56, "score": 176084.60416786183 }, { "content": "struct dntt_type_union\n\n{\n\n unsigned int extension:\t1;\n\n unsigned int kind:\t10;\n\n unsigned int unused:\t\t21;\n\n dnttpointer firstfield;\n\n unsigned int bitlength;\n\n};\n\n\n\n/* DNTT_TYPE_FIELD\n\n\n\n DNTT_TYPE_FIELD describes one field in a structure or union\n\n or C++ class.\n\n\n\n VISIBILITY is used to describe the visibility of the field\n\n (for c++. public = 0, protected = 1, private = 2).\n\n\n\n A_UNION is nonzero if this field is a member of an anonymous union.\n\n\n\n STATICMEM is nonzero if this field is a static member of a template.\n", "file_path": "libc/include/hp-symtab.h", "rank": 57, "score": 176084.60416786183 }, { "content": "struct dntt_type_block\n\n{\n\n unsigned int extension:\t1;\n\n unsigned int kind: 10;\n\n unsigned int unused:\t\t21;\n\n unsigned int word[2];\n\n};\n\n\n\n/* One entry in a DNTT (either the LNTT or GNTT). \n\n This is a union of the above 60 or so structure definitions. */\n\n\n\nunion dnttentry\n\n{\n\n struct dntt_type_srcfile dsfile;\n\n struct dntt_type_module dmodule;\n\n struct dntt_type_function dfunc;\n\n struct dntt_type_function dentry;\n\n struct dntt_type_begin dbegin;\n\n struct dntt_type_end dend;\n\n struct dntt_type_fparam dfparam;\n", "file_path": "libc/include/hp-symtab.h", "rank": 58, "score": 176084.60416786183 }, { "content": "struct dntt_type_template\n\n{\n\n unsigned int extension: 1;\t /* always zero */\n\n unsigned int kind: 10; /* always DNTT_TYPE_TEMPLATE */\n\n unsigned int abstract: 1; /* is this an abstract class? */\n\n unsigned int class_decl: 2; /* 0=class,1=union,2=struct */\n\n unsigned int unused:\t 18;\n\n dnttpointer memberlist ; /* ptr to chain of K_[GEN]FIELDs */\n\n long unused2 ; /* offset in obj of ptr to vtbl */\n\n dnttpointer parentlist ; /* ptr to K_INHERITANCE list */\n\n unsigned long bitlength ; /* total at this level */\n\n dnttpointer identlist ; /* ptr to chain of class ident's */\n\n dnttpointer friendlist ; /* ptr to K_FRIEND list */\n\n dnttpointer arglist ; /* ptr to argument list */\n\n dnttpointer expansions ; /* ptr to expansion list */\n\n};\n\n\n\n/* Template-class arguments are a list of TEMPL_ARG records\n\n chained together. The \"name\" field is the name of the formal.\n\n E.g.:\n\n \n\n template <class T> class q { ... };\n\n \n\n Then \"T\" is the name of the formal argument. */\n\n\n", "file_path": "libc/include/hp-symtab.h", "rank": 59, "score": 176084.60416786183 }, { "content": "struct dntt_type_link\n\n{\n\n unsigned int extension: 1;\t /* always zero */\n\n unsigned int kind: 10; /* always DNTT_TYPE_LINK */\n\n unsigned int linkKind: 4; /* always LINK_UNKNOWN */\n\n unsigned int unused:\t 17;\n\n long future1 ; /* expansion */\n\n dnttpointer ptr1 ; /* link from template */\n\n dnttpointer ptr2 ; /* to expansion */\n\n long future[2] ; /* padding to 3-word block end */\n\n};\n\n\n\n/* end of C++ specific SOM's. */\n\n\n\n/* DNTT_TYPE_DYN_ARRAY_DESC is unused by GDB */\n\n/* DNTT_TYPE_DESC_SUBRANGE is unused by GDB */\n\n/* DNTT_TYPE_BEGIN_EXT is unused by GDB */\n\n/* DNTT_TYPE_INLN is unused by GDB */\n\n/* DNTT_TYPE_INLN_LIST is unused by GDB */\n\n/* DNTT_TYPE_ALIAS is unused by GDB */\n\n\n", "file_path": "libc/include/hp-symtab.h", "rank": 60, "score": 176084.60416786183 }, { "content": "struct dntt_type_type\n\n{\n\n unsigned int extension:\t1;\n\n unsigned int kind:\t\t10; /* DNTT_TYPE_TYPEDEF or \n\n DNTT_TYPE_TAGDEF. */\n\n unsigned int global:\t\t1;\n\n unsigned int typeinfo:\t1;\n\n unsigned int unused:\t\t19;\n\n vtpointer name;\n\n dnttpointer type; /* Underlying type, which for TAGDEF's may be\n\n DNTT_TYPE_STRUCT, DNTT_TYPE_UNION,\n\n DNTT_TYPE_ENUM, or DNTT_TYPE_CLASS. \n\n For TYPEDEF's other underlying types\n\n are also possible. */\n\n};\n\n\n\n/* DNTT_TYPE_POINTER:\n\n\n\n Used to describe a pointer to an underlying type.\n\n\n\n POINTSTO is a pointer into the GNTT or LNTT for the type which this\n\n pointer points to.\n\n\n\n BITLENGTH is the length of the pointer (not the underlying type). */\n\n\n", "file_path": "libc/include/hp-symtab.h", "rank": 61, "score": 176084.60416786183 }, { "content": "struct dntt_type_field\n\n{\n\n unsigned int extension:\t1;\n\n unsigned int kind:\t10;\n\n unsigned int visibility:\t2;\n\n unsigned int a_union:\t\t1;\n\n unsigned int staticmem:\t1;\n\n unsigned int unused:\t\t17;\n\n vtpointer name;\n\n unsigned int bitoffset;\n\n dnttpointer type;\n\n unsigned int bitlength;\n\n dnttpointer nextfield;\n\n};\n\n\n\n/* DNTT_TYPE_VARIANT is unused by GDB. */\n\n/* DNTT_TYPE_FILE is unused by GDB. */\n\n\n\n/* DNTT_TYPE_FUNCTYPE\n\n\n\n I think this is used to describe a function type (e.g., would\n\n be emitted as part of a function-pointer description).\n\n\n\n VARARGS is nonzero if this function uses varargs.\n\n\n\n FIRSTPARAM is a DNTT pointer to the first entry in the parameter\n\n chain.\n\n\n\n RETVAL is a DNTT pointer to the type of the return value. */\n\n\n", "file_path": "libc/include/hp-symtab.h", "rank": 62, "score": 176084.60416786183 }, { "content": "struct dntt_type_subrange\n\n{\n\n unsigned int extension:\t1;\n\n unsigned int kind:\t10;\n\n unsigned int dyn_low:\t\t2;\n\n unsigned int dyn_high:\t2;\n\n unsigned int unused:\t\t17;\n\n int lowbound;\n\n int highbound;\n\n dnttpointer subtype;\n\n unsigned int bitlength;\n\n};\n\n\n\n/* DNTT_TYPE_ARRAY\n\n\n\n Used to describe an array type.\n\n\n\n DECLARATION describes the bit packing used in the array.\n\n\n\n ARRAYISBYTES is nonzero if the field in arraylength describes the\n", "file_path": "libc/include/hp-symtab.h", "rank": 63, "score": 176084.60416786183 }, { "content": "struct dntt_type_end\n\n{\n\n unsigned int extension:\t1;\n\n unsigned int kind:\t\t10;\n\n unsigned int endkind:\t\t10;\n\n unsigned int classflag:\t1;\n\n unsigned int unused:\t\t10;\n\n sltpointer address;\n\n dnttpointer beginscope;\n\n};\n\n\n\n/* DNTT_TYPE_IMPORT is unused by GDB. */\n\n/* DNTT_TYPE_LABEL is unused by GDB. */\n\n\n\n/* DNTT_TYPE_FPARAM:\n\n\n\n A DNTT_TYPE_FPARAM symbol is emitted for a function argument. When\n\n chained together the symbols represent an argument list for a function.\n\n\n\n REGPARAM is nonzero if this parameter was passed in a register.\n", "file_path": "libc/include/hp-symtab.h", "rank": 64, "score": 176084.60416786183 }, { "content": "struct dntt_type_memenum\n\n{\n\n unsigned int extension:\t1;\n\n unsigned int kind:\t10;\n\n unsigned int classmem:\t1;\n\n unsigned int unused:\t\t20;\n\n vtpointer name;\n\n unsigned int value;\n\n dnttpointer nextmem;\n\n};\n\n\n\n/* DNTT_TYPE_SET\n\n\n\n Used to describe PASCAL \"set\" type.\n\n\n\n DECLARATION describes the bitpacking of the set.\n\n\n\n SUBTYPE points to a DNTT entry describing the type of the members.\n\n\n\n BITLENGTH is the size of the set. */ \n\n\n", "file_path": "libc/include/hp-symtab.h", "rank": 65, "score": 176084.60416786183 }, { "content": "struct dntt_type_ptrmem\n\n{\n\n unsigned int extension: 1;\t /* Always zero. */\n\n unsigned int kind: 10; /* Always DNTT_TYPE_PTRMEM. */\n\n unsigned int unused:\t 21;\n\n dnttpointer pointsto\t ; /* Pointer to class DNTT. */\n\n dnttpointer memtype \t ; /* Type of member. */\n\n};\n\n\n", "file_path": "libc/include/hp-symtab.h", "rank": 66, "score": 176084.60416786183 }, { "content": "struct dntt_type_modifier\n\n{\n\n unsigned int extension: 1;\t /* always zero */\n\n unsigned int kind: 10; /* always DNTT_TYPE_MODIFIER */\n\n unsigned int m_const: 1; /* const */\n\n unsigned int m_static: 1; /* static */\n\n unsigned int m_void: 1; /* void */\n\n unsigned int m_volatile: 1; /* volatile */\n\n unsigned int m_duplicate: 1; /* duplicate */\n\n unsigned int unused:\t 16;\n\n dnttpointer type ; /* subtype */\n\n unsigned long future ; /* padding to 3-word block end */\n\n};\n\n\n\n/* I'm not sure what this was intended for - DDE ignores it. */\n\n\n", "file_path": "libc/include/hp-symtab.h", "rank": 67, "score": 176084.60416786183 }, { "content": "struct __lock;\n\ntypedef struct __lock * _LOCK_T;\n\n#define _LOCK_RECURSIVE_T _LOCK_T\n\n\n", "file_path": "libc/newlib/libc/include/sys/lock.h", "rank": 68, "score": 176084.60416786183 }, { "content": "struct dntt_type_inheritance\n\n{\n\n unsigned int extension: 1;\t /* always zero */\n\n unsigned int kind: 10; /* always DNTT_TYPE_INHERITANCE */\n\n unsigned int Virtual: 1; /* virtual base class ? */\n\n unsigned int visibility: 2; /* pub = 0, prot = 1, priv = 2 */\n\n unsigned int unused:\t 18;\n\n dnttpointer classname ; /* first parent class, if any */\n\n unsigned long offset ; /* offset to start of base class */\n\n dnttpointer next ; /* pointer to next K_INHERITANCE */\n\n unsigned long future[2] ; /* padding to 3-word block end */\n\n};\n\n\n\n/* C++ \"friend\" classes ... */\n\n\n", "file_path": "libc/include/hp-symtab.h", "rank": 69, "score": 176084.60416786183 }, { "content": "struct dntt_type_begin\n\n{\n\n unsigned int extension:\t1;\n\n unsigned int kind:\t\t10;\n\n unsigned int classflag:\t1;\n\n unsigned int unused:\t\t20;\n\n sltpointer address;\n\n};\n\n\n\n/* DNTT_TYPE_END:\n\n\n\n A DNTT_TYPE_END symbol is emitted when closing a scope started by\n\n a DNTT_TYPE_MODULE, DNTT_TYPE_FUNCTION, DNTT_TYPE_WITH,\n\n DNTT_TYPE_COMMON, DNTT_TYPE_BEGIN, and DNTT_TYPE_CLASS_SCOPE symbols.\n\n\n\n ENDKIND describes what type of scope the DNTT_TYPE_END is closing\n\n (one of the above 6 kinds).\n\n\n\n CLASSFLAG is nonzero if this is the end of a c++ class definition.\n\n\n\n ADDRESS points to an SLT entry from which line number and code locations\n\n may be determined.\n\n\n\n BEGINSCOPE points to the LNTT entry which opened the scope. */\n\n\n", "file_path": "libc/include/hp-symtab.h", "rank": 70, "score": 176084.60416786183 }, { "content": "struct dntt_type_ptrmemfunc\n\n{\n\n unsigned int extension: 1;\t /* Always zero. */\n\n unsigned int kind: 10; /* Always DNTT_TYPE_PTRMEMFUNC. */\n\n unsigned int unused:\t 21;\n\n dnttpointer pointsto\t ; /* Pointer to class DNTT. */\n\n dnttpointer memtype \t ; /* Type of member. */\n\n};\n\n\n\n/* The DNTT_TYPE_CLASS symbol is emitted to describe a class type.\n\n \"memberlist\" points to a chained list of FIELD or GENFIELD records\n\n indicating the class members. \"parentlist\" points to a chained list\n\n of INHERITANCE records indicating classes from which we inherit\n\n fields. */\n\n\n", "file_path": "libc/include/hp-symtab.h", "rank": 71, "score": 176084.60416786183 }, { "content": "struct dntt_type_svar\n\n{\n\n unsigned int extension:\t1;\n\n unsigned int kind:\t\t10;\n\n unsigned int global:\t\t1;\n\n unsigned int indirect:\t1;\n\n unsigned int longaddr:\t1;\n\n unsigned int staticmem:\t1;\n\n unsigned int a_union:\t\t1;\n\n unsigned int unused1: 1;\n\n unsigned int thread_specific: 1;\n\n unsigned int unused2: 14;\n\n vtpointer name;\n\n CORE_ADDR location;\n\n dnttpointer type;\n\n unsigned int offset;\n\n unsigned int displacement;\n\n};\n\n\n\n/* DNTT_TYPE_DVAR:\n", "file_path": "libc/include/hp-symtab.h", "rank": 72, "score": 176084.60416786183 }, { "content": "struct dntt_type_pointer\n\n{\n\n unsigned int extension:\t1;\n\n unsigned int kind:\t\t10;\n\n unsigned int unused:\t\t21;\n\n dnttpointer pointsto;\n\n unsigned int bitlength;\n\n};\n\n\n\n\n\n/* DNTT_TYPE_ENUM:\n\n\n\n Used to describe enumerated types.\n\n\n\n FIRSTMEM is a pointer to a DNTT_TYPE_MEMENUM in the GNTT/LNTT which\n\n describes the first member (and contains a pointer to the chain of\n\n members).\n\n\n\n BITLENGTH is the number of bits used to hold the values of the enum's\n\n members. */\n\n\n", "file_path": "libc/include/hp-symtab.h", "rank": 73, "score": 176084.60416786183 }, { "content": "struct dntt_type_set\n\n{\n\n unsigned int extension:\t1;\n\n unsigned int kind:\t10;\n\n unsigned int declaration:\t2;\n\n unsigned int unused:\t\t19;\n\n dnttpointer subtype;\n\n unsigned int bitlength;\n\n};\n\n\n\n/* DNTT_TYPE_SUBRANGE\n\n\n\n Used to describe subrange type.\n\n\n\n DYN_LOW describes the lower bound of the subrange:\n\n\n\n 00 for a constant lower bound (found in LOWBOUND).\n\n\n\n 01 for a dynamic lower bound with the lower bound found in the\n\n memory address pointed to by LOWBOUND.\n", "file_path": "libc/include/hp-symtab.h", "rank": 74, "score": 176084.60416786183 }, { "content": "struct quehead {\n\n\tstruct quehead *qh_link;\n\n\tstruct quehead *qh_rlink;\n\n};\n\n\n\n#ifdef\t__GNUC__\n\n\n\nstatic __inline void\n\ninsque(void *a, void *b)\n\n{\n\n\tstruct quehead *element = (struct quehead *)a,\n\n\t\t *head = (struct quehead *)b;\n\n\n\n\telement->qh_link = head->qh_link;\n\n\telement->qh_rlink = head;\n\n\thead->qh_link = element;\n\n\telement->qh_link->qh_rlink = element;\n\n}\n\n\n\nstatic __inline void\n", "file_path": "libc/newlib/libc/include/sys/queue.h", "rank": 75, "score": 176084.60416786183 }, { "content": "#define ILLEGAL_SIG_FUNC_PTR ((_sig_func_ptr) (-2))\n\nstruct system_call_handle\n\n{\n\n _sig_func_ptr oldint;\n\n _sig_func_ptr oldquit;\n\n sigset_t oldmask;\n\n bool is_system_call ()\n\n {\n\n return oldint != ILLEGAL_SIG_FUNC_PTR;\n\n }\n\n system_call_handle (bool issystem)\n\n {\n\n if (!issystem)\n\n oldint = ILLEGAL_SIG_FUNC_PTR;\n\n else\n\n {\n\n\tsig_send (NULL, __SIGHOLD);\n\n\toldint = NULL;\n\n }\n\n }\n\n void arm()\n", "file_path": "libc/winsup/cygwin/spawn.cc", "rank": 76, "score": 175927.81127126733 }, { "content": "struct __DIR_drives\n\n{\n\n char *pdrive;\n\n char pbuf[MAX_DRIVE_BUF_LEN];\n\n};\n\n\n\n#define d_drives(d)\t((__DIR_drives *) (d)->__d_internal)\n\n\n\nDIR *\n\nfhandler_cygdrive::opendir (int fd)\n\n{\n\n DIR *dir;\n\n\n\n dir = fhandler_disk_file::opendir (fd);\n\n if (dir)\n\n {\n\n dir->__d_internal = (uintptr_t) new __DIR_drives;\n\n GetLogicalDriveStrings (MAX_DRIVE_BUF_LEN, d_drives(dir)->pbuf);\n\n d_drives(dir)->pdrive = d_drives(dir)->pbuf;\n\n }\n", "file_path": "libc/winsup/cygwin/fhandler_cygdrive.cc", "rank": 77, "score": 175921.29541261084 }, { "content": "struct shm_handle {\n\n\t/* vm_offset_t kva; */\n\n\tvm_object_t shm_object;\n\n};\n\n\n", "file_path": "libc/winsup/cygserver/sysv_shm.cc", "rank": 78, "score": 175920.9101358011 }, { "content": "struct win_shortcut_hdr\n\n {\n\n DWORD size;\t\t/* Header size in bytes. Must contain 0x4c. */\n\n GUID magic;\t\t/* GUID of shortcut files. */\n\n DWORD flags;\t/* Content flags. See above. */\n\n\n\n /* The next fields from attr to icon_no are always set to 0 in Cygwin\n\n and U/Win shortcuts. */\n\n DWORD attr;\t/* Target file attributes. */\n\n FILETIME ctime;\t/* These filetime items are never touched by the */\n\n FILETIME mtime;\t/* system, apparently. Values don't matter. */\n\n FILETIME atime;\n\n DWORD filesize;\t/* Target filesize. */\n\n DWORD icon_no;\t/* Icon number. */\n\n\n\n DWORD run;\t\t/* Values defined in winuser.h. Use SW_NORMAL. */\n\n DWORD hotkey;\t/* Hotkey value. Set to 0. */\n\n DWORD dummy[2];\t/* Future extension probably. Always 0. */\n\n };\n\n\n", "file_path": "libc/winsup/utils/path.cc", "rank": 79, "score": 175876.320222869 }, { "content": "struct win_shortcut_hdr\n\n{\n\n DWORD size;\t\t/* Header size in bytes. Must contain 0x4c. */\n\n GUID magic;\t\t/* GUID of shortcut files. */\n\n DWORD flags;\t/* Content flags. See above. */\n\n\n\n /* The next fields from attr to icon_no are always set to 0 in Cygwin\n\n and U/Win shortcuts. */\n\n DWORD attr;\t/* Target file attributes. */\n\n FILETIME ctime;\t/* These filetime items are never touched by the */\n\n FILETIME mtime;\t/* system, apparently. Values don't matter. */\n\n FILETIME atime;\n\n DWORD filesize;\t/* Target filesize. */\n\n DWORD icon_no;\t/* Icon number. */\n\n\n\n DWORD run;\t\t/* Values defined in winuser.h. Use SW_NORMAL. */\n\n DWORD hotkey;\t/* Hotkey value. Set to 0. */\n\n DWORD dummy[2];\t/* Future extension probably. Always 0. */\n\n};\n\n\n", "file_path": "libc/winsup/cygwin/path.cc", "rank": 80, "score": 175876.320222869 }, { "content": "\tu_int32_t\tdot3StatsInternalMacTransmitErrors;\n", "file_path": "libc/newlib/libc/sys/linux/include/net/if_mib.h", "rank": 81, "score": 174385.6700959997 }, { "content": "\tu_int32_t\tdot3StatsInternalMacReceiveErrors;\n", "file_path": "libc/newlib/libc/sys/linux/include/net/if_mib.h", "rank": 82, "score": 174385.6700959997 }, { "content": "struct dntt_type_friend_class\n\n{\n\n unsigned int extension: 1;\t /* always zero */\n\n unsigned int kind: 10; /* always DNTT_TYPE_FRIEND_CLASS */\n\n unsigned int unused:\t 21;\n\n dnttpointer classptr ; /* pointer to class DNTT */\n\n dnttpointer next ; /* next DNTT_FRIEND */\n\n};\n\n\n", "file_path": "libc/include/hp-symtab.h", "rank": 83, "score": 173460.35647680267 }, { "content": "struct qm_trace {\n\n\tunsigned long\t lastline;\n\n\tunsigned long\t prevline;\n\n\tconst char\t*lastfile;\n\n\tconst char\t*prevfile;\n\n};\n\n\n\n#define\tTRACEBUF\tstruct qm_trace trace;\n\n#define\tTRACEBUF_INITIALIZER\t{ __LINE__, 0, __FILE__, NULL } ,\n\n\n\n#define\tQMD_TRACE_HEAD(head) do {\t\t\t\t\t\\\n\n\t(head)->trace.prevline = (head)->trace.lastline;\t\t\\\n\n\t(head)->trace.prevfile = (head)->trace.lastfile;\t\t\\\n\n\t(head)->trace.lastline = __LINE__;\t\t\t\t\\\n\n\t(head)->trace.lastfile = __FILE__;\t\t\t\t\\\n\n} while (0)\n\n\n\n#define\tQMD_TRACE_ELEM(elem) do {\t\t\t\t\t\\\n\n\t(elem)->trace.prevline = (elem)->trace.lastline;\t\t\\\n\n\t(elem)->trace.prevfile = (elem)->trace.lastfile;\t\t\\\n", "file_path": "libc/newlib/libc/include/sys/queue.h", "rank": 84, "score": 173460.35647680267 }, { "content": "struct dntt_type_class_scope\n\n{\n\n unsigned int extension: 1;\t /* Always zero. */\n\n unsigned int kind: 10; /* Always DNTT_TYPE_CLASS_SCOPE. */\n\n unsigned int unused: 21; \n\n sltpointer address ; /* Pointer to SLT entry. */\n\n dnttpointer type ; /* Pointer to class type DNTT. */\n\n};\n\n\n\n/* C++ reference parameter.\n\n The structure of this record is the same as DNTT_TYPE_POINTER - \n\n refer to struct dntt_type_pointer. */\n\n\n\n/* The next two describe C++ pointer-to-data-member type, and \n\n pointer-to-member-function type, respectively.\n\n DNTT_TYPE_PTRMEM and DNTT_TYPE_PTRMEMFUNC have the same structure. */\n\n\n", "file_path": "libc/include/hp-symtab.h", "rank": 85, "score": 173460.35647680267 }, { "content": "#include \"perprocess.h\"\n\n#include \"path.h\"\n\n#include \"fhandler.h\"\n\n#include \"select.h\"\n\n#include \"dtable.h\"\n\n#include \"cygheap.h\"\n\n#include \"tls_pbuf.h\"\n\n#include \"ntdll.h\"\n\n#include \"shared_info.h\"\n\n\n\nstatic const DWORD std_consts[] = {STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,\n\n\t\t\t\t STD_ERROR_HANDLE};\n\n\n\nstatic bool handle_to_fn (HANDLE, char *);\n\n\n\n#define WCLEN(x) ((sizeof (x) / sizeof (WCHAR)) - 1)\n\nstatic const char unknown_file[] = \"some disk file\";\n\nstatic const WCHAR DEV_NULL[] = L\"\\\\Device\\\\Null\";\n\nstatic const WCHAR DEV_SOCKET[] = L\"\\\\Device\\\\Afd\";\n\n\n", "file_path": "libc/winsup/cygwin/dtable.cc", "rank": 88, "score": 58.46848477035209 }, { "content": "\n\n PCWSTR rel_path = L\"\\\\etc\\\\nsswitch.conf\";\n\n path.Length = cygheap->installation_root.Length\n\n\t\t+ wcslen (rel_path) * sizeof (WCHAR);\n\n path.MaximumLength = path.Length + sizeof (WCHAR);\n\n path.Buffer = (PWCHAR) alloca (path.MaximumLength);\n\n wcpcpy (wcpcpy (path.Buffer, cygheap->installation_root.Buffer), rel_path);\n\n InitializeObjectAttributes (&attr, &path, OBJ_CASE_INSENSITIVE,\n\n\t\t\t NULL, NULL);\n\n if (rl.init (&attr, buf, NT_MAX_PATH))\n\n while ((buf = rl.gets ()))\n\n nss_init_line (buf);\n\n nss_inited = true;\n\n}\n\n\n\n/* Override the ParentIndex value of the PDS_DOMAIN_TRUSTSW entry with the\n\n PosixOffset. */\n\n#define PosixOffset ParentIndex\n\n\n\nbool\n", "file_path": "libc/winsup/cygwin/uinfo.cc", "rank": 89, "score": 49.97828993246266 }, { "content": "}\n\n\n\nstatic void\n\ndecode_tty (char *buf, WCHAR *w32)\n\n{\n\n int ttyn = wcstol (w32, NULL, 10);\n\n __ptsname (buf, ttyn);\n\n}\n\n\n\n/* Try to derive posix filename from given handle. Return true if\n\n the handle is associated with a cygwin tty. */\n\nstatic bool\n\nhandle_to_fn (HANDLE h, char *posix_fn)\n\n{\n\n tmp_pathbuf tp;\n\n ULONG len = 0;\n\n WCHAR *maxmatchdos = NULL;\n\n PWCHAR device = tp.w_get ();\n\n int maxmatchlen = 0;\n\n OBJECT_NAME_INFORMATION *ntfn = (OBJECT_NAME_INFORMATION *) tp.w_get ();\n", "file_path": "libc/winsup/cygwin/dtable.cc", "rank": 90, "score": 48.2135562280717 }, { "content": "}\n\n\n\nstatic off_t\n\nformat_proc_partitions (void *, char *&destbuf)\n\n{\n\n OBJECT_ATTRIBUTES attr;\n\n IO_STATUS_BLOCK io;\n\n NTSTATUS status;\n\n HANDLE dirhdl;\n\n tmp_pathbuf tp;\n\n\n\n char *buf = tp.c_get ();\n\n char *bufptr = buf;\n\n char *ioctl_buf = tp.c_get ();\n\n PWCHAR mp_buf = tp.w_get ();\n\n WCHAR fpath[MAX_PATH];\n\n WCHAR gpath[MAX_PATH];\n\n DWORD len;\n\n\n\n /* Open \\Device object directory. */\n", "file_path": "libc/winsup/cygwin/fhandler_proc.cc", "rank": 92, "score": 47.51380695327129 }, { "content": "simple_nt_stat (const char *filename, struct stat *st)\n\n{\n\n size_t len = mbstowcs (NULL, filename, 0) + 1;\n\n WCHAR path[len + 8];\t/* Enough space for the NT prefix */\n\n PWCHAR p = path;\n\n UNICODE_STRING upath;\n\n OBJECT_ATTRIBUTES attr;\n\n FILE_BASIC_INFORMATION fbi;\n\n NTSTATUS status;\n\n\n\n wcscpy (p, L\"\\\\??\\\\\");\n\n p += 4;\n\n if (filename[0] == '\\\\' && filename[1] == '\\\\')\n\n {\n\n wcscpy (p, L\"UNC\");\n\n p += 3;\n\n p += mbstowcs (p, filename + 1, len);\n\n }\n\n else\n\n p += mbstowcs (p, filename, len);\n", "file_path": "libc/winsup/utils/dump_setup.cc", "rank": 93, "score": 47.50475732195784 }, { "content": "\t && (attr.ObjectName->Length > 7 * sizeof (WCHAR)\n\n\t\t || status == STATUS_NO_MEDIA_IN_DEVICE))\n\n\t{\n\n\t RtlSplitUnicodePath (attr.ObjectName, &dir, NULL);\n\n\t attr.ObjectName = &dir;\n\n\t if (status == STATUS_NO_MEDIA_IN_DEVICE)\n\n\t {\n\n\t no_media = true;\n\n\t dir.Length = 6 * sizeof (WCHAR);\n\n\t }\n\n\t else if (dir.Length > 7 * sizeof (WCHAR))\n\n\t dir.Length -= sizeof (WCHAR);\n\n\t status = NtOpenFile (&vol, access, &attr, &io, FILE_SHARE_VALID_FLAGS,\n\n\t\t\t FILE_OPEN_FOR_BACKUP_INTENT);\n\n\t}\n\n if (!NT_SUCCESS (status))\n\n\t{\n\n\t debug_printf (\"Cannot access path %S, status %y\",\n\n\t\t\tattr.ObjectName, status);\n\n\t return false;\n", "file_path": "libc/winsup/cygwin/mount.cc", "rank": 94, "score": 46.81664303065342 }, { "content": " void try_remove_forkables (PWCHAR dirbuf, size_t dirlen, size_t dirbufsize);\n\n void set_forkables_inheritance (bool);\n\n void request_forkables ();\n\n\n\n dll *end;\n\n dll *hold;\n\n dll_type hold_type;\n\n static muto protect;\n\n /* Use this buffer under loader lock conditions only. */\n\n static WCHAR NO_COPY nt_max_path_buffer[NT_MAX_PATH];\n\npublic:\n\n static HANDLE ntopenfile (PCWCHAR ntname, NTSTATUS *pstatus = NULL,\n\n\t\t\t ULONG openopts = 0, ACCESS_MASK access = 0,\n\n\t\t\t HANDLE rootDir = NULL);\n\n static bool read_fii (HANDLE fh, PFILE_INTERNAL_INFORMATION pfii);\n\n static PWCHAR form_ntname (PWCHAR ntbuf, size_t bufsize, PCWCHAR name);\n\n static PWCHAR form_shortname (PWCHAR shortbuf, size_t bufsize, PCWCHAR name);\n\n static PWCHAR nt_max_path_buf ()\n\n {\n\n return nt_max_path_buffer;\n", "file_path": "libc/winsup/cygwin/dll_init.h", "rank": 95, "score": 46.5534053021436 }, { "content": " fcwd_version_t fast_cwd_version;\n\n void override_win32_cwd (bool init, ULONG old_dismount_count);\n\n\n\npublic:\n\n UNICODE_STRING win32;\n\n static muto cwd_lock;\n\n const char *get_posix () const { return posix; };\n\n void reset_posix (wchar_t *w_cwd);\n\n char *get (char *buf, int need_posix = 1, int with_chroot = 0,\n\n\t unsigned ulen = NT_MAX_PATH);\n\n PWCHAR get (PWCHAR buf, unsigned buflen = NT_MAX_PATH)\n\n {\n\n cwd_lock.acquire ();\n\n buf[0] = L'\\0';\n\n wcsncat (buf, win32.Buffer, buflen - 1);\n\n cwd_lock.release ();\n\n return buf;\n\n }\n\n HANDLE get_handle () { return dir; }\n\n DWORD get_drive (char * dst)\n", "file_path": "libc/winsup/cygwin/cygheap.h", "rank": 97, "score": 45.843164029668365 }, { "content": "}\n\n\n\nextern \"C\" void\n\n__assert_func (const char *file, int line, const char *func,\n\n\t const char *failedexpr)\n\n{\n\n HANDLE h;\n\n\n\n /* If we don't have a console in a Windows program, then bring up a\n\n message box for the assertion failure. */\n\n\n\n h = CreateFile (\"CONOUT$\", GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,\n\n\t\t &sec_none_nih, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);\n\n if (h == INVALID_HANDLE_VALUE)\n\n {\n\n PWCHAR buf = (PWCHAR) alloca ((100 + strlen (failedexpr))\n\n\t\t\t\t * sizeof (WCHAR));\n\n __small_swprintf (buf,\n\n\t\t\tL\"Failed assertion\\n\\t%s\\nat line %d of file %s%s%s\",\n\n\t\t\tfailedexpr, line, file,\n", "file_path": "libc/winsup/cygwin/assert.cc", "rank": 98, "score": 44.64571350675112 } ]
C++
iverilog-parser/IRStmtVisitor.cc
gokhankici/xenon
d749abd865f2017cda323cf63cf38b585de9e7af
#include <sstream> #include "IRExporter.h" #include "IRStmtVisitor.h" #include "IRExprVisitor.h" using namespace std; void IRStmtVisitor::visit(PGAssign *ga) { if (ga->delay_count() != 0) { cerr << "continuous assignment has a delay:" << endl; ga->dump(cerr,0); cerr << endl; } if (ga->pin_count() != 2 || ga->pin(0) == NULL || ga->pin(1) == NULL) { cerr << "NOT SUPPORTED: PrologExporter@PGAssign: sth wrong with pins" << endl; exit(1); } irStmt = doAssignment(IRStmt_AssignmentType::CONTINUOUS, ga->pin(0), ga->pin(1)); } void IRStmtVisitor::visit(PGBuiltin *gb) { unsigned inputCnt = 0; IRUFOp fun; switch (gb->type()) { case PGBuiltin::AND: fun = IRBinaryOp::AND; inputCnt = 2; break; case PGBuiltin::NAND: fun = IRBinaryOp::NAND; inputCnt = 2; break; case PGBuiltin::OR: fun = IRBinaryOp::OR; inputCnt = 2; break; case PGBuiltin::NOR: fun = IRBinaryOp::NOR; inputCnt = 2; break; case PGBuiltin::XOR: fun = IRBinaryOp::XOR; inputCnt = 2; break; case PGBuiltin::XNOR: fun = IRBinaryOp::XNOR; inputCnt = 2; break; case PGBuiltin::NOT: fun = IRUnaryOp::NOT; inputCnt = 1; break; default: cerr << "NOT SUPPORTED: builtin gate type: " << gb->type() << endl; exit(1); } if (inputCnt + 1 != gb->pin_count()) { cerr << "builtin gate "; gb->dump(cerr, 0); cerr << " has wrong number of inputs" << endl; exit(1); } PExpr* lhs = gb->pin(0); IRExpr_UF* uf = new IRExpr_UF(fun); for (unsigned i = 1; i < inputCnt + 1; i++) { uf->addOperand(toIRExpr(gb->pin(i))); } irStmt = doAssignment(IRStmt_AssignmentType::CONTINUOUS, lhs, uf); } extern std::map<perm_string,Module*> pform_modules; void IRStmtVisitor::visit(PGModule *gm) { Module* mod; auto mod_itr = pform_modules.find(gm->get_type()); if (mod_itr != pform_modules.end()) { mod = (*mod_itr).second; } else { cerr << "module " << gm->get_type() << " not found !"; exit(1); } const string module_name(gm->get_type().str()); const string instance_name(gm->get_name().str()); IRStmt_ModuleInstance* mi = new IRStmt_ModuleInstance(module_name, instance_name); if (gm->pins_) { for (unsigned i=0; i < gm->npins_; i++) { const string name(gm->pins_[i].name.str()); PExpr* expr = gm->pins_[i].parm; if(expr == NULL) { cerr << "module instance " << instance_name << " of type " << module_name << " has a null pin for " << name << endl; gm->dump(cerr, 0); exit(1); } mi->setPort(IRExpr_Variable(name, mod), toIRExpr(expr)); } } else { PGate *g = (PGate *)gm; for (unsigned i = 0; i < g->pin_count(); i += 1) { const string name(mod->ports[i]->name.str()); PExpr* expr = g->pin(i); if(expr == NULL) { cerr << "module instance " << module_name << " of type " << module_name << " has a null pin for " << name << endl; gm->dump(cerr, 0); exit(1); } mi->setPort(IRExpr_Variable(name, mod), toIRExpr(expr)); } } if (!IRExporter::moduleExists(module_name)) { IRExporter submoduleExporter(this->irExporter, mod, gm); submoduleExporter.extractModule(); } irStmt = mi; } void IRStmtVisitor::visit(PCondit *c) { const IRStmt *thenStmt = (c->if_) ? toIRStmt(c->if_) : new IRStmt_Skip(); const IRStmt *elseStmt = (c->else_) ? toIRStmt(c->else_) : new IRStmt_Skip(); irStmt = new IRStmt_If(toIRExpr(c->expr_), thenStmt, elseStmt); } void IRStmtVisitor::visit(PAssign *ba) { if (ba->delay_ || ba->count_ || ba->event_) { cerr << "Blocking assignment has a delay, repeat or event:" << endl; ba->dump(cerr, 0); exit(1); } irStmt = doAssignment(IRStmt_AssignmentType::BLOCKING, ba->lval_, ba->rval_); } void IRStmtVisitor::visit(PAssignNB *nba) { if (nba->count_ || nba->event_) { cerr << "Non-blocking assignment has a delay, repeat or event:" << endl; nba->dump(cerr, 0); exit(1); } if (nba->delay_) { cerr << endl; nba->dump(cerr, 0); cerr << endl; } irStmt = doAssignment(IRStmt_AssignmentType::NON_BLOCKING, nba->lval_, nba->rval_); } void IRStmtVisitor::visit(PBlock *b) { if (b->pscope_name() != 0) { cerr << "NOT SUPPORTED: PBLock w/ pscope_name non-NULL" << endl; exit(1); } if (b->list_.size() == 0) { irStmt = new IRStmt_Skip(); } IRStmt_Sequence *irSeq = new IRStmt_Sequence(); for (unsigned idx = 0; idx < b->list_.size(); idx += 1) { Statement *s = b->list_[idx]; if (s) { irSeq->addStmt(toIRStmt(s)); } else { irSeq->addStmt(new IRStmt_Skip()); } } irStmt = irSeq; } void IRStmtVisitor::visit(PCase *c) { struct CaseStruct { const IRExpr *const caseExpr; const IRStmt *const caseStmt; }; vector<CaseStruct> items; bool hasDefault = false; Statement *defaultStmt = NULL; auto switchExpr = toIRExpr(c->expr_); for (unsigned idx = 0; idx < c->items_->count(); idx += 1) { PCase::Item *cur = (*c->items_)[idx]; if (cur == NULL || cur->stat == NULL) { continue; } if (cur->expr.size() == 0 && cur->stat) { hasDefault = true; defaultStmt = cur->stat; } else { if (cur->expr.size() == 1) { IRExpr_UF *uf = new IRExpr_UF(IRBinaryOp::LOGIC_EQ, switchExpr, toIRExpr(cur->expr.front())); CaseStruct cs = {uf, toIRStmt(cur->stat)}; items.push_back(cs); } else { IRExpr_UF *bigUf = new IRExpr_UF(IRBinaryOp::OR); for (auto idx_expr : cur->expr) { IRExpr_UF *uf = new IRExpr_UF(IRBinaryOp::LOGIC_EQ, switchExpr, toIRExpr(idx_expr)); bigUf->addOperand(uf); } CaseStruct cs = {bigUf, toIRStmt(cur->stat)}; items.push_back(cs); } } } irStmt = (hasDefault) ? toIRStmt(defaultStmt) : new IRStmt_Skip(); for (int i = items.size() - 1; i >= 0; i--) { CaseStruct cs = items.at(i); irStmt = new IRStmt_If(cs.caseExpr, cs.caseStmt, irStmt); } } void IRStmtVisitor::visit(PCallTask *ct) { ostringstream os; os << ct->path(); string taskname = os.str(); if (taskname == "$readmemh" || taskname == "$display" || taskname == "$finish") { irStmt = new IRStmt_Skip(); } else { cerr << endl << "unknown task name " << taskname << endl; exit(1); } } const IRStmt *IRStmtVisitor::doAssignment(IRStmt_AssignmentType assignmentType, const IRExpr *lhs, const IRExpr *rhs) const { if (auto lhsVar = dynamic_cast<const IRExpr_Variable *>(lhs)) { return new IRStmt_Assignment(assignmentType, lhsVar, rhs); } else if (auto lhsSelect = dynamic_cast<const IRExpr_Select *>(lhs)) { IRExpr_UF *newRhs = new IRExpr_UF(IROtherOp::WRITE_TO_INDEX); newRhs->addOperand(lhsSelect->getVariable()); for (auto i : lhsSelect->getIndices()) { newRhs->addOperand(i); } newRhs->addOperand(rhs); return new IRStmt_Assignment(assignmentType, lhsSelect->getVariable(), newRhs); } else { cerr << "Lhs is not a variable or a select expression" << endl; cerr << lhs->toIRString() << " = " << rhs->toIRString() << endl; exit(1); } }
#include <sstream> #include "IRExporter.h" #include "IRStmtVisitor.h" #include "IRExprVisitor.h" using namespace std; void IRStmtVisitor::visit(PGAssign *ga) {
if (ga->pin_count() != 2 || ga->pin(0) == NULL || ga->pin(1) == NULL) { cerr << "NOT SUPPORTED: PrologExporter@PGAssign: sth wrong with pins" << endl; exit(1); } irStmt = doAssignment(IRStmt_AssignmentType::CONTINUOUS, ga->pin(0), ga->pin(1)); } void IRStmtVisitor::visit(PGBuiltin *gb) { unsigned inputCnt = 0; IRUFOp fun; switch (gb->type()) { case PGBuiltin::AND: fun = IRBinaryOp::AND; inputCnt = 2; break; case PGBuiltin::NAND: fun = IRBinaryOp::NAND; inputCnt = 2; break; case PGBuiltin::OR: fun = IRBinaryOp::OR; inputCnt = 2; break; case PGBuiltin::NOR: fun = IRBinaryOp::NOR; inputCnt = 2; break; case PGBuiltin::XOR: fun = IRBinaryOp::XOR; inputCnt = 2; break; case PGBuiltin::XNOR: fun = IRBinaryOp::XNOR; inputCnt = 2; break; case PGBuiltin::NOT: fun = IRUnaryOp::NOT; inputCnt = 1; break; default: cerr << "NOT SUPPORTED: builtin gate type: " << gb->type() << endl; exit(1); } if (inputCnt + 1 != gb->pin_count()) { cerr << "builtin gate "; gb->dump(cerr, 0); cerr << " has wrong number of inputs" << endl; exit(1); } PExpr* lhs = gb->pin(0); IRExpr_UF* uf = new IRExpr_UF(fun); for (unsigned i = 1; i < inputCnt + 1; i++) { uf->addOperand(toIRExpr(gb->pin(i))); } irStmt = doAssignment(IRStmt_AssignmentType::CONTINUOUS, lhs, uf); } extern std::map<perm_string,Module*> pform_modules; void IRStmtVisitor::visit(PGModule *gm) { Module* mod; auto mod_itr = pform_modules.find(gm->get_type()); if (mod_itr != pform_modules.end()) { mod = (*mod_itr).second; } else { cerr << "module " << gm->get_type() << " not found !"; exit(1); } const string module_name(gm->get_type().str()); const string instance_name(gm->get_name().str()); IRStmt_ModuleInstance* mi = new IRStmt_ModuleInstance(module_name, instance_name); if (gm->pins_) { for (unsigned i=0; i < gm->npins_; i++) { const string name(gm->pins_[i].name.str()); PExpr* expr = gm->pins_[i].parm; if(expr == NULL) { cerr << "module instance " << instance_name << " of type " << module_name << " has a null pin for " << name << endl; gm->dump(cerr, 0); exit(1); } mi->setPort(IRExpr_Variable(name, mod), toIRExpr(expr)); } } else { PGate *g = (PGate *)gm; for (unsigned i = 0; i < g->pin_count(); i += 1) { const string name(mod->ports[i]->name.str()); PExpr* expr = g->pin(i); if(expr == NULL) { cerr << "module instance " << module_name << " of type " << module_name << " has a null pin for " << name << endl; gm->dump(cerr, 0); exit(1); } mi->setPort(IRExpr_Variable(name, mod), toIRExpr(expr)); } } if (!IRExporter::moduleExists(module_name)) { IRExporter submoduleExporter(this->irExporter, mod, gm); submoduleExporter.extractModule(); } irStmt = mi; } void IRStmtVisitor::visit(PCondit *c) { const IRStmt *thenStmt = (c->if_) ? toIRStmt(c->if_) : new IRStmt_Skip(); const IRStmt *elseStmt = (c->else_) ? toIRStmt(c->else_) : new IRStmt_Skip(); irStmt = new IRStmt_If(toIRExpr(c->expr_), thenStmt, elseStmt); } void IRStmtVisitor::visit(PAssign *ba) { if (ba->delay_ || ba->count_ || ba->event_) { cerr << "Blocking assignment has a delay, repeat or event:" << endl; ba->dump(cerr, 0); exit(1); } irStmt = doAssignment(IRStmt_AssignmentType::BLOCKING, ba->lval_, ba->rval_); } void IRStmtVisitor::visit(PAssignNB *nba) { if (nba->count_ || nba->event_) { cerr << "Non-blocking assignment has a delay, repeat or event:" << endl; nba->dump(cerr, 0); exit(1); } if (nba->delay_) { cerr << endl; nba->dump(cerr, 0); cerr << endl; } irStmt = doAssignment(IRStmt_AssignmentType::NON_BLOCKING, nba->lval_, nba->rval_); } void IRStmtVisitor::visit(PBlock *b) { if (b->pscope_name() != 0) { cerr << "NOT SUPPORTED: PBLock w/ pscope_name non-NULL" << endl; exit(1); } if (b->list_.size() == 0) { irStmt = new IRStmt_Skip(); } IRStmt_Sequence *irSeq = new IRStmt_Sequence(); for (unsigned idx = 0; idx < b->list_.size(); idx += 1) { Statement *s = b->list_[idx]; if (s) { irSeq->addStmt(toIRStmt(s)); } else { irSeq->addStmt(new IRStmt_Skip()); } } irStmt = irSeq; } void IRStmtVisitor::visit(PCase *c) { struct CaseStruct { const IRExpr *const caseExpr; const IRStmt *const caseStmt; }; vector<CaseStruct> items; bool hasDefault = false; Statement *defaultStmt = NULL; auto switchExpr = toIRExpr(c->expr_); for (unsigned idx = 0; idx < c->items_->count(); idx += 1) { PCase::Item *cur = (*c->items_)[idx]; if (cur == NULL || cur->stat == NULL) { continue; } if (cur->expr.size() == 0 && cur->stat) { hasDefault = true; defaultStmt = cur->stat; } else { if (cur->expr.size() == 1) { IRExpr_UF *uf = new IRExpr_UF(IRBinaryOp::LOGIC_EQ, switchExpr, toIRExpr(cur->expr.front())); CaseStruct cs = {uf, toIRStmt(cur->stat)}; items.push_back(cs); } else { IRExpr_UF *bigUf = new IRExpr_UF(IRBinaryOp::OR); for (auto idx_expr : cur->expr) { IRExpr_UF *uf = new IRExpr_UF(IRBinaryOp::LOGIC_EQ, switchExpr, toIRExpr(idx_expr)); bigUf->addOperand(uf); } CaseStruct cs = {bigUf, toIRStmt(cur->stat)}; items.push_back(cs); } } } irStmt = (hasDefault) ? toIRStmt(defaultStmt) : new IRStmt_Skip(); for (int i = items.size() - 1; i >= 0; i--) { CaseStruct cs = items.at(i); irStmt = new IRStmt_If(cs.caseExpr, cs.caseStmt, irStmt); } } void IRStmtVisitor::visit(PCallTask *ct) { ostringstream os; os << ct->path(); string taskname = os.str(); if (taskname == "$readmemh" || taskname == "$display" || taskname == "$finish") { irStmt = new IRStmt_Skip(); } else { cerr << endl << "unknown task name " << taskname << endl; exit(1); } } const IRStmt *IRStmtVisitor::doAssignment(IRStmt_AssignmentType assignmentType, const IRExpr *lhs, const IRExpr *rhs) const { if (auto lhsVar = dynamic_cast<const IRExpr_Variable *>(lhs)) { return new IRStmt_Assignment(assignmentType, lhsVar, rhs); } else if (auto lhsSelect = dynamic_cast<const IRExpr_Select *>(lhs)) { IRExpr_UF *newRhs = new IRExpr_UF(IROtherOp::WRITE_TO_INDEX); newRhs->addOperand(lhsSelect->getVariable()); for (auto i : lhsSelect->getIndices()) { newRhs->addOperand(i); } newRhs->addOperand(rhs); return new IRStmt_Assignment(assignmentType, lhsSelect->getVariable(), newRhs); } else { cerr << "Lhs is not a variable or a select expression" << endl; cerr << lhs->toIRString() << " = " << rhs->toIRString() << endl; exit(1); } }
if (ga->delay_count() != 0) { cerr << "continuous assignment has a delay:" << endl; ga->dump(cerr,0); cerr << endl; }
if_condition
[ { "content": "extern DLLEXPORT void (*vlog_startup_routines[])(void);\n", "file_path": "iverilog-parser/vpi_user.h", "rank": 0, "score": 98623.54510942122 }, { "content": "static void do_include();\n", "file_path": "iverilog-parser/ivlpp/lexor.c", "rank": 1, "score": 54072.9176525741 }, { "content": "extern char**include_dir;\n", "file_path": "iverilog-parser/ivlpp/globals.h", "rank": 2, "score": 52663.2608396363 }, { "content": "class PEVoid : public PExpr {\n\n\n\n public:\n\n explicit PEVoid();\n\n ~PEVoid();\n\n\n\n virtual NetExpr*elaborate_expr(Design*des, NetScope*scope,\n\n\t\t\t\t unsigned expr_wid,\n\n unsigned flags) const;\n\n};\n\n\n\n#endif /* IVL_PExpr_H */\n", "file_path": "iverilog-parser/PExpr.h", "rank": 3, "score": 52660.38472497118 }, { "content": "struct void_type_t : public data_type_t {\n\n virtual void pform_dump(std::ostream&out, unsigned indent) const;\n\n};\n\n\n\n/*\n\n * The enum_type_t holds the parsed declaration to represent an\n\n * enumeration. Since this is in the pform, it represents the type\n\n * before elaboration so the range, for example, may not be complete\n\n * until it is elaborated in a scope.\n\n */\n", "file_path": "iverilog-parser/pform_types.h", "rank": 4, "score": 52660.38472497118 }, { "content": "extern unsigned include_cnt;\n", "file_path": "iverilog-parser/ivlpp/globals.h", "rank": 5, "score": 52656.079698491114 }, { "content": "unsigned include_cnt = 0;\n", "file_path": "iverilog-parser/ivlpp/main.c", "rank": 6, "score": 52656.079698491114 }, { "content": "char**include_dir = 0;\n", "file_path": "iverilog-parser/ivlpp/main.c", "rank": 7, "score": 52656.079698491114 }, { "content": "static void include_filename();\n", "file_path": "iverilog-parser/ivlpp/lexor.c", "rank": 8, "score": 52656.079698491114 }, { "content": "int relative_include = 0;\n", "file_path": "iverilog-parser/ivlpp/main.c", "rank": 9, "score": 52656.079698491114 }, { "content": "extern int relative_include;\n", "file_path": "iverilog-parser/ivlpp/globals.h", "rank": 10, "score": 52656.079698491114 }, { "content": "struct include_stack_t\n\n{\n\n char* path;\n\n\n\n /* If the current input is from a file, this member is set. */\n\n FILE* file;\n\n\n\n /* If we are reparsing a macro expansion, file is 0 and this\n\n * member points to the string in progress\n\n */\n\n char* str;\n\n char* orig_str;\n\n\n\n int stringify_flag;\n\n\n\n unsigned lineno;\n\n YY_BUFFER_STATE yybs;\n\n\n\n struct include_stack_t* next;\n\n\n\n /* A single line comment can be associated with this include. */\n\n char* comment;\n", "file_path": "iverilog-parser/ivlpp/lexor.c", "rank": 11, "score": 52656.079698491114 }, { "content": "int heap_memory_used = 0;\n", "file_path": "benchmarks/picorv32/dhrystone/stdlib.c", "rank": 12, "score": 51316.33733326166 }, { "content": "static void expand_using_args()\n\n{\n\n char* head;\n\n char* tail;\n\n char* dest;\n\n int arg;\n\n int length;\n\n\n\n if (def_argc != cur_macro->argc)\n\n {\n\n emit_pathline(istack);\n\n fprintf(stderr, \"error: wrong number of arguments for `%s\\n\", cur_macro->name);\n\n return;\n\n }\n\n\n\n head = cur_macro->value;\n\n tail = head;\n\n\n\n while (*tail)\n\n {\n\n if (*tail != ARG_MARK)\n\n tail++;\n\n else\n\n {\n\n arg = tail[1]; assert(arg < def_argc);\n\n\n\n length = (tail - head) + def_argl[arg];\n\n exp_buf_grow_to_fit(length);\n\n\n\n dest = &exp_buf[exp_buf_size - exp_buf_free];\n\n memcpy(dest, head, tail - head);\n\n dest += tail - head;\n\n memcpy(dest, def_argv(arg), def_argl[arg]);\n\n\n\n exp_buf_free -= length;\n\n\n\n head = tail + 2;\n\n tail = head;\n\n }\n\n }\n\n\n\n length = tail - head;\n\n exp_buf_grow_to_fit(length);\n\n\n\n dest = &exp_buf[exp_buf_size - exp_buf_free];\n\n memcpy(dest, head, length + 1);\n\n\n\n exp_buf_free -= length + 1;\n", "file_path": "iverilog-parser/ivlpp/lexor.c", "rank": 13, "score": 51316.33733326166 }, { "content": "#include <string>\n\n#include <vector>\n\n#include <sstream>\n\n#include <unordered_map>\n\n\n\n#include \"IRExpr.h\"\n\n#include \"IRStmt.h\"\n\n\n\n#include \"IRExporterHelper.h\"\n\n\n\nusing namespace std;\n\n\n\nIRStmt::~IRStmt() {}\n\n\n\nvoid IRStmt_Sequence::addStmt(const IRStmt *stmt)\n\n{\n\n statements.push_back(stmt);\n\n}\n\n\n\nvoid IRStmt_ModuleInstance::setPort(const IRExpr_Variable &port, const IRExpr *value)\n", "file_path": "iverilog-parser/IRStmt.cc", "rank": 15, "score": 30.420973343322252 }, { "content": "\n\n# include <iostream>\n\n\n\n# include \"functor.h\"\n\n# include \"netlist.h\"\n\n\n\nusing namespace std;\n\n\n\nfunctor_t::~functor_t()\n\n{\n\n}\n\n\n\nvoid functor_t::event(Design*, NetEvent*)\n\n{\n\n}\n\n\n\nvoid functor_t::signal(Design*, NetNet*)\n\n{\n\n}\n\n\n", "file_path": "iverilog-parser/functor.cc", "rank": 16, "score": 29.844634426785582 }, { "content": "# include \"pform.h\"\n\n# include \"PPackage.h\"\n\n# include \"parse_misc.h\"\n\n# include \"parse_api.h\"\n\n# include <map>\n\n# include <sstream>\n\n# include \"ivl_assert.h\"\n\n\n\nusing namespace std;\n\n\n\n/*\n\n * This is a map of packages that have been defined.\n\n */\n\nmap<perm_string,PPackage*> pform_packages;\n\n\n\nstatic PPackage*pform_cur_package = 0;\n\n\n\nvoid pform_start_package_declaration(const struct vlltype&loc, const char*name,\n\n\t\t\t\t LexicalScope::lifetime_t lifetime)\n\n{\n", "file_path": "iverilog-parser/pform_package.cc", "rank": 17, "score": 29.633290891615893 }, { "content": "# include <iostream>\n\n# include <cassert>\n\n\n\nusing namespace std;\n\n\n\nivl_type_s::~ivl_type_s()\n\n{\n\n}\n\n\n\n/*\n\n * The derived class may override this to provide a more accurate\n\n * response.\n\n */\n\nbool ivl_type_s::packed(void) const\n\n{\n\n return false;\n\n}\n\n\n\nlong ivl_type_s::packed_width(void) const\n\n{\n", "file_path": "iverilog-parser/nettypes.cc", "rank": 18, "score": 28.118172907219986 }, { "content": "#include <string>\n\n#include <vector>\n\n#include <sstream>\n\n#include <iostream>\n\n#include <assert.h>\n\n\n\n#include \"IRExpr.h\"\n\n#include \"IRExporterHelper.h\"\n\n\n\nusing namespace std;\n\n\n\nIRExpr::~IRExpr() {}\n\n\n\ninline ostream &IRExpr_Constant::print(ostream &out) const\n\n{\n\n return out << \"const(\" << constant << \")\";\n\n}\n\n\n\ninline std::ostream &IRExpr_Variable::print(ostream &out) const\n\n{\n", "file_path": "iverilog-parser/IRExpr.cc", "rank": 19, "score": 27.94852471590164 }, { "content": "#include <iostream>\n\n\n\n#include \"IRModule.h\"\n\n#include \"IRExporterHelper.h\"\n\n\n\nusing namespace std;\n\n\n\nvoid IRModule::addPort(const IRPort &irPort)\n\n{\n\n ports.push_back(irPort);\n\n}\n\n\n\nvoid IRModule::addVariable(const IRVariable &irVariable)\n\n{\n\n variables.push_back(irVariable);\n\n}\n\n\n\nstd::ostream &operator<<(std::ostream &out, const IRVariableType &t)\n\n{\n\n switch (t)\n", "file_path": "iverilog-parser/IRModule.cc", "rank": 20, "score": 27.698226805728467 }, { "content": "# include \"netstruct.h\"\n\n# include \"netvector.h\"\n\n# include <iostream>\n\n\n\n# include \"ivl_assert.h\"\n\n\n\nusing namespace std;\n\n\n\nnetstruct_t::netstruct_t()\n\n: union_(false), packed_(false)\n\n{\n\n}\n\n\n\nnetstruct_t::~netstruct_t()\n\n{\n\n}\n\n\n\nvoid netstruct_t::union_flag(bool flag)\n\n{\n\n\t// This MUST be called before any members are pushed into the\n", "file_path": "iverilog-parser/netstruct.cc", "rank": 21, "score": 27.583684549979484 }, { "content": "# include \"netparray.h\"\n\n\n\nusing namespace std;\n\n\n\nnetsarray_t::~netsarray_t()\n\n{\n\n}\n\n\n\nnetparray_t::~netparray_t()\n\n{\n\n}\n\n\n\n/*\n\n * The packed width of a packed array is the packed width of the\n\n * element times the dimension width of the array itself.\n\n */\n\n\n\nbool netparray_t::packed(void) const\n\n{\n\n return true;\n", "file_path": "iverilog-parser/netparray.cc", "rank": 22, "score": 26.34705600715612 }, { "content": "# include <sstream>\n\n\n\nusing namespace std;\n\n\n\nLineInfo::LineInfo()\n\n: lineno_(0)\n\n{\n\n}\n\n\n\nLineInfo::LineInfo(const LineInfo&that) :\n\n file_(that.file_), lineno_(that.lineno_)\n\n{\n\n}\n\n\n\nLineInfo::~LineInfo()\n\n{\n\n}\n\n\n\nstring LineInfo::get_fileline() const\n\n{\n", "file_path": "iverilog-parser/LineInfo.cc", "rank": 23, "score": 25.5997790445154 }, { "content": "\n\n# include \"svector.h\"\n\n# include <string>\n\n# include <list>\n\n# include <iostream>\n\n\n\n#include \"Visitor.h\"\n\n\n\n#ifdef __GNUC__\n\n#if __GNUC__ > 2\n\nusing namespace std;\n\n#endif\n\n#endif\n\n\n", "file_path": "iverilog-parser/PDelays.h", "rank": 24, "score": 24.94772782069448 }, { "content": "#include <iostream>\n\n#include <iomanip>\n\n#include <stdint.h>\n\nusing namespace std;\n\n\n\nint main()\n\n{\n\n\tdouble f = 1.0;\n\n\tuint64_t i;\n\n\tuint64_t a;\n\n\n\n\twhile(1){\n\n\t\tcin >> a;\n\n\t\tf = *(double*)&a;\n\n\t\ti = (uint64_t)f;\n\n\t\tcout << i << endl;\n\n\t}\n\n\n\n\treturn 0;\n\n}\n", "file_path": "benchmarks/fpu2/double_to_long/c_test/test.cpp", "rank": 25, "score": 24.13264556813089 }, { "content": "#include <iostream>\n\n#include <iomanip>\n\n#include <stdint.h>\n\nusing namespace std;\n\n\n\nint main()\n\n{\n\n\tfloat f = 1.0;\n\n\tunsigned int i;\n\n\tuint32_t a;\n\n\n\n\twhile(1){\n\n\t\tcin >> a;\n\n\t\tf = *(float*)&a;\n\n\t\ti = (int)f;\n\n\t\tcout << i << endl;\n\n\t}\n\n\n\n\treturn 0;\n\n}\n", "file_path": "benchmarks/fpu2/float_to_int/c_test/test.cpp", "rank": 26, "score": 23.959237659181568 }, { "content": "#include <iostream>\n\n#include <iomanip>\n\n#include <stdint.h>\n\nusing namespace std;\n\n\n\nint main()\n\n{\n\n\tdouble f = 1.0;\n\n\tuint64_t i;\n\n\tint64_t b;\n\n\tuint64_t a;\n\n\n\n\twhile(1){\n\n\t\tcin >> a;\n\n\t\tb = a;\n\n\t\tf = double(b);\n\n\t\ti = *(uint64_t*)&f;\n\n\t\tcout << i << endl;\n\n\t}\n\n\n\n\treturn 0;\n\n}\n", "file_path": "benchmarks/fpu2/long_to_double/c_test/test.cpp", "rank": 27, "score": 23.959237659181568 }, { "content": "#include <iostream>\n\n#include <iomanip>\n\n#include <stdint.h>\n\nusing namespace std;\n\n\n\nint main()\n\n{\n\n uint32_t a;\n\n float b;\n\n\tdouble f = 1.0;\n\n\tuint64_t i;\n\n\n\n\twhile(1){\n\n\t\tcin >> a;\n\n b = *(float*)&a;\n\n\t\tf = (double)b;\n\n\t\ti = *(uint64_t*)&f;\n\n\t\tcout << i << endl;\n\n\t}\n\n\n\n\treturn 0;\n\n}\n", "file_path": "benchmarks/fpu2/float_to_double/c_test/test.cpp", "rank": 28, "score": 23.788541537278327 }, { "content": "#include <iostream>\n\n#include <iomanip>\n\n#include <stdint.h>\n\nusing namespace std;\n\n\n\nint main()\n\n{\n\n\tdouble f = 1.0;\n\n\tfloat i;\n\n\tuint64_t a;\n\n\tuint32_t z;\n\n\n\n\twhile(1){\n\n\t\tcin >> a;\n\n\t\tf = *(double*)&a;\n\n\t\ti = (float)f;\n\n z = *(uint32_t*)&i;\n\n\t\tcout << z << endl;\n\n\t}\n\n\n\n\treturn 0;\n\n}\n", "file_path": "benchmarks/fpu2/double_to_float/c_test/test.cpp", "rank": 29, "score": 23.788541537278327 }, { "content": "#include <iostream>\n\n#include <iomanip>\n\n#include <stdint.h>\n\nusing namespace std;\n\n\n\nint main()\n\n{\n\n\tfloat f = 1.0;\n\n\tunsigned int i;\n\n\tint32_t b;\n\n\tuint32_t a;\n\n\n\n\twhile(1){\n\n\t\tcin >> a;\n\n\t\tb = a;\n\n\t\tf = float(b);\n\n\t\ti = *(int*)&f;\n\n\t\tcout << i << endl;\n\n\t}\n\n\n\n\treturn 0;\n\n}\n", "file_path": "benchmarks/fpu2/int_to_float/c_test/test.cpp", "rank": 30, "score": 23.788541537278327 }, { "content": "#include <iostream>\n\n#include <iomanip>\n\nusing namespace std;\n\n\n\nint main()\n\n{\n\n\tfloat f = 1.0;\n\n\tunsigned int a, b, i;\n\n\n\n\twhile(1){\n\n\t\tcin >> a;\n\n\t\tcin >> b;\n\n\t\tf = *(float*)&a * *(float*)&b;\n\n\t\ti = *(int*)&f;\n\n\t\tcout << i << endl;\n\n\t}\n\n\n\n\treturn 0;\n\n}\n", "file_path": "benchmarks/fpu2/multiplier/c_test/test.cpp", "rank": 31, "score": 23.61179191286095 }, { "content": "#include <iostream>\n\n#include <iomanip>\n\nusing namespace std;\n\n\n\nint main()\n\n{\n\n\tfloat f = 1.0;\n\n\tunsigned int a, b, i;\n\n\n\n\twhile(1){\n\n\t\tcin >> a;\n\n\t\tcin >> b;\n\n\t\tf = *(float*)&a + *(float*)&b;\n\n\t\ti = *(int*)&f;\n\n\t\tcout << i << endl;\n\n\t}\n\n\n\n\treturn 0;\n\n}\n", "file_path": "benchmarks/fpu2/adder/c_test/test.cpp", "rank": 32, "score": 23.61179191286095 }, { "content": "#include <iostream>\n\n#include <iomanip>\n\nusing namespace std;\n\n\n\nint main()\n\n{\n\n\tfloat f = 1.0;\n\n\tunsigned int a, b, i;\n\n\n\n\twhile(1){\n\n\t\tcin >> a;\n\n\t\tcin >> b;\n\n\t\tf = *(float*)&a / *(float*)&b;\n\n\t\ti = *(int*)&f;\n\n\t\tcout << i << endl << flush;\n\n\t}\n\n\n\n\treturn 0;\n\n}\n", "file_path": "benchmarks/fpu2/divider/c_test/test.cpp", "rank": 33, "score": 23.430272507815875 }, { "content": "#include <iostream>\n\n#include <iomanip>\n\nusing namespace std;\n\n\n\nint main()\n\n{\n\n\tdouble f = 1.0;\n\n\tlong unsigned int a, b, i;\n\n\n\n\twhile(1){\n\n\t\tcin >> a;\n\n\t\tcin >> b;\n\n\t\tf = *(double*)&a * *(double*)&b;\n\n\t\ti = *(long unsigned int*)&f;\n\n\t\tcout << i << endl;\n\n\t}\n\n\n\n\treturn 0;\n\n}\n", "file_path": "benchmarks/fpu2/double_multiplier/c_test/test.cpp", "rank": 34, "score": 23.07579937914562 }, { "content": "#include <iostream>\n\n#include <iomanip>\n\nusing namespace std;\n\n\n\nint main()\n\n{\n\n\tdouble f = 1.0;\n\n\tunsigned long int a, b, i;\n\n\n\n\twhile(1){\n\n\t\tcin >> a;\n\n\t\tcin >> b;\n\n\t\tf = *(double*)&a / *(double*)&b;\n\n\t\ti = *(unsigned long int*)&f;\n\n\t\tcout << i << endl;\n\n\t}\n\n\n\n\treturn 0;\n\n}\n", "file_path": "benchmarks/fpu2/double_divider/c_test/test.cpp", "rank": 35, "score": 23.07579937914562 }, { "content": "#include <iostream>\n\n#include <iomanip>\n\nusing namespace std;\n\n\n\nint main()\n\n{\n\n\tdouble f = 1.0;\n\n\tunsigned long int a, b, i;\n\n\n\n\twhile(1){\n\n\t\tcin >> a;\n\n\t\tcin >> b;\n\n\t\tf = *(double*)&a + *(double*)&b;\n\n\t\ti = *(unsigned long int*)&f;\n\n\t\tcout << i << endl;\n\n\t}\n\n\n\n\treturn 0;\n\n}\n", "file_path": "benchmarks/fpu2/double_adder/c_test/test.cpp", "rank": 36, "score": 23.07579937914562 }, { "content": "# include <iostream>\n\n\n\nusing namespace std;\n\n\n\nnetdarray_t::netdarray_t(ivl_type_t vec)\n\n: netarray_t(vec)\n\n{\n\n}\n\n\n\nnetdarray_t::~netdarray_t()\n\n{\n\n}\n\n\n\nivl_variable_type_t netdarray_t::base_type(void) const\n\n{\n\n return IVL_VT_DARRAY;\n\n}\n\n\n\nbool netdarray_t::test_compatibility(ivl_type_t that) const\n\n{\n\n const netdarray_t*that_da = dynamic_cast<const netdarray_t*>(that);\n\n if (that_da == 0)\n\n\t return false;\n\n\n\n return element_type()->type_compatible(that_da->element_type());\n\n}\n", "file_path": "iverilog-parser/netdarray.cc", "rank": 37, "score": 22.945544643132784 }, { "content": "#include \"Visitor.h\"\n\n#include \"IRExporter.h\"\n\n#include \"IRExprVisitor.h\"\n\n#include \"IRStmtVisitor.h\"\n\n\n\n#define UNW_LOCAL_ONLY\n\n#include <cxxabi.h>\n\n#include <libunwind.h>\n\n#include <cstdio>\n\n\n\nusing namespace std;\n\n\n\nextern std::map<perm_string, Module *> pform_modules;\n\n\n\nstd::unordered_map<std::string, const IRModule*> IRExporter::irModules;\n\n\n\nstatic IRVariableType getVariableType(PWire *w)\n\n{\n\n switch (w->get_wire_type())\n\n {\n", "file_path": "iverilog-parser/IRExporter.cc", "rank": 38, "score": 22.689520762999962 }, { "content": "# include \"HName.h\"\n\n# include <iostream>\n\n# include <cstring>\n\n# include <cstdlib>\n\n\n\nusing namespace std;\n\n\n\nhname_t::hname_t()\n\n{\n\n}\n\n\n\nhname_t::hname_t(perm_string text)\n\n: name_(text)\n\n{\n\n}\n\n\n\nhname_t::hname_t(perm_string text, int num)\n\n: name_(text), number_(1)\n\n{\n\n number_[0] = num;\n", "file_path": "iverilog-parser/HName.cc", "rank": 39, "score": 22.15128096832208 }, { "content": "# include \"pform_types.h\"\n\n# include \"netlist.h\"\n\n# include \"netclass.h\"\n\n# include \"netdarray.h\"\n\n# include \"netenum.h\"\n\n# include \"netqueue.h\"\n\n# include \"netparray.h\"\n\n# include \"netscalar.h\"\n\n# include \"netstruct.h\"\n\n# include \"netvector.h\"\n\n# include \"netmisc.h\"\n\n# include <typeinfo>\n\n# include \"ivl_assert.h\"\n\n\n\nusing namespace std;\n\n\n\n/*\n\n * Some types have a list of ranges that need to be elaborated. This\n\n * function elaborates the ranges referenced by \"dims\" into the vector\n\n * \"ranges\".\n", "file_path": "iverilog-parser/elab_type.cc", "rank": 40, "score": 22.00209710188628 }, { "content": "\n\n# include \"StringHeap.h\"\n\n# include <string>\n\n\n\nusing namespace std;\n\n\n\n/*\n\n * This class holds line information for an internal object.\n\n *\n\n * Note that the file names are C-style strings that are allocated by\n\n * the lexor (which parses the line directives) and are never\n\n * deallocated. We can therefore safely store the pointer and never\n\n * delete the string, even if LineInfo objects are destroyed.\n\n */\n\n\n", "file_path": "iverilog-parser/LineInfo.h", "rank": 41, "score": 20.59536017985458 }, { "content": "# include \"netvector.h\"\n\n# include \"netdarray.h\"\n\n# include \"netparray.h\"\n\n# include \"netqueue.h\"\n\n# include \"util.h\"\n\n# include \"ivl_assert.h\"\n\n\n\nusing namespace std;\n\n\n\nstatic bool get_const_argument(NetExpr*exp, verinum&res)\n\n{\n\n switch (exp->expr_type()) {\n\n\t case IVL_VT_REAL: {\n\n\t NetECReal*cv = dynamic_cast<NetECReal*>(exp);\n\n\t if (cv == 0) return false;\n\n\t verireal tmp = cv->value();\n\n\t res = verinum(tmp.as_long());\n\n\t break;\n\n\t }\n\n\n", "file_path": "iverilog-parser/elab_sig.cc", "rank": 42, "score": 20.070358873122537 }, { "content": "\n\n# include \"functor.h\"\n\n# include \"netlist.h\"\n\n# include \"netvector.h\"\n\n# include \"netmisc.h\"\n\n# include \"compiler.h\"\n\n# include \"ivl_assert.h\"\n\n\n\nusing namespace std;\n\n\n\nbool NetProc::synth_async(Design*, NetScope*, NexusSet&, NetBus&, NetBus&)\n\n{\n\n return false;\n\n}\n\n\n\nbool NetProc::synth_sync(Design*des, NetScope*scope,\n\n\t\t\t bool& /* ff_negedge */,\n\n\t\t\t NetNet* /* ff_clk */, NetBus& /* ff_ce */,\n\n\t\t\t NetBus& /* ff_aclr*/, NetBus& /* ff_aset*/,\n\n\t\t\t vector<verinum>& /*ff_aset_value*/,\n", "file_path": "iverilog-parser/synth2.cc", "rank": 43, "score": 19.144981396845285 }, { "content": "# include \"netlist.h\"\n\n# include <iostream>\n\n\n\nusing namespace std;\n\n\n\nnetclass_t::netclass_t(perm_string name, netclass_t*sup)\n\n: name_(name), super_(sup), class_scope_(0), definition_scope_(0)\n\n{\n\n}\n\n\n\nnetclass_t::~netclass_t()\n\n{\n\n}\n\n\n\nbool netclass_t::set_property(perm_string pname, property_qualifier_t qual, ivl_type_s*ptype)\n\n{\n\n map<perm_string,size_t>::const_iterator cur;\n\n cur = properties_.find(pname);\n\n if (cur != properties_.end())\n\n\t return false;\n", "file_path": "iverilog-parser/netclass.cc", "rank": 44, "score": 19.068058800100356 }, { "content": "# include \"netmisc.h\"\n\n# include \"compiler.h\"\n\n# include <typeinfo>\n\n# include \"ivl_assert.h\"\n\n\n\nusing namespace std;\n\n\n\n/*\n\n * We only evaluate one function at a time, so to support the disable\n\n * statement, we just need to record the target block and then early\n\n * terminate each enclosing block or loop statement until we get back\n\n * to the target block.\n\n */\n\nstatic const NetScope*disable = 0;\n\n\n\nstatic NetExpr* fix_assign_value(const NetNet*lhs, NetExpr*rhs)\n\n{\n\n NetEConst*ce = dynamic_cast<NetEConst*>(rhs);\n\n if (ce == 0) return rhs;\n\n\n", "file_path": "iverilog-parser/net_func_eval.cc", "rank": 45, "score": 18.970547209791714 }, { "content": "# include <iostream>\n\n\n\nusing namespace std;\n\n\n\nnetqueue_t::netqueue_t(ivl_type_t vec)\n\n: netdarray_t(vec)\n\n{\n\n}\n\n\n\nnetqueue_t::~netqueue_t()\n\n{\n\n}\n\n\n\nivl_variable_type_t netqueue_t::base_type() const\n\n{\n\n return IVL_VT_QUEUE;\n\n}\n\n\n\nbool netqueue_t::test_compatibility(ivl_type_t that) const\n\n{\n\n const netqueue_t*that_q = dynamic_cast<const netqueue_t*>(that);\n\n if (that_q == 0)\n\n\t return false;\n\n\n\n return element_type()->type_compatible(that_q->element_type());\n\n}\n", "file_path": "iverilog-parser/netqueue.cc", "rank": 46, "score": 18.939674298940766 }, { "content": "\n\n/*\n\n * The discipline types include the discipline, nature and other\n\n * related types for managing declared and used disciplines in a\n\n * Verilog-AMS program.\n\n */\n\n\n\n# include \"StringHeap.h\"\n\n# include <iostream>\n\n# include <map>\n\n# include \"ivl_target.h\"\n\n# include \"LineInfo.h\"\n\n\n\nextern std::ostream& operator << (std::ostream&, ivl_dis_domain_t);\n\n\n", "file_path": "iverilog-parser/discipline.h", "rank": 47, "score": 18.8300627455627 }, { "content": "# include \"compiler.h\"\n\n# include <cassert>\n\n\n\nusing namespace std;\n\n\n\nnetenum_t::netenum_t(ivl_variable_type_t btype, bool signed_flag,\n\n\t\t bool integer_flag, long msb, long lsb, size_t name_count,\n\n\t\t enum_type_t*enum_type)\n\n: base_type_(btype), enum_type_(enum_type), signed_flag_(signed_flag),\n\n integer_flag_(integer_flag), msb_(msb), lsb_(lsb),\n\n names_(name_count), bits_(name_count)\n\n{\n\n}\n\n\n\nnetenum_t::~netenum_t()\n\n{\n\n}\n\n\n\nbool netenum_t::get_signed() const\n\n{\n", "file_path": "iverilog-parser/netenum.cc", "rank": 48, "score": 18.17302793756641 }, { "content": "\n\n# include <iostream>\n\n\n\n# include \"netlist.h\"\n\n# include <sstream>\n\n# include <cstring>\n\n# include <string>\n\n# include <typeinfo>\n\n# include <cstdlib>\n\n# include \"ivl_alloc.h\"\n\n\n\nvoid Nexus::connect(Link&r)\n\n{\n\n Nexus*r_nexus = r.next_? r.find_nexus_() : 0;\n\n if (this == r_nexus)\n\n\t return;\n\n\n\n delete[] name_;\n\n name_ = 0;\n\n\n", "file_path": "iverilog-parser/net_link.cc", "rank": 49, "score": 18.07222319523001 }, { "content": "#ifndef IVL_StringHeap_H\n\n#define IVL_StringHeap_H\n\n/*\n\n * Copyright (c) 2002-2014 Stephen Williams ([email protected])\n\n *\n\n * This source code is free software; you can redistribute it\n\n * and/or modify it in source code form under the terms of the GNU\n\n * General Public License as published by the Free Software\n\n * Foundation; either version 2 of the License, or (at your option)\n\n * any later version.\n\n *\n\n * This program is distributed in the hope that it will be useful,\n\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\n * GNU General Public License for more details.\n\n *\n\n * You should have received a copy of the GNU General Public License\n\n * along with this program; if not, write to the Free Software\n\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n */\n\n\n\n# include <string>\n\n#include \"Visitor.h\"\n\n\n\nusing namespace std;\n\n\n", "file_path": "iverilog-parser/StringHeap.h", "rank": 50, "score": 16.85778842909899 }, { "content": "\n\n#include \"srec.hpp\"\n\n\n\n\n\nnamespace srec {\n\n\n\nunsigned char hctoi (unsigned char hc) {\n\n if (hc >= 'a') return hc- 87;\n\n else if(hc >= 'A') return hc- 55;\n\n else return hc- 48;\n\n}\n\n\n\nsrec_file::srec_file (\n\n std::string path\n\n) {\n\n\n\n std::ifstream file (path);\n\n\n\n if(file.is_open()) {\n\n\n", "file_path": "benchmarks/xcrypto-ref/flow/verilator/srec.cpp", "rank": 51, "score": 16.70405452311943 }, { "content": "\n\n#include \"srec.hpp\"\n\n\n\n\n\nnamespace srec {\n\n\n\nunsigned char hctoi (unsigned char hc) {\n\n if (hc >= 'a') return hc- 87;\n\n else if(hc >= 'A') return hc- 55;\n\n else return hc- 48;\n\n}\n\n\n\nsrec_file::srec_file (\n\n std::string path\n\n) {\n\n\n\n std::ifstream file (path);\n\n\n\n if(file.is_open()) {\n\n\n", "file_path": "benchmarks/scarv-cpu/flow/verilator/srec.cpp", "rank": 52, "score": 16.70405452311943 }, { "content": "#include \"Visitor.h\"\n\n#include \"PrologExporter.h\"\n\n#include \"ExprVisitor.h\"\n\n\n\n#define UNW_LOCAL_ONLY\n\n#include <cxxabi.h>\n\n#include <libunwind.h>\n\n#include <cstdio>\n\n#include <cstdlib>\n\n\n\nvoid backtrace() {\n\n unw_cursor_t cursor;\n\n unw_context_t context;\n\n\n\n // Initialize cursor to current frame for local unwinding.\n\n unw_getcontext(&context);\n\n unw_init_local(&cursor, &context);\n\n\n\n std::fprintf(stderr, \"PRINTING THE STACK TRACE :\\n\");\n\n\n", "file_path": "iverilog-parser/PrologExporter.cc", "rank": 53, "score": 16.53433940144007 }, { "content": " inline bool is_interface() const { return is_interface_; }\n\n TYPE type() const;\n\n void print_type(ostream&) const;\n\n\n\n\t// This provides a link to the variable initialisation process\n\n\t// for use when evaluating a constant function. Note this is\n\n\t// only used for static functions - the variable initialization\n\n\t// for automatic functions is included in the function definition.\n\n void set_var_init(const NetProc*proc) { var_init_ = proc; }\n\n const NetProc* var_init() const { return var_init_; }\n\n\n\n void set_task_def(NetTaskDef*);\n\n void set_func_def(NetFuncDef*);\n\n void set_class_def(netclass_t*);\n\n void set_module_name(perm_string);\n\n\n\n NetTaskDef* task_def();\n\n NetFuncDef* func_def();\n\n\n\n\t// This is used by the evaluate_function setup to collect\n", "file_path": "iverilog-parser/netlist.h", "rank": 54, "score": 16.402352869969324 }, { "content": " std::fprintf(stderr, \" -- error: unable to obtain symbol name for this frame\\n\");\n\n }\n\n }\n\n std::fprintf(stderr, \"\\n\");\n\n}\n\n\n\nusing namespace std;\n\n\n\nextern std::map<perm_string,Module*> pform_modules;\n\n\n\nconst string prolog_comment = \"% \";\n\nconst string sep = \"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\";\n\nconst string sep2 = \"%-------------------------------------------------------------------------------\";\n\n\n\nconst string missing_id = \"id_MISSING_ID\";\n\n\n\nconst string id_prefix = \"\"; // \"v_\";\n\n\n\nconst string nopStmt = \"skip\";\n\n\n", "file_path": "iverilog-parser/PrologExporter.cc", "rank": 55, "score": 16.291618928550818 }, { "content": "# endif\n\n# else\n\n# define YY_NULLPTR ((void*)0)\n\n# endif\n\n# endif\n\n\n\n/* Enabling verbose error messages. */\n\n#ifdef YYERROR_VERBOSE\n\n# undef YYERROR_VERBOSE\n\n# define YYERROR_VERBOSE 1\n\n#else\n\n# define YYERROR_VERBOSE 0\n\n#endif\n\n\n\n/* Use api.header.include to #include this header\n\n instead of duplicating it here. */\n\n#ifndef YY_VL_PARSE_HH_INCLUDED\n\n# define YY_VL_PARSE_HH_INCLUDED\n\n/* Debug traces. */\n\n#ifndef YYDEBUG\n", "file_path": "iverilog-parser/parse.cc", "rank": 56, "score": 16.105769175879303 }, { "content": "#define UNW_LOCAL_ONLY\n\n#include <cxxabi.h>\n\n#include <libunwind.h>\n\n#include <cstdio>\n\n#include <cstdlib>\n\n\n\n#include \"IRExporterHelper.h\"\n\n\n\nvoid backtrace() {\n\n unw_cursor_t cursor;\n\n unw_context_t context;\n\n\n\n // Initialize cursor to current frame for local unwinding.\n\n unw_getcontext(&context);\n\n unw_init_local(&cursor, &context);\n\n\n\n std::fprintf(stderr, \"PRINTING THE STACK TRACE :\\n\");\n\n\n\n // Unwind frames one by one, going up the frame stack.\n\n while (unw_step(&cursor) > 0) {\n", "file_path": "iverilog-parser/IRExporterHelper.cc", "rank": 57, "score": 15.735788896727193 }, { "content": " void decay_time(const NetExpr* d) { delay3_ = d; }\n\n\n\n void dump_obj_attr(ostream&, unsigned) const;\n\n\n\n virtual void show_type(std::ostream&fd) const;\n\n\n\n private:\n\n NetScope*scope_;\n\n perm_string name_;\n\n const NetExpr* delay1_;\n\n const NetExpr* delay2_;\n\n const NetExpr* delay3_;\n\n};\n\n\n\n/*\n\n* Objects that can be island branches are derived from this. (It is\n\n* possible for an object to be a NetObj and an IslandBranch.) This is\n\n* used to collect island information about the node.\n\n*/\n\n\n", "file_path": "iverilog-parser/netlist.h", "rank": 58, "score": 15.265527856556902 }, { "content": "\n\n\t// Find the elaborated signal (NetNet) for a static\n\n\t// property. Search by name. The signal is created by the\n\n\t// elaborate_sig pass.\n\n NetNet*find_static_property(perm_string name) const;\n\n\n\n\t// Test if this scope is a method within the class. This is\n\n\t// used to check scope for handling data protection keywords\n\n\t// \"local\" and \"protected\".\n\n bool test_scope_is_method(const NetScope*scope) const;\n\n\n\n void elaborate_sig(Design*des, PClass*pclass);\n\n void elaborate(Design*des, PClass*pclass);\n\n\n\n void emit_scope(struct target_t*tgt) const;\n\n bool emit_defs(struct target_t*tgt) const;\n\n\n\n std::ostream& debug_dump(std::ostream&fd) const;\n\n void dump_scope(ostream&fd) const;\n\n\n", "file_path": "iverilog-parser/netclass.h", "rank": 59, "score": 15.205548138541008 }, { "content": " void visit(PCase*) ;\n\n void visit(PCallTask*) ;\n\n void visit(PForStatement* o) { std::cerr << \"NOT SUPPORTED: \" << typeid(*this).name() << \" @ \" << typeid(*o).name() << std::endl; exit(1); } \n\n\n\n void visit(PExpr* o) { std::cerr << \"NOT SUPPORTED: \" << typeid(*this).name() << \" @ \" << typeid(*o).name() << std::endl; exit(1); }\n\n void visit(PEIdent* o) { std::cerr << \"NOT SUPPORTED: \" << typeid(*this).name() << \" @ \" << typeid(*o).name() << std::endl; exit(1); }\n\n void visit(PETernary* o) { std::cerr << \"NOT SUPPORTED: \" << typeid(*this).name() << \" @ \" << typeid(*o).name() << std::endl; exit(1); }\n\n void visit(PEConcat* o) { std::cerr << \"NOT SUPPORTED: \" << typeid(*this).name() << \" @ \" << typeid(*o).name() << std::endl; exit(1); }\n\n void visit(PECallFunction* o) { std::cerr << \"NOT SUPPORTED: \" << typeid(*this).name() << \" @ \" << typeid(*o).name() << std::endl; exit(1); }\n\n void visit(PENumber* o) { std::cerr << \"NOT SUPPORTED: \" << typeid(*this).name() << \" @ \" << typeid(*o).name() << std::endl; exit(1); }\n\n void visit(PEEvent* o) { std::cerr << \"NOT SUPPORTED: \" << typeid(*this).name() << \" @ \" << typeid(*o).name() << std::endl; exit(1); }\n\n void visit(PEBinary* o) { std::cerr << \"NOT SUPPORTED: \" << typeid(*this).name() << \" @ \" << typeid(*o).name() << std::endl; exit(1); }\n\n void visit(PEUnary* o) { std::cerr << \"NOT SUPPORTED: \" << typeid(*this).name() << \" @ \" << typeid(*o).name() << std::endl; exit(1); }\n\n void visit(PEString* o) { std::cerr << \"NOT SUPPORTED: \" << typeid(*this).name() << \" @ \" << typeid(*o).name() << std::endl; exit(1); }\n\n\n\n void visit(PDelays* o) { std::cerr << \"NOT SUPPORTED: \" << typeid(*this).name() << \" @ \" << typeid(*o).name() << std::endl; exit(1); }\n\n void visit(data_type_t* o) { std::cerr << \"NOT SUPPORTED: \" << typeid(*this).name() << \" @ \" << typeid(*o).name() << std::endl; exit(1); }\n\n\n\n const IRStmt *getIRStmt()\n\n {\n", "file_path": "iverilog-parser/IRStmtVisitor.h", "rank": 60, "score": 15.046590114997834 }, { "content": " void visit(PGModule*o) { std::cerr << \"NOT SUPPORTED: \" << typeid(*this).name() << \" @ \" << typeid(*o).name() << std::endl; exit(1); }\n\n void visit(Statement*o) { std::cerr << \"NOT SUPPORTED: \" << typeid(*this).name() << \" @ \" << typeid(*o).name() << std::endl; exit(1); }\n\n void visit(PForStatement*o) { std::cerr << \"NOT SUPPORTED: \" << typeid(*this).name() << \" @ \" << typeid(*o).name() << std::endl; exit(1); }\n\n void visit(PProcess*o) { std::cerr << \"NOT SUPPORTED: \" << typeid(*this).name() << \" @ \" << typeid(*o).name() << std::endl; exit(1); }\n\n void visit(PEventStatement*o) { std::cerr << \"NOT SUPPORTED: \" << typeid(*this).name() << \" @ \" << typeid(*o).name() << std::endl; exit(1); }\n\n void visit(PCondit*o) { std::cerr << \"NOT SUPPORTED: \" << typeid(*this).name() << \" @ \" << typeid(*o).name() << std::endl; exit(1); }\n\n void visit(PAssign*o) { std::cerr << \"NOT SUPPORTED: \" << typeid(*this).name() << \" @ \" << typeid(*o).name() << std::endl; exit(1); }\n\n void visit(PAssignNB*o) { std::cerr << \"NOT SUPPORTED: \" << typeid(*this).name() << \" @ \" << typeid(*o).name() << std::endl; exit(1); }\n\n void visit(PBlock*o) { std::cerr << \"NOT SUPPORTED: \" << typeid(*this).name() << \" @ \" << typeid(*o).name() << std::endl; exit(1); }\n\n void visit(PCase*o) { std::cerr << \"NOT SUPPORTED: \" << typeid(*this).name() << \" @ \" << typeid(*o).name() << std::endl; exit(1); }\n\n void visit(PCallTask*o) { std::cerr << \"NOT SUPPORTED: \" << typeid(*this).name() << \" @ \" << typeid(*o).name() << std::endl; exit(1); }\n\n void visit(PDelays*o) { std::cerr << \"NOT SUPPORTED: \" << typeid(*this).name() << \" @ \" << typeid(*o).name() << std::endl; exit(1); }\n\n void visit(data_type_t*o) { std::cerr << \"NOT SUPPORTED: \" << typeid(*this).name() << \" @ \" << typeid(*o).name() << std::endl; exit(1); }\n\n};\n\n\n\n#endif\n", "file_path": "iverilog-parser/ExprVisitor.h", "rank": 61, "score": 15.004208174714694 }, { "content": "extern void pform_bind_attributes(map<perm_string,PExpr*>&attributes,\n\n\t\t\t\t list<named_pexpr_t>*attr,\n\n\t\t\t\t bool keep_attr =false);\n\n\n\n /* The lexor calls this function to change the default nettype. */\n\nextern void pform_set_default_nettype(NetNet::Type net,\n\n\t\t\t\t const char*file,\n\n\t\t\t\t unsigned lineno);\n\n\n\n /* Return true if currently processing a program block. This can be\n\n used to reject statements that cannot exist in program blocks. */\n\nextern bool pform_in_program_block(void);\n\n\n\n /* Return true if currently processing an interface. This can be\n\n used to reject statements that cannot exist in interfaces. */\n\nextern bool pform_in_interface(void);\n\n\n\n/*\n\n * Look for the given wire in the current lexical scope. If the wire\n\n * (including variables of any type) cannot be found in the current\n", "file_path": "iverilog-parser/pform.h", "rank": 62, "score": 14.893515093125815 }, { "content": "\n\nusing namespace std;\n\n\n\nnetreal_t netreal_t::type_real;\n\nnetreal_t netreal_t::type_shortreal;\n\nnetstring_t netstring_t::type_string;\n\n\n\nnetreal_t::~netreal_t()\n\n{\n\n}\n\n\n\nivl_variable_type_t netreal_t::base_type() const\n\n{\n\n return IVL_VT_REAL;\n\n}\n\n\n\nnetstring_t::~netstring_t()\n\n{\n\n}\n\n\n\nivl_variable_type_t netstring_t::base_type() const\n\n{\n\n return IVL_VT_STRING;\n\n}\n", "file_path": "iverilog-parser/netscalar.cc", "rank": 63, "score": 14.749027646919421 }, { "content": "#define YY_ASSERT(E) ((void) (0 && (E)))\n\n\n\n#if ! defined yyoverflow || YYERROR_VERBOSE\n\n\n\n/* The parser invokes alloca or malloc; define the necessary symbols. */\n\n\n\n# ifdef YYSTACK_USE_ALLOCA\n\n# if YYSTACK_USE_ALLOCA\n\n# ifdef __GNUC__\n\n# define YYSTACK_ALLOC __builtin_alloca\n\n# elif defined __BUILTIN_VA_ARG_INCR\n\n# include <alloca.h> /* INFRINGES ON USER NAME SPACE */\n\n# elif defined _AIX\n\n# define YYSTACK_ALLOC __alloca\n\n# elif defined _MSC_VER\n\n# include <malloc.h> /* INFRINGES ON USER NAME SPACE */\n\n# define alloca _alloca\n\n# else\n\n# define YYSTACK_ALLOC alloca\n\n# if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS\n", "file_path": "iverilog-parser/parse.cc", "rank": 64, "score": 14.221615074225358 }, { "content": " netenum_t* enumeration_for_key(const enum_type_t*key) const;\n\n\n\n\t// Look up an enumeration literal in this scope. If the\n\n\t// literal is present, return the expression that defines its\n\n\t// value.\n\n const NetExpr* enumeration_expr(perm_string key);\n\n\n\n\t// Definitions scopes can also hold classes, by name.\n\n void add_class(netclass_t*class_type);\n\n\n\n protected:\n\n\t// Enumerations. The enum_sets_ is a list of all the\n\n\t// enumerations present in this scope. The enum_names_ is a\n\n\t// map of all the enumeration names back to the sets that\n\n\t// contain them.\n\n std::map<const enum_type_t*,netenum_t*> enum_sets_;\n\n std::map<perm_string,NetEConstEnum*> enum_names_;\n\n\n\n\t// This is a map of all the classes (by name) in this scope.\n\n std::map<perm_string,netclass_t*> classes_;\n\n\n\n};\n\n\n\n/*\n\n * This object type is used to contain a logical scope within a\n\n * design. The scope doesn't represent any executable hardware, but is\n\n * just a handle that netlist processors can use to grab at the design.\n\n */\n", "file_path": "iverilog-parser/netlist.h", "rank": 65, "score": 14.092596493898423 }, { "content": "# include \"compiler.h\"\n\n\n\n# include \"netlist.h\"\n\n# include \"netclass.h\"\n\n# include \"netenum.h\"\n\n# include <cstring>\n\n# include <cstdlib>\n\n# include <sstream>\n\n# include \"ivl_assert.h\"\n\n\n", "file_path": "iverilog-parser/net_scope.cc", "rank": 66, "score": 13.804069007040045 }, { "content": "\n\n# include \"parse_misc.h\"\n\n# include \"compiler.h\"\n\n# include \"pform.h\"\n\n# include \"Statement.h\"\n\n# include \"PSpec.h\"\n\n# include <stack>\n\n# include <cstring>\n\n# include <sstream>\n\n\n", "file_path": "iverilog-parser/parse.cc", "rank": 67, "score": 13.741499995493607 }, { "content": "\n\n# include <iostream>\n\n\n\n# include \"target.h\"\n\n# include <typeinfo>\n\n\n\ntarget_t::~target_t()\n\n{\n\n}\n\n\n\nvoid target_t::scope(const NetScope*)\n\n{\n\n}\n\n\n\nvoid target_t::convert_module_ports(const NetScope*)\n\n{\n\n}\n\n\n\nbool target_t::branch(const NetBranch*obj)\n\n{\n", "file_path": "iverilog-parser/target.cc", "rank": 68, "score": 13.557479952022039 }, { "content": "# include \"netlist.h\"\n\n# include \"netenum.h\"\n\n# include \"netvector.h\"\n\n# include \"netdarray.h\"\n\n# include \"netparray.h\"\n\n# include \"netclass.h\"\n\n# include \"netmisc.h\"\n\n# include \"util.h\"\n\n# include \"parse_api.h\"\n\n# include \"compiler.h\"\n\n# include \"ivl_assert.h\"\n\n\n\n\n\n// Implemented in elab_scope.cc\n\nextern void set_scope_timescale(Design*des, NetScope*scope, PScope*pscope);\n\n\n\nvoid PGate::elaborate(Design*, NetScope*) const\n\n{\n\n cerr << \"internal error: what kind of gate? \" <<\n\n\t typeid(*this).name() << endl;\n", "file_path": "iverilog-parser/elaborate.cc", "rank": 69, "score": 13.520883523547358 }, { "content": "\n\n# include <iostream>\n\n\n\n# include <cassert>\n\n# include <typeinfo>\n\n# include \"netlist.h\"\n\n# include \"netmisc.h\"\n\n\n\nvoid NetProc::nex_output(NexusSet&)\n\n{\n\n cerr << get_fileline()\n\n\t << \": internal error: NetProc::nex_output not implemented\"\n\n\t << endl;\n\n cerr << get_fileline()\n\n\t << \": : on object type \" << typeid(*this).name()\n\n\t << endl;\n\n}\n\n\n\nvoid NetAssign_::nex_output(NexusSet&out)\n\n{\n", "file_path": "iverilog-parser/net_nex_output.cc", "rank": 70, "score": 13.472422603873051 }, { "content": "\n\n# include \"parse_misc.h\"\n\n# include <cstdarg>\n\n# include <cstdio>\n\n# include <iostream>\n\n\n\nextern const char*vl_file;\n\nunsigned error_count = 0;\n\nunsigned warn_count = 0;\n\nunsigned long based_size = 0;\n\n\n\nstd::ostream& operator << (std::ostream&o, const YYLTYPE&loc)\n\n{\n\n if (loc.text)\n\n\t o << loc.text << \":\";\n\n else\n\n\t o << \"<>:\";\n\n o << loc.first_line;\n\n return o;\n\n}\n", "file_path": "iverilog-parser/parse_misc.cc", "rank": 71, "score": 13.401980887930819 }, { "content": "\n\n# include <iostream>\n\n\n\n# include \"PDelays.h\"\n\n# include \"PExpr.h\"\n\n# include \"verinum.h\"\n\n# include \"netmisc.h\"\n\n\n\nbool dly_used_no_timescale = false;\n\nbool dly_used_timescale = false;\n\nbool display_ts_dly_warning = true;\n\n\n\n\n\nPDelays::PDelays()\n\n{\n\n delete_flag_ = true;\n\n for (unsigned idx = 0 ; idx < 3 ; idx += 1)\n\n\t delay_[idx] = 0;\n\n}\n\n\n", "file_path": "iverilog-parser/PDelays.cc", "rank": 72, "score": 13.387235219668552 }, { "content": "}\n\n\n\nvoid pform_dump(std::ostream&out, const PPackage*pac)\n\n{\n\n pac->pform_dump(out);\n\n}\n\n\n\nvoid PPackage::pform_dump(std::ostream&out) const\n\n{\n\n out << \"package \" << pscope_name() << endl;\n\n dump_localparams_(out, 4);\n\n dump_parameters_(out, 4);\n\n dump_enumerations_(out, 4);\n\n dump_tasks_(out, 4);\n\n dump_funcs_(out, 4);\n\n out << \"endpackage\" << endl;\n\n}\n\n\n\nvoid pform_dump(std::ostream&fd, const PTaskFunc*obj)\n\n{\n\n obj->dump(fd, 0);\n\n}\n", "file_path": "iverilog-parser/pform_dump.cc", "rank": 73, "score": 13.270490615000671 }, { "content": " virtual void dump(std::ostream&, unsigned) const =0;\n\n\n\n protected:\n\n\t// Elaborate the ports list. Write into the ports vector the\n\n\t// NetNet pointers for the ports, and write into the pdefs the\n\n\t// default value expressions, if any.\n\n void elaborate_sig_ports_(Design*des, NetScope*scope,\n\n\t\t\t\tstd::vector<NetNet*>&ports,\n\n\t\t\t\tstd::vector<NetExpr*>&pdefs) const;\n\n\n\n void dump_ports_(std::ostream&out, unsigned ind) const;\n\n\n\n private:\n\n VISITOR_FRIENDS;\n\n class_type_t*this_type_;\n\n std::vector<pform_tf_port_t>*ports_;\n\n};\n\n\n\n/*\n\n * The PTask holds the parsed definitions of a task.\n\n */\n", "file_path": "iverilog-parser/PTask.h", "rank": 74, "score": 13.232341160737068 }, { "content": "#ifndef PROLOG_EXPORTER_H\n\n#define PROLOG_EXPORTER_H\n\n\n\n#include <iostream>\n\n#include <vector>\n\n#include <sstream>\n\n#include <cassert>\n\n#include <unordered_set>\n\n#include <unordered_map>\n\n\n\n#include \"Visitor.h\"\n\n#include \"ExprVisitor.h\"\n\n\n", "file_path": "iverilog-parser/PrologExporter.h", "rank": 75, "score": 13.216464350407605 }, { "content": "\tint n;\n\n\tfor ( n = 0; s[n]; ++n )\n\n\t\t;\n\n\n\n\treturn n;\n\n}\n\n#endif\n\n\n\nvoid *VLalloc (yy_size_t size )\n\n{\n\n\t\t\treturn malloc(size);\n\n}\n\n\n\nvoid *VLrealloc (void * ptr, yy_size_t size )\n\n{\n\n\t\t\n\n\t/* The cast to (char *) in the following accommodates both\n\n\t * implementations that use char* generic pointers, and those\n\n\t * that use void* generic pointers. It works with the latter\n\n\t * because both ANSI C and C++ allow castless assignment from\n", "file_path": "iverilog-parser/lexor.cc", "rank": 76, "score": 13.195572361301954 }, { "content": "# include <iostream>\n\n\n\nusing namespace std;\n\n\n\nnetvector_t netvector_t::atom2s64 (IVL_VT_BOOL, 63, 0, true);\n\nnetvector_t netvector_t::atom2u64 (IVL_VT_BOOL, 63, 0, false);\n\nnetvector_t netvector_t::atom2s32 (IVL_VT_BOOL, 31, 0, true);\n\nnetvector_t netvector_t::atom2u32 (IVL_VT_BOOL, 31, 0, false);\n\nnetvector_t netvector_t::atom2s16 (IVL_VT_BOOL, 15, 0, true);\n\nnetvector_t netvector_t::atom2u16 (IVL_VT_BOOL, 15, 0, false);\n\nnetvector_t netvector_t::atom2s8 (IVL_VT_BOOL, 7, 0, true);\n\nnetvector_t netvector_t::atom2u8 (IVL_VT_BOOL, 7, 0, false);\n\n\n\n//netvector_t netvector_t::scalar_bool (IVL_VT_BOOL);\n\nnetvector_t netvector_t::scalar_logic (IVL_VT_LOGIC);\n\n\n\nnetvector_t::netvector_t(ivl_variable_type_t type, long msb, long lsb, bool flag)\n\n: type_(type), signed_(flag), isint_(false), is_scalar_(false)\n\n{\n\n packed_dims_.push_back(netrange_t(msb,lsb));\n", "file_path": "iverilog-parser/netvector.cc", "rank": 77, "score": 13.124679521085307 }, { "content": "\n\n# include <iostream>\n\n# include <set>\n\n# include <cstdlib>\n\n\n\n/*\n\n * This source file contains all the implementations of the Design\n\n * class declared in netlist.h.\n\n */\n\n\n\n# include \"netlist.h\"\n\n# include \"util.h\"\n\n# include \"compiler.h\"\n\n# include \"netmisc.h\"\n\n# include \"PExpr.h\"\n\n# include \"PTask.h\"\n\n# include <sstream>\n\n# include \"ivl_assert.h\"\n\n\n\nDesign:: Design()\n", "file_path": "iverilog-parser/net_design.cc", "rank": 78, "score": 13.040556410445488 }, { "content": "#ifndef IR_EXPORTER_H\n\n#define IR_EXPORTER_H\n\n\n\n#include <iostream>\n\n#include <vector>\n\n#include <sstream>\n\n#include <cassert>\n\n#include <unordered_set>\n\n#include <unordered_map>\n\n\n\n#include \"Visitor.h\"\n\n#include \"ExprVisitor.h\"\n\n\n\n#include \"IRExpr.h\"\n\n#include \"IRStmt.h\"\n\n#include \"IRModule.h\"\n\n\n", "file_path": "iverilog-parser/IRExporter.h", "rank": 79, "score": 12.947251348296716 }, { "content": "\n\n#include <iostream>\n\n#include <fstream>\n\n#include <string>\n\n#include <map>\n\n\n\n#ifndef SREC_HPP\n\n#define SREC_HPP\n\n\n\nnamespace srec {\n\n\n\n/*!\n\n@brief Represents a single SREC file contents as a key/value store.\n\n*/\n", "file_path": "benchmarks/xcrypto-ref/flow/verilator/srec.hpp", "rank": 80, "score": 12.77477863441307 }, { "content": "\n\n#include <iostream>\n\n#include <fstream>\n\n#include <string>\n\n#include <map>\n\n\n\n#ifndef SREC_HPP\n\n#define SREC_HPP\n\n\n\nnamespace srec {\n\n\n\n/*!\n\n@brief Represents a single SREC file contents as a key/value store.\n\n*/\n", "file_path": "benchmarks/scarv-cpu/flow/verilator/srec.hpp", "rank": 81, "score": 12.77477863441307 }, { "content": "# include \"config.h\"\n\n\n\n# include \"compiler.h\"\n\n# include \"pform.h\"\n\n# include \"parse_misc.h\"\n\n# include \"parse_api.h\"\n\n# include \"PClass.h\"\n\n# include \"PEvent.h\"\n\n# include \"PPackage.h\"\n\n# include \"PUdp.h\"\n\n# include \"PGenerate.h\"\n\n# include \"PModport.h\"\n\n# include \"PSpec.h\"\n\n# include \"discipline.h\"\n\n# include <list>\n\n# include <map>\n\n# include <cassert>\n\n# include <stack>\n\n# include <typeinfo>\n\n# include <sstream>\n", "file_path": "iverilog-parser/pform.cc", "rank": 82, "score": 12.744324840320395 }, { "content": "#include \"config.h\"\n\n#include \"pform.h\"\n\n#include \"PClass.h\"\n\n#include \"PEvent.h\"\n\n#include \"PGenerate.h\"\n\n#include \"PPackage.h\"\n\n#include \"PSpec.h\"\n\n#include \"PTask.h\"\n\n#include \"discipline.h\"\n\n#include \"ivl_target_priv.h\"\n\n#include <iostream>\n\n#include <iomanip>\n\n#include <typeinfo>\n\n#include <stdlib.h>\n\n#include <sstream>\n\n#include <vector>\n\n#include <unordered_set>\n\n#include <unordered_map>\n\n#include <cstring>\n\n\n", "file_path": "iverilog-parser/IRExporter.cc", "rank": 83, "score": 12.707570843738502 }, { "content": "#include \"config.h\"\n\n#include \"pform.h\"\n\n#include \"PClass.h\"\n\n#include \"PEvent.h\"\n\n#include \"PGenerate.h\"\n\n#include \"PPackage.h\"\n\n#include \"PSpec.h\"\n\n#include \"PTask.h\"\n\n#include \"discipline.h\"\n\n#include \"ivl_target_priv.h\"\n\n#include <iostream>\n\n#include <iomanip>\n\n#include <typeinfo>\n\n#include <stdlib.h>\n\n#include <sstream>\n\n#include <vector>\n\n#include <unordered_set>\n\n#include <unordered_map>\n\n#include <cstring>\n\n\n", "file_path": "iverilog-parser/PrologExporter.cc", "rank": 84, "score": 12.707570843738502 }, { "content": "\n\n# include <list>\n\n# include <ostream>\n\n# include \"compiler.h\"\n\n# include \"pform.h\"\n\n\n\n/*\n\n * The vlltype supports the passing of detailed source file location\n\n * information between the lexical analyzer and the parser. Defining\n\n * YYLTYPE compels the lexor to use this type and not something other.\n\n */\n", "file_path": "iverilog-parser/parse_misc.h", "rank": 85, "score": 12.686865025880092 }, { "content": "\n\n\t/* This method returns true if there are any drivers\n\n\t (including variables) attached to this nexus. */\n\n bool drivers_present() const;\n\n\n\n\t/* This method returns true if all the possible drivers of\n\n\t this nexus are constant. It will also return true if there\n\n\t are no drivers at all. */\n\n bool drivers_constant() const;\n\n\n\n\t/* Given the nexus has constant drivers, this method returns\n\n\t the value that has been driven. */\n\n verinum::V driven_value() const;\n\n verinum driven_vector() const;\n\n\n\n\t/* Return a mask of the bits of this vector that are\n\n\t driven. This is usually all false or all true, but in\n\n\t special cases it may be a blend. */\n\n std::vector<bool> driven_mask(void)const;\n\n\n", "file_path": "iverilog-parser/netlist.h", "rank": 86, "score": 12.670528080102805 }, { "content": "\t\t\t struct_type_t*struct_type,\n\n\t\t\t NetNet::PortType,\n\n\t\t\t list<perm_string>*names,\n\n\t\t\t list<named_pexpr_t>*attr);\n\n\n\nextern void pform_make_var_init(const struct vlltype&li,\n\n\t\t\t\tperm_string name, PExpr*expr);\n\n\n\n/* This function is used when we have an incomplete port definition in\n\n a non-ansi style declaration. Look up the names of the wires, and set\n\n the port type, i.e. input, output or inout, and, if specified, the\n\n range and signedness. If the wire does not exist, create it. */\n\nextern void pform_set_port_type(const struct vlltype&li,\n\n\t\t\t\tlist<pform_port_t>*ports,\n\n\t\t\t\tNetNet::PortType,\n\n\t\t\t\tdata_type_t*dt,\n\n\t\t\t\tlist<named_pexpr_t>*attr);\n\n\n\nextern void pform_set_reg_idx(perm_string name,\n\n\t\t\t std::list<pform_range_t>*indices);\n", "file_path": "iverilog-parser/pform.h", "rank": 87, "score": 12.59342762759706 }, { "content": "\n\n ~netvector_t();\n\n\n\n\t// Vectors can be interpreted as signed or unsigned when\n\n\t// handled as vectors.\n\n inline void set_signed(bool flag) { signed_ = flag; }\n\n inline bool get_signed(void) const { return signed_; }\n\n\n\n inline void set_isint(bool flag) { isint_ = flag; }\n\n inline bool get_isint(void) const { return isint_; }\n\n\n\n inline void set_scalar(bool flag) { is_scalar_ = flag; }\n\n inline bool get_scalar(void) const { return is_scalar_; }\n\n\n\n ivl_variable_type_t base_type() const;\n\n const std::vector<netrange_t>&packed_dims() const;\n\n\n\n bool packed(void) const;\n\n long packed_width() const;\n\n std::vector<netrange_t> slice_dimensions() const;\n", "file_path": "iverilog-parser/netvector.h", "rank": 88, "score": 12.573041265072936 }, { "content": " * proc_match_t functor can be used to scan a process and generate a\n\n * string of tokens. That string of tokens can then be matched by the\n\n * rules to determine what kind of device is to be made.\n\n */\n\n\n\n# include \"netlist.h\"\n\n# include \"netmisc.h\"\n\n# include \"functor.h\"\n\n# include <cassert>\n\n\n", "file_path": "iverilog-parser/syn-rules.cc", "rank": 89, "score": 12.55901412543377 }, { "content": " bool get_scalar() const;\n\n\n\n bool set_data_type(ivl_variable_type_t dt);\n\n ivl_variable_type_t get_data_type() const;\n\n\n\n void set_range_scalar(PWSRType type);\n\n void set_range(const std::list<pform_range_t>&ranges, PWSRType type);\n\n\n\n void set_unpacked_idx(const std::list<pform_range_t>&ranges);\n\n\n\n void set_data_type(data_type_t*type);\n\n\n\n void set_discipline(ivl_discipline_t);\n\n ivl_discipline_t get_discipline(void) const;\n\n\n\n map<perm_string,PExpr*> attributes;\n\n\n\n\t// Write myself to the specified stream.\n\n void dump(ostream&out, unsigned ind=4) const;\n\n\n", "file_path": "iverilog-parser/PWire.h", "rank": 90, "score": 12.539279045286548 }, { "content": " }\n\n void addOperand(const IRExpr *operand);\n\n bool isConstant() const\n\n {\n\n return std::all_of(operands.begin(), operands.end(),\n\n [](const IRExpr *e) { return e->isConstant(); });\n\n }\n\n\n\n std::ostream &print(std::ostream &) const;\n\n\n\nprivate:\n\n IRUFOp function;\n\n std::vector<const IRExpr *> operands;\n\n};\n\n\n", "file_path": "iverilog-parser/IRExpr.h", "rank": 91, "score": 12.51211795755029 }, { "content": "# include \"compiler.h\"\n\n\n\n# include <iostream>\n\n# include <cstdlib>\n\n# include <cstring>\n\n# include <cmath>\n\n\n\n# include \"netlist.h\"\n\n# include \"ivl_assert.h\"\n\n# include \"netmisc.h\"\n\n\n\nNetExpr* NetExpr::eval_tree()\n\n{\n\n return 0;\n\n}\n\n\n\nstatic void eval_debug(const NetExpr*expr, NetExpr*res, bool is_real)\n\n{\n\n if (res != 0) {\n\n\t res->set_line(*expr);\n", "file_path": "iverilog-parser/eval_tree.cc", "rank": 92, "score": 12.473971426134778 }, { "content": "# include \"config.h\"\n\n\n\n/*\n\n * Elaboration takes as input a complete parse tree and the name of a\n\n * root module, and generates as output the elaborated design. This\n\n * elaborated design is presented as a Module, which does not\n\n * reference any other modules. It is entirely self contained.\n\n */\n\n\n\n# include <typeinfo>\n\n# include <cstdlib>\n\n# include <sstream>\n\n# include <list>\n\n# include \"pform.h\"\n\n# include \"PClass.h\"\n\n# include \"PEvent.h\"\n\n# include \"PGenerate.h\"\n\n# include \"PPackage.h\"\n\n# include \"PScope.h\"\n\n# include \"PSpec.h\"\n", "file_path": "iverilog-parser/elaborate.cc", "rank": 93, "score": 12.407875397970942 }, { "content": "\n\n# include <iostream>\n\n\n\n# include <cstring>\n\n# include \"t-dll.h\"\n\n# include \"netlist.h\"\n\n# include \"netclass.h\"\n\n# include <cassert>\n\n# include <cstdlib>\n\n# include \"ivl_alloc.h\"\n\n# include \"ivl_assert.h\"\n\n\n\n/*\n\n * This is a little convenience function for converting a NetExpr\n\n * expression type to the expression type used by ivl_expr_t objects.\n\n */\n\nstatic ivl_variable_type_t get_expr_type(const NetExpr*net)\n\n{\n\n return net->expr_type();\n\n}\n", "file_path": "iverilog-parser/t-dll-expr.cc", "rank": 94, "score": 12.386532204154955 }, { "content": "\n\nextern void pform_set_data_type(const struct vlltype&li, data_type_t*, list<perm_string>*names, NetNet::Type net_type, list<named_pexpr_t>*attr);\n\n\n\nextern void pform_set_struct_type(struct_type_t*struct_type, std::list<perm_string>*names, NetNet::Type net_type, std::list<named_pexpr_t>*attr);\n\n\n\nextern void pform_set_string_type(const string_type_t*string_type, std::list<perm_string>*names, NetNet::Type net_type, std::list<named_pexpr_t>*attr);\n\n\n\nextern void pform_set_class_type(class_type_t*class_type, std::list<perm_string>*names, NetNet::Type net_type, std::list<named_pexpr_t>*addr);\n\n\n\n\n\n /* pform_set_attrib and pform_set_type_attrib exist to support the\n\n $attribute syntax, which can only set string values to\n\n attributes. The functions keep the value strings that are\n\n passed in. */\n\nextern void pform_set_attrib(perm_string name, perm_string key,\n\n\t\t\t char*value);\n\nextern void pform_set_type_attrib(perm_string name, const string&key,\n\n\t\t\t\t char*value);\n\n\n\nextern LexicalScope::range_t* pform_parameter_value_range(bool exclude_flag,\n", "file_path": "iverilog-parser/pform.h", "rank": 95, "score": 12.375859552750825 }, { "content": " const char* get_flag(const string&key) const;\n\n\n\n NetScope* make_root_scope(perm_string name, bool program_block,\n\n\t\t\t\tbool is_interface);\n\n NetScope* find_root_scope();\n\n std::list<NetScope*> find_root_scopes() const;\n\n\n\n NetScope* make_package_scope(perm_string name);\n\n std::list<NetScope*> find_package_scopes() const;\n\n\n\n\t/* Attempt to set the precision to the specified value. If the\n\n\t precision is already more precise, the keep the precise\n\n\t setting. This is intended to hold the simulation precision\n\n\t for use throughout the entire design. */\n\n\n\n void set_precision(int val);\n\n int get_precision() const;\n\n\n\n\t/* This function takes a delay value and a scope, and returns\n\n\t the delay value scaled to the precision of the design. */\n", "file_path": "iverilog-parser/netlist.h", "rank": 96, "score": 12.32651698530009 }, { "content": "# include \"PGate.h\"\n\n# include \"PGenerate.h\"\n\n# include \"PPackage.h\"\n\n# include \"PTask.h\"\n\n# include \"PWire.h\"\n\n# include \"Statement.h\"\n\n# include \"AStatement.h\"\n\n# include \"netlist.h\"\n\n# include \"netclass.h\"\n\n# include \"netenum.h\"\n\n# include \"parse_api.h\"\n\n# include \"util.h\"\n\n# include <typeinfo>\n\n# include <cassert>\n\n# include \"ivl_assert.h\"\n\n\n\n\n\nvoid set_scope_timescale(Design*des, NetScope*scope, PScope*pscope)\n\n{\n\n scope->time_unit(pscope->time_unit);\n", "file_path": "iverilog-parser/elab_scope.cc", "rank": 97, "score": 12.272979165651481 }, { "content": "\t// If the bl_type() is BL_PAR, it is possible to replace it\n\n\t// with JOIN_NONE or JOIN_ANY. This is to help the parser.\n\n void set_join_type(BL_TYPE);\n\n\n\n void set_statement(const std::vector<Statement*>&st);\n\n\n\n\t// Copy the statement from that block to the front of this\n\n\t// block.\n\n void push_statement_front(Statement*that);\n\n\n\n virtual void dump(ostream&out, unsigned ind) const;\n\n virtual NetProc* elaborate(Design*des, NetScope*scope) const;\n\n virtual void elaborate_scope(Design*des, NetScope*scope) const;\n\n virtual void elaborate_sig(Design*des, NetScope*scope) const;\n\n\n\n private:\n\n BL_TYPE bl_type_;\n\n std::vector<Statement*>list_;\n\n\n\n public:\n\n VISITOR_FRIENDS;\n\n virtual void accept(Visitor* v) {\n\n v->visit(this);\n\n }\n\n};\n\n\n", "file_path": "iverilog-parser/Statement.h", "rank": 98, "score": 12.213298465266167 }, { "content": " }\n\n}\n\n\n\n\n\nvoid load_srec_file (\n\n memory_bus * mem\n\n) {\n\n std::cout <<\">> Loading srec: \" << srec_path << std::endl;\n\n\n\n srec::srec_file fh(srec_path);\n\n\n\n for(auto it = fh.data.begin();\n\n it != fh.data.end();\n\n it ++) {\n\n mem -> write_byte(it -> first, it -> second);\n\n }\n\n}\n\n\n\n//! Write out the memory signature for verification\n\nvoid dump_signature_file (\n", "file_path": "benchmarks/scarv-cpu/flow/verilator/main.cpp", "rank": 99, "score": 12.188825114392898 } ]
C++
examples/12-fonts/src/Main.cpp
szszszsz/blue
a6a93d9a6c7bda6b4ed4fa3b9b4b01094c4915b8
#include <blue/Context.hpp> #include <blue/Timestep.hpp> #include <blue/ShaderUtils.h> #include <blue/TextureUtils.hpp> #include <blue/camera/OrthographicCamera.hpp> #include <blue/FontUtils.hpp> #include <atomic> #include <string> #include <cstdint> #include <cstdlib> namespace Sample { const std::uint16_t window_width = 400; const std::uint16_t window_height = 400; } int main(int argc, char* argv[]) { blue::Context::init(); blue::Context::window().create(Sample::window_width, Sample::window_height); blue::Context::gpu_thread().run(); std::atomic_bool running{ true }; blue::Context::input().registerKeyCallback({ [&running]() { running = false; }, SDLK_ESCAPE, SDL_KEYDOWN } ); auto compile_shader_entity = ShaderUtils::make_entity ( "resources/SimpleTextureShader.vertex.glsl", "resources/SimpleTextureShader.fragment.glsl" ); auto shader = blue::Context::gpu_system().submit(compile_shader_entity).get(); Vertices vertices = { -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.0f, 1.0f, 0.5f, 0.5f, 1.0f, 1.0f, 0.5f, -0.5f, 1.0f, 0.0f, }; Indices indices = { 0, 1, 2, 2, 3, 0 }; Attributes attributes = { {ShaderAttribute::Type::VEC2, ShaderAttribute::Purpose::VERTEX_POSITION, ShaderAttribute::Buffer::VERTEX}, {ShaderAttribute::Type::VEC2, ShaderAttribute::Purpose::TEXTURE_COORDINATE, ShaderAttribute::Buffer::VERTEX} }; auto vertex_array = blue::Context::gpu_system().submit(CreateMeshEntity{ vertices, indices, attributes, static_cast<std::uint32_t>(indices.size()) }).get(); auto environment = blue::Context::gpu_system().submit(CreateEnvironmentEntity{}).get(); OrthographicCamera camera(OrthographicCamera::Mode::SCREEN_SPACE, blue::Context::window().get_width(), blue::Context::window().get_height()); blue::Context::gpu_system().submit(UpdateEnvironmentEntity_Projection{ environment, camera.get_projection() }); blue::Context::gpu_system().submit(UpdateEnvironmentEntity_View{ environment, camera.get_view() }); auto font = FontUtils::read_ttf_relative("resources/Lato-Black.ttf"); auto create_texture_entity = FontUtils::create_text(font, "The quick brown fox jumps over the lazy dog.", Sample::window_width, Sample::window_height, 22); auto texture = blue::Context::gpu_system().submit(create_texture_entity).get(); UpdateUniformVariableEntity update_uniform_entity{}; update_uniform_entity.type = ShaderAttribute::Type::INT; update_uniform_entity.value = &create_texture_entity.slot; update_uniform_entity.program = shader; update_uniform_entity.location = 9; blue::Context::gpu_system().submit(update_uniform_entity); RenderEntity entity; entity.position = { blue::Context::window().get_width() / 2, blue::Context::window().get_height() / 2, 0.0f }; entity.shader = shader; entity.vertex_array = vertex_array; entity.scale = { Sample::window_width, Sample::window_height, 1.0f }; entity.rotation = glm::identity<glm::quat>(); entity.environment = environment; entity.textures[0] = texture; RenderEntityId id = blue::Context::renderer().add(entity); Timestep timestep(30); while (running) { timestep.mark_start(); blue::Context::input().poll(); timestep.mark_end(); timestep.delay(); } blue::Context::gpu_thread().stop(); blue::Context::dispose(); return EXIT_SUCCESS; }
#include <blue/Context.hpp> #include <blue/Timestep.hpp> #include <blue/ShaderUtils.h> #include <blue/TextureUtils.hpp> #include <blue/camera/OrthographicCamera.hpp> #include <blue/FontUtils.hpp> #include <atomic> #include <string> #include <cstdint> #include <cstdlib> namespace Sample { const std::uint16_t window_width = 400; const std::uint16_t window_height = 400; } int main(int argc, char* argv[]) { blue::Context::init(); blue::Context::window().create(Sample::window_width, Sample::window_height); blue::Context::gpu_thread().run(); std::atomic_bool running{ true }; blue::Context::input().registerKeyCallback({ [&running]() { running = false; }, SDLK_ESCAPE, SDL_KEYDOWN } ); auto compile_shader_entity = ShaderUtils::make_entity ( "resources/SimpleTextureShader.vertex.glsl", "resources/SimpleTextureShader.fragment.glsl" ); auto shader = blue::Context::gpu_system().submit(compile_shader_entity).get(); Vertices vertices = { -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.0f, 1.0f, 0.5f, 0.5f, 1.0f, 1.0f, 0.5f, -0.5f, 1.0f, 0.0f, }; Indices indices = { 0, 1, 2, 2, 3, 0 }; Attributes attributes = { {ShaderAttribute::Type::VEC2, ShaderAttribute::Purpose::VERTEX_POSITION, ShaderAttribute::Buffer::VERTEX}, {ShaderAttribute::Type::VEC2, ShaderAttribute::Purpose::TEXTURE_COORDINATE, ShaderAttribute::Buffer::VERTEX} }; auto vertex_
view() }); auto font = FontUtils::read_ttf_relative("resources/Lato-Black.ttf"); auto create_texture_entity = FontUtils::create_text(font, "The quick brown fox jumps over the lazy dog.", Sample::window_width, Sample::window_height, 22); auto texture = blue::Context::gpu_system().submit(create_texture_entity).get(); UpdateUniformVariableEntity update_uniform_entity{}; update_uniform_entity.type = ShaderAttribute::Type::INT; update_uniform_entity.value = &create_texture_entity.slot; update_uniform_entity.program = shader; update_uniform_entity.location = 9; blue::Context::gpu_system().submit(update_uniform_entity); RenderEntity entity; entity.position = { blue::Context::window().get_width() / 2, blue::Context::window().get_height() / 2, 0.0f }; entity.shader = shader; entity.vertex_array = vertex_array; entity.scale = { Sample::window_width, Sample::window_height, 1.0f }; entity.rotation = glm::identity<glm::quat>(); entity.environment = environment; entity.textures[0] = texture; RenderEntityId id = blue::Context::renderer().add(entity); Timestep timestep(30); while (running) { timestep.mark_start(); blue::Context::input().poll(); timestep.mark_end(); timestep.delay(); } blue::Context::gpu_thread().stop(); blue::Context::dispose(); return EXIT_SUCCESS; }
array = blue::Context::gpu_system().submit(CreateMeshEntity{ vertices, indices, attributes, static_cast<std::uint32_t>(indices.size()) }).get(); auto environment = blue::Context::gpu_system().submit(CreateEnvironmentEntity{}).get(); OrthographicCamera camera(OrthographicCamera::Mode::SCREEN_SPACE, blue::Context::window().get_width(), blue::Context::window().get_height()); blue::Context::gpu_system().submit(UpdateEnvironmentEntity_Projection{ environment, camera.get_projection() }); blue::Context::gpu_system().submit(UpdateEnvironmentEntity_View{ environment, camera.get_
random
[ { "content": "struct ShaderAttribute\n\n{\n", "file_path": "include/blue/gpu/GpuEntities.hpp", "rank": 0, "score": 105984.379388146 }, { "content": "\tenum class Model : int\n\n\t{\n\n\t\tPINE_TREE = 0,\n\n\t\tHURDLE = 1,\n\n\t\tWHEAT = 2,\n\n\t\tBOULDER = 3,\n\n\t\tSMALL_BOULDER = 4,\n\n\t\tGRASS = 5,\n\n\t\tPYLON = 6,\n\n\t\tBUSH = 7,\n\n\t\tCUT_TREE = 8,\n\n\t\tTRACK = 9,\n\n\t\tBRIDGE = 10,\n\n\t};\n\n\n\n\tstatic Resources& instance();\n\n\n\n\tstatic void init();\n\n\n\n\tstatic void dispose();\n", "file_path": "examples/advanced/common/include/Resources.hpp", "rank": 1, "score": 84277.53761065585 }, { "content": "namespace ShaderUtils\n\n{\n\n\tstd::string read(const std::string& filename);\n\n\tCompileShaderEntity make_entity(const std::string vertex_path, const std::string fragment_path);\n", "file_path": "include/blue/ShaderUtils.h", "rank": 2, "score": 79144.78404255229 }, { "content": "\tenum class Mode : int\n\n\t{\n\n\t\tELEVATION = 0,\n\n\t\tVERTEX_PAINT = 1,\n\n\t\tADDING_MODELS = 2,\n\n\t\tVERTEX_PAINT_SHUFFLE = 3,\n\n\t\tWATER = 4,\n\n\t};\n\n\n\n\texplicit ModelingTerrain(const bool map_imported);\n\n\t~ModelingTerrain();\n\n\tstd::shared_ptr<BaseState> update() override;\n\n\tvoid on_entry() override;\n\n\n\nprivate:\n\n\n\n\tstruct ModelEntry\n\n\t{\n\n\t\tRenderEntityId id;\n\n\t\tResources::Model model;\n", "file_path": "examples/advanced/terrain-editor/include/states/ModelingTerrain.hpp", "rank": 3, "score": 77970.84007274383 }, { "content": "\t\tVertices vertices;\n", "file_path": "include/blue/ModelLoader.h", "rank": 4, "score": 70360.51118899097 }, { "content": "#pragma once\n\n\n\n#include \"blue/gpu/GpuCommandSystem.hpp\"\n\n\n\nvoid handle(std::pair<std::promise<ShaderId>, CompileShaderEntity>& pair);\n", "file_path": "include/blue/gpu/handlers/CompileShaderHandler.hpp", "rank": 5, "score": 70290.09645328792 }, { "content": "#pragma once\n\n\n\n#include \"blue/gpu/GpuCommandSystem.hpp\"\n\n\n\nvoid handle(const DisposeShaderEntity& entity);\n", "file_path": "include/blue/gpu/handlers/DisposeShaderHandler.hpp", "rank": 6, "score": 70289.75625938458 }, { "content": "struct DisposeShaderEntity\n\n{\n\n\tconst ShaderId& shader;\n\n};\n\n\n", "file_path": "include/blue/gpu/GpuEntities.hpp", "rank": 7, "score": 67885.74514380776 }, { "content": "struct CompileShaderEntity\n\n{\n\n\tstd::string vertex;\n\n\tstd::string fragment;\n\n};\n\n\n", "file_path": "include/blue/gpu/GpuEntities.hpp", "rank": 8, "score": 67885.74514380776 }, { "content": " @Override\n\n public void run() {\n\n // Runs SDL_main()\n\n String library = SDLActivity.mSingleton.getMainSharedObject();\n\n String function = SDLActivity.mSingleton.getMainFunction();\n\n String[] arguments = SDLActivity.mSingleton.getArguments();\n\n\n\n Log.v(\"SDL\", \"Running main function \" + function + \" from library \" + library);\n\n SDLActivity.nativeRunMain(library, function, arguments);\n\n\n\n Log.v(\"SDL\", \"Finished main function\");\n\n\n\n // Native thread has finished, let's finish the Activity\n\n if (!SDLActivity.mExitCalledFromJava) {\n\n SDLActivity.handleNativeExit();\n\n }\n", "file_path": "platforms/android/android-app/src/main/java/org/libsdl/app/SDLActivity.java", "rank": 9, "score": 57277.003576343275 }, { "content": " public void run(int device_id, float intensity, int length) {\n\n SDLHaptic haptic = getHaptic(device_id);\n\n if (haptic != null) {\n\n haptic.vib.vibrate(length);\n\n }\n", "file_path": "platforms/android/android-app/src/main/java/org/libsdl/app/SDLControllerManager.java", "rank": 10, "score": 56034.150488163585 }, { "content": " @Override\n\n public void run() {\n\n SDLActivity.this.superOnBackPressed();\n", "file_path": "platforms/android/android-app/src/main/java/org/libsdl/app/SDLActivity.java", "rank": 11, "score": 55456.77065200845 }, { "content": " @Override\n\n public void run() {\n\n int flags = View.SYSTEM_UI_FLAG_FULLSCREEN |\n\n View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |\n\n View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY |\n\n View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |\n\n View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |\n\n View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.INVISIBLE;\n\n\n\n SDLActivity.this.getWindow().getDecorView().setSystemUiVisibility(flags);\n", "file_path": "platforms/android/android-app/src/main/java/org/libsdl/app/SDLActivity.java", "rank": 12, "score": 55456.77065200845 }, { "content": " @Override\n\n public void run(int device_id, float intensity, int length) {\n\n SDLHaptic haptic = getHaptic(device_id);\n\n if (haptic != null) {\n\n Log.d(\"SDL\", \"Rtest: Vibe with intensity \" + intensity + \" for \" + length);\n\n if (intensity == 0.0f) {\n\n stop(device_id);\n\n return;\n\n }\n\n\n\n int vibeValue = Math.round(intensity * 255);\n\n\n\n if (vibeValue > 255) {\n\n vibeValue = 255;\n\n }\n\n if (vibeValue < 1) {\n\n stop(device_id);\n\n return;\n\n }\n\n try {\n\n haptic.vib.vibrate(VibrationEffect.createOneShot(length, vibeValue));\n\n }\n\n catch (Exception e) {\n\n // Fall back to the generic method, which uses DEFAULT_AMPLITUDE, but works even if\n\n // something went horribly wrong with the Android 8.0 APIs.\n\n haptic.vib.vibrate(length);\n\n }\n\n }\n", "file_path": "platforms/android/android-app/src/main/java/org/libsdl/app/SDLControllerManager.java", "rank": 13, "score": 55456.77065200845 }, { "content": " @Override\n\n public void run() {\n\n showDialog(dialogs++, args);\n", "file_path": "platforms/android/android-app/src/main/java/org/libsdl/app/SDLActivity.java", "rank": 14, "score": 54906.044203667276 }, { "content": " @Override\n\n public void run() {\n\n RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(w, h + HEIGHT_PADDING);\n\n params.leftMargin = x;\n\n params.topMargin = y;\n\n\n\n if (mTextEdit == null) {\n\n mTextEdit = new DummyEdit(SDL.getContext());\n\n\n\n mLayout.addView(mTextEdit, params);\n\n } else {\n\n mTextEdit.setLayoutParams(params);\n\n }\n\n\n\n mTextEdit.setVisibility(View.VISIBLE);\n\n mTextEdit.requestFocus();\n\n\n\n InputMethodManager imm = (InputMethodManager) SDL.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);\n\n imm.showSoftInput(mTextEdit, 0);\n\n\n\n mScreenKeyboardShown = true;\n", "file_path": "platforms/android/android-app/src/main/java/org/libsdl/app/SDLActivity.java", "rank": 15, "score": 54906.044203667276 }, { "content": "#pragma once\n\n\n\n#include <glm/gtx/quaternion.hpp>\n\n\n\n#include <vector>\n\n#include <atomic>\n\n#include <map>\n\n#include <utility>\n\n#include <functional>\n\n\n\n#include \"blue/GlDebugging.h\"\n\n#include \"blue/Assertions.h\"\n\n#include \"blue/gpu/GpuEntities.hpp\"\n\n#include \"glad/glad.h\"\n\n\n\nstatic const std::uint32_t BLUE_AVAILABLE_TEXTURE_SLOTS = 8;\n\n\n\nusing ImGuiEntity = std::function<void()>;\n\nusing RenderEntityId = std::uint32_t;\n\nusing ImGuiEntityId = std::uint32_t;\n\n\n", "file_path": "include/blue/Renderer.h", "rank": 16, "score": 42095.38633966095 }, { "content": "\n\n struct\n\n {\n\n ShaderId current_shader = 0;\n\n UniformBufferId current_environment = 0;\n\n\t\tFramebufferId current_framebuffer = 0;\n\n\t\tstd::map<TextureSlot, TextureId> textures;\n\n\t} cache;\n\n\n\n\tvoid draw_render_entities();\n\n\tvoid draw_imgui_entities();\n\n\tvoid clear() const;\n\n\n\n\tvoid lock();\n\n\tvoid unlock();\n\n\n\n\tvoid sort_entities_by_shader();\n\n\tvoid sort_entities_by_framebuffer();\n\n\n\n\tstd::atomic_bool locked{ false };\n\n\tstd::vector<RenderEntity> render_entities;\n\n\tstd::vector<std::pair<ImGuiEntityId, ImGuiEntity>> imgui_entities;\n\n};\n", "file_path": "include/blue/Renderer.h", "rank": 17, "score": 42093.636922095124 }, { "content": "#pragma once\n\n\n\n#include <atomic>\n\n#include <string>\n\n\n\n#include <SDL2/SDL.h>\n\n\n\nnamespace blue\n\n{\n", "file_path": "include/blue/Window.hpp", "rank": 18, "score": 40375.06829445434 }, { "content": "\t\tvoid update_size();\n\n\n\n\t\tstd::atomic_bool _cursor_attached{ true };\n\n\t\tstd::atomic<SDL_GLContext> _gl_context{};\n\n\t\tstd::atomic<SDL_Window*> _window_handle{};\n\n\t\tstd::string _title = \"Blue\";\n\n\t\tstd::atomic<std::uint16_t> _width{ 0 };\n\n\t\tstd::atomic<std::uint16_t> _height{ 0 };\n\n\t\tstd::atomic<std::uint16_t> _last_x{ 0 };\n\n\t\tstd::atomic<std::uint16_t> _last_y{ 0 };\n\n\t\tbool _fullscreen = false;\n\n\t\tbool _hidden = false;\n\n\t};\n\n}\n", "file_path": "include/blue/Window.hpp", "rank": 19, "score": 40367.50078520649 }, { "content": "#pragma once\n\n\n\n#include \"blue/Logger.hpp\"\n\n#include \"blue/Window.hpp\"\n\n#include \"blue/Renderer.h\"\n\n#include \"blue/InputHandler.h\"\n\n#include \"blue/GpuThread.hpp\"\n\n#include \"blue/gpu/GpuCommandSystem.hpp\"\n\n\n\nnamespace blue\n\n{\n", "file_path": "include/blue/Context.hpp", "rank": 20, "score": 40365.99427346243 }, { "content": "//\n\n// Created by dbeef on 4/4/19.\n\n//\n\n\n\n#ifndef OPENGL_PLAYGROUND_INPUTHANDLER_H\n\n#define OPENGL_PLAYGROUND_INPUTHANDLER_H\n\n\n\n#include <SDL2/SDL.h>\n\n#include <vector>\n\n#include <utility>\n\n#include <functional>\n\n#include <atomic>\n\n#include <algorithm>\n\n\n\n// Currently using SDL's enums for keys / actions (press/release).\n\n// TODO: Map SDL's enums to Blue's enums to have a layer of abstraction from SDL.\n\nusing MouseCallback = std::function<void(double dx, double dy)>;\n\nusing GestureCallback = std::function<void(SDL_MultiGestureEvent)>;\n\n\n", "file_path": "include/blue/InputHandler.h", "rank": 21, "score": 40364.65230837609 }, { "content": "#pragma once\n\n\n\n#include \"blue/Context.hpp\"\n\n\n\n#include <chrono>\n\n#include <thread>\n\n\n\nusing Timestamp = std::chrono::system_clock::time_point;\n\n\n", "file_path": "include/blue/Timestep.hpp", "rank": 22, "score": 40362.71316443719 }, { "content": "//\n\n// Created by dbeef on 6/9/19.\n\n//\n\n\n\n#ifndef OPENGL_PLAYGROUND_LOGGER_HPP\n\n#define OPENGL_PLAYGROUND_LOGGER_HPP\n\n\n\n#include \"spdlog/spdlog.h\"\n\n#include \"blue/Assertions.h\"\n\n\n", "file_path": "include/blue/Logger.hpp", "rank": 23, "score": 40362.21499030574 }, { "content": " }\n\n\n\n\tvoid poll();\n\n\n\n\tvoid mouse_callback(double xpos, double ypos);\n\n\n\n\tvoid keyboard_callback(int key, int action);\n\n\n\n\tvoid mouse_button_callback(int key, int action, double x, double y);\n\n\n\n\tstd::vector<MouseKeyCallback> mouseButtonCommands;\n\n\tstd::vector<KeyCallback> keyboardKeyCommands;\n\n\tstd::vector<MouseCallback> mouseCommands;\n\n\tGestureCallback gestureCallback = {};\n\n};\n\n\n\n#endif //OPENGL_PLAYGROUND_INPUTHANDLER_H\n", "file_path": "include/blue/InputHandler.h", "rank": 24, "score": 40362.08826897494 }, { "content": "//\t\tauto iterator = std::remove_if(mouseButtonCommands.begin(), mouseButtonCommands.end(), [callback](const MouseKeyCallback& list_callback) -> bool {\n\n//\t\t\treturn callback.key_type == list_callback.key_type && callback.action == list_callback.action;\n\n//\t\t\t});\n\n//\n\n//\t\tif (iterator != mouseButtonCommands.end())\n\n//\t\t{\n\n//\t\t\tmouseButtonCommands.erase(iterator);\n\n//\t\t}\n\n\n\n\t\tmouseButtonCommands.emplace_back(callback);\n\n\t}\n\n\n\n\tinline void registerMouseMoveCallback(const MouseCallback& callback)\n\n\t{\n\n\t\tmouseCommands.emplace_back(callback);\n\n\t}\n\n\n\n\tinline void registerGestureCallback(const GestureCallback& callback)\n\n {\n\n\t gestureCallback = callback;\n", "file_path": "include/blue/InputHandler.h", "rank": 25, "score": 40359.67680331251 }, { "content": "\t\tinline SDL_Window* get_window() const { return _window_handle.load(); }\n\n\n\n\t\tinline void swap_buffers() const { SDL_GL_SwapWindow(_window_handle.load()); }\n\n\n\n\t\tinline bool is_cursor_attached() const { return _cursor_attached.load(); }\n\n\n\n\t\tvoid attach_cursor();\n\n\n\n\t\tvoid detach_cursor();\n\n\n\n\t\tstd::uint16_t get_last_x();\n\n\n\n\t\tstd::uint16_t get_last_y();\n\n\n\n\t\tvoid set_last_xy(std::uint16_t x, std::uint16_t y);\n\n\n\n\tprivate:\n\n\n\n\t\tbool _create();\n\n\n", "file_path": "include/blue/Window.hpp", "rank": 26, "score": 40357.77635577466 }, { "content": "\tvoid delay() const;\n\n\n\n\tinline std::uint64_t get_delta() const { return std::chrono::duration_cast<std::chrono::microseconds>(_end - _start).count(); };\n\n\n\nprivate:\n\n\t\n\n\tTimestamp _start;\n\n\tTimestamp _end;\n\n\tconst std::chrono::microseconds _frequency;\n\n\tconst double _fps;\n\n\tconst bool _logging;\n\n};", "file_path": "include/blue/Timestep.hpp", "rank": 27, "score": 40357.77635577466 }, { "content": "\t\t\tcontext = nullptr;\n\n\t\t}\n\n\n\n\t\tinline static spdlog::logger& logger()\n\n\t\t{\n\n\t\t\treturn context->_logger.get();\n\n\t\t}\n\n\n\n\t\tinline static Window& window()\n\n\t\t{\n\n\t\t\treturn context->_window;\n\n\t\t}\n\n\n\n\t\tinline static Renderer& renderer()\n\n\t\t{\n\n\t\t\treturn context->_renderer;\n\n\t\t}\n\n\t\t\n\n\t\tinline static InputHandler& input()\n\n\t\t{\n", "file_path": "include/blue/Context.hpp", "rank": 28, "score": 40357.77635577466 }, { "content": "class Renderer {\n\n\n\npublic:\n\n\n\n\tfriend class GpuThread;\n\n\n\n\tImGuiEntityId add(const ImGuiEntity& entity);\n\n\tRenderEntityId add(const RenderEntity& entity);\n\n\tvoid update(const RenderEntity& entity);\n\n\tvoid remove_render_entity(const RenderEntityId& id);\n\n\tvoid remove_imgui_entity(const ImGuiEntityId& id);\n\n\n\n void invalidate_cache_uniform_buffer();\n\n\tvoid set_cached_shader(ShaderId);\n\n\tvoid set_cached_framebuffer(FramebufferId);\n\n\tvoid set_cached_texture(TextureSlot, TextureId);\n\n\tstd::map<TextureSlot, TextureId>& get_cached_textures();\n\n\tShaderId get_cached_shader() const;\n\n\n\nprivate:\n", "file_path": "include/blue/Renderer.h", "rank": 29, "score": 40357.77635577466 }, { "content": "\t\t\treturn context->_input;\n\n\t\t}\n\n\n\n\t\tinline static GpuCommandSystem& gpu_system()\n\n\t\t{\n\n\t\t\treturn context->_gpu_command_system;\n\n\t\t}\n\n\n\n\t\tinline static GpuThread& gpu_thread()\n\n\t\t{\n\n\t\t\treturn context->_gpu_thread;\n\n\t\t}\n\n\t\t\n\n\tprivate:\n\n\n\n\t\tLogger _logger;\n\n\t\tWindow _window;\n\n\t\tRenderer _renderer;\n\n\t\tInputHandler _input;\n\n\t\tGpuThread _gpu_thread;\n\n\t\tGpuCommandSystem _gpu_command_system;\n\n\n\n\t\tstatic Context* context;\n\n\t};\n\n}\n", "file_path": "include/blue/Context.hpp", "rank": 30, "score": 40357.77635577466 }, { "content": "#include \"blue/ShaderUtils.h\"\n\n#include \"blue/ResourcesPath.h\"\n\n#include \"blue/Context.hpp\"\n\n\n\n#include <SDL2/SDL_rwops.h>\n\n\n\nnamespace ShaderUtils\n\n{\n\n\tstd::string read(const std::string& filename) {\n\n\n\n\t\tstd::string data;\n\n\n\n\t\tauto path_extended = paths::getResourcesPath() + filename;\n\n\n\n\t\tSDL_RWops* file = SDL_RWFromFile(path_extended.c_str(), \"rb\");\n\n\t\tif (file != NULL) {\n\n\t\t\tauto size = file->size(file);\n\n\t\t\t//Initialize data\n\n\t\t\tdata.resize(size);\n\n\t\t\tauto read = file->read(file, &data[0], size, 1);\n", "file_path": "src/blue/ShaderUtils.cpp", "rank": 31, "score": 39860.29393087329 }, { "content": "\t\t\t//Close file handler\n\n\t\t\tSDL_RWclose(file);\n\n\t\t}\n\n\t\telse\n\n\t\t{\n\n\t\t\tblue::Context::logger().error(\"Error: Unable to open shader file. SDL Error: {}\", SDL_GetError());\n\n\t\t}\n\n\n\n\t\treturn data;\n\n\t}\n\n\n\n\tCompileShaderEntity make_entity(const std::string vertex_path, const std::string fragment_path)\n\n\t{\n\n\t\tCompileShaderEntity entity;\n\n\t\tentity.vertex = ShaderUtils::read(vertex_path);\n\n\t\tentity.fragment = ShaderUtils::read(fragment_path);\n\n\t\treturn entity;\n\n\t}\n\n}\n", "file_path": "src/blue/ShaderUtils.cpp", "rank": 32, "score": 39851.81220753317 }, { "content": "#pragma once\n\n\n\n#include \"blue/gpu/GpuEntities.hpp\"\n\n\n\n#include <string>\n\n\n\nnamespace ImageUtils\n\n{\n\n\tCreateTextureEntity read(const std::string& filepath);\n\n}\n", "file_path": "include/blue/TextureUtils.hpp", "rank": 33, "score": 38776.57271059234 }, { "content": "#pragma once\n\n\n\n#include <vector>\n\n#include <memory>\n\n#include <string>\n\n\n\n#include \"blue/gpu/GpuEntities.hpp\"\n\n\n\n#include \"stb/truetype.h\"\n\n#include \"stb/image_write.h\"\n\n\n\nnamespace FontUtils\n\n{\n\n\tstruct Font\n\n\t{\n\n\t\tstd::shared_ptr<std::vector<char>> raw_ttf_font;\n\n\t\tstbtt_fontinfo info;\n\n\t};\n\n\n\n\t// TODO: Use flags for reading properties (relative/absolute?)\n\n\tFont read_ttf_relative(const std::string& filepath);\n\n\tFont read_ttf_absolute(const std::string& filepath);\n\n\tCreateTextureEntity create_text(const Font& font, const std::string& text, std::uint16_t width, std::uint16_t height, std::uint16_t line_height);\n\n}\n", "file_path": "include/blue/FontUtils.hpp", "rank": 34, "score": 38776.300635507694 }, { "content": "#pragma once\n\n\n\n#include <thread>\n\n#include <atomic>\n\n#include <future>\n\n#include <condition_variable>\n\n\n", "file_path": "include/blue/GpuThread.hpp", "rank": 35, "score": 38773.62770027689 }, { "content": "#pragma once\n\n\n\n#include <glm/glm.hpp>\n\n#include <glm/gtc/matrix_transform.hpp>\n\n#include <glm/gtc/type_ptr.hpp>\n\n\n\n#include \"glad/glad.h\"\n\n\n\nusing CameraId = std::uint32_t;\n\n\n", "file_path": "include/blue/camera/Camera.hpp", "rank": 36, "score": 38769.18619242989 }, { "content": "// TODO: 'gui' should be a subproject for blue.\n\n\n\n#pragma once\n\n\n\n#include <blue/Renderer.h>\n\n#include <blue/gui/PlacingRules.h>\n\n\n", "file_path": "include/blue/gui/Button.hpp", "rank": 37, "score": 38768.852279182676 }, { "content": "class Timestep {\n\n\n\npublic:\n\n\n\n\texplicit Timestep(double fps = 60, bool logging = false) \n\n\t\t: _logging(logging), _fps(fps), _frequency(std::chrono::microseconds(static_cast<unsigned long long>(1000 * 1000 * (1 / fps))))\n\n\t{\n\n\t\tblue::Context::logger().info(\"Created timestep with frequency of {} microseconds ({} fps).\", _frequency.count(), _fps);\n\n\t}\n\n\n\n\tinline void mark_start()\n\n\t{\n\n\t\t_start = std::chrono::system_clock::now();\n\n\t}\n\n\n\n\tinline void mark_end()\n\n\t{\n\n\t\t_end = std::chrono::system_clock::now();\n\n\t}\n\n\n", "file_path": "include/blue/Timestep.hpp", "rank": 38, "score": 38764.18591210263 }, { "content": "\tclass Context {\n\n\n\n\tpublic:\n\n\n\n\t\tContext() {}\n\n\t\t\n\n\t\t~Context()\n\n\t\t{\n\n\t\t\tblue::Context::logger().info(\"Disposed context.\");\n\n\t\t}\n\n\n\n\t\tinline static void init()\n\n\t\t{\n\n\t\t\tcontext = new Context();\n\n\t\t\tblue::Context::logger().info(\"Created context.\");\n\n\t\t}\n\n\n\n\t\tinline static void dispose()\n\n\t\t{\n\n\t\t\tdelete context;\n", "file_path": "include/blue/Context.hpp", "rank": 39, "score": 38764.18591210263 }, { "content": "struct RenderEntity\n\n{\n\n\tShaderId shader{};\n\n\tRenderEntityId id{};\n\n\tVertexArray vertex_array{};\n\n\tglm::vec3 position{};\n\n\tglm::quat rotation{};\n\n\tglm::vec3 scale{};\n\n\tUniformBufferId environment{};\n\n\tTexture textures[BLUE_AVAILABLE_TEXTURE_SLOTS];\n\n\tFramebuffer framebuffer{};\n\n};\n\n\n\n// 64 bytes of size - fills CPU cache line on IA32/IA64 and ARM A-series (most of smartphones).\n\n// It is performance optimization, to keep RenderEntity from being too bloated and get boost \n\n// from prefetching on modern CPU's.\n\n// static_assert(sizeof(RenderEntity) <= 64, \"Render entity too big.\");\n\n\n", "file_path": "include/blue/Renderer.h", "rank": 40, "score": 38764.18591210263 }, { "content": "class Logger \n\n{\n\npublic:\n\n\n\n\tLogger();\n\n\n\n\tinline spdlog::logger& get() \n\n\t{\n\n\t\tBLUE_ASSERT(_logger);\n\n\t\treturn *_logger;\n\n\t}\n\n\n\nprivate:\n\n\n\n std::shared_ptr<spdlog::logger> _logger = nullptr;\n\n};\n\n\n\n\n\n#endif //OPENGL_PLAYGROUND_LOGGER_HPP\n", "file_path": "include/blue/Logger.hpp", "rank": 41, "score": 38764.18591210263 }, { "content": "\tclass Window\n\n\t{\n\n\tpublic:\n\n\n\n\t\t~Window();\n\n\n\n\t\tbool create(std::uint16_t width, std::uint16_t height);\n\n\n\n\t\tbool create_fullscreen();\n\n\n\n\t\tbool create_hidden();\n\n\n\n\t\tbool init_gl_context();\n\n\n\n\t\tinline std::uint16_t get_width() const { return _width.load(); }\n\n\n\n\t\tinline std::uint16_t get_height() const { return _height.load(); }\n\n\n\n\t\tinline SDL_GLContext get_context() const { return _gl_context.load(); }\n\n\n", "file_path": "include/blue/Window.hpp", "rank": 42, "score": 38764.18591210263 }, { "content": "using InstanceType = float;\n\n\n\nusing Vertices = std::vector<VertexType>;\n\nusing Indices = std::vector<IndexType>;\n\nusing Instances = std::vector<InstanceType>;\n\nusing Attributes = std::vector<ShaderAttribute>;\n\n\n\nusing ShaderId = GLuint;\n\nusing TextureId = GLuint;\n\nusing TextureSlot = GLuint;\n\nusing VertexArrayId = GLuint;\n\nusing IndexBufferId = GLuint;\n\nusing VertexBufferId = GLuint;\n\nusing InstanceBufferId = GLuint;\n\nusing UniformBufferId = GLuint;\n\nusing FramebufferId = GLuint;\n\n\n", "file_path": "include/blue/gpu/GpuEntities.hpp", "rank": 43, "score": 37300.95947069121 }, { "content": "#pragma once\n\n\n\n#include \"blue/Assertions.h\"\n\n\n\n#include <glad/glad.h>\n\n#include <glm/mat4x4.hpp>\n\n#include <memory>\n\n#include <vector>\n\n#include <string>\n\n\n", "file_path": "include/blue/gpu/GpuEntities.hpp", "rank": 44, "score": 37300.75484885709 }, { "content": "\t\tstd::atomic<std::uint32_t> y_tiles{ 0 };\n\n\t\tstd::atomic<std::uint32_t> x{ 0 };\n\n\t\tstd::atomic<std::uint32_t> y{ 0 };\n\n\t} intersection;\n\n\n\nprivate:\n\n\n\n\tstd::atomic_bool _running{ true };\n\n\tstd::shared_ptr<BaseState> _current_state = nullptr;\n\n\tstd::shared_ptr<Map> _map = std::make_shared<Map>();\n\n\tstd::shared_ptr<Water> _water = std::make_shared<Water>();\n\n\tstd::shared_ptr<Flora> _flora = std::make_shared<Flora>();\n\n\tstatic Game* _instance;\n\n};\n", "file_path": "examples/advanced/game/include/Game.hpp", "rank": 45, "score": 37300.58616913804 }, { "content": "#pragma once\n\n\n\n#include \"terrain/Map.hpp\"\n\n#include \"terrain/Flora.hpp\"\n\n#include \"terrain/Water.hpp\"\n\n\n\n#include \"states/BaseState.hpp\"\n\n\n\n#include <atomic>\n\n#include <memory>\n\n#include <states/MainMenu.hpp>\n\n\n", "file_path": "examples/advanced/game/include/Game.hpp", "rank": 46, "score": 37300.169260702285 }, { "content": "\tMap& get_map();\n\n\n\n\tFlora& get_flora();\n\n\n\n\tWater& get_water();\n\n\n\n\tstruct {\n\n\t\tstd::atomic_bool gesture{ false };\n\n\t\tstd::atomic<std::uint32_t> press_x{ 0 };\n\n\t\tstd::atomic<std::uint32_t> press_y{ 0 };\n\n\t\tstd::atomic<std::uint32_t> release_x{ 0 };\n\n\t\tstd::atomic<std::uint32_t> release_y{ 0 };\n\n\t\tstd::atomic<std::uint32_t> last_x{ 0 };\n\n\t\tstd::atomic<std::uint32_t> last_y{ 0 };\n\n\t} input;\n\n\n\n\tstruct {\n\n\t\tstd::atomic_bool requested{ false };\n\n\t\tstd::atomic_bool found{ false };\n\n\t\tstd::atomic<std::uint32_t> x_tiles{ 0 };\n", "file_path": "examples/advanced/game/include/Game.hpp", "rank": 47, "score": 37296.9681243787 }, { "content": "\t\tShaderId clickable_map;\n\n\t\tShaderId decoration_map;\n\n\t\tShaderId model;\n\n\t\tShaderId model_instanced;\n\n\t\tShaderId simple_depth;\n\n\t\tShaderId simple_depth_instanced;\n\n\t\tShaderId swinging;\n\n\t\tShaderId water;\n\n\t\tShaderId tile_highlight;\n\n\t\tShaderId simple_texture;\n\n\t} shaders;\n\n\t\n\n\tstruct {\n\n\t\tVertexArray pine_tree;\n\n\t\tVertexArray hurdle;\n\n\t\tVertexArray wheat;\n\n\t\tVertexArray boulder;\n\n\t\tVertexArray small_boulder;\n\n\t\tVertexArray grass;\n\n\t\tVertexArray pylon;\n", "file_path": "examples/advanced/common/include/Resources.hpp", "rank": 48, "score": 37296.87825154772 }, { "content": "#pragma once\n\n\n\n#include <blue/camera/OrthographicCamera.hpp>\n\n#include <blue/camera/PerspectiveCamera.hpp>\n\n#include <blue/gpu/GpuEntities.hpp>\n\n#include <blue/gui/Button.hpp>\n\n#include <blue/FontUtils.hpp>\n\n\n", "file_path": "examples/advanced/common/include/Resources.hpp", "rank": 49, "score": 37296.74990758923 }, { "content": "#pragma once\n\n\n\n#include \"blue/camera/Camera.hpp\"\n\n\n", "file_path": "include/blue/camera/OrthographicCamera.hpp", "rank": 50, "score": 37295.89716569578 }, { "content": "\n\n\tvoid load_render_entities();\n\n\n\n\tvoid load_environment();\n\n\n\n\tvoid load_shaders();\n\n\n\n\tvoid load_fonts();\n\n\n\n\tvoid load_models();\n\n\n\n\tvoid load_textures();\n\n\n\n\tstruct\n\n\t{\n\n\t\tFontUtils::Font lato;\n\n\t} fonts;\n\n\n\n\tstruct {\n\n\t\tUniformBufferId environment = 0;\n", "file_path": "examples/advanced/common/include/Resources.hpp", "rank": 51, "score": 37294.64977986472 }, { "content": "\t\tcase Type::VEC4:\n\n\t\t\treturn 4;\n\n\t\tdefault:\n\n\t\t\tBLUE_ASSERT(false);\n\n\t\t\treturn 0;\n\n\t\t}\n\n\t}\n\n\n\n\tstd::size_t getSize() const\n\n\t{\n\n\t\treturn sizeof(float) * getNumOfComponents();\n\n\t}\n\n\n\n\tconst Type _type;\n\n\tconst Purpose _purpose;\n\n\tconst Buffer _buffer;\n\n};\n\n\n\nusing VertexType = float;\n\nusing IndexType = unsigned int;\n", "file_path": "include/blue/gpu/GpuEntities.hpp", "rank": 52, "score": 37294.580437797806 }, { "content": "#pragma once\n\n\n\n#include \"blue/camera/Camera.hpp\"\n\n\n\n// A normalized vector is one which is often used just to denote pure directions\n\n// without bothering about the magnitude (set to 1; hence their other, more common name unit vector)\n\n// i.e. how far the vector pushes doesn't matter but in what direction does it point/push matters.\n\n\n\n// FIXME: Quaternions may be faster than rotation matrices\n", "file_path": "include/blue/camera/PerspectiveCamera.hpp", "rank": 53, "score": 37294.25732155503 }, { "content": "// TODO: Rename this class to \"Input\".\n\nclass InputHandler {\n\n\n\npublic:\n\n\n\n\tinline void registerKeyCallback(const KeyCallback& callback)\n\n\t{\n\n\t\tauto iterator = std::remove_if(keyboardKeyCommands.begin(), keyboardKeyCommands.end(), [callback](const KeyCallback& list_callback) -> bool {\n\n\t\t\treturn callback.key_type == list_callback.key_type && callback.action == list_callback.action;\n\n\t\t\t});\n\n\n\n\t\tif (iterator != keyboardKeyCommands.end())\n\n\t\t{\n\n\t\t\tkeyboardKeyCommands.erase(iterator);\n\n\t\t}\n\n\n\n\t\tkeyboardKeyCommands.emplace_back(callback);\n\n\t}\n\n\t\n\n\tinline void registerMouseKeyCallback(const MouseKeyCallback& callback)\n\n\t{\n", "file_path": "include/blue/InputHandler.h", "rank": 54, "score": 37291.665683582505 }, { "content": "\tvoid set_rotation(const glm::vec3& euler);\n\n\n\n\t// moving\n\n\n\n\tvoid go_forward(float distance);\n\n\n\n\tvoid go_backward(float distance);\n\n\n\n\tvoid go_left(float distance);\n\n\n\n\tvoid go_right(float distance);\n\n\n\n\tvoid mouse_rotation(double xpos, double ypos);\n\n\n\n\t// getters\n\n\n\n\tfloat get_roll() const;\n\n\n\n\tfloat get_pitch() const;\n\n\n", "file_path": "include/blue/camera/OrthographicCamera.hpp", "rank": 55, "score": 37291.665683582505 }, { "content": "\tvoid add_rotation(float yaw, float pitch);\n\n\n\n\tvoid set_near(float);\n\n\n\n\tvoid set_far(float);\n\n\n\n\t// moving\n\n\n\n\tvoid go_forward(float distance);\n\n\n\n\tvoid go_backward(float distance);\n\n\n\n\tvoid go_left(float distance);\n\n\n\n\tvoid go_right(float distance);\n\n\n\n\tvoid mouse_rotation(double xpos, double ypos);\n\n\n\n\t// getters\n\n\n", "file_path": "include/blue/camera/PerspectiveCamera.hpp", "rank": 56, "score": 37291.665683582505 }, { "content": "class Camera\n\n{\n\npublic:\n\n\n\n\tCamera(std::uint16_t viewport_width, std::uint16_t viewport_height) : _viewport_width(viewport_width), _viewport_height(viewport_height)\n\n\t{ }\n\n\n\n\tvirtual glm::mat4 get_view() = 0;\n\n\n\n\tvirtual glm::mat4 get_projection() = 0;\n\n\n\n\tvoid set_viewport_width(std::uint16_t viewport_width) { _viewport_width = viewport_width; };\n\n\tvoid set_viewport_height(std::uint16_t viewport_height) { _viewport_height = viewport_height; };\n\n\n\nprotected:\n\n\n\n\tstd::uint16_t _viewport_width{};\n\n\tstd::uint16_t _viewport_height{};\n\n};\n", "file_path": "include/blue/camera/Camera.hpp", "rank": 57, "score": 37291.665683582505 }, { "content": "class Button\n\n{\n\n\n\npublic:\n\n\n\n static void init(); // Not thread safe.\n\n\n\n void create(const UniformBufferId& environment, const Texture& clicked, const Texture& idle);\n\n void update_placing_rules(const PlacingRules&);\n\n\n\n void set_clicked(bool clicked);\n\n bool is_clicked() { return _clicked;}\n\n bool collision(std::uint16_t click_x, std::uint16_t click_y) const;\n\n\n\n void dispose();\n\n\n\nprivate:\n\n\n\n std::uint16_t _x_center{};\n\n std::uint16_t _y_center{};\n\n std::uint16_t _width{};\n\n std::uint16_t _height{};\n\n\n\n bool _clicked{};\n\n PlacingRules _rules{};\n\n RenderEntity _entity{};\n\n};\n", "file_path": "include/blue/gui/Button.hpp", "rank": 58, "score": 37291.665683582505 }, { "content": "\tfloat get_roll() const;\n\n\n\n\tfloat get_pitch() const;\n\n\n\n\tfloat get_yaw() const;\n\n\n\n\tfloat get_fov() const;\n\n\n\n\tglm::vec3 get_position() const;\n\n\n\n\tglm::vec3 get_front() const;\n\n\n\n\tglm::vec3 get_up() const;\n\n\n\n\tGLfloat get_last_x() const;\n\n\n\n\tGLfloat get_last_y() const;\n\n\n\nprivate:\n\n\n", "file_path": "include/blue/camera/PerspectiveCamera.hpp", "rank": 59, "score": 37291.665683582505 }, { "content": "\tfloat get_yaw() const;\n\n\n\n\tfloat get_fov() const;\n\n\n\n\tglm::vec3 get_position() const;\n\n\n\n\tglm::vec3 get_front() const;\n\n\n\n\tglm::vec3 get_up() const;\n\n\n\n\tGLfloat get_last_x() const;\n\n\n\n\tGLfloat get_last_y() const;\n\n\n\n\tvoid set_near(float);\n\n\n\n\tvoid set_far(float);\n\n\n\nprivate:\n\n\n", "file_path": "include/blue/camera/OrthographicCamera.hpp", "rank": 60, "score": 37291.665683582505 }, { "content": " Mode _mode;\n\n\n\n\t// roll is always 0\n\n\tGLfloat _yaw = 0;\n\n\tGLfloat _pitch = 0;\n\n\tGLfloat _lastX = 0;\n\n\tGLfloat _lastY = 0;\n\n\tGLfloat _fov = 0;\n\n\tfloat _aspect{}; // (view ratio)\n\n\n\n\tglm::vec3 _position = glm::vec3(0.0f, 0.0f, 10.0f);\n\n\tglm::vec3 _front = glm::vec3(0.0f, 0.0f, -1.0f);\n\n\n\n\tglm::vec3 _HELPER_CAMERA_TARGET = glm::vec3(0.0f, 0.0f, 0.0f);\n\n\tglm::vec3 _HELPER_CAMERA_DIRECTION = glm::normalize(_position - _HELPER_CAMERA_TARGET);\n\n\tglm::vec3 _HELPER_UP = glm::vec3(0.0f, 1.0f, 0.0f);\n\n\tglm::vec3 _CAMERA_RIGHT = glm::normalize(glm::cross(_HELPER_UP, _HELPER_CAMERA_DIRECTION));\n\n\tglm::vec3 _CAMERA_UP = glm::cross(_HELPER_CAMERA_DIRECTION, _CAMERA_RIGHT);\n\n\n\n\tfloat _near = -1;\n\n\tfloat _far = 1;\n\n};\n", "file_path": "include/blue/camera/OrthographicCamera.hpp", "rank": 61, "score": 37291.665683582505 }, { "content": "struct KeyCallback\n\n{\n\n\tstd::function<void()> callback;\n\n\tint key_type;\n\n\tint action;\n\n};\n\n\n", "file_path": "include/blue/InputHandler.h", "rank": 62, "score": 37291.665683582505 }, { "content": "\t// roll is always 0\n\n\tGLfloat _yaw = 0;\n\n\tGLfloat _pitch = 0;\n\n\tGLfloat _lastX = 0;\n\n\tGLfloat _lastY = 0;\n\n\tGLfloat _fov = 0;\n\n\n\n\tglm::vec3 _position = glm::vec3(0.0f, 0.0f, 10.0f);\n\n\tglm::vec3 _front = glm::vec3(0.0f, 0.0f, -1.0f);\n\n\n\n\tglm::vec3 _HELPER_CAMERA_TARGET = glm::vec3(0.0f, 0.0f, 0.0f);\n\n\tglm::vec3 _HELPER_CAMERA_DIRECTION = glm::normalize(_position - _HELPER_CAMERA_TARGET);\n\n\tglm::vec3 _HELPER_UP = glm::vec3(0.0f, 1.0f, 0.0f);\n\n\tglm::vec3 _CAMERA_RIGHT = glm::normalize(glm::cross(_HELPER_UP, _HELPER_CAMERA_DIRECTION));\n\n\tglm::vec3 _CAMERA_UP = glm::cross(_HELPER_CAMERA_DIRECTION, _CAMERA_RIGHT);\n\n\n\n\tfloat _near = 0.1f;\n\n\tfloat _far = 500.0f;\n\n\n\n\tfloat _aspect{}; // (view ratio)\n\n};\n", "file_path": "include/blue/camera/PerspectiveCamera.hpp", "rank": 63, "score": 37291.665683582505 }, { "content": "\t\tPerspectiveCamera camera = PerspectiveCamera(0, 0);\n\n\t} map_environment;\n\n\n\n\tstruct {\n\n\t\tOrthographicCamera camera = OrthographicCamera(OrthographicCamera::Mode::SCREEN_SPACE, 0, 0);\n\n\t\tUniformBufferId environment = 0;\n\n\t} gui_environment;\n\n\n\n\tstruct {\n\n\t\tUniformBufferId environment = 0;\n\n\t\tOrthographicCamera camera = OrthographicCamera(OrthographicCamera::Mode::CLIP_SPACE, 0, 0);\n\n\t\tFramebuffer depth;\n\n\t} light_environment;\n\n\n\n\tstruct\n\n\t{\n\n\t\tRenderEntity selected_tile_highlight;\n\n\t} render_entities;\n\n\n\n\tstruct {\n", "file_path": "examples/advanced/common/include/Resources.hpp", "rank": 64, "score": 37291.665683582505 }, { "content": "\t\tVertexArray bush;\n\n\t\tVertexArray cut_tree;\n\n\t\tVertexArray track;\n\n\t\tVertexArray bridge;\n\n\t\tVertexArray square;\n\n\t} models;\n\n\n\n\tstruct {\n\n\t\tTexture start;\n\n\t\tTexture start_clicked;\n\n\t\tTexture options;\n\n\t\tTexture options_clicked;\n\n\t\tTexture exit;\n\n\t\tTexture exit_clicked;\n\n\t} textures;\n\n\n\nprivate:\n\n\n\n\tstatic Resources* _instance;\n\n};\n", "file_path": "examples/advanced/common/include/Resources.hpp", "rank": 65, "score": 37291.665683582505 }, { "content": "\tstd::uint32_t decoration_tiles = 0;\n\n\tstd::uint32_t clickable_tiles = 0;\n\n\n\n\tVertices decoration_vertices;\n\n\tIndices decoration_indices;\n\n\t\n\n\tVertices clickable_vertices;\n\n\tIndices clickable_indices;\n\n\n\n\tVertices clickable_vertices;\n\n\tIndices clickable_indices;\n\n\n\n\tstd::mutex tiles_access;\n\n\tTile tiles[CHUNK_DIMENSION][CHUNK_DIMENSION];\n\n\n\n\tRenderEntityId clickable_vertices_render_entity;\n\n\tRenderEntityId decoration_vertices_render_entity;\n\n};\n", "file_path": "examples/advanced/common/include/terrain/Map.hpp", "rank": 66, "score": 35937.06789840063 }, { "content": " Water& get_water();\n\n\n\n\tstruct {\n\n\t\tstd::atomic_bool clicked{ false };\n\n\t\tstd::atomic_int clicked_button { 0 };\n\n\t\tstd::atomic_bool intersection {false};\n\n\t\tstd::atomic<uint16_t> intersection_tile_x {0};\n\n\t\tstd::atomic<uint16_t> intersection_tile_y {0};\n\n\t\t// It's assumed that y = 0 on intersection point.\n\n\t\tstd::atomic<double> intersection_point_x {0};\n\n\t\tstd::atomic<double> intersection_point_y {0};\n\n\t} input;\n\n\n\nprivate:\n\n\n\n\tvoid register_callbacks();\n\n\n\n std::shared_ptr<Flora> _flora = std::make_shared<Flora>();\n\n std::shared_ptr<Water> _water = std::make_shared<Water>();\n\n std::shared_ptr<Map> _map = std::make_shared<Map>();\n\n\tstd::shared_ptr<BaseState> _current_state = nullptr;\n\n\tstd::atomic_bool _running{ true };\n\n\tstatic Application* _instance;\n\n};\n", "file_path": "examples/advanced/terrain-editor/include/Application.hpp", "rank": 67, "score": 35936.89673764018 }, { "content": "#pragma once\n\n\n\n#include \"terrain/Map.hpp\"\n\n\n\n#include <string>\n\n\n", "file_path": "examples/advanced/common/include/terrain/Water.hpp", "rank": 68, "score": 35936.148253096115 }, { "content": "#pragma once\n\n\n\n#include <future>\n\n#include <queue>\n\n#include <utility>\n\n#include <atomic>\n\n\n\n#include <blue/gpu/GpuEntities.hpp>\n\n#include <blue/Renderer.h>\n\n\n", "file_path": "include/blue/gpu/GpuCommandSystem.hpp", "rank": 69, "score": 35935.92993318649 }, { "content": "#pragma once\n\n\n\n#include <string>\n\n#include <vector>\n\n\n\n#include \"Resources.hpp\"\n\n#include \"glm/glm.hpp\"\n\n#include \"blue/Renderer.h\"\n\n\n\n// Not thread safe.\n", "file_path": "examples/advanced/common/include/terrain/Flora.hpp", "rank": 70, "score": 35935.89139561121 }, { "content": "#pragma once\n\n\n\n#include \"states/BaseState.hpp\"\n\n#include \"terrain/Map.hpp\"\n\n#include \"terrain/Water.hpp\"\n\n#include \"terrain/Flora.hpp\"\n\n\n\n#include <atomic>\n\n#include <memory>\n\n\n", "file_path": "examples/advanced/terrain-editor/include/Application.hpp", "rank": 71, "score": 35935.64077977987 }, { "content": "\n\n\tvoid elevate_clickable_points(float x, float y, float R, float elevation);\n\n\tvoid elevate_decoration_points(float x, float y, float R, float elevation);\n\n\n\n\tvoid shuffle_color_points(float x, float y, float R);\n\n\n\n\tvoid import_from_file(const std::string& filename);\n\n\tvoid export_to_file(const std::string& filename);\n\n\n\n\tvoid set_tile_occupant(UnitType occupant, std::uint16_t tile_x, std::uint16_t tile_y);\n\n\tUnitType get_tile_occupant(std::uint16_t tile_x, std::uint16_t tile_y);\n\n\n\nprivate:\n\n\t\n\n\tvoid color_points(float x, float y, float R, const glm::vec3& color, Vertices& vertices);\n\n\tvoid elevate_points(float x, float y, float R, float elevation, Vertices& vertices);\n\n\n\n\tvoid color_points(float x, float y, float R, const glm::vec3& color, Vertices& vertices);\n\n\tvoid elevate_points(float x, float y, float R, float elevation, Vertices& vertices);\n\n\n", "file_path": "examples/advanced/common/include/terrain/Map.hpp", "rank": 72, "score": 35933.766806054125 }, { "content": "#pragma once\n\n\n\n#include \"blue/Renderer.h\"\n\n#include \"blue/camera/PerspectiveCamera.hpp\"\n\n#include \"terrain/Tile.hpp\"\n\n#include <mutex>\n\n\n", "file_path": "examples/advanced/common/include/terrain/Map.hpp", "rank": 73, "score": 35932.15377708238 }, { "content": "#pragma once\n\n\n\n#include \"jobs/MapIntersectionJob.h\"\n\n#include \"jobs/FramerateRenderingJob.h\"\n\n#include \"BaseState.hpp\"\n\n\n", "file_path": "examples/advanced/game/include/states/Playing.hpp", "rank": 74, "score": 35931.93277079107 }, { "content": "#pragma once\n\n\n\n#include \"blue/Renderer.h\"\n\n\n", "file_path": "examples/advanced/common/include/terrain/Tile.hpp", "rank": 75, "score": 35931.31852102294 }, { "content": "\tstd::queue<std::pair<std::promise<std::vector<char>>, ReadFramebufferEntity>> read_framebuffer_entities;\n\n\n\n\tstd::queue<UpdateUniformVariableEntity> update_uniform_variable_entities;\n\n\tstd::queue<SetClearColorEntity> set_clear_color_entities;\n\n\tstd::queue<std::pair<std::promise<bool>, AddFramebufferTextureAttachmentEntity>> add_framebuffer_texture_attachment_entities;\n\n\tstd::queue<DisposeMeshEntity> dispose_mesh_entities;\n\n\tstd::queue<DisposeTextureEntity> dispose_texture_entities;\n\n\tstd::queue<DisposeShaderEntity> dispose_shader_entities;\n\n\tstd::queue<UpdateEnvironmentEntity_CameraPos> update_environment_camera_pos_entities;\n\n\tstd::queue<UpdateEnvironmentEntity_LightPos> update_environment_light_pos_entities;\n\n\tstd::queue<UpdateEnvironmentEntity_View> update_environment_view_entities;\n\n\tstd::queue<UpdateEnvironmentEntity_LightSpaceMatrix> update_environment_light_space_matrix_entities;\n\n\tstd::queue<UpdateEnvironmentEntity_Projection> update_environment_projection_entities;\n\n\tstd::queue<UpdateEnvironmentEntity_AmbientStrength> update_ambient_strength_entities;\n\n\tstd::queue<UpdateEnvironmentEntity_LightColor> update_light_color_entities;\n\n\n\n\tstd::atomic_bool locked {false};\n\n};\n", "file_path": "include/blue/gpu/GpuCommandSystem.hpp", "rank": 76, "score": 35930.98871389419 }, { "content": "\tvoid submit(const UpdateEnvironmentEntity_View&);\n\n\tvoid submit(const UpdateEnvironmentEntity_LightSpaceMatrix&);\n\n\tvoid submit(const UpdateEnvironmentEntity_CameraPos&);\n\n\tvoid submit(const UpdateEnvironmentEntity_LightPos&);\n\n\tvoid submit(const UpdateEnvironmentEntity_LightColor&);\n\n\tvoid submit(const UpdateEnvironmentEntity_AmbientStrength&);\n\n\tvoid submit(const SetClearColorEntity&);\n\n\n\nprivate:\n\n\t\n\n\tbool execute();\n\n\tvoid lock();\n\n\tvoid unlock();\n\n\n\n\tstd::queue<std::pair<std::promise<VertexArray>, CreateMeshEntity>> create_mesh_entities;\n\n\tstd::queue<std::pair<std::promise<VertexArray>, CreateInstancedMeshEntity>> create_instanced_mesh_entities;\n\n\tstd::queue<std::pair<std::promise<ShaderId>, CompileShaderEntity>> compile_shader_entities;\n\n\tstd::queue<std::pair<std::promise<Texture>, CreateTextureEntity>> create_texture_entities;\n\n\tstd::queue<std::pair<std::promise<Framebuffer>, CreateFramebufferEntity>> create_framebuffer_entities;\n\n\tstd::queue<std::pair<std::promise<UniformBufferId>, CreateEnvironmentEntity>> create_env_entities;\n", "file_path": "include/blue/gpu/GpuCommandSystem.hpp", "rank": 77, "score": 35929.52940592877 }, { "content": "struct Texture\n\n{\n\n\tTextureSlot slot = 0;\n\n\tTextureId id = 0;\n\n\tstd::uint16_t width;\n\n\tstd::uint16_t height;\n\n\tTexturePassedDataFormat passedDataFormat;\n\n\tTextureStoringFormat storingFormat;\n\n\tTexturePassedDataComponentSize passedDataComponentSize;\n\n};\n\n\n", "file_path": "include/blue/gpu/GpuEntities.hpp", "rank": 78, "score": 35926.92345338177 }, { "content": "class Resources\n\n{\n\npublic:\n\n\n", "file_path": "examples/advanced/common/include/Resources.hpp", "rank": 79, "score": 35926.92345338177 }, { "content": "\t\tstd::vector<CreateTextureEntity> create_texture_entities;\n", "file_path": "include/blue/ModelLoader.h", "rank": 80, "score": 35926.92345338177 }, { "content": "class Game\n\n{\n\npublic:\n\n\n\n\tstatic Game& instance();\n\n\n\n\tstatic void init();\n\n\n\n\tstatic void dispose();\n\n\n\n\tvoid reset_state();\n\n\n\n\tvoid enter_state(std::shared_ptr<BaseState> state);\n\n\n\n\tvoid shutdown();\n\n\n\n\tvoid handle_input();\n\n\n\n\tbool is_running();\n\n\n", "file_path": "examples/advanced/game/include/Game.hpp", "rank": 81, "score": 35926.92345338177 }, { "content": "struct MouseKeyCallback\n\n{\n\n\tstd::function<void(double x, double y)> callback;\n\n\tint key_type;\n\n\tint action;\n\n};\n\n\n", "file_path": "include/blue/InputHandler.h", "rank": 82, "score": 35926.92345338177 }, { "content": "struct Environment\n\n{\n\n\tglm::mat4 view;\n\n\tglm::mat4 projection;\n\n};\n\n\n", "file_path": "include/blue/gpu/GpuEntities.hpp", "rank": 83, "score": 35926.92345338177 }, { "content": "struct Framebuffer\n\n{\n\n\tFramebufferId framebuffer = 0;\n\n\tTexture texture{};\n\n};\n\n\n", "file_path": "include/blue/gpu/GpuEntities.hpp", "rank": 84, "score": 35926.92345338177 }, { "content": "class GpuThread\n\n{\n\npublic:\n\n\n\n\tvoid wait_for_render_pass();\n\n\n\n\tbool is_running();\n\n\n\n\tbool run();\n\n\n\n\tvoid stop();\n\n\n\n\tinline std::uint64_t get_time_spent() { return _time_spent.load(); }\n\n\n\nprivate:\n\n\n\n\tvoid render_thread_loop();\n\n\n\n\tstd::atomic<std::uint64_t> _time_spent{0};\n\n\tstd::promise<bool> _start_thread_status;\n\n\tstd::atomic_bool _thread_running{ false };\n\n\tstd::thread _thread;\n\n\tstd::mutex render_pass_mtx;\n\n\tstd::condition_variable render_pass_cv;\n\n};\n", "file_path": "include/blue/GpuThread.hpp", "rank": 85, "score": 35926.92345338177 }, { "content": "\t}\n\n\n\n\tGLuint compile_shader(const std::string& source, GLenum shader_type)\n\n\t{\n\n\t\tGLuint shaderId = 0;\n\n\n\n\t\tstd::string source_copy = source;\n\n\t\tsource_copy.insert(0, getOpenGLVersion());\n\n\n\n\t\tconst char* cstr = source_copy.c_str();\n\n\t\tconst GLchar* const* c = &cstr;\n\n\n\n\t\tshaderId = glCreateShader(shader_type);\n\n\t\tglShaderSource(shaderId, 1, c, NULL);\n\n\t\tglCompileShader(shaderId);\n\n\n\n\t\tGLint success;\n\n\t\tGLchar infoLog[512];\n\n\t\tglGetShaderiv(shaderId, GL_COMPILE_STATUS, &success);\n\n\n", "file_path": "src/blue/gpu/handlers/CompileShaderHandler.cpp", "rank": 86, "score": 35634.0247361399 }, { "content": "#include \"blue/gpu/handlers/CompileShaderHandler.hpp\"\n\n#include \"blue/Context.hpp\"\n\n\n\nnamespace\n\n{\n\n\t// TODO: Remove explicit uniform location once uniform buffers are used.\n\n\tconst char* getOpenGLVersion() {\n\n#ifdef BLUE_ANDROID\n\n\t // Explicit uniform locations work from 3.1 ES - setting 3.0 with enabled extension:\n\n\t // https://android-developers.googleblog.com/2015/04/game-performance-explicit-uniform.html\n\n\t\treturn \"#version 300 es\\n #extension GL_ARB_explicit_uniform_location : enable \\n\";\n\n#else\n\n\t\treturn \"#version 330 core\\n #extension GL_ARB_explicit_uniform_location : enable \\n\";\n\n#endif\n\n\t}\n\n\n\n\tGLuint link_shaders(GLuint vertexShaderId, GLuint fragmentShaderId)\n\n\t{\n\n\t\tGLuint shaderProgramId = glCreateProgram();\n\n\n", "file_path": "src/blue/gpu/handlers/CompileShaderHandler.cpp", "rank": 87, "score": 35633.983136672236 }, { "content": "#include \"blue/gpu/handlers/DisposeShaderHandler.hpp\"\n\n#include \"blue/Context.hpp\"\n\n\n\nvoid handle(const DisposeShaderEntity& entity)\n\n{\n\n\tblue::Context::logger().info(\"Disposing shader program with id: {}\", entity.shader);\n\n\tDebugGlCall(glDeleteShader(entity.shader));\n\n}\n", "file_path": "src/blue/gpu/handlers/DisposeShaderHandler.cpp", "rank": 88, "score": 35632.71593409378 }, { "content": " DebugGlCall(glUniformBlockBinding(id, uniformBlockIndex, 0));\n\n\t}\n\n\telse\n\n\t{\n\n\t\tblue::Context::logger().warn(\"Not found blue uniform buffer in shader.\");\n\n\t}\n\n}\n\n\n\nvoid handle(std::pair<std::promise<ShaderId>, CompileShaderEntity>& pair)\n\n{\n\n\tstd::promise<ShaderId>& promise = pair.first;\n\n\tconst CompileShaderEntity& entity = pair.second;\n\n\n\n\tconst auto vertexProgram = compile_shader(entity.vertex, GL_VERTEX_SHADER);\n\n\tconst auto fragmentProgram = compile_shader(entity.fragment, GL_FRAGMENT_SHADER);\n\n\tconst auto linked = link_shaders(vertexProgram, fragmentProgram);\n\n\n\n\tbind_with_uniform_buffer(linked);\n\n\n\n\tpromise.set_value(linked);\n\n}\n", "file_path": "src/blue/gpu/handlers/CompileShaderHandler.cpp", "rank": 89, "score": 35632.109910842475 }, { "content": "\t\tif (!success)\n\n\t\t{\n\n\t\t\tglGetShaderInfoLog(shaderId, 512, NULL, infoLog);\n\n\t\t\tblue::Context::logger().info(\"Shader failed to compile ({}).\", shaderId);\n\n\t\t\tblue::Context::logger().info(\"Reason: {}\", infoLog);\n\n\t\t\treturn 0;\n\n\t\t}\n\n\n\n\t\tblue::Context::logger().info(\"Shader compiled successfuly ({}).\", shaderId);\n\n\t\treturn shaderId;\n\n\t}\n\n}\n\n\n\nvoid bind_with_uniform_buffer(ShaderId id)\n\n{\n\n\t// TODO: Rename \"Matrices\" to \"Blue_Environment\"\n\n\tint uniformBlockIndex = glGetUniformBlockIndex(id, \"Matrices\");\n\n\tif (uniformBlockIndex >= 0)\n\n\t{\n\n\t\tblue::Context::logger().info(\"Found blue uniform buffer in shader, binding.\");\n", "file_path": "src/blue/gpu/handlers/CompileShaderHandler.cpp", "rank": 90, "score": 35630.648844511255 }, { "content": "\t\tglAttachShader(shaderProgramId, vertexShaderId);\n\n\t\tglAttachShader(shaderProgramId, fragmentShaderId);\n\n\t\tglLinkProgram(shaderProgramId);\n\n\n\n\t\tGLint success;\n\n\t\tGLchar infoLog[512];\n\n\t\tglGetProgramiv(shaderProgramId, GL_LINK_STATUS, &success);\n\n\n\n\t\tif (!success)\n\n\t\t{\n\n\t\t\tglGetProgramInfoLog(shaderProgramId, 512, NULL, infoLog);\n\n\t\t\tblue::Context::logger().info(\"Linking failed for shaders: {} {}\", vertexShaderId, fragmentShaderId);\n\n\t\t\tblue::Context::logger().info(\"Reason: {}\", infoLog);\n\n\t\t\treturn 0;\n\n\t\t}\n\n\n\n\t\tglDeleteShader(vertexShaderId);\n\n\t\tglDeleteShader(fragmentShaderId);\n\n\n\n\t\treturn shaderProgramId;\n", "file_path": "src/blue/gpu/handlers/CompileShaderHandler.cpp", "rank": 91, "score": 35629.18042051879 }, { "content": "#pragma once\n\n\n\n#include <atomic>\n\n#include <thread>\n\n\n", "file_path": "examples/advanced/game/include/jobs/MapIntersectionJob.h", "rank": 92, "score": 34668.0339262143 }, { "content": "#pragma once\n\n\n\n#include <atomic>\n\n#include <thread>\n\n#include <blue/Renderer.h>\n\n\n", "file_path": "examples/advanced/game/include/jobs/FramerateRenderingJob.h", "rank": 93, "score": 34667.993845144265 }, { "content": "#pragma once\n\n\n\n#include \"states/BaseState.hpp\"\n\n#include \"blue/Renderer.h\"\n\n\n\n#include <atomic>\n\n\n", "file_path": "examples/advanced/terrain-editor/include/states/Greeting.hpp", "rank": 94, "score": 34667.66104246224 }, { "content": "#pragma once\n\n\n\n#include <blue/gui/Button.hpp>\n\n#include \"BaseState.hpp\"\n\n\n\n#include <atomic>\n\n\n", "file_path": "examples/advanced/game/include/states/MainMenu.hpp", "rank": 95, "score": 34667.556061383584 }, { "content": "#pragma once\n\n\n\n#include \"blue/gpu/GpuCommandSystem.hpp\"\n\n\n\nvoid handle(std::pair<std::promise<std::vector<char>>, ReadFramebufferEntity>& pair);\n", "file_path": "include/blue/gpu/handlers/ReadFramebufferHandler.hpp", "rank": 96, "score": 34665.224919237575 }, { "content": "#pragma once\n\n\n\n#include <memory>\n\n\n", "file_path": "examples/advanced/game/include/states/BaseState.hpp", "rank": 97, "score": 34663.02579787662 }, { "content": "#pragma once\n\n\n\n#include \"blue/gpu/GpuCommandSystem.hpp\"\n\n\n\nvoid handle(const DisposeMeshEntity& entity);\n", "file_path": "include/blue/gpu/handlers/DisposeMeshHandler.hpp", "rank": 98, "score": 34662.22723440335 }, { "content": "#pragma once\n\n\n\n#include \"blue/gpu/GpuCommandSystem.hpp\"\n\n\n\nvoid handle(DisposeTextureEntity& entity);\n", "file_path": "include/blue/gpu/handlers/DisposeTextureHandler.hpp", "rank": 99, "score": 34662.22723440335 } ]
C++
Code/Engine/Animation/Graph/Nodes/Animation_RuntimeGraphNode_Parameters.cpp
JuanluMorales/KRG
f3a11de469586a4ef0db835af4bc4589e6b70779
#include "Animation_RuntimeGraphNode_Parameters.h" namespace KRG::Animation::GraphNodes { void ControlParameterBoolNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<ControlParameterBoolNode>( nodePtrs, options ); } void ControlParameterBoolNode::GetValueInternal( GraphContext& context, void* pOutValue ) { *( (bool*) pOutValue ) = m_value; } void ControlParameterBoolNode::SetValueInternal( GraphContext& context, void const* pInValue ) { m_value = *(bool*) pInValue; } void ControlParameterIDNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<ControlParameterIDNode>( nodePtrs, options ); } void ControlParameterIDNode::GetValueInternal( GraphContext& context, void* pOutValue ) { *( (StringID*) pOutValue ) = m_value; } void ControlParameterIDNode::SetValueInternal( GraphContext& context, void const* pInValue ) { m_value = *(StringID*) pInValue; } void ControlParameterIntNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<ControlParameterIntNode>( nodePtrs, options ); } void ControlParameterIntNode::GetValueInternal( GraphContext& context, void* pOutValue ) { *( (int32*) pOutValue ) = m_value; } void ControlParameterIntNode::SetValueInternal( GraphContext& context, void const* pInValue ) { m_value = *(int32*) pInValue; } void ControlParameterFloatNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<ControlParameterFloatNode>( nodePtrs, options ); } void ControlParameterFloatNode::GetValueInternal( GraphContext& context, void* pOutValue ) { *( (float*) pOutValue ) = m_value; } void ControlParameterFloatNode::SetValueInternal( GraphContext& context, void const* pInValue ) { m_value = *(float*) pInValue; } void ControlParameterVectorNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<ControlParameterVectorNode>( nodePtrs, options ); } void ControlParameterVectorNode::GetValueInternal( GraphContext& context, void* pOutValue ) { *( (Vector*) pOutValue ) = m_value; } void ControlParameterVectorNode::SetValueInternal( GraphContext& context, void const* pInValue ) { m_value = *(Vector*) pInValue; } void ControlParameterTargetNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<ControlParameterTargetNode>( nodePtrs, options ); } void ControlParameterTargetNode::GetValueInternal( GraphContext& context, void* pOutValue ) { *( (Target*) pOutValue ) = m_value; } void ControlParameterTargetNode::SetValueInternal( GraphContext& context, void const* pInValue ) { m_value = *(Target*) pInValue; } void ControlParameterBoneMaskNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<ControlParameterBoneMaskNode>( nodePtrs, options ); } void ControlParameterBoneMaskNode::InitializeInternal( GraphContext& context ) { BoneMaskValueNode::InitializeInternal( context ); m_value = eastl::move( BoneMask( context.m_pSkeleton, 1.0f ) ); } void ControlParameterBoneMaskNode::ShutdownInternal( GraphContext& context ) { m_value = eastl::move( BoneMask() ); BoneMaskValueNode::ShutdownInternal( context ); } void ControlParameterBoneMaskNode::GetValueInternal( GraphContext& context, void* pOutValue ) { *reinterpret_cast<BoneMask const**>( pOutValue ) = &m_value; } void ControlParameterBoneMaskNode::SetValueInternal( GraphContext& context, void const* pInValue ) { auto pBoneMaskPtr = *reinterpret_cast<BoneMask const* const*>( pInValue ); m_value = *pBoneMaskPtr; } void VirtualParameterBoolNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<VirtualParameterBoolNode>( nodePtrs, options ); SetNodePtrFromIndex( nodePtrs, m_childNodeIdx, pNode->m_pChildNode ); } void VirtualParameterBoolNode::InitializeInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); BoolValueNode::InitializeInternal( context ); m_pChildNode->Initialize( context ); } void VirtualParameterBoolNode::ShutdownInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); m_pChildNode->Shutdown( context ); BoolValueNode::ShutdownInternal( context ); } void VirtualParameterBoolNode::GetValueInternal( GraphContext& context, void* pOutValue ) { KRG_ASSERT( m_pChildNode != nullptr ); *reinterpret_cast<bool*>( pOutValue ) = m_pChildNode->GetValue<bool>( context ); } void VirtualParameterIDNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<VirtualParameterIDNode>( nodePtrs, options ); SetNodePtrFromIndex( nodePtrs, m_childNodeIdx, pNode->m_pChildNode ); } void VirtualParameterIDNode::InitializeInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); IDValueNode::InitializeInternal( context ); m_pChildNode->Initialize( context ); } void VirtualParameterIDNode::ShutdownInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); m_pChildNode->Shutdown( context ); IDValueNode::ShutdownInternal( context ); } void VirtualParameterIDNode::GetValueInternal( GraphContext& context, void* pOutValue ) { KRG_ASSERT( m_pChildNode != nullptr ); *reinterpret_cast<StringID*>( pOutValue ) = m_pChildNode->GetValue<StringID>( context ); } void VirtualParameterIntNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<VirtualParameterIntNode>( nodePtrs, options ); SetNodePtrFromIndex( nodePtrs, m_childNodeIdx, pNode->m_pChildNode ); } void VirtualParameterIntNode::InitializeInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); IntValueNode::InitializeInternal( context ); m_pChildNode->Initialize( context ); } void VirtualParameterIntNode::ShutdownInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); m_pChildNode->Shutdown( context ); IntValueNode::ShutdownInternal( context ); } void VirtualParameterIntNode::GetValueInternal( GraphContext& context, void* pOutValue ) { KRG_ASSERT( m_pChildNode != nullptr ); *reinterpret_cast<int32*>( pOutValue ) = m_pChildNode->GetValue<int32>( context ); } void VirtualParameterFloatNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<VirtualParameterFloatNode>( nodePtrs, options ); SetNodePtrFromIndex( nodePtrs, m_childNodeIdx, pNode->m_pChildNode ); } void VirtualParameterFloatNode::InitializeInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); FloatValueNode::InitializeInternal( context ); m_pChildNode->Initialize( context ); } void VirtualParameterFloatNode::ShutdownInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); m_pChildNode->Shutdown( context ); FloatValueNode::ShutdownInternal( context ); } void VirtualParameterFloatNode::GetValueInternal( GraphContext& context, void* pOutValue ) { KRG_ASSERT( m_pChildNode != nullptr ); *reinterpret_cast<float*>( pOutValue ) = m_pChildNode->GetValue<float>( context ); } void VirtualParameterVectorNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<VirtualParameterVectorNode>( nodePtrs, options ); SetNodePtrFromIndex( nodePtrs, m_childNodeIdx, pNode->m_pChildNode ); } void VirtualParameterVectorNode::InitializeInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); VectorValueNode::InitializeInternal( context ); m_pChildNode->Initialize( context ); } void VirtualParameterVectorNode::ShutdownInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); m_pChildNode->Shutdown( context ); VectorValueNode::ShutdownInternal( context ); } void VirtualParameterVectorNode::GetValueInternal( GraphContext& context, void* pOutValue ) { KRG_ASSERT( m_pChildNode != nullptr ); *reinterpret_cast<Vector*>( pOutValue ) = m_pChildNode->GetValue<Vector>( context ); } void VirtualParameterTargetNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<VirtualParameterTargetNode>( nodePtrs, options ); SetNodePtrFromIndex( nodePtrs, m_childNodeIdx, pNode->m_pChildNode ); } void VirtualParameterTargetNode::InitializeInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); TargetValueNode::InitializeInternal( context ); m_pChildNode->Initialize( context ); } void VirtualParameterTargetNode::ShutdownInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); m_pChildNode->Shutdown( context ); TargetValueNode::ShutdownInternal( context ); } void VirtualParameterTargetNode::GetValueInternal( GraphContext& context, void* pOutValue ) { KRG_ASSERT( m_pChildNode != nullptr ); *reinterpret_cast<Target*>( pOutValue ) = m_pChildNode->GetValue<Target>( context ); } void VirtualParameterBoneMaskNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<VirtualParameterBoneMaskNode>( nodePtrs, options ); SetNodePtrFromIndex( nodePtrs, m_childNodeIdx, pNode->m_pChildNode ); } void VirtualParameterBoneMaskNode::InitializeInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); BoneMaskValueNode::InitializeInternal( context ); m_pChildNode->Initialize( context ); } void VirtualParameterBoneMaskNode::ShutdownInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); m_pChildNode->Shutdown( context ); BoneMaskValueNode::ShutdownInternal( context ); } void VirtualParameterBoneMaskNode::GetValueInternal( GraphContext& context, void* pOutValue ) { KRG_ASSERT( m_pChildNode != nullptr ); *reinterpret_cast<BoneMask const**>( pOutValue ) = m_pChildNode->GetValue<BoneMask const*>( context ); } }
#include "Animation_RuntimeGraphNode_Parameters.h" namespace KRG::Animation::GraphNodes { void ControlParameterBoolNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<ControlParameterBoolNode>( nodePtrs, options ); } void ControlParameterBoolNode::GetValueInternal( GraphContext& context, void* pOutValue ) { *( (bool*) pOutValue ) = m_value; } void ControlParameterBoolNode::SetValueInternal( GraphContext& context, void const* pInValue ) { m_value = *(bool*) pInValue; } void ControlParameterIDNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<ControlParameterIDNode>( nodePtrs, options ); } void ControlParameterIDNode::GetValueInternal( GraphContext& context, void* pOutValue ) { *( (StringID*) pOutValue ) = m_value; } void ControlParameterIDNode::SetValueInternal( GraphContext& context, void const* pInValue ) { m_value = *(StringID*) pInValue; } void ControlParameterIntNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<ControlParameterIntNode>( nodePtrs, options ); } void ControlParameterIntNode::GetValueInternal( GraphContext& context, void* pOutValue ) { *( (int32*) pOutValue ) = m_value; } void ControlParameterIntNode::SetValueInternal( GraphContext& context, void const* pInValue ) { m_value = *(int32*) pInValue; } void ControlParameterFloatNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<ControlParameterFloatNode>( nodePtrs, options ); } void ControlParameterFloatNode::GetValueInternal( GraphContext& context, void* pOutValue ) { *( (float*) pOutValue ) = m_value; } void ControlParameterFloatNode::SetValueInternal( GraphContext& context, void const* pInValue ) { m_value = *(float*) pInValue; } void ControlParameterVectorNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<ControlParameterVectorNode>( nodePtrs, options ); } void ControlParameterVectorNode::GetValueInternal( GraphContext& context, void* pOutValue ) { *( (Vector*) pOutValue ) = m_value; } void ControlParameterVectorNode::SetValueInternal( GraphContext& context, void const* pInValue ) { m_value = *(Vector*) pInValue; } void ControlParameterTargetNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<ControlParameterTargetNode>( nodePtrs, options ); } void ControlParameterTargetNode::GetValueInternal( GraphContext& context, void* pOutValue ) { *( (Target*) pOutValue ) = m_value; } void ControlParameterTargetNode::SetValueInternal( GraphContext& context, void const* pInValue ) { m_value = *(Target*) pInValue; } void ControlParameterBoneMaskNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<ControlParameterBoneMaskNode>( nodePtrs, options ); } void ControlParameterBoneMaskNode::InitializeInternal( GraphContext& context ) { BoneMaskValueNode::InitializeInternal( context ); m_value = eastl::move( BoneMask( context.m_pSkeleton, 1.0f ) ); } void ControlParameterBoneMaskNode::ShutdownInternal( GraphContext& context ) { m_value = eastl::move( BoneMask() ); BoneMaskValueNode::ShutdownInternal( context ); } void ControlParameterBoneMaskNode::GetValueInternal( GraphContext& context, void* pOutValue ) { *reinterpret_cast<BoneMask const**>( pOutValue ) = &m_value; } void ControlParameterBoneMaskNode::SetValueInternal( GraphContext& context, void const* pInValue ) { auto pBoneMaskPtr = *reinterpret_cast<BoneMask const* const*>( pInValue ); m_value = *pBoneMaskPtr; } void VirtualParameterBoolNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<VirtualParameterBoolNode>( nodePtrs, options ); SetNodePtrFromIndex( nodePtrs, m_childNodeIdx, pNode->m_pChildNode ); } void VirtualParameterBoolNode::InitializeInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); BoolValueNode::InitializeInternal( context ); m_pChildNode->Initialize( context ); } void VirtualParameterBoolNode::ShutdownInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); m_pChildNode->Shutdown( context ); BoolValueNode::ShutdownInternal( context ); } void VirtualParameterBoolNode::GetValueInternal( GraphContext& context, void* pOutValue ) { KRG_ASSERT( m_pChildNode != nullptr ); *reinterpret_cast<bool*>( pOutValue ) = m_pChildNode->GetValue<bool>( context ); } void VirtualParameterIDNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<VirtualParameterIDNode>( nodePtrs, options ); SetNodePtrFromIndex( nodePtrs, m_childNodeIdx, pNode->m_pChildNode ); } void VirtualParameterIDNode::InitializeInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); IDValueNode::InitializeInternal( context ); m_pChildNode->Initialize( context ); } void VirtualParameterIDNode::ShutdownInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); m_pChildNode->Shutdown( context ); IDValueNode::ShutdownInternal( context ); } void VirtualParameterIDNode::GetValueInternal( GraphContext& context, void* pOutValue ) { KRG_ASSERT( m_pChildNode != nullptr ); *reinterpret_cast<StringID*>( pOutValue ) = m_pChildNode->GetValue<StringID>( context ); } void VirtualParameterIntNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<VirtualParameterIntNode>( nodePtrs, options ); SetNodePtrFromIndex( nodePtrs, m_childNodeIdx, pNode->m_pChildNode ); } void VirtualParameterIntNode::InitializeInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); IntValueNode::InitializeInternal( context ); m_pChildNode->Initialize( context ); } void VirtualParameterIntNode::ShutdownInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); m_pChildNode->Shutdown( context ); IntValueNode::ShutdownInternal( context ); } void VirtualParameterIntNode::GetValueInternal( GraphContext& context, void* pOutValue ) { KRG_ASSERT( m_pChildNode != nullptr ); *reinterpret_cast<int32*>( pOutValue ) = m_pChildNode->GetValue<int32>( context ); } void VirtualParameterFloatNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<VirtualParameterFloatNode>( nodePtrs, options ); SetNodePtrFromIndex( nodePtrs, m_childNodeIdx, pNode->m_pChildNode ); } void VirtualParameterFloatNode::InitializeInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); FloatValueNode::InitializeInternal( context ); m_pChildNode->Initialize( context ); } void VirtualParameterFloatNode::ShutdownInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); m_pChildNode->Shutdown( context ); FloatValueNode::ShutdownInternal( context ); } void VirtualParameterFloatNode::GetValueInternal( GraphContext& context, void* pOutValue ) { KRG_ASSERT( m_pChildNode != nullptr ); *reinterpret_cast<float*>( pOutValue ) = m_pChildNode->GetValue<float>( context ); } void VirtualParameterVectorNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<VirtualParameterVectorNode>( nodePtrs, options ); SetNodePtrFromIndex( nodePtrs, m_childNodeIdx, pNode->m_pChildNode ); } void VirtualParameterVectorNode::InitializeInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); VectorValueNode::InitializeInternal( context ); m_pChildNode->Initialize( context ); } void VirtualParameterVectorNode::ShutdownInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); m_pChildNode->Shutdown( context ); VectorValueNode::ShutdownInternal( context ); } void VirtualParameterVectorNode::GetValueInternal( GraphContext& context, void* pOutValue ) { KRG_ASSERT( m_pChildNode != nullptr ); *reinterpret_cast<Vector*>( pOutValue ) = m_pChildNode->GetValue<Vector>( context ); } void VirtualParameterTargetNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<VirtualParameterTargetNode>( nodePtrs, options ); SetNodePtrFromIndex( nodePtrs, m_childNodeIdx, pNode->m_pChildNode ); }
void VirtualParameterTargetNode::ShutdownInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); m_pChildNode->Shutdown( context ); TargetValueNode::ShutdownInternal( context ); } void VirtualParameterTargetNode::GetValueInternal( GraphContext& context, void* pOutValue ) { KRG_ASSERT( m_pChildNode != nullptr ); *reinterpret_cast<Target*>( pOutValue ) = m_pChildNode->GetValue<Target>( context ); } void VirtualParameterBoneMaskNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<VirtualParameterBoneMaskNode>( nodePtrs, options ); SetNodePtrFromIndex( nodePtrs, m_childNodeIdx, pNode->m_pChildNode ); } void VirtualParameterBoneMaskNode::InitializeInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); BoneMaskValueNode::InitializeInternal( context ); m_pChildNode->Initialize( context ); } void VirtualParameterBoneMaskNode::ShutdownInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); m_pChildNode->Shutdown( context ); BoneMaskValueNode::ShutdownInternal( context ); } void VirtualParameterBoneMaskNode::GetValueInternal( GraphContext& context, void* pOutValue ) { KRG_ASSERT( m_pChildNode != nullptr ); *reinterpret_cast<BoneMask const**>( pOutValue ) = m_pChildNode->GetValue<BoneMask const*>( context ); } }
void VirtualParameterTargetNode::InitializeInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); TargetValueNode::InitializeInternal( context ); m_pChildNode->Initialize( context ); }
function_block-full_function
[]
C++
chrome/browser/renderer_host/render_process_host_chrome_browsertest.cc
hujiajie/pa-chromium
1816ff80336a6efd1616f9e936880af460b1e105
#include "base/command_line.h" #include "chrome/browser/devtools/devtools_window.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/singleton_tabs.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" using content::RenderViewHost; using content::RenderWidgetHost; using content::WebContents; namespace { int RenderProcessHostCount() { content::RenderProcessHost::iterator hosts = content::RenderProcessHost::AllHostsIterator(); int count = 0; while (!hosts.IsAtEnd()) { if (hosts.GetCurrentValue()->HasConnection()) count++; hosts.Advance(); } return count; } RenderViewHost* FindFirstDevToolsHost() { content::RenderProcessHost::iterator hosts = content::RenderProcessHost::AllHostsIterator(); for (; !hosts.IsAtEnd(); hosts.Advance()) { content::RenderProcessHost* render_process_host = hosts.GetCurrentValue(); DCHECK(render_process_host); if (!render_process_host->HasConnection()) continue; content::RenderProcessHost::RenderWidgetHostsIterator iter( render_process_host->GetRenderWidgetHostsIterator()); for (; !iter.IsAtEnd(); iter.Advance()) { const RenderWidgetHost* widget = iter.GetCurrentValue(); DCHECK(widget); if (!widget || !widget->IsRenderView()) continue; RenderViewHost* host = RenderViewHost::From(const_cast<RenderWidgetHost*>(widget)); WebContents* contents = WebContents::FromRenderViewHost(host); GURL url = contents->GetURL(); if (url.SchemeIs(chrome::kChromeDevToolsScheme)) return host; } } return NULL; } } class ChromeRenderProcessHostTest : public InProcessBrowserTest { public: ChromeRenderProcessHostTest() {} base::ProcessHandle ShowSingletonTab(const GURL& page) { chrome::ShowSingletonTab(browser(), page); WebContents* wc = browser()->tab_strip_model()->GetActiveWebContents(); CHECK(wc->GetURL() == page); content::BrowserThread::PostTaskAndReply( content::BrowserThread::PROCESS_LAUNCHER, FROM_HERE, base::Bind(&base::DoNothing), base::MessageLoop::QuitClosure()); base::MessageLoop::current()->Run(); return wc->GetRenderProcessHost()->GetHandle(); } void TestProcessOverflow() { int tab_count = 1; int host_count = 1; WebContents* tab1 = NULL; WebContents* tab2 = NULL; content::RenderProcessHost* rph1 = NULL; content::RenderProcessHost* rph2 = NULL; content::RenderProcessHost* rph3 = NULL; GURL newtab(chrome::kChromeUINewTabURL); ui_test_utils::NavigateToURL(browser(), newtab); EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph1 = tab1->GetRenderProcessHost(); EXPECT_EQ(tab1->GetURL(), newtab); EXPECT_EQ(host_count, RenderProcessHostCount()); GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph2 = tab1->GetRenderProcessHost(); EXPECT_EQ(tab1->GetURL(), page1); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph2); GURL page2("data:text/html,hello world2"); ui_test_utils::WindowedTabAddedNotificationObserver observer2( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page2); observer2.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), page2); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_EQ(tab2->GetRenderProcessHost(), rph2); GURL history(chrome::kChromeUIHistoryURL); ui_test_utils::WindowedTabAddedNotificationObserver observer3( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), history); observer3.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), GURL(history)); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_EQ(tab2->GetRenderProcessHost(), rph1); GURL bookmarks(chrome::kChromeUIBookmarksURL); ui_test_utils::WindowedTabAddedNotificationObserver observer4( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), bookmarks); observer4.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph3 = tab1->GetRenderProcessHost(); EXPECT_EQ(tab1->GetURL(), bookmarks); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph3); EXPECT_NE(rph2, rph3); } }; class ChromeRenderProcessHostTestWithCommandLine : public ChromeRenderProcessHostTest { protected: virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE { command_line->AppendSwitchASCII(switches::kRendererProcessLimit, "1"); } }; IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, ProcessPerTab) { content::RenderProcessHost::SetMaxRendererProcessCount(1); CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess(); parsed_command_line.AppendSwitch(switches::kProcessPerTab); int tab_count = 1; int host_count = 1; GURL newtab(chrome::kChromeUINewTabURL); ui_test_utils::NavigateToURL(browser(), newtab); EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); GURL page2("data:text/html,hello world2"); ui_test_utils::WindowedTabAddedNotificationObserver observer2( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page2); observer2.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); ui_test_utils::WindowedTabAddedNotificationObserver observer3( content::NotificationService::AllSources()); chrome::NewTab(browser()); observer3.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); ui_test_utils::WindowedTabAddedNotificationObserver observer4( content::NotificationService::AllSources()); chrome::NewTab(browser()); observer4.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); } #if defined(OS_WIN) || defined(OS_LINUX) IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, Backgrounding) { if (!base::Process::CanBackgroundProcesses()) { LOG(ERROR) << "Can't background processes"; return; } CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess(); parsed_command_line.AppendSwitch(switches::kProcessPerTab); GURL newtab(chrome::kChromeUINewTabURL); ui_test_utils::NavigateToURL(browser(), newtab); GURL page1("data:text/html,hello world1"); base::ProcessHandle pid1 = ShowSingletonTab(page1); EXPECT_FALSE(base::Process(pid1).IsProcessBackgrounded()); GURL page2("data:text/html,hello world2"); base::ProcessHandle pid2 = ShowSingletonTab(page2); EXPECT_NE(pid1, pid2); EXPECT_TRUE(base::Process(pid1).IsProcessBackgrounded()); EXPECT_FALSE(base::Process(pid2).IsProcessBackgrounded()); EXPECT_EQ(pid1, ShowSingletonTab(page1)); EXPECT_FALSE(base::Process(pid1).IsProcessBackgrounded()); EXPECT_TRUE(base::Process(pid2).IsProcessBackgrounded()); } #endif #if defined(OS_WIN) #define MAYBE_ProcessOverflow DISABLED_ProcessOverflow #else #define MAYBE_ProcessOverflow ProcessOverflow #endif IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, MAYBE_ProcessOverflow) { content::RenderProcessHost::SetMaxRendererProcessCount(1); TestProcessOverflow(); } IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTestWithCommandLine, ProcessOverflow) { TestProcessOverflow(); } IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, DevToolsOnSelfInOwnProcessPPT) { CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess(); parsed_command_line.AppendSwitch(switches::kProcessPerTab); int tab_count = 1; int host_count = 1; GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); chrome::ToggleDevToolsWindow(browser(), DEVTOOLS_TOGGLE_ACTION_INSPECT); host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); RenderViewHost* devtools = FindFirstDevToolsHost(); DCHECK(devtools); DevToolsWindow::ToggleDevToolsWindow( devtools, true, DEVTOOLS_TOGGLE_ACTION_INSPECT); host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); } IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, DevToolsOnSelfInOwnProcess) { int tab_count = 1; int host_count = 1; GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); chrome::ToggleDevToolsWindow(browser(), DEVTOOLS_TOGGLE_ACTION_INSPECT); host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); RenderViewHost* devtools = FindFirstDevToolsHost(); DCHECK(devtools); DevToolsWindow::ToggleDevToolsWindow( devtools, true, DEVTOOLS_TOGGLE_ACTION_INSPECT); host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); }
#include "base/command_line.h" #include "chrome/browser/devtools/devtools_window.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/singleton_tabs.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" using content::RenderViewHost; using content::RenderWidgetHost; using content::WebContents; namespace {
RenderViewHost* FindFirstDevToolsHost() { content::RenderProcessHost::iterator hosts = content::RenderProcessHost::AllHostsIterator(); for (; !hosts.IsAtEnd(); hosts.Advance()) { content::RenderProcessHost* render_process_host = hosts.GetCurrentValue(); DCHECK(render_process_host); if (!render_process_host->HasConnection()) continue; content::RenderProcessHost::RenderWidgetHostsIterator iter( render_process_host->GetRenderWidgetHostsIterator()); for (; !iter.IsAtEnd(); iter.Advance()) { const RenderWidgetHost* widget = iter.GetCurrentValue(); DCHECK(widget); if (!widget || !widget->IsRenderView()) continue; RenderViewHost* host = RenderViewHost::From(const_cast<RenderWidgetHost*>(widget)); WebContents* contents = WebContents::FromRenderViewHost(host); GURL url = contents->GetURL(); if (url.SchemeIs(chrome::kChromeDevToolsScheme)) return host; } } return NULL; } } class ChromeRenderProcessHostTest : public InProcessBrowserTest { public: ChromeRenderProcessHostTest() {} base::ProcessHandle ShowSingletonTab(const GURL& page) { chrome::ShowSingletonTab(browser(), page); WebContents* wc = browser()->tab_strip_model()->GetActiveWebContents(); CHECK(wc->GetURL() == page); content::BrowserThread::PostTaskAndReply( content::BrowserThread::PROCESS_LAUNCHER, FROM_HERE, base::Bind(&base::DoNothing), base::MessageLoop::QuitClosure()); base::MessageLoop::current()->Run(); return wc->GetRenderProcessHost()->GetHandle(); } void TestProcessOverflow() { int tab_count = 1; int host_count = 1; WebContents* tab1 = NULL; WebContents* tab2 = NULL; content::RenderProcessHost* rph1 = NULL; content::RenderProcessHost* rph2 = NULL; content::RenderProcessHost* rph3 = NULL; GURL newtab(chrome::kChromeUINewTabURL); ui_test_utils::NavigateToURL(browser(), newtab); EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph1 = tab1->GetRenderProcessHost(); EXPECT_EQ(tab1->GetURL(), newtab); EXPECT_EQ(host_count, RenderProcessHostCount()); GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph2 = tab1->GetRenderProcessHost(); EXPECT_EQ(tab1->GetURL(), page1); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph2); GURL page2("data:text/html,hello world2"); ui_test_utils::WindowedTabAddedNotificationObserver observer2( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page2); observer2.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), page2); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_EQ(tab2->GetRenderProcessHost(), rph2); GURL history(chrome::kChromeUIHistoryURL); ui_test_utils::WindowedTabAddedNotificationObserver observer3( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), history); observer3.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), GURL(history)); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_EQ(tab2->GetRenderProcessHost(), rph1); GURL bookmarks(chrome::kChromeUIBookmarksURL); ui_test_utils::WindowedTabAddedNotificationObserver observer4( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), bookmarks); observer4.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph3 = tab1->GetRenderProcessHost(); EXPECT_EQ(tab1->GetURL(), bookmarks); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph3); EXPECT_NE(rph2, rph3); } }; class ChromeRenderProcessHostTestWithCommandLine : public ChromeRenderProcessHostTest { protected: virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE { command_line->AppendSwitchASCII(switches::kRendererProcessLimit, "1"); } }; IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, ProcessPerTab) { content::RenderProcessHost::SetMaxRendererProcessCount(1); CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess(); parsed_command_line.AppendSwitch(switches::kProcessPerTab); int tab_count = 1; int host_count = 1; GURL newtab(chrome::kChromeUINewTabURL); ui_test_utils::NavigateToURL(browser(), newtab); EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); GURL page2("data:text/html,hello world2"); ui_test_utils::WindowedTabAddedNotificationObserver observer2( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page2); observer2.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); ui_test_utils::WindowedTabAddedNotificationObserver observer3( content::NotificationService::AllSources()); chrome::NewTab(browser()); observer3.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); ui_test_utils::WindowedTabAddedNotificationObserver observer4( content::NotificationService::AllSources()); chrome::NewTab(browser()); observer4.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); } #if defined(OS_WIN) || defined(OS_LINUX) IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, Backgrounding) { if (!base::Process::CanBackgroundProcesses()) { LOG(ERROR) << "Can't background processes"; return; } CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess(); parsed_command_line.AppendSwitch(switches::kProcessPerTab); GURL newtab(chrome::kChromeUINewTabURL); ui_test_utils::NavigateToURL(browser(), newtab); GURL page1("data:text/html,hello world1"); base::ProcessHandle pid1 = ShowSingletonTab(page1); EXPECT_FALSE(base::Process(pid1).IsProcessBackgrounded()); GURL page2("data:text/html,hello world2"); base::ProcessHandle pid2 = ShowSingletonTab(page2); EXPECT_NE(pid1, pid2); EXPECT_TRUE(base::Process(pid1).IsProcessBackgrounded()); EXPECT_FALSE(base::Process(pid2).IsProcessBackgrounded()); EXPECT_EQ(pid1, ShowSingletonTab(page1)); EXPECT_FALSE(base::Process(pid1).IsProcessBackgrounded()); EXPECT_TRUE(base::Process(pid2).IsProcessBackgrounded()); } #endif #if defined(OS_WIN) #define MAYBE_ProcessOverflow DISABLED_ProcessOverflow #else #define MAYBE_ProcessOverflow ProcessOverflow #endif IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, MAYBE_ProcessOverflow) { content::RenderProcessHost::SetMaxRendererProcessCount(1); TestProcessOverflow(); } IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTestWithCommandLine, ProcessOverflow) { TestProcessOverflow(); } IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, DevToolsOnSelfInOwnProcessPPT) { CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess(); parsed_command_line.AppendSwitch(switches::kProcessPerTab); int tab_count = 1; int host_count = 1; GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); chrome::ToggleDevToolsWindow(browser(), DEVTOOLS_TOGGLE_ACTION_INSPECT); host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); RenderViewHost* devtools = FindFirstDevToolsHost(); DCHECK(devtools); DevToolsWindow::ToggleDevToolsWindow( devtools, true, DEVTOOLS_TOGGLE_ACTION_INSPECT); host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); } IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, DevToolsOnSelfInOwnProcess) { int tab_count = 1; int host_count = 1; GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); chrome::ToggleDevToolsWindow(browser(), DEVTOOLS_TOGGLE_ACTION_INSPECT); host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); RenderViewHost* devtools = FindFirstDevToolsHost(); DCHECK(devtools); DevToolsWindow::ToggleDevToolsWindow( devtools, true, DEVTOOLS_TOGGLE_ACTION_INSPECT); host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); }
int RenderProcessHostCount() { content::RenderProcessHost::iterator hosts = content::RenderProcessHost::AllHostsIterator(); int count = 0; while (!hosts.IsAtEnd()) { if (hosts.GetCurrentValue()->HasConnection()) count++; hosts.Advance(); } return count; }
function_block-full_function
[]
C++
src/material/material_mixture.cpp
Luvideria/lightmetrica-v3
3e83db59998e79648047bac29c37d8eb18d7600d
#include <pch.h> #include <lm/core.h> #include <lm/material.h> #include <lm/surface.h> LM_NAMESPACE_BEGIN(LM_NAMESPACE) class Material_ConstantWeightMixture_RR final : public Material { private: struct Entry { Material* material; Float weight; template <typename Archive> void serialize(Archive& ar) { ar(material, weight); } }; std::vector<Entry> materials_; Dist dist_; public: LM_SERIALIZE_IMPL(ar) { ar(materials_, dist_); } virtual void foreach_underlying(const ComponentVisitor& visit) override { for (auto& e : materials_) { comp::visit(visit, e.material); } } public: virtual void construct(const Json& prop) override { for (auto& entry : prop) { auto* mat = json::comp_ref<Material>(entry, "material"); const auto weight = json::value<Float>(entry, "weight"); materials_.push_back({ mat, weight }); dist_.add(weight); } dist_.norm(); } virtual ComponentSample sample_component(const ComponentSampleU& u, const PointGeometry&, Vec3) const override { const int comp = dist_.sample(u.uc[0]); const auto p = dist_.pmf(comp); return { comp, 1_f / p }; } virtual Float pdf_component(int comp, const PointGeometry&, Vec3) const override { return dist_.pmf(comp); } virtual std::optional<DirectionSample> sample_direction(const DirectionSampleU& us, const PointGeometry& geom, Vec3 wi, int comp, TransDir trans_dir) const override { const auto& e = materials_[comp]; const auto s = e.material->sample_direction(us, geom, wi, {}, trans_dir); if (!s) { return {}; } return DirectionSample{ s->wo, e.weight * s->weight }; } virtual Vec3 reflectance(const PointGeometry& geom) const override { Vec3 sum(0_f); for (const auto& e : materials_) { sum += e.weight * e.material->reflectance(geom); } return sum; } virtual Float pdf_direction(const PointGeometry& geom, Vec3 wi, Vec3 wo, int comp, bool eval_delta) const override { return materials_[comp].material->pdf_direction(geom, wi, wo, {}, eval_delta); } virtual Vec3 eval(const PointGeometry& geom, Vec3 wi, Vec3 wo, int comp, TransDir trans_dir, bool eval_delta) const override { const auto& e = materials_[comp]; return e.weight * e.material->eval(geom, wi, wo, {}, trans_dir, eval_delta); } virtual bool is_specular_component(int comp) const override { return materials_[comp].material->is_specular_component({}); } }; LM_COMP_REG_IMPL(Material_ConstantWeightMixture_RR, "material::constant_weight_mixture_rr"); class Material_ConstantWeightMixture_Marginalized final : public Material { private: struct MaterialGroup { struct Entry { Material* material; Float weight; template <typename Archive> void serialize(Archive& ar) { ar(material, weight); } }; std::vector<Entry> entries; Dist dist; template <typename Archive> void serialize(Archive& ar) { ar(entries, dist); } }; std::vector<MaterialGroup> material_groups_; Dist dist_; public: LM_SERIALIZE_IMPL(ar) { ar(material_groups_, dist_); } virtual void foreach_underlying(const ComponentVisitor& visit) override { for (auto& material_group : material_groups_) { for (auto& e : material_group.entries) { comp::visit(visit, e.material); } } } public: virtual void construct(const Json& prop) override { material_groups_.emplace_back(); for (auto& entry : prop) { auto* mat = json::comp_ref<Material>(entry, "material"); const auto weight = json::value<Float>(entry, "weight"); if (mat->is_specular_component({})) { material_groups_.emplace_back(); material_groups_.back().entries.push_back({ mat, weight }); } else { material_groups_[0].entries.push_back({ mat, weight }); } } for (auto& group : material_groups_) { Float weight_sum = 0_f; for (const auto& entry : group.entries) { weight_sum += entry.weight; group.dist.add(entry.weight); } group.dist.norm(); dist_.add(weight_sum); } dist_.norm(); } virtual ComponentSample sample_component(const ComponentSampleU& u, const PointGeometry&, Vec3) const override { const int comp = dist_.sample(u.uc[0]); const auto p = dist_.pmf(comp); return { comp, 1_f / p }; } virtual Float pdf_component(int comp, const PointGeometry&, Vec3) const override { return dist_.pmf(comp); } virtual std::optional<DirectionSample> sample_direction(const DirectionSampleU& us, const PointGeometry& geom, Vec3 wi, int comp, TransDir trans_dir) const override { const auto& group = material_groups_[comp]; const int comp_in_group = group.dist.sample(us.udc[0]); const auto& e = group.entries[comp_in_group]; const auto s = e.material->sample_direction(us, geom, wi, {}, trans_dir); if (!s) { return {}; } const auto f = eval(geom, wi, s->wo, comp, trans_dir, false); const auto p = pdf_direction(geom, wi, s->wo, comp, false); const auto C = f / p; return DirectionSample{ s->wo, C }; } virtual Vec3 reflectance(const PointGeometry& geom) const override { Vec3 sum(0_f); for (auto& group : material_groups_) { for (const auto& entry : group.entries) { sum += entry.weight * entry.material->reflectance(geom); } } return sum; } virtual Float pdf_direction(const PointGeometry& geom, Vec3 wi, Vec3 wo, int comp, bool eval_delta) const override { const auto& group = material_groups_[comp]; Float p_marginal = 0_f; for (int i = 0; i < (int)(group.entries.size()); i++) { const auto p_sel = group.dist.pmf(i); const auto p = group.entries[i].material->pdf_direction(geom, wi, wo, {}, eval_delta); p_marginal += p_sel * p; } return p_marginal; } virtual Vec3 eval(const PointGeometry& geom, Vec3 wi, Vec3 wo, int comp, TransDir trans_dir, bool eval_delta) const override { const auto& group = material_groups_[comp]; Vec3 result(0_f); for (const auto& entry : group.entries) { const auto f = entry.material->eval(geom, wi, wo, {}, trans_dir, eval_delta); result += entry.weight * f; } return result; } virtual bool is_specular_component(int comp) const override { return comp != 0; } }; LM_COMP_REG_IMPL(Material_ConstantWeightMixture_Marginalized, "material::constant_weight_mixture_marginalized"); LM_NAMESPACE_END(LM_NAMESPACE)
#include <pch.h> #include <lm/core.h> #include <lm/material.h> #include <lm/surface.h> LM_NAMESPACE_BEGIN(LM_NAMESPACE) class Material_ConstantWeightMixture_RR final : public Material { private: struct Entry { Material* material; Float weight; template <typename Archive> void serialize(Archive& ar) { ar(material, weight); } }; std::vector<Entry> materials_; Dist dist_; public: LM_SERIALIZE_IMPL(ar) { ar(materials_, dist_); } virtual void foreach_underlying(const ComponentVisitor& visit) override { for (auto& e : materials_) { comp::visit(visit, e.material); } } public: virtual void construct(const Json& prop) override { for (auto& entry : prop) { auto* mat = json::comp_ref<Material>(entry, "material"); const auto weight = json::value<Float>(entry, "weight"); materials_.push_back({ mat, weight }); dist_.add(weight); } dist_.norm(); } virtual ComponentSample sample_component(const ComponentSampleU& u, const PointGeometry&, Vec3) const override { const int comp = dist_.sample(u.uc[0]); const auto p = dist_.pmf(comp); return { comp, 1_f / p }; } virtual Float pdf_component(int comp, const PointGeometry&, Vec3) const override { return dist_.pmf(comp); } virtual std::optional<DirectionSample> sample_direction(const DirectionSampleU& us, const PointGeometry& geom, Vec3 wi, int comp, TransDir trans_dir) const override { const auto& e = materials_[comp]; const auto s = e.material->sample_direction(us, geom, wi, {}, trans_dir); if (!s) { return {}; } return DirectionSample{ s->wo, e.weight * s->weight }; } virtual Vec3 reflectance(const PointGeometry& geom) const override { Vec3 sum(0_f); for (const auto& e : materials_) { sum += e.weight * e.material->reflectance(geom); } return sum; } virtual Float pdf_direction(const PointGeometry& geom, Vec3 wi, Vec3 wo, int comp, bool eval_delta) const override { return materials_[comp].material->pdf_direction(geom, wi, wo, {}, eval_delta); } virtual Vec3 eval(const PointGeometry& geom, Vec3 wi, Vec3 wo, int comp, TransDir trans_dir, bool eval_delta) const override { const auto& e = materials_[comp]; return e.weight * e.material->eval(geom, wi, wo, {}, trans_dir, eval_delta); } virtual bool is_specular_component(int comp) const override { return materials_[comp].material->is_specular_component({}); } }; LM_COMP_REG_IMPL(Material_ConstantWeightMixture_RR, "material::constant_weight_mixture_rr"); class Material_ConstantWeightMixture_Marginalized final : public Material { private: struct MaterialGroup { struct Entry { Material* material; Float weight; template <typename Archive> void serialize(Archive& ar) { ar(material, weight); } }; std::vector<Entry> entries; Dist dist; template <typename Archive> void serialize(Archive& ar) { ar(entries, dist); } }; std::vector<MaterialGroup> material_groups_; Dist dist_; public: LM_SERIALIZE_IMPL(ar) { ar(material_groups_, dist_); } virtual void foreach_underlying(const ComponentVisitor& visit) override { for (auto& material_group : material_groups_) { for (auto& e : material_group.entries) { comp::visit(visit, e.material); } } } public: virtual void construct(const Json& prop) override { material_groups_.emplace_back();
group.dist.add(entry.weight); } group.dist.norm(); dist_.add(weight_sum); } dist_.norm(); } virtual ComponentSample sample_component(const ComponentSampleU& u, const PointGeometry&, Vec3) const override { const int comp = dist_.sample(u.uc[0]); const auto p = dist_.pmf(comp); return { comp, 1_f / p }; } virtual Float pdf_component(int comp, const PointGeometry&, Vec3) const override { return dist_.pmf(comp); } virtual std::optional<DirectionSample> sample_direction(const DirectionSampleU& us, const PointGeometry& geom, Vec3 wi, int comp, TransDir trans_dir) const override { const auto& group = material_groups_[comp]; const int comp_in_group = group.dist.sample(us.udc[0]); const auto& e = group.entries[comp_in_group]; const auto s = e.material->sample_direction(us, geom, wi, {}, trans_dir); if (!s) { return {}; } const auto f = eval(geom, wi, s->wo, comp, trans_dir, false); const auto p = pdf_direction(geom, wi, s->wo, comp, false); const auto C = f / p; return DirectionSample{ s->wo, C }; } virtual Vec3 reflectance(const PointGeometry& geom) const override { Vec3 sum(0_f); for (auto& group : material_groups_) { for (const auto& entry : group.entries) { sum += entry.weight * entry.material->reflectance(geom); } } return sum; } virtual Float pdf_direction(const PointGeometry& geom, Vec3 wi, Vec3 wo, int comp, bool eval_delta) const override { const auto& group = material_groups_[comp]; Float p_marginal = 0_f; for (int i = 0; i < (int)(group.entries.size()); i++) { const auto p_sel = group.dist.pmf(i); const auto p = group.entries[i].material->pdf_direction(geom, wi, wo, {}, eval_delta); p_marginal += p_sel * p; } return p_marginal; } virtual Vec3 eval(const PointGeometry& geom, Vec3 wi, Vec3 wo, int comp, TransDir trans_dir, bool eval_delta) const override { const auto& group = material_groups_[comp]; Vec3 result(0_f); for (const auto& entry : group.entries) { const auto f = entry.material->eval(geom, wi, wo, {}, trans_dir, eval_delta); result += entry.weight * f; } return result; } virtual bool is_specular_component(int comp) const override { return comp != 0; } }; LM_COMP_REG_IMPL(Material_ConstantWeightMixture_Marginalized, "material::constant_weight_mixture_marginalized"); LM_NAMESPACE_END(LM_NAMESPACE)
for (auto& entry : prop) { auto* mat = json::comp_ref<Material>(entry, "material"); const auto weight = json::value<Float>(entry, "weight"); if (mat->is_specular_component({})) { material_groups_.emplace_back(); material_groups_.back().entries.push_back({ mat, weight }); } else { material_groups_[0].entries.push_back({ mat, weight }); } } for (auto& group : material_groups_) { Float weight_sum = 0_f; for (const auto& entry : group.entries) { weight_sum += entry.weight;
random
[ { "content": "class Material_Glossy final : public Material {\n\nprivate:\n\n Vec3 Ks_; // Specular reflectance\n\n Float ax_, ay_; // Roughness (anisotropic)\n\n\n\npublic:\n\n LM_SERIALIZE_IMPL(ar) {\n\n ar(Ks_, ax_, ay_);\n\n }\n\n\n\npublic:\n\n virtual void construct(const Json& prop) override {\n\n Ks_ = json::value<Vec3>(prop, \"Ks\");\n\n ax_ = json::value<Float>(prop, \"ax\");\n\n ay_ = json::value<Float>(prop, \"ay\");\n\n }\n\n\n\nprivate:\n\n // Normal distribution of anisotropic GGX\n\n Float normal_dist(Vec3 wh, Vec3 u, Vec3 v, Vec3 n) const {\n", "file_path": "src/material/material_glossy.cpp", "rank": 2, "score": 221361.51628941984 }, { "content": "class Material_Diffuse final : public Material {\n\nprivate:\n\n Vec3 Kd_;\n\n Texture* mapKd_ = nullptr;\n\n\n\npublic:\n\n LM_SERIALIZE_IMPL(ar) {\n\n ar(Kd_, mapKd_);\n\n }\n\n\n\n virtual Component* underlying(const std::string& name) const override {\n\n if (name == \"mapKd\") {\n\n return mapKd_;\n\n }\n\n return nullptr;\n\n }\n\n\n\n virtual void foreach_underlying(const ComponentVisitor& visit) override {\n\n comp::visit(visit, mapKd_);\n\n }\n", "file_path": "src/material/material_diffuse.cpp", "rank": 3, "score": 221361.51628941984 }, { "content": "class Material_Proxy final : public Material {\n\nprivate:\n\n Material* ref_;\n\n\n\npublic:\n\n LM_SERIALIZE_IMPL(ar) {\n\n ar(ref_);\n\n }\n\n\n\n virtual void foreach_underlying(const ComponentVisitor& visit) override {\n\n comp::visit(visit, ref_);\n\n }\n\n\n\npublic:\n\n virtual void construct(const Json& prop) override {\n\n ref_ = json::comp_ref<Material>(prop, \"ref\");\n\n }\n\n\n\n virtual ComponentSample sample_component(const ComponentSampleU& u, const PointGeometry& geom, Vec3 wi) const override {\n\n return ref_->sample_component(u, geom, wi);\n", "file_path": "src/material/material_proxy.cpp", "rank": 4, "score": 221361.51628941984 }, { "content": "class Material_Mask final : public Material {\n\npublic:\n\n virtual ComponentSample sample_component(const ComponentSampleU&, const PointGeometry&, Vec3) const override {\n\n return { 0, 1_f };\n\n }\n\n\n\n virtual Float pdf_component(int, const PointGeometry&, Vec3) const override {\n\n return 1_f;\n\n }\n\n\n\n virtual std::optional<DirectionSample> sample_direction(const DirectionSampleU&, const PointGeometry&, Vec3 wi, int, TransDir) const override {\n\n return DirectionSample{\n\n -wi,\n\n Vec3(1_f)\n\n };\n\n }\n\n\n\n virtual Float pdf_direction(const PointGeometry&, Vec3, Vec3, int, bool eval_delta) const override {\n\n return eval_delta ? 0_f : 1_f;\n\n }\n", "file_path": "src/material/material_mask.cpp", "rank": 5, "score": 221361.51628941984 }, { "content": "class Material_Mirror final : public Material {\n\npublic:\n\n virtual ComponentSample sample_component(const ComponentSampleU&, const PointGeometry&, Vec3) const override {\n\n return { 0, 1_f };\n\n }\n\n\n\n virtual Float pdf_component(int, const PointGeometry&, Vec3) const override {\n\n return 1_f;\n\n }\n\n\n\n virtual std::optional<DirectionSample> sample_direction(const DirectionSampleU&, const PointGeometry& geom, Vec3 wi, int, TransDir) const override {\n\n return DirectionSample{\n\n math::reflection(wi, geom.n),\n\n Vec3(1_f)\n\n };\n\n }\n\n\n\n virtual Float pdf_direction(const PointGeometry&, Vec3, Vec3, int, bool eval_delta) const override {\n\n return eval_delta ? 0_f : 1_f;\n\n }\n", "file_path": "src/material/material_mirror.cpp", "rank": 6, "score": 221361.51628941984 }, { "content": "class Material_Glass final : public Material {\n\nprivate:\n\n Float Ni_;\n\n\n\nprivate:\n\n #if MATERIAL_GLASS_USE_COMPONENT_SAMPLING\n\n enum {\n\n Comp_Reflection = 0,\n\n Comp_Refraction = 1\n\n };\n\n #endif\n\n\n\npublic:\n\n LM_SERIALIZE_IMPL(ar) {\n\n ar(Ni_);\n\n }\n\n\n\nprivate:\n\n // Energy compensation for importance transport\n\n Float refr_correction(Float eta, TransDir trans_dir) const {\n", "file_path": "src/material/material_glass.cpp", "rank": 7, "score": 221361.51628941984 }, { "content": " class Material_Py final : public Material {\n\n virtual void construct(const Json& prop) override {\n\n PYBIND11_OVERLOAD(void, Material, construct, prop);\n\n }\n\n virtual ComponentSample sample_component(const ComponentSampleU& u, const PointGeometry& geom, Vec3 wi) const override {\n\n PYBIND11_OVERLOAD_PURE(ComponentSample, Material, sample_component, u, geom, wi);\n\n }\n\n virtual Float pdf_component(int comp, const PointGeometry& geom, Vec3 wi) const override {\n\n PYBIND11_OVERLOAD_PURE(Float, Material, pdf_component, comp, geom, wi);\n\n }\n\n virtual std::optional<DirectionSample> sample_direction(const DirectionSampleU& u, const PointGeometry& geom, Vec3 wi, int comp, TransDir trans_dir) const override {\n\n PYBIND11_OVERLOAD_PURE(std::optional<DirectionSample>, Material, sample_direction, u, geom, wi, comp, trans_dir);\n\n }\n\n virtual Float pdf_direction(const PointGeometry& geom, Vec3 wi, Vec3 wo, int comp, bool eval_delta) const override {\n\n PYBIND11_OVERLOAD_PURE(Float, Material, pdf_direction, geom, wi, wo, comp, eval_delta);\n\n }\n\n virtual Vec3 eval(const PointGeometry& geom, Vec3 wi, Vec3 wo, int comp, TransDir trans_dir, bool eval_delta) const override {\n\n PYBIND11_OVERLOAD_PURE(Vec3, Material, eval, geom, wi, wo, comp, trans_dir, eval_delta);\n\n }\n\n virtual bool is_specular_component(int comp) const override {\n", "file_path": "src/pylm.cpp", "rank": 8, "score": 221230.05681632698 }, { "content": "class Material : public Component {\n\npublic:\n", "file_path": "include/lm/material.h", "rank": 9, "score": 211902.91866271792 }, { "content": "class OutputArchive final : public cereal::OutputArchive<OutputArchive, cereal::AllowEmptyClassElision> {\n\nprivate:\n\n // Locator of the root component\n\n std::string root_loc_;\n\n cereal::PortableBinaryOutputArchive archive_; \n\n\n\npublic:\n\n OutputArchive(std::ostream& stream)\n\n : OutputArchive(stream, \"\")\n\n {}\n\n\n\n OutputArchive(std::ostream& stream, const std::string& root_loc)\n\n : cereal::OutputArchive<OutputArchive, cereal::AllowEmptyClassElision>(this)\n\n , archive_(stream)\n\n , root_loc_(root_loc)\n\n {}\n\n\n\n template <std::size_t DataSize> inline\n\n void saveBinary(const void* data, std::size_t size) {\n\n archive_.saveBinary<DataSize>(data, size);\n", "file_path": "include/lm/serialtype.h", "rank": 10, "score": 206936.45229707402 }, { "content": "class InputArchive final : public cereal::InputArchive<InputArchive, cereal::AllowEmptyClassElision> {\n\nprivate:\n\n // Locator of the root component\n\n std::string root_loc_;\n\n cereal::PortableBinaryInputArchive archive_;\n\n\n\n // Pairs of weak pointer and locators to be recovered later\n\n struct WeakptrAddressLocPair {\n\n std::uintptr_t address;\n\n std::string loc;\n\n };\n\n std::vector<WeakptrAddressLocPair> weakptr_loc_pairs_;\n\n\n\npublic:\n\n InputArchive(std::istream& stream)\n\n : InputArchive(stream, \"\")\n\n {}\n\n\n\n InputArchive(std::istream& stream, const std::string& root_loc)\n\n : cereal::InputArchive<InputArchive, cereal::AllowEmptyClassElision>(this)\n", "file_path": "include/lm/serialtype.h", "rank": 11, "score": 206936.45229707402 }, { "content": "class Material_Mixture_WavefrontObj final : public Material {\n\nprivate:\n\n Component::Ptr<Material> diffuse_;\n\n Component::Ptr<Material> glossy_;\n\n Texture* mask_tex_ = nullptr;\n\n\n\npublic:\n\n LM_SERIALIZE_IMPL(ar) {\n\n ar(diffuse_, glossy_, mask_tex_);\n\n }\n\n\n\n virtual void foreach_underlying(const ComponentVisitor& visit) override {\n\n comp::visit(visit, diffuse_);\n\n comp::visit(visit, glossy_);\n\n comp::visit(visit, mask_tex_);\n\n }\n\n\n\n virtual Component* underlying(const std::string& name) const override {\n\n if (name == \"diffuse\")\n\n return diffuse_.get();\n", "file_path": "src/model/model_wavefrontobj.cpp", "rank": 12, "score": 201967.0919684957 }, { "content": "class RngImpl<float> : public RngImplBase {\n\npublic:\n\n RngImpl() = default;\n\n RngImpl(int seed) : RngImplBase(seed) {}\n\n\n\n /*\n\n According to the C++ standard std::uniform_real_distribution::operator()\n\n always returns non-inclusive range. For instance, in our case u()\n\n should return values in [0,1). Yet due to the rounding issue\n\n the function might return exact value of 1.f when std::uniform_real_distribution is\n\n specialized for float. To avoid this problem, we generate\n\n the number with double then round it toward negative infinity\n\n rather than generating the number with float directly.\n\n cf. https://stackoverflow.com/questions/25668600/is-1-0-a-valid-output-from-stdgenerate-canonical\n\n */\n\n float u() {\n\n const double rd = RngImplBase::u();\n\n float rf = static_cast<float>(rd);\n\n if (rf > rd) {\n\n rf = std::nextafter(rf, -std::numeric_limits<float>::infinity());\n", "file_path": "include/lm/math.h", "rank": 13, "score": 198024.05902275594 }, { "content": "class Light_EnvConst final : public Light {\n\nprivate:\n\n Vec3 Le_;\n\n SphereBound sphere_bound_;\n\n \n\npublic:\n\n LM_SERIALIZE_IMPL(ar) {\n\n ar(Le_, sphere_bound_);\n\n }\n\n \n\npublic:\n\n virtual void construct(const Json& prop) override {\n\n Le_ = json::value<Vec3>(prop, \"Le\");\n\n }\n\n\n\n // --------------------------------------------------------------------------------------------\n\n\n\n virtual void set_scene_bound(const Bound& bound) {\n\n // Compute the bounding sphere of the scene.\n\n // Although it is inefficient, currently we just use a convervative bound of AABB.\n", "file_path": "src/light/light_envconst.cpp", "rank": 14, "score": 194271.52836155245 }, { "content": "struct Dist {\n\n std::vector<Float> c{ 0_f }; // CDF\n\n\n\n //! \\cond\n\n template <typename Archive>\n\n void serialize(Archive& ar) {\n\n ar(c);\n\n }\n\n //! \\endcond\n\n\n\n /*!\n\n \\brief Clear internal state.\n\n */\n\n void clear() {\n\n c.clear();\n\n c.push_back(0_f);\n\n }\n\n\n\n /*!\n\n \\brief Add a value to the distribution.\n", "file_path": "include/lm/math.h", "rank": 15, "score": 191903.6647739696 }, { "content": "struct TestPluginWithTemplate_ final : public TestPluginWithTemplate<T> {\n\n virtual T f() const override {\n\n if constexpr (std::is_same_v<T, int>) {\n\n return 1;\n\n }\n\n if constexpr (std::is_same_v<T, double>) {\n\n return 2;\n\n }\n\n }\n\n};\n\n\n\nLM_COMP_REG_IMPL(TestPluginWithTemplate_<int>, \"testplugin::template\");\n\nLM_COMP_REG_IMPL(TestPluginWithTemplate_<double>, \"testplugin::template\");\n\n\n\n// ------------------------------------------------------------------------------------------------\n\n\n\nLM_NAMESPACE_END(lmtest)\n", "file_path": "test/test_interface_impl.cpp", "rank": 16, "score": 189187.26701607864 }, { "content": "class Scene_ final : public Scene {\n\nprivate:\n\n Accel* accel_; // Acceleration structure\n\n std::vector<SceneNode> nodes_; // Scene nodes (index 0: root node)\n\n std::optional<int> camera_; // Camera index\n\n std::vector<LightPrimitiveIndex> lights_; // Primitive node indices of lights and global transforms\n\n std::unordered_map<int, int> light_indices_map_; // Map from node indices to light indices.\n\n std::optional<int> env_light_; // Environment light index\n\n std::optional<int> medium_; // Medium index\n\n\n\npublic:\n\n LM_SERIALIZE_IMPL(ar) {\n\n ar(accel_, nodes_, camera_, lights_, light_indices_map_, env_light_);\n\n }\n\n\n\n virtual void foreach_underlying(const ComponentVisitor& visit) override {\n\n comp::visit(visit, accel_);\n\n for (auto& node : nodes_) {\n\n if (node.type == SceneNodeType::Primitive) {\n\n comp::visit(visit, node.primitive.mesh);\n", "file_path": "src/scene.cpp", "rank": 17, "score": 179327.2270395385 }, { "content": " class Light_Py final : public Light {\n\n virtual void construct(const Json& prop) override {\n\n PYBIND11_OVERLOAD(void, Light, construct, prop);\n\n }\n\n // ----------------------------------------------------------------------------------------\n\n virtual std::optional<RaySample> sample_ray(const RaySampleU& u, const Transform& transform) const override {\n\n PYBIND11_OVERLOAD_PURE(std::optional<RaySample>, Light, sample_ray, u, transform);\n\n }\n\n virtual Float pdf_ray(const PointGeometry& geom, Vec3 wo, const Transform& transform, bool eval_delta) const override {\n\n PYBIND11_OVERLOAD_PURE(Float, Light, pdf_ray, geom, wo, transform, eval_delta);\n\n }\n\n // ----------------------------------------------------------------------------------------\n\n virtual std::optional<DirectionSample> sample_direction(const DirectionSampleU& u, const PointGeometry& geom) const override {\n\n PYBIND11_OVERLOAD_PURE(std::optional<DirectionSample>, Light, sample_direction, u, geom);\n\n }\n\n virtual Float pdf_direction(const PointGeometry& geom, Vec3 wo) const override {\n\n PYBIND11_OVERLOAD_PURE(Float, Light, pdf_direction, geom, wo);\n\n }\n\n // ----------------------------------------------------------------------------------------\n\n virtual std::optional<PositionSample> sample_position(const PositionSampleU& u, const Transform& transform) const override {\n", "file_path": "src/pylm.cpp", "rank": 18, "score": 174889.86827612386 }, { "content": " class Scene_Py final : public Scene {\n\n virtual void construct(const Json& prop) override {\n\n PYBIND11_OVERLOAD(void, Scene, construct, prop);\n\n }\n\n // ----------------------------------------------------------------------------------------\n\n virtual void reset() override {\n\n PYBIND11_OVERLOAD_PURE(void, Scene, reset);\n\n }\n\n // ----------------------------------------------------------------------------------------\n\n virtual int root_node() override {\n\n PYBIND11_OVERLOAD_PURE(int, Scene, root_node);\n\n }\n\n virtual int create_primitive_node(const Json& prop) override {\n\n PYBIND11_OVERLOAD_PURE(int, Scene, create_primitive_node, prop);\n\n }\n\n virtual int create_group_node(Mat4 transform) override {\n\n PYBIND11_OVERLOAD_PURE(int, Scene, create_group_node, transform);\n\n }\n\n virtual int create_instance_group_node() override {\n\n PYBIND11_OVERLOAD_PURE(int, Scene, create_instance_group_node);\n", "file_path": "src/pylm.cpp", "rank": 19, "score": 174889.86827612386 }, { "content": " class Phase_Py final : public Phase {\n\n virtual void construct(const Json& prop) override {\n\n PYBIND11_OVERLOAD(void, Phase, construct, prop);\n\n }\n\n virtual std::optional<DirectionSample> sample_direction(const DirectionSampleU& u, const PointGeometry& geom, Vec3 wi) const override {\n\n PYBIND11_OVERLOAD_PURE(std::optional<DirectionSample>, Phase, sample_direction, u, geom, wi);\n\n }\n\n virtual Float pdf_direction(const PointGeometry& geom, Vec3 wi, Vec3 wo) const override {\n\n PYBIND11_OVERLOAD_PURE(Float, Phase, pdf_direction, geom, wi, wo);\n\n }\n\n virtual Vec3 eval(const PointGeometry& geom, Vec3 wi, Vec3 wo) const override {\n\n PYBIND11_OVERLOAD_PURE(Vec3, Phase, eval, geom, wi, wo);\n\n }\n\n };\n\n pybind11::class_<Phase, Phase_Py, Component, Component::Ptr<Phase>>(m, \"Phase\")\n\n .def(pybind11::init<>())\n\n .def(\"sample_direction\", &Phase::sample_direction)\n\n .def(\"pdf_direction\", &Phase::pdf_direction)\n\n .def(\"eval\", &Phase::eval)\n\n .PYLM_DEF_COMP_BIND(Phase);\n", "file_path": "src/pylm.cpp", "rank": 20, "score": 174889.86827612386 }, { "content": " class Accel_Py final : public Accel {\n\n virtual void construct(const Json& prop) override {\n\n PYBIND11_OVERLOAD(void, Accel, construct, prop);\n\n }\n\n virtual void build(const Scene& scene) override {\n\n PYBIND11_OVERLOAD_PURE(void, Accel, build, scene);\n\n }\n\n virtual std::optional<Hit> intersect(Ray ray, Float tmin, Float tmax) const override {\n\n PYBIND11_OVERLOAD_PURE(std::optional<Hit>, Accel, intersect, ray, tmin, tmax);\n\n }\n\n };\n\n pybind11::class_<Accel, Accel_Py, Component, Component::Ptr<Accel>>(m, \"Accel\")\n\n .def(pybind11::init<>())\n\n .def(\"build\", &Accel::build)\n\n .def(\"intersect\", &Accel::intersect)\n\n .PYLM_DEF_COMP_BIND(Accel);\n\n}\n\n\n\n// ------------------------------------------------------------------------------------------------\n\n\n\n// Bind renderer.h\n\nstatic void bind_renderer(pybind11::module& m) {\n", "file_path": "src/pylm.cpp", "rank": 21, "score": 174889.86827612386 }, { "content": " class Volume_Py final : public Volume {\n\n virtual void construct(const Json& prop) override {\n\n PYBIND11_OVERLOAD(void, Volume, construct, prop);\n\n }\n\n virtual Bound bound() const override {\n\n PYBIND11_OVERLOAD_PURE(Bound, Volume, bound);\n\n }\n\n virtual bool has_scalar() const override {\n\n PYBIND11_OVERLOAD_PURE(bool, Volume, has_scalar);\n\n }\n\n virtual Float max_scalar() const override {\n\n PYBIND11_OVERLOAD_PURE(Float, Volume, has_scalar);\n\n }\n\n virtual Float eval_scalar(Vec3 p) const override {\n\n PYBIND11_OVERLOAD(Float, Volume, eval_scalar, p);\n\n }\n\n virtual bool has_color() const override {\n\n PYBIND11_OVERLOAD_PURE(bool, Volume, has_color);\n\n }\n\n virtual Vec3 eval_color(Vec3 p) const override {\n", "file_path": "src/pylm.cpp", "rank": 22, "score": 174889.86827612386 }, { "content": " class Mesh_Py final : public Mesh {\n\n virtual void construct(const Json& prop) override {\n\n PYBIND11_OVERLOAD(void, Mesh, construct, prop);\n\n }\n\n virtual void foreach_triangle(const ProcessTriangleFunc& process_triangle) const override {\n\n PYBIND11_OVERLOAD_PURE(void, Mesh, foreach_triangle, process_triangle);\n\n }\n\n virtual Tri triangle_at(int face) const override {\n\n PYBIND11_OVERLOAD_PURE(Tri, Mesh, triangle_at, face);\n\n }\n\n virtual InterpolatedPoint surface_point(int face, Vec2 uv) const override {\n\n PYBIND11_OVERLOAD_PURE(InterpolatedPoint, Mesh, surface_point, face, uv);\n\n }\n\n virtual int num_triangles() const override {\n\n PYBIND11_OVERLOAD_PURE(int, Mesh, num_triangles);\n\n }\n\n };\n\n pybind11::class_<Mesh, Mesh_Py, Component, Component::Ptr<Mesh>>(m, \"Mesh\")\n\n .def(pybind11::init<>())\n\n .def(\"foreach_triangle\", &Mesh::foreach_triangle)\n", "file_path": "src/pylm.cpp", "rank": 23, "score": 174889.86827612386 }, { "content": " class Renderer_Py final : public Renderer {\n\n PYLM_SERIALIZE_IMPL(Renderer);\n\n virtual void construct(const Json& prop) override {\n\n PYBIND11_OVERLOAD(void, Renderer, construct, prop);\n\n }\n\n virtual Json render() const override {\n\n PYBIND11_OVERLOAD_PURE(Json, Renderer, render);\n\n }\n\n };\n\n pybind11::class_<Renderer, Renderer_Py, Component, Component::Ptr<Renderer>>(m, \"Renderer\")\n\n .def(pybind11::init<>())\n\n .def(\"render\", &Renderer::render, pybind11::call_guard<pybind11::gil_scoped_release>())\n\n .PYLM_DEF_COMP_BIND(Renderer);\n\n}\n\n\n\n// ------------------------------------------------------------------------------------------------\n\n\n\n// Bind texture.h\n\nstatic void bind_texture(pybind11::module& m) {\n\n pybind11::class_<TextureSize>(m, \"TextureSize\")\n\n .def_readwrite(\"w\", &TextureSize::w)\n\n .def_readwrite(\"h\", &TextureSize::h);\n", "file_path": "src/pylm.cpp", "rank": 24, "score": 174889.86827612386 }, { "content": " class Component_Py final : public Component {\n\n public:\n\n PYLM_SERIALIZE_IMPL(Component);\n\n virtual void construct(const Json& prop) override {\n\n PYBIND11_OVERLOAD(void, Component, construct, prop);\n\n }\n\n };\n\n using make_loc_func_ptr = const std::string(Component::*)(const std::string&) const;\n\n pybind11::class_<Component, Component_Py, Component::Ptr<Component>>(m, \"Component\")\n\n .def(pybind11::init<>())\n\n .def(\"key\", &Component::key)\n\n .def(\"loc\", &Component::loc)\n\n .def(\"make_loc\", (make_loc_func_ptr)&Component::make_loc)\n\n .def(\"parentLoc\", &Component::parent_loc)\n\n .def(\"construct\", &Component::construct)\n\n .def(\"underlying\", &Component::underlying, pybind11::return_value_policy::reference)\n\n .def(\"underlying_value\", &Component::underlying_value, \"query\"_a = \"\")\n\n .def(\"save\", [](Component* self) -> pybind11::bytes {\n\n std::ostringstream os;\n\n {\n", "file_path": "src/pylm.cpp", "rank": 25, "score": 174889.86827612386 }, { "content": " class Model_Py final : public Model {\n\n virtual void construct(const Json& prop) override {\n\n PYBIND11_OVERLOAD(void, Model, construct, prop);\n\n }\n\n virtual void create_primitives(const CreatePrimitiveFunc& create_primitive) const override {\n\n PYBIND11_OVERLOAD_PURE(void, Model, create_primitives, create_primitive)\n\n }\n\n virtual void foreach_node(const VisitNodeFuncType& visit) const override {\n\n PYBIND11_OVERLOAD_PURE(void, Model, foreach_node, visit);\n\n }\n\n };\n\n pybind11::class_<Model, Model_Py, Component, Component::Ptr<Model>>(m, \"Model\")\n\n .def(pybind11::init<>())\n\n .def(\"create_primitives\", &Model::create_primitives)\n\n .def(\"foreach_node\", &Model::foreach_node)\n\n .PYLM_DEF_COMP_BIND(Model);\n\n}\n\n\n\n// ------------------------------------------------------------------------------------------------\n\n\n", "file_path": "src/pylm.cpp", "rank": 26, "score": 174889.86827612386 }, { "content": " class Camera_Py final : public Camera {\n\n virtual void construct(const Json& prop) override {\n\n PYBIND11_OVERLOAD(void, Camera, construct, prop);\n\n }\n\n // ----------------------------------------------------------------------------------------\n\n virtual void set_aspect_ratio(Float aspect) override {\n\n PYBIND11_OVERLOAD_PURE(void, Camera, set_aspect_ratio, aspect);\n\n }\n\n // ----------------------------------------------------------------------------------------\n\n virtual Mat4 view_matrix() const override {\n\n PYBIND11_OVERLOAD_PURE(Mat4, Camera, view_matrix);\n\n }\n\n virtual Mat4 projection_matrix() const override {\n\n PYBIND11_OVERLOAD_PURE(Mat4, Camera, projection_matrix);\n\n }\n\n // ----------------------------------------------------------------------------------------\n\n virtual Ray primary_ray(Vec2 rp) const override {\n\n PYBIND11_OVERLOAD_PURE(Ray, Camera, primary_ray, rp);\n\n }\n\n virtual std::optional<RaySample> sample_ray(const RaySampleU& u) const override {\n", "file_path": "src/pylm.cpp", "rank": 27, "score": 174889.86827612386 }, { "content": " class Medium_Py final : public Medium {\n\n virtual void construct(const Json& prop) override {\n\n PYBIND11_OVERLOAD(void, Medium, construct, prop);\n\n }\n\n virtual std::optional<DistanceSample> sample_distance(Rng& rng, Ray ray, Float tmin, Float tmax) const override {\n\n PYBIND11_OVERLOAD_PURE(std::optional<DistanceSample>, Medium, sample_distance, rng, ray, tmin, tmax);\n\n }\n\n virtual Vec3 eval_transmittance(Rng& rng, Ray ray, Float tmin, Float tmax) const override {\n\n PYBIND11_OVERLOAD_PURE(Vec3, Medium, eval_transmittance, rng, ray, tmin, tmax);\n\n }\n\n virtual bool is_emitter() const override {\n\n PYBIND11_OVERLOAD_PURE(bool, Medium, is_emitter);\n\n }\n\n virtual const Phase* phase() const override {\n\n PYBIND11_OVERLOAD_PURE(const Phase*, Medium, phase);\n\n }\n\n };\n\n pybind11::class_<Medium, Medium_Py, Component, Component::Ptr<Medium>>(m, \"Medium\")\n\n .def(pybind11::init<>())\n\n .def(\"sample_distance\", &Medium::sample_distance)\n\n .def(\"eval_transmittance\", &Medium::eval_transmittance)\n\n .def(\"is_emitter\", &Medium::is_emitter)\n\n .def(\"phase\", &Medium::phase, pybind11::return_value_policy::reference)\n\n .PYLM_DEF_COMP_BIND(Medium);\n\n}\n\n\n\n// Bind volume.h\n\nstatic void bind_volume(pybind11::module& m) {\n", "file_path": "src/pylm.cpp", "rank": 28, "score": 174889.86827612386 }, { "content": " // Film\n\n class Film_Py final : public Film {\n\n public:\n\n virtual void construct(const Json& prop) override {\n\n PYBIND11_OVERLOAD(void, Film, construct, prop);\n\n }\n\n virtual FilmSize size() const override {\n\n PYBIND11_OVERLOAD_PURE(FilmSize, Film, size);\n\n }\n\n virtual long long num_pixels() const override {\n\n PYBIND11_OVERLOAD_PURE(long long, Film, num_pixels);\n\n }\n\n virtual void set_pixel(int x, int y, Vec3 v) override {\n\n PYBIND11_OVERLOAD_PURE(void, Film, set_pixel, x, y, v);\n\n }\n\n virtual bool save(const std::string& outpath) const override {\n\n PYBIND11_OVERLOAD_PURE(bool, Film, save, outpath);\n\n }\n\n virtual FilmBuffer buffer() override {\n\n PYBIND11_OVERLOAD_PURE(FilmBuffer, Film, buffer);\n\n }\n", "file_path": "src/pylm.cpp", "rank": 29, "score": 174889.86827612386 }, { "content": " class Texture_Py final : public Texture {\n\n virtual void construct(const Json& prop) override {\n\n PYBIND11_OVERLOAD(void, Texture, construct, prop);\n\n }\n\n virtual TextureSize size() const override {\n\n PYBIND11_OVERLOAD_PURE(TextureSize, Texture, size);\n\n }\n\n virtual Vec3 eval(Vec2 t) const override {\n\n PYBIND11_OVERLOAD_PURE(Vec3, Texture, eval, t);\n\n }\n\n virtual Vec3 eval_by_pixel_coords(int x, int y) const override {\n\n PYBIND11_OVERLOAD_PURE(Vec3, Texture, eval_by_pixel_coords, x, y);\n\n }\n\n };\n\n pybind11::class_<Texture, Texture_Py, Component, Component::Ptr<Texture>>(m, \"Texture\")\n\n .def(pybind11::init<>())\n\n .def(\"size\", &Texture::size)\n\n .def(\"eval\", &Texture::eval)\n\n .def(\"eval_by_pixel_coords\", &Texture::eval_by_pixel_coords)\n\n .PYLM_DEF_COMP_BIND(Texture);\n", "file_path": "src/pylm.cpp", "rank": 30, "score": 174889.86827612386 }, { "content": "// Simple ambient occlusion renderer\n\nclass Renderer_AO final : public Renderer {\n\nprivate:\n\n Scene* scene_;\n\n Film* film_;\n\n long long spp_;\n\n int rng_seed_ = 42;\n\n\n\npublic:\n\n virtual void construct(const Json& prop) override {\n\n scene_ = json::comp_ref<Scene>(prop, \"scene\");\n\n film_ = json::comp_ref<Film>(prop, \"output\");\n\n spp_ = json::value<long long>(prop, \"spp\");\n\n }\n\n\n\n virtual Json render() const override {\n\n const auto size = film_->size();\n\n parallel::foreach(size.w*size.h, [&](long long index, int threadId) -> void {\n\n thread_local Rng rng(rng_seed_ + threadId);\n\n const int x = int(index % size.w);\n\n const int y = int(index / size.w);\n", "file_path": "example/custom_renderer.cpp", "rank": 31, "score": 170806.7565296846 }, { "content": "class Renderer_AO final : public Renderer {\n\nprivate:\n\n Scene* scene_;\n\n Film* film_;\n\n long long spp_;\n\n int rng_seed_ = 42;\n\n\n\npublic:\n\n virtual void construct(const Json& prop) override {\n\n scene_ = json::comp_ref<Scene>(prop, \"scene\");\n\n film_ = json::comp_ref<Film>(prop, \"output\");\n\n spp_ = json::value<long long>(prop, \"spp\");\n\n }\n\n\n\n virtual Json render() const override {\n\n const auto size = film_->size();\n\n parallel::foreach(size.w*size.h, [&](long long index, int threadId) -> void {\n\n thread_local Rng rng(rng_seed_ + threadId);\n\n const int x = int(index % size.w);\n\n const int y = int(index / size.w);\n", "file_path": "functest/renderer_ao.cpp", "rank": 32, "score": 170806.7565296846 }, { "content": "class AssetGroup_ final : public AssetGroup {\n\nprivate:\n\n std::vector<Ptr<Component>> assets_;\n\n std::unordered_map<std::string, int> asset_index_map_;\n\n\n\npublic:\n\n LM_SERIALIZE_IMPL(ar) {\n\n ar(asset_index_map_, assets_);\n\n }\n\n\n\n virtual void foreach_underlying(const ComponentVisitor& visitor) override {\n\n for (auto& asset : assets_) {\n\n comp::visit(visitor, asset);\n\n }\n\n }\n\n\n\n virtual Component* underlying(const std::string& name) const override {\n\n auto it = asset_index_map_.find(name);\n\n if (it == asset_index_map_.end()) {\n\n LM_ERROR(\"Invalid asset name [name='{}']\", name);\n", "file_path": "src/assetgroup.cpp", "rank": 33, "score": 170806.7565296846 }, { "content": " //! Light transport direction.\n\n enum class TransDir {\n\n LE, //!< Light to camera.\n\n EL //!< Camera to light.\n\n };\n\n\n\n // --------------------------------------------------------------------------------------------\n\n\n\n //! Result of component sampling.\n\n struct ComponentSample {\n\n int comp;\n\n Float weight;\n\n };\n\n\n\n //! Random number input for component sampling.\n\n struct ComponentSampleU {\n\n Vec2 uc;\n\n };\n\n\n\n /*!\n\n \\brief Component sampling.\n", "file_path": "include/lm/material.h", "rank": 34, "score": 170755.93558986537 }, { "content": "class Medium_Heterogeneous final : public Medium {\n\nprivate:\n\n const Volume* volume_density_; // Density volume. density := \\mu_t = \\mu_a + \\mu_s\n\n const Volume* volme_albedo_;\t// Albedo volume. albedo := \\mu_s / \\mu_t\n\n const Phase* phase_; // Underlying phase function.\n\n\n\npublic:\n\n LM_SERIALIZE_IMPL(ar) {\n\n ar(volume_density_, volme_albedo_, phase_);\n\n }\n\n\n\npublic:\n\n virtual void construct(const Json& prop) override {\n\n volume_density_ = json::comp_ref<Volume>(prop, \"volume_density\");\n\n volme_albedo_ = json::comp_ref<Volume>(prop, \"volume_albedo\");\n\n phase_ = json::comp_ref<Phase>(prop, \"phase\");\n\n }\n\n\n\n virtual std::optional<DistanceSample> sample_distance(Rng& rng, Ray ray, Float tmin, Float tmax) const override {\n\n // Compute overlapping range between the ray and the volume\n", "file_path": "src/medium/medium_heterogeneous.cpp", "rank": 35, "score": 167037.0992665274 }, { "content": "class Renderer_Blank final : public Renderer {\n\nprivate:\n\n Vec3 color_;\n\n Film* film_;\n\n\n\npublic:\n\n LM_SERIALIZE_IMPL(ar) {\n\n ar(color_, film_);\n\n }\n\n\n\n virtual void foreach_underlying(const ComponentVisitor& visit) override {\n\n comp::visit(visit, film_);\n\n }\n\n\n\npublic:\n\n virtual void construct(const Json& prop) override {\n\n color_ = json::value<Vec3>(prop, \"color\");\n\n film_ = json::comp_ref<Film>(prop, \"output\");\n\n }\n\n\n", "file_path": "src/renderer/renderer_blank.cpp", "rank": 36, "score": 167037.0992665274 }, { "content": "class Camera_Pinhole final : public Camera {\n\nprivate:\n\n Vec3 position_; // Camera position\n\n Vec3 center_; // Lookat position\n\n Vec3 up_; // Up vector\n\n\n\n Vec3 u_, v_, w_; // Basis for camera coordinates\n\n Float vfov_; // Vertical field of view\n\n Float tf_; // Half of the screen height at 1 unit forward from the position\n\n\n\n Float aspect_; // Aspect raio (height / width)\n\n\n\npublic:\n\n LM_SERIALIZE_IMPL(ar) {\n\n ar(position_, center_, up_, u_, v_, w_, vfov_, tf_, aspect_);\n\n }\n\n\n\npublic:\n\n virtual Json underlying_value(const std::string&) const override {\n\n return {\n", "file_path": "src/camera/camera_pinhole.cpp", "rank": 37, "score": 167037.0992665274 }, { "content": " class ProgressContext_Py final : public ProgressContext {\n\n virtual void construct(const Json& prop) override {\n\n pybind11::gil_scoped_acquire acquire;\n\n PYBIND11_OVERLOAD(void, ProgressContext, construct, prop);\n\n }\n\n virtual void start(progress::ProgressMode mode, long long total, double totalTime) override {\n\n pybind11::gil_scoped_acquire acquire;\n\n PYBIND11_OVERLOAD_PURE(void, ProgressContext, start, mode, total, totalTime);\n\n }\n\n virtual void end() override {\n\n pybind11::gil_scoped_acquire acquire;\n\n PYBIND11_OVERLOAD_PURE(void, ProgressContext, end);\n\n }\n\n virtual void update(long long processed) override {\n\n pybind11::gil_scoped_acquire acquire;\n\n PYBIND11_OVERLOAD_PURE(void, ProgressContext, update, processed);\n\n }\n\n virtual void update_time(Float elapsed) override {\n\n pybind11::gil_scoped_acquire acquire;\n\n PYBIND11_OVERLOAD_PURE(void, ProgressContext, update_time, elapsed);\n", "file_path": "src/pylm.cpp", "rank": 38, "score": 167037.0992665274 }, { "content": "class Renderer_Raycast final : public Renderer {\n\nprivate:\n\n Scene* scene_;\n\n Film* film_;\n\n Vec3 bg_color_;\n\n bool use_constant_color_;\n\n bool visualize_normal_;\n\n std::optional<Vec3> color_;\n\n Component::Ptr<scheduler::Scheduler> sched_;\n\n\n\npublic:\n\n LM_SERIALIZE_IMPL(ar) {\n\n ar(scene_, film_, bg_color_, use_constant_color_, visualize_normal_, sched_);\n\n }\n\n\n\n virtual void foreach_underlying(const ComponentVisitor& visit) override {\n\n comp::visit(visit, scene_);\n\n comp::visit(visit, film_);\n\n comp::visit(visit, sched_);\n\n }\n", "file_path": "src/renderer/renderer_raycast.cpp", "rank": 39, "score": 167037.0992665274 }, { "content": "class Phase_Isotropic final : public Phase {\n\npublic:\n\n virtual std::optional<DirectionSample> sample_direction(const DirectionSampleU& us, const PointGeometry& geom, Vec3) const override {\n\n LM_UNUSED(geom);\n\n assert(geom.degenerated);\n\n return DirectionSample{\n\n math::sample_uniform_sphere(us.ud),\n\n Vec3(1_f)\n\n };\n\n }\n\n\n\n virtual Float pdf_direction(const PointGeometry& geom, Vec3, Vec3) const override {\n\n LM_UNUSED(geom);\n\n assert(geom.degenerated);\n\n return math::pdf_uniform_sphere();\n\n }\n\n\n\n virtual Vec3 eval(const PointGeometry&, Vec3, Vec3) const override {\n\n // Normalization constant = 1/(4*pi)\n\n return Vec3(math::pdf_uniform_sphere());\n\n }\n\n};\n\n\n\nLM_COMP_REG_IMPL(Phase_Isotropic, \"phase::isotropic\");\n\n\n\nLM_NAMESPACE_END(LM_NAMESPACE)\n", "file_path": "src/phase/phase_isotropic.cpp", "rank": 40, "score": 167037.0992665274 }, { "content": "class Light_Point final : public Light {\n\nprivate:\n\n Vec3 Le_; // Luminance\n\n Vec3 position_; // Position of the light\n\n\n\npublic:\n\n LM_SERIALIZE_IMPL(ar) {\n\n ar(Le_, position_);\n\n }\n\n\n\npublic:\n\n virtual void construct(const Json& prop) override {\n\n Le_ = json::value<Vec3>(prop, \"Le\");\n\n position_ = json::value<Vec3>(prop, \"position\");\n\n }\n\n\n\n virtual std::optional<RaySample> sample_ray(const RaySampleU& us, const Transform&) const override {\n\n const auto d = math::sample_uniform_sphere(us.ud);\n\n const auto geomL = PointGeometry::make_degenerated(position_);\n\n const auto p = math::pdf_uniform_sphere();\n", "file_path": "src/light/light_point.cpp", "rank": 41, "score": 167037.0992665274 }, { "content": " class AssetGroup_Py final : public AssetGroup {\n\n virtual void construct(const Json& prop) override {\n\n PYBIND11_OVERLOAD(void, AssetGroup, construct, prop);\n\n }\n\n virtual Component* load_asset(const std::string& name, const std::string& impl_key, const Json& prop) override {\n\n PYBIND11_OVERLOAD_PURE(Component*, AssetGroup, load_asset, name, impl_key, prop);\n\n }\n\n virtual Component* load_serialized(const std::string& name, const std::string& path) override {\n\n PYBIND11_OVERLOAD_PURE(Component*, AssetGroup, load_serialized, name, path);\n\n }\n\n };\n\n pybind11::class_<AssetGroup, AssetGroup_Py, Component, Component::Ptr<AssetGroup>>(m, \"AssetGroup\")\n\n .def(pybind11::init<>())\n\n .def(\"load_asset\", &AssetGroup::load_asset, pybind11::return_value_policy::reference)\n\n .def(\"load_serialized\", &AssetGroup::load_serialized, pybind11::return_value_policy::reference)\n\n .PYLM_DEF_ASSET_LOAD_MEMBER_FUNC(Mesh, mesh)\n\n .PYLM_DEF_ASSET_LOAD_MEMBER_FUNC(Texture, texture)\n\n .PYLM_DEF_ASSET_LOAD_MEMBER_FUNC(Material, material)\n\n .PYLM_DEF_ASSET_LOAD_MEMBER_FUNC(Camera, camera)\n\n .PYLM_DEF_ASSET_LOAD_MEMBER_FUNC(Light, light)\n", "file_path": "src/pylm.cpp", "rank": 42, "score": 167037.0992665274 }, { "content": "class Film_Bitmap final : public Film {\n\nprivate:\n\n int w_;\n\n int h_;\n\n int quality_;\n\n std::vector<AtomicWrapper<Vec3>> data_;\n\n std::vector<Vec3> data_temp_; // Temporary buffer for external reference\n\n\n\npublic:\n\n LM_SERIALIZE_IMPL(ar) {\n\n ar(w_, h_, quality_, data_);\n\n }\n\n\n\npublic:\n\n virtual void construct(const Json& prop) override {\n\n w_ = json::value<int>(prop, \"w\");\n\n h_ = json::value<int>(prop, \"h\");\n\n quality_ = json::value<int>(prop, \"quality\", 90);\n\n data_.assign(w_*h_, {});\n\n }\n", "file_path": "src/film/film_bitmap.cpp", "rank": 43, "score": 167037.0992665274 }, { "content": "class Texture_Bitmap final : public Texture {\n\nprivate:\n\n int w_; // Width of the image\n\n int h_; // Height of the image\n\n int c_; // Number of components\n\n std::vector<float> data_;\n\n\n\npublic:\n\n LM_SERIALIZE_IMPL(ar) {\n\n ar(w_, h_, c_, data_);\n\n }\n\n\n\npublic:\n\n virtual TextureSize size() const override {\n\n return { w_, h_ };\n\n }\n\n\n\n virtual void construct(const Json& prop) override {\n\n // Image path\n\n const std::string path = sanitize_directory_separator(json::value<std::string>(prop, \"path\"));\n", "file_path": "src/texture/texture_bitmap.cpp", "rank": 44, "score": 167037.0992665274 }, { "content": "class Light_Area final : public Light {\n\nprivate:\n\n Vec3 Ke_; // Luminance\n\n Dist dist_; // For surface sampling of area lights\n\n Float invA_; // Inverse area of area lights\n\n Mesh* mesh_; // Underlying mesh\n\n\n\npublic:\n\n LM_SERIALIZE_IMPL(ar) {\n\n ar(Ke_, dist_, invA_, mesh_);\n\n }\n\n\n\n virtual void foreach_underlying(const ComponentVisitor& visit) override {\n\n comp::visit(visit, mesh_);\n\n }\n\n\n\nprivate:\n\n Float tranformed_invA(const Transform& transform) const {\n\n // TODO: Handle degenerated axis\n\n // e.g., scaling by (.2,.2,.2) leads J=1/5^3\n", "file_path": "src/light/light_area.cpp", "rank": 45, "score": 167037.0992665274 }, { "content": " class LoggerContext_Py final : public LoggerContext {\n\n virtual void construct(const Json& prop) override {\n\n pybind11::gil_scoped_acquire acquire;\n\n PYBIND11_OVERLOAD(void, LoggerContext, construct, prop);\n\n }\n\n virtual void log(log::LogLevel level, int severity, const char* filename, int line, const char* message) override {\n\n pybind11::gil_scoped_acquire acquire;\n\n PYBIND11_OVERLOAD_PURE(void, LoggerContext, log, level, severity, filename, line, message);\n\n }\n\n virtual void update_indentation(int n) override {\n\n pybind11::gil_scoped_acquire acquire;\n\n PYBIND11_OVERLOAD_PURE(void, LoggerContext, update_indentation, n);\n\n }\n\n virtual void set_severity(int severity) override {\n\n pybind11::gil_scoped_acquire acquire;\n\n PYBIND11_OVERLOAD_PURE(void, LoggerContext, set_severity, severity);\n\n }\n\n };\n\n pybind11::class_<LoggerContext, LoggerContext_Py, Component, Component::Ptr<LoggerContext>>(sm, \"LoggerContext\")\n\n .def(pybind11::init<>())\n", "file_path": "src/pylm.cpp", "rank": 46, "score": 167037.0992665274 }, { "content": "class Accel_SAHBVH final : public Accel {\n\nprivate:\n\n std::vector<Node> nodes_; // Nodes\n\n std::vector<Tri> trs_; // Triangles\n\n std::vector<int> indices_; // Triangle indices\n\n std::vector<FlattenedPrimitiveNode> flattened_nodes_; // Flattened scene graph\n\n \n\npublic:\n\n LM_SERIALIZE_IMPL(ar) {\n\n ar(nodes_, trs_, indices_, flattened_nodes_);\n\n }\n\n\n\npublic:\n\n virtual void build(const Scene& scene) override {\n\n // Flatten the scene graph and setup triangle list\n\n LM_INFO(\"Flattening scene\");\n\n trs_.clear();\n\n flattened_nodes_.clear();\n\n scene.traverse_primitive_nodes([&](const SceneNode& node, Mat4 global_transform) {\n\n if (node.type != SceneNodeType::Primitive) {\n", "file_path": "src/accel/accel_sahbvh.cpp", "rank": 47, "score": 167037.0992665274 }, { "content": "class Texture_Constant final : public Texture {\n\nprivate:\n\n\tVec3 color_;\n\n std::optional<Float> alpha_;\n\n\n\npublic:\n\n\tLM_SERIALIZE_IMPL(ar) {\n\n\t\tar(color_);\n\n\t}\n\n\n\npublic:\n\n\tvirtual void construct(const Json& prop) override {\n\n\t\tcolor_ = json::value<Vec3>(prop, \"color\");\n\n alpha_ = json::value_or_none<Float>(prop, \"alpha\");\n\n\t}\n\n\t\n\n\tvirtual TextureSize size() const override {\n\n\t\treturn { 1,1 };\n\n\t}\n\n\n", "file_path": "src/texture/texture_constant.cpp", "rank": 48, "score": 167037.0992665274 }, { "content": "class Mesh_Raw final : public Mesh {\n\nprivate:\n\n std::vector<Vec3> ps_; // Positions\n\n std::vector<Vec3> ns_; // Normals\n\n std::vector<Vec2> ts_; // Texture coordinates\n\n std::vector<MeshFaceIndex> fs_; // Faces\n\n\n\npublic:\n\n LM_SERIALIZE_IMPL(ar) {\n\n ar(ps_, ns_, ts_, fs_);\n\n }\n\n\n\npublic:\n\n virtual void construct(const Json& prop) override {\n\n const auto& ps = prop[\"ps\"];\n\n for (int i = 0; i < ps.size(); i+=3) {\n\n ps_.push_back(Vec3(ps[i],ps[i+1],ps[i+2]));\n\n }\n\n const auto& ns = prop[\"ns\"];\n\n for (int i = 0; i < ns.size(); i+=3) {\n", "file_path": "src/mesh/mesh_raw.cpp", "rank": 49, "score": 167037.0992665274 }, { "content": "class Medium_Homogeneous final : public Medium {\n\nprivate:\n\n Float density_; // Density of volume := extinction coefficient \\mu_t\n\n Vec3 albedo_; // Albedo of volume := \\mu_s / \\mu_t\n\n Vec3 muA_; // Absorption coefficient.\n\n Vec3 muS_; // Scattering coefficient.\n\n const Phase* phase_; // Underlying phase function.\n\n Bound bound_;\n\n\n\npublic:\n\n LM_SERIALIZE_IMPL(ar) {\n\n ar(density_, muA_, muS_, phase_, bound_);\n\n }\n\n\n\npublic:\n\n virtual void construct(const Json& prop) override {\n\n density_ = json::value<Float>(prop, \"density\");\n\n albedo_ = json::value<Vec3>(prop, \"albedo\");\n\n muS_ = albedo_ * density_;\n\n muA_ = density_ - muS_;\n", "file_path": "src/medium/medium_homogeneous.cpp", "rank": 50, "score": 167037.0992665274 }, { "content": "class Light_Env final : public Light {\n\nprivate:\n\n SphereBound sphere_bound_;\n\n Component::Ptr<Texture> envmap_; // Environment map\n\n Float rot_; // Rotation of the environment map around (0,1,0)\n\n Float scale_; // Scale multilied to stored luminance\n\n Dist2 dist_; // For sampling directions\n\n\n\npublic:\n\n LM_SERIALIZE_IMPL(ar) {\n\n ar(sphere_bound_, envmap_, rot_, dist_);\n\n }\n\n\n\n virtual void foreach_underlying(const ComponentVisitor& visitor) override {\n\n comp::visit(visitor, envmap_);\n\n }\n\n\n\n virtual Component* underlying(const std::string& name) const override {\n\n if (name == \"envmap\") {\n\n return envmap_.get();\n", "file_path": "src/light/light_env.cpp", "rank": 51, "score": 167037.0992665274 }, { "content": "class Light_Directional final : public Light {\n\nprivate:\n\n SphereBound sphere_bound_;\n\n Vec3 Le_; // Luminance\n\n Vec3 direction_; // Direction of the light\n\n \n\npublic:\n\n LM_SERIALIZE_IMPL(ar) {\n\n ar(sphere_bound_, Le_, direction_);\n\n }\n\n\n\npublic:\n\n virtual void construct(const Json& prop) override {\n\n Le_ = json::value<Vec3>(prop, \"Le\");\n\n direction_ = glm::normalize(json::value<Vec3>(prop, \"direction\"));\n\n }\n\n\n\n // --------------------------------------------------------------------------------------------\n\n\n\n virtual void set_scene_bound(const Bound& bound) {\n", "file_path": "src/light/light_directional.cpp", "rank": 52, "score": 167037.0992665274 }, { "content": "struct TestPlugin_ final : public TestPlugin {\n\n virtual int f() override {\n\n return 42;\n\n }\n\n};\n\n\n\nLM_COMP_REG_IMPL(TestPlugin_, \"testplugin::default\");\n\n\n\n// ------------------------------------------------------------------------------------------------\n\n\n", "file_path": "test/test_interface_impl.cpp", "rank": 53, "score": 164786.8495404697 }, { "content": "struct TestAsset_Simple final : public TestAsset {\n\n int v = -1;\n\n\n\n virtual void construct(const lm::Json& prop) override {\n\n if (prop.count(\"v\")) {\n\n v = prop[\"v\"];\n\n }\n\n }\n\n\n\n virtual int f() const override {\n\n return v;\n\n }\n\n};\n\n\n", "file_path": "test/test_assets.cpp", "rank": 54, "score": 164786.8495404697 }, { "content": "struct TestAsset_Dependent final : public TestAsset {\n\n TestAsset* other;\n\n\n\n virtual void construct(const lm::Json& prop) override {\n\n // In this test an instance of Assets are registered as root component\n\n // thus we can access the underlying component via lm::comp::get function.\n\n LM_UNUSED(prop);\n\n other = lm::comp::get<TestAsset>(\"$.asset1\");\n\n }\n\n\n\n virtual void foreach_underlying(const ComponentVisitor& visit) override {\n\n lm::comp::visit(visit, other);\n\n }\n\n\n\n virtual int f() const override {\n\n return other->f() + 1;\n\n }\n\n};\n\n\n\nLM_COMP_REG_IMPL(TestAsset_Simple, \"testasset::simple\");\n", "file_path": "test/test_assets.cpp", "rank": 55, "score": 164786.8495404697 }, { "content": "class Accel_Embree final : public Accel {\n\nprivate:\n\n RTCDevice device_ = nullptr;\n\n RTCScene scene_ = nullptr;\n\n RTCBuildArguments settings_;\n\n RTCSceneFlags sf_;\n\n std::vector<FlattenedPrimitiveNode> flattened_nodes_;\n\n\n\npublic:\n\n\n\n virtual void construct(const Json& prop) override {\n\n settings_ = prop;\n\n sf_ = prop;\n\n\n\n //check actual values used for building\n\n Json j;\n\n j = settings_;\n\n LM_INFO(j.dump());\n\n j.clear();\n\n j = sf_;\n", "file_path": "plugin/accel_embree/accel_embree.cpp", "rank": 56, "score": 163546.13559831452 }, { "content": "class Model_WavefrontObj final : public Model {\n\nprivate:\n\n friend class Mesh_WavefrontObj;\n\n\n\nprivate:\n\n // Surface geometry\n\n OBJSurfaceGeometry geo_;\n\n\n\n // Underlying assets\n\n std::vector<Component::Ptr<Component>> assets_;\n\n std::unordered_map<std::string, int> assets_map_;\n\n\n\n // Mesh group which assocites a mesh and a material\n\n struct Group {\n\n int mesh;\n\n int material;\n\n int light;\n\n\n\n template <typename Archive>\n\n void serialize(Archive& ar) {\n", "file_path": "src/model/model_wavefrontobj.cpp", "rank": 57, "score": 163546.13559831452 }, { "content": "// Optimized BDPT\n\nclass Renderer_BDPT_Optimized final : public Renderer {\n\nprivate:\n\n Scene* scene_; // Reference to scene asset\n\n Film* film_; // Reference to film asset for output\n\n int min_verts_; // Minimum number of path vertices\n\n int max_verts_; // Maximum number of path vertices\n\n std::optional<unsigned int> seed_; // Random seed\n\n Component::Ptr<scheduler::Scheduler> sched_; // Scheduler for parallel processing\n\n\n\n #if BDPT_PER_STRATEGY_FILM\n\n // Index: (k, s)\n\n // where k = 2,..,max_verts,\n\n // s = 0,...,s\n\n mutable std::vector<std::vector<Ptr<Film>>> strategy_films_;\n\n std::unordered_map<std::string, Film*> strategy_film_name_map_;\n\n #endif\n\n\n\npublic:\n\n virtual void construct(const Json& prop) override {\n\n scene_ = json::comp_ref<Scene>(prop, \"scene\");\n", "file_path": "src/renderer/renderer_bdptopt.cpp", "rank": 58, "score": 163546.13559831452 }, { "content": "class Mesh_WavefrontObj final : public Mesh {\n\nprivate:\n\n Model_WavefrontObj* model_;\n\n OBJMeshFace fs_;\n\n\n\npublic:\n\n LM_SERIALIZE_IMPL(ar) {\n\n ar(model_, fs_);\n\n }\n\n\n\n virtual void foreach_underlying(const ComponentVisitor& visit) override {\n\n comp::visit(visit, model_);\n\n }\n\n\n\npublic:\n\n virtual void construct(const Json& prop) override {\n\n model_ = prop[\"model_\"].get<Model_WavefrontObj*>();\n\n fs_ = *prop[\"fs_\"].get<const OBJMeshFace*>();\n\n }\n\n\n", "file_path": "src/model/model_wavefrontobj.cpp", "rank": 59, "score": 163546.13559831452 }, { "content": "class Phase_HenyeyGreenstein final : public Phase {\n\nprivate:\n\n Float g_; // Asymmetry parameter in [-1,1]\n\n\n\npublic:\n\n LM_SERIALIZE_IMPL(ar) {\n\n ar(g_);\n\n }\n\n\n\n virtual void construct(const Json& prop) override {\n\n g_ = json::value<Float>(prop, \"g\");\n\n }\n\n\n\npublic:\n\n virtual std::optional<DirectionSample> sample_direction(const DirectionSampleU& us, const PointGeometry&, Vec3 wi) const override {\n\n const auto cosT = [&]() -> Float {\n\n if (std::abs(g_) < Eps) {\n\n return 1_f - 2_f*us.ud[0];\n\n }\n\n else {\n", "file_path": "src/phase/phase_hg.cpp", "rank": 60, "score": 163546.13559831452 }, { "content": "class Volume : public Component {\n\npublic:\n\n /*!\n\n \\brief Get bound of the volume.\n\n \\return Bound of the volume.\n\n */\n\n virtual Bound bound() const = 0;\n\n\n\n // --------------------------------------------------------------------------------------------\n\n\n\n /*!\n\n \\brief Check if the volume has scalar component.\n\n \\return True if the volume has scalar component.\n\n */\n\n virtual bool has_scalar() const = 0;\n\n\n\n /*!\n\n \\brief Evaluate maximum scalar value.\n\n */\n\n virtual Float max_scalar() const = 0;\n", "file_path": "include/lm/volume.h", "rank": 61, "score": 162806.9336235799 }, { "content": "class Film : public Component {\n\npublic:\n\n /*!\n\n \\brief Get size of the film.\n\n \\return Size of the film.\n\n */\n\n virtual FilmSize size() const = 0;\n\n\n\n /*!\n\n \\brief Get the number of pixels.\n\n */\n\n virtual long long num_pixels() const = 0;\n\n\n\n /*!\n\n \\brief Set pixel value.\n\n \\param x x coordinate of the film.\n\n \\param y y coordinate of the film.\n\n \\param v Pixel color.\n\n \n\n \\rst\n", "file_path": "include/lm/film.h", "rank": 62, "score": 162806.9336235799 }, { "content": "class Medium : public Component {\n\npublic:\n\n //! Result of distance sampling.\n\n struct DistanceSample {\n\n Vec3 p; //!< Sampled point.\n\n Vec3 weight; //!< Contribution divided by probability.\n\n bool medium; //!< True if the point is is medium.\n\n };\n\n\n\n /*!\n\n \\brief Sample a distance in a ray direction.\n\n \\param rng Random number generator.\n\n \\param ray Ray.\n\n \\param tmin Lower bound of the valid range of the ray.\n\n \\param tmax Upper bound of the valid range of the ray.\n\n\n\n \\rst\n\n This function samples a scattering event in the valid range of the ray segmnet.\n\n Note that this function assumes there is no scene surfaces\n\n in the given range of the ray segment.\n", "file_path": "include/lm/medium.h", "rank": 63, "score": 162806.9336235799 }, { "content": "class Texture : public Component {\n\npublic:\n\n /*!\n\n \\brief Get size of the texture.\n\n \\return Size of the texture.\n\n */\n\n virtual TextureSize size() const = 0;\n\n\n\n /*!\n\n \\brief Evaluate color component of the texture.\n\n \\param t Texture coordinates.\n\n\n\n \\rst\n\n This function evaluate color of the texture\n\n of the specified texture coordinates.\n\n Handling of the texture coodinates outside of\n\n the range :math:`[0,1]^2` is implementation-dependent.\n\n \\endrst\n\n */\n\n virtual Vec3 eval(Vec2 t) const = 0;\n", "file_path": "include/lm/texture.h", "rank": 64, "score": 162806.9336235799 }, { "content": "class Phase : public Component {\n\npublic:\n\n //! Result of direction sampling.\n\n struct DirectionSample {\n\n Vec3 wo; //!< Sampled direction.\n\n Vec3 weight; //!< Contribution divided by probability.\n\n };\n\n\n\n //! Random number input for direction sampling.\n\n struct DirectionSampleU {\n\n Vec2 ud;\n\n };\n\n\n\n /*!\n\n \\brief Sample a direction.\n\n \\param u Random number input.\n\n \\param geom Point geometry.\n\n \\param wi Incident ray direction.\n\n \\return Sampled direction and associated information.\n\n */\n", "file_path": "include/lm/phase.h", "rank": 65, "score": 162806.9336235799 }, { "content": "class Model : public Component {\n\npublic:\n\n /*!\n\n \\brief Callback function to process a primitive.\n\n \\param mesh Underlying mesh.\n\n \\param material Underlying material.\n\n \\param light Underlying light.\n\n\n\n \\rst\n\n The function of this type is used as an argument of\n\n :cpp:func:`lm::Model::create_primitives` function.\n\n \\endrst\n\n */\n\n using CreatePrimitiveFunc = std::function<void(Component* mesh, Component* material, Component* light)>;\n\n\n\n /*!\n\n \\brief Create primitives from underlying components.\n\n \\param create_primitive Callback function to be called for each primitive.\n\n\n\n \\rst\n", "file_path": "include/lm/model.h", "rank": 66, "score": 162806.9336235799 }, { "content": "class Scheduler : public Component {\n\npublic:\n\n /*!\n\n \\brief Callback function for parallel loop.\n\n \\param pixel_index Pixel index.\n\n \\param sample_index Pixel sample index.\n\n \\param threadid Thread index.\n\n */\n\n using ProcessFunc = std::function<void(long long pixel_index, long long sample_index, int threadid)>;\n\n\n\n /*!\n\n \\brief Dispatch scheduler.\n\n \\param process Callback function for parallel loop.\n\n \\return Processed samples per pixel.\n\n */\n\n virtual long long run(const ProcessFunc& process) const = 0;\n\n};\n\n\n\n/*!\n\n @}\n\n*/\n\n\n\nLM_NAMESPACE_END(scheduler)\n\nLM_NAMESPACE_END(LM_NAMESPACE)\n", "file_path": "include/lm/scheduler.h", "rank": 67, "score": 162806.9336235799 }, { "content": "class Mesh : public Component {\n\npublic:\n\n /*!\n\n \\brief Vertex of a triangle.\n\n\n\n \\rst\n\n Represents geometry information associated with a vertice of a triangle.\n\n \\endrst\n\n */\n\n struct Point {\n\n Vec3 p; //!< Position.\n\n Vec3 n; //!< Normal.\n\n Vec2 t; //!< Texture coordinates.\n\n };\n\n\n\n /*!\n\n \\brief Triangle.\n\n\n\n \\rst\n\n Represents a triangle composed of three vertices.\n", "file_path": "include/lm/mesh.h", "rank": 68, "score": 162806.9336235799 }, { "content": "class Scene : public Component {\n\npublic:\n\n /*!\n\n \\brief Reset the scene.\n\n */\n\n virtual void reset() = 0;\n\n\n\n // --------------------------------------------------------------------------------------------\n\n\n\n #pragma region Scene graph manipulation and access\n\n\n\n /*!\n\n \\brief Get index of the root node.\n\n \\return Node index.\n\n */\n\n virtual int root_node() = 0;\n\n\n\n\t/*!\n\n\t\t\\brief Create primitive node.\n\n \\param prop Property containing references to the scene components.\n", "file_path": "include/lm/scene.h", "rank": 69, "score": 162806.9336235799 }, { "content": "class Renderer : public Component {\n\npublic:\n\n /*!\n\n \\brief Process rendering.\n\n */\n\n virtual Json render() const = 0;\n\n};\n\n\n\n/*!\n\n @}\n\n*/\n\n\n\nLM_NAMESPACE_END(LM_NAMESPACE)\n", "file_path": "include/lm/renderer.h", "rank": 70, "score": 162806.9336235799 }, { "content": "class Camera : public Component {\n\npublic:\n\n /*!\n\n \\brief Set aspect ratio.\n\n \\param aspect Aspect ratio (width / height).\n\n\n\n \\rst\n\n This function sets the aspect ratio of the film to be rendered.\n\n Note that this function overrides the aspect ratio given by a parameter of\n\n :cpp:func:`lm::Component::construct` function.\n\n \\endrst\n\n */\n\n virtual void set_aspect_ratio(Float aspect) = 0;\n\n\n\n // --------------------------------------------------------------------------------------------\n\n\n\n /*!\n\n \\brief Get view matrix if available.\n\n \\return View matrix.\n\n */\n", "file_path": "include/lm/camera.h", "rank": 71, "score": 162806.9336235799 }, { "content": "class Accel : public Component {\n\npublic:\n\n /*!\n\n \\brief Build acceleration structure.\n\n \\param scene Input scene.\n\n\n\n \\rst\n\n Builds the acceleration structure from the primitives inside the given scene.\n\n When a primitive inside the scene is updated by addition or modification,\n\n you need to call the function again to update the structure.\n\n \\endrst\n\n */\n\n virtual void build(const Scene& scene) = 0;\n\n\n\n /*!\n\n \\brief Hit result.\n\n\n\n \\rst\n\n Shows information associated to the hit point of the ray.\n\n More additional information like surface positions can be obtained\n", "file_path": "include/lm/accel.h", "rank": 72, "score": 162806.9336235799 }, { "content": "class Light : public Component {\n\npublic:\n\n /*!\n\n \\brief Set scene bound.\n\n \\param bound Scene bound.\n\n */\n\n virtual void set_scene_bound(const Bound& bound) {\n\n LM_UNUSED(bound);\n\n }\n\n\n\n // --------------------------------------------------------------------------------------------\n\n\n\n //! Result of primary ray sampling.\n\n struct RaySample {\n\n PointGeometry geom; //!< Sampled geometry information.\n\n Vec3 wo; //!< Sampled direction.\n\n Vec3 weight; //!< Contribution divided by probability.\n\n };\n\n\n\n //! Random number input for primary ray sampling.\n", "file_path": "include/lm/light.h", "rank": 73, "score": 162806.9336235799 }, { "content": "struct type_caster<lm::Json> {\n\npublic:\n\n // Register this class as type caster\n\n PYBIND11_TYPE_CASTER(lm::Json, _(\"json\"));\n\n\n\n // Python -> C++\n\n bool load(handle src, bool convert) {\n\n if (!convert) {\n\n // No-convert mode\n\n return false;\n\n }\n\n\n\n using namespace nlohmann::detail;\n\n if (isinstance<none>(src)) {\n\n value = {};\n\n }\n\n else if (isinstance<bool_>(src)) {\n\n value = src.cast<bool>();\n\n }\n\n else if (isinstance<float_>(src)) {\n", "file_path": "include/lm/pylm.h", "rank": 74, "score": 161107.9927611164 }, { "content": "class Accel_NanoRT final : public Accel {\n\nprivate:\n\n std::vector<Float> vs_;\n\n std::vector<unsigned int> fs_;\n\n nanort::BVHAccel<Float> accel_;\n\n std::vector<std::tuple<int, int>> flatten_node_and_face_per_triangle_;\n\n std::vector<FlattenedPrimitiveNode> flattened_nodes_;\n\n\n\npublic:\n\n virtual void build(const Scene& scene) override {\n\n // Make a combined mesh\n\n LM_INFO(\"Flattening scene\");\n\n vs_.clear();\n\n fs_.clear();\n\n flatten_node_and_face_per_triangle_.clear();\n\n flattened_nodes_.clear();\n\n scene.traverse_primitive_nodes([&](const SceneNode& node, Mat4 global_transform) {\n\n if (node.type != SceneNodeType::Primitive) {\n\n return;\n\n }\n", "file_path": "plugin/accel_nanort/accel_nanort.cpp", "rank": 75, "score": 160304.06121223705 }, { "content": "// Bidirectional path tracing\n\nclass Renderer_BDPT final : public Renderer_Path_Base {\n\npublic:\n\n #if BDPT_PER_STRATEGY_FILM\n\n // Index: (k, s)\n\n // where k = 2,..,max_verts,\n\n // s = 0,...,s\n\n mutable std::vector<std::vector<Ptr<Film>>> strategy_films_;\n\n std::unordered_map<std::string, Film*> strategy_film_name_map_;\n\n\n\n virtual Component* underlying(const std::string& name) const override {\n\n return strategy_film_name_map_.at(name);\n\n }\n\n\n\n virtual void construct(const Json& prop) override {\n\n Renderer_Path_Base::construct(prop);\n\n const auto size = film_->size();\n\n for (int k = 2; k <= max_verts_; k++) {\n\n strategy_films_.emplace_back();\n\n for (int s = 0; s <= k; s++) {\n\n const auto name = fmt::format(\"film_{}_{}\", k, s);\n", "file_path": "src/renderer/renderer_bdpt.cpp", "rank": 76, "score": 160304.06121223705 }, { "content": "enum class LogLevel : int {\n\n /*!\n\n \\rst\n\n Debug message.\n\n You may use this level to specify the error messages\n\n are only emitted in a Debug session.\n\n You can generate a log message with this type by :func:`LM_DEBUG` macro.\n\n \\endrst\n\n */\n\n Debug = -10,\n\n /*!\n\n \\rst\n\n Information message.\n\n You may use this level to notice information to the user. \n\n Typical usage is to indicate the execution flow of the application\n\n before/after the execution enters/leaves the codes of heavy computation or IO.\n\n You can generate a log message with this type by :func:`LM_INFO` macro.\n\n \\endrst\n\n */\n\n Info = 10,\n", "file_path": "include/lm/logger.h", "rank": 77, "score": 159810.47468713945 }, { "content": "struct TestSerial_Nested final : public lm::Component {\n\n Component::Ptr<Component> p;\n\n TestSerial_Nested() {\n\n p = lm::comp::create<Component>(\"testserial_simple\", \"\", {\n\n { \"v1\", 42 },\n\n { \"v2\", 32 }\n\n });\n\n }\n\n LM_SERIALIZE_IMPL(ar) {\n\n ar(p);\n\n }\n\n};\n\n\n\nLM_COMP_REG_IMPL(TestSerial_Nested, \"testserial_nested\");\n\n\n", "file_path": "test/test_serial.cpp", "rank": 78, "score": 158364.5233659453 }, { "content": "struct TestSerial_Ref final : public lm::Component {\n\n Component* p;\n\n virtual void construct(const lm::Json& prop) {\n\n p = lm::comp::get<Component>(prop[\"ref\"]);\n\n }\n\n LM_SERIALIZE_IMPL(ar) {\n\n ar(p);\n\n }\n\n};\n\n\n\nLM_COMP_REG_IMPL(TestSerial_Ref, \"testserial_ref\");\n\n\n", "file_path": "test/test_serial.cpp", "rank": 79, "score": 158364.5233659453 }, { "content": "// Imitating root component\n\nstruct TestSerial_Root final : public lm::Component {\n\n // Underlying component\n\n Component::Ptr<Component> p;\n\n\n\n TestSerial_Root() {\n\n // Register this component as root\n\n lm::comp::detail::Access::loc(this) = \"$\";\n\n lm::comp::detail::register_root_comp(this);\n\n }\n\n\n\n virtual Component* underlying(const std::string& name) const {\n\n if (name == \"p\") {\n\n return p.get();\n\n }\n\n return nullptr;\n\n }\n\n\n\n // Clear state. Returns old underlying component.\n\n Component::Ptr<Component> clear() {\n\n return Component::Ptr<Component>(p.release());\n", "file_path": "test/test_serial.cpp", "rank": 80, "score": 158364.5233659453 }, { "content": "struct TestSerial_Container final : public lm::Component {\n\n std::vector<Component::Ptr<Component>> v;\n\n std::unordered_map<std::string, int> m;\n\n\n\n // Add a component to the container\n\n void add(const std::string& name, const std::string& key, const lm::Json& prop) {\n\n auto p = lm::comp::create<lm::Component>(key, make_loc(loc(), name), prop);\n\n CHECK(p);\n\n m[name] = int(v.size());\n\n v.push_back(std::move(p));\n\n }\n\n\n\n virtual Component* underlying(const std::string& name) const {\n\n return v[m.at(name)].get();\n\n }\n\n\n\n LM_SERIALIZE_IMPL(ar) {\n\n // Order of the argument is critical\n\n ar(m, v);\n\n }\n\n};\n\n\n\nLM_COMP_REG_IMPL(TestSerial_Container, \"testserial_container\");\n\n\n", "file_path": "test/test_serial.cpp", "rank": 81, "score": 158364.5233659453 }, { "content": "struct TestSerial_Simple final : public lm::Component {\n\n int v1;\n\n int v2;\n\n virtual void construct(const lm::Json& prop) override {\n\n v1 = prop[\"v1\"];\n\n v2 = prop[\"v2\"];\n\n }\n\n LM_SERIALIZE_IMPL(ar) {\n\n ar(v1, v2);\n\n }\n\n};\n\n\n\nLM_COMP_REG_IMPL(TestSerial_Simple, \"testserial_simple\");\n\n\n", "file_path": "test/test_serial.cpp", "rank": 82, "score": 158364.5233659453 }, { "content": "class ProgressContext : public Component {\n\npublic:\n\n virtual void start(ProgressMode mode, long long total, double totalTime) = 0;\n\n virtual void update(long long processed) = 0;\n\n virtual void update_time(Float elapsed) = 0;\n\n virtual void end() = 0;\n\n};\n\n\n\n/*!\n\n @}\n\n*/\n\n\n\nLM_NAMESPACE_END(progress)\n\nLM_NAMESPACE_END(LM_NAMESPACE)\n", "file_path": "include/lm/progresscontext.h", "rank": 83, "score": 158045.32373385294 }, { "content": "class AssetGroup : public Component {\n\npublic:\n\n /*!\n\n \\brief Loads an asset.\n\n \\param name Name of the asset.\n\n \\param impl_key Key of component implementation in `interface::implementation` format.\n\n \\param prop Properties.\n\n \\return Pointer to the created asset. nullptr if failed.\n\n\n\n \\rst\n\n Loads an asset from the given information and registers to the class.\n\n ``impl_key`` is used to create an instance and ``prop`` is used to construct it.\n\n ``prop`` is passed to :cpp:func:`lm::Component::construct` function of\n\n the implementation of the asset.\n\n This function returns a pointer to the created instance.\n\n If failed, it returns nullptr.\n\n\n\n If the asset with same name is already loaded, the function tries\n\n to deregister the previously-loaded asset and reload an asset again.\n\n If the global component hierarchy contains a reference to the original asset,\n", "file_path": "include/lm/assetgroup.h", "rank": 84, "score": 158045.32373385294 }, { "content": "class LoggerContext : public Component {\n\npublic:\n\n virtual void log(LogLevel level, int severity, const char* filename, int line, const char* message) = 0;\n\n virtual void update_indentation(int n) = 0;\n\n virtual void set_severity(int severity) = 0;\n\n};\n\n\n\n/*!\n\n @}\n\n*/\n\n\n\nLM_NAMESPACE_END(log)\n\nLM_NAMESPACE_END(LM_NAMESPACE)\n", "file_path": "include/lm/loggercontext.h", "rank": 85, "score": 158045.32373385294 }, { "content": "class ScopedTimer : public Component {\n\nprivate:\n\n std::chrono::high_resolution_clock::time_point start;\n\npublic:\n\n /*!\n\n \\brief Timer initialisation at the time of object creation\n\n */\n\n ScopedTimer():start(std::chrono::high_resolution_clock::now()){}\n\n\n\n /*!\n\n \\brief elapsed time since object creation in seconds\n\n */\n\n virtual Float now() const{\n\n return std::chrono::duration<Float>(std::chrono::high_resolution_clock::now()-start).count();\n\n }\n\n};\n\n\n\n/*!\n\n @}\n\n*/\n\n\n\nLM_NAMESPACE_END(timer)\n\nLM_NAMESPACE_END(LM_NAMESPACE)\n", "file_path": "include/lm/timer.h", "rank": 86, "score": 158045.32373385294 }, { "content": "class ParallelContext : public Component {\n\npublic:\n\n virtual int num_threads() const = 0;\n\n virtual bool main_thread() const = 0;\n\n virtual void foreach(long long numSamples, const ParallelProcessFunc& processFunc, const ProgressUpdateFunc& progressFunc) const = 0;\n\n};\n\n\n\n/*!\n\n @}\n\n*/\n\n\n\nLM_NAMESPACE_END(parallel)\n\nLM_NAMESPACE_END(LM_NAMESPACE)\n", "file_path": "include/lm/parallelcontext.h", "rank": 87, "score": 158045.32373385294 }, { "content": "class Accel_Embree_Instanced final : public Accel {\n\nprivate:\n\n RTCDevice device_ = nullptr;\n\n RTCScene scene_ = nullptr;\n\n RTCBuildArguments settings_;\n\n RTCSceneFlags sf_;\n\n std::vector<FlattenedScene> flattened_scenes_; // Flattened scenes (index 0: root)\n\n\n\npublic:\n\n \n\n virtual void construct(const Json& prop) override { \n\n settings_ = prop;\n\n sf_ = prop;\n\n \n\n //check actual values used for building\n\n Json j;\n\n j = settings_; \n\n LM_DEBUG(j.dump());\n\n j.clear();\n\n j = sf_;\n", "file_path": "plugin/accel_embree/accel_embree_instanced.cpp", "rank": 88, "score": 157285.17532868893 }, { "content": "class ParallelContext_OpenMP final : public ParallelContext {\n\nprivate:\n\n long long progress_update_interval_;\t// Number of samples per progress update\n\n int num_threads_;\t\t\t\t\t// Number of threads\n\n\n\npublic:\n\n virtual void construct(const Json& prop) override {\n\n progress_update_interval_ = json::value<long long>(prop, \"progress_update_interval\", 100);\n\n num_threads_ = json::value(prop, \"num_threads\", std::thread::hardware_concurrency());\n\n if (num_threads_ <= 0) {\n\n num_threads_ = std::thread::hardware_concurrency() + num_threads_;\n\n }\n\n omp_set_num_threads(num_threads_);\n\n }\n\n\n\n virtual int num_threads() const override {\n\n return num_threads_;\n\n }\n\n\n\n virtual bool main_thread() const override {\n", "file_path": "src/parallel/parallel_openmp.cpp", "rank": 89, "score": 157285.17532868893 }, { "content": "class Material; // material.h\n", "file_path": "include/lm/common.h", "rank": 90, "score": 156154.33906996512 }, { "content": "// Implements naive path tracing using path structure\n\nclass Renderer_PT_Naive_Path final : public Renderer_Path_Base {\n\npublic:\n\n virtual Json render() const override {\n\n scene_->require_renderable();\n\n film_->clear();\n\n const auto size = film_->size();\n\n timer::ScopedTimer st;\n\n\n\n // Execute parallel process\n\n const auto processed = sched_->run([&](long long, long long sample_index, int threadid) {\n\n LM_KEEP_UNUSED(sample_index);\n\n\n\n // Per-thread random number generator\n\n thread_local Rng rng(seed_ ? *seed_ + threadid : math::rng_seed());\n\n\n\n // Sample eye subpath\n\n const auto subpathE = path::sample_subpath(rng, scene_, max_verts_, TransDir::EL);\n\n const int nE = (int)(subpathE.vs.size());\n\n\n\n // Create full paths of all possible lengths\n", "file_path": "src/renderer/renderer_bdpt.cpp", "rank": 91, "score": 154467.19797025673 }, { "content": "// Renderer based on openvdb_render.cc in OpenVDB\n\nclass Renderer_OpenVDBRenderExample final : public Renderer {\n\nprivate:\n\n Scene* scene_;\n\n Film* film_;\n\n const Volume* volume_;\n\n Float march_step_;\n\n Float march_step_shadow_;\n\n Vec3 light_dir_;\n\n Vec3 Le_;\n\n Vec3 muA_; // Maximum absorption coefficient.\n\n Vec3 muS_; // Maximum scattering coefficient.\n\n Vec3 muT_; // Maximum extinction coefficient.\n\n Float cutoff_;\n\n Component::Ptr<scheduler::Scheduler> sched_;\n\n\n\npublic:\n\n virtual void construct(const Json& prop) override {\n\n scene_ = json::comp_ref<Scene>(prop, \"scene\");\n\n film_ = json::comp_ref<Film>(prop, \"output\");\n\n volume_ = json::comp_ref<Volume>(prop, \"volume\");\n", "file_path": "plugin/volume_openvdb/renderer_volraycast.cpp", "rank": 92, "score": 154467.19797025673 }, { "content": "// Path tracing with NEE using path structure\n\nclass Renderer_PT_NEE_Path final : public Renderer_Path_Base {\n\npublic:\n\n virtual Json render() const override {\n\n scene_->require_renderable();\n\n film_->clear();\n\n const auto size = film_->size();\n\n timer::ScopedTimer st;\n\n\n\n // Execute parallel process\n\n const auto processed = sched_->run([&](long long, long long, int threadid) {\n\n // Per-thread random number generator\n\n thread_local Rng rng(seed_ ? *seed_ + threadid : math::rng_seed());\n\n\n\n // Sample subpaths\n\n const auto subpathE = path::sample_subpath(rng, scene_, max_verts_, TransDir::EL);\n\n const auto subpathL = path::sample_subpath(rng, scene_, 1, TransDir::LE);\n\n const int nE = (int)(subpathE.vs.size());\n\n const int nL = (int)(subpathL.vs.size());\n\n assert(nL > 0);\n\n\n", "file_path": "src/renderer/renderer_bdpt.cpp", "rank": 93, "score": 154467.19797025673 }, { "content": "// Light trasing with NEE using path structure\n\nclass Renderer_LT_NEE_Path final : public Renderer_Path_Base {\n\npublic:\n\n virtual Json render() const override {\n\n scene_->require_renderable();\n\n film_->clear();\n\n const auto size = film_->size();\n\n timer::ScopedTimer st;\n\n\n\n // Execute parallel process\n\n const auto processed = sched_->run([&](long long, long long sample_index, int threadid) {\n\n LM_KEEP_UNUSED(sample_index);\n\n\n\n // Per-thread random number generator\n\n thread_local Rng rng(seed_ ? *seed_ + threadid : math::rng_seed());\n\n\n\n // Sample subpaths\n\n const auto subpathE = path::sample_subpath(rng, scene_, 1, TransDir::EL);\n\n const auto subpathL = path::sample_subpath(rng, scene_, max_verts_, TransDir::LE);\n\n const int nE = (int)(subpathE.vs.size());\n\n assert(nE > 0);\n", "file_path": "src/renderer/renderer_bdpt.cpp", "rank": 94, "score": 154467.19797025673 }, { "content": "class Renderer_VolPT final : public Renderer_VolPT_Base {\n\npublic:\n\n virtual Json render() const override {\n\n\t\tscene_->require_renderable();\n\n\n\n film_->clear();\n\n const auto size = film_->size();\n\n timer::ScopedTimer st;\n\n const auto processed = sched_->run([&](long long pixel_index, long long sample_index, int threadid) {\n\n LM_KEEP_UNUSED(sample_index);\n\n\n\n // Per-thread random number generator\n\n thread_local Rng rng(seed_ ? *seed_ + threadid : math::rng_seed());\n\n\n\n // ------------------------------------------------------------------------------------\n\n\n\n // Sample window\n\n Vec4 window(0,0,1,1);\n\n #if VOLPT_IMAGE_SAMPLING\n\n LM_UNUSED(pixel_index);\n", "file_path": "src/renderer/renderer_volpt.cpp", "rank": 95, "score": 154467.19797025673 }, { "content": "class OBJLoaderContext : public Component {\n\npublic:\n\n virtual bool load(\n\n const std::string& path,\n\n OBJSurfaceGeometry& geo,\n\n const ProcessMeshFunc& processMesh,\n\n const ProcessMaterialFunc& processMaterial) = 0;\n\n};\n\n\n\n/*!\n\n @}\n\n*/\n\n\n\nLM_NAMESPACE_END(objloader)\n\nLM_NAMESPACE_END(LM_NAMESPACE)\n", "file_path": "include/lm/objloader.h", "rank": 96, "score": 153679.6511570914 }, { "content": "struct TestPluginWithCtorAndDtor_ final : public TestPluginWithCtorAndDtor {\n\n TestPluginWithCtorAndDtor_() { std::cout << \"B\"; }\n\n ~TestPluginWithCtorAndDtor_() { std::cout << \"~B\"; }\n\n};\n\n\n\nLM_COMP_REG_IMPL(TestPluginWithCtorAndDtor_, \"testpluginxtor::default\");\n\n\n\n// ------------------------------------------------------------------------------------------------\n\n\n\ntemplate <typename T>\n", "file_path": "test/test_interface_impl.cpp", "rank": 97, "score": 153027.41038354306 }, { "content": "class Exception : public std::exception {\n\nprivate:\n\n Error error_;\n\n std::string file_;\n\n int line_;\n\n std::string message_;\n\n std::string what_;\n\n\n\nprivate:\n\n // Generate error string\n\n void generante_error_message() {\n\n // Compose error message with error code\n\n const auto errorCodeStr = [this]() -> std::string {\n\n if (error_ == Error::None) {\n\n return \"None\";\n\n }\n\n if (error_ == Error::Unsupported) {\n\n return \"Unsupported\";\n\n }\n\n if (error_ == Error::Uninitialized) {\n", "file_path": "include/lm/exception.h", "rank": 98, "score": 152966.7617361523 }, { "content": "class Renderer_VolPTNaive final : public Renderer_VolPT_Base {\n\npublic:\n\n virtual Json render() const override {\n\n\t\tscene_->require_renderable();\n\n\n\n film_->clear();\n\n const auto size = film_->size();\n\n timer::ScopedTimer st;\n\n const auto processed = sched_->run([&](long long pixel_index, long long sample_index, int threadid) {\n\n LM_KEEP_UNUSED(sample_index);\n\n\n\n // Per-thread random number generator\n\n thread_local Rng rng(seed_ ? *seed_ + threadid : math::rng_seed());\n\n\n\n // ------------------------------------------------------------------------------------\n\n\n\n // Sample window\n\n Vec4 window(0,0,1,1);\n\n #if VOLPT_IMAGE_SAMPLING\n\n LM_UNUSED(pixel_index);\n", "file_path": "src/renderer/renderer_volpt.cpp", "rank": 99, "score": 151830.71914945578 } ]
C++
example/add2/addserver.cc
walterzhaoJR/braft_walter
bba0afae3b28e9446e4ecc44e0b2b8baac1c4780
#include <map> #include <string> #include <fstream> #include <gflags/gflags.h> #include <brpc/controller.h> #include <brpc/server.h> #include <braft/raft.h> #include <braft/util.h> #include <braft/storage.h> #include <butil/sys_byteorder.h> #include "add.pb.h" DEFINE_int32(port, 8100, "Listen port of this peer"); DEFINE_bool(h, false, "print help information"); DEFINE_string(group, "add", "Id of the replication group"); DEFINE_string(conf, "", "Initial configuration of the replication group"); DEFINE_string(data_path, "./data", "Path of data stored on"); DEFINE_int32(election_timeout_ms, 5000, "Start election in such milliseconds if disconnect with the leader"); DEFINE_int32(snapshot_interval, 60, "Interval between each snapshot"); using namespace std; namespace example { class AddStateMachine ; class AddClosure : public braft::Closure { public: AddClosure(AddStateMachine* statemachine,const AddRequest* request,AddResponse* response ,google::protobuf::Closure* done) :statemachine_(statemachine),request_(request),response_(response),done_(done){ }; void Run(); const AddRequest* Request(){ return request_; } AddResponse* Response(){ return response_; } private: AddStateMachine* statemachine_; const AddRequest* request_; AddResponse* response_; google::protobuf::Closure* done_; }; class AddStateMachine : public braft::StateMachine { public: AddStateMachine():_node(NULL),leader_term_(-1),id_(-1){}; ~AddStateMachine(){} int start(int id); virtual void on_apply(::braft::Iterator& iter) ; virtual void on_snapshot_save(::braft::SnapshotWriter* writer, ::braft::Closure* done); virtual int on_snapshot_load(::braft::SnapshotReader* reader); void on_shutdown() { LOG(INFO) << "This node is down"; } void on_error(const ::braft::Error& e) { LOG(ERROR) << "Met raft error " << e; } void on_configuration_committed(const ::braft::Configuration& conf) { LOG(INFO) << "Configuration of this group is " << conf; } void on_stop_following(const ::braft::LeaderChangeContext& ctx) { LOG(INFO) << "Node stops following " << ctx; } void on_start_following(const ::braft::LeaderChangeContext& ctx) { LOG(INFO) << "Node start following " << ctx; } void on_leader_start(int64_t term) { leader_term_.store(term, butil::memory_order_release); LOG(INFO) << "Node becomes leader"; } void on_leader_stop(const butil::Status& status) { leader_term_.store(-1, butil::memory_order_release); LOG(INFO) << "Node stepped down : " << status; } bool is_leader() const { return leader_term_.load(butil::memory_order_acquire) > 0; } void redirect(AddResponse* response) { response->set_success(false); response->set_result(-1); if (_node) { braft::PeerId leader = _node->leader_id(); if (!leader.is_empty()) { LOG(DEBUG) << "id:"<<id_<<"," <<"redirect : " << leader; response->set_redirect(leader.to_string()); } else{ LOG(ERROR) << "id:"<<id_<<"," <<"NO LEADER "; } } } void write(const ::example::AddRequest* request,::example::AddResponse* response ,::google::protobuf::Closure* done); void reallyWrite(const string& key ,long long number,AddResponse* response); void shutdown() { if (_node) { _node->shutdown(NULL); } } void join() { if (_node) { _node->join(); } } private: map<string,long long> number_map_; braft::Node* volatile _node; butil::atomic<int64_t> leader_term_; int id_; }; void AddStateMachine::on_snapshot_save(::braft::SnapshotWriter* writer, ::braft::Closure* done){ brpc::ClosureGuard done_guard(done); std::string snapshot_path = writer->get_path(); snapshot_path.append("/data"); std::ofstream os(snapshot_path.c_str()); for (auto it = number_map_.begin(); it != number_map_.end() ; it++) { os << it->first << ' ' << it->second << '\n'; } CHECK_EQ(0, writer->add_file("data")); return; } int AddStateMachine::on_snapshot_load(::braft::SnapshotReader* reader){ CHECK_EQ(-1, leader_term_) << "Leader is not supposed to load snapshot"; number_map_.clear(); std::string snapshot_path = reader->get_path(); snapshot_path.append("/data"); std::ifstream is(snapshot_path.c_str()); string key ; int64_t value = 0; while (is >> key >> value) { LOG(DEBUG) << "key:" << key << ",value:" << value; number_map_[key] = value; } return 0; } int AddStateMachine::start(int id){ id_ = id; butil::EndPoint addr(butil::my_ip(), FLAGS_port); braft::Node* node = new braft::Node(FLAGS_group, braft::PeerId(addr,id)); braft::NodeOptions node_options; stringstream data_path_stream; data_path_stream << FLAGS_data_path << id; string data_path = data_path_stream.str(); if (!butil::CreateDirectory(butil::FilePath(data_path))) { LOG(ERROR) << "Fail to create directory " << data_path; return -1; } LOG(INFO) << "data_path:"<<data_path; node_options.election_timeout_ms = FLAGS_election_timeout_ms; node_options.fsm = this; node_options.snapshot_interval_s = FLAGS_snapshot_interval; std::string prefix = "local://" + data_path; node_options.log_uri = prefix + "/log"; node_options.raft_meta_uri = prefix + "/raft_meta"; node_options.snapshot_uri = prefix + "/snapshot"; stringstream ss(FLAGS_conf); string t; stringstream conf; while (getline(ss, t, ',')) { conf << t <<":"<<id<<","; } LOG(INFO) << "CONF:"<<conf.str(); if (node_options.initial_conf.parse_from(conf.str()) != 0) { LOG(ERROR) << "Fail to parse configuration `" << conf.str() << '\''; return -1; } if (node->init(node_options) != 0) { LOG(ERROR) << "Fail to init raft node"; delete node; return -1; } _node = node; return 0; } void AddStateMachine::on_apply(braft::Iterator& iter) { for (; iter.valid(); iter.next()) { braft::AsyncClosureGuard closure_guard(iter.done()); butil::IOBuf data; string key; long long number; AddResponse* response = NULL; if (iter.done()) { LOG(DEBUG) << "id:"<<id_<<"," <<"iter.done"; AddClosure* c = dynamic_cast<AddClosure*>(iter.done()); LOG(INFO) << "id:"<<id_<<"," <<"request ptr:" <<c->Request(); key = c->Request()->key(); number = c->Request()->number(); response = c->Response(); } else { LOG(DEBUG) << "id:"<<id_<<"," << "parse from iter.data"; uint32_t meta_size = 0; butil::IOBuf saved_log = iter.data(); saved_log.cutn(&meta_size, sizeof(uint32_t)); meta_size = butil::NetToHost32(meta_size); butil::IOBuf meta; saved_log.cutn(&meta, meta_size); butil::IOBufAsZeroCopyInputStream wrapper(meta); AddRequest request; CHECK(request.ParseFromZeroCopyStream(&wrapper)); key = request.key(); number = request.number(); } reallyWrite(key,number,response); } } void AddStateMachine::write(const ::example::AddRequest* request,::example::AddResponse* response ,::google::protobuf::Closure* done){ brpc::ClosureGuard done_guard(done); const int64_t term = leader_term_.load(butil::memory_order_relaxed); LOG(DEBUG) <<"term:" <<term; if (term < 0) { LOG(DEBUG) <<"redirect"; return redirect(response); } LOG(INFO) << "id:"<<id_<<","<<"request ptr:" <<request; LOG(INFO) << "id:"<<id_<<","<<"done ptr:" <<done; LOG(INFO) << "id:"<<id_<<"," << "request message ,key:" << request->key() << ",number:" << request->number(); butil::IOBuf log; const uint32_t meta_size_raw = butil::HostToNet32(request->ByteSize()); log.append(&meta_size_raw, sizeof(uint32_t)); butil::IOBufAsZeroCopyOutputStream wrapper(&log); if (!request->SerializeToZeroCopyStream(&wrapper)) { LOG(ERROR) << "Fail to serialize request"; response->set_success(false); return; } braft::Task task; task.data = &log; task.done = new AddClosure( this,request,response,done_guard.release()); _node->apply(task); LOG(INFO) << "id:"<<id_<<"," <<"apply done"; return; } void AddStateMachine::reallyWrite(const string& key ,long long number,AddResponse* response){ LOG(INFO) << "request message ,key:" << key << ",number:" << number; long long result = number; if (number_map_.find(key) == number_map_.end()) { number_map_.insert(make_pair(key,result)); } else { result += number_map_[key]; number_map_[key] = result; } LOG(INFO) << "reslut:" << result; if (response) { LOG(DEBUG) << "response isn't NULL,set response"; response->set_success(true); response->set_result(result); } } class AddServiceImpl :public AddService{ public: AddServiceImpl(AddStateMachine* sm,AddStateMachine* sm2):statemachine_(sm),statemachine2_(sm2) ,statemachine3_(NULL){ } void shutdown(){ if (statemachine3_ != NULL) { statemachine3_->shutdown(); } } void write(::google::protobuf::RpcController* controller, const ::example::AddRequest* request, ::example::AddResponse* response, ::google::protobuf::Closure* done) { brpc::ClosureGuard done_guard(done); if (request->key() == "key2") { statemachine2_->write(request,response, done_guard.release()); return; } if (request->key() == "key3") { if (statemachine3_ == NULL) { response->set_success(false); response->set_result(-1); response->set_redirect("statemachine3 can't start."); return; } statemachine3_->write(request,response, done_guard.release()); return; } statemachine_->write(request,response, done_guard.release()); return; } void start_new_statemachine(::google::protobuf::RpcController* controller, const ::example::NewStateMachineRequest* request, ::example::NewStateMachineResponse* response, ::google::protobuf::Closure* done){ brpc::ClosureGuard done_guard(done); statemachine3_ = new AddStateMachine(); if (statemachine3_->start(2) != 0) { LOG(ERROR) << "Fail to start state machine1"; response->set_success(false); return ; } response->set_success(true); } private: AddStateMachine* statemachine_; AddStateMachine* statemachine2_; AddStateMachine* statemachine3_; }; void AddClosure::Run(){ std::unique_ptr<AddClosure> self_guard(this); LOG(INFO) <<"done ptr:" <<done_; brpc::ClosureGuard done_guard(done_); if (status().ok()) { return; } statemachine_->redirect(response_); } } int main(int argc, char* argv[]){ gflags::SetVersionString("0.1"); gflags::SetUsageMessage("Usage: xxxx"); gflags::ParseCommandLineFlags(&argc, &argv, true); brpc::Server server; example::AddStateMachine statemachine; example::AddStateMachine statemachine2; example::AddServiceImpl service(&statemachine,&statemachine2); if (server.AddService(&service, brpc::SERVER_DOESNT_OWN_SERVICE) != 0) { LOG(ERROR) << "Fail to add service"; return -1; } if (braft::add_service(&server, FLAGS_port) != 0) { LOG(ERROR) << "Fail to add raft service"; return -1; } if (server.Start(FLAGS_port, NULL) != 0) { LOG(ERROR) << "Fail to start Server"; return -1; } if (statemachine.start(0) != 0) { LOG(ERROR) << "Fail to start state machine0"; return -1; } if (statemachine2.start(1) != 0) { LOG(ERROR) << "Fail to start state machine1"; return -1; } LOG(INFO) << "add service is running on " << server.listen_address(); while (!brpc::IsAskedToQuit()) { sleep(1); } LOG(INFO) << "add service is going to quit"; statemachine.shutdown(); statemachine2.shutdown(); service.shutdown(); server.Stop(0); statemachine.join(); statemachine2.join(); server.Join(); return 0; }
#include <map> #include <string> #include <fstream> #include <gflags/gflags.h> #include <brpc/controller.h> #include <brpc/server.h> #include <braft/raft.h> #include <braft/util.h> #include <braft/storage.h> #include <butil/sys_byteorder.h> #include "add.pb.h" DEFINE_int32(port, 8100, "Listen port of this peer"); DEFINE_bool(h, false, "print help information"); DEFINE_string(group, "add", "Id of the replication group"); DEFINE_string(conf, "", "Initial configuration of the replication group"); DEFINE_string(data_path, "./data", "Path of data stored on"); DEFINE_int32(election_timeout_ms, 5000, "Start election in such milliseconds if disconnect with the leader"); DEFINE_int32(snapshot_interval, 60, "Interval between each snapshot"); using namespace std; namespace example { class AddStateMachine ; class AddClosure : public braft::Closure { public: AddClosure(AddStateMachine* statemachine,const AddRequest* request,AddResponse* response ,google::protobuf::Closure* done) :statemachine_(statemachine),request_(request),response_(response),done_(done){ }; void Run(); const AddRequest* Request(){ return request_; } AddResponse* Response(){ return response_; } private: AddStateMachine* statemachine_; const AddRequest* request_; AddResponse* response_; google::protobuf::Closure* done_; }; class AddStateMachine : public braft::StateMachine { public: AddStateMachine():_node(NULL),leader_term_(-1),id_(-1){}; ~AddStateMachine(){} int start(int id); virtual void on_apply(::braft::Iterator& iter) ; virtual void on_snapshot_save(::braft::SnapshotWriter* writer, ::braft::Closure* done); virtual int on_snapshot_load(::braft::SnapshotReader* reader); void on_shutdown() { LOG(INFO) << "This node is down"; } void on_error(const ::braft::Error& e) { LOG(ERROR) << "Met raft error " << e; } void on_configuration_committed(const ::braft::Configuration& conf) { LOG(INFO) << "Configuration of this group is " << conf; } void on_stop_following(const ::braft::LeaderChangeContext& ctx) { LOG(INFO) << "Node stops following " << ctx; } void on_start_following(const ::braft::LeaderChangeContext& ctx) { LOG(INFO) << "Node start following " << ctx; } void on_leader_start(int64_t term) { leader_term_.store(term, butil::memory_order_release); LOG(INFO) << "Node becomes leader"; } void on_leader_stop(const butil::Status& status) { leader_term_.store(-1, butil::memory_order_release); LOG(INFO) << "Node stepped down : " << status; } bool is_leader() const { return leader_term_.load(butil::memory_order_acquire) > 0; } void redirect(AddResponse* response) { response->set_success(false); response->set_result(-1); if (_node) { braft::PeerId leader = _node->leader_id(); if (!leader.is_empty()) { LOG(DEBUG) << "id:"<<id_<<"," <<"redirect : " << leader; response->set_redirect(leader.to_string()); } else{ LOG(ERROR) << "id:"<<id_<<"," <<"NO LEADER "; } } } void write(const ::example::AddRequest* request,::example::AddResponse* response ,::google::protobuf::Closure* done); void reallyWrite(const string& key ,long long number,AddResponse* response); void shutdown() { if (_node) { _node->shutdown(NULL); } } void join() { if (_node) { _node->join(); } } private: map<string,long long> number_map_; braft::Node* volatile _node; butil::atomic<int64_t> leader_term_; int id_; }; void AddStateMachine::on_snapshot_save(::braft::SnapshotWriter* writer, ::braft::Closure* done){ brpc::ClosureGuard done_guard(done); std::string snapshot_path = writer->get_path(); snapshot_path.append("/data"); std::ofstream os(snapshot_path.c_str()); for (auto it = number_map_.begin(); it != number_map_.end() ; it++) { os << it->first << ' ' << it->second << '\n'; } CHECK_EQ(0, writer->add_file("data")); return; } int AddStateMachine::on_snapshot_load(::braft::SnapshotReader* reader){ CHECK_EQ(-1, leader_term_) << "Leader is not supposed to load snapshot"; number_map_.clear(); std::string snapshot_path = reader->get_pat
int AddStateMachine::start(int id){ id_ = id; butil::EndPoint addr(butil::my_ip(), FLAGS_port); braft::Node* node = new braft::Node(FLAGS_group, braft::PeerId(addr,id)); braft::NodeOptions node_options; stringstream data_path_stream; data_path_stream << FLAGS_data_path << id; string data_path = data_path_stream.str(); if (!butil::CreateDirectory(butil::FilePath(data_path))) { LOG(ERROR) << "Fail to create directory " << data_path; return -1; } LOG(INFO) << "data_path:"<<data_path; node_options.election_timeout_ms = FLAGS_election_timeout_ms; node_options.fsm = this; node_options.snapshot_interval_s = FLAGS_snapshot_interval; std::string prefix = "local://" + data_path; node_options.log_uri = prefix + "/log"; node_options.raft_meta_uri = prefix + "/raft_meta"; node_options.snapshot_uri = prefix + "/snapshot"; stringstream ss(FLAGS_conf); string t; stringstream conf; while (getline(ss, t, ',')) { conf << t <<":"<<id<<","; } LOG(INFO) << "CONF:"<<conf.str(); if (node_options.initial_conf.parse_from(conf.str()) != 0) { LOG(ERROR) << "Fail to parse configuration `" << conf.str() << '\''; return -1; } if (node->init(node_options) != 0) { LOG(ERROR) << "Fail to init raft node"; delete node; return -1; } _node = node; return 0; } void AddStateMachine::on_apply(braft::Iterator& iter) { for (; iter.valid(); iter.next()) { braft::AsyncClosureGuard closure_guard(iter.done()); butil::IOBuf data; string key; long long number; AddResponse* response = NULL; if (iter.done()) { LOG(DEBUG) << "id:"<<id_<<"," <<"iter.done"; AddClosure* c = dynamic_cast<AddClosure*>(iter.done()); LOG(INFO) << "id:"<<id_<<"," <<"request ptr:" <<c->Request(); key = c->Request()->key(); number = c->Request()->number(); response = c->Response(); } else { LOG(DEBUG) << "id:"<<id_<<"," << "parse from iter.data"; uint32_t meta_size = 0; butil::IOBuf saved_log = iter.data(); saved_log.cutn(&meta_size, sizeof(uint32_t)); meta_size = butil::NetToHost32(meta_size); butil::IOBuf meta; saved_log.cutn(&meta, meta_size); butil::IOBufAsZeroCopyInputStream wrapper(meta); AddRequest request; CHECK(request.ParseFromZeroCopyStream(&wrapper)); key = request.key(); number = request.number(); } reallyWrite(key,number,response); } } void AddStateMachine::write(const ::example::AddRequest* request,::example::AddResponse* response ,::google::protobuf::Closure* done){ brpc::ClosureGuard done_guard(done); const int64_t term = leader_term_.load(butil::memory_order_relaxed); LOG(DEBUG) <<"term:" <<term; if (term < 0) { LOG(DEBUG) <<"redirect"; return redirect(response); } LOG(INFO) << "id:"<<id_<<","<<"request ptr:" <<request; LOG(INFO) << "id:"<<id_<<","<<"done ptr:" <<done; LOG(INFO) << "id:"<<id_<<"," << "request message ,key:" << request->key() << ",number:" << request->number(); butil::IOBuf log; const uint32_t meta_size_raw = butil::HostToNet32(request->ByteSize()); log.append(&meta_size_raw, sizeof(uint32_t)); butil::IOBufAsZeroCopyOutputStream wrapper(&log); if (!request->SerializeToZeroCopyStream(&wrapper)) { LOG(ERROR) << "Fail to serialize request"; response->set_success(false); return; } braft::Task task; task.data = &log; task.done = new AddClosure( this,request,response,done_guard.release()); _node->apply(task); LOG(INFO) << "id:"<<id_<<"," <<"apply done"; return; } void AddStateMachine::reallyWrite(const string& key ,long long number,AddResponse* response){ LOG(INFO) << "request message ,key:" << key << ",number:" << number; long long result = number; if (number_map_.find(key) == number_map_.end()) { number_map_.insert(make_pair(key,result)); } else { result += number_map_[key]; number_map_[key] = result; } LOG(INFO) << "reslut:" << result; if (response) { LOG(DEBUG) << "response isn't NULL,set response"; response->set_success(true); response->set_result(result); } } class AddServiceImpl :public AddService{ public: AddServiceImpl(AddStateMachine* sm,AddStateMachine* sm2):statemachine_(sm),statemachine2_(sm2) ,statemachine3_(NULL){ } void shutdown(){ if (statemachine3_ != NULL) { statemachine3_->shutdown(); } } void write(::google::protobuf::RpcController* controller, const ::example::AddRequest* request, ::example::AddResponse* response, ::google::protobuf::Closure* done) { brpc::ClosureGuard done_guard(done); if (request->key() == "key2") { statemachine2_->write(request,response, done_guard.release()); return; } if (request->key() == "key3") { if (statemachine3_ == NULL) { response->set_success(false); response->set_result(-1); response->set_redirect("statemachine3 can't start."); return; } statemachine3_->write(request,response, done_guard.release()); return; } statemachine_->write(request,response, done_guard.release()); return; } void start_new_statemachine(::google::protobuf::RpcController* controller, const ::example::NewStateMachineRequest* request, ::example::NewStateMachineResponse* response, ::google::protobuf::Closure* done){ brpc::ClosureGuard done_guard(done); statemachine3_ = new AddStateMachine(); if (statemachine3_->start(2) != 0) { LOG(ERROR) << "Fail to start state machine1"; response->set_success(false); return ; } response->set_success(true); } private: AddStateMachine* statemachine_; AddStateMachine* statemachine2_; AddStateMachine* statemachine3_; }; void AddClosure::Run(){ std::unique_ptr<AddClosure> self_guard(this); LOG(INFO) <<"done ptr:" <<done_; brpc::ClosureGuard done_guard(done_); if (status().ok()) { return; } statemachine_->redirect(response_); } } int main(int argc, char* argv[]){ gflags::SetVersionString("0.1"); gflags::SetUsageMessage("Usage: xxxx"); gflags::ParseCommandLineFlags(&argc, &argv, true); brpc::Server server; example::AddStateMachine statemachine; example::AddStateMachine statemachine2; example::AddServiceImpl service(&statemachine,&statemachine2); if (server.AddService(&service, brpc::SERVER_DOESNT_OWN_SERVICE) != 0) { LOG(ERROR) << "Fail to add service"; return -1; } if (braft::add_service(&server, FLAGS_port) != 0) { LOG(ERROR) << "Fail to add raft service"; return -1; } if (server.Start(FLAGS_port, NULL) != 0) { LOG(ERROR) << "Fail to start Server"; return -1; } if (statemachine.start(0) != 0) { LOG(ERROR) << "Fail to start state machine0"; return -1; } if (statemachine2.start(1) != 0) { LOG(ERROR) << "Fail to start state machine1"; return -1; } LOG(INFO) << "add service is running on " << server.listen_address(); while (!brpc::IsAskedToQuit()) { sleep(1); } LOG(INFO) << "add service is going to quit"; statemachine.shutdown(); statemachine2.shutdown(); service.shutdown(); server.Stop(0); statemachine.join(); statemachine2.join(); server.Join(); return 0; }
h(); snapshot_path.append("/data"); std::ifstream is(snapshot_path.c_str()); string key ; int64_t value = 0; while (is >> key >> value) { LOG(DEBUG) << "key:" << key << ",value:" << value; number_map_[key] = value; } return 0; }
function_block-function_prefixed
[]
C++
Wargame/Auth/Session.hpp
N00byEdge/best-wargame
35af9e00bad31c31eed4b902266e24dbf33a42ef
#pragma once #include <array> #include <random> #include <queue> #include "Wargame/Web/Network.hpp" #include "Wargame/Util.hpp" namespace Wargame { struct User; } namespace Auth { auto sessionTimeoutDuration = std::chrono::hours{24*7}; using SessionKey = std::array<char, 40>; constexpr char sessionChars[] { "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" }; SessionKey makeSessionKey() { SessionKey key; for(std::size_t i = 0; i < key.size(); ++ i) std::sample(std::begin(sessionChars), std::end(sessionChars) - 1, key.begin()+ i, 1, Util::rand); return key; } struct UserPtr: std::weak_ptr<Wargame::User> { bool operator<(UserPtr const &other) const { return owner_before(other); } }; struct ActiveSession { static constexpr std::size_t SessionIndex = 0; static constexpr std::size_t UserIndex = 1; SessionKey sessionKey; UserPtr user; mutable std::chrono::time_point<std::chrono::system_clock> lastActiveAt; mutable std::queue<SessionKey> csrfTokens; }; struct CSRFToken { static constexpr std::size_t SessionIndex = 0; static constexpr std::size_t TokenIndex = 1; SessionKey session; SessionKey token; std::string uri; }; } namespace std { template<size_t Ind> constexpr auto &get(Auth::ActiveSession &session) noexcept { if constexpr(Ind == Auth::ActiveSession::SessionIndex) return session.sessionKey; else if constexpr(Ind == Auth::ActiveSession::UserIndex) return session.user; } template<size_t Ind> constexpr auto &get(Auth::ActiveSession const &session) noexcept { if constexpr(Ind == Auth::ActiveSession::SessionIndex) return session.sessionKey; else if constexpr(Ind == Auth::ActiveSession::UserIndex) return session.user; } template<size_t Ind> constexpr auto &get(Auth::CSRFToken &session) noexcept { if constexpr(Ind == Auth::CSRFToken::SessionIndex) return session.session; else if constexpr(Ind == Auth::CSRFToken::TokenIndex) return session.token; } template<size_t Ind> constexpr auto &get(Auth::CSRFToken const &session) noexcept { if constexpr(Ind == Auth::CSRFToken::SessionIndex) return session.session; else if constexpr(Ind == Auth::CSRFToken::TokenIndex) return session.token; } } template<> struct std::tuple_size<Auth::ActiveSession>: std::integral_constant<std::size_t, 2> { }; template<> struct std::tuple_size<Auth::CSRFToken>: std::integral_constant<std::size_t, 2> { }; #include "CQL/Custom.hpp" namespace CQL::Custom { template<> struct Unique<Auth::ActiveSession, Auth::ActiveSession::SessionIndex> { constexpr Uniqueness operator()() const { return Uniqueness::EnforceUnique; } }; template<> struct Unique<Auth::ActiveSession, Auth::ActiveSession::UserIndex> { constexpr Uniqueness operator()() const { return Uniqueness::NotUnique; } }; template<> struct Unique<Auth::CSRFToken, Auth::CSRFToken::SessionIndex> { constexpr Uniqueness operator()() const { return Uniqueness::NotUnique; } }; template<> struct Unique<Auth::CSRFToken, Auth::CSRFToken::TokenIndex> { constexpr Uniqueness operator()() const { return Uniqueness::AssumeUnique; } }; } #include "CQL.hpp" namespace Auth { CQL::Table<ActiveSession> activeSessions; CQL::Table<CSRFToken> csrfTokens; ActiveSession const *getSession(SessionKey const &sKey) { auto session = activeSessions.lookup<ActiveSession::SessionIndex>(sKey); if(session) { auto timeSinceOnline = std::chrono::system_clock::now() - session->lastActiveAt; if(timeSinceOnline > sessionTimeoutDuration) activeSessions.erase(std::exchange(session, nullptr)); } return session; } void updateSession(ActiveSession const *ptr, UserPtr user) { activeSessions.update<ActiveSession::UserIndex>(ptr, user); ptr->lastActiveAt = std::chrono::system_clock::now(); } void updateSession(ActiveSession const *ptr) { updateSession(ptr, ptr->user); } ActiveSession const *updateSession(SessionKey const &sKey, UserPtr user = {}) { auto ptr = getSession(sKey); if(!ptr) { ptr = activeSessions.emplace(ActiveSession{sKey}); } updateSession(ptr, user); return ptr; } void invalidateCSRFToken(SessionKey const &csrf) { auto tok = csrfTokens.lookup<CSRFToken::TokenIndex>(csrf); if(tok) csrfTokens.erase(tok); } bool consumeCSRFToken(ActiveSession const &session, SessionKey const &csrf, std::string_view uri) { auto tok = csrfTokens.lookup<CSRFToken::TokenIndex>(csrf); bool valid = tok && tok->session == session.sessionKey && tok->uri == uri; if(valid) csrfTokens.erase(tok); return valid; } SessionKey makeCSRFForSession(ActiveSession const &session, std::string_view uri) { auto csrf = Auth::makeSessionKey(); auto token = csrfTokens.emplace(CSRFToken{session.sessionKey, csrf, std::string{uri}}); session.csrfTokens.emplace(csrf); if(session.csrfTokens.size() > 10) invalidateCSRFToken(session.csrfTokens.front()), session.csrfTokens.pop(); return csrf; } }
#pragma once #include <array> #include <random> #include <queue> #include "Wargame/Web/Network.hpp" #include "Wargame/Util.hpp" namespace Wargame { struct User; } namespace Auth { auto sessionTimeoutDuration = std::chrono::hours{24*7}; using SessionKey = std::array<char, 40>; constexpr char sessionChars[] { "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" }; SessionKey makeSessionKey() { SessionKey key; for(std::size_t i = 0; i < key.size(); ++ i) std::sample(std::begin(sessionChars), std::end(sessionChars) - 1, key.begin()+ i, 1, Util::rand); return key; } struct UserPtr: std::weak_ptr<Wargame::User> { bool operator<(UserPtr const &other) const { return owner_before(other); } }; struct ActiveSession { static constexpr std::size_t SessionIndex = 0; static constexpr std::size_t UserIndex = 1; SessionKey sessionKey; UserPtr user; mutable std::chrono::time_point<std::chrono::system_clock> lastActiveAt; mutable std::queue<SessionKey> csrfTokens; }; struct CSRFToken { static constexpr std::size_t SessionIndex = 0; static constexpr std::size_t TokenIndex = 1; SessionKey session; SessionKey token; std::string uri; }; } namespace std { template<size_t Ind> constexpr auto &get(Auth::ActiveSession &session) noexcept { if constexpr(Ind == Auth::ActiveSession::SessionIndex) return session.sessionKey; else if constexpr(Ind == Auth::ActiveSession::UserIndex) return session.user; } template<size_t Ind> constexpr auto &get(Auth::ActiveSession const &session) noexcept { if constexpr(Ind == Auth::ActiveSession::SessionIndex) return session.sessionKey; else if constexpr(Ind == Auth::ActiveSession::UserIndex) return session.user; } template<size_t Ind> constexpr auto &get(Auth::CSRFToken &session) noexcept { if constexpr(Ind == Auth::CSRFToken::SessionIndex) return session.session; else if constexpr(Ind == Auth::CSRFToken::TokenIndex) return session.token; } template<size_t Ind> constexpr auto &get(Auth::CSRFToken const &session) noexcept { if constexpr(Ind == Auth::CSRFToken::SessionIndex) return session.session; else if constexpr(Ind == Auth::CSRFToken::TokenIndex) return session.token; } } template<> struct std::tuple_size<Auth::ActiveSession>: std::integral_constant<std::size_t, 2> { }; template<> struct std::tuple_size<Auth::CSRFToken>: std::integral_constant<std::size_t, 2> { }; #include "CQL/Custom.hpp" namespace CQL::Custom { template<> struct Unique<Auth::ActiveSession, Auth::ActiveSession::SessionIndex> { constexpr Uniqueness operator()() const { return Uniqueness::EnforceUnique; } }; template<> struct Unique<Auth::ActiveSession, Auth::ActiveSession::UserIndex> { constexpr Uniqueness operator()() const { return Uniqueness::NotUnique; } }; template<> struct Unique<Auth::CSRFToken, Auth::CSRFToken::SessionIndex> { constexpr Uniqueness operator()() const { return Uniqueness::NotUnique; } }; template<> struct Unique<Auth::CSRFToken, Auth::CSRFToken::TokenIndex> { constexpr Uniqueness operator()() const { return Uniqueness::AssumeUnique; } }; } #include "CQL.hpp" namespace Auth { CQL::Table<ActiveSession> activeSessions; CQL::Table<CSRFToken> csrfTokens; ActiveSession const *getSession(SessionKey const &sKey) { auto session = activeSessions.lookup<ActiveSession::SessionIndex>(sKey);
return session; } void updateSession(ActiveSession const *ptr, UserPtr user) { activeSessions.update<ActiveSession::UserIndex>(ptr, user); ptr->lastActiveAt = std::chrono::system_clock::now(); } void updateSession(ActiveSession const *ptr) { updateSession(ptr, ptr->user); } ActiveSession const *updateSession(SessionKey const &sKey, UserPtr user = {}) { auto ptr = getSession(sKey); if(!ptr) { ptr = activeSessions.emplace(ActiveSession{sKey}); } updateSession(ptr, user); return ptr; } void invalidateCSRFToken(SessionKey const &csrf) { auto tok = csrfTokens.lookup<CSRFToken::TokenIndex>(csrf); if(tok) csrfTokens.erase(tok); } bool consumeCSRFToken(ActiveSession const &session, SessionKey const &csrf, std::string_view uri) { auto tok = csrfTokens.lookup<CSRFToken::TokenIndex>(csrf); bool valid = tok && tok->session == session.sessionKey && tok->uri == uri; if(valid) csrfTokens.erase(tok); return valid; } SessionKey makeCSRFForSession(ActiveSession const &session, std::string_view uri) { auto csrf = Auth::makeSessionKey(); auto token = csrfTokens.emplace(CSRFToken{session.sessionKey, csrf, std::string{uri}}); session.csrfTokens.emplace(csrf); if(session.csrfTokens.size() > 10) invalidateCSRFToken(session.csrfTokens.front()), session.csrfTokens.pop(); return csrf; } }
if(session) { auto timeSinceOnline = std::chrono::system_clock::now() - session->lastActiveAt; if(timeSinceOnline > sessionTimeoutDuration) activeSessions.erase(std::exchange(session, nullptr)); }
if_condition
[ { "content": "#pragma once\n\n\n\n#include \"Wargame/Auth/Passwords.hpp\"\n\n\n\nnamespace Auth {\n\n struct UserAuth {\n\n bool authenticate(std::string password) {\n\n auto attemptedHash = Auth::hashPassword(password, salt, hashIterations);\n\n return attemptedHash == passwordHash;\n\n }\n\n\n\n void setPassword(std::string_view const &password, int iterations) {\n\n passwordHash =\n\n Auth::hashPassword(password\n\n // User always gets a new salt on every password change\n\n , salt = Auth::randomizePasswordSalt()\n\n , hashIterations = iterations\n\n );\n\n }\n\n\n\n PasswordHash passwordHash;\n\n PasswordSalt salt;\n\n int hashIterations;\n\n };\n\n}\n", "file_path": "Wargame/Auth/UserAuth.hpp", "rank": 0, "score": 46029.02189986459 }, { "content": "#pragma once\n\n\n\n#include \"Wargame/Auth/UserAuth.hpp\"\n\n\n\nnamespace Wargame {\n\n constexpr int newUserIterations = 100'000;\n\n\n\n struct User {\n\n Auth::UserAuth auth;\n\n };\n\n}\n", "file_path": "Wargame/Game/User.hpp", "rank": 10, "score": 26819.55702655867 }, { "content": "#pragma once\n\n\n\n#include <array>\n\n#include <random>\n\n#include <string>\n\n#include <openssl/sha.h>\n\n\n\n#include \"Wargame/Util.hpp\"\n\n\n\nnamespace Auth {\n\n using PasswordSalt = std::array<unsigned char, SHA512_DIGEST_LENGTH>;\n\n using PasswordHash = std::array<unsigned char, SHA512_DIGEST_LENGTH>;\n\n\n\n PasswordHash hashPassword(std::string_view const &password, PasswordSalt const &salt, int iterations) {\n\n SHA512_CTX ctx;\n\n PasswordHash out;\n\n\n\n SHA512_Init(&ctx);\n\n SHA512_Update(&ctx, salt.data(), salt.size());\n\n SHA512_Update(&ctx, password.data(), password.size());\n", "file_path": "Wargame/Auth/Passwords.hpp", "rank": 11, "score": 25295.57600765442 }, { "content": " SHA512_Final(out.data(), &ctx);\n\n\n\n for(int i = 0; i < iterations; ++ i)\n\n SHA512(out.data(), out.size(), out.data());\n\n\n\n return out;\n\n }\n\n\n\n PasswordSalt randomizePasswordSalt() {\n\n PasswordSalt out;\n\n for(auto &c: out)\n\n c = Util::rand();\n\n return out;\n\n }\n\n}\n", "file_path": "Wargame/Auth/Passwords.hpp", "rank": 12, "score": 25285.735110112793 }, { "content": "#pragma once\n\n\n\n#include <array>\n\n#include <random>\n\n\n\nnamespace Util {\n\n inline static std::random_device rand{};\n\n\n\n template<std::size_t sz>\n\n std::string hexstr(std::array<unsigned char, sz> const &arr) {\n\n auto hex = [](char c) {\n\n return \"0123456789abcdef\"[c & 0xf];\n\n };\n\n \n\n std::string result;\n\n for(auto &v: arr) {\n\n result += hex(v >> 4);\n\n result += hex(v);\n\n }\n\n return result;\n\n }\n\n}\n", "file_path": "Wargame/Util.hpp", "rank": 13, "score": 9546.914924338445 }, { "content": "#pragma once\n\n\n\n#include <string>\n\n#include <sstream>\n\n#include <type_traits>\n\n\n\n#define FMT_HEADER_ONLY\n\n#include <fmt/ostream.h>\n\n\n\n#include \"Wargame/Auth/Session.hpp\"\n\n\n\nnamespace HTML {\n\n namespace Impl {\n\n template<char const *tag>\n\n struct SimpleTag {\n\n void operator()(std::stringstream &stream, std::string_view content) const {\n\n fmt::print(stream,\n\n \"<{0}>{1}</{0}>\",\n\n tag, content\n\n );\n", "file_path": "Wargame/Web/HTML.hpp", "rank": 14, "score": 8860.633778019459 }, { "content": "#pragma once\n\n\n\n#include <sstream>\n\n\n\n#include <mana/middleware/cookie_parser.hpp>\n\n\n\n#include \"Wargame/Web/HTML.hpp\"\n\n#include \"Wargame/Web/Network.hpp\"\n\n#include \"Wargame/Auth/Session.hpp\"\n\n#include \"Wargame/Auth/UserAuth.hpp\"\n\n\n\nnamespace Wargame {\n\n constexpr bool debugMiddleware = false;\n\n\n\n namespace Impl {\n\n mana::middleware::Cookie_parser cookieParser;\n\n }\n\n\n\n struct SessionAttribute: mana::Attribute {\n\n SessionAttribute(Auth::ActiveSession const *sess): session{sess} { }\n", "file_path": "Wargame/Web/Middleware.hpp", "rank": 15, "score": 8859.753032790517 }, { "content": "#pragma once\n\n\n\n#include <memdisk>\n\n#include <variant>\n\n\n\nnamespace Filesystem {\n\n static inline auto initFs = []() {\n\n fs::memdisk().init_fs([](bool err, auto &){assert(!err);});\n\n return std::monostate{};\n\n }();\n\n}\n", "file_path": "Wargame/Content/Filesystem.hpp", "rank": 16, "score": 8858.127159238367 }, { "content": "\n\n inline static const Impl::ArgTag<Impl::form> form;\n\n\n\n void csrfField(std::stringstream &stream, std::string_view const &csrfToken) {\n\n fmt::print(stream, R\"(<input type=\"hidden\" name=\"csrfToken\" value=\"{}\">)\", csrfToken);\n\n }\n\n\n\n template<typename F>\n\n void makeForm(\n\n std::stringstream &stream\n\n , std::string const &target\n\n , Auth::ActiveSession const &session\n\n , F &&f) {\n\n\n\n auto fWithCSRF = [&]() {\n\n auto csrf = Auth::makeCSRFForSession(session, target);\n\n csrfField(stream, {csrf.data(), csrf.size()});\n\n std::forward<F>(f)();\n\n };\n\n \n", "file_path": "Wargame/Web/HTML.hpp", "rank": 17, "score": 8856.499574433901 }, { "content": " request->set_attribute(std::make_shared<SessionAttribute>(session));\n\n stream->ss << HTML::doctype << R\"(<meta charset=\"utf-8\"/>)\";\n\n\n\n if(request->method() == http::POST) {\n\n Auth::SessionKey csrf;\n\n auto csrfString = request->source().post_value(\"csrfToken\");\n\n if(csrfString.size() != csrf.size())\n\n return;\n\n std::copy(csrfString.begin(), csrfString.end(), csrf.begin());\n\n auto uri = request->uri().path();\n\n if(!Auth::consumeCSRFToken(*session, csrf, uri)) {\n\n // Someone attempted CSRF; deny the POST.\n\n HTML::errorPage(stream->ss, \"Invalid CSRF token, try sending your request again.\");\n\n sendResponse();\n\n return;\n\n }\n\n }\n\n\n\n f();\n\n\n\n sendResponse();\n\n }\n\n}\n", "file_path": "Wargame/Web/Middleware.hpp", "rank": 18, "score": 8856.039715138835 }, { "content": "#pragma once\n\n\n\n#include <variant>\n\n\n\n#include \"Wargame/Util.hpp\"\n\n#include \"Wargame/Web/Router.hpp\"\n\n#include \"Wargame/Game/User.hpp\"\n\n#include \"Wargame/Web/Middleware.hpp\"\n\n\n\nnamespace Wargame {\n\n void registrationPage(std::stringstream &stream, Auth::ActiveSession const &session) {\n\n HTML::makeForm(stream, \"/signup\", session, [&](){\n\n HTML::title(stream, \"Best wargame - Sign up\");\n\n HTML::div(stream, \"\", [&]() {\n\n HTML::h1(stream, \"Registration\");\n\n HTML::p (stream, \"Fill in the following fields to complete your registration\");\n\n stream << HTML::hr;\n\n HTML::labelledInputField(stream, \"username\", \"Username\", \"Enter username\", \"text\", true);\n\n stream << HTML::br;\n\n HTML::labelledInputField(stream, \"password\", \"Password\", \"Enter password\", \"password\", true);\n", "file_path": "Wargame/Game/Game.hpp", "rank": 19, "score": 8855.630344775538 }, { "content": " }\n\n\n\n template<typename F>\n\n std::enable_if_t<!std::is_convertible_v<F, std::string>, void>\n\n operator()(std::stringstream &stream, F &&f) const {\n\n fmt::print(stream, \"<{}>\", tag);\n\n f();\n\n fmt::print(stream, \"</{}>\", tag);\n\n }\n\n };\n\n\n\n inline static char const h1[] = \"h1\";\n\n inline static char const h2[] = \"h2\";\n\n inline static char const h3[] = \"h3\";\n\n inline static char const h4[] = \"h4\";\n\n\n\n inline static char const title[] = \"title\";\n\n inline static char const p[] = \"p\";\n\n inline static char const b[] = \"b\";\n\n\n", "file_path": "Wargame/Web/HTML.hpp", "rank": 20, "score": 8855.305408187927 }, { "content": " template<char const *tag>\n\n struct ArgTag {\n\n void operator()(std::stringstream &stream, std::string const &arg, std::string_view content) const {\n\n fmt::print(stream,\n\n \"<{0}{1}>{2}</{0}>\",\n\n tag, arg.empty() ? \"\" : ' ' + arg, content\n\n );\n\n }\n\n\n\n template<typename F>\n\n std::enable_if_t<!std::is_convertible_v<F, std::string>, void>\n\n operator()(std::stringstream &stream, std::string const &arg, F &&f) const {\n\n fmt::print(stream, \"<{}{}>\", tag, arg.empty() ? \"\" : ' ' + arg);\n\n f();\n\n fmt::print(stream, \"</{}>\", tag);\n\n }\n\n };\n\n\n\n inline static char const a[] = \"a\";\n\n inline static char const form[] = \"form\";\n", "file_path": "Wargame/Web/HTML.hpp", "rank": 21, "score": 8854.910774085152 }, { "content": " \n\n Auth::SessionKey sKey{};\n\n Auth::ActiveSession const *session = nullptr;\n\n auto cookies = request->get_attribute<mana::attribute::Cookie_jar>();\n\n\n\n if constexpr(debugMiddleware)\n\n printf(\"Cookies parsed!\\n\");\n\n\n\n if(cookies && cookies->cookie_value(\"sKey\").size() == sKey.size()) {\n\n auto sKeyStr = cookies->cookie_value(\"sKey\");\n\n \n\n if constexpr(debugMiddleware)\n\n printf(\"Session key cookie found: %s!\\n\", sKeyStr.c_str());\n\n\n\n std::copy(sKeyStr.begin(), sKeyStr.end(), sKey.begin());\n\n\n\n session = Auth::getSession(sKey);\n\n if(!session) {\n\n if constexpr(debugMiddleware)\n\n printf(\"Creating new session!\\n\");\n", "file_path": "Wargame/Web/Middleware.hpp", "rank": 22, "score": 8854.77763128446 }, { "content": "#pragma once\n\n\n\n#include <mana/request.hpp>\n\n#include <mana/response.hpp>\n\n\n\nnamespace Networking {\n\n using Request = mana::Request_ptr;\n\n using Response = mana::Response_ptr;\n\n}\n", "file_path": "Wargame/Web/Network.hpp", "rank": 23, "score": 8853.981404824648 }, { "content": "#pragma once\n\n\n\n#include <mana/router.hpp>\n\n\n\nnamespace Networking {\n\n inline static mana::Router router;\n\n}\n", "file_path": "Wargame/Web/Router.hpp", "rank": 24, "score": 8853.914623892812 }, { "content": " session = Auth::updateSession(sKey = Auth::makeSessionKey());\n\n response->cookie(http::Cookie{\"sKey\", {sKey.begin(), sKey.end()}});\n\n }\n\n else {\n\n if constexpr(debugMiddleware)\n\n printf(\"Updating session!\\n\");\n\n Auth::updateSession(session);\n\n }\n\n } else {\n\n if constexpr(debugMiddleware)\n\n printf(\"Created and sending new session key.\\n\");\n\n\n\n sKey = Auth::makeSessionKey();\n\n response->cookie(http::Cookie{\"sKey\", {sKey.begin(), sKey.end()}});\n\n session = Auth::updateSession(sKey);\n\n }\n\n \n\n if constexpr(debugMiddleware)\n\n printf(\"Setting session attribute.\\n\");\n\n\n", "file_path": "Wargame/Web/Middleware.hpp", "rank": 25, "score": 8853.518208033895 }, { "content": " Auth::ActiveSession const *session;\n\n };\n\n\n\n struct StreamAttribute: mana::Attribute {\n\n StreamAttribute() = default;\n\n std::stringstream ss;\n\n };\n\n\n\n template<typename F>\n\n void middleware(Networking::Request &request, Networking::Response &response, F &&f) {\n\n Impl::cookieParser.process(request, response, std::make_shared<mana::next_t>([](){}));\n\n\n\n auto stream = std::make_shared<StreamAttribute>();\n\n request->set_attribute(stream);\n\n\n\n auto sendResponse =\n\n [&]() {\n\n response->writer().write(stream->ss.str());\n\n response->writer().write();\n\n };\n", "file_path": "Wargame/Web/Middleware.hpp", "rank": 26, "score": 8852.527211201284 }, { "content": " inline static char const div[] = \"div\";\n\n inline static char const button[] = \"button\";\n\n inline static char const label[] = \"label\";\n\n }\n\n\n\n inline static const Impl::SimpleTag<Impl::h1> h1;\n\n inline static const Impl::SimpleTag<Impl::h2> h2;\n\n inline static const Impl::SimpleTag<Impl::h3> h3;\n\n inline static const Impl::SimpleTag<Impl::h4> h4;\n\n\n\n inline static const Impl::SimpleTag<Impl::title> title;\n\n inline static const Impl::SimpleTag<Impl::p> p;\n\n inline static const Impl::SimpleTag<Impl::b> b;\n\n\n\n inline static const Impl::ArgTag<Impl::a> a;\n\n\n\n template<typename F>\n\n void href(std::stringstream &stream, std::string const &target, F &&f) {\n\n a(stream, \"href=\\\"\" + target + '\\\"', std::forward<F>(f));\n\n };\n", "file_path": "Wargame/Web/HTML.hpp", "rank": 27, "score": 8852.393932862522 }, { "content": " Networking::router.on_post(\"/signup\",\n\n [](Networking::Request request, Networking::Response response) {\n\n auto stream = request->get_attribute<Wargame::StreamAttribute>();\n\n auto uname = request->source().post_value(\"username\");\n\n auto pwd = request->source().post_value(\"password\");\n\n auto pwd_conf = request->source().post_value(\"password_conf\");\n\n\n\n if(pwd != pwd_conf) {\n\n HTML::errorPage(stream->ss, \"Passwords do not match!\");\n\n return;\n\n }\n\n\n\n if(pwd.empty()) {\n\n HTML::errorPage(stream->ss, \"Password cannot be empty!\");\n\n return;\n\n }\n\n\n\n Auth::UserAuth auth;\n\n auth.setPassword(pwd, newUserIterations);\n\n fmt::print(stream->ss,\n", "file_path": "Wargame/Game/Game.hpp", "rank": 28, "score": 8851.971020898507 }, { "content": " }\n\n\n\n template<typename F>\n\n void doPage(Networking::Request &request, Networking::Response &response, F &&f) {\n\n auto &session = *request->get_attribute<SessionAttribute>()->session;\n\n auto &stream = request->get_attribute<Wargame::StreamAttribute>()->ss;\n\n f(stream, session);\n\n }\n\n\n\n auto addGameRoutes = []() {\n\n Networking::router.on_get(\"/\",\n\n [](Networking::Request request, Networking::Response response) {\n\n doPage(request, response, homepage);\n\n });\n\n\n\n Networking::router.on_get(\"/signup\",\n\n [](Networking::Request request, Networking::Response response) {\n\n doPage(request, response, registrationPage);\n\n });\n\n\n", "file_path": "Wargame/Game/Game.hpp", "rank": 29, "score": 8851.705709484928 }, { "content": " form(stream, \"action=\\\"\" + target + \"\\\" method=\\\"post\\\"\", fWithCSRF);\n\n };\n\n\n\n inline static const Impl::ArgTag<Impl::div> div;\n\n inline static const Impl::ArgTag<Impl::button> button;\n\n inline static const Impl::ArgTag<Impl::label> label;\n\n\n\n inline static char const br[] = \"<br>\";\n\n inline static char const hr[] = \"<hr>\";\n\n\n\n std::string doctype = \"<!DOCTYPE html>\";\n\n\n\n void errorPage(std::stringstream &stream, std::string const &errorString) {\n\n title(stream, \"Error\");\n\n h1(stream, errorString);\n\n }\n\n\n\n void labelledInputField(std::stringstream &stream\n\n , std::string &&nameStr\n\n , std::string &&labelStr\n", "file_path": "Wargame/Web/HTML.hpp", "rank": 30, "score": 8851.485953681175 }, { "content": " stream << HTML::br;\n\n HTML::labelledInputField(stream, \"password_conf\", \"Repeat password\", \"Repeat password\", \"password\", true);\n\n stream << HTML::hr,\n\n HTML::button(stream, \"type=\\\"submit\\\"\", \"Sign up\");\n\n });\n\n });\n\n }\n\n\n\n void homepage(std::stringstream &stream, Auth::ActiveSession const &session) {\n\n HTML::title(stream, \"Best wargame\");\n\n HTML::h1(stream, \"Homepage\");\n\n if(session.user.lock()) {\n\n HTML::href(stream, \"/game\", \"Go to game\");\n\n stream << HTML::br;\n\n HTML::href(stream, \"/logout\", \"Log out\");\n\n } else {\n\n HTML::href(stream, \"/signup\", \"Sign up\");\n\n stream << HTML::br;\n\n HTML::href(stream, \"/login\", \"Login\");\n\n }\n", "file_path": "Wargame/Game/Game.hpp", "rank": 31, "score": 8851.132488348061 }, { "content": " , std::string &&placeholderStr\n\n , std::string &&typeStr\n\n , bool required) {\n\n fmt::print(stream,\n\n R\"(<label for=\"{}\">{}</label><br>)\"\n\n R\"(<input type=\"{}\" placeholder=\"{}\" name=\"{}\"{}>)\",\n\n nameStr, std::move(labelStr),\n\n std::move(typeStr), std::move(placeholderStr), nameStr, required ? \" required\" : \"\"\n\n );\n\n }\n\n}\n", "file_path": "Wargame/Web/HTML.hpp", "rank": 32, "score": 8849.520589825264 }, { "content": " \"Success!<br>\"\n\n \"Password hash: <pre>{}</pre><br>\"\n\n \"Password salt: <pre>{}</pre><br>\"\n\n ,\n\n Util::hexstr(auth.passwordHash),\n\n Util::hexstr(auth.salt)\n\n );\n\n });\n\n\n\n return std::monostate{};\n\n }();\n\n}\n", "file_path": "Wargame/Game/Game.hpp", "rank": 33, "score": 8849.311893780932 }, { "content": "#include <os>\n\n#include <https>\n\n#include <net/interfaces>\n\n\n\n#include <mana/middleware/cookie_parser.hpp>\n\n\n\n#include \"Wargame/Content/Filesystem.hpp\"\n\n#include \"Wargame/Game/Game.hpp\"\n\n#include \"Wargame/Web/Middleware.hpp\"\n\n\n\nnamespace {\n\n auto &inet = net::Interfaces::get(0);\n\n\n\n using WebServer = std::unique_ptr<http::Server>;\n\n struct {\n\n WebServer httpServer, httpsServer;\n\n } webServers;\n\n \n\n void dispatchRequest(Networking::Request &&request, Networking::Response &&response) {\n\n Wargame::middleware(request, response,\n", "file_path": "service.cpp", "rank": 34, "score": 9.471137845953317 }, { "content": " [](net::Inet::Stack &) {\n\n auto makeServer = [](WebServer &server, auto ssl, int port) {\n\n if constexpr(std::is_same_v<decltype(ssl), decltype(UseSSL)>) {\n\n static_assert(std::is_same_v<decltype(Filesystem::initFs), std::monostate>,\n\n \"Filesystem not loaded!\");\n\n server = std::make_unique<http::OpenSSL_server>(\"/ssl.pem\", \"/ssl.key\", inet.tcp());\n\n } else {\n\n server = std::make_unique<http::Server>(inet.tcp());\n\n }\n\n\n\n server->on_request(\n\n [](http::Request_ptr request, http::Response_writer_ptr response) {\n\n dispatchRequest(\n\n std::make_shared<mana::Request>(std::move(request)),\n\n std::make_shared<mana::Response>(std::move(response))\n\n );\n\n });\n\n\n\n server->listen(port);\n\n };\n", "file_path": "service.cpp", "rank": 35, "score": 7.40845305811262 }, { "content": " [&](){\n\n try {\n\n auto route = Networking::router.match(request->method(), request->uri().to_string());\n\n route.job(request, response);\n\n }\n\n catch(mana::Router_error) {\n\n auto &stream = request->get_attribute<Wargame::StreamAttribute>()->ss;\n\n HTML::errorPage(stream, \"Page not found.\");\n\n }\n\n });\n\n }\n\n}\n\n\n\nstruct {} UseSSL;\n\nstruct {} NoSSL;\n\n\n\nvoid Service::start() {\n\n Networking::router.optimize_route_search();\n\n\n\n inet.on_config(\n", "file_path": "service.cpp", "rank": 36, "score": 5.429883036488192 }, { "content": "\n\n makeServer(webServers.httpServer, NoSSL, 80);\n\n makeServer(webServers.httpsServer, UseSSL, 443);\n\n });\n\n\n\n inet.negotiate_dhcp(3.0,\n\n [](bool timeout){\n\n if(timeout) {\n\n printf(\"DHCP negotiation failed, falling back to static assignment.\\n\");\n\n inet.network_config(\n\n {10,0,0,69},\n\n {255,255,255,0},\n\n {10,0,0,1},\n\n {1,1,1,1}\n\n );\n\n }\n\n });\n\n}\n", "file_path": "service.cpp", "rank": 37, "score": 4.599404276341998 } ]
C++
requests/requestexecutor.cpp
aghoward/dbpp
b55f1f3d70ea3f0a8d6058ab0ba3b4d5a568b802
#include "requests/requestexecutor.h" #include <algorithm> #include <cstdio> #include <memory> #include <optional> #include <string> #include <vector> #include <cpr/cpr.h> #include "parameters/arguments.h" #include "multi-threading/threadpool.h" #include "multi-threading/workqueue.h" #include "requests/executioncontext.h" #include "requests/requestfactory.h" #include "support/fileio.h" #include "support/template_formatting.h" bool RequestExecutor::status_code_indicates_existance(const int status_code) const { return std::find( _args.ignore_codes.begin(), _args.ignore_codes.end(), static_cast<uint16_t>(status_code)) == _args.ignore_codes.end(); } bool RequestExecutor::passes_content_length_check(const uint32_t content_length) const { return std::find( _args.ignore_content_lengths.begin(), _args.ignore_content_lengths.end(), static_cast<uint32_t>(content_length)) == _args.ignore_content_lengths.end(); } uint32_t get_content_length(cpr::Response& response) { return std::atoi(response.header["Content-Length"].c_str()); } bool RequestExecutor::response_passes_checks(cpr::Response& response) const { return status_code_indicates_existance(response.status_code) && passes_content_length_check(get_content_length(response)); } cpr::Response RequestExecutor::get_response( const std::string& url, const std::string& data, const std::map<std::string, std::string>& templates) { using namespace std::string_literals; if (data == ""s) _context->logger.log("Trying: \""s + url + "\"\r"s); else _context->logger.log("Trying: \""s + url + "\" - \"" + data + "\"\r"s); return _context->request_factory.make_request(url, data, templates); } std::optional<std::string> RequestExecutor::execute(const std::string& item, const std::string& request_template) { using namespace std::string_literals; auto templates = std::map<std::string, std::string>{{"{WORD}"s, item}, {"{BASE_URL}"s, _context->base_url}}; auto url = format_template(request_template, templates); auto data = format_template(_context->request_data, templates); auto response = get_response(url, data, templates); if (response_passes_checks(response)) { auto message_addendum = (data != ""s) ? "\" - \""s + data : ""s; _context->logger.log_line( "\""s + url + message_addendum + "\" - "s + std::to_string(get_content_length(response)) + " (CL) - "s + std::to_string(response.status_code) + " (S)"s); return url; } return {}; } std::vector<std::string> RequestExecutor::execute(const std::string& item) { auto results = std::vector<std::string>(); for (const auto& request_template : _context->request_templates) { auto result = execute(item, request_template); if (result) results.push_back(result.value()); } return results; } std::shared_ptr<WorkQueue<std::string>> RequestExecutor::create_work_queue(std::size_t queue_size) const { auto word_list = get_word_list(_args.wordlist_file); auto work_pool = std::make_shared<WorkQueue<std::string>>(queue_size); work_pool->add_items(word_list.begin(), word_list.end()); return work_pool; } std::vector<std::string> RequestExecutor::search(const std::vector<std::string>& request_templates) { using namespace std::string_literals; _context = std::make_shared<ExecutionContext>(_args.base_url, request_templates, _request_factory, _args.ignore_codes, _args.request_body); auto work_pool = create_work_queue(_args.thread_count); std::function work_func = [&](const std::string& item) { return execute(item); }; auto thread_pool = ThreadPool(work_func, work_pool); auto pool_results = thread_pool.execute(); auto found_items = std::vector<std::string>{}; for (const auto& pool_result : pool_results) found_items.insert(found_items.end(), pool_result.begin(), pool_result.end()); _context->logger.log_line(); return found_items; } void RequestExecutor::search() { search(_args.request_templates); } void RequestExecutor::recursive_search() { using namespace std::string_literals; auto urls = search(_args.request_templates); while (!urls.empty()) { auto url = urls.back(); urls.pop_back(); auto new_template = url + "/{WORD}"s; auto results = search({new_template}); urls.insert(urls.end(), results.begin(), results.end()); } }
#include "requests/requestexecutor.h" #include <algorithm> #include <cstdio> #include <memory> #include <optional> #include <string> #include <vector> #include <cpr/cpr.h> #include "parameters/arguments.h" #include "multi-threading/threadpool.h" #include "multi-threading/workqueue.h" #include "requests/executioncontext.h" #include "requests/requestfactory.h" #include "support/fileio.h" #include "support/template_formatting.h" bool RequestExecutor::status_code_indicates_existance(const int status_code) const { return std::find( _args.ignore_codes.begin(), _args.ignore_codes.end(), static_cast<uint16_t>(status_code)) == _args.ignore_codes.end(); } bool RequestExecutor::passes_content_length_check(const uint32_t content_length) const { return std::find( _args.ignore_content_lengths.begin(), _args.ignore_content_lengths.end(), static_cast<uint32_t>(content_length)) == _args.ignore_content_lengths.end(); } uint32_t get_content_length(cpr::Response& response) { return std::atoi(response.header["Content-Length"].c_str()); } bool RequestExecutor::response_passes_checks(cpr::Response& response) const { return status_code_indicates_existance(response.status_code) && passes_content_length_check(get_content_length(response)); } cpr::Response RequestExecutor::get_response( const std::string& url, const std::string& data, const std::map<std::string, std::string>& templates) { using namespace std::string_literals; if (data == ""s) _context->logger.log("Trying: \""s + url + "\"\r"s); else _context->logger.log("Trying: \""s + url + "\" - \"" + data + "\"\r"s); return _context->request_factory.make_request(url, data, templates); } std::optional<std::string> RequestExecutor::execute(const std::string& item, const std::string& request_template) { using namespace std::string_literals; auto templates = std::map<std::string, std::string>{{"{WORD}"s, item}, {"{BASE_URL}"s, _context->base_url}}; auto url = format_template(request_template, templates); auto data = format_template(_context->request_data, templates); auto response = get_response(url, data, templates); if (response_passes_checks(response)) { auto message_addendum = (data != ""s) ? "\" - \""s + data : ""s; _context->logger.log_line( "\""s + url + message_addendum + "\" - "s + std::to_string(get_content_length(response)) + " (CL) - "s + std::to_string(response.status_code) + " (S)"s); return url; } return {}; }
std::shared_ptr<WorkQueue<std::string>> RequestExecutor::create_work_queue(std::size_t queue_size) const { auto word_list = get_word_list(_args.wordlist_file); auto work_pool = std::make_shared<WorkQueue<std::string>>(queue_size); work_pool->add_items(word_list.begin(), word_list.end()); return work_pool; } std::vector<std::string> RequestExecutor::search(const std::vector<std::string>& request_templates) { using namespace std::string_literals; _context = std::make_shared<ExecutionContext>(_args.base_url, request_templates, _request_factory, _args.ignore_codes, _args.request_body); auto work_pool = create_work_queue(_args.thread_count); std::function work_func = [&](const std::string& item) { return execute(item); }; auto thread_pool = ThreadPool(work_func, work_pool); auto pool_results = thread_pool.execute(); auto found_items = std::vector<std::string>{}; for (const auto& pool_result : pool_results) found_items.insert(found_items.end(), pool_result.begin(), pool_result.end()); _context->logger.log_line(); return found_items; } void RequestExecutor::search() { search(_args.request_templates); } void RequestExecutor::recursive_search() { using namespace std::string_literals; auto urls = search(_args.request_templates); while (!urls.empty()) { auto url = urls.back(); urls.pop_back(); auto new_template = url + "/{WORD}"s; auto results = search({new_template}); urls.insert(urls.end(), results.begin(), results.end()); } }
std::vector<std::string> RequestExecutor::execute(const std::string& item) { auto results = std::vector<std::string>(); for (const auto& request_template : _context->request_templates) { auto result = execute(item, request_template); if (result) results.push_back(result.value()); } return results; }
function_block-full_function
[ { "content": "#include \"support/template_formatting.h\"\n\n\n\n#include <string>\n\n#include <map>\n\n#include <utility>\n\n\n\nnamespace impl\n\n{\n\n std::string format_single(const std::string& _template, const std::pair<std::string, std::string>& replacement)\n\n {\n\n auto result = _template;\n\n auto index = 0ul;\n\n while ((index = result.find(replacement.first)) != std::string::npos)\n\n result.replace(index, replacement.first.size(), replacement.second);\n\n\n\n return result;\n\n }\n\n}\n\n\n\nstd::string format_template(const std::string& _template, const std::map<std::string, std::string>& replacements)\n\n{\n\n auto result = _template;\n\n for (const auto& replacement : replacements)\n\n result = impl::format_single(result, replacement);\n\n return result;\n\n} \n", "file_path": "support/template_formatting.cpp", "rank": 0, "score": 22838.637904644133 }, { "content": "#include <algorithm>\n\n#include <cctype>\n\n#include <cstdio>\n\n#include <functional>\n\n#include <iterator>\n\n#include <numeric>\n\n#include <string>\n\n#include <tuple>\n\n#include <vector>\n\n\n\n#include \"parameters/parameter_conversions.h\"\n\n#include \"models/header.h\"\n\n\n\nnamespace impl {\n\n template <typename It, typename TItem>\n\n std::vector<TItem> parse_range(const It& begin, const It& end, const std::function<TItem(std::string)>& converter)\n\n {\n\n auto token_it = std::find_if(begin, end, [] (const auto& c) { return c == '-'; });\n\n\n\n auto lhs = converter({begin, token_it});\n", "file_path": "parameters/parameter_conversions.cpp", "rank": 2, "score": 16.15714598903447 }, { "content": "#pragma once\n\n\n\n#include <algorithm>\n\n#include <cstddef>\n\n#include <list>\n\n#include <type_traits>\n\n#include <vector>\n\n\n\ntemplate <typename T>\n\nusing remove_cvref_t = std::remove_cv_t<std::remove_reference_t<T>>;\n\n\n\ntemplate <typename TWorkItem>\n", "file_path": "multi-threading/workqueue.h", "rank": 7, "score": 12.184019089432086 }, { "content": "#include \"requestfactory.h\"\n\n\n\n#include <map>\n\n#include <string>\n\n#include <functional>\n\n\n\n#include <cpr/cpr.h>\n\n\n\n#include \"requests/requestmethod.h\"\n\n#include \"support/template_formatting.h\"\n\n\n\ncpr::Response RequestFactory::make_request(\n\n const std::string& url,\n\n const std::string& data,\n\n const std::map<std::string, std::string>& templates)\n\n{\n\n return _make_request_with_data(\n\n data,\n\n cpr::Url(url),\n\n cpr::VerifySsl(_verify_ssl),\n", "file_path": "requests/requestfactory.cpp", "rank": 8, "score": 12.040942246430738 }, { "content": "#include <fstream>\n\n#include <string>\n\n#include <vector>\n\n\n\n#include \"fileio.h\"\n\n\n\nstd::vector<std::string> get_word_list(const std::string& file)\n\n{\n\n using namespace std::string_literals;\n\n\n\n auto words = std::vector<std::string>();\n\n std::ifstream fs(file);\n\n std::string str;\n\n\n\n while (std::getline(fs, str))\n\n if (str != \"\"s)\n\n words.push_back(str);\n\n \n\n return words;\n\n}\n\n\n", "file_path": "support/fileio.cpp", "rank": 9, "score": 11.614803858598457 }, { "content": "#include <algorithm>\n\n#include <fstream>\n\n#include <iostream>\n\n#include <iterator>\n\n#include <string>\n\n#include <vector>\n\n\n\n#include \"argparsing/argparsing.h\"\n\n#include \"requests/requestexecutor.h\"\n\n\n\nint main(int argc, const char * argv[])\n\n{\n\n auto parser = createArgumentParser();\n\n auto argresult = parser.parse(argc, argv);\n\n\n\n return argresult.match(\n\n [&] (const auto& args) {\n\n if (args.help) {\n\n std::cout << parser.help(argv[0]) << std::endl;\n\n return 0;\n", "file_path": "db++.cpp", "rank": 10, "score": 11.567721001753384 }, { "content": "#pragma once\n\n\n\n#include \"workqueue.h\"\n\n\n\n#include <chrono>\n\n#include <memory>\n\n#include <optional>\n\n#include <thread>\n\n\n\ntemplate <typename TWorkItem, typename TResultItem, typename TWorkFunc>\n", "file_path": "multi-threading/worker.h", "rank": 11, "score": 11.15104432222238 }, { "content": "#pragma once\n\n\n\n#include <memory>\n\n#include <optional>\n\n#include <string>\n\n#include <vector>\n\n\n\n#include <cpr/cpr.h>\n\n\n\n#include \"parameters/arguments.h\"\n\n#include \"requests/executioncontext.h\"\n\n#include \"requests/requestfactory.h\"\n\n#include \"multi-threading/workqueue.h\"\n\n\n", "file_path": "requests/requestexecutor.h", "rank": 13, "score": 10.492373597076677 }, { "content": "#pragma once\n\n\n\n#include <cstddef>\n\n#include <future>\n\n#include <memory>\n\n#include <type_traits>\n\n#include <utility>\n\n#include <vector>\n\n\n\n#include \"worker.h\"\n\n#include \"workqueue.h\"\n\n\n\ntemplate <typename TWorkItem, typename TWorkFunc, typename TResultItem = std::invoke_result_t<TWorkFunc, TWorkItem>>\n", "file_path": "multi-threading/threadpool.h", "rank": 14, "score": 10.150440439273346 }, { "content": " out << \"request_templates: \";\n\n for (auto& request_template : args.request_templates)\n\n out << '\"' << request_template << \"\\\" \";\n\n out << '\\n';\n\n\n\n if (args.headers.size() > 0)\n\n {\n\n out << \"headers: \\n\";\n\n for (auto& header : args.headers)\n\n out << \"\\t'\" << header.name << \"' = '\" << header.value << \"'\" << '\\n';\n\n out << '\\n';\n\n }\n\n\n\n return out;\n\n}\n\n\n\nap::ArgumentParser<Arguments> createArgumentParser()\n\n{\n\n using namespace std::string_literals;\n\n\n", "file_path": "parameters/arguments.cpp", "rank": 15, "score": 9.358892999972477 }, { "content": "#include <iostream>\n\n#include <string>\n\n\n\n#include \"parameters/arguments.h\"\n\n#include \"argparsing/argparsing.h\"\n\n#include \"parameters/parameter_conversions.h\"\n\n#include \"requests/requestmethod.h\"\n\n\n\nstd::ostream& operator<<(std::ostream& out, const Arguments& args)\n\n{\n\n using namespace std::string_literals;\n\n\n\n out << \"base_url: \" << args.base_url << '\\n';\n\n\n\n out << \"request_method: \";\n\n if (args.request_method == RequestMethod::DEFAULT && args.request_body != \"\"s)\n\n out << RequestMethod::POST << '\\n';\n\n else\n\n out << args.request_method << '\\n';\n\n\n", "file_path": "parameters/arguments.cpp", "rank": 16, "score": 9.330068454298077 }, { "content": " bool verify_ssl,\n\n const RequestMethod& request_method,\n\n const std::string& content_type,\n\n const std::vector<Header>& headers)\n\n :\n\n _user(user),\n\n _pass(pass),\n\n _verify_ssl(verify_ssl),\n\n _request_method(request_method),\n\n _content_type(content_type),\n\n _headers(headers)\n\n {}\n\n\n\n cpr::Response make_request(\n\n const std::string& url,\n\n const std::string& body_data,\n\n const std::map<std::string, std::string>& templates);\n\n};\n", "file_path": "requests/requestfactory.h", "rank": 17, "score": 9.255070288273405 }, { "content": " _create_header(templates));\n\n}\n\n\n\ncpr::Header RequestFactory::_create_header(const std::map<std::string, std::string>& templates) const\n\n{\n\n using namespace std::string_literals;\n\n\n\n std::map<std::string, std::string> map = {};\n\n if (_content_type != \"\"s)\n\n map[\"Content-Type\"s] = _content_type;\n\n\n\n for (const auto& header : _headers)\n\n map[format_template(header.name, templates)] = format_template(header.value, templates);\n\n\n\n return cpr::Header(map.begin(), map.end());\n\n}\n", "file_path": "requests/requestfactory.cpp", "rank": 18, "score": 8.755496639691572 }, { "content": " auto rhs = converter({token_it + 1, end});\n\n\n\n auto min = std::min(lhs, rhs);\n\n auto max = std::max(lhs, rhs);\n\n auto size = max - min;\n\n auto result = std::vector<TItem>(static_cast<uint32_t>(size));\n\n\n\n std::iota(std::begin(result), std::end(result), min);\n\n return result;\n\n }\n\n\n\n template <typename It, typename TItem>\n\n std::vector<TItem> parse_values(const It& begin, const It& end, const std::function<TItem(std::string)>& converter)\n\n {\n\n auto hyphen_it = std::find_if(begin, end, [] (const auto& c) { return c == '-'; });\n\n if (hyphen_it != end)\n\n return parse_range<decltype(begin), TItem>(begin, end, converter);\n\n return { converter({begin, end}) };\n\n }\n\n\n", "file_path": "parameters/parameter_conversions.cpp", "rank": 19, "score": 8.563610684063272 }, { "content": " template <typename TItem>\n\n std::vector<TItem> parse_status_code_list(const std::string& parameter, std::function<TItem(std::string)> converter)\n\n {\n\n auto result = std::vector<TItem>();\n\n auto comma_it = std::find_if(std::begin(parameter), std::end(parameter), [] (const auto& c) { return c == ','; });\n\n auto begin = std::begin(parameter);\n\n while (comma_it != std::end(parameter))\n\n {\n\n auto elements = parse_values<decltype(begin), TItem>(begin, comma_it, converter);\n\n result.insert(std::end(result), std::begin(elements), std::end(elements));\n\n\n\n begin = comma_it + 1;\n\n comma_it = std::find_if(begin, std::end(parameter), [] (const auto& c) { return c == ','; });\n\n }\n\n\n\n auto elements = parse_values<decltype(begin), TItem>(begin, std::end(parameter), converter);\n\n result.insert(std::end(result), std::begin(elements), std::end(elements));\n\n\n\n return result;\n\n }\n", "file_path": "parameters/parameter_conversions.cpp", "rank": 20, "score": 8.367552294767943 }, { "content": " template <typename TIter>\n\n void add_items(TIter begin, TIter end)\n\n {\n\n std::for_each(begin, end, [&] (auto&& item) { this->add_item(item); });\n\n }\n\n \n\n TWorkItem take_item(std::size_t worker_id)\n\n {\n\n auto item = _work_pool[worker_id].front();\n\n _work_pool[worker_id].pop_front();\n\n return item;\n\n }\n\n\n\n bool work_available(std::size_t worker_id) const\n\n {\n\n return !_work_pool[worker_id].empty();\n\n }\n\n\n\n bool is_empty() const\n\n {\n", "file_path": "multi-threading/workqueue.h", "rank": 22, "score": 7.958492067999423 }, { "content": "\n\n std::vector<std::string> parse_request_template_list(const std::string& parameter)\n\n {\n\n auto result = std::vector<std::string>();\n\n auto comma_it = std::find_if(std::begin(parameter), std::end(parameter), [] (const auto& c) { return c == ','; });\n\n auto begin = std::begin(parameter);\n\n while (comma_it != std::end(parameter))\n\n {\n\n auto element = std::string(begin, comma_it);\n\n result.push_back(element);\n\n\n\n begin = comma_it + 1;\n\n comma_it = std::find_if(begin, std::end(parameter), [] (const auto& c) { return c == ','; });\n\n }\n\n\n\n auto element = std::string(begin, comma_it);\n\n result.push_back(element);\n\n\n\n return result;\n\n }\n", "file_path": "parameters/parameter_conversions.cpp", "rank": 23, "score": 7.595206932141256 }, { "content": "#pragma once\n\n\n\n#include <iostream>\n\n#include <cstdio>\n\n#include <mutex>\n\n#include <shared_mutex>\n\n#include <string>\n\n\n", "file_path": "multi-threading/logger.h", "rank": 24, "score": 7.503040169353153 }, { "content": " return {};\n\n\n\n auto item = _work_pool->take_item(_worker_id);\n\n return _func(item);\n\n }\n\n\n\n std::vector<TResultItem> do_all()\n\n {\n\n auto results = std::vector<TResultItem>{};\n\n\n\n while (!_work_pool->is_empty()) {\n\n auto result = do_one();\n\n if (result)\n\n results.push_back(result.value());\n\n }\n\n\n\n return results;\n\n }\n\n};\n\n\n", "file_path": "multi-threading/worker.h", "rank": 25, "score": 7.407626836339228 }, { "content": " .add_optional(\n\n \"username\"s,\n\n &Arguments::username,\n\n \"\"s,\n\n { \"-u\"s, \"--username\"s },\n\n \"Username for basic authentication\"s)\n\n .add_optional(\n\n \"password\"s,\n\n &Arguments::password,\n\n \"\"s,\n\n { \"-p\"s, \"--password\"s },\n\n \"Password for basic authentication\"s)\n\n .add_optional(\n\n \"request_templates\"s,\n\n &Arguments::request_templates,\n\n { \"{BASE_URL}/{WORD}\" },\n\n { \"-t\"s, \"--request-templates\"s },\n\n \"Template defining how to construct URLs to fetch. Default: {BASE_URL}/{WORD}\"s,\n\n request_template_parser_factory)\n\n .add_optional(\n", "file_path": "parameters/arguments.cpp", "rank": 26, "score": 7.365197216876455 }, { "content": " return cpr::Post(args...);\n\n if (_request_method == RequestMethod::PUT)\n\n return cpr::Put(args...);\n\n if (_request_method == RequestMethod::PATCH)\n\n return cpr::Patch(args...);\n\n return cpr::Head(args...);\n\n }\n\n\n\n template <typename ... TArgs>\n\n cpr::Response _make_request_with_data(\n\n const std::string& data,\n\n TArgs&&... parameters)\n\n {\n\n using namespace std::string_literals;\n\n if (data == \"\"s)\n\n return _make_request_with_authentication(std::forward<TArgs>(parameters)...);\n\n\n\n if (_request_method == RequestMethod::DEFAULT)\n\n _request_method = RequestMethod::POST;\n\n return _make_request_with_authentication(std::forward<TArgs>(parameters)..., cpr::Body(data));\n", "file_path": "requests/requestfactory.h", "rank": 27, "score": 7.257405755178164 }, { "content": " {}\n\n\n\n std::vector<TResultItem> execute()\n\n {\n\n auto futures = std::vector<std::future<std::vector<TResultItem>>>{};\n\n auto results = std::vector<TResultItem>{};\n\n for (auto& worker : _workers)\n\n futures.push_back(std::async(std::launch::async, [&]() -> std::vector<TResultItem> { return worker.do_all(); }));\n\n std::for_each(\n\n futures.begin(),\n\n futures.end(),\n\n [&] (auto&& f)\n\n {\n\n f.wait();\n\n auto task_result = f.get();\n\n results.reserve(results.size() + task_result.size());\n\n results.insert(results.end(), task_result.begin(), task_result.end());\n\n });\n\n\n\n return results;\n\n }\n\n};\n", "file_path": "multi-threading/threadpool.h", "rank": 28, "score": 7.186234960024933 }, { "content": "\n\n template <typename It>\n\n std::tuple<Header, It> parse_header(const It& begin, const It& end)\n\n {\n\n auto name_beg = std::find_if(begin, end, [] (const auto& c) { return c != ' '; });\n\n auto name_end = std::find_if(name_beg, end, [] (const auto& c) { return c == ':'; });\n\n auto value_beg = std::find_if(name_end + 1, end, [] (const auto& c) { return c != ' '; });\n\n auto value_end = std::find_if(value_beg, end, [] (const auto& c) { return c == ';'; });\n\n return {\n\n { std::string(name_beg, name_end), std::string(value_beg, value_end) },\n\n (value_end == end) ? end : value_end + 1\n\n };\n\n }\n\n\n\n std::vector<Header> parse_headers(const std::string& parameter)\n\n {\n\n auto result = std::vector<Header>();\n\n\n\n auto it = std::begin(parameter);\n\n while (it != std::end(parameter))\n", "file_path": "parameters/parameter_conversions.cpp", "rank": 29, "score": 7.122866173208242 }, { "content": " auto output = std::string();\n\n for (auto& c : input)\n\n output += std::toupper(c);\n\n return output;\n\n}\n\n\n\nstd::function<RequestMethod(const std::string&)> request_method_parser_factory(const cdif::Container&)\n\n{\n\n using namespace std::string_literals;\n\n\n\n return [] (const std::string& arg) -> RequestMethod\n\n {\n\n auto method = to_upper(arg);\n\n if (method == \"HEAD\"s)\n\n return RequestMethod::HEAD;\n\n if (method == \"POST\"s)\n\n return RequestMethod::POST;\n\n if (method == \"PUT\"s)\n\n return RequestMethod::PUT;\n\n if (method == \"PATCH\"s)\n", "file_path": "parameters/parameter_conversions.cpp", "rank": 30, "score": 7.02074988306293 }, { "content": "#pragma once\n\n\n\n#include <functional>\n\n#include <map>\n\n#include <string>\n\n#include <vector>\n\n\n\n#include <cpr/cpr.h>\n\n\n\n#include \"requests/requestmethod.h\"\n\n#include \"models/header.h\"\n\n\n", "file_path": "requests/requestfactory.h", "rank": 31, "score": 6.900159734404919 }, { "content": "# db++\n\n\n\n`db++` is a c++ recreation of dirbuster (`dirb`). I made this a toy project after getting fed up with dirbuster being broken. This project will work in the happy path, but it is a toy so don't expect it to give nice failures yet. Feel free to submit PRs for anything you would like to see.\n\n\n\n## Usage\n\n\n\n```\n\nUsage: ./db++ [-h|--help] [-w|--wordlist <wordlist_file>] [-r|--recursive] [-u|--username <username>] [-p|--password <password>] [-t|--request-templates <request_templates>] [-k|--ignore-ssl-errors] [-s|--ignored-status-codes <ignore_codes>] [-c|--ignored-content-lengths <ignore_content_lengths>] [-X|--request-method <request_method>] [-T|--thread-count <thread_count>] [-d|--data <request_data>] [-D|--content-type <content_type>] [-H|--headers <headers>] <base_url> \n\n\n\n -h|--help \n\n Print this help message and exit \n\n -w|--wordlist <wordlist_file> \n\n Wordlist containing words to try to find on server \n\n -r|--recursive \n\n Recurse all found items as if they are directories \n\n -u|--username <username> \n\n Username for basic authentication \n\n -p|--password <password> \n\n Password for basic authentication \n\n -t|--request-templates <request_templates> \n\n Template defining how to construct URLs to fetch. Default: {BASE_URL}/{WORD}\n\n -k|--ignore-ssl-errors \n\n Ignore SSL errors \n\n -s|--ignored-status-codes <ignore_codes> \n\n Ignore any responses having the indicated status codes. Default: 404,400\n\n -c|--ignored-content-lengths <ignore_content_lengths> \n\n Ignore any responses having the indicated content lengths. Default: <none>\n\n -X|--request-method <request_method> \n\n HTTP method to use when making requests. Possible values are HEAD, POST, GET. Default: HEAD\n\n -T|--thread-count <thread_count> \n\n Number of threads to use for making requests. Default: 10\n\n -d|--data <request_data> \n\n Body of the post request. Changes request_method to POST \n\n -D|--content-type <content_type> \n\n HTTP content type of the <request_data>. Default: x-www-form-urlencoded\n\n -H|--headers <headers> \n\n Headers to add to request. Default <none> \n\n <base_url> \n\n URL to the server to attempt to query\n", "file_path": "README.md", "rank": 32, "score": 6.593097726632436 }, { "content": " &Arguments::content_type,\n\n \"\"s,\n\n { \"-D\"s, \"--content-type\"s },\n\n \"HTTP content type of the <request_data>. Default: x-www-form-urlencoded when data is provided\"s)\n\n .add_optional(\n\n \"headers\"s,\n\n &Arguments::headers,\n\n { },\n\n { \"-H\"s, \"--headers\"s },\n\n \"Headers to add to request. Default <none>\"s,\n\n header_parser_factory)\n\n .add_positional(\n\n \"base_url\"s,\n\n &Arguments::base_url,\n\n \"\"s,\n\n \"URL to the server to attempt to query\"s)\n\n .build();\n\n\n\n return parser;\n\n}\n", "file_path": "parameters/arguments.cpp", "rank": 33, "score": 6.3342356945807365 }, { "content": " }\n\n\n\n template <typename ... TArgs>\n\n cpr::Response _make_request_with_authentication(TArgs&&... parameters) const\n\n {\n\n using namespace std::string_literals;\n\n if (_user == \"\"s)\n\n return _make_request(std::forward<TArgs>(parameters)...);\n\n return _make_request(std::forward<TArgs>(parameters)..., cpr::Authentication(_user, _pass));\n\n }\n\n\n\n cpr::Header _create_header(const std::map<std::string, std::string>& templates) const;\n\n\n\n public:\n\n RequestFactory()\n\n : _user(), _pass(), _request_method(RequestMethod::HEAD) {}\n\n\n\n RequestFactory(\n\n const std::string& user,\n\n const std::string& pass,\n", "file_path": "requests/requestfactory.h", "rank": 34, "score": 6.305725350538596 }, { "content": "\n\nstd::function<std::vector<uint32_t>(const std::string&)> content_length_parser_factory(const cdif::Container& ctx)\n\n{\n\n return [&] (const std::string& parameter)\n\n {\n\n return impl::parse_status_code_list<uint32_t>(\n\n parameter,\n\n ctx.resolve<std::function<uint32_t(std::string)>>());\n\n };\n\n}\n\n\n\n\n\nstd::function<std::vector<std::string>(const std::string&)> request_template_parser_factory(const cdif::Container&)\n\n{\n\n return impl::parse_request_template_list;\n\n}\n\n\n\n\n\nstd::string to_upper(const std::string& input)\n\n{\n", "file_path": "parameters/parameter_conversions.cpp", "rank": 35, "score": 6.00643288365754 }, { "content": " out << \"thread_count: \" << std::to_string(args.thread_count) << '\\n';\n\n out << \"wordlist_file: \" << args.wordlist_file << '\\n';\n\n if (args.recursive)\n\n out << \"searching recursively\" << '\\n';\n\n if (args.ignore_ssl_errors)\n\n out << \"ignoring ssl errors\" << '\\n';\n\n\n\n out << \"ignored_status_codes: \";\n\n for (auto& code : args.ignore_codes)\n\n out << std::to_string(code) << ' ';\n\n out << '\\n';\n\n\n\n if (args.ignore_content_lengths.size() > 0)\n\n {\n\n out << \"ignored_content_lengths: \";\n\n for (auto& cl : args.ignore_content_lengths)\n\n out << std::to_string(cl) << ' ';\n\n out << '\\n';\n\n }\n\n\n", "file_path": "parameters/arguments.cpp", "rank": 36, "score": 5.98192969366696 }, { "content": " \"request_method\"s,\n\n &Arguments::request_method,\n\n RequestMethod::DEFAULT,\n\n { \"-X\"s, \"--request-method\"s },\n\n \"HTTP method to use when making requests. Possible values are HEAD, POST, PUT, PATCH, GET. Default: HEAD\"s,\n\n request_method_parser_factory)\n\n .add_optional(\n\n \"thread_count\"s,\n\n &Arguments::thread_count,\n\n 10u,\n\n { \"-T\"s, \"--thread-count\"s },\n\n \"Number of threads to use for making requests. Default: 10\"s)\n\n .add_optional(\n\n \"request_data\"s,\n\n &Arguments::request_body,\n\n \"\"s,\n\n { \"-d\"s, \"--data\"s },\n\n \"Body of the post request. Changes request_method to POST if not otherwise provided\"s)\n\n .add_optional(\n\n \"content_type\"s,\n", "file_path": "parameters/arguments.cpp", "rank": 37, "score": 5.957583125089727 }, { "content": " auto parser = ap::ArgumentParserBuilder<Arguments>()\n\n .add_optional(\n\n \"help\"s,\n\n &Arguments::help,\n\n false,\n\n { \"-h\"s, \"--help\"s },\n\n \"Print this help message and exit\"s,\n\n true)\n\n .add_optional(\n\n \"wordlist_file\"s,\n\n &Arguments::wordlist_file,\n\n \"/usr/share/dirb/wordlists/common.txt\"s,\n\n { \"-w\"s, \"--wordlist\" },\n\n \"Wordlist containing words to try to find on server\"s)\n\n .add_optional(\n\n \"recursive_search\"s,\n\n &Arguments::recursive,\n\n false,\n\n { \"-r\"s, \"--recursive\"s },\n\n \"Recurse all found items as if they are directories\"s)\n", "file_path": "parameters/arguments.cpp", "rank": 38, "score": 5.122959953672219 }, { "content": " {\n\n const auto& [header, end] = parse_header(it, std::end(parameter));\n\n result.push_back(header);\n\n it = end;\n\n }\n\n\n\n return result;\n\n }\n\n}\n\n\n\n\n\nstd::function<std::vector<uint16_t>(const std::string&)> status_code_parser_factory(const cdif::Container& ctx)\n\n{\n\n return [&] (const std::string& parameter)\n\n {\n\n return impl::parse_status_code_list<uint16_t>(\n\n parameter,\n\n ctx.resolve<std::function<uint16_t(std::string)>>());\n\n };\n\n}\n", "file_path": "parameters/parameter_conversions.cpp", "rank": 39, "score": 4.917184010344535 }, { "content": "#include \"logger.h\"\n\n\n\n#include <iostream>\n\n#include <shared_mutex>\n\n#include <string>\n\n\n\nvoid Logger::log_line(const std::string& msg)\n\n{\n\n std::unique_lock<std::shared_mutex> lock(_mutex);\n\n if (line_length != 0u)\n\n clear_line();\n\n\n\n std::cout << msg << std::endl;\n\n line_length = 0u;\n\n}\n\n\n\nvoid Logger::log(const std::string& msg)\n\n{\n\n std::unique_lock<std::shared_mutex> lock(_mutex);\n\n if (line_length != 0u)\n", "file_path": "multi-threading/logger.cpp", "rank": 40, "score": 4.551277355171605 }, { "content": " return std::all_of(_work_pool.begin(), _work_pool.end(), [] (auto&& items) { return items.empty(); });\n\n }\n\n\n\n std::size_t pool_size() const\n\n {\n\n return _work_pool.size();\n\n }\n\n};\n\n\n", "file_path": "multi-threading/workqueue.h", "rank": 41, "score": 4.531591518492164 }, { "content": " return RequestMethod::PATCH;\n\n if (method == \"GET\"s)\n\n return RequestMethod::GET;\n\n return RequestMethod::GET;\n\n };\n\n}\n\n\n\nstd::function<std::vector<Header>(const std::string&)> header_parser_factory(const cdif::Container&)\n\n{\n\n return impl::parse_headers;\n\n}\n", "file_path": "parameters/parameter_conversions.cpp", "rank": 42, "score": 3.2841856928603628 }, { "content": " \"ignore_ssl_errors\"s,\n\n &Arguments::ignore_ssl_errors,\n\n false,\n\n { \"-k\"s, \"--ignore-ssl-errors\"s },\n\n \"Ignore SSL errors\"s)\n\n .add_optional(\n\n \"ignore_codes\"s,\n\n &Arguments::ignore_codes,\n\n { 404u, 400u },\n\n { \"-s\"s, \"--ignored-status-codes\"s },\n\n \"Ignore any responses having the indicated status codes. Default: 404,400\"s,\n\n status_code_parser_factory)\n\n .add_optional(\n\n \"ignore_content_lengths\"s,\n\n &Arguments::ignore_content_lengths,\n\n { },\n\n { \"-c\"s, \"--ignored-content-lengths\"s },\n\n \"Ignore any responses having the indicated content lengths. Default: <none>\"s,\n\n content_length_parser_factory)\n\n .add_optional(\n", "file_path": "parameters/arguments.cpp", "rank": 43, "score": 2.338162149573982 }, { "content": "#include \"requests/requestmethod.h\"\n\n\n\n#include <iostream>\n\n\n\nstd::ostream& operator<<(std::ostream& out, const RequestMethod& request_method)\n\n{\n\n if (request_method == RequestMethod::HEAD)\n\n return out << \"HEAD\";\n\n if (request_method == RequestMethod::GET)\n\n return out << \"GET\";\n\n if (request_method == RequestMethod::POST)\n\n return out << \"POST\";\n\n if (request_method == RequestMethod::PUT)\n\n return out << \"PUT\";\n\n if (request_method == RequestMethod::PATCH)\n\n return out << \"PATCH\";\n\n return out << \"Unknown\";\n\n}\n", "file_path": "requests/requestmethod.cpp", "rank": 44, "score": 2.068910008904739 }, { "content": " }\n\n\n\n std::cout << args << std::endl;\n\n\n\n auto request_executor = RequestExecutor(args);\n\n\n\n if (args.recursive)\n\n request_executor.recursive_search();\n\n else\n\n request_executor.search();\n\n\n\n return 0;\n\n },\n\n [&] (const auto& error) {\n\n std::cerr << parser.usage(argv[0]) << std::endl << std::endl;\n\n std::cerr << parser.get_error_message(error) << std::endl;\n\n\n\n return 1;\n\n });\n\n}\n", "file_path": "db++.cpp", "rank": 45, "score": 2.0624715634003357 }, { "content": "```\n\n\n\nThis project relies on [cpr](https://github.com/whoshuu/cpr) as a third-party dependency. Other third-party dependencies are submoduled under `include`, so don't forget to `git submodule update --init` after checking out.\n", "file_path": "README.md", "rank": 46, "score": 1.8910524532383166 }, { "content": " clear_line();\n\n\n\n std::cout << msg << std::flush;\n\n line_length = msg.size();\n\n}\n\n\n\nvoid Logger::clear_line()\n\n{\n\n std::cout << std::string(line_length, ' ') << '\\r' << std::flush;\n\n}\n", "file_path": "multi-threading/logger.cpp", "rank": 47, "score": 1.606641049787809 } ]
C++
SurgSim/Graphics/RenderTests/OsgPointCloudRepresentationRenderTests.cpp
dbungert/opensurgsim
bd30629f2fd83f823632293959b7654275552fa9
#include <gtest/gtest.h> #include <memory> #include <vector> #include "SurgSim/DataStructures/Vertices.h" #include "SurgSim/Framework/Runtime.h" #include "SurgSim/Framework/Scene.h" #include "SurgSim/Graphics/OsgBoxRepresentation.h" #include "SurgSim/Graphics/OsgManager.h" #include "SurgSim/Graphics/OsgMaterial.h" #include "SurgSim/Graphics/OsgPointCloudRepresentation.h" #include "SurgSim/Graphics/OsgViewElement.h" #include "SurgSim/Graphics/PointCloudRepresentation.h" #include "SurgSim/Graphics/RenderTests/RenderTest.h" #include "SurgSim/Math/Quaternion.h" #include "SurgSim/Math/RigidTransform.h" #include "SurgSim/Math/Vector.h" #include "SurgSim/Testing/MathUtilities.h" using SurgSim::Math::Vector3d; using SurgSim::Math::Vector4d; using SurgSim::Math::Quaterniond; using SurgSim::Math::RigidTransform3d; using SurgSim::Math::makeRigidTransform; using SurgSim::Math::makeRotationQuaternion; using SurgSim::Testing::interpolate; using SurgSim::Testing::interpolatePose; namespace SurgSim { namespace Graphics { using SurgSim::Graphics::PointCloud; struct OsgPointCloudRepresentationRenderTests : public RenderTest { protected: std::vector<Vector3d> makeCube() { std::vector<Vector3d> result; result.push_back(Vector3d(0.01, -0.01, 0.01)); result.push_back(Vector3d(0.01, -0.01, 0.01)); result.push_back(Vector3d(-0.01, -0.01, 0.01)); result.push_back(Vector3d(-0.01, -0.01, -0.01)); result.push_back(Vector3d(0.01, -0.01, -0.01)); result.push_back(Vector3d(0.01, 0.01, 0.01)); result.push_back(Vector3d(-0.01, 0.01, 0.01)); result.push_back(Vector3d(-0.01, 0.01, -0.01)); result.push_back(Vector3d(0.01, 0.01, -0.01)); return result; } std::shared_ptr<PointCloudRepresentation> makeCloud(std::vector<Vector3d> vertices) { std::shared_ptr<PointCloudRepresentation> representation = std::make_shared<OsgPointCloudRepresentation>("cloud representation"); representation->setLocalPose(makeRigidTransform(Quaterniond::Identity(), Vector3d(0.0, 0.0, -0.2))); for (auto it = std::begin(vertices); it != std::end(vertices); ++it) { representation->getVertices()->addVertex(SurgSim::Graphics::PointCloud::VertexType(*it)); } viewElement->addComponent(representation); return representation; } }; TEST_F(OsgPointCloudRepresentationRenderTests, PointAdd) { std::vector<Vector3d> vertices = makeCube(); auto representation = std::make_shared<OsgPointCloudRepresentation>("pointcloud representation"); auto pointCloud = representation->getVertices(); representation->setPointSize(2.0); RigidTransform3d pose = makeRigidTransform(makeRotationQuaternion(0.2, Vector3d(1.0, 1.0, 1.0)), Vector3d(0.0, 0.0, -0.2)); representation->setLocalPose(pose); viewElement->addComponent(representation); runtime->start(); EXPECT_TRUE(graphicsManager->isInitialized()); EXPECT_TRUE(viewElement->isInitialized()); boost::this_thread::sleep(boost::posix_time::milliseconds(500)); for (size_t i = 0; i < vertices.size(); ++i) { pointCloud->addVertex(PointCloud::VertexType(vertices[i])); boost::this_thread::sleep(boost::posix_time::milliseconds(250)); } } TEST_F(OsgPointCloudRepresentationRenderTests, StaticRotate) { std::shared_ptr<PointCloudRepresentation> representation = makeCloud(makeCube()); runtime->start(); EXPECT_TRUE(graphicsManager->isInitialized()); EXPECT_TRUE(viewElement->isInitialized()); boost::this_thread::sleep(boost::posix_time::milliseconds(500)); int numSteps = 100; Vector3d startAngles(0.0, 0.0, 0.0); Vector3d endAngles(M_PI_4, M_PI_2, M_PI_2); Vector3d startPosition(-0.1, 0.0, -0.0); Vector3d endPosition(0.1, 0.0, -0.4); for (int i = 0; i < numSteps; ++i) { double t = static_cast<double>(i) / numSteps; representation->setLocalPose(interpolatePose(startAngles, endAngles, startPosition, endPosition, t)); boost::this_thread::sleep(boost::posix_time::milliseconds(1000 / numSteps)); } } TEST_F(OsgPointCloudRepresentationRenderTests, DynamicRotate) { std::vector<Vector3d> startVertices = makeCube(); std::shared_ptr<PointCloudRepresentation> representation = makeCloud(startVertices); std::shared_ptr<PointCloud> pointCloud = representation->getVertices(); runtime->start(); EXPECT_TRUE(graphicsManager->isInitialized()); EXPECT_TRUE(viewElement->isInitialized()); boost::this_thread::sleep(boost::posix_time::milliseconds(500)); int numSteps = 100; RigidTransform3d start = makeRigidTransform(makeRotationQuaternion(-M_PI_2, Vector3d(1.0, 1.0, 1.0)), Vector3d(-0.1, 0.0, 0.2)); RigidTransform3d end = makeRigidTransform(makeRotationQuaternion(M_PI_2, Vector3d(1.0, 1.0, 1.0)), Vector3d(0.1, 0.0, -0.2)); for (int i = 0; i < numSteps; ++i) { double t = static_cast<double>(i) / numSteps; RigidTransform3d currentPose = interpolate(start, end, t); int id = 0; for (auto it = std::begin(startVertices); it != std::end(startVertices); ++it, ++id) { pointCloud->setVertexPosition(id, currentPose * (*it)); } boost::this_thread::sleep(boost::posix_time::milliseconds(1000 / numSteps)); } } TEST_F(OsgPointCloudRepresentationRenderTests, PointSizeAndColor) { std::shared_ptr<PointCloudRepresentation> representation = makeCloud(makeCube()); runtime->start(); EXPECT_TRUE(graphicsManager->isInitialized()); EXPECT_TRUE(viewElement->isInitialized()); boost::this_thread::sleep(boost::posix_time::milliseconds(500)); int numSteps = 100; std::pair<double, double> size = std::make_pair(0.0, 20.0); std::pair<Vector4d, Vector4d> color = std::make_pair(Vector4d(0.0, 1.0, 0.0, 1.0), Vector4d(1.0, 0.0, 1.0, 1.0)); for (int i = 0; i < numSteps; ++i) { double t = static_cast<double>(i) / numSteps; representation->setPointSize(interpolate(size, t)); representation->setColor(interpolate(color, t)); boost::this_thread::sleep(boost::posix_time::milliseconds(1000 / numSteps)); } } TEST_F(OsgPointCloudRepresentationRenderTests, PointSprite) { std::vector<Vector3d> vertices = makeCube(); auto graphics = std::make_shared<SurgSim::Graphics::OsgPointCloudRepresentation>("Cloud"); graphics->setPointSize(10.0f); graphics->setLocalPose(makeRigidTransform(Quaterniond::Identity(), Vector3d(0.0, 0.0, -0.2))); for (auto vertex : vertices) { graphics->getVertices()->addVertex(SurgSim::Graphics::PointCloud::VertexType(vertex)); } auto material = std::make_shared<SurgSim::Graphics::OsgMaterial>("material"); auto texture = std::make_shared<SurgSim::Graphics::OsgTexture2d>(); texture->setIsPointSprite(true); std::string textureFilename; ASSERT_TRUE(runtime->getApplicationData()->tryFindFile("Textures/checkered.png", &textureFilename)); texture->loadImage(textureFilename); auto diffuseMapUniform = std::make_shared<SurgSim::Graphics::OsgTextureUniform<SurgSim::Graphics::OsgTexture2d>>("diffuseMap"); diffuseMapUniform->set(texture); material->addUniform(diffuseMapUniform); graphics->setMaterial(material); auto sceneElement = std::make_shared<SurgSim::Framework::BasicSceneElement>("Blood"); sceneElement->addComponent(graphics); sceneElement->addComponent(material); scene->addSceneElement(sceneElement); runtime->start(); boost::this_thread::sleep(boost::posix_time::milliseconds(500)); runtime->stop(); } }; };
#include <gtest/gtest.h> #include <memory> #include <vector> #include "SurgSim/DataStructures/Vertices.h" #include "SurgSim/Framework/Runtime.h" #include "SurgSim/Framework/Scene.h" #include "SurgSim/Graphics/OsgBoxRepresentation.h" #include "SurgSim/Graphics/OsgManager.h" #include "SurgSim/Graphics/OsgMaterial.h" #include "SurgSim/Graphics/OsgPointCloudRepresentation.h" #include "SurgSim/Graphics/OsgViewElement.h" #include "SurgSim/Graphics/PointCloudRepresentation.h" #include "SurgSim/Graphics/RenderTests/RenderTest.h" #include "SurgSim/Math/Quaternion.h" #include "SurgSim/Math/RigidTransform.h" #include "SurgSim/Math/Vector.h" #include "SurgSim/Testing/MathUtilities.h" using SurgSim::Math::Vector3d; using SurgSim::Math::Vector4d; using SurgSim::Math::Quaterniond; using SurgSim::Math::RigidTransform3d; using SurgSim::Math::makeRigidTransform; using SurgSim::Math::makeRotationQuaternion; using SurgSim::Testing::interpolate; using SurgSim::Testing::interpolatePose; namespace SurgSim { namespace Graphics { using SurgSim::Graphics::PointCloud; struct OsgPointCloudRepresentationRenderTests : public RenderTest { protected: std::vector<Vector3d> makeCube() { std::vector<Vector3d> result; result.push_back(Vector3d(0.01, -0.01, 0.01)); result.push_back(Vector3d(0.01, -0.01, 0.01)); result.push_back(Vector3d(-0.01, -0.01, 0.01)); result.push_back(Vector3d(-0.01, -0.01, -0.01)); result.push_back(Vector3d(0.01, -0.01, -0.01)); result.push_back(Vector3d(0.01, 0.01, 0.01)); result.push_back(Vector3d(-0.01, 0.01, 0.01)); result.push_back(Vector3d(-0.01, 0.01, -0.01)); result.push_back(Vector3d(0.01, 0.01, -0.01)); return result; } std::shared_ptr<PointCloudRepresentation> makeCloud(std::vector<Vector3d> vertices) { std::shared_ptr<PointCloudRepresentation> representation = std::make_shared<OsgPointCloudRepresentation>("cloud representation"); representation->setLocalPose(makeRigidTransform(Quaterniond::Identity(), Vector3d(0.0, 0.0, -0.2))); for (auto it = std::begin(vertices); it != std::end(vertices); ++it) { representation->getVertices()->addVertex(SurgSim::Graphics::PointCloud::VertexType(*it)); } viewElement->addComponent(representation); return representation; } }; TEST_F(OsgPointCloudRepresentationRenderTests, PointAdd) { std::vector<Vector3d> vertices = makeCube(); auto representation = std::make_shared<OsgPointCloudRepresentation>("pointcloud representation"); auto pointCloud = representation->getVertices(); representation->setPointSize(2.0); RigidTransform3d pose = makeRigidTransform(makeRotationQuaternion(0.2, Vector3d(1.0, 1.0, 1.0)), Vector3d(0.0, 0.0, -0.2)); representation->setLocalPose(pose);
TEST_F(OsgPointCloudRepresentationRenderTests, StaticRotate) { std::shared_ptr<PointCloudRepresentation> representation = makeCloud(makeCube()); runtime->start(); EXPECT_TRUE(graphicsManager->isInitialized()); EXPECT_TRUE(viewElement->isInitialized()); boost::this_thread::sleep(boost::posix_time::milliseconds(500)); int numSteps = 100; Vector3d startAngles(0.0, 0.0, 0.0); Vector3d endAngles(M_PI_4, M_PI_2, M_PI_2); Vector3d startPosition(-0.1, 0.0, -0.0); Vector3d endPosition(0.1, 0.0, -0.4); for (int i = 0; i < numSteps; ++i) { double t = static_cast<double>(i) / numSteps; representation->setLocalPose(interpolatePose(startAngles, endAngles, startPosition, endPosition, t)); boost::this_thread::sleep(boost::posix_time::milliseconds(1000 / numSteps)); } } TEST_F(OsgPointCloudRepresentationRenderTests, DynamicRotate) { std::vector<Vector3d> startVertices = makeCube(); std::shared_ptr<PointCloudRepresentation> representation = makeCloud(startVertices); std::shared_ptr<PointCloud> pointCloud = representation->getVertices(); runtime->start(); EXPECT_TRUE(graphicsManager->isInitialized()); EXPECT_TRUE(viewElement->isInitialized()); boost::this_thread::sleep(boost::posix_time::milliseconds(500)); int numSteps = 100; RigidTransform3d start = makeRigidTransform(makeRotationQuaternion(-M_PI_2, Vector3d(1.0, 1.0, 1.0)), Vector3d(-0.1, 0.0, 0.2)); RigidTransform3d end = makeRigidTransform(makeRotationQuaternion(M_PI_2, Vector3d(1.0, 1.0, 1.0)), Vector3d(0.1, 0.0, -0.2)); for (int i = 0; i < numSteps; ++i) { double t = static_cast<double>(i) / numSteps; RigidTransform3d currentPose = interpolate(start, end, t); int id = 0; for (auto it = std::begin(startVertices); it != std::end(startVertices); ++it, ++id) { pointCloud->setVertexPosition(id, currentPose * (*it)); } boost::this_thread::sleep(boost::posix_time::milliseconds(1000 / numSteps)); } } TEST_F(OsgPointCloudRepresentationRenderTests, PointSizeAndColor) { std::shared_ptr<PointCloudRepresentation> representation = makeCloud(makeCube()); runtime->start(); EXPECT_TRUE(graphicsManager->isInitialized()); EXPECT_TRUE(viewElement->isInitialized()); boost::this_thread::sleep(boost::posix_time::milliseconds(500)); int numSteps = 100; std::pair<double, double> size = std::make_pair(0.0, 20.0); std::pair<Vector4d, Vector4d> color = std::make_pair(Vector4d(0.0, 1.0, 0.0, 1.0), Vector4d(1.0, 0.0, 1.0, 1.0)); for (int i = 0; i < numSteps; ++i) { double t = static_cast<double>(i) / numSteps; representation->setPointSize(interpolate(size, t)); representation->setColor(interpolate(color, t)); boost::this_thread::sleep(boost::posix_time::milliseconds(1000 / numSteps)); } } TEST_F(OsgPointCloudRepresentationRenderTests, PointSprite) { std::vector<Vector3d> vertices = makeCube(); auto graphics = std::make_shared<SurgSim::Graphics::OsgPointCloudRepresentation>("Cloud"); graphics->setPointSize(10.0f); graphics->setLocalPose(makeRigidTransform(Quaterniond::Identity(), Vector3d(0.0, 0.0, -0.2))); for (auto vertex : vertices) { graphics->getVertices()->addVertex(SurgSim::Graphics::PointCloud::VertexType(vertex)); } auto material = std::make_shared<SurgSim::Graphics::OsgMaterial>("material"); auto texture = std::make_shared<SurgSim::Graphics::OsgTexture2d>(); texture->setIsPointSprite(true); std::string textureFilename; ASSERT_TRUE(runtime->getApplicationData()->tryFindFile("Textures/checkered.png", &textureFilename)); texture->loadImage(textureFilename); auto diffuseMapUniform = std::make_shared<SurgSim::Graphics::OsgTextureUniform<SurgSim::Graphics::OsgTexture2d>>("diffuseMap"); diffuseMapUniform->set(texture); material->addUniform(diffuseMapUniform); graphics->setMaterial(material); auto sceneElement = std::make_shared<SurgSim::Framework::BasicSceneElement>("Blood"); sceneElement->addComponent(graphics); sceneElement->addComponent(material); scene->addSceneElement(sceneElement); runtime->start(); boost::this_thread::sleep(boost::posix_time::milliseconds(500)); runtime->stop(); } }; };
viewElement->addComponent(representation); runtime->start(); EXPECT_TRUE(graphicsManager->isInitialized()); EXPECT_TRUE(viewElement->isInitialized()); boost::this_thread::sleep(boost::posix_time::milliseconds(500)); for (size_t i = 0; i < vertices.size(); ++i) { pointCloud->addVertex(PointCloud::VertexType(vertices[i])); boost::this_thread::sleep(boost::posix_time::milliseconds(250)); } }
function_block-function_prefix_line
[ { "content": "struct OsgVectorFieldRepresentationRenderTests : public SurgSim::Graphics::RenderTest\n\n{\n\nprotected:\n\n\t// A point is a location (X,Y,Z) in 3D space\n\n\tstd::vector<Vector3d> makeStartingPoints()\n\n\t{\n\n\t\tstd::vector<Vector3d> points(8);\n\n\t\tpoints[0] = Vector3d(1.0, 0.0, 0.0);\n\n\t\tpoints[1] = Vector3d(0.0, 1.0, 0.0);\n\n\t\tpoints[2] = Vector3d(-1.0, 0.0, 0.0);\n\n\t\tpoints[3] = Vector3d(0.0, -1.0, 0.0);\n\n\n\n\t\tpoints[4] = Vector3d(2.0, 0.0, 0.0);\n\n\t\tpoints[5] = Vector3d(0.0, 2.0, 0.0);\n\n\t\tpoints[6] = Vector3d(-2.0, 0.0, 0.0);\n\n\t\tpoints[7] = Vector3d(0.0, -2.0, 0.0);\n\n\t\treturn points;\n\n\t}\n\n\n\n\tstd::vector<Vector3d> makeEndingPoints()\n", "file_path": "SurgSim/Graphics/RenderTests/OsgVectorFieldRepresentationRenderTests.cpp", "rank": 0, "score": 304379.0189008919 }, { "content": "struct OsgTextRepresentationRenderTests : public SurgSim::Graphics::RenderTest\n\n{\n\n\n\n};\n\n\n\n\n\nTEST_F(OsgTextRepresentationRenderTests, Operation)\n\n{\n\n\tauto text = std::make_shared<OsgTextRepresentation>(\"HUD\");\n\n\ttext->setText(\"HelloWorld\");\n\n\tviewElement->addComponent(text);\n\n\n\n\truntime->start();\n\n\tEXPECT_TRUE(graphicsManager->isInitialized());\n\n\tEXPECT_TRUE(viewElement->isInitialized());\n\n\tboost::this_thread::sleep(boost::posix_time::milliseconds(1500));\n\n\n\n\tauto dimensions = viewElement->getView()->getDimensions();\n\n\ttext->setLocation(dimensions[0] / 2.0, dimensions[1] / 2.0);\n\n\ttext->setText(\"Hello Again\");\n", "file_path": "SurgSim/Graphics/RenderTests/OsgTextRepresentationRenderTests.cpp", "rank": 1, "score": 256331.6306025539 }, { "content": "struct OsgOctreeRepresentationRenderTests : public SurgSim::Graphics::RenderTest\n\n{\n\n};\n\n\n\n// An Octree(Node) is traversed in following order (the 2nd OctreeNode, i.e. OctreeNode with \"1\" is now shown):\n\n/*\n\n\t\t\t\t________\n\n\t\t\t /3 / 7/|\n\n\t\t\t /-------/ |\n\n\t\t\t /2__/_6_/| |\n\n\t\t\t| | | |/|\n\n\t\t\t|___|___|/|5|\n\n\t\t\t| | | |/\n\n\t\t\t|0__|__4|/\n\n*/\n\nTEST_F(OsgOctreeRepresentationRenderTests, OctreeSubdivide)\n\n{\n\n\tSurgSim::DataStructures::EmptyData emptyData;\n\n\n\n\tSurgSim::Math::OctreeShape::NodeType::AxisAlignedBoundingBox boundingBox;\n", "file_path": "SurgSim/Graphics/RenderTests/OsgOctreeRepresentationRenderTests.cpp", "rank": 2, "score": 256331.63060255387 }, { "content": "struct RenderTest : public ::testing::Test\n\n{\n\npublic:\n\n\n\n\tvoid SetUp() override;\n\n\n\n\tvoid TearDown() override;\n\n\n\n\tstd::shared_ptr<ScreenSpaceQuadRepresentation> makeQuad(\n\n\t\tconst std::string& name,\n\n\t\tint width,\n\n\t\tint height,\n\n\t\tint x,\n\n\t\tint y);\n\n\n\n\tstd::shared_ptr<SurgSim::Framework::Runtime> runtime;\n\n\tstd::shared_ptr<OsgManager> graphicsManager;\n\n\tstd::shared_ptr<SurgSim::Framework::Scene> scene;\n\n\tstd::shared_ptr<OsgViewElement> viewElement;\n\n\tstd::shared_ptr<const SurgSim::Framework::ApplicationData> applicationData;\n\n\tstd::shared_ptr<OsgCamera> camera;\n\n\n\n};\n\n\n\n}; // Graphics\n\n}; // SurgSim\n\n\n\n#endif", "file_path": "SurgSim/Graphics/RenderTests/RenderTest.h", "rank": 3, "score": 245484.323376732 }, { "content": "struct OsgRepresentationRenderTests : public RenderTest\n\n{\n\n\n\n};\n\n\n\n/// This test will put all shape one by one along the X-axis\n\n/// To make sure all shapes are aligned.\n\n/// X-axis points horizontally to the right\n\n/// Y-axis points vertically up\n\n/// Z-axis is perpendicular to the screen and points out\n\nTEST_F(OsgRepresentationRenderTests, RepresentationTest)\n\n{\n\n\t///\tBox position\n\n\tVector3d boxPosition(0.05, 0.0, -0.2);\n\n\t/// Capsule position\n\n\tVector3d capsulePosition(-0.05, 0.0, -0.2);\n\n\t/// Cylinder position\n\n\tVector3d cylinderPosition(-0.025, 0.0, -0.2);\n\n\t/// Sphere position\n\n\tVector3d spherePosition(0.025, 0.0, -0.2);\n", "file_path": "SurgSim/Graphics/RenderTests/OsgRepresentationRenderTests.cpp", "rank": 4, "score": 238108.73067516438 }, { "content": "struct OsgProgramRenderTests : public RenderTest\n\n{\n\n\tvoid SetUp()\n\n\t{\n\n\t\tRenderTest::SetUp();\n\n\n\n\t\t// Light\n\n\t\tauto sceneElement = std::make_shared<SurgSim::Framework::BasicSceneElement>(\"Light\");\n\n\t\tauto light = std::make_shared<SurgSim::Graphics::OsgLight>(\"Light\");\n\n\t\tlight->setDiffuseColor(SurgSim::Math::Vector4d(0.8, 0.8, 0.8, 1.0));\n\n\t\tlight->setSpecularColor(SurgSim::Math::Vector4d(0.8, 0.8, 0.8, 1.0));\n\n\t\tlight->setLightGroupReference(SurgSim::Graphics::Representation::DefaultGroupName);\n\n\t\tsceneElement->addComponent(light);\n\n\t\tsceneElement->addComponent(std::make_shared<SurgSim::Graphics::OsgAxesRepresentation>(\"axes\"));\n\n\t\tsceneElement->setPose(makeRigidTransform(Quaterniond::Identity(), Vector3d(-2.0, -2.0, -4.0)));\n\n\t\tscene->addSceneElement(sceneElement);\n\n\n\n\t\t// Camera\n\n\t\tviewElement->getCamera()->setAmbientColor(SurgSim::Math::Vector4d(0.1, 0.1, 0.1, 1.0));\n\n\t\tviewElement->setPose(\n", "file_path": "SurgSim/Graphics/RenderTests/OsgProgramRenderTests.cpp", "rank": 5, "score": 238108.73067516438 }, { "content": "struct OsgCameraRenderTests: public RenderTest\n\n{\n\n\n\n};\n\n\n\nTEST_F(OsgCameraRenderTests, PassTest)\n\n{\n\n\tauto defaultCamera = viewElement->getCamera();\n\n\tauto renderPass = std::make_shared<OsgCamera>(\"RenderPass\");\n\n\n\n\trenderPass->setProjectionMatrix(defaultCamera->getProjectionMatrix());\n\n\trenderPass->setRenderGroupReference(\"RenderPass\");\n\n\trenderPass->setGroupReference(SurgSim::Graphics::Representation::DefaultGroupName);\n\n\n\n\tstd::array<int, 2> dimensions = viewElement->getView()->getDimensions();\n\n\n\n\tauto renderTargetOsg = std::make_shared<OsgRenderTarget2d>(dimensions[0], dimensions[1], 1.0, 2, true);\n\n\trenderPass->setRenderTarget(renderTargetOsg);\n\n\trenderPass->setRenderOrder(Camera::RENDER_ORDER_PRE_RENDER, 0);\n\n\n", "file_path": "SurgSim/Graphics/RenderTests/OsgCameraRenderTests.cpp", "rank": 6, "score": 238108.73067516438 }, { "content": "struct OsgCapsuleRepresentationRenderTests : public RenderTest\n\n{\n\n\n\n};\n\n\n\nTEST_F(OsgCapsuleRepresentationRenderTests, MovingCapsuleTest)\n\n{\n\n\t/// Add the two capsule representation to the view element\n\n\tstd::shared_ptr<CapsuleRepresentation> capsuleRepresentation1 =\n\n\t\tstd::make_shared<OsgCapsuleRepresentation>(\"capsule representation 1\");\n\n\tviewElement->addComponent(capsuleRepresentation1);\n\n\tstd::shared_ptr<CapsuleRepresentation> capsuleRepresentation2 =\n\n\t\tstd::make_shared<OsgCapsuleRepresentation>(\"capsule representation 2\");\n\n\tviewElement->addComponent(capsuleRepresentation2);\n\n\n\n\t/// Run the thread\n\n\truntime->start();\n\n\tEXPECT_TRUE(graphicsManager->isInitialized());\n\n\tboost::this_thread::sleep(boost::posix_time::milliseconds(1000));\n\n\n", "file_path": "SurgSim/Graphics/RenderTests/OsgCapsuleRepresentationRenderTests.cpp", "rank": 7, "score": 232595.15138025885 }, { "content": "struct OsgSphereRepresentationRenderTests : public RenderTest\n\n{\n\n};\n\n\n\n/// Pops up a window with two spheres that are translating and changing radius\n\nTEST_F(OsgSphereRepresentationRenderTests, MovingSpheresTest)\n\n{\n\n\t/// Initial sphere 1 position\n\n\tVector3d startPosition1(-0.1, 0.0, -0.2);\n\n\t/// Final sphere 1 position\n\n\tVector3d endPosition1(0.1, 0.0, -0.2);\n\n\t/// Initial sphere 1 radius;\n\n\tdouble startRadius1 = 0.001;\n\n\t/// Final sphere 1 radius;\n\n\tdouble endRadius1 = 0.01;\n\n\t/// Initial sphere 2 position\n\n\tVector3d startPosition2(0.0, -0.1, -0.2);\n\n\t/// Final sphere 2 position\n\n\tVector3d endPosition2(0.0, 0.1, -0.2);\n\n\t/// Initial sphere 2 radius;\n", "file_path": "SurgSim/Graphics/RenderTests/OsgSphereRepresentationRenderTests.cpp", "rank": 8, "score": 232595.15138025885 }, { "content": "struct OsgSceneryRepresentationRenderTests : public RenderTest\n\n{\n\n};\n\n\n\nTEST_F(OsgSceneryRepresentationRenderTests, RenderTest)\n\n{\n\n\t/// Initial position of object 1\n\n\tVector3d startPosition1(-5.0, 0.0, -5.0);\n\n\t/// Final position of object 1\n\n\tVector3d endPosition1(5.0, 0.0, -5.0);\n\n\t/// Initial angles (X, Y, Z) of object 1\n\n\tVector3d startAngles1(0.0, 0.0, 0.0);\n\n\t/// Final angles (X, Y, Z) of object 1\n\n\tVector3d endAngles1(-M_PI_4, -M_PI_4, -M_PI_4);\n\n\n\n\t/// Initial position of object 2\n\n\tVector3d startPosition2(0.0, -5.0, -5.0);\n\n\t/// Final position of object 2\n\n\tVector3d endPosition2(0.0, 5.0, -5.0);\n\n\t/// Initial angles (X, Y, Z) of object 2\n", "file_path": "SurgSim/Graphics/RenderTests/OsgSceneryRepresentationRenderTests.cpp", "rank": 9, "score": 232595.15138025885 }, { "content": "struct OsgBoxRepresentationRenderTests : public RenderTest\n\n{\n\n\n\n};\n\n\n\nTEST_F(OsgBoxRepresentationRenderTests, MovingBoxesTest)\n\n{\n\n\t/// Initial and final position (X, Y, Z) of box 1\n\n\tVector3d startPosition1(-0.1, 0.0, -0.2), finalPosition1(0.1, 0.0, -0.2);\n\n\t/// Initial angles (X, Y, Z) and final of the cylinder 1\n\n\tVector3d startAngles1(0.0, 0.0, 0.0), finalAngles1(-M_PI_4, -M_PI_4, -M_PI_4);\n\n\t/// Initial box 1 sizeX;\n\n\tdouble startSizeX1 = 0.001;\n\n\t/// Final box 1 sizeX;\n\n\tdouble endSizeX1 = 0.01;\n\n\t/// Initial box 1 sizeY;\n\n\tdouble startSizeY1 = 0.011;\n\n\t/// Final box 1 sizeY;\n\n\tdouble endSizeY1 = 0.02;\n\n\t/// Initial box 1 sizeZ;\n", "file_path": "SurgSim/Graphics/RenderTests/OsgBoxRepresentationRenderTests.cpp", "rank": 10, "score": 232595.15138025885 }, { "content": "struct OsgSkeletonRepresentationRenderTests : public RenderTest\n\n{\n\n};\n\n\n\nTEST_F(OsgSkeletonRepresentationRenderTests, BasicTest)\n\n{\n\n\tauto graphics = std::make_shared<SurgSim::Graphics::OsgSkeletonRepresentation>(\"Skeleton\");\n\n\tgraphics->loadModel(\"OsgSkeletonRepresentationRenderTests/rigged_cylinder.osgt\");\n\n\tgraphics->setSkinningShaderFileName(\"Shaders/skinning.vert\");\n\n\tauto sceneElement = std::make_shared<SurgSim::Framework::BasicSceneElement>(\"Rigged Cylinder\");\n\n\tsceneElement->addComponent(graphics);\n\n\tscene->addSceneElement(sceneElement);\n\n\n\n\tviewElement->setPose(SurgSim::Math::makeRigidTransform(\n\n\t\t\t\t\t\t\t Vector3d(-0.3, 0.3, -0.3),\n\n\t\t\t\t\t\t\t Vector3d(0.0, 0.0, 0.0),\n\n\t\t\t\t\t\t\t Vector3d(0.0, 0.0, 1.0)));\n\n\n\n\truntime->start();\n\n\tboost::this_thread::sleep(boost::posix_time::milliseconds(2000));\n", "file_path": "SurgSim/Graphics/RenderTests/OsgSkeletonRepresentationRenderTests.cpp", "rank": 11, "score": 232595.15138025885 }, { "content": "struct OsgCylinderRepresentationRenderTests : public RenderTest\n\n{\n\n};\n\n\n\nTEST_F(OsgCylinderRepresentationRenderTests, MovingCylinderTest)\n\n{\n\n\t/// Add the two cylinder representation to the view element\n\n\tstd::shared_ptr<CylinderRepresentation> cylinderRepresentation1 =\n\n\t\tstd::make_shared<OsgCylinderRepresentation>(\"cylinder representation 1\");\n\n\tviewElement->addComponent(cylinderRepresentation1);\n\n\tstd::shared_ptr<CylinderRepresentation> cylinderRepresentation2 =\n\n\t\tstd::make_shared<OsgCylinderRepresentation>(\"cylinder representation 2\");\n\n\tviewElement->addComponent(cylinderRepresentation2);\n\n\n\n\t/// Run the thread\n\n\truntime->start();\n\n\tEXPECT_TRUE(graphicsManager->isInitialized());\n\n\tboost::this_thread::sleep(boost::posix_time::milliseconds(1000));\n\n\n\n\tenum SetterType {SetterTypeIndividual,\n", "file_path": "SurgSim/Graphics/RenderTests/OsgCylinderRepresentationRenderTests.cpp", "rank": 12, "score": 232595.15138025885 }, { "content": "struct OsgCurveRepresentationRenderTests : public RenderTest\n\n{\n\n\n\n\n\nprotected:\n\n\tDataStructures::VerticesPlain makeCube()\n\n\t{\n\n\t\ttypedef DataStructures::VerticesPlain::VertexType Vertex;\n\n\t\tDataStructures::VerticesPlain result;\n\n\t\tresult.addVertex(Vertex(Vector3d(0.1, -0.1, 0.1)));\n\n\t\tresult.addVertex(Vertex(Vector3d(0.1, -0.1, 0.1)));\n\n\t\tresult.addVertex(Vertex(Vector3d(-0.1, -0.1, 0.1)));\n\n\t\tresult.addVertex(Vertex(Vector3d(-0.1, -0.1, -0.1)));\n\n\t\tresult.addVertex(Vertex(Vector3d(0.1, -0.1, -0.1)));\n\n\n\n\t\tresult.addVertex(Vertex(Vector3d(0.1, 0.1, 0.1)));\n\n\t\tresult.addVertex(Vertex(Vector3d(-0.1, 0.1, 0.1)));\n\n\t\tresult.addVertex(Vertex(Vector3d(-0.1, 0.1, -0.1)));\n\n\t\tresult.addVertex(Vertex(Vector3d(0.1, 0.1, -0.1)));\n\n\t\treturn result;\n", "file_path": "SurgSim/Graphics/RenderTests/OsgCurveRepresentationRenderTests.cpp", "rank": 13, "score": 232595.15138025885 }, { "content": "struct OsgMeshRepresentationRenderTests : public RenderTest\n\n{\n\n\n\nprotected:\n\n\tstd::vector<Vector3d> cubeVertices;\n\n\tstd::vector<size_t> cubeTriangles;\n\n\tstd::vector<Vector4d> cubeColors;\n\n\tstd::vector<Vector2d> cubeTextures;\n\n\n\n\tstd::shared_ptr<MeshRepresentation> makeRepresentation(const std::string& name)\n\n\t{\n\n\t\tauto meshRepresentation = std::make_shared<OsgMeshRepresentation>(name);\n\n\t\tmeshRepresentation->setLocalPose(makeRigidTransform(Quaterniond::Identity(), Vector3d(0.0, 0.0, 0.0)));\n\n\t\treturn meshRepresentation;\n\n\t}\n\n};\n\n\n\nTEST_F(OsgMeshRepresentationRenderTests, BasicCubeTest)\n\n{\n\n\tauto element = std::make_shared<SurgSim::Framework::BasicSceneElement>(\"Scene\");\n", "file_path": "SurgSim/Graphics/RenderTests/OsgMeshRepresentationRenderTests.cpp", "rank": 14, "score": 232595.15138025885 }, { "content": "struct OsgScreenSpaceQuadRenderTests : public RenderTest\n\n{\n\n\n\n};\n\n\n\n\n\nTEST_F(OsgScreenSpaceQuadRenderTests, InitTest)\n\n{\n\n\tstd::shared_ptr<OsgScreenSpaceQuadRepresentation> quad =\n\n\t\tstd::make_shared<OsgScreenSpaceQuadRepresentation>(\"Screen Quad\");\n\n\n\n\tviewElement->addComponent(quad);\n\n\n\n\t/// Run the thread\n\n\truntime->start();\n\n\tEXPECT_TRUE(graphicsManager->isInitialized());\n\n\tEXPECT_TRUE(viewElement->isInitialized());\n\n\tquad->setSize(100, 100);\n\n\tboost::this_thread::sleep(boost::posix_time::milliseconds(1000));\n\n\n", "file_path": "SurgSim/Graphics/RenderTests/OsgScreenSpaceQuadRenderTests.cpp", "rank": 15, "score": 227542.71032353933 }, { "content": "class OsgUniform<std::vector<T>> : public Uniform<std::vector<T>>, public OsgUniformBase\n\n{\n\npublic:\n\n\t/// Constructor\n\n\t/// \\param\tname\tName used in shader code to access this uniform\n\n\t/// \\param\tnumElements\tNumber of elements\n\n\tOsgUniform(const std::string& name, size_t numElements);\n\n\n\n\t/// \\return the number of elements in the uniform\n\n\tvirtual size_t getNumElements() const;\n\n\n\n\t/// Sets the value of one of the uniform's elements\n\n\t/// \\param\tindex\tIndex of the element\n\n\t/// \\param\tvalue\tValue to set\n\n\tvirtual void setElement(size_t index, const T& value);\n\n\n\n\t/// Sets the value of all of the uniform's elements\n\n\t/// \\param\tvalue\tArray of values\n\n\tvirtual void set(const std::vector<T>& value);\n\n\n", "file_path": "SurgSim/Graphics/OsgUniform.h", "rank": 17, "score": 220292.39026505803 }, { "content": "struct MeshTests : public ::testing::Test\n\n{\n\npublic:\n\n\n\n\tvirtual void SetUp()\n\n\t{\n\n\t\tSurgSim::Testing::Cube::makeCube(&cubeVertices, &cubeColors, &cubeTextures, &cubeTriangles);\n\n\t}\n\n\n\n\n\n\tstd::vector<Vector3d> cubeVertices;\n\n\tstd::vector<size_t> cubeTriangles;\n\n\tstd::vector<Vector4d> cubeColors;\n\n\tstd::vector<Vector2d> cubeTextures;\n\n};\n\n\n\n\n\nTEST_F(MeshTests, MakeMeshTestWorking)\n\n{\n\n\tstd::shared_ptr<Mesh> mesh = std::make_shared<Mesh>();\n", "file_path": "SurgSim/Graphics/UnitTests/MeshTests.cpp", "rank": 18, "score": 206908.64546298038 }, { "content": "/// OSG vector field representation, implements a VectorFieldRepresenation using OSG.\n\nclass OsgVectorFieldRepresentation : public VectorFieldRepresentation, public OsgRepresentation\n\n{\n\npublic:\n\n\t/// Constructor\n\n\t/// \\param name Name of OsgVectorFieldRepresentation\n\n\texplicit OsgVectorFieldRepresentation(const std::string& name);\n\n\t/// Destructor\n\n\t~OsgVectorFieldRepresentation();\n\n\n\n\tSURGSIM_CLASSNAME(SurgSim::Graphics::OsgVectorFieldRepresentation);\n\n\n\n\tstd::shared_ptr<VectorField> getVectorField() const override;\n\n\n\n\tvoid setLineWidth(double width) override;\n\n\tdouble getLineWidth() const override;\n\n\n\n\tvoid setScale(double scale) override;\n\n\tdouble getScale() const override;\n\n\n\n\t/// Sets the size of point indicating the starting of vector\n", "file_path": "SurgSim/Graphics/OsgVectorFieldRepresentation.h", "rank": 19, "score": 206895.24896386746 }, { "content": "struct PosedShapeMotion : public std::pair<PosedShape<T>, PosedShape<T>>\n\n{\n\n\tPosedShapeMotion() {}\n\n\tPosedShapeMotion(const PosedShape<T>& posedShapeFirst, const PosedShape<T>& posedShapeSecond)\n\n\t{\n\n\t\tthis->first = posedShapeFirst;\n\n\t\tthis->second = posedShapeSecond;\n\n\t}\n\n\n\n\tvoid invalidate()\n\n\t{\n\n\t\tthis->first.invalidate();\n\n\t\tthis->second.invalidate();\n\n\t}\n\n};\n\n\n\n}; // Math\n\n}; // SurgSim\n\n\n\n#endif // SURGSIM_MATH_SHAPE_H\n", "file_path": "SurgSim/Math/Shape.h", "rank": 20, "score": 205589.865877652 }, { "content": "class Uniform<std::vector<T>> : public virtual UniformBase\n\n{\n\npublic:\n\n\t/// Returns the number of elements\n\n\tvirtual size_t getNumElements() const = 0;\n\n\n\n\t/// Sets the value of one of the uniform's elements\n\n\t/// \\param\tindex\tIndex of the element\n\n\t/// \\param\tvalue\tValue to set\n\n\tvirtual void setElement(size_t index, const T& value) = 0;\n\n\n\n\t/// Sets the value of all of the uniform's elements\n\n\t/// \\param\tvalue\tVector of values\n\n\tvirtual void set(const std::vector<T>& value) = 0;\n\n\n\n\t/// Gets the value of one of the uniform's elements\n\n\t/// \\param\tindex\tIndex of the element\n\n\t/// \\return\tValue of the element\n\n\tvirtual typename std::vector<T>::const_reference getElement(size_t index) const = 0;\n\n\n\n\t/// Gets the value of all of the uniform's elements\n\n\t/// \\return\tVector of values\n\n\tvirtual const std::vector<T>& get() const = 0;\n\n};\n\n\n\n}; // namespace Graphics\n\n\n\n}; // namespace SurgSim\n\n\n\n#endif // SURGSIM_GRAPHICS_UNIFORM_H", "file_path": "SurgSim/Graphics/Uniform.h", "rank": 21, "score": 197642.57432695592 }, { "content": "/// Graphic representation of a vector field\n\n/// Each point/location, i.e. (X,Y,Z), in the vector field is associated with a vector and an optional color\n\nclass VectorFieldRepresentation : public virtual Representation\n\n{\n\npublic:\n\n\t/// Constructor\n\n\t/// \\param name Name of VectorFieldRepresentation\n\n\texplicit VectorFieldRepresentation(const std::string& name) : Representation(name)\n\n\t{\n\n\t}\n\n\n\n\t/// Destructor\n\n\tvirtual ~VectorFieldRepresentation()\n\n\t{\n\n\t}\n\n\n\n\t/// Gets the vector field\n\n\t/// \\return The vector field\n\n\tvirtual std::shared_ptr<SurgSim::Graphics::VectorField> getVectorField() const = 0;\n\n\n\n\t/// Updates the vector field in a threadsafe manner\n\n\t/// \\param vectorfield the new data\n", "file_path": "SurgSim/Graphics/VectorFieldRepresentation.h", "rank": 22, "score": 191219.2151037731 }, { "content": "/// Local data structure to store the bones and their references to the transforms.\n\nstruct SurgSim::Graphics::BoneData\n\n{\n\n\tosg::ref_ptr<osgAnimation::Bone> osgBone;\n\n\tosg::ref_ptr<osgAnimation::StackedQuaternionElement> osgRotation;\n\n\tosg::ref_ptr<osgAnimation::StackedTranslateElement> osgTranslation;\n\n\tSurgSim::Math::RigidTransform3d neutralPose;\n\n\tSurgSim::Math::RigidTransform3d pose;\n\n\n\n\tBoneData() :\n\n\t\tosgBone(nullptr),\n\n\t\tosgRotation(nullptr),\n\n\t\tosgTranslation(nullptr),\n\n\t\tneutralPose(SurgSim::Math::RigidTransform3d::Identity()),\n\n\t\tpose(SurgSim::Math::RigidTransform3d::Identity())\n\n\t{\n\n\t}\n\n};\n\n\n\nnamespace\n\n{\n\n\n", "file_path": "SurgSim/Graphics/OsgSkeletonRepresentation.cpp", "rank": 23, "score": 185238.90950674072 }, { "content": "struct TestListener : public SurgSim::Input::InputConsumerInterface\n\n{\n\n\tvoid initializeInput(const std::string& device, const DataGroup& inputData) override\n\n\t{\n\n\t}\n\n\n\n\tvoid handleInput(const std::string& device, const DataGroup& inputData) override\n\n\t{\n\n\t\tbool button1, button2, button3;\n\n\t\tdouble x, y;\n\n\t\tint scrollDeltaX, scrollDeltaY;\n\n\n\n\t\tif (inputData.booleans().get(SurgSim::DataStructures::Names::BUTTON_1, &button1))\n\n\t\t{\n\n\t\t\tstd::cerr << \"button1 = \" << button1 << std::endl;\n\n\t\t}\n\n\t\tif (inputData.booleans().get(SurgSim::DataStructures::Names::BUTTON_2, &button2))\n\n\t\t{\n\n\t\t\tstd::cerr << \"button2 = \" << button2 << std::endl;\n\n\t\t}\n", "file_path": "SurgSim/Devices/Mouse/VisualTests/MouseVisualTests.cpp", "rank": 24, "score": 175639.67512221803 }, { "content": "struct TestListener : public SurgSim::Input::InputConsumerInterface\n\n{\n\n\tTestListener()\n\n\t{\n\n\t\tcreatKeyMap();\n\n\t\tcreateModifierMap();\n\n\t}\n\n\tvoid initializeInput(const std::string& device, const DataGroup& inputData) override {}\n\n\tvoid handleInput(const std::string& device, const DataGroup& inputData) override\n\n\t{\n\n\t\tint key, modifierMask;\n\n\t\tinputData.integers().get(\"key\", &key);\n\n\t\tinputData.integers().get(\"modifierMask\", &modifierMask);\n\n\n\n\t\tif (key != SurgSim::Devices::KeyCode::NONE)\n\n\t\t{\n\n\t\t\tstd::cerr << \"Key pressed :\" << keyMap[key] << std::endl;\n\n\t\t\tif (modifierMask != SurgSim::Devices::ModKeyMask::MODKEY_NONE)\n\n\t\t\t{\n\n\t\t\t\tif (modifierMap[modifierMask] != \"\")\n", "file_path": "SurgSim/Devices/Keyboard/VisualTests/KeyboardVisualTests.cpp", "rank": 25, "score": 175639.67512221803 }, { "content": "/// Perform linear interpolation on two poses\n\nclass PoseInterpolator : public SurgSim::Framework::Behavior\n\n{\n\npublic:\n\n\n\n\t/// Constructor\n\n\texplicit PoseInterpolator(const std::string& name);\n\n\n\n\t/// Set the starting pose. This is optional, if not set the target's pose\n\n\t/// will be used as the starting pose.\n\n\t/// \\param transform The starting pose.\n\n\tvoid setStartingPose(const SurgSim::Math::RigidTransform3d& transform);\n\n\n\n\t/// Set the end pose.\n\n\t/// \\param transform The end pose.\n\n\tvoid setEndingPose(const SurgSim::Math::RigidTransform3d& transform);\n\n\n\n\t/// Set the target of the interpolation, this is where the interpolated transform\n\n\t/// will be applied to. If this value is not set, the Scene Element that contains\n\n\t/// this PoseInterpolator will be used. If no starting pose is set, the pose of\n\n\t/// this scene element will be used as the starting pose\n", "file_path": "SurgSim/Blocks/PoseInterpolator.h", "rank": 26, "score": 173534.41953792793 }, { "content": "/// Osg specialization of the Font class, supports osgText::Font\n\nclass OsgFont : public SurgSim::Graphics::Font\n\n{\n\npublic:\n\n\t/// Constructor\n\n\tOsgFont();\n\n\n\n\t/// Destructor\n\n\tvirtual ~OsgFont();\n\n\n\n\tSURGSIM_CLASSNAME(SurgSim::Graphics::OsgFont);\n\n\n\n\t/// \\return the appropriate osgText::Font reference\n\n\tosg::ref_ptr<osgText::Font> getOsgFont() const;\n\n\n\n\n\nprotected:\n\n\n\n\tbool doLoad(const std::string& filePath) override;\n\n\n\nprivate:\n", "file_path": "SurgSim/Graphics/OsgFont.h", "rank": 27, "score": 172536.35258913855 }, { "content": "/// Particles Shape: A shape consisting of a group of particles of equal radius\n\nclass ParticlesShape : public VerticesShape, public SurgSim::DataStructures::Vertices<DataStructures::EmptyData>\n\n{\n\npublic:\n\n\t/// Constructor\n\n\t/// \\param radius The particles' radius (in m)\n\n\texplicit ParticlesShape(double radius = 0.0);\n\n\n\n\t/// Copy constructor\n\n\t/// \\param other The ParticleShape to be copied from\n\n\texplicit ParticlesShape(const ParticlesShape& other);\n\n\n\n\t/// Copy constructor from another Vertices type\n\n\t/// \\tparam V type of data stored in the other vertices\n\n\t/// \\param other The vertices to be copied from. Vertex data will not be copied\n\n\ttemplate <class V>\n\n\texplicit ParticlesShape(const SurgSim::DataStructures::Vertices<V>& other);\n\n\n\n\t/// Assignment when the template data is a different type\n\n\t/// \\tparam V type of data stored in the other Vertices\n\n\t/// \\param other the Vertices to copy from\n", "file_path": "SurgSim/Math/ParticlesShape.h", "rank": 28, "score": 171499.44106368942 }, { "content": "/// A class implementing the replay pose device, which is a pretend device that replays a recorded motion from a file\n\n///\n\n/// This can be useful not only for writing tests, but also as a way to replace real hardware devices in situations\n\n/// where the simulator needs to be run but the hardware is not currently available.\n\n/// The pose file can be created manually, or via the RecordPose DeviceFilter.\n\n/// Only one ReplayPoseDevice can be initialized at a time.\n\n///\n\n/// \\par Application input provided by the device:\n\n/// | type | name | |\n\n/// | ---- | ---- | --- |\n\n/// | pose | \"pose\" | %Device pose (units are meters). |\n\n///\n\n/// \\sa SurgSim::Input::CommonDevice\n\nclass ReplayPoseDevice : public SurgSim::Input::CommonDevice\n\n{\n\npublic:\n\n\t/// Constructor.\n\n\t/// \\param uniqueName A unique name for the device that will be used by the application.\n\n\texplicit ReplayPoseDevice(const std::string& uniqueName);\n\n\n\n\t/// \\return The filename from which the input poses are read (default is 'ReplayPoseDevice.txt')\n\n\tconst std::string getFileName() const;\n\n\n\n\t/// \\param fileName from which the input poses will be read (default is 'ReplayPoseDevice.txt')\n\n\tvoid setFileName(const std::string& fileName);\n\n\n\n\t/// \\return The rate (in Hz) at which the device is running (1KHz is the default)\n\n\tdouble getRate() const;\n\n\n\n\t/// \\param rate The rate (in Hz) at which the device will run (1KHz is the default)\n\n\t/// \\exception SurgSim::Framework::AssertionFailure if the method is called after initialization\n\n\tvoid setRate(double rate);\n\n\n", "file_path": "SurgSim/Devices/ReplayPoseDevice/ReplayPoseDevice.h", "rank": 29, "score": 169768.99881012045 }, { "content": "/// A class implementing the identity pose device, which is a pretend device that doesn't move.\n\n///\n\n/// The identity pose device produces a pose that's always the identity transform (no translation from the origin\n\n/// and no rotation from the model orientation).\n\n/// This can be useful not only for writing tests, but also as a way to replace real hardware devices in situations\n\n/// where the simulator needs to be run but the hardware is not currently available.\n\n///\n\n/// \\sa SurgSim::Input::DeviceInterface\n\nclass IdentityPoseDevice : public SurgSim::Input::CommonDevice\n\n{\n\npublic:\n\n\t/// Constructor.\n\n\t/// \\param uniqueName A unique name for the device that will be used by the application.\n\n\texplicit IdentityPoseDevice(const std::string& uniqueName);\n\n\n\n\tSURGSIM_CLASSNAME(SurgSim::Devices::IdentityPoseDevice);\n\n\n\n\tbool addInputConsumer(std::shared_ptr<SurgSim::Input::InputConsumerInterface> inputConsumer) override;\n\n\n\n\tbool initialize() override;\n\n\n\n\tbool isInitialized() const override;\n\n\n\nprotected:\n\n\t/// Builds the data layout for the application input (i.e. device output).\n\n\tstatic SurgSim::DataStructures::DataGroup buildInputData();\n\n\n\nprivate:\n", "file_path": "SurgSim/Devices/IdentityPoseDevice/IdentityPoseDevice.h", "rank": 30, "score": 169768.73307001044 }, { "content": "class ReplayPoseScaffold : public SurgSim::Framework::BasicThread\n\n{\n\n\tfriend class ReplayPoseDevice;\n\n\n\npublic:\n\n\t/// Constructor.\n\n\tReplayPoseScaffold();\n\n\n\n\t/// Destructor.\n\n\t~ReplayPoseScaffold();\n\n\n\n\t/// Gets or creates the scaffold shared by all ReplayPoseDevice instances.\n\n\t/// The scaffold is managed using a SharedInstance object, so it will be destroyed when all devices are released.\n\n\t/// \\return the scaffold object.\n\n\tstatic std::shared_ptr<ReplayPoseScaffold> getOrCreateSharedInstance();\n\n\n\nprotected:\n\n\tbool doInitialize() override;\n\n\tbool doStartUp() override;\n\n\tbool doUpdate(double dt) override;\n", "file_path": "SurgSim/Devices/ReplayPoseDevice/ReplayPoseScaffold.h", "rank": 31, "score": 169757.01763136033 }, { "content": "class Fem : public SurgSim::DataStructures::Vertices<VertexData>, public SurgSim::Framework::Asset,\n\n\t\tpublic std::enable_shared_from_this<Fem<VertexData, Element>>\n\n{\n\npublic:\n\n\t/// Default constructor\n\n\tFem();\n\n\n\n\t/// Adds FEM element to mesh of Element template type\n\n\t/// \\param element A shared pointer of the Element template type\n\n\t/// \\return The new size of the vector of elements\n\n\tsize_t addElement(std::shared_ptr<Element> element);\n\n\n\n\t/// Gets number of FEM elements in the mesh\n\n\t/// \\return The number of FEM elements stored\n\n\tsize_t getNumElements() const;\n\n\n\n\t/// Gets entire FEM element vector\n\n\t/// \\return A const vector of all FEM elements stored in the mesh\n\n\tconst std::vector<std::shared_ptr<Element>>& getElements() const;\n\n\n", "file_path": "SurgSim/Physics/Fem.h", "rank": 32, "score": 168302.90580174868 }, { "content": "class MockGroup : public SurgSim::Graphics::Group\n\n{\n\npublic:\n\n\t/// Constructor. The group is initially empty.\n\n\t/// \\param\tname\tName of the group\n\n\texplicit MockGroup(const std::string& name) : SurgSim::Graphics::Group(name), m_isVisible(false)\n\n\t{\n\n\t}\n\n\n\n\t/// Sets whether the group is currently visible\n\n\t/// \\param visible True for visible, false for invisible\n\n\tvirtual void setVisible(bool visible)\n\n\t{\n\n\t\tm_isVisible = visible;\n\n\t}\n\n\n\n\t/// Gets whether the group is currently visible\n\n\t/// \\return visible True for visible, false for invisible\n\n\tvirtual bool isVisible() const\n\n\t{\n\n\t\treturn m_isVisible;\n\n\t}\n\n\n\nprivate:\n\n\t/// Whether this group is currently visible or not\n\n\tbool m_isVisible;\n\n};\n\n\n", "file_path": "SurgSim/Graphics/UnitTests/MockObjects.h", "rank": 33, "score": 168149.05944742565 }, { "content": "/// View class for testing\n\nclass MockView : public SurgSim::Graphics::View\n\n{\n\npublic:\n\n\t/// Constructor\n\n\t/// \\param\tname\tName of the view\n\n\t/// \\post m_x and m_y are initialized to 0\n\n\t/// \\post m_width is initialized to 800, m_height to 600\n\n\t/// \\post m_isWindowBorderEnabled is initialized to true\n\n\t/// \\post m_numUpdates and m_sumDt are initialized to 0\n\n\t/// \\post m_transform is set to identity\n\n\texplicit MockView(const std::string& name) : SurgSim::Graphics::View(name),\n\n\t\tm_x(0),\n\n\t\tm_y(0),\n\n\t\tm_width(800),\n\n\t\tm_height(600),\n\n\t\tm_isWindowBorderEnabled(true),\n\n\t\tm_numUpdates(0),\n\n\t\tm_sumDt(0.0),\n\n\t\tm_isInitialized(false),\n\n\t\tm_isAwoken(false)\n", "file_path": "SurgSim/Graphics/UnitTests/MockObjects.h", "rank": 34, "score": 168149.05944742565 }, { "content": "/// Manager class for testing\n\nclass MockManager : public SurgSim::Graphics::Manager\n\n{\n\npublic:\n\n\n\n\tfriend class GraphicsManagerTest;\n\n\n\n\t/// Constructor\n\n\t/// \\post m_numUpdates and m_sumDt are initialized to 0\n\n\tMockManager() : SurgSim::Graphics::Manager(),\n\n\t\tm_numUpdates(0),\n\n\t\tm_sumDt(0.0)\n\n\t{\n\n\t}\n\n\n\n\t/// Returns the number of times the manager has been updated\n\n\tint getNumUpdates() const\n\n\t{\n\n\t\treturn m_numUpdates;\n\n\t}\n\n\t/// Returns the sum of the dt that the manager has been updated with\n", "file_path": "SurgSim/Graphics/UnitTests/MockObjects.h", "rank": 35, "score": 168149.05944742565 }, { "content": "/// Representation class for testing\n\nclass MockRepresentation : public SurgSim::Graphics::Representation\n\n{\n\npublic:\n\n\t/// Constructor\n\n\t/// \\param\tname\tName of the representation\n\n\t/// \\post m_numUpdates and m_sumDt are initialized to 0\n\n\t/// \\post m_transform is set to identity\n\n\t/// \\post m_isInitialized and m_isAwoken are set to false\n\n\texplicit MockRepresentation(const std::string& name) : SurgSim::Graphics::Representation(name),\n\n\t\tm_numUpdates(0),\n\n\t\tm_sumDt(0.0),\n\n\t\tm_isInitialized(false),\n\n\t\tm_isAwoken(false),\n\n\t\tm_drawAsWireFrame(false)\n\n\t{\n\n\t\tm_transform.setIdentity();\n\n\t}\n\n\n\n\t/// Returns the number of times the representation has been updated\n\n\tint getNumUpdates() const\n", "file_path": "SurgSim/Graphics/UnitTests/MockObjects.h", "rank": 36, "score": 168149.05944742565 }, { "content": "/// Camera class for testing\n\nclass MockCamera : public SurgSim::Graphics::Camera\n\n{\n\npublic:\n\n\t/// Constructor\n\n\t/// \\param\tname\tName of the camera\n\n\t/// \\post m_numUpdates and m_sumDt are initialized to 0\n\n\t/// \\post m_transform is set to identity, m_eye to (0,0,0), m_center to (0, 0, -1), and m_up to (0, 1, 0)\n\n\t/// \\post m_isVisible is set to true\n\n\texplicit MockCamera(const std::string& name) :\n\n\t\tSurgSim::Graphics::Representation(name),\n\n\t\tSurgSim::Graphics::Camera(name),\n\n\t\tm_numUpdates(0),\n\n\t\tm_sumDt(0.0)\n\n\t{\n\n\t\tm_pose.setIdentity();\n\n\t\tm_viewMatrix.setIdentity();\n\n\t\tm_projectionMatrix.setIdentity();\n\n\t}\n\n\n\n\t/// Returns the number of times the representation has been updated\n", "file_path": "SurgSim/Graphics/UnitTests/MockObjects.h", "rank": 37, "score": 168149.05944742565 }, { "content": "/// Representation that does not subclass any graphics components\n\nclass NonGraphicsRepresentation : public SurgSim::Framework::Representation\n\n{\n\npublic:\n\n\t/// Constructor\n\n\t/// \\param\tname\tName of the representation\n\n\texplicit NonGraphicsRepresentation(const std::string& name) : SurgSim::Framework::Representation(name)\n\n\t{\n\n\t}\n\n};\n\n\n\n#endif // SURGSIM_GRAPHICS_UNITTESTS_MOCKOBJECTS_H\n", "file_path": "SurgSim/Graphics/UnitTests/MockObjects.h", "rank": 38, "score": 166095.79485032186 }, { "content": "/// A simple box as a scenelement\n\nclass SimpleBox : public SurgSim::Framework::BasicSceneElement\n\n{\n\npublic:\n\n\texplicit SimpleBox(const std::string& name) : BasicSceneElement(name)\n\n\t{\n\n\t\tm_box = std::make_shared<SurgSim::Graphics::OsgBoxRepresentation>(getName() + \" Graphics\");\n\n\n\n\t\t// The material that this object uses\n\n\t\tm_box->setMaterial(materials[\"basicShadowed\"]);\n\n\n\n\t\t// Assign this to the pass for shadowing objects\n\n\t\tm_box->addGroupReference(SurgSim::Blocks::GROUP_SHADOW_CASTER);\n\n\n\n\t\t// Assign this to the pass for shadowed objects\n\n\t\tm_box->addGroupReference(SurgSim::Blocks::GROUP_SHADOW_RECEIVER);\n\n\t}\n\n\n\n\tbool doInitialize() override\n\n\t{\n\n\t\taddComponent(m_box);\n", "file_path": "Examples/GraphicsScene/GraphicsScene.cpp", "rank": 39, "score": 166089.03764251858 }, { "content": "class SimpleSphere : public SurgSim::Framework::BasicSceneElement\n\n{\n\npublic:\n\n\texplicit SimpleSphere(const std::string& name) : BasicSceneElement(name)\n\n\t{\n\n\t\tm_sphere = std::make_shared<SurgSim::Graphics::OsgSphereRepresentation>(getName() + \" Graphics\");\n\n\t\tm_sphere->setMaterial(materials[\"basicShadowed\"]);\n\n\t\tm_sphere->addGroupReference(SurgSim::Blocks::GROUP_SHADOW_CASTER);\n\n\t\tm_sphere->addGroupReference(SurgSim::Blocks::GROUP_SHADOW_RECEIVER);\n\n\t}\n\n\n\n\tbool doInitialize() override\n\n\t{\n\n\t\taddComponent(m_sphere);\n\n\t\treturn true;\n\n\t}\n\n\n\n\tvoid setRadius(double radius)\n\n\t{\n\n\t\tm_sphere->setRadius(radius);\n", "file_path": "Examples/GraphicsScene/GraphicsScene.cpp", "rank": 40, "score": 166089.03764251858 }, { "content": "struct convert <std::vector<std::shared_ptr<SurgSim::Framework::SceneElement>>>\n\n{\n\n\n\n\tstatic bool decode(const Node& node,\n\n\t\t\t\t\t std::vector<std::shared_ptr<SurgSim::Framework::SceneElement>>& rhs, //NOLINT\n\n\t\t\t\t\t std::vector<std::string>* stack = nullptr);\n\n};\n\n\n\n\n\ntemplate<>\n", "file_path": "SurgSim/Framework/FrameworkConvert.h", "rank": 41, "score": 165738.86955443048 }, { "content": "/// Square with center at local origin.\n\nstruct GlutSquare : public GlutRenderObject\n\n{\n\n\t/// The unit direction along one of the pairs edges of the square.\n\n\tSurgSim::Math::Vector3d planeDirectionX;\n\n\t/// The unit direction along the other pair of edges of the square.\n\n\tSurgSim::Math::Vector3d planeDirectionY;\n\n\t/// One half of the edge length of the square, in meters.\n\n\tdouble halfSize;\n\n\t/// Color of the square.\n\n\tSurgSim::Math::Vector3d color;\n\n\n\n\t/// Constructor\n\n\t/// \\param halfSize One half of the edge length of the square, in meters.\n\n\t/// \\param color Color of the square.\n\n\t/// \\param planeDirectionX The unit direction along one of the pairs edges of the square, default is X-axis.\n\n\t/// \\param planeDirectionY The unit direction along the other pair of edges of the square, default is Y-axis.\n\n\tGlutSquare(double halfSize, const SurgSim::Math::Vector3d& color,\n\n\t\t\t const SurgSim::Math::Vector3d& planeDirectionX = SurgSim::Math::Vector3d(1.0, 0.0, 0.0),\n\n\t\t\t const SurgSim::Math::Vector3d& planeDirectionY = SurgSim::Math::Vector3d(0.0, 1.0, 0.0)) :\n\n\t\tGlutRenderObject(), planeDirectionX(planeDirectionX), planeDirectionY(planeDirectionY),\n\n\t\thalfSize(halfSize), color(color)\n\n\t{\n\n\t}\n\n\n\n\t/// Draws the square with Glut.\n\n\tvirtual void draw();\n\n};\n\n\n", "file_path": "SurgSim/Testing/VisualTestCommon/GlutRenderer.h", "rank": 42, "score": 164575.8994544938 }, { "content": "/// Group of objects which provides a transform hierarchy.\n\nstruct GlutGroup : public GlutRenderObject\n\n{\n\n\t/// Children of this group.\n\n\tstd::vector< std::shared_ptr<GlutRenderObject> > children;\n\n\n\n\t/// Constructor. The group is initialized with no children.\n\n\tGlutGroup() : GlutRenderObject()\n\n\t{\n\n\t}\n\n\n\n\t/// Draws the group with Glut and iterates through its children to draw them.\n\n\tvirtual void draw();\n\n};\n\n\n", "file_path": "SurgSim/Testing/VisualTestCommon/GlutRenderer.h", "rank": 43, "score": 164575.8994544938 }, { "content": "struct TestInputConsumer : public InputConsumerInterface\n\n{\n\npublic:\n\n\tTestInputConsumer() :\n\n\t m_numTimesReceivedInput(0)\n\n\t {\n\n\t }\n\n\n\n\t virtual void initializeInput(const std::string& device, const DataGroup& initialInput)\n\n\t {\n\n\t }\n\n\t virtual void handleInput(const std::string& device, const DataGroup& inputData);\n\n\n\n\t int m_numTimesReceivedInput;\n\n\t DataGroup m_lastReceivedInput;\n\n};\n\n\n", "file_path": "SurgSim/Input/UnitTests/TestDevice.h", "rank": 44, "score": 164575.8994544938 }, { "content": "struct TestOutputProducer : public OutputProducerInterface\n\n{\n\npublic:\n\n\tTestOutputProducer() :\n\n\t m_numTimesRequestedOutput(0),\n\n\t\t m_refuseToProduce(false)\n\n\t {\n\n\t\t DataGroupBuilder builder;\n\n\t\t builder.addInteger(\"value\");\n\n\t\t m_nextSentOutput = builder.createData();\n\n\t\t m_nextSentOutput.integers().set(\"value\", 123);\n\n\t }\n\n\n\n\t virtual bool requestOutput(const std::string& device, DataGroup* outputData);\n\n\n\n\t int m_numTimesRequestedOutput;\n\n\t bool m_refuseToProduce;\n\n\t DataGroup m_nextSentOutput;\n\n};\n\n\n\n#endif // SURGSIM_INPUT_UNITTESTS_TESTDEVICE_H\n", "file_path": "SurgSim/Input/UnitTests/TestDevice.h", "rank": 45, "score": 164575.8994544938 }, { "content": "class TriangleMesh : public Vertices<VertexData>, public SurgSim::Framework::Asset,\n\n\tpublic std::enable_shared_from_this<TriangleMesh<VertexData, EdgeData, TriangleData>>\n\n{\n\npublic:\n\n\t/// Edge type for convenience (Ids of the 2 vertices)\n\n\ttypedef MeshElement<2, EdgeData> EdgeType;\n\n\t/// Triangle type for convenience (Ids of the 3 vertices)\n\n\ttypedef MeshElement<3, TriangleData> TriangleType;\n\n\n\n\t/// Constructor. The mesh is initially empty (no vertices, no edges, no triangles).\n\n\tTriangleMesh();\n\n\n\n\t/// Copy constructor when the template data is the same type\n\n\t/// \\param other the mesh to copy from\n\n\tTriangleMesh(const TriangleMesh<VertexData, EdgeData, TriangleData>& other);\n\n\n\n\t/// Copy constructor when the template data is a different type\n\n\t/// \\tparam\tV Type of extra data stored in each vertex\n\n\t/// \\tparam\tE Type of extra data stored in each edge\n\n\t/// \\tparam\tT Type of extra data stored in each triangle\n", "file_path": "SurgSim/DataStructures/TriangleMesh.h", "rank": 46, "score": 163850.00243707787 }, { "content": "/// Base class for a data structure for holding MassSpring mesh data.\n\nclass MassSpringModel : public SurgSim::DataStructures::Vertices<Mass>, public SurgSim::Framework::Asset,\n\n\tpublic std::enable_shared_from_this<MassSpringModel>\n\n{\n\npublic:\n\n\t/// Default constructor\n\n\tMassSpringModel();\n\n\n\n\tSURGSIM_CLASSNAME(SurgSim::Physics::MassSpringModel);\n\n\n\n\t/// Adds a mass\n\n\t/// \\param mass The mass to add to the representation\n\n\t/// \\note Masses are kept in an ordered list, giving them an index\n\n\t/// \\note This mass will be associated with the node of same index in any associated OdeState\n\n\tvoid addMass(const std::shared_ptr<Mass> mass);\n\n\n\n\t/// Adds a spring, and sets its rest length.\n\n\t/// \\param spring The spring to add to the representation\n\n\tvoid addSpring(const std::shared_ptr<Spring> spring);\n\n\n\n\t/// Gets the number of masses\n", "file_path": "SurgSim/Physics/MassSpringModel.h", "rank": 47, "score": 163165.8335138752 }, { "content": "/// Base class that defines the interface for graphics materials.\n\n///\n\n/// Graphics materials define the visual appearance of graphics representations and are composed of the uniforms and\n\n/// shaders applied used when rendering the geometry.\n\n/// \\sa\tUniformBase\n\n/// \\sa Shader\n\nclass Material : public SurgSim::Framework::Component\n\n{\n\npublic:\n\n\n\n\t/// Constructor\n\n\texplicit Material(const std::string& name) : Component(name) {}\n\n\n\n\t/// Destructor.\n\n\t// (Note that Visual Studio does not support \"= default\" yet.)\n\n\tvirtual ~Material()\n\n\t{\n\n\t}\n\n\n\n\t/// Adds a uniform to this material.\n\n\t/// \\param\tuniform\tUniform to add.\n\n\tvirtual void addUniform(std::shared_ptr<UniformBase> uniform) = 0;\n\n\n\n\t/// Adds a GLSL typed uniform to this material\n\n\t/// \\param type the type of the uniform\n\n\t/// \\param name the name that this uniform should have\n", "file_path": "SurgSim/Graphics/Material.h", "rank": 48, "score": 162478.35702087352 }, { "content": "/// Base graphics representation class, which defines the interface that all graphics representations must implement.\n\n///\n\n/// A Graphics::Representation is the visual Framework::Representation of a Framework::SceneElement in the\n\n/// Framework::Scene. Graphical representations can request to be assigned to groups, groups are used to select certain\n\n/// elements for rendering in various special effects.\n\nclass Representation : public SurgSim::Framework::Representation\n\n{\n\npublic:\n\n\n\n\tstatic const std::string DefaultGroupName;\n\n\tstatic const std::string DefaultHudGroupName;\n\n\n\n\t/// Constructor\n\n\t/// \\param\tname\tName of the representation\n\n\texplicit Representation(const std::string& name);\n\n\n\n\t/// Destructor\n\n\tvirtual ~Representation();\n\n\n\n\t/// Sets the material that defines the visual appearance of the representation\n\n\t/// \\param\tmaterial\tGraphics material\n\n\t/// \\return\tTrue if set successfully, otherwise false\n\n\tvirtual bool setMaterial(std::shared_ptr<SurgSim::Framework::Component> material) = 0;\n\n\n\n\t/// Gets the material that defines the visual appearance of the representation\n", "file_path": "SurgSim/Graphics/Representation.h", "rank": 49, "score": 162478.06020884577 }, { "content": "/// Base graphics view class, which defines the basic interface for all graphics views.\n\n///\n\n/// A Graphics::View provides a visualization of the scene to the user.\n\n///\n\n/// A Graphics::Camera controls the viewpoint of this View.\n\nclass View : public SurgSim::Framework::Component\n\n{\n\npublic:\n\n\t/// Constructor\n\n\t/// \\param\tname\tName of the view\n\n\texplicit View(const std::string& name);\n\n\n\n\tenum StereoMode\n\n\t{\n\n\t\tSTEREO_MODE_NONE = -1,\n\n\t\tSTEREO_MODE_QUAD_BUFFER,\n\n\t\tSTEREO_MODE_ANAGLYPHIC,\n\n\t\tSTEREO_MODE_HORIZONTAL_SPLIT,\n\n\t\tSTEREO_MODE_VERTICAL_SPLIT,\n\n\t\tSTEREO_MODE_LEFT_EYE,\n\n\t\tSTEREO_MODE_RIGHT_EYE,\n\n\t\tSTEREO_MODE_HORIZONTAL_INTERLACE,\n\n\t\tSTEREO_MODE_VERTICAL_INTERLACE,\n\n\t\tSTEREO_MODE_CHECKERBOARD,\n\n\t\tSTEREO_MODE_COUNT\n", "file_path": "SurgSim/Graphics/View.h", "rank": 50, "score": 162473.3560342913 }, { "content": "// Wraps the Graphics Model class\n\nclass Model : public SurgSim::Framework::Asset\n\n{\n\n};\n\n\n\n}\n\n}\n\n\n\n#endif\n", "file_path": "SurgSim/Graphics/Model.h", "rank": 51, "score": 162472.10645751917 }, { "content": "/// Abstract base class for the Font Asset, fonts are typefaces that can be used to render\n\n/// text on screen they would usually be loaded from disk\n\nclass Font : public SurgSim::Framework::Asset\n\n{\n\n\n\n};\n\n\n\n}\n\n}\n\n\n\n#endif\n", "file_path": "SurgSim/Graphics/Font.h", "rank": 52, "score": 162471.30938007578 }, { "content": "/// Representation class for testing\n\nclass MockOsgRepresentation : public SurgSim::Graphics::OsgRepresentation\n\n{\n\npublic:\n\n\t/// Constructor\n\n\t/// \\param\tname\tName of the representation\n\n\t/// \\post m_numUpdates and m_sumDt are initialized to 0\n\n\t/// \\post m_transform is set to identity\n\n\t/// \\post m_isInitialized and m_isAwoken are set to false\n\n\t/// \\post m_isVisible is set to true\n\n\texplicit MockOsgRepresentation(const std::string& name) :\n\n\t\tSurgSim::Graphics::Representation(name),\n\n\t\tSurgSim::Graphics::OsgRepresentation(name),\n\n\t\tm_numUpdates(0),\n\n\t\tm_sumDt(0.0),\n\n\t\tm_isInitialized(false),\n\n\t\tm_isAwoken(false)\n\n\t{\n\n\t}\n\n\n\n\t/// Returns the number of times the representation has been updated\n", "file_path": "SurgSim/Graphics/UnitTests/MockOsgObjects.h", "rank": 53, "score": 162209.30734899527 }, { "content": "struct convert<std::shared_ptr<SurgSim::Graphics::OsgUniformBase>>\n\n{\n\n\tstatic Node encode(const std::shared_ptr<SurgSim::Graphics::OsgUniformBase> rhs);\n\n\tstatic bool decode(const Node& node, std::shared_ptr<SurgSim::Graphics::OsgUniformBase>& rhs); //NOLINT\n\n};\n\n\n\n};\n\n\n\n\n\n#endif // SURGSIM_GRAPHICS_OSGUNIFORMBASE_H\n", "file_path": "SurgSim/Graphics/OsgUniformBase.h", "rank": 54, "score": 161335.9744069724 }, { "content": "struct RepresentationTest : public ::testing::Test\n\n{\n\n\tvirtual void SetUp()\n\n\t{\n\n\t\truntime = std::make_shared<Framework::Runtime>();\n\n\t\tscene = runtime->getScene();\n\n\t\telement = std::make_shared<BasicSceneElement>(\"Element\");\n\n\t\tplane = std::make_shared<PlaneShape>();\n\n\t\tsphere = std::make_shared<SphereShape>(1.0);\n\n\t\tplaneRep = std::make_shared<ShapeCollisionRepresentation>(\"PlaneShape\");\n\n\t\tsphereRep = std::make_shared<ShapeCollisionRepresentation>(\"SphereShape\");\n\n\n\n\t\tplaneRep->setShape(plane);\n\n\t\tplaneRep->setLocalPose(RigidTransform3d::Identity());\n\n\n\n\t\tsphereRep->setShape(sphere);\n\n\t\tsphereRep->setLocalPose(RigidTransform3d::Identity());\n\n\n\n\t\telement->addComponent(planeRep);\n\n\t\telement->addComponent(sphereRep);\n", "file_path": "SurgSim/Collision/UnitTests/RepresentationTest.cpp", "rank": 55, "score": 160987.88841955084 }, { "content": "/// Mesh shape: shape made of a triangle mesh\n\n/// The triangle mesh needs to be watertight to produce valid volume, center and second moment of\n\n/// volume. If it is not the case and you need valid geometric properties, use SurfaceMeshShape instead.\n\n/// Various geometrical properties (volume based) are computed from the triangle mesh using\n\n/// David Eberly's work (http://www.geometrictools.com/Documentation/PolyhedralMassProperties.pdf)\n\n/// which is improving Brian Mirtich previous work (http://www.cs.berkeley.edu/~jfc/mirtich/massProps.html)\n\n/// by making the assumption that the polyhedral mesh is composed of triangles.\n\n///\n\n/// \\note The internal mesh should not be modified, otherwise the geometric properties will be invalid.\n\n/// \\note Practical use cases:\n\n/// \\note * Fixed/Rigid object, the mesh will not change anyway.\n\n/// \\note * Deformable object, the mesh will be updated, but the geometric properties will not be used.\n\n///\n\n/// \\sa SurfaceMeshShape\n\nclass MeshShape : public VerticesShape, public SurgSim::DataStructures::TriangleMesh<SurgSim::DataStructures::EmptyData,\n\n\tSurgSim::DataStructures::EmptyData, SurgSim::DataStructures::NormalData>\n\n{\n\npublic:\n\n\t/// Constructor\n\n\tMeshShape();\n\n\n\n\t/// Copy constructor\n\n\t/// \\param other The MeshShape to be copied from\n\n\texplicit MeshShape(const MeshShape& other);\n\n\n\n\t/// Copy constructor when the template data is a different type\n\n\t/// \\tparam\tVertexData Type of extra data stored in each vertex\n\n\t/// \\tparam\tEdgeData Type of extra data stored in each edge\n\n\t/// \\tparam\tTriangleData Type of extra data stored in each triangle\n\n\t/// \\param other The mesh to be copied from. Vertex, edge and triangle data will not be copied\n\n\ttemplate <class V, class E, class T>\n\n\texplicit MeshShape(const SurgSim::DataStructures::TriangleMesh<V, E, T>& other);\n\n\n\n\tSURGSIM_CLASSNAME(SurgSim::Math::MeshShape);\n", "file_path": "SurgSim/Math/MeshShape.h", "rank": 56, "score": 160042.73535707136 }, { "content": "/// Basic graphics manager class which manages graphics components to provide a visualization of the scene to the user.\n\n///\n\n/// Graphics::Manager manages Graphics::Representation, Graphics::Group, and Graphics::View components.\n\nclass Manager : public SurgSim::Framework::ComponentManager\n\n{\n\npublic:\n\n\t/// Constructor\n\n\tManager();\n\n\t/// Destructor\n\n\tvirtual ~Manager();\n\n\n\n\t/// Returns the representations assigned to the manager\n\n\tconst std::vector<std::shared_ptr<Representation>>& getRepresentations() const\n\n\t{\n\n\t\treturn m_representations;\n\n\t}\n\n\n\n\t/// Returns the groups assigned to the manager\n\n\tconst std::unordered_map<std::string, std::shared_ptr<Group>>& getGroups() const\n\n\t{\n\n\t\treturn m_groups;\n\n\t}\n\n\n", "file_path": "SurgSim/Graphics/Manager.h", "rank": 57, "score": 159833.0227194375 }, { "content": "struct PosedShape\n\n{\n\n\tPosedShape()\n\n\t{\n\n\t\tpose = Math::RigidTransform3d::Identity();\n\n\t}\n\n\tPosedShape(const T& shapeInput, const Math::RigidTransform3d& poseInput) : shape(shapeInput), pose(poseInput) {}\n\n\n\n\tvoid invalidate()\n\n\t{\n\n\t\tshape = nullptr;\n\n\t}\n\n\tconst T& getShape() const\n\n\t{\n\n\t\treturn shape;\n\n\t}\n\n\tconst Math::RigidTransform3d& getPose() const\n\n\t{\n\n\t\treturn pose;\n\n\t}\n\n\n\nprotected:\n\n\tT shape;\n\n\tMath::RigidTransform3d pose;\n\n};\n\n\n\n/// PosedShapeMotion is embedding the motion of a PosedShape, providing a posed shape at 2 different instant.\n\ntemplate <class T>\n", "file_path": "SurgSim/Math/Shape.h", "rank": 58, "score": 158798.2096698458 }, { "content": "class ImplicitSurfaceRenderTests : public RenderTest\n\n{\n\n\n\n};\n\n\n\nTEST_F(ImplicitSurfaceRenderTests, PointSpriteFluid)\n\n{\n\n\tMath::Vector4f diffuseColor(0.83f, 0.0f, 0.0f, 1.0f);\n\n\tMath::Vector4f specularColor(0.8f, 0.8f, 0.8f, 1.0f);\n\n\n\n\tstd::array<int, 2> dimensions = {1280, 720};\n\n\tviewElement->getView()->setDimensions(dimensions);\n\n\tviewElement->getCamera()->setPerspectiveProjection(45, 1.7, 0.01, 10.0);\n\n\tviewElement->getCamera()->setAmbientColor(Math::Vector4d(0.2, 0.2, 0.2, 1.0));\n\n\n\n\n\n\tauto interpolator = std::make_shared<Blocks::PoseInterpolator>(\"Interpolator\");\n\n\tRigidTransform3d from = makeRigidTransform(\n\n\t\t\t\t\t\t\t\tVector3d(0.5, 0.0, -0.5),\n\n\t\t\t\t\t\t\t\tVector3d(0.0, 0.0, 0.0),\n", "file_path": "SurgSim/Graphics/RenderTests/ImplicitSurfaceRenderTests.cpp", "rank": 59, "score": 158000.3332198914 }, { "content": "class PaintBehaviorRenderTests : public RenderTest\n\n{\n\n\n\n};\n\n\n\nTEST_F(PaintBehaviorRenderTests, PaintTest)\n\n{\n\n\tviewElement->getCamera()->setLocalPose(makeRigidTransform(Math::Vector3d(0.0, 0.2, 0.0),\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t Math::Vector3d(0.0, 0.0, 0.0),\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t Math::Vector3d(0.0, 0.0, -1.0)));\n\n\tviewElement->getCamera()->setAmbientColor(Math::Vector4d(0.2, 0.2, 0.2, 1.0));\n\n\n\n\tauto light = std::make_shared<Graphics::OsgLight>(\"Light\");\n\n\tlight->setDiffuseColor(Math::Vector4d(1.0, 1.0, 1.0, 1.0));\n\n\tlight->setSpecularColor(Math::Vector4d(0.8, 0.8, 0.8, 1.0));\n\n\tlight->setLightGroupReference(Graphics::Representation::DefaultGroupName);\n\n\n\n\tauto lightElement = std::make_shared<Framework::BasicSceneElement>(\"LightElement\");\n\n\tlightElement->setPose(makeRigidTranslation(Math::Vector3d(2.0, 2.0, 2.0)));\n\n\tlightElement->addComponent(light);\n", "file_path": "SurgSim/Graphics/RenderTests/PaintBehaviorRenderTests.cpp", "rank": 60, "score": 158000.3332198914 }, { "content": "struct VertexData\n\n{\n\n\tSurgSim::DataStructures::OptionalValue<SurgSim::Math::Vector2d> texture;\n\n\tSurgSim::DataStructures::OptionalValue<SurgSim::Math::Vector4d> color;\n\n\n\n\t/// Equality operator.\n\n\t/// \\param\trhs\tThe right hand side.\n\n\t/// \\return\ttrue if the parameters are considered equivalent.\n\n\tbool operator==(const SurgSim::Graphics::VertexData& rhs) const\n\n\t{\n\n\t\treturn texture == rhs.texture &&\n\n\t\t\t color == rhs.color;\n\n\t}\n\n\n\n\t/// Inequality operator.\n\n\t/// \\param\trhs\tThe right hand side.\n\n\t/// \\return\ttrue if the parameters are not considered equivalent.\n\n\tbool operator!=(const SurgSim::Graphics::VertexData& rhs) const\n\n\t{\n\n\t\treturn !((*this) == rhs);\n\n\t}\n\n};\n\n\n\nSURGSIM_STATIC_REGISTRATION(Mesh);\n\n\n", "file_path": "SurgSim/Graphics/Mesh.h", "rank": 61, "score": 157911.9388203977 }, { "content": "/// Common base class for all graphics uniforms.\n\n///\n\n/// Graphics uniforms act as parameters to shader programs.\n\n/// \\note\n\n/// SurgSim::Graphics::Uniform is templated on the type of value, so this base class allows a pointer to any type\n\n/// of Uniform.\n\nclass UniformBase : public SurgSim::Framework::Accessible\n\n{\n\npublic:\n\n\t/// Destructor\n\n\tvirtual ~UniformBase() = 0;\n\n};\n\n\n\ninline UniformBase::~UniformBase()\n\n{\n\n}\n\n\n\n}; // namespace Graphics\n\n\n\n}; // namespace SurgSim\n\n\n\n#endif // SURGSIM_GRAPHICS_UNIFORMBASE_H\n", "file_path": "SurgSim/Graphics/UniformBase.h", "rank": 62, "score": 157327.58848378115 }, { "content": "/// Fem class data structure implementation for 2-Dimensional FEMs\n\n/// \\sa Fem\n\nclass Fem2D : public Fem<FemElementStructs::RotationVectorData, FemElementStructs::FemElement2DParameter>\n\n{\n\npublic:\n\n\t/// Default constructor\n\n\tFem2D();\n\n\n\n\tSURGSIM_CLASSNAME(SurgSim::Physics::Fem2D);\n\n\n\nprotected:\n\n\t// Asset API override\n\n\tbool doLoad(const std::string& filePath) override;\n\n};\n\n\n\n} // namespace Physics\n\n} // namespace SurgSim\n\n\n\n#endif // SURGSIM_PHYSICS_FEM2D_H\n", "file_path": "SurgSim/Physics/Fem2D.h", "rank": 63, "score": 156807.06905083568 }, { "content": "/// Fem class data structure implementation for 1-Dimensional FEMs\n\n/// \\sa Fem\n\nclass Fem1D : public Fem<FemElementStructs::RotationVectorData, FemElementStructs::FemElement1DParameter>\n\n{\n\npublic:\n\n\tFem1D();\n\n\n\n\tSURGSIM_CLASSNAME(SurgSim::Physics::Fem1D);\n\n\n\nprotected:\n\n\t// Asset API override\n\n\tbool doLoad(const std::string& filePath) override;\n\n};\n\n\n\n} // namespace Physics\n\n} // namespace SurgSim\n\n\n\n#endif // SURGSIM_PHYSICS_FEM1D_H\n", "file_path": "SurgSim/Physics/Fem1D.h", "rank": 64, "score": 156807.06905083568 }, { "content": "struct ContactFilteringTest : public ::testing::Test\n\n{\n\n\tvirtual void SetUp()\n\n\t{\n\n\t\t// Setup Framework\n\n\t\truntime = std::make_shared<Framework::Runtime>();\n\n\t\tstate = std::make_shared<PhysicsManagerState>();\n\n\t\tcontactFiltering = std::make_shared<ContactFiltering>(false);\n\n\n\n\t\tstd::vector<std::shared_ptr<Collision::ContactFilter>> filters;\n\n\t\tfilter = std::make_shared<MockContactFilter>(\"Filter\");\n\n\t\tfilters.push_back(filter);\n\n\t\tstate->setContactFilters(filters);\n\n\n\n\t\tcollision0 = std::make_shared<Physics::RigidCollisionRepresentation>(\"Collision0\");\n\n\n\n\n\n\t\tpairWithContacts = std::make_shared<Collision::CollisionPair>(collision0, collision0);\n\n\t\tauto contact = std::make_shared<Collision::Contact>(Collision::COLLISION_DETECTION_TYPE_NONE,\n\n\t\t\t\t\t 0.0, 0.0, Math::Vector3d::Zero(), Math::Vector3d::Zero(),\n", "file_path": "SurgSim/Physics/UnitTests/ContactFilteringTest.cpp", "rank": 65, "score": 156536.09961359453 }, { "content": "struct RigidStateTest : public ::testing::Test\n\n{\n\n\tvoid SetUp()\n\n\t{\n\n\t\tquaterniond = SurgSim::Math::Quaterniond(0.5, 0.4, 0.3, 0.2);\n\n\t\tquaterniond.normalize();\n\n\t\ttranslation = SurgSim::Math::Vector3d(5.2, -6.13, 4.12356);\n\n\t\tpose = SurgSim::Math::makeRigidTransform(quaterniond, translation);\n\n\t\tlinearVelocity = SurgSim::Math::Vector3d(2, -3.1, -2.75);\n\n\t\tangularVelocity = SurgSim::Math::Vector3d (5, -10, 21.5);\n\n\t\tid4x4 = SurgSim::Math::RigidTransform3d::Identity();\n\n\t}\n\n\n\n\tSurgSim::Math::Quaterniond quaterniond;\n\n\tSurgSim::Math::Vector3d translation;\n\n\tSurgSim::Math::RigidTransform3d pose;\n\n\n\n\tSurgSim::Math::Vector3d linearVelocity;\n\n\tSurgSim::Math::Vector3d angularVelocity;\n\n\n", "file_path": "SurgSim/Physics/UnitTests/RigidStateTest.cpp", "rank": 66, "score": 156536.09961359453 }, { "content": "struct CompoundShapeTest : public ::testing::Test\n\n{\n\npublic:\n\n\n\n\tvirtual void SetUp()\n\n\t{\n\n\t\tcompoundShape = std::make_shared<CompoundShape>();\n\n\t\tshape1 = std::make_shared<BoxShape>(1.0, 1.0, 1.0);\n\n\t\tshape2 = std::make_shared<BoxShape>(1.0, 2.0, 1.0);\n\n\n\n\t\ttransform1 = makeRigidTranslation(Vector3d(-1.0, 0.0, 0.0));\n\n\t\ttransform2 = makeRigidTranslation(Vector3d(1.0, 0.0, 0.0));\n\n\t}\n\n\n\n\tstd::shared_ptr<CompoundShape> compoundShape;\n\n\tstd::shared_ptr<Shape> shape1;\n\n\tstd::shared_ptr<Shape> shape2;\n\n\n\n\tRigidTransform3d transform1;\n\n\tRigidTransform3d transform2;\n", "file_path": "SurgSim/Math/UnitTests/CompoundShapeTests.cpp", "rank": 67, "score": 156536.09961359453 }, { "content": "/// Encapsulation of all the components necessary needed to implement a full renderpass, this SceneElement contains\n\n/// a Camera and Group, it can also take a Material (for shaders and uniforms) and a RenderTarget for textures that\n\n/// are used as the output for the camera.\n\n/// Other components do not need to be added to the pass explicitly, they only need to refer to the passes name in\n\n/// their respective groupReferences to be added to the render pass. The passes attributes should all be set up through\n\n/// uniforms in the material.\n\nclass RenderPass : public SurgSim::Framework::SceneElement\n\n{\n\npublic:\n\n\n\n\t/// Constructor\n\n\t/// \\param name The name for this SceneElement\n\n\texplicit RenderPass(const std::string& name);\n\n\t~RenderPass();\n\n\n\n\t/// Executes the initialize operation.\n\n\t/// \\return\ttrue if it succeeds, false if it fails.\n\n\tbool doInitialize() override;\n\n\n\n\t/// Sets render target for the camera, this abstracts the textures that are being used for rendering into.\n\n\t/// \\param\ttarget\tThe rendertarget structure.\n\n\t/// \\return true if the target was successfully set\n\n\tbool setRenderTarget(std::shared_ptr<RenderTarget> target);\n\n\n\n\t/// Gets render target that is being used in this pass.\n\n\t/// \\return\tThe render target that should be used.\n", "file_path": "SurgSim/Graphics/RenderPass.h", "rank": 68, "score": 154945.9081719732 }, { "content": "/// A Shape that also inherits from Vertices is transformable and carries a member variable of the initial Vertices for\n\n/// transforming.\n\nclass VerticesShape : public Shape\n\n{\n\npublic:\n\n\tbool isTransformable() const override;\n\n\n\n\t/// Set the initial Vertices.\n\n\t/// \\param vertices The initial vertices.\n\n\tvoid setInitialVertices(const DataStructures::Vertices<DataStructures::EmptyData>& vertices);\n\n\n\n\t/// Set the initial Vertices via r-value.\n\n\t/// \\param vertices The initial vertices.\n\n\tvoid setInitialVertices(DataStructures::Vertices<DataStructures::EmptyData>&& vertices);\n\n\n\n\t/// Get the initial Vertices.\n\n\t/// \\return The initial Vertices.\n\n\tconst DataStructures::Vertices<DataStructures::EmptyData>& getInitialVertices() const;\n\n\n\nprotected:\n\n\t/// The initial vertex positions.\n\n\tDataStructures::Vertices<DataStructures::EmptyData> m_initialVertices;\n\n};\n\n\n\n}; // Math\n\n}; // SurgSim\n\n\n\n#endif // SURGSIM_MATH_VERTICESSHAPE_H\n", "file_path": "SurgSim/Math/VerticesShape.h", "rank": 69, "score": 154481.74219745013 }, { "content": "/// Propagates the Mlcp result to the representations.\n\n/// Can optionally discard (not push) MLCP results that do not meet the contact tolerance.\n\n/// The MlcpGaussSeidelSolver has a contact tolerance that can be set through the SolveMlcp Computation, and which\n\n/// is used to determine if the solver should stop before reaching the maximum iterations. Often the SolveMlcp has a\n\n/// \"tight\" (small) tolerance to get the most accurate contacts possible, but then the MLCP tends to iterate the\n\n/// maximum number of times. Then, here a looser (larger) tolerance can be set such that if the MLCP is failing to\n\n/// meet that tolerance (i.e., the solve failed), the results are discarded. Discarding the MLCP results will mean\n\n/// the constraints will not be satisfied and may drive the simulation further away from successful MLCP results.\n\nclass PushResults : public Computation\n\n{\n\npublic:\n\n\t/// Constructor\n\n\t/// \\param doCopyState Specify if the output state in Computation::Update() is a copy or not of the input state\n\n\texplicit PushResults(bool doCopyState = false);\n\n\n\n\tSURGSIM_CLASSNAME(SurgSim::Physics::PushResults);\n\n\n\n\t/// Destructor\n\n\tvirtual ~PushResults();\n\n\n\n\t/// Enable/disable discarding all MLCP results if any contact constraint has a violation greater than the tolerance.\n\n\t/// \\param filter true to enable filtering.\n\n\tvoid setDiscardBadResults(bool filter);\n\n\n\n\t/// \\return true if discarding MLCP results that have a contact violation greater than the tolerance.\n\n\tbool isDiscardBadResults() const;\n\n\n\n\t/// \\param tolerance The contact tolerance limit, only matters if discarding bad MLCP results.\n", "file_path": "SurgSim/Physics/PushResults.h", "rank": 70, "score": 154481.06855225208 }, { "content": "/// The PoseComponent holds a pose. It is used to group Representations that\n\n/// share a common pose, in a SceneElement for example.\n\nclass PoseComponent : public Component\n\n{\n\npublic:\n\n\t/// Constructor\n\n\t/// \\param name Name of the representation\n\n\texplicit PoseComponent(const std::string& name);\n\n\n\n\tSURGSIM_CLASSNAME(SurgSim::Framework::PoseComponent);\n\n\n\n\t/// Set the Pose of the PoseComponent\n\n\t/// \\param pose The pose in world coordinates\n\n\tvoid setPose(const SurgSim::Math::RigidTransform3d& pose);\n\n\n\n\t/// Get the pose of the PoseComponent\n\n\t/// \\return The pose in world coordinates\n\n\tconst SurgSim::Math::RigidTransform3d& getPose() const;\n\n\n\nprotected:\n\n\t/// Get the PoseComponent for this component\n\n\t/// A PoseComponent cannot have a PoseComponent, so this will\n", "file_path": "SurgSim/Framework/PoseComponent.h", "rank": 71, "score": 154410.00475906432 }, { "content": "struct ReplayPoseScaffold::DeviceData\n\n{\n\n\t/// Constructor\n\n\t/// \\param device Device to be managed by this scaffold\n\n\texplicit DeviceData(ReplayPoseDevice* device) :\n\n\t\tdeviceObject(device),\n\n\t\tm_timestamp(0),\n\n\t\tm_index(0),\n\n\t\tm_fileLoaded(false)\n\n\t{\n\n\t\tm_fileLoaded = loadFile(deviceObject->getFileName());\n\n\t\tm_timer.start();\n\n\t}\n\n\n\n\t/// Retrieve the pose for the given time stamp \"m_timestamp\"\n\n\t/// \\return The requested pose, Identity if none could be loaded\n\n\tMath::RigidTransform3d getPose()\n\n\t{\n\n\t\tif (m_motion.size() == 0)\n\n\t\t{\n", "file_path": "SurgSim/Devices/ReplayPoseDevice/ReplayPoseScaffold.cpp", "rank": 72, "score": 154045.20465198375 }, { "content": "/// OSG implementation of a graphics camera.\n\n///\n\n/// A Graphics::OsgCamera wraps a osg::Camera to provide camera functionality and a osg::Switch to allow enabling and\n\n/// disabling of the camera.\n\nclass OsgCamera : public OsgRepresentation, public Camera\n\n{\n\npublic:\n\n\t/// Constructor\n\n\t/// \\param\tname\tName of the camera\n\n\t/// The view matrix is initialized with eye at (0, 0, 0), center at (0, 0, -1), and up (0, 1, 0).\n\n\t/// The projection matrix is initialized to a perspective matrix with FOV Y of 45 deg, Aspect Ratio of 1.0,\n\n\t/// Z Near of 0.01, and Z Far of 10.0.\n\n\texplicit OsgCamera(const std::string& name);\n\n\n\n\tSURGSIM_CLASSNAME(SurgSim::Graphics::OsgCamera);\n\n\n\n\tbool setRenderGroup(std::shared_ptr<Group> group) override;\n\n\n\n\tbool setRenderGroups(const std::vector<std::shared_ptr<Group>>& groups) override;\n\n\n\n\tvoid setLocalActive(bool val) override;\n\n\n\n\tvirtual SurgSim::Math::Matrix44d getViewMatrix() const;\n\n\n", "file_path": "SurgSim/Graphics/OsgCamera.h", "rank": 73, "score": 153149.8782539071 }, { "content": "/// OSG implementation of a 1D Texture\n\n///\n\n/// Wraps an osg::Texture1d\n\nclass OsgTexture1d : public OsgTexture, public Texture1d\n\n{\n\npublic:\n\n\t/// Constructor\n\n\t/// \\post\tNo image is loaded in the texture.\n\n\tOsgTexture1d();\n\n\n\n\t/// Sets the size of the texture\n\n\t/// \\param\twidth\tWidth of the texture\n\n\t/// \\note\tUse this to setup a texture as a render target rather than loading from file.\n\n\tvirtual void setSize(int width);\n\n\n\n\t/// Gets the size of the texture\n\n\t/// \\return\twidth\tWidth of the texture\n\n\tvirtual void getSize(int* width) const;\n\n\n\n\t/// Returns the osg::Texture1D\n\n\tosg::ref_ptr<osg::Texture1D> getOsgTexture1d() const\n\n\t{\n\n\t\treturn static_cast<osg::Texture1D*>(getOsgTexture().get());\n", "file_path": "SurgSim/Graphics/OsgTexture1d.h", "rank": 74, "score": 153142.72432238085 }, { "content": "/// OpenScenegraph implementation for the Light interface\n\nclass OsgLight : public OsgRepresentation, public Light\n\n{\n\npublic:\n\n\n\n\t/// If we use the uniforms map, to check for all the uniforms that should be set in the stateset, then\n\n\t/// we can reduce the breakability of the unittest\n\n\tfriend class OsgLightTests;\n\n\n\n\t/// Constructor\n\n\texplicit OsgLight(const std::string& name);\n\n\tvirtual ~OsgLight();\n\n\n\n\tSURGSIM_CLASSNAME(SurgSim::Graphics::OsgLight);\n\n\n\n\tbool setGroup(std::shared_ptr<SurgSim::Graphics::Group> group) override;\n\n\n\n\tvoid setLightGroupReference(const std::string& name) override;\n\n\n\n\tstd::string getLightGroupReference() override;\n\n\n", "file_path": "SurgSim/Graphics/OsgLight.h", "rank": 75, "score": 153142.72432238085 }, { "content": "/// OSG implementation of a 2D Texture\n\n///\n\n/// Wraps an osg::Texture2d\n\nclass OsgTexture2d : public OsgTexture, public Texture2d\n\n{\n\npublic:\n\n\t/// Constructor\n\n\t/// \\post\tNo image is loaded in the texture.\n\n\tOsgTexture2d();\n\n\n\n\t/// Sets the size of the texture\n\n\t/// \\param\twidth\tWidth of the texture\n\n\t/// \\param\theight\tHeight of the texture\n\n\t/// \\note\tUse this to setup a texture as a render target rather than loading from file.\n\n\tvirtual void setSize(int width, int height);\n\n\n\n\t/// Gets the size of the texture\n\n\t/// \\param[out]\twidth\tWidth of the texture\n\n\t/// \\param[out]\theight\tHeight of the texture\n\n\tvirtual void getSize(int* width, int* height) const;\n\n\n\n\t/// Returns the osg::Texture2D\n\n\tosg::ref_ptr<osg::Texture2D> getOsgTexture2d() const\n", "file_path": "SurgSim/Graphics/OsgTexture2d.h", "rank": 76, "score": 153142.72432238085 }, { "content": "/// OSG implementation of a 3D Texture\n\n///\n\n/// Wraps an osg::Texture3d\n\nclass OsgTexture3d : public OsgTexture, public Texture3d\n\n{\n\npublic:\n\n\t/// Constructor\n\n\t/// \\post\tNo image is loaded in the texture.\n\n\tOsgTexture3d();\n\n\n\n\t/// Sets the size of the texture\n\n\t/// \\param\twidth\tWidth of the texture\n\n\t/// \\param\theight\tHeight of the texture\n\n\t/// \\param\tdepth\tDepth of the texture\n\n\t/// \\note\tUse this to setup a texture as a render target rather than loading from file.\n\n\tvirtual void setSize(int width, int height, int depth);\n\n\n\n\t/// Gets the size of the texture\n\n\t/// \\param[out]\twidth\tWidth of the texture\n\n\t/// \\param[out]\theight\tHeight of the texture\n\n\t/// \\param[out]\tdepth\tDepth of the texture\n\n\tvirtual void getSize(int* width, int* height, int* depth) const;\n\n\n", "file_path": "SurgSim/Graphics/OsgTexture3d.h", "rank": 77, "score": 153142.72432238085 }, { "content": "/// OculusView is a customization of SurgSim::Graphics::OsgView with projection matrices pulled from the Oculus device.\n\nclass OculusView : public SurgSim::Graphics::OsgView\n\n{\n\npublic:\n\n\t/// Constructor\n\n\t/// \\param\tname\tName of the view\n\n\texplicit OculusView(const std::string& name);\n\n\n\n\t/// Destructor\n\n\t~OculusView();\n\n\n\n\tSURGSIM_CLASSNAME(SurgSim::Devices::OculusView);\n\n\n\n\t/// Set the InputComponent this view connects to.\n\n\t/// Projection matrices of the Oculus device are passed via the DataGroup the InputComponent carries.\n\n\t/// \\param input The InputComponent\n\n\tvoid setInputComponent(std::shared_ptr<Framework::Component> input);\n\n\n\n\t/// \\return The InputComponnet this view connects\n\n\tstd::shared_ptr<Input::InputComponent> getInputComponent() const;\n\n\n", "file_path": "SurgSim/Devices/Oculus/OculusView.h", "rank": 78, "score": 152685.06196405677 }, { "content": "struct ParticlesCollisionRepresentationTest : public ::testing::Test\n\n{\n\n\tvoid SetUp()\n\n\t{\n\n\t\tm_runtime = std::make_shared<SurgSim::Framework::Runtime>();\n\n\t\tm_particleRepresentation = std::make_shared<MockParticleSystem>(\"ParticleRepresentation\");\n\n\t\tm_particleCollisionRepresentation =\n\n\t\t\tstd::make_shared<ParticlesCollisionRepresentation>(\"ParticlesCollisionRepresentation\");\n\n\t}\n\n\n\n\tstd::shared_ptr<SurgSim::Framework::Runtime> m_runtime;\n\n\tstd::shared_ptr<SurgSim::Particles::Representation> m_particleRepresentation;\n\n\tstd::shared_ptr<SurgSim::Particles::ParticlesCollisionRepresentation> m_particleCollisionRepresentation;\n\n};\n\n\n\nTEST_F(ParticlesCollisionRepresentationTest, InitTest)\n\n{\n\n\tEXPECT_NO_THROW(ParticlesCollisionRepresentation(\"TestParticlesCollisionRepresentation\"));\n\n}\n\n\n", "file_path": "SurgSim/Particles/UnitTests/ParticlesCollisionRepresentationTests.cpp", "rank": 79, "score": 152490.62728391343 }, { "content": "struct RigidCollisionRepresentationTest : public ::testing::Test\n\n{\n\n\tvoid SetUp()\n\n\t{\n\n\t\tm_sphereShape = std::make_shared<SurgSim::Math::SphereShape>(1.0);\n\n\t\tm_rigidRepresentation = std::make_shared<RigidRepresentation>(\"RigidRepresentation\");\n\n\t\tm_rigidRepresentation->setShape(m_sphereShape);\n\n\t}\n\n\n\n\tstd::shared_ptr<SurgSim::Math::SphereShape> m_sphereShape;\n\n\tstd::shared_ptr<SurgSim::Physics::RigidCollisionRepresentation> m_rigidCollisionRepresentation;\n\n\tstd::shared_ptr<SurgSim::Physics::RigidRepresentation> m_rigidRepresentation;\n\n};\n\n\n\nTEST_F(RigidCollisionRepresentationTest, InitTest)\n\n{\n\n\tEXPECT_NO_THROW(RigidCollisionRepresentation(\"TestRigidCollisionRepresentation\"));\n\n\tEXPECT_NO_THROW(m_rigidCollisionRepresentation =\n\n\t\tstd::make_shared<RigidCollisionRepresentation>(\"RigidCollisionRepresentation\")\n\n\t);\n", "file_path": "SurgSim/Physics/UnitTests/RigidCollisionRepresentationTest.cpp", "rank": 80, "score": 152490.62728391343 }, { "content": "struct DeformableCollisionRepresentationTest : public ::testing::Test\n\n{\n\n\tvoid SetUp()\n\n\t{\n\n\t\tm_runtime = std::make_shared<SurgSim::Framework::Runtime>(\"config.txt\");\n\n\t\tm_filename = std::string(\"Geometry/wound_deformable.ply\");\n\n\t\tm_meshShape = std::make_shared<SurgSim::Math::MeshShape>();\n\n\t\tm_meshShape->load(m_filename);\n\n\t\tm_deformableRepresentation = std::make_shared<MockDeformableRepresentation>(\"DeformableRepresentation\");\n\n\t\tm_deformableCollisionRepresentation =\n\n\t\t\tstd::make_shared<DeformableCollisionRepresentation>(\"DeformableCollisionRepresentation\");\n\n\t}\n\n\n\n\tstd::shared_ptr<SurgSim::Framework::Runtime> m_runtime;\n\n\tstd::string m_filename;\n\n\tstd::shared_ptr<SurgSim::Math::MeshShape> m_meshShape;\n\n\tstd::shared_ptr<SurgSim::Physics::DeformableRepresentation> m_deformableRepresentation;\n\n\tstd::shared_ptr<SurgSim::Physics::DeformableCollisionRepresentation> m_deformableCollisionRepresentation;\n\n};\n\n\n", "file_path": "SurgSim/Physics/UnitTests/DeformableCollisionRepresentationTest.cpp", "rank": 81, "score": 152490.62728391343 }, { "content": "struct VirtualToolCouplerTest : public ::testing::Test\n\n{\n\n\tvirtual void SetUp()\n\n\t{\n\n\t\trepresentationName = \"Rigid Representation\";\n\n\t\tinputDeviceName = \"Device\";\n\n\n\n\t\trigidBody = std::make_shared<RigidRepresentation>(representationName);\n\n\t\trigidBody->setDensity(700.0);\n\n\t\trigidBody->setAngularDamping(0.0);\n\n\t\trigidBody->setLinearDamping(0.0);\n\n\t\trigidBody->setShape(std::make_shared<SphereShape>(0.1));\n\n\n\n\t\tRigidState state;\n\n\t\tstate.setAngularVelocity(Vector3d::Zero());\n\n\t\tstate.setLinearVelocity(Vector3d::Zero());\n\n\t\tstate.setPose(RigidTransform3d::Identity());\n\n\t\trigidBody->setInitialState(state);\n\n\n\n\t\tinput = std::make_shared<InputComponent>(\"Input\");\n", "file_path": "SurgSim/Physics/UnitTests/VirtualToolCouplerTest.cpp", "rank": 82, "score": 152490.62728391343 }, { "content": "struct ContactConstraintGenerationTests: public ::testing::Test\n\n{\n\n\tvirtual void SetUp()\n\n\t{\n\n\t\trigid0 = std::make_shared<RigidRepresentation>(\"Physics Representation 0\");\n\n\t\trigid0->setShape(std::make_shared<SphereShape>(2.0));\n\n\t\tcollision0 = std::make_shared<RigidCollisionRepresentation>(\"Collision Representation 0\");\n\n\t\trigid0->setCollisionRepresentation(collision0);\n\n\t\trepresentations.push_back(rigid0);\n\n\n\n\t\trigid1 = std::make_shared<RigidRepresentation>(\"Physics Representation 1\");\n\n\t\trigid1->setShape(std::make_shared<DoubleSidedPlaneShape>());\n\n\t\tcollision1 = std::make_shared<RigidCollisionRepresentation>(\"Collision Representation 1\");\n\n\t\trigid1->setCollisionRepresentation(collision1);\n\n\t\trepresentations.push_back(rigid1);\n\n\n\n\t\tstate = std::make_shared<PhysicsManagerState>();\n\n\t\tstate->setRepresentations(representations);\n\n\n\n\t\tauto runtime = std::make_shared<SurgSim::Framework::Runtime>(\"config.txt\");\n", "file_path": "SurgSim/Physics/UnitTests/ContactConstraintGenerationTests.cpp", "rank": 83, "score": 152490.62728391343 }, { "content": "struct BoneData;\n", "file_path": "SurgSim/Graphics/OsgSkeletonRepresentation.h", "rank": 84, "score": 151461.4008658388 }, { "content": "struct Fem3DVSTruthCubeRenderTests : public RenderTests\n\n{\n\n\tvoid addComponent(std::shared_ptr<SurgSim::Framework::Component> component)\n\n\t{\n\n\t\tviewElement->addComponent(component);\n\n\t}\n\n\n\n\tvoid SetUp() override\n\n\t{\n\n\t\tRenderTests::SetUp();\n\n\n\n\t\t// Load truth cube data\n\n\t\ttruthCubeData = std::make_shared<TruthCubeData>();\n\n\t\tparseTruthCubeData(truthCubeData);\n\n\n\n\t\t// Compute the center point of the cube\n\n\t\tSurgSim::Math::Vector3d center = SurgSim::Math::Vector3d::Zero();\n\n\t\tfor (size_t nodeId = 0; nodeId < truthCubeData->cubeData0.size(); ++nodeId)\n\n\t\t{\n\n\t\t\tcenter += truthCubeData->cubeData0[nodeId];\n", "file_path": "SurgSim/Physics/RenderTests/Fem3DvsTruthCubeRenderTest.cpp", "rank": 85, "score": 151283.16110728183 }, { "content": "namespace SurgSim\n\n{\n\nnamespace Graphics\n\n{\n\n\n\n/// A (mathematical) vector is represented as (X,Y,Z) associated with an optional color (R,G,B,alpha) information\n\nstruct VectorFieldData\n\n{\n\n\t/// Direction (X,Y,Z) of the vector\n\n\tSurgSim::Math::Vector3d direction;\n\n\t/// Color (R,G,B,alpha) of the vector (Optional)\n\n\tSurgSim::DataStructures::OptionalValue<SurgSim::Math::Vector4d> color;\n\n\n\n\t/// Compare the vectors and return true if equal; Othwise, false.\n\n\t/// \\return True if vector1 and rhs have the same value; Otherwise, false.\n\n\tbool operator==(const VectorFieldData& rhs) const\n\n\t{\n\n\t\tif (color.hasValue() && rhs.color.hasValue())\n\n\t\t{\n\n\t\t\treturn direction == rhs.direction &&\n\n\t\t\t\t color.getValue() == rhs.color.getValue();\n\n\t\t}\n\n\t\telse\n\n\t\t{\n\n\t\t\treturn direction == rhs.direction;\n\n\t\t}\n\n\t}\n\n\n\n\t/// Compare the vectors and return true if not equal, false if equal.\n\n\t/// \\return True if vector1 and rhs have different values; Otherwise, false.\n\n\tbool operator!=(const VectorFieldData& rhs) const\n\n\t{\n\n\t\treturn ! (*this == rhs);\n\n\t}\n\n};\n\n\n\ntypedef SurgSim::DataStructures::Vertices<VectorFieldData> VectorField;\n\n\n", "file_path": "SurgSim/Graphics/VectorField.h", "rank": 86, "score": 150519.8723054056 }, { "content": "/// Specific class for rotation vector constraints.\n\n/// It handles the specificity of the rotation vector in the constraint calculation.\n\nclass RotationVectorConstraint: public Constraint\n\n{\n\npublic:\n\n\tRotationVectorConstraint(\n\n\t\tConstraintType constraintType,\n\n\t\tstd::shared_ptr<ConstraintData> data,\n\n\t\tstd::shared_ptr<Representation> representation0,\n\n\t\tconst SurgSim::DataStructures::Location& location0,\n\n\t\tstd::shared_ptr<Representation> representation1,\n\n\t\tconst SurgSim::DataStructures::Location& location1);\n\n\n\n\t/// Destructor\n\n\tvirtual ~RotationVectorConstraint();\n\n\n\nprotected:\n\n\t/// \\note The rotation vector violation being calculated based on a quaternion interpolation (slerp), and this\n\n\t/// type of interpolation being highly non-linear, the classical way of using the implementation one after the\n\n\t/// other one won't work.\n\n\t/// Therefore, this method temporarily uses the vector mlcpPhysicsProblem->b to retrieve both representation's\n\n\t/// rotation vectors, then calculate the proper slerp and set the violation back in mlcpPhysicsProblem->b\n", "file_path": "SurgSim/Physics/RotationVectorConstraint.h", "rank": 87, "score": 149333.81195868854 }, { "content": "namespace SurgSim\n\n{\n\n\n\nnamespace Graphics\n\n{\n\n\n\n/// Convert 2D vector of floats to OSG\n\ninline osg::Vec2f toOsg(const SurgSim::Math::Vector2f& vector)\n\n{\n\n\tosg::Vec2f osgVector;\n\n\tEigen::Map<SurgSim::Math::Vector2f>(osgVector.ptr()) = vector;\n\n\treturn osgVector;\n\n}\n\n/// Convert from OSG to 2D vector of floats\n\ninline SurgSim::Math::Vector2f fromOsg(const osg::Vec2f& vector)\n\n{\n\n\treturn SurgSim::Math::Vector2f(vector.ptr());\n\n}\n\n\n\n/// Convert 2D vector of doubles to OSG\n\ninline osg::Vec2d toOsg(const SurgSim::Math::Vector2d& vector)\n\n{\n\n\tosg::Vec2d osgVector;\n\n\tEigen::Map<SurgSim::Math::Vector2d>(osgVector.ptr()) = vector;\n\n\treturn osgVector;\n\n}\n\n/// Convert from OSG to 2D vector of doubles\n\ninline SurgSim::Math::Vector2d fromOsg(const osg::Vec2d& vector)\n\n{\n\n\treturn SurgSim::Math::Vector2d(vector.ptr());\n\n}\n\n\n\n/// Convert 3D vector of floats to OSG\n\ninline osg::Vec3f toOsg(const SurgSim::Math::Vector3f& vector)\n\n{\n\n\tosg::Vec3f osgVector;\n\n\tEigen::Map<SurgSim::Math::Vector3f>(osgVector.ptr()) = vector;\n\n\treturn osgVector;\n\n}\n\n/// Convert from OSG to 3D vector of floats\n\ninline SurgSim::Math::Vector3f fromOsg(const osg::Vec3f& vector)\n\n{\n\n\treturn SurgSim::Math::Vector3f(vector.ptr());\n\n}\n\n\n\n/// Convert 3D vector of doubles to OSG\n\ninline osg::Vec3d toOsg(SurgSim::Math::Vector3d vector)\n\n{\n\n\tosg::Vec3d osgVector;\n\n\tEigen::Map<SurgSim::Math::Vector3d>(osgVector.ptr()) = vector;\n\n\treturn osgVector;\n\n}\n\n/// Convert from OSG to 3D vector of doubles\n\ninline SurgSim::Math::Vector3d fromOsg(const osg::Vec3d& vector)\n\n{\n\n\treturn SurgSim::Math::Vector3d(vector.ptr());\n\n}\n\n\n\n\n\n/// Convert 4D vector of floats to OSG\n\ninline osg::Vec4f toOsg(const SurgSim::Math::Vector4f& vector)\n\n{\n\n\tosg::Vec4f osgVector;\n\n\tEigen::Map<SurgSim::Math::Vector4f>(osgVector.ptr()) = vector;\n\n\treturn osgVector;\n\n}\n\n/// Convert from OSG to 4D vector of floats\n\ninline SurgSim::Math::Vector4f fromOsg(const osg::Vec4f& vector)\n\n{\n\n\treturn SurgSim::Math::Vector4f(vector.ptr());\n\n}\n\n\n\n/// Convert 4D vector of doubles to OSG\n\ninline osg::Vec4d toOsg(const SurgSim::Math::Vector4d& vector)\n\n{\n\n\tosg::Vec4d osgVector;\n\n\tEigen::Map<SurgSim::Math::Vector4d>(osgVector.ptr()) = vector;\n\n\treturn osgVector;\n\n}\n\n/// Convert from OSG to 4D vector of doubles\n\ninline SurgSim::Math::Vector4d fromOsg(const osg::Vec4d& vector)\n\n{\n\n\treturn SurgSim::Math::Vector4d(vector.ptr());\n\n}\n\n\n\n}; // namespace Graphics\n\n\n", "file_path": "SurgSim/Graphics/OsgVectorConversions.h", "rank": 88, "score": 147873.7372887305 }, { "content": "/// An input device filter that record the input pose along with the relative time. All entries in the DataGroup are\n\n/// passed through. For convenience, it is also an OutputProducerInterface that does no filtering of the ouput data.\n\n/// Once a file of timestamped poses has been created, the ReplayPoseDevice can use that file to replay the poses.\n\nclass RecordPose : public DeviceFilter\n\n{\n\npublic:\n\n\t/// Constructor.\n\n\t/// \\param name\tName of this device filter.\n\n\texplicit RecordPose(const std::string& name);\n\n\n\n\t/// Desctructor\n\n\t~RecordPose();\n\n\n\n\t/// \\param fileName The filename to record the pose/time to (default is empty string)\n\n\tvoid setFileName(const std::string& fileName);\n\n\n\n\t/// \\return The filename where the pose/time are recorded (default is empty string)\n\n\tconst std::string& getFileName() const;\n\n\n\n\tvoid initializeInput(const std::string& device, const DataStructures::DataGroup& inputData) override;\n\n\n\n\tSURGSIM_CLASSNAME(SurgSim::Devices::RecordPose);\n\n\n", "file_path": "SurgSim/Devices/DeviceFilters/RecordPose.h", "rank": 89, "score": 147009.42480651394 }, { "content": "/// A device filter that transforms the input pose. It can scale the translation, and/or apply a constant transform.\n\n/// Any other data in the DataGroup is passed through. For an input/output device (e.g., a haptic device), the filter\n\n/// should be added as one of the device's input consumers and set as the device's output producer. For a purely input\n\n/// device, the filter can just be added as an input consumer. If it is used for both input and output, the input data\n\n/// is filtered using the offset(s) and scaling, and the output data is un-filtered so the device does not need to know\n\n/// about the filtering.\n\n/// For haptic devices, so that changing the translation scaling does not alter the relationship between displayed\n\n/// forces and collision penetrations, the output filter does not scale the nominal forces and torques, and it does\n\n/// scale the Jacobians. Thereby the displayed forces and torques are appropriate for the scene (not the device-space\n\n/// motions). In other words, a 1 m motion by the device's scene representation generates forces according to that 1 m\n\n/// motion, instead of the original device motion before scaling. This means the device displays forces and torques\n\n/// that are \"true\" to the scene, with the consequence that increasing the translation scaling can negatively impact the\n\n/// haptic stability. As the scaling increases, the same motion would cause larger forces, until at great enough\n\n/// scaling the system becomes unstable (either when colliding with another scene element, or just due to over-damping).\n\n/// Consider chaining this device filter with a force scaling device filter to improve system stability.\n\n/// \\sa\tSurgSim::Input::CommonDevice\n\n/// \\sa\tSurgSim::Input::InputConsumerInterface\n\n/// \\sa\tSurgSim::Input::OutputProducerInterface\n\nclass PoseTransform : public DeviceFilter\n\n{\n\npublic:\n\n\t/// Constructor.\n\n\t/// \\param name\tName of this device filter.\n\n\texplicit PoseTransform(const std::string& name);\n\n\n\n\tSURGSIM_CLASSNAME(SurgSim::Devices::PoseTransform);\n\n\n\n\t/// \\return Get the translation scale factor.\n\n\tdouble getTranslationScale() const;\n\n\n\n\t/// Set the translation scale factor so that each direction has the same scale.\n\n\t/// \\param translationScale The scalar scaling factor.\n\n\t/// \\warning This setter is thread-safe, but after calling this function the output filter will use the new\n\n\t///\t\ttransform even if the following output data is based off input data that used the old transform.\n\n\tvoid setTranslationScale(double translationScale);\n\n\n\n\t/// \\return The current transform.\n\n\tconst Math::RigidTransform3d& getTransform() const;\n", "file_path": "SurgSim/Devices/DeviceFilters/PoseTransform.h", "rank": 90, "score": 147003.10786851883 }, { "content": "/// A device filter that integrates the pose, turning a relative device into an absolute one.\n\n/// Also provides the instantaneous linear and angular velocities.\n\n/// \\sa\tSurgSim::Input::CommonDevice\n\n/// \\sa\tSurgSim::Input::InputConsumerInterface\n\n/// \\sa\tSurgSim::Input::OutputProducerInterface\n\nclass PoseIntegrator : public DeviceFilter\n\n{\n\npublic:\n\n\t/// The type used for poses.\n\n\ttypedef Math::RigidTransform3d PoseType;\n\n\n\n\t/// Constructor.\n\n\t/// \\param name\tName of this device filter.\n\n\texplicit PoseIntegrator(const std::string& name);\n\n\n\n\tSURGSIM_CLASSNAME(SurgSim::Devices::PoseIntegrator);\n\n\n\n\t/// Integrates the pose.\n\n\t/// \\param pose\tThe latest differential pose.\n\n\t/// \\return\tThe integrated pose.\n\n\tconst PoseType& integrate(const PoseType& pose);\n\n\n\n\tvoid initializeInput(const std::string& device, const DataStructures::DataGroup& inputData) override;\n\n\n\n\t/// Notifies the consumer that the application input coming from the device has been updated.\n", "file_path": "SurgSim/Devices/DeviceFilters/PoseIntegrator.h", "rank": 91, "score": 147001.73918654872 }, { "content": "/// OSG implementation of a graphics capsule representation.\n\nclass OsgCapsuleRepresentation : public OsgRepresentation, public CapsuleRepresentation\n\n{\n\npublic:\n\n\t/// Constructor\n\n\t/// \\param\tname\tName of the representation\n\n\texplicit OsgCapsuleRepresentation(const std::string& name);\n\n\n\n\tSURGSIM_CLASSNAME(SurgSim::Graphics::OsgCapsuleRepresentation);\n\n\n\n\t/// Sets the radius of the capsule\n\n\t/// \\param radius Radius of the capsule\n\n\tvoid setRadius(double radius) override;\n\n\t/// Returns the radius of the capsule\n\n\t/// \\return Radius along X-axis and Z-axis of the capsule\n\n\tdouble getRadius() const override;\n\n\n\n\t/// Sets the height of the capsule\n\n\t/// \\param height Height of the capsule\n\n\tvoid setHeight(double height) override;\n\n\t/// Returns the height of the capsule\n", "file_path": "SurgSim/Graphics/OsgCapsuleRepresentation.h", "rank": 92, "score": 146706.0374576741 }, { "content": "/// OSG implementation of a graphics Cylinder representation.\n\nclass OsgCylinderRepresentation : public OsgRepresentation, public CylinderRepresentation\n\n{\n\npublic:\n\n\t/// Constructor\n\n\t/// \\param\tname\tName of the representation\n\n\texplicit OsgCylinderRepresentation(const std::string& name);\n\n\n\n\tSURGSIM_CLASSNAME(SurgSim::Graphics::OsgCylinderRepresentation);\n\n\n\n\t/// Sets the radius of the cylinder\n\n\t/// \\param\tradius\tRadius along X-axis and Z-axis of the cylinder\n\n\tvoid setRadius(double radius) override;\n\n\t/// Returns the radius of the cylinder\n\n\t/// \\return\tRadius along X-axis and Z-axis of cylinder\n\n\tdouble getRadius() const override;\n\n\n\n\t/// Sets the height of the cylinder\n\n\t/// \\param\theight\tHeight along Y-axis of the cylinder\n\n\tvoid setHeight(double height) override;\n\n\t/// Returns the height of the cylinder\n", "file_path": "SurgSim/Graphics/OsgCylinderRepresentation.h", "rank": 93, "score": 146706.0374576741 }, { "content": "/// OSG implementation of a graphics box representation.\n\nclass OsgBoxRepresentation : public OsgRepresentation, public BoxRepresentation\n\n{\n\npublic:\n\n\t/// Constructor\n\n\t/// \\param\tname\tName of the representation\n\n\texplicit OsgBoxRepresentation(const std::string& name);\n\n\n\n\tSURGSIM_CLASSNAME(SurgSim::Graphics::OsgBoxRepresentation);\n\n\n\n\t/// Sets the size along X-axis of the box\n\n\t/// \\param sizeX Size along X-axis of the box\n\n\tvoid setSizeX(double sizeX) override;\n\n\n\n\t/// Returns the size along X-axis of the box\n\n\t/// \\return Size along X-axis of the box\n\n\tdouble getSizeX() const override;\n\n\n\n\t/// Sets the size along Y-axis of the box\n\n\t/// \\param sizeY Size along Y-axis of the box\n\n\tvoid setSizeY(double sizeY) override;\n", "file_path": "SurgSim/Graphics/OsgBoxRepresentation.h", "rank": 94, "score": 146706.0374576741 }, { "content": "/// OSG implementation of a graphics plane representation.\n\nclass OsgPlaneRepresentation : public OsgRepresentation, public PlaneRepresentation\n\n{\n\npublic:\n\n\t/// Constructor\n\n\t/// \\param\tname\tName of the representation\n\n\texplicit OsgPlaneRepresentation(const std::string& name);\n\n\n\n\tSURGSIM_CLASSNAME(SurgSim::Graphics::OsgPlaneRepresentation);\n\n\n\nprivate:\n\n\n\n\t/// Shared plane, so that the geometry can be instanced rather than having multiple copies.\n\n\tstd::shared_ptr<OsgPlane> m_sharedPlane;\n\n\n\n\t/// Returns the shared plane\n\n\tstatic std::shared_ptr<OsgPlane> getSharedPlane();\n\n};\n\n\n\n}; // namespace Graphics\n\n\n\n}; // namespace SurgSim\n\n\n\n#if defined(_MSC_VER)\n\n#pragma warning(pop)\n\n#endif\n\n\n\n#endif // SURGSIM_GRAPHICS_OSGPLANEREPRESENTATION_H\n", "file_path": "SurgSim/Graphics/OsgPlaneRepresentation.h", "rank": 95, "score": 146706.0374576741 }, { "content": "/// OSG implementation of a graphics sphere representation.\n\nclass OsgSphereRepresentation : public OsgRepresentation, public SphereRepresentation\n\n{\n\npublic:\n\n\t/// Constructor\n\n\t/// \\param\tname\tName of the representation\n\n\texplicit OsgSphereRepresentation(const std::string& name);\n\n\n\n\tSURGSIM_CLASSNAME(SurgSim::Graphics::OsgSphereRepresentation);\n\n\n\n\t/// Sets the radius of the sphere\n\n\t/// \\param\tradius\tRadius of the sphere\n\n\tvirtual void setRadius(double radius);\n\n\n\n\t/// Returns the radius of the sphere\n\n\t/// \\return\tRadius of the sphere\n\n\tvirtual double getRadius() const;\n\n\n\nprivate:\n\n\t/// Shared unit sphere, so that the geometry can be instanced rather than having multiple copies.\n\n\tstd::shared_ptr<OsgUnitSphere> m_sharedUnitSphere;\n", "file_path": "SurgSim/Graphics/OsgSphereRepresentation.h", "rank": 96, "score": 146706.0374576741 }, { "content": "/// Implements the CurveRepresentation for OpenSceneGraph, it uses Catmull Rom interpolation, to draw the line\n\n/// as a GL_LINESTRIP. use the material_curve.vert shader for rendering. This class will also deposit the information\n\n/// of the segment in the normal information for the vertex.\n\nclass OsgCurveRepresentation : public OsgRepresentation, public CurveRepresentation\n\n{\n\npublic:\n\n\t/// Constructor\n\n\t/// \\param name Name of the representation\n\n\texplicit OsgCurveRepresentation(const std::string& name);\n\n\n\n\t~OsgCurveRepresentation();\n\n\n\n\tSURGSIM_CLASSNAME(SurgSim::Graphics::OsgCurveRepresentation);\n\n\n\n\tbool doInitialize() override;\n\n\n\n\tbool doWakeUp() override;\n\n\n\n\tvoid doUpdate(double dt) override;\n\n\n\n\tvoid setSubdivisions(size_t num) override;\n\n\n\n\tsize_t getSubdivisions() const override;\n", "file_path": "SurgSim/Graphics/OsgCurveRepresentation.h", "rank": 97, "score": 146706.0012451041 }, { "content": "/// Osg axes representation implementation for the AxesRepresentation interface in graphics.\n\nclass OsgAxesRepresentation : public OsgRepresentation, public AxesRepresentation\n\n{\n\npublic:\n\n\n\n\t/// Constructor\n\n\texplicit OsgAxesRepresentation(const std::string& name);\n\n\t~OsgAxesRepresentation();\n\n\n\n\tSURGSIM_CLASSNAME(SurgSim::Graphics::OsgAxesRepresentation);\n\n\n\n\t/// Sets the size of the shown axes.\n\n\t/// \\param\tval\tThe value.\n\n\tvoid setSize(double val) override;\n\n\n\n\t/// Gets the current size.\n\n\t/// \\return\tThe size.\n\n\tdouble getSize() override;\n\n\n\nprivate:\n\n\n", "file_path": "SurgSim/Graphics/OsgAxesRepresentation.h", "rank": 98, "score": 146705.8435013718 }, { "content": "/// Osg implementation of the TextRepresentation, to be used with OsgFont assets\n\nclass OsgTextRepresentation : public OsgRepresentation, public TextRepresentation\n\n{\n\npublic:\n\n\t/// Constructor\n\n\t/// \\param name Name of this OsgInfo\n\n\texplicit OsgTextRepresentation(const std::string& name);\n\n\n\n\t/// Destructor\n\n\t~OsgTextRepresentation();\n\n\n\n\tfriend class OsgTextRepresentationTests_MaximumWidth_Test;\n\n\n\n\tSURGSIM_CLASSNAME(SurgSim::Graphics::OsgTextRepresentation);\n\n\n\n\tvoid setLocation(double x, double y) override;\n\n\tvoid getLocation(double* x, double* y) const override;\n\n\n\n\tvoid setMaximumWidth(double width) override;\n\n\tdouble getMaximumWidth() override;\n\n\n", "file_path": "SurgSim/Graphics/OsgTextRepresentation.h", "rank": 99, "score": 146705.7108252126 } ]
C++
Utilities/itkSplitAlternatingTimeSeriesImageFilter.hxx
KevinScholtes/ANTsX
5462269c0c32e5d65560bae4014c5a05cb02588d
#ifndef __itkSplitAlternatingTimeSeriesImageFilter_hxx #define __itkSplitAlternatingTimeSeriesImageFilter_hxx #include "itkSplitAlternatingTimeSeriesImageFilter.h" #include "itkProgressReporter.h" #include "itkImageRegionIterator.h" #include "itkImageRegionConstIterator.h" namespace itk { template< typename TInputImage, typename TOutputImage > SplitAlternatingTimeSeriesImageFilter< TInputImage, TOutputImage > ::SplitAlternatingTimeSeriesImageFilter() { this->SetNumberOfRequiredOutputs(2); this->SetNthOutput( 0, this->MakeOutput(0) ); this->SetNthOutput( 1, this->MakeOutput(1) ); } template< typename TInputImage, typename TOutputImage > void SplitAlternatingTimeSeriesImageFilter< TInputImage, TOutputImage > ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); } template< typename TInputImage, typename TOutputImage > void SplitAlternatingTimeSeriesImageFilter< TInputImage, TOutputImage > ::GenerateOutputInformation() { typename Superclass::InputImageConstPointer inputPtr = this->GetInput(); typename Superclass::OutputImagePointer outputPtr0 = this->GetOutput(0); typename Superclass::OutputImagePointer outputPtr1 = this->GetOutput(1); if ( !outputPtr0 || !outputPtr1 || !inputPtr ) { return; } OutputImageRegionType outputLargestPossibleRegion; this->CallCopyInputRegionToOutputRegion( outputLargestPossibleRegion, inputPtr->GetLargestPossibleRegion() ); unsigned int halfTime = inputPtr->GetLargestPossibleRegion().GetSize()[InputImageDimension-1] / 2; outputLargestPossibleRegion.SetSize( InputImageDimension-1, halfTime ); outputPtr0->SetLargestPossibleRegion(outputLargestPossibleRegion); outputPtr1->SetLargestPossibleRegion(outputLargestPossibleRegion); outputPtr0->SetSpacing( inputPtr->GetSpacing() ); outputPtr1->SetSpacing( inputPtr->GetSpacing() ); outputPtr0->SetDirection( inputPtr->GetDirection() ); outputPtr1->SetDirection( inputPtr->GetDirection() ); typename InputImageType::PointType origin = inputPtr->GetOrigin(); outputPtr0->SetOrigin( origin ); origin[InputImageDimension-1] += inputPtr->GetSpacing()[InputImageDimension-1]; outputPtr1->SetOrigin( origin ); const unsigned int numComponents = inputPtr->GetNumberOfComponentsPerPixel(); if ( numComponents != outputPtr0->GetNumberOfComponentsPerPixel() ) { outputPtr0->SetNumberOfComponentsPerPixel( numComponents ); } if ( numComponents != outputPtr1->GetNumberOfComponentsPerPixel() ) { outputPtr1->SetNumberOfComponentsPerPixel( numComponents ); } } template< typename TInputImage, typename TOutputImage > void SplitAlternatingTimeSeriesImageFilter< TInputImage, TOutputImage > ::ThreadedGenerateData(const OutputImageRegionType & outputRegionForThread, ThreadIdType threadId) { itkDebugMacro(<< "Actually executing"); ProgressReporter progress( this, threadId, outputRegionForThread.GetNumberOfPixels() ); OutputImageRegionType outputRegion = outputRegionForThread; ImageRegionIterator< OutputImageType > outIt0( this->GetOutput(0), outputRegion); ImageRegionIterator< OutputImageType > outIt1( this->GetOutput(1), outputRegion); while ( !outIt0.IsAtEnd() ) { typename InputImageType::IndexType idx = outIt0.GetIndex(); idx[InputImageDimension-1] *= 2; outIt0.Set( this->GetInput()->GetPixel( idx ) ); idx[InputImageDimension-1] += 1; outIt1.Set( this->GetInput()->GetPixel( idx ) ); ++outIt0; ++outIt1; } } } #endif
#ifndef __itkSplitAlternatingTimeSeriesImageFilter_hxx #define __itkSplitAlternatingTimeSeriesImageFilter_hxx #include "itkSplitAlternatingTimeSeriesImageFilter.h" #include "itkProgressReporter.h" #include "itkImageRegionIterator.h" #include "itkImageRegionConstIterator.h" namespace itk { template< typename TInputImage, typename TOutputImage > SplitAlternatingTimeSeriesImageFilter< TInputImage, TOutputImage > ::SplitAlternatingTimeSeriesImageFilter() { this->SetNumberOfRequiredOutputs(2); this->SetNthOutput( 0, this->MakeOutput(0) ); this->SetNthOutput( 1, this->MakeOutput(1) ); } template< typename TInputImage, typename TOutputImage > void SplitAlternatingTimeSeriesImageFilter< TInputImage, TOutputImage > ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); } template< typename TInputImage, typename TOutputImage > void SplitAlternatingTimeSeriesImageFilter< TInputImage, TOutputImage > ::GenerateOutputInformation() { typename Superclass::InputImageConstPointer inputPtr = this->GetInput(); typename Superclass::OutputImagePointer outputPtr0 = this->GetOutput(0); typename Superclass::OutputImagePointer outputPtr1 = this->GetOutput(1); if ( !outputPtr0 || !outputPtr1 || !inputPtr ) { return; } OutputImageRegionType outputLargestPossibleRegion; this->CallCopyInputRegionToOutputRegion( outputLargestPossibleRegion, inputPtr->GetLargestPossibleRegion() ); unsigned int halfTime = inputPtr->GetLargestPossibleRegion().GetSize()[InputImageDimension-1] / 2; outputLargestPossibleRegion.SetSize( InputImageDimension-1, halfTime ); outputPtr0->SetLargestPossibleRegion(outputLargestPossibleRegion); outputPtr1->SetLargestPossibleRegion(outputLargestPossibleRegion); outputPtr0->SetSpacing( inputPtr->GetSpacing() ); outputPtr1->SetSpacing( inputPtr->GetSpacing() ); outputPtr0->SetDirection( inputPtr->GetDirection() ); outputPtr1->SetDirection( inputPtr->GetDirection() ); typename InputImageType::PointType origin = inputPtr->GetOrigin(); outputPtr0->SetOrigin( origin ); origin[InputImageDimension-1] += inputPtr->GetSpacing()[InputImageDimension-1]; outputPtr1->SetOrigin( origin ); const unsigned int numComponents = inputPtr->GetNumberOfComponentsPerPixel();
if ( numComponents != outputPtr1->GetNumberOfComponentsPerPixel() ) { outputPtr1->SetNumberOfComponentsPerPixel( numComponents ); } } template< typename TInputImage, typename TOutputImage > void SplitAlternatingTimeSeriesImageFilter< TInputImage, TOutputImage > ::ThreadedGenerateData(const OutputImageRegionType & outputRegionForThread, ThreadIdType threadId) { itkDebugMacro(<< "Actually executing"); ProgressReporter progress( this, threadId, outputRegionForThread.GetNumberOfPixels() ); OutputImageRegionType outputRegion = outputRegionForThread; ImageRegionIterator< OutputImageType > outIt0( this->GetOutput(0), outputRegion); ImageRegionIterator< OutputImageType > outIt1( this->GetOutput(1), outputRegion); while ( !outIt0.IsAtEnd() ) { typename InputImageType::IndexType idx = outIt0.GetIndex(); idx[InputImageDimension-1] *= 2; outIt0.Set( this->GetInput()->GetPixel( idx ) ); idx[InputImageDimension-1] += 1; outIt1.Set( this->GetInput()->GetPixel( idx ) ); ++outIt0; ++outIt1; } } } #endif
if ( numComponents != outputPtr0->GetNumberOfComponentsPerPixel() ) { outputPtr0->SetNumberOfComponentsPerPixel( numComponents ); }
if_condition
[ { "content": "class ITK_TEMPLATE_EXPORT SimulatedDisplacementFieldSource:\n\n public ImageSource<TOutputImage>\n\n{\n\npublic:\n\n ITK_DISALLOW_COPY_AND_ASSIGN( SimulatedDisplacementFieldSource );\n\n\n\n /** Standard class type aliases. */\n\n using Self = SimulatedDisplacementFieldSource;\n\n using Superclass = ImageSource<TOutputImage>;\n\n using Pointer = SmartPointer<Self>;\n\n using ConstPointer = SmartPointer<const Self>;\n\n\n\n using OutputImageType = TOutputImage;\n\n using OutputImagePointer = typename OutputImageType::Pointer;\n\n\n\n /** Method for creation through the object factory. */\n\n itkNewMacro( Self );\n\n\n\n /** Run-time type information (and related methods). */\n\n itkTypeMacro( SimulatedDisplacementFieldSource, ImageSource );\n", "file_path": "Utilities/itkSimulatedDisplacementFieldSource.h", "rank": 0, "score": 82973.37958700932 }, { "content": "namespace ants\n\n{\n\nextern int SetOrigin( std::vector<std::string>, // equivalent to argv of command line parameters to main()\n\n std::ostream* out_stream // [optional] output stream to write\n\n );\n", "file_path": "Examples/include/SetOrigin.h", "rank": 1, "score": 81908.13317098703 }, { "content": "namespace ants\n\n{\n\nextern int antsAlignOrigin( std::vector<std::string>, // equivalent to argv of command line parameters to main()\n\n std::ostream* out_stream // [optional] output stream to write\n\n );\n", "file_path": "Examples/include/antsAlignOrigin.h", "rank": 2, "score": 79816.52123039108 }, { "content": "class ITK_TEMPLATE_EXPORT SimulatedExponentialDisplacementFieldSource:\n\n public SimulatedDisplacementFieldSource<TOutputImage>\n\n{\n\npublic:\n\n ITK_DISALLOW_COPY_AND_ASSIGN( SimulatedExponentialDisplacementFieldSource );\n\n\n\n /** Standard class type aliases. */\n\n using Self = SimulatedExponentialDisplacementFieldSource;\n\n using Superclass = SimulatedDisplacementFieldSource<TOutputImage>;\n\n using Pointer = SmartPointer<Self>;\n\n using ConstPointer = SmartPointer<const Self>;\n\n\n\n using OutputImageType = TOutputImage;\n\n using OutputImagePointer = typename OutputImageType::Pointer;\n\n\n\n /** Method for creation through the object factory. */\n\n itkNewMacro( Self );\n\n\n\n /** Run-time type information (and related methods). */\n\n itkTypeMacro( SimulatedExponentialDisplacementFieldSource, SimulatedDisplacementFieldSource );\n", "file_path": "Utilities/itkSimulatedExponentialDisplacementFieldSource.h", "rank": 3, "score": 79806.39164844561 }, { "content": "class ITK_TEMPLATE_EXPORT SimulatedBSplineDisplacementFieldSource:\n\n public SimulatedDisplacementFieldSource<TOutputImage>\n\n{\n\npublic:\n\n ITK_DISALLOW_COPY_AND_ASSIGN( SimulatedBSplineDisplacementFieldSource );\n\n\n\n /** Standard class type aliases. */\n\n using Self = SimulatedBSplineDisplacementFieldSource;\n\n using Superclass = SimulatedDisplacementFieldSource<TOutputImage>;\n\n using Pointer = SmartPointer<Self>;\n\n using ConstPointer = SmartPointer<const Self>;\n\n\n\n using OutputImageType = TOutputImage;\n\n using OutputImagePointer = typename OutputImageType::Pointer;\n\n\n\n /** Method for creation through the object factory. */\n\n itkNewMacro( Self );\n\n\n\n /** Run-time type information (and related methods). */\n\n itkTypeMacro( SimulatedBSplineDisplacementFieldSource, SimulatedDisplacementFieldSource );\n", "file_path": "Utilities/itkSimulatedBSplineDisplacementFieldSource.h", "rank": 4, "score": 76880.68025585258 }, { "content": "namespace itk\n\n{\n\nnamespace ants\n\n{\n\ntemplate <typename T, unsigned VImageDimension>\n\ntypename itk::Transform<T, VImageDimension, VImageDimension>::Pointer\n\nReadTransform(const std::string & filename,\n\n const bool useStaticCastForR = false) // This parameter changes to true by the programs that use R, so this code\n\n // returns a different output for them.\n\n{\n\n // We must explicitly check for file existance because failed reading is an acceptable\n\n // state for non-displacment feilds.\n\n if( !itksys::SystemTools::FileExists( filename.c_str() ) )\n\n {\n\n std::cerr << \"Transform file does not exist: \" << filename << std::endl;\n\n return nullptr;\n\n }\n\n\n\n bool hasTransformBeenRead = false;\n\n\n\n typedef typename itk::DisplacementFieldTransform<T, VImageDimension> DisplacementFieldTransformType;\n\n typedef typename DisplacementFieldTransformType::DisplacementFieldType DisplacementFieldType;\n\n typedef itk::ImageFileReader<DisplacementFieldType> DisplacementFieldReaderType;\n\n \n\n typename DisplacementFieldReaderType::Pointer fieldReader = DisplacementFieldReaderType::New();\n\n typedef typename itk::CompositeTransform<T, VImageDimension> CompositeTransformType;\n\n\n\n // There are known transform type extentions that should not be considered as imaging files\n\n // That would be used as deformatino feilds\n\n // If file is an hdf5 file, assume it is a transform instead of an image.\n\n bool recognizedExtension = false;\n\n recognizedExtension |= ( itksys::SystemTools::GetFilenameLastExtension(filename) == \".h5\" );\n\n recognizedExtension |= ( itksys::SystemTools::GetFilenameLastExtension(filename) == \".hdf5\" );\n\n recognizedExtension |= ( itksys::SystemTools::GetFilenameLastExtension(filename) == \".hdf4\" );\n\n recognizedExtension |= ( itksys::SystemTools::GetFilenameLastExtension(filename) == \".mat\" );\n\n recognizedExtension |= ( itksys::SystemTools::GetFilenameLastExtension(filename) == \".txt\" );\n\n recognizedExtension |= ( itksys::SystemTools::GetFilenameLastExtension(filename) == \".xfm\" );\n\n\n\n if( !recognizedExtension )\n\n {\n\n try\n\n {\n\n fieldReader->SetFileName( filename.c_str() );\n\n fieldReader->Update();\n\n hasTransformBeenRead = true;\n\n }\n\n catch( ... )\n\n {\n\n hasTransformBeenRead = false;\n\n }\n\n }\n\n\n\n typedef typename itk::Transform<T, VImageDimension, VImageDimension> TransformType;\n\n typename TransformType::Pointer transform;\n\n if( hasTransformBeenRead )\n\n {\n\n typename DisplacementFieldTransformType::Pointer displacementFieldTransform =\n\n DisplacementFieldTransformType::New();\n\n displacementFieldTransform->SetDisplacementField( fieldReader->GetOutput() );\n\n transform = dynamic_cast<TransformType *>( displacementFieldTransform.GetPointer() );\n\n }\n\n else\n\n {\n\n typename itk::TransformFileReaderTemplate<T>::Pointer transformReader\n\n = itk::TransformFileReaderTemplate<T>::New();\n\n\n\n transformReader->SetFileName( filename.c_str() );\n\n try\n\n {\n\n transformReader->Update();\n\n }\n\n catch( const itk::ExceptionObject & e )\n\n {\n\n std::cerr << \"Transform reader for \"\n\n << filename << \" caught an ITK exception:\\n\";\n\n e.Print( std::cerr );\n\n return transform;\n\n }\n\n catch( const std::exception & e )\n\n {\n\n std::cerr << \"Transform reader for \"\n\n << filename << \" caught an exception:\\n\";\n\n std::cerr << e.what() << std::endl;\n\n return transform;\n\n }\n\n catch( ... )\n\n {\n\n std::cerr << \"Transform reader for \"\n\n << filename << \" caught an unknown exception!!!\\n\";\n\n return transform;\n\n }\n\n\n\n const typename itk::TransformFileReaderTemplate<T>::TransformListType * const listOfTransforms =\n\n transformReader->GetTransformList();\n\n \n\n if(listOfTransforms->size()>1)\n\n {\n\n typename CompositeTransformType::Pointer comp_transform=CompositeTransformType::New();\n\n for(typename itk::TransformFileReaderTemplate<T>::TransformListType::const_iterator i=listOfTransforms->begin();\n\n i!=listOfTransforms->end();\n\n ++i)\n\n {\n\n comp_transform->AddTransform( dynamic_cast<TransformType *>(i->GetPointer()) );\n\n }\n\n transform = dynamic_cast<TransformType *>(comp_transform.GetPointer());\n\n } else {\n\n \n\n transform = dynamic_cast<TransformType *>( listOfTransforms->front().GetPointer() );\n\n }\n\n\n\n /** below is a bad thing but it's the only temporary fix i could find for ANTsR on unix --- B.A. */\n\n if ( transform.IsNull() && ( useStaticCastForR == true ) )\n\n {\n\n transform = static_cast<TransformType *>( listOfTransforms->front().GetPointer() );\n\n }\n\n }\n\n return transform;\n\n}\n\n\n\ntemplate <typename T, unsigned int VImageDimension>\n\nint\n\nWriteTransform(typename itk::Transform<T, VImageDimension, VImageDimension>::Pointer & xfrm,\n\n const std::string & filename)\n\n{\n\n typedef typename itk::Transform<T, VImageDimension, VImageDimension> GenericTransformType;\n\n typedef typename itk::DisplacementFieldTransform<T, VImageDimension> DisplacementFieldTransformType;\n\n typedef typename DisplacementFieldTransformType::DisplacementFieldType DisplacementFieldType;\n\n typedef typename itk::ImageFileWriter<DisplacementFieldType> DisplacementFieldWriter;\n\n typedef itk::TransformFileWriterTemplate<T> TransformWriterType;\n\n\n\n DisplacementFieldTransformType *dispXfrm =\n\n dynamic_cast<DisplacementFieldTransformType *>(xfrm.GetPointer() );\n\n\n\n // if it's a displacement field transform or output file indicates it should be a transform\n\n try\n\n {\n\n if( dispXfrm != nullptr \n\n && filename.find(\".mat\") == std::string::npos\n\n && filename.find(\".txt\") == std::string::npos\n\n )\n\n {\n\n typename DisplacementFieldType::Pointer dispField = dispXfrm->GetModifiableDisplacementField();\n\n if( filename.find(\".xfm\" ) == std::string::npos\n\n && filename.find(\".h5\" ) == std::string::npos\n\n && filename.find(\".hdf5\") == std::string::npos\n\n && filename.find(\".hdf4\") == std::string::npos\n\n )\n\n {\n\n typename DisplacementFieldWriter::Pointer writer = DisplacementFieldWriter::New();\n\n writer->SetInput(dispField);\n\n writer->SetFileName(filename.c_str() );\n\n writer->Update();\n\n }\n\n else // creating a DisplacementFieldTransformType object to make everybody happy\n\n {\n\n typename DisplacementFieldTransformType::Pointer tmp_xfrm=DisplacementFieldTransformType::New();\n\n tmp_xfrm->SetDisplacementField(dispField);\n\n typename TransformWriterType::Pointer transformWriter = TransformWriterType::New();\n\n transformWriter->SetInput(tmp_xfrm);\n\n transformWriter->SetFileName(filename.c_str() );\n\n#if ITK_VERSION_MAJOR >= 5\n\n transformWriter->SetUseCompression(true);\n\n#endif\n\n transformWriter->Update();\n\n }\n\n }\n\n else\n\n // regular transform, hope that everything works as expected!\n\n {\n\n typedef itk::CompositeTransform<T, VImageDimension> CompositeTransformType;\n\n typedef typename CompositeTransformType::Pointer CompositeTransformPointer;\n\n typename TransformWriterType::Pointer transformWriter = TransformWriterType::New();\n\n \n\n CompositeTransformType *comp_xfm =\n\n dynamic_cast<CompositeTransformType *>(xfrm.GetPointer() ); \n\n if( comp_xfm != nullptr )\n\n { //this is a composite transform, make sure it doesn't contain wiered stuff\n\n CompositeTransformPointer tmp_comp_xfm=CompositeTransformType::New();\n\n \n\n size_t numTransforms = comp_xfm->GetNumberOfTransforms();\n\n for( size_t i = 0; i < numTransforms; i++ )\n\n {\n\n GenericTransformType *_xfm=comp_xfm->GetNthTransform( i );\n\n DisplacementFieldTransformType *_dispXfrm =\n\n dynamic_cast<DisplacementFieldTransformType *>(_xfm );\n\n \n\n if ( _dispXfrm != nullptr )\n\n { //assume that we have to make it DisplacementFieldTransform \n\n typename DisplacementFieldTransformType::Pointer _xfm_disp=DisplacementFieldTransformType::New();\n\n _xfm_disp->SetDisplacementField(_dispXfrm->GetModifiableDisplacementField());\n\n tmp_comp_xfm->AddTransform(_xfm_disp);\n\n } else { //asume we just pass it on\n\n tmp_comp_xfm->AddTransform(_xfm);\n\n }\n\n }\n\n transformWriter->SetInput(tmp_comp_xfm);\n\n }\n\n else \n\n { //this is a simple transform\n\n transformWriter->SetInput(xfrm);\n\n }\n\n transformWriter->SetFileName(filename.c_str() );\n\n#if ITK_VERSION_MAJOR >= 5\n\n transformWriter->SetUseCompression(true);\n\n#endif\n\n transformWriter->Update();\n\n }\n\n }\n\n catch( itk::ExceptionObject & err )\n\n {\n\n std::cerr << \"Can't write transform file \" << filename << std::endl;\n\n std::cerr << \"Exception Object caught: \" << std::endl;\n\n std::cerr << err << std::endl;\n\n return EXIT_FAILURE;\n\n }\n\n return EXIT_SUCCESS;\n\n}\n\n\n\ntemplate <typename T, unsigned int VImageDimension>\n\nint\n\nWriteInverseTransform(typename itk::DisplacementFieldTransform<T, VImageDimension>::Pointer & xfrm,\n\n const std::string & filename)\n\n{\n\n typedef typename itk::DisplacementFieldTransform<T, VImageDimension> DisplacementFieldTransformType;\n\n typedef typename DisplacementFieldTransformType::DisplacementFieldType DisplacementFieldType;\n\n typedef typename itk::ImageFileWriter<DisplacementFieldType> DisplacementFieldWriter;\n\n typedef itk::TransformFileWriterTemplate<T> TransformWriterType;\n\n \n\n typename DisplacementFieldType::Pointer inverseDispField = xfrm->GetModifiableInverseDisplacementField();\n\n try\n\n {\n\n if( filename.find(\".xfm\" ) == std::string::npos\n\n && filename.find(\".h5\" ) == std::string::npos\n\n && filename.find(\".hdf5\") == std::string::npos\n\n && filename.find(\".hdf4\") == std::string::npos )\n\n {\n\n typename DisplacementFieldWriter::Pointer writer = DisplacementFieldWriter::New();\n\n writer->SetInput(inverseDispField);\n\n writer->SetFileName(filename.c_str() );\n\n writer->Update();\n\n }\n\n else\n\n // regular transform, but need to create inverse of the right type\n\n {\n\n typename DisplacementFieldTransformType::Pointer inv_xfrm=DisplacementFieldTransformType::New();\n\n inv_xfrm->SetDisplacementField(inverseDispField);\n\n typename TransformWriterType::Pointer transformWriter = TransformWriterType::New();\n\n transformWriter->SetInput(inv_xfrm);\n\n transformWriter->SetFileName(filename.c_str() );\n\n#if ITK_VERSION_MAJOR >= 5\n\n transformWriter->SetUseCompression(true);\n\n#endif\n\n transformWriter->Update();\n\n }\n\n }\n\n catch( itk::ExceptionObject & err )\n\n {\n\n std::cerr << \"Can't write transform file \" << filename << std::endl;\n\n std::cerr << \"Exception Object caught: \" << std::endl;\n\n std::cerr << err << std::endl;\n\n return EXIT_FAILURE;\n\n }\n\n return EXIT_SUCCESS;\n\n}\n\n\n\n\n\n} // namespace ants\n", "file_path": "Utilities/itkantsReadWriteTransform.h", "rank": 5, "score": 73867.93032142107 }, { "content": "class DijkstrasAlgorithm : public itk::LightObject\n\n{\n\npublic:\n\n typedef DijkstrasAlgorithm Self;\n\n typedef LightObject Superclass;\n\n typedef SmartPointer<Self> Pointer;\n\n typedef SmartPointer<const Self> ConstPointer;\n\n itkTypeMacro(DijkstrasAlgorithm, LightObject);\n\n itkNewMacro(Self);\n\n\n\n// Computation Data\n\n typedef TGraphSearchNode SearchNode; /** dimension of the graph */\n\n typedef typename SearchNode::Pointer SearchNodePointer;\n\n enum { GraphDimension = SearchNode::GraphDimension }; /** dimension of the graph */\n\n typedef typename SearchNode::PixelType PixelType; /** pixel type for the cost */\n\n typedef typename SearchNode::CoordRep CoordRep; /** coordinate type */\n\n typedef Image<SearchNodePointer, GraphDimension> GraphType;\n\n typedef typename GraphType::SizeType GraphSizeType;\n\n typedef ImageRegionIteratorWithIndex<GraphType> GraphIteratorType;\n\n typedef typename GraphType::RegionType GraphRegionType;\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 6, "score": 71629.42010319629 }, { "content": "namespace ants\n\n{\n\nextern int itkCommandLineParserTest( std::vector<std::string>, // equivalent to argv of command line parameters to main()\n\n std::ostream* out_stream // [optional] output stream to write\n\n );\n", "file_path": "Examples/include/itkCommandLineParserTest.h", "rank": 7, "score": 71618.31263719207 }, { "content": "class DijkstrasAlgorithmQueue : public itk::LightObject\n\n/** \\class DijkstrasAlgorithmQueue\n\nthe class containing the priority queue and associated data.\n\n*/\n\n{\n\nprivate:\n\n\n\n template <typename G>\n\n typename GraphSearchNodePriority /* defines the comparison operator for the prioritiy queue */\n\n {\n\npublic:\n\n bool operator()( typename G::Pointer N1,\n\n typename G::Pointer N2)\n\n {\n\n return N1->GetTotalCost() > N2->GetTotalCost();\n\n }\n\n };\n\npublic: /* Standard typedefs.*/\n\n typedef DijkstrasAlgorithmQueue Self;\n\n typedef LightObject Superclass;\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 8, "score": 70844.62055305742 }, { "content": "class ManifoldIntegrationAlgorithm : public itk::LightObject\n\n{\n\npublic:\n\n typedef ManifoldIntegrationAlgorithm Self;\n\n typedef LightObject Superclass;\n\n typedef SmartPointer<Self> Pointer;\n\n typedef SmartPointer<const Self> ConstPointer;\n\n itkTypeMacro(ManifoldIntegrationAlgorithm, LightObject);\n\n itkNewMacro(Self);\n\n\n\n// Computation Data\n\n typedef TGraphSearchNode SearchNode; /** dimension of the graph */\n\n typedef typename SearchNode::Pointer SearchNodePointer;\n\n enum { GraphDimension = SearchNode::GraphDimension }; /** dimension of the graph */\n\n typedef typename SearchNode::PixelType PixelType; /** pixel type for the cost */\n\n typedef typename SearchNode::CoordRep CoordRep; /** coordinate type */\n\n typedef typename DijkstrasAlgorithmQueue<TGraphSearchNode>::Pointer QType;\n\n typedef typename DijkstrasAlgorithmQueue<TGraphSearchNode>::NodeListType NodeListType;\n\n\n\n typedef typename TGraphSearchNode::NodeLocationType NodeLocationType;\n", "file_path": "Temporary/itkManifoldIntegrationAlgorithm.h", "rank": 9, "score": 70085.52987296009 }, { "content": "class HelperType<Dispatcher<2> >\n\n{\n\npublic:\n\n typedef ANTSCenteredAffine2DTransform<double> InternalAffineTransformType;\n\n\n\n typedef HelperCommonType<InternalAffineTransformType>::InternalAffineTransformPointerType\n\n InternalAffineTransformPointerType;\n\n typedef HelperCommonType<InternalAffineTransformType>::SingleInternalTransformItemType\n\n SingleInternalTransformItemType;\n\n typedef HelperCommonType<InternalAffineTransformType>::InternalTransformListType InternalTransformListType;\n\n typedef HelperCommonType<InternalAffineTransformType>::ParametersType ParametersType;\n\n\n\n static void ComputeAverageScaleParameters(InternalTransformListType & transform_list,\n\n ParametersType & average_parameters);\n\n\n\n static void ComputeAverageShearingParameters(InternalTransformListType & transform_list,\n\n ParametersType & average_parameters);\n\n\n\n static void ComputeAverageRotationParameters(InternalTransformListType & transform_list,\n\n ParametersType & average_parameters);\n\n\n\n static void ComputeAverageTranslationParameters(InternalTransformListType & transform_list,\n\n ParametersType & average_parameters);\n\n};\n\n\n\n// explicit specialization for 3D affine transform\n\ntemplate <>\n", "file_path": "Utilities/itkAverageAffineTransformFunction.h", "rank": 10, "score": 64391.10938802136 }, { "content": "class HelperType<Dispatcher<2> >\n\n{\n\npublic:\n\n typedef ANTSCenteredAffine2DTransform<double> InternalAffineTransformType;\n\n\n\n typedef HelperCommonType<InternalAffineTransformType>::InternalAffineTransformPointerType\n\n InternalAffineTransformPointerType;\n\n typedef HelperCommonType<InternalAffineTransformType>::SingleInternalTransformItemType\n\n SingleInternalTransformItemType;\n\n typedef HelperCommonType<InternalAffineTransformType>::InternalTransformListType InternalTransformListType;\n\n typedef HelperCommonType<InternalAffineTransformType>::ParametersType ParametersType;\n\n\n\n static void ComputeAverageScaleParameters(InternalTransformListType & transform_list,\n\n ParametersType & average_parameters);\n\n\n\n static void ComputeAverageShearingParameters(InternalTransformListType & transform_list,\n\n ParametersType & average_parameters);\n\n\n\n static void ComputeAverageRotationParameters(InternalTransformListType & transform_list,\n\n ParametersType & average_parameters);\n\n\n\n static void ComputeAverageTranslationParameters(InternalTransformListType & transform_list,\n\n ParametersType & average_parameters);\n\n};\n\n\n\n// explicit specialization for 3D affine transform\n\ntemplate <>\n", "file_path": "Utilities/itkAverageAffineTransformNoRigidFunction.h", "rank": 11, "score": 63409.78622125291 }, { "content": "class RegistrationHelper : public itk::Object\n\n{\n\npublic:\n\n /** Standard class typedefs */\n\n typedef RegistrationHelper Self;\n\n typedef itk::Object Superclass;\n\n typedef itk::SmartPointer<Self> Pointer;\n\n typedef itk::SmartPointer<const Self> ConstPointer;\n\n typedef itk::WeakPointer<const Self> ConstWeakPointer;\n\n\n\n typedef TComputeType RealType;\n\n typedef TComputeType PixelType;\n\n typedef itk::Image<PixelType, VImageDimension> ImageType;\n\n typedef typename ImageType::Pointer ImagePointer;\n\n typedef itk::ImageBase<VImageDimension> ImageBaseType;\n\n typedef typename ImageType::SpacingType ImageSpacingType;\n\n\n\n typedef itk::Array<TComputeType> IntensityAndGradientArrayType;\n\n typedef itk::PointSet<unsigned int, VImageDimension> LabeledPointSetType;\n\n typedef typename LabeledPointSetType::Pointer LabeledPointSetPointer;\n", "file_path": "Examples/itkantsRegistrationHelper.h", "rank": 12, "score": 61947.569420629196 }, { "content": "class BinaryImageToMeshFilter : public itk::ProcessObject\n\n{\n\npublic:\n\n typedef BinaryImageToMeshFilter Self;\n\n typedef itk::ProcessObject Superclass;\n\n typedef itk::SmartPointer<Self> Pointer;\n\n typedef itk::SmartPointer<const Self> ConstPointer;\n\n typedef itk::Image<float, 3> FloatImageType;\n\n\n\n /** Method for creation through the object factory. */\n\n itkNewMacro(Self);\n\n\n\n /** Image dimension. */\n\n static constexpr unsigned int ImageDimension = TImage::ImageDimension;\n\n\n\n /** Get the result mesh */\n\n vtkPolyData * GetMesh()\n\n {\n\n return fltTriangle->GetOutput();\n\n }\n", "file_path": "Utilities/BinaryImageToMeshFilter.h", "rank": 13, "score": 58308.374776419936 }, { "content": "class antsRegistrationCommandIterationUpdate : public itk::Command\n\n{\n\npublic:\n\n typedef antsRegistrationCommandIterationUpdate Self;\n\n typedef itk::Command Superclass;\n\n typedef itk::SmartPointer<Self> Pointer;\n\n itkNewMacro( Self );\n\nprotected:\n\n antsRegistrationCommandIterationUpdate()\n\n {\n\n m_clock.Start();\n\n m_clock.Stop();\n\n const itk::RealTimeClock::TimeStampType now = m_clock.GetTotal();\n\n this->m_lastTotalTime = now;\n\n m_clock.Start();\n\n this->m_LogStream = &std::cout;\n\n }\n\n\n\npublic:\n\n\n", "file_path": "Examples/antsRegistrationCommandIterationUpdate.h", "rank": 14, "score": 57506.47369268503 }, { "content": "class antsRegistrationOptimizerCommandIterationUpdate : public itk::Command\n\n{\n\npublic:\n\n typedef antsRegistrationOptimizerCommandIterationUpdate Self;\n\n typedef itk::Command Superclass;\n\n typedef itk::SmartPointer<Self> Pointer;\n\n itkNewMacro( Self );\n\n\n\n typedef ParametersValueType RealType;\n\n typedef ParametersValueType PixelType;\n\n typedef typename itk::Image<PixelType, VImageDimension> ImageType;\n\n typedef itk::ImageToImageMetricv4\n\n <ImageType, ImageType, ImageType, RealType> ImageMetricType;\n\n typedef itk::ObjectToObjectMultiMetricv4\n\n <VImageDimension, VImageDimension, ImageType, RealType> MultiMetricType;\n\n typedef typename ImageMetricType::MeasureType MeasureType;\n\n typedef itk::CompositeTransform<RealType, VImageDimension> CompositeTransformType;\n\n typedef typename CompositeTransformType::TransformType TransformBaseType;\n\nprotected:\n\n antsRegistrationOptimizerCommandIterationUpdate()\n", "file_path": "Examples/antsRegistrationOptimizerCommandIterationUpdate.h", "rank": 15, "score": 56011.62475776028 }, { "content": "class antsDisplacementAndVelocityFieldRegistrationCommandIterationUpdate : public itk::Command\n\n{\n\npublic:\n\n typedef antsDisplacementAndVelocityFieldRegistrationCommandIterationUpdate Self;\n\n typedef itk::Command Superclass;\n\n typedef itk::SmartPointer<Self> Pointer;\n\n itkNewMacro( Self );\n\n\n\n typedef typename TFilter::FixedImageType FixedImageType;\n\n typedef typename TFilter::MovingImageType MovingImageType;\n\n\n\n /** ImageDimension constants */\n\n static constexpr unsigned int VImageDimension = FixedImageType::ImageDimension;\n\n\n\n typedef typename TFilter::OutputTransformType OutputTransformType;\n\n typedef typename TFilter::OutputTransformType::ScalarType RealType;\n\n typedef itk::ImageToImageMetricv4\n\n <FixedImageType, MovingImageType, FixedImageType, RealType> MetricType;\n\n typedef typename MetricType::MeasureType MeasureType;\n\n typedef typename MetricType::VirtualImageType VirtualImageType;\n", "file_path": "Examples/antsDisplacementAndVelocityFieldRegistrationCommandIterationUpdate.h", "rank": 16, "score": 53394.39529877629 }, { "content": "class ITK_EXPORT LabelSelectionPixelAccessor\n\n{\n\npublic:\n\n /** External typedef. It defines the external aspect\n\n * that this class will exhibit. */\n\n typedef TExternalType ExternalType;\n\n\n\n /** Internal typedef. It defines the internal real\n\n * representation of data. */\n\n typedef TInternalType InternalType;\n\n\n\n\tvoid SetAcceptedValue(TInternalType value) { m_AcceptedValue = value; }\n\n\n\n inline TExternalType Get(const TInternalType & input) const\n\n {\n\n return (TExternalType)(\n\n ( input == m_AcceptedValue ) ? 1 : 0 );\n\n }\n\nprotected:\n\n\tTInternalType m_AcceptedValue;\n", "file_path": "ImageRegistration/itkLabelSelectionAdaptor.h", "rank": 17, "score": 45585.53849203797 }, { "content": "class ITK_EXPORT LabelPerimeterEstimationCalculator:\n\n public Object\n\n{\n\npublic:\n\n /** Standard class typedefs. */\n\n typedef LabelPerimeterEstimationCalculator Self;\n\n typedef Object Superclass;\n\n typedef SmartPointer< Self > Pointer;\n\n typedef SmartPointer< const Self > ConstPointer;\n\n\n\n /** Some convenient typedefs. */\n\n typedef TInputImage InputImageType;\n\n typedef typename InputImageType::Pointer InputImagePointer;\n\n typedef typename InputImageType::ConstPointer InputImageConstPointer;\n\n typedef typename InputImageType::RegionType InputImageRegionType;\n\n typedef typename InputImageType::PixelType InputImagePixelType;\n\n\n\n typedef typename InputImageType::RegionType RegionType;\n\n typedef typename InputImageType::SizeType SizeType;\n\n typedef typename InputImageType::IndexType IndexType;\n", "file_path": "Utilities/itkLabelPerimeterEstimationCalculator.h", "rank": 18, "score": 45585.53849203797 }, { "content": "class ITK_EXPORT DeterminantTensorImageFilter :\n\n public ImageToImageFilter<TInputImage, TOutputImage>\n\n{\n\npublic:\n\n /** Standard class typedefs. */\n\n typedef DeterminantTensorImageFilter Self;\n\n typedef ImageToImageFilter< TInputImage, TOutputImage > Superclass;\n\n typedef SmartPointer<Self> Pointer;\n\n typedef SmartPointer<const Self> ConstPointer;\n\n\n\n /** Method for creation through the object factory. */\n\n itkNewMacro(Self);\n\n\n\n /** Run-time type information (and related methods) */\n\n itkTypeMacro( DeterminantTensorImageFilter, ImageToImageFilter );\n\n\n\n /** Extract some information from the image types. Dimensionality\n\n * of the two images is assumed to be the same. */\n\n typedef typename TOutputImage::PixelType OutputPixelType;\n\n typedef typename TInputImage::PixelType InputPixelType;\n", "file_path": "Utilities/itkDeterminantTensorImageFilter.h", "rank": 19, "score": 45585.53849203797 }, { "content": "class ITK_EXPORT LabelSelectionImageAdaptor:public\n\n ImageAdaptor< TImage,\n\n Accessor::LabelSelectionPixelAccessor<\n\n typename TImage::PixelType,\n\n TOutputPixelType > >\n\n{\n\npublic:\n\n /** Standard class typedefs. */\n\n typedef LabelSelectionImageAdaptor Self;\n\n typedef ImageAdaptor< TImage, Accessor::LabelSelectionPixelAccessor<\n\n typename TImage::PixelType,\n\n TOutputPixelType > > Superclass;\n\n\n\n typedef SmartPointer< Self > Pointer;\n\n typedef SmartPointer< const Self > ConstPointer;\n\n\n\n /** Method for creation through the object factory. */\n\n itkNewMacro(Self);\n\n\n\n /** Run-time type information (and related methods). */\n", "file_path": "ImageRegistration/itkLabelSelectionAdaptor.h", "rank": 20, "score": 44850.91376335248 }, { "content": "class ITK_EXPORT GeometricJacobianDeterminantImageFilter :\n\n public ImageToImageFilter<TInputImage, TOutputImage>\n\n{\n\npublic:\n\n /** Standard class typedefs. */\n\n typedef GeometricJacobianDeterminantImageFilter Self;\n\n typedef ImageToImageFilter<TInputImage, TOutputImage> Superclass;\n\n typedef SmartPointer<Self> Pointer;\n\n typedef SmartPointer<const Self> ConstPointer;\n\n\n\n /** Method for creation through the object factory. */\n\n itkNewMacro( Self );\n\n\n\n /** Run-time type information (and related methods) */\n\n itkTypeMacro( GeometricJacobianDeterminantImageFilter, ImageToImageFilter );\n\n\n\n /** Extract some information from the image types. Dimensionality\n\n * of the two images is assumed to be the same. */\n\n typedef typename TOutputImage::PixelType OutputPixelType;\n\n typedef typename TInputImage::PixelType InputPixelType;\n", "file_path": "Utilities/itkGeometricJacobianDeterminantImageFilter.h", "rank": 21, "score": 44139.5909168052 }, { "content": " unsigned long m_NumberSearched;\n\n DijkstrasAlgorithm();\n\n ~DijkstrasAlgorithm()\n\n {\n\n };\n\nprivate:\n\n\n\n DijkstrasAlgorithm(const Self &); // purposely not implemented\n\n void operator=(const Self &); // purposely not implemented\n\n};\n\n} // end namespace itk\n\n\n\n#ifndef ITK_MANUAL_INSTANTIATION\n\n#include \"itkDijkstrasAlgorithm.cxx\"\n\n#endif\n\n\n\n#endif\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 22, "score": 43293.73324032943 }, { "content": " typedef typename DijkstrasAlgorithmQueue<TGraphSearchNode>::Pointer QType;\n\n typedef typename DijkstrasAlgorithmQueue<TGraphSearchNode>::NodeListType\n\n NodeListType;\n\n typedef itk::NeighborhoodIterator<GraphType>\n\n GraphNeighborhoodIteratorType;\n\n typedef typename GraphNeighborhoodIteratorType::IndexType\n\n GraphNeighborhoodIndexType;\n\n typedef typename GraphNeighborhoodIteratorType::RadiusType\n\n RadiusType;\n\n typedef typename TGraphSearchNode::NodeLocationType NodeLocationType;\n\n typedef typename GraphType::IndexType IndexType;\n\n// FUNCTIONS\n\n void InitializeGraph(); /** initializes all graph values appropriately */\n\n\n\n void InitializeQueue(); /** initializes all queue values appropriately\n\n call AFTER source and sink are set*/\n\n\n\n void InitializeEdgeTemplate(); /** helper function initializes edge set appropriately */\n\n\n\n void InitializeEdgeTemplate(vector<unsigned int>, unsigned int); /** user supplied edge template */\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 23, "score": 43291.56822460355 }, { "content": "#include \"itkNumericTraits.h\"\n\n\n\nnamespace itk\n\n{\n\nnamespace Function\n\n{\n\n\n\n/*\n\n *\n\n *\n\n */\n\ntemplate< typename TInputPixel, typename TOutputPixel >\n", "file_path": "Utilities/itkTextureHistogram.h", "rank": 24, "score": 43290.926088820044 }, { "content": "* the node to have a pointer to itself and entry for the cumulative cost.\n\n* We also define an index to its location and a couple of booleans\n\n* for keeping track of the graph node's state.\n\n* We assume the connectivity between nodes is defined externally.\n\n* The class will also be useful for minimum spanning trees and\n\n* other graph search algorithms. Connectivity is defined externally.\n\n* May be worthwhile to implement arbitrary connectivity e.g. for random graphs.\n\n* One way to do this is to include a list of pointers which define\n\n* the neighbors of this node, similar to how the predecessor is defined.\n\n*/\n\ntemplate <typename TPixelType, typename TCoordRep = unsigned int,\n\n unsigned int NGraphDimension = 2>\n\ntypename GraphSearchNode : public itk::LightObject\n\n{\n\npublic:\n\n\n\n /* Standard typedefs.*/\n\n typedef GraphSearchNode Self;\n\n typedef LightObject Superclass;\n\n typedef SmartPointer<Self> Pointer;\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 25, "score": 43289.42571337337 }, { "content": " /* alternatively, we could pass the function as a template parameter\n\n or set a function pointer. the latter method is used in dijkstrasegment. */\n\n\n\n virtual void FindPath(); /* runs the algorithm */\n\n\n\n inline unsigned int GetPathSize()\n\n {\n\n return m_QS->m_Path.size();\n\n }\n\n\n\n inline typename TGraphSearchNode::Pointer GetPathAtIndex(unsigned int i)\n\n {\n\n return m_QS->m_Path[i];\n\n }\n\n\n\n inline typename TGraphSearchNode::Pointer GetNeighborNode()\n\n {\n\n return m_NeighborNode;\n\n }\n\n\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 26, "score": 43288.1332267971 }, { "content": "#include <iostream>\n\n#include <stack>\n\n#include <vector>\n\n#include <list>\n\n#include <queue>\n\n#include <map>\n\n\n\n#include \"itkMath.h\"\n\n// #include \"vnl/vnl_matrix_fixed.h\"\n\n// #include \"vnl/vnl_vector_fixed.h\"\n\n#include \"itkImage.h\"\n\n#include \"itkImageRegionIteratorWithIndex.h\"\n\n#include \"itkNeighborhoodIterator.h\"\n\n#include \"itkVector.h\"\n\nusing namespace std;\n\n\n\nnamespace itk\n\n{\n\n/** The GraphSearchNode class defines a general shortest path graph node.\n\n* The algorithm requires\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 27, "score": 43287.46820041252 }, { "content": " return m_State;\n\n }\n\n\n\n inline void SetIdentity(unsigned int i)\n\n {\n\n m_Identity = i;\n\n }\n\n\n\n inline unsigned int GetIdentity()\n\n {\n\n return m_Identity;\n\n }\n\n\n\n inline int GetNumberOfNeighbors()\n\n {\n\n return m_Neighbors.size();\n\n }\n\n\n\n inline Pointer GetNeighbor(int i)\n\n {\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 28, "score": 43285.96364762888 }, { "content": " return m_Neighbors[i];\n\n }\n\n\n\n void SetNeighborSize(int i)\n\n {\n\n m_Neighbors.resize(i);\n\n }\n\n\n\n NodeListType m_Neighbors;\n\n unsigned short m_NumberOfNeighbors;\n\n unsigned int m_Identity;\n\nprotected:\n\n\n\n GraphSearchNode()\n\n {\n\n m_TotalCost = 0.0;\n\n m_Value1 = 0.0;\n\n m_Value2 = 0.0;\n\n m_Value3 = 0.0;\n\n m_Value4 = 0.0;\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 29, "score": 43285.23148317178 }, { "content": " out[i++] = kurtosis;\n\n out[i++] = entropy;\n\n return out;\n\n }\n\n\n\n void AddBoundary(){}\n\n\n\n void RemoveBoundary(){}\n\n\n\nprivate:\n\n typedef typename std::map< TInputPixel, size_t > MapType;\n\n\n\n MapType m_Map;\n\n size_t m_Count;\n\n};\n\n\n\n} // end namespace Function\n\n} // end namespace itk\n\n#endif\n", "file_path": "Utilities/itkTextureHistogram.h", "rank": 30, "score": 43285.20943436532 }, { "content": "\n\n * Modified source versions must be plainly marked as such, and must not be\n\n misrepresented as being the original software.\n\n\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''\n\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\n\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n\n=========================================================================*/\n\n#ifndef _itkDijkstrasAlgorithm_h_\n\n#define _itkDijkstrasAlgorithm_h_\n\n\n\n#include <string>\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 31, "score": 43283.68359363911 }, { "content": " double skewness = 0.0;\n\n double kurtosis = 0.0;\n\n if(std::abs(variance * sigma) > itk::NumericTraits<double>::min())\n\n {\n\n\n\n skewness = ( ( sum3 - 3.0 * mean * sum2 ) * icount + 2.0 * mean * mean*mean ) / ( variance * sigma );\n\n }\n\n if(std::abs(variance) > itk::NumericTraits<double>::min())\n\n {\n\n kurtosis = ( sum4 * icount + mean *( -4.0 * sum3 * icount + mean * ( 6.0 *sum2 * icount - 3.0 * mean * mean ))) /\n\n ( variance * variance ) - 3.0;\n\n }\n\n\n\n unsigned int i = 0;\n\n out[i++] = mean;\n\n out[i++] = m_Map.begin()->first;\n\n out[i++] = m_Map.rbegin()->first;\n\n out[i++] = variance;\n\n out[i++] = sigma;\n\n out[i++] = skewness;\n", "file_path": "Utilities/itkTextureHistogram.h", "rank": 32, "score": 43282.51263381715 }, { "content": " typedef SmartPointer<const Self> ConstPointer;\n\n itkTypeMacro(GraphSearchNode, LightObject);\n\n itkNewMacro(Self); /** Method for creation through the object factory. */\n\n\n\n enum StateType { UnVisitedState, VisitedState, DeliveredState, UnVisitableState };\n\n enum { GraphDimension = NGraphDimension };\n\n typedef TPixelType PixelType; /** defines the cost data type */\n\n typedef TCoordRep CoordRep; /** defines the location data type */\n\n typedef itk::Vector<CoordRep, GraphDimension> NodeLocationType;\n\n\n\n// typedef typename itk::Image<float,GraphDimension>::IndexType NodeLocationType;\n\n\n\n typedef vector<Pointer> NodeListType;\n\n\n\n// typedef itk::Image<CoordRep,GraphDimension>::IndexType NodeLocationType;\n\n\n\n inline void SetLocation(NodeLocationType loc)\n\n {\n\n m_Location = loc;\n\n }\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 33, "score": 43281.66576004313 }, { "content": "\n\n void SetGraphSize(typename GraphType::SizeType Sz); /** the rectangular size of the graph */\n\n\n\n inline void EmptyQ()\n\n {\n\n m_QS->EmptyQ(); this->m_TotalCost = 0;\n\n }\n\n\n\n /* adds a source to the source set */\n\n void SetSource(typename TGraphSearchNode::Pointer G)\n\n {\n\n m_QS->m_SourceNodes.push_back(G);\n\n for( int i = 0; i < GraphDimension; i++ )\n\n {\n\n m_GraphIndex[i] = (long int)(G->GetLocation()[i] + 0.5);\n\n// ::std::cout << \" mgi \" << m_GraphIndex[i];\n\n }\n\n m_Graph->SetPixel(m_GraphIndex, G);\n\n };\n\n\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 34, "score": 43280.06928349516 }, { "content": " typedef SmartPointer<Self> Pointer;\n\n typedef SmartPointer<const Self> ConstPointer;\n\n itkTypeMacro(DijkstrasAlgorithmQueue, LightObject);\n\n itkNewMacro(Self); /** Method for creation through the object factory. */\n\n\n\n typedef typename TGraphSearchNode::Pointer TGraphSearchNodePointer;\n\n typedef typename TGraphSearchNode::PixelType PixelType; /** pixel type for the cost */\n\n typedef typename TGraphSearchNode::CoordRep CoordRep; /** type for coordinates */\n\n typedef typename std::priority_queue<typename TGraphSearchNode::Pointer,\n\n std::vector<typename TGraphSearchNode::Pointer>,\n\n GraphSearchNodePriority<TGraphSearchNode> > QType; /** the queue we are using */\n\n typedef vector<typename TGraphSearchNode::Pointer> NodeListType;\n\n inline QType GetQ()\n\n {\n\n return m_Q;\n\n }\n\n\n\n void AddToPath(TGraphSearchNodePointer G)\n\n {\n\n this->m_Path.push_back(G);\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 35, "score": 43279.97705157872 }, { "content": "\n\n inline NodeLocationType GetLocation()\n\n {\n\n return m_Location;\n\n }\n\n\n\n inline void SetTotalCost(TPixelType cost)\n\n {\n\n m_TotalCost = cost;\n\n }\n\n\n\n inline void SetValue(TPixelType cost, int which = 0)\n\n {\n\n if( which <= 0 )\n\n {\n\n m_Value1 = cost;\n\n }\n\n if( which == 1 )\n\n {\n\n m_Value2 = cost;\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 36, "score": 43279.521270518955 }, { "content": " /** sets the boolean that indicates if the algorithm is done */\n\nprotected:\n\n QType m_QS;\n\n vector<unsigned int> m_EdgeTemplate; /** defines neighborhood connectivity */\n\n RadiusType m_Radius; /** used by the neighborhood iterator */\n\n typename TGraphSearchNode::Pointer m_PredecessorNode; /** holds the predecessor node */\n\n typename TGraphSearchNode::Pointer m_CurrentNode; /** holds the current node */\n\n typename TGraphSearchNode::Pointer m_NeighborNode; /** holds the current neighbor node */\n\n typename GraphType::Pointer m_Graph; /** holds all the graph information */\n\n GraphRegionType m_GraphRegion;\n\n GraphSizeType m_GraphSize; /** rectangular size of graph */\n\n\n\n typename GraphType::IndexType m_GraphIndex;\n\n bool m_SearchFinished;\n\n PixelType m_NewCost;\n\n PixelType m_CurrentCost;\n\n PixelType m_MaxCost; // This creates an insurmountable barrier unless all costs are max\n\n\n\n double m_TotalCost;\n\n\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 37, "score": 43279.511619350786 }, { "content": " m_PredecessorAddress = nullptr;\n\n m_AncestorAddress = nullptr;\n\n m_State = UnVisitedState;\n\n m_NumberOfNeighbors = 0;\n\n m_Identity = 0;\n\n }\n\n\n\n ~GraphSearchNode()\n\n {\n\n }\n\n\n\nprivate:\n\n TPixelType m_TotalCost; /** keeps track of the minimum accumulated cost. */\n\n TPixelType m_Value1; /** keeps track of the minimum accumulated cost. */\n\n TPixelType m_Value2; /** keeps track of the minimum accumulated cost. */\n\n TPixelType m_Value3; /** keeps track of the minimum accumulated cost. */\n\n TPixelType m_Value4; /** keeps track of the minimum accumulated cost. */\n\n\n\n StateType m_State;\n\n NodeLocationType m_Location; /** provides the location in the graph. */\n\n Pointer m_PredecessorAddress; /** provides the best predecessor address */\n\n Pointer m_AncestorAddress; /** provides the best predecessor address */\n\n\n\n GraphSearchNode(const Self &); // purposely not implemented\n\n void operator=(const Self &); // purposely not implemented\n\n};\n\n\n\n// Forward declaration of DijkstrasAlgorithm so it can be declared a friend\n\ntemplate <typename TGraphSearchNode>\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 38, "score": 43276.15976357402 }, { "content": " DijkstrasAlgorithmQueue(const Self &); // purposely not implemented\n\n void operator=(const Self &); // purposely not implemented\n\n};\n\n\n\n/**\n\n * \\class DijkstrasAlgorithm\n\n * \\brief General shortest path / greedy dynamic programming solver.\n\n *\n\n * This class uses Dijkstra's algorithm to solve the shortest path problem.\n\n * We use the stl priority queue which is not optimal for this problem, but which\n\n * works o.k. It's implemented to be used for general regularly connected\n\n * graphs with fixed costs, or for the variational solution of an integral\n\n * curve matching energy.\n\n * Note: we assume all edge weights are positive.\n\n * The class is implemented as a an abstract base class, with virtual functions for\n\n * LocalCost, SearchEdgeSet and FindPath. LocalCost must be implemented by derived classes.\n\n * The connectivity of the graph defined\n\n * here is always regular and is controlled by a set of neighborhood indices.\n\n * the default is a radius 1 neighborhood with all entries used. However, the\n\n * user may also supply her own regular connectivity by selecting the size of\n\n * the neighborhood and a subset of the indices which define the edges. If\n\n * the GraphSearchNode contains its edges, they may be used with minor modification\n\n * to the function SearchEdgeSet.\n\n * Another improvement would be to make the LocalCost function a pointer\n\n * to a function which could be set.\n\n */\n\ntemplate <typename TGraphSearchNode>\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 39, "score": 43275.78381183656 }, { "content": " }\n\n if( which == 2 )\n\n {\n\n return m_Value3;\n\n }\n\n if( which >= 3 )\n\n {\n\n return m_Value4;\n\n }\n\n return m_Value1;\n\n }\n\n\n\n inline void SetUnVisited()\n\n {\n\n m_State = UnVisitedState;\n\n }\n\n\n\n inline void SetUnVisitable()\n\n {\n\n m_State = UnVisitableState;\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 40, "score": 43275.204817021375 }, { "content": " }\n\n\n\n inline void SetVisited()\n\n {\n\n m_State = VisitedState;\n\n }\n\n\n\n inline void SetDelivered()\n\n {\n\n m_State = DeliveredState;\n\n }\n\n\n\n inline bool IsInQueue()\n\n {\n\n if( m_State == VisitedState )\n\n {\n\n return true;\n\n }\n\n else\n\n {\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 41, "score": 43275.204817021375 }, { "content": " }\n\n\n\n inline void IncrementTimer()\n\n {\n\n m_timer++;\n\n }\n\n\n\n inline long GetTimer()\n\n {\n\n return m_timer;\n\n }\n\n\n\n inline void EmptyQ()\n\n {\n\n while( !m_Q.empty() )\n\n {\n\n m_Q.pop();\n\n }\n\n\n\n m_timer = 0; m_SourceNodes.clear(); m_SinkNodes.clear();\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 42, "score": 43275.13586115757 }, { "content": " inline typename TGraphSearchNode::Pointer GetCurrentNode()\n\n {\n\n return m_CurrentNode;\n\n }\n\n\n\n void SetMaxCost(PixelType m)\n\n {\n\n m_MaxCost = m;\n\n }\n\n\n\n double GetTotalCost()\n\n {\n\n return m_TotalCost;\n\n }\n\n\n\n void SetSearchFinished(bool m)\n\n {\n\n m_SearchFinished = m;\n\n }\n\n\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 43, "score": 43275.00291647629 }, { "content": " inline TPixelType GetTotalCost()\n\n {\n\n return m_TotalCost;\n\n }\n\n\n\n inline void SetPredecessor(Pointer address)\n\n {\n\n m_PredecessorAddress = address;\n\n }\n\n\n\n inline Pointer GetPredecessor()\n\n {\n\n return m_PredecessorAddress;\n\n }\n\n\n\n inline void SetAncestor(Pointer address)\n\n {\n\n m_AncestorAddress = address;\n\n }\n\n\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 44, "score": 43275.00291647629 }, { "content": " }\n\n if( G->GetValue() > P->GetValue() )\n\n {\n\n P->SetValue(G->GetValue() );\n\n }\n\n G = P;\n\n P = G->GetAncestor();\n\n }\n\n\n\n return;\n\n }\n\n\n\n virtual bool TerminationCondition(); /** decides when the algorithm stops */\n\n\n\n virtual void SearchEdgeSet(); /** loops over the neighbors in the graph */\n\n\n\n void CheckNodeStatus(); /** checks if the node has been explored already, its cost, etc. */\n\n\n\n virtual PixelType LocalCost(); /* computes the local cost */\n\n\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 45, "score": 43274.7259367764 }, { "content": " }\n\n if( which == 2 )\n\n {\n\n m_Value3 = cost;\n\n }\n\n if( which >= 3 )\n\n {\n\n m_Value4 = cost;\n\n }\n\n }\n\n\n\n inline TPixelType GetValue(int which = 0)\n\n {\n\n if( which <= 0 )\n\n {\n\n return m_Value1;\n\n }\n\n if( which == 1 )\n\n {\n\n return m_Value2;\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 46, "score": 43274.569342021874 }, { "content": "/*=========================================================================\n\n *\n\n * Copyright Insight Software Consortium\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/LICENSE-2.0.txt\n\n *\n\n * Unless required by applicable law or agreed to in writing, software\n\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\n * See the License for the specific language governing permissions and\n\n * limitations under the License.\n\n *\n\n *=========================================================================*/\n\n// histogram from the moving histogram operations\n\n#ifndef __itkTextureHistogram_h\n\n#define __itkTextureHistogram_h\n", "file_path": "Utilities/itkTextureHistogram.h", "rank": 47, "score": 43274.35058923121 }, { "content": " typename TGraphSearchNode::Pointer GetGraphNode( IndexType index)\n\n {\n\n // ::std::cout << \" get node \" << index << std::endl;\n\n return m_Graph->GetPixel(index);\n\n };\n\n\n\n // adds a sink to the sink set\n\n void SetSink(typename TGraphSearchNode::Pointer G)\n\n {\n\n m_QS->m_SinkNodes.push_back(G);\n\n }\n\n\n\n // Backtracks from the given node to its source node;\n\n void BackTrack(typename TGraphSearchNode::Pointer SinkNode)\n\n {\n\n m_QS->m_Path.clear();\n\n\n\n typename TGraphSearchNode::Pointer G = SinkNode;\n\n typename TGraphSearchNode::Pointer P = SinkNode->GetPredecessor();\n\n if( !P || !G )\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 48, "score": 43274.29778061582 }, { "content": "\n\n inline bool GetDelivered()\n\n {\n\n if( m_State == DeliveredState )\n\n {\n\n return true;\n\n }\n\n else\n\n {\n\n return false;\n\n }\n\n }\n\n\n\n inline void SetState(StateType S)\n\n {\n\n m_State = S;\n\n }\n\n\n\n inline StateType GetState()\n\n {\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 49, "score": 43274.27150941599 }, { "content": " }\n\n\n\n inline NodeListType GetPath()\n\n {\n\n return m_Path;\n\n }\n\n\n\n void EmptyPath()\n\n {\n\n m_Path.clear();\n\n }\n\n\n\n inline NodeListType GetSourceNodes()\n\n {\n\n return m_SourceNodes;\n\n }\n\n\n\n inline NodeListType GetSinkNodes()\n\n {\n\n return m_SinkNodes;\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 50, "score": 43274.107699988584 }, { "content": " }\n\n\n\n NodeListType m_SinkNodes;\n\n NodeListType m_SourceNodes;\n\n QType m_Q;\n\n NodeListType m_Path;\n\nprotected:\n\n friend class DijkstrasAlgorithm<TGraphSearchNode>; // so it can access this data easily\n\n\n\n DijkstrasAlgorithmQueue()\n\n {\n\n m_timer = 0;\n\n }\n\n\n\n ~DijkstrasAlgorithmQueue()\n\n {\n\n }\n\n\n\nprivate:\n\n unsigned long m_timer;\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 51, "score": 43273.98049581795 }, { "content": " }\n\n }\n\n\n\n if( !P )\n\n {\n\n cout << \" null pred \"; // else cout << \" pred == self \\n\";\n\n }\n\n return;\n\n }\n\n\n\n // Inverse of backtrack - from the given node to its sink node;\n\n void ForwardTrack(typename TGraphSearchNode::Pointer SinkNode)\n\n {\n\n typename TGraphSearchNode::Pointer G = SinkNode;\n\n typename TGraphSearchNode::Pointer P = SinkNode->GetAncestor();\n\n while( P && G != P && G )\n\n {\n\n if( P->GetValue() > G->GetValue() )\n\n {\n\n G->SetValue(P->GetValue() );\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 52, "score": 43273.535900855124 }, { "content": "/*=========================================================================\n\n\n\n Program: Insight Segmentation & Registration Toolkit (ITK)\n\n\n\nCopyright (c) 2001 Insight Consortium\n\nAll rights reserved.\n\n\n\nRedistribution and use in source and binary forms, with or without\n\nmodification, are permitted provided that the following conditions are met:\n\n\n\n * Redistributions of source code must retain the above copyright notice,\n\n this list of conditions and the following disclaimer.\n\n\n\n * Redistributions in binary form must reproduce the above copyright notice,\n\n this list of conditions and the following disclaimer in the documentation\n\n and/or other materials provided with the distribution.\n\n\n\n * The name of the Insight Consortium, nor the names of any consortium members,\n\n nor of any contributors, may be used to endorse or promote products derived\n\n from this software without specific prior written permission.\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 53, "score": 43273.25484218557 }, { "content": " return false;\n\n }\n\n }\n\n\n\n inline bool WasVisited()\n\n {\n\n if( m_State == VisitedState )\n\n {\n\n return true;\n\n }\n\n else if( m_State == DeliveredState )\n\n {\n\n return true;\n\n }\n\n else\n\n {\n\n return false;\n\n }\n\n }\n\n\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 54, "score": 43269.598979840535 }, { "content": "// // this is wrong!\n\n// if ( curCount == count / 2 )\n\n// {\n\n// median += i->first;\n\n// medianIt = il\n\n// // we have an even number so take the average\n\n// if ( !(count % 2) )\n\n// {\n\n// median *= 0.5;\n\n// }\n\n// }\n\n\n\n }\n\n\n\n// curCount = 0;\n\n// typename MapType::iterator fmedianIt = medianIt;\n\n// typename MapType::iterator rmedianIt = medianIt;\n\n// double mad = 0.0;\n\n\n\n// while (curCount < count/2 )\n", "file_path": "Utilities/itkTextureHistogram.h", "rank": 55, "score": 43269.598979840535 }, { "content": " // insert new item if one doesn't exist\n\n typename MapType::iterator it = m_Map.find( p );\n\n\n\n assert( it != m_Map.end() );\n\n\n\n if ( --(it->second) == 0 )\n\n {\n\n m_Map.erase( it );\n\n }\n\n --m_Count;\n\n\n\n }\n\n\n\n TOutputPixel GetValue(const TInputPixel &)\n\n {\n\n TOutputPixel out;\n\n NumericTraits<TOutputPixel>::SetLength( out, 8 );\n\n\n\n double sum = 0.0;\n\n double sum2 = 0.0;\n", "file_path": "Utilities/itkTextureHistogram.h", "rank": 56, "score": 43269.598979840535 }, { "content": " {\n\n return;\n\n }\n\n float highcost = G->GetValue();\n\n if( G->GetTotalCost() > P->GetValue() )\n\n {\n\n P->SetAncestor(G);\n\n P->SetValue(G->GetTotalCost() );\n\n highcost = G->GetTotalCost();\n\n }\n\n\n\n while( P && G != P )\n\n {\n\n m_QS->m_Path.push_back(G);\n\n G = P;\n\n P = G->GetPredecessor();\n\n if( P->GetValue() < highcost )\n\n {\n\n P->SetValue(highcost);\n\n P->SetAncestor(G);\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 57, "score": 43269.598979840535 }, { "content": " {\n\n return true;\n\n }\n\n else\n\n {\n\n return false;\n\n }\n\n }\n\n\n\n inline bool GetVisited()\n\n {\n\n if( m_State == VisitedState )\n\n {\n\n return true;\n\n }\n\n else\n\n {\n\n return false;\n\n }\n\n }\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 58, "score": 43269.598979840535 }, { "content": " double sum3 = 0.0;\n\n double sum4 = 0.0;\n\n const size_t count = m_Count;\n\n //double median = 0.0;\n\n\n\n double entropy = 0.0;\n\n size_t curCount = 0;\n\n for ( typename MapType::iterator i = m_Map.begin(); i != m_Map.end(); ++i )\n\n {\n\n double t = double(i->first)*double(i->second);\n\n sum += t;\n\n sum2 += ( t *= double(i->first) );\n\n sum3 += ( t *= double(i->first) );\n\n sum4 += ( t *= double(i->first) );\n\n\n\n curCount += i->second;\n\n\n\n const double p_x = double( i->second ) / count;\n\n entropy += -p_x*std::log( p_x );\n\n\n", "file_path": "Utilities/itkTextureHistogram.h", "rank": 59, "score": 43269.598979840535 }, { "content": " inline Pointer GetAncestor()\n\n {\n\n return m_AncestorAddress;\n\n }\n\n\n\n inline bool GetUnVisited()\n\n {\n\n if( m_State == UnVisitedState )\n\n {\n\n return true;\n\n }\n\n else\n\n {\n\n return false;\n\n }\n\n }\n\n\n\n inline bool GetUnVisitable()\n\n {\n\n if( m_State == UnVisitableState )\n", "file_path": "Temporary/itkDijkstrasAlgorithm.h", "rank": 60, "score": 43269.598979840535 }, { "content": "// {\n\n// if ( std::fabs( fmedianIt->first - median ) < std::fabs( rmedianIt->first - median ) )\n\n// {\n\n// curCount += fmedianIt->second;\n\n// ++fmedianIt;\n\n// }\n\n// else\n\n// {\n\n// curCount += rmedianIt->second;\n\n// --rmedianIt;\n\n// }\n\n// }\n\n\n\n\n\n const double icount = 1.0 / count;\n\n const double mean = sum * icount;\n\n\n\n // unbiased estimate\n\n const double variance = ( sum2 - ( sum * sum * icount ) ) / ( count - 1 );\n\n const double sigma = std::sqrt(variance);\n", "file_path": "Utilities/itkTextureHistogram.h", "rank": 61, "score": 43269.598979840535 }, { "content": "class ITK_EXPORT NeighborhoodFirstOrderStatisticsImageFilter:\n\n public MovingHistogramImageFilter< TInputImage,\n\n TOutputImage,\n\n TKernel,\n\n typename Function::TextureHistogram< typename TInputImage::PixelType,\n\n typename TOutputImage::PixelType > >\n\n{\n\npublic:\n\n /** Standard class typedefs. */\n\n typedef NeighborhoodFirstOrderStatisticsImageFilter Self;\n\n typedef MovingHistogramImageFilter< TInputImage, TOutputImage, TKernel,\n\n typename Function::TextureHistogram< typename TInputImage::PixelType, typename TOutputImage::PixelType> > Superclass;\n\n typedef SmartPointer< Self > Pointer;\n\n typedef SmartPointer< const Self > ConstPointer;\n\n\n\n /** Standard New method. */\n\n itkNewMacro(Self);\n\n\n\n /** Runtime information support. */\n\n itkTypeMacro( NeighborhoodFirstOrderStatisticsImageFilter, MovingHistogramImageFilter );\n", "file_path": "Utilities/itkNeighborhoodFirstOrderStatisticsImageFilter.h", "rank": 62, "score": 42782.55247735143 }, { "content": "class ITK_EXPORT DeformationFieldGradientTensorImageFilter :\n\n public ImageToImageFilter<TInputImage, TOutputImage>\n\n{\n\npublic:\n\n /** Standard class typedefs. */\n\n typedef DeformationFieldGradientTensorImageFilter Self;\n\n typedef ImageToImageFilter<TInputImage, TOutputImage> Superclass;\n\n typedef SmartPointer<Self> Pointer;\n\n typedef SmartPointer<const Self> ConstPointer;\n\n\n\n /** Method for creation through the object factory. */\n\n itkNewMacro(Self);\n\n\n\n /** Run-time type information (and related methods) */\n\n itkTypeMacro( DeformationFieldGradientTensorImageFilter, ImageToImageFilter );\n\n\n\n /** Extract some information from the image types. Dimensionality\n\n * of the two images is assumed to be the same. */\n\n typedef typename TOutputImage::PixelType OutputPixelType;\n\n typedef typename TInputImage::PixelType InputPixelType;\n", "file_path": "Utilities/itkDeformationFieldGradientTensorImageFilter.h", "rank": 63, "score": 42782.55247735143 }, { "content": "// #include <vnl/algo/vnl_rpoly_roots.h>\n\n#include \"itkObject.h\"\n\n#include \"itkProcessObject.h\"\n\n\n\n#include \"itkVectorContainer.h\"\n\n#include \"itkCastImageFilter.h\"\n\n\n\nnamespace itk\n\n{\n\n/** \\class SurfaceCurvatureBase\n\n *\n\n * This class takes a surface as input and creates a local\n\n * geometric frame for each surface point.\n\n *\n\n * \\note The origin of a neighborhood is always taken to be\n\n * the first point entered into and the\n\n * last point stored in the list.\n\n */\n\ntemplate <typename TSurface, unsigned int TDimension = 3>\n", "file_path": "Utilities/itkSurfaceCurvatureBase.h", "rank": 64, "score": 41997.24468843087 }, { "content": "#include \"itkFEM.h\"\n\n#include \"itkFEMLinearSystemWrapperItpack.h\"\n\n#include \"itkFEMElement3DC0LinearTriangularLaplaceBeltrami.h\"\n\n#include \"itkFEMElement3DC0LinearTriangularMembrane.h\"\n\n\n\nnamespace itk\n\n{\n\n/** \\class FEMConformalMap\n\n * Angenent, Haker conformal mapping algorithm using FEM.\n\n *\n\n * \\note The origin of a neighborhood is always taken to be\n\n * the first point entered into and the\n\n * last point stored in the list.\n\n */\n\ntemplate <typename TSurface, typename TImage, unsigned int TDimension = 3>\n", "file_path": "Temporary/itkFEMConformalMap.h", "rank": 65, "score": 41996.41794494095 }, { "content": " void PrintSelf( std::ostream& os, Indent indent ) const;\n\n\n\nprivate:\n\n\n\n DecomposeTensorFunction2(const Self &) = delete;\n\n void operator=(const Self &) = delete;\n\n};\n\n} // end namespace itk\n\n\n\n#ifndef ITK_MANUAL_INSTANTIATION\n\n#include \"itkDecomposeTensorFunction2.hxx\"\n\n#endif\n\n\n\n#endif\n", "file_path": "Tensor/itkDecomposeTensorFunction2.h", "rank": 66, "score": 41995.75276029281 }, { "content": "private:\n\n PointSetFunction(const Self &) = delete;\n\n void operator=(const Self &) = delete;\n\n};\n\n} // end namespace itk\n\n\n\n// Define instantiation macro for this template.\n\n#define ITK_TEMPLATE_PointSetFunction(_, EXPORT, x, y) namespace itk { \\\n\n _(3 (class EXPORT PointSetFunction<ITK_TEMPLATE_3 x> ) ) \\\n\n namespace Templates { typedef PointSetFunction<ITK_TEMPLATE_3 x> PointSetFunction##y; } \\\n\n }\n\n\n\n#ifndef ITK_MANUAL_INSTANTIATION\n\n#include \"itkPointSetFunction.hxx\"\n\n#endif\n\n\n\n#endif\n", "file_path": "Utilities/itkPointSetFunction.h", "rank": 67, "score": 41995.48814825715 }, { "content": " RealType EvaluateDeterminant( InputMatrixType & );\n\n\n\n DecomposeTensorFunction();\n\n ~DecomposeTensorFunction() override = default;\n\n\n\nprotected:\n\n\n\n void PrintSelf( std::ostream& os, Indent indent ) const override;\n\n\n\nprivate:\n\n\n\n DecomposeTensorFunction(const Self &) = delete;\n\n void operator=(const Self &) = delete;\n\n};\n\n} // end namespace itk\n\n\n\n#ifndef ITK_MANUAL_INSTANTIATION\n\n#include \"itkDecomposeTensorFunction.hxx\"\n\n#endif\n\n\n\n#endif\n", "file_path": "Utilities/itkDecomposeTensorFunction.h", "rank": 68, "score": 41993.98835446315 }, { "content": "\n\n /** Estimate the directional curvature using Shimshoni's method (eq 6).*/\n\n virtual void EstimateDirectionalCurvature(PointType, PointType);\n\n\n\n void PrintFrame();\n\n\n\n virtual void ComputeFrameOverDomain(unsigned int /* which */ = 3)\n\n {\n\n };\n\n\n\n RealType ErrorEstimate(PointType, RealType sign = 1.0 );\n\n\n\n unsigned int CharacterizeSurface();\n\n\n\n itkSetMacro(Origin, PointType);\n\n itkGetMacro(Origin, PointType);\n\n\n\n itkSetMacro(AveragePoint, PointType);\n\n itkGetMacro(AveragePoint, PointType);\n\n\n", "file_path": "Utilities/itkSurfaceCurvatureBase.h", "rank": 69, "score": 41990.82800252299 }, { "content": " itkSetMacro(kSign, float);\n\n\n\n itkSetMacro(Threshold, float);\n\n\n\n itkGetMacro(FunctionImage, OutputImagePointer);\n\n itkSetMacro(FunctionImage, OutputImagePointer);\n\n\n\n void ProcessLabelImage();\n\n\n\n float CurvatureAtIndex(IndexType index)\n\n {\n\n PointType p;\n\n\n\n for( unsigned int k = 0; k < ImageDimension; k++ )\n\n {\n\n p[k] = (RealType) index[k];\n\n }\n\n this->SetOrigin(p);\n\n this->EstimateFrameFromGradient(index);\n\n this->FindNeighborhood();\n", "file_path": "Utilities/itkSurfaceImageCurvature.h", "rank": 70, "score": 41986.80998604075 }, { "content": " RealType m_Eval1;\n\n RealType m_Eval2;\n\n\n\n unsigned int m_CurrentNeighborhoodPointIndex;\n\n\n\n std::string m_ParameterFileName;\n\n\n\n /** We use this to avoid computing the frame in degenerate cases. */\n\n RealType m_TotalDKap;\n\n\n\n RealType m_TotalArea;\n\n\n\n RealType m_Sigma;\n\n\n\n bool m_UseGeodesicNeighborhood;\n\nprivate:\n\n};\n\n} // namespace itk\n\n\n\n#ifndef ITK_MANUAL_INSTANTIATION\n\n#include \"itkSurfaceCurvatureBase.hxx\"\n\n#endif\n\n\n\n#endif\n", "file_path": "Utilities/itkSurfaceCurvatureBase.h", "rank": 71, "score": 41986.80514520139 }, { "content": "#include \"itkGradientImageFilter.h\"\n\n#include \"itkVectorLinearInterpolateImageFunction.h\"\n\n\n\nnamespace itk\n\n{\n\n/** \\class SurfaceImageCurvature\n\n *\n\n * This class takes a surface as input and creates a local\n\n * geometric frame for each surface point.\n\n *\n\n *\n\n */\n\ntemplate <typename TSurface>\n", "file_path": "Utilities/itkSurfaceImageCurvature.h", "rank": 72, "score": 41985.35596383265 }, { "content": "\n\n * Modified source versions must be plainly marked as such, and must not be\n\n misrepresented as being the original software.\n\n\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''\n\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\n\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n\n=========================================================================*/\n\n#ifndef _itkManifoldIntegrationAlgorithm_h_\n\n#define _itkManifoldIntegrationAlgorithm_h_\n\n\n\nnamespace itk\n\n{\n\n/**\n\n * \\class ManifoldIntegrationAlgorithm\n\n * \\brief General shortest path / greedy dynamic programming solver.\n\n */\n\ntemplate <typename TGraphSearchNode>\n", "file_path": "Temporary/itkManifoldIntegrationAlgorithm.h", "rank": 73, "score": 41985.30205202719 }, { "content": "private:\n\n VarianceImageFilter(const Self &) = delete;\n\n void operator=(const Self &) = delete;\n\n};\n\n} // end namespace itk\n\n\n\n#ifndef ITK_MANUAL_INSTANTIATION\n\n#include \"itkVarianceImageFilter.hxx\"\n\n#endif\n\n\n\n#endif\n", "file_path": "Utilities/itkVarianceImageFilter.h", "rank": 74, "score": 41984.97493198303 }, { "content": " itk::fem::LinearSystemWrapperItpack itpackWrapper;\n\n\n\n unsigned long m_PoleElementsGN[7];\n\n};\n\n} // namespace itk\n\n\n\n#ifndef ITK_MANUAL_INSTANTIATION\n\n#include \"itkFEMConformalMap.cxx\"\n\n#endif\n\n\n\n#endif\n", "file_path": "Temporary/itkFEMConformalMap.h", "rank": 75, "score": 41984.88410697565 }, { "content": " {\n\n };\n\nprivate:\n\n\n\n ManifoldIntegrationAlgorithm(const Self &); // purposely not implemented\n\n void operator=(const Self &); // purposely not implemented\n\n};\n\n} // end namespace itk\n\n\n\n#ifndef ITK_MANUAL_INSTANTIATION\n\n#include \"itkManifoldIntegrationAlgorithm.cxx\"\n\n#endif\n\n\n\n#endif\n", "file_path": "Temporary/itkManifoldIntegrationAlgorithm.h", "rank": 76, "score": 41984.79917360579 }, { "content": "// static constexpr unsigned int ImageDimension = TImage::ImageDimension;\n\n static constexpr unsigned int ImageDimension = TDimension;\n\n static constexpr unsigned int SurfaceDimension = TDimension;\n\n\n\n typedef float RealType;\n\n typedef vnl_vector<RealType> VectorType;\n\n typedef vnl_vector_fixed<RealType, itkGetStaticConstMacro(ImageDimension)>\n\n FixedVectorType;\n\n typedef vnl_vector_fixed<RealType, itkGetStaticConstMacro(ImageDimension)>\n\n PointType;\n\n typedef vnl_matrix<double> MatrixType;\n\n typedef std::vector<PointType> PointContainerType;\n\n typedef std::vector<float> FunctionContainerType;\n\n\n\n /** Set input parameter file */\n\n itkSetStringMacro( ParameterFileName );\n\n\n\n /** Set input parameter file */\n\n itkGetStringMacro( ParameterFileName );\n\n\n", "file_path": "Utilities/itkSurfaceCurvatureBase.h", "rank": 77, "score": 41984.482513097864 }, { "content": "\n\n#include \"itkVariableSizeMatrix.h\"\n\n\n\nnamespace itk\n\n{\n\n/** \\class DecomposeTensorFunction\n\n *\n\n */\n\ntemplate <typename TInput,\n\n typename TRealType = float,\n\n typename TOutput = itk::VariableSizeMatrix<TRealType>\n\n >\n", "file_path": "Utilities/itkDecomposeTensorFunction.h", "rank": 78, "score": 41984.464262836205 }, { "content": " /** Find all points within some distance of the origin.\n\n * The argument gives the number of times to apply the\n\n * mean shift algorithm to find the best neighborhood.\n\n */\n\n void FindNeighborhood(unsigned int numMeanShifts = 0) override;\n\n\n\n void FindEuclideanNeighborhood(PointType p);\n\n\n\n void FindGeodesicNeighborhood();\n\n\n\n /** This applies one of the algorithms for finding the local curvature\n\n and frame. The default is joshi. */\n\n void ComputeFrameOverDomain(unsigned int which = 0) override;\n\n\n\n ImageType * GetInput();\n\n\n\n virtual void SetInputImage(typename ImageType::Pointer & input);\n\n OutputImageType * GetOutput();\n\n\n\n /** Apply the level set curvature equation over the whole image */\n", "file_path": "Utilities/itkSurfaceImageCurvature.h", "rank": 79, "score": 41984.05119177187 }, { "content": "\n\n int GetGraphSize()\n\n {\n\n return m_GraphX.size();\n\n }\n\n\n\n // sanity check to see if mesh to graph conversion is ok\n\n // see if genus is the same\n\n void ConvertGraphBackToMesh();\n\n\n\n void SetParamWhileSearching( bool b )\n\n {\n\n this->m_ParamWhileSearching = b;\n\n }\n\n\n\n std::vector<SearchNodePointer> m_BoundaryList;\n\nprotected:\n\n QType m_QS;\n\n vector<unsigned int> m_EdgeTemplate; /** defines neighborhood connectivity */\n\n\n", "file_path": "Temporary/itkManifoldIntegrationAlgorithm.h", "rank": 80, "score": 41983.7359783021 }, { "content": "#include \"itkBoxImageFilter.h\"\n\n#include \"itkImage.h\"\n\n#include \"itkNumericTraits.h\"\n\n\n\nnamespace itk\n\n{\n\n/** \\class VarianceImageFilter\n\n * \\brief Applies an averaging filter to an image\n\n *\n\n * Computes an image where a given pixel is the variance value of the\n\n * the pixels in a neighborhood about the corresponding input pixel.\n\n *\n\n * A variacne filter is one of the family of linear filters.\n\n *\n\n * \\sa Image\n\n * \\sa Neighborhood\n\n * \\sa NeighborhoodOperator\n\n * \\sa NeighborhoodIterator\n\n *\n\n * \\ingroup IntensityImageFilters\n\n * \\ingroup ITKSmoothing\n\n *\n\n * \\wiki\n\n * \\wikiexample{Smoothing/VarianceImageFilter,Variance filter an image}\n\n * \\endwiki\n\n */\n\ntemplate< typename TInputImage, typename TOutputImage >\n", "file_path": "Utilities/itkVarianceImageFilter.h", "rank": 81, "score": 41983.52706362196 }, { "content": " /** Get the input image. */\n\n const InputPointSetType * GetInputPointSet() const\n\n {\n\n return m_PointSet.GetPointer();\n\n }\n\n\n\n /** Evaluate the function at specified Point position.\n\n * Subclasses must provide this method. */\n\n virtual TOutput Evaluate( const InputPointType& point ) const = 0;\n\n\n\nprotected:\n\n PointSetFunction();\n\n ~PointSetFunction()\n\n {\n\n }\n\n\n\n void PrintSelf(std::ostream& os, Indent indent) const;\n\n\n\n /** Const pointer to the input image. */\n\n InputPointSetConstPointer m_PointSet;\n", "file_path": "Utilities/itkPointSetFunction.h", "rank": 82, "score": 41983.40605581873 }, { "content": " /** Surface (mesh) types. */\n\n typedef TSurface SurfaceType;\n\n typedef typename SurfaceType::Pointer SurfaceTypePointer;\n\n typedef typename SurfaceType::PointType PointType;\n\n typedef typename SurfaceType::CellsContainerPointer InputCellsContainerPointer;\n\n typedef typename SurfaceType::CellsContainer::Iterator InputCellsContainerIterator;\n\n\n\n /** Image dimension. */\n\n// static constexpr unsigned int ImageDimension = TImage::ImageDimension;\n\n static constexpr unsigned int ImageDimension = TDimension;\n\n static constexpr unsigned int SurfaceDimension = TDimension;\n\n\n\n typedef double RealType;\n\n typedef vnl_vector<RealType> VectorType;\n\n typedef vnl_vector_fixed<RealType, itkGetStaticConstMacro(ImageDimension)>\n\n FixedVectorType;\n\n typedef vnl_matrix<double> MatrixType;\n\n\n\n /** FEM types */\n\n typedef itk::fem::MaterialLinearElasticity MaterialType;\n", "file_path": "Temporary/itkFEMConformalMap.h", "rank": 83, "score": 41982.169905126655 }, { "content": " /** Fill the point list with the points neighboring the current origin */\n\n virtual void FindNeighborhood(unsigned int temp = 0);\n\n\n\n /** A Euclidean relative of L.D. Griffin's compactness.*/\n\n RealType ComputeMeanEuclideanDistance();\n\n\n\n /** */\n\n void ComputeAveragePoint();\n\n\n\n void ProjectToTangentPlane(PointType);\n\n\n\n void EigenDecomposition(MatrixType D);\n\n\n\n /** Estimate the plane tangent to a point using the neighborhood\n\n * of the point. This is, in general, an over-constrained least\n\n * squares fitting problem.\n\n */\n\n void EstimateTangentPlane(PointType);\n\n void WeightedEstimateTangentPlane(PointType);\n\n void TestEstimateTangentPlane(PointType);\n", "file_path": "Utilities/itkSurfaceCurvatureBase.h", "rank": 84, "score": 41982.1492960635 }, { "content": "\n\n bool ParameterizeBoundary( SearchNodePointer);\n\n\n\n bool TerminationCondition(); /** decides when the algorithm stops */\n\n\n\n virtual void SearchEdgeSet(); /** loops over the neighbors in the graph */\n\n\n\n void CheckNodeStatus(); /** checks if the node has been explored already, its cost, etc. */\n\n\n\n virtual PixelType MyLocalCost(); /* computes the local cost */\n\n\n\n /* alternatively, we could pass the function as a template parameter\n\n or set a function pointer. the latter method is used in dijkstrasegment. */\n\n\n\n virtual void FindPath(); /* runs the algorithm */\n\n\n\n inline unsigned int GetPathSize()\n\n {\n\n return m_QS->m_Path.size();\n\n }\n", "file_path": "Temporary/itkManifoldIntegrationAlgorithm.h", "rank": 85, "score": 41981.914520575345 }, { "content": "/*=========================================================================\n\n\n\n Program: Advanced Normalization Tools\n\n\n\n Copyright (c) ConsortiumOfANTS. All rights reserved.\n\n See accompanying COPYING.txt or\n\n https://github.com/stnava/ANTs/blob/master/ANTSCopyright.txt for details.\n\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n\n PURPOSE. See the above copyright notices for more information.\n\n\n\n=========================================================================*/\n\n#ifndef __itkDecomposeTensorFunction2_h\n\n#define __itkDecomposeTensorFunction2_h\n\n\n\n#include \"itkVariableSizeMatrix.h\"\n\n\n\nnamespace itk\n\n{\n\n/** \\class DecomposeTensorFunction2\n\n *\n\n */\n\ntemplate <typename TInput,\n\n typename TRealType = float,\n\n typename TOutput = itk::VariableSizeMatrix<TRealType>\n\n >\n", "file_path": "Tensor/itkDecomposeTensorFunction2.h", "rank": 86, "score": 41981.599633271915 }, { "content": " itkSetMacro(SphereImage, ImageTypePointer);\n\n itkSetMacro(SouthPole, int);\n\n void SetNorthPole(int p)\n\n {\n\n if( p % 2 == 0 )\n\n {\n\n m_NorthPole = p;\n\n m_SouthPole = p + 1;\n\n }\n\n else\n\n {\n\n m_NorthPole = p - 1;\n\n m_SouthPole = p - 1;\n\n }\n\n }\n\n\n\n void SetDebug(bool b)\n\n {\n\n m_Debug = b;\n\n }\n", "file_path": "Temporary/itkFEMConformalMap.h", "rank": 87, "score": 41980.833125422156 }, { "content": "/*=========================================================================\n\n\n\n Program: Advanced Normalization Tools\n\n\n\n Copyright (c) ConsortiumOfANTS. All rights reserved.\n\n See accompanying COPYING.txt or\n\n https://github.com/stnava/ANTs/blob/master/ANTSCopyright.txt for details.\n\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n\n PURPOSE. See the above copyright notices for more information.\n\n\n\n=========================================================================*/\n\n#ifndef _SurfaceMeshCurvature_h\n\n#define _SurfaceMeshCurvature_h\n\n\n\n#include \"itkSurfaceCurvatureBase.h\"\n\n\n\nnamespace itk\n\n{\n\n/** \\class SurfaceMeshCurvature\n\n *\n\n * This class takes a surface as input and creates a local\n\n * geometric frame for each surface point.\n\n *\n\n *\n\n */\n\ntemplate <typename TSurface, typename TSurfacePatch>\n", "file_path": "Utilities/itkSurfaceMeshCurvature.h", "rank": 88, "score": 41980.78277545711 }, { "content": " typedef typename Superclass::PointType PointType;\n\n typedef typename Superclass::MatrixType MatrixType;\n\n\n\n typedef TSurfacePatch SurfacePatch;\n\n typedef typename TSurfacePatch::Pointer SurfacePatchPointer;\n\n typedef typename TSurfacePatch::NodeLocationType VertexType;\n\n typedef typename TSurfacePatch::PixelType FunctionValueType;\n\n typedef TSurface * SurfacePointer; // probably vtkmesh\n\n\n\n /** Find all points within some distance of the origin.\n\n * The argument gives the number of times to apply the\n\n * mean shift algorithm to find the best neighborhood.\n\n */\n\n virtual void FindNeighborhood(unsigned int numMeanShifts = 0)\n\n {\n\n this->m_PointList.clear();\n\n this->m_FunctionValueList.clear();\n\n VertexType origin = m_SurfacePatch->GetLocation();\n\n PointType pt;\n\n for( int j = 0; j < 3; j++ )\n", "file_path": "Utilities/itkSurfaceMeshCurvature.h", "rank": 89, "score": 41980.74408186503 }, { "content": "#include \"itkImageBase.h\"\n\n\n\nnamespace itk\n\n{\n\n/** \\class PointSetFunction\n\n * \\brief Evaluates a function of an image at specified position.\n\n *\n\n * PointSetFunction is a baseclass for all objects that evaluates\n\n * a function of an image at index, continuous index or point.\n\n * This class is templated over the input image type, the type\n\n * of the function output and the coordinate representation type\n\n * (e.g. float or double).\n\n *\n\n * The input image is set via method SetInputPointSet().\n\n * Methods Evaluate, EvaluateAtIndex and EvaluateAtContinuousIndex\n\n * respectively evaluates the function at an geometric point,\n\n * image index and continuous image index.\n\n *\n\n * \\warning Image BufferedRegion information is cached during\n\n * in SetInputPointSet( image ). If the image BufferedRegion has changed\n", "file_path": "Utilities/itkPointSetFunction.h", "rank": 90, "score": 41980.723975145396 }, { "content": " };\n\nprotected:\n\nprivate:\n\n\n\n SurfacePointer m_Surface;\n\n SurfacePatchPointer m_SurfacePatch;\n\n};\n\n} // namespace itk\n\n\n\n#ifndef ITK_MANUAL_INSTANTIATION\n\n// #include \"itkSurfaceMeshCurvature.hxx\"\n\n#endif\n\n\n\n#endif\n", "file_path": "Utilities/itkSurfaceMeshCurvature.h", "rank": 91, "score": 41980.3176501207 }, { "content": " enum { ImageDimension = TSurface::ImageDimension };\n\n typedef Image<PixelType, itkGetStaticConstMacro(ImageDimension)>\n\n ImageType;\n\n typedef typename ImageType::IndexType IndexType;\n\n typedef typename ImageType::SizeType SizeType;\n\n typedef ImageRegionIteratorWithIndex<ImageType> ImageIteratorType;\n\n /** Image dimension. */\n\n static constexpr unsigned int SurfaceDimension = TSurface::ImageDimension;\n\n\n\n typedef typename Superclass::RealType RealType;\n\n typedef typename Superclass::PointType VectorType;\n\n typedef typename Superclass::PointType FixedVectorType;\n\n typedef typename Superclass::PointType PointType;\n\n typedef typename Superclass::MatrixType MatrixType;\n\n typedef typename ImageType::PointType ImagePointType;\n\n\n\n typedef Image<PixelType, itkGetStaticConstMacro(ImageDimension)>\n\n OutputImageType;\n\n typedef ImageRegionIteratorWithIndex<OutputImageType> OutputImageIteratorType;\n\n\n", "file_path": "Utilities/itkSurfaceImageCurvature.h", "rank": 92, "score": 41979.23501259832 }, { "content": " {\n\n pt(j) = origin[j];\n\n }\n\n this->m_Origin = pt;\n\n this->m_PointList.insert(this->m_PointList.begin(), pt);\n\n this->m_FunctionValueList.insert(this->m_FunctionValueList.begin(), m_SurfacePatch->GetValue() );\n\n for( unsigned int i = 0; i < m_SurfacePatch->m_Neighbors.size(); i++ )\n\n {\n\n VertexType neigh = m_SurfacePatch->m_Neighbors[i]->GetLocation();\n\n PointType pti;\n\n for( int j = 0; j < 3; j++ )\n\n {\n\n pti(j) = neigh[j];\n\n }\n\n this->m_PointList.insert(this->m_PointList.begin(), pti);\n\n this->m_FunctionValueList.insert(\n\n this->m_FunctionValueList.begin(), this->m_SurfacePatch->m_Neighbors[i]->GetValue(0) );\n\n }\n\n }\n\n\n", "file_path": "Utilities/itkSurfaceMeshCurvature.h", "rank": 93, "score": 41978.836128231036 }, { "content": " SizeType m_ImageSize;\n\n GradientImagePointer m_GradientImage;\n\n NeighborhoodIteratorType m_ti;\n\n NeighborhoodIteratorType m_ti2;\n\n bool m_UseLabel;\n\n float m_kSign;\n\n float m_Threshold;\n\n float m_Area;\n\n RealType m_MinSpacing;\n\n typename VectorInterpolatorType::Pointer m_Vinterp;\n\n};\n\n} // namespace itk\n\n\n\n#ifndef ITK_MANUAL_INSTANTIATION\n\n#include \"itkSurfaceImageCurvature.hxx\"\n\n#endif\n\n\n\n#endif\n", "file_path": "Utilities/itkSurfaceImageCurvature.h", "rank": 94, "score": 41978.717417923 }, { "content": "\n\n inline void EmptyPath()\n\n {\n\n m_QS->m_Path.clear();\n\n }\n\n\n\n inline typename TGraphSearchNode::Pointer GetPathAtIndex(unsigned int i)\n\n {\n\n return m_QS->m_Path[i];\n\n }\n\n\n\n inline typename TGraphSearchNode::Pointer GetNeighborNode()\n\n {\n\n return m_NeighborNode;\n\n }\n\n\n\n inline typename TGraphSearchNode::Pointer GetCurrentNode()\n\n {\n\n return m_CurrentNode;\n\n }\n", "file_path": "Temporary/itkManifoldIntegrationAlgorithm.h", "rank": 95, "score": 41977.398900881846 }, { "content": "#include \"vtkPolyDataNormals.h\"\n\n#include \"vtkMarchingCubes.h\"\n\n#include \"vtkImageGaussianSmooth.h\"\n\n#include \"vtkDecimatePro.h\"\n\n#include \"vtkContourFilter.h\"\n\n#include \"vtkPolyDataConnectivityFilter.h\"\n\n// #include \"vtkKitwareContourFilter.h\"\n\n#include \"vtkSmoothPolyDataFilter.h\"\n\n#include \"vtkSTLWriter.h\"\n\n#include \"vtkUnstructuredGridToPolyDataFilter.h\"\n\n// #include \"itkImageToVTKImageFilter.h\"\n\n#include \"vtkDelaunay2D.h\"\n\n#include \"vtkFloatArray.h\"\n\n\n\n#include \"itkObject.h\"\n\n#include \"itkProcessObject.h\"\n\n\n\n#include \"itkVectorContainer.h\"\n\n#include \"itkCastImageFilter.h\"\n\n\n", "file_path": "Temporary/itkFEMConformalMap.h", "rank": 96, "score": 41977.09817023997 }, { "content": "\n\n /** This function sets the reference tangent arbitrarily.\n\n * It can be overridden in case there is a better practical approach.\n\n */\n\n void ChooseReferenceTangent();\n\n\n\n /** This function fills the weight and angle vectors for\n\n * a given neighborhood.\n\n */\n\n virtual void ComputeWeightsAndDirectionalKappaAndAngles(PointType origin);\n\n\n\n /** */\n\n void ComputeFrame(PointType origin);\n\n\n\n /** */\n\n void ComputeFrameAndKappa(PointType origin);\n\n\n\n void ShimshoniFrame(PointType origin);\n\n\n\n /** */\n", "file_path": "Utilities/itkSurfaceCurvatureBase.h", "rank": 97, "score": 41976.953437844655 }, { "content": "\n\n void SetReadFromFile(bool b)\n\n {\n\n m_ReadFromFile = b;\n\n }\n\n\n\n void FindPoles(int dim);\n\n\n\n void FixPoles(int dim);\n\n\n\n void ConformalParameterize();\n\n\n\n void ConformalMap();\n\n\n\n void ComputeStereographicCoordinates();\n\n\n\n void MapStereographicCoordinatesToImage(int dim);\n\n\n\n void MapImageToSphere(ImageType* img, float rad );\n\n\n", "file_path": "Temporary/itkFEMConformalMap.h", "rank": 98, "score": 41976.88175988941 }, { "content": "/*=========================================================================\n\n\n\n Program: Advanced Normalization Tools\n\n\n\n Copyright (c) ConsortiumOfANTS. All rights reserved.\n\n See accompanying COPYING.txt or\n\n https://github.com/stnava/ANTs/blob/master/ANTSCopyright.txt for details.\n\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n\n PURPOSE. See the above copyright notices for more information.\n\n\n\n=========================================================================*/\n\n#ifndef __itkPointSetFunction_h\n\n#define __itkPointSetFunction_h\n\n\n\n#include \"itkFunctionBase.h\"\n\n#include \"itkPoint.h\"\n\n#include \"itkIndex.h\"\n\n#include \"itkContinuousIndex.h\"\n", "file_path": "Utilities/itkPointSetFunction.h", "rank": 99, "score": 41976.538486678124 } ]
C++
searchlib/src/tests/features/subqueries/subqueries_test.cpp
amahussein/vespa
29d266ae1e5c95e25002b97822953fdd02b1451e
#include <vespa/vespalib/testkit/test_kit.h> #include <vespa/searchlib/features/setup.h> #include <vespa/searchlib/fef/test/indexenvironment.h> #include <vespa/searchlib/fef/test/indexenvironmentbuilder.h> #include <vespa/searchlib/fef/test/queryenvironment.h> #include <vespa/searchlib/features/subqueries_feature.h> #include <vespa/searchlib/fef/fef.h> #include <vespa/searchlib/fef/test/dummy_dependency_handler.h> #include <vespa/vespalib/util/stringfmt.h> using search::feature_t; using namespace search::fef; using namespace search::fef::test; using namespace search::features; using CollectionType = FieldInfo::CollectionType; struct BlueprintFactoryFixture { BlueprintFactory factory; BlueprintFactoryFixture() : factory() { setup_search_features(factory); } }; struct IndexFixture { IndexEnvironment indexEnv; IndexFixture() : indexEnv() { IndexEnvironmentBuilder builder(indexEnv); builder.addField(FieldType::INDEX, CollectionType::SINGLE, "foo"); builder.addField(FieldType::ATTRIBUTE, CollectionType::SINGLE, "bar"); } }; struct FeatureDumpFixture : public IDumpFeatureVisitor { virtual void visitDumpFeature(const vespalib::string &) override { TEST_ERROR("no features should be dumped"); } FeatureDumpFixture() : IDumpFeatureVisitor() {} }; struct RankFixture : BlueprintFactoryFixture, IndexFixture { QueryEnvironment queryEnv; RankSetup rankSetup; MatchDataLayout mdl; MatchData::UP match_data; RankProgram::UP rankProgram; std::vector<TermFieldHandle> fooHandles; std::vector<TermFieldHandle> barHandles; RankFixture(size_t fooCnt, size_t barCnt, std::string featureName = "subqueries(foo)") : queryEnv(&indexEnv), rankSetup(factory, indexEnv), mdl(), match_data(), rankProgram(), fooHandles(), barHandles() { fooHandles = addFields(fooCnt, indexEnv.getFieldByName("foo")->id()); barHandles = addFields(barCnt, indexEnv.getFieldByName("bar")->id()); rankSetup.setFirstPhaseRank(featureName); rankSetup.setIgnoreDefaultRankFeatures(true); ASSERT_TRUE(rankSetup.compile()); match_data = mdl.createMatchData(); rankProgram = rankSetup.create_first_phase_program(); rankProgram->setup(*match_data, queryEnv); } std::vector<TermFieldHandle> addFields(size_t count, uint32_t fieldId) { std::vector<TermFieldHandle> handles; for (size_t i = 0; i < count; ++i) { handles.push_back(mdl.allocTermField(fieldId)); SimpleTermData term; term.addField(fieldId).setHandle(handles.back()); queryEnv.getTerms().push_back(term); } return handles; } feature_t getSubqueries(uint32_t docId) { return Utils::getScoreFeature(*rankProgram, docId); } void setSubqueries(TermFieldHandle handle, uint32_t docId, uint64_t subqueries) { match_data->resolveTermField(handle)->setSubqueries(docId, subqueries); } void setFooSubqueries(uint32_t i, uint32_t docId, uint64_t subqueries) { ASSERT_LESS(i, fooHandles.size()); setSubqueries(fooHandles[i], docId, subqueries); } void setBarSubqueries(uint32_t i, uint32_t docId, uint64_t subqueries) { ASSERT_LESS(i, barHandles.size()); setSubqueries(barHandles[i], docId, subqueries); } }; TEST_F("require that blueprint can be created from factory", BlueprintFactoryFixture) { Blueprint::SP bp = f.factory.createBlueprint("subqueries"); EXPECT_TRUE(bp.get() != 0); EXPECT_TRUE(dynamic_cast<SubqueriesBlueprint*>(bp.get()) != 0); } TEST_FFF("require that no features are dumped", SubqueriesBlueprint, IndexFixture, FeatureDumpFixture) { f1.visitDumpFeatures(f2.indexEnv, f3); } TEST_FF("require that setup can be done on index field", SubqueriesBlueprint, IndexFixture) { DummyDependencyHandler deps(f1); f1.setName(vespalib::make_string("%s(foo)", f1.getBaseName().c_str())); EXPECT_TRUE(((Blueprint&)f1).setup(f2.indexEnv, {"foo"})); } TEST_FF("require that setup can be done on attribute field", SubqueriesBlueprint, IndexFixture) { DummyDependencyHandler deps(f1); f1.setName(vespalib::make_string("%s(bar)", f1.getBaseName().c_str())); EXPECT_TRUE(((Blueprint&)f1).setup(f2.indexEnv, {"bar"})); } TEST_FF("require that setup fails for unknown field", SubqueriesBlueprint, IndexFixture) { DummyDependencyHandler deps(f1); f1.setName(vespalib::make_string("%s(unknown)", f1.getBaseName().c_str())); EXPECT_FALSE(((Blueprint&)f1).setup(f2.indexEnv, {"unknown"})); } TEST_F("require that not searching a field will give it 0 subqueries", RankFixture(0, 3)) { EXPECT_EQUAL(0, f1.getSubqueries(10)); } TEST_F("require that subqueries can be obtained", RankFixture(1, 0)) { f1.setFooSubqueries(0, 10, 0x1234); EXPECT_EQUAL(0x1234, f1.getSubqueries(10)); } TEST_F("require that msb subqueries can be obtained", RankFixture(1, 0, "subqueries(foo).msb")) { f1.setFooSubqueries(0, 10, 0x123412345678ULL); EXPECT_EQUAL(0x1234, f1.getSubqueries(10)); } TEST_F("require that multiple subqueries are accumulated", RankFixture(3, 0)) { f1.setFooSubqueries(0, 10, 1); f1.setFooSubqueries(1, 10, 2); f1.setFooSubqueries(2, 10, 4); EXPECT_EQUAL(7, f1.getSubqueries(10)); } TEST_F("require that stale subqueries are ignored", RankFixture(3, 0)) { f1.setFooSubqueries(0, 10, 1); f1.setFooSubqueries(1, 9, 2); f1.setFooSubqueries(2, 10, 4); EXPECT_EQUAL(5, f1.getSubqueries(10)); } TEST_F("require that subqueries from other fields are ignored", RankFixture(2, 2)) { f1.setFooSubqueries(0, 10, 1); f1.setFooSubqueries(1, 10, 2); f1.setBarSubqueries(0, 10, 4); f1.setBarSubqueries(1, 10, 8); EXPECT_EQUAL(3, f1.getSubqueries(10)); } TEST_MAIN() { TEST_RUN_ALL(); }
#include <vespa/vespalib/testkit/test_kit.h> #include <vespa/searchlib/features/setup.h> #include <vespa/searchlib/fef/test/indexenvironment.h> #include <vespa/searchlib/fef/test/indexenvironmentbuilder.h> #include <vespa/searchlib/fef/test/queryenvironment.h> #include <vespa/searchlib/features/subqueries_feature.h> #include <vespa/searchlib/fef/fef.h> #include <vespa/searchlib/fef/test/dummy_dependency_handler.h> #include <vespa/vespalib/util/stringfmt.h> using search::feature_t; using namespace search::fef; using namespace search::fef::test; using namespace search::features; using CollectionType = FieldInfo::CollectionType; struct BlueprintFactoryFixture { BlueprintFactory factory; BlueprintFactoryFixture() : factory() { setup_search_features(factory); } }; struct IndexFixture { IndexEnvironment indexEnv; IndexFixture() : indexEnv() { IndexEnvironmentBuilder builder(indexEnv); builder.addField(FieldType::INDEX, CollectionType::SINGLE, "foo"); builder.addField(FieldType::ATTRIBUTE, CollectionType::SINGLE, "bar"); } }; struct FeatureDumpFixture : public IDumpFeatureVisitor { virtual void visitDumpFeature(const vespalib::string &) override { TEST_ERROR("no features should be dumped"); } FeatureDumpFixture() : IDumpFeatureVisitor() {} }; struct RankFixture : BlueprintFactoryFixture, IndexFixture { QueryEnvironment queryEnv; RankSetup rankSetup; MatchDataLayout mdl; MatchData::UP match_data; RankProgram::UP rankProgram; std::vector<TermFieldHandle> fooHandles; std::vector<TermFieldHandle> barHandles; RankFixture(size_t fooCnt, size_t barCnt, std::string featureName = "subqueries(foo)") : queryEnv(&indexEnv), rankSetup(factory, indexEnv), mdl(), match_data(), rankProgram(), fooHandles(), barHandles() { fooHandles = addFields(fooCnt, indexEnv.getFieldByName("foo")->id()); barHandles = addFields(barCnt, indexEnv.getFieldByName("bar")->id()); rankSetup.setFirstPhaseRank(featureName); rankSetup.setIgnoreDefaultRankFeatures(true); ASSERT_TRUE(rankSetup.compile()); match_data = mdl.createMatchData(); rankProgram = rankSetup.create_first_phase_program(); rankProgram->setup(*match_data, queryEnv); } std::vector<TermFieldHandle> addFields(size_t count, uint32_t fieldId) { std::vector<TermFieldHandle> handles; for (size_t i = 0; i < count; ++i) { handles.push_back(mdl.allocTermField(fieldId)); SimpleTermData term; term.addField(fieldId).setHandle(handles.back()); queryEnv.getTerms().push_back(term); } return handles; } feature_t getSubqueries(uint32_t docId) { return Utils::getScoreFeature(*rankProgram, docId); } void setSubqueries(TermFieldHandle handle, uint32_t docId, uint64_t subqueries) { match_data->resolveTermField(handle)->setSubqueries(docId, subqueries); } void setFooSubqueries(uint32_t i, uint32_t docId, uint64_t subqueries) { ASSERT_LESS(i, fooHandles.size()); setSubqueries(fooHandles[i], docId, subqueries); } void setBarSubqueries(uint32_t i, uint32_t docId, uint64_t subqueries) { ASSERT_LESS(i, barHandles.size()); setSubqueries(barHandles[i], docId, subqueries); } }; TEST_F("require that blueprint can be created from factory", BlueprintFactoryFixture) { Blueprint::SP bp = f.factory.createBlueprint("subqueries"); EXPECT_TRUE(bp.get() != 0); EXPECT_TRUE(dynamic_cast<SubqueriesBlueprint*>(bp.get()) != 0); } TEST_FFF("require that no features are dumped", SubqueriesBlueprint, IndexFixture, FeatureDumpFixture) { f1.visitDumpFeatures(f2.indexEnv, f3); } TEST_FF("require that setup can be done on index field", SubqueriesBlueprint, IndexFixture) { DummyDependencyHandler deps(f1); f1.setName(vespalib::make_string("%s(foo)", f1.getBaseName().c_str())); EXPECT_TRUE(((Blueprint&)f1).setup(f2.indexEnv, {"f
())); EXPECT_FALSE(((Blueprint&)f1).setup(f2.indexEnv, {"unknown"})); } TEST_F("require that not searching a field will give it 0 subqueries", RankFixture(0, 3)) { EXPECT_EQUAL(0, f1.getSubqueries(10)); } TEST_F("require that subqueries can be obtained", RankFixture(1, 0)) { f1.setFooSubqueries(0, 10, 0x1234); EXPECT_EQUAL(0x1234, f1.getSubqueries(10)); } TEST_F("require that msb subqueries can be obtained", RankFixture(1, 0, "subqueries(foo).msb")) { f1.setFooSubqueries(0, 10, 0x123412345678ULL); EXPECT_EQUAL(0x1234, f1.getSubqueries(10)); } TEST_F("require that multiple subqueries are accumulated", RankFixture(3, 0)) { f1.setFooSubqueries(0, 10, 1); f1.setFooSubqueries(1, 10, 2); f1.setFooSubqueries(2, 10, 4); EXPECT_EQUAL(7, f1.getSubqueries(10)); } TEST_F("require that stale subqueries are ignored", RankFixture(3, 0)) { f1.setFooSubqueries(0, 10, 1); f1.setFooSubqueries(1, 9, 2); f1.setFooSubqueries(2, 10, 4); EXPECT_EQUAL(5, f1.getSubqueries(10)); } TEST_F("require that subqueries from other fields are ignored", RankFixture(2, 2)) { f1.setFooSubqueries(0, 10, 1); f1.setFooSubqueries(1, 10, 2); f1.setBarSubqueries(0, 10, 4); f1.setBarSubqueries(1, 10, 8); EXPECT_EQUAL(3, f1.getSubqueries(10)); } TEST_MAIN() { TEST_RUN_ALL(); }
oo"})); } TEST_FF("require that setup can be done on attribute field", SubqueriesBlueprint, IndexFixture) { DummyDependencyHandler deps(f1); f1.setName(vespalib::make_string("%s(bar)", f1.getBaseName().c_str())); EXPECT_TRUE(((Blueprint&)f1).setup(f2.indexEnv, {"bar"})); } TEST_FF("require that setup fails for unknown field", SubqueriesBlueprint, IndexFixture) { DummyDependencyHandler deps(f1); f1.setName(vespalib::make_string("%s(unknown)", f1.getBaseName().c_str
random
[]
C++
Engine/src/CotQuaternion.cpp
TeamNut/CotEngine
d7f8c39715b8828eb8b4295c8ad844bdc7ab6849
#include "math/CotQuaternion.h" #include "math/CotVec3.h" #include "math/CotVec4.h" namespace Cot { Quaternion::Quaternion() : x(0.0f), y(0.0f), z(0.0f), w(1.0f) { } Quaternion::Quaternion(const float value) : x(value), y(value), z(value), w(value) { } Quaternion::Quaternion(const float xx, const float yy, const float zz, const float ww) : x(xx), y(yy), z(zz), w(ww) { } Quaternion::Quaternion(const float* array) : x(array[0]), y(array[1]), z(array[2]), w(array[3]) { } Quaternion::Quaternion(const Vec3& v, float ww) : x(v.x), y(v.y), z(v.z), w(ww) { } Quaternion::Quaternion(const Vec4& v) : x(v.x), y(v.y), z(v.z), w(v.w) { } Quaternion::Quaternion(const Quaternion& other) : x(other.x), y(other.y), z(other.z), w(other.w) { } Quaternion::Quaternion(const Quaternion&& other) : x(other.x), y(other.y), z(other.z), w(other.w) { } Quaternion::~Quaternion() { } void Quaternion::SetXYZ(const Vec3& v) { x = v.x; y = v.y; z = v.z; } Vec3 Quaternion::GetXYZ() const { return Vec3(x, y, z); } void Quaternion::SetEuler(const Vec3& euler) { Quaternion pitch(1.0f, 0.0f, 0.0f, euler.x); Quaternion yaw(0.0f, 1.0f, 1.0f, euler.y); Quaternion roll(0.0f, 0.0f, 1.0f, euler.z); (*this) = pitch * yaw * roll; } Vec3 Quaternion::GetEuler() const { return Vec3( atan2(2 * x * w - 2 * y * z, 1 - 2 * x * x - 2 * z * z), atan2(2 * y * w - 2 * x * z, 1 - 2 * y * y - 2 * z * z), asin(2 * x * y + 2 * z * w)); } float Quaternion::Length() const { return sqrt(x * x + y * y + z * z + w * w); } Vec3 Quaternion::GetAxis() const { float x = 1.0f - w * w; if (x <= 0.0f) { return Vec3::AxisX; } float x2 = x * x; Vec3 xyz = GetXYZ(); return GetXYZ() / x2; } const Quaternion Quaternion::operator+(const Quaternion& other) const { return Quaternion(x + other.x, y + other.y, z + other.z, w + other.w); } const Quaternion Quaternion::operator-(const Quaternion& other) const { return Quaternion(x - other.x, y - other.y, z - other.z, w - other.w); } const Quaternion Quaternion::operator*(const Quaternion& other) const { return Quaternion::Normalize( Quaternion ( ((x * other.x) + (x * other.w)) + ((y * other.z) - (z * other.y)), ((x * other.y) + (y * other.w)) + ((z * other.x) - (x * other.z)), ((x * other.z) + (z * other.w)) + ((x * other.y) - (y * other.x)), ((w * other.w) + (x * other.x)) + ((y * other.y) - (z * other.z)) )); } const Quaternion Quaternion::operator/(const Quaternion& other) const { COT_ASSERT(other.x <= 0.0f, "Division by 0"); COT_ASSERT(other.y <= 0.0f, "Division by 0"); COT_ASSERT(other.z <= 0.0f, "Division by 0"); COT_ASSERT(other.w <= 0.0f, "Division by 0"); return Quaternion(x / other.x, y / other.y, z / other.z, w / other.w); } const Quaternion Quaternion::operator+(const float value) const { return Quaternion(x + value, y + value, z + value, w + value); } const Quaternion Quaternion::operator-(const float value) const { return Quaternion(x - value, y - value, z - value, w - value); } const Quaternion Quaternion::operator*(const float value) const { return Quaternion(x * value, y * value, z * value, w * value); } const Quaternion Quaternion::operator/(const float value) const { COT_ASSERT(value <= 0.0f, "Division by 0"); return Quaternion(x / value, y / value, z / value, w / value); } Quaternion& Quaternion::operator+=(const Quaternion& other) { x += other.x; y += other.y; z += other.z; w += other.w; return *this; } Quaternion& Quaternion::operator-=(const Quaternion& other) { x -= other.x; y -= other.y; z -= other.z; w -= other.w; return *this; } Quaternion& Quaternion::operator*=(const Quaternion& other) { (*this) = (*this) * other; return *this; } Quaternion& Quaternion::operator/=(const Quaternion& other) { COT_ASSERT(other.x <= 0.0f, "Division by 0"); COT_ASSERT(other.y <= 0.0f, "Division by 0"); COT_ASSERT(other.z <= 0.0f, "Division by 0"); COT_ASSERT(other.w <= 0.0f, "Division by 0"); x /= other.x; y /= other.y; z /= other.z; w /= other.w; return *this; } Quaternion& Quaternion::operator=(const Quaternion& other) { x = other.x; y = other.y; z = other.z; w = other.w; return *this; } Quaternion& Quaternion::operator+=(const float value) { x += value; y += value; z += value; w += value; return *this; } Quaternion& Quaternion::operator-=(const float value) { x -= value; y -= value; z -= value; w -= value; return *this; } Quaternion& Quaternion::operator*=(const float value) { x *= value; y *= value; z *= value; w *= value; return *this; } Quaternion& Quaternion::operator/=(const float value) { COT_ASSERT(value <= 0.0f, "Division by 0"); x /= value; y /= value; z /= value; w /= value; return *this; } Quaternion& Quaternion::operator=(const float value) { x = value; y = value; z = value; w = value; return *this; } const Quaternion Quaternion::operator-() const { return Quaternion(-x, -y, -z, -w); } bool Quaternion::operator<(const Quaternion& other) const { return (x < other.x && y < other.y && z < other.z && w < other.w); } bool Quaternion::operator<=(const Quaternion& other) const { return (x <= other.x && y <= other.y && z <= other.z && w <= other.w); } bool Quaternion::operator>(const Quaternion& other) const { return (x > other.x && y > other.y && z > other.z && w > other.w); } bool Quaternion::operator>=(const Quaternion& other) const { return (x >= other.x && y >= other.y && z >= other.z && w >= other.w); } bool Quaternion::operator==(const Quaternion& other) const { return (x == other.x && y == other.y && z == other.z && w == other.w); } bool Quaternion::operator!=(const Quaternion& other) const { return (x != other.x || y != other.y || z != other.z, w != other.w); } bool Quaternion::IsZero() const { return (x == 0.0f && y == 0.0f && z == 0.0f && w == 0.0f); } bool Quaternion::IsOne() const { return (x == 1.0f && y == 1.0f && z == 1.0f && w == 1.0f); } const Vec3 Quaternion::Rotate(const Quaternion& quaternion, const Vec3& axis) { float tempX, tempY, tempZ, tempW; tempX = (((quaternion.w * axis.x) + (quaternion.y * axis.z)) - (quaternion.z * axis.y)); tempY = (((quaternion.w * axis.y) + (quaternion.z * axis.x)) - (quaternion.x * axis.z)); tempZ = (((quaternion.w * axis.z) + (quaternion.x * axis.y)) - (quaternion.y * axis.x)); tempW = (((quaternion.x * axis.x) + (quaternion.y * axis.y)) + (quaternion.z * axis.z)); return Vec3( ((((tempW * quaternion.x) + (tempX * quaternion.w)) - (tempY * quaternion.z)) + (tempZ * quaternion.y)), ((((tempW * quaternion.y) + (tempY * quaternion.w)) - (tempZ * quaternion.x)) + (tempX * quaternion.z)), ((((tempW * quaternion.z) + (tempZ * quaternion.w)) - (tempX * quaternion.y)) + (tempY * quaternion.x)) ); } const Quaternion Quaternion::Rotation(const Vec3& axis1, const Vec3& axis2) { float cosHalfAngle, recipCosHalfAngle; cosHalfAngle = sqrt((1.0f * (1.0f + axis1.Dot(axis2)))); recipCosHalfAngle = (1.0f / cosHalfAngle); return Quaternion ( (Vec3::Cross(axis1, axis2) * recipCosHalfAngle), (cosHalfAngle * 0.5f) ); } const Quaternion Quaternion::Rotation(const float r, const Vec3 axis) { float angle = r * 0.5f; return Quaternion( (axis * sin(r)), cos(r) ); } const Quaternion Quaternion::RotationX(const float r) { float angle = r * 0.5f; return Quaternion(sin(angle), 0.0f, 0.0f, cos(angle)); } const Quaternion Quaternion::RotationY(const float r) { float angle = r * 0.5f; return Quaternion(0.0f, sin(angle), 0.0f, cos(angle)); } const Quaternion Quaternion::RotationZ(const float r) { float angle = r * 0.5f; return Quaternion(0.0f, 0.0f, sin(angle), cos(angle)); } Quaternion Quaternion::Normalize() { float length = sqrt(x * x + y * y + z * z + w * w); return Quaternion(x / length, y / length, z / length, w / length); } Quaternion Quaternion::Normalize(const Quaternion& other) { float length = other.Length(); return Quaternion(other.x / length, other.y / length, other.z / length, other.w / length); } float Quaternion::Dot(const Quaternion& other) const { return x * other.x + y * other.y + z * other.z + w * other.w; } float Quaternion::Dot(const Quaternion& other1, const Quaternion& other2) { return other1.x * other2.x + other1.y * other2.y + other1.z + other2.z + other1.w * other2.w; } Quaternion Quaternion::Conjugate() const { return Quaternion(-x, -y, -z, w); } const Quaternion Quaternion::Zero(0.0f, 0.0f, 0.0f, 0.0f); const Quaternion Quaternion::Identity(0.0f, 0.0f, 0.0f, 1.0f); }
#include "math/CotQuaternion.h" #include "math/CotVec3.h" #include "math/CotVec4.h" namespace Cot { Quaternion::Quaternion() : x(0.0f), y(0.0f), z(0.0f), w(1.0f) { } Quaternion::Quaternion(const float value) : x(value), y(value), z(value), w(value) { } Quaternion::Quaternion(const float xx, const float yy, const float zz, const float ww) : x(xx), y(yy), z(zz), w(ww) { } Quaternion::Quaternion(const float* array) : x(array[0]), y(array[1]), z(array[2]), w(array[3]) { } Quaternion::Quaternion(const Vec3& v, float ww) : x(v.x), y(v.y), z(v.z), w(ww) { } Quaternion::Quaternion(const Vec4& v) : x(v.x), y(v.y), z(v.z), w(v.w) { } Quaternion::Quaternion(const Quaternion& other) : x(other.x), y(other.y), z(other.z), w(other.w) { } Quaternion::Quaternion(const Quaternion&& other) : x(other.x), y(other.y), z(other.z), w(other.w) { } Quaternion::~Quaternion() { } void Quaternion::SetXYZ(const Vec3& v) { x = v.x; y = v.y; z = v.z; } Vec3 Quaternion::GetXYZ() const { return Vec3(x, y, z); } void Quaternion::SetEuler(const Vec3& euler) { Quaternion pitch(1.0f, 0.0f, 0.0f, euler.x); Quaternion yaw(0.0f, 1.0f, 1.0f, euler.y); Quaternion roll(0.0f, 0.0f, 1.0f, euler.z); (*this) = pitch * yaw * roll; } Vec3 Quaternion::GetEuler() const { return Vec3( atan2(2 * x * w - 2 * y * z, 1 - 2 * x * x - 2 * z * z), atan2(2 * y * w - 2 * x * z, 1 - 2 * y * y - 2 * z * z), asin(2 * x * y + 2 * z * w)); } float Quaternion::Length() const { return sqrt(x * x + y * y + z * z + w * w); } Vec3 Quaternion::GetAxis() const { float x = 1.0f - w * w; if (x <= 0.0f) { return Vec3::AxisX; } float x2 = x * x; Vec3 xyz = GetXYZ(); return GetXYZ() / x2; } const Quaternion Quaternion::operator+(const Quaternion& other) const { return Quaternion(x + other.x, y + other.y, z + other.z, w + other.w); } const Quaternion Quaternion::operator-(const Quaternion& other) const { return Quaternion(x - other.x, y - other.y, z - other.z, w - other.w); } const Quaternion Quaternion::operator*(const Quaternion& other) const { return Quaternion::Normalize( Quaternion ( ((x * other.x) + (x * other.w)) + ((y * other.z) - (z * other.y)), ((x * other.y) + (y * other.w)) + ((z * other.x) - (x * other.z)), ((x * other.z) + (z * other.w)) + ((x * other.y) - (y * other.x)), ((w * other.w) + (x * other.x)) + ((y * other.y) - (z * other.z)) )); } const Quaternion Quaternion::operator/(const Quaternion& other) const { COT_ASSERT(other.x <= 0.0f, "Division by 0"); COT_ASSERT(other.y <= 0.0f, "Division by 0"); COT_ASSERT(other.z <= 0.0f, "Division by 0"); COT_ASSERT(other.w <= 0.0f, "Division by 0"); return Quaternion(x / other.x, y / other.y, z / other.z, w / other.w); } const Quaternion Quaternion::operator+(const float value) const { return Quaternion(x + value, y + value, z + value, w + value); } const Quaternion Quaternion::operator-(const float value) const { return Quaternion(x - value, y - value, z - value, w - value); } const Quaternion Quaternion::operator*(const float value) const { return Quaternion(x * value, y * value, z * value, w * value); } const Quaternion Quaternion::operator/(const float value) const { COT_ASSERT(value <= 0.0f, "Division by 0"); return Quaternion(x / value, y / value, z / value, w / value); } Quaternion& Quaternion::operator+=(const Quaternion& other) { x += other.x; y += other.y; z += other.z; w += other.w; return *this; } Quaternion& Quaternion::operator-=(const Quaternion& other) { x -= other.x; y -= other.y; z -= other.z; w -= other.w; return *this; } Quaternion& Quaternion::operator*=(const Quaternion& other) { (*this) = (*this) * other; return *this; } Quaternion& Quaternion::operator/=(const Quaternion& other) { COT_ASSERT(other.x <= 0.0f, "Division by 0"); COT_ASSERT(other.y <= 0.0f, "Division by 0"); COT_ASSERT(other.z <= 0.0f, "Division by 0"); COT_ASSERT(other.w <= 0.0f, "Division by 0"); x /= other.x; y /= other.y; z /= other.z; w /= other.w; return *this; } Quaternion& Quaternion::operator=(const Quaternion& other) { x = other.x; y = other.y; z = other.z; w = other.w; return *this; }
Quaternion& Quaternion::operator-=(const float value) { x -= value; y -= value; z -= value; w -= value; return *this; } Quaternion& Quaternion::operator*=(const float value) { x *= value; y *= value; z *= value; w *= value; return *this; } Quaternion& Quaternion::operator/=(const float value) { COT_ASSERT(value <= 0.0f, "Division by 0"); x /= value; y /= value; z /= value; w /= value; return *this; } Quaternion& Quaternion::operator=(const float value) { x = value; y = value; z = value; w = value; return *this; } const Quaternion Quaternion::operator-() const { return Quaternion(-x, -y, -z, -w); } bool Quaternion::operator<(const Quaternion& other) const { return (x < other.x && y < other.y && z < other.z && w < other.w); } bool Quaternion::operator<=(const Quaternion& other) const { return (x <= other.x && y <= other.y && z <= other.z && w <= other.w); } bool Quaternion::operator>(const Quaternion& other) const { return (x > other.x && y > other.y && z > other.z && w > other.w); } bool Quaternion::operator>=(const Quaternion& other) const { return (x >= other.x && y >= other.y && z >= other.z && w >= other.w); } bool Quaternion::operator==(const Quaternion& other) const { return (x == other.x && y == other.y && z == other.z && w == other.w); } bool Quaternion::operator!=(const Quaternion& other) const { return (x != other.x || y != other.y || z != other.z, w != other.w); } bool Quaternion::IsZero() const { return (x == 0.0f && y == 0.0f && z == 0.0f && w == 0.0f); } bool Quaternion::IsOne() const { return (x == 1.0f && y == 1.0f && z == 1.0f && w == 1.0f); } const Vec3 Quaternion::Rotate(const Quaternion& quaternion, const Vec3& axis) { float tempX, tempY, tempZ, tempW; tempX = (((quaternion.w * axis.x) + (quaternion.y * axis.z)) - (quaternion.z * axis.y)); tempY = (((quaternion.w * axis.y) + (quaternion.z * axis.x)) - (quaternion.x * axis.z)); tempZ = (((quaternion.w * axis.z) + (quaternion.x * axis.y)) - (quaternion.y * axis.x)); tempW = (((quaternion.x * axis.x) + (quaternion.y * axis.y)) + (quaternion.z * axis.z)); return Vec3( ((((tempW * quaternion.x) + (tempX * quaternion.w)) - (tempY * quaternion.z)) + (tempZ * quaternion.y)), ((((tempW * quaternion.y) + (tempY * quaternion.w)) - (tempZ * quaternion.x)) + (tempX * quaternion.z)), ((((tempW * quaternion.z) + (tempZ * quaternion.w)) - (tempX * quaternion.y)) + (tempY * quaternion.x)) ); } const Quaternion Quaternion::Rotation(const Vec3& axis1, const Vec3& axis2) { float cosHalfAngle, recipCosHalfAngle; cosHalfAngle = sqrt((1.0f * (1.0f + axis1.Dot(axis2)))); recipCosHalfAngle = (1.0f / cosHalfAngle); return Quaternion ( (Vec3::Cross(axis1, axis2) * recipCosHalfAngle), (cosHalfAngle * 0.5f) ); } const Quaternion Quaternion::Rotation(const float r, const Vec3 axis) { float angle = r * 0.5f; return Quaternion( (axis * sin(r)), cos(r) ); } const Quaternion Quaternion::RotationX(const float r) { float angle = r * 0.5f; return Quaternion(sin(angle), 0.0f, 0.0f, cos(angle)); } const Quaternion Quaternion::RotationY(const float r) { float angle = r * 0.5f; return Quaternion(0.0f, sin(angle), 0.0f, cos(angle)); } const Quaternion Quaternion::RotationZ(const float r) { float angle = r * 0.5f; return Quaternion(0.0f, 0.0f, sin(angle), cos(angle)); } Quaternion Quaternion::Normalize() { float length = sqrt(x * x + y * y + z * z + w * w); return Quaternion(x / length, y / length, z / length, w / length); } Quaternion Quaternion::Normalize(const Quaternion& other) { float length = other.Length(); return Quaternion(other.x / length, other.y / length, other.z / length, other.w / length); } float Quaternion::Dot(const Quaternion& other) const { return x * other.x + y * other.y + z * other.z + w * other.w; } float Quaternion::Dot(const Quaternion& other1, const Quaternion& other2) { return other1.x * other2.x + other1.y * other2.y + other1.z + other2.z + other1.w * other2.w; } Quaternion Quaternion::Conjugate() const { return Quaternion(-x, -y, -z, w); } const Quaternion Quaternion::Zero(0.0f, 0.0f, 0.0f, 0.0f); const Quaternion Quaternion::Identity(0.0f, 0.0f, 0.0f, 1.0f); }
Quaternion& Quaternion::operator+=(const float value) { x += value; y += value; z += value; w += value; return *this; }
function_block-full_function
[ { "content": "\tclass Vec4;\n", "file_path": "Engine/include/math/CotQuaternion.h", "rank": 0, "score": 178629.8132119183 }, { "content": "\tclass Vec3;\n", "file_path": "Engine/include/math/CotQuaternion.h", "rank": 1, "score": 178621.05006660835 }, { "content": "\tclass Vec3;\n", "file_path": "Engine/include/math/CotVec4.h", "rank": 2, "score": 178615.00717985723 }, { "content": "\tclass COT_API Quaternion final\n\n\t{\n\n\tpublic:\n\n\t\tunion\n\n\t\t{\n\n\t\t\tstruct\n\n\t\t\t{\n\n\t\t\t\tfloat x, y, z, w;\n\n\t\t\t};\n\n\t\t\tfloat ToArray[4];\n\n\t\t};\n\n\n\n\t\tQuaternion();\n\n\t\tQuaternion(const float value);\n\n\t\tQuaternion(const float xx, const float yy, const float zz, const float ww);\n\n\t\tQuaternion(const float* array);\n\n\t\tQuaternion(const Vec3& v, float ww);\n\n\t\tQuaternion(const Vec4& v);\n\n\t\tQuaternion(const Quaternion& other);\n\n\t\tQuaternion(const Quaternion&& other);\n", "file_path": "Engine/include/math/CotQuaternion.h", "rank": 3, "score": 139933.4873862201 }, { "content": "\tclass COT_API Vec4 final\n\n\t{\n\n\tpublic:\n\n\t\tunion\n\n\t\t{\n\n\t\t\tstruct\n\n\t\t\t{\n\n\t\t\t\tfloat x, y, z, w;\n\n\t\t\t};\n\n\t\t\tfloat ToArray[4];\n\n\t\t};\n\n\n\n\t\tVec4();\n\n\t\tVec4(const float value);\n\n\t\tVec4(const float xx, const float yy);\n\n\t\tVec4(const Vec2& other);\n\n\t\tVec4(const float xx, const float yy, const float zz);\n\n\t\tVec4(const Vec3& other);\n\n\t\tVec4(const float xx, const float yy, const float zz, const float ww);\n\n\t\tVec4(const float* array);\n", "file_path": "Engine/include/math/CotVec4.h", "rank": 4, "score": 139922.6252362061 }, { "content": "\tclass COT_API Vec3 final\n\n\t{\n\n\tpublic:\n\n\t\tunion\n\n\t\t{\n\n\t\t\tstruct\n\n\t\t\t{\n\n\t\t\t\tfloat x, y, z;\n\n\t\t\t};\n\n\t\t\tfloat ToArray[3];\n\n\t\t};\n\n\n\n\t\tVec3();\n\n\t\tVec3(const float value);\n\n\t\tVec3(const float xx, const float yy);\n\n\t\tVec3(const Vec2& other);\n\n\t\tVec3(const float xx, const float yy, const float zz);\n\n\t\tVec3(const float* array);\n\n\t\tVec3(const Vec3& other);\n\n\t\tVec3(const Vec3&& other);\n", "file_path": "Engine/include/math/CotVec3.h", "rank": 5, "score": 139913.6793728065 }, { "content": "\tclass Vec3;\n", "file_path": "Engine/include/math/CotMat4.h", "rank": 6, "score": 137059.68324513195 }, { "content": " LONG x2;\n", "file_path": "Engine/thirdparty/directx/include/d3d9types.h", "rank": 7, "score": 127452.1586376348 }, { "content": " FLOAT V; // Barycentric Hit Coordinates\n", "file_path": "Engine/thirdparty/directx/include/d3dx9mesh.h", "rank": 8, "score": 127446.72211593491 }, { "content": " INT Pitch;\n", "file_path": "Engine/thirdparty/directx/include/d3d9types.h", "rank": 9, "score": 127441.62357961375 }, { "content": " SHORT X, Y; // Top-left coordinates of the rect in the destination surface\n", "file_path": "Engine/thirdparty/directx/include/d3d9types.h", "rank": 10, "score": 127419.73172161318 }, { "content": " long W;\n", "file_path": "Engine/thirdparty/libvorbis/include/vorbis/codec.h", "rank": 11, "score": 124353.67243869304 }, { "content": "\t\t~Quaternion();\n\n\n\n\t\tvoid SetXYZ(const Vec3& v);\n\n\t\tVec3 GetXYZ() const;\n\n\n\n\t\tvoid SetEuler(const Vec3& euler);\n\n\t\tVec3 GetEuler() const;\n\n\n\n\t\tfloat Length() const;\n\n\t\tVec3 GetAxis() const;\n\n\n\n\t\tconst Quaternion operator+(const Quaternion& other) const;\n\n\t\tconst Quaternion operator-(const Quaternion& other) const;\n\n\t\tconst Quaternion operator*(const Quaternion& other) const;\n\n\t\tconst Quaternion operator/(const Quaternion& other) const;\n\n\n\n\t\tconst Quaternion operator+(const float value) const;\n\n\t\tconst Quaternion operator-(const float value) const;\n\n\t\tconst Quaternion operator*(const float value) const;\n\n\t\tconst Quaternion operator/(const float value) const;\n", "file_path": "Engine/include/math/CotQuaternion.h", "rank": 12, "score": 118949.18311877771 }, { "content": "\t\tbool operator==(const Quaternion& other) const;\n\n\t\tbool operator!=(const Quaternion& other) const;\n\n\n\n\t\tbool IsZero() const;\n\n\t\tbool IsOne() const;\n\n\n\n\t\tstatic const Vec3 Rotate(const Quaternion& quaternion, const Vec3& axis);\n\n\n\n\t\tstatic const Quaternion Rotation(const Vec3& axis1, const Vec3& axis2);\n\n\t\tstatic const Quaternion Rotation(const float r, const Vec3 axis);\n\n\n\n\t\tstatic const Quaternion RotationX(const float r);\n\n\t\tstatic const Quaternion RotationY(const float r);\n\n\t\tstatic const Quaternion RotationZ(const float r);\n\n\n\n\t\tQuaternion Normalize();\n\n\t\tstatic Quaternion Normalize(const Quaternion& other);\n\n\n\n\t\tfloat Dot(const Quaternion& other) const;\n\n\t\tstatic float Dot(const Quaternion& other1, const Quaternion& other2);\n\n\n\n\t\tQuaternion Conjugate() const;\n\n\n\n\t\tstatic const Quaternion Zero;\n\n\t\tstatic const Quaternion Identity;\n\n\t};\n\n}", "file_path": "Engine/include/math/CotQuaternion.h", "rank": 13, "score": 118936.54392515883 }, { "content": "\n\n\t\tQuaternion& operator+=(const Quaternion& other);\n\n\t\tQuaternion& operator-=(const Quaternion& other);\n\n\t\tQuaternion& operator*=(const Quaternion& other);\n\n\t\tQuaternion& operator/=(const Quaternion& other);\n\n\t\tQuaternion& operator=(const Quaternion& other);\n\n\n\n\t\tQuaternion& operator+=(const float value);\n\n\t\tQuaternion& operator-=(const float value);\n\n\t\tQuaternion& operator*=(const float value);\n\n\t\tQuaternion& operator/=(const float value);\n\n\t\tQuaternion& operator=(const float value);\n\n\n\n\t\tconst Quaternion operator-() const;\n\n\n\n\t\tbool operator<(const Quaternion& other) const;\n\n\t\tbool operator<=(const Quaternion& other) const;\n\n\t\tbool operator>(const Quaternion& other) const;\n\n\t\tbool operator>=(const Quaternion& other) const;\n\n\n", "file_path": "Engine/include/math/CotQuaternion.h", "rank": 14, "score": 118933.27317433007 }, { "content": "#pragma once\n\n\n\n#include \"base/CotRule.h\"\n\n\n\nnamespace Cot \n\n{\n", "file_path": "Engine/include/math/CotQuaternion.h", "rank": 15, "score": 118931.62037861774 }, { "content": "\t\tVec4& operator+=(const float value);\n\n\t\tVec4& operator-=(const float value);\n\n\t\tVec4& operator*=(const float value);\n\n\t\tVec4& operator/=(const float value);\n\n\t\tVec4& operator=(const float value);\n\n\n\n\t\tconst Vec4 operator-() const;\n\n\n\n\t\tbool operator<(const Vec4& other) const;\n\n\t\tbool operator<=(const Vec4& other) const;\n\n\t\tbool operator>(const Vec4& other) const;\n\n\t\tbool operator>=(const Vec4& other) const;\n\n\n\n\t\tbool operator==(const Vec4& other) const;\n\n\t\tbool operator!=(const Vec4& other) const;\n\n\n\n\t\tbool IsZero() const;\n\n\t\tbool IsOne() const;\n\n\n\n\t\tVec4 Normalize();\n", "file_path": "Engine/include/math/CotVec4.h", "rank": 16, "score": 118926.86689404667 }, { "content": "\t\tVec4(const Vec4& other);\n\n\t\tVec4(const Vec4&& other);\n\n\t\t~Vec4();\n\n\n\n\t\tconst Vec4 operator+(const Vec4& other) const;\n\n\t\tconst Vec4 operator-(const Vec4& other) const;\n\n\t\tconst Vec4 operator*(const Vec4& other) const;\n\n\t\tconst Vec4 operator/(const Vec4& other) const;\n\n\n\n\t\tconst Vec4 operator+(const float value) const;\n\n\t\tconst Vec4 operator-(const float value) const;\n\n\t\tconst Vec4 operator*(const float value) const;\n\n\t\tconst Vec4 operator/(const float value) const;\n\n\n\n\t\tVec4& operator+=(const Vec4& other);\n\n\t\tVec4& operator-=(const Vec4& other);\n\n\t\tVec4& operator*=(const Vec4& other);\n\n\t\tVec4& operator/=(const Vec4& other);\n\n\t\tVec4& operator=(const Vec4& other);\n\n\n", "file_path": "Engine/include/math/CotVec4.h", "rank": 17, "score": 118926.53946229967 }, { "content": "#pragma once\n\n\n\n#include \"base/CotRule.h\"\n\n\n\nnamespace Cot\n\n{\n", "file_path": "Engine/include/math/CotVec4.h", "rank": 18, "score": 118925.32484451986 }, { "content": "\t\tstatic Vec4 Normalize(const Vec4& other);\n\n\n\n\t\tfloat Length() const;\n\n\t\tfloat Distance(const Vec4& other) const;\n\n\t\tstatic float Distance(const Vec4& other1, const Vec4& other2);\n\n\n\n\t\tfloat Dot(const Vec4& other) const;\n\n\t\tstatic float Dot(const Vec4& other1, const Vec4& other2);\n\n\n\n\t\tstatic const Vec4 Zero;\n\n\t\tstatic const Vec4 One;\n\n\t};\n\n}", "file_path": "Engine/include/math/CotVec4.h", "rank": 19, "score": 118922.34393859975 }, { "content": "\t\t~Vec3();\n\n\n\n\t\tconst Vec3 operator+(const Vec3& other) const;\n\n\t\tconst Vec3 operator-(const Vec3& other) const;\n\n\t\tconst Vec3 operator*(const Vec3& other) const;\n\n\t\tconst Vec3 operator/(const Vec3& other) const;\n\n\n\n\t\tconst Vec3 operator+(const float value) const;\n\n\t\tconst Vec3 operator-(const float value) const;\n\n\t\tconst Vec3 operator*(const float value) const;\n\n\t\tconst Vec3 operator/(const float value) const;\n\n\n\n\t\tVec3& operator+=(const Vec3& other);\n\n\t\tVec3& operator-=(const Vec3& other);\n\n\t\tVec3& operator*=(const Vec3& other);\n\n\t\tVec3& operator/=(const Vec3& other);\n\n\t\tVec3& operator=(const Vec3& other);\n\n\n\n\t\tVec3& operator+=(const float value);\n\n\t\tVec3& operator-=(const float value);\n", "file_path": "Engine/include/math/CotVec3.h", "rank": 20, "score": 118921.09965309182 }, { "content": "\t\tVec3& operator*=(const float value);\n\n\t\tVec3& operator/=(const float value);\n\n\t\tVec3& operator=(const float value);\n\n\n\n\t\tconst Vec3 operator*(const Mat4& mat) const;\n\n\t\tVec3& operator*=(const Mat4& mat);\n\n\n\n\t\tconst Vec3 operator-() const;\n\n\n\n\t\tbool operator<(const Vec3& other) const;\n\n\t\tbool operator<=(const Vec3& other) const;\n\n\t\tbool operator>(const Vec3& other) const;\n\n\t\tbool operator>=(const Vec3& other) const;\n\n\n\n\t\tbool operator==(const Vec3& other) const;\n\n\t\tbool operator!=(const Vec3& other) const;\n\n\n\n\t\tbool IsZero() const;\n\n\t\tbool IsOne() const;\n\n\n", "file_path": "Engine/include/math/CotVec3.h", "rank": 21, "score": 118919.0888960675 }, { "content": "\t\tVec3 Normalize();\n\n\t\tstatic Vec3 Normalize(const Vec3& other);\n\n\n\n\t\tfloat Length() const;\n\n\t\tfloat Distance(const Vec3& other) const;\n\n\t\tstatic float Distance(const Vec3& other1, const Vec3& other2);\n\n\n\n\t\tfloat Dot(const Vec3& other) const;\n\n\t\tstatic float Dot(const Vec3& other1, const Vec3& other2);\n\n\n\n\t\tVec3 Cross(const Vec3& other) const;\n\n\t\tstatic Vec3 Cross(const Vec3& other1, const Vec3& other2);\n\n\n\n\t\tstatic const Vec3 Zero;\n\n\t\tstatic const Vec3 One;\n\n\n\n\t\tstatic const Vec3 Front;\n\n\t\tstatic const Vec3 Back;\n\n\t\tstatic const Vec3 Up;\n\n\t\tstatic const Vec3 Down;\n\n\t\tstatic const Vec3 Left;\n\n\t\tstatic const Vec3 Right;\n\n\n\n\t\tstatic const Vec3 AxisX;\n\n\t\tstatic const Vec3 AxisY;\n\n\t\tstatic const Vec3 AxisZ;\n\n\t};\n\n}", "file_path": "Engine/include/math/CotVec3.h", "rank": 22, "score": 118919.03005153978 }, { "content": "#pragma once\n\n\n\n#include \"base/CotRule.h\"\n\n\n\nnamespace Cot \n\n{\n", "file_path": "Engine/include/math/CotVec3.h", "rank": 23, "score": 118919.02303443008 }, { "content": "\tclass Vec2;\n", "file_path": "Engine/include/math/CotVec4.h", "rank": 24, "score": 114138.55982552955 }, { "content": "\tclass Vec2;\n", "file_path": "Engine/include/math/CotVec3.h", "rank": 25, "score": 114132.51091464961 }, { "content": "\tclass Mat4;\n", "file_path": "Engine/include/math/CotVec3.h", "rank": 26, "score": 114132.51091464961 }, { "content": "namespace Cot\n\n{\n\n\tCOT_API inline const char* GetVersion()\n\n\t{\n\n\t\treturn \"CotEngine v1.5.7\";\n\n\t}\n", "file_path": "Engine/include/CotEngine.h", "rank": 27, "score": 111556.95664367868 }, { "content": "\t\tclass Vec4 GetColumn(int index);\n\n\n\n\t\tstatic Mat4 Multiply(const Mat4& mat1, const Mat4& mat2);\n\n\n\n\t\tstatic Mat4 Orthographic(float left, float right, float bottom, float top, float near, float far);\n\n\t\tstatic Mat4 Perspective(float fov, float aspectRatio, float near, float far);\n\n\t\tstatic Mat4 LookAt(const class Vec3& eye, const Vec3& center, const Vec3& up);\n\n\n\n\t\tstatic Mat4 Translate(const Vec3& position);\n\n\t\tstatic Mat4 Rotate(float angle, const Vec3& axis);\n\n\t\tstatic Mat4 Rotate(const class Quaternion& quaternion);\n\n\t\tstatic Mat4 Scale(const Vec3& scale);\n\n\t\tstatic Mat4 Transpose(const Mat4& mat);\n\n\n\n\t\tstatic const Mat4 Zero;\n\n\t\tstatic const Mat4 Identity;\n\n\n\n\t};\n\n}", "file_path": "Engine/include/math/CotMat4.h", "rank": 28, "score": 110604.494833343 }, { "content": "namespace Cot\n\n{\n\n\tComponent(Button, COT_API)\n\n\t{\n\n\t\tCOT_COMPONENT(Button);\n\n\tprivate:\n\n\t\tenum class Type { Color, Image, };\n\n\t\tType\t\t\t\t_buttonType;\n\n\t\tSpriteRenderer*\t\t_spriteRenderer;\n\n\t\tTexture*\t\t\t_originImage;\n\n\t\tTexture*\t\t\t_clickImage;\n\n\t\tColor\t\t\t\t_originColor;\n\n\t\tColor\t\t\t\t_clickColor;\n\n\t\tbool\t\t\t\t_down;\n\n\n\n\t\tCallBack<void()>\t_buttonDown;\n\n\t\tCallBack<void()>\t_buttonUp;\n\n\t\tCallBack<void()>\t_buttonClick;\n\n\n\n\tpublic:\n\n\t\t// Image\n\n\t\tButton* Init(const string& clickImage);\n\n\t\tButton* Init(const Color& clickColor);\n\n\n\n\t\tvoid Reset() override;\n\n\t\tvoid Awake() override;\n\n\t\tvoid Update(Time& time) override;\n\n\n\n\t\tvoid AddButtonDown(const Function<void()>& function);\n\n\t\tvoid AddButtonUp(const Function<void()>& function);\n\n\t\tvoid AddButtonClick(const Function<void()>& function);\n\n\n\n\t};\n", "file_path": "Engine/include/component/CotButton.h", "rank": 29, "score": 109676.05568774493 }, { "content": "namespace Cot\n\n{\n\n\tCOT_API inline bool IntersectRect(Rect& rect1, Rect& rect2);\n\n\tCOT_API inline bool IntersectCircle(Circle& circle1, Circle& circle2);\n\n\n\n\tCOT_API inline bool IntersectRectCircle(Rect& rect, Circle& circle);\n\n\n\n\tCOT_API inline bool PointInRect(Rect& rect, Vec2& position);\n", "file_path": "Engine/include/physics/CotPhysics.h", "rank": 30, "score": 109676.05568774493 }, { "content": "namespace Cot\n\n{\n\n\tCOT_API void RegisteInputDevice(InputDevice* device);\n\n\tCOT_API void DestroyInputDevice();\n\n\n\n\tCOT_API bool IsKeyDown(KeyCode code);\n\n\tCOT_API bool IsKeyStay(KeyCode code);\n\n\tCOT_API bool IsKeyUp(KeyCode code);\n\n\n\n\tCOT_API bool IsMouseDown(MouseButton button);\n\n\tCOT_API bool IsMouseStay(MouseButton button);\n\n\tCOT_API bool IsMouseUp(MouseButton button);\n\n\n\n\tCOT_API Vec2 GetMousePosition();\n\n\tCOT_API float GetMouseWheel();\n", "file_path": "Engine/include/input/CotInput.h", "rank": 31, "score": 109676.05568774493 }, { "content": "namespace Cot\n\n{\n\n\tComponent(ICollider)\n\n\t{\n\n\t\tCOT_COMPONENT(ICollider);\n\n\tpublic:\n\n\t\tenum class Type\n\n\t\t{\n\n\t\t\tBox,\n\n\t\t\tCircle,\n\n\t\t\tLine,\n\n\t\t};\n\n\n\n\tprotected:\n\n\t\tType\t_collType;\n\n\t\tbool\t_enter = false;\n\n\t\tEntity* _target;\n\n\n\n\tpublic:\n\n\t\tvoid SetEnter(bool enter) { _enter = enter; }\n\n\t\tbool IsEnter() { return _enter; }\n\n\n\n\t\tType GetCollType() { return _collType; }\n\n\n\n\t\tvoid SetTarget(Entity* target) { _target = target; }\n\n\t\tEntity* GetTarget() { return _target; }\n\n\n\n\t};\n", "file_path": "Engine/include/component/CotICollider.h", "rank": 32, "score": 109676.05568774493 }, { "content": "namespace Cot\n\n{\n\n\tCOT_API inline D3DXCOLOR\t\tToDxMath(const Color32& color);\n\n\tCOT_API inline D3DXMATRIX\t\tToDxMath(const Mat4& mat);\n\n\tCOT_API inline D3DXVECTOR2\t\tToDxMath(const Vec2& vec);\n\n\tCOT_API inline D3DXVECTOR3\t\tToDxMath(const Vec3& vec);\n\n\tCOT_API inline D3DXVECTOR4\t\tToDxMath(const Vec4& vec);\n\n\tCOT_API inline D3DXQUATERNION\tToDxMath(const Quaternion& quternion);\n\n\tCOT_API inline RECT\t\t\t\tToDxMath(Rect& rect);\n", "file_path": "Engine/include/math/CotGL2DX.h", "rank": 33, "score": 109676.05568774493 }, { "content": "namespace Cot\n\n{\n\n\tComponentExt(FontRenderer, IRenderComponent, COT_API)\n\n\t{\n\n\t\tCOT_COMPONENT(FontRenderer);\n\n\tprivate:\n\n\t\tFont*\t_font;\n\n\t\tstring\t_text;\n\n\n\n\tpublic:\n\n\t\tFontRenderer* Init(const string& font, const string& text, int fontSize);\n\n\n\n\t\tvoid Reset() override;\n\n\t\tvoid Update(Time& time) override;\n\n\t\tvoid OnDestroy() override;\n\n\n\n\t\tvoid SetFont(Font* font);\n\n\t\tvoid SetFont(const string& font, int fontSize);\n\n\t\tFont* GetFont() { return _font; }\n\n\n\n\t\tvoid SetFontSize(int fontSize);\n\n\t\tint GetFontSize() { return _font->GetFontSize(); }\n\n\n\n\t\tvoid SetText(const string& text);\n\n\t\tstring GetText() { return _text; }\n\n\n\n\t};\n", "file_path": "Engine/include/component/CotFontRenderer.h", "rank": 34, "score": 107891.36542042563 }, { "content": "namespace Cot\n\n{\n\n\tenum class AudioState\n\n\t{\n\n\t\tPlaying,\n\n\t\tPaused,\n\n\t\tStopped,\n\n\t};\n\n\n\n\tComponent(AudioSource, COT_API)\n\n\t{\n\n\t\tCOT_COMPONENT(AudioSource);\n\n\tprivate:\n\n\t\tAudioClip*\t_clip;\n\n\t\tAudioState\t_state;\n\n\t\tALuint\t\t_source;\n\n\t\tfloat\t\t_volume;\n\n\t\tfloat\t\t_pitch;\n\n\t\tfloat\t\t_maxDistance;\n\n\t\tVec3\t\t_velocity;\n\n\t\tbool\t\t_loop;\n\n\t\tbool\t\t_2d;\n\n\n\n\tpublic:\n\n\t\tAudioSource* Init(const string& filename, bool loop = false);\n\n\n\n\t\tvoid Reset() override;\n\n\t\tvoid Update(Time& time) override;\n\n\t\tvoid OnDestroy() override;\n\n\n\n\t\tvoid Play();\n\n\t\tvoid Pause();\n\n\t\tvoid Resume();\n\n\t\tvoid Stop();\n\n\n\n\t\tvoid SetClip(const string& filename);\n\n\t\tAudioClip& GetClip() { return *_clip; }\n\n\n\n\t\tvoid SetPitch(float pitch);\n\n\t\tfloat GetPitch() { return _pitch; }\n\n\n\n\t\tvoid SetLoop(bool loop);\n\n\t\tbool IsLoop() { return _loop; }\n\n\n\n\t\tvoid SetVolume(float volume);\n\n\t\tfloat GetVolume() { return _volume; }\n\n\n\n\t\tint GetPosition();\n\n\t\tint GetLength() { return _clip->GetLength(); }\n\n\n\n\t\tvoid SetMaxDistance(float maxDistance);\n\n\t\tfloat GetMaxDistance() { return _maxDistance; }\n\n\n\n\t\tvoid SetVelocity(const Vec3& velocity);\n\n\t\tVec3 GetVelocity() { return _velocity; }\n\n\n\n\t\tvoid Set2D(bool value);\n\n\t\tbool Is2D() { return _2d; }\n\n\n\n\t\tAudioState GetState() { return _state; }\n\n\n\n\t};\n", "file_path": "Engine/include/component/CotAudioSource.h", "rank": 35, "score": 107891.36542042563 }, { "content": "namespace Cot\n\n{\n\n\tComponentExt(SpriteRenderer, IRenderComponent, COT_API)\n\n\t{\n\n\t\tCOT_COMPONENT(SpriteRenderer);\n\n\tprotected:\n\n\t\tTexture*\t_texture;\n\n\n\n\tpublic:\n\n\t\tSpriteRenderer* Init(const string& filename);\n\n\t\tSpriteRenderer* Init(const string& caif, const string& key);\n\n\n\n\t\tvoid Reset() override;\n\n\t\tvoid Update(Time& time) override;\n\n\t\tvoid OnDestroy() override;\n\n\n\n\t\tvoid SetTexture(Texture* texture);\n\n\t\tvoid SetTexture(const string& filename);\n\n\t\tvoid SetTexture(const string& caif, const string& key);\n\n\t\tTexture* GetTexture() { return _texture; }\n\n\n\n\t};\n", "file_path": "Engine/include/component/CotSpriteRenderer.h", "rank": 36, "score": 107891.36542042563 }, { "content": "namespace Cot\n\n{\n\n\tComponent(PrograssBar, COT_API)\n\n\t{\n\n\t\tCOT_COMPONENT(PrograssBar);\n\n\tprivate:\n\n\t\tSpriteRenderer* _spriteRenderer;\n\n\t\tfloat _value;\n\n\t\tfloat _x;\n\n\n\n\tpublic:\n\n\t\tvoid Reset() override;\n\n\t\tvoid Awake() override;\n\n\n\n\t\tvoid SetValue(float value);\n\n\t\tfloat GetValue() { return _value; }\n\n\t\t\n\n\t};\n", "file_path": "Engine/include/component/CotPrograssBar.h", "rank": 37, "score": 107891.36542042563 }, { "content": "namespace Cot \n\n{\n\n\tCOT_API inline float ToRad(const float deg);\n\n\tCOT_API inline float ToDeg(const float rad);\n\n\tCOT_API inline float Pi();\n\n\tCOT_API inline float Lerp(float v1, float v2, float amount);\n\n\t\n\n\ttemplate<typename T>\n\n\tCOT_API inline T Clamp(const T value, const T min, const T max)\n\n\t{\n\n\t\tif (value < min)\n\n\t\t{\n\n\t\t\treturn min;\n\n\t\t}\n\n\t\telse if (value > max)\n\n\t\t{\n\n\t\t\treturn max;\n\n\t\t}\n\n\t\treturn value;\n\n\t}\n\n\n\n\ttemplate<typename T>\n\n\tCOT_API inline T Max(const T v1, const T v2)\n\n\t{\n\n\t\treturn (v1 > v2) ? return v1 : return v2;\n\n\t}\n\n\n\n\ttemplate<typename T>\n\n\tCOT_API inline T Min(const T v1, const T v2)\n\n\t{\n\n\t\treturn (v1 > v2) ? return v1 : return v2;\n\n\t}\n", "file_path": "Engine/include/math/CotMathFunc.h", "rank": 38, "score": 107891.36542042563 }, { "content": "namespace Cot\n\n{\n\n\tComponentExt(BoxCollider, ICollider, COT_API)\n\n\t{\n\n\t\tCOT_COMPONENT(BoxCollider);\n\n\tprivate:\n\n\t\tSize\t_size;\n\n\t\tVec2\t_offset;\n\n\n\n\tpublic:\n\n\t\tBoxCollider* Init(const Size& size = Size(300, 300));\n\n\n\n\t\tvoid Reset() override;\n\n\t\tvoid Update(Time& time) override;\n\n\n\n\t\tvoid SetSpriteSize();\n\n\n\n\t\tvoid SetOffset(const Vec2& offset);\n\n\t\tVec2 GetOffset() { return _offset; }\n\n\n\n\t\tvoid SetRect(const Size& size);\n\n\t\tRect GetRect();\n\n\n\n\t};\n", "file_path": "Engine/include/component/CotBoxCollider.h", "rank": 39, "score": 107891.36542042563 }, { "content": "namespace Cot\n\n{\n\n\tComponentExt(ScrollBar, SpriteRenderer, COT_API)\n\n\t{\n\n\t\tCOT_COMPONENT(ScrollBar);\n\n\tprivate:\n\n\t\tEntity* _button;\n\n\t\tbool\t_buttonDown;\n\n\t\tfloat\t_beginY;\n\n\t\tfloat\t_endY;\n\n\n\n\t\tfloat\t_value;\n\n\t\tfloat\t_minValue;\n\n\t\tfloat\t_maxValue;\n\n\n\n\tpublic:\n\n\t\tScrollBar* Init(const string& background, Entity* button);\n\n\t\t\n\n\t\tvoid Reset() override;\n\n\t\tvoid Update(Time& time) override;\n\n\t\tvoid OnDestroy() override;\n\n\n\n\t\tvoid SetValue(float value);\n\n\t\tfloat GetValue() { return _value; }\n\n\n\n\t};\n", "file_path": "Engine/include/component/CotScrollBar.h", "rank": 40, "score": 107891.36542042563 }, { "content": "namespace Cot\n\n{\n\n\tComponent(IRenderComponent, COT_API)\n\n\t{\n\n\t\tCOT_COMPONENT(IRenderComponent);\n\n\tpublic:\n\n\t\tenum class Type\n\n\t\t{\n\n\t\t\tSprite,\n\n\t\t\tFont,\n\n\t\t};\n\n\t\t\n\n\tprotected:\n\n\t\tType\t_renderType;\n\n\t\tVec2\t_anchor;\n\n\t\tColor\t_color;\n\n\t\tRect\t_rect;\n\n\t\tSize\t_size;\n\n\t\tint\t\t_depth;\n\n\t\tMask*\t_maskData;\n\n\t\tbool\t_masked;\n\n\n\n\tpublic:\n\n\t\tType GetRenderType() { return _renderType; }\n\n\n\n\t\tvoid SetMask(Mask* maskData, bool value);\n\n\t\tbool IsUseMask() { return _masked; }\n\n\t\tMask* GetMaskData() { return _maskData; }\n\n\n\n\t\tvoid SetAnchor(const Vec2& anchor);\n\n\t\tVec2 GetAnchor() { return _anchor; }\n\n\n\n\t\tvoid SetRect(const Rect& rect);\n\n\t\tRect GetRect() { return _rect; }\n\n\n\n\t\tvoid SetSize(const Size& size);\n\n\t\tSize GetSize() { return _size; }\n\n\n\n\t\tvoid SetDepth(int depth);\n\n\t\tint GetDepth() { return _depth; }\n\n\n\n\t\tvoid SetColor(const Color& color);\n\n\t\tColor GetColor() { return _color; }\n\n\n\n\t};\n", "file_path": "Engine/include/component/CotIRenderComponent.h", "rank": 41, "score": 107891.36542042563 }, { "content": "namespace Cot\n\n{\n\n\tComponent(AudioListener, COT_API)\n\n\t{\n\n\t\tCOT_COMPONENT(AudioListener);\n\n\tprivate:\n\n\t\tALCdevice*\t_device;\n\n\t\tALCcontext* _context;\n\n\n\n\tpublic:\n\n\t\tAudioListener* Init();\n\n\t\tvoid Update(Time& time) override;\n\n\n\n\t};\n", "file_path": "Engine/include/component/CotAudioListener.h", "rank": 42, "score": 107891.36542042563 }, { "content": "namespace Cot\n\n{\n\n\tComponentExt(CircleCollider, ICollider, COT_API)\n\n\t{\n\n\t\tCOT_COMPONENT(CircleCollider);\n\n\tprivate:\n\n\t\tfloat\t_radius;\n\n\t\tVec2\t_offset;\n\n\n\n\tpublic:\n\n\t\tCircleCollider* Init(float radius = 0.0f);\n\n\n\n\t\tvoid Reset() override;\n\n\t\tvoid Update(Time& time) override;\n\n\n\n\t\tvoid SetOffset(const Vec2& offset);\n\n\t\tVec2 GetOffset() { return _offset; }\n\n\n\n\t\tvoid SetRadius(float radius);\n\n\t\tCircle GetCircle();\n\n\n\n\t};\n", "file_path": "Engine/include/component/CotCircleCollider.h", "rank": 43, "score": 107891.36542042563 }, { "content": "class ValueConstIterator;\n\n\n\n} // namespace Json\n\n\n\n#endif // JSON_FORWARDS_H_INCLUDED\n\n\n\n// //////////////////////////////////////////////////////////////////////\n\n// End of content of file: include/json/forwards.h\n\n// //////////////////////////////////////////////////////////////////////\n\n\n\n\n\n\n\n\n\n\n\n\n\n// //////////////////////////////////////////////////////////////////////\n\n// Beginning of content of file: include/json/features.h\n\n// //////////////////////////////////////////////////////////////////////\n\n\n\n// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors\n", "file_path": "Engine/thirdparty/json/include/json/json.h", "rank": 44, "score": 106667.98681231124 }, { "content": "class ValueConstIterator;\n\n\n\n} // namespace Json\n\n\n\n#endif // JSON_FORWARDS_H_INCLUDED\n\n\n\n// //////////////////////////////////////////////////////////////////////\n\n// End of content of file: include/json/forwards.h\n\n// //////////////////////////////////////////////////////////////////////\n\n\n\n\n\n\n\n\n\n\n\n#endif //ifndef JSON_FORWARD_AMALGATED_H_INCLUDED\n", "file_path": "Engine/thirdparty/json/include/json/json-forwards.h", "rank": 45, "score": 102979.38451773452 }, { "content": "class JSON_API ValueConstIterator : public ValueIteratorBase {\n\n friend class Value;\n\n\n\npublic:\n\n typedef const Value value_type;\n\n //typedef unsigned int size_t;\n\n //typedef int difference_type;\n\n typedef const Value& reference;\n\n typedef const Value* pointer;\n\n typedef ValueConstIterator SelfType;\n\n\n\n ValueConstIterator();\n\n ValueConstIterator(ValueIterator const& other);\n\n\n\nprivate:\n\n/*! \\internal Use by Value to create an iterator.\n\n */\n\n explicit ValueConstIterator(const Value::ObjectValues::iterator& current);\n\npublic:\n\n SelfType& operator=(const ValueIteratorBase& other);\n", "file_path": "Engine/thirdparty/json/include/json/json.h", "rank": 46, "score": 100690.82367664558 }, { "content": " LPVOID pValue; // data for the default of the effect\n", "file_path": "Engine/thirdparty/directx/include/d3dx9mesh.h", "rank": 47, "score": 95083.18530760742 }, { "content": " D3DXQUATERNION Value;\n", "file_path": "Engine/thirdparty/directx/include/d3dx9anim.h", "rank": 48, "score": 95078.58241840679 }, { "content": " WORD value;\n", "file_path": "Engine/thirdparty/directx/include/d3dx9math.h", "rank": 49, "score": 95078.58241840678 }, { "content": " float z;\n", "file_path": "Engine/thirdparty/directx/include/d3d9types.h", "rank": 50, "score": 94866.38035264192 }, { "content": " float x;\n", "file_path": "Engine/thirdparty/directx/include/d3d9types.h", "rank": 51, "score": 94839.38995832019 }, { "content": " FLOAT x, y, z, w;\n", "file_path": "Engine/thirdparty/directx/include/d3dx9math.h", "rank": 52, "score": 94839.38995832019 }, { "content": " BOOL InVBlank;\n", "file_path": "Engine/thirdparty/directx/include/d3d9types.h", "rank": 53, "score": 92047.17966822787 }, { "content": " float MinZ; /* Min/max of clip Volume */\n", "file_path": "Engine/thirdparty/directx/include/d3d9types.h", "rank": 54, "score": 92047.17966822787 }, { "content": " float MaxZ;\n", "file_path": "Engine/thirdparty/directx/include/d3d9types.h", "rank": 55, "score": 92047.17966822787 }, { "content": " INT RowPitch;\n", "file_path": "Engine/thirdparty/directx/include/d3d9types.h", "rank": 56, "score": 92042.24603559567 }, { "content": " INT SlicePitch;\n", "file_path": "Engine/thirdparty/directx/include/d3d9types.h", "rank": 57, "score": 92042.24603559567 }, { "content": " BYTE PitchAndFamily;\n", "file_path": "Engine/thirdparty/directx/include/d3dx9core.h", "rank": 58, "score": 92042.24603559567 }, { "content": " int returned;\n", "file_path": "Engine/thirdparty/libvorbis/include/ogg/ogg.h", "rank": 59, "score": 92039.80602564912 }, { "content": " HRESULT ReturnCode;\n", "file_path": "Engine/thirdparty/directx/include/d3d9types.h", "rank": 60, "score": 92039.80602564912 }, { "content": " long lW;\n", "file_path": "Engine/thirdparty/libvorbis/include/vorbis/codec.h", "rank": 61, "score": 92034.94578475777 }, { "content": " long nW;\n", "file_path": "Engine/thirdparty/libvorbis/include/vorbis/codec.h", "rank": 62, "score": 92034.94578475777 }, { "content": " DWORD DefaultValue; // offset of default value\n", "file_path": "Engine/thirdparty/directx/include/d3dx9shader.h", "rank": 63, "score": 92003.42358913997 }, { "content": " DWORD ZCmpCaps;\n", "file_path": "Engine/thirdparty/directx/include/d3d9caps.h", "rank": 64, "score": 89163.33954488905 }, { "content": " int pcm_returned;\n", "file_path": "Engine/thirdparty/libvorbis/include/vorbis/codec.h", "rank": 65, "score": 89156.19691869125 }, { "content": " long body_returned; /* elements of fill returned */\n", "file_path": "Engine/thirdparty/libvorbis/include/ogg/ogg.h", "rank": 66, "score": 89156.19691869125 }, { "content": " long lacing_returned;\n", "file_path": "Engine/thirdparty/libvorbis/include/ogg/ogg.h", "rank": 67, "score": 89156.19691869125 }, { "content": " long centerW;\n", "file_path": "Engine/thirdparty/libvorbis/include/vorbis/codec.h", "rank": 68, "score": 89151.48894925181 }, { "content": " float MaxVertexW;\n", "file_path": "Engine/thirdparty/directx/include/d3d9caps.h", "rank": 69, "score": 89151.48894925181 }, { "content": " DWORD MaxVertexShaderConst; // number of vertex shader constant registers\n", "file_path": "Engine/thirdparty/directx/include/d3d9caps.h", "rank": 70, "score": 86450.07768551432 }, { "content": " float PixelShader1xMaxValue; // max value storable in registers of ps.1.x shaders\n", "file_path": "Engine/thirdparty/directx/include/d3d9caps.h", "rank": 71, "score": 86413.61395655731 }, { "content": " DWORD MaxVShaderInstructionsExecuted; // maximum number of vertex shader instructions that can be executed\n", "file_path": "Engine/thirdparty/directx/include/d3d9caps.h", "rank": 72, "score": 83905.79858773535 }, { "content": "#include \"math/CotVec4.h\"\n\n#include \"math/CotVec2.h\"\n\n#include \"math/CotVec3.h\"\n\n#include <cmath>\n\n\n\nnamespace Cot \n\n{\n\n\tVec4::Vec4()\n\n\t\t: x(0.0f), y(0.0f), z(0.0f), w(0.0f)\n\n\t{\t}\n\n\n\n\tVec4::Vec4(const float value)\n\n\t\t: x(value), y(value), z(value), w(value)\n\n\t{\t}\n\n\n\n\tVec4::Vec4(const float xx, const float yy)\n\n\t\t: x(xx), y(yy), z(0.0f), w(0.0f)\n\n\t{\t}\n\n\n\n\tVec4::Vec4(const Vec2& other)\n", "file_path": "Engine/src/CotVec4.cpp", "rank": 75, "score": 81116.78464237148 }, { "content": "\t\t: x(other.x), y(other.y), z(0.0f), w(0.0f)\n\n\t{\t}\n\n\n\n\tVec4::Vec4(const float xx, const float yy, const float zz)\n\n\t\t: x(xx), y(yy), z(zz), w(0.0f)\n\n\t{\t}\n\n\n\n\tVec4::Vec4(const Vec3& other)\n\n\t\t: x(other.x), y(other.y), z(other.z), w(0.0f)\n\n\t{\t}\n\n\n\n\tVec4::Vec4(const float xx, const float yy, const float zz, const float ww)\n\n\t\t: x(xx), y(yy), z(zz), w(ww)\n\n\t{\t}\n\n\n\n\tVec4::Vec4(const float* array)\n\n\t\t: x(array[0]), y(array[1]), z(array[2]), w(array[3])\n\n\t{\t}\n\n\n\n\tVec4::Vec4(const Vec4& other)\n", "file_path": "Engine/src/CotVec4.cpp", "rank": 76, "score": 81116.48291866129 }, { "content": "\t\t}\n\n\n\n\t\tfloat zz = 0.0f;\n\n\t\tif (value > 0.0f)\n\n\t\t{\n\n\t\t\tzz = z / value;\n\n\t\t}\n\n\n\n\t\tfloat ww = 0.0f;\n\n\t\tif (value > 0.0f)\n\n\t\t{\n\n\t\t\tww = w / value;\n\n\t\t}\n\n\t\treturn Vec4(xx, yy, zz, ww);\n\n\t}\n\n\n\n\tVec4& Vec4::operator+=(const Vec4& other)\n\n\t{\n\n\t\tx += other.x;\n\n\t\ty += other.y;\n", "file_path": "Engine/src/CotVec4.cpp", "rank": 77, "score": 81111.42472927677 }, { "content": "\t\tif (other.z > 0.0f)\n\n\t\t{\n\n\t\t\tzz = z / other.z;\n\n\t\t}\n\n\n\n\t\tfloat ww = 0.0f;\n\n\t\tif (other.w > 0.0f)\n\n\t\t{\n\n\t\t\tww = w / other.w;\n\n\t\t}\n\n\t\treturn Vec4(xx, yy, zz, ww);\n\n\t}\n\n\n\n\tconst Vec4 Vec4::operator+(const float value) const\n\n\t{\n\n\t\treturn Vec4(x + value, y + value, z + value, w + value);\n\n\t}\n\n\n\n\tconst Vec4 Vec4::operator-(const float value) const\n\n\t{\n", "file_path": "Engine/src/CotVec4.cpp", "rank": 78, "score": 81110.59266907649 }, { "content": "#include \"math/CotVec3.h\"\n\n#include \"math/CotVec2.h\"\n\n#include \"math/CotMat4.h\"\n\n\n\nnamespace Cot \n\n{\n\n\tVec3::Vec3()\n\n\t\t: x(0.0f), y(0.0f), z(0.0f)\n\n\t{\t}\n\n\n\n\tVec3::Vec3(const float value)\n\n\t\t: x(value), y(value), z(value)\n\n\t{\t}\n\n\n\n\tVec3::Vec3(const float xx, const float yy)\n\n\t\t: x(xx), y(yy), z(0.0f)\n\n\t{\t}\n\n\n\n\tVec3::Vec3(const Vec2& other)\n\n\t\t: x(other.x), y(other.y), z(0.0f)\n", "file_path": "Engine/src/CotVec3.cpp", "rank": 79, "score": 81107.7659355377 }, { "content": "\t\treturn *this;\n\n\t}\n\n\n\n\tVec4& Vec4::operator/=(const Vec4& other)\n\n\t{\n\n\t\tfloat xx = 0.0f;\n\n\t\tif (other.x > 0.0f)\n\n\t\t{\n\n\t\t\txx = x / other.x;\n\n\t\t}\n\n\t\tx = xx;\n\n\n\n\t\tfloat yy = 0.0f;\n\n\t\tif (other.y > 0.0f)\n\n\t\t{\n\n\t\t\tyy = y / other.y;\n\n\t\t}\n\n\t\ty = yy;\n\n\n\n\t\tfloat zz = 0.0f;\n", "file_path": "Engine/src/CotVec4.cpp", "rank": 84, "score": 81103.82075853318 }, { "content": "\t\treturn Vec4(x - value, y - value, z - value, w - value);\n\n\t}\n\n\n\n\tconst Vec4 Vec4::operator*(const float value) const\n\n\t{\n\n\t\treturn Vec4(x * value, y * value, z * value, w * value);\n\n\t}\n\n\n\n\tconst Vec4 Vec4::operator/(const float value) const\n\n\t{\n\n\t\tfloat xx = 0.0f;\n\n\t\tif (value > 0.0f)\n\n\t\t{\n\n\t\t\txx = x / value;\n\n\t\t}\n\n\n\n\t\tfloat yy = 0.0f;\n\n\t\tif (value > 0.0f)\n\n\t\t{\n\n\t\t\tyy = y / value;\n", "file_path": "Engine/src/CotVec4.cpp", "rank": 87, "score": 81103.11334090677 }, { "content": "#include \"math/CotVec2.h\"\n\n#include <cmath>\n\n\n\nnamespace Cot \n\n{\n\n\tVec2::Vec2()\n\n\t\t: x(0.0f), y(0.0f)\n\n\t{\t}\n\n\n\n\tVec2::Vec2(const float value)\n\n\t\t: x(value), y(value)\n\n\t{\t}\n\n\n\n\tVec2::Vec2(const float xx, const float yy)\n\n\t\t: x(xx), y(yy)\n\n\t{\t}\n\n\n\n\tVec2::Vec2(const float* array)\n\n\t\t: x(array[0]), y(array[1])\n\n\t{\t}\n", "file_path": "Engine/src/CotVec2.cpp", "rank": 88, "score": 35.03750153382204 }, { "content": "\t\t{\n\n\t\t\txx = x / other.x;\n\n\t\t}\n\n\n\n\t\tfloat yy = 0.0f;\n\n\t\tif (other.y > 0.0f)\n\n\t\t{\n\n\t\t\tyy = y / other.y;\n\n\t\t}\n\n\n\n\t\tfloat zz = 0.0f;\n\n\t\tif (other.z > 0.0f)\n\n\t\t{\n\n\t\t\tzz = z / other.z;\n\n\t\t}\n\n\t\treturn Vec3(xx, yy, zz);\n\n\t}\n\n\n\n\tconst Vec3 Vec3::operator+(const float value) const\n\n\t{\n", "file_path": "Engine/src/CotVec3.cpp", "rank": 89, "score": 30.876344442040335 }, { "content": "\n\n\t\tfloat yy = 0.0f;\n\n\t\tif (value > 0.0f)\n\n\t\t{\n\n\t\t\tyy = y / value;\n\n\t\t}\n\n\n\n\t\tfloat zz = 0.0f;\n\n\t\tif (value > 0.0f)\n\n\t\t{\n\n\t\t\tzz = z / value;\n\n\t\t}\n\n\t\treturn Vec3(xx, yy, zz);\n\n\t}\n\n\n\n\tVec3& Vec3::operator+=(const Vec3& other)\n\n\t{\n\n\t\tx += other.x;\n\n\t\ty += other.y;\n\n\t\tz += other.z;\n", "file_path": "Engine/src/CotVec3.cpp", "rank": 90, "score": 30.819872987667978 }, { "content": "\t{\t}\n\n\n\n\tVec3::Vec3(const float xx, const float yy, const float zz)\n\n\t\t: x(xx), y(yy), z(zz)\n\n\t{\t}\n\n\n\n\tVec3::Vec3(const float* array)\n\n\t\t: x(array[0]), y(array[1]), z(array[2])\n\n\t{\t}\n\n\n\n\tVec3::Vec3(const Vec3& other)\n\n\t\t: x(other.x), y(other.y), z(other.z)\n\n\t{\t}\n\n\n\n\tVec3::Vec3(const Vec3&& other)\n\n\t\t: x(other.x), y(other.y), z(other.z)\n\n\t{\t}\n\n\n\n\tVec3::~Vec3()\n\n\t{\t}\n", "file_path": "Engine/src/CotVec3.cpp", "rank": 91, "score": 30.81178252318434 }, { "content": "#include \"math/CotMat4.h\"\n\n#include \"math/CotGeometry.h\"\n\n#include \"math/CotVec3.h\"\n\n#include \"math/CotVec4.h\"\n\n#include \"math/CotQuaternion.h\"\n\n#include \"math/CotMathFunc.h\"\n\n#include <cmath>\n\n\n\nnamespace Cot \n\n{\n\n\tMat4::Mat4()\n\n\t\t: _11(1.0f), _12(0.0f), _13(0.0f), _14(0.0f)\n\n\t\t, _21(0.0f), _22(1.0f), _23(0.0f), _24(0.0f)\n\n\t\t, _31(0.0f), _32(0.0f), _33(1.0f), _34(0.0f)\n\n\t\t, _41(0.0f), _42(0.0f), _43(0.0f), _44(1.0f)\n\n\t{ }\n\n\n\n\tMat4::Mat4\n\n\t(\n\n\t\tconst float m11, const float m12, const float m13, const float m14,\n", "file_path": "Engine/src/CotMat4.cpp", "rank": 92, "score": 26.849276852293322 }, { "content": "\tconst Vec4 Vec4::operator*(const Vec4& other) const\n\n\t{\n\n\t\treturn Vec4(x * other.x, y * other.y, z * other.z, w * other.w);\n\n\t}\n\n\n\n\tconst Vec4 Vec4::operator/(const Vec4& other) const\n\n\t{\n\n\t\tfloat xx = 0.0f;\n\n\t\tif (other.x > 0.0f)\n\n\t\t{\n\n\t\t\txx = x / other.x;\n\n\t\t}\n\n\n\n\t\tfloat yy = 0.0f;\n\n\t\tif (other.y > 0.0f)\n\n\t\t{\n\n\t\t\tyy = y / other.y;\n\n\t\t}\n\n\n\n\t\tfloat zz = 0.0f;\n", "file_path": "Engine/src/CotVec4.cpp", "rank": 93, "score": 25.508493294490883 }, { "content": "\t{\n\n\t\tfloat deltaX = (other.x - x);\n\n\t\tfloat deltaY = (other.y - y);\n\n\t\tfloat deltaZ = (other.z - z);\n\n\t\tfloat deltaW = (other.w - w);\n\n\t\treturn sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ + deltaW * deltaW);\n\n\t}\n\n\n\n\tfloat Vec4::Distance(const Vec4& other1, const Vec4& other2)\n\n\t{\n\n\t\tfloat deltaX = (other1.x - other2.x);\n\n\t\tfloat deltaY = (other1.y - other2.y);\n\n\t\tfloat deltaZ = (other1.z - other2.z);\n\n\t\tfloat deltaW = (other1.w - other2.w);\n\n\t\treturn sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ + deltaW * deltaW);\n\n\t}\n\n\n\n\tfloat Vec4::Dot(const Vec4& other) const\n\n\t{\n\n\t\treturn x * other.x + y * other.y + z * other.z + w * other.w;\n", "file_path": "Engine/src/CotVec4.cpp", "rank": 94, "score": 24.365866709693567 }, { "content": "\t{\n\n\t\tfloat xx = 0.0f;\n\n\t\tif (other.x > 0.0f)\n\n\t\t{\n\n\t\t\txx = x / other.x;\n\n\t\t}\n\n\t\tx = xx;\n\n\n\n\t\tfloat yy = 0.0f;\n\n\t\tif (other.y > 0.0f)\n\n\t\t{\n\n\t\t\tyy = y / other.y;\n\n\t\t}\n\n\t\ty = yy;\n\n\n\n\t\tfloat zz = 0.0f;\n\n\t\tif (other.z > 0.0f)\n\n\t\t{\n\n\t\t\tzz = z / other.z;\n\n\t\t}\n", "file_path": "Engine/src/CotVec3.cpp", "rank": 95, "score": 22.745228921358937 }, { "content": "\t\tvoid ResetTransform();\n\n\n\n\t\tvoid SetPosition(const Vec3& position);\n\n\t\tvoid SetPositionX(float x);\n\n\t\tvoid SetPositionY(float y);\n\n\t\tvoid SetPositionZ(float z);\n\n\t\tVec3 GetPosition();\n\n\n\n\t\tvoid SetRotateAxis(float deg, const Vec3& axis);\n\n\t\tVec3 GetRotate();\n\n\n\n\t\tvoid SetScale(const Vec3& scale);\n\n\t\tvoid SetScaleX(float x);\n\n\t\tvoid SetScaleY(float y);\n\n\t\tvoid SetScaleZ(float z);\n\n\t\tVec3 GetScale();\n\n\n\n\t\tvoid SetLocalPosition(const Vec3& position);\n\n\t\tvoid SetLocalPositionX(float x);\n\n\t\tvoid SetLocalPositionY(float y);\n", "file_path": "Engine/include/base/CotEntity.h", "rank": 96, "score": 22.411138635926463 }, { "content": "\t\treturn Vec3(x + value, y + value, z + value);\n\n\t}\n\n\n\n\tconst Vec3 Vec3::operator-(const float value) const\n\n\t{\n\n\t\treturn Vec3(x - value, y - value, z - value);\n\n\t}\n\n\n\n\tconst Vec3 Vec3::operator*(const float value) const\n\n\t{\n\n\t\treturn Vec3(x * value, y * value, z * value);\n\n\t}\n\n\n\n\tconst Vec3 Vec3::operator/(const float value) const\n\n\t{\n\n\t\tfloat xx = 0.0f;\n\n\t\tif (value > 0.0f)\n\n\t\t{\n\n\t\t\txx = x / value;\n\n\t\t}\n", "file_path": "Engine/src/CotVec3.cpp", "rank": 97, "score": 21.74218556883645 }, { "content": "\t\tfloat xx = 0.0f;\n\n\t\tif (value > 0.0f)\n\n\t\t{\n\n\t\t\txx = x / value;\n\n\t\t}\n\n\n\n\t\tfloat yy = 0.0f;\n\n\t\tif (value > 0.0f)\n\n\t\t{\n\n\t\t\tyy = y / value;\n\n\t\t}\n\n\t\treturn Vec2(xx, yy);\n\n\t}\n\n\n\n\tVec2& Vec2::operator+=(const Vec2& other)\n\n\t{\n\n\t\tx += other.x;\n\n\t\ty += other.y;\n\n\t\treturn *this;\n\n\t}\n", "file_path": "Engine/src/CotVec2.cpp", "rank": 98, "score": 21.477735247423215 }, { "content": "\t\tif (other.z > 0.0f)\n\n\t\t{\n\n\t\t\tzz = z / other.z;\n\n\t\t}\n\n\t\tz = zz;\n\n\n\n\t\tfloat ww = 0.0f;\n\n\t\tif (other.w > 0.0f)\n\n\t\t{\n\n\t\t\tww = w / other.w;\n\n\t\t}\n\n\t\tw = ww;\n\n\n\n\t\treturn *this;\n\n\t}\n\n\n\n\tVec4& Vec4::operator=(const Vec4& other)\n\n\t{\n\n\t\tx = other.x;\n\n\t\ty = other.y;\n", "file_path": "Engine/src/CotVec4.cpp", "rank": 99, "score": 21.477018882151537 } ]
C++
trunk/third_party/webrtc/modules/rtp_rtcp/test/testAPI/test_api_audio.cc
goddino/libjingle
9516bee51c73af4c3082e74b88ed1198a0eb2bb1
#include <algorithm> #include <vector> #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/modules/rtp_rtcp/test/testAPI/test_api.h" #include "webrtc/common_types.h" #include "webrtc/modules/rtp_rtcp/interface/rtp_rtcp.h" #include "webrtc/modules/rtp_rtcp/interface/rtp_rtcp_defines.h" using namespace webrtc; #define test_rate 64000u class VerifyingAudioReceiver : public RtpData { public: virtual int32_t OnReceivedPayloadData( const uint8_t* payloadData, const uint16_t payloadSize, const webrtc::WebRtcRTPHeader* rtpHeader) { if (rtpHeader->header.payloadType == 98 || rtpHeader->header.payloadType == 99) { EXPECT_EQ(4, payloadSize); char str[5]; memcpy(str, payloadData, payloadSize); str[4] = 0; EXPECT_STRCASEEQ("test", str); return 0; } if (rtpHeader->header.payloadType == 100 || rtpHeader->header.payloadType == 101 || rtpHeader->header.payloadType == 102) { if (rtpHeader->type.Audio.channel == 1) { if (payloadData[0] == 0xff) { return 0; } } ADD_FAILURE() << "This code path should never happen."; return -1; } return 0; } }; class RTPCallback : public RtpFeedback { public: virtual int32_t OnInitializeDecoder( const int32_t id, const int8_t payloadType, const char payloadName[RTP_PAYLOAD_NAME_SIZE], const int frequency, const uint8_t channels, const uint32_t rate) { if (payloadType == 96) { EXPECT_EQ(test_rate, rate) << "The rate should be 64K for this payloadType"; } return 0; } virtual void OnPacketTimeout(const int32_t id) { } virtual void OnReceivedPacket(const int32_t id, const RtpRtcpPacketType packetType) { } virtual void OnPeriodicDeadOrAlive(const int32_t id, const RTPAliveType alive) { } virtual void OnIncomingSSRCChanged(const int32_t id, const uint32_t SSRC) { } virtual void OnIncomingCSRCChanged(const int32_t id, const uint32_t CSRC, const bool added) { } }; class AudioFeedback : public RtpAudioFeedback { virtual void OnReceivedTelephoneEvent(const int32_t id, const uint8_t event, const bool end) { static uint8_t expectedEvent = 0; if (end) { uint8_t oldEvent = expectedEvent-1; if (expectedEvent == 32) { oldEvent = 15; } EXPECT_EQ(oldEvent, event); } else { EXPECT_EQ(expectedEvent, event); expectedEvent++; } if (expectedEvent == 16) { expectedEvent = 32; } } virtual void OnPlayTelephoneEvent(const int32_t id, const uint8_t event, const uint16_t lengthMs, const uint8_t volume) { }; }; class RtpRtcpAudioTest : public ::testing::Test { protected: RtpRtcpAudioTest() : fake_clock(123456) { test_CSRC[0] = 1234; test_CSRC[2] = 2345; test_id = 123; test_ssrc = 3456; test_timestamp = 4567; test_sequence_number = 2345; } ~RtpRtcpAudioTest() {} virtual void SetUp() { audioFeedback = new AudioFeedback(); data_receiver1 = new VerifyingAudioReceiver(); data_receiver2 = new VerifyingAudioReceiver(); rtp_callback = new RTPCallback(); transport1 = new LoopBackTransport(); transport2 = new LoopBackTransport(); RtpRtcp::Configuration configuration; configuration.id = test_id; configuration.audio = true; configuration.clock = &fake_clock; configuration.incoming_data = data_receiver1; configuration.outgoing_transport = transport1; configuration.audio_messages = audioFeedback; module1 = RtpRtcp::CreateRtpRtcp(configuration); configuration.id = test_id + 1; configuration.incoming_data = data_receiver2; configuration.incoming_messages = rtp_callback; configuration.outgoing_transport = transport2; configuration.audio_messages = audioFeedback; module2 = RtpRtcp::CreateRtpRtcp(configuration); transport1->SetSendModule(module2); transport2->SetSendModule(module1); } virtual void TearDown() { delete module1; delete module2; delete transport1; delete transport2; delete audioFeedback; delete data_receiver1; delete data_receiver2; delete rtp_callback; } int test_id; RtpRtcp* module1; RtpRtcp* module2; VerifyingAudioReceiver* data_receiver1; VerifyingAudioReceiver* data_receiver2; LoopBackTransport* transport1; LoopBackTransport* transport2; AudioFeedback* audioFeedback; RTPCallback* rtp_callback; uint32_t test_ssrc; uint32_t test_timestamp; uint16_t test_sequence_number; uint32_t test_CSRC[webrtc::kRtpCsrcSize]; SimulatedClock fake_clock; }; TEST_F(RtpRtcpAudioTest, Basic) { EXPECT_EQ(0, module1->SetSSRC(test_ssrc)); EXPECT_EQ(0, module1->SetStartTimestamp(test_timestamp)); EXPECT_EQ(0, module2->SetTelephoneEventForwardToDecoder(true)); EXPECT_EQ(0, module1->SetSendingStatus(true)); EXPECT_EQ(-1, module1->SendOutgoingData(webrtc::kAudioFrameSpeech, 96, 0, -1, NULL, 0)); CodecInst voiceCodec; voiceCodec.pltype = 96; voiceCodec.plfreq = 8000; memcpy(voiceCodec.plname, "PCMU", 5); EXPECT_EQ(0, module1->RegisterSendPayload(voiceCodec)); EXPECT_EQ(0, module1->RegisterReceivePayload(voiceCodec)); EXPECT_EQ(0, module2->RegisterSendPayload(voiceCodec)); voiceCodec.rate = test_rate; EXPECT_EQ(0, module2->RegisterReceivePayload(voiceCodec)); printf("4\n"); const uint8_t test[5] = "test"; EXPECT_EQ(0, module1->SendOutgoingData(webrtc::kAudioFrameSpeech, 96, 0, -1, test, 4)); EXPECT_EQ(test_ssrc, module2->RemoteSSRC()); EXPECT_EQ(test_timestamp, module2->RemoteTimestamp()); } TEST_F(RtpRtcpAudioTest, RED) { CodecInst voiceCodec; voiceCodec.pltype = 96; voiceCodec.plfreq = 8000; memcpy(voiceCodec.plname, "PCMU", 5); EXPECT_EQ(0, module1->RegisterSendPayload(voiceCodec)); EXPECT_EQ(0, module1->RegisterReceivePayload(voiceCodec)); EXPECT_EQ(0, module2->RegisterSendPayload(voiceCodec)); voiceCodec.rate = test_rate; EXPECT_EQ(0, module2->RegisterReceivePayload(voiceCodec)); EXPECT_EQ(0, module1->SetSSRC(test_ssrc)); EXPECT_EQ(0, module1->SetStartTimestamp(test_timestamp)); EXPECT_EQ(0, module1->SetSendingStatus(true)); voiceCodec.pltype = 127; voiceCodec.plfreq = 8000; memcpy(voiceCodec.plname, "RED", 4); EXPECT_EQ(0, module1->SetSendREDPayloadType(voiceCodec.pltype)); int8_t red = 0; EXPECT_EQ(0, module1->SendREDPayloadType(red)); EXPECT_EQ(voiceCodec.pltype, red); EXPECT_EQ(0, module1->RegisterReceivePayload(voiceCodec)); EXPECT_EQ(0, module2->RegisterReceivePayload(voiceCodec)); RTPFragmentationHeader fragmentation; fragmentation.fragmentationVectorSize = 2; fragmentation.fragmentationLength = new uint32_t[2]; fragmentation.fragmentationLength[0] = 4; fragmentation.fragmentationLength[1] = 4; fragmentation.fragmentationOffset = new uint32_t[2]; fragmentation.fragmentationOffset[0] = 0; fragmentation.fragmentationOffset[1] = 4; fragmentation.fragmentationTimeDiff = new uint16_t[2]; fragmentation.fragmentationTimeDiff[0] = 0; fragmentation.fragmentationTimeDiff[1] = 0; fragmentation.fragmentationPlType = new uint8_t[2]; fragmentation.fragmentationPlType[0] = 96; fragmentation.fragmentationPlType[1] = 96; const uint8_t test[5] = "test"; EXPECT_EQ(0, module1->SendOutgoingData(webrtc::kAudioFrameSpeech, 96, 160, -1, test, 4, &fragmentation)); EXPECT_EQ(0, module1->SetSendREDPayloadType(-1)); EXPECT_EQ(-1, module1->SendREDPayloadType(red)); } TEST_F(RtpRtcpAudioTest, DTMF) { CodecInst voiceCodec; voiceCodec.pltype = 96; voiceCodec.plfreq = 8000; memcpy(voiceCodec.plname, "PCMU", 5); EXPECT_EQ(0, module1->RegisterSendPayload(voiceCodec)); EXPECT_EQ(0, module1->RegisterReceivePayload(voiceCodec)); EXPECT_EQ(0, module2->RegisterSendPayload(voiceCodec)); voiceCodec.rate = test_rate; EXPECT_EQ(0, module2->RegisterReceivePayload(voiceCodec)); EXPECT_EQ(0, module1->SetSSRC(test_ssrc)); EXPECT_EQ(0, module1->SetStartTimestamp(test_timestamp)); EXPECT_EQ(0, module1->SetSendingStatus(true)); voiceCodec.pltype = 97; voiceCodec.plfreq = 8000; memcpy(voiceCodec.plname, "telephone-event", 16); EXPECT_EQ(0, module1->RegisterSendPayload(voiceCodec)); EXPECT_EQ(0, module2->RegisterReceivePayload(voiceCodec)); uint32_t timeStamp = 160; for (int i = 0; i < 16; i++) { EXPECT_EQ(0, module1->SendTelephoneEventOutband(i, timeStamp, 10)); } timeStamp += 160; const uint8_t test[9] = "test"; for (;timeStamp <= 250 * 160; timeStamp += 160) { EXPECT_EQ(0, module1->SendOutgoingData(webrtc::kAudioFrameSpeech, 96, timeStamp, -1, test, 4)); fake_clock.AdvanceTimeMilliseconds(20); module1->Process(); } EXPECT_EQ(0, module1->SendTelephoneEventOutband(32, 9000, 10)); for (;timeStamp <= 740 * 160; timeStamp += 160) { EXPECT_EQ(0, module1->SendOutgoingData(webrtc::kAudioFrameSpeech, 96, timeStamp, -1, test, 4)); fake_clock.AdvanceTimeMilliseconds(20); module1->Process(); } }
#include <algorithm> #include <vector> #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/modules/rtp_rtcp/test/testAPI/test_api.h" #include "webrtc/common_types.h" #include "webrtc/modules/rtp_rtcp/interface/rtp_rtcp.h" #include "webrtc/modules/rtp_rtcp/interface/rtp_rtcp_defines.h" using namespace webrtc; #define test_rate 64000u class VerifyingAudioReceiver : public RtpData { public: virtual int32_t OnReceivedPayloadData( const uint8_t* payloadData, const uint16_t payloadSize, const webrtc::WebRtcRTPHeader* rtpHeader) { if (rtpHeader->header.payloadType == 98 || rtpHeader->header.payloadType == 99) { EXPECT_EQ(4, payloadSize); char str[5]; memcpy(str, payloadData, payloadSize); str[4] = 0; EXPECT_STRCASEEQ("test", str); return 0; } if (rtpHeader->header.payloadType == 100 || rtpHeader->header.payloadType == 101 || rtpHeader->header.payloadType == 102) { if (rtpHeader->type.Audio.channel == 1) { if (payloadData[0] == 0xff) { return 0; } } ADD_FAILURE() << "This code path should never happen."; return -1; } return 0; } }; class RTPCallback : public RtpFeedback { public: virtual int32_t OnInitializeDecoder( const int32_t id, const int8_t payloadType, const char payloadName[RTP_PAYLOAD_NAME_SIZE], const int frequency, const uint8_t channels, const uint32_t rate) { if (payloadType == 96) { EXPECT_EQ(test_rate, rate) << "The rate should be 64K for this payloadType"; } return 0; } virtual void OnPacketTimeout(const int32_t id) { } virtual void OnReceivedPacket(const int32_t id, const RtpRtcpPacketType packetType) { } virtual void OnPeriodicDeadOrAlive(const int32_t id, const RTPAliveType alive) { } virtual void OnIncomingSSRCChanged(const int32_t id, const uint32_t SSRC) { } virtual void OnIncomingCSRCChanged(const int32_t id, const uint32_t CSRC, const bool added) { } }; class AudioFeedback : public RtpAudioFeedback { virtual void OnReceivedTelephoneEvent(const int32_t id, const uint8_t event, const bool end) { static uint8_t expectedEvent = 0; if (end) { uint8_t oldEvent = expectedEvent-1; if (expectedEvent == 32) { oldEvent = 15; } EXPECT_EQ(oldEvent, event); } else { EXPECT_EQ(expectedEvent, event); expectedEvent++; } if (expectedEvent == 16) { expectedEvent = 32; } } virtual void OnPlayTelephoneEvent(const int32_t id, const uint8_t event, const uint16_t lengthMs, const uint8_t volume) { }; }; class RtpRtcpAudioTest : public ::testing::Test { protected: RtpRtcpAudioTest() : fake_clock(123456) { test_CSRC[0] = 1234; test_CSRC[2] = 2345; test_id = 123; test_ssrc = 3456; test_timestamp = 4567; test_sequence_number = 2345; } ~RtpRtcpAudioTest() {} virtual void SetUp() { audioFeedback = new AudioFeedback(); data_receiver1 = new VerifyingAudioReceiver(); data_receiver2 = new VerifyingAudioReceiver(); rtp_callback = new RTPCallback(); transport1 = new LoopBackTransport(); transport2 = new LoopBackTransport(); RtpRtcp::Configuration configuration; configuration.id = test_id; configuration.audio = true; configuration.clock = &fake_clock; configuration.incoming_data = data_receiver1; configuration.outgoing_transport = transport1; configuration.audio_messages = audioFeedback; module1 = RtpRtcp::CreateRtpRtcp(configuration); configuration.id = test_id + 1; configuration.incoming_data = data_receiver2; configuration.incoming_messages = rtp_callback; configuration.outgoing_transport = transport2; configuration.audio_messages = audioFeedback; module2 = RtpRtcp::CreateRtpRtcp(configuration); transport1->SetSendModule(module2); transport2->SetSendModule(module1); } virtual void TearDown() { delete module1; delete module2; delete transport1; delete transport2; delete audioFeedback; delete data_receiver1; delete data_receiver2; delete rtp_callback; } int test_id; RtpRtcp* module1; RtpRtcp* module2; VerifyingAudioReceiver* data_receiver1; VerifyingAudioReceiver* data_receiver2; LoopBackTransport* transport1; LoopBackTransport* transport2; AudioFeedback* audioFeedback; RTPCallback* rtp_callback; uint32_t test_ssrc; uint32_t test_timestamp; uint16_t test_sequence_number; uint32_t test_CSRC[webrtc::kRtpCsrcSize]; SimulatedClock fake_clock; }; TEST_F(RtpRtcpAudioTest, Basic) { EXPECT_EQ(0, module1->SetSSRC(test_ssrc)); EXPECT_EQ(0, module1->SetStartTimestamp(test_timestamp)); EXPECT_EQ(0, module2->SetTelephoneEventForwardToDecoder(true)); EXPECT_EQ(0, module1->SetSendingStatus(true)); EXPECT_EQ(-1, module1->SendOutgoingData(webrtc::kAudioFrameSpeech, 96, 0, -1, NULL, 0)); CodecInst voiceCodec; voiceCodec.pltype = 96; voiceCodec.plfreq = 8000; memcpy(voiceCodec.plname, "PCMU", 5); EXPECT_EQ(0, module1->RegisterSendPayload(voiceCodec)); EXPECT_EQ(0, module1->RegisterReceivePayload(voiceCodec)); EXPECT_EQ(0, module2->RegisterSendPayload(voiceCodec)); voiceCodec.rate = test_rate; EXPECT_EQ(0, module2->RegisterReceivePayload(voiceCodec)); printf("4\n"); const uint8_t test[5] = "test"; EXPECT_EQ(0, module1->SendOutgoingData(webrtc::kAudioFrameSpeech, 96, 0, -1, test, 4)); EXPECT_EQ(test_ssrc, module2->RemoteSSRC()); EXPECT_EQ(test_timestamp, module2->RemoteTimestamp()); } TEST_F(RtpRtcpAudioTest, RED) { CodecInst voiceCodec; voiceCodec.pltype = 96; voiceCodec.plfreq = 8000; memcpy(voiceCodec.plname, "PCMU", 5); EXPECT_EQ(0, module1->RegisterSendPayload(voiceCodec)); EXPECT_EQ(0, module1->RegisterReceivePayload(voiceCodec)); EXPECT_EQ(0, module2->RegisterSendPayload(voiceCodec)); voiceCodec.rate = test_rate; EXPECT_EQ(0, module2->RegisterReceivePayload(voiceCodec)); EXPECT_EQ(0, module1->SetSSRC(test_ssrc
160; timeStamp += 160) { EXPECT_EQ(0, module1->SendOutgoingData(webrtc::kAudioFrameSpeech, 96, timeStamp, -1, test, 4)); fake_clock.AdvanceTimeMilliseconds(20); module1->Process(); } }
)); EXPECT_EQ(0, module1->SetStartTimestamp(test_timestamp)); EXPECT_EQ(0, module1->SetSendingStatus(true)); voiceCodec.pltype = 127; voiceCodec.plfreq = 8000; memcpy(voiceCodec.plname, "RED", 4); EXPECT_EQ(0, module1->SetSendREDPayloadType(voiceCodec.pltype)); int8_t red = 0; EXPECT_EQ(0, module1->SendREDPayloadType(red)); EXPECT_EQ(voiceCodec.pltype, red); EXPECT_EQ(0, module1->RegisterReceivePayload(voiceCodec)); EXPECT_EQ(0, module2->RegisterReceivePayload(voiceCodec)); RTPFragmentationHeader fragmentation; fragmentation.fragmentationVectorSize = 2; fragmentation.fragmentationLength = new uint32_t[2]; fragmentation.fragmentationLength[0] = 4; fragmentation.fragmentationLength[1] = 4; fragmentation.fragmentationOffset = new uint32_t[2]; fragmentation.fragmentationOffset[0] = 0; fragmentation.fragmentationOffset[1] = 4; fragmentation.fragmentationTimeDiff = new uint16_t[2]; fragmentation.fragmentationTimeDiff[0] = 0; fragmentation.fragmentationTimeDiff[1] = 0; fragmentation.fragmentationPlType = new uint8_t[2]; fragmentation.fragmentationPlType[0] = 96; fragmentation.fragmentationPlType[1] = 96; const uint8_t test[5] = "test"; EXPECT_EQ(0, module1->SendOutgoingData(webrtc::kAudioFrameSpeech, 96, 160, -1, test, 4, &fragmentation)); EXPECT_EQ(0, module1->SetSendREDPayloadType(-1)); EXPECT_EQ(-1, module1->SendREDPayloadType(red)); } TEST_F(RtpRtcpAudioTest, DTMF) { CodecInst voiceCodec; voiceCodec.pltype = 96; voiceCodec.plfreq = 8000; memcpy(voiceCodec.plname, "PCMU", 5); EXPECT_EQ(0, module1->RegisterSendPayload(voiceCodec)); EXPECT_EQ(0, module1->RegisterReceivePayload(voiceCodec)); EXPECT_EQ(0, module2->RegisterSendPayload(voiceCodec)); voiceCodec.rate = test_rate; EXPECT_EQ(0, module2->RegisterReceivePayload(voiceCodec)); EXPECT_EQ(0, module1->SetSSRC(test_ssrc)); EXPECT_EQ(0, module1->SetStartTimestamp(test_timestamp)); EXPECT_EQ(0, module1->SetSendingStatus(true)); voiceCodec.pltype = 97; voiceCodec.plfreq = 8000; memcpy(voiceCodec.plname, "telephone-event", 16); EXPECT_EQ(0, module1->RegisterSendPayload(voiceCodec)); EXPECT_EQ(0, module2->RegisterReceivePayload(voiceCodec)); uint32_t timeStamp = 160; for (int i = 0; i < 16; i++) { EXPECT_EQ(0, module1->SendTelephoneEventOutband(i, timeStamp, 10)); } timeStamp += 160; const uint8_t test[9] = "test"; for (;timeStamp <= 250 * 160; timeStamp += 160) { EXPECT_EQ(0, module1->SendOutgoingData(webrtc::kAudioFrameSpeech, 96, timeStamp, -1, test, 4)); fake_clock.AdvanceTimeMilliseconds(20); module1->Process(); } EXPECT_EQ(0, module1->SendTelephoneEventOutband(32, 9000, 10)); for (;timeStamp <= 740 *
random
[]
C++
lib/fiber/element_pair_topology.hpp
nicolas-chaulet/bempp
0f5cc72e0e542437e787db5704978456b0ad9e35
#ifndef fiber_element_pair_topology_hpp #define fiber_element_pair_topology_hpp #include "../common/common.hpp" #include "../common/armadillo_fwd.hpp" #include <cassert> #include <iostream> #include <boost/tuple/tuple_comparison.hpp> namespace Fiber { struct ElementPairTopology { ElementPairTopology() : type(Disjoint), testVertexCount(0), trialVertexCount(0), testSharedVertex0(-1), testSharedVertex1(-1), trialSharedVertex0(-1), trialSharedVertex1(-1) {} enum Type { Disjoint, SharedVertex, SharedEdge, Coincident }; Type type; unsigned char testVertexCount; unsigned char trialVertexCount; signed char testSharedVertex0; signed char testSharedVertex1; signed char trialSharedVertex0; signed char trialSharedVertex1; bool operator<(const ElementPairTopology& other) const { using boost::tuples::make_tuple; return make_tuple(type, testVertexCount, trialVertexCount, testSharedVertex0, testSharedVertex1, trialSharedVertex0, trialSharedVertex1) < make_tuple(other.type, other.testVertexCount, other.trialVertexCount, other.testSharedVertex0, other.testSharedVertex1, other.trialSharedVertex0, other.trialSharedVertex1); } bool operator==(const ElementPairTopology& other) const { return type == other.type && testVertexCount == other.testVertexCount && trialVertexCount == other.trialVertexCount && testSharedVertex0 == other.testSharedVertex0 && testSharedVertex1 == other.testSharedVertex1 && trialSharedVertex0 == other.trialSharedVertex0 && trialSharedVertex1 == other.trialSharedVertex1; } bool operator!=(const ElementPairTopology& other) const { return !operator==(other); } friend std::ostream& operator<< (std::ostream& dest, const ElementPairTopology& obj) { dest << obj.type << " " << (int)obj.testVertexCount << " " << (int)obj.trialVertexCount << " " << (int)obj.testSharedVertex0 << " " << (int)obj.testSharedVertex1 << " " << (int)obj.trialSharedVertex0 << " " << (int)obj.trialSharedVertex1; return dest; } }; inline ElementPairTopology determineElementPairTopologyIn3D( const arma::Col<int>& testElementCornerIndices, const arma::Col<int>& trialElementCornerIndices) { ElementPairTopology topology; #ifndef NDEBUG const int MIN_VERTEX_COUNT = 3; #endif const int MAX_VERTEX_COUNT = 4; topology.testVertexCount = testElementCornerIndices.n_rows; assert(MIN_VERTEX_COUNT <= topology.testVertexCount && topology.testVertexCount <= MAX_VERTEX_COUNT); topology.trialVertexCount = trialElementCornerIndices.n_rows; assert(MIN_VERTEX_COUNT <= topology.trialVertexCount && topology.trialVertexCount <= MAX_VERTEX_COUNT); int testSharedVertices[MAX_VERTEX_COUNT]; int trialSharedVertices[MAX_VERTEX_COUNT]; int hits = 0; for (int trialV = 0; trialV < topology.trialVertexCount; ++trialV) for (int testV = 0; testV < topology.testVertexCount; ++testV) if (testElementCornerIndices(testV) == trialElementCornerIndices(trialV)) { testSharedVertices[hits] = testV; trialSharedVertices[hits] = trialV; ++hits; break; } if (hits == 0) { topology.type = ElementPairTopology::Disjoint; } else if (hits == 1) { topology.type = ElementPairTopology::SharedVertex; topology.testSharedVertex0 = testSharedVertices[0]; topology.trialSharedVertex0 = trialSharedVertices[0]; } else if (hits == 2) { topology.type = ElementPairTopology::SharedEdge; topology.testSharedVertex0 = testSharedVertices[0]; topology.testSharedVertex1 = testSharedVertices[1]; topology.trialSharedVertex0 = trialSharedVertices[0]; topology.trialSharedVertex1 = trialSharedVertices[1]; } else if (hits == topology.testVertexCount && hits == topology.trialVertexCount) { for (int i = 0; i < hits; ++i) assert(testSharedVertices[i] == trialSharedVertices[i]); topology.type = ElementPairTopology::Coincident; } else throw std::runtime_error( "Standard3DIntegrationManager::" "selectTestKernelTrialQuadratureRules() :" "Invalid element configuration"); return topology; } } #endif
#ifndef fiber_element_pair_topology_hpp #define fiber_element_pair_topology_hpp #include "../common/common.hpp" #include "../common/armadillo_fwd.hpp" #include <cassert> #include <iostream> #include <boost/tuple/tuple_comparison.hpp> namespace Fiber { struct ElementPairTopology { ElementPairTopology() : type(Disjoint), testVertexCount(0), trialVertexCount(0), testSharedVertex0(-1), testSharedVertex1(-1), trialSharedVertex0(-1), trialSharedVertex1(-1) {} enum Type { Disjoint, SharedVertex, SharedEdge, Coincident }; Type type; unsigned char testVertexCount; unsigned char trialVertexCount; signed char testSharedVertex0; signed char testSharedVertex1; signed char trialSharedVertex0; signed char trialSharedVertex1; bool operator<(const ElementPairTopology& other) const { using boost::tuples::make_tuple; return make_tuple(type, testVertexCount, trialVertexCount, testSharedVertex0, testSharedVertex1, trialSharedVertex0, trialSharedVertex1) < make_tuple(other.type, other.testVertexCount, other.trialVertexCount, other.testSharedVertex0, other.testSharedVertex1, other.trialSharedVertex0, other.trialSharedVertex1); } bool operator==(const ElementPairTopology& o
+testV) if (testElementCornerIndices(testV) == trialElementCornerIndices(trialV)) { testSharedVertices[hits] = testV; trialSharedVertices[hits] = trialV; ++hits; break; } if (hits == 0) { topology.type = ElementPairTopology::Disjoint; } else if (hits == 1) { topology.type = ElementPairTopology::SharedVertex; topology.testSharedVertex0 = testSharedVertices[0]; topology.trialSharedVertex0 = trialSharedVertices[0]; } else if (hits == 2) { topology.type = ElementPairTopology::SharedEdge; topology.testSharedVertex0 = testSharedVertices[0]; topology.testSharedVertex1 = testSharedVertices[1]; topology.trialSharedVertex0 = trialSharedVertices[0]; topology.trialSharedVertex1 = trialSharedVertices[1]; } else if (hits == topology.testVertexCount && hits == topology.trialVertexCount) { for (int i = 0; i < hits; ++i) assert(testSharedVertices[i] == trialSharedVertices[i]); topology.type = ElementPairTopology::Coincident; } else throw std::runtime_error( "Standard3DIntegrationManager::" "selectTestKernelTrialQuadratureRules() :" "Invalid element configuration"); return topology; } } #endif
ther) const { return type == other.type && testVertexCount == other.testVertexCount && trialVertexCount == other.trialVertexCount && testSharedVertex0 == other.testSharedVertex0 && testSharedVertex1 == other.testSharedVertex1 && trialSharedVertex0 == other.trialSharedVertex0 && trialSharedVertex1 == other.trialSharedVertex1; } bool operator!=(const ElementPairTopology& other) const { return !operator==(other); } friend std::ostream& operator<< (std::ostream& dest, const ElementPairTopology& obj) { dest << obj.type << " " << (int)obj.testVertexCount << " " << (int)obj.trialVertexCount << " " << (int)obj.testSharedVertex0 << " " << (int)obj.testSharedVertex1 << " " << (int)obj.trialSharedVertex0 << " " << (int)obj.trialSharedVertex1; return dest; } }; inline ElementPairTopology determineElementPairTopologyIn3D( const arma::Col<int>& testElementCornerIndices, const arma::Col<int>& trialElementCornerIndices) { ElementPairTopology topology; #ifndef NDEBUG const int MIN_VERTEX_COUNT = 3; #endif const int MAX_VERTEX_COUNT = 4; topology.testVertexCount = testElementCornerIndices.n_rows; assert(MIN_VERTEX_COUNT <= topology.testVertexCount && topology.testVertexCount <= MAX_VERTEX_COUNT); topology.trialVertexCount = trialElementCornerIndices.n_rows; assert(MIN_VERTEX_COUNT <= topology.trialVertexCount && topology.trialVertexCount <= MAX_VERTEX_COUNT); int testSharedVertices[MAX_VERTEX_COUNT]; int trialSharedVertices[MAX_VERTEX_COUNT]; int hits = 0; for (int trialV = 0; trialV < topology.trialVertexCount; ++trialV) for (int testV = 0; testV < topology.testVertexCount; +
random
[ { "content": "enum CallVariant\n\n{\n\n TEST_TRIAL = 0,\n\n TRIAL_TEST = 1\n\n};\n\n\n\ntypedef int LocalDofIndex;\n\nconst LocalDofIndex ALL_DOFS = -1;\n\n\n\n}\n\n\n\n#endif\n", "file_path": "lib/fiber/types.hpp", "rank": 0, "score": 187458.7934374725 }, { "content": "enum GeometricalDataType\n\n{\n\n GLOBALS = 0x0001,\n\n INTEGRATION_ELEMENTS = 0x0002,\n\n NORMALS = 0x0004,\n\n JACOBIANS_TRANSPOSED = 0x0008,\n\n JACOBIAN_INVERSES_TRANSPOSED = 0x0010\n\n};\n\n\n\n/** \\cond FORWARD_DECL */\n\ntemplate <typename CoordinateType> class ConstGeometricalDataSlice;\n\n/** \\endcond */\n\n\n\ntemplate <typename CoordinateType>\n", "file_path": "lib/fiber/geometrical_data.hpp", "rank": 1, "score": 178588.53894853673 }, { "content": "enum BasisDataType\n\n{\n\n VALUES = 0x0001,\n\n DERIVATIVES = 0x0002\n\n};\n\n\n\n/** \\cond FORWARD_DECL */\n\ntemplate <typename ValueType> class ConstBasisDataSlice;\n\n/** \\endcond */\n\n\n\ntemplate <typename ValueType>\n", "file_path": "lib/fiber/basis_data.hpp", "rank": 2, "score": 178588.5389485367 }, { "content": "struct GetInfoHelper<Func, VECTOR_CLASS<char *> >\n\n{\n\n static cl_int\n\n get(Func f, cl_uint name, VECTOR_CLASS<char *>* param)\n\n {\n\n cl_uint err = f(name, param->size() * sizeof(char *), &(*param)[0], NULL);\n\n if (err != CL_SUCCESS) {\n\n return err;\n\n }\n\n \n\n return CL_SUCCESS;\n\n }\n\n};\n\n\n\n// Specialized GetInfoHelper for STRING_CLASS params\n\ntemplate <typename Func>\n", "file_path": "lib/fiber/CL/cl.hpp", "rank": 3, "score": 176506.84658784064 }, { "content": "struct MblockArrayConverter<Type, Type>\n\n{\n\n static void convert(\n\n unsigned int n,\n\n const boost::shared_array<mblock<Type> *>& in,\n\n boost::shared_array<mblock<Type> *>& out) {\n\n out = in;\n\n }\n\n};\n\n\n\ntemplate <typename ValueType>\n\nvoid SparseToHMatrixConverter<ValueType>::constructHMatrix(\n\n int* rowOffsets, int* colIndices, double* values,\n\n std::vector<unsigned int>& domain_o2p,\n\n std::vector<unsigned int>& range_p2o,\n\n double eps,\n\n bemblcluster<AhmedDofType, AhmedDofType>* blockCluster,\n\n boost::shared_array<AhmedMblock*>& mblocks,\n\n int& maximumRank)\n\n{\n", "file_path": "lib/assembly/sparse_to_h_matrix_converter.cpp", "rank": 4, "score": 170064.80276353093 }, { "content": "struct GetInfoHelper<Func, CPP_TYPE> \\\n\n{ \\\n\n static cl_int get(Func f, cl_uint name, CPP_TYPE* param) \\\n\n { \\\n\n cl_uint err = f(name, sizeof(CPP_TYPE), param, NULL); \\\n\n if (err != CL_SUCCESS) { \\\n\n return err; \\\n\n } \\\n\n \\\n\n return ReferenceHandler<CPP_TYPE::cl_type>::retain((*param)()); \\\n\n } \\\n\n}; \\\n\n} \n\n\n\n\n\n#define __PARAM_NAME_INFO_1_0(F) \\\n\n F(cl_platform_info, CL_PLATFORM_PROFILE, STRING_CLASS) \\\n\n F(cl_platform_info, CL_PLATFORM_VERSION, STRING_CLASS) \\\n\n F(cl_platform_info, CL_PLATFORM_NAME, STRING_CLASS) \\\n\n F(cl_platform_info, CL_PLATFORM_VENDOR, STRING_CLASS) \\\n", "file_path": "lib/fiber/CL/cl.hpp", "rank": 5, "score": 157411.51858549006 }, { "content": "struct PiecewiseLinearContinuousScalarBasisTraits<4, CoordinateType, ValueType>\n\n{\n\npublic:\n\n typedef Dune::Q1LocalBasis<CoordinateType, ValueType, 2> DuneBasis;\n\n};\n\n\n\ntemplate <int elementVertexCount, typename ValueType>\n", "file_path": "lib/fiber/piecewise_linear_continuous_scalar_basis.hpp", "rank": 6, "score": 148248.23237424754 }, { "content": "struct PiecewiseLinearContinuousScalarBasisTraits<2, CoordinateType, ValueType>\n\n{\n\npublic:\n\n typedef Dune::Q1LocalBasis<CoordinateType, ValueType, 1> DuneBasis;\n\n};\n\n\n\n// Triangle\n\ntemplate <typename CoordinateType, typename ValueType>\n", "file_path": "lib/fiber/piecewise_linear_continuous_scalar_basis.hpp", "rank": 7, "score": 148248.23237424754 }, { "content": "struct PiecewiseLinearContinuousScalarBasisTraits<3, CoordinateType, ValueType>\n\n{\n\npublic:\n\n typedef Dune::P1LocalBasis<CoordinateType, ValueType, 2> DuneBasis;\n\n};\n\n\n\n// Quadrilateral\n\ntemplate <typename CoordinateType, typename ValueType>\n", "file_path": "lib/fiber/piecewise_linear_continuous_scalar_basis.hpp", "rank": 8, "score": 148248.23237424754 }, { "content": "enum DofType\n\n{\n\n GLOBAL_DOFS, FLAT_LOCAL_DOFS\n\n};\n\n\n\n/** \\ingroup space\n\n * \\brief Function space.\n\n *\n\n * This class represents a space of functions defined on a grid. The space is\n\n * spanned by a finite number of scalar- or vector-valued basis functions. The\n\n * template parameter \\p BasisFunctionType is the type of the values of (the\n\n * components of) these basis functions, and can be set to \\c float,\n\n * \\c double, <tt>std::complex<float></tt> or <tt>std::complex<double></tt>.\n\n *\n\n * The basis functions of a space, also known as global degrees of freedom\n\n * (DOFs), can have support extending over multiple elements of the grid. They\n\n * are, however, composed of one or more *local* basis functions (local\n\n * degrees of freedom), each of which resides on a single element. The mapping\n\n * of local to global degrees of freedom is triggered by calling the function\n\n * assignDofs(). Many other member functions of Space may only be invoked after\n\n * assignDofs() has beeen called. */\n\ntemplate <typename BasisFunctionType>\n", "file_path": "lib/space/space.hpp", "rank": 9, "score": 139015.70472538922 }, { "content": "struct LocalDof\n\n{\n\n LocalDof() {}\n\n LocalDof(EntityIndex ei, LocalDofIndex ldi) :\n\n entityIndex(ei), dofIndex(ldi) {\n\n }\n\n\n\n EntityIndex entityIndex;\n\n LocalDofIndex dofIndex;\n\n};\n\n\n\ntemplate <typename ValueType>\n", "file_path": "lib/common/types.hpp", "rank": 10, "score": 138052.9799339606 }, { "content": "struct Point3D\n\n{\n\n ValueType x, y, z;\n\n};\n\n\n\n} // namespace Bempp\n\n\n\n#endif\n", "file_path": "lib/common/types.hpp", "rank": 11, "score": 138052.9799339606 }, { "content": "#define __DECLARE_PARAM_TRAITS(token, param_name, T) \\\n\nstruct token; \\\n\ntemplate<> \\\n", "file_path": "lib/fiber/CL/cl.hpp", "rank": 12, "score": 135711.0531631047 }, { "content": "struct Equal\n\n{\n\n bool operator()(const std::pair<double, QuadratureOptions>& first,\n\n const std::pair<double, QuadratureOptions>& second) const\n\n {\n\n return first.first == second.first;\n\n }\n\n};\n\n\n\n} // namespace\n\n\n\nAccuracyOptionsEx::AccuracyOptionsEx()\n\n{\n\n m_doubleRegular.push_back(std::make_pair(std::numeric_limits<double>::infinity(),\n\n QuadratureOptions()));\n\n}\n\n\n\nAccuracyOptionsEx::AccuracyOptionsEx(const AccuracyOptions& oldStyleOpts)\n\n{\n\n m_singleRegular = oldStyleOpts.singleRegular;\n", "file_path": "lib/fiber/accuracy_options.cpp", "rank": 13, "score": 135705.18754253467 }, { "content": "struct Coercion\n\n{\n\n // If you get a compilation error here, chances are that you are trying to\n\n // mix floating-point numbers with different precisions (e.g. float and\n\n // double or std::complex<float> and double). BEM++ does not support this.\n\n};\n\n\n\ntemplate <>\n", "file_path": "lib/fiber/scalar_traits.hpp", "rank": 14, "score": 135705.18754253467 }, { "content": "struct LessOrEqual\n\n{\n\n bool operator()(const std::pair<double, QuadratureOptions>& first,\n\n const std::pair<double, QuadratureOptions>& second) const\n\n {\n\n return first.first <= second.first;\n\n }\n\n};\n\n\n", "file_path": "lib/fiber/accuracy_options.cpp", "rank": 15, "score": 132687.71270744532 }, { "content": "struct ReferenceHandler\n\n{ };\n\n\n\ntemplate <>\n", "file_path": "lib/fiber/CL/cl.hpp", "rank": 16, "score": 132687.71270744532 }, { "content": "struct GeometricalData\n\n{\n\n arma::Mat<CoordinateType> globals;\n\n arma::Row<CoordinateType> integrationElements;\n\n arma::Cube<CoordinateType> jacobiansTransposed;\n\n arma::Cube<CoordinateType> jacobianInversesTransposed;\n\n arma::Mat<CoordinateType> normals;\n\n\n\n // For the time being, I (somewhat dangerously) assume that\n\n // integrationElements or globals or normals are always used\n\n int pointCount() const {\n\n int result = std::max(std::max(globals.n_cols, normals.n_cols),\n\n integrationElements.n_cols);\n\n assert(result > 0);\n\n return result;\n\n }\n\n\n\n int dimWorld() const {\n\n int result = std::max(globals.n_rows, normals.n_rows);\n\n assert(result > 0);\n\n return result;\n\n }\n\n\n\n ConstGeometricalDataSlice<CoordinateType> const_slice(int point) const {\n\n return ConstGeometricalDataSlice<CoordinateType>(*this, point);\n\n }\n\n};\n\n\n\ntemplate <typename CoordinateType>\n", "file_path": "lib/fiber/geometrical_data.hpp", "rank": 17, "score": 132687.71270744532 }, { "content": "struct AccuracyOptions\n\n{\n\npublic:\n\n /** \\brief Options controlling integration of regular functions\n\n * on single elements. */\n\n QuadratureOptions singleRegular;\n\n /** \\brief Options controlling integration of regular functions\n\n * on pairs of elements. */\n\n QuadratureOptions doubleRegular;\n\n /** \\brief Options controlling integration of singular functions\n\n * on pairs of elements. */\n\n QuadratureOptions doubleSingular;\n\n};\n\n\n\n/** \\brief New-style options controlling quadrature accuracy. */\n", "file_path": "lib/fiber/accuracy_options.hpp", "rank": 18, "score": 132687.71270744532 }, { "content": "struct VerbosityLevel {\n\n enum Level {\n\n DEFAULT = 0,\n\n HIGH = 5,\n\n LOW = -5\n\n };\n\n};\n\n\n\n} // namespace Fiber\n\n\n\n#endif\n", "file_path": "lib/fiber/verbosity_level.hpp", "rank": 19, "score": 132687.71270744532 }, { "content": "struct ScalarTraits\n\n{\n\n // If you get a compilation error here, you are probably trying to use an\n\n // unsupported floating-point type. The supported types are: float, double,\n\n // std::complex<float> and std::complex<double>.\n\n};\n\n\n\ntemplate <>\n", "file_path": "lib/fiber/scalar_traits.hpp", "rank": 20, "score": 132687.71270744532 }, { "content": "struct param_traits {};\n\n\n", "file_path": "lib/fiber/CL/cl.hpp", "rank": 21, "score": 132687.71270744532 }, { "content": "struct QuadraturePoint\n\n{\n\n\tdouble coords[NUM_COORDS];\n\n\tdouble quadrature_weight;\n\n};\n\n\n\n\n\n\n\n/**\n\n * @ingroup quadrature\n\n *\n\n * The QuadratureRule object is a non specialzed template class for all\n\n * different @p QUADRATURE_RULES and @p ELEMENT_SHAPES (e.g. GAUSS for\n\n * TRIANGLES). \n\n * @tparam ELEMENT_SHAPE \n\n * @tparam QUADRATURE_RULE\n\n */\n\ntemplate<ELEMENT_SHAPE SHAPE, QUADRATURE_RULE RULE>\n", "file_path": "lib/fiber/quadrature/quadrature.hpp", "rank": 22, "score": 132687.71270744532 }, { "content": "struct BasisData\n\n{\n\n // values(i,k,l) = (f_k)_i(x_l) ->\n\n // ith component of kth basis function at lth point\n\n _3dArray<ValueType> values;\n\n // derivatives(i,j,k,l) = (d_j (f_k)_i)(x_l) ->\n\n // derivative in direction j of ith component of kth basis function at lth point\n\n _4dArray<ValueType> derivatives;\n\n\n\n int componentCount() const {\n\n return std::max<int>(values.extent(0), derivatives.extent(0));\n\n }\n\n\n\n int functionCount() const {\n\n return std::max<int>(values.extent(1), derivatives.extent(2));\n\n }\n\n\n\n int pointCount() const {\n\n return std::max<int>(values.extent(2), derivatives.extent(3));\n\n }\n\n\n\n ConstBasisDataSlice<ValueType> const_slice(int function, int point) const {\n\n return ConstBasisDataSlice<ValueType>(*this, function, point);\n\n }\n\n};\n\n\n\ntemplate <typename ValueType>\n", "file_path": "lib/fiber/basis_data.hpp", "rank": 23, "score": 132687.71270744532 }, { "content": "struct null_deleter\n\n{\n\n void operator() (const void*) const {\n\n }\n\n};\n\n\n\n/** \\brief Create a shared pointer from a reference to an object allocated on stack.\n\n\n\nThe object will not be deleted when the shared pointer goes out of scope. */\n\ntemplate <typename T>\n\ninline shared_ptr<T> make_shared_from_ref(T& t)\n\n{\n\n return shared_ptr<T>(&t, null_deleter());\n\n}\n\n\n\ntemplate <typename T>\n\ninline shared_ptr<const T> make_shared_from_const_ref(const T& t)\n\n{\n\n return shared_ptr<const T>(&t, null_deleter());\n\n}\n\n\n\n} // namespace Fiber\n\n\n\n#endif // fiber_shared_ptr_hpp\n", "file_path": "lib/fiber/shared_ptr.hpp", "rank": 24, "score": 132687.71270744532 }, { "content": "enum SpaceType { \n\n PIECEWISE_CONSTANTS,\n\n PIECEWISE_LINEARS\n\n};\n\n\n\ntemplate <typename BFT, typename RT>\n", "file_path": "tests/unit/linalg/laplace_3d_dirichlet_fixture.hpp", "rank": 25, "score": 130263.31381397537 }, { "content": "struct GetInfoFunctor1\n\n{\n\n Func f_; const Arg0& arg0_; const Arg1& arg1_;\n\n cl_int operator ()(\n\n cl_uint param, ::size_t size, void* value, ::size_t* size_ret)\n\n { return f_(arg0_, arg1_, param, size, value, size_ret); }\n\n};\n\n\n\ntemplate <typename Func, typename Arg0, typename T>\n\ninline cl_int\n\ngetInfo(Func f, const Arg0& arg0, cl_uint name, T* param)\n\n{\n\n GetInfoFunctor0<Func, Arg0> f0 = { f, arg0 };\n\n return GetInfoHelper<GetInfoFunctor0<Func, Arg0>, T>\n\n ::get(f0, name, param);\n\n}\n\n\n\ntemplate <typename Func, typename Arg0, typename Arg1, typename T>\n\ninline cl_int\n\ngetInfo(Func f, const Arg0& arg0, const Arg1& arg1, cl_uint name, T* param)\n\n{\n\n GetInfoFunctor1<Func, Arg0, Arg1> f0 = { f, arg0, arg1 };\n\n return GetInfoHelper<GetInfoFunctor1<Func, Arg0, Arg1>, T>\n\n ::get(f0, name, param);\n\n}\n\n\n\ntemplate<typename T>\n", "file_path": "lib/fiber/CL/cl.hpp", "rank": 26, "score": 129848.56585107828 }, { "content": "struct LocalSpaceArg\n\n{\n\n ::size_t size_;\n\n};\n\n\n\nnamespace detail {\n\n\n\ntemplate <typename T>\n", "file_path": "lib/fiber/CL/cl.hpp", "rank": 27, "score": 129848.56585107828 }, { "content": "struct KernelArgumentHandler\n\n{\n\n static ::size_t size(const T&) { return sizeof(T); }\n\n static T* ptr(T& value) { return &value; }\n\n};\n\n\n\ntemplate <>\n", "file_path": "lib/fiber/CL/cl.hpp", "rank": 28, "score": 129848.56585107828 }, { "content": "struct DoubleQuadratureDescriptor\n\n{\n\n ElementPairTopology topology;\n\n int testOrder;\n\n int trialOrder;\n\n\n\n bool operator<(const DoubleQuadratureDescriptor& other) const {\n\n using boost::tuples::make_tuple;\n\n return make_tuple(topology, testOrder, trialOrder) <\n\n make_tuple(other.topology, other.testOrder, other.trialOrder);\n\n }\n\n\n\n bool operator==(const DoubleQuadratureDescriptor& other) const {\n\n return topology == other.topology &&\n\n testOrder == other.testOrder &&\n\n trialOrder == other.trialOrder;\n\n }\n\n\n\n bool operator!=(const DoubleQuadratureDescriptor& other) const {\n\n return !operator==(other);\n", "file_path": "lib/fiber/numerical_quadrature.hpp", "rank": 29, "score": 129848.56585107828 }, { "content": "struct OpenClOptions\n\n{\n\n OpenClOptions ()\n\n {\n\n useOpenCl = true;\n\n }\n\n\n\n bool useOpenCl;\n\n // add more as required\n\n};\n\n\n\n}\n\n\n\n#endif\n", "file_path": "lib/fiber/opencl_options.hpp", "rank": 30, "score": 129848.56585107828 }, { "content": "struct GetInfoFunctor0\n\n{\n\n Func f_; const Arg0& arg0_;\n\n cl_int operator ()(\n\n cl_uint param, ::size_t size, void* value, ::size_t* size_ret)\n\n { return f_(arg0_, param, size, value, size_ret); }\n\n};\n\n\n\ntemplate <typename Func, typename Arg0, typename Arg1>\n", "file_path": "lib/fiber/CL/cl.hpp", "rank": 31, "score": 129848.56585107828 }, { "content": "struct GetInfoHelper\n\n{\n\n static cl_int\n\n get(Functor f, cl_uint name, T* param)\n\n {\n\n return f(name, sizeof(T), param, NULL);\n\n }\n\n};\n\n\n\n// Specialized GetInfoHelper for VECTOR_CLASS params\n\ntemplate <typename Func, typename T>\n", "file_path": "lib/fiber/CL/cl.hpp", "rank": 32, "score": 129848.56585107828 }, { "content": "struct SingleQuadratureDescriptor\n\n{\n\n int vertexCount;\n\n int order;\n\n\n\n bool operator<(const SingleQuadratureDescriptor& other) const {\n\n return std::make_pair(vertexCount, order) <\n\n std::make_pair(other.vertexCount, other.order);\n\n }\n\n\n\n bool operator==(const SingleQuadratureDescriptor& other) const {\n\n return vertexCount == other.vertexCount &&\n\n order == other.order;\n\n }\n\n\n\n bool operator!=(const SingleQuadratureDescriptor& other) const {\n\n return !operator==(other);\n\n }\n\n\n\n friend std::ostream&\n", "file_path": "lib/fiber/numerical_quadrature.hpp", "rank": 33, "score": 129848.56585107828 }, { "content": "struct AhmedTypeTraits\n\n{\n\n typedef T Type;\n\n};\n\n\n\ntemplate <>\n", "file_path": "lib/assembly/ahmed_aux_fwd.hpp", "rank": 34, "score": 129318.03197259083 }, { "content": "struct PointTraits<5>\n\n{\ttypedef Mat<double,5,1> point_type; };\n\n\n\ntemplate<>\n", "file_path": "lib/fiber/quadrature/mat.hpp", "rank": 35, "score": 127723.91219135188 }, { "content": "struct PointTraits<4>\n\n{\ttypedef Mat<double,4,1> point_type; };\n\n\n\ntemplate<>\n", "file_path": "lib/fiber/quadrature/mat.hpp", "rank": 36, "score": 127723.91219135188 }, { "content": "struct PointTraits<2>\n\n{\ttypedef Mat<double,2,1> point_type; };\n\n\n\ntemplate<>\n", "file_path": "lib/fiber/quadrature/mat.hpp", "rank": 37, "score": 127723.91219135188 }, { "content": "struct PointTraits<6>\n\n{\ttypedef Mat<double,6,1> point_type; };\n\n//@}\n\n\n\n\n\n//////////////////////////////////////////////////////////////////////\n\n// OUTPUT ////////////////////////////////////////////////////////\n\n//////////////////////////////////////////////////////////////////////\n\n\n\n/**\n\n * overloading output operator.\n\n * @tparam T value_type\n\n * @tparam NUM_ROWS number of rows\n\n * @tparam NUM_COLS number of colums\n\n * @param[out] out output-stream\n\n * @param[in] m mat to write\n\n */\n\ntemplate<typename T, int NUM_ROWS, int NUM_COLS>\n\nstd::ostream& operator << (std::ostream& out,\n\n const Mat<T,NUM_ROWS,NUM_COLS>& m)\n", "file_path": "lib/fiber/quadrature/mat.hpp", "rank": 38, "score": 127723.91219135188 }, { "content": "struct PointTraits<1>\n\n{\ttypedef Mat<double,1,1> point_type; };\n\n\n\ntemplate<>\n", "file_path": "lib/fiber/quadrature/mat.hpp", "rank": 39, "score": 127723.91219135188 }, { "content": "struct PointTraits<3>\n\n{\ttypedef Mat<double,3,1> point_type; };\n\n\n\ntemplate<>\n", "file_path": "lib/fiber/quadrature/mat.hpp", "rank": 40, "score": 127723.91219135188 }, { "content": "struct QuadratureOptions;\n\ntemplate <typename ValueType> class Basis;\n\ntemplate <typename CoordinateType> class CollectionOfBasisTransformations;\n\ntemplate <typename ValueType> class CollectionOfKernels;\n\ntemplate <typename BasisFunctionType, typename KernelType, typename ResultType>\n", "file_path": "lib/fiber/default_evaluator_for_integral_operators.hpp", "rank": 42, "score": 127172.39233947435 }, { "content": "struct ScalarTraits<double>\n\n{\n\n typedef double RealType;\n\n typedef std::complex<double> ComplexType;\n\n};\n\n\n\ntemplate <>\n", "file_path": "lib/fiber/scalar_traits.hpp", "rank": 43, "score": 124884.76533498483 }, { "content": "struct ScalarTraits<float>\n\n{\n\n typedef float RealType;\n\n typedef std::complex<float> ComplexType;\n\n};\n\n\n\ntemplate <>\n", "file_path": "lib/fiber/scalar_traits.hpp", "rank": 44, "score": 124884.76533498483 }, { "content": "struct IdentityOperator<BasisFunctionType, ResultType>::Impl\n\n{\n\n typedef Fiber::ScalarFunctionValueFunctor<CoordinateType>\n\n TransformationFunctor;\n\n\n\n Impl() : transformations(TransformationFunctor())\n\n {}\n\n\n\n Fiber::DefaultCollectionOfBasisTransformations<TransformationFunctor>\n\n transformations;\n\n};\n\n/** \\endcond */\n\n\n\ntemplate <typename BasisFunctionType, typename ResultType>\n\nIdentityOperator<BasisFunctionType, ResultType>::IdentityOperator(\n\n const shared_ptr<const Space<BasisFunctionType> >& domain,\n\n const shared_ptr<const Space<BasisFunctionType> >& range,\n\n const shared_ptr<const Space<BasisFunctionType> >& dualToRange,\n\n const std::string& label,\n\n int symmetry) :\n", "file_path": "lib/assembly/identity_operator.cpp", "rank": 45, "score": 122233.81001526414 }, { "content": "struct ReferenceHandler<cl_mem>\n\n{\n\n static cl_int retain(cl_mem memory)\n\n { return ::clRetainMemObject(memory); }\n\n static cl_int release(cl_mem memory)\n\n { return ::clReleaseMemObject(memory); }\n\n};\n\n\n\ntemplate <>\n", "file_path": "lib/fiber/CL/cl.hpp", "rank": 46, "score": 122208.5918233809 }, { "content": "struct ReferenceHandler<cl_kernel>\n\n{\n\n static cl_int retain(cl_kernel kernel)\n\n { return ::clRetainKernel(kernel); }\n\n static cl_int release(cl_kernel kernel)\n\n { return ::clReleaseKernel(kernel); }\n\n};\n\n\n\ntemplate <>\n", "file_path": "lib/fiber/CL/cl.hpp", "rank": 47, "score": 122208.5918233809 }, { "content": "struct ReferenceHandler<cl_context>\n\n{\n\n static cl_int retain(cl_context context)\n\n { return ::clRetainContext(context); }\n\n static cl_int release(cl_context context)\n\n { return ::clReleaseContext(context); }\n\n};\n\n\n\ntemplate <>\n", "file_path": "lib/fiber/CL/cl.hpp", "rank": 48, "score": 122208.5918233809 }, { "content": "struct ReferenceHandler<cl_sampler>\n\n{\n\n static cl_int retain(cl_sampler sampler)\n\n { return ::clRetainSampler(sampler); }\n\n static cl_int release(cl_sampler sampler)\n\n { return ::clReleaseSampler(sampler); }\n\n};\n\n\n\ntemplate <>\n", "file_path": "lib/fiber/CL/cl.hpp", "rank": 49, "score": 122208.5918233809 }, { "content": "struct ReferenceHandler<cl_event>\n\n{\n\n static cl_int retain(cl_event event)\n\n { return ::clRetainEvent(event); }\n\n static cl_int release(cl_event event)\n\n { return ::clReleaseEvent(event); }\n\n};\n\n\n\ntemplate <typename T>\n", "file_path": "lib/fiber/CL/cl.hpp", "rank": 50, "score": 122208.5918233809 }, { "content": "struct ReferenceHandler<cl_program>\n\n{\n\n static cl_int retain(cl_program program)\n\n { return ::clRetainProgram(program); }\n\n static cl_int release(cl_program program)\n\n { return ::clReleaseProgram(program); }\n\n};\n\n\n\ntemplate <>\n", "file_path": "lib/fiber/CL/cl.hpp", "rank": 51, "score": 122208.5918233809 }, { "content": "struct Coercion<double, double>\n\n{\n\n typedef double Type;\n\n};\n\n\n\ntemplate <>\n", "file_path": "lib/fiber/scalar_traits.hpp", "rank": 52, "score": 121106.41598731262 }, { "content": "struct Coercion<float, float>\n\n{\n\n typedef float Type;\n\n};\n\n\n\ntemplate <>\n", "file_path": "lib/fiber/scalar_traits.hpp", "rank": 53, "score": 121106.41598731262 }, { "content": "struct generate_test_case_4_num_type {\n\n explicit generate_test_case_4_num_type( const_string tc_name, Generator& G )\n\n : m_test_case_name( tc_name )\n\n , m_holder( G )\n\n {}\n\n\n\n template<typename TestType>\n\n void operator()( mpl::identity<TestType> ) {\n\n std::string full_name;\n\n assign_op( full_name, m_test_case_name, 0 );\n\n\n\n // This is the essential fragment changed wrt. boost_test_case_template.hpp\n\n std::stringstream sstream;\n\n sstream << full_name;\n\n sstream << '<';\n\n sstream << TestType::value;\n\n sstream << '>';\n\n full_name = sstream.str();\n\n\n\n m_holder.m_test_cases.push_back(\n", "file_path": "tests/unit/boost_test_case_num_template.hpp", "rank": 54, "score": 119770.36071084044 }, { "content": "struct ReferenceHandler<cl_command_queue>\n\n{\n\n static cl_int retain(cl_command_queue queue)\n\n { return ::clRetainCommandQueue(queue); }\n\n static cl_int release(cl_command_queue queue)\n\n { return ::clReleaseCommandQueue(queue); }\n\n};\n\n\n\ntemplate <>\n", "file_path": "lib/fiber/CL/cl.hpp", "rank": 55, "score": 119681.75062069544 }, { "content": "struct ReferenceHandler<cl_device_id>\n\n{\n\n // cl_device_id does not have retain().\n\n static cl_int retain(cl_device_id)\n\n { return CL_INVALID_DEVICE; }\n\n // cl_device_id does not have release().\n\n static cl_int release(cl_device_id)\n\n { return CL_INVALID_DEVICE; }\n\n};\n\n\n\ntemplate <>\n", "file_path": "lib/fiber/CL/cl.hpp", "rank": 56, "score": 119681.75062069544 }, { "content": "struct ReferenceHandler<cl_platform_id>\n\n{\n\n // cl_platform_id does not have retain().\n\n static cl_int retain(cl_platform_id)\n\n { return CL_INVALID_PLATFORM; }\n\n // cl_platform_id does not have release().\n\n static cl_int release(cl_platform_id)\n\n { return CL_INVALID_PLATFORM; }\n\n};\n\n\n\ntemplate <>\n", "file_path": "lib/fiber/CL/cl.hpp", "rank": 57, "score": 119681.75062069544 }, { "content": "struct DefaultDirectSolver<BasisFunctionType, ResultType>::Impl\n\n{\n\n Impl(const BoundaryOperator<BasisFunctionType, ResultType>& op_) :\n\n op(op_)\n\n {\n\n }\n\n\n\n Impl(const BlockedBoundaryOperator<BasisFunctionType, ResultType>& op_) :\n\n op(op_)\n\n {\n\n }\n\n \n\n boost::variant<\n\n BoundaryOperator<BasisFunctionType, ResultType>,\n\n BlockedBoundaryOperator<BasisFunctionType, ResultType> > op;\n\n};\n\n\n\n/** \\endcond */\n\n\n\ntemplate <typename BasisFunctionType, typename ResultType>\n", "file_path": "lib/linalg/default_direct_solver.cpp", "rank": 58, "score": 118338.21758936445 }, { "content": "struct DefaultIterativeSolver<BasisFunctionType, ResultType>::Impl\n\n{\n\n\n\n // Constructor for non-blocked operators\n\n Impl(const BoundaryOperator<BasisFunctionType, ResultType>& op_,\n\n ConvergenceTestMode::Mode mode_) :\n\n op(op_),\n\n mode(mode_)\n\n {\n\n typedef BoundaryOperator<BasisFunctionType, ResultType> BoundaryOp;\n\n typedef Solver<BasisFunctionType, ResultType> Solver_;\n\n const BoundaryOp& boundaryOp = boost::get<BoundaryOp>(op);\n\n if (!boundaryOp.isInitialized())\n\n throw std::invalid_argument(\"DefaultIterativeSolver::Impl::Impl(): \"\n\n \"boundary operator must be initialized\");\n\n\n\n if (mode == ConvergenceTestMode::TEST_CONVERGENCE_IN_DUAL_TO_RANGE) {\n\n if (boundaryOp.domain()->globalDofCount() !=\n\n boundaryOp.dualToRange()->globalDofCount())\n\n throw std::invalid_argument(\"DefaultIterativeSolver::Impl::Impl(): \"\n", "file_path": "lib/linalg/default_iterative_solver.cpp", "rank": 59, "score": 118338.21758936445 }, { "content": "struct KernelArgumentHandler<LocalSpaceArg>\n\n{\n\n static ::size_t size(const LocalSpaceArg& value) { return value.size_; }\n\n static void* ptr(LocalSpaceArg&) { return NULL; }\n\n};\n\n\n\n} \n\n//! \\endcond\n\n\n\ninline LocalSpaceArg\n\n__local(::size_t size)\n\n{\n\n LocalSpaceArg ret = { size };\n\n return ret;\n\n}\n\n\n", "file_path": "lib/fiber/CL/cl.hpp", "rank": 60, "score": 117292.08172787684 }, { "content": "struct PiecewiseLinearContinuousScalarBasisTraits\n\n{\n\n};\n\n\n\n// Line\n\ntemplate <typename CoordinateType, typename ValueType>\n", "file_path": "lib/fiber/piecewise_linear_continuous_scalar_basis.hpp", "rank": 61, "score": 115806.6218329503 }, { "content": "struct CompareSharedPtrsToConstAbstractBoundaryOperatorIds\n\n{\n\n bool operator()(const shared_ptr<const Bempp::AbstractBoundaryOperatorId>& a,\n\n const shared_ptr<const Bempp::AbstractBoundaryOperatorId>& b) const {\n\n return *a == *b;\n\n }\n\n};\n\n\n\n} // namespace\n\n\n\n/** \\cond PRIVATE */\n\ntemplate <typename BasisFunctionType, typename ResultType>\n", "file_path": "lib/assembly/discrete_boundary_operator_cache.cpp", "rank": 62, "score": 115753.89266808578 }, { "content": "struct ScalarSpace<BasisFunctionType>::Impl\n\n{\n\n typedef Fiber::ScalarFunctionValueFunctor<CoordinateType>\n\n TransformationFunctor;\n\n\n\n Impl() : transformations(TransformationFunctor())\n\n {}\n\n\n\n Fiber::DefaultCollectionOfBasisTransformations<TransformationFunctor>\n\n transformations;\n\n};\n\n/** \\endcond */\n\n\n\ntemplate <typename BasisFunctionType>\n\nScalarSpace<BasisFunctionType>::ScalarSpace(const shared_ptr<const Grid>& grid) :\n\n Base(grid), m_impl(new Impl)\n\n{\n\n}\n\n\n\ntemplate <typename BasisFunctionType>\n", "file_path": "lib/space/scalar_space.cpp", "rank": 63, "score": 115542.89364328989 }, { "content": "struct DiscreteBoundaryOperatorCache<BasisFunctionType, ResultType>::Impl\n\n{\n\n typedef tbb::concurrent_unordered_map<shared_ptr<const AbstractBoundaryOperatorId>,\n\n boost::weak_ptr<const DiscreteBoundaryOperator<ResultType> >,\n\n tbb::tbb_hash<shared_ptr<const AbstractBoundaryOperatorId> >,\n\n CompareSharedPtrsToConstAbstractBoundaryOperatorIds >\n\n DiscreteBoundaryOperatorMap;\n\n\n\n mutable DiscreteBoundaryOperatorMap discreteOps;\n\n};\n\n/** \\endcond */\n\n\n\ntemplate <typename BasisFunctionType, typename ResultType>\n\nDiscreteBoundaryOperatorCache<BasisFunctionType, ResultType>::\n\nDiscreteBoundaryOperatorCache() :\n\n m_impl(new Impl)\n\n{\n\n}\n\n\n\ntemplate <typename BasisFunctionType, typename ResultType>\n", "file_path": "lib/assembly/discrete_boundary_operator_cache.cpp", "rank": 64, "score": 114752.7180302841 }, { "content": "struct ImageFormat : public cl_image_format\n\n{\n\n ImageFormat(){}\n\n\n\n ImageFormat(cl_channel_order order, cl_channel_type type)\n\n {\n\n image_channel_order = order;\n\n image_channel_data_type = type;\n\n }\n\n\n\n ImageFormat& operator = (const ImageFormat& rhs)\n\n {\n\n if (this != &rhs) {\n\n this->image_channel_data_type = rhs.image_channel_data_type;\n\n this->image_channel_order = rhs.image_channel_order;\n\n }\n\n return *this;\n\n }\n\n};\n\n\n\n/*! \\class Device\n\n * \\brief Device interface for cl_device_id.\n\n */\n", "file_path": "lib/fiber/CL/cl.hpp", "rank": 65, "score": 113513.73238020463 }, { "content": "struct GetInfoHelper<Func, STRING_CLASS>\n\n{\n\n static cl_int get(Func f, cl_uint name, STRING_CLASS* param)\n\n {\n\n ::size_t required;\n\n cl_int err = f(name, 0, NULL, &required);\n\n if (err != CL_SUCCESS) {\n\n return err;\n\n }\n\n\n\n char* value = (char*) alloca(required);\n\n err = f(name, required, value, NULL);\n\n if (err != CL_SUCCESS) {\n\n return err;\n\n }\n\n\n\n *param = value;\n\n return CL_SUCCESS;\n\n }\n\n};\n\n\n\n#define __GET_INFO_HELPER_WITH_RETAIN(CPP_TYPE) \\\n\nnamespace detail { \\\n\ntemplate <typename Func> \\\n", "file_path": "lib/fiber/CL/cl.hpp", "rank": 66, "score": 113513.73238020463 }, { "content": "struct ScalarTraits<std::complex<double> >\n\n{\n\n typedef double RealType;\n\n typedef std::complex<double> ComplexType;\n\n};\n\n\n\n/** \\brief \"Larger\" of the types U and V. */\n\ntemplate <typename U, typename V>\n", "file_path": "lib/fiber/scalar_traits.hpp", "rank": 67, "score": 112931.13986015916 }, { "content": "struct ScalarTraits<std::complex<float> >\n\n{\n\n typedef float RealType;\n\n typedef std::complex<float> ComplexType;\n\n};\n\n\n\ntemplate <>\n", "file_path": "lib/fiber/scalar_traits.hpp", "rank": 68, "score": 112931.13986015916 }, { "content": "struct param_traits<detail:: token,param_name> \\\n\n{ \\\n\n enum { value = param_name }; \\\n\n typedef T param_type; \\\n\n};\n\n\n\n__PARAM_NAME_INFO_1_0(__DECLARE_PARAM_TRAITS);\n\n#if defined(CL_VERSION_1_1)\n\n__PARAM_NAME_INFO_1_1(__DECLARE_PARAM_TRAITS);\n\n#endif // CL_VERSION_1_1\n\n\n\n#if defined(USE_CL_DEVICE_FISSION)\n\n__PARAM_NAME_DEVICE_FISSION(__DECLARE_PARAM_TRAITS);\n\n#endif // USE_CL_DEVICE_FISSION\n\n\n\n#undef __DECLARE_PARAM_TRAITS\n\n\n\n// Convenience functions\n\n\n\ntemplate <typename Func, typename T>\n\ninline cl_int\n\ngetInfo(Func f, cl_uint name, T* param)\n\n{\n\n return GetInfoHelper<Func, T>::get(f, name, param);\n\n}\n\n\n\ntemplate <typename Func, typename Arg0>\n", "file_path": "lib/fiber/CL/cl.hpp", "rank": 69, "score": 110541.47096734055 }, { "content": "struct Coercion<double, std::complex<double> >\n\n{\n\n typedef std::complex<double> Type;\n\n};\n\n\n\ntemplate <>\n", "file_path": "lib/fiber/scalar_traits.hpp", "rank": 70, "score": 110531.87024296448 }, { "content": "struct Coercion<float, std::complex<float> >\n\n{\n\n typedef std::complex<float> Type;\n\n};\n\n\n\ntemplate <>\n", "file_path": "lib/fiber/scalar_traits.hpp", "rank": 71, "score": 110531.87024296448 }, { "content": "struct Coercion<std::complex<double>, double>\n\n{\n\n typedef std::complex<double> Type;\n\n};\n\n\n\n} // namespace Fiber\n\n\n\n#endif\n", "file_path": "lib/fiber/scalar_traits.hpp", "rank": 72, "score": 110531.87024296448 }, { "content": "struct Coercion<std::complex<float>, float>\n\n{\n\n typedef std::complex<float> Type;\n\n};\n\n\n\ntemplate <>\n", "file_path": "lib/fiber/scalar_traits.hpp", "rank": 73, "score": 110531.87024296448 }, { "content": "struct AhmedTypeTraits<std::complex<double> >\n\n{\n\n typedef dcomp Type;\n\n};\n\n\n\ntemplate <typename T>\n\ninline typename AhmedTypeTraits<T>::Type* ahmedCast(T* x) {\n\n#ifdef AHMED_USES_STD_COMPLEX\n\n return x;\n\n#else\n\n return reinterpret_cast<typename AhmedTypeTraits<T>::Type*>(x);\n\n#endif \n\n}\n\n\n\nfloat ahmedCast(float x);\n\ndouble ahmedCast(double x);\n\nscomp ahmedCast(std::complex<float> x);\n\ndcomp ahmedCast(std::complex<double> x);\n\n\n\n} // namespace Bempp\n\n\n\n#endif\n", "file_path": "lib/assembly/ahmed_aux_fwd.hpp", "rank": 74, "score": 110253.6388576969 }, { "content": "struct AhmedTypeTraits<std::complex<float> >\n\n{\n\n typedef scomp Type;\n\n};\n\n\n\ntemplate <>\n", "file_path": "lib/assembly/ahmed_aux_fwd.hpp", "rank": 75, "score": 110253.6388576969 }, { "content": "struct GetInfoHelper<Func, VECTOR_CLASS<T> >\n\n{\n\n static cl_int get(Func f, cl_uint name, VECTOR_CLASS<T>* param)\n\n {\n\n ::size_t required;\n\n cl_int err = f(name, 0, NULL, &required);\n\n if (err != CL_SUCCESS) {\n\n return err;\n\n }\n\n\n\n T* value = (T*) alloca(required);\n\n err = f(name, required, value, NULL);\n\n if (err != CL_SUCCESS) {\n\n return err;\n\n }\n\n\n\n param->assign(&value[0], &value[required/sizeof(T)]);\n\n return CL_SUCCESS;\n\n }\n\n};\n\n\n\n// Specialized for getInfo<CL_PROGRAM_BINARIES>\n\ntemplate <typename Func>\n", "file_path": "lib/fiber/CL/cl.hpp", "rank": 76, "score": 108278.09973447479 }, { "content": "struct AhmedDofWrapper : public Point3D<CoordinateType>\n\n{\n\n CoordinateType getcenter(int dim) const\n\n {\n\n switch (dim)\n\n {\n\n case 0: return this->x;\n\n case 1: return this->y;\n\n case 2: return this->z;\n\n default:\n\n throw std::invalid_argument(\"AhmedDofWrapper::getcenter(): \"\n\n \"invalid dimension index\");\n\n }\n\n }\n\n};\n\n\n\ntemplate <typename T>\n", "file_path": "lib/assembly/ahmed_aux.hpp", "rank": 77, "score": 108055.94943421069 }, { "content": "struct size_t : public cl::vector< ::size_t, N> { };\n\n\n\nnamespace detail {\n\n\n\n// GetInfo help struct\n\ntemplate <typename Functor, typename T>\n", "file_path": "lib/fiber/CL/cl.hpp", "rank": 78, "score": 106164.79862120884 }, { "content": "// Copyright (C) 2011-2012 by the BEM++ Authors\n\n//\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n\n// of this software and associated documentation files (the \"Software\"), to deal\n\n// in the Software without restriction, including without limitation the rights\n\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\n// copies of the Software, and to permit persons to whom the Software is\n\n// furnished to do so, subject to the following conditions:\n\n//\n\n// The above copyright notice and this permission notice shall be included in\n\n// all copies or substantial portions of the Software.\n\n//\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\n// THE SOFTWARE.\n\n\n\n#ifndef fiber_types_hpp\n\n#define fiber_types_hpp\n\n\n\n#include \"../common/common.hpp\"\n\n\n\nnamespace Fiber\n\n{\n\n\n", "file_path": "lib/fiber/types.hpp", "rank": 79, "score": 105905.55292845913 }, { "content": "struct Coercion<std::complex<float>, std::complex<float> >\n\n{\n\n typedef std::complex<float> Type;\n\n};\n\n\n\ntemplate <>\n", "file_path": "lib/fiber/scalar_traits.hpp", "rank": 80, "score": 102243.61693498399 }, { "content": "struct Coercion<std::complex<double>, std::complex<double> >\n\n{\n\n typedef std::complex<double> Type;\n\n};\n\n\n\ntemplate <>\n", "file_path": "lib/fiber/scalar_traits.hpp", "rank": 81, "score": 102243.61693498399 }, { "content": "class QuadratureStrategy<BasisFunctionType, ResultType, GeometryFactory,\n\n typename boost::enable_if<boost::is_same<ResultType, typename ScalarTraits<ResultType>::RealType> >::type > :\n\n public QuadratureStrategyBase<BasisFunctionType, ResultType, GeometryFactory>\n\n{\n\n typedef QuadratureStrategyBase<BasisFunctionType, ResultType, GeometryFactory> Base;\n\npublic:\n\n typedef typename Base::CoordinateType CoordinateType;\n\n};\n\n/** \\endcond */\n\n\n\n} // namespace Fiber\n\n\n\n#endif\n", "file_path": "lib/fiber/quadrature_strategy.hpp", "rank": 82, "score": 93584.51750964939 }, { "content": " def test_type_returns_a_GeometryType_for_codim(self, codim):\n\n entity = self.get_entity(codim)\n", "file_path": "python/tests/unit/test_entity.py", "rank": 83, "score": 91750.94650204162 }, { "content": "class ConstGeometricalDataSlice\n\n{\n\npublic:\n\n ConstGeometricalDataSlice(const GeometricalData<CoordinateType>& geomData,\n\n int point) :\n\n m_geomData(geomData), m_point(point) {}\n\n\n\n CoordinateType global(int dim) const {\n\n return m_geomData.globals(dim, m_point);\n\n }\n\n CoordinateType integrationElement() const {\n\n return m_geomData.integrationElements(m_point);\n\n }\n\n CoordinateType jacobianTransposed(int row, int col) const {\n\n return m_geomData.jacobiansTransposed(row, col, m_point);\n\n }\n\n CoordinateType jacobianInverseTransposed(int row, int col) const {\n\n return m_geomData.jacobianInversesTransposed(row, col, m_point);\n\n }\n\n CoordinateType normal(int dim) const {\n", "file_path": "lib/fiber/geometrical_data.hpp", "rank": 84, "score": 90755.29890967123 }, { "content": "class ConstBasisDataSlice\n\n{\n\npublic:\n\n ConstBasisDataSlice(const BasisData<ValueType>& basisData,\n\n int function, int point) :\n\n m_basisData(basisData), m_function(function), m_point(point) {}\n\n\n\n ValueType values(int dim) const {\n\n return m_basisData.values(dim, m_function, m_point);\n\n }\n\n\n\n ValueType derivatives(int dim, int direction) const {\n\n return m_basisData.derivatives(dim, direction, m_function, m_point);\n\n }\n\n\n\n int componentCount() const {\n\n return m_basisData.componentCount();\n\n }\n\n\n\nprivate:\n\n const BasisData<ValueType>& m_basisData;\n\n int m_function, m_point;\n\n};\n\n\n\n} // namespace Fiber\n\n\n\n#endif // BASIS_DATA_TYPES_HPP\n", "file_path": "lib/fiber/basis_data.hpp", "rank": 85, "score": 90755.29890967123 }, { "content": "enum Symmetry\n\n{\n\n NO_SYMMETRY = 0x0000,\n\n SYMMETRIC = 0x0001,\n\n HERMITIAN = 0x0002,\n\n AUTO_SYMMETRY = 0x8000\n\n};\n\n\n\n} // namespace Bempp\n\n\n\n#endif\n", "file_path": "lib/assembly/symmetry.hpp", "rank": 86, "score": 89873.84779439632 }, { "content": "enum TranspositionMode\n\n{\n\n#ifdef WITH_TRILINOS\n\n /** \\brief Use the non-transposed operator. */\n\n NO_TRANSPOSE = Thyra::NOTRANS,\n\n /** \\brief Use the non-transposed operator with complex-conjugated elements\n\n * (same as \\c NO_TRANSPOSE for operators with real elements). */\n\n CONJUGATE = Thyra::CONJ,\n\n /** \\brief Use the transposed operator. */\n\n TRANSPOSE = Thyra::TRANS,\n\n /** \\brief Use the transposed operator with complex-conjugated elements\n\n * (same as \\c TRANSPOSE for operators with real elements). */\n\n CONJUGATE_TRANSPOSE = Thyra::CONJTRANS\n\n#else\n\n NO_TRANSPOSE,\n\n CONJUGATE,\n\n TRANSPOSE,\n\n CONJUGATE_TRANSPOSE\n\n#endif\n\n};\n\n\n\n} // namespace Bempp\n\n\n\n#endif\n", "file_path": "lib/assembly/transposition_mode.hpp", "rank": 87, "score": 86676.22155720726 }, { "content": "struct GridParameters {\n\n /** \\brief %Grid topology */\n\n enum Topology {\n\n /** \\brief one-dimensional grid embedded in a two-dimensional space */\n\n LINEAR,\n\n /** \\brief two-dimensional grid composed of triangular elements,\n\n embedded in a three-dimensional space */\n\n TRIANGULAR,\n\n /** \\brief two-dimensional grid composed of quadrilateral elements,\n\n embedded in a three-dimensional space */\n\n QUADRILATERAL,\n\n /** \\brief two-dimensional grid composed (potentially) both of\n\n triangular and quadrilateral elements, embedded in a\n\n three-dimensional space */\n\n HYBRID_2D,\n\n /** \\brief three-dimensional grid composed of tetrahedral elements,\n\n embedded in a three-dimensional space*/\n\n TETRAHEDRAL\n\n } topology;\n\n};\n\n\n\n} // namespace Bempp\n\n\n\n#endif\n", "file_path": "lib/grid/grid_parameters.hpp", "rank": 88, "score": 85719.66516213119 }, { "content": "struct AcaOptions\n\n{\n\n /** \\brief Initialize ACA parameters to default values. */\n\n AcaOptions();\n\n\n\n /** \\brief Estimate of the desired approximation accuracy.\n\n *\n\n * Default value: 1e-4. */\n\n double eps;\n\n /** \\brief Cluster-pair admissibility parameter.\n\n *\n\n * Default value: 1.2. */\n\n double eta;\n\n /** \\brief Minimum size of blocks approximated with ACA.\n\n *\n\n * Matrix blocks whose smaller side is less than this value will be stored\n\n * in the dense format (ACA will not be attempted on these blocks).\n\n *\n\n * Default value: 16. */\n\n unsigned int minimumBlockSize;\n", "file_path": "lib/assembly/assembly_options.hpp", "rank": 89, "score": 85719.66516213119 }, { "content": "struct ConvergenceTestMode {\n\n enum Mode {\n\n TEST_CONVERGENCE_IN_DUAL_TO_RANGE,\n\n TEST_CONVERGENCE_IN_RANGE\n\n };\n\n};\n\n\n\n/** \\ingroup linalg\n\n * \\brief An abstract interface for various types of solvers\n\n *\n\n * This class is an interface to the solution of linear systems in BEM++.\n\n * Concrete subclasses implement specific linear solvers.\n\n *\n\n */\n\n\n\ntemplate <typename BasisFunctionType, typename ResultType>\n", "file_path": "lib/linalg/solver.hpp", "rank": 90, "score": 85719.66516213119 }, { "content": "struct SolutionStatus {\n\n enum Status {\n\n CONVERGED,\n\n UNCONVERGED,\n\n UNKNOWN};\n\n};\n\n\n\n/** \\ingroup linalg\n\n * \\brief The base class for the Solution and BlockedSolution container classes.\n\n *\n\n * This class holds various information about the solution of a BEM computation. It derives from\n\n * <a href=\"http://trilinos.sandia.gov/packages/docs/r10.10/packages/thyra/doc/html/structThyra_1_1SolveStatus.html\">Thyra::SolveStatus</a>\n\n * if Trilinos is enabled.\n\n *\n\n * <tt>MagnitudeType</tt> is identical to <tt>float</tt> if <tt>ResultType</tt> is <tt>float</tt> or <tt>complex<float></tt>. It is double\n\n * if <tt>ResultType</tt> is <tt>double</tt> or <tt>complex<double></tt>\n\n */\n\n\n\ntemplate <typename BasisFunctionType, typename ResultType>\n", "file_path": "lib/linalg/solution_base.hpp", "rank": 91, "score": 85719.66516213119 }, { "content": "struct ChunkStatistics\n\n{\n\n ChunkStatistics() : valid(false) {}\n\n bool valid;\n\n size_t chunkStart;\n\n size_t chunkSize;\n\n tbb::tick_count startTime;\n\n tbb::tick_count endTime;\n\n};\n\n\n\n} // namespace Bempp\n\n\n\n#endif\n", "file_path": "lib/common/chunk_statistics.hpp", "rank": 92, "score": 85719.66516213119 }, { "content": "struct CreateOperator_3_I\n\n{\n\n BoundaryOperator<BasisFunctionType, ResultType> operator() (\n\n const shared_ptr<const Context<BasisFunctionType, ResultType> >& context,\n\n const shared_ptr<const Space<BasisFunctionType> >& domain,\n\n const shared_ptr<const Space<BasisFunctionType> >& range,\n\n const shared_ptr<const Space<BasisFunctionType> >& dualToRange) const\n\n {\n\n return 3. * identityOperator<BasisFunctionType, ResultType>(\n\n context, domain, range, dualToRange);\n\n }\n\n};\n\n\n\ntemplate <typename BasisFunctionType, typename ResultType>\n", "file_path": "tests/unit/assembly/test_joint_assembly.cpp", "rank": 93, "score": 82900.41519583325 }, { "content": "struct MblockArrayConverter\n\n{\n\n static void convert(\n\n unsigned int n,\n\n const boost::shared_array<mblock<FromType> *>& in,\n\n boost::shared_array<mblock<ToType> *>& out) {\n\n out = allocateAhmedMblockArray<ToType>(n);\n\n copyH(n, in.get(), out.get());\n\n }\n\n};\n\n\n\ntemplate <typename Type>\n", "file_path": "lib/assembly/sparse_to_h_matrix_converter.cpp", "rank": 94, "score": 82900.41519583325 }, { "content": "struct UnitFunctor\n\n{\n\n typedef ValueType_ ValueType;\n\n typedef typename ScalarTraits<ValueType>::RealType CoordinateType;\n\n\n\n int argumentDimension() const { return 3; }\n\n int resultDimension() const { return 1; }\n\n\n\n void evaluate(const arma::Col<CoordinateType>& point,\n\n arma::Col<ValueType>& result) const {\n\n result(0) = 1.;\n\n }\n\n};\n\n\n", "file_path": "tests/unit/linalg/laplace_3d_dirichlet_fixture.hpp", "rank": 95, "score": 82900.41519583325 }, { "content": "struct ClusterConstructionHelper\n\n{\n\n typedef typename Fiber::ScalarTraits<BasisFunctionType>::RealType CoordinateType;\n\n typedef AhmedDofWrapper<CoordinateType> AhmedDofType;\n\n typedef ExtendedBemCluster<AhmedDofType> AhmedBemCluster;\n\n typedef bemblcluster<AhmedDofType, AhmedDofType> AhmedBemBlcluster;\n\n\n\n static void constructBemCluster(\n\n const Space<BasisFunctionType>& space,\n\n bool indexWithGlobalDofs,\n\n const AcaOptions& acaOptions,\n\n shared_ptr<AhmedBemCluster>& cluster,\n\n shared_ptr<IndexPermutation>& o2p,\n\n shared_ptr<IndexPermutation>& p2o);\n\n\n\n static std::auto_ptr<AhmedBemBlcluster>\n\n constructBemBlockCluster(\n\n const AcaOptions& acaOptions,\n\n bool symmetric,\n\n /* input parameter (effectively const */\n", "file_path": "lib/assembly/cluster_construction_helper.hpp", "rank": 96, "score": 82900.41519583325 }, { "content": "struct CreateOperator_I\n\n{\n\n BoundaryOperator<BasisFunctionType, ResultType> operator() (\n\n const shared_ptr<const Context<BasisFunctionType, ResultType> >& context,\n\n const shared_ptr<const Space<BasisFunctionType> >& domain,\n\n const shared_ptr<const Space<BasisFunctionType> >& range,\n\n const shared_ptr<const Space<BasisFunctionType> >& dualToRange) const\n\n {\n\n return identityOperator<BasisFunctionType, ResultType>(\n\n context, domain, range, dualToRange);\n\n }\n\n};\n\n\n\ntemplate <typename BasisFunctionType, typename ResultType>\n", "file_path": "tests/unit/assembly/test_joint_assembly.cpp", "rank": 97, "score": 82900.41519583325 }, { "content": "struct CreateOperator_V\n\n{\n\n BoundaryOperator<BasisFunctionType, ResultType> operator() (\n\n const shared_ptr<const Context<BasisFunctionType, ResultType> >& context,\n\n const shared_ptr<const Space<BasisFunctionType> >& domain,\n\n const shared_ptr<const Space<BasisFunctionType> >& range,\n\n const shared_ptr<const Space<BasisFunctionType> >& dualToRange) const\n\n {\n\n return laplace3dSingleLayerBoundaryOperator<BasisFunctionType, ResultType>(\n\n context, domain, range, dualToRange);\n\n }\n\n};\n\n\n\ntemplate <typename BasisFunctionType, typename ResultType>\n", "file_path": "tests/unit/assembly/test_joint_assembly.cpp", "rank": 98, "score": 81608.77726725866 }, { "content": "struct SparseToHMatrixConverter\n\n{\n\n typedef typename Fiber::ScalarTraits<ValueType>::RealType CoordinateType;\n\n typedef AhmedDofWrapper<CoordinateType> AhmedDofType;\n\n typedef bemblcluster<AhmedDofType, AhmedDofType> AhmedBemBlcluster;\n\n typedef mblock<typename AhmedTypeTraits<ValueType>::Type> AhmedMblock;\n\n\n\n static void constructHMatrix(\n\n int* rowOffsets, int* colIndices, double* values,\n\n std::vector<unsigned int>& domain_o2p,\n\n std::vector<unsigned int>& range_p2o,\n\n double eps,\n\n AhmedBemBlcluster* blockCluster,\n\n boost::shared_array<AhmedMblock*>& mblocks,\n\n int& maximumRank);\n\n};\n\n\n\n} // namespace Bempp\n\n\n\n#endif // WITH_AHMED\n\n\n\n#endif\n", "file_path": "lib/assembly/sparse_to_h_matrix_converter.hpp", "rank": 99, "score": 81608.77726725866 } ]
C++
src/automaton/core/testnet/testnet.cc
sept-en/automaton
b7448dfe578cf52df37ec7c86536d1e51017c548
#include "automaton/core/testnet/testnet.h" #include <set> #include "automaton/core/io/io.h" #include "automaton/core/node/node.h" namespace automaton { namespace core { namespace testnet { static const uint32_t STARTING_PORT = 12300; std::unordered_map<std::string, std::shared_ptr<testnet>> testnet::testnets; bool testnet::create_testnet(const std::string& node_type, const std::string& id, const std::string& smart_protocol_id, network_protocol_type ntype, uint32_t number_nodes, std::unordered_map<uint32_t, std::vector<uint32_t> > peer_list) { auto it = testnets.find(id); if (it != testnets.end()) { LOG(ERROR) << "Testnet with id " << id << " already exists!"; return false; } auto net = std::unique_ptr<testnet>(new testnet(node_type, id, smart_protocol_id, ntype, number_nodes)); bool initialised = net->init(); if (!initialised) { LOG(ERROR) << "Testnet " << id << " initialization failed!"; return false; } net->connect(peer_list); testnets[id] = std::move(net); return true; } void testnet::destroy_testnet(const std::string& id) { auto it = testnets.find(id); if (it != testnets.end()) { testnets.erase(it); } } std::shared_ptr<testnet> testnet::get_testnet(const std::string& id) { auto it = testnets.find(id); if (it != testnets.end()) { return it->second; } return nullptr; } std::vector<std::string> testnet::list_testnets() { std::vector<std::string> result; for (auto it = testnets.begin(); it != testnets.end(); it++) { result.push_back(it->first); } return result; } testnet::~testnet() { for (uint32_t i = 0; i < node_ids_list.size(); ++i) { automaton::core::node::node::remove_node(node_ids_list[i]); } } void testnet::connect(const std::unordered_map<uint32_t, std::vector<uint32_t> >& peers_list) const { std::string id = network_id + "_"; std::string address = ""; uint32_t port = 0; if (network_type == network_protocol_type::localhost) { address = "tcp://127.0.0.1:"; port = STARTING_PORT; } else { address = "sim://1:20:10000:"; } for (auto it = peers_list.begin(); it != peers_list.end(); it++) { std::stringstream nid; nid << id << it->first; std::shared_ptr<automaton::core::node::node> n = automaton::core::node::node::get_node(nid.str()); if (n == nullptr) { LOG(ERROR) << "No such node: " << nid.str(); continue; } const std::vector<uint32_t>& peers = it->second; for (uint32_t i = 0; i < peers.size(); ++i) { std::stringstream ss; ss << address << (port + peers[i]); uint32_t pid = n->add_peer(ss.str()); n->connect(pid); } } } std::vector<std::string> testnet::list_nodes() { return node_ids_list; } testnet::testnet(const std::string& node_type, const std::string& id, const std::string& smart_protocol_id, network_protocol_type ntype, uint32_t number_nodes): node_type(node_type), network_id(id), protocol_id(smart_protocol_id), network_type(ntype), number_nodes(number_nodes), node_ids_list(number_nodes, "") {} bool testnet::init() { std::string address = ""; uint32_t port = 0; if (network_type == network_protocol_type::localhost) { address = "tcp://127.0.0.1:"; port = STARTING_PORT; } else { address = "sim://100:10000:"; } for (uint32_t i = 1; i <= number_nodes; ++i) { std::string node_id = network_id + "_" + std::to_string(i); bool res = automaton::core::node::node::launch_node(node_type, node_id, protocol_id, address + std::to_string(port + i)); if (!res) { return false; } node_ids_list[i-1] = node_id; } return true; } std::unordered_map<uint32_t, std::vector<uint32_t> > create_connections_vector(uint32_t n, uint32_t p) { std::unordered_map<uint32_t, std::vector<uint32_t> > result; if (p >= ((n + 1) / 2)) { LOG(ERROR) << "'p' is too big! Setting 'p' to max valid number of peers for 'n' = " << n << " : " << ((n + 1) / 2 - 1); return result; } for (uint32_t i = 1; i <= n; ++i) { std::vector<uint32_t> peers; for (uint32_t j = 0; j < p; ++j) { peers.push_back((i + j) % n + 1); } result[i] = std::move(peers); } return result; } std::unordered_map<uint32_t, std::vector<uint32_t> > create_rnd_connections_vector(uint32_t n, uint32_t p) { std::unordered_map<uint32_t, std::vector<uint32_t> > result; uint32_t k; if (p >= ((n + 1) / 2)) { LOG(ERROR) << "'p' is too big! Setting 'p' to max valid number of peers for 'n' = " << n << " : " << ((n + 1) / 2 - 1); return result; } for (uint32_t i = 1; i <= n; ++i) { std::set<uint32_t> peers; while (peers.size() < p) { k = std::rand() % n + 1; if (k == i) {continue;} peers.insert(k); } result[i] = std::vector<uint32_t>(peers.begin(), peers.end()); } return result; } } } }
#include "automaton/core/testnet/testnet.h" #include <set> #include "automaton/core/io/io.h" #include "automaton/core/node/node.h" namespace automaton { namespace core { namespace testnet { static const uint32_t STARTING_PORT = 12300; std::unordered_map<std::string, std::shared_ptr<testnet>> testnet::testnets; bool testnet::create_testnet(const std::string& node_type, const std::string& id, const std::string& smart_protocol_id, network_protocol_type ntype, uint32_t number_nodes, std::unordered_map<uint32_t, std::vector<uint32_t> > peer_list) { auto it = testnets.find(id); if (it != testnets.end()) { LOG(ERROR) << "Testnet with id " << id << " already exists!"; return false; } auto net = std::unique_ptr<testnet>(new testnet(node_type, id, smart_protocol_id, ntype, number_nodes)); bool initialised = net->init(); if (!initialised) { LOG(ERROR) << "Testnet " << id << " initialization failed!"; return false; } net->connect(peer_list); testnets
= ""; uint32_t port = 0; if (network_type == network_protocol_type::localhost) { address = "tcp://127.0.0.1:"; port = STARTING_PORT; } else { address = "sim://100:10000:"; } for (uint32_t i = 1; i <= number_nodes; ++i) { std::string node_id = network_id + "_" + std::to_string(i); bool res = automaton::core::node::node::launch_node(node_type, node_id, protocol_id, address + std::to_string(port + i)); if (!res) { return false; } node_ids_list[i-1] = node_id; } return true; } std::unordered_map<uint32_t, std::vector<uint32_t> > create_connections_vector(uint32_t n, uint32_t p) { std::unordered_map<uint32_t, std::vector<uint32_t> > result; if (p >= ((n + 1) / 2)) { LOG(ERROR) << "'p' is too big! Setting 'p' to max valid number of peers for 'n' = " << n << " : " << ((n + 1) / 2 - 1); return result; } for (uint32_t i = 1; i <= n; ++i) { std::vector<uint32_t> peers; for (uint32_t j = 0; j < p; ++j) { peers.push_back((i + j) % n + 1); } result[i] = std::move(peers); } return result; } std::unordered_map<uint32_t, std::vector<uint32_t> > create_rnd_connections_vector(uint32_t n, uint32_t p) { std::unordered_map<uint32_t, std::vector<uint32_t> > result; uint32_t k; if (p >= ((n + 1) / 2)) { LOG(ERROR) << "'p' is too big! Setting 'p' to max valid number of peers for 'n' = " << n << " : " << ((n + 1) / 2 - 1); return result; } for (uint32_t i = 1; i <= n; ++i) { std::set<uint32_t> peers; while (peers.size() < p) { k = std::rand() % n + 1; if (k == i) {continue;} peers.insert(k); } result[i] = std::vector<uint32_t>(peers.begin(), peers.end()); } return result; } } } }
[id] = std::move(net); return true; } void testnet::destroy_testnet(const std::string& id) { auto it = testnets.find(id); if (it != testnets.end()) { testnets.erase(it); } } std::shared_ptr<testnet> testnet::get_testnet(const std::string& id) { auto it = testnets.find(id); if (it != testnets.end()) { return it->second; } return nullptr; } std::vector<std::string> testnet::list_testnets() { std::vector<std::string> result; for (auto it = testnets.begin(); it != testnets.end(); it++) { result.push_back(it->first); } return result; } testnet::~testnet() { for (uint32_t i = 0; i < node_ids_list.size(); ++i) { automaton::core::node::node::remove_node(node_ids_list[i]); } } void testnet::connect(const std::unordered_map<uint32_t, std::vector<uint32_t> >& peers_list) const { std::string id = network_id + "_"; std::string address = ""; uint32_t port = 0; if (network_type == network_protocol_type::localhost) { address = "tcp://127.0.0.1:"; port = STARTING_PORT; } else { address = "sim://1:20:10000:"; } for (auto it = peers_list.begin(); it != peers_list.end(); it++) { std::stringstream nid; nid << id << it->first; std::shared_ptr<automaton::core::node::node> n = automaton::core::node::node::get_node(nid.str()); if (n == nullptr) { LOG(ERROR) << "No such node: " << nid.str(); continue; } const std::vector<uint32_t>& peers = it->second; for (uint32_t i = 0; i < peers.size(); ++i) { std::stringstream ss; ss << address << (port + peers[i]); uint32_t pid = n->add_peer(ss.str()); n->connect(pid); } } } std::vector<std::string> testnet::list_nodes() { return node_ids_list; } testnet::testnet(const std::string& node_type, const std::string& id, const std::string& smart_protocol_id, network_protocol_type ntype, uint32_t number_nodes): node_type(node_type), network_id(id), protocol_id(smart_protocol_id), network_type(ntype), number_nodes(number_nodes), node_ids_list(number_nodes, "") {} bool testnet::init() { std::string address
random
[ { "content": "class testnet {\n\n public:\n\n enum network_protocol_type {\n\n localhost = 1,\n\n simulation = 2\n\n };\n\n\n\n ~testnet();\n\n\n\n static bool create_testnet(const std::string& node_type, const std::string& id, const std::string& smart_protocol_id,\n\n network_protocol_type ntype, uint32_t number_nodes, std::unordered_map<uint32_t,\n\n std::vector<uint32_t> > peer_list);\n\n\n\n static void destroy_testnet(const std::string& id);\n\n\n\n static std::shared_ptr<testnet> get_testnet(const std::string& id);\n\n\n\n static std::vector<std::string> list_testnets();\n\n\n\n void connect(const std::unordered_map<uint32_t, std::vector<uint32_t> >& peers_list) const;\n", "file_path": "src/automaton/core/testnet/testnet.h", "rank": 0, "score": 144806.9425492996 }, { "content": "function rpc_testnet_get_node_id(m)\n\n local request = TestNetGetNodeID()\n\n request:deserialize(m)\n\n local response = NodeID()\n\n response.node_id = get_testnet_node_id(request.testnet_id, request.node_index)\n\n return response:serialize()\n", "file_path": "src/automaton/core/core.lua", "rank": 1, "score": 142168.56568530062 }, { "content": "function disconnect(node_id, peer_ids)\n\n local node = get_node(node_id)\n\n if node == nil then\n\n return \"\"\n\n end\n\n for _,id in ipairs(peer_ids) do\n\n node:disconnect(id)\n\n end\n\n return \"\"\n\nend\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 2, "score": 110053.42286049656 }, { "content": "function connect(node_id, peer_ids)\n\n print(\"getting node \" .. node_id)\n\n local node = get_node(node_id)\n\n if node == nil then\n\n return \"\"\n\n end\n\n for _,id in ipairs(peer_ids) do\n\n node:connect(id)\n\n end\n\n return \"\"\n\nend\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 3, "score": 110053.42286049656 }, { "content": "#ifndef AUTOMATON_CORE_TESTNET_TESTNET_H_\n\n#define AUTOMATON_CORE_TESTNET_TESTNET_H_\n\n\n\n#include <memory>\n\n#include <string>\n\n#include <unordered_map>\n\n#include <utility>\n\n#include <vector>\n\n\n\nnamespace automaton {\n\nnamespace core {\n\nnamespace testnet {\n\n\n", "file_path": "src/automaton/core/testnet/testnet.h", "rank": 4, "score": 109307.50131997446 }, { "content": "\n\nstd::unordered_map<uint32_t, std::vector<uint32_t> > create_connections_vector(uint32_t n, uint32_t p);\n\nstd::unordered_map<uint32_t, std::vector<uint32_t> > create_rnd_connections_vector(uint32_t n, uint32_t p);\n\n\n\n} // namespace testnet\n\n} // namespace core\n\n} // namespace automaton\n\n\n\n#endif // AUTOMATON_CORE_TESTNET_TESTNET_H_\n", "file_path": "src/automaton/core/testnet/testnet.h", "rank": 5, "score": 109299.4143957997 }, { "content": "\n\n std::vector<std::string> list_nodes();\n\n\n\n private:\n\n static std::unordered_map<std::string, std::shared_ptr<testnet>> testnets;\n\n\n\n std::string node_type;\n\n std::string network_id;\n\n std::string protocol_id;\n\n network_protocol_type network_type;\n\n uint32_t number_nodes;\n\n std::vector<std::string> node_ids_list; // <network_id>_1, <network_id>_2, ...\n\n\n\n testnet(const std::string& node_type, const std::string& id, const std::string& smart_protocol_id,\n\n network_protocol_type ntype, uint32_t number_nodes);\n\n\n\n bool init();\n\n};\n\n\n\n// Helper functions\n", "file_path": "src/automaton/core/testnet/testnet.h", "rank": 6, "score": 109298.82802599936 }, { "content": "function remove_peers(node_id, peer_ids)\n\n local node = get_node(node_id)\n\n if node == nil then\n\n return \"\"\n\n end\n\n for _,id in ipairs(peer_ids) do\n\n node:remove_peer(id)\n\n print(\"removed \" .. tostring(id))\n\n end\n\n return \"\"\n\nend\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 7, "score": 108561.66097982852 }, { "content": "function get_peers(node_id, peer_ids)\n\n local node = get_node(node_id)\n\n if node == nil then\n\n return \"\"\n\n end\n\n local response = PeersList()\n\n response.node_id = node_id\n\n for _,id in ipairs(peer_ids) do\n\n local p = Peer()\n\n p.id = id\n\n p.address = node:get_peer_address(id)\n\n response.peers = p\n\n end\n\n return response:serialize()\n\nend\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 8, "score": 108561.66097982852 }, { "content": "function rpc_start_testnet(m)\n\n local request = Network()\n\n request:deserialize(m)\n\n if (request.is_localhost) then\n\n testnet(localhost, _G[request.protocol_id], request.number_nodes, request.number_peers_per_node, request.logging_path)\n\n else\n\n testnet(simulation, _G[request.protocol_id], request.number_nodes, request.number_peers_per_node, request.logging_path)\n\n end\n\n return \"\"\n\nend\n", "file_path": "src/automaton/core/core.lua", "rank": 18, "score": 102507.06342568771 }, { "content": "function rpc_testnet_destroy(m)\n\n local request = TestNetID()\n\n request:deserialize(m)\n\n testnet_destroy(request.testnet_id)\n\n return \"\"\n\nend\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 19, "score": 102507.06342568771 }, { "content": "function rpc_testnet_create(m)\n\n local request = TestNetCreate()\n\n request:deserialize(m)\n\n local peers_list = {}\n\n for _,v in pairs(request.topology) do\n\n peers_list[v.from_node] = v.to_node\n\n end\n\n testnet_create(request.testnet_id, request.protocol_id, request.network_type, request.number_nodes, peers_list)\n\n return \"\"\n\nend\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 20, "score": 102507.06342568771 }, { "content": "function get_protocols(ids)\n\n local protocols = get_core_supported_protocols()\n\n local response = ProtocolsList()\n\n for _,id in ipairs(ids) do\n\n local p = protocols[id] -- p -> std::vector<std::pair<std::string, std::string> >\n\n if p ~= nil then\n\n local m = Protocol()\n\n m.protocol_id = id\n\n for k,v in pairs(p) do\n\n m.file_names = k\n\n m.files = v\n\n end\n\n response.protocols = m\n\n end\n\n end\n\n return response:serialize()\n\nend\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 21, "score": 102466.19633702708 }, { "content": "function remove_nodes(node_ids)\n\n\n\nend\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 22, "score": 100665.65353248196 }, { "content": "function get_nodes(node_ids)\n\n local response = NodesList()\n\n for _,id in ipairs(node_ids) do\n\n local node = get_node(id)\n\n if (node ~= nil) then\n\n local n = Node()\n\n n.id = node:get_id()\n\n n.protocol_id = node:get_protocol_id()\n\n n.address = node:get_address()\n\n print(\"node \" .. n.id .. \" -> \" .. n.protocol_id .. \" -> \" .. n.address)\n\n response.nodes = n\n\n end\n\n end\n\n return response:serialize()\n\nend\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 23, "score": 100665.65353248196 }, { "content": "function get_nodes_from_testnet(testnet_id)\n\n if networks[testnet_id] ~= nil then\n\n return networks[testnet_id][\"nodes\"]\n\n end\n\n print(\"NO NODES @ PATH \" .. testnet_id)\n\n return nil\n\nend\n", "file_path": "src/automaton/examples/smartproto/common/network.lua", "rank": 24, "score": 100636.59593931846 }, { "content": "function sent(peer_id, msg_id, success)\n\nend\n", "file_path": "src/automaton/tests/testnet/testproto/chat.lua", "rank": 25, "score": 99002.48961835624 }, { "content": "function list_connected_peers(node_id)\n\n local node = get_node(node_id)\n\n if node == nil then\n\n return \"\"\n\n end\n\n local response = PeerIdsList()\n\n local list = node:peers()\n\n print(\"connected peers to \" .. node_id .. \" ::\")\n\n for _,id in ipairs(list) do\n\n response.peer_ids = id\n\n print(id)\n\n end\n\n return response:serialize()\n\nend\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 26, "score": 98930.50237028612 }, { "content": "function list_known_peers(node_id)\n\n local node = get_node(node_id)\n\n if node == nil then\n\n return \"\"\n\n end\n\n local response = PeerIdsList()\n\n local list = node:known_peers()\n\n print(\"known peers to \" .. node_id .. \" ::\")\n\n for _,id in ipairs(list) do\n\n response.peer_ids = id\n\n print(id)\n\n end\n\n return response:serialize()\n\nend\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 27, "score": 98930.50237028612 }, { "content": "function add_peers(node_id, peer_addresses)\n\n local node = get_node(node_id)\n\n if node == nil then\n\n return \"\"\n\n end\n\n local response = PeersList()\n\n response.node_id = node_id\n\n for _,addr in ipairs(peer_addresses) do\n\n local p = Peer()\n\n p.id = node:add_peer(addr)\n\n print(\"added \" .. tostring(p.id))\n\n p.address = addr\n\n response.peers = p\n\n end\n\n return response:serialize()\n\nend\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 28, "score": 97257.09573288659 }, { "content": "function process_cmd(node_id, cmd, params)\n\n local node = get_node(node_id)\n\n if node == nil then\n\n return \"\"\n\n end\n\n local response = NodeCmdResponse()\n\n response.response = node:process_cmd(cmd, params)\n\n return response:serialize()\n\nend\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 29, "score": 97257.09573288659 }, { "content": "function disconnected(peer_id)\n\n peers[peer_id] = nil\n\nend\n\n\n", "file_path": "src/automaton/tests/testnet/testproto/connections.lua", "rank": 30, "score": 92924.71485703217 }, { "content": "function connected(peer_id)\n\n peers[peer_id] = { name = \"N/A\" }\n\n hi = Hello()\n\n hi.name = nodeid\n\n send(peer_id, hi, 1)\n\nend\n\n\n", "file_path": "src/automaton/tests/testnet/testproto/connections.lua", "rank": 31, "score": 92924.71485703217 }, { "content": "function on_Msg(peer_id, m)\n\n if heard_of[m.author] == nil then\n\n heard_of[m.author] = true\n\n end\n\n gossip(peer_id, m)\n\nend\n\n\n", "file_path": "src/automaton/tests/testnet/testproto/chat.lua", "rank": 32, "score": 92924.71485703217 }, { "content": "function on_Hello(peer_id, m)\n\n peers[peer_id].name = m.name\n\nend\n", "file_path": "src/automaton/tests/testnet/testproto/connections.lua", "rank": 33, "score": 92924.71485703217 }, { "content": "class rpc_server_handler: public automaton::core::network::http_server::server_handler {\n\n engine* script;\n\n\n\n public:\n\n explicit rpc_server_handler(engine* en): script(en) {}\n\n std::string handle(std::string json_cmd, http_server::status_code* s) {\n\n std::stringstream sstr(json_cmd);\n\n nlohmann::json j;\n\n sstr >> j;\n\n std::string cmd = \"rpc_\";\n\n std::string msg = \"\";\n\n if (j.find(\"method\") != j.end() && j.find(\"msg\") != j.end()) {\n\n cmd += j[\"method\"].get<std::string>();\n\n msg = j[\"msg\"].get<std::string>();\n\n } else {\n\n LOG(ERROR) << \"ERROR in rpc server handler: Invalid request\";\n\n *s = http_server::status_code::BAD_REQUEST;\n\n return \"\";\n\n }\n\n std::string params = \"\";\n", "file_path": "src/automaton/core/core.cc", "rank": 34, "score": 92475.3691730035 }, { "content": "function gossip(peer_id, msg)\n\n for k, v in pairs(peers) do\n\n if k ~= 0 and k ~= peer_id then\n\n send(k, msg, 0)\n\n end\n\n end\n\nend\n\n\n", "file_path": "src/automaton/tests/testnet/testproto/chat.lua", "rank": 35, "score": 91002.29116373339 }, { "content": "namespace automaton {\n\nnamespace core {\n\nnamespace io {\n\n\n\n/**\n\n Checks whether the specified file exist.\n\n\n\n Returns true if it does.\n\n*/\n\nbool file_exists(const char* filename);\n\n\n\n/**\n\n Gets the file contents and returns them as a string.\n\n\n\n Exception is thrown when error occurs.\n\n*/\n\nstd::string get_file_contents(const char* filename);\n\n\n\n/**\n\n Converts binary byte buffer to hex string representation.\n\n*/\n\nstd::string bin2hex(const std::string& input);\n\n\n\n/**\n\n Creates a binary byte buffer from hex string representation.\n\n*/\n\nstd::string hex2bin(const std::string& input);\n\n\n\n/**\n\n Returns string representing hex value of a number. Does not contain base prefix 0x. Length is always even.\n\n*/\n\nstd::string dec2hex(uint32_t n);\n\n\n\n/**\n\n Returns a number from its hex representation.\n\n*/\n\nuint32_t hex2dec(const std::string& hex);\n\n\n\n\n\n/**\n\n Returns string representation of a date.\n\n*/\n\nstd::string get_date_string(std::chrono::system_clock::time_point t);\n\n\n\nstd::string zero_padded(int num, int width);\n\n\n\n// This must be called after main entry point.\n\nextern bool init_logger();\n\n\n\n} // namespace io\n\n} // namespace core\n", "file_path": "src/automaton/core/io/io.h", "rank": 36, "score": 87219.53318958718 }, { "content": "namespace automaton {\n\nnamespace core {\n\nnamespace io {\n\n\n\nstruct blob {\n\n explicit blob(size_t size) {\n\n resize(size);\n\n }\n\n\n\n ~blob() {\n\n }\n\n\n\n void set(size_t key, int value) {\n\n CHECK_GT(key, buffer.size());\n\n buffer[key] = value;\n\n }\n\n\n\n uint8_t get(size_t key) {\n\n return buffer[key];\n\n }\n\n\n\n size_t size() {\n\n return buffer.size();\n\n }\n\n\n\n void resize(size_t new_size) {\n\n buffer.resize(new_size, 0);\n\n }\n\n\n\n std::string tostring() {\n\n return io::bin2hex(std::string(reinterpret_cast<const char*>(buffer.data()), buffer.size()));\n\n }\n\n\n\n std::vector<uint8_t> buffer;\n\n};\n\n\n\n} // namespace io\n", "file_path": "src/automaton/core/io/blob.h", "rank": 37, "score": 87219.53318958718 }, { "content": "namespace automaton {\n\nnamespace core {\n\nnamespace common {\n\n\n\nstruct status {\n\n enum status_code {\n\n OK = 0,\n\n CANCELLED = 1,\n\n UNKNOWN = 2,\n\n INVALID_ARGUMENT = 3,\n\n DEADLINE_EXCEEDED = 4,\n\n NOT_FOUND = 5,\n\n ALREADY_EXISTS = 6,\n\n PERMISSION_DENIED = 7,\n\n UNAUTHENTICATED = 16,\n\n RESOURCE_EXHAUSTED = 8,\n\n FAILED_PRECONDITION = 9,\n\n ABORTED = 10,\n\n OUT_OF_RANGE = 11,\n\n UNIMPLEMENTED = 12,\n\n INTERNAL = 13,\n\n UNAVAILABLE = 14,\n\n DATA_LOSS = 15,\n\n };\n\n\n\n explicit status(status_code error_code) : code(error_code), msg(\"\") {}\n\n status(status_code error_code, std::string msg) : code(error_code), msg(msg) {}\n\n\n\n status_code code;\n\n std::string msg;\n\n\n\n bool is_ok() {\n\n return code == OK;\n\n }\n\n\n\n static status ok() {\n\n return status(OK);\n\n }\n\n\n\n static status ok(std::string msg) {\n\n return status(OK, msg);\n\n }\n\n\n\n static status canceled(std::string msg) {\n\n return status(CANCELLED, msg);\n\n }\n\n\n\n static status invalid_argument(std::string msg) {\n\n return status(INVALID_ARGUMENT, msg);\n\n }\n\n\n\n static status unknown(std::string msg) {\n\n return status(UNKNOWN, msg);\n\n }\n\n\n\n static status not_found(std::string msg) {\n\n return status(NOT_FOUND, msg);\n\n }\n\n\n\n static status permission_denied(std::string msg) {\n\n return status(PERMISSION_DENIED, msg);\n\n }\n\n\n\n static status resource_exhausted(std::string msg) {\n\n return status(RESOURCE_EXHAUSTED, msg);\n\n }\n\n\n\n static status failed_precondition(std::string msg) {\n\n return status(FAILED_PRECONDITION, msg);\n\n }\n\n\n\n static status aborted(std::string msg) {\n\n return status(ABORTED, msg);\n\n }\n\n\n\n static status out_of_range(std::string msg) {\n\n return status(OUT_OF_RANGE, msg);\n\n }\n\n\n\n static status unimplemented(std::string msg) {\n\n return status(UNIMPLEMENTED, msg);\n\n }\n\n\n\n static status internal(std::string msg) {\n\n return status(INTERNAL, msg);\n\n }\n\n\n\n static status unavailable(std::string msg) {\n\n return status(UNAVAILABLE, msg);\n\n }\n\n\n\n static status data_loss(std::string msg) {\n\n return status(DATA_LOSS, msg);\n\n }\n\n\n\n std::string to_string() const;\n\n};\n\n\n\nstd::ostream& operator<<(std::ostream& os, const status& s);\n\n\n\n} // namespace common\n", "file_path": "src/automaton/core/common/status.h", "rank": 38, "score": 87219.53318958718 }, { "content": "class eth_contract: public automaton::core::network::connection::connection_handler,\n\n public std::enable_shared_from_this<eth_contract> {\n\n public:\n\n static std::unordered_map<std::string, std::shared_ptr<eth_contract> > contracts;\n\n\n\n static void register_contract(const std::string& server, const std::string& address,\n\n std::unordered_map<std::string, std::pair<std::string, bool> > signs);\n\n static std::shared_ptr<eth_contract> get_contract(const std::string&);\n\n\n\n ~eth_contract();\n\n\n\n void call(const std::string& address, const std::string& f, const std::string& params,\n\n std::function<void(const automaton::core::common::status& s, const std::string&)>);\n\n\n\n private:\n\n uint32_t call_id;\n\n std::string server;\n\n std::string address; // ETH address of the contract\n\n std::unordered_map<std::string, std::pair<std::string, bool> > signatures; // function signatures\n\n std::unordered_map<uint32_t,\n", "file_path": "src/automaton/core/interop/ethereum/eth_contract_raw.h", "rank": 39, "score": 86529.93380071611 }, { "content": "namespace automaton {\n\nnamespace core {\n\nnamespace interop {\n\nnamespace ethereum {\n\n\n\n#ifdef _WIN32\n\n// TODO(vitalyster): use correct error level for these errors\n\n#define _ERROR WARNING\n\n#else\n\n#define _ERROR ERROR\n\n#endif\n\n\n\nstatic size_t curl_callback(void *contents, size_t size, size_t nmemb, std::string *s) {\n\n size_t new_length = size * nmemb;\n\n try {\n\n s->append(reinterpret_cast<char*>(contents), new_length);\n\n }\n\n catch (std::bad_alloc &e) {\n\n LOG(_ERROR) << \"Bad_alloc while reading data!\";\n\n return 0;\n\n }\n\n return new_length;\n\n}\n\n\n\nstatic status handle_result(const std::string& result) {\n\n json j;\n\n std::stringstream ss(result);\n\n try {\n\n ss >> j;\n\n } catch (...) {\n\n return status::internal(\"Could not parse JSON!\");\n\n }\n\n\n\n if (j.find(\"error\") != j.end()) {\n\n json obj = j[\"error\"];\n\n if (obj.is_string()) {\n\n std::string error = obj[\"message\"].get<std::string>();\n\n return status::internal(error);\n\n }\n\n return status::internal(obj.dump());\n\n } else if (j.find(\"result\") != j.end()) {\n\n if (j[\"result\"].is_string()) {\n\n std::string result = j[\"result\"].get<std::string>();\n\n return status::ok(result.substr(2));\n\n }\n\n return status::ok(j[\"result\"].dump());\n\n }\n\n return status::internal(\"No result and no error!?\");\n\n}\n\n\n\nstatic status curl_post(const std::string& url, const std::string& data) {\n\n CURL *curl;\n\n CURLcode res;\n\n std::string message;\n\n char curl_err_buf[1024];\n\n\n\n curl = curl_easy_init();\n\n\n\n LOG(INFO) << \"\\n======= REQUEST =======\\n\" << data << \"\\n=====================\";\n\n\n\n if (curl) {\n\n struct curl_slist *list = NULL;\n\n\n\n list = curl_slist_append(list, \"Content-Type: application/json\");\n\n\n\n curl_easy_setopt(curl, CURLOPT_URL, url.c_str());\n\n curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_buf);\n\n curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_callback);\n\n curl_easy_setopt(curl, CURLOPT_WRITEDATA, &message);\n\n curl_easy_setopt(curl, CURLOPT_ENCODING, \"gzip\");\n\n curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list);\n\n\n\n curl_err_buf[0] = '\\0';\n\n curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str());\n\n res = curl_easy_perform(curl);\n\n curl_slist_free_all(list);\n\n curl_easy_cleanup(curl);\n\n if (res != CURLE_OK) {\n\n size_t len = strlen(curl_err_buf);\n\n LOG(_ERROR) << \"Curl result code != CURLE_OK. Result code: \" << res;\n\n if (len) {\n\n return status::internal(std::string(curl_err_buf, len));\n\n }\n\n return status::internal(\"CURL error\");\n\n } else {\n\n LOG(INFO) << \"\\n======= RESPONSE =======\\n\" << message << \"\\n=====================\";\n\n return handle_result(message);\n\n }\n\n } else {\n\n return status::internal(\"No curl!\");\n\n }\n\n}\n\n\n\nstatic status eth_getTransactionCount(const std::string& url, const std::string& address) {\n\n std::stringstream ss;\n\n ss << \"{\\\"jsonrpc\\\":\\\"2.0\\\",\\\"method\\\":\\\"eth_getTransactionCount\\\",\\\"params\\\":[\\\"\" << address <<\n\n \"\\\",\\\"latest\\\"\" << \"],\\\"id\\\":1}\";\n\n return curl_post(url, ss.str());\n\n}\n\n\n\nstatic status eth_getCode(const std::string& url, const std::string& address) {\n\n std::stringstream ss;\n\n ss << \"{\\\"jsonrpc\\\":\\\"2.0\\\",\\\"method\\\":\\\"eth_getCode\\\",\\\"params\\\":[\\\"\" << address <<\n\n \"\\\",\\\"latest\\\"\" << \"],\\\"id\\\":1}\";\n\n return curl_post(url, ss.str());\n\n}\n\n\n\nstatic status eth_getBalance(const std::string& url, const std::string& address) {\n\n std::stringstream ss;\n\n ss << \"{\\\"jsonrpc\\\":\\\"2.0\\\",\\\"method\\\":\\\"eth_getBalance\\\",\\\"params\\\":[\\\"\" << address <<\n\n \"\\\",\\\"latest\\\"\" << \"],\\\"id\\\":1}\";\n\n return curl_post(url, ss.str());\n\n}\n\n\n\nstatic status eth_gasPrice(const std::string& url) {\n\n std::stringstream ss;\n\n ss << \"{\\\"jsonrpc\\\":\\\"2.0\\\",\\\"method\\\":\\\"eth_gasPrice\\\",\\\"params\\\":[],\\\"id\\\":1}\";\n\n return curl_post(url, ss.str());\n\n}\n\n\n\nstatic status eth_getTransactionReceipt(const std::string& url, const std::string& tx_hash) {\n\n std::stringstream ss;\n\n ss << \"{\\\"jsonrpc\\\":\\\"2.0\\\",\\\"method\\\":\\\"eth_getTransactionReceipt\\\",\\\"params\\\":[\\\"\" << tx_hash << \"\\\"],\\\"id\\\":1}\";\n\n return curl_post(url, ss.str());\n\n}\n\n\n\n// Argument encoding and decoding\n\n\n\n/* TODO(kari):\n\n \t* Replace type bitmask with variables\n\n \t* Type structure is messy and confusing - clean it up\n\n \t* Use switch after replacing the bitmask\n\n \t* Move convertion functions to the io module\n\n * Add support for fixed-point numbers\n\n*/\n\n\n\nstatic const uint32_t BUFFER_SIZE = 2048;\n\n\n\nenum abi_type {\n\n empty = 0,\n\n numerical = 1, // bool, int<>, uint<>, fixed, ufixed, fixed<M>x<N>, ufixed<M>x<N>\n\n fixed_size_bytes = 2, // bytes<>, function(bytes24), address(uint160)\n\n dynamic_size_bytes = 3, // bytes\n\n string = 4, // string\n\n};\n\n\n\nenum abi_array_type {\n\n no_array = 0,\n\n fixed = 1,\n\n dynamic = 2\n\n};\n\n\n\nstatic std::ostream& operator<<(std::ostream& os, const abi_type& obj) {\n\n switch (obj) {\n\n case numerical: os << \"numerical\"; break;\n\n case string: os << \"string\"; break;\n\n case fixed_size_bytes: os << \"fixed_size_bytes\"; break;\n\n case dynamic_size_bytes: os << \"dynamic_size_bytes\"; break;\n\n default: os << \"no type\"; break;\n\n }\n\n return os;\n\n}\n\n\n\nstruct type {\n\n std::string str = \"\";\n\n abi_type s_type = empty;\n\n abi_array_type s_array_type = no_array;\n\n uint32_t array_len = 0;\n\n};\n\n\n\nstatic std::ostream& operator<<(std::ostream& os, const type& obj) {\n\n os << \"TYPE{\" << obj.str << \", \" << obj.s_type;\n\n if (obj.s_array_type != no_array) {\n\n if (obj.s_array_type == fixed) {\n\n os << \", fixed array of size \";\n\n } else {\n\n os << \", dynamic array of size \";\n\n }\n\n os << obj.array_len;\n\n }\n\n os << \"}\";\n\n return os;\n\n}\n\n\n\nstatic type get_type(std::string s) {\n\n type t;\n\n t.str = s;\n\n t.s_array_type = no_array;\n\n t.array_len = 0;\n\n\n\n bool is_array = false;\n\n // Check if it is an array and its size if any\n\n int32_t k1 = 0, k2 = 0, pos, first_pos;\n\n first_pos = pos = s.find('[');\n\n while (pos != std::string::npos) {\n\n k1 = pos;\n\n pos = s.find('[', pos + 1);\n\n }\n\n if (k1 != 0) {\n\n k2 = s.find(']', k1 + 1);\n\n }\n\n if (k1 && k2) {\n\n is_array = true;\n\n if (k1 < (k2 - 1)) {\n\n std::string len_str = s.substr(k1 + 1, k2 - k1 - 1);\n\n t.array_len = stoi(len_str);\n\n }\n\n }\n\n\n\n if (is_array) {\n\n type arr_type = get_type(s.substr(0, k1));\n\n t.s_type = arr_type.s_type;\n\n if (arr_type.s_array_type == dynamic || t.array_len == 0 ||\n\n t.s_type == dynamic_size_bytes || t.s_type == string) {\n\n t.s_array_type = dynamic;\n\n } else {\n\n t.s_array_type = fixed;\n\n }\n\n } else {\n\n if (s == \"function\" || (s.find(\"bytes\") == 0 && s.size() > 5) || s == \"address\") {\n\n t.s_type = fixed_size_bytes;\n\n } else if (s == \"bytes\") {\n\n t.s_type = dynamic_size_bytes;\n\n } else if (s == \"string\") {\n\n t.s_type = string;\n\n } else {\n\n t.s_type = numerical; // TODO(kari): Could be invalid type\n\n }\n\n }\n\n return t;\n\n}\n\n\n\nstatic type extract_array_type(std::string s) {\n\n type new_t;\n\n int32_t k1 = 0, k2 = 0, pos = 0;\n\n pos = s.find('[', pos + 1);\n\n while (pos != std::string::npos) {\n\n k1 = pos;\n\n pos = s.find('[', pos + 1);\n\n }\n\n if (k1 != 0) {\n\n k2 = s.find(']', k1 + 1);\n\n }\n\n if (k1 && k2) {\n\n s.erase(k1, k2 - k1 + 1);\n\n new_t = get_type(s);\n\n } else {\n\n LOG(_ERROR) << \"Array expected!: \" << s;\n\n }\n\n return new_t;\n\n}\n\n\n\nstatic uint32_t calculate_offset(std::vector<std::string> params) {\n\n uint32_t tail_offset = 0;\n\n for (uint32_t i = 0; i < params.size(); ++i) {\n\n type t = get_type(params[i]);\n\n if (t.s_array_type == fixed) {\n\n uint32_t element_count = 1;\n\n // Add the other dimenstions if any\n\n while (t.s_array_type == fixed) {\n\n element_count *= t.array_len;\n\n t = extract_array_type(t.str);\n\n }\n\n tail_offset += 32 * element_count;\n\n } else {\n\n tail_offset += 32;\n\n }\n\n }\n\n return tail_offset;\n\n}\n\n\n\nstatic std::string encode_string(const std::string& byte_array) {\n\n std::stringstream ss;\n\n auto reminder = byte_array.size() % 32;\n\n ss << byte_array << (reminder ? std::string(32 - reminder, '\\0') : \"\");\n\n return ss.str();\n\n}\n\n\n\nstatic std::string u64_to_u256(uint64_t n) {\n\n char bytes[8];\n\n bytes[7] = (n) & 0xFF;\n\n bytes[6] = (n >> 8) & 0xFF;\n\n bytes[5] = (n >> 16) & 0xFF;\n\n bytes[4] = (n >> 24) & 0xFF;\n\n bytes[3] = (n >> 32) & 0xFF;\n\n bytes[2] = (n >> 40) & 0xFF;\n\n bytes[1] = (n >> 48) & 0xFF;\n\n bytes[0] = (n >> 56) & 0xFF;\n\n\n\n return std::string(24, '\\0') + std::string(bytes, 8);\n\n}\n\n\n\nstatic std::string dec_to_i256(bool is_signed, std::string s) {\n\n CryptoPP::Integer::Signedness sign = is_signed ? CryptoPP::Integer::SIGNED : CryptoPP::Integer::UNSIGNED;\n\n if (s.substr(0, 2) == \"0x\") {\n\n s = \"h\" + s.substr(2);\n\n }\n\n CryptoPP::Integer i(s.c_str());\n\n uint8_t bytes[32] = {0};\n\n i.Encode(bytes, 32, sign);\n\n return std::string(reinterpret_cast<const char*>(bytes), 32);\n\n}\n\n\n\nstatic std::string i256_to_dec(bool is_signed, const std::string& s) {\n\n // TODO(kari): If the number is more than 64 bits, throw error or use only 64 bits of it.\n\n CryptoPP::Integer::Signedness sign = is_signed ? CryptoPP::Integer::SIGNED : CryptoPP::Integer::UNSIGNED;\n\n CryptoPP::Integer i(reinterpret_cast<const uint8_t*>(s.c_str()), 32, sign);\n\n std::stringstream ss;\n\n ss << i;\n\n std::string res = ss.str();\n\n return res.substr(0, res.size() - 1); // remove suffix\n\n}\n\n\n\nstatic uint64_t u256_to_u64(const std::string& s) {\n\n if (s.size() != 32) {\n\n LOG(_ERROR) << \"Invalid argument format!\" << s;\n\n return 0;\n\n }\n\n uint64_t n = 0;\n\n for (auto i = 0; i < 8; i++) {\n\n uint64_t k = reinterpret_cast<const uint8_t &>(s[24 + i]);\n\n n |= (k << ((7 - i) * 8));\n\n }\n\n return n;\n\n}\n\n\n\nstatic void check_and_resize_buffer(char** buffer, uint64_t* size, uint64_t pos, uint64_t data_size) {\n\n uint64_t new_size = *size;\n\n while (pos + data_size > new_size) {\n\n new_size += BUFFER_SIZE;\n\n }\n\n if (*size != new_size) {\n\n char* new_buffer = new char[new_size];\n\n memcpy(new_buffer, *buffer, *size);\n\n delete [] *buffer;\n\n *buffer = new_buffer;\n\n *size = new_size;\n\n }\n\n}\n\n\n\nstatic void encode_param(type t, const json& json_data, char** buffer, uint64_t* buf_size,\n\n uint64_t* head_pos, uint64_t* tail_pos) {\n\n if (t.s_array_type == fixed) {\n\n if (!json_data.is_array() || json_data.size() != t.array_len) {\n\n LOG(_ERROR) << \"Invalid argument! Expected array with length \" << t.array_len << \", got \" << json_data;\n\n return;\n\n }\n\n type tp = extract_array_type(t.str);\n\n for (auto it = json_data.begin(); it != json_data.end(); ++it) {\n\n encode_param(tp, *it, buffer, buf_size, head_pos, tail_pos);\n\n }\n\n } else if (t.s_array_type == dynamic) {\n\n if (!json_data.is_array()) {\n\n LOG(_ERROR) << \"Invalid argument! Expected array, got \" << json_data;\n\n return;\n\n }\n\n if (t.array_len && json_data.size() != t.array_len) {\n\n LOG(_ERROR) << \"Invalid argument! Expected array with length \" << t.array_len << \", got \" << json_data;\n\n return;\n\n }\n\n std::string encoded;\n\n if (t.array_len == 0) { // Size is unknown; not fixed\n\n encoded = u64_to_u256(json_data.size());\n\n check_and_resize_buffer(buffer, buf_size, *tail_pos, 32);\n\n memcpy(*buffer + *tail_pos, encoded.c_str(), 32);\n\n *tail_pos += 32;\n\n }\n\n uint64_t head_prim_pos = *tail_pos;\n\n uint64_t tail_prim_pos = *tail_pos;\n\n type tp = extract_array_type(t.str);\n\n if (tp.s_array_type == fixed) {\n\n tail_prim_pos += (json_data.size() * calculate_offset({tp.str}));\n\n for (auto it = json_data.begin(); it != json_data.end(); ++it) {\n\n encode_param(tp, *it, buffer, buf_size, &head_prim_pos, &tail_prim_pos);\n\n }\n\n } else if (tp.s_type == dynamic_size_bytes || tp.s_type == string || tp.s_array_type == dynamic) {\n\n tail_prim_pos += (32 * json_data.size());\n\n for (auto it = json_data.begin(); it != json_data.end(); ++it) {\n\n encoded = u64_to_u256(tail_prim_pos - *tail_pos);\n\n check_and_resize_buffer(buffer, buf_size, head_prim_pos, 32);\n\n memcpy(*buffer + head_prim_pos, encoded.c_str(), 32);\n\n head_prim_pos += 32;\n\n encode_param(tp, *it, buffer, buf_size, &tail_prim_pos, &tail_prim_pos);\n\n }\n\n } else if (tp.s_type == numerical || tp.s_type == fixed_size_bytes) {\n\n tail_prim_pos += (32 * json_data.size());\n\n for (auto it = json_data.begin(); it != json_data.end(); ++it) {\n\n encode_param(tp, *it, buffer, buf_size, &head_prim_pos, &tail_prim_pos);\n\n }\n\n } else {\n\n LOG(_ERROR) << \"Invalid type!\" << tp.s_type;\n\n return;\n\n }\n\n *tail_pos = tail_prim_pos;\n\n } else if (t.s_type == string || t.s_type == dynamic_size_bytes) {\n\n if (!json_data.is_string()) {\n\n LOG(_ERROR) << \"Invalid argument!\";\n\n return;\n\n }\n\n std::string s;\n\n std::string data = json_data.get<std::string>();\n\n if (t.s_type == dynamic_size_bytes) {\n\n s = hex2bin(data);\n\n } else {\n\n s = data;\n\n }\n\n std::string encoded = u64_to_u256(s.size());\n\n check_and_resize_buffer(buffer, buf_size, *tail_pos, 32);\n\n memcpy(*buffer + *tail_pos, encoded.c_str(), 32);\n\n *tail_pos += 32;\n\n encoded = encode_string(s);\n\n check_and_resize_buffer(buffer, buf_size, *tail_pos, encoded.size());\n\n memcpy(*buffer + *tail_pos, encoded.c_str(), encoded.size());\n\n *tail_pos += encoded.size();\n\n } else if (t.s_type == fixed_size_bytes) {\n\n if (!json_data.is_string()) {\n\n LOG(_ERROR) << \"Invalid argument! Expected string, got \" << json_data;\n\n return;\n\n }\n\n std::string data = json_data.get<std::string>();\n\n std::string bin_data = hex2bin(data);\n\n if (bin_data.size() > 32) {\n\n LOG(_ERROR) << \"Invalid argument! Size > 32 bytes! \" << data;\n\n return;\n\n }\n\n std::string encoded;\n\n if (t.str == \"address\") {\n\n if (bin_data.size() != 20) {\n\n LOG(_ERROR) << \"Invalid argument! Address size != 20 bytes! \" << data;\n\n return;\n\n }\n\n encoded = std::string(12, '\\0') + bin_data;\n\n } else {\n\n encoded = bin_data + std::string(32 - bin_data.size(), '\\0');\n\n }\n\n check_and_resize_buffer(buffer, buf_size, *head_pos, 32);\n\n memcpy(*buffer + *head_pos, encoded.c_str(), 32);\n\n *head_pos += 32;\n\n } else if (t.s_type == numerical) {\n\n std::string encoded;\n\n if (t.str == \"bool\") {\n\n if (!json_data.is_boolean()) {\n\n LOG(_ERROR) << \"Invalid argument! Expected boolean, got \" << json_data;\n\n return;\n\n }\n\n encoded = u64_to_u256(json_data.get<bool>() ? 1 : 0);\n\n } else if (t.str.find(\"int\") >= 0) {\n\n std::string s;\n\n if (json_data.is_number()) {\n\n s = std::to_string(json_data.get<uint64_t>());\n\n } else if (json_data.is_string()) {\n\n s = json_data.get<std::string>();\n\n } else {\n\n LOG(_ERROR) << \"Invalid argument! Expected number or string, got \" << json_data;\n\n return;\n\n }\n\n bool is_signed = t.str[0] != 'u';\n\n encoded = dec_to_i256(is_signed, s);\n\n } else if (t.str.find(\"fixed\") >= 0) {\n\n LOG(_ERROR) << \"Unsuported data type double!\";\n\n return;\n\n }\n\n check_and_resize_buffer(buffer, buf_size, *head_pos, 32);\n\n memcpy(*buffer + *head_pos, encoded.c_str(), 32);\n\n *head_pos += 32;\n\n } else {\n\n LOG(_ERROR) << \"Undefined type: \" << t.s_type;\n\n }\n\n}\n\n\n\nstatic std::string encode(const std::string& signatures_json, const std::string& parameters_json) {\n\n json j_sigs, j_params;\n\n try {\n\n std::stringstream sigs(signatures_json);\n\n sigs >> j_sigs;\n\n std::stringstream params(parameters_json);\n\n params >> j_params;\n\n } catch (const std::exception& e) {\n\n LOG(_ERROR) << \"Json error: \" << e.what();\n\n return \"\";\n\n }\n\n\n\n if (!j_params.is_array() || j_params.size() != j_sigs.size()) {\n\n LOG(_ERROR) << \"Invalid arguments!\";\n\n return \"\";\n\n }\n\n\n\n char* buffer = new char[BUFFER_SIZE];\n\n uint64_t buf_size = BUFFER_SIZE;\n\n\n\n std::vector<std::string> signatures;\n\n try {\n\n signatures = j_sigs.get<std::vector<std::string> >();\n\n } catch (const std::exception& e) {\n\n LOG(_ERROR) << \"Invalid arguments! \" << e.what();\n\n return \"\";\n\n }\n\n\n\n uint64_t head_pos = 0;\n\n uint64_t tail_pos = calculate_offset(signatures);\n\n std::string signature;\n\n auto p_it = j_params.begin();\n\n uint32_t s_i = 0;\n\n for (; s_i < signatures.size() && p_it != j_params.end(); ++s_i, ++p_it) {\n\n signature = signatures[s_i];\n\n type t = get_type(signature);\n\n if (t.s_type == dynamic_size_bytes || t.s_type == string || t.s_array_type == dynamic) {\n\n std::string encoded = u64_to_u256(tail_pos);\n\n check_and_resize_buffer(&buffer, &buf_size, tail_pos, 32);\n\n memcpy(buffer + head_pos, encoded.c_str(), 32);\n\n head_pos += 32;\n\n encode_param(t, *p_it, &buffer, &buf_size, &tail_pos, &tail_pos);\n\n } else {\n\n encode_param(t, *p_it, &buffer, &buf_size, &head_pos, &tail_pos);\n\n }\n\n }\n\n std::string result = std::string(buffer, tail_pos);\n\n delete [] buffer;\n\n return std::move(result);\n\n}\n\n\n\nstatic std::string decode_param(type t, const std::string& data, uint64_t pos) {\n\n if (t.s_array_type == fixed) {\n\n auto tp = extract_array_type(t.str);\n\n std::stringstream ss;\n\n ss << '[';\n\n if (tp.s_array_type == fixed) {\n\n for (int32_t i = 0; i < t.array_len - 1; ++i) {\n\n ss << decode_param(tp, data, pos) << \",\";\n\n pos += calculate_offset({tp.str});\n\n }\n\n ss << decode_param(tp, data, pos);\n\n } else if (tp.s_type == numerical || tp.s_type == fixed_size_bytes) {\n\n for (int32_t i = 0; i < t.array_len - 1; ++i) {\n\n ss << decode_param(tp, data, pos) << \",\";\n\n pos += 32;\n\n }\n\n ss << decode_param(tp, data, pos);\n\n }\n\n ss << ']';\n\n return ss.str();\n\n } else if (t.s_array_type == dynamic) {\n\n int64_t len = t.array_len;\n\n if (len == 0) {\n\n std::string s = data.substr(pos, 32);\n\n len = u256_to_u64(s);\n\n pos += 32;\n\n }\n\n std::stringstream ss;\n\n ss << '[';\n\n auto tp = extract_array_type(t.str);\n\n if (tp.s_array_type == no_array && (tp.s_type == numerical || tp.s_type == fixed_size_bytes)) {\n\n for (int32_t i = 0; i < len - 1; ++i) {\n\n ss << decode_param(tp, data, pos) << \",\";\n\n pos += 32;\n\n }\n\n ss << decode_param(tp, data, pos);\n\n } else if (tp.s_array_type == fixed) {\n\n for (int32_t i = 0; i < len - 1; ++i) {\n\n ss << decode_param(tp, data, pos) << \",\";\n\n pos += calculate_offset({tp.str});\n\n }\n\n ss << decode_param(tp, data, pos);\n\n } else if (tp.s_type == string || tp.s_type == dynamic_size_bytes || tp.s_array_type == dynamic) {\n\n for (int32_t i = 0; i < len - 1; ++i) {\n\n std::string s = data.substr(pos + (32 * i), 32);\n\n uint64_t offset = u256_to_u64(s);\n\n ss << decode_param(tp, data, pos + offset) << \",\";\n\n }\n\n std::string s = data.substr(pos + (32 * (len - 1)), 32);\n\n uint64_t offset = u256_to_u64(s);\n\n ss << decode_param(tp, data, pos + offset);\n\n } else {\n\n LOG(_ERROR) << \"Invalid type!\";\n\n return \"\";\n\n }\n\n ss << ']';\n\n return ss.str();\n\n } else if (t.s_type == dynamic_size_bytes || t.s_type == string) {\n\n std::string s = data.substr(pos, 32);\n\n int64_t len = u256_to_u64(s);\n\n pos += 32;\n\n std::string res = data.substr(pos, len);\n\n if (t.s_type == string) {\n\n return '\"' + res + '\"';\n\n }\n\n return '\"' + bin2hex(res) + '\"';\n\n } else if (t.s_type == numerical) {\n\n std::string res = data.substr(pos, 32);\n\n if (t.str == \"bool\") {\n\n uint64_t k = u256_to_u64(res);\n\n return k > 0 ? \"true\" : \"false\";\n\n } else if (t.str.find(\"int\") >= 0) {\n\n bool is_signed = t.str[0] != 'u';\n\n return '\"' + i256_to_dec(is_signed, res) + '\"';\n\n } else if (t.str.find(\"fixed\") >= 0) {\n\n LOG(_ERROR) << \"Unsuported data type double!\";\n\n return \"\\\"\\\"\";\n\n }\n\n return \"\";\n\n } else if (t.s_type == fixed_size_bytes) {\n\n if (t.str == \"address\") {\n\n std::string res = data.substr(pos, 32);\n\n return '\"' + bin2hex(res.substr(12, 20)) + '\"';\n\n }\n\n std::regex rgx_sim(\"bytes(\\\\d+)\");\n\n std::smatch match;\n\n const std::string sig = t.str;\n\n uint32_t k = 32;\n\n if (t.str == \"function\") {\n\n k = 24;\n\n } else if (std::regex_match(sig.begin(), sig.end(), match, rgx_sim) && match.size() == 2) {\n\n k = std::stoul(match[1]);\n\n }\n\n std::string res = data.substr(pos, k);\n\n return '\"' + bin2hex(res) + '\"';\n\n } else {\n\n LOG(_ERROR) << \"Undefined type: \" << t.s_type;\n\n }\n\n return \"\";\n\n}\n\n\n\nstatic std::string decode(const std::string& signatures_json, const std::string& data) {\n\n json j_sigs, j_params;\n\n try {\n\n std::stringstream sigs(signatures_json);\n\n sigs >> j_sigs;\n\n } catch (const std::exception& e) {\n\n LOG(_ERROR) << \"Json error: \" << e.what();\n\n return \"\";\n\n }\n\n\n\n std::stringstream ss;\n\n std::string signature;\n\n ss << '[';\n\n uint64_t pos = 0;\n\n for (auto s_it = j_sigs.begin(); s_it != j_sigs.end();) {\n\n signature = (*s_it).get<std::string>();\n\n type t = get_type(signature);\n\n if (t.s_type == dynamic_size_bytes || t.s_type == string || t.s_array_type == dynamic) {\n\n std::string s = data.substr(pos, 32);\n\n uint64_t offset = u256_to_u64(s);\n\n ss << decode_param(t, data, offset);\n\n } else {\n\n ss << decode_param(t, data, pos);\n\n }\n\n if (++s_it != j_sigs.end()) {\n\n ss << ',';\n\n }\n\n if (t.s_array_type == fixed) {\n\n pos += calculate_offset({t.str});\n\n } else {\n\n pos += 32;\n\n }\n\n }\n\n ss << ']';\n\n return ss.str();\n\n}\n\n\n\n} // namespace ethereum\n\n} // namespace interop\n", "file_path": "src/automaton/core/interop/ethereum/eth_helper_functions.h", "rank": 40, "score": 84633.63705223227 }, { "content": "function chat_node(id)\n\n local n = node(id, \"automaton/examples/smartproto/chat/\")\n\n\n\n _G[id] = {\n\n node_type = \"chat\",\n\n }\n\n\n\n return n\n\nend\n", "file_path": "src/automaton/examples/smartproto/chat/init.lua", "rank": 41, "score": 78261.6856954901 }, { "content": "function blockchain_node(id)\n\n local n = node(id, \"automaton/examples/smartproto/blockchain/\")\n\n\n\n -- print(id)\n\n _G[id] = {\n\n node_type = \"blockchain\",\n\n\n\n set_mining_power = function(x)\n\n n:script(\"MINE_ATTEMPTS=\" .. x .. \" return ''\")\n\n end,\n\n\n\n get_mining_power = function()\n\n n:script(\"return tostring(MINE_ATTEMPTS)\");\n\n end,\n\n\n\n get_stats = function()\n\n return n:script(\"return node_stats()\")\n\n end,\n\n\n\n disconnect_all = function()\n", "file_path": "src/automaton/examples/smartproto/blockchain/init.lua", "rank": 42, "score": 78261.6856954901 }, { "content": "class blockchain_cpp_node : public automaton::core::node::node {\n\n public:\n\n blockchain_cpp_node(const std::string& id, const std::string& proto_id);\n\n\n\n ~blockchain_cpp_node();\n\n\n\n void init();\n\n\n\n void script(const std::string& command, std::promise<std::string>* result) {}\n\n\n\n std::string process_cmd(const std::string& cmd, const std::string& params);\n\n\n\n std::string node_stats(uint32_t last_blocks);\n\n\n\n block get_blockchain_top();\n\n\n\n uint32_t get_blocks_size() {\n\n return blocks.size();\n\n }\n\n\n", "file_path": "src/automaton/examples/node/blockchain_cpp_node/blockchain_cpp_node.h", "rank": 43, "score": 77876.32672979373 }, { "content": "function reservation_system_node(id)\n\n local n = node(id, \"automaton/examples/smartproto/reservationsystem/\")\n\n\n\n -- print(id)\n\n _G[id] = {\n\n node_type = \"reservation_system_node\",\n\n\n\n connect = function(peer_id)\n\n n:call(\"connect(\"..tostring(peer_id)..\")\")\n\n end,\n\n\n\n reserve = function(room_id, start_day, end_day)\n\n n:call(\"reserve(\" .. tostring(room_id) .. \",\"\n\n .. tostring(start_day) .. \",\"\n\n .. tostring(end_day) .. \")\")\n\n end,\n\n\n\n cancel = function(room_id, start_day, end_day)\n\n n:call(\"cancel(\" .. tostring(room_id) .. \",\"\n\n .. tostring(start_day) .. \",\"\n\n .. tostring(end_day) .. \")\")\n\n end\n\n }\n\n return n\n\nend\n\n\n\n-- test network functions\n\n\n", "file_path": "src/automaton/examples/smartproto/reservationsystem/init.lua", "rank": 44, "score": 77233.76974964066 }, { "content": "function testnet(discovery, node_factory, num_nodes, num_peers, path)\n\n return discovery(node_factory, num_nodes, num_peers, path)\n\nend\n\n\n", "file_path": "src/automaton/examples/smartproto/common/network.lua", "rank": 45, "score": 62659.26343585753 }, { "content": " uint32_t number_nodes, std::unordered_map<uint32_t, std::vector<uint32_t> > peer_list) {\n\n bool success = false;\n\n if (ntype == \"simulation\") {\n\n success = testnet::create_testnet(\"lua\", id, smart_protocol_id, testnet::network_protocol_type::simulation,\n\n number_nodes, peer_list);\n\n } else if (ntype == \"localhost\") {\n\n success = testnet::create_testnet(\"lua\", id, smart_protocol_id, testnet::network_protocol_type::localhost,\n\n number_nodes, peer_list);\n\n }\n\n if (!success) {\n\n throw std::runtime_error(\"Testnet creation failed!\");\n\n }\n\n std::shared_ptr<testnet> net = testnet::get_testnet(id);\n\n for (auto nid : net->list_nodes()) {\n\n updater->add_node(nid);\n\n }\n\n });\n\n\n\n script.set(\"testnet_destroy\", &testnet::destroy_testnet);\n\n\n", "file_path": "src/automaton/core/core.cc", "rank": 46, "score": 60032.74038196619 }, { "content": " script.set(\"testnet_list_all\", &testnet::list_testnets);\n\n\n\n script.set_function(\"connect_testnet_nodes\",\n\n [&](std::string id, std::unordered_map<uint32_t, std::vector<uint32_t> > peers_list) {\n\n auto net = testnet::get_testnet(id);\n\n if (net == nullptr) {\n\n LOG(ERROR) << \"No testnet with id \" << id;\n\n } else {\n\n net->connect(peers_list);\n\n }\n\n });\n\n\n\n script.set_function(\"list_testnet_nodes\", [&](std::string id) {\n\n auto net = testnet::get_testnet(id);\n\n if (net == nullptr) {\n\n LOG(ERROR) << \"No testnet with id \" << id;\n\n } else {\n\n return net->list_nodes();\n\n }\n\n return std::vector<std::string>();\n", "file_path": "src/automaton/core/core.cc", "rank": 47, "score": 60028.3096206236 }, { "content": " });\n\n\n\n script.set_function(\"get_testnet_node_id\", [&](std::string testnet_id, uint32_t index) -> std::string {\n\n auto net = testnet::get_testnet(testnet_id);\n\n if (net == nullptr) {\n\n LOG(ERROR) << \"No testnet with id \" << testnet_id;\n\n return \"\";\n\n }\n\n std::vector<std::string> nodes = net->list_nodes();\n\n if (index < 1 || index > nodes.size()) {\n\n LOG(ERROR) << \"No node with index \" << index;\n\n return \"\";\n\n }\n\n return nodes[index - 1];\n\n });\n\n\n\n // end of testnet functions\n\n\n\n script.set_function(\"history_add\", [&](std::string cmd){\n\n cli.history_add(cmd.c_str());\n", "file_path": "src/automaton/core/core.cc", "rank": 48, "score": 60025.548640974164 }, { "content": "#include \"automaton/core/node/node.h\"\n\n#include \"automaton/core/node/node_updater.h\"\n\n#include \"automaton/core/script/engine.h\"\n\n#include \"automaton/core/smartproto/smart_protocol.h\"\n\n#include \"automaton/core/testnet/testnet.h\"\n\n\n\n#include \"automaton/core/io/io.h\" // IO needs to be included after boost\n\n\n\nusing automaton::core::data::factory;\n\nusing automaton::core::data::protobuf::protobuf_factory;\n\nusing automaton::core::data::protobuf::protobuf_schema;\n\nusing automaton::core::data::schema;\n\nusing automaton::core::io::get_file_contents;\n\nusing automaton::core::network::http_server;\n\nusing automaton::core::node::luanode::lua_node;\n\nusing automaton::core::node::node;\n\nusing automaton::core::node::default_node_updater;\n\nusing automaton::core::script::engine;\n\nusing automaton::core::smartproto::smart_protocol;\n\nusing automaton::core::testnet::testnet;\n", "file_path": "src/automaton/core/core.cc", "rank": 49, "score": 60023.917746297084 }, { "content": " curl_global_init(CURL_GLOBAL_DEFAULT);\n\n\n\n automaton::core::io::init_logger();\n\n automaton::core::cli::cli cli;\n\n engine script(core_factory);\n\n script.bind_core();\n\n\n\n // Bind node::node class\n\n auto node_type = script.create_simple_usertype<lua_node>();\n\n\n\n node_type.set(sol::call_constructor,\n\n sol::factories(\n\n [&](const std::string& id, std::string proto) -> std::shared_ptr<lua_node> {\n\n return std::dynamic_pointer_cast<lua_node>(node::create(\"lua\", id, proto));\n\n }));\n\n\n\n // Bind this node to its own Lua state.\n\n node_type.set(\"add_peer\", &lua_node::add_peer);\n\n node_type.set(\"remove_peer\", &lua_node::remove_peer);\n\n node_type.set(\"connect\", &lua_node::connect);\n", "file_path": "src/automaton/core/core.cc", "rank": 50, "score": 60021.50317361124 }, { "content": " script.set_function(\"list_nodes_as_table\", [&](){\n\n return sol::as_table(node::list_nodes());\n\n });\n\n\n\n script.set_function(\"get_node\", [&](const std::string& node_id) -> std::shared_ptr<lua_node> {\n\n return std::dynamic_pointer_cast<lua_node>(node::get_node(node_id));\n\n });\n\n\n\n script.set_function(\"launch_node\", [&](std::string node_id, std::string protocol_id, std::string address) {\n\n LOG(INFO) << \"launching node ... \" << node_id << \" on \" << protocol_id << \" @ \" << address;\n\n node::launch_node(\"lua\", node_id, protocol_id, address);\n\n updater->add_node(node_id);\n\n return \"\";\n\n });\n\n\n\n script.set_function(\"remove_node\", &node::remove_node);\n\n\n\n // Bind testnet static functions\n\n\n\n script.set(\"testnet_create\", [&](std::string id, std::string smart_protocol_id, std::string ntype,\n", "file_path": "src/automaton/core/core.cc", "rank": 51, "score": 60021.47559042056 }, { "content": " });\n\n\n\n script.set_function(\"hints_add\", [&](std::string cmd){\n\n cli.hints_add(cmd.c_str());\n\n });\n\n\n\n script.set_function(\"hints_clear\", [&](){\n\n cli.hints_clear();\n\n });\n\n\n\n script.set_function(\"load_protocol\", [&](std::string proto_id, std::string path){\n\n smart_protocol::load(proto_id, path);\n\n });\n\n\n\n automaton::core::network::tcp_init();\n\n\n\n std::shared_ptr<automaton::core::network::simulation> sim = automaton::core::network::simulation::get_simulator();\n\n sim->simulation_start(100);\n\n cli.print(automaton_ascii_logo.c_str());\n\n\n", "file_path": "src/automaton/core/core.cc", "rank": 52, "score": 60020.37181057663 }, { "content": "#include <curl/curl.h>\n\n#include <cryptopp/base64.h>\n\n#include <cryptopp/filters.h>\n\n\n\n#include <future>\n\n#include <fstream>\n\n#include <iostream>\n\n#include <regex>\n\n#include <string>\n\n\n\n#include <json.hpp>\n\n\n\n#include \"automaton/core/cli/cli.h\"\n\n#include \"automaton/core/data/factory.h\"\n\n#include \"automaton/core/data/protobuf/protobuf_factory.h\"\n\n#include \"automaton/core/data/protobuf/protobuf_schema.h\"\n\n#include \"automaton/core/network/http_server.h\"\n\n#include \"automaton/core/network/simulated_connection.h\"\n\n#include \"automaton/core/network/tcp_implementation.h\"\n\n#include \"automaton/core/node/lua_node/lua_node.h\"\n", "file_path": "src/automaton/core/core.cc", "rank": 53, "score": 60019.10394696151 }, { "content": " LOG(ERROR) << \"Status code variable is missing\";\n\n }\n\n std::string encoded;\n\n CryptoPP::StringSource ss(reinterpret_cast<const unsigned char*>(result.c_str()), result.size(), true,\n\n new CryptoPP::Base64Encoder(new CryptoPP::StringSink(encoded)));\n\n return encoded;\n\n }\n\n};\n\n\n\nint main(int argc, char* argv[]) {\n\n string automaton_ascii_logo(automaton_ascii_logo_cstr);\n\n string_replace(&automaton_ascii_logo, \"@\", \"\\x1b[38;5;\");\n\n auto core_factory = std::make_shared<protobuf_factory>();\n\n node::register_node_type(\"lua\", [](const std::string& id, const std::string& proto_id)->std::shared_ptr<node> {\n\n return std::shared_ptr<node>(new lua_node(id, proto_id));\n\n });\n\n\n\n default_node_updater* updater;\n\n{\n\n // TODO(asen): Get rid of this, it is temporary to verify libcurl works across all platforms.\n", "file_path": "src/automaton/core/core.cc", "rank": 54, "score": 60015.55257799395 }, { "content": " node_type.set(\"get_address\", [](lua_node& n) -> std::string {\n\n std::shared_ptr<automaton::core::network::acceptor> a = n.get_acceptor();\n\n if (a) {\n\n return a->get_address();\n\n }\n\n return \"\";\n\n });\n\n\n\n node_type.set(\"process_cmd\", &lua_node::process_cmd);\n\n\n\n node_type.set(\"process_update\", &lua_node::process_update);\n\n\n\n node_type.set(\"get_time_to_update\", &lua_node::get_time_to_update);\n\n\n\n node_type.set(\"call\", [](lua_node& n, std::string command) {\n\n n.script(command, nullptr);\n\n });\n\n\n\n node_type.set(\"known_peers\", [](lua_node& n) {\n\n LOG(DBUG) << \"getting known peers... \" << &n;\n", "file_path": "src/automaton/core/core.cc", "rank": 55, "score": 60012.66084536088 }, { "content": " node_type.set(\"disconnect\", &lua_node::disconnect);\n\n node_type.set(\"send\", &lua_node::send_message);\n\n node_type.set(\"listen\", &lua_node::set_acceptor);\n\n\n\n node_type.set(\"msg_id\", &lua_node::find_message_id);\n\n node_type.set(\"new_msg\", &lua_node::create_msg_by_id);\n\n node_type.set(\"send\", &lua_node::send_message);\n\n\n\n node_type.set(\"dump_logs\", &lua_node::dump_logs);\n\n\n\n node_type.set(\"script\", [](lua_node& n, std::string command) -> std::string {\n\n std::promise<std::string> prom;\n\n std::future<std::string> fut = prom.get_future();\n\n n.script(command, &prom);\n\n std::string result = fut.get();\n\n return result;\n\n });\n\n\n\n node_type.set(\"get_id\", &lua_node::get_id);\n\n node_type.set(\"get_protocol_id\", &lua_node::get_protocol_id);\n", "file_path": "src/automaton/core/core.cc", "rank": 56, "score": 60012.14519883586 }, { "content": "history_add(\"testnet_get_node_id()\")\n\nhints_add(\"testnet_get_node_id()\")\n\nhistory_add(\"testnet_destroy()\")\n\nhints_add(\"testnet_destroy()\")\n\n\n\nhistory_add(\"start_testnet()\")\n\nhints_add(\"start_testnet()\")\n\n\n\nhistory_add(\"history_add()\")\n\nhints_add(\"history_add()\")\n\nhistory_add(\"hints_add()\")\n\nhints_add(\"hints_add()\")\n\nhistory_add(\"hints_clear()\")\n\nhints_add(\"hints_clear()\")\n\n\n\n-- PROTOCOLS RPC --\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 57, "score": 60011.42975041688 }, { "content": " }\n\n logger_mutex.unlock();\n\n }\n\n });\n\n\n\n std::shared_ptr<automaton::core::network::http_server::server_handler> s_handler(new rpc_server_handler(&script));\n\n http_server rpc_server(rpc_port, s_handler);\n\n rpc_server.run();\n\n\n\n while (1) {\n\n auto input = cli.input(\"\\x1b[38;5;15m\\x1b[1m|A|\\x1b[0m \");\n\n if (input == nullptr) {\n\n cli.print(\"\\n\");\n\n break;\n\n }\n\n\n\n string cmd{input};\n\n cli.history_add(cmd.c_str());\n\n\n\n logger_mutex.lock();\n", "file_path": "src/automaton/core/core.cc", "rank": 58, "score": 60011.37089950824 }, { "content": " script.safe_script(get_file_contents(\"automaton/examples/smartproto/common/names.lua\"));\n\n script.safe_script(get_file_contents(\"automaton/examples/smartproto/common/dump.lua\"));\n\n script.safe_script(get_file_contents(\"automaton/examples/smartproto/common/network.lua\"));\n\n script.safe_script(get_file_contents(\"automaton/examples/smartproto/common/connections_graph.lua\"));\n\n script.safe_script(get_file_contents(\"automaton/examples/smartproto/common/show_states.lua\"));\n\n\n\n std::unordered_map<std::string, std::pair<std::string, std::string> > rpc_commands;\n\n uint32_t rpc_port = 0;\n\n uint32_t updater_workers_number = 0;\n\n uint32_t updater_workers_sleep_time = 0;\n\n\n\n std::ifstream i(\"automaton/core/coreinit.json\");\n\n if (!i.is_open()) {\n\n LOG(ERROR) << \"coreinit.json could not be opened\";\n\n } else {\n\n nlohmann::json j;\n\n i >> j;\n\n i.close();\n\n std::vector<std::vector<std::string>> protocols = j[\"protocols\"];\n\n for (auto& p : protocols) {\n", "file_path": "src/automaton/core/core.cc", "rank": 59, "score": 60011.22935354277 }, { "content": " std::vector<std::string> rpc_luas = j[\"command_implementations\"];\n\n for (auto& p : rpc_luas) {\n\n script.safe_script(get_file_contents(p.c_str()));\n\n }\n\n for (auto& c : j[\"commands\"]) {\n\n rpc_commands[c[\"cmd\"]] = std::make_pair(c[\"input\"], c[\"output\"]);\n\n }\n\n rpc_port = j[\"rpc_config\"][\"default_port\"];\n\n\n\n updater_workers_number = j[\"updater_config\"][\"workers_number\"];\n\n updater_workers_sleep_time = j[\"updater_config\"][\"workers_sleep_time\"];\n\n }\n\n i.close();\n\n updater = new default_node_updater(updater_workers_number, updater_workers_sleep_time, std::set<std::string>());\n\n updater->start();\n\n\n\n // Start dump_logs thread.\n\n std::mutex logger_mutex;\n\n bool stop_logger = false;\n\n std::thread logger([&]() {\n", "file_path": "src/automaton/core/core.cc", "rank": 60, "score": 60010.90861951198 }, { "content": " std::string pid = p[0];\n\n std::string path = p[1];\n\n script.safe_script(get_file_contents((path + \"init.lua\").c_str()));\n\n smart_protocol::load(pid, path);\n\n }\n\n script.set_function(\"get_core_supported_protocols\", [&](){\n\n std::unordered_map<std::string, std::unordered_map<std::string, std::string> > protocols;\n\n for (std::string proto : smart_protocol::list_protocols()) {\n\n auto p = smart_protocol::get_protocol(proto);\n\n protocols[proto] = p->get_msgs_definitions();\n\n protocols[proto][\"config\"] = p->get_configuration_file();\n\n }\n\n return sol::as_table(protocols);\n\n });\n\n\n\n std::vector<std::string> rpc_protos = j[\"command_definitions\"];\n\n for (auto& p : rpc_protos) {\n\n schema* rpc_schema = new protobuf_schema(get_file_contents(p.c_str()));\n\n script.import_schema(rpc_schema);\n\n }\n", "file_path": "src/automaton/core/core.cc", "rank": 61, "score": 60010.344319513315 }, { "content": "}\n\n\n\n LOG(DBUG) << \"tcp_release\";\n\n\n\n automaton::core::network::tcp_release();\n\n\n\n LOG(DBUG) << \"tcp_release done.\";\n\n\n\n return 0;\n\n}\n", "file_path": "src/automaton/core/core.cc", "rank": 62, "score": 60009.998278515945 }, { "content": " // TODO(asen): need STL support for logger\n\n // LOG(DBUG) << n.list_known_peers();\n\n return sol::as_table(n.list_known_peers());\n\n });\n\n\n\n node_type.set(\"peers\", [](lua_node& n) {\n\n LOG(DBUG) << \"getting peers... \" << &n;\n\n // TODO(asen): need STL support for logger\n\n // LOG(DBUG) << n.list_connected_peers();\n\n return sol::as_table(n.list_connected_peers());\n\n });\n\n\n\n node_type.set(\"get_peer_address\", [](lua_node& n, uint32_t pid) {\n\n return n.get_peer_info(pid).address;\n\n });\n\n\n\n script.set_usertype(\"node\", node_type);\n\n\n\n // Bind node static functions\n\n\n", "file_path": "src/automaton/core/core.cc", "rank": 63, "score": 60009.03724070865 }, { "content": "\n\nusing json = nlohmann::json;\n\n\n\nusing std::make_unique;\n\nusing std::string;\n\nusing std::unique_ptr;\n\nusing std::vector;\n\n\n\nvoid string_replace(string* str,\n\n const string& oldStr,\n\n const string& newStr) {\n\n string::size_type pos = 0u;\n\n while ((pos = str->find(oldStr, pos)) != string::npos) {\n\n str->replace(pos, oldStr.length(), newStr);\n\n pos += newStr.length();\n\n }\n\n}\n\n\n\nstatic const char* automaton_ascii_logo_cstr =\n\n \"\\n\\x1b[40m\\x1b[1m\"\n\n \" \" \"\\x1b[0m\\n\\x1b[40m\\x1b[1m\"\n\n \" \" \"\\x1b[0m\\n\\x1b[40m\\x1b[1m\"\n\n \" @197m█▀▀▀█ @39m█ █ █ @11m▀▀█▀▀ @129m█▀▀▀█ @47m█▀█▀█ @9m█▀▀▀█ @27m▀▀█▀▀ @154m█▀▀▀█ @13m█▀█ █ \" \"\\x1b[0m\\n\\x1b[40m\\x1b[1m\" // NOLINT\n\n \" @197m█▀▀▀█ @39m█ ▀ █ @11m█ █ █ @129m█ ▀ █ @47m█ ▀ █ @9m█▀▀▀█ @27m█ █ █ @154m█ ▀ █ @13m█ █ █ @15mCORE \" \"\\x1b[0m\\n\\x1b[40m\\x1b[1m\" // NOLINT\n\n \" @197m▀ ▀ ▀ @39m▀▀▀▀▀ @11m▀ ▀ ▀ @129m▀▀▀▀▀ @47m▀ ▀ ▀ @9m▀ ▀ ▀ @27m▀ ▀ ▀ @154m▀▀▀▀▀ @13m▀ ▀▀▀ @15mv0.0.1 \" \"\\x1b[0m\\n\\x1b[40m\\x1b[1m\" // NOLINT\n\n \" \" \"\\x1b[0m\\n@0m\"\n\n \"▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀\" \"\\x1b[0m\\n\";\n\n\n", "file_path": "src/automaton/core/core.cc", "rank": 64, "score": 60008.60095139311 }, { "content": " LOG(INFO) << \"Server received command: \" << cmd << \" -> \" << automaton::core::io::bin2hex(msg);\n\n if (msg.size() > 0) {\n\n CryptoPP::StringSource ss(msg, true, new CryptoPP::Base64Decoder(new CryptoPP::StringSink(params)));\n\n }\n\n if ((*script)[cmd] == nullptr) {\n\n LOG(ERROR) << \"ERROR in rpc server handler: Invalid request\";\n\n *s = http_server::status_code::BAD_REQUEST;\n\n return \"\";\n\n }\n\n sol::protected_function_result pfr = (*script)[cmd](params);\n\n if (!pfr.valid()) {\n\n sol::error err = pfr;\n\n LOG(ERROR) << \"ERROR in rpc server handler: \" << err.what();\n\n *s = http_server::status_code::INTERNAL_SERVER_ERROR;\n\n return \"\";\n\n }\n\n std::string result = pfr;\n\n if (s != nullptr) {\n\n *s = http_server::status_code::OK;\n\n } else {\n", "file_path": "src/automaton/core/core.cc", "rank": 65, "score": 60006.569943505136 }, { "content": "\n\nhistory_add(\"add_peers()\")\n\nhints_add(\"add_peers()\")\n\nhistory_add(\"remove_peers()\")\n\nhints_add(\"remove_peers()\")\n\nhistory_add(\"list_known_peers()\")\n\nhints_add(\"list_known_peers()\")\n\nhistory_add(\"list_connected_peers()\")\n\nhints_add(\"list_connected_peers()\")\n\nhistory_add(\"get_peers()\")\n\nhints_add(\"get_peers()\")\n\nhistory_add(\"connect()\")\n\nhints_add(\"connect()\")\n\nhistory_add(\"disconnect()\")\n\nhints_add(\"disconnect()\")\n\nhistory_add(\"process_cmd()\")\n\nhints_add(\"process_cmd()\")\n\n\n\nhistory_add(\"testnet_create()\")\n\nhints_add(\"testnet_create()\")\n", "file_path": "src/automaton/core/core.lua", "rank": 66, "score": 60005.1849412731 }, { "content": "-- core.lua\n\n\n\n-- add rpc/core commands to cli history/hints\n\nhistory_add(\"list_supported_protocols()\")\n\nhints_add(\"list_supported_protocols()\")\n\nhistory_add(\"list_running_protocols()\")\n\nhints_add(\"list_running_protocols()\")\n\nhistory_add(\"get_protocols()\")\n\nhints_add(\"get_protocols()\")\n\nhistory_add(\"load_protocol()\")\n\nhints_add(\"load_protocol()\")\n\n\n\nhistory_add(\"launch_node()\")\n\nhints_add(\"launch_node()\")\n\nhistory_add(\"list_nodes()\")\n\nhints_add(\"list_nodes()\")\n\nhistory_add(\"get_node()\")\n\nhints_add(\"get_node()\")\n\nhistory_add(\"remove_node()\")\n\nhints_add(\"remove_node()\")\n", "file_path": "src/automaton/core/core.lua", "rank": 67, "score": 60004.942561872005 }, { "content": " sol::protected_function_result pfr = script.safe_script(cmd, &sol::script_pass_on_error);\n\n logger_mutex.unlock();\n\n\n\n if (!pfr.valid()) {\n\n sol::error err = pfr;\n\n LOG(ERROR) << \"Error while executing command: \" << err.what();\n\n }\n\n }\n\n\n\n rpc_server.stop();\n\n\n\n updater->stop();\n\n delete updater;\n\n\n\n stop_logger = true;\n\n logger.join();\n\n\n\n LOG(DBUG) << \"Destroying lua state & objects\";\n\n\n\n sim->simulation_stop();\n", "file_path": "src/automaton/core/core.cc", "rank": 68, "score": 60000.730238236814 }, { "content": "end\n\n-----------------\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 69, "score": 60000.730238236814 }, { "content": " while (!stop_logger) {\n\n // Dump logs once per second.\n\n std::this_thread::sleep_for(std::chrono::milliseconds(1500));\n\n logger_mutex.lock();\n\n try {\n\n sol::protected_function_result pfr;\n\n pfr = script.safe_script(\n\n R\"(for k,v in pairs(networks) do\n\n dump_logs(k)\n\n end\n\n )\");\n\n if (!pfr.valid()) {\n\n sol::error err = pfr;\n\n std::cout << \"\\n\" << err.what() << \"\\n\";\n\n break;\n\n }\n\n } catch (std::exception& e) {\n\n LOG(FATAL) << \"Exception in logger: \" << e.what();\n\n } catch (...) {\n\n LOG(FATAL) << \"Exception in logger\";\n", "file_path": "src/automaton/core/core.cc", "rank": 70, "score": 60000.730238236814 }, { "content": "function sent(peer_id, msg_id)\n\nend\n\n\n\nMIN_LAG = 0\n\nMAX_LAG = 0\n\nlag = 0\n\nd_blocks = {}\n\ncurrent_message_id = 0\n\n\n", "file_path": "src/automaton/examples/smartproto/blockchain/connections.lua", "rank": 71, "score": 59140.89621652327 }, { "content": "function sent(peer_id, msg_id, success)\n\n -- log(\"sent\",\n\n -- string.format(\"Sent to %s (%d), success: %s\", peers[peer_id].name, msg_id, tostring(success))\n\n -- )\n\nend\n\n\n", "file_path": "src/automaton/examples/smartproto/chat/chat.lua", "rank": 72, "score": 58341.32782408651 }, { "content": "function sent(peer_id, msg_id, success)\n\nend\n\n\n", "file_path": "src/automaton/examples/smartproto/reservationsystem/reservationsystem.lua", "rank": 73, "score": 58341.32782408651 }, { "content": "function list_nodes()\n\n local res = NodeIdsList()\n\n for _,id in ipairs(list_nodes_as_table()) do\n\n res.node_ids = id\n\n end\n\n return res:serialize()\n\nend\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 74, "score": 58214.18348942617 }, { "content": "function rpc_disconnect(m)\n\n local request = PeerIdsList()\n\n request:deserialize(m)\n\n return disconnect(request.node_id, request.peer_ids)\n\nend\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 75, "score": 58214.18348942617 }, { "content": "function rpc_connect(m)\n\n local request = PeerIdsList()\n\n request:deserialize(m)\n\n return connect(request.node_id, request.peer_ids)\n\nend\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 76, "score": 58214.18348942617 }, { "content": "#include <memory>\n\n#include <string>\n\n\n\n#include \"automaton/core/network/tcp_implementation.h\"\n\n\n\nstatic const char* SERVER_ADDRESS = \"127.0.0.1:33777\";\n\nusing namespace automaton::core::network; // NOLINT\n\n\n\nstd::shared_ptr<connection> connection_c;\n\n\n", "file_path": "src/automaton/core/rpc_server_core_test.cc", "rank": 77, "score": 57386.562634860435 }, { "content": " std::stringstream ss;\n\n ss << \"GET /hello.htm HTTP/1.1\\r\\n\";\n\n ss << \"User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)\\r\\n\";\n\n ss << \"Host: localhost\\r\\n\";\n\n ss << \"Accept-Language: en-us\\r\\n\";\n\n ss << \"Accept-Encoding: gzip, deflate\\r\\n\";\n\n ss << \"Content-Length: \" << input.size() << \"\\r\\n\";\n\n ss << \"Connection: Keep-Alive\\r\\n\";\n\n ss << \"\\r\\n\" << input;\n\n\n\n connection_c -> async_send(ss.str(), 0);\n\n }\n\n connection_c -> disconnect();\n\n } else {\n\n std::cout << \"Connection init failed!\" << std::endl;\n\n }\n\n}\n\n\n\nint main(int argc, char* argv[]) {\n\n automaton::core::network::tcp_init();\n\n client();\n\n automaton::core::network::tcp_release();\n\n return 0;\n\n}\n", "file_path": "src/automaton/core/rpc_server_core_test.cc", "rank": 78, "score": 57373.54285717968 }, { "content": " void on_connection_error(connection_id c, const automaton::core::common::status& s) {\n\n if (s.code == automaton::core::common::status::OK) {\n\n return;\n\n }\n\n std::cout << s << std::endl;\n\n }\n\n};\n\n\n\nstd::shared_ptr<char> buffer_c = std::shared_ptr<char>(new char[256], std::default_delete<char[]>());\n\n\n\nstd::shared_ptr<client_handler> handler_c;\n\n\n\nvoid client() {\n\n connection_c = connection::create(\"tcp\", 1, SERVER_ADDRESS, std::move(handler_c));\n\n if (connection_c->init()) {\n\n std::cout << \"Connection init was successful!\" << std::endl;\n\n connection_c -> connect();\n\n connection_c -> async_read(buffer_c, 256, 0, 0);\n\n std::string input;\n\n while (std::getline(std::cin, input)) {\n", "file_path": "src/automaton/core/rpc_server_core_test.cc", "rank": 79, "score": 57373.31224076798 }, { "content": "function rpc_process_cmd(m)\n\n local request = NodeCmdRequest()\n\n request:deserialize(m)\n\n return process_cmd(request.node_id, request.cmd, request.params)\n\nend\n\n\n\n-- TESTNET --\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 80, "score": 57361.6041668068 }, { "content": "function rpc_list_nodes()\n\n return list_nodes()\n\nend\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 81, "score": 57361.6041668068 }, { "content": "function rpc_get_protocols(m)\n\n local request = ProtocolIDsList()\n\n request:deserialize(m)\n\n return get_protocols(request.protocol_ids)\n\nend\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 82, "score": 57361.6041668068 }, { "content": "function rpc_launch_node(m)\n\n local msg = Node()\n\n msg:deserialize(m)\n\n return launch_node(msg.id, msg.protocol_id, msg.address) -- implemented in core.cc\n\nend\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 83, "score": 57361.6041668068 }, { "content": "function list_supported_protocols()\n\n local m = ProtocolIDsList()\n\n for k,_ in pairs(get_core_supported_protocols()) do\n\n m.protocol_ids = k\n\n end\n\n return m:serialize()\n\nend\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 84, "score": 57361.6041668068 }, { "content": "function rpc_get_nodes(m)\n\n local request = NodeIdsList()\n\n request:deserialize(m)\n\n return get_nodes(request.node_ids)\n\nend\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 85, "score": 57361.6041668068 }, { "content": "function rpc_load_protocols(m)\n\n local request = ProtocolsList()\n\n request:deserialize(m)\n\n local protocol_list = {}\n\n for _,p in ipairs(request.protocols) do\n\n protocol_list[p.protocol_id] = p.path\n\n end\n\n return load_protocols(protocol_list)\n\nend\n\n\n\n-- NODE RPC COMMON --\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 86, "score": 57361.6041668068 }, { "content": "function rpc_remove_peers(m)\n\n local request = PeerIdsList()\n\n request:deserialize(m)\n\n return remove_peers(request.node_id, request.peer_ids)\n\nend\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 87, "score": 57361.6041668068 }, { "content": "function rpc_remove_nodes(m)\n\n\n\nend\n\n\n\n-- NODE RPC --\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 88, "score": 57361.6041668068 }, { "content": "function rpc_get_peers(m)\n\n local request = PeerIdsList()\n\n request:deserialize(m)\n\n return get_peers(request.node_id, request.peer_ids)\n\nend\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 89, "score": 57361.6041668068 }, { "content": "function rpc_add_peers(m)\n\n local request = PeerAddressesList()\n\n request:deserialize(m)\n\n return add_peers(request.node_id, request.peer_addresses)\n\nend\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 90, "score": 57361.6041668068 }, { "content": "function list_running_protocols()\n\n -- local response = ListProtocolsResponse()\n\n -- need to store and get info\n\n print(\"This function is not yet supported\")\n\n return \"\"\n\n -- return response:serialize()\n\nend\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 91, "score": 57361.6041668068 }, { "content": "function rpc_list_supported_protocols()\n\n return list_supported_protocols()\n\nend\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 92, "score": 56534.45904601318 }, { "content": "function rpc_list_connected_peers(m)\n\n local request = NodeId()\n\n request:deserialize(m)\n\n return list_connected_peers(request.node_id)\n\nend\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 93, "score": 56534.45904601318 }, { "content": "function rpc_list_known_peers(m)\n\n local request = NodeId()\n\n request:deserialize(m)\n\n return list_known_peers(request.node_id)\n\nend\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 94, "score": 56534.45904601318 }, { "content": "function rpc_list_running_protocols()\n\n return list_running_protocols()\n\nend\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 95, "score": 56534.45904601318 }, { "content": "function load_protocols(protocol_list)\n\n for pid, path in pairs(protocol_list) do\n\n load_protocol(pid, path)\n\n end\n\n return \"\"\n\nend\n\n\n", "file_path": "src/automaton/core/core.lua", "rank": 96, "score": 56534.45904601318 }, { "content": " return std::shared_ptr<node>(new lua_node(id, proto_id));\n\n });\n\n\n\n EXPECT_EQ(smart_protocol::load(\"chat\", \"automaton/tests/testnet/testproto/\"), true);\n\n\n\n std::shared_ptr<automaton::core::network::simulation> sim = automaton::core::network::simulation::get_simulator();\n\n sim->simulation_start(50);\n\n\n\n EXPECT_EQ(testnet::create_testnet(\"lua\", \"testnet\", \"chat\", testnet::network_protocol_type::simulation, 5,\n\n {\n\n {1, {2, 3}}, {2, {4, 5}}\n\n }),\n\n true);\n\n\n\n auto net = testnet::get_testnet(\"testnet\");\n\n std::vector<std::string> ids = net->list_nodes();\n\n\n\n default_node_updater updater(1, 20, std::set<std::string>(ids.begin(), ids.end()));\n\n updater.start();\n\n\n", "file_path": "src/automaton/tests/testnet/test_simulation.cc", "rank": 97, "score": 53121.353129425195 }, { "content": " return std::shared_ptr<node>(new lua_node(id, proto_id));\n\n });\n\n\n\n EXPECT_EQ(smart_protocol::load(\"chat\", \"automaton/tests/testnet/testproto/\"), true);\n\n\n\n automaton::core::network::tcp_init();\n\n\n\n EXPECT_EQ(testnet::create_testnet(\"lua\", \"testnet\", \"chat\", testnet::network_protocol_type::localhost, 5,\n\n {\n\n {1, {2, 3}}, {2, {4, 5}}\n\n }),\n\n true);\n\n\n\n auto net = testnet::get_testnet(\"testnet\");\n\n std::vector<std::string> ids = net->list_nodes();\n\n\n\n default_node_updater updater(1, 20, std::set<std::string>(ids.begin(), ids.end()));\n\n updater.start();\n\n\n\n auto msg_factory = smart_protocol::get_protocol(\"chat\")->get_factory();\n", "file_path": "src/automaton/tests/testnet/test_localhost.cc", "rank": 98, "score": 53120.95427097712 }, { "content": "#include \"automaton/core/data/factory.h\"\n\n#include \"automaton/core/data/protobuf/protobuf_factory.h\"\n\n#include \"automaton/core/data/protobuf/protobuf_schema.h\"\n\n#include \"automaton/core/network/simulated_connection.h\"\n\n#include \"automaton/core/node/node.h\"\n\n#include \"automaton/core/node/node_updater.h\"\n\n#include \"automaton/core/node/lua_node/lua_node.h\"\n\n#include \"automaton/core/smartproto/smart_protocol.h\"\n\n#include \"automaton/core/testnet/testnet.h\"\n\n\n\n#include \"gtest/gtest.h\"\n\n\n\nusing automaton::core::node::node;\n\nusing automaton::core::node::default_node_updater;\n\nusing automaton::core::node::luanode::lua_node;\n\nusing automaton::core::smartproto::smart_protocol;\n\nusing automaton::core::testnet::testnet;\n\n\n\nTEST(testnet, test_all) {\n\n node::register_node_type(\"lua\", [](const std::string& id, const std::string& proto_id)->std::shared_ptr<node> {\n", "file_path": "src/automaton/tests/testnet/test_simulation.cc", "rank": 99, "score": 53117.742079269316 } ]
C++
include/SctpSocket.hpp
GaborTimko/lsctp
cdc89010b1afcc2ed9cd811a61256749938a54dd
#ifndef LSSOCKET_HPP #define LSSOCKET_HPP #include <vector> #include <cstring> #include <cerrno> #include <type_traits> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/sctp.h> #include <arpa/inet.h> #include <unistd.h> #include <fcntl.h> #include "Lua/Lua.hpp" namespace Sctp { namespace Socket { template<int IPVersion> class Base { static_assert(IPVersion == 4 or IPVersion == 6, ""); public: using SockAddrType = std::conditional_t<IPVersion == 4, sockaddr_in, sockaddr_in6>; using AddressArray = std::vector<SockAddrType>; static constexpr int IPv = IPVersion; protected: int fd; bool haveBoundAddresses; AddressArray boundAddresses; public: Base() noexcept; Base(int sock) noexcept; ~Base(); public: auto create() noexcept -> bool; auto bind(Lua::State*) noexcept -> int; auto close(Lua::State*) noexcept -> int; auto setNonBlocking(Lua::State*) noexcept -> int; protected: auto loadAddresses(Lua::State*, AddressArray&) noexcept -> int; private: auto bindFirst(Lua::State*) noexcept -> int; auto pushIPAddress(Lua::State*, AddressArray&, const char* ip, uint16_t port, int idx) noexcept -> int; auto checkIPConversionResult(Lua::State*, const char* ip, int result) noexcept -> int; }; template<int IPVersion> Base<IPVersion>::Base() noexcept : haveBoundAddresses(false) {} template<int IPVersion> auto Base<IPVersion>::create() noexcept -> bool { fd = ::socket(IPVersion == 4 ? AF_INET : AF_INET6, SOCK_STREAM, IPPROTO_SCTP); if(fd == -1) { return false; } int True = 1; setsockopt(fd, IPPROTO_SCTP, SO_REUSEADDR, &True, sizeof(int)); return true; } template<int IPVersion> Base<IPVersion>::Base(int sock) noexcept : fd(sock), haveBoundAddresses(false) {} template<int IPVersion> Base<IPVersion>::~Base() { ::close(fd); } template<int IPVersion> auto Base<IPVersion>::setNonBlocking(Lua::State* L) noexcept -> int { int flags = fcntl(fd, F_GETFL); if(flags < 0) { Lua::PushBoolean(L, false); Lua::PushFString(L, "fcntl(get): %s", std::strerror(errno)); return 2; } flags = fcntl(fd, F_SETFL, flags | O_NONBLOCK); if(flags < 0) { Lua::PushBoolean(L, false); Lua::PushFString(L, "fcntl(set): %s", std::strerror(errno)); return 2; } Lua::PushBoolean(L, true); return 1; } template<int IPVersion> auto Base<IPVersion>::bind(Lua::State* L) noexcept -> int { int loadAddrResult = loadAddresses(L, boundAddresses); std::size_t addrCount = boundAddresses.size(); if(loadAddrResult > 0) { return loadAddrResult; } int retVal = bindFirst(L); if(retVal > 0) { return retVal; } if(addrCount > 1) { if(::sctp_bindx(fd, reinterpret_cast<sockaddr*>(boundAddresses.data() + 1), addrCount - 1, SCTP_BINDX_ADD_ADDR) < 0) { Lua::PushBoolean(L, false); Lua::PushFString(L, "sctp_bindx: %s", std::strerror(errno)); return 2; } } haveBoundAddresses = true; Lua::PushBoolean(L, true); return 1; } template<int IPVersion> auto Base<IPVersion>::loadAddresses(Lua::State* L, AddressArray& addrs) noexcept -> int { uint16_t port = htons(Lua::ToInteger(L, 2)); int stackSize = Lua::GetTop(L); std::size_t addrCount = stackSize - 2; if(addrCount < 1) { Lua::PushBoolean(L, false); Lua::PushString(L, "No addresses were given"); return 2; } addrs.clear(); addrs.resize(addrCount); std::memset(addrs.data(), 0, sizeof(SockAddrType) * addrCount); for(int i = 3; i <= stackSize; i++) { int idx = i - 3; auto addrI = Lua::ToString(L, i); int pushResult = pushIPAddress(L, addrs, addrI, port, idx); if(pushResult > 0) { return pushResult; } } return 0; } template<int IPVersion> auto Base<IPVersion>::bindFirst(Lua::State* L) noexcept -> int { int bindRes = ::bind(fd, reinterpret_cast<sockaddr*>(boundAddresses.data()), sizeof(SockAddrType)); if(bindRes < 0) { Lua::PushBoolean(L, false); Lua::PushFString(L, "bind: %s", std::strerror(errno)); return 2; } return bindRes; } template<> inline auto Base<4>::pushIPAddress(Lua::State* L, AddressArray& addrs, const char* ip, uint16_t port, int idx) noexcept -> int { addrs[idx].sin_family = AF_INET; addrs[idx].sin_port = port; int conversion = ::inet_pton(AF_INET, ip, &addrs[idx].sin_addr); return checkIPConversionResult(L, ip, conversion); } template<> inline auto Base<6>::pushIPAddress(Lua::State* L, AddressArray& addrs, const char* ip, uint16_t port, int idx) noexcept -> int { addrs[idx].sin6_family = AF_INET6; addrs[idx].sin6_port = port; int conversion = ::inet_pton(AF_INET6, ip, &addrs[idx].sin6_addr); return checkIPConversionResult(L, ip, conversion); } template<int IPVersion> auto Base<IPVersion>::checkIPConversionResult(Lua::State* L, const char* ip, int result) noexcept -> int { if(result == 0) { Lua::PushBoolean(L, false); Lua::PushFString(L, "inet_pton: invalid IP: %s", ip); return 2; } else if (result < 0) { Lua::PushBoolean(L, false); Lua::PushFString(L, "inet_pton: %s", std::strerror(errno)); return 2; } return 0; } template<int IPVersion> auto Base<IPVersion>::close(Lua::State* L) noexcept -> int { if(fd > -1 and ::close(fd) < 0) { Lua::PushBoolean(L, false); Lua::PushFString(L, "close: %s", std::strerror(errno)); fd = -1; return 2; } fd = -1; boundAddresses.clear(); Lua::PushBoolean(L, true); return 1; } } template<class Type> struct IsSctpSocket : public std::integral_constant<bool, std::is_same<Type, Socket::Base<4>>::value or std::is_same<Type, Socket::Base<6>>::value or std::is_base_of<Socket::Base<4>, Type>::value or std::is_base_of<Socket::Base<6>, Type>::value> { }; } #endif
#ifndef LSSOCKET_HPP #define LSSOCKET_HPP #include <vector> #include <cstring> #include <cerrno> #include <type_traits> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/sctp.h> #include <arpa/inet.h> #include <unistd.h> #include <fcntl.h> #include "Lua/Lua.hpp" namespace Sctp { namespace Socket { template<int IPVersion> class Base { static_assert(IPVersion == 4 or IPVersion == 6, ""); public: using SockAddrType = std::conditional_t<IPVersion == 4, sockaddr_in, sockaddr_in6>; using AddressArray = std::vector<SockAddrType>; static constexpr int IPv = IPVersion; protected: int fd; bool haveBoundAddresses; AddressArray boundAddresses; public: Base() noexcept; Base(int sock) noexcept; ~Base(); public: auto create() noexcept -> bool; auto bind(Lua::State*) noexcept -> int; auto close(Lua::State*) noexcept -> int; auto setNonBlocking(Lua::State*) noexcept -> int; protected: auto loadAddresses(Lua::State*, AddressArray&) noexcept -> int; private: auto bindFirst(Lua::State*) noexcept -> int; auto pushIPAddress(Lua::State*, AddressArray&, const char* ip, uint16_t port, int idx) noexcept -> int; auto checkIPConversionResult(Lua::State*, const char* ip, int result) noexcept -> int; }; template<int IPVersion> Base<IPVersion>::Base() noexcept : haveBoundAddresses(false) {} template<int IPVersion> auto Base<IPVersion>::create() noexcept -> bool { fd = ::socket(IPVersion == 4 ? AF_INET : AF_INET6, SOCK_STREAM, IPPROTO_SCTP); if(fd == -1) { return false; } int True = 1; setsockopt(fd, IPPROTO_SCTP, SO_REUSEADDR, &True, sizeof(int)); return true; } template<int IPVersion> Base<IPVersion>::Base(int sock) noexcept : fd(sock), haveBoundAddresses(false) {} template<int IPVersion> Base<IPVersion>::~Base() { ::close(fd); } template<int IPVersion> auto Base<IPVersion>::setNonBlocking(Lua::State* L) noexcept -> int { int flags = fcntl(fd, F_GETFL); if(flags < 0) { Lua::PushBoolean(L, false); Lua::PushFString(L, "fcntl(get): %s", std::strerror(errno)); return 2; } flags = fcntl(fd, F_SETFL, flags | O_NONBLOCK); if(flags < 0) { Lua::PushBoolean(L, false); Lua::PushFString(L, "fcntl(set): %s", std::strerror(errno)); return 2; } Lua::PushBoolean(L, true); return 1; } template<int IPVersion> auto Base<IPVersion>::bind(Lua::State* L) noexcept -> int { int loadAddrResult = loadAddresses(L, boundAddresses); std::size_t addrCount = boundAddresses.size(); if(loadAddrResult > 0) { return loadAddrResult; } int retVal = bindFirst(L); if(retVal > 0) { return retVal; } if(addrCount > 1) { if(::sctp_bindx(fd, reinterpret_cast<sockaddr*>(boundAddresses.data() + 1), addrCount - 1, SCTP_BINDX_ADD_ADDR) < 0) { Lua::PushBoolean(L, false); Lua::PushFString(L, "sctp_bindx: %s", std::strerror(errno)); return 2; } } haveBoundAddresses = true; Lua::PushBoolean(L, true); return 1; } template<int IPVersion> auto Base<IPVersion>::loadAddresses(Lua::State* L, AddressArray& addrs) noexcept -> int { uint16_t port = htons(Lua::ToInteger(L, 2)); int stackSize = Lua::GetTop(L); std::size_t addrCount = stackSize - 2; if(addrCount < 1) { Lua::PushBoolean(L, false); Lua::PushString(L, "No addresses were given"); return 2; } addrs.clear(); addrs.resize(addrCount); std::memset(addrs.data(), 0, sizeof(SockAddrType) * addrCount); for(int i = 3; i <= stackSize; i++) { int idx = i - 3; auto addrI = Lua::ToString(L, i); int pushResult = pushIPAddress(L, addrs, addrI, port, idx); if(pushResult > 0) { return pushResult; } } return 0; } template<int IPVersion> auto Base<IPVersion>::bindFirst(Lua::State* L) noexcept -> int { int bindRes = ::bind(fd, reinterpret_cast<sockaddr*>(boundAddresses.data()), sizeof(SockAddrType)); if(bindRes < 0) { Lua::PushBoolean(L, false); Lua::PushFString(L, "bind: %s", std::strerror(errno)); return 2; } return bindRes; } template<>
template<> inline auto Base<6>::pushIPAddress(Lua::State* L, AddressArray& addrs, const char* ip, uint16_t port, int idx) noexcept -> int { addrs[idx].sin6_family = AF_INET6; addrs[idx].sin6_port = port; int conversion = ::inet_pton(AF_INET6, ip, &addrs[idx].sin6_addr); return checkIPConversionResult(L, ip, conversion); } template<int IPVersion> auto Base<IPVersion>::checkIPConversionResult(Lua::State* L, const char* ip, int result) noexcept -> int { if(result == 0) { Lua::PushBoolean(L, false); Lua::PushFString(L, "inet_pton: invalid IP: %s", ip); return 2; } else if (result < 0) { Lua::PushBoolean(L, false); Lua::PushFString(L, "inet_pton: %s", std::strerror(errno)); return 2; } return 0; } template<int IPVersion> auto Base<IPVersion>::close(Lua::State* L) noexcept -> int { if(fd > -1 and ::close(fd) < 0) { Lua::PushBoolean(L, false); Lua::PushFString(L, "close: %s", std::strerror(errno)); fd = -1; return 2; } fd = -1; boundAddresses.clear(); Lua::PushBoolean(L, true); return 1; } } template<class Type> struct IsSctpSocket : public std::integral_constant<bool, std::is_same<Type, Socket::Base<4>>::value or std::is_same<Type, Socket::Base<6>>::value or std::is_base_of<Socket::Base<4>, Type>::value or std::is_base_of<Socket::Base<6>, Type>::value> { }; } #endif
inline auto Base<4>::pushIPAddress(Lua::State* L, AddressArray& addrs, const char* ip, uint16_t port, int idx) noexcept -> int { addrs[idx].sin_family = AF_INET; addrs[idx].sin_port = port; int conversion = ::inet_pton(AF_INET, ip, &addrs[idx].sin_addr); return checkIPConversionResult(L, ip, conversion); }
function_block-full_function
[ { "content": "class Server final : public Base<IPVersion> {\n\npublic:\n\n static constexpr int DefaultBackLogSize = 1000;\n\n static const char* MetaTableName;\n\npublic:\n\n Server() : Base<IPVersion>() {}\n\npublic:\n\n auto listen(Lua::State*) noexcept -> int;\n\n auto accept(Lua::State*) noexcept -> int;\n\n};\n\n\n\ntemplate<int IPVersion>\n\nauto Server<IPVersion>::listen(Lua::State* L) noexcept -> int {\n\n int backLogSize = Lua::Aux::OptInteger(L, 2, Server<IPVersion>::DefaultBackLogSize);\n\n int result = ::listen(this->fd, backLogSize);\n\n if(result < 0) {\n\n Lua::PushBoolean(L, false);\n\n Lua::PushFString(L, \"listen: %s\", std::strerror(errno));\n\n return 2;\n\n }\n", "file_path": "include/SctpServerSocket.hpp", "rank": 0, "score": 343239.04808772984 }, { "content": "class Client final : public Base<IPVersion> {\n\npublic:\n\n static const char* MetaTableName;\n\n static const std::size_t MaxRecvBufferSize = 5000;\n\nprivate:\n\n char recvBuffer[MaxRecvBufferSize];\n\npublic:\n\n Client() : Base<IPVersion>() {}\n\n Client(int sock);\n\npublic:\n\n auto connect(Lua::State*) noexcept -> int;\n\n auto sendmsg(Lua::State*) noexcept -> int;\n\n auto recvmsg(Lua::State*) noexcept -> int;\n\n};\n\n\n\ntemplate<int IPVersion>\n\nClient<IPVersion>::Client(int sock) : Base<IPVersion>(sock) {}\n\n\n\ntemplate<int IPVersion>\n\nauto Client<IPVersion>::connect(Lua::State* L) noexcept -> int {\n", "file_path": "include/SctpClientSocket.hpp", "rank": 1, "score": 343239.04808772984 }, { "content": " typename Base<IPVersion>::AddressArray peerAddresses;\n\n int loadAddrResult = this->loadAddresses(L, peerAddresses);\n\n if(loadAddrResult > 0) {\n\n return loadAddrResult;\n\n }\n\n\n\n if(::sctp_connectx(this->fd, reinterpret_cast<sockaddr*>(peerAddresses.data()), peerAddresses.size(), nullptr) < 0) {\n\n Lua::PushBoolean(L, false);\n\n Lua::PushFString(L, \"sctp_connectx: %s\", std::strerror(errno));\n\n return 2;\n\n }\n\n\n\n Lua::PushBoolean(L, true);\n\n return 1;\n\n}\n\n\n\ntemplate<int IPVersion>\n\nauto Client<IPVersion>::sendmsg(Lua::State* L) noexcept -> int {\n\n std::size_t bufferLength;\n\n auto buffer = Lua::Aux::CheckLString(L, -1, bufferLength);\n", "file_path": "include/SctpClientSocket.hpp", "rank": 13, "score": 149133.79724916868 }, { "content": "#ifndef SCTPSERVERSOCKET_HPP\n\n#define SCTPSERVERSOCKET_HPP\n\n\n\n#include \"SctpSocket.hpp\"\n\n#include \"SctpClientSocket.hpp\"\n\n\n\nnamespace Sctp {\n\n\n\nnamespace Socket {\n\n\n\ntemplate<int IPVersion>\n", "file_path": "include/SctpServerSocket.hpp", "rank": 14, "score": 149131.08434680558 }, { "content": "#ifndef SCTPCLIENTSOCKET_HPP\n\n#define SCTPCLIENTSOCKET_HPP\n\n\n\n#include \"SctpSocket.hpp\"\n\n\n\nnamespace Sctp {\n\n\n\nnamespace Socket {\n\n\n\ntemplate<int IPVersion>\n", "file_path": "include/SctpClientSocket.hpp", "rank": 15, "score": 149130.85856605924 }, { "content": " Lua::PushBoolean(L, true);\n\n return 1;\n\n}\n\n\n\ntemplate<int IPVersion>\n\nauto Server<IPVersion>::accept(Lua::State* L) noexcept -> int {\n\n int newFD = ::accept(this->fd, nullptr, nullptr);\n\n if(newFD < 0 and (errno == EAGAIN or errno == EWOULDBLOCK)) {\n\n //Non-blocking socket is being used, nothing to do\n\n Lua::PushBoolean(L, false);\n\n Lua::PushString(L, \"EAGAIN/EWOULDBLOCK\");\n\n return 2;\n\n } else if(newFD < 0) {\n\n Lua::PushBoolean(L, false);\n\n Lua::PushFString(L, \"accept() failed: %s\", std::strerror(errno));\n\n return 2;\n\n }\n\n auto connSock = Lua::NewUserData<Sctp::Socket::Client<IPVersion>>(L);\n\n if(connSock == nullptr) {\n\n Lua::PushNil(L);\n", "file_path": "include/SctpServerSocket.hpp", "rank": 16, "score": 149130.20075423576 }, { "content": " Lua::PushString(L, \"Socket userdata allocation failed\");\n\n return 2;\n\n }\n\n\n\n new (connSock) Sctp::Socket::Client<IPVersion>(newFD);\n\n\n\n Lua::Aux::GetMetaTable(L, Sctp::Socket::Client<IPVersion>::MetaTableName);\n\n Lua::SetMetaTable(L, -2);\n\n return 1;\n\n}\n\n\n\n} //namespace Socket\n\n\n\n} //namespace Sctp\n\n\n\n\n\n#endif /* SCTPSERVERSOCKET_HPP */\n\n\n", "file_path": "include/SctpServerSocket.hpp", "rank": 17, "score": 149127.49328594562 }, { "content": "\n\n// sctp_sndrcvinfo info;\n\n// std::memset(&info, 0, sizeof(sctp_sndrcvinfo));\n\n\n\n //TODO: Add support for choosing at least ppid, stream number and flags\n\n ssize_t numBytesSent = ::sctp_sendmsg(this->fd, buffer, bufferLength, nullptr, 0, 0, 0, 0, 0, 0);\n\n if(numBytesSent < 0) {\n\n Lua::PushBoolean(L, false);\n\n Lua::PushFString(L, (errno == EAGAIN ? \"EAGAIN\" : \"sctp_sendmsg: %s\"), std::strerror(errno));\n\n return 2;\n\n }\n\n Lua::PushInteger(L, numBytesSent);\n\n return 1;\n\n}\n\n\n\ntemplate<int IPVersion>\n\nauto Client<IPVersion>::recvmsg(Lua::State* L) noexcept -> int {\n\n// sctp_sndrcvinfo info;\n\n// std::memset(&info, 0, sizeof(sctp_sndrcvinfo));\n\n\n", "file_path": "include/SctpClientSocket.hpp", "rank": 18, "score": 149123.7412056626 }, { "content": " //TODO: Add support for filling sctp_sndrcvinfo and flags\n\n std::memset(&recvBuffer, 0, sizeof(recvBuffer));\n\n ssize_t numBytesReceived = ::sctp_recvmsg(this->fd, recvBuffer, MaxRecvBufferSize, nullptr, nullptr, nullptr, nullptr);\n\n if(numBytesReceived < 0) {\n\n Lua::PushBoolean(L, false);\n\n Lua::PushFString(L, (errno == EAGAIN or errno == EWOULDBLOCK ? \"EAGAIN/EWOULDBLOCK\" : \"sctp_recvmsg: %s\"), std::strerror(errno));\n\n return 2;\n\n }\n\n Lua::PushInteger(L, numBytesReceived);\n\n Lua::PushLString(L, recvBuffer, numBytesReceived);\n\n return 2;\n\n}\n\n\n\n} //namespace Socket\n\n\n\n} //namespace Sctp\n\n\n\n#endif /* SCTPCLIENTSOCKET_HPP */\n\n\n", "file_path": "include/SctpClientSocket.hpp", "rank": 19, "score": 149119.52590539312 }, { "content": "enum class Types {\n\n None = LUA_TNONE,\n\n Nil = LUA_TNIL,\n\n Boolean = LUA_TBOOLEAN,\n\n LightUserData = LUA_TLIGHTUSERDATA,\n\n Number = LUA_TNUMBER,\n\n String = LUA_TSTRING,\n\n Table = LUA_TTABLE,\n\n Function = LUA_TFUNCTION,\n\n UserData = LUA_TUSERDATA,\n\n Thread = LUA_TTHREAD,\n\n NumTags = LUA_NUMTAGS\n\n};\n\n\n\n\n\ntemplate<class ConstType>\n\nconstexpr ConstType MinStack = ConstType(LUA_MINSTACK);\n\n\n\n\n", "file_path": "include/Lua/Lua.hpp", "rank": 20, "score": 117023.18663559256 }, { "content": "enum class Hooks {\n\n Call = LUA_HOOKCALL,\n\n Return = LUA_HOOKRET,\n\n Line = LUA_HOOKLINE,\n\n Count = LUA_HOOKCOUNT,\n\n TailCall = LUA_HOOKTAILCALL\n\n};\n\n\n", "file_path": "include/Lua/Lua.hpp", "rank": 21, "score": 117023.18663559256 }, { "content": "enum class Statuses {\n\n OK = LUA_OK,\n\n Yield = LUA_YIELD,\n\n RuntimeError = LUA_ERRRUN,\n\n SyntaxError = LUA_ERRSYNTAX,\n\n MemAllocError = LUA_ERRMEM,\n\n GCMethaMError = LUA_ERRGCMM,\n\n MsgHandlerError = LUA_ERRERR,\n\n FileError = LUA_ERRFILE\n\n};\n\n\n\nusing State = detail::lua_State;\n\n\n", "file_path": "include/Lua/Lua.hpp", "rank": 22, "score": 117023.18663559256 }, { "content": "enum class HookMasks {\n\n Call = LUA_MASKCALL,\n\n Return = LUA_MASKRET,\n\n Line = LUA_MASKLINE,\n\n Count = LUA_MASKCOUNT\n\n};\n\n\n\n\n\nusing Debug = detail::lua_Debug;\n\n\n\nusing Hook = detail::lua_Hook;\n\n\n\n\n\ninline bool GetStack(State* L, int level, Debug* ar) {\n\n return static_cast<bool>(detail::lua_getstack(L, level, ar));\n\n}\n\ninline int GetInfo(State* L, const char* what, Debug* ar) {\n\n return detail::lua_getinfo(L, what, ar);\n\n}\n\ninline const char* GetLocal(State* L, const Debug* ar, int n) {\n", "file_path": "include/Lua/Lua.hpp", "rank": 23, "score": 114945.578801029 }, { "content": "//TODO::Consider later if it's possible to do this all\n\n//arithmetic, with operator overloading\n\nenum class ArithmeticOperators {\n\n Add = LUA_OPADD,\n\n Sub = LUA_OPSUB,\n\n Mul = LUA_OPMUL,\n\n Mod = LUA_OPMOD,\n\n Pow = LUA_OPPOW,\n\n FloatDiv = LUA_OPDIV,\n\n FloorDiv = LUA_OPIDIV,\n\n BitwiseAnd = LUA_OPBAND,\n\n BitwiseOr = LUA_OPBOR,\n\n BitwiseXor = LUA_OPBXOR,\n\n ShiftLeft = LUA_OPSHL,\n\n ShiftRight = LUA_OPSHR,\n\n UnaryNegation = LUA_OPUNM,\n\n BitwiseNot = LUA_OPBNOT,\n\n};\n\n\n", "file_path": "include/Lua/Lua.hpp", "rank": 24, "score": 114945.578801029 }, { "content": "enum class RelationalOperators {\n\n Equals = LUA_OPEQ,\n\n LessThan = LUA_OPLT,\n\n LessOrEqual = LUA_OPLE\n\n};\n\n\n\ninline void Arith(State* L, ArithmeticOperators op) {\n\n detail::lua_arith(L, static_cast<int>(op));\n\n}\n\n//TODO: should these 2 functions return bool?\n\ninline bool RawEqual(State* L, int idx1, int idx2) {\n\n return static_cast<bool>(detail::lua_rawequal(L, idx1, idx2));\n\n}\n\ninline bool Compare(State* L, int idx1, int idx2, RelationalOperators op) {\n\n return static_cast<bool>(detail::lua_compare(L, idx1, idx2, static_cast<int>(op)));\n\n}\n\n\n\n\n\n//TODO: check for possibility of function overloading (+type_traits)\n\ninline void PushNil(State* L) {\n", "file_path": "include/Lua/Lua.hpp", "rank": 25, "score": 114945.578801029 }, { "content": "enum class RidX {\n\n MainThread = LUA_RIDX_MAINTHREAD,\n\n Globals = LUA_RIDX_GLOBALS,\n\n Last = RidX::Globals\n\n};\n\n\n\nusing Number = detail::lua_Number;\n\nusing Integer = detail::lua_Integer;\n\nusing Unsigned = detail::lua_Unsigned;\n\nusing KContext = detail::lua_KContext;\n\n\n\nusing CFunction = detail::lua_CFunction;\n\nusing KFunction = detail::lua_KFunction;\n\nusing Reader = detail::lua_Reader;\n\nusing Writer = detail::lua_Writer;\n\nusing Alloc = detail::lua_Alloc;\n\n\n\n//auto Ident = detail::lua_ident;\n\n\n\ninline State* NewState(Alloc f, void* ud) {\n", "file_path": "include/Lua/Lua.hpp", "rank": 26, "score": 114945.578801029 }, { "content": "enum class GarbageCollectionOpts {\n\n Stop = LUA_GCSTOP,\n\n Restart = LUA_GCRESTART,\n\n Collect = LUA_GCCOLLECT,\n\n Count = LUA_GCCOUNT,\n\n CountB = LUA_GCCOUNTB,\n\n Step = LUA_GCSTEP,\n\n SetPause = LUA_GCSETPAUSE,\n\n SetStupMul = LUA_GCSETSTEPMUL,\n\n IsRunning = LUA_GCISRUNNING\n\n};\n\n\n\ninline int GC(State* L, GarbageCollectionOpts what, int data) {\n\n return detail::lua_gc(L, static_cast<int>(what), data);\n\n}\n\n\n\n\n\ninline int Error(State* L) {\n\n return detail::lua_error(L);\n\n}\n", "file_path": "include/Lua/Lua.hpp", "rank": 27, "score": 112954.91953362757 }, { "content": "LUALIB_API void luaL_pushresult (luaL_Buffer *B) {\n\n lua_State *L = B->L;\n\n lua_pushlstring(L, B->b, B->n);\n\n if (buffonstack(B)) {\n\n resizebox(L, -2, 0); /* delete old buffer */\n\n lua_remove(L, -2); /* remove its header from the stack */\n\n }\n", "file_path": "subprojects/lua/src/lauxlib.c", "rank": 28, "score": 87725.50148733547 }, { "content": " lu_byte idx; /* index of upvalue (in stack or in outer function's list) */\n", "file_path": "subprojects/lua/src/lobject.h", "rank": 29, "score": 80840.32941658188 }, { "content": " short idx; /* variable index in stack */\n", "file_path": "subprojects/lua/src/lparser.h", "rank": 30, "score": 80840.32941658188 }, { "content": " StkId base; /* base for this function */\n", "file_path": "subprojects/lua/src/lstate.h", "rank": 31, "score": 80823.32422003653 }, { "content": " struct lua_State *L;\n", "file_path": "subprojects/lua/src/llex.h", "rank": 32, "score": 80633.44798611967 }, { "content": " lua_State *L;\n", "file_path": "subprojects/lua/src/lauxlib.h", "rank": 33, "score": 80633.44798611967 }, { "content": " lua_State *L;\n", "file_path": "subprojects/lua/src/ldump.c", "rank": 34, "score": 80633.44798611967 }, { "content": " lua_State *L;\n", "file_path": "subprojects/lua/src/lundump.c", "rank": 35, "score": 80633.44798611967 }, { "content": " lua_State *L;\n", "file_path": "subprojects/lua/src/lstrlib.c", "rank": 36, "score": 80633.44798611967 }, { "content": " lua_State *L;\t\t\t/* Lua state (for reader) */\n", "file_path": "subprojects/lua/src/lzio.h", "rank": 37, "score": 80633.44798611967 }, { "content": "LUALIB_API int (luaL_getsubtable) (lua_State *L, int idx, const char *fname);\n", "file_path": "subprojects/lua/src/lauxlib.h", "rank": 38, "score": 80453.84854638053 }, { "content": "LUAMOD_API int (luaopen_debug) (lua_State *L);\n", "file_path": "subprojects/lua/src/lualib.h", "rank": 39, "score": 80453.84854638053 }, { "content": "LUA_API int (lua_gethookcount) (lua_State *L);\n", "file_path": "subprojects/lua/src/lua.h", "rank": 40, "score": 80453.84854638053 }, { "content": " return 2;\n\n }\n\n new (sock) SocketType();\n\n if (not sock->create()) {\n\n Lua::PushBoolean(L, false);\n\n Lua::PushFString(L, \"socket(): %s\", std::strerror(errno));\n\n return 2;\n\n }\n\n\n\n Lua::Aux::GetMetaTable(L, SocketType::MetaTableName);\n\n Lua::SetMetaTable(L, -2);\n\n return 1;\n\n}\n\n\n\ntemplate<int IPVersion, template<int> class SocketType = Sctp::Socket::Base>\n\nusing MemberFuncType = int (SocketType<IPVersion>::*)(Lua::State*);\n\n\n\ntemplate<int IPVersion, template<int> class SocketType, MemberFuncType<IPVersion, SocketType> fn>\n\nauto CallMemberFunction(Lua::State* L) -> int {\n\n static_assert(Sctp::IsSctpSocket<SocketType<IPVersion>>::value, \"\");\n", "file_path": "src/lsctp.cpp", "rank": 41, "score": 25.51902882688075 }, { "content": "\n\n} //namespace Sctp\n\n\n\nnamespace {\n\n\n\ntemplate<class SocketType>\n\nauto UserDataToSocket(Lua::State* L, int idx) -> SocketType* {\n\n static_assert(Sctp::IsSctpSocket<SocketType>::value, \"\");\n\n\n\n return Lua::Aux::TestUData<SocketType>(L, idx, SocketType::MetaTableName);\n\n}\n\n\n\ntemplate<class SocketType>\n\nauto New(Lua::State* L) -> int {\n\n static_assert(Sctp::IsSctpSocket<SocketType>::value, \"\");\n\n\n\n auto sock = Lua::NewUserData<SocketType>(L);\n\n if(sock == nullptr) {\n\n Lua::PushNil(L);\n\n Lua::PushString(L, \"Socket userdata allocation failed\");\n", "file_path": "src/lsctp.cpp", "rank": 42, "score": 25.499793753932018 }, { "content": "sctp = {\n\n --[[\n\n returns a userdata (Sctp::Socket)\n\n ]]\n\n socket(),\n\n \n\n --[[\n\n Calls bind() and sctp_bindx() internally. No IP version mixing\n\n sock: contains the address family.\n\n port: every given address will use this port number\n\n addr1: at least 1 address is mandatory\n\n ...: no limit for multihoming\n\n ]]\n\n bind(sock, port, addr1, ...),\n\n listen(),\n\n accept(),\n\n \n\n --[[\n\n Should it be connect or connectx?\n\n ]]\n", "file_path": "plan.lua", "rank": 43, "score": 24.78407578231151 }, { "content": " auto basePtr = static_cast<Sctp::Socket::Base<IPVersion>*>(sock);\n\n return (basePtr->*fn)(L);\n\n}\n\n\n\ntemplate<class SocketType>\n\nauto DestroySocket(Lua::State* L) noexcept -> int {\n\n static_assert(Sctp::IsSctpSocket<SocketType>::value, \"\");\n\n\n\n auto sock = UserDataToSocket<SocketType>(L, 1);\n\n sock->SocketType::~SocketType();\n\n return 0;\n\n}\n\n\n\n//I haven't found a way yet to keep array of structures in the format below\n\n//So for now, clang-format is off-limits\n\n// clang-format off\n\nconst Lua::Aux::Reg ServerSocketMetaTable4[] = {\n\n { \"bind\", CallMemberFunction<4, Sctp::Socket::Server, &Sctp::Socket::Server<4>::bind> },\n\n { \"close\", CallMemberFunction<4, Sctp::Socket::Server, &Sctp::Socket::Server<4>::close> },\n\n { \"listen\", CallMemberFunction<4, Sctp::Socket::Server, &Sctp::Socket::Server<4>::listen> },\n", "file_path": "src/lsctp.cpp", "rank": 44, "score": 24.241510993377187 }, { "content": "\n\n auto sock = UserDataToSocket<SocketType<IPVersion>>(L, 1);\n\n if (sock == nullptr) {\n\n Lua::PushBoolean(L, false);\n\n Lua::PushFString(L, \"Can\\'t call function, pointer is nil.\");\n\n return 2;\n\n }\n\n return (sock->*fn)(L);\n\n}\n\n\n\ntemplate<int IPVersion, template<int> class SocketType, MemberFuncType<IPVersion> fn>\n\nauto CallMemberFunction(Lua::State* L) -> int {\n\n static_assert(Sctp::IsSctpSocket<SocketType<IPVersion>>::value, \"\");\n\n\n\n auto sock = UserDataToSocket<SocketType<IPVersion>>(L, 1);\n\n if (sock == nullptr) {\n\n Lua::PushBoolean(L, false);\n\n Lua::PushFString(L, \"Can\\'t call function, pointer is nil.\");\n\n return 2;\n\n }\n", "file_path": "src/lsctp.cpp", "rank": 45, "score": 23.277176002609387 }, { "content": "#include <type_traits>\n\n\n\n#include \"Lua/Lua.hpp\"\n\n#include \"SctpSocket.hpp\"\n\n#include \"SctpServerSocket.hpp\"\n\n#include \"SctpClientSocket.hpp\"\n\n\n\nnamespace Sctp {\n\n\n\nnamespace Socket {\n\n\n\ntemplate<> const char* Server<4>::MetaTableName = \"ServerSocketMeta4\";\n\n\n\ntemplate<> const char* Server<6>::MetaTableName = \"ServerSocketMeta6\";\n\n\n\ntemplate<> const char* Client<4>::MetaTableName = \"ClientSocketMeta4\";\n\n\n\ntemplate<> const char* Client<6>::MetaTableName = \"ClientSocketMeta6\";\n\n\n\n} //namespace Socket\n", "file_path": "src/lsctp.cpp", "rank": 46, "score": 21.07689011714052 }, { "content": "inline void XMove(State* from, State* to, int n) {\n\n detail::lua_xmove(from, to, n);\n\n}\n\n\n\n\n\ninline bool IsString(State* L, int idx) {\n\n return static_cast<bool>(detail::lua_isstring(L, idx));\n\n}\n\ninline bool IsCFunction(State* L, int idx) {\n\n return static_cast<bool>(detail::lua_iscfunction(L, idx));\n\n}\n\ninline bool IsInteger(State* L, int idx) {\n\n return static_cast<bool>(detail::lua_isinteger(L, idx));\n\n}\n\ninline bool IsUserData(State* L, int idx) {\n\n return static_cast<bool>(detail::lua_isuserdata(L, idx));\n\n}\n\ninline Types Type(State* L, int idx) {\n\n return static_cast<Types>(detail::lua_type(L, idx));\n\n}\n", "file_path": "include/Lua/Lua.hpp", "rank": 47, "score": 19.051388971640893 }, { "content": "}\n\ninline bool IsNone(State* L, int idx) {\n\n return Type(L, idx) == Types::None;\n\n}\n\ninline bool IsNoneOrNil(State* L, int idx) {\n\n return static_cast<int>(Type(L, idx)) <= 0;\n\n}\n\ninline const char* PushLiteral(State* L, const char* s) {\n\n return PushString(L, s);\n\n}\n\n//TODO: Check RawGet's input params and convert macro to const\n\ninline void PushGlobalTable(State* L) {\n\n RawGet(L, RegistryIndex, static_cast<int>(RidX::Globals));\n\n}\n\ninline const char* ToString(State* L, int idx) {\n\n return ToLString(L, idx, nullptr);\n\n}\n\ninline void Insert(State* L, int idx) {\n\n Rotate(L, idx, 1);\n\n}\n", "file_path": "include/Lua/Lua.hpp", "rank": 48, "score": 18.192991345873924 }, { "content": "inline const char* GSub(State* L, const char* s, const char* p, const char* r) {\n\n return detail::luaL_gsub(L, s, p, r);\n\n}\n\ninline void SetFuncs(State* L, const Reg* l, int nup) {\n\n detail::luaL_setfuncs(L, l, nup);\n\n}\n\ninline bool GetSubTable(State* L, int idx, const char* fname) {\n\n return static_cast<bool>(detail::luaL_getsubtable(L, idx, fname));\n\n}\n\ninline void TraceBack(State* L, State* L1, const char* msg, int level) {\n\n detail::luaL_traceback(L, L1, msg, level);\n\n}\n\ninline void RequiRef(State* L, const char* modname, CFunction openf, bool glb) {\n\n detail::luaL_requiref(L, modname, openf, static_cast<int>(glb));\n\n}\n\n\n\ntemplate<size_t N>\n\ninline void NewLibTable(State* L, const Reg (&l)[N]) {\n\n CreateTable(L, 0, sizeof(l)/sizeof(l[0]) - 1);\n\n}\n", "file_path": "include/Lua/Lua.hpp", "rank": 49, "score": 17.14468228704644 }, { "content": "inline const char* TypeName(State* L, Types tp) {\n\n return detail::lua_typename(L, static_cast<int>(tp));\n\n}\n\ninline Number ToNumberX(State* L, int idx, int* isNum) {\n\n return detail::lua_tonumberx(L, idx, isNum);\n\n}\n\ninline Integer ToIntegerX(State* L, int idx, int* isNum) {\n\n return detail::lua_tointegerx(L, idx, isNum);\n\n}\n\ninline bool ToBoolean(State* L, int idx) {\n\n return static_cast<bool>(detail::lua_toboolean(L, idx));\n\n}\n\ninline const char* ToLString(State* L, int idx, std::size_t* len) {\n\n return detail::lua_tolstring(L, idx, len);\n\n}\n\ninline std::size_t RawLen(State* L, int idx) {\n\n return detail::lua_rawlen(L, idx);\n\n}\n\ninline CFunction ToCFunction(State* L, int idx) {\n\n return detail::lua_tocfunction(L, idx);\n", "file_path": "include/Lua/Lua.hpp", "rank": 50, "score": 17.119412881810902 }, { "content": " return static_cast<Types>(detail::lua_gettable(L, idx));\n\n}\n\ninline Types GetField(State* L, int idx, const char* k) {\n\n return static_cast<Types>(detail::lua_getfield(L, idx, k));\n\n}\n\ninline Types Geti(State* L, int idx, Integer n) {\n\n return static_cast<Types>(detail::lua_geti(L, idx, n));\n\n}\n\ninline Types RawGet(State* L, int idx) {\n\n return static_cast<Types>(detail::lua_rawget(L, idx));\n\n}\n\ninline Types RawGet(State* L, int idx, Integer n) {\n\n return static_cast<Types>(detail::lua_rawgeti(L, idx, n));\n\n}\n\ninline Types RawGet(State* L, int idx, const void* p) {\n\n return static_cast<Types>(detail::lua_rawgetp(L, idx, p));\n\n}\n\ninline void CreateTable(State* L, int narr, int nrec) {\n\n detail::lua_createtable(L, narr, nrec);\n\n}\n", "file_path": "include/Lua/Lua.hpp", "rank": 51, "score": 16.717529067209448 }, { "content": " PushCFunction(L, fn);\n\n SetGlobal(L, name);\n\n}\n\ninline bool IsFunction(State* L, int idx) {\n\n return Type(L, idx) == Types::Function;\n\n}\n\ninline bool IsTable(State* L, int idx) {\n\n return Type(L, idx) == Types::Table;\n\n}\n\ninline bool IsLightUserData(State* L, int idx) {\n\n return Type(L, idx) == Types::LightUserData;\n\n}\n\ninline bool IsNil(State* L, int idx) {\n\n return Type(L, idx) == Types::Nil;\n\n}\n\ninline bool IsBoolean(State* L, int idx) {\n\n return Type(L, idx) == Types::Boolean;\n\n}\n\ninline bool IsThread(State* L, int idx) {\n\n return Type(L, idx) == Types::Thread;\n", "file_path": "include/Lua/Lua.hpp", "rank": 52, "score": 16.342414826675643 }, { "content": " return detail::lua_absindex(L, idx);\n\n}\n\ninline int GetTop(State* L) {\n\n return detail::lua_gettop(L);\n\n}\n\ninline void SetTop(State* L, int idx) {\n\n detail::lua_settop(L, idx);\n\n}\n\ninline void PushValue(State* L, int idx) {\n\n detail::lua_pushvalue(L, idx);\n\n}\n\ninline void Rotate(State* L, int idx, int n) {\n\n detail::lua_rotate(L, idx, n);\n\n}\n\ninline void Copy(State* L, int fromIdx, int toIdx) {\n\n detail::lua_copy(L, fromIdx, toIdx);\n\n}\n\ninline bool CheckStack(State* L, int n) {\n\n return static_cast<bool>(detail::lua_checkstack(L, n));\n\n}\n", "file_path": "include/Lua/Lua.hpp", "rank": 53, "score": 16.026457083100613 }, { "content": "template<class Type>\n\ninline Type* NewUserData(State* L) {\n\n return static_cast<Type*>(detail::lua_newuserdata(L, sizeof(Type)));\n\n}\n\ninline Types GetMetaTable(State* L, int objindex) {\n\n return static_cast<Types>(detail::lua_getmetatable(L, objindex));\n\n}\n\ninline Types GetUserValue(State* L, int idx) {\n\n return static_cast<Types>(detail::lua_getuservalue(L, idx));\n\n}\n\n\n\ninline void SetGlobal(State* L, const char* name) {\n\n detail::lua_setglobal(L, name);\n\n}\n\ninline void SetTable(State* L, int idx) {\n\n detail::lua_settable(L, idx);\n\n}\n\ninline void SetField(State* L, int idx, const char* k) {\n\n detail::lua_setfield(L, idx, k);\n\n}\n", "file_path": "include/Lua/Lua.hpp", "rank": 54, "score": 15.49242232440698 }, { "content": "}\n\ninline int ExecResult(State* L, int stat) {\n\n return detail::luaL_execresult(L, stat);\n\n}\n\n\n\n\n\n\n\nconstexpr auto Noref = LUA_NOREF;\n\nconstexpr auto Refnil = LUA_REFNIL;\n\n\n\ninline int Ref(State* L, int t) {\n\n return detail::luaL_ref(L, t);\n\n}\n\ninline void UnRef(State* L, int t, int ref) {\n\n return detail::luaL_unref(L, t, ref);\n\n}\n\ntemplate<size_t N>\n\ninline Statuses LoadFileX(State* L, const char* filename, const char (&mode)[N]) {\n\n static_assert(::detail::LoadModeChecker(mode), R\"(Load mode can only be \"b\", \"t\", \"bt\" or null pointer)\");\n\n return static_cast<Statuses>(detail::luaL_loadfilex(L, filename, mode));\n", "file_path": "include/Lua/Lua.hpp", "rank": 55, "score": 15.18046820434199 }, { "content": "inline Type* TestUData(State* L, int ud, const char* tname) {\n\n return static_cast<Type*>(detail::luaL_testudata(L, ud, tname));\n\n}\n\ntemplate<class Type>\n\ninline Type* CheckUData(State* L, int ud, const char* tname) {\n\n return static_cast<Type*>(detail::luaL_checkudata(L, ud, tname));\n\n}\n\ninline void Where(State* L, int lvl) {\n\n detail::luaL_where(L, lvl);\n\n}\n\ntemplate<class ...VarArgs>\n\ninline int Error(State* L, const char* fmt, VarArgs&&... args) {\n\n return detail::luaL_error(L, fmt, args...);\n\n}\n\ntemplate<size_t N>\n\ninline int CheckOption(State* L, int arg, const char* def, const char* const (&lst)[N]) {\n\n return detail::luaL_checkoption(L, arg, def, lst);\n\n}\n\ninline int FileTesult(State* L, int stat, const char* fname) {\n\n return detail::luaL_fileresult(L, stat, fname);\n", "file_path": "include/Lua/Lua.hpp", "rank": 56, "score": 14.688046827984765 }, { "content": "\n\nusing Reg = detail::luaL_Reg;\n\n\n\nconstexpr auto NumSizes = (sizeof(Integer) * 16) + sizeof(Number);\n\n\n\ninline void CheckVersion(State* L, Number ver, size_t sz) {\n\n detail::luaL_checkversion_(L, ver, sz);\n\n}\n\ninline void CheckVersion(State* L) {\n\n CheckVersion(L, VersionNumber, NumSizes);\n\n}\n\n\n\n\n\n\n\ninline Types GetMetaField(State* L, int obj, const char* e) {\n\n return static_cast<Types>(detail::luaL_getmetafield(L, obj, e));\n\n}\n\ninline bool CallMeta(State* L, int obj, const char* e) {\n\n return static_cast<bool>(detail::luaL_callmeta(L, obj, e));\n\n}\n", "file_path": "include/Lua/Lua.hpp", "rank": 57, "score": 14.265906050961044 }, { "content": "inline Hook GetHook(State* L) {\n\n return detail::lua_gethook(L);\n\n}\n\ninline HookMasks GetHookMask(State* L) {\n\n return static_cast<HookMasks>(detail::lua_gethookmask(L));\n\n}\n\ninline int GetHookCount(State* L) {\n\n return detail::lua_gethookcount(L);\n\n}\n\n\n\n\n\n//TODO: What should be done about lualib.h?\n\nnamespace Lib {\n\n\n\nnamespace Open {\n\n\n\ninline int Base(State* L) {\n\n return detail::luaopen_base(L);\n\n}\n\ninline int Coroutine(State* L) {\n", "file_path": "include/Lua/Lua.hpp", "rank": 58, "score": 13.598832587130484 }, { "content": " return ::Lua::TypeName(L, Type(L, index));\n\n}\n\n\n\ninline bool DoFile(State* L, const char* filename) {\n\n return LoadFile(L, filename) == Statuses::OK ? (PCall(L, 0, MultiReturn, 0) == Statuses::OK ? false : true) : true;\n\n}\n\n\n\ninline bool DoString(State* L, const char* str) {\n\n return LoadString(L, str) == Statuses::OK ? (PCall(L, 0, MultiReturn, 0) == Statuses::OK ? false : true) : true;\n\n}\n\n\n\ninline Types GetMetaTable(State* L, const char* tname) {\n\n return GetField(L, RegistryIndex, tname);\n\n}\n\n\n\n//TODO: Don't miss this\n\n#define luaL_opt(L,f,n,d) (lua_isnoneornil(L,(n)) ? (d) : f(L,(n)))\n\n\n\ninline Statuses LoadBuffer(State* L, const char* buff, size_t sz, const char* name) {\n\n return LoadBufferX(L, buff, sz, name, nullptr);\n", "file_path": "include/Lua/Lua.hpp", "rank": 59, "score": 13.478691705172412 }, { "content": " return detail::lua_newstate(f, ud);\n\n}\n\ninline void Close(State* L) {\n\n detail::lua_close(L);\n\n}\n\ninline State* NewThread(State* L) {\n\n return detail::lua_newthread(L);\n\n}\n\ninline CFunction AtPanic(State* L, CFunction panicf) {\n\n return detail::lua_atpanic(L, panicf);\n\n}\n\ninline const Number* Version(State* L) {\n\n return detail::lua_version(L);\n\n}\n\ninline bool IsNumber(State* L, int idx) {\n\n return static_cast<bool>(detail::lua_isnumber(L, idx));\n\n}\n\n\n\n\n\ninline int AbsIndex(State* L, int idx) {\n", "file_path": "include/Lua/Lua.hpp", "rank": 60, "score": 13.368108187316427 }, { "content": "inline void* GetExtraSpace(State* L) {\n\n return lua_getextraspace(L);\n\n}\n\ninline Number ToNumber(State* L, int idx){\n\n return ToNumberX(L, idx, nullptr);\n\n}\n\ninline Integer ToInteger(State* L,int idx) {\n\n return ToIntegerX(L, idx, nullptr);\n\n}\n\ninline void Pop(State* L, int idx) {\n\n SetTop(L, -idx-1);\n\n}\n\ninline void Newtable(State* L) {\n\n CreateTable(L, 0, 0);\n\n}\n\ninline void PushCFunction(State* L, CFunction fn) {\n\n PushCClosure(L, fn, 0);\n\n}\n\n\n\ninline void Register(State* L, const char* name, CFunction fn) {\n", "file_path": "include/Lua/Lua.hpp", "rank": 61, "score": 13.352878787140988 }, { "content": "template<size_t N>\n\ninline void NewLib(State* L, const Reg (&l)[N]) {\n\n CheckVersion(L);\n\n NewLibTable(L, l);\n\n SetFuncs(L, l, 0);\n\n}\n\n\n\ninline void ArgCheck(State* L, bool cond, int arg, const char *extramsg) {\n\n if(not cond) {\n\n ArgError(L, arg, extramsg);\n\n }\n\n}\n\ninline const char* CheckString(State* L, int arg) {\n\n return detail::luaL_checklstring(L, arg, nullptr);\n\n}\n\ninline const char* OptString(State* L, int arg, const char* d) {\n\n return detail::luaL_optlstring(L, arg, d, nullptr);\n\n}\n\n\n\ninline const char* TypeName(State* L, int index) {\n", "file_path": "include/Lua/Lua.hpp", "rank": 62, "score": 13.277981043945267 }, { "content": "}\n\ninline Statuses LoadFileX(State* L, const char* filename, const char* mode) {\n\n return static_cast<Statuses>(detail::luaL_loadfilex(L, filename, mode));\n\n}\n\ninline Statuses LoadFile(State* L, const char* filename) {\n\n return static_cast<Statuses>(LoadFileX(L, filename, nullptr));\n\n}\n\n\n\ninline Statuses LoadBufferX(State* L, const char* buff, size_t sz, const char* name, const char* mode) {\n\n return static_cast<Statuses>(detail::luaL_loadbufferx(L, buff, sz, name, mode));\n\n}\n\ninline Statuses LoadString(State* L, const char* s) {\n\n return static_cast<Statuses>(detail::luaL_loadstring(L, s));\n\n}\n\ninline State* NewState() {\n\n return detail::luaL_newstate();\n\n}\n\ninline Integer Len(State* L, int idx) {\n\n return detail::luaL_len(L, idx);\n\n}\n", "file_path": "include/Lua/Lua.hpp", "rank": 63, "score": 13.19255727104671 }, { "content": "inline void Remove(State* L, int idx) {\n\n Rotate(L, idx, (-1));\n\n Pop(L, 1);\n\n}\n\ninline void Replace(State* L, int idx) {\n\n Copy(L, -1, idx);\n\n Pop(L, 1);\n\n}\n\n\n\n\n", "file_path": "include/Lua/Lua.hpp", "rank": 64, "score": 13.189570501045935 }, { "content": "\n\ninline Statuses Load(State* L, Reader reader, void* dt, const char* chunkname, const char* mode) {\n\n return static_cast<Statuses>(detail::lua_load(L, reader, dt, chunkname, mode));\n\n}\n\ninline int Dump(State* L, Writer writer, void* data, int strip) {\n\n return detail::lua_dump(L, writer, data, strip);\n\n}\n\n\n\n\n\ninline int YieldK(State* L, int nresults, KContext ctx, KFunction k) {\n\n return detail::lua_yieldk(L, nresults, ctx, k);\n\n}\n\ninline Statuses Resume(State* L, State* from, int narg) {\n\n return static_cast<Statuses>(detail::lua_resume(L, from, narg));\n\n}\n\ninline Statuses Status(State* L) {\n\n return static_cast<Statuses>(detail::lua_status(L));\n\n}\n\ninline bool IsYieldable(State* L) {\n\n return static_cast<bool>(detail::lua_isyieldable(L));\n\n}\n\ninline int Yield(State* L,int nresults) {\n\n return YieldK(L, nresults, 0, nullptr);\n\n}\n\n\n\n\n", "file_path": "include/Lua/Lua.hpp", "rank": 65, "score": 13.040231040458186 }, { "content": "inline const char* ToLString(State* L, int idx, size_t& len) {\n\n return detail::luaL_tolstring(L, idx, &len);\n\n}\n\ninline int ArgError(State* L, int arg, const char* extramsg) {\n\n return detail::luaL_argerror(L, arg, extramsg);\n\n}\n\ninline const char* CheckLString(State* L, int arg, size_t& l) {\n\n return detail::luaL_checklstring(L, arg, &l);\n\n}\n\ninline const char* OptLString(State* L, int arg, const char* def, size_t& l) {\n\n return detail::luaL_optlstring(L, arg, def, &l);\n\n}\n\ninline Number CheckNumber(State* L, int arg) {\n\n return detail::luaL_checknumber(L, arg);\n\n}\n\ninline Number OptNumber(State* L, int arg, Number def) {\n\n return detail::luaL_optnumber(L, arg, def);\n\n}\n\ninline Integer CheckInteger(State* L, int arg) {\n\n return detail::luaL_checkinteger(L, arg);\n", "file_path": "include/Lua/Lua.hpp", "rank": 66, "score": 12.943742915153086 }, { "content": "}\n\ninline void* ToUserData(State* L, int idx) {\n\n return detail::lua_touserdata(L, idx);\n\n}\n\ninline State* ToThread(State* L, int idx) {\n\n return detail::lua_tothread(L, idx);\n\n}\n\ninline const void* ToPointer(State* L, int idx) {\n\n return detail::lua_topointer(L, idx);\n\n}\n\n\n\n\n", "file_path": "include/Lua/Lua.hpp", "rank": 67, "score": 12.850118281241182 }, { "content": "}\n\ninline void PushCClosure(State* L, CFunction fn, int n) {\n\n detail::lua_pushcclosure(L, fn, n);\n\n}\n\ninline void PushBoolean(State* L, bool b) {\n\n detail::lua_pushboolean(L, static_cast<int>(b));\n\n}\n\ninline void PushLightUserData(State* L, void* p) {\n\n detail::lua_pushlightuserdata(L, p);\n\n}\n\ninline int PushThread(State* L) {\n\n return detail::lua_pushthread(L);\n\n}\n\n\n\n\n\n//TODO: function overloading\n\ninline Types GetGlobal(State* L, const char* name) {\n\n return static_cast<Types>(detail::lua_getglobal(L, name));\n\n}\n\ninline Types GetTable(State* L, int idx) {\n", "file_path": "include/Lua/Lua.hpp", "rank": 68, "score": 12.77856624729492 }, { "content": "inline void Seti(State* L, int idx, Integer n) {\n\n detail::lua_seti(L, idx, n);\n\n}\n\ninline void RawSet(State* L, int idx) {\n\n detail::lua_rawset(L, idx);\n\n}\n\ninline void RawSet(State* L, int idx, Integer n) {\n\n detail::lua_rawseti(L, idx, n);\n\n}\n\ninline void RawSet(State* L, int idx, const void* p) {\n\n detail::lua_rawsetp(L, idx, p);\n\n}\n\ninline int SetMetaTable(State* L, int objindex) {\n\n return detail::lua_setmetatable(L, objindex);\n\n}\n\ninline void SetUserValue(State* L, int idx) {\n\n detail::lua_setuservalue(L, idx);\n\n}\n\n\n\n\n", "file_path": "include/Lua/Lua.hpp", "rank": 69, "score": 12.69964356390427 }, { "content": "inline int Next(State* L, int idx) {\n\n return detail::lua_next(L, idx);\n\n}\n\ninline void Concat(State* L, int n) {\n\n detail::lua_concat(L, n);\n\n}\n\ninline void Len(State* L, int idx) {\n\n detail::lua_len(L, idx);\n\n}\n\ninline std::size_t StringToNumber(State* L, const char* s) {\n\n return detail::lua_stringtonumber(L, s);\n\n}\n\ninline Alloc GetAllocF(State* L, void** ud) {\n\n return detail::lua_getallocf(L, ud);\n\n}\n\ninline void SetAllocF(State* L, Alloc f, void* ud) {\n\n detail::lua_setallocf(L, f, ud);\n\n}\n\n\n\n\n", "file_path": "include/Lua/Lua.hpp", "rank": 70, "score": 11.88652076210818 }, { "content": "constexpr auto Release = LUA_RELEASE;\n\nconstexpr auto CopyRight = LUA_COPYRIGHT;\n\nconstexpr auto Authors = LUA_AUTHORS;\n\n\n\nconstexpr auto Signature = LUA_SIGNATURE;\n\nconstexpr auto MultiReturn = LUA_MULTRET;\n\nconstexpr auto RegistryIndex = LUA_REGISTRYINDEX;\n\n\n\ntemplate<class IdxType>\n\nconstexpr auto UpvalueIndex(const IdxType i) -> decltype(lua_upvalueindex(-1)) {\n\n static_assert(std::is_arithmetic<IdxType>::value, \"\");\n\n return RegistryIndex - i;\n\n}\n\n\n", "file_path": "include/Lua/Lua.hpp", "rank": 71, "score": 11.883256550546049 }, { "content": " { \"accept\", CallMemberFunction<4, Sctp::Socket::Server, &Sctp::Socket::Server<4>::accept> },\n\n { \"setnonblocking\", CallMemberFunction<4, Sctp::Socket::Server, &Sctp::Socket::Server<4>::setNonBlocking> },\n\n { \"__gc\", DestroySocket<Sctp::Socket::Server<4>> },\n\n { nullptr, nullptr }\n\n};\n\n\n\nconst Lua::Aux::Reg ServerSocketMetaTable6[] = {\n\n { \"bind\", CallMemberFunction<6, Sctp::Socket::Server, &Sctp::Socket::Server<6>::bind> },\n\n { \"close\", CallMemberFunction<6, Sctp::Socket::Server, &Sctp::Socket::Server<6>::close> },\n\n { \"listen\", CallMemberFunction<6, Sctp::Socket::Server, &Sctp::Socket::Server<6>::listen> },\n\n { \"accept\", CallMemberFunction<6, Sctp::Socket::Server, &Sctp::Socket::Server<6>::accept> },\n\n { \"setnonblocking\", CallMemberFunction<6, Sctp::Socket::Server, &Sctp::Socket::Server<6>::setNonBlocking> },\n\n { \"__gc\", DestroySocket<Sctp::Socket::Server<6>> },\n\n { nullptr, nullptr }\n\n};\n\n\n\nconst Lua::Aux::Reg ClientSocketMetaTable4[] = {\n\n { \"bind\", CallMemberFunction<4, Sctp::Socket::Client, &Sctp::Socket::Client<4>::bind> },\n\n { \"connect\", CallMemberFunction<4, Sctp::Socket::Client, &Sctp::Socket::Client<4>::connect> },\n\n { \"send\", CallMemberFunction<4, Sctp::Socket::Client, &Sctp::Socket::Client<4>::sendmsg> },\n", "file_path": "src/lsctp.cpp", "rank": 72, "score": 11.692924077176585 }, { "content": " { \"recv\", CallMemberFunction<4, Sctp::Socket::Client, &Sctp::Socket::Client<4>::recvmsg> },\n\n { \"close\", CallMemberFunction<4, Sctp::Socket::Client, &Sctp::Socket::Client<4>::close> },\n\n { \"setnonblocking\", CallMemberFunction<4, Sctp::Socket::Client, &Sctp::Socket::Client<4>::setNonBlocking> },\n\n { \"__gc\", DestroySocket<Sctp::Socket::Client<4>> },\n\n { nullptr, nullptr }\n\n};\n\n\n\nconst Lua::Aux::Reg ClientSocketMetaTable6[] = {\n\n { \"bind\", CallMemberFunction<6, Sctp::Socket::Client, &Sctp::Socket::Client<6>::bind> },\n\n { \"connect\", CallMemberFunction<6, Sctp::Socket::Client, &Sctp::Socket::Client<6>::connect> },\n\n { \"send\", CallMemberFunction<6, Sctp::Socket::Client, &Sctp::Socket::Client<6>::sendmsg> },\n\n { \"recv\", CallMemberFunction<6, Sctp::Socket::Client, &Sctp::Socket::Client<6>::recvmsg> },\n\n { \"close\", CallMemberFunction<6, Sctp::Socket::Client, &Sctp::Socket::Client<6>::close> },\n\n { \"setnonblocking\", CallMemberFunction<6, Sctp::Socket::Client, &Sctp::Socket::Client<6>::setNonBlocking> },\n\n { \"__gc\", DestroySocket<Sctp::Socket::Client<6>> },\n\n { nullptr, nullptr }\n\n};\n\n// clang-format on\n\n\n\n} //anonymous namespace\n", "file_path": "src/lsctp.cpp", "rank": 73, "score": 11.670484716151195 }, { "content": "}\n\ninline Integer OptInteger(State* L, int arg, Integer def) {\n\n return detail::luaL_optinteger(L, arg, def);\n\n}\n\ninline void CheckStack(State* L, int sz, const char* msg) {\n\n detail::luaL_checkstack(L, sz, msg);\n\n}\n\ninline void CheckType(State* L, int arg, int t) {\n\n detail::luaL_checktype(L, arg, t);\n\n}\n\ninline void CheckAny(State* L, int arg) {\n\n detail::luaL_checkany(L, arg);\n\n}\n\ninline int NewMetaTable(State* L, const char* tname) {\n\n return detail::luaL_newmetatable(L, tname);\n\n}\n\ninline void SetMetaTable(State* L, const char* tname) {\n\n detail::luaL_setmetatable(L, tname);\n\n}\n\ntemplate<class Type>\n", "file_path": "include/Lua/Lua.hpp", "rank": 74, "score": 11.568357447931916 }, { "content": "\n\ninline void CallK(State* L, int nargs, int nresults, KContext ctx, KFunction k) {\n\n detail::lua_callk(L, nargs, nresults, ctx, k);\n\n}\n\ninline void Call(State* L, int nargs, int nresults) {\n\n CallK(L, nargs, nresults, 0, nullptr);\n\n}\n\n\n\ninline Statuses PCallK(State* L, int nargs, int nresults, int errfunc, KContext ctx, KFunction k) {\n\n return static_cast <Statuses>(detail::lua_pcallk(L, nargs, nresults, errfunc, ctx, k));\n\n}\n\ninline Statuses PCall(State* L,int nargs, int nresults, int errfunc) {\n\n return static_cast<Statuses>(PCallK(L, nargs, nresults, errfunc, 0, nullptr));\n\n}\n\n\n\ntemplate<size_t N>\n\ninline Statuses Load(State* L, Reader reader, void* dt, const char* chunkname, const char (&mode)[N]) {\n\n static_assert(::detail::LoadModeChecker(mode), R\"(Load mode can only be \"b\", \"t\", \"bt\" or null pointer)\");\n\n return static_cast<Statuses>(detail::lua_load(L, reader, dt, chunkname, mode));\n\n}\n", "file_path": "include/Lua/Lua.hpp", "rank": 75, "score": 11.541677332441203 }, { "content": "printResult(sock6 ~= nil and type(sock6) == \"userdata\", error)\n\n\n\nio.write(\"bind(ipv6SH): \")\n\nlocal success, error = sock6:bind(12345, \"::1\")\n\nprintResult(success, error)\n\nsock6:close()\n\n\n\n--[[io.write(\"bind(ipv6MH): \")\n\nlocal success, error = sock6:bind(12345, \"::1\", \"::2\")\n\nprintResult(success, error)]]\n\n\n\n--I really should create/use a testing framework\n\nio.write(\"send/receive: \")\n\nlocal server = sctp.server.socket4()\n\nserver:bind(12345, \"127.1.1.1\", \"127.3.3.3\")\n\nserver:listen()\n\n\n\nlocal client = sctp.client.socket4()\n\nclient:bind(12345, \"127.2.2.2\", \"127.4.4.4\")\n\nclient:connect(12345, \"127.1.1.1\", \"127.3.3.3\")\n", "file_path": "tst/lua/socket.lua", "rank": 76, "score": 11.524527758517618 }, { "content": "#ifndef LUA_HPP\n\n#define LUA_HPP\n\n\n\n#include <type_traits>\n\n#include <cstddef>\n\n#include <cstdarg>\n\n#include <cstdio>\n\n\n\nnamespace detail {\n\n\n\nextern \"C\" {\n\n#include \"lua.h\"\n\n#include \"lualib.h\"\n\n#include \"lauxlib.h\"\n\n}\n\n\n\nconstexpr bool LoadModeChecker(const char* c) {\n\n return c == nullptr or\n\n (c[0] == 't' and c[1] == '\\0') or\n\n (c[0] == 'b' and c[1] == '\\0') or\n", "file_path": "include/Lua/Lua.hpp", "rank": 77, "score": 11.408185844643699 }, { "content": "\n\nextern \"C\" int luaopen_sctp(Lua::State* L) {\n\n Lua::Aux::NewMetaTable(L, Sctp::Socket::Server<4>::MetaTableName);\n\n Lua::PushValue(L, -1);\n\n Lua::SetField(L, -2, \"__index\");\n\n Lua::Aux::SetFuncs(L, ServerSocketMetaTable4, 0);\n\n\n\n Lua::Aux::NewMetaTable(L, Sctp::Socket::Server<6>::MetaTableName);\n\n Lua::PushValue(L, -1);\n\n Lua::SetField(L, -2, \"__index\");\n\n Lua::Aux::SetFuncs(L, ServerSocketMetaTable6, 0);\n\n\n\n Lua::Aux::NewMetaTable(L, Sctp::Socket::Client<4>::MetaTableName);\n\n Lua::PushValue(L, -1);\n\n Lua::SetField(L, -2, \"__index\");\n\n Lua::Aux::SetFuncs(L, ClientSocketMetaTable4, 0);\n\n\n\n Lua::Aux::NewMetaTable(L, Sctp::Socket::Client<6>::MetaTableName);\n\n Lua::PushValue(L, -1);\n\n Lua::SetField(L, -2, \"__index\");\n", "file_path": "src/lsctp.cpp", "rank": 78, "score": 11.197900779331864 }, { "content": "int luaK_exp2anyreg (FuncState *fs, expdesc *e) {\n\n luaK_dischargevars(fs, e);\n\n if (e->k == VNONRELOC) { /* expression already has a register? */\n\n if (!hasjumps(e)) /* no jumps? */\n\n return e->u.info; /* result is already in a register */\n\n if (e->u.info >= fs->nactvar) { /* reg. is not a local? */\n\n exp2reg(fs, e, e->u.info); /* put final result in it */\n\n return e->u.info;\n\n }\n\n }\n\n luaK_exp2nextreg(fs, e); /* otherwise, use next available register */\n\n return e->u.info;\n", "file_path": "subprojects/lua/src/lcode.c", "rank": 79, "score": 11.167742520678704 }, { "content": " return detail::lua_getlocal(L, ar, n);\n\n}\n\ninline const char* SetLocal(State* L, const Debug* ar, int n) {\n\n return detail::lua_setlocal(L, ar, n);\n\n}\n\ninline const char* GetUpvalue(State* L, int funcindex, int n) {\n\n return detail::lua_getupvalue(L, funcindex, n);\n\n}\n\ninline const char* SetUpvalue(State* L, int funcindex, int n) {\n\n return detail::lua_setupvalue(L, funcindex, n);\n\n}\n\ninline void* UpvalueID(State* L, int fidx, int n) {\n\n return detail::lua_upvalueid(L, fidx, n);\n\n}\n\ninline void UpvalueJoin(State* L, int fidx1, int n1, int fidx2, int n2) {\n\n return detail::lua_upvaluejoin(L, fidx1, n1, fidx2, n2);\n\n}\n\ninline void SetHook(State* L, Hook func, int mask, int count) {\n\n return detail::lua_sethook(L, func, mask, count);\n\n}\n", "file_path": "include/Lua/Lua.hpp", "rank": 80, "score": 11.010122842500133 }, { "content": "inline int Math(State* L) {\n\n return detail::luaopen_math(L);\n\n}\n\ninline int Debug(State* L) {\n\n return detail::luaopen_debug(L);\n\n}\n\ninline int Package(State* L) {\n\n return detail::luaopen_package(L);\n\n}\n\n//Not sure it's the right place for this function since it's an auxiliary\n\n//function, but declared in lualib.h\n\ninline void Libs(State* L) {\n\n detail::luaL_openlibs(L);\n\n}\n\n\n\n} //Namespace Open\n\n\n\n} //Namespace Lib\n\n\n\nnamespace Aux {\n", "file_path": "include/Lua/Lua.hpp", "rank": 81, "score": 10.96071563375165 }, { "content": "static int luaB_xpcall (lua_State *L) {\n\n int status;\n\n int n = lua_gettop(L);\n\n luaL_checktype(L, 2, LUA_TFUNCTION); /* check error function */\n\n lua_pushboolean(L, 1); /* first result */\n\n lua_pushvalue(L, 1); /* function */\n\n lua_rotate(L, 3, 2); /* move them below function's arguments */\n\n status = lua_pcallk(L, n - 2, LUA_MULTRET, 2, 2, finishpcall);\n\n return finishpcall(L, status, 2);\n", "file_path": "subprojects/lua/src/lbaselib.c", "rank": 82, "score": 10.884724030644609 }, { "content": " Lua::Aux::SetFuncs(L, ClientSocketMetaTable6, 0);\n\n\n\n const Lua::Aux::Reg SocketFuncs[] = { { nullptr, nullptr } };\n\n Lua::Aux::NewLib(L, SocketFuncs);\n\n\n\n Lua::Newtable(L);\n\n Lua::PushCFunction(L, New<Sctp::Socket::Server<4>>);\n\n Lua::SetField(L, -2, \"socket4\");\n\n Lua::PushCFunction(L, New<Sctp::Socket::Server<6>>);\n\n Lua::SetField(L, -2, \"socket6\");\n\n Lua::SetField(L, -2, \"server\");\n\n\n\n Lua::Newtable(L);\n\n Lua::PushCFunction(L, New<Sctp::Socket::Client<4>>);\n\n Lua::SetField(L, -2, \"socket4\");\n\n Lua::PushCFunction(L, New<Sctp::Socket::Client<6>>);\n\n Lua::SetField(L, -2, \"socket6\");\n\n Lua::SetField(L, -2, \"client\");\n\n\n\n return 1;\n\n}\n", "file_path": "src/lsctp.cpp", "rank": 83, "score": 10.84917153962978 }, { "content": "void luaK_setoneret (FuncState *fs, expdesc *e) {\n\n if (e->k == VCALL) { /* expression is an open function call? */\n\n /* already returns 1 value */\n\n lua_assert(GETARG_C(getinstruction(fs, e)) == 2);\n\n e->k = VNONRELOC; /* result has fixed position */\n\n e->u.info = GETARG_A(getinstruction(fs, e));\n\n }\n\n else if (e->k == VVARARG) {\n\n SETARG_B(getinstruction(fs, e), 2);\n\n e->k = VRELOCABLE; /* can relocate its simple result */\n\n }\n", "file_path": "subprojects/lua/src/lcode.c", "rank": 84, "score": 10.658761331721664 }, { "content": " but that would prevent the other tests to run\n\n]]\n\n\n\nio.write(\"socket(ipv4): \")\n\nlocal sock4, error = sctp.server.socket4()\n\nprintResult(sock4 ~= nil and type(sock4) == \"userdata\", error)\n\n\n\nio.write(\"bind(ipv4SH): \")\n\nlocal success, error = sock4:bind(12345, \"127.0.0.1\")\n\nprintResult(success, error)\n\nsock4:close()\n\n\n\nlocal sock4MH = sctp.server.socket4()\n\nio.write(\"bind(ipv4MH): \")\n\nlocal success, error = sock4MH:bind(12345, \"127.0.0.1\", \"127.0.0.2\", \"127.1.1.1\")\n\nprintResult(success, error)\n\nsock4MH:close()\n\n\n\nio.write(\"socket(ipv6): \")\n\nlocal sock6, error = sctp.server.socket6()\n", "file_path": "tst/lua/socket.lua", "rank": 85, "score": 10.54536527745663 }, { "content": " detail::lua_pushnil(L);\n\n}\n\ninline void PushNumber(State* L, Number n) {\n\n detail::lua_pushnumber(L, n);\n\n}\n\ninline void PushInteger(State* L, Integer n) {\n\n detail::lua_pushinteger(L, n);\n\n}\n\ninline const char* PushLString(State* L, const char* s, std::size_t len) {\n\n return detail::lua_pushlstring(L, s, len);\n\n}\n\ninline const char* PushString(State* L, const char* s) {\n\n return detail::lua_pushstring(L, s);\n\n}\n\ninline const char* PushVFString(State* L, const char* fmt, va_list argp) {\n\n return detail::lua_pushvfstring(L, fmt, argp);\n\n}\n\ntemplate<class ...VarArgs>\n\ninline const char* PushFString(State* L, const char* fmt, VarArgs&&... args) {\n\n return detail::lua_pushfstring(L, fmt, args...);\n", "file_path": "include/Lua/Lua.hpp", "rank": 86, "score": 9.457614957293085 }, { "content": "}\n\ninline void AddValue(Buffer& B) {\n\n detail::luaL_addvalue(&B);\n\n}\n\ninline void PushResult(Buffer& B) {\n\n detail::luaL_pushresult(&B);\n\n}\n\ninline void PushResultSize(Buffer& B, size_t sz) {\n\n detail::luaL_pushresultsize(&B, sz);\n\n}\n\ninline char* BuffInitSize(State* L, Buffer& B, size_t sz) {\n\n return detail::luaL_buffinitsize(L, &B, sz);\n\n}\n\n\n\n//#define luaL_prepbuffsize(B, sz) PrepBuffSize(*B, sz)\n\ninline void AddChar(Buffer& B, char c) {\n\n luaL_addchar(&B, c);\n\n //B.n < B.size || PrepBuffSize(B, 1), B.b[B.n++] = c;\n\n}\n\n\n", "file_path": "include/Lua/Lua.hpp", "rank": 87, "score": 9.128178870002944 }, { "content": " return detail::luaopen_coroutine(L);\n\n}\n\ninline int Table(State* L) {\n\n return detail::luaopen_table(L);\n\n}\n\ninline int IO(State* L) {\n\n return detail::luaopen_io(L);\n\n}\n\ninline int OS(State* L) {\n\n return detail::luaopen_os(L);\n\n}\n\ninline int String(State* L) {\n\n return detail::luaopen_string(L);\n\n}\n\ninline int Utf8(State* L) {\n\n return detail::luaopen_utf8(L);\n\n}\n\ninline int Bit32(State* L) {\n\n return detail::luaopen_bit32(L);\n\n}\n", "file_path": "include/Lua/Lua.hpp", "rank": 88, "score": 9.10607574635613 }, { "content": "static void settabss (lua_State *L, const char *k, const char *v) {\n\n lua_pushstring(L, v);\n\n lua_setfield(L, -2, k);\n", "file_path": "subprojects/lua/src/ldblib.c", "rank": 89, "score": 9.067385165854153 }, { "content": "TString *luaS_new (lua_State *L, const char *str) {\n\n unsigned int i = point2uint(str) % STRCACHE_N; /* hash */\n\n int j;\n\n TString **p = G(L)->strcache[i];\n\n for (j = 0; j < STRCACHE_M; j++) {\n\n if (strcmp(str, getstr(p[j])) == 0) /* hit? */\n\n return p[j]; /* that is it */\n\n }\n\n /* normal route */\n\n for (j = STRCACHE_M - 1; j > 0; j--)\n\n p[j] = p[j - 1]; /* move out last element */\n\n /* new element is first in the list */\n\n p[0] = luaS_newlstr(L, str, strlen(str));\n\n return p[0];\n", "file_path": "subprojects/lua/src/lstring.c", "rank": 90, "score": 8.564880373665204 }, { "content": "# lsctp\n\nA simple Lua module that binds some features of the SCTP api.\n\n\n\nLimitations:\n\n- One-to-one sockets only\n\n- Mixing IPv4 and IPv6 addresses are not supported\n\n- Usage of deprecated sctp_sendmsg() and sctp_recvmsg() functions (because of lksctp-tools)\n\n\n\nExample usage:\n\n```lua\n\nsctp = require \"sctp\"\n\n\n\nlocal server = sctp.server.socket4()\n\nserver:bind(12345, \"127.0.0.1\")\n\nserver:listen()\n\n\n\nlocal client = sctp.client.socket4()\n\nclient:connect(12345, \"127.0.0.1\")\n\n\n\nlocal peer = server:accept()\n\n\n\nclient:send(string.pack(\"iii\", 1, 2, 3))\n\nlocal size, msg = peer:recv()\n\n\n\nprint(string.unpack(\"iii\", msg))\n\n\n\npeer:close()\n\nclient:close()\n\nserver:close()\n\n\n\n```\n", "file_path": "README.md", "rank": 91, "score": 8.365179254265 }, { "content": "static int checkupval (lua_State *L, int argf, int argnup) {\n\n int nup = (int)luaL_checkinteger(L, argnup); /* upvalue index */\n\n luaL_checktype(L, argf, LUA_TFUNCTION); /* closure */\n\n luaL_argcheck(L, (lua_getupvalue(L, argf, nup) != NULL), argnup,\n\n \"invalid upvalue index\");\n\n return nup;\n", "file_path": "subprojects/lua/src/ldblib.c", "rank": 92, "score": 8.198772678703804 }, { "content": "static const char *get_prompt (lua_State *L, int firstline) {\n\n const char *p;\n\n lua_getglobal(L, firstline ? \"_PROMPT\" : \"_PROMPT2\");\n\n p = lua_tostring(L, -1);\n\n if (p == NULL) p = (firstline ? LUA_PROMPT : LUA_PROMPT2);\n\n return p;\n", "file_path": "subprojects/lua/src/lua.c", "rank": 93, "score": 8.162816266821402 }, { "content": "}\n\n\n\n\n\nusing Buffer = detail::luaL_Buffer;\n\n\n\ninline void AddSize(Buffer& B, size_t n) {\n\n luaL_addsize(&B, n);\n\n}\n\n\n\ninline void BuffInit(State* L, Buffer& B) {\n\n detail::luaL_buffinit(L, &B);\n\n}\n\ninline char* PrepBuffSize(Buffer& B, size_t sz) {\n\n return detail::luaL_prepbuffsize(&B, sz);\n\n}\n\ninline void AddLString(Buffer& B, const char* s, size_t l) {\n\n detail::luaL_addlstring(&B, s, l);\n\n}\n\ninline void AddString(Buffer& B, const char* s) {\n\n detail::luaL_addstring(&B, s);\n", "file_path": "include/Lua/Lua.hpp", "rank": 94, "score": 8.160194375290773 }, { "content": "static int luaB_ipairs (lua_State *L) {\n\n#if defined(LUA_COMPAT_IPAIRS)\n\n return pairsmeta(L, \"__ipairs\", 1, ipairsaux);\n\n#else\n\n luaL_checkany(L, 1);\n\n lua_pushcfunction(L, ipairsaux); /* iteration function */\n\n lua_pushvalue(L, 1); /* state */\n\n lua_pushinteger(L, 0); /* initial value */\n\n return 3;\n\n#endif\n", "file_path": "subprojects/lua/src/lbaselib.c", "rank": 95, "score": 7.996607489444553 }, { "content": "void luaK_exp2nextreg (FuncState *fs, expdesc *e) {\n\n luaK_dischargevars(fs, e);\n\n freeexp(fs, e);\n\n luaK_reserveregs(fs, 1);\n\n exp2reg(fs, e, fs->freereg - 1);\n", "file_path": "subprojects/lua/src/lcode.c", "rank": 96, "score": 7.825387211621011 }, { "content": " (c[0] == 'b' and c[1] == 't');\n\n}\n\n\n\n} //Namespace detail\n\n\n\nnamespace Lua {\n\n\n\nnamespace Conf {\n\n\n\nconstexpr auto ExtraSpace = LUA_EXTRASPACE;\n\n\n\n} //namespace Conf\n\n\n\nconstexpr auto VersionMajor = LUA_VERSION_MAJOR;\n\nconstexpr auto VersionMinor = LUA_VERSION_MINOR;\n\nconstexpr auto VersionNumber = LUA_VERSION_NUM;\n\nconstexpr auto VersionRelease = LUA_VERSION_RELEASE;\n\n\n\n//Version renamed to prevent name clash with the function Version\n\nconstexpr auto VersionStr = LUA_VERSION;\n", "file_path": "include/Lua/Lua.hpp", "rank": 97, "score": 7.65218168666935 }, { "content": "void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) {\n\n lua_assert(!hasjumps(t) && (vkisinreg(t->k) || t->k == VUPVAL));\n\n t->u.ind.t = t->u.info; /* register or upvalue index */\n\n t->u.ind.idx = luaK_exp2RK(fs, k); /* R/K index for key */\n\n t->u.ind.vt = (t->k == VUPVAL) ? VUPVAL : VLOCAL;\n\n t->k = VINDEXED;\n", "file_path": "subprojects/lua/src/lcode.c", "rank": 98, "score": 7.401123782567147 }, { "content": "static int moveresults (lua_State *L, const TValue *firstResult, StkId res,\n\n int nres, int wanted) {\n\n switch (wanted) { /* handle typical cases separately */\n\n case 0: break; /* nothing to move */\n\n case 1: { /* one result needed */\n\n if (nres == 0) /* no results? */\n\n firstResult = luaO_nilobject; /* adjust with nil */\n\n setobjs2s(L, res, firstResult); /* move it to proper place */\n\n break;\n\n }\n\n case LUA_MULTRET: {\n\n int i;\n\n for (i = 0; i < nres; i++) /* move all results to correct place */\n\n setobjs2s(L, res + i, firstResult + i);\n\n L->top = res + nres;\n\n return 0; /* wanted == LUA_MULTRET */\n\n }\n\n default: {\n\n int i;\n\n if (wanted <= nres) { /* enough results? */\n\n for (i = 0; i < wanted; i++) /* move wanted results to correct place */\n\n setobjs2s(L, res + i, firstResult + i);\n\n }\n\n else { /* not enough results; use all of them plus nils */\n\n for (i = 0; i < nres; i++) /* move all results to correct place */\n\n setobjs2s(L, res + i, firstResult + i);\n\n for (; i < wanted; i++) /* complete wanted number of results */\n\n setnilvalue(res + i);\n\n }\n\n break;\n\n }\n\n }\n\n L->top = res + wanted; /* top points after the last result */\n\n return 1;\n", "file_path": "subprojects/lua/src/ldo.c", "rank": 99, "score": 7.3077081771281955 } ]
C++
SM_RayIntersect.cpp
xzrunner/sm
e31351c4fcd4470efa4dbec5bb6ee02c21ae42f8
#include "SM_RayIntersect.h" namespace sm { bool ray_ray_intersect(const Ray& ray0, const Ray& ray1, vec3* cross) { auto& da = ray0.dir; auto& db = ray1.dir; auto dc = ray1.origin - ray0.origin; auto cross_ab = da.Cross(db); if (fabs(dc.Dot(cross_ab)) > SM_LARGE_EPSILON) { return false; } float d = cross_ab.LengthSquared(); if (d < std::numeric_limits<float>::epsilon()) { return false; } auto s = dc.Cross(db).Dot(cross_ab) / d; auto t = dc.Cross(da).Dot(cross_ab) / d; if (s >= 0 && t >= 0) { *cross = ray0.origin + ray0.dir * s; return true; } return false; } bool line_line_intersect(const sm::vec3& p1, const sm::vec3& p2, const sm::vec3& p3, const sm::vec3& p4, sm::vec3* pa, sm::vec3* pb, float* mua, float* mub) { sm::vec3 p13,p43,p21; float d1343,d4321,d1321,d4343,d2121; float numer,denom; float EPS = std::numeric_limits<float>::epsilon(); p13.x = p1.x - p3.x; p13.y = p1.y - p3.y; p13.z = p1.z - p3.z; p43.x = p4.x - p3.x; p43.y = p4.y - p3.y; p43.z = p4.z - p3.z; if (fabs(p43.x) < EPS && fabs(p43.y) < EPS && fabs(p43.z) < EPS) return false; p21.x = p2.x - p1.x; p21.y = p2.y - p1.y; p21.z = p2.z - p1.z; if (fabs(p21.x) < EPS && fabs(p21.y) < EPS && fabs(p21.z) < EPS) return false; d1343 = p13.x * p43.x + p13.y * p43.y + p13.z * p43.z; d4321 = p43.x * p21.x + p43.y * p21.y + p43.z * p21.z; d1321 = p13.x * p21.x + p13.y * p21.y + p13.z * p21.z; d4343 = p43.x * p43.x + p43.y * p43.y + p43.z * p43.z; d2121 = p21.x * p21.x + p21.y * p21.y + p21.z * p21.z; denom = d2121 * d4343 - d4321 * d4321; if (fabs(denom) < EPS) return false; numer = d1343 * d4321 - d1321 * d4343; *mua = numer / denom; *mub = (d1343 + d4321 * (*mua)) / d4343; pa->x = p1.x + *mua * p21.x; pa->y = p1.y + *mua * p21.y; pa->z = p1.z + *mua * p21.z; pb->x = p3.x + *mub * p43.x; pb->y = p3.y + *mub * p43.y; pb->z = p3.z + *mub * p43.z; return true; } #define NUMDIM 3 #define RIGHT 0 #define LEFT 1 #define MIDDLE 2 bool ray_aabb_intersect(const cube& aabb, const Ray& ray, vec3* _cross) { vec3 cross; char quadrant[3]; float candidate_plane[3]; bool inside = true; for (int i = 0; i < 3; ++i) { if (ray.origin[i] < aabb.Min()[i]) { quadrant[i] = LEFT; candidate_plane[i] = aabb.Min()[i]; inside = false; } else if (ray.origin[i] > aabb.Max()[i]) { quadrant[i] = RIGHT; candidate_plane[i] = aabb.Max()[i]; inside = false; } else { quadrant[i] = MIDDLE; } } if (inside) { cross = ray.origin; return true; } float max_t[3]; for (int i = 0; i < 3; ++i) { if (quadrant[i] != MIDDLE && ray.dir[i] != 0) { max_t[i] = (candidate_plane[i]-ray.origin[i])/ray.dir[i]; } else { max_t[i] = -1; } } int which_plane = 0; for (int i = 1; i < 3; ++i) { if (max_t[which_plane] < max_t[i]) { which_plane = i; } } if (max_t[which_plane] < 0) { return false; } for (int i = 0; i < 3; ++i) { if (which_plane != i) { cross[i] = ray.origin[i] + max_t[which_plane] * ray.dir[i]; if (cross[i] < aabb.Min()[i] || cross[i] > aabb.Max()[i]) { return false; } } else { cross[i] = candidate_plane[i]; } } if (_cross) { *_cross = cross; } return true; } bool ray_obb_intersect(const cube& aabb, const vec3& pos, const Quaternion& angle, const vec3& scale, const Ray& ray, vec3* cross) { mat4 rot_mat(-angle); vec3 start = rot_mat * (ray.origin - pos); vec3 dir = rot_mat * ray.dir; Ray ray_fix(start, dir); auto aabb_scaled = aabb; aabb_scaled.Scale(scale); return ray_aabb_intersect(aabb_scaled, ray_fix, cross); } bool ray_plane_intersect(const Ray& ray, const Plane& plane, vec3* cross) { float d = ray.dir.Dot(plane.normal); if (d < -std::numeric_limits<float>::epsilon()) { float dist = -(ray.origin.Dot(plane.normal) + plane.dist) / d; *cross = ray.origin + ray.dir * dist; return true; } return false; } bool ray_plane_intersect_both_faces(const Ray& ray, const Plane& plane, vec3* cross) { float d = ray.dir.Dot(plane.normal); if (d < -std::numeric_limits<float>::epsilon() || d > std::numeric_limits<float>::epsilon()) { float dist = -(ray.origin.Dot(plane.normal) + plane.dist) / d; *cross = ray.origin + ray.dir * dist; return true; } return false; } bool ray_triangle_intersect(const mat4& mat, const vec3& v0, const vec3& v1, const vec3& v2, const Ray& ray, vec3* cross) { auto _v0 = mat * v0; auto _v1 = mat * v1; auto _v2 = mat * v2; auto e1 = _v1 - _v0; auto e2 = _v2 - _v0; auto p = ray.dir.Cross(e2);; auto a = e1.Dot(p); auto epsilon = std::numeric_limits<float>::epsilon(); if (a < epsilon) { return false; } float f = 1.0f / a; auto s = ray.origin - _v0; cross->x = f * s.Dot(p); if (cross->x < 0.0f) { return false; } if (cross->x > 1.0f) { return false; } auto q = s.Cross(e1); cross->y = f * ray.dir.Dot(q); if (cross->y < 0.0f) { return false; } if (cross->y + cross->x > 1.0f) { return false; } cross->z = f * e2.Dot(q); return cross->z >= 0.0f; } bool ray_triangle_intersect_both_faces(const mat4& mat, const vec3& v0, const vec3& v1, const vec3& v2, const Ray& ray, vec3* cross) { auto _v0 = mat * v0; auto _v1 = mat * v1; auto _v2 = mat * v2; auto e1 = _v1 - _v0; auto e2 = _v2 - _v0; auto p = ray.dir.Cross(e2);; auto a = e1.Dot(p); float f = 1.0f / a; auto s = ray.origin - _v0; cross->x = f * s.Dot(p); if (cross->x < 0.0f) { return false; } if (cross->x > 1.0f) { return false; } auto q = s.Cross(e1); cross->y = f * ray.dir.Dot(q); if (cross->y < 0.0f) { return false; } if (cross->y + cross->x > 1.0f) { return false; } cross->z = f * e2.Dot(q); return cross->z >= 0.0f; } bool ray_polygon_intersect(const mat4& mat, const vec3* polygon, size_t polygon_n, const Ray& ray, vec3* cross) { for (size_t i = 1; i < polygon_n - 1; ++i) { if (ray_triangle_intersect(mat, polygon[0], polygon[i], polygon[i + 1], ray, cross)) { return true; } } return false; } bool ray_polygon_intersect_both_faces(const mat4& mat, const vec3* polygon, size_t polygon_n, const Ray& ray, vec3* cross) { for (size_t i = 1; i < polygon_n - 1; ++i) { if (ray_triangle_intersect_both_faces(mat, polygon[0], polygon[i], polygon[i + 1], ray, cross)) { return true; } } return false; } }
#include "SM_RayIntersect.h" namespace sm { bool ray_ray_intersect(const Ray& ray0, const Ray& ray1, vec3* cross) { auto& da = ray0.dir; auto& db = ray1.dir; auto dc = ray1.origin - ray0.origin; auto cross_ab = da.Cross(db); if (fabs(dc.Dot(cross_ab)) > SM_LARGE_EPSILON) { return false; } float d = cross_ab.LengthSquared(); if (d < std::numeric_limits<float>::epsilon()) { return false; } auto s = dc.Cross(db).Dot(cross_ab) / d; auto t = dc.Cross(da).Dot(cross_ab) / d; if (s >= 0 && t >= 0) { *cross = ray0.origin + ray0.dir * s; return true; } return false; } bool line_line_intersect(const sm::vec3& p1, const sm::vec3& p2, const sm::vec3& p3, const sm::vec3& p4, sm::vec3* pa, sm::vec3* pb, float* mua, float* mub) { sm::vec3 p13,p43,p21; float d1343,d4321,d1321,d4343,d2121; float numer,denom; float EPS = std::numeric_limits<float>::epsilon(); p13.x = p1.x - p3.x; p13.y = p1.y - p3.y; p13.z = p1.z - p3.z; p43.x = p4.x - p3.x; p43.y = p4.y - p3.y; p43.z = p4.z - p3.z; if (fabs(p43.x) < EPS && fabs(p43.y) < EPS && fabs(p43.z) < EPS) return false; p21.x = p2.x - p1.x; p21.y = p2.y - p1.y; p21.z = p2.z - p1.z; if (fabs(p21.x) < EPS && fabs(p21.y) < EPS && fabs(p21.z) < EPS) return false; d1343 = p13.x * p43.x + p13.y * p43.y + p13.z * p43.z; d4321 = p43.x * p21.x + p43.y * p21.y + p43.z * p21.z; d1321 = p13.x * p21.x + p13.y * p21.y + p13.z * p21.z; d4343 = p43.x * p43.x + p43.y * p43.y + p43.z * p43.z; d2121 = p21.x * p21.x + p21.y * p21.y + p21.z * p21.z; denom = d2121 * d4343 - d4321 * d4321; if (fabs(denom) < EPS) return false; numer = d1343 * d4321 - d1321 * d4343; *mua = numer / denom; *mub = (d1343 + d4321 * (*mua)) / d4343; pa->x = p1.x + *mua * p21.x; pa->y = p1.y + *mua * p21.y; pa->z = p1.z + *mua * p21.z; pb->x = p3.x + *mub * p43.x; pb->y = p3.y + *mub * p43.y; pb->z = p3.z + *mub * p43.z; return true; } #define NUMDIM 3 #define RIGHT 0 #define LEFT 1 #define MIDDLE 2 bool ray_aabb_intersect(const cube& aabb, const Ray& ray, vec3* _cross) { vec3 cross; char quadrant[3]; float candidate_plane[3]; bool inside = true; for (int i = 0; i < 3; ++i) { if (ray.origin[i] < aabb.Min()[i]) { quadrant[i] = LEFT; candidate_plane[i] = aabb.Min()[i]; inside = false; } else if (ray.origin[i] > aabb.Max()[i]) { quadrant[i] = RIGHT; candidate_plane[i] = aabb.Max()[i]; inside = false; } else { quadrant[i] = MIDDLE; } } if (inside) { cross = ray.origin; return true; } float max_t[3]; for (int i = 0; i < 3; ++i) { if (quadrant[i] != MIDDLE && ray.dir[i] != 0) { max_t[i] = (candidate_plane[i]-ray.origin[i])/ray.dir[i]; } else { max_t[i] = -1; } } int which_plane = 0; for (int i = 1; i < 3; ++i) { if (max_t[which_plane] < max_t[i]) { which_plane = i; } } if (max_t[which_plane] < 0) { return false; } for (int i = 0; i < 3; ++i) { if (which_plane != i) { cross[i] = ray.origin[i] + max_t[which_plane] * ray.dir[i]; if (cross[i] < aabb.Min()[i] || cross[i] > aabb.Max()[i]) { return false; } } else { cross[i] = candidate_plane[i]; } } if (_cross) { *_cross = cross; } return true; } bool ray_obb_intersect(const cube& aabb, const vec3& pos, const Quaternion& angle, const vec3& scale, const Ray& ray, vec3* cross) { mat4 rot_mat(-angle); vec3 start = rot_mat * (ray.origin - pos); vec3 dir = rot_mat * ray.dir; Ray ray_fix(start, dir); auto aabb_scaled = aabb; aabb_scaled.Scale(scale); return ray_aabb_intersect(aabb_scaled, ray_fix, cross); } bool ray_plane_intersect(const Ray& ray, const Plane& plane, vec3* cross) { float d = ray.dir.Dot(plane.normal); if (d < -std::numeric_limits<float>::epsilon()) { float dist = -(ray.origin.Dot(plane.normal) + plane.dist) / d; *cross = ray.origin + ray.dir * dist; return true; } return false; } bool ray_plane_intersect_both_faces(const Ray& ray, const Plane& plane, vec3* cross) { float d = ray.dir.Dot(plane.normal); if (d < -std::numeric_limits<float>::epsilon() || d > std::numeric_limits<float>::epsilon()) { float dist = -(ray.origin.Dot(plane.normal) + plane.dist) / d; *cross = ray.origin + ray.dir * dist; return true; } return false; } bool ray_triangle_intersect(const mat4& mat, const vec3& v0, const vec3& v1, const vec3& v2, const Ray& ray, vec3* cross) { auto _v0 = mat * v0; auto _v1 = mat * v1; auto _v2 = mat * v2; auto e1 = _v1 - _v0; auto e2 = _v2 - _v0; auto p = ray.dir.Cross(e2);; auto a = e1.Dot(p); auto epsilon = std::numeric_limits<float>::epsilon(); if (a < epsilon) { return false; } float f = 1.0f / a; auto s = ray.origin - _v0; cross->x = f * s.Dot(p); if (cross->x < 0.0f) { return false; } if (cross->x > 1.0f) { return false; }
bool ray_triangle_intersect_both_faces(const mat4& mat, const vec3& v0, const vec3& v1, const vec3& v2, const Ray& ray, vec3* cross) { auto _v0 = mat * v0; auto _v1 = mat * v1; auto _v2 = mat * v2; auto e1 = _v1 - _v0; auto e2 = _v2 - _v0; auto p = ray.dir.Cross(e2);; auto a = e1.Dot(p); float f = 1.0f / a; auto s = ray.origin - _v0; cross->x = f * s.Dot(p); if (cross->x < 0.0f) { return false; } if (cross->x > 1.0f) { return false; } auto q = s.Cross(e1); cross->y = f * ray.dir.Dot(q); if (cross->y < 0.0f) { return false; } if (cross->y + cross->x > 1.0f) { return false; } cross->z = f * e2.Dot(q); return cross->z >= 0.0f; } bool ray_polygon_intersect(const mat4& mat, const vec3* polygon, size_t polygon_n, const Ray& ray, vec3* cross) { for (size_t i = 1; i < polygon_n - 1; ++i) { if (ray_triangle_intersect(mat, polygon[0], polygon[i], polygon[i + 1], ray, cross)) { return true; } } return false; } bool ray_polygon_intersect_both_faces(const mat4& mat, const vec3* polygon, size_t polygon_n, const Ray& ray, vec3* cross) { for (size_t i = 1; i < polygon_n - 1; ++i) { if (ray_triangle_intersect_both_faces(mat, polygon[0], polygon[i], polygon[i + 1], ray, cross)) { return true; } } return false; } }
auto q = s.Cross(e1); cross->y = f * ray.dir.Dot(q); if (cross->y < 0.0f) { return false; } if (cross->y + cross->x > 1.0f) { return false; } cross->z = f * e2.Dot(q); return cross->z >= 0.0f; }
function_block-function_prefix_line
[ { "content": "struct sm_vec3* sm_vec3_vector(struct sm_vec3* v, const struct sm_vec3* p1, const struct sm_vec3* p2)\n\n{\n\n\t*(vec3*)v = (*(const vec3*)p1) - (*(const vec3*)p2);\n\n\treturn v;\n\n}\n\n\n\nextern \"C\"\n", "file_path": "sm_c_vector.cpp", "rank": 0, "score": 127451.4694807237 }, { "content": "struct sm_vec3* sm_vec3_cross(struct sm_vec3* v, const struct sm_vec3* a, const struct sm_vec3* b)\n\n{\n\n\t*(vec3*)v = (*(const vec3*)a).Cross(*(const vec3*)b);\n\n\treturn v;\n\n}\n\n\n\nextern \"C\"\n", "file_path": "sm_c_vector.cpp", "rank": 1, "score": 99254.79997200954 }, { "content": "struct sm_vec2* sm_vec2_add(struct sm_vec2* v, const struct sm_vec2* p1, const struct sm_vec2* p2)\n\n{\n\n\t*(vec2*)v = (*(const vec2*)p1) + (*(const vec2*)p2);\n\n\treturn v;\n\n}\n\n\n\nextern \"C\"\n", "file_path": "sm_c_vector.cpp", "rank": 2, "score": 90633.57182052534 }, { "content": "struct sm_vec2* sm_vec2_vector(struct sm_vec2* v, const struct sm_vec2* p1, const struct sm_vec2* p2)\n\n{\n\n\t*(vec2*)v = (*(const vec2*)p1) - (*(const vec2*)p2);\n\n\treturn v;\n\n}\n\n\n\nextern \"C\"\n", "file_path": "sm_c_vector.cpp", "rank": 3, "score": 90633.57182052534 }, { "content": "struct sm_vec3* sm_vec3_mul(struct sm_vec3* v, const union sm_mat4* m)\n\n{\n\n\t*(vec3*)v = *((mat4*)m) * (*(vec3*)v);\n\n\treturn v;\n\n}\n\n\n\n}", "file_path": "sm_c_matrix.cpp", "rank": 4, "score": 88395.97956415084 }, { "content": "class Cube\n\n{\n\npublic:\n\n\tunion\n\n\t{\n\n\t\tstruct\n\n\t\t{\n\n\t\t\tT xmin;\n\n\t\t\tT ymin;\n\n\t\t\tT zmin;\n\n\n\n\t\t\tT xmax;\n\n\t\t\tT ymax;\n\n\t\t\tT zmax;\n\n\t\t};\n\n\n\n\t\tstruct\n\n\t\t{\n\n\t\t\tT min[3];\n\n\t\t\tT max[3];\n", "file_path": "SM_Cube.h", "rank": 5, "score": 64890.40767913923 }, { "content": "namespace sm\n\n{\n\n\n\nbool ray_ray_intersect(const Ray& ray0, const Ray& ray1, vec3* cross);\n\nbool line_line_intersect(const sm::vec3& p1, const sm::vec3& p2,\n\n\t const sm::vec3& p3, const sm::vec3& p4,\n\n\t sm::vec3* pa, sm::vec3* pb, float* mua, float* mub);\n\n\n\nbool ray_aabb_intersect(const cube& aabb, const Ray& ray, vec3* cross);\n\nbool ray_obb_intersect(const cube& aabb, const vec3& pos, const Quaternion& angle, const vec3& scale, const Ray& ray, vec3* cross);\n\n\n\nbool ray_plane_intersect(const Ray& ray, const Plane& plane, vec3* cross);\n\nbool ray_plane_intersect_both_faces(const Ray& ray, const Plane& plane, vec3* cross);\n\n\n\nbool ray_triangle_intersect(const mat4& mat, const vec3& v0, const vec3& v1, const vec3& v2, const Ray& ray, vec3* cross);\n\nbool ray_triangle_intersect_both_faces(const mat4& mat, const vec3& v0, const vec3& v1, const vec3& v2, const Ray& ray, vec3* cross);\n\n\n\nbool ray_polygon_intersect(const mat4& mat, const vec3* polygon, size_t polygon_n, const Ray& ray, vec3* cross);\n\nbool ray_polygon_intersect_both_faces(const mat4& mat, const vec3* polygon, size_t polygon_n, const Ray& ray, vec3* cross);\n\n\n", "file_path": "SM_RayIntersect.h", "rank": 6, "score": 55230.392108289256 }, { "content": "class PlaneT\n\n{\n\npublic:\n\n\tPlaneT() : dist(0) {}\n\n\tPlaneT(const Vector3<T>& normal, T d);\n\n\tPlaneT(const Vector3<T>& normal, const Vector3<T>& v0);\n\n\tPlaneT(const Vector3<T>& v0, const Vector3<T>& v1, const Vector3<T>& v2);\n\n\n\n T GetDistance(const Vector3<T>& v) const;\n\n\n\n\tvoid Build(const Vector3<T>& normal, T d);\n\n\tvoid Build(const Vector3<T>& normal, const Vector3<T>& v);\n\n\tvoid Build(const Vector3<T>& v0, const Vector3<T>& v1, const Vector3<T>& v2);\n\n\n\n void Flip();\n\n\n\npublic:\n\n\tVector3<T> normal;\n\n\tT dist;\n\n\n\n}; // PlaneT\n\n\n\ntypedef PlaneT<float> Plane;\n\n\n\n}\n\n\n\n#include \"SM_Plane.inl\"\n\n\n\n#endif // _SPATIAL_MATH_PLANE_H_", "file_path": "SM_Plane.h", "rank": 7, "score": 42761.786856540326 }, { "content": "class QuaternionT\n\n{\n\npublic:\n\n\tQuaternionT();\n\n\tQuaternionT(T x, T y, T z);\n\n\tQuaternionT(T x, T y, T z, T w);\n\n\tQuaternionT(const Vector4<T>& vec4);\n\n\n\n\tbool operator == (const QuaternionT<T>& q) const;\n\n\tbool operator != (const QuaternionT<T>& q) const;\n\n\n\n\tQuaternionT<T> operator - () const;\n\n\n\n\tQuaternionT<T> operator + (const QuaternionT<T>& q) const;\n\n\tQuaternionT<T> operator - (const QuaternionT<T>& q) const;\n\n\tQuaternionT<T> operator * (const QuaternionT<T>& q) const;\n\n\n\n\tvoid Normalize();\n\n\tT Dot(const QuaternionT<T>& q) const;\n\n\n", "file_path": "SM_Quaternion.h", "rank": 8, "score": 42680.34130678028 }, { "content": "class RayT\n\n{\n\npublic:\n\n\tRayT() {}\n\n\tRayT(const Vector3<T>& origin, const Vector3<T>& dir)\n\n\t\t: origin(origin), dir(dir) {}\n\n\n\npublic:\n\n\tVector3<T> origin;\n\n\tVector3<T> dir;\n\n\n\n}; // RayT\n\n\n\ntypedef RayT<float> Ray;\n\n\n\n}", "file_path": "SM_Ray.h", "rank": 9, "score": 42106.3964685321 }, { "content": "struct sm_vec3* sm_vec3_normalize(struct sm_vec3* v)\n\n{\n\n\t((vec3*)v)->Normalize();\n\n\treturn v;\n\n}\n\n\n\n}", "file_path": "sm_c_vector.cpp", "rank": 10, "score": 41888.922732299216 }, { "content": "#ifndef _SPATIAL_MATH_PLANE_H_\n\n#define _SPATIAL_MATH_PLANE_H_\n\n\n\n#include \"SM_Vector.h\"\n\n\n\nnamespace sm\n\n{\n\n\n\ntemplate <typename T>\n", "file_path": "SM_Plane.h", "rank": 11, "score": 38422.97512379597 }, { "content": "\tbool Combine(const Vector3<T>& v);\n\n\tbool Combine(const Cube<T>& r);\n\n\n\n\tT Width() const;\n\n\tT Height() const;\n\n\tT Depth() const;\n\n\n\n\tVector3<T> Size() const;\n\n\tVector3<T> Center() const;\n\n\n\n\tvoid Translate(const Vector3<T>& trans);\n\n\tvoid Scale(const Vector3<T>& scale);\n\n\n\n\tconst T* Max() const { return max; }\n\n\tconst T* Min() const { return min; }\n\n\n\n}; // Cube\n\n\n\ntypedef Cube<int16_t> i16_cube;\n\n\n\ntypedef Cube<float> cube;\n\n\n\n}\n\n\n\n#include \"SM_Cube.inl\"\n\n\n\n#endif // _SPATIAL_MATH_CUBE_H_", "file_path": "SM_Cube.h", "rank": 12, "score": 38353.45963225734 }, { "content": "#ifndef _SPATIAL_MATH_CUBE_H_\n\n#define _SPATIAL_MATH_CUBE_H_\n\n\n\n#include \"SM_Vector.h\"\n\n\n\n#include <stdint.h>\n\n\n\nnamespace sm\n\n{\n\n\n\ntemplate <typename T>\n", "file_path": "SM_Cube.h", "rank": 13, "score": 38352.09533464624 }, { "content": "#ifndef _SPATIAL_MATH_QUATERNION_H_\n\n#define _SPATIAL_MATH_QUATERNION_H_\n\n\n\n#include \"SM_Vector.h\"\n\n\n\nnamespace sm\n\n{\n\n\n\ntemplate <typename T>\n", "file_path": "SM_Quaternion.h", "rank": 14, "score": 38351.61433448528 }, { "content": "\n\npublic:\n\n\tT x;\n\n\tT y;\n\n\tT z;\n\n\tT w;\n\n\n\n}; // QuaternionT\n\n\n\ntypedef QuaternionT<float> Quaternion;\n\n\n\n}\n\n\n\n#include \"SM_Quaternion.inl\"\n\n\n\n#endif // _SPATIAL_MATH_QUATERNION_H_", "file_path": "SM_Quaternion.h", "rank": 15, "score": 38351.3000097533 }, { "content": "\tvoid Slerp(const QuaternionT<T>& a, const QuaternionT<T>& b, T t);\n\n\tvoid NSlerp(const QuaternionT<T>& a, const QuaternionT<T>& b, T t);\n\n\n\n\tvoid Inverted();\n\n\n\n\tvoid Rotate(const QuaternionT<T>& q);\n\n\tvoid Scale(T scale);\n\n\n\n\tQuaternionT<T> Rotated(const QuaternionT<T>& b) const;\n\n\tQuaternionT<T> Scaled(T scale) const;\n\n\n\n\tVector4<T> ToVector() const;\n\n\t//// use Matrix4's QuaternionT ctor\n\n\t//Matrix3<T> ToMatrix() const;\n\n\n\n\tstatic QuaternionT<T> CreateFromVectors(const Vector3<T>& v0, const Vector3<T>& v1);\n\n\tstatic QuaternionT<T> CreateFromAxisAngle(const Vector3<T>& axis, T radians);\n\n\tstatic QuaternionT<T> CreateFromEulerAngle(T roll, T pitch, T yaw);\n\n\n\n\tstatic void TransToEulerAngle(const QuaternionT<T>& q, T& roll, T& pitch, T& yaw);\n", "file_path": "SM_Quaternion.h", "rank": 16, "score": 38350.75317877065 }, { "content": "\t\t};\n\n\t};\n\n\n\n\n\n\n\npublic:\n\n\tCube();\n\n\tCube(T width, T height, T depth);\n\n\tCube(const Vector3<T>& center, T width, T height, T depth);\n\n\tCube(const Vector3<T>& v0, const Vector3<T>& v1);\n\n\tCube(T xmin, T ymin, T zmin, T xmax, T ymax, T zmax);\n\n\n\n\tbool operator == (const Cube& r) const;\n\n\tbool operator != (const Cube& r) const;\n\n\n\n\tvoid Build(T width, T height, T depth);\n\n\n\n\tvoid MakeEmpty();\n\n\tbool IsValid() const;\n\n\n", "file_path": "SM_Cube.h", "rank": 17, "score": 38349.62870225958 }, { "content": "#pragma once\n\n\n\n#include \"SM_Vector.h\"\n\n\n\nnamespace sm\n\n{\n\n\n\ntemplate <typename T>\n", "file_path": "SM_Ray.h", "rank": 18, "score": 37846.23547243927 }, { "content": "namespace sm\n\n{\n\n\n\nfloat sin(float x);\n\nfloat cos(float x);\n\n\n\nfloat sin_fast(float x);\n\nfloat cos_fast(float x);\n\n\n\nint next_p2(int a);\n\nbool is_power_of_two(int x);\n\n\n", "file_path": "SM_Math.h", "rank": 34, "score": 29005.409210771355 }, { "content": "namespace sm\n\n{\n\n\n\n/**\n\n * @brief\n\n * float\n\n */\n\n\n\n/**\n\n * @brief\n\n * To check if test at middle of bound0 and bound1\n\n */\n\nbool is_between(float bound0, float bound1, float test);\n\n\n\n/**\n\n * @brief\n\n * point\n\n */\n\n\n\n/**\n\n * @note\n\n * It can't handle the point on segment.\n\n *\t Before use it must make sure the point is not on the segment.\n\n */\n\nbool is_point_at_line_left(const vec2& v, const vec2& s, const vec2& e);\n\nbool is_point_in_rect(const vec2& v, const rect& r);\n\nbool is_point_on_rect(const vec2& v, const rect& r);\n\nbool is_point_in_area(const vec2& v, const std::vector<vec2>& area);\n\nbool is_point_in_circle(const vec2& v, const vec2& center, float radius);\n\nbool is_point_in_convex(const vec2& pos, const std::vector<vec2>& convex);\n\nbool is_point_in_convex(const vec2& pos, const vec2* convex, size_t num);\n\nbool is_point_intersect_polyline(const vec2& point, const std::vector<vec2>& polyline);\n\n\n\n/**\n\n * @brief\n\n * segment\n\n */\n\nbool is_segment_intersect_segment(const vec2& s0, const vec2& e0, const vec2& s1, const vec2& e1);\n\nbool is_segment_intersect_polyline(const vec2& s, const vec2& e, const std::vector<vec2>& poly);\n\n\n\nbool is_two_line_parallel(const vec2& s0, const vec2& e0, const vec2& s1, const vec2& e1);\n\n\n\n/**\n\n * @brief\n\n * rect\n\n */\n\nbool is_rect_contain_point(const rect& r, const vec2& v);\n\nbool is_rect_contain_rect(const rect& outer, const rect& inner);\n\nbool is_rect_intersect_rect(const rect& r0, const rect& r1);\n\nbool is_rect_intersect_segment(const rect& r, const vec2& s, const vec2& e);\n\nbool is_rect_intersect_polyline(const rect& r, const std::vector<vec2>& poly, bool loop);\n\nbool is_rect_intersect_polygon(const rect& r, const std::vector<vec2>& poly);\n\n\n\n/**\n\n * @brief\n\n * convex\n\n */\n\nbool is_polygon_convex(const std::vector<vec2>& poly);\n\nbool is_convex_intersect_convex(const std::vector<vec2>& c0, const std::vector<vec2>& c1);\n\n\n\n/**\n\n * @brief\n\n * polygon\n\n */\n\nbool is_polygon_intersect_polygon(const std::vector<vec2>& poly0, const std::vector<vec2>& poly1);\n\nbool is_polygon_in_polygon(const std::vector<vec2>& in, const std::vector<vec2>& out);\n\nbool is_polygon_clockwise(const std::vector<vec2>& poly);\n\n\n", "file_path": "SM_Test.h", "rank": 35, "score": 29005.409210771355 }, { "content": "namespace sm\n\n{\n\n\n\nenum TriangulateConstrained\n\n{\n\n\tTC_CONSTRAINED,\n\n\tTC_CONFORMING,\n\n\tTC_CONSTRAINED_CONFORMING_ANGLE,\n\n\tTC_CONSTRAINED_CONFORMING_AREA,\n\n\tTC_CONSTRAINED_CONFORMING_COUNT\n\n};\n\n\n\nvoid triangulate_normal(const std::vector<vec2>& bound,\n\n\t\t\t\t\t\tstd::vector<vec2>& result,\n\n\t\t\t\t\t\tTriangulateConstrained tc = TC_CONSTRAINED);\n\n\n\nvoid triangulate_holes(const std::vector<vec2>& bound,\n\n\t\t\t\t\t const std::vector<std::vector<vec2>>& holes,\n\n\t\t\t\t\t std::vector<vec2>& result,\n\n\t\t\t\t\t TriangulateConstrained tc = TC_CONSTRAINED);\n\n\n\nvoid triangulate_points(const std::vector<vec2>& bound,\n\n\t\t\t\t\t\tconst std::vector<vec2>& points,\n\n\t\t\t\t\t\tstd::vector<vec2>& result,\n\n\t\t\t\t\t\tTriangulateConstrained tc = TC_CONSTRAINED);\n\nvoid triangulate_points(const std::vector<vec2>& bound,\n\n\t\t\t\t\t\tconst std::vector<vec2>& points,\n\n\t\t\t\t\t\tstd::vector<vec2>& out_vertices,\n\n\t\t\t\t\t\tstd::vector<int>& out_triangles,\n\n\t\t\t\t\t\tTriangulateConstrained tc = TC_CONSTRAINED);\n\n\n\nvoid triangulate_lines(const std::vector<vec2>& bound,\n\n\t\t\t\t\t const std::vector<vec2>& lines,\n\n\t\t\t\t\t std::vector<vec2>& result,\n\n\t\t\t\t\t TriangulateConstrained tc = TC_CONSTRAINED);\n\n\n\nvoid triangulate_points_and_lines(const std::vector<vec2>& bound,\n\n\t\t\t\t\t\t\t\t const std::vector<vec2>& points,\n\n\t\t\t\t\t\t\t\t const std::vector<vec2>& lines,\n\n\t\t\t\t\t\t\t\t std::vector<vec2>& result,\n\n\t\t\t\t\t\t\t\t TriangulateConstrained tc = TC_CONSTRAINED);\n\n\n\nvoid triangulate_lines_and_loops(const std::vector<vec2>& bound,\n\n\t\t\t\t\t\t\t\t const std::vector<vec2>& lines,\n\n\t\t\t\t\t\t\t\t const std::vector<std::vector<vec2> >& loops,\n\n\t\t\t\t\t\t\t\t std::vector<vec2>& result,\n\n\t\t\t\t\t\t\t\t TriangulateConstrained tc = TC_CONSTRAINED);\n\n\n", "file_path": "SM_Triangulation.h", "rank": 36, "score": 29005.409210771355 }, { "content": "namespace sm\n\n{\n\n\n\ninline\n\nfloat linear(float t)\n\n{\n\n\treturn t;\n\n}\n\n\n\ninline\n\nfloat in_quad(float t)\n\n{\n\n\treturn t * t;\n\n}\n\n\n\ninline\n\nfloat out_quad(float t)\n\n{\n\n\treturn -t * (t - 2);\n\n}\n\n\n\ninline\n\nfloat in_out_quad(float t)\n\n{\n\n\tif (t < 0.5f) {\n\n\t\treturn 2 * t * t;\n\n\t} else {\n\n\t\tt = 2 * t - 1;\n\n\t\treturn -0.5f * (t*(t-2) - 1);\n\n\t}\n\n}\n\n\n\ninline\n\nfloat in_cubic(float t)\n\n{\n\n\treturn t * t * t;\n\n}\n\n\n\ninline\n\nfloat out_cubic(float t)\n\n{\n\n\tt -= 1;\n\n\treturn t*t*t + 1;\n\n}\n\n\n\ninline\n\nfloat in_out_cubic(float t)\n\n{\n\n\tt *= 2;\n\n\tif (t < 1) {\n\n\t\treturn 0.5f * t * t * t;\n\n\t} else {\n\n\t\tt -= 2;\n\n\t\treturn 0.5f * (t*t*t + 2);\n\n\t}\n\n}\n\n\n\ninline\n\nfloat in_quart(float t)\n\n{\n\n\treturn t * t * t * t;\n\n}\n\n\n\ninline\n\nfloat out_quart(float t)\n\n{\n\n\tt -= 1;\n\n\treturn -(t*t*t*t - 1);\n\n}\n\n\n\ninline\n\nfloat in_out_quart(float t)\n\n{\n\n\tt *= 2;\n\n\tif (t < 1) {\n\n\t\treturn 0.5f * t * t * t * t;\n\n\t} else {\n\n\t\tt -= 2;\n\n\t\treturn -0.5f * (t*t*t*t - 2);\n\n\t}\n\n}\n\n\n\ninline\n\nfloat in_quint(float t)\n\n{\n\n\treturn t * t * t * t * t;\n\n}\n\n\n\ninline\n\nfloat out_quint(float t)\n\n{\n\n\tt -= 1;\n\n\treturn t*t*t*t*t + 1;\n\n}\n\n\n\ninline\n\nfloat in_out_quint(float t)\n\n{\n\n\tt *= 2;\n\n\tif (t < 1) {\n\n\t\treturn 0.5f * t * t * t * t * t;\n\n\t} else {\n\n\t\tt -= 2;\n\n\t\treturn 0.5f * (t*t*t*t*t + 2);\n\n\t}\n\n}\n\n\n\ninline\n\nfloat in_sine(float t)\n\n{\n\n\treturn -1 * cosf(t * SM_PI / 2) + 1;\n\n}\n\n\n\ninline\n\nfloat out_sine(float t)\n\n{\n\n\treturn sinf(t * SM_PI / 2);\n\n}\n\n\n\ninline\n\nfloat in_out_sine(float t)\n\n{\n\n\treturn -0.5f * (cosf(SM_PI * t) - 1);\n\n}\n\n\n\ninline\n\nfloat in_expo(float t)\n\n{\n\n\tif (t == 0) {\n\n\t\treturn 0;\n\n\t} else {\n\n\t\treturn powf(2, 10*(t-1));\n\n\t}\n\n}\n\n\n\ninline\n\nfloat out_expo(float t)\n\n{\n\n\tif (t == 1) {\n\n\t\treturn 1;\n\n\t} else {\n\n\t\treturn 1 - powf(2, -10*t);\n\n\t}\n\n}\n\n\n\ninline\n\nfloat in_out_expo(float t)\n\n{\n\n\tif (t == 0) {\n\n\t\treturn 0;\n\n\t} else if (t == 1) {\n\n\t\treturn 1;\n\n\t} else {\n\n\t\tif (t < 0.5f) {\n\n\t\t\treturn 0.5f * powf(2, (20*t)-10);\n\n\t\t} else {\n\n\t\t\treturn 1 - 0.5f * powf(2, (-20*t)+10);\n\n\t\t}\n\n\t}\n\n}\n\n\n\ninline\n\nfloat in_circ(float t)\n\n{\n\n\treturn -1 * (sqrtf(1-t*t) - 1);\n\n}\n\n\n\ninline\n\nfloat out_circ(float t)\n\n{\n\n\tt -= 1;\n\n\treturn sqrtf(1 - (t * t));\n\n}\n\n\n\ninline\n\nfloat in_out_circ(float t)\n\n{\n\n\tt *= 2;\n\n\tif (t < 1) {\n\n\t\treturn -0.5f * (sqrtf(1-t*t) - 1);\n\n\t} else {\n\n\t\tt = t - 2;\n\n\t\treturn 0.5f * (sqrtf(1-t*t) + 1);\n\n\t}\n\n}\n\n\n\ninline\n\nfloat in_elastic_function(float t)\n\n{\n\n\tconst float p = 0.5f;\n\n\tt -= 1;\n\n\treturn -1 * (powf(2, 10*t) * sinf((t-p/4)*(2*SM_PI)/p));\n\n}\n\n\n\ninline\n\nfloat out_elastic_function(float t)\n\n{\n\n\tconst float p = 0.5f;\n\n\treturn powf(2, -10*t) * sinf((t-p/4)*(2*SM_PI/p)) + 1;\n\n}\n\n\n\ninline\n\nfloat in_out_elastic_function(float t)\n\n{\n\n\tconst float p = 0.5f;\n\n\tt *= 2;\n\n\tif (t < 1) {\n\n\t\tt -= 1;\n\n\t\treturn -0.5f * (powf(2, 10*t) * sinf((t-p/4)*2*SM_PI/p));\n\n\t} else {\n\n\t\tt -= 1;\n\n\t\treturn powf(2, -10*t)*sinf((t-p/4)*2*SM_PI/p)*0.5f + 1;\n\n\t}\n\n}\n\n\n\ninline\n\nfloat in_elastic(float t)\n\n{\n\n\treturn in_elastic_function(0.5f);\n\n}\n\n\n\ninline\n\nfloat out_elastic(float t)\n\n{\n\n\treturn out_elastic_function(0.5f);\n\n}\n\n\n\ninline\n\nfloat in_out_elastic(float t)\n\n{\n\n\treturn in_out_elastic_function(t);\n\n}\n\n\n\ninline\n\nfloat in_back(float t)\n\n{\n\n\tfloat s = 1.70158f;\n\n\treturn t * t * ((s+1)*t - s);\n\n}\n\n\n\ninline\n\nfloat out_back(float t)\n\n{\n\n\tfloat s = 1.70158f;\n\n\tt -= 1;\n\n\treturn t*t*((s+1)*t+s) + 1;\n\n}\n\n\n\ninline\n\nfloat in_out_back(float t)\n\n{\n\n\tfloat s = 1.70158f;\n\n\tt *= 2;\n\n\tif (t < 1) {\n\n\t\ts *= 1.525f;\n\n\t\treturn 0.5f * (t * t * ((s+1)*t - s));\n\n\t} else {\n\n\t\tt -= 2;\n\n\t\ts *= 1.525f;\n\n\t\treturn 0.5f * (t*t*((s+1)*t+s) + 2);\n\n\t}\n\n}\n\n\n\ninline\n\nfloat out_bounce(float t)\n\n{\n\n\tif (t < 4/11.0f) {\n\n\t\treturn (121 * t * t) / 16.0f;\n\n\t} else if (t < 8/11.0f) {\n\n\t\treturn (363 / 40.0f * t * t) - (99 / 10.0f * t) + 17/5.0f;\n\n\t} else if (t < 9/10.0f) {\n\n\t\treturn (4356 / 361.0f * t * t) - (35442 / 1805.0f * t) + 16061/1805.0f;\n\n\t} else {\n\n\t\treturn (54 / 5.0f * t * t) - (513 / 25.0f * t) + 268/25.0f;\n\n\t}\n\n}\n\n\n\ninline\n\nfloat in_bounce(float t)\n\n{\n\n\treturn 1 - out_bounce(1-t);\n\n}\n\n\n\ninline\n\nfloat in_out_bounce(float t)\n\n{\n\n\tif (t < 0.5f) {\n\n\t\treturn in_bounce(2*t) * 0.5f;\n\n\t} else {\n\n\t\treturn out_bounce(2*t-1)*0.5f + 0.5f;\n\n\t}\n\n}\n\n\n\ninline\n\nfloat in_square(float t)\n\n{\n\n\tif (t < 1) {\n\n\t\treturn 0;\n\n\t} else {\n\n\t\treturn 1;\n\n\t}\n\n}\n\n\n\ninline\n\nfloat out_square(float t)\n\n{\n\n\tif (t > 0) {\n\n\t\treturn 1;\n\n\t} else {\n\n\t\treturn 0;\n\n\t}\n\n}\n\n\n\ninline\n\nfloat in_out_square(float t)\n\n{\n\n\tif (t < 0.5f) {\n\n\t\treturn 0;\n\n\t} else {\n\n\t\treturn 1;\n\n\t}\n\n}\n\n\n", "file_path": "SM_Ease.h", "rank": 37, "score": 29005.409210771355 }, { "content": "namespace sm\n\n{\n\n\n\nvoid douglas_peucker(const std::vector<vec2>& line,\n\n\t\t\t\t\t float precision,\n\n\t\t\t\t\t std::vector<vec2>& dst);\n\n\n", "file_path": "SM_DouglasPeucker.h", "rank": 38, "score": 28893.595509987532 }, { "content": "namespace sm\n\n{\n\n\n\nvoid convex_hull(const std::vector<vec2>& points,\n\n\t\t\t\t std::vector<vec2>& convex_hull);\n\n\n", "file_path": "SM_ConvexHull.h", "rank": 39, "score": 28893.595509987532 }, { "content": "namespace sm\n\n{\n\n\n\nvoid cosine_smooth(const std::vector<vec2>& src,\n\n\t\t\t\t float sampling_width,\n\n\t\t\t\t std::vector<vec2>& dst);\n\n\n", "file_path": "SM_CosineSmooth.h", "rank": 40, "score": 28893.595509987532 }, { "content": "struct sm_vec2* sm_vec2_normalize(struct sm_vec2* v)\n\n{\n\n\t((vec2*)v)->Normalize();\n\n\treturn v;\n\n}\n\n\n\nextern \"C\"\n", "file_path": "sm_c_vector.cpp", "rank": 41, "score": 5252.6894885384 }, { "content": "\tfloat x, y, z, w;\n", "file_path": "sm_c_vector.h", "rank": 42, "score": 4970.711533571934 }, { "content": "*/\n\nfloat get_polygon_perimeter(const std::vector<sm::vec2>& poly);\n\n\n\n/**\n\n* @brief\n\n* Get the cross point of three planes.\n\n*/\n\nbool intersect_planes(const Plane& p0, const Plane& p1, const Plane& p2, vec3* cross);\n\n\n\nsm::vec3 calc_plane_mirror(const Plane& plane, const sm::vec3& pos);\n\n\n\n}\n\n\n\n#include \"SM_Calc.inl\"\n\n\n\n#endif // _SPATIAL_MATH_CALC_H_", "file_path": "SM_Calc.h", "rank": 43, "score": 4511.767917447597 }, { "content": "float dis_pos3_to_pos3(const vec3& v0, const vec3& v1);\n\nfloat dis_square_pos3_to_pos3(const vec3& v0, const vec3& v1);\n\nfloat distance_aabb(const vec3& pos, const vec3& aabb_min, const vec3& aabb_max);\n\n\n\n/**\n\n * @brief\n\n * Get the cross point of two segment.\n\n * If they are not crossed, direct return false withnot compute the cross point.\n\n */\n\nbool intersect_line_line(const vec2& s0, const vec2& e0, const vec2& s1, const vec2& e1, vec2* cross);\n\nbool intersect_segment_segment(const vec2& s0, const vec2& e0, const vec2& s1, const vec2& e1, vec2* cross);\n\n\n\n/**\n\n * @brief\n\n * Get the foot of out at line(s, e).\n\n * Is return -1 the foot is outside the line(s, e), return 0 the foot on the line(s, e).\n\n */\n\nint get_foot_of_perpendicular(const vec2& s, const vec2& e, const vec2& out, vec2* foot);\n\nint get_foot_of_perpendicular(const vec3& s, const vec3& e, const vec3& out, vec3* foot);\n\n\n", "file_path": "SM_Calc.h", "rank": 44, "score": 4510.130204144008 }, { "content": "bool is_acute_angle(const vec2& a, const vec2& center, const vec2& b);\n\n\n\n/**\n\n * @brief\n\n * To check angle a-center-b turn left or right.\n\n */\n\nbool is_turn_left(const vec2& a, const vec2& center, const vec2& b);\n\nbool is_turn_right(const vec2& a, const vec2& center, const vec2& b);\n\n\n\n/**\n\n * @brief\n\n * distance position to ...\n\n */\n\nfloat dis_pos_to_pos(const vec2& v0, const vec2& v1);\n\nfloat dis_square_pos_to_pos(const vec2& v0, const vec2& v1);\n\nfloat dis_pos_to_multi_pos(const vec2& pos, const std::vector<vec2>& multi_pos, int* nearest_idx = NULL);\n\nfloat dis_pos_to_seg(const vec2& v, const vec2& s0, const vec2& s1);\n\nfloat dis_pos_to_polyline(const vec2& pos, const std::vector<vec2>& polyline, int* nearest_idx = NULL);\n\nfloat dis_pos_to_polygon(const vec2& pos, const std::vector<vec2>& polygon, int* nearest_idx = NULL);\n\n\n", "file_path": "SM_Calc.h", "rank": 45, "score": 4505.934705035493 }, { "content": "/**\n\n * @brief\n\n * triangle\n\n */\n\nvec2 get_tri_gravity_center(const vec2& p0, const vec2& p1, const vec2& p2);\n\n\n\n/**\n\n* @brief\n\n* area\n\n*/\n\nfloat get_polygon_area(const std::vector<sm::vec2>& polygon);\n\nfloat get_polygon_area(const std::vector<sm::vec3>& polygon);\n\nfloat get_triangle_area(const sm::vec2& p0, const sm::vec2& p1, const sm::vec2& p2);\n\n\n\nsm::vec3 calc_unit_normal(const sm::vec3& a, const sm::vec3& b, const sm::vec3& c);\n\nsm::vec3 calc_face_normal(const std::vector<sm::vec3>& polygon);\n\n\n\n/**\n\n* @brief\n\n* perimeter\n", "file_path": "SM_Calc.h", "rank": 46, "score": 4503.704845433337 }, { "content": "\tT Dot(const Vector4& v) const;\n\n\n\n}; // Vector4\n\n\n\ntypedef Vector2<bool> bvec2;\n\ntypedef Vector3<bool> bvec3;\n\ntypedef Vector4<bool> bvec4;\n\n\n\ntypedef Vector2<uint16_t> i16_vec2;\n\ntypedef Vector3<uint16_t> i16_vec3;\n\ntypedef Vector4<uint16_t> i16_vec4;\n\n\n\ntypedef Vector2<int> ivec2;\n\ntypedef Vector3<int> ivec3;\n\ntypedef Vector4<int> ivec4;\n\n\n\ntypedef Vector2<float> vec2;\n\ntypedef Vector3<float> vec3;\n\ntypedef Vector4<float> vec4;\n\n\n\n}\n\n\n\n#include \"SM_Vector.inl\"\n\n\n\n#endif // _SPATIAL_MATH_VECTOR_H_\n", "file_path": "SM_Vector.h", "rank": 47, "score": 4502.4674948716365 }, { "content": "#ifndef _SPATIAL_MATH_CALC_H_\n\n#define _SPATIAL_MATH_CALC_H_\n\n\n\n#include \"SM_Vector.h\"\n\n#include \"SM_Plane.h\"\n\n\n\n#include <vector>\n\n\n\nnamespace sm\n\n{\n\n\n", "file_path": "SM_Calc.h", "rank": 48, "score": 4501.388998164068 }, { "content": "#ifndef _SPATIAL_MATH_MATRIX_H_\n\n#define _SPATIAL_MATH_MATRIX_H_\n\n\n\n#include \"SM_Vector.h\"\n\n#include \"SM_Quaternion.h\"\n\n\n\nnamespace sm\n\n{\n\n\n\n/**\n\n * @brief\n\n * matrix2\n\n */\n\ntemplate <typename T>\n", "file_path": "SM_Matrix.h", "rank": 49, "score": 4500.6326890933 }, { "content": "\tbool IsValid() const;\n\n\n\n\tbool Combine(const Vector2<T>& v);\n\n\tbool Combine(const Rect<T>& r);\n\n\n\n\tT Width() const;\n\n\tT Height() const;\n\n\tVector2<T> Size() const;\n\n\tVector2<T> Center() const;\n\n\n\n\tvoid Translate(const Vector2<T>& trans);\n\n\tvoid Scale(const Vector2<T>& scale);\n\n\tvoid Shear(const Vector2<T>& shear);\n\n\n\n}; // Rect\n\n\n\ntypedef Rect<int> irect;\n\ntypedef Rect<int16_t> i16_rect;\n\n\n\ntypedef Rect<float> rect;\n\n\n\n}\n\n\n\n#include \"SM_Rect.inl\"\n\n\n\n#endif // _SPATIAL_MATH_RECT_H_", "file_path": "SM_Rect.h", "rank": 50, "score": 4500.565969793508 }, { "content": "#ifndef _SPATIAL_MATH_VECTOR_H_\n\n#define _SPATIAL_MATH_VECTOR_H_\n\n\n\n#include <float.h>\n\n#include <stdint.h>\n\n\n\nnamespace sm\n\n{\n\n\n\n/**\n\n * @brief\n\n * vector2\n\n */\n\ntemplate <typename T>\n", "file_path": "SM_Vector.h", "rank": 51, "score": 4499.528333776571 }, { "content": "#ifndef _SPATIAL_MATH_PROCESS_H_\n\n#define _SPATIAL_MATH_PROCESS_H_\n\n\n\n#include \"SM_Vector.h\"\n\n\n\n#include <vector>\n\n\n\nnamespace sm\n\n{\n\n\n", "file_path": "SM_Process.h", "rank": 52, "score": 4498.31268876575 }, { "content": "#ifndef _SPATIAL_MATH_RECT_H_\n\n#define _SPATIAL_MATH_RECT_H_\n\n\n\n#include \"SM_Vector.h\"\n\n\n\n#include <stdint.h>\n\n\n\nnamespace sm\n\n{\n\n\n\ntemplate <typename T>\n", "file_path": "SM_Rect.h", "rank": 53, "score": 4497.990179156728 }, { "content": "\tVector3<T> GetTranslate() const;\n\n\tVector3<T> GetScale() const;\n\n\tvoid Decompose(Vector3<T>& trans, Vector3<T>& rot, Vector3<T>& scale) const;\n\n\n\n\tstatic Matrix4<T> Translated(T x, T y, T z);\n\n\tstatic Matrix4<T> Scaled(T x, T y, T z);\n\n\tstatic Matrix4<T> Rotated(T x, T y, T z);\n\n\tstatic Matrix4<T> RotatedX(T degrees);\n\n\tstatic Matrix4<T> RotatedY(T degrees);\n\n\tstatic Matrix4<T> RotatedZ(T degrees);\n\n\tstatic Matrix4<T> RotatedAxis(const Vector3<T>& axis, T angle);\n\n\tstatic Matrix4<T> Sheared(T kx, T ky);\n\n\tstatic Matrix4<T> SkewY(T sx, T sz);\n\n\n\n\tstatic Matrix4<T> Perspective(T fovy, T aspect, T znear, T zfar);\n\n\tstatic Matrix4<T> Orthographic(T left, T right, T bottom, T top, T znear, T zfar);\n\n static Matrix4<T> LookAt(const Vector3<T>& eye, const Vector3<T>& center, const Vector3<T>& up);\n\n\n\n}; // Matrix4\n\n\n\ntypedef Matrix2<float> mat2;\n\ntypedef Matrix3<float> mat3;\n\ntypedef Matrix4<float> mat4;\n\n\n\n}\n\n\n\n#include \"SM_Matrix.inl\"\n\n\n\n#endif // _SPATIAL_MATH_MATRIX_H_", "file_path": "SM_Matrix.h", "rank": 54, "score": 4497.896384758305 }, { "content": "\t* @param sx Scale along x-axis.\n\n\t* @param sy Scale along y-axis.\n\n\t* @param ox The offset for rotation along the x-axis.\n\n\t* @param oy The offset for rotation along the y-axis.\n\n\t* @param kx Shear along x-axis\n\n\t* @param ky Shear along y-axis\n\n\t**/\n\n\tvoid SetTransformation(T x, T y, T angle, T sx, T sy, T ox, T oy, T kx, T ky);\n\n\n\n\tvoid SetTransformation(const Vector3<T>& scale, const Vector3<T>& rotation_origin,\n\n\t\tconst Vector4<T>& rotation_quaternion, const Vector3<T>& translation);\n\n\n\n\tMatrix4<T> FastMul43(const Matrix4<T>& b);\n\n\n\n Matrix4<T> Transposed() const;\n\n\tT Determinant() const;\n\n\tMatrix4<T> Inverted() const;\n\n\n\n\tQuaternionT<T> ToQuaternion() const;\n\n\n", "file_path": "SM_Matrix.h", "rank": 55, "score": 4495.265115354299 }, { "content": "\tbool operator == (const Matrix4<T>& b) const;\n\n\tbool operator != (const Matrix4<T>& b) const;\n\n\n\n Matrix4<T> operator * (const Matrix4<T>& b) const;\n\n\n\n\tVector2<T> operator * (const Vector2<T>& v) const;\n\n\tVector3<T> operator * (const Vector3<T>& v) const;\n\n\tVector4<T> operator * (const Vector4<T>& v) const;\n\n\n\n\tvoid Identity();\n\n\n\n\tvoid Translate(T x, T y, T z);\n\n\tvoid Scale(T x, T y, T z);\n\n\tvoid Shear(T kx, T ky);\n\n\tvoid RotateZ(T degrees);\n\n\n\n\t/**\n\n\t* @param x The translation along the x-axis.\n\n\t* @param y The translation along the y-axis.\n\n\t* @param angle The rotation (rad) around the center with offset (ox,oy).\n", "file_path": "SM_Matrix.h", "rank": 56, "score": 4494.053861959175 }, { "content": "\n\n\tT operator[](size_t i) const;\n\n\tT& operator[](size_t i);\n\n\n\n\tVector3& operator = (const Vector3& v);\n\n\tvoid Set(T x, T y, T z);\n\n\n\n\tvoid MakeInvalid();\n\n\tbool IsValid() const;\n\n\n\n\tbool operator == (const Vector3& v) const;\n\n\tbool operator != (const Vector3& v) const;\n\n\n\n bool operator < (const Vector3& v) const;\n\n bool operator > (const Vector3& v) const;\n\n\n\n\tVector3 operator - () const;\n\n\n\n\tvoid operator += (const Vector3& v);\n\n\tvoid operator -= (const Vector3& v);\n", "file_path": "SM_Vector.h", "rank": 57, "score": 4492.452281913595 }, { "content": "\tvoid Set(T x, T y);\n\n\n\n\tvoid MakeInvalid();\n\n\tbool IsValid() const;\n\n\n\n\tbool operator == (const Vector2& v) const;\n\n\tbool operator != (const Vector2& v) const;\n\n\n\n bool operator < (const Vector2& v) const;\n\n\n\n\tVector2<T> operator - () const;\n\n\n\n\tvoid operator += (const Vector2& v);\n\n\tvoid operator -= (const Vector2& v);\n\n\tvoid operator *= (const Vector2& v);\n\n\tvoid operator /= (const Vector2& v);\n\n\tvoid operator *= (T f);\n\n\tvoid operator /= (T f);\n\n\n\n\tVector2 operator + (const Vector2& v) const;\n", "file_path": "SM_Vector.h", "rank": 58, "score": 4492.209250656513 }, { "content": "\n\n\tT operator[](size_t i) const;\n\n\tT& operator[](size_t i);\n\n\n\n\tVector4& operator = (const Vector4& v);\n\n\tvoid Assign(T x, T y, T z, T w);\n\n\n\n\tbool operator == (const Vector4& v) const;\n\n\tbool operator != (const Vector4& v) const;\n\n\n\n\tvoid operator += (const Vector4& v);\n\n\tvoid operator -= (const Vector4& v);\n\n\tvoid operator *= (T f);\n\n\tvoid operator /= (T f);\n\n\n\n\tVector4 operator + (const Vector4& v) const;\n\n\tVector4 operator - (const Vector4& v) const;\n\n\tVector4 operator * (T f) const;\n\n\tVector4 operator / (T f) const;\n\n\n", "file_path": "SM_Vector.h", "rank": 59, "score": 4491.416992807099 }, { "content": "\tVector2 operator - (const Vector2& v) const;\n\n\tVector2 operator * (const Vector2& v) const;\n\n\tVector2 operator / (const Vector2& v) const;\n\n\tVector2 operator * (T f) const;\n\n\tVector2 operator / (T f) const;\n\n\n\n\tT Length() const;\n\n\tT LengthSquared() const;\n\n\tvoid Normalize();\n\n\tVector2 Normalized() const;\n\n\n\n\tT Cross(const Vector2& v) const;\n\n\tT Dot(const Vector2& v) const;\n\n\n\n}; // Vector2\n\n\n", "file_path": "SM_Vector.h", "rank": 60, "score": 4490.992019877361 }, { "content": "\tvoid operator *= (T f);\n\n\tvoid operator /= (T f);\n\n\n\n\tVector3 operator + (const Vector3& v) const;\n\n\tVector3 operator - (const Vector3& v) const;\n\n Vector3 operator * (const Vector3& v) const;\n\n\tVector3 operator * (T f) const;\n\n\tVector3 operator / (T f) const;\n\n\n\n\tT Length() const;\n\n\tT LengthSquared() const;\n\n\tvoid Normalize();\n\n\tVector3 Normalized() const;\n\n\n\n\tVector3 Cross(const Vector3& v) const;\n\n\tT Dot(const Vector3& v) const;\n\n\n\n}; // Vector3\n\n\n", "file_path": "SM_Vector.h", "rank": 61, "score": 4490.832724495314 }, { "content": "#include \"SM_Calc.h\"\n\n\n\nnamespace sm\n\n{\n\n\n\nsm::vec3 calc_plane_mirror(const Plane& plane, const sm::vec3& pos)\n\n{\n\n\tfloat len_s = plane.normal.LengthSquared();\n\n\tauto v1 = pos;\n\n\tfloat k = (-plane.normal.Dot(v1) - plane.dist) / len_s;\n\n\tauto v2 = plane.normal * k + v1;\n\n\treturn v2 * 2 - v1;\n\n}\n\n\n\n}", "file_path": "SM_Calc.cpp", "rank": 62, "score": 4290.698852654579 }, { "content": "#include \"SM_Calc.h\"\n\n#include \"SM_Vector.h\"\n\n#include \"sm_c_vector.h\"\n\n\n\nnamespace sm\n\n{\n\n\n\nextern \"C\"\n\nvoid sm_rotate_vector_right_angle(const struct sm_vec2* v, bool turn_left, struct sm_vec2* ret)\n\n{\n\n\tvec2 r = rotate_vector_right_angle(*(vec2*)v, turn_left);\n\n\tret->x = r.x;\n\n\tret->y = r.y;\n\n}\n\n\n\nextern \"C\"\n\nfloat sm_get_line_angle(struct sm_vec2* s, struct sm_vec2* e)\n\n{\n\n\treturn get_line_angle(*(vec2*)s, *(vec2*)e);\n\n}\n", "file_path": "sm_c_calc.cpp", "rank": 63, "score": 4282.509793156569 }, { "content": "\t\t}\n\n\t\tidx0 = next_idx0;\n\n\t}\n\n\n\n\treturn true;\n\n}\n\n\n\n//bool is_polygon_clockwise(const std::vector<vec2>& poly)\n\n//{\n\n// float cross_sum = 0.0f;\n\n// for (size_t i = 0, n = poly.size(); i < n; ++i)\n\n// {\n\n// auto& p0 = poly[i];\n\n// auto& p1 = poly[(i + 1) % n];\n\n// auto& p2 = poly[(i + 2) % n];\n\n// cross_sum += (p1 - p0).Cross(p2 - p1);\n\n// }\n\n// return cross_sum < 0;\n\n//}\n\n\n", "file_path": "SM_Test.cpp", "rank": 64, "score": 4281.650977946331 }, { "content": "#include \"SM_Test.h\"\n\n#include \"SM_Calc.h\"\n\n\n\nnamespace sm\n\n{\n\n\n\nbool is_rect_intersect_segment(const rect& r, const vec2& s, const vec2& e)\n\n{\n\n\tunsigned char type_s, type_e;\n\n\ttype_s = type_e = 0;\n\n\tif (s.x < r.xmin) // left: 1000\n\n\t\ttype_s |= 0x8;\n\n\telse if (s.x > r.xmax) // right: 0100\n\n\t\ttype_s |= 0x4;\n\n\tif (s.y < r.ymin) // down: 0001\n\n\t\ttype_s |= 0x1;\n\n\telse if (s.y > r.ymax) // up: 0010\n\n\t\ttype_s |= 0x2;\n\n\n\n\tif (e.x < r.xmin) // left: 1000\n", "file_path": "SM_Test.cpp", "rank": 65, "score": 4280.575312387531 }, { "content": " }\n\n\n\n size_t n_positive = 0, n_negative = 0;\n\n for (size_t i = 0, n = poly.size(); i < n; ++i)\n\n {\n\n auto& p0 = poly[(i + n - 1) % n];\n\n auto& p1 = poly[i];\n\n auto& p2 = poly[(i + 1) % n];\n\n auto cross = (p1 - p0).Cross(p2 - p1);\n\n if (cross > 0) {\n\n ++n_positive;\n\n } else if (cross < 0) {\n\n ++n_positive;\n\n }\n\n }\n\n return n_positive == 0 || n_negative == 0;\n\n}\n\n\n\nbool is_polygon_in_polygon(const std::vector<vec2>& in, const std::vector<vec2>& out)\n\n{\n", "file_path": "SM_Test.cpp", "rank": 66, "score": 4277.589118438845 }, { "content": "\t\t\t\tfloat angle = get_angle(start, end, start_prev);\n\n\t\t\t\tif (angle > get_angle(start, end, e) ||\n\n\t\t\t\t\tangle > get_angle(start, end, s)) {\n\n\t\t\t\t\t\treturn true;\n\n\t\t\t\t}\n\n\t\t\t} else if (is_two_points_same(end, cross)) {\n\n\t\t\t\tconst vec2& end_next = poly[get_next_idx_in_ring(sz, end_idx, 1)];\n\n\t\t\t\tfloat angle = get_angle(end, end_next, start);\n\n\t\t\t\tif (angle > get_angle(end, end_next, e) ||\n\n\t\t\t\t\tangle > get_angle(end, end_next, s)) {\n\n\t\t\t\t\t\treturn true;\n\n\t\t\t\t}\n\n\n\n\t\t\t} else {\n\n\t\t\t\treturn true;\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\n\n\treturn false;\n", "file_path": "SM_Test.cpp", "rank": 67, "score": 4277.584787873817 }, { "content": "static inline\n\nbool is_convex_intersect_convex(const std::vector<vec2>& c0, const std::vector<vec2>& c1, const vec2& v0, const vec2& v1)\n\n{\n\n\tfloat angle = SM_PI * 0.5f - atan2(v1.y - v0.y, v1.x - v0.x);\n\n\treturn is_convex_intersect_convex(c0, c1, angle);\n\n}\n\n\n\nstatic inline\n\nbool is_convex_intersect_convex(const std::vector<vec2>& c0, const std::vector<vec2>& c1, const std::vector<vec2>& proj)\n\n{\n\n\tfor (int i = 0, n = c0.size() - 1; i < n; ++i) {\n\n\t\tif (!is_convex_intersect_convex(c0, c1, proj[i], proj[i+1])) {\n\n\t\t\treturn false;\n\n\t\t}\n\n\t}\n\n\tif (!is_convex_intersect_convex(c0, c1, proj[c0.size() - 1], proj[0])) {\n\n\t\treturn false;\n\n\t}\n\n\treturn true;\n\n}\n", "file_path": "SM_Test.cpp", "rank": 68, "score": 4277.434580182571 }, { "content": "\t\ttype_e |= 0x8;\n\n\telse if (e.x > r.xmax) // right: 0100\n\n\t\ttype_e |= 0x4;\n\n\tif (e.y < r.ymin) // down: 0001\n\n\t\ttype_e |= 0x1;\n\n\telse if (e.y > r.ymax) // up: 0010\n\n\t\ttype_e |= 0x2;\n\n\n\n\tunsigned char comp;\n\n\tcomp = type_s & type_e;\n\n\tif (comp != 0)\t\t// must be outside, so must intersect\n\n\t\treturn false;\n\n\tcomp = type_s | type_e;\n\n\tif (comp == 0)\t\t// must be inside, so must not intersect\n\n\t\treturn true;\n\n\n\n\t// test each edge\n\n\tif (comp & 0x8)\t\t// 1000, left edge\n\n\t{\n\n\t\tfloat cross_y;\n", "file_path": "SM_Test.cpp", "rank": 69, "score": 4277.016277704861 }, { "content": "#include \"SM_Matrix.h\"\n\n\n\nnamespace sm\n\n{\n\n\n\nextern \"C\"\n\nunion sm_mat4* sm_mat4_mul(union sm_mat4* m, const union sm_mat4* m1, const union sm_mat4* m2)\n\n{\n\n\t*(mat4*)m = (*(mat4*)m1) * (*(mat4*)m2);\n\n\treturn m;\n\n}\n\n\n\nextern \"C\"\n\nunion sm_mat4* sm_mat4_rotxmat(union sm_mat4* m, float degrees)\n\n{\n\n\t*(mat4*)m = ((mat4*)m)->RotatedX(degrees);\n\n\treturn m;\n\n}\n\n\n\nextern \"C\"\n", "file_path": "sm_c_matrix.cpp", "rank": 70, "score": 4275.590584440552 }, { "content": "{\n\n\treturn (curr + sz + step) % sz;\n\n}\n\n\n\nstatic inline\n\nbool is_two_points_same(const vec2& p0, const vec2& p1)\n\n{\n\n\treturn fabs(p0.x - p1.x) < SM_LARGE_EPSILON\n\n\t\t&& fabs(p0.y - p1.y) < SM_LARGE_EPSILON;\n\n}\n\n\n\nbool is_segment_intersect_polyline(const vec2& s, const vec2& e, const std::vector<vec2>& poly)\n\n{\n\n\tif (poly.size() < 2) {\n\n\t\treturn false;\n\n\t} else if (poly.size() < 3) {\n\n\t\tvec2 cross;\n\n\t\tif (intersect_segment_segment(s, e, poly[0], poly[1], &cross)) {\n\n\t\t\tif (!is_two_points_same(s, cross) && !is_two_points_same(e, cross) &&\n\n\t\t\t\t!is_two_points_same(poly[0], cross) && !is_two_points_same(poly[1], cross)) {\n", "file_path": "SM_Test.cpp", "rank": 71, "score": 4275.531084272151 }, { "content": "\t\tfloat cross_x;\n\n\t\tcross_x = find_x_on_seg(s, e, r.ymax);\n\n\t\tif (cross_x >= r.xmin && cross_x <= r.xmax)\n\n\t\t\treturn true;\n\n\t}\n\n\n\n\treturn false;\n\n}\n\n\n\nstatic inline\n\nvoid project_convex(const std::vector<vec2>& c, float angle, float* min, float* max)\n\n{\n\n\t*min = FLT_MAX;\n\n\t*max = -FLT_MAX;\n\n\tfor (int i = 0, n = c.size(); i < n; ++i) {\n\n\t\tvec2 v = rotate_vector(c[i], angle);\n\n\t\tif (v.x < *min) {\n\n\t\t\t*min = v.x;\n\n\t\t}\n\n\t\tif (v.x > *max) {\n", "file_path": "SM_Test.cpp", "rank": 72, "score": 4275.402879893704 }, { "content": "\n\nextern \"C\"\n\nbool sm_intersect_line_line(const struct sm_vec2* s0, const struct sm_vec2* e0, const struct sm_vec2* s1, const struct sm_vec2* e1, struct sm_vec2* cross)\n\n{\n\n\tvec2 _cross;\n\n\tbool ret = intersect_line_line(*(vec2*)s0, *(vec2*)e0, *(vec2*)s1, *(vec2*)e1, &_cross);\n\n\tcross->x = _cross.x;\n\n\tcross->y = _cross.y;\n\n\treturn ret;\n\n}\n\n\n\n}", "file_path": "sm_c_calc.cpp", "rank": 73, "score": 4275.0999772166 }, { "content": "\t\tcross_y = find_y_on_seg(s, e, r.xmin);\n\n\t\tif (cross_y >= r.ymin && cross_y <= r.ymax)\n\n\t\t\treturn true;\n\n\t}\n\n\tif (comp & 0x4)\t\t// 0100, right edge\n\n\t{\n\n\t\tfloat cross_y;\n\n\t\tcross_y = find_y_on_seg(s, e, r.xmax);\n\n\t\tif (cross_y >= r.ymin && cross_y <= r.ymax)\n\n\t\t\treturn true;\n\n\t}\n\n\tif (comp & 0x1)\t\t// 0001, down edge\n\n\t{\n\n\t\tfloat cross_x;\n\n\t\tcross_x = find_x_on_seg(s, e, r.ymin);\n\n\t\tif (cross_x >= r.xmin && cross_x <= r.xmax)\n\n\t\t\treturn true;\n\n\t}\n\n\tif (comp & 0x2)\t\t// 0010, up edge\n\n\t{\n", "file_path": "SM_Test.cpp", "rank": 74, "score": 4273.9713495408405 }, { "content": "\n\n\tvoid Identity();\n\n\n\n\tMatrixFix Inverted() const;\n\n\n\n\tvoid Translate(float x, float y);\n\n\tvoid Scale(float sx, float sy);\n\n\tvoid Rotate(float angle);\n\n\n\n\tvoid SetTransformation(float x, float y, float angle, float sx, float sy, float ox, float oy, float kx, float ky);\n\n\t\n\n}; // MatrixFix\n\n\n\n}\n\n\n\n#include \"SM_MatrixFix.inl\"\n\n\n\n#endif // _SPATIAL_MATH_FIX_MATH_H_", "file_path": "SM_MatrixFix.h", "rank": 75, "score": 4273.858935469699 }, { "content": "\t\t\t\t\treturn true;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn false;\n\n\t}\n\n\n\n\tint sz = poly.size();\n\n\tfor (int i = 0; i < sz; ++i)\n\n\t{\n\n\t\tconst vec2& start = poly[i];\n\n\t\tint end_idx = get_next_idx_in_ring(sz, i, 1);\n\n\t\tconst vec2& end = poly[end_idx];\n\n\t\tvec2 cross;\n\n\t\tif (intersect_segment_segment(s, e, start, end, &cross)) {\n\n\t\t\tif (is_two_points_same(s, cross) || is_two_points_same(e, cross)) {\n\n\t\t\t\tcontinue;\n\n\t\t\t}\n\n\n\n\t\t\tif (is_two_points_same(start, cross)) {\n\n\t\t\t\tconst vec2& start_prev = poly[get_next_idx_in_ring(sz, i, -1)];\n", "file_path": "SM_Test.cpp", "rank": 76, "score": 4273.789608013801 }, { "content": "union sm_mat4* sm_mat4_identity(union sm_mat4* m)\n\n{\n\n\t((mat4*)m)->Identity();\n\n\treturn m;\n\n}\n\n\n\nextern \"C\"\n\nunion sm_mat4* sm_mat4_trans(union sm_mat4* m, float x, float y, float z)\n\n{\n\n\t((mat4*)m)->Translate(x, y, z);\n\n\treturn m;\n\n}\n\n\n\nextern \"C\"\n\nunion sm_mat4* sm_mat4_perspective(union sm_mat4* m, float fovy, float aspect, float znear, float zfar)\n\n{\n\n\t*(mat4*)m = ((mat4*)m)->Perspective(fovy, aspect, znear, zfar);\n\n\treturn m;\n\n}\n\n\n\nextern \"C\"\n", "file_path": "sm_c_matrix.cpp", "rank": 77, "score": 4273.708481889627 }, { "content": "\t\t\tconst vec2& start1 = poly1[idx1];\n\n\t\t\tint next_idx1 = get_next_idx_in_ring(sz1, idx1, step1);\n\n\t\t\tconst vec2& end1 = poly1[next_idx1];\n\n\n\n\t\t\tvec2 cross;\n\n\t\t\tif (intersect_segment_segment(start0, end0, start1, end1, &cross)) {\n\n\t\t\t\t// test if cross is end\n\n\t\t\t\tbool is_cross0 = is_two_points_same(cross, end0),\n\n\t\t\t\t\t is_cross1 = is_two_points_same(cross, end1);\n\n\t\t\t\tif (is_cross0 && is_cross1) {\n\n\t\t\t\t\tconst vec2& end_next0 = poly0[get_next_idx_in_ring(sz0, next_idx0, step0)];\n\n\t\t\t\t\tconst vec2& end_next1 = poly1[get_next_idx_in_ring(sz1, next_idx1, step1)];\n\n\t\t\t\t\tfloat angle0 = get_angle(end0, end_next0, start0);\n\n\t\t\t\t\tif (angle0 > get_angle(end0, end_next0, start1) ||\n\n\t\t\t\t\t\tangle0 > get_angle(end0, end_next0, end_next1)) {\n\n\t\t\t\t\t\t\treturn true;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat angle1 = get_angle(end1, end_next1, start1);\n\n\t\t\t\t\tif (angle1 > get_angle(end1, end_next1, start0) ||\n\n\t\t\t\t\t\tangle1 > get_angle(end1, end_next1, end_next0)) {\n", "file_path": "SM_Test.cpp", "rank": 78, "score": 4273.610172782884 }, { "content": "bool is_polygon_clockwise(const std::vector<vec2>& poly)\n\n{\n\n float sum = 0.0f;\n\n for (size_t i = 0, n = poly.size(); i < n; ++i)\n\n {\n\n auto& p0 = poly[i];\n\n auto& p1 = poly[(i + 1) % n];\n\n sum += (p1.x - p0.x) * (p1.y + p0.y);\n\n }\n\n return sum > 0;\n\n}\n\n\n\n}", "file_path": "SM_Test.cpp", "rank": 79, "score": 4273.607846401534 }, { "content": "\tvoid Scale(float sx, float sy);\n\n\tvoid Rotate(float angle);\n\n\tvoid Translate(float x, float y);\n\n\n\n\tvoid SetTransformation(float x, float y, float angle, float sx, float sy, float ox, float oy, float kx, float ky);\n\n\n\n\tvoid Decompose(sm::vec2& scale, float& rotate, sm::vec2& translate) const;\n\n\n\n\tstatic void Mul(const Matrix2D& m0, const Matrix2D& m1, Matrix2D& out);\n\n\n\n}; // Matrix2D\n\n\n\n#define SM_MAT2D_MUL(m0, m1, out) \\\n\n\tout[0] = m0[0] * m1[0] + m0[1] * m1[2]; \\\n\n\tout[1] = m0[0] * m1[1] + m0[1] * m1[3]; \\\n\n\tout[2] = m0[2] * m1[0] + m0[3] * m1[2]; \\\n\n\tout[3] = m0[2] * m1[1] + m0[3] * m1[3]; \\\n\n\tout[4] = m0[4] * m1[0] + m0[5] * m1[2] + m1[4]; \\\n\n\tout[5] = m0[4] * m1[1] + m0[5] * m1[3] + m1[5]; \\\n\n\n\n}\n\n\n\n#include \"SM_Matrix2D.inl\"\n\n\n\n#endif // _SPATIAL_MATH_MATRIX_2D_H_", "file_path": "SM_Matrix2D.h", "rank": 80, "score": 4273.349604494869 }, { "content": "\n\n\tfloat left = FLT_MAX;\n\n\tint left_idx = 0;\n\n\tint sz = poly.size();\n\n\tfor (int i = 0; i < sz; ++i) {\n\n\t\tif (poly[i].x < left) {\n\n\t\t\tleft = poly[i].x;\n\n\t\t\tleft_idx = i;\n\n\t\t}\n\n\t}\n\n\n\n\tconst vec2& curr = poly[left_idx];\n\n\tconst vec2& next = poly[(left_idx+1)%sz];\n\n\tconst vec2& prev = poly[(left_idx+sz-1)%sz];\n\n\tvec2 up(curr.x, curr.y + 1);\n\n\treturn get_angle(curr, up, next) < get_angle(curr, up, prev);\n\n}\n\n\n\nstatic inline\n\nint get_next_idx_in_ring(int sz, int curr, int step)\n", "file_path": "SM_Test.cpp", "rank": 81, "score": 4273.313105672091 }, { "content": "\t\tconst vec2& start0 = in[idx0];\n\n\t\tint next_idx0 = get_next_idx_in_ring(sz0, idx0, step0);\n\n\t\tconst vec2& end0 = in[next_idx0];\n\n\t\tfor (int j = 0; j < sz1; ++j) {\n\n\t\t\tconst vec2& start1 = out[idx1];\n\n\t\t\tint next_idx1 = get_next_idx_in_ring(sz1, idx1, step1);\n\n\t\t\tconst vec2& end1 = out[next_idx1];\n\n\n\n\t\t\tvec2 cross;\n\n\t\t\tif (intersect_segment_segment(start0, end0, start1, end1, &cross)) {\n\n\t\t\t\t// test if cross is end\n\n\t\t\t\tbool is_cross0 = is_two_points_same(cross, end0),\n\n\t\t\t\t\tis_cross1 = is_two_points_same(cross, end1);\n\n\t\t\t\tif (is_cross0 && is_cross1) {\n\n\t\t\t\t\tconst vec2& end_next0 = in[get_next_idx_in_ring(sz0, next_idx0, step0)];\n\n\t\t\t\t\tconst vec2& end_next1 = out[get_next_idx_in_ring(sz1, next_idx1, step1)];\n\n\t\t\t\t\tfloat angle0 = get_angle(end0, end_next0, start0);\n\n\n\n\t\t\t\t\tfloat angle_start1 = get_angle(end0, end_next0, start1),\n\n\t\t\t\t\t\tangle_end_next1 = get_angle(end0, end_next0, end_next1);\n", "file_path": "SM_Test.cpp", "rank": 82, "score": 4273.269045797124 }, { "content": "#include \"SM_Vector.h\"\n\n\n\nnamespace sm\n\n{\n\n\n\nextern \"C\"\n", "file_path": "sm_c_vector.cpp", "rank": 83, "score": 4272.050129353312 }, { "content": "#include \"SM_Triangulation.h\"\n\n#include \"SM_Calc.h\"\n\n#include \"SM_Test.h\"\n\n\n\n#include \"external/triangle/triangle.cpp\"\n\n\n\n#include <iterator>\n\n\n\n#include <assert.h>\n\n\n\nnamespace sm\n\n{\n\n\n\nstatic void init(struct triangulateio& in, struct triangulateio& out)\n\n{\n\n\tin.pointlist = NULL;\n\n\tin.pointattributelist = NULL;\n\n\tin.pointmarkerlist = NULL;\n\n\tin.trianglelist = NULL;\n\n\tin.triangleattributelist = NULL;\n", "file_path": "SM_Triangulation.cpp", "rank": 84, "score": 4271.479468050824 }, { "content": "#ifndef _SPATIAL_MATH_MATRIX_2D_H_\n\n#define _SPATIAL_MATH_MATRIX_2D_H_\n\n\n\n#include \"SM_Vector.h\"\n\n#include \"SM_Matrix.h\"\n\n\n\nnamespace sm\n\n{\n\n\n", "file_path": "SM_Matrix2D.h", "rank": 85, "score": 4271.4542170356435 }, { "content": "\t\t\t*max = v.x;\n\n\t\t}\n\n\t}\n\n}\n\n\n\nstatic inline\n\nbool is_project_intersect(float min0, float max0, float min1, float max1)\n\n{\n\n\treturn !(max1 <= min0 || min1 >= max0);\n\n}\n\n\n\nstatic inline\n\nbool is_convex_intersect_convex(const std::vector<vec2>& c0, const std::vector<vec2>& c1, float angle)\n\n{\n\n\tfloat min0, max0, min1, max1;\n\n\tproject_convex(c0, angle, &min0, &max0);\n\n\tproject_convex(c1, angle, &min1, &max1);\n\n\treturn is_project_intersect(min0, max0, min1, max1);\n\n}\n\n\n", "file_path": "SM_Test.cpp", "rank": 86, "score": 4270.720649442901 }, { "content": "\t\t\t\t\t// \t\t\t\t\t\t\treturn true;\n\n\t\t\t\t\t// \t\t\t\t\t}\n\n\t\t\t\t} else if (is_cross0) {\n\n\t\t\t\t\tconst vec2& end_next0 = poly0[get_next_idx_in_ring(sz0, next_idx0, step0)];\n\n\t\t\t\t\tif (is_turn_left(end_next0, end0, end1)) {\n\n\t\t\t\t\t\treturn true;\n\n\t\t\t\t\t}\n\n\t\t\t\t} else if (is_cross1) {\n\n\t\t\t\t\tconst vec2& end_next1 = poly0[get_next_idx_in_ring(sz1, next_idx1, step1)];\n\n\t\t\t\t\tif (is_turn_left(end_next1, end1, end0)) {\n\n\t\t\t\t\t\treturn true;\n\n\t\t\t\t\t}\n\n\t\t\t\t} else if (!is_two_points_same(cross, start0)\n\n\t\t\t\t\t&& !is_two_points_same(cross, start1)) {\n\n\t\t\t\t\t\treturn true;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tidx1 = next_idx1;\n\n\t\t}\n\n\t\tidx0 = next_idx0;\n", "file_path": "SM_Test.cpp", "rank": 87, "score": 4270.667355884127 }, { "content": "#ifndef _SPATIAL_MATH_FIX_MATH_H_\n\n#define _SPATIAL_MATH_FIX_MATH_H_\n\n\n\n#include \"SM_Vector.h\"\n\n\n\nnamespace sm\n\n{\n\n\n", "file_path": "SM_MatrixFix.h", "rank": 88, "score": 4270.661742977758 }, { "content": "\t\t\t\t\tif ((angle0 > angle_start1 && angle_start1) != 0 ||\n\n\t\t\t\t\t\t(angle0 > angle_end_next1 && angle_end_next1 != 0)) {\n\n\t\t\t\t\t\t\treturn false;\n\n\t\t\t\t\t}\n\n\t\t\t\t} else if (is_cross0) {\n\n\t\t\t\t\tconst vec2& end_next0 = in[get_next_idx_in_ring(sz0, next_idx0, step0)];\n\n\t\t\t\t\tif (is_turn_left(end_next0, end0, end1)) {\n\n\t\t\t\t\t\treturn false;\n\n\t\t\t\t\t}\n\n\t\t\t\t} else if (is_cross1) {\n\n\t\t\t\t\tconst vec2& end_next1 = in[get_next_idx_in_ring(sz1, next_idx1, step1)];\n\n\t\t\t\t\tif (is_turn_left(end_next1, end1, end0)) {\n\n\t\t\t\t\t\treturn false;\n\n\t\t\t\t\t}\n\n\t\t\t\t} else if (!is_two_points_same(cross, start0)\n\n\t\t\t\t\t&& !is_two_points_same(cross, start1)) {\n\n\t\t\t\t\t\treturn false;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tidx1 = next_idx1;\n", "file_path": "SM_Test.cpp", "rank": 89, "score": 4270.295255269406 }, { "content": "\t\tin.pointlist[ptr_p++] = p.x;\n\n\t\tin.pointlist[ptr_p++] = p.y;\n\n\t}\n\n for (auto& hole : holes_fixed) {\n\n for (auto& p : hole) {\n\n in.pointlist[ptr_p++] = p.x;\n\n in.pointlist[ptr_p++] = p.y;\n\n }\n\n }\n\n\n\n\tin.numberofsegments = in.numberofpoints;\n\n\tin.segmentlist = (int *) malloc(in.numberofsegments * 2 * sizeof(int));\n\n\tsize_t ptr_s = 0;\n\n size_t start_p_idx = 0;\n\n size_t curr_p_idx = 0;\n\n\tfor (size_t i = 0; i < bound_fixed.size() - 1; ++i)\n\n {\n\n\t\tin.segmentlist[ptr_s++] = curr_p_idx;\n\n\t\tin.segmentlist[ptr_s++] = curr_p_idx + 1;\n\n ++curr_p_idx;\n", "file_path": "SM_Triangulation.cpp", "rank": 90, "score": 4269.201959248575 }, { "content": "\t\tif (is_point_in_area(center, bound))\n\n {\n\n bool in_hole = false;\n\n for (auto& hole : holes)\n\n {\n\n if (is_point_in_area(center, hole)) {\n\n in_hole = true;\n\n break;\n\n }\n\n }\n\n\n\n if (!in_hole) {\n\n copy(tri.begin(), tri.end(), back_inserter(result));\n\n }\n\n\t\t}\n\n\t}\n\n\n\n\tfinish(in, out);\n\n}\n\n\n", "file_path": "SM_Triangulation.cpp", "rank": 91, "score": 4269.009487008918 }, { "content": "\t}\n\n\n\n\tfor (int i = 0; i < sz0; ++i) {\n\n\t\tif (is_point_intersect_polyline(poly0[i], poly1)) { continue; }\n\n\t\treturn is_point_in_area(poly0[i], poly1);\n\n\t}\n\n\tfor (int i = 0; i < sz1; ++i) {\n\n\t\tif (is_point_intersect_polyline(poly1[i], poly0)) { continue; }\n\n\t\treturn is_point_in_area(poly1[i], poly0);\n\n\t}\n\n\treturn false;\n\n}\n\n\n\nbool is_polygon_convex(const std::vector<vec2>& poly)\n\n{\n\n if (poly.size() < 2) {\n\n return false;\n\n }\n\n if (poly.size() == 3) {\n\n return true;\n", "file_path": "SM_Test.cpp", "rank": 92, "score": 4268.625797210231 }, { "content": "\t\t\t skip = true;\n\n\t\t\t break;\n\n\t\t }\n\n\t }\n\n\t if (skip) {\n\n\t\t continue;\n\n\t }\n\n\t dst.push_back(src[i]);\n\n }\n\n}\n\n\n\nstatic void verify_inner(const std::vector<vec2>& outer, std::vector<vec2>& inner)\n\n{\n\n\tstd::vector<vec2>::iterator itr = inner.begin();\n\n\tfor ( ; itr != inner.end(); )\n\n\t{\n\n\t\tbool find = false;\n\n\t\tfor (int i = 0, n = outer.size(); i < n; ++i) {\n\n\t\t\tif (*itr == outer[i]) {\n\n\t\t\t\tfind = true;\n", "file_path": "SM_Triangulation.cpp", "rank": 93, "score": 4268.537920147126 }, { "content": "\t}\n\n\tin.segmentlist[ptr_s++] = curr_p_idx;\n\n\tin.segmentlist[ptr_s++] = start_p_idx;\n\n ++curr_p_idx;\n\n start_p_idx = curr_p_idx;\n\n\n\n for (auto& hole : holes_fixed)\n\n {\n\n\t for (size_t i = 0; i < hole.size() - 1; ++i)\n\n {\n\n\t\t in.segmentlist[ptr_s++] = curr_p_idx;\n\n\t\t in.segmentlist[ptr_s++] = curr_p_idx + 1;\n\n ++curr_p_idx;\n\n\t }\n\n\t in.segmentlist[ptr_s++] = curr_p_idx;\n\n\t in.segmentlist[ptr_s++] = start_p_idx;\n\n ++curr_p_idx;\n\n start_p_idx = curr_p_idx;\n\n }\n\n\n", "file_path": "SM_Triangulation.cpp", "rank": 94, "score": 4267.367902920074 }, { "content": "\t\tin.segmentlist[index++] = start;\n\n\t\t++loopIndex;\n\n\t}\n\n\n\n\tin.segmentmarkerlist = (int *) NULL;\n\n\n\n\tin.numberofholes = 0;\n\n\tin.numberofregions = 0;\n\n\n\n\timplement(in, out, tc);\n\n\tfinish(in, out, bound_fixed, result);\n\n}\n\n\n\n}", "file_path": "SM_Triangulation.cpp", "rank": 95, "score": 4267.321745967001 }, { "content": "static void finish(struct triangulateio& in,\n\n struct triangulateio& out,\n\n\t\t\t\t const std::vector<vec2>& bound,\n\n\t\t\t\t std::vector<vec2>& out_vertices,\n\n\t\t\t\t std::vector<int>& out_triangles)\n\n{\n\n\tout_vertices.reserve(out.numberofpoints);\n\n\tint ptr = 0;\n\n\tfor (int i = 0; i < out.numberofpoints; ++i)\n\n\t{\n\n\t\tfloat x = out.pointlist[ptr++],\n\n\t\t\t y = out.pointlist[ptr++];\n\n\t\tout_vertices.push_back(vec2(x, y));\n\n\t}\n\n\n\n\tint index = 0;\n\n\tout_triangles.reserve(out.numberoftriangles);\n\n\tfor (int i = 0; i < out.numberoftriangles; ++i)\n\n\t{\n\n\t\tstd::vector<int> tri;\n", "file_path": "SM_Triangulation.cpp", "rank": 96, "score": 4267.295163996944 }, { "content": "#include \"SM_DouglasPeucker.h\"\n\n#include \"SM_Calc.h\"\n\n\n\n#include <float.h>\n\n\n\nnamespace sm\n\n{\n\n\n\nstatic inline\n\nvoid points_reduction(const std::vector<vec2>& line,\n\n\t\t\t\t\t float precision,\n\n\t\t\t\t\t std::vector<bool>& flag,\n\n\t\t\t\t\t int begin,\n\n\t\t\t\t\t int end)\n\n{\n\n\tif (begin > end)\n\n\t\treturn;\n\n\n\n\tif (begin == end)\n\n\t{\n", "file_path": "SM_DouglasPeucker.cpp", "rank": 97, "score": 16.95288831341636 }, { "content": "// code from https://github.com/ejoy/ejoy2d/blob/master/lib/matrix.c\n\n\n\n#include \"SM_MatrixFix.h\"\n\n#include \"sm_const.h\"\n\n\n\n#include <string.h>\n\n#include <stdint.h>\n\n\n\nnamespace sm\n\n{\n\n\n\nconst float MatrixFix::SCALE_INV = 1.0f / SCALE;\n\nconst float MatrixFix::TRANSLATE_SCALE_INV = 1.0f / TRANSLATE_SCALE;\n\n\n\nMatrixFix::MatrixFix()\n\n{\n\n\tIdentity();\n\n}\n\n\n\nMatrixFix::MatrixFix(const MatrixFix& mt)\n", "file_path": "SM_MatrixFix.cpp", "rank": 98, "score": 15.96545991536301 }, { "content": "\t\t\tis_other_dir = b;\n\n\t\t}\n\n\t}\n\n\tbool b = TextOtherDir(hull, hull[0], hull[hull.size()-1], area_min, bounding);\n\n\tif (b) {\n\n\t\tis_other_dir = b;\n\n\t}\n\n\n\n\tassert(is_turn_right(bounding[0], bounding[1], bounding[2]));\n\n\n\n\treturn b;\n\n}\n\n\n\nbool MinBoundingBox::TextOtherDir(const CU_VEC<vec2>& points, \n\n\t\t\t\t\t\t\t\t const vec2& start, const vec2& end,\n\n\t\t\t\t\t\t\t\t float& min_area, vec2 bounding[4])\n\n{\n\n\tfloat dx = start.x - end.x,\n\n\t\t dy = start.y - end.y;\n\n\tif (fabs(dx) < FLT_EPSILON ||\n", "file_path": "SM_MinBoundingBox.cpp", "rank": 99, "score": 15.77004440691335 } ]
C++
Source/VoxelWorld/World/Chunk/ChunkLoader.cpp
AirGuanZ/VoxelWorld
8defdee9e2b8fb20607d33ba0f3a316b95273693
#include <algorithm> #include <cassert> #include <Utility\HelperFunctions.h> #include <World\Land\V0\LandGenerator_V0.h> #include <World\Land\V1\LandGenerator_V1.h> #include <World\Land\V2\LandGenerator_V2.h> #include <World\Land\V3\LandGenerator_V3.h> #include "ChunkLoader.h" #include "ChunkManager.h" #include "ChunkModelBuilder.h" ChunkLoader::ChunkLoader(size_t ckPoolSize) : ckPool_(ckPoolSize), landGen_(std::make_unique<LandGenerator_V0::LandGenerator>(4792539)) { } ChunkLoader::~ChunkLoader(void) { Destroy(); } void ChunkLoader::Initialize(int threadNum) { assert(threads_.empty()); if(threadNum <= 0) threadNum = (std::max)(4u, std::thread::hardware_concurrency()) - 2; running_ = true; while(threadNum-- > 0) threads_.emplace_back(&ChunkLoader::TaskThreadEntry, this); } void ChunkLoader::Destroy(void) { running_ = false; for(std::thread &th : threads_) { if(th.joinable()) th.join(); } threads_.clear(); loaderTasks_.ForEach([](ChunkLoaderTask *t) { Helper::SafeDeleteObjects(t); }); loaderTasks_.Clear(); ckPool_.Destroy(); } void ChunkLoader::AddTask(ChunkLoaderTask *task) { assert(task != nullptr); std::lock_guard<std::mutex> lk(taskQueueMutex_); loaderTasks_.PushFront(task->GetPosition(), task); } void ChunkLoader::AddMsg(ChunkLoaderMessage *msg) { assert(msg != nullptr); std::lock_guard<std::mutex> lk(msgQueueMutex_); loaderMsgs_.push(msg); } ChunkLoaderMessage *ChunkLoader::FetchMsg(void) { std::lock_guard<std::mutex> lk(msgQueueMutex_); if(loaderMsgs_.empty()) return nullptr; ChunkLoaderMessage *rt = loaderMsgs_.front(); loaderMsgs_.pop(); return rt; } std::queue<ChunkLoaderMessage*> ChunkLoader::FetchAllMsgs(void) { std::lock_guard<std::mutex> lk(msgQueueMutex_); return std::move(loaderMsgs_); } void ChunkLoader::TaskThreadEntry(void) { while(running_) { ChunkLoaderTask *task = nullptr; { std::lock_guard<std::mutex> lk(taskQueueMutex_); if(loaderTasks_.Size()) { task = loaderTasks_.Back(); loaderTasks_.PopBack(); } } if(task) { task->Run(this); Helper::SafeDeleteObjects(task); } else std::this_thread::sleep_for(std::chrono::milliseconds(2)); } } ChunkLoaderTask::ChunkLoaderTask(Chunk *ck) : ck_(ck) { assert(ck != nullptr); } void ChunkLoaderTask::Run(ChunkLoader *loader) { assert(loader != nullptr); std::vector<IntVector3> lightUpdates; loader->LoadChunkData(ck_); ChunkLoaderMessage *msg = new ChunkLoaderMessage; msg->type = ChunkLoaderMessage::ChunkLoaded; msg->ckLoaded = ck_; ck_ = nullptr; loader->AddMsg(msg); } ChunkLoaderTask::~ChunkLoaderTask(void) { Helper::SafeDeleteObjects(ck_); } namespace { inline bool OutOfBound(int x, int y, int z) { return (x | y | z | (3 * CHUNK_SECTION_SIZE - 1 - x) | (3 * CHUNK_SECTION_SIZE - 1 - z) | (CHUNK_MAX_HEIGHT - 1 - y)) < 0; } inline BlockLight GetLight(Chunk *(&cks)[3][3], int x, int y, int z) { if(OutOfBound(x, y, z)) return LIGHT_ALL_MAX; return cks[x / CHUNK_SECTION_SIZE][z / CHUNK_SECTION_SIZE] ->GetBlockLight(x % CHUNK_SECTION_SIZE, y, z % CHUNK_SECTION_SIZE); } inline int GetHeight(Chunk *(&cks)[3][3], int x, int z) { if(OutOfBound(x, 0, z)) return 0; return cks[x / CHUNK_SECTION_SIZE][z / CHUNK_SECTION_SIZE] ->GetHeight(x % CHUNK_SECTION_SIZE, z % CHUNK_SECTION_SIZE); } inline BlockType GetType(Chunk *(&cks)[3][3], int x, int y, int z) { if(OutOfBound(x, y, z)) return BlockType::Air; return cks[x / CHUNK_SECTION_SIZE][z / CHUNK_SECTION_SIZE] ->GetBlockType(x % CHUNK_SECTION_SIZE, y, z % CHUNK_SECTION_SIZE); } inline void SetLight(Chunk *(&cks)[3][3], int x, int y, int z, BlockLight light) { if(OutOfBound(x, y, z)) return; cks[x / CHUNK_SECTION_SIZE][z / CHUNK_SECTION_SIZE] ->SetBlockLight(x % CHUNK_SECTION_SIZE, y, z % CHUNK_SECTION_SIZE, light); } void LightProg(Chunk *(&cks)[3][3]) { BlockInfoManager &infoMgr = BlockInfoManager::GetInstance(); std::deque<IntVector3> progQueue; auto DirectionalUpdate = [&](BlockLight cenLight, int ax, int ay, int az) -> void { BlockLight nX = GetLight(cks, ax, ay, az); BlockLight newNX = BlockLightMax(nX, BlockLightMinus( cenLight, infoMgr.GetBlockInfo(GetType(cks, ax, ay, az)).lightDec)); if(newNX != nX) { SetLight(cks, ax, ay, az, newNX); if(!OutOfBound(ax, ay, az)) progQueue.push_back({ ax, ay, az }); } }; auto TryAsSource = [&](int x, int y, int z) { if(!OutOfBound(x, y, z) && GetLight(cks, x, y, z) != LIGHT_ALL_MIN) { progQueue.push_back({ x, y, z }); while(progQueue.size()) { auto [x, y, z] = progQueue.front(); progQueue.pop_front(); BlockLight cenLight = GetLight(cks, x, y, z); DirectionalUpdate(cenLight, x - 1, y, z); DirectionalUpdate(cenLight, x + 1, y, z); DirectionalUpdate(cenLight, x, y - 1, z); DirectionalUpdate(cenLight, x, y + 1, z); DirectionalUpdate(cenLight, x, y, z - 1); DirectionalUpdate(cenLight, x, y, z + 1); } } }; for(int x = 0; x < 3 * CHUNK_SECTION_SIZE; ++x) { for(int z = 0; z < 3 * CHUNK_SECTION_SIZE; ++z) { int H = GetHeight(cks, x, z); for(int y = 0; y <= H; ++y) { if(infoMgr.GetBlockInfo(GetType(cks, x, y, z)).lightDec < LIGHT_COMPONENT_MAX) { TryAsSource(x - 1, y, z); TryAsSource(x + 1, y, z); TryAsSource(x, y - 1, z); TryAsSource(x, y + 1, z); TryAsSource(x, y, z - 1); TryAsSource(x, y, z + 1); } } } } } } void ChunkLoader::LoadChunkData(Chunk *ck) { IntVectorXZ ckPos = ck->GetPosition(); Chunk *neis = new Chunk[8] { { ck->GetChunkManager(), { ckPos.x - 1, ckPos.z } }, { ck->GetChunkManager(), { ckPos.x + 1, ckPos.z } }, { ck->GetChunkManager(), { ckPos.x, ckPos.z - 1 } }, { ck->GetChunkManager(), { ckPos.x, ckPos.z + 1 } }, { ck->GetChunkManager(), { ckPos.x - 1, ckPos.z - 1 } }, { ck->GetChunkManager(), { ckPos.x - 1, ckPos.z + 1 } }, { ck->GetChunkManager(), { ckPos.x + 1, ckPos.z - 1 } }, { ck->GetChunkManager(), { ckPos.x + 1, ckPos.z + 1 } }, }; for(int i = 0; i != 8; ++i) { Chunk &dst = neis[i]; if(!ckPool_.GetChunk(dst)) { landGen_->GenerateLand(&dst); Chunk *addedCk = new Chunk(dst.GetChunkManager(), dst.GetPosition()); CopyChunkData(*addedCk, dst); ckPool_.AddChunk(addedCk); } } if(!ckPool_.GetChunk(*ck)) { landGen_->GenerateLand(ck); Chunk *addedCk = new Chunk(ck->GetChunkManager(), ck->GetPosition()); CopyChunkData(*addedCk, *ck); ckPool_.AddChunk(addedCk); } Chunk *cks[3][3] = { { neis + 4, neis + 0, neis + 5 }, { neis + 2, ck, neis + 3 }, { neis + 6, neis + 1, neis + 7 } }; LightProg(cks); for(int section = 0; section != CHUNK_SECTION_NUM; ++section) ck->SetModels(section, BackgroundChunkModelBuilder().Build(cks, section)); delete[] neis; } void ChunkLoader::TryAddLoadingTask(ChunkManager *ckMgr, int x, int z) { assert(ckMgr != nullptr); std::lock_guard<std::mutex> lk(taskQueueMutex_); ChunkLoaderTask *oldTask = nullptr; if(!loaderTasks_.Exists({ x, z })) { loaderTasks_.PushFront( IntVectorXZ{ x, z }, new ChunkLoaderTask(new Chunk(ckMgr, { x, z }))); } }
#include <algorithm> #include <cassert> #include <Utility\HelperFunctions.h> #include <World\Land\V0\LandGenerator_V0.h> #include <World\Land\V1\LandGenerator_V1.h> #include <World\Land\V2\LandGenerator_V2.h> #include <World\Land\V3\LandGenerator_V3.h> #include "ChunkLoader.h" #include "ChunkManager.h" #include "ChunkModelBuilder.h" ChunkLoader::ChunkLoader(size_t ckPoolSize) : ckPool_(ckPoolSize), landGen_(std::make_unique<LandGenerator_V0::LandGenerator>(4792539)) { } ChunkLoader::~ChunkLoader(void) { Destroy(); } void ChunkLoader::Initialize(int threadNum) { assert(threads_.empty()); if(threadNum <= 0) threadNum = (std::max)(4u, std::thread::hardware_concurrency()) - 2; running_ = true; while(threadNum-- > 0) threads_.emplace_back(&ChunkLoader::TaskThreadEntry, this); } void ChunkLoader::Destroy(void) { running_ = false; for(std::thread &th : threads_) { if(th.joinable()) th.join(); } threads_.clear(); loaderTasks_.ForEach([](ChunkLoaderTask *t) { Helper::SafeDeleteObjects(t); }); loaderTasks_.Clear(); ckPool_.Destroy(); } void ChunkLoader::AddTask(ChunkLoaderTask *task) { assert(task != nullptr); std::lock_guard<std::mutex> lk(taskQueueMutex_); loaderTasks_.PushFront(task->GetPosition(), task); } void ChunkLoader::AddMsg(ChunkLoaderMessage *msg) { assert(msg != nullptr); std::lock_guard<std::mutex> lk(msgQueueMutex_); loaderMsgs_.push(msg); } ChunkLoaderMessage *ChunkLoader::FetchMsg(void) { std::lock_guard<std::mutex> lk(msgQueueMutex_); if(loaderMsgs_.empty()) return nullptr; ChunkLoaderMessage *rt = loaderMsgs_.front(); loaderMsgs_.pop(); return rt; } std::queue<ChunkLoaderMessage*> ChunkLoader::FetchAllMsgs(void) { std::lock_guard<std::mutex> lk(msgQueueMutex_); return std::move(loaderMsgs_); } void ChunkLoade
{ if(infoMgr.GetBlockInfo(GetType(cks, x, y, z)).lightDec < LIGHT_COMPONENT_MAX) { TryAsSource(x - 1, y, z); TryAsSource(x + 1, y, z); TryAsSource(x, y - 1, z); TryAsSource(x, y + 1, z); TryAsSource(x, y, z - 1); TryAsSource(x, y, z + 1); } } } } } } void ChunkLoader::LoadChunkData(Chunk *ck) { IntVectorXZ ckPos = ck->GetPosition(); Chunk *neis = new Chunk[8] { { ck->GetChunkManager(), { ckPos.x - 1, ckPos.z } }, { ck->GetChunkManager(), { ckPos.x + 1, ckPos.z } }, { ck->GetChunkManager(), { ckPos.x, ckPos.z - 1 } }, { ck->GetChunkManager(), { ckPos.x, ckPos.z + 1 } }, { ck->GetChunkManager(), { ckPos.x - 1, ckPos.z - 1 } }, { ck->GetChunkManager(), { ckPos.x - 1, ckPos.z + 1 } }, { ck->GetChunkManager(), { ckPos.x + 1, ckPos.z - 1 } }, { ck->GetChunkManager(), { ckPos.x + 1, ckPos.z + 1 } }, }; for(int i = 0; i != 8; ++i) { Chunk &dst = neis[i]; if(!ckPool_.GetChunk(dst)) { landGen_->GenerateLand(&dst); Chunk *addedCk = new Chunk(dst.GetChunkManager(), dst.GetPosition()); CopyChunkData(*addedCk, dst); ckPool_.AddChunk(addedCk); } } if(!ckPool_.GetChunk(*ck)) { landGen_->GenerateLand(ck); Chunk *addedCk = new Chunk(ck->GetChunkManager(), ck->GetPosition()); CopyChunkData(*addedCk, *ck); ckPool_.AddChunk(addedCk); } Chunk *cks[3][3] = { { neis + 4, neis + 0, neis + 5 }, { neis + 2, ck, neis + 3 }, { neis + 6, neis + 1, neis + 7 } }; LightProg(cks); for(int section = 0; section != CHUNK_SECTION_NUM; ++section) ck->SetModels(section, BackgroundChunkModelBuilder().Build(cks, section)); delete[] neis; } void ChunkLoader::TryAddLoadingTask(ChunkManager *ckMgr, int x, int z) { assert(ckMgr != nullptr); std::lock_guard<std::mutex> lk(taskQueueMutex_); ChunkLoaderTask *oldTask = nullptr; if(!loaderTasks_.Exists({ x, z })) { loaderTasks_.PushFront( IntVectorXZ{ x, z }, new ChunkLoaderTask(new Chunk(ckMgr, { x, z }))); } }
r::TaskThreadEntry(void) { while(running_) { ChunkLoaderTask *task = nullptr; { std::lock_guard<std::mutex> lk(taskQueueMutex_); if(loaderTasks_.Size()) { task = loaderTasks_.Back(); loaderTasks_.PopBack(); } } if(task) { task->Run(this); Helper::SafeDeleteObjects(task); } else std::this_thread::sleep_for(std::chrono::milliseconds(2)); } } ChunkLoaderTask::ChunkLoaderTask(Chunk *ck) : ck_(ck) { assert(ck != nullptr); } void ChunkLoaderTask::Run(ChunkLoader *loader) { assert(loader != nullptr); std::vector<IntVector3> lightUpdates; loader->LoadChunkData(ck_); ChunkLoaderMessage *msg = new ChunkLoaderMessage; msg->type = ChunkLoaderMessage::ChunkLoaded; msg->ckLoaded = ck_; ck_ = nullptr; loader->AddMsg(msg); } ChunkLoaderTask::~ChunkLoaderTask(void) { Helper::SafeDeleteObjects(ck_); } namespace { inline bool OutOfBound(int x, int y, int z) { return (x | y | z | (3 * CHUNK_SECTION_SIZE - 1 - x) | (3 * CHUNK_SECTION_SIZE - 1 - z) | (CHUNK_MAX_HEIGHT - 1 - y)) < 0; } inline BlockLight GetLight(Chunk *(&cks)[3][3], int x, int y, int z) { if(OutOfBound(x, y, z)) return LIGHT_ALL_MAX; return cks[x / CHUNK_SECTION_SIZE][z / CHUNK_SECTION_SIZE] ->GetBlockLight(x % CHUNK_SECTION_SIZE, y, z % CHUNK_SECTION_SIZE); } inline int GetHeight(Chunk *(&cks)[3][3], int x, int z) { if(OutOfBound(x, 0, z)) return 0; return cks[x / CHUNK_SECTION_SIZE][z / CHUNK_SECTION_SIZE] ->GetHeight(x % CHUNK_SECTION_SIZE, z % CHUNK_SECTION_SIZE); } inline BlockType GetType(Chunk *(&cks)[3][3], int x, int y, int z) { if(OutOfBound(x, y, z)) return BlockType::Air; return cks[x / CHUNK_SECTION_SIZE][z / CHUNK_SECTION_SIZE] ->GetBlockType(x % CHUNK_SECTION_SIZE, y, z % CHUNK_SECTION_SIZE); } inline void SetLight(Chunk *(&cks)[3][3], int x, int y, int z, BlockLight light) { if(OutOfBound(x, y, z)) return; cks[x / CHUNK_SECTION_SIZE][z / CHUNK_SECTION_SIZE] ->SetBlockLight(x % CHUNK_SECTION_SIZE, y, z % CHUNK_SECTION_SIZE, light); } void LightProg(Chunk *(&cks)[3][3]) { BlockInfoManager &infoMgr = BlockInfoManager::GetInstance(); std::deque<IntVector3> progQueue; auto DirectionalUpdate = [&](BlockLight cenLight, int ax, int ay, int az) -> void { BlockLight nX = GetLight(cks, ax, ay, az); BlockLight newNX = BlockLightMax(nX, BlockLightMinus( cenLight, infoMgr.GetBlockInfo(GetType(cks, ax, ay, az)).lightDec)); if(newNX != nX) { SetLight(cks, ax, ay, az, newNX); if(!OutOfBound(ax, ay, az)) progQueue.push_back({ ax, ay, az }); } }; auto TryAsSource = [&](int x, int y, int z) { if(!OutOfBound(x, y, z) && GetLight(cks, x, y, z) != LIGHT_ALL_MIN) { progQueue.push_back({ x, y, z }); while(progQueue.size()) { auto [x, y, z] = progQueue.front(); progQueue.pop_front(); BlockLight cenLight = GetLight(cks, x, y, z); DirectionalUpdate(cenLight, x - 1, y, z); DirectionalUpdate(cenLight, x + 1, y, z); DirectionalUpdate(cenLight, x, y - 1, z); DirectionalUpdate(cenLight, x, y + 1, z); DirectionalUpdate(cenLight, x, y, z - 1); DirectionalUpdate(cenLight, x, y, z + 1); } } }; for(int x = 0; x < 3 * CHUNK_SECTION_SIZE; ++x) { for(int z = 0; z < 3 * CHUNK_SECTION_SIZE; ++z) { int H = GetHeight(cks, x, z); for(int y = 0; y <= H; ++y)
random
[ { "content": "class BasicBufferSetter<true> : public BasicBufferView\n\n{\n\npublic:\n\n bool SetData(const void *data, int byteSize)\n\n {\n\n assert(data && byteSize > 0);\n\n\n\n D3D11_MAPPED_SUBRESOURCE rsc;\n\n HRESULT hr = Window::GetInstance().GetD3DDeviceContext()\n\n ->Map(buf_, 0, D3D11_MAP_WRITE_DISCARD, 0, &rsc);\n\n if(FAILED(hr))\n\n return false;\n\n\n\n std::memcpy(rsc.pData, data, byteSize);\n\n Window::GetInstance().GetD3DDeviceContext()\n\n ->Unmap(buf_, 0);\n\n return true;\n\n }\n\n};\n\n\n\ntemplate<>\n", "file_path": "Source/Components/WinFramework/D3DObject/BasicBuffer.h", "rank": 0, "score": 57176.0980323595 }, { "content": " class ConstantBufferObject<BufferType_, _StageSelector, true>\n\n : public ConstantBufferAttributes<BufferType_, _StageSelector, true>,\n\n public ConstantBufferObjectBase<_StageSelector>,\n\n public Uncopiable\n\n {\n\n public:\n\n void SetBufferData(ID3D11DeviceContext *devCon, const BufferType_ &data)\n\n {\n\n assert(devCon != nullptr && buf_ != nullptr);\n\n D3D11_MAPPED_SUBRESOURCE mappedRsc;\n\n devCon->Map(buf_, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedRsc);\n\n std::memcpy(mappedRsc.pData, &data, sizeof(BufferType_));\n\n devCon->Unmap(buf_, 0);\n\n }\n\n\n\n private:\n\n friend class ConstantBufferManager<_StageSelector>;\n\n\n\n ConstantBufferObject(void)\n\n : ConstantBufferObjectBase(0, nullptr)\n", "file_path": "Library/OWE/Src/OWEShader/OWEShaderConstantBuffer.h", "rank": 1, "score": 57176.0980323595 }, { "content": "", "file_path": "Source/VoxelWorld/World/Chunk/ChunkLoader.h", "rank": 2, "score": 44103.48510240957 }, { "content": "struct VMECmdMsg\n\n{\n\n Color color;\n\n std::string msg;\n\n\n\n static const Color ERROR_COLOR;\n\n static const Color NORMAL_COLOR;\n\n};\n\n\n\nusing VMECmdMsgQueue = std::queue<VMECmdMsg>;\n\n\n", "file_path": "Source/VoxelWorld/Application/VoxelModelEditorBak/VoxelModelEditorCommandWindow.h", "rank": 3, "score": 38404.21818430002 }, { "content": "", "file_path": "Source/VoxelWorld/World/World.cpp", "rank": 7, "score": 19.711699406668604 }, { "content": "", "file_path": "Source/Components/WinFramework/Window/Window.cpp", "rank": 9, "score": 19.309345241452707 }, { "content": "", "file_path": "Source/VoxelWorld/World/Actor/ActorModel.cpp", "rank": 10, "score": 18.832287901593926 }, { "content": "/*================================================================\n\nFilename: Texture2D.cpp\n\nDate: 2018.1.14\n\nCreated by AirGuanZ\n\n================================================================*/\n\n#include <cassert>\n\n#include <utility>\n\n\n\n#include <Utility\\HelperFunctions.h>\n\n\n\n#include <Window\\Window.h>\n\n#include \"Texture2D.h\"\n\n#include \"TextureFile.h\"\n\n\n\nTexture2D::Texture2D(void)\n\n : tex_(nullptr), SRV_(nullptr)\n\n{\n\n\n\n}\n\n\n", "file_path": "Source/Components/WinFramework/Texture/Texture2D.cpp", "rank": 11, "score": 18.795856732912256 }, { "content": "", "file_path": "Source/Components/WinFramework/Screen/GUISystem.cpp", "rank": 12, "score": 18.727367612401075 }, { "content": "", "file_path": "Source/Components/WinFramework/D3DObject/FrameBuffer.cpp", "rank": 13, "score": 18.38356497331864 }, { "content": "", "file_path": "Library/OWE/Src/OWEShader/OWEShaderStage.h", "rank": 14, "score": 18.29671654038274 }, { "content": "", "file_path": "Library/OWE/Src/OWEShader/OWEShaderStage.h", "rank": 15, "score": 18.296716540382736 }, { "content": "", "file_path": "Library/OWE/Src/OWEShader/OWEShaderStage.h", "rank": 16, "score": 18.29671654038274 }, { "content": "bool LiquidRenderer::Initialize(std::string &errMsg)\n\n{\n\n if(!basic_.Initialize(errMsg))\n\n return false;\n\n\n\n raster_ = std::make_unique<RasterState>(D3D11_FILL_SOLID, D3D11_CULL_NONE);\n\n blend_ = std::make_unique<BlendState>();\n\n depth_ = std::make_unique<DepthStencilState>(true, false);\n\n\n\n if(!raster_ || !blend_ || !depth_)\n\n {\n\n Destroy();\n\n return false;\n\n }\n\n\n\n return true;\n\n}\n\n\n\nvoid LiquidRenderer::Destroy(void)\n\n{\n", "file_path": "Source/VoxelWorld/World/Chunk/LiquidRenderer.cpp", "rank": 17, "score": 17.95935252806238 }, { "content": "{\n\n Destroy();\n\n}\n\n\n\nvoid ChunkDataPool::Destroy(void)\n\n{\n\n std::lock_guard<std::mutex> lk(mapMutex_);\n\n map_.ForEach([](Chunk *ck) { Helper::SafeDeleteObjects(ck); });\n\n map_.Clear();\n\n}\n\n\n\nbool ChunkDataPool::GetChunk(Chunk &ck)\n\n{\n\n IntVectorXZ pos = ck.GetPosition();\n\n std::lock_guard<std::mutex> lk(mapMutex_);\n\n Chunk *rt = nullptr;\n\n if(map_.FindAndErase({ pos.x, pos.z }, rt))\n\n {\n\n assert(rt != nullptr);\n\n\n", "file_path": "Source/VoxelWorld/World/Chunk/ChunkDataPool.cpp", "rank": 18, "score": 17.732728312431867 }, { "content": " assert(byteCode != nullptr && length > 0);\n\n assert(Window::GetInstance().IsD3DAvailable());\n\n\n\n ID3D11InputLayout *rt = nullptr;\n\n HRESULT hr = Window::GetInstance().GetD3DDevice()->CreateInputLayout(\n\n desc, static_cast<UINT>(num), byteCode, static_cast<SIZE_T>(length), &rt);\n\n return FAILED(hr) ? nullptr : rt;\n\n }\n\n}\n\n\n\nBasicRenderer::BasicRenderer(void)\n\n : inputLayout_(nullptr)\n\n{\n\n\n\n}\n\n\n\nBasicRenderer::~BasicRenderer(void)\n\n{\n\n Destroy();\n\n}\n", "file_path": "Source/VoxelWorld/World/Chunk/BasicRenderer.cpp", "rank": 19, "score": 17.613000026026015 }, { "content": "", "file_path": "Source/Components/SkeletonAnimation/SkeletonData.cpp", "rank": 20, "score": 17.38980933233488 }, { "content": "", "file_path": "Source/Components/WinFramework/Window/Window.cpp", "rank": 21, "score": 17.233813754884896 }, { "content": " errMsg = \"Bone \" + modelBindings[i] + \" not found\";\n\n Clear();\n\n return false;\n\n }\n\n modelToBone_[i] = it->second;\n\n }\n\n\n\n return true;\n\n}\n\n\n\nvoid VoxelModelAnimationDisplayer::Clear(void)\n\n{\n\n models_.clear();\n\n modelToBone_.clear();\n\n skeleton_ = nullptr;\n\n\n\n curAniName_ = \"\";\n\n curAni_ = nullptr;\n\n aniTime_ = 0.0f;\n\n aniLoop_ = false;\n", "file_path": "Source/VoxelWorld/VoxelModel/VoxelModelAnimationDisplayer.cpp", "rank": 22, "score": 16.971324559927794 }, { "content": " return true;\n\n}\n\n\n\nvoid ImmediateScreen2D::Destroy(void)\n\n{\n\n norShader_.Destroy();\n\n norUniforms_.reset();\n\n quadVtxBuf_.Destroy();\n\n}\n\n\n\nbool ImmediateScreen2D::IsAvailable(void) const\n\n{\n\n return norShader_.IsAllStagesAvailable();\n\n}\n\n\n\nvoid ImmediateScreen2D::DrawRectangle(const Vector2 &LB, const Vector2 &RT, Texture2D tex)\n\n{\n\n ID3D11Device *dev = Window::GetInstance().GetD3DDevice();\n\n ID3D11DeviceContext *DC = Window::GetInstance().GetD3DDeviceContext();\n\n\n", "file_path": "Source/Components/WinFramework/Screen/ImmediateScreen2D.cpp", "rank": 23, "score": 16.30861114474451 }, { "content": " {\n\n Destroy();\n\n return false;\n\n }\n\n\n\n return true;\n\n}\n\n\n\nvoid BasicRenderer::Destroy(void)\n\n{\n\n Helper::ReleaseCOMObjects(inputLayout_);\n\n shader_.Destroy();\n\n}\n\n\n\nbool BasicRenderer::IsAvailable(void) const\n\n{\n\n return inputLayout_ && shader_.IsAllStagesAvailable();\n\n}\n\n\n\nvoid BasicRenderer::Begin(void)\n", "file_path": "Source/VoxelWorld/World/Chunk/BasicRenderer.cpp", "rank": 24, "score": 15.703950689856628 }, { "content": "/*================================================================\n\nFilename: VoxelModelAnimationDisplayer.cpp\n\nDate: 2018.3.3\n\nCreated by AirGuanZ\n\n================================================================*/\n\n#include <cassert>\n\n#include <string>\n\n\n\n#include <Utility\\FileSystem.h>\n\n#include <Utility\\HelperFunctions.h>\n\n\n\n#include <Resource\\ResourceNameManager.h>\n\n#include <Window\\Window.h>\n\n#include \"VoxelModelAnimationDisplayer.h\"\n\n\n\nVoxelModelAnimationDisplayer::VoxelModelAnimationDisplayer(void)\n\n{\n\n curAni_ = nullptr;\n\n aniTime_ = 0.0f;\n\n aniLoop_ = false;\n", "file_path": "Source/VoxelWorld/VoxelModel/VoxelModelAnimationDisplayer.cpp", "rank": 25, "score": 15.680306771537236 }, { "content": "", "file_path": "Source/VoxelWorld/Application/VoxelModelEditorBak/VoxelModelEditorCommandWindow.cpp", "rank": 26, "score": 15.455315034562929 }, { "content": "/*================================================================\n\nFilename: Application/Common.cpp\n\nDate: 2018.2.27\n\nCreated by AirGuanZ\n\n================================================================*/\n\n#include <Window\\Window.h>\n\n\n\n#include \"Common.h\"\n\n\n\nvoid ShowErrMsgBox(const std::string &errMsg)\n\n{\n\n Window::GetInstance().ErrMsgBox(errMsg);\n\n}\n", "file_path": "Source/VoxelWorld/Application/Common.cpp", "rank": 27, "score": 14.99715948690695 }, { "content": " return TextureFile::GetInstance().LoadTexture2D(filename, tex_, SRV_);\n\n}\n\n\n\nvoid Texture2D::Destroy(void)\n\n{\n\n Helper::ReleaseCOMObjects(tex_, SRV_);\n\n}\n\n\n\nbool Texture2D::IsAvailable(void) const\n\n{\n\n assert((tex_ != nullptr) == (SRV_ != nullptr));\n\n return tex_ != nullptr;\n\n}\n", "file_path": "Source/Components/WinFramework/Texture/Texture2D.cpp", "rank": 28, "score": 14.986061980504285 }, { "content": " CopyChunkData(ck, *rt);\n\n\n\n map_.PushFront(pos, rt);\n\n return true;\n\n }\n\n return false;\n\n}\n\n\n\nvoid ChunkDataPool::AddChunk(Chunk *ck)\n\n{\n\n assert(ck != nullptr);\n\n IntVectorXZ pos = ck->GetPosition();\n\n std::lock_guard<std::mutex> lk(mapMutex_);\n\n\n\n Chunk *existed = nullptr;\n\n if(map_.FindAndErase(pos, existed))\n\n {\n\n map_.PushFront(pos, ck);\n\n Helper::SafeDeleteObjects(existed);\n\n return;\n", "file_path": "Source/VoxelWorld/World/Chunk/ChunkDataPool.cpp", "rank": 29, "score": 14.812046147538268 }, { "content": " return false;\n\n }\n\n\n\n raster_ = std::make_unique<RasterState>(D3D11_FILL_SOLID, D3D11_CULL_NONE);\n\n\n\n return true;\n\n}\n\n\n\nvoid CarveRenderer::Destroy(void)\n\n{\n\n inputLayout_.Destroy();\n\n shader_.Destroy();\n\n raster_.reset();\n\n}\n\n\n\nbool CarveRenderer::IsAvailable(void) const\n\n{\n\n return inputLayout_.IsAvailable();\n\n}\n\n\n", "file_path": "Source/VoxelWorld/World/Chunk/CarveRenderer.cpp", "rank": 30, "score": 14.74683268757731 }, { "content": " return true;\n\n}\n\n\n\nbool VoxelModel::Initialize(const std::vector<VoxelModelVertex> &vtx, const std::vector<UINT16> &idx)\n\n{\n\n Destroy();\n\n if(!vtxBuf_.Initialize(vtx.data(), sizeof(Vertex) * vtx.size()) ||\n\n !idxBuf_.Initialize(idx.data(), sizeof(UINT16) * idx.size()))\n\n {\n\n Destroy();\n\n return false;\n\n }\n\n idxCount_ = idx.size();\n\n return true;\n\n}\n\n\n\nvoid VoxelModel::Destroy(void)\n\n{\n\n vtxBuf_.Destroy();\n\n idxBuf_.Destroy();\n", "file_path": "Source/VoxelWorld/VoxelModel/VoxelModel.cpp", "rank": 31, "score": 14.67786667214256 }, { "content": "/*================================================================\n\nFilename: TransparentRenderer.cpp\n\nDate: 2018.1.27\n\nCreated by AirGuanZ\n\n================================================================*/\n\n#include <Utility\\HelperFunctions.h>\n\n\n\n#include <Resource\\ResourceNameManager.h>\n\n#include \"LiquidRenderer.h\"\n\n\n\nLiquidRenderer::LiquidRenderer(void)\n\n{\n\n\n\n}\n\n\n\nLiquidRenderer::~LiquidRenderer(void)\n\n{\n\n Destroy();\n\n}\n\n\n", "file_path": "Source/VoxelWorld/World/Chunk/LiquidRenderer.cpp", "rank": 32, "score": 14.475330454368807 }, { "content": "/*================================================================\n\nFilename: CarveRenderer.cpp\n\nDate: 2018.1.22\n\nCreated by AirGuanZ\n\n================================================================*/\n\n#include <Utility\\FileSystem.h>\n\n#include <Utility\\HelperFunctions.h>\n\n\n\n#include <Resource\\ResourceNameManager.h>\n\n#include \"CarveRenderer.h\"\n\n\n\nCarveRenderer::CarveRenderer(void)\n\n{\n\n\n\n}\n\n\n\nCarveRenderer::~CarveRenderer(void)\n\n{\n\n Destroy();\n\n}\n", "file_path": "Source/VoxelWorld/World/Chunk/CarveRenderer.cpp", "rank": 33, "score": 14.456092382053328 }, { "content": "/*================================================================\n\nFilename: V1/LandGenerator.cpp\n\nDate: 2018.1.30\n\nCreated by AirGuanZ\n\n================================================================*/\n\n#include <cassert>\n\n#include <cstdlib>\n\n\n\n#include \"..\\V0\\OakGenerator_V0.h\"\n\n#include \"Biome_V1.h\"\n\n#include \"LandGenerator_V1.h\"\n\n#include \"PalmGenerator_V1.h\"\n\n\n\nvoid ::LandGenerator_V1::LandGenerator::GenerateLand(Chunk *ck)\n\n{\n\n assert(ck != nullptr);\n\n auto[ckX, ckZ] = ck->GetPosition();\n\n int xBase = ck->GetXPosBase();\n\n int zBase = ck->GetZPosBase();\n\n\n", "file_path": "Source/VoxelWorld/World/Land/V1/LandGenerator_V1.cpp", "rank": 34, "score": 14.44464118768655 }, { "content": "\n\n if(!vtxBuf_.Initialize(vtxData, vtxCnt) || !idxBuf_.Initialize(idxData, idxCnt))\n\n {\n\n Destroy();\n\n return false;\n\n }\n\n idxCnt_ = idxCnt;\n\n\n\n return true;\n\n }\n\n\n\n bool IsAvailable(void) const\n\n {\n\n assert(vtxBuf_.IsAvailable() == idxBuf_.IsAvailable());\n\n return vtxBuf_.IsAvailable();\n\n }\n\n\n\n void Destroy(void)\n\n {\n\n vtxBuf_.Destroy();\n", "file_path": "Source/Components/WinFramework/D3DObject/SingleBufferMesh.h", "rank": 35, "score": 14.297180290780382 }, { "content": "/*================================================================\n\nFilename: VoxelModelEditorView.cpp\n\nDate: 2018.3.14\n\nCreated by AirGuanZ\n\n================================================================*/\n\n#include <Utility\\FileSystem.h>\n\n\n\n#include <Screen\\GUISystem.h>\n\n#include <Window\\Window.h>\n\n#include \"VoxelModelEditorCommand.h\"\n\n#include \"VoxelModelEditorCore.h\"\n\n#include \"VoxelModelEditorView.h\"\n\n\n\nVMEView::VMEView(void)\n\n{\n\n showConsole_ = true;\n\n showBindingAttributes_ = true;\n\n showComponentView_ = true;\n\n}\n\n\n", "file_path": "Source/VoxelWorld/Application/VoxelModelEditor/VoxelModelEditorView.cpp", "rank": 36, "score": 14.230819300740928 }, { "content": "/*================================================================\n\nFilename: ChunkRendererManager.cpp\n\nDate: 2018.2.25\n\nCreated by AirGuanZ\n\n================================================================*/\n\n#include <Resource\\ResourceNameManager.h>\n\n#include <Window\\Window.h>\n\n\n\n#include \"ChunkRendererManager.h\"\n\n\n\nChunkRendererManager::ChunkRendererManager(void)\n\n : sampler_(D3DObj_Noinit())\n\n{\n\n DC_ = nullptr;\n\n\n\n basicUniform_Trans_ = nullptr;\n\n basicUniform_Sunlight_ = nullptr;\n\n basicUniform_Fog_ = nullptr;\n\n basicUniform_Tex_ = nullptr;\n\n\n", "file_path": "Source/VoxelWorld/Application/Game/ChunkRendererManager.cpp", "rank": 37, "score": 14.163359983402337 }, { "content": "", "file_path": "Source/Components/WinFramework/Screen/GUISystem.cpp", "rank": 39, "score": 13.879540726199254 }, { "content": "", "file_path": "Source/Components/WinFramework/Window/Window.cpp", "rank": 40, "score": 13.68593332829586 }, { "content": "/*================================================================\n\nFilename: V3/LandGenerator.cpp\n\nDate: 2018.4.16\n\nCreated by AirGuanZ\n\n================================================================*/\n\n#include <cassert>\n\n\n\n#include <World\\Land\\V3\\LandGenerator_V3.h>\n\n\n\nvoid ::LandGenerator_V3::LandGenerator::GenerateLand(Chunk *ck)\n\n{\n\n assert(ck != nullptr);\n\n\n\n for(int x = 0; x != CHUNK_SECTION_SIZE; ++x)\n\n {\n\n for(int z = 0; z != CHUNK_SECTION_SIZE; ++z)\n\n {\n\n for(int y = 0; y != 10; ++y)\n\n ck->SetBlockType(x, y, z, BlockType::Dirt);\n\n ck->SetBlockType(x, 10, z, BlockType::GrassBox);\n", "file_path": "Source/VoxelWorld/World/Land/V3/LandGenerator_V3.cpp", "rank": 41, "score": 13.541434991676716 }, { "content": "/*================================================================\n\nFilename: ConfigFile.cpp\n\nDate: 2018.1.17\n\nCreated by AirGuanZ\n\n================================================================*/\n\n#include <algorithm>\n\n#include <cassert>\n\n#include <cctype>\n\n#include <fstream>\n\n\n\n#include \"ConfigFile.h\"\n\n\n\nnamespace\n\n{\n\n const std::string EMPTY_STR;\n\n}\n\n\n\nconst std::string &ConfigFileSection::operator[](const std::string &key) const\n\n{\n\n auto it = data_.find(key);\n", "file_path": "Source/Components/Utility/ConfigFile.cpp", "rank": 42, "score": 13.521670774442512 }, { "content": "", "file_path": "Source/Components/WinFramework/Window/Window.cpp", "rank": 43, "score": 13.384907242519054 }, { "content": "", "file_path": "Source/VoxelWorld/World/Chunk/BasicModel.cpp", "rank": 44, "score": 13.358004687486403 }, { "content": "", "file_path": "Source/VoxelWorld/Application/VoxelModelEditor/VoxelModelEditorComponentView.cpp", "rank": 45, "score": 13.153433347284668 }, { "content": "", "file_path": "Source/VoxelWorld/World/Chunk/ChunkLoader.h", "rank": 46, "score": 13.129407433067543 }, { "content": " return *this;\n\n }\n\n\n\n ~InputLayout(void)\n\n {\n\n Helper::ReleaseCOMObjects(inputLayout_);\n\n }\n\n\n\n bool IsAvailable(void) const\n\n {\n\n return inputLayout_ != nullptr;\n\n }\n\n\n\n void Destroy(void)\n\n {\n\n Helper::ReleaseCOMObjects(inputLayout_);\n\n }\n\n\n\n template<int N>\n\n bool Initialize(const D3D11_INPUT_ELEMENT_DESC (&desc)[N], const void *byteCode, UINT length)\n", "file_path": "Source/Components/WinFramework/D3DObject/InputLayout.h", "rank": 47, "score": 12.963057497051055 }, { "content": "\n\n shader_.Destroy();\n\n uniforms_.reset();\n\n inputLayout_.Destroy();\n\n}\n\n\n\nvoid VoxelModelAnimationDisplayer::SetModel(size_t idx, VoxelModel *model)\n\n{\n\n assert(idx < models_.size() && model != nullptr);\n\n models_[idx] = model;\n\n}\n\n\n\nbool VoxelModelAnimationDisplayer::SetCurrentAnimation(const std::string &aniName, bool loop)\n\n{\n\n if(!(curAni_ = skeleton_->GetAniClip(aniName)))\n\n return false;\n\n aniLoop_ = loop;\n\n aniTime_ = 0.0f;\n\n curAniName_ = aniName;\n\n return true;\n", "file_path": "Source/VoxelWorld/VoxelModel/VoxelModelAnimationDisplayer.cpp", "rank": 48, "score": 12.926460781291683 }, { "content": "", "file_path": "Source/Components/WinFramework/Window/Window.cpp", "rank": 49, "score": 12.901217321979766 }, { "content": " carveUniform_Trans_ = nullptr;\n\n carveUniform_Sunlight_ = nullptr;\n\n carveUniform_Fog_ = nullptr;\n\n carveUniform_Tex_ = nullptr;\n\n\n\n liquidUniform_Trans_ = nullptr;\n\n liquidUniform_Sunlight_ = nullptr;\n\n liquidUniform_Fog_ = nullptr;\n\n liquidUniform_Tex_ = nullptr;\n\n}\n\n\n\nbool ChunkRendererManager::Initialize(std::string &errMsg)\n\n{\n\n RscNameMgr &rscMgr = RscNameMgr::GetInstance();\n\n DC_ = Window::GetInstance().GetD3DDeviceContext();\n\n ID3D11Device *dev = Window::GetInstance().GetD3DDevice();\n\n\n\n if(!basicRenderer_.Initialize(errMsg))\n\n {\n\n Destroy();\n", "file_path": "Source/VoxelWorld/Application/Game/ChunkRendererManager.cpp", "rank": 50, "score": 12.73045418904458 }, { "content": "\n\n core.needRefreshDisplay_ = true;\n\n}\n\n\n\nVMECmd_UnloadBinding::VMECmd_UnloadBinding(bool showMsg)\n\n{\n\n showMsg_ = showMsg;\n\n}\n\n\n\nvoid VMECmd_UnloadBinding::Execute(VoxelModelEditorCore &core, VMECmdMsgQueue &cmdMsgs)\n\n{\n\n if(core.model_)\n\n {\n\n if(showMsg_)\n\n {\n\n cmdMsgs.push({ VMECmdMsg::NORMAL_COLOR,\n\n \"Binding file unloaded: \" + ConstructBindingPath(core.model_->GetName()) });\n\n }\n\n core.model_.reset();\n\n core.needRefreshDisplay_ = true;\n", "file_path": "Source/VoxelWorld/Application/VoxelModelEditorBak/VoxelModelEditorCommand.cpp", "rank": 51, "score": 12.688514197841751 }, { "content": "/*================================================================\n\nFilename: VoxelModelEditor.cpp\n\nDate: 2018.3.5\n\nCreated by AirGuanZ\n\n================================================================*/\n\n#include <cassert>\n\n#include <filesystem>\n\n#include <map>\n\n\n\n#include <Utility/HelperFunctions.h>\n\n\n\n#include \"VoxelModelBinding.h\"\n\n#include \"VoxelModelEditor.h\"\n\n#include \"VoxelModelEditorCommand.h\"\n\n#include \"VoxelModelEditorCommandWindow.h\"\n\n\n\nVoxelModelEditor::VoxelModelEditor(void)\n\n : VoxelModelEditorCore(), display_(cmdQueue_)\n\n{\n\n\n", "file_path": "Source/VoxelWorld/Application/VoxelModelEditorBak/VoxelModelEditor.cpp", "rank": 52, "score": 12.63697522338802 }, { "content": "/*================================================================\n\nFilename: ChunkDataPool.cpp\n\nDate: 2018.1.29\n\nCreated by AirGuanZ\n\n================================================================*/\n\n#include <cassert>\n\n#include <cstring>\n\n#include <type_traits>\n\n\n\n#include <Utility\\HelperFunctions.h>\n\n\n\n#include \"ChunkDataPool.h\"\n\n\n\nChunkDataPool::ChunkDataPool(size_t maxDataCnt)\n\n : maxDataCnt_(maxDataCnt)\n\n{\n\n\n\n}\n\n\n\nChunkDataPool::~ChunkDataPool(void)\n", "file_path": "Source/VoxelWorld/World/Chunk/ChunkDataPool.cpp", "rank": 53, "score": 12.569826036215392 }, { "content": " for(size_t i = 0; i < conf.fonts.size(); ++i)\n\n {\n\n conf.fonts[i].ttfFilename = rM.AsString(\"ImFont\", \"TTFName[\" + std::to_string(i) + \"]\");\n\n conf.fonts[i].pixelSize = std::stof(rM.AsString(\"ImFont\", \"PixelSize[\" + std::to_string(i) + \"]\"));\n\n }\n\n }\n\n catch(const std::exception&)\n\n {\n\n return false;\n\n }\n\n\n\n return true;\n\n }\n\n}\n\n\n\nvoid Application::Run(void)\n\n{\n\n std::string errMsg;\n\n if(!Initialize(errMsg))\n\n {\n", "file_path": "Source/VoxelWorld/Application/Application.cpp", "rank": 54, "score": 12.544589766212175 }, { "content": "/*================================================================\n\nFilename: ImmediateScreen2D.cpp\n\nDate: 2018.1.23\n\nCreated by AirGuanZ\n\n================================================================*/\n\n#include <cassert>\n\n#include <string>\n\n\n\n#include <Utility\\FileSystem.h>\n\n#include <Utility\\HelperFunctions.h>\n\n\n\n#include <Resource\\ResourceNameManager.h>\n\n#include <Window\\Window.h>\n\n#include \"ImmediateScreen2D.h\"\n\n\n\nImmediateScreen2D::ImmediateScreen2D(void)\n\n : norDepthStencilState_(D3DObj_Noinit()),\n\n norSampler_(D3DObj_Noinit())\n\n{\n\n\n", "file_path": "Source/Components/WinFramework/Screen/ImmediateScreen2D.cpp", "rank": 55, "score": 12.505583123965625 }, { "content": "/*================================================================\n\nFilename: Crosshair.cpp\n\nDate: 2018.1.23\n\nCreated by AirGuanZ\n\n================================================================*/\n\n#include <Resource\\ResourceNameManager.h>\n\n#include <Window\\Window.h>\n\n#include \"Crosshair.h\"\n\n\n\nbool Crosshair::Initialize(void)\n\n{\n\n if(!tex_.IsAvailable())\n\n return tex_.LoadFromFile(RscNameMgr::GetInstance()(\"Crosshair\", \"Texture\"));\n\n return true;\n\n}\n\n\n\nvoid Crosshair::Draw(ImmediateScreen2D *imScr2D)\n\n{\n\n assert(imScr2D != nullptr);\n\n Window &win = Window::GetInstance();\n\n\n\n constexpr float CROSSHAIR_PIXEL_SIZE = 35.0f;\n\n float XSize = 0.5f * CROSSHAIR_PIXEL_SIZE / win.GetClientWidth();\n\n float YSize = 0.5f * CROSSHAIR_PIXEL_SIZE / win.GetClientHeight();\n\n\n\n imScr2D->DrawRectangle({ -XSize, -YSize }, { XSize, YSize }, tex_);\n\n}\n", "file_path": "Source/VoxelWorld/Application/Game/Crosshair.cpp", "rank": 56, "score": 12.48295041538595 }, { "content": " ResultType *rtObj = new ResultType;\n\n if(!rtObj->Initialize(dev, rec.slot, data))\n\n {\n\n delete rtObj;\n\n#ifdef OWE_NO_EXCEPTION\n\n return nullptr;\n\n#else\n\n throw OWEShaderError(\"Failed to initialize constant buffer object: \" + name);\n\n#endif\n\n }\n\n rec.obj = rtObj;\n\n return rtObj;\n\n }\n\n\n\n void Bind(ID3D11DeviceContext *DC)\n\n {\n\n for(auto it : CBs_)\n\n {\n\n if(it.second.obj)\n\n it.second.obj->Bind(DC);\n", "file_path": "Library/OWE/Src/OWEShader/OWEShaderConstantBuffer.h", "rank": 57, "score": 12.381108995255794 }, { "content": "/*================================================================\n\nFilename: BasicRenderer.cpp\n\nDate: 2018.1.13\n\nCreated by AirGuanZ\n\n================================================================*/\n\n#include <vector>\n\n\n\n#include <Utility\\FileSystem.h>\n\n#include <Utility\\HelperFunctions.h>\n\n\n\n#include <Resource\\ResourceNameManager.h>\n\n#include <Window\\Window.h>\n\n#include \"BasicRenderer.h\"\n\n\n\nnamespace\n\n{\n\n ID3D11InputLayout *CreateInputLayout(const D3D11_INPUT_ELEMENT_DESC *desc,\n\n int num, const void *byteCode, size_t length)\n\n {\n\n assert(desc != nullptr && num > 0);\n", "file_path": "Source/VoxelWorld/World/Chunk/BasicRenderer.cpp", "rank": 59, "score": 12.247592307495701 }, { "content": "/*================================================================\n\nFilename: VoxelModel.cpp\n\nDate: 2018.3.3\n\nCreated by AirGuanZ\n\n================================================================*/\n\n#define _CRT_SECURE_NO_WARNINGS\n\n\n\n#include <cassert>\n\n#include <cstdio>\n\n#include <fstream>\n\n\n\n#include <Utility\\HelperFunctions.h>\n\n\n\n#include \"VoxelModel.h\"\n\n\n\nInputLayout VoxelModel::CreateInputLayout(const void *shaderByteCode, UINT length)\n\n{\n\n static const D3D11_INPUT_ELEMENT_DESC desc[] =\n\n {\n\n { \"POSITION\", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0,\n", "file_path": "Source/VoxelWorld/VoxelModel/VoxelModel.cpp", "rank": 60, "score": 12.11911049470179 }, { "content": " {\n\n\n\n }\n\n\n\n bool Initialize(ID3D11Device *dev, UINT slot, const BufferType_ *data = nullptr)\n\n {\n\n assert(dev);\n\n slot_ = slot;\n\n if(data)\n\n {\n\n D3D11_SUBRESOURCE_DATA dataDesc = { &data, 0, 0 };\n\n buf_ = GenConstantBuffer(dev, sizeof(BufferType_), true, &dataDesc);\n\n }\n\n else\n\n buf_ = GenConstantBuffer(dev, sizeof(BufferType_), true, nullptr);\n\n return buf_ != nullptr;\n\n }\n\n\n\n ~ConstantBufferObject(void)\n\n {\n\n ReleaseCOMObjects(buf_);\n\n }\n\n };\n\n\n\n template<ShaderStageSelector StageSelector>\n", "file_path": "Library/OWE/Src/OWEShader/OWEShaderConstantBuffer.h", "rank": 61, "score": 12.089360772958445 }, { "content": "", "file_path": "Source/VoxelWorld/World/Chunk/BasicModel.cpp", "rank": 63, "score": 11.892766875024646 }, { "content": "/*================================================================\n\nFilename: HelperFunctions.cpp\n\nDate: 2018.1.13\n\nCreated by AirGuanZ\n\n================================================================*/\n\n#include <fstream>\n\n#include <iterator>\n\n#include <string>\n\n#include <vector>\n\n\n\n#include <Windows.h>\n\n\n\n#include \"D3D11Header.h\"\n\n#include \"HelperFunctions.h\"\n\n\n\nstd::string Helper::ToStr(const std::wstring &wstr)\n\n{\n\n int size = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, nullptr, 0, nullptr, nullptr);\n\n char *chs = new char[size];\n\n WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, chs, size, nullptr, nullptr);\n", "file_path": "Source/Components/Utility/HelperFunctions.cpp", "rank": 64, "score": 11.857366367517463 }, { "content": "/*================================================================\n\nFilename: OWEShaderUniforms.h\n\nDate: 2017.12.18\n\nCreated by AirGuanZ\n\n================================================================*/\n\n#ifndef OWESHADER_UNIFORMS_H\n\n#define OWESHADER_UNIFORMS_H\n\n\n\n#include <cassert>\n\n\n\n#include \"OWEShaderStage.h\"\n\n\n\nnamespace OWEShaderAux\n\n{\n\n struct ShaderStageUniformsBinder\n\n {\n\n template<typename T>\n\n void operator()(T &ref)\n\n {\n\n ref.Bind(DC);\n", "file_path": "Library/OWE/Src/OWEShader/OWEShaderUniforms.h", "rank": 65, "score": 11.736644264666797 }, { "content": "", "file_path": "Source/VoxelWorld/World/Land/V0/LandGenerator_V0.cpp", "rank": 66, "score": 11.684802860979296 }, { "content": " return true;\n\n }\n\n\n\n SSObj *GetShaderSamplerObject(const std::string &name)\n\n {\n\n auto it = SSs_.find(name);\n\n if(it == SSs_.end())\n\n {\n\n#ifdef OWE_NO_EXCEPTION\n\n return nullptr;\n\n#else\n\n throw OWEShaderError((\"Shader sampler not found: \" + name).c_str());\n\n#endif\n\n }\n\n\n\n assert(it->second.obj != nullptr);\n\n return it->second.obj;\n\n }\n\n\n\n void Bind(ID3D11DeviceContext *DC)\n", "file_path": "Library/OWE/Src/OWEShader/OWEShaderSampler.h", "rank": 67, "score": 11.675519359789124 }, { "content": "", "file_path": "Source/VoxelWorld/World/Chunk/BasicModel.cpp", "rank": 68, "score": 11.631073194123498 }, { "content": "/*================================================================\n\nFilename: VoxelModelEditorCommand.cpp\n\nDate: 2018.3.14\n\nCreated by AirGuanZ\n\n================================================================*/\n\n#include <cassert>\n\n\n\n#include <Utility\\FileSystem.h>\n\n#include <Utility\\HelperFunctions.h>\n\n\n\n#include <Resource\\ResourceNameManager.h>\n\n#include <Window\\Window.h>\n\n#include \"VoxelModelEditorCommand.h\"\n\n#include \"VoxelModelEditorConsole.h\"\n\n#include \"VoxelModelEditorCore.h\"\n\n#include \"VoxelModelEditorView.h\"\n\n\n\nvoid VMECmd_LoadBinding::Execute(VMECore &core, VMEViewRefreshConfig &refresh, VMEConsole &console)\n\n{\n\n auto &rM = RscNameMgr::GetInstance();\n", "file_path": "Source/VoxelWorld/Application/VoxelModelEditor/VoxelModelEditorCommand.cpp", "rank": 69, "score": 11.58991105612775 }, { "content": "", "file_path": "Source/Components/WinFramework/Screen/GUISystem.cpp", "rank": 70, "score": 11.582181443098996 }, { "content": "/*================================================================\n\nFilename: Model.cpp\n\nDate: 2018.1.13\n\nCreated by AirGuanZ\n\n================================================================*/\n\n#include <Window\\Window.h>\n\n#include \"Model.h\"\n\n\n\nconst std::vector<ID3D11Buffer*> Model::emptyVtxBufs_(\n\n D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT, nullptr);\n\n\n\nbool Model::IsAvailable(void) const\n\n{\n\n assert(vtxBufBinding_.startSlot < 0 ||\n\n vtxBufBinding_.startSlot + vtxBufBinding_.bufs.size()\n\n <= D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT);\n\n return vtxBufBinding_.bufs.size() > 0;\n\n}\n\n\n\nvoid Model::Draw(void) const\n", "file_path": "Source/VoxelWorld/World/Chunk/Model.cpp", "rank": 71, "score": 11.579115536952035 }, { "content": "", "file_path": "Source/VoxelWorld/Application/Game/Game.cpp", "rank": 72, "score": 11.567779410057781 }, { "content": " boneMaps.clear();\n\n return false;\n\n }\n\n }\n\n\n\n return true;\n\n}\n\n\n\nint main(void)\n\n{\n\n try\n\n {\n\n std::string errMsg;\n\n std::wstring confFilename;\n\n\n\n std::cout << \"Enter configure: \";\n\n std::wcin >> confFilename;\n\n\n\n std::vector<InputUnit> files;\n\n float timeFactor;\n", "file_path": "Source/Components/SkeletonAnimationConvertor/Main.cpp", "rank": 73, "score": 11.3826414031038 }, { "content": "", "file_path": "Source/Components/WinFramework/D3DObject/FrameBuffer.cpp", "rank": 74, "score": 11.371741135070312 }, { "content": " filenames);\n\n for(auto &it : filenames)\n\n core.bindingNames_.push_back(it.first);\n\n\n\n if(showMsg_)\n\n cmdMsgs.push({ VMECmdMsg::NORMAL_COLOR, \"Binding list reloaded\" });\n\n core.needRefreshDisplay_ = true;\n\n\n\n VMECmd_SelectBindingName(0).Execute(core, cmdMsgs);\n\n}\n\n\n\nVMECmd_SelectBindingName::VMECmd_SelectBindingName(int selected)\n\n : selected_(selected)\n\n{\n\n\n\n}\n\n\n\nvoid VMECmd_SelectBindingName::Execute(VoxelModelEditorCore &core, VMECmdMsgQueue &cmdMsgs)\n\n{\n\n core.needRefreshDisplay_ = true;\n", "file_path": "Source/VoxelWorld/Application/VoxelModelEditorBak/VoxelModelEditorCommand.cpp", "rank": 75, "score": 11.261967938987098 }, { "content": "", "file_path": "Source/Components/WinFramework/D3DObject/FrameBuffer.cpp", "rank": 76, "score": 11.243790190027099 }, { "content": " basic_.Destroy();\n\n blend_.reset();\n\n raster_.reset();\n\n depth_.reset();\n\n}\n\n\n\nbool LiquidRenderer::IsAvailable(void) const\n\n{\n\n return basic_.IsAvailable();\n\n}\n\n\n\nvoid LiquidRenderer::Begin(void)\n\n{\n\n ID3D11DeviceContext *DC = Window::GetInstance().GetD3DDeviceContext();\n\n\n\n basic_.Begin();\n\n DC->OMSetBlendState(*blend_, nullptr, 0xFFFFFFFF);\n\n DC->RSSetState(*raster_);\n\n DC->OMSetDepthStencilState(*depth_, 0);\n\n}\n", "file_path": "Source/VoxelWorld/World/Chunk/LiquidRenderer.cpp", "rank": 77, "score": 11.22666058949465 }, { "content": "", "file_path": "Source/VoxelWorld/World/Chunk/BasicModel.cpp", "rank": 78, "score": 11.161358532334434 }, { "content": "", "file_path": "Source/VoxelWorld/Application/VoxelModelEditor/VoxelModelEditorConsole.cpp", "rank": 79, "score": 11.096198081243841 }, { "content": "/*================================================================\n\nFilename: FPSCounter.h\n\nDate: 2018.1.27\n\nCreated by AirGuanZ\n\n================================================================*/\n\n#pragma once\n\n\n\n#include <cassert>\n\n\n\n#include \"Clock.h\"\n\n#include \"Uncopiable.h\"\n\n\n", "file_path": "Source/Components/Utility/FPSCounter.h", "rank": 80, "score": 10.980292111041923 }, { "content": "", "file_path": "Source/VoxelWorld/World/Chunk/ChunkLoader.h", "rank": 81, "score": 10.979243217965871 }, { "content": " idxBuf_.Destroy();\n\n idxCnt_ = 0;\n\n }\n\n\n\n void Bind(ID3D11DeviceContext *DC)\n\n {\n\n assert(IsAvailable() && DC != nullptr);\n\n static const UINT stride = sizeof(Vertex), offset = 0;\n\n ID3D11Buffer *vtxBuf = vtxBuf_.GetBuffer();\n\n DC->IASetVertexBuffers(0, 1, &vtxBuf, &stride, &offset);\n\n DC->IASetIndexBuffer(idxBuf_.GetBuffer(), DXGI_FORMAT_R16_UINT, 0);\n\n }\n\n\n\n void Unbind(ID3D11DeviceContext *DC)\n\n {\n\n assert(IsAvailable() && DC != nullptr);\n\n static const UINT stride = 0, offset = 0;\n\n static const ID3D11Buffer *vtxBuf = nullptr;\n\n DC->IASetVertexBuffers(0, 1, &vtxBuf, &stride, &offset);\n\n DC->IASetIndexBuffer(nullptr, DXGI_FORMAT_UNKNOWN, 0);\n", "file_path": "Source/Components/WinFramework/D3DObject/SingleBufferMesh.h", "rank": 82, "score": 10.88895143093471 }, { "content": "", "file_path": "Source/Components/WinFramework/Window/Window.cpp", "rank": 83, "score": 10.879606805219925 }, { "content": "", "file_path": "Source/Components/WinFramework/Window/Window.cpp", "rank": 84, "score": 10.878566890750065 }, { "content": " IMGUI_API void AddGlyph(ImWchar c, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x);\n\n IMGUI_API void AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst = true); // Makes 'dst' character/glyph points to 'src' character/glyph. Currently needs to be called AFTER fonts have been built.\n\n\n\n#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS\n\n typedef ImFontGlyph Glyph; // OBSOLETE 1.52+\n\n#endif\n\n};\n\n\n\n#if defined(__clang__)\n\n#pragma clang diagnostic pop\n\n#endif\n\n\n\n// Include imgui_user.h at the end of imgui.h (convenient for user to only explicitly include vanilla imgui.h)\n\n#ifdef IMGUI_INCLUDE_IMGUI_USER_H\n\n#include \"imgui_user.h\"\n\n#endif\n", "file_path": "Source/Components/WinFramework/Screen/imgui/imgui.h", "rank": 85, "score": 10.77193638914004 }, { "content": "", "file_path": "Source/Components/WinFramework/Window/Window.cpp", "rank": 86, "score": 10.71971574513881 }, { "content": "", "file_path": "Source/Components/SkeletonAnimation/SkeletonDataLoader.cpp", "rank": 87, "score": 10.700620827814202 }, { "content": "\n\nvoid LiquidRenderer::End(void)\n\n{\n\n ID3D11DeviceContext *DC = Window::GetInstance().GetD3DDeviceContext();\n\n\n\n DC->OMSetBlendState(nullptr, nullptr, 0xFFFFFFFF);\n\n DC->RSSetState(nullptr);\n\n DC->OMSetDepthStencilState(nullptr, 0);\n\n basic_.End();\n\n}\n\n\n\nLiquidRenderer::ShaderType &LiquidRenderer::GetShader(void)\n\n{\n\n return basic_.GetShader();\n\n}\n", "file_path": "Source/VoxelWorld/World/Chunk/LiquidRenderer.cpp", "rank": 88, "score": 10.636605706260841 }, { "content": "/*================================================================\n\nFilename: Clock.cpp\n\nDate: 2017.10.16\n\nCreated by AirGuanZ\n\n================================================================*/\n\n#include <Windows.h>\n\n\n\n#include \"Clock.h\"\n\n\n\nClock::Clock(void)\n\n{\n\n LARGE_INTEGER freq;\n\n QueryPerformanceFrequency(&freq);\n\n ratio_ = 1000.0f / freq.QuadPart;\n\n\n\n Restart();\n\n}\n\n\n\nvoid Clock::Restart(void)\n\n{\n", "file_path": "Source/Components/Utility/Clock.cpp", "rank": 89, "score": 10.62690468657603 }, { "content": "/*================================================================\n\nFilename: BasicBuffer.h\n\nDate: 2018.1.23\n\nCreated by AirGuanZ\n\n================================================================*/\n\n#pragma once\n\n\n\n#include <cassert>\n\n\n\n#include <Utility\\D3D11Header.h>\n\n#include <Utility\\HelperFunctions.h>\n\n\n\n#include <Window\\Window.h>\n\n\n", "file_path": "Source/Components/WinFramework/D3DObject/BasicBuffer.h", "rank": 90, "score": 10.597581721085588 }, { "content": "\n\nvoid ChunkRendererManager::Destroy(void)\n\n{\n\n basicRenderer_.Destroy();\n\n for(Texture2D &tex : basicRendererTextures_)\n\n tex.Destroy();\n\n basicUniforms_.reset();\n\n\n\n carveRenderer_.Destroy();\n\n for(Texture2D &tex : carveRendererTextures_)\n\n tex.Destroy();\n\n carveUniforms_.reset();\n\n\n\n liquidRenderer_.Destroy();\n\n for(Texture2D &tex : liquidRendererTextures_)\n\n tex.Destroy();\n\n liquidUniforms_.reset();\n\n\n\n sampler_ = Sampler(D3DObj_Noinit());\n\n\n", "file_path": "Source/VoxelWorld/Application/Game/ChunkRendererManager.cpp", "rank": 91, "score": 10.55761434574319 }, { "content": "", "file_path": "Source/Components/WinFramework/Window/Window.cpp", "rank": 93, "score": 10.455681231094307 }, { "content": "/*================================================================\n\nFilename: SingleBufferMesh.h\n\nDate: 2018.3.19\n\nCreated by AirGuanZ\n\n================================================================*/\n\n#pragma once\n\n\n\n#include <cassert>\n\n#include <vector>\n\n\n\n#include <Utility\\D3D11Header.h>\n\n#include <Utility\\Uncopiable.h>\n\n\n\n#include \"BasicBuffer.h\"\n\n\n\ntemplate<typename _vertexType>\n", "file_path": "Source/Components/WinFramework/D3DObject/SingleBufferMesh.h", "rank": 94, "score": 10.395747161695738 }, { "content": "/*================================================================\n\nFilename: V2/Biome_V2.h\n\nDate: 2018.2.3\n\nCreated by AirGuanZ\n\n================================================================*/\n\n#pragma once\n\n\n\n#include <cassert>\n\n\n\n#include <World\\Chunk\\Chunk.h>\n\n#include \"Area_V2.h\"\n\n#include \"Common_V2.h\"\n\n\n\nnamespace LandGenerator_V2\n\n{\n", "file_path": "Source/VoxelWorld/World/Land/V2/Biome_V2.h", "rank": 95, "score": 10.375297389745548 }, { "content": "/*================================================================\n\nFilename: LinkedMap.h\n\nDate: 2018.1.29\n\nCreated by AirGuanZ\n\n================================================================*/\n\n#pragma once\n\n\n\n#include <algorithm>\n\n#include <list>\n\n#include <map>\n\n\n\ntemplate<typename KeyType, typename ValueType>\n", "file_path": "Source/Components/Utility/LinkedMap.h", "rank": 96, "score": 10.366333807669399 }, { "content": "", "file_path": "Source/Components/WinFramework/Window/Window.cpp", "rank": 97, "score": 10.347523836311467 }, { "content": "/*================================================================\n\nFilename: PerlinNoise2D.h\n\nDate: 2018.1.31\n\nCreated by AirGuanZ\n\n================================================================*/\n\n#pragma once\n\n\n\n#include <cmath>\n\n#include <random>\n\n\n\ntemplate<typename RT>\n", "file_path": "Source/VoxelWorld/World/Land/PerlinNoise/PerlinNoise2D.h", "rank": 98, "score": 10.292864818243347 }, { "content": "", "file_path": "Source/VoxelWorld/World/Block/BlockInfoManager.cpp", "rank": 99, "score": 10.2052068517044 } ]
C++
src/classical/aig.hpp
eletesta/cirkit
6d0939798ea25cecf92306ce796be154139b94f5
#ifndef AIG_HPP #define AIG_HPP #include <iostream> #include <map> #include <vector> #include <boost/dynamic_bitset.hpp> #include <boost/graph/adjacency_list.hpp> #include <boost/property_map/property_map.hpp> #include <core/properties.hpp> #include <core/utils/graph_utils.hpp> #include <classical/traits.hpp> namespace cirkit { namespace detail { using traits_t = boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS>; } struct aig_function { detail::traits_t::vertex_descriptor node; bool complemented; inline aig_function operator!() const { return {node, !complemented}; } inline bool operator==( const aig_function& other ) const { return node == other.node && complemented == other.complemented; } inline bool operator!=( const aig_function& other ) const { return !( this->operator==(other) ); } inline bool operator<( const aig_function& other ) const { return node < other.node || ( node == other.node && complemented < other.complemented ); } inline aig_function operator^( bool value ) const { return {node, complemented != value }; } }; namespace detail { using node_pair = std::pair<traits_t::vertex_descriptor, traits_t::vertex_descriptor>; } struct aig_graph_info { std::string model_name; detail::traits_t::vertex_descriptor constant; bool constant_used = false; bool enable_strashing = true; bool enable_local_optimization = true; std::map<detail::traits_t::vertex_descriptor, std::string> node_names; std::vector<std::pair<aig_function, std::string> > outputs; std::vector<detail::traits_t::vertex_descriptor> inputs; std::vector<aig_function> cos; std::vector<detail::traits_t::vertex_descriptor> cis; std::map<std::pair<aig_function, aig_function>, aig_function> strash; std::map<aig_function, aig_function> latch; boost::dynamic_bitset<> unateness; std::vector<detail::node_pair> input_symmetries; std::vector<std::vector<detail::traits_t::vertex_descriptor>> trans_words; }; namespace detail { using vertex_properties_t = boost::property<boost::vertex_name_t, unsigned, boost::property<boost::vertex_annotation_t, std::map<std::string, std::string>>>; using edge_properties_t = boost::property<boost::edge_complement_t, bool>; using graph_properties_t = boost::property<boost::graph_name_t, aig_graph_info>; } using aig_graph = digraph_t<detail::vertex_properties_t, detail::edge_properties_t, detail::graph_properties_t>; using aig_node = vertex_t<aig_graph>; using aig_edge = edge_t<aig_graph>; void aig_initialize( aig_graph& aig, const std::string& model_name = std::string() ); aig_function aig_get_constant( aig_graph& aig, bool value ); bool aig_is_constant_used( const aig_graph& aig ); aig_function aig_create_pi( aig_graph& aig, const std::string& name ); void aig_create_po( aig_graph& aig, const aig_function& f, const std::string& name ); void aig_remove_po( aig_graph& aig ); aig_function aig_create_ci( aig_graph& aig, const std::string& name ); void aig_create_co( aig_graph& aig, const aig_function& f ); aig_function aig_create_and( aig_graph& aig, const aig_function& left, const aig_function& right ); aig_function aig_create_nand( aig_graph& aig, const aig_function& left, const aig_function& right ); aig_function aig_create_or( aig_graph& aig, const aig_function& left, const aig_function& right ); aig_function aig_create_nor( aig_graph& aig, const aig_function& left, const aig_function& right ); aig_function aig_create_xor( aig_graph& aig, const aig_function& left, const aig_function& right ); aig_function aig_create_ite( aig_graph& aig, const aig_function& cond, const aig_function& t, const aig_function& e ); aig_function aig_create_implies( aig_graph& aig, const aig_function& a, const aig_function& b ); aig_function aig_create_maj( aig_graph& aig, const aig_function& a, const aig_function& b, const aig_function& c ); aig_function aig_create_lat( aig_graph& aig, const aig_function& in, const std::string& name ); aig_function aig_create_nary_and( aig_graph& aig, const std::vector< aig_function >& v ); aig_function aig_create_nary_nand( aig_graph& aig, const std::vector< aig_function >& v ); aig_function aig_create_nary_or( aig_graph& aig, const std::vector< aig_function >& v ); aig_function aig_create_nary_nor( aig_graph& aig, const std::vector< aig_function >& v ); aig_function aig_create_nary_xor( aig_graph& aig, const std::vector< aig_function >& v ); void write_dot( const aig_graph& aig, std::ostream& os, const properties::ptr& settings = properties::ptr() ); void write_dot( const aig_graph& aig, const std::string& filename, const properties::ptr& settings = properties::ptr() ); unsigned aig_to_literal( const aig_graph& aig, const aig_function& f ); unsigned aig_to_literal( const aig_graph& aig, const aig_node& node ); aig_function aig_to_function( const aig_graph& aig, const aig_edge& edge ); std::ostream& operator<<( std::ostream& os, const aig_function &f ); template<> struct circuit_traits<aig_graph> { using node = aig_node; using edge = aig_edge; using node_color_map = std::map<aig_node, boost::default_color_type>; }; } #endif
#ifndef AIG_HPP #define AIG_HPP #include <iostream> #include <map> #include <vector> #include <boost/dynamic_bitset.hpp> #include <boost/graph/adjacency_list.hpp> #include <boost/property_map/property_map.hpp> #include <core/properties.hpp> #include <core/utils/graph_utils.hpp> #include <classical/traits.hpp> namespace cirkit { namespace detail { using traits_t = boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS>; } struct aig_function { detail::traits_t::vertex_descriptor node; bool complemented; inline aig_function operator!() const { return {node, !complemented}; } inline bool operator==( const aig_function& other ) const { return node == other.node && complemented == other.complemented; } inline bool operator!=( const aig_function& other ) const { return !( this->operator==(other) ); } inline bool operator<( const aig_function& other ) const { return node < other.node || ( node == other.node && complemented < other.complemented ); } inline aig_function operator^( bool value ) const { return {node, complemented != value }; } }; namespace detail { using node_pair = std::pair<traits_t::vertex_descriptor, traits_t::vertex_descriptor>; } struct aig_graph_info { std::string model_name; detail::traits_t::vertex_descriptor constant; bool constant_used = false; bool enable_strashing = true; bool enable_local_optimization = true; std::map<detail::traits_t::vertex_descriptor, std::string> node_names; std::vector<std::pair<aig_function, std::string> > outputs; std::vector<detail::traits_t::vertex_descriptor> inputs; std::vector<aig_function> cos; std::vector<detail::traits_t::vertex_descriptor> cis; std::map<std::pair<aig_function, aig_function>, aig_function> strash; std::map<aig_function, aig_function> latch; boost::dynamic_bitset<> unateness; std::vector<detail::node_pair> input_symmetries; std::vector<std::vector<detail::traits_t::vertex_descriptor>> trans_words; }; namespace detail { using vertex_properties_t = boost::property<boost::vertex_name_t, unsigned, boost::property<boost::vertex_annotation_t, std::map<std::string, std::string>>>; using edge_properties_t = boost::property<boost::edge_complement_t, bool>; using graph_properties_t = boost::property<boost::graph_name_t, aig_graph_info>; } using aig_graph = digraph_t<detail::vertex_properties_t,
onst std::string& name ); void aig_remove_po( aig_graph& aig ); aig_function aig_create_ci( aig_graph& aig, const std::string& name ); void aig_create_co( aig_graph& aig, const aig_function& f ); aig_function aig_create_and( aig_graph& aig, const aig_function& left, const aig_function& right ); aig_function aig_create_nand( aig_graph& aig, const aig_function& left, const aig_function& right ); aig_function aig_create_or( aig_graph& aig, const aig_function& left, const aig_function& right ); aig_function aig_create_nor( aig_graph& aig, const aig_function& left, const aig_function& right ); aig_function aig_create_xor( aig_graph& aig, const aig_function& left, const aig_function& right ); aig_function aig_create_ite( aig_graph& aig, const aig_function& cond, const aig_function& t, const aig_function& e ); aig_function aig_create_implies( aig_graph& aig, const aig_function& a, const aig_function& b ); aig_function aig_create_maj( aig_graph& aig, const aig_function& a, const aig_function& b, const aig_function& c ); aig_function aig_create_lat( aig_graph& aig, const aig_function& in, const std::string& name ); aig_function aig_create_nary_and( aig_graph& aig, const std::vector< aig_function >& v ); aig_function aig_create_nary_nand( aig_graph& aig, const std::vector< aig_function >& v ); aig_function aig_create_nary_or( aig_graph& aig, const std::vector< aig_function >& v ); aig_function aig_create_nary_nor( aig_graph& aig, const std::vector< aig_function >& v ); aig_function aig_create_nary_xor( aig_graph& aig, const std::vector< aig_function >& v ); void write_dot( const aig_graph& aig, std::ostream& os, const properties::ptr& settings = properties::ptr() ); void write_dot( const aig_graph& aig, const std::string& filename, const properties::ptr& settings = properties::ptr() ); unsigned aig_to_literal( const aig_graph& aig, const aig_function& f ); unsigned aig_to_literal( const aig_graph& aig, const aig_node& node ); aig_function aig_to_function( const aig_graph& aig, const aig_edge& edge ); std::ostream& operator<<( std::ostream& os, const aig_function &f ); template<> struct circuit_traits<aig_graph> { using node = aig_node; using edge = aig_edge; using node_color_map = std::map<aig_node, boost::default_color_type>; }; } #endif
detail::edge_properties_t, detail::graph_properties_t>; using aig_node = vertex_t<aig_graph>; using aig_edge = edge_t<aig_graph>; void aig_initialize( aig_graph& aig, const std::string& model_name = std::string() ); aig_function aig_get_constant( aig_graph& aig, bool value ); bool aig_is_constant_used( const aig_graph& aig ); aig_function aig_create_pi( aig_graph& aig, const std::string& name ); void aig_create_po( aig_graph& aig, const aig_function& f, c
random
[ { "content": "struct store_info<std::vector<aig_node>>\n\n{\n\n static constexpr const char* key = \"gates\";\n\n static constexpr const char* option = \"gate\";\n\n static constexpr const char* mnemonic = \"\";\n\n static constexpr const char* name = \"gate\";\n\n static constexpr const char* name_plural = \"gates\";\n\n};\n\n\n\ntemplate<>\n\nstd::string store_entry_to_string<std::vector<aig_node>>( const std::vector<aig_node>& g );\n\n\n\ntemplate<>\n\nvoid print_store_entry<std::vector<aig_node>>( std::ostream& os, const std::vector<aig_node>& g );\n\n\n\n/******************************************************************************\n\n * tt *\n\n ******************************************************************************/\n\n\n\ntemplate<>\n", "file_path": "src/cli/stores.hpp", "rank": 0, "score": 209246.71412900373 }, { "content": "struct value_traits<unsigned>\n\n{\n\n static const unsigned null_value = 0u;\n\n};\n\n\n\n/******************************************************************************\n\n * index_map *\n\n ******************************************************************************/\n\n\n\ntemplate<typename IndexType, typename ValueType>\n", "file_path": "src/core/utils/index.hpp", "rank": 1, "score": 203014.05879441692 }, { "content": "struct stg_map_esop_params\n\n{\n\n bool optimize_postesop = false; /* post-optimize ESOP cover */\n\n exorcism_script script = exorcism_script::def_wo4; /* optimize ESOP synthesized circuit */\n\n\n\n bool progress = false; /* show progress line */\n\n\n\n bool nocollapse = false; /* DEBUG: do not collapse (useful with dumpfile parameter) */\n\n std::string dumpfile; /* DEBUG: dump ESOP and AIG files for each ESOP cover and LUT */\n\n};\n\n\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/synthesis/lhrs/stg_map_esop.hpp", "rank": 2, "score": 191562.50185482664 }, { "content": "struct stg_map_luts_stats\n\n{\n\n stg_map_luts_stats()\n\n : own_sub_stats( true ),\n\n map_esop_stats( new stg_map_esop_stats() ),\n\n map_precomp_stats( new stg_map_precomp_stats() )\n\n {\n\n }\n\n\n\n stg_map_luts_stats( stg_map_esop_stats& map_esop_stats,\n\n stg_map_precomp_stats& map_precomp_stats )\n\n : own_sub_stats( false ),\n\n map_esop_stats( &map_esop_stats ),\n\n map_precomp_stats( &map_precomp_stats )\n\n {\n\n }\n\n\n\n ~stg_map_luts_stats()\n\n {\n\n if ( own_sub_stats )\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/synthesis/lhrs/stg_map_luts.hpp", "rank": 3, "score": 191562.50185482664 }, { "content": "struct stg_map_precomp_params\n\n{\n\n unsigned class_method = 0u; /* classification method: 0u: spectral, 1u: affine */\n\n};\n\n\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/synthesis/lhrs/stg_map_precomp.hpp", "rank": 4, "score": 191562.50185482664 }, { "content": "struct stg_map_precomp_stats\n\n{\n\n stg_map_precomp_stats()\n\n : class_counter( 4u ),\n\n class_hash( 4u )\n\n {\n\n class_counter[0u].resize( 3u );\n\n class_counter[1u].resize( 6u );\n\n class_counter[2u].resize( 18u );\n\n class_counter[3u].resize( 48u );\n\n }\n\n\n\n double class_runtime = 0.0;\n\n\n\n std::vector<std::vector<unsigned>> class_counter;\n\n\n\n std::vector<std::unordered_map<uint64_t, uint64_t>> class_hash;\n\n};\n\n\n\nvoid stg_map_precomp( circuit& circ, uint64_t function, unsigned num_vars,\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/synthesis/lhrs/stg_map_precomp.hpp", "rank": 5, "score": 191562.50185482664 }, { "content": "struct stg_map_esop_stats\n\n{\n\n double cover_runtime = 0.0;\n\n double exorcism_runtime = 0.0;\n\n unsigned dumpfile_counter = 0u;\n\n};\n\n\n\nvoid stg_map_esop( circuit& circ, const xmg_graph& function,\n\n const std::vector<unsigned>& line_map,\n\n const stg_map_esop_params& params,\n\n stg_map_esop_stats& stats );\n\n\n\n}\n\n\n\n#endif\n\n\n\n// Local Variables:\n\n// c-basic-offset: 2\n\n// eval: (c-set-offset 'substatement-open 0)\n\n// eval: (c-set-offset 'innamespace 0)\n\n// End:\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/synthesis/lhrs/stg_map_esop.hpp", "rank": 6, "score": 191562.50185482664 }, { "content": "struct stg_map_shannon_stats\n\n{\n\n stg_map_shannon_stats()\n\n : own_sub_stats( true ),\n\n map_luts_stats( new stg_map_luts_stats() )\n\n {\n\n }\n\n\n\n stg_map_shannon_stats( stg_map_luts_stats& map_luts_stats )\n\n : own_sub_stats( false ),\n\n map_luts_stats( &map_luts_stats )\n\n {\n\n }\n\n\n\n ~stg_map_shannon_stats()\n\n {\n\n if ( own_sub_stats )\n\n {\n\n delete map_luts_stats;\n\n }\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/synthesis/lhrs/stg_map_shannon.hpp", "rank": 7, "score": 191562.50185482664 }, { "content": "struct stg_map_shannon_params\n\n{\n\n stg_map_shannon_params()\n\n : own_sub_params( true ),\n\n map_luts_params( new stg_map_luts_params() )\n\n {\n\n }\n\n\n\n stg_map_shannon_params( const stg_map_luts_params& map_luts_params )\n\n : own_sub_params( false ),\n\n map_luts_params( &map_luts_params )\n\n {\n\n }\n\n\n\n ~stg_map_shannon_params()\n\n {\n\n if ( own_sub_params )\n\n {\n\n delete map_luts_params;\n\n }\n\n }\n\n\n\n bool own_sub_params = false;\n\n\n\n stg_map_luts_params const* map_luts_params = nullptr;\n\n};\n\n\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/synthesis/lhrs/stg_map_shannon.hpp", "rank": 8, "score": 191562.50185482664 }, { "content": "struct stg_map_luts_params\n\n{\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/synthesis/lhrs/stg_map_luts.hpp", "rank": 9, "score": 191562.50185482664 }, { "content": "struct stg_map_shannon_stats\n\n{\n\n stg_map_shannon_stats()\n\n : own_sub_stats( true ),\n\n map_luts_stats( new stg_map_luts_stats() )\n\n {\n\n }\n\n\n\n stg_map_shannon_stats( stg_map_luts_stats& map_luts_stats )\n\n : own_sub_stats( false ),\n\n map_luts_stats( &map_luts_stats )\n\n {\n\n }\n\n\n\n ~stg_map_shannon_stats()\n\n {\n\n if ( own_sub_stats )\n\n {\n\n delete map_luts_stats;\n\n }\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/synthesis/lhrs/legacy/stg_map_shannon.hpp", "rank": 10, "score": 188747.12247965336 }, { "content": "struct stg_map_esop_stats\n\n{\n\n double cover_runtime = 0.0;\n\n double exorcism_runtime = 0.0;\n\n unsigned dumpfile_counter = 0u;\n\n};\n\n\n\nvoid stg_map_esop( circuit& circ, const gia_graph& function,\n\n const std::vector<unsigned>& line_map,\n\n const stg_map_esop_params& params,\n\n stg_map_esop_stats& stats );\n\n\n\n}\n\n\n\n}\n\n\n\n#endif\n\n\n\n// Local Variables:\n\n// c-basic-offset: 2\n\n// eval: (c-set-offset 'substatement-open 0)\n\n// eval: (c-set-offset 'innamespace 0)\n\n// End:\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/synthesis/lhrs/legacy/stg_map_esop.hpp", "rank": 11, "score": 188747.12247965336 }, { "content": "struct stg_map_shannon_params\n\n{\n\n stg_map_shannon_params()\n\n : own_sub_params( true ),\n\n map_luts_params( new stg_map_luts_params() )\n\n {\n\n }\n\n\n\n stg_map_shannon_params( const stg_map_luts_params& map_luts_params )\n\n : own_sub_params( false ),\n\n map_luts_params( &map_luts_params )\n\n {\n\n }\n\n\n\n ~stg_map_shannon_params()\n\n {\n\n if ( own_sub_params )\n\n {\n\n delete map_luts_params;\n\n }\n\n }\n\n\n\n bool own_sub_params = false;\n\n\n\n stg_map_luts_params const* map_luts_params = nullptr;\n\n};\n\n\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/synthesis/lhrs/legacy/stg_map_shannon.hpp", "rank": 12, "score": 188747.12247965336 }, { "content": "struct stg_map_precomp_params\n\n{\n\n unsigned class_method = 0u; /* classification method: 0u: spectral, 1u: affine */\n\n};\n\n\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/synthesis/lhrs/legacy/stg_map_precomp.hpp", "rank": 13, "score": 188747.12247965336 }, { "content": "struct stg_map_luts_stats\n\n{\n\n stg_map_luts_stats()\n\n : own_sub_stats( true ),\n\n map_esop_stats( new stg_map_esop_stats() ),\n\n map_precomp_stats( new stg_map_precomp_stats() )\n\n {\n\n }\n\n\n\n stg_map_luts_stats( stg_map_esop_stats& map_esop_stats,\n\n stg_map_precomp_stats& map_precomp_stats )\n\n : own_sub_stats( false ),\n\n map_esop_stats( &map_esop_stats ),\n\n map_precomp_stats( &map_precomp_stats )\n\n {\n\n }\n\n\n\n ~stg_map_luts_stats()\n\n {\n\n if ( own_sub_stats )\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/synthesis/lhrs/legacy/stg_map_luts.hpp", "rank": 14, "score": 188747.12247965336 }, { "content": "struct stg_map_luts_params\n\n{\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/synthesis/lhrs/legacy/stg_map_luts.hpp", "rank": 15, "score": 188747.12247965336 }, { "content": "struct stg_map_precomp_stats\n\n{\n\n stg_map_precomp_stats()\n\n : class_counter( 4u ),\n\n class_hash( 4u )\n\n {\n\n class_counter[0u].resize( 3u );\n\n class_counter[1u].resize( 6u );\n\n class_counter[2u].resize( 18u );\n\n class_counter[3u].resize( 48u );\n\n }\n\n\n\n double class_runtime = 0.0;\n\n\n\n std::vector<std::vector<unsigned>> class_counter;\n\n\n\n std::vector<std::unordered_map<uint64_t, uint64_t>> class_hash;\n\n};\n\n\n\nvoid stg_map_precomp( circuit& circ, uint64_t function, unsigned num_vars,\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/synthesis/lhrs/legacy/stg_map_precomp.hpp", "rank": 16, "score": 188747.12247965336 }, { "content": "struct stg_map_esop_params\n\n{\n\n gia_graph::esop_cover_method cover_method = gia_graph::esop_cover_method::aig_threshold; /* method to extract initial ESOP cover */\n\n bool optimize_postesop = false; /* post-optimize ESOP cover */\n\n exorcism_script script = exorcism_script::def_wo4; /* optimize ESOP synthesized circuit */\n\n\n\n bool progress = false; /* show progress line */\n\n\n\n bool nocollapse = false; /* DEBUG: do not collapse (useful with dumpfile parameter) */\n\n std::string dumpfile; /* DEBUG: dump ESOP and AIG files for each ESOP cover and LUT */\n\n};\n\n\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/synthesis/lhrs/legacy/stg_map_esop.hpp", "rank": 17, "score": 188747.12247965336 }, { "content": "struct transform_to_constants\n\n{\n\n constant operator()( const char& c ) const\n\n {\n\n switch ( c ) {\n\n case '-':\n\n return constant();\n\n break;\n\n\n\n case '0':\n\n case '1':\n\n return constant( c == '1' );\n\n break;\n\n\n\n default:\n\n assert( false );\n\n return constant();\n\n break;\n\n }\n\n }\n\n};\n\n\n\n// CODE move to utils\n\ntemplate<typename Map>\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/io/revlib_parser.cpp", "rank": 18, "score": 188240.41343450002 }, { "content": "struct map_access_functor\n\n{\n\n explicit map_access_functor( Map& map )\n\n : _map( map )\n\n {\n\n }\n\n\n\n const typename Map::mapped_type& operator()( const typename Map::key_type& key ) const\n\n {\n\n return _map.find( key )->second;\n\n }\n\n\n\nprivate:\n\n Map& _map;\n\n};\n\n\n\ntemplate<typename Map>\n\nmap_access_functor<Map> make_map_access_functor( Map& map )\n\n{\n\n return map_access_functor<Map>( map );\n\n}\n\n\n\nbool parse_string_list( const std::string& line, std::vector<std::string>& params )\n\n{\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/io/revlib_parser.cpp", "rank": 19, "score": 184722.17307116368 }, { "content": "struct symmetric_variables_visitor : public boost::static_visitor<std::vector<std::pair<unsigned, unsigned>>>\n\n{\n\n std::vector<std::pair<unsigned, unsigned>> operator()( const tt& spec ) const\n\n {\n\n std::vector<std::pair<unsigned, unsigned>> pairs;\n\n\n\n const auto n = tt_num_vars( spec );\n\n\n\n for ( auto j = 1u; j < n; ++j )\n\n {\n\n for ( auto i = 0u; i < j; ++i )\n\n {\n\n if ( tt_permute( spec, i, j ) == spec )\n\n {\n\n pairs.push_back( {i, j} );\n\n }\n\n }\n\n }\n\n\n\n return pairs;\n\n }\n\n\n\n std::vector<std::pair<unsigned, unsigned>> operator()( const mig_graph& spec ) const\n\n {\n\n return {};\n\n }\n\n};\n\n\n", "file_path": "src/classical/utils/spec_representation.cpp", "rank": 20, "score": 176340.65777762025 }, { "content": "struct make_one_setting<const char*>\n\n{\n\n static void impl( const properties::ptr& settings, const char* s )\n\n {\n\n settings->set( s, true );\n\n }\n\n};\n\n\n\n}\n\n\n\nvoid make_settings_rec( const properties::ptr& settings );\n\n\n\ntemplate<class T, class... Ts>\n\nvoid make_settings_rec( const properties::ptr& settings, T value, Ts... rest )\n\n{\n\n detail::make_one_setting<T>::impl( settings, value );\n\n make_settings_rec( settings, rest... );\n\n}\n\n\n\ntemplate<class... Ts>\n", "file_path": "src/core/properties.hpp", "rank": 21, "score": 164037.57979882613 }, { "content": "struct is_trivial_visitor : public boost::static_visitor<boost::optional<std::pair<unsigned, bool>>>\n\n{\n\n boost::optional<std::pair<unsigned, bool>> operator()( const tt& spec ) const\n\n {\n\n /* terminal cases */\n\n if ( ( ~spec ).none() || spec.none() )\n\n {\n\n return std::make_pair( 0u, spec.test( 0u ) );\n\n }\n\n\n\n /* single variable */\n\n tt spec_copy = spec;\n\n tt_extend( spec_copy, 6u );\n\n\n\n const auto nvars = tt_num_vars( spec_copy );\n\n\n\n if ( nvars == 6u )\n\n {\n\n for ( auto i = 0u; i < 6u; ++i )\n\n {\n", "file_path": "src/classical/utils/spec_representation.cpp", "rank": 22, "score": 162493.1282355422 }, { "content": "struct hash<cirkit::cube2>\n\n{\n\n std::size_t operator()( cirkit::cube2 const& c ) const\n\n {\n\n return c.value;\n\n }\n\n};\n\n\n\n}\n\n\n\n#endif\n\n\n\n// Local Variables:\n\n// c-basic-offset: 2\n\n// eval: (c-set-offset 'substatement-open 0)\n\n// eval: (c-set-offset 'innamespace 0)\n\n// End:\n", "file_path": "src/classical/utils/cube2.hpp", "rank": 23, "score": 161416.54556464902 }, { "content": "struct iterator_extractor<T const>\n\n{\n\n using type = typename T::const_iterator;\n\n};\n\n\n\ntemplate<typename T>\n", "file_path": "src/core/utils/range_utils.hpp", "rank": 24, "score": 161275.38696004282 }, { "content": " class BA = std::allocator<bool>,\n", "file_path": "addons/cirkit-addon-reversible/lib/xtensor-0.10.9/include/xtensor/xtensor_forward.hpp", "rank": 25, "score": 161059.64024199478 }, { "content": " class xiterator : detail::shape_storage<S>\n\n {\n\n public:\n\n\n\n using self_type = xiterator<It, S, L>;\n\n\n\n using subiterator_type = It;\n\n using value_type = typename subiterator_type::value_type;\n\n using reference = typename subiterator_type::reference;\n\n using pointer = typename subiterator_type::pointer;\n\n using difference_type = typename subiterator_type::difference_type;\n\n using size_type = typename subiterator_type::size_type;\n\n using iterator_category = std::bidirectional_iterator_tag;\n\n\n\n using private_base = detail::shape_storage<S>;\n\n using shape_type = typename private_base::shape_type;\n\n using shape_param_type = typename private_base::param_type;\n\n using index_type = xindex_type_t<shape_type>;\n\n\n\n xiterator() = default;\n", "file_path": "addons/cirkit-addon-reversible/lib/xtensor-0.10.9/include/xtensor/xiterator.hpp", "rank": 26, "score": 161057.10066448618 }, { "content": "struct hash<cirkit::xmg_function>\n\n{\n\n inline std::size_t operator()( const cirkit::xmg_function& f ) const\n\n {\n\n return ( f.node << 1u ) + static_cast<int>( f.complemented );\n\n }\n\n};\n\n\n\n}\n\n\n\nnamespace cirkit\n\n{\n\n\n", "file_path": "src/classical/xmg/xmg.hpp", "rank": 27, "score": 158650.47298331925 }, { "content": " class slice_vector : private std::vector<std::array<long int, 3>>\n\n {\n\n\n\n public:\n\n using index_type = long int;\n\n using base_type = std::vector<std::array<index_type, 3>>;\n\n\n\n // propagating interface\n\n using base_type::begin;\n\n using base_type::cbegin;\n\n using base_type::end;\n\n using base_type::cend;\n\n using base_type::size;\n\n using base_type::operator[];\n\n using base_type::push_back;\n\n\n\n inline slice_vector() = default;\n\n\n\n template <class E, class... Args>\n\n inline slice_vector(const xexpression<E>& e, Args... args)\n", "file_path": "addons/cirkit-addon-reversible/lib/xtensor-0.10.9/include/xtensor/xstridedview.hpp", "rank": 28, "score": 157603.67981844526 }, { "content": "struct mig_functional_hashing_constants\n\n{\n\n static const std::unordered_map<unsigned, std::tuple<unsigned, unsigned, std::map<char, unsigned>, std::string>> min_mig_sizes;\n\n static const std::unordered_map<unsigned, std::tuple<unsigned, unsigned, std::map<char, unsigned>, std::string>> min_depth_mig_sizes;\n\n};\n\n\n\n}\n\n\n\n#endif\n\n\n\n// Local Variables:\n\n// c-basic-offset: 2\n\n// eval: (c-set-offset 'substatement-open 0)\n\n// eval: (c-set-offset 'innamespace 0)\n\n// End:\n", "file_path": "src/classical/mig/mig_functional_hashing_constants.hpp", "rank": 29, "score": 156904.2178180312 }, { "content": "struct hash<cirkit::mig_function>\n\n{\n\n std::size_t operator()( const cirkit::mig_function& f ) const\n\n {\n\n return std::hash<unsigned>()( ( f.node << 1u ) | f.complemented );\n\n }\n\n};\n\n\n\n}\n\n\n\nnamespace cirkit\n\n{\n\n\n\n/******************************************************************************\n\n * Public functions *\n\n ******************************************************************************/\n\n\n\nplim_program\n\ncompile_for_plim( const mig_graph& mig,\n\n const properties::ptr& settings,\n", "file_path": "src/classical/plim/plim_compiler.cpp", "rank": 30, "score": 156020.6613811803 }, { "content": "DdNode * Extra_VectorSupport( DdManager * dd, DdNode * pbFuncs[], int nFuncs )\n\n{\n\n DdNode ** pbFuncsNew;\n\n DdNode * bVars;\n\n int i, Counter;\n\n\n\n Counter = 0;\n\n pbFuncsNew = ALLOC( DdNode *, nFuncs );\n\n // collect the non-zero functions into an array\n\n for ( i = 0; i < nFuncs; i++ )\n\n if ( pbFuncs[i] )\n\n pbFuncsNew[ Counter++ ] = pbFuncs[i];\n\n bVars = Cudd_VectorSupport( dd, pbFuncsNew, Counter ); \n\n\n\n free( pbFuncsNew );\n\n return bVars; \n", "file_path": "lib/extra/extraBddUnate.c", "rank": 31, "score": 155080.45774310204 }, { "content": "struct value_traits\n\n{\n\n static const T null_value;\n\n};\n\n\n\ntemplate<typename T>\n\nconst T value_traits<T>::null_value = T();\n\n\n\ntemplate<>\n", "file_path": "src/core/utils/index.hpp", "rank": 32, "score": 154961.79840943636 }, { "content": "struct remove_constant_if_unused\n\n{\n\n remove_constant_if_unused() {}\n\n remove_constant_if_unused( const aig_graph& aig ) : aig( &aig ) {}\n\n\n\n template <typename Vertex>\n\n bool operator()( const Vertex& v ) const\n\n {\n\n const auto& graph_info = boost::get_property( *aig, boost::graph_name );\n\n\n\n return ( v != graph_info.constant ) || graph_info.constant_used;\n\n }\n\n\n\nprivate:\n\n aig_graph const* aig = nullptr;\n\n};\n\n\n\n/******************************************************************************\n\n * Public functions *\n\n ******************************************************************************/\n", "file_path": "src/classical/aig.cpp", "rank": 33, "score": 154947.7583652048 }, { "content": "struct names_map\n\n{\n\n std::string operator()( const unsigned id )\n\n {\n\n const std::string name = (boost::format(\"var_%d\") % id).str();\n\n auto it = name_map.find( id );\n\n if ( it == name_map.end() )\n\n {\n\n return name;\n\n }\n\n return it->second;\n\n }\n\n\n\n void insert( const unsigned id, const std::string& s )\n\n {\n\n std::string na;\n\n unsigned idx;\n\n if ( split_name( na, idx, s ) )\n\n {\n\n const std::string&& format_string = (boost::format(\"%s_%s\") % na % idx).str();\n", "file_path": "programs/classical/aig_to_smt2.cpp", "rank": 34, "score": 154894.50445100773 }, { "content": "struct hash<std::vector<T>>\n\n{\n\n std::size_t operator()( std::vector<T> const& c ) const\n\n {\n\n std::size_t seed = 0;\n\n for ( const auto& v : c )\n\n {\n\n hash_combine( seed, v );\n\n }\n\n return seed;\n\n }\n\n};\n\n\n\n}\n\n\n\n#endif\n\n\n\n// Local Variables:\n\n// c-basic-offset: 2\n\n// eval: (c-set-offset 'substatement-open 0)\n\n// eval: (c-set-offset 'innamespace 0)\n\n// End:\n", "file_path": "src/core/utils/hash_utils.hpp", "rank": 35, "score": 154543.67982999008 }, { "content": "struct mighty_operation_t\n\n{\n", "file_path": "src/classical/mig/mig_verilog.cpp", "rank": 36, "score": 151889.53776433688 }, { "content": "struct dd_node\n\n{\n\n unsigned var;\n\n unsigned high;\n\n unsigned low;\n\n\n\n bool operator==( const dd_node& other ) const\n\n {\n\n return var == other.var && high == other.high && low == other.low;\n\n }\n\n};\n\n\n\nstd::ostream& operator<<( std::ostream& os, const dd_node& z );\n\n\n", "file_path": "src/classical/dd/dd_manager.hpp", "rank": 37, "score": 151880.98191305745 }, { "content": " class vector;\n\nRANGES_END_NAMESPACE_STD\n\n#else\n\n#include <vector>\n\n#endif\n\n\n\nnamespace ranges\n\n{\n\n inline namespace v3\n\n {\n\n /// \\cond\n\n namespace detail\n\n {\n\n template<typename Rng, typename Cont, typename I = range_common_iterator_t<Rng>>\n\n using ConvertibleToContainer = meta::strict_and<\n\n Range<Cont>,\n\n meta::not_<View<Cont>>,\n\n Movable<Cont>,\n\n ConvertibleTo<range_value_t<Rng>, range_value_t<Cont>>,\n\n Constructible<Cont, I, I>>;\n", "file_path": "ext/include/range/v3/to_container.hpp", "rank": 38, "score": 151495.1185621253 }, { "content": "extern void Extra_WriteBlifNodeUsingGates( FILE * pFile, DdManager * dd, DdNode * Func, char * pInputNames[], char * pOutputName, int fCascade );\n", "file_path": "lib/extra/extra.h", "rank": 39, "score": 151443.58561126588 }, { "content": "DdNode *\n\nExtra_ConstCofVars(\n\n DdManager * dd, /* the manager */\n\n DdNode * Func, /* the function whose constant cofactor variables are computed */\n\n int fCofValue ) /* the flag which shows which constant we are interested in */\n\n{\n\n DdNode * zRes;\n\n DdNode * bSupp;\n\n bSupp = Cudd_Support( dd, Func ); Cudd_Ref( bSupp );\n\n zRes = Extra_ConstCofVarsSupport( dd, Func, bSupp, fCofValue ); Cudd_Ref( zRes );\n\n Cudd_RecursiveDeref( dd, bSupp );\n\n Cudd_Deref( zRes );\n\n return zRes;\n", "file_path": "lib/extra/extraBddUnate.c", "rank": 40, "score": 151436.20201134076 }, { "content": "struct hash_value_impl\n\n{\n\n static void apply( std::size_t& seed, const Tuple& tuple )\n\n {\n\n hash_value_impl<Tuple, Index - 1>::apply( seed, tuple );\n\n hash_combine( seed, std::get<Index>( tuple ) );\n\n }\n\n};\n\n\n\ntemplate<class Tuple>\n", "file_path": "src/core/utils/hash_utils.hpp", "rank": 41, "score": 148996.43787576997 }, { "content": "struct mig_remove_constant_if_unused\n\n{\n\n mig_remove_constant_if_unused() {}\n\n mig_remove_constant_if_unused( const mig_graph& mig ) : mig( &mig ) {}\n\n\n\n template <typename Vertex>\n\n bool operator()( const Vertex& v ) const\n\n {\n\n const auto& graph_info = boost::get_property( *mig, boost::graph_name );\n\n\n\n return ( v != graph_info.constant ) || graph_info.constant_used;\n\n }\n\n\n\nprivate:\n\n mig_graph const* mig = nullptr;\n\n};\n\n\n\n/******************************************************************************\n\n * Public functions *\n\n ******************************************************************************/\n", "file_path": "src/classical/mig/mig.cpp", "rank": 42, "score": 148983.10693132997 }, { "content": " class xoptional_vector;\n\n\n\n template <class T, class A, class BA>\n\n struct xoptional_sequence_inner_types<xoptional_vector<T, A, BA>>\n\n {\n\n using base_container_type = std::vector<T, A>;\n\n using flag_container_type = std::vector<bool, BA>;\n\n };\n\n\n\n /*****************************************************\n\n * xoptional_vector and xoptional_array declarations *\n\n *****************************************************/\n\n\n\n template <class T, std::size_t I>\n", "file_path": "addons/cirkit-addon-reversible/lib/xtensor-0.10.9/include/xtensor/xmissing.hpp", "rank": 43, "score": 148170.60298256885 }, { "content": "int\n\nextraConstCofVarsVerify( \n\n DdManager * dd, /* the manager */\n\n DdNode * bFunc, /* the function whose symmetries are computed */\n\n int fCofValue, /* const cof value */\n\n DdNode * zConstCofVar ) /* the set of unate variables */\n\n{\n\n DdNode * bSupp;\n\n DdNode * zTemp;\n\n DdNode * bF0, * bF1;\n\n int flag;\n\n\n\n flag = 1;\n\n bSupp = Cudd_Support( dd, bFunc ); Cudd_Ref( bSupp );\n\n for ( zTemp = zConstCofVar; zTemp != z0; zTemp = cuddE(zTemp) )\n\n {\n\n// if ( !Cudd_bddLeq( dd, bSupp, dd->vars[zTemp->index/2] ) )\n\n// flag = 0;\n\n\n\n bF0 = Cudd_Cofactor( dd, bFunc, Cudd_Not(dd->vars[zTemp->index/2]) ); Cudd_Ref( bF0 );\n\n bF1 = Cudd_Cofactor( dd, bFunc, dd->vars[zTemp->index/2] ); Cudd_Ref( bF1 );\n\n\n\n if ( zTemp->index%2 == 0 )\n\n {\n\n if ( fCofValue == 0 )\n\n {\n\n if ( bF1 != b0 )\n\n flag = 0;\n\n } \n\n else // if ( fCofValue == 1 )\n\n {\n\n if ( bF1 != b1 )\n\n flag = 0;\n\n }\n\n }\n\n if ( zTemp->index%2 == 1 )\n\n {\n\n if ( fCofValue == 0 )\n\n {\n\n if ( bF0 != b0 )\n\n flag = 0;\n\n } \n\n else // if ( fCofValue == 1 )\n\n {\n\n if ( bF0 != b1 )\n\n flag = 0;\n\n }\n\n }\n\n\n\n Cudd_RecursiveDeref( dd, bF0 );\n\n Cudd_RecursiveDeref( dd, bF1 );\n\n\n\n if ( flag == 0 )\n\n break;\n\n\n\n }\n\n Cudd_RecursiveDeref( dd, bSupp );\n\n return flag;\n", "file_path": "lib/extra/extraBddUnate.c", "rank": 44, "score": 147969.15629563318 }, { "content": "DdNode * Extra_ConstCofVarsSharing( \n\n DdManager * dd, /* the manager */\n\n DdNode * pbFuncs[], /* the functions whose constant cofactor variables are computed */\n\n int nFuncs, /* the number of functions */\n\n int fCofValue ) /* the flag which shows which constant we are interested in */\n\n{\n\n DdNode * zRes, * zTemp, * zConstCofVars;\n\n DdNode * bVars;\n\n int i;\n\n\n\n assert( nFuncs > 0 );\n\n\n\n// bVars = Cudd_VectorSupport( dd, pbFuncs, nFuncs ); Cudd_Ref( bVars );\n\n bVars = Extra_VectorSupport( dd, pbFuncs, nFuncs ); Cudd_Ref( bVars );\n\n\n\n zRes = NULL;\n\n for ( i = 0; i < nFuncs; i++ )\n\n if ( pbFuncs[i] )\n\n {\n\n zConstCofVars = Extra_ConstCofVarsSupport( dd, pbFuncs[i], bVars, fCofValue ); Cudd_Ref( zConstCofVars );\n\n if ( zRes == NULL )\n\n zRes = zConstCofVars; // takes ref\n\n else\n\n {\n\n zRes = Cudd_zddIntersect( dd, zTemp = zRes, zConstCofVars ); Cudd_Ref( zRes );\n\n Cudd_RecursiveDerefZdd( dd, zTemp );\n\n Cudd_RecursiveDerefZdd( dd, zConstCofVars );\n\n }\n\n if ( zRes == z0 )\n\n break;\n\n }\n\n Cudd_RecursiveDeref( dd, bVars );\n\n Cudd_Deref(zRes);\n\n return zRes;\n", "file_path": "lib/extra/extraBddUnate.c", "rank": 45, "score": 147963.00895696066 }, { "content": "DdNode *\n\nExtra_ConstCofVarsSupport(\n\n DdManager * dd, /* the manager */\n\n DdNode * Func, /* the function whose constant cofactor variables are computed */\n\n DdNode * bSupp, /* the given support */\n\n int fCofValue ) /* the flag which shows which constant we are interested in */\n\n{\n\n DdNode * zRes;\n\n do {\n\n dd->reordered = 0;\n\n if ( fCofValue == 0 )\n\n zRes = extraConst0CofVars( dd, Func, bSupp );\n\n else\n\n zRes = extraConst1CofVars( dd, Func, bSupp );\n\n } while (dd->reordered == 1);\n\n Cudd_Ref( zRes );\n\n assert( extraConstCofVarsVerify(dd, Func, fCofValue, zRes) );\n\n Cudd_Deref( zRes );\n\n return zRes;\n", "file_path": "lib/extra/extraBddUnate.c", "rank": 46, "score": 147956.73455090827 }, { "content": "struct less<std::vector<boost::tribool>>\n\n{\n\n bool operator()( const std::vector<boost::tribool>& v1, const std::vector<boost::tribool>& v2 ) const\n\n {\n\n assert( v1.size() == v2.size() );\n\n\n\n auto i = 0u;\n\n while ( i < v1.size() )\n\n {\n\n const auto& t1 = v1[i];\n\n const auto& t2 = v2[i];\n\n\n\n if ( t1 != t2 )\n\n {\n\n if ( boost::indeterminate( t1 ) ) { return true; }\n\n if ( boost::indeterminate( t2 ) ) { return false; }\n\n return !t1 && t2;\n\n }\n\n\n\n ++i;\n", "file_path": "src/classical/dd/visit_solutions.cpp", "rank": 47, "score": 146732.56820602648 }, { "content": " class xoptional_vector;\n\n\n\n /**\n\n * @typedef xarray_optional\n\n * Alias template on xarray_container for handling missing values\n\n *\n\n * @tparam T The value type of the elements.\n\n * @tparam L The layout_type of the container (default: row_major).\n\n * @tparam A The allocator of the container holding the elements.\n\n * @tparam BA The allocator of the container holding the missing flags.\n\n * @tparam SA The allocator of the containers holding the shape and the strides.\n\n */\n\n template <class T, layout_type L = DEFAULT_LAYOUT,\n", "file_path": "addons/cirkit-addon-reversible/lib/xtensor-0.10.9/include/xtensor/xtensor_forward.hpp", "rank": 48, "score": 144772.16571669516 }, { "content": "void Extra_WriteBlifNodeUsingGates( FILE * pFile, DdManager * dd, DdNode * Func, char * pInputNames[], char * pOutputName, int fCascade )\n\n{\n\n DdNode * zCover;\n\n // create the ZDD cover\n\n if ( Extra_WithComplementedEdges(Func) )\n\n {\n\n zCover = Extra_zddIsopCover( dd, Func, Func ); Cudd_Ref( zCover );\n\n extraWriteBlifNodeUsingGates( pFile, dd, zCover, pInputNames, pOutputName, fCascade );\n\n Cudd_RecursiveDerefZdd( dd, zCover );\n\n }\n\n else\n\n extraWriteBlifNodeUsingGates( pFile, dd, Func, pInputNames, pOutputName, fCascade );\n", "file_path": "lib/extra/extraDdPrint.c", "rank": 49, "score": 144670.74032101617 }, { "content": "static void extraWriteBlifNodeUsingGates( FILE * pFile, DdManager * dd, DdNode * zCover, char * pInputNames[], char * pOutputName, int fCascade );\n", "file_path": "lib/extra/extraDdPrint.c", "rank": 50, "score": 144652.3368948362 }, { "content": " class xoptional_vector : public xoptional_sequence<xoptional_vector<T, A, BA>>\n\n {\n\n public:\n\n\n\n using self_type = xoptional_vector;\n\n using base_type = xoptional_sequence<self_type>;\n\n using base_value_type = typename base_type::base_value_type;\n\n\n\n using value_type = typename base_type::value_type;\n\n using size_type = typename base_type::size_type;\n\n using difference_type = typename base_type::difference_type;\n\n using reference = typename base_type::reference;\n\n using const_reference = typename base_type::const_reference;\n\n using pointer = typename base_type::pointer;\n\n using const_pointer = typename base_type::const_pointer;\n\n\n\n using iterator = typename base_type::iterator;\n\n using const_iterator = typename base_type::const_iterator;\n\n using reverse_iterator = typename base_type::reverse_iterator;\n\n using const_reverse_iterator = typename base_type::const_reverse_iterator;\n", "file_path": "addons/cirkit-addon-reversible/lib/xtensor-0.10.9/include/xtensor/xmissing.hpp", "rank": 51, "score": 143864.81056976088 }, { "content": " class xbuffer_adaptor : private detail::buffer_storage_t<T, A, O>\n\n {\n\n public:\n\n\n\n using base_type = detail::buffer_storage_t<T, A, O>;\n\n using allocator_type = typename base_type::allocator_type;\n\n using value_type = typename base_type::value_type;\n\n using reference = typename base_type::reference;\n\n using const_reference = typename base_type::const_reference;\n\n using pointer = typename base_type::pointer;\n\n using const_pointer = typename base_type::const_pointer;\n\n\n\n using size_type = typename base_type::size_type;\n\n using difference_type = typename base_type::difference_type;\n\n\n\n using iterator = pointer;\n\n using const_iterator = const_pointer;\n\n using reverse_iterator = std::reverse_iterator<iterator>;\n\n using const_reverse_iterator = std::reverse_iterator<const_iterator>;\n\n\n", "file_path": "addons/cirkit-addon-reversible/lib/xtensor-0.10.9/include/xtensor/xbuffer_adaptor.hpp", "rank": 52, "score": 143555.0726091149 }, { "content": "struct is_explicit_visitor : public boost::static_visitor<bool>\n\n{\n\n bool operator()( const tt& spec ) const\n\n {\n\n return true;\n\n }\n\n\n\n bool operator()( const mig_graph& spec ) const\n\n {\n\n return false;\n\n }\n\n};\n\n\n", "file_path": "src/classical/utils/spec_representation.cpp", "rank": 53, "score": 141830.90009251123 }, { "content": "struct is_normal_visitor : public boost::static_visitor<bool>\n\n{\n\n bool operator()( const tt& spec ) const\n\n {\n\n return !spec[0];\n\n }\n\n\n\n bool operator()( const mig_graph& spec ) const\n\n {\n\n mig_simple_assignment_simulator::mig_name_value_map m;\n\n const auto r = simulate_mig( spec, mig_simple_assignment_simulator( m ) );\n\n\n\n return !r.at( mig_info( spec ).outputs[0u].first );\n\n }\n\n};\n\n\n", "file_path": "src/classical/utils/spec_representation.cpp", "rank": 54, "score": 141830.90009251123 }, { "content": "struct t_costs {\n\n cost_t operator()(const gate& g, unsigned lines) const;\n\n};\n\n\n\n/**\n\n * @brief H cost from Barenco:1995 based on the Clifford+T Library\n\n *\n\n * Reference: {Barenco, Adriano and Bennett, Charles H and Cleve, Richard\n\n * and DiVincenzo, David P and Margolus, Norman and Shor, Peter\n\n * and Sleator, Tycho and Smolin, John A and Weinfurter, Harald\n\n * Elementary gates for quantum computation\n\n * Physical Review A, 1995\n\n */\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/utils/costs.hpp", "rank": 55, "score": 140988.33030453918 }, { "content": "struct h_costs {\n\n cost_t operator()(const gate& g, unsigned lines) const;\n\n};\n\n\n\n/**\n\n * @brief Calculates the costs of a circuit by a given cost function\n\n *\n\n * With this function the costs for a circuit can be calculated.\n\n * Thereby this functions is generic and calls a cost_function for determine the costs.\n\n * The costs function can either be derived from costs_by_circuit, whereby\n\n * the costs are calculated on base by the whole circuit or it can be\n\n * derived from costs_by_gate, whereby the costs are of each gate are calculated\n\n * and the sum is returned.\n\n *\n\n * @param circ Circuit\n\n * @param f Cost function\n\n *\n\n * @return The costs for the circuit in respect to the given cost function\n\n *\n\n * @sa \\ref sub_cost_functions\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/utils/costs.hpp", "rank": 56, "score": 140988.33030453918 }, { "content": "class _LIBCPP_TYPE_VIS_ONLY vector;\n\ntemplate <class, class>\n", "file_path": "ext/include/meta/meta.hpp", "rank": 57, "score": 139233.60898120014 }, { "content": "class _LIBCPP_TYPE_VIS_ONLY map;\n\ntemplate <class, class, class, class>\n", "file_path": "ext/include/meta/meta.hpp", "rank": 58, "score": 139182.1058852118 }, { "content": "struct _LIBCPP_TYPE_VIS_ONLY equal_to;\n\ntemplate <class>\n", "file_path": "ext/include/meta/meta.hpp", "rank": 59, "score": 139014.74574546036 }, { "content": "struct _LIBCPP_TYPE_VIS_ONLY pair;\n\ntemplate <class>\n", "file_path": "ext/include/meta/meta.hpp", "rank": 60, "score": 139014.74574546036 }, { "content": "struct _LIBCPP_TYPE_VIS_ONLY hash;\n\ntemplate <class>\n", "file_path": "ext/include/meta/meta.hpp", "rank": 61, "score": 139014.74574546036 }, { "content": "struct _LIBCPP_TYPE_VIS_ONLY less;\n\ntemplate <class>\n", "file_path": "ext/include/meta/meta.hpp", "rank": 62, "score": 139014.74574546036 }, { "content": "struct line_costs\n\n{\n\n /**\n\n * @brief Returns the number of lines\n\n *\n\n * @param circ Circuit\n\n *\n\n * @return Number of lines\n\n *\n\n * @since 1.0\n\n */\n\n cost_t operator()( const circuit& circ ) const;\n\n};\n\n\n\n/**\n\n * @brief Calculates the transistor costs\n\n *\n\n * This class calculates the so called transistor\n\n * costs for a gate. They are the number of\n\n * control lines multiplied by 8.\n\n *\n\n * @sa \\ref sub_cost_functions\n\n *\n\n * @since 1.0\n\n */\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/utils/costs.hpp", "rank": 63, "score": 138484.95308096363 }, { "content": "struct stg_tag\n\n{\n\n stg_tag() {}\n\n stg_tag( const boost::dynamic_bitset<>& function ) : function( function ) {}\n\n\n\n boost::dynamic_bitset<> function;\n\n boost::dynamic_bitset<> affine_class;\n\n};\n\n\n\n/**\n\n * @brief Compares type of a boost::any variable\n\n *\n\n * This method is called by is_\\em gate functions\n\n * like is_toffoli().\n\n *\n\n * @param operand A variable of type boost::any\n\n * @return true, if \\p operand is of type \\p T.\n\n *\n\n * @since 1.0\n\n */\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/target_tags.hpp", "rank": 64, "score": 138484.95308096363 }, { "content": "struct depth_costs\n\n{\n\n cost_t operator()( const circuit& circ ) const;\n\n};\n\n\n\n/**\n\n * @brief Quantum costs from SK:2013\n\n *\n\n * Reference: Marek Szyprowski and Pawel Kerntopf, Low quantum\n\n * cost realization of generalized peres and toffoli gates with\n\n * multiple-control signals, IEEE Nano 2013, 802--807.\n\n */\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/utils/costs.hpp", "rank": 65, "score": 138484.95308096363 }, { "content": "struct pauli_tag\n\n{\n\n pauli_tag() {}\n\n\n\n pauli_tag( pauli_axis axis, unsigned root = 1u, bool adjoint = false )\n\n : axis( axis ),\n\n root( root ),\n\n adjoint( adjoint )\n\n {\n\n }\n\n\n\n /**\n\n * @brief Axis of Pauli gate\n\n */\n\n pauli_axis axis = pauli_axis::X;\n\n\n\n /**\n\n * @brief root, i.e., U^{1/root}\n\n */\n\n unsigned root = 1u;\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/pauli_tags.hpp", "rank": 66, "score": 138484.95308096363 }, { "content": "struct fredkin_tag {};\n\n\n\n/**\n\n * @brief Target Tag for Peres gates.\n\n *\n\n * @sa \\ref sub_target_tags\n\n *\n\n * @since 1.0\n\n */\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/target_tags.hpp", "rank": 67, "score": 138484.95308096363 }, { "content": "struct peres_tag {};\n\n\n\n/**\n\n * @brief Target Tag for Modules\n\n *\n\n * @sa \\ref sub_target_tags\n\n *\n\n * @since 1.1\n\n */\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/target_tags.hpp", "rank": 68, "score": 138484.95308096363 }, { "content": "struct hadamard_tag {};\n\n\n\nbool is_hadamard( const gate& g );\n\n\n\ngate& append_hadamard( circuit& circ, unsigned target );\n\ngate& prepend_hadamard( circuit& circ, unsigned target );\n\ngate& insert_hadamard( circuit& circ, unsigned n, unsigned target );\n\n\n\n}\n\n\n\n#endif\n\n\n\n// Local Variables:\n\n// c-basic-offset: 2\n\n// eval: (c-set-offset 'substatement-open 0)\n\n// eval: (c-set-offset 'innamespace 0)\n\n// End:\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/pauli_tags.hpp", "rank": 69, "score": 138484.95308096363 }, { "content": "struct t_depth_costs {\n\n cost_t operator()(const gate& g, unsigned lines) const;\n\n};\n\n\n\n/**\n\n * @brief T cost from Barenco:1995 based on the Clifford+T Library\n\n *\n\n * Reference: {Barenco, Adriano and Bennett, Charles H and Cleve, Richard\n\n * and DiVincenzo, David P and Margolus, Norman and Shor, Peter\n\n * and Sleator, Tycho and Smolin, John A and Weinfurter, Harald\n\n * Elementary gates for quantum computation\n\n * Physical Review A, 1995\n\n */\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/utils/costs.hpp", "rank": 70, "score": 138484.95308096363 }, { "content": "struct module_tag\n\n{\n\n /**\n\n * @brief Name of the module\n\n *\n\n * @since 1.1\n\n */\n\n std::string name;\n\n\n\n /**\n\n * @brief Reference to the circuit\n\n *\n\n * Usually the circuit is inside of the\n\n * circuit modules list.\n\n *\n\n * @since 1.1\n\n */\n\n std::shared_ptr<circuit> reference;\n\n};\n\n\n\n/**\n\n * @brief Single target tag\n\n *\n\n * @sa \\ref sub_target_tags\n\n *\n\n * @since 2.3\n\n */\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/target_tags.hpp", "rank": 71, "score": 138484.95308096363 }, { "content": "struct toffoli_tag {};\n\n\n\n/**\n\n * @brief Target Tag for Fredkin gates.\n\n *\n\n * @sa \\ref sub_target_tags\n\n *\n\n * @since 1.0\n\n */\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/target_tags.hpp", "rank": 72, "score": 138484.95308096363 }, { "content": "struct transistor_costs\n\n{\n\n /**\n\n * @brief Returns the transistor costs for gate \\p g\n\n *\n\n * @param g Gate\n\n * @param lines Number of lines in the circuit\n\n *\n\n * @return Transistor Costs for gate \\p g\n\n *\n\n * @since 1.0\n\n */\n\n cost_t operator()( const gate& g, unsigned lines ) const;\n\n};\n\n\n\n/**\n\n * @brief Returns the depth of the rev. circuit\n\n */\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/utils/costs.hpp", "rank": 73, "score": 138484.95308096363 }, { "content": "struct gate_costs\n\n{\n\n /**\n\n * @brief Returns the number of gates\n\n *\n\n * @param circ Circuit\n\n *\n\n * @return Number of gates\n\n *\n\n * @since 1.0\n\n */\n\n cost_t operator()( const circuit& circ ) const;\n\n};\n\n\n\n/**\n\n * @brief Calculates the line costs\n\n *\n\n * This costs class is basically a wrapper around lines()\n\n * and is given for convenience use with other cost\n\n * functions.\n\n *\n\n * @sa \\ref sub_cost_functions\n\n *\n\n * @since 1.0\n\n */\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/utils/costs.hpp", "rank": 74, "score": 138484.95308096363 }, { "content": " class SA = std::allocator<typename std::vector<T, A>::size_type>>\n\n using xarray_optional = xarray_container<xoptional_vector<T, A, BA>, L, DEFAULT_SHAPE_CONTAINER(T, A, SA)>;\n\n\n\n /**\n\n * @typedef xtensor_optional\n\n * Alias template on xtensor_container for handling missing values\n\n *\n\n * @tparam T The value type of the elements.\n\n * @tparam N The dimension of the tensor.\n\n * @tparam L The layout_type of the container (default: row_major).\n\n * @tparam A The allocator of the containers holding the elements.\n\n * @tparam BA The allocator of the container holding the missing flags.\n\n */\n\n template <class T, std::size_t N, layout_type L = DEFAULT_LAYOUT, class A = std::allocator<T>, class BA = std::allocator<bool>>\n\n using xtensor_optional = xtensor_container<xoptional_vector<T, A, BA>, N, L>;\n\n\n\n namespace check_policy\n\n {\n\n struct none\n\n {\n\n };\n\n struct full\n\n {\n\n };\n\n }\n\n}\n\n\n\n#endif\n", "file_path": "addons/cirkit-addon-reversible/lib/xtensor-0.10.9/include/xtensor/xtensor_forward.hpp", "rank": 75, "score": 138483.11804434698 }, { "content": "struct _LIBCPP_TYPE_VIS_ONLY char_traits;\n\ntemplate <class, class>\n", "file_path": "ext/include/meta/meta.hpp", "rank": 76, "score": 136339.53086817384 }, { "content": "struct io_projectq_tag_t {};\n", "file_path": "addons/cirkit-addon-reversible/src/cli/reversible_stores.hpp", "rank": 77, "score": 136099.106328871 }, { "content": "struct io_liquid_tag_t {};\n", "file_path": "addons/cirkit-addon-reversible/src/cli/reversible_stores.hpp", "rank": 78, "score": 136099.106328871 }, { "content": "struct weighted_reordering\n\n{\n\n /**\n\n * @brief Standard constructor\n\n *\n\n * Initializes default values\n\n *\n\n * @since 1.0\n\n */\n\n weighted_reordering();\n\n\n\n /**\n\n * @brief Constructor for adjusting the parameters\n\n *\n\n * In this parameters the values for \\p alpha and \\p beta can\n\n * be set directly.\n\n *\n\n * @param alpha Control variable for the weight of the variable frequency term\n\n * @param beta Control variable for the weight of the balanced variable term\n\n *\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/synthesis/esop_synthesis.hpp", "rank": 79, "score": 136099.106328871 }, { "content": "struct io_qpic_tag_t {};\n", "file_path": "addons/cirkit-addon-reversible/src/cli/reversible_stores.hpp", "rank": 80, "score": 136099.106328871 }, { "content": "struct io_qcode_tag_t {};\n", "file_path": "addons/cirkit-addon-reversible/src/cli/reversible_stores.hpp", "rank": 81, "score": 136099.106328871 }, { "content": "struct garbage_manager\n\n{\n\npublic:\n\n garbage_manager( const rcbdd& cf ) : cf( cf )\n\n {\n\n std::vector<BDD> garbage;\n\n\n\n for ( auto i = cf.num_outputs(); i < cf.num_vars(); ++i )\n\n {\n\n garbage += cf.y(i);\n\n }\n\n\n\n store += garbage;\n\n }\n\n\n\n const std::vector<BDD>& operator[]( unsigned index )\n\n {\n\n if ( index >= store.size() )\n\n {\n\n for ( auto i = store.size(); i <= index; ++i )\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/synthesis/embed_bdd.cpp", "rank": 82, "score": 136099.106328871 }, { "content": "struct io_qsharp_tag_t {};\n\n\n\n/******************************************************************************\n\n * circuit *\n\n ******************************************************************************/\n\n\n\ntemplate<>\n", "file_path": "addons/cirkit-addon-reversible/src/cli/reversible_stores.hpp", "rank": 83, "score": 136099.106328871 }, { "content": "struct cube_sort\n\n{\n\n explicit cube_sort( unsigned var ) : var( var ) {}\n\n\n\n bool operator()( const cubes_type::value_type& cube1, const cubes_type::value_type& cube2 ) const\n\n {\n\n return !cube_is_negative( var )( cube1 ) && cube_is_negative( var)( cube2 );\n\n }\n\n\n\nprivate:\n\n unsigned var;\n\n};\n\n\n\nweighted_reordering::weighted_reordering()\n\n : alpha( 0.5 ), beta( 0.5 ) {}\n\n\n\nweighted_reordering::weighted_reordering( float alpha, float beta )\n\n : alpha( alpha ), beta( beta ) {}\n\n\n\nvoid weighted_reordering::reorder( cubes_type::iterator begin, cubes_type::iterator end, const std::vector<unsigned>& vars ) const\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/synthesis/esop_synthesis.cpp", "rank": 84, "score": 136099.106328871 }, { "content": "struct cube_is_negative\n\n{\n\n explicit cube_is_negative( unsigned var ) : var( var ) {}\n\n\n\n bool operator()( const cubes_type::value_type& cube ) const\n\n {\n\n return !( cube.first.at( var ) && *cube.first.at( var ) );\n\n }\n\n\n\nprivate:\n\n unsigned var;\n\n};\n\n\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/synthesis/esop_synthesis.cpp", "rank": 85, "score": 136099.106328871 }, { "content": "struct io_tikz_tag_t {};\n", "file_path": "addons/cirkit-addon-reversible/src/cli/reversible_stores.hpp", "rank": 86, "score": 136099.106328871 }, { "content": "struct io_qc_tag_t {};\n", "file_path": "addons/cirkit-addon-reversible/src/cli/reversible_stores.hpp", "rank": 87, "score": 136099.106328871 }, { "content": "struct ncv_quantum_costs {\n\n cost_t operator()(const gate& g, unsigned lines) const;\n\n};\n\n\n\n/**\n\n * @brief Quantum costs from Barenco:1995 based on the Clifford+T Library\n\n *\n\n * Reference: {Barenco, Adriano and Bennett, Charles H and Cleve, Richard\n\n * and DiVincenzo, David P and Margolus, Norman and Shor, Peter\n\n * and Sleator, Tycho and Smolin, John A and Weinfurter, Harald\n\n * Elementary gates for quantum computation\n\n * Physical Review A, 1995\n\n */\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/utils/costs.hpp", "rank": 88, "score": 136099.106328871 }, { "content": "struct sk2013_quantum_costs\n\n{\n\n cost_t operator()( const gate& g, unsigned lines ) const;\n\n};\n\n\n\n/**\n\n * @brief Quantum costs from Barenco:1995 based on the NCV Library\n\n *\n\n * Reference: {Barenco, Adriano and Bennett, Charles H and Cleve, Richard\n\n * and DiVincenzo, David P and Margolus, Norman and Shor, Peter\n\n * and Sleator, Tycho and Smolin, John A and Weinfurter, Harald\n\n * Elementary gates for quantum computation\n\n * Physical Review A, 1995\n\n *\n\n */\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/utils/costs.hpp", "rank": 89, "score": 136099.106328871 }, { "content": "struct io_spec_tag_t {};\n", "file_path": "addons/cirkit-addon-reversible/src/cli/reversible_stores.hpp", "rank": 90, "score": 136099.106328871 }, { "content": "struct io_quipper_tag_t {};\n", "file_path": "addons/cirkit-addon-reversible/src/cli/reversible_stores.hpp", "rank": 91, "score": 136099.106328871 }, { "content": "struct feature\n\n{\n\n uint16_t control = 0u;\n\n uint16_t polarity = 0u;\n\n\n\n feature( gate& g );\n\n feature();\n\n};\n\n\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/optimization/esop_post_optimization.cpp", "rank": 92, "score": 136099.106328871 }, { "content": "struct pair\n\n{\n\n gate f;\n\n gate s;\n\n feature a;\n\n feature b;\n\n circuit const* c = nullptr;\n\n circuit equivalent;\n\n\n\n pair( const gate& f, const gate& s, const circuit& c, feature& a, feature& b );\n\n pair();\n\n\n\n bool computequivalence( unsigned& c1, unsigned& c2, double* t1, double* t2 );\n\n\n\n unsigned long long get_cost();\n\n\n\nprivate:\n\n std::pair<gate, unsigned> single_control{f, 0u};\n\n};\n\n\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/optimization/esop_post_optimization.cpp", "rank": 93, "score": 136099.106328871 }, { "content": "struct io_numpy_tag_t {};\n", "file_path": "addons/cirkit-addon-reversible/src/cli/reversible_stores.hpp", "rank": 94, "score": 136099.106328871 }, { "content": "struct clifford_t_quantum_costs {\n\n cost_t operator()(const gate& g, unsigned lines) const;\n\n};\n\n\n\n/**\n\n * @brief T depth from Barenco:1995 based on the Clifford+T Library\n\n *\n\n * Reference: {Barenco, Adriano and Bennett, Charles H and Cleve, Richard\n\n * and DiVincenzo, David P and Margolus, Norman and Shor, Peter\n\n * and Sleator, Tycho and Smolin, John A and Weinfurter, Harald\n\n * Elementary gates for quantum computation\n\n * Physical Review A, 1995\n\n */\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/utils/costs.hpp", "rank": 95, "score": 136099.106328871 }, { "content": "struct io_real_tag_t {};\n", "file_path": "addons/cirkit-addon-reversible/src/cli/reversible_stores.hpp", "rank": 96, "score": 136099.106328871 }, { "content": "#include <gmpxx.h>\n\n\n\nusing namespace boost::assign;\n\n\n\nnamespace cirkit\n\n{\n\n\n\nvoid count_output_pattern_recurse( DdManager* mgr, DdNode* node, unsigned num_inputs, unsigned num_outputs,\n\n const std::string& pattern, unsigned depth,\n\n std::vector<mpz_class>& counts, std::vector<std::string>& patterns,\n\n bool verbose )\n\n{\n\n if ( Cudd_IsConstant( node ) ) { return; }\n\n\n\n if ( depth == num_outputs )\n\n {\n\n if ( verbose )\n\n {\n\n std::cout << pattern << \" has \" << Cudd_CountMinterm( mgr, node, num_inputs ) << std::endl;\n\n }\n", "file_path": "addons/cirkit-addon-reversible/src/reversible/functions/calculate_additional_lines.cpp", "rank": 97, "score": 59.832802568007025 }, { "content": " using maj_strash_key_t = std::tuple<xmg_function, xmg_function, xmg_function>;\n\n using xor_strash_key_t = std::pair<xmg_function, xmg_function>;\n\n std::unordered_map<maj_strash_key_t, node_t, hash<maj_strash_key_t>> maj_strash;\n\n std::unordered_map<xor_strash_key_t, node_t, hash<xor_strash_key_t>> xor_strash;\n\n\n\n complement_property_map_t _complement;\n\n\n\n /* additional network information */\n\n dirty<std::vector<unsigned>> fanout;\n\n dirty<std::vector<std::vector<node_t>>> parentss;\n\n dirty<std::vector<unsigned>> levels;\n\n\n\n /* network settings and stats */\n\n bool _native_xor = true;\n\n bool _enable_structural_hashing = true;\n\n bool _enable_inverter_propagation = true;\n\n unsigned _num_maj = 0u;\n\n unsigned _num_xor = 0u;\n\n\n\n /* cover */\n", "file_path": "src/classical/xmg/xmg.hpp", "rank": 99, "score": 54.98194654906311 } ]
C++
src/orbital/software/self.cpp
Klern28/orbital
3e0a669e550e1d9a36eef24c9e77f40782bc5381
#include "self.h" #include <orbital/crypto_ps4.h> #include <zlib.h> #include <stdexcept> constexpr U32 SELF_MAGIC = '\x4F\x15\x3D\x1D'; enum SelfEndian { LITTLE = 1, }; enum ProgramAuthID : U64 { PAID_KERNEL = UINT64_C(0x3C00000000000001), }; enum ProgramType : U64 { PTYPE_FAKE = 0x1, PTYPE_NPDRM_EXEC = 0x4, PTYPE_NPDRM_DYNLIB = 0x5, PTYPE_SYSTEM_EXEC = 0x8, PTYPE_SYSTEM_DYNLIB = 0x9, PTYPE_HOST_KERNEL = 0xC, PTYPE_SECURE_MODULE = 0xE, PTYPE_SECURE_KERNEL = 0xF, }; static Key getKey(const SelfInfo& info) { const auto& crypto = ps4Crypto(); switch (info.paid) { case PAID_KERNEL: if (info.version_app >= 0x00000900'00000000) { return crypto.get("self.80010002.900"); } else if (info.version_app >= 0x00000850'00000000) { return crypto.get("self.80010002.8xx"); } else if (info.version_app >= 0x00000800'00000000) { return crypto.get("self.80010002.800"); } else if (info.version_app >= 0x00000750'00000000) { return crypto.get("self.80010002.7xx"); } else if (info.version_app >= 0x00000700'00000000) { return crypto.get("self.80010002.700"); } else if (info.version_app >= 0x00000650'00000000) { return crypto.get("self.80010002.6xx"); } else if (info.version_app >= 0x00000600'00000000) { return crypto.get("self.80010002.600"); } else if (info.version_app >= 0x00000550'00000000) { return crypto.get("self.80010002.550"); } else if (info.version_app >= 0x00000500'00000000) { return crypto.get("self.80010002.500"); } else if (info.version_app >= 0x00000450'00000000) { return crypto.get("self.80010002.450"); } else if (info.version_app >= 0x00000406'00000000) { return crypto.get("self.80010002.406"); } else if (info.version_app >= 0x00000400'00000000) { return crypto.get("self.80010002.400"); } else if (info.version_app >= 0x00000350'00000000) { return crypto.get("self.80010002.350"); } else if (info.version_app >= 0x00000150'00000000) { return crypto.get("self.80010002.1xx"); } else { throw std::runtime_error("Unsupported"); } break; default: throw std::runtime_error("Unsupported"); } } SelfParser::SelfParser(Stream& s) : CfParser(s) { const auto& crypto = ps4Crypto(); s.seek(0, StreamSeek::Set); header = s.read_t<SelfHeader>(); assert(header.magic == SELF_MAGIC); assert(header.version == 0); assert(header.mode == 1); assert(header.endian == SelfEndian::LITTLE); assert(header.attr == 0x12); segments.resize(header.segment_count); s.read(sizeof(SelfSegment) * segments.size(), segments.data()); const auto elf_offset = s.tell(); elf = std::make_unique<ElfParser>(s); const auto ehdr = elf->get_ehdr(); const auto info_offset = elf_offset + ehdr.e_phoff + ehdr.e_phentsize * ehdr.e_phnum; s.seek(align(info_offset, 16), StreamSeek::Set); info = s.read_t<SelfInfo>(); assert(s.tell() == header.header_size, "NPDRM Control Blocks are unsupported"); Buffer buffer(header.meta_size); s.read(buffer.size(), buffer.data()); crypto.decrypt(buffer.data(), buffer.size(), getKey(info)); auto* meta_entries = reinterpret_cast<const SelfMeta*>(&buffer[0]); metas.clear(); for (size_t i = 0; i < header.segment_count; i++) { metas.push_back(meta_entries[i]); } } SelfParser::~SelfParser() { } Elf_Ehdr<> SelfParser::get_ehdr() { return elf->get_ehdr(); } Elf_Phdr<> SelfParser::get_phdr(size_t i) { return elf->get_phdr(i); } Buffer SelfParser::get_pdata(size_t i) { const auto segment_idx = find_segment(i); if (segments[segment_idx].has_blocks()) { return get_segment_blocked(i); } else { return get_segment_nonblocked(i); } } U64 SelfParser::find_segment(U64 phdr_idx) const { for (size_t i = 0; i < header.segment_count; i++) { if (segments[i].id() == phdr_idx) { return i; } } throw std::out_of_range("SELF segment not found"); } Buffer SelfParser::get_segment_blocked(U64 index) { throw std::runtime_error("Unimplemented"); } Buffer SelfParser::get_segment_nonblocked(U64 index) { const auto segment_idx = find_segment(index); const auto& segment = segments[segment_idx]; const auto& meta = metas[segment_idx]; s.seek(segment.offset, StreamSeek::Set); Buffer buffer = s.read_b(segment.mem_size); if (segment.is_encrypted()) { decrypt(buffer, meta); } if (segment.is_compressed()) { const auto size = segment.mem_size; unsigned long cur_zsize = (size & ~0xF) - (size & 0xF); unsigned long cur_usize = segment.file_size; Buffer result(segment.file_size); int zerr = uncompress(result.data(), &cur_usize, buffer.data(), cur_zsize); assert(zerr == 0); buffer = std::move(result); } return buffer; }
#include "self.h" #include <orbital/crypto_ps4.h> #include <zlib.h> #include <stdexcept> constexpr U32 SELF_MAGIC = '\x4F\x15\x3D\x1D'; enum SelfEndian { LITTLE = 1, }; enum ProgramAuthID : U64 { PAID_KERNEL = UINT64_C(0x3C00000000000001), }; enum ProgramType : U64 { PTYPE_FAKE = 0x1, PTYPE_NPDRM_EXEC = 0x4, PTYPE_NPDRM_DYNLIB = 0x5, PTYPE_SYSTEM_EXEC = 0x8, PTYPE_SYSTEM_DYNLIB = 0x9, PTYPE_HOST_KERNEL = 0xC, PTYPE_SECURE_MODULE = 0xE, PTYPE_SECURE_KERNEL = 0xF, }; static Key getKey(const SelfInfo& info) { const auto& crypto = ps4Crypto(); switch (info.paid) { case PAID_KERNEL: if (info.version_app >= 0x00000900'00000000) { return crypto.get("self.80010002.900"); } else if (info.version_app >= 0x00000850'00000000) { return crypto.get("self.80010002.8xx"); } else if (info.version_app >= 0x00000800'00000000) { return crypto.get("self.80010002.800"); } else if (info.version_app >= 0x00000750'00000000) { return crypto.get("self.80010002.7xx"); } else if (info.version_app >= 0x00000700'00000000) { return crypto.get("self.80010002.700"); } else if (info.version_app >= 0x00000650'00000000) { return crypto.get("self.80010002.6xx"); } else if (info.version_app >= 0x00000600'00000000) { return crypto.get("self.80010002.600"); } else if (info.version_app >= 0x00000550'00000000) { return crypto.get("self.80010002.550"); } else if (info.version_app >= 0x00000500'00000000) { return crypto.get("self.80010002.500"); } else if (info.version_app >= 0x00000450'00000000) { return crypto.get("self.80010002.450"); } else if (info.version_app >= 0x00000406'00000000) { return crypto.get("self.80010002.406"); } else if (info.version_app >= 0x00000400'00000000) { return crypto.get("self.80010002.400"); } else if (info.version_app >= 0x00000350'00000000) { return crypto.get("self.80010002.350"); } else if (info.version_app >= 0x00000150'00000000) { return crypto.get("self.80010002.1xx"); } else { throw std::runtime_error("Unsupported"); } break; default: throw std::runtime_error("Unsupported"); } } SelfParser::SelfParser(Stream& s) : CfParser(s) { const auto& cryp
d_segment(index); const auto& segment = segments[segment_idx]; const auto& meta = metas[segment_idx]; s.seek(segment.offset, StreamSeek::Set); Buffer buffer = s.read_b(segment.mem_size); if (segment.is_encrypted()) { decrypt(buffer, meta); } if (segment.is_compressed()) { const auto size = segment.mem_size; unsigned long cur_zsize = (size & ~0xF) - (size & 0xF); unsigned long cur_usize = segment.file_size; Buffer result(segment.file_size); int zerr = uncompress(result.data(), &cur_usize, buffer.data(), cur_zsize); assert(zerr == 0); buffer = std::move(result); } return buffer; }
to = ps4Crypto(); s.seek(0, StreamSeek::Set); header = s.read_t<SelfHeader>(); assert(header.magic == SELF_MAGIC); assert(header.version == 0); assert(header.mode == 1); assert(header.endian == SelfEndian::LITTLE); assert(header.attr == 0x12); segments.resize(header.segment_count); s.read(sizeof(SelfSegment) * segments.size(), segments.data()); const auto elf_offset = s.tell(); elf = std::make_unique<ElfParser>(s); const auto ehdr = elf->get_ehdr(); const auto info_offset = elf_offset + ehdr.e_phoff + ehdr.e_phentsize * ehdr.e_phnum; s.seek(align(info_offset, 16), StreamSeek::Set); info = s.read_t<SelfInfo>(); assert(s.tell() == header.header_size, "NPDRM Control Blocks are unsupported"); Buffer buffer(header.meta_size); s.read(buffer.size(), buffer.data()); crypto.decrypt(buffer.data(), buffer.size(), getKey(info)); auto* meta_entries = reinterpret_cast<const SelfMeta*>(&buffer[0]); metas.clear(); for (size_t i = 0; i < header.segment_count; i++) { metas.push_back(meta_entries[i]); } } SelfParser::~SelfParser() { } Elf_Ehdr<> SelfParser::get_ehdr() { return elf->get_ehdr(); } Elf_Phdr<> SelfParser::get_phdr(size_t i) { return elf->get_phdr(i); } Buffer SelfParser::get_pdata(size_t i) { const auto segment_idx = find_segment(i); if (segments[segment_idx].has_blocks()) { return get_segment_blocked(i); } else { return get_segment_nonblocked(i); } } U64 SelfParser::find_segment(U64 phdr_idx) const { for (size_t i = 0; i < header.segment_count; i++) { if (segments[i].id() == phdr_idx) { return i; } } throw std::out_of_range("SELF segment not found"); } Buffer SelfParser::get_segment_blocked(U64 index) { throw std::runtime_error("Unimplemented"); } Buffer SelfParser::get_segment_nonblocked(U64 index) { const auto segment_idx = fin
random
[ { "content": "struct Key {\n\n enum Type {\n\n NONE,\n\n AES_128_EBC,\n\n AES_128_CBC,\n\n } type;\n\n\n\n Botan::SymmetricKey key;\n\n Botan::InitializationVector iv;\n\n\n\n Key() : type(NONE) {}\n\n Key(Type type, const void* key_buf, size_t key_len, const void* iv_buf, size_t iv_len)\n\n : type(type), key((const U8*)key_buf, key_len), iv((const U8*)iv_buf, iv_len) {\n\n }\n\n Key(Type type, std::string_view key, std::string_view iv)\n\n : type(type), key(std::string(key)), iv(std::string(iv)) {\n\n }\n\n};\n\n\n", "file_path": "src/orbital/crypto.h", "rank": 2, "score": 126619.02313683904 }, { "content": "const Crypto& ps4Crypto();\n", "file_path": "src/orbital/crypto_ps4.h", "rank": 4, "score": 91847.0847283303 }, { "content": "struct OffsetRange {\n\n uint64_t base;\n\n uint64_t size;\n\n\n\n constexpr OffsetRange(uint64_t base, uint64_t size)\n\n : base(base), size(size) {\n\n }\n\n constexpr bool contains(uint64_t off) const noexcept {\n\n return (base <= off) && (off < base + size);\n\n }\n", "file_path": "src/orbital/offset_range.h", "rank": 5, "score": 81730.7374976328 }, { "content": "class Crypto : public CryptoVault {\n\npublic:\n\n /**\n\n * Decrypt typed data with specified key.\n\n * @tparam T Type of the data to decrypt\n\n * @param[in] value Typed value to decrypt\n\n * @param[in] key Unique identifier of key in vault\n\n */\n\n template <typename T>\n\n T decrypt(const T& value, std::string_view key) const {\n\n return decrypt<T>(value, get(key));\n\n }\n\n\n\n /**\n\n * Read and decrypt typed data with specified key.\n\n * @tparam T Type of the data to decrypt\n\n * @param[in] s Stream to read encrypted typed data from\n\n * @param[in] key Unique identifier of key in vault\n\n */\n\n template <typename T>\n", "file_path": "src/orbital/crypto.h", "rank": 6, "score": 80792.43718746952 }, { "content": " uint8_t key[0x10];\n", "file_path": "tools/dumper/source/ksdk_sbl.h", "rank": 7, "score": 80662.50707856947 }, { "content": " Bitrange<U64, 0, 16> offset;\n", "file_path": "src/orbital/hardware/liverpool/gca/pm4.h", "rank": 8, "score": 79656.17924586838 }, { "content": "struct AeoliaNVS {\n\n union {\n\n U08 data[0x400];\n\n union {\n\n // [0x9B330, 0x9B34F]\n\n NVS_RANGE(0x000, 0x20) OsBootParameter;\n\n // [0x9B350, 0x9B38F]\n\n NVS_RANGE(0x000, 0x40) LsiBootParameter;\n\n // [0x9B390, 0x9B48F]\n\n NVS_RANGE(0x300, 0x100) BiosConfig;\n\n // [0x9B6E4, 0x9B743]\n\n NVS_RANGE(0x200, 0x60) EapPartitionKey;\n\n // 0x9B6DD\n\n NVS_RANGE(0x065, 0x1) CsBackupMode;\n\n // 0x9B6DE\n\n NVS_RANGE(0x0C0, 0x2) TempSlewRate;\n\n };\n\n };\n\n\n\n AeoliaNVS() {\n\n memset(data, 0, sizeof(data));\n\n\n\n OsBootParameter.data[0x18] = 2; // sceKernelHwHasWlanBt second bit as 1 for none\n\n BiosConfig.data[0] = 0xF0; // verbose ubios boot\n\n }\n\n\n", "file_path": "src/orbital/hardware/aeolia/nvs/aeolia_nvs.h", "rank": 9, "score": 78718.43502368708 }, { "content": "struct SelfInfo {\n\n LE<U64> paid; // Program Authority ID\n\n LE<U64> ptype; // Program Type\n\n LE<U64> version_app; // Application Version\n\n LE<U64> version_fw; // Firmware Version\n\n U08 digest[0x20];\n\n};\n\n\n", "file_path": "src/orbital/software/self.h", "rank": 10, "score": 75479.71197644131 }, { "content": "enum PupEndian {\n\n LITTLE = 1,\n\n};\n\n\n", "file_path": "src/orbital/software/pup.cpp", "rank": 11, "score": 74316.43692397267 }, { "content": "enum PupFlags {\n\n JIG = 1,\n\n};\n\n\n\n// PUP parser\n\nPupParser::PupParser(Stream& s, bool verify) : CfParser(s) {\n\n Buffer buffer;\n\n const auto& crypto = ps4Crypto();\n\n\n\n // Read and verify PUP header\n\n s.seek(0, StreamSeek::Set);\n\n header = s.read_t<PupHeader>();\n\n assert(header.magic == PUP_MAGIC);\n\n assert(header.version == 0);\n\n assert(header.mode == 1);\n\n assert(header.endian == PupEndian::LITTLE);\n\n assert(header.attr == 0x12);\n\n\n\n // Discard unsupported flags\n\n assert((header.flags & PupFlags::JIG) == 0, \"Unsupported JIG flag\");\n", "file_path": "src/orbital/software/pup.cpp", "rank": 12, "score": 74316.43692397267 }, { "content": "enum VulkanManagerMode {\n\n VULKAN_MANAGER_CREATE,\n\n VULKAN_MANAGER_REUSE,\n\n};\n\n\n", "file_path": "src/orbital/host/graphics/vulkan.h", "rank": 13, "score": 73211.84188991266 }, { "content": "enum HPETGeneralReg {\n\n HPET_REG_CAP = 0x00,\n\n HPET_REG_CFG = 0x10,\n\n HPET_REG_IS = 0x20,\n\n HPET_REG_CNT = 0xF0,\n\n};\n\n\n", "file_path": "src/orbital/hardware/aeolia/hpet/aeolia_hpet.cpp", "rank": 14, "score": 70201.4872298204 }, { "content": "enum HPETTimerReg {\n\n HPET_REG_TNCFG_0 = 0x00,\n\n HPET_REG_TNCFG_1 = 0x04,\n\n HPET_REG_TNCMP_0 = 0x08,\n\n HPET_REG_TNCMP_1 = 0x0C,\n\n HPET_REG_TNROUTE_0 = 0x10,\n\n HPET_REG_TNROUTE_1 = 0x14,\n\n};\n\n\n\nAeoliaHpet::AeoliaHpet(ContainerSpace* mem, const AeoliaHpetConfig& config)\n\n : Device(nullptr, config), mem(mem) {\n\n // Initialize MMIO\n\n mmio = new MemorySpace(this, 0x1000, {\n\n static_cast<MemorySpaceReadOp>(&AeoliaHpet::mmio_read),\n\n static_cast<MemorySpaceWriteOp>(&AeoliaHpet::mmio_write),\n\n });\n\n mem->addSubspace(mmio, config.base);\n\n\n\n // Create timers\n\n assert_true(config.count >= 3);\n", "file_path": "src/orbital/hardware/aeolia/hpet/aeolia_hpet.cpp", "rank": 15, "score": 70201.4872298204 }, { "content": "// ELF conversion\n\nenum class ElfType {\n\n LE_32,\n\n BE_32,\n\n LE_64,\n\n BE_64,\n\n};\n\n\n", "file_path": "src/orbital/software/elf.h", "rank": 16, "score": 68951.77951778917 }, { "content": "class CryptoVault {\n\n std::map<std::string, Key> keys;\n\n\n\npublic:\n\n /**\n\n * Add named key to the vault.\n\n * @param[in] name Unique key identifier\n\n * @param[in] key Key data\n\n */\n\n void add(std::string_view name, Key key) {\n\n std::string k(name);\n\n keys[k] = key;\n\n }\n\n\n\n /**\n\n * Get key by name.\n\n * @param[in] name Unique key identifier\n\n */\n\n const Key& get(std::string_view name) const {\n\n std::string k(name);\n", "file_path": "src/orbital/crypto.h", "rank": 17, "score": 57439.591720265824 }, { "content": "class CryptoStream : public Stream {\n\n Stream& s;\n\n Key key;\n\n\n\npublic:\n\n CryptoStream(Stream& s, const Key& key) : s(s), key(key) {}\n\n\n\n // Interface\n\n virtual U64 read(U64 size, void* buffer) override;\n\n virtual U64 write(U64 size, const void* buffer) override;\n\n virtual void seek(U64 offset, StreamSeek mode) override;\n\n virtual U64 tell() const override;\n\n};\n\n\n", "file_path": "src/orbital/crypto.h", "rank": 18, "score": 55646.1962063667 }, { "content": " * @param[in] key Decryption key\n\n */\n\n static void decrypt(const void* input_buf, size_t input_len,\n\n void* output_buf, size_t output_len, Key key);\n\n\n\n /**\n\n * Decrypt buffer with specified key.\n\n */\n\n static Buffer decrypt(const Buffer& buffer, Key key);\n\n\n\n /**\n\n * Decrypt stream with specified key.\n\n */\n\n static CryptoStream decrypt(Stream& s, Key key);\n\n};\n", "file_path": "src/orbital/crypto.h", "rank": 19, "score": 49958.49752462618 }, { "content": " T decrypt(Stream& s, std::string_view key) const {\n\n return decrypt<T>(s, get(key));\n\n }\n\n\n\n // Static methods\n\n\n\n /**\n\n * Decrypt typed data with specified key.\n\n */\n\n template <typename T>\n\n static T decrypt(const T& value, Key key) {\n\n T output = {};\n\n decrypt(&value, sizeof(T), &output, sizeof(T), key);\n\n return output;\n\n }\n\n\n\n /**\n\n * Read and decrypt typed data with specified key.\n\n */\n\n template <typename T>\n", "file_path": "src/orbital/crypto.h", "rank": 20, "score": 49954.61093128656 }, { "content": " static T decrypt(Stream& s, Key key) {\n\n T output = s.read_t<T>();\n\n decrypt(&output, sizeof(T), key);\n\n return output;\n\n }\n\n\n\n /**\n\n * Decrypt buffer in-place with specified key.\n\n * @param[in,out] buf Pointer to input/output data\n\n * @param[in,out] len Input/Output length in bytes\n\n * @param[in] key Decryption key\n\n */\n\n static void decrypt(void* buf, size_t len, Key key);\n\n\n\n /**\n\n * Decrypt buffer with specified key.\n\n * @param[in] input_buf Pointer to input data\n\n * @param[in] input_len Input length in bytes\n\n * @param[out] output_buf Pointer to output data\n\n * @param[out] output_len Output length in bytes\n", "file_path": "src/orbital/crypto.h", "rank": 21, "score": 49953.88725728598 }, { "content": " return keys.at(k);\n\n }\n\n\n\n /**\n\n * Remove key by name.\n\n * @param[in] name Unique key identifier\n\n */\n\n void remove(std::string_view name) {\n\n std::string k(name);\n\n keys.erase(k);\n\n }\n\n\n\n /**\n\n * Number of keys in the vault.\n\n */\n\n size_t size() const {\n\n return keys.size();\n\n }\n\n};\n\n\n", "file_path": "src/orbital/crypto.h", "rank": 22, "score": 49950.87753506528 }, { "content": "/**\n\n * Cryptography.\n\n *\n\n * Copyright 2017-2021. Orbital project.\n\n * Released under MIT license. Read LICENSE for more details.\n\n *\n\n * Authors:\n\n * - Alexandro Sanchez Bach <[email protected]>\n\n */\n\n \n\n#pragma once\n\n\n\n#include <orbital/core.h>\n\n\n\n#include <botan/botan.h>\n\n\n\n#include <filesystem>\n\n#include <string>\n\n#include <string_view>\n\n#include <unordered_map>\n\n\n", "file_path": "src/orbital/crypto.h", "rank": 23, "score": 49950.66583054152 }, { "content": "}\n\n\n\nvoid CryptoStream::seek(U64 offset, StreamSeek mode) {\n\n s.seek(offset, mode);\n\n}\n\n\n\nU64 CryptoStream::tell() const {\n\n return s.tell();\n\n}\n\n\n\nvoid Crypto::decrypt(void* buf, size_t len, Key key) {\n\n Crypto::decrypt(buf, len, buf, len, key);\n\n}\n\n\n\nvoid Crypto::decrypt(const void* input_buf, size_t input_len,\n\n void* output_buf, size_t output_len, Key key) {\n\n const char* algo;\n\n switch (key.type) {\n\n case Key::AES_128_EBC:\n\n algo = \"AES-128/EBC\";\n", "file_path": "src/orbital/crypto.cpp", "rank": 24, "score": 48602.41007807528 }, { "content": "/**\n\n * Cryptography.\n\n *\n\n * Copyright 2017-2021. Orbital project.\n\n * Released under MIT license. Read LICENSE for more details.\n\n *\n\n * Authors:\n\n * - Alexandro Sanchez Bach <[email protected]>\n\n */\n\n\n\n#include \"crypto.h\"\n\n\n\n#include <stdexcept>\n\n\n\nU64 CryptoStream::read(U64 size, void* buffer) {\n\n return 0;\n\n}\n\n\n\nU64 CryptoStream::write(U64 size, const void* buffer) {\n\n return 0;\n", "file_path": "src/orbital/crypto.cpp", "rank": 25, "score": 48600.801010046096 }, { "content": " break;\n\n case Key::AES_128_CBC:\n\n algo = \"AES-128/CBC/CTS\";\n\n break;\n\n default:\n\n throw std::invalid_argument(\"Unrecognized key type\");\n\n }\n\n auto cipher = Botan::get_cipher(algo, key.key, key.iv, Botan::Cipher_Dir::DECRYPTION);\n\n Botan::Pipe pipe(cipher);\n\n pipe.start_msg();\n\n pipe.write((const uint8_t*)input_buf, input_len);\n\n pipe.end_msg();\n\n pipe.read((uint8_t*)output_buf, output_len);\n\n}\n\n\n\nBuffer Crypto::decrypt(const Buffer& buffer, Key key) {\n\n Buffer output(buffer.size());\n\n decrypt(buffer.data(), buffer.size(), output.data(), output.size(), key);\n\n return output;\n\n}\n\n\n\nCryptoStream Crypto::decrypt(Stream& s, Key key) {\n\n return CryptoStream(s, key);\n\n}\n", "file_path": "src/orbital/crypto.cpp", "rank": 26, "score": 48600.59428595044 }, { "content": "/**\n\n * PS4 cryptography.\n\n *\n\n * Copyright 2017-2021. Orbital project.\n\n * Released under MIT license. Read LICENSE for more details.\n\n *\n\n * Authors:\n\n * - Alexandro Sanchez Bach <[email protected]>\n\n */\n\n\n\n#include \"crypto.h\"\n\n\n\n#include <rapidjson/document.h>\n\n#include <rapidjson/istreamwrapper.h>\n\n\n\n#include <fstream>\n\n#include <stdexcept>\n\n\n\nstatic Crypto g_ps4Crypto;\n\n\n", "file_path": "src/orbital/crypto_ps4.cpp", "rank": 27, "score": 47311.02203661777 }, { "content": "static Key parseAesKey(Key::Type type, const rapidjson::Value& value) {\n\n auto key = value[\"aes_key\"].GetString();\n\n auto iv = value[\"aes_iv\"].GetString();\n\n return Key(type, key, iv);\n\n}\n\n\n\nconst Crypto& ps4Crypto() {\n\n if (g_ps4Crypto.size() > 0) {\n\n return g_ps4Crypto;\n\n }\n\n\n\n // Parse keys from hardcoded file\n\n std::ifstream ifs(\"crypto/keys.json\");\n\n rapidjson::IStreamWrapper isw(ifs);\n\n rapidjson::Document document;\n\n document.ParseStream(isw);\n\n\n\n // Add individual keys\n\n g_ps4Crypto.add(\"pup.hdr\",\n\n parseAesKey(Key::AES_128_CBC, document[\"pup\"][\"hdr\"]));\n", "file_path": "src/orbital/crypto_ps4.cpp", "rank": 28, "score": 47310.68383057247 }, { "content": " g_ps4Crypto.add(\"pup.root_key\",\n\n parseAesKey(Key::AES_128_CBC, document[\"pup\"][\"root_key\"]));\n\n\n\n for (const auto& m : document[\"self\"][\"80010002\"].GetObject()) {\n\n std::string name = \"self.80010002.\";\n\n g_ps4Crypto.add(name + m.name.GetString(), parseAesKey(Key::AES_128_CBC, m.value));\n\n }\n\n\n\n return g_ps4Crypto;\n\n}\n", "file_path": "src/orbital/crypto_ps4.cpp", "rank": 29, "score": 47307.66440379626 }, { "content": "\tElf64_Xword\tr_info;\t\t/* Relocation type and symbol index. */\n", "file_path": "tools/dumper/source/elf64.h", "rank": 30, "score": 43803.05591974685 }, { "content": "\tElf64_Xword \tm_info;\t\t/* size + index */\n", "file_path": "tools/dumper/source/elf64.h", "rank": 31, "score": 43803.05591974685 }, { "content": "\tElf32_Word\tr_info;\t\t/* Relocation type and symbol index. */\n", "file_path": "tools/dumper/source/elf32.h", "rank": 32, "score": 43803.05591974685 }, { "content": "\tElf32_Word \tm_info;\t\t/* size + index */\n", "file_path": "tools/dumper/source/elf32.h", "rank": 33, "score": 43803.05591974685 }, { "content": "\tunsigned char\tst_info;\t/* Type and binding information. */\n", "file_path": "tools/dumper/source/elf32.h", "rank": 34, "score": 42752.226785497165 }, { "content": "\tunsigned char\tst_info;\t/* Type and binding information. */\n", "file_path": "tools/dumper/source/elf64.h", "rank": 35, "score": 42752.226785497165 }, { "content": "\tElf32_Word\tsh_info;\t/* Depends on section type. */\n", "file_path": "tools/dumper/source/elf32.h", "rank": 36, "score": 42752.226785497165 }, { "content": "\tElf64_Word\tsh_info;\t/* Depends on section type. */\n", "file_path": "tools/dumper/source/elf64.h", "rank": 37, "score": 42752.226785497165 }, { "content": " uint32_t key_type;\n", "file_path": "tools/dumper/source/self_decrypter.h", "rank": 38, "score": 41792.59279867457 }, { "content": " uint32_t key_id;\n", "file_path": "tools/dumper/source/ksdk_sbl.h", "rank": 39, "score": 41792.59279867457 }, { "content": " struct self_auth_info_t auth_info;\n", "file_path": "tools/dumper/source/self_decrypter.h", "rank": 40, "score": 41750.63494108576 }, { "content": "#define SELF_KEY_SIZE 0x10\n", "file_path": "tools/dumper/source/self_decrypter.c", "rank": 41, "score": 40835.89641388528 }, { "content": "#ifndef SELF_DECRYPTER_H\n\n#define SELF_DECRYPTER_H\n\n\n\n#include \"ksdk.h\"\n\n\n\n#include \"elf32.h\"\n\n#include \"elf64.h\"\n\n\n\n// Format\n\ntypedef struct self_entry_t {\n\n uint32_t props;\n\n uint32_t reserved;\n\n uint64_t offset;\n\n uint64_t filesz;\n\n uint64_t memsz;\n\n} self_entry_t;\n\n\n\ntypedef struct self_header_t {\n\n uint32_t magic;\n\n uint8_t version;\n\n uint8_t mode;\n\n uint8_t endian;\n\n uint8_t attr;\n\n uint32_t key_type;\n\n uint16_t header_size;\n\n uint16_t meta_size;\n\n uint64_t file_size;\n\n uint16_t num_entries;\n\n uint16_t flags;\n\n uint32_t reserved;\n\n self_entry_t entries[0];\n\n} self_header_t;\n\n\n\n// Context\n\nstruct self_auth_info_t {\n\n uint8_t buf[0x88];\n\n};\n\n\n\ntypedef struct self_t {\n\n int fd;\n\n char *file_path;\n\n size_t file_size;\n\n size_t entries_size;\n\n size_t data_offset;\n\n size_t data_size;\n\n /* contents */\n\n struct self_header_t header;\n\n struct self_entry_t *entries;\n\n uint8_t *data;\n\n /* kernel */\n\n struct self_auth_info_t auth_info;\n\n struct self_context_t *ctx;\n\n int auth_ctx_id;\n\n int ctx_id;\n\n int svc_id;\n\n int verified;\n\n /* blobs */\n\n struct blob_t *blobs;\n\n} self_t;\n\n\n\n/* functions */\n\nself_t* self_open(const char *file);\n\nint self_verify_header(self_t *self);\n\nint self_load_segments(self_t *self);\n\nvoid self_close(self_t *self);\n\n\n", "file_path": "tools/dumper/source/self_decrypter.h", "rank": 42, "score": 40794.89903584515 }, { "content": " uint64_t auth_info_addr;\n", "file_path": "tools/dumper/source/ksdk_sbl.h", "rank": 43, "score": 40794.89903584515 }, { "content": "#define SELF_AUTH_INFO_SIZE 0x88\n", "file_path": "tools/dumper/source/self_decrypter.c", "rank": 44, "score": 39881.94040727142 }, { "content": "static void self_get_block_info(self_t *self, unsigned int target_entry_idx, self_block_info_t *info)\n\n{\n\n struct self_entry_t* table_segment;\n\n struct self_entry_t* target_segment;\n\n struct self_block_extent_t* extents;\n\n const uint8_t* segment_data;\n\n unsigned int target_num_blocks;\n\n unsigned int i;\n\n\n\n memset(&info->digest, 0, sizeof(info->digest));\n\n memset(&info->extent, 0, sizeof(info->extent));\n\n\n\n for (i = 0; i < self->header.num_entries; ++i) {\n\n table_segment = &self->entries[i];\n\n if (!EXTRACT(table_segment->props, SELF_PROPS_HAS_DIGESTS) &&\n\n !EXTRACT(table_segment->props, SELF_PROPS_HAS_EXTENTS))\n\n continue;\n\n if (EXTRACT(table_segment->props, SELF_PROPS_SEGMENT_INDEX) != target_entry_idx)\n\n continue;\n\n\n\n target_segment = &self->entries[target_entry_idx];\n\n target_num_blocks = (target_segment->memsz + (info->size - 1)) / info->size;\n\n segment_data = &self->data[table_segment->offset];\n\n if (EXTRACT(table_segment->props, SELF_PROPS_HAS_DIGESTS)) {\n\n memcpy(&info->digest, &segment_data[info->index * sizeof(info->digest)], sizeof(info->digest));\n\n }\n\n if (EXTRACT(table_segment->props, SELF_PROPS_HAS_EXTENTS)) {\n\n if (EXTRACT(table_segment->props, SELF_PROPS_HAS_DIGESTS))\n\n extents = (void*)(&segment_data[target_num_blocks * sizeof(info->digest)]);\n\n else\n\n extents = (void*)(&segment_data[0]);\n\n memcpy(&info->extent, &extents[info->index], sizeof(info->extent));\n\n }\n\n return;\n\n }\n", "file_path": "tools/dumper/source/self_decrypter.c", "rank": 45, "score": 39881.94040727142 }, { "content": "#define CCP_FLAG_SLOT_KEY 0x40000\n", "file_path": "src/orbital/hardware/liverpool/sam/ccp.h", "rank": 46, "score": 39048.1525174442 }, { "content": " static void* EndianessCopyLittleEndian(void* _dst, void* _src, size_t s, int is_little_endian)\n\n {\n\n if (is_little_endian)\n\n {\n\n return memcpy(_dst, _src, s);\n\n }\n\n else\n\n {\n\n uint8_t* dst = (uint8_t*)_dst;\n\n uint8_t* src = (uint8_t*)_src + s - 1;\n\n for (int i = 0, n = (int)s; i < n; ++i)\n\n memcpy(dst++, src--, 1);\n\n return _dst;\n\n }\n", "file_path": "src/orbital/ui/imgui/widgets/imgui_memory_editor.h", "rank": 47, "score": 37428.14614714086 }, { "content": "struct ImGui_ImplVulkan_InitInfo\n\n{\n\n VkInstance Instance;\n\n VkPhysicalDevice PhysicalDevice;\n\n VkDevice Device;\n\n uint32_t QueueFamily;\n\n VkQueue Queue;\n\n VkPipelineCache PipelineCache;\n\n VkDescriptorPool DescriptorPool;\n\n uint32_t Subpass;\n\n uint32_t MinImageCount; // >= 2\n\n uint32_t ImageCount; // >= MinImageCount\n\n VkSampleCountFlagBits MSAASamples; // >= VK_SAMPLE_COUNT_1_BIT\n\n const VkAllocationCallbacks* Allocator;\n\n void (*CheckVkResultFn)(VkResult err);\n", "file_path": "src/orbital/ui/imgui/imgui_impl_vulkan.h", "rank": 48, "score": 36605.158631800165 }, { "content": "class CfParser {\n\nprotected:\n\n Stream& s;\n\n\n\npublic:\n\n CfParser(Stream& s) : s(s) {}\n\n\n\n static void decrypt(Buffer& data, const CfMeta& meta);\n\n};\n", "file_path": "src/orbital/software/cf.h", "rank": 49, "score": 29402.72158890154 }, { "content": "class SelfParser : public CfParser {\n\n SelfHeader header;\n\n SelfInfo info;\n\n std::vector<SelfSegment> segments;\n\n std::vector<SelfMeta> metas;\n\n std::unique_ptr<ElfParser> elf;\n\n\n\npublic:\n\n SelfParser(Stream& s);\n\n ~SelfParser();\n\n\n\n // ELF parser interface\n\n Elf_Ehdr<> get_ehdr();\n\n\n\n Elf_Phdr<> get_phdr(size_t i);\n\n\n\n Buffer get_pdata(size_t i);\n\n\n\nprivate:\n\n /**\n", "file_path": "src/orbital/software/self.h", "rank": 50, "score": 20322.18115527322 }, { "content": "class PupParser : public CfParser {\n\n PupHeader header;\n\n PupHeaderEx headerEx;\n\n std::vector<PupSegmentEntry> segEntries;\n\n std::vector<PupSegmentMeta> segMetas;\n\n\n\npublic:\n\n /**\n\n * Create PUP parser. \n\n * @param[in] verify Verify digital signatures.\n\n */\n\n PupParser(Stream& s, bool verify=false);\n\n ~PupParser();\n\n\n\n /**\n\n * Get PUP segment by identifier.\n\n * @param[in] id Segment identifier (44-bits).\n\n */\n\n Buffer get(U64 id);\n\n\n", "file_path": "src/orbital/software/pup.h", "rank": 51, "score": 20322.18115527322 }, { "content": " }\n\n }\n\n else {\n\n /* Timer-N access */\n\n const U64 index = (addr - 0x100) / 0x20;\n\n const U64 offset = addr % 0x20;\n\n assert_true(index < timers.size());\n\n const auto& timer = timers[index];\n\n\n\n switch (offset) {\n\n case HPET_REG_TNCFG_0:\n\n value = timer.config.value_lo;\n\n break;\n\n case HPET_REG_TNCFG_1:\n\n value = timer.config.value_hi;\n\n break;\n\n case HPET_REG_TNCMP_0:\n\n value = timer.comparator;\n\n break;\n\n case HPET_REG_TNCMP_1:\n", "file_path": "src/orbital/hardware/aeolia/hpet/aeolia_hpet.cpp", "rank": 52, "score": 17.800756468411777 }, { "content": " value = timer.comparator >> 32;\n\n break;\n\n case HPET_REG_TNROUTE_0:\n\n value = timer.fsb.int_val;\n\n break;\n\n case HPET_REG_TNROUTE_1:\n\n value = timer.fsb.int_addr;\n\n break;\n\n default:\n\n assert_always(\"Invalid register access\");\n\n }\n\n }\n\n return static_cast<U32>(value);\n\n}\n\n\n\nvoid AeoliaHpet::mmio_write(U64 addr, U64 value, U64 size) {\n\n // Sanity checks\n\n assert_true(size == 4);\n\n\n\n if (addr < 0x100) {\n", "file_path": "src/orbital/hardware/aeolia/hpet/aeolia_hpet.cpp", "rank": 53, "score": 17.755988829271743 }, { "content": " // Ignored accesses\n\n case HPET_REG_CAP + 0:\n\n break;\n\n\n\n default:\n\n assert_always(\"Invalid register access\");\n\n }\n\n }\n\n else {\n\n // Timer-N access\n\n const U64 index = (addr - 0x100) / 0x20;\n\n const U64 offset = addr % 0x20;\n\n assert_true(index < timers.size());\n\n auto& tn = timers[index];\n\n\n\n switch (offset) {\n\n case HPET_REG_TNCFG_0:\n\n tn.config.value_lo = value;\n\n break;\n\n case HPET_REG_TNROUTE_0:\n", "file_path": "src/orbital/hardware/aeolia/hpet/aeolia_hpet.cpp", "rank": 54, "score": 17.38329099349554 }, { "content": "U32 SmuDevice::mmio_read(U32 index) {\n\n U32 value = 0;\n\n\n\n switch (index) {\n\n case mmSMC_IND_INDEX:\n\n value = smc_ix;\n\n break;\n\n case mmSMC_IND_DATA:\n\n value = smc_read(smc_ix);\n\n break;\n\n default:\n\n assert_always(\"Unimplemented\");\n\n }\n\n\n\n return value;\n\n}\n\n\n\nvoid SmuDevice::mmio_write(U32 index, U32 value) {\n\n switch (index) {\n\n case mmSMC_IND_INDEX:\n", "file_path": "src/orbital/hardware/liverpool/smu/smu.cpp", "rank": 55, "score": 16.834625942029366 }, { "content": " s.seek(base + offset, StreamSeek::Set);\n\n size = std::min<U32>(size, this->size - offset);\n\n\n\n U64 nbytes = s.read(size, buffer);\n\n offset += nbytes;\n\n return nbytes;\n\n}\n\n\n\nU64 BlsStream::write(U64 size, const void* buffer) {\n\n throw std::runtime_error(\"Unsupported method\");\n\n}\n\n\n\nvoid BlsStream::seek(U64 offset, StreamSeek mode) {\n\n switch (mode) {\n\n case StreamSeek::Set:\n\n this->offset = offset;\n\n break;\n\n case StreamSeek::Cur:\n\n this->offset += offset;\n\n break;\n", "file_path": "src/orbital/software/bls.cpp", "rank": 56, "score": 16.790604910472105 }, { "content": " smc_ix = value;\n\n break;\n\n case mmSMC_IND_DATA:\n\n smc_write(smc_ix, value);\n\n break;\n\n default:\n\n assert_always(\"Unimplemented\");\n\n }\n\n}\n\n\n\nU32 SmuDevice::smc_read(U32 index) {\n\n U32 value = 0;\n\n\n\n switch (index) {\n\n // Clocks\n\n case ixCG_SCLK_STATUS:\n\n value = 0x1;\n\n break;\n\n case ixCG_LCLK_STATUS:\n\n value = 0x1;\n", "file_path": "src/orbital/hardware/liverpool/smu/smu.cpp", "rank": 57, "score": 16.228077502766517 }, { "content": " (U32&)config_mask[0xE4] = ~0xFF;\n\n}\n\n\n\nvoid LiverpoolRCDevice::config_write(U32 offset, U64 value, size_t size) {\n\n U32 smc_ix;\n\n switch (offset) {\n\n case D0F0xBC:\n\n assert(size == 4);\n\n smc_ix = (U32&)config_data[D0F0xB8];\n\n smu->smc_write(smc_ix, value);\n\n break;\n\n default:\n\n PCIDevice::config_write(offset, value, size);\n\n }\n\n}\n\n\n\nU64 LiverpoolRCDevice::config_read(U32 offset, size_t size) {\n\n U64 value = 0;\n\n\n\n U32 smc_ix;\n", "file_path": "src/orbital/hardware/liverpool/liverpool_rc.cpp", "rank": 58, "score": 16.14756881677502 }, { "content": " return;\n\n }\n\n\n\n auto data = func_data[func];\n\n switch (func) {\n\n case 0:\n\n assert(sub < 4);\n\n data |= func0_data_lo[sub];\n\n break;\n\n case 1:\n\n assert(sub < 4);\n\n data |= func1_data_lo[sub];\n\n break;\n\n case 2:\n\n assert(sub < 4);\n\n data |= func2_data_lo[sub];\n\n break;\n\n case 3:\n\n assert(sub < 4);\n\n data |= func3_data_lo[sub];\n", "file_path": "src/orbital/hardware/aeolia/msic/aeolia_msic.cpp", "rank": 59, "score": 16.031932182851097 }, { "content": " advfault_cntl = 0;\n\n}\n\n\n\nU32 IhDevice::mmio_read(U32 index) {\n\n U32 value = 0;\n\n\n\n switch (index) {\n\n case mmIH_RB_BASE:\n\n value = rb_base;\n\n break;\n\n case mmIH_RB_WPTR:\n\n value = rb_wptr;\n\n break;\n\n case mmIH_RB_WPTR_ADDR_LO:\n\n value = rb_wptr_addr_lo;\n\n break;\n\n case mmIH_RB_WPTR_ADDR_HI:\n\n value = rb_wptr_addr_hi;\n\n break;\n\n case mmIH_STATUS:\n", "file_path": "src/orbital/hardware/liverpool/oss/ih.cpp", "rank": 60, "score": 16.01304746288052 }, { "content": " value = status;\n\n break;\n\n default:\n\n assert_always(\"Unimplemented\");\n\n }\n\n\n\n return value;\n\n}\n\n\n\nvoid IhDevice::mmio_write(U32 index, U32 value) {\n\n switch (index) {\n\n case mmIH_RB_CNTL:\n\n rb_cntl = value;\n\n break;\n\n case mmIH_RB_BASE:\n\n rb_base = value;\n\n break;\n\n case mmIH_RB_WPTR:\n\n rb_wptr = value;\n\n break;\n", "file_path": "src/orbital/hardware/liverpool/oss/ih.cpp", "rank": 61, "score": 16.005481664149414 }, { "content": "}\n\n\n\nvoid AeoliaPCIeDevice::bar0_write(U64 addr, U64 value, U64 size) {\n\n assert_always(\"Unimplemented\");\n\n}\n\n\n\nU64 AeoliaPCIeDevice::bar2_read(U64 addr, U64 size) {\n\n U64 value = 0;\n\n switch (addr) {\n\n case APCIE_RTC_STATUS:\n\n value = 0\n\n | APCIE_RTC_STATUS__BATTERY_OK\n\n | APCIE_RTC_STATUS__CLOCK_OK;\n\n break;\n\n case 0x210:\n\n value = 0x18080; /* check 0xFFFFFFFF82833286 @ 5.00 */\n\n break;\n\n case APCIE_CHIP_ID0:\n\n value = 0x41B30130;\n\n break;\n", "file_path": "src/orbital/hardware/aeolia/aeolia_pcie.cpp", "rank": 62, "score": 15.942134007623423 }, { "content": " // TODO\n\n}\n\n\n\nU64 AeoliaHpet::mmio_read(U64 addr, U64 size) {\n\n U64 value = 0;\n\n\n\n // Sanity checks\n\n assert_true(size == 4);\n\n\n\n if (addr < 0x100) {\n\n /* General access */\n\n switch (addr) {\n\n case HPET_REG_CAP + 0:\n\n value = s.cap.value_lo;\n\n break;\n\n case HPET_REG_CAP + 4:\n\n value = s.cap.value_hi;\n\n break;\n\n case HPET_REG_CFG + 0:\n\n value = s.config.value;\n", "file_path": "src/orbital/hardware/aeolia/hpet/aeolia_hpet.cpp", "rank": 63, "score": 15.851602920029741 }, { "content": " break;\n\n default:\n\n assert_always(\"Unimplemented\");\n\n }\n\n\n\n return value;\n\n}\n\n\n\nvoid SamDevice::mmio_write(U32 index, U32 value) {\n\n switch (index) {\n\n case mmSAM_IX_INDEX:\n\n ix_index = value;\n\n break;\n\n case mmSAM_IX_DATA:\n\n switch (ix_index) {\n\n case ixSAM_IH_CPU_AM32_INT:\n\n handle_request(value);\n\n break;\n\n case ixSAM_IH_CPU_AM32_INT_CTX_HIGH:\n\n ih_cpu_am32_int_ctx_high = value;\n", "file_path": "src/orbital/hardware/liverpool/sam/sam.cpp", "rank": 64, "score": 15.820750029780257 }, { "content": " switch (index) {\n\n case mmCP_RB0_BASE:\n\n cp_rb[0].base = U64(value) << 8;\n\n break;\n\n case mmCP_RB1_BASE:\n\n cp_rb[1].base = U64(value) << 8;\n\n break;\n\n case mmCP_RB0_CNTL:\n\n cp_rb[0].cntl = value;\n\n break;\n\n case mmCP_RB1_CNTL:\n\n cp_rb[1].cntl = value;\n\n break;\n\n case mmCP_RB0_RPTR:\n\n cp_rb[0].rptr = value;\n\n break;\n\n case mmCP_RB1_RPTR:\n\n cp_rb[1].rptr = value;\n\n break;\n\n case mmCP_RB0_WPTR:\n", "file_path": "src/orbital/hardware/liverpool/gca/gfx.cpp", "rank": 65, "score": 15.729147611557407 }, { "content": " break;\n\n default:\n\n assert_always(\"Unknown register\");\n\n }\n\n\n\ndone:\n\n return value;\n\n}\n\n\n\nvoid AeoliaUARTDevice::io_write(U64 addr, U64 rawval, U64 size) {\n\n U8 diff;\n\n U8 value = static_cast<U8>(rawval);\n\n\n\n // Sanity checks\n\n assert_true(size == 1);\n\n assert_true(addr < 0x8);\n\n\n\n if (s.lcr & LCR_DLAB) {\n\n switch (addr) {\n\n case UART_REG_DLL:\n", "file_path": "src/orbital/hardware/aeolia/uart/aeolia_uart.cpp", "rank": 66, "score": 15.714308015566692 }, { "content": " if (e.type == SDL_WINDOWEVENT || e.window.windowID == SDL_GetWindowID(window)) {\n\n switch (e.window.event) {\n\n case SDL_WINDOWEVENT_CLOSE:\n\n is_quitting = true;\n\n return;\n\n case SDL_WINDOWEVENT_MINIMIZED:\n\n is_minimized = false;\n\n break;\n\n case SDL_WINDOWEVENT_MAXIMIZED:\n\n is_minimized = false;\n\n break;\n\n case SDL_WINDOWEVENT_EXPOSED:\n\n is_resized = true;\n\n break;\n\n case SDL_WINDOWEVENT_RESIZED:\n\n w = static_cast<int>(e.window.data1);\n\n h = static_cast<int>(e.window.data2);\n\n is_resized = true;\n\n break;\n\n }\n", "file_path": "src/orbital/ui.cpp", "rank": 67, "score": 15.711647235222888 }, { "content": "}\n\n\n\nvoid LiverpoolHDACDevice::reset() {\n\n // PCI Configuration Space\n\n auto& header = config_header();\n\n header.command = PCI_COMMAND_MEMORY; // TODO: Is this needed?\n\n header.header_type |= PCI_HEADER_TYPE_MULTI_FUNCTION;\n\n header.intr_line = 0xFF;\n\n header.intr_pin = 0x02;\n\n msi_enable(1, true);\n\n}\n\n\n\nU64 LiverpoolHDACDevice::mmio_read(U64 addr, U64 size) {\n\n U64 value = 0;\n\n\n\n switch (addr) {\n\n case HDAC_UNK08:\n\n value = 0;\n\n break;\n\n case HDAC_UNK68:\n", "file_path": "src/orbital/hardware/liverpool/liverpool_hdac.cpp", "rank": 68, "score": 15.58802685965836 }, { "content": " case APCIE_CHIP_ID1:\n\n value = 0x52024D44;\n\n break;\n\n case APCIE_CHIP_REV:\n\n value = 0x00000300;\n\n break;\n\n default:\n\n assert_always(\"Unimplemented\");\n\n }\n\n return value;\n\n}\n\n\n\nvoid AeoliaPCIeDevice::bar2_write(U64 addr, U64 value, U64 size) {\n\n assert_always(\"Unimplemented\");\n\n}\n\n\n\nU64 AeoliaPCIeDevice::peripherals_read(U64 addr, U64 size) {\n\n U64 value = 0;\n\n\n\n switch (addr) {\n", "file_path": "src/orbital/hardware/aeolia/aeolia_pcie.cpp", "rank": 69, "score": 15.582563148009939 }, { "content": " const U32 vmid = 8 + index - mmVM_CONTEXT8_PAGE_TABLE_BASE_ADDR;\n\n return vm_contexts[vmid].base >> 12;\n\n }\n\n\n\n U32 value = 0;\n\n switch (index) {\n\n // VM\n\n case mmVM_INVALIDATE_RESPONSE:\n\n value = vm_invalidate_response;\n\n break;\n\n\n\n // MC\n\n case mmMC_BIST_MISMATCH_ADDR:\n\n value = mc_bist_mismatch_addr;\n\n break;\n\n\n\n default:\n\n //assert_always(\"Unimplemented\");\n\n break;\n\n }\n", "file_path": "src/orbital/hardware/liverpool/gmc/gmc.cpp", "rank": 70, "score": 14.960976664085884 }, { "content": " cp_handle_pm4_type0(cp, pm4.type0);\n\n break;\n\n case PM4_PACKET_TYPE1:\n\n cp_handle_pm4_type1(cp, pm4.type1);\n\n break;\n\n case PM4_PACKET_TYPE2:\n\n cp_handle_pm4_type2(cp, pm4.type2);\n\n break;\n\n case PM4_PACKET_TYPE3:\n\n cp_handle_pm4_type3(cp, pm4.type3);\n\n break;\n\n }\n\n}\n\n\n\nvoid GfxDevice::cp_handle_pm4_type0(CpBuffer& cp, PM4Packet::Type0 p) {\n\n const auto size = p.count + 1;\n\n const auto data = cp_read(cp, size);\n\n\n\n U32 index = p.reg;\n\n for (auto reg : data) {\n", "file_path": "src/orbital/hardware/liverpool/gca/gfx.cpp", "rank": 71, "score": 14.795237271497497 }, { "content": " value = 0;\n\n break;\n\n default:\n\n assert_always(\"Unimplemented\");\n\n // TODO: Previous implementation was memory-like.\n\n }\n\n return value;\n\n}\n\n\n\nvoid LiverpoolHDACDevice::mmio_write(U64 addr, U64 value, U64 size) {\n\n switch (addr) {\n\n case HDAC_UNK08:\n\n break;\n\n default:\n\n assert_always(\"Unimplemented\");\n\n // TODO: Previous implementation was memory-like.\n\n }\n\n}\n", "file_path": "src/orbital/hardware/liverpool/liverpool_hdac.cpp", "rank": 72, "score": 14.743410537169472 }, { "content": "\n\n // Determine ELF-type at runtime\n\n switch (e_ident[EI_CLASS]) {\n\n case ELFCLASS32:\n\n switch (e_ident[EI_DATA]) {\n\n case ELFDATA2LSB:\n\n type = ElfType::LE_32;\n\n break;\n\n case ELFDATA2MSB:\n\n type = ElfType::BE_32;\n\n break;\n\n default:\n\n throw std::runtime_error(\"Unimplemented\");\n\n }\n\n break;\n\n case ELFCLASS64:\n\n switch (e_ident[EI_DATA]) {\n\n case ELFDATA2LSB:\n\n type = ElfType::LE_64;\n\n break;\n", "file_path": "src/orbital/software/elf.cpp", "rank": 73, "score": 14.654789293084036 }, { "content": " case CPUBreakpoint::Prot::RWX:\n\n return \"RWX\";\n\n default:\n\n return \"---\";\n\n }\n\n}\n\n\n\nstatic const char* bp_type(CPUBreakpoint::Type type) {\n\n switch (type) {\n\n case CPUBreakpoint::Type::HW:\n\n return \"HW\";\n\n case CPUBreakpoint::Type::SW:\n\n return \"SW\";\n\n case CPUBreakpoint::Type::HV:\n\n return \"HV\";\n\n default:\n\n return \"Auto\";\n\n }\n\n}\n\n\n", "file_path": "src/orbital/ui/tab_cpu.cpp", "rank": 74, "score": 14.434372431440945 }, { "content": "/**\n\n * PUP format.\n\n *\n\n * Copyright 2017-2021. Orbital project.\n\n * Released under MIT license. Read LICENSE for more details.\n\n *\n\n * Authors:\n\n * - Alexandro Sanchez Bach <[email protected]>\n\n */\n\n\n\n#include \"pup.h\"\n\n#include <orbital/crypto_ps4.h>\n\n\n\n#include <zlib.h>\n\n\n\n#include <stdexcept>\n\n\n\nconstexpr U32 PUP_MAGIC = 0x1D3D154F;\n\n\n", "file_path": "src/orbital/software/pup.cpp", "rank": 75, "score": 14.421966548927236 }, { "content": " case 0xC0107074:\n\n case 0xC0107078:\n\n case 0xC010707C:\n\n case 0xC0107080:\n\n case 0xC0107084:\n\n break;\n\n\n\n // Unknown EFUSE registers (Kernel)\n\n case 0xC0104068:\n\n break;\n\n\n\n default:\n\n assert_always(\"Unimplemented\");\n\n break;\n\n }\n\n\n\n return value;\n\n}\n\n\n\nvoid SmuDevice::smc_write(U32 index, U32 value) {\n", "file_path": "src/orbital/hardware/liverpool/smu/smu.cpp", "rank": 76, "score": 14.421290924910322 }, { "content": " value = data_lo[data_lo_index];\n\n }\n\n }\n\n return value;\n\n}\n\n\n\nvoid AeoliaMsic::mmio_write(U32 offset, U32 value) {\n\n U32 data_lo_index;\n\n\n\n switch (offset) {\n\n // Handle global control/status\n\n case REG_MSI_CONTROL:\n\n case REG_MSI_UNK004:\n\n case REG_MSI_UNK008:\n\n break;\n\n\n\n // Handle regular function-specific registers\n\n CASE_FUNCS(W, ADDR, func_addr);\n\n CASE_FUNCS(W, MASK, func_mask);\n\n CASE_FUNCS(W, DATA, func_data);\n", "file_path": "src/orbital/hardware/aeolia/msic/aeolia_msic.cpp", "rank": 77, "score": 14.257850766096562 }, { "content": "}\n\n\n\nvoid AeoliaPCIeDevice::peripherals_write(U64 addr, U64 value, U64 size) {\n\n switch (addr) {\n\n case APCIE_ICC_REG_DOORBELL:\n\n icc_doorbell |= value;\n\n update_icc();\n\n break;\n\n case APCIE_ICC_REG_STATUS:\n\n icc_status &= ~value;\n\n break;\n\n case APCIE_ICC_REG_UNK820:\n\n case APCIE_ICC_REG_IRQ_MASK:\n\n fprintf(stderr, \"AeoliaPCIeDevice::peripherals_write: addr=0x%llX, value=0x%llX, size=0x%llX\\n\", addr, value, size);\n\n break;\n\n default:\n\n if (range_wdt.contains(addr)) {\n\n assert_always(\"Unimplemented\");\n\n }\n\n else if (range_unk1.contains(addr)) {\n", "file_path": "src/orbital/hardware/aeolia/aeolia_pcie.cpp", "rank": 79, "score": 14.103989836098757 }, { "content": "void SamDevice::reset() {\n\n gpr.fill(0);\n\n ih_cpu_am32_int_ctx = 0;\n\n ih_cpu_am32_int_status = 0;\n\n ih_am32_cpu_int_ctx = 0;\n\n\n\n ix_data.fill(0);\n\n sab_ix_data.fill(0);\n\n}\n\n\n\nU32 SamDevice::mmio_read(U32 index) {\n\n U32 value = 0;\n\n\n\n switch (index) {\n\n case mmSAM_IX_INDEX:\n\n value = ix_index;\n\n break;\n\n case mmSAM_IX_DATA:\n\n switch (ix_index) {\n\n case ixSAM_IH_CPU_AM32_INT_CTX_HIGH:\n", "file_path": "src/orbital/hardware/liverpool/sam/sam.cpp", "rank": 80, "score": 14.019935192519963 }, { "content": " const auto& state = c->state();\n\n const auto& space = c->space();\n\n\n\n // Read stack contents\n\n Buffer buf(0x100);\n\n const auto rsp = state.get_linear_rsp();\n\n try {\n\n space->read(rsp, buf.size(), buf.data());\n\n } catch (std::runtime_error& e) {\n\n g_error(\"Error: {}\", e.what());\n\n return;\n\n }\n\n\n\n // Adjust stack view width\n\n switch (c->mode()) {\n\n case X86CPUMode::REAL:\n\n case X86CPUMode::PROTECTED:\n\n case X86CPUMode::LONG_COMPATIBILITY:\n\n me_stack.Cols = 4;\n\n break;\n", "file_path": "src/orbital/ui/tab_cpu.cpp", "rank": 81, "score": 13.713127535275113 }, { "content": "/**\n\n * BLS format.\n\n *\n\n * Copyright 2017-2021. Orbital project.\n\n * Released under MIT license. Read LICENSE for more details.\n\n *\n\n * Authors:\n\n * - Alexandro Sanchez Bach <[email protected]>\n\n */\n\n\n\n#include \"bls.h\"\n\n\n\n#include <stdexcept>\n\n\n\nconstexpr U32 BLS_MAGIC = '2BLS';\n\nconstexpr U64 BLS_BLOCK = 0x200;\n\n\n\nU64 BlsStream::read(U64 size, void* buffer) {\n\n std::unique_lock<std::mutex> lock(bls->mtx);\n\n Stream& s = bls->s;\n", "file_path": "src/orbital/software/bls.cpp", "rank": 83, "score": 13.660183767635491 }, { "content": "#include \"smu/smu.h\"\n\n\n\n#include <array>\n\n#include <memory>\n\n\n\nconstexpr auto LIVERPOOL_GC_DEV = 0x1;\n\nconstexpr auto LIVERPOOL_GC_FNC = 0x0;\n\nconstexpr auto LIVERPOOL_GC_VID = static_cast<PCIVendorId>(0x1002);\n\nconstexpr auto LIVERPOOL_GC_DID = static_cast<PCIDeviceId>(0x9920);\n\n\n", "file_path": "src/orbital/hardware/liverpool/liverpool_gc.h", "rank": 84, "score": 13.641520557605553 }, { "content": "#include <string>\n\n\n\nstatic std::string cpu_name(size_t index) {\n\n return \"CPU #\" + std::to_string(index);\n\n}\n\n\n\nstatic const char* bp_prot(CPUBreakpoint::Prot prot) {\n\n switch (prot) {\n\n case CPUBreakpoint::Prot::R:\n\n return \"R--\";\n\n case CPUBreakpoint::Prot::W:\n\n return \"-W-\";\n\n case CPUBreakpoint::Prot::X:\n\n return \"--X\";\n\n case CPUBreakpoint::Prot::RW:\n\n return \"RW-\";\n\n case CPUBreakpoint::Prot::RX:\n\n return \"R-X\";\n\n case CPUBreakpoint::Prot::WX:\n\n return \"-WX\";\n", "file_path": "src/orbital/ui/tab_cpu.cpp", "rank": 85, "score": 13.578977648530632 }, { "content": " value = 0; // TODO\n\n break;\n\n case mmCP_HQD_ACTIVE:\n\n value = 0; // TODO\n\n break;\n\n\n\n // Ignored access\n\n case mmCP_MEM_SLP_CNTL:\n\n case mmCP_IQ_WAIT_TIME1:\n\n break;\n\n\n\n default:\n\n //assert_always(\"Unimplemented\");\n\n break;\n\n }\n\n\n\n return value;\n\n}\n\n\n\nvoid GfxDevice::mmio_write(U32 index, U32 value) {\n", "file_path": "src/orbital/hardware/liverpool/gca/gfx.cpp", "rank": 86, "score": 13.532558738875471 }, { "content": " value = 0xBD;\n\n break;\n\n case AGBE_DEVICE_REV:\n\n assert(size == 1);\n\n value = 0x00; // TODO\n\n break;\n\n case AGBE_UNK2880:\n\n assert(size == 2);\n\n value = 0x10; // TODO\n\n break;\n\n }\n\n return value;\n\n}\n\n\n\nvoid AeoliaGBEDevice::mmio_write(U64 addr, U64 value, U64 size) {\n\n assert_always(\"Unimplemented\");\n\n}\n", "file_path": "src/orbital/hardware/aeolia/aeolia_gbe.cpp", "rank": 87, "score": 13.442715173722865 }, { "content": "/**\n\n * AMD PM4 packets.\n\n *\n\n * Copyright 2017-2021. Orbital project.\n\n * Released under MIT license. Read LICENSE for more details.\n\n *\n\n * Authors:\n\n * - Alexandro Sanchez Bach <[email protected]>\n\n */\n\n\n\n#include \"pm4.h\"\n\n\n\nconst char* pm4_itop_name(U32 itop) {\n\n#define CASE(itop) case PM4_IT_##itop: return #itop\n\n switch (itop) {\n\n CASE(NOP);\n\n CASE(SET_BASE);\n\n CASE(CLEAR_STATE);\n\n CASE(INDEX_BUFFER_SIZE);\n\n CASE(DISPATCH_DIRECT);\n", "file_path": "src/orbital/hardware/liverpool/gca/pm4.cpp", "rank": 88, "score": 13.344752807146818 }, { "content": " U32 data_lo_index;\n\n U32 value;\n\n\n\n value = 0;\n\n switch (offset) {\n\n // Handle global control/status\n\n case REG_MSI_CONTROL:\n\n case REG_MSI_UNK004:\n\n case REG_MSI_UNK008:\n\n break;\n\n\n\n // Handle regular function-specific registers\n\n CASE_FUNCS(R, ADDR, func_addr);\n\n CASE_FUNCS(R, MASK, func_mask);\n\n CASE_FUNCS(R, DATA, func_data);\n\n\n\n // Handle irregular function-specific registers\n\n default:\n\n data_lo_index = (offset - REG_MSI_FNC0_DATA_LO(0)) >> 2;\n\n if (data_lo_index < 48) {\n", "file_path": "src/orbital/hardware/aeolia/msic/aeolia_msic.cpp", "rank": 89, "score": 13.26402099402677 }, { "content": " mmio_write(index++, reg);\n\n }\n\n}\n\n\n\nvoid GfxDevice::cp_handle_pm4_type1(CpBuffer& cp, PM4Packet::Type1 p) {\n\n assert_always(\"Unsupported packet type\");\n\n}\n\n\n\nvoid GfxDevice::cp_handle_pm4_type2(CpBuffer& cp, PM4Packet::Type2 p) {\n\n assert_always(\"Unsupported packet type\");\n\n}\n\n\n\nvoid GfxDevice::cp_handle_pm4_type3(CpBuffer& cp, PM4Packet::Type3 p) {\n\n const auto rptr_old = cp.rptr;\n\n\n\n switch (p.itop) {\n\n case PM4_IT_INDIRECT_BUFFER_CONST:\n\n cp_handle_pm4_it_indirect_buffer_const(cp);\n\n break;\n\n case PM4_IT_INDIRECT_BUFFER:\n", "file_path": "src/orbital/hardware/liverpool/gca/gfx.cpp", "rank": 90, "score": 13.195346836515228 }, { "content": " cp_handle_pm4_it_indirect_buffer(cp);\n\n break;\n\n case PM4_IT_SET_CONFIG_REG:\n\n case PM4_IT_SET_CONTEXT_REG:\n\n case PM4_IT_SET_SH_REG:\n\n case PM4_IT_SET_UCONFIG_REG:\n\n cp_handle_pm4_it_set_reg(cp, p);\n\n break;\n\n\n\n // Ignored commands\n\n case PM4_IT_PREAMBLE_CNTL:\n\n case PM4_IT_CONTEXT_CONTROL:\n\n case PM4_IT_CLEAR_STATE:\n\n case PM4_IT_SET_BASE:\n\n break;\n\n#if 0\n\n case PM4_IT_DRAW_INDEX_AUTO:\n\n cp_handle_pm4_it_draw_index_auto(s, vmid, packet);\n\n break;\n\n case PM4_IT_EVENT_WRITE_EOP:\n", "file_path": "src/orbital/hardware/liverpool/gca/gfx.cpp", "rank": 91, "score": 13.06823571010183 }, { "content": "}\n\n\n\nvoid GfxDevice::cp_read(CpBuffer& cp, U32* dwords, U32 count) {\n\n auto vm = gmc.get(cp.vmid);\n\n auto va = cp.base | cp.rptr;\n\n const auto size = count * sizeof(U32);\n\n vm.read(va, size, dwords);\n\n cp.rptr += size;\n\n}\n\n\n\nstd::vector<U32> GfxDevice::cp_read(CpBuffer& cp, U32 count) {\n\n std::vector<U32> dwords(count);\n\n cp_read(cp, dwords.data(), dwords.size());\n\n return dwords;\n\n}\n\n\n\nvoid GfxDevice::cp_handle_pm4(CpBuffer& cp) {\n\n auto pm4 = cp_read<PM4Packet>(cp);\n\n switch (pm4.type) {\n\n case PM4_PACKET_TYPE0:\n", "file_path": "src/orbital/hardware/liverpool/gca/gfx.cpp", "rank": 92, "score": 13.059170751965308 }, { "content": " switch (offset) {\n\n case D0F0xBC:\n\n assert(size == 4);\n\n smc_ix = (U32&)config_data[D0F0xB8];\n\n value = smu->smc_read(smc_ix);\n\n break;\n\n default:\n\n value = PCIDevice::config_read(offset, size);\n\n }\n\n\n\n return value;\n\n}\n", "file_path": "src/orbital/hardware/liverpool/liverpool_rc.cpp", "rank": 93, "score": 12.888455928611155 }, { "content": " break;\n\n case 4:\n\n assert(sub < 24);\n\n data |= func4_data_lo[sub];\n\n break;\n\n case 5:\n\n assert(sub < 2);\n\n data |= func5_data_lo[sub];\n\n break;\n\n case 6:\n\n assert(sub < 2);\n\n data |= func6_data_lo[sub];\n\n break;\n\n case 7:\n\n assert(sub < 4);\n\n data |= func7_data_lo[sub];\n\n break;\n\n default:\n\n fprintf(stderr, \"%s: Function #%u out of range!\", __FUNCTION__, func);\n\n return;\n\n }\n\n mem->write<U32>(func_addr[func], data);\n\n}\n", "file_path": "src/orbital/hardware/aeolia/msic/aeolia_msic.cpp", "rank": 94, "score": 12.825965770662467 }, { "content": " case 0x619:\n\n case 0x61B:\n\n case 0x3BD3:\n\n case 0x3BD4:\n\n case 0x3BD5:\n\n break;\n\n\n\n default:\n\n DPRINTF(\"index=0x%llX, size=0x%llX\", index, size);\n\n assert_always(\"Unimplemented\");\n\n value = mmio[index];\n\n }\n\n\n\n return value;\n\n}\n\n\n\nvoid LiverpoolGCDevice::mmio_write(U64 addr, U64 value, U64 size) {\n\n U64 index = addr >> 2;\n\n U64 index_ix = 0;\n\n\n", "file_path": "src/orbital/hardware/liverpool/liverpool_gc.cpp", "rank": 95, "score": 12.743228126634138 }, { "content": " ImGui::Text(\"DCP%d\", i);\n\n ImGui::NextColumn();\n\n }\n\n ImGui::Separator();\n\n for (const auto& attr : dcp_attrs) {\n\n ImGui::Text(\"%s\", attr.name);\n\n ImGui::NextColumn();\n\n for (int i = 0; i < DCP_COUNT; i++) {\n\n int mm_index = attr.mmio_indices[i];\n\n snprintf(tag, sizeof(tag), \"##dcp%d_%s\", i, attr.name);\n\n switch (attr.type) {\n\n case ATTR_U32_DEC:\n\n ImGui::PushItemWidth(-1);\n\n ImGui::InputScalar(tag, ImGuiDataType_U32, &mmio[mm_index], &u32_one, NULL, \"%d\",\n\n ImGuiInputTextFlags_CharsDecimal |\n\n ImGuiInputTextFlags_ReadOnly);\n\n ImGui::PopItemWidth();\n\n break;\n\n case ATTR_U32_HEX:\n\n ImGui::PushItemWidth(-1);\n", "file_path": "src/orbital/ui/tab_gpu.cpp", "rank": 96, "score": 12.728347672521194 }, { "content": " // General access\n\n switch (addr) {\n\n case HPET_REG_CNT + 0:\n\n s.counter.lo = value;\n\n break;\n\n case HPET_REG_CNT + 4:\n\n s.counter.hi = value;\n\n break;\n\n case HPET_REG_CFG + 0:\n\n s.config.value = value;\n\n break;\n\n case HPET_REG_IS + 0:\n\n value &= s.isr.value_lo;\n\n for (int i = 0; i < timers.size(); i++) {\n\n if (value & (1 << i)) {\n\n update_irq(timers[i], i);\n\n }\n\n }\n\n break;\n\n\n", "file_path": "src/orbital/hardware/aeolia/hpet/aeolia_hpet.cpp", "rank": 97, "score": 12.670608287724466 }, { "content": " const auto& crypto = ps4Crypto();\n\n\n\n // Get target segment\n\n const PupSegmentEntry& entry = segEntries[index];\n\n const PupSegmentMeta& meta = segMetas[index];\n\n const auto block_size = entry.block_size();\n\n const auto block_count = entry.block_count();\n\n\n\n // Get information segment\n\n const auto info_index = find_info(index);\n\n const PupSegmentEntry& info_entry = segEntries[info_index];\n\n const PupSegmentMeta& info_meta = segMetas[info_index];\n\n\n\n // Read and process information segment data\n\n Buffer info_buffer(info_entry.file_size);\n\n s.seek(info_entry.offset, StreamSeek::Set);\n\n s.read(info_buffer.size(), info_buffer.data());\n\n if (info_entry.is_encrypted()) {\n\n decrypt(info_buffer, info_meta);\n\n }\n", "file_path": "src/orbital/software/pup.cpp", "rank": 98, "score": 12.576344674880698 }, { "content": " // Add PCIe capability\n\n // TODO: Refactor this code\n\n const auto cap_off = add_capability(PCI_CAP_ID_EXP, 0x14 /* V1 */);\n\n (U16&)config_data[cap_off + 2 /*PCI_EXP_FLAGS*/ ] = 0x0001;\n\n (U32&)config_data[cap_off + 4 /*PCI_EXP_DEVCAP*/] = 0;\n\n (U16&)config_data[cap_off + 8 /*PCI_EXP_DEVCTL*/] = 0;\n\n (U16&)config_data[cap_off + 10 /*PCI_EXP_DEVSTA*/] = 0;\n\n (U32&)config_data[cap_off + 12 /*PCI_EXP_LNKCAP*/] = 0;\n\n (U16&)config_data[cap_off + 16 /*PCI_EXP_LNKCTL*/] = 0;\n\n (U16&)config_data[cap_off + 18 /*PCI_EXP_LNKSTA*/] = 0;\n\n}\n\n\n\nU64 AeoliaGBEDevice::mmio_read(U64 addr, U64 size) {\n\n U64 value = 0;\n\n assert_always(\"Unimplemented\");\n\n\n\n DPRINTF(\"addr=0x%llX, size=0x%llX\\n\", addr, size);\n\n switch (addr) {\n\n case AGBE_DEVICE_ID:\n\n assert(size == 1);\n", "file_path": "src/orbital/hardware/aeolia/aeolia_gbe.cpp", "rank": 99, "score": 12.509224652278615 } ]
C++
include/svg_reader.hpp
phonxvzf/svg2scad
eb458df6cee6a65fbabbe5a5600f50551532adb4
#ifndef SVG_READER_HPP #define SVG_READER_HPP #include <string> #include <memory> #include "svgpp/svgpp.hpp" #include "rapidxml_ns/rapidxml_ns_utils.hpp" #include "svgpp/policy/xml/rapidxml_ns.hpp" #include "math/util.hpp" namespace svg { using namespace math; namespace action { enum type { ACTION_MOVE_TO, ACTION_LINE_TO, ACTION_QUAD_BEZIER_TO, ACTION_CUBIC_BEZIER_TO, ACTION_ELLIPTIC_ARC_TO, ACTION_UNKNOWN }; struct base { virtual ~base() {} }; struct move_to : base { union { vector2f p1, dst; }; move_to() = delete; move_to(const vector2f& _p1) : p1(_p1) {} }; struct line_to : base { union { vector2f p1, dst; }; line_to() = delete; line_to(const vector2f& _p1) : p1(_p1) {} }; struct quadratic_bezier_to : base { vector2f p1; union { vector2f p2, dst; }; quadratic_bezier_to() = delete; quadratic_bezier_to(const vector2f& _p1, const vector2f& _p2) : p1(_p1), p2(_p2) {} }; struct cubic_bezier_to : base { vector2f p1, p2; union { vector2f p3, dst; }; cubic_bezier_to() = delete; cubic_bezier_to(const vector2f& _p1, const vector2f& _p2, const vector2f& _p3) : p1(_p1), p2(_p2), p3(_p3) {} }; struct elliptic_arc_to : base { vector2f r; float x_axis_rotation; union { vector2f p1, dst; }; bool large_arc; bool sweep; elliptic_arc_to() = delete; elliptic_arc_to( const vector2f& _r, float _x_axis_rotation, const vector2f& _p1, bool _large_arc, bool _sweep) : r(_r), x_axis_rotation(_x_axis_rotation), p1(_p1), large_arc(_large_arc), sweep(_sweep) {} }; inline type get_type(const std::shared_ptr<base>& action) { base* base_ptr = action.get(); if (dynamic_cast<move_to*>(base_ptr)) return ACTION_MOVE_TO; if (dynamic_cast<line_to*>(base_ptr)) return ACTION_LINE_TO; if (dynamic_cast<quadratic_bezier_to*>(base_ptr)) return ACTION_QUAD_BEZIER_TO; if (dynamic_cast<cubic_bezier_to*>(base_ptr)) return ACTION_CUBIC_BEZIER_TO; if (dynamic_cast<elliptic_arc_to*>(base_ptr)) return ACTION_ELLIPTIC_ARC_TO; return ACTION_UNKNOWN; } } class reader { private: class context { private: std::vector<std::shared_ptr<action::base>> m_actions; public: context() = default; ~context(); const std::vector<std::shared_ptr<action::base>>& actions() const; void path_move_to(float x, float y, svgpp::tag::coordinate::absolute); void path_line_to(float x, float y, svgpp::tag::coordinate::absolute); void path_quadratic_bezier_to( float x1, float y1, float x, float y, svgpp::tag::coordinate::absolute); void path_cubic_bezier_to( float x1, float y1, float x2, float y2, float x, float y, svgpp::tag::coordinate::absolute); void path_elliptical_arc_to( float rx, float ry, float x_axis_rotation, bool large_arc_flag, bool sweep_flag, float x, float y, svgpp::tag::coordinate::absolute); void path_close_subpath(); void path_exit(); void on_enter_element(svgpp::tag::element::any); void on_exit_element(); static const bool convert_only_rounded_rect_to_path = false; } m_context; float m_width = 0.0f; float m_height = 0.0f; public: reader(); reader(const std::string& fpath); ~reader(); const std::vector<std::shared_ptr<action::base>>& actions() const; const std::vector<std::shared_ptr<action::base>>& load_file(const std::string& fpath); float width() const; float height() const; }; using processed_element_t = boost::mpl::set< svgpp::tag::element::svg, svgpp::tag::element::g, svgpp::tag::element::circle, svgpp::tag::element::ellipse, svgpp::tag::element::line, svgpp::tag::element::path, svgpp::tag::element::polygon, svgpp::tag::element::polyline, svgpp::tag::element::rect >; } #endif
#ifndef SVG_READER_HPP #define SVG_READER_HPP #include <string> #include <memory> #include "svgpp/svgpp.hpp" #include "rapidxml_ns/rapidxml_ns_utils.hpp" #include "svgpp/policy/xml/rapidxml_ns.hpp" #include "math/util.hpp" namespace svg { using namespace math; namespace action { enum type { ACTION_MOVE_TO, ACTION_LINE_TO, ACTION_QUAD_BEZIER_TO, ACTION_CUBIC_BEZIER_TO, ACTION_ELLIPTIC_ARC_TO, ACTION_UNKNOWN }; struct base { virtual ~base() {} }; struct move_to : base { union { vector2f p1, dst; }; move_to() = delete; move_to(const vector2f& _p1) : p1(_p1) {} }; struct line_to : base { union { vector2f p1, dst; }; line_to() = delete; line_to(const vector2f& _p1) : p1(_p1) {} }; struct quadratic_bezier_to : base { vector2f p1; union { vector2f p2, dst; }; quadratic_bezier_to() = delete; quadratic_bezier_to(const vector2f& _p1, const vector2f& _p2) : p1(_p1), p2(_p2) {} }; struct cubic_bezier_to : base { vector2f p1, p2; union { vector2f p3, dst; }; cubic_bezier_to() = delete; cubic_bezier_to(const vector2f& _p1, const vector2f& _p2, const vector2f& _p3) : p1(_p1), p2(_p2), p3(_p3) {} }; struct elliptic_arc_to : base { vector2f r; float x_axis_rotation; union { vector2f p1, dst; }; bool large_arc; bool sweep; elliptic_arc_to() = delete; elliptic_arc_to( const vector2f& _r, float _x_axis_rotation, const vector2f& _p1, bool _large_arc, bool _sweep) : r(_r), x_axis_rotation(_x_axis_rotation), p1(_p1), large_arc(_large_arc), sweep(_sweep) {} }; inline type get_type(const std::shared_ptr<base>& action) { base* base_ptr = action.get(); if (dynamic_cast<move_to*>(base_ptr)) return ACTION_MOVE_T
} class reader { private: class context { private: std::vector<std::shared_ptr<action::base>> m_actions; public: context() = default; ~context(); const std::vector<std::shared_ptr<action::base>>& actions() const; void path_move_to(float x, float y, svgpp::tag::coordinate::absolute); void path_line_to(float x, float y, svgpp::tag::coordinate::absolute); void path_quadratic_bezier_to( float x1, float y1, float x, float y, svgpp::tag::coordinate::absolute); void path_cubic_bezier_to( float x1, float y1, float x2, float y2, float x, float y, svgpp::tag::coordinate::absolute); void path_elliptical_arc_to( float rx, float ry, float x_axis_rotation, bool large_arc_flag, bool sweep_flag, float x, float y, svgpp::tag::coordinate::absolute); void path_close_subpath(); void path_exit(); void on_enter_element(svgpp::tag::element::any); void on_exit_element(); static const bool convert_only_rounded_rect_to_path = false; } m_context; float m_width = 0.0f; float m_height = 0.0f; public: reader(); reader(const std::string& fpath); ~reader(); const std::vector<std::shared_ptr<action::base>>& actions() const; const std::vector<std::shared_ptr<action::base>>& load_file(const std::string& fpath); float width() const; float height() const; }; using processed_element_t = boost::mpl::set< svgpp::tag::element::svg, svgpp::tag::element::g, svgpp::tag::element::circle, svgpp::tag::element::ellipse, svgpp::tag::element::line, svgpp::tag::element::path, svgpp::tag::element::polygon, svgpp::tag::element::polyline, svgpp::tag::element::rect >; } #endif
O; if (dynamic_cast<line_to*>(base_ptr)) return ACTION_LINE_TO; if (dynamic_cast<quadratic_bezier_to*>(base_ptr)) return ACTION_QUAD_BEZIER_TO; if (dynamic_cast<cubic_bezier_to*>(base_ptr)) return ACTION_CUBIC_BEZIER_TO; if (dynamic_cast<elliptic_arc_to*>(base_ptr)) return ACTION_ELLIPTIC_ARC_TO; return ACTION_UNKNOWN; }
function_block-function_prefixed
[ { "content": "struct value_parser<tag::type::string, SVGPP_TEMPLATE_ARGS_PASS>\n\n{\n\n template<class AttributeTag, class Context, class AttributeValue, class PropertySource>\n\n static bool parse(AttributeTag tag, Context & context, AttributeValue const & attribute_value, \n\n PropertySource property_source)\n\n {\n\n typedef detail::value_parser_parameters<Context, SVGPP_TEMPLATE_ARGS_PASS> args_t;\n\n args_t::value_events_policy::set(args_t::value_events_context::get(context), tag, property_source, attribute_value);\n\n return true;\n\n }\n\n};\n\n\n\n}", "file_path": "include/svgpp/parser/string.hpp", "rank": 0, "score": 236280.6541854153 }, { "content": "struct get_viewport_size_source<tag::element::use_, tag::element::svg>\n\n{\n\n typedef tag::viewport_size_source::reference_override_own type;\n\n};\n\n\n\ntemplate<>\n", "file_path": "include/svgpp/adapter/viewport.hpp", "rank": 1, "score": 184513.20181909585 }, { "content": "struct skip_inherit: Base\n\n{\n\n using Base::set;\n\n\n\n template<class AttributeTag>\n\n static void set(Context &, AttributeTag, tag::source::any const &, tag::value::inherit,\n\n typename boost::enable_if<traits::inherited_property<AttributeTag> >::type * = NULL)\n\n {}\n\n\n\n template<class AttributeTag>\n\n static void set(Context &, AttributeTag, tag::source::any const &, tag::value::inherit, tag::source::attribute,\n\n typename boost::enable_if<traits::inherited_property<AttributeTag> >::type * = NULL)\n\n {}\n\n\n\n template<class AttributeTag>\n\n static void set(Context &, AttributeTag, tag::source::any const &, tag::value::inherit, tag::source::css,\n\n typename boost::enable_if<traits::inherited_property<AttributeTag> >::type * = NULL)\n\n {}\n\n};\n\n\n\ntemplate<class Context>\n", "file_path": "include/svgpp/policy/value_events.hpp", "rank": 2, "score": 179816.56954977656 }, { "content": "struct svg_attribute_name_to_id: dictionary_base<attribute_id>\n\n{\n\n template<class Ch>\n\n inline static boost::iterator_range<value_type<Ch> const *> const & get_map();\n\n};\n\n\n", "file_path": "include/svgpp/detail/names_dictionary.hpp", "rank": 3, "score": 168827.10899653847 }, { "content": "struct element_name_to_id: dictionary_base<element_type_id>\n\n{\n\n template<class Ch>\n\n inline static boost::iterator_range<value_type<Ch> const *> const & get_map();\n\n};\n\n\n", "file_path": "include/svgpp/detail/names_dictionary.hpp", "rank": 4, "score": 168677.9461959993 }, { "content": "struct element_iterator<xercesc::DOMNode const *>\n\n : xerces_detail::string_policy\n\n{\n\n typedef xercesc::DOMNode const * iterator_type;\n\n typedef const XMLCh * element_name_type;\n\n typedef const XMLCh * element_text_type;\n\n typedef xerces_detail::attribute_iterator attribute_enumerator_type;\n\n\n\n static void advance_element(iterator_type & xml_node)\n\n {\n\n find_next<false, false>(xml_node);\n\n }\n\n\n\n static void advance_element_or_text(iterator_type & xml_node)\n\n {\n\n find_next<false, true>(xml_node);\n\n }\n\n\n\n static bool is_end(iterator_type xml_node)\n\n {\n", "file_path": "include/svgpp/policy/xml/xerces.hpp", "rank": 5, "score": 162039.5161215817 }, { "content": "struct element_iterator<xercesc::DOMElement const *>\n\n : element_iterator<xercesc::DOMNode const *>\n\n{};\n\n\n\n}}}\n", "file_path": "include/svgpp/policy/xml/xerces.hpp", "rank": 6, "score": 162039.5161215817 }, { "content": "struct value_parser<tag::type::list_of<tag::type::length>, SVGPP_TEMPLATE_ARGS_PASS>\n\n{\n\n template<class AttributeTag, class Context, class AttributeValue, class PropertySource>\n\n static bool parse(AttributeTag tag, Context & context, AttributeValue const & attribute_value, \n\n PropertySource property_source)\n\n {\n\n typedef typename traits::length_dimension_by_attribute<AttributeTag>::type direction_t;\n\n typedef typename boost::range_const_iterator<AttributeValue>::type iterator_t;\n\n return parseT<\n\n detail::length_grammar_tag,\n\n AttributeTag, Context, AttributeValue, PropertySource, direction_t>\n\n (tag, context, attribute_value, property_source);\n\n }\n\n\n\nprotected:\n\n template<class LengthGrammarTag, class AttributeTag, class Context, class AttributeValue, class PropertySource, class Direction>\n\n static bool parseT(AttributeTag tag, Context & context, AttributeValue const & attribute_value, \n\n PropertySource property_source)\n\n {\n\n typedef typename boost::range_const_iterator<AttributeValue>::type iterator_t;\n", "file_path": "include/svgpp/parser/length.hpp", "rank": 7, "score": 161882.61139255483 }, { "content": "struct value_parser<tag::type::list_of<tag::type::number>, SVGPP_TEMPLATE_ARGS_PASS>\n\n{\n\n template<class AttributeTag, class Context, class AttributeValue, class PropertySource>\n\n static bool parse(AttributeTag tag, Context & context, AttributeValue const & attribute_value, \n\n PropertySource property_source)\n\n {\n\n namespace qi = boost::spirit::qi;\n\n\n\n typedef detail::value_parser_parameters<Context, SVGPP_TEMPLATE_ARGS_PASS> args_t;\n\n typedef typename args_t::number_type coordinate_t;\n\n typedef typename boost::range_const_iterator<AttributeValue>::type iterator_t;\n\n typedef qi::real_parser<coordinate_t, detail::number_policies<coordinate_t, PropertySource> > grammar_t;\n\n typedef detail::comma_wsp_rule_no_skip<iterator_t> separator_t;\n\n typedef detail::parse_list_iterator<coordinate_t, iterator_t, grammar_t, separator_t> parse_list_iterator_t;\n\n typedef detail::finite_function_iterator<parse_list_iterator_t> output_iterator_t;\n\n\n\n SVGPP_STATIC_IF_SAFE const grammar_t number_grammar;\n\n SVGPP_STATIC_IF_SAFE const separator_t separator_grammar;\n\n parse_list_iterator_t parse_list(\n\n boost::begin(attribute_value), boost::end(attribute_value), \n", "file_path": "include/svgpp/parser/number.hpp", "rank": 8, "score": 161882.61139255483 }, { "content": "struct attribute_type\n\n{\n\n // By default type is specific to attribute\n\n typedef Attribute type;\n\n};\n\n\n\ntemplate<class Element> struct attribute_type<Element, tag::attribute::x1 > { typedef tag::type::length type; };\n\ntemplate<class Element> struct attribute_type<Element, tag::attribute::y1 > { typedef tag::type::length type; };\n\ntemplate<class Element> struct attribute_type<Element, tag::attribute::x2 > { typedef tag::type::length type; };\n\ntemplate<class Element> struct attribute_type<Element, tag::attribute::y2 > { typedef tag::type::length type; };\n\ntemplate<class Element> struct attribute_type<Element, tag::attribute::width > { typedef tag::type::length type; };\n\ntemplate<class Element> struct attribute_type<Element, tag::attribute::height > { typedef tag::type::length type; };\n\ntemplate<class Element> struct attribute_type<Element, tag::attribute::r > { typedef tag::type::length type; };\n\ntemplate<class Element> struct attribute_type<Element, tag::attribute::rx > { typedef tag::type::length type; };\n\ntemplate<class Element> struct attribute_type<Element, tag::attribute::ry > { typedef tag::type::length type; };\n\ntemplate<class Element> struct attribute_type<Element, tag::attribute::cx > { typedef tag::type::length type; };\n\ntemplate<class Element> struct attribute_type<Element, tag::attribute::cy > { typedef tag::type::length type; };\n\ntemplate<class Element> struct attribute_type<Element, tag::attribute::refX > { typedef tag::type::length type; };\n\ntemplate<class Element> struct attribute_type<Element, tag::attribute::refY > { typedef tag::type::length type; };\n\ntemplate<class Element> struct attribute_type<Element, tag::attribute::markerWidth > { typedef tag::type::length type; };\n\ntemplate<class Element> struct attribute_type<Element, tag::attribute::markerHeight > { typedef tag::type::length type; };\n\ntemplate<class Element> struct attribute_type<Element, tag::attribute::fx > { typedef tag::type::length type; };\n\ntemplate<class Element> struct attribute_type<Element, tag::attribute::fy > { typedef tag::type::length type; };\n\ntemplate<class Element> struct attribute_type<Element, tag::attribute::startOffset > { typedef tag::type::length type; };\n\ntemplate<class Element> struct attribute_type<Element, tag::attribute::textLength > { typedef tag::type::length type; };\n\n\n\ntemplate<class ElementTag, class AttributeTag>\n", "file_path": "include/svgpp/traits/attribute_type.hpp", "rank": 9, "score": 160396.7319435013 }, { "content": "struct value_parser<tag::type::list_of<tag::type::percentage_or_length>, SVGPP_TEMPLATE_ARGS_PASS>\n\n : value_parser<tag::type::list_of<tag::type::length>, SVGPP_TEMPLATE_ARGS_PASS>\n\n{\n\n typedef value_parser<tag::type::list_of<tag::type::length>, SVGPP_TEMPLATE_ARGS_PASS> base_type;\n\n\n\n using base_type::parse;\n\n\n\n template<class AttributeTag, class Context, class AttributeValue, class PropertySource>\n\n static bool parse(AttributeTag tag, Context & context, AttributeValue const & attribute_value, \n\n tag::source::css property_source)\n\n {\n\n typedef typename boost::range_const_iterator<AttributeValue>::type iterator_t;\n\n return base_type::template parseT<\n\n detail::percentage_or_length_grammar_tag,\n\n AttributeTag, Context, AttributeValue, \n\n tag::source::css, \n\n tag::length_dimension::not_width_nor_height>\n\n (tag, context, attribute_value, property_source);\n\n }\n\n};\n\n\n\n}", "file_path": "include/svgpp/parser/percentage_or_length.hpp", "rank": 10, "score": 158384.2906277508 }, { "content": "struct get_viewport_size_source<void, tag::element::svg>\n\n{\n\n typedef tag::viewport_size_source::use_own type;\n\n};\n\n\n\ntemplate<>\n", "file_path": "include/svgpp/adapter/viewport.hpp", "rank": 11, "score": 155669.69674172247 }, { "content": "struct child_element_types;\n\n\n\ntemplate<class ElementTag>\n", "file_path": "include/svgpp/traits/child_element_types.hpp", "rank": 12, "score": 155439.386393058 }, { "content": "struct get_char_type<WCharType, typename boost::enable_if_c<sizeof(WCharType) == 2>::type>\n\n{\n\n typedef wchar_t type;\n\n};\n\n\n", "file_path": "include/svgpp/policy/xml/xerces.hpp", "rank": 13, "score": 154585.52348393877 }, { "content": "struct value_parser<tag::type::integer, SVGPP_TEMPLATE_ARGS_PASS>\n\n{\n\n template<class AttributeTag, class Context, class AttributeValue, class PropertySource>\n\n static bool parse(AttributeTag tag, Context & context, AttributeValue const & attribute_value, \n\n PropertySource property_source)\n\n {\n\n namespace qi = boost::spirit::qi;\n\n\n\n typedef detail::value_parser_parameters<Context, SVGPP_TEMPLATE_ARGS_PASS> args_t;\n\n typedef typename boost::range_const_iterator<AttributeValue>::type iterator_t;\n\n iterator_t it = boost::begin(attribute_value), end = boost::end(attribute_value);\n\n\n\n int value;\n\n if (qi::parse(it, end, qi::int_, value) && it == end)\n\n {\n\n args_t::value_events_policy::set(args_t::value_events_context::get(context), tag, property_source, value);\n\n return true;\n\n }\n\n else\n\n {\n\n return args_t::error_policy::parse_failed(args_t::error_policy_context::get(context), tag, attribute_value);\n\n }\n\n }\n\n};\n\n\n\ntemplate<SVGPP_TEMPLATE_ARGS>\n", "file_path": "include/svgpp/parser/misc.hpp", "rank": 14, "score": 153161.57706227465 }, { "content": "struct value_parser<tag::type::funciri, SVGPP_TEMPLATE_ARGS_PASS>\n\n : detail::iri_value_parser<boost::mpl::quote2<funciri_grammar>, SVGPP_TEMPLATE_ARGS_PASS>\n\n{\n\n};\n\n\n\n}", "file_path": "include/svgpp/parser/iri.hpp", "rank": 15, "score": 153161.57706227462 }, { "content": "struct value_parser<tag::type::angle, SVGPP_TEMPLATE_ARGS_PASS>\n\n{\n\n template<class AttributeTag, class Context, class AttributeValue, class PropertySource>\n\n static bool parse(AttributeTag tag, Context & context, AttributeValue const & attribute_value, \n\n PropertySource source)\n\n {\n\n namespace qi = boost::spirit::qi;\n\n\n\n typedef detail::value_parser_parameters<Context, SVGPP_TEMPLATE_ARGS_PASS> args_t;\n\n typedef typename boost::range_const_iterator<AttributeValue>::type iterator_t;\n\n typedef typename boost::parameter::parameters<\n\n boost::parameter::optional<tag::angle_factory>\n\n >::template bind<SVGPP_TEMPLATE_ARGS_PASS>::type args2_t;\n\n typedef typename detail::unwrap_context<Context, tag::angle_factory>::template bind<args2_t>::type angle_factory_t;\n\n\n\n SVGPP_STATIC_IF_SAFE const angle_grammar<PropertySource, iterator_t, angle_factory_t, typename args_t::number_type> grammar;\n\n iterator_t it = boost::begin(attribute_value), end = boost::end(attribute_value);\n\n typename angle_factory_t::angle_type value;\n\n if (boost::spirit::qi::parse(it, end, grammar, value) \n\n && it == end)\n", "file_path": "include/svgpp/parser/angle.hpp", "rank": 16, "score": 153161.57706227462 }, { "content": "struct value_parser<tag::type::number, SVGPP_TEMPLATE_ARGS_PASS>\n\n{\n\n template<class AttributeTag, class Context, class AttributeValue, class PropertySource>\n\n static bool parse(AttributeTag tag, Context & context, AttributeValue const & attribute_value, \n\n PropertySource property_source)\n\n {\n\n namespace qi = boost::spirit::qi;\n\n\n\n typedef detail::value_parser_parameters<Context, SVGPP_TEMPLATE_ARGS_PASS> args_t;\n\n typedef typename args_t::number_type coordinate_t;\n\n typedef typename boost::range_const_iterator<AttributeValue>::type iterator_t;\n\n\n\n iterator_t it = boost::begin(attribute_value), end = boost::end(attribute_value);\n\n SVGPP_STATIC_IF_SAFE const qi::real_parser<coordinate_t, detail::number_policies<coordinate_t, PropertySource> > number;\n\n coordinate_t value;\n\n if (qi::parse(it, end, number, value) && it == end)\n\n {\n\n args_t::value_events_policy::set(args_t::value_events_context::get(context), tag, property_source, value);\n\n return true;\n\n }\n\n else\n\n {\n\n return args_t::error_policy::parse_failed(args_t::error_policy_context::get(context), tag, attribute_value);\n\n }\n\n }\n\n};\n\n\n\ntemplate<SVGPP_TEMPLATE_ARGS>\n", "file_path": "include/svgpp/parser/number.hpp", "rank": 17, "score": 153161.57706227462 }, { "content": "struct value_parser<tag::type::paint, SVGPP_TEMPLATE_ARGS_PASS>\n\n {\n\n template<class AttributeTag, class Context, class AttributeValue, class PropertySource>\n\n static bool parse(AttributeTag tag, Context & context, AttributeValue const & attribute_value, \n\n PropertySource property_source)\n\n {\n\n typedef typename boost::range_const_iterator<AttributeValue>::type iterator_t;\n\n typedef detail::value_parser_parameters<Context, SVGPP_TEMPLATE_ARGS_PASS> args_t;\n\n typedef typename boost::parameter::parameters<\n\n boost::parameter::optional<tag::color_factory>,\n\n boost::parameter::optional<tag::icc_color_policy>,\n\n boost::parameter::optional<tag::iri_policy>\n\n >::template bind<SVGPP_TEMPLATE_ARGS_PASS>::type args2_t;\n\n typedef typename detail::unwrap_context<Context, tag::color_factory>::template bind<args2_t>::type color_factory_t;\n\n typedef detail::unwrap_context<Context, tag::icc_color_policy> icc_color_context_t;\n\n typedef typename icc_color_context_t::template bind<args2_t>::type icc_color_policy_t;\n\n typedef typename icc_color_policy_t::icc_color_factory_type icc_color_factory_t;\n\n typedef typename detail::unwrap_context<Context, tag::iri_policy>::template bind<args2_t>::type iri_policy_t;\n\n typedef typename args_t::value_events_policy value_events_policy_t;\n\n typename args_t::value_events_context::type & value_events_context = args_t::value_events_context::get(context);\n", "file_path": "include/svgpp/parser/paint.hpp", "rank": 18, "score": 153161.57706227462 }, { "content": "struct value_parser<tag::type::color, SVGPP_TEMPLATE_ARGS_PASS>\n\n{\n\n template<class AttributeTag, class Context, class AttributeValue, class PropertySource>\n\n static bool parse(AttributeTag tag, Context & context, AttributeValue const & attribute_value, \n\n PropertySource property_source)\n\n {\n\n typedef typename boost::range_const_iterator<AttributeValue>::type iterator_t;\n\n typedef detail::value_parser_parameters<Context, SVGPP_TEMPLATE_ARGS_PASS> args_t;\n\n typedef typename boost::parameter::parameters<\n\n boost::parameter::optional<tag::color_factory>\n\n >::template bind<SVGPP_TEMPLATE_ARGS_PASS>::type args2_t;\n\n typedef typename detail::unwrap_context<Context, tag::color_factory>::template bind<args2_t>::type color_factory_t;\n\n\n\n iterator_t it = boost::begin(attribute_value), end = boost::end(attribute_value);\n\n typename color_factory_t::color_type color;\n\n if (detail::parse_color<color_factory_t>(it, end, property_source, color) && it == end)\n\n {\n\n args_t::value_events_policy::set(args_t::value_events_context::get(context), tag, property_source, color);\n\n return true;\n\n }\n\n else\n\n {\n\n return args_t::error_policy::parse_failed(args_t::error_policy_context::get(context), tag, attribute_value);\n\n }\n\n }\n\n};\n\n\n\ntemplate<SVGPP_TEMPLATE_ARGS>\n", "file_path": "include/svgpp/parser/color.hpp", "rank": 19, "score": 153161.57706227462 }, { "content": "struct value_parser<tag::type::iri, SVGPP_TEMPLATE_ARGS_PASS>\n\n : detail::iri_value_parser<boost::mpl::bind1<boost::mpl::quote1<iri_grammar>, boost::mpl::_2>, SVGPP_TEMPLATE_ARGS_PASS>\n\n{\n\n};\n\n\n\ntemplate<SVGPP_TEMPLATE_ARGS>\n", "file_path": "include/svgpp/parser/iri.hpp", "rank": 20, "score": 153161.57706227462 }, { "content": "struct value_parser<tag::type::length, SVGPP_TEMPLATE_ARGS_PASS>\n\n{\n\n template<class AttributeTag, class Context, class AttributeValue, class PropertySource>\n\n static bool parse(AttributeTag tag, Context & context, AttributeValue const & attribute_value, \n\n PropertySource source)\n\n {\n\n typedef typename traits::length_dimension_by_attribute<AttributeTag>::type direction_t;\n\n typedef typename boost::range_const_iterator<AttributeValue>::type iterator_t;\n\n typedef detail::value_parser_parameters<Context, SVGPP_TEMPLATE_ARGS_PASS> args_t;\n\n typedef typename boost::parameter::parameters<\n\n boost::parameter::optional<tag::length_policy>\n\n >::template bind<SVGPP_TEMPLATE_ARGS_PASS>::type args2_t;\n\n typedef typename detail::unwrap_context<Context, tag::length_policy> length_policy_context;\n\n typedef typename length_policy_context::template bind<args2_t>::type length_policy_t;\n\n\n\n typename length_policy_t::length_factory_type & length_factory \n\n = length_policy_t::length_factory(length_policy_context::get(context));\n\n iterator_t it = boost::begin(attribute_value), end = boost::end(attribute_value);\n\n typename length_policy_t::length_factory_type::length_type value;\n\n if (detail::parse_length<direction_t, PropertySource>(length_factory, it, end, value)\n", "file_path": "include/svgpp/parser/length.hpp", "rank": 21, "score": 153161.57706227462 }, { "content": "struct is_context_inexpensively_copyable<const Context>: is_context_inexpensively_copyable<Context>\n\n{};\n\n\n\ntemplate<class Context, class Enable = void>\n", "file_path": "include/svgpp/detail/adapt_context.hpp", "rank": 22, "score": 151389.91213971173 }, { "content": "struct attribute_iterator<rapidxml_ns::xml_attribute<Ch> const *>\n\n{\n\n typedef rapidxml_ns::xml_attribute<Ch> const * iterator_type;\n\n typedef boost::iterator_range<Ch const *> string_type;\n\n typedef string_type attribute_name_type;\n\n typedef string_type attribute_value_type;\n\n typedef string_type saved_value_type;\n\n\n\n static string_type get_string_range(string_type const & str)\n\n { \n\n return str;\n\n }\n\n\n\n static void advance(iterator_type & xml_attribute)\n\n {\n\n xml_attribute = xml_attribute->next_attribute();\n\n }\n\n\n\n static bool is_end(iterator_type xml_attribute)\n\n {\n", "file_path": "include/svgpp/policy/xml/rapidxml_ns.hpp", "rank": 23, "score": 151389.91213971173 }, { "content": "struct element_iterator<rapidxml_ns::xml_node<Ch> const *>\n\n{\n\n typedef rapidxml_ns::xml_node<Ch> const * iterator_type;\n\n typedef boost::iterator_range<Ch const *> string_type;\n\n typedef boost::iterator_range<Ch const *> element_name_type;\n\n typedef boost::iterator_range<Ch const *> element_text_type;\n\n typedef rapidxml_ns::xml_attribute<Ch> const * attribute_enumerator_type;\n\n\n\n static string_type get_string_range(string_type const & str)\n\n { \n\n return str;\n\n }\n\n\n\n static void advance_element(iterator_type & xml_element)\n\n {\n\n xml_element = xml_element->next_sibling(); \n\n find_next<false>(xml_element);\n\n }\n\n\n\n static void advance_element_or_text(iterator_type & xml_element)\n", "file_path": "include/svgpp/policy/xml/rapidxml_ns.hpp", "rank": 24, "score": 151389.91213971173 }, { "content": "struct value_parser<tag::type::clock_value, SVGPP_TEMPLATE_ARGS_PASS>\n\n{\n\n template<class AttributeTag, class Context, class AttributeValue>\n\n static bool parse(AttributeTag tag, Context & context, AttributeValue const & attribute_value, \n\n tag::source::attribute source)\n\n {\n\n namespace qi = boost::spirit::qi;\n\n\n\n typedef typename boost::range_const_iterator<AttributeValue>::type iterator_t;\n\n typedef detail::value_parser_parameters<Context, SVGPP_TEMPLATE_ARGS_PASS> args_t;\n\n\n\n iterator_t it = boost::begin(attribute_value), end = boost::end(attribute_value);\n\n // TODO: own type for clock_value\n\n SVGPP_STATIC_IF_SAFE const clock_value_grammar<iterator_t, typename args_t::number_type> grammar;\n\n typename args_t::number_type value;\n\n if (qi::parse(it, end, grammar, value) && it == end)\n\n {\n\n args_t::value_events_policy::set(args_t::value_events_context::get(context), tag, source, value);\n\n return true;\n\n }\n\n else\n\n {\n\n return args_t::error_policy::parse_failed(args_t::error_policy_context::get(context), tag, attribute_value);\n\n }\n\n return true;\n\n }\n\n};\n\n\n\n}\n", "file_path": "include/svgpp/parser/animation.hpp", "rank": 25, "score": 151067.43682089794 }, { "content": "struct value_parser<tag::type::transform_list, SVGPP_TEMPLATE_ARGS_PASS>\n\n{\n\n template<class AttributeTag, class Context, class AttributeValue>\n\n static bool parse(AttributeTag tag, Context & context, AttributeValue const & attribute_value, \n\n tag::source::attribute)\n\n {\n\n typedef detail::value_parser_parameters<Context, SVGPP_TEMPLATE_ARGS_PASS> args_t;\n\n typedef typename boost::range_const_iterator<AttributeValue>::type iterator_t;\n\n typedef typename boost::parameter::parameters<\n\n boost::parameter::optional<tag::transform_events_policy>\n\n >::template bind<SVGPP_TEMPLATE_ARGS_PASS>::type args2_t;\n\n typedef detail::bind_context_parameters_wrapper<Context, args2_t> context_t;\n\n typedef typename detail::unwrap_context<context_t, tag::transform_events_policy> transform_events_context;\n\n typedef typename transform_events_context::policy transform_events_policy;\n\n typedef detail::transform_adapter_if_needed<context_t> adapted_context_t; \n\n typedef \n\n typename detail::unwrap_context<typename adapted_context_t::adapted_context, tag::transform_events_policy>::policy\n\n adapted_transform_events_policy;\n\n\n\n context_t bound_context(context);\n", "file_path": "include/svgpp/parser/transform_list.hpp", "rank": 26, "score": 149061.32925492615 }, { "content": "struct value_parser<tag::type::path_data, SVGPP_TEMPLATE_ARGS_PASS>\n\n{\n\n template<class AttributeTag, class Context, class AttributeValue>\n\n static bool parse(AttributeTag tag, Context & context, AttributeValue const & attribute_value, \n\n tag::source::attribute)\n\n {\n\n namespace qi = boost::spirit::qi;\n\n\n\n typedef detail::value_parser_parameters<Context, SVGPP_TEMPLATE_ARGS_PASS> args_t;\n\n typedef typename args_t::number_type coordinate_t;\n\n typedef typename boost::range_const_iterator<AttributeValue>::type iterator_t;\n\n\n\n typedef typename boost::parameter::parameters<\n\n boost::parameter::optional<tag::path_events_policy>\n\n >::template bind<SVGPP_TEMPLATE_ARGS_PASS>::type args2_t;\n\n typedef detail::bind_context_parameters_wrapper<Context, args2_t> context_t;\n\n typedef typename detail::unwrap_context<context_t, tag::path_events_policy> path_events_context;\n\n typedef detail::path_adapter_if_needed<context_t> adapted_context_t; \n\n\n\n context_t bound_context(context);\n", "file_path": "include/svgpp/parser/path_data.hpp", "rank": 27, "score": 149061.32925492615 }, { "content": "struct value_parser<tag::type::percentage_or_length, SVGPP_TEMPLATE_ARGS_PASS>\n\n : value_parser<tag::type::length, SVGPP_TEMPLATE_ARGS_PASS>\n\n{\n\n using value_parser<tag::type::length, SVGPP_TEMPLATE_ARGS_PASS>::parse;\n\n\n\n template<class AttributeTag, class Context, class AttributeValue>\n\n static bool parse(AttributeTag tag, Context & context, AttributeValue const & attribute_value, \n\n tag::source::css property_source)\n\n {\n\n typedef typename boost::range_const_iterator<AttributeValue>::type iterator_t;\n\n typedef detail::value_parser_parameters<Context, SVGPP_TEMPLATE_ARGS_PASS> args_t;\n\n typedef typename boost::parameter::parameters<\n\n boost::parameter::optional<tag::length_policy>\n\n >::template bind<SVGPP_TEMPLATE_ARGS_PASS>::type args2_t;\n\n typedef typename detail::unwrap_context<Context, tag::length_policy> length_policy_context;\n\n typedef typename length_policy_context::template bind<args2_t>::type length_policy_t;\n\n\n\n typename length_policy_t::length_factory_type & length_factory \n\n = length_policy_t::length_factory(length_policy_context::get(context));\n\n iterator_t it = boost::begin(attribute_value), end = boost::end(attribute_value);\n", "file_path": "include/svgpp/parser/percentage_or_length.hpp", "rank": 28, "score": 149061.32925492615 }, { "content": "struct value_parser<tag::type::number_optional_number, SVGPP_TEMPLATE_ARGS_PASS>\n\n{\n\n template<class AttributeTag, class Context, class AttributeValue>\n\n static bool parse(AttributeTag tag, Context & context, AttributeValue const & attribute_value, \n\n tag::source::attribute property_source)\n\n {\n\n namespace qi = boost::spirit::qi;\n\n namespace phx = boost::phoenix;\n\n using qi::_1;\n\n\n\n typedef detail::value_parser_parameters<Context, SVGPP_TEMPLATE_ARGS_PASS> args_t;\n\n typedef typename args_t::number_type coordinate_t;\n\n typedef typename boost::range_const_iterator<AttributeValue>::type iterator_t;\n\n\n\n iterator_t it = boost::begin(attribute_value), end = boost::end(attribute_value);\n\n SVGPP_STATIC_IF_SAFE const qi::real_parser<coordinate_t, detail::number_policies<coordinate_t, tag::source::attribute> > number;\n\n SVGPP_STATIC_IF_SAFE const detail::comma_wsp_rule_no_skip<iterator_t> comma_wsp;\n\n coordinate_t value1, value2;\n\n bool two_values = false;\n\n if (qi::parse(it, end, \n", "file_path": "include/svgpp/parser/number.hpp", "rank": 29, "score": 149061.32925492615 }, { "content": "struct string_policy\n\n{\n\nprotected:\n\n typedef get_char_type<>::type char_type;\n\n\n\npublic:\n\n typedef boost::iterator_range<char_type const *> string_type;\n\n\n\n static string_type get_string_range(XMLCh const * str)\n\n {\n\n return string_type(\n\n reinterpret_cast<char_type const *>(str),\n\n reinterpret_cast<char_type const *>(str) + xercesc::XMLString::stringLen(str));\n\n }\n\n};\n\n\n", "file_path": "include/svgpp/policy/xml/xerces.hpp", "rank": 30, "score": 148737.55684773612 }, { "content": "struct transform_adapter_base\n\n{\n\n typedef typename boost::mpl::if_c<\n\n TransformPolicy::join_transforms,\n\n matrix_only_transform_adapter<\n\n join_transform_adapter<Context, Number, EventsPolicy> \n\n >,\n\n typename boost::mpl::if_c<\n\n TransformPolicy::only_matrix_transform,\n\n matrix_only_transform_adapter<\n\n passthrough_transform_adapter<Context, Number, EventsPolicy> \n\n >,\n\n passthrough_transform_adapter<Context, Number, EventsPolicy>\n\n >::type\n\n >::type type;\n\n};\n\n\n\n} // namespace detail\n\n\n\ntemplate<\n", "file_path": "include/svgpp/adapter/transform.hpp", "rank": 31, "score": 148685.6351310892 }, { "content": "struct dictionary_base\n\n{\n\n typedef MappedType mapped_type;\n\n\n\n template<class Ch> struct value_type\n\n {\n\n Ch const * key;\n\n size_t key_length;\n\n mapped_type value;\n\n };\n\n};\n\n\n", "file_path": "include/svgpp/detail/names_dictionary.hpp", "rank": 32, "score": 148685.6351310892 }, { "content": "struct integer_base\n\n{\n\n typedef Value color_type;\n\n\n\n static color_type create(unsigned char r, unsigned char g, unsigned char b)\n\n {\n\n return Policy::preset_bits \n\n | (static_cast<color_type>(r) << Policy::r_offset)\n\n | (static_cast<color_type>(g) << Policy::g_offset)\n\n | (static_cast<color_type>(b) << Policy::b_offset);\n\n }\n\n};\n\n\n\ntemplate<\n", "file_path": "include/svgpp/factory/integer_color.hpp", "rank": 33, "score": 148685.6351310892 }, { "content": "struct value_parser<\n\n tag::type::type_or_literal<InnerType, Value, BOOST_PP_ENUM_PARAMS(SVGPP_TYPE_OR_LITERAL_ARITY, Value)>, \n\n SVGPP_TEMPLATE_ARGS_PASS\n\n>\n\n{\n\n typedef value_parser<InnerType, SVGPP_TEMPLATE_ARGS_PASS> inner_parser;\n\n\n\n template<class AttributeTag, class Context, class AttributeValue, class PropertySource>\n\n static bool parse(AttributeTag tag, Context & context, \n\n AttributeValue const & attribute_value, PropertySource property_source)\n\n {\n\n typedef detail::value_parser_parameters<Context, SVGPP_TEMPLATE_ARGS_PASS> args_t;\n\n typedef detail::literal_values_dictionary<typename boost::range_value<AttributeValue>::type> dictionary;\n\n typedef boost::mpl::vector<Value, BOOST_PP_ENUM_PARAMS(SVGPP_TYPE_OR_LITERAL_ARITY, Value)> tag_list;\n\n\n\n detail::literal_enumeration_type_visitor<\n\n dictionary, \n\n AttributeTag, \n\n typename args_t::value_events_context::type, \n\n typename args_t::value_events_policy,\n", "file_path": "include/svgpp/parser/type_or_literal.hpp", "rank": 34, "score": 148529.6895148574 }, { "content": "struct value_parser<tag::type::color_optional_icc_color, SVGPP_TEMPLATE_ARGS_PASS>\n\n{\n\n template<class AttributeTag, class Context, class AttributeValue, class PropertySource>\n\n static bool parse(AttributeTag tag, Context & context, AttributeValue const & attribute_value, \n\n PropertySource property_source)\n\n {\n\n namespace qi = boost::spirit::qi;\n\n\n\n typedef typename boost::range_const_iterator<AttributeValue>::type iterator_t;\n\n typedef detail::value_parser_parameters<Context, SVGPP_TEMPLATE_ARGS_PASS> args_t;\n\n typedef typename boost::parameter::parameters<\n\n boost::parameter::optional<tag::color_factory>,\n\n boost::parameter::optional<tag::icc_color_policy>\n\n >::template bind<SVGPP_TEMPLATE_ARGS_PASS>::type args2_t;\n\n typedef typename detail::unwrap_context<Context, tag::color_factory>::template bind<args2_t>::type color_factory_t;\n\n typedef detail::unwrap_context<Context, tag::icc_color_policy> icc_color_context_t;\n\n typedef typename icc_color_context_t::template bind<args2_t>::type icc_color_policy_t;\n\n typedef typename icc_color_policy_t::icc_color_factory_type icc_color_factory_t;\n\n\n\n icc_color_factory_t & icc_color_factory = icc_color_policy_t::icc_color_factory(icc_color_context_t::get(context));\n", "file_path": "include/svgpp/parser/color.hpp", "rank": 35, "score": 147137.81761196136 }, { "content": "struct get_char_type\n\n{\n\n typedef char16_t type;\n\n};\n\n\n\ntemplate<class WCharType>\n", "file_path": "include/svgpp/policy/xml/xerces.hpp", "rank": 36, "score": 145761.46180531703 }, { "content": "struct attribute_type<ElementTag, AttributeTag,\n\n typename boost::enable_if_c<\n\n boost::mpl::has_key<animation_event_attributes, AttributeTag>::value\n\n || boost::mpl::has_key<graphical_event_attributes, AttributeTag>::value\n\n || boost::mpl::has_key<document_event_attributes, AttributeTag>::value \n\n >::type>\n\n{\n\n typedef tag::type::string type;\n\n};\n\n\n\ntemplate<class Element> struct attribute_type<Element, tag::attribute::baseProfile > { typedef tag::type::string type; };\n\ntemplate<class Element> struct attribute_type<Element, tag::attribute::class_ > { typedef tag::type::string type; }; // TODO: parse list of strings\n\ntemplate<class Element> struct attribute_type<Element, tag::attribute::contentScriptType > { typedef tag::type::string type; };\n\ntemplate<class Element> struct attribute_type<Element, tag::attribute::contentStyleType > { typedef tag::type::string type; };\n\ntemplate<class Element> struct attribute_type<Element, tag::attribute::id > { typedef tag::type::string type; };\n\ntemplate<class Element> struct attribute_type<Element, tag::attribute::attributeName > { typedef tag::type::string type; };\n\ntemplate<class Element> struct attribute_type<Element, tag::attribute::font_family > { typedef tag::type::string type; };\n\ntemplate<class Element> struct attribute_type<Element, tag::attribute::format > { typedef tag::type::string type; };\n\ntemplate<class Element> struct attribute_type<Element, tag::attribute::glyphRef > { typedef tag::type::string type; };\n\ntemplate<class Element> struct attribute_type<Element, tag::attribute::lang > { typedef tag::type::string type; };\n", "file_path": "include/svgpp/traits/attribute_type.hpp", "rank": 37, "score": 145183.9040680698 }, { "content": "struct get_viewport_size_source<tag::element::image, tag::element::svg>\n\n{\n\n typedef tag::viewport_size_source::use_reference type;\n\n};\n\n\n\ntemplate<>\n", "file_path": "include/svgpp/adapter/viewport.hpp", "rank": 38, "score": 144704.82526996266 }, { "content": "struct unwrap_context<const bind_context_parameters_wrapper<Context, Parameters>, PolicyTag>\n\n : unwrap_context<bind_context_parameters_wrapper<Context, Parameters>, PolicyTag>\n\n{};\n\n\n\ntemplate<class OriginalContext, class AdaptedPolicyTag, class AdaptedPolicy>\n", "file_path": "include/svgpp/detail/adapt_context.hpp", "rank": 39, "score": 143903.93014754 }, { "content": "struct length_dimension_by_attribute{ typedef tag::length_dimension::not_width_nor_height type; };\n\ntemplate<> struct length_dimension_by_attribute<tag::attribute::x> { typedef tag::length_dimension::width type; };\n\ntemplate<> struct length_dimension_by_attribute<tag::attribute::y> { typedef tag::length_dimension::height type; };\n\ntemplate<> struct length_dimension_by_attribute<tag::attribute::x1> { typedef tag::length_dimension::width type; };\n\ntemplate<> struct length_dimension_by_attribute<tag::attribute::y1> { typedef tag::length_dimension::height type; };\n\ntemplate<> struct length_dimension_by_attribute<tag::attribute::x2> { typedef tag::length_dimension::width type; };\n\ntemplate<> struct length_dimension_by_attribute<tag::attribute::y2> { typedef tag::length_dimension::height type; };\n\ntemplate<> struct length_dimension_by_attribute<tag::attribute::width> { typedef tag::length_dimension::width type; }; \n\ntemplate<> struct length_dimension_by_attribute<tag::attribute::height> { typedef tag::length_dimension::height type; };\n\ntemplate<> struct length_dimension_by_attribute<tag::attribute::rx> { typedef tag::length_dimension::width type; };\n\ntemplate<> struct length_dimension_by_attribute<tag::attribute::ry> { typedef tag::length_dimension::height type; };\n\ntemplate<> struct length_dimension_by_attribute<tag::attribute::cx> { typedef tag::length_dimension::width type; };\n\ntemplate<> struct length_dimension_by_attribute<tag::attribute::cy> { typedef tag::length_dimension::height type; };\n\ntemplate<> struct length_dimension_by_attribute<tag::attribute::refX> { typedef tag::length_dimension::width type; };\n\ntemplate<> struct length_dimension_by_attribute<tag::attribute::refY> { typedef tag::length_dimension::height type; };\n\ntemplate<> struct length_dimension_by_attribute<tag::attribute::markerWidth> { typedef tag::length_dimension::width type; };\n\ntemplate<> struct length_dimension_by_attribute<tag::attribute::markerHeight> { typedef tag::length_dimension::height type; };\n\n\n\n}}", "file_path": "include/svgpp/traits/length_dimension_by_attribute.hpp", "rank": 40, "score": 143598.0084792959 }, { "content": "class exception_base: public virtual boost::exception, public virtual std::exception\n\n{};\n\n\n", "file_path": "include/svgpp/policy/error.hpp", "rank": 41, "score": 143422.71029771632 }, { "content": "struct value_parser<tag::type::literal_enumeration<LiteralsList>, SVGPP_TEMPLATE_ARGS_PASS>\n\n{\n\n template<class AttributeTag, class Context, class ValueRange, class PropertySource>\n\n static bool parse(AttributeTag tag, Context & context, ValueRange const & attribute_value, PropertySource)\n\n {\n\n typedef detail::value_parser_parameters<Context, SVGPP_TEMPLATE_ARGS_PASS> args_t;\n\n typedef detail::literal_values_dictionary<typename boost::range_value<ValueRange>::type> dictionary_t;\n\n\n\n detail::literal_enumeration_type_visitor<\n\n dictionary_t, \n\n AttributeTag, \n\n typename args_t::value_events_context::type, \n\n typename args_t::value_events_policy,\n\n ValueRange,\n\n PropertySource\n\n > fn(args_t::value_events_context::get(context), attribute_value);\n\n\n\n boost::mpl::for_each<LiteralsList>(boost::ref(fn));\n\n if (fn.found())\n\n return true;\n\n else\n\n return args_t::error_policy::parse_failed(args_t::error_policy_context::get(context), tag, attribute_value);\n\n }\n\n};\n\n\n\n}", "file_path": "include/svgpp/parser/literal_enumeration.hpp", "rank": 42, "score": 141752.09466315803 }, { "content": "struct percentage_adapter: BaseFactory\n\n{\n\n typedef double percentage_type;\n\n \n\n static typename BaseFactory::color_type create_from_percent(percentage_type r, percentage_type g, percentage_type b)\n\n {\n\n return BaseFactory::create(cast_percent(r), cast_percent(g), cast_percent(b));\n\n }\n\n\n\nprivate:\n\n static unsigned char cast_percent(percentage_type c)\n\n {\n\n if (c > 100)\n\n c = 100;\n\n else if (c < 0)\n\n c = 0;\n\n return static_cast<unsigned char>(c * 2.55 + 0.0049);\n\n }\n\n};\n\n\n", "file_path": "include/svgpp/factory/integer_color.hpp", "rank": 43, "score": 140184.06284386222 }, { "content": "struct get_viewport_size_source; // Shouldn't be called for anything other than 'svg' and 'symbol',\n\n // referenced by 'use' or 'image'\n\n // 'symbol' must only be used while referenced by 'use'\n\n\n\ntemplate<>\n", "file_path": "include/svgpp/adapter/viewport.hpp", "rank": 44, "score": 137317.6062054354 }, { "content": "struct child_element_types<tag::element::tref, void>\n\n{\n\n typedef \n\n boost::mpl::fold<\n\n traits::descriptive_elements,\n\n boost::mpl::set3<\n\n tag::element::animate,\n\n tag::element::animateColor,\n\n tag::element::set\n\n >,\n\n boost::mpl::insert<boost::mpl::_1, boost::mpl::_2>\n\n >::type type;\n\n};\n\n\n\ntemplate<>\n", "file_path": "include/svgpp/traits/child_element_types.hpp", "rank": 45, "score": 136826.44223462878 }, { "content": "struct child_element_types<tag::element::font, void>\n\n{\n\n typedef \n\n boost::mpl::fold<\n\n traits::descriptive_elements,\n\n boost::mpl::set5<\n\n tag::element::font_face,\n\n tag::element::glyph,\n\n tag::element::hkern,\n\n tag::element::missing_glyph,\n\n tag::element::vkern\n\n >,\n\n boost::mpl::insert<boost::mpl::_1, boost::mpl::_2>\n\n >::type type;\n\n};\n\n\n\ntemplate<>\n", "file_path": "include/svgpp/traits/child_element_types.hpp", "rank": 46, "score": 136826.44223462878 }, { "content": "struct child_element_types<tag::element::filter, void>\n\n{\n\n typedef\n\n boost::mpl::fold<\n\n boost::mpl::joint_view<\n\n traits::filter_primitive_elements,\n\n traits::descriptive_elements>,\n\n boost::mpl::set2<\n\n tag::element::animate,\n\n tag::element::set\n\n >,\n\n boost::mpl::insert<boost::mpl::_1, boost::mpl::_2>\n\n >::type type;\n\n};\n\n\n\ntemplate<>\n", "file_path": "include/svgpp/traits/child_element_types.hpp", "rank": 47, "score": 136826.44223462878 }, { "content": "struct child_element_types<tag::element::stop, void>\n\n{\n\n typedef \n\n boost::mpl::set3<\n\n tag::element::animate,\n\n tag::element::animateColor,\n\n tag::element::set\n\n > type;\n\n};\n\n\n\ntemplate<>\n", "file_path": "include/svgpp/traits/child_element_types.hpp", "rank": 48, "score": 136826.44223462878 }, { "content": "struct child_element_types<tag::element::text, void>\n\n{\n\n typedef \n\n boost::mpl::fold<\n\n boost::mpl::joint_view<\n\n traits::animation_elements,\n\n traits::descriptive_elements>,\n\n boost::mpl::set6<\n\n tag::element::altGlyph,\n\n tag::element::textPath,\n\n tag::element::tref,\n\n tag::element::tspan,\n\n tag::element::a,\n\n tag::text_content\n\n >,\n\n boost::mpl::insert<boost::mpl::_1, boost::mpl::_2>\n\n >::type type;\n\n};\n\n\n\ntemplate<class ElementTag>\n", "file_path": "include/svgpp/traits/child_element_types.hpp", "rank": 49, "score": 136826.44223462878 }, { "content": "struct child_element_types<tag::element::switch_, void>\n\n{\n\n typedef \n\n boost::mpl::fold<\n\n boost::mpl::joint_view<\n\n boost::mpl::joint_view<\n\n traits::animation_elements,\n\n traits::descriptive_elements>,\n\n traits::shape_elements>,\n\n boost::mpl::set8<\n\n tag::element::a,\n\n tag::element::foreignObject,\n\n tag::element::g,\n\n tag::element::image,\n\n tag::element::svg,\n\n tag::element::switch_,\n\n tag::element::text,\n\n tag::element::use_\n\n >,\n\n boost::mpl::insert<boost::mpl::_1, boost::mpl::_2>\n\n >::type type;\n\n};\n\n\n\ntemplate<class ElementTag>\n", "file_path": "include/svgpp/traits/child_element_types.hpp", "rank": 50, "score": 136826.44223462878 }, { "content": "struct child_element_types<tag::element::feMerge, void>\n\n{\n\n typedef \n\n boost::mpl::set1<\n\n tag::element::feMergeNode\n\n > type;\n\n};\n\n\n\n}}\n", "file_path": "include/svgpp/traits/child_element_types.hpp", "rank": 51, "score": 134839.62705868192 }, { "content": "struct child_element_types<tag::element::font_face, void>\n\n{\n\n typedef \n\n boost::mpl::fold<\n\n traits::descriptive_elements,\n\n boost::mpl::set1<\n\n tag::element::font_face_src\n\n >,\n\n boost::mpl::insert<boost::mpl::_1, boost::mpl::_2>\n\n >::type type;\n\n};\n\n\n\ntemplate<>\n", "file_path": "include/svgpp/traits/child_element_types.hpp", "rank": 52, "score": 134839.62705868192 }, { "content": "struct child_element_types<tag::element::feImage, void>\n\n{\n\n typedef \n\n boost::mpl::set3<\n\n tag::element::animate,\n\n tag::element::animateTransform,\n\n tag::element::set\n\n > type;\n\n};\n\n\n\ntemplate<>\n", "file_path": "include/svgpp/traits/child_element_types.hpp", "rank": 53, "score": 134839.62705868192 }, { "content": "struct child_element_types<tag::element::feFlood, void>\n\n{\n\n typedef \n\n boost::mpl::set3<\n\n tag::element::animate,\n\n tag::element::animateColor,\n\n tag::element::set\n\n > type;\n\n};\n\n\n\ntemplate<>\n", "file_path": "include/svgpp/traits/child_element_types.hpp", "rank": 54, "score": 134839.62705868192 }, { "content": "struct child_element_types<tag::element::clipPath, void>\n\n{\n\n typedef\n\n boost::mpl::fold<\n\n boost::mpl::joint_view<\n\n boost::mpl::joint_view<\n\n traits::animation_elements,\n\n traits::descriptive_elements>,\n\n traits::shape_elements>,\n\n boost::mpl::set2<\n\n tag::element::text,\n\n tag::element::use_\n\n >,\n\n boost::mpl::insert<boost::mpl::_1, boost::mpl::_2>\n\n >::type type;\n\n};\n\n\n\ntemplate<class ElementTag>\n", "file_path": "include/svgpp/traits/child_element_types.hpp", "rank": 55, "score": 134839.62705868192 }, { "content": "struct child_element_types<tag::element::animateMotion, void>\n\n{\n\n typedef\n\n boost::mpl::fold<\n\n traits::descriptive_elements,\n\n boost::mpl::set1<\n\n tag::element::mpath\n\n >,\n\n boost::mpl::insert<boost::mpl::_1, boost::mpl::_2>\n\n >::type type;\n\n};\n\n\n\ntemplate<>\n", "file_path": "include/svgpp/traits/child_element_types.hpp", "rank": 56, "score": 134839.62705868192 }, { "content": "struct attribute_type<tag::element::stop, tag::attribute::offset> \n\n{\n\n typedef boost::mpl::pair<tag::element::stop, tag::attribute::offset> type;\n\n};\n\n\n\ntemplate<class Element> struct attribute_type<Element, tag::attribute::font> \n\n{ \n\n typedef tag::type::type_or_literal<tag::attribute::font, \n\n tag::value::inherit,\n\n tag::value::caption,\n\n tag::value::icon,\n\n tag::value::menu,\n\n tag::value::message_box,\n\n tag::value::small_caption,\n\n tag::value::status_bar\n\n > type; \n\n};\n\n\n\n/*\n\n'font-face' element attributes:\n", "file_path": "include/svgpp/traits/attribute_type.hpp", "rank": 57, "score": 133671.87280812915 }, { "content": "struct child_element_types<tag::element::font_face_uri, void>\n\n{\n\n typedef boost::mpl::set1<tag::element::font_face_format> type;\n\n};\n\n\n\ntemplate<>\n", "file_path": "include/svgpp/traits/child_element_types.hpp", "rank": 58, "score": 132925.73417646406 }, { "content": "struct child_element_types<tag::element::altGlyphDef, void>\n\n{\n\n typedef\n\n boost::mpl::set2<\n\n tag::element::altGlyphItem,\n\n tag::element::glyphRef\n\n >\n\n type;\n\n};\n\n\n\ntemplate<>\n", "file_path": "include/svgpp/traits/child_element_types.hpp", "rank": 59, "score": 132925.73417646406 }, { "content": "struct child_element_types<tag::element::font_face_src, void>\n\n{\n\n typedef boost::mpl::set2<\n\n tag::element::font_face_name,\n\n tag::element::font_face_uri\n\n > type;\n\n};\n\n\n\ntemplate<class ElementTag>\n", "file_path": "include/svgpp/traits/child_element_types.hpp", "rank": 60, "score": 132925.73417646406 }, { "content": "struct child_element_types<tag::element::feDiffuseLighting, void>\n\n{\n\n typedef \n\n boost::mpl::fold<\n\n traits::light_source_elements,\n\n traits::descriptive_elements,\n\n boost::mpl::insert<boost::mpl::_1, boost::mpl::_2>\n\n >::type type;\n\n};\n\n\n\ntemplate<>\n", "file_path": "include/svgpp/traits/child_element_types.hpp", "rank": 61, "score": 132925.73417646406 }, { "content": "struct child_element_types<tag::element::feComponentTransfer, void>\n\n{\n\n typedef \n\n boost::mpl::set4<\n\n svgpp::tag::element::feFuncA,\n\n svgpp::tag::element::feFuncB,\n\n svgpp::tag::element::feFuncG,\n\n svgpp::tag::element::feFuncR\n\n > type;\n\n};\n\n\n\ntemplate<>\n", "file_path": "include/svgpp/traits/child_element_types.hpp", "rank": 62, "score": 132925.73417646406 }, { "content": "struct child_element_types<tag::element::altGlyphItem, void>\n\n{\n\n typedef\n\n boost::mpl::set1<\n\n tag::element::glyphRef\n\n >\n\n type;\n\n};\n\n\n\ntemplate<>\n", "file_path": "include/svgpp/traits/child_element_types.hpp", "rank": 63, "score": 132925.73417646406 }, { "content": "struct child_element_types<tag::element::feSpecularLighting, void>\n\n{\n\n typedef \n\n boost::mpl::fold<\n\n traits::light_source_elements,\n\n traits::descriptive_elements,\n\n boost::mpl::insert<boost::mpl::_1, boost::mpl::_2>\n\n >::type type;\n\n};\n\n\n\ntemplate<>\n", "file_path": "include/svgpp/traits/child_element_types.hpp", "rank": 64, "score": 132925.73417646406 }, { "content": "struct need_path_adapter: boost::mpl::bool_<\n\n PathPolicy::absolute_coordinates_only \n\n || PathPolicy::no_ortho_line_to\n\n || PathPolicy::no_quadratic_bezier_shorthand \n\n || PathPolicy::no_cubic_bezier_shorthand \n\n || PathPolicy::quadratic_bezier_as_cubic>\n\n{};\n\n\n\ntemplate<class OriginalContext, class Enabled = void>\n", "file_path": "include/svgpp/adapter/path.hpp", "rank": 65, "score": 132903.40714729435 }, { "content": "struct literal_enumeration_type_visitor: boost::noncopyable\n\n{\n\n literal_enumeration_type_visitor(Context & context, ValueRange const & range)\n\n : context_(context)\n\n , range_(range)\n\n , found_(false)\n\n {}\n\n\n\n template<class T>\n\n void operator ()(T value_tag) \n\n {\n\n if (!found_ && boost::algorithm::equals(range_, Dictionary::template get_name<T>(), \n\n typename boost::mpl::if_<\n\n boost::is_same<PropertySource, tag::source::attribute>, \n\n boost::algorithm::is_equal, \n\n boost::algorithm::is_iequal\n\n >::type()))\n\n {\n\n ValueEventsPolicy::set(context_, AttributeTag(), PropertySource(), value_tag);\n\n found_ = true;\n", "file_path": "include/svgpp/parser/literal_enumeration.hpp", "rank": 66, "score": 132523.73807810855 }, { "content": "struct unwrap_context<const adapted_policy_context_wrapper<OriginalContext, AdaptedPolicyTag, AdaptedPolicy>, PolicyTag>\n\n : unwrap_context<adapted_policy_context_wrapper<OriginalContext, AdaptedPolicyTag, AdaptedPolicy>, PolicyTag>\n\n{};\n\n\n\ntemplate<class OriginalContext, class AdaptedContext, class AdaptedPolicyTag, class AdaptedPolicy>\n", "file_path": "include/svgpp/detail/adapt_context.hpp", "rank": 67, "score": 132223.23106259044 }, { "content": "struct literal_values_dictionary<SVGPP_ITER_CHAR_TYPE>\n\n : property_values_dictionary<SVGPP_ITER_CHAR_TYPE> \n\n{ \n\n template<class ValueTag>\n\n static string_type get_name();\n\n};\n\n\n\n#define SVGPP_ON_VALUE(name) SVGPP_ON_VALUE2(name, name)\n\n#define SVGPP_ON_VALUE2(name, string) \\\n\n template<> \\\n\n inline literal_values_dictionary<SVGPP_ITER_CHAR_TYPE>::string_type \\\n\n literal_values_dictionary<SVGPP_ITER_CHAR_TYPE>::get_name<tag::value::name>() \\\n\n { static const SVGPP_ITER_CHAR_TYPE value[] = BOOST_PP_CAT(SVGPP_ITER_STRINGIZE, #string); \\\n\n return string_type(value, value + sizeof(value)/sizeof(value[0]) - 1); }\n\n#include <svgpp/detail/dict/enumerate_literal_values.inc>\n\n#undef SVGPP_ON_VALUE\n\n#undef SVGPP_ON_VALUE2\n\n\n\n#undef SVGPP_ITER_CHAR_TYPE\n\n#undef SVGPP_ITER_STRINGIZE\n\n\n\n#endif // !BOOST_PP_IS_ITERATING", "file_path": "include/svgpp/detail/literal_values_dictionary.hpp", "rank": 68, "score": 130651.68896057134 }, { "content": "struct element_iterator<SVGPP_MSXML_NAMESPACE::IXMLDOMNode *>\n\n : element_iterator<msxml_detail::node_ptr>\n\n{};\n\n\n\n}}}\n", "file_path": "include/svgpp/policy/xml/msxml.hpp", "rank": 69, "score": 130415.75886835743 }, { "content": "struct element_iterator<SVGPP_MSXML_NAMESPACE::IXMLDOMElement *>\n\n : element_iterator<msxml_detail::node_ptr>\n\n{};\n\n\n\ntemplate<>\n", "file_path": "include/svgpp/policy/xml/msxml.hpp", "rank": 70, "score": 130415.75886835743 }, { "content": "struct css_property_name_to_id: dictionary_base<attribute_id>\n\n{\n\n struct lower_case_values;\n\n\n\n template<class Ch>\n\n inline static boost::iterator_range<value_type<Ch> const *> const & get_map();\n\n};\n\n\n\ntemplate<class ValuesHolder, typename ValuesHolder::mapped_type NotFoundValue>\n", "file_path": "include/svgpp/detail/names_dictionary.hpp", "rank": 71, "score": 128182.53313251302 }, { "content": "struct xlink_attribute_name_to_id: dictionary_base<attribute_id>\n\n{\n\n template<class Ch>\n\n inline static boost::iterator_range<value_type<Ch> const *> const & get_map();\n\n};\n\n\n", "file_path": "include/svgpp/detail/names_dictionary.hpp", "rank": 72, "score": 128182.53313251302 }, { "content": "struct xml_attribute_name_to_id: dictionary_base<attribute_id>\n\n{\n\n template<class Ch>\n\n inline static boost::iterator_range<value_type<Ch> const *> const & get_map();\n\n};\n\n\n", "file_path": "include/svgpp/detail/names_dictionary.hpp", "rank": 73, "score": 128182.53313251302 }, { "content": "struct unwrap_context<const adapted_context_wrapper<OriginalContext, AdaptedContext, AdaptedPolicyTag, AdaptedPolicy>, PolicyTag>\n\n : unwrap_context<adapted_context_wrapper<OriginalContext, AdaptedContext, AdaptedPolicyTag, AdaptedPolicy>, PolicyTag>\n\n{};\n\n\n\n}}", "file_path": "include/svgpp/detail/adapt_context.hpp", "rank": 74, "score": 127928.46535649474 }, { "content": "struct svg_real_policies: real_policies_without_inf_nan<Number>\n\n{\n\n static bool const allow_trailing_dot = false;\n\n};\n\n\n\ntemplate<class Number, class PropertySource>\n", "file_path": "include/svgpp/parser/detail/common.hpp", "rank": 75, "score": 126098.93730845791 }, { "content": "#ifndef MATH_FLOAT_HPP\n\n#define MATH_FLOAT_HPP\n\n\n\n#include <cmath>\n\n#include <algorithm>\n\n\n\n#ifdef USE_DOUBLE_AS_FLOAT\n\n #error Using double precision float is currently not supported.\n\n typedef double Float;\n\n#else\n\n typedef float Float;\n\n#endif\n\n\n\nextern const Float FLOAT_TOLERANT;\n\nextern const Float ONE_MINUS_FLOAT_TOLERANT;\n\n\n\nnamespace math {\n\n inline bool COMPARE_EQ(Float x, Float y) {\n\n return std::abs(x - y) < FLOAT_TOLERANT;\n\n }\n", "file_path": "include/math/float.hpp", "rank": 76, "score": 125859.19827426758 }, { "content": "\n\n inline bool COMPARE_EQ(Float x, Float y, Float eps) {\n\n return std::abs(x - y) < eps;\n\n }\n\n\n\n inline bool COMPARE_LEQ(Float x, Float y) {\n\n return COMPARE_EQ(x, y) || (x < y);\n\n }\n\n\n\n inline bool COMPARE_GEQ(Float x, Float y) {\n\n return COMPARE_EQ(x, y) || (x > y);\n\n }\n\n\n\n inline Float lerp(Float t, Float a, Float b) {\n\n return (1 - t) * a + t * b;\n\n }\n\n\n\n template <typename T>\n\n inline T clamp(T x, T min, T max) {\n\n return std::min(max, std::max(min, x));\n\n }\n\n}\n\n\n\n#endif /* MATH_FLOAT_HPP */\n", "file_path": "include/math/float.hpp", "rank": 77, "score": 125847.97754558577 }, { "content": "struct get_default_policy<Context, tag::number_type>\n\n{\n\n typedef typename number_type_by_context<Context>::type type;\n\n};\n\n\n\ntemplate<class Context>\n", "file_path": "include/svgpp/policy/detail/default_policies.hpp", "rank": 78, "score": 125822.39129056528 }, { "content": "struct get_viewport_size_source<tag::element::use_, tag::element::symbol>\n\n{\n\n typedef tag::viewport_size_source::use_reference type;\n\n};\n\n\n\ntemplate<>\n", "file_path": "include/svgpp/adapter/viewport.hpp", "rank": 79, "score": 118833.7582090087 }, { "content": "struct number_policies<Number, tag::source::css>: svg_real_policies<Number>\n\n{\n\n template <typename Iterator>\n\n static BOOST_CONSTEXPR bool parse_exp(Iterator &, Iterator const &)\n\n {\n\n return false;\n\n }\n\n};\n\n\n\ntemplate<class Iterator>\n", "file_path": "include/svgpp/parser/detail/common.hpp", "rank": 80, "score": 116788.13948415243 }, { "content": "struct number_policies<Number, tag::source::attribute>: svg_real_policies<Number>\n\n{\n\n template <typename Iterator>\n\n static bool parse_exp(Iterator & first, Iterator const & last)\n\n {\n\n // Check that \"e\" is followed by integer to be able to parse something like \"4em\" correctly\n\n Iterator it = first;\n\n if (svg_real_policies<Number>::parse_exp(it, last))\n\n {\n\n // Do some prefetch before accepting \"e\" as start of the exponent part\n\n Iterator it2 = it;\n\n int exp_val;\n\n if (svg_real_policies<Number>::parse_exp_n(it2, last, exp_val))\n\n {\n\n first = it;\n\n return true;\n\n }\n\n }\n\n return false;\n\n }\n\n};\n\n\n\ntemplate<class Number>\n", "file_path": "include/svgpp/parser/detail/common.hpp", "rank": 81, "score": 116788.13948415243 }, { "content": "struct child_element_types<ElementTag, typename boost::enable_if<boost::mpl::has_key<boost::mpl::set10<\n\n tag::element::svg, tag::element::g, tag::element::glyph, tag::element::a, tag::element::defs, tag::element::symbol,\n\n tag::element::marker, tag::element::mask, tag::element::missing_glyph, tag::element::pattern>, ElementTag> >::type>\n\n{\n\n typedef \n\n boost::mpl::fold<\n\n boost::mpl::joint_view<\n\n boost::mpl::joint_view<\n\n boost::mpl::joint_view<\n\n boost::mpl::joint_view<\n\n traits::animation_elements,\n\n traits::descriptive_elements>,\n\n traits::shape_elements>,\n\n traits::structural_elements>,\n\n traits::gradient_elements\n\n >,\n\n boost::mpl::set18<\n\n tag::element::a,\n\n tag::element::altGlyphDef,\n\n tag::element::clipPath,\n", "file_path": "include/svgpp/traits/child_element_types.hpp", "rank": 82, "score": 116681.51076671021 }, { "content": "struct child_element_types<ElementTag, typename boost::enable_if<boost::mpl::has_key<boost::mpl::set6<\n\n tag::element::altGlyph, tag::element::desc, tag::element::metadata, \n\n tag::element::script, tag::element::style, tag::element::title\n\n>, ElementTag> >::type>\n\n{\n\n typedef boost::mpl::set1<tag::text_content> type;\n\n};\n\n\n\ntemplate<class ElementTag>\n", "file_path": "include/svgpp/traits/child_element_types.hpp", "rank": 83, "score": 116681.51076671021 }, { "content": "struct child_element_types<ElementTag, typename boost::enable_if<boost::mpl::has_key<boost::mpl::set8<\n\n tag::element::animate, tag::element::animateColor, tag::element::animateTransform, \n\n tag::element::color_profile, tag::element::cursor, tag::element::mpath, tag::element::set,\n\n tag::element::view>, ElementTag> >::type>\n\n{\n\n typedef traits::descriptive_elements type;\n\n};\n\n\n\ntemplate<>\n", "file_path": "include/svgpp/traits/child_element_types.hpp", "rank": 84, "score": 116681.51076671021 }, { "content": "struct child_element_types<ElementTag, typename boost::enable_if<boost::mpl::has_key<boost::mpl::set9<\n\n tag::element::rect, tag::element::circle, tag::element::ellipse, tag::element::line, \n\n tag::element::polygon, tag::element::polyline, tag::element::path, tag::element::image,\n\n tag::element::use_>, ElementTag> >::type>\n\n{\n\n typedef \n\n boost::mpl::fold<\n\n traits::animation_elements,\n\n traits::descriptive_elements,\n\n boost::mpl::insert<boost::mpl::_1, boost::mpl::_2>\n\n >::type type;\n\n};\n\n\n\ntemplate<>\n", "file_path": "include/svgpp/traits/child_element_types.hpp", "rank": 85, "score": 116681.51076671021 }, { "content": "struct child_element_types<ElementTag, typename boost::enable_if<boost::mpl::has_key<boost::mpl::set14<\n\n tag::element::feBlend, tag::element::feColorMatrix, tag::element::feComposite, tag::element::feConvolveMatrix, \n\n tag::element::feDisplacementMap, tag::element::feDistantLight, tag::element::feGaussianBlur, tag::element::feMergeNode,\n\n tag::element::feMorphology, tag::element::feOffset, tag::element::fePointLight, tag::element::feSpotLight,\n\n tag::element::feTile, tag::element::feTurbulence>, ElementTag> >::type>\n\n{\n\n typedef \n\n boost::mpl::set2<\n\n tag::element::animate,\n\n tag::element::set\n\n > type;\n\n};\n\n\n\ntemplate<>\n", "file_path": "include/svgpp/traits/child_element_types.hpp", "rank": 86, "score": 116681.51076671021 }, { "content": "struct child_element_types<ElementTag, typename boost::enable_if<boost::mpl::has_key<boost::mpl::set2<\n\n tag::element::linearGradient, tag::element::radialGradient>, ElementTag> >::type>\n\n{\n\n typedef \n\n boost::mpl::fold<\n\n traits::descriptive_elements,\n\n boost::mpl::set4<\n\n tag::element::animate,\n\n tag::element::animateTransform,\n\n tag::element::set,\n\n tag::element::stop\n\n >,\n\n boost::mpl::insert<boost::mpl::_1, boost::mpl::_2>\n\n >::type type;\n\n};\n\n\n\ntemplate<>\n", "file_path": "include/svgpp/traits/child_element_types.hpp", "rank": 87, "score": 116681.51076671021 }, { "content": "struct text_content; // Used in child element sequences together with tag::element::* tags to\n\n // mark elements that should handle character data content\n\n\n\n}} // namespace tag\n", "file_path": "include/svgpp/definitions.hpp", "rank": 88, "score": 115587.86296808199 }, { "content": "struct mid_tag {};\n", "file_path": "include/svgpp/definitions.hpp", "rank": 89, "score": 105391.29778536694 }, { "content": "struct by_context\n\n{\n\n typedef default_policy type;\n\n};\n\n\n\n}}}", "file_path": "include/svgpp/policy/transform.hpp", "rank": 90, "score": 105391.29778536694 }, { "content": "struct matrix\n\n{\n\n static const bool join_transforms = true;\n\n static const bool no_rotate_about_point = false;\n\n static const bool no_shorthands = false; \n\n static const bool only_matrix_transform = false;\n\n};\n\n\n\ntypedef matrix default_policy;\n\n\n\ntemplate<class Context>\n", "file_path": "include/svgpp/policy/transform.hpp", "rank": 91, "score": 105391.29778536694 }, { "content": "struct max_tag {};\n\n\n\nnamespace value \n\n{\n\n#define SVGPP_ON_VALUE(tag) struct tag {};\n\n#define SVGPP_ON_VALUE2(tag, string) SVGPP_ON_VALUE(tag)\n\n#include <svgpp/detail/dict/enumerate_literal_values.inc>\n\n#undef SVGPP_ON_VALUE\n\n#undef SVGPP_ON_VALUE2\n\n\n\n struct rect {}; // Used as shape in 'clip' property\n\n struct underline {};\n\n struct overline {};\n\n struct line_through {};\n\n struct blink {};\n\n\n\n struct meet {};\n\n struct slice {};\n\n struct xMinYMin { typedef min_tag x; typedef min_tag y; };\n\n struct xMidYMin { typedef mid_tag x; typedef min_tag y; };\n", "file_path": "include/svgpp/definitions.hpp", "rank": 92, "score": 105391.29778536694 }, { "content": "struct raw\n\n{\n\n static const bool join_transforms = false;\n\n static const bool no_rotate_about_point = false;\n\n static const bool no_shorthands = false; // Replace translate(tx) with translate(tx 0) and scale(scale) with scale(scale scale)\n\n static const bool only_matrix_transform = false;\n\n};\n\n\n", "file_path": "include/svgpp/policy/transform.hpp", "rank": 93, "score": 105391.29778536694 }, { "content": "struct minimal\n\n{\n\n static const bool join_transforms = false;\n\n static const bool no_rotate_about_point = true;\n\n static const bool no_shorthands = true;\n\n static const bool only_matrix_transform = false;\n\n};\n\n\n", "file_path": "include/svgpp/policy/transform.hpp", "rank": 94, "score": 105391.29778536694 }, { "content": "// helper tags\n\nstruct min_tag {};\n", "file_path": "include/svgpp/definitions.hpp", "rank": 95, "score": 105391.29778536694 }, { "content": "#ifndef BEZIER_HPP\n\n#define BEZIER_HPP\n\n\n\n#include <vector>\n\n#include \"math/vector.hpp\"\n\n\n\nnamespace bezier {\n\n using namespace math;\n\n\n\n vector2f curve(std::vector<vector2f> points, float t);\n\n\n\n vector2f elliptical_curve(\n\n const vector2f& p0,\n\n const vector2f& p1,\n\n const vector2f& r,\n\n bool large_arc_flag,\n\n bool sweep_flag,\n\n float x_axis_rotation,\n\n float t\n\n );\n", "file_path": "include/bezier.hpp", "rank": 99, "score": 44.71567927973513 } ]
C++
src/graphics/examples/vkproto/cmd-buf-benchmark/main.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
#include <unistd.h> #include <memory> #include <vector> #include "src/graphics/examples/vkproto/common/command_buffers.h" #include "src/graphics/examples/vkproto/common/command_pool.h" #include "src/graphics/examples/vkproto/common/debug_utils_messenger.h" #include "src/graphics/examples/vkproto/common/device.h" #include "src/graphics/examples/vkproto/common/framebuffers.h" #include "src/graphics/examples/vkproto/common/graphics_pipeline.h" #include "src/graphics/examples/vkproto/common/image_view.h" #include "src/graphics/examples/vkproto/common/instance.h" #include "src/graphics/examples/vkproto/common/physical_device.h" #include "src/graphics/examples/vkproto/common/render_pass.h" #include "src/graphics/examples/vkproto/common/swapchain.h" #include "src/graphics/examples/vkproto/common/utils.h" #include <vulkan/vulkan.hpp> static bool DrawAllFrames(const vkp::Device& vkp_device, const vkp::CommandBuffers& vkp_command_buffers); int main(int argc, char* argv[]) { #ifndef NDEBUG printf("Warning - benchmarking debug build.\n"); const bool kEnableValidation = true; #else const bool kEnableValidation = false; #endif vkp::Instance vkp_instance(kEnableValidation); RTN_IF_MSG(1, !vkp_instance.Init(), "Instance Initialization Failed.\n"); if (kEnableValidation) { vkp::DebugUtilsMessenger vkp_debug_messenger(vkp_instance.shared()); RTN_IF_MSG(1, !vkp_debug_messenger.Init(), "Debug Messenger Initialization Failed.\n"); } vkp::PhysicalDevice vkp_physical_device(vkp_instance.shared()); RTN_IF_MSG(1, !vkp_physical_device.Init(), "Phys Device Initialization Failed.\n"); vkp::Device vkp_device(vkp_physical_device.get()); RTN_IF_MSG(1, !vkp_device.Init(), "Logical Device Initialization Failed.\n"); std::shared_ptr<vk::Device> device = vkp_device.shared(); vk::Format image_format; vk::Extent2D extent; std::vector<std::shared_ptr<vkp::ImageView>> vkp_image_views; std::vector<vk::ImageView> image_views; constexpr uint32_t kCommandBufferCount = 100; for (uint32_t i = 0; i < kCommandBufferCount; i++) { auto vkp_offscreen_image_view = std::make_shared<vkp::ImageView>(device, vkp_physical_device.get(), vk::Extent2D{64, 64}); RTN_IF_MSG(1, !vkp_offscreen_image_view->Init(), "Image View Initialization Failed.\n"); image_format = vkp_offscreen_image_view->format(); extent = vkp_offscreen_image_view->extent(); image_views.emplace_back(vkp_offscreen_image_view->get()); vkp_image_views.emplace_back(std::move(vkp_offscreen_image_view)); } auto vkp_render_pass = std::make_shared<vkp::RenderPass>(device, image_format, true); RTN_IF_MSG(1, !vkp_render_pass->Init(), "Render Pass Initialization Failed.\n"); auto vkp_pipeline = std::make_unique<vkp::GraphicsPipeline>(device, extent, vkp_render_pass); RTN_IF_MSG(1, !vkp_pipeline->Init(), "Graphics Pipeline Initialization Failed.\n"); auto vkp_framebuffer = std::make_unique<vkp::Framebuffers>(device, extent, vkp_render_pass->get(), image_views); RTN_IF_MSG(1, !vkp_framebuffer->Init(), "Framebuffers Initialization Failed.\n"); auto vkp_command_pool = std::make_shared<vkp::CommandPool>(device, vkp_device.queue_family_index()); RTN_IF_MSG(1, !vkp_command_pool->Init(), "Command Pool Initialization Failed.\n"); auto vkp_command_buffers = std::make_unique<vkp::CommandBuffers>( device, vkp_command_pool, vkp_framebuffer->framebuffers(), vkp_pipeline->get(), vkp_render_pass->get(), extent); RTN_IF_MSG(1, !vkp_command_buffers->Init(), "Command Buffer Initialization Failed.\n"); sleep(1); if (!DrawAllFrames(vkp_device, *vkp_command_buffers)) { RTN_MSG(1, "First DrawAllFrames Failed.\n"); } device->waitIdle(); auto start_time = std::chrono::steady_clock::now(); if (!DrawAllFrames(vkp_device, *vkp_command_buffers)) { RTN_MSG(1, "Second DrawAllFrames Failed.\n"); } device->waitIdle(); auto end_time = std::chrono::steady_clock::now(); fprintf(stderr, "End time: %lld\n", std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time).count()); return 0; } bool DrawAllFrames(const vkp::Device& device, const vkp::CommandBuffers& command_buffers) { vk::SubmitInfo submit_info; submit_info.commandBufferCount = static_cast<uint32_t>(command_buffers.command_buffers().size()); std::vector<vk::CommandBuffer> command_buffer(submit_info.commandBufferCount); for (uint32_t i = 0; i < submit_info.commandBufferCount; i++) { command_buffer[i] = command_buffers.command_buffers()[i].get(); } submit_info.pCommandBuffers = command_buffer.data(); if (device.queue().submit(1, &submit_info, vk::Fence()) != vk::Result::eSuccess) { RTN_MSG(false, "Failed to submit draw command buffer.\n"); } return true; }
#include <unistd.h> #include <memory> #include <vector> #include "src/graphics/examples/vkproto/common/command_buffers.h" #include "src/graphics/examples/vkproto/common/command_pool.h" #include "src/graphics/examples/vkproto/common/debug_utils_messenger.h" #include "src/graphics/examples/vkproto/common/device.h" #include "src/graphics/examples/vkproto/common/framebuffers.h" #include "src/graphics/examples/vkproto/common/graphics_pipeline.h" #include "src/graphics/examples/vkproto/common/image_view.h" #include "src/graphics/examples/vkproto/common/instance.h" #include "src/graphics/examples/vkproto/common/physical_device.h" #include "src/graphics/examples/vkproto/common/render_pass.h" #include "src/graphics/examples/vkproto/common/swapchain.h" #include "src/graphics/examples/vkproto/common/utils.h" #include <vulkan/vulkan.hpp> static bool DrawAllFrames(const vkp::Device& vkp_device, const vkp::CommandBuffers& vkp_command_buffers); int main(int argc, char* argv[]) { #ifndef NDEBUG printf("Warning - benchmarking debug build.\n"); const bool kEnableValidation = true; #else const bool kEnableValidation = false; #endif vkp::Instance vkp_instance(kEnableValidation); RTN_IF_MSG(1, !vkp_instance.Init(), "Instance Initialization Failed.\n");
vkp::PhysicalDevice vkp_physical_device(vkp_instance.shared()); RTN_IF_MSG(1, !vkp_physical_device.Init(), "Phys Device Initialization Failed.\n"); vkp::Device vkp_device(vkp_physical_device.get()); RTN_IF_MSG(1, !vkp_device.Init(), "Logical Device Initialization Failed.\n"); std::shared_ptr<vk::Device> device = vkp_device.shared(); vk::Format image_format; vk::Extent2D extent; std::vector<std::shared_ptr<vkp::ImageView>> vkp_image_views; std::vector<vk::ImageView> image_views; constexpr uint32_t kCommandBufferCount = 100; for (uint32_t i = 0; i < kCommandBufferCount; i++) { auto vkp_offscreen_image_view = std::make_shared<vkp::ImageView>(device, vkp_physical_device.get(), vk::Extent2D{64, 64}); RTN_IF_MSG(1, !vkp_offscreen_image_view->Init(), "Image View Initialization Failed.\n"); image_format = vkp_offscreen_image_view->format(); extent = vkp_offscreen_image_view->extent(); image_views.emplace_back(vkp_offscreen_image_view->get()); vkp_image_views.emplace_back(std::move(vkp_offscreen_image_view)); } auto vkp_render_pass = std::make_shared<vkp::RenderPass>(device, image_format, true); RTN_IF_MSG(1, !vkp_render_pass->Init(), "Render Pass Initialization Failed.\n"); auto vkp_pipeline = std::make_unique<vkp::GraphicsPipeline>(device, extent, vkp_render_pass); RTN_IF_MSG(1, !vkp_pipeline->Init(), "Graphics Pipeline Initialization Failed.\n"); auto vkp_framebuffer = std::make_unique<vkp::Framebuffers>(device, extent, vkp_render_pass->get(), image_views); RTN_IF_MSG(1, !vkp_framebuffer->Init(), "Framebuffers Initialization Failed.\n"); auto vkp_command_pool = std::make_shared<vkp::CommandPool>(device, vkp_device.queue_family_index()); RTN_IF_MSG(1, !vkp_command_pool->Init(), "Command Pool Initialization Failed.\n"); auto vkp_command_buffers = std::make_unique<vkp::CommandBuffers>( device, vkp_command_pool, vkp_framebuffer->framebuffers(), vkp_pipeline->get(), vkp_render_pass->get(), extent); RTN_IF_MSG(1, !vkp_command_buffers->Init(), "Command Buffer Initialization Failed.\n"); sleep(1); if (!DrawAllFrames(vkp_device, *vkp_command_buffers)) { RTN_MSG(1, "First DrawAllFrames Failed.\n"); } device->waitIdle(); auto start_time = std::chrono::steady_clock::now(); if (!DrawAllFrames(vkp_device, *vkp_command_buffers)) { RTN_MSG(1, "Second DrawAllFrames Failed.\n"); } device->waitIdle(); auto end_time = std::chrono::steady_clock::now(); fprintf(stderr, "End time: %lld\n", std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time).count()); return 0; } bool DrawAllFrames(const vkp::Device& device, const vkp::CommandBuffers& command_buffers) { vk::SubmitInfo submit_info; submit_info.commandBufferCount = static_cast<uint32_t>(command_buffers.command_buffers().size()); std::vector<vk::CommandBuffer> command_buffer(submit_info.commandBufferCount); for (uint32_t i = 0; i < submit_info.commandBufferCount; i++) { command_buffer[i] = command_buffers.command_buffers()[i].get(); } submit_info.pCommandBuffers = command_buffer.data(); if (device.queue().submit(1, &submit_info, vk::Fence()) != vk::Result::eSuccess) { RTN_MSG(false, "Failed to submit draw command buffer.\n"); } return true; }
if (kEnableValidation) { vkp::DebugUtilsMessenger vkp_debug_messenger(vkp_instance.shared()); RTN_IF_MSG(1, !vkp_debug_messenger.Init(), "Debug Messenger Initialization Failed.\n"); }
if_condition
[]
C++
src/resources/track.hpp
mnewhouse/tselements
bd1c6724018e862156948a680bb1bc70dd28bef6
#pragma once #include "tile_library.hpp" #include "terrain_library.hpp" #include "texture_library.hpp" #include "path_library.hpp" #include "track_layer.hpp" #include "start_point.hpp" #include "control_point.hpp" #include "track_path.hpp" #include "utility/vector2.hpp" #include <boost/range/iterator_range.hpp> #include <boost/iterator/transform_iterator.hpp> #include <boost/iterator/indirect_iterator.hpp> #include <vector> #include <list> #include <memory> #include <string> #include <cstdint> #include <cstddef> #include <map> namespace ts { namespace resources { namespace detail { struct ConstPathRangeTransform { const resources::TrackPath* operator()(const std::unique_ptr<TrackPath>& p) const { return p.get(); } }; struct PathRangeTransform { resources::TrackPath* operator()(const std::unique_ptr<TrackPath>& p) const { return p.get(); } }; } class Track { public: Track() = default; Track(const Track&) = default; Track& operator=(const Track&) = default; Track(Track&&) = default; Track& operator=(Track&&) = default; void set_path(const std::string& path); const std::string& path() const noexcept; void set_author(std::string author); const std::string& author() const noexcept; Vector2i size() const; void set_size(const Vector2i& size); void set_height_level_count(std::int32_t height_levels) noexcept; std::int32_t height_level_count() const noexcept; TileLibrary& tile_library() noexcept; const TileLibrary& tile_library() const noexcept; TextureLibrary& texture_library() noexcept; const TextureLibrary& texture_library() const noexcept; TerrainLibrary& terrain_library() noexcept; const TerrainLibrary& terrain_library() const noexcept; PathLibrary& path_library() noexcept; const PathLibrary& path_library() const noexcept; using LayerId = std::uint32_t; TrackLayer* create_layer(TrackLayerType type, std::string layer_name, std::uint32_t level); void deactivate_layer(TrackLayer* layer); void activate_layer(TrackLayer* layer); std::size_t layer_count() const noexcept; void set_layer_level(TrackLayer* layer, std::uint32_t level); std::int32_t shift_towards_front(const TrackLayer* layer, std::int32_t amount = 1); std::int32_t shift_towards_back(const TrackLayer* layer, std::int32_t amount = 1); using LayerOrderInterface = boost::iterator_range<boost::indirect_iterator<TrackLayer* const*>>; using ConstLayerOrderInterface = boost::iterator_range<boost::indirect_iterator<const TrackLayer* const*>>; LayerOrderInterface layers(); ConstLayerOrderInterface layers() const; void add_control_point(const ControlPoint& point); void add_control_point(const ControlPoint& point, std::size_t idx); const std::vector<ControlPoint>& control_points() const; void remove_control_point(std::size_t idx); void update_control_point(std::size_t idx, const ControlPoint& cp); void add_start_point(const StartPoint& point); const std::vector<StartPoint>& custom_start_points() const; const std::vector<StartPoint>& start_points() const; void add_asset(const std::string& path); const std::vector<std::string>& assets() const; private: void insert_layer(TrackLayer* layer); void update_z_index(); std::string path_; std::string author_; Vector2i size_ = {}; std::int32_t height_level_count_ = 1; TileLibrary tile_library_; TerrainLibrary terrain_library_; TextureLibrary texture_library_; PathLibrary path_library_; std::vector<std::string> assets_; std::map<LayerId, TrackLayer> layers_; std::vector<TrackLayer*> layer_order_; std::vector<ControlPoint> control_points_; std::vector<StartPoint> custom_start_points_; mutable std::vector<StartPoint> start_points_; }; template<typename LayerType> struct LayerOrderInterface { private: friend Track; explicit LayerOrderInterface(LayerType** begin, LayerType** end); LayerType** begin_; LayerType** end_; }; } }
#pragma once #include "tile_library.hpp" #include "terrain_library.hpp" #include "texture_library.hpp" #include "path_library.hpp" #include "track_layer.hpp" #include "start_point.hpp" #include "control_point.hpp" #include "track_path.hpp" #include "utility/vector2.hpp" #include <boost/range/iterator_range.hpp> #include <boost/iterator/transform_iterator.hpp> #include <boost/iterator/indirect_iterator.hpp> #include <vector> #include <list> #include <memory> #include <string> #include <
ult; Track& operator=(const Track&) = default; Track(Track&&) = default; Track& operator=(Track&&) = default; void set_path(const std::string& path); const std::string& path() const noexcept; void set_author(std::string author); const std::string& author() const noexcept; Vector2i size() const; void set_size(const Vector2i& size); void set_height_level_count(std::int32_t height_levels) noexcept; std::int32_t height_level_count() const noexcept; TileLibrary& tile_library() noexcept; const TileLibrary& tile_library() const noexcept; TextureLibrary& texture_library() noexcept; const TextureLibrary& texture_library() const noexcept; TerrainLibrary& terrain_library() noexcept; const TerrainLibrary& terrain_library() const noexcept; PathLibrary& path_library() noexcept; const PathLibrary& path_library() const noexcept; using LayerId = std::uint32_t; TrackLayer* create_layer(TrackLayerType type, std::string layer_name, std::uint32_t level); void deactivate_layer(TrackLayer* layer); void activate_layer(TrackLayer* layer); std::size_t layer_count() const noexcept; void set_layer_level(TrackLayer* layer, std::uint32_t level); std::int32_t shift_towards_front(const TrackLayer* layer, std::int32_t amount = 1); std::int32_t shift_towards_back(const TrackLayer* layer, std::int32_t amount = 1); using LayerOrderInterface = boost::iterator_range<boost::indirect_iterator<TrackLayer* const*>>; using ConstLayerOrderInterface = boost::iterator_range<boost::indirect_iterator<const TrackLayer* const*>>; LayerOrderInterface layers(); ConstLayerOrderInterface layers() const; void add_control_point(const ControlPoint& point); void add_control_point(const ControlPoint& point, std::size_t idx); const std::vector<ControlPoint>& control_points() const; void remove_control_point(std::size_t idx); void update_control_point(std::size_t idx, const ControlPoint& cp); void add_start_point(const StartPoint& point); const std::vector<StartPoint>& custom_start_points() const; const std::vector<StartPoint>& start_points() const; void add_asset(const std::string& path); const std::vector<std::string>& assets() const; private: void insert_layer(TrackLayer* layer); void update_z_index(); std::string path_; std::string author_; Vector2i size_ = {}; std::int32_t height_level_count_ = 1; TileLibrary tile_library_; TerrainLibrary terrain_library_; TextureLibrary texture_library_; PathLibrary path_library_; std::vector<std::string> assets_; std::map<LayerId, TrackLayer> layers_; std::vector<TrackLayer*> layer_order_; std::vector<ControlPoint> control_points_; std::vector<StartPoint> custom_start_points_; mutable std::vector<StartPoint> start_points_; }; template<typename LayerType> struct LayerOrderInterface { private: friend Track; explicit LayerOrderInterface(LayerType** begin, LayerType** end); LayerType** begin_; LayerType** end_; }; } }
cstdint> #include <cstddef> #include <map> namespace ts { namespace resources { namespace detail { struct ConstPathRangeTransform { const resources::TrackPath* operator()(const std::unique_ptr<TrackPath>& p) const { return p.get(); } }; struct PathRangeTransform { resources::TrackPath* operator()(const std::unique_ptr<TrackPath>& p) const { return p.get(); } }; } class Track { public: Track() = default; Track(const Track&) = defa
random
[ { "content": "/*\n\n * Created by Phil on 5/11/2010.\n\n * Copyright 2010 Two Blue Cubes Ltd. All rights reserved.\n\n *\n\n * Distributed under the Boost Software License, Version 1.0. (See accompanying\n\n * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n */\n\n#ifndef TWOBLUECUBES_CATCH_LIST_HPP_INCLUDED\n\n#define TWOBLUECUBES_CATCH_LIST_HPP_INCLUDED\n\n\n\n#include \"catch_commandline.hpp\"\n\n#include \"catch_text.h\"\n\n#include \"catch_console_colour.hpp\"\n\n#include \"catch_interfaces_reporter.h\"\n\n#include \"catch_test_spec_parser.hpp\"\n\n\n\n#include <limits>\n\n#include <algorithm>\n\n\n\nnamespace Catch {\n", "file_path": "dependencies/catch/include/internal/catch_list.hpp", "rank": 0, "score": 106285.11305512878 }, { "content": " return factories.size();\n\n }\n\n\n\n inline Option<std::size_t> list( Config const& config ) {\n\n Option<std::size_t> listedCount;\n\n if( config.listTests() )\n\n listedCount = listedCount.valueOr(0) + listTests( config );\n\n if( config.listTestNamesOnly() )\n\n listedCount = listedCount.valueOr(0) + listTestsNamesOnly( config );\n\n if( config.listTags() )\n\n listedCount = listedCount.valueOr(0) + listTags( config );\n\n if( config.listReporters() )\n\n listedCount = listedCount.valueOr(0) + listReporters( config );\n\n return listedCount;\n\n }\n\n\n\n} // end namespace Catch\n\n\n\n#endif // TWOBLUECUBES_CATCH_LIST_HPP_INCLUDED\n", "file_path": "dependencies/catch/include/internal/catch_list.hpp", "rank": 1, "score": 106284.04172676249 }, { "content": " ++count;\n\n spellings.insert( spelling );\n\n }\n\n std::string all() const {\n\n std::string out;\n\n for( std::set<std::string>::const_iterator it = spellings.begin(), itEnd = spellings.end();\n\n it != itEnd;\n\n ++it )\n\n out += \"[\" + *it + \"]\";\n\n return out;\n\n }\n\n std::set<std::string> spellings;\n\n std::size_t count;\n\n };\n\n\n\n inline std::size_t listTags( Config const& config ) {\n\n TestSpec testSpec = config.testSpec();\n\n if( config.testSpec().hasFilters() )\n\n Catch::cout() << \"Tags for matching test cases:\\n\";\n\n else {\n", "file_path": "dependencies/catch/include/internal/catch_list.hpp", "rank": 2, "score": 106283.11018546503 }, { "content": " inline std::size_t listTestsNamesOnly( Config const& config ) {\n\n TestSpec testSpec = config.testSpec();\n\n if( !config.testSpec().hasFilters() )\n\n testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( \"*\" ).testSpec();\n\n std::size_t matchedTests = 0;\n\n std::vector<TestCase> matchedTestCases;\n\n getRegistryHub().getTestCaseRegistry().getFilteredTests( testSpec, config, matchedTestCases );\n\n for( std::vector<TestCase>::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end();\n\n it != itEnd;\n\n ++it ) {\n\n matchedTests++;\n\n TestCaseInfo const& testCaseInfo = it->getTestCaseInfo();\n\n Catch::cout() << testCaseInfo.name << std::endl;\n\n }\n\n return matchedTests;\n\n }\n\n\n\n struct TagInfo {\n\n TagInfo() : count ( 0 ) {}\n\n void add( std::string const& spelling ) {\n", "file_path": "dependencies/catch/include/internal/catch_list.hpp", "rank": 3, "score": 106281.95762104508 }, { "content": " Catch::cout() << \"All available tags:\\n\";\n\n testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( \"*\" ).testSpec();\n\n }\n\n\n\n std::map<std::string, TagInfo> tagCounts;\n\n\n\n std::vector<TestCase> matchedTestCases;\n\n getRegistryHub().getTestCaseRegistry().getFilteredTests( testSpec, config, matchedTestCases );\n\n for( std::vector<TestCase>::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end();\n\n it != itEnd;\n\n ++it ) {\n\n for( std::set<std::string>::const_iterator tagIt = it->getTestCaseInfo().tags.begin(),\n\n tagItEnd = it->getTestCaseInfo().tags.end();\n\n tagIt != tagItEnd;\n\n ++tagIt ) {\n\n std::string tagName = *tagIt;\n\n std::string lcaseTagName = toLower( tagName );\n\n std::map<std::string, TagInfo>::iterator countIt = tagCounts.find( lcaseTagName );\n\n if( countIt == tagCounts.end() )\n\n countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;\n", "file_path": "dependencies/catch/include/internal/catch_list.hpp", "rank": 4, "score": 106281.91109259009 }, { "content": "\n\n inline std::size_t listTests( Config const& config ) {\n\n\n\n TestSpec testSpec = config.testSpec();\n\n if( config.testSpec().hasFilters() )\n\n Catch::cout() << \"Matching test cases:\\n\";\n\n else {\n\n Catch::cout() << \"All available test cases:\\n\";\n\n testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( \"*\" ).testSpec();\n\n }\n\n\n\n std::size_t matchedTests = 0;\n\n TextAttributes nameAttr, tagsAttr;\n\n nameAttr.setInitialIndent( 2 ).setIndent( 4 );\n\n tagsAttr.setIndent( 6 );\n\n\n\n std::vector<TestCase> matchedTestCases;\n\n getRegistryHub().getTestCaseRegistry().getFilteredTests( testSpec, config, matchedTestCases );\n\n for( std::vector<TestCase>::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end();\n\n it != itEnd;\n", "file_path": "dependencies/catch/include/internal/catch_list.hpp", "rank": 5, "score": 106279.49501884238 }, { "content": " inline std::size_t listReporters( Config const& /*config*/ ) {\n\n Catch::cout() << \"Available reporters:\\n\";\n\n IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();\n\n IReporterRegistry::FactoryMap::const_iterator itBegin = factories.begin(), itEnd = factories.end(), it;\n\n std::size_t maxNameLen = 0;\n\n for(it = itBegin; it != itEnd; ++it )\n\n maxNameLen = (std::max)( maxNameLen, it->first.size() );\n\n\n\n for(it = itBegin; it != itEnd; ++it ) {\n\n Text wrapper( it->second->getDescription(), TextAttributes()\n\n .setInitialIndent( 0 )\n\n .setIndent( 7+maxNameLen )\n\n .setWidth( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 ) );\n\n Catch::cout() << \" \"\n\n << it->first\n\n << \":\"\n\n << std::string( maxNameLen - it->first.size() + 2, ' ' )\n\n << wrapper << \"\\n\";\n\n }\n\n Catch::cout() << std::endl;\n", "file_path": "dependencies/catch/include/internal/catch_list.hpp", "rank": 6, "score": 106278.3007672196 }, { "content": " countIt->second.add( tagName );\n\n }\n\n }\n\n\n\n for( std::map<std::string, TagInfo>::const_iterator countIt = tagCounts.begin(),\n\n countItEnd = tagCounts.end();\n\n countIt != countItEnd;\n\n ++countIt ) {\n\n std::ostringstream oss;\n\n oss << \" \" << std::setw(2) << countIt->second.count << \" \";\n\n Text wrapper( countIt->second.all(), TextAttributes()\n\n .setInitialIndent( 0 )\n\n .setIndent( oss.str().size() )\n\n .setWidth( CATCH_CONFIG_CONSOLE_WIDTH-10 ) );\n\n Catch::cout() << oss.str() << wrapper << \"\\n\";\n\n }\n\n Catch::cout() << pluralise( tagCounts.size(), \"tag\" ) << \"\\n\" << std::endl;\n\n return tagCounts.size();\n\n }\n\n\n", "file_path": "dependencies/catch/include/internal/catch_list.hpp", "rank": 7, "score": 106275.8980097289 }, { "content": " ++it ) {\n\n matchedTests++;\n\n TestCaseInfo const& testCaseInfo = it->getTestCaseInfo();\n\n Colour::Code colour = testCaseInfo.isHidden()\n\n ? Colour::SecondaryText\n\n : Colour::None;\n\n Colour colourGuard( colour );\n\n\n\n Catch::cout() << Text( testCaseInfo.name, nameAttr ) << std::endl;\n\n if( !testCaseInfo.tags.empty() )\n\n Catch::cout() << Text( testCaseInfo.tagsAsString, tagsAttr ) << std::endl;\n\n }\n\n\n\n if( !config.testSpec().hasFilters() )\n\n Catch::cout() << pluralise( matchedTests, \"test case\" ) << \"\\n\" << std::endl;\n\n else\n\n Catch::cout() << pluralise( matchedTests, \"matching test case\" ) << \"\\n\" << std::endl;\n\n return matchedTests;\n\n }\n\n\n", "file_path": "dependencies/catch/include/internal/catch_list.hpp", "rank": 8, "score": 106275.71357107938 }, { "content": "#include \"catch.hpp\"\n\n#include <vector>\n\n\n\n\n\n// vedctor\n\nTEST_CASE( \"vector<int> -> toString\", \"[toString][vector]\" )\n\n{\n\n std::vector<int> vv;\n\n REQUIRE( Catch::toString(vv) == \"{ }\" );\n\n vv.push_back( 42 );\n\n REQUIRE( Catch::toString(vv) == \"{ 42 }\" );\n\n vv.push_back( 250 );\n\n REQUIRE( Catch::toString(vv) == \"{ 42, 250 }\" );\n\n}\n\n\n\nTEST_CASE( \"vector<string> -> toString\", \"[toString][vector]\" )\n\n{\n\n std::vector<std::string> vv;\n\n REQUIRE( Catch::toString(vv) == \"{ }\" );\n\n vv.push_back( \"hello\" );\n", "file_path": "dependencies/catch/projects/SelfTest/ToStringVector.cpp", "rank": 9, "score": 104656.754491409 }, { "content": " REQUIRE( Catch::toString(vv) == \"{ 42, 250 }\" );\n\n}\n\n\n\nTEST_CASE( \"vec<vec<string,alloc>> -> toString\", \"[toString][vector,allocator]\" ) {\n\n typedef std::vector<std::string,minimal_allocator<std::string> > inner;\n\n typedef std::vector<inner> vector;\n\n vector v;\n\n REQUIRE( Catch::toString(v) == \"{ }\" );\n\n v.push_back( inner { \"hello\" } );\n\n v.push_back( inner { \"world\" } );\n\n REQUIRE( Catch::toString(v) == \"{ { \\\"hello\\\" }, { \\\"world\\\" } }\" );\n\n}\n\n\n\n#ifdef __clang__\n\n#pragma clang diagnostic pop\n\n#endif\n\n#endif // CATCH_CPP11_OR_GREATER\n", "file_path": "dependencies/catch/projects/SelfTest/ToStringVector.cpp", "rank": 10, "score": 104654.56610708775 }, { "content": " typedef std::size_t size_type;\n\n T *allocate( size_type n ) {\n\n return static_cast<T *>( ::operator new( n * sizeof(T) ) );\n\n }\n\n void deallocate( T *p, size_type /*n*/ ) {\n\n ::operator delete( static_cast<void *>(p) );\n\n }\n\n template<typename U>\n\n bool operator==( const minimal_allocator<U>& ) const { return true; }\n\n template<typename U>\n\n bool operator!=( const minimal_allocator<U>& ) const { return false; }\n\n };\n\n}\n\n\n\nTEST_CASE( \"vector<int,allocator> -> toString\", \"[toString][vector,allocator]\" ) {\n\n std::vector<int,minimal_allocator<int> > vv;\n\n REQUIRE( Catch::toString(vv) == \"{ }\" );\n\n vv.push_back( 42 );\n\n REQUIRE( Catch::toString(vv) == \"{ 42 }\" );\n\n vv.push_back( 250 );\n", "file_path": "dependencies/catch/projects/SelfTest/ToStringVector.cpp", "rank": 11, "score": 104648.14493087585 }, { "content": " REQUIRE( Catch::toString(vv) == \"{ \\\"hello\\\" }\" );\n\n vv.push_back( \"world\" );\n\n REQUIRE( Catch::toString(vv) == \"{ \\\"hello\\\", \\\"world\\\" }\" );\n\n}\n\n\n\n#if defined(CATCH_CPP11_OR_GREATER)\n\n#ifdef __clang__\n\n#pragma clang diagnostic push\n\n#pragma clang diagnostic ignored \"-Wc++98-compat\"\n\n#endif\n\n\n\n/*\n\n Note: These tests *can* be made to work with C++ < 11, but the\n\n allocator is a lot more work...\n\n*/\n\nnamespace {\n\n /* Minimal Allocator */\n\n template<typename T>\n\n struct minimal_allocator {\n\n typedef T value_type;\n", "file_path": "dependencies/catch/projects/SelfTest/ToStringVector.cpp", "rank": 12, "score": 104647.09308975127 }, { "content": "struct StringMaker :\n\n Detail::StringMakerBase<Detail::IsStreamInsertable<T>::value> {};\n\n\n\ntemplate<typename T>\n", "file_path": "dependencies/catch/single_include/catch.hpp", "rank": 13, "score": 102943.81152685128 }, { "content": "struct StringMaker<T*> {\n\n template<typename U>\n\n static std::string convert( U* p ) {\n\n if( !p )\n\n return INTERNAL_CATCH_STRINGIFY( NULL );\n\n else\n\n return Detail::rawMemoryToString( p );\n\n }\n\n};\n\n\n\ntemplate<typename R, typename C>\n", "file_path": "dependencies/catch/single_include/catch.hpp", "rank": 14, "score": 99827.84109724201 }, { "content": " struct point *list; /* allocated list */\n", "file_path": "dependencies/zlib-1.2.8/examples/zran.c", "rank": 15, "score": 97027.0703027005 }, { "content": "std::string toString( T const& value ) {\n\n return StringMaker<T>::convert( value );\n", "file_path": "dependencies/catch/include/internal/catch_tostring.h", "rank": 16, "score": 96894.96121409806 }, { "content": "struct StringMaker<R C::*> {\n\n static std::string convert( R C::* p ) {\n\n if( !p )\n\n return INTERNAL_CATCH_STRINGIFY( NULL );\n\n else\n\n return Detail::rawMemoryToString( p );\n\n }\n\n};\n\n\n\nnamespace Detail {\n\n template<typename InputIterator>\n\n std::string rangeToString( InputIterator first, InputIterator last );\n\n}\n\n\n\n//template<typename T, typename Allocator>\n\n//struct StringMaker<std::vector<T, Allocator> > {\n\n// static std::string convert( std::vector<T,Allocator> const& v ) {\n\n// return Detail::rangeToString( v.begin(), v.end() );\n\n// }\n\n//};\n", "file_path": "dependencies/catch/single_include/catch.hpp", "rank": 17, "score": 96894.96121409806 }, { "content": "\tcpConstraint *constraintList;\n", "file_path": "dependencies/chipmunk-7.0.2/include/chipmunk/chipmunk_structs.h", "rank": 18, "score": 94140.14914889622 }, { "content": "\tcpArbiter *arbiterList;\n", "file_path": "dependencies/chipmunk-7.0.2/include/chipmunk/chipmunk_structs.h", "rank": 19, "score": 94140.14914889622 }, { "content": "\tcpShape *shapeList;\n", "file_path": "dependencies/chipmunk-7.0.2/include/chipmunk/chipmunk_structs.h", "rank": 20, "score": 94140.14914889622 }, { "content": "struct StringMaker<std::tuple<Types...>> {\n\n\n\n static std::string convert( const std::tuple<Types...>& tuple )\n\n {\n\n std::ostringstream os;\n\n os << '{';\n\n TupleDetail::ElementPrinter<std::tuple<Types...>>::print( tuple, os );\n\n os << \" }\";\n\n return os.str();\n\n }\n\n};\n\n#endif // CATCH_CONFIG_CPP11_TUPLE\n\n\n\nnamespace Detail {\n\n template<typename T>\n\n std::string makeString( T const& value ) {\n\n return StringMaker<T>::convert( value );\n\n }\n\n} // end namespace Detail\n\n\n", "file_path": "dependencies/catch/single_include/catch.hpp", "rank": 21, "score": 94129.49518961307 }, { "content": " CHAR DeviceString[128]; \n", "file_path": "dependencies/chipmunk-7.0.2/msvc/glew/include/GL/wglew.h", "rank": 22, "score": 91517.50637859157 }, { "content": "GLEW_VAR_EXPORT GLboolean __GLEW_AMD_pinned_memory;\n", "file_path": "dependencies/chipmunk-7.0.2/msvc/glew/include/GL/glew.h", "rank": 23, "score": 86724.79632590723 }, { "content": "GLEW_VAR_EXPORT GLboolean __GLEW_SUN_triangle_list;\n", "file_path": "dependencies/chipmunk-7.0.2/msvc/glew/include/GL/glew.h", "rank": 24, "score": 86715.3553509698 }, { "content": "GLEW_VAR_EXPORT GLboolean __GLEW_SGIX_list_priority;\n", "file_path": "dependencies/chipmunk-7.0.2/msvc/glew/include/GL/glew.h", "rank": 25, "score": 86715.3553509698 }, { "content": "GLEW_VAR_EXPORT GLboolean __GLEW_APPLE_specular_vector;\n", "file_path": "dependencies/chipmunk-7.0.2/msvc/glew/include/GL/glew.h", "rank": 26, "score": 86712.08613964343 }, { "content": "WGLEW_VAR_EXPORT GLboolean __WGLEW_EXT_extensions_string;\n", "file_path": "dependencies/chipmunk-7.0.2/msvc/glew/include/GL/wglew.h", "rank": 27, "score": 86705.541664955 }, { "content": "GLEW_VAR_EXPORT GLboolean __GLEW_GREMEDY_string_marker;\n", "file_path": "dependencies/chipmunk-7.0.2/msvc/glew/include/GL/glew.h", "rank": 28, "score": 86705.541664955 }, { "content": "GLEW_VAR_EXPORT GLboolean __GLEW_REGAL_error_string;\n", "file_path": "dependencies/chipmunk-7.0.2/msvc/glew/include/GL/glew.h", "rank": 29, "score": 86705.541664955 }, { "content": "WGLEW_VAR_EXPORT GLboolean __WGLEW_ARB_extensions_string;\n", "file_path": "dependencies/chipmunk-7.0.2/msvc/glew/include/GL/wglew.h", "rank": 30, "score": 86705.541664955 }, { "content": "GLEW_VAR_EXPORT GLboolean __GLEW_AMD_pinned_memory;\n", "file_path": "dependencies/chipmunk-7.0.2/xcode/libGLEW/include/GL/glew.h", "rank": 31, "score": 84503.21860697691 }, { "content": "GLEW_VAR_EXPORT GLboolean __GLEW_NVX_gpu_memory_info;\n", "file_path": "dependencies/chipmunk-7.0.2/msvc/glew/include/GL/glew.h", "rank": 32, "score": 84503.21860697691 }, { "content": "GLEW_VAR_EXPORT GLboolean __GLEW_IBM_vertex_array_lists;\n", "file_path": "dependencies/chipmunk-7.0.2/msvc/glew/include/GL/glew.h", "rank": 33, "score": 84494.01947590022 }, { "content": "GLEW_VAR_EXPORT GLboolean __GLEW_SUN_triangle_list;\n", "file_path": "dependencies/chipmunk-7.0.2/xcode/libGLEW/include/GL/glew.h", "rank": 34, "score": 84494.01947590022 }, { "content": "GLEW_VAR_EXPORT GLboolean __GLEW_SGIX_list_priority;\n", "file_path": "dependencies/chipmunk-7.0.2/xcode/libGLEW/include/GL/glew.h", "rank": 35, "score": 84494.01947590022 }, { "content": "GLEW_VAR_EXPORT GLboolean __GLEW_APPLE_specular_vector;\n", "file_path": "dependencies/chipmunk-7.0.2/xcode/libGLEW/include/GL/glew.h", "rank": 36, "score": 84490.83401002325 }, { "content": "GLEW_VAR_EXPORT GLboolean __GLEW_GREMEDY_string_marker;\n", "file_path": "dependencies/chipmunk-7.0.2/xcode/libGLEW/include/GL/glew.h", "rank": 37, "score": 84484.45718126498 }, { "content": "GLEW_VAR_EXPORT GLboolean __GLEW_REGAL_error_string;\n", "file_path": "dependencies/chipmunk-7.0.2/xcode/libGLEW/include/GL/glew.h", "rank": 38, "score": 84484.45718126498 }, { "content": "GLEW_VAR_EXPORT GLboolean __GLEW_NVX_gpu_memory_info;\n", "file_path": "dependencies/chipmunk-7.0.2/xcode/libGLEW/include/GL/glew.h", "rank": 39, "score": 82392.61578981737 }, { "content": "GLEW_VAR_EXPORT GLboolean __GLEW_NV_vertex_buffer_unified_memory;\n", "file_path": "dependencies/chipmunk-7.0.2/msvc/glew/include/GL/glew.h", "rank": 40, "score": 82392.61578981737 }, { "content": "GLEW_VAR_EXPORT GLboolean __GLEW_IBM_vertex_array_lists;\n", "file_path": "dependencies/chipmunk-7.0.2/xcode/libGLEW/include/GL/glew.h", "rank": 41, "score": 82383.64642172825 }, { "content": "GLEW_VAR_EXPORT GLboolean __GLEW_NV_vertex_buffer_unified_memory;\n", "file_path": "dependencies/chipmunk-7.0.2/xcode/libGLEW/include/GL/glew.h", "rank": 42, "score": 80384.875175908 }, { "content": "struct ImGuiListClipper; // Helper to manually clip large list of items\n", "file_path": "src/imgui/imgui.h", "rank": 43, "score": 71992.0353780674 }, { "content": "struct ImDrawList; // A single draw command list (generally one per window)\n", "file_path": "src/imgui/imgui.h", "rank": 44, "score": 70056.62963776068 }, { "content": "struct has_toString { };\n", "file_path": "dependencies/catch/projects/SelfTest/ToStringWhich.cpp", "rank": 45, "score": 67366.04175752998 }, { "content": "struct has_maker_and_toString {};\n\n\n\nnamespace Catch {\n\n inline std::string toString( const has_toString& ) {\n\n return \"toString( has_toString )\";\n\n }\n\n inline std::string toString( const has_maker_and_toString& ) {\n\n return \"toString( has_maker_and_toString )\";\n\n }\n\n template<>\n\n struct StringMaker<has_maker> {\n\n static std::string convert( const has_maker& ) {\n\n return \"StringMaker<has_maker>\";\n\n }\n\n };\n\n template<>\n\n struct StringMaker<has_maker_and_toString> {\n\n static std::string convert( const has_maker_and_toString& ) {\n\n return \"StringMaker<has_maker_and_toString>\";\n\n }\n", "file_path": "dependencies/catch/projects/SelfTest/ToStringWhich.cpp", "rank": 46, "score": 66038.85746424063 }, { "content": "/*\n\n* TS Elements\n\n* Copyright 2015-2018 M. Newhouse\n\n* Released under the MIT license.\n\n*/\n\n\n\n#pragma once\n\n\n\n#include <algorithm>\n\n#include <cctype>\n\n#include <iterator>\n\n\n\n#include <boost/utility/string_ref.hpp>\n\n#include <boost/functional/hash.hpp>\n\n\n\n#include \"caseless_string_compare.hpp\"\n\n\n\nnamespace ts\n\n{\n\n // This function template splits a block of memory by newlines. \n", "file_path": "src/utility/string_utilities.hpp", "rank": 47, "score": 57740.87699236288 }, { "content": "/*\n\n* TS Elements\n\n* Copyright 2015-2018 M. Newhouse\n\n* Released under the MIT license.\n\n*/\n\n\n\n#include \"string_utilities.hpp\"\n\n\n\n#include <iostream>\n\n\n\nnamespace ts\n\n{\n\n}", "file_path": "src/utility/string_utilities.cpp", "rank": 48, "score": 57731.30341313457 }, { "content": "class ImVector\n\n{\n\npublic:\n\n int Size;\n\n int Capacity;\n\n T* Data;\n\n\n\n typedef T value_type;\n\n typedef value_type* iterator;\n\n typedef const value_type* const_iterator;\n\n\n\n ImVector() { Size = Capacity = 0; Data = NULL; }\n\n ~ImVector() { if (Data) ImGui::MemFree(Data); }\n\n\n\n inline bool empty() const { return Size == 0; }\n\n inline int size() const { return Size; }\n\n inline int capacity() const { return Capacity; }\n\n\n\n inline value_type& operator[](int i) { IM_ASSERT(i < Size); return Data[i]; }\n\n inline const value_type& operator[](int i) const { IM_ASSERT(i < Size); return Data[i]; }\n", "file_path": "src/imgui/imgui.h", "rank": 49, "score": 57727.78906196238 }, { "content": " // OutputIt must be dereferencable and then assignable from a brace-init-list\n\n // containing a const char* and a std::size_t.\n\n // For example, a (back_)insert_iterator for a container holding strings or string_refs.\n\n template <typename OutputIt>\n\n std::size_t split_by_line(const char* data, std::size_t data_size, OutputIt out)\n\n {\n\n std::size_t count = 0;\n\n for (auto end = data + data_size; data != end; ++count)\n\n {\n\n const char* line_end = std::find(data, end, '\\n');\n\n std::size_t line_size = std::distance(data, line_end);\n\n\n\n *out = { data, line_size }; ++out;\n\n\n\n data = std::find_if(line_end, end, [](char ch) { return ch != '\\n'; });\n\n }\n\n\n\n return count;\n\n }\n\n\n", "file_path": "src/utility/string_utilities.hpp", "rank": 50, "score": 57727.29339691259 }, { "content": " if (new_size == boost::string_ref::npos) new_size = string.size();\n\n\n\n return boost::string_ref(string.data(), new_size);\n\n }\n\n\n\n\n\n template <typename String>\n\n inline void primitive_tolower(String& string)\n\n {\n\n using std::begin;\n\n using std::end;\n\n\n\n std::transform(begin(string), end(string), begin(string), [](auto ch) { return std::tolower(ch); });\n\n }\n\n\n\n struct StringRefHasher\n\n {\n\n auto operator()(boost::string_ref string) const\n\n {\n\n return boost::hash_range(string.begin(), string.end());\n\n }\n\n };\n\n}\n", "file_path": "src/utility/string_utilities.hpp", "rank": 51, "score": 57727.214206387434 }, { "content": " inline boost::string_ref make_string_ref(const char* data, const char* end)\n\n {\n\n return boost::string_ref(data, std::distance(data, end));\n\n }\n\n\n\n inline boost::string_ref remove_leading_spaces(boost::string_ref string, const char* spaces = \" \\t\\r\\n\")\n\n {\n\n auto pos = string.find_first_not_of(spaces);\n\n if (pos == std::string::npos) pos = string.size();\n\n\n\n string.remove_prefix(pos);\n\n return string;\n\n }\n\n\n\n inline boost::string_ref extract_word(boost::string_ref string)\n\n {\n\n const char spaces[] = \" \\t\\r\\n\";\n\n string = remove_leading_spaces(string, spaces);\n\n\n\n auto new_size = string.find_first_of(spaces);\n", "file_path": "src/utility/string_utilities.hpp", "rank": 52, "score": 57727.178707422354 }, { "content": "GLEW_VAR_EXPORT GLboolean __GLEW_ARB_shading_language_include;\n", "file_path": "dependencies/chipmunk-7.0.2/msvc/glew/include/GL/glew.h", "rank": 53, "score": 57155.71522148998 }, { "content": "GLEW_VAR_EXPORT GLboolean __GLEW_ARB_shading_language_include;\n", "file_path": "dependencies/chipmunk-7.0.2/xcode/libGLEW/include/GL/glew.h", "rank": 54, "score": 56166.15355421444 }, { "content": "/*\n\n* TS Elements\n\n* Copyright 2015-2018 M. Newhouse\n\n* Released under the MIT license.\n\n*/\n\n\n\n#pragma once\n\n\n\n#include <string>\n\n#include <initializer_list>\n\n\n\n#include <boost/utility/string_ref.hpp>\n\n#include <boost/filesystem/path.hpp>\n\n\n\nnamespace ts\n\n{\n\n namespace resources\n\n {\n\n // These are utility functions that take a file name and a list of search directories, \n\n // iterating over these directories until the specified file name is found in one of them.\n\n // find_include_directory returns only the directory, find_include_path returns the full path.\n\n // If the file is not found, an empty-state object is returned.\n\n // Paths are expected to be UTF-8 encoded.\n\n\n\n boost::string_ref find_include_directory(boost::string_ref file_name, std::initializer_list<boost::string_ref> search_paths);\n\n boost::filesystem::path find_include_path(boost::string_ref file_name, std::initializer_list<boost::string_ref> search_paths);\n\n }\n\n}\n", "file_path": "src/resources/include_path.hpp", "rank": 55, "score": 55881.96144167202 }, { "content": "/*\n\n* TS Elements\n\n* Copyright 2015-2018 M. Newhouse\n\n* Released under the MIT license.\n\n*/\n\n\n\n\n\n#include \"include_path.hpp\"\n\n\n\n#include <boost/filesystem/convenience.hpp>\n\n\n\nnamespace ts\n\n{\n\n namespace resources\n\n {\n\n namespace bfs = boost::filesystem;\n\n\n\n bfs::path find_include_path(boost::string_ref file_name,\n\n std::initializer_list<boost::string_ref> search_paths)\n\n {\n", "file_path": "src/resources/include_path.cpp", "rank": 56, "score": 55876.6744837734 }, { "content": " _stream << \"\\n\";\n\n _stream << *it;\n\n }\n\n return _stream;\n\n }\n\n\n\n private:\n\n std::string str;\n\n TextAttributes attr;\n\n std::vector<std::string> lines;\n\n };\n\n\n\n} // end namespace Tbc\n\n\n\n#ifdef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE\n\n} // end outer namespace\n\n#endif\n\n\n\n#endif // TBC_TEXT_FORMAT_H_INCLUDED\n\n\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 57, "score": 55875.53000111851 }, { "content": "#define STITCH_TBC_TEXT_FORMAT_OPEN_NAMESPACE STITCH_CLARA_OPEN_NAMESPACE\n\n\n\n// ----------- #included from tbc_text_format.h -----------\n\n\n\n/*\n\n * Created by Phil on 18/4/2013.\n\n * Copyright 2013 Two Blue Cubes Ltd. All rights reserved.\n\n *\n\n * Distributed under the Boost Software License, Version 1.0. (See accompanying\n\n * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n */\n\n// Only use header guard if we are not using an outer namespace\n\n#if !defined(TBC_TEXT_FORMAT_H_INCLUDED) || defined(STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE)\n\n#ifndef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE\n\n#define TBC_TEXT_FORMAT_H_INCLUDED\n\n#endif\n\n\n\n#include <string>\n\n#include <vector>\n\n#include <sstream>\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 58, "score": 55873.01179513845 }, { "content": " bfs::path full_path;\n\n for (boost::string_ref path : search_paths)\n\n {\n\n full_path.assign(path.begin(), path.end());\n\n full_path.append(file_name.begin(), file_name.end());\n\n\n\n if (boost::filesystem::is_regular_file(full_path)) return full_path;\n\n }\n\n\n\n full_path.clear();\n\n return full_path;\n\n }\n\n\n\n boost::string_ref find_include_directory(boost::string_ref file_name,\n\n std::initializer_list<boost::string_ref> search_paths)\n\n {\n\n bfs::path full_path;\n\n for (boost::string_ref path : search_paths)\n\n {\n\n full_path.assign(path.begin(), path.end());\n\n full_path.append(file_name.begin(), file_name.end());\n\n\n\n if (boost::filesystem::is_regular_file(full_path)) return path;\n\n }\n\n\n\n return boost::string_ref();\n\n }\n\n }\n\n}", "file_path": "src/resources/include_path.cpp", "rank": 59, "score": 55872.448492608855 }, { "content": "// ----------- end of #include from tbc_text_format.h -----------\n\n// ........... back in /Users/philnash/Dev/OSS/Clara/srcs/clara.h\n\n\n\n#undef STITCH_TBC_TEXT_FORMAT_OPEN_NAMESPACE\n\n\n\n\n\n#include <map>\n\n#include <algorithm>\n\n#include <stdexcept>\n\n#include <memory>\n\n\n\n// Use optional outer namespace\n\n#ifdef STITCH_CLARA_OPEN_NAMESPACE\n\nSTITCH_CLARA_OPEN_NAMESPACE\n\n#endif\n\n\n\nnamespace Clara {\n\n\n\n struct UnpositionalTag {};\n\n\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 60, "score": 55871.36334788559 }, { "content": "\n\n struct Parser {\n\n Parser() : separators( \" \\t=:\" ) {}\n\n\n\n struct Token {\n\n enum Type { Positional, ShortOpt, LongOpt };\n\n Token( Type _type, std::string const& _data ) : type( _type ), data( _data ) {}\n\n Type type;\n\n std::string data;\n\n };\n\n\n\n void parseIntoTokens( int argc, char const * const * argv, std::vector<Parser::Token>& tokens ) const {\n\n const std::string doubleDash = \"--\";\n\n for( int i = 1; i < argc && argv[i] != doubleDash; ++i )\n\n parseIntoTokens( argv[i] , tokens);\n\n }\n\n void parseIntoTokens( std::string arg, std::vector<Parser::Token>& tokens ) const {\n\n while( !arg.empty() ) {\n\n Parser::Token token( Parser::Token::Positional, arg );\n\n arg = \"\";\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 61, "score": 55871.21285230026 }, { "content": "/*\n\n * Created by Phil on 22/10/2010.\n\n * Copyright 2010 Two Blue Cubes Ltd\n\n *\n\n * Distributed under the Boost Software License, Version 1.0. (See accompanying\n\n * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n */\n\n\n\n#ifndef TWOBLUECUBES_CATCH_HPP_INCLUDED\n\n#define TWOBLUECUBES_CATCH_HPP_INCLUDED\n\n\n\n#ifdef __clang__\n\n# pragma clang system_header\n\n#elif defined __GNUC__\n\n# pragma GCC system_header\n\n#endif\n\n\n\n#include \"internal/catch_suppress_warnings.h\"\n\n\n\n#if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)\n", "file_path": "dependencies/catch/include/catch.hpp", "rank": 62, "score": 55871.1577613205 }, { "content": " _remainder = _remainder.substr( _pos );\n\n }\n\n\n\n typedef std::vector<std::string>::const_iterator const_iterator;\n\n\n\n const_iterator begin() const { return lines.begin(); }\n\n const_iterator end() const { return lines.end(); }\n\n std::string const& last() const { return lines.back(); }\n\n std::size_t size() const { return lines.size(); }\n\n std::string const& operator[]( std::size_t _index ) const { return lines[_index]; }\n\n std::string toString() const {\n\n std::ostringstream oss;\n\n oss << *this;\n\n return oss.str();\n\n }\n\n\n\n inline friend std::ostream& operator << ( std::ostream& _stream, Text const& _text ) {\n\n for( Text::const_iterator it = _text.begin(), itEnd = _text.end();\n\n it != itEnd; ++it ) {\n\n if( it != _text.begin() )\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 63, "score": 55870.37347780317 }, { "content": " ConfigT parse( int argc, char const * const * argv ) const {\n\n ConfigT config;\n\n parseInto( argc, argv, config );\n\n return config;\n\n }\n\n\n\n std::vector<Parser::Token> parseInto( int argc, char const * const * argv, ConfigT& config ) const {\n\n std::string processName = argv[0];\n\n std::size_t lastSlash = processName.find_last_of( \"/\\\\\" );\n\n if( lastSlash != std::string::npos )\n\n processName = processName.substr( lastSlash+1 );\n\n m_boundProcessName.set( config, processName );\n\n std::vector<Parser::Token> tokens;\n\n Parser parser;\n\n parser.parseIntoTokens( argc, argv, tokens );\n\n return populate( tokens, config );\n\n }\n\n\n\n std::vector<Parser::Token> populate( std::vector<Parser::Token> const& tokens, ConfigT& config ) const {\n\n validate();\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 64, "score": 55870.346277313736 }, { "content": " }\n\n if( !errors.empty() ) {\n\n std::ostringstream oss;\n\n for( std::vector<std::string>::const_iterator it = errors.begin(), itEnd = errors.end();\n\n it != itEnd;\n\n ++it ) {\n\n if( it != errors.begin() )\n\n oss << \"\\n\";\n\n oss << *it;\n\n }\n\n throw std::runtime_error( oss.str() );\n\n }\n\n return unusedTokens;\n\n }\n\n std::vector<Parser::Token> populateFixedArgs( std::vector<Parser::Token> const& tokens, ConfigT& config ) const {\n\n std::vector<Parser::Token> unusedTokens;\n\n int position = 1;\n\n for( std::size_t i = 0; i < tokens.size(); ++i ) {\n\n Parser::Token const& token = tokens[i];\n\n typename std::map<int, Arg>::const_iterator it = m_positionalArgs.find( position );\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 65, "score": 55869.81297989231 }, { "content": " throw std::logic_error( \"option not bound\" );\n\n }\n\n };\n\n struct OptionArgProperties {\n\n std::vector<std::string> shortNames;\n\n std::string longName;\n\n\n\n bool hasShortName( std::string const& shortName ) const {\n\n return std::find( shortNames.begin(), shortNames.end(), shortName ) != shortNames.end();\n\n }\n\n bool hasLongName( std::string const& _longName ) const {\n\n return _longName == longName;\n\n }\n\n };\n\n struct PositionalArgProperties {\n\n PositionalArgProperties() : position( -1 ) {}\n\n int position; // -1 means non-positional (floating)\n\n\n\n bool isFixedPositional() const {\n\n return position != -1;\n\n }\n\n };\n\n\n\n template<typename ConfigT>\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 66, "score": 55869.76202114379 }, { "content": " std::vector<Parser::Token> unusedTokens = populateOptions( tokens, config );\n\n unusedTokens = populateFixedArgs( unusedTokens, config );\n\n unusedTokens = populateFloatingArgs( unusedTokens, config );\n\n return unusedTokens;\n\n }\n\n\n\n std::vector<Parser::Token> populateOptions( std::vector<Parser::Token> const& tokens, ConfigT& config ) const {\n\n std::vector<Parser::Token> unusedTokens;\n\n std::vector<std::string> errors;\n\n for( std::size_t i = 0; i < tokens.size(); ++i ) {\n\n Parser::Token const& token = tokens[i];\n\n typename std::vector<Arg>::const_iterator it = m_options.begin(), itEnd = m_options.end();\n\n for(; it != itEnd; ++it ) {\n\n Arg const& arg = *it;\n\n\n\n try {\n\n if( ( token.type == Parser::Token::ShortOpt && arg.hasShortName( token.data ) ) ||\n\n ( token.type == Parser::Token::LongOpt && arg.hasLongName( token.data ) ) ) {\n\n if( arg.takesArg() ) {\n\n if( i == tokens.size()-1 || tokens[i+1].type != Parser::Token::Positional )\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 67, "score": 55869.20645410334 }, { "content": "# define CATCH_IMPL\n\n#endif\n\n\n\n#ifdef CATCH_IMPL\n\n# ifndef CLARA_CONFIG_MAIN\n\n# define CLARA_CONFIG_MAIN_NOT_DEFINED\n\n# define CLARA_CONFIG_MAIN\n\n# endif\n\n#endif\n\n\n\n#include \"internal/catch_notimplemented_exception.h\"\n\n#include \"internal/catch_context.h\"\n\n#include \"internal/catch_test_registry.hpp\"\n\n#include \"internal/catch_capture.hpp\"\n\n#include \"internal/catch_section.h\"\n\n#include \"internal/catch_generators.hpp\"\n\n#include \"internal/catch_interfaces_exception.h\"\n\n#include \"internal/catch_approx.hpp\"\n\n#include \"internal/catch_matchers.hpp\"\n\n#include \"internal/catch_compiler_capabilities.h\"\n", "file_path": "dependencies/catch/include/catch.hpp", "rank": 68, "score": 55867.81637342835 }, { "content": "#include \"internal/catch_interfaces_tag_alias_registry.h\"\n\n\n\n// These files are included here so the single_include script doesn't put them\n\n// in the conditionally compiled sections\n\n#include \"internal/catch_test_case_info.h\"\n\n#include \"internal/catch_interfaces_runner.h\"\n\n\n\n#ifdef __OBJC__\n\n#include \"internal/catch_objc.hpp\"\n\n#endif\n\n\n\n#ifdef CATCH_IMPL\n\n#include \"internal/catch_impl.hpp\"\n\n#endif\n\n\n\n#ifdef CATCH_CONFIG_MAIN\n\n#include \"internal/catch_default_main.hpp\"\n\n#endif\n\n\n\n\n", "file_path": "dependencies/catch/include/catch.hpp", "rank": 69, "score": 55867.757168767384 }, { "content": " virtual void set( C& p, std::string const& stringValue ) const {\n\n convertInto( stringValue, p.*member );\n\n }\n\n virtual void setFlag( C& p ) const {\n\n convertInto( true, p.*member );\n\n }\n\n virtual bool takesArg() const { return !IsBool<M>::value; }\n\n virtual IArgFunction<C>* clone() const { return new BoundDataMember( *this ); }\n\n M C::* member;\n\n };\n\n template<typename C, typename M>\n\n struct BoundUnaryMethod : IArgFunction<C>{\n\n BoundUnaryMethod( void (C::*_member)( M ) ) : member( _member ) {}\n\n virtual void set( C& p, std::string const& stringValue ) const {\n\n typename RemoveConstRef<M>::type value;\n\n convertInto( stringValue, value );\n\n (p.*member)( value );\n\n }\n\n virtual void setFlag( C& p ) const {\n\n typename RemoveConstRef<M>::type value;\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 70, "score": 55866.72855319066 }, { "content": "\n\n // Bind a free function taking a single argument - the object to operate on (requires a placeholder string)\n\n template<typename C, typename T>\n\n void bind( void (* binaryFunction)( C&, T ), std::string const& placeholder ) {\n\n m_arg->boundField = new Detail::BoundBinaryFunction<C, T>( binaryFunction );\n\n m_arg->placeholder = placeholder;\n\n }\n\n\n\n ArgBuilder& describe( std::string const& description ) {\n\n m_arg->description = description;\n\n return *this;\n\n }\n\n ArgBuilder& detail( std::string const& detail ) {\n\n m_arg->detail = detail;\n\n return *this;\n\n }\n\n\n\n protected:\n\n Arg* m_arg;\n\n };\n\n\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 71, "score": 55866.609553619586 }, { "content": " }\n\n }\n\n std::string separators;\n\n };\n\n\n\n template<typename ConfigT>\n\n struct CommonArgProperties {\n\n CommonArgProperties() {}\n\n CommonArgProperties( Detail::BoundArgFunction<ConfigT> const& _boundField ) : boundField( _boundField ) {}\n\n\n\n Detail::BoundArgFunction<ConfigT> boundField;\n\n std::string description;\n\n std::string detail;\n\n std::string placeholder; // Only value if boundField takes an arg\n\n\n\n bool takesArg() const {\n\n return !placeholder.empty();\n\n }\n\n void validate() const {\n\n if( !boundField.isSet() )\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 72, "score": 55866.609553619586 }, { "content": " pos = remainder.find_last_of( wrappableChars, width );\n\n if( pos != std::string::npos && pos > 0 ) {\n\n spliceLine( indent, remainder, pos );\n\n if( remainder[0] == ' ' )\n\n remainder = remainder.substr( 1 );\n\n }\n\n else {\n\n spliceLine( indent, remainder, width-1 );\n\n lines.back() += \"-\";\n\n }\n\n if( lines.size() == 1 )\n\n indent = _attr.indent;\n\n if( tabPos != std::string::npos )\n\n indent += tabPos;\n\n }\n\n }\n\n }\n\n\n\n void spliceLine( std::size_t _indent, std::string& _remainder, std::size_t _pos ) {\n\n lines.push_back( std::string( _indent, ' ' ) + _remainder.substr( 0, _pos ) );\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 73, "score": 55866.56399660906 }, { "content": " argSynopsis( oss );\n\n return oss.str();\n\n }\n\n\n\n void usage( std::ostream& os, std::string const& procName ) const {\n\n validate();\n\n os << \"usage:\\n \" << procName << \" \";\n\n argSynopsis( os );\n\n if( !m_options.empty() ) {\n\n os << \" [options]\\n\\nwhere options are: \\n\";\n\n optUsage( os, 2 );\n\n }\n\n os << \"\\n\";\n\n }\n\n std::string usage( std::string const& procName ) const {\n\n std::ostringstream oss;\n\n usage( oss, procName );\n\n return oss.str();\n\n }\n\n\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 74, "score": 55866.407543056834 }, { "content": " .setWidth( width - maxWidth - 3 ) );\n\n\n\n for( std::size_t i = 0; i < (std::max)( usage.size(), desc.size() ); ++i ) {\n\n std::string usageCol = i < usage.size() ? usage[i] : \"\";\n\n os << usageCol;\n\n\n\n if( i < desc.size() && !desc[i].empty() )\n\n os << std::string( indent + 2 + maxWidth - usageCol.size(), ' ' )\n\n << desc[i];\n\n os << \"\\n\";\n\n }\n\n }\n\n }\n\n std::string optUsage() const {\n\n std::ostringstream oss;\n\n optUsage( oss );\n\n return oss.str();\n\n }\n\n\n\n void argSynopsis( std::ostream& os ) const {\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 75, "score": 55866.18622971891 }, { "content": " template<typename T> struct RemoveConstRef{ typedef T type; };\n\n template<typename T> struct RemoveConstRef<T&>{ typedef T type; };\n\n template<typename T> struct RemoveConstRef<T const&>{ typedef T type; };\n\n template<typename T> struct RemoveConstRef<T const>{ typedef T type; };\n\n\n\n template<typename T> struct IsBool { static const bool value = false; };\n\n template<> struct IsBool<bool> { static const bool value = true; };\n\n\n\n template<typename T>\n\n void convertInto( std::string const& _source, T& _dest ) {\n\n std::stringstream ss;\n\n ss << _source;\n\n ss >> _dest;\n\n if( ss.fail() )\n\n throw std::runtime_error( \"Unable to convert \" + _source + \" to destination type\" );\n\n }\n\n inline void convertInto( std::string const& _source, std::string& _dest ) {\n\n _dest = _source;\n\n }\n\n inline void convertInto( std::string const& _source, bool& _dest ) {\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 76, "score": 55865.89610102517 }, { "content": " convertInto( true, value );\n\n (p.*member)( value );\n\n }\n\n virtual bool takesArg() const { return !IsBool<M>::value; }\n\n virtual IArgFunction<C>* clone() const { return new BoundUnaryMethod( *this ); }\n\n void (C::*member)( M );\n\n };\n\n template<typename C>\n\n struct BoundNullaryMethod : IArgFunction<C>{\n\n BoundNullaryMethod( void (C::*_member)() ) : member( _member ) {}\n\n virtual void set( C& p, std::string const& stringValue ) const {\n\n bool value;\n\n convertInto( stringValue, value );\n\n if( value )\n\n (p.*member)();\n\n }\n\n virtual void setFlag( C& p ) const {\n\n (p.*member)();\n\n }\n\n virtual bool takesArg() const { return false; }\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 77, "score": 55865.858455544156 }, { "content": " virtual IArgFunction<C>* clone() const { return new BoundNullaryMethod( *this ); }\n\n void (C::*member)();\n\n };\n\n\n\n template<typename C>\n\n struct BoundUnaryFunction : IArgFunction<C>{\n\n BoundUnaryFunction( void (*_function)( C& ) ) : function( _function ) {}\n\n virtual void set( C& obj, std::string const& stringValue ) const {\n\n bool value;\n\n convertInto( stringValue, value );\n\n if( value )\n\n function( obj );\n\n }\n\n virtual void setFlag( C& p ) const {\n\n function( p );\n\n }\n\n virtual bool takesArg() const { return false; }\n\n virtual IArgFunction<C>* clone() const { return new BoundUnaryFunction( *this ); }\n\n void (*function)( C& );\n\n };\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 78, "score": 55865.83472499425 }, { "content": " if( it != m_positionalArgs.end() )\n\n it->second.boundField.set( config, token.data );\n\n else\n\n unusedTokens.push_back( token );\n\n if( token.type == Parser::Token::Positional )\n\n position++;\n\n }\n\n return unusedTokens;\n\n }\n\n std::vector<Parser::Token> populateFloatingArgs( std::vector<Parser::Token> const& tokens, ConfigT& config ) const {\n\n if( !m_floatingArg.get() )\n\n return tokens;\n\n std::vector<Parser::Token> unusedTokens;\n\n for( std::size_t i = 0; i < tokens.size(); ++i ) {\n\n Parser::Token const& token = tokens[i];\n\n if( token.type == Parser::Token::Positional )\n\n m_floatingArg->boundField.set( config, token.data );\n\n else\n\n unusedTokens.push_back( token );\n\n }\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 79, "score": 55865.819319091366 }, { "content": " extern UnpositionalTag _;\n\n\n\n#ifdef CLARA_CONFIG_MAIN\n\n UnpositionalTag _;\n\n#endif\n\n\n\n namespace Detail {\n\n\n\n#ifdef CLARA_CONSOLE_WIDTH\n\n const unsigned int consoleWidth = CLARA_CONFIG_CONSOLE_WIDTH;\n\n#else\n\n const unsigned int consoleWidth = 80;\n\n#endif\n\n\n\n using namespace Tbc;\n\n\n\n inline bool startsWith( std::string const& str, std::string const& prefix ) {\n\n return str.size() >= prefix.size() && str.substr( 0, prefix.size() ) == prefix;\n\n }\n\n\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 80, "score": 55865.615822273714 }, { "content": "\n\n template<typename C, typename T>\n\n struct BoundBinaryFunction : IArgFunction<C>{\n\n BoundBinaryFunction( void (*_function)( C&, T ) ) : function( _function ) {}\n\n virtual void set( C& obj, std::string const& stringValue ) const {\n\n typename RemoveConstRef<T>::type value;\n\n convertInto( stringValue, value );\n\n function( obj, value );\n\n }\n\n virtual void setFlag( C& obj ) const {\n\n typename RemoveConstRef<T>::type value;\n\n convertInto( true, value );\n\n function( obj, value );\n\n }\n\n virtual bool takesArg() const { return !IsBool<T>::value; }\n\n virtual IArgFunction<C>* clone() const { return new BoundBinaryFunction( *this ); }\n\n void (*function)( C&, T );\n\n };\n\n\n\n } // namespace Detail\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 81, "score": 55865.5647634745 }, { "content": " return unusedTokens;\n\n }\n\n\n\n void validate() const\n\n {\n\n if( m_options.empty() && m_positionalArgs.empty() && !m_floatingArg.get() )\n\n throw std::logic_error( \"No options or arguments specified\" );\n\n\n\n for( typename std::vector<Arg>::const_iterator it = m_options.begin(),\n\n itEnd = m_options.end();\n\n it != itEnd; ++it )\n\n it->validate();\n\n }\n\n\n\n private:\n\n Detail::BoundArgFunction<ConfigT> m_boundProcessName;\n\n std::vector<Arg> m_options;\n\n std::map<int, Arg> m_positionalArgs;\n\n ArgAutoPtr m_floatingArg;\n\n int m_highestSpecifiedArgPosition;\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 82, "score": 55865.31450083142 }, { "content": " bool m_throwOnUnrecognisedTokens;\n\n };\n\n\n\n} // end namespace Clara\n\n\n\n\n\nSTITCH_CLARA_CLOSE_NAMESPACE\n\n#undef STITCH_CLARA_OPEN_NAMESPACE\n\n#undef STITCH_CLARA_CLOSE_NAMESPACE\n\n\n\n\n\n#endif // TWOBLUECUBES_CLARA_H_INCLUDED\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 83, "score": 55865.12197911819 }, { "content": "/*\n\n * Created by Phil on 25/05/2013.\n\n * Copyright 2013 Two Blue Cubes Ltd. All rights reserved.\n\n *\n\n * Distributed under the Boost Software License, Version 1.0. (See accompanying\n\n * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n */\n\n\n\n// Only use header guard if we are not using an outer namespace\n\n#if !defined(TWOBLUECUBES_CLARA_H_INCLUDED) || defined(STITCH_CLARA_OPEN_NAMESPACE)\n\n\n\n#ifndef STITCH_CLARA_OPEN_NAMESPACE\n\n#define TWOBLUECUBES_CLARA_H_INCLUDED\n\n#define STITCH_CLARA_OPEN_NAMESPACE\n\n#define STITCH_CLARA_CLOSE_NAMESPACE\n\n#else\n\n#define STITCH_CLARA_CLOSE_NAMESPACE }\n\n#endif\n\n\n\n\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 84, "score": 55865.0226476791 }, { "content": " if( token.data[0] == '-' ) {\n\n if( token.data.size() > 1 && token.data[1] == '-' ) {\n\n token = Parser::Token( Parser::Token::LongOpt, token.data.substr( 2 ) );\n\n }\n\n else {\n\n token = Parser::Token( Parser::Token::ShortOpt, token.data.substr( 1 ) );\n\n if( token.data.size() > 1 && separators.find( token.data[1] ) == std::string::npos ) {\n\n arg = \"-\" + token.data.substr( 1 );\n\n token.data = token.data.substr( 0, 1 );\n\n }\n\n }\n\n }\n\n if( token.type != Parser::Token::Positional ) {\n\n std::size_t pos = token.data.find_first_of( separators );\n\n if( pos != std::string::npos ) {\n\n arg = token.data.substr( pos+1 );\n\n token.data = token.data.substr( 0, pos );\n\n }\n\n }\n\n tokens.push_back( token );\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 85, "score": 55864.8081709475 }, { "content": " m_arg->placeholder = placeholder;\n\n }\n\n\n\n // Bind a method taking a single, boolean argument (no placeholder string required)\n\n template<typename C>\n\n void bind( void (C::* unaryMethod)( bool ) ) {\n\n m_arg->boundField = new Detail::BoundUnaryMethod<C,bool>( unaryMethod );\n\n }\n\n\n\n // Bind a method that takes no arguments (will be called if opt is present)\n\n template<typename C>\n\n void bind( void (C::* nullaryMethod)() ) {\n\n m_arg->boundField = new Detail::BoundNullaryMethod<C>( nullaryMethod );\n\n }\n\n\n\n // Bind a free function taking a single argument - the object to operate on (no placeholder string required)\n\n template<typename C>\n\n void bind( void (* unaryFunction)( C& ) ) {\n\n m_arg->boundField = new Detail::BoundUnaryFunction<C>( unaryFunction );\n\n }\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 86, "score": 55864.478315762484 }, { "content": "# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS\n\n IArgFunction() = default;\n\n IArgFunction( IArgFunction const& ) = default;\n\n# endif\n\n virtual void set( ConfigT& config, std::string const& value ) const = 0;\n\n virtual void setFlag( ConfigT& config ) const = 0;\n\n virtual bool takesArg() const = 0;\n\n virtual IArgFunction* clone() const = 0;\n\n };\n\n\n\n template<typename ConfigT>\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 87, "score": 55864.334765368876 }, { "content": "#define GENERATE( expr) INTERNAL_CATCH_GENERATE( expr )\n\n\n\n#endif\n\n\n\n#define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )\n\n\n\n// \"BDD-style\" convenience wrappers\n\n#ifdef CATCH_CONFIG_VARIADIC_MACROS\n\n#define SCENARIO( ... ) TEST_CASE( \"Scenario: \" __VA_ARGS__ )\n\n#define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, \"Scenario: \" __VA_ARGS__ )\n\n#else\n\n#define SCENARIO( name, tags ) TEST_CASE( \"Scenario: \" name, tags )\n\n#define SCENARIO_METHOD( className, name, tags ) INTERNAL_CATCH_TEST_CASE_METHOD( className, \"Scenario: \" name, tags )\n\n#endif\n\n#define GIVEN( desc ) SECTION( \" Given: \" desc, \"\" )\n\n#define WHEN( desc ) SECTION( \" When: \" desc, \"\" )\n\n#define AND_WHEN( desc ) SECTION( \"And when: \" desc, \"\" )\n\n#define THEN( desc ) SECTION( \" Then: \" desc, \"\" )\n\n#define AND_THEN( desc ) SECTION( \" And: \" desc, \"\" )\n\n\n\nusing Catch::Detail::Approx;\n\n\n\n#include \"internal/catch_reenable_warnings.h\"\n\n\n\n#endif // TWOBLUECUBES_CATCH_HPP_INCLUDED\n", "file_path": "dependencies/catch/include/catch.hpp", "rank": 88, "score": 55864.217272092836 }, { "content": " width = pos;\n\n }\n\n pos = remainder.find_last_of( _attr.tabChar, width );\n\n if( pos != std::string::npos ) {\n\n tabPos = pos;\n\n if( remainder[width] == '\\n' )\n\n width--;\n\n remainder = remainder.substr( 0, tabPos ) + remainder.substr( tabPos+1 );\n\n }\n\n\n\n if( width == remainder.size() ) {\n\n spliceLine( indent, remainder, width );\n\n }\n\n else if( remainder[width] == '\\n' ) {\n\n spliceLine( indent, remainder, width );\n\n if( width <= 1 || remainder.size() != 1 )\n\n remainder = remainder.substr( 1 );\n\n indent = _attr.indent;\n\n }\n\n else {\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 89, "score": 55863.95407635165 }, { "content": "\n\n// Use optional outer namespace\n\n#ifdef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE\n\nnamespace STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE {\n\n#endif\n\n\n\nnamespace Tbc {\n\n\n\n#ifdef TBC_TEXT_FORMAT_CONSOLE_WIDTH\n\n const unsigned int consoleWidth = TBC_TEXT_FORMAT_CONSOLE_WIDTH;\n\n#else\n\n const unsigned int consoleWidth = 80;\n\n#endif\n\n\n\n struct TextAttributes {\n\n TextAttributes()\n\n : initialIndent( std::string::npos ),\n\n indent( 0 ),\n\n width( consoleWidth-1 ),\n\n tabChar( '\\t' )\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 90, "score": 55863.922923300284 }, { "content": " errors.push_back( \"Expected argument to option: \" + token.data );\n\n else\n\n arg.boundField.set( config, tokens[++i].data );\n\n }\n\n else {\n\n arg.boundField.setFlag( config );\n\n }\n\n break;\n\n }\n\n }\n\n catch( std::exception& ex ) {\n\n errors.push_back( std::string( ex.what() ) + \"\\n- while parsing: (\" + arg.commands() + \")\" );\n\n }\n\n }\n\n if( it == itEnd ) {\n\n if( token.type == Parser::Token::Positional || !m_throwOnUnrecognisedTokens )\n\n unusedTokens.push_back( token );\n\n else if( errors.empty() && m_throwOnUnrecognisedTokens )\n\n errors.push_back( \"unrecognised option: \" + token.data );\n\n }\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 91, "score": 55863.77462281197 }, { "content": " for( int i = 1; i <= m_highestSpecifiedArgPosition; ++i ) {\n\n if( i > 1 )\n\n os << \" \";\n\n typename std::map<int, Arg>::const_iterator it = m_positionalArgs.find( i );\n\n if( it != m_positionalArgs.end() )\n\n os << \"<\" << it->second.placeholder << \">\";\n\n else if( m_floatingArg.get() )\n\n os << \"<\" << m_floatingArg->placeholder << \">\";\n\n else\n\n throw std::logic_error( \"non consecutive positional arguments with no floating args\" );\n\n }\n\n // !TBD No indication of mandatory args\n\n if( m_floatingArg.get() ) {\n\n if( m_highestSpecifiedArgPosition > 1 )\n\n os << \" \";\n\n os << \"[<\" << m_floatingArg->placeholder << \"> ...]\";\n\n }\n\n }\n\n std::string argSynopsis() const {\n\n std::ostringstream oss;\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 92, "score": 55863.77462281197 }, { "content": "\n\n bool isSet() const {\n\n return functionObj != NULL;\n\n }\n\n private:\n\n IArgFunction<ConfigT>* functionObj;\n\n };\n\n\n\n\n\n template<typename C>\n\n struct NullBinder : IArgFunction<C>{\n\n virtual void set( C&, std::string const& ) const {}\n\n virtual void setFlag( C& ) const {}\n\n virtual bool takesArg() const { return true; }\n\n virtual IArgFunction<C>* clone() const { return new NullBinder( *this ); }\n\n };\n\n\n\n template<typename C, typename M>\n\n struct BoundDataMember : IArgFunction<C>{\n\n BoundDataMember( M C::* _member ) : member( _member ) {}\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 93, "score": 55863.691195096726 }, { "content": " m_options ( other.m_options ),\n\n m_positionalArgs( other.m_positionalArgs ),\n\n m_highestSpecifiedArgPosition( other.m_highestSpecifiedArgPosition ),\n\n m_throwOnUnrecognisedTokens( other.m_throwOnUnrecognisedTokens )\n\n {\n\n if( other.m_floatingArg.get() )\n\n m_floatingArg.reset( new Arg( *other.m_floatingArg ) );\n\n }\n\n\n\n CommandLine& setThrowOnUnrecognisedTokens( bool shouldThrow = true ) {\n\n m_throwOnUnrecognisedTokens = shouldThrow;\n\n return *this;\n\n }\n\n\n\n\n\n OptBuilder operator[]( std::string const& optName ) {\n\n m_options.push_back( Arg() );\n\n addOptName( m_options.back(), optName );\n\n OptBuilder builder( &m_options.back() );\n\n return builder;\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 94, "score": 55863.560500006104 }, { "content": " {}\n\n\n\n TextAttributes& setInitialIndent( std::size_t _value ) { initialIndent = _value; return *this; }\n\n TextAttributes& setIndent( std::size_t _value ) { indent = _value; return *this; }\n\n TextAttributes& setWidth( std::size_t _value ) { width = _value; return *this; }\n\n TextAttributes& setTabChar( char _value ) { tabChar = _value; return *this; }\n\n\n\n std::size_t initialIndent; // indent of first line, or npos\n\n std::size_t indent; // indent of subsequent lines, or all if initialIndent is npos\n\n std::size_t width; // maximum width of text, including indent. Longer text will wrap\n\n char tabChar; // If this char is seen the indent is changed to current pos\n\n };\n\n\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 95, "score": 55863.3038058 }, { "content": " std::string sourceLC = _source;\n\n std::transform( sourceLC.begin(), sourceLC.end(), sourceLC.begin(), ::tolower );\n\n if( sourceLC == \"y\" || sourceLC == \"1\" || sourceLC == \"true\" || sourceLC == \"yes\" || sourceLC == \"on\" )\n\n _dest = true;\n\n else if( sourceLC == \"n\" || sourceLC == \"0\" || sourceLC == \"false\" || sourceLC == \"no\" || sourceLC == \"off\" )\n\n _dest = false;\n\n else\n\n throw std::runtime_error( \"Expected a boolean value but did not recognise:\\n '\" + _source + \"'\" );\n\n }\n\n inline void convertInto( bool _source, bool& _dest ) {\n\n _dest = _source;\n\n }\n\n template<typename T>\n\n inline void convertInto( bool, T& ) {\n\n throw std::runtime_error( \"Invalid conversion\" );\n\n }\n\n\n\n template<typename ConfigT>\n\n struct IArgFunction {\n\n virtual ~IArgFunction() {}\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 96, "score": 55863.22132760569 }, { "content": "#else\n\n typedef std::auto_ptr<Arg> ArgAutoPtr;\n\n#endif\n\n\n\n friend void addOptName( Arg& arg, std::string const& optName )\n\n {\n\n if( optName.empty() )\n\n return;\n\n if( Detail::startsWith( optName, \"--\" ) ) {\n\n if( !arg.longName.empty() )\n\n throw std::logic_error( \"Only one long opt may be specified. '\"\n\n + arg.longName\n\n + \"' already specified, now attempting to add '\"\n\n + optName + \"'\" );\n\n arg.longName = optName.substr( 2 );\n\n }\n\n else if( Detail::startsWith( optName, \"-\" ) )\n\n arg.shortNames.push_back( optName.substr( 1 ) );\n\n else\n\n throw std::logic_error( \"option must begin with - or --. Option was: '\" + optName + \"'\" );\n\n }\n\n friend void setPositionalArg( Arg& arg, int position )\n\n {\n\n arg.position = position;\n\n }\n\n\n\n\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 97, "score": 55863.12302956673 }, { "content": " template<typename C, typename M>\n\n void bindProcessName( M C::* field ) {\n\n m_boundProcessName = new Detail::BoundDataMember<C,M>( field );\n\n }\n\n template<typename C, typename M>\n\n void bindProcessName( void (C::*_unaryMethod)( M ) ) {\n\n m_boundProcessName = new Detail::BoundUnaryMethod<C,M>( _unaryMethod );\n\n }\n\n\n\n void optUsage( std::ostream& os, std::size_t indent = 0, std::size_t width = Detail::consoleWidth ) const {\n\n typename std::vector<Arg>::const_iterator itBegin = m_options.begin(), itEnd = m_options.end(), it;\n\n std::size_t maxWidth = 0;\n\n for( it = itBegin; it != itEnd; ++it )\n\n maxWidth = (std::max)( maxWidth, it->commands().size() );\n\n\n\n for( it = itBegin; it != itEnd; ++it ) {\n\n Detail::Text usage( it->commands(), Detail::TextAttributes()\n\n .setWidth( maxWidth+indent )\n\n .setIndent( indent ) );\n\n Detail::Text desc( it->description, Detail::TextAttributes()\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 98, "score": 55862.71791526197 }, { "content": " if( first )\n\n first = false;\n\n else\n\n oss << \", \";\n\n oss << \"-\" << *it;\n\n }\n\n if( !longName.empty() ) {\n\n if( !first )\n\n oss << \", \";\n\n oss << \"--\" << longName;\n\n }\n\n if( !placeholder.empty() )\n\n oss << \" <\" << placeholder << \">\";\n\n return oss.str();\n\n }\n\n };\n\n\n\n // NOTE: std::auto_ptr is deprecated in c++11/c++0x\n\n#if defined(__cplusplus) && __cplusplus > 199711L\n\n typedef std::unique_ptr<Arg> ArgAutoPtr;\n", "file_path": "dependencies/catch/include/external/clara.h", "rank": 99, "score": 55860.209469045345 } ]
C++
Samples/cuSolverDn_LinearSolver/cuSolverDn_LinearSolver.cpp
rob-opsi/cuda-samples
32943424ed7023f9168266d9fb7b76e8566fd054
#include <assert.h> #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <cuda_runtime.h> #include "cublas_v2.h" #include "cusolverDn.h" #include "helper_cuda.h" #include "helper_cusolver.h" template <typename T_ELEM> int loadMMSparseMatrix(char *filename, char elem_type, bool csrFormat, int *m, int *n, int *nnz, T_ELEM **aVal, int **aRowInd, int **aColInd, int extendSymMatrix); void UsageDN(void) { printf("<options>\n"); printf("-h : display this help\n"); printf("-R=<name> : choose a linear solver\n"); printf(" chol (cholesky factorization), this is default\n"); printf(" qr (QR factorization)\n"); printf(" lu (LU factorization)\n"); printf("-lda=<int> : leading dimension of A , m by default\n"); printf("-file=<filename>: filename containing a matrix in MM format\n"); printf("-device=<device_id> : <device_id> if want to run on specific GPU\n"); exit(0); } int linearSolverCHOL(cusolverDnHandle_t handle, int n, const double *Acopy, int lda, const double *b, double *x) { int bufferSize = 0; int *info = NULL; double *buffer = NULL; double *A = NULL; int h_info = 0; double start, stop; double time_solve; cublasFillMode_t uplo = CUBLAS_FILL_MODE_LOWER; checkCudaErrors(cusolverDnDpotrf_bufferSize(handle, uplo, n, (double *)Acopy, lda, &bufferSize)); checkCudaErrors(cudaMalloc(&info, sizeof(int))); checkCudaErrors(cudaMalloc(&buffer, sizeof(double) * bufferSize)); checkCudaErrors(cudaMalloc(&A, sizeof(double) * lda * n)); checkCudaErrors( cudaMemcpy(A, Acopy, sizeof(double) * lda * n, cudaMemcpyDeviceToDevice)); checkCudaErrors(cudaMemset(info, 0, sizeof(int))); start = second(); start = second(); checkCudaErrors( cusolverDnDpotrf(handle, uplo, n, A, lda, buffer, bufferSize, info)); checkCudaErrors( cudaMemcpy(&h_info, info, sizeof(int), cudaMemcpyDeviceToHost)); if (0 != h_info) { fprintf(stderr, "Error: Cholesky factorization failed\n"); } checkCudaErrors( cudaMemcpy(x, b, sizeof(double) * n, cudaMemcpyDeviceToDevice)); checkCudaErrors(cusolverDnDpotrs(handle, uplo, n, 1, A, lda, x, n, info)); checkCudaErrors(cudaDeviceSynchronize()); stop = second(); time_solve = stop - start; fprintf(stdout, "timing: cholesky = %10.6f sec\n", time_solve); if (info) { checkCudaErrors(cudaFree(info)); } if (buffer) { checkCudaErrors(cudaFree(buffer)); } if (A) { checkCudaErrors(cudaFree(A)); } return 0; } int linearSolverLU(cusolverDnHandle_t handle, int n, const double *Acopy, int lda, const double *b, double *x) { int bufferSize = 0; int *info = NULL; double *buffer = NULL; double *A = NULL; int *ipiv = NULL; int h_info = 0; double start, stop; double time_solve; checkCudaErrors(cusolverDnDgetrf_bufferSize(handle, n, n, (double *)Acopy, lda, &bufferSize)); checkCudaErrors(cudaMalloc(&info, sizeof(int))); checkCudaErrors(cudaMalloc(&buffer, sizeof(double) * bufferSize)); checkCudaErrors(cudaMalloc(&A, sizeof(double) * lda * n)); checkCudaErrors(cudaMalloc(&ipiv, sizeof(int) * n)); checkCudaErrors( cudaMemcpy(A, Acopy, sizeof(double) * lda * n, cudaMemcpyDeviceToDevice)); checkCudaErrors(cudaMemset(info, 0, sizeof(int))); start = second(); start = second(); checkCudaErrors(cusolverDnDgetrf(handle, n, n, A, lda, buffer, ipiv, info)); checkCudaErrors( cudaMemcpy(&h_info, info, sizeof(int), cudaMemcpyDeviceToHost)); if (0 != h_info) { fprintf(stderr, "Error: LU factorization failed\n"); } checkCudaErrors( cudaMemcpy(x, b, sizeof(double) * n, cudaMemcpyDeviceToDevice)); checkCudaErrors( cusolverDnDgetrs(handle, CUBLAS_OP_N, n, 1, A, lda, ipiv, x, n, info)); checkCudaErrors(cudaDeviceSynchronize()); stop = second(); time_solve = stop - start; fprintf(stdout, "timing: LU = %10.6f sec\n", time_solve); if (info) { checkCudaErrors(cudaFree(info)); } if (buffer) { checkCudaErrors(cudaFree(buffer)); } if (A) { checkCudaErrors(cudaFree(A)); } if (ipiv) { checkCudaErrors(cudaFree(ipiv)); } return 0; } int linearSolverQR(cusolverDnHandle_t handle, int n, const double *Acopy, int lda, const double *b, double *x) { cublasHandle_t cublasHandle = NULL; int bufferSize = 0; int bufferSize_geqrf = 0; int bufferSize_ormqr = 0; int *info = NULL; double *buffer = NULL; double *A = NULL; double *tau = NULL; int h_info = 0; double start, stop; double time_solve; const double one = 1.0; checkCudaErrors(cublasCreate(&cublasHandle)); checkCudaErrors(cusolverDnDgeqrf_bufferSize(handle, n, n, (double *)Acopy, lda, &bufferSize_geqrf)); checkCudaErrors(cusolverDnDormqr_bufferSize(handle, CUBLAS_SIDE_LEFT, CUBLAS_OP_T, n, 1, n, A, lda, NULL, x, n, &bufferSize_ormqr)); printf("buffer_geqrf = %d, buffer_ormqr = %d \n", bufferSize_geqrf, bufferSize_ormqr); bufferSize = (bufferSize_geqrf > bufferSize_ormqr) ? bufferSize_geqrf : bufferSize_ormqr; checkCudaErrors(cudaMalloc(&info, sizeof(int))); checkCudaErrors(cudaMalloc(&buffer, sizeof(double) * bufferSize)); checkCudaErrors(cudaMalloc(&A, sizeof(double) * lda * n)); checkCudaErrors(cudaMalloc((void **)&tau, sizeof(double) * n)); checkCudaErrors( cudaMemcpy(A, Acopy, sizeof(double) * lda * n, cudaMemcpyDeviceToDevice)); checkCudaErrors(cudaMemset(info, 0, sizeof(int))); start = second(); start = second(); checkCudaErrors( cusolverDnDgeqrf(handle, n, n, A, lda, tau, buffer, bufferSize, info)); checkCudaErrors( cudaMemcpy(&h_info, info, sizeof(int), cudaMemcpyDeviceToHost)); if (0 != h_info) { fprintf(stderr, "Error: LU factorization failed\n"); } checkCudaErrors( cudaMemcpy(x, b, sizeof(double) * n, cudaMemcpyDeviceToDevice)); checkCudaErrors(cusolverDnDormqr(handle, CUBLAS_SIDE_LEFT, CUBLAS_OP_T, n, 1, n, A, lda, tau, x, n, buffer, bufferSize, info)); checkCudaErrors(cublasDtrsm(cublasHandle, CUBLAS_SIDE_LEFT, CUBLAS_FILL_MODE_UPPER, CUBLAS_OP_N, CUBLAS_DIAG_NON_UNIT, n, 1, &one, A, lda, x, n)); checkCudaErrors(cudaDeviceSynchronize()); stop = second(); time_solve = stop - start; fprintf(stdout, "timing: QR = %10.6f sec\n", time_solve); if (cublasHandle) { checkCudaErrors(cublasDestroy(cublasHandle)); } if (info) { checkCudaErrors(cudaFree(info)); } if (buffer) { checkCudaErrors(cudaFree(buffer)); } if (A) { checkCudaErrors(cudaFree(A)); } if (tau) { checkCudaErrors(cudaFree(tau)); } return 0; } void parseCommandLineArguments(int argc, char *argv[], struct testOpts &opts) { memset(&opts, 0, sizeof(opts)); if (checkCmdLineFlag(argc, (const char **)argv, "-h")) { UsageDN(); } if (checkCmdLineFlag(argc, (const char **)argv, "R")) { char *solverType = NULL; getCmdLineArgumentString(argc, (const char **)argv, "R", &solverType); if (solverType) { if ((STRCASECMP(solverType, "chol") != 0) && (STRCASECMP(solverType, "lu") != 0) && (STRCASECMP(solverType, "qr") != 0)) { printf("\nIncorrect argument passed to -R option\n"); UsageDN(); } else { opts.testFunc = solverType; } } } if (checkCmdLineFlag(argc, (const char **)argv, "file")) { char *fileName = 0; getCmdLineArgumentString(argc, (const char **)argv, "file", &fileName); if (fileName) { opts.sparse_mat_filename = fileName; } else { printf("\nIncorrect filename passed to -file \n "); UsageDN(); } } if (checkCmdLineFlag(argc, (const char **)argv, "lda")) { opts.lda = getCmdLineArgumentInt(argc, (const char **)argv, "lda"); } } int main(int argc, char *argv[]) { struct testOpts opts; cusolverDnHandle_t handle = NULL; cublasHandle_t cublasHandle = NULL; cudaStream_t stream = NULL; int rowsA = 0; int colsA = 0; int nnzA = 0; int baseA = 0; int lda = 0; int *h_csrRowPtrA = NULL; int *h_csrColIndA = NULL; double *h_csrValA = NULL; double *h_A = NULL; double *h_x = NULL; double *h_b = NULL; double *h_r = NULL; double *d_A = NULL; double *d_x = NULL; double *d_b = NULL; double *d_r = NULL; const double minus_one = -1.0; const double one = 1.0; double x_inf = 0.0; double r_inf = 0.0; double A_inf = 0.0; int errors = 0; parseCommandLineArguments(argc, argv, opts); if (NULL == opts.testFunc) { opts.testFunc = "chol"; } findCudaDevice(argc, (const char **)argv); printf("step 1: read matrix market format\n"); if (opts.sparse_mat_filename == NULL) { opts.sparse_mat_filename = sdkFindFilePath("gr_900_900_crg.mtx", argv[0]); if (opts.sparse_mat_filename != NULL) printf("Using default input file [%s]\n", opts.sparse_mat_filename); else printf("Could not find gr_900_900_crg.mtx\n"); } else { printf("Using input file [%s]\n", opts.sparse_mat_filename); } if (opts.sparse_mat_filename == NULL) { fprintf(stderr, "Error: input matrix is not provided\n"); return EXIT_FAILURE; } if (loadMMSparseMatrix<double>(opts.sparse_mat_filename, 'd', true, &rowsA, &colsA, &nnzA, &h_csrValA, &h_csrRowPtrA, &h_csrColIndA, true)) { exit(EXIT_FAILURE); } baseA = h_csrRowPtrA[0]; printf("sparse matrix A is %d x %d with %d nonzeros, base=%d\n", rowsA, colsA, nnzA, baseA); if (rowsA != colsA) { fprintf(stderr, "Error: only support square matrix\n"); exit(EXIT_FAILURE); } printf("step 2: convert CSR(A) to dense matrix\n"); lda = opts.lda ? opts.lda : rowsA; if (lda < rowsA) { fprintf(stderr, "Error: lda must be greater or equal to dimension of A\n"); exit(EXIT_FAILURE); } h_A = (double *)malloc(sizeof(double) * lda * colsA); h_x = (double *)malloc(sizeof(double) * colsA); h_b = (double *)malloc(sizeof(double) * rowsA); h_r = (double *)malloc(sizeof(double) * rowsA); assert(NULL != h_A); assert(NULL != h_x); assert(NULL != h_b); assert(NULL != h_r); memset(h_A, 0, sizeof(double) * lda * colsA); for (int row = 0; row < rowsA; row++) { const int start = h_csrRowPtrA[row] - baseA; const int end = h_csrRowPtrA[row + 1] - baseA; for (int colidx = start; colidx < end; colidx++) { const int col = h_csrColIndA[colidx] - baseA; const double Areg = h_csrValA[colidx]; h_A[row + col * lda] = Areg; } } printf("step 3: set right hand side vector (b) to 1\n"); for (int row = 0; row < rowsA; row++) { h_b[row] = 1.0; } if (0 == strcmp(opts.testFunc, "chol")) { int issym = 1; for (int j = 0; j < colsA; j++) { for (int i = j; i < rowsA; i++) { double Aij = h_A[i + j * lda]; double Aji = h_A[j + i * lda]; if (Aij != Aji) { issym = 0; break; } } } if (!issym) { printf("Error: A has no symmetric pattern, please use LU or QR \n"); exit(EXIT_FAILURE); } } checkCudaErrors(cusolverDnCreate(&handle)); checkCudaErrors(cublasCreate(&cublasHandle)); checkCudaErrors(cudaStreamCreate(&stream)); checkCudaErrors(cusolverDnSetStream(handle, stream)); checkCudaErrors(cublasSetStream(cublasHandle, stream)); checkCudaErrors(cudaMalloc((void **)&d_A, sizeof(double) * lda * colsA)); checkCudaErrors(cudaMalloc((void **)&d_x, sizeof(double) * colsA)); checkCudaErrors(cudaMalloc((void **)&d_b, sizeof(double) * rowsA)); checkCudaErrors(cudaMalloc((void **)&d_r, sizeof(double) * rowsA)); printf("step 4: prepare data on device\n"); checkCudaErrors(cudaMemcpy(d_A, h_A, sizeof(double) * lda * colsA, cudaMemcpyHostToDevice)); checkCudaErrors( cudaMemcpy(d_b, h_b, sizeof(double) * rowsA, cudaMemcpyHostToDevice)); printf("step 5: solve A*x = b \n"); if (0 == strcmp(opts.testFunc, "chol")) { linearSolverCHOL(handle, rowsA, d_A, lda, d_b, d_x); } else if (0 == strcmp(opts.testFunc, "lu")) { linearSolverLU(handle, rowsA, d_A, lda, d_b, d_x); } else if (0 == strcmp(opts.testFunc, "qr")) { linearSolverQR(handle, rowsA, d_A, lda, d_b, d_x); } else { fprintf(stderr, "Error: %s is unknown function\n", opts.testFunc); exit(EXIT_FAILURE); } printf("step 6: evaluate residual\n"); checkCudaErrors( cudaMemcpy(d_r, d_b, sizeof(double) * rowsA, cudaMemcpyDeviceToDevice)); checkCudaErrors(cublasDgemm_v2(cublasHandle, CUBLAS_OP_N, CUBLAS_OP_N, rowsA, 1, colsA, &minus_one, d_A, lda, d_x, rowsA, &one, d_r, rowsA)); checkCudaErrors( cudaMemcpy(h_x, d_x, sizeof(double) * colsA, cudaMemcpyDeviceToHost)); checkCudaErrors( cudaMemcpy(h_r, d_r, sizeof(double) * rowsA, cudaMemcpyDeviceToHost)); x_inf = vec_norminf(colsA, h_x); r_inf = vec_norminf(rowsA, h_r); A_inf = mat_norminf(rowsA, colsA, h_A, lda); printf("|b - A*x| = %E \n", r_inf); printf("|A| = %E \n", A_inf); printf("|x| = %E \n", x_inf); printf("|b - A*x|/(|A|*|x|) = %E \n", r_inf / (A_inf * x_inf)); if (handle) { checkCudaErrors(cusolverDnDestroy(handle)); } if (cublasHandle) { checkCudaErrors(cublasDestroy(cublasHandle)); } if (stream) { checkCudaErrors(cudaStreamDestroy(stream)); } if (h_csrValA) { free(h_csrValA); } if (h_csrRowPtrA) { free(h_csrRowPtrA); } if (h_csrColIndA) { free(h_csrColIndA); } if (h_A) { free(h_A); } if (h_x) { free(h_x); } if (h_b) { free(h_b); } if (h_r) { free(h_r); } if (d_A) { checkCudaErrors(cudaFree(d_A)); } if (d_x) { checkCudaErrors(cudaFree(d_x)); } if (d_b) { checkCudaErrors(cudaFree(d_b)); } if (d_r) { checkCudaErrors(cudaFree(d_r)); } return 0; }
#include <assert.h> #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <cuda_runtime.h> #include "cublas_v2.h" #include "cusolverDn.h" #include "helper_cuda.h" #include "helper_cusolver.h" template <typename T_ELEM> int loadMMSparseMatrix(char *filename, char elem_type, bool csrFormat, int *m, int *n, int *nnz, T_ELEM **aVal, int **aRowInd, int **aColInd, int extendSymMatrix); void UsageDN(void) { printf("<options>\n"); printf("-h : display this help\n"); printf("-R=<name> : choose a linear solver\n"); printf(" chol (cholesky factorization), this is default\n"); printf(" qr (QR factorization)\n"); printf(" lu (LU factorization)\n"); printf("-lda=<int> : leading dimension of A , m by default\n"); printf("-file=<filename>: filename containing a matrix in MM format\n"); printf("-device=<device_id> : <device_id> if want to run on specific GPU\n"); exit(0); } int linearSolverCHOL(cusolverDnHandle_t handle, int n, const double *Acopy, int lda, const double *b, double *x) { int bufferSize = 0; int *info = NULL; double *buffer = NULL; double *A = NULL; int h_info = 0; double start, stop; double time_solve; cublasFillMode_t uplo = CUBLAS_FILL_MODE_LOWER; checkCudaErrors(cusolverDnDpotrf_bufferSize(handle, uplo, n, (double *)Acopy, lda, &bufferSize)); checkCudaErrors(cudaMalloc(&info, sizeof(int))); checkCudaErrors(cudaMalloc(&buffer, sizeof(double) * bufferSize)); checkCudaErrors(cudaMalloc(&A, sizeof(double) * lda * n)); checkCudaErrors( cudaMemcpy(A, Acopy, sizeof(double) * lda * n, cudaMemcpyDeviceToDevice)); checkCudaErrors(cudaMemset(info, 0, sizeof(int))); start = second(); start = second(); checkCudaErrors( cusolverDnDpotrf(handle, uplo, n, A, lda, buffer, bufferSize, info)); checkCudaErrors( cudaMemcpy(&h_info, info, sizeof(int), cudaMemcpyDeviceToHost)); if (0 != h_info) { fprintf(stderr, "Error: Cholesky factorization failed\n"); } checkCudaErrors( cudaMemcpy(x, b, sizeof(double) * n, cudaMemcpyDeviceToDevice)); checkCudaErrors(cusolverDnDpotrs(handle, uplo, n, 1, A, lda, x, n, info)); checkCudaErrors(cudaDeviceSynchronize()); stop = second(); time_solve = stop - start; fprintf(stdout, "timing: cholesky = %10.6f sec\n", time_solve); if (info) { checkCudaErrors(cudaFree(info)); } if (buffer) { checkCudaErrors(cudaFree(buffer)); } if (A) { checkCudaErrors(cudaFree(A)); } return 0; } int linearSolverLU(cusolverDnHandle_t handle, int n, const double *Acopy, int lda, const double *b, double *x) { int bufferSize = 0; int *info = NULL; double *buffer = NULL; double *A = NULL; int *ipiv = NULL; int h_info = 0; double start, stop; double time_solve; checkCudaErrors(cusolverDnDgetrf_bufferSize(handle, n, n, (double *)Acopy, lda, &bufferSize)); checkCudaErrors(cudaMalloc(&info, sizeof(int))); checkCudaErrors(cudaMalloc(&buffer, sizeof(double) * bufferSize)); checkCudaErrors(cudaMalloc(&A, sizeof(double) * lda * n)); checkCudaErrors(cudaMalloc(&ipiv, sizeof(int) * n)); checkCudaErrors( cudaMemcpy(A, Acopy, sizeof(double) * lda * n, cudaMemcpyDeviceToDevice)); checkCudaErrors(cudaMemset(info, 0, sizeof(int))); start = second(); start = second(); checkCudaErrors(cusolverDnDgetrf(handle, n, n, A, lda, buffer, ipiv, info)); checkCudaErrors( cudaMemcpy(&h_info, info, sizeof(int), cudaMemcpyDeviceToHost)); if (0 != h_info) { fprintf(stderr, "Error: LU factorization failed\n"); } checkCudaErrors( cudaMemcpy(x, b, sizeof(double) * n, cudaMemcpyDeviceToDevice)); checkCudaErrors( cusolverDnDgetrs(handle, CUBLAS_OP_N, n, 1, A, lda, ipiv, x, n, info)); checkCudaErrors(cudaDeviceSynchronize()); stop = second(); time_solve = stop - start; fprintf(stdout, "timing: LU = %10.6f sec\n", time_solve); if (info) { checkCudaErrors(cudaFree(info)); } if (buffer) { checkCudaErrors(cudaFree(buffer)); } if (A) { checkCudaErrors(cudaFree(A)); } if (ipiv) { checkCudaErrors(cudaFree(ipiv)); } return 0; } int linearSolverQR(cusolverDnHandle_t handle, int n, const double *Acopy, int lda, const double *b, double *x) { cublasHandle_t cublasHandle = NULL; int bufferSize = 0; int bufferSize_geqrf = 0; int bufferSize_ormqr = 0; int *info = NULL; double *buffer = NULL; double *A = NULL; double *tau = NULL; int h_info = 0; double start, stop; double time_solve; const double one = 1.0; checkCudaErrors(cublasCreate(&cublasHandle)); checkCudaErrors(cusolverDnDgeqrf_bufferSize(handle, n, n, (double *)Acopy, lda, &bufferSize_geqrf)); checkCudaErrors(cusolverDnDormqr_bufferSize(handle, CUBLAS_SIDE_LEFT, CUBLAS_OP_T, n, 1, n, A, lda, NULL, x, n, &bufferSize_ormqr)); printf("buffer_geqrf = %d, buffer_ormqr = %d \n", bufferSize_geqrf, bufferSize_ormqr); bufferSize = (bufferSize_geqrf > bufferSize_ormqr) ? bufferSize_geqrf : bufferSize_ormqr; checkCudaErrors(cudaMalloc(&info, sizeof(int))); checkCudaErrors(cudaMalloc(&buffer, sizeof(double) * bufferSize)); checkCudaErrors(cudaMalloc(&A, sizeof(double) * lda * n)); checkCudaErrors(cudaMalloc((void **)&tau, sizeof(double) * n)); checkCudaErrors( cudaMemcpy(A, Acopy, sizeof(double) * lda * n, cudaMemcpyDeviceToDevice)); checkCudaErrors(cudaMemset(info, 0, sizeof(int))); start = second(); start = second(); checkCudaErrors( cusolverDnDgeqrf(handle, n, n, A, lda, tau, buffer, bufferSize, info)); checkCudaErrors( cudaMemcpy(&h_info, info, sizeof(int), cudaMemcpyDeviceToHost)); if (0 != h_info) { fprintf(stderr, "Error: LU factorization failed\n"); } checkCudaErrors( cudaMemcpy(x, b, sizeof(double) * n, cudaMemcpyDeviceToDevice)); checkCudaErrors(cusolverDnDormqr(handle, CUBLAS_SIDE_LEFT, CUBLAS_OP_T, n, 1, n, A, lda, tau, x, n, buffer, bufferSize, info)); checkCudaErrors(cublasDtrsm(cublasHandle, CUBLAS_SIDE_LEFT, CUBLAS_FILL_MODE_UPPER, CUBLAS_OP_N, CUBLAS_DIAG_NON_UNIT, n, 1, &one, A, lda, x, n)); checkCudaErrors(cudaDeviceSynchronize()); stop = second(); time_solve = stop - start; fprintf(stdout, "timing: QR = %10.6f sec\n", time_solve); if (cublasHandle) { checkCudaErrors(cublasDestroy(cublasHandle)); } if (info) { checkCudaErrors(cudaFree(info)); } if (buffer) { checkCudaErrors(cudaFree(buffer)); } if (A) { checkCudaErrors(cudaFree(A)); } if (tau) { checkCudaErrors(cudaFree(tau)); } return 0; } void parseCommandLineArguments(int argc, char *argv[], struct testOpts &opts) { memset(&opts, 0, sizeof(opts)); if (checkCmdLineFlag(argc, (const char **)argv, "-h")) { UsageDN(); } if (checkCmdLineFlag(argc, (const char **)argv, "R")) { char *solverType = NULL; getCmdLineArgumentString(argc, (const char **)argv, "R", &solverType); if (solverType) { if ((STRCASECMP(solverType, "chol") != 0) && (STRCASECMP(solverType, "lu") != 0) && (STRCASECMP(solverType, "qr") != 0)) { printf("\nIncorrect argument passed to -R option\n"); UsageDN(); } else { opts.testFunc = solverType; } } } if (checkCmdLineFlag(argc, (const char **)argv, "file")) { char *fileName = 0; getCmdLineArgumentString(argc, (const char **)argv, "file", &fileName); if (fileName) { opts.sparse_mat_filename = fileName; } else { printf("\nIncorrect filename passed to -file \n "); UsageDN(); } } if (checkCmdLineFlag(argc, (const char **)argv, "lda")) { opts.lda = getCmdLineArgumentInt(argc, (const char **)argv, "lda"); } }
int main(int argc, char *argv[]) { struct testOpts opts; cusolverDnHandle_t handle = NULL; cublasHandle_t cublasHandle = NULL; cudaStream_t stream = NULL; int rowsA = 0; int colsA = 0; int nnzA = 0; int baseA = 0; int lda = 0; int *h_csrRowPtrA = NULL; int *h_csrColIndA = NULL; double *h_csrValA = NULL; double *h_A = NULL; double *h_x = NULL; double *h_b = NULL; double *h_r = NULL; double *d_A = NULL; double *d_x = NULL; double *d_b = NULL; double *d_r = NULL; const double minus_one = -1.0; const double one = 1.0; double x_inf = 0.0; double r_inf = 0.0; double A_inf = 0.0; int errors = 0; parseCommandLineArguments(argc, argv, opts); if (NULL == opts.testFunc) { opts.testFunc = "chol"; } findCudaDevice(argc, (const char **)argv); printf("step 1: read matrix market format\n"); if (opts.sparse_mat_filename == NULL) { opts.sparse_mat_filename = sdkFindFilePath("gr_900_900_crg.mtx", argv[0]); if (opts.sparse_mat_filename != NULL) printf("Using default input file [%s]\n", opts.sparse_mat_filename); else printf("Could not find gr_900_900_crg.mtx\n"); } else { printf("Using input file [%s]\n", opts.sparse_mat_filename); } if (opts.sparse_mat_filename == NULL) { fprintf(stderr, "Error: input matrix is not provided\n"); return EXIT_FAILURE; } if (loadMMSparseMatrix<double>(opts.sparse_mat_filename, 'd', true, &rowsA, &colsA, &nnzA, &h_csrValA, &h_csrRowPtrA, &h_csrColIndA, true)) { exit(EXIT_FAILURE); } baseA = h_csrRowPtrA[0]; printf("sparse matrix A is %d x %d with %d nonzeros, base=%d\n", rowsA, colsA, nnzA, baseA); if (rowsA != colsA) { fprintf(stderr, "Error: only support square matrix\n"); exit(EXIT_FAILURE); } printf("step 2: convert CSR(A) to dense matrix\n"); lda = opts.lda ? opts.lda : rowsA; if (lda < rowsA) { fprintf(stderr, "Error: lda must be greater or equal to dimension of A\n"); exit(EXIT_FAILURE); } h_A = (double *)malloc(sizeof(double) * lda * colsA); h_x = (double *)malloc(sizeof(double) * colsA); h_b = (double *)malloc(sizeof(double) * rowsA); h_r = (double *)malloc(sizeof(double) * rowsA); assert(NULL != h_A); assert(NULL != h_x); assert(NULL != h_b); assert(NULL != h_r); memset(h_A, 0, sizeof(double) * lda * colsA); for (int row = 0; row < rowsA; row++) { const int start = h_csrRowPtrA[row] - baseA; const int end = h_csrRowPtrA[row + 1] - baseA; for (int colidx = start; colidx < end; colidx++) { const int col = h_csrColIndA[colidx] - baseA; const double Areg = h_csrValA[colidx]; h_A[row + col * lda] = Areg; } } printf("step 3: set right hand side vector (b) to 1\n"); for (int row = 0; row < rowsA; row++) { h_b[row] = 1.0; } if (0 == strcmp(opts.testFunc, "chol")) { int issym = 1; for (int j = 0; j < colsA; j++) { for (int i = j; i < rowsA; i++) { double Aij = h_A[i + j * lda]; double Aji = h_A[j + i * lda]; if (Aij != Aji) { issym = 0; break; } } } if (!issym) { printf("Error: A has no symmetric pattern, please use LU or QR \n"); exit(EXIT_FAILURE); } } checkCudaErrors(cusolverDnCreate(&handle)); checkCudaErrors(cublasCreate(&cublasHandle)); checkCudaErrors(cudaStreamCreate(&stream)); checkCudaErrors(cusolverDnSetStream(handle, stream)); checkCudaErrors(cublasSetStream(cublasHandle, stream)); checkCudaErrors(cudaMalloc((void **)&d_A, sizeof(double) * lda * colsA)); checkCudaErrors(cudaMalloc((void **)&d_x, sizeof(double) * colsA)); checkCudaErrors(cudaMalloc((void **)&d_b, sizeof(double) * rowsA)); checkCudaErrors(cudaMalloc((void **)&d_r, sizeof(double) * rowsA)); printf("step 4: prepare data on device\n"); checkCudaErrors(cudaMemcpy(d_A, h_A, sizeof(double) * lda * colsA, cudaMemcpyHostToDevice)); checkCudaErrors( cudaMemcpy(d_b, h_b, sizeof(double) * rowsA, cudaMemcpyHostToDevice)); printf("step 5: solve A*x = b \n"); if (0 == strcmp(opts.testFunc, "chol")) { linearSolverCHOL(handle, rowsA, d_A, lda, d_b, d_x); } else if (0 == strcmp(opts.testFunc, "lu")) { linearSolverLU(handle, rowsA, d_A, lda, d_b, d_x); } else if (0 == strcmp(opts.testFunc, "qr")) { linearSolverQR(handle, rowsA, d_A, lda, d_b, d_x); } else { fprintf(stderr, "Error: %s is unknown function\n", opts.testFunc); exit(EXIT_FAILURE); } printf("step 6: evaluate residual\n"); checkCudaErrors( cudaMemcpy(d_r, d_b, sizeof(double) * rowsA, cudaMemcpyDeviceToDevice)); checkCudaErrors(cublasDgemm_v2(cublasHandle, CUBLAS_OP_N, CUBLAS_OP_N, rowsA, 1, colsA, &minus_one, d_A, lda, d_x, rowsA, &one, d_r, rowsA)); checkCudaErrors( cudaMemcpy(h_x, d_x, sizeof(double) * colsA, cudaMemcpyDeviceToHost)); checkCudaErrors( cudaMemcpy(h_r, d_r, sizeof(double) * rowsA, cudaMemcpyDeviceToHost)); x_inf = vec_norminf(colsA, h_x); r_inf = vec_norminf(rowsA, h_r); A_inf = mat_norminf(rowsA, colsA, h_A, lda); printf("|b - A*x| = %E \n", r_inf); printf("|A| = %E \n", A_inf); printf("|x| = %E \n", x_inf); printf("|b - A*x|/(|A|*|x|) = %E \n", r_inf / (A_inf * x_inf)); if (handle) { checkCudaErrors(cusolverDnDestroy(handle)); } if (cublasHandle) { checkCudaErrors(cublasDestroy(cublasHandle)); } if (stream) { checkCudaErrors(cudaStreamDestroy(stream)); } if (h_csrValA) { free(h_csrValA); } if (h_csrRowPtrA) { free(h_csrRowPtrA); } if (h_csrColIndA) { free(h_csrColIndA); } if (h_A) { free(h_A); } if (h_x) { free(h_x); } if (h_b) { free(h_b); } if (h_r) { free(h_r); } if (d_A) { checkCudaErrors(cudaFree(d_A)); } if (d_x) { checkCudaErrors(cudaFree(d_x)); } if (d_b) { checkCudaErrors(cudaFree(d_b)); } if (d_r) { checkCudaErrors(cudaFree(d_r)); } return 0; }
function_block-full_function
[ { "content": "// structure defining the properties of a single buffer\n\nstruct bufferConfig {\n\n string name;\n\n GLenum format;\n\n int bits;\n\n};\n\n\n", "file_path": "Common/rendercheck_gl.h", "rank": 0, "score": 201948.48625693982 }, { "content": "class ArrayFileWriter<int> {\n\n public:\n\n bool write(const char *filename, int *data, unsigned int len, float epsilon) {\n\n return sdkWriteFile(filename, data, len, epsilon, false);\n\n }\n\n};\n\n\n\n// Here's the specialization for floats:\n\ntemplate <>\n", "file_path": "Samples/simpleTemplates_nvrtc/simpleTemplates.cpp", "rank": 1, "score": 185017.40764760156 }, { "content": "struct ConstantBuffer {\n\n float vQuadRect[4];\n\n int UseCase;\n\n};\n\n\n\nID3D11VertexShader *g_pVertexShader;\n\nID3D11PixelShader *g_pPixelShader;\n\nID3D11Buffer *g_pConstantBuffer;\n\nID3D11SamplerState *g_pSamplerState;\n\n\n\n#endif\n\n// testing/tracing function used pervasively in tests. if the condition is\n\n// unsatisfied\n\n// then spew and fail the function immediately (doing no cleanup)\n\n#define AssertOrQuit(x) \\\n\n if (!(x)) { \\\n\n fprintf(stdout, \"Assert unsatisfied in %s at %s:%d\\n\", __FUNCTION__, \\\n\n __FILE__, __LINE__); \\\n\n return 1; \\\n\n }\n", "file_path": "Samples/simpleD3D11Texture/simpleD3D11Texture.cpp", "rank": 2, "score": 172519.0598137092 }, { "content": "class ArrayComparator<int> {\n\n public:\n\n bool compare(const int *reference, int *data, unsigned int len) {\n\n return compareData(reference, data, len, 0.15f, 0.0f);\n\n }\n\n};\n\n\n\n// Here's the specialization for floats:\n\ntemplate <>\n", "file_path": "Samples/simpleTemplates_nvrtc/simpleTemplates.cpp", "rank": 3, "score": 138370.69183356277 }, { "content": "struct vec4<double> {\n\n typedef double4 Type;\n\n};\n\n\n", "file_path": "Samples/nbody/bodysystem.h", "rank": 4, "score": 138366.70264845793 }, { "content": "struct vec3<double> {\n\n typedef double3 Type;\n\n};\n\n\n\ntemplate <typename T>\n", "file_path": "Samples/nbody/bodysystem.h", "rank": 5, "score": 138366.70264845793 }, { "content": "////////////////////////////////////////\n\n// Demo Parameters\n\n////////////////////////////////////////\n\nstruct NBodyParams {\n\n float m_timestep;\n\n float m_clusterScale;\n\n float m_velocityScale;\n\n float m_softening;\n\n float m_damping;\n\n float m_pointSize;\n\n float m_x, m_y, m_z;\n\n\n\n void print() {\n\n printf(\"{ %f, %f, %f, %f, %f, %f, %f, %f, %f },\\n\", m_timestep,\n\n m_clusterScale, m_velocityScale, m_softening, m_damping, m_pointSize,\n\n m_x, m_y, m_z);\n\n }\n\n};\n\n\n\nNBodyParams demoParams[] = {\n\n {0.016f, 1.54f, 8.0f, 0.1f, 1.0f, 1.0f, 0, -2, -100},\n\n {0.016f, 0.68f, 20.0f, 0.1f, 1.0f, 0.8f, 0, -2, -30},\n\n {0.0006f, 0.16f, 1000.0f, 1.0f, 1.0f, 0.07f, 0, 0, -1.5f},\n", "file_path": "Samples/nbody/nbody.cpp", "rank": 6, "score": 138052.20075445133 }, { "content": "// Main structure that gets initialized at library load time\n\n// Choose a unique name, or it can clash with other preloaded libraries.\n\nstruct cuHookInfo {\n\n void* handle;\n\n void* preHooks[CU_HOOK_SYMBOLS];\n\n void* postHooks[CU_HOOK_SYMBOLS];\n\n\n\n // Debugging/Stats Info\n\n int bDebugEnabled;\n\n int hookedFunctionCalls[CU_HOOK_SYMBOLS];\n\n\n\n cuHookInfo() {\n\n const char* envHookDebug;\n\n\n\n // Check environment for CU_HOOK_DEBUG to facilitate debugging\n\n envHookDebug = getenv(\"CU_HOOK_DEBUG\");\n\n if (envHookDebug && envHookDebug[0] == '1') {\n\n bDebugEnabled = 1;\n\n fprintf(stderr, \"* %6d >> CUDA HOOK Library loaded.\\n\", getpid());\n\n }\n\n }\n\n\n", "file_path": "Samples/cuHook/libcuhook.cpp", "rank": 7, "score": 135132.02661432605 }, { "content": "struct gemmOpts {\n\n int m;\n\n int n;\n\n int k;\n\n testMethod test_method;\n\n char *elem_type;\n\n int N; // number of multiplications\n\n};\n\n\n\ntemplate <typename T_ELEM>\n", "file_path": "Samples/batchCUBLAS/batchCUBLAS.cpp", "rank": 8, "score": 135127.56338398636 }, { "content": "struct vec4<double> {\n\n typedef double4 Type;\n\n};\n\n\n", "file_path": "Samples/nbody_screen/bodysystem.h", "rank": 9, "score": 135085.6652249439 }, { "content": "struct vec3<double> {\n\n typedef double3 Type;\n\n};\n\n\n\ntemplate <typename T>\n", "file_path": "Samples/nbody_screen/bodysystem.h", "rank": 10, "score": 135085.6652249439 }, { "content": "struct vec3<double> {\n\n typedef double3 Type;\n\n};\n\n\n\ntemplate <typename T>\n", "file_path": "Samples/nbody_opengles/bodysystem.h", "rank": 11, "score": 135085.6652249439 }, { "content": "struct vec4<double> {\n\n typedef double4 Type;\n\n};\n\n\n", "file_path": "Samples/nbody_opengles/bodysystem.h", "rank": 12, "score": 135085.6652249439 }, { "content": "////////////////////////////////////////\n\n// Demo Parameters\n\n////////////////////////////////////////\n\nstruct NBodyParams {\n\n float m_timestep;\n\n float m_clusterScale;\n\n float m_velocityScale;\n\n float m_softening;\n\n float m_damping;\n\n float m_pointSize;\n\n float m_x, m_y, m_z;\n\n\n\n void print() {\n\n printf(\"{ %f, %f, %f, %f, %f, %f, %f, %f, %f },\\n\", m_timestep,\n\n m_clusterScale, m_velocityScale, m_softening, m_damping, m_pointSize,\n\n m_x, m_y, m_z);\n\n }\n\n};\n\n\n\nNBodyParams demoParams[] = {\n\n {0.016f, 1.54f, 8.0f, 0.1f, 1.0f, 1.0f, 0, -2, -100},\n\n {0.016f, 0.68f, 20.0f, 0.1f, 1.0f, 0.8f, 0, -2, -30},\n\n {0.0006f, 0.16f, 1000.0f, 1.0f, 1.0f, 0.07f, 0, 0, -1.5f},\n", "file_path": "Samples/nbody_opengles/nbody_opengles.cpp", "rank": 13, "score": 132342.3017808525 }, { "content": "////////////////////////////////////////\n\n// Demo Parameters\n\n////////////////////////////////////////\n\nstruct NBodyParams {\n\n float m_timestep;\n\n float m_clusterScale;\n\n float m_velocityScale;\n\n float m_softening;\n\n float m_damping;\n\n float m_pointSize;\n\n float m_x, m_y, m_z;\n\n\n\n void print() {\n\n printf(\"{ %f, %f, %f, %f, %f, %f, %f, %f, %f },\\n\", m_timestep,\n\n m_clusterScale, m_velocityScale, m_softening, m_damping, m_pointSize,\n\n m_x, m_y, m_z);\n\n }\n\n};\n\n\n\nNBodyParams demoParams[] = {\n\n {0.016f, 1.54f, 8.0f, 0.1f, 1.0f, 1.0f, 0, -2, -100},\n\n {0.016f, 0.68f, 20.0f, 0.1f, 1.0f, 0.8f, 0, -2, -30},\n\n {0.0006f, 0.16f, 1000.0f, 1.0f, 1.0f, 0.07f, 0, 0, -1.5f},\n", "file_path": "Samples/nbody_screen/nbody_screen.cpp", "rank": 14, "score": 132342.3017808525 }, { "content": "struct cooFormat {\n\n int i ;\n\n int j ;\n\n int p ; // permutation\n\n};\n\n\n\n\n\nint cmp_cooFormat_csr( struct cooFormat *s, struct cooFormat *t)\n\n{\n\n if ( s->i < t->i ){\n\n return -1 ;\n\n }\n\n else if ( s->i > t->i ){\n\n return 1 ;\n\n }\n\n else{\n\n return s->j - t->j ;\n\n }\n\n}\n\n\n", "file_path": "Samples/cuSolverSp_LowlevelCholesky/mmio_wrapper.cpp", "rank": 15, "score": 127172.00006336693 }, { "content": "struct cooFormat {\n\n int i;\n\n int j;\n\n int p; // permutation\n\n};\n\n\n\nint cmp_cooFormat_csr(struct cooFormat *s, struct cooFormat *t) {\n\n if (s->i < t->i) {\n\n return -1;\n\n } else if (s->i > t->i) {\n\n return 1;\n\n } else {\n\n return s->j - t->j;\n\n }\n\n}\n\n\n\nint cmp_cooFormat_csc(struct cooFormat *s, struct cooFormat *t) {\n\n if (s->j < t->j) {\n\n return -1;\n\n } else if (s->j > t->j) {\n", "file_path": "Samples/cuSolverSp_LowlevelQR/mmio_wrapper.cpp", "rank": 16, "score": 127170.77208502454 }, { "content": "struct cooFormat {\n\n int i ;\n\n int j ;\n\n int p ; // permutation\n\n};\n\n\n\n\n\nint cmp_cooFormat_csr( struct cooFormat *s, struct cooFormat *t)\n\n{\n\n if ( s->i < t->i ){\n\n return -1 ;\n\n }\n\n else if ( s->i > t->i ){\n\n return 1 ;\n\n }\n\n else{\n\n return s->j - t->j ;\n\n }\n\n}\n\n\n", "file_path": "Samples/cuSolverDn_LinearSolver/mmio_wrapper.cpp", "rank": 17, "score": 127115.22533360074 }, { "content": "struct cooFormat {\n\n int i ;\n\n int j ;\n\n int p ; // permutation\n\n};\n\n\n\n\n\nint cmp_cooFormat_csr( struct cooFormat *s, struct cooFormat *t)\n\n{\n\n if ( s->i < t->i ){\n\n return -1 ;\n\n }\n\n else if ( s->i > t->i ){\n\n return 1 ;\n\n }\n\n else{\n\n return s->j - t->j ;\n\n }\n\n}\n\n\n", "file_path": "Samples/cuSolverSp_LinearSolver/mmio_wrapper.cpp", "rank": 18, "score": 127115.22533360074 }, { "content": "tcuGraphicsGLRegisterBuffer *cuGraphicsGLRegisterBuffer;\n", "file_path": "Samples/matrixMulDynlinkJIT/cuda_drvapi_dynlink.c", "rank": 19, "score": 124698.38359298406 }, { "content": "tcuD3D9RegisterVertexBuffer *cuD3D9RegisterVertexBuffer;\n", "file_path": "Samples/matrixMulDynlinkJIT/cuda_drvapi_dynlink.c", "rank": 20, "score": 122103.41942374603 }, { "content": "tcuD3D9UnmapVertexBuffer *cuD3D9UnmapVertexBuffer;\n", "file_path": "Samples/matrixMulDynlinkJIT/cuda_drvapi_dynlink.c", "rank": 21, "score": 122103.41942374603 }, { "content": "tcuD3D9MapVertexBuffer *cuD3D9MapVertexBuffer;\n", "file_path": "Samples/matrixMulDynlinkJIT/cuda_drvapi_dynlink.c", "rank": 22, "score": 122103.41942374603 }, { "content": "tcuD3D9UnregisterVertexBuffer *cuD3D9UnregisterVertexBuffer;\n", "file_path": "Samples/matrixMulDynlinkJIT/cuda_drvapi_dynlink.c", "rank": 23, "score": 122103.41942374603 }, { "content": "", "file_path": "Samples/interval/boost/numeric/interval/hw_rounding.hpp", "rank": 24, "score": 121137.939184862 }, { "content": "", "file_path": "Samples/interval/boost/numeric/interval/detail/x86_rounding_control.hpp", "rank": 25, "score": 118316.04851529331 }, { "content": "", "file_path": "Samples/interval/boost/numeric/interval/detail/c99_rounding_control.hpp", "rank": 26, "score": 116487.50339655076 }, { "content": "struct rounding_control<double>:\n\n detail::ia64_rounding_control\n\n{\n\n static const double & force_rounding(const double& r) { return r; }\n\n static double to_int(const double& r) { return rint(r); }\n\n};\n\n\n\ntemplate<>\n", "file_path": "Samples/interval/boost/numeric/interval/detail/ia64_rounding_control.hpp", "rank": 27, "score": 116487.50339655076 }, { "content": "", "file_path": "Samples/interval/boost/numeric/interval/detail/alpha_rounding_control.hpp", "rank": 28, "score": 116487.50339655076 }, { "content": "", "file_path": "Samples/interval/boost/numeric/interval/detail/ppc_rounding_control.hpp", "rank": 29, "score": 116487.50339655076 }, { "content": "", "file_path": "Samples/interval/boost/numeric/interval/detail/sparc_rounding_control.hpp", "rank": 30, "score": 116487.50339655076 }, { "content": "class ArrayFileWriter {\n\n public:\n\n bool write(const char *filename, T *data, unsigned int len, float epsilon) {\n\n fprintf(stderr,\n\n \"Error: no file write function implemented for this type\\n\");\n\n return false;\n\n }\n\n};\n\n\n\n// Here's the specialization for ints:\n\ntemplate <>\n", "file_path": "Samples/simpleTemplates_nvrtc/simpleTemplates.cpp", "rank": 31, "score": 114862.81175968467 }, { "content": "", "file_path": "Samples/interval/boost/numeric/interval/hw_rounding.hpp", "rank": 32, "score": 114767.99530169155 }, { "content": "class ArrayFileWriter<float> {\n\n public:\n\n bool write(const char *filename, float *data, unsigned int len,\n\n float epsilon) {\n\n return sdkWriteFile(filename, data, len, epsilon, false);\n\n }\n\n};\n\n\n\ntemplate <typename T>\n\nCUfunction getKernel(CUmodule in);\n\n\n\ntemplate <>\n\nCUfunction getKernel<int>(CUmodule in) {\n\n CUfunction kernel_addr;\n\n checkCudaErrors(cuModuleGetFunction(&kernel_addr, in, \"testInt\"));\n\n\n\n return kernel_addr;\n\n}\n\n\n\ntemplate <>\n", "file_path": "Samples/simpleTemplates_nvrtc/simpleTemplates.cpp", "rank": 33, "score": 112560.33729264894 }, { "content": "struct rounding_control<long double>:\n\n detail::ia64_rounding_control\n\n{\n\n static const long double & force_rounding(const long double& r) { return r; }\n\n static long double to_int(const long double& r) { return rintl(r); }\n\n};\n\n\n\n} // namespace interval_lib\n\n} // namespace numeric\n\n} // namespace boost\n\n\n\n#undef BOOST_NUMERIC_INTERVAL_NO_HARDWARE\n\n\n\n#endif /* __hpux */\n\n\n\n#endif /* BOOST_NUMERIC_INTERVAL_DETAIL_IA64_ROUNDING_CONTROL_HPP */\n\n\n", "file_path": "Samples/interval/boost/numeric/interval/detail/ia64_rounding_control.hpp", "rank": 34, "score": 110336.21863321881 }, { "content": "", "file_path": "Samples/interval/boost/numeric/interval/detail/c99_rounding_control.hpp", "rank": 35, "score": 110336.21863321881 }, { "content": "", "file_path": "Samples/interval/boost/numeric/interval/detail/x86_rounding_control.hpp", "rank": 36, "score": 110336.21863321881 }, { "content": "", "file_path": "Samples/interval/boost/numeric/interval/detail/ppc_rounding_control.hpp", "rank": 37, "score": 110336.21863321881 }, { "content": "", "file_path": "Samples/interval/boost/numeric/interval/detail/sparc_rounding_control.hpp", "rank": 38, "score": 110336.21863321881 }, { "content": "", "file_path": "Samples/interval/boost/numeric/interval/detail/alpha_rounding_control.hpp", "rank": 39, "score": 110336.21863321881 }, { "content": "class CFrameBufferObject {\n\n public:\n\n CFrameBufferObject(unsigned int width, unsigned int height, unsigned int Bpp,\n\n bool bUseFloat, GLenum eTarget)\n\n : m_Width(width),\n\n m_Height(height),\n\n m_bUseFloat(bUseFloat),\n\n m_eGLTarget(eTarget) {\n\n glGenFramebuffersEXT(1, &m_fboData.fb);\n\n\n\n m_fboData.colorTex =\n\n createTexture(m_eGLTarget, width, height,\n\n (bUseFloat ? GL_RGBA32F_ARB : GL_RGBA8), GL_RGBA);\n\n\n\n m_fboData.depthTex = createTexture(\n\n m_eGLTarget, width, height, GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT);\n\n\n\n attachTexture(m_eGLTarget, m_fboData.colorTex, GL_COLOR_ATTACHMENT0_EXT);\n\n attachTexture(m_eGLTarget, m_fboData.depthTex, GL_DEPTH_ATTACHMENT_EXT);\n\n\n", "file_path": "Common/rendercheck_gl.h", "rank": 40, "score": 108694.75211167293 }, { "content": "class CheckBackBuffer : public CheckRender {\n\n public:\n\n CheckBackBuffer(unsigned int width, unsigned int height, unsigned int Bpp,\n\n bool bUseOpenGL = true)\n\n : CheckRender(width, height, Bpp, false, false, bUseOpenGL) {}\n\n\n\n virtual ~CheckBackBuffer() {}\n\n\n\n virtual bool checkStatus(const char *zfile, int line, bool silent) {\n\n GLenum nErrorCode = glGetError();\n\n\n\n if (nErrorCode != GL_NO_ERROR) {\n\n if (!silent) {\n\n printf(\"Assertion failed(%s,%d): %s\\n\", zfile, line,\n\n gluErrorString(nErrorCode));\n\n }\n\n }\n\n\n\n return true;\n\n }\n", "file_path": "Common/rendercheck_gl.h", "rank": 41, "score": 102982.09225018509 }, { "content": "struct cudaGraphicsResource *cuda_pbo_resource; // handles OpenGL-CUDA exchange\n\n\n\n// Source image on the host side\n\nuchar4 *h_Src = 0;\n\n\n\n// Destination image on the GPU side\n\nuchar4 *d_dst = NULL;\n\n\n\n// Original image width and height\n\nint imageW = 800, imageH = 600;\n\n\n\n// Starting iteration limit\n\nint crunch = 512;\n\n\n\n// Starting position and scale\n\ndouble xOff = -0.5;\n\ndouble yOff = 0.0;\n\ndouble scale = 3.2;\n\n\n\n// Starting stationary position and scale motion\n", "file_path": "Samples/Mandelbrot/Mandelbrot.cpp", "rank": 42, "score": 101715.4787095705 }, { "content": "", "file_path": "Samples/interval/boost/numeric/interval/detail/x86_rounding_control.hpp", "rank": 43, "score": 101585.6194335104 }, { "content": "", "file_path": "Samples/interval/boost/numeric/interval/detail/x86_rounding_control.hpp", "rank": 44, "score": 100870.71351249013 }, { "content": "", "file_path": "Samples/interval/boost/numeric/interval/detail/x86_rounding_control.hpp", "rank": 45, "score": 100870.71351249013 }, { "content": " unsigned int aux_buffer;\n", "file_path": "Common/GL/glxew.h", "rank": 46, "score": 100345.17625583387 }, { "content": " unsigned int buffer_mask;\n", "file_path": "Common/GL/glxew.h", "rank": 47, "score": 100345.17625583387 }, { "content": " unsigned int *g_pos_one;\n", "file_path": "Samples/eigenvalues/structs.h", "rank": 48, "score": 100314.82906264688 }, { "content": " unsigned int *g_num_one;\n", "file_path": "Samples/eigenvalues/structs.h", "rank": 49, "score": 100314.82906264688 }, { "content": " float *g_right_one;\n", "file_path": "Samples/eigenvalues/structs.h", "rank": 50, "score": 100302.35755387873 }, { "content": " float *g_left_one;\n", "file_path": "Samples/eigenvalues/structs.h", "rank": 51, "score": 100302.35755387873 }, { "content": "void display_matrix(int m, int n, int nnzA, const cusparseMatDescr_t descrA,\n\n const double *csrValA, const int *csrRowPtrA,\n\n const int *csrColIndA) {\n\n const int baseA =\n\n (CUSPARSE_INDEX_BASE_ONE == cusparseGetMatIndexBase(descrA)) ? 1 : 0;\n\n\n\n printf(\"m = %d, n = %d, nnz = %d, matlab base-1\\n\", m, n, nnzA);\n\n\n\n for (int row = 0; row < m; row++) {\n\n const int start = csrRowPtrA[row] - baseA;\n\n const int end = csrRowPtrA[row + 1] - baseA;\n\n for (int colidx = start; colidx < end; colidx++) {\n\n const int col = csrColIndA[colidx] - baseA;\n\n double Areg = csrValA[colidx];\n\n printf(\"A(%d, %d) = %20.16E\\n\", row + 1, col + 1, Areg);\n\n }\n\n }\n", "file_path": "Common/helper_cusolver.h", "rank": 52, "score": 100093.46807320893 }, { "content": "", "file_path": "Samples/interval/boost/numeric/interval/ext/x86_fast_rounding_control.hpp", "rank": 53, "score": 98046.05412649104 }, { "content": "struct cudaGraphicsResource *cuda_vbo_resource; // handles OpenGL-CUDA exchange\n\nstatic cData *particles = NULL; // particle positions in host memory\n\nstatic int lastx = 0, lasty = 0;\n\n\n\n// Texture pitch\n\nsize_t tPitch = 0; // Now this is compatible with gcc in 64-bit\n\n\n\nchar *ref_file = NULL;\n\nbool g_bQAAddTestForce = true;\n\nint g_iFrameToCompare = 100;\n\nint g_TotalErrors = 0;\n\n\n\nbool g_bExitESC = false;\n\n\n\n// CheckFBO/BackBuffer class objects\n\nCheckRender *g_CheckRender = NULL;\n\n\n\nvoid autoTest(char **);\n\n\n\nextern \"C\" void addForces(cData *v, int dx, int dy, int spx, int spy, float fx,\n", "file_path": "Samples/fluidsGL/fluidsGL.cpp", "rank": 54, "score": 97854.33590273985 }, { "content": "struct cudaGraphicsResource *cuda_pbo_resource; // handles OpenGL-CUDA exchange\n\nGLuint displayTex = 0;\n\nGLuint bufferTex = 0;\n\nGLuint fprog; // fragment program (shader)\n\n\n\nfloat tx = 9.0f, ty = 10.0f; // image translation\n\nfloat scale = 1.0f / 16.0f; // image scale\n\nfloat cx, cy; // image centre\n\n\n\nvoid display();\n\nvoid initGLBuffers();\n\nvoid runBenchmark(int iterations);\n\nvoid cleanup();\n\n\n\n#define GL_TEXTURE_TYPE GL_TEXTURE_RECTANGLE_ARB\n\n//#define GL_TEXTURE_TYPE GL_TEXTURE_2D\n\n\n\nextern \"C\" void initGL(int *argc, char **argv);\n\nextern \"C\" void loadImageData(int argc, char **argv);\n\n\n", "file_path": "Samples/bicubicTexture/bicubicTexture.cpp", "rank": 55, "score": 97854.33590273985 }, { "content": "struct cudaGraphicsResource *cuda_pbo_resource; // handles OpenGL-CUDA exchange\n\nGLuint texid; // Texture\n\nGLuint shader;\n\n\n\nStopWatchInterface *timer = NULL, *kernel_timer = NULL;\n\n\n\n// Auto-Verification Code\n\nint fpsCount = 0; // FPS count for averaging\n\nint fpsLimit = 8; // FPS limit for sampling\n\nint g_Index = 0;\n\nint g_nFilterSign = 1;\n\nfloat avgFPS = 0.0f;\n\nunsigned int frameCount = 0;\n\nunsigned int g_TotalErrors = 0;\n\nbool g_bInteractive = false;\n\n\n\nint *pArgc = NULL;\n\nchar **pArgv = NULL;\n\n\n\nextern \"C\" int runSingleTest(char *ref_file, char *exec_path);\n", "file_path": "Samples/boxFilter/boxFilter.cpp", "rank": 56, "score": 97854.33590273985 }, { "content": "struct cudaGraphicsResource *cuda_pbo_resource; // handles OpenGL-CUDA exchange\n\nGLuint texid; // texture\n\nGLuint shader;\n\n\n\nint *pArgc = NULL;\n\nchar **pArgv = NULL;\n\n\n\nStopWatchInterface *timer = NULL;\n\nStopWatchInterface *kernel_timer = NULL;\n\n\n\n// Auto-Verification Code\n\nconst int frameCheckNumber = 4;\n\nint fpsCount = 0; // FPS count for averaging\n\nint fpsLimit = 1; // FPS limit for sampling\n\nunsigned int g_TotalErrors = 0;\n\nbool g_bInteractive = false;\n\n\n\n//#define GL_TEXTURE_TYPE GL_TEXTURE_RECTANGLE_ARB\n\n#define GL_TEXTURE_TYPE GL_TEXTURE_2D\n\n\n", "file_path": "Samples/bilateralFilter/bilateralFilter.cpp", "rank": 57, "score": 97854.33590273985 }, { "content": "struct cudaGraphicsResource *cuda_vbo_resource; // handles OpenGLES-CUDA exchange\n\nstatic cData *particles = NULL; // particle positions in host memory\n\nstatic int lastx = 0, lasty = 0;\n\n\n\n// Texture pitch\n\nsize_t tPitch = 0; // Now this is compatible with gcc in 64-bit\n\n\n\nchar *ref_file = NULL;\n\nbool g_bQAAddTestForce = true;\n\nint g_iFrameToCompare = 100;\n\nint g_TotalErrors = 0;\n\n\n\nbool g_bExitESC = false;\n\n\n\nconst unsigned int window_width = 512;\n\nconst unsigned int window_height = 512;\n\n\n\n// CheckFBO/BackBuffer class objects\n\nCheckRender *g_CheckRender = NULL;\n\n\n", "file_path": "Samples/fluidsGLES/fluidsGLES.cpp", "rank": 58, "score": 97854.33590273985 }, { "content": "struct cudaGraphicsResource *cuda_pbo_resource; // handles OpenGL-CUDA exchange\n\n// Source image on the host side\n\nuchar4 *h_Src;\n\nint imageW, imageH;\n\nGLuint shader;\n\n\n\n////////////////////////////////////////////////////////////////////////////////\n\n// Main program\n\n////////////////////////////////////////////////////////////////////////////////\n\nint g_Kernel = 0;\n\nbool g_FPS = false;\n\nbool g_Diag = false;\n\nStopWatchInterface *timer = NULL;\n\n\n\n// Algorithms global parameters\n\nconst float noiseStep = 0.025f;\n\nconst float lerpStep = 0.025f;\n\nstatic float knnNoise = 0.32f;\n\nstatic float nlmNoise = 1.45f;\n\nstatic float lerpC = 0.2f;\n", "file_path": "Samples/imageDenoising/imageDenoisingGL.cpp", "rank": 59, "score": 96046.85106745653 }, { "content": "enum ReduceType { REDUCE_INT, REDUCE_FLOAT, REDUCE_DOUBLE };\n\n\n\n////////////////////////////////////////////////////////////////////////////////\n\n// declaration, forward\n\ntemplate <class T>\n\nbool runTest(int argc, char **argv, ReduceType datatype);\n\n\n\n#define MAX_BLOCK_DIM_SIZE 65535\n\n\n\n#ifdef WIN32\n\n#define strcasecmp strcmpi\n\n#endif\n\n\n\nextern \"C\" bool isPow2(unsigned int x) { return ((x & (x - 1)) == 0); }\n\n\n\nconst char *getReduceTypeString(const ReduceType type) {\n\n switch (type) {\n\n case REDUCE_INT:\n\n return \"int\";\n\n case REDUCE_FLOAT:\n", "file_path": "Samples/reduction/reduction.cpp", "rank": 60, "score": 95514.12384134177 }, { "content": " GLEW_VAR_EXPORT GLboolean __GLEW_KTX_buffer_region;\n", "file_path": "Common/GL/glew.h", "rank": 61, "score": 95456.72692457867 }, { "content": " GLEW_VAR_EXPORT GLboolean __GLEW_MESA_resize_buffers;\n", "file_path": "Common/GL/glew.h", "rank": 62, "score": 95456.72692457867 }, { "content": " WGLEW_EXPORT GLboolean __WGLEW_ARB_buffer_region;\n", "file_path": "Common/GL/wglew.h", "rank": 63, "score": 95456.72692457867 }, { "content": " GLEW_VAR_EXPORT GLboolean __GLEW_APPLE_pixel_buffer;\n", "file_path": "Common/GL/glew.h", "rank": 64, "score": 95456.72692457867 }, { "content": " GLEW_VAR_EXPORT GLboolean __GLEW_ARB_draw_buffers;\n", "file_path": "Common/GL/glew.h", "rank": 65, "score": 95456.72692457867 }, { "content": " WGLEW_EXPORT GLboolean __WGLEW_NV_float_buffer;\n", "file_path": "Common/GL/wglew.h", "rank": 66, "score": 95456.72692457867 }, { "content": " GLXEW_EXPORT GLboolean __GLXEW_NV_float_buffer;\n", "file_path": "Common/GL/glxew.h", "rank": 67, "score": 95456.72692457867 }, { "content": " GLEW_VAR_EXPORT GLboolean __GLEW_NV_float_buffer;\n", "file_path": "Common/GL/glew.h", "rank": 68, "score": 95456.72692457867 }, { "content": " GLEW_VAR_EXPORT GLboolean __GLEW_ARB_copy_buffer;\n", "file_path": "Common/GL/glew.h", "rank": 69, "score": 95456.72692457867 }, { "content": " GLEW_VAR_EXPORT GLboolean __GLEW_ATI_draw_buffers;\n", "file_path": "Common/GL/glew.h", "rank": 70, "score": 95456.72692457867 }, { "content": " GLXEW_EXPORT GLboolean __GLXEW_MESA_release_buffers;\n", "file_path": "Common/GL/glxew.h", "rank": 71, "score": 95456.72692457867 }, { "content": "struct cudaGraphicsResource *cuda_VB_resource; // handles D3D10-CUDA exchange\n\n\n\n// testing/tracing function used pervasively in tests. if the condition is\n\n// unsatisfied then spew and fail the function immediately (doing no cleanup)\n\n#define AssertOrQuit(x) \\\n\n if (!(x)) { \\\n\n fprintf(stdout, \"Assert unsatisfied in %s at %s:%d\\n\", __FUNCTION__, \\\n\n __FILE__, __LINE__); \\\n\n return 1; \\\n\n }\n\n\n", "file_path": "Samples/simpleD3D10/simpleD3D10.cpp", "rank": 72, "score": 94314.59348450573 }, { "content": "struct cudaGraphicsResource *cuda_VB_resource; // handles D3D9-CUDA exchange\n\n\n\nHRESULT InitD3D9(HWND hWnd);\n\nHRESULT InitD3D9RenderState();\n\nHRESULT InitCUDA();\n\nHRESULT InitCUFFT();\n\nHRESULT InitVertexBuffer();\n\nHRESULT FreeVertexBuffer();\n\nHRESULT InitPointTexture();\n\nHRESULT RestoreContextResources();\n\n\n\n#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ | D3DFVF_DIFFUSE)\n\nvoid updateVB(void);\n\nvoid initParticles(cData *p, int dx, int dy);\n\n\n\n// CUFFT plan handle\n\nstatic cufftHandle g_planr2c;\n\nstatic cufftHandle g_planc2r;\n\nstatic cData *g_vxfield = NULL;\n\nstatic cData *g_vyfield = NULL;\n", "file_path": "Samples/fluidsD3D9/fluidsD3D9.cpp", "rank": 73, "score": 94314.59348450573 }, { "content": "struct cudaGraphicsResource *cuda_VB_resource; // handles D3D9-CUDA exchange\n\n\n\nD3DDISPLAYMODEEX g_d3ddm;\n\nD3DPRESENT_PARAMETERS g_d3dpp;\n\n\n\nbool g_bWindowed = true;\n\nbool g_bDeviceLost = false;\n\nbool g_bPassed = true;\n\n\n", "file_path": "Samples/simpleD3D9/simpleD3D9.cpp", "rank": 74, "score": 94314.59348450573 }, { "content": "", "file_path": "Samples/interval/boost/numeric/interval/ext/x86_fast_rounding_control.hpp", "rank": 75, "score": 94278.9785139519 }, { "content": "inline int getCmdLineArgumentInt(const int argc, const char **argv,\n\n const char *string_ref) {\n\n bool bFound = false;\n\n int value = -1;\n\n\n\n if (argc >= 1) {\n\n for (int i = 1; i < argc; i++) {\n\n int string_start = stringRemoveDelimiter('-', argv[i]);\n\n const char *string_argv = &argv[i][string_start];\n\n int length = static_cast<int>(strlen(string_ref));\n\n\n\n if (!STRNCASECMP(string_argv, string_ref, length)) {\n\n if (length + 1 <= static_cast<int>(strlen(string_argv))) {\n\n int auto_inc = (string_argv[length] == '=') ? 1 : 0;\n\n value = atoi(&string_argv[length + auto_inc]);\n\n } else {\n\n value = 0;\n\n }\n\n\n\n bFound = true;\n\n continue;\n\n }\n\n }\n\n }\n\n\n\n if (bFound) {\n\n return value;\n\n } else {\n\n return 0;\n\n }\n", "file_path": "Common/helper_string.h", "rank": 76, "score": 93255.74362049146 }, { "content": " GLEW_VAR_EXPORT GLboolean __GLEW_NV_shader_buffer_load;\n", "file_path": "Common/GL/glew.h", "rank": 77, "score": 93186.8655929867 }, { "content": " GLEW_VAR_EXPORT GLboolean __GLEW_SGIX_texture_multi_buffer;\n", "file_path": "Common/GL/glew.h", "rank": 78, "score": 93186.8655929867 }, { "content": " GLEW_VAR_EXPORT GLboolean __GLEW_AMD_draw_buffers_blend;\n", "file_path": "Common/GL/glew.h", "rank": 79, "score": 93186.8655929867 }, { "content": " BYTE SOBuffers;\n", "file_path": "Samples/simpleD3D11Texture/d3dx11effect/d3dx11effect.h", "rank": 80, "score": 93186.8655929867 }, { "content": "void graphics_swap_buffers() { eglSwapBuffers(eglDisplay, eglSurface); }\n", "file_path": "Samples/fluidsGLES/graphics_interface.h", "rank": 81, "score": 93186.8655929867 }, { "content": " GLEW_VAR_EXPORT GLboolean __GLEW_NV_parameter_buffer_object;\n", "file_path": "Common/GL/glew.h", "rank": 82, "score": 93186.8655929867 }, { "content": " GLEW_VAR_EXPORT GLboolean __GLEW_EXT_pixel_buffer_object;\n", "file_path": "Common/GL/glew.h", "rank": 83, "score": 93186.8655929867 }, { "content": " GLEW_VAR_EXPORT GLboolean __GLEW_ARB_draw_buffers_blend;\n", "file_path": "Common/GL/glew.h", "rank": 84, "score": 93186.8655929867 }, { "content": " GLEW_VAR_EXPORT GLboolean __GLEW_ARB_map_buffer_range;\n", "file_path": "Common/GL/glew.h", "rank": 85, "score": 93186.8655929867 }, { "content": " GLEW_VAR_EXPORT GLboolean __GLEW_EXT_texture_buffer_object;\n", "file_path": "Common/GL/glew.h", "rank": 86, "score": 93186.8655929867 }, { "content": " GLEW_VAR_EXPORT GLboolean __GLEW_NV_parameter_buffer_object2;\n", "file_path": "Common/GL/glew.h", "rank": 87, "score": 93186.8655929867 }, { "content": " GLEW_VAR_EXPORT GLboolean __GLEW_ARB_pixel_buffer_object;\n", "file_path": "Common/GL/glew.h", "rank": 88, "score": 93186.8655929867 }, { "content": " GLEW_VAR_EXPORT GLboolean __GLEW_SGIX_tag_sample_buffer;\n", "file_path": "Common/GL/glew.h", "rank": 89, "score": 93186.8655929867 }, { "content": " GLEW_VAR_EXPORT GLboolean __GLEW_ARB_texture_buffer_object;\n", "file_path": "Common/GL/glew.h", "rank": 90, "score": 93186.8655929867 }, { "content": " GLEW_VAR_EXPORT GLboolean __GLEW_ARB_color_buffer_float;\n", "file_path": "Common/GL/glew.h", "rank": 91, "score": 93186.8655929867 }, { "content": " GLEW_VAR_EXPORT GLboolean __GLEW_NV_depth_buffer_float;\n", "file_path": "Common/GL/glew.h", "rank": 92, "score": 93186.8655929867 }, { "content": " GLEW_VAR_EXPORT GLboolean __GLEW_ATI_map_object_buffer;\n", "file_path": "Common/GL/glew.h", "rank": 93, "score": 93186.8655929867 }, { "content": " GLXEW_EXPORT GLboolean __GLXEW_MESA_copy_sub_buffer;\n", "file_path": "Common/GL/glxew.h", "rank": 94, "score": 93186.8655929867 }, { "content": " GLEW_VAR_EXPORT GLboolean __GLEW_ARB_depth_buffer_float;\n", "file_path": "Common/GL/glew.h", "rank": 95, "score": 93186.8655929867 }, { "content": " GLEW_VAR_EXPORT GLboolean __GLEW_ARB_uniform_buffer_object;\n", "file_path": "Common/GL/glew.h", "rank": 96, "score": 93186.8655929867 }, { "content": " GLEW_VAR_EXPORT GLboolean __GLEW_APPLE_flush_buffer_range;\n", "file_path": "Common/GL/glew.h", "rank": 97, "score": 93186.8655929867 }, { "content": " WGLEW_EXPORT GLboolean __WGLEW_I3D_image_buffer;\n", "file_path": "Common/GL/wglew.h", "rank": 98, "score": 93186.8655929867 }, { "content": " GLEW_VAR_EXPORT GLboolean __GLEW_ARB_vertex_buffer_object;\n", "file_path": "Common/GL/glew.h", "rank": 99, "score": 93186.8655929867 } ]
C++
common/sockets.cpp
kkamagui/TPM2.0-TSS
106e914dd285f1b152c127f1cad564744596cf2f
#include <tcti/tcti_socket.h> #include "debug.h" #include "sockets.h" #ifndef _WIN32 void WSACleanup() {} int WSAGetLastError() { return errno; } #endif void CloseSockets( SOCKET otherSock, SOCKET tpmSock) { closesocket(otherSock); closesocket(tpmSock); } TSS2_RC recvBytes( SOCKET tpmSock, unsigned char *data, int len ) { int iResult = 0; int length; int bytesRead; for( bytesRead = 0, length = len; bytesRead != len; length -= iResult, bytesRead += iResult ) { iResult = recv( tpmSock, (char *)&( data[bytesRead] ), length, 0); if ((iResult == SOCKET_ERROR) || (!iResult)) return TSS2_TCTI_RC_IO_ERROR; } return TSS2_RC_SUCCESS; } TSS2_RC sendBytes( SOCKET tpmSock, const unsigned char *data, int len ) { int iResult = 0; int sentLength = 0; for( sentLength = 0; sentLength < len; len -= iResult, sentLength += iResult ) { iResult = send( tpmSock, (char *)data, len, MSG_NOSIGNAL ); if (iResult == SOCKET_ERROR) return TSS2_TCTI_RC_IO_ERROR; } return TSS2_RC_SUCCESS; } #define SAFE_CALL(func, ...) (func != NULL) ? func(__VA_ARGS__) : 0 int InitSockets( const char *hostName, UINT16 port, UINT8 serverSockets, SOCKET *otherSock, SOCKET *tpmSock, TCTI_LOG_CALLBACK debugfunc, void* data ) { sockaddr_in otherService; sockaddr_in tpmService; int iResult = 0; #ifdef _WIN32 WSADATA wsaData = {0}; static UINT8 socketsEnabled = 0; if( socketsEnabled == 0 ) { iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { SAFE_CALL( debugfunc, data, NO_PREFIX, "WSAStartup failed: %d\n", iResult); return 1; } socketsEnabled = 1; } #endif *otherSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (*otherSock == INVALID_SOCKET) { SAFE_CALL( debugfunc, data, NO_PREFIX, "socket creation failed with error = %d\n", WSAGetLastError() ); return(1); } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "socket created: 0x%x\n", *otherSock ); otherService.sin_family = AF_INET; otherService.sin_addr.s_addr = inet_addr( hostName ); otherService.sin_port = htons(port + 1); if( serverSockets ) { iResult = bind(*otherSock, (SOCKADDR *) &otherService, sizeof (otherService)); if (iResult == SOCKET_ERROR) { SAFE_CALL( debugfunc, data, NO_PREFIX, "bind failed with error %u\n", WSAGetLastError()); closesocket(*otherSock); WSACleanup(); return 1; } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "bind to IP address:port: %s:%d\n", hostName, port + 1 ); } iResult = listen( *otherSock, 4 ); if (iResult == SOCKET_ERROR) { SAFE_CALL( debugfunc, data, NO_PREFIX, "listen failed with error %u\n", WSAGetLastError()); closesocket(*otherSock); WSACleanup(); return 1; } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "Other CMD server listening to socket: 0x%x\n", *otherSock ); } } } *tpmSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (*tpmSock == INVALID_SOCKET) { SAFE_CALL( debugfunc, data, NO_PREFIX, "socket creation failed with error = %d\n", WSAGetLastError() ); closesocket( *otherSock ); return(1); } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "socket created: 0x%x\n", *tpmSock ); tpmService.sin_family = AF_INET; tpmService.sin_addr.s_addr = inet_addr( hostName ); tpmService.sin_port = htons( port ); if( serverSockets ) { iResult = bind(*tpmSock, (SOCKADDR *) &tpmService, sizeof (tpmService)); if (iResult == SOCKET_ERROR) { SAFE_CALL( debugfunc, data, NO_PREFIX, "bind failed with error %u\n", WSAGetLastError()); closesocket(*tpmSock); WSACleanup(); return 1; } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "bind to IP address:port: %s:%d\n", hostName, port ); } iResult = listen( *tpmSock, 4 ); if (iResult == SOCKET_ERROR) { SAFE_CALL( debugfunc, data, NO_PREFIX, "listen failed with error %u\n", WSAGetLastError()); closesocket(*tpmSock); WSACleanup(); return 1; } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "TPM CMD server listening to socket: 0x%x\n", *tpmSock ); } } } if( !serverSockets ) { iResult = connect(*otherSock, (SOCKADDR *) &otherService, sizeof (otherService)); if (iResult == SOCKET_ERROR) { SAFE_CALL( debugfunc, data, NO_PREFIX, "connect function failed with error: %d\n", WSAGetLastError() ); iResult = closesocket(*otherSock); WSACleanup(); return 1; } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "Client connected to server on port: %d\n", port + 1 ); } iResult = connect(*tpmSock, (SOCKADDR *) &tpmService, sizeof (tpmService)); if (iResult == SOCKET_ERROR) { SAFE_CALL( debugfunc, data, NO_PREFIX, "connect function failed with error: %d\n", WSAGetLastError() ); iResult = closesocket(*otherSock); if (iResult == SOCKET_ERROR) { SAFE_CALL( debugfunc, data, NO_PREFIX, "closesocket function failed with error: %d\n", WSAGetLastError() ); } WSACleanup(); return 1; } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "Client connected to server on port: %d\n", port ); } } return 0; }
#include <tcti/tcti_socket.h> #include "debug.h" #include "sockets.h" #ifndef _WIN32 void WSACleanup() {} int WSAGetLastError() { return errno; } #endif void CloseSockets( SOCKET otherSock, SOCKET tpmSock) { closesocket(otherSock); closesocket(tpmSock); } TSS2_RC recvBytes( SOCKET tpmSock, unsigned char *data, int len ) { int iResult = 0; int length; int bytesRead; for( bytesRead = 0, length = len; bytesRead != len; length -= iResult, bytesRead += iResult ) { iResult = recv( tpmSock, (char *)&( data[bytesRead] ), length, 0); if ((iResult == SOCKET_ERROR) || (!iResult)) return TSS2_TCTI_RC_IO_ERROR; } return TSS2_RC_SUCCESS; } TSS2_RC sendBytes( SOCKET tpmSock, const unsigned char *data, int len ) { int iResult = 0; int sentLength = 0; for( sentLength = 0; sentLength < len; len -= iResult, sentLength += iResult ) { iResult = send( tpmSock, (char *)data, len, MSG_NOSIGNAL ); if (iResult == SOCKET_ERROR) return TSS2_TCTI_RC_IO_ERROR; } return TSS2_RC_SUCCESS; } #define SAFE_CALL(func, ...) (func != NULL) ? func(__VA_ARGS__) : 0 int InitSockets( const char *hostName, UINT16 port, UINT8 serverSockets, SOCKET *otherSock, SOCKET *tpmSock, TCTI_LOG_CALLBACK debugfunc, void* data ) { sockaddr_in otherService; sockaddr_in tpmService; int iResult = 0; #ifdef _WIN32 WSADATA wsaData = {0}; static UINT8 socketsEnabled = 0; if( socketsEnabled == 0 ) { iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { SAFE_CALL( debugfunc, data, NO_PREFIX, "WSAStartup failed: %d\n", iResult); return 1; } socketsEnabled = 1; } #endif *otherSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (*otherSock == INVALID_SOCKET) { SAFE_CALL( debugfunc, data, NO_PREFIX, "socket creation failed with error = %d\n", WSAGetLastError() ); return(1); } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "socket created: 0x%x\n", *otherSock ); otherService.sin_family = AF_INET; otherService.sin_addr.s_addr = inet_addr( hostName ); otherService.sin_port = htons(port + 1); if( serverSockets ) { iResult = bind(*otherSock, (SOCKADDR *) &otherService, sizeof (otherService));
bind to IP address:port: %s:%d\n", hostName, port + 1 ); } iResult = listen( *otherSock, 4 ); if (iResult == SOCKET_ERROR) { SAFE_CALL( debugfunc, data, NO_PREFIX, "listen failed with error %u\n", WSAGetLastError()); closesocket(*otherSock); WSACleanup(); return 1; } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "Other CMD server listening to socket: 0x%x\n", *otherSock ); } } } *tpmSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (*tpmSock == INVALID_SOCKET) { SAFE_CALL( debugfunc, data, NO_PREFIX, "socket creation failed with error = %d\n", WSAGetLastError() ); closesocket( *otherSock ); return(1); } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "socket created: 0x%x\n", *tpmSock ); tpmService.sin_family = AF_INET; tpmService.sin_addr.s_addr = inet_addr( hostName ); tpmService.sin_port = htons( port ); if( serverSockets ) { iResult = bind(*tpmSock, (SOCKADDR *) &tpmService, sizeof (tpmService)); if (iResult == SOCKET_ERROR) { SAFE_CALL( debugfunc, data, NO_PREFIX, "bind failed with error %u\n", WSAGetLastError()); closesocket(*tpmSock); WSACleanup(); return 1; } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "bind to IP address:port: %s:%d\n", hostName, port ); } iResult = listen( *tpmSock, 4 ); if (iResult == SOCKET_ERROR) { SAFE_CALL( debugfunc, data, NO_PREFIX, "listen failed with error %u\n", WSAGetLastError()); closesocket(*tpmSock); WSACleanup(); return 1; } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "TPM CMD server listening to socket: 0x%x\n", *tpmSock ); } } } if( !serverSockets ) { iResult = connect(*otherSock, (SOCKADDR *) &otherService, sizeof (otherService)); if (iResult == SOCKET_ERROR) { SAFE_CALL( debugfunc, data, NO_PREFIX, "connect function failed with error: %d\n", WSAGetLastError() ); iResult = closesocket(*otherSock); WSACleanup(); return 1; } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "Client connected to server on port: %d\n", port + 1 ); } iResult = connect(*tpmSock, (SOCKADDR *) &tpmService, sizeof (tpmService)); if (iResult == SOCKET_ERROR) { SAFE_CALL( debugfunc, data, NO_PREFIX, "connect function failed with error: %d\n", WSAGetLastError() ); iResult = closesocket(*otherSock); if (iResult == SOCKET_ERROR) { SAFE_CALL( debugfunc, data, NO_PREFIX, "closesocket function failed with error: %d\n", WSAGetLastError() ); } WSACleanup(); return 1; } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "Client connected to server on port: %d\n", port ); } } return 0; }
if (iResult == SOCKET_ERROR) { SAFE_CALL( debugfunc, data, NO_PREFIX, "bind failed with error %u\n", WSAGetLastError()); closesocket(*otherSock); WSACleanup(); return 1; } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "
function_block-random_span
[ { "content": " uint16_t port;\n", "file_path": "include/tcti/tcti_socket.h", "rank": 0, "score": 158306.02717439883 }, { "content": " const char *hostname;\n", "file_path": "include/tcti/tcti_socket.h", "rank": 1, "score": 127279.91855985833 }, { "content": " void *logData;\n", "file_path": "include/tcti/tcti_socket.h", "rank": 2, "score": 123489.09362518475 }, { "content": "\tTPM2B_SENSITIVE_DATA\tdata;\t /* data to be sealed */\n", "file_path": "include/sapi/tss2_tpm2_types.h", "rank": 3, "score": 112435.98324259827 }, { "content": "void Unmarshal_TPM2B_CREATION_DATA(\n\n\tTSS2_SYS_CONTEXT *sysContext,\n\n\tTPM2B_CREATION_DATA *creationData\n", "file_path": "sysapi/include/sys_api_marshalUnmarshal.h", "rank": 4, "score": 110970.98984524261 }, { "content": "void Unmarshal_TPMS_CREATION_DATA(\n\n\tTSS2_SYS_CONTEXT *sysContext,\n\n\tTPMS_CREATION_DATA *creationData\n", "file_path": "sysapi/include/sys_api_marshalUnmarshal.h", "rank": 5, "score": 110970.98984524261 }, { "content": "void Unmarshal_TPMS_CREATION_DATA(\n\n\tTSS2_SYS_CONTEXT *sysContext,\n\n\tTPMS_CREATION_DATA *creationData\n\n\t)\n\n{\n\n\tif( SYS_CONTEXT->rval != TSS2_RC_SUCCESS )\n\n\t\treturn;\n\n\n\n\tif( creationData == 0 )\n\n\t\treturn;\n\n\n\n\tUnmarshal_TPML_PCR_SELECTION( sysContext, &creationData->pcrSelect );\n\n\tUNMARSHAL_SIMPLE_TPM2B_NO_SIZE_CHECK( sysContext, (TPM2B *)&creationData->pcrDigest );\n\n\tUnmarshal_TPMA_LOCALITY( sysContext, &creationData->locality );\n\n\tUnmarshal_UINT16( SYS_CONTEXT->tpmOutBuffPtr, SYS_CONTEXT->maxResponseSize, &(SYS_CONTEXT->nextData), &creationData->parentNameAlg, &( SYS_CONTEXT->rval ) );\n\n\tUNMARSHAL_SIMPLE_TPM2B_NO_SIZE_CHECK( sysContext, (TPM2B *)&creationData->parentName );\n\n\tUNMARSHAL_SIMPLE_TPM2B_NO_SIZE_CHECK( sysContext, (TPM2B *)&creationData->parentQualifiedName );\n\n\tUNMARSHAL_SIMPLE_TPM2B_NO_SIZE_CHECK( sysContext, (TPM2B *)&creationData->outsideInfo );\n\n\n\n\treturn;\n", "file_path": "sysapi/sysapi_util/Unmarshal_TPMS_CREATION_DATA.c", "rank": 6, "score": 100637.13076407637 }, { "content": "void Unmarshal_TPM2B_CREATION_DATA(\n\n\tTSS2_SYS_CONTEXT *sysContext,\n\n\tTPM2B_CREATION_DATA *creationData\n\n\t)\n\n{\n\n\tif( SYS_CONTEXT->rval != TSS2_RC_SUCCESS )\n\n\t\treturn;\n\n\n\n\tif( creationData == 0 )\n\n\t\treturn;\n\n\n\n\tif( creationData->t.size != 0 )\n\n\t\tSYS_CONTEXT->rval = TSS2_SYS_RC_BAD_VALUE;\n\n\n\n\tUnmarshal_UINT16( SYS_CONTEXT->tpmOutBuffPtr, SYS_CONTEXT->maxResponseSize, &(SYS_CONTEXT->nextData), &creationData->t.size, &( SYS_CONTEXT->rval ) );\n\n\tUnmarshal_TPMS_CREATION_DATA( sysContext, &creationData->t.creationData );\n\n\n\n\treturn;\n", "file_path": "sysapi/sysapi_util/Unmarshal_TPM2B_CREATION_DATA.c", "rank": 7, "score": 100637.13076407637 }, { "content": "TPM2B_AUTH nullSessionHmac;\n", "file_path": "test/common/sample/CreateNullSession.c", "rank": 8, "score": 91025.12208684918 }, { "content": "void InitNullSession( TPMS_AUTH_COMMAND *nullSessionData )\n\n{\n\n if( nullSessionData )\n\n {\n\n\n\n nullSessionData->sessionHandle = TPM_RS_PW;\n\n\n\n // Init nonce.\n\n nullSessionData->nonce.t.size = 0;\n\n\n\n // init hmac\n\n nullSessionData->hmac.t.size = 0;\n\n\n\n // Init session attributes\n\n *( (UINT8 *)((void *)&( nullSessionData->sessionAttributes ) ) ) = 0;\n\n }\n", "file_path": "test/common/sample/CreateNullSession.c", "rank": 9, "score": 91025.12208684918 }, { "content": "TPM2B_NONCE nullSessionNonce;\n", "file_path": "test/common/sample/CreateNullSession.c", "rank": 10, "score": 91025.12208684918 }, { "content": "void\n\nmarshal_UINT16_rc_previous_fail (void **state)\n\n{\n\n /* Set 'rc' to an error condition. */\n\n TSS2_RC rc = TSS2_SYS_RC_BAD_SIZE;\n\n /* 'rc' is checked first, all other parameters can be NULL.*/\n\n Marshal_UINT16 (NULL, 0, NULL, 0, &rc);\n\n assert_int_equal (rc, TSS2_SYS_RC_BAD_SIZE);\n", "file_path": "test/marshal-UINT16_unit.c", "rank": 11, "score": 91020.97647783147 }, { "content": "void\n\nCheckDataPointers_null_nextData (void **state)\n\n{\n\n TSS2_RC rc;\n\n UINT8 *buffer = (UINT8*)5, *nextData = NULL;\n\n\n\n rc = CheckDataPointers (buffer, &nextData);\n\n assert_int_equal (rc, TSS2_SYS_RC_BAD_REFERENCE);\n", "file_path": "test/CheckOverflow_unit.c", "rank": 12, "score": 88953.41097364799 }, { "content": "void\n\nCheckDataPointers_null_nextData_ptr (void **state)\n\n{\n\n TSS2_RC rc;\n\n UINT8 *buffer = (UINT8*)5, **nextData = NULL;\n\n\n\n rc = CheckDataPointers (buffer, nextData);\n\n assert_int_equal (rc, TSS2_SYS_RC_BAD_REFERENCE);\n", "file_path": "test/CheckOverflow_unit.c", "rank": 13, "score": 87149.04724357736 }, { "content": "#define HOSTNAME_LENGTH 200\n\n\n", "file_path": "tcti/tcti_device.c", "rank": 14, "score": 86767.19747441878 }, { "content": "static UINT8 rmErrorDuringSend = 0;\n", "file_path": "resourcemgr/resourcemgr.c", "rank": 15, "score": 86751.25225012747 }, { "content": "void SendErrorResponse( SOCKET sock )\n\n{\n\n UINT32 numBytes = CHANGE_ENDIAN_DWORD( sizeof( TPM20_ErrorResponse ) );\n\n UINT32 trash = 0;\n\n\n\n rmSendBytes( sock, (unsigned char *)&numBytes, 4 );\n\n rmSendBytes( sock, (unsigned char *)&errorResponse, sizeof( TPM20_ErrorResponse ) );\n\n rmSendBytes( sock, (unsigned char *)&trash, 4 );\n", "file_path": "resourcemgr/resourcemgr.c", "rank": 16, "score": 86751.25225012747 }, { "content": "void CreateErrorResponse( TSS2_RC responseCode )\n\n{\n\n errorResponse.tag = CHANGE_ENDIAN_WORD( TPM_ST_NO_SESSIONS );\n\n errorResponse.responseSize = CHANGE_ENDIAN_DWORD( sizeof( TPM20_ErrorResponse ) );\n\n errorResponse.responseCode = CHANGE_ENDIAN_DWORD( responseCode );\n", "file_path": "resourcemgr/resourcemgr.c", "rank": 17, "score": 86722.4424288969 }, { "content": " uint16_t data_net;\n", "file_path": "test/unmarshal-UINT16_unit.c", "rank": 18, "score": 84076.44483446282 }, { "content": " uint16_t data_net;\n", "file_path": "test/marshal-UINT16_unit.c", "rank": 19, "score": 84076.44483446282 }, { "content": " uint16_t data_host;\n", "file_path": "test/unmarshal-UINT16_unit.c", "rank": 20, "score": 84076.44483446282 }, { "content": " uint16_t data_host;\n", "file_path": "test/marshal-UINT16_unit.c", "rank": 21, "score": 84076.44483446282 }, { "content": " UINT8 otherData;\n", "file_path": "sysapi/include/sysapi_util.h", "rank": 22, "score": 83786.04376025357 }, { "content": " UINT16 decryptNull:1; // Indicates that the decrypt param was NULL at _Prepare call.\n", "file_path": "sysapi/include/sysapi_util.h", "rank": 23, "score": 81589.13267512654 }, { "content": " TCTI_LOG_CALLBACK logCallback;\n", "file_path": "include/tcti/tcti_socket.h", "rank": 24, "score": 81521.83512387738 }, { "content": " UINT8 *nextData;\n", "file_path": "sysapi/include/sysapi_util.h", "rank": 25, "score": 81418.31787172599 }, { "content": "\tUINT8 otherData;\n", "file_path": "include/sapi/sys_api_part3.h", "rank": 26, "score": 81413.63278204601 }, { "content": " void *logData;\n", "file_path": "sysapi/include/tcti_util.h", "rank": 27, "score": 81413.63278204601 }, { "content": " void *logData;\n", "file_path": "include/tcti/tcti_device.h", "rank": 28, "score": 81413.63278204601 }, { "content": "\tUINT8\tsizeofSelect;\t /* the size in octets of the pcrSelect array */\n", "file_path": "include/sapi/tss2_tpm2_types.h", "rank": 29, "score": 79351.70351821468 }, { "content": "\tTPM2B_DIGEST\tcreationHash;\t /* creationHash */\n", "file_path": "include/sapi/tss2_tpm2_types.h", "rank": 30, "score": 79326.2234453517 }, { "content": " TCTI_LOG_BUFFER_CALLBACK logBufferCallback;\n", "file_path": "include/tcti/tcti_socket.h", "rank": 31, "score": 79277.09550779907 }, { "content": "\tUINT16\tdataSize;\t /* the size of the data areaThe maximum size is implementationdependent. The minimum maximum size is platformspecific. */\n", "file_path": "include/sapi/tss2_tpm2_types.h", "rank": 32, "score": 79171.87256508075 }, { "content": "\tTPM2B_DATA\textraData;\t /* external information supplied by callerNOTE\tA TPM2B_DATA structure provides room for a digest and a method indicator to indicate the components of the digest. The definition of this method indicator is outside the scope of this specification. */\n", "file_path": "include/sapi/tss2_tpm2_types.h", "rank": 33, "score": 79171.87256508075 }, { "content": "void\n\nCheckDataPointers_null_buffer (void **state)\n\n{\n\n TSS2_RC rc;\n\n UINT8 *buffer = NULL, *nextData = (UINT8*)5;\n\n\n\n rc = CheckDataPointers (buffer, &nextData);\n\n assert_int_equal (rc, TSS2_SYS_RC_BAD_REFERENCE);\n", "file_path": "test/CheckOverflow_unit.c", "rank": 34, "score": 77543.43393211071 }, { "content": "void Marshal_UINT8( UINT8 *inBuffPtr, UINT32 maxCommandSize, UINT8 **nextData, UINT8 value, TSS2_RC *rval );\n", "file_path": "sysapi/include/sys_api_marshalUnmarshal.h", "rank": 35, "score": 77223.46315242487 }, { "content": "void Unmarshal_UINT8( UINT8 *outBuffPtr, UINT32 maxResponseSize, UINT8 **nextData, UINT8 *value, TSS2_RC *rval );\n", "file_path": "sysapi/include/sys_api_marshalUnmarshal.h", "rank": 36, "score": 77223.46315242487 }, { "content": "TPM_RC Tss2_Sys_Create(\n\n TSS2_SYS_CONTEXT *sysContext,\n\n TPMI_DH_OBJECT\tparentHandle,\n\n TSS2_SYS_CMD_AUTHS const *cmdAuthsArray,\n\n TPM2B_SENSITIVE_CREATE\t*inSensitive,\n\n TPM2B_PUBLIC\t*inPublic,\n\n TPM2B_DATA\t*outsideInfo,\n\n TPML_PCR_SELECTION\t*creationPCR,\n\n TPM2B_PRIVATE\t*outPrivate,\n\n TPM2B_PUBLIC\t*outPublic,\n\n TPM2B_CREATION_DATA\t*creationData,\n\n TPM2B_DIGEST\t*creationHash,\n\n TPMT_TK_CREATION\t*creationTicket,\n\n TSS2_SYS_RSP_AUTHS *rspAuthsArray\n", "file_path": "include/sapi/sys_api_part3.h", "rank": 37, "score": 77195.18050723374 }, { "content": "void Unmarshal_UINT16( UINT8 *outBuffPtr, UINT32 maxResponseSize, UINT8 **nextData, UINT16 *value, TSS2_RC *rval );\n", "file_path": "sysapi/include/sys_api_marshalUnmarshal.h", "rank": 38, "score": 77184.58093877167 }, { "content": "void Marshal_UINT16( UINT8 *inBuffPtr, UINT32 maxCommandSize, UINT8 **nextData, UINT16 value, TSS2_RC *rval );\n", "file_path": "sysapi/include/sys_api_marshalUnmarshal.h", "rank": 39, "score": 77184.58093877167 }, { "content": "\tunsigned int sensitiveDataOrigin : 1;\t/* SET 1 Indicates that when the object was created with TPM2_Create or TPM2_CreatePrimary the TPM generated all of the sensitive data other than the authValue.CLEAR 0 A portion of the sensitive data other than the authValue was provided by the caller. */\n", "file_path": "include/sapi/tss2_tpm2_types.h", "rank": 40, "score": 77050.25974543695 }, { "content": "TPM_RC Tss2_Sys_CertifyCreation(\n\n TSS2_SYS_CONTEXT *sysContext,\n\n TPMI_DH_OBJECT\tsignHandle,\n\n TPMI_DH_OBJECT\tobjectHandle,\n\n TSS2_SYS_CMD_AUTHS const *cmdAuthsArray,\n\n TPM2B_DATA\t*qualifyingData,\n\n TPM2B_DIGEST\t*creationHash,\n\n TPMT_SIG_SCHEME\t*inScheme,\n\n TPMT_TK_CREATION\t*creationTicket,\n\n TPM2B_ATTEST\t*certifyInfo,\n\n TPMT_SIGNATURE\t*signature,\n\n TSS2_SYS_RSP_AUTHS *rspAuthsArray\n", "file_path": "include/sapi/sys_api_part3.h", "rank": 41, "score": 75185.68175743902 }, { "content": "TPM_RC Tss2_Sys_Create_Prepare(\n\n TSS2_SYS_CONTEXT *sysContext,\n\n TPMI_DH_OBJECT\tparentHandle,\n\n TPM2B_SENSITIVE_CREATE\t*inSensitive,\n\n TPM2B_PUBLIC\t*inPublic,\n\n TPM2B_DATA\t*outsideInfo,\n\n TPML_PCR_SELECTION\t*creationPCR\n", "file_path": "include/sapi/sys_api_part3.h", "rank": 42, "score": 75180.52602657302 }, { "content": "\n\nstatic TSS2_RC tctiRecvBytes( TSS2_TCTI_CONTEXT *tctiContext, SOCKET sock, unsigned char *data, int len )\n\n{\n\n TSS2_RC result = 0;\n\n result = recvBytes( sock, data, len);\n\n if ( (INT32)result == SOCKET_ERROR) {\n\n TCTI_LOG( tctiContext, NO_PREFIX, \"In recvBytes, recv failed (socket: 0x%x) with error: %d\\n\", sock, WSAGetLastError() );\n\n return TSS2_TCTI_RC_IO_ERROR;\n\n }\n\n#ifdef DEBUG_SOCKETS\n\n TCTI_LOG( tctiContext, NO_PREFIX, \"Receive Bytes from socket #0x%x: \\n\", sock );\n\n TCTI_LOG_BUFFER( tctiContext, NO_PREFIX, data, len );\n\n#endif\n\n\n\n return TSS2_RC_SUCCESS;\n\n}\n\n\n\nstatic TSS2_RC tctiSendBytes( TSS2_TCTI_CONTEXT *tctiContext, SOCKET sock, const unsigned char *data, int len )\n\n{\n\n TSS2_RC ret = TSS2_RC_SUCCESS;\n", "file_path": "tcti/tcti_socket.cpp", "rank": 46, "score": 45.435858222377185 }, { "content": "\n\n#ifdef DEBUG_SOCKETS\n\n TCTI_LOG( tctiContext, NO_PREFIX, \"Send Bytes to socket #0x%x: \\n\", sock );\n\n TCTI_LOG_BUFFER( tctiContext, NO_PREFIX, (UINT8 *)data, len );\n\n#endif\n\n\n\n ret = sendBytes( sock, data, len);\n\n if (ret != TSS2_RC_SUCCESS)\n\n TCTI_LOG( tctiContext, NO_PREFIX, \"In recvBytes, recv failed (socket: 0x%x) with error: %d\\n\", sock, WSAGetLastError() );\n\n return ret;\n\n}\n\n\n\nTSS2_RC SendSessionEndSocketTcti(\n\n TSS2_TCTI_CONTEXT *tctiContext, /* in */\n\n UINT8 tpmCmdServer )\n\n{\n\n UINT32 tpmSendCommand = TPM_SESSION_END; // Value for \"send command\" to MS simulator.\n\n SOCKET sock;\n\n TSS2_RC rval = TSS2_RC_SUCCESS;\n\n\n", "file_path": "tcti/tcti_socket.cpp", "rank": 51, "score": 33.568600447719675 }, { "content": " return -3;\n\n }\n\n\n\n fclose(f);\n\n return 0;\n\n}\n\n\n\nvoid\n\nhexdump (unsigned long bse, UINT8 *buf, int len)\n\n{\n\n int pos;\n\n char line[80];\n\n\n\n while (len > 0)\n\n {\n\n int cnt, i;\n\n\n\n pos = snprintf (line, sizeof (line), \"%08lx \", bse);\n\n cnt = 16;\n\n if (cnt > len)\n", "file_path": "test/tpmtcticlient/tpmtcticlient.cpp", "rank": 54, "score": 32.415037983973754 }, { "content": "#endif\n\n\n\nextern TSS2_RC SocketSendTpmCommand(\n\n TSS2_TCTI_CONTEXT *tctiContext, /* in */\n\n size_t command_size, /* in */\n\n uint8_t *command_buffer /* in */\n\n );\n\n\n\nTSS2_RC SocketReceiveTpmResponse(\n\n TSS2_TCTI_CONTEXT *tctiContext, /* in */\n\n size_t *response_size, /* out */\n\n unsigned char *response_buffer, /* in */\n\n int32_t timeout\n\n );\n\n\n\nvoid TestCreate1()\n\n{\n\n UINT32 rval;\n\n TPM2B_SENSITIVE_CREATE inSensitive = { { sizeof( TPM2B_SENSITIVE_CREATE ) - 2, } };\n\n TPM2B_PUBLIC inPublic = { { sizeof( TPM2B_PUBLIC ) - 2, } };\n", "file_path": "test/tpmclient/tpmclient.cpp", "rank": 55, "score": 30.182724943348088 }, { "content": " *size += count;\n\n left -= count;\n\n buf += count;\n\n }\n\n\n\n if( *size == 0 )\n\n {\n\n printf(\"File read error\\n\");\n\n fclose(f);\n\n return -3;\n\n }\n\n fclose(f);\n\n return 0;\n\n}\n\n\n\nint saveDataToFile(const char *fileName, UINT8 *buf, UINT16 size)\n\n{\n\n FILE *f;\n\n UINT16 count = 1;\n\n if( fileName == NULL || buf == NULL || size == 0 )\n", "file_path": "test/tpmtcticlient/tpmtcticlient.cpp", "rank": 56, "score": 29.72870968494607 }, { "content": "\n\nint loadDataFromFile(const char *fileName, UINT8 *buf, UINT16 *size)\n\n{\n\n UINT16 count = 1, left;\n\n FILE *f;\n\n if ( size == NULL || buf == NULL || fileName == NULL )\n\n return -1;\n\n\n\n f = fopen(fileName, \"rb+\");\n\n if( f == NULL )\n\n {\n\n printf(\"File(%s) open error.\\n\", fileName);\n\n return -2;\n\n }\n\n\n\n left = *size;\n\n *size = 0;\n\n while( left > 0 && count > 0 )\n\n {\n\n count = fread(buf, 1, left, f);\n", "file_path": "test/tpmtcticlient/tpmtcticlient.cpp", "rank": 58, "score": 28.832633248682853 }, { "content": " hashCheck.digest.t.size = 0;\n\n\n\n char SignMsg[]= \"try to get sign with this msg!\";\n\n UINT16 length = sizeof(SignMsg);\n\n BYTE *buffer = NULL;\n\n UINT8 numBuffers = 0;\n\n UINT16 cpLength = 0;\n\n\n\n buffer = (BYTE*)malloc(length*sizeof(BYTE));\n\n memset(buffer, 0, length*sizeof(BYTE));\n\n memcpy (buffer, SignMsg, length);\n\n if(length%(MAX_DIGEST_BUFFER) != 0)\n\n numBuffers = length/(MAX_DIGEST_BUFFER) + 1;\n\n else\n\n numBuffers = length/(MAX_DIGEST_BUFFER);\n\n\n\n TPM2B_DIGEST *bufferList[numBuffers];\n\n for(UINT8 i = 0; i < numBuffers; i++)\n\n {\n\n (bufferList)[i] = (TPM2B_DIGEST *)calloc(1,sizeof(TPM2B_DIGEST));\n", "file_path": "test/tpmtest/tpmtest.cpp", "rank": 59, "score": 25.795603977177784 }, { "content": " &creationHash, &creationTicket, &sessionsDataOut );\n\n CheckPassed( rval );\n\n printf( \"Name of created key: \" );\n\n PrintSizedBuffer( (TPM2B *)&name );\n\n\n\n rval = Tss2_Sys_Load ( sysContext, handle2048rsa, &sessionsData, &outPrivate, &outPublic,\n\n &loadedSha1KeyHandle, &name, &sessionsDataOut);\n\n CheckPassed( rval );\n\n\n\n printf( \"Name of loading key: \" );\n\n PrintSizedBuffer( (TPM2B *)&name );\n\n\n\n inScheme.scheme = TPM_ALG_RSASSA;\n\n inScheme.details.rsassa.hashAlg = TPM_ALG_SHA1;\n\n hashCheck.tag = TPM_ST_HASHCHECK;\n\n hashCheck.hierarchy = TPM_RH_NULL;\n\n hashCheck.digest.t.size = 0;\n\n\n\n char SignMsg[]= \"try to get sign with this msg!\";\n\n UINT16 length = sizeof(SignMsg);\n", "file_path": "test/tpmtest/tpmtest.cpp", "rank": 60, "score": 24.74464451935264 }, { "content": " DebugPrintf( NO_PREFIX, \"\\nLoaded key handle: %8.8x\\n\", loadedSha1KeyHandle );\n\n}\n\n\n\nvoid TestEvict()\n\n{\n\n TPM_RC rval = TPM_RC_SUCCESS;\n\n TPM2B_SENSITIVE_CREATE inSensitive = { { sizeof( TPM2B_SENSITIVE_CREATE ) - 2, } };\n\n TPM2B_DATA outsideInfo = { { sizeof( TPM2B_DATA ) - 2, } };\n\n TPML_PCR_SELECTION creationPCR;\n\n TPMS_AUTH_COMMAND sessionData;\n\n TPMS_AUTH_RESPONSE sessionDataOut;\n\n TSS2_SYS_CMD_AUTHS sessionsData;\n\n TSS2_SYS_RSP_AUTHS sessionsDataOut;\n\n\n\n TPM2B_PRIVATE outPrivate = { { sizeof( TPM2B_PRIVATE ) - 2, } };\n\n TPM2B_PUBLIC outPublic = { { sizeof( TPM2B_PUBLIC ) - 2, } };\n\n TPM2B_CREATION_DATA creationData = { { sizeof( TPM2B_CREATION_DATA ) - 2, } };\n\n\tTPM2B_DIGEST creationHash = { { sizeof( TPM2B_DIGEST ) - 2, } };\n\n\tTPMT_TK_CREATION creationTicket = { 0, 0, { { sizeof( TPM2B_DIGEST ) - 2, } } };\n\n\n", "file_path": "test/tpmclient/tpmclient.cpp", "rank": 61, "score": 23.157465977308117 }, { "content": " BYTE *buffer = NULL;\n\n UINT8 numBuffers = 0;\n\n UINT16 cpLength = 0;\n\n\n\n buffer = (BYTE*)malloc(length*sizeof(BYTE));\n\n memset(buffer, 0, length*sizeof(BYTE));\n\n memcpy (buffer, SignMsg, length);\n\n\n\n if(length%(MAX_DIGEST_BUFFER) != 0)\n\n numBuffers = length/(MAX_DIGEST_BUFFER) + 1;\n\n else\n\n numBuffers = length/(MAX_DIGEST_BUFFER);\n\n\n\n TPM2B_DIGEST *bufferList[numBuffers];\n\n for(UINT8 i = 0; i < numBuffers; i++)\n\n {\n\n (bufferList)[i] = (TPM2B_DIGEST *)calloc(1,sizeof(TPM2B_DIGEST));\n\n if(i < numBuffers-1)\n\n {\n\n for( UINT16 m = 0; m < MAX_DIGEST_BUFFER; m++)\n", "file_path": "test/tpmtest/tpmtest.cpp", "rank": 62, "score": 22.99614400043099 }, { "content": "TSS2_SYS_CMD_AUTHS nullSessionsData = { 1, &nullSessionDataArray[0] };\n\nTSS2_SYS_RSP_AUTHS nullSessionsDataOut = { 1, &nullSessionDataOutArray[0] };\n\nTPM2B_NONCE nullSessionNonce, nullSessionNonceOut;\n\nTPM2B_AUTH nullSessionHmac;\n\n\n\nvoid CheckFailed( UINT32 rval, UINT32 expectedTpmErrorCode )\n\n{\n\n DebugPrintf( NO_PREFIX, \"\\tfailing case: \" );\n\n if ( rval != expectedTpmErrorCode) {\n\n ErrorHandler( rval);\n\n DebugPrintf( NO_PREFIX, \"\\tFAILED! Ret code s/b: %x, but was: %x\\n\", expectedTpmErrorCode, rval );\n\n Cleanup();\n\n }\n\n else\n\n {\n\n DebugPrintf( NO_PREFIX, \"\\tPASSED!\\n\" );\n\n }\n\n Delay(demoDelay);\n\n}\n\n\n", "file_path": "test/tpmtest/tpmtest.cpp", "rank": 63, "score": 22.77868735648474 }, { "content": " uint8_t responseBuffer[20];\n\n size_t responseSize;\n\n size_t expectedResponseSize;\n\n SOCKET savedTpmSock = 0;\n\n SOCKET savedOtherSock = 0;\n\n int savedDevFile = 0;\n\n uint64_t savedMagic;\n\n uint32_t savedVersion;\n\n uint8_t goodResponseBuffer[] = { 0x80, 0x01, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n uint8_t goodResponseBuffer1[] = { 0x80, 0x01, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00,\n\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };\n\n uint8_t *goodRspBuffer;\n\n\n\n int responseBufferError = 0;\n\n unsigned int i;\n\n char *typeString;\n\n char typeRMString[] = \"RM\";\n\n char typeLocalString[] = \"Local TPM\";\n\n\n\n TSS2_RC rval = TSS2_RC_SUCCESS;\n", "file_path": "test/tpmclient/tpmclient.cpp", "rank": 64, "score": 22.69424306578029 }, { "content": "TPMS_AUTH_COMMAND nullSessionData;\n\nTPMS_AUTH_RESPONSE nullSessionDataOut;\n\nTPMS_AUTH_COMMAND *nullSessionDataArray[1] = { &nullSessionData };\n\nTPMS_AUTH_RESPONSE *nullSessionDataOutArray[1] = { &nullSessionDataOut };\n\nTSS2_SYS_CMD_AUTHS nullSessionsData = { 1, &nullSessionDataArray[0] };\n\nTSS2_SYS_RSP_AUTHS nullSessionsDataOut = { 1, &nullSessionDataOutArray[0] };\n\nTPM2B_NONCE nullSessionNonce, nullSessionNonceOut;\n\nTPM2B_AUTH nullSessionHmac;\n\n\n\nvoid CheckFailed( UINT32 rval, UINT32 expectedTpmErrorCode )\n\n{\n\n DebugPrintf( NO_PREFIX, \"\\tfailing case: \" );\n\n if ( rval != expectedTpmErrorCode) {\n\n ErrorHandler( rval);\n\n DebugPrintf( NO_PREFIX, \"\\tFAILED! Ret code s/b: %x, but was: %x\\n\", expectedTpmErrorCode, rval );\n\n Cleanup();\n\n }\n\n else\n\n {\n\n DebugPrintf( NO_PREFIX, \"\\tPASSED!\\n\" );\n", "file_path": "test/tpmclient/tpmclient.cpp", "rank": 65, "score": 22.53375884229746 }, { "content": " // init hmac\n\n sessionData.hmac.t.size = 0;\n\n\n\n // Init session attributes\n\n *( (UINT8 *)((void *)&sessionData.sessionAttributes ) ) = 0;\n\n\n\n sessionsData.cmdAuthsCount = 1;\n\n sessionsData.cmdAuths[0] = &sessionData;\n\n\n\n inPublic.t.publicArea.parameters.rsaDetail.keyBits = 2048;\n\n\n\n outPublic.t.size = 0;\n\n creationData.t.size = 0;\n\n rval = Tss2_Sys_CreatePrimary( sysContext, TPM_RH_PLATFORM, &sessionsData, &inSensitive, &inPublic,\n\n &outsideInfo, &creationPCR, &handle2048rsa, &outPublic, &creationData, &creationHash,\n\n &creationTicket, &name, &sessionsDataOut );\n\n\tprintf(\"\\nerrorcode: 0x%x\\n\", rval);\n\n CheckPassed( rval );\n\n}\n\nvoid TPM2Create()\n", "file_path": "test/tpmtest/tpmtest.cpp", "rank": 66, "score": 22.26102650798692 }, { "content": "### Changed\n\n- Fixed bug in CreatePrimary and Create: for one-call and decrypt session\n\ncase, they were copying first parameter from incorrect pointer.\n\n- For CopyCreationDataOut, CopyECCPointOut, CopyNvPublicOut, CopyPublicOut\n\nadded placeholder for return code if size != 0 when called. To be filled in\n\nwhen TSS WG decides on error code.\n\n- Fixed bugs in CopySensitiveCreateIn and CopySensitiveIn: they shouldn't look\n\nat the size.\n\n- Fixed bugs in CopyECCPointIn, CopyNvPublicIn, CopyPublicIn, CopySensitiveIn,\n\nand CopySensitiveCreateIn: not handling NULL outpul parameters correctly.\n\n- Changes all instances of calls to ExecuteFinish to a timeout that works for\n\nall cases including communicating with the simulator over the network.\n\n- Fixed call to LoadExternal in TestUnseal--needed to pass in a NULL pointer\n\nfor the inSensitive parameter.\n\n- Fixed bug in CreatePrimary: not passing correct pointer for inSensitive.\n\n- Fixed timeouts for all ExecuteFinish calls in test application.\n\n- Fixed bugs in RM: cases where I wasn't handling errors and then parsing data\n\nthat hadn't been received. Caused seg faults under Linux.\n\n- Fixed timeout for async Startup test.\n\n- Fixed SocketReceiveTpmResponse for blocking case.\n\n- Fixed bug in ExecuteFinish: BAD_SEQUENCE error generated early in function\n\nwas getting overwritten by INSUFFICENT_RESPONSE error.\n\n- Fixed bug in ExecuteFinish: it was always setting timeout to 0 instead of\n\nTSS2_TCTI_TIMEOUT_BLOCK.\n\n- Fixed bug in resource manager: error level for non-TPM errors was getting\n\noverwritten with resource manager error level.\n\n- Replace Implementation.h with implementation.h.\n\n- Changed name of TPMB.h tpmb.h\n\n- GetCapability with bad property returns different error code.\n\n- Shutdown with bad value for shutdownValue causes TPM to go into failure\n\nmode.\n\n- Fixed overlap in error codes: TSS2_BASE_RC_NOT_SUPPORTED and\n\nTSS2_BASE_RC_BAD_TCTI_STRUCTURE had same value.\n\n- Cleaned up all app level error codes.\n\n- Fixed bug with ordering of -startAuthSessionTest command line parameter: if\n\nit was not the last option, tpmclient would fail.\n\n- Fixed bugs related to ContextLoad.\n\n- Fixed bug in EvictContext: it was updating lastSessionSequenceNum even if\n\nthe ContextSave command failed.\n\n- Fixed handling of RM errors that occur during command send.\n\n- Fixed bug in simDriver init function. A second TCTI context being\n\ninitialized was re-initing the whole driver.\n\n- Updated to latest 1.19 header files.\n\n- Fixed bugs in resource manager:\n\n- FindOldestSession wasn't working correctly—it was just finding the first\n\none.\n\n- HandleGap needed to un-gap all the session contexts from the older interval.\n\nIt wasn't doing that.\n\n- Fixed bug in handling of command line options—specifying none would cause\n\nprogram to error out.\n\n- Fixed issues in cleanup of TestStartAuthSession test. It was leaving some\n\nsessions alive.\n\n- Updated copyright notices on all files.\n\n- Changed test app to use linked list of session structures instead of fixed\n\narray. This fixed a host of issues.\n\n- Fixed bugs in Certify, CertifyCreation, Commit, Create, CreatePrimary, and\n\nGetCapability: if null used for return parameters, the function would fail.\n\n- Fixed bug in SimpleHmacOrPolicyTest where it was re-creating the global\n\nsysContext causing failures in later tests because the context was too small.\n\n- Fixed a bug in ExecuteFinish. If response is too small, code was just using\n\nthe command buffer as the response buffer instead of returning an error.\n\n- Fixed some places in test app where I wasn't deleting entries from the\n\nsessions table.\n\n- Fixed build warnings related to size mismatch of connectionId.\n\n- Changed TeardownSysContext to zero out freed context pointer.\n\n- This helps prevent double free errors.\n\n- Fixed bug in EncryptDecryptXOR: wasn't setting the size of the outputData\n\nbuffer.\n", "file_path": "CHANGELOG.md", "rank": 67, "score": 22.24370271498811 }, { "content": "#endif\n\n , version, DEFAULT_HOSTNAME, DEFAULT_RESMGR_TPM_PORT );\n\n}\n\n\n\nint main(int argc, char* argv[])\n\n{\n\n int count;\n\n TSS2_RC rval;\n\n\n\n setvbuf (stdout, NULL, _IONBF, BUFSIZ);\n\n#ifdef SHARED_OUT_FILE\n\n if( argc > 12 )\n\n#else\n\n if( argc > 10 )\n\n#endif\n\n {\n\n PrintHelp();\n\n return 1;\n\n }\n\n else\n", "file_path": "test/tpmclient/tpmclient.cpp", "rank": 68, "score": 22.06915869818419 }, { "content": " &creationTicket, &name, &sessionsDataOut );\n\n CheckFailed( rval, TSS2_SYS_RC_BAD_VALUE );\n\n\n\n outPublic.t.size = 0;\n\n creationData.t.size = 0;\n\n INIT_SIMPLE_TPM2B_SIZE( creationHash );\n\n INIT_SIMPLE_TPM2B_SIZE( name );\n\n rval = Tss2_Sys_CreatePrimary( sysContext, TPM_RH_OWNER, &sessionsData, &inSensitive, &inPublic,\n\n &outsideInfo, &creationPCR, &handle2048rsa, &outPublic, &creationData, &creationHash,\n\n &creationTicket, &name, &sessionsDataOut );\n\n CheckPassed( rval );\n\n\n\n printf( \"\\nNew key successfully created in owner hierarchy (RSA 2048). Handle: 0x%8.8x\\n\",\n\n handle2048rsa );\n\n printf( \"Name of created primary key: \" );\n\n PrintSizedBuffer( (TPM2B *)&name );\n\n\n\n char buffer1contents[] = \"test\";\n\n //char buffer2contents[] = \"string\";\n\n\n", "file_path": "test/tpmclient/tpmclient.cpp", "rank": 69, "score": 22.056793526882135 }, { "content": " (pcrSelection).sizeofSelect = size;\n\n\n\nTPM_CC currentCommandCode;\n\nTPM_CC *currentCommandCodePtr = &currentCommandCode;\n\n\n\n#define errorStringSize 200\n\nchar errorString[errorStringSize];\n\n\n\nUINT8 simulator = 1;\n\n\n\n#if __linux || __unix\n\nUINT8 testLocalTcti = 0;\n\n#endif\n\n\n\nUINT32 tpmMaxResponseLen = TPMBUF_LEN;\n\n\n\nUINT8 resMgrInitialized = 0;\n\n\n\nUINT8 pcrAfterExtend[20];\n\nTPM_HANDLE loadedRsaKeyHandle;\n", "file_path": "test/tpmclient/tpmclient.cpp", "rank": 70, "score": 21.856336634694713 }, { "content": "\n\n // Init session attributes\n\n *( (UINT8 *)((void *)&sessionData.sessionAttributes ) ) = 0;\n\n\n\n sessionsData.cmdAuthsCount = 1;\n\n sessionsData.cmdAuths[0] = &sessionData;\n\n\n\n printf( \"\\nVERIFICATION on CREATED KEY TESTS:\\n\" );\n\n\n\n outPublic.t.size = 0;\n\n creationData.t.size = 0;\n\n rval = Tss2_Sys_CreatePrimary( sysContext, TPM_RH_OWNER, &sessionsData, &inSensitive, &inPublic,\n\n &outsideInfo, &creationPCR, &handle2048rsa, &outPublic, &creationData, &creationHash,\n\n &creationTicket, &name, &sessionsDataOut );\n\n CheckPassed( rval );\n\n\n\n printf( \"\\nNew key successfully created in owner hierarchy (RSA 2048). Handle: 0x%8.8x\\n\",\n\n handle2048rsa );\n\n printf( \"Name of created primary key: \" );\n\n PrintSizedBuffer( (TPM2B *)&name );\n", "file_path": "test/tpmtest/tpmtest.cpp", "rank": 71, "score": 21.635365193570994 }, { "content": "void TestCreate()\n\n{\n\n UINT32 rval;\n\n TPM2B_SENSITIVE_CREATE inSensitive;\n\n TPM2B_PUBLIC inPublic;\n\n TPM2B_DATA outsideInfo;\n\n TPML_PCR_SELECTION creationPCR;\n\n TPMS_AUTH_COMMAND sessionData;\n\n TPMS_AUTH_RESPONSE sessionDataOut;\n\n TSS2_SYS_CMD_AUTHS sessionsData;\n\n\n\n TSS2_SYS_RSP_AUTHS sessionsDataOut;\n\n TPM2B_NAME name;\n\n TPM2B_NAME name1;\n\n TPM2B_PRIVATE outPrivate;\n\n TPM2B_PUBLIC outPublic;\n\n TPM2B_CREATION_DATA creationData;\n\n TPM2B_DIGEST creationHash;\n\n TPMT_TK_CREATION creationTicket = { 0, 0, { { sizeof( TPM2B_DIGEST ) - 2, } } };\n\n\n", "file_path": "test/tpmtest/tpmtest.cpp", "rank": 72, "score": 21.38676163365247 }, { "content": " // Do SAPI test for non-zero sized outPublic\n\n outPublic.t.size = 0xff;\n\n creationData.t.size = 0;\n\n INIT_SIMPLE_TPM2B_SIZE( creationHash );\n\n INIT_SIMPLE_TPM2B_SIZE( name );\n\n rval = Tss2_Sys_CreatePrimary( sysContext, TPM_RH_NULL, &sessionsData, &inSensitive, &inPublic,\n\n &outsideInfo, &creationPCR, &handle2048rsa, &outPublic, &creationData, &creationHash,\n\n &creationTicket, &name, &sessionsDataOut );\n\n CheckFailed( rval, TSS2_SYS_RC_BAD_VALUE );\n\n\n\n#if 0\n\n // Do SAPI test for non-zero sized creationData\n\n outPublic.t.size = 0;\n\n creationData.t.size = 0x10;\n\n rval = Tss2_Sys_CreatePrimary( sysContext, TPM_RH_PLATFORM, &sessionsData, &inSensitive, &inPublic,\n\n &outsideInfo, &creationPCR, &handle2048rsa, &outPublic, &creationData, &creationHash,\n\n &creationTicket, &name, &sessionsDataOut );\n\n CheckFailed( rval, TSS2_SYS_RC_INSUFFICIENT_BUFFER );\n\n#endif\n\n\n", "file_path": "test/tpmtest/tpmtest.cpp", "rank": 73, "score": 21.071331155212324 }, { "content": " nvAuxSessionData.sessionHandle = TPM_RS_PW;\n\n\n\n // Init nonce.\n\n nvAuxSessionData.nonce.t.size = 0;\n\n\n\n // init hmac\n\n nvAuxSessionData.hmac.t.size = 0;\n\n\n\n // init nvAuth\n\n nvAuth.t.size = 0;\n\n\n\n // Init session attributes\n\n *( (UINT8 *)((void *)&nvAuxSessionData.sessionAttributes ) ) = 0;\n\n\n\n nvAuxSessionsData.cmdAuthsCount = 1;\n\n nvAuxSessionsData.cmdAuths[0] = &nvAuxSessionData;\n\n\n\n publicInfo.t.size = sizeof( TPMI_RH_NV_INDEX ) +\n\n sizeof( TPMI_ALG_HASH ) + sizeof( TPMA_NV ) + sizeof( UINT16) +\n\n sizeof( UINT16 );\n", "file_path": "test/tpmtest/tpmtest.cpp", "rank": 74, "score": 20.864931298901286 }, { "content": "{\n\n DebugPrintf( NO_PREFIX, \"\\tpassing case: \" );\n\n if ( rval != TPM_RC_SUCCESS) {\n\n ErrorHandler( rval);\n\n// printf( \"\\tFAILED! %s\\n\", errorString );\n\n\t\tDebugPrintf( NO_PREFIX, \"\\tFAILED! %s\\n\", errorString );\n\n Cleanup();\n\n }\n\n else\n\n {\n\n printf( \"\\tPASSED!\\n\" );\n\n }\n\n\n\n Delay(demoDelay);\n\n}\n\n\n\nTPMS_AUTH_COMMAND nullSessionData;\n\nTPMS_AUTH_RESPONSE nullSessionDataOut;\n\nTPMS_AUTH_COMMAND *nullSessionDataArray[1] = { &nullSessionData };\n\nTPMS_AUTH_RESPONSE *nullSessionDataOutArray[1] = { &nullSessionDataOut };\n", "file_path": "test/tpmtest/tpmtest.cpp", "rank": 75, "score": 20.755205188235205 }, { "content": " *( (UINT8 *)((void *)&sessionData.sessionAttributes ) ) = 0;\n\n\n\n sessionsDataOut.rspAuthsCount = 1;\n\n\n\n sessionsData.cmdAuthsCount = 1;\n\n sessionsData.cmdAuths[0] = &sessionData;\n\n\n\n nvAuth.t.size = strlen( password );\n\n for( i = 0; i < nvAuth.t.size; i++ )\n\n nvAuth.t.buffer[i] = password[i];\n\n\n\n\tpublicInfo.t.size = sizeof( TPMI_RH_NV_INDEX ) +\n\n sizeof( TPMI_ALG_HASH ) + sizeof( TPMA_NV ) + sizeof( UINT16) +\n\n sizeof( UINT16 );\n\n publicInfo.t.nvPublic.nvIndex = nvIndex;\n\n publicInfo.t.nvPublic.nameAlg = TPM_ALG_SHA1;\n\n\n\n // First zero out attributes.\n\n *(UINT32 *)&( publicInfo.t.nvPublic.attributes ) = 0;\n\n\n", "file_path": "test/tpmtest/tpmtest.cpp", "rank": 76, "score": 20.67895423472946 }, { "content": "TPM_HANDLE loadedSha1KeyHandle;\n\n\n\nTPM2B_AUTH loadedSha1KeyAuth;\n\n\n\nTPM_HANDLE handle1024, handle2048sha1, handle2048rsa;\n\n\n\nUINT32 passCount = 1;\n\nUINT32 demoDelay = 0;\n\nint debugLevel = 0;\n\nUINT8 indent = 0;\n\n\n\nTSS2_SYS_CONTEXT *sysContext;\n\n\n\nTCTI_SOCKET_CONF rmInterfaceConfig = {\n\n DEFAULT_HOSTNAME,\n\n DEFAULT_RESMGR_TPM_PORT,\n\n DebugPrintfCallback,\n\n DebugPrintBufferCallback,\n\n NULL\n\n};\n", "file_path": "test/tpmclient/tpmclient.cpp", "rank": 77, "score": 20.593002850429254 }, { "content": " TPM2B_PRIVATE outPrivate = { { sizeof( TPM2B_PRIVATE ) - 2, } };\n\n TPM2B_PUBLIC outPublic = { { sizeof( TPM2B_PUBLIC ) - 2, } };\n\n TPM2B_CREATION_DATA creationData = { { sizeof( TPM2B_CREATION_DATA ) - 2, } };\n\n\tTPM2B_DIGEST creationHash = { { sizeof( TPM2B_DIGEST ) - 2, } };\n\n\tTPMT_TK_CREATION creationTicket = { 0, 0, { { sizeof( TPM2B_DIGEST ) - 2, } } };\n\n\n\n TPMS_AUTH_COMMAND *sessionDataArray[1];\n\n TPMS_AUTH_RESPONSE *sessionDataOutArray[1];\n\n\n\n sessionDataArray[0] = &sessionData;\n\n sessionDataOutArray[0] = &sessionDataOut;\n\n\n\n sessionsDataOut.rspAuths = &sessionDataOutArray[0];\n\n sessionsData.cmdAuths = &sessionDataArray[0];\n\n\n\n sessionsDataOut.rspAuthsCount = 1;\n\n\n\n DebugPrintf( NO_PREFIX, \"\\nCREATE, CREATE PRIMARY, and LOAD TESTS:\\n\" );\n\n\n\n inSensitive.t.sensitive.userAuth = loadedSha1KeyAuth;\n", "file_path": "test/tpmclient/tpmclient.cpp", "rank": 78, "score": 20.49705406113036 }, { "content": "\n\n writeData.t.size = sizeof( writeDataString );\n\n memcpy( (void *)&writeData.t.buffer, (void *)&writeDataString,\n\n sizeof( writeDataString ) );\n\n\n\n\n\n // Create NV index with empty auth value.\n\n *(UINT32 *)( (void *)&nvAttributes ) = 0;\n\n nvAttributes.TPMA_NV_AUTHREAD = 1;\n\n nvAttributes.TPMA_NV_AUTHWRITE = 1;\n\n nvAttributes.TPMA_NV_PLATFORMCREATE = 1;\n\n\n\n // No authorization required.\n\n authPolicy.t.size = 0;\n\n nvAuth.t.size = 0;\n\n rval = DefineNvIndex( TPM_RH_PLATFORM, TPM_RS_PW,\n\n &nvAuth, &authPolicy, TPM20_INDEX_TEST1,\n\n TPM_ALG_SHA1, nvAttributes,\n\n sizeof( writeDataString ) );\n\n\n", "file_path": "test/tpmclient/tpmclient.cpp", "rank": 79, "score": 20.45287633428048 }, { "content": " CopySizedByteBuffer( &publicInfo.t.nvPublic.authPolicy.b, &authPolicy->b );\n\n publicInfo.t.nvPublic.dataSize = size;\n\n publicInfo.t.size = sizeof( TPMI_RH_NV_INDEX ) +\n\n sizeof( TPMI_ALG_HASH ) + sizeof( TPMA_NV ) + sizeof( UINT16) +\n\n sizeof( UINT16 );\n\n publicInfo.t.nvPublic.nvIndex = nvIndex;\n\n publicInfo.t.nvPublic.nameAlg = nameAlg;\n\n\n\n // Create the index\n\n rval = Tss2_Sys_NV_DefineSpace( sysContext, authHandle, &sessionsData, auth, &publicInfo, &sessionsDataOut );\n\n\n\n return rval;\n\n}\n\n\n\ntypedef struct {\n\n char name[50];\n\n TPM_RC (*buildPolicyFn )( TSS2_SYS_CONTEXT *sysContext, SESSION *trialPolicySession, TPM2B_DIGEST *policyDigest );\n\n TPM_RC (*createObjectFn )( TSS2_SYS_CONTEXT *sysContext, SESSION **policySession, TPM2B_DIGEST *policyDigest );\n\n TPM_RC (*testPolicyFn )( TSS2_SYS_CONTEXT *sysContext, SESSION *policySession );\n\n} POLICY_TEST_SETUP;\n", "file_path": "test/tpmclient/tpmclient.cpp", "rank": 80, "score": 20.446472996623328 }, { "content": "\n\n // Now undefine the index so that next run will work correctly.\n\n rval = Tss2_Sys_NV_UndefineSpace( sysContext, TPM_RH_PLATFORM, TPM20_INDEX_TEST1, &sessionsData, 0 );\n\n CheckPassed( rval );\n\n}\n\n\n\nTPM2B_PUBLIC inPublic = { { sizeof( TPM2B_PUBLIC ) - 2, } };\n\n\n\nvoid TestCreate(){\n\n UINT32 rval;\n\n TPM2B_SENSITIVE_CREATE inSensitive = { { sizeof( TPM2B_SENSITIVE_CREATE ) - 2, } };\n\n TPM2B_DATA outsideInfo = { { sizeof( TPM2B_DATA ) - 2, } };\n\n TPML_PCR_SELECTION creationPCR;\n\n TPMS_AUTH_COMMAND sessionData;\n\n TPMS_AUTH_RESPONSE sessionDataOut;\n\n TSS2_SYS_CMD_AUTHS sessionsData;\n\n\n\n TSS2_SYS_RSP_AUTHS sessionsDataOut;\n\n\tTPM2B_NAME name = { { sizeof( TPM2B_NAME ) - 2, } };\n\n\tTPM2B_NAME name1 = { { sizeof( TPM2B_NAME ) - 2, } };\n", "file_path": "test/tpmclient/tpmclient.cpp", "rank": 81, "score": 20.442432409706278 }, { "content": " outPublic.t.size = 0;\n\n creationData.t.size = 0;\n\n creationPCR.count = 0;\n\n //outPublic.t.publicArea.authPolicy.t.size = sizeof( TPM2B_DIGEST ) - 2;\n\n //outPublic.t.publicArea.unique.keyedHash.t.size = sizeof( TPM2B_DIGEST ) - 2;\n\n //INIT_SIMPLE_TPM2B_SIZE( creationHash );\n\n //INIT_SIMPLE_TPM2B_SIZE( name );\n\n rval = Tss2_Sys_CreatePrimary( sysContext, TPM_RH_NULL, &sessionsData, &inSensitive, &inPublic,\n\n &outsideInfo, &creationPCR, &handle2048rsa, &outPublic, &creationData, &creationHash,\n\n &creationTicket, &name, &sessionsDataOut );\n\n CheckPassed( rval );\n\n\n\n printf( \"\\nNew key successfully created (RSA 2048). Handle: 0x%8.8x\\n\",\n\n handle2048rsa );\n\n\n\n rval = Tss2_Sys_ContextSave(sysContext, handle2048rsa, &context);\n\n CheckPassed(rval);\n\n\n\n rval = Tss2_Sys_ContextLoad(sysContext, &context, &symHandle);\n\n CheckPassed(rval);\n", "file_path": "test/tpmtest/tpmtest.cpp", "rank": 82, "score": 20.16878952894868 }, { "content": " }\n\n}\n\nvoid PrintCreateTestDescription()\n\n{\n\n printf(\" CreatePrimary Case(primaryHandle:TPM_RH_PLATFORM,authArray:{1,{sessionHandle:TPM_RS_PW}},outPublic.t.size:0xff,creationData.t.size:0):Failed(0x8000b)\\n\"\n\n \" CreatePrimary Case(primaryHandle:TPM_RH_PLATFORM,authArray:{1,{sessionHandle:TPM_RS_PW}},outPublic.t.size:0,creationData.t.size:0xff):Failed(0x8000b)\\n\"\n\n \" CreatePrimary Case(primaryHandle:TPM_RH_PLATFORM,authArray:{1,{sessionHandle:TPM_RS_PW}},outPublic.t.size:0,creationData.t.size:0):Passed\\n\"\n\n \" Create Case(parentHandle:handle2048rsa,authArray:{1,{sessionHandle:TPM_RS_PW,hmac:{2,{0x00,0xff}}}}):Passed\\n\"\n\n \" Load Case(parentHandle:handle2048rsa,authArray:{1,{sessionHandle:TPM_RS_PW,hmac:{2,{0x00,0xff}}}},&outPrivate, &outPublic):Passed\\n\"\n\n \" HandleToNameFunctionPtr Case(loadedSha1KeyHandle,name1):Passed\\n\"\n\n \" CompareTPM2B Case(name.b,name1.b):Passed\\n\");\n\n}\n\nvoid PrintNVTestDescription()\n\n{\n\n printf(\" NV_Read Case(authHandle:TPM_RH_PLATFORM,nvIndex:0x1500015,Size:32,authArray:{1,{TPM_RS_PW}}):Failed(0x28B)\\n\"\n\n \" NV_DefineSpace Case(authHandle:TPM_RH_PLATFORM,nvAuth:{20,{0,...19}},publicInfo:{nvIndex:0x1500015,\"\n\n \"authPolicy:{0},attribute:0x40014001}):Passed\\n\"\n\n \" NV_ReadPublic Case(nvIndex:0x1500015,nvPublic:0):Passed\\n\"\n\n \" NV_Read Case(auHandle:TPM_RH_PLATFORM,nvIndex:0x1500015,dataSize:32):Failed(0x14A)\\n\"\n\n \" NV_DefineSpace Case(authHandle:TPM_RH_PLATFORM,nvAuth:{20,{0,...19}},publicInfo:{nvIndex:0x1500015,\"\n", "file_path": "test/tpmtest/tpmtest.cpp", "rank": 83, "score": 20.16533728660592 }, { "content": " rval = tctiSendBytes( tctiContext, TCTI_CONTEXT_INTEL->tpmSock, (unsigned char *)&tpmSendCommand, 4 );\n\n if( rval != TSS2_RC_SUCCESS )\n\n goto returnFromSocketSendTpmCommand;\n\n\n\n // Send the locality\n\n locality = (UINT8)( (TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.locality;\n\n rval = tctiSendBytes( tctiContext, TCTI_CONTEXT_INTEL->tpmSock, (unsigned char *)&locality, 1 );\n\n if( rval != TSS2_RC_SUCCESS )\n\n goto returnFromSocketSendTpmCommand;\n\n\n\n#ifdef DEBUG\n\n if( ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext )->status.debugMsgEnabled == 1 )\n\n {\n\n TCTI_LOG( tctiContext, rmPrefix, \"Locality = %d\", ( (TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.locality );\n\n }\n\n#endif\n\n\n\n // Send number of bytes.\n\n cnt1 = cnt;\n\n cnt = CHANGE_ENDIAN_DWORD(cnt);\n", "file_path": "tcti/tcti_socket.cpp", "rank": 84, "score": 19.884049674359552 }, { "content": "// TCTI_LOG( tctiContext, NO_PREFIX, \"%s sent cancel OFF command:\\n\", interfaceName );\n\n }\n\n\n\nretSocketReceiveTpmResponse:\n\n if( rval == TSS2_RC_SUCCESS &&\n\n\t\tresponse_buffer != NULL )\n\n {\n\n ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->previousStage = TCTI_STAGE_RECEIVE_RESPONSE;\n\n }\n\n\n\n return rval;\n\n}\n\n\n\n#ifdef __cplusplus\n\n}\n\n#endif\n\n\n\n#define HOSTNAME_LENGTH 200\n\n#define PORT_LENGTH 4\n\n\n", "file_path": "tcti/tcti_socket.cpp", "rank": 85, "score": 19.81422695392105 }, { "content": " sessionsData.cmdAuthsCount = 1;\n\n sessionsData.cmdAuths[0] = &sessionData;\n\n\n\n printf( \"\\nVERIFICATION on PUBLIC LOADED KEY TESTS:\\n\" );\n\n\n\n outPublic.t.size = 0;\n\n creationData.t.size = 0;\n\n rval = Tss2_Sys_CreatePrimary( sysContext, TPM_RH_OWNER, &sessionsData, &inSensitive, &inPublic,\n\n &outsideInfo, &creationPCR, &handle2048rsa, &outPublic, &creationData, &creationHash,\n\n &creationTicket, &name, &sessionsDataOut );\n\n CheckPassed( rval );\n\n\n\n printf( \"\\nNew key successfully created in owner hierarchy (RSA 2048). Handle: 0x%8.8x\\n\",\n\n handle2048rsa );\n\n printf( \"Name of created primary key: \" );\n\n PrintSizedBuffer( (TPM2B *)&name );\n\n\n\n outPublic.t.size = 0;\n\n creationData.t.size = sizeof( TPM2B_CREATION_DATA ) - 2;\n\n outPublic.t.publicArea.authPolicy.t.size = sizeof( TPM2B_DIGEST ) - 2;\n", "file_path": "test/tpmtest/tpmtest.cpp", "rank": 86, "score": 19.69070732874482 }, { "content": " if( tpmCmdServer )\n\n {\n\n sock = TCTI_CONTEXT_INTEL->tpmSock;\n\n }\n\n else\n\n {\n\n sock = TCTI_CONTEXT_INTEL->otherSock;\n\n }\n\n\n\n tpmSendCommand = CHANGE_ENDIAN_DWORD(tpmSendCommand);\n\n rval = tctiSendBytes( tctiContext, sock, (char unsigned *)&tpmSendCommand, 4 );\n\n\n\n return( rval );\n\n}\n\n\n\nTSS2_RC SocketSendTpmCommand(\n\n TSS2_TCTI_CONTEXT *tctiContext, /* in */\n\n size_t command_size, /* in */\n\n uint8_t *command_buffer /* in */\n\n )\n", "file_path": "tcti/tcti_socket.cpp", "rank": 87, "score": 19.617609749982677 }, { "content": " const char sensitiveData[] = \"this is sensitive\";\n\n\n\n// printf( \"\\nUNSEAL TEST :\\n\" );\n\n\n\n sessionData.sessionHandle = TPM_RS_PW;\n\n\n\n // Init nonce.\n\n sessionData.nonce.t.size = 0;\n\n\n\n sessionData.hmac.t.size = 2;\n\n sessionData.hmac.t.buffer[0] = 0x00;\n\n sessionData.hmac.t.buffer[1] = 0xff;\n\n\n\n // Init session attributes\n\n *( (UINT8 *)((void *)&sessionData.sessionAttributes ) ) = 0;\n\n\n\n inSensitive.t.sensitive.userAuth.t.size = sizeof( authStr ) - 1;\n\n memcpy( &( inSensitive.t.sensitive.userAuth.t.buffer[0] ), authStr, sizeof( authStr ) - 1 );\n\n inSensitive.t.sensitive.data.t.size = sizeof( sensitiveData ) - 1;\n\n memcpy( &( inSensitive.t.sensitive.data.t.buffer[0] ), sensitiveData, sizeof( sensitiveData ) - 1 );\n", "file_path": "test/tpmtest/tpmtest.cpp", "rank": 88, "score": 19.614718056002335 }, { "content": "TPM_CC currentCommandCode;\n\nTPM_CC *currentCommandCodePtr = &currentCommandCode;\n\n\n\n//----\n\n//char errorString[200];\n\n//----\n\n\n\n//+++\n\n#define errorStringSize 200\n\nchar errorString[errorStringSize];\n\n\n\nUINT8 simulator = 1;\n\n//+++\n\n\n\nUINT32 tpmMaxResponseLen = TPMBUF_LEN;\n\n\n\nUINT8 pcrAfterExtend[20];\n\nTPM_HANDLE loadedRsaKeyHandle;\n\nTPM_HANDLE loadedSha1KeyHandle;\n\n\n", "file_path": "test/tpmtest/tpmtest.cpp", "rank": 89, "score": 19.60744659449611 }, { "content": " TPM2B_NAME name;\n\n TPM2B_NAME qualifiedName;\n\n UINT8 commandCode[4];\n\n size_t\t\t\t\trpBufferUsedSize;\n\n\tconst uint8_t \t\t*rpBuffer;\n\n\tconst uint8_t \t\tgoodRpBuffer[] = { 0x01, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,\n\n 0x01, 0x00, 0x00, 0x01, 0x11, 0x00, 0x00, 0x00,\n\n\t\t\t\t\t\t\t\t\t\t 0x40 };\n\n TPMI_YES_NO moreData;\n\n TPMS_CAPABILITY_DATA\tcapabilityData;\n\n int rpBufferError = 0;\n\n unsigned int i;\n\n UINT32 savedRspSize;\n\n\n\n DebugPrintf( NO_PREFIX, \"\\nSAPI API TESTS:\\n\" );\n\n\n\n //\n\n // First test the one-call interface.\n\n //\n\n rval = Tss2_Sys_GetTestResult( sysContext, 0, &outData, &testResult, 0 );\n", "file_path": "test/tpmclient/tpmclient.cpp", "rank": 90, "score": 19.55135387712727 }, { "content": " sessionData.nonce.t.size = 0;\n\n\n\n // init hmac\n\n sessionData.hmac.t.size = 2;\n\n sessionData.hmac.t.buffer[0] = 0x00;\n\n sessionData.hmac.t.buffer[1] = 0xff;\n\n\n\n // Init session attributes\n\n *( (UINT8 *)((void *)&sessionData.sessionAttributes ) ) = 0;\n\n\n\n qualifyingData.t.size = sizeof( qualDataString );\n\n memcpy( &( qualifyingData.t.buffer[0] ), qualDataString, sizeof( qualDataString ) );\n\n\n\n inScheme.scheme = TPM_ALG_NULL;\n\n\n\n pcrSelection.count = 1;\n\n pcrSelection.pcrSelections[0].hash = TPM_ALG_SHA1;\n\n pcrSelection.pcrSelections[0].sizeofSelect = 3;\n\n\n\n // Clear out PCR select bit field\n", "file_path": "test/tpmclient/tpmclient.cpp", "rank": 91, "score": 19.398018350844623 }, { "content": " sessionData.nonce.t.size = 0;\n\n\n\n // init hmac\n\n sessionData.hmac.t.size = 0;\n\n\n\n // Init session attributes\n\n *( (UINT8 *)((void *)&sessionData.sessionAttributes ) ) = 0;\n\n\n\n sessionsData.cmdAuthsCount = 1;\n\n sessionsData.cmdAuths[0] = &sessionData;\n\n\n\n inPublic.t.publicArea.parameters.rsaDetail.keyBits = 2048;\n\n\n\n // Do SAPI test for non-zero sized outPublic\n\n outPublic.t.size = 0xff;\n\n creationData.t.size = 0;\n\n INIT_SIMPLE_TPM2B_SIZE( creationHash );\n\n INIT_SIMPLE_TPM2B_SIZE( name );\n\n rval = Tss2_Sys_CreatePrimary( sysContext, TPM_RH_OWNER, &sessionsData, &inSensitive, &inPublic,\n\n &outsideInfo, &creationPCR, &handle2048rsa, &outPublic, &creationData, &creationHash,\n", "file_path": "test/tpmclient/tpmclient.cpp", "rank": 92, "score": 19.322056245939347 }, { "content": "\n\n // first way is to use as command parameter.\n\n *(UINT8 *)( (void *)&locality ) = 0;\n\n locality.TPM_LOC_THREE = 1;\n\n rval = Tss2_Sys_PolicyLocality( sysContext, badSessionHandle, 0, locality, 0 );\n\n CheckFailed( rval, TSS2_RESMGRTPM_ERROR_LEVEL + TPM_RC_HANDLE + ( 1 << 8 ) );\n\n\n\n // Second way is to use as handle in session area.\n\n rval = Tss2_Sys_PolicyLocality( sysContext, sessions[0]->sessionHandle, &sessionsDataIn, locality, 0 );\n\n CheckFailed( rval, TSS2_RESMGRTPM_ERROR_LEVEL + TPM_RC_VALUE + TPM_RC_S + ( 1 << 8 ) );\n\n\n\n // clean up the sessions that I don't want here.\n\n#ifdef DEBUG_GAP_HANDLING\n\n for( i = 0; i < ( debugMaxActiveSessions*3); i++ )\n\n#else\n\n for( i = 0; i < ( sizeof(sessions) / sizeof (SESSION *)); i++ )\n\n#endif\n\n {\n\n// DebugPrintf( NO_PREFIX, \"i(2) = 0x%4.4x\\n\", i );\n\n rval = Tss2_Sys_FlushContext( sysContext, sessions[i]->sessionHandle );\n", "file_path": "test/tpmclient/tpmclient.cpp", "rank": 93, "score": 19.321718790589944 }, { "content": " sessionData.hmac.t.size = 2;\n\n sessionData.hmac.t.buffer[0] = 0x00;\n\n sessionData.hmac.t.buffer[1] = 0xff;\n\n\n\n // Init session attributes\n\n *( (UINT8 *)((void *)&sessionData.sessionAttributes ) ) = 0;\n\n\n\n inSensitive.t.sensitive.userAuth.t.size = sizeof( authStr ) - 1;\n\n memcpy( &( inSensitive.t.sensitive.userAuth.t.buffer[0] ), authStr, sizeof( authStr ) - 1 );\n\n inSensitive.t.sensitive.data.t.size = sizeof( sensitiveData ) - 1;\n\n memcpy( &( inSensitive.t.sensitive.data.t.buffer[0] ), sensitiveData, sizeof( sensitiveData ) - 1 );\n\n\n\n inPublic.t.publicArea.authPolicy.t.size = 0;\n\n\n\n inPublic.t.publicArea.unique.keyedHash.t.size = 0;\n\n\n\n outsideInfo.t.size = 0;\n\n creationPCR.count = 0;\n\n\n\n inPublic.t.publicArea.type = TPM_ALG_KEYEDHASH;\n", "file_path": "test/tpmtest/tpmtest.cpp", "rank": 94, "score": 19.257582434132676 }, { "content": " sessionData.hmac.t.buffer[1] = 0xff;\n\n\n\n // Init session attributes\n\n *( (UINT8 *)((void *)&sessionData.sessionAttributes ) ) = 0;\n\n\n\n inSensitive.t.sensitive.userAuth.t.size = sizeof( authStr ) - 1;\n\n memcpy( &( inSensitive.t.sensitive.userAuth.t.buffer[0] ), authStr, sizeof( authStr ) - 1 );\n\n inSensitive.t.sensitive.data.t.size = sizeof( sensitiveData ) - 1;\n\n memcpy( &( inSensitive.t.sensitive.data.t.buffer[0] ), sensitiveData, sizeof( sensitiveData ) - 1 );\n\n\n\n inPublic.t.publicArea.authPolicy.t.size = 0;\n\n\n\n inPublic.t.publicArea.unique.keyedHash.t.size = 0;\n\n\n\n outsideInfo.t.size = 0;\n\n creationPCR.count = 0;\n\n\n\n inPublic.t.publicArea.type = TPM_ALG_KEYEDHASH;\n\n inPublic.t.publicArea.nameAlg = TPM_ALG_SHA1;\n\n\n", "file_path": "test/tpmclient/tpmclient.cpp", "rank": 95, "score": 19.18903555876977 }, { "content": " sizeof( TPMI_ALG_HASH ) + sizeof( TPMA_NV ) + sizeof( UINT16) +\n\n sizeof( UINT16 );\n\n publicInfo.t.nvPublic.nvIndex = nvIndex;\n\n publicInfo.t.nvPublic.nameAlg = nameAlg;\n\n\n\n // Create the index\n\n rval = Tss2_Sys_NV_DefineSpace( sysContext, authHandle, &sessionsData, auth, &publicInfo, &sessionsDataOut );\n\n\n\n return rval;\n\n}\n\n\n\ntypedef struct {\n\n char name[50];\n\n TPM_RC (*buildPolicyFn )( TSS2_SYS_CONTEXT *sysContext, SESSION *trialPolicySession, TPM2B_DIGEST *policyDigest );\n\n TPM_RC (*createObjectFn )( TSS2_SYS_CONTEXT *sysContext, SESSION **policySession, TPM2B_DIGEST *policyDigest );\n\n TPM_RC (*testPolicyFn )( TSS2_SYS_CONTEXT *sysContext, SESSION *policySession );\n\n} POLICY_TEST_SETUP;\n\n\n\nTPM_RC BuildPolicy( TSS2_SYS_CONTEXT *sysContext, SESSION **policySession,\n\n TPM_RC (*buildPolicyFn )( TSS2_SYS_CONTEXT *sysContext, SESSION *policySession, TPM2B_DIGEST *policyDigest ),\n", "file_path": "test/tpmtest/tpmtest.cpp", "rank": 96, "score": 19.119447482583155 }, { "content": " &outPrivate, &outPublic, &creationData,\n\n &creationHash, &creationTicket, &sessionsDataOut );\n\n CheckPassed( rval );\n\n printf( \"Name of created key: \" );\n\n PrintSizedBuffer( (TPM2B *)&name );\n\n\n\n rval = Tss2_Sys_Load ( sysContext, handle2048rsa, &sessionsData, &outPrivate, &outPublic,\n\n &loadedSha1KeyHandle, &name, &sessionsDataOut);\n\n CheckPassed( rval );\n\n\n\n printf( \"Name of loading key: \" );\n\n PrintSizedBuffer( (TPM2B *)&name );\n\n\n\n printf( \"\\nLoaded key handle: %8.8x\\n\", loadedSha1KeyHandle );\n\n\n\n char buffer1contents[] = \"test\";\n\n TPMT_RSA_DECRYPT inScheme;\n\n TPM2B_PUBLIC_KEY_RSA message = { { sizeof(TPM2B_PUBLIC_KEY_RSA)-2, } };\n\n TPM2B_PUBLIC_KEY_RSA messageOut = { { sizeof(TPM2B_PUBLIC_KEY_RSA)-2, } };\n\n TPM2B_PUBLIC_KEY_RSA outData = { { sizeof(TPM2B_PUBLIC_KEY_RSA)-2, } };\n", "file_path": "test/tpmtest/tpmtest.cpp", "rank": 97, "score": 19.08778264231395 }, { "content": " inPublic.t.publicArea.parameters.rsaDetail.symmetric.mode.aes = TPM_ALG_CFB;\n\n inPublic.t.publicArea.parameters.rsaDetail.scheme.scheme = TPM_ALG_NULL;\n\n inPublic.t.publicArea.parameters.rsaDetail.keyBits = 2048;\n\n inPublic.t.publicArea.parameters.rsaDetail.exponent = 0;\n\n\n\n inPublic.t.publicArea.unique.rsa.t.size = 0;\n\n\n\n outsideInfo.t.size = 0;\n\n\n\n // This one should fail, because a different context is trying to use the primary object.\n\n outPublic.t.size = 0;\n\n creationData.t.size = 0;\n\n INIT_SIMPLE_TPM2B_SIZE( outPrivate );\n\n INIT_SIMPLE_TPM2B_SIZE( creationHash );\n\n rval = Tss2_Sys_Create( otherSysContext, handle2048rsa, &sessionsData, &inSensitive, &inPublic,\n\n &outsideInfo, &creationPCR,\n\n &outPrivate, &outPublic, &creationData,\n\n &creationHash, &creationTicket, &sessionsDataOut );\n\n CheckFailed( rval, TSS2_RESMGR_UNOWNED_HANDLE );\n\n\n", "file_path": "test/tpmtest/tpmtest.cpp", "rank": 98, "score": 19.010453740920124 }, { "content": " outPublic.t.size = 0;\n\n creationData.t.size = 0;\n\n INIT_SIMPLE_TPM2B_SIZE( creationHash );\n\n INIT_SIMPLE_TPM2B_SIZE( name );\n\n rval = Tss2_Sys_CreatePrimary( sysContext, TPM_RH_NULL, &sessionsData, &inSensitive, &inPublic,\n\n &outsideInfo, &creationPCR, &handle2048rsa, &outPublic, &creationData, &creationHash,\n\n &creationTicket, &name, &sessionsDataOut );\n\n CheckPassed( rval );\n\n\n\n printf( \"\\nNew key successfully created in NULL hierarchy (RSA 2048). Handle: 0x%8.8x\\n\",\n\n handle2048rsa );\n\n\n\n sessionData.hmac.t.size = 2;\n\n sessionData.hmac.t.buffer[0] = 0x00;\n\n sessionData.hmac.t.buffer[1] = 0xff;\n\n\n\n inPublic.t.publicArea.type = TPM_ALG_KEYEDHASH;\n\n inPublic.t.publicArea.objectAttributes.decrypt = 0;\n\n inPublic.t.publicArea.objectAttributes.sign = 1;\n\n\n", "file_path": "test/tpmtest/tpmtest.cpp", "rank": 99, "score": 18.883660367005568 } ]
C++
src/add-ons/media/media-add-ons/dvb/DVBCard.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #include <sys/ioctl.h> #include <errno.h> #include <OS.h> #include "DVBCard.h" DVBCard::DVBCard(const char *path) : fInitStatus(B_OK) , fDev(-1) { printf("DVBCard opening %s\n", path); fDev = open(path, O_RDWR); if (fDev < 0) { printf("DVBCard opening %s failed\n", path); fInitStatus = B_ERROR; return; } dvb_frequency_info_t info; if (do_ioctl(fDev, DVB_GET_FREQUENCY_INFO, &info) < 0) { printf("DVB_GET_FREQUENCY_INFO failed with error %s\n", strerror(errno)); } fFreqMin = info.frequency_min; fFreqMax = info.frequency_max; fFreqStep = info.frequency_step; fCaptureActive = false; } DVBCard::~DVBCard() { if (fDev > 0) close(fDev); } status_t DVBCard::InitCheck() { return fInitStatus; } status_t DVBCard::GetCardType(dvb_type_t *type) { dvb_interface_info_t info; if (do_ioctl(fDev, DVB_GET_INTERFACE_INFO, &info) < 0) { printf("DVB_GET_INTERFACE_INFO failed with error %s\n", strerror(errno)); return errno; } if (info.version < 1) { printf("DVBCard::GetCardInfo wrong API version\n"); return B_ERROR; } *type = info.type; return B_OK; } status_t DVBCard::GetCardInfo(char *_name, int max_name_len, char *_info, int max_info_len) { dvb_interface_info_t info; if (do_ioctl(fDev, DVB_GET_INTERFACE_INFO, &info) < 0) { printf("DVB_GET_INTERFACE_INFO failed with error %s\n", strerror(errno)); return errno; } strcpy(_name, info.name); strcpy(_info, info.info); if (info.version < 1) { printf("DVBCard::GetCardInfo wrong API version\n"); return B_ERROR; } return B_OK; } status_t DVBCard::SetTuningParameter(const dvb_tuning_parameters_t& param) { if (fDev < 0) return B_NO_INIT; printf("DVBCard::SetTuningParameter:\n"); params = param; if (ioctl(fDev, DVB_SET_TUNING_PARAMETERS, (void *)(&param)) < 0) { printf("DVB_SET_TUNING_PARAMETERS failed with error %s\n", strerror(errno)); return errno; } dvb_status_t status; bigtime_t start = system_time(); bool has_lock = false; bool has_signal = false; bool has_carrier = false; do { if (do_ioctl(fDev, DVB_GET_STATUS, &status) < 0) { printf("DVB_GET_STATUS failed with error %s\n", strerror(errno)); return errno; } if (!has_signal && status & DVB_STATUS_SIGNAL) { has_signal = true; printf("got signal after %.6f\n", (system_time() - start) / 1e6); } if (!has_carrier && status & DVB_STATUS_CARRIER) { has_carrier = true; printf("got carrier after %.6f\n", (system_time() - start) / 1e6); } if (!has_lock && status & DVB_STATUS_LOCK) { has_lock = true; printf("got lock after %.6f\n", (system_time() - start) / 1e6); } if ((status & (DVB_STATUS_SIGNAL|DVB_STATUS_CARRIER|DVB_STATUS_LOCK)) == (DVB_STATUS_SIGNAL|DVB_STATUS_CARRIER|DVB_STATUS_LOCK)) break; snooze(25000); } while ((system_time() - start) < 5000000); if ((status & (DVB_STATUS_SIGNAL|DVB_STATUS_CARRIER|DVB_STATUS_LOCK)) != (DVB_STATUS_SIGNAL|DVB_STATUS_CARRIER|DVB_STATUS_LOCK)) { printf("DVB tuning failed! need these status flags: DVB_STATUS_SIGNAL, DVB_STATUS_CARRIER, DVB_STATUS_LOCK\n"); return B_ERROR; } return B_OK; } status_t DVBCard::GetTuningParameter(dvb_tuning_parameters_t *param) { *param = params; return B_OK; } status_t DVBCard::GetSignalInfo(uint32 *ss, uint32 *ber, uint32 *snr) { if (do_ioctl(fDev, DVB_GET_SS, ss) < 0) { printf("DVB_GET_SS failed with error %s\n", strerror(errno)); return errno; } if (do_ioctl(fDev, DVB_GET_BER, ber) < 0) { printf("DVB_GET_BER failed with error %s\n", strerror(errno)); return errno; } if (do_ioctl(fDev, DVB_GET_SNR, snr) < 0) { printf("DVB_GET_SNR failed with error %s\n", strerror(errno)); return errno; } printf("ss %08lx, ber %08lx, snr %08lx\n", *ss, *ber, *snr); printf("ss %lu%%, ber %lu%%, snr %lu%%\n", *ss / (0xffffffff / 100), *ber / (0xffffffff / 100), *snr / (0xffffffff / 100)); return B_OK; } status_t DVBCard::CaptureStart() { printf("DVBCard::CaptureStart\n"); if (fCaptureActive) { printf("CaptureStart already called, doing nothing\n"); return B_OK; } if (do_ioctl(fDev, DVB_START_CAPTURE, 0) < 0) { printf("DVB_START_CAPTURE failed with error %s\n", strerror(errno)); return errno; } fCaptureActive = true; return B_OK; } status_t DVBCard::CaptureStop() { printf("DVBCard::CaptureStop\n"); if (!fCaptureActive) { printf("CaptureStop already called, doing nothing\n"); return B_OK; } if (do_ioctl(fDev, DVB_STOP_CAPTURE, 0) < 0) { printf("DVB_STOP_CAPTURE failed with error %s\n", strerror(errno)); return errno; } fCaptureActive = false; return B_OK; } status_t DVBCard::Capture(void **data, size_t *size, bigtime_t *end_time) { dvb_capture_t cap; if (ioctl(fDev, DVB_CAPTURE, &cap) < 0) return errno; *data = cap.data; *size = cap.size; *end_time = cap.end_time; return B_OK; } int DVBCard::do_ioctl(int fDev, ulong op, void *arg) { int res = 0; int i; for (i = 0; i < 20; i++) { res = ioctl(fDev, op, arg); if (res >= 0) break; } if (i != 0) printf("ioctl %lx repeated %d times\n", op, i); return res; }
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #include <sys/ioctl.h> #include <errno.h> #include <OS.h> #include "DVBCard.h" DVBCard::DVBCard(const char *path) : fInitStatus(B_OK) , fDev(-1) { printf("DVBCard opening %s\n", path); fDev = open(path, O_RDWR); if (fDev < 0) { printf("DVBCard opening %s failed\n", path); fInitStatus = B_ERROR; return; } dvb_frequency_info_t info; if (do_ioctl(fDev, DVB_GET_FREQUENCY_INFO, &info) < 0) { printf("DVB_GET_FREQUENCY_INFO failed with error %s\n", strerror(errno)); } fFreqMin = info.frequency_min; fFreqMax = info.frequency_max; fFreqStep = info.frequency_step; fCaptureActive = false; } DVBCard::~DVBCard() { if (fDev > 0) close(fDev); } status_t DVBCard::InitCheck() { return fInitStatus; } status_t DVBCard::GetCardType(dvb_type_t *ty
return B_OK; } int DVBCard::do_ioctl(int fDev, ulong op, void *arg) { int res = 0; int i; for (i = 0; i < 20; i++) { res = ioctl(fDev, op, arg); if (res >= 0) break; } if (i != 0) printf("ioctl %lx repeated %d times\n", op, i); return res; }
pe) { dvb_interface_info_t info; if (do_ioctl(fDev, DVB_GET_INTERFACE_INFO, &info) < 0) { printf("DVB_GET_INTERFACE_INFO failed with error %s\n", strerror(errno)); return errno; } if (info.version < 1) { printf("DVBCard::GetCardInfo wrong API version\n"); return B_ERROR; } *type = info.type; return B_OK; } status_t DVBCard::GetCardInfo(char *_name, int max_name_len, char *_info, int max_info_len) { dvb_interface_info_t info; if (do_ioctl(fDev, DVB_GET_INTERFACE_INFO, &info) < 0) { printf("DVB_GET_INTERFACE_INFO failed with error %s\n", strerror(errno)); return errno; } strcpy(_name, info.name); strcpy(_info, info.info); if (info.version < 1) { printf("DVBCard::GetCardInfo wrong API version\n"); return B_ERROR; } return B_OK; } status_t DVBCard::SetTuningParameter(const dvb_tuning_parameters_t& param) { if (fDev < 0) return B_NO_INIT; printf("DVBCard::SetTuningParameter:\n"); params = param; if (ioctl(fDev, DVB_SET_TUNING_PARAMETERS, (void *)(&param)) < 0) { printf("DVB_SET_TUNING_PARAMETERS failed with error %s\n", strerror(errno)); return errno; } dvb_status_t status; bigtime_t start = system_time(); bool has_lock = false; bool has_signal = false; bool has_carrier = false; do { if (do_ioctl(fDev, DVB_GET_STATUS, &status) < 0) { printf("DVB_GET_STATUS failed with error %s\n", strerror(errno)); return errno; } if (!has_signal && status & DVB_STATUS_SIGNAL) { has_signal = true; printf("got signal after %.6f\n", (system_time() - start) / 1e6); } if (!has_carrier && status & DVB_STATUS_CARRIER) { has_carrier = true; printf("got carrier after %.6f\n", (system_time() - start) / 1e6); } if (!has_lock && status & DVB_STATUS_LOCK) { has_lock = true; printf("got lock after %.6f\n", (system_time() - start) / 1e6); } if ((status & (DVB_STATUS_SIGNAL|DVB_STATUS_CARRIER|DVB_STATUS_LOCK)) == (DVB_STATUS_SIGNAL|DVB_STATUS_CARRIER|DVB_STATUS_LOCK)) break; snooze(25000); } while ((system_time() - start) < 5000000); if ((status & (DVB_STATUS_SIGNAL|DVB_STATUS_CARRIER|DVB_STATUS_LOCK)) != (DVB_STATUS_SIGNAL|DVB_STATUS_CARRIER|DVB_STATUS_LOCK)) { printf("DVB tuning failed! need these status flags: DVB_STATUS_SIGNAL, DVB_STATUS_CARRIER, DVB_STATUS_LOCK\n"); return B_ERROR; } return B_OK; } status_t DVBCard::GetTuningParameter(dvb_tuning_parameters_t *param) { *param = params; return B_OK; } status_t DVBCard::GetSignalInfo(uint32 *ss, uint32 *ber, uint32 *snr) { if (do_ioctl(fDev, DVB_GET_SS, ss) < 0) { printf("DVB_GET_SS failed with error %s\n", strerror(errno)); return errno; } if (do_ioctl(fDev, DVB_GET_BER, ber) < 0) { printf("DVB_GET_BER failed with error %s\n", strerror(errno)); return errno; } if (do_ioctl(fDev, DVB_GET_SNR, snr) < 0) { printf("DVB_GET_SNR failed with error %s\n", strerror(errno)); return errno; } printf("ss %08lx, ber %08lx, snr %08lx\n", *ss, *ber, *snr); printf("ss %lu%%, ber %lu%%, snr %lu%%\n", *ss / (0xffffffff / 100), *ber / (0xffffffff / 100), *snr / (0xffffffff / 100)); return B_OK; } status_t DVBCard::CaptureStart() { printf("DVBCard::CaptureStart\n"); if (fCaptureActive) { printf("CaptureStart already called, doing nothing\n"); return B_OK; } if (do_ioctl(fDev, DVB_START_CAPTURE, 0) < 0) { printf("DVB_START_CAPTURE failed with error %s\n", strerror(errno)); return errno; } fCaptureActive = true; return B_OK; } status_t DVBCard::CaptureStop() { printf("DVBCard::CaptureStop\n"); if (!fCaptureActive) { printf("CaptureStop already called, doing nothing\n"); return B_OK; } if (do_ioctl(fDev, DVB_STOP_CAPTURE, 0) < 0) { printf("DVB_STOP_CAPTURE failed with error %s\n", strerror(errno)); return errno; } fCaptureActive = false; return B_OK; } status_t DVBCard::Capture(void **data, size_t *size, bigtime_t *end_time) { dvb_capture_t cap; if (ioctl(fDev, DVB_CAPTURE, &cap) < 0) return errno; *data = cap.data; *size = cap.size; *end_time = cap.end_time;
random
[]
C++
cpdp/src/v20190820/model/CreateInvoiceItem.cpp
li5ch/tencentcloud-sdk-cpp
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
#include <tencentcloud/cpdp/v20190820/model/CreateInvoiceItem.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Cpdp::V20190820::Model; using namespace rapidjson; using namespace std; CreateInvoiceItem::CreateInvoiceItem() : m_nameHasBeenSet(false), m_taxCodeHasBeenSet(false), m_totalPriceHasBeenSet(false), m_taxRateHasBeenSet(false), m_taxAmountHasBeenSet(false), m_taxTypeHasBeenSet(false), m_modelsHasBeenSet(false), m_unitHasBeenSet(false), m_totalHasBeenSet(false), m_priceHasBeenSet(false), m_discountHasBeenSet(false), m_preferentialPolicyFlagHasBeenSet(false), m_zeroTaxFlagHasBeenSet(false), m_vatSpecialManagementHasBeenSet(false) { } CoreInternalOutcome CreateInvoiceItem::Deserialize(const Value &value) { string requestId = ""; if (value.HasMember("Name") && !value["Name"].IsNull()) { if (!value["Name"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.Name` IsString=false incorrectly").SetRequestId(requestId)); } m_name = string(value["Name"].GetString()); m_nameHasBeenSet = true; } if (value.HasMember("TaxCode") && !value["TaxCode"].IsNull()) { if (!value["TaxCode"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.TaxCode` IsString=false incorrectly").SetRequestId(requestId)); } m_taxCode = string(value["TaxCode"].GetString()); m_taxCodeHasBeenSet = true; } if (value.HasMember("TotalPrice") && !value["TotalPrice"].IsNull()) { if (!value["TotalPrice"].IsInt64()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.TotalPrice` IsInt64=false incorrectly").SetRequestId(requestId)); } m_totalPrice = value["TotalPrice"].GetInt64(); m_totalPriceHasBeenSet = true; } if (value.HasMember("TaxRate") && !value["TaxRate"].IsNull()) { if (!value["TaxRate"].IsInt64()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.TaxRate` IsInt64=false incorrectly").SetRequestId(requestId)); } m_taxRate = value["TaxRate"].GetInt64(); m_taxRateHasBeenSet = true; } if (value.HasMember("TaxAmount") && !value["TaxAmount"].IsNull()) { if (!value["TaxAmount"].IsInt64()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.TaxAmount` IsInt64=false incorrectly").SetRequestId(requestId)); } m_taxAmount = value["TaxAmount"].GetInt64(); m_taxAmountHasBeenSet = true; } if (value.HasMember("TaxType") && !value["TaxType"].IsNull()) { if (!value["TaxType"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.TaxType` IsString=false incorrectly").SetRequestId(requestId)); } m_taxType = string(value["TaxType"].GetString()); m_taxTypeHasBeenSet = true; } if (value.HasMember("Models") && !value["Models"].IsNull()) { if (!value["Models"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.Models` IsString=false incorrectly").SetRequestId(requestId)); } m_models = string(value["Models"].GetString()); m_modelsHasBeenSet = true; } if (value.HasMember("Unit") && !value["Unit"].IsNull()) { if (!value["Unit"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.Unit` IsString=false incorrectly").SetRequestId(requestId)); } m_unit = string(value["Unit"].GetString()); m_unitHasBeenSet = true; } if (value.HasMember("Total") && !value["Total"].IsNull()) { if (!value["Total"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.Total` IsString=false incorrectly").SetRequestId(requestId)); } m_total = string(value["Total"].GetString()); m_totalHasBeenSet = true; } if (value.HasMember("Price") && !value["Price"].IsNull()) { if (!value["Price"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.Price` IsString=false incorrectly").SetRequestId(requestId)); } m_price = string(value["Price"].GetString()); m_priceHasBeenSet = true; } if (value.HasMember("Discount") && !value["Discount"].IsNull()) { if (!value["Discount"].IsInt64()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.Discount` IsInt64=false incorrectly").SetRequestId(requestId)); } m_discount = value["Discount"].GetInt64(); m_discountHasBeenSet = true; } if (value.HasMember("PreferentialPolicyFlag") && !value["PreferentialPolicyFlag"].IsNull()) { if (!value["PreferentialPolicyFlag"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.PreferentialPolicyFlag` IsString=false incorrectly").SetRequestId(requestId)); } m_preferentialPolicyFlag = string(value["PreferentialPolicyFlag"].GetString()); m_preferentialPolicyFlagHasBeenSet = true; } if (value.HasMember("ZeroTaxFlag") && !value["ZeroTaxFlag"].IsNull()) { if (!value["ZeroTaxFlag"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.ZeroTaxFlag` IsString=false incorrectly").SetRequestId(requestId)); } m_zeroTaxFlag = string(value["ZeroTaxFlag"].GetString()); m_zeroTaxFlagHasBeenSet = true; } if (value.HasMember("VatSpecialManagement") && !value["VatSpecialManagement"].IsNull()) { if (!value["VatSpecialManagement"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.VatSpecialManagement` IsString=false incorrectly").SetRequestId(requestId)); } m_vatSpecialManagement = string(value["VatSpecialManagement"].GetString()); m_vatSpecialManagementHasBeenSet = true; } return CoreInternalOutcome(true); } void CreateInvoiceItem::ToJsonObject(Value &value, Document::AllocatorType& allocator) const { if (m_nameHasBeenSet) { Value iKey(kStringType); string key = "Name"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_name.c_str(), allocator).Move(), allocator); } if (m_taxCodeHasBeenSet) { Value iKey(kStringType); string key = "TaxCode"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_taxCode.c_str(), allocator).Move(), allocator); } if (m_totalPriceHasBeenSet) { Value iKey(kStringType); string key = "TotalPrice"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_totalPrice, allocator); } if (m_taxRateHasBeenSet) { Value iKey(kStringType); string key = "TaxRate"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_taxRate, allocator); } if (m_taxAmountHasBeenSet) { Value iKey(kStringType); string key = "TaxAmount"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_taxAmount, allocator); } if (m_taxTypeHasBeenSet) { Value iKey(kStringType); string key = "TaxType"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_taxType.c_str(), allocator).Move(), allocator); } if (m_modelsHasBeenSet) { Value iKey(kStringType); string key = "Models"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_models.c_str(), allocator).Move(), allocator); } if (m_unitHasBeenSet) { Value iKey(kStringType); string key = "Unit"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_unit.c_str(), allocator).Move(), allocator); } if (m_totalHasBeenSet) { Value iKey(kStringType); string key = "Total"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_total.c_str(), allocator).Move(), allocator); } if (m_priceHasBeenSet) { Value iKey(kStringType); string key = "Price"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_price.c_str(), allocator).Move(), allocator); } if (m_discountHasBeenSet) { Value iKey(kStringType); string key = "Discount"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_discount, allocator); } if (m_preferentialPolicyFlagHasBeenSet) { Value iKey(kStringType); string key = "PreferentialPolicyFlag"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_preferentialPolicyFlag.c_str(), allocator).Move(), allocator); } if (m_zeroTaxFlagHasBeenSet) { Value iKey(kStringType); string key = "ZeroTaxFlag"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_zeroTaxFlag.c_str(), allocator).Move(), allocator); } if (m_vatSpecialManagementHasBeenSet) { Value iKey(kStringType); string key = "VatSpecialManagement"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_vatSpecialManagement.c_str(), allocator).Move(), allocator); } } string CreateInvoiceItem::GetName() const { return m_name; } void CreateInvoiceItem::SetName(const string& _name) { m_name = _name; m_nameHasBeenSet = true; } bool CreateInvoiceItem::NameHasBeenSet() const { return m_nameHasBeenSet; } string CreateInvoiceItem::GetTaxCode() const { return m_taxCode; } void CreateInvoiceItem::SetTaxCode(const string& _taxCode) { m_taxCode = _taxCode; m_taxCodeHasBeenSet = true; } bool CreateInvoiceItem::TaxCodeHasBeenSet() const { return m_taxCodeHasBeenSet; } int64_t CreateInvoiceItem::GetTotalPrice() const { return m_totalPrice; } void CreateInvoiceItem::SetTotalPrice(const int64_t& _totalPrice) { m_totalPrice = _totalPrice; m_totalPriceHasBeenSet = true; } bool CreateInvoiceItem::TotalPriceHasBeenSet() const { return m_totalPriceHasBeenSet; } int64_t CreateInvoiceItem::GetTaxRate() const { return m_taxRate; } void CreateInvoiceItem::SetTaxRate(const int64_t& _taxRate) { m_taxRate = _taxRate; m_taxRateHasBeenSet = true; } bool CreateInvoiceItem::TaxRateHasBeenSet() const { return m_taxRateHasBeenSet; } int64_t CreateInvoiceItem::GetTaxAmount() const { return m_taxAmount; } void CreateInvoiceItem::SetTaxAmount(const int64_t& _taxAmount) { m_taxAmount = _taxAmount; m_taxAmountHasBeenSet = true; } bool CreateInvoiceItem::TaxAmountHasBeenSet() const { return m_taxAmountHasBeenSet; } string CreateInvoiceItem::GetTaxType() const { return m_taxType; } void CreateInvoiceItem::SetTaxType(const string& _taxType) { m_taxType = _taxType; m_taxTypeHasBeenSet = true; } bool CreateInvoiceItem::TaxTypeHasBeenSet() const { return m_taxTypeHasBeenSet; } string CreateInvoiceItem::GetModels() const { return m_models; } void CreateInvoiceItem::SetModels(const string& _models) { m_models = _models; m_modelsHasBeenSet = true; } bool CreateInvoiceItem::ModelsHasBeenSet() const { return m_modelsHasBeenSet; } string CreateInvoiceItem::GetUnit() const { return m_unit; } void CreateInvoiceItem::SetUnit(const string& _unit) { m_unit = _unit; m_unitHasBeenSet = true; } bool CreateInvoiceItem::UnitHasBeenSet() const { return m_unitHasBeenSet; } string CreateInvoiceItem::GetTotal() const { return m_total; } void CreateInvoiceItem::SetTotal(const string& _total) { m_total = _total; m_totalHasBeenSet = true; } bool CreateInvoiceItem::TotalHasBeenSet() const { return m_totalHasBeenSet; } string CreateInvoiceItem::GetPrice() const { return m_price; } void CreateInvoiceItem::SetPrice(const string& _price) { m_price = _price; m_priceHasBeenSet = true; } bool CreateInvoiceItem::PriceHasBeenSet() const { return m_priceHasBeenSet; } int64_t CreateInvoiceItem::GetDiscount() const { return m_discount; } void CreateInvoiceItem::SetDiscount(const int64_t& _discount) { m_discount = _discount; m_discountHasBeenSet = true; } bool CreateInvoiceItem::DiscountHasBeenSet() const { return m_discountHasBeenSet; } string CreateInvoiceItem::GetPreferentialPolicyFlag() const { return m_preferentialPolicyFlag; } void CreateInvoiceItem::SetPreferentialPolicyFlag(const string& _preferentialPolicyFlag) { m_preferentialPolicyFlag = _preferentialPolicyFlag; m_preferentialPolicyFlagHasBeenSet = true; } bool CreateInvoiceItem::PreferentialPolicyFlagHasBeenSet() const { return m_preferentialPolicyFlagHasBeenSet; } string CreateInvoiceItem::GetZeroTaxFlag() const { return m_zeroTaxFlag; } void CreateInvoiceItem::SetZeroTaxFlag(const string& _zeroTaxFlag) { m_zeroTaxFlag = _zeroTaxFlag; m_zeroTaxFlagHasBeenSet = true; } bool CreateInvoiceItem::ZeroTaxFlagHasBeenSet() const { return m_zeroTaxFlagHasBeenSet; } string CreateInvoiceItem::GetVatSpecialManagement() const { return m_vatSpecialManagement; } void CreateInvoiceItem::SetVatSpecialManagement(const string& _vatSpecialManagement) { m_vatSpecialManagement = _vatSpecialManagement; m_vatSpecialManagementHasBeenSet = true; } bool CreateInvoiceItem::VatSpecialManagementHasBeenSet() const { return m_vatSpecialManagementHasBeenSet; }
#include <tencentcloud/cpdp/v20190820/model/CreateInvoiceItem.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Cpdp::V20190820::Model; using namespace rapidjson; using namespace std; CreateInvoiceItem::CreateInvoiceItem() : m_nameHasBeenSet(false), m_taxCodeHasBeenSet(false), m_totalPriceHasBeenSet(false), m_taxRateHasBeenSet(false), m_taxAmountHasBeenSet(false), m_taxTypeHasBeenSet(false), m_modelsHasBeenSet(false), m_unitHasBeenSet(false), m_totalHasBeenSet(false), m_priceHasBeenSet(false), m_discountHasBeenSet(false), m_preferentialPolicyFlagHasBeenSet(false), m_zeroTaxFlagHasBeenSet(false), m_vatSpecialManagementHasBeenSet(false) { }
void CreateInvoiceItem::ToJsonObject(Value &value, Document::AllocatorType& allocator) const { if (m_nameHasBeenSet) { Value iKey(kStringType); string key = "Name"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_name.c_str(), allocator).Move(), allocator); } if (m_taxCodeHasBeenSet) { Value iKey(kStringType); string key = "TaxCode"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_taxCode.c_str(), allocator).Move(), allocator); } if (m_totalPriceHasBeenSet) { Value iKey(kStringType); string key = "TotalPrice"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_totalPrice, allocator); } if (m_taxRateHasBeenSet) { Value iKey(kStringType); string key = "TaxRate"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_taxRate, allocator); } if (m_taxAmountHasBeenSet) { Value iKey(kStringType); string key = "TaxAmount"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_taxAmount, allocator); } if (m_taxTypeHasBeenSet) { Value iKey(kStringType); string key = "TaxType"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_taxType.c_str(), allocator).Move(), allocator); } if (m_modelsHasBeenSet) { Value iKey(kStringType); string key = "Models"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_models.c_str(), allocator).Move(), allocator); } if (m_unitHasBeenSet) { Value iKey(kStringType); string key = "Unit"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_unit.c_str(), allocator).Move(), allocator); } if (m_totalHasBeenSet) { Value iKey(kStringType); string key = "Total"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_total.c_str(), allocator).Move(), allocator); } if (m_priceHasBeenSet) { Value iKey(kStringType); string key = "Price"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_price.c_str(), allocator).Move(), allocator); } if (m_discountHasBeenSet) { Value iKey(kStringType); string key = "Discount"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_discount, allocator); } if (m_preferentialPolicyFlagHasBeenSet) { Value iKey(kStringType); string key = "PreferentialPolicyFlag"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_preferentialPolicyFlag.c_str(), allocator).Move(), allocator); } if (m_zeroTaxFlagHasBeenSet) { Value iKey(kStringType); string key = "ZeroTaxFlag"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_zeroTaxFlag.c_str(), allocator).Move(), allocator); } if (m_vatSpecialManagementHasBeenSet) { Value iKey(kStringType); string key = "VatSpecialManagement"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_vatSpecialManagement.c_str(), allocator).Move(), allocator); } } string CreateInvoiceItem::GetName() const { return m_name; } void CreateInvoiceItem::SetName(const string& _name) { m_name = _name; m_nameHasBeenSet = true; } bool CreateInvoiceItem::NameHasBeenSet() const { return m_nameHasBeenSet; } string CreateInvoiceItem::GetTaxCode() const { return m_taxCode; } void CreateInvoiceItem::SetTaxCode(const string& _taxCode) { m_taxCode = _taxCode; m_taxCodeHasBeenSet = true; } bool CreateInvoiceItem::TaxCodeHasBeenSet() const { return m_taxCodeHasBeenSet; } int64_t CreateInvoiceItem::GetTotalPrice() const { return m_totalPrice; } void CreateInvoiceItem::SetTotalPrice(const int64_t& _totalPrice) { m_totalPrice = _totalPrice; m_totalPriceHasBeenSet = true; } bool CreateInvoiceItem::TotalPriceHasBeenSet() const { return m_totalPriceHasBeenSet; } int64_t CreateInvoiceItem::GetTaxRate() const { return m_taxRate; } void CreateInvoiceItem::SetTaxRate(const int64_t& _taxRate) { m_taxRate = _taxRate; m_taxRateHasBeenSet = true; } bool CreateInvoiceItem::TaxRateHasBeenSet() const { return m_taxRateHasBeenSet; } int64_t CreateInvoiceItem::GetTaxAmount() const { return m_taxAmount; } void CreateInvoiceItem::SetTaxAmount(const int64_t& _taxAmount) { m_taxAmount = _taxAmount; m_taxAmountHasBeenSet = true; } bool CreateInvoiceItem::TaxAmountHasBeenSet() const { return m_taxAmountHasBeenSet; } string CreateInvoiceItem::GetTaxType() const { return m_taxType; } void CreateInvoiceItem::SetTaxType(const string& _taxType) { m_taxType = _taxType; m_taxTypeHasBeenSet = true; } bool CreateInvoiceItem::TaxTypeHasBeenSet() const { return m_taxTypeHasBeenSet; } string CreateInvoiceItem::GetModels() const { return m_models; } void CreateInvoiceItem::SetModels(const string& _models) { m_models = _models; m_modelsHasBeenSet = true; } bool CreateInvoiceItem::ModelsHasBeenSet() const { return m_modelsHasBeenSet; } string CreateInvoiceItem::GetUnit() const { return m_unit; } void CreateInvoiceItem::SetUnit(const string& _unit) { m_unit = _unit; m_unitHasBeenSet = true; } bool CreateInvoiceItem::UnitHasBeenSet() const { return m_unitHasBeenSet; } string CreateInvoiceItem::GetTotal() const { return m_total; } void CreateInvoiceItem::SetTotal(const string& _total) { m_total = _total; m_totalHasBeenSet = true; } bool CreateInvoiceItem::TotalHasBeenSet() const { return m_totalHasBeenSet; } string CreateInvoiceItem::GetPrice() const { return m_price; } void CreateInvoiceItem::SetPrice(const string& _price) { m_price = _price; m_priceHasBeenSet = true; } bool CreateInvoiceItem::PriceHasBeenSet() const { return m_priceHasBeenSet; } int64_t CreateInvoiceItem::GetDiscount() const { return m_discount; } void CreateInvoiceItem::SetDiscount(const int64_t& _discount) { m_discount = _discount; m_discountHasBeenSet = true; } bool CreateInvoiceItem::DiscountHasBeenSet() const { return m_discountHasBeenSet; } string CreateInvoiceItem::GetPreferentialPolicyFlag() const { return m_preferentialPolicyFlag; } void CreateInvoiceItem::SetPreferentialPolicyFlag(const string& _preferentialPolicyFlag) { m_preferentialPolicyFlag = _preferentialPolicyFlag; m_preferentialPolicyFlagHasBeenSet = true; } bool CreateInvoiceItem::PreferentialPolicyFlagHasBeenSet() const { return m_preferentialPolicyFlagHasBeenSet; } string CreateInvoiceItem::GetZeroTaxFlag() const { return m_zeroTaxFlag; } void CreateInvoiceItem::SetZeroTaxFlag(const string& _zeroTaxFlag) { m_zeroTaxFlag = _zeroTaxFlag; m_zeroTaxFlagHasBeenSet = true; } bool CreateInvoiceItem::ZeroTaxFlagHasBeenSet() const { return m_zeroTaxFlagHasBeenSet; } string CreateInvoiceItem::GetVatSpecialManagement() const { return m_vatSpecialManagement; } void CreateInvoiceItem::SetVatSpecialManagement(const string& _vatSpecialManagement) { m_vatSpecialManagement = _vatSpecialManagement; m_vatSpecialManagementHasBeenSet = true; } bool CreateInvoiceItem::VatSpecialManagementHasBeenSet() const { return m_vatSpecialManagementHasBeenSet; }
CoreInternalOutcome CreateInvoiceItem::Deserialize(const Value &value) { string requestId = ""; if (value.HasMember("Name") && !value["Name"].IsNull()) { if (!value["Name"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.Name` IsString=false incorrectly").SetRequestId(requestId)); } m_name = string(value["Name"].GetString()); m_nameHasBeenSet = true; } if (value.HasMember("TaxCode") && !value["TaxCode"].IsNull()) { if (!value["TaxCode"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.TaxCode` IsString=false incorrectly").SetRequestId(requestId)); } m_taxCode = string(value["TaxCode"].GetString()); m_taxCodeHasBeenSet = true; } if (value.HasMember("TotalPrice") && !value["TotalPrice"].IsNull()) { if (!value["TotalPrice"].IsInt64()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.TotalPrice` IsInt64=false incorrectly").SetRequestId(requestId)); } m_totalPrice = value["TotalPrice"].GetInt64(); m_totalPriceHasBeenSet = true; } if (value.HasMember("TaxRate") && !value["TaxRate"].IsNull()) { if (!value["TaxRate"].IsInt64()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.TaxRate` IsInt64=false incorrectly").SetRequestId(requestId)); } m_taxRate = value["TaxRate"].GetInt64(); m_taxRateHasBeenSet = true; } if (value.HasMember("TaxAmount") && !value["TaxAmount"].IsNull()) { if (!value["TaxAmount"].IsInt64()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.TaxAmount` IsInt64=false incorrectly").SetRequestId(requestId)); } m_taxAmount = value["TaxAmount"].GetInt64(); m_taxAmountHasBeenSet = true; } if (value.HasMember("TaxType") && !value["TaxType"].IsNull()) { if (!value["TaxType"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.TaxType` IsString=false incorrectly").SetRequestId(requestId)); } m_taxType = string(value["TaxType"].GetString()); m_taxTypeHasBeenSet = true; } if (value.HasMember("Models") && !value["Models"].IsNull()) { if (!value["Models"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.Models` IsString=false incorrectly").SetRequestId(requestId)); } m_models = string(value["Models"].GetString()); m_modelsHasBeenSet = true; } if (value.HasMember("Unit") && !value["Unit"].IsNull()) { if (!value["Unit"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.Unit` IsString=false incorrectly").SetRequestId(requestId)); } m_unit = string(value["Unit"].GetString()); m_unitHasBeenSet = true; } if (value.HasMember("Total") && !value["Total"].IsNull()) { if (!value["Total"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.Total` IsString=false incorrectly").SetRequestId(requestId)); } m_total = string(value["Total"].GetString()); m_totalHasBeenSet = true; } if (value.HasMember("Price") && !value["Price"].IsNull()) { if (!value["Price"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.Price` IsString=false incorrectly").SetRequestId(requestId)); } m_price = string(value["Price"].GetString()); m_priceHasBeenSet = true; } if (value.HasMember("Discount") && !value["Discount"].IsNull()) { if (!value["Discount"].IsInt64()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.Discount` IsInt64=false incorrectly").SetRequestId(requestId)); } m_discount = value["Discount"].GetInt64(); m_discountHasBeenSet = true; } if (value.HasMember("PreferentialPolicyFlag") && !value["PreferentialPolicyFlag"].IsNull()) { if (!value["PreferentialPolicyFlag"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.PreferentialPolicyFlag` IsString=false incorrectly").SetRequestId(requestId)); } m_preferentialPolicyFlag = string(value["PreferentialPolicyFlag"].GetString()); m_preferentialPolicyFlagHasBeenSet = true; } if (value.HasMember("ZeroTaxFlag") && !value["ZeroTaxFlag"].IsNull()) { if (!value["ZeroTaxFlag"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.ZeroTaxFlag` IsString=false incorrectly").SetRequestId(requestId)); } m_zeroTaxFlag = string(value["ZeroTaxFlag"].GetString()); m_zeroTaxFlagHasBeenSet = true; } if (value.HasMember("VatSpecialManagement") && !value["VatSpecialManagement"].IsNull()) { if (!value["VatSpecialManagement"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.VatSpecialManagement` IsString=false incorrectly").SetRequestId(requestId)); } m_vatSpecialManagement = string(value["VatSpecialManagement"].GetString()); m_vatSpecialManagementHasBeenSet = true; } return CoreInternalOutcome(true); }
function_block-full_function
[]
C++
src/tracking/multi_tracker.cpp
PPokorski/laser_object_tracker
bc967459218b417c7e0e97603464e77f110e25ef
#include "laser_object_tracker/tracking/multi_tracker.hpp" #include <numeric> namespace laser_object_tracker { namespace tracking { MultiTracker::MultiTracker(DistanceFunctor distance_calculator, std::unique_ptr<data_association::BaseDataAssociation> data_association, std::unique_ptr<BaseTracking> tracker_prototype, std::unique_ptr<BaseTrackerRejection> tracker_rejector_prototype) : distance_calculator_(std::move(distance_calculator)), data_association_(std::move(data_association)), tracker_prototype_(std::move(tracker_prototype)), tracker_rejector_prototype_(std::move(tracker_rejector_prototype)) {} void MultiTracker::predict() { for (auto& tracker : trackers_) { tracker->predict(); } } void MultiTracker::update(const std::vector<Eigen::VectorXd>& measurements) { Eigen::MatrixXd cost_matrix = buildCostMatrix(measurements); Eigen::VectorXi assignment_vector = buildAssignmentVector(cost_matrix); updateAndInitializeTracks(measurements, assignment_vector); handleNotUpdatedTracks(assignment_vector); handleRejectedTracks(); } std::vector<std::unique_ptr<BaseTracking>>::const_iterator MultiTracker::begin() const { return trackers_.begin(); } std::vector<std::unique_ptr<BaseTracking>>::const_iterator MultiTracker::end() const { return trackers_.end(); } std::vector<std::unique_ptr<BaseTracking>>::const_iterator MultiTracker::cbegin() const { return trackers_.cbegin(); } std::vector<std::unique_ptr<BaseTracking>>::const_iterator MultiTracker::cend() const { return trackers_.cend(); } const BaseTracking& MultiTracker::at(int index) const { return *trackers_.at(index); } int MultiTracker::size() const { return trackers_.size(); } Eigen::MatrixXd MultiTracker::buildCostMatrix(const std::vector<Eigen::VectorXd>& measurements) { Eigen::MatrixXd cost_matrix(trackers_.size(), measurements.size()); for (int row = 0; row < cost_matrix.rows(); ++row) { for (int col = 0; col < cost_matrix.cols(); ++col) { cost_matrix(row, col) = distance_calculator_(measurements.at(col), *trackers_.at(row)); } } return cost_matrix; } Eigen::VectorXi MultiTracker::buildAssignmentVector(const Eigen::MatrixXd& cost_matrix) { Eigen::VectorXi assignment_vector; data_association_->solve(cost_matrix, data_association_->NOT_NEEDED, assignment_vector); return assignment_vector; } void MultiTracker::updateAndInitializeTracks(const std::vector<Eigen::VectorXd>& measurements, const Eigen::VectorXi& assignment_vector) { for (int i = 0; i < measurements.size(); ++i) { if (assignment_vector(i) != data_association_->NO_ASSIGNMENT) { int tracker_index = assignment_vector(i); trackers_.at(tracker_index)->update(measurements.at(i)); trackers_rejections_.at(tracker_index)->updated(*trackers_.at(tracker_index)); } else { trackers_.push_back(std::move(tracker_prototype_->clone())); trackers_.back()->initFromMeasurement(measurements.at(i)); trackers_rejections_.push_back(std::move(tracker_rejector_prototype_->clone())); } } } void MultiTracker::handleNotUpdatedTracks(const Eigen::VectorXi& assignment_vector) { std::vector<int> trackers_indices(trackers_.size()); std::iota(trackers_indices.begin(), trackers_indices.end(), 0); std::vector<int> updated_trackers(assignment_vector.data(), assignment_vector.data() + assignment_vector.size()); std::sort(updated_trackers.begin(), updated_trackers.end()); std::vector<int> not_updated_trackers; not_updated_trackers.reserve(trackers_indices.size()); std::set_difference(trackers_indices.begin(), trackers_indices.end(), updated_trackers.begin(), updated_trackers.end(), std::back_inserter(not_updated_trackers)); for (int index : not_updated_trackers) { trackers_rejections_.at(index)->notUpdated(*trackers_.at(index)); } } void MultiTracker::handleRejectedTracks() { auto trackers_it = trackers_.cbegin(); auto rejectors_it = trackers_rejections_.cbegin(); for (; trackers_it != trackers_.cend(); ) { const auto& tracker = **trackers_it; const auto& rejector = **rejectors_it; if (rejector.invalidate(tracker)) { trackers_it = trackers_.erase(trackers_it); rejectors_it = trackers_rejections_.erase(rejectors_it); } else { ++trackers_it; ++rejectors_it; } } } } }
#include "laser_object_tracker/tracking/multi_tracker.hpp" #include <numeric> namespace laser_object_tracker { namespace tracking { MultiTracker::MultiTracker(DistanceFunctor distance_calculator, std::unique_ptr<data_association::BaseDataAssociation> data_association, std::unique_ptr<BaseTracking> tracker_prototype, std::unique_ptr<BaseTrackerRejection> tracker_rejector_prototype) : distance_calculator_(std::move(distance_calculator)), data_association_(std::move(data_association)), tracker_prototype_(std::move(tracker_prototype)), tracker_rejector_prototype_(std::move(tracker_rejector_prototype)) {} void MultiTracker::predict() { for (auto& tracker : trackers_) { tracker->predict(); } } void MultiTracker::update(const std::vector<Eigen::VectorXd>& measurements) { Eigen::MatrixXd cost_matrix = buildCostMatrix(measurements); Eigen::VectorXi assignment_vector = buildAssignmentVector(cost_matrix); updateAndInitializeTracks(measurements, assignment_vector); handleNotUpdatedTracks(assignment_vector); handleRejectedTracks(); } std::vector<std::unique_ptr<BaseTracking>>::const_iterator MultiTracker::begin() const { return trackers_.begin(); } std::vector<std::unique_ptr<BaseTracking>>::const_iterator MultiTracker::end() const { return trackers_.end(); } std::vector<std::unique_ptr<BaseTracking>>::const_iterator MultiTracker::cbegin() const { return trackers_.cbegin(); } std::vector<std::unique_ptr<BaseTracking>>::const_iterator MultiTracker::cend() const { return trackers_.cend(); } const BaseTracking& MultiTracker::at(int index) const { return *trackers_.at(index); } int MultiTracker::size() const { return trackers_.size(); } Eigen::MatrixXd MultiTracker::buildCostMatrix(const std::vector<Eigen::VectorXd>& measurements) { Eigen::MatrixXd cost_matrix(trackers_.size(), measurements.size()); for (int row = 0; row < cost_matrix.rows(); ++row) { for (int col = 0; col < cost_matrix.cols(); ++col) { cost_matrix(row, col) = distance_calculator_(measurements.at(col), *trackers_.at(row)); } } return cost_matrix; } Eigen::VectorXi MultiTracker::buildAssignmentVector(const Eigen::MatrixXd& cost_matrix) { Eigen::VectorXi assignment_vector; data_association_->solve(cost_matrix, data_association_->NOT_NEEDED, assignment_vector); return assignment_vector; } void MultiTracker::updateAndInitializeTracks(const std::vector<Eigen::VectorXd>& measurements, const Eigen::VectorXi& assignment_vector) { for (int i = 0; i < measurements.size(); ++i) { if (assignment_vector(i) != data_association_->NO_ASSIGNMENT) { int tracker_index = assignment_vector(i); trackers_.at(tracker_index)->update(measurements.at(i)); trackers_rejections_.at(tracker_index)->updated(*trackers_.at(tracker_index)); } else { trackers_.push_back(std::move(tracker_prototype_->clone())); trackers_.back()->initFromMeasurement(measurements.at(i)); trackers_rejections_.push_back(std::move(tracker_rejector_prototype_->clone())); } } }
void MultiTracker::handleRejectedTracks() { auto trackers_it = trackers_.cbegin(); auto rejectors_it = trackers_rejections_.cbegin(); for (; trackers_it != trackers_.cend(); ) { const auto& tracker = **trackers_it; const auto& rejector = **rejectors_it; if (rejector.invalidate(tracker)) { trackers_it = trackers_.erase(trackers_it); rejectors_it = trackers_rejections_.erase(rejectors_it); } else { ++trackers_it; ++rejectors_it; } } } } }
void MultiTracker::handleNotUpdatedTracks(const Eigen::VectorXi& assignment_vector) { std::vector<int> trackers_indices(trackers_.size()); std::iota(trackers_indices.begin(), trackers_indices.end(), 0); std::vector<int> updated_trackers(assignment_vector.data(), assignment_vector.data() + assignment_vector.size()); std::sort(updated_trackers.begin(), updated_trackers.end()); std::vector<int> not_updated_trackers; not_updated_trackers.reserve(trackers_indices.size()); std::set_difference(trackers_indices.begin(), trackers_indices.end(), updated_trackers.begin(), updated_trackers.end(), std::back_inserter(not_updated_trackers)); for (int index : not_updated_trackers) { trackers_rejections_.at(index)->notUpdated(*trackers_.at(index)); } }
function_block-full_function
[ { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#ifndef LASER_OBJECT_TRACKER_TRACKING_TRACKING_HPP\n\n#define LASER_OBJECT_TRACKER_TRACKING_TRACKING_HPP\n\n\n\n#include \"laser_object_tracker/tracking/base_tracker_rejection.hpp\"\n\n#include \"laser_object_tracker/tracking/base_tracking.hpp\"\n\n#include \"laser_object_tracker/tracking/iteration_tracker_rejection.hpp\"\n\n#include \"laser_object_tracker/tracking/kalman_filter.hpp\"\n\n#include \"laser_object_tracker/tracking/multi_tracker.hpp\"\n\n\n\n#endif // LASER_OBJECT_TRACKER_TRACKING_TRACKING_HPP\n", "file_path": "include/laser_object_tracker/tracking/tracking.hpp", "rank": 0, "score": 113729.64539441212 }, { "content": "/*********************************************************************\n\n*\n\n* BSD 3-Clause License\n\n*\n\n* Copyright (c) 2019, Piotr Pokorski\n\n* All rights reserved.\n\n*\n\n* Redistribution and use in source and binary forms, with or without\n\n* modification, are permitted provided that the following conditions are met:\n\n*\n\n* 1. Redistributions of source code must retain the above copyright notice, this\n\n* list of conditions and the following disclaimer.\n\n*\n\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n\n* this list of conditions and the following disclaimer in the documentation\n\n* and/or other materials provided with the distribution.\n\n*\n\n* 3. Neither the name of the copyright holder nor the names of its\n\n* contributors may be used to endorse or promote products derived from\n\n* this software without specific prior written permission.\n", "file_path": "include/laser_object_tracker/tracking/tracking.hpp", "rank": 1, "score": 113714.37475258336 }, { "content": "class BaseTracking {\n\n public:\n\n BaseTracking(int state_dimensions, int measurement_dimensions);\n\n\n\n virtual void initFromState(const Eigen::VectorXd& init_state) = 0;\n\n\n\n virtual void initFromState();\n\n\n\n virtual void initFromMeasurement(const Eigen::VectorXd& measurement) = 0;\n\n\n\n virtual void initFromMeasurement();\n\n\n\n virtual void predict() = 0;\n\n\n\n virtual void update(const Eigen::VectorXd& measurement) = 0;\n\n\n\n virtual Eigen::VectorXd getStateVector() const = 0;\n\n\n\n virtual std::unique_ptr<BaseTracking> clone() const = 0;\n\n\n\n virtual ~BaseTracking() = default;\n\n\n\n protected:\n\n int state_dimensions_, measurement_dimensions_;\n\n};\n\n} // namespace tracking\n\n} // namespace laser_object_tracker\n\n\n\n#endif //LASER_OBJECT_TRACKER_TRACKING_BASE_TRACKING_HPP\n", "file_path": "include/laser_object_tracker/tracking/base_tracking.hpp", "rank": 2, "score": 111660.48448213535 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#ifndef LASER_OBJECT_TRACKER_TRACKING_BASE_TRACKING_HPP\n\n#define LASER_OBJECT_TRACKER_TRACKING_BASE_TRACKING_HPP\n\n\n\n#include <memory>\n\n\n\n#include <Eigen/Core>\n\n\n\nnamespace laser_object_tracker {\n\nnamespace tracking {\n\n\n", "file_path": "include/laser_object_tracker/tracking/base_tracking.hpp", "rank": 3, "score": 111603.92013482649 }, { "content": "/*********************************************************************\n\n*\n\n* BSD 3-Clause License\n\n*\n\n* Copyright (c) 2019, Piotr Pokorski\n\n* All rights reserved.\n\n*\n\n* Redistribution and use in source and binary forms, with or without\n\n* modification, are permitted provided that the following conditions are met:\n\n*\n\n* 1. Redistributions of source code must retain the above copyright notice, this\n\n* list of conditions and the following disclaimer.\n\n*\n\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n\n* this list of conditions and the following disclaimer in the documentation\n\n* and/or other materials provided with the distribution.\n\n*\n\n* 3. Neither the name of the copyright holder nor the names of its\n\n* contributors may be used to endorse or promote products derived from\n\n* this software without specific prior written permission.\n", "file_path": "include/laser_object_tracker/tracking/base_tracking.hpp", "rank": 4, "score": 111585.75436521549 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#ifndef LASER_OBJECT_TRACKER_TRACKING_MULTI_TRACKER_H\n\n#define LASER_OBJECT_TRACKER_TRACKING_MULTI_TRACKER_H\n\n\n\n#include <vector>\n\n\n\n#include \"laser_object_tracker/data_association/base_data_association.hpp\"\n\n#include \"laser_object_tracker/tracking/base_tracker_rejection.hpp\"\n\n#include \"laser_object_tracker/tracking/base_tracking.hpp\"\n\n\n\nnamespace laser_object_tracker {\n\nnamespace tracking {\n", "file_path": "include/laser_object_tracker/tracking/multi_tracker.hpp", "rank": 5, "score": 110906.09565746282 }, { "content": " void handleNotUpdatedTracks(const Eigen::VectorXi& assignment_vector);\n\n\n\n void handleRejectedTracks();\n\n\n\n std::vector<std::unique_ptr<BaseTracking>>::const_iterator begin() const;\n\n\n\n std::vector<std::unique_ptr<BaseTracking>>::const_iterator end() const;\n\n\n\n std::vector<std::unique_ptr<BaseTracking>>::const_iterator cbegin() const;\n\n\n\n std::vector<std::unique_ptr<BaseTracking>>::const_iterator cend() const;\n\n\n\n const BaseTracking& at(int index) const;\n\n\n\n int size() const;\n\n\n\n private:\n\n DistanceFunctor distance_calculator_;\n\n std::unique_ptr<data_association::BaseDataAssociation> data_association_;\n\n\n", "file_path": "include/laser_object_tracker/tracking/multi_tracker.hpp", "rank": 6, "score": 110904.8190737856 }, { "content": " std::unique_ptr<BaseTracking> tracker_prototype_;\n\n std::vector<std::unique_ptr<BaseTracking>> trackers_;\n\n\n\n std::unique_ptr<BaseTrackerRejection> tracker_rejector_prototype_;\n\n std::vector<std::unique_ptr<BaseTrackerRejection>> trackers_rejections_;\n\n};\n\n} // namespace tracking\n\n} // namespace laser_object_tracker\n\n\n\n#endif //LASER_OBJECT_TRACKER_TRACKING_MULTI_TRACKER_H\n", "file_path": "include/laser_object_tracker/tracking/multi_tracker.hpp", "rank": 7, "score": 110901.83642008188 }, { "content": "/*********************************************************************\n\n*\n\n* BSD 3-Clause License\n\n*\n\n* Copyright (c) 2019, Piotr Pokorski\n\n* All rights reserved.\n\n*\n\n* Redistribution and use in source and binary forms, with or without\n\n* modification, are permitted provided that the following conditions are met:\n\n*\n\n* 1. Redistributions of source code must retain the above copyright notice, this\n\n* list of conditions and the following disclaimer.\n\n*\n\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n\n* this list of conditions and the following disclaimer in the documentation\n\n* and/or other materials provided with the distribution.\n\n*\n\n* 3. Neither the name of the copyright holder nor the names of its\n\n* contributors may be used to endorse or promote products derived from\n\n* this software without specific prior written permission.\n", "file_path": "include/laser_object_tracker/tracking/multi_tracker.hpp", "rank": 8, "score": 110887.37369432811 }, { "content": "class MultiTracker {\n\n public:\n\n using DistanceFunctor = std::function<double(const Eigen::VectorXd&, const BaseTracking&)>;\n\n\n\n MultiTracker(DistanceFunctor distance_calculator,\n\n std::unique_ptr<data_association::BaseDataAssociation> data_association,\n\n std::unique_ptr<BaseTracking> tracker_prototype,\n\n std::unique_ptr<BaseTrackerRejection> tracker_rejector_prototype);\n\n\n\n void predict();\n\n\n\n void update(const std::vector<Eigen::VectorXd>& measurements);\n\n\n\n Eigen::MatrixXd buildCostMatrix(const std::vector<Eigen::VectorXd>& measurements);\n\n\n\n Eigen::VectorXi buildAssignmentVector(const Eigen::MatrixXd& cost_matrix);\n\n\n\n void updateAndInitializeTracks(const std::vector<Eigen::VectorXd>& measurements,\n\n const Eigen::VectorXi& assignment_vector);\n\n\n", "file_path": "include/laser_object_tracker/tracking/multi_tracker.hpp", "rank": 9, "score": 110601.5526987534 }, { "content": "class MockTrackerRejection : public laser_object_tracker::tracking::BaseTrackerRejection {\n\n MOCK_CONST_METHOD1(invalidate, bool(const laser_object_tracker::tracking::BaseTracking& tracker));\n\n\n\n std::unique_ptr<BaseTrackerRejection> clone() const override {\n\n return std::unique_ptr<BaseTrackerRejection>(new MockTrackerRejection());\n\n }\n\n};\n\n\n\n} // namespace test\n\n\n\n#endif //TEST_TEST_TRACKING_MOCKS_HPP\n", "file_path": "test/include/test/tracking/mocks.hpp", "rank": 10, "score": 108880.96727942834 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#ifndef LASER_OBJECT_TRACKER_TRACKING_BASE_TRACKER_REJECTION_HPP\n\n#define LASER_OBJECT_TRACKER_TRACKING_BASE_TRACKER_REJECTION_HPP\n\n\n\n#include \"laser_object_tracker/tracking/base_tracking.hpp\"\n\n\n\nnamespace laser_object_tracker {\n\nnamespace tracking {\n\n\n", "file_path": "include/laser_object_tracker/tracking/base_tracker_rejection.hpp", "rank": 11, "score": 108844.52089006154 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#ifndef LASER_OBJECT_TRACKER_TRACKING_ITERATION_TRACKER_REJECTION_HPP\n\n#define LASER_OBJECT_TRACKER_TRACKING_ITERATION_TRACKER_REJECTION_HPP\n\n\n\n#include \"laser_object_tracker/tracking/base_tracker_rejection.hpp\"\n\n\n\nnamespace laser_object_tracker {\n\nnamespace tracking {\n\n\n", "file_path": "include/laser_object_tracker/tracking/iteration_tracker_rejection.hpp", "rank": 12, "score": 108844.41375443932 }, { "content": "/*********************************************************************\n\n*\n\n* BSD 3-Clause License\n\n*\n\n* Copyright (c) 2019, Piotr Pokorski\n\n* All rights reserved.\n\n*\n\n* Redistribution and use in source and binary forms, with or without\n\n* modification, are permitted provided that the following conditions are met:\n\n*\n\n* 1. Redistributions of source code must retain the above copyright notice, this\n\n* list of conditions and the following disclaimer.\n\n*\n\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n\n* this list of conditions and the following disclaimer in the documentation\n\n* and/or other materials provided with the distribution.\n\n*\n\n* 3. Neither the name of the copyright holder nor the names of its\n\n* contributors may be used to endorse or promote products derived from\n\n* this software without specific prior written permission.\n", "file_path": "include/laser_object_tracker/tracking/base_tracker_rejection.hpp", "rank": 13, "score": 108826.14027406639 }, { "content": "/*********************************************************************\n\n*\n\n* BSD 3-Clause License\n\n*\n\n* Copyright (c) 2019, Piotr Pokorski\n\n* All rights reserved.\n\n*\n\n* Redistribution and use in source and binary forms, with or without\n\n* modification, are permitted provided that the following conditions are met:\n\n*\n\n* 1. Redistributions of source code must retain the above copyright notice, this\n\n* list of conditions and the following disclaimer.\n\n*\n\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n\n* this list of conditions and the following disclaimer in the documentation\n\n* and/or other materials provided with the distribution.\n\n*\n\n* 3. Neither the name of the copyright holder nor the names of its\n\n* contributors may be used to endorse or promote products derived from\n\n* this software without specific prior written permission.\n", "file_path": "include/laser_object_tracker/tracking/iteration_tracker_rejection.hpp", "rank": 14, "score": 108826.14027406642 }, { "content": "class BaseTrackerRejection {\n\n public:\n\n virtual bool invalidate(const BaseTracking& tracker) const = 0;\n\n\n\n virtual void updated(const BaseTracking& tracker) {}\n\n\n\n virtual void notUpdated(const BaseTracking& tracker) {}\n\n\n\n virtual std::unique_ptr<BaseTrackerRejection> clone() const = 0;\n\n};\n\n\n\n} // namespace tracking\n\n} // namespace laser_object_tracker\n\n\n\n#endif //LASER_OBJECT_TRACKER_TRACKING_BASE_TRACKER_REJECTION_HPP\n", "file_path": "include/laser_object_tracker/tracking/base_tracker_rejection.hpp", "rank": 15, "score": 107057.33943102525 }, { "content": "class MockTracking : public laser_object_tracker::tracking::BaseTracking {\n\n public:\n\n MockTracking() : BaseTracking(0, 0) {}\n\n\n\n MockTracking(int s, int m) : BaseTracking(0, 0) {}\n\n\n\n MOCK_METHOD1(initFromState, void(const Eigen::VectorXd&));\n\n\n\n MOCK_METHOD1(initFromMeasurement, void(const Eigen::VectorXd&));\n\n\n\n MOCK_METHOD0(predict, void());\n\n\n\n MOCK_METHOD1(update, void(const Eigen::VectorXd&));\n\n\n\n MOCK_CONST_METHOD0(getStateVector, Eigen::VectorXd());\n\n\n\n std::unique_ptr<BaseTracking> clone() const override {\n\n return std::unique_ptr<BaseTracking>(new MockTracking());\n\n }\n\n};\n\n\n", "file_path": "test/include/test/tracking/mocks.hpp", "rank": 16, "score": 106050.53427492321 }, { "content": "class IterationTrackerRejection : public BaseTrackerRejection {\n\n public:\n\n explicit IterationTrackerRejection(int max_iterations_without_update);\n\n\n\n bool invalidate(const BaseTracking& tracker) const override;\n\n\n\n void updated(const BaseTracking& tracker) override;\n\n\n\n void notUpdated(const BaseTracking& tracker) override;\n\n\n\n std::unique_ptr<BaseTrackerRejection> clone() const override;\n\n\n\n int getMaxIterationsWithoutUpdate() const;\n\n\n\n void setMaxIterationsWithoutUpdate(int max_iterations_without_update);\n\n private:\n\n int max_iterations_without_update_, iterations_without_update_;\n\n};\n\n\n\n} // namespace tracking\n\n} // namespace laser_object_tracker\n\n\n\n#endif //LASER_OBJECT_TRACKER_TRACKING_ITERATION_TRACKER_REJECTION_HPP\n", "file_path": "include/laser_object_tracker/tracking/iteration_tracker_rejection.hpp", "rank": 17, "score": 103223.66338046256 }, { "content": " void initFromMeasurement(const Eigen::VectorXd& measurement) override;\n\n\n\n void predict() override;\n\n\n\n void update(const Eigen::VectorXd& measurement) override;\n\n\n\n Eigen::VectorXd getStateVector() const override;\n\n\n\n std::unique_ptr<BaseTracking> clone() const override;\n\n\n\nprivate:\n\n void copyMats(const KalmanFilter& other);\n\n\n\n cv::KalmanFilter kalman_filter_;\n\n cv::Mat inverse_measurement_matrix_;\n\n};\n\n} // namespace tracking\n\n} // namespace laser_object_tracker\n\n\n\n#endif //LASER_OBJECT_TRACKER_TRACKING_KALMAN_FILTER_HPP\n", "file_path": "include/laser_object_tracker/tracking/kalman_filter.hpp", "rank": 18, "score": 103027.09116375758 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#ifndef LASER_OBJECT_TRACKER_TRACKING_KALMAN_FILTER_HPP\n\n#define LASER_OBJECT_TRACKER_TRACKING_KALMAN_FILTER_HPP\n\n\n\n#include <opencv2/video/tracking.hpp>\n\n\n\n#include \"laser_object_tracker/tracking/base_tracking.hpp\"\n\n\n\nnamespace laser_object_tracker {\n\nnamespace tracking {\n", "file_path": "include/laser_object_tracker/tracking/kalman_filter.hpp", "rank": 19, "score": 103022.26528416884 }, { "content": "/*********************************************************************\n\n*\n\n* BSD 3-Clause License\n\n*\n\n* Copyright (c) 2019, Piotr Pokorski\n\n* All rights reserved.\n\n*\n\n* Redistribution and use in source and binary forms, with or without\n\n* modification, are permitted provided that the following conditions are met:\n\n*\n\n* 1. Redistributions of source code must retain the above copyright notice, this\n\n* list of conditions and the following disclaimer.\n\n*\n\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n\n* this list of conditions and the following disclaimer in the documentation\n\n* and/or other materials provided with the distribution.\n\n*\n\n* 3. Neither the name of the copyright holder nor the names of its\n\n* contributors may be used to endorse or promote products derived from\n\n* this software without specific prior written permission.\n", "file_path": "include/laser_object_tracker/tracking/kalman_filter.hpp", "rank": 20, "score": 103003.92647213789 }, { "content": "class KalmanFilter : public BaseTracking {\n\n public:\n\n KalmanFilter(int state_dimensions,\n\n int measurement_dimensions,\n\n const Eigen::MatrixXd& transition_matrix,\n\n const Eigen::MatrixXd& measurement_matrix,\n\n const Eigen::MatrixXd& measurement_noise_covariance,\n\n const Eigen::MatrixXd& initial_state_covariance,\n\n const Eigen::MatrixXd& process_noise_covariance);\n\n\n\n KalmanFilter(const KalmanFilter& other) noexcept;\n\n\n\n KalmanFilter(KalmanFilter&& other) noexcept = default;\n\n\n\n KalmanFilter& operator=(const KalmanFilter& other) noexcept;\n\n\n\n KalmanFilter& operator=(KalmanFilter&& other) noexcept = default;\n\n\n\n void initFromState(const Eigen::VectorXd& init_state) override;\n\n\n", "file_path": "include/laser_object_tracker/tracking/kalman_filter.hpp", "rank": 21, "score": 102080.41015656681 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#ifndef TEST_TEST_TRACKING_MOCKS_HPP\n\n#define TEST_TEST_TRACKING_MOCKS_HPP\n\n\n\n#include <gmock/gmock.h>\n\n\n\n#include \"laser_object_tracker/tracking/base_tracking.hpp\"\n\n\n\nnamespace test {\n", "file_path": "test/include/test/tracking/mocks.hpp", "rank": 30, "score": 73026.00110554376 }, { "content": "/*********************************************************************\n\n*\n\n* BSD 3-Clause License\n\n*\n\n* Copyright (c) 2019, Piotr Pokorski\n\n* All rights reserved.\n\n*\n\n* Redistribution and use in source and binary forms, with or without\n\n* modification, are permitted provided that the following conditions are met:\n\n*\n\n* 1. Redistributions of source code must retain the above copyright notice, this\n\n* list of conditions and the following disclaimer.\n\n*\n\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n\n* this list of conditions and the following disclaimer in the documentation\n\n* and/or other materials provided with the distribution.\n\n*\n\n* 3. Neither the name of the copyright holder nor the names of its\n\n* contributors may be used to endorse or promote products derived from\n\n* this software without specific prior written permission.\n", "file_path": "test/include/test/tracking/mocks.hpp", "rank": 31, "score": 73010.04178133917 }, { "content": " iterations_without_update_(0) {}\n\n\n\nbool IterationTrackerRejection::invalidate(const BaseTracking& tracker) const {\n\n return iterations_without_update_ > max_iterations_without_update_;\n\n}\n\n\n\nvoid IterationTrackerRejection::updated(const BaseTracking& tracker) {\n\n iterations_without_update_ = 0;\n\n}\n\n\n\nvoid IterationTrackerRejection::notUpdated(const BaseTracking& tracker) {\n\n ++iterations_without_update_;\n\n}\n\n\n\nstd::unique_ptr<BaseTrackerRejection> IterationTrackerRejection::clone() const {\n\n return std::unique_ptr<BaseTrackerRejection>(new IterationTrackerRejection(*this));\n\n}\n\n\n\nint IterationTrackerRejection::getMaxIterationsWithoutUpdate() const {\n\n return max_iterations_without_update_;\n\n}\n\n\n\nvoid IterationTrackerRejection::setMaxIterationsWithoutUpdate(int max_iterations_without_update) {\n\n max_iterations_without_update_ = max_iterations_without_update;\n\n}\n\n} // namespace tracking\n\n} // namespace laser_object_tracker\n", "file_path": "src/tracking/iteration_tracker_rejection.cpp", "rank": 32, "score": 72605.06829454323 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#include \"laser_object_tracker/tracking/iteration_tracker_rejection.hpp\"\n\n\n\nnamespace laser_object_tracker {\n\nnamespace tracking {\n\n\n\nIterationTrackerRejection::IterationTrackerRejection(int max_iterations_without_update)\n\n : max_iterations_without_update_(max_iterations_without_update),\n", "file_path": "src/tracking/iteration_tracker_rejection.cpp", "rank": 33, "score": 72603.35916499073 }, { "content": "/*********************************************************************\n\n*\n\n* BSD 3-Clause License\n\n*\n\n* Copyright (c) 2019, Piotr Pokorski\n\n* All rights reserved.\n\n*\n\n* Redistribution and use in source and binary forms, with or without\n\n* modification, are permitted provided that the following conditions are met:\n\n*\n\n* 1. Redistributions of source code must retain the above copyright notice, this\n\n* list of conditions and the following disclaimer.\n\n*\n\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n\n* this list of conditions and the following disclaimer in the documentation\n\n* and/or other materials provided with the distribution.\n\n*\n\n* 3. Neither the name of the copyright holder nor the names of its\n\n* contributors may be used to endorse or promote products derived from\n\n* this software without specific prior written permission.\n", "file_path": "src/tracking/iteration_tracker_rejection.cpp", "rank": 34, "score": 72582.82411071574 }, { "content": " void publishAssignments(const tracking::MultiTracker& multi_tracker,\n\n const std::vector<Eigen::VectorXd>& measurements,\n\n const Eigen::MatrixXd& cost_matrix,\n\n const Eigen::VectorXi& assignment_vector);\n\n\n\n private:\n\n void expandToNColors(int colors);\n\n\n\n rviz_visual_tools::RvizVisualToolsPtr rviz_visual_tools_;\n\n ros::Publisher pub_point_cloud_;\n\n ros::Publisher pub_point_clouds_;\n\n\n\n std::vector<float> colours_;\n\n std::vector<std_msgs::ColorRGBA> rgb_colors_;\n\n};\n\n} // namespace visualization\n\n} // namespace laser_object_tracker\n\n\n\n#endif //LASER_OBJECT_TRACKER_VISUALIZATION_LASER_OBJECT_TRACKER_VISUALIZATION_HPP\n", "file_path": "include/laser_object_tracker/visualization/laser_object_tracker_visualization.hpp", "rank": 35, "score": 72235.37632755458 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#ifndef LASER_OBJECT_TRACKER_VISUALIZATION_LASER_OBJECT_TRACKER_VISUALIZATION_HPP\n\n#define LASER_OBJECT_TRACKER_VISUALIZATION_LASER_OBJECT_TRACKER_VISUALIZATION_HPP\n\n\n\n#include <ros/ros.h>\n\n\n\n#include <pcl_ros/point_cloud.h>\n\n#include <rviz_visual_tools/rviz_visual_tools.h>\n\n\n\n#include \"laser_object_tracker/data_types/definitions.hpp\"\n\n#include \"laser_object_tracker/data_types/laser_scan_fragment.hpp\"\n\n#include \"laser_object_tracker/feature_extraction/features/features.hpp\"\n\n#include \"laser_object_tracker/tracking/multi_tracker.hpp\"\n\n\n\nnamespace laser_object_tracker {\n\nnamespace visualization {\n", "file_path": "include/laser_object_tracker/visualization/laser_object_tracker_visualization.hpp", "rank": 36, "score": 72228.66981081547 }, { "content": " }\n\n\n\n void publishPointClouds(const std::vector<data_types::LaserScanFragment>& fragments);\n\n\n\n void publishFeatures(const std::vector<data_types::LaserScanFragment>& fragments);\n\n\n\n void publishSegment(const feature_extraction::features::Segment2D& segment, const std_msgs::ColorRGBA& color);\n\n\n\n void publishSegments(const feature_extraction::features::Segments2D& segments);\n\n\n\n void publishCorner(const feature_extraction::features::Corner2D& corner, const std_msgs::ColorRGBA& color);\n\n\n\n void publishCorners(const feature_extraction::features::Corners2D& corners);\n\n\n\n void publishPoint(const feature_extraction::features::Point2D& point, const std_msgs::ColorRGBA& color);\n\n\n\n void publishTracker(const tracking::BaseTracking& tracker, const std_msgs::ColorRGBA& color);\n\n\n\n void publishMultiTracker(const tracking::MultiTracker& multi_tracker);\n\n\n", "file_path": "include/laser_object_tracker/visualization/laser_object_tracker_visualization.hpp", "rank": 37, "score": 72226.47285401858 }, { "content": "/*********************************************************************\n\n*\n\n* BSD 3-Clause License\n\n*\n\n* Copyright (c) 2019, Piotr Pokorski\n\n* All rights reserved.\n\n*\n\n* Redistribution and use in source and binary forms, with or without\n\n* modification, are permitted provided that the following conditions are met:\n\n*\n\n* 1. Redistributions of source code must retain the above copyright notice, this\n\n* list of conditions and the following disclaimer.\n\n*\n\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n\n* this list of conditions and the following disclaimer in the documentation\n\n* and/or other materials provided with the distribution.\n\n*\n\n* 3. Neither the name of the copyright holder nor the names of its\n\n* contributors may be used to endorse or promote products derived from\n\n* this software without specific prior written permission.\n", "file_path": "include/laser_object_tracker/visualization/laser_object_tracker_visualization.hpp", "rank": 38, "score": 72212.1925468263 }, { "content": "class LaserObjectTrackerVisualization {\n\n public:\n\n LaserObjectTrackerVisualization(ros::NodeHandle& pnh, const std::string& base_frame) {\n\n rviz_visual_tools_.reset(new rviz_visual_tools::RvizVisualTools(base_frame, \"visualization/markers\"));\n\n rviz_visual_tools_->setLifetime(0.0);\n\n\n\n pub_point_cloud_ = pnh.advertise<data_types::PointCloudType>(\"visualization/point_cloud\", 1);\n\n pub_point_clouds_ = pnh.advertise<pcl::PointCloud<pcl::PointXYZRGB>>(\"visualization/point_clouds\", 1);\n\n }\n\n\n\n void publishPointCloud(const data_types::LaserScanFragment& fragment) {\n\n pub_point_cloud_.publish(fragment.pointCloud());\n\n }\n\n\n\n void trigger() {\n\n rviz_visual_tools_->trigger();\n\n }\n\n\n\n void clearMarkers() {\n\n rviz_visual_tools_->deleteAllMarkers();\n", "file_path": "include/laser_object_tracker/visualization/laser_object_tracker_visualization.hpp", "rank": 39, "score": 71825.01880690889 }, { "content": "\n\nTEST(MultiTrackerTest, UpdateAndInitializeTracksTest) {\n\n auto data_association = std::make_unique<test::MockDataAssociation>();\n\n auto tracking = std::make_unique<test::MockTracking>();\n\n auto tracker_rejection = std::make_unique<test::MockTrackerRejection>();\n\n laser_object_tracker::tracking::MultiTracker multi_tracker(\n\n [](const auto& lhs, const auto& rhs) {return 0.0;},\n\n std::move(data_association),\n\n std::move(tracking),\n\n std::move(tracker_rejection));\n\n\n\n static constexpr int NO_ASSIGNMENT = laser_object_tracker::data_association::BaseDataAssociation::NO_ASSIGNMENT;\n\n\n\n std::vector<Eigen::VectorXd> measurements;\n\n Eigen::VectorXi assignment_vector;\n\n\n\n measurements.resize(5);\n\n assignment_vector.setConstant(5, NO_ASSIGNMENT);\n\n multi_tracker.updateAndInitializeTracks(measurements, assignment_vector);\n\n ASSERT_EQ(5, multi_tracker.size());\n", "file_path": "test/src/tracking/multi_tracker_test.cpp", "rank": 40, "score": 70966.83760261044 }, { "content": " // All objects should be unique (with respect to pointer)\n\n for (auto it_1 = multi_tracker.begin(); it_1 != multi_tracker.end(); ++it_1) {\n\n for (auto it_2 = std::next(it_1); it_2 != multi_tracker.end(); ++it_2) {\n\n EXPECT_NE(*it_1, *it_2);\n\n }\n\n }\n\n\n\n measurements.resize(3);\n\n assignment_vector.setConstant(3, NO_ASSIGNMENT);\n\n multi_tracker.updateAndInitializeTracks(measurements, assignment_vector);\n\n ASSERT_EQ(8, multi_tracker.size());\n\n // All objects should be unique (with respect to pointer)\n\n for (auto it_1 = multi_tracker.begin(); it_1 != multi_tracker.end(); ++it_1) {\n\n for (auto it_2 = std::next(it_1); it_2 != multi_tracker.end(); ++it_2) {\n\n EXPECT_NE(*it_1, *it_2);\n\n }\n\n }\n\n\n\n measurements.resize(8);\n\n assignment_vector.resize(8);\n\n assignment_vector << 0, 1, 2, 3, 4, 5, 6, 7;\n\n for (const auto& tracker : multi_tracker) {\n\n auto& cast_tracker = dynamic_cast<test::MockTracking&>(*tracker);\n\n EXPECT_CALL(cast_tracker, update(testing::_));\n\n }\n\n\n\n multi_tracker.updateAndInitializeTracks(measurements, assignment_vector);\n\n}\n", "file_path": "test/src/tracking/multi_tracker_test.cpp", "rank": 41, "score": 70963.90063184885 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#include <gtest/gtest.h>\n\n\n\n#include \"laser_object_tracker/tracking/multi_tracker.hpp\"\n\n\n\n#include \"test/utils.hpp\"\n\n#include \"test/data_association/mocks.hpp\"\n\n#include \"test/tracking/mocks.hpp\"\n", "file_path": "test/src/tracking/multi_tracker_test.cpp", "rank": 42, "score": 70957.37697471277 }, { "content": "/*********************************************************************\n\n*\n\n* BSD 3-Clause License\n\n*\n\n* Copyright (c) 2019, Piotr Pokorski\n\n* All rights reserved.\n\n*\n\n* Redistribution and use in source and binary forms, with or without\n\n* modification, are permitted provided that the following conditions are met:\n\n*\n\n* 1. Redistributions of source code must retain the above copyright notice, this\n\n* list of conditions and the following disclaimer.\n\n*\n\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n\n* this list of conditions and the following disclaimer in the documentation\n\n* and/or other materials provided with the distribution.\n\n*\n\n* 3. Neither the name of the copyright holder nor the names of its\n\n* contributors may be used to endorse or promote products derived from\n\n* this software without specific prior written permission.\n", "file_path": "test/src/tracking/multi_tracker_test.cpp", "rank": 43, "score": 70944.20835354984 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#include <gtest/gtest.h>\n\n\n\n#include \"laser_object_tracker/tracking/iteration_tracker_rejection.hpp\"\n\n\n\n#include \"test/utils.hpp\"\n\n#include \"test/tracking/mocks.hpp\"\n\n\n", "file_path": "test/src/tracking/iteration_tracker_rejection_test.cpp", "rank": 44, "score": 69391.14489325396 }, { "content": "TEST(IterationTrackerRejectionTest, AccessorsTest) {\n\n laser_object_tracker::tracking::IterationTrackerRejection rejection(1);\n\n EXPECT_EQ(1, rejection.getMaxIterationsWithoutUpdate());\n\n\n\n rejection.setMaxIterationsWithoutUpdate(5);\n\n EXPECT_EQ(5, rejection.getMaxIterationsWithoutUpdate());\n\n}\n\n\n\nTEST(IterationTrackerRejectionTest, InvalidationTest) {\n\n laser_object_tracker::tracking::IterationTrackerRejection rejection(3);\n\n\n\n test::MockTracking tracking;\n\n\n\n EXPECT_FALSE(rejection.invalidate(tracking));\n\n\n\n rejection.updated(tracking);\n\n EXPECT_FALSE(rejection.invalidate(tracking));\n\n\n\n rejection.notUpdated(tracking);\n\n EXPECT_FALSE(rejection.invalidate(tracking));\n", "file_path": "test/src/tracking/iteration_tracker_rejection_test.cpp", "rank": 45, "score": 69388.02744443632 }, { "content": " rejection.notUpdated(tracking);\n\n EXPECT_FALSE(rejection.invalidate(tracking));\n\n rejection.notUpdated(tracking);\n\n EXPECT_FALSE(rejection.invalidate(tracking));\n\n\n\n rejection.updated(tracking);\n\n EXPECT_FALSE(rejection.invalidate(tracking));\n\n rejection.notUpdated(tracking);\n\n EXPECT_FALSE(rejection.invalidate(tracking));\n\n\n\n rejection.notUpdated(tracking);\n\n EXPECT_FALSE(rejection.invalidate(tracking));\n\n rejection.notUpdated(tracking);\n\n EXPECT_FALSE(rejection.invalidate(tracking));\n\n rejection.notUpdated(tracking);\n\n EXPECT_TRUE(rejection.invalidate(tracking));\n\n rejection.notUpdated(tracking);\n\n EXPECT_TRUE(rejection.invalidate(tracking));\n\n}\n", "file_path": "test/src/tracking/iteration_tracker_rejection_test.cpp", "rank": 46, "score": 69383.49542294124 }, { "content": "/*********************************************************************\n\n*\n\n* BSD 3-Clause License\n\n*\n\n* Copyright (c) 2019, Piotr Pokorski\n\n* All rights reserved.\n\n*\n\n* Redistribution and use in source and binary forms, with or without\n\n* modification, are permitted provided that the following conditions are met:\n\n*\n\n* 1. Redistributions of source code must retain the above copyright notice, this\n\n* list of conditions and the following disclaimer.\n\n*\n\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n\n* this list of conditions and the following disclaimer in the documentation\n\n* and/or other materials provided with the distribution.\n\n*\n\n* 3. Neither the name of the copyright holder nor the names of its\n\n* contributors may be used to endorse or promote products derived from\n\n* this software without specific prior written permission.\n", "file_path": "test/src/tracking/iteration_tracker_rejection_test.cpp", "rank": 47, "score": 69377.94531830397 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#ifndef LASER_OBJECT_TRACKER_SEGMENTATION_SEGMENTATION_HPP\n\n#define LASER_OBJECT_TRACKER_SEGMENTATION_SEGMENTATION_HPP\n\n\n\n#include \"laser_object_tracker/segmentation/adaptive_breakpoint_detection.hpp\"\n\n#include \"laser_object_tracker/segmentation/base_segmentation.hpp\"\n\n#include \"laser_object_tracker/segmentation/breakpoint_detection.hpp\"\n\n#include \"laser_object_tracker/segmentation/distance_calculation.hpp\"\n\n\n\n#endif // LASER_OBJECT_TRACKER_SEGMENTATION_SEGMENTATION_HPP\n", "file_path": "include/laser_object_tracker/segmentation/segmentation.hpp", "rank": 48, "score": 68362.35094905633 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#ifndef LASER_OBJECT_TRACKER_FILTERING_FILTERING_HPP\n\n#define LASER_OBJECT_TRACKER_FILTERING_FILTERING_HPP\n\n\n\n#include \"laser_object_tracker/filtering/aggregate_segmented_filtering.hpp\"\n\n#include \"laser_object_tracker/filtering/base_segmented_filtering.hpp\"\n\n#include \"laser_object_tracker/filtering/obb_area_filter.hpp\"\n\n#include \"laser_object_tracker/filtering/points_number_filter.hpp\"\n\n\n\n#endif // LASER_OBJECT_TRACKER_FILTERING_FILTERING_HPP\n", "file_path": "include/laser_object_tracker/filtering/filtering.hpp", "rank": 49, "score": 68362.33155495749 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#ifndef LASER_OBJECT_TRACKER_VISUALIZATION_VISUALIZATION_HPP\n\n#define LASER_OBJECT_TRACKER_VISUALIZATION_VISUALIZATION_HPP\n\n\n\n#include \"laser_object_tracker/visualization/laser_object_tracker_visualization.hpp\"\n\n\n\n#endif // LASER_OBJECT_TRACKER_VISUALIZATION_VISUALIZATION_HPP\n", "file_path": "include/laser_object_tracker/visualization/visualization.hpp", "rank": 50, "score": 68361.95932379953 }, { "content": "/*********************************************************************\n\n*\n\n* BSD 3-Clause License\n\n*\n\n* Copyright (c) 2019, Piotr Pokorski\n\n* All rights reserved.\n\n*\n\n* Redistribution and use in source and binary forms, with or without\n\n* modification, are permitted provided that the following conditions are met:\n\n*\n\n* 1. Redistributions of source code must retain the above copyright notice, this\n\n* list of conditions and the following disclaimer.\n\n*\n\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n\n* this list of conditions and the following disclaimer in the documentation\n\n* and/or other materials provided with the distribution.\n\n*\n\n* 3. Neither the name of the copyright holder nor the names of its\n\n* contributors may be used to endorse or promote products derived from\n\n* this software without specific prior written permission.\n", "file_path": "include/laser_object_tracker/segmentation/segmentation.hpp", "rank": 51, "score": 68352.65667550865 }, { "content": "/*********************************************************************\n\n*\n\n* BSD 3-Clause License\n\n*\n\n* Copyright (c) 2019, Piotr Pokorski\n\n* All rights reserved.\n\n*\n\n* Redistribution and use in source and binary forms, with or without\n\n* modification, are permitted provided that the following conditions are met:\n\n*\n\n* 1. Redistributions of source code must retain the above copyright notice, this\n\n* list of conditions and the following disclaimer.\n\n*\n\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n\n* this list of conditions and the following disclaimer in the documentation\n\n* and/or other materials provided with the distribution.\n\n*\n\n* 3. Neither the name of the copyright holder nor the names of its\n\n* contributors may be used to endorse or promote products derived from\n\n* this software without specific prior written permission.\n", "file_path": "include/laser_object_tracker/visualization/visualization.hpp", "rank": 52, "score": 68352.65667550865 }, { "content": "/*********************************************************************\n\n*\n\n* BSD 3-Clause License\n\n*\n\n* Copyright (c) 2019, Piotr Pokorski\n\n* All rights reserved.\n\n*\n\n* Redistribution and use in source and binary forms, with or without\n\n* modification, are permitted provided that the following conditions are met:\n\n*\n\n* 1. Redistributions of source code must retain the above copyright notice, this\n\n* list of conditions and the following disclaimer.\n\n*\n\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n\n* this list of conditions and the following disclaimer in the documentation\n\n* and/or other materials provided with the distribution.\n\n*\n\n* 3. Neither the name of the copyright holder nor the names of its\n\n* contributors may be used to endorse or promote products derived from\n\n* this software without specific prior written permission.\n", "file_path": "include/laser_object_tracker/filtering/filtering.hpp", "rank": 53, "score": 68352.65667550865 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#ifndef LASER_OBJECT_TRACKER_SEGMENTATION_BASE_SEGMENTATION_HPP\n\n#define LASER_OBJECT_TRACKER_SEGMENTATION_BASE_SEGMENTATION_HPP\n\n\n\n#include <vector>\n\n\n\n#include \"laser_object_tracker/data_types/laser_scan_fragment.hpp\"\n\n\n\nnamespace laser_object_tracker {\n\nnamespace segmentation {\n\n\n", "file_path": "include/laser_object_tracker/segmentation/base_segmentation.hpp", "rank": 54, "score": 66856.88081629838 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#ifndef LASER_OBJECT_TRACKER_SEGMENTATION_DISTANCE_CALCULATION_HPP\n\n#define LASER_OBJECT_TRACKER_SEGMENTATION_DISTANCE_CALCULATION_HPP\n\n\n\n#include \"laser_object_tracker/data_types/definitions.hpp\"\n\n\n\nnamespace laser_object_tracker {\n\nnamespace segmentation {\n", "file_path": "include/laser_object_tracker/segmentation/distance_calculation.hpp", "rank": 55, "score": 66856.78762119141 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#ifndef LASER_OBJECT_TRACKER_SEGMENTATION_BREAKPOINT_DETECTION_HPP\n\n#define LASER_OBJECT_TRACKER_SEGMENTATION_BREAKPOINT_DETECTION_HPP\n\n\n\n#include \"laser_object_tracker/segmentation/base_segmentation.hpp\"\n\n\n\nnamespace laser_object_tracker {\n\nnamespace segmentation {\n\n\n", "file_path": "include/laser_object_tracker/segmentation/breakpoint_detection.hpp", "rank": 56, "score": 66856.78762119141 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#ifndef LASER_OBJECT_TRACKER_FILTERING_OCCLUSION_DETECTION_HPP\n\n#define LASER_OBJECT_TRACKER_FILTERING_OCCLUSION_DETECTION_HPP\n\n\n\n#include \"laser_object_tracker/filtering/base_segmented_filtering.hpp\"\n\n\n\nnamespace laser_object_tracker {\n\nnamespace filtering {\n", "file_path": "include/laser_object_tracker/filtering/occlusion_detection.hpp", "rank": 57, "score": 66856.76990575047 }, { "content": "#include <sensor_msgs/LaserScan.h>\n\n\n\n// PCL\n\n#include <pcl/point_types.h>\n\n#include <pcl/point_cloud.h>\n\n\n\nnamespace laser_object_tracker {\n\nnamespace data_types {\n\n\n\n/**\n\n* @brief Proxy class for bool built-in type, used becuse std::vector<bool> is specialized template container,\n\n* not fully conforming to the standard.\n\n*/\n", "file_path": "include/laser_object_tracker/data_types/definitions.hpp", "rank": 58, "score": 66856.52981062968 }, { "content": "\n\ntemplate<class T>\n\nT distance(const T& one,\n\n const T& two) {\n\n return std::fabs(one - two);\n\n}\n\n\n\ntemplate<class T>\n\nT distanceDirected(const T& one,\n\n const T& two) {\n\n return one - two;\n\n}\n\n} // namespace segmentation\n\n} // namespace laser_object_tracker\n\n\n\n#endif // LASER_OBJECT_TRACKER_SEGMENTATION_DISTANCE_CALCULATION_HPP\n", "file_path": "include/laser_object_tracker/segmentation/distance_calculation.hpp", "rank": 59, "score": 66852.36080367761 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#ifndef LASER_OBJECT_TRACKER_DATA_TYPES_DEFINITIONS_HPP\n\n#define LASER_OBJECT_TRACKER_DATA_TYPES_DEFINITIONS_HPP\n\n\n\n// STD\n\n#include <vector>\n\n\n\n// ROS\n", "file_path": "include/laser_object_tracker/data_types/definitions.hpp", "rank": 60, "score": 66852.26357441011 }, { "content": " bool isValid() const {\n\n return !less_than_min_ && !more_than_max_;\n\n }\n\n\n\n bool lessThanMin() const {\n\n return less_than_min_;\n\n }\n\n\n\n bool moreThanMax() const {\n\n return more_than_max_;\n\n }\n\n\n\n private:\n\n double angle_;\n\n LaserScanType::_ranges_type::reference range_;\n\n OcclusionType::reference is_occluded_;\n\n PointCloudType::PointType& point_;\n\n\n\n bool less_than_min_;\n\n bool more_than_max_;\n\n};\n\n} // namespace data_types\n\n} // namespace laser_object_tracker\n\n\n\n#endif // LASER_OBJECT_TRACKER_DATA_TYPES_DEFINITIONS_HPP\n", "file_path": "include/laser_object_tracker/data_types/definitions.hpp", "rank": 61, "score": 66852.0908266655 }, { "content": " return value_;\n\n }\n\n\n\n private:\n\n bool value_;\n\n};\n\n\n\nusing LaserScanType = sensor_msgs::LaserScan;\n\nusing OcclusionType = std::vector<Bool>;\n\nusing PointCloudType = pcl::PointCloud<pcl::PointXYZ>;\n\n\n\n/**\n\n * @brief Proxy class or aggregator for a single element of LaserScanFragment container, e.g. single measurement.\n\n * Each element consists of polar (angle and range members) and cartesian (point member) coordinates\n\n * corresponding to the current measure. Also provides information whether a measurement is occluded or no.\n\n */\n", "file_path": "include/laser_object_tracker/data_types/definitions.hpp", "rank": 62, "score": 66848.47399389603 }, { "content": "/*********************************************************************\n\n*\n\n* BSD 3-Clause License\n\n*\n\n* Copyright (c) 2019, Piotr Pokorski\n\n* All rights reserved.\n\n*\n\n* Redistribution and use in source and binary forms, with or without\n\n* modification, are permitted provided that the following conditions are met:\n\n*\n\n* 1. Redistributions of source code must retain the above copyright notice, this\n\n* list of conditions and the following disclaimer.\n\n*\n\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n\n* this list of conditions and the following disclaimer in the documentation\n\n* and/or other materials provided with the distribution.\n\n*\n\n* 3. Neither the name of the copyright holder nor the names of its\n\n* contributors may be used to endorse or promote products derived from\n\n* this software without specific prior written permission.\n", "file_path": "include/laser_object_tracker/segmentation/base_segmentation.hpp", "rank": 63, "score": 66843.60834025659 }, { "content": " return range_;\n\n }\n\n LaserScanType::_ranges_type::const_reference range() const {\n\n return range_;\n\n }\n\n\n\n OcclusionType::reference isOccluded() {\n\n return is_occluded_;\n\n }\n\n OcclusionType::const_reference isOccluded() const {\n\n return is_occluded_;\n\n }\n\n\n\n PointCloudType::PointType& point() {\n\n return point_;\n\n }\n\n const PointCloudType::PointType& point() const {\n\n return point_;\n\n }\n\n\n", "file_path": "include/laser_object_tracker/data_types/definitions.hpp", "rank": 64, "score": 66843.60834025659 }, { "content": "/*********************************************************************\n\n*\n\n* BSD 3-Clause License\n\n*\n\n* Copyright (c) 2019, Piotr Pokorski\n\n* All rights reserved.\n\n*\n\n* Redistribution and use in source and binary forms, with or without\n\n* modification, are permitted provided that the following conditions are met:\n\n*\n\n* 1. Redistributions of source code must retain the above copyright notice, this\n\n* list of conditions and the following disclaimer.\n\n*\n\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n\n* this list of conditions and the following disclaimer in the documentation\n\n* and/or other materials provided with the distribution.\n\n*\n\n* 3. Neither the name of the copyright holder nor the names of its\n\n* contributors may be used to endorse or promote products derived from\n\n* this software without specific prior written permission.\n", "file_path": "include/laser_object_tracker/filtering/occlusion_detection.hpp", "rank": 65, "score": 66843.60834025659 }, { "content": "/*********************************************************************\n\n*\n\n* BSD 3-Clause License\n\n*\n\n* Copyright (c) 2019, Piotr Pokorski\n\n* All rights reserved.\n\n*\n\n* Redistribution and use in source and binary forms, with or without\n\n* modification, are permitted provided that the following conditions are met:\n\n*\n\n* 1. Redistributions of source code must retain the above copyright notice, this\n\n* list of conditions and the following disclaimer.\n\n*\n\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n\n* this list of conditions and the following disclaimer in the documentation\n\n* and/or other materials provided with the distribution.\n\n*\n\n* 3. Neither the name of the copyright holder nor the names of its\n\n* contributors may be used to endorse or promote products derived from\n\n* this software without specific prior written permission.\n", "file_path": "include/laser_object_tracker/segmentation/breakpoint_detection.hpp", "rank": 66, "score": 66843.60834025659 }, { "content": "/*********************************************************************\n\n*\n\n* BSD 3-Clause License\n\n*\n\n* Copyright (c) 2019, Piotr Pokorski\n\n* All rights reserved.\n\n*\n\n* Redistribution and use in source and binary forms, with or without\n\n* modification, are permitted provided that the following conditions are met:\n\n*\n\n* 1. Redistributions of source code must retain the above copyright notice, this\n\n* list of conditions and the following disclaimer.\n\n*\n\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n\n* this list of conditions and the following disclaimer in the documentation\n\n* and/or other materials provided with the distribution.\n\n*\n\n* 3. Neither the name of the copyright holder nor the names of its\n\n* contributors may be used to endorse or promote products derived from\n\n* this software without specific prior written permission.\n", "file_path": "include/laser_object_tracker/data_types/definitions.hpp", "rank": 67, "score": 66843.60834025659 }, { "content": "/*********************************************************************\n\n*\n\n* BSD 3-Clause License\n\n*\n\n* Copyright (c) 2019, Piotr Pokorski\n\n* All rights reserved.\n\n*\n\n* Redistribution and use in source and binary forms, with or without\n\n* modification, are permitted provided that the following conditions are met:\n\n*\n\n* 1. Redistributions of source code must retain the above copyright notice, this\n\n* list of conditions and the following disclaimer.\n\n*\n\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n\n* this list of conditions and the following disclaimer in the documentation\n\n* and/or other materials provided with the distribution.\n\n*\n\n* 3. Neither the name of the copyright holder nor the names of its\n\n* contributors may be used to endorse or promote products derived from\n\n* this software without specific prior written permission.\n", "file_path": "include/laser_object_tracker/segmentation/distance_calculation.hpp", "rank": 68, "score": 66843.60834025659 }, { "content": " void step2b(const Eigen::MatrixXd& cost_matrix, Eigen::ArrayXXd& cost_matrix_copy, Eigen::VectorXi& assignment);\n\n void step3(const Eigen::MatrixXd& cost_matrix, Eigen::ArrayXXd& cost_matrix_copy, Eigen::VectorXi& assignment);\n\n void step4(const Eigen::MatrixXd& cost_matrix,\n\n Eigen::ArrayXXd& cost_matrix_copy,\n\n Eigen::VectorXi& assignment,\n\n int row,\n\n int column);\n\n void step5(const Eigen::MatrixXd& cost_matrix, Eigen::ArrayXXd& cost_matrix_copy, Eigen::VectorXi& assignment);\n\n\n\n bool isZero(double number, double precision = Eigen::NumTraits<double>::dummy_precision());\n\n\n\n Eigen::ArrayXXb star_matrix_;\n\n Eigen::ArrayXXb new_star_matrix_;\n\n Eigen::ArrayXXb prime_matrix_;\n\n Eigen::RowArrayXb covered_columns_;\n\n Eigen::ArrayXb covered_rows_;\n\n Eigen::Index min_dimension_;\n\n};\n\n} // namespace data_association\n\n} // namespace laser_object_tracker\n\n\n\n#endif //LASER_OBJECT_TRACKER_DATA_ASSOCIATION_HUNGARIAN_ALGORITHM_HPP\n", "file_path": "include/laser_object_tracker/data_association/hungarian_algorithm.hpp", "rank": 69, "score": 65422.60678866495 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#ifndef LASER_OBJECT_TRACKER_DATA_ASSOCIATION_HUNGARIAN_ALGORITHM_HPP\n\n#define LASER_OBJECT_TRACKER_DATA_ASSOCIATION_HUNGARIAN_ALGORITHM_HPP\n\n\n\n#include \"laser_object_tracker/data_association/base_data_association.hpp\"\n\n\n\nnamespace Eigen {\n\nusing ArrayXXb = Array<bool, Dynamic, Dynamic>;\n\nusing ArrayXb = Array<bool, Dynamic, 1>;\n\nusing RowArrayXb = Array<bool, 1, Dynamic>;\n\n} // namespace Eigen\n\n\n\nnamespace laser_object_tracker {\n\nnamespace data_association {\n\n\n", "file_path": "include/laser_object_tracker/data_association/hungarian_algorithm.hpp", "rank": 70, "score": 65416.169098594284 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#ifndef LASER_OBJECT_TRACKER_FEATURE_EXTRACTION_FEATURES_FEATURES_HPP\n\n#define LASER_OBJECT_TRACKER_FEATURE_EXTRACTION_FEATURES_FEATURES_HPP\n\n\n\nnamespace laser_object_tracker {\n\nnamespace feature_extraction {\n\nnamespace features {\n\n\n", "file_path": "include/laser_object_tracker/feature_extraction/features/features.hpp", "rank": 71, "score": 65412.92983030366 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#ifndef LASER_OBJECT_TRACKER_SEGMENTATION_ADAPTIVE_BREAKPOINT_DETECTION_HPP\n\n#define LASER_OBJECT_TRACKER_SEGMENTATION_ADAPTIVE_BREAKPOINT_DETECTION_HPP\n\n\n\n#include \"laser_object_tracker/segmentation/base_segmentation.hpp\"\n\n\n\nnamespace laser_object_tracker {\n\nnamespace segmentation {\n\n\n", "file_path": "include/laser_object_tracker/segmentation/adaptive_breakpoint_detection.hpp", "rank": 72, "score": 65412.896328118004 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#ifndef LASER_OBJECT_TRACKER_FILTERING_OBB_AREA_FILTER_HPP\n\n#define LASER_OBJECT_TRACKER_FILTERING_OBB_AREA_FILTER_HPP\n\n\n\n#include \"laser_object_tracker/filtering/base_segmented_filtering.hpp\"\n\n\n\nnamespace laser_object_tracker {\n\nnamespace filtering {\n\n\n", "file_path": "include/laser_object_tracker/filtering/obb_area_filter.hpp", "rank": 73, "score": 65412.87871451743 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#ifndef LASER_OBJECT_TRACKER_FILTERING_POINTS_NUMBER_FILTER_HPP\n\n#define LASER_OBJECT_TRACKER_FILTERING_POINTS_NUMBER_FILTER_HPP\n\n\n\n#include \"laser_object_tracker/filtering/base_segmented_filtering.hpp\"\n\n\n\nnamespace laser_object_tracker {\n\nnamespace filtering {\n\n\n", "file_path": "include/laser_object_tracker/filtering/points_number_filter.hpp", "rank": 74, "score": 65412.87871451743 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#ifndef LASER_OBJECT_TRACKER_FILTERING_AGGREGATE_SEGMENTED_FILTERING_HPP\n\n#define LASER_OBJECT_TRACKER_FILTERING_AGGREGATE_SEGMENTED_FILTERING_HPP\n\n\n\n#include \"laser_object_tracker/filtering/base_segmented_filtering.hpp\"\n\n\n\nnamespace laser_object_tracker {\n\nnamespace filtering {\n\n\n", "file_path": "include/laser_object_tracker/filtering/aggregate_segmented_filtering.hpp", "rank": 75, "score": 65412.87871451743 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#ifndef LASER_OBJECT_TRACKER_FILTERING_BASE_SEGMENTED_FILTERING_HPP\n\n#define LASER_OBJECT_TRACKER_FILTERING_BASE_SEGMENTED_FILTERING_HPP\n\n\n\n#include \"laser_object_tracker/data_types/laser_scan_fragment.hpp\"\n\n\n\nnamespace laser_object_tracker {\n\nnamespace filtering {\n\n\n", "file_path": "include/laser_object_tracker/filtering/base_segmented_filtering.hpp", "rank": 76, "score": 65412.86115148409 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#ifndef LASER_OBJECT_TRACKER_FEATURE_EXTRACTION_FEATURE_EXTRACTION_HPP\n\n#define LASER_OBJECT_TRACKER_FEATURE_EXTRACTION_FEATURE_EXTRACTION_HPP\n\n\n\n#include \"laser_object_tracker/feature_extraction/features/features.hpp\"\n\n#include \"laser_object_tracker/feature_extraction/pcl/sac_model_cross2d.hpp\"\n\n#include \"laser_object_tracker/feature_extraction/base_feature_extraction.hpp\"\n\n#include \"laser_object_tracker/feature_extraction/random_sample_consensus_corner_detection.hpp\"\n\n#include \"laser_object_tracker/feature_extraction/random_sample_consensus_segment_detection.hpp\"\n\n#include \"laser_object_tracker/feature_extraction/search_based_corner_detection.hpp\"\n\n\n\n#endif // LASER_OBJECT_TRACKER_FEATURE_EXTRACTION_FEATURE_EXTRACTION_HPP\n", "file_path": "include/laser_object_tracker/feature_extraction/feature_extraction.hpp", "rank": 77, "score": 65409.502842355854 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#ifndef LASER_OBJECT_TRACKER_DATA_ASSOCIATION_DATA_ASSOCIATION_HPP\n\n#define LASER_OBJECT_TRACKER_DATA_ASSOCIATION_DATA_ASSOCIATION_HPP\n\n\n\n#include \"laser_object_tracker/data_association/base_data_association.hpp\"\n\n#include \"laser_object_tracker/data_association/hungarian_algorithm.hpp\"\n\n#include \"laser_object_tracker/data_association/naive_linear_assignment.hpp\"\n\n\n\n#endif // LASER_OBJECT_TRACKER_DATA_ASSOCIATION_DATA_ASSOCIATION_HPP\n", "file_path": "include/laser_object_tracker/data_association/data_association.hpp", "rank": 78, "score": 65409.250199490605 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#ifndef LASER_OBJECT_TRACKER_DATA_TYPES_DATA_TYPES_HPP\n\n#define LASER_OBJECT_TRACKER_DATA_TYPES_DATA_TYPES_HPP\n\n\n\n#include \"laser_object_tracker/data_types/definitions.hpp\"\n\n#include \"laser_object_tracker/data_types/laser_scan_fragment.hpp\"\n\n\n\n#endif // LASER_OBJECT_TRACKER_DATA_TYPES_DATA_TYPES_HPP\n", "file_path": "include/laser_object_tracker/data_types/data_types.hpp", "rank": 79, "score": 65409.096369224426 }, { "content": "/*********************************************************************\n\n*\n\n* BSD 3-Clause License\n\n*\n\n* Copyright (c) 2019, Piotr Pokorski\n\n* All rights reserved.\n\n*\n\n* Redistribution and use in source and binary forms, with or without\n\n* modification, are permitted provided that the following conditions are met:\n\n*\n\n* 1. Redistributions of source code must retain the above copyright notice, this\n\n* list of conditions and the following disclaimer.\n\n*\n\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n\n* this list of conditions and the following disclaimer in the documentation\n\n* and/or other materials provided with the distribution.\n\n*\n\n* 3. Neither the name of the copyright holder nor the names of its\n\n* contributors may be used to endorse or promote products derived from\n\n* this software without specific prior written permission.\n", "file_path": "include/laser_object_tracker/data_types/data_types.hpp", "rank": 80, "score": 65399.75242702672 }, { "content": "/*********************************************************************\n\n*\n\n* BSD 3-Clause License\n\n*\n\n* Copyright (c) 2019, Piotr Pokorski\n\n* All rights reserved.\n\n*\n\n* Redistribution and use in source and binary forms, with or without\n\n* modification, are permitted provided that the following conditions are met:\n\n*\n\n* 1. Redistributions of source code must retain the above copyright notice, this\n\n* list of conditions and the following disclaimer.\n\n*\n\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n\n* this list of conditions and the following disclaimer in the documentation\n\n* and/or other materials provided with the distribution.\n\n*\n\n* 3. Neither the name of the copyright holder nor the names of its\n\n* contributors may be used to endorse or promote products derived from\n\n* this software without specific prior written permission.\n", "file_path": "include/laser_object_tracker/segmentation/adaptive_breakpoint_detection.hpp", "rank": 81, "score": 65399.75242702672 }, { "content": "class Bool {\n\n public:\n\n /**\n\n * @brief Implicit conversion c-tor from bool type.\n\n * @param value Value to be initialized to.\n\n */\n\n Bool(bool value) : value_(value) {}\n\n\n\n /**\n\n * @brief Conversion operator to type bool&.\n\n * @return Reference to underlying bool value.\n\n */\n\n operator bool&() {\n\n return value_;\n\n }\n\n /**\n\n * @brief Conversion operator to type const bool&.\n\n * @return Const reference to underlying bool value.\n\n */\n\n operator const bool&() const {\n", "file_path": "include/laser_object_tracker/data_types/definitions.hpp", "rank": 82, "score": 65399.75242702672 }, { "content": "/*********************************************************************\n\n*\n\n* BSD 3-Clause License\n\n*\n\n* Copyright (c) 2019, Piotr Pokorski\n\n* All rights reserved.\n\n*\n\n* Redistribution and use in source and binary forms, with or without\n\n* modification, are permitted provided that the following conditions are met:\n\n*\n\n* 1. Redistributions of source code must retain the above copyright notice, this\n\n* list of conditions and the following disclaimer.\n\n*\n\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n\n* this list of conditions and the following disclaimer in the documentation\n\n* and/or other materials provided with the distribution.\n\n*\n\n* 3. Neither the name of the copyright holder nor the names of its\n\n* contributors may be used to endorse or promote products derived from\n\n* this software without specific prior written permission.\n", "file_path": "include/laser_object_tracker/feature_extraction/feature_extraction.hpp", "rank": 83, "score": 65399.75242702672 }, { "content": "/*********************************************************************\n\n*\n\n* BSD 3-Clause License\n\n*\n\n* Copyright (c) 2019, Piotr Pokorski\n\n* All rights reserved.\n\n*\n\n* Redistribution and use in source and binary forms, with or without\n\n* modification, are permitted provided that the following conditions are met:\n\n*\n\n* 1. Redistributions of source code must retain the above copyright notice, this\n\n* list of conditions and the following disclaimer.\n\n*\n\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n\n* this list of conditions and the following disclaimer in the documentation\n\n* and/or other materials provided with the distribution.\n\n*\n\n* 3. Neither the name of the copyright holder nor the names of its\n\n* contributors may be used to endorse or promote products derived from\n\n* this software without specific prior written permission.\n", "file_path": "include/laser_object_tracker/data_association/data_association.hpp", "rank": 84, "score": 65399.75242702672 }, { "content": "/*********************************************************************\n\n*\n\n* BSD 3-Clause License\n\n*\n\n* Copyright (c) 2019, Piotr Pokorski\n\n* All rights reserved.\n\n*\n\n* Redistribution and use in source and binary forms, with or without\n\n* modification, are permitted provided that the following conditions are met:\n\n*\n\n* 1. Redistributions of source code must retain the above copyright notice, this\n\n* list of conditions and the following disclaimer.\n\n*\n\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n\n* this list of conditions and the following disclaimer in the documentation\n\n* and/or other materials provided with the distribution.\n\n*\n\n* 3. Neither the name of the copyright holder nor the names of its\n\n* contributors may be used to endorse or promote products derived from\n\n* this software without specific prior written permission.\n", "file_path": "include/laser_object_tracker/filtering/aggregate_segmented_filtering.hpp", "rank": 85, "score": 65399.75242702672 }, { "content": "/*********************************************************************\n\n*\n\n* BSD 3-Clause License\n\n*\n\n* Copyright (c) 2019, Piotr Pokorski\n\n* All rights reserved.\n\n*\n\n* Redistribution and use in source and binary forms, with or without\n\n* modification, are permitted provided that the following conditions are met:\n\n*\n\n* 1. Redistributions of source code must retain the above copyright notice, this\n\n* list of conditions and the following disclaimer.\n\n*\n\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n\n* this list of conditions and the following disclaimer in the documentation\n\n* and/or other materials provided with the distribution.\n\n*\n\n* 3. Neither the name of the copyright holder nor the names of its\n\n* contributors may be used to endorse or promote products derived from\n\n* this software without specific prior written permission.\n", "file_path": "include/laser_object_tracker/data_association/hungarian_algorithm.hpp", "rank": 86, "score": 65399.75242702672 }, { "content": "/*********************************************************************\n\n*\n\n* BSD 3-Clause License\n\n*\n\n* Copyright (c) 2019, Piotr Pokorski\n\n* All rights reserved.\n\n*\n\n* Redistribution and use in source and binary forms, with or without\n\n* modification, are permitted provided that the following conditions are met:\n\n*\n\n* 1. Redistributions of source code must retain the above copyright notice, this\n\n* list of conditions and the following disclaimer.\n\n*\n\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n\n* this list of conditions and the following disclaimer in the documentation\n\n* and/or other materials provided with the distribution.\n\n*\n\n* 3. Neither the name of the copyright holder nor the names of its\n\n* contributors may be used to endorse or promote products derived from\n\n* this software without specific prior written permission.\n", "file_path": "include/laser_object_tracker/feature_extraction/features/features.hpp", "rank": 87, "score": 65399.75242702672 }, { "content": "/*********************************************************************\n\n*\n\n* BSD 3-Clause License\n\n*\n\n* Copyright (c) 2019, Piotr Pokorski\n\n* All rights reserved.\n\n*\n\n* Redistribution and use in source and binary forms, with or without\n\n* modification, are permitted provided that the following conditions are met:\n\n*\n\n* 1. Redistributions of source code must retain the above copyright notice, this\n\n* list of conditions and the following disclaimer.\n\n*\n\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n\n* this list of conditions and the following disclaimer in the documentation\n\n* and/or other materials provided with the distribution.\n\n*\n\n* 3. Neither the name of the copyright holder nor the names of its\n\n* contributors may be used to endorse or promote products derived from\n\n* this software without specific prior written permission.\n", "file_path": "include/laser_object_tracker/filtering/points_number_filter.hpp", "rank": 88, "score": 65399.75242702672 }, { "content": "/*********************************************************************\n\n*\n\n* BSD 3-Clause License\n\n*\n\n* Copyright (c) 2019, Piotr Pokorski\n\n* All rights reserved.\n\n*\n\n* Redistribution and use in source and binary forms, with or without\n\n* modification, are permitted provided that the following conditions are met:\n\n*\n\n* 1. Redistributions of source code must retain the above copyright notice, this\n\n* list of conditions and the following disclaimer.\n\n*\n\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n\n* this list of conditions and the following disclaimer in the documentation\n\n* and/or other materials provided with the distribution.\n\n*\n\n* 3. Neither the name of the copyright holder nor the names of its\n\n* contributors may be used to endorse or promote products derived from\n\n* this software without specific prior written permission.\n", "file_path": "include/laser_object_tracker/filtering/obb_area_filter.hpp", "rank": 89, "score": 65399.75242702672 }, { "content": "/*********************************************************************\n\n*\n\n* BSD 3-Clause License\n\n*\n\n* Copyright (c) 2019, Piotr Pokorski\n\n* All rights reserved.\n\n*\n\n* Redistribution and use in source and binary forms, with or without\n\n* modification, are permitted provided that the following conditions are met:\n\n*\n\n* 1. Redistributions of source code must retain the above copyright notice, this\n\n* list of conditions and the following disclaimer.\n\n*\n\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n\n* this list of conditions and the following disclaimer in the documentation\n\n* and/or other materials provided with the distribution.\n\n*\n\n* 3. Neither the name of the copyright holder nor the names of its\n\n* contributors may be used to endorse or promote products derived from\n\n* this software without specific prior written permission.\n", "file_path": "include/laser_object_tracker/filtering/base_segmented_filtering.hpp", "rank": 90, "score": 65399.75242702672 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#ifndef LASER_OBJECT_TRACKER_DATA_TYPES_LASER_SCAN_FRAGMENT_HPP\n\n#define LASER_OBJECT_TRACKER_DATA_TYPES_LASER_SCAN_FRAGMENT_HPP\n\n\n\n// ROS\n\n#include <laser_geometry/laser_geometry.h>\n\n\n\n// PROJECT\n\n#include \"laser_object_tracker/data_types/definitions.hpp\"\n\n\n\nnamespace laser_object_tracker {\n\nnamespace data_types {\n\n\n\n/**\n\n * @brief Container-type class consisting of LaserScan measurement, corresponding PointCloud and Occlusion vector\n\n * informing whether each point is occluded or not by its neighbours.\n\n */\n", "file_path": "include/laser_object_tracker/data_types/laser_scan_fragment.hpp", "rank": 91, "score": 64032.85606226058 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#ifndef LASER_OBJECT_TRACKER_DATA_ASSOCIATION_NAIVE_LINEAR_ASSIGNMENT_HPP\n\n#define LASER_OBJECT_TRACKER_DATA_ASSOCIATION_NAIVE_LINEAR_ASSIGNMENT_HPP\n\n\n\n#include \"laser_object_tracker/data_association/base_data_association.hpp\"\n\n\n\nnamespace laser_object_tracker {\n\nnamespace data_association {\n\n\n", "file_path": "include/laser_object_tracker/data_association/naive_linear_assignment.hpp", "rank": 92, "score": 64030.01002729893 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#ifndef LASER_OBJECT_TRACKER_FEATURE_EXTRACTION_BASE_FEATURE_EXTRACTION_HPP\n\n#define LASER_OBJECT_TRACKER_FEATURE_EXTRACTION_BASE_FEATURE_EXTRACTION_HPP\n\n\n\n#include \"laser_object_tracker/data_types/laser_scan_fragment.hpp\"\n\n\n\nnamespace laser_object_tracker {\n\nnamespace feature_extraction {\n\n\n", "file_path": "include/laser_object_tracker/feature_extraction/base_feature_extraction.hpp", "rank": 93, "score": 64030.01002729893 }, { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\n* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\n* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\n* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*********************************************************************/\n\n\n\n#ifndef LASER_OBJECT_TRACKER_DATA_ASSOCIATION_BASE_DATA_ASSOCIATION_HPP\n\n#define LASER_OBJECT_TRACKER_DATA_ASSOCIATION_BASE_DATA_ASSOCIATION_HPP\n\n\n\n#include <Eigen/Core>\n\n\n\nnamespace laser_object_tracker {\n\nnamespace data_association {\n\n\n", "file_path": "include/laser_object_tracker/data_association/base_data_association.hpp", "rank": 94, "score": 64029.90355607481 }, { "content": " Reference at(size_t index);\n\n\n\n ConstReference at(size_t index) const;\n\n\n\n Reference operator[](size_t index);\n\n\n\n ConstReference operator[](size_t index) const;\n\n\n\n Reference front();\n\n\n\n ConstReference front() const;\n\n\n\n Reference back();\n\n\n\n ConstReference back() const;\n\n\n\n /**\n\n *\n\n * @return True if the container is empty, false otherwise\n\n */\n", "file_path": "include/laser_object_tracker/data_types/laser_scan_fragment.hpp", "rank": 95, "score": 64027.505424463794 }, { "content": " * @return Iterator pointing to the first measurement (counting from min to max angle)\n\n */\n\n Iterator begin();\n\n /**\n\n *\n\n * @return Const iterator pointing to the first measurement (counting from min to max angle)\n\n */\n\n ConstIterator cbegin() const;\n\n\n\n /**\n\n *\n\n * @return Iterator pointing to the one measurement beyond last (counting from min to max angle)\n\n */\n\n Iterator end();\n\n /**\n\n *\n\n * @return Const iterator pointing to the one measurement beyond last (counting from min to max angle)\n\n */\n\n ConstIterator cend() const;\n\n\n", "file_path": "include/laser_object_tracker/data_types/laser_scan_fragment.hpp", "rank": 96, "score": 64027.2766308965 }, { "content": " * @param other Prototype container\n\n * @param first First element of the range, included\n\n * @param last Last element of the range, not included\n\n */\n\n LaserScanFragment(const LaserScanFragment& other, long first, long last);\n\n\n\n /**\n\n *\n\n * @return Header of LaserScanType measurement\n\n */\n\n std_msgs::Header getHeader() const {\n\n return laser_scan_.header;\n\n }\n\n\n\n /**\n\n *\n\n * @return Min angle of the measurement (in polar coordinates)\n\n */\n\n double getAngleMin() const {\n\n return laser_scan_.angle_min;\n", "file_path": "include/laser_object_tracker/data_types/laser_scan_fragment.hpp", "rank": 97, "score": 64025.90779545393 }, { "content": " LaserScanType laser_scan_;\n\n OcclusionType occlusion_vector_;\n\n PointCloudType laser_scan_cloud_;\n\n ContainerType elements_;\n\n};\n\n} // namespace data_types\n\n} // namespace laser_object_tracker\n\n\n\n#endif // LASER_OBJECT_TRACKER_DATA_TYPES_LASER_SCAN_FRAGMENT_HPP\n", "file_path": "include/laser_object_tracker/data_types/laser_scan_fragment.hpp", "rank": 98, "score": 64025.74345520761 }, { "content": " }\n\n\n\n /**\n\n *\n\n * @return Max angle of the measurement (in polar coordinates)\n\n */\n\n double getAngleMax() const {\n\n return laser_scan_.angle_max;\n\n }\n\n\n\n /**\n\n *\n\n * @return Angle resolution of the laser scanner\n\n */\n\n double getAngleIncrement() const {\n\n return laser_scan_.angle_increment;\n\n }\n\n\n\n /**\n\n *\n", "file_path": "include/laser_object_tracker/data_types/laser_scan_fragment.hpp", "rank": 99, "score": 64021.03211602552 } ]
C++
src/rendering/ui.cpp
hyp/Arpheg
78d142c15028da7c0c2ef4503bed6bcfd1ced67d
#include <limits> #include <string.h> #include "../core/assert.h" #include "../core/allocatorNew.h" #include "../core/bufferArray.h" #include "../services.h" #include "rendering.h" #include "ui.h" #include "../data/font/font.h" #include "2d.h" #include "text.h" #include "opengl/gl.h" namespace rendering { namespace ui { enum { NormalGeometry, TextGeometry, OutlinedTextGeometry }; Batch::Batch() : verticesSize(0),indicesSize(0),primitive(topology::Triangle),name("") { layer=depth = 0; } struct BatchImpl { uint32 layerDepth; core::BufferAllocator vertices; core::BufferAllocator indices; uint32 meshId; uint32 vertexSize; int pipelineId; const data::Font* font; uint32 textureId; BatchImpl(const Batch& batch); BatchImpl(const BatchImpl& other,uint32 layer,uint32 texture); inline bool operator < (const BatchImpl& other){ return this->layerDepth < other.layerDepth; } }; BatchImpl::BatchImpl(const Batch& batch) : vertices(batch.verticesSize?batch.verticesSize: 2048,services::threadSafeFrameAllocator(),core::BufferAllocator::GrowOnOverflow), indices(batch.indicesSize? batch.indicesSize: 1024,services::threadSafeFrameAllocator() ,core::BufferAllocator::GrowOnOverflow) { assert(batch.layer <= Batch::kMaxLayer); assert(batch.depth <= Batch::kMaxDepth); layerDepth = (batch.layer<<8) | batch.depth; meshId = 0; font = nullptr; textureId = 0; } BatchImpl::BatchImpl(const BatchImpl& other,uint32 layer,uint32 texture) : vertices(2048,services::threadSafeFrameAllocator(),core::BufferAllocator::GrowOnOverflow), indices( 1024,services::threadSafeFrameAllocator() ,core::BufferAllocator::GrowOnOverflow) { assert(layer <= Batch::kMaxLayer); layerDepth = (layer << 8) | (other.layerDepth & Batch::kMaxDepth); meshId = other.meshId; font = other.font; textureId = texture; vertexSize = other.vertexSize; pipelineId = other.pipelineId; } uint32 Service::registerBatch(const Batch& batch,int pipelineId,uint32 meshId ) { using namespace core::bufferArray; auto bimpl = new(batches_.allocate(sizeof(BatchImpl),alignof(BatchImpl))) BatchImpl(batch); bimpl->meshId = meshId; bimpl->vertexSize = meshes_[meshId].vertexSize; bimpl->pipelineId = pipelineId; return uint32(length<BatchImpl>(batches_)-1); } uint32 Service::cloneBatch(uint32 id,uint32 layerId,uint32 textureId) { using namespace core::bufferArray; auto bimpl = new(batches_.allocate(sizeof(BatchImpl),alignof(BatchImpl))) BatchImpl(nth<BatchImpl>(batches_,id),layerId,textureId); return uint32(length<BatchImpl>(batches_)-1); } struct BatchFontMapping { const data::Font* key; uint32 value; }; Service::UniquePipeline::UniquePipeline(Pipeline pipeline) :matrixConstant("matrix"),texturesConstant("textures") { this->pipeline = pipeline; } uint32 Service::uiPipeline(const rendering::Pipeline& pipeline) { for(uint32 i = 0;i<kMaxPipelines;++i){ if(pipelines_[i].pipeline == pipeline) return i; } for(uint32 dest = kMaxDefaultPipelines;dest<kMaxPipelines;++dest){ if(pipelines_[dest].pipeline == Pipeline::nullPipeline()){ pipelines_[dest] = UniquePipeline(pipeline); return dest; } } assertRelease(false && "Can't register a new ui pipeline!"); return 0; } uint32 Service::uiTexture (const rendering::Texture2D& texture) { for(uint32 i = 0;i<kMaxTextures;++i){ if(textures_[i] == texture) return i; } for(uint32 dest = 0;dest<kMaxTextures;++dest){ if(textures_[dest] == Texture2D::null()){ textures_[dest] = texture; return dest; } } assertRelease(false && "Can't register a new ui texture - need mores storage units!"); return 0; } bool Service::loadCorePipeline(int id,const char* name) { int& pipe = defaultPipelines_[id]; if(pipe == -1){ if(auto asset = services::data()->pipeline(services::data()->bundle("core",true),name,true)){ pipe = id; assert(pipelines_[id].pipeline == Pipeline::nullPipeline()); pipelines_[id] = UniquePipeline(asset->pipeline()); } else { pipe = -2; return false; } } return true; } uint32 Service::registerFontBatch(const data::Font* font) { if(font->renderingType() == text::fontType::Outlined) loadCorePipeline(OutlinedTextPipeline,"rendering.text.outlined.pipeline"); else loadCorePipeline(TextPipeline,"rendering.text.pipeline"); Batch batch; batch.name = "font"; batch.depth = Batch::kMaxDepth; auto id = registerBatch(batch, font->renderingType() == text::fontType::Outlined? OutlinedTextPipeline : TextPipeline, font->renderingType() == text::fontType::Outlined? OutlinedTextGeometry : TextGeometry); core::bufferArray::nth<BatchImpl>(batches_,id).font = font; BatchFontMapping map = {font,id}; core::bufferArray::add<BatchFontMapping>(fontBatches_,map); return id; } Batch::Geometry Service::allocate(uint32 layerId,const data::Font* font,uint32 vertexCount,uint32 indexCount) { uint32 batchId = 0xFFFF; using namespace core::bufferArray; for(const BatchFontMapping* i = begin<BatchFontMapping>(fontBatches_),*e = end<BatchFontMapping>(fontBatches_);i<e;++i){ if(i->key == font){ batchId = i->value; break; } } if(batchId == 0xFFFF) batchId = registerFontBatch(font); return allocate(layerId,batchId,0,vertexCount,indexCount); } Batch::Geometry Service::allocate(uint32 layerId,uint32 batchId,uint32 textureId,uint32 vertexCount,uint32 indexCount) { assert(batchId < core::bufferArray::length<BatchImpl>(batches_)); auto batch = core::bufferArray::begin<BatchImpl>(batches_) + batchId; if(batch->textureId != textureId){ batch = core::bufferArray::begin<BatchImpl>(batches_) + cloneBatch(batchId,layerId,textureId); } Batch::Geometry result = { batch->vertices.size()/batch->vertexSize, (float*)batch->vertices.allocate(batch->vertexSize*vertexCount), indexCount? (uint16*)batch->indices.allocate(sizeof(uint16)*indexCount) : nullptr }; return result; } static VertexDescriptor meshVertexDescriptor(uint32 i){ return i == NormalGeometry? draw2D::positionInt16::vertexLayout(draw2D::mode::Textured|draw2D::mode::Coloured) : i == TextGeometry? text::vertexLayout(text::fontType::Default) : text::vertexLayout(text::fontType::Outlined) ; } static uint32 vertexSize(uint32 i){ auto layout = meshVertexDescriptor(i); uint32 sz = 0; for(uint32 i = 0;i<layout.count;++i){ sz += layout.fields[i].size(); } return sz; } void Service::prepareRendering() { using namespace core::bufferArray; loadCorePipeline(TexturedColouredPipeline,"rendering.2d.textured.coloured.pipeline"); loadCorePipeline(ColouredPipeline,"rendering.2d.coloured.pipeline"); pointSampler_ = services::data()->sampler(services::data()->bundle("core",true),"rendering.sampler.point",true); fontSampler_ = pointSampler_; auto batchCount = length<BatchImpl>(batches_); uint32 storage[1024]; if(batchCount > (sizeof(storage)/sizeof(storage[0]))){ assert(false && "Can't sort the ui batches"); return; } for(size_t i = 0;i<batchCount;++i){ storage[i] = (uint32(i)<<16) | nth<BatchImpl>(batches_,i).layerDepth; } struct Pred{ inline bool operator ()(uint32 a,uint32 b) { return (a&0xFFFF) < (b&0xFFFF); } }; std::sort(storage,storage+batchCount,Pred()); } void Service::render(const mat44f& matrix) { auto renderer = services::rendering(); renderer->bind(blending::alpha()); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); using namespace core::bufferArray; struct MeshSupport { size_t requiredVertexSize; size_t requiredIndexSize; uint32 vertexOffset,indexOffset; Buffer::Mapping vertexMapping,indexMapping; bool justCreated; inline uint8* vertices(uint32 vertexSize){ return ((uint8*)vertexMapping.data) + vertexOffset*vertexSize; } inline uint8* indices(){ return ((uint8*)indexMapping.data) + indexOffset*sizeof(uint16); } }; MeshSupport meshSupport[kMaxGeometries]; struct BatchSupport { bool draw,indexed; uint32 baseVertex; uint32 offset,count; }; for(uint32 i = 0;i<kMaxGeometries;++i){ meshSupport[i].requiredVertexSize = meshSupport[i].requiredIndexSize = 0; meshSupport[i].justCreated = false; } for(BatchImpl* i = begin<BatchImpl>(batches_),*e = end<BatchImpl>(batches_);i<e;++i){ meshSupport[i->meshId].requiredVertexSize+= i->vertices.size(); meshSupport[i->meshId].requiredIndexSize += i->indices.size(); } for(uint32 i = 0;i<kMaxGeometries;++i){ auto mesh = meshes_ + i; if(mesh->vbo.isNull()){ mesh->vbo = renderer->create(rendering::Buffer::Vertex,true,meshSupport[i].requiredVertexSize); mesh->ibo = renderer->create(rendering::Buffer::Index,true,meshSupport[i].requiredIndexSize); mesh->mesh = renderer->create(mesh->vbo,mesh->ibo,meshVertexDescriptor(i)); meshSupport[i].justCreated = true; } } size_t batchCount = length<BatchImpl>(batches_); BatchSupport* batchSupport = (BatchSupport*)services::frameAllocator()->allocate(sizeof(BatchSupport)*batchCount,alignof(BatchSupport)); for(uint32 i = 0;i<kMaxGeometries;++i){ auto mesh = meshes_ + i; if(!meshSupport[i].justCreated){ renderer->recreate(rendering::Buffer::Vertex,mesh->vbo,true,meshSupport[i].requiredVertexSize); renderer->recreate(rendering::Buffer::Index,mesh->ibo,true,meshSupport[i].requiredIndexSize); } if(meshSupport[i].requiredVertexSize > 0){ meshSupport[i].vertexMapping = renderer->map(rendering::Buffer::Vertex,mesh->vbo); meshSupport[i].vertexOffset = 0; } if(meshSupport[i].requiredIndexSize > 0){ meshSupport[i].indexMapping = renderer->map(rendering::Buffer::Index,mesh->ibo); meshSupport[i].indexOffset = 0; } } for(size_t i = 0;i<batchCount;++i){ const BatchImpl* batch = begin<BatchImpl>(batches_) + i; BatchSupport support; support.draw = false; if(batch->vertices.size()){ support.baseVertex = meshSupport[batch->meshId].vertexOffset; support.draw = true; memcpy(meshSupport[batch->meshId].vertices(batch->vertexSize),batch->vertices.bufferBase(),batch->vertices.size()); support.offset = uint32(meshSupport[batch->meshId].vertexOffset); uint32 vertexCount = uint32(batch->vertices.size()/batch->vertexSize); support.count = vertexCount; meshSupport[batch->meshId].vertexOffset+=vertexCount; } if(batch->indices.size()){ support.indexed = true; memcpy(meshSupport[batch->meshId].indices(),batch->indices.bufferBase(),batch->indices.size()); support.offset = uint32(meshSupport[batch->meshId].indexOffset)*sizeof(uint16); uint32 indexCount = uint32(batch->indices.size()/sizeof(uint16)); support.count = indexCount; meshSupport[batch->meshId].indexOffset+=indexCount; } batchSupport[i] = support; } for(uint32 i = 0;i<kMaxGeometries;++i){ if(meshSupport[i].requiredVertexSize > 0) renderer->unmap(meshSupport[i].vertexMapping); if(meshSupport[i].requiredIndexSize > 0) renderer->unmap(meshSupport[i].indexMapping); } if(!(textures_[0] == Texture2D::null())){ renderer->bind(textures_[0],0); renderer->bind(pointSampler_,0); } uint32 currentBoundMesh = kMaxGeometries; Pipeline currentBoundPipeline = Pipeline::nullPipeline(); bool constantsBound[kMaxPipelines] = {false}; bool textureUnitsBound[kMaxPipelines] = {false}; for(size_t i = 0;i<batchCount;++i){ if(!batchSupport[i].draw) continue; const BatchImpl* batch = begin<BatchImpl>(batches_) + i; if(!(pipelines_[batch->pipelineId].pipeline == currentBoundPipeline)){ renderer->bind(pipelines_[batch->pipelineId].pipeline); if(!constantsBound[batch->pipelineId]){ renderer->bind(pipelines_[batch->pipelineId].matrixConstant,matrix); constantsBound[batch->pipelineId] = true; } if(batch->font){ int fontTextureUnit = 2; renderer->bind(batch->font->pages_[0],fontTextureUnit); renderer->bind(fontSampler_,fontTextureUnit); renderer->bind(pipelines_[batch->pipelineId].texturesConstant,&fontTextureUnit); } else { if(batch->textureId != 0){ int unit = 1; renderer->bind(textures_[batch->textureId],unit); renderer->bind(pointSampler_,unit); renderer->bind(pipelines_[batch->pipelineId].texturesConstant,&unit); textureUnitsBound[batch->pipelineId] = false; } else if(!textureUnitsBound[batch->pipelineId]) { int unit = 0 ; renderer->bind(pipelines_[batch->pipelineId].texturesConstant,&unit); textureUnitsBound[batch->pipelineId] = true; } } } if(currentBoundMesh != batch->meshId){ renderer->bind(meshes_[batch->meshId].mesh,rendering::topology::Triangle,sizeof(uint16)); currentBoundMesh = batch->meshId; } if(batchSupport[i].indexed) renderer->drawIndexed(batchSupport[i].offset,batchSupport[i].count,batchSupport[i].baseVertex); else renderer->draw(batchSupport[i].offset,batchSupport[i].count); } glEnable(GL_DEPTH_TEST); renderer->bind(blending::disabled()); } void Service::servicePreStep(){ new(&fontBatches_) core::BufferAllocator(sizeof(BatchFontMapping)*32,services::frameAllocator(),core::BufferAllocator::GrowOnOverflow); new(&batches_) core::BufferAllocator(sizeof(BatchImpl)*64,services::frameAllocator(),core::BufferAllocator::GrowOnOverflow); for(uint32 dest = 0;dest<kMaxTextures;++dest){ textures_[dest] = Texture2D::null(); } } void Service::servicePostStep(){ } Service::Service() : batches_(128,services::frameAllocator()), fontBatches_(128,services::frameAllocator()) { for(uint32 i = 0;i<kMaxDefaultPipelines;++i) defaultPipelines_[i] = -1; for(uint32 i = 0; i<kMaxGeometries;++i){ meshes_[i].vertexSize = vertexSize(i); meshes_[i].vbo = meshes_[i].ibo = Buffer::nullBuffer(); } } Service::~Service(){ using namespace core::bufferArray; auto renderer = services::rendering(); for(uint32 i = 0; i<kMaxGeometries;++i){ if(!meshes_[i].vbo.isNull()){ renderer->release(meshes_[i].mesh); renderer->release(meshes_[i].vbo); if(meshes_[i].ibo.isNull()) renderer->release(meshes_[i].ibo); } } } } }
#include <limits> #include <string.h> #include "../core/assert.h" #include "../core/allocatorNew.h" #include "../core/bufferArray.h" #include "../services.h" #include "rendering.h" #include "ui.h" #include "../data/font/font.h" #include "2d.h" #include "text.h" #include "opengl/gl.h" namespace rendering { namespace ui { enum { NormalGeometry, TextGeometry, OutlinedTextGeometry }; Batch::Batch() : verticesSize(0),indicesSize(0),primitive(topology::Triangle),name("") { layer=depth = 0; } struct BatchImpl { uint32 layerDepth; core::BufferAllocator vertices; core::BufferAllocator indices; uint32 meshId; uint32 vertexSize; int pipelineId; const data::Font* font; uint32 textureId; BatchImpl(const Batch& batch); BatchImpl(const BatchImpl& other,uint32 layer,uint32 texture); inline bool operator < (const BatchImpl& other){ return this->layerDepth < other.layerDepth; } }; BatchImpl::BatchImpl(const Batch& batch) : vertices(batch.verticesSize?batch.verticesSize: 2048,services::threadSafeFrameAllocator(),core::BufferAllocator::GrowOnOverflow), indices(batch.indicesSize? batch.indicesSize: 1024,services::threadSafeFrameAllocator() ,core::BufferAllocator::GrowOnOverflow) { assert(batch.layer <= Batch::kMaxLayer); assert(batch.depth <= Batch::kMaxDepth); layerDepth = (batch.layer<<8) | batch.depth; meshId = 0; font = nullptr; textureId = 0; } BatchImpl::BatchImpl(const BatchImpl& other,uint32 layer,uint32 texture) : vertices(2048,services::threadSafeFrameAllocator(),core::BufferAllocator::GrowOnOverflow), indices( 1024,services::threadSafeFrameAllocator() ,core::BufferAllocator::GrowOnOverflow) { assert(layer <= Batch::kMaxLayer); layerDepth = (layer << 8) | (other.layerDepth & Batch::kMaxDepth); meshId = other.meshId; font = other.font; textureId = texture; vertexSize = other.vertexSize; pipelineId = other.pipelineId; } uint32 Service::registerBatch(const Batch& batch,int pipelineId,uint32 meshId ) { using namespace core::bufferArray; auto bimpl = new(batches_.allocate(sizeof(BatchImpl),alignof(BatchImpl))) BatchImpl(batch); bimpl->meshId = meshId; bimpl->vertexSize = meshes_[meshId].vertexSize; bimpl->pipelineId = pipelineId; return uint32(length<BatchImpl>(batches_)-1); } uint32 Service::cloneBatch(uint32 id,uint32 layerId,uint32 textureId) { using namespace core::bufferArray; auto bimpl = new(batches_.allocate(sizeof(BatchImpl),alignof(BatchImpl))) BatchImpl(nth<BatchImpl>(batches_,id),layerId,textureId); return uint32(length<BatchImpl>(batches_)-1); } struct BatchFontMapping { const data::Font* key; uint32 value; }; Service::UniquePipeline::UniquePipeline(Pipeline pipeline) :matrixConstant("matrix"),texturesConstant("textures") { this->pipeline = pipeline; } uint32 Service::uiPipeline(const rendering::Pipeline& pipeline) { for(uint32 i = 0;i<kMaxPipelines;++i){ if(pipelines_[i].pipeline == pipeline) return i; } for(uint32 dest = kMaxDefaultPipelines;dest<kMaxPipelines;++dest){ if(pipelines_[dest].pipeline == Pipeline::nullPipeline()){ pipelines_[dest] = UniquePipeline(pipeline); return dest; } } assertRelease(false && "Can't register a new ui pipeline!"); return 0; } uint32 Service::uiTexture (const rendering::Texture2D& texture) { for(uint32 i = 0;i<kMaxTextures;++i){ if(textures_[i] == texture) return i; } for(uint32 dest = 0;dest<kMaxTextures;++dest){ if(textures_[dest] == Texture2D::null()){ textures_[dest] = texture; return dest; } } assertRelease(false && "Can't register a new ui texture - need mores storage units!"); return 0; } bool Service::loadCorePipeline(int id,const char* name) { int& pipe = defaultPipelines_[id]; if(pipe == -1){ if(auto asset = services::data()->pipeline(services::data()->bundle("core",true),name,true)){ pipe = id; assert(pipelines_[id].pipeline == Pipeline::nullPipeline()); pipelines_[id] = UniquePipeline(asset->pipeline()); } else { pipe = -2; return false; } } return true; } uint32 Service::registerFontBatch(const data::Font* font) { if(font->renderingType() == text::fontType::Outlined) loadCorePipeline(OutlinedTextPipeline,"rendering.text.outlined.pipeline"); else loadCorePipeline(TextPipeline,"rendering.text.pipeline"); Batch batch; batch.name = "font"; batch.depth = Batch::kMaxDepth; auto id =
; core::bufferArray::nth<BatchImpl>(batches_,id).font = font; BatchFontMapping map = {font,id}; core::bufferArray::add<BatchFontMapping>(fontBatches_,map); return id; } Batch::Geometry Service::allocate(uint32 layerId,const data::Font* font,uint32 vertexCount,uint32 indexCount) { uint32 batchId = 0xFFFF; using namespace core::bufferArray; for(const BatchFontMapping* i = begin<BatchFontMapping>(fontBatches_),*e = end<BatchFontMapping>(fontBatches_);i<e;++i){ if(i->key == font){ batchId = i->value; break; } } if(batchId == 0xFFFF) batchId = registerFontBatch(font); return allocate(layerId,batchId,0,vertexCount,indexCount); } Batch::Geometry Service::allocate(uint32 layerId,uint32 batchId,uint32 textureId,uint32 vertexCount,uint32 indexCount) { assert(batchId < core::bufferArray::length<BatchImpl>(batches_)); auto batch = core::bufferArray::begin<BatchImpl>(batches_) + batchId; if(batch->textureId != textureId){ batch = core::bufferArray::begin<BatchImpl>(batches_) + cloneBatch(batchId,layerId,textureId); } Batch::Geometry result = { batch->vertices.size()/batch->vertexSize, (float*)batch->vertices.allocate(batch->vertexSize*vertexCount), indexCount? (uint16*)batch->indices.allocate(sizeof(uint16)*indexCount) : nullptr }; return result; } static VertexDescriptor meshVertexDescriptor(uint32 i){ return i == NormalGeometry? draw2D::positionInt16::vertexLayout(draw2D::mode::Textured|draw2D::mode::Coloured) : i == TextGeometry? text::vertexLayout(text::fontType::Default) : text::vertexLayout(text::fontType::Outlined) ; } static uint32 vertexSize(uint32 i){ auto layout = meshVertexDescriptor(i); uint32 sz = 0; for(uint32 i = 0;i<layout.count;++i){ sz += layout.fields[i].size(); } return sz; } void Service::prepareRendering() { using namespace core::bufferArray; loadCorePipeline(TexturedColouredPipeline,"rendering.2d.textured.coloured.pipeline"); loadCorePipeline(ColouredPipeline,"rendering.2d.coloured.pipeline"); pointSampler_ = services::data()->sampler(services::data()->bundle("core",true),"rendering.sampler.point",true); fontSampler_ = pointSampler_; auto batchCount = length<BatchImpl>(batches_); uint32 storage[1024]; if(batchCount > (sizeof(storage)/sizeof(storage[0]))){ assert(false && "Can't sort the ui batches"); return; } for(size_t i = 0;i<batchCount;++i){ storage[i] = (uint32(i)<<16) | nth<BatchImpl>(batches_,i).layerDepth; } struct Pred{ inline bool operator ()(uint32 a,uint32 b) { return (a&0xFFFF) < (b&0xFFFF); } }; std::sort(storage,storage+batchCount,Pred()); } void Service::render(const mat44f& matrix) { auto renderer = services::rendering(); renderer->bind(blending::alpha()); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); using namespace core::bufferArray; struct MeshSupport { size_t requiredVertexSize; size_t requiredIndexSize; uint32 vertexOffset,indexOffset; Buffer::Mapping vertexMapping,indexMapping; bool justCreated; inline uint8* vertices(uint32 vertexSize){ return ((uint8*)vertexMapping.data) + vertexOffset*vertexSize; } inline uint8* indices(){ return ((uint8*)indexMapping.data) + indexOffset*sizeof(uint16); } }; MeshSupport meshSupport[kMaxGeometries]; struct BatchSupport { bool draw,indexed; uint32 baseVertex; uint32 offset,count; }; for(uint32 i = 0;i<kMaxGeometries;++i){ meshSupport[i].requiredVertexSize = meshSupport[i].requiredIndexSize = 0; meshSupport[i].justCreated = false; } for(BatchImpl* i = begin<BatchImpl>(batches_),*e = end<BatchImpl>(batches_);i<e;++i){ meshSupport[i->meshId].requiredVertexSize+= i->vertices.size(); meshSupport[i->meshId].requiredIndexSize += i->indices.size(); } for(uint32 i = 0;i<kMaxGeometries;++i){ auto mesh = meshes_ + i; if(mesh->vbo.isNull()){ mesh->vbo = renderer->create(rendering::Buffer::Vertex,true,meshSupport[i].requiredVertexSize); mesh->ibo = renderer->create(rendering::Buffer::Index,true,meshSupport[i].requiredIndexSize); mesh->mesh = renderer->create(mesh->vbo,mesh->ibo,meshVertexDescriptor(i)); meshSupport[i].justCreated = true; } } size_t batchCount = length<BatchImpl>(batches_); BatchSupport* batchSupport = (BatchSupport*)services::frameAllocator()->allocate(sizeof(BatchSupport)*batchCount,alignof(BatchSupport)); for(uint32 i = 0;i<kMaxGeometries;++i){ auto mesh = meshes_ + i; if(!meshSupport[i].justCreated){ renderer->recreate(rendering::Buffer::Vertex,mesh->vbo,true,meshSupport[i].requiredVertexSize); renderer->recreate(rendering::Buffer::Index,mesh->ibo,true,meshSupport[i].requiredIndexSize); } if(meshSupport[i].requiredVertexSize > 0){ meshSupport[i].vertexMapping = renderer->map(rendering::Buffer::Vertex,mesh->vbo); meshSupport[i].vertexOffset = 0; } if(meshSupport[i].requiredIndexSize > 0){ meshSupport[i].indexMapping = renderer->map(rendering::Buffer::Index,mesh->ibo); meshSupport[i].indexOffset = 0; } } for(size_t i = 0;i<batchCount;++i){ const BatchImpl* batch = begin<BatchImpl>(batches_) + i; BatchSupport support; support.draw = false; if(batch->vertices.size()){ support.baseVertex = meshSupport[batch->meshId].vertexOffset; support.draw = true; memcpy(meshSupport[batch->meshId].vertices(batch->vertexSize),batch->vertices.bufferBase(),batch->vertices.size()); support.offset = uint32(meshSupport[batch->meshId].vertexOffset); uint32 vertexCount = uint32(batch->vertices.size()/batch->vertexSize); support.count = vertexCount; meshSupport[batch->meshId].vertexOffset+=vertexCount; } if(batch->indices.size()){ support.indexed = true; memcpy(meshSupport[batch->meshId].indices(),batch->indices.bufferBase(),batch->indices.size()); support.offset = uint32(meshSupport[batch->meshId].indexOffset)*sizeof(uint16); uint32 indexCount = uint32(batch->indices.size()/sizeof(uint16)); support.count = indexCount; meshSupport[batch->meshId].indexOffset+=indexCount; } batchSupport[i] = support; } for(uint32 i = 0;i<kMaxGeometries;++i){ if(meshSupport[i].requiredVertexSize > 0) renderer->unmap(meshSupport[i].vertexMapping); if(meshSupport[i].requiredIndexSize > 0) renderer->unmap(meshSupport[i].indexMapping); } if(!(textures_[0] == Texture2D::null())){ renderer->bind(textures_[0],0); renderer->bind(pointSampler_,0); } uint32 currentBoundMesh = kMaxGeometries; Pipeline currentBoundPipeline = Pipeline::nullPipeline(); bool constantsBound[kMaxPipelines] = {false}; bool textureUnitsBound[kMaxPipelines] = {false}; for(size_t i = 0;i<batchCount;++i){ if(!batchSupport[i].draw) continue; const BatchImpl* batch = begin<BatchImpl>(batches_) + i; if(!(pipelines_[batch->pipelineId].pipeline == currentBoundPipeline)){ renderer->bind(pipelines_[batch->pipelineId].pipeline); if(!constantsBound[batch->pipelineId]){ renderer->bind(pipelines_[batch->pipelineId].matrixConstant,matrix); constantsBound[batch->pipelineId] = true; } if(batch->font){ int fontTextureUnit = 2; renderer->bind(batch->font->pages_[0],fontTextureUnit); renderer->bind(fontSampler_,fontTextureUnit); renderer->bind(pipelines_[batch->pipelineId].texturesConstant,&fontTextureUnit); } else { if(batch->textureId != 0){ int unit = 1; renderer->bind(textures_[batch->textureId],unit); renderer->bind(pointSampler_,unit); renderer->bind(pipelines_[batch->pipelineId].texturesConstant,&unit); textureUnitsBound[batch->pipelineId] = false; } else if(!textureUnitsBound[batch->pipelineId]) { int unit = 0 ; renderer->bind(pipelines_[batch->pipelineId].texturesConstant,&unit); textureUnitsBound[batch->pipelineId] = true; } } } if(currentBoundMesh != batch->meshId){ renderer->bind(meshes_[batch->meshId].mesh,rendering::topology::Triangle,sizeof(uint16)); currentBoundMesh = batch->meshId; } if(batchSupport[i].indexed) renderer->drawIndexed(batchSupport[i].offset,batchSupport[i].count,batchSupport[i].baseVertex); else renderer->draw(batchSupport[i].offset,batchSupport[i].count); } glEnable(GL_DEPTH_TEST); renderer->bind(blending::disabled()); } void Service::servicePreStep(){ new(&fontBatches_) core::BufferAllocator(sizeof(BatchFontMapping)*32,services::frameAllocator(),core::BufferAllocator::GrowOnOverflow); new(&batches_) core::BufferAllocator(sizeof(BatchImpl)*64,services::frameAllocator(),core::BufferAllocator::GrowOnOverflow); for(uint32 dest = 0;dest<kMaxTextures;++dest){ textures_[dest] = Texture2D::null(); } } void Service::servicePostStep(){ } Service::Service() : batches_(128,services::frameAllocator()), fontBatches_(128,services::frameAllocator()) { for(uint32 i = 0;i<kMaxDefaultPipelines;++i) defaultPipelines_[i] = -1; for(uint32 i = 0; i<kMaxGeometries;++i){ meshes_[i].vertexSize = vertexSize(i); meshes_[i].vbo = meshes_[i].ibo = Buffer::nullBuffer(); } } Service::~Service(){ using namespace core::bufferArray; auto renderer = services::rendering(); for(uint32 i = 0; i<kMaxGeometries;++i){ if(!meshes_[i].vbo.isNull()){ renderer->release(meshes_[i].mesh); renderer->release(meshes_[i].vbo); if(meshes_[i].ibo.isNull()) renderer->release(meshes_[i].ibo); } } } } }
registerBatch(batch, font->renderingType() == text::fontType::Outlined? OutlinedTextPipeline : TextPipeline, font->renderingType() == text::fontType::Outlined? OutlinedTextGeometry : TextGeometry)
call_expression
[ { "content": "struct Batch {\n\n\tenum { kMaxLayer = 0xFF };\n\n\tenum { kMaxDepth = 0xFF };\n\n\n\n\ttypedef batching::Geometry Geometry;\n\n\n\n\tsize_t verticesSize,indicesSize;\n\n\ttopology::Primitive primitive;\n\n\tconst char* name;\n\n\tuint32 layer,depth;//Batches are sorted by depth and layers.\n\n\n\n\tBatch();\n\n};\n\n\n", "file_path": "src/rendering/ui.h", "rank": 0, "score": 352725.6525907602 }, { "content": "struct ScreenSpaceVertex;\n", "file_path": "src/rendering/softwareOcclusion/softwareOcclusion.h", "rank": 3, "score": 220950.05525405455 }, { "content": "struct Key\n\n{\n\n\tKey()\n\n\t\t:\tinter\t(IT_LINE)\n\n\t{}\n\n\n\n\t//! Current time\n\n\tdouble time;\n\n\n\n\t//! Current value\n\n\tfloat value;\n\n\n\n\t//! How to interpolate this key with previous key?\n\n\tInterpolationType inter;\n\n\n\n\t//! Interpolation parameters\n\n\tfloat params[5];\n\n\n\n\n\n\t// for std::find()\n\n\toperator double () {\n\n\t\treturn time;\n\n\t}\n\n};\n\n\n\n// ---------------------------------------------------------------------------\n\n/** \\brief Data structure for a LWO animation envelope\n\n */\n", "file_path": "src/dependencies/assimp/code/LWOAnimation.h", "rank": 4, "score": 215414.97951352285 }, { "content": "struct Key: Event {\n\n\tuint32 key;\n\n};\n", "file_path": "src/input/events.h", "rank": 5, "score": 208486.09568461473 }, { "content": "#include <cppunit/plugin/PlugInParameters.h>\n\nstruct CppUnitTestPlugIn;\n\n\n\nCPPUNIT_NS_BEGIN\n\n\n\n\n", "file_path": "src/dependencies/assimp/contrib/cppunit-1.12.1/include/cppunit/plugin/PlugInManager.h", "rank": 6, "score": 204835.6165781913 }, { "content": "struct CppUnitTestPlugIn\n\n{\n\n /*! \\brief Called just after loading the dynamic library. \n\n *\n\n * Override this method to add additional suite to the registry, though this\n\n * is preferably done using the macros (CPPUNIT_TEST_SUITE_REGISTRATION...).\n\n * If you are creating a custom listener to extends the plug-in runner,\n\n * you can use this to configure the listener using the \\a parameters.\n\n *\n\n * You could also use the parameters to specify some global parameter, such\n\n * as test datas location, database name...\n\n *\n\n * N.B.: Parameters interface is not define yet, and the plug-in runner does\n\n * not yet support plug-in parameter.\n\n */\n\n virtual void initialize( CPPUNIT_NS::TestFactoryRegistry *registry,\n\n const CPPUNIT_NS::PlugInParameters &parameters ) =0;\n\n\n\n /*! \\brief Gives a chance to the plug-in to register TestListener.\n\n * \n", "file_path": "src/dependencies/assimp/contrib/cppunit-1.12.1/include/cppunit/plugin/TestPlugIn.h", "rank": 7, "score": 204829.0124875928 }, { "content": "class CppUnitMap : public std::map<Key\n\n ,T\n\n ,std::less<Key>\n\n ,CPPUNIT_STD_ALLOCATOR>\n\n{\n\npublic:\n\n};\n\n\n\n#else // CPPUNIT_STD_NEED_ALLOCATOR\n\n\n\n#define CppUnitMap std::map\n\n\n\n#endif\n\n\n\n#endif // CPPUNIT_PORTABILITY_CPPUNITMAP_H\n\n\n", "file_path": "src/dependencies/assimp/contrib/cppunit-1.12.1/include/cppunit/portability/CppUnitMap.h", "rank": 8, "score": 192167.58117668846 }, { "content": "class AutoRegisterRegistry\n\n{\n\npublic:\n\n AutoRegisterRegistry( const std::string &which,\n\n const std::string &to )\n\n {\n\n TestFactoryRegistry::getRegistry( to ).addRegistry( which );\n\n }\n\n\n\n AutoRegisterRegistry( const std::string &which )\n\n {\n\n TestFactoryRegistry::getRegistry().addRegistry( which );\n\n }\n\n};\n\n\n\n\n\nCPPUNIT_NS_END\n\n\n\n#endif // CPPUNIT_EXTENSIONS_AUTOREGISTERSUITE_H\n", "file_path": "src/dependencies/assimp/contrib/cppunit-1.12.1/include/cppunit/extensions/AutoRegisterSuite.h", "rank": 9, "score": 187995.93104576762 }, { "content": "class AutoRegisterSuite\n\n{\n\npublic:\n\n /** Auto-register the suite factory in the global registry.\n\n */\n\n AutoRegisterSuite()\n\n : m_registry( &TestFactoryRegistry::getRegistry() )\n\n {\n\n m_registry->registerFactory( &m_factory );\n\n }\n\n\n\n /** Auto-register the suite factory in the specified registry.\n\n * \\param name Name of the registry.\n\n */\n\n AutoRegisterSuite( const std::string &name )\n\n : m_registry( &TestFactoryRegistry::getRegistry( name ) )\n\n {\n\n m_registry->registerFactory( &m_factory );\n\n }\n\n\n", "file_path": "src/dependencies/assimp/contrib/cppunit-1.12.1/include/cppunit/extensions/AutoRegisterSuite.h", "rank": 10, "score": 187995.93104576762 }, { "content": "inline uint32 Font::renderingType() const { return renderType_; }\n", "file_path": "src/data/font/font.h", "rank": 11, "score": 187916.76094510045 }, { "content": "class TextureView: public Renderable {\n\npublic:\n\n\tTextureView(rendering::Texture2D texture = rendering::Texture2D::null(),rendering::Pipeline pipeline = rendering::Pipeline::nullPipeline());\n\n\n\n\tvoid draw(Widget* widget,events::Draw& ev);\n\n\n\n\trendering::Pipeline pipeline_;\n\n\trendering::Texture2D texture_;\n\n\tuint32 color_;\n\n};\n", "file_path": "src/ui/components.h", "rank": 12, "score": 181336.27772355507 }, { "content": "\t\tuint8* dest;\n", "file_path": "src/rendering/2d.h", "rank": 13, "score": 179159.75141670628 }, { "content": "\tuint32 layerId;\n", "file_path": "src/ui/events.h", "rank": 14, "score": 177855.70013786922 }, { "content": "\tstruct Pipeline {\n\n\t\tstruct Constant {\n\n\t\t\tint32 location;\n\n\t\t\tuint8 shaderType,coreTypeId;\n\n\t\t\tuint16 count;\n\n\t\t\tconst char* name;\n\n\n\n\t\t\tConstant(const char* name);\n\n\t\t};\n\n\n\n\t\t//GLSL specific extra information for program linking (GLSL 3.3 layout)\n\n\t\tstruct GLSLLayout {\n\n\t\t\tconst char** vertexAttributes;\n\n\t\t\tuint32 vertexAttributeCount;\n\n\t\t\tconst char** pixelAttributes;\n\n\t\t\tuint32 pixelAttributeCount;\n\n\n\n\t\t\tGLSLLayout();\n\n\t\t};\n\n\t\n\n\t\tuint32 id;\n\n\n\n\t\tstatic inline Pipeline nullPipeline() { Pipeline result = { 0 }; return result; }\n", "file_path": "src/rendering/opengl/types.h", "rank": 15, "score": 174021.88248831098 }, { "content": "\t\tuint32 id;\n", "file_path": "src/rendering/opengl/types.h", "rank": 16, "score": 173998.76498501786 }, { "content": "\t\t\tconst char* name;\n", "file_path": "src/rendering/opengl/types.h", "rank": 17, "score": 173972.3732611782 }, { "content": "struct TaskKey;\n\n\n", "file_path": "src/application/tasking.h", "rank": 18, "score": 173464.28925531515 }, { "content": "struct TaskKey {\n\n\tTaskID id;\n\n\tTask* task;\n\n\tTaskKey* next;\n\n};\n", "file_path": "src/application/tasking.cpp", "rank": 19, "score": 170715.89288282403 }, { "content": " char pipeName[GLX_HYPERPIPE_PIPE_NAME_LENGTH_SGIX];\n", "file_path": "src/rendering/opengl/gl/glxext.h", "rank": 20, "score": 170519.52410983024 }, { "content": "struct SkeletalAnimation {\n\n\tenum { kMaxAnimations = 3 };\n\n\n\n\tEntityId entity;\n\n\tuint32 nodeCount;\n\n\tdata::Transformation3D* transformations;\n\n\tdata::Mesh* mesh;\n\n\tstruct Anim {\n\n\t\tfloat time;\n\n\t\tdata::animation::Animation* animation;\n\n\t};\n\n\tAnim anim[kMaxAnimations];\n\n\n\n\tSkeletalAnimation(EntityId id,data::Mesh* m) {\n\n\t\tentity = id;\n\n\t\tmesh = m;\n\n\t\tnodeCount= m->skeletonNodeCount();\n\n\t\ttransformations = (data::Transformation3D*)allocator()->allocate(sizeof(data::Transformation3D)*mesh->skeletonNodeCount(),alignof(vec4f));\n\n\t\tfor(uint32 i = 0;i<kMaxAnimations;++i){\n\n\t\t\tanim[i].time = 0.f;\n", "file_path": "src/scene/rendering.cpp", "rank": 21, "score": 170442.737282211 }, { "content": "struct EntityGrid {\n\n\tEntityGridCell grid[10];\n\n\n\n\tCullId createFrustumCullSphere(const vec4f& sphere,EntityId entity);\n\n\tCullId updateFrustumCullSphere(CullId id,const vec4f& sphere);\n\n\tvoid removeFrustumCullSphere(CullId id);\n\n\tvec4f getFrustumCullSphere(CullId id);\n\n\n\n\tEntityGrid();\n\n};\n\nCullId EntityGrid::createFrustumCullSphere(const vec4f& sphere,EntityId entity){\n\n\tvec4f s = sphere;\n\n\ts.w = -s.w; //NB: frustum culler expects sphere in format center, - radius\n\n\treturn grid[0].createSphere(s,entity);\n\n}\n\nCullId EntityGrid::updateFrustumCullSphere(CullId id,const vec4f& sphere){\n\n\t//grid[0].update(id&kEntityBlockIdMask,sphere);\n\n\treturn id;\n\n}\n\nvoid EntityGrid::removeFrustumCullSphere(CullId id){\n", "file_path": "src/scene/rendering.cpp", "rank": 22, "score": 170442.737282211 }, { "content": "struct VisibleEntity {\n\n\tFrustumMask mask;\n\n\tEntity* entity;\n\n\tuint32 offset,size;\n\n};\n", "file_path": "src/scene/rendering.cpp", "rank": 23, "score": 170442.737282211 }, { "content": "//function loading\n\nstruct Loader {\n\n\tint major,minor;\n\n\tvoid (*onError)(const char*);\n\n\tcore::bufferStringStream::Formatter formatter;\n\n\t\n\n\tvoid* load(const char* name){\n\n#ifdef ARPHEG_PLATFORM_WIN32\n\n\t\tvoid* proc = (void*)wglGetProcAddress(name);\n\n#endif\n\n\t\tif(!proc){\n\n\t\t\tformatter.allocator.reset();\n\n\t\t\tcore::bufferStringStream::printf(formatter,\"Failed to load OpenGL core function '%s' - the application may not behave correctly!\\n Please update your graphics card's drivers.\",name);\n\n\t\t\tservices::logging()->warning(core::bufferStringStream::asCString(formatter));\n\n\t\t}\n\n\t\tif(!proc && onError) onError(name);\n\n\t\treturn proc;\n\n\t}\n\n};\n\n\n\n#define F(f,T) f = (T) loader.load(#f);\n", "file_path": "src/rendering/opengl/api.cpp", "rank": 24, "score": 170442.737282211 }, { "content": "struct aiMeshKey \n\n{\n\n\t/** The time of this key */\n\n\tdouble mTime;\n\n\n\n\t/** Index into the aiMesh::mAnimMeshes array of the \n\n\t * mesh coresponding to the #aiMeshAnim hosting this\n\n\t * key frame. The referenced anim mesh is evaluated\n\n\t * according to the rules defined in the docs for #aiAnimMesh.*/\n\n\tunsigned int mValue;\n\n\n\n#ifdef __cplusplus\n\n\n\n\taiMeshKey() {\n\n\t}\n\n\n\n\t/** Construction from a given time and key value */\n\n\taiMeshKey(double time, const unsigned int value)\n\n\t\t:\tmTime\t(time)\n\n\t\t,\tmValue\t(value)\n\n\t{}\n\n\n\n\ttypedef unsigned int elem_type;\n\n\n\n\t// Comparison operators. For use with std::find();\n\n\tbool operator == (const aiMeshKey& o) const {\n\n\t\treturn o.mValue == this->mValue;\n\n\t}\n\n\tbool operator != (const aiMeshKey& o) const {\n\n\t\treturn o.mValue != this->mValue;\n\n\t}\n\n\n\n\t// Relational operators. For use with std::sort();\n", "file_path": "src/dependencies/assimp/include/assimp/anim.h", "rank": 25, "score": 169245.2592724326 }, { "content": "\tconst char* id; \n", "file_path": "src/dependencies/assimp/include/assimp/cexport.h", "rank": 26, "score": 169222.5977103394 }, { "content": "struct aiScene\n\n{\n\n\n\n\t/** Any combination of the AI_SCENE_FLAGS_XXX flags. By default \n\n\t* this value is 0, no flags are set. Most applications will\n\n\t* want to reject all scenes with the AI_SCENE_FLAGS_INCOMPLETE \n\n\t* bit set.\n\n\t*/\n\n\tunsigned int mFlags;\n\n\n\n\n\n\t/** The root node of the hierarchy. \n\n\t* \n\n\t* There will always be at least the root node if the import\n\n\t* was successful (and no special flags have been set). \n\n\t* Presence of further nodes depends on the format and content \n\n\t* of the imported file.\n\n\t*/\n\n\tC_STRUCT aiNode* mRootNode;\n\n\n\n\n\n\n\n\t/** The number of meshes in the scene. */\n\n\tunsigned int mNumMeshes;\n\n\n\n\t/** The array of meshes. \n\n\t*\n\n\t* Use the indices given in the aiNode structure to access \n\n\t* this array. The array is mNumMeshes in size. If the\n\n\t* AI_SCENE_FLAGS_INCOMPLETE flag is not set there will always \n\n\t* be at least ONE material.\n\n\t*/\n\n\tC_STRUCT aiMesh** mMeshes;\n\n\n\n\n\n\n\n\t/** The number of materials in the scene. */\n\n\tunsigned int mNumMaterials;\n\n\n\n\t/** The array of materials. \n\n\t* \n\n\t* Use the index given in each aiMesh structure to access this\n\n\t* array. The array is mNumMaterials in size. If the\n\n\t* AI_SCENE_FLAGS_INCOMPLETE flag is not set there will always \n\n\t* be at least ONE material.\n\n\t*/\n\n\tC_STRUCT aiMaterial** mMaterials;\n\n\n\n\n\n\n\n\t/** The number of animations in the scene. */\n\n\tunsigned int mNumAnimations; \n\n\n\n\t/** The array of animations. \n\n\t*\n\n\t* All animations imported from the given file are listed here.\n\n\t* The array is mNumAnimations in size.\n\n\t*/\n\n\tC_STRUCT aiAnimation** mAnimations;\n\n\n\n\n\n\n\n\t/** The number of textures embedded into the file */\n\n\tunsigned int mNumTextures;\n\n\n\n\t/** The array of embedded textures.\n\n\t* \n\n\t* Not many file formats embed their textures into the file.\n\n\t* An example is Quake's MDL format (which is also used by\n\n\t* some GameStudio versions)\n\n\t*/\n\n\tC_STRUCT aiTexture** mTextures;\n\n\n\n\n\n\t/** The number of light sources in the scene. Light sources\n\n\t* are fully optional, in most cases this attribute will be 0 \n\n */\n\n\tunsigned int mNumLights;\n\n\n\n\t/** The array of light sources.\n\n\t* \n\n\t* All light sources imported from the given file are\n\n\t* listed here. The array is mNumLights in size.\n\n\t*/\n\n\tC_STRUCT aiLight** mLights;\n\n\n\n\n\n\t/** The number of cameras in the scene. Cameras\n\n\t* are fully optional, in most cases this attribute will be 0 \n\n */\n\n\tunsigned int mNumCameras;\n\n\n\n\t/** The array of cameras.\n\n\t* \n\n\t* All cameras imported from the given file are listed here.\n\n\t* The array is mNumCameras in size. The first camera in the\n\n\t* array (if existing) is the default camera view into\n\n\t* the scene.\n\n\t*/\n\n\tC_STRUCT aiCamera** mCameras;\n\n\n\n#ifdef __cplusplus\n\n\n\n\t//! Default constructor - set everything to 0/NULL\n\n\taiScene();\n\n\n\n\t//! Destructor\n\n\t~aiScene();\n\n\n\n\t//! Check whether the scene contains meshes\n\n\t//! Unless no special scene flags are set this will always be true.\n\n\tinline bool HasMeshes() const \n\n\t\t{ return mMeshes != NULL && mNumMeshes > 0; }\n\n\n\n\t//! Check whether the scene contains materials\n\n\t//! Unless no special scene flags are set this will always be true.\n\n\tinline bool HasMaterials() const \n", "file_path": "src/dependencies/assimp/include/assimp/scene.h", "rank": 27, "score": 169201.41527628223 }, { "content": "struct BatchData;\n\n\n\n// ---------------------------------------------------------------------------\n\n/** FOR IMPORTER PLUGINS ONLY: A helper class to the pleasure of importers \n\n * that need to load many external meshes recursively.\n\n *\n\n * The class uses several threads to load these meshes (or at least it\n\n * could, this has not yet been implemented at the moment).\n\n *\n\n * @note The class may not be used by more than one thread*/\n", "file_path": "src/dependencies/assimp/code/Importer.h", "rank": 28, "score": 168089.83153344432 }, { "content": "//An intermediate pointer mapper, slow, not to be used in final builds.\n\nstruct IDPointerMapper {\n\n\tstruct Obj {\n\n\t\tcore::Bytes key;\n\n\t\tvoid* value;\n\n\t};\n\n\tcore::BufferAllocator objects;\n\n\tcore::Allocator* stringStorage;\n\n\t\n\n\tIDPointerMapper(core::Allocator* allocator);\n\n\t\n\n\tvoid insert(core::Bytes key,void* value);\n\n\tvoid* get(core::Bytes key);\n\n};\n\nIDPointerMapper::IDPointerMapper(core::Allocator* allocator) :\n\n\tobjects(sizeof(IDPointerMapper) * 128,allocator,core::BufferAllocator::GrowOnOverflow)\n\n{ stringStorage = allocator; }\n\nvoid IDPointerMapper::insert(core::Bytes key,void* value){\n\n\t//copy string\n\n\tauto dest = (uint8*)stringStorage->allocate(key.length()+1);\n\n\tmemcpy(dest,key.begin,key.length());\n", "file_path": "src/data/data.cpp", "rank": 29, "score": 168086.1108146393 }, { "content": "struct Vertex\n\n{\n\n\tint32_t X : 11;\n\n\tint32_t Y : 11;\n\n\tint32_t Z : 10;\n\n};\n\n\n\n\t// UNREAL vertex compression\n\ninline void CompressVertex(const aiVector3D& v, uint32_t& out)\n\n{\n\n\tunion {\n\n\t\tVertex n;\n\n\t\tint32_t t;\n\n\t};\n\n\tn.X = (int32_t)v.x;\n\n\tn.Y = (int32_t)v.y;\n\n\tn.Z = (int32_t)v.z;\n\n\tout = t;\n\n}\n\n\n", "file_path": "src/dependencies/assimp/code/UnrealLoader.h", "rank": 30, "score": 168056.41334457824 }, { "content": "struct Vertex\n\n{\n\n\tVertex() : iParentNode(UINT_MAX)\n\n\t {}\n\n\n\n\t//! Vertex position, normal and texture coordinate\n\n\taiVector3D pos,nor,uv;\n\n\n\n\t//! Vertex parent node\n\n\tunsigned int iParentNode;\n\n\n\n\t//! Links to bones: pair.first is the bone index,\n\n\t//! pair.second is the vertex weight.\n\n\t//! WARN: The remaining weight (to reach 1.0f) is assigned\n\n\t//! to the parent node/bone\n\n\tstd::vector<std::pair<unsigned int, float> > aiBoneLinks;\n\n};\n\n\n\n// ---------------------------------------------------------------------------\n\n/** Data structure for a face in a SMD file\n\n*/\n", "file_path": "src/dependencies/assimp/code/SMDLoader.h", "rank": 31, "score": 168056.41334457824 }, { "content": "struct Texture\n\n{\n\n\t//! Default constructor\n\n\tTexture()\n\n\t\t: mOffsetU\t(0.0f)\n\n\t\t, mOffsetV\t(0.0f)\n\n\t\t, mScaleU\t(1.0f)\n\n\t\t, mScaleV\t(1.0f)\n\n\t\t, mRotation\t(0.0f)\n\n\t\t, mMapMode\t(aiTextureMapMode_Wrap)\n\n\t\t, iUVSrc\t(0)\n\n\t{\n\n\t\tmTextureBlend = get_qnan();\n\n\t}\n\n\n\n\t//! Specifies the blend factor for the texture\n\n\tfloat mTextureBlend;\n\n\n\n\t//! Specifies the filename of the texture\n\n\tstd::string mMapName;\n", "file_path": "src/dependencies/assimp/code/3DSHelper.h", "rank": 32, "score": 168050.10256881008 }, { "content": "struct TouchedNodeMask {\n\n\tenum { kSizeofSizetInBits = sizeof(size_t)*8 };\n\n\tsize_t bits[Animator::kMaxNodes/kSizeofSizetInBits];\n\n\n\n\tTouchedNodeMask(){\n\n\t\tfor(size_t i = 0;i<Animator::kMaxNodes/kSizeofSizetInBits;++i) bits[i] = 0;\n\n\t}\n\n\tinline void mark(size_t i){\n\n\t\tsize_t element= i/kSizeofSizetInBits;\n\n\t\tsize_t bit = i%kSizeofSizetInBits;\n\n\t\tbits[element] |= 1<<bit;\n\n\t}\n\n\tinline bool isNotTouched(size_t i){\n\n\t\tsize_t element= i/kSizeofSizetInBits;\n\n\t\tsize_t bit = i%kSizeofSizetInBits;\n\n\t\treturn (bits[element] & (1<<bit)) == 0;\n\n\t}\n\n};\n\n\n\n//Obtain and store the wrapped local time\n", "file_path": "src/rendering/animation.cpp", "rank": 33, "score": 167817.15997603053 }, { "content": "struct VisibleAnimatedEntity {\n\n\tFrustumMask mask;\n\n\tAnimatedEntity* entity;\n\n\tuint32 offset,size;\n\n};\n", "file_path": "src/scene/rendering.cpp", "rank": 34, "score": 167817.15997603053 }, { "content": "struct VisibleCustomEntity {\n\n\tFrustumMask mask;\n\n\tCustomEntity* entity;\n\n};\n", "file_path": "src/scene/rendering.cpp", "rank": 35, "score": 167817.15997603053 }, { "content": "struct VisibleLightEntity {\n\n\tFrustumMask mask;\n\n\tLightEntity* entity;\n\n};\n\n\n\nService::Service(core::Allocator* alloc) :\n\n\tskeletonAnimations_(sizeof(SkeletalAnimation)*1024,allocator(),core::BufferAllocator::GrowOnOverflow),\n\n\tentityConstantStorage(1024*8,allocator(),core::BufferAllocator::GrowOnOverflow)\n\n{\n\n\t//Entity pools.\n\n\tentities_ = ALLOCATOR_NEW(alloc,EntityPool<Entity>) (1024*32,allocator());\n\n\tanimatedEntities_ = ALLOCATOR_NEW(alloc,EntityPool<AnimatedEntity>) (1024*2,allocator());\n\n\tcustomEntities_ = ALLOCATOR_NEW(alloc,EntityPool<CustomEntity>) (1024*2,allocator());\n\n\tlights_ = ALLOCATOR_NEW(alloc,EntityPool<LightEntity>) (1024*2,allocator());\n\n\n\n\tvisibleEntities_ = (core::BufferAllocator*)alloc->allocate(sizeof(core::BufferAllocator)*services::tasking()->threadCount(),alignof(core::BufferAllocator));\n\n\tvisibleAnimatedEntities_ = (core::BufferAllocator*)alloc->allocate(sizeof(core::BufferAllocator)*services::tasking()->threadCount(),alignof(core::BufferAllocator));\n\n\tvisibleLights_ = (core::BufferAllocator*)alloc->allocate(sizeof(core::BufferAllocator)*services::tasking()->threadCount(),alignof(core::BufferAllocator));\n\n\t\n\n\tvisibleEntitiesInited = false;\n", "file_path": "src/scene/rendering.cpp", "rank": 36, "score": 167817.15997603053 }, { "content": "#ifndef CPPUNIT_EXTENSIONS_AUTOREGISTERSUITE_H\n\n#define CPPUNIT_EXTENSIONS_AUTOREGISTERSUITE_H\n\n\n\n#include <cppunit/extensions/TestSuiteFactory.h>\n\n#include <cppunit/extensions/TestFactoryRegistry.h>\n\n#include <string>\n\n\n\nCPPUNIT_NS_BEGIN\n\n\n\n\n\n/*! \\brief (Implementation) Automatically register the test suite of the specified type.\n\n *\n\n * You should not use this class directly. Instead, use the following macros:\n\n * - CPPUNIT_TEST_SUITE_REGISTRATION()\n\n * - CPPUNIT_TEST_SUITE_NAMED_REGISTRATION()\n\n *\n\n * This object will register the test returned by TestCaseType::suite()\n\n * when constructed to the test registry.\n\n *\n\n * This object is intented to be used as a static variable.\n\n *\n\n *\n\n * \\param TestCaseType Type of the test case which suite is registered.\n\n * \\see CPPUNIT_TEST_SUITE_REGISTRATION, CPPUNIT_TEST_SUITE_NAMED_REGISTRATION\n\n * \\see CppUnit::TestFactoryRegistry.\n\n */\n\ntemplate<class TestCaseType>\n", "file_path": "src/dependencies/assimp/contrib/cppunit-1.12.1/include/cppunit/extensions/AutoRegisterSuite.h", "rank": 37, "score": 167184.32764964696 }, { "content": " ~AutoRegisterSuite()\n\n {\n\n if ( TestFactoryRegistry::isValid() )\n\n m_registry->unregisterFactory( &m_factory );\n\n }\n\n\n\nprivate:\n\n TestFactoryRegistry *m_registry;\n\n TestSuiteFactory<TestCaseType> m_factory;\n\n};\n\n\n\n\n\n/*! \\brief (Implementation) Automatically adds a registry into another registry.\n\n *\n\n * Don't use this class. Use the macros CPPUNIT_REGISTRY_ADD() and\n\n * CPPUNIT_REGISTRY_ADD_TO_DEFAULT() instead.\n\n */\n", "file_path": "src/dependencies/assimp/contrib/cppunit-1.12.1/include/cppunit/extensions/AutoRegisterSuite.h", "rank": 38, "score": 167173.21386308954 }, { "content": "\tunsigned int mVertexId;\n", "file_path": "src/dependencies/assimp/include/assimp/mesh.h", "rank": 39, "score": 167121.1441121757 }, { "content": "enum VertexFormat\n\n{\n\n\tVertex_Standard,\n\n\tVertex_Extended\n\n};\n\n\n", "file_path": "src/dependencies/assimp/code/M3Importer.h", "rank": 40, "score": 165882.4358405176 }, { "content": "struct KeyPred {\n\n\tinline bool operator () (const T& a,const T& b){\n\n\t\treturn a.time < b.time;\n\n\t}\n\n};\n\nvoid Scene::importSkeletalAnimationTracks() {\n\n\tfor(uint32 i = 0;i<scene->mNumAnimations;++i){\n\n\t\tauto animation = scene->mAnimations[i];\n\n\t\tanimation::Animation destAnimation;\n\n\t\tdestAnimation.length = scene->mAnimations[i]->mDuration;\n\n\t\tdestAnimation.frequency = scene->mAnimations[i]->mTicksPerSecond == 0.f? 25.f : scene->mAnimations[i]->mTicksPerSecond;\n\n\t\tdestAnimation.trackCount = 0;\n\n\t\tdestAnimation.tracks = nullptr;\n\n\n\n\t\t//Find the track count\n\n\t\tfor(uint32 i = 0;i<animation->mNumChannels;++i){\n\n\t\t\tif(!findSkeletonNode(animation->mChannels[i]->mNodeName)){\n\n\t\t\t\tlogging->warning(\"An animation contains a track which doesn't influence any bone\");\n\n\t\t\t\tcontinue;\n\n\t\t\t}\n", "file_path": "src/data/intermediate/mesh/reader.cpp", "rank": 41, "score": 165562.7982199745 }, { "content": "struct VertexDesc\n\n{\n\n\tVertexDesc()\n\n\t\t: mFirstWeight\t(0)\n\n\t\t, mNumWeights\t(0)\n\n\t{}\n\n\n\n\t//! UV cordinate of the vertex\n\n\taiVector2D mUV;\n\n\n\n\t//! Index of the first weight of the vertex in\n\n\t//! the vertex weight list\n\n\tunsigned int mFirstWeight;\n\n\n\n\t//! Number of weights assigned to this vertex\n\n\tunsigned int mNumWeights;\n\n};\n\n\n\ntypedef std::vector< VertexDesc > VertexList;\n\n\n\n// ---------------------------------------------------------------------------\n\n/** Represents a vertex weight descriptor in a MD5 file\n\n*/\n", "file_path": "src/dependencies/assimp/code/MD5Parser.h", "rank": 42, "score": 165535.29579188526 }, { "content": "struct BoneVertex\n\n{\n\n\t//! Bone and corresponding vertex weight.\n\n\t//! -1 for unrequired bones ....\n\n\tstd::vector<std::pair<int,float> > mBoneWeights;\n\n\n\n\t//! Position of the bone vertex.\n\n\t//! MUST be identical to the vertex position\n\n\t//aiVector3D mPosition;\n\n};\n\n\n\n// ---------------------------------------------------------------------------\n\n/** Helper structure to represent an ASE file animation */\n", "file_path": "src/dependencies/assimp/code/ASEParser.h", "rank": 43, "score": 165535.29579188526 }, { "content": "struct aiTexture;\n", "file_path": "src/dependencies/assimp/code/LWOLoader.h", "rank": 44, "score": 165529.116547456 }, { "content": "struct aiNode;\n\n\n\nnamespace Assimp\t{\n\n\n\n#define AI_TT_UV_IDX_LOCK_TBD\t0xffffffff\n\n#define AI_TT_UV_IDX_LOCK_NONE\t0xeeeeeeee\n\n\n\n\n\n#define AI_TT_ROTATION_EPSILON\t((float)AI_DEG_TO_RAD(0.5))\n\n\n\n// ---------------------------------------------------------------------------\n\n/** Small helper structure representing a shortcut into the material list\n\n * to be able to update some values quickly.\n\n*/\n", "file_path": "src/dependencies/assimp/code/TextureTransform.h", "rank": 45, "score": 165529.116547456 }, { "content": "struct LightAABBXAxis {\n\n\tuint8 firstTile,lastTile;\n\n\tuint16 index;\n\n};\n\n\n\n\n\nstatic inline bool rowIntersect(int32 ty,const TileGrid::LightAABB& lightRect){\n\n\tif(ty > lightRect.min[1]){\n\n\t\tif(lightRect.max[1] <= ty) return false;\n\n\t}\n\n\telse {\n\n\t\tif((ty + kTileSize) <= lightRect.min[1]) return false;\n\n\t}\n\n\treturn true;\n\n}\n\n\n\n// This is a naive tile assignment implementation.\n\nvoid TileGrid::performLightAssignment(const Tiler& tiler) {\n\n\tindexOffset = 0;\n\n\tuint32 idx = 0;\n", "file_path": "src/rendering/lighting/tiled.cpp", "rank": 46, "score": 165301.02902356844 }, { "content": "//A rasterizable triangle.\n\nstruct XY {\n\n\t//struct {\n\n\t\tint32 x, y;\n\n\t//};\n\n\t//uint32 xy;\n\n};\n", "file_path": "src/rendering/softwareOcclusion/softwareOcclusion.cpp", "rank": 47, "score": 165301.02902356844 }, { "content": "struct BinnedTriangle;\n\n\n", "file_path": "src/rendering/softwareOcclusion/softwareOcclusion.h", "rank": 48, "score": 165301.02902356844 }, { "content": "", "file_path": "src/dependencies/assimp/include/assimp/matrix3x3.h", "rank": 49, "score": 165258.4689067915 }, { "content": "", "file_path": "src/dependencies/assimp/include/assimp/matrix4x4.h", "rank": 50, "score": 165258.4689067915 }, { "content": "struct aiQuaternion {\n\n\tfloat w, x, y, z;\t\n\n};\n\n\n\n#endif\n\n\n\n\n\n#endif // AI_QUATERNION_H_INC\n", "file_path": "src/dependencies/assimp/include/assimp/quaternion.h", "rank": 51, "score": 165258.4689067915 }, { "content": "struct auto_any : auto_any_base\n\n{\n\n auto_any(T const& t) : item(t) {}\n\n mutable T item;\n\n};\n\n\n\ntemplate<typename T>\n\nT& auto_any_cast(auto_any_base const& any)\n\n{\n\n return static_cast<auto_any<T> const&>(any).item;\n\n}\n\n\n\n///////////////////////////////////////////////////////////////////////////////\n\n// FOREACH helper function\n\n\n\ntemplate<typename T>\n\nauto_any<typename T::const_iterator> begin(T const& t)\n\n{\n\n return t.begin();\n\n}\n", "file_path": "src/dependencies/assimp/code/BoostWorkaround/boost/foreach.hpp", "rank": 52, "score": 165002.77310433466 }, { "content": "struct aiFloatKey \n\n{\n\n\tdouble mTime; ///< The time of this key\n\n\tfloat mValue;\t///< The value of this key\n\n\n\n#ifdef __cplusplus\n\n\n\n\t// time is not compared\n\n\tbool operator == (const aiFloatKey& o) const\n\n\t\t{return o.mValue == this->mValue;}\n\n\n\n\tbool operator != (const aiFloatKey& o) const\n\n\t\t{return o.mValue != this->mValue;}\n\n\n\n\t// Only time is compared. This operator is defined\n\n\t// for use with std::sort\n\n\tbool operator < (const aiFloatKey& o) const\n\n\t\t{return mTime < o.mTime;}\n\n\n\n\tbool operator > (const aiFloatKey& o) const\n\n\t\t{return mTime < o.mTime;}\n\n\n\n#endif\n\n};\n\n\n\n// ---------------------------------------------------------------------------\n\n/** Helper structure to represent a 3ds file node */\n", "file_path": "src/dependencies/assimp/code/3DSHelper.h", "rank": 53, "score": 163144.06549500418 }, { "content": "struct aiMesh;\n\nnamespace Assimp\t{\n\n\n\n// --------------------------------------------------------------------------------------------\n\n/** @brief The VertexTriangleAdjacency class computes a vertex-triangle\n\n * adjacency map from a given index buffer.\n\n *\n\n * @note Although it is called #VertexTriangleAdjacency, the current version does also\n\n * support arbitrary polygons. */\n", "file_path": "src/dependencies/assimp/code/VertexTriangleAdjacency.h", "rank": 54, "score": 163117.124578673 }, { "content": "struct TTUpdateInfo\n\n{\n\n\tTTUpdateInfo() :\n\n\t\t\tdirectShortcut\t(NULL)\n\n\t\t,\tmat\t\t\t\t(NULL)\n\n\t\t,\tsemantic\t\t(0)\n\n\t\t,\tindex\t\t\t(0)\n\n\t{}\n\n\n\n\t//! Direct shortcut, if available\n\n\tunsigned int* directShortcut;\n\n\n\n\t//! Material \n\n\taiMaterial *mat;\n\n\n\n\t//! Texture type and index\n\n\tunsigned int semantic, index;\n\n};\n\n\n\n\n\n// ---------------------------------------------------------------------------\n\n/** Helper class representing texture coordinate transformations\n\n*/\n", "file_path": "src/dependencies/assimp/code/TextureTransform.h", "rank": 55, "score": 163111.0714946828 }, { "content": "struct aiTexture;\n", "file_path": "src/dependencies/assimp/code/ValidateDataStructure.h", "rank": 56, "score": 163111.0714946828 }, { "content": "", "file_path": "src/dependencies/assimp/contrib/clipper/clipper.hpp", "rank": 57, "score": 163107.34360151124 }, { "content": "struct BinnedTriangle {\n\n\tXY v[3];\n\n\tfloat z[3];\n\n};\n\n\n\nenum {\n\n\tkMaxTrianglesPerTile = 1024*2,\n\n\t\n\n\tkModeDepthFlat = 0, //Depth buffer pixels are stored in rows \n\n\tkModeDepthPackedTiles,//Depth buffer pixels are stored in rows for each tile\n\n\tkModeDepthPackedQuads,//Depth buffer pixels are stored in 2x2 quads ((0,0),(1,0),(0,1),(1,1))\n\n};\n\n\n\nDepthBuffer::DepthBuffer(vec2i size){\n\n\tmode_ = kModeDepthPackedQuads;\n\n\tauto allocator= core::memory::globalAllocator();\n\n\tsize_ = size;\n\n\ttileCount_ = vec2i(4,4);\n\n\n\n\tif(size.y%tileCount_.y){\n", "file_path": "src/rendering/softwareOcclusion/softwareOcclusion.cpp", "rank": 58, "score": 162887.64078968109 }, { "content": "struct ScreenSpaceQuad;\n", "file_path": "src/rendering/softwareOcclusion/softwareOcclusion.h", "rank": 59, "score": 162887.64078968109 }, { "content": "struct aiVector2D {\n\n\tfloat x,y;\n\n};\n\n\n\n#endif // __cplusplus\n\n\n\n#include \"./Compiler/poppack1.h\"\n\n\n\n#endif // AI_VECTOR2D_H_INC\n", "file_path": "src/dependencies/assimp/include/assimp/vector2.h", "rank": 60, "score": 162845.94961458148 }, { "content": "struct aiVector3D {\n\n\n\n\tfloat x,y,z;\n\n} PACK_STRUCT;\n\n\n\n#endif // __cplusplus\n\n\n\n#include \"./Compiler/poppack1.h\"\n\n\n\n#ifdef __cplusplus\n\n\n\n\n\n\n\n#endif // __cplusplus\n\n\n\n#endif // AI_VECTOR3D_H_INC\n", "file_path": "src/dependencies/assimp/include/assimp/vector3.h", "rank": 61, "score": 162845.94961458148 }, { "content": "struct aiScene;\n\n\n", "file_path": "src/dependencies/assimp/include/assimp/Importer.hpp", "rank": 62, "score": 162845.94961458148 }, { "content": "struct Asserter\n\n{\n\n /*! \\brief Throws a Exception with the specified message and location.\n\n */\n\n static void CPPUNIT_API fail( const Message &message, \n\n const SourceLine &sourceLine = SourceLine() );\n\n\n\n /*! \\brief Throws a Exception with the specified message and location.\n\n * \\deprecated Use fail( Message, SourceLine ) instead.\n\n */\n\n static void CPPUNIT_API fail( std::string message, \n\n const SourceLine &sourceLine = SourceLine() );\n\n\n\n /*! \\brief Throws a Exception with the specified message and location.\n\n * \\param shouldFail if \\c true then the exception is thrown. Otherwise\n\n * nothing happen.\n\n * \\param message Message explaining the assertion failiure.\n\n * \\param sourceLine Location of the assertion.\n\n */\n\n static void CPPUNIT_API failIf( bool shouldFail, \n", "file_path": "src/dependencies/assimp/contrib/cppunit-1.12.1/include/cppunit/Asserter.h", "rank": 63, "score": 162845.94961458148 }, { "content": "struct aiColor4D {\n\n\tfloat r, g, b, a;\n\n} PACK_STRUCT;\n\n\n\n#endif // __cplusplus\n\n\n\n#include \"./Compiler/poppack1.h\"\n\n\n\n#endif // AI_COLOR4D_H_INC\n", "file_path": "src/dependencies/assimp/include/assimp/color4.h", "rank": 64, "score": 162845.94961458148 }, { "content": "struct aiMesh;\n", "file_path": "src/dependencies/assimp/code/LimitBoneWeightsProcess.h", "rank": 65, "score": 160819.39434500068 }, { "content": "struct ScreenSpaceQuad {\n\n\tvec4f v[4];\n\n};\n", "file_path": "src/rendering/softwareOcclusion/softwareOcclusion.cpp", "rank": 66, "score": 160570.82815262617 }, { "content": "// importerdesc.h\n\nstruct aiImporterDesc;\n\n\n\n/** @namespace Assimp Assimp's CPP-API and all internal APIs */\n\nnamespace Assimp\t{\n\n\n\n// ----------------------------------------------------------------------------------\n\n/** CPP-API: The Importer class forms an C++ interface to the functionality of the \n\n* Open Asset Import Library.\n\n*\n\n* Create an object of this class and call ReadFile() to import a file. \n\n* If the import succeeds, the function returns a pointer to the imported data. \n\n* The data remains property of the object, it is intended to be accessed \n\n* read-only. The imported data will be destroyed along with the Importer \n\n* object. If the import fails, ReadFile() returns a NULL pointer. In this\n\n* case you can retrieve a human-readable error description be calling \n\n* GetErrorString(). You can call ReadFile() multiple times with a single Importer\n\n* instance. Actually, constructing Importer objects involves quite many\n\n* allocations and may take some time, so it's better to reuse them as often as\n\n* possible.\n\n*\n\n* If you need the Importer to do custom file handling to access the files,\n\n* implement IOSystem and IOStream and supply an instance of your custom \n\n* IOSystem implementation by calling SetIOHandler() before calling ReadFile().\n\n* If you do not assign a custion IO handler, a default handler using the \n\n* standard C++ IO logic will be used.\n\n*\n\n* @note One Importer instance is not thread-safe. If you use multiple\n\n* threads for loading, each thread should maintain its own Importer instance.\n\n*/\n", "file_path": "src/dependencies/assimp/include/assimp/Importer.hpp", "rank": 67, "score": 160529.97114711054 }, { "content": "struct auto_any_base\n\n{\n\n operator bool() const { return false; }\n\n};\n\n\n\ntemplate<typename T>\n", "file_path": "src/dependencies/assimp/code/BoostWorkaround/boost/foreach.hpp", "rank": 68, "score": 158596.63404461573 }, { "content": "struct FontParser : core::text::Tokenizer {\n\n\tstruct Common {\n\n\t\tint lineHeight,base,width,height,pages,packed;\n\n\t\tint redChannel,greenChannel,blueChannel,alphaChannel;\n\n\t};\n\n\tstruct Char {\n\n\t\tint id;\n\n\t\tint x,y,width,height;\n\n\t\tint xoffset,yoffset;\n\n\t\tint xadvance;\n\n\t\tint page;\n\n\t\tint channel;\n\n\t};\n\n\n\n\tReader* reader;\n\n\tFont& font;\n\n\tCommon common;\n\n\tint prevCharId;\n\n\n\n\tvoid wildcard(){\n", "file_path": "src/data/intermediate/font/reader.cpp", "rank": 69, "score": 158445.8958615713 }, { "content": "struct LogStreamInfo;\n\n\n\n/** default name of logfile */\n\n#define ASSIMP_DEFAULT_LOG_NAME \"AssimpLog.txt\"\n\n\n\n// ------------------------------------------------------------------------------------\n\n/** @brief CPP-API: Primary logging facility of Assimp. \n\n *\n\n * The library stores its primary #Logger as a static member of this class.\n\n * #get() returns this primary logger. By default the underlying implementation is\n\n * just a #NullLogger which rejects all log messages. By calling #create(), logging\n\n * is turned on. To capture the log output multiple log streams (#LogStream) can be\n\n * attach to the logger. Some default streams for common streaming locations (such as\n\n * a file, std::cout, OutputDebugString()) are also provided.\n\n * \n\n * If you wish to customize the logging at an even deeper level supply your own\n\n * implementation of #Logger to #set().\n\n * @note The whole logging stuff causes a small extra overhead for all imports. */\n", "file_path": "src/dependencies/assimp/include/assimp/DefaultLogger.hpp", "rank": 70, "score": 158304.85232153072 }, { "content": "struct ExceptionSwallower<aiReturn>\t{\n\n\taiReturn operator ()() const {\n\n\t\ttry {\n\n\t\t\tthrow;\n\n\t\t}\n\n\t\tcatch (std::bad_alloc&) {\n\n\t\t\treturn aiReturn_OUTOFMEMORY;\n\n\t\t}\n\n\t\tcatch (...) {\n\n\t\t\treturn aiReturn_FAILURE;\n\n\t\t}\n\n\t}\n\n};\n\n\n\n// ---------------------------------------------------------------------------\n\ntemplate <>\n", "file_path": "src/dependencies/assimp/code/Exceptional.h", "rank": 71, "score": 157013.08573015608 }, { "content": "struct ExpectedExceptionTraits\n\n{\n\n static void expectedException()\n\n {\n\n#if CPPUNIT_USE_TYPEINFO_NAME\n\n throw Exception( Message(\n\n \"expected exception not thrown\",\n\n \"Expected exception type: \" + \n\n TypeInfoHelper::getClassName( typeid( ExceptionType ) ) ) );\n\n#else\n\n throw Exception( \"expected exception not thrown\" );\n\n#endif\n\n }\n\n};\n\n\n\n\n\n/*! \\brief (Implementation) Traits specialization used by TestCaller to \n\n * expect no exception.\n\n *\n\n * This class is an implementation detail. You should never use this class directly.\n\n */\n\ntemplate<>\n", "file_path": "src/dependencies/assimp/contrib/cppunit-1.12.1/include/cppunit/TestCaller.h", "rank": 72, "score": 156165.34914346485 }, { "content": "// ------------------------------------------------------------------------------------------------\n\n// BatchLoader::pimpl data structure\n\nstruct Assimp::BatchData\n\n{\n\n\tBatchData()\n\n\t\t:\tnext_id(0xffff)\n\n\t{}\n\n\n\n\t// IO system to be used for all imports\n\n\tIOSystem* pIOSystem;\n\n\n\n\t// Importer used to load all meshes\n\n\tImporter* pImporter;\n\n\n\n\t// List of all imports\n\n\tstd::list<LoadRequest> requests;\n\n\n\n\t// Base path\n\n\tstd::string pathBase;\n\n\n\n\t// Id for next item\n\n\tunsigned int next_id;\n", "file_path": "src/dependencies/assimp/code/BaseImporter.cpp", "rank": 73, "score": 154694.80721160557 }, { "content": "struct Vertex // 32 byte\n\n{\n\n\tVec3D pos;\n\n\tuint8 boneWeight[4];\n\n\tuint8 boneIndex[4];\n\n\tuint8 normal[4]; //normal_x = (float)normal[0]/255.0f...\n\n\tint16 uv[2];\n\n\tuint8 tangent[4];\n\n};\n\n\n", "file_path": "src/dependencies/assimp/code/M3Importer.h", "rank": 74, "score": 154673.2169321969 }, { "content": "struct VertexExt // 36 byte\n\n{\n\n\tVec3D pos;\n\n\tuint8 boneWeight[ 4 ];\n\n\tuint8 boneIndex[ 4 ];\n\n\tuint8 normal[ 4 ]; //normal_x = (float)normal[0]/255.0f...\n\n\tint16 uv[ 2 ];\n\n\tuint32 d1;\n\n\tuint8 tangent[ 4 ];\n\n};\n\n\n", "file_path": "src/dependencies/assimp/code/M3Importer.h", "rank": 75, "score": 152255.04571898462 }, { "content": "Open Asset Import Library (assimp)\n\n----------------------------------------------------------------------\n\n\n\nCopyright (c) 2006-2012, assimp team\n\nAll rights reserved.\n\n\n\nRedistribution and use of this software in source and binary forms, \n\nwith or without modification, are permitted provided that the \n\nfollowing conditions are met:\n\n\n\n* Redistributions of source code must retain the above\n\n copyright notice, this list of conditions and the\n\n following disclaimer.\n\n\n\n* Redistributions in binary form must reproduce the above\n\n copyright notice, this list of conditions and the\n\n following disclaimer in the documentation and/or other\n\n materials provided with the distribution.\n\n\n\n* Neither the name of the assimp team, nor the names of its\n", "file_path": "src/dependencies/assimp/code/Vertex.h", "rank": 76, "score": 148554.26033793742 }, { "content": "Open Asset Import Library (assimp)\n\n----------------------------------------------------------------------\n\n\n\nCopyright (c) 2006-2012, assimp team\n\nAll rights reserved.\n\n\n\nRedistribution and use of this software in source and binary forms, \n\nwith or without modification, are permitted provided that the \n\nfollowing conditions are met:\n\n\n\n* Redistributions of source code must retain the above\n\n copyright notice, this list of conditions and the\n\n following disclaimer.\n\n\n\n* Redistributions in binary form must reproduce the above\n\n copyright notice, this list of conditions and the\n\n following disclaimer in the documentation and/or other\n\n materials provided with the distribution.\n\n\n\n* Neither the name of the assimp team, nor the names of its\n", "file_path": "src/dependencies/assimp/code/PretransformVertices.h", "rank": 77, "score": 146228.2868903945 }, { "content": "Open Asset Import Library (assimp)\n\n----------------------------------------------------------------------\n\n\n\nCopyright (c) 2006-2012, assimp team\n\nAll rights reserved.\n\n\n\nRedistribution and use of this software in source and binary forms, \n\nwith or without modification, are permitted provided that the \n\nfollowing conditions are met:\n\n\n\n* Redistributions of source code must retain the above\n\n copyright notice, this list of conditions and the\n\n following disclaimer.\n\n\n\n* Redistributions in binary form must reproduce the above\n\n copyright notice, this list of conditions and the\n\n following disclaimer in the documentation and/or other\n\n materials provided with the distribution.\n\n\n\n* Neither the name of the assimp team, nor the names of its\n", "file_path": "src/dependencies/assimp/code/TextureTransform.h", "rank": 78, "score": 146226.4610574569 }, { "content": "struct ExpectedExceptionTraits<NoExceptionExpected>\n\n{\n\n static void expectedException()\n\n {\n\n }\n\n};\n\n\n\n\n\n#endif\n\n\n\n//*** FIXME: rework this when class Fixture is implemented. ***//\n\n\n\n\n\n/*! \\brief Generate a test case from a fixture method.\n\n * \\ingroup WritingTestFixture\n\n *\n\n * A test caller provides access to a test case method \n\n * on a test fixture class. Test callers are useful when \n\n * you want to run an individual test or add it to a \n\n * suite.\n", "file_path": "src/dependencies/assimp/contrib/cppunit-1.12.1/include/cppunit/TestCaller.h", "rank": 79, "score": 145985.1639417485 }, { "content": "Open Asset Import Library (assimp)\n\n----------------------------------------------------------------------\n\n\n\nCopyright (c) 2006-2012, assimp team\n\nAll rights reserved.\n\n\n\nRedistribution and use of this software in source and binary forms, \n\nwith or without modification, are permitted provided that the \n\nfollowing conditions are met:\n\n\n\n* Redistributions of source code must retain the above\n\n copyright notice, this list of conditions and the\n\n following disclaimer.\n\n\n\n* Redistributions in binary form must reproduce the above\n\n copyright notice, this list of conditions and the\n\n following disclaimer in the documentation and/or other\n\n materials provided with the distribution.\n\n\n\n* Neither the name of the assimp team, nor the names of its\n", "file_path": "src/dependencies/assimp/include/assimp/quaternion.h", "rank": 80, "score": 145966.6438157566 }, { "content": "---------------------------------------------------------------------------\n\nOpen Asset Import Library (assimp)\n\n---------------------------------------------------------------------------\n\n\n\nCopyright (c) 2006-2012, assimp team\n\n\n\nAll rights reserved.\n\n\n\nRedistribution and use of this software in source and binary forms, \n\nwith or without modification, are permitted provided that the following \n\nconditions are met:\n\n\n\n* Redistributions of source code must retain the above\n\n copyright notice, this list of conditions and the\n\n following disclaimer.\n\n\n\n* Redistributions in binary form must reproduce the above\n\n copyright notice, this list of conditions and the\n\n following disclaimer in the documentation and/or other\n\n materials provided with the distribution.\n\n\n", "file_path": "src/dependencies/assimp/include/assimp/vector2.h", "rank": 81, "score": 145966.6438157566 }, { "content": "---------------------------------------------------------------------------\n\nOpen Asset Import Library (assimp)\n\n---------------------------------------------------------------------------\n\n\n\nCopyright (c) 2006-2012, assimp team\n\n\n\nAll rights reserved.\n\n\n\nRedistribution and use of this software in source and binary forms, \n\nwith or without modification, are permitted provided that the following \n\nconditions are met:\n\n\n\n* Redistributions of source code must retain the above\n\n copyright notice, this list of conditions and the\n\n following disclaimer.\n\n\n\n* Redistributions in binary form must reproduce the above\n\n copyright notice, this list of conditions and the\n\n following disclaimer in the documentation and/or other\n\n materials provided with the distribution.\n\n\n", "file_path": "src/dependencies/assimp/include/assimp/color4.h", "rank": 82, "score": 145966.6438157566 }, { "content": "", "file_path": "src/dependencies/assimp/include/assimp/matrix4x4.h", "rank": 83, "score": 145966.6438157566 }, { "content": "---------------------------------------------------------------------------\n\nOpen Asset Import Library (assimp)\n\n---------------------------------------------------------------------------\n\n\n\nCopyright (c) 2006-2012, assimp team\n\n\n\nAll rights reserved.\n\n\n\nRedistribution and use of this software in source and binary forms, \n\nwith or without modification, are permitted provided that the following \n\nconditions are met:\n\n\n\n* Redistributions of source code must retain the above\n\n copyright notice, this list of conditions and the\n\n following disclaimer.\n\n\n\n* Redistributions in binary form must reproduce the above\n\n copyright notice, this list of conditions and the\n\n following disclaimer in the documentation and/or other\n\n materials provided with the distribution.\n\n\n", "file_path": "src/dependencies/assimp/include/assimp/vector3.h", "rank": 84, "score": 145966.6438157566 }, { "content": "", "file_path": "src/dependencies/assimp/include/assimp/matrix3x3.h", "rank": 85, "score": 145966.6438157566 }, { "content": "\tService();\n\n\t~Service();\n\nprivate:\n\n\tuint32 cloneBatch(uint32 id,uint32 layerId,uint32 textureId);\n\n\tbool loadCorePipeline(int id,const char* name);\n\n\n\n\tuint32 registerFontBatch(const data::Font* font);\n\n\tcore::BufferAllocator batches_;\n\n\tcore::BufferAllocator fontBatches_;\n\n\n\n\tenum {\n\n\t\tkMaxGeometries = 3\n\n\t};\n\n\tstruct Mesh {\n\n\t\tuint32 vertexSize;\n\n\t\trendering::Buffer vbo;\n\n\t\trendering::Buffer ibo;\n\n\t\trendering::Mesh mesh;\n\n\t};\n\n\tMesh meshes_[kMaxGeometries];\n", "file_path": "src/rendering/ui.h", "rank": 88, "score": 78.78206597987672 }, { "content": "\t\t//Create a new batch for this texture.\n\n\t\trendering::ui::Batch batch;\n\n\t\tbatch.depth = 0;\n\n\t\tbatch.name = \"TextureView\";\n\n\t\tauto pipelineId = ev.renderer->uiPipeline(pipeline_);\n\n\t\tbatchId = ev.renderer->registerBatch(batch,pipelineId);\n\n\t}\n\n\tauto geometry = ev.renderer->allocate(ev.layerId,batchId,ev.renderer->uiTexture(texture_),4,6);\n\n\trendering::draw2D::positionInt16::textured::coloured::quad(geometry,ev.position,ev.position + ev.size,defaultTextureCoords,color_);\t\n\n}\n\n\n\nRectangle::Rectangle(uint32 colour){\n\n\tcolors_[0] = colors_[1] = colors_[2] = colors_[3] = colour;\n\n\tcheckOpaque(colour);\n\n}\n\nvoid Rectangle::makeFlat(uint32 colour) {\n\n\tcolors_[0] = colors_[1] = colors_[2] = colors_[3] = colour;\n\n\tcheckOpaque(colour);\n\n}\n\nvoid Rectangle::makeTopDownGradient(uint32 topColour,uint32 bottomColour){\n", "file_path": "src/ui/components.cpp", "rank": 91, "score": 69.18575831451984 }, { "content": "\trendering::Pipeline::GLSLLayout glslLayout;\n\n\tchar attributeBufferStorage[2048];\n\n\tcore::BufferAllocator attributeBuffer(core::Bytes(attributeBufferStorage,sizeof(attributeBufferStorage)),core::BufferAllocator::GrowOnOverflow);\n\n\tuint32 attributeBufferOffset = 0;\n\n\tif(vertexAttributeCount){\n\n\t\tglslLayout.vertexAttributes = (const char**) attributeBuffer.allocate(vertexAttributeCount * sizeof(char*),alignof(char*));\n\n\t\tglslLayout.vertexAttributeCount = vertexAttributeCount;\n\n\t\tfor(uint32 i = 0;i< vertexAttributeCount;++i){\n\n\t\t\tauto dest = (char*)attributeBuffer.allocate(vertexAttributes[i].length()+1,0);\n\n\t\t\tmemcpy(dest,vertexAttributes[i].begin,vertexAttributes[i].length());\n\n\t\t\tdest[vertexAttributes[i].length()] = '\\0';\n\n\t\t\tglslLayout.vertexAttributes[i] = dest;\n\n\t\t}\n\n\t}\n\n\tauto pipeline = rendering->create(shaders,shaderCount,glslLayout);\n\n#else\n\n\tauto pipeline = rendering->create(shaders,shaderCount);\n\n#endif\n\n\n\n\tauto obj = parser->service->newPipeline();\n\n\tnew(obj) ::data::Pipeline(pipeline);\n\n\tparser->service->mapPointerToID(parser->bundle,obj,id);\n\n\tparser->service->registerPipeline(pipeline);\n\n}\n\n\n\n//\n\n\n", "file_path": "src/data/intermediate/bundle/parser.cpp", "rank": 97, "score": 63.59396663842986 }, { "content": "\t\t\tservice->mapPointerToID(bundle,destMesh,self->id);\n\n\t\t}\n\n\t\tvoid Reader::processMaterial(const char* name,const char** textures,size_t textureCount) {\n\n\t\t\tcore::bufferStringStream::Formatter fmt;\n\n\t\t\tif(!name || !strlen(name)) {\n\n\t\t\t\tusing namespace core::bufferStringStream;\n\n\t\t\t\tname = asCString(fmt.allocator<<self->id<<\".material.\"<<materialId);\n\n\t\t\t}\n\n\n\n\t\t\tauto destMaterial = service->allocateObject<::data::Material>();\n\n\t\t\trendering::Texture2D ts[::data::Material::kMaxTextures];\n\n\t\t\tfor(size_t i = 0;i<textureCount;++i){\n\n\t\t\t\tTexture texture;\n\n\t\t\t\ttexture.parser = parser;\n\n\t\t\t\ttexture.id = core::Bytes(nullptr,nullptr);\n\n\t\t\t\ttexture.mipmapping = true;\n\n\t\t\t\ttexture.path = core::Bytes((void*)textures[i],strlen(textures[i]));\n\n\t\t\t\ttexture.end();\n\n\t\t\t\tts[i] = texture.result;\n\n\t\t\t}\n", "file_path": "src/data/intermediate/bundle/parser.cpp", "rank": 99, "score": 58.4321715741477 } ]