hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 77k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 653k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8ed85250c8014f4cdfb3b204486aba15d51f0bbb | 357 | cpp | C++ | test/test4.cpp | Prilog/fp-debt | d8bd328cb403151fab1f9b915dacd37fbd3e5d36 | [
"MIT"
] | null | null | null | test/test4.cpp | Prilog/fp-debt | d8bd328cb403151fab1f9b915dacd37fbd3e5d36 | [
"MIT"
] | null | null | null | test/test4.cpp | Prilog/fp-debt | d8bd328cb403151fab1f9b915dacd37fbd3e5d36 | [
"MIT"
] | null | null | null | bool satisfy(int x, int y) {
if (x < 10) {
if (y > 4) {
return true;
} else {
return false;
}
} else {
return false;
}
}
int main() {
int a = 7;
int b = 7;
while (satisfy(a, b)) {
cout << a;
cout << " ";
cout << b;
cout << "\n";
a = a + 1;
b = b - 1;
}
cout << "finished\n";
return 0;
} | 13.730769 | 28 | 0.403361 |
8ed99072c5824ac16f4a579bfc9832b3a4202f97 | 198 | cpp | C++ | qfb-messenger/src/network_reply_handler.cpp | NickCis/harbour-facebook-messenger | b2c2305fdcec27321893c3230bbd9e724773bd7d | [
"MIT"
] | 1 | 2015-05-05T22:45:11.000Z | 2015-05-05T22:45:11.000Z | qfb-messenger/src/network_reply_handler.cpp | NickCis/harbour-facebook-messenger | b2c2305fdcec27321893c3230bbd9e724773bd7d | [
"MIT"
] | null | null | null | qfb-messenger/src/network_reply_handler.cpp | NickCis/harbour-facebook-messenger | b2c2305fdcec27321893c3230bbd9e724773bd7d | [
"MIT"
] | null | null | null | #include "network_reply_handler.h"
NetworkReplyHandler::NetworkReplyHandler(QNetworkReply* r) :
QObject(r),
reply(r)
{
connect(this->reply, SIGNAL(finished()), this, SLOT(replyFinished()));
}
| 18 | 71 | 0.737374 |
8eda40c7ef81d7a9161be254020ec7fa33e68e6e | 801 | cpp | C++ | HW1Submit/main.cpp | manamhr/ITP365 | 616ea8f4074e05fd26eb8ece712b2df6aa70111f | [
"MIT"
] | null | null | null | HW1Submit/main.cpp | manamhr/ITP365 | 616ea8f4074e05fd26eb8ece712b2df6aa70111f | [
"MIT"
] | null | null | null | HW1Submit/main.cpp | manamhr/ITP365 | 616ea8f4074e05fd26eb8ece712b2df6aa70111f | [
"MIT"
] | null | null | null | // ITP 365 Spring 2017
// HW1 - Sieve of Eratosthenes
// Name: Mana Mehraein
// Email: mehraein@usc.edu
// Platform: Mac
#include <iostream>
#include "gwindow.h"
#include "sieve.h"
#include <string>
#include "vector.h"
#include "strlib.h"
int main(int argc, char** argv)
{
// Create a 500x500 window
GWindow gw(500, 500);
Vector<int> number;
Vector<NumberType> type;
// Call initVectors in main
initVectors (number, type);
// drawGrid
drawGrid(gw,number,type);
int index=2;
// loop to find prime numbers and composites
while (calcNextPrime(number, type, index)!=-1)
{
drawGrid(gw,number,type);
pause(1000.0);
index++;
}
return 0;
}
| 18.627907 | 51 | 0.561798 |
8edd65aebe7ac2a9a4c04604b60008f586d0ae7b | 239 | hh | C++ | mimosa/rpc/http-call.hh | abique/mimosa | 42c0041b570b55a24c606a7da79c70c9933c07d4 | [
"MIT"
] | 24 | 2015-01-19T16:38:24.000Z | 2022-01-15T01:25:30.000Z | mimosa/rpc/http-call.hh | abique/mimosa | 42c0041b570b55a24c606a7da79c70c9933c07d4 | [
"MIT"
] | 2 | 2017-01-07T10:47:06.000Z | 2018-01-16T07:19:57.000Z | mimosa/rpc/http-call.hh | abique/mimosa | 42c0041b570b55a24c606a7da79c70c9933c07d4 | [
"MIT"
] | 7 | 2015-01-19T16:38:31.000Z | 2020-12-12T19:10:30.000Z | #pragma once
#include "json.hh"
namespace mimosa
{
namespace rpc
{
bool httpCall(const std::string &url,
const google::protobuf::Message &request,
google::protobuf::Message *response);
}
}
| 17.071429 | 57 | 0.589958 |
8ede1878426df41d8ee00964ca039bddd4c4dd65 | 7,365 | hpp | C++ | src/vm/objects/function.hpp | mbeckem/tiro | b3d729fce46243f25119767c412c6db234c2d938 | [
"MIT"
] | 10 | 2020-01-23T20:41:19.000Z | 2021-12-28T20:24:44.000Z | src/vm/objects/function.hpp | mbeckem/tiro | b3d729fce46243f25119767c412c6db234c2d938 | [
"MIT"
] | 22 | 2021-03-25T16:22:08.000Z | 2022-03-17T12:50:38.000Z | src/vm/objects/function.hpp | mbeckem/tiro | b3d729fce46243f25119767c412c6db234c2d938 | [
"MIT"
] | null | null | null | #ifndef TIRO_VM_OBJECTS_FUNCTION_HPP
#define TIRO_VM_OBJECTS_FUNCTION_HPP
#include "common/adt/span.hpp"
#include "vm/handles/handle.hpp"
#include "vm/object_support/layout.hpp"
#include "vm/objects/value.hpp"
namespace tiro::vm {
/// Represents executable byte code, typically used to
/// represents the instructions within a function.
///
/// TODO: Need a bytecode validation routine.
/// TODO: Code should not be movable on the heap.
class Code final : public HeapValue {
public:
using Layout = BufferLayout<byte, alignof(byte)>;
static Code make(Context& ctx, Span<const byte> code);
explicit Code(Value v)
: HeapValue(v, DebugCheck<Code>()) {}
const byte* data();
size_t size();
Span<const byte> view() { return {data(), size()}; }
Layout* layout() const { return access_heap<Layout>(); }
};
/// Represents the table of exception handlers for a function.
class HandlerTable final : public HeapValue {
public:
struct Entry {
u32 from; // start pc (inclusive)
u32 to; // end pc (exclusive)
u32 target; // target pc
bool operator==(const Entry& other) const {
return from == other.from && to == other.to && target == other.target;
}
bool operator!=(const Entry& other) const { return !(*this == other); }
};
using Layout = BufferLayout<Entry, alignof(Entry)>;
/// Creates a new table with the given set of entries.
/// \pre `entries` must be sorted. The individual entries must not overlap.
static HandlerTable make(Context& ctx, Span<const Entry> entries);
explicit HandlerTable(Value v)
: HeapValue(v, DebugCheck<HandlerTable>()) {}
const Entry* data();
size_t size();
Span<const Entry> view() { return {data(), size()}; }
/// Returns the appropriate table entry for the given program counter.
/// Returns nullptr if no such entry exists.
const Entry* find_entry(u32 pc);
Layout* layout() const { return access_heap<Layout>(); }
};
/// Represents a function prototype.
///
/// Function prototypes contain the static properties of functions and are referenced
/// by the actual function instances. Function prototypes are a necessary implementation
/// detail because actual functions (i.e. with closures) share all static properties
/// but have different closure variables each.
class CodeFunctionTemplate final : public HeapValue {
private:
struct Payload {
u32 params;
u32 locals;
};
enum Slots {
NameSlot,
ModuleSlot,
CodeSlot,
HandlersSlot,
SlotCount_,
};
public:
using Layout = StaticLayout<StaticSlotsPiece<SlotCount_>, StaticPayloadPiece<Payload>>;
static CodeFunctionTemplate make(Context& ctx, Handle<String> name, Handle<Module> module,
u32 params, u32 locals, Span<const HandlerTable::Entry> handlers, Span<const byte> code);
explicit CodeFunctionTemplate(Value v)
: HeapValue(v, DebugCheck<CodeFunctionTemplate>()) {}
/// The name of the function.
String name();
/// The module the function belongs to.
Module module();
/// The executable byte code of this function.
Code code();
/// Exception handler table for this function.
Nullable<HandlerTable> handlers();
/// The (minimum) number of required parameters.
u32 params();
/// The number of local variables used by the function. These must be allocated
/// on the stack before the function may execute.
u32 locals();
Layout* layout() const { return access_heap<Layout>(); }
};
/// Represents captured variables from an upper scope captured by a nested function.
/// ClosureContexts point to their parent (or null if they are at the root).
class Environment final : public HeapValue {
private:
enum Slots {
ParentSlot,
SlotCount_,
};
public:
using Layout = FixedSlotsLayout<Value, StaticSlotsPiece<SlotCount_>>;
static Environment make(Context& ctx, size_t size, MaybeHandle<Environment> parent);
explicit Environment(Value v)
: HeapValue(v, DebugCheck<Environment>()) {}
Nullable<Environment> parent();
Value* data();
size_t size();
Span<Value> values() { return {data(), size()}; }
/// Reads the value at the specified index.
/// \pre `index() < size()`
Value get(size_t index);
/// Writes the value at the specified index.
/// \pre `index() < size()`
void set(size_t index, Value value);
// level == 0 -> return *this. Returns null in the unlikely case that the level is invalid.
Nullable<Environment> parent(size_t level);
Layout* layout() const { return access_heap<Layout>(); }
};
/// Represents a function value.
///
/// A function can be thought of a pair of a closure context and a function template:
///
/// - The function template contains the static properties (parameter declarations, bytecode, ...)
/// and is never null. All closure function that are constructed by the same function declaration
/// share a common function template instance.
/// - The closure context contains the captured variables bound to this function object
/// and can be null.
/// - The function combines the two.
///
/// Only the function type is exposed within the language.
class CodeFunction final : public HeapValue {
private:
enum Slots {
TmplSlot,
ClosureSlot,
SlotCount_,
};
public:
using Layout = StaticLayout<StaticSlotsPiece<SlotCount_>>;
static CodeFunction
make(Context& ctx, Handle<CodeFunctionTemplate> tmpl, MaybeHandle<Environment> closure);
explicit CodeFunction(Value v)
: HeapValue(v, DebugCheck<CodeFunction>()) {}
CodeFunctionTemplate tmpl();
Nullable<Environment> closure();
Layout* layout() const { return access_heap<Layout>(); }
};
/// A function where the first parameter ("this") has been bound
/// and will be automatically passed as the first argument
/// of the wrapped function.
class BoundMethod final : public HeapValue {
private:
enum Slots {
FunctionSlot,
ObjectSlot,
SlotCount_,
};
public:
using Layout = StaticLayout<StaticSlotsPiece<SlotCount_>>;
static BoundMethod make(Context& ctx, Handle<Value> function, Handle<Value> object);
explicit BoundMethod(Value v)
: HeapValue(v, DebugCheck<BoundMethod>()) {}
Value function();
Value object();
Layout* layout() const { return access_heap<Layout>(); }
};
/// For functions that rely on runtime magic, which is implemented in the
/// interpreter itself.
///
/// TODO: This class should eventually be replaced by
/// coroutine-style native functions, which are not available yet.
class MagicFunction final : public HeapValue {
public:
enum Which {
Catch,
};
private:
struct Data {
Which which;
};
public:
using Layout = StaticLayout<StaticPayloadPiece<Data>>;
static MagicFunction make(Context& ctx, Which which);
explicit MagicFunction(Value v)
: HeapValue(v, DebugCheck<MagicFunction>()) {}
Which which();
Layout* layout() const { return access_heap<Layout>(); }
};
std::string_view to_string(MagicFunction::Which);
} // namespace tiro::vm
TIRO_ENABLE_FREE_TO_STRING(tiro::vm::MagicFunction::Which);
#endif // TIRO_VM_OBJECTS_FUNCTION_HPP
| 29.22619 | 100 | 0.677529 |
8edf2cc62dde1c74a2e30859cf5d18206771b2eb | 184 | cpp | C++ | judger/uoj_judger/tests/newer/answer14.cpp | contropist/uoj | 114ebf690dcfb22ec899cbdc3d3cb77a30b46285 | [
"MIT"
] | null | null | null | judger/uoj_judger/tests/newer/answer14.cpp | contropist/uoj | 114ebf690dcfb22ec899cbdc3d3cb77a30b46285 | [
"MIT"
] | null | null | null | judger/uoj_judger/tests/newer/answer14.cpp | contropist/uoj | 114ebf690dcfb22ec899cbdc3d3cb77a30b46285 | [
"MIT"
] | null | null | null | #pragma GCC optimize ("O0")
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
for (int i = 0; i < (1 << 5); i++)
new int[1 << 20]();
return 0;
}
| 15.333333 | 38 | 0.538043 |
8ee250a474a297cfa9773bc8ee3176d49ab97767 | 1,935 | cpp | C++ | BasiliskII/src/BeOS/xpram_beos.cpp | jvernet/macemu | c616a0dae0f451fc15016765c896175fae3f46cf | [
"Intel",
"X11"
] | 940 | 2015-01-04T12:20:10.000Z | 2022-03-29T12:35:27.000Z | BasiliskII/src/BeOS/xpram_beos.cpp | Seanpm2001-virtual-machines/macemu | c616a0dae0f451fc15016765c896175fae3f46cf | [
"Intel",
"X11"
] | 163 | 2015-02-10T09:08:10.000Z | 2022-03-13T05:48:10.000Z | BasiliskII/src/BeOS/xpram_beos.cpp | Seanpm2001-virtual-machines/macemu | c616a0dae0f451fc15016765c896175fae3f46cf | [
"Intel",
"X11"
] | 188 | 2015-01-07T19:46:11.000Z | 2022-03-26T19:06:00.000Z | /*
* xpram_beos.cpp - XPRAM handling, BeOS specific stuff
*
* Basilisk II (C) 1997-2008 Christian Bauer
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <StorageKit.h>
#include <unistd.h>
#include "sysdeps.h"
#include "xpram.h"
// XPRAM file name and path
#if POWERPC_ROM
const char XPRAM_FILE_NAME[] = "SheepShaver_NVRAM";
#else
const char XPRAM_FILE_NAME[] = "BasiliskII_XPRAM";
#endif
static BPath xpram_path;
/*
* Load XPRAM from settings file
*/
void LoadXPRAM(const char *vmdir)
{
// Construct XPRAM path
find_directory(B_USER_SETTINGS_DIRECTORY, &xpram_path, true);
xpram_path.Append(XPRAM_FILE_NAME);
// Load XPRAM from settings file
int fd;
if ((fd = open(xpram_path.Path(), O_RDONLY)) >= 0) {
read(fd, XPRAM, XPRAM_SIZE);
close(fd);
}
}
/*
* Save XPRAM to settings file
*/
void SaveXPRAM(void)
{
if (xpram_path.InitCheck() != B_NO_ERROR)
return;
int fd;
if ((fd = open(xpram_path.Path(), O_WRONLY | O_CREAT, 0666)) >= 0) {
write(fd, XPRAM, XPRAM_SIZE);
close(fd);
}
}
/*
* Delete PRAM file
*/
void ZapPRAM(void)
{
// Construct PRAM path
find_directory(B_USER_SETTINGS_DIRECTORY, &xpram_path, true);
xpram_path.Append(XPRAM_FILE_NAME);
// Delete file
unlink(xpram_path.Path());
}
| 22.764706 | 77 | 0.710078 |
8ee65978c71f54b000ca8db80dcf15b9bcd191ff | 11,443 | cpp | C++ | jmax/Window.cpp | JeanGamain/jmax | 1d4aee47c7fad25b9c4d9a678b84c5f4aad98c04 | [
"MIT"
] | null | null | null | jmax/Window.cpp | JeanGamain/jmax | 1d4aee47c7fad25b9c4d9a678b84c5f4aad98c04 | [
"MIT"
] | null | null | null | jmax/Window.cpp | JeanGamain/jmax | 1d4aee47c7fad25b9c4d9a678b84c5f4aad98c04 | [
"MIT"
] | null | null | null | #include "Window.hpp"
#include "jmax.hpp"
#include "math.h"
#include "shader/Shader.hpp"
#include <map>
#include <stdexcept>
#include <string>
#include <utility>
namespace jmax {
Window::Window(unsigned int width, unsigned int height)
: view(width, height)
, _windowIO()
, _resizeAction(
std::string("window_resize"), std::string("Resize window image buffer"), IO_INPUT_FWINDOW, actionResizeWindow)
, _fileDropAction(
std::string("window_filedrop"),
std::string("Process files drag&drop as new model to import"),
IO_INPUT_FWINDOW,
actionFileDropImport)
, _renderTimer()
, _background(NULL)
, _somvp("omvp")
, _sgCameraLocalPos("gCameraLocalPos")
, _globalLight(vec3(0.6f))
, _simpleUniDirectLight(vec3(0.0f, -1.0f, 0.15f), vec3(0.4f))
, _materialUniform(Material::getUniform())
, _simpleUniDirectLightUniform(UniDirectionalLight::getUniform())
, _mainShaderProg(NULL)
, _guiShaderProg(NULL)
, _mainVs(NULL)
, _mainFs(NULL)
, _maxFps(0)
, _vsync(true)
, _fps(0)
// GUI stuff
, _guiInit(false)
, _guiEnable(false)
, _modelPickerEnable(false)
, _selectionBuffer(0)
, _selectionIds{0}
, _selectedModel(NULL)
, _selectedMaterialId(0)
, _guiFpsStats()
, _guiFs(NULL)
{
const char* error;
if ((error = jmax::init()) != NULL) {
throw new std::runtime_error(error);
}
initRender(width, height, "JMAX");
setupRenderSettings();
initInputBind();
setupSceneRender();
setMaxFps(222);
}
Window::~Window()
{
delete _materialUniform;
delete _simpleUniDirectLightUniform;
disableBackgroundSurface();
for (jmax::Model* model : _models) {
delete model;
}
if (_mainShaderProg) delete _mainShaderProg;
if (_guiShaderProg) delete _guiShaderProg;
if (_mainVs) delete _mainVs;
if (_mainFs) delete _mainFs;
// UI
if (_guiFs) delete _guiFs;
if (_guiInit) gui::deleteUI();
glfwDestroyWindow(_window);
glfwTerminate();
}
void Window::initRender(unsigned int width, unsigned height, char* windowsTitle)
{
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, true); // DEBUG
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, JMAX_GLVERSION_MAJOR);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, JMAX_GLVERSION_MINOR);
glfwWindowHint(GLFW_OPENGL_PROFILE, JMAX_GLVERSION_TYPE);
const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
glfwWindowHint(GLFW_RED_BITS, mode->redBits);
glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits);
glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits);
glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate);
if (!(_window = glfwCreateWindow(width, height, windowsTitle, NULL, NULL))) {
fprintf(stderr, "Error glfwCreateWindow()");
}
glfwMakeContextCurrent(_window);
glfwSwapInterval(_vsync ? 1 : 0);
jmax::setGLDebug();
}
void Window::setClearColor(vec4 color)
{
GLclampf Red = color.x, Green = color.y, Blue = color.z, Alpha = color.w;
glClearColor(Red, Green, Blue, Alpha);
}
void Window::setupRenderSettings()
{
setClearColor();
glEnable(GL_CULL_FACE);
/*
glFrontFace(GL_CW);
glCullFace(GL_BACK);
*/
glFrontFace(GL_CW);
glCullFace(GL_FRONT);
glEnable(GL_MULTISAMPLE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// GUI model/material picker
glGenBuffers(1, &_selectionBuffer);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, _selectionBuffer);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, _selectionBuffer);
glBufferStorage(GL_SHADER_STORAGE_BUFFER, sizeof(_selectionIds), &_selectionIds[0], GL_MAP_READ_BIT);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
}
void Window::setupSceneRender()
{
_mainVs = new Shader("../jmax/shader/shader.vs");
_mainFs = new Shader("../jmax/shader/shader.fs");
_guiFs = new Shader("../jmax/shader/gui_shader.fs");
_mainShaderProg = new jmax::ShaderProgram({_mainVs, _mainFs});
_guiShaderProg = new jmax::ShaderProgram({_mainVs, _guiFs});
_mainShaderProg->enable();
_scene.scale = vec3(1.0f);
_scene.position = vec3(0.0f, 0.0f, 2.0f);
_scene.rotation = vec3(0.0f, 0.01f, 0.0f);
}
void Window::initInputBind()
{
_input = new IO::InputActionManager(_window, this);
_input->addInput(&_windowIO);
_windowIO.bindAction(&_resizeAction, jmax::IO::WindowEvent(IO::WindowEvent::RESIZE));
_windowIO.bindAction(&_fileDropAction, jmax::IO::WindowEvent(IO::WindowEvent::FILEDROP));
}
void Window::render()
{
makeCurrent();
applyFpsControls();
_input->sync(1);
_renderTimer.reset();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
mat4 omvp;
mat4 mprojection = view.getProjection();
mat4 mview = view.getView();
mat4 mmodel = _scene.getMatrix();
mat4 mvp = mprojection * mview * mmodel;
view.bindUniform();
vec4 camLocPos =
_scene.getReversedRotationMatrix() * _scene.getReversedTranslationMatrix() * vec4(view.getPosition(), 1.0f);
glUniform3f(_sgCameraLocalPos(), camLocPos.x, camLocPos.y, camLocPos.z);
if (_background) {
_background->render(_somvp, _materialUniform);
}
glEnable(GL_DEPTH_TEST);
for (jmax::Model* model : _models) {
// sun
_simpleUniDirectLight.calcDirection(mmodel * mat4(mat3(model->getTransformation())));
_simpleUniDirectLight.bind(_simpleUniDirectLightUniform);
// global light
_globalLight.bind();
omvp = mvp * model->getTransformation();
glUniformMatrix4fv(_somvp(), 1, GL_FALSE, glm::value_ptr(omvp));
model->render(_materialUniform);
}
glDisable(GL_DEPTH_TEST);
renderGUI();
}
void Window::renderGUI()
{
gui::fpsStatsCalc(&_guiFpsStats, glfwGetTime(), _fps);
if (!_guiEnable || !_guiInit) {
return;
}
gui::newFrame();
ImGui::Begin("JMAX");
if (ImGui::CollapsingHeader("Render")) {
gui::LabelText("Render", "%s", (const char*)glGetString(GL_RENDERER));
gui::LabelText("Version", "%s", (const char*)glGetString(GL_VERSION));
gui::fpsStatsHistogram(&_guiFpsStats);
ImGui::Separator();
gui::Label("Vsync");
if (gui::ToggleSwitchBool(&_vsync)) {
setVSync(_vsync, true);
}
gui::SliderFloat("MAX", &_maxFps, 0.0f, _maxFpsMax, "%.1f fps");
}
if (ImGui::CollapsingHeader("Scene")) {
static_cast<Entity3d&>(_scene).drawUI();
if (ImGui::TreeNode("Light")) {
_globalLight.drawUI();
_simpleUniDirectLight.drawUI();
ImGui::TreePop();
}
if (ImGui::TreeNode("Background")) {
_background->drawUI();
ImGui::TreePop();
}
}
if (ImGui::CollapsingHeader("Camera")) {
view.drawUI();
}
if (ImGui::CollapsingHeader("Model")) {
gui::Label("Model picker");
if (gui::ToggleSwitchBool(&_modelPickerEnable) && !_modelPickerEnable) {
_selectedMaterialId = 0;
}
if (_modelPickerEnable) {
glBindBuffer(GL_SHADER_STORAGE_BUFFER, _selectionBuffer);
glGetBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, sizeof(_selectionIds), &_selectionIds[0]);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
_selectedModel = getModel(_selectionIds[0]);
_selectedMaterialId = _selectionIds[1];
}
gui::Label("Model");
const char* current_item = _selectedModel ? _selectedModel->getName().c_str() : NULL;
ImGui::PushItemWidth(ImGui::CalcItemWidth());
if (ImGui::BeginCombo("##Model combo", current_item)) {
int n = 0;
for (jmax::Model* model : _models) {
const char* item = model->getName().c_str();
bool is_selected = (current_item == item);
if (ImGui::Selectable(item, is_selected)) {
_selectedModel = model;
_selectedMaterialId = 0;
_modelPickerEnable = false;
}
if (is_selected) ImGui::SetItemDefaultFocus();
++n;
}
ImGui::EndCombo();
}
ImGui::PopItemWidth();
if (_selectedModel) {
_selectedModel->drawUI(_selectedMaterialId);
}
}
ImGui::End();
gui::render();
}
void Window::swapBuffer()
{
glfwSwapBuffers(_window);
}
void Window::renderLoop()
{
while (!shouldClose()) {
render();
swapBuffer();
pollEvents();
}
}
Model* Window::getModel(unsigned int id) const
{
if (id < 1) {
return NULL;
}
for (jmax::Model* model : _models) {
if (model->id == id) {
return model;
}
}
return NULL;
}
double Window::getDelta()
{
return _renderTimer();
}
float Window::getfDelta()
{
return (float)_renderTimer();
}
void Window::setVSync(bool enable, bool force)
{
if (_vsync == enable && !force) {
return;
}
_vsync = enable;
glfwSwapInterval(_vsync ? 1 : 0);
// ifdef WIN32
/* if (wglSwapIntervalEXT != nullptr) {
_vsync = enable;
if (enable) {
wglSwapIntervalEXT(1);
} else {
wglSwapIntervalEXT(0);
}
} else {
_vsync = false;
}
*/
}
bool Window::getVSync()
{
bool vsyncEnable = _vsync;
/*
if (wglGetSwapIntervalEXT != nullptr) {
vsyncEnable = wglGetSwapIntervalEXT() > 0;
}*/
return vsyncEnable;
}
void Window::makeCurrent()
{
glfwMakeContextCurrent(_window);
}
bool Window::shouldClose() const
{
return glfwWindowShouldClose(_window);
}
void Window::pollEvents()
{
glfwPollEvents();
}
void Window::enableBackgroundSurface(Texture* surfacePath)
{
if (!_background) {
makeCurrent();
_background = new BackgroundSurface(surfacePath);
}
}
void Window::disableBackgroundSurface()
{
if (_background) {
delete _background;
_background = NULL;
}
}
Model* Window::addModel(const char* modelPath)
{
const char* error;
printf("Adding model \"%s\"\n", modelPath);
makeCurrent();
Model* newObject = new Model();
if ((error = newObject->import(modelPath)) != NULL) {
printf("%s", error);
delete newObject;
return NULL;
}
_models.push_back(newObject);
// delete newObject;
return newObject;
}
void Window::setMaxFps(float fps)
{
_maxFps = (fps < _maxFpsMin || fps > _maxFpsMax) ? 0.0f : fps;
}
void Window::applyFpsControls()
{
double time = _renderTimer.getSecond();
if (_maxFps > 0.0f) {
double minTime = 1;
minTime /= _maxFps;
while (minTime > time) {
// glfwPollEvents();
time = _renderTimer.getSecond();
}
}
_fps = static_cast<float>(1. / time);
}
IO::InputActionManager* Window::getInputManager()
{
return _input;
}
void Window::setGuiEnable(bool enable)
{
_guiEnable = enable;
if (_guiEnable) {
if (!_guiInit) {
gui::newUI(_window);
_guiInit = true;
}
_guiShaderProg->enable();
} else {
_mainShaderProg->enable();
}
}
bool Window::getGuiEnable() const
{
return _guiEnable;
}
void Window::actionResizeWindow(Window* window, IO::IInput* input, void* userContext)
{
IO::Window* windowIO = (IO::Window*)input;
ivec2 size = windowIO->getResizeData();
if (size.x == 0 || size.y == 0) {
return;
}
window->makeCurrent();
// glfwGetFramebufferSize(me->window, &size.x, &size.y);
window->view.resize(size.x, size.y);
glViewport(0, 0, size.x, size.y);
}
/*
void Engine::hRefresh(GLFWwindow* window)
{
Engine* me = (Engine*)jmax::IO::InputActionManager::getAppContext(window);
me->render();
}
*/
void Window::actionFileDropImport(Window* window, IO::IInput* input, void* userContext)
{
IO::Window* windowIO = (IO::Window*)input;
const std::list<std::string>& files = windowIO->getFileDropsData();
for (auto const& file : files) {
window->addModel(file.c_str());
}
windowIO->clearFileDropsData();
}
} // namespace jmax
| 24.450855 | 120 | 0.672289 |
8ee690a8f8a24b61111ea21d5c0190700cbe681f | 955 | hpp | C++ | include/cores/pdump_log.hpp | dotcom/QDPDK | 9f430f9b0cef36228d14f763a023d0ff13f6a8a8 | [
"MIT"
] | 1 | 2022-02-17T03:56:57.000Z | 2022-02-17T03:56:57.000Z | include/cores/pdump_log.hpp | dotcom/QDPDK | 9f430f9b0cef36228d14f763a023d0ff13f6a8a8 | [
"MIT"
] | null | null | null | include/cores/pdump_log.hpp | dotcom/QDPDK | 9f430f9b0cef36228d14f763a023d0ff13f6a8a8 | [
"MIT"
] | null | null | null | #pragma once
#include "qdpdk.hpp"
#define BURST_SIZE 32
template<class FROM, class TO>
class CorePdumpLog{
protected:
QDPDK::DeqInterface<FROM> from;
QDPDK::EnqInterface<TO> to;
public:
CorePdumpLog(FROM deq, TO enq) : from(deq), to(enq){};
void FirstCycle(){}
void LastCycle(){}
void Cycle() {
rte_mbuf *bufs[BURST_SIZE];
int nb_rx = from.Dequeue((rte_mbuf **)bufs, BURST_SIZE);
if (unlikely(nb_rx == 0))
return;
for (int n = 0; n < nb_rx; n++){
int len = bufs[n]->data_len;
auto pkt = rte_pktmbuf_mtod(bufs[n], char*);
char str[ETHER_MAX_LEN*5] = "";
for (int i=0;i<len;i++){
sprintf(str, "%s 0x%02x", str, 0x000000ff & pkt[i]);
}
rte_log(RTE_LOG_INFO, RTE_LOGTYPE_USER3, "==== PDUMP LOG ==== %u\n %s\n", rte_lcore_id(), str);
}
to.Enqueue((rte_mbuf **)bufs, nb_rx);
}
}; | 27.285714 | 107 | 0.548691 |
8ee6c42df047eec64719e4e26ad5122ca0b407fd | 2,541 | cpp | C++ | morse/DotNet/D3DVisualizator/DisplayableCoordinateSystem.cpp | jonnyzzz/phd-project | beab8615585bd52ef9ee1c19d1557e8c933c047a | [
"Apache-2.0"
] | 1 | 2019-12-24T15:52:45.000Z | 2019-12-24T15:52:45.000Z | morse/DotNet/D3DVisualizator/DisplayableCoordinateSystem.cpp | jonnyzzz/phd-project | beab8615585bd52ef9ee1c19d1557e8c933c047a | [
"Apache-2.0"
] | null | null | null | morse/DotNet/D3DVisualizator/DisplayableCoordinateSystem.cpp | jonnyzzz/phd-project | beab8615585bd52ef9ee1c19d1557e8c933c047a | [
"Apache-2.0"
] | null | null | null | #include "StdAfx.h"
#include ".\displayablecoordinatesystem.h"
const DWORD DisplayableCoordinateSystem::POINTVERTEX::FVF = D3DFVF_XYZ | D3DFVF_DIFFUSE;
DisplayableCoordinateSystem::DisplayableCoordinateSystem(void)
{
vb = NULL;
axisColor[0] = 0xff0000;
axisColor[1] = 0x00ff00;
axisColor[2] = 0x0000ff;
}
DisplayableCoordinateSystem::~DisplayableCoordinateSystem(void)
{
Dispose();
}
HRESULT DisplayableCoordinateSystem::Create(LPDIRECT3DDEVICE8 d3d_device, D3DXVECTOR3 x[3]) {
this->x[0] = x[0];
this->x[1] = x[1];
this->x[2] = x[2];
this->d3d_device = d3d_device;
return CreateVertexBuffer();
}
void DisplayableCoordinateSystem::Dispose() {
if (vb != NULL) {
vb->Release();
}
}
/////////////////////////////////////////////////////////////////////////////////////
HRESULT DisplayableCoordinateSystem::Render() {
HRESULT hr = initDevice();
if (FAILED(hr)) return hr;
hr = render();
if (FAILED(hr)) return hr;
return S_OK;
}
HRESULT DisplayableCoordinateSystem::initDevice() {
HRESULT hr;
hr = d3d_device->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );
if (FAILED(hr)) return hr;
hr = d3d_device->SetRenderState( D3DRS_LIGHTING, FALSE );
if (FAILED(hr)) return hr;
return S_OK;
}
HRESULT DisplayableCoordinateSystem::render() {
HRESULT hr;
printf("Coordinated Render Started\n");
hr = d3d_device->SetStreamSource(0, vb, sizeof(POINTVERTEX));
if (FAILED(hr)) return hr;
hr = d3d_device->SetVertexShader(POINTVERTEX::FVF);
if (FAILED(hr)) return hr;
hr = d3d_device->DrawPrimitive(D3DPT_LINELIST, 0, 3);
if (FAILED(hr)) return hr;
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////////
HRESULT DisplayableCoordinateSystem::CreateVertexBuffer() {
const int factor = 6;
HRESULT hr;
POINTVERTEX* pv = NULL;
hr = d3d_device->CreateVertexBuffer( factor * sizeof(POINTVERTEX),
D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY | D3DUSAGE_POINTS,
POINTVERTEX::FVF, D3DPOOL_DEFAULT, &vb );
if (FAILED(hr)) {
printf("Creation Failed: Parameters Of Creation: number = %d\n", factor);
return hr;
}
hr = vb->Lock( 0, factor * sizeof(POINTVERTEX),
(BYTE**) &pv, D3DLOCK_DISCARD );
if (FAILED(hr)) {
printf("Failed to create Lock created VertexBuffer\n");
vb->Release();
vb = NULL;
return hr;
}
for (int i=0; i<3; i++) {
pv->v = D3DXVECTOR3(0.0f, 0.0f, 0.0f);
pv->color = axisColor[i];
pv++;
pv->v = D3DXVECTOR3(x[i][0], x[i][1], x[i][2])*100;
pv->color = axisColor[i];
pv++;
}
hr = vb->Unlock();
return hr;
} | 21.717949 | 93 | 0.645415 |
8ee818419c7f2148571b8a8d244209147662bd80 | 749 | cc | C++ | Source/VM/Source/instruction.cc | DylanEHolland/liz | 50f030896fcca272d4e0f2186e84896d7b93ca40 | [
"BSD-3-Clause"
] | null | null | null | Source/VM/Source/instruction.cc | DylanEHolland/liz | 50f030896fcca272d4e0f2186e84896d7b93ca40 | [
"BSD-3-Clause"
] | 1 | 2022-02-21T04:58:44.000Z | 2022-02-21T05:14:14.000Z | Source/VM/Source/instruction.cc | DylanEHolland/liz | 50f030896fcca272d4e0f2186e84896d7b93ca40 | [
"BSD-3-Clause"
] | null | null | null | /**
* @file instruction.cc
* @author Dylan E. Holland (salinson1138@gmail.com)
* @brief
* @version 0.1
* @date 2022-03-16
*
* @copyright Copyright (c) 2022
*
*/
#include <VM/Include/instruction.h>
#include <Common/Include/output.h>
namespace liz::vm {
Instruction::Instruction() {
}
Instruction::~Instruction() {
}
void Instruction::toByteCode() {
}
void Instruction::fromIntermediate(struct intermediateInstruction *ins) {
//ins->opcode
}
class Instruction *fromByteCodeInstruction() {
class Instruction *buffer = new Instruction();
return buffer;
}
void intermediateInstructionToBytes(struct intermediateInstruction *ins) {
}
}
| 18.268293 | 78 | 0.624833 |
8eebfa9caf8a5e3d6fecfa5e877de0fd423374bd | 224 | cpp | C++ | core/src/task/semaphore.cpp | ExaBerries/spruce | 85845244f7d6cd5a662f0dbc9b4079a1230d9a4b | [
"MIT"
] | null | null | null | core/src/task/semaphore.cpp | ExaBerries/spruce | 85845244f7d6cd5a662f0dbc9b4079a1230d9a4b | [
"MIT"
] | null | null | null | core/src/task/semaphore.cpp | ExaBerries/spruce | 85845244f7d6cd5a662f0dbc9b4079a1230d9a4b | [
"MIT"
] | null | null | null | #include <task/semaphore.h>
namespace spruce {
void semaphore::lock() noexcept {
locked = true;
}
void semaphore::unlock() noexcept {
locked = false;
}
void semaphore::wait() noexcept {
while (locked) {};
}
}
| 14 | 36 | 0.647321 |
8ef370a2a057895eb2c6f29c4b72e2fbe7035c89 | 109 | cpp | C++ | src/add.cpp | JacknJo/JacksHome | b1b2d0d7683eb1a8adcfdd02380c6b620e567fe2 | [
"MIT"
] | null | null | null | src/add.cpp | JacknJo/JacksHome | b1b2d0d7683eb1a8adcfdd02380c6b620e567fe2 | [
"MIT"
] | null | null | null | src/add.cpp | JacknJo/JacksHome | b1b2d0d7683eb1a8adcfdd02380c6b620e567fe2 | [
"MIT"
] | null | null | null | #include "add.hpp"
namespace jhm
{
add::add() = default;
add::~add() = default;
} // namespace jhm. | 15.571429 | 26 | 0.577982 |
8ef5895790d79b560e252c6e6e7f40634ccff4a0 | 2,574 | cpp | C++ | 01-dda-chessboard/DDA_Chessboard.cpp | ChetanaHegde/vtu-mca-sem3-cg | 92667bef2b89726d6a272cd6425217257d47846d | [
"MIT"
] | 2 | 2020-10-08T10:36:40.000Z | 2021-05-11T16:23:19.000Z | 01-dda-chessboard/DDA_Chessboard.cpp | ChetanaHegde/vtu-mca-sem3-cg | 92667bef2b89726d6a272cd6425217257d47846d | [
"MIT"
] | null | null | null | 01-dda-chessboard/DDA_Chessboard.cpp | ChetanaHegde/vtu-mca-sem3-cg | 92667bef2b89726d6a272cd6425217257d47846d | [
"MIT"
] | 2 | 2017-01-25T13:43:09.000Z | 2019-03-18T12:03:40.000Z | /* Program 1: Write a program to implement Chessboard using DDA Line drawing algorithm.
Coded by: Basavaraju R, Assistant Professor, RNSIT, Bangalore
Email: basavaraju dot revanna at gmail dot com
*/
#include<gl\glut.h>
#include<math.h>
GLint start_x=50,start_y=40,end_x=start_x+80,end_y=start_y+80;
void setPixel(GLint, GLint);
void init();
void display();
void lineDDA(GLint,GLint,GLint,GLint);
void fillRow(GLint,GLint,GLint,GLint,GLfloat);
void main(int argc, char** argv)
{
glutInit(&argc, argv); //initialize GLUT
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); //initialize display mode
glutInitWindowPosition(250,100); //set display-window upper-left position
glutInitWindowSize(600,500); //set display-window width & height
glutCreateWindow("Chess Board using DDA Line Algorithm"); //create display-window with a title
init(); //initialize window prpperties
glutDisplayFunc(display); //call graphics to be displayed on the window
glutMainLoop(); //display everything and wait
}
inline int round(const float a)
{
return int(a+0.5);
}
void setPixel(GLint xCoordinate, GLint yCoordinate)
{
glBegin(GL_POINTS);
glVertex2i(xCoordinate,yCoordinate);
glEnd();
glFlush(); //executes all OpenGL functions as quickly as possible
}
void init(void)
{
glClearColor(0.0,0.5,0.5,0.0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0.0,200.0,0.0,150.0);
}
//DDA line drawing procedure
void lineDDA(GLint x0,GLint y0, GLint xe, GLint ye)
{
GLint dx=xe-x0, dy=ye-y0, steps, k;
GLfloat xinc, yinc, x=x0, y=y0;
if(abs(dx)>abs(dy))
steps=abs(dx);
else
steps=abs(dy);
xinc=float(dx)/float(steps);
yinc=float(dy)/float(steps);
setPixel(round(x),round(y));
for(k=0;k<steps;k++)
{
x+=xinc;
y+=yinc;
setPixel(round(x), round(y));
}
}
//Function fills one row of chessbord with alternate black and white color
void fillRow(GLint x1,GLint y1,GLint x2,GLint y2,GLfloat c)
{
while(x1<end_x)
{
glColor3f(c,c,c);
glRecti(x1,y1,x2,y2);
x1=x2;
x2+=10;
if(c==0.0)
c=1.0;
else
c=0.0;
}
}
void display(void)
{
GLint i=0,a,b;
a=start_x;
b=start_y;
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0,0.0,0.0);
while(i<9)
{
lineDDA(a,start_y,a,end_y);
a+=10;
lineDDA(start_x,b,end_x,b);
b+=10;
i++;
}
GLint x1=start_x,y1=end_y,x2=start_x+10,y2=end_y-10;
GLfloat cl=0.0;
while(y1>start_y)
{
fillRow(x1,y1,x2,y2,cl);
if(cl==0.0)
cl=1.0;
else
cl=0.0;
y1=y2;
y2-=10;
}
glFlush();
}
| 22.578947 | 97 | 0.661616 |
8ef60977c3acc029e6540d17f9aef44f5f3376c5 | 13,949 | cpp | C++ | source/test/mp-integer-unsigned-arithmetic-test.cpp | CaptainCrowbar/rs-sci | 40768e7665c555f28e4b0ca2b1c2d1fa2da9775a | [
"BSL-1.0"
] | null | null | null | source/test/mp-integer-unsigned-arithmetic-test.cpp | CaptainCrowbar/rs-sci | 40768e7665c555f28e4b0ca2b1c2d1fa2da9775a | [
"BSL-1.0"
] | null | null | null | source/test/mp-integer-unsigned-arithmetic-test.cpp | CaptainCrowbar/rs-sci | 40768e7665c555f28e4b0ca2b1c2d1fa2da9775a | [
"BSL-1.0"
] | null | null | null | #include "rs-sci/mp-integer.hpp"
#include "rs-format/format.hpp"
#include "rs-unit-test.hpp"
#include <string>
#include <vector>
using namespace RS::Format;
using namespace RS::Sci;
namespace {
using ByteVector = std::vector<uint8_t>;
std::string hexdump(const ByteVector& v) {
std::string s(reinterpret_cast<const char*>(v.data()), v.size());
return format_string(s, "x");
}
}
void test_rs_sci_mp_integer_unsigned_arithmetic() {
MPN x, y, z, q, r;
std::string s;
TRY(x = 0);
TEST_EQUAL(x.bits(), 0u);
TRY(s = x.str("b")); TEST_EQUAL(s, "0");
TRY(s = x.str("n")); TEST_EQUAL(s, "0");
TRY(s = x.str("x")); TEST_EQUAL(s, "0");
TRY(y = x + 15);
TEST_EQUAL(y.bits(), 4u);
TRY(s = to_string(y)); TEST_EQUAL(s, "15");
TRY(s = y.str("x")); TEST_EQUAL(s, "f");
TRY(y = 15 - x);
TEST_EQUAL(y.bits(), 4u);
TRY(s = to_string(y)); TEST_EQUAL(s, "15");
TRY(s = y.str("x")); TEST_EQUAL(s, "f");
TRY(x = 0x123456789abcdef0ull);
TRY(y = 0xffffffffffffffffull);
TEST_EQUAL(x.bits(), 61u);
TEST_EQUAL(y.bits(), 64u);
TRY(s = to_string(x)); TEST_EQUAL(s, "1311768467463790320");
TRY(s = to_string(y)); TEST_EQUAL(s, "18446744073709551615");
TRY(z = x + 15);
TEST_EQUAL(z.bits(), 61u);
TRY(s = to_string(z)); TEST_EQUAL(s, "1311768467463790335");
TRY(s = z.str("x")); TEST_EQUAL(s, "123456789abcdeff");
TRY(z = x + y);
TEST_EQUAL(z.bits(), 65u);
TRY(s = to_string(z)); TEST_EQUAL(s, "19758512541173341935");
TRY(s = z.str("x")); TEST_EQUAL(s, "1123456789abcdeef");
TRY(z = y - 15);
TEST_EQUAL(z.bits(), 64u);
TRY(s = to_string(z)); TEST_EQUAL(s, "18446744073709551600");
TRY(s = z.str("x")); TEST_EQUAL(s, "fffffffffffffff0");
TRY(z = y - x);
TEST_EQUAL(z.bits(), 64u);
TRY(s = to_string(z)); TEST_EQUAL(s, "17134975606245761295");
TRY(s = z.str("x")); TEST_EQUAL(s, "edcba9876543210f");
TRY(z = x * y);
TEST_EQUAL(z.bits(), 125u);
TRY(s = to_string(z)); TEST_EQUAL(s, "24197857203266734862169780735577366800");
TRY(s = z.str("x")); TEST_EQUAL(s, "123456789abcdeefedcba98765432110");
TRY(x = MPN("123456789123456789123456789123456789123456789"));
TRY(y = MPN("123456789123456789123456789123456789"));
TRY(z = x - y);
TEST_EQUAL(z, MPN("123456789000000000000000000000000000000000000"));
TRY(y = MPN("123456789123456789123456789123456789000000000"));
TRY(z = x - y);
TEST_EQUAL(z, MPN("123456789"));
TRY(x = MPN("123456789123456789123456789123456789123456789"));
TRY(y = MPN("1357913579135791357913579"));
TRY(z = x - y);
TEST_EQUAL(z, MPN("123456789123456789122098875544320997765543210"));
TRY(x = MPN("123456789123456789123456789123456789123456789"));
TRY(y = MPN("123456789"));
TRY(q = x / y);
TRY(r = x % y);
TEST_EQUAL(q, MPN("1000000001000000001000000001000000001"));
TEST_EQUAL(r, MPN("0"));
TRY(y = MPN("987654321"));
TRY(q = x / y);
TRY(r = x % y);
TEST_EQUAL(q, MPN("124999998985937499000175780249997801"));
TEST_EQUAL(r, MPN("725308668"));
TRY(y = MPN("987654321987654321987654321987654321987654321"));
TRY(q = x / y);
TRY(r = x % y);
TEST_EQUAL(q, MPN("0"));
TEST_EQUAL(r, MPN("123456789123456789123456789123456789123456789"));
TRY(y = {});
}
void test_rs_sci_mp_integer_unsigned_arithmetic_powers() {
MPN x, y;
std::string s;
TRY(x = 0); TRY(y = x.pow(0)); TEST_EQUAL(y.str(), "1");
TRY(x = 0); TRY(y = x.pow(1)); TEST_EQUAL(y.str(), "0");
TRY(x = 0); TRY(y = x.pow(2)); TEST_EQUAL(y.str(), "0");
TRY(x = 0); TRY(y = x.pow(3)); TEST_EQUAL(y.str(), "0");
TRY(x = 1); TRY(y = x.pow(0)); TEST_EQUAL(y.str(), "1");
TRY(x = 1); TRY(y = x.pow(1)); TEST_EQUAL(y.str(), "1");
TRY(x = 1); TRY(y = x.pow(2)); TEST_EQUAL(y.str(), "1");
TRY(x = 1); TRY(y = x.pow(3)); TEST_EQUAL(y.str(), "1");
TRY(x = 10); TRY(y = x.pow(0)); TEST_EQUAL(y.str(), "1");
TRY(x = 10); TRY(y = x.pow(1)); TEST_EQUAL(y.str(), "10");
TRY(x = 10); TRY(y = x.pow(2)); TEST_EQUAL(y.str(), "100");
TRY(x = 10); TRY(y = x.pow(3)); TEST_EQUAL(y.str(), "1000");
TRY(x = 10); TRY(y = x.pow(4)); TEST_EQUAL(y.str(), "10000");
TRY(x = 10); TRY(y = x.pow(5)); TEST_EQUAL(y.str(), "100000");
TRY(x = 10); TRY(y = x.pow(6)); TEST_EQUAL(y.str(), "1000000");
TRY(x = 10); TRY(y = x.pow(7)); TEST_EQUAL(y.str(), "10000000");
TRY(x = 10); TRY(y = x.pow(8)); TEST_EQUAL(y.str(), "100000000");
TRY(x = 10); TRY(y = x.pow(9)); TEST_EQUAL(y.str(), "1000000000");
TRY(x = 10); TRY(y = x.pow(10)); TEST_EQUAL(y.str(), "10000000000");
TRY(x = 10); TRY(y = x.pow(11)); TEST_EQUAL(y.str(), "100000000000");
TRY(x = 10); TRY(y = x.pow(12)); TEST_EQUAL(y.str(), "1000000000000");
TRY(x = 10); TRY(y = x.pow(13)); TEST_EQUAL(y.str(), "10000000000000");
TRY(x = 10); TRY(y = x.pow(14)); TEST_EQUAL(y.str(), "100000000000000");
TRY(x = 10); TRY(y = x.pow(15)); TEST_EQUAL(y.str(), "1000000000000000");
TRY(x = 10); TRY(y = x.pow(16)); TEST_EQUAL(y.str(), "10000000000000000");
TRY(x = 10); TRY(y = x.pow(17)); TEST_EQUAL(y.str(), "100000000000000000");
TRY(x = 10); TRY(y = x.pow(18)); TEST_EQUAL(y.str(), "1000000000000000000");
TRY(x = 10); TRY(y = x.pow(19)); TEST_EQUAL(y.str(), "10000000000000000000");
TRY(x = 10); TRY(y = x.pow(20)); TEST_EQUAL(y.str(), "100000000000000000000");
TRY(x = 10); TRY(y = x.pow(21)); TEST_EQUAL(y.str(), "1000000000000000000000");
TRY(x = 10); TRY(y = x.pow(22)); TEST_EQUAL(y.str(), "10000000000000000000000");
TRY(x = 10); TRY(y = x.pow(23)); TEST_EQUAL(y.str(), "100000000000000000000000");
TRY(x = 10); TRY(y = x.pow(24)); TEST_EQUAL(y.str(), "1000000000000000000000000");
TRY(x = 10); TRY(y = x.pow(25)); TEST_EQUAL(y.str(), "10000000000000000000000000");
TRY(x = 10); TRY(y = x.pow(26)); TEST_EQUAL(y.str(), "100000000000000000000000000");
TRY(x = 10); TRY(y = x.pow(27)); TEST_EQUAL(y.str(), "1000000000000000000000000000");
TRY(x = 10); TRY(y = x.pow(28)); TEST_EQUAL(y.str(), "10000000000000000000000000000");
TRY(x = 10); TRY(y = x.pow(29)); TEST_EQUAL(y.str(), "100000000000000000000000000000");
TRY(x = 10); TRY(y = x.pow(30)); TEST_EQUAL(y.str(), "1000000000000000000000000000000");
}
void test_rs_sci_mp_integer_unsigned_bit_operations() {
MPN x, y, z;
std::string s;
TEST_EQUAL(x.bits_set(), 0u);
TEST(x.is_even());
TEST(! x.is_odd());
TRY(x = 0x123456789abcdef0ull);
TRY(y = 0xffffffffffffffffull);
TEST_EQUAL(x.bits(), 61u);
TEST_EQUAL(y.bits(), 64u);
TEST_EQUAL(x.bits_set(), 32u);
TEST_EQUAL(y.bits_set(), 64u);
TEST(x.is_even());
TEST(! x.is_odd());
TEST(! y.is_even());
TEST(y.is_odd());
TRY(s = to_string(x)); TEST_EQUAL(s, "1311768467463790320");
TRY(s = to_string(y)); TEST_EQUAL(s, "18446744073709551615");
TRY(z = x & y);
TEST_EQUAL(z.bits(), 61u);
TRY(s = to_string(z)); TEST_EQUAL(s, "1311768467463790320");
TRY(s = z.str("x")); TEST_EQUAL(s, "123456789abcdef0");
TRY(z = x | y);
TEST_EQUAL(z.bits(), 64u);
TRY(s = to_string(z)); TEST_EQUAL(s, "18446744073709551615");
TRY(s = z.str("x")); TEST_EQUAL(s, "ffffffffffffffff");
TRY(z = x ^ y);
TEST_EQUAL(z.bits(), 64u);
TRY(s = to_string(z)); TEST_EQUAL(s, "17134975606245761295");
TRY(s = z.str("x")); TEST_EQUAL(s, "edcba9876543210f");
TRY(z = x >> 0); TRY(s = z.str("x")); TEST_EQUAL(s, "123456789abcdef0");
TRY(z = x >> 1); TRY(s = z.str("x")); TEST_EQUAL(s, "91a2b3c4d5e6f78");
TRY(z = x >> 2); TRY(s = z.str("x")); TEST_EQUAL(s, "48d159e26af37bc");
TRY(z = x >> 3); TRY(s = z.str("x")); TEST_EQUAL(s, "2468acf13579bde");
TRY(z = x >> 31); TRY(s = z.str("x")); TEST_EQUAL(s, "2468acf1");
TRY(z = x >> 32); TRY(s = z.str("x")); TEST_EQUAL(s, "12345678");
TRY(z = x >> 33); TRY(s = z.str("x")); TEST_EQUAL(s, "91a2b3c");
TRY(z = x >> 58); TRY(s = z.str("x")); TEST_EQUAL(s, "4");
TRY(z = x >> 59); TRY(s = z.str("x")); TEST_EQUAL(s, "2");
TRY(z = x >> 60); TRY(s = z.str("x")); TEST_EQUAL(s, "1");
TRY(z = x >> 61); TRY(s = z.str("x")); TEST_EQUAL(s, "0");
TRY(z = x >> 62); TRY(s = z.str("x")); TEST_EQUAL(s, "0");
TRY(z = x >> 63); TRY(s = z.str("x")); TEST_EQUAL(s, "0");
TRY(z = x >> 64); TRY(s = z.str("x")); TEST_EQUAL(s, "0");
TRY(z = x >> 65); TRY(s = z.str("x")); TEST_EQUAL(s, "0");
TRY(z = x << 0); TRY(s = z.str("x")); TEST_EQUAL(s, "123456789abcdef0");
TRY(z = x << 1); TRY(s = z.str("x")); TEST_EQUAL(s, "2468acf13579bde0");
TRY(z = x << 2); TRY(s = z.str("x")); TEST_EQUAL(s, "48d159e26af37bc0");
TRY(z = x << 3); TRY(s = z.str("x")); TEST_EQUAL(s, "91a2b3c4d5e6f780");
TRY(z = x << 4); TRY(s = z.str("x")); TEST_EQUAL(s, "123456789abcdef00");
TRY(z = x << 5); TRY(s = z.str("x")); TEST_EQUAL(s, "2468acf13579bde00");
TRY(z = x << 6); TRY(s = z.str("x")); TEST_EQUAL(s, "48d159e26af37bc00");
TRY(z = x << 7); TRY(s = z.str("x")); TEST_EQUAL(s, "91a2b3c4d5e6f7800");
TRY(z = x << 8); TRY(s = z.str("x")); TEST_EQUAL(s, "123456789abcdef000");
TRY(z = x << 9); TRY(s = z.str("x")); TEST_EQUAL(s, "2468acf13579bde000");
TRY(z = x << 10); TRY(s = z.str("x")); TEST_EQUAL(s, "48d159e26af37bc000");
TRY(z = x << 11); TRY(s = z.str("x")); TEST_EQUAL(s, "91a2b3c4d5e6f78000");
TRY(z = x << 12); TRY(s = z.str("x")); TEST_EQUAL(s, "123456789abcdef0000");
TRY(z = x << 13); TRY(s = z.str("x")); TEST_EQUAL(s, "2468acf13579bde0000");
TRY(z = x << 14); TRY(s = z.str("x")); TEST_EQUAL(s, "48d159e26af37bc0000");
TRY(z = x << 15); TRY(s = z.str("x")); TEST_EQUAL(s, "91a2b3c4d5e6f780000");
TRY(z = x << 16); TRY(s = z.str("x")); TEST_EQUAL(s, "123456789abcdef00000");
TRY(z = x << 17); TRY(s = z.str("x")); TEST_EQUAL(s, "2468acf13579bde00000");
TRY(z = x << 18); TRY(s = z.str("x")); TEST_EQUAL(s, "48d159e26af37bc00000");
TRY(z = x << 19); TRY(s = z.str("x")); TEST_EQUAL(s, "91a2b3c4d5e6f7800000");
TRY(z = x << 20); TRY(s = z.str("x")); TEST_EQUAL(s, "123456789abcdef000000");
TRY(x = {});
TEST(! x.get_bit(0));
TEST(! x.get_bit(100));
TRY(x.set_bit(16));
TEST_EQUAL(x, MPN("0x10000"));
TEST(! x.get_bit(15));
TEST(x.get_bit(16));
TEST(! x.get_bit(17));
TRY(x.set_bit(80));
TEST_EQUAL(x, MPN("0x100000000000000010000"));
TEST(! x.get_bit(79));
TEST(x.get_bit(80));
TEST(! x.get_bit(81));
TRY(x.set_bit(80, false));
TEST_EQUAL(x, MPN("0x10000"));
TEST(! x.get_bit(80));
TRY(x.flip_bit(80));
TEST_EQUAL(x, MPN("0x100000000000000010000"));
TEST(x.get_bit(80));
TRY(x.flip_bit(80));
TEST_EQUAL(x, MPN("0x10000"));
TEST(! x.get_bit(80));
}
void test_rs_sci_mp_integer_unsigned_byte_operations() {
MPN a, b;
ByteVector v;
TEST_EQUAL(a.bytes(), 0u);
TRY(a = MPN("0x12")); TEST_EQUAL(a.bytes(), 1u);
TRY(a = MPN("0x1234")); TEST_EQUAL(a.bytes(), 2u);
TRY(a = MPN("0x123456")); TEST_EQUAL(a.bytes(), 3u);
TRY(a = MPN("0x12345678")); TEST_EQUAL(a.bytes(), 4u);
TRY(a = MPN("0x123456789a")); TEST_EQUAL(a.bytes(), 5u);
TRY(a = MPN("0x123456789abc")); TEST_EQUAL(a.bytes(), 6u);
TRY(a = MPN("0x123456789abcde")); TEST_EQUAL(a.bytes(), 7u);
TRY(a = MPN("0x123456789abcdef1")); TEST_EQUAL(a.bytes(), 8u);
TRY(a = MPN("0x123456789abcdef123")); TEST_EQUAL(a.bytes(), 9u);
TRY(a = MPN("0x123456789abcdef12345")); TEST_EQUAL(a.bytes(), 10u);
TEST_EQUAL(a.get_byte(0), 0x45);
TEST_EQUAL(a.get_byte(1), 0x23);
TEST_EQUAL(a.get_byte(2), 0xf1);
TEST_EQUAL(a.get_byte(3), 0xde);
TEST_EQUAL(a.get_byte(4), 0xbc);
TEST_EQUAL(a.get_byte(5), 0x9a);
TEST_EQUAL(a.get_byte(6), 0x78);
TEST_EQUAL(a.get_byte(7), 0x56);
TEST_EQUAL(a.get_byte(8), 0x34);
TEST_EQUAL(a.get_byte(9), 0x12);
TEST_EQUAL(a.get_byte(10), 0u);
TEST_EQUAL(a.get_byte(11), 0u);
TEST_EQUAL(a.get_byte(12), 0u);
TEST_EQUAL(a.get_byte(13), 0u);
TEST_EQUAL(a.get_byte(14), 0u);
TEST_EQUAL(a.get_byte(15), 0u);
TEST_EQUAL(a.get_byte(16), 0u);
TRY(a.set_byte(1, 0xff)); TEST_EQUAL(a.str("x"), "123456789abcdef1ff45");
TRY(a.set_byte(3, 0xff)); TEST_EQUAL(a.str("x"), "123456789abcfff1ff45");
TRY(a.set_byte(5, 0xff)); TEST_EQUAL(a.str("x"), "12345678ffbcfff1ff45");
TRY(a.set_byte(7, 0xff)); TEST_EQUAL(a.str("x"), "1234ff78ffbcfff1ff45");
TRY(a.set_byte(9, 0xff)); TEST_EQUAL(a.str("x"), "ff34ff78ffbcfff1ff45");
TRY(a.set_byte(11, 0xff)); TEST_EQUAL(a.str("x"), "ff00ff34ff78ffbcfff1ff45");
TRY(a.set_byte(13, 0xff)); TEST_EQUAL(a.str("x"), "ff00ff00ff34ff78ffbcfff1ff45");
TRY(a.set_byte(15, 0xff)); TEST_EQUAL(a.str("x"), "ff00ff00ff00ff34ff78ffbcfff1ff45");
TRY(a = 0);
TRY(b = MPN("0x123456789abcdef12345"));
v.resize(7);
TRY(a.write_be(v.data(), v.size())); TEST_EQUAL(hexdump(v), "00 00 00 00 00 00 00");
TRY(b.write_be(v.data(), v.size())); TEST_EQUAL(hexdump(v), "78 9a bc de f1 23 45");
TRY(a.write_le(v.data(), v.size())); TEST_EQUAL(hexdump(v), "00 00 00 00 00 00 00");
TRY(b.write_le(v.data(), v.size())); TEST_EQUAL(hexdump(v), "45 23 f1 de bc 9a 78");
v = {0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xaa,0xbb,0xcc,0xdd,0xee,0xff};
TRY(a = MPN::read_be(v.data(), v.size())); TEST_EQUAL(a.str("x"), "112233445566778899aabbccddeeff");
TRY(a = MPN::read_le(v.data(), v.size())); TEST_EQUAL(a.str("x"), "ffeeddccbbaa998877665544332211");
}
| 43.590625 | 105 | 0.577246 |
8ef7b6a4a6cc310bccf1b00824337df2b9ff2966 | 411 | hpp | C++ | libs/parse/include/fcppt/parse/tag.hpp | freundlich/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 13 | 2015-02-21T18:35:14.000Z | 2019-12-29T14:08:29.000Z | libs/parse/include/fcppt/parse/tag.hpp | cpreh/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 5 | 2016-08-27T07:35:47.000Z | 2019-04-21T10:55:34.000Z | libs/parse/include/fcppt/parse/tag.hpp | freundlich/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 8 | 2015-01-10T09:22:37.000Z | 2019-12-01T08:31:12.000Z | // Copyright Carl Philipp Reh 2009 - 2021.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef FCPPT_PARSE_TAG_HPP_INCLUDED
#define FCPPT_PARSE_TAG_HPP_INCLUDED
namespace fcppt::parse
{
/**
\brief The tag parsers derive from.
\ingroup fcpptparse
*/
struct tag
{
};
}
#endif
| 18.681818 | 61 | 0.717762 |
8ef8d27920731249682d2403bb0520863b51bbcd | 2,849 | hpp | C++ | lib/libcpp/Perulangan/Perulangan/iterativesolvervisitorinterface.hpp | beckerrh/simfemsrc | d857eb6f6f8627412d4f9d89a871834c756537db | [
"MIT"
] | null | null | null | lib/libcpp/Perulangan/Perulangan/iterativesolvervisitorinterface.hpp | beckerrh/simfemsrc | d857eb6f6f8627412d4f9d89a871834c756537db | [
"MIT"
] | 1 | 2019-01-31T10:59:11.000Z | 2019-01-31T10:59:11.000Z | lib/libcpp/Perulangan/Perulangan/iterativesolvervisitorinterface.hpp | beckerrh/simfemsrc | d857eb6f6f8627412d4f9d89a871834c756537db | [
"MIT"
] | null | null | null | #ifndef __Perulangan_IterativeSolverVisitorInterface_h
#define __Perulangan_IterativeSolverVisitorInterface_h
#include "Alat/interfacebase.hpp"
#include "Alat/armadillo.hpp"
/*--------------------------------------------------------------------------*/
namespace alat
{
class GhostLinearSolver;
class GhostMatrix;
class GhostVector;
class StringVector;
}
namespace perulangan
{
class IterativeSolverVisitorInterface : public alat::InterfaceBase
{
protected:
std::string getInterfaceName() const;
public:
~IterativeSolverVisitorInterface();
IterativeSolverVisitorInterface();
IterativeSolverVisitorInterface( const IterativeSolverVisitorInterface& iterativesolvervisitorinterface);
IterativeSolverVisitorInterface& operator=( const IterativeSolverVisitorInterface& iterativesolvervisitorinterface);
std::string getClassName() const;
perulangan::IterativeSolverVisitorInterface* clone() const;
// virtual void basicInit(const alat::ParameterFile* parameterfile, std::string blockname);
virtual std::ostream& printLoopInformation(std::ostream& os) const;
virtual std::string getVectorType() const;
// virtual int getVectorLevel() const=0;
virtual void newVector(alat::GhostVector* u) = 0;
virtual void vectorEqual(alat::GhostVector& r, const alat::GhostVector& f) const;
virtual void vectorZero(alat::GhostVector& v) const;
virtual void vectorAdd(alat::GhostVector& p, double d, const alat::GhostVector& q) const;
virtual void vectorScale(alat::GhostVector& r, double d) const;
virtual double vectorDot(const alat::GhostVector& gu, const alat::GhostVector& gv) const;
virtual double vectorNorm(const alat::GhostVector& r) const;
virtual void residual(const alat::GhostMatrix& A, alat::GhostVector& r, const alat::GhostVector& u, const alat::GhostVector& f) const;
virtual void matrixVectorProduct(const alat::GhostMatrix& A, alat::GhostVector& r, const alat::GhostVector& u, double d) const;
virtual void postProcess(alat::GhostVector& u) const;
// virtual const alat::armaivec& getDomainsPermutation(int iteration) const;
// virtual void solveOnDomain(int idomain, const alat::GhostLinearSolver& linearsolverdomain, const alat::GhostMatrix& ghostmatrix, alat::GhostVector& u, const alat::GhostVector& f) const;
// virtual void vectorEqualOnDomain(int idomain, alat::GhostVector& u, const alat::GhostVector& f) const;
// virtual void matrixVectorProductCoupling(int i, const alat::GhostMatrix& ghostmatrix, alat::GhostVector& u, const alat::GhostVector& f, double d) const;
// virtual void smoothInterface(int idomain, alat::GhostVector& u) const;
// virtual void smoothInterfaceOnLevel(int level, alat::GhostVector& u) const;
};
}
/*--------------------------------------------------------------------------*/
#endif
| 47.483333 | 192 | 0.724465 |
8efc12a8115c48f8f4862cafa92222aa80df25a8 | 896 | cpp | C++ | lib/PointerAnalysis/MemoryModel/PointerLayout.cpp | grievejia/tpa | 8a7aa4c7d41c266fcf3a5e2011ff324bcddf5816 | [
"MIT"
] | 16 | 2016-08-03T12:09:19.000Z | 2022-02-20T08:22:12.000Z | lib/PointerAnalysis/MemoryModel/PointerLayout.cpp | grievejia/tpa | 8a7aa4c7d41c266fcf3a5e2011ff324bcddf5816 | [
"MIT"
] | 1 | 2016-12-14T08:42:19.000Z | 2016-12-21T08:21:20.000Z | lib/PointerAnalysis/MemoryModel/PointerLayout.cpp | grievejia/tpa | 8a7aa4c7d41c266fcf3a5e2011ff324bcddf5816 | [
"MIT"
] | 6 | 2016-08-19T14:17:06.000Z | 2019-08-05T08:34:47.000Z | #include "PointerAnalysis/MemoryModel/Type/PointerLayout.h"
namespace tpa
{
const PointerLayout* PointerLayout::getEmptyLayout()
{
return emptyLayout;
}
const PointerLayout* PointerLayout::getSinglePointerLayout()
{
return singlePointerLayout;
}
const PointerLayout* PointerLayout::getLayout(SetType&& set)
{
auto itr = layoutSet.insert(PointerLayout(std::move(set))).first;
return &(*itr);
}
const PointerLayout* PointerLayout::getLayout(std::initializer_list<size_t> ilist)
{
SetType set(ilist);
return getLayout(std::move(set));
}
const PointerLayout* PointerLayout::merge(const PointerLayout* lhs, const PointerLayout* rhs)
{
assert(lhs != nullptr && rhs != nullptr);
if (lhs == rhs)
return lhs;
if (lhs->empty())
return rhs;
if (rhs->empty())
return lhs;
SetType newSet(lhs->validOffsets);
newSet.merge(rhs->validOffsets);
return getLayout(std::move(newSet));
}
} | 20.363636 | 93 | 0.739955 |
8eff0a67d91b7eb211ff45a1703d34d455e17e9e | 3,951 | cpp | C++ | duds/data/Unit.cpp | jjackowski/duds | 0fc4eec0face95c13575672f2a2d8625517c9469 | [
"BSD-2-Clause"
] | null | null | null | duds/data/Unit.cpp | jjackowski/duds | 0fc4eec0face95c13575672f2a2d8625517c9469 | [
"BSD-2-Clause"
] | null | null | null | duds/data/Unit.cpp | jjackowski/duds | 0fc4eec0face95c13575672f2a2d8625517c9469 | [
"BSD-2-Clause"
] | null | null | null | /*
* This file is part of the DUDS project. It is subject to the BSD-style
* license terms in the LICENSE file found in the top-level directory of this
* distribution and at https://github.com/jjackowski/duds/blob/master/LICENSE.
* No part of DUDS, including this file, may be copied, modified, propagated,
* or distributed except according to the terms contained in the LICENSE file.
*
* Copyright (C) 2017 Jeff Jackowski
*/
#include <duds/data/Unit.hpp>
#include <duds/general/Errors.hpp>
namespace duds { namespace data {
void Unit::setAmpere(int e) {
int v = general::SignExtend<4>(e);
if (v != e) {
DUDS_THROW_EXCEPTION(UnitRangeError() << BadUnitExponent(e) <<
BadUnit("Ampere"));
}
u = (u & 0xFFFFFFF0) | v;
}
void Unit::setCandela(int e) {
int v = general::SignExtend<4>(e);
if (v != e) {
DUDS_THROW_EXCEPTION(UnitRangeError() << BadUnitExponent(e) <<
BadUnit("Candela"));
}
u = (u & 0xFFFFFF0F) | (v << 4);
}
void Unit::setKelvin(int e) {
int v = general::SignExtend<4>(e);
if (v != e) {
DUDS_THROW_EXCEPTION(UnitRangeError() << BadUnitExponent(e) <<
BadUnit("Kelvin"));
}
u = (u & 0xFFFFF0FF) | (v << 8);
}
void Unit::setKilogram(int e) {
int v = general::SignExtend<4>(e);
if (v != e) {
DUDS_THROW_EXCEPTION(UnitRangeError() << BadUnitExponent(e) <<
BadUnit("Kilogram"));
}
u = (u & 0xFFFF0FFF) | (v << 12);
}
void Unit::setMeter(int e) {
int v = general::SignExtend<4>(e);
if (v != e) {
DUDS_THROW_EXCEPTION(UnitRangeError() << BadUnitExponent(e) <<
BadUnit("Meter"));
}
u = (u & 0xFFF0FFFF) | (v << 16);
}
void Unit::setMole(int e) {
int v = general::SignExtend<4>(e);
if (v != e) {
DUDS_THROW_EXCEPTION(UnitRangeError() << BadUnitExponent(e) <<
BadUnit("Mole"));
}
u = (u & 0xFF0FFFFF) | (v << 20);
}
void Unit::setSecond(int e) {
int v = general::SignExtend<4>(e);
if (v != e) {
DUDS_THROW_EXCEPTION(UnitRangeError() << BadUnitExponent(e) <<
BadUnit("Second"));
}
u = (u & 0xF0FFFFFF) | (v << 24);
}
void Unit::setRadian(int e) {
int v = general::SignExtend<2>(e);
if (v != e) {
DUDS_THROW_EXCEPTION(UnitRangeError() << BadUnitExponent(e) <<
BadUnit("Radian"));
}
u = (u & 0xCFFFFFFF) | (v << 28);
}
void Unit::setSteradian(int e) {
int v = general::SignExtend<2>(e);
if (v != e) {
DUDS_THROW_EXCEPTION(UnitRangeError() << BadUnitExponent(e) <<
BadUnit("Steradian"));
}
u = (u & 0x3FFFFFFF) | (v << 30);
}
Unit::Unit(int A, int cd, int K, int kg, int m, int mol, int s,
int rad, int sr) {
setAmpere(A);
setCandela(cd);
setKelvin(K);
setKilogram(kg);
setMeter(m);
setMole(mol);
setSecond(s);
setRadian(rad);
setSteradian(sr);
}
const Unit Unit::operator * (const Unit &U) const {
// the result
Unit r;
// set the result; may fail with exception
r.setAmpere(ampere() + U.ampere());
r.setCandela(candela() + U.candela());
r.setKelvin(kelvin() + U.kelvin());
r.setKilogram(kilogram() + U.kilogram());
r.setMeter(meter() + U.meter());
r.setMole(mole() + U.mole());
r.setSecond(second() + U.second());
r.setRadian(radian() + U.radian());
r.setSteradian(steradian() + U.steradian());
// return the result
return r;
}
const Unit Unit::operator / (const Unit &U) const {
// the result
Unit r;
// set the result; may fail with exception
r.setAmpere(ampere() - U.ampere());
r.setCandela(candela() - U.candela());
r.setKelvin(kelvin() - U.kelvin());
r.setKilogram(kilogram() - U.kilogram());
r.setMeter(meter() - U.meter());
r.setMole(mole() - U.mole());
r.setSecond(second() - U.second());
r.setRadian(radian() - U.radian());
r.setSteradian(steradian() - U.steradian());
// return the result
return r;
}
Unit &Unit::operator *= (const Unit &U) {
// a temporary
Unit n(*this * U); // may throw
// keep the new value
u = n.value();
return *this;
}
Unit &Unit::operator /= (const Unit &U) {
// a temporary
Unit n(*this / U); // may throw
// keep the new value
u = n.value();
return *this;
}
} }
| 24.69375 | 78 | 0.632498 |
f102ceb88409595e3e0ee48f71065afc42677212 | 829 | hpp | C++ | PrEngineSwitch/Game_Engine/include/SpriteLayer.hpp | aprithul/Prengine | 7aff20bb73ab21e9e11dda1985e6b22992479f0d | [
"BSD-3-Clause"
] | 1 | 2019-10-08T05:20:30.000Z | 2019-10-08T05:20:30.000Z | PrEngineSwitch/Game_Engine/include/SpriteLayer.hpp | aprithul/PrEngine | 7aff20bb73ab21e9e11dda1985e6b22992479f0d | [
"BSD-3-Clause"
] | null | null | null | PrEngineSwitch/Game_Engine/include/SpriteLayer.hpp | aprithul/PrEngine | 7aff20bb73ab21e9e11dda1985e6b22992479f0d | [
"BSD-3-Clause"
] | null | null | null | #ifndef SPRITE_LAYER_HPP
#define SPRITE_LAYER_HPP
#include "GlAssert.hpp"
#include "RenderLayer.hpp"
#include "Graphics.hpp"
#include "EntityManagementSystemModule.hpp"
#include "DirectionalLight.hpp"
#include "Camera3D.hpp"
#include "Matrix4x4f.hpp"
#include <vector>
#include "Sprite.hpp"
#include "Transform3D.hpp"
namespace PrEngine
{
void insertion_sort(std::vector<Sprite*>& arr, Int_32 n);
//extern RendererOpenGL2D* renderer;
class SpriteLayer : public RenderLayer
{
public:
SpriteLayer();
~SpriteLayer() override;
void start() override;
void update() override;
void end() override;
std::vector<Sprite*> sprite_list;
private:
void UpdateTransforms(Transform3D* transform);
};
} // namespace Pringin
#endif
| 21.815789 | 61 | 0.670688 |
f102e7e7ec1cf25062fb7fa4946df2b2ed4b3e87 | 232 | hh | C++ | build/ARM/debug/VIO9PData.hh | msharmavikram/gem5_experiments | 87353d28df55b9a6a5be6cbb19bce87a500ab3b4 | [
"BSD-3-Clause"
] | 5 | 2019-12-12T16:26:09.000Z | 2022-03-17T03:23:33.000Z | build/X86/debug/VIO9PData.hh | zhoushuxin/impl_of_HPCA2018 | 594d807fb0c0712bb7766122c4efe3321d012687 | [
"BSD-3-Clause"
] | 1 | 2020-08-20T05:53:30.000Z | 2020-08-20T05:53:30.000Z | build/X86/debug/VIO9PData.hh | zhoushuxin/impl_of_HPCA2018 | 594d807fb0c0712bb7766122c4efe3321d012687 | [
"BSD-3-Clause"
] | null | null | null | /*
* DO NOT EDIT THIS FILE! Automatically generated by SCons.
*/
#ifndef __DEBUG_VIO9PData_HH__
#define __DEBUG_VIO9PData_HH__
namespace Debug {
class SimpleFlag;
extern SimpleFlag VIO9PData;
}
#endif // __DEBUG_VIO9PData_HH__
| 16.571429 | 59 | 0.788793 |
f10648e5e4555887d3f3edb4cf771ecf7b04e628 | 13,938 | inl | C++ | source/bsys/geometry/geometry_vertex_3.inl | bluebackblue/brownie | 917fcc71e5b0a807c0a8dab22a9ca7f3b0d60917 | [
"MIT"
] | null | null | null | source/bsys/geometry/geometry_vertex_3.inl | bluebackblue/brownie | 917fcc71e5b0a807c0a8dab22a9ca7f3b0d60917 | [
"MIT"
] | null | null | null | source/bsys/geometry/geometry_vertex_3.inl | bluebackblue/brownie | 917fcc71e5b0a807c0a8dab22a9ca7f3b0d60917 | [
"MIT"
] | null | null | null | #pragma once
/**
* Copyright (c) blueback
* Released under the MIT License
* https://github.com/bluebackblue/brownie/blob/master/LICENSE.txt
* http://bbbproject.sakura.ne.jp/wordpress/mitlicense
* @brief ジオメトリ。
*/
/** include
*/
#pragma warning(push)
#pragma warning(disable:4464)
#include "../types/types.h"
#pragma warning(pop)
/** include
*/
#include "./geometry_vector.h"
/** NBsys::NGeometry
*/
#if(BSYS_GEOMETRY_ENABLE)
#pragma warning(push)
#pragma warning(disable:4514 4710)
namespace NBsys{namespace NGeometry
{
/** x
*/
inline const f32& Geometry_Vector3::x() const
{
return this->raw.v.xx;
}
/** x
*/
inline f32& Geometry_Vector3::x()
{
return this->raw.v.xx;
}
/** y
*/
inline const f32& Geometry_Vector3::y() const
{
return this->raw.v.yy;
}
/** y
*/
inline f32& Geometry_Vector3::y()
{
return this->raw.v.yy;
}
/** z
*/
inline const f32& Geometry_Vector3::z() const
{
return this->raw.v.zz;
}
/** z
*/
inline f32& Geometry_Vector3::z()
{
return this->raw.v.zz;
}
/** constructor
*/
inline Geometry_Vector3::Geometry_Vector3() noexcept
{
}
/** constructor
*/
inline Geometry_Vector3::Geometry_Vector3(f32 a_xx,f32 a_yy,f32 a_zz) noexcept
{
this->raw.v.xx = a_xx;
this->raw.v.yy = a_yy;
this->raw.v.zz = a_zz;
}
/** constructor
*/
inline Geometry_Vector3::Geometry_Vector3(f32 a_value) noexcept
{
this->raw.v.xx = a_value;
this->raw.v.yy = a_value;
this->raw.v.zz = a_value;
}
/** constructor
*/
inline Geometry_Vector3::Geometry_Vector3(const f32* a_value_pointer) noexcept
{
this->raw.v.xx = a_value_pointer[0];
this->raw.v.yy = a_value_pointer[1];
this->raw.v.zz = a_value_pointer[2];
}
/** copy constructor
*/
inline Geometry_Vector3::Geometry_Vector3(const Geometry_Vector3& a_vector) noexcept
{
this->raw.v.xx = a_vector.raw.v.xx;
this->raw.v.yy = a_vector.raw.v.yy;
this->raw.v.zz = a_vector.raw.v.zz;
}
/** constructor
*/
inline Geometry_Vector3::Geometry_Vector3(const Geometry_Identity_Type& /*a_identity*/) noexcept
{
this->Set_Zero();
}
/** destructor
*/
inline Geometry_Vector3::~Geometry_Vector3()
{
}
/** t_1 = t_2;
*/
inline Geometry_Vector3& Geometry_Vector3::operator =(const Geometry_Vector3& a_right)
{
this->raw.v.xx = a_right.raw.v.xx;
this->raw.v.yy = a_right.raw.v.yy;
this->raw.v.zz = a_right.raw.v.zz;
return *this;
}
/** t_1 = +t_2;
*/
inline Geometry_Vector3 Geometry_Vector3::operator +() const
{
return *this;
}
/** t_1 = -t_2;
*/
inline Geometry_Vector3 Geometry_Vector3::operator -() const
{
return Geometry_Vector3(-this->raw.v.xx,-this->raw.v.yy,-this->raw.v.zz);
}
/** t_1 += t_2;
*/
inline Geometry_Vector3& Geometry_Vector3::operator +=(const Geometry_Vector3& a_right)
{
this->raw.v.xx += a_right.raw.v.xx;
this->raw.v.yy += a_right.raw.v.yy;
this->raw.v.zz += a_right.raw.v.zz;
return *this;
}
/** t_1 -= t_2;
*/
inline Geometry_Vector3& Geometry_Vector3::operator -=(const Geometry_Vector3& a_right)
{
this->raw.v.xx -= a_right.raw.v.xx;
this->raw.v.yy -= a_right.raw.v.yy;
this->raw.v.zz -= a_right.raw.v.zz;
return *this;
}
/** t_1 *= t_2;
*/
inline Geometry_Vector3& Geometry_Vector3::operator *=(const Geometry_Vector3& a_right)
{
this->raw.v.xx *= a_right.raw.v.xx;
this->raw.v.yy *= a_right.raw.v.yy;
this->raw.v.zz *= a_right.raw.v.zz;
return *this;
}
/** t_1 /= t_2;
*/
inline Geometry_Vector3& Geometry_Vector3::operator /=(const Geometry_Vector3& a_right)
{
this->raw.v.xx /= a_right.raw.v.xx;
this->raw.v.yy /= a_right.raw.v.yy;
this->raw.v.zz /= a_right.raw.v.zz;
return *this;
}
/** t_1 = 2;
*/
inline Geometry_Vector3& Geometry_Vector3::operator =(f32 a_right_value)
{
this->raw.v.xx = a_right_value;
this->raw.v.yy = a_right_value;
this->raw.v.zz = a_right_value;
return *this;
}
/** t_1 += 2;
*/
inline Geometry_Vector3& Geometry_Vector3::operator +=(f32 a_right_value)
{
this->raw.v.xx += a_right_value;
this->raw.v.yy += a_right_value;
this->raw.v.zz += a_right_value;
return *this;
}
/** t_1 -= 2;
*/
inline Geometry_Vector3& Geometry_Vector3::operator -=(f32 a_right_value)
{
this->raw.v.xx -= a_right_value;
this->raw.v.yy -= a_right_value;
this->raw.v.zz -= a_right_value;
return *this;
}
/** t_1 *= 2;
*/
inline Geometry_Vector3& Geometry_Vector3::operator *=(f32 a_right_value)
{
this->raw.v.xx *= a_right_value;
this->raw.v.yy *= a_right_value;
this->raw.v.zz *= a_right_value;
return *this;
}
/** t_1 /= 2;
*/
inline Geometry_Vector3& Geometry_Vector3::operator /=(f32 a_right_value)
{
this->raw.v.xx /= a_right_value;
this->raw.v.yy /= a_right_value;
this->raw.v.zz /= a_right_value;
return *this;
}
/** [static]Zero。
*/
inline const Geometry_Vector3& Geometry_Vector3::Zero()
{
static const NGeometry::Geometry_Vector3 s_zero(0.0f,0.0f,0.0f);
return s_zero;
}
/** [static]One。
*/
inline const Geometry_Vector3& Geometry_Vector3::One()
{
static const NGeometry::Geometry_Vector3 s_one(1.0f,1.0f,1.0f);
return s_one;
}
/** [設定]。
*/
inline Geometry_Vector3& Geometry_Vector3::Set(f32 a_xx,f32 a_yy,f32 a_zz)
{
this->raw.v.xx = a_xx;
this->raw.v.yy = a_yy;
this->raw.v.zz = a_zz;
return *this;
}
/** [設定]。
*/
inline Geometry_Vector3& Geometry_Vector3::Set_X(f32 a_xx)
{
this->raw.v.xx = a_xx;
return *this;
}
/** [設定]。
*/
inline Geometry_Vector3& Geometry_Vector3::Set_Y(f32 a_yy)
{
this->raw.v.yy = a_yy;
return *this;
}
/** [設定]。
*/
inline Geometry_Vector3& Geometry_Vector3::Set_Z(f32 a_zz)
{
this->raw.v.zz = a_zz;
return *this;
}
/** [設定]。
*/
inline Geometry_Vector3& Geometry_Vector3::Set(const Geometry_Vector3& a_vector)
{
this->raw.v.xx = a_vector.raw.v.xx;
this->raw.v.yy = a_vector.raw.v.yy;
this->raw.v.zz = a_vector.raw.v.zz;
return *this;
}
/** [設定]Set_Zero。
*/
inline Geometry_Vector3& Geometry_Vector3::Set_Zero()
{
*this = Geometry_Vector3::Zero();
return *this;
}
/** [取得]。
*/
inline f32 Geometry_Vector3::Get_X()
{
return this->raw.v.xx;
}
/** [取得]。
*/
inline f32 Geometry_Vector3::Get_Y()
{
return this->raw.v.yy;
}
/** [取得]。
*/
inline f32 Geometry_Vector3::Get_Z()
{
return this->raw.v.zz;
}
/** [作成]外積。
*/
inline Geometry_Vector3 Geometry_Vector3::Make_Cross(const Geometry_Vector3& a_vector) const
{
Geometry_Vector3 t_temp;
{
t_temp.raw.v.xx = (this->raw.v.yy * a_vector.raw.v.zz) - (this->raw.v.zz * a_vector.raw.v.yy);
t_temp.raw.v.yy = (this->raw.v.zz * a_vector.raw.v.xx) - (this->raw.v.xx * a_vector.raw.v.zz);
t_temp.raw.v.zz = (this->raw.v.xx * a_vector.raw.v.yy) - (this->raw.v.yy * a_vector.raw.v.xx);
}
return t_temp;
}
/** [設定]外積。
*/
inline Geometry_Vector3& Geometry_Vector3::Set_Cross(const Geometry_Vector3& a_vector)
{
f32 t_temp_x = (this->raw.v.yy * a_vector.raw.v.zz) - (this->raw.v.zz * a_vector.raw.v.yy);
f32 t_temp_y = (this->raw.v.zz * a_vector.raw.v.xx) - (this->raw.v.xx * a_vector.raw.v.zz);
f32 t_temp_z = (this->raw.v.xx * a_vector.raw.v.yy) - (this->raw.v.yy * a_vector.raw.v.xx);
this->raw.v.xx = t_temp_x;
this->raw.v.yy = t_temp_y;
this->raw.v.zz = t_temp_z;
return *this;
}
/** [設定]外積。
*/
inline Geometry_Vector3& Geometry_Vector3::Set_Cross(const Geometry_Vector3& a_vector_1,const Geometry_Vector3& a_vector_2)
{
f32 t_temp_x = (a_vector_1.raw.v.yy * a_vector_2.raw.v.zz) - (a_vector_1.raw.v.zz * a_vector_2.raw.v.yy);
f32 t_temp_y = (a_vector_1.raw.v.zz * a_vector_2.raw.v.xx) - (a_vector_1.raw.v.xx * a_vector_2.raw.v.zz);
f32 t_temp_z = (a_vector_1.raw.v.xx * a_vector_2.raw.v.yy) - (a_vector_1.raw.v.yy * a_vector_2.raw.v.xx);
this->raw.v.xx = t_temp_x;
this->raw.v.yy = t_temp_y;
this->raw.v.zz = t_temp_z;
return *this;
}
/** [設定]正規化。
*/
inline Geometry_Vector3& Geometry_Vector3::Set_Normalize()
{
f32 t_value = this->SquareLength();
ASSERT(t_value != 0.0f);
t_value = NMath::sqrt_f(t_value);
ASSERT(t_value != 0.0f);
t_value = 1.0f / t_value;
this->raw.v.xx *= t_value;
this->raw.v.yy *= t_value;
this->raw.v.zz *= t_value;
return *this;
}
/** [設定]正規化。
*/
inline Geometry_Vector3& Geometry_Vector3::Set_Normalize_Safe(const Geometry_Vector3& a_vector_safe)
{
f32 t_value = this->SquareLength();
if(t_value == 0.0f){
*this = a_vector_safe;
return *this;
}
t_value = NMath::sqrt_f(t_value);
if(t_value == 0.0f){
*this = a_vector_safe;
return *this;
}
t_value = 1.0f / t_value;
this->raw.v.xx *= t_value;
this->raw.v.yy *= t_value;
this->raw.v.zz *= t_value;
return *this;
}
/** [設定]正規化。
*/
inline f32 Geometry_Vector3::Set_Normalize_GetLength()
{
f32 t_value = this->SquareLength();
if(t_value == 0.0f){
return 0.0f;
}
t_value = NMath::sqrt_f(t_value);
if(t_value == 0.0f){
return 0.0f;
}
f32 t_length = t_value;
t_value = 1.0f / t_value;
this->raw.v.xx *= t_value;
this->raw.v.yy *= t_value;
this->raw.v.zz *= t_value;
return t_length;
}
/** [作成]正規化。
*/
inline Geometry_Vector3 Geometry_Vector3::Make_Normalize() const
{
Geometry_Vector3 t_temp;
{
f32 t_value = this->SquareLength();
ASSERT(t_value != 0.0f);
t_value = NMath::sqrt_f(t_value);
ASSERT(t_value != 0.0f);
t_value = 1.0f / t_value;
t_temp.raw.v.xx = this->raw.v.xx * t_value;
t_temp.raw.v.yy = this->raw.v.yy * t_value;
t_temp.raw.v.zz = this->raw.v.zz * t_value;
}
return t_temp;
}
/** [作成]正規化。
*/
inline Geometry_Vector3 Geometry_Vector3::Make_Normalize_Safe(const Geometry_Vector3& a_vector_safe) const
{
Geometry_Vector3 t_temp;
{
f32 t_value = this->SquareLength();
if(t_value == 0.0f){
return a_vector_safe;
}
t_value = NMath::sqrt_f(t_value);
if(t_value == 0.0f){
return a_vector_safe;
}
t_value = 1.0f / t_value;
t_temp.raw.v.xx = this->raw.v.xx * t_value;
t_temp.raw.v.yy = this->raw.v.yy * t_value;
t_temp.raw.v.zz = this->raw.v.zz * t_value;
}
return t_temp;
}
/** [内積]length(this)*length(a_vector)*cos(θ)。
*/
inline f32 Geometry_Vector3::Dot(const Geometry_Vector3& a_vector) const
{
f32 t_value = (this->raw.v.xx * a_vector.raw.v.xx) + (this->raw.v.yy * a_vector.raw.v.yy) + (this->raw.v.zz * a_vector.raw.v.zz);
return t_value;
}
/** [チェック]。
*/
inline bool Geometry_Vector3::IsZero() const
{
return (this->raw.v.xx == 0.0f)&&(this->raw.v.yy == 0.0f)&&(this->raw.v.zz == 0.0f);
}
/** [作成]長さ。
*/
inline f32 Geometry_Vector3::Length() const
{
f32 t_value = this->SquareLength();
t_value = NMath::sqrt_f(t_value);
return t_value;
}
/** [作成]長さの2乗。
*/
inline f32 Geometry_Vector3::SquareLength() const
{
return (this->raw.v.xx * this->raw.v.xx) + (this->raw.v.yy * this->raw.v.yy) + (this->raw.v.zz * this->raw.v.zz);
}
/** [作成]2点間の距離の2乗。
*/
inline f32 Geometry_Vector3::SquareDistance(const Geometry_Vector3& a_vector) const
{
f32 t_temp_x = (this->raw.v.xx - a_vector.raw.v.xx);
f32 t_temp_y = (this->raw.v.yy - a_vector.raw.v.yy);
f32 t_temp_z = (this->raw.v.zz - a_vector.raw.v.zz);
f32 t_value = (t_temp_x * t_temp_x) + (t_temp_y * t_temp_y) + (t_temp_z * t_temp_z);
return t_value;
}
/** [作成]Make_Lerp。
a_per = 0.0f : return = this
a_per = 1.0f : return = a_vector
*/
inline Geometry_Vector3 Geometry_Vector3::Make_Lerp(const Geometry_Vector3& a_vector,f32 a_per) const
{
Geometry_Vector3 t_temp;
{
t_temp.raw.v.xx = this->raw.v.xx + (a_vector.raw.v.xx - this->raw.v.xx) * a_per;
t_temp.raw.v.yy = this->raw.v.yy + (a_vector.raw.v.yy - this->raw.v.yy) * a_per;
t_temp.raw.v.zz = this->raw.v.zz + (a_vector.raw.v.zz - this->raw.v.zz) * a_per;
}
return t_temp;
}
/** [static][作成]Lerp
a_per = 0.0f : return = this
a_per = 1.0f : return = a_vector
*/
inline Geometry_Vector3 Geometry_Vector3::Make_Lerp(const Geometry_Vector3& a_vector_1,const Geometry_Vector3& a_vector_2,f32 a_per)
{
Geometry_Vector3 t_temp;
{
t_temp.raw.v.xx = a_vector_1.raw.v.xx + (a_vector_2.raw.v.xx - a_vector_1.raw.v.xx) * a_per;
t_temp.raw.v.yy = a_vector_1.raw.v.yy + (a_vector_2.raw.v.yy - a_vector_1.raw.v.yy) * a_per;
t_temp.raw.v.zz = a_vector_1.raw.v.zz + (a_vector_2.raw.v.zz - a_vector_1.raw.v.zz) * a_per;
}
return t_temp;
}
/** [設定]Set_Lerp。
a_per = 0.0f : this = this
a_per = 1.0f : this = a_vector
*/
inline void Geometry_Vector3::Set_Lerp(const Geometry_Vector3& a_vector,f32 a_per)
{
this->raw.v.xx += (a_vector.raw.v.xx - this->raw.v.xx) * a_per;
this->raw.v.yy += (a_vector.raw.v.yy - this->raw.v.yy) * a_per;
this->raw.v.zz += (a_vector.raw.v.zz - this->raw.v.zz) * a_per;
}
/** [設定]Lerp。
a_per = 0.0f : this = a_vector_1
a_per = 1.0f : this = a_vector_2
*/
inline void Geometry_Vector3::Set_Lerp(const Geometry_Vector3& a_vector_1,const Geometry_Vector3& a_vector_2,f32 a_per)
{
this->raw.v.xx = a_vector_1.raw.v.xx + (a_vector_2.raw.v.xx - a_vector_1.raw.v.xx) * a_per;
this->raw.v.yy = a_vector_1.raw.v.yy + (a_vector_2.raw.v.yy - a_vector_1.raw.v.yy) * a_per;
this->raw.v.zz = a_vector_1.raw.v.zz + (a_vector_2.raw.v.zz - a_vector_1.raw.v.zz) * a_per;
}
}}
#pragma warning(pop)
#endif
| 21.054381 | 134 | 0.617305 |
f1064af791209147bd47565f3703d6aeab1c6d83 | 914 | cpp | C++ | ststring.cpp | ohmyjons/SPOJ-1 | 870ae3b072a3fbc89149b35fe5649a74512a8f60 | [
"Unlicense"
] | 264 | 2015-01-08T10:07:01.000Z | 2022-03-26T04:11:51.000Z | ststring.cpp | ohmyjons/SPOJ-1 | 870ae3b072a3fbc89149b35fe5649a74512a8f60 | [
"Unlicense"
] | 17 | 2016-04-15T03:38:07.000Z | 2020-10-30T00:33:57.000Z | ststring.cpp | ohmyjons/SPOJ-1 | 870ae3b072a3fbc89149b35fe5649a74512a8f60 | [
"Unlicense"
] | 127 | 2015-01-08T04:56:44.000Z | 2022-02-25T18:40:37.000Z | // 2008-10-22
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
void inc(char* s)
{
int cur=0;
bool ok=false;
while (!ok)
{
s[cur]++;
if (s[cur]=='K')
s[cur++]='A';
else
ok=true;
}
if (s[cur]==1)
{
s[cur]='A';
s[cur+1]=0;
}
}
int ok(char* s)
{
int i=1;
while (s[i])
{
if (s[i]==s[i-1]||s[i]==s[i-1]-1||s[i]==s[i-1]+1)
return 0;
i++;
}
return 1;
}
int hash(char* s)
{
int x=1;
int i=0;
int res=0;
while (s[i])
{
res+=x*(s[i++]-'A'+1);
x*=11;
}
return res;
}
int ans[2000000];
int main()
{
//precompute answers
char s1[10]="A",s2[10]="AAAAAAA";
int sum=0;
while (strcmp(s1,s2))
{
if (ok(s1))
sum++;
ans[hash(s1)]=sum;
inc(s1);
}
for(;;)
{
s1[0]=0;
scanf("%s %s",s1,s2);
if (!s1[0]) return 0;
reverse(s1,s1+strlen(s1));
reverse(s2,s2+strlen(s2));
printf("%d\n",max(ans[hash(s2)]-ans[hash(s1)]-ok(s2),0));
}
}
| 13.057143 | 59 | 0.514223 |
f1071f2a2259d40223c641fdcc79d9d6fc9e2942 | 1,700 | cpp | C++ | leetcode_0721_unionfind.cpp | xiaoxiaoxiang-Wang/01-leetcode | 5a9426dd70c3dd6725444783aaa8cefc27196779 | [
"MIT"
] | 3 | 2021-01-18T06:26:10.000Z | 2021-01-29T07:52:49.000Z | leetcode_0721_unionfind.cpp | xiaoxiaoxiang-Wang/leetcode | 5a9426dd70c3dd6725444783aaa8cefc27196779 | [
"MIT"
] | null | null | null | leetcode_0721_unionfind.cpp | xiaoxiaoxiang-Wang/leetcode | 5a9426dd70c3dd6725444783aaa8cefc27196779 | [
"MIT"
] | null | null | null | class Solution {
public:
vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {
vector<pair<string, int>> emails;
for (int i = 0; i < accounts.size(); i++) {
for (int j = 1; j < accounts[i].size(); j++) {
emails.push_back({ accounts[i][j],i });
}
}
sort(emails.begin(), emails.end());
vector<int> uf(accounts.size(),-1);
unordered_map<int, int> um;
for (int i = 0; i < emails.size() - 1; i++){
if (emails[i].first == emails[i + 1].first) {
unionFind(uf, emails[i].second, emails[i+1].second);
}
}
int idx = 0;
for (int i = 0; i < accounts.size(); i++) {
setIndex(uf, um, i, idx);
}
vector<vector<string>> res(idx);
emails.push_back({ "",0 });
for (int i = 0; i<emails.size() - 1; i++) {
if (res[um[emails[i].second]].empty()) {
// 插入名字
res[um[emails[i].second]].push_back(accounts[emails[i].second][0]);
}
if (emails[i].first == emails[i + 1].first) {
auto iter2 = um.find(emails[i + 1].second);
if (iter2 == um.end()) {
um[emails[i+1].second] = um[emails[i].second];
}
}
else {
// 插入元素
res[um[emails[i].second]].push_back(emails[i].first);
}
}
return res;
}
int unionFind(vector<int>& uf, int a,int b) {
a = find(uf,a);
b = find(uf,b);
if (a == b) {
return false;
}
uf[a] = b;
return true;
}
int find(vector<int>& uf, int a) {
while (uf[a] != -1) {
a = uf[a];
}
return a;
}
int setIndex(vector<int>& uf, unordered_map<int, int>& um,int i,int& idx) {
auto iter = um.find(i);
if (iter != um.end()) {
return iter->second;
}
if (uf[i] == -1) {
um[i] = idx;
return idx++;
}
return um[i] = setIndex(uf, um, uf[i], idx);
}
}; | 23.943662 | 76 | 0.545294 |
f1088921c111614dc731eba6e955608389cbe272 | 982 | cpp | C++ | src/Utils.cpp | bsmithcompsci/Experiment-EmbedSystems-Playground | fcf72d6e3500c8cfea9446fcbc777be3e28cd86f | [
"MIT"
] | null | null | null | src/Utils.cpp | bsmithcompsci/Experiment-EmbedSystems-Playground | fcf72d6e3500c8cfea9446fcbc777be3e28cd86f | [
"MIT"
] | null | null | null | src/Utils.cpp | bsmithcompsci/Experiment-EmbedSystems-Playground | fcf72d6e3500c8cfea9446fcbc777be3e28cd86f | [
"MIT"
] | null | null | null | #include "global/Utils.h"
std::vector<std::string> splitStrs(const std::string &_str, char _delimiter)
{
std::vector<std::string> output;
std::string::size_type prev_pos = 0, cur_pos = 0;
while ((cur_pos = _str.find(_delimiter, cur_pos)) != std::string::npos)
{
std::string substring(_str.substr(prev_pos, cur_pos - prev_pos));
output.push_back(substring);
prev_pos = ++cur_pos;
}
output.push_back(_str.substr(prev_pos, cur_pos - prev_pos)); // Catch the last bits.
return output;
}
std::vector<int> splitInts(const std::string &_str, char _delimiter)
{
std::vector<int> output;
std::string::size_type prev_pos = 0, cur_pos = 0;
while ((cur_pos = _str.find(_delimiter, cur_pos)) != std::string::npos)
{
std::string substring(_str.substr(prev_pos, cur_pos - prev_pos));
output.push_back(atoi(substring.c_str()));
prev_pos = ++cur_pos;
}
output.push_back(atoi(_str.substr(prev_pos, cur_pos - prev_pos).c_str())); // Catch the last bits.
return output;
} | 30.6875 | 99 | 0.705703 |
f1094fbea6cdbe832dff1f5bd659025df443c301 | 1,970 | hpp | C++ | src/registry.hpp | rcabot/codscape | 5619b40d7857066818c8409d3db4371d3c8f758c | [
"Unlicense"
] | null | null | null | src/registry.hpp | rcabot/codscape | 5619b40d7857066818c8409d3db4371d3c8f758c | [
"Unlicense"
] | null | null | null | src/registry.hpp | rcabot/codscape | 5619b40d7857066818c8409d3db4371d3c8f758c | [
"Unlicense"
] | null | null | null | #ifndef REGISTRY_H
#define REGISTRY_H
#pragma once
#include "dialogue_initiator.hpp"
#include "Map.h"
#include "Person.h"
#include "interactable.hpp"
#include "dialogue_ui.hpp"
#include "rect_transform.hpp"
#include <sstream>
#include <limits>
template<typename T>
using uvector = std::vector<std::unique_ptr<T>>;
class registry
{
private:
public:
uvector<Map> maps_;
uvector<person> people_;
std::vector<interactable> interactables_;
player_state_machine player_state_machine_;
dialogue_state dialogue_state_;
dialogue_initiator dialogue_initiator_;
dialogue_ui dialogue_ui_;
rect_transform dialogue_ui_transform_;
registry() :
maps_{},
people_{},
interactables_{},
player_state_machine_{},
dialogue_state_{*this},
dialogue_initiator_{player_state_machine_, dialogue_state_},
dialogue_ui_transform_{} ,
dialogue_ui_{*this,dialogue_ui_transform_,dialogue_state_}
{}
void add_new_person_at(const Vector2& position, const std::string name, int map_index_)
{
auto start_dialogue_with_person = std::function([name](registry& r){
r.dialogue_initiator_.start_dialogue_with(name);
});
people_.emplace_back(std::make_unique<person>(name, maps_[map_index_].get(), position));
interactables_.emplace_back(position,std::move(start_dialogue_with_person),*this);
}
template<class...Params>
void add_map(Params&&... args)
{
maps_.emplace_back(std::make_unique<Map>(args...));
}
interactable* try_get_nearest_interactable_object_in_radius(const Vector2 center, const float radius)
{
interactable* nearest_interactable = nullptr;
float min_distance{std::numeric_limits<float>::max()};
for(auto& interactable : interactables_)
{
float distance = center.distance(interactable.position_);
if(radius > distance && distance < min_distance)
{
min_distance = distance;
nearest_interactable = &interactable;
}
}
return nearest_interactable;
}
};
#endif | 25.25641 | 102 | 0.744162 |
f10c6af1132219f183e8088cef1ee69cee874021 | 22 | cpp | C++ | library/containers/flat_hash/lib/probings.cpp | ZhekehZ/catboost | 3f774da539b8e57cca25686b89c473cbd1f61a6c | [
"Apache-2.0"
] | 6,989 | 2017-07-18T06:23:18.000Z | 2022-03-31T15:58:36.000Z | library/cpp/containers/flat_hash/lib/probings.cpp | birichie/catboost | de75c6af12cf490700e76c22072fbdc15b35d679 | [
"Apache-2.0"
] | 1,978 | 2017-07-18T09:17:58.000Z | 2022-03-31T14:28:43.000Z | library/cpp/containers/flat_hash/lib/probings.cpp | birichie/catboost | de75c6af12cf490700e76c22072fbdc15b35d679 | [
"Apache-2.0"
] | 1,228 | 2017-07-18T09:03:13.000Z | 2022-03-29T05:57:40.000Z | #include "probings.h"
| 11 | 21 | 0.727273 |
f10cd8557ccd76ef1c08f38c105009ce9e26196e | 650 | cpp | C++ | Spline/Source.cpp | Fahersto/Spline | cbe4645aedd9b6e53c9c3393b1c7f2fc0040666d | [
"MIT"
] | null | null | null | Spline/Source.cpp | Fahersto/Spline | cbe4645aedd9b6e53c9c3393b1c7f2fc0040666d | [
"MIT"
] | null | null | null | Spline/Source.cpp | Fahersto/Spline | cbe4645aedd9b6e53c9c3393b1c7f2fc0040666d | [
"MIT"
] | null | null | null | #include "ParametricSpline.h"
int main()
{
ParametricSpline parametricSpline = ParametricSpline();
const int VALUE_COUNT = 3;
double* x = new double[VALUE_COUNT]{ 0, 1, 2 };
double* y = new double[VALUE_COUNT]{ 0, 3, 0 };
double* z = new double[VALUE_COUNT]{ 1, 2, 3 };
parametricSpline.Compute(x, y, z, VALUE_COUNT);
const int STEPS = 10;
for (int i = 0; i < parametricSpline.GetSegmentCount(); i++)
{
for (int j = 0; j < STEPS; j++)
{
double t = i + (double)j / (STEPS);
double* position = parametricSpline.eval(t);
printf("new Vector3(%ff, %ff, %ff),\n", position[0], position[1], position[2]);
}
}
return 0;
} | 21.666667 | 82 | 0.629231 |
f10f1c8509669062f615ca8b59fe48ba8955c30e | 1,443 | cc | C++ | project/core/id/test/SequentialIdGenerator.cc | letsmake-games/engine | b40559037353e000adf2f18ca9ead16529f932c6 | [
"MIT"
] | null | null | null | project/core/id/test/SequentialIdGenerator.cc | letsmake-games/engine | b40559037353e000adf2f18ca9ead16529f932c6 | [
"MIT"
] | null | null | null | project/core/id/test/SequentialIdGenerator.cc | letsmake-games/engine | b40559037353e000adf2f18ca9ead16529f932c6 | [
"MIT"
] | null | null | null | //
// (c) LetsMakeGames 2019
// http://www.letsmake.games
//
#include "core/id/IdClass.hh"
#include "core/id/SequentialIdGenerator.hh"
#include "gtest/gtest.h"
//
// types //////////////////////////////////////////////////////////////////////
//
DECLARE_IDCLASS(BasicId, uint8_t);
//
// Generator //////////////////////////////////////////////////////////////////
//
TEST(Test_SequentialIdGenerator, Generation )
{
//
// generate an id
//
Engine::SequentialIdGenerator<BasicId> generator;
BasicId id1 = generator.next();
EXPECT_NE(id1, BasicId::InvalidId);
EXPECT_EQ(id1.getRawId(), 0);
//
// the last id should be the id we just generated
//
BasicId id1_2 = generator.prev();
EXPECT_EQ(id1, id1_2);
//
// generate another id
//
BasicId id2 = generator.next();
EXPECT_NE(id2, BasicId::InvalidId);
EXPECT_NE(id1, id2);
//
// once we run out of numbers, we generate only InvalidIds
//
for(size_t i = 0; i != 256; ++i )
{
generator.next();
}
EXPECT_EQ(generator.next(), BasicId::InvalidId);
EXPECT_EQ(generator.next(), BasicId::InvalidId);
//
// prev always returns the last VALID id
//
EXPECT_EQ(BasicId(BasicId::InvalidValue-1), generator.prev());
//
// we can reset a generator to recycle old ids
//
generator.reset();
BasicId id1_3 = generator.next();
EXPECT_EQ(id1, id1_3);
}
| 21.220588 | 79 | 0.559252 |
f10f929d172d14eb072e9b9b455635bf323d7f0c | 266 | hpp | C++ | NewCalculator/judge.hpp | MichaelTan9999/NewCalculator | f7b5840b876317f405712f9aee80586cb10bbbaf | [
"Apache-2.0"
] | null | null | null | NewCalculator/judge.hpp | MichaelTan9999/NewCalculator | f7b5840b876317f405712f9aee80586cb10bbbaf | [
"Apache-2.0"
] | null | null | null | NewCalculator/judge.hpp | MichaelTan9999/NewCalculator | f7b5840b876317f405712f9aee80586cb10bbbaf | [
"Apache-2.0"
] | null | null | null | //
// judge.hpp
// NewCalculator
//
// Created by Michael Tan on 2019/3/21.
// Copyright © 2019 Michael Tan. All rights reserved.
//
#ifndef judge_hpp
#define judge_hpp
#include <string>
using namespace std;
string proc(string expr);
#endif /* judge_hpp */
| 14 | 54 | 0.68797 |
f10fe3c7b0a9556130f2361f133bf535c6bd8706 | 5,361 | hpp | C++ | contrib/backends/nntpchan-daemon/libnntpchan/kqueue.hpp | majestrate/nntpchan | f92f68c3cdce4b7ce6d4121ca4356b36ebcd933f | [
"MIT"
] | 233 | 2015-08-06T02:51:52.000Z | 2022-02-14T11:29:13.000Z | contrib/backends/nntpchan-daemon/libnntpchan/kqueue.hpp | Revivify/nntpchan | 0d555bb88a2298dae9aacf11348e34c52befa3d8 | [
"MIT"
] | 98 | 2015-09-19T22:29:00.000Z | 2021-06-12T09:43:13.000Z | contrib/backends/nntpchan-daemon/libnntpchan/kqueue.hpp | Revivify/nntpchan | 0d555bb88a2298dae9aacf11348e34c52befa3d8 | [
"MIT"
] | 49 | 2015-08-06T02:51:55.000Z | 2020-03-11T04:23:56.000Z | #include <nntpchan/event.hpp>
#include <sys/types.h>
#include <sys/event.h>
#include <iostream>
#include <cstring>
#include <errno.h>
namespace nntpchan
{
namespace ev
{
template<size_t bufsz>
struct KqueueLoop : public Loop
{
int kfd;
size_t conns;
char readbuf[bufsz];
KqueueLoop() : kfd(kqueue()), conns(0)
{
};
virtual ~KqueueLoop()
{
::close(kfd);
}
virtual bool TrackConn(ev::io * handler)
{
struct kevent event;
short filter = 0;
if(handler->readable() || handler->acceptable())
{
filter |= EVFILT_READ;
}
if(handler->writeable())
{
filter |= EVFILT_WRITE;
}
EV_SET(&event, handler->fd, filter, EV_ADD | EV_CLEAR, 0, 0, handler);
int ret = kevent(kfd, &event, 1, nullptr, 0, nullptr);
if(ret == -1) return false;
if(event.flags & EV_ERROR)
{
std::cerr << "KqueueLoop::TrackConn() kevent failed: " << strerror(event.data) << std::endl;
return false;
}
++conns;
return true;
}
virtual void UntrackConn(ev::io * handler)
{
struct kevent event;
short filter = 0;
if(handler->readable() || handler->acceptable())
{
filter |= EVFILT_READ;
}
if(handler->writeable())
{
filter |= EVFILT_WRITE;
}
EV_SET(&event, handler->fd, filter, EV_DELETE, 0, 0, handler);
int ret = kevent(kfd, &event, 1, nullptr, 0, nullptr);
if(ret == -1 || event.flags & EV_ERROR)
std::cerr << "KqueueLoop::UntrackConn() kevent failed: " << strerror(event.data) << std::endl;
else
--conns;
}
virtual void Run()
{
struct kevent events[512];
struct kevent * event;
io * handler;
int ret, idx;
do
{
idx = 0;
ret = kevent(kfd, nullptr, 0, events, 512, nullptr);
if(ret > 0)
{
while(idx < ret)
{
event = &events[idx++];
handler = static_cast<io *>(event->udata);
if(event->flags & EV_EOF)
{
handler->close();
delete handler;
continue;
}
if(event->filter & EVFILT_READ && handler->acceptable())
{
int backlog = event->data;
while(backlog)
{
handler->accept();
--backlog;
}
}
if(event->filter & EVFILT_READ && handler->readable())
{
int readed = 0;
size_t readnum = event->data;
while(readnum > sizeof(readbuf))
{
int r = handler->read(readbuf, sizeof(readbuf));
if(r > 0)
{
readnum -= r;
readed += r;
}
else
readnum = 0;
}
if(readnum && readed != -1)
{
int r = handler->read(readbuf, readnum);
if(r > 0)
readed += r;
else
readed = r;
}
}
if(event->filter & EVFILT_WRITE && handler->writeable())
{
int writespace = 1024;
int written = handler->write(writespace);
if(written == -1)
{
if (errno == EAGAIN || errno == EWOULDBLOCK)
{
// blocking
}
else
{
perror("write()");
handler->close();
delete handler;
continue;
}
}
}
if(!handler->keepalive())
{
handler->close();
delete handler;
}
}
}
}
while(ret != -1);
}
};
}
} | 33.092593 | 110 | 0.320463 |
f111b50b2ed434352fe1d8198b05939082989892 | 1,215 | cpp | C++ | Tree/589-n-ary-tree-preorder-traversal.cpp | wandsX/LeetCodeExperience | 8502e6e8ce911045f45f0075bcf3ee751a4558c7 | [
"MIT"
] | null | null | null | Tree/589-n-ary-tree-preorder-traversal.cpp | wandsX/LeetCodeExperience | 8502e6e8ce911045f45f0075bcf3ee751a4558c7 | [
"MIT"
] | null | null | null | Tree/589-n-ary-tree-preorder-traversal.cpp | wandsX/LeetCodeExperience | 8502e6e8ce911045f45f0075bcf3ee751a4558c7 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
//leetcode submit region begin(Prohibit modification and deletion)
class Solution
{
public:
vector<int> preorder(Node *root)
{
stack < Node * > s;
std::vector<int> ans;
Node *cur = nullptr;
if (root != nullptr)
{ s.push(root); }
while(!s.empty())
{
cur = s.top();
s.pop();
ans.emplace_back(cur->val);
for (int i = cur->children.size() - 1; i >= 0; --i)
s.push(cur->children[i]);
}
return ans;
}
};
// 递归
class Solution1
{
public:
vector<int> preorder(Node *root)
{
std::vector<int> ans;
traverse(root, ans);
return ans;
}
void traverse(Node *cur, vector<int> &ans)
{
if (cur == nullptr)
{ return; }
ans.push_back(cur->val);
for (auto &e : cur->children)
{
traverse(e, ans);
}
}
};
//leetcode submit region end(Prohibit modification and deletion)
| 19.596774 | 67 | 0.443621 |
47dbd807a98370edc068e9a4687d752e159c0fea | 2,389 | cpp | C++ | LeetCode/200/148.cpp | K-ona/C-_Training | d54970f7923607bdc54fc13677220d1b3daf09e5 | [
"Apache-2.0"
] | null | null | null | LeetCode/200/148.cpp | K-ona/C-_Training | d54970f7923607bdc54fc13677220d1b3daf09e5 | [
"Apache-2.0"
] | null | null | null | LeetCode/200/148.cpp | K-ona/C-_Training | d54970f7923607bdc54fc13677220d1b3daf09e5 | [
"Apache-2.0"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode* next) : val(x), next(next) {}
};
class Solution {
tuple<ListNode*, ListNode*> partition(ListNode* begin, ListNode* end) {
int sep = begin->val;
ListNode* res = begin;
ListNode* head = begin;
ListNode* tail = begin;
while (begin != end) {
// cout << begin->val << " ";
auto next = begin->next;
if (begin->val <= sep) {
begin->next = head;
head = begin;
} else {
begin->next = nullptr;
tail->next = begin;
tail = begin;
}
begin = next;
}
// cout << endl;
tail->next = end;
return {res, head};
}
tuple<ListNode*, ListNode*> quick_sort(ListNode* begin, ListNode* end) {
if (begin->next == end) return {begin, begin};
auto [sep, head] = partition(begin, end);
if (sep == head) {
auto [h, t] = quick_sort(sep->next, end);
sep->next = h;
return {sep, t};
}
auto [h1, t1] = quick_sort(head, sep);
if (sep->next != end) {
auto [h2, t2] = quick_sort(sep->next, end);
t1->next = sep;
sep->next = h2;
return {h1, t2};
} else {
t1->next = sep;
return {h1, sep};
}
}
public:
ListNode* sortList(ListNode* head) {
if (head)
return std::get<0>(quick_sort(head, nullptr));
return nullptr;
}
};
class Solution {
public:
ListNode* sortList(ListNode* head) {
if (!head || !head->next) return head;
auto slow = head, fast = head;
while (fast->next && fast->next->next)
slow = slow->next, fast = fast->next->next;
// 切链
fast = slow->next, slow->next = nullptr;
return merge(sortList(head), sortList(fast));
}
private:
ListNode* merge(ListNode* l1, ListNode* l2) {
ListNode sub(0), *ptr = ⊂
while (l1 && l2) {
auto &node = l1->val < l2->val ? l1 : l2;
ptr = ptr->next = node, node = node->next;
}
ptr->next = l1 ? l1 : l2;
return sub.next;
}
};
int main() {
ListNode e(0);
ListNode d(4, &e);
ListNode c(3, &d);
ListNode b(5, &c);
ListNode a(-1, &b);
Solution().sortList(&a);
} | 23.421569 | 74 | 0.518627 |
47e158798760a23cd391c2952c00eed2e8f5ee4c | 265 | cpp | C++ | libs/core/render/src/vulkan/detail/bksge_core_render_vulkan_detail_cull_mode.cpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 4 | 2018-06-10T13:35:32.000Z | 2021-06-03T14:27:41.000Z | libs/core/render/src/vulkan/detail/bksge_core_render_vulkan_detail_cull_mode.cpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 566 | 2017-01-31T05:36:09.000Z | 2022-02-09T05:04:37.000Z | libs/core/render/src/vulkan/detail/bksge_core_render_vulkan_detail_cull_mode.cpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 1 | 2018-07-05T04:40:53.000Z | 2018-07-05T04:40:53.000Z | /**
* @file bksge_core_render_vulkan_detail_cull_mode.cpp
*
* @brief CullMode クラスの定義
*
* @author myoukaku
*/
#include <bksge/fnd/config.hpp>
#if !defined(BKSGE_HEADER_ONLY)
#include <bksge/core/render/vulkan/detail/inl/cull_mode_inl.hpp>
#endif
| 20.384615 | 65 | 0.713208 |
47e22f8b52fb7c6425212e051080062f04e3f07e | 5,905 | cpp | C++ | src/mercury.cpp | darkedge/mercury | 5bdf857b38f68b2a8c6ae1455f7623313ad0af71 | [
"MIT"
] | null | null | null | src/mercury.cpp | darkedge/mercury | 5bdf857b38f68b2a8c6ae1455f7623313ad0af71 | [
"MIT"
] | null | null | null | src/mercury.cpp | darkedge/mercury | 5bdf857b38f68b2a8c6ae1455f7623313ad0af71 | [
"MIT"
] | null | null | null | #include <codeanalysis/warnings.h>
#pragma warning( push, 0 )
#pragma warning( disable : ALL_CODE_ANALYSIS_WARNINGS )
#include "glad/glad.h"
#include "glad.c"
#include "GLFW/glfw3.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include <stdint.h>
// ImGui
#include "imgui.cpp"
#include "imgui_demo.cpp"
#include "imgui_draw.cpp"
#pragma warning( pop )
#include "mercury.h"
#include "mercury_imgui.cpp"
#include "mercury_input.cpp"
#include "mercury_game.cpp"
#include "mercury_program.cpp"
#include "mercury_math.cpp"
// Tell Optimus to use the high-performance NVIDIA processor
// option if it's on auto-select (we cannot override it)
extern "C" {
_declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
}
static GLFWwindow *s_window;
static float s_deltaTime = 0.0f;
static int32_t s_width = 1280;
static int32_t s_height = 720;
static const char *s_name = "Hello World!";
inline float GetDeltaTime() {
return s_deltaTime;
}
inline GLFWwindow *GetWindow() {
return s_window;
}
inline int32_t GetWindowWidth() {
return s_width;
}
inline int32_t GetWindowHeight() {
return s_height;
}
void CALLBACK debugCallbackARB( GLenum source, GLenum type, GLuint id, GLenum severity,
GLsizei length, const GLchar *message, GLvoid *userParam ) {
if (type == GL_DEBUG_TYPE_OTHER) return;
Log("Type: ");
switch (type)
{
case GL_DEBUG_TYPE_ERROR:
Log("ERROR");
break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
Log("DEPRECATED_BEHAVIOR");
break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
Log("UNDEFINED_BEHAVIOR");
break;
case GL_DEBUG_TYPE_PORTABILITY:
Log("PORTABILITY");
break;
case GL_DEBUG_TYPE_PERFORMANCE:
Log("PERFORMANCE");
break;
case GL_DEBUG_TYPE_OTHER:
Log("OTHER");
break;
}
Log(" - id: %d", id);
Log(" - Severity: ");
switch (severity)
{
case GL_DEBUG_SEVERITY_LOW:
Log("LOW");
break;
case GL_DEBUG_SEVERITY_MEDIUM:
Log("MEDIUM");
break;
case GL_DEBUG_SEVERITY_HIGH:
Log("HIGH");
break;
}
Log(" - %s\n", message);
}
void GlfwErrorCallback( int32_t, const char *description ) {
Log("%s\n", description);
}
void GlfwKeyCallBack( GLFWwindow* window, int32_t key, int32_t scancode, int32_t action, int32_t mods ) {
if ( key == GLFW_KEY_ESCAPE && action == GLFW_PRESS ) {
glfwSetWindowShouldClose( window, GL_TRUE );
}
if ( action == GLFW_PRESS ) {
Input::SetKey( key, true );
}
if ( action == GLFW_RELEASE ) {
Input::SetKey( key, false );
}
ImGui_ImplGlfwGL3_KeyCallback(window, key, scancode, action, mods);
}
void GlfwMouseButtonCallback( GLFWwindow *window, int32_t button, int32_t action, int32_t mods ) {
if ( action == GLFW_PRESS ) {
Input::SetMouseButton( button, true );
}
if ( action == GLFW_RELEASE ) {
Input::SetMouseButton( button, false );
}
if(!Input::IsMouseGrabbed()) {
ImGui_ImplGlfwGL3_MouseButtonCallback(window, button, action, mods);
}
}
void GlfwScrollCallback( GLFWwindow *window, double xoffset, double yoffset ) {
ImGui_ImplGlfwGL3_ScrollCallback(window, xoffset, yoffset);
}
void GlfwCharCallback( GLFWwindow *window, uint32_t codepoint ) {
ImGui_ImplGlfwGL3_CharCallback(window, codepoint);
}
void GlfwCursorPosCallback( GLFWwindow *window, double xpos, double ypos ) {
Input::SetMousePosition( float2 { (float) xpos, (float) ypos } );
}
void GlfwWindowSizeCallBack( GLFWwindow *window, int32_t width, int32_t height ) {
// TODO
//Application::SetWidth( width );
//Application::SetHeight( height );
}
void EnterWindowLoop() {
Init(); // Slow
double lastTime = glfwGetTime();
while ( !glfwWindowShouldClose( s_window ) )
{
double now = glfwGetTime();
s_deltaTime = (float) ( now - lastTime );
lastTime = now;
glfwPollEvents();
Input::Tick();
Tick();
Input::PostTick();
glfwSwapBuffers( s_window );
}
glfwDestroyWindow( s_window );
glfwTerminate();
std::exit( EXIT_SUCCESS );
}
int CALLBACK WinMain(
_In_ HINSTANCE hInstance,
_In_ HINSTANCE hPrevInstance,
_In_ LPSTR lpCmdLine,
_In_ int nCmdShow
) {
glfwSetErrorCallback( GlfwErrorCallback );
if ( glfwInit() ) {
// Window hints
glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 4 );
glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 5 );
glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE );
s_window = glfwCreateWindow( s_width, s_height, s_name, nullptr, nullptr );
glfwMakeContextCurrent( s_window );
// TODO: Callbacks
glfwSetKeyCallback( s_window, GlfwKeyCallBack );
glfwSetMouseButtonCallback( s_window, GlfwMouseButtonCallback );
glfwSetScrollCallback( s_window, GlfwScrollCallback );
glfwSetCharCallback( s_window, GlfwCharCallback );
glfwSetCursorPosCallback( s_window, GlfwCursorPosCallback );
glfwSetWindowSizeCallback( s_window, GlfwWindowSizeCallBack );
ImGui_ImplGlfwGL3_Init(s_window, false);
// Sync to monitor refresh rate
glfwSwapInterval( 1 );
/************************************************************************/
/* OpenGL */
/************************************************************************/
if ( gladLoadGLLoader((GLADloadproc) glfwGetProcAddress) ) {
Log("OpenGL %d.%d\n", GLVersion.major, GLVersion.minor);
glEnable( GL_BLEND );
glEnable( GL_MULTISAMPLE );
glEnable( GL_CULL_FACE );
glEnable( GL_DEPTH_TEST );
glClearColor( 0.192156862745098f, 0.3019607843137255f, 0.4745098039215686f, 1.0f );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
glDepthFunc( GL_LEQUAL );
// https://www.opengl.org/wiki/Debug_Output
glDebugMessageCallback( (GLDEBUGPROC) debugCallbackARB, nullptr );
glEnable( GL_DEBUG_OUTPUT );
glEnable( GL_DEBUG_OUTPUT_SYNCHRONOUS );
EnterWindowLoop();
} else {
printf( "Failed to init glad!\n" );
std::exit( EXIT_FAILURE );
}
} else {
printf( "Failed to init GLFW!\n" );
std::exit( EXIT_FAILURE );
}
}
| 25.343348 | 105 | 0.695512 |
47e9bfdb27625f3517d82ddced901e0cc185a5da | 182 | cpp | C++ | docs/mfc/codesnippet/CPP/cfontdialog-class_8.cpp | jmittert/cpp-docs | cea5a8ee2b4764b2bac4afe5d386362ffd64e55a | [
"CC-BY-4.0",
"MIT"
] | 14 | 2018-01-28T18:10:55.000Z | 2021-11-16T13:21:18.000Z | docs/mfc/codesnippet/CPP/cfontdialog-class_8.cpp | jmittert/cpp-docs | cea5a8ee2b4764b2bac4afe5d386362ffd64e55a | [
"CC-BY-4.0",
"MIT"
] | null | null | null | docs/mfc/codesnippet/CPP/cfontdialog-class_8.cpp | jmittert/cpp-docs | cea5a8ee2b4764b2bac4afe5d386362ffd64e55a | [
"CC-BY-4.0",
"MIT"
] | 2 | 2018-11-01T12:33:08.000Z | 2021-11-16T13:21:19.000Z | // Is the selected font bold?
CFontDialog dlg;
if (dlg.DoModal() == IDOK)
{
BOOL bold = dlg.IsBold();
TRACE(_T("Is the selected font bold? %d\n"), bold);
} | 26 | 57 | 0.56044 |
47ea21529b3531fee3ea9b666be608dbeac4ac54 | 25,678 | cpp | C++ | released_plugins/v3d_plugins/bigneuron_LinGU_LCM_boost/components.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2021-12-27T19:14:03.000Z | 2021-12-27T19:14:03.000Z | released_plugins/v3d_plugins/bigneuron_LinGU_LCM_boost/components.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2016-12-03T05:33:13.000Z | 2016-12-03T05:33:13.000Z | released_plugins/v3d_plugins/bigneuron_LinGU_LCM_boost/components.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | /*
* components.cpp
*
* Created on: May 20, 2015
* Author: gulin
*/
# include <cstdlib>
# include <iostream>
# include <iomanip>
# include <fstream>
# include <ctime>
# include <cmath>
# include <cstring>
using namespace std;
# include "components.hpp"
//****************************************************************************80
int file_column_count ( string filename )
//****************************************************************************80
//
// Purpose:
//
// FILE_COLUMN_COUNT counts the columns in the first line of a file.
//
// Discussion:
//
// The file is assumed to be a simple text file.
//
// Most lines of the file are presumed to consist of COLUMN_NUM words,
// separated by spaces. There may also be some blank lines, and some
// comment lines, which have a "#" in column 1.
//
// The routine tries to find the first non-comment non-blank line and
// counts the number of words in that line.
//
// If all lines are blanks or comments, it goes back and tries to analyze
// a comment line.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 05 July 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, string FILENAME, the name of the file.
//
// Output, int FILE_COLUMN_COUNT, the number of columns assumed
// to be in the file.
//
{
int column_num;
ifstream input;
bool got_one;
string text;
//
// Open the file.
//
input.open ( filename.c_str ( ) );
if ( !input )
{
column_num = -1;
cerr << "\n";
cerr << "FILE_COLUMN_COUNT - Fatal error!\n";
cerr << " Could not open the file:\n";
cerr << " \"" << filename << "\"\n";
exit ( 1 );
}
//
// Read one line, but skip blank lines and comment lines.
//
got_one = false;
for ( ; ; )
{
getline ( input, text );
if ( input.eof ( ) )
{
break;
}
if ( s_len_trim ( text ) <= 0 )
{
continue;
}
if ( text[0] == '#' )
{
continue;
}
got_one = true;
break;
}
if ( !got_one )
{
input.close ( );
input.open ( filename.c_str ( ) );
for ( ; ; )
{
input >> text;
if ( input.eof ( ) )
{
break;
}
if ( s_len_trim ( text ) == 0 )
{
continue;
}
got_one = true;
break;
}
}
input.close ( );
if ( !got_one )
{
cerr << "\n";
cerr << "FILE_COLUMN_COUNT - Warning!\n";
cerr << " The file does not seem to contain any data.\n";
return -1;
}
column_num = s_word_count ( text );
return column_num;
}
//****************************************************************************80
int file_row_count ( string input_filename )
//****************************************************************************80
//
// Purpose:
//
// FILE_ROW_COUNT counts the number of row records in a file.
//
// Discussion:
//
// It does not count lines that are blank, or that begin with a
// comment symbol '#'.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 23 February 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, string INPUT_FILENAME, the name of the input file.
//
// Output, int FILE_ROW_COUNT, the number of rows found.
//
{
//int bad_num;
int comment_num;
ifstream input;
// int i;
string line;
int record_num;
int row_num;
row_num = 0;
comment_num = 0;
record_num = 0;
//bad_num = 0;
input.open ( input_filename.c_str ( ) );
if ( !input )
{
cerr << "\n";
cerr << "FILE_ROW_COUNT - Fatal error!\n";
cerr << " Could not open the input file: \"" << input_filename << "\"\n";
exit ( 1 );
}
for ( ; ; )
{
getline ( input, line );
if ( input.eof ( ) )
{
break;
}
record_num = record_num + 1;
if ( line[0] == '#' )
{
comment_num = comment_num + 1;
continue;
}
if ( s_len_trim ( line ) == 0 )
{
comment_num = comment_num + 1;
continue;
}
row_num = row_num + 1;
}
input.close ( );
return row_num;
}
//****************************************************************************80
int i4_min ( int i1, int i2 )
//****************************************************************************80
//
// Purpose:
//
// I4_MIN returns the minimum of two I4's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 13 October 1998
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int I1, I2, two integers to be compared.
//
// Output, int I4_MIN, the smaller of I1 and I2.
//
{
int value;
if ( i1 < i2 )
{
value = i1;
}
else
{
value = i2;
}
return value;
}
//****************************************************************************80
int i4block_components ( int l, int m, int n, int *a, int *c )
//****************************************************************************80
//
// Purpose:
//
// I4BLOCK_COMPONENTS assigns contiguous nonzero pixels to a common component.
//
// Discussion:
//
// On input, the A array contains values of 0 or 1.
//
// The 0 pixels are to be ignored. The 1 pixels are to be grouped
// into connected components.
//
// The pixel A(I,J,K) is "connected" to the pixels:
//
// A(I-1,J, K ), A(I+1,J, K ),
// A(I, J-1,K ), A(I, J+1,K ),
// A(I, J, K-1), A(I, J, K+1),
//
// so most pixels have 6 neighbors.
//
// On output, COMPONENT_NUM reports the number of components of nonzero
// data, and the array C contains the component assignment for
// each nonzero pixel, and is 0 for zero pixels.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 February 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int L, M, N, the order of the array.
//
// Input, int A[L*M*N], the pixel array.
//
// Output, int C[L*M*N], the component array.
//
// Output, int I4BLOCK_COMPONENTS, the number of components
// of nonzero data.
//
{
int b;
int c1;
// int c2;
int component;
int component_num;
int i;
int j;
int k;
int north;
int *p;
int *q;
int up;
int west;
//
// Initialization.
//
for ( k = 0; k < n; k++ )
{
for ( j = 0; j < m; j++ )
{
for ( i = 0; i < l; i++ )
{
c[i+j*l+k*l*m] = 0;
}
}
}
component_num = 0;
//
// P is simply used to store the component labels. The dimension used
// here is, of course, usually an absurd overestimate.
//
p = new int[l*m*n+1];
for ( i = 0; i <= l * m * n; i++ )
{
p[i] = i;
}
//
// "Read" the array one pixel at a time. If a (nonzero) pixel has a north or
// west neighbor with a label, the current pixel inherits it.
// In case the labels disagree, we need to adjust the P array so we can
// later deal with the fact that the two labels need to be merged.
//
for ( i = 0; i < l; i++ )
{
for ( j = 0; j < m; j++ )
{
for ( k = 0; k < n; k++ )
{
if ( i == 0 )
{
north = 0;
}
else
{
north = c[i-1+j*l+k*l*m];
}
if ( j == 0 )
{
west = 0;
}
else
{
west = c[i+(j-1)*l+k*l*m];
}
if ( k == 0 )
{
up = 0;
}
else
{
up = c[i+j*l+(k-1)*l*m];
}
if ( a[i+j*l+k*l*m] != 0 )
{
//
// New component?
//
if ( north == 0 && west == 0 && up == 0 )
{
component_num = component_num + 1;
c[i+j*l+k*l*m] = component_num;
}
//
// One predecessor is labeled.
//
else if ( north != 0 && west == 0 && up == 0 )
{
c[i+j*l+k*l*m] = north;
}
else if ( north == 0 && west != 0 && up == 0 )
{
c[i+j*l+k*l*m] = west;
}
else if ( north == 0 && west == 0 && up != 0 )
{
c[i+j*l+k*l*m] = up;
}
//
// Two predecessors are labeled.
//
else if ( north == 0 && west != 0 && up != 0 )
{
c[i+j*l+k*l*m] = i4_min ( west, up );
c1 = i4_min ( p[west], p[up] );
p[west] = c1;
p[up] = c1;
}
else if ( north != 0 && west == 0 && up != 0 )
{
c[i+j*l+k*l*m] = i4_min ( north, up );
c1 = i4_min ( p[north], p[up] );
p[north] = c1;
p[up] = c1;
}
else if ( north != 0 && west != 0 && up == 0 )
{
c[i+j*l+k*l*m] = i4_min ( north, west );
c1 = i4_min ( p[north], p[west] );
p[north] = c1;
p[west] = c1;
}
//
// Three predecessors are labeled.
//
else if ( north != 0 && west != 0 && up != 0 )
{
c[i+j*l+k*l*m] = i4_min ( north, i4_min ( west, up ) );
c1 = i4_min ( p[north], i4_min ( p[west], p[up] ) );
p[north] = c1;
p[west] = c1;
p[up] = c1;
}
}
}
}
}
//
// When a component has multiple labels, have the higher labels
// point to the lowest one.
//
for ( component = component_num; 1 <= component; component-- )
{
b = component;
while ( p[b] != b )
{
b = p[b];
}
p[component] = b;
}
//
// Locate the minimum label for each component.
// Assign these mininum labels new consecutive indices.
//
q = new int[component_num+1];
for ( j = 0; j <= component_num; j++ )
{
q[j] = 0;
}
i = 0;
for ( component = 1; component <= component_num; component++ )
{
if ( p[component] == component )
{
i = i + 1;
q[component] = i;
}
}
component_num = i;
//
// Replace the labels by consecutive labels.
//
for ( i = 0; i < l; i++ )
{
for ( j = 0; j < m; j++ )
{
for ( k = 0; k < n; k++ )
{
c[i+j*l+k*l*m] = q [ p [ c[i+j*l+k*l*m] ] ];
}
}
}
delete [] p;
delete [] q;
return component_num;
}
//****************************************************************************80
int i4mat_components ( int m, int n, int a[], int c[] )
//****************************************************************************80
//
// Purpose:
//
// I4MAT_COMPONENTS assigns contiguous nonzero pixels to a common component.
//
// Discussion:
//
// On input, the A array contains values of 0 or 1.
//
// The 0 pixels are to be ignored. The 1 pixels are to be grouped
// into connected components.
//
// The pixel A(I,J) is "connected" to the pixels A(I-1,J), A(I+1,J),
// A(I,J-1) and A(I,J+1), so most pixels have 4 neighbors.
//
// (Another choice would be to assume that a pixel was connected
// to the other 8 pixels in the 3x3 block containing it.)
//
// On output, COMPONENT_NUM reports the number of components of nonzero
// data, and the array C contains the component assignment for
// each nonzero pixel, and is 0 for zero pixels.
//
// Picture:
//
// Input A:
//
// 0 2 0 0 17 0 3
// 0 0 3 0 1 0 4
// 1 0 4 8 8 0 7
// 3 0 6 45 0 0 0
// 3 17 0 5 9 2 5
//
// Output:
//
// COMPONENT_NUM = 4
//
// C:
//
// 0 1 0 0 2 0 3
// 0 0 2 0 2 0 3
// 4 0 2 2 2 0 3
// 4 0 2 2 0 0 0
// 4 4 0 2 2 2 2
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 March 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the order of the array.
//
// Input, int A[M*N], the pixel array.
//
// Output, int C[M*N], the component array.
//
// Output, int I4MAT_COMPONENTS, the number of components
// of nonzero data.
//
{
int b;
int component;
int component_num;
int i;
int j;
int north;
int *p;
int *q;
int west;
//
// Initialization.
//
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
c[i+j*m] = 0;
}
}
component_num = 0;
//
// P is simply used to store the component labels. The dimension used
// here is, of course, usually an absurd overestimate.
//
p = new int[m*n+1];
for ( i = 0; i <= m * n; i++ )
{
p[i] = i;
}
//
// "Read" the array one pixel at a time. If a (nonzero) pixel has a north or
// west neighbor with a label, the current pixel inherits it.
// In case the labels disagree, we need to adjust the P array so we can
// later deal with the fact that the two labels need to be merged.
//
for ( i = 0; i < m; i++ )
{
for ( j = 0; j < n; j++ )
{
if ( i == 0 )
{
north = 0;
}
else
{
north = c[i-1+j*m];
}
if ( j == 0 )
{
west = 0;
}
else
{
west = c[i+(j-1)*m];
}
if ( a[i+j*m] != 0 )
{
if ( north == 0 )
{
if ( west == 0 )
{
component_num = component_num + 1;
c[i+j*m] = component_num;
}
else
{
c[i+j*m] = west;
}
}
else if ( north != 0 )
{
if ( west == 0 || west == north )
{
c[i+j*m] = north;
}
else
{
c[i+j*m] = i4_min ( north, west );
if ( north < west )
{
p[west] = north;
}
else
{
p[north] = west;
}
}
}
}
}
}
//
// When a component has multiple labels, have the higher labels
// point to the lowest one.
//
for ( component = component_num; 1 <= component; component-- )
{
b = component;
while ( p[b] != b )
{
b = p[b];
}
p[component] = b;
}
//
// Locate the minimum label for each component.
// Assign these mininum labels new consecutive indices.
//
q = new int[component_num+1];
for ( j = 0; j <= component_num; j++ )
{
q[j] = 0;
}
i = 0;
for ( component = 1; component <= component_num; component++ )
{
if ( p[component] == component )
{
i = i + 1;
q[component] = i;
}
}
component_num = i;
//
// Replace the labels by consecutive labels.
//
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
c[i+j*m] = q [ p [ c[i+j*m] ] ];
}
}
delete [] p;
delete [] q;
return component_num;
}
//****************************************************************************80
int *i4mat_data_read ( string input_filename, int m, int n )
//****************************************************************************80
//
// Purpose:
//
// I4MAT_DATA_READ reads data from an I4MAT file.
//
// Discussion:
//
// An I4MAT is an array of I4's.
//
// The file is assumed to contain one record per line.
//
// Records beginning with '#' are comments, and are ignored.
// Blank lines are also ignored.
//
// Each line that is not ignored is assumed to contain exactly (or at least)
// M real numbers, representing the coordinates of a point.
//
// There are assumed to be exactly (or at least) N such records.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 23 February 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, string INPUT_FILENAME, the name of the input file.
//
// Input, int M, the number of spatial dimensions.
//
// Input, int N, the number of points. The program
// will stop reading data once N values have been read.
//
// Output, int I4MAT_DATA_READ[M*N], the data.
//
{
bool error;
ifstream input;
int i;
int j;
string line;
int *table;
int *x;
input.open ( input_filename.c_str ( ) );
if ( !input )
{
cerr << "\n";
cerr << "I4MAT_DATA_READ - Fatal error!\n";
cerr << " Could not open the input file: \"" << input_filename << "\"\n";
exit ( 1 );
}
table = new int[m*n];
x = new int[m];
j = 0;
while ( j < n )
{
getline ( input, line );
if ( input.eof ( ) )
{
break;
}
if ( line[0] == '#' || s_len_trim ( line ) == 0 )
{
continue;
}
error = s_to_i4vec ( line, m, x );
if ( error )
{
continue;
}
for ( i = 0; i < m; i++ )
{
table[i+j*m] = x[i];
}
j = j + 1;
}
input.close ( );
delete [] x;
return table;
}
//****************************************************************************80
void i4mat_header_read ( string input_filename, int *m, int *n )
//****************************************************************************80
//
// Purpose:
//
// I4MAT_HEADER_READ reads the header from an I4MAT file.
//
// Discussion:
//
// An I4MAT is an array of I4's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 23 February 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, string INPUT_FILENAME, the name of the input file.
//
// Output, int *M, the number of spatial dimensions.
//
// Output, int *N, the number of points
//
{
*m = file_column_count ( input_filename );
if ( *m <= 0 )
{
cerr << "\n";
cerr << "I4MAT_HEADER_READ - Fatal error!\n";
cerr << " FILE_COLUMN_COUNT failed.\n";
exit ( 1 );
}
*n = file_row_count ( input_filename );
if ( *n <= 0 )
{
cerr << "\n";
cerr << "I4MAT_HEADER_READ - Fatal error!\n";
cerr << " FILE_ROW_COUNT failed.\n";
exit ( 1 );
}
return;
}
//****************************************************************************80
int i4vec_components ( int n, int a[], int c[] )
//****************************************************************************80
//
// Purpose:
//
// I4VEC_COMPONENTS assigns contiguous nonzero pixels to a common component.
//
// Discussion:
//
// This calculation is trivial compared to the 2D problem, and is included
// primarily for comparison.
//
// On input, the A array contains values of 0 or 1.
//
// The 0 pixels are to be ignored. The 1 pixels are to be grouped
// into connected components.
//
// The pixel A(I) is "connected" to the pixels A(I-1) and A(I+1).
//
// On output, COMPONENT_NUM reports the number of components of nonzero
// data, and the array C contains the component assignment for
// each nonzero pixel, and is 0 for zero pixels.
//
// Picture:
//
// Input A:
//
// 0 0 1 2 4 0 0 4 0 0 0 8 9 9 1 2 3 0 0 5 0 1 6 0 0 0 4 0
//
// Output:
//
// COMPONENT_NUM = 6
//
// C:
//
// 0 0 1 1 1 0 0 2 0 0 0 3 3 3 3 3 3 0 0 4 0 5 5 0 0 0 6 0
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 March 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the vector.
//
// Input, int A(N), the pixel array.
//
// Output, int C[N], the component array.
//
// Output, int I4VEC_COMPONENTS, the number of components
// of nonzero data.
//
{
int component_num;
int j;
int west;
//
// Initialization.
//
for ( j = 0; j < n; j++ )
{
c[j] = 0;
}
component_num = 0;
//
// "Read" the array one pixel at a time. If a (nonzero) pixel has a west
// neighbor with a label, the current pixel inherits it. Otherwise, we have
// begun a new component.
//
west = 0;
for ( j = 0; j < n; j++ )
{
if ( a[j] != 0 )
{
if ( west == 0 )
{
component_num = component_num + 1;
}
c[j] = component_num;
}
west = c[j];
}
return component_num;
}
//****************************************************************************80
int s_len_trim ( string s )
//****************************************************************************80
//
// Purpose:
//
// S_LEN_TRIM returns the length of a string to the last nonblank.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 05 July 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, string S, a string.
//
// Output, int S_LEN_TRIM, the length of the string to the last nonblank.
// If S_LEN_TRIM is 0, then the string is entirely blank.
//
{
int n;
n = s.length ( );
while ( 0 < n )
{
if ( s[n-1] != ' ' )
{
return n;
}
n = n - 1;
}
return n;
}
//****************************************************************************80
int s_to_i4 ( string s, int *last, bool *error )
//****************************************************************************80
//
// Purpose:
//
// S_TO_I4 reads an I4 from a string.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 05 July 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, string S, a string to be examined.
//
// Output, int *LAST, the last character of S used to make IVAL.
//
// Output, bool *ERROR is TRUE if an error occurred.
//
// Output, int *S_TO_I4, the integer value read from the string.
// If the string is blank, then IVAL will be returned 0.
//
{
char c;
int i;
int isgn;
int istate;
int ival;
*error = false;
istate = 0;
isgn = 1;
i = 0;
ival = 0;
for ( ; ; )
{
c = s[i];
i = i + 1;
//
// Haven't read anything.
//
if ( istate == 0 )
{
if ( c == ' ' )
{
}
else if ( c == '-' )
{
istate = 1;
isgn = -1;
}
else if ( c == '+' )
{
istate = 1;
isgn = + 1;
}
else if ( '0' <= c && c <= '9' )
{
istate = 2;
ival = c - '0';
}
else
{
*error = true;
return ival;
}
}
//
// Have read the sign, expecting digits.
//
else if ( istate == 1 )
{
if ( c == ' ' )
{
}
else if ( '0' <= c && c <= '9' )
{
istate = 2;
ival = c - '0';
}
else
{
*error = true;
return ival;
}
}
//
// Have read at least one digit, expecting more.
//
else if ( istate == 2 )
{
if ( '0' <= c && c <= '9' )
{
ival = 10 * (ival) + c - '0';
}
else
{
ival = isgn * ival;
*last = i - 1;
return ival;
}
}
}
//
// If we read all the characters in the string, see if we're OK.
//
if ( istate == 2 )
{
ival = isgn * ival;
*last = s_len_trim ( s );
}
else
{
*error = true;
*last = 0;
}
return ival;
}
//****************************************************************************80
bool s_to_i4vec ( string s, int n, int ivec[] )
//****************************************************************************80
//
// Purpose:
//
// S_TO_I4VEC reads an I4VEC from a string.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 05 July 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, string S, the string to be read.
//
// Input, int N, the number of values expected.
//
// Output, int IVEC[N], the values read from the string.
//
// Output, bool S_TO_I4VEC, is TRUE if an error occurred.
//
{
int begin;
bool error;
int i;
int lchar;
int length;
begin = 0;
length = s.length ( );
error = 0;
for ( i = 0; i < n; i++ )
{
ivec[i] = s_to_i4 ( s.substr(begin,length), &lchar, &error );
if ( error )
{
return error;
}
begin = begin + lchar;
length = length - lchar;
}
return error;
}
//****************************************************************************80
int s_word_count ( string s )
//****************************************************************************80
//
// Purpose:
//
// S_WORD_COUNT counts the number of "words" in a string.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 05 July 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, string S, the string to be examined.
//
// Output, int S_WORD_COUNT, the number of "words" in the string.
// Words are presumed to be separated by one or more blanks.
//
{
bool blank;
int char_count;
int i;
int word_count;
word_count = 0;
blank = true;
char_count = s.length ( );
for ( i = 0; i < char_count; i++ )
{
if ( isspace ( s[i] ) )
{
blank = true;
}
else if ( blank )
{
word_count = word_count + 1;
blank = false;
}
}
return word_count;
}
//****************************************************************************80
void timestamp ( )
//****************************************************************************80
//
// Purpose:
//
// TIMESTAMP prints the current YMDHMS date as a time stamp.
//
// Example:
//
// 31 May 2001 09:45:54 AM
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 08 July 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// None
//
{
# define TIME_SIZE 40
static char time_buffer[TIME_SIZE];
const struct std::tm *tm_ptr;
//size_t len;
std::time_t now;
now = std::time ( NULL );
tm_ptr = std::localtime ( &now );
//len = std::strftime ( time_buffer, TIME_SIZE, "%d %B %Y %I:%M:%S %p", tm_ptr );
std::cout << time_buffer << "\n";
return;
# undef TIME_SIZE
}
| 19.162687 | 83 | 0.467404 |
47ea935abdcb6cafecbcd071877e2c7547f5d0c5 | 17,028 | cpp | C++ | partman/loader.cpp | XplosiveLugnut/3d-pinball-space-cadet | 5bf9b86f379a3d28321a4d29df03965ff1245fad | [
"MIT"
] | 1 | 2021-04-23T12:50:21.000Z | 2021-04-23T12:50:21.000Z | partman/loader.cpp | XplosiveLugnut/3d-pinball-space-cadet | 5bf9b86f379a3d28321a4d29df03965ff1245fad | [
"MIT"
] | null | null | null | partman/loader.cpp | XplosiveLugnut/3d-pinball-space-cadet | 5bf9b86f379a3d28321a4d29df03965ff1245fad | [
"MIT"
] | null | null | null | //
// Created by neo on 2019-08-15.
//
#include "../pinball.h"
//----- (01008F7A) --------------------------------------------------------
signed int loader_error(int a1, int a2)
{
int v2; // eax
const CHAR *v3; // esi
const CHAR *v4; // edi
int v5; // edx
int v6; // ecx
v2 = loader_errors[0];
v3 = 0;
v4 = 0;
v5 = 0;
if ( loader_errors[0] < 0 )
goto LABEL_13;
v6 = 0;
do
{
if ( a1 == v2 )
v3 = off_10235FC[v6];
if ( a2 == v2 )
v4 = off_10235FC[v6];
v6 = 2 * ++v5;
v2 = loader_errors[2 * v5];
}
while ( v2 >= 0 );
if ( !v3 )
LABEL_13:
v3 = off_10235FC[2 * v5];
MessageBoxA(0, v3, v4, 0x2000u);
return -1;
}
// 10235F8: using guessed type int loader_errors[];
//----- (01008FE0) --------------------------------------------------------
DWORD *loader_default_vsi(DWORD *a1)
{
DWORD *result; // eax
result = a1;
a1[13] = 0;
a1[5] = 1369940824;
a1[12] = 0;
*a1 = 1064514355;
a1[1] = 1058642330;
a1[2] = 0;
a1[4] = 0;
a1[16] = 0;
a1[17] = 0;
a1[15] = 0;
a1[14] = 0;
return result;
}
//----- (0100901F) --------------------------------------------------------
signed int loader_get_sound_id(int a1)
{
signed int v1; // dx
signed int v2; // eax
signed int result; // eax
signed int v4; // edi
int v5; // esi
int v6; // eax
WORD *v7; // eax
const CHAR *lpName; // ST18_4
HFILE hFile; // ST1C_4
int v10; // [esp+10h] [ebp+8h]
v1 = 1;
if ( sound_count <= 1 )
{
LABEL_5:
loader_error(25, 26);
result = -1;
}
else
{
v2 = 1;
while ( dword_1027C24[5 * v2] != a1 )
{
v2 = ++v1;
if ( v1 >= sound_count )
goto LABEL_5;
}
v4 = v1;
v5 = 5 * v1;
if ( !dword_1027C28[v5] && !sound_list[v5] )
{
v6 = dword_1027C24[v5];
*(float *)&algn_1027C2C[20 * v1] = 0.0;
v10 = v6;
if ( v6 > 0 && !play_midi_music )
{
v7 = (WORD *)partman_field(loader_table, v6, 0);
if ( v7 )
{
if ( *v7 == 202 )
{
lpName = (const CHAR *)partman_field(loader_table, v10, 9);
hFile = _lopen(lpName, 0);
*(float *)(v5 * 4 + 16940076) = (double)_llseek(hFile, 0, 2) * 0.0000909090909090909;
_lclose(hFile);
sound_list[v5] = (int)Sound_LoadWaveFile(lpName);
}
}
}
}
++dword_1027C28[v5];
result = v4;
}
return result;
}
// 10236D8: using guessed type int sound_count;
// 102556C: using guessed type int play_midi_music;
// 1027C20: using guessed type int sound_list[];
// 1027C24: using guessed type int dword_1027C24[];
// 1027C28: using guessed type int dword_1027C28[];
//----- (0100911D) --------------------------------------------------------
void loader_unload()
{
signed int v0; // esi
LPCVOID *v1; // edi
v0 = 1;
if ( sound_count > 1 )
{
v1 = (LPCVOID *)&unk_1027C34;
do
{
Sound_FreeSound(*v1);
++v0;
v1 += 5;
}
while ( v0 < sound_count );
}
if ( dword_1027C30[5 * v0] )
memoryfree(dword_1027C30[5 * v0]);
sound_count = 1;
}
// 10236D8: using guessed type int sound_count;
// 1027C30: using guessed type int dword_1027C30[];
//----- (0100916A) --------------------------------------------------------
int loader_loadfrom(WORD *a1)
{
WORD *v1; // edx
int v2; // di
WORD *v3; // eax
int result; // eax
int v5; // ecx
v1 = a1;
v2 = 0;
loader_table = (int)a1;
if ( *a1 <= 0 )
{
result = sound_count;
}
else
{
do
{
v3 = (WORD *)partman_field((int)v1, v2, 0);
v1 = (WORD *)loader_table;
if ( v3 && *v3 == 202 )
{
result = sound_count;
sound_record_table = loader_table;
if ( sound_count < 65 )
{
v5 = 5 * sound_count;
sound_list[v5] = 0;
++result;
dword_1027C24[v5] = v2;
sound_count = result;
}
}
else
{
result = sound_count;
}
++v2;
}
while ( v2 < *v1 );
}
loader_sound_count = result;
return result;
}
// 10236D8: using guessed type int sound_count;
// 1027C10: using guessed type int sound_record_table;
// 1027C20: using guessed type int sound_list[];
// 1027C24: using guessed type int dword_1027C24[];
// 1028134: using guessed type int loader_sound_count;
//----- (010091EB) --------------------------------------------------------
int loader_query_handle(const char * lpString)
{
return partman_record_labeled(loader_table, lpString);
}
//----- (01009207) --------------------------------------------------------
signed int loader_query_visual_states(int a1)
{
signed int result; // eax
WORD *v2; // eax
if ( a1 < 0 )
return loader_error(0, 17);
v2 = (WORD *)partman_field(loader_table, a1, 10);
if ( v2 && *v2 == 100 )
result = (signed int)v2[1];
else
result = 1;
return result;
}
//----- (01009249) --------------------------------------------------------
signed int loader_material(int a1, DWORD *a2)
{
int v2; // edi
WORD *v4; // eax
float *v5; // esi
unsigned int v6; // ebx
double v7; // st7
DWORD *v8; // esi
double v9; // st7
signed __int64 v10; // rax
int v11; // [esp+1Ch] [ebp+8h]
int v12; // [esp+1Ch] [ebp+8h]
v2 = a1;
if ( a1 < 0 )
return loader_error(0, 21);
v4 = (WORD *)partman_field(loader_table, a1, 0);
if ( !v4 )
return loader_error(1, 21);
if ( *v4 == 300 )
{
v5 = (float *)partman_field(loader_table, a1, 11);
if ( !v5 )
return loader_error(11, 21);
v11 = 0;
v6 = (unsigned int)partman_field_size(loader_table, v2, 11) >> 2;
if ( (signed int)v6 <= 0 )
return 0;
while ( 1 )
{
v7 = *v5;
v8 = v5 + 1;
v12 = v11 + 1;
v9 = _floor(v7);
switch ( (signed int)(signed __int64)v9 )
{
case 301:
*a2 = *v8;
break;
case 302:
a2[1] = *v8;
break;
case 304:
v10 = (signed __int64)_floor(*(float *)v8);
a2[4] = loader_get_sound_id((signed int)v10);
break;
default:
return loader_error(9, 21);
}
v5 = (float *)(v8 + 1);
v11 = v12 + 1;
if ( (signed int)v11 >= (signed int)v6 )
return 0;
}
}
return loader_error(3, 21);
}
//----- (01009349) --------------------------------------------------------
signed int loader_kicker(int a1, DWORD *a2)
{
WORD *v3; // eax
float *v4; // esi
double v5; // st7
DWORD *v6; // esi
double v7; // st7
signed __int64 v8; // rax
int v9; // eax
DWORD *v10; // esi
int v11; // eax
int v12; // eax
unsigned int v13; // [esp+14h] [ebp-4h]
int v14; // [esp+20h] [ebp+8h]
int v15; // [esp+20h] [ebp+8h]
if ( a1 < 0 )
return loader_error(0, 20);
v3 = (WORD *)partman_field(loader_table, a1, 0);
if ( !v3 )
return loader_error(1, 20);
if ( *v3 != 400 )
return loader_error(4, 20);
v4 = (float *)partman_field(loader_table, a1, 11);
if ( !v4 )
return loader_error(11, 20);
v13 = (unsigned int)partman_field_size(loader_table, a1, 11) >> 2;
v14 = 0;
if ( (signed int)v13 <= 0 )
return 0;
while ( 1 )
{
v5 = *v4;
v6 = v4 + 1;
v15 = v14 + 1;
v7 = _floor(v5);
switch ( (signed int)(signed __int64)v7 )
{
case 401:
*a2 = *v6;
goto LABEL_24;
case 402:
a2[1] = *v6;
goto LABEL_24;
case 403:
a2[2] = *v6;
goto LABEL_24;
}
if ( (signed int)(signed __int64)v7 != 404 )
break;
v9 = *v6;
v10 = v6 + 1;
a2[3] = v9;
v11 = *v10;
++v10;
a2[4] = v11;
v12 = *v10;
v4 = (float *)(v10 + 1);
v14 = v15 + 3;
a2[5] = v12;
LABEL_25:
if ( (signed int)v14 >= (signed int)v13 )
return 0;
}
if ( (signed int)(signed __int64)v7 == 405 )
{
a2[6] = *v6;
goto LABEL_24;
}
if ( (signed int)(signed __int64)v7 == 406 )
{
v8 = (signed __int64)_floor(*(float *)v6);
a2[7] = loader_get_sound_id((signed int)v8);
LABEL_24:
v4 = (float *)(v6 + 1);
v14 = v15 + 1;
goto LABEL_25;
}
return loader_error(10, 20);
}
//----- (01009486) --------------------------------------------------------
signed int loader_state_id(int a1, signed int a2)
{
int v2; // esi
int v3; // di
WORD *v5; // eax
WORD *v6; // eax
v2 = a1;
v3 = loader_query_visual_states(a1);
if ( v3 <= 0 )
return loader_error(12, 24);
v5 = (WORD *)partman_field(loader_table, a1, 0);
if ( !v5 )
return loader_error(1, 24);
if ( *v5 != 200 )
return loader_error(5, 24);
if ( a2 > v3 )
return loader_error(12, 24);
if ( !a2 )
return v2;
v2 = a2 + a1;
v6 = (WORD *)partman_field(loader_table, a2 + a1, 0);
if ( !v6 )
return loader_error(1, 24);
if ( *v6 == 201 )
return v2;
return loader_error(6, 24);
}
//----- (0100950A) --------------------------------------------------------
signed int loader_query_visual(int a1, signed int a2, DWORD *a3)
{
DWORD *v3; // edi
int v5; // eax
int v6; // ebx
int v7; // eax
signed int *v8; // esi
unsigned int v9; // eax
int v10; // ebx
signed int v11; // ecx
_BYTE *v12; // esi
int v13; // ebx
int v14; // ecx
int v15; // ecx
int v16; // ecx
int v17; // ecx
int v18; // ecx
int v19; // ecx
float *v20; // eax
float *v21; // esi
signed __int64 v22; // rax
int v23; // esi
int v24; // [esp+1Ch] [ebp+8h]
unsigned int v25; // [esp+24h] [ebp+10h]
v3 = a3;
loader_default_vsi(a3);
if ( a1 < 0 )
return loader_error(0, 18);
v5 = loader_state_id(a1, a2);
v6 = v5;
v24 = v5;
if ( v5 < 0 )
return loader_error(16, 18);
a3[16] = partman_field(loader_table, v5, 1);
v7 = partman_field(loader_table, v6, 12);
a3[17] = v7;
if ( v7 )
{
*(DWORD *)(v7 + 6) = v7 + 14;
*(DWORD *)(a3[17] + 10) = *(DWORD *)(a3[17] + 6);
}
v8 = (signed int *)partman_field(loader_table, v6, 10);
if ( v8 )
{
v9 = partman_field_size(loader_table, v6, 10);
v10 = 0;
v25 = v9 >> 1;
if ( (signed int)(v9 >> 1) > 0 )
{
while ( 1 )
{
v11 = *v8;
v12 = v8 + 1;
v13 = v10 + 1;
if ( v11 <= 406 )
{
if ( v11 == 406 )
{
v3[12] = loader_get_sound_id(*(signed int *)v12);
}
else
{
v14 = v11 - 100;
if ( v14 )
{
v15 = v14 - 200;
if ( v15 )
{
v16 = v15 - 4;
if ( v16 )
{
if ( v16 != 96 )
return loader_error(9, 18);
if ( loader_kicker(*(signed int *)v12, v3 + 5) )
return loader_error(14, 18);
}
else
{
v3[4] = loader_get_sound_id(*(signed int *)v12);
}
}
else if ( loader_material(*(signed int *)v12, v3) )
{
return loader_error(15, 18);
}
}
else if ( a2 )
{
return loader_error(7, 18);
}
}
goto LABEL_32;
}
v17 = v11 - 602;
if ( !v17 )
{
v3[13] |= 1 << *v12;
goto LABEL_32;
}
v18 = v17 - 498;
if ( !v18 )
break;
v19 = v18 - 1;
if ( !v19 )
{
v3[15] = loader_get_sound_id(*(signed int *)v12);
LABEL_32:
v8 = (signed int *)(v12 + 2);
v10 = v13 + 1;
goto LABEL_33;
}
if ( v19 != 399 )
return loader_error(9, 18);
v8 = (signed int *)(v12 + 16);
v10 = v13 + 8;
LABEL_33:
if ( (signed int)v10 >= (signed int)v25 )
goto LABEL_34;
}
v3[14] = loader_get_sound_id(*(signed int *)v12);
goto LABEL_32;
}
}
LABEL_34:
if ( !v3[13] )
v3[13] = 1;
v20 = (float *)partman_field(loader_table, v24, 11);
if ( !v20 )
return 0;
v21 = v20 + 1;
if ( *v20 != 600.0 )
return 0;
v3[2] = (signed int)((unsigned int)partman_field_size(loader_table, v24, 11) >> 2) / 2 - 2;
v22 = (signed __int64)(_floor(*v21) - 1.0);
v23 = (int)(v21 + 1);
if ( !(WORD)v22 )
{
v3[2] = 1;
LABEL_40:
v3[3] = v23;
return 0;
}
if ( (WORD)v22 == 1 )
{
v3[2] = 2;
goto LABEL_40;
}
if ( (signed int)v22 == v3[2] )
goto LABEL_40;
return loader_error(8, 18);
}
//----- (0100975D) --------------------------------------------------------
int loader_query_name(int a1)
{
if ( a1 >= 0 )
return partman_field(loader_table, a1, 3);
loader_error(0, 19);
return 0;
}
//----- (0100978E) --------------------------------------------------------
int loader_query_float_attribute(int a1, signed int a2, int a3)
{
int v3; // bx
int result; // eax
int v5; // edi
float *v6; // eax
float *v7; // esi
v3 = 0;
if ( a1 >= 0 )
{
v5 = loader_state_id(a1, a2);
if ( v5 >= 0 )
{
while ( 1 )
{
v6 = (float *)partman_field_nth(loader_table, v5, 11, v3);
v7 = v6;
if ( !v6 )
break;
if ( (signed int)(signed __int64)_floor(*v6) == a3 )
return (int)(v7 + 1);
++v3;
}
loader_error(13, 22);
result = 0;
}
else
{
loader_error(16, 22);
result = 0;
}
}
else
{
loader_error(0, 22);
result = 0;
}
return result;
}
//----- (0100981A) --------------------------------------------------------
int loader_query_iattribute(int a1, int a2, DWORD *a3)
{
int v3; // di
int result; // eax
signed int *v5; // eax
signed int *v6; // esi
v3 = 0;
if ( a1 >= 0 )
{
while ( 1 )
{
v5 = (signed int *)partman_field_nth(loader_table, a1, 10, v3);
v6 = v5;
if ( !v5 )
break;
if ( *v5 == a2 )
{
*a3 = partman_field_size(loader_table, a1, 10) / 2 - 1;
return (int)(v6 + 1);
}
++v3;
}
loader_error(2, 23);
*a3 = 0;
result = 0;
}
else
{
loader_error(0, 22);
result = 0;
}
return result;
}
//----- (01009895) --------------------------------------------------------
double loader_play_sound(int a1)
{
if ( a1 <= 0 )
return 0.0;
Sound_PlaySound(sound_list[5 * a1], 0, 7, 5u, 0);
return *(float *)&algn_1027C2C[20 * a1];
}
// 1027C20: using guessed type int sound_list[];
| 26.4 | 109 | 0.401926 |
47eadaeebabcd54b782d7438128de912c2bfdfbd | 3,217 | hh | C++ | src/BGL/BGLLine.hh | revarbat/Mandoline | 1aafd7e6702ef740bcac6ab8c8c43282a104c60a | [
"BSD-2-Clause-FreeBSD"
] | 17 | 2015-01-07T10:32:06.000Z | 2021-07-06T11:00:38.000Z | src/BGL/BGLLine.hh | revarbat/Mandoline | 1aafd7e6702ef740bcac6ab8c8c43282a104c60a | [
"BSD-2-Clause-FreeBSD"
] | 2 | 2017-08-17T17:44:42.000Z | 2018-06-14T23:39:04.000Z | src/BGL/BGLLine.hh | revarbat/Mandoline | 1aafd7e6702ef740bcac6ab8c8c43282a104c60a | [
"BSD-2-Clause-FreeBSD"
] | 3 | 2015-01-07T10:32:06.000Z | 2019-03-22T16:56:51.000Z | //
// BGLLine.hh
// Part of the Belfry Geometry Library
//
// Created by GM on 10/13/10.
// Copyright 2010 Belfry Software. All rights reserved.
//
#ifndef BGL_LINE_H
#define BGL_LINE_H
#include <math.h>
#include <iostream>
#include <list>
#include "BGLCommon.hh"
#include "BGLAffine.hh"
#include "BGLIntersection.hh"
#include "BGLPoint.hh"
using namespace std;
namespace BGL {
class Line {
public:
// Member variables
Point startPt;
Point endPt;
int flags;
double temperature;
double extrusionWidth;
// Constructors
Line() :
startPt(),
endPt(),
flags(0),
temperature(0),
extrusionWidth(0)
{
}
Line(const Point& p1, const Point& p2) :
startPt(p1),
endPt(p2),
flags(0),
temperature(0),
extrusionWidth(0)
{
}
Line(const Line& ln) :
startPt(ln.startPt),
endPt(ln.endPt),
flags(ln.flags),
temperature(ln.temperature),
extrusionWidth(ln.extrusionWidth)
{
}
// Assignment operator
Line& operator=(const Line &rhs);
// Compound assignment operators
Line& operator+=(const Point &rhs);
Line& operator-=(const Point &rhs);
Line& operator*=(double rhs);
Line& operator*=(const Point &rhs);
Line& operator/=(double rhs);
Line& operator/=(const Point &rhs);
// Binary arithmetic operators
const Line operator+(const Point &rhs) const;
const Line operator-(const Point &rhs) const;
const Line operator*(double rhs) const;
const Line operator*(const Point &rhs) const;
const Line operator/(double rhs) const;
const Line operator/(const Point &rhs) const;
// Comparison operators
bool operator==(const Line &rhs) const;
bool operator!=(const Line &rhs) const;
bool hasEndPoint(const Point& pt) const;
// Transformations
Line& scale(double scale);
Line& scale(const Point& vect);
Line& scaleAroundPoint(const Point& center, double scale);
Line& scaleAroundPoint(const Point& center, const Point& vect);
Line& rotate(double angle);
void quantize(double quanta);
void quantize();
// Calculations
double length() const;
double angle() const;
double angleDelta(const Line& ln) const;
bool isLeftOf(const Point &pt) const;
bool isLeftOfNormal(const Point &pt) const;
// Misc
Line& reverse();
Line& reverseIfRightOfNormal(const Point &pt);
bool isLinearWith(const Point& pt) const;
bool hasInBounds(const Point &pt) const;
bool contains(const Point &pt) const;
Point closestSegmentPointTo(const Point &pt) const;
Point closestExtendedLinePointTo(const Point &pt) const;
double minimumSegmentDistanceFromPoint(const Point &pt) const;
double minimumExtendedLineDistanceFromPoint(const Point &pt) const;
Intersection intersectionWithSegment(const Line &ln) const;
Intersection intersectionWithExtendedLine(const Line &ln) const;
Line& leftOffset(double offsetby);
// Friend functions
friend ostream& operator <<(ostream &os,const Line &pt);
};
typedef list<Line> Lines;
}
#endif
// vim: set ts=4 sw=4 nowrap expandtab: settings
| 23.654412 | 71 | 0.660242 |
47ed68f919d084e86deeb009c4dcdffcbf520811 | 50,330 | cpp | C++ | includes/mfbt/tests/TestTextUtils.cpp | gregtatum/spec-cpp | ebd40fa119a302f82ab10a2b8ddd52671f92e2ef | [
"MIT"
] | 5 | 2018-02-01T18:25:35.000Z | 2018-02-12T14:09:22.000Z | includes/mfbt/tests/TestTextUtils.cpp | gregtatum/spec-cpp | ebd40fa119a302f82ab10a2b8ddd52671f92e2ef | [
"MIT"
] | null | null | null | includes/mfbt/tests/TestTextUtils.cpp | gregtatum/spec-cpp | ebd40fa119a302f82ab10a2b8ddd52671f92e2ef | [
"MIT"
] | 1 | 2019-03-15T06:01:40.000Z | 2019-03-15T06:01:40.000Z | /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "./Assertions.h"
#include "./TextUtils.h"
using mozilla::AsciiAlphanumericToNumber;
using mozilla::IsAscii;
using mozilla::IsAsciiAlpha;
using mozilla::IsAsciiAlphanumeric;
using mozilla::IsAsciiDigit;
using mozilla::IsAsciiLowercaseAlpha;
using mozilla::IsAsciiNullTerminated;
using mozilla::IsAsciiUppercaseAlpha;
static void TestIsAscii() {
// char
static_assert(!IsAscii(char(-1)), "char(-1) isn't ASCII");
static_assert(IsAscii('\0'), "nul is ASCII");
static_assert(IsAscii('A'), "'A' is ASCII");
static_assert(IsAscii('B'), "'B' is ASCII");
static_assert(IsAscii('M'), "'M' is ASCII");
static_assert(IsAscii('Y'), "'Y' is ASCII");
static_assert(IsAscii('Z'), "'Z' is ASCII");
static_assert(IsAscii('['), "'[' is ASCII");
static_assert(IsAscii('`'), "'`' is ASCII");
static_assert(IsAscii('a'), "'a' is ASCII");
static_assert(IsAscii('b'), "'b' is ASCII");
static_assert(IsAscii('m'), "'m' is ASCII");
static_assert(IsAscii('y'), "'y' is ASCII");
static_assert(IsAscii('z'), "'z' is ASCII");
static_assert(IsAscii('{'), "'{' is ASCII");
static_assert(IsAscii('5'), "'5' is ASCII");
static_assert(IsAscii('\x7F'), "'\\x7F' is ASCII");
static_assert(!IsAscii('\x80'), "'\\x80' isn't ASCII");
// char16_t
static_assert(!IsAscii(char16_t(-1)), "char16_t(-1) isn't ASCII");
static_assert(IsAscii(u'\0'), "nul is ASCII");
static_assert(IsAscii(u'A'), "u'A' is ASCII");
static_assert(IsAscii(u'B'), "u'B' is ASCII");
static_assert(IsAscii(u'M'), "u'M' is ASCII");
static_assert(IsAscii(u'Y'), "u'Y' is ASCII");
static_assert(IsAscii(u'Z'), "u'Z' is ASCII");
static_assert(IsAscii(u'['), "u'[' is ASCII");
static_assert(IsAscii(u'`'), "u'`' is ASCII");
static_assert(IsAscii(u'a'), "u'a' is ASCII");
static_assert(IsAscii(u'b'), "u'b' is ASCII");
static_assert(IsAscii(u'm'), "u'm' is ASCII");
static_assert(IsAscii(u'y'), "u'y' is ASCII");
static_assert(IsAscii(u'z'), "u'z' is ASCII");
static_assert(IsAscii(u'{'), "u'{' is ASCII");
static_assert(IsAscii(u'5'), "u'5' is ASCII");
static_assert(IsAscii(u'\x7F'), "u'\\x7F' is ASCII");
static_assert(!IsAscii(u'\x80'), "u'\\x80' isn't ASCII");
// char32_t
static_assert(!IsAscii(char32_t(-1)), "char32_t(-1) isn't ASCII");
static_assert(IsAscii(U'\0'), "nul is ASCII");
static_assert(IsAscii(U'A'), "U'A' is ASCII");
static_assert(IsAscii(U'B'), "U'B' is ASCII");
static_assert(IsAscii(U'M'), "U'M' is ASCII");
static_assert(IsAscii(U'Y'), "U'Y' is ASCII");
static_assert(IsAscii(U'Z'), "U'Z' is ASCII");
static_assert(IsAscii(U'['), "U'[' is ASCII");
static_assert(IsAscii(U'`'), "U'`' is ASCII");
static_assert(IsAscii(U'a'), "U'a' is ASCII");
static_assert(IsAscii(U'b'), "U'b' is ASCII");
static_assert(IsAscii(U'm'), "U'm' is ASCII");
static_assert(IsAscii(U'y'), "U'y' is ASCII");
static_assert(IsAscii(U'z'), "U'z' is ASCII");
static_assert(IsAscii(U'{'), "U'{' is ASCII");
static_assert(IsAscii(U'5'), "U'5' is ASCII");
static_assert(IsAscii(U'\x7F'), "U'\\x7F' is ASCII");
static_assert(!IsAscii(U'\x80'), "U'\\x80' isn't ASCII");
}
static void TestIsAsciiNullTerminated() {
// char
constexpr char allChar[] =
"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\0x0C\x0D\x0E\x0F"
"\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\0x1C\x1D\x1E\x1F"
"\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\0x2C\x2D\x2E\x2F"
"\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\0x3C\x3D\x3E\x3F"
"\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\0x4C\x4D\x4E\x4F"
"\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\0x5C\x5D\x5E\x5F"
"\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\0x6C\x6D\x6E\x6F"
"\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\0x7C\x7D\x7E\x7F";
static_assert(IsAsciiNullTerminated(allChar), "allChar is ASCII");
constexpr char loBadChar[] = "\x80";
static_assert(!IsAsciiNullTerminated(loBadChar), "loBadChar isn't ASCII");
constexpr char hiBadChar[] = "\xFF";
static_assert(!IsAsciiNullTerminated(hiBadChar), "hiBadChar isn't ASCII");
// char16_t
constexpr char16_t allChar16[] =
u"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\0x0C\x0D\x0E\x0F"
"\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\0x1C\x1D\x1E\x1F"
"\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\0x2C\x2D\x2E\x2F"
"\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\0x3C\x3D\x3E\x3F"
"\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\0x4C\x4D\x4E\x4F"
"\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\0x5C\x5D\x5E\x5F"
"\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\0x6C\x6D\x6E\x6F"
"\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\0x7C\x7D\x7E\x7F";
static_assert(IsAsciiNullTerminated(allChar16), "allChar16 is ASCII");
constexpr char16_t loBadChar16[] = u"\x80";
static_assert(!IsAsciiNullTerminated(loBadChar16), "loBadChar16 isn't ASCII");
constexpr char16_t hiBadChar16[] = u"\xFF";
static_assert(!IsAsciiNullTerminated(hiBadChar16), "hiBadChar16 isn't ASCII");
constexpr char16_t highestChar16[] = u"\uFFFF";
static_assert(!IsAsciiNullTerminated(highestChar16),
"highestChar16 isn't ASCII");
// char32_t
constexpr char32_t allChar32[] =
U"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\0x0C\x0D\x0E\x0F"
"\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\0x1C\x1D\x1E\x1F"
"\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\0x2C\x2D\x2E\x2F"
"\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\0x3C\x3D\x3E\x3F"
"\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\0x4C\x4D\x4E\x4F"
"\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\0x5C\x5D\x5E\x5F"
"\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\0x6C\x6D\x6E\x6F"
"\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\0x7C\x7D\x7E\x7F";
static_assert(IsAsciiNullTerminated(allChar32), "allChar32 is ASCII");
constexpr char32_t loBadChar32[] = U"\x80";
static_assert(!IsAsciiNullTerminated(loBadChar32), "loBadChar32 isn't ASCII");
constexpr char32_t hiBadChar32[] = U"\xFF";
static_assert(!IsAsciiNullTerminated(hiBadChar32), "hiBadChar32 isn't ASCII");
constexpr char32_t highestChar32[] = {static_cast<char32_t>(-1), 0};
static_assert(!IsAsciiNullTerminated(highestChar32),
"highestChar32 isn't ASCII");
}
static void TestIsAsciiAlpha() {
// char
static_assert(!IsAsciiAlpha('@'), "'@' isn't ASCII alpha");
static_assert('@' == 0x40, "'@' has value 0x40");
static_assert('A' == 0x41, "'A' has value 0x41");
static_assert(IsAsciiAlpha('A'), "'A' is ASCII alpha");
static_assert(IsAsciiAlpha('B'), "'B' is ASCII alpha");
static_assert(IsAsciiAlpha('M'), "'M' is ASCII alpha");
static_assert(IsAsciiAlpha('Y'), "'Y' is ASCII alpha");
static_assert(IsAsciiAlpha('Z'), "'Z' is ASCII alpha");
static_assert('Z' == 0x5A, "'Z' has value 0x5A");
static_assert('[' == 0x5B, "'[' has value 0x5B");
static_assert(!IsAsciiAlpha('['), "'[' isn't ASCII alpha");
static_assert(!IsAsciiAlpha('`'), "'`' isn't ASCII alpha");
static_assert('`' == 0x60, "'`' has value 0x60");
static_assert('a' == 0x61, "'a' has value 0x61");
static_assert(IsAsciiAlpha('a'), "'a' is ASCII alpha");
static_assert(IsAsciiAlpha('b'), "'b' is ASCII alpha");
static_assert(IsAsciiAlpha('m'), "'m' is ASCII alpha");
static_assert(IsAsciiAlpha('y'), "'y' is ASCII alpha");
static_assert(IsAsciiAlpha('z'), "'z' is ASCII alpha");
static_assert('z' == 0x7A, "'z' has value 0x7A");
static_assert('{' == 0x7B, "'{' has value 0x7B");
static_assert(!IsAsciiAlpha('{'), "'{' isn't ASCII alpha");
static_assert(!IsAsciiAlpha('5'), "'5' isn't ASCII alpha");
// char16_t
static_assert(!IsAsciiAlpha(u'@'), "u'@' isn't ASCII alpha");
static_assert(u'@' == 0x40, "u'@' has value 0x40");
static_assert(u'A' == 0x41, "u'A' has value 0x41");
static_assert(IsAsciiAlpha(u'A'), "u'A' is ASCII alpha");
static_assert(IsAsciiAlpha(u'B'), "u'B' is ASCII alpha");
static_assert(IsAsciiAlpha(u'M'), "u'M' is ASCII alpha");
static_assert(IsAsciiAlpha(u'Y'), "u'Y' is ASCII alpha");
static_assert(IsAsciiAlpha(u'Z'), "u'Z' is ASCII alpha");
static_assert(u'Z' == 0x5A, "u'Z' has value 0x5A");
static_assert(u'[' == 0x5B, "u'[' has value 0x5B");
static_assert(!IsAsciiAlpha(u'['), "u'[' isn't ASCII alpha");
static_assert(!IsAsciiAlpha(u'`'), "u'`' isn't ASCII alpha");
static_assert(u'`' == 0x60, "u'`' has value 0x60");
static_assert(u'a' == 0x61, "u'a' has value 0x61");
static_assert(IsAsciiAlpha(u'a'), "u'a' is ASCII alpha");
static_assert(IsAsciiAlpha(u'b'), "u'b' is ASCII alpha");
static_assert(IsAsciiAlpha(u'm'), "u'm' is ASCII alpha");
static_assert(IsAsciiAlpha(u'y'), "u'y' is ASCII alpha");
static_assert(IsAsciiAlpha(u'z'), "u'z' is ASCII alpha");
static_assert(u'z' == 0x7A, "u'z' has value 0x7A");
static_assert(u'{' == 0x7B, "u'{' has value 0x7B");
static_assert(!IsAsciiAlpha(u'{'), "u'{' isn't ASCII alpha");
static_assert(!IsAsciiAlpha(u'5'), "u'5' isn't ASCII alpha");
// char32_t
static_assert(!IsAsciiAlpha(U'@'), "U'@' isn't ASCII alpha");
static_assert(U'@' == 0x40, "U'@' has value 0x40");
static_assert(U'A' == 0x41, "U'A' has value 0x41");
static_assert(IsAsciiAlpha(U'A'), "U'A' is ASCII alpha");
static_assert(IsAsciiAlpha(U'B'), "U'B' is ASCII alpha");
static_assert(IsAsciiAlpha(U'M'), "U'M' is ASCII alpha");
static_assert(IsAsciiAlpha(U'Y'), "U'Y' is ASCII alpha");
static_assert(IsAsciiAlpha(U'Z'), "U'Z' is ASCII alpha");
static_assert(U'Z' == 0x5A, "U'Z' has value 0x5A");
static_assert(U'[' == 0x5B, "U'[' has value 0x5B");
static_assert(!IsAsciiAlpha(U'['), "U'[' isn't ASCII alpha");
static_assert(!IsAsciiAlpha(U'`'), "U'`' isn't ASCII alpha");
static_assert(U'`' == 0x60, "U'`' has value 0x60");
static_assert(U'a' == 0x61, "U'a' has value 0x61");
static_assert(IsAsciiAlpha(U'a'), "U'a' is ASCII alpha");
static_assert(IsAsciiAlpha(U'b'), "U'b' is ASCII alpha");
static_assert(IsAsciiAlpha(U'm'), "U'm' is ASCII alpha");
static_assert(IsAsciiAlpha(U'y'), "U'y' is ASCII alpha");
static_assert(IsAsciiAlpha(U'z'), "U'z' is ASCII alpha");
static_assert(U'z' == 0x7A, "U'z' has value 0x7A");
static_assert(U'{' == 0x7B, "U'{' has value 0x7B");
static_assert(!IsAsciiAlpha(U'{'), "U'{' isn't ASCII alpha");
static_assert(!IsAsciiAlpha(U'5'), "U'5' isn't ASCII alpha");
}
static void TestIsAsciiUppercaseAlpha() {
// char
static_assert(!IsAsciiUppercaseAlpha('@'), "'@' isn't ASCII alpha uppercase");
static_assert('@' == 0x40, "'@' has value 0x40");
static_assert('A' == 0x41, "'A' has value 0x41");
static_assert(IsAsciiUppercaseAlpha('A'), "'A' is ASCII alpha uppercase");
static_assert(IsAsciiUppercaseAlpha('B'), "'B' is ASCII alpha uppercase");
static_assert(IsAsciiUppercaseAlpha('M'), "'M' is ASCII alpha uppercase");
static_assert(IsAsciiUppercaseAlpha('Y'), "'Y' is ASCII alpha uppercase");
static_assert(IsAsciiUppercaseAlpha('Z'), "'Z' is ASCII alpha uppercase");
static_assert('Z' == 0x5A, "'Z' has value 0x5A");
static_assert('[' == 0x5B, "'[' has value 0x5B");
static_assert(!IsAsciiUppercaseAlpha('['), "'[' isn't ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha('`'), "'`' isn't ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha('a'), "'a' is ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha('b'), "'b' is ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha('m'), "'m' is ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha('y'), "'y' is ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha('z'), "'z' is ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha('{'), "'{' isn't ASCII alpha uppercase");
// char16_t
static_assert(!IsAsciiUppercaseAlpha(u'@'),
"u'@' isn't ASCII alpha uppercase");
static_assert(u'@' == 0x40, "u'@' has value 0x40");
static_assert(u'A' == 0x41, "u'A' has value 0x41");
static_assert(IsAsciiUppercaseAlpha(u'A'), "u'A' is ASCII alpha uppercase");
static_assert(IsAsciiUppercaseAlpha(u'B'), "u'B' is ASCII alpha uppercase");
static_assert(IsAsciiUppercaseAlpha(u'M'), "u'M' is ASCII alpha uppercase");
static_assert(IsAsciiUppercaseAlpha(u'Y'), "u'Y' is ASCII alpha uppercase");
static_assert(IsAsciiUppercaseAlpha(u'Z'), "u'Z' is ASCII alpha uppercase");
static_assert(u'Z' == 0x5A, "u'Z' has value 0x5A");
static_assert(u'[' == 0x5B, "u'[' has value 0x5B");
static_assert(!IsAsciiUppercaseAlpha(u'['),
"u'[' isn't ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha(u'`'),
"u'`' isn't ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha(u'a'), "u'a' is ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha(u'b'), "u'b' is ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha(u'm'), "u'm' is ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha(u'y'), "u'y' is ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha(u'z'), "u'z' is ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha(u'{'),
"u'{' isn't ASCII alpha uppercase");
// char32_t
static_assert(!IsAsciiUppercaseAlpha(U'@'),
"U'@' isn't ASCII alpha uppercase");
static_assert(U'@' == 0x40, "U'@' has value 0x40");
static_assert(U'A' == 0x41, "U'A' has value 0x41");
static_assert(IsAsciiUppercaseAlpha(U'A'), "U'A' is ASCII alpha uppercase");
static_assert(IsAsciiUppercaseAlpha(U'B'), "U'B' is ASCII alpha uppercase");
static_assert(IsAsciiUppercaseAlpha(U'M'), "U'M' is ASCII alpha uppercase");
static_assert(IsAsciiUppercaseAlpha(U'Y'), "U'Y' is ASCII alpha uppercase");
static_assert(IsAsciiUppercaseAlpha(U'Z'), "U'Z' is ASCII alpha uppercase");
static_assert(U'Z' == 0x5A, "U'Z' has value 0x5A");
static_assert(U'[' == 0x5B, "U'[' has value 0x5B");
static_assert(!IsAsciiUppercaseAlpha(U'['),
"U'[' isn't ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha(U'`'),
"U'`' isn't ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha(U'a'), "U'a' is ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha(U'b'), "U'b' is ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha(U'm'), "U'm' is ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha(U'y'), "U'y' is ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha(U'z'), "U'z' is ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha(U'{'),
"U'{' isn't ASCII alpha uppercase");
}
static void TestIsAsciiLowercaseAlpha() {
// char
static_assert(!IsAsciiLowercaseAlpha('`'), "'`' isn't ASCII alpha lowercase");
static_assert('`' == 0x60, "'`' has value 0x60");
static_assert('a' == 0x61, "'a' has value 0x61");
static_assert(IsAsciiLowercaseAlpha('a'), "'a' is ASCII alpha lowercase");
static_assert(IsAsciiLowercaseAlpha('b'), "'b' is ASCII alpha lowercase");
static_assert(IsAsciiLowercaseAlpha('m'), "'m' is ASCII alpha lowercase");
static_assert(IsAsciiLowercaseAlpha('y'), "'y' is ASCII alpha lowercase");
static_assert(IsAsciiLowercaseAlpha('z'), "'z' is ASCII alpha lowercase");
static_assert('z' == 0x7A, "'z' has value 0x7A");
static_assert('{' == 0x7B, "'{' has value 0x7B");
static_assert(!IsAsciiLowercaseAlpha('{'), "'{' isn't ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha('@'), "'@' isn't ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha('A'), "'A' is ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha('B'), "'B' is ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha('M'), "'M' is ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha('Y'), "'Y' is ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha('Z'), "'Z' is ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha('['), "'[' isn't ASCII alpha lowercase");
// char16_t
static_assert(!IsAsciiLowercaseAlpha(u'`'),
"u'`' isn't ASCII alpha lowercase");
static_assert(u'`' == 0x60, "u'`' has value 0x60");
static_assert(u'a' == 0x61, "u'a' has value 0x61");
static_assert(IsAsciiLowercaseAlpha(u'a'), "u'a' is ASCII alpha lowercase");
static_assert(IsAsciiLowercaseAlpha(u'b'), "u'b' is ASCII alpha lowercase");
static_assert(IsAsciiLowercaseAlpha(u'm'), "u'm' is ASCII alpha lowercase");
static_assert(IsAsciiLowercaseAlpha(u'y'), "u'y' is ASCII alpha lowercase");
static_assert(IsAsciiLowercaseAlpha(u'z'), "u'z' is ASCII alpha lowercase");
static_assert(u'z' == 0x7A, "u'z' has value 0x7A");
static_assert(u'{' == 0x7B, "u'{' has value 0x7B");
static_assert(!IsAsciiLowercaseAlpha(u'{'),
"u'{' isn't ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha(u'@'),
"u'@' isn't ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha(u'A'), "u'A' is ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha(u'B'), "u'B' is ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha(u'M'), "u'M' is ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha(u'Y'), "u'Y' is ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha(u'Z'), "u'Z' is ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha(u'['),
"u'[' isn't ASCII alpha lowercase");
// char32_t
static_assert(!IsAsciiLowercaseAlpha(U'`'),
"U'`' isn't ASCII alpha lowercase");
static_assert(U'`' == 0x60, "U'`' has value 0x60");
static_assert(U'a' == 0x61, "U'a' has value 0x61");
static_assert(IsAsciiLowercaseAlpha(U'a'), "U'a' is ASCII alpha lowercase");
static_assert(IsAsciiLowercaseAlpha(U'b'), "U'b' is ASCII alpha lowercase");
static_assert(IsAsciiLowercaseAlpha(U'm'), "U'm' is ASCII alpha lowercase");
static_assert(IsAsciiLowercaseAlpha(U'y'), "U'y' is ASCII alpha lowercase");
static_assert(IsAsciiLowercaseAlpha(U'z'), "U'z' is ASCII alpha lowercase");
static_assert(U'z' == 0x7A, "U'z' has value 0x7A");
static_assert(U'{' == 0x7B, "U'{' has value 0x7B");
static_assert(!IsAsciiLowercaseAlpha(U'{'),
"U'{' isn't ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha(U'@'),
"U'@' isn't ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha(U'A'), "U'A' is ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha(U'B'), "U'B' is ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha(U'M'), "U'M' is ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha(U'Y'), "U'Y' is ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha(U'Z'), "U'Z' is ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha(U'['),
"U'[' isn't ASCII alpha lowercase");
}
static void TestIsAsciiAlphanumeric() {
// char
static_assert(!IsAsciiAlphanumeric('/'), "'/' isn't ASCII alphanumeric");
static_assert('/' == 0x2F, "'/' has value 0x2F");
static_assert('0' == 0x30, "'0' has value 0x30");
static_assert(IsAsciiAlphanumeric('0'), "'0' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric('1'), "'1' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric('5'), "'5' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric('8'), "'8' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric('9'), "'9' is ASCII alphanumeric");
static_assert('9' == 0x39, "'9' has value 0x39");
static_assert(':' == 0x3A, "':' has value 0x3A");
static_assert(!IsAsciiAlphanumeric(':'), "':' isn't ASCII alphanumeric");
static_assert(!IsAsciiAlphanumeric('@'), "'@' isn't ASCII alphanumeric");
static_assert('@' == 0x40, "'@' has value 0x40");
static_assert('A' == 0x41, "'A' has value 0x41");
static_assert(IsAsciiAlphanumeric('A'), "'A' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric('B'), "'B' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric('M'), "'M' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric('Y'), "'Y' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric('Z'), "'Z' is ASCII alphanumeric");
static_assert('Z' == 0x5A, "'Z' has value 0x5A");
static_assert('[' == 0x5B, "'[' has value 0x5B");
static_assert(!IsAsciiAlphanumeric('['), "'[' isn't ASCII alphanumeric");
static_assert(!IsAsciiAlphanumeric('`'), "'`' isn't ASCII alphanumeric");
static_assert('`' == 0x60, "'`' has value 0x60");
static_assert('a' == 0x61, "'a' has value 0x61");
static_assert(IsAsciiAlphanumeric('a'), "'a' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric('b'), "'b' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric('m'), "'m' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric('y'), "'y' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric('z'), "'z' is ASCII alphanumeric");
static_assert('z' == 0x7A, "'z' has value 0x7A");
static_assert('{' == 0x7B, "'{' has value 0x7B");
static_assert(!IsAsciiAlphanumeric('{'), "'{' isn't ASCII alphanumeric");
// char16_t
static_assert(!IsAsciiAlphanumeric(u'/'), "u'/' isn't ASCII alphanumeric");
static_assert(u'/' == 0x2F, "u'/' has value 0x2F");
static_assert(u'0' == 0x30, "u'0' has value 0x30");
static_assert(IsAsciiAlphanumeric(u'0'), "u'0' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(u'1'), "u'1' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(u'5'), "u'5' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(u'8'), "u'8' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(u'9'), "u'9' is ASCII alphanumeric");
static_assert(u'9' == 0x39, "u'9' has value 0x39");
static_assert(u':' == 0x3A, "u':' has value 0x3A");
static_assert(!IsAsciiAlphanumeric(u':'), "u':' isn't ASCII alphanumeric");
static_assert(!IsAsciiAlphanumeric(u'@'), "u'@' isn't ASCII alphanumeric");
static_assert(u'@' == 0x40, "u'@' has value 0x40");
static_assert(u'A' == 0x41, "u'A' has value 0x41");
static_assert(IsAsciiAlphanumeric(u'A'), "u'A' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(u'B'), "u'B' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(u'M'), "u'M' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(u'Y'), "u'Y' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(u'Z'), "u'Z' is ASCII alphanumeric");
static_assert(u'Z' == 0x5A, "u'Z' has value 0x5A");
static_assert(u'[' == 0x5B, "u'[' has value 0x5B");
static_assert(!IsAsciiAlphanumeric(u'['), "u'[' isn't ASCII alphanumeric");
static_assert(!IsAsciiAlphanumeric(u'`'), "u'`' isn't ASCII alphanumeric");
static_assert(u'`' == 0x60, "u'`' has value 0x60");
static_assert(u'a' == 0x61, "u'a' has value 0x61");
static_assert(IsAsciiAlphanumeric(u'a'), "u'a' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(u'b'), "u'b' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(u'm'), "u'm' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(u'y'), "u'y' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(u'z'), "u'z' is ASCII alphanumeric");
static_assert(u'z' == 0x7A, "u'z' has value 0x7A");
static_assert(u'{' == 0x7B, "u'{' has value 0x7B");
static_assert(!IsAsciiAlphanumeric(u'{'), "u'{' isn't ASCII alphanumeric");
// char32_t
static_assert(!IsAsciiAlphanumeric(U'/'), "U'/' isn't ASCII alphanumeric");
static_assert(U'/' == 0x2F, "U'/' has value 0x2F");
static_assert(U'0' == 0x30, "U'0' has value 0x30");
static_assert(IsAsciiAlphanumeric(U'0'), "U'0' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(U'1'), "U'1' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(U'5'), "U'5' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(U'8'), "U'8' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(U'9'), "U'9' is ASCII alphanumeric");
static_assert(U'9' == 0x39, "U'9' has value 0x39");
static_assert(U':' == 0x3A, "U':' has value 0x3A");
static_assert(!IsAsciiAlphanumeric(U':'), "U':' isn't ASCII alphanumeric");
static_assert(!IsAsciiAlphanumeric(U'@'), "U'@' isn't ASCII alphanumeric");
static_assert(U'@' == 0x40, "U'@' has value 0x40");
static_assert(U'A' == 0x41, "U'A' has value 0x41");
static_assert(IsAsciiAlphanumeric(U'A'), "U'A' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(U'B'), "U'B' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(U'M'), "U'M' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(U'Y'), "U'Y' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(U'Z'), "U'Z' is ASCII alphanumeric");
static_assert(U'Z' == 0x5A, "U'Z' has value 0x5A");
static_assert(U'[' == 0x5B, "U'[' has value 0x5B");
static_assert(!IsAsciiAlphanumeric(U'['), "U'[' isn't ASCII alphanumeric");
static_assert(!IsAsciiAlphanumeric(U'`'), "U'`' isn't ASCII alphanumeric");
static_assert(U'`' == 0x60, "U'`' has value 0x60");
static_assert(U'a' == 0x61, "U'a' has value 0x61");
static_assert(IsAsciiAlphanumeric(U'a'), "U'a' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(U'b'), "U'b' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(U'm'), "U'm' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(U'y'), "U'y' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(U'z'), "U'z' is ASCII alphanumeric");
static_assert(U'z' == 0x7A, "U'z' has value 0x7A");
static_assert(U'{' == 0x7B, "U'{' has value 0x7B");
static_assert(!IsAsciiAlphanumeric(U'{'), "U'{' isn't ASCII alphanumeric");
}
static void TestAsciiAlphanumericToNumber() {
// When AsciiAlphanumericToNumber becomes constexpr, make sure to convert all
// these to just static_assert.
// char
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('0') == 0, "'0' converts to 0");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('1') == 1, "'1' converts to 1");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('2') == 2, "'2' converts to 2");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('3') == 3, "'3' converts to 3");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('4') == 4, "'4' converts to 4");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('5') == 5, "'5' converts to 5");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('6') == 6, "'6' converts to 6");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('7') == 7, "'7' converts to 7");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('8') == 8, "'8' converts to 8");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('9') == 9, "'9' converts to 9");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('A') == 10,
"'A' converts to 10");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('B') == 11,
"'B' converts to 11");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('C') == 12,
"'C' converts to 12");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('D') == 13,
"'D' converts to 13");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('E') == 14,
"'E' converts to 14");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('F') == 15,
"'F' converts to 15");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('G') == 16,
"'G' converts to 16");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('H') == 17,
"'H' converts to 17");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('I') == 18,
"'I' converts to 18");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('J') == 19,
"'J' converts to 19");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('K') == 20,
"'K' converts to 20");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('L') == 21,
"'L' converts to 21");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('M') == 22,
"'M' converts to 22");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('N') == 23,
"'N' converts to 23");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('O') == 24,
"'O' converts to 24");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('P') == 25,
"'P' converts to 25");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('Q') == 26,
"'Q' converts to 26");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('R') == 27,
"'R' converts to 27");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('S') == 28,
"'S' converts to 28");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('T') == 29,
"'T' converts to 29");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('U') == 30,
"'U' converts to 30");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('V') == 31,
"'V' converts to 31");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('W') == 32,
"'W' converts to 32");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('X') == 33,
"'X' converts to 33");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('Y') == 34,
"'Y' converts to 34");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('Z') == 35,
"'Z' converts to 35");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('a') == 10,
"'a' converts to 10");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('b') == 11,
"'b' converts to 11");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('c') == 12,
"'c' converts to 12");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('d') == 13,
"'d' converts to 13");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('e') == 14,
"'e' converts to 14");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('f') == 15,
"'f' converts to 15");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('g') == 16,
"'g' converts to 16");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('h') == 17,
"'h' converts to 17");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('i') == 18,
"'i' converts to 18");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('j') == 19,
"'j' converts to 19");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('k') == 20,
"'k' converts to 20");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('l') == 21,
"'l' converts to 21");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('m') == 22,
"'m' converts to 22");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('n') == 23,
"'n' converts to 23");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('o') == 24,
"'o' converts to 24");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('p') == 25,
"'p' converts to 25");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('q') == 26,
"'q' converts to 26");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('r') == 27,
"'r' converts to 27");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('s') == 28,
"'s' converts to 28");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('t') == 29,
"'t' converts to 29");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('u') == 30,
"'u' converts to 30");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('v') == 31,
"'v' converts to 31");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('w') == 32,
"'w' converts to 32");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('x') == 33,
"'x' converts to 33");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('y') == 34,
"'y' converts to 34");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('z') == 35,
"'z' converts to 35");
// char16_t
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'0') == 0,
"u'0' converts to 0");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'1') == 1,
"u'1' converts to 1");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'2') == 2,
"u'2' converts to 2");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'3') == 3,
"u'3' converts to 3");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'4') == 4,
"u'4' converts to 4");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'5') == 5,
"u'5' converts to 5");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'6') == 6,
"u'6' converts to 6");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'7') == 7,
"u'7' converts to 7");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'8') == 8,
"u'8' converts to 8");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'9') == 9,
"u'9' converts to 9");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'A') == 10,
"u'A' converts to 10");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'B') == 11,
"u'B' converts to 11");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'C') == 12,
"u'C' converts to 12");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'D') == 13,
"u'D' converts to 13");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'E') == 14,
"u'E' converts to 14");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'F') == 15,
"u'F' converts to 15");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'G') == 16,
"u'G' converts to 16");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'H') == 17,
"u'H' converts to 17");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'I') == 18,
"u'I' converts to 18");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'J') == 19,
"u'J' converts to 19");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'K') == 20,
"u'K' converts to 20");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'L') == 21,
"u'L' converts to 21");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'M') == 22,
"u'M' converts to 22");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'N') == 23,
"u'N' converts to 23");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'O') == 24,
"u'O' converts to 24");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'P') == 25,
"u'P' converts to 25");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'Q') == 26,
"u'Q' converts to 26");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'R') == 27,
"u'R' converts to 27");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'S') == 28,
"u'S' converts to 28");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'T') == 29,
"u'T' converts to 29");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'U') == 30,
"u'U' converts to 30");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'V') == 31,
"u'V' converts to 31");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'W') == 32,
"u'W' converts to 32");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'X') == 33,
"u'X' converts to 33");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'Y') == 34,
"u'Y' converts to 34");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'Z') == 35,
"u'Z' converts to 35");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'a') == 10,
"u'a' converts to 10");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'b') == 11,
"u'b' converts to 11");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'c') == 12,
"u'c' converts to 12");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'd') == 13,
"u'd' converts to 13");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'e') == 14,
"u'e' converts to 14");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'f') == 15,
"u'f' converts to 15");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'g') == 16,
"u'g' converts to 16");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'h') == 17,
"u'h' converts to 17");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'i') == 18,
"u'i' converts to 18");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'j') == 19,
"u'j' converts to 19");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'k') == 20,
"u'k' converts to 20");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'l') == 21,
"u'l' converts to 21");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'm') == 22,
"u'm' converts to 22");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'n') == 23,
"u'n' converts to 23");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'o') == 24,
"u'o' converts to 24");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'p') == 25,
"u'p' converts to 25");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'q') == 26,
"u'q' converts to 26");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'r') == 27,
"u'r' converts to 27");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u's') == 28,
"u's' converts to 28");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u't') == 29,
"u't' converts to 29");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'u') == 30,
"u'u' converts to 30");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'v') == 31,
"u'v' converts to 31");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'w') == 32,
"u'w' converts to 32");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'x') == 33,
"u'x' converts to 33");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'y') == 34,
"u'y' converts to 34");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'z') == 35,
"u'z' converts to 35");
// char32_t
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'0') == 0,
"U'0' converts to 0");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'1') == 1,
"U'1' converts to 1");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'2') == 2,
"U'2' converts to 2");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'3') == 3,
"U'3' converts to 3");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'4') == 4,
"U'4' converts to 4");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'5') == 5,
"U'5' converts to 5");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'6') == 6,
"U'6' converts to 6");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'7') == 7,
"U'7' converts to 7");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'8') == 8,
"U'8' converts to 8");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'9') == 9,
"U'9' converts to 9");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'A') == 10,
"U'A' converts to 10");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'B') == 11,
"U'B' converts to 11");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'C') == 12,
"U'C' converts to 12");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'D') == 13,
"U'D' converts to 13");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'E') == 14,
"U'E' converts to 14");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'F') == 15,
"U'F' converts to 15");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'G') == 16,
"U'G' converts to 16");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'H') == 17,
"U'H' converts to 17");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'I') == 18,
"U'I' converts to 18");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'J') == 19,
"U'J' converts to 19");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'K') == 20,
"U'K' converts to 20");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'L') == 21,
"U'L' converts to 21");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'M') == 22,
"U'M' converts to 22");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'N') == 23,
"U'N' converts to 23");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'O') == 24,
"U'O' converts to 24");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'P') == 25,
"U'P' converts to 25");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'Q') == 26,
"U'Q' converts to 26");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'R') == 27,
"U'R' converts to 27");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'S') == 28,
"U'S' converts to 28");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'T') == 29,
"U'T' converts to 29");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'U') == 30,
"U'U' converts to 30");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'V') == 31,
"U'V' converts to 31");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'W') == 32,
"U'W' converts to 32");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'X') == 33,
"U'X' converts to 33");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'Y') == 34,
"U'Y' converts to 34");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'Z') == 35,
"U'Z' converts to 35");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'a') == 10,
"U'a' converts to 10");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'b') == 11,
"U'b' converts to 11");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'c') == 12,
"U'c' converts to 12");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'd') == 13,
"U'd' converts to 13");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'e') == 14,
"U'e' converts to 14");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'f') == 15,
"U'f' converts to 15");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'g') == 16,
"U'g' converts to 16");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'h') == 17,
"U'h' converts to 17");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'i') == 18,
"U'i' converts to 18");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'j') == 19,
"U'j' converts to 19");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'k') == 20,
"U'k' converts to 20");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'l') == 21,
"U'l' converts to 21");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'm') == 22,
"U'm' converts to 22");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'n') == 23,
"U'n' converts to 23");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'o') == 24,
"U'o' converts to 24");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'p') == 25,
"U'p' converts to 25");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'q') == 26,
"U'q' converts to 26");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'r') == 27,
"U'r' converts to 27");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U's') == 28,
"U's' converts to 28");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U't') == 29,
"U't' converts to 29");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'u') == 30,
"U'u' converts to 30");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'v') == 31,
"U'v' converts to 31");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'w') == 32,
"U'w' converts to 32");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'x') == 33,
"U'x' converts to 33");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'y') == 34,
"U'y' converts to 34");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'z') == 35,
"U'z' converts to 35");
}
static void TestIsAsciiDigit() {
// char
static_assert(!IsAsciiDigit('/'), "'/' isn't an ASCII digit");
static_assert('/' == 0x2F, "'/' has value 0x2F");
static_assert('0' == 0x30, "'0' has value 0x30");
static_assert(IsAsciiDigit('0'), "'0' is an ASCII digit");
static_assert(IsAsciiDigit('1'), "'1' is an ASCII digit");
static_assert(IsAsciiDigit('5'), "'5' is an ASCII digit");
static_assert(IsAsciiDigit('8'), "'8' is an ASCII digit");
static_assert(IsAsciiDigit('9'), "'9' is an ASCII digit");
static_assert('9' == 0x39, "'9' has value 0x39");
static_assert(':' == 0x3A, "':' has value 0x3A");
static_assert(!IsAsciiDigit(':'), "':' isn't an ASCII digit");
static_assert(!IsAsciiDigit('@'), "'@' isn't an ASCII digit");
static_assert(!IsAsciiDigit('A'), "'A' isn't an ASCII digit");
static_assert(!IsAsciiDigit('B'), "'B' isn't an ASCII digit");
static_assert(!IsAsciiDigit('M'), "'M' isn't an ASCII digit");
static_assert(!IsAsciiDigit('Y'), "'Y' isn't an ASCII digit");
static_assert(!IsAsciiDigit('Z'), "'Z' isn't an ASCII digit");
static_assert(!IsAsciiDigit('['), "'[' isn't an ASCII digit");
static_assert(!IsAsciiDigit('`'), "'`' isn't an ASCII digit");
static_assert(!IsAsciiDigit('a'), "'a' isn't an ASCII digit");
static_assert(!IsAsciiDigit('b'), "'b' isn't an ASCII digit");
static_assert(!IsAsciiDigit('m'), "'m' isn't an ASCII digit");
static_assert(!IsAsciiDigit('y'), "'y' isn't an ASCII digit");
static_assert(!IsAsciiDigit('z'), "'z' isn't an ASCII digit");
static_assert(!IsAsciiDigit('{'), "'{' isn't an ASCII digit");
// char16_t
static_assert(!IsAsciiDigit(u'/'), "u'/' isn't an ASCII digit");
static_assert(u'/' == 0x2F, "u'/' has value 0x2F");
static_assert(u'0' == 0x30, "u'0' has value 0x30");
static_assert(IsAsciiDigit(u'0'), "u'0' is an ASCII digit");
static_assert(IsAsciiDigit(u'1'), "u'1' is an ASCII digit");
static_assert(IsAsciiDigit(u'5'), "u'5' is an ASCII digit");
static_assert(IsAsciiDigit(u'8'), "u'8' is an ASCII digit");
static_assert(IsAsciiDigit(u'9'), "u'9' is an ASCII digit");
static_assert(u'9' == 0x39, "u'9' has value 0x39");
static_assert(u':' == 0x3A, "u':' has value 0x3A");
static_assert(!IsAsciiDigit(u':'), "u':' isn't an ASCII digit");
static_assert(!IsAsciiDigit(u'@'), "u'@' isn't an ASCII digit");
static_assert(!IsAsciiDigit(u'A'), "u'A' isn't an ASCII digit");
static_assert(!IsAsciiDigit(u'B'), "u'B' isn't an ASCII digit");
static_assert(!IsAsciiDigit(u'M'), "u'M' isn't an ASCII digit");
static_assert(!IsAsciiDigit(u'Y'), "u'Y' isn't an ASCII digit");
static_assert(!IsAsciiDigit(u'Z'), "u'Z' isn't an ASCII digit");
static_assert(!IsAsciiDigit(u'['), "u'[' isn't an ASCII digit");
static_assert(!IsAsciiDigit(u'`'), "u'`' isn't an ASCII digit");
static_assert(!IsAsciiDigit(u'a'), "u'a' isn't an ASCII digit");
static_assert(!IsAsciiDigit(u'b'), "u'b' isn't an ASCII digit");
static_assert(!IsAsciiDigit(u'm'), "u'm' isn't an ASCII digit");
static_assert(!IsAsciiDigit(u'y'), "u'y' isn't an ASCII digit");
static_assert(!IsAsciiDigit(u'z'), "u'z' isn't an ASCII digit");
static_assert(!IsAsciiDigit(u'{'), "u'{' isn't an ASCII digit");
// char32_t
static_assert(!IsAsciiDigit(U'/'), "U'/' isn't an ASCII digit");
static_assert(U'/' == 0x2F, "U'/' has value 0x2F");
static_assert(U'0' == 0x30, "U'0' has value 0x30");
static_assert(IsAsciiDigit(U'0'), "U'0' is an ASCII digit");
static_assert(IsAsciiDigit(U'1'), "U'1' is an ASCII digit");
static_assert(IsAsciiDigit(U'5'), "U'5' is an ASCII digit");
static_assert(IsAsciiDigit(U'8'), "U'8' is an ASCII digit");
static_assert(IsAsciiDigit(U'9'), "U'9' is an ASCII digit");
static_assert(U'9' == 0x39, "U'9' has value 0x39");
static_assert(U':' == 0x3A, "U':' has value 0x3A");
static_assert(!IsAsciiDigit(U':'), "U':' isn't an ASCII digit");
static_assert(!IsAsciiDigit(U'@'), "U'@' isn't an ASCII digit");
static_assert(!IsAsciiDigit(U'A'), "U'A' isn't an ASCII digit");
static_assert(!IsAsciiDigit(U'B'), "U'B' isn't an ASCII digit");
static_assert(!IsAsciiDigit(U'M'), "U'M' isn't an ASCII digit");
static_assert(!IsAsciiDigit(U'Y'), "U'Y' isn't an ASCII digit");
static_assert(!IsAsciiDigit(U'Z'), "U'Z' isn't an ASCII digit");
static_assert(!IsAsciiDigit(U'['), "U'[' isn't an ASCII digit");
static_assert(!IsAsciiDigit(U'`'), "U'`' isn't an ASCII digit");
static_assert(!IsAsciiDigit(U'a'), "U'a' isn't an ASCII digit");
static_assert(!IsAsciiDigit(U'b'), "U'b' isn't an ASCII digit");
static_assert(!IsAsciiDigit(U'm'), "U'm' isn't an ASCII digit");
static_assert(!IsAsciiDigit(U'y'), "U'y' isn't an ASCII digit");
static_assert(!IsAsciiDigit(U'z'), "U'z' isn't an ASCII digit");
static_assert(!IsAsciiDigit(U'{'), "U'{' isn't an ASCII digit");
}
int main() {
TestIsAscii();
TestIsAsciiNullTerminated();
TestIsAsciiAlpha();
TestIsAsciiUppercaseAlpha();
TestIsAsciiLowercaseAlpha();
TestIsAsciiAlphanumeric();
TestAsciiAlphanumericToNumber();
TestIsAsciiDigit();
}
| 47.258216 | 80 | 0.63638 |
47f21e4f6679cab3af02c95b4f10ba36b13abc46 | 1,280 | cpp | C++ | src/Example/CubeExample.cpp | slicgun/ray_tracing | 913f8a03887c20ca4fbad1fb38395b9f70fe54d4 | [
"Apache-2.0"
] | null | null | null | src/Example/CubeExample.cpp | slicgun/ray_tracing | 913f8a03887c20ca4fbad1fb38395b9f70fe54d4 | [
"Apache-2.0"
] | null | null | null | src/Example/CubeExample.cpp | slicgun/ray_tracing | 913f8a03887c20ca4fbad1fb38395b9f70fe54d4 | [
"Apache-2.0"
] | null | null | null | #include "CubeExample.h"
#include<vector>
#include<glm/geometric.hpp>
#include"Log.h"
std::vector<Material> mat;
Vertex v1 = {0, {0, 1, -3}, {0, 0, 1}, {0, 0}};
Vertex v2 = {0, {-1, 1, -3}, {0, 0, 1}, {0, 0}};
Vertex v3 = {0, {0, 0, -3}, {0, 0, 1}, {0, 0}};
CubeExample::CubeExample(Image& img)
:Example(img, "res/models/cube/cube.obj", {0, 0, 3}, 1, 3), m_texture("res/textures/test.png"), m_triangle(v1, v2, v3, mat)
{
m_camera.position = {0, 0, 0};
m_camera.target = {0, 0, -1};
m_camera.lookAt = glm::normalize(m_camera.target - m_camera.position);
m_camera.right = glm::normalize(glm::cross({0, 1, 0}, m_camera.lookAt));
m_camera.up = glm::cross(m_camera.lookAt, m_camera.right);
}
void CubeExample::draw()
{
for(unsigned y = 0; y < m_image.height; y++)
for(unsigned x = 0; x < m_image.width; x++)
{
glm::ivec2 pixel;
Ray r = getRayThroughPixel(pixel.x, pixel.y);
float u, v, t;
if(m_triangle.intersection(r, t, u, v))
{
float depth = r(t).z;
int depthBufferIndex = index(pixel.x, pixel.y);
glm::vec3 color = {1, 1, 1}; //m_texture.getColor((1 - v - u) * m_triangle[0].uv + u * m_triangle[1].uv + v * m_triangle[2].uv);
setPixelColor(x, y, color);
}
}
writeImage("cube");
}
| 28.444444 | 133 | 0.585938 |
47f22170c5228eac4b407b78897ae5c4e93e9d35 | 3,772 | cpp | C++ | source/common/lua/performance.cpp | xiaobodu/breeze | e74f0cd680274fd431118104d1fdb45926da6328 | [
"Apache-2.0"
] | 1 | 2020-08-13T08:10:15.000Z | 2020-08-13T08:10:15.000Z | source/common/lua/performance.cpp | xiaobodu/breeze | e74f0cd680274fd431118104d1fdb45926da6328 | [
"Apache-2.0"
] | null | null | null | source/common/lua/performance.cpp | xiaobodu/breeze | e74f0cd680274fd431118104d1fdb45926da6328 | [
"Apache-2.0"
] | 1 | 2017-04-30T14:25:25.000Z | 2017-04-30T14:25:25.000Z | /*
* zsummerX License
* -----------
*
* zsummerX is licensed under the terms of the MIT license reproduced below.
* This means that zsummerX is free software and can be used for both academic
* and commercial purposes at absolutely no cost.
*
*
* ===============================================================================
*
* Copyright (C) 2010-2015 YaweiZhang <yawei.zhang@foxmail.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* ===============================================================================
*
* (end of COPYRIGHT)
*/
#include "performance.h"
static void hook_run_fn(lua_State *L, lua_Debug *ar);
static int newindex(lua_State * L)
{
lua_pushvalue(L, 1);
lua_pushvalue(L, 2);
lua_pushvalue(L, 3);
lua_rawset(L, 4);
lua_pop(L, 1);
const char * key = luaL_checkstring(L, 2);
const char * v = luaL_typename(L, 3);
std::stringstream ss;
ss << "catch one operation that it's set a global value. key=" << key << ", type(v)=" << v << ", is it correct ?";
if (lua_getglobal(L, "summer") == LUA_TTABLE && lua_getfield(L, -1, "logw") == LUA_TFUNCTION)
{
lua_pushstring(L, ss.str().c_str());
lua_pcall(L, 1, 0, 0);
}
else if (lua_getglobal(L, "print") == LUA_TFUNCTION)
{
lua_pushstring(L, ss.str().c_str());
lua_pcall(L, 1, 0, 0);
}
lua_pop(L, lua_gettop(L) - 3);
return 0;
}
zsummer::Performence __perf;
void luaopen_performence(lua_State * L)
{
//lua_Hook oldhook = lua_gethook(L);
//int oldmask = lua_gethookmask(L);
lua_sethook(L, &hook_run_fn, LUA_MASKCALL | LUA_MASKRET, 0);
lua_getglobal(L, "_G");
lua_newtable(L);
lua_pushcclosure(L, newindex, 0);
lua_setfield(L, -2, "__newindex");
lua_setmetatable(L, -2);
}
void hook_run_fn(lua_State *L, lua_Debug *ar)
{
// 获取Lua调用信息
lua_getinfo(L, "Snl", ar);
std::string key;
if (ar->source)
{
key += ar->source;
}
key += "_";
if (ar->what)
{
key += ar->what;
}
key += "_";
if (ar->namewhat)
{
key += ar->namewhat;
}
key += "_";
if (ar->name)
{
key += ar->name;
}
if (ar->event == LUA_HOOKCALL)
{
__perf._stack.push(key, lua_gc(L, LUA_GCCOUNT, 0) * 1024 + lua_gc(L, LUA_GCCOUNTB, 0));
}
else if (ar->event == LUA_HOOKRET)
{
//lua_gc(L, LUA_GCCOLLECT, 0);
auto t = __perf._stack.pop(key, lua_gc(L, LUA_GCCOUNT, 0) * 1024 + lua_gc(L, LUA_GCCOUNTB, 0));
if (std::get<0>(t))
{
__perf.call(key, std::get<1>(t), std::get<2>(t));
}
if (__perf.expire(50000.0))
{
__perf.dump(100);
}
}
}
| 30.176 | 118 | 0.595175 |
47f7e140f4798a78082e3cbee4103984473522bd | 1,021 | cpp | C++ | src/atomic.cpp | sriramch/thirdparty-libcxx | a97a7380c76346c22bb67b93695bed19592afad2 | [
"Apache-2.0"
] | 2 | 2020-09-03T03:36:36.000Z | 2020-09-03T08:09:10.000Z | src/atomic.cpp | sriramch/thirdparty-libcxx | a97a7380c76346c22bb67b93695bed19592afad2 | [
"Apache-2.0"
] | 1 | 2019-12-27T02:42:26.000Z | 2019-12-27T02:42:26.000Z | src/atomic.cpp | sriramch/thirdparty-libcxx | a97a7380c76346c22bb67b93695bed19592afad2 | [
"Apache-2.0"
] | 3 | 2019-09-25T21:43:35.000Z | 2020-03-27T19:12:47.000Z | //===------------------------- atomic.cpp ---------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifdef _LIBCPP_SIMT
#include <details/__config>
#else
#include "__config"
#endif
#ifndef _LIBCPP_HAS_NO_THREADS
#ifdef _LIBCPP_SIMT
#include <simt/atomic>
#else
#include "atomic"
#endif
_LIBCPP_BEGIN_NAMESPACE_STD
#if !defined(_LIBCPP_HAS_NO_THREAD_CONTENTION_TABLE)
__libcpp_contention_t __libcpp_contention_state_[ 256 /* < there's no magic in this number */ ];
_LIBCPP_FUNC_VIS
__libcpp_contention_t * __libcpp_contention_state(void const volatile * p) _NOEXCEPT {
return __libcpp_contention_state_ + ((std::uintptr_t)p & 255);
}
#endif //_LIBCPP_HAS_NO_THREAD_CONTENTION_TABLE
_LIBCPP_END_NAMESPACE_STD
#endif //_LIBCPP_HAS_NO_THREADS
| 26.868421 | 96 | 0.676787 |
47f9627eb40dc250db2fe29a5e7e3c98b5bc0974 | 7,058 | cpp | C++ | test_samd21/dma_spi/program.cpp | azydevelopment/test-samd21 | 8442606d6909ada67a29f1f83c9ba3e7da16fd90 | [
"MIT"
] | null | null | null | test_samd21/dma_spi/program.cpp | azydevelopment/test-samd21 | 8442606d6909ada67a29f1f83c9ba3e7da16fd90 | [
"MIT"
] | null | null | null | test_samd21/dma_spi/program.cpp | azydevelopment/test-samd21 | 8442606d6909ada67a29f1f83c9ba3e7da16fd90 | [
"MIT"
] | null | null | null | #include "program.h"
#include <azydev/embedded/bus/spi/atmel/samd21/bus.h>
#include <azydev/embedded/bus/spi/atmel/samd21/device.h>
#include <azydev/embedded/clock/atmel/samd21/clock.h>
#include <azydev/embedded/dma/atmel/samd21/engine.h>
#include <azydev/embedded/dma/common/pool.h>
/* FILE SCOPED STATICS */
static const uint8_t SPI_BUS_ID = 0;
static const uint8_t NUM_SPI_BUS_DEVICES = 1;
static const uint8_t SPI_BUS_DEVICE_0_ID = 0;
static const uint8_t SPI_BUS_DEVICE_0_SS_PIN = PIN_PA05;
static const uint16_t NUM_BYTES = 4;
/* PUBLIC */
CProgram::CProgram()
: m_dma_clock(nullptr)
, m_dma_engine(nullptr)
, m_dma_pool(nullptr)
, m_dma_transfer(nullptr)
, m_spi_clock(nullptr)
, m_spi_bus(nullptr)
, m_spi_device(nullptr)
, m_pins(CPinsAtmelSAMD21()) {
}
CProgram::~CProgram() {
}
void CProgram::Main() {
OnInit();
while (1) {
OnUpdate();
}
}
void CProgram::OnInit() {
// init system
system_init();
// init DMA clock
{
CClockAtmelSAMD21::DESC desc = {};
desc.id = 0;
desc.clock_ahb = CClockAtmelSAMD21::CLOCK_AHB::CLOCK_DMAC;
desc.clock_apbb = CClockAtmelSAMD21::CLOCK_APBB::CLOCK_DMAC;
m_dma_clock = new CClockAtmelSAMD21(desc);
// no additional config needed
// leave clock enabled
m_dma_clock->SetEnabled(true);
}
// init DMA engine
{
CDMAEngineAtmelSAMD21<uint8_t>::DESC desc = {};
// create DMA engine
m_dma_engine = new CDMAEngineAtmelSAMD21<uint8_t>(desc);
// enable DMA engine
m_dma_engine->SetEnabled(true);
}
// init DMA pool
{
CDMAPool<uint8_t>::DESC descPool = {};
descPool.num_allocations_max = 1;
descPool.num_beats_max = NUM_BYTES;
m_dma_pool = new CDMAPool<uint8_t>(descPool);
}
// init DMA transfer object
{
CDMATransferAtmelSAMD21<uint8_t>::DESC desc = {};
desc.id_initial = 0;
desc.num_steps_max = 1;
// create DMA transfer
m_dma_transfer = new CDMATransferAtmelSAMD21<uint8_t>(desc);
}
// init SPI clock
{
CClockAtmelSAMD21::DESC desc = {};
desc.id = 0;
desc.clock_gclk = CClockAtmelSAMD21::CLOCK_GCLK::CLOCK_SERCOM2_CORE;
desc.clock_apbc = CClockAtmelSAMD21::CLOCK_APBC::CLOCK_SERCOM2;
m_spi_clock = new CClockAtmelSAMD21(desc);
CClockAtmelSAMD21::CONFIG_DESC config = {};
config.gclk_generator = CClockAtmelSAMD21::GCLK_GENERATOR::GEN0;
m_spi_clock->SetConfig(config);
// leave clock enabled
m_spi_clock->SetEnabled(true);
}
// init SPI target device
{
// init pin config
CSPIDeviceAtmelSAMD21::PIN_CONFIG_DESC pinConfig = {};
{ pinConfig.ss = SPI_BUS_DEVICE_0_SS_PIN; }
CSPIDeviceAtmelSAMD21::DESC desc = {};
desc.id = SPI_BUS_DEVICE_0_ID;
desc.pin_config = pinConfig;
// create SPI target device
// TODO HACK: Usage of 'new'
m_spi_device = new CSPIDeviceAtmelSAMD21(desc, m_pins);
}
// create SPI bus
{
// setup pin config
CSPIBusAtmelSAMD21::PIN_CONFIG_DESC pinConfig = {};
{
// TODO IMPLEMENT
pinConfig.pad0 = PINMUX_PA08D_SERCOM2_PAD0;
pinConfig.pad1 = PINMUX_UNUSED;
pinConfig.pad2 = PINMUX_PA10D_SERCOM2_PAD2;
pinConfig.pad3 = PINMUX_PA11D_SERCOM2_PAD3;
pinConfig.data_in_pinout = CSPIBusAtmelSAMD21::DATA_IN_PINOUT::PAD_0;
pinConfig.data_out_pinout =
CSPIBusAtmelSAMD21::DATA_OUT_PINOUT::DO_PAD2_SCK_PAD3_SS_PAD1;
}
CSPIBusAtmelSAMD21::DESC desc = {};
desc.id = SPI_BUS_ID;
desc.pin_config = pinConfig;
desc.sercomSpi = &(SERCOM2->SPI);
desc.num_devices = NUM_SPI_BUS_DEVICES;
desc.devices = &m_spi_device;
// create SPI bus
m_spi_bus = new CSPIBusAtmelSAMD21(desc, m_pins);
}
// configure SPI bus
{
// create config
CSPIBusAtmelSAMD21::CONFIG_DESC busConfig = {};
{
busConfig.endianness = CSPIBusAtmelSAMD21::ENDIANNESS::BIG;
busConfig.duplex_mode_intial = CSPIBusAtmelSAMD21::DUPLEX_MODE::FULL;
busConfig.clock_polarity = CSPIBusAtmelSAMD21::CLOCK_POLARITY::IDLE_LOW;
busConfig.clock_phase = CSPIBusAtmelSAMD21::CLOCK_PHASE::SAMPLE_TRAILING;
busConfig.frame_format = CSPIBusAtmelSAMD21::FRAME_FORMAT::SPI;
busConfig.immediate_buffer_overflow_notification = false;
busConfig.run_in_standby = false;
busConfig.address_mode = CSPIBusAtmelSAMD21::ADDRESS_MODE::MASK;
busConfig.enable_manager_worker_select = false;
busConfig.enable_worker_select_low_detect = false;
busConfig.enable_worker_data_preload = false;
busConfig.baud_rate = 128;
busConfig.enable_interrupt_error = false;
busConfig.enable_interrupt_worker_select_low = false;
busConfig.enable_interrupt_receive_complete = false;
busConfig.enable_interrupt_transmit_complete = false;
busConfig.enable_interrupt_data_register_empty = false;
// DMA
busConfig.dma_transfer_id = 0;
busConfig.dma_engine = m_dma_engine;
busConfig.dma_transfer = m_dma_transfer;
}
// set role
m_spi_bus->SetRole(CSPIEntity::ROLE::MANAGER);
// set config
m_spi_bus->SetConfig(busConfig);
// enable SPI
m_spi_bus->SetEnabled(true);
}
m_spi_bus->SetDeviceRole(SPI_BUS_DEVICE_0_ID, CSPIEntity::ROLE::WORKER);
}
void CProgram::OnUpdate() {
// reset DMA pool
m_dma_pool->PopAllocation();
// prepare transfer node
const IDMANode<uint8_t>* nodeSrc = nullptr;
{
// prepare source node
uint8_t allocationId = 0;
m_dma_pool->PushAllocation(allocationId);
for (uint32_t j = 0; j < NUM_BYTES; j++) {
m_dma_pool->RecordWrite(j);
}
nodeSrc = m_dma_pool->GetAllocationDMANode(allocationId);
}
// execute the SPI transfer
{
m_spi_bus->Start(SPI_BUS_DEVICE_0_ID);
// uint16_t data;
// m_spi_bus->Read(data);
// data = 0;
CSPIBusAtmelSAMD21* spiBusSAMD21 = static_cast<CSPIBusAtmelSAMD21*>(m_spi_bus);
spiBusSAMD21->Write(*nodeSrc, NUM_BYTES);
m_spi_bus->Stop();
}
}
| 31.792793 | 100 | 0.590536 |
47fbba07d41575b11562d65477c18a9b23314a7b | 173 | cpp | C++ | assec-renderer/src/renderer/shader.cpp | TeamVistic/assec-renderer | 5c6fc9a46fc3f6302471a22bfd2bdf2942b794db | [
"Apache-2.0"
] | null | null | null | assec-renderer/src/renderer/shader.cpp | TeamVistic/assec-renderer | 5c6fc9a46fc3f6302471a22bfd2bdf2942b794db | [
"Apache-2.0"
] | null | null | null | assec-renderer/src/renderer/shader.cpp | TeamVistic/assec-renderer | 5c6fc9a46fc3f6302471a22bfd2bdf2942b794db | [
"Apache-2.0"
] | null | null | null | #include "pch.h"
#include "shader.h"
namespace assec::renderer
{
shader::shader(const std::wstring& source, SHADER_TYPE type) : m_source(source), m_shader_type(type) {}
} | 21.625 | 104 | 0.728324 |
47fcb01c73b270ea1521ab1a777cd3884b6cb43c | 3,137 | cpp | C++ | libraries/utilities/example/cmdline1.cpp | tneele/mCRL2 | 8f2d730d650ffec15130d6419f69c50f81e5125c | [
"BSL-1.0"
] | null | null | null | libraries/utilities/example/cmdline1.cpp | tneele/mCRL2 | 8f2d730d650ffec15130d6419f69c50f81e5125c | [
"BSL-1.0"
] | null | null | null | libraries/utilities/example/cmdline1.cpp | tneele/mCRL2 | 8f2d730d650ffec15130d6419f69c50f81e5125c | [
"BSL-1.0"
] | null | null | null | // Author(s): Wieger Wesselink
// Copyright: see the accompanying file COPYING or copy at
// https://github.com/mCRL2org/mCRL2/blob/master/COPYING
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
/// \file cmdline1.cpp
/// \brief CLI example
#include <iostream>
#include <stdexcept>
#include <string>
#include <utility>
#include "mcrl2/utilities/input_output_tool.h"
using namespace mcrl2;
using utilities::command_line_parser;
using utilities::interface_description;
using utilities::make_optional_argument;
using utilities::tools::tool;
/// The pbesinst tool.
class my_tool: public tool
{
protected:
typedef tool super;
std::string synopsis() const
{
return "[OPTION]... [FIRST]\n";
}
/// Parse the non-default options.
void parse_options(const command_line_parser& parser)
{
super::parse_options(parser);
std::string s = parser.option_argument("option1");
std::cout << "option o: " << s << std::endl;
int i = parser.option_argument_as<int>("option2");
std::cout << "option i: " << i << std::endl;
bool b = parser.option_argument_as<bool>("option3");
std::cout << "option b: " << std::boolalpha << b << std::endl;
bool a = parser.options.count("option4") > 0;
std::cout << "option a: " << std::boolalpha << a << std::endl;
if (0 < parser.arguments.size())
{
std::string s = parser.arguments[0];
std::cout << "positional option 1: " << s << std::endl;
}
std::cout << "--- parser arguments ---" << std::endl;
for (const auto & option : parser.options)
{
std::cout << option.first << " -> " << option.second << std::endl;
}
}
void add_options(interface_description& desc)
{
super::add_options(desc);
desc
/// string option with default value 'name1'
.add_option("option1",
make_optional_argument("NAME", "name1"),
"string option NAME:\n"
" 'name1' (default),\n"
" 'name2', or\n"
" 'name3'.",
'o')
/// integer option with default value 1
.add_option("option2",
make_optional_argument("NAME", "1"),
"integer option",
'i')
/// boolean option with default value true
.add_option("option3",
make_optional_argument("NAME", "1"),
"boolean option",
'b')
/// boolean flag (default off)
.add_option("option4",
"boolean option",
'a')
;
}
public:
/// Constructor.
my_tool()
: super(
"My tool",
"John Doe",
"One line description",
"First line of the long description. "
"Second line of the long description."
)
{}
/// Runs the tool.
bool run()
{
return true;
}
};
int main(int argc, char* argv[])
{
return my_tool().execute(argc, argv);
}
| 26.584746 | 74 | 0.559133 |
47fded78073828b55b3a98e9ff8bda0d3caa6284 | 37,799 | cpp | C++ | src/bitname/bitname_channel.cpp | gcbpay/R9-VRBcoinShares | 2b77f7a77b9254e20250cdcd99c7a289fd0c3ca4 | [
"Unlicense"
] | 2 | 2016-10-21T22:54:50.000Z | 2017-11-08T07:06:46.000Z | src/bitname/bitname_channel.cpp | gcbpay/R9-VRBcoinShares | 2b77f7a77b9254e20250cdcd99c7a289fd0c3ca4 | [
"Unlicense"
] | 7 | 2016-10-23T12:26:43.000Z | 2017-09-01T09:35:28.000Z | src/bitname/bitname_channel.cpp | gcbpay/R9-VRBcoinShares | 2b77f7a77b9254e20250cdcd99c7a289fd0c3ca4 | [
"Unlicense"
] | null | null | null | #include <bts/bitname/bitname_channel.hpp>
#include <bts/bitname/bitname_messages.hpp>
#include <bts/bitname/bitname_db.hpp>
#include <bts/bitname/bitname_fork_db.hpp>
#include <bts/bitname/bitname_hash.hpp>
#include <bts/blockchain/fork_tree.hpp>
#include <bts/network/server.hpp>
#include <bts/network/channel.hpp>
#include <bts/network/broadcast_manager.hpp>
#include <bts/difficulty.hpp>
#include <fc/reflect/variant.hpp>
#include <fc/crypto/hex.hpp>
#include <fc/thread/thread.hpp>
#include <fc/log/logger.hpp>
#include <unordered_map>
namespace bts { namespace bitname {
using namespace bts::network;
namespace detail
{
class chan_data : public network::channel_data
{
public:
broadcast_manager<name_hash_type,name_header>::channel_data trxs_mgr;
broadcast_manager<name_id_type,name_block_index>::channel_data block_mgr;
fc::optional<fc::time_point> requested_headers;
fc::optional<fc::time_point> requested_block;
/** tracks the block ids this connection has reported to us */
std::unordered_set<name_id_type> available_blocks;
/// the head block as reported by the remote node
name_id_type recv_head_block_id;
/// the head block as we have reported to the remote node
name_id_type sent_head_block_id;
};
struct block_index_download_manager
{
name_block incomplete;
name_block_index index;
/** map short id to incomplete.name_trxs index */
std::unordered_map<short_name_id_type,uint32_t> unknown;
bool try_complete( const name_header& n )
{
auto itr = unknown.find(n.short_id());
if( itr != unknown.end() )
{
incomplete.name_trxs[itr->second] = n;
unknown.erase(itr);
}
return unknown.size() == 0;
}
};
struct fetch_loop_state
{
bool synchronizing;
};
class name_channel_impl : public bts::network::channel
{
public:
name_channel_impl()
:_delegate(nullptr),_new_block_info(true){}
name_channel_delegate* _delegate;
/** set this flag anytime the fork database has new info that
* might change what blocks to fetch.
*/
bool _new_block_info;
bts::peer::peer_channel_ptr _peers;
network::channel_id _chan_id;
name_db _name_db;
fork_db _fork_db;
fetch_loop_state _fetch_state;
fc::future<void> _fetch_loop;
// TODO: on connection disconnect, check to see if there was a pending fetch and
// cancel it so we can get it from someone else.
fc::optional<fc::time_point> _pending_block_fetch;
broadcast_manager<short_name_id_type,name_header> _trx_broadcast_mgr;
broadcast_manager<name_id_type,name_block_index> _block_index_broadcast_mgr;
std::vector<block_index_download_manager> _block_downloads;
void fetch_block_from_index( const name_block_index& index )
{
block_index_download_manager block_idx_downloader;
block_idx_downloader.incomplete = name_block(index.header);
block_idx_downloader.index = index;
block_idx_downloader.incomplete.name_trxs.resize( index.name_trxs.size() );
for( uint32_t i = 0; i < index.name_trxs.size(); ++i )
{
auto val = _trx_broadcast_mgr.get_value( index.name_trxs[i] );
if( val )
{
block_idx_downloader.incomplete.name_trxs[i] = *val;
}
else
{
FC_ASSERT( block_idx_downloader.unknown.find(index.name_trxs[i]) ==
block_idx_downloader.unknown.end() ); // checks for duplicates
block_idx_downloader.unknown[index.name_trxs[i]] = i;
}
}
if( block_idx_downloader.unknown.size() == 0 )
{
submit_block( block_idx_downloader.incomplete );
}
else
{
_block_downloads.push_back( block_idx_downloader );
fetch_unknown_name_trxs( _block_downloads.back() );
}
}
void fetch_unknown_name_trxs( const block_index_download_manager& dlmgr )
{
for( auto itr = dlmgr.unknown.begin(); itr != dlmgr.unknown.end(); ++itr )
{
// TODO: fetch missing from various hosts..
}
}
void update_block_index_downloads( const name_header& trx )
{
for( auto itr = _block_downloads.begin(); itr != _block_downloads.end(); )
{
if( itr->try_complete( trx) )
{
try {
submit_block( itr->incomplete );
}
catch ( fc::exception& e )
{
// TODO: how do we punish block that sent us this...
// what was the reason we couldn't submit it... peraps
// it is just too old and another block beat it to the
// punch...
wlog( "unable to submit block after download\n${e}",
("e",e.to_detail_string() ) );
}
itr = _block_downloads.erase(itr);
}
else
{
++itr;
}
}
}
void fetch_next_from_fork_db()
{ try {
if( _pending_block_fetch &&
(fc::time_point::now() - *_pending_block_fetch) < fc::seconds( BITNAME_BLOCK_FETCH_TIMEOUT_SEC ) )
{
return;
}
if( _new_block_info )
{
_new_block_info = false;
auto valid_head_num = _name_db.head_block_num();
//ilog( "valid_head_num: ${v}", ("v",valid_head_num) );
if( valid_head_num >= _fork_db.best_fork_height() )
{
return;
}
meta_header next_best = _fork_db.best_fork_fetch_at( valid_head_num + 1);
//ilog( "next_best: ${v}", ("v",next_best) );
//ilog( "head_block_id: ${v}", ("v",_name_db.head_block_id()) );
while( next_best.prev != _name_db.head_block_id() )
{
wlog( "pop back!" );
_name_db.pop_block();
next_best = _fork_db.fetch_header( next_best.prev );
ilog( "next_best: ${v}", ("v",next_best) );
}
fc::optional<name_block> next_block = _fork_db.fetch_block( next_best.id() );
if( next_block )
{
try {
_name_db.push_block( *next_block );
}
catch ( const fc::exception& e )
{
elog( "error applying block from this fork, this fork must be invalid\n${e}", ( "e", e.to_detail_string() ) );
_fork_db.set_valid( next_block->id(), false );
}
_new_block_info = true; // attempt another block on next call
}
else
{
auto cons = _peers->get_connections( _chan_id );
if( cons.size() != 0 )
{
fetch_block_from_best_connection( cons, next_best.id() );
}
}
}
} FC_RETHROW_EXCEPTIONS( warn , "" ) }
/**
* The fetch loop has several modes:
* 1) synchronize mode.
* 2) maitenance mode.
*
* In Synchronize mode the client is not conserned with inventory
* notices from other nodes. In fact, other nodes probably shouldn't
* bother broadcasting inv notices to us until we have finished sync.
*
* The client stays in synchronize mode until it has determined that it
* is on the proper chain. When a client first connects it sends a request
* for new block headers and it will get a response that may include
* a potential chain reorganization though this should be relatively
* rare.
*
*/
void fetch_loop()
{
try
{
while( !_fetch_loop.canceled() )
{
broadcast_inv();
fetch_next_from_fork_db();
short_name_id_type trx_query = 0;
if( _trx_broadcast_mgr.find_next_query( trx_query ) )
{
auto cons = _peers->get_connections( _chan_id );
fetch_name_from_best_connection( cons, trx_query );
_trx_broadcast_mgr.item_queried( trx_query );
}
name_id_type blk_idx_query;
if( _block_index_broadcast_mgr.find_next_query( blk_idx_query ) )
{
auto cons = _peers->get_connections( _chan_id );
fetch_block_idx_from_best_connection( cons, blk_idx_query );
_block_index_broadcast_mgr.item_queried( blk_idx_query );
}
/* By using a random sleep we give other peers the oppotunity to find
* out about messages before we pick who to fetch from.
* TODO: move constants to config.hpp
*
* TODO: fetch set your fetch order based upon how many times we have received
* an inv regarding a particular item.
*
* TODO: make sure we seed rand()
*/
fc::usleep( fc::microseconds( (rand() % 20000) + 100) );
}
}
catch ( const fc::exception& e )
{
elog( "fetch loop threw... something bad happened\n${e}", ("e", e.to_detail_string()) );
// TODO: bitname will hang if we don't find some way to recover or report this
// to the user...
}
}
void request_latest_blocks()
{
auto cons = _peers->get_connections( _chan_id );
for( auto c = cons.begin(); c != cons.end(); ++c )
{
request_block_headers( *c );
}
}
/**
* Send any new inventory items that we have received since the last
* broadcast to all connections that do not know about the inv item.
*/
void broadcast_inv()
{ try {
if( _trx_broadcast_mgr.has_new_since_broadcast() || _block_index_broadcast_mgr.has_new_since_broadcast() )
{
auto cons = _peers->get_connections( _chan_id );
if( _trx_broadcast_mgr.has_new_since_broadcast() )
{
for( auto c = cons.begin(); c != cons.end(); ++c )
{
name_inv_message inv_msg;
chan_data& con_data = get_channel_data( *c );
inv_msg.name_trxs = _trx_broadcast_mgr.get_inventory( con_data.trxs_mgr );
if( inv_msg.name_trxs.size() )
{
(*c)->send( network::message(inv_msg,_chan_id) );
}
con_data.trxs_mgr.update_known( inv_msg.name_trxs );
}
_trx_broadcast_mgr.set_new_since_broadcast(false);
}
if( _block_index_broadcast_mgr.has_new_since_broadcast() )
{
for( auto c = cons.begin(); c != cons.end(); ++c )
{
block_inv_message inv_msg;
chan_data& con_data = get_channel_data( *c );
inv_msg.block_ids = _block_index_broadcast_mgr.get_inventory( con_data.block_mgr );
if( inv_msg.block_ids.size() )
{
(*c)->send( network::message(inv_msg,_chan_id) );
}
con_data.block_mgr.update_known( inv_msg.block_ids );
}
_block_index_broadcast_mgr.set_new_since_broadcast(false);
}
}
} FC_RETHROW_EXCEPTIONS( warn, "error broadcasting bitname inventory") } // broadcast_inv
/**
* For any given message id, there are many potential hosts from which it could be fetched. We
* want to distribute the load across all hosts equally and therefore, the best one to fetch from
* is the host that we have fetched the least from and that has fetched the most from us.
*/
void fetch_name_from_best_connection( const std::vector<connection_ptr>& cons, uint64_t id )
{ try {
ilog( "${id}", ("id",id) );
// if request is made, move id from unknown_names to requested_msgs
// TODO: update this algorithm to be something better.
for( uint32_t i = 0; i < cons.size(); ++i )
{
ilog( "con ${i}", ("i",i) );
chan_data& chan_data = get_channel_data(cons[i]);
if( chan_data.trxs_mgr.knows( id ) && !chan_data.trxs_mgr.has_pending_request() )
{
chan_data.trxs_mgr.requested(id);
get_name_header_message request( id );
ilog( "request ${msg}", ("msg",request) );
cons[i]->send( network::message( request, _chan_id ) );
return;
}
}
} FC_RETHROW_EXCEPTIONS( warn, "error fetching name ${name_hash}", ("name_hash",id) ) }
void fetch_block_from_best_connection( const std::vector<connection_ptr>& cons, const name_id_type& id )
{ try {
ilog( "${id}", ("id",id) );
// if request is made, move id from unknown_names to requested_msgs
// TODO: update this algorithm to be something better.
for( uint32_t i = 0; i < cons.size(); ++i )
{
ilog( "con ${i}", ("i",i) );
chan_data& chan_data = get_channel_data(cons[i]);
if( chan_data.available_blocks.find(id) != chan_data.available_blocks.end() )
{
ilog( "request ${msg}", ("msg",get_block_message(id)) );
_pending_block_fetch = fc::time_point::now();
get_channel_data( cons[i] ).requested_block = *_pending_block_fetch;
// TODO: track how many blocks I have requested from this connection...
// and perform soem load balancing...
cons[i]->send( network::message( get_block_message(id), _chan_id ) );
return;
}
else
{
}
}
} FC_RETHROW_EXCEPTIONS( warn, "error fetching name ${name_hash}", ("name_hash",id) ) }
void fetch_block_idx_from_best_connection( const std::vector<connection_ptr>& cons, const name_id_type& id )
{ try {
ilog( "${id}", ("id",id) );
// if request is made, move id from unknown_names to requested_msgs
// TODO: update this algorithm to be something better.
for( uint32_t i = 0; i < cons.size(); ++i )
{
ilog( "con ${i}", ("i",i) );
chan_data& chan_data = get_channel_data(cons[i]);
if( chan_data.block_mgr.knows(id) && !chan_data.block_mgr.has_pending_request() )
{
ilog( "request ${msg}", ("msg",get_block_index_message(id)) );
chan_data.block_mgr.requested(id);
// TODO: track how many blocks I have requested from this connection...
// and perform soem load balancing...
cons[i]->send( network::message( get_block_index_message(id), _chan_id ) );
return;
}
}
} FC_RETHROW_EXCEPTIONS( warn, "error fetching name ${name_hash}", ("name_hash",id) ) }
/**
* Get or create the bitchat channel data for this connection and return
* a reference to the result.
*/
chan_data& get_channel_data( const connection_ptr& c )
{
auto cd = c->get_channel_data( _chan_id );
if( !cd )
{
cd = std::make_shared<chan_data>();
c->set_channel_data( _chan_id, cd );
}
chan_data& cdat = cd->as<chan_data>();
return cdat;
}
virtual void handle_subscribe( const connection_ptr& c )
{
get_channel_data(c); // creates it...
request_latest_blocks();
}
virtual void handle_unsubscribe( const connection_ptr& c )
{
c->set_channel_data( _chan_id, nullptr );
}
/* ===================================================== */
void handle_message( const connection_ptr& con, const message& m )
{
try {
chan_data& cdat = get_channel_data(con);
ilog( "${msg_type}", ("msg_type", (bitname::message_type)m.msg_type ) );
switch( (bitname::message_type)m.msg_type )
{
case name_inv_msg:
handle_name_inv( con, cdat, m.as<name_inv_message>() );
break;
case block_inv_msg:
handle_block_inv( con, cdat, m.as<block_inv_message>() );
break;
case get_name_inv_msg:
handle_get_name_inv( con, cdat, m.as<get_name_inv_message>() );
break;
case get_headers_msg:
handle_get_headers( con, cdat, m.as<get_headers_message>() );
break;
case get_block_msg:
handle_get_block( con, cdat, m.as<get_block_message>() );
break;
case get_block_index_msg:
handle_get_block_index( con, cdat, m.as<get_block_index_message>() );
break;
case get_name_header_msg:
handle_get_name( con, cdat, m.as<get_name_header_message>() );
break;
case name_header_msg:
handle_name( con, cdat, m.as<name_header_message>() );
break;
case block_index_msg:
handle_block_index( con, cdat, m.as<block_index_message>() );
break;
case block_msg:
handle_block( con, cdat, m.as<block_message>() );
break;
case headers_msg:
handle_headers( con, cdat, m.as<headers_message>() );
break;
default:
FC_THROW_EXCEPTION( exception, "unknown bitname message type ${msg_type}", ("msg_type", m.msg_type ) );
}
}
catch ( fc::exception& e )
{
wlog( "${e} ${from}", ("e",e.to_detail_string())("from",con->remote_endpoint()) );
}
} // handle_message
/* ===================================================== */
void request_block_headers( const connection_ptr& con )
{
chan_data& cdat = get_channel_data(con);
FC_ASSERT( !cdat.requested_headers );
ilog( "requesting block headers from ${ep}", ("ep",con->remote_endpoint() ));
get_headers_message request;
const std::vector<name_id_type>& ids = _name_db.get_header_ids();
uint32_t delta = 1;
for( int32_t i = ids.size() - 1; i >= 0; )
{
request.locator_hashes.push_back(ids[i]);
i -= delta;
delta *= 2;
}
cdat.requested_headers = fc::time_point::now();
con->send( network::message(request,_chan_id) );
}
/* ===================================================== */
void handle_name_inv( const connection_ptr& con, chan_data& cdat, const name_inv_message& msg )
{
ilog( "inv: ${msg}", ("msg",msg) );
for( auto itr = msg.name_trxs.begin(); itr != msg.name_trxs.end(); ++itr )
{
_trx_broadcast_mgr.received_inventory_notice( *itr );
}
cdat.trxs_mgr.update_known( msg.name_trxs );
}
/* ===================================================== */
void handle_block_inv( const connection_ptr& con, chan_data& cdat, const block_inv_message& msg )
{
ilog( "inv: ${msg}", ("msg",msg) );
for( auto itr = msg.block_ids.begin(); itr != msg.block_ids.end(); ++itr )
{
_block_index_broadcast_mgr.received_inventory_notice( *itr );
}
cdat.block_mgr.update_known( msg.block_ids );
}
/* ===================================================== */
void handle_get_name_inv( const connection_ptr& con, chan_data& cdat, const get_name_inv_message& msg )
{
name_inv_message reply;
reply.name_trxs = _trx_broadcast_mgr.get_inventory( cdat.trxs_mgr );
cdat.trxs_mgr.update_known( reply.name_trxs );
con->send( network::message(reply,_chan_id) );
}
/* ===================================================== */
void handle_get_headers( const connection_ptr& con, chan_data& cdat, const get_headers_message& msg )
{ try {
// TODO: prevent abuse of this message... only allow it at a limited rate and take notice
// when the remote node starts abusing it.
uint32_t start_block = 0;
for( uint32_t i = 0; i < msg.locator_hashes.size(); ++i )
{
try {
start_block = _name_db.get_block_num( msg.locator_hashes[i] );
break;
}
catch ( const fc::exception& e )
{
// TODO: should I do something other than log this exception?
wlog( "apparently this node is on a different fork, error fetching ${id}\n${e}",
("id", msg.locator_hashes[i] )("e",e.to_detail_string()) );
}
}
const std::vector<name_id_type>& ids = _name_db.get_header_ids();
uint32_t end = std::min<uint32_t>(start_block+2000, ids.size() );
headers_message reply;
reply.first_block_num = start_block;
reply.first = _name_db.fetch_block_header(start_block);
reply.headers.reserve( end - start_block - 1 );
for( auto i = start_block+1; i < end; ++i )
{
reply.headers.push_back( _name_db.fetch_block_header(ids[i]) );
}
reply.head_block_num = ids.size() - 1;
reply.head_block_id = ids.back();
con->send( network::message( reply, _chan_id ) );
} FC_RETHROW_EXCEPTIONS( warn, "", ("msg",msg) ) }
/* ===================================================== */
void handle_get_block_index( const connection_ptr& con, chan_data& cdat, const get_block_index_message& msg )
{ try {
ilog( "${msg}", ("msg",msg) );
const fc::optional<name_block_index>& trx = _block_index_broadcast_mgr.get_value( msg.block_id );
if( !trx ) // must be a db
{
auto debug_str = _block_index_broadcast_mgr.debug();
FC_ASSERT( !"Name block index not in broadcast cache", "${str}", ("str",debug_str) );
}
con->send( network::message( block_index_message( *trx ), _chan_id ) );
} FC_RETHROW_EXCEPTIONS( warn, "", ("msg",msg) ) }
/* ===================================================== */
void handle_get_block( const connection_ptr& con, chan_data& cdat, const get_block_message& msg )
{ try {
// TODO: charge POW for this...
auto block = _name_db.fetch_block( msg.block_id );
con->send( network::message( block_message( std::move(block) ), _chan_id ) );
} FC_RETHROW_EXCEPTIONS( warn, "", ("msg",msg) ) }
/* ===================================================== */
void handle_get_name( const connection_ptr& con, chan_data& cdat, const get_name_header_message& msg )
{
ilog( "${msg}", ("msg",msg) );
const fc::optional<name_header>& trx = _trx_broadcast_mgr.get_value( msg.name_trx_id );
if( !trx ) // must be a db
{
auto debug_str = _trx_broadcast_mgr.debug();
FC_ASSERT( !"Name transaction not in broadcast cache", "${str}", ("str",debug_str) );
/*
... we should not allow fetching of individual name trx from our db...
this would require a huge index
name_header trx = _name_db.fetch_trx_header( msg.name_trx_id );
con->send( network::message( name_header_message( trx ), _chan_id ) );
*/
}
else
{
con->send( network::message( name_header_message( *trx ), _chan_id ) );
}
}
void handle_block_index( const connection_ptr& con, chan_data& cdat, const block_index_message& msg )
{
ilog( "${msg}", ("msg",msg) );
cdat.block_mgr.received_response( msg.index.header.id() );
_fork_db.cache_header( msg.index.header );
_new_block_info = true;
if( msg.index.name_trxs.size() == 0 )
{
submit_block( msg.index.header );
}
else
{
_block_downloads.push_back( block_index_download_manager() );
block_index_download_manager& dlmgr = _block_downloads.back();
dlmgr.incomplete = name_block(msg.index.header);
dlmgr.index = msg.index;
dlmgr.incomplete.name_trxs.resize( msg.index.name_trxs.size() );
for( uint32_t i = 0; i < msg.index.name_trxs.size(); ++i )
{
auto opt_trx = _trx_broadcast_mgr.get_value( msg.index.name_trxs[i] );
if( opt_trx )
{
dlmgr.incomplete.name_trxs[i] = *opt_trx;
}
else
{
dlmgr.unknown[msg.index.name_trxs[i]] = i;
_trx_broadcast_mgr.received_inventory_notice( msg.index.name_trxs[i] );
cdat.trxs_mgr.update_known( msg.index.name_trxs[i] );
}
}
if( dlmgr.unknown.size() == 0 )
{
submit_block( dlmgr.incomplete );
_block_downloads.pop_back();
}
}
}
void handle_name( const connection_ptr& con, chan_data& cdat, const name_header_message& msg )
{ try {
ilog( "${msg}", ("msg",msg) );
auto short_id = msg.trx.short_id();
cdat.trxs_mgr.received_response( short_id );
try {
// attempt to complete blocks without validating the trx so that
// we can then mark the block as 'complete' and then invalidate it
update_block_index_downloads( msg.trx );
submit_name( msg.trx );
}
catch ( fc::exception& e )
{
// TODO: connection just sent us an invalid trx... what do we do...
// log it and ignore it because it was probably for the prior
// block that they haven't received yet... we should note it though.
//
// it may be valid because we are not yet synced...
_trx_broadcast_mgr.validated( short_id, msg.trx, false );
// FC_RETHROW_EXCEPTION( e, warn, "" );
}
} FC_RETHROW_EXCEPTIONS( warn, "", ("msg", msg) ) }
void handle_block( const connection_ptr& con, chan_data& cdat, const block_message& msg )
{ try {
FC_ASSERT( !!cdat.requested_block );
// TODO: make sure that I requrested this block...
_fork_db.cache_block( msg.block );
_new_block_info = true;
cdat.requested_block.reset();
_pending_block_fetch.reset();
try {
submit_block(msg.block); //_name_db.push_block( msg.block );
}
catch( const fc::exception& e )
{
// don't try to fetch this or any of its decendants again..
//_fork_tree.set_valid_state( _name_db.head_block_num()+1, msg.block.id(), false );
throw;
}
} FC_RETHROW_EXCEPTIONS( warn,"handling block ${block}", ("block",msg) ) }
/**
* Received in response to get_headers message, we should certify that we requested this.
*/
void handle_headers( const connection_ptr& con, chan_data& cdat, const headers_message& msg )
{ try {
FC_ASSERT( !!cdat.requested_headers );
cdat.requested_headers.reset();
// TODO: validate that all ids reported have the min proof of work for a name.
ilog( "received ${msg}", ("msg",msg) );
_fork_db.cache_header( msg.first );
_new_block_info = true;
name_id_type prev_id = msg.first.id();
for( auto itr = msg.headers.begin(); itr != msg.headers.end(); ++itr )
{
name_header next_head( *itr, prev_id );
ilog( "${id} = ${next_head}", ("id",next_head.id())("next_head",next_head) );
_fork_db.cache_header( next_head );
prev_id = next_head.id();
cdat.available_blocks.insert(prev_id);
}
if( prev_id != msg.head_block_id )
{
cdat.requested_headers = fc::time_point::now();
get_headers_message request;
request.locator_hashes.push_back( prev_id );
con->send( network::message( request, _chan_id ) );
}
} FC_RETHROW_EXCEPTIONS( warn, "", ("msg",msg) ) }
void submit_name( const name_header& new_name_trx )
{ try {
_name_db.validate_trx( new_name_trx );
_trx_broadcast_mgr.validated( new_name_trx.short_id(), new_name_trx, true );
if( _delegate )
{
try {
_delegate->pending_name_trx( new_name_trx );
}
catch ( const fc::exception& e )
{
// This could fail if the head block was replaced between the start of the last
// mining round and the discovery of a name... perhaps catch this earlier rather than
// waiting until we get here!
wlog( "delegate threw exception... it shouldn't do that!\n ${e}", ("e", e.to_detail_string() ) );
}
}
} FC_RETHROW_EXCEPTIONS( warn, "error submitting name", ("new_name_trx", new_name_trx) ) }
void submit_block( const name_block& block )
{ try {
_fork_db.cache_block( block );
_new_block_info = true;
_name_db.push_block( block ); // this throws on error
_trx_broadcast_mgr.invalidate_all(); // current inventory is now invalid
_block_index_broadcast_mgr.clear_old_inventory(); // we can clear old inventory
_trx_broadcast_mgr.clear_old_inventory(); // this inventory no longer matters
_block_index_broadcast_mgr.validated( block.id(), block, true );
_name_db.dump(); // DEBUG
if( _delegate ) _delegate->name_block_added( block );
} FC_RETHROW_EXCEPTIONS( warn, "error submitting block", ("block", block) ) }
};
} // namespace detail
name_channel::name_channel( const bts::peer::peer_channel_ptr& n )
:my( new detail::name_channel_impl() )
{
my->_peers = n;
my->_chan_id = channel_id(network::name_proto,0);
my->_peers->subscribe_to_channel( my->_chan_id, my );
}
name_channel::~name_channel()
{
my->_peers->unsubscribe_from_channel( my->_chan_id );
my->_delegate = nullptr;
try {
if( my->_fetch_loop.valid() )
{
my->_fetch_loop.cancel();
my->_fetch_loop.wait();
}
}
catch ( ... )
{
wlog( "unexpected exception ${e}", ("e", fc::except_str()));
}
}
void name_channel::configure( const name_channel::config& c )
{
fc::create_directories( c.name_db_dir / "forks" );
my->_name_db.open( c.name_db_dir, true/*create*/ );
my->_fork_db.open( c.name_db_dir / "forks" , true/*create*/ );
my->_fetch_loop = fc::async( [=](){ my->fetch_loop(); } );
// TODO: connect to the network and attempt to download the chain...
// * what if no peers on on the name channel ?? *
// I guess when I do connect to a peer on this channel they will
// learn that I am subscribed to this channel...
}
void name_channel::set_delegate( name_channel_delegate* d )
{
my->_delegate = d;
}
void name_channel::submit_name( const name_header& new_name_trx )
{
my->submit_name( new_name_trx );
}
void name_channel::submit_block( const name_block& block_to_submit )
{
auto id = block_to_submit.id();
uint64_t block_difficulty = bts::difficulty(id);
//ilog( "target: ${target} block ${block}", ("target",my->_name_db.target_difficulty())("block",block_difficulty) );
if( block_difficulty >= my->_name_db.target_difficulty() )
{
my->submit_block( block_to_submit );
}
else
{
submit_name( block_to_submit );
}
}
/**
* Performs a lookup in the internal database
*/
fc::optional<name_record> name_channel::lookup_name( const std::string& name )
{ try {
try {
name_trx last_trx = my->_name_db.fetch_trx( name_hash( name ) );
name_record name_rec;
name_rec.last_update = last_trx.utc_sec;
name_rec.pub_key = last_trx.key;
name_rec.age = last_trx.age;
name_rec.repute = my->_name_db.fetch_repute( name_hash(name) ); //last_trx.repute_points;
name_rec.revoked = last_trx.key == fc::ecc::public_key_data();
name_rec.name_hash = fc::to_hex((char*)&last_trx.name_hash, sizeof(last_trx.name_hash));
name_rec.name = name;
return name_rec;
}
catch ( const fc::key_not_found_exception& )
{
// expected, convert to null optional, all other errors should be
// thrown up the chain
}
return fc::optional<name_record>();
} FC_RETHROW_EXCEPTIONS( warn, "name: ${name}", ("name",name) ) }
uint32_t name_channel::get_head_block_number()const
{
return my->_name_db.head_block_num();
}
name_id_type name_channel::get_head_block_id()const
{
return my->_name_db.head_block_id();
}
std::vector<name_header> name_channel::get_pending_name_trxs()const
{
return my->_trx_broadcast_mgr.get_inventory_values();
}
} } // bts::bitname
| 42.710734 | 135 | 0.500966 |
9a08e490d7805cbe942677b40610478d836883e3 | 1,310 | cpp | C++ | 1 - BinarySearch/ABC-023-D.cpp | KagamisakiMashiro/SampleCode | 135dfb98d8c54f18ca5e9d79a9ace4124d690a52 | [
"Unlicense"
] | null | null | null | 1 - BinarySearch/ABC-023-D.cpp | KagamisakiMashiro/SampleCode | 135dfb98d8c54f18ca5e9d79a9ace4124d690a52 | [
"Unlicense"
] | null | null | null | 1 - BinarySearch/ABC-023-D.cpp | KagamisakiMashiro/SampleCode | 135dfb98d8c54f18ca5e9d79a9ace4124d690a52 | [
"Unlicense"
] | null | null | null | #include <cstdio>
#include <algorithm>
using namespace std;
long long int h[100000], s[100000];
bool checkSuccess(long long int n, long long int score)
{
long long int maxAcceptTime[100000];
for (long long int i = 0; i < n; ++i)
{
if (score - h[i] < 0)
{
return false;
}
maxAcceptTime[i] = (score - h[i]) / s[i];
}
sort(maxAcceptTime, maxAcceptTime + n);
for (long long int i = 0; i < n; ++i)
{
if (maxAcceptTime[i] < i)
{
return false;
}
}
return true;
}
long long int bs(long long int n, long long int minValue, long long int maxValue)
{
long long int mean;
while (minValue + 1 < maxValue)
{
mean = (minValue + maxValue) / 2;
if (checkSuccess(n, mean))
{
maxValue = mean;
}
else
{
minValue = mean;
}
}
return maxValue;
}
int main()
{
long long int n;
long long int maxValue = 0;
scanf("%lld", &n);
for (long long int i = 0; i < n; ++i)
{
scanf("%lld %lld", &h[i], &s[i]);
long long int temp = h[i] + s[i] * n;
if (temp > maxValue)
{
maxValue = temp;
}
}
printf("%lld\n", bs(n, 0, maxValue));
return 0;
}
| 20.46875 | 81 | 0.484733 |
9a0b33f2d7300aa1b7233ff1b54c5f6a5b33909c | 2,812 | cc | C++ | o3d/plugin/cross/blacklist.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | 11 | 2015-03-20T04:08:08.000Z | 2021-11-15T15:51:36.000Z | o3d/plugin/cross/blacklist.cc | changbai1980/chromium | c4625eefca763df86471d798ee5a4a054b4716ae | [
"BSD-3-Clause"
] | null | null | null | o3d/plugin/cross/blacklist.cc | changbai1980/chromium | c4625eefca763df86471d798ee5a4a054b4716ae | [
"BSD-3-Clause"
] | 1 | 2020-04-13T05:45:10.000Z | 2020-04-13T05:45:10.000Z | /*
* Copyright 2009, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
#include <fstream>
#include "plugin/cross/config.h"
#include "base/logging.h"
namespace o3d {
// Checks the driver GUID against the blacklist file. Returns true if there's a
// match [this driver is blacklisted] or if an IO error occurred. Check the
// state of input_file to determine which it was.
//
// Note that this function always returns false if the guid is 0, since it will
// be zero if we had a failure in reading it, and the user will already have
// been warned.
bool IsDriverBlacklisted(std::ifstream *input_file, unsigned int guid) {
if (!guid) {
return false;
}
*input_file >> std::ws;
while (input_file->good()) {
if (input_file->peek() == '#') {
char comment[256];
input_file->getline(comment, 256);
// If the line was too long for this to work, it'll set the failbit.
} else {
unsigned int id;
*input_file >> std::hex >> id;
if (id == guid) {
return true;
}
}
*input_file >> std::ws; // Skip whitespace here, to catch EOF cleanly.
}
if (input_file->fail()) {
LOG(ERROR) << "Failed to read the blacklisted driver file completely.";
return true;
}
CHECK(input_file->eof());
return false;
}
} // namespace o3d
| 38 | 80 | 0.713371 |
9a0bfaff0340d3a2b1aca283326d460b206a3dcf | 5,158 | cpp | C++ | webrtc-jni/src/main/cpp/src/media/video/VideoTrackDesktopSource.cpp | preciate/webrtc-java | 9073e12b57a74e8c89ed0950d41d29ab7f5cc691 | [
"Apache-2.0"
] | null | null | null | webrtc-jni/src/main/cpp/src/media/video/VideoTrackDesktopSource.cpp | preciate/webrtc-java | 9073e12b57a74e8c89ed0950d41d29ab7f5cc691 | [
"Apache-2.0"
] | null | null | null | webrtc-jni/src/main/cpp/src/media/video/VideoTrackDesktopSource.cpp | preciate/webrtc-java | 9073e12b57a74e8c89ed0950d41d29ab7f5cc691 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2019 Alex Andres
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "media/video/VideoTrackDesktopSource.h"
#include "Exception.h"
#include "api/video/i420_buffer.h"
#include "libyuv/convert.h"
#include "modules/desktop_capture/cropping_window_capturer.h"
#include "modules/desktop_capture/desktop_capture_options.h"
#include "modules/video_capture/video_capture_factory.h"
#include "third_party/libyuv/include/libyuv/video_common.h"
#include "system_wrappers/include/sleep.h"
#include "modules/desktop_capture/desktop_capturer.h"
#include "modules/desktop_capture/desktop_and_cursor_composer.h"
#include "modules/desktop_capture/mouse_cursor_monitor.h"
namespace jni
{
VideoTrackDesktopSource::VideoTrackDesktopSource() :
AdaptedVideoTrackSource(),
frameRate(20),
isCapturing(false),
sourceState(kInitializing),
sourceId(-1),
sourceIsWindow(false)
{
}
VideoTrackDesktopSource::~VideoTrackDesktopSource()
{
stop();
}
void VideoTrackDesktopSource::setSourceId(webrtc::DesktopCapturer::SourceId source, bool isWindow)
{
this->sourceId = source;
this->sourceIsWindow = isWindow;
}
void VideoTrackDesktopSource::setFrameRate(const uint16_t frameRate)
{
this->frameRate = frameRate;
}
void VideoTrackDesktopSource::start()
{
isCapturing = true;
captureThread = rtc::Thread::Create();
captureThread->Start();
captureThread->PostTask(RTC_FROM_HERE, [&] { capture(); });
}
void VideoTrackDesktopSource::stop()
{
if (isCapturing) {
isCapturing = false;
captureThread->Stop();
captureThread.reset();
}
}
bool VideoTrackDesktopSource::is_screencast() const {
return true;
}
absl::optional<bool> VideoTrackDesktopSource::needs_denoising() const {
return false;
}
webrtc::MediaSourceInterface::SourceState VideoTrackDesktopSource::state() const {
return sourceState;
}
bool VideoTrackDesktopSource::remote() const {
return false;
}
void VideoTrackDesktopSource::OnCaptureResult(webrtc::DesktopCapturer::Result result, std::unique_ptr<webrtc::DesktopFrame> frame)
{
if (result != webrtc::DesktopCapturer::Result::SUCCESS) {
return;
}
int width = frame->size().width();
int height = frame->size().height();
int64_t time = rtc::TimeMicros();
int adapted_width;
int adapted_height;
int crop_width;
int crop_height;
int crop_x;
int crop_y;
if (!AdaptFrame(width, height, time, &adapted_width, &adapted_height, &crop_width, &crop_height, &crop_x, &crop_y)) {
// Drop frame in order to respect frame rate constraint.
return;
}
if (!buffer || buffer->width() != width || buffer->height() != height) {
buffer = webrtc::I420Buffer::Create(width, height);
}
const int conversionResult = libyuv::ARGBToI420(frame->data(), frame->stride(),
buffer->MutableDataY(), buffer->StrideY(),
buffer->MutableDataU(), buffer->StrideU(),
buffer->MutableDataV(), buffer->StrideV(),
width, height);
if (conversionResult >= 0) {
if (adapted_width != width || adapted_height != height) {
// Video adapter has requested a down-scale. Allocate a new buffer and return scaled version.
rtc::scoped_refptr<webrtc::I420Buffer> scaled_buffer = webrtc::I420Buffer::Create(adapted_width, adapted_height);
scaled_buffer->ScaleFrom(*buffer);
OnFrame(webrtc::VideoFrame::Builder()
.set_video_frame_buffer(scaled_buffer)
.set_rotation(webrtc::kVideoRotation_0)
.set_timestamp_us(time)
.build());
}
else {
// No adaptations needed, just return the frame as is.
OnFrame(webrtc::VideoFrame::Builder()
.set_video_frame_buffer(buffer)
.set_rotation(webrtc::kVideoRotation_0)
.set_timestamp_us(time)
.build());
}
}
}
void VideoTrackDesktopSource::capture()
{
auto options = webrtc::DesktopCaptureOptions::CreateDefault();
// Enable desktop effects.
options.set_disable_effects(false);
#if defined(WEBRTC_WIN)
options.set_allow_directx_capturer(true);
options.set_allow_use_magnification_api(true);
#endif
std::unique_ptr<webrtc::DesktopCapturer> capturer;
if (sourceIsWindow) {
capturer.reset(new webrtc::DesktopAndCursorComposer(
webrtc::DesktopCapturer::CreateWindowCapturer(options),
options));
}
else {
capturer.reset(new webrtc::DesktopAndCursorComposer(
webrtc::DesktopCapturer::CreateScreenCapturer(options),
options));
}
if (!capturer->SelectSource(sourceId)) {
return;
}
capturer->Start(this);
sourceState = kLive;
int msPerFrame = 1000 / frameRate;
while (isCapturing) {
capturer->CaptureFrame();
webrtc::SleepMs(msPerFrame);
}
sourceState = kEnded;
}
} | 26.587629 | 131 | 0.727995 |
9a0d0b8acd952408bbe78205d4948eb94fb02aa4 | 13,907 | cxx | C++ | pandatool/src/xfile/xFileDataObject.cxx | kestred/panda3d | 16bfd3750f726a8831771b81649d18d087917fd5 | [
"PHP-3.01",
"PHP-3.0"
] | 3 | 2018-03-09T12:07:29.000Z | 2021-02-25T06:50:25.000Z | pandatool/src/xfile/xFileDataObject.cxx | Sinkay/panda3d | 16bfd3750f726a8831771b81649d18d087917fd5 | [
"PHP-3.01",
"PHP-3.0"
] | null | null | null | pandatool/src/xfile/xFileDataObject.cxx | Sinkay/panda3d | 16bfd3750f726a8831771b81649d18d087917fd5 | [
"PHP-3.01",
"PHP-3.0"
] | null | null | null | // Filename: xFileDataObject.cxx
// Created by: drose (03Oct04)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University. All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license. You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////
#include "xFileDataObject.h"
#include "xFileTemplate.h"
#include "xFile.h"
#include "xFileDataNodeTemplate.h"
#include "xFileDataObjectInteger.h"
#include "xFileDataObjectDouble.h"
#include "xFileDataObjectString.h"
#include "config_xfile.h"
#include "indent.h"
TypeHandle XFileDataObject::_type_handle;
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::Destructor
// Access: Public, Virtual
// Description:
////////////////////////////////////////////////////////////////////
XFileDataObject::
~XFileDataObject() {
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::is_complex_object
// Access: Public, Virtual
// Description: Returns true if this kind of data object is a complex
// object that can hold nested data elements, false
// otherwise.
////////////////////////////////////////////////////////////////////
bool XFileDataObject::
is_complex_object() const {
return false;
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::get_type_name
// Access: Public, Virtual
// Description: Returns a string that represents the type of object
// this data object represents.
////////////////////////////////////////////////////////////////////
string XFileDataObject::
get_type_name() const {
return get_type().get_name();
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::add_int
// Access: Public
// Description: Appends a new integer value to the data object, if it
// makes sense to do so. Normally, this is valid only
// for a DataObjectArray, or in certain special cases for
// a DataNodeTemplate.
////////////////////////////////////////////////////////////////////
XFileDataObject &XFileDataObject::
add_int(int int_value) {
XFileDataObject *object =
new XFileDataObjectInteger(get_data_def(), int_value);
add_element(object);
return *object;
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::add_double
// Access: Public
// Description: Appends a new floating-point value to the data
// object, if it makes sense to do so. Normally, this
// is valid only for a DataObjectArray, or in certain
// special cases for a DataNodeTemplate.
////////////////////////////////////////////////////////////////////
XFileDataObject &XFileDataObject::
add_double(double double_value) {
XFileDataObject *object =
new XFileDataObjectDouble(get_data_def(), double_value);
add_element(object);
return *object;
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::add_string
// Access: Public
// Description: Appends a new string value to the data object, if it
// makes sense to do so. Normally, this is valid only
// for a DataObjectArray, or in certain special cases for
// a DataNodeTemplate.
////////////////////////////////////////////////////////////////////
XFileDataObject &XFileDataObject::
add_string(const string &string_value) {
XFileDataObject *object =
new XFileDataObjectString(get_data_def(), string_value);
add_element(object);
return *object;
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::add_Vector
// Access: Public
// Description: Appends a new Vector instance.
////////////////////////////////////////////////////////////////////
XFileDataObject &XFileDataObject::
add_Vector(XFile *x_file, const LVecBase3d &vector) {
XFileTemplate *xtemplate = XFile::find_standard_template("Vector");
nassertr(xtemplate != (XFileTemplate *)NULL, *this);
XFileDataNodeTemplate *node =
new XFileDataNodeTemplate(x_file, "", xtemplate);
add_element(node);
node->zero_fill();
node->set(vector);
return *node;
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::add_MeshFace
// Access: Public
// Description: Appends a new MeshFace instance.
////////////////////////////////////////////////////////////////////
XFileDataObject &XFileDataObject::
add_MeshFace(XFile *x_file) {
XFileTemplate *xtemplate = XFile::find_standard_template("MeshFace");
nassertr(xtemplate != (XFileTemplate *)NULL, *this);
XFileDataNodeTemplate *node =
new XFileDataNodeTemplate(x_file, "", xtemplate);
add_element(node);
node->zero_fill();
return *node;
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::add_IndexedColor
// Access: Public
// Description: Appends a new IndexedColor instance.
////////////////////////////////////////////////////////////////////
XFileDataObject &XFileDataObject::
add_IndexedColor(XFile *x_file, int index, const LColor &color) {
XFileTemplate *xtemplate = XFile::find_standard_template("IndexedColor");
nassertr(xtemplate != (XFileTemplate *)NULL, *this);
XFileDataNodeTemplate *node =
new XFileDataNodeTemplate(x_file, "", xtemplate);
add_element(node);
node->zero_fill();
(*node)["index"] = index;
(*node)["indexColor"] = LCAST(double, color);
return *node;
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::add_Coords2d
// Access: Public
// Description: Appends a new Coords2d instance.
////////////////////////////////////////////////////////////////////
XFileDataObject &XFileDataObject::
add_Coords2d(XFile *x_file, const LVecBase2d &coords) {
XFileTemplate *xtemplate = XFile::find_standard_template("Coords2d");
nassertr(xtemplate != (XFileTemplate *)NULL, *this);
XFileDataNodeTemplate *node =
new XFileDataNodeTemplate(x_file, "", xtemplate);
add_element(node);
node->zero_fill();
node->set(coords);
return *node;
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::add_element
// Access: Public, Virtual
// Description: Adds the indicated element as a nested data element,
// if this data object type supports it. Returns true
// if added successfully, false if the data object type
// does not support nested data elements.
////////////////////////////////////////////////////////////////////
bool XFileDataObject::
add_element(XFileDataObject *element) {
return false;
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::output_data
// Access: Public, Virtual
// Description: Writes a suitable representation of this node to an
// .x file in text mode.
////////////////////////////////////////////////////////////////////
void XFileDataObject::
output_data(ostream &out) const {
out << "(" << get_type() << "::output_data() not implemented.)";
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::write_data
// Access: Public, Virtual
// Description: Writes a suitable representation of this node to an
// .x file in text mode.
////////////////////////////////////////////////////////////////////
void XFileDataObject::
write_data(ostream &out, int indent_level, const char *) const {
indent(out, indent_level)
<< "(" << get_type() << "::write_data() not implemented.)\n";
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::set_int_value
// Access: Protected, Virtual
// Description: Sets the object's value as an integer, if this is
// legal.
////////////////////////////////////////////////////////////////////
void XFileDataObject::
set_int_value(int int_value) {
xfile_cat.error()
<< get_type_name() << " does not support integer values.\n";
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::set_double_value
// Access: Protected, Virtual
// Description: Sets the object's value as a floating-point number,
// if this is legal.
////////////////////////////////////////////////////////////////////
void XFileDataObject::
set_double_value(double double_value) {
xfile_cat.error()
<< get_type_name() << " does not support floating-point values.\n";
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::set_string_value
// Access: Protected, Virtual
// Description: Sets the object's value as a string, if this is
// legal.
////////////////////////////////////////////////////////////////////
void XFileDataObject::
set_string_value(const string &string_value) {
xfile_cat.error()
<< get_type_name() << " does not support string values.\n";
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::store_double_array
// Access: Protected
// Description: Stores the indicated array of doubles in the nested
// elements within this object. There must be exactly
// the indicated number of nested values, and they must
// all accept a double.
////////////////////////////////////////////////////////////////////
void XFileDataObject::
store_double_array(int num_elements, const double *values) {
if (get_num_elements() != num_elements) {
xfile_cat.error()
<< get_type_name() << " does not accept "
<< num_elements << " values.\n";
return;
}
for (int i = 0; i < num_elements; i++) {
get_element(i)->set_double_value(values[i]);
}
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::get_int_value
// Access: Protected, Virtual
// Description: Returns the object's representation as an integer, if
// it has one.
////////////////////////////////////////////////////////////////////
int XFileDataObject::
get_int_value() const {
return 0;
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::get_double_value
// Access: Protected, Virtual
// Description: Returns the object's representation as a double, if
// it has one.
////////////////////////////////////////////////////////////////////
double XFileDataObject::
get_double_value() const {
return 0.0;
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::get_string_value
// Access: Protected, Virtual
// Description: Returns the object's representation as a string, if
// it has one.
////////////////////////////////////////////////////////////////////
string XFileDataObject::
get_string_value() const {
return string();
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::get_double_array
// Access: Protected
// Description: Fills the indicated array of doubles with the values
// from the nested elements within this object. There
// must be exactly the indicated number of nested
// values, and they must all return a double.
////////////////////////////////////////////////////////////////////
void XFileDataObject::
get_double_array(int num_elements, double *values) const {
if (get_num_elements() != num_elements) {
xfile_cat.error()
<< get_type_name() << " does not contain "
<< num_elements << " values.\n";
return;
}
for (int i = 0; i < num_elements; i++) {
values[i] = ((XFileDataObject *)this)->get_element(i)->get_double_value();
}
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::get_num_elements
// Access: Protected, Virtual
// Description: Returns the number of nested data elements within the
// object. This may be, e.g. the size of the array, if
// it is an array.
////////////////////////////////////////////////////////////////////
int XFileDataObject::
get_num_elements() const {
return 0;
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::get_element
// Access: Protected, Virtual
// Description: Returns the nth nested data element within the
// object.
////////////////////////////////////////////////////////////////////
XFileDataObject *XFileDataObject::
get_element(int n) {
xfile_cat.warning()
<< "Looking for [" << n << "] within data object of type "
<< get_type_name() << ", does not support nested objects.\n";
return NULL;
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::get_element
// Access: Protected, Virtual
// Description: Returns the nested data element within the
// object that has the indicated name.
////////////////////////////////////////////////////////////////////
XFileDataObject *XFileDataObject::
get_element(const string &name) {
xfile_cat.warning()
<< "Looking for [\"" << name << "\"] within data object of type "
<< get_type_name() << ", does not support nested objects.\n";
return NULL;
}
| 37.485175 | 78 | 0.511829 |
9a0df3b530d67be768a82f6b0b440593cccdff56 | 11,699 | hpp | C++ | src/vanillaswap.hpp | quantlibnode/quantlibnode | b50348131af77a2b6c295f44ef3245daf05c4afc | [
"MIT"
] | 27 | 2016-11-19T16:51:21.000Z | 2021-09-08T16:44:15.000Z | src/vanillaswap.hpp | quantlibnode/quantlibnode | b50348131af77a2b6c295f44ef3245daf05c4afc | [
"MIT"
] | 1 | 2016-12-28T16:38:38.000Z | 2017-02-17T05:32:13.000Z | src/vanillaswap.hpp | quantlibnode/quantlibnode | b50348131af77a2b6c295f44ef3245daf05c4afc | [
"MIT"
] | 10 | 2016-12-28T02:31:38.000Z | 2021-06-15T09:02:07.000Z | /*
Copyright (C) 2016 -2017 Jerry Jin
*/
#ifndef vanillaswap_h
#define vanillaswap_h
#include <nan.h>
#include <string>
#include <queue>
#include <utility>
#include "../quantlibnode.hpp"
#include <oh/objecthandler.hpp>
using namespace node;
using namespace v8;
using namespace std;
class VanillaSwapWorker : public Nan::AsyncWorker {
public:
string mObjectID;
string mPayerReceiver;
double mNominal;
string mFixSchedule;
double mFixedRate;
string mFixDayCounter;
string mFloatingLegSchedule;
string mIborIndex;
double mSpread;
string mFloatingLegDayCounter;
string mPaymentConvention;
string mReturnValue;
string mError;
VanillaSwapWorker(
Nan::Callback *callback
,string ObjectID
,string PayerReceiver
,double Nominal
,string FixSchedule
,double FixedRate
,string FixDayCounter
,string FloatingLegSchedule
,string IborIndex
,double Spread
,string FloatingLegDayCounter
,string PaymentConvention
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
,mPayerReceiver(PayerReceiver)
,mNominal(Nominal)
,mFixSchedule(FixSchedule)
,mFixedRate(FixedRate)
,mFixDayCounter(FixDayCounter)
,mFloatingLegSchedule(FloatingLegSchedule)
,mIborIndex(IborIndex)
,mSpread(Spread)
,mFloatingLegDayCounter(FloatingLegDayCounter)
,mPaymentConvention(PaymentConvention)
{
};
//~VanillaSwapWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class MakeVanillaSwapWorker : public Nan::AsyncWorker {
public:
string mObjectID;
ObjectHandler::property_t mSettlDays;
string mSwapTenor;
string mIborIndex;
double mFixedRate;
string mForwardStart;
string mFixDayCounter;
double mSpread;
string mPricingEngineID;
string mReturnValue;
string mError;
MakeVanillaSwapWorker(
Nan::Callback *callback
,string ObjectID
,ObjectHandler::property_t SettlDays
,string SwapTenor
,string IborIndex
,double FixedRate
,string ForwardStart
,string FixDayCounter
,double Spread
,string PricingEngineID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
,mSettlDays(SettlDays)
,mSwapTenor(SwapTenor)
,mIborIndex(IborIndex)
,mFixedRate(FixedRate)
,mForwardStart(ForwardStart)
,mFixDayCounter(FixDayCounter)
,mSpread(Spread)
,mPricingEngineID(PricingEngineID)
{
};
//~MakeVanillaSwapWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class MakeIMMSwapWorker : public Nan::AsyncWorker {
public:
string mObjectID;
string mSwapTenor;
string mIborIndex;
double mFixedRate;
ObjectHandler::property_t mFirstImmDate;
string mFixDayCounter;
double mSpread;
string mPricingEngineID;
string mReturnValue;
string mError;
MakeIMMSwapWorker(
Nan::Callback *callback
,string ObjectID
,string SwapTenor
,string IborIndex
,double FixedRate
,ObjectHandler::property_t FirstImmDate
,string FixDayCounter
,double Spread
,string PricingEngineID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
,mSwapTenor(SwapTenor)
,mIborIndex(IborIndex)
,mFixedRate(FixedRate)
,mFirstImmDate(FirstImmDate)
,mFixDayCounter(FixDayCounter)
,mSpread(Spread)
,mPricingEngineID(PricingEngineID)
{
};
//~MakeIMMSwapWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapFromSwapIndexWorker : public Nan::AsyncWorker {
public:
string mObjectID;
string mSwapIndex;
ObjectHandler::property_t mFixingDate;
string mReturnValue;
string mError;
VanillaSwapFromSwapIndexWorker(
Nan::Callback *callback
,string ObjectID
,string SwapIndex
,ObjectHandler::property_t FixingDate
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
,mSwapIndex(SwapIndex)
,mFixingDate(FixingDate)
{
};
//~VanillaSwapFromSwapIndexWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapFromSwapRateHelperWorker : public Nan::AsyncWorker {
public:
string mObjectID;
string mSwapRateHelper;
string mReturnValue;
string mError;
VanillaSwapFromSwapRateHelperWorker(
Nan::Callback *callback
,string ObjectID
,string SwapRateHelper
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
,mSwapRateHelper(SwapRateHelper)
{
};
//~VanillaSwapFromSwapRateHelperWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapFixedLegBPSWorker : public Nan::AsyncWorker {
public:
string mObjectID;
double mReturnValue;
string mError;
VanillaSwapFixedLegBPSWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~VanillaSwapFixedLegBPSWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapFixedLegNPVWorker : public Nan::AsyncWorker {
public:
string mObjectID;
double mReturnValue;
string mError;
VanillaSwapFixedLegNPVWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~VanillaSwapFixedLegNPVWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapFairRateWorker : public Nan::AsyncWorker {
public:
string mObjectID;
double mReturnValue;
string mError;
VanillaSwapFairRateWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~VanillaSwapFairRateWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapFloatingLegBPSWorker : public Nan::AsyncWorker {
public:
string mObjectID;
double mReturnValue;
string mError;
VanillaSwapFloatingLegBPSWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~VanillaSwapFloatingLegBPSWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapFloatingLegNPVWorker : public Nan::AsyncWorker {
public:
string mObjectID;
double mReturnValue;
string mError;
VanillaSwapFloatingLegNPVWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~VanillaSwapFloatingLegNPVWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapFairSpreadWorker : public Nan::AsyncWorker {
public:
string mObjectID;
double mReturnValue;
string mError;
VanillaSwapFairSpreadWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~VanillaSwapFairSpreadWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapTypeWorker : public Nan::AsyncWorker {
public:
string mObjectID;
string mReturnValue;
string mError;
VanillaSwapTypeWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~VanillaSwapTypeWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapNominalWorker : public Nan::AsyncWorker {
public:
string mObjectID;
double mReturnValue;
string mError;
VanillaSwapNominalWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~VanillaSwapNominalWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapFixedRateWorker : public Nan::AsyncWorker {
public:
string mObjectID;
double mReturnValue;
string mError;
VanillaSwapFixedRateWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~VanillaSwapFixedRateWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapFixedDayCountWorker : public Nan::AsyncWorker {
public:
string mObjectID;
string mReturnValue;
string mError;
VanillaSwapFixedDayCountWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~VanillaSwapFixedDayCountWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapSpreadWorker : public Nan::AsyncWorker {
public:
string mObjectID;
double mReturnValue;
string mError;
VanillaSwapSpreadWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~VanillaSwapSpreadWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapFloatingDayCountWorker : public Nan::AsyncWorker {
public:
string mObjectID;
string mReturnValue;
string mError;
VanillaSwapFloatingDayCountWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~VanillaSwapFloatingDayCountWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapPaymentConventionWorker : public Nan::AsyncWorker {
public:
string mObjectID;
string mReturnValue;
string mError;
VanillaSwapPaymentConventionWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~VanillaSwapPaymentConventionWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapFixedLegAnalysisWorker : public Nan::AsyncWorker {
public:
string mObjectID;
ObjectHandler::property_t mAfterDate;
std::vector< std::vector<string> > mReturnValue;
string mError;
VanillaSwapFixedLegAnalysisWorker(
Nan::Callback *callback
,string ObjectID
,ObjectHandler::property_t AfterDate
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
,mAfterDate(AfterDate)
{
};
//~VanillaSwapFixedLegAnalysisWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapFloatingLegAnalysisWorker : public Nan::AsyncWorker {
public:
string mObjectID;
ObjectHandler::property_t mAfterDate;
std::vector< std::vector<string> > mReturnValue;
string mError;
VanillaSwapFloatingLegAnalysisWorker(
Nan::Callback *callback
,string ObjectID
,ObjectHandler::property_t AfterDate
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
,mAfterDate(AfterDate)
{
};
//~VanillaSwapFloatingLegAnalysisWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
#endif
| 17.409226 | 70 | 0.651081 |
9a15237559ffecc8d6c93fc1ef2ed229aca7c43e | 981 | cpp | C++ | src/apps/processors/envelope/EnvelopeController.cpp | pigatron-industries/xen_filter | 10de7c617b59e02c29b448764d60f503f14dd564 | [
"Unlicense"
] | null | null | null | src/apps/processors/envelope/EnvelopeController.cpp | pigatron-industries/xen_filter | 10de7c617b59e02c29b448764d60f503f14dd564 | [
"Unlicense"
] | null | null | null | src/apps/processors/envelope/EnvelopeController.cpp | pigatron-industries/xen_filter | 10de7c617b59e02c29b448764d60f503f14dd564 | [
"Unlicense"
] | null | null | null | #include "EnvelopeController.h"
#define LEFT 0
#define RIGHT 1
void EnvelopeController::init(float sampleRate) {
envelope.init(sampleRate, 3, 1, false);
envelope.setPoint(0, deprecated::Point(0, 0));
envelope.setPoint(1, deprecated::Point(1, 1));
envelope.setPoint(2, deprecated::Point(2, 0));
displayPage.initTitle("Envelope", "ENV ");
}
void EnvelopeController::update() {
if(gateInput.update()) {
if(gateInput.isTriggeredOn()) {
envelope.trigger();
}
}
if(attackTimeInput.update()) {
envelope.setSegmentLength(0, attackTimeInput.getValue());
}
if(decayTimeInput.update()) {
envelope.setSegmentLength(1, decayTimeInput.getValue());
}
}
void EnvelopeController::process(float **in, float **out, size_t size) {
for (size_t i = 0; i < size; i++) {
float gain = envelope.process();
out[LEFT][i] = in[LEFT][i] * gain;
out[RIGHT][i] = in[RIGHT][i] * gain;
}
} | 27.25 | 72 | 0.622834 |
9a178cf3d5bce7a74afea64687c86095bce351ca | 5,123 | cc | C++ | test/horver_correlation_test.cc | gomezpirry/aom | 1709156644cdd104842401e7b11721ce2913a049 | [
"BSD-2-Clause"
] | null | null | null | test/horver_correlation_test.cc | gomezpirry/aom | 1709156644cdd104842401e7b11721ce2913a049 | [
"BSD-2-Clause"
] | null | null | null | test/horver_correlation_test.cc | gomezpirry/aom | 1709156644cdd104842401e7b11721ce2913a049 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2018, Alliance for Open Media. All rights reserved
*
* This source code is subject to the terms of the BSD 2 Clause License and
* the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
* was not distributed with this source code in the LICENSE file, you can
* obtain it at www.aomedia.org/license/software. If the Alliance for Open
* Media Patent License 1.0 was not distributed with this source code in the
* PATENTS file, you can obtain it at www.aomedia.org/license/patent.
*/
#include <vector>
#include "third_party/googletest/src/googletest/include/gtest/gtest.h"
#include "test/function_equivalence_test.h"
#include "test/register_state_check.h"
#include "config/aom_config.h"
#include "config/aom_dsp_rtcd.h"
#include "config/av1_rtcd.h"
#include "aom/aom_integer.h"
#include "av1/encoder/rdopt.h"
using libaom_test::FunctionEquivalenceTest;
namespace {
typedef void (*horver_Func)(const int16_t *diff, int stride, int w, int h,
float *hcorr, float *vcorr);
typedef libaom_test::FuncParam<horver_Func> TestFuncs;
typedef ::testing::tuple<const horver_Func> HorverTestParam;
class HorverTest : public ::testing::TestWithParam<HorverTestParam> {
public:
virtual void SetUp() {
data_buf = (int16_t *)aom_malloc(MAX_SB_SQUARE * sizeof(int16_t));
target_func_ = GET_PARAM(0);
}
virtual void TearDown() { aom_free(data_buf); }
void runHorverTest(void);
void runHorverTest_ExtremeValues(void);
void runHorverSpeedTest(int run_times);
private:
horver_Func target_func_;
ACMRandom rng_;
int16_t *data_buf;
};
void HorverTest::runHorverTest(void) {
for (int block_size = 0; block_size < BLOCK_SIZES_ALL; block_size++) {
const int w = block_size_wide[block_size];
const int h = block_size_high[block_size];
for (int iter = 0; iter < 1000 && !HasFatalFailure(); ++iter) {
float hcorr_ref = 0.0, vcorr_ref = 0.0;
float hcorr_test = 0.0, vcorr_test = 0.0;
for (int i = 0; i < MAX_SB_SQUARE; ++i) {
data_buf[i] = (rng_.Rand16() % (1 << 12)) - (1 << 11);
}
av1_get_horver_correlation_full_c(data_buf, MAX_SB_SIZE, w, h, &hcorr_ref,
&vcorr_ref);
target_func_(data_buf, MAX_SB_SIZE, w, h, &hcorr_test, &vcorr_test);
ASSERT_LE(fabs(hcorr_ref - hcorr_test), 1e-6)
<< "hcorr incorrect (" << w << "x" << h << ")";
ASSERT_LE(fabs(vcorr_ref - vcorr_test), 1e-6)
<< "vcorr incorrect (" << w << "x" << h << ")";
}
// printf("(%3dx%-3d) passed\n", w, h);
}
}
void HorverTest::runHorverSpeedTest(int run_times) {
for (int i = 0; i < MAX_SB_SQUARE; ++i) {
data_buf[i] = rng_.Rand16() % (1 << 12);
}
for (int block_size = 0; block_size < BLOCK_SIZES_ALL; block_size++) {
const int w = block_size_wide[block_size];
const int h = block_size_high[block_size];
float hcorr_ref = 0.0, vcorr_ref = 0.0;
float hcorr_test = 0.0, vcorr_test = 0.0;
aom_usec_timer timer;
aom_usec_timer_start(&timer);
for (int i = 0; i < run_times; ++i) {
av1_get_horver_correlation_full_c(data_buf, MAX_SB_SIZE, w, h, &hcorr_ref,
&vcorr_ref);
}
aom_usec_timer_mark(&timer);
const double time1 = static_cast<double>(aom_usec_timer_elapsed(&timer));
aom_usec_timer_start(&timer);
for (int i = 0; i < run_times; ++i) {
target_func_(data_buf, MAX_SB_SIZE, w, h, &hcorr_test, &vcorr_test);
}
aom_usec_timer_mark(&timer);
const double time2 = static_cast<double>(aom_usec_timer_elapsed(&timer));
printf("%3dx%-3d:%7.2f/%7.2fns (%3.2f)\n", w, h, time1, time2,
time1 / time2);
}
}
void HorverTest::runHorverTest_ExtremeValues(void) {
for (int i = 0; i < MAX_SB_SQUARE; ++i) {
// Most of get_horver_test is squaring and summing, so simply saturating
// the whole buffer is mostly likely to cause an overflow.
data_buf[i] = (1 << 12) - 1;
}
for (int block_size = 0; block_size < BLOCK_SIZES_ALL; block_size++) {
const int w = block_size_wide[block_size];
const int h = block_size_high[block_size];
float hcorr_ref = 0.0, vcorr_ref = 0.0;
float hcorr_test = 0.0, vcorr_test = 0.0;
av1_get_horver_correlation_full_c(data_buf, MAX_SB_SIZE, w, h, &hcorr_ref,
&vcorr_ref);
target_func_(data_buf, MAX_SB_SIZE, w, h, &hcorr_test, &vcorr_test);
ASSERT_LE(fabs(hcorr_ref - hcorr_test), 1e-6) << "hcorr incorrect";
ASSERT_LE(fabs(vcorr_ref - vcorr_test), 1e-6) << "vcorr incorrect";
}
}
TEST_P(HorverTest, RandomValues) { runHorverTest(); }
TEST_P(HorverTest, ExtremeValues) { runHorverTest_ExtremeValues(); }
TEST_P(HorverTest, DISABLED_Speed) { runHorverSpeedTest(100000); }
#if HAVE_SSE4_1
INSTANTIATE_TEST_CASE_P(
SSE4_1, HorverTest,
::testing::Values(av1_get_horver_correlation_full_sse4_1));
#endif // HAVE_SSE4_1
#if HAVE_AVX2
INSTANTIATE_TEST_CASE_P(
AVX2, HorverTest, ::testing::Values(av1_get_horver_correlation_full_avx2));
#endif // HAVE_AVX2
} // namespace
| 34.153333 | 80 | 0.670506 |
9a17d8c1302934c72bf6ee801a894a9858b13368 | 2,505 | cpp | C++ | src/logic/torrentdetailscontentview.cpp | herokukuki/ydyd | 942a98158e139f0bb00a837b762492bdaaffb94c | [
"MIT"
] | null | null | null | src/logic/torrentdetailscontentview.cpp | herokukuki/ydyd | 942a98158e139f0bb00a837b762492bdaaffb94c | [
"MIT"
] | null | null | null | src/logic/torrentdetailscontentview.cpp | herokukuki/ydyd | 942a98158e139f0bb00a837b762492bdaaffb94c | [
"MIT"
] | null | null | null | #include "torrentdetailscontentview.h"
#include <QMenu>
#include <QFileInfo>
#include <QDir>
#include "utilities/utils.h"
#include "utilities/filesystem_utils.h"
#include "torrentcontentmodel.h"
#include "global_functions.h"
TorrentDetailsContentView::TorrentDetailsContentView(QWidget* parent /*= 0*/): QTreeView(parent)
{
setContextMenuPolicy(Qt::CustomContextMenu);
VERIFY(connect(this, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(on_showTreeTorentContextMenu(const QPoint&))));
}
void TorrentDetailsContentView::setModel(TorrentContentFilterModel* a_model)
{
QTreeView::setModel(a_model);
VERIFY(connect(this, SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(on_ItemOpenFolder())));
}
TorrentContentFilterModel* TorrentDetailsContentView::model()
{
return static_cast<TorrentContentFilterModel*>(QTreeView::model());
}
void TorrentDetailsContentView::on_showTreeTorentContextMenu(const QPoint& pos)
{
QModelIndex index = indexAt(pos);
if (index.isValid())
{
QMenu menu;
menu.setObjectName(QStringLiteral("TorrentDetailsContextMenu"));
menu.addAction(QIcon(), tr("Open in folder"), this, SLOT(on_ItemOpenFolder()));
menu.addAction(QIcon(), tr("Open File"), this, SLOT(on_ItemOpenFile()));
menu.exec(QCursor::pos());
}
}
void TorrentDetailsContentView::on_ItemOpenFolder()
{
QModelIndex curr_index = selectionModel()->currentIndex();
if (!curr_index.isValid())
{
return;
}
TorrentContentModelItem* torrentItem = model()->getTorrentContentModelItem(curr_index);
QString pathFile = torrentItem->getPath();
if (pathFile.isEmpty())
{
pathFile = torrentItem->getName();
}
QString savePath = model()->model()->getSavePath();
QString filename = savePath + pathFile;
QFileInfo downloadFile(filename);
utilities::SelectFile(downloadFile.absoluteFilePath(), downloadFile.dir().path());
}
void TorrentDetailsContentView::on_ItemOpenFile()
{
QModelIndex curr_index = selectionModel()->currentIndex();
if (!curr_index.isValid())
{
return;
}
TorrentContentModelItem* torrentItem = model()->getTorrentContentModelItem(curr_index);
QString pathFile = torrentItem->getPath();
QString savePath = model()->model()->getSavePath();
QString filename = savePath + pathFile;
if (torrentItem->isFolder() || !QFile::exists(filename))
{
return;
}
global_functions::openFile(filename);
}
| 30.54878 | 134 | 0.712974 |
9a184ea67dbdf0c85121b89294df837fce391a3a | 4,618 | hh | C++ | include/LACE/LpcResiduals.hh | petrmanek/LACE | 5e189bb871a47972490fe2888a60df876cb6b120 | [
"BSL-1.0"
] | 1 | 2019-03-14T13:13:34.000Z | 2019-03-14T13:13:34.000Z | include/LACE/LpcResiduals.hh | petrmanek/LACE | 5e189bb871a47972490fe2888a60df876cb6b120 | [
"BSL-1.0"
] | null | null | null | include/LACE/LpcResiduals.hh | petrmanek/LACE | 5e189bb871a47972490fe2888a60df876cb6b120 | [
"BSL-1.0"
] | 2 | 2018-04-19T21:29:46.000Z | 2019-03-14T13:37:26.000Z | // Copyright University of Warwick 2014
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// Authors:
// John Back
/*! \file LpcResiduals.hh
\brief File containing the declaration of the LpcResiduals class
*/
/*! \class LpcResiduals
\brief Class that stores the lpc-to-hit residuals
*/
#ifndef LPC_RESIDUALS_HH
#define LPC_RESIDUALS_HH
#include <Eigen/Dense>
#include <vector>
class LpcResiduals {
public:
//! Constructor using residual arrays stored as Eigen vector objects
/*!
\param [in] lpcResiduals the average residual over all hits for each lpc point
\param [in] hitResiduals the residual of the nearest lpc point for each hit
\param [in] lpcWeightRes the average weighted residual over all hits for each lpc point
\param [in] hitWeightRes the weighted residual of the nearest lpc point for each hit
\param [in] hitNearestLpc the nearest lpc point index number for each hit
*/
LpcResiduals(const Eigen::VectorXd& lpcResiduals,
const Eigen::VectorXd& hitResiduals,
const Eigen::VectorXd& lpcWeightRes,
const Eigen::VectorXd& hitWeightRes,
const Eigen::VectorXi& hitNearestLpc);
//! Default, empty constructor
LpcResiduals();
//! Copy constructor
/*!
\param [in] other The LpcResiduals object to copy
*/
LpcResiduals(const LpcResiduals& other);
//! Assignment operator
/*!
\param [in] other The LpcResiduals used for the assignment
*/
LpcResiduals& operator=(const LpcResiduals& other);
//! Destructor
virtual ~LpcResiduals();
// Accessors
//! Get the average residual over all hits for each lpc point
/*!
\returns an Eigen VectorXd of the average residual with the hits per lpc point
*/
Eigen::VectorXd getLpcResiduals() const {return lpcResiduals_;}
//! Get the residual of the nearest lpc point for each hit
/*!
\returns an Eigen VectorXd of the residual of the nearest lpc point for each hit
*/
Eigen::VectorXd getHitResiduals() const {return hitResiduals_;}
//! Get the average weighted residual over all hits for each lpc point
/*!
\returns an Eigen VectorXd of the average weighted residual with the hits per lpc point
*/
Eigen::VectorXd getWeightedLpcResiduals() const {return lpcWeightRes_;}
//! Get the weighted residual of the nearest lpc point for each hit
/*!
\returns an Eigen VectorXd of the weighted residual of the nearest lpc point for each hit
*/
Eigen::VectorXd getWeightedHitResiduals() const {return hitWeightRes_;}
//! Get the nearest lpc point index number for each hit
/*!
\returns an Eigen VectorXi of the index number of the nearest lpc point for each hit
*/
Eigen::VectorXi getHitNearestLpc() const {return hitNearestLpc_;}
// STL vector versions of the above access functions
//! Get the average residual over all hits for each lpc point
/*!
\returns a STL vector of the average residual with the hits per lpc point
*/
std::vector<double> getLpcResVector() const;
//! Get the residual of the nearest lpc point for each hit
/*!
\returns a STL vector of the residual of the nearest lpc point for each hit
*/
std::vector<double> getHitResVector() const;
//! Get the average weighted residual over all hits for each lpc point
/*!
\returns a STL vector of the average weighted residual with the hits per lpc point
*/
std::vector<double> getWeightedLpcResVector() const;
//! Get the weighted residual of the nearest lpc point for each hit
/*!
\returns a STL vector of the weighted residual of the nearest lpc point for each hit
*/
std::vector<double> getWeightedHitResVector() const;
//! Get the nearest lpc point index number for each hit
/*!
\returns a STL vector of the index number of the nearest lpc point for each hit
*/
std::vector<int> getHitNearestLpcVector() const;
protected:
private:
//! The average residual over all hits for each lpc point
Eigen::VectorXd lpcResiduals_;
//! The residual of the nearest lpc point for each hit
Eigen::VectorXd hitResiduals_;
//! The average weighted residual over all hits for each lpc point
Eigen::VectorXd lpcWeightRes_;
//! The weighted residual of the nearest lpc point for each hit
Eigen::VectorXd hitWeightRes_;
//! The nearest lpc point index number for each hit
Eigen::VectorXi hitNearestLpc_;
};
#endif
| 31.630137 | 95 | 0.699654 |
9a18a9a0f986855045c83f581bcf07ec3460d0a4 | 7,376 | cpp | C++ | server.cpp | AnuragDPawar/Centralized-Multi-User-Concurrent-Bank-Account-Manager | c7a8f0b7a61636855c1207f50f82ab554fe89a5f | [
"MIT"
] | null | null | null | server.cpp | AnuragDPawar/Centralized-Multi-User-Concurrent-Bank-Account-Manager | c7a8f0b7a61636855c1207f50f82ab554fe89a5f | [
"MIT"
] | null | null | null | server.cpp | AnuragDPawar/Centralized-Multi-User-Concurrent-Bank-Account-Manager | c7a8f0b7a61636855c1207f50f82ab554fe89a5f | [
"MIT"
] | null | null | null | #include <arpa/inet.h>
#include <libexplain/read.h>
#include <netdb.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <fstream>
#include <iomanip> //to format the float value
#include <iostream>
#include <sstream> //for appending operations
#include <string>
#define MAX 200
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
using namespace std;
int s_accout_number[MAX];
float s_amount[MAX];
string name[MAX];
char *c_ip;
int filectr;
void *calculate_interest(void *arg) {
while (true) {
sleep(60);
cout << "\nAdding 10% Interest in every account after every 60 seconds\n";
for (int i = 0; i < filectr; i++) {
pthread_mutex_lock(&lock);
s_amount[i] = s_amount[i] * 1.1;
pthread_mutex_unlock(&lock);
}
}
}
void *operations(void *arg) {
stringstream amt_stream;
stringstream amt_stream1;
int *client_socket = (int *)arg;
int accout_number;
int timestamp;
int amount;
char transaction_type[1];
char buff[4096];
string msg_to_client;
cout << "Client connected"
<< " " << *client_socket << " "
<< "Thread ID"
<< " " << pthread_self() << endl;
int n;
bzero(buff, 4096);
int locked = 0;
while (n = read(*client_socket, buff, 4096))
{
if (n < 0)
{
cout << "Error" << endl;
break;
}
c_ip = strtok(buff, " ");
if (c_ip)
{
timestamp = atoi(c_ip);
}
c_ip = strtok(NULL, " ");
if (c_ip)
{
accout_number = atoi(c_ip);
}
c_ip = strtok(NULL, " ");
if (c_ip)
{
strcpy(transaction_type, c_ip);
}
c_ip = strtok(NULL, " ");
if (c_ip)
{
amount = stof(c_ip);
}
int current_account = -1;
for (int i = 0; i < filectr; i++)
{
if (s_accout_number[i] == accout_number)
{
current_account = i;
break;
}
}
pthread_mutex_lock(&lock);
if (current_account != -1)
{
if (strcmp(transaction_type, "d") == 0)
{
s_amount[current_account] = s_amount[current_account] + amount;
string amt;
string msg;
amt.clear();
msg.clear();
std::stringstream stream;
stream << std::fixed << std::setprecision(2) << s_amount[current_account];
std::string s = stream.str();
amt = s;
msg = "Updated balence after deposite: \n";
msg_to_client = msg+amt;
write(*client_socket, msg_to_client.c_str(), msg_to_client.size() + 1);
}
else if (strcmp(transaction_type, "w") == 0)
{
if ((s_amount[current_account] - amount) < 0)
{
msg_to_client = "Insufficient balence\n";
write(*client_socket, msg_to_client.c_str(), msg_to_client.size() + 1);
}
else
{
s_amount[current_account] = s_amount[current_account] - amount;
string amt;
string msg;
amt.clear();
msg.clear();
std::stringstream stream;
stream << std::fixed << std::setprecision(2) << s_amount[current_account];
std::string s = stream.str();
amt = s;
msg = "Updated balence after withdrawal: \n";
msg_to_client = msg+amt;
write(*client_socket, msg_to_client.c_str(), msg_to_client.size() + 1);
}
}
else
{
msg_to_client = "Invalid transaction type\n";
write(*client_socket, msg_to_client.c_str(), msg_to_client.size() + 1);
}
}
else
{
msg_to_client = "Account number doesn't exist\n";
write(*client_socket, msg_to_client.c_str(), msg_to_client.size() + 1);
}
pthread_mutex_unlock(&lock);
}
}
int main() { //For socket part I have referred below video
//https://www.youtube.com/watch?v=cNdlrbZSkyQ
pthread_t newthread[200];
//Reading the file
fstream accounts;
accounts.open("./accounts");
if (accounts.fail()) {
cout << "Unable to read the file\n"
<< endl;
exit(1);
}
string line;
filectr = 0;
while (getline(accounts, line)) {
filectr++;
}
accounts.close();
accounts.open("./accounts");
for (size_t i = 0; i < filectr; i++) {
accounts >> s_accout_number[i];
accounts >> name[i];
accounts >> s_amount[i];
}
accounts.close();
//Create a server socket
int listening = 0;
listening = socket(AF_INET, SOCK_STREAM, 0);
if (listening == -1) {
cerr << "socket not created\n";
}
else {
cout << "Socket created with FD: " << listening << "\n";
}
int reuse_address = 1;
//Below code is referred from: https://pubs.opengroup.org/onlinepubs/000095399/functions/setsockopt.html
//To reuse the address
/*if(setsockopt(listening, SOL_SOCKET, SO_REUSEADDR, &reuse_address, sizeof(reuse_address)) != 0){
cout<<"Failed to reuse the address"<<endl;
}*/
//To reuse the port
if (setsockopt(listening, SOL_SOCKET, SO_REUSEPORT, &reuse_address, sizeof(reuse_address)) != 0) {
cout << "Failed to reuse the port" << endl;
}
//Bind socket on ip & port
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(54004);
inet_pton(AF_INET, "127.0.0.1", &hint.sin_addr);
if (bind(listening, (sockaddr *)&hint, sizeof(hint)) == -1) {
cerr << "Binding failed\n";
}
//Make the socket listen
if (listen(listening, 4) == -1) {
cerr << "Listening failed\n";
}
//accpet the connection
sockaddr_in client;
socklen_t clientsize = sizeof(client);
char host[NI_MAXHOST];
char svc[NI_MAXSERV];
int clientsocket[200];
for (int j =0; j < 200; j++) {
clientsocket[j] = 0;
}
pthread_t interest;
int i = 0;
pthread_create(&interest, NULL, calculate_interest, NULL);
while (true) {
while (clientsocket[i] = accept(listening, (struct sockaddr *)&client, (socklen_t *)&clientsize)) {
if (clientsocket[i] == -1) {
cerr << "Unable to connect with client\n";
continue;
} else {
pthread_create(&newthread[i], NULL, operations, &clientsocket[i]);
i++;
}
}
cout << "closing " << clientsocket << endl;
close(clientsocket[i]);
close(listening);
}
return 0;
}
| 30.229508 | 119 | 0.50583 |
9a1957eed44c4ed8c755bd0da4386a401e71db85 | 4,444 | cc | C++ | stapl_release/tools/mtl-2.0/test/src/matrix_row_col_test.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/tools/mtl-2.0/test/src/matrix_row_col_test.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/tools/mtl-2.0/test/src/matrix_row_col_test.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | // -*- c++ -*-
//
// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a
// component of the Texas A&M University System.
//
// All rights reserved.
//
// The information and source code contained herein is the exclusive
// property of TEES and may not be disclosed, examined or reproduced
// in whole or in part without explicit written authorization from TEES.
//
// Copyright 1997, 1998, 1999 University of Notre Dame.
// Authors: Andrew Lumsdaine, Jeremy G. Siek, Lie-Quan Lee
//
// This file is part of the Matrix Template Library
//
// You should have received a copy of the License Agreement for the
// Matrix Template Library along with the software; see the
// file LICENSE. If not, contact Office of Research, University of Notre
// Dame, Notre Dame, IN 46556.
//
// Permission to modify the code and to distribute modified code is
// granted, provided the text of this NOTICE is retained, a notice that
// the code was modified is included with the above COPYRIGHT NOTICE and
// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE
// file is distributed with the modified code.
//
// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.
// By way of example, but not limitation, Licensor MAKES NO
// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY
// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS
// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS
// OR OTHER RIGHTS.
//
//===========================================================================
#include "mtl/utils.h"
#include "mtl/matrix.h"
#include "matrix_test.h"
#include "iter_ij_test.h"
// matrix_attr.h is generated by make_and_test.pl and defines
// NUMTYPE, SHAPE, STORAGE, ORIEN, and TESTNAME
// you can create your own for testing purposes
#include "matrix_attr.h"
template <class Matrix, class Shape>
bool rows_test(const Matrix& A, std::string test_name, Shape, row_tag)
{
return iterator_operator_ij_test(A, test_name);
}
template <class Matrix>
bool rows_test(const Matrix& A, std::string test_name,
rectangle_tag, column_tag)
{
return strided_iterator_operator_ij_test(A, test_name);
}
template <class Matrix, class Shape>
bool columns_test(const Matrix& A, std::string test_name, Shape, row_tag)
{
return strided_iterator_operator_ij_test(A, test_name);
}
template <class Matrix>
bool columns_test(const Matrix& A, std::string test_name,
rectangle_tag, column_tag)
{
return iterator_operator_ij_test(A, test_name);
}
template <class Matrix>
bool rows_columns_test(Matrix& A, std::string test_name, strideable)
{
using mtl::rows;
using mtl::columns;
typedef typename mtl::matrix_traits<Matrix>::shape Shape;
typedef typename mtl::matrix_traits<Matrix>::orientation Orien;
bool ret1 = mtl::matrix_equal(rows(A), columns(A));
bool ret2 = rows_test(rows(A), test_name, Shape(), Orien());
bool ret3 = columns_test(columns(A), test_name, Shape(), Orien());
if (ret1 && ret2 && ret3)
std::cout << test_name.c_str() << " passed rows & columns test" << std::endl;
return ret1 && ret2 && ret3;
}
template <class Matrix>
bool rows_columns_test(Matrix&, std::string test_name, not_strideable)
{
std::cout << test_name.c_str() << " skipping rows & columns test" << std::endl;
return true;
}
template <class Matrix>
bool rows_columns_test(Matrix& A, std::string test_name)
{
typedef typename mtl::matrix_traits<Matrix>::strideability Stridable;
return rows_columns_test(A, test_name, Stridable());
}
template <class Matrix>
void
do_test(Matrix& A, std::string test_name)
{
using namespace mtl;
typedef typename mtl::matrix_traits<Matrix>::value_type T;
typedef typename mtl::matrix_traits<Matrix>::size_type Int;
matrix_fill(A);
rows_columns_test(A, test_name);
}
int
main(int argc, char* argv[])
{
if (argc < 5) {
std::cerr << "matrix_test <M> <N> <SUB> <SUPER>" << std::endl;
return -1;
}
using namespace mtl;
using std::string;
const int M = atoi(argv[1]);
const int N = atoi(argv[2]);
const int SUB = atoi(argv[3]);
const int SUP = atoi(argv[4]);
std::cout << "M: " << M << " N: " << N
<< " SUB: " << SUB << " SUPER: " << SUP << std::endl;
typedef matrix<NUMTYPE, SHAPE, STORAGE, ORIEN>::type Matrix;
string test_name = TESTNAME;
Matrix* a = 0;
create_and_run(M, N, SUB, SUP, test_name, a, Matrix::shape());
return 0;
}
| 30.027027 | 81 | 0.70387 |
9a1a2b02e904868e53e4ad156e1936048ba7c46c | 1,050 | cpp | C++ | libs/camera/src/camera/coordinate_system/identity.cpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | libs/camera/src/camera/coordinate_system/identity.cpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | libs/camera/src/camera/coordinate_system/identity.cpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <sge/camera/coordinate_system/forward.hpp>
#include <sge/camera/coordinate_system/identity.hpp>
#include <sge/camera/coordinate_system/object.hpp>
#include <sge/camera/coordinate_system/position.hpp>
#include <sge/camera/coordinate_system/right.hpp>
#include <sge/camera/coordinate_system/up.hpp>
#include <sge/renderer/vector3.hpp>
sge::camera::coordinate_system::object sge::camera::coordinate_system::identity()
{
return sge::camera::coordinate_system::object(
sge::camera::coordinate_system::right(sge::renderer::vector3(1.0F, 0.0F, 0.0F)),
sge::camera::coordinate_system::up(sge::renderer::vector3(0.0F, 1.0F, 0.0F)),
sge::camera::coordinate_system::forward(sge::renderer::vector3(0.0F, 0.0F, 1.0F)),
sge::camera::coordinate_system::position(sge::renderer::vector3(0.0F, 0.0F, 0.0F)));
}
| 47.727273 | 90 | 0.730476 |
9a1a6dd25cc40f9ff5700fd28e8824579e224b29 | 10,728 | cpp | C++ | avogadro/io/cjsonformat.cpp | AlbertDeFusco/avogadrolibs | 572aad6d16295c91da684d180b6b2705070549c1 | [
"BSD-3-Clause"
] | null | null | null | avogadro/io/cjsonformat.cpp | AlbertDeFusco/avogadrolibs | 572aad6d16295c91da684d180b6b2705070549c1 | [
"BSD-3-Clause"
] | null | null | null | avogadro/io/cjsonformat.cpp | AlbertDeFusco/avogadrolibs | 572aad6d16295c91da684d180b6b2705070549c1 | [
"BSD-3-Clause"
] | null | null | null | /******************************************************************************
This source file is part of the Avogadro project.
Copyright 2012 Kitware, Inc.
This source code is released under the New BSD License, (the "License").
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
******************************************************************************/
#include "cjsonformat.h"
#include <avogadro/core/crystaltools.h>
#include <avogadro/core/elements.h>
#include <avogadro/core/molecule.h>
#include <avogadro/core/unitcell.h>
#include <jsoncpp.cpp>
using Avogadro::Core::Molecule;
namespace Avogadro {
namespace Io {
using std::string;
using Core::Elements;
using Core::Atom;
using Core::Bond;
using Core::Variant;
CjsonFormat::CjsonFormat()
{
}
CjsonFormat::~CjsonFormat()
{
}
bool CjsonFormat::read(std::istream &file, Core::Molecule &molecule)
{
Json::Value root;
Json::Reader reader;
bool ok = reader.parse(file, root);
if (!ok) {
appendError("Error parsing JSON: " + reader.getFormatedErrorMessages());
return false;
}
if (!root.isObject()) {
appendError("Error: Input is not a JSON object.");
return false;
}
Json::Value value = root["chemical json"];
if (value.empty()) {
appendError("Error: no \"chemical json\" key found.");
return false;
}
// It looks like a valid Chemical JSON file - attempt to read data.
value = root["name"];
if (!value.empty() && value.isString())
molecule.setData("name", value.asString());
value = root["inchi"];
if (!value.empty() && value.isString())
molecule.setData("inchi", value.asString());
value = root["unit cell"];
if (value.type() == Json::objectValue) {
if (!value["a"].isNumeric() ||
!value["b"].isNumeric() ||
!value["c"].isNumeric() ||
!value["alpha"].isNumeric() ||
!value["beta"].isNumeric() ||
!value["gamma"].isNumeric()) {
appendError("Invalid unit cell specification: a, b, c, alpha, beta, gamma"
" must be present and numeric.");
return false;
}
Real a = static_cast<Real>(value["a"].asDouble());
Real b = static_cast<Real>(value["b"].asDouble());
Real c = static_cast<Real>(value["c"].asDouble());
Real alpha = static_cast<Real>(value["alpha"].asDouble()) * DEG_TO_RAD;
Real beta = static_cast<Real>(value["beta" ].asDouble()) * DEG_TO_RAD;
Real gamma = static_cast<Real>(value["gamma"].asDouble()) * DEG_TO_RAD;
Core::UnitCell *unitCell = new Core::UnitCell(a, b, c, alpha, beta, gamma);
molecule.setUnitCell(unitCell);
}
// Read in the atomic data.
Json::Value atoms = root["atoms"];
if (atoms.empty()) {
appendError("Error: no \"atom\" key found");
return false;
}
else if (atoms.type() != Json::objectValue) {
appendError("Error: \"atom\" is not of type object");
return false;
}
value = atoms["elements"];
if (value.empty()) {
appendError("Error: no \"atoms.elements\" key found");
return false;
}
else if (value.type() != Json::objectValue) {
appendError("Error: \"atoms.elements\" is not of type object");
return false;
}
value = value["number"];
if (value.empty()) {
appendError("Error: no \"atoms.elements.number\" key found");
return false;
}
Index atomCount(0);
if (value.isArray()) {
atomCount = static_cast<Index>(value.size());
for (Index i = 0; i < atomCount; ++i)
molecule.addAtom(static_cast<unsigned char>(value.get(i, 0).asInt()));
}
else {
appendError("Error: \"atoms.elements.number\" is not of type array");
return false;
}
Json::Value coords = atoms["coords"];
if (!coords.empty()) {
value = coords["3d"];
if (value.isArray()) {
if (value.size() && atomCount != static_cast<Index>(value.size() / 3)) {
appendError("Error: number of elements != number of 3D coordinates.");
return false;
}
for (Index i = 0; i < atomCount; ++i) {
Atom a = molecule.atom(i);
a.setPosition3d(Vector3(value.get(3 * i + 0, 0).asDouble(),
value.get(3 * i + 1, 0).asDouble(),
value.get(3 * i + 2, 0).asDouble()));
}
}
value = coords["2d"];
if (value.isArray()) {
if (value.size() && atomCount != static_cast<Index>(value.size() / 2)) {
appendError("Error: number of elements != number of 2D coordinates.");
return false;
}
for (Index i = 0; i < atomCount; ++i) {
Atom a = molecule.atom(i);
a.setPosition2d(Vector2(value.get(2 * i + 0, 0).asDouble(),
value.get(2 * i + 1, 0).asDouble()));
}
}
value = coords["3d fractional"];
if (value.type() == Json::arrayValue) {
if (!molecule.unitCell()) {
appendError("Cannot interpret fractional coordinates without "
"unit cell.");
return false;
}
if (value.size() && atomCount != static_cast<size_t>(value.size() / 3)) {
appendError("Error: number of elements != number of fractional "
"coordinates.");
return false;
}
Core::Array<Vector3> fcoords;
fcoords.reserve(atomCount);
for (Index i = 0; i < atomCount; ++i) {
fcoords.push_back(
Vector3(static_cast<Real>(value.get(i * 3 + 0, 0).asDouble()),
static_cast<Real>(value.get(i * 3 + 1, 0).asDouble()),
static_cast<Real>(value.get(i * 3 + 2, 0).asDouble())));
}
Core::CrystalTools::setFractionalCoordinates(molecule, fcoords);
}
}
// Now for the bonding data.
Json::Value bonds = root["bonds"];
if (!bonds.empty()) {
value = bonds["connections"];
if (value.empty()) {
appendError("Error: no \"bonds.connections\" key found");
return false;
}
value = value["index"];
Index bondCount(0);
if (value.isArray()) {
bondCount = static_cast<Index>(value.size() / 2);
for (Index i = 0; i < bondCount * 2; i += 2) {
molecule.addBond(
molecule.atom(static_cast<Index>(value.get(i + 0, 0).asInt())),
molecule.atom(static_cast<Index>(value.get(i + 1, 0).asInt())));
}
}
else {
appendError("Warning, no bonding information found.");
}
value = bonds["order"];
if (value.isArray()) {
if (bondCount != static_cast<Index>(value.size())) {
appendError("Error: number of bonds != number of bond orders.");
return false;
}
for (Index i = 0; i < bondCount; ++i)
molecule.bond(i).setOrder(
static_cast<unsigned char>(value.get(i, 1).asInt()));
}
}
return true;
}
bool CjsonFormat::write(std::ostream &file, const Core::Molecule &molecule)
{
Json::StyledStreamWriter writer(" ");
Json::Value root;
root["chemical json"] = 0;
if (molecule.data("name").type() == Variant::String)
root["name"] = molecule.data("name").toString().c_str();
if (molecule.data("inchi").type() == Variant::String)
root["inchi"] = molecule.data("inchi").toString().c_str();
if (molecule.unitCell()) {
Json::Value unitCell = Json::Value(Json::objectValue);
unitCell["a"] = molecule.unitCell()->a();
unitCell["b"] = molecule.unitCell()->b();
unitCell["c"] = molecule.unitCell()->c();
unitCell["alpha"] = molecule.unitCell()->alpha() * RAD_TO_DEG;
unitCell["beta"] = molecule.unitCell()->beta() * RAD_TO_DEG;
unitCell["gamma"] = molecule.unitCell()->gamma() * RAD_TO_DEG;
root["unit cell"] = unitCell;
}
// Create and populate the atom arrays.
if (molecule.atomCount()) {
Json::Value elements(Json::arrayValue);
for (Index i = 0; i < molecule.atomCount(); ++i)
elements.append(molecule.atom(i).atomicNumber());
root["atoms"]["elements"]["number"] = elements;
// 3d positions:
if (molecule.atomPositions3d().size() == molecule.atomCount()) {
if (molecule.unitCell()) {
Json::Value coordsFractional(Json::arrayValue);
Core::Array<Vector3> fcoords;
Core::CrystalTools::fractionalCoordinates(*molecule.unitCell(),
molecule.atomPositions3d(),
fcoords);
for (std::vector<Vector3>::const_iterator it = fcoords.begin(),
itEnd = fcoords.end(); it != itEnd; ++it) {
coordsFractional.append(it->x());
coordsFractional.append(it->y());
coordsFractional.append(it->z());
}
root["atoms"]["coords"]["3d fractional"] = coordsFractional;
}
else {
Json::Value coords3d(Json::arrayValue);
for (std::vector<Vector3>::const_iterator
it = molecule.atomPositions3d().begin(),
itEnd = molecule.atomPositions3d().end(); it != itEnd; ++it) {
coords3d.append(it->x());
coords3d.append(it->y());
coords3d.append(it->z());
}
root["atoms"]["coords"]["3d"] = coords3d;
}
}
// 2d positions:
if (molecule.atomPositions2d().size() == molecule.atomCount()) {
Json::Value coords2d(Json::arrayValue);
for (std::vector<Vector2>::const_iterator
it = molecule.atomPositions2d().begin(),
itEnd = molecule.atomPositions2d().end(); it != itEnd; ++it) {
coords2d.append(it->x());
coords2d.append(it->y());
}
root["atoms"]["coords"]["2d"] = coords2d;
}
}
// Create and populate the bond arrays.
if (molecule.bondCount()) {
Json::Value connections(Json::arrayValue);
Json::Value order(Json::arrayValue);
for (Index i = 0; i < molecule.bondCount(); ++i) {
Bond bond = molecule.bond(i);
connections.append(static_cast<Json::Value::UInt>(bond.atom1().index()));
connections.append(static_cast<Json::Value::UInt>(bond.atom2().index()));
order.append(bond.order());
}
root["bonds"]["connections"]["index"] = connections;
root["bonds"]["order"] = order;
}
writer.write(file, root);
return true;
}
std::vector<std::string> CjsonFormat::fileExtensions() const
{
std::vector<std::string> ext;
ext.push_back("cjson");
return ext;
}
std::vector<std::string> CjsonFormat::mimeTypes() const
{
std::vector<std::string> mime;
mime.push_back("chemical/x-cjson");
return mime;
}
} // end Io namespace
} // end Avogadro namespace
| 32.216216 | 80 | 0.584452 |
9a1a9315aa9fb37f48c00f2e5dea109306c5e6f6 | 3,691 | cc | C++ | api/video/test/i444_buffer_unittest.cc | wyshen2020/webrtc | b93e2240f1653b82e24553e092bbab84337774af | [
"BSD-3-Clause"
] | 2 | 2022-03-10T01:47:56.000Z | 2022-03-31T12:51:46.000Z | api/video/test/i444_buffer_unittest.cc | wyshen2020/webrtc | b93e2240f1653b82e24553e092bbab84337774af | [
"BSD-3-Clause"
] | null | null | null | api/video/test/i444_buffer_unittest.cc | wyshen2020/webrtc | b93e2240f1653b82e24553e092bbab84337774af | [
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (c) 2021 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "api/video/i444_buffer.h"
#include "api/video/i420_buffer.h"
#include "test/frame_utils.h"
#include "test/gmock.h"
#include "test/gtest.h"
namespace webrtc {
namespace {
int GetY(rtc::scoped_refptr<I444BufferInterface> buf, int col, int row) {
return buf->DataY()[row * buf->StrideY() + col];
}
int GetU(rtc::scoped_refptr<I444BufferInterface> buf, int col, int row) {
return buf->DataU()[row * buf->StrideU() + col];
}
int GetV(rtc::scoped_refptr<I444BufferInterface> buf, int col, int row) {
return buf->DataV()[row * buf->StrideV() + col];
}
void FillI444Buffer(rtc::scoped_refptr<I444Buffer> buf) {
const uint8_t Y = 1;
const uint8_t U = 2;
const uint8_t V = 3;
for (int row = 0; row < buf->height(); ++row) {
for (int col = 0; col < buf->width(); ++col) {
buf->MutableDataY()[row * buf->StrideY() + col] = Y;
buf->MutableDataU()[row * buf->StrideU() + col] = U;
buf->MutableDataV()[row * buf->StrideV() + col] = V;
}
}
}
} // namespace
TEST(I444BufferTest, InitialData) {
constexpr int stride = 3;
constexpr int width = 3;
constexpr int height = 3;
rtc::scoped_refptr<I444Buffer> i444_buffer(I444Buffer::Create(width, height));
EXPECT_EQ(width, i444_buffer->width());
EXPECT_EQ(height, i444_buffer->height());
EXPECT_EQ(stride, i444_buffer->StrideY());
EXPECT_EQ(stride, i444_buffer->StrideU());
EXPECT_EQ(stride, i444_buffer->StrideV());
EXPECT_EQ(3, i444_buffer->ChromaWidth());
EXPECT_EQ(3, i444_buffer->ChromaHeight());
}
TEST(I444BufferTest, ReadPixels) {
constexpr int width = 3;
constexpr int height = 3;
rtc::scoped_refptr<I444Buffer> i444_buffer(I444Buffer::Create(width, height));
// Y = 1, U = 2, V = 3.
FillI444Buffer(i444_buffer);
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
EXPECT_EQ(1, GetY(i444_buffer, col, row));
EXPECT_EQ(2, GetU(i444_buffer, col, row));
EXPECT_EQ(3, GetV(i444_buffer, col, row));
}
}
}
TEST(I444BufferTest, ToI420) {
constexpr int width = 3;
constexpr int height = 3;
constexpr int size_y = width * height;
constexpr int size_u = (width + 1) / 2 * (height + 1) / 2;
constexpr int size_v = (width + 1) / 2 * (height + 1) / 2;
rtc::scoped_refptr<I420Buffer> reference(I420Buffer::Create(width, height));
memset(reference->MutableDataY(), 8, size_y);
memset(reference->MutableDataU(), 4, size_u);
memset(reference->MutableDataV(), 2, size_v);
rtc::scoped_refptr<I444Buffer> i444_buffer(I444Buffer::Create(width, height));
// Convert the reference buffer to I444.
memset(i444_buffer->MutableDataY(), 8, size_y);
memset(i444_buffer->MutableDataU(), 4, size_y);
memset(i444_buffer->MutableDataV(), 2, size_y);
// Confirm YUV values are as expected.
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
EXPECT_EQ(8, GetY(i444_buffer, col, row));
EXPECT_EQ(4, GetU(i444_buffer, col, row));
EXPECT_EQ(2, GetV(i444_buffer, col, row));
}
}
rtc::scoped_refptr<I420BufferInterface> i420_buffer(i444_buffer->ToI420());
EXPECT_EQ(height, i420_buffer->height());
EXPECT_EQ(width, i420_buffer->width());
EXPECT_TRUE(test::FrameBufsEqual(reference, i420_buffer));
}
} // namespace webrtc
| 32.663717 | 80 | 0.674614 |
9a1ccc6c28fe8c5122d866b5b74592e3c680f62a | 17,289 | cpp | C++ | src/randomforest.cpp | McSnappy/PUML | a04ab37999abc4874303569e64694ade8258cb74 | [
"MIT"
] | 1 | 2016-05-26T13:21:51.000Z | 2016-05-26T13:21:51.000Z | src/randomforest.cpp | McSnappy/PUML | a04ab37999abc4874303569e64694ade8258cb74 | [
"MIT"
] | null | null | null | src/randomforest.cpp | McSnappy/PUML | a04ab37999abc4874303569e64694ade8258cb74 | [
"MIT"
] | null | null | null | /*
Copyright (c) Carl Sherrell
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <sstream>
#include <fstream>
#include <iomanip>
#include <algorithm>
#include <thread>
#include <string.h>
#include "randomforest.h"
#include "mlutil.h"
namespace puml {
static const ml_string &RF_BASEINFO_FILE = "rf.json";
static const ml_string &RF_MLID_FILE = "mlid.json";
struct rf_thread_config {
rf_thread_config(ml_uint tindex, ml_uint ntrees,
const decision_tree &ptree, const ml_data &data) :
thread_index(tindex), number_of_trees(ntrees),
proto_tree(ptree), mld(data) {}
ml_uint thread_index;
ml_uint number_of_trees;
decision_tree proto_tree;
const ml_data &mld;
ml_vector<rf_oob_indices> oobs;
ml_vector<decision_tree> trees;
};
using rf_thread_config_ptr = std::shared_ptr<rf_thread_config>;
random_forest::random_forest(const ml_instance_definition &mlid,
const ml_string &feature_to_predict,
ml_uint number_of_trees,
ml_uint seed,
ml_uint number_of_threads,
ml_uint max_tree_depth,
ml_uint min_leaf_instances,
ml_uint features_to_consider_per_node) :
mlid_(mlid),
index_of_feature_to_predict_(index_of_feature_with_name(feature_to_predict, mlid)),
number_of_trees_(number_of_trees),
seed_(seed),
number_of_threads_(number_of_threads),
max_tree_depth_(max_tree_depth),
min_leaf_instances_(min_leaf_instances),
features_to_consider_per_node_(features_to_consider_per_node) {
type_ = (mlid_[index_of_feature_to_predict_]->type == ml_feature_type::discrete) ? ml_model_type::classification : ml_model_type::regression;
if(number_of_threads_ > number_of_trees_) {
number_of_threads_ = 1;
}
if(features_to_consider_per_node_ == RF_DEFAULT_FEATURES_SQRT) {
features_to_consider_per_node_ = (ml_uint) (std::sqrt(mlid.size() - 1) + 0.5);
}
}
static void init_outofbag_indices(ml_uint size, rf_oob_indices &oob) {
oob.clear();
for(ml_uint ii=0; ii < size; ++ii) {
oob.insert(oob.end(), ii);
}
}
static void bootstrapped_sample_from_data(const ml_data &mld, ml_rng &rng,
ml_data &bootstrapped, rf_oob_indices &oob) {
bootstrapped.clear();
init_outofbag_indices(mld.size(), oob);
for(std::size_t ii=0; ii < mld.size(); ++ii) {
ml_uint index = rng.random_number() % mld.size();
bootstrapped.push_back(mld[index]);
rf_oob_indices::iterator oobit = oob.find(index);
if(oobit != oob.end()) {
oob.erase(oobit);
}
}
}
void random_forest::set_trees(const ml_vector<decision_tree> &trees) {
oob_predictions_.clear();
feature_importance_.clear();
trees_ = trees;
}
void random_forest::evaluate_out_of_bag(const ml_data &mld, const ml_vector<rf_oob_indices> &oobs) {
oob_predictions_.clear();
random_forest oob_forest = *this;
for(ml_uint instance_index = 0; instance_index < mld.size(); ++instance_index) {
// find all trees that were built without this instance (it's in their out-of-bag set)
ml_vector<decision_tree> oob_trees;
for(std::size_t tree_index = 0; tree_index < trees_.size(); ++tree_index) {
if(oobs[tree_index].find(instance_index) != oobs[tree_index].end()) {
oob_trees.push_back(trees_[tree_index]);
}
}
oob_forest.set_trees(oob_trees);
ml_feature_value prediction = oob_forest.evaluate(*mld[instance_index]);
oob_predictions_.push_back(prediction);
}
}
static void collect_feature_importance(const ml_vector<dt_feature_importance> &tree_feature_importance,
ml_vector<dt_feature_importance> &forest_feature_importance) {
for(std::size_t ii = 0; ii < tree_feature_importance.size(); ++ii) {
forest_feature_importance[ii].count += tree_feature_importance[ii].count;
forest_feature_importance[ii].sum_score_delta += tree_feature_importance[ii].sum_score_delta;
}
}
static ml_vector<feature_importance_tuple> calculate_feature_importance(const ml_instance_definition &mlid,
ml_uint index_of_feature_to_predict,
ml_vector<dt_feature_importance> forest_feature_importance) {
ml_double best_score_delta = 0.0;
for(const auto &feature_importance : forest_feature_importance) {
ml_double score_delta = (feature_importance.count > 0) ? feature_importance.sum_score_delta : 0.0;
if(score_delta > best_score_delta) {
best_score_delta = score_delta;
}
}
ml_vector<feature_importance_tuple> feature_importance_norm;
feature_importance_norm.reserve(forest_feature_importance.size());
for(std::size_t ii = 0; ii < forest_feature_importance.size(); ++ii) {
if(ii == index_of_feature_to_predict) {
continue;
}
ml_double score_delta = (forest_feature_importance[ii].count > 0) ? forest_feature_importance[ii].sum_score_delta : 0.0;
ml_double avg_score_delta = (forest_feature_importance[ii].count > 0) ? (forest_feature_importance[ii].sum_score_delta / forest_feature_importance[ii].count) : 0.0;
ml_double norm_score = (best_score_delta > 0.0) ? (100.0 * (score_delta / best_score_delta)) : 0.0;
std::ostringstream ss;
ss << std::setw(7) << std::fixed << std::setprecision(2) << norm_score << " " << mlid[ii]->name << " (" << forest_feature_importance[ii].count << " nodes, " << avg_score_delta << ")";
//
// feature_importance_tuple represents the feature index and feature
// importance score description
//
feature_importance_norm.push_back(std::make_pair(ii, ss.str()));
}
std::sort(feature_importance_norm.begin(),
feature_importance_norm.end(),
[](feature_importance_tuple const &t1, feature_importance_tuple const &t2) {
return(std::get<1>(t1) < std::get<1>(t2));
});
return(feature_importance_norm);
}
bool random_forest::single_threaded_train(const ml_data &mld,
ml_vector<rf_oob_indices> &oobs,
ml_vector<dt_feature_importance> &forest_feature_importance) {
ml_rng rng(seed_);
for(ml_uint ii=0; ii < number_of_trees_; ++ii) {
ml_data bootstrapped;
rf_oob_indices oob;
bootstrapped_sample_from_data(mld, rng, bootstrapped, oob);
log("\nbuilding tree %d...\n", ii+1);
decision_tree tree{mlid_, index_of_feature_to_predict_,
max_tree_depth_, min_leaf_instances_,
features_to_consider_per_node_, seed_};
if(!tree.train(bootstrapped)) {
log_error("rf failed to build decision tree...");
return(false);
}
oobs.push_back(oob);
collect_feature_importance(tree.feature_importance(), forest_feature_importance);
trees_.push_back(tree);
}
return(true);
}
static void multi_threaded_work(rf_thread_config_ptr rftc) {
ml_rng rng(rftc->proto_tree.seed());
for(ml_uint ii=0; ii < rftc->number_of_trees; ++ii) {
ml_data bootstrapped;
rf_oob_indices oob;
bootstrapped_sample_from_data(rftc->mld, rng, bootstrapped, oob);
log("%s building tree %d...\n", rftc->proto_tree.name().c_str(), ii+1);
if(!rftc->proto_tree.train(bootstrapped)) {
log_error("rf failed to build decision tree %d-%d...\n", rftc->thread_index, ii+1);
return;
}
rftc->oobs.push_back(oob);
rftc->trees.push_back(rftc->proto_tree);
}
}
bool random_forest::multi_threaded_train(const ml_data &mld,
ml_vector<rf_oob_indices> &oobs,
ml_vector<dt_feature_importance> &forest_feature_importance) {
ml_vector<std::thread> work_threads;
ml_vector<rf_thread_config_ptr> thread_configs;
// init thread input (# trees to build, custom seed, etc) and spawn the threads
for(ml_uint thread_index = 0; thread_index < number_of_threads_; ++thread_index) {
ml_uint ntrees = (number_of_trees_ / number_of_threads_);
ntrees += (thread_index == 0) ? (number_of_trees_ % number_of_threads_) : 0;
decision_tree proto_tree{mlid_, index_of_feature_to_predict_,
max_tree_depth_, min_leaf_instances_,
features_to_consider_per_node_, seed_ + thread_index};
proto_tree.set_name(string_format("[thread %d]", thread_index));
auto rftc = std::make_shared<rf_thread_config>(thread_index, ntrees, proto_tree, mld);
thread_configs.push_back(rftc);
work_threads.emplace_back(std::thread([rftc] { multi_threaded_work(rftc); }));
}
// wait for all threads to finish
for(auto &thread : work_threads) {
thread.join();
}
// combine trees, out of bag maps, and feature importance
for(auto &thread_config : thread_configs) {
if(thread_config->trees.size() != thread_config->number_of_trees) {
log_error("some trees failed to build in thread %d\n", thread_config->thread_index);
return(false);
}
for(ml_uint tree_index = 0; tree_index < thread_config->number_of_trees; ++tree_index) {
oobs.push_back(thread_config->oobs[tree_index]);
trees_.push_back(thread_config->trees[tree_index]);
collect_feature_importance(thread_config->trees[tree_index].feature_importance(), forest_feature_importance);
}
}
return(true);
}
bool random_forest::train(const ml_data &mld) {
trees_.clear();
feature_importance_.clear();
oob_predictions_.clear();
if(mlid_.empty()) {
log_error("rf train() invalid instance definition...\n");
return(false);
}
ml_vector<rf_oob_indices> oobs;
ml_vector<dt_feature_importance> forest_feature_importance;
forest_feature_importance.resize(mlid_.size());
bool forest_was_built = (number_of_threads_ <= 1) ? single_threaded_train(mld, oobs, forest_feature_importance) :
multi_threaded_train(mld, oobs, forest_feature_importance);
if(!forest_was_built) {
log_error("hit a snag while building the forest...\n");
return(false);
}
feature_importance_ = calculate_feature_importance(mlid_, index_of_feature_to_predict_, forest_feature_importance);
if(evaluate_oob_) {
evaluate_out_of_bag(mld, oobs);
}
return(true);
}
ml_feature_value random_forest::evaluate(const ml_instance &instance) const {
ml_feature_value rf_eval = {};
if(trees_.empty()) {
log_warn("evaluate() called on an empty forest\n");
return(rf_eval);
}
ml_double sum = 0;
ml_map<ml_uint, ml_uint> prediction_map;
//
// evaluate all trees in the forest for the instance
//
for(const auto &tree : trees_) {
ml_feature_value tree_eval = tree.evaluate(instance);
if(type_ == ml_model_type::classification) {
prediction_map[tree_eval.discrete_value_index] += 1;
}
else {
sum += tree_eval.continuous_value;
}
}
if(type_ == ml_model_type::classification) {
//
// classification returns the mode
//
ml_uint predicted_discrete_value_index = 0;
ml_uint predicted_count = 0;
// we iterate over all categories in a fixed order so that
// ties in voting between categories are broken in a determinate
// way (not dependent on the order of iteration within the container)
ml_uint categories = mlid_[index_of_feature_to_predict_]->discrete_values.size();
for(ml_uint category = 0; category < categories; ++category) {
auto it = prediction_map.find(category);
if(it == prediction_map.end()) {
continue;
}
if(it->second > predicted_count) {
predicted_discrete_value_index = it->first;
predicted_count = it->second;
}
}
rf_eval.discrete_value_index = predicted_discrete_value_index;
}
else {
//
// regression returns the mean
//
rf_eval.continuous_value = sum / trees_.size();
}
return(rf_eval);
}
bool random_forest::write_random_forest_base_info_to_file(const ml_string &path) const {
json json_object = {{"object", "random_forest"},
{"version", ML_VERSION_STRING},
{"type", type_},
{"index_of_feature_to_predict", index_of_feature_to_predict_},
{"number_of_trees", number_of_trees_},
{"seed", seed_},
{"number_of_threads", number_of_threads_},
{"max_tree_depth", max_tree_depth_},
{"min_leaf_instances", min_leaf_instances_},
{"features_to_consider_per_node", features_to_consider_per_node_},
{"evaluate_oob", evaluate_oob_}};
std::ofstream modelout(path);
modelout << std::setw(4) << json_object << std::endl;
return(true);
}
bool random_forest::save(const ml_string &path) const {
if(mlid_.empty()) {
return(false);
}
if(!prepare_directory_for_model_save(path)) {
return(false);
}
// write the instance definition
if(!write_instance_definition_to_file(path + "/" + RF_MLID_FILE, mlid_)) {
log_error("couldn't write rf instance definition to %s\n", RF_MLID_FILE.c_str());
return(false);
}
// store the forest type, index to predict, etc
if(!write_random_forest_base_info_to_file(path + "/" + RF_BASEINFO_FILE)) {
log_error("couldn't write rf info to %s\n", RF_BASEINFO_FILE.c_str());
return(false);
}
std::time_t timestamp = std::time(0);
// each tree is written to its own file
for(std::size_t ii = 0; ii < trees_.size(); ++ii) {
// we use the timestamp in the filename to make it easier to consolidate trees from multiple runs.
// for example, tree1.1457973944.json
ml_string filename = path + "/" + puml::TREE_MODEL_FILE_PREFIX + std::to_string(ii+1) + "." + std::to_string(timestamp) + ".json";
if(!trees_[ii].save(filename, true)) {
log_error("couldn't write tree to file: %s\n", filename.c_str());
return(false);
}
}
return(true);
}
bool random_forest::read_random_forest_base_info_from_file(const ml_string &path) {
std::ifstream jsonfile(path);
json json_object;
jsonfile >> json_object;
ml_string object_name = json_object["object"];
if(object_name != "random_forest") {
log_error("json object is not a random forest...\n");
return(false);
}
if(!(get_modeltype_value_from_json(json_object, "type", type_) &&
get_numeric_value_from_json(json_object, "index_of_feature_to_predict", index_of_feature_to_predict_) &&
get_numeric_value_from_json(json_object, "number_of_trees", number_of_trees_) &&
get_numeric_value_from_json(json_object, "seed", seed_) &&
get_numeric_value_from_json(json_object, "number_of_threads", number_of_threads_) &&
get_numeric_value_from_json(json_object, "max_tree_depth", max_tree_depth_) &&
get_numeric_value_from_json(json_object, "min_leaf_instances", min_leaf_instances_) &&
get_numeric_value_from_json(json_object, "features_to_consider_per_node", features_to_consider_per_node_) &&
get_bool_value_from_json(json_object, "evaluate_oob", evaluate_oob_))) {
return(false);
}
return(true);
}
bool random_forest::restore(const ml_string &path) {
if(!read_instance_definition_from_file(path + "/" + RF_MLID_FILE, mlid_)) {
log_error("couldn't read rf instance defintion\n");
return(false);
}
if(!read_random_forest_base_info_from_file(path + "/" + RF_BASEINFO_FILE)) {
log_error("couldn't read rf base info\n");
return(false);
}
if(!read_decision_trees_from_directory(path, mlid_, trees_)) {
return(false);
}
return(true);
}
ml_string random_forest::summary() const {
if(mlid_.empty() || trees_.empty()) {
return("(empty forest)\n");
}
ml_string desc;
desc += "\n\n*** Random Forest Summary ***\n\n";
desc += "Feature To Predict: " + mlid_[index_of_feature_to_predict_]->name + "\n";
ml_string type_str = (type_ == ml_model_type::regression) ? "regression" : "classification";
desc += "Type: " + type_str;
desc += ", Trees: " + std::to_string(number_of_trees_);
desc += ", Threads: " + std::to_string(number_of_threads_);
desc += ", Max Depth: " + std::to_string(max_tree_depth_);
desc += ", Min Leaf Instances: " + std::to_string(min_leaf_instances_);
desc += ", Features p/n: " + std::to_string(features_to_consider_per_node_);
desc += ", Seed: " + std::to_string(seed_);
desc += ", Eval Out-Of-Bag: " + std::to_string(evaluate_oob_);
desc += "\n";
desc += feature_importance_summary();
return(desc);
}
ml_string random_forest::feature_importance_summary() const {
if(feature_importance_.empty()) {
return("");
}
ml_string desc = "\n*** Feature Importance ***\n\n";
for(const auto &importance_tuple : feature_importance_) {
desc += std::get<1>(importance_tuple) + "\n";
}
return(desc);
}
} // namespace puml
| 31.839779 | 187 | 0.711782 |
9a1dbe88c0e383142c322bd3b1d423c0cad52185 | 67,275 | cxx | C++ | Modules/Loadable/SubjectHierarchy/Widgets/qMRMLSubjectHierarchyTreeView.cxx | forfullstack/slicersources-src | 91bcecf037a27f3fad4c0ab57e8286fc258bb0f5 | [
"Apache-2.0"
] | null | null | null | Modules/Loadable/SubjectHierarchy/Widgets/qMRMLSubjectHierarchyTreeView.cxx | forfullstack/slicersources-src | 91bcecf037a27f3fad4c0ab57e8286fc258bb0f5 | [
"Apache-2.0"
] | null | null | null | Modules/Loadable/SubjectHierarchy/Widgets/qMRMLSubjectHierarchyTreeView.cxx | forfullstack/slicersources-src | 91bcecf037a27f3fad4c0ab57e8286fc258bb0f5 | [
"Apache-2.0"
] | null | null | null | /*==============================================================================
Program: 3D Slicer
Copyright (c) Laboratory for Percutaneous Surgery (PerkLab)
Queen's University, Kingston, ON, Canada. All Rights Reserved.
See COPYRIGHT.txt
or http://www.slicer.org/copyright/copyright.txt for details.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
This file was originally developed by Csaba Pinter, PerkLab, Queen's University
and was supported through the Applied Cancer Research Unit program of Cancer Care
Ontario with funds provided by the Ontario Ministry of Health and Long-Term Care
==============================================================================*/
// Qt includes
#include <QHeaderView>
#include <QAction>
#include <QActionGroup>
#include <QMenu>
#include <QMouseEvent>
#include <QKeyEvent>
#include <QInputDialog>
#include <QMessageBox>
#include <QDebug>
#include <QToolTip>
#include <QBuffer>
#include <QApplication>
// SubjectHierarchy includes
#include "qMRMLSubjectHierarchyTreeView.h"
#include "qMRMLSubjectHierarchyModel.h"
#include "qMRMLSortFilterSubjectHierarchyProxyModel.h"
#include "qMRMLTransformItemDelegate.h"
#include "vtkSlicerSubjectHierarchyModuleLogic.h"
#include "qSlicerSubjectHierarchyPluginHandler.h"
#include "qSlicerSubjectHierarchyAbstractPlugin.h"
#include "qSlicerSubjectHierarchyDefaultPlugin.h"
// Terminologies includes
#include "qSlicerTerminologyItemDelegate.h"
// MRML includes
#include <vtkMRMLScene.h>
#include <vtkMRMLScalarVolumeNode.h>
// qMRML includes
#include "qMRMLItemDelegate.h"
// VTK includes
#include <vtkIdList.h>
//------------------------------------------------------------------------------
/// \ingroup Slicer_QtModules_SubjectHierarchy
class qMRMLSubjectHierarchyTreeViewPrivate
{
Q_DECLARE_PUBLIC(qMRMLSubjectHierarchyTreeView);
protected:
qMRMLSubjectHierarchyTreeView* const q_ptr;
public:
qMRMLSubjectHierarchyTreeViewPrivate(qMRMLSubjectHierarchyTreeView& object);
virtual void init();
/// Setup all actions for tree view
void setupActions();
/// Get list of enabled plugins \sa PluginWhitelist \sa PluginBlacklist
QList<qSlicerSubjectHierarchyAbstractPlugin*> enabledPlugins();
public:
qMRMLSubjectHierarchyModel* Model;
qMRMLSortFilterSubjectHierarchyProxyModel* SortFilterModel;
bool ShowRootItem;
vtkIdType RootItemID;
bool ContextMenuEnabled;
bool EditActionVisible;
bool SelectRoleSubMenuVisible;
QMenu* NodeMenu;
QAction* RenameAction;
QAction* DeleteAction;
QAction* EditAction;
QAction* ToggleVisibilityAction;
QList<QAction*> SelectPluginActions;
QMenu* SelectPluginSubMenu;
QActionGroup* SelectPluginActionGroup;
QAction* ExpandToDepthAction;
QMenu* SceneMenu;
QMenu* VisibilityMenu;
QStringList PluginWhitelist;
QStringList PluginBlacklist;
qMRMLTransformItemDelegate* TransformItemDelegate;
/// Subject hierarchy node
vtkWeakPointer<vtkMRMLSubjectHierarchyNode> SubjectHierarchyNode;
/// Flag determining whether to highlight items referenced by DICOM. Storing DICOM references:
/// Referenced SOP instance UIDs (in attribute named vtkMRMLSubjectHierarchyConstants::GetDICOMReferencedInstanceUIDsAttributeName())
/// -> SH node instance UIDs (serialized string lists in subject hierarchy UID vtkMRMLSubjectHierarchyConstants::GetDICOMInstanceUIDName())
bool HighlightReferencedItems;
/// Cached list of selected items to return the current selection
QList<vtkIdType> SelectedItems;
/// List of selected items to restore at the end of batch processing (the whole tree is rebuilt and selection is lost)
QList<vtkIdType> SelectedItemsToRestore;
/// Cached list of highlighted items to speed up clearing highlight after new selection
QList<vtkIdType> HighlightedItems;
};
//------------------------------------------------------------------------------
qMRMLSubjectHierarchyTreeViewPrivate::qMRMLSubjectHierarchyTreeViewPrivate(qMRMLSubjectHierarchyTreeView& object)
: q_ptr(&object)
, Model(nullptr)
, SortFilterModel(nullptr)
, ShowRootItem(false)
, RootItemID(vtkMRMLSubjectHierarchyNode::INVALID_ITEM_ID)
, ContextMenuEnabled(true)
, EditActionVisible(true)
, SelectRoleSubMenuVisible(false)
, NodeMenu(nullptr)
, RenameAction(nullptr)
, DeleteAction(nullptr)
, EditAction(nullptr)
, ToggleVisibilityAction(nullptr)
, SelectPluginSubMenu(nullptr)
, SelectPluginActionGroup(nullptr)
, ExpandToDepthAction(nullptr)
, SceneMenu(nullptr)
, VisibilityMenu(nullptr)
, TransformItemDelegate(nullptr)
, SubjectHierarchyNode(nullptr)
, HighlightReferencedItems(true)
{
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeViewPrivate::init()
{
Q_Q(qMRMLSubjectHierarchyTreeView);
// Set up scene model and sort and proxy model
this->Model = new qMRMLSubjectHierarchyModel(q);
QObject::connect( this->Model, SIGNAL(requestExpandItem(vtkIdType)), q, SLOT(expandItem(vtkIdType)) );
QObject::connect( this->Model, SIGNAL(requestCollapseItem(vtkIdType)), q, SLOT(collapseItem(vtkIdType)) );
QObject::connect( this->Model, SIGNAL(requestSelectItems(QList<vtkIdType>)), q, SLOT(setCurrentItems(QList<vtkIdType>)) );
QObject::connect( this->Model, SIGNAL(subjectHierarchyUpdated()), q, SLOT(updateRootItem()) );
this->SortFilterModel = new qMRMLSortFilterSubjectHierarchyProxyModel(q);
q->QTreeView::setModel(this->SortFilterModel);
QObject::connect( q->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
q, SLOT(onSelectionChanged(QItemSelection,QItemSelection)) );
this->SortFilterModel->setParent(q);
this->SortFilterModel->setSourceModel(this->Model);
// Set up headers
q->resetColumnSizesToDefault();
if (this->Model->descriptionColumn()>=0)
{
q->setColumnHidden(this->Model->descriptionColumn(), true);
}
// Set generic MRML item delegate
q->setItemDelegate(new qMRMLItemDelegate(q));
// Create default menu actions
this->NodeMenu = new QMenu(q);
this->NodeMenu->setObjectName("nodeMenuTreeView");
this->RenameAction = new QAction("名前の変更", this->NodeMenu);
this->NodeMenu->addAction(this->RenameAction);
QObject::connect(this->RenameAction, SIGNAL(triggered()), q, SLOT(renameCurrentItem()));
this->DeleteAction = new QAction("削除", this->NodeMenu);
this->NodeMenu->addAction(this->DeleteAction);
QObject::connect(this->DeleteAction, SIGNAL(triggered()), q, SLOT(deleteSelectedItems()));
this->EditAction = new QAction("Edit properties...", this->NodeMenu);
this->NodeMenu->addAction(this->EditAction);
QObject::connect(this->EditAction, SIGNAL(triggered()), q, SLOT(editCurrentItem()));
this->ToggleVisibilityAction = new QAction("Toggle visibility", this->NodeMenu);
this->NodeMenu->addAction(this->ToggleVisibilityAction);
QObject::connect(this->ToggleVisibilityAction, SIGNAL(triggered()), q, SLOT(toggleVisibilityOfSelectedItems()));
this->SceneMenu = new QMenu(q);
this->SceneMenu->setObjectName("sceneMenuTreeView");
this->VisibilityMenu = new QMenu(q);
this->VisibilityMenu->setObjectName("visibilityMenuTreeView");
// Set item delegate for color column
q->setItemDelegateForColumn(this->Model->colorColumn(), new qSlicerTerminologyItemDelegate(q));
// Set item delegate for transform column (that creates widgets for certain types of data)
this->TransformItemDelegate = new qMRMLTransformItemDelegate(q);
this->TransformItemDelegate->setMRMLScene(q->mrmlScene());
q->setItemDelegateForColumn(this->Model->transformColumn(), this->TransformItemDelegate);
QObject::connect( this->TransformItemDelegate, SIGNAL(removeTransformsFromBranchOfCurrentItem()),
this->Model, SLOT(onRemoveTransformsFromBranchOfCurrentItem()) );
QObject::connect( this->TransformItemDelegate, SIGNAL(hardenTransformOnBranchOfCurrentItem()),
this->Model, SLOT(onHardenTransformOnBranchOfCurrentItem()) );
q->setContextMenuPolicy(Qt::CustomContextMenu);
QObject::connect(q, SIGNAL(customContextMenuRequested(const QPoint&)), q, SLOT(onCustomContextMenu(const QPoint&)));
// Make connections
QObject::connect( this->Model, SIGNAL(invalidateFilter()), this->SortFilterModel, SLOT(invalidate()) );
QObject::connect( q, SIGNAL(expanded(const QModelIndex&)), q, SLOT(onItemExpanded(const QModelIndex&)) );
QObject::connect( q, SIGNAL(collapsed(const QModelIndex&)), q, SLOT(onItemCollapsed(const QModelIndex&)) );
// Set up scene and node actions for the tree view
this->SceneMenu->setVisible(false);
this->setupActions();
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::resetColumnSizesToDefault()
{
Q_D(qMRMLSubjectHierarchyTreeView);
// Set up headers
this->header()->setStretchLastSection(false);
if (this->header()->count() <= 0)
{
return;
}
if (d->Model->nameColumn() >= 0)
{
this->header()->setSectionResizeMode(d->Model->nameColumn(), QHeaderView::Stretch);
}
if (d->Model->descriptionColumn() >= 0)
{
this->header()->setSectionResizeMode(d->Model->descriptionColumn(), QHeaderView::Interactive);
}
if (d->Model->visibilityColumn() >= 0)
{
this->header()->setSectionResizeMode(d->Model->visibilityColumn(), QHeaderView::ResizeToContents);
}
if (d->Model->colorColumn() >= 0)
{
this->header()->setSectionResizeMode(d->Model->colorColumn(), QHeaderView::ResizeToContents);
}
if (d->Model->transformColumn() >= 0)
{
this->header()->setSectionResizeMode(d->Model->transformColumn(), QHeaderView::ResizeToContents);
}
if (d->Model->idColumn() >= 0)
{
this->header()->setSectionResizeMode(d->Model->idColumn(), QHeaderView::ResizeToContents);
}
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeViewPrivate::setupActions()
{
Q_Q(qMRMLSubjectHierarchyTreeView);
// Set up expand to level action and its menu
this->ExpandToDepthAction = new QAction("Expand tree to level...", this->NodeMenu);
//this->SceneMenu->addAction(this->ExpandToDepthAction);
QMenu* expandToDepthSubMenu = new QMenu();
this->ExpandToDepthAction->setMenu(expandToDepthSubMenu);
QAction* expandToDepth_1 = new QAction("1",q);
QObject::connect(expandToDepth_1, SIGNAL(triggered()), q, SLOT(expandToDepthFromContextMenu()));
expandToDepthSubMenu->addAction(expandToDepth_1);
this->ExpandToDepthAction->setMenu(expandToDepthSubMenu);
QAction* expandToDepth_2 = new QAction("2",q);
QObject::connect(expandToDepth_2, SIGNAL(triggered()), q, SLOT(expandToDepthFromContextMenu()));
expandToDepthSubMenu->addAction(expandToDepth_2);
this->ExpandToDepthAction->setMenu(expandToDepthSubMenu);
QAction* expandToDepth_3 = new QAction("3",q);
QObject::connect(expandToDepth_3, SIGNAL(triggered()), q, SLOT(expandToDepthFromContextMenu()));
expandToDepthSubMenu->addAction(expandToDepth_3);
this->ExpandToDepthAction->setMenu(expandToDepthSubMenu);
QAction* expandToDepth_4 = new QAction("4",q);
QObject::connect(expandToDepth_4, SIGNAL(triggered()), q, SLOT(expandToDepthFromContextMenu()));
expandToDepthSubMenu->addAction(expandToDepth_4);
//this->ExpandToDepthAction->hide();
// Perform tasks needed for all plugins
int index = 0; // Index used to insert actions before default tree actions
foreach (qSlicerSubjectHierarchyAbstractPlugin* plugin, qSlicerSubjectHierarchyPluginHandler::instance()->allPlugins())
{
// Add node context menu actions
foreach (QAction* action, plugin->itemContextMenuActions())
{
this->NodeMenu->insertAction(this->NodeMenu->actions()[index++], action);
}
// Add scene context menu actions
foreach (QAction* action, plugin->sceneContextMenuActions())
{
this->SceneMenu->addAction(action);
}
// Add visibility context menu actions
foreach (QAction* action, plugin->visibilityContextMenuActions())
{
this->VisibilityMenu->addAction(action);
}
// Connect plugin events to be handled by the tree view
QObject::connect( plugin, SIGNAL(requestExpandItem(vtkIdType)), q, SLOT(expandItem(vtkIdType)) );
QObject::connect( plugin, SIGNAL(requestInvalidateFilter()), q->model(), SIGNAL(invalidateFilter()) );
}
// Create a plugin selection action for each plugin in a sub-menu
this->SelectPluginSubMenu = this->NodeMenu->addMenu("Select role");
this->SelectPluginActionGroup = new QActionGroup(q);
foreach (qSlicerSubjectHierarchyAbstractPlugin* plugin, qSlicerSubjectHierarchyPluginHandler::instance()->allPlugins())
{
QAction* selectPluginAction = new QAction(plugin->name(),q);
selectPluginAction->setCheckable(true);
selectPluginAction->setActionGroup(this->SelectPluginActionGroup);
selectPluginAction->setData(QVariant(plugin->name()));
this->SelectPluginSubMenu->addAction(selectPluginAction);
QObject::connect(selectPluginAction, SIGNAL(triggered()), q, SLOT(selectPluginForCurrentItem()));
this->SelectPluginActions << selectPluginAction;
}
// Update actions in owner plugin sub-menu when opened
QObject::connect( this->SelectPluginSubMenu, SIGNAL(aboutToShow()), q, SLOT(updateSelectPluginActions()) );
}
//------------------------------------------------------------------------------
QList<qSlicerSubjectHierarchyAbstractPlugin*> qMRMLSubjectHierarchyTreeViewPrivate::enabledPlugins()
{
QList<qSlicerSubjectHierarchyAbstractPlugin*> enabledPluginList;
foreach (qSlicerSubjectHierarchyAbstractPlugin* plugin, qSlicerSubjectHierarchyPluginHandler::instance()->allPlugins())
{
QString pluginName = plugin->name();
bool whitelisted = (this->PluginWhitelist.isEmpty() || this->PluginWhitelist.contains(pluginName));
bool blacklisted = (!this->PluginBlacklist.isEmpty() && this->PluginBlacklist.contains(pluginName));
if ((whitelisted && !blacklisted) || !pluginName.compare("Default"))
{
enabledPluginList << plugin;
}
}
return enabledPluginList;
}
//------------------------------------------------------------------------------
// qMRMLSubjectHierarchyTreeView
//------------------------------------------------------------------------------
qMRMLSubjectHierarchyTreeView::qMRMLSubjectHierarchyTreeView(QWidget *parent)
: QTreeView(parent)
, d_ptr(new qMRMLSubjectHierarchyTreeViewPrivate(*this))
{
Q_D(qMRMLSubjectHierarchyTreeView);
d->init();
}
//------------------------------------------------------------------------------
qMRMLSubjectHierarchyTreeView::~qMRMLSubjectHierarchyTreeView() = default;
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setSubjectHierarchyNode(vtkMRMLSubjectHierarchyNode* shNode)
{
Q_D(qMRMLSubjectHierarchyTreeView);
d->SubjectHierarchyNode = shNode;
qvtkReconnect( shNode, vtkMRMLSubjectHierarchyNode::SubjectHierarchyItemModifiedEvent,
this, SLOT( onSubjectHierarchyItemModified(vtkObject*,void*) ) );
if (!shNode)
{
d->Model->setMRMLScene(nullptr);
d->TransformItemDelegate->setMRMLScene(nullptr);
return;
}
vtkMRMLScene* scene = shNode->GetScene();
if (!scene)
{
qCritical() << Q_FUNC_INFO << ": Given subject hierarchy node is not in a MRML scene";
}
d->Model->setMRMLScene(scene);
d->TransformItemDelegate->setMRMLScene(scene);
this->setRootItem(shNode->GetSceneItemID());
this->expandToDepth(4);
}
//------------------------------------------------------------------------------
vtkMRMLSubjectHierarchyNode* qMRMLSubjectHierarchyTreeView::subjectHierarchyNode()const
{
Q_D(const qMRMLSubjectHierarchyTreeView);
return d->SubjectHierarchyNode;
}
//------------------------------------------------------------------------------
vtkMRMLScene* qMRMLSubjectHierarchyTreeView::mrmlScene()const
{
Q_D(const qMRMLSubjectHierarchyTreeView);
return d->Model ? d->Model->mrmlScene() : nullptr;
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setMRMLScene(vtkMRMLScene* scene)
{
if (this->mrmlScene() == scene)
{
return;
}
this->setSubjectHierarchyNode(scene ? vtkMRMLSubjectHierarchyNode::GetSubjectHierarchyNode(scene) : nullptr);
// Connect scene close ended event so that subject hierarchy can be cleared
qvtkReconnect( scene, vtkMRMLScene::EndCloseEvent, this, SLOT( onMRMLSceneCloseEnded(vtkObject*) ) );
qvtkReconnect( scene, vtkMRMLScene::StartBatchProcessEvent, this, SLOT( onMRMLSceneStartBatchProcess(vtkObject*) ) );
qvtkReconnect( scene, vtkMRMLScene::EndBatchProcessEvent, this, SLOT( onMRMLSceneEndBatchProcess(vtkObject*) ) );
}
//------------------------------------------------------------------------------
vtkIdType qMRMLSubjectHierarchyTreeView::currentItem()const
{
Q_D(const qMRMLSubjectHierarchyTreeView);
return d->SelectedItems.count() ? d->SelectedItems[0] : vtkMRMLSubjectHierarchyNode::INVALID_ITEM_ID;
}
//------------------------------------------------------------------------------
vtkMRMLNode* qMRMLSubjectHierarchyTreeView::currentNode()const
{
Q_D(const qMRMLSubjectHierarchyTreeView);
vtkIdType itemID = currentItem();
if (itemID == vtkMRMLSubjectHierarchyNode::INVALID_ITEM_ID || !d->SubjectHierarchyNode)
{
return nullptr;
}
return d->SubjectHierarchyNode->GetItemDataNode(itemID);
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setCurrentItem(vtkIdType itemID)
{
Q_D(const qMRMLSubjectHierarchyTreeView);
if (!d->SortFilterModel)
{
qCritical() << Q_FUNC_INFO << ": Invalid data model";
return;
}
QModelIndex itemIndex = d->SortFilterModel->indexFromSubjectHierarchyItem(itemID);
this->selectionModel()->select(itemIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
}
//------------------------------------------------------------------------------
QList<vtkIdType> qMRMLSubjectHierarchyTreeView::currentItems()
{
Q_D(const qMRMLSubjectHierarchyTreeView);
return d->SelectedItems;
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::currentItems(vtkIdList* selectedItems)
{
Q_D(const qMRMLSubjectHierarchyTreeView);
if (!selectedItems)
{
qCritical() << Q_FUNC_INFO << ": Invalid item list";
return;
}
foreach (vtkIdType item, d->SelectedItems)
{
selectedItems->InsertNextId(item);
}
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setCurrentItems(QList<vtkIdType> items)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SortFilterModel)
{
qCritical() << Q_FUNC_INFO << ": Invalid data model";
return;
}
this->clearSelection();
foreach (long itemID, items)
{
QModelIndex itemIndex = d->SortFilterModel->indexFromSubjectHierarchyItem(vtkIdType(itemID));
if (itemIndex.isValid())
{
this->selectionModel()->select(itemIndex, QItemSelectionModel::Select | QItemSelectionModel::Rows);
}
}
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setCurrentItems(vtkIdList* items)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SortFilterModel)
{
qCritical() << Q_FUNC_INFO << ": Invalid data model";
return;
}
if (!items)
{
qCritical() << Q_FUNC_INFO << ": Invalid item list";
return;
}
this->clearSelection();
for (int index=0; index<items->GetNumberOfIds(); ++index)
{
QModelIndex itemIndex = d->SortFilterModel->indexFromSubjectHierarchyItem(items->GetId(index));
if (itemIndex.isValid())
{
this->selectionModel()->select(itemIndex, QItemSelectionModel::Select | QItemSelectionModel::Rows);
}
}
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setCurrentNode(vtkMRMLNode* node)
{
Q_D(const qMRMLSubjectHierarchyTreeView);
if (!node || !d->SubjectHierarchyNode)
{
return;
}
vtkIdType itemID = d->SubjectHierarchyNode->GetItemByDataNode(node);
if (!itemID)
{
qCritical() << Q_FUNC_INFO << ": Unable to find subject hierarchy item by data node " << node->GetName();
return;
}
this->setCurrentItem(itemID);
}
//--------------------------------------------------------------------------
qMRMLSortFilterSubjectHierarchyProxyModel* qMRMLSubjectHierarchyTreeView::sortFilterProxyModel()const
{
Q_D(const qMRMLSubjectHierarchyTreeView);
if (!d->SortFilterModel)
{
qCritical() << Q_FUNC_INFO << ": Invalid sort filter proxy model";
}
return d->SortFilterModel;
}
//--------------------------------------------------------------------------
qMRMLSubjectHierarchyModel* qMRMLSubjectHierarchyTreeView::model()const
{
Q_D(const qMRMLSubjectHierarchyTreeView);
if (!d->Model)
{
qCritical() << Q_FUNC_INFO << ": Invalid data model";
}
return d->Model;
}
//--------------------------------------------------------------------------
int qMRMLSubjectHierarchyTreeView::displayedItemCount()const
{
Q_D(const qMRMLSubjectHierarchyTreeView);
int count = this->sortFilterProxyModel()->acceptedItemCount(this->rootItem());
if (d->ShowRootItem)
{
count++;
}
return count;
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setShowRootItem(bool show)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (d->ShowRootItem == show)
{
return;
}
vtkIdType oldRootItemID = this->rootItem();
d->ShowRootItem = show;
this->setRootItem(oldRootItemID);
}
//--------------------------------------------------------------------------
bool qMRMLSubjectHierarchyTreeView::showRootItem()const
{
Q_D(const qMRMLSubjectHierarchyTreeView);
return d->ShowRootItem;
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setRootItem(vtkIdType rootItemID)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode)
{
return;
}
qMRMLSubjectHierarchyModel* sceneModel = qobject_cast<qMRMLSubjectHierarchyModel*>(this->model());
// Reset item in unaffiliated filter (that hides all siblings and their children)
this->sortFilterProxyModel()->setHideItemsUnaffiliatedWithItemID(vtkMRMLSubjectHierarchyNode::INVALID_ITEM_ID);
QModelIndex treeRootIndex;
if (!rootItemID)
{
treeRootIndex = sceneModel->invisibleRootItem()->index();
}
else if (rootItemID == d->SubjectHierarchyNode->GetSceneItemID())
{
if (d->ShowRootItem)
{
// Scene is a special item, so it needs to be shown, then the invisible root item needs to be root
treeRootIndex = sceneModel->invisibleRootItem()->index();
}
else
{
treeRootIndex = this->sortFilterProxyModel()->subjectHierarchySceneIndex();
}
}
else
{
treeRootIndex = this->sortFilterProxyModel()->indexFromSubjectHierarchyItem(rootItemID);
if (d->ShowRootItem)
{
// Hide the siblings of the root item and their children
this->sortFilterProxyModel()->setHideItemsUnaffiliatedWithItemID(rootItemID);
// The parent of the root node becomes the root for QTreeView.
treeRootIndex = treeRootIndex.parent();
rootItemID = this->sortFilterProxyModel()->subjectHierarchyItemFromIndex(treeRootIndex);
}
}
//TODO: Connect SH node's item modified event if necessary
//qvtkReconnect(this->rootItem(), rootItemID, vtkCommand::ModifiedEvent,
// this, SLOT(updateRootItem(vtkObject*)));
d->RootItemID = rootItemID;
this->setRootIndex(treeRootIndex);
}
//--------------------------------------------------------------------------
vtkIdType qMRMLSubjectHierarchyTreeView::rootItem()const
{
Q_D(const qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode)
{
return vtkMRMLSubjectHierarchyNode::INVALID_ITEM_ID;
}
vtkIdType treeRootItemID = this->sortFilterProxyModel()->subjectHierarchyItemFromIndex(this->rootIndex());
if (d->ShowRootItem)
{
if (d->RootItemID == d->SubjectHierarchyNode->GetSceneItemID())
{
// Scene is a special item, so it needs to be shown, then the invisible root item needs to be root.
// So in that case no checks are performed
return d->RootItemID;
}
else if (this->sortFilterProxyModel()->hideItemsUnaffiliatedWithItemID())
{
treeRootItemID = this->sortFilterProxyModel()->hideItemsUnaffiliatedWithItemID();
}
}
// Check if stored root item ID matches the actual root item in the tree view.
// If the tree is empty (e.g. due to filters), then treeRootItemID is invalid, and then it's not an error
if (treeRootItemID && d->RootItemID != treeRootItemID)
{
qCritical() << Q_FUNC_INFO << ": Root item mismatch";
}
return d->RootItemID;
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::updateRootItem()
{
Q_D(qMRMLSubjectHierarchyTreeView);
// The scene might have been updated, need to update root item as well to restore view
this->setRootItem(d->RootItemID);
}
//--------------------------------------------------------------------------
bool qMRMLSubjectHierarchyTreeView::highlightReferencedItems()const
{
Q_D(const qMRMLSubjectHierarchyTreeView);
return d->HighlightReferencedItems;
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setHighlightReferencedItems(bool highlightOn)
{
Q_D(qMRMLSubjectHierarchyTreeView);
d->HighlightReferencedItems = highlightOn;
}
//--------------------------------------------------------------------------
bool qMRMLSubjectHierarchyTreeView::contextMenuEnabled()const
{
Q_D(const qMRMLSubjectHierarchyTreeView);
return d->ContextMenuEnabled;
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setContextMenuEnabled(bool enabled)
{
Q_D(qMRMLSubjectHierarchyTreeView);
d->ContextMenuEnabled = enabled;
}
//--------------------------------------------------------------------------
bool qMRMLSubjectHierarchyTreeView::editMenuActionVisible()const
{
Q_D(const qMRMLSubjectHierarchyTreeView);
return d->EditActionVisible;
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setEditMenuActionVisible(bool visible)
{
Q_D(qMRMLSubjectHierarchyTreeView);
d->EditActionVisible = visible;
}
//--------------------------------------------------------------------------
bool qMRMLSubjectHierarchyTreeView::selectRoleSubMenuVisible()const
{
Q_D(const qMRMLSubjectHierarchyTreeView);
return d->SelectRoleSubMenuVisible;
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setSelectRoleSubMenuVisible(bool visible)
{
Q_D(qMRMLSubjectHierarchyTreeView);
d->SelectRoleSubMenuVisible = visible;
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setAttributeFilter(const QString& attributeName, const QVariant& attributeValue/*=QVariant()*/)
{
this->sortFilterProxyModel()->setAttributeNameFilter(attributeName);
this->sortFilterProxyModel()->setAttributeValueFilter(attributeValue.toString());
// Reset root item, as it may have been corrupted, when tree became empty due to the filter
this->setRootItem(this->rootItem());
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setAttributeNameFilter(const QString& attributeName)
{
this->sortFilterProxyModel()->setAttributeNameFilter(attributeName);
// Reset root item, as it may have been corrupted, when tree became empty due to the filter
this->setRootItem(this->rootItem());
}
//--------------------------------------------------------------------------
QString qMRMLSubjectHierarchyTreeView::attributeNameFilter()const
{
return this->sortFilterProxyModel()->attributeNameFilter();
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setAttributeValueFilter(const QString& attributeValue)
{
this->sortFilterProxyModel()->setAttributeValueFilter(attributeValue);
// Reset root item, as it may have been corrupted, when tree became empty due to the filter
this->setRootItem(this->rootItem());
}
//--------------------------------------------------------------------------
QString qMRMLSubjectHierarchyTreeView::attributeValueFilter()const
{
return this->sortFilterProxyModel()->attributeValueFilter();
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::removeAttributeFilter()
{
this->sortFilterProxyModel()->setAttributeNameFilter(QString());
this->sortFilterProxyModel()->setAttributeValueFilter(QString());
// Reset root item, as it may have been corrupted, when tree became empty due to the filter
this->setRootItem(this->rootItem());
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setLevelFilter(QStringList &levelFilter)
{
this->sortFilterProxyModel()->setLevelFilter(levelFilter);
// Reset root item, as it may have been corrupted, when tree became empty due to the filter
this->setRootItem(this->rootItem());
}
//--------------------------------------------------------------------------
QStringList qMRMLSubjectHierarchyTreeView::levelFilter()const
{
return this->sortFilterProxyModel()->levelFilter();
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setNameFilter(QString &nameFilter)
{
this->sortFilterProxyModel()->setNameFilter(nameFilter);
// Reset root item, as it may have been corrupted, when tree became empty due to the filter
this->setRootItem(this->rootItem());
}
//--------------------------------------------------------------------------
QString qMRMLSubjectHierarchyTreeView::nameFilter()const
{
return this->sortFilterProxyModel()->nameFilter();
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setNodeTypes(const QStringList& types)
{
this->sortFilterProxyModel()->setNodeTypes(types);
// Reset root item, as it may have been corrupted, when tree became empty due to the filter
this->setRootItem(this->rootItem());
}
//--------------------------------------------------------------------------
QStringList qMRMLSubjectHierarchyTreeView::nodeTypes()const
{
return this->sortFilterProxyModel()->nodeTypes();
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setHideChildNodeTypes(const QStringList& types)
{
this->sortFilterProxyModel()->setHideChildNodeTypes(types);
// Reset root item, as it may have been corrupted, when tree became empty due to the filter
this->setRootItem(this->rootItem());
}
//--------------------------------------------------------------------------
QStringList qMRMLSubjectHierarchyTreeView::hideChildNodeTypes()const
{
return this->sortFilterProxyModel()->hideChildNodeTypes();
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::toggleSubjectHierarchyItemVisibility(vtkIdType itemID)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode)
{
return;
}
if (!itemID)
{
return;
}
// If more than 10 item visibilities are changed, then enter in batch processing state
vtkNew<vtkIdList> childItemsList;
d->SubjectHierarchyNode->GetItemChildren(itemID, childItemsList, true);
bool batchProcessing = (childItemsList->GetNumberOfIds() > 10);
if (batchProcessing)
{
d->SubjectHierarchyNode->GetScene()->StartState(vtkMRMLScene::BatchProcessState);
}
qSlicerSubjectHierarchyAbstractPlugin* ownerPlugin =
qSlicerSubjectHierarchyPluginHandler::instance()->getOwnerPluginForSubjectHierarchyItem(itemID);
if (!ownerPlugin)
{
qCritical() << Q_FUNC_INFO << ": Subject hierarchy item " << itemID << " (named "
<< d->SubjectHierarchyNode->GetItemName(itemID).c_str() << ") is not owned by any plugin";
return;
}
int visible = (ownerPlugin->getDisplayVisibility(itemID) > 0 ? 0 : 1);
ownerPlugin->setDisplayVisibility(itemID, visible);
if (batchProcessing)
{
d->SubjectHierarchyNode->GetScene()->EndState(vtkMRMLScene::BatchProcessState);
}
// Trigger view update for the modified item
d->SubjectHierarchyNode->ItemModified(itemID);
}
//------------------------------------------------------------------------------
bool qMRMLSubjectHierarchyTreeView::clickDecoration(QMouseEvent* e)
{
Q_D(qMRMLSubjectHierarchyTreeView);
QModelIndex index = this->indexAt(e->pos());
QStyleOptionViewItem opt = this->viewOptions();
opt.rect = this->visualRect(index);
qobject_cast<qMRMLItemDelegate*>(this->itemDelegate())->initStyleOption(&opt,index);
QRect decorationElement = this->style()->subElementRect(QStyle::SE_ItemViewItemDecoration, &opt, this);
if (!decorationElement.contains(e->pos()))
{
// Mouse event is not within an item decoration
return false;
}
QModelIndex sourceIndex = this->sortFilterProxyModel()->mapToSource(index);
if (!(sourceIndex.flags() & Qt::ItemIsEnabled))
{
// Item is disabled
return false;
}
// Visibility and color columns
if ( sourceIndex.column() == this->model()->visibilityColumn()
|| sourceIndex.column() == this->model()->colorColumn() )
{
vtkIdType itemID = d->SortFilterModel->subjectHierarchyItemFromIndex(index);
if (!itemID)
{
// Valid item is needed for visibility actions
return false;
}
if (e->button() == Qt::LeftButton && sourceIndex.column() == this->model()->visibilityColumn())
{
// Toggle simple visibility
this->toggleSubjectHierarchyItemVisibility(itemID);
}
return true;
}
return false;
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::mousePressEvent(QMouseEvent* e)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode)
{
return;
}
// Perform default mouse press event (make selections etc.)
this->QTreeView::mousePressEvent(e);
if (e->button() == Qt::LeftButton)
{
// Custom left button action for item decorations (i.e. icon): simple visibility toggle
if (this->clickDecoration(e))
{
return;
}
}
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::keyPressEvent(QKeyEvent* e)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (e->key() == Qt::Key_Space)
{
// Show/hide current item(s) using space
QList<vtkIdType> currentItemIDs = d->SelectedItems;
foreach (vtkIdType itemID, currentItemIDs)
{
this->toggleSubjectHierarchyItemVisibility(itemID);
}
}
this->QTreeView::keyPressEvent(e);
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::onSelectionChanged(const QItemSelection& selected, const QItemSelection& deselected)
{
Q_UNUSED(selected);
Q_UNUSED(deselected);
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SortFilterModel || !d->SubjectHierarchyNode || this->mrmlScene()->IsBatchProcessing())
{
return;
}
// Collect selected subject hierarchy items
QList<vtkIdType> selectedShItems;
QList<QModelIndex> selectedIndices = this->selectedIndexes();
foreach (QModelIndex index, selectedIndices)
{
// Only consider the first column to avoid duplicates
if (index.column() != 0)
{
continue;
}
vtkIdType itemID = this->sortFilterProxyModel()->subjectHierarchyItemFromIndex(index);
if (itemID)
{
selectedShItems << itemID;
}
}
// If no item was selected, then the scene is considered to be selected
if (selectedShItems.count() == 0)
{
selectedShItems << d->SubjectHierarchyNode->GetSceneItemID();
}
// Set current item(s) to plugin handler
qSlicerSubjectHierarchyPluginHandler::instance()->setCurrentItems(selectedShItems);
// Cache selected item(s) so that currentItem and currentItems can return them quickly
d->SelectedItems = selectedShItems;
// Highlight items referenced by DICOM in case of single-selection
// Referenced SOP instance UIDs (in attribute named vtkMRMLSubjectHierarchyConstants::GetDICOMReferencedInstanceUIDsAttributeName())
// -> SH item instance UIDs (serialized string lists in subject hierarchy UID vtkMRMLSubjectHierarchyConstants::GetDICOMInstanceUIDName())
if (this->highlightReferencedItems())
{
this->applyReferenceHighlightForItems(selectedShItems);
}
// Emit current item changed signal
vtkIdType newCurrentItemID = vtkMRMLSubjectHierarchyNode::INVALID_ITEM_ID;
if (selectedIndices.count() > 0)
{
newCurrentItemID = d->SortFilterModel->subjectHierarchyItemFromIndex(selectedIndices[0]);
}
emit currentItemChanged(newCurrentItemID);
emit currentItemsChanged(selectedShItems);
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::onItemExpanded(const QModelIndex &expandedItemIndex)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode || !d->SortFilterModel)
{
return;
}
vtkIdType expandedShItemID = d->SortFilterModel->subjectHierarchyItemFromIndex(expandedItemIndex);
if (expandedShItemID)
{
d->SubjectHierarchyNode->SetItemExpanded(expandedShItemID, true);
}
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::onItemCollapsed(const QModelIndex &collapsedItemIndex)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode || !d->SortFilterModel)
{
return;
}
vtkIdType collapsedShItemID = d->SortFilterModel->subjectHierarchyItemFromIndex(collapsedItemIndex);
if (collapsedShItemID)
{
d->SubjectHierarchyNode->SetItemExpanded(collapsedShItemID, false);
}
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::populateContextMenuForItem(vtkIdType itemID)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode)
{
qCritical() << Q_FUNC_INFO << ": Invalid subject hierarchy";
return;
}
// Have all plugins hide all context menu actions
foreach (qSlicerSubjectHierarchyAbstractPlugin* plugin, qSlicerSubjectHierarchyPluginHandler::instance()->allPlugins())
{
plugin->hideAllContextMenuActions();
}
// Show multi-selection context menu if there are more than one selected items,
// and right-click didn't happen on the scene or the empty area
if ( d->SelectedItems.size() > 1
&& itemID && itemID != d->SubjectHierarchyNode->GetSceneItemID() )
{
// Multi-selection: only show delete and toggle visibility actions
d->EditAction->setVisible(false);
d->RenameAction->setVisible(false);
d->ToggleVisibilityAction->setVisible(true);
d->SelectPluginSubMenu->menuAction()->setVisible(false);
return;
}
// Single selection
vtkIdType currentItemID = this->currentItem();
// If clicked item is the scene or the empty area, then show scene menu regardless the selection
if (!itemID || itemID == d->SubjectHierarchyNode->GetSceneItemID())
{
currentItemID = d->SubjectHierarchyNode->GetSceneItemID();
}
// Do not show certain actions for the scene or empty area
if (!currentItemID || currentItemID == d->SubjectHierarchyNode->GetSceneItemID())
{
d->EditAction->setVisible(false);
d->RenameAction->setVisible(false);
d->ToggleVisibilityAction->setVisible(false);
d->SelectPluginSubMenu->menuAction()->setVisible(false);
}
else
{
d->EditAction->setVisible(d->EditActionVisible);
d->RenameAction->setVisible(true);
d->ToggleVisibilityAction->setVisible(false);
d->SelectPluginSubMenu->menuAction()->setVisible(d->SelectRoleSubMenuVisible);
}
// Have all enabled plugins show context menu actions for current item
foreach (qSlicerSubjectHierarchyAbstractPlugin* plugin, d->enabledPlugins())
{
plugin->showContextMenuActionsForItem(currentItemID);
}
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::populateVisibilityContextMenuForItem(vtkIdType itemID)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode)
{
qCritical() << Q_FUNC_INFO << ": Invalid subject hierarchy";
return;
}
if (!itemID || itemID == d->SubjectHierarchyNode->GetSceneItemID())
{
qWarning() << Q_FUNC_INFO << ": Invalid subject hierarchy item for visibility context menu: " << itemID;
return;
}
// Have all plugins hide all visibility context menu actions
foreach (qSlicerSubjectHierarchyAbstractPlugin* plugin, qSlicerSubjectHierarchyPluginHandler::instance()->allPlugins())
{
plugin->hideAllContextMenuActions();
}
// Have all enabled plugins show visibility context menu actions for current item
foreach (qSlicerSubjectHierarchyAbstractPlugin* plugin, d->enabledPlugins())
{
plugin->showVisibilityContextMenuActionsForItem(itemID);
}
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::expandItem(vtkIdType itemID)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (itemID)
{
QModelIndex itemIndex = d->SortFilterModel->indexFromSubjectHierarchyItem(itemID);
if (itemIndex.isValid())
{
this->expand(itemIndex);
}
}
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::collapseItem(vtkIdType itemID)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (itemID)
{
QModelIndex itemIndex = d->SortFilterModel->indexFromSubjectHierarchyItem(itemID);
if (itemIndex.isValid())
{
this->collapse(itemIndex);
}
}
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::selectPluginForCurrentItem()
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode)
{
qCritical() << Q_FUNC_INFO << ": Invalid subject hierarchy";
return;
}
vtkIdType currentItemID = this->currentItem();
if (!currentItemID)
{
qCritical() << Q_FUNC_INFO << ": Invalid current item for manually selecting role";
return;
}
QString selectedPluginName = d->SelectPluginActionGroup->checkedAction()->data().toString();
if (selectedPluginName.isEmpty())
{
qCritical() << Q_FUNC_INFO << ": No owner plugin found for item " << d->SubjectHierarchyNode->GetItemName(currentItemID).c_str();
return;
}
else if (!selectedPluginName.compare(d->SubjectHierarchyNode->GetItemOwnerPluginName(currentItemID).c_str()))
{
// Do nothing if the owner plugin stays the same
return;
}
// Set new owner plugin
d->SubjectHierarchyNode->SetItemOwnerPluginName(currentItemID, selectedPluginName.toUtf8().constData());
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::updateSelectPluginActions()
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode)
{
qCritical() << Q_FUNC_INFO << ": Invalid subject hierarchy";
return;
}
vtkIdType currentItemID = this->currentItem();
if (!currentItemID)
{
qCritical() << Q_FUNC_INFO << ": Invalid current item";
return;
}
QString ownerPluginName = QString(d->SubjectHierarchyNode->GetItemOwnerPluginName(currentItemID).c_str());
QList<qSlicerSubjectHierarchyAbstractPlugin*> enabledPluginsList = d->enabledPlugins();
foreach (QAction* currentSelectPluginAction, d->SelectPluginActions)
{
// Check select plugin action if it's the owner
bool isOwner = !(currentSelectPluginAction->data().toString().compare(ownerPluginName));
// Get confidence numbers and show the plugins with non-zero confidence
qSlicerSubjectHierarchyAbstractPlugin* currentPlugin =
qSlicerSubjectHierarchyPluginHandler::instance()->pluginByName( currentSelectPluginAction->data().toString() );
double confidenceNumber = currentPlugin->canOwnSubjectHierarchyItem(currentItemID);
// Do not show plugin in list if confidence is 0, or if it's disabled (by whitelist or blacklist).
// Always show owner plugin.
if ( (confidenceNumber <= 0.0 || !enabledPluginsList.contains(currentPlugin))
&& !isOwner )
{
currentSelectPluginAction->setVisible(false);
}
else
{
// Set text to display for the role
QString role = currentPlugin->roleForPlugin();
QString currentSelectPluginActionText = QString("%1: '%2', (%3%)").arg(
role).arg(currentPlugin->displayedItemName(currentItemID)).arg(confidenceNumber*100.0, 0, 'f', 0);
currentSelectPluginAction->setText(currentSelectPluginActionText);
currentSelectPluginAction->setVisible(true);
}
currentSelectPluginAction->setChecked(isOwner);
}
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::renameCurrentItem()
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode)
{
qCritical() << Q_FUNC_INFO << ": Invalid subject hierarchy";
return;
}
vtkIdType currentItemID = this->currentItem();
if (!currentItemID)
{
qCritical() << Q_FUNC_INFO << ": Invalid current item";
return;
}
// Pop up an entry box for the new name, with the old name as default
QString oldName = QString(d->SubjectHierarchyNode->GetItemName(currentItemID).c_str());
bool ok = false;
QString newName = QInputDialog::getText(this, "Rename " + oldName, "New name:", QLineEdit::Normal, oldName, &ok);
if (!ok)
{
return;
}
d->SubjectHierarchyNode->SetItemName(currentItemID, newName.toUtf8().constData());
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::editCurrentItem()
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode)
{
qCritical() << Q_FUNC_INFO << ": Invalid subject hierarchy";
return;
}
vtkIdType currentItemID = this->currentItem();
if (!currentItemID)
{
qCritical() << Q_FUNC_INFO << ": Invalid current item";
return;
}
qSlicerSubjectHierarchyAbstractPlugin* ownerPlugin =
qSlicerSubjectHierarchyPluginHandler::instance()->getOwnerPluginForSubjectHierarchyItem(currentItemID);
ownerPlugin->editProperties(currentItemID);
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::deleteSelectedItems()
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode)
{
qCritical() << Q_FUNC_INFO << ": Invalid subject hierarchy";
return;
}
// Remove each selected item
QList<vtkIdType> currentItemIDs = d->SelectedItems;
foreach (vtkIdType itemID, currentItemIDs)
{
if (itemID == d->SubjectHierarchyNode->GetSceneItemID())
{
// Do not delete scene (if no item is selected then the scene will be marked as selected)
continue;
}
// Ask the user whether to delete all the item's children
bool deleteChildren = false;
QMessageBox::StandardButton answer = QMessageBox::Yes;
if ( currentItemIDs.count() > 1
&& !qSlicerSubjectHierarchyPluginHandler::instance()->autoDeleteSubjectHierarchyChildren() )
{
answer =
QMessageBox::question(nullptr, tr("Delete subject hierarchy branch?"),
tr("The deleted subject hierarchy item has children. "
"Do you want to remove those too?\n\n"
"If you choose yes, the whole branch will be deleted, including all children.\n"
"If you choose Yes to All, this question never appears again, and all subject hierarchy children "
"are automatically deleted. This can be later changed in Application Settings."),
QMessageBox::Yes | QMessageBox::No | QMessageBox::YesToAll,
QMessageBox::No);
}
// Delete branch if the user chose yes
if (answer == QMessageBox::Yes || answer == QMessageBox::YesToAll)
{
deleteChildren = true;
}
// Save auto-creation flag in settings
if (answer == QMessageBox::YesToAll)
{
qSlicerSubjectHierarchyPluginHandler::instance()->setAutoDeleteSubjectHierarchyChildren(true);
}
// Remove item (and if requested its children) and its associated data node if any
if (!d->SubjectHierarchyNode->RemoveItem(itemID, true, deleteChildren))
{
qWarning() << Q_FUNC_INFO << ": Failed to remove subject hierarchy item (ID:"
<< itemID << ", name:" << d->SubjectHierarchyNode->GetItemName(itemID).c_str() << ")";
}
}
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::toggleVisibilityOfSelectedItems()
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode)
{
qCritical() << Q_FUNC_INFO << ": Invalid subject hierarchy";
return;
}
// Remove items from the list whose ancestor item is also contained
// to prevent toggling visibility multiple times on the same item
QList<vtkIdType> consolidatedItemIDs(d->SelectedItems);
foreach (vtkIdType itemID, d->SelectedItems)
{
// Get children recursively for current item
std::vector<vtkIdType> childItemIDs;
d->SubjectHierarchyNode->GetItemChildren(itemID, childItemIDs, true);
// If any of the current item's children is also in the list,
// then remove that child item from the consolidated list
std::vector<vtkIdType>::iterator childIt;
for (childIt=childItemIDs.begin(); childIt!=childItemIDs.end(); ++childIt)
{
vtkIdType childItemID = (*childIt);
if (d->SelectedItems.contains(childItemID))
{
consolidatedItemIDs.removeOne(childItemID);
}
}
}
// Toggle visibility on the remaining items
foreach (vtkIdType itemID, consolidatedItemIDs)
{
this->toggleSubjectHierarchyItemVisibility(itemID);
}
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::expandToDepthFromContextMenu()
{
QAction* senderAction = qobject_cast<QAction*>(this->sender());
if (!senderAction)
{
qCritical() << Q_FUNC_INFO << ": Unable to get sender action";
return;
}
int depth = senderAction->text().toInt();
this->expandToDepth(depth);
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::applyReferenceHighlightForItems(QList<vtkIdType> itemIDs)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode)
{
qCritical() << Q_FUNC_INFO << ": Invalid subject hierarchy";
return;
}
vtkMRMLScene* scene = this->mrmlScene();
if (!scene)
{
qCritical() << Q_FUNC_INFO << ": Invalid MRML scene";
return;
}
if (scene->IsImporting())
{
return;
}
// Get scene model and column to highlight
qMRMLSubjectHierarchyModel* sceneModel = qobject_cast<qMRMLSubjectHierarchyModel*>(this->model());
int nameColumn = sceneModel->nameColumn();
// Clear highlight for previously highlighted items
foreach (vtkIdType highlightedItemID, d->HighlightedItems)
{
QStandardItem* item = sceneModel->itemFromSubjectHierarchyItem(highlightedItemID, nameColumn);
if (item)
{
item->setBackground(Qt::transparent);
}
}
d->HighlightedItems.clear();
// Go through all given items
foreach (vtkIdType itemID, itemIDs)
{
if (itemID == d->SubjectHierarchyNode->GetSceneItemID())
{
continue;
}
vtkMRMLNode* node = d->SubjectHierarchyNode->GetItemDataNode(itemID);
// Get items referenced recursively by argument node by MRML
vtkSmartPointer<vtkCollection> recursivelyReferencedNodes;
recursivelyReferencedNodes.TakeReference(scene->GetReferencedNodes(node));
// Get items referenced by argument node by DICOM
std::vector<vtkIdType> directlyReferencedItems = d->SubjectHierarchyNode->GetItemsReferencedFromItemByDICOM(itemID);
// Get items referenced directly by argument node by MRML
if (node)
{
vtkSmartPointer<vtkCollection> referencedNodes;
referencedNodes.TakeReference(scene->GetReferencedNodes(node, false));
for (int index=0; index!=referencedNodes->GetNumberOfItems(); ++index)
{
vtkIdType nodeItemID = d->SubjectHierarchyNode->GetItemByDataNode(
vtkMRMLNode::SafeDownCast(referencedNodes->GetItemAsObject(index)) );
if ( nodeItemID && nodeItemID != itemID
&& (std::find(directlyReferencedItems.begin(), directlyReferencedItems.end(), nodeItemID) == directlyReferencedItems.end()) )
{
directlyReferencedItems.push_back(nodeItemID);
}
}
}
// Get items referencing the argument node by DICOM
std::vector<vtkIdType> referencingItems = d->SubjectHierarchyNode->GetItemsReferencingItemByDICOM(itemID);
// Get items referencing the argument node by MRML
if (node)
{
std::vector<vtkMRMLNode*> referencingNodes;
scene->GetReferencingNodes(node, referencingNodes);
for (std::vector<vtkMRMLNode*>::iterator refNodeIt=referencingNodes.begin(); refNodeIt!=referencingNodes.end(); refNodeIt++)
{
vtkIdType nodeItemID = d->SubjectHierarchyNode->GetItemByDataNode(*refNodeIt);
if ( nodeItemID && nodeItemID != itemID
&& (std::find(referencingItems.begin(), referencingItems.end(), nodeItemID) == referencingItems.end()) )
{
referencingItems.push_back(nodeItemID);
}
}
}
// Highlight recursively referenced items
for (int index=0; index!=recursivelyReferencedNodes->GetNumberOfItems(); ++index)
{
vtkIdType referencedItem = d->SubjectHierarchyNode->GetItemByDataNode(
vtkMRMLNode::SafeDownCast(recursivelyReferencedNodes->GetItemAsObject(index)) );
if (referencedItem && referencedItem != itemID)
{
QStandardItem* item = sceneModel->itemFromSubjectHierarchyItem(referencedItem, nameColumn);
if (item && !d->HighlightedItems.contains(referencedItem))
{
item->setBackground(QColor::fromRgb(255, 255, 170));
d->HighlightedItems.append(referencedItem);
}
}
}
// Highlight directly referenced items
std::vector<vtkIdType>::iterator itemIt;
for (itemIt=directlyReferencedItems.begin(); itemIt!=directlyReferencedItems.end(); ++itemIt)
{
vtkIdType referencedItem = (*itemIt);
QStandardItem* item = sceneModel->itemFromSubjectHierarchyItem(referencedItem, nameColumn);
if (item) // Note: these items have been added as the recursively referenced items already
{
item->setBackground(Qt::yellow);
}
}
// Highlight referencing items
for (itemIt=referencingItems.begin(); itemIt!=referencingItems.end(); ++itemIt)
{
vtkIdType referencingItem = (*itemIt);
QStandardItem* item = sceneModel->itemFromSubjectHierarchyItem(referencingItem, nameColumn);
if (item && !d->HighlightedItems.contains(referencingItem))
{
item->setBackground(QColor::fromRgb(69, 204, 69));
d->HighlightedItems.append(referencingItem);
}
}
}
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setMultiSelection(bool multiSelectionOn)
{
if (multiSelectionOn)
{
this->setSelectionMode(QAbstractItemView::ExtendedSelection);
}
else
{
this->setSelectionMode(QAbstractItemView::SingleSelection);
}
}
//-----------------------------------------------------------------------------
bool qMRMLSubjectHierarchyTreeView::multiSelection()
{
return (this->selectionMode() == QAbstractItemView::ExtendedSelection);
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setPluginWhitelist(QStringList whitelist)
{
Q_D(qMRMLSubjectHierarchyTreeView);
d->PluginWhitelist = whitelist;
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setPluginBlacklist(QStringList blacklist)
{
Q_D(qMRMLSubjectHierarchyTreeView);
d->PluginBlacklist = blacklist;
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::disablePlugin(QString plugin)
{
Q_D(qMRMLSubjectHierarchyTreeView);
d->PluginBlacklist << plugin;
}
//-----------------------------------------------------------------------------
vtkIdType qMRMLSubjectHierarchyTreeView::firstSelectedSubjectHierarchyItemInBranch(vtkIdType itemID)
{
Q_D(qMRMLSubjectHierarchyTreeView);
// Check if item itself is selected
if (d->SelectedItems.contains(itemID))
{
return itemID;
}
// Look for selected item in children recursively
std::vector<vtkIdType> childItemIDs;
d->SubjectHierarchyNode->GetItemChildren(itemID, childItemIDs, true);
for (std::vector<vtkIdType>::iterator childIt=childItemIDs.begin(); childIt!=childItemIDs.end(); ++childIt)
{
vtkIdType selectedId = this->firstSelectedSubjectHierarchyItemInBranch(*childIt);
if (selectedId != vtkMRMLSubjectHierarchyNode::INVALID_ITEM_ID)
{
return selectedId;
}
}
// That item is not selected and does not have
// any children items selected
return vtkMRMLSubjectHierarchyNode::INVALID_ITEM_ID;
}
//-----------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::onSubjectHierarchyItemModified(vtkObject *caller, void *callData)
{
Q_D(qMRMLSubjectHierarchyTreeView);
vtkMRMLSubjectHierarchyNode* shNode = vtkMRMLSubjectHierarchyNode::SafeDownCast(caller);
if (!shNode)
{
qCritical() << Q_FUNC_INFO << ": Failed to access subject hierarchy node";
return;
}
// Get item ID
vtkIdType itemID = vtkMRMLSubjectHierarchyNode::INVALID_ITEM_ID;
if (callData)
{
vtkIdType* itemIdPtr = reinterpret_cast<vtkIdType*>(callData);
itemID = *itemIdPtr;
}
// Highlight items referenced by DICOM in case of single-selection
// Referenced SOP instance UIDs (in attribute named vtkMRMLSubjectHierarchyConstants::GetDICOMReferencedInstanceUIDsAttributeName())
// -> SH item instance UIDs (serialized string lists in subject hierarchy UID vtkMRMLSubjectHierarchyConstants::GetDICOMInstanceUIDName())
if (this->highlightReferencedItems() && d->SelectedItems.count() == 1)
{
this->applyReferenceHighlightForItems(d->SelectedItems);
}
// Forward `currentItemModified` if the modified item or one of
// its children was selected, to adequately update other widgets
// that use that modified item such as qMRMLSubjectHierarchyComboBox
vtkIdType selectedId = this->firstSelectedSubjectHierarchyItemInBranch(itemID);
if (selectedId != vtkMRMLSubjectHierarchyNode::INVALID_ITEM_ID)
{
emit currentItemModified(selectedId);
}
}
//-----------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::onMRMLSceneCloseEnded(vtkObject* sceneObject)
{
vtkMRMLScene* scene = vtkMRMLScene::SafeDownCast(sceneObject);
if (!scene)
{
return;
}
Q_D(qMRMLSubjectHierarchyTreeView);
// Remove selection
QList<vtkIdType> emptySelection;
this->setCurrentItems(emptySelection);
d->SelectedItems.clear();
d->HighlightedItems.clear();
// Get new subject hierarchy node (or if not created yet then trigger creating it, because
// scene close removed the pseudo-singleton subject hierarchy node), and set it to the tree view
this->setSubjectHierarchyNode(vtkMRMLSubjectHierarchyNode::ResolveSubjectHierarchy(scene));
}
//-----------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::onMRMLSceneStartBatchProcess(vtkObject* sceneObject)
{
vtkMRMLScene* scene = vtkMRMLScene::SafeDownCast(sceneObject);
if (!scene)
{
return;
}
Q_D(qMRMLSubjectHierarchyTreeView);
d->SelectedItemsToRestore = d->SelectedItems;
}
//-----------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::onMRMLSceneEndBatchProcess(vtkObject* sceneObject)
{
vtkMRMLScene* scene = vtkMRMLScene::SafeDownCast(sceneObject);
if (!scene)
{
return;
}
Q_D(qMRMLSubjectHierarchyTreeView);
this->setCurrentItems(d->SelectedItemsToRestore);
d->SelectedItemsToRestore.clear();
}
//------------------------------------------------------------------------------
bool qMRMLSubjectHierarchyTreeView::showContextMenuHint(bool visibility/*=false*/)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode)
{
qCritical() << Q_FUNC_INFO << ": Invalid subject hierarchy";
return false;
}
// Get current item
vtkIdType itemID = this->currentItem();
if (!itemID || !d->SubjectHierarchyNode->GetDisplayNodeForItem(itemID))
{
// If current item is not displayable, then find first displayable leaf item
itemID = vtkMRMLSubjectHierarchyNode::INVALID_ITEM_ID;
std::vector<vtkIdType> childItems;
d->SubjectHierarchyNode->GetItemChildren(d->SubjectHierarchyNode->GetSceneItemID(), childItems, true);
for (std::vector<vtkIdType>::iterator childIt=childItems.begin(); childIt!=childItems.end(); ++childIt)
{
std::vector<vtkIdType> currentChildItems;
d->SubjectHierarchyNode->GetItemChildren(*childIt, currentChildItems);
if ( (currentChildItems.empty() || d->SubjectHierarchyNode->IsItemVirtualBranchParent(*childIt)) // Leaf
&& ( d->SubjectHierarchyNode->GetDisplayNodeForItem(*childIt) // Displayable
|| vtkMRMLScalarVolumeNode::SafeDownCast(d->SubjectHierarchyNode->GetItemDataNode(*childIt)) ) ) // Volume
{
itemID = (*childIt);
break;
}
}
}
if (!itemID)
{
// No displayable item in subject hierarchy
return false;
}
// Create information icon
QIcon icon = QApplication::style()->standardIcon(QStyle::SP_MessageBoxInformation);
QPixmap pixmap = icon.pixmap(32,32);
QByteArray data;
QBuffer buffer(&data);
pixmap.save(&buffer, "PNG", 100);
QString iconHtml = QString("<img src='data:image/png;base64, %0'>").arg(QString(data.toBase64()));
if (!visibility)
{
// Get name cell position
QModelIndex nameIndex = this->sortFilterProxyModel()->indexFromSubjectHierarchyItem(
itemID, this->model()->nameColumn() );
QRect nameRect = this->visualRect(nameIndex);
// Show name tooltip
QString nameTooltip = QString(
"<div align=\"left\" style=\"font-size:10pt;\"><!--↑<br/>-->Right-click an item<br/>to access additional<br/>options</div><br/>")
+ iconHtml;
QToolTip::showText(
this->mapToGlobal( QPoint( nameRect.x() + nameRect.width()/6, nameRect.y() + nameRect.height() ) ),
nameTooltip );
}
else
{
// Get visibility cell position
QModelIndex visibilityIndex = this->sortFilterProxyModel()->indexFromSubjectHierarchyItem(
itemID, this->model()->visibilityColumn() );
QRect visibilityRect = this->visualRect(visibilityIndex);
// Show visibility tooltip
QString visibilityTooltip = QString(
"<div align=\"left\" style=\"font-size:10pt;\"><!--↑<br/>-->Right-click the visibility<br/>"
"button of an item to<br/>access additional<br/>visibility options</div><br/>")
+ iconHtml;
QToolTip::showText( this->mapToGlobal( QPoint( visibilityRect.x() + visibilityRect.width()/2, visibilityRect.y() + visibilityRect.height() ) ),
visibilityTooltip );
}
return true;
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::onCustomContextMenu(const QPoint& point)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->ContextMenuEnabled)
{
// Context menu not enabled, ignore the event
return;
}
QPoint globalPoint = this->viewport()->mapToGlobal(point);
// Custom right button actions for item decorations (i.e. icon): visibility context menu
QModelIndex index = this->indexAt(point);
QStyleOptionViewItem opt = this->viewOptions();
opt.rect = this->visualRect(index);
qobject_cast<qMRMLItemDelegate*>(this->itemDelegate())->initStyleOption(&opt, index);
QRect decorationElement = this->style()->subElementRect(QStyle::SE_ItemViewItemDecoration, &opt, this);
if (decorationElement.contains(point))
{
// Mouse event is within an item decoration
QModelIndex sourceIndex = this->sortFilterProxyModel()->mapToSource(index);
if (sourceIndex.flags() & Qt::ItemIsEnabled)
{
// Item is enabled
if (sourceIndex.column() == this->model()->visibilityColumn()
|| sourceIndex.column() == this->model()->colorColumn())
{
vtkIdType itemID = d->SortFilterModel->subjectHierarchyItemFromIndex(index);
if (itemID) // Valid item is needed for visibility actions
{
// If multiple items are selected then show the node menu instead of the visibility menu
if (d->SelectedItems.size() > 1)
{
this->populateContextMenuForItem(itemID);
d->NodeMenu->exec(globalPoint);
}
else
{
// Populate then show visibility context menu if only one item is selected
this->populateVisibilityContextMenuForItem(itemID);
d->VisibilityMenu->exec(globalPoint);
}
return;
}
}
}
}
// Get subject hierarchy item at mouse click position
vtkIdType itemID = this->sortFilterProxyModel()->subjectHierarchyItemFromIndex(index);
// Populate context menu for the current item
this->populateContextMenuForItem(itemID);
// Show context menu
if (!itemID || itemID == d->SubjectHierarchyNode->GetSceneItemID())
{
d->SceneMenu->exec(globalPoint);
}
else
{
d->NodeMenu->exec(globalPoint);
}
}
| 35.88 | 147 | 0.656306 |
9a2384ae83b1d714ddd87a6d08e4748e933a5918 | 20,891 | cc | C++ | FreeBSD/cddl/usr.sbin/zfsd/tests/zfsd_unittest.cc | TigerBSD/FreeBSD-Custom-ThinkPad | 3d092f261b362f73170871403397fc5d6b89d1dc | [
"0BSD"
] | 4 | 2016-08-22T22:02:55.000Z | 2017-03-04T22:56:44.000Z | FreeBSD/cddl/usr.sbin/zfsd/tests/zfsd_unittest.cc | TigerBSD/FreeBSD-Custom-ThinkPad | 3d092f261b362f73170871403397fc5d6b89d1dc | [
"0BSD"
] | 21 | 2016-08-11T09:43:43.000Z | 2017-01-29T12:52:56.000Z | FreeBSD/cddl/usr.sbin/zfsd/tests/zfsd_unittest.cc | TigerBSD/TigerBSD | 3d092f261b362f73170871403397fc5d6b89d1dc | [
"0BSD"
] | null | null | null | /*-
* Copyright (c) 2012, 2013, 2014 Spectra Logic Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
*
* NO WARRANTY
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* Authors: Alan Somers (Spectra Logic Corporation)
*/
#include <sys/cdefs.h>
#include <stdarg.h>
#include <syslog.h>
#include <libnvpair.h>
#include <libzfs.h>
#include <list>
#include <map>
#include <sstream>
#include <string>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <devdctl/guid.h>
#include <devdctl/event.h>
#include <devdctl/event_factory.h>
#include <devdctl/exception.h>
#include <devdctl/consumer.h>
#include <zfsd/callout.h>
#include <zfsd/vdev_iterator.h>
#include <zfsd/zfsd_event.h>
#include <zfsd/case_file.h>
#include <zfsd/vdev.h>
#include <zfsd/zfsd.h>
#include <zfsd/zfsd_exception.h>
#include <zfsd/zpool_list.h>
#include "libmocks.h"
__FBSDID("$FreeBSD$");
/*================================== Macros ==================================*/
#define NUM_ELEMENTS(x) (sizeof(x) / sizeof(*x))
/*============================ Namespace Control =============================*/
using std::string;
using std::stringstream;
using DevdCtl::Event;
using DevdCtl::EventBuffer;
using DevdCtl::EventFactory;
using DevdCtl::EventList;
using DevdCtl::Guid;
using DevdCtl::NVPairMap;
/* redefine zpool_handle here because libzfs_impl.h is not includable */
struct zpool_handle
{
libzfs_handle_t *zpool_hdl;
zpool_handle_t *zpool_next;
char zpool_name[ZPOOL_MAXNAMELEN];
int zpool_state;
size_t zpool_config_size;
nvlist_t *zpool_config;
nvlist_t *zpool_old_config;
nvlist_t *zpool_props;
diskaddr_t zpool_start_block;
};
class MockZfsEvent : public ZfsEvent
{
public:
MockZfsEvent(Event::Type, NVPairMap&, const string&);
virtual ~MockZfsEvent() {}
static BuildMethod MockZfsEventBuilder;
MOCK_CONST_METHOD0(ProcessPoolEvent, void());
static EventFactory::Record s_buildRecords[];
};
EventFactory::Record MockZfsEvent::s_buildRecords[] =
{
{ Event::NOTIFY, "ZFS", &MockZfsEvent::MockZfsEventBuilder }
};
MockZfsEvent::MockZfsEvent(Event::Type type, NVPairMap& map,
const string& str)
: ZfsEvent(type, map, str)
{
}
Event *
MockZfsEvent::MockZfsEventBuilder(Event::Type type,
NVPairMap &nvpairs,
const string &eventString)
{
return (new MockZfsEvent(type, nvpairs, eventString));
}
/*
* A dummy Vdev class used for testing other classes
*/
class MockVdev : public Vdev
{
public:
MockVdev(nvlist_t *vdevConfig);
virtual ~MockVdev() {}
MOCK_CONST_METHOD0(GUID, Guid());
MOCK_CONST_METHOD0(PoolGUID, Guid());
MOCK_CONST_METHOD0(State, vdev_state());
MOCK_CONST_METHOD0(PhysicalPath, string());
};
MockVdev::MockVdev(nvlist_t *vdevConfig)
: Vdev(vdevConfig)
{
}
/*
* A CaseFile class with side effects removed, for testing
*/
class TestableCaseFile : public CaseFile
{
public:
static TestableCaseFile &Create(Vdev &vdev);
TestableCaseFile(Vdev &vdev);
virtual ~TestableCaseFile() {}
MOCK_METHOD0(Close, void());
MOCK_METHOD1(RegisterCallout, void(const Event &event));
MOCK_METHOD0(RefreshVdevState, bool());
MOCK_METHOD1(ReEvaluate, bool(const ZfsEvent &event));
bool RealReEvaluate(const ZfsEvent &event)
{
return (CaseFile::ReEvaluate(event));
}
/*
* This splices the event lists, a procedure that would normally be done
* by OnGracePeriodEnded, but we don't necessarily call that in the
* unit tests
*/
void SpliceEvents();
/*
* Used by some of our expectations. CaseFile does not publicize this
*/
static int getActiveCases()
{
return (s_activeCases.size());
}
};
TestableCaseFile::TestableCaseFile(Vdev &vdev)
: CaseFile(vdev)
{
}
TestableCaseFile &
TestableCaseFile::Create(Vdev &vdev)
{
TestableCaseFile *newCase;
newCase = new TestableCaseFile(vdev);
return (*newCase);
}
void
TestableCaseFile::SpliceEvents()
{
m_events.splice(m_events.begin(), m_tentativeEvents);
}
/*
* Test class ZfsdException
*/
class ZfsdExceptionTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
ASSERT_EQ(0, nvlist_alloc(&poolConfig, NV_UNIQUE_NAME, 0));
ASSERT_EQ(0, nvlist_add_string(poolConfig,
ZPOOL_CONFIG_POOL_NAME, "unit_test_pool"));
ASSERT_EQ(0, nvlist_add_uint64(poolConfig,
ZPOOL_CONFIG_POOL_GUID, 0x1234));
ASSERT_EQ(0, nvlist_alloc(&vdevConfig, NV_UNIQUE_NAME, 0));
ASSERT_EQ(0, nvlist_add_uint64(vdevConfig,
ZPOOL_CONFIG_GUID, 0x5678));
bzero(&poolHandle, sizeof(poolHandle));
poolHandle.zpool_config = poolConfig;
}
virtual void TearDown()
{
nvlist_free(poolConfig);
nvlist_free(vdevConfig);
}
nvlist_t *poolConfig;
nvlist_t *vdevConfig;
zpool_handle_t poolHandle;
};
TEST_F(ZfsdExceptionTest, StringConstructorNull)
{
ZfsdException ze("");
EXPECT_STREQ("", ze.GetString().c_str());
}
TEST_F(ZfsdExceptionTest, StringConstructorFormatted)
{
ZfsdException ze(" %d %s", 55, "hello world");
EXPECT_STREQ(" 55 hello world", ze.GetString().c_str());
}
TEST_F(ZfsdExceptionTest, LogSimple)
{
ZfsdException ze("unit test w/o vdev or pool");
ze.Log();
EXPECT_EQ(LOG_ERR, syslog_last_priority);
EXPECT_STREQ("unit test w/o vdev or pool\n", syslog_last_message);
}
TEST_F(ZfsdExceptionTest, Pool)
{
const char msg[] = "Exception with pool name";
char expected[4096];
sprintf(expected, "Pool unit_test_pool: %s\n", msg);
ZfsdException ze(poolConfig, msg);
ze.Log();
EXPECT_STREQ(expected, syslog_last_message);
}
TEST_F(ZfsdExceptionTest, PoolHandle)
{
const char msg[] = "Exception with pool handle";
char expected[4096];
sprintf(expected, "Pool unit_test_pool: %s\n", msg);
ZfsdException ze(&poolHandle, msg);
ze.Log();
EXPECT_STREQ(expected, syslog_last_message);
}
/*
* Test class Vdev
*/
class VdevTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
ASSERT_EQ(0, nvlist_alloc(&m_poolConfig, NV_UNIQUE_NAME, 0));
ASSERT_EQ(0, nvlist_add_uint64(m_poolConfig,
ZPOOL_CONFIG_POOL_GUID,
0x1234));
ASSERT_EQ(0, nvlist_alloc(&m_vdevConfig, NV_UNIQUE_NAME, 0));
ASSERT_EQ(0, nvlist_add_uint64(m_vdevConfig, ZPOOL_CONFIG_GUID,
0x5678));
}
virtual void TearDown()
{
nvlist_free(m_poolConfig);
nvlist_free(m_vdevConfig);
}
nvlist_t *m_poolConfig;
nvlist_t *m_vdevConfig;
};
TEST_F(VdevTest, StateFromConfig)
{
vdev_stat_t vs;
vs.vs_state = VDEV_STATE_OFFLINE;
ASSERT_EQ(0, nvlist_add_uint64_array(m_vdevConfig,
ZPOOL_CONFIG_VDEV_STATS,
(uint64_t*)&vs,
sizeof(vs) / sizeof(uint64_t)));
Vdev vdev(m_poolConfig, m_vdevConfig);
EXPECT_EQ(VDEV_STATE_OFFLINE, vdev.State());
}
TEST_F(VdevTest, StateFaulted)
{
ASSERT_EQ(0, nvlist_add_uint64(m_vdevConfig, ZPOOL_CONFIG_FAULTED, 1));
Vdev vdev(m_poolConfig, m_vdevConfig);
EXPECT_EQ(VDEV_STATE_FAULTED, vdev.State());
}
/*
* Test that we can construct a Vdev from the label information that is stored
* on an available spare drive
*/
TEST_F(VdevTest, ConstructAvailSpare)
{
nvlist_t *labelConfig;
ASSERT_EQ(0, nvlist_alloc(&labelConfig, NV_UNIQUE_NAME, 0));
ASSERT_EQ(0, nvlist_add_uint64(labelConfig, ZPOOL_CONFIG_GUID,
1948339428197961030));
ASSERT_EQ(0, nvlist_add_uint64(labelConfig, ZPOOL_CONFIG_POOL_STATE,
POOL_STATE_SPARE));
EXPECT_NO_THROW(Vdev vdev(labelConfig));
nvlist_free(labelConfig);
}
/* Available spares will always show the HEALTHY state */
TEST_F(VdevTest, AvailSpareState) {
nvlist_t *labelConfig;
ASSERT_EQ(0, nvlist_alloc(&labelConfig, NV_UNIQUE_NAME, 0));
ASSERT_EQ(0, nvlist_add_uint64(labelConfig, ZPOOL_CONFIG_GUID,
1948339428197961030));
ASSERT_EQ(0, nvlist_add_uint64(labelConfig, ZPOOL_CONFIG_POOL_STATE,
POOL_STATE_SPARE));
Vdev vdev(labelConfig);
EXPECT_EQ(VDEV_STATE_HEALTHY, vdev.State());
nvlist_free(labelConfig);
}
/* Test the Vdev::IsSpare method */
TEST_F(VdevTest, IsSpare) {
Vdev notSpare(m_poolConfig, m_vdevConfig);
EXPECT_EQ(false, notSpare.IsSpare());
ASSERT_EQ(0, nvlist_add_uint64(m_vdevConfig, ZPOOL_CONFIG_IS_SPARE, 1));
Vdev isSpare(m_poolConfig, m_vdevConfig);
EXPECT_EQ(true, isSpare.IsSpare());
}
/*
* Test class ZFSEvent
*/
class ZfsEventTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
m_eventFactory = new EventFactory();
m_eventFactory->UpdateRegistry(MockZfsEvent::s_buildRecords,
NUM_ELEMENTS(MockZfsEvent::s_buildRecords));
m_event = NULL;
}
virtual void TearDown()
{
delete m_eventFactory;
delete m_event;
}
EventFactory *m_eventFactory;
Event *m_event;
};
TEST_F(ZfsEventTest, ProcessPoolEventGetsCalled)
{
string evString("!system=ZFS "
"subsystem=ZFS "
"type=misc.fs.zfs.vdev_remove "
"pool_name=foo "
"pool_guid=9756779504028057996 "
"vdev_guid=1631193447431603339 "
"vdev_path=/dev/da1 "
"timestamp=1348871594");
m_event = Event::CreateEvent(*m_eventFactory, evString);
MockZfsEvent *mock_event = static_cast<MockZfsEvent*>(m_event);
EXPECT_CALL(*mock_event, ProcessPoolEvent()).Times(1);
mock_event->Process();
}
/*
* Test class CaseFile
*/
class CaseFileTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
m_eventFactory = new EventFactory();
m_eventFactory->UpdateRegistry(MockZfsEvent::s_buildRecords,
NUM_ELEMENTS(MockZfsEvent::s_buildRecords));
m_event = NULL;
nvlist_alloc(&m_vdevConfig, NV_UNIQUE_NAME, 0);
ASSERT_EQ(0, nvlist_add_uint64(m_vdevConfig,
ZPOOL_CONFIG_GUID, 0xbeef));
m_vdev = new MockVdev(m_vdevConfig);
ON_CALL(*m_vdev, GUID())
.WillByDefault(::testing::Return(Guid(123)));
ON_CALL(*m_vdev, PoolGUID())
.WillByDefault(::testing::Return(Guid(456)));
ON_CALL(*m_vdev, State())
.WillByDefault(::testing::Return(VDEV_STATE_HEALTHY));
m_caseFile = &TestableCaseFile::Create(*m_vdev);
ON_CALL(*m_caseFile, ReEvaluate(::testing::_))
.WillByDefault(::testing::Invoke(m_caseFile, &TestableCaseFile::RealReEvaluate));
return;
}
virtual void TearDown()
{
delete m_caseFile;
nvlist_free(m_vdevConfig);
delete m_vdev;
delete m_event;
delete m_eventFactory;
}
nvlist_t *m_vdevConfig;
MockVdev *m_vdev;
TestableCaseFile *m_caseFile;
Event *m_event;
EventFactory *m_eventFactory;
};
/*
* A Vdev with no events should not be degraded or faulted
*/
TEST_F(CaseFileTest, HealthyVdev)
{
EXPECT_FALSE(m_caseFile->ShouldDegrade());
EXPECT_FALSE(m_caseFile->ShouldFault());
}
/*
* A Vdev with only one event should not be degraded or faulted
* For performance reasons, RefreshVdevState should not be called.
*/
TEST_F(CaseFileTest, HealthyishVdev)
{
string evString("!system=ZFS "
"class=ereport.fs.zfs.io "
"ena=12091638756982918145 "
"parent_guid=13237004955564865395 "
"parent_type=raidz "
"pool=testpool.4415 "
"pool_context=0 "
"pool_failmode=wait "
"pool_guid=456 "
"subsystem=ZFS "
"timestamp=1348867914 "
"type=ereport.fs.zfs.io "
"vdev_guid=123 "
"vdev_path=/dev/da400 "
"vdev_type=disk "
"zio_blkid=622 "
"zio_err=1 "
"zio_level=-2 "
"zio_object=0 "
"zio_objset=37 "
"zio_offset=25598976 "
"zio_size=1024");
m_event = Event::CreateEvent(*m_eventFactory, evString);
ZfsEvent *zfs_event = static_cast<ZfsEvent*>(m_event);
EXPECT_CALL(*m_caseFile, RefreshVdevState())
.Times(::testing::Exactly(0));
EXPECT_TRUE(m_caseFile->ReEvaluate(*zfs_event));
EXPECT_FALSE(m_caseFile->ShouldDegrade());
EXPECT_FALSE(m_caseFile->ShouldFault());
}
/* The case file should be closed when its pool is destroyed */
TEST_F(CaseFileTest, PoolDestroy)
{
string evString("!system=ZFS "
"pool_name=testpool.4415 "
"pool_guid=456 "
"subsystem=ZFS "
"timestamp=1348867914 "
"type=misc.fs.zfs.pool_destroy ");
m_event = Event::CreateEvent(*m_eventFactory, evString);
ZfsEvent *zfs_event = static_cast<ZfsEvent*>(m_event);
EXPECT_CALL(*m_caseFile, Close());
EXPECT_TRUE(m_caseFile->ReEvaluate(*zfs_event));
}
/*
* A Vdev with a very large number of IO errors should fault
* For performance reasons, RefreshVdevState should be called at most once
*/
TEST_F(CaseFileTest, VeryManyIOErrors)
{
EXPECT_CALL(*m_caseFile, RefreshVdevState())
.Times(::testing::AtMost(1))
.WillRepeatedly(::testing::Return(true));
for(int i=0; i<100; i++) {
stringstream evStringStream;
evStringStream <<
"!system=ZFS "
"class=ereport.fs.zfs.io "
"ena=12091638756982918145 "
"parent_guid=13237004955564865395 "
"parent_type=raidz "
"pool=testpool.4415 "
"pool_context=0 "
"pool_failmode=wait "
"pool_guid=456 "
"subsystem=ZFS "
"timestamp=";
evStringStream << i << " ";
evStringStream <<
"type=ereport.fs.zfs.io "
"vdev_guid=123 "
"vdev_path=/dev/da400 "
"vdev_type=disk "
"zio_blkid=622 "
"zio_err=1 "
"zio_level=-2 "
"zio_object=0 "
"zio_objset=37 "
"zio_offset=25598976 "
"zio_size=1024";
Event *event(Event::CreateEvent(*m_eventFactory,
evStringStream.str()));
ZfsEvent *zfs_event = static_cast<ZfsEvent*>(event);
EXPECT_TRUE(m_caseFile->ReEvaluate(*zfs_event));
delete event;
}
m_caseFile->SpliceEvents();
EXPECT_FALSE(m_caseFile->ShouldDegrade());
EXPECT_TRUE(m_caseFile->ShouldFault());
}
/*
* A Vdev with a very large number of checksum errors should degrade
* For performance reasons, RefreshVdevState should be called at most once
*/
TEST_F(CaseFileTest, VeryManyChecksumErrors)
{
EXPECT_CALL(*m_caseFile, RefreshVdevState())
.Times(::testing::AtMost(1))
.WillRepeatedly(::testing::Return(true));
for(int i=0; i<100; i++) {
stringstream evStringStream;
evStringStream <<
"!system=ZFS "
"bad_cleared_bits=03000000000000803f50b00000000000 "
"bad_range_clears=0000000e "
"bad_range_sets=00000000 "
"bad_ranges=0000000000000010 "
"bad_ranges_min_gap=8 "
"bad_set_bits=00000000000000000000000000000000 "
"class=ereport.fs.zfs.checksum "
"ena=12272856582652437505 "
"parent_guid=5838204195352909894 "
"parent_type=raidz pool=testpool.7640 "
"pool_context=0 "
"pool_failmode=wait "
"pool_guid=456 "
"subsystem=ZFS timestamp=";
evStringStream << i << " ";
evStringStream <<
"type=ereport.fs.zfs.checksum "
"vdev_guid=123 "
"vdev_path=/mnt/tmp/file1.7702 "
"vdev_type=file "
"zio_blkid=0 "
"zio_err=0 "
"zio_level=0 "
"zio_object=3 "
"zio_objset=0 "
"zio_offset=16896 "
"zio_size=512";
Event *event(Event::CreateEvent(*m_eventFactory,
evStringStream.str()));
ZfsEvent *zfs_event = static_cast<ZfsEvent*>(event);
EXPECT_TRUE(m_caseFile->ReEvaluate(*zfs_event));
delete event;
}
m_caseFile->SpliceEvents();
EXPECT_TRUE(m_caseFile->ShouldDegrade());
EXPECT_FALSE(m_caseFile->ShouldFault());
}
/*
* Test CaseFile::ReEvaluateByGuid
*/
class ReEvaluateByGuidTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
m_eventFactory = new EventFactory();
m_eventFactory->UpdateRegistry(MockZfsEvent::s_buildRecords,
NUM_ELEMENTS(MockZfsEvent::s_buildRecords));
m_event = Event::CreateEvent(*m_eventFactory, s_evString);
nvlist_alloc(&m_vdevConfig, NV_UNIQUE_NAME, 0);
ASSERT_EQ(0, nvlist_add_uint64(m_vdevConfig,
ZPOOL_CONFIG_GUID, 0xbeef));
m_vdev456 = new ::testing::NiceMock<MockVdev>(m_vdevConfig);
m_vdev789 = new ::testing::NiceMock<MockVdev>(m_vdevConfig);
ON_CALL(*m_vdev456, GUID())
.WillByDefault(::testing::Return(Guid(123)));
ON_CALL(*m_vdev456, PoolGUID())
.WillByDefault(::testing::Return(Guid(456)));
ON_CALL(*m_vdev456, State())
.WillByDefault(::testing::Return(VDEV_STATE_HEALTHY));
ON_CALL(*m_vdev789, GUID())
.WillByDefault(::testing::Return(Guid(123)));
ON_CALL(*m_vdev789, PoolGUID())
.WillByDefault(::testing::Return(Guid(789)));
ON_CALL(*m_vdev789, State())
.WillByDefault(::testing::Return(VDEV_STATE_HEALTHY));
m_caseFile456 = NULL;
m_caseFile789 = NULL;
return;
}
virtual void TearDown()
{
delete m_caseFile456;
delete m_caseFile789;
nvlist_free(m_vdevConfig);
delete m_vdev456;
delete m_vdev789;
delete m_event;
delete m_eventFactory;
}
static string s_evString;
nvlist_t *m_vdevConfig;
::testing::NiceMock<MockVdev> *m_vdev456;
::testing::NiceMock<MockVdev> *m_vdev789;
TestableCaseFile *m_caseFile456;
TestableCaseFile *m_caseFile789;
Event *m_event;
EventFactory *m_eventFactory;
};
string ReEvaluateByGuidTest::s_evString(
"!system=ZFS "
"pool_guid=16271873792808333580 "
"pool_name=foo "
"subsystem=ZFS "
"timestamp=1360620391 "
"type=misc.fs.zfs.config_sync");
/*
* Test the ReEvaluateByGuid method on an empty list of casefiles.
* We must create one event, even though it never gets used, because it will
* be passed by reference to ReEvaluateByGuid
*/
TEST_F(ReEvaluateByGuidTest, ReEvaluateByGuid_empty)
{
ZfsEvent *zfs_event = static_cast<ZfsEvent*>(m_event);
EXPECT_EQ(0, TestableCaseFile::getActiveCases());
CaseFile::ReEvaluateByGuid(Guid(456), *zfs_event);
EXPECT_EQ(0, TestableCaseFile::getActiveCases());
}
/*
* Test the ReEvaluateByGuid method on a list of CaseFiles that contains only
* one CaseFile, which doesn't match the criteria
*/
TEST_F(ReEvaluateByGuidTest, ReEvaluateByGuid_oneFalse)
{
m_caseFile456 = &TestableCaseFile::Create(*m_vdev456);
ZfsEvent *zfs_event = static_cast<ZfsEvent*>(m_event);
EXPECT_EQ(1, TestableCaseFile::getActiveCases());
EXPECT_CALL(*m_caseFile456, ReEvaluate(::testing::_))
.Times(::testing::Exactly(0));
CaseFile::ReEvaluateByGuid(Guid(789), *zfs_event);
EXPECT_EQ(1, TestableCaseFile::getActiveCases());
}
/*
* Test the ReEvaluateByGuid method on a list of CaseFiles that contains only
* one CaseFile, which does match the criteria
*/
TEST_F(ReEvaluateByGuidTest, ReEvaluateByGuid_oneTrue)
{
m_caseFile456 = &TestableCaseFile::Create(*m_vdev456);
ZfsEvent *zfs_event = static_cast<ZfsEvent*>(m_event);
EXPECT_EQ(1, TestableCaseFile::getActiveCases());
EXPECT_CALL(*m_caseFile456, ReEvaluate(::testing::_))
.Times(::testing::Exactly(1))
.WillRepeatedly(::testing::Return(false));
CaseFile::ReEvaluateByGuid(Guid(456), *zfs_event);
EXPECT_EQ(1, TestableCaseFile::getActiveCases());
}
/*
* Test the ReEvaluateByGuid method on a long list of CaseFiles that contains a
* few cases which meet the criteria
*/
TEST_F(ReEvaluateByGuidTest, ReEvaluateByGuid_five)
{
TestableCaseFile *CaseFile1 = &TestableCaseFile::Create(*m_vdev456);
TestableCaseFile *CaseFile2 = &TestableCaseFile::Create(*m_vdev789);
TestableCaseFile *CaseFile3 = &TestableCaseFile::Create(*m_vdev456);
TestableCaseFile *CaseFile4 = &TestableCaseFile::Create(*m_vdev789);
TestableCaseFile *CaseFile5 = &TestableCaseFile::Create(*m_vdev789);
ZfsEvent *zfs_event = static_cast<ZfsEvent*>(m_event);
EXPECT_EQ(5, TestableCaseFile::getActiveCases());
EXPECT_CALL(*CaseFile1, ReEvaluate(::testing::_))
.Times(::testing::Exactly(1))
.WillRepeatedly(::testing::Return(false));
EXPECT_CALL(*CaseFile3, ReEvaluate(::testing::_))
.Times(::testing::Exactly(1))
.WillRepeatedly(::testing::Return(false));
EXPECT_CALL(*CaseFile2, ReEvaluate(::testing::_))
.Times(::testing::Exactly(0));
EXPECT_CALL(*CaseFile4, ReEvaluate(::testing::_))
.Times(::testing::Exactly(0));
EXPECT_CALL(*CaseFile5, ReEvaluate(::testing::_))
.Times(::testing::Exactly(0));
CaseFile::ReEvaluateByGuid(Guid(456), *zfs_event);
EXPECT_EQ(5, TestableCaseFile::getActiveCases());
delete CaseFile1;
delete CaseFile2;
delete CaseFile3;
delete CaseFile4;
delete CaseFile5;
}
| 27.060881 | 87 | 0.724475 |
9a2386687d9ee5240b21cf272e063af465e06284 | 1,097 | cpp | C++ | ConsoleGameEngine/KeyEvents.cpp | sirjavlux/ConsoleGameEngine | 04ece4053d7ad4566aef356fdb6e76233e8dd714 | [
"MIT"
] | 3 | 2021-01-03T12:44:08.000Z | 2021-01-08T14:02:50.000Z | ConsoleGameEngine/KeyEvents.cpp | sirjavlux/ConsoleGameEngine | 04ece4053d7ad4566aef356fdb6e76233e8dd714 | [
"MIT"
] | null | null | null | ConsoleGameEngine/KeyEvents.cpp | sirjavlux/ConsoleGameEngine | 04ece4053d7ad4566aef356fdb6e76233e8dd714 | [
"MIT"
] | null | null | null | #include <iostream>
#include "SEngine.h"
using namespace std;
void keyAUpdateEvent(KeyState state, SEngine* engine) {
if (state == KeyState::down) {
if (engine->hasCameraObjectAttatched()) {
GameObject* obj = engine->getCameraFollowObject();
Vector2D vel(-1, 0);
obj->addForce(vel);
}
}
}
void keyWUpdateEvent(KeyState state, SEngine* engine) {
if (state == KeyState::down) {
if (engine->hasCameraObjectAttatched()) {
GameObject* obj = engine->getCameraFollowObject();
Vector2D vel(0, 1);
obj->addForce(vel);
}
}
}
void keySUpdateEvent(KeyState state, SEngine* engine) {
if (state == KeyState::down) {
if (engine->hasCameraObjectAttatched()) {
GameObject* obj = engine->getCameraFollowObject();
Vector2D vel(0, -1);
obj->addForce(vel);
}
}
}
void keyDUpdateEvent(KeyState state, SEngine* engine) {
if (state == KeyState::down) {
if (engine->hasCameraObjectAttatched()) {
GameObject* obj = engine->getCameraFollowObject();
Vector2D vel(1, 0);
obj->addForce(vel);
}
}
}
void keySPACEUpdateEvent(KeyState state, SEngine* engine) {
} | 22.387755 | 59 | 0.68186 |
9a25fd85c68799a05aab142cdb513e6773fda2da | 10,852 | hpp | C++ | src/compiler/lib/Solution.hpp | gperrotta/yask | a35aa5a6f52bb5a11c182045c469a55a84fa9b36 | [
"MIT"
] | null | null | null | src/compiler/lib/Solution.hpp | gperrotta/yask | a35aa5a6f52bb5a11c182045c469a55a84fa9b36 | [
"MIT"
] | null | null | null | src/compiler/lib/Solution.hpp | gperrotta/yask | a35aa5a6f52bb5a11c182045c469a55a84fa9b36 | [
"MIT"
] | null | null | null | /*****************************************************************************
YASK: Yet Another Stencil Kit
Copyright (c) 2014-2019, Intel Corporation
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*****************************************************************************/
// Base class for defining stencil equations.
#pragma once
// Generation code.
#include "ExprUtils.hpp"
#include "Settings.hpp"
#include "Eqs.hpp"
using namespace std;
namespace yask {
class PrinterBase;
// A base class for whole stencil solutions. This is used by solutions
// defined in C++ that are inherited from StencilBase as well as those
// defined via the stencil-compiler API.
class StencilSolution :
public virtual yc_solution {
protected:
// Simple name for the stencil soln. Must be a legal C++ var name.
string _name;
// Longer descriptive string.
string _long_name;
// Debug output.
yask_output_ptr _debug_output;
ostream* _dos = &std::cout; // just a handy pointer to an ostream.
// All vars accessible by the kernel.
Vars _vars;
// All equations defined in this solution.
Eqs _eqs;
// Settings for the solution.
CompilerSettings _settings;
// Code extensions.
vector<string> _kernel_code;
vector<output_hook_t> _output_hooks;
private:
// Intermediate data needed to format output.
Dimensions _dims; // various dimensions.
PrinterBase* _printer = 0;
EqBundles* _eqBundles = 0; // eq-bundles for scalar and vector.
EqBundlePacks* _eqBundlePacks = 0; // packs of bundles w/o inter-dependencies.
EqBundles* _clusterEqBundles = 0; // eq-bundles for scalar and vector.
// Create the intermediate data.
void analyze_solution(int vlen,
bool is_folding_efficient);
// Free allocated objs.
void _free(bool free_printer);
public:
StencilSolution(const string& name) :
_name(name) {
yask_output_factory ofac;
auto so = ofac.new_stdout_output();
set_debug_output(so);
}
virtual ~StencilSolution() { _free(true); }
// Identification.
virtual const string& getName() const { return _name; }
virtual const string& getLongName() const {
return _long_name.length() ? _long_name : _name;
}
// Simple accessors.
virtual Vars& getVars() { return _vars; }
virtual Eqs& getEqs() { return _eqs; }
virtual CompilerSettings& getSettings() { return _settings; }
virtual void setSettings(const CompilerSettings& settings) {
_settings = settings;
}
virtual const Dimensions& getDims() { return _dims; }
virtual const vector<string>& getKernelCode() { return _kernel_code; }
// Get the messsage output stream.
virtual std::ostream& get_ostr() const {
assert(_dos);
return *_dos;
}
// Make a new var.
virtual yc_var_ptr newVar(const std::string& name,
bool isScratch,
const std::vector<yc_index_node_ptr>& dims);
// stencil_solution APIs.
// See yask_stencil_api.hpp for documentation.
virtual void set_debug_output(yask_output_ptr debug) override {
_debug_output = debug; // to share ownership of referent.
_dos = &_debug_output->get_ostream();
}
virtual yask_output_ptr get_debug_output() const {
return _debug_output;
}
virtual void set_name(std::string name) override {
_name = name;
}
virtual void set_description(std::string str) override {
_long_name = str;
}
virtual std::string get_name() const override {
return _name;
}
virtual std::string get_description() const override {
return getLongName();
}
virtual yc_var_ptr new_var(const std::string& name,
const std::vector<yc_index_node_ptr>& dims) override {
return newVar(name, false, dims);
}
virtual yc_var_ptr new_var(const std::string& name,
const std::initializer_list<yc_index_node_ptr>& dims) override {
std::vector<yc_index_node_ptr> dim_vec(dims);
return newVar(name, false, dim_vec);
}
virtual yc_var_ptr new_scratch_var(const std::string& name,
const std::vector<yc_index_node_ptr>& dims) override {
return newVar(name, true, dims);
}
virtual yc_var_ptr new_scratch_var(const std::string& name,
const std::initializer_list<yc_index_node_ptr>& dims) override {
std::vector<yc_index_node_ptr> dim_vec(dims);
return newVar(name, true, dim_vec);
}
virtual int get_num_vars() const override {
return int(_vars.size());
}
virtual yc_var_ptr get_var(const std::string& name) override {
for (int i = 0; i < get_num_vars(); i++)
if (_vars.at(i)->getName() == name)
return _vars.at(i);
return nullptr;
}
virtual std::vector<yc_var_ptr> get_vars() override {
std::vector<yc_var_ptr> gv;
for (int i = 0; i < get_num_vars(); i++)
gv.push_back(_vars.at(i));
return gv;
}
virtual int get_num_equations() const override {
return _eqs.getNum();
}
virtual std::vector<yc_equation_node_ptr> get_equations() override {
std::vector<yc_equation_node_ptr> ev;
for (int i = 0; i < get_num_equations(); i++)
ev.push_back(_eqs.getAll().at(i));
return ev;
}
virtual void
call_after_new_solution(const string& code) override {
_kernel_code.push_back(code);
}
virtual int
get_prefetch_dist(int level) override ;
virtual void
set_prefetch_dist(int level,
int distance) override;
virtual void add_flow_dependency(yc_equation_node_ptr from,
yc_equation_node_ptr to) override {
auto fp = dynamic_pointer_cast<EqualsExpr>(from);
assert(fp);
auto tp = dynamic_pointer_cast<EqualsExpr>(to);
assert(tp);
_eqs.getDeps().set_imm_dep_on(fp, tp);
}
virtual void clear_dependencies() override {
_eqs.getDeps().clear_deps();
}
virtual void set_fold_len(const yc_index_node_ptr, int len) override;
virtual bool is_folding_set() override {
return _settings._foldOptions.size() > 0;
}
virtual void clear_folding() override {
_settings._foldOptions.clear();
}
virtual void set_cluster_mult(const yc_index_node_ptr, int mult) override;
virtual bool is_clustering_set() override {
return _settings._clusterOptions.size() > 0;
}
virtual void clear_clustering() override {
_settings._clusterOptions.clear();
}
virtual bool is_target_set() override {
return _settings._target.length() > 0;
}
virtual std::string get_target() override {
if (!is_target_set())
THROW_YASK_EXCEPTION("Error: call to get_target() before set_target()");
return _settings._target;
}
virtual void set_target(const std::string& format) override;
virtual void set_element_bytes(int nbytes) override {
_settings._elem_bytes = nbytes;
}
virtual int get_element_bytes() const override {
return _settings._elem_bytes;
}
virtual bool is_dependency_checker_enabled() const override {
return _settings._findDeps;
}
virtual void set_dependency_checker_enabled(bool enable) override {
_settings._findDeps = enable;
}
virtual void output_solution(yask_output_ptr output) override;
virtual void
call_before_output(output_hook_t hook_fn) override {
_output_hooks.push_back(hook_fn);
}
virtual void
set_domain_dims(const std::vector<yc_index_node_ptr>& dims) override {
_settings._domainDims.clear();
for (auto& d : dims) {
auto dp = dynamic_pointer_cast<IndexExpr>(d);
assert(dp);
auto& dname = d->get_name();
if (dp->getType() != DOMAIN_INDEX)
THROW_YASK_EXCEPTION("Error: set_domain_dims() called with non-domain index '" +
dname + "'");
_settings._domainDims.push_back(dname);
}
}
virtual void
set_domain_dims(const std::initializer_list<yc_index_node_ptr>& dims) override {
vector<yc_index_node_ptr> vdims(dims);
set_domain_dims(vdims);
}
virtual void
set_step_dim(const yc_index_node_ptr dim) override {
auto dp = dynamic_pointer_cast<IndexExpr>(dim);
assert(dp);
auto& dname = dim->get_name();
if (dp->getType() != STEP_INDEX)
THROW_YASK_EXCEPTION("Error: set_step_dim() called with non-step index '" +
dname + "'");
_settings._stepDim = dname;
}
};
} // namespace yask.
| 38.34629 | 109 | 0.588555 |
9a263a6528831a76724fa8d442bd37b186de73c3 | 15,769 | cpp | C++ | CurrencyRecognition/src/ImageAnalysis/ImageDetector.cpp | vogt31337/Currency-Recognition | 05198cb002d854d650479d97d6b4e7538f670965 | [
"MIT"
] | 42 | 2015-08-20T06:57:50.000Z | 2021-04-30T17:52:27.000Z | CurrencyRecognition/src/ImageAnalysis/ImageDetector.cpp | vogt31337/Currency-Recognition | 05198cb002d854d650479d97d6b4e7538f670965 | [
"MIT"
] | 3 | 2016-11-17T14:55:43.000Z | 2019-05-20T21:01:19.000Z | CurrencyRecognition/src/ImageAnalysis/ImageDetector.cpp | vogt31337/Currency-Recognition | 05198cb002d854d650479d97d6b4e7538f670965 | [
"MIT"
] | 27 | 2016-01-29T05:41:26.000Z | 2020-11-09T12:58:42.000Z | #include "ImageDetector.h"
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <ImageDetector> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
ImageDetector::ImageDetector(Ptr<FeatureDetector> featureDetector, Ptr<DescriptorExtractor> descriptorExtractor, Ptr<DescriptorMatcher> descriptorMatcher, Ptr<ImagePreprocessor> imagePreprocessor,
const string& configurationTags, const string& selectorTags, const vector<string>& referenceImagesDirectories,
bool useInliersGlobalMatch,
const string& referenceImagesListPath, const string& testImagesListPath) :
_featureDetector(featureDetector), _descriptorExtractor(descriptorExtractor), _descriptorMatcher(descriptorMatcher),
_imagePreprocessor(imagePreprocessor), _configurationTags(configurationTags), _selectorTags(selectorTags),
_referenceImagesDirectories(referenceImagesDirectories), _referenceImagesListPath(referenceImagesListPath), _testImagesListPath(testImagesListPath),
_contourAspectRatioRange(-1, -1), _contourCircularityRange(-1, -1) {
setupTargetDB(referenceImagesListPath, useInliersGlobalMatch);
setupTargetsShapesRanges();
}
ImageDetector::~ImageDetector() {}
bool ImageDetector::setupTargetDB(const string& referenceImagesListPath, bool useInliersGlobalMatch) {
_targetDetectors.clear();
ifstream imgsList(referenceImagesListPath);
if (imgsList.is_open()) {
string configurationLine;
vector<string> configurations;
while (getline(imgsList, configurationLine)) {
configurations.push_back(configurationLine);
}
int numberOfFiles = configurations.size();
cout << " -> Initializing recognition database with " << numberOfFiles << " reference images and with " << _referenceImagesDirectories.size() << " levels of detail..." << endl;
PerformanceTimer performanceTimer;
performanceTimer.start();
//#pragma omp parallel for schedule(dynamic)
for (int configIndex = 0; configIndex < numberOfFiles; ++configIndex) {
string filename;
size_t targetTag;
string separator;
Scalar color;
stringstream ss(configurations[configIndex]);
ss >> filename >> separator >> targetTag >> separator >> color[2] >> color[1] >> color[0];
TargetDetector targetDetector(_featureDetector, _descriptorExtractor, _descriptorMatcher, targetTag, color, useInliersGlobalMatch);
for (size_t i = 0; i < _referenceImagesDirectories.size(); ++i) {
string referenceImagesDirectory = _referenceImagesDirectories[i];
Mat targetImage;
stringstream referenceImgePath;
referenceImgePath << REFERENCE_IMGAGES_DIRECTORY << referenceImagesDirectory << "/" << filename;
cout << " => Adding reference image " << referenceImgePath.str() << endl;
if (_imagePreprocessor->loadAndPreprocessImage(referenceImgePath.str(), targetImage, CV_LOAD_IMAGE_GRAYSCALE, false)) {
string filenameWithoutExtension = ImageUtils::getFilenameWithoutExtension(filename);
stringstream maskFilename;
maskFilename << REFERENCE_IMGAGES_DIRECTORY << referenceImagesDirectory << "/" << filenameWithoutExtension << MASK_TOKEN << MASK_EXTENSION;
Mat targetROIs;
if (ImageUtils::loadBinaryMask(maskFilename.str(), targetROIs)) {
targetDetector.setupTargetRecognition(targetImage, targetROIs);
vector<KeyPoint>& targetKeypoints = targetDetector.getTargetKeypoints();
stringstream imageKeypointsFilename;
imageKeypointsFilename << REFERENCE_IMGAGES_ANALYSIS_DIRECTORY << filenameWithoutExtension << "_" << referenceImagesDirectory << _selectorTags << IMAGE_OUTPUT_EXTENSION;
if (targetKeypoints.empty()) {
imwrite(imageKeypointsFilename.str(), targetImage);
} else {
Mat imageKeypoints;
cv::drawKeypoints(targetImage, targetKeypoints, imageKeypoints, TARGET_KEYPOINT_COLOR);
imwrite(imageKeypointsFilename.str(), imageKeypoints);
}
}
}
}
//#pragma omp critical
_targetDetectors.push_back(targetDetector);
}
cout << " -> Finished initialization of targets database in " << performanceTimer.getElapsedTimeFormated() << "\n" << endl;
return !_targetDetectors.empty();
} else {
return false;
}
}
void ImageDetector::setupTargetsShapesRanges(const string& maskPath) {
Mat shapeROIs;
if (ImageUtils::loadBinaryMask(maskPath, shapeROIs)) {
vector< vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours(shapeROIs, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
int contoursSize = (int)contours.size();
#pragma omp parallel for
for (int i = 0; i < contoursSize; ++i) {
double contourAspectRatio = ImageUtils::computeContourAspectRatio(contours[i]);
double contourCircularity = ImageUtils::computeContourCircularity(contours[i]);
#pragma omp critical
if (_contourAspectRatioRange[0] == -1 || contourAspectRatio < _contourAspectRatioRange[0]) {
_contourAspectRatioRange[0] = contourAspectRatio;
}
#pragma omp critical
if (_contourAspectRatioRange[1] == -1 || contourAspectRatio > _contourAspectRatioRange[1]) {
_contourAspectRatioRange[1] = contourAspectRatio;
}
#pragma omp critical
if (_contourCircularityRange[0] == -1 || contourCircularity < _contourCircularityRange[0]) {
_contourCircularityRange[0] = contourCircularity;
}
#pragma omp critical
if (_contourCircularityRange[1] == -1 || contourCircularity > _contourCircularityRange[1]) {
_contourCircularityRange[1] = contourCircularity;
}
}
}
}
Ptr< vector< Ptr<DetectorResult> > > ImageDetector::detectTargets(Mat& image, float minimumMatchAllowed, float minimumTargetAreaPercentage,
float maxDistanceRatio, float reprojectionThresholdPercentage, double confidence, int maxIters, size_t minimumNumberInliers) {
Ptr< vector< Ptr<DetectorResult> > > detectorResults(new vector< Ptr<DetectorResult> >());
vector<KeyPoint> keypointsQueryImage;
_featureDetector->detect(image, keypointsQueryImage);
if (keypointsQueryImage.size() < 4) { return detectorResults; }
Mat descriptorsQueryImage;
_descriptorExtractor->compute(image, keypointsQueryImage, descriptorsQueryImage);
cv::drawKeypoints(image, keypointsQueryImage, image, NONTARGET_KEYPOINT_COLOR);
float bestMatch = 0;
Ptr<DetectorResult> bestDetectorResult;
int targetDetectorsSize = _targetDetectors.size();
bool validDetection = true;
float reprojectionThreshold = image.cols * reprojectionThresholdPercentage;
//float reprojectionThreshold = 3.0;
do {
bestMatch = 0;
#pragma omp parallel for schedule(dynamic)
for (int i = 0; i < targetDetectorsSize; ++i) {
_targetDetectors[i].updateCurrentLODIndex(image);
Ptr<DetectorResult> detectorResult = _targetDetectors[i].analyzeImage(keypointsQueryImage, descriptorsQueryImage, maxDistanceRatio, reprojectionThreshold, confidence, maxIters, minimumNumberInliers);
if (detectorResult->getBestROIMatch() > minimumMatchAllowed) {
float contourArea = (float)cv::contourArea(detectorResult->getTargetContour());
float imageArea = (float)(image.cols * image.rows);
float contourAreaPercentage = contourArea / imageArea;
if (contourAreaPercentage > minimumTargetAreaPercentage) {
double contourAspectRatio = ImageUtils::computeContourAspectRatio(detectorResult->getTargetContour());
if (contourAspectRatio > _contourAspectRatioRange[0] && contourAspectRatio < _contourAspectRatioRange[1]) {
double contourCircularity = ImageUtils::computeContourCircularity(detectorResult->getTargetContour());
if (contourCircularity > _contourCircularityRange[0] && contourCircularity < _contourCircularityRange[1]) {
if (cv::isContourConvex(detectorResult->getTargetContour())) {
#pragma omp critical
{
if (detectorResult->getBestROIMatch() > bestMatch) {
bestMatch = detectorResult->getBestROIMatch();
bestDetectorResult = detectorResult;
}
}
}
}
}
}
}
}
validDetection = bestMatch > minimumMatchAllowed && bestDetectorResult->getInliers().size() > minimumNumberInliers;
if (bestDetectorResult.obj != NULL && validDetection) {
detectorResults->push_back(bestDetectorResult);
// remove inliers of best match to detect more occurrences of targets
ImageUtils::removeInliersFromKeypointsAndDescriptors(bestDetectorResult->getInliers(), keypointsQueryImage, descriptorsQueryImage);
}
} while (validDetection);
return detectorResults;
}
vector<size_t> ImageDetector::detectTargetsAndOutputResults(Mat& image, const string& imageFilename, bool useHighGUI) {
Mat imageBackup = image.clone();
Ptr< vector< Ptr<DetectorResult> > > detectorResultsOut = detectTargets(image);
vector<size_t> results;
stringstream imageInliersOutputFilename;
imageInliersOutputFilename << TEST_OUTPUT_DIRECTORY << imageFilename << FILENAME_SEPARATOR << _configurationTags << FILENAME_SEPARATOR << INLIERS_MATCHES << FILENAME_SEPARATOR;
for (size_t i = 0; i < detectorResultsOut->size(); ++i) {
Ptr<DetectorResult> detectorResult = (*detectorResultsOut)[i];
results.push_back(detectorResult->getTargetValue());
cv::drawKeypoints(image, detectorResult->getInliersKeypoints(), image, TARGET_KEYPOINT_COLOR);
stringstream ss;
ss << detectorResult->getTargetValue();
Mat imageMatchesSingle = imageBackup.clone();
Mat matchesInliers = detectorResult->getInliersMatches(imageMatchesSingle);
try {
Rect boundingBox = cv::boundingRect(detectorResult->getTargetContour());
ImageUtils::correctBoundingBox(boundingBox, image.cols, image.rows);
GUIUtils::drawLabelInCenterOfROI(ss.str(), image, boundingBox);
GUIUtils::drawLabelInCenterOfROI(ss.str(), matchesInliers, boundingBox);
ImageUtils::drawContour(image, detectorResult->getTargetContour(), detectorResult->getContourColor());
ImageUtils::drawContour(matchesInliers, detectorResult->getTargetContour(), detectorResult->getContourColor());
} catch (...) {
std::cerr << "!!! Drawing outside image !!!" << endl;
}
if (useHighGUI) {
stringstream windowName;
windowName << "Target inliers matches (window " << i << ")";
cv::namedWindow(windowName.str(), CV_WINDOW_KEEPRATIO);
cv::imshow(windowName.str(), matchesInliers);
cv::waitKey(10);
}
stringstream imageOutputFilenameFull;
imageOutputFilenameFull << imageInliersOutputFilename.str() << i << IMAGE_OUTPUT_EXTENSION;
imwrite(imageOutputFilenameFull.str(), matchesInliers);
}
sort(results.begin(), results.end());
cout << " -> Detected " << results.size() << (results.size() != 1 ? " targets" : " target");
size_t globalResult = 0;
stringstream resultsSS;
if (!results.empty()) {
resultsSS << " (";
for (size_t i = 0; i < results.size(); ++i) {
size_t resultValue = results[i];
resultsSS << " " << resultValue;
globalResult += resultValue;
}
resultsSS << " )";
cout << resultsSS.str();
}
cout << endl;
stringstream globalResultSS;
globalResultSS << "Global result: " << globalResult << resultsSS.str();
Rect globalResultBoundingBox(0, 0, image.cols, image.rows);
GUIUtils::drawImageLabel(globalResultSS.str(), image, globalResultBoundingBox);
stringstream imageOutputFilename;
imageOutputFilename << TEST_OUTPUT_DIRECTORY << imageFilename << FILENAME_SEPARATOR << _configurationTags << IMAGE_OUTPUT_EXTENSION;
imwrite(imageOutputFilename.str(), image);
return results;
}
DetectorEvaluationResult ImageDetector::evaluateDetector(const string& testImgsList, bool saveResults) {
double globalPrecision = 0;
double globalRecall = 0;
double globalAccuracy = 0;
size_t numberTestImages = 0;
stringstream resultsFilename;
resultsFilename << TEST_OUTPUT_DIRECTORY << _configurationTags << FILENAME_SEPARATOR << RESULTS_FILE;
ofstream resutlsFile(resultsFilename.str());
ifstream imgsList(testImgsList);
if (resutlsFile.is_open() && imgsList.is_open()) {
resutlsFile << RESULTS_FILE_HEADER << "\n" << endl;
string filename;
vector<string> imageFilenames;
vector< vector<size_t> > expectedResults;
while (getline(imgsList, filename)) {
imageFilenames.push_back(filename);
vector<size_t> expectedResultFromTest;
extractExpectedResultsFromFilename(filename, expectedResultFromTest);
expectedResults.push_back(expectedResultFromTest);
}
int numberOfTests = imageFilenames.size();
cout << " -> Evaluating detector with " << numberOfTests << " test images..." << endl;
PerformanceTimer globalPerformanceTimer;
globalPerformanceTimer.start();
//#pragma omp parallel for schedule(dynamic)
for (int i = 0; i < numberOfTests; ++i) {
PerformanceTimer testPerformanceTimer;
testPerformanceTimer.start();
string imageFilename = imageFilenames[i];
//string imageFilename = ImageUtils::getFilenameWithoutExtension("");
string imageFilenameWithPath = TEST_IMGAGES_DIRECTORY + imageFilenames[i];
stringstream detectorEvaluationResultSS;
DetectorEvaluationResult detectorEvaluationResult;
Mat imagePreprocessed;
cout << "\n -> Evaluating image " << imageFilename << " (" << (i + 1) << "/" << numberOfTests << ")" << endl;
if (_imagePreprocessor->loadAndPreprocessImage(imageFilenameWithPath, imagePreprocessed, CV_LOAD_IMAGE_GRAYSCALE, false)) {
vector<size_t> results = detectTargetsAndOutputResults(imagePreprocessed, imageFilename, false);
detectorEvaluationResult = DetectorEvaluationResult(results, expectedResults[i]);
globalPrecision += detectorEvaluationResult.getPrecision();
globalRecall += detectorEvaluationResult.getRecall();
globalAccuracy += detectorEvaluationResult.getAccuracy();
detectorEvaluationResultSS << PRECISION_TOKEN << ": " << detectorEvaluationResult.getPrecision() << " | " << RECALL_TOKEN << ": " << detectorEvaluationResult.getRecall() << " | " << ACCURACY_TOKEN << ": " << detectorEvaluationResult.getAccuracy();
++numberTestImages;
if (saveResults) {
resutlsFile << imageFilename << " -> " << detectorEvaluationResultSS.str() << endl;
}
}
cout << " -> Evaluation of image " << imageFilename << " finished in " << testPerformanceTimer.getElapsedTimeFormated() << endl;
cout << " -> " << detectorEvaluationResultSS.str() << endl;
}
globalPrecision /= (double)numberTestImages;
globalRecall /= (double)numberTestImages;
globalAccuracy /= (double)numberTestImages;
stringstream detectorEvaluationGloablResultSS;
detectorEvaluationGloablResultSS << GLOBAL_PRECISION_TOKEN << ": " << globalPrecision << " | " << GLOBAL_RECALL_TOKEN << ": " << globalRecall << " | " << GLOBAL_ACCURACY_TOKEN << ": " << globalAccuracy;
resutlsFile << "\n\n" << RESULTS_FILE_FOOTER << endl;
resutlsFile << " ==> " << detectorEvaluationGloablResultSS.str() << endl;
cout << "\n -> Finished evaluation of detector in " << globalPerformanceTimer.getElapsedTimeFormated() << " || " << detectorEvaluationGloablResultSS.str() << "\n" << endl;
}
return DetectorEvaluationResult(globalPrecision, globalRecall, globalAccuracy);
}
void ImageDetector::extractExpectedResultsFromFilename(string filename, vector<size_t>& expectedResultFromTestOut) {
for (size_t i = 0; i < filename.size(); ++i) {
char letter = filename[i];
if (letter == '-') {
filename[i] = ' ';
} else if (letter == '.' || letter == '_') {
filename = filename.substr(0, i);
break;
}
}
stringstream ss(filename);
size_t number;
while (ss >> number) {
expectedResultFromTestOut.push_back(number);
}
}
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> </ImageDetector> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
| 42.850543 | 251 | 0.722684 |
9a2c88ddbed7605526dca4235c577809eba1b6b2 | 28,057 | cpp | C++ | Src/Value.cpp | draede/cx | f3ce4aec9b99095760481b1507e383975b2827e3 | [
"MIT"
] | 1 | 2016-08-28T18:29:17.000Z | 2016-08-28T18:29:17.000Z | Src/Value.cpp | draede/cx | f3ce4aec9b99095760481b1507e383975b2827e3 | [
"MIT"
] | null | null | null | Src/Value.cpp | draede/cx | f3ce4aec9b99095760481b1507e383975b2827e3 | [
"MIT"
] | null | null | null | /*
* CX - C++ framework for general purpose development
*
* https://github.com/draede/cx
*
* Copyright (C) 2014 - 2021 draede - draede [at] outlook [dot] com
*
* Released under the MIT License.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "CX/precomp.hpp"
#include "CX/Value.hpp"
#include "CX/IO/MemInputStream.hpp"
#include "CX/IO/MemOutputStream.hpp"
namespace CX
{
class VarJSONSAXParserObserver : public Data::JSON::ISAXParserObserver
{
public:
Bool m_bInit;
Value *m_pRoot;
Value *m_pCurrent;
String m_sKey;
virtual Bool OnBeginParse()
{
return True;
}
virtual Bool OnEndParse()
{
return True;
}
virtual Bool OnBeginObject()
{
if (m_bInit)
{
if (m_pCurrent->SetAsObject().IsNOK())
{
return False;
}
m_bInit = False;
}
else
{
Value *pValue = new (std::nothrow) Value(Value::Type_Object);
if (NULL == pValue)
{
return False;
}
if (m_pCurrent->IsObject())
{
m_pCurrent->AddMember(m_sKey, pValue);
m_pCurrent = pValue;
}
else
{
m_pCurrent->AddItem(pValue);
m_pCurrent = pValue;
}
}
return True;
}
virtual Bool OnEndObject()
{
m_pCurrent = &m_pCurrent->GetParent();
return True;
}
virtual Bool OnBeginArray()
{
if (m_bInit)
{
if (m_pCurrent->SetAsArray().IsNOK())
{
return False;
}
m_bInit = False;
}
else
{
Value *pValue = new (std::nothrow) Value(Value::Type_Array);
if (NULL == pValue)
{
return False;
}
if (m_pCurrent->IsObject())
{
m_pCurrent->AddMember(m_sKey, pValue);
m_pCurrent = pValue;
}
else
{
m_pCurrent->AddItem(pValue);
m_pCurrent = pValue;
}
}
return True;
}
virtual Bool OnEndArray()
{
m_pCurrent = &m_pCurrent->GetParent();
return True;
}
virtual Bool OnKey(const Char *pBuffer, Size cLen)
{
m_sKey.assign(pBuffer, cLen);
return True;
}
virtual Bool OnNullValue()
{
if (m_pCurrent->IsObject())
{
(*m_pCurrent)[m_sKey].SetNull();
}
else
{
(*m_pCurrent)[-1].SetNull();
}
return True;
}
virtual Bool OnBoolValue(Bool bBool)
{
if (m_pCurrent->IsObject())
{
(*m_pCurrent)[m_sKey].SetBool(bBool);
}
else
{
(*m_pCurrent)[-1].SetBool(bBool);
}
return True;
}
virtual Bool OnIntValue(Int64 nInt)
{
if (m_pCurrent->IsObject())
{
(*m_pCurrent)[m_sKey].SetInt(nInt);
}
else
{
(*m_pCurrent)[-1].SetInt(nInt);
}
return True;
}
virtual Bool OnUIntValue(UInt64 uInt)
{
if (m_pCurrent->IsObject())
{
(*m_pCurrent)[m_sKey].SetUInt(uInt);
}
else
{
(*m_pCurrent)[-1].SetUInt(uInt);
}
return True;
}
virtual Bool OnRealValue(Double lfReal)
{
if (m_pCurrent->IsObject())
{
(*m_pCurrent)[m_sKey].SetReal(lfReal);
}
else
{
(*m_pCurrent)[-1].SetReal(lfReal);
}
return True;
}
virtual Bool OnStringValue(const Char *pBuffer, Size cLen)
{
if (m_pCurrent->IsObject())
{
(*m_pCurrent)[m_sKey].SetString(String(pBuffer, cLen));
}
else
{
(*m_pCurrent)[-1].SetString(String(pBuffer, cLen));
}
return True;
}
};
Value Value::INVALID_VALUE(NULL, NULL, NULL);
const Double Value::DEFAULT_REAL = 0.0;
const String Value::DEFAULT_STRING;
Value::Value()
{
m_nType = Type_Null;
m_pParent = NULL;
}
Value::Value(void *pDummy1, void *pDummy2, void *pDummy3)
{
CX_UNUSED(pDummy1);
CX_UNUSED(pDummy2);
CX_UNUSED(pDummy3);
m_nType = Type_Invalid;
m_pParent = NULL;
}
Value::Value(Value *pParent)
{
m_nType = Type_Null;
m_pParent = pParent;
}
Value::Value(Type nType)
{
m_nType = Type_Null;
m_pParent = NULL;
switch (nType)
{
case Type_Bool: SetBool(DEFAULT_BOOL); break;
case Type_Int: SetInt(DEFAULT_INT); break;
case Type_UInt: SetUInt(DEFAULT_UINT); break;
case Type_Real: SetReal(DEFAULT_REAL); break;
case Type_String: SetString(DEFAULT_STRING); break;
case Type_Object: SetAsObject(); break;
case Type_Array: SetAsArray(); break;
default:
{
}
}
}
Value::Value(Bool bValue)
{
m_nType = Type_Null;
m_pParent = NULL;
SetBool(bValue);
}
Value::Value(Int64 nValue)
{
m_nType = Type_Null;
m_pParent = NULL;
SetInt(nValue);
}
Value::Value(UInt64 uValue)
{
m_nType = Type_Null;
m_pParent = NULL;
SetUInt(uValue);
}
Value::Value(Double lfValue)
{
m_nType = Type_Null;
m_pParent = NULL;
SetReal(lfValue);
}
Value::Value(const String &sValue)
{
m_nType = Type_Null;
m_pParent = NULL;
SetString(sValue);
}
Value::Value(const Value &value)
{
m_nType = Type_Null;
Copy(value);
}
Value::~Value()
{
if (!IsInvalid())
{
FreeMem();
m_nType = Type_Null;
m_pParent = NULL;
}
}
void Value::FreeMem()
{
if (IsInvalid())
{
return;
}
if (Type_String == m_nType)
{
delete m_psString;
}
else
if (Type_Object == m_nType)
{
for (Object::iterator iter = m_pObject->begin(); iter != m_pObject->end(); ++iter)
{
delete iter->second;
}
delete m_pObject;
}
else
if (Type_Array == m_nType)
{
for (Array::iterator iter = m_pArray->begin(); iter != m_pArray->end(); ++iter)
{
delete *iter;
}
delete m_pArray;
}
}
Value &Value::operator=(const Value &value)
{
if (IsInvalid())
{
return *this;
}
Copy(value);
return *this;
}
Status Value::Copy(const Value &value)
{
if (IsInvalid())
{
return Status_InvalidCall;
}
switch (value.m_nType)
{
case Type_Null: return SetNull();
case Type_Bool: return SetBool(value.GetBool());
case Type_Int: return SetInt(value.GetInt());
case Type_UInt: return SetUInt(value.GetUInt());
case Type_Real: return SetReal(value.GetReal());
case Type_String: return SetString(value.GetString());
case Type_Object:
{
Status status;
if ((status = SetAsObject()).IsNOK())
{
return status;
}
for (Object::iterator iter = value.m_pObject->begin(); iter != value.m_pObject->end(); ++iter)
{
if ((status = AddMember(iter->first, iter->second)).IsNOK())
{
return status;
}
}
return Status();
}
break;
case Type_Array:
{
Status status;
if ((status = SetAsArray()).IsNOK())
{
return status;
}
for (Array::iterator iter = value.m_pArray->begin(); iter != value.m_pArray->end(); ++iter)
{
if ((status = AddItem(*iter)).IsNOK())
{
return status;
}
}
return Status();
}
break;
default:
{
return Status_InvalidArg;
}
}
}
Bool Value::HasParent()
{
return (NULL != m_pParent);
}
const Value &Value::GetParent() const
{
if (NULL != m_pParent)
{
return *m_pParent;
}
else
{
return INVALID_VALUE;
}
}
Value &Value::GetParent()
{
if (NULL != m_pParent)
{
return *m_pParent;
}
else
{
return INVALID_VALUE;
}
}
Value::Type Value::GetType() const
{
return m_nType;
}
Bool Value::IsInvalid() const
{
return (Type_Invalid == GetType());
}
Bool Value::IsNull() const
{
return (Type_Null == GetType());
}
Bool Value::IsBool() const
{
return (Type_Bool == GetType());
}
Bool Value::IsInt() const
{
return (Type_Int == GetType());
}
Bool Value::IsUInt() const
{
return (Type_UInt == GetType());
}
Bool Value::IsReal() const
{
return (Type_Real == GetType());
}
Bool Value::IsString() const
{
return (Type_String == GetType());
}
Bool Value::IsObject() const
{
return (Type_Object == GetType());
}
Bool Value::IsArray() const
{
return (Type_Array == GetType());
}
Bool Value::GetNull(Status *pStatus/* = NULL*/) const
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return False;
}
if (IsNull())
{
if (NULL != pStatus)
{
*pStatus = Status_OK;
}
return True;
}
else
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return False;
}
}
Status Value::SetNull()
{
if (IsInvalid())
{
return Status_InvalidCall;
}
FreeMem();
m_nType = Type_Null;
return Status();
}
Bool Value::GetBool(Bool bDefault/* = DEFAULT_BOOL*/, Status *pStatus/* = NULL*/) const
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return bDefault;
}
if (IsBool())
{
if (NULL != pStatus)
{
*pStatus = Status_OK;
}
return m_bBool;
}
else
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return bDefault;
}
}
Status Value::SetBool(Bool bValue)
{
if (IsInvalid())
{
return Status_InvalidCall;
}
FreeMem();
m_nType = Type_Bool;
m_bBool = bValue;
return Status();
}
Int64 Value::GetInt(Int64 nDefault/* = DEFAULT_INT*/, Status *pStatus/* = NULL*/) const
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return nDefault;
}
if (IsInt())
{
if (NULL != pStatus)
{
*pStatus = Status_OK;
}
return m_nInt;
}
else
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return nDefault;
}
}
Status Value::SetInt(Int64 nValue)
{
if (IsInvalid())
{
return Status_InvalidCall;
}
FreeMem();
m_nType = Type_Int;
m_nInt = nValue;
return Status();
}
UInt64 Value::GetUInt(UInt64 uDefault/* = DEFAULT_UINT*/, Status *pStatus/* = NULL*/) const
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return uDefault;
}
if (IsUInt())
{
if (NULL != pStatus)
{
*pStatus = Status_OK;
}
return m_uInt;
}
else
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return uDefault;
}
}
Status Value::SetUInt(UInt64 uValue)
{
if (IsInvalid())
{
return Status_InvalidCall;
}
FreeMem();
m_nType = Type_UInt;
m_uInt = uValue;
return Status();
}
Double Value::GetReal(Double lfDefault/* = DEFAULT_DOUBLE*/, Status *pStatus/* = NULL*/) const
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return lfDefault;
}
if (IsReal())
{
if (NULL != pStatus)
{
*pStatus = Status_OK;
}
return m_lfReal;
}
else
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return lfDefault;
}
}
Status Value::SetReal(Double lfValue)
{
if (IsInvalid())
{
return Status_InvalidCall;
}
FreeMem();
m_nType = Type_Real;
m_lfReal = lfValue;
return Status();
}
const String &Value::GetString(const String &sDefault/* = DEFAULT_STRING*/, Status *pStatus/* = NULL*/) const
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return sDefault;
}
if (IsString())
{
if (NULL != pStatus)
{
*pStatus = Status_OK;
}
return *m_psString;
}
else
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return sDefault;
}
}
Status Value::SetString(const String &sValue)
{
if (IsInvalid())
{
return Status_InvalidCall;
}
String *psValue;
if (NULL == (psValue = new (std::nothrow) String(sValue)))
{
return Status_MemAllocFailed;
}
FreeMem();
m_nType = Type_String;
m_psString = psValue;
return Status();
}
Status Value::SetAsArray()
{
if (IsInvalid())
{
return Status_InvalidCall;
}
Array *pArray;
if (NULL == (pArray = new (std::nothrow) Array()))
{
return Status_MemAllocFailed;
}
FreeMem();
m_nType = Type_Array;
m_pArray = pArray;
return Status();
}
Status Value::SetAsObject()
{
if (IsInvalid())
{
return Status_InvalidCall;
}
Object *pObject;
if (NULL == (pObject = new (std::nothrow) Object()))
{
return Status_MemAllocFailed;
}
FreeMem();
m_nType = Type_Object;
m_pObject = pObject;
return Status();
}
Size Value::GetItemsCount(Status *pStatus/* = NULL*/) const
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return 0;
}
if (IsArray())
{
if (NULL != pStatus)
{
*pStatus = Status_OK;
}
return m_pArray->size();
}
else
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return 0;
}
}
Value &Value::AddItem(Status *pStatus/* = NULL*/)
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return INVALID_VALUE;
}
if (!IsArray())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return INVALID_VALUE;
}
Value *pValue;
if (NULL == (pValue = new (std::nothrow) Value(this)))
{
return INVALID_VALUE;
}
m_pArray->push_back(pValue);
return *pValue;
}
Status Value::AddItem(Value *pValue)
{
if (IsInvalid())
{
return Status_InvalidCall;
}
if (!IsArray())
{
return Status_InvalidArg;
}
if (NULL != pValue->m_pParent)
{
return Status_InvalidArg;
}
pValue->m_pParent = this;
m_pArray->push_back(pValue);
return Status();
}
Value &Value::InsertItem(int cIndex, Status *pStatus/* = NULL*/)
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return INVALID_VALUE;
}
if (!IsArray())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return INVALID_VALUE;
}
if (0 > cIndex)
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return INVALID_VALUE;
}
if (cIndex >= (int)m_pArray->size())
{
return AddItem(pStatus);
}
Value *pValue;
if (NULL == (pValue = new (std::nothrow) Value(this)))
{
return INVALID_VALUE;
}
Array::iterator iter = m_pArray->begin() + cIndex;
m_pArray->insert(iter, pValue);
return *pValue;
}
Status Value::InsertItem(int cIndex, Value *pValue)
{
if (IsInvalid())
{
return Status_InvalidCall;
}
if (!IsArray())
{
return Status_InvalidArg;
}
if (NULL == pValue->m_pParent)
{
return Status_InvalidArg;
}
if (0 > cIndex)
{
return Status_InvalidArg;
}
if (cIndex >= (int)m_pArray->size())
{
return AddItem(pValue);
}
pValue->m_pParent = this;
Array::iterator iter = m_pArray->begin() + cIndex;
m_pArray->insert(iter, pValue);
return Status();
}
Status Value::RemoveItem(int cIndex)
{
if (IsInvalid())
{
return Status_InvalidCall;
}
if (!IsArray())
{
return Status_InvalidArg;
}
if (cIndex >= (int)m_pArray->size())
{
return Status_InvalidArg;
}
Array::iterator iter = m_pArray->begin() + cIndex;
delete *iter;
m_pArray->erase(iter);
return Status();
}
Status Value::RemoveAllItems()
{
if (IsInvalid())
{
return Status_InvalidCall;
}
if (!IsArray())
{
return Status_InvalidArg;
}
for (Array::iterator iter = m_pArray->begin(); iter != m_pArray->end(); ++iter)
{
delete *iter;
}
m_pArray->clear();
return Status();
}
const Value &Value::GetItem(int cIndex, Status *pStatus/* = NULL*/) const
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return INVALID_VALUE;
}
if (!IsArray())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return INVALID_VALUE;
}
if (0 > cIndex || cIndex >= (int)m_pArray->size())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return INVALID_VALUE;
}
return *(*m_pArray)[cIndex];
}
Value &Value::GetItem(int cIndex, Status *pStatus/* = NULL*/) //-1 will create a new value at the end
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return INVALID_VALUE;
}
if (!IsArray())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return INVALID_VALUE;
}
if (-1 == cIndex)
{
return AddItem(pStatus);
}
if (0 > cIndex || cIndex >= (int)m_pArray->size())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return INVALID_VALUE;
}
return *(*m_pArray)[cIndex];
}
const Value &Value::operator[](int cIndex) const
{
return GetItem(cIndex);
}
Value &Value::operator[](int cIndex) //a non existing member will be created
{
return GetItem(cIndex);
}
Size Value::GetMembersCount(Status *pStatus/* = NULL*/) const
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return 0;
}
if (!IsObject())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return 0;
}
return m_pObject->size();
}
Bool Value::Exists(const String &sName, Status *pStatus/* = NULL*/) const
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return False;
}
if (!IsObject())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return False;
}
return (m_pObject->end() != m_pObject->find(sName));
}
Value &Value::AddMember(const String &sName, Status *pStatus/* = NULL*/)
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return INVALID_VALUE;
}
if (!IsObject())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return INVALID_VALUE;
}
Object::iterator iter = m_pObject->find(sName);
if (m_pObject->end() != iter)
{
return *iter->second;
}
Value *pValue;
if (NULL == (pValue = new (std::nothrow) Value(this)))
{
return INVALID_VALUE;
}
(*m_pObject)[sName] = pValue;
return *pValue;
}
Status Value::AddMember(const String &sName, Value *pValue)
{
if (IsInvalid())
{
return Status_InvalidCall;
}
if (!IsObject())
{
return Status_InvalidArg;
}
Object::iterator iter = m_pObject->find(sName);
if (m_pObject->end() != iter)
{
return Status_InvalidArg;
}
if (NULL != pValue->m_pParent)
{
return Status_InvalidArg;
}
pValue->m_pParent = this;
(*m_pObject)[sName] = pValue;
return Status();
}
Status Value::RemoveMember(const String &sName)
{
if (IsInvalid())
{
return Status_InvalidCall;
}
if (!IsObject())
{
return Status_InvalidArg;
}
Object::iterator iter = m_pObject->find(sName);
if (m_pObject->end() == iter)
{
return Status_NotFound;
}
m_pObject->erase(iter);
return Status();
}
Status Value::RemoveAllMembers()
{
if (IsInvalid())
{
return Status_InvalidCall;
}
if (!IsObject())
{
return Status_InvalidArg;
}
for (Object::iterator iter = m_pObject->begin(); iter != m_pObject->end(); ++iter)
{
delete iter->second;
}
m_pObject->clear();
return Status();
}
Value &Value::GetMemberByIndex(Size cIndex, String *psName/* = NULL*/, Status *pStatus/* = NULL*/)
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return INVALID_VALUE;
}
if (!IsObject())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return INVALID_VALUE;
}
if (cIndex >= m_pObject->size())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return INVALID_VALUE;
}
Object::iterator iter = m_pObject->begin();
while (0 < cIndex)
{
++iter;
cIndex--;
}
if (NULL != psName)
{
*psName = iter->first;
}
return *iter->second;
}
const Value &Value::GetMemberByIndex(Size cIndex, String *psName/* = NULL*/, Status *pStatus/* = NULL*/) const
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return INVALID_VALUE;
}
if (!IsObject())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return INVALID_VALUE;
}
if (cIndex >= m_pObject->size())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return INVALID_VALUE;
}
Object::const_iterator iter = m_pObject->begin();
while (0 < cIndex)
{
++iter;
cIndex--;
}
if (NULL != psName)
{
*psName = iter->first;
}
return *iter->second;
}
const Value &Value::GetMember(const String &sName, Status *pStatus/* = NULL*/) const
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return INVALID_VALUE;
}
if (!IsObject())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return INVALID_VALUE;
}
Object::const_iterator iter = m_pObject->find(sName);
if (m_pObject->end() == iter)
{
if (NULL != pStatus)
{
*pStatus = Status_NotFound;
}
return INVALID_VALUE;
}
return *iter->second;
}
Value &Value::GetMember(const String &sName, Status *pStatus/* = NULL*/) //a non existing member will be created
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return INVALID_VALUE;
}
if (!IsObject())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return INVALID_VALUE;
}
Object::iterator iter = m_pObject->find(sName);
if (m_pObject->end() == iter)
{
return AddMember(sName, pStatus);
}
return *iter->second;
}
const Value &Value::operator[](const String &sName) const
{
return GetMember(sName);
}
Value &Value::operator[](const String &sName) //a non existing member will be created
{
return GetMember(sName);
}
const Value &Value::operator[](const Char *szName) const
{
return GetMember(szName);
}
Value &Value::operator[](const Char *szName) //a non existing member will be created
{
return GetMember(szName);
}
Value &Value::operator=(Bool bBool)
{
SetBool(bBool);
return *this;
}
Value &Value::operator=(Int64 nInt)
{
SetInt(nInt);
return *this;
}
Value &Value::operator=(UInt64 uInt)
{
SetUInt(uInt);
return *this;
}
Value &Value::operator=(Double lfReal)
{
SetReal(lfReal);
return *this;
}
Value &Value::operator=(const String &sString)
{
SetString(sString);
return *this;
}
Value &Value::operator=(const Char *szString)
{
SetString(szString);
return *this;
}
Value::operator Bool () const
{
return GetBool();
}
Value::operator Int64 () const
{
return GetInt();
}
Value::operator UInt64 () const
{
return GetUInt();
}
Value::operator Double () const
{
return GetReal();
}
Value::operator const String & () const
{
return GetString();
}
Value::operator const Char * () const
{
return GetString().c_str();
}
Status Value::Read(IO::IInputStream *pInputStream)
{
Data::JSON::SAXParser parser;
VarJSONSAXParserObserver observer;
Status status;
observer.m_pRoot = observer.m_pCurrent = this;
observer.m_bInit = True;
if ((status = parser.AddObserver(&observer)).IsNOK())
{
return status;
}
return parser.ParseStream(pInputStream);
}
Status Value::Read(const void *pData, Size cbSize)
{
IO::MemInputStream mis(pData, cbSize);
return Read(&mis);
}
Status Value::Read(const String &sData)
{
return Read(sData.c_str(), sData.size());
}
Status Value::Read(const Char *szData)
{
return Read(String(szData));
}
int Value::Compare(const Value &v) const
{
struct Node
{
const Value *pV1;
const Value *pV2;
int cIndex;
};
typedef Stack<Node>::Type NodesStack;
NodesStack stackNodes;
const Value *pV1 = this;
const Value *pV2 = &v;
bool bReady;
Status status;
for (;;)
{
if (!stackNodes.empty())
{
stackNodes.top().cIndex++;
if (stackNodes.top().pV1->IsObject())
{
String sName;
if ((Size)stackNodes.top().cIndex < stackNodes.top().pV1->GetMembersCount())
{
pV1 = &stackNodes.top().pV1->GetMemberByIndex((Size)stackNodes.top().cIndex, &sName, &status);
if (!status)
{
return status;
}
pV2 = &stackNodes.top().pV2->GetMember(sName, &status);
if (!status)
{
return status;
}
}
else
{
stackNodes.pop();
if (stackNodes.empty())
{
break;
}
else
{
continue;
}
}
}
else
{
if ((Size)stackNodes.top().cIndex < stackNodes.top().pV1->GetItemsCount())
{
pV1 = &stackNodes.top().pV1->GetItem((Size)stackNodes.top().cIndex, &status);
if (!status)
{
return status;
}
pV2 = &stackNodes.top().pV2->GetItem((Size)stackNodes.top().cIndex, &status);
if (!status)
{
return status;
}
}
else
{
stackNodes.pop();
if (stackNodes.empty())
{
break;
}
else
{
continue;
}
}
}
}
bReady = false;
if (pV1->IsInt())
{
if (pV2->IsUInt())
{
if (0 > pV1->GetInt())
{
return -1;
}
else
{
if ((UInt64)pV1->GetInt() < pV2->GetUInt())
{
return -1;
}
else
if ((UInt64)pV1->GetInt() > pV2->GetUInt())
{
return 1;
}
}
bReady = true;
}
else
if (pV2->IsReal())
{
if ((double)pV1->GetInt() < pV2->GetReal())
{
return -1;
}
else
if ((double)pV1->GetInt() > pV2->GetReal())
{
return 1;
}
bReady = true;
}
}
else
if (pV1->IsUInt())
{
if (pV2->IsInt())
{
if (0 > pV2->GetInt())
{
return 1;
}
else
{
if (pV1->GetUInt() < (UInt64)pV2->GetInt())
{
return -1;
}
else
if (pV1->GetUInt() > (UInt64)pV2->GetInt())
{
return 1;
}
}
bReady = true;
}
else
if (pV2->IsReal())
{
if ((double)pV1->GetUInt() < pV2->GetReal())
{
return -1;
}
else
if ((double)pV1->GetUInt() > pV2->GetReal())
{
return 1;
}
bReady = true;
}
}
else
if (pV1->IsReal())
{
if (pV2->IsInt())
{
if (pV1->GetReal() < (double)pV2->GetInt())
{
return -1;
}
else
if (pV1->GetReal() > (double)pV2->GetInt())
{
return 1;
}
bReady = true;
}
else
if (pV2->IsUInt())
{
if (pV1->GetReal() < (double)pV2->GetUInt())
{
return -1;
}
else
if (pV1->GetReal() > (double)pV2->GetUInt())
{
return 1;
}
bReady = true;
}
}
if (!bReady)
{
if (pV1->GetType() < pV2->GetType())
{
return -1;
}
else
if (pV1->GetType() > pV2->GetType())
{
return 1;
}
else
{
if (pV1->IsNull())
{
//nothing to do
}
else
if (pV1->IsBool())
{
if (pV1->GetBool() < pV2->GetBool())
{
return -1;
}
else
if (pV1->GetBool() > pV2->GetBool())
{
return 1;
}
}
else
if (pV1->IsInt())
{
if (pV1->GetInt() < pV2->GetInt())
{
return -1;
}
if (pV1->GetInt() > pV2->GetInt())
{
return 1;
}
}
else
if (pV1->IsUInt())
{
if (pV1->GetUInt() < pV2->GetUInt())
{
return -1;
}
if (pV1->GetUInt() > pV2->GetUInt())
{
return 1;
}
}
else
if (pV1->IsReal())
{
if (pV1->GetReal() < pV2->GetReal())
{
return -1;
}
if (pV1->GetReal() > pV2->GetReal())
{
return 1;
}
}
else
if (pV1->IsString())
{
int nCmp = cx_strcmp(pV1->GetString().c_str(), pV2->GetString().c_str());
if (0 != nCmp)
{
return nCmp;
}
}
else
if (pV1->IsObject())
{
if (pV1->GetMembersCount() < pV2->GetMembersCount())
{
return -1;
}
else
if (pV1->GetMembersCount() > pV2->GetMembersCount())
{
return 1;
}
Node node;
node.pV1 = pV1;
node.pV2 = pV2;
node.cIndex = -1;
stackNodes.push(node);
}
else
if (pV1->IsArray())
{
if (pV1->GetItemsCount() < pV2->GetItemsCount())
{
return -1;
}
else
if (pV1->GetItemsCount() > pV2->GetItemsCount())
{
return 1;
}
Node node;
node.pV1 = pV1;
node.pV2 = pV2;
node.cIndex = -1;
stackNodes.push(node);
}
else
{
return -1;
}
}
}
if (stackNodes.empty())
{
break;
}
}
return 0;
}
}//namespace CX
| 14.651175 | 112 | 0.602559 |
9a2d05e47bd44d6d79b0bff50eda108f63beb5b2 | 473 | cpp | C++ | fboss/agent/hw/sai/store/SaiObjectEventPublisher.cpp | nathanawmk/fboss | 9f36dbaaae47202f9131598560c65715334a9a83 | [
"BSD-3-Clause"
] | 834 | 2015-03-10T18:12:28.000Z | 2022-03-31T20:16:17.000Z | fboss/agent/hw/sai/store/SaiObjectEventPublisher.cpp | nathanawmk/fboss | 9f36dbaaae47202f9131598560c65715334a9a83 | [
"BSD-3-Clause"
] | 82 | 2015-04-07T08:48:29.000Z | 2022-03-11T21:56:58.000Z | fboss/agent/hw/sai/store/SaiObjectEventPublisher.cpp | nathanawmk/fboss | 9f36dbaaae47202f9131598560c65715334a9a83 | [
"BSD-3-Clause"
] | 296 | 2015-03-11T03:45:37.000Z | 2022-03-14T22:54:22.000Z | // Copyright 2004-present Facebook. All Rights Reserved.
#include "fboss/agent/hw/sai/store/SaiObjectEventPublisher.h"
#include <folly/Singleton.h>
namespace {
struct singleton_tag_type {};
} // namespace
namespace facebook::fboss {
static folly::Singleton<SaiObjectEventPublisher, singleton_tag_type>
kSingleton{};
std::shared_ptr<SaiObjectEventPublisher>
SaiObjectEventPublisher::getInstance() {
return kSingleton.try_get();
}
} // namespace facebook::fboss
| 21.5 | 68 | 0.778013 |
9a2fb0628aefad8b7f0559296a58049cf8c5d057 | 1,245 | hpp | C++ | include/Pomdog/Graphics/InputLayoutHelper.hpp | bis83/pomdog | 133a9262958d539ae6d93664e6cb2207b5b6c7ff | [
"MIT"
] | null | null | null | include/Pomdog/Graphics/InputLayoutHelper.hpp | bis83/pomdog | 133a9262958d539ae6d93664e6cb2207b5b6c7ff | [
"MIT"
] | null | null | null | include/Pomdog/Graphics/InputLayoutHelper.hpp | bis83/pomdog | 133a9262958d539ae6d93664e6cb2207b5b6c7ff | [
"MIT"
] | null | null | null | // Copyright (c) 2013-2015 mogemimi.
// Distributed under the MIT license. See LICENSE.md file for details.
#ifndef POMDOG_INPUTLAYOUTHELPER_A6C6ACE6_HPP
#define POMDOG_INPUTLAYOUTHELPER_A6C6ACE6_HPP
#include "detail/ForwardDeclarations.hpp"
#include "InputElementFormat.hpp"
#include "InputElement.hpp"
#include "InputLayoutDescription.hpp"
#include "Pomdog/Basic/Export.hpp"
#include <cstdint>
namespace Pomdog {
class POMDOG_EXPORT InputLayoutHelper final {
public:
InputLayoutHelper & PushBack(InputElementFormat format);
InputLayoutHelper & Byte4();
InputLayoutHelper & Float();
InputLayoutHelper & Float2();
InputLayoutHelper & Float3();
InputLayoutHelper & Float4();
InputLayoutHelper & Int4();
InputLayoutHelper & AddInputSlot();
InputLayoutHelper & AddInputSlot(InputClassification slotClass,
std::uint16_t instanceStepRate);
InputLayoutDescription CreateInputLayout();
private:
std::vector<InputElement> elements;
std::uint16_t inputSlot = 0;
std::uint16_t byteOffset = 0;
std::uint16_t instanceStepRate = 0;
InputClassification slotClass = InputClassification::InputPerVertex;
};
} // namespace Pomdog
#endif // POMDOG_INPUTLAYOUTHELPER_A6C6ACE6_HPP
| 24.9 | 72 | 0.759839 |
9a2fb48bc643b588adf33c4b65b984ac3fbbd498 | 7,800 | cpp | C++ | include/et/rendering/vulkan/vulkan_textureset.cpp | sergeyreznik/et-engine | a95fe4b9c5db0e873361f36908de284d0ae4b6d6 | [
"BSD-3-Clause"
] | 55 | 2015-01-13T22:50:36.000Z | 2022-02-26T01:55:02.000Z | include/et/rendering/vulkan/vulkan_textureset.cpp | sergeyreznik/et-engine | a95fe4b9c5db0e873361f36908de284d0ae4b6d6 | [
"BSD-3-Clause"
] | 4 | 2015-01-17T01:57:42.000Z | 2016-07-29T07:49:27.000Z | include/et/rendering/vulkan/vulkan_textureset.cpp | sergeyreznik/et-engine | a95fe4b9c5db0e873361f36908de284d0ae4b6d6 | [
"BSD-3-Clause"
] | 10 | 2015-01-17T18:46:44.000Z | 2021-05-21T09:19:13.000Z | /*
* This file is part of `et engine`
* Copyright 2009-2016 by Sergey Reznik
* Please, modify content only if you know what are you doing.
*
*/
#pragma once
#include <et/rendering/vulkan/vulkan_textureset.h>
#include <et/rendering/vulkan/vulkan_texture.h>
#include <et/rendering/vulkan/vulkan_sampler.h>
#include <et/rendering/vulkan/vulkan_renderer.h>
#include <et/rendering/vulkan/vulkan.h>
namespace et
{
class VulkanTextureSetPrivate : public VulkanNativeTextureSet
{
public:
VulkanTextureSetPrivate(VulkanState& v) :
vulkan(v) { }
VulkanState& vulkan;
};
VulkanTextureSet::VulkanTextureSet(VulkanRenderer* renderer, VulkanState& vulkan, const Description& desc)
{
ET_PIMPL_INIT(VulkanTextureSet, vulkan);
const uint32_t MaxObjectsCount = 32;
std::array<VkDescriptorSetLayoutBinding, MaxObjectsCount> texturesBindings = {};
std::array<VkWriteDescriptorSet, MaxObjectsCount> texturesWriteSet = {};
std::array<VkDescriptorImageInfo, MaxObjectsCount> texturesInfos = {};
std::array<VkDescriptorSetLayoutBinding, MaxObjectsCount> imagesBindings = {};
std::array<VkWriteDescriptorSet, MaxObjectsCount> imagesWriteSet = {};
std::array<VkDescriptorImageInfo, MaxObjectsCount> imagesInfos = {};
std::array<VkDescriptorSetLayoutBinding, MaxObjectsCount> samplersBindings = {};
std::array<VkWriteDescriptorSet, MaxObjectsCount> samplersWriteSet = {};
std::array<VkDescriptorImageInfo, MaxObjectsCount> samplersInfos = {};
bool allowEmptySet = false;
uint32_t texturesCount = 0;
uint32_t samplersCount = 0;
uint32_t imagesCount = 0;
for (const auto& entry : desc)
{
allowEmptySet |= entry.second.allowEmptySet;
VkShaderStageFlagBits stageFlags = vulkan::programStageValue(entry.first);
for (const auto& e : entry.second.textures)
{
VkDescriptorSetLayoutBinding& binding = texturesBindings[texturesCount];
binding.binding = e.first;
binding.descriptorCount = 1;
binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
binding.stageFlags = stageFlags;
VkDescriptorImageInfo& info = texturesInfos[texturesCount];
info.imageView = VulkanTexture::Pointer(e.second.image)->nativeTexture().imageView(e.second.range);
info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
VkWriteDescriptorSet& ws = texturesWriteSet[texturesCount];
ws.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
ws.descriptorCount = binding.descriptorCount;
ws.descriptorType = binding.descriptorType;
ws.dstBinding = binding.binding;
ws.pImageInfo = texturesInfos.data() + texturesCount;
++texturesCount;
ET_ASSERT(texturesCount < MaxObjectsCount);
}
for (const auto& e : entry.second.images)
{
VkDescriptorSetLayoutBinding& binding = imagesBindings[imagesCount];
binding.binding = e.first;
binding.descriptorCount = 1;
binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
binding.stageFlags = stageFlags;
// TODO : use range for images (instead of whole range)
VkDescriptorImageInfo& info = imagesInfos[imagesCount];
info.imageView = VulkanTexture::Pointer(e.second)->nativeTexture().imageView(ResourceRange::whole);
info.imageLayout = VK_IMAGE_LAYOUT_GENERAL;
VkWriteDescriptorSet& ws = imagesWriteSet[imagesCount];
ws.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
ws.descriptorCount = binding.descriptorCount;
ws.descriptorType = binding.descriptorType;
ws.dstBinding = binding.binding;
ws.pImageInfo = imagesInfos.data() + imagesCount;
++imagesCount;
ET_ASSERT(imagesCount < MaxObjectsCount);
}
for (const auto& e : entry.second.samplers)
{
VkDescriptorSetLayoutBinding& binding = samplersBindings[samplersCount];
binding.binding = e.first;
binding.descriptorCount = 1;
binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER;
binding.stageFlags = stageFlags;
VkDescriptorImageInfo& info = samplersInfos[samplersCount];
info.sampler = VulkanSampler::Pointer(e.second)->nativeSampler().sampler;
VkWriteDescriptorSet& ws = samplersWriteSet[samplersCount];
ws.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
ws.descriptorCount = binding.descriptorCount;
ws.descriptorType = binding.descriptorType;
ws.dstBinding = binding.binding;
ws.pImageInfo = samplersInfos.data() + samplersCount;
++samplersCount;
ET_ASSERT(samplersCount < MaxObjectsCount);
}
}
if ((imagesCount > 0) || allowEmptySet)
{
VkDescriptorSetLayoutCreateInfo createInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO };
createInfo.bindingCount = imagesCount;
createInfo.pBindings = imagesBindings.data();
VULKAN_CALL(vkCreateDescriptorSetLayout(vulkan.device, &createInfo, nullptr, &_private->imagesSetLayout));
VkDescriptorSetAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO };
allocInfo.descriptorPool = vulkan.descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &_private->imagesSetLayout;
VULKAN_CALL(vkAllocateDescriptorSets(vulkan.device, &allocInfo, &_private->imagesSet));
for (uint32_t i = 0; i < imagesCount; ++i)
imagesWriteSet[i].dstSet = _private->imagesSet;
vkUpdateDescriptorSets(vulkan.device, imagesCount, imagesWriteSet.data(), 0, nullptr);
}
if ((samplersCount > 0) || allowEmptySet)
{
VkDescriptorSetLayoutCreateInfo createInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO };
createInfo.bindingCount = samplersCount;
createInfo.pBindings = samplersBindings.data();
VULKAN_CALL(vkCreateDescriptorSetLayout(vulkan.device, &createInfo, nullptr, &_private->samplersSetLayout));
VkDescriptorSetAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO };
allocInfo.descriptorPool = vulkan.descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &_private->samplersSetLayout;
VULKAN_CALL(vkAllocateDescriptorSets(vulkan.device, &allocInfo, &_private->samplersSet));
for (uint32_t i = 0; i < samplersCount; ++i)
samplersWriteSet[i].dstSet = _private->samplersSet;
vkUpdateDescriptorSets(vulkan.device, samplersCount, samplersWriteSet.data(), 0, nullptr);
}
if ((texturesCount > 0) || allowEmptySet)
{
VkDescriptorSetLayoutCreateInfo createInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO };
createInfo.bindingCount = texturesCount;
createInfo.pBindings = texturesBindings.data();
VULKAN_CALL(vkCreateDescriptorSetLayout(vulkan.device, &createInfo, nullptr, &_private->texturesSetLayout));
VkDescriptorSetAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO };
allocInfo.descriptorPool = vulkan.descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &_private->texturesSetLayout;
VULKAN_CALL(vkAllocateDescriptorSets(vulkan.device, &allocInfo, &_private->texturesSet));
for (uint32_t i = 0; i < texturesCount; ++i)
texturesWriteSet[i].dstSet = _private->texturesSet;
vkUpdateDescriptorSets(vulkan.device, texturesCount, texturesWriteSet.data(), 0, nullptr);
}
}
VulkanTextureSet::~VulkanTextureSet()
{
VULKAN_CALL(vkFreeDescriptorSets(_private->vulkan.device, _private->vulkan.descriptorPool, 1, &_private->texturesSet));
vkDestroyDescriptorSetLayout(_private->vulkan.device, _private->texturesSetLayout, nullptr);
VULKAN_CALL(vkFreeDescriptorSets(_private->vulkan.device, _private->vulkan.descriptorPool, 1, &_private->samplersSet));
vkDestroyDescriptorSetLayout(_private->vulkan.device, _private->samplersSetLayout, nullptr);
VULKAN_CALL(vkFreeDescriptorSets(_private->vulkan.device, _private->vulkan.descriptorPool, 1, &_private->imagesSet));
vkDestroyDescriptorSetLayout(_private->vulkan.device, _private->imagesSetLayout, nullptr);
ET_PIMPL_FINALIZE(VulkanTextureSet);
}
const VulkanNativeTextureSet& VulkanTextureSet::nativeSet() const
{
return *(_private);
}
} | 38.613861 | 120 | 0.782821 |
9a317db3c774b45f8f4c3e1a3770092005b5f11b | 2,482 | cpp | C++ | lab_01/lab1_fixed.cpp | pwestrich/csc_2110 | ed56c0ccdc7aeb55e6f0711a958b8c1fff691bd5 | [
"MIT"
] | null | null | null | lab_01/lab1_fixed.cpp | pwestrich/csc_2110 | ed56c0ccdc7aeb55e6f0711a958b8c1fff691bd5 | [
"MIT"
] | null | null | null | lab_01/lab1_fixed.cpp | pwestrich/csc_2110 | ed56c0ccdc7aeb55e6f0711a958b8c1fff691bd5 | [
"MIT"
] | null | null | null | // -------------------------------------------------------
//
// lab1.cpp
//
// Program to read a 3 X 3 matrix of integers mat and an integer item, and
// search mat to see if it contains item.
//
// Add your name here and other info requested by your instructor.
//
// -------------------------------------------------------
#include <iostream>
const int SIZE = 3; // Set Matrix size
typedef int Matrix[SIZE][SIZE];
bool matrixSearch(Matrix &mat, int n, int item);
// -------------------------------------------------------
// Search the n X n matrix mat in row-wise order for item.
//
// Precondition:
// Matrix mat is an n X n matrix of integers with n > 0.
// Postcondition:
// True is returned if item is found in mat, else false.
// -------------------------------------------------------
int main()
{
Matrix mat;
// Enter the matrix Matrix mat;
std::cout << "Enter the elements of the " << SIZE << " X " <<
SIZE << " matrix row-wise:" << std::endl;
for (int i = 0; i < SIZE; i++)
for (int j = 0; j < SIZE; j++)
std::cin >> mat[i][j];
// Search mat for various items mt itemToFind;
char response;
int itemToFind;
do {
std::cout << "Enter integer to search for: ";
std::cin >> itemToFind;
if (matrixSearch(mat, SIZE, itemToFind))
std::cout << "item found" << std::endl;
else
std::cout << "item not found" << std::endl;
std::cout << std::endl << "More items to search for (Y or N)? ";
std::cin >> response;
} while (response == 'Y' || response == 'y');
}
//-- (-- Incorrect --) Definition of matrixSearch()
// -------------------------------------------------------
// Search the n X n matrix mat in row-wise order for item
//
// Precondition:
// Matrix mat is an n X n matrix of integers with n > 0.
//
// Postcondition:
// True is returned if item is found in mat, else false.
//
// NOTE:
// mat[row] [col] denotes the entry of the matrix in the
// (horizontal) row numbered row (counting from 0) and the
// (vertical) column numbered col.
// --------------------------------------------------------
bool matrixSearch(Matrix & mat, int n, int item)
{
bool found = false;
for (int row = 0; row < n; row++){
for (int col = 0; col < n; col++) {
if (mat[row][col] == item) {
found = true;
}
}
}
return found;
} | 30.641975 | 76 | 0.485093 |
9a37f162856d71c3c687204a72f279927840f9d2 | 9,499 | cxx | C++ | include/selfSphericalMapping.cxx | guangxv/RiemannMapping | 4b084aaa2c7b89909416b34dbd4c1c7eee79fc2d | [
"MIT"
] | null | null | null | include/selfSphericalMapping.cxx | guangxv/RiemannMapping | 4b084aaa2c7b89909416b34dbd4c1c7eee79fc2d | [
"MIT"
] | null | null | null | include/selfSphericalMapping.cxx | guangxv/RiemannMapping | 4b084aaa2c7b89909416b34dbd4c1c7eee79fc2d | [
"MIT"
] | 1 | 2019-09-11T09:29:38.000Z | 2019-09-11T09:29:38.000Z | /****************************************************************
*
*
*
*
*****************************************************************/
#ifndef _selfSphericalMapping_cxx
#define _selfSphericalMapping_cxx
#include <selfSphericalMapping.h>
#include <math.h>
namespace Self
{
SphericalMapping::SphericalMapping( MeshType& inputMesh )
{
m_mesh = inputMesh;
}
SphericalMapping::~SphericalMapping()
{
}
// Creat Spherical Coordinate System from Cartesian Coordinate
void
SphericalMapping::request_SphericalCoords()
{
m_mesh.add_property( SphericalCoordinates );
}
// Update Spherical Coordinate System from Cartesian Coordinate
void
SphericalMapping::update_SphericalCoords( ScalarType radius )
{
PointType vertex;
SpheriCoordType radian;
VertexIterType v_it( m_mesh.vertices_begin() ), v_end( m_mesh.vertices_end() );
while( v_it != v_end )
{
vertex = m_mesh.point( v_it );
// elevation: 0~PI
double temp = vertex[2] / radius;
if( temp >1 ) temp = 1; else if(temp < -1) temp = -1;
radian[0] = acos( temp );
// azimuth: 0~2PI
if( vertex[0] != 0 )
{
double x = vertex[0];
double y = vertex[1];
radian[1] = atan( y / x);
if(x < 0)
radian[1] += M_PI;
else if(radian[1] < 0)
radian[1] += M_PI * 2;
}
else
{
if(vertex[1] == 0)
{
radian[1] = 0;
}
else
{
if(vertex[1] > 0)
radian[1] = M_PI_2;
else
radian[1] = 3 * M_PI_2;
}
}
m_mesh.property( SphericalCoordinates,v_it ) = radian;
++v_it;
}
}
void
SphericalMapping::release_SphericalCoords()
{
m_mesh.remove_property( SphericalCoordinates );
}
// Creat Cartesian Coordinate from Spherical Coordinate System
void
SphericalMapping::update_CartesianCoords( ScalarType radius )
{
PointType vertex;
SpheriCoordType radian;
VertexIterType v_it( m_mesh.vertices_begin() ), v_end( m_mesh.vertices_end() );
while( v_it != v_end )
{
radian = m_mesh.property( SphericalCoordinates,v_it );
vertex[0] = (ScalarType)(radius * sin(radian[1]) * cos(radian[1]));
vertex[1] = (ScalarType)(radius * sin(radian[1]) * sin(radian[1]));
vertex[2] = (ScalarType)(radius * cos(radian[1]));
m_mesh.set_point( v_it, vertex );
++v_it;
}
}
// Get Spherical Coordinates
SphericalMapping::SpheriCoordType
SphericalMapping::getSphericalCoords( VertexIterType v_it )
{
return m_mesh.property( SphericalCoordinates,v_it );
}
SphericalMapping::SpheriCoordType
SphericalMapping::getSphericalCoords( VertexHandleType verhandle )
{
return m_mesh.property( SphericalCoordinates,verhandle );
}
// Stereographic Projection
// Get 2d stereographic projective coordinates from 3d spherical coordinates
SphericalMapping::SpheriCoordType
SphericalMapping::getStereoProj( PointType &vertex )
{
SpheriCoordType project;
if( vertex[2] != 1)
{
double tmp = 1 / ( 1 - vertex[2] );
project[0] = vertex[0] * tmp; // Real part
project[1] = vertex[1] * tmp; // Imaginary part
}
else
{
if( vertex[0] > 0) project[0] = 1.7e308;
else project[0] = -1.7e308;
if( vertex[1] > 0) project[1] = 1.7e308;
else project[1] = -1.7e308;
}
return project;
}
// Set 3d spherical coordinates to 2d stereographic projective coordinates
SphericalMapping::PointType
SphericalMapping::setStereoProj( SpheriCoordType &value )
{
PointType vertex;
double tmp = 1 / ( 1+ value[0] * value[0] + value[1] * value[1] );
vertex[0] = (float)(2 * value[0] * tmp);
vertex[1] = (float)(2 * value[1] * tmp);
vertex[2] = (float)(1 - 2 * tmp);
return vertex;
}
// Mobius Transformation
// Set 3 points, which are mapped to 0, 1, infinity seperately
void
SphericalMapping::setFixPoints( SpheriCoordType &zero,
SpheriCoordType &one, SpheriCoordType &infinity)
{
m_z0 = zero; m_z1 = one; m_z2 = infinity;
}
// Calculate the mobius after set the 3 fixed points
SphericalMapping::SpheriCoordType
SphericalMapping::mobiusTransFor3Fixs( SpheriCoordType &inputPoint )
{
SpheriCoordType tmp_z1,tmp_z2;
tmp_z1[0] = inputPoint[0] - m_z0[0]; tmp_z1[1] = inputPoint[1] - m_z0[1];
tmp_z2[0] = m_z1[0] - m_z2[0]; tmp_z2[1] = m_z1[1] - m_z2[1];
SpheriCoordType tmp0 = complexNumMulti(tmp_z1, tmp_z2);
tmp_z1[0] = inputPoint[0] - m_z2[0]; tmp_z1[1] = inputPoint[1] - m_z2[1];
tmp_z2[0] = m_z1[0] - m_z0[0]; tmp_z2[1] = m_z1[1] - m_z0[1];
SpheriCoordType tmp1 = complexNumMulti(tmp_z1, tmp_z2);
tmp0 = complexNumDivi(tmp0, tmp1);
return tmp0;
}
// 2d vector square root
SphericalMapping::SpheriCoordType
SphericalMapping::sqrtOfVector2D( SpheriCoordType &input )
{
double sqrtSum = sqrt(input[0] * input[0] + input[1] * input[1]);
SpheriCoordType result;
result[0] = sqrt(0.5 * (sqrtSum + input[0]));
result[1] = sqrt(0.5 * (sqrtSum - input[0]));
return result;
}
// Sort the vertices
bool
SphericalMapping::sortSpheriCoord()
{
MeshType::VertexIter v_it( m_mesh.vertices_begin() );
while( v_it != m_mesh.vertices_end() )
{
CoordinatesType tmp;
tmp.first = this->getSphericalCoords( v_it )[0];
tmp.second = this->getSphericalCoords( v_it )[1];
m_sortedVertices.push_back( std::make_pair(tmp, v_it.handle()) );
++v_it;
}
// sort the spherical coordinates
std::sort( m_sortedVertices.begin(), m_sortedVertices.end() );
return SUCCESS;
}
// Search for 2D nearest points
bool
SphericalMapping::searchVertices( std::vector< VertexHandleType > & filteredValue,
SpheriCoordType cntrValue, double recRange = 0.01 )
{
// Limite the search range to a rectangular from (value*0.99) to (value*1.01)
//// Limite the first coordinate
IndexDataType upperLeft, lowerRight;
upperLeft.first.first = cntrValue[0] - recRange;
upperLeft.first.second = cntrValue[1] - recRange;
std::vector< IndexDataType >::iterator upperLeftIter =
std::lower_bound( m_sortedVertices.begin(), m_sortedVertices.end(), upperLeft );
lowerRight.first.first = cntrValue[0] + recRange;
lowerRight.first.second = cntrValue[1] + recRange;
std::vector< IndexDataType >::iterator lowerRightIter =
std::upper_bound( upperLeftIter, m_sortedVertices.end(), lowerRight );
//// Limite the second coordinate
std::vector< IndexDataType >::iterator iter(upperLeftIter);
while( iter != lowerRightIter )
{
if( (iter->first).second >= upperLeft.first.second &&
(iter->first).second <= lowerRight.first.second )
{
filteredValue.push_back(iter->second);
}
++iter;
}
if(filteredValue.size())
return 1;
else
return 0;
}
// Search for 2D nearest points
SphericalMapping::VertexHandleType
SphericalMapping::searchNearestVertex( SpheriCoordType value, double recRange = 0.01 )
{
// Limite the search range to a rectangular from (value*0.99) to (value*1.01)
//// Limite the first coordinate
IndexDataType upperLeft, lowerRight;
upperLeft.first.first = value[0] - recRange;
upperLeft.first.second = value[1] - recRange;
std::vector< IndexDataType >::iterator upperLeftIter =
std::lower_bound( m_sortedVertices.begin(), m_sortedVertices.end(), upperLeft );
lowerRight.first.first = value[0] + recRange;
lowerRight.first.second = value[1] + recRange;
std::vector< IndexDataType >::iterator lowerRightIter =
std::upper_bound( upperLeftIter, m_sortedVertices.end(), lowerRight );
//// Limite the second coordinate
std::vector< IndexDataType > filteredValue;
std::vector< IndexDataType >::iterator iter(upperLeftIter);
while( iter != lowerRightIter)
{
if( (iter->first).second >= upperLeft.first.second &&
(iter->first).second <= lowerRight.first.second )
{
filteredValue.push_back(*iter);
}
++iter;
}
//std::cout << "Refer:" << referCoordinates[i].first << " " << referCoordinates[i].second << " " << std::endl;
//std::cout << "low:" << upperLeft.first.first << " " << upperLeft.first.second << " " << std::endl;
//std::cout << "up:" << lowerRight.first.first << " " << lowerRight.first.second << " " << std::endl;
double distanRef(65535);
VertexHandleType vhTmp;
std::vector< IndexDataType >::iterator it(upperLeftIter);
while( it != lowerRightIter )
{
double tmp0 = (it->first).first - value[0];
double tmp1 = (it->first).second - value[1];
double distanTmp(tmp0 * tmp0 + tmp1 * tmp1);
if( distanTmp < distanRef)
{
distanRef = distanTmp;
vhTmp = it->second;
}
++it;
}
return vhTmp;
}
/**********************************************************************/
//////////////////////// ComplexNumber Type class //////////////////////
/**********************************************************************/
SphericalMapping::SpheriCoordType
SphericalMapping::complexNumMulti( SpheriCoordType &a, SpheriCoordType &b)
{
SpheriCoordType result;
result[0] = a[0]*b[0] - a[1]*b[1];
result[1] = a[0]*b[1] + a[1]*b[0];
return result;
}
SphericalMapping::SpheriCoordType
SphericalMapping::complexNumDivi( SpheriCoordType &a, SpheriCoordType &b)
{
SpheriCoordType result;
if( b[0]*b[1] != 0)
{
double deno = 1 / (b[0] * b[0] + b[1] * b[1]);
result[0] = a[0]*b[0] + a[1]*b[1];
result[1] = a[1]*b[0] - a[0]*b[1];
result[0] *= deno;
result[1] *= deno;
}
else
{
if( a[0] > 0) result[0] = 1.7e308;
else result[0] = -1.7e308;
if( a[1] > 0) result[1] = 1.7e308;
else result[1] = -1.7e308;
}
return result;
}
}// end namespace
#endif
| 26.985795 | 111 | 0.640278 |
9a389690742920a2c94fc47c069346cc422bf1d7 | 4,502 | cpp | C++ | tests/manipulating_values.cpp | whiterabbit963/tomlplusplus | 6b8fa1bef546664b1031d4f0d32c77df5d8d94c1 | [
"MIT"
] | null | null | null | tests/manipulating_values.cpp | whiterabbit963/tomlplusplus | 6b8fa1bef546664b1031d4f0d32c77df5d8d94c1 | [
"MIT"
] | null | null | null | tests/manipulating_values.cpp | whiterabbit963/tomlplusplus | 6b8fa1bef546664b1031d4f0d32c77df5d8d94c1 | [
"MIT"
] | null | null | null | // This file is a part of toml++ and is subject to the the terms of the MIT license.
// Copyright (c) 2019-2020 Mark Gillard <mark.gillard@outlook.com.au>
// See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
// SPDX-License-Identifier: MIT
#include "tests.h"
#ifdef _WIN32
TOML_PUSH_WARNINGS
TOML_DISABLE_ALL_WARNINGS
#include <Windows.h>
TOML_POP_WARNINGS
#endif
// TOML_PUSH_WARNINGS
// TOML_DISABLE_ARITHMETIC_WARNINGS
template <typename T>
static constexpr T one = static_cast<T>(1);
TEST_CASE("values - construction")
{
#define CHECK_VALUE_INIT2(initializer, target_type, equiv) \
do { \
auto v = value{ initializer }; \
static_assert(std::is_same_v<decltype(v), value<target_type>>); \
CHECK(v == equiv); \
CHECK(equiv == v); \
CHECK(*v == equiv); \
CHECK(v.get() == equiv); \
} while (false)
#define CHECK_VALUE_INIT(initializer, target_type) \
CHECK_VALUE_INIT2(initializer, target_type, initializer)
CHECK_VALUE_INIT(one<signed char>, int64_t);
CHECK_VALUE_INIT(one<signed short>, int64_t);
CHECK_VALUE_INIT(one<signed int>, int64_t);
CHECK_VALUE_INIT(one<signed long>, int64_t);
CHECK_VALUE_INIT(one<signed long long>, int64_t);
CHECK_VALUE_INIT2(one<unsigned char>, int64_t, 1u);
CHECK_VALUE_INIT2(one<unsigned short>, int64_t, 1u);
CHECK_VALUE_INIT2(one<unsigned int>, int64_t, 1u);
CHECK_VALUE_INIT2(one<unsigned long>, int64_t, 1u);
CHECK_VALUE_INIT2(one<unsigned long long>, int64_t, 1u);
CHECK_VALUE_INIT(true, bool);
CHECK_VALUE_INIT(false, bool);
CHECK_VALUE_INIT("kek", std::string);
CHECK_VALUE_INIT("kek"s, std::string);
CHECK_VALUE_INIT("kek"sv, std::string);
CHECK_VALUE_INIT2("kek"sv.data(), std::string, "kek"sv);
#ifdef __cpp_lib_char8_t
CHECK_VALUE_INIT2(u8"kek", std::string, "kek"sv);
CHECK_VALUE_INIT2(u8"kek"s, std::string, "kek"sv);
CHECK_VALUE_INIT2(u8"kek"sv, std::string, "kek"sv);
CHECK_VALUE_INIT2(u8"kek"sv.data(), std::string, "kek"sv);
#endif
#ifdef _WIN32
CHECK_VALUE_INIT(one<BOOL>, int64_t);
CHECK_VALUE_INIT(one<SHORT>, int64_t);
CHECK_VALUE_INIT(one<INT>, int64_t);
CHECK_VALUE_INIT(one<LONG>, int64_t);
CHECK_VALUE_INIT(one<INT_PTR>, int64_t);
CHECK_VALUE_INIT(one<LONG_PTR>, int64_t);
CHECK_VALUE_INIT2(one<USHORT>, int64_t, 1u);
CHECK_VALUE_INIT2(one<UINT>, int64_t, 1u);
CHECK_VALUE_INIT2(one<ULONG>, int64_t, 1u);
CHECK_VALUE_INIT2(one<UINT_PTR>, int64_t, 1u);
CHECK_VALUE_INIT2(one<ULONG_PTR>, int64_t, 1u);
CHECK_VALUE_INIT2(one<WORD>, int64_t, 1u);
CHECK_VALUE_INIT2(one<DWORD>, int64_t, 1u);
CHECK_VALUE_INIT2(one<DWORD32>, int64_t, 1u);
CHECK_VALUE_INIT2(one<DWORD64>, int64_t, 1u);
CHECK_VALUE_INIT2(one<DWORDLONG>, int64_t, 1u);
#if TOML_WINDOWS_COMPAT
CHECK_VALUE_INIT2(L"kek", std::string, "kek"sv);
CHECK_VALUE_INIT2(L"kek"s, std::string, "kek"sv);
CHECK_VALUE_INIT2(L"kek"sv, std::string, "kek"sv);
CHECK_VALUE_INIT2(L"kek"sv.data(), std::string, "kek"sv);
#endif // TOML_WINDOWS_COMPAT
#endif
}
// TOML_POP_WARNINGS
TEST_CASE("values - printing")
{
static constexpr auto print_value = [](auto&& raw)
{
auto val = toml::value{ std::forward<decltype(raw)>(raw) };
std::stringstream ss;
ss << val;
return ss.str();
};
CHECK(print_value(1) == "1");
CHECK(print_value(1.0f) == "1.0");
CHECK(print_value(1.0) == "1.0");
CHECK(print_value(1.5f) == "1.5");
CHECK(print_value(1.5) == "1.5");
CHECK(print_value(10) == "10");
CHECK(print_value(10.0f) == "10.0");
CHECK(print_value(10.0) == "10.0");
CHECK(print_value(100) == "100");
CHECK(print_value(100.0f) == "100.0");
CHECK(print_value(100.0) == "100.0");
CHECK(print_value(1000) == "1000");
CHECK(print_value(1000.0f) == "1000.0");
CHECK(print_value(1000.0) == "1000.0");
CHECK(print_value(10000) == "10000");
CHECK(print_value(10000.0f) == "10000.0");
CHECK(print_value(10000.0) == "10000.0");
CHECK(print_value(std::numeric_limits<double>::infinity()) == "inf");
CHECK(print_value(-std::numeric_limits<double>::infinity()) == "-inf");
CHECK(print_value(std::numeric_limits<double>::quiet_NaN()) == "nan");
// only integers for large values;
// large floats might get output as scientific notation and that's fine
CHECK(print_value(10000000000) == "10000000000");
CHECK(print_value(100000000000000) == "100000000000000");
}
| 33.849624 | 92 | 0.683696 |
9a3ba4e009c36026703baa2c7cd1c15a6daabbd1 | 530 | cpp | C++ | uva/11889_0.cpp | larc/competitive_programming | deccd7152a14adf217c58546d1cf8ac6b45f1c52 | [
"MIT"
] | 1 | 2019-05-23T19:05:39.000Z | 2019-05-23T19:05:39.000Z | uva/11889_0.cpp | larc/oremor | deccd7152a14adf217c58546d1cf8ac6b45f1c52 | [
"MIT"
] | null | null | null | uva/11889_0.cpp | larc/oremor | deccd7152a14adf217c58546d1cf8ac6b45f1c52 | [
"MIT"
] | null | null | null | // 11889 - Benefit
#include <cstdio>
int gcd(const int & a, const int & b)
{
if(!b) return a;
return gcd(b, a % b);
}
// gcd and lcm solution
int main()
{
int a, b, c, n;
scanf("%d", &n);
while(n-- && scanf("%d %d", &a, &c))
{
if(c % a != 0) printf("NO SOLUTION\n");
else
{
b = c;
for(int i = 1; i * i <= c; ++i)
if(c % i == 0)
{
if(i < b && (a / gcd(a, i)) * i == c)
b = i;
if(c / i < b && a == gcd(a, c / i) * i)
b = c / i;
}
printf("%d\n", b);
}
}
return 0;
}
| 13.25 | 44 | 0.40566 |
9a3dc57ae50cc8948a2e03f3e3e135080d576bb3 | 1,410 | cpp | C++ | test/SliceTest.cpp | jerryzhenleicai/Streams | e699eb1767bc96a50098a148eafe4fc09a559d51 | [
"MIT"
] | 494 | 2015-01-06T14:56:51.000Z | 2022-01-31T23:09:30.000Z | test/SliceTest.cpp | jerryzhenleicai/Streams | e699eb1767bc96a50098a148eafe4fc09a559d51 | [
"MIT"
] | 9 | 2015-04-07T15:27:41.000Z | 2017-01-11T05:54:40.000Z | test/SliceTest.cpp | jerryzhenleicai/Streams | e699eb1767bc96a50098a148eafe4fc09a559d51 | [
"MIT"
] | 54 | 2018-07-06T02:09:27.000Z | 2021-11-10T08:42:50.000Z | #include <Stream.h>
#include <gmock/gmock.h>
using namespace testing;
using namespace stream;
using namespace stream::op;
TEST(SliceTest, Slice) {
EXPECT_THAT(MakeStream::range(0, 10) | slice(0, 5) | to_vector(),
ElementsAre(0, 1, 2, 3, 4));
EXPECT_THAT(MakeStream::range(0, 10) | slice(2, 8, 2) | to_vector(),
ElementsAre(2, 4, 6));
EXPECT_THAT(MakeStream::range(0, 10) | slice(1, 8, 2) | to_vector(),
ElementsAre(1, 3, 5, 7));
}
TEST(SliceTest, SliceToEnd) {
EXPECT_THAT(MakeStream::range(1, 11) | slice_to_end(5, 2) | to_vector(),
ElementsAre(6, 8, 10));
EXPECT_THAT(MakeStream::range(0, 5) | slice_to_end(7, 10) | to_vector(),
IsEmpty());
}
TEST(SliceTest, Skip) {
EXPECT_THAT(MakeStream::range(1, 8) | skip(3) | to_vector(),
ElementsAre(4, 5, 6, 7));
EXPECT_THAT(MakeStream::range(1, 5) | skip(10) | to_vector(),
IsEmpty());
EXPECT_THAT(MakeStream::empty<int>() | skip(5) | to_vector(),
IsEmpty());
}
TEST(SliceTest, Limit) {
EXPECT_THAT(MakeStream::counter(0) | limit(5) | to_vector(),
ElementsAre(0, 1, 2, 3, 4));
EXPECT_THAT(MakeStream::range(0, 3) | limit(5) | to_vector(),
ElementsAre(0, 1, 2));
EXPECT_THAT(MakeStream::empty<int>() | limit(20) | to_vector(),
IsEmpty());
}
| 33.571429 | 76 | 0.570922 |
9a3f18d4595fd1fa3a7f1e6b3ca075b5012eb67e | 1,810 | cc | C++ | ash/accelerators/accelerator_dispatcher_win.cc | gavinp/chromium | 681563ea0f892a051f4ef3d5e53438e0bb7d2261 | [
"BSD-3-Clause"
] | 1 | 2016-03-10T09:13:57.000Z | 2016-03-10T09:13:57.000Z | ash/accelerators/accelerator_dispatcher_win.cc | gavinp/chromium | 681563ea0f892a051f4ef3d5e53438e0bb7d2261 | [
"BSD-3-Clause"
] | 1 | 2022-03-13T08:39:05.000Z | 2022-03-13T08:39:05.000Z | ash/accelerators/accelerator_dispatcher_win.cc | gavinp/chromium | 681563ea0f892a051f4ef3d5e53438e0bb7d2261 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/accelerators/accelerator_dispatcher.h"
#include "ash/accelerators/accelerator_controller.h"
#include "ash/ime/event.h"
#include "ash/shell.h"
#include "ui/aura/env.h"
#include "ui/aura/event.h"
#include "ui/aura/root_window.h"
#include "ui/base/accelerators/accelerator.h"
#include "ui/base/events.h"
namespace ash {
namespace {
const int kModifierMask = (ui::EF_SHIFT_DOWN |
ui::EF_CONTROL_DOWN |
ui::EF_ALT_DOWN);
} // namespace
bool AcceleratorDispatcher::Dispatch(const MSG& msg) {
// TODO(oshima): Consolidate win and linux. http://crbug.com/116282
if (!associated_window_)
return false;
if (!ui::IsNoopEvent(msg) && !associated_window_->CanReceiveEvents())
return aura::Env::GetInstance()->GetDispatcher()->Dispatch(msg);
if (msg.message == WM_KEYDOWN || msg.message == WM_SYSKEYDOWN ||
msg.message == WM_KEYUP || msg.message == WM_SYSKEYUP) {
ash::AcceleratorController* accelerator_controller =
ash::Shell::GetInstance()->accelerator_controller();
if (accelerator_controller) {
ui::Accelerator accelerator(ui::KeyboardCodeFromNative(msg),
ui::EventFlagsFromNative(msg) & kModifierMask);
if (msg.message == WM_KEYUP || msg.message == WM_SYSKEYUP)
accelerator.set_type(ui::ET_KEY_RELEASED);
if (accelerator_controller->Process(accelerator))
return true;
accelerator.set_type(TranslatedKeyEvent(msg, false).type());
if (accelerator_controller->Process(accelerator))
return true;
}
}
return nested_dispatcher_->Dispatch(msg);
}
} // namespace ash
| 34.150943 | 73 | 0.69116 |
9a4001b994da872b3f169344c8f06a215cecc3ec | 1,058 | cpp | C++ | MovieRental/main.cpp | SonicYeager/CppPractice | 05b80ac918648ba733ec5fce969eac4b2ae79b58 | [
"MIT"
] | null | null | null | MovieRental/main.cpp | SonicYeager/CppPractice | 05b80ac918648ba733ec5fce969eac4b2ae79b58 | [
"MIT"
] | 9 | 2020-10-26T10:14:46.000Z | 2020-10-27T12:13:51.000Z | MovieRental/main.cpp | SonicYeager/CppPractice | 05b80ac918648ba733ec5fce969eac4b2ae79b58 | [
"MIT"
] | null | null | null | #include "Customer.h"
#include <iostream>
#include <sstream>
int main()
{
Customer paul("Paul"), jana("Jana");
paul.AddRental({{"Planet Erde", Movie::REGULAR}, 3});
paul.AddRental({{"Planet der Affen", Movie::NEW_RELEASE}, 5});
paul.AddRental({{"HowTo MAGIX", Movie::NEW_RELEASE}, 1});
jana.AddRental({{"Der kleine Zwerg", Movie::CHILDRENS}, 2});
jana.AddRental({{"Murx der Arzt", Movie::CHILDRENS}, 5});
std::ostringstream out;
out << paul.Statement() << '\n' << jana.Statement() << '\n';
const std::string expected = R"(Rental Record for Paul
Planet Erde 3.5
Planet der Affen 15
HowTo MAGIX 3
Amount owed is 21.5
You earned 4 frequent renter points
Rental Record for Jana
Der kleine Zwerg 1.5
Murx der Arzt 4.5
Amount owed is 6
You earned 2 frequent renter points
)";
const std::string actual = out.str();
if(actual != expected)
{
std::cout << "actual:\n" << actual << "\ndiffers from expected:\n" << expected;
}
else
{
std::cout << "programm runs fine\n";
}
system("pause");
return 0;
}
| 26.45 | 82 | 0.643667 |
9a422b4a5bfcbd31df6cd0e7cb09e588cd3e83cc | 8,902 | cpp | C++ | apps/ncv_benchmark_optimizers.cpp | 0x0all/nanocv | dc58dea6b4eb7be2089b168d39c2b02aa2730741 | [
"MIT"
] | null | null | null | apps/ncv_benchmark_optimizers.cpp | 0x0all/nanocv | dc58dea6b4eb7be2089b168d39c2b02aa2730741 | [
"MIT"
] | null | null | null | apps/ncv_benchmark_optimizers.cpp | 0x0all/nanocv | dc58dea6b4eb7be2089b168d39c2b02aa2730741 | [
"MIT"
] | 1 | 2018-08-02T02:41:37.000Z | 2018-08-02T02:41:37.000Z | #include "nanocv/timer.h"
#include "nanocv/logger.h"
#include "nanocv/minimize.h"
#include "nanocv/tabulator.h"
#include "nanocv/math/abs.hpp"
#include "nanocv/math/clamp.hpp"
#include "nanocv/math/stats.hpp"
#include "nanocv/math/random.hpp"
#include "nanocv/math/numeric.hpp"
#include "nanocv/math/epsilon.hpp"
#include "nanocv/thread/loopi.hpp"
#include "nanocv/functions/function_trid.h"
#include "nanocv/functions/function_beale.h"
#include "nanocv/functions/function_booth.h"
#include "nanocv/functions/function_sphere.h"
#include "nanocv/functions/function_matyas.h"
#include "nanocv/functions/function_powell.h"
#include "nanocv/functions/function_mccormick.h"
#include "nanocv/functions/function_himmelblau.h"
#include "nanocv/functions/function_rosenbrock.h"
#include "nanocv/functions/function_3hump_camel.h"
#include "nanocv/functions/function_sum_squares.h"
#include "nanocv/functions/function_dixon_price.h"
#include "nanocv/functions/function_goldstein_price.h"
#include "nanocv/functions/function_rotated_ellipsoid.h"
#include <map>
#include <tuple>
using namespace ncv;
const size_t trials = 1024;
struct optimizer_stat_t
{
stats_t<scalar_t> m_time;
stats_t<scalar_t> m_crits;
stats_t<scalar_t> m_fails;
stats_t<scalar_t> m_iters;
stats_t<scalar_t> m_fvals;
stats_t<scalar_t> m_grads;
};
std::map<string_t, optimizer_stat_t> optimizer_stats;
static void check_problem(
const string_t& problem_name,
const opt_opsize_t& fn_size, const opt_opfval_t& fn_fval, const opt_opgrad_t& fn_grad,
const std::vector<std::pair<vector_t, scalar_t>>&)
{
const size_t iterations = 1024;
const scalar_t epsilon = 1e-6;
const size_t dims = fn_size();
// generate fixed random trials
vectors_t x0s;
for (size_t t = 0; t < trials; t ++)
{
random_t<scalar_t> rgen(-1.0, +1.0);
vector_t x0(dims);
rgen(x0.data(), x0.data() + x0.size());
x0s.push_back(x0);
}
// optimizers to try
const auto optimizers =
{
// optim::batch_optimizer::GD,
// optim::batch_optimizer::CGD_CD,
// optim::batch_optimizer::CGD_DY,
// optim::batch_optimizer::CGD_FR,
// optim::batch_optimizer::CGD_HS,
// optim::batch_optimizer::CGD_LS,
// optim::batch_optimizer::CGD_DYCD,
optim::batch_optimizer::CGD_DYHS,
optim::batch_optimizer::CGD_PRP,
optim::batch_optimizer::CGD_N,
optim::batch_optimizer::LBFGS
};
const auto ls_initializers =
{
optim::ls_initializer::unit,
optim::ls_initializer::quadratic,
optim::ls_initializer::consistent
};
const auto ls_strategies =
{
optim::ls_strategy::backtrack_armijo,
optim::ls_strategy::backtrack_wolfe,
optim::ls_strategy::backtrack_strong_wolfe,
optim::ls_strategy::interpolation,
optim::ls_strategy::cg_descent
};
tabulator_t table(text::resize(problem_name, 32));
table.header() << "cost"
<< "time [us]"
<< "|grad|/|fval|"
<< "#fails"
<< "#iters"
<< "#fvals"
<< "#grads";
thread_pool_t pool;
thread_pool_t::mutex_t mutex;
for (optim::batch_optimizer optimizer : optimizers)
for (optim::ls_initializer ls_initializer : ls_initializers)
for (optim::ls_strategy ls_strategy : ls_strategies)
{
stats_t<scalar_t> times;
stats_t<scalar_t> crits;
stats_t<scalar_t> fails;
stats_t<scalar_t> iters;
stats_t<scalar_t> fvals;
stats_t<scalar_t> grads;
thread_loopi(trials, pool, [&] (size_t t)
{
const vector_t& x0 = x0s[t];
// check gradients
const opt_problem_t problem(fn_size, fn_fval, fn_grad);
if (problem.grad_accuracy(x0) > math::epsilon2<scalar_t>())
{
const thread_pool_t::lock_t lock(mutex);
log_error() << "invalid gradient for problem [" << problem_name << "]!";
}
// optimize
const ncv::timer_t timer;
const opt_state_t state = ncv::minimize(
fn_size, fn_fval, fn_grad, nullptr, nullptr, nullptr,
x0, optimizer, iterations, epsilon, ls_initializer, ls_strategy);
const scalar_t crit = state.convergence_criteria();
// update stats
const thread_pool_t::lock_t lock(mutex);
times(timer.microseconds());
crits(crit);
iters(state.n_iterations());
fvals(state.n_fval_calls());
grads(state.n_grad_calls());
fails(!state.converged(epsilon) ? 1.0 : 0.0);
});
// update per-problem table
const string_t name =
text::to_string(optimizer) + "[" +
text::to_string(ls_initializer) + "][" +
text::to_string(ls_strategy) + "]";
table.append(name)
<< static_cast<int>(fvals.sum() + 2 * grads.sum()) / trials
<< times.avg()
<< crits.avg()
<< static_cast<int>(fails.sum())
<< iters.avg()
<< fvals.avg()
<< grads.avg();
// update global statistics
optimizer_stat_t& stat = optimizer_stats[name];
stat.m_time(times.avg());
stat.m_crits(crits.avg());
stat.m_fails(fails.sum());
stat.m_iters(iters.avg());
stat.m_fvals(fvals.avg());
stat.m_grads(grads.avg());
}
// print stats
table.sort_as_number(2, tabulator_t::sorting::ascending);
table.print(std::cout);
}
static void check_problems(const std::vector<ncv::function_t>& funcs)
{
for (const ncv::function_t& func : funcs)
{
check_problem(func.m_name, func.m_opsize, func.m_opfval, func.m_opgrad, func.m_solutions);
}
}
int main(int, char* [])
{
using namespace ncv;
// check_problems(ncv::make_beale_funcs());
check_problems(ncv::make_booth_funcs());
check_problems(ncv::make_matyas_funcs());
check_problems(ncv::make_trid_funcs(128));
check_problems(ncv::make_sphere_funcs(128));
check_problems(ncv::make_powell_funcs(128));
check_problems(ncv::make_mccormick_funcs());
check_problems(ncv::make_himmelblau_funcs());
check_problems(ncv::make_rosenbrock_funcs(7));
check_problems(ncv::make_3hump_camel_funcs());
check_problems(ncv::make_dixon_price_funcs(128));
check_problems(ncv::make_sum_squares_funcs(128));
// check_problems(ncv::make_goldstein_price_funcs());
check_problems(ncv::make_rotated_ellipsoid_funcs(128));
// show global statistics
tabulator_t table(text::resize("optimizer", 32));
table.header() << "cost"
<< "time [us]"
<< "|grad|/|fval|"
<< "#fails"
<< "#iters"
<< "#fvals"
<< "#grads";
for (const auto& it : optimizer_stats)
{
const string_t& name = it.first;
const optimizer_stat_t& stat = it.second;
table.append(name) << static_cast<int>(stat.m_fvals.sum() + 2 * stat.m_grads.sum())
<< stat.m_time.sum()
<< stat.m_crits.avg()
<< static_cast<int>(stat.m_fails.sum())
<< stat.m_iters.sum()
<< stat.m_fvals.sum()
<< stat.m_grads.sum();
}
table.sort_as_number(2, tabulator_t::sorting::ascending);
table.print(std::cout);
// OK
log_info() << done;
return EXIT_SUCCESS;
}
| 36.040486 | 106 | 0.526174 |
9a44bd53683b19536e69b70574d6793589cbb5aa | 7,010 | cc | C++ | components/drive/search_metadata_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | components/drive/search_metadata_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | components/drive/search_metadata_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/drive/chromeos/search_metadata.h"
#include <stddef.h>
#include <stdint.h>
#include <memory>
#include <vector>
#include "base/i18n/string_search.h"
#include "base/strings/utf_string_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace drive {
namespace internal {
namespace {
// A simple wrapper for testing FindAndHighlightWrapper(). It just converts the
// query text parameter to FixedPatternStringSearchIgnoringCaseAndAccents.
bool FindAndHighlightWrapper(
const std::string& text,
const std::string& query_text,
std::string* highlighted_text) {
std::vector<std::unique_ptr<
base::i18n::FixedPatternStringSearchIgnoringCaseAndAccents>>
queries;
queries.push_back(std::make_unique<
base::i18n::FixedPatternStringSearchIgnoringCaseAndAccents>(
base::UTF8ToUTF16(query_text)));
return FindAndHighlight(text, queries, highlighted_text);
}
} // namespace
TEST(SearchMetadataSimpleTest, FindAndHighlight_ZeroMatches) {
std::string highlighted_text;
EXPECT_FALSE(FindAndHighlightWrapper("text", "query", &highlighted_text));
}
TEST(SearchMetadataSimpleTest, FindAndHighlight_EmptyText) {
std::string highlighted_text;
EXPECT_FALSE(FindAndHighlightWrapper("", "query", &highlighted_text));
}
TEST(SearchMetadataSimpleTest, FindAndHighlight_EmptyQuery) {
std::vector<std::unique_ptr<
base::i18n::FixedPatternStringSearchIgnoringCaseAndAccents>>
queries;
std::string highlighted_text;
EXPECT_TRUE(FindAndHighlight("hello", queries, &highlighted_text));
EXPECT_EQ("hello", highlighted_text);
}
TEST(SearchMetadataSimpleTest, FindAndHighlight_FullMatch) {
std::string highlighted_text;
EXPECT_TRUE(FindAndHighlightWrapper("hello", "hello", &highlighted_text));
EXPECT_EQ("<b>hello</b>", highlighted_text);
}
TEST(SearchMetadataSimpleTest, FindAndHighlight_StartWith) {
std::string highlighted_text;
EXPECT_TRUE(FindAndHighlightWrapper("hello, world", "hello",
&highlighted_text));
EXPECT_EQ("<b>hello</b>, world", highlighted_text);
}
TEST(SearchMetadataSimpleTest, FindAndHighlight_EndWith) {
std::string highlighted_text;
EXPECT_TRUE(FindAndHighlightWrapper("hello, world", "world",
&highlighted_text));
EXPECT_EQ("hello, <b>world</b>", highlighted_text);
}
TEST(SearchMetadataSimpleTest, FindAndHighlight_InTheMiddle) {
std::string highlighted_text;
EXPECT_TRUE(FindAndHighlightWrapper("yo hello, world", "hello",
&highlighted_text));
EXPECT_EQ("yo <b>hello</b>, world", highlighted_text);
}
TEST(SearchMetadataSimpleTest, FindAndHighlight_MultipeMatches) {
std::string highlighted_text;
EXPECT_TRUE(FindAndHighlightWrapper("yoyoyoyoy", "yoy", &highlighted_text));
// Only the first match is highlighted.
EXPECT_EQ("<b>yoy</b>oyoyoy", highlighted_text);
}
TEST(SearchMetadataSimpleTest, FindAndHighlight_IgnoreCase) {
std::string highlighted_text;
EXPECT_TRUE(FindAndHighlightWrapper("HeLLo", "hello", &highlighted_text));
EXPECT_EQ("<b>HeLLo</b>", highlighted_text);
}
TEST(SearchMetadataSimpleTest, FindAndHighlight_IgnoreCaseNonASCII) {
std::string highlighted_text;
// Case and accent ignorance in Greek. Find "socra" in "Socra'tes".
EXPECT_TRUE(FindAndHighlightWrapper(
"\xCE\xA3\xCF\x89\xCE\xBA\xCF\x81\xCE\xAC\xCF\x84\xCE\xB7\xCF\x82",
"\xCF\x83\xCF\x89\xCE\xBA\xCF\x81\xCE\xB1", &highlighted_text));
EXPECT_EQ(
"<b>\xCE\xA3\xCF\x89\xCE\xBA\xCF\x81\xCE\xAC</b>\xCF\x84\xCE\xB7\xCF\x82",
highlighted_text);
// In Japanese characters.
// Find Hiragana "pi" + "(small)ya" in Katakana "hi" + semi-voiced-mark + "ya"
EXPECT_TRUE(FindAndHighlightWrapper(
"\xE3\x81\xB2\xE3\x82\x9A\xE3\x82\x83\xE3\x83\xBC",
"\xE3\x83\x94\xE3\x83\xA4",
&highlighted_text));
EXPECT_EQ(
"<b>\xE3\x81\xB2\xE3\x82\x9A\xE3\x82\x83</b>\xE3\x83\xBC",
highlighted_text);
}
TEST(SearchMetadataSimpleTest, MultiTextBySingleQuery) {
std::vector<std::unique_ptr<
base::i18n::FixedPatternStringSearchIgnoringCaseAndAccents>>
queries;
queries.push_back(std::make_unique<
base::i18n::FixedPatternStringSearchIgnoringCaseAndAccents>(
u"hello"));
std::string highlighted_text;
EXPECT_TRUE(FindAndHighlight("hello", queries, &highlighted_text));
EXPECT_EQ("<b>hello</b>", highlighted_text);
EXPECT_FALSE(FindAndHighlight("goodbye", queries, &highlighted_text));
EXPECT_TRUE(FindAndHighlight("1hello2", queries, &highlighted_text));
EXPECT_EQ("1<b>hello</b>2", highlighted_text);
}
TEST(SearchMetadataSimpleTest, FindAndHighlight_MetaChars) {
std::string highlighted_text;
EXPECT_TRUE(FindAndHighlightWrapper("<hello>", "hello", &highlighted_text));
EXPECT_EQ("<<b>hello</b>>", highlighted_text);
}
TEST(SearchMetadataSimpleTest, FindAndHighlight_MoreMetaChars) {
std::string highlighted_text;
EXPECT_TRUE(FindAndHighlightWrapper("a&b&c&d", "b&c", &highlighted_text));
EXPECT_EQ("a&<b>b&c</b>&d", highlighted_text);
}
TEST(SearchMetadataSimpleTest, FindAndHighlight_SurrogatePair) {
std::string highlighted_text;
// \xF0\x9F\x98\x81 (U+1F601) is a surrogate pair for smile icon of emoji.
EXPECT_TRUE(FindAndHighlightWrapper("hi\xF0\x9F\x98\x81hello",
"i\xF0\x9F\x98\x81", &highlighted_text));
EXPECT_EQ("h<b>i\xF0\x9F\x98\x81</b>hello", highlighted_text);
}
TEST(SearchMetadataSimpleTest, FindAndHighlight_MultipleQueries) {
std::vector<std::unique_ptr<
base::i18n::FixedPatternStringSearchIgnoringCaseAndAccents>>
queries;
queries.push_back(std::make_unique<
base::i18n::FixedPatternStringSearchIgnoringCaseAndAccents>(
u"hello"));
queries.push_back(
std::make_unique<
base::i18n::FixedPatternStringSearchIgnoringCaseAndAccents>(u"good"));
std::string highlighted_text;
EXPECT_TRUE(
FindAndHighlight("good morning, hello", queries, &highlighted_text));
EXPECT_EQ("<b>good</b> morning, <b>hello</b>", highlighted_text);
}
TEST(SearchMetadataSimpleTest, FindAndHighlight_OverlappingHighlights) {
std::vector<std::unique_ptr<
base::i18n::FixedPatternStringSearchIgnoringCaseAndAccents>>
queries;
queries.push_back(std::make_unique<
base::i18n::FixedPatternStringSearchIgnoringCaseAndAccents>(
u"morning"));
queries.push_back(
std::make_unique<
base::i18n::FixedPatternStringSearchIgnoringCaseAndAccents>(u"ing,"));
std::string highlighted_text;
EXPECT_TRUE(
FindAndHighlight("good morning, hello", queries, &highlighted_text));
EXPECT_EQ("good <b>morning,</b> hello", highlighted_text);
}
} // namespace internal
} // namespace drive
| 36.321244 | 80 | 0.727817 |
9a487b9a7ccac9f34b2618dcad4491cc3fcc14ec | 5,047 | cpp | C++ | ares/fc/cartridge/board/konami-vrc2.cpp | moon-chilled/Ares | 909fb098c292f8336d0502dc677050312d8b5c81 | [
"0BSD"
] | 7 | 2020-07-25T11:44:39.000Z | 2021-01-29T13:21:31.000Z | ares/fc/cartridge/board/konami-vrc2.cpp | jchw-forks/ares | d78298a1e95fd0ce65feabfd4f13b60e31210a7a | [
"0BSD"
] | null | null | null | ares/fc/cartridge/board/konami-vrc2.cpp | jchw-forks/ares | d78298a1e95fd0ce65feabfd4f13b60e31210a7a | [
"0BSD"
] | 1 | 2021-03-22T16:15:30.000Z | 2021-03-22T16:15:30.000Z | struct KonamiVRC2 : Interface {
Memory::Readable<uint8> programROM;
Memory::Writable<uint8> programRAM;
Memory::Readable<uint8> characterROM;
Memory::Writable<uint8> characterRAM;
using Interface::Interface;
auto load(Markup::Node document) -> void override {
auto board = document["game/board"];
Interface::load(programROM, board["memory(type=ROM,content=Program)"]);
Interface::load(programRAM, board["memory(type=RAM,content=Save)"]);
Interface::load(characterROM, board["memory(type=ROM,content=Character)"]);
Interface::load(characterRAM, board["memory(type=RAM,content=Character)"]);
pinA0 = 1 << board["chip(type=VRC2)/pinout/a0"].natural();
pinA1 = 1 << board["chip(type=VRC2)/pinout/a1"].natural();
}
auto save(Markup::Node document) -> void override {
auto board = document["game/board"];
Interface::save(programRAM, board["memory(type=RAM,content=Save)"]);
Interface::save(characterRAM, board["memory(type=RAM,content=Character)"]);
}
auto readPRG(uint address) -> uint8 {
if(address < 0x6000) return cpu.mdr();
if(address < 0x8000) {
if(!programRAM && (address & 0xf000) == 0x6000) return cpu.mdr() | latch;
if(!programRAM) return cpu.mdr();
return programRAM.read((uint13)address);
}
uint5 bank, banks = programROM.size() >> 13;
switch(address & 0xe000) {
case 0x8000: bank = programBank[0]; break;
case 0xa000: bank = programBank[1]; break;
case 0xc000: bank = banks - 2; break;
case 0xe000: bank = banks - 1; break;
}
address = bank << 13 | (uint13)address;
return programROM.read(address);
}
auto writePRG(uint address, uint8 data) -> void {
if(address < 0x6000) return;
if(address < 0x8000) {
if(!programRAM && (address & 0xf000) == 0x6000) latch = data.bit(0);
if(!programRAM) return;
return programRAM.write((uint13)address, data);
}
bool a0 = address & pinA0;
bool a1 = address & pinA1;
address &= 0xf000;
address |= a0 << 0 | a1 << 1;
switch(address) {
case 0x8000: case 0x8001: case 0x8002: case 0x8003:
programBank[0] = data.bit(0,4);
break;
case 0x9000: case 0x9001: case 0x9002: case 0x9003:
mirror = data.bit(0,1);
break;
case 0xa000: case 0xa001: case 0xa002: case 0xa003:
programBank[1] = data.bit(0,4);
break;
case 0xb000: characterBank[0].bit(0,3) = data.bit(0,3); break;
case 0xb001: characterBank[0].bit(4,7) = data.bit(0,3); break;
case 0xb002: characterBank[1].bit(0,3) = data.bit(0,3); break;
case 0xb003: characterBank[1].bit(4,7) = data.bit(0,3); break;
case 0xc000: characterBank[2].bit(0,3) = data.bit(0,3); break;
case 0xc001: characterBank[2].bit(4,7) = data.bit(0,3); break;
case 0xc002: characterBank[3].bit(0,3) = data.bit(0,3); break;
case 0xc003: characterBank[3].bit(4,7) = data.bit(0,3); break;
case 0xd000: characterBank[4].bit(0,3) = data.bit(0,3); break;
case 0xd001: characterBank[4].bit(4,7) = data.bit(0,3); break;
case 0xd002: characterBank[5].bit(0,3) = data.bit(0,3); break;
case 0xd003: characterBank[5].bit(4,7) = data.bit(0,3); break;
case 0xe000: characterBank[6].bit(0,3) = data.bit(0,3); break;
case 0xe001: characterBank[6].bit(4,7) = data.bit(0,3); break;
case 0xe002: characterBank[7].bit(0,3) = data.bit(0,3); break;
case 0xe003: characterBank[7].bit(4,7) = data.bit(0,3); break;
}
}
auto addressCIRAM(uint address) const -> uint {
switch(mirror) {
case 0: return address >> 0 & 0x0400 | address & 0x03ff; //vertical mirroring
case 1: return address >> 1 & 0x0400 | address & 0x03ff; //horizontal mirroring
case 2: return 0x0000 | address & 0x03ff; //one-screen mirroring (first)
case 3: return 0x0400 | address & 0x03ff; //one-screen mirroring (second)
}
unreachable;
}
auto addressCHR(uint address) const -> uint {
uint8 bank = characterBank[address >> 10];
return bank << 10 | (uint10)address;
}
auto readCHR(uint address) -> uint8 {
if(address & 0x2000) return ppu.readCIRAM(addressCIRAM(address));
if(characterROM) return characterROM.read(addressCHR(address));
if(characterRAM) return characterRAM.read(addressCHR(address));
return 0x00;
}
auto writeCHR(uint address, uint8 data) -> void {
if(address & 0x2000) return ppu.writeCIRAM(addressCIRAM(address), data);
if(characterRAM) return characterRAM.write(addressCHR(address), data);
}
auto power() -> void {
for(auto& bank : programBank) bank = 0;
for(auto& bank : characterBank) bank = 0;
mirror = 0;
latch = 0;
}
auto serialize(serializer& s) -> void {
programRAM.serialize(s);
characterRAM.serialize(s);
s.integer(pinA0);
s.integer(pinA1);
s.array(programBank);
s.array(characterBank);
s.integer(mirror);
s.integer(latch);
}
uint8 pinA0;
uint8 pinA1;
uint5 programBank[2];
uint8 characterBank[8];
uint2 mirror;
uint1 latch;
};
| 36.05 | 93 | 0.644938 |
9a487e6564783f51cf469c2a1abd163251228c67 | 8,829 | cpp | C++ | QuantLib-Ext/qlext/termstructures/yield/ratehelpers.cpp | ChinaQuants/qlengine | 6f40f8204df9b5c46eec6c6bb5cae6cde9b1455d | [
"BSD-3-Clause"
] | 17 | 2017-09-24T13:25:43.000Z | 2021-08-31T13:14:45.000Z | QuantLib-Ext/qlext/termstructures/yield/ratehelpers.cpp | Bralzer/ExoticOptionPriceEngine | 55650eee29b054b2e3d5083eb42a81419960901f | [
"BSD-3-Clause"
] | null | null | null | QuantLib-Ext/qlext/termstructures/yield/ratehelpers.cpp | Bralzer/ExoticOptionPriceEngine | 55650eee29b054b2e3d5083eb42a81419960901f | [
"BSD-3-Clause"
] | 6 | 2017-09-25T01:29:35.000Z | 2021-09-01T05:14:17.000Z | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2017 Cheng Li
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
#include <boost/make_shared.hpp>
#include <ql/cashflows/iborcoupon.hpp>
#include <ql/indexes/ibor/shibor.hpp>
#include <ql/pricingengines/swap/discountingswapengine.hpp>
#include <ql/time/calendars/china.hpp>
#include <ql/utilities/null_deleter.hpp>
#include <qlext/instruments/shiborswap.hpp>
#include <qlext/instruments/subperiodsswap.hpp>
#include <qlext/termstructures/yield/ratehelpers.hpp>
namespace QuantLib {
ShiborSwapRateHelper::ShiborSwapRateHelper(const Handle<Quote>& rate, const Period& swapTenor, Frequency fixedFreq,
const boost::shared_ptr<Shibor>& shiborIndex, const Period& fwdStart,
const Handle<YieldTermStructure>& discountingCurve)
: RelativeDateRateHelper(rate), tenor_(swapTenor), fixedFrequency_(fixedFreq), fwdStart_(fwdStart),
discountHandle_(discountingCurve) {
settlementDays_ = shiborIndex->fixingDays();
shiborIndex_ = boost::dynamic_pointer_cast<Shibor>(shiborIndex->clone(termStructureHandle_));
shiborIndex_->unregisterWith(termStructureHandle_);
registerWith(shiborIndex_);
registerWith(discountHandle_);
initializeDates();
}
void ShiborSwapRateHelper::initializeDates() {
Date refDate = Settings::instance().evaluationDate();
China floatCalendar(China::IB);
refDate = floatCalendar.adjust(refDate);
Date spotDate = floatCalendar.advance(refDate, settlementDays_ * Days);
Date startDate = spotDate + fwdStart_;
if (fwdStart_.length() < 0)
startDate = floatCalendar.adjust(startDate, Preceding);
else
startDate = floatCalendar.adjust(startDate, Following);
swap_ = boost::make_shared<ShiborSwap>(VanillaSwap::Payer, 1., startDate, tenor_, Period(fixedFrequency_), 0.,
shiborIndex_);
bool includeSettlementDateFlows = false;
boost::shared_ptr<PricingEngine> engine(
new DiscountingSwapEngine(discountRelinkableHandle_, includeSettlementDateFlows));
swap_->setPricingEngine(engine);
earliestDate_ = swap_->startDate();
maturityDate_ = swap_->maturityDate();
boost::shared_ptr<IborCoupon> lastCoupon = boost::dynamic_pointer_cast<IborCoupon>(swap_->floatingLeg().back());
latestRelevantDate_ = std::max(maturityDate_, lastCoupon->fixingEndDate());
latestDate_ = maturityDate_;
}
void ShiborSwapRateHelper::accept(AcyclicVisitor& v) {
Visitor<ShiborSwapRateHelper>* v1 = dynamic_cast<Visitor<ShiborSwapRateHelper>*>(&v);
if (v1 != 0)
v1->visit(*this);
else
RateHelper::accept(v);
}
Real ShiborSwapRateHelper::impliedQuote() const {
QL_REQUIRE(termStructure_ != 0, "term structure not set");
// we didn't register as observers - force calculation
swap_->recalculate();
// weak implementation... to be improved
static const Spread basisPoint = 1.0e-4;
Real floatingLegNPV = swap_->floatingLegNPV();
Real totNPV = -floatingLegNPV;
Real result = totNPV / (swap_->fixedLegBPS() / basisPoint);
return result;
}
void ShiborSwapRateHelper::setTermStructure(YieldTermStructure* t) {
// do not set the relinkable handle as an observer -
// force recalculation when needed---the index is not lazy
bool observer = false;
boost::shared_ptr<YieldTermStructure> temp(t, null_deleter());
termStructureHandle_.linkTo(temp, observer);
if (discountHandle_.empty())
discountRelinkableHandle_.linkTo(temp, observer);
else
discountRelinkableHandle_.linkTo(*discountHandle_, observer);
RelativeDateRateHelper::setTermStructure(t);
}
SubPeriodsSwapRateHelper::SubPeriodsSwapRateHelper(
const Handle<Quote>& rate, const Period& swapTenor, Frequency fixedFreq, const Calendar& fixedCalendar,
const DayCounter& fixedDayCount, BusinessDayConvention fixedConvention, const Period& floatPayTenor,
const boost::shared_ptr<IborIndex>& iborIndex, const DayCounter& floatingDayCount, DateGeneration::Rule rule,
Ext::SubPeriodsCoupon::Type type, const Period& fwdStart, const Handle<YieldTermStructure>& discountingCurve)
: RelativeDateRateHelper(rate), tenor_(swapTenor), fixedFrequency_(fixedFreq), fixedCalendar_(fixedCalendar),
fixedDayCount_(fixedDayCount), fixedConvention_(fixedConvention), floatPayTenor_(floatPayTenor),
floatingDayCount_(floatingDayCount), rule_(rule), type_(type), fwdStart_(fwdStart),
discountHandle_(discountingCurve) {
settlementDays_ = iborIndex->fixingDays();
iborIndex_ = boost::dynamic_pointer_cast<IborIndex>(iborIndex->clone(termStructureHandle_));
iborIndex_->unregisterWith(termStructureHandle_);
registerWith(iborIndex_);
registerWith(discountHandle_);
initializeDates();
}
void SubPeriodsSwapRateHelper::initializeDates() {
Date refDate = Settings::instance().evaluationDate();
Calendar floatCalendar = iborIndex_->fixingCalendar();
refDate = floatCalendar.adjust(refDate);
Date spotDate = floatCalendar.advance(refDate, settlementDays_ * Days);
Date startDate = spotDate + fwdStart_;
if (fwdStart_.length() < 0)
startDate = floatCalendar.adjust(startDate, Preceding);
else
startDate = floatCalendar.adjust(startDate, Following);
swap_ = boost::shared_ptr<SubPeriodsSwap>(new SubPeriodsSwap(startDate, 1., tenor_, true, Period(fixedFrequency_), 0.,
fixedCalendar_, fixedDayCount_, fixedConvention_, floatPayTenor_,
iborIndex_, floatingDayCount_, rule_, type_));
bool includeSettlementDateFlows = false;
boost::shared_ptr<PricingEngine> engine(
new DiscountingSwapEngine(discountRelinkableHandle_, includeSettlementDateFlows));
swap_->setPricingEngine(engine);
earliestDate_ = swap_->startDate();
maturityDate_ = swap_->maturityDate();
Leg floatLeg = swap_->floatLeg();
boost::shared_ptr<Ext::SubPeriodsCoupon> lastCoupon =
boost::dynamic_pointer_cast<Ext::SubPeriodsCoupon>(floatLeg[floatLeg.size() - 1]);
latestRelevantDate_ = std::max(latestDate_, lastCoupon->latestRelevantDate());
latestDate_ = maturityDate_;
}
void SubPeriodsSwapRateHelper::accept(AcyclicVisitor& v) {
Visitor<SubPeriodsSwapRateHelper>* v1 = dynamic_cast<Visitor<SubPeriodsSwapRateHelper>*>(&v);
if (v1 != 0)
v1->visit(*this);
else
RateHelper::accept(v);
}
Real SubPeriodsSwapRateHelper::impliedQuote() const {
QL_REQUIRE(termStructure_ != 0, "term structure not set");
// we didn't register as observers - force calculation
swap_->recalculate();
// weak implementation... to be improved
static const Spread basisPoint = 1.0e-4;
Real floatingLegNPV = swap_->floatLegNPV();
Real totNPV = -floatingLegNPV;
Real result = totNPV / (swap_->fixedLegBPS() / basisPoint);
return result;
}
void SubPeriodsSwapRateHelper::setTermStructure(YieldTermStructure* t) {
// do not set the relinkable handle as an observer -
// force recalculation when needed---the index is not lazy
bool observer = false;
boost::shared_ptr<YieldTermStructure> temp(t, null_deleter());
termStructureHandle_.linkTo(temp, observer);
if (discountHandle_.empty())
discountRelinkableHandle_.linkTo(temp, observer);
else
discountRelinkableHandle_.linkTo(*discountHandle_, observer);
RelativeDateRateHelper::setTermStructure(t);
}
} // namespace QuantLib
| 42.859223 | 126 | 0.680372 |
9a4d816ed7e9a880ed798674b6969d2a8b5aa9a7 | 4,079 | cpp | C++ | user/tests/wiring/no_fixture/system.cpp | zsoltmazlo/indoor-controller2 | 5fde9f40b30d087af03f6cccdb97821719941955 | [
"MIT"
] | 1 | 2019-02-24T07:13:51.000Z | 2019-02-24T07:13:51.000Z | user/tests/wiring/no_fixture/system.cpp | zsoltmazlo/indoor-controller2 | 5fde9f40b30d087af03f6cccdb97821719941955 | [
"MIT"
] | 1 | 2018-05-29T19:27:53.000Z | 2018-05-29T19:27:53.000Z | user/tests/wiring/no_fixture/system.cpp | zsoltmazlo/indoor-controller2 | 5fde9f40b30d087af03f6cccdb97821719941955 | [
"MIT"
] | null | null | null |
#include "application.h"
#include "unit-test/unit-test.h"
#if PLATFORM_ID >= 3
test(SYSTEM_01_freeMemory)
{
// this test didn't work on the core attempting to allocate the current value of
// freeMemory(), presumably because of fragmented heap from
// relatively large allocations during the handshake, so the request was satisfied
// without calling _sbrk()
// 4096 was chosen to be small enough to allocate, but large enough to force _sbrk() to be called.)
uint32_t free1 = System.freeMemory();
if (free1>128) {
void* m1 = malloc(1024*6);
uint32_t free2 = System.freeMemory();
free(m1);
assertLess(free2, free1);
}
}
#endif
test(SYSTEM_02_version)
{
uint32_t versionNumber = System.versionNumber();
// Serial.println(System.versionNumber()); // 328193 -> 0x00050201
// Serial.println(System.version().c_str()); // 0.5.2-rc.1
char expected[20];
if (SYSTEM_VERSION & 0xFF)
sprintf(expected, "%d.%d.%d-rc.%d", (int)BYTE_N(versionNumber,3), (int)BYTE_N(versionNumber,2), (int)BYTE_N(versionNumber,1), (int)BYTE_N(versionNumber,0));
else
sprintf(expected, "%d.%d.%d", (int)BYTE_N(versionNumber,3), (int)BYTE_N(versionNumber,2), (int)BYTE_N(versionNumber,1));
assertTrue(strcmp(expected,System.version().c_str())==0);
}
// todo - use platform feature flags
#if defined(STM32F2XX)
// subtract 4 bytes for signature (3068 bytes)
#define USER_BACKUP_RAM ((1024*3)-4)
#endif // defined(STM32F2XX)
#if defined(USER_BACKUP_RAM)
STARTUP(System.enableFeature(FEATURE_RETAINED_MEMORY));
static retained uint8_t app_backup[USER_BACKUP_RAM];
static uint8_t app_ram[USER_BACKUP_RAM];
test(SYSTEM_03_user_backup_ram)
{
int total_backup = 0;
int total_ram = 0;
for (unsigned i=0; i<(sizeof(app_backup)/sizeof(app_backup[0])); i++) {
app_backup[i] = 1;
app_ram[i] = 1;
total_backup += app_backup[i];
total_ram += app_ram[i];
}
// Serial.printlnf("app_backup(0x%x), app_ram(0x%x)", &app_backup, &app_ram);
// Serial.printlnf("total_backup: %d, total_ram: %d", total_backup, total_ram);
assertTrue(total_backup==(USER_BACKUP_RAM));
assertTrue(total_ram==(USER_BACKUP_RAM));
if (int(&app_backup) < 0x40024000) {
Serial.printlnf("ERROR: expected app_backup in user backup memory, but was at %x", &app_backup);
}
assertTrue(int(&app_backup)>=0x40024000);
if (int(&app_ram) >= 0x40024000) {
Serial.printlnf("ERROR: expected app_ram in user sram memory, but was at %x", &app_ram);
}
assertTrue(int(&app_ram)<0x40024000);
}
#endif // defined(USER_BACKUP_RAM)
#if defined(BUTTON1_MIRROR_SUPPORTED)
static int s_button_clicks = 0;
static void onButtonClick(system_event_t ev, int data) {
s_button_clicks = data;
}
test(SYSTEM_04_button_mirror)
{
// Known bug:
// events posted from an ISR might not be delivered to the application queue
// when threading is enabled
if (system_thread_get_state(nullptr) == spark::feature::ENABLED) {
skip();
return;
}
System.buttonMirror(D1, FALLING, false);
auto pinmap = HAL_Pin_Map();
System.on(button_click, onButtonClick);
// "Click" setup button 3 times
// First click
pinMode(D1, INPUT_PULLDOWN);
// Just in case manually trigger EXTI interrupt
EXTI_GenerateSWInterrupt(pinmap[D1].gpio_pin);
delay(300);
pinMode(D1, INPUT_PULLUP);
delay(100);
// Second click
pinMode(D1, INPUT_PULLDOWN);
// Just in case manually trigger EXTI interrupt
EXTI_GenerateSWInterrupt(pinmap[D1].gpio_pin);
delay(300);
pinMode(D1, INPUT_PULLUP);
delay(100);
// Third click
pinMode(D1, INPUT_PULLDOWN);
// Just in case manually trigger EXTI interrupt
EXTI_GenerateSWInterrupt(pinmap[D1].gpio_pin);
delay(300);
pinMode(D1, INPUT_PULLUP);
delay(300);
assertEqual(s_button_clicks, 3);
}
test(SYSTEM_05_button_mirror_disable)
{
System.disableButtonMirror(false);
}
#endif // defined(BUTTON1_MIRROR_SUPPORTED) | 31.137405 | 164 | 0.683256 |
9a51c4f477a971b0aac14e517d23c8ae2cd5a1a5 | 6,234 | hpp | C++ | ModelData/InstableCPUcoreOperationDetection.hpp | st-gb/CPUinfoAndControl | 5e93d4a195b4692d147bb05cfef534e38d7f8b64 | [
"MIT"
] | null | null | null | ModelData/InstableCPUcoreOperationDetection.hpp | st-gb/CPUinfoAndControl | 5e93d4a195b4692d147bb05cfef534e38d7f8b64 | [
"MIT"
] | null | null | null | ModelData/InstableCPUcoreOperationDetection.hpp | st-gb/CPUinfoAndControl | 5e93d4a195b4692d147bb05cfef534e38d7f8b64 | [
"MIT"
] | 1 | 2021-07-16T21:01:26.000Z | 2021-07-16T21:01:26.000Z | /*
* InstableCPUcoreOperationDetection.hpp
*
* Created on: 22.04.2012
* Author: Stefan
*/
#ifndef INSTABLECPUCOREVOLTAGEDETECTION_HPP_
#define INSTABLECPUCOREVOLTAGEDETECTION_HPP_
//#include "VoltageAndFreq.hpp" //class VoltageAndFreq
#include <Controller/multithread/thread_type.hpp>
//THREAD_PROC_CALLING_CONVENTION
#include <preprocessor_macros/thread_proc_calling_convention.h>
#include <preprocessor_macros/logging_preprocessor_macros.h>
//struct external_caller, StartInstableVoltageDetectionFunctionPointer,
// StopInstableVoltageDetectionFunctionPointer
#include <InstableCPUcoreVoltageDefintions.h>
#include <UserInterface/UserInterface.hpp>
#include <Controller/multithread/condition_type.hpp>
//#include ""
//Forward decl.
class CPUcoreData;
class I_CPUcontroller;
/** Used for displaying the progress of finding the lowest voltage for an
* instable CPU operation detection status in GUI. */
struct InstableCPUoperationDetectionData
{
//protected:
public:
unsigned m_secondsUntilCPUcoreVoltageDecrease;
float m_fCPUcoreUsageOfDynLibThread;
};
class wxX86InfoAndControlApp;
class InstableCPUcoreOperationDetection
: public InstableCPUoperationDetectionData
{
public:
/** Set to true if executable was called by instable CPU core op detection dyn lib */
volatile bool m_bVoltageWasTooLowCalled;
volatile bool m_bStopFindingLowestStableCPUcoreVoltageRequestedViaUI;
//Is set to true when "VoltageTooLow" was called.
volatile bool m_vbExitFindLowestStableVoltage;
static InstableCPUcoreOperationDetection * s_p_instableCPUcoreOperationDetection;
uint32_t m_ui32CPUcoreMask;
CPUcoreData & m_r_cpucoredata;
I_CPUcontroller * m_p_cpucontroller;
// float m_fCPUcoreUsageOfDynLibThread;
/** Use unsigned datatype because same bit width as CPU arch.->fast. */
unsigned m_secondsUntilVoltageDecrease;
unsigned m_milliSecondsToWaitBeforeSecondsCountDown;
#ifdef _WIN32
//TODO replace with wxDynLib
typedef HMODULE dynlibType;
#else
typedef int dynlibType;
#endif
typedef wxX86InfoAndControlApp userinterface_type;
//UserInterface * m_p_userinterface;
userinterface_type * m_p_userinterface;
dynlibType m_hmoduleUnstableVoltageDetectionDynLib;
StartInstableVoltageDetectionFunctionPointer
m_pfnStartInstableCPUcoreVoltageDetection;
StopInstableVoltageDetectionFunctionPointer
m_pfnStopInstableCPUcoreVoltageDetection;
struct external_caller m_external_caller;
condition_type m_conditionFindLowestStableVoltage;
//http://forums.wxwidgets.org/viewtopic.php?t=4824:
// wxMutex m_wxmutexFindLowestStableVoltage;
// wxCondition m_wxconditionFindLowestStableVoltage;
x86IandC::thread_type m_x86iandc_threadFindLowestStableVoltage;
x86IandC::thread_type m_x86iandc_threadFindLowestStableCPUcoreOperationInDLL;
unsigned m_uiNumberOfSecondsToWaitUntilVoltageIsReduced;
//std::wstring m_std_wstrInstableCPUcoreVoltageDynLibPath;
std::wstring m_std_wstrDynLibPath;
// VoltageAndFreq m_lastSetVoltageAndFreq;
//TODO if the reference clock changes after starting to find an unstable
//CPU core voltage then (if the ref. clock in heightened) it can be still
//instable. But on the other hand: if the calculation of the ref. clock is
//inaccurate then it is better to set to the same multiplier as at start of
//find lowest voltage.
//Use separate values for both multi and ref clock rather than a single
//composed value for the frequency. because the mult
float m_lastSetCPUcoreMultiplier;
float m_lastSetCPUcoreVoltageInVolt;
float m_fReferenceClockInMHz;
/** min CPU core usage for unstable CPU operation detection thread needed */
float m_fMinCPUcoreUsage;
InstableCPUcoreOperationDetection(/*UserInterface * p_ui*/
CPUcoreData & r_cpucoredata);
/** Must be virtual because else g++ warning:
* `class InstableCPUcoreOperationDetection' has virtual functions
* but non-virtual destructor */
virtual ~InstableCPUcoreOperationDetection() {}
void CountSecondsDown();
float DecreaseVoltageStepByStep(
unsigned wCPUcoreVoltageArrayIndex, const float fMultiplier);
bool DynLibAccessInitialized()
{
return m_hmoduleUnstableVoltageDetectionDynLib &&
m_pfnStartInstableCPUcoreVoltageDetection &&
m_pfnStopInstableCPUcoreVoltageDetection;
}
void ExitFindLowestStableVoltageThread()
{
//Exit the "find lowest stable voltage" thread.
m_vbExitFindLowestStableVoltage = true;
// wxGetApp().m_wxconditionFindLowestStableVoltage.Signal();
LOGN( "signalling the condition to end finding the"
" lowest stable voltage thread")
//Wake up all threads waiting on the condition.
m_conditionFindLowestStableVoltage.Broadcast();
LOGN( "after signalling the condition to end finding the"
" lowest stable voltage thread")
}
virtual dynlibType LoadDynLib() = 0;
bool DynLibSuccessFullyLoaded()
{
return m_hmoduleUnstableVoltageDetectionDynLib != NULL;
}
static DWORD THREAD_PROC_CALLING_CONVENTION FindLowestStableVoltage_ThreadProc(
void * p_v );
DWORD FindLowestStableVoltage();
virtual /*ULONG64*/ unsigned long long GetThreadUserModeStartTime(/*void **/) = 0;
virtual float GetCPUcoreUsageForDynLibThread() = 0;
void HandleVoltageTooLow();
bool IsRunning()
{
return m_x86iandc_threadFindLowestStableVoltage.IsRunning();
}
void SetStopRequestedViaGUI(bool b)
{
m_bStopFindingLowestStableCPUcoreVoltageRequestedViaUI = b;
}
void SetUserInterface(/*UserInterface * p_ui*/ userinterface_type * p_ui);
const x86IandC::thread_type & StartInDynLibInSeparateThread();
void StartInDynLib(/*uint16_t m_ui32CPUcoreMask*/);
/** Must be static as thread proc. */
static DWORD THREAD_PROC_CALLING_CONVENTION
StartInDynLib_ThreadProc(void * p_v );
void Stop();
virtual void UnloadDynLib() = 0;
void ShowMessage(const wchar_t * const msg);
BYTE Start();
virtual StartInstableVoltageDetectionFunctionPointer AssignStartFunctionPointer() = 0;
virtual StopInstableVoltageDetectionFunctionPointer AssignStopFunctionPointer() = 0;
/** Called by "instable CPU core operation" dyn lib */
static void VoltageTooLow();
};
#endif /* INSTABLECPUCOREVOLTAGEDETECTION_HPP_ */
| 34.441989 | 88 | 0.796118 |
9a5463c61acadf9034e5c0698b86f19004fbdeb8 | 949 | cpp | C++ | graphics-library/src/illumination/directional_light.cpp | thetorine/opengl3-library | 3904d857fd1085ba2c57c4289eb0e0d123f11a14 | [
"MIT"
] | null | null | null | graphics-library/src/illumination/directional_light.cpp | thetorine/opengl3-library | 3904d857fd1085ba2c57c4289eb0e0d123f11a14 | [
"MIT"
] | null | null | null | graphics-library/src/illumination/directional_light.cpp | thetorine/opengl3-library | 3904d857fd1085ba2c57c4289eb0e0d123f11a14 | [
"MIT"
] | null | null | null | #include <string>
#include "engine/shader_controller.hpp"
#include "illumination/directional_light.hpp"
namespace gl::illumination {
DirectionalLight::DirectionalLight(const glm::vec3 &dir, const glm::vec3 &color, float intensity)
: m_dir(dir), m_color(color), m_intensity(intensity) {
}
DirectionalLight::~DirectionalLight() {
}
void DirectionalLight::setShaderParams(int index) {
char buffer[22];
snprintf(buffer, sizeof(buffer), "directionalLights[%d]", index);
std::string structName { buffer };
engine::ShaderController::getInstance()->setVec3(structName + ".dir", m_dir);
engine::ShaderController::getInstance()->setVec3(structName + ".color", m_color);
engine::ShaderController::getInstance()->setFloat(structName + ".intensity", m_intensity);
engine::ShaderController::getInstance()->setInt(structName + ".on", true);
}
} | 36.5 | 102 | 0.667018 |
9a5890fa0da18e461b3e74a85105ea2216cb4fff | 6,755 | cc | C++ | Code/Components/Analysis/analysis/current/sourcefitting/CurvatureMapCreator.cc | rtobar/askapsoft | 6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e | [
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
] | null | null | null | Code/Components/Analysis/analysis/current/sourcefitting/CurvatureMapCreator.cc | rtobar/askapsoft | 6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e | [
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
] | null | null | null | Code/Components/Analysis/analysis/current/sourcefitting/CurvatureMapCreator.cc | rtobar/askapsoft | 6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e | [
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
] | null | null | null | /// @file
///
/// XXX Notes on program XXX
///
/// @copyright (c) 2011 CSIRO
/// Australia Telescope National Facility (ATNF)
/// Commonwealth Scientific and Industrial Research Organisation (CSIRO)
/// PO Box 76, Epping NSW 1710, Australia
/// atnf-enquiries@csiro.au
///
/// This file is part of the ASKAP software distribution.
///
/// The ASKAP software distribution is free software: you can redistribute it
/// and/or modify it under the terms of the GNU General Public License as
/// published by the Free Software Foundation; either version 2 of the License,
/// or (at your option) any later version.
///
/// This program is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU General Public License for more details.
///
/// You should have received a copy of the GNU General Public License
/// along with this program; if not, write to the Free Software
/// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
///
/// @author XXX XXX <XXX.XXX@csiro.au>
///
#include <sourcefitting/CurvatureMapCreator.h>
#include <askap_analysis.h>
#include <askap/AskapLogging.h>
#include <askap/AskapError.h>
#include <askapparallel/AskapParallel.h>
#include <Common/ParameterSet.h>
#include <string>
#include <casacore/casa/Arrays/Array.h>
#include <casacore/casa/Arrays/ArrayMath.h>
#include <outputs/DistributedImageWriter.h>
#include <casainterface/CasaInterface.h>
#include <analysisparallel/SubimageDef.h>
#include <casacore/scimath/Mathematics/Convolver.h>
#include <duchamp/Cubes/cubes.hh>
#include <casacore/images/Images/PagedImage.h>
#include <casacore/images/Images/SubImage.h>
#include <casacore/images/Images/ImageOpener.h>
#include <casacore/images/Images/FITSImage.h>
#include <casacore/images/Images/MIRIADImage.h>
#include <casainterface/CasaInterface.h>
///@brief Where the log messages go.
ASKAP_LOGGER(logger, ".curvaturemap");
namespace askap {
namespace analysis {
CurvatureMapCreator::CurvatureMapCreator(askap::askapparallel::AskapParallel &comms,
const LOFAR::ParameterSet &parset):
itsComms(&comms), itsParset(parset)
{
itsFilename = parset.getString("curvatureImage", "");
ASKAPLOG_DEBUG_STR(logger, "Define a CurvatureMapCreator to write to image " <<
itsFilename);
}
CurvatureMapCreator::CurvatureMapCreator(const CurvatureMapCreator& other)
{
this->operator=(other);
}
CurvatureMapCreator& CurvatureMapCreator::operator= (const CurvatureMapCreator& other)
{
if (this == &other) return *this;
itsComms = other.itsComms;
itsParset = other.itsParset;
itsFilename = other.itsFilename;
itsArray = other.itsArray;
itsSigmaCurv = other.itsSigmaCurv;
return *this;
}
void CurvatureMapCreator::initialise(duchamp::Cube &cube, analysisutilities::SubimageDef &subdef)
{
itsCube = &cube;
itsSubimageDef = &subdef;
casa::Slicer slicer = analysisutilities::subsectionToSlicer(cube.pars().section());
analysisutilities::fixSlicer(slicer, cube.header().getWCS());
const boost::shared_ptr<SubImage<Float> > sub =
analysisutilities::getSubImage(cube.pars().getImageFile(), slicer);
itsShape = sub->shape();
duchamp::Section sec = itsSubimageDef->section(itsComms->rank() - 1);
sec.parse(itsShape.asStdVector());
duchamp::Section secMaster = itsSubimageDef->section(-1);
secMaster.parse(itsShape.asStdVector());
itsLocation = casa::IPosition(sec.getStartList());
ASKAPLOG_DEBUG_STR(logger, "Initialised CurvatureMapCreator with shape=" <<
itsShape << " and location=" << itsLocation);
}
void CurvatureMapCreator::calculate()
{
casa::Array<float> inputArray(itsShape, itsCube->getArray(), casa::SHARE);
casa::IPosition kernelShape(2, 3, 3);
casa::Array<float> kernel(kernelShape, 1.);
kernel(casa::IPosition(2, 1, 1)) = -8.;
ASKAPLOG_DEBUG_STR(logger, "Defined a kernel for the curvature map calculations: " << kernel);
casa::Convolver<float> convolver(kernel, itsShape);
ASKAPLOG_DEBUG_STR(logger, "Defined a convolver");
itsArray = casa::Array<float>(itsShape);
ASKAPLOG_DEBUG_STR(logger, "About to convolve");
convolver.linearConv(itsArray, inputArray);
ASKAPLOG_DEBUG_STR(logger, "Convolving done.");
this->findSigma();
this->maskBorders();
}
void CurvatureMapCreator::findSigma()
{
itsSigmaCurv = madfm(itsArray, False, False, False) / Statistics::correctionFactor;
ASKAPLOG_DEBUG_STR(logger, "Found sigma_curv = " << itsSigmaCurv);
}
void CurvatureMapCreator::maskBorders()
{
int nsubx = itsSubimageDef->nsubx();
int nsuby = itsSubimageDef->nsuby();
int overlapx = itsSubimageDef->overlapx() / 2;
int overlapy = itsSubimageDef->overlapy() / 2;
int rank = itsComms->rank() - 1;
int xminOffset = (rank % nsubx == 0) ? 0 : overlapx;
int xmaxOffset = (rank % nsubx == (nsubx - 1)) ? 0 : overlapx;
int yminOffset = (rank / nsubx == 0) ? 0 : overlapy;
int ymaxOffset = (rank / nsubx == (nsuby - 1)) ? 0 : overlapy;
ASKAPLOG_DEBUG_STR(logger, "xminOffset=" << xminOffset <<
", xmaxOffset=" << xmaxOffset <<
", yminOffset=" << yminOffset <<
", ymaxOffset=" << ymaxOffset);
ASKAPLOG_DEBUG_STR(logger, "Starting with location=" << itsLocation <<
" and shape=" << itsShape);
casa::IPosition blc(itsLocation), trc(itsShape - 1);
blc[0] = xminOffset;
blc[1] = yminOffset;
trc[0] -= xmaxOffset;
trc[1] -= ymaxOffset;
casa::Slicer arrSlicer(blc, trc, Slicer::endIsLast);
ASKAPLOG_DEBUG_STR(logger, "Defined a masking Slicer " << arrSlicer);
casa::Array<float> newArr = itsArray(arrSlicer);
ASKAPLOG_DEBUG_STR(logger, "Have extracted a subarray of shape " << newArr.shape());
itsArray.assign(newArr);
itsLocation += blc;
itsShape = trc - blc + 1;
ASKAPLOG_DEBUG_STR(logger, "Now have location=" << itsLocation <<
" and shape=" << itsShape);
}
void CurvatureMapCreator::write()
{
if (itsFilename != "") {
ASKAPLOG_DEBUG_STR(logger, "In CurvatureMapCreator::write()");
DistributedImageWriter writer(*itsComms, itsParset, itsCube, itsFilename);
ASKAPLOG_DEBUG_STR(logger, "Creating the output image " << itsFilename);
writer.create();
ASKAPLOG_DEBUG_STR(logger, "Writing curvature map of shape " <<
itsArray.shape() << " to " << itsFilename);
writer.write(itsArray, itsLocation, true);
ASKAPLOG_DEBUG_STR(logger, "Curvature image written");
}
}
}
}
| 34.116162 | 98 | 0.687491 |
9a58b8685fc78db29f02005c77e7a87db6265711 | 6,229 | cpp | C++ | windows/advcore/ctf/aimm1.2/win32/funcprv.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | windows/advcore/ctf/aimm1.2/win32/funcprv.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | windows/advcore/ctf/aimm1.2/win32/funcprv.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //
// funcprv.cpp
//
#include "private.h"
#include "helpers.h"
#include "immxutil.h"
#include "funcprv.h"
#include "cresstr.h"
#include "resource.h"
//////////////////////////////////////////////////////////////////////////////
//
// CFunctionProvider
//
//////////////////////////////////////////////////////////////////////////////
//+---------------------------------------------------------------------------
//
// ctor
//
//----------------------------------------------------------------------------
CFunctionProvider::CFunctionProvider(ImmIfIME *pImmIfIME, TfClientId tid) : CFunctionProviderBase(tid)
{
Init(CLSID_CAImmLayer, L"AIMM12 Function Provider");
_ImmIfIME = pImmIfIME;
}
//+---------------------------------------------------------------------------
//
// GetFunction
//
//----------------------------------------------------------------------------
STDAPI CFunctionProvider::GetFunction(REFGUID rguid, REFIID riid, IUnknown **ppunk)
{
*ppunk = NULL;
if (!IsEqualIID(rguid, GUID_NULL))
return E_NOINTERFACE;
if (IsEqualIID(riid, IID_IAImmFnDocFeed))
{
*ppunk = new CFnDocFeed(this);
}
if (*ppunk)
return S_OK;
return E_NOINTERFACE;
}
//////////////////////////////////////////////////////////////////////////////
//
// CFnDocFeed
//
//////////////////////////////////////////////////////////////////////////////
//+---------------------------------------------------------------------------
//
// IUnknown
//
//----------------------------------------------------------------------------
STDAPI CFnDocFeed::QueryInterface(REFIID riid, void **ppvObj)
{
*ppvObj = NULL;
if (IsEqualIID(riid, IID_IUnknown) ||
IsEqualIID(riid, IID_IAImmFnDocFeed))
{
*ppvObj = SAFECAST(this, CFnDocFeed *);
}
if (*ppvObj)
{
AddRef();
return S_OK;
}
return E_NOINTERFACE;
}
STDAPI_(ULONG) CFnDocFeed::AddRef()
{
return InterlockedIncrement(&_cRef);
}
STDAPI_(ULONG) CFnDocFeed::Release()
{
long cr;
cr = InterlockedDecrement(&_cRef);
Assert(cr >= 0);
if (cr == 0)
{
delete this;
}
return cr;
}
//+---------------------------------------------------------------------------
//
// ctor
//
//----------------------------------------------------------------------------
CFnDocFeed::CFnDocFeed(CFunctionProvider *pFuncPrv)
{
_cRef = 1;
_pFuncPrv = pFuncPrv;
_pFuncPrv->AddRef();
}
//+---------------------------------------------------------------------------
//
// dtor
//
//----------------------------------------------------------------------------
CFnDocFeed::~CFnDocFeed()
{
_pFuncPrv->Release();
}
//+---------------------------------------------------------------------------
//
// dtor
//
//----------------------------------------------------------------------------
STDAPI CFnDocFeed::GetDisplayName(BSTR *pbstrName)
{
if (!pbstrName)
return E_INVALIDARG;
*pbstrName = SysAllocString(CRStr2(IDS_FUNCPRV_CONVERSION));
if (!*pbstrName)
return E_OUTOFMEMORY;
return S_OK;
}
//+---------------------------------------------------------------------------
//
// dtor
//
//----------------------------------------------------------------------------
STDAPI CFnDocFeed::IsEnabled(BOOL *pfEnable)
{
if (!pfEnable)
return E_INVALIDARG;
*pfEnable = TRUE;
return S_OK;
}
//+---------------------------------------------------------------------------
//
// CFnDocFeed::DocFeed
//
//----------------------------------------------------------------------------
STDAPI CFnDocFeed::DocFeed()
{
IMTLS *ptls = IMTLS_GetOrAlloc();
if (ptls == NULL)
return E_FAIL;
IMCLock imc(ptls->hIMC);
if (imc.Invalid())
return E_FAIL;
CAImeContext* pAImeContext = imc->m_pAImeContext;
if (!pAImeContext)
return E_FAIL;
Assert(_pFuncPrv);
_pFuncPrv->_ImmIfIME->SetupDocFeedString(pAImeContext->GetInputContext(), imc);
return S_OK;
}
//+---------------------------------------------------------------------------
//
// CFnDocFeed::ClearDocFeedBuffer
//
//----------------------------------------------------------------------------
STDAPI CFnDocFeed::ClearDocFeedBuffer()
{
IMTLS *ptls = IMTLS_GetOrAlloc();
if (ptls == NULL)
return E_FAIL;
IMCLock imc(ptls->hIMC);
if (imc.Invalid())
return E_FAIL;
CAImeContext* pAImeContext = imc->m_pAImeContext;
if (!pAImeContext)
return E_FAIL;
Assert(_pFuncPrv);
_pFuncPrv->_ImmIfIME->ClearDocFeedBuffer(pAImeContext->GetInputContext(), imc);
return S_OK;
}
//+---------------------------------------------------------------------------
//
// CFnDocFeed::StartReconvert
//
//----------------------------------------------------------------------------
STDAPI CFnDocFeed::StartReconvert()
{
IMTLS *ptls = IMTLS_GetOrAlloc();
if (ptls == NULL)
return E_FAIL;
IMCLock imc(ptls->hIMC);
if (imc.Invalid())
return E_FAIL;
CAImeContext* pAImeContext = imc->m_pAImeContext;
if (!pAImeContext)
return E_FAIL;
Assert(_pFuncPrv);
pAImeContext->SetupReconvertString();
pAImeContext->EndReconvertString();
return S_OK;
}
//+---------------------------------------------------------------------------
//
// CFnDocFeed::StartUndoCompositionString
//
//----------------------------------------------------------------------------
STDAPI CFnDocFeed::StartUndoCompositionString()
{
IMTLS *ptls = IMTLS_GetOrAlloc();
if (ptls == NULL)
return E_FAIL;
IMCLock imc(ptls->hIMC);
if (imc.Invalid())
return E_FAIL;
CAImeContext* pAImeContext = imc->m_pAImeContext;
if (!pAImeContext)
return E_FAIL;
Assert(_pFuncPrv);
pAImeContext->SetupUndoCompositionString();
pAImeContext->EndUndoCompositionString();
return S_OK;
}
| 22.98524 | 103 | 0.396693 |
9a5bea3fff59bbd804be55fc3bae91234f087268 | 267 | cpp | C++ | Day2/zadanie2.cpp | majkel84/kurs_cpp_podstawowy | eddaffb310c6132304aa26dc87ec04ddfc09c541 | [
"MIT"
] | 1 | 2022-03-03T14:07:57.000Z | 2022-03-03T14:07:57.000Z | Day2/zadanie2.cpp | majkel84/kurs_cpp_podstawowy | eddaffb310c6132304aa26dc87ec04ddfc09c541 | [
"MIT"
] | 2 | 2020-05-22T22:01:52.000Z | 2020-05-30T09:24:42.000Z | Day2/zadanie2.cpp | majkel84/kurs_cpp_podstawowy | eddaffb310c6132304aa26dc87ec04ddfc09c541 | [
"MIT"
] | null | null | null | #include <iostream>
void foo(int* ptr) {
*ptr = 10;
}
void bar(int* ptr) {
*ptr = 20;
}
int main() {
int number = 5;
std::cout << number << '\n';
foo(&number);
std::cout << number << '\n';
bar(&number);
std::cout << number << '\n';
return 0;
}
| 12.714286 | 30 | 0.505618 |
9a5c8fa10db7b514eb5979e451ad60d3e6ff69a5 | 4,060 | cpp | C++ | ImdViewerV2/plugins/efbbox/efbbox.cpp | olivierchatry/iri3d | cae98c61d9257546d0fc81e69709297d04a17a14 | [
"MIT"
] | 2 | 2022-01-02T08:12:29.000Z | 2022-02-12T22:15:11.000Z | ImdViewerV2/plugins/efbbox/efbbox.cpp | olivierchatry/iri3d | cae98c61d9257546d0fc81e69709297d04a17a14 | [
"MIT"
] | null | null | null | ImdViewerV2/plugins/efbbox/efbbox.cpp | olivierchatry/iri3d | cae98c61d9257546d0fc81e69709297d04a17a14 | [
"MIT"
] | 1 | 2022-01-02T08:09:51.000Z | 2022-01-02T08:09:51.000Z | #include "stdafx.h"
#include "efbbox.h"
#include "magic/MgcBox3.h"
#include "magic/MgcVector3.h"
static imdviewer_plugin_info_t plugins_info =
{
"Epifighter BoundingBox generator.",
"Generate bounding box around bones.",
"Chatry Oliver, Julien Barbier.",
true // display box for octree.
};
BOOL APIENTRY DllMain(HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
void PluginEfBox::PluginDestroy()
{
if (_bbox)
delete _bbox;
_bbox = 0;
_bbox_count = 0;
}
#define DEFAULT_FILE_NAME "\\bones_bbox.dat"
#define NB_POINTS_PER_BBOX 8
#define NB_COORD_PER_POINT 3
void PluginEfBox::SaveToFile(const char *path)
{
int i;
std::string file_name(path);
file_name += DEFAULT_FILE_NAME;
FILE *fd = fopen(file_name.c_str(), "wb");
if (fd == NULL)
return;
fwrite(&_bbox_count, sizeof(_bbox_count), 1, fd);
for (i = 0; i < _bbox_count; i++)
fwrite(&_bbox[i], sizeof(_bbox[i]), 1, fd);
fclose(fd);
}
bool PluginEfBox::PluginGo(const char *path, imd2_object_t *object, imd2_bone_file_t *bones)
{
if (object == 0 || !object->imd2_object_header.have_skin)
return false;
PluginDestroy();
_bbox = new BoundingBox[object->imd2_object_header.num_bones];
_bbox_count = object->imd2_object_header.num_bones;
for (int bi = 0; bi < _bbox_count; bi++)
{
std::vector<Mgc::Vector3> mesh_point;
mesh_point.clear();
for (int mi = 0; mi < object->imd2_object_header.num_mesh; mi++)
{
imd2_mesh_t *mesh = object->imd2_mesh + mi;
if (mesh->imd2_mesh_header.have_skin)
{
for (int vi = 0; vi < mesh->imd2_mesh_header.num_vertex; vi++)
{
imd2_skin_t *skin = mesh->imd2_skin + vi;
imd2_vertex_t *vertex = mesh->imd2_vertex + vi;
int bone_index = -1;
float max_weight = 0.0f;
for (int wi = 0; wi < skin->num_bones_assigned; wi++)
{
imd2_weight_t *weight = skin->weight + wi;
if (weight->weight > max_weight)
{
bone_index = weight->bone_index;
max_weight = weight->weight;
}
}
if (bone_index != -1 && bone_index == bi)
{
Mgc::Vector3 v(vertex->pos);
mesh_point.push_back(v);
}
}
}
}
size_t count = mesh_point.size();
Mgc::Vector3 *pt = new Mgc::Vector3[count];
for (size_t i = 0; i < count; ++i)
pt[i] = mesh_point[i];
// compute bounding box.
Mgc::Box3 magic_bbox;
BoundingBox *bbox = _bbox + bi;
if (mesh_point.size() > 0)
{
bbox->box = ContOrientedBox((int)mesh_point.size(), pt);
bbox->bone_index = bi;
}
else
bbox->bone_index = -1;
delete pt;
}
SaveToFile(path);
return false;
}
void PluginEfBox::PluginInit()
{
_bbox = 0;
_bbox_count = 0;
}
void PluginEfBox::PluginRender(unsigned int current_anim, imd2_bone_file_t *bones)
{
for (int i = 0; i < _bbox_count; ++i)
{
BoundingBox *bbox = _bbox + i;
int pair[] = {3, 2, 2, 1, 1, 0, 0, 3, 1, 5, 2, 6, 3, 7, 0, 4, 4, 7, 7, 6, 6, 5, 5, 4};
Mgc::Vector3 p[8];
bbox->box.ComputeVertices(p);
// search for bone index
glPushMatrix();
if (bones)
for (int i = 0; i < bones->imd2_bone_file_header.bone_count; ++i)
{
if (bones->bones[i].imd2_bone_header.bone_index == bbox->bone_index)
{
glMultMatrixf(bones->bones[i].imd2_bone_anim[current_anim].matrix);
continue;
}
}
glBegin(GL_LINES);
for (int i = 0; i < 24; i += 2)
{
glVertex3fv(p[pair[i]]);
glVertex3fv(p[pair[i + 1]]);
}
glEnd();
glPopMatrix();
}
}
DLLAPI imdviewer_plugin_info_t *GetPluginInfo()
{
return &plugins_info;
}
DLLAPI ImdViewerPlugins *CreateInstance()
{
return new PluginEfBox;
}
| 25.061728 | 92 | 0.599015 |
9a5e005d2f388ea2c62ff109bd5bc7fc4f0d0c44 | 8,320 | cpp | C++ | source/examples/states/main.cpp | citron0xa9/globjects | 53a1de45f3c177fbd805610f274d3ffb1b97843a | [
"MIT"
] | null | null | null | source/examples/states/main.cpp | citron0xa9/globjects | 53a1de45f3c177fbd805610f274d3ffb1b97843a | [
"MIT"
] | null | null | null | source/examples/states/main.cpp | citron0xa9/globjects | 53a1de45f3c177fbd805610f274d3ffb1b97843a | [
"MIT"
] | 2 | 2020-10-01T04:10:51.000Z | 2021-07-01T07:45:45.000Z |
#include <iostream>
#include <algorithm>
#include <cpplocate/cpplocate.h>
#include <cpplocate/ModuleInfo.h>
#include <glm/vec2.hpp>
#include <glbinding/gl/gl.h>
#include <glbinding/ContextInfo.h>
#include <glbinding/Version.h>
#include <GLFW/glfw3.h>
#include <globjects/globjects.h>
#include <globjects/base/File.h>
#include <globjects/logging.h>
#include <globjects/Buffer.h>
#include <globjects/Program.h>
#include <globjects/Shader.h>
#include <globjects/VertexArray.h>
#include <globjects/VertexAttributeBinding.h>
#include <globjects/State.h>
#include "datapath.inl"
using namespace gl;
namespace
{
std::unique_ptr<globjects::Program> g_shaderProgram = nullptr;
std::unique_ptr<globjects::File> g_vertexShaderSource = nullptr;
std::unique_ptr<globjects::AbstractStringSource> g_vertexShaderTemplate = nullptr;
std::unique_ptr<globjects::Shader> g_vertexShader = nullptr;
std::unique_ptr<globjects::File> g_fragmentShaderSource = nullptr;
std::unique_ptr<globjects::AbstractStringSource> g_fragmentShaderTemplate = nullptr;
std::unique_ptr<globjects::Shader> g_fragmentShader = nullptr;
std::unique_ptr<globjects::VertexArray> g_vao = nullptr;
std::unique_ptr<globjects::Buffer> g_buffer = nullptr;
std::unique_ptr<globjects::State> g_thinnestPointSizeState = nullptr;
std::unique_ptr<globjects::State> g_thinPointSizeState = nullptr;
std::unique_ptr<globjects::State> g_normalPointSizeState = nullptr;
std::unique_ptr<globjects::State> g_thickPointSizeState = nullptr;
std::unique_ptr<globjects::State> g_disableRasterizerState = nullptr;
std::unique_ptr<globjects::State> g_enableRasterizerState = nullptr;
std::unique_ptr<globjects::State> g_defaultPointSizeState = nullptr;
auto g_size = glm::ivec2{};
}
void initialize()
{
// Initialize OpenGL objects
g_defaultPointSizeState = globjects::State::create();
g_defaultPointSizeState->pointSize(globjects::getFloat(GL_POINT_SIZE));
g_thinnestPointSizeState = globjects::State::create();
g_thinnestPointSizeState->pointSize(2.0f);
g_thinPointSizeState = globjects::State::create();
g_thinPointSizeState->pointSize(5.0f);
g_normalPointSizeState = globjects::State::create();
g_normalPointSizeState->pointSize(10.0f);
g_thickPointSizeState = globjects::State::create();
g_thickPointSizeState->pointSize(20.0f);
g_disableRasterizerState = globjects::State::create();
g_disableRasterizerState->enable(GL_RASTERIZER_DISCARD);
g_enableRasterizerState = globjects::State::create();
g_enableRasterizerState->disable(GL_RASTERIZER_DISCARD);
g_vao = globjects::VertexArray::create();
g_buffer = globjects::Buffer::create();
g_shaderProgram = globjects::Program::create();
const auto dataPath = common::retrieveDataPath("globjects", "dataPath");
g_vertexShaderSource = globjects::Shader::sourceFromFile(dataPath + "states/standard.vert");
g_vertexShaderTemplate = globjects::Shader::applyGlobalReplacements(g_vertexShaderSource.get());
g_vertexShader = globjects::Shader::create(GL_VERTEX_SHADER, g_vertexShaderTemplate.get());
g_fragmentShaderSource = globjects::Shader::sourceFromFile(dataPath + "states/standard.frag");
g_fragmentShaderTemplate = globjects::Shader::applyGlobalReplacements(g_fragmentShaderSource.get());
g_fragmentShader = globjects::Shader::create(GL_FRAGMENT_SHADER, g_fragmentShaderTemplate.get());
g_shaderProgram->attach(g_vertexShader.get(), g_fragmentShader.get());
static auto data = std::vector<glm::vec2>();
if (data.empty())
{
for (auto y = 0.8f; y > -1.f; y -= 0.2f)
for (auto x = -0.8f; x < 1.f; x += 0.4f)
data.push_back(glm::vec2(x, y));
}
g_buffer->setData(data, GL_STATIC_DRAW );
g_vao->binding(0)->setAttribute(0);
g_vao->binding(0)->setBuffer(g_buffer.get(), 0, sizeof(glm::vec2));
g_vao->binding(0)->setFormat(2, GL_FLOAT);
g_vao->enable(0);
}
void deinitialize()
{
g_shaderProgram.reset(nullptr);
g_vertexShaderSource.reset(nullptr);
g_vertexShaderTemplate.reset(nullptr);
g_vertexShader.reset(nullptr);
g_fragmentShaderSource.reset(nullptr);
g_fragmentShaderTemplate.reset(nullptr);
g_fragmentShader.reset(nullptr);
g_vao.reset(nullptr);
g_buffer.reset(nullptr);
g_thinnestPointSizeState.reset(nullptr);
g_thinPointSizeState.reset(nullptr);
g_normalPointSizeState.reset(nullptr);
g_thickPointSizeState.reset(nullptr);
g_disableRasterizerState.reset(nullptr);
g_enableRasterizerState.reset(nullptr);
g_defaultPointSizeState.reset(nullptr);
}
void draw()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glViewport(0, 0, g_size.x, g_size.y);
g_shaderProgram->use();
g_defaultPointSizeState->apply();
g_vao->drawArrays(GL_POINTS, 0, 5);
g_thinnestPointSizeState->apply();
g_vao->drawArrays(GL_POINTS, 5, 5);
g_thinPointSizeState->apply();
g_vao->drawArrays(GL_POINTS, 10, 5);
g_normalPointSizeState->apply();
g_vao->drawArrays(GL_POINTS, 15, 5);
g_thickPointSizeState->apply();
g_vao->drawArrays(GL_POINTS, 20, 1);
g_disableRasterizerState->apply();
g_vao->drawArrays(GL_POINTS, 21, 1);
g_enableRasterizerState->apply();
g_vao->drawArrays(GL_POINTS, 22, 1);
g_disableRasterizerState->apply();
g_vao->drawArrays(GL_POINTS, 23, 1);
g_enableRasterizerState->apply();
g_vao->drawArrays(GL_POINTS, 24, 1);
g_normalPointSizeState->apply();
g_vao->drawArrays(GL_POINTS, 25, 5);
g_thinPointSizeState->apply();
g_vao->drawArrays(GL_POINTS, 30, 5);
g_thinnestPointSizeState->apply();
g_vao->drawArrays(GL_POINTS, 35, 5);
g_defaultPointSizeState->apply();
g_vao->drawArrays(GL_POINTS, 35, 5);
g_shaderProgram->release();
}
void error(int errnum, const char * errmsg)
{
globjects::critical() << errnum << ": " << errmsg << std::endl;
}
void framebuffer_size_callback(GLFWwindow * /*window*/, int width, int height)
{
g_size = glm::ivec2{ width, height };
}
void key_callback(GLFWwindow * window, int key, int /*scancode*/, int action, int /*modes*/)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE)
glfwSetWindowShouldClose(window, true);
if (key == GLFW_KEY_F5 && action == GLFW_RELEASE)
{
g_vertexShaderSource->reload();
g_fragmentShaderSource->reload();
}
}
int main(int /*argc*/, char * /*argv*/[])
{
// Initialize GLFW
if (!glfwInit())
return 1;
glfwSetErrorCallback(error);
glfwDefaultWindowHints();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, true);
// Create a context and, if valid, make it current
GLFWwindow * window = glfwCreateWindow(640, 480, "globjects States", NULL, NULL);
if (window == nullptr)
{
globjects::critical() << "Context creation failed. Terminate execution.";
glfwTerminate();
return -1;
}
glfwSetKeyCallback(window, key_callback);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glfwMakeContextCurrent(window);
// Initialize globjects (internally initializes glbinding, and registers the current context)
globjects::init();
std::cout << std::endl
<< "OpenGL Version: " << glbinding::ContextInfo::version() << std::endl
<< "OpenGL Vendor: " << glbinding::ContextInfo::vendor() << std::endl
<< "OpenGL Renderer: " << glbinding::ContextInfo::renderer() << std::endl << std::endl;
globjects::info() << "Press F5 to reload shaders." << std::endl << std::endl;
glfwGetFramebufferSize(window, &g_size[0], &g_size[1]);
initialize();
// Main loop
while (!glfwWindowShouldClose(window))
{
glfwPollEvents();
draw();
glfwSwapBuffers(window);
}
deinitialize();
// Properly shutdown GLFW
glfwTerminate();
return 0;
}
| 32.885375 | 105 | 0.683774 |
9a5f5c33216fd13f253f598c1e49cd75cc8c66df | 559 | cpp | C++ | dev/assem.cpp | jordanjohnston/manseglib | 00723792c9b16f6518e25095569d77f2ed7b6d22 | [
"MIT"
] | null | null | null | dev/assem.cpp | jordanjohnston/manseglib | 00723792c9b16f6518e25095569d77f2ed7b6d22 | [
"MIT"
] | null | null | null | dev/assem.cpp | jordanjohnston/manseglib | 00723792c9b16f6518e25095569d77f2ed7b6d22 | [
"MIT"
] | 1 | 2020-06-09T18:48:14.000Z | 2020-06-09T18:48:14.000Z | #include <iostream>
#include "../manseglib.hpp"
int main()
{
constexpr int size = 1000;
ManSeg::ManSegArray a(size);
ManSeg::ManSegArray b(size);
// double a[size];
// double b[size];
std::cout << "filling\n";
for(int i = 0; i < size; ++i)
{
b.pairs[i] = 0;
a.pairs[i] = i;
}
std::cout << "now copying\n";
for(int i = 0; i < size; ++i)
{
for(int j = 0; j < size; ++j) b.pairs[i] += a.pairs[j];
}
std::cout << "finished copying\n";
for(int i = 0; i < size; ++i)
std::cout << b.pairs[i] << " ";
std::cout << std::endl;
return 0;
}
| 17.46875 | 57 | 0.543828 |
9a602f9f5123a3670e8b693e3b9852c589b22c54 | 30 | cpp | C++ | src/expression.cpp | koraxkorakos/mv | b5f589bd089fd05fde7a0837f39746e2e343499e | [
"BSD-2-Clause"
] | null | null | null | src/expression.cpp | koraxkorakos/mv | b5f589bd089fd05fde7a0837f39746e2e343499e | [
"BSD-2-Clause"
] | null | null | null | src/expression.cpp | koraxkorakos/mv | b5f589bd089fd05fde7a0837f39746e2e343499e | [
"BSD-2-Clause"
] | null | null | null | //#include <mv/expression.hpp> | 30 | 30 | 0.733333 |
9a6070ae0d84e05add8020fe843e371cff24d5a0 | 16,062 | cpp | C++ | src/cpm_BaseParaManager_MPI.cpp | jorji/CPMlib | 7ba683d1abc60f11bafcc5732da831278b002afa | [
"BSD-2-Clause"
] | 4 | 2015-03-17T17:30:10.000Z | 2019-01-31T15:13:59.000Z | src/cpm_BaseParaManager_MPI.cpp | jorji/CPMlib | 7ba683d1abc60f11bafcc5732da831278b002afa | [
"BSD-2-Clause"
] | null | null | null | src/cpm_BaseParaManager_MPI.cpp | jorji/CPMlib | 7ba683d1abc60f11bafcc5732da831278b002afa | [
"BSD-2-Clause"
] | 4 | 2015-12-09T02:42:29.000Z | 2022-03-18T09:03:28.000Z | /*
###################################################################################
#
# CPMlib - Computational space Partitioning Management library
#
# Copyright (c) 2012-2014 Institute of Industrial Science (IIS), The University of Tokyo.
# All rights reserved.
#
# Copyright (c) 2014-2016 Advanced Institute for Computational Science (AICS), RIKEN.
# All rights reserved.
#
# Copyright (c) 2016-2017 Research Institute for Information Technology (RIIT), Kyushu University.
# All rights reserved.
#
###################################################################################
*/
/**
* @file cpm_BaseParaManager_MPI.cpp
* パラレルマネージャクラスのMPIインターフェイス関数ソースファイル
* @date 2012/05/31
*/
#include "stdlib.h"
#include "cpm_BaseParaManager.h"
#if !defined(_WIN32) && !defined(WIN32)
#include <unistd.h> // for gethostname() of FX10/K
#endif
////////////////////////////////////////////////////////////////////////////////
// MPI_Datatypeを取得
MPI_Datatype
cpm_BaseParaManager::GetMPI_Datatype(int datatype)
{
if( datatype == CPM_REAL )
{
if( RealIsDouble() ) return MPI_DOUBLE;
return MPI_FLOAT;
}
else if( datatype == CPM_CHAR ) return MPI_CHAR;
else if( datatype == CPM_SHORT ) return MPI_SHORT;
else if( datatype == CPM_INT ) return MPI_INT;
else if( datatype == CPM_LONG ) return MPI_LONG;
else if( datatype == CPM_FLOAT ) return MPI_FLOAT;
else if( datatype == CPM_DOUBLE ) return MPI_DOUBLE;
else if( datatype == CPM_LONG_DOUBLE ) return MPI_LONG_DOUBLE;
else if( datatype == CPM_UNSIGNED_CHAR ) return MPI_UNSIGNED_CHAR;
else if( datatype == CPM_UNSIGNED_SHORT ) return MPI_UNSIGNED_SHORT;
else if( datatype == CPM_UNSIGNED ) return MPI_UNSIGNED;
else if( datatype == CPM_UNSIGNED_LONG ) return MPI_UNSIGNED_LONG;
#ifdef MPI_LONG_LONG_INT
else if( datatype == CPM_LONG_LONG_INT ) return MPI_LONG_LONG_INT;
#endif
#ifdef MPI_LONG_LONG
else if( datatype == CPM_LONG_LONG ) return MPI_LONG_LONG;
#endif
#ifdef MPI_UNSIGNED_LONG_LONG
else if( datatype == CPM_UNSIGNED_LONG_LONG ) return MPI_UNSIGNED_LONG_LONG;
#endif
return MPI_DATATYPE_NULL;
}
////////////////////////////////////////////////////////////////////////////////
// MPI_Opを取得
MPI_Op
cpm_BaseParaManager::GetMPI_Op(int op)
{
if ( op == CPM_MAX ) return MPI_MAX;
else if( op == CPM_MIN ) return MPI_MIN;
else if( op == CPM_SUM ) return MPI_SUM;
else if( op == CPM_PROD ) return MPI_PROD;
else if( op == CPM_LAND ) return MPI_LAND;
else if( op == CPM_BAND ) return MPI_BAND;
else if( op == CPM_LOR ) return MPI_LOR;
else if( op == CPM_BOR ) return MPI_BOR;
else if( op == CPM_LXOR ) return MPI_LXOR;
else if( op == CPM_BXOR ) return MPI_BXOR;
// else if( op == CPM_MINLOC ) return CPM_MINLOC; // not support
// else if( op == CPM_MAXLOC ) return CPM_MAXLOC; // not support
return MPI_OP_NULL;
}
////////////////////////////////////////////////////////////////////////////////
// ランク番号の取得
int
cpm_BaseParaManager::GetMyRankID( int procGrpNo )
{
// 不正なプロセスグループ番号
if( procGrpNo < 0 || procGrpNo >= int(m_procGrpList.size()) )
{
// プロセスグループが存在しない
return getRankNull();
}
// コミュニケータをチェック
MPI_Comm comm = m_procGrpList[procGrpNo];
if( IsCommNull(comm) )
{
// プロセスグループに自ランクが含まれない
return getRankNull();
}
// ランク番号を取得
int rankNo;
MPI_Comm_rank( comm, &rankNo );
// ランク番号
return rankNo;
}
////////////////////////////////////////////////////////////////////////////////
// ランク数の取得
int
cpm_BaseParaManager::GetNumRank( int procGrpNo )
{
// 不正なプロセスグループ番号
if( procGrpNo < 0 || procGrpNo >= int(m_procGrpList.size()) )
{
// プロセスグループが存在しない
return -1;
}
// コミュニケータをチェック
MPI_Comm comm = m_procGrpList[procGrpNo];
if( IsCommNull(comm) )
{
// プロセスグループに自ランクが含まれない
return -1;
}
// ランク数を取得
int nrank;
MPI_Comm_size( comm, &nrank );
// ランク数
return nrank;
}
////////////////////////////////////////////////////////////////////////////////
// ホスト名の取得
std::string
cpm_BaseParaManager::GetHostName()
{
char name[512];
memset(name, 0x00, sizeof(char)*512);
if( gethostname(name, 512) != 0 ) return std::string("");
return std::string(name);
}
////////////////////////////////////////////////////////////////////////////////
// コミュニケータの取得
MPI_Comm
cpm_BaseParaManager::GetMPI_Comm( int procGrpNo )
{
// 不正なプロセスグループ番号
if( procGrpNo < 0 || procGrpNo >= int(m_procGrpList.size()) )
{
// プロセスグループが存在しない
return getCommNull();
}
return m_procGrpList[procGrpNo];
}
////////////////////////////////////////////////////////////////////////////////
// Abort
void
cpm_BaseParaManager::Abort( int errorcode )
{
// MPI_Abort
MPI_Abort(MPI_COMM_WORLD, errorcode);
exit(errorcode);
}
////////////////////////////////////////////////////////////////////////////////
// Barrier
cpm_ErrorCode
cpm_BaseParaManager::Barrier( int procGrpNo )
{
// コミュニケータを取得
MPI_Comm comm = GetMPI_Comm( procGrpNo );
if( IsCommNull( comm ) )
{
// プロセスグループが存在しない
return CPM_ERROR_NOT_IN_PROCGROUP;
}
// MPI_Barrier
if( MPI_Barrier(comm) != MPI_SUCCESS )
{
return CPM_ERROR_MPI_BARRIER;
}
return CPM_SUCCESS;
}
////////////////////////////////////////////////////////////////////////////////
// Wait
cpm_ErrorCode
cpm_BaseParaManager::Wait( MPI_Request *request )
{
if( !request )
{
return CPM_ERROR_INVALID_PTR;
}
if( *request == MPI_REQUEST_NULL )
{
return CPM_ERROR_MPI_INVALID_REQUEST;
}
// MPI_Wait
MPI_Status status;
if( MPI_Wait( request, &status ) != MPI_SUCCESS )
{
return CPM_ERROR_MPI_WAIT;
}
return CPM_SUCCESS;
}
////////////////////////////////////////////////////////////////////////////////
// Waitall
cpm_ErrorCode
cpm_BaseParaManager::Waitall( int count, MPI_Request requests[] )
{
// status
int cnt = 0;
MPI_Status *stat = new MPI_Status[count];
MPI_Request *req = new MPI_Request[count];
for( int i=0;i<count;i++ )
{
if( requests[i] != MPI_REQUEST_NULL ) req[cnt++] = requests[i];
}
if( cnt == 0 )
{
delete [] stat;
delete [] req;
return CPM_SUCCESS;
}
// MPI_Waitall
if( MPI_Waitall( cnt, req, stat ) != MPI_SUCCESS )
{
delete [] stat;
delete [] req;
return CPM_ERROR_MPI_WAITALL;
}
delete [] stat;
delete [] req;
return CPM_SUCCESS;
}
////////////////////////////////////////////////////////////////////////////////
// Bcast(MPI_Datatype指定)
cpm_ErrorCode
cpm_BaseParaManager::Bcast( MPI_Datatype dtype, void *buf, int count, int root, int procGrpNo )
{
if( !buf )
{
return CPM_ERROR_INVALID_PTR;
}
// コミュニケータを取得
MPI_Comm comm = GetMPI_Comm(procGrpNo);
if( IsCommNull(comm) )
{
// プロセスグループが存在しない
return CPM_ERROR_NOT_IN_PROCGROUP;
}
// MPI_Bcast
if( MPI_Bcast( buf, count, dtype, root, comm ) != MPI_SUCCESS )
{
return CPM_ERROR_MPI_BCAST;
}
return CPM_SUCCESS;
}
////////////////////////////////////////////////////////////////////////////////
// Send(MPI_Datatype指定)
cpm_ErrorCode
cpm_BaseParaManager::Send( MPI_Datatype dtype, void *buf, int count, int dest, int procGrpNo )
{
if( !buf )
{
return CPM_ERROR_INVALID_PTR;
}
// コミュニケータを取得
MPI_Comm comm = GetMPI_Comm(procGrpNo);
if( IsCommNull(comm) )
{
// プロセスグループが存在しない
return CPM_ERROR_NOT_IN_PROCGROUP;
}
// MPI_Send
int tag = 1;
if( MPI_Send( buf, count, dtype, dest, tag, comm ) != MPI_SUCCESS )
{
return CPM_ERROR_MPI_SEND;
}
return CPM_SUCCESS;
}
////////////////////////////////////////////////////////////////////////////////
// Recv(MPI_Datatype指定)
cpm_ErrorCode
cpm_BaseParaManager::Recv( MPI_Datatype dtype, void *buf, int count, int source, int procGrpNo )
{
if( !buf )
{
return CPM_ERROR_INVALID_PTR;
}
// コミュニケータを取得
MPI_Comm comm = GetMPI_Comm(procGrpNo);
if( IsCommNull(comm) )
{
// プロセスグループが存在しない
return CPM_ERROR_NOT_IN_PROCGROUP;
}
// MPI_Send
int tag = 1;
MPI_Status status;
if( MPI_Recv( buf, count, dtype, source, tag, comm, &status ) != MPI_SUCCESS )
{
return CPM_ERROR_MPI_SEND;
}
return CPM_SUCCESS;
}
////////////////////////////////////////////////////////////////////////////////
// Isend(MPI_Datatype指定)
cpm_ErrorCode
cpm_BaseParaManager::Isend( MPI_Datatype dtype, void *buf, int count, int dest, MPI_Request *request, int procGrpNo )
{
if( !buf || !request )
{
return CPM_ERROR_INVALID_PTR;
}
*request = MPI_REQUEST_NULL;
// コミュニケータを取得
MPI_Comm comm = GetMPI_Comm(procGrpNo);
if( IsCommNull(comm) )
{
// プロセスグループが存在しない
return CPM_ERROR_NOT_IN_PROCGROUP;
}
// MPI_Isend
int tag = 1;
if( MPI_Isend( buf, count, dtype, dest, tag, comm, request ) != MPI_SUCCESS )
{
return CPM_ERROR_MPI_ISEND;
}
return CPM_SUCCESS;
}
////////////////////////////////////////////////////////////////////////////////
// Irecv(MPI_Datatype指定)
cpm_ErrorCode
cpm_BaseParaManager::Irecv( MPI_Datatype dtype, void *buf, int count, int source, MPI_Request *request, int procGrpNo )
{
if( !buf || !request )
{
return CPM_ERROR_INVALID_PTR;
}
*request = MPI_REQUEST_NULL;
// コミュニケータを取得
MPI_Comm comm = GetMPI_Comm(procGrpNo);
if( IsCommNull(comm) )
{
// プロセスグループが存在しない
return CPM_ERROR_NOT_IN_PROCGROUP;
}
// MPI_Irecv
int tag = 1;
if( MPI_Irecv( buf, count, dtype, source, tag, comm, request ) != MPI_SUCCESS )
{
return CPM_ERROR_MPI_IRECV;
}
return CPM_SUCCESS;
}
////////////////////////////////////////////////////////////////////////////////
// Allreduce(MPI_Datatype指定)
cpm_ErrorCode
cpm_BaseParaManager::Allreduce( MPI_Datatype dtype, void *sendbuf, void *recvbuf, int count, MPI_Op op, int procGrpNo )
{
if( !sendbuf || !recvbuf )
{
return CPM_ERROR_INVALID_PTR;
}
// コミュニケータを取得
MPI_Comm comm = GetMPI_Comm(procGrpNo);
if( IsCommNull(comm) )
{
// プロセスグループが存在しない
return CPM_ERROR_NOT_IN_PROCGROUP;
}
// MPI_Allreduce
if( MPI_Allreduce( sendbuf, recvbuf, count, dtype, op, comm ) != MPI_SUCCESS )
{
return CPM_ERROR_MPI_ALLREDUCE;
}
return CPM_SUCCESS;
}
////////////////////////////////////////////////////////////////////////////////
// Gather(MPI_Datatype指定)
cpm_ErrorCode
cpm_BaseParaManager::Gather( MPI_Datatype stype, void *sendbuf, int sendcnt
, MPI_Datatype rtype, void *recvbuf, int recvcnt
, int root, int procGrpNo )
{
if( !sendbuf || !recvbuf )
{
return CPM_ERROR_INVALID_PTR;
}
//コミュニケータを取得
MPI_Comm comm = GetMPI_Comm(procGrpNo);
if( IsCommNull(comm) )
{
// プロセスグループが存在しない
return CPM_ERROR_NOT_IN_PROCGROUP;
}
// MPI_Gather
if( MPI_Gather( sendbuf, sendcnt, stype, recvbuf, recvcnt, rtype, root, comm ) != MPI_SUCCESS )
{
return CPM_ERROR_MPI_GATHER;
}
return CPM_SUCCESS;
}
////////////////////////////////////////////////////////////////////////////////
// Allgather(MPI_Datatype指定)
cpm_ErrorCode
cpm_BaseParaManager::Allgather( MPI_Datatype stype, void *sendbuf, int sendcnt
, MPI_Datatype rtype, void *recvbuf, int recvcnt
, int procGrpNo )
{
if( !sendbuf || !recvbuf )
{
return CPM_ERROR_INVALID_PTR;
}
//コミュニケータを取得
MPI_Comm comm = GetMPI_Comm(procGrpNo);
if( IsCommNull(comm) )
{
// プロセスグループが存在しない
return CPM_ERROR_NOT_IN_PROCGROUP;
}
// MPI_Allaather
if( MPI_Allgather( sendbuf, sendcnt, stype, recvbuf, recvcnt, rtype, comm ) != MPI_SUCCESS )
{
return CPM_ERROR_MPI_ALLGATHER;
}
return CPM_SUCCESS;
}
////////////////////////////////////////////////////////////////////////////////
// Gatherv(MPI_Datatype指定)
cpm_ErrorCode
cpm_BaseParaManager::Gatherv( MPI_Datatype stype, void *sendbuf, int sendcnt
, MPI_Datatype rtype, void *recvbuf, int *recvcnts
, int *displs, int root, int procGrpNo )
{
if( !sendbuf || !recvbuf || !recvcnts || !displs )
{
return CPM_ERROR_INVALID_PTR;
}
//コミュニケータを取得
MPI_Comm comm = GetMPI_Comm(procGrpNo);
if( IsCommNull(comm) )
{
// プロセスグループが存在しない
return CPM_ERROR_NOT_IN_PROCGROUP;
}
// MPI_Gather
if( MPI_Gatherv( sendbuf, sendcnt, stype, recvbuf, recvcnts, displs
, rtype, root, comm ) != MPI_SUCCESS )
{
return CPM_ERROR_MPI_GATHERV;
}
return CPM_SUCCESS;
}
////////////////////////////////////////////////////////////////////////////////
// Allgatherv(MPI_Datatype指定)
cpm_ErrorCode
cpm_BaseParaManager::Allgatherv( MPI_Datatype stype, void *sendbuf, int sendcnt
, MPI_Datatype rtype, void *recvbuf, int *recvcnts
, int *displs, int procGrpNo )
{
if( !sendbuf || !recvbuf || !recvcnts || !displs )
{
return CPM_ERROR_INVALID_PTR;
}
// コミュニケータを取得
MPI_Comm comm = GetMPI_Comm(procGrpNo);
if( IsCommNull(comm) )
{
// プロセスグループが存在しない
return CPM_ERROR_NOT_IN_PROCGROUP;
}
// MPI_Allaather
if( MPI_Allgatherv( sendbuf, sendcnt, stype, recvbuf, recvcnts, displs, rtype, comm ) != MPI_SUCCESS )
{
return CPM_ERROR_MPI_ALLGATHERV;
}
return CPM_SUCCESS;
}
////////////////////////////////////////////////////////////////////////////////
// cpm_Wait
cpm_ErrorCode
cpm_BaseParaManager::cpm_Wait( int reqNo )
{
// MPI_Request
MPI_Request *req = m_reqList.Get(reqNo);
if( !req )
{
return CPM_ERROR_INVALID_OBJKEY;
}
// MPI_Wait
MPI_Status status;
if( MPI_Wait( req, &status ) != MPI_SUCCESS )
{
return CPM_ERROR_MPI_WAIT;
}
// 削除
return m_reqList.Delete(reqNo);
}
////////////////////////////////////////////////////////////////////////////////
// cpm_Waitall
cpm_ErrorCode
cpm_BaseParaManager::cpm_Waitall( int count, int reqNoList[] )
{
// MPI_Request
MPI_Status* stat = new MPI_Status [count];
MPI_Request* req = new MPI_Request[count];
int cnt = 0;
for( int i=0;i<count;i++ )
{
MPI_Request *r = m_reqList.Get( reqNoList[i] );
if( r )
{
r[cnt++] = *req;
}
}
if( cnt == 0 )
{
delete [] stat;
delete [] req;
return CPM_ERROR_INVALID_OBJKEY;
}
// MPI_Waitall
if( MPI_Waitall( cnt, req, stat ) != MPI_SUCCESS )
{
delete [] stat;
delete [] req;
return CPM_ERROR_MPI_WAITALL;
}
// 削除
for( int i=0;i<count;i++ )
{
m_reqList.Delete( reqNoList[i] );
}
return CPM_SUCCESS;
}
////////////////////////////////////////////////////////////////////////////////
// cpm_Isend
cpm_ErrorCode
cpm_BaseParaManager::cpm_Isend( void *buf, int count, int datatype, int dest, int *reqNo, int procGrpNo )
{
// MPI_Datatype
MPI_Datatype dtype = cpm_BaseParaManager::GetMPI_Datatype( datatype );
if( dtype == MPI_DATATYPE_NULL )
{
return CPM_ERROR_MPI_INVALID_DATATYPE;
}
// MPI_Request
MPI_Request *req = m_reqList.Create();
if( !req )
{
return CPM_ERROR_INVALID_PTR;
}
// Isend
cpm_ErrorCode ret = Isend( dtype, buf, count, dest, req, procGrpNo );
if( ret != MPI_SUCCESS )
{
delete req;
return ret;
}
// MPI_Requestを登録
if( (*reqNo = m_reqList.Add(req) ) < 0 )
{
delete req;
return CPM_ERROR_REGIST_OBJKEY;
}
return CPM_SUCCESS;
}
////////////////////////////////////////////////////////////////////////////////
// cpm_Irecv
cpm_ErrorCode
cpm_BaseParaManager::cpm_Irecv( void *buf, int count, int datatype, int source, int *reqNo, int procGrpNo )
{
// MPI_Datatype
MPI_Datatype dtype = cpm_BaseParaManager::GetMPI_Datatype( datatype );
if( dtype == MPI_DATATYPE_NULL )
{
return CPM_ERROR_MPI_INVALID_DATATYPE;
}
// Irecv
MPI_Request req;
cpm_ErrorCode ret = Irecv( dtype, buf, count, source, &req, procGrpNo );
if( ret != MPI_SUCCESS )
{
return ret;
}
// MPI_Requestを登録
MPI_Request *r = m_reqList.Create();
*r = req;
if( (*reqNo = m_reqList.Add(r) ) < 0 )
{
delete r;
return CPM_ERROR_REGIST_OBJKEY;
}
return CPM_SUCCESS;
}
| 23.86627 | 119 | 0.577886 |
9a666e5b485039da1cb223c3e70bf30f808f2da4 | 28 | cpp | C++ | DataStructures/Src/Precompiled.cpp | ikarusx/ModernCpp | 8c0111dec2d0a2a183250e2f9594573b99687ec5 | [
"MIT"
] | null | null | null | DataStructures/Src/Precompiled.cpp | ikarusx/ModernCpp | 8c0111dec2d0a2a183250e2f9594573b99687ec5 | [
"MIT"
] | null | null | null | DataStructures/Src/Precompiled.cpp | ikarusx/ModernCpp | 8c0111dec2d0a2a183250e2f9594573b99687ec5 | [
"MIT"
] | null | null | null |
#include "Precompiled.hpp"
| 9.333333 | 26 | 0.75 |
9a6726017803c35221f177ec07786cb6a428563f | 10,074 | cpp | C++ | coh2_rgt_extractor/Rainman_src/CRgdHashTable.cpp | tranek/coh2_rgt_extractor | dba2db9a06d3f31fb815ca865181d8f631306522 | [
"MIT"
] | 1 | 2016-09-24T14:57:56.000Z | 2016-09-24T14:57:56.000Z | coh2_rgt_extractor/Rainman_src/CRgdHashTable.cpp | tranek/coh2_rgt_extractor | dba2db9a06d3f31fb815ca865181d8f631306522 | [
"MIT"
] | null | null | null | coh2_rgt_extractor/Rainman_src/CRgdHashTable.cpp | tranek/coh2_rgt_extractor | dba2db9a06d3f31fb815ca865181d8f631306522 | [
"MIT"
] | null | null | null | /*
Rainman Library
Copyright (C) 2006 Corsix <corsix@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "CRgdHashTable.h"
#include "memdebug.h"
#include "Exception.h"
extern "C" {
typedef unsigned long int ub4; /* unsigned 4-byte quantities */
typedef unsigned char ub1;
ub4 hash(ub1 * k,ub4 length,ub4 initval);
ub4 hash3(ub1 * k,ub4 length,ub4 initval);
}
static char* mystrdup(const char* sStr)
{
char* s = new char[strlen(sStr) + 1];
if(s == 0) return 0;
strcpy(s, sStr);
return s;
}
CRgdHashTable::CRgdHashTable(void)
{
for(int i = 1; i < 10000; ++i)
{
char sBuf[24];
_Value Val;
Val.bCustom = false;
Val.sString = CHECK_MEM(mystrdup(itoa(i,sBuf,10)));
m_mHashTable[hash((ub1*)sBuf, (ub4) strlen(sBuf), 0)] = Val;
}
}
CRgdHashTable::~CRgdHashTable(void)
{
_Clean();
}
void CRgdHashTable::New()
{
_Clean();
}
void CRgdHashTable::FillUnknownList(std::vector<unsigned long>& oList)
{
for(std::map<unsigned long, CRgdHashTable::_Value>::iterator itr = m_mHashTable.begin(); itr != m_mHashTable.end(); ++itr)
{
if(itr->second.sString == 0) oList.push_back(itr->first);
}
}
static char* fgetline(FILE *f, unsigned int iInitSize = 32)
{
unsigned int iTotalLen;
if(f == 0) throw new CRainmanException(__FILE__, __LINE__, "No file");
if(iInitSize < 4) iInitSize = 4;
iTotalLen = iInitSize;
char *sBuffer = new char[iInitSize];
char *sReadTo = sBuffer;
if(sBuffer == 0) throw new CRainmanException(0, __FILE__, __LINE__, "Failed to allocate %u", iInitSize);
do
{
if(fgets(sReadTo, iInitSize, f) == 0)
{
if(feof(f))
{
if(sReadTo[strlen(sReadTo) - 1] == '\n') sReadTo[strlen(sReadTo) - 1] = 0;
return sBuffer;
}
delete[] sBuffer;
throw new CRainmanException(__FILE__, __LINE__, "Failed to read string");
}
if(sReadTo[strlen(sReadTo) - 1] == '\n')
{
size_t n = strlen(sReadTo) - 1;
sReadTo[n] = 0;
while(n > 0)
{
--n;
if(sReadTo[n] == '\n' || sReadTo[n] == '\r') sReadTo[n] = 0;
else break;
}
return sBuffer;
}
iTotalLen += iInitSize;
char *sTmp = new char[iTotalLen];
if(sTmp == 0)
{
delete[] sBuffer;
throw new CRainmanException(0, __FILE__, __LINE__, "Failed to allocate %u", iTotalLen);
}
strcpy(sTmp, sBuffer);
delete[] sBuffer;
sBuffer = sTmp;
sReadTo = sBuffer + strlen(sBuffer);
}while(1);
}
void CRgdHashTable::ExtendWithDictionary(const char* sFile, bool bCustom)
{
FILE *fFile = fopen(sFile, "rb");
if(fFile == 0) throw new CRainmanException(0, __FILE__, __LINE__, "Failed to open file \'%s\'", sFile);
while(!feof(fFile))
{
char* sLine;
try
{
sLine = fgetline(fFile);
}
catch(CRainmanException* pE)
{
fclose(fFile);
throw new CRainmanException(__FILE__, __LINE__, "Failed to read line", pE);
}
char *sBaseLine = sLine;
bool bUnk = false;
if( (strncmp(sLine, "# 0x", 4) == 0) && (strncmp(sLine + 12, " is an unknown value!!", 22) == 0))
{
bUnk = true;
sLine[0] = ' ';
sLine[12] = '=';
}
if(sLine[0] != '#')
{
unsigned long iKey = 0;
int iBitsRead = -8;
// Read in key
while((*sLine != '=') && *sLine)
{
if(iBitsRead == -8)
{
if(*sLine == '0') iBitsRead = -4;
}
else if(iBitsRead == -4)
{
if(*sLine == 'x' || *sLine == 'X') iBitsRead = 0;
}
else if(iBitsRead < 32)
{
if(*sLine >= '0' && *sLine <= '9')
{
iKey <<= 4;
iKey |= (*sLine - '0');
iBitsRead += 4;
}
else if(*sLine >= 'a' && *sLine <= 'f')
{
iKey <<= 4;
iKey |= (*sLine - 'a' + 10);
iBitsRead += 4;
}
else if(*sLine >= 'A' && *sLine <= 'F')
{
iKey <<= 4;
iKey |= (*sLine - 'A' + 10);
iBitsRead += 4;
}
}
++sLine;
}
if(*sLine && *sLine == '=')
{
++sLine;
// Read in value
char *sValue = 0;
if(!bUnk)
{
sValue = new char[strlen(sLine) + 1];
if(sValue == 0)
{
delete[] sBaseLine;
fclose(fFile);
throw new CRainmanException(__FILE__, __LINE__, "Failed to allocate memory");
}
char *sTmp = sValue;
memset(sValue, 0, strlen(sLine) + 1);
while(*sLine)
{
if( (*sLine != ' ') && (*sLine != '\t') && (*sLine != '\r') && (*sLine != '\n') )
{
*sTmp = *sLine;
++sTmp;
}
++sLine;
}
}
_Value Val;
Val = m_mHashTable[iKey];
if(Val.sString)
{
Val.bCustom = Val.bCustom && bCustom;
delete[] sValue;
}
else
{
Val.sString = sValue;
Val.bCustom = bCustom;
}
m_mHashTable[iKey] = Val;
}
delete[] sBaseLine;
}
else
{
delete[] sLine;
}
}
fclose(fFile);
}
void CRgdHashTable::XRefWithStringList(const char* sFile)
{
FILE *fFile = fopen(sFile, "rb");
if(fFile == 0) throw new CRainmanException(0, __FILE__, __LINE__, "Failed to open file \'%s\'", sFile);
while(!feof(fFile))
{
char* sLine;
try
{
sLine = fgetline(fFile);
}
catch(CRainmanException* pE)
{
fclose(fFile);
throw new CRainmanException(__FILE__, __LINE__, "Failed to read line", pE);
}
unsigned long iKey = hash((ub1*)sLine, (ub4) strlen(sLine), 0);
if(m_mHashTable.find(iKey) != m_mHashTable.end() && m_mHashTable[iKey].sString == 0)
{
_Value Val;
Val.bCustom = true;
Val.sString = CHECK_MEM(mystrdup(sLine));
m_mHashTable[iKey] = Val;
}
delete[] sLine;
}
}
void CRgdHashTable::SaveCustomKeys(const char* sFile)
{
FILE *fFile = fopen(sFile, "wb");
if(fFile == 0) throw new CRainmanException(0, __FILE__, __LINE__, "Failed to open file \'%s\'", sFile);
fputs("#RGD_DIC\n# This dictionary is generated from any keys that are \'discovered\'\n", fFile);
for(std::map<unsigned long, _Value>::iterator itr = m_mHashTable.begin(); itr != m_mHashTable.end(); ++itr)
{
if(itr->second.bCustom)
{
if(itr->second.sString == 0) fputs("# ", fFile);
// Output key
fputs("0x", fFile);
unsigned long iMask = 0xF0000000;
for(int i = 7; i >= 0; --i)
{
fputc("0123456789ABCDEF"[(itr->first & iMask) >> (i << 2)], fFile);
iMask >>= 4;
}
// Output value
if(itr->second.sString == 0)
{
fputs(" is an unknown value!!\n", fFile);
}
else
{
fputc('=', fFile);
fputs(itr->second.sString, fFile);
fputc('\n', fFile);
}
}
}
fclose(fFile);
}
const char* CRgdHashTable::HashToValue(unsigned long iHash)
{
const char* s = m_mHashTable[iHash].sString;
if(s == 0)
{
m_mHashTable[iHash].bCustom = true;
return 0;
}
return s;
}
unsigned long CRgdHashTable::ValueToHash(const char* sValue)
{
if(sValue[0] == '0' && sValue[1] == 'x')
{
for(int i = 2; i < 10; ++i)
{
if(!(
(sValue[i] >= '0' && sValue[i] <= '9') ||
(sValue[i] >= 'a' && sValue[i] <= 'f') ||
(sValue[i] >= 'A' && sValue[i] <= 'F')
))
goto nothex;
}
if(sValue[10] == 0)
{
unsigned long iKey = 0;
for(int i = 2; i < 10; ++i)
{
iKey <<= 4;
if(sValue[i] >= '0' && sValue[i] <= '9') iKey |= (sValue[i] - '0');
if(sValue[i] >= 'a' && sValue[i] <= 'f') iKey |= (sValue[i] - 'a' + 10);
if(sValue[i] >= 'A' && sValue[i] <= 'F') iKey |= (sValue[i] - 'A' + 10);
}
return iKey;
}
}
nothex:
unsigned long iKey = hash((ub1*)sValue, (ub4) strlen(sValue), 0);
if(m_mHashTable[iKey].sString == 0)
{
_Value Val;
Val.bCustom = false;
const char* sTmp = sValue;
do
{
if( ((*sTmp) < '0') || ((*sTmp) > '9') )
{
Val.bCustom = true;
break;
}
++sTmp;
}while(*sTmp);
Val.sString = CHECK_MEM(mystrdup(sValue));
m_mHashTable[iKey] = Val;
}
return iKey;
}
unsigned long CRgdHashTable::ValueToHashStatic(const char* sValue, size_t iValueLen)
{
if(sValue[0] == '0' && sValue[1] == 'x' && iValueLen == 10)
{
for(int i = 2; i < 10; ++i)
{
if(!(
(sValue[i] >= '0' && sValue[i] <= '9') ||
(sValue[i] >= 'a' && sValue[i] <= 'f') ||
(sValue[i] >= 'A' && sValue[i] <= 'F')
))
goto nothex;
}
unsigned long iKey = 0;
for(int i = 2; i < 10; ++i)
{
iKey <<= 4;
if(sValue[i] >= '0' && sValue[i] <= '9') iKey |= (sValue[i] - '0');
if(sValue[i] >= 'a' && sValue[i] <= 'f') iKey |= (sValue[i] - 'a' + 10);
if(sValue[i] >= 'A' && sValue[i] <= 'F') iKey |= (sValue[i] - 'A' + 10);
}
return iKey;
}
nothex:
unsigned long iKey = hash((ub1*)sValue, (ub4) iValueLen, 0);
return iKey;
}
unsigned long CRgdHashTable::ValueToHashStatic(const char* sValue)
{
if(sValue[0] == '0' && sValue[1] == 'x')
{
for(int i = 2; i < 10; ++i)
{
if(!(
(sValue[i] >= '0' && sValue[i] <= '9') ||
(sValue[i] >= 'a' && sValue[i] <= 'f') ||
(sValue[i] >= 'A' && sValue[i] <= 'F')
))
goto nothex;
}
if(sValue[10] == 0)
{
unsigned long iKey = 0;
for(int i = 2; i < 10; ++i)
{
iKey <<= 4;
if(sValue[i] >= '0' && sValue[i] <= '9') iKey |= (sValue[i] - '0');
if(sValue[i] >= 'a' && sValue[i] <= 'f') iKey |= (sValue[i] - 'a' + 10);
if(sValue[i] >= 'A' && sValue[i] <= 'F') iKey |= (sValue[i] - 'A' + 10);
}
return iKey;
}
}
nothex:
unsigned long iKey = hash((ub1*)sValue, (ub4) strlen(sValue), 0);
return iKey;
}
CRgdHashTable::_Value::_Value()
{
sString = 0;
bCustom = false;
}
void CRgdHashTable::_Clean()
{
for(std::map<unsigned long, _Value>::iterator itr = m_mHashTable.begin(); itr != m_mHashTable.end(); ++itr)
{
if(itr->second.sString) delete[] itr->second.sString;
}
}
| 23.105505 | 123 | 0.571074 |
9a6b74f17a9d9e386a1fb0d561ea3f9cb5dada08 | 1,518 | hpp | C++ | include/pichi/common/endpoint.hpp | imuzi/pichi | 5ad1372bff4c3bffd201ccfb41df6c839c83c506 | [
"BSD-3-Clause"
] | 164 | 2018-09-28T09:41:05.000Z | 2021-11-13T09:17:07.000Z | include/pichi/common/endpoint.hpp | imuzi/pichi | 5ad1372bff4c3bffd201ccfb41df6c839c83c506 | [
"BSD-3-Clause"
] | 5 | 2018-12-21T13:40:02.000Z | 2021-07-24T04:23:44.000Z | include/pichi/common/endpoint.hpp | imuzi/pichi | 5ad1372bff4c3bffd201ccfb41df6c839c83c506 | [
"BSD-3-Clause"
] | 14 | 2018-12-18T09:35:42.000Z | 2021-07-06T12:16:34.000Z | #ifndef PICHI_COMMON_ENDPOINT_HPP
#define PICHI_COMMON_ENDPOINT_HPP
#include <algorithm>
#include <functional>
#include <iterator>
#include <pichi/common/buffer.hpp>
#include <pichi/common/enumerations.hpp>
#include <string>
#include <string_view>
#include <type_traits>
namespace std {
inline string to_string(string_view sv) { return {cbegin(sv), cend(sv)}; }
} // namespace std
namespace pichi {
struct Endpoint {
EndpointType type_;
std::string host_;
uint16_t port_;
};
template <typename Int> void hton(Int src, MutableBuffer<uint8_t> dst)
{
static_assert(std::is_integral_v<Int>, "input type must be integral.");
assert(sizeof(Int) <= dst.size());
auto p = reinterpret_cast<uint8_t*>(&src);
std::reverse_copy(p, p + sizeof(Int), std::begin(dst));
}
template <typename Int> Int ntoh(ConstBuffer<uint8_t> src)
{
static_assert(std::is_integral_v<Int>, "output type must be integral.");
assert(src.size() >= sizeof(Int));
Int dst;
std::reverse_copy(std::cbegin(src), std::cend(src), reinterpret_cast<uint8_t*>(&dst));
return dst;
}
extern size_t serializeEndpoint(Endpoint const&, MutableBuffer<uint8_t>);
extern Endpoint parseEndpoint(std::function<void(MutableBuffer<uint8_t>)>);
extern EndpointType detectHostType(std::string_view);
extern Endpoint makeEndpoint(std::string_view, uint16_t);
extern Endpoint makeEndpoint(std::string_view, std::string_view);
extern bool operator==(Endpoint const&, Endpoint const&);
} // namespace pichi
#endif // PICHI_COMMON_ENDPOINT_HPP
| 27.107143 | 88 | 0.746377 |
9a6c9753edc8507678f6e6f21f471beed68494d1 | 3,668 | cpp | C++ | oneEngine/oneGame/source/renderer/camera/RrRTCamera.cpp | jonting/1Engine | f22ba31f08fa96fe6405ebecec4f374138283803 | [
"BSD-3-Clause"
] | 8 | 2017-12-08T02:59:31.000Z | 2022-02-02T04:30:03.000Z | oneEngine/oneGame/source/renderer/camera/RrRTCamera.cpp | jonting/1Engine | f22ba31f08fa96fe6405ebecec4f374138283803 | [
"BSD-3-Clause"
] | 2 | 2021-04-16T03:44:42.000Z | 2021-08-30T06:48:44.000Z | oneEngine/oneGame/source/renderer/camera/RrRTCamera.cpp | jonting/1Engine | f22ba31f08fa96fe6405ebecec4f374138283803 | [
"BSD-3-Clause"
] | 1 | 2021-04-16T02:09:54.000Z | 2021-04-16T02:09:54.000Z | #include "core/time/time.h"
#include "renderer/state/Settings.h"
#include "renderer/types/ObjectSettings.h"
#include "renderer/texture/RrRenderTexture.h"
#include "renderer/state/RrHybridBufferChain.h"
#include "RrRTCamera.h"
RrRTCamera::RrRTCamera (
renderer::rrInternalSettings* const targetSettings,
Vector2i const& targetSize,
Real renderFramerate,
bool autoRender
) : RrCamera (),
m_renderCounter(0),
m_renderStepTime(1.0F / renderFramerate),
m_autoRender(autoRender)
{
layerVisibility[renderer::kRenderLayerSecondary] = false;
layerVisibility[renderer::kRenderLayerV2D] = false;
// Set render texture immediately
//m_renderTexture = targetTexture;
// Create the buffer chain immediately.
SetTargetInfo(targetSettings, targetSize);
}
RrRTCamera::~RrRTCamera ( void )
{
;
}
// SetTargetInfo(settings, size) : Sets up render target for the camera.
// Will free previously created buffers.
// Returns true on successful creation.
bool RrRTCamera::SetTargetInfo ( renderer::rrInternalSettings* const settings, Vector2i const& size )
{
m_usedTargetSettings = *settings;
m_targetSize = size;
gpu::ErrorCode status = m_chain.CreateTargetBufferChain(&m_usedTargetSettings, size);
return status == gpu::kError_SUCCESS;
}
// FreeTarget() : Frees up the render target.
bool RrRTCamera::FreeTarget ( void )
{
bool status = m_chain.FreeTargetBufferChain();
return status;
}
// Update
void RrRTCamera::LateUpdate ( void )
{
// If autorender, then tell scene to update at given framerate
if ( m_autoRender )
{
if ( m_needsNewPasses ) {
m_needsNewPasses = false;
}
m_renderCounter += Time::deltaTime;
if ( m_renderCounter > m_renderStepTime )
{
m_renderCounter = 0.0F; // TODO: why not a subtract+limit
m_needsNewPasses = true;
}
}
// However, if there's not a valid render target, turn rendering off
//if ( m_renderTexture == NULL )
if ( !active )
{
m_needsNewPasses = false;
}
// Perform late update, which will update the viewport size to an incorrect value:
RrCamera::LateUpdate();
// So we set the proper viewport now:
viewport.pos.x = viewportPercent.pos.x * m_targetSize.x;
viewport.pos.y = viewportPercent.pos.y * m_targetSize.y;
viewport.size.x = viewportPercent.size.x * m_targetSize.x;
viewport.size.y = viewportPercent.size.y * m_targetSize.y;
}
// Update Camera Matrix
void RrRTCamera::UpdateMatrix ( void )
{
// Update the projection matrix normally.
RrCamera::UpdateMatrix();
// Update the texture matrix after the camera matrix is updated
UpdateTextureMatrix();
}
// Update Texture Matrix
void RrRTCamera::UpdateTextureMatrix ( void )
{
const Real bias[16] = {
0.5F, 0.0F, 0.0F, 0.0F,
0.0F, 0.5F, 0.0F, 0.0F,
0.0F, 0.0F, 0.5F, 0.0F,
0.5F, 0.5F, 0.5F, 1.0F
};
const Matrix4x4 biasMatrix ( bias );
//textureMatrix = viewTransform * projTransform * biasMatrix;
textureMatrix = viewprojMatrix * biasMatrix;
}
// PassCount() : Returns number of passes this camera will render
// Must be 1 or greater in order to render.
int RrRTCamera::PassCount ( void )
{
return 1;
}
// PassRetrieve(array, array_size) : Writes pass information into the array given in
// Will write either PassCount() or maxPasses passes, whatever is smaller.
void RrRTCamera::PassRetrieve ( const rrCameraPassInput* input, rrCameraPass* passList )
{
RrCamera::PassRetrieve(input, passList); // TODO: Proper buffer chain!
if (input->m_maxPasses > 0)
{
passList[0].m_bufferChain = &m_chain;
}
}
void RrRTCamera::RenderBegin ( void )
{
// Call the parent one
RrCamera::RenderBegin();
// bind to m_renderTexture ???
// todo
}
void RrRTCamera::RenderEnd ( void )
{
RrCamera::RenderEnd();
}
| 26.014184 | 101 | 0.730098 |
9a7253aa706747c7104c81bf942ca292d57d6aa9 | 1,303 | cpp | C++ | src/trace/GLLib/Texture/TextureTarget.cpp | attila-sim/attila-sim | a64b57240b4e10dc4df7f21eff0232b28df09532 | [
"BSD-3-Clause"
] | 23 | 2016-01-14T04:47:13.000Z | 2022-01-13T14:02:08.000Z | src/trace/GLLib/Texture/TextureTarget.cpp | attila-sim/attila-sim | a64b57240b4e10dc4df7f21eff0232b28df09532 | [
"BSD-3-Clause"
] | 2 | 2018-03-25T14:39:20.000Z | 2022-03-18T05:11:21.000Z | src/trace/GLLib/Texture/TextureTarget.cpp | attila-sim/attila-sim | a64b57240b4e10dc4df7f21eff0232b28df09532 | [
"BSD-3-Clause"
] | 17 | 2016-02-13T05:35:35.000Z | 2022-03-24T16:05:40.000Z | /**************************************************************************
*
* Copyright (c) 2002 - 2011 by Computer Architecture Department,
* Universitat Politecnica de Catalunya.
* All rights reserved.
*
* The contents of this file may not be disclosed to third parties,
* copied or duplicated in any form, in whole or in part, without the
* prior permission of the authors, Computer Architecture Department
* and Universitat Politecnica de Catalunya.
*
*/
#include "TextureTarget.h"
using namespace libgl;
TextureTarget::TextureTarget(GLuint target) : BaseTarget(target)
{
if ( target != GL_TEXTURE_1D && target != GL_TEXTURE_2D && target != GL_TEXTURE_3D &&
target != GL_TEXTURE_CUBE_MAP )
panic("TextureTarget", "TextureTarget", "Unexpected texture target");
TextureObject* defTex = new TextureObject(0, target); // create a default object
defTex->setTarget(*this);
setCurrent(*defTex);
setDefault(defTex);
/*****************************************
* CONFIGURE DEFAULT TEXTURE OBJECT HERE *
*****************************************/
}
TextureObject* TextureTarget::createObject(GLuint name)
{
TextureObject* to = new TextureObject(name, getName());
to->setTarget(*this);
return to;
}
| 30.302326 | 90 | 0.604758 |
9a77b287a6fd0647a604244033677071702b2567 | 187,010 | cpp | C++ | libs/graph_parallel/test/performance_test.cpp | thejkane/AGM | 4d5cfe9522461d207ceaef7d90c1cd10ce9b469c | [
"BSL-1.0"
] | 1 | 2021-09-03T10:22:04.000Z | 2021-09-03T10:22:04.000Z | libs/graph_parallel/test/performance_test.cpp | thejkane/AGM | 4d5cfe9522461d207ceaef7d90c1cd10ce9b469c | [
"BSL-1.0"
] | null | null | null | libs/graph_parallel/test/performance_test.cpp | thejkane/AGM | 4d5cfe9522461d207ceaef7d90c1cd10ce9b469c | [
"BSL-1.0"
] | null | null | null | // Copyright (C) 2014 The Trustees of Indiana University.
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Authors: Nicholas Edmonds
// Andrew Lumsdaine
// Marcin Zalewski
// Thejaka Kanewala
#define LIB_CDS 1
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#endif
#include <stdint.h>
#include <inttypes.h>
#include <cstdlib>
#include <math.h>
//#define DISABLE_SELF_SEND_CHECK
//#define AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
//#define PBGL2_PRINT_WORK_STATS
// #define PRINT_STATS
// #define PRINT_DEBUG
#define AMPLUSPLUS_PRINT_HIT_RATES
#define BFS_SV_CC_HACK
// #define DS_SHARED_REDUCTIONS
// #define BFS_VECTOR
#define DISABLE_BFS_BITMAP
#ifdef __bgp__
#define BGP_REPORT_MEMORY 1 // if >1 all ranks will report memory usage
#endif
//#define NUMBER_COMPONENTS
// #define PBGL_TIMING // turn on local component counting, sequential timing, and such in CC
// #define PRINT_ET
#define BARRIER_TRANS
// #define CLONE
#define CALCULATE_GTEPS 1
#include <am++/am++.hpp>
#include <am++/mpi_transport.hpp>
#include <am++/counter_coalesced_message_type.hpp>
#include <boost/graph/distributed/time_calc.hpp>
#include <boost/iterator/transform_iterator.hpp>
#include <boost/graph/use_mpi.hpp>
#include <boost/property_map/parallel/distributed_property_map.hpp>
#include <boost/property_map/property_map.hpp>
#include <boost/graph/distributed/compressed_sparse_row_graph.hpp>
#include <boost/graph/recursive_rmat_generator.hpp>
#include <boost/graph/erdos_renyi_generator.hpp>
#include <boost/graph/graph500_generator.hpp>
#include <boost/graph/permute_graph.hpp>
#include <boost/graph/parallel/algorithm.hpp> // for all_reduce
#include <boost/graph/breadth_first_search.hpp>
#include <boost/graph/distributed/delta_stepping_shortest_paths.hpp>
#include <boost/graph/distributed/delta_stepping_shortest_paths_node.hpp>
#include <boost/graph/distributed/delta_stepping_shortest_paths_thread.hpp>
#include <boost/graph/distributed/delta_stepping_shortest_paths_numa.hpp>
#include <boost/graph/distributed/mis.hpp>
#include <boost/graph/distributed/mis_delta.hpp>
#include <boost/graph/distributed/luby_mis.hpp>
#include <boost/graph/distributed/kla_sssp_buffer.hpp>
#include <boost/graph/distributed/kla_sssp_numa.hpp>
#include <boost/graph/distributed/kla_sssp_node.hpp>
#include <boost/graph/distributed/kla_sssp_thread.hpp>
#include <boost/graph/distributed/distributed_control.hpp>
#include <boost/graph/distributed/distributed_control_node.hpp>
#include <boost/graph/distributed/distributed_control_pheet.hpp>
#include <boost/graph/distributed/priority_q_defs.hpp>
#include <boost/graph/distributed/distributed_control_chaotic.hpp>
#include <boost/graph/distributed/cc_dc.hpp>
#include <boost/graph/distributed/cc_chaotic.hpp>
#include <boost/graph/distributed/delta_stepping_cc.hpp>
#include <boost/graph/distributed/cc_diff_dc.hpp>
#include <boost/graph/distributed/level_sync_cc.hpp>
#include <boost/graph/distributed/connected_components.hpp>
#include <boost/graph/distributed/sv_cc.hpp>
#include <boost/graph/distributed/page_rank.hpp>
#include <boost/graph/distributed/graph_reader.hpp>
#include <boost/graph/relax.hpp>
#include <boost/random/linear_congruential.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/property_map/parallel/global_index_map.hpp>
#include <boost/parallel/append_buffer.hpp>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics.hpp>
#include <parallel/algorithm>
#include <algorithm> // for std::min, std::max
#include <functional>
#include <cds/init.h> // for cds::Initialize and cds::Terminate
#include <cds/gc/hp.h> // for cds::HP (Hazard Pointer) SMR
//#include "statistics.h"
#define HAS_NOT_BEEN_SEEN
#ifdef DISABLE_SELF_SEND_CHECK
#warning "==================^^^^^Self send check is disabled !^^^^^======================="
#endif
int _RANK;
using namespace boost;
using boost::parallel::all_reduce;
using boost::parallel::maximum;
using std::max;
#include <time.h>
#include <sys/time.h>
/*typedef double time_type;
inline time_type get_time()
{
return MPI_Wtime();
#if 0
timeval tp;
gettimeofday(&tp, 0);
return tp.tv_sec + tp.tv_usec / 1000000.0;
#endif
}*/
std::string print_time(time_type t)
{
std::ostringstream out;
out << std::setiosflags(std::ios::fixed) << std::setprecision(2) << t;
return out.str();
}
struct flip_pair {
template <typename T>
T operator()(const T& x) const {
// flipping edges by keeping same weight
return std::make_pair(x.second.first, std::make_pair(x.first, x.second.second));
}
};
#define PRINT_GRAPH500_STATS(lbl, israte) \
do { \
printf ("Min(%s): %20.17e\n", lbl, stats[0]); \
printf ("First Quartile(%s): %20.17e\n", lbl, stats[1]); \
printf ("Median(%s): %20.17e\n", lbl, stats[2]); \
printf ("Third Quartile(%s): %20.17e\n", lbl, stats[3]); \
printf ("Max(%s): %20.17e\n", lbl, stats[4]); \
if (!israte) { \
printf ("Mean(%s): %20.17e\n", lbl, stats[5]); \
printf ("Stddev(%s): %20.17e\n", lbl, stats[6]); \
} else { \
printf ("Harmonic Mean(%s): %20.17e\n", lbl, stats[7]); \
printf ("Harmonic Stddev(%s): %20.17e\n", lbl, stats[8]); \
} \
} while (0)
extern void statistics (double *out, double *data, size_t n);
static int
dcmp (const void *a, const void *b)
{
const double da = *(const double*)a;
const double db = *(const double*)b;
if (da > db) return 1;
if (db > da) return -1;
if (da == db) return 0;
fprintf (stderr, "No NaNs permitted in output.\n");
abort ();
return 0;
}
void statistics (double *out, double *data, size_t n)
{
long double s, mean;
double t;
int k;
/* Quartiles */
qsort (data, n, sizeof (*data), dcmp);
out[0] = data[0];
t = (n+1) / 4.0;
k = (int) t;
if (t == k)
out[1] = data[k];
else
out[1] = 3*(data[k]/4.0) + data[k+1]/4.0;
t = (n+1) / 2.0;
k = (int) t;
if (t == k)
out[2] = data[k];
else
out[2] = data[k]/2.0 + data[k+1]/2.0;
t = 3*((n+1) / 4.0);
k = (int) t;
if (t == k)
out[3] = data[k];
else
out[3] = data[k]/4.0 + 3*(data[k+1]/4.0);
out[4] = data[n-1];
s = data[n-1];
for (k = n-1; k > 0; --k)
s += data[k-1];
mean = s/n;
out[5] = mean;
s = data[n-1] - mean;
s *= s;
for (k = n-1; k > 0; --k) {
long double tmp = data[k-1] - mean;
s += tmp * tmp;
}
out[6] = sqrt (s/(n-1));
s = (data[0]? 1.0L/data[0] : 0);
for (k = 1; k < n; ++k)
s += (data[k]? 1.0L/data[k] : 0);
out[7] = n/s;
mean = s/n;
/*
Nilan Norris, The Standard Errors of the Geometric and Harmonic
Means and Their Application to Index Numbers, 1940.
http://www.jstor.org/stable/2235723
*/
s = (data[0]? 1.0L/data[0] : 0) - mean;
s *= s;
for (k = 1; k < n; ++k) {
long double tmp = (data[k]? 1.0L/data[k] : 0) - mean;
s += tmp * tmp;
}
s = (sqrt (s)/(n-1)) * out[7] * out[7];
out[8] = s;
}
//
// Performance counters
//
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
std::vector<time_type> epoch_times;
// These should really be atomic
typedef unsigned long long flush_type;
typedef amplusplus::detail::atomic<flush_type> atomic_flush_type;
#define FLUSH_MPI_TYPE MPI_UNSIGNED_LONG
std::unique_ptr<atomic_flush_type[]> flushes;
flush_type flushes_size;
std::vector<flush_type> all_flushes, cumulative_flushes;
atomic_flush_type full{}, messages_received{};
flush_type all_full{}, cumulative_full{}, all_messages{}, cumulative_messages{};
void print_and_clear_epoch_times()
{
if(_RANK == 0) {
std::cout << "There were " << epoch_times.size() << " epochs." << std::endl;
std::cout << "Epoch times ";
BOOST_FOREACH(time_type t, epoch_times) {
std::cout << print_time(t) << " ";
}
std::cout << "\n";
}
epoch_times.clear();
}
void clear_buffer_stats() {
for(unsigned int i = 0; i < flushes_size; ++i)
flushes[i] = 0;
full = 0;
messages_received = 0;
}
void clear_cumulative_buffer_stats() {
for(unsigned int i = 0; i < flushes_size; ++i)
cumulative_flushes[i] = 0;
cumulative_full = 0;
cumulative_messages = 0;
}
void print_buffer_stats() {
unsigned long long sum = 0;
unsigned long long number_of_buffers = 0;
flush_type tmp_flushes[flushes_size];
for(int i = 0; i < flushes_size; ++i)
tmp_flushes[i] = flushes[i].load();
flush_type tmp_full = full.load();
flush_type tmp_messages = messages_received.load();
MPI_Allreduce(&tmp_flushes, &all_flushes.front(), flushes_size, FLUSH_MPI_TYPE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&tmp_full, &all_full, 1, FLUSH_MPI_TYPE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&tmp_messages, &all_messages, 1, FLUSH_MPI_TYPE, MPI_SUM, MPI_COMM_WORLD);
if(_RANK == 0) std::cout << "Flushes: ";
for(unsigned int i = 0; i < all_flushes.size(); ++i) {
if(all_flushes[i] != 0) {
if(_RANK == 0) std::cout << i+1 << "->" << all_flushes[i] << " ";
sum += (i + 1) * all_flushes[i];
number_of_buffers += all_flushes[i];
cumulative_flushes[i] += all_flushes[i];
}
}
cumulative_full += all_full;
cumulative_messages += all_messages;
if(_RANK == 0) {
std::cout << std::endl;
std::cout << "There were " << number_of_buffers << " incomplete flushes with the average size of a flush of " << (number_of_buffers != 0 ? sum/number_of_buffers : 0) << std::endl;
std::cout << "Full buffers: " << all_full << std::endl;
std::cout << "Messages: " << all_messages << std::endl;
}
}
namespace amplusplus {
namespace performance_counters {
void hook_flushed_message_size(amplusplus::rank_type dest, size_t count, size_t elt_size)
{
if(count <= flushes_size)
flushes[count-1]++;
#ifdef PRINT_STATS
time_type t = get_time();
fprintf(stderr, "Flush: %d bytes to %d at %f\n", (count * elt_size), dest, t);
#endif
}
void hook_full_buffer_send(amplusplus::rank_type dest, size_t count, size_t elt_size)
{
full++;
#ifdef PRINT_STATS
time_type t = get_time();
fprintf(stderr, "Full buffer: %d bytes to %d at %f\n", (count * elt_size), dest, t);
#endif
}
void hook_message_received(amplusplus::rank_type src, size_t count, size_t elt_size)
{
messages_received += count;
#ifdef PRINT_STATS
time_type t = get_time();
fprintf(stderr, "%d: Message received: %d bytes from %d at %f\n", _RANK, (count * elt_size), src, t);
#endif
}
void hook_begin_epoch(amplusplus::transport& trans)
{
epoch_times.push_back(get_time());
}
void hook_epoch_finished(amplusplus::transport& trans)
{
epoch_times.back() = get_time() - epoch_times.back();
}
}
}
#endif // AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
// Hit rates
#ifdef AMPLUSPLUS_PRINT_HIT_RATES
unsigned long long cumulative_hits, cumulative_tests;
void print_and_accumulate_cache_stats(std::pair<unsigned long long, unsigned long long> stats) {
unsigned long long hits, tests;
MPI_Allreduce(&stats.first, &hits, 1, MPI_UNSIGNED_LONG, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&stats.second, &tests, 1, MPI_UNSIGNED_LONG, MPI_SUM, MPI_COMM_WORLD);
cumulative_hits += hits;
cumulative_tests += tests;
if(_RANK == 0) {
std::cout << "Cache hit rates: " << hits << " hits, " << tests << " tests. Success ratio: " << (double)hits / (double)tests << "." << std::endl;
}
}
#endif // AMPLUSPLUS_PRINT_HIT_RATES
#ifdef PBGL2_PRINT_WORK_STATS
typedef std::tuple<unsigned long long, unsigned long long, unsigned long long, unsigned long long> work_stats_t;
typedef std::tuple<unsigned long long, unsigned long long, unsigned long long, unsigned long long, unsigned long long, unsigned long long> all_work_stats_t;
// Distributed control work stats
all_work_stats_t dc_stats, ds_stats;
void clear_cumulative_work_stats() {
dc_stats = all_work_stats_t{ 0ul, 0ul, 0ul, 0ul, 0ul, 0ul };
ds_stats = all_work_stats_t{ 0ul, 0ul, 0ul, 0ul, 0ul, 0ul };
}
void print_q_stats(unsigned long long max_q_sz,
unsigned long long avg_max_q_size = 0) {
unsigned long long max, min;
MPI_Allreduce(&max_q_sz, &max, 1, MPI_UNSIGNED_LONG, MPI_MAX, MPI_COMM_WORLD);
MPI_Allreduce(&max_q_sz, &min, 1, MPI_UNSIGNED_LONG, MPI_MIN, MPI_COMM_WORLD);
if (_RANK == 0)
std::cout << "Maximum max q size : " <<
max << " minimum max q size : " << min << std::endl;
if (avg_max_q_size != 0) {
int world_size;
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
unsigned long long avg_max_sum;
MPI_Allreduce(&avg_max_q_size, &avg_max_sum, 1, MPI_UNSIGNED_LONG, MPI_SUM, MPI_COMM_WORLD);
if (_RANK == 0)
std::cout << "Average maximum queue size : " << (avg_max_sum / world_size) << std::endl;
}
}
void print_and_accumulate_work_stats(work_stats_t stats, all_work_stats_t &cummulative_stats, size_t edges_traverse) {
work_stats_t temp_stats;
MPI_Allreduce(&std::get<0>(stats), &std::get<0>(temp_stats), 1, MPI_UNSIGNED_LONG, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&std::get<1>(stats), &std::get<1>(temp_stats), 1, MPI_UNSIGNED_LONG, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&std::get<2>(stats), &std::get<2>(temp_stats), 1, MPI_UNSIGNED_LONG, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&std::get<3>(stats), &std::get<3>(temp_stats), 1, MPI_UNSIGNED_LONG, MPI_SUM, MPI_COMM_WORLD);
if(_RANK == 0) std::cout << "Useful work: " << std::get<0>(temp_stats) << ", invalidated work: " << std::get<1>(temp_stats) << ", useless work: " << std::get<2>(temp_stats) << ", rejected work: " << std::get<3>(temp_stats) << ", number of edges traversed : " << edges_traverse << ", level of ordering: " << (std::get<0>(temp_stats) + std::get<2>(temp_stats) - (2*edges_traverse)-1) << ", extra edge relaxes: " << (std::get<1>(temp_stats)-std::get<3>(temp_stats)) << std::endl;
std::get<0>(cummulative_stats) += std::get<0>(temp_stats);
std::get<1>(cummulative_stats) += std::get<1>(temp_stats);
std::get<2>(cummulative_stats) += std::get<2>(temp_stats);
std::get<3>(cummulative_stats) += std::get<3>(temp_stats);
std::get<4>(cummulative_stats) += (std::get<0>(temp_stats) + std::get<2>(temp_stats) - (2*edges_traverse) - 1); // ordering
std::get<5>(cummulative_stats) += (std::get<1>(temp_stats)-std::get<3>(temp_stats)); // extra relaxes
}
// TODO: Unify these two macros? We probably don't need macros at all. This is just a leftover from the previous test harness.
#define PBGL2_DC_PRINT \
<< "\nUseful work: " << (std::get<0>(dc_stats) / num_sources) << " (per source), invalidated work: " << (std::get<1>(dc_stats) / num_sources) << " (per source), useless work: " << (std::get<2>(dc_stats)/num_sources) << " (per source), rejected work: " << (std::get<3>(dc_stats)/num_sources) << " (per source). Rejected/useful ratio: " << ((double)std::get<3>(dc_stats) / (double)std::get<0>(dc_stats)) << ". Invalidated/useful ratio: " << ((double)std::get<1>(dc_stats) / (double)std::get<0>(dc_stats)) << ", level of ordering: " << std::get<4>(dc_stats) << ", extra edge relaxes: " << std::get<5>(dc_stats)
#define PBGL2_DS_PRINT \
<< "\nUseful work: " << (std::get<0>(ds_stats) / num_sources) << " (per source), invalidated work: " << (std::get<1>(ds_stats) / num_sources) << " (per source), useless work: " << (std::get<2>(ds_stats)/num_sources) << " (per source), rejected work: " << (std::get<3>(ds_stats)/num_sources) << " (per source). Rejected/useful ratio: " << ((double)std::get<3>(ds_stats) / (double)std::get<0>(ds_stats)) << ". Invalidated/useful ratio: " << ((double)std::get<1>(ds_stats) / (double)std::get<0>(ds_stats)) << ", level of ordering: " << (std::get<4>(ds_stats)/num_sources) << ", extra edge relaxes: " << (std::get<5>(ds_stats)/num_sources)
#endif // PBGL2_PRINT_WORK_STATS
//
// Edge properties
//
typedef int32_t weight_type; // Needed so atomics are available on MacOS
struct WeightedEdge {
WeightedEdge(weight_type weight = 0) : weight(weight) { }
weight_type weight;
};
namespace amplusplus {
template<>
struct make_mpi_datatype<WeightedEdge> : make_mpi_datatype_base {
make_mpi_datatype<weight_type> dt1;
scoped_mpi_datatype dt;
make_mpi_datatype(): dt1() {
int blocklengths[1] = {1};
MPI_Aint displacements[1];
WeightedEdge test_object;
MPI_Aint test_object_ptr;
MPI_Get_address(&test_object, &test_object_ptr);
MPI_Get_address(&test_object.weight, &displacements[0]);
displacements[0] -= test_object_ptr;
MPI_Datatype types[1] = {dt1.get()};
MPI_Type_create_struct(1, blocklengths, displacements, types, dt.get_ptr());
MPI_Type_commit(dt.get_ptr());
}
MPI_Datatype get() const {return dt;}
};
}
//
// Edge weight generator iterator
//
template<typename F, typename RandomGenerator>
class generator_iterator
{
public:
typedef std::input_iterator_tag iterator_category;
typedef typename F::result_type value_type;
typedef const value_type& reference;
typedef const value_type* pointer;
typedef void difference_type;
explicit
generator_iterator(RandomGenerator& gen, const F& f = F())
: f(f), gen(&gen)
{
value = this->f(gen);
}
reference operator*() const { return value; }
pointer operator->() const { return &value; }
generator_iterator& operator++()
{
value = f(*gen);
return *this;
}
generator_iterator operator++(int)
{
generator_iterator temp(*this);
++(*this);
return temp;
}
bool operator==(const generator_iterator& other) const
{ return f == other.f; }
bool operator!=(const generator_iterator& other) const
{ return !(*this == other); }
private:
F f;
RandomGenerator* gen;
value_type value;
};
template<typename F, typename RandomGenerator>
inline generator_iterator<F, RandomGenerator>
make_generator_iterator( RandomGenerator& gen, const F& f)
{ return generator_iterator<F, RandomGenerator>(gen, f); }
template <typename Graph, typename DistanceMap, typename WeightMap>
size_t get_gteps(amplusplus::transport& trans, Graph& g, DistanceMap& distance, const WeightMap& weight) {
distance.set_consistency_model(boost::parallel::cm_forward);
distance.set_max_ghost_cells(0);
size_t gteps = 0;
{
amplusplus::scoped_epoch epoch(g.transport());
size_t dist = std::numeric_limits<size_t>::max();
BGL_FORALL_VERTICES_T(v, g, Graph) {
dist = get(distance, v);
if(dist < std::numeric_limits<size_t>::max()) {
BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {
gteps+=1;
//get(distance, target(e, g));
}
}
}
}
gteps = gteps / 2; // we are considering an undirected graph
return gteps;
}
template <typename Graph, typename DistanceMap, typename WeightMap, typename Vertex>
size_t count_edges(amplusplus::transport& trans, Graph& g, DistanceMap& distance, const WeightMap& weight, const Vertex source) {
distance.set_consistency_model(boost::parallel::cm_forward);
distance.set_max_ghost_cells(0);
size_t gteps = 0;
{
amplusplus::scoped_epoch epoch(g.transport());
size_t dist = std::numeric_limits<size_t>::max();
BGL_FORALL_VERTICES_T(v, g, Graph) {
dist = get(distance, v);
if(dist < std::numeric_limits<size_t>::max()) {
BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {
// check whether this is a self loop; if self loop dont count it
if (target(e,g) == v)
continue;
gteps+=1;
//get(distance, target(e, g));
}
}
}
}
return gteps;
}
template<typename MessageType>
class threaded_distributor {
public:
threaded_distributor(MessageType& mtype) : msg_type(mtype) {}
void operator()() {
}
template <typename InIter, typename Flip>
void operator()(int tid, InIter begin, InIter end, const Flip& flip,
amplusplus::transport& trans) {
AMPLUSPLUS_WITH_THREAD_ID(tid) {
concurrent_distribute(begin, end, flip, trans, msg_type);
}
}
private:
MessageType& msg_type;
};
template <typename Edges>
class threaded_merger {
public:
threaded_merger(Edges& all) : all_edges(all) {}
void operator()() {
}
template <typename EdgesIter>
void operator()(EdgesIter pos, EdgesIter begin, EdgesIter end) {
std::copy(begin, end, pos);
}
private:
Edges& all_edges;
};
template <typename Graph, typename ComponentMap, typename vertices_sz_t>
void calculate_cc_stats(Graph& g, ComponentMap& components, vertices_sz_t n, bool allstats) {
typedef unsigned int component_t;
typedef std::map<component_t, component_t> component_stats_t;
component_stats_t component_stats;
#ifdef PRINT_DEBUG
std::cout << "Calculating local components ..." << std::endl;
#endif
BGL_FORALL_VERTICES_T(v, g, Graph) {
component_t vcomp = (component_t)get(components, v);
component_stats_t::iterator
ite = component_stats.find(vcomp);
if (ite == component_stats.end()) {
component_stats.insert(std::make_pair(vcomp, 1));
} else {
++((*ite).second);
}
}
// end calculating local components.
// exchange all components
component_t localcomps = component_stats.size();
#ifdef PRINT_DEBUG
std::cout << "Rank : " << _RANK << ", found local components : " << localcomps << std::endl;
#endif
// allstats false
if (!allstats) {
// sort by number of vertices
std::vector<std::pair<int, int>> pairs;
for (auto itr = component_stats.begin(); itr != component_stats.end(); ++itr)
pairs.push_back(*itr);
component_stats.clear();
std::sort(pairs.begin(), pairs.end(), [=](std::pair<int, int>& a, std::pair<int, int>& b) {
return a.second > b.second;
});
if (_RANK == 0) {
std::cout << "Printing component statistics ..." << std::endl;
std::cout << "Printing only five largest components. To print all use --allstats" << std::endl;
std::cout << "Total number of components in root : " << pairs.size() << std::endl;
}
int i = 0;
vertices_sz_t rn = 0;
for (; i < 5; ++i) {
int compid = pairs[i].first;
int vtcs = pairs[i].second;
//check whether component id is same across all nodes
int retcomp;
MPI_Barrier(MPI_COMM_WORLD);
std::cout << "r : " << _RANK << ", c=" << compid << ", i=" << i << std::endl;
MPI_Allreduce(&compid, &retcomp, 1, MPI_INT, MPI_LAND, MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD);
if (retcomp == compid) {
// run a all reduce on all the vertices
int allvs;
MPI_Barrier(MPI_COMM_WORLD);
MPI_Allreduce(&vtcs, &allvs, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
if (_RANK == 0) {
std::cout << "component : " << compid << " vertices : " << allvs
<< " percentage : " << ((((double)allvs)/(double)n) * 100)
<< std::endl;
}
} else {
std::cout << "[ComponentStats] A mismatch found" << std::endl;
}
}
} else { // allstats true
component_t allcomps;
// calculate sum of localcomps
MPI_Allreduce(&localcomps, &allcomps, 1, MPI_UNSIGNED, MPI_SUM, MPI_COMM_WORLD);
component_t expectedcomps = allcomps - localcomps;
if (_RANK == 0)
std::cout << "All the components : " << allcomps << ", expecting receive components : "
<< expectedcomps << std::endl;
typedef struct component_vertices {
component_t c;
component_t vs;
component_vertices():
c(0), vs(0) {}
component_vertices(int pc, int pvs):
c(pc), vs(pvs) {}
component_vertices(const component_vertices &cvob):
c(cvob.c), vs(cvob.vs) {}
} cvs;
const int nitems=2;
int blocklengths[2] = {1,1};
MPI_Datatype types[2] = {MPI_UNSIGNED, MPI_UNSIGNED};
MPI_Datatype mpi_cv_type;
MPI_Aint offsets[2];
offsets[0] = offsetof(cvs, c);
offsets[1] = offsetof(cvs, vs);
MPI_Type_create_struct(nitems, blocklengths, offsets, types, &mpi_cv_type);
MPI_Type_commit(&mpi_cv_type);
std::vector<cvs> sendcomps;
std::vector<cvs> recvcomps;
if (_RANK != 0) {
// go through local component stat maps and collect them to an array
sendcomps.resize(localcomps);
int j = 0;
component_stats_t::iterator itesend = component_stats.begin();
for (; itesend != component_stats.end(); ++itesend) {
sendcomps[j].c = (*itesend).first;
sendcomps[j].vs = (*itesend).second;
#ifdef PRINT_DEBUG
std::cout << "Rank : " << _RANK << ", c=" << sendcomps[j].c << ", vs=" << sendcomps[j].vs << std::endl;
#endif
++j;
}
#ifdef PRINT_DEBUG
std::cout << "Rank : " << _RANK << ", sending components : " << localcomps << std::endl;
#endif
if (MPI_Send(&sendcomps[0], localcomps, mpi_cv_type, 0/*rank = 0*/, 13 /*tag*/,
MPI_COMM_WORLD) != 0) {
std::cout << "MPI_Send : " << "Error exchanging components" << std::endl;
}
}
MPI_Barrier(MPI_COMM_WORLD);
if (_RANK == 0) {
recvcomps.resize(expectedcomps);
if (expectedcomps != 0) {
#ifdef PRINT_DEBUG
std::cout << "Rank : " << _RANK << ", expected components : " << expectedcomps << std::endl;
#endif
int recvcount = 0;
component_t rcvexpectedcomps = expectedcomps;
while (recvcount != expectedcomps) {
MPI_Status status;
if (MPI_Recv(&recvcomps[recvcount], rcvexpectedcomps, mpi_cv_type, MPI_ANY_SOURCE, 13,
MPI_COMM_WORLD, &status) != 0)
std::cout << "MPI_Recv : " << "Error receiving messages" << std::endl;
int instcount = 0;
if (MPI_Get_count(&status, mpi_cv_type, &instcount) != MPI_SUCCESS)
std::cout << "MPI_Get_count :" << "Error getting received count" << std::endl;
recvcount += instcount;
rcvexpectedcomps -= instcount;
}
}
}
sendcomps.clear();
#ifdef PRINT_DEBUG
std::cout << "Rank : " << _RANK
<< ", Merging received components to component stats. Received components : "
<< recvcomps.size() << std::endl;
#endif
// update compnent stats
typename std::vector<cvs>::iterator veciter = recvcomps.begin();
for(; veciter != recvcomps.end(); ++veciter) {
component_stats_t::iterator
ite = component_stats.find((*veciter).c);
if (ite == component_stats.end()) {
#ifdef PRINT_DEBUG
std::cout << "inserting c=" << (*veciter).c << ", vs=" << (*veciter).vs << std::endl;
#endif
component_stats.insert(std::make_pair((*veciter).c, (*veciter).vs));
} else {
#ifdef PRINT_DEBUG
std::cout << "adding c=" << (*veciter).c << ", vs=" << (*veciter).vs << std::endl;
#endif
(*ite).second += (*veciter).vs;
}
}
recvcomps.clear();
if (_RANK == 0) {
// sort by number of vertices
std::vector<std::pair<int, int>> pairs;
for (auto itr = component_stats.begin(); itr != component_stats.end(); ++itr)
pairs.push_back(*itr);
component_stats.clear();
#ifdef PRINT_DEBUG
std::cout << "Sorting components by the number of vertices in their" << std::endl;
#endif
std::sort(pairs.begin(), pairs.end(), [=](std::pair<int, int>& a, std::pair<int, int>& b) {
return a.second > b.second;
});
std::cout << "Printing component statistics ..." << std::endl;
std::cout << "Total number of components : " << pairs.size() << std::endl;
int i = 0;
vertices_sz_t rn = 0;
std::vector<std::pair<int, int>>::iterator piter = pairs.begin();
for (; piter != pairs.end(); ++piter) {
std::cout << "component : " << (*piter).first << " vertices : " << (*piter).second
<< " percentage : " << ((((double)((*piter).second))/(double)n) * 100)
<< std::endl;
rn += (vertices_sz_t)(*piter).second;
}
std::cout << "rn = " << rn << ", n = " << n << std::endl;
assert(rn == n);
std::cout << "Done with CC stats." << std::endl;
}
}
}
template <typename Graph>
bool run_grah_stats(Graph& g) {
typedef typename boost::property_map<Graph, vertex_owner_t>::const_type OwnerMap;
OwnerMap owner = get(vertex_owner, g);
int remote_edges = 0;
int local_edges = 0;
BGL_FORALL_EDGES_T(e, g, Graph) {
if (get(owner, source(e, g)) != _RANK)
std::cout << "sv : " << source(e, g) << " svown : "
<< get(owner, source(e, g))
<< " tv : " << target(e, g)
<< " tvown : " << get(owner, target(e, g))
<< " rank : " << _RANK << std::endl;
// assert(get(owner, source(e, g)) == _RANK);
if (get(owner, target(e, g)) != _RANK)
++remote_edges;
else
++local_edges;
}
int alllocale = num_edges(g);
std::cout << "Rank : " << _RANK << " remote e : " << remote_edges
<< " local e : " << local_edges
<< " remote per : "
<< ((double)remote_edges / (double)alllocale) * 100
<< "%" << std::endl;
}
template <typename Graph, typename ComponentMap>
bool verify_cc(Graph& g, ComponentMap& components) {
typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
components.set_consistency_model(boost::parallel::cm_forward);
components.set_max_ghost_cells(0);
{
amplusplus::scoped_epoch epoch(g.transport());
BGL_FORALL_VERTICES_T(v, g, Graph) {
BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {
get(components, source(e, g));
get(components, target(e, g));
}
}
}
{
amplusplus::scoped_epoch epoch(g.transport()); // at the moment get() sends a message
BGL_FORALL_VERTICES_T(v, g, Graph) {
BGL_FORALL_ADJ_T(v, u, g, Graph) {
// std::cout << "verifying vertex v : " << v << std::endl;
//#ifdef PRINT_DEBUG
if (get(components, v) != get(components, u))
std::cout << "Component of " << v << " : " << get(components, v)
<< " component of " << u << " : " << get(components, u)
<< std::endl;
assert(get(components, v) == get(components, u));
}
}
}
components.clear(); // Clear memory used by ghost cells
}
template <typename Graph, typename DistanceMap, typename WeightMap>
bool verify_sssp(amplusplus::transport& trans, Graph& g, DistanceMap& distance, const WeightMap& weight) {
distance.set_consistency_model(boost::parallel::cm_forward);
distance.set_max_ghost_cells(0);
if (trans.rank() == 0) std::cout<<"Verifying results......";
{
amplusplus::scoped_epoch epoch(g.transport());
BGL_FORALL_VERTICES_T(v, g, Graph) {
BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {
get(distance, target(e, g));
}
}
}
BGL_FORALL_VERTICES_T(v, g, Graph) {
BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {
#ifdef PRINT_DEBUG
if (get(distance, target(e, g)) > boost::closed_plus<weight_type>()(get(distance, source(e, g)), get(weight, e)))
std::cout << get(get(vertex_local, g), source(e, g)) << "@" << get(get(vertex_owner, g), source(e, g)) << "->"
<< get(get(vertex_local, g), target(e, g)) << "@" << get(get(vertex_owner, g), target(e, g)) << " weight = "
<< get(weight, e)
<< " distance(" << get(get(vertex_local, g), source(e, g)) << "@" << get(get(vertex_owner, g), source(e, g))
<< ") = " << get(distance, source(e, g)) << " distance(" << get(get(vertex_local, g), target(e, g)) << "@"
<< get(get(vertex_owner, g), target(e, g)) << ") = " << get(distance, target(e, g)) << std::endl;
#else
if(get(distance, target(e, g)) > boost::closed_plus<weight_type>()(get(distance, v), get(weight, e))) std::abort();
#endif
}
}
if (trans.rank() == 0) std::cout << "Verified." << std::endl;
distance.clear(); // Clear memory used by ghost cells
return true;
}
template <typename Graph, typename MISMap>
bool verify_mis(amplusplus::transport& trans, Graph& g, MISMap& mis) {
typedef typename boost::property_map<Graph, vertex_owner_t>::const_type OwnerMap;
OwnerMap owner(get(vertex_owner, g));
mis.set_consistency_model(boost::parallel::cm_forward || boost::parallel::cm_backward);
mis.set_max_ghost_cells(0);
if (trans.rank() == 0) std::cout<<"Verifying MIS results......";
{
amplusplus::scoped_epoch epoch(g.transport());
BGL_FORALL_VERTICES_T(v, g, Graph) {
BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {
get(mis, target(e, g));
}
}
}
bool result = true;
int found_mis = 0;
#ifdef PRINT_DEBUG
std::cout << "MIS = {";
#endif
BGL_FORALL_VERTICES_T(v, g, Graph) {
if (get(mis, v) == MIS_FIX1) {// v in mis, none of the neigbours should be in mis
#ifdef PRINT_DEBUG
if (v == 35) {
std::cout << "Printing all neighbors of " << v
<< " -- [";
BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {
std::cout << target(e, g) << ", ";
}
std::cout << "]" << std::endl;
}
std::cout << v << "-[";
#endif
BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {
#ifdef PRINT_DEBUG
std::cout << target(e, g) << ", ";
#endif
if (v == target(e, g))
continue;
if (get(mis, target(e, g)) == MIS_FIX1) {
std::cout << "[FAIL] Vertex : " << v << " and its neigbour " << target(e, g)
<< " are both in MIS."
<< " Vertex value : " << get(mis, v)
<< " neighbor value : " << get(mis, target(e, g))
<< std::endl;
std::cout << "Neighbors of " << v << "- {";
BGL_FORALL_ADJ_T(v, u1, g, Graph) {
std::cout << "(" << u1 << ", " << get(mis, u1) << ")";
}
std::cout << "}" << std::endl;
auto k = target(e, g);
if (get(owner, k) == g.transport().rank()) {
std::cout << "Neighbors of " << k << "- {";
BGL_FORALL_ADJ_T(k, u2, g, Graph) {
std::cout << "(" << u2 << ", " << get(mis, u2) << ")";
}
std::cout << "}" << std::endl;
}
result = false;
} else {
#ifdef PRINT_DEBUG
if (get(mis, target(e, g)) != MIS_FIX0) {
std::cout << "vertex : "
<< target(e, g)
<< ", is in "
<< get(mis, target(e, g))
<< std::endl;
}
#endif
// cannot be MIS_UNFIX
assert(get(mis, target(e, g)) == MIS_FIX0);
found_mis = 1;
}
}
#ifdef PRINT_DEBUG
std::cout << "], ";
#endif
} else {
// if v is not in mis, at least one of its neighbors must
// be in mis
if (get(mis, v) != MIS_FIX0) {
std::cout << "[ERROR] Vertex - " << v << " is in " << get(mis, v)
<< std::endl;
}
if (get(mis, v) != MIS_FIX0) {
std::cout << "Error : " << v << " is not in MIS_FIX0. But in " << get(mis, v)
<< std::endl;
BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {
auto k = target(e, g);
std::cout << "neigbor : " << k << " mis : " << get(mis, k)
<< std::endl;
}
}
assert(get(mis, v) == MIS_FIX0);
bool inmis = false;
BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {
if (v == target(e, g))
continue;
if (get(mis, target(e, g)) == MIS_FIX1) {
inmis = true;
break;
}
}
if (!inmis) {
std::cout << "Vertex : " << v << " and none of its neighbors is in MIS" << std::endl;
assert(false);
}
}
}
#ifdef PRINT_DEBUG
std::cout << "}" << std::endl;
#endif
// Run a reduction on found mis.
// We cannot expect every rank will have found_mis true.
// E.g:- rank0 - {0,1}, rank1 - {281474976710656, 281474976710657}
// If every vertex is connect to each other, a vertex (Lets say 0) will
// be in one rank. In the second rank all vertices are out of mis.
int or_found_mis = 0;
MPI_Allreduce(&found_mis, &or_found_mis, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
if (or_found_mis == 0) {
std::cout << "Did not find any MIS" <<std::endl;
result = false;
}
return result;
}
//=================================================//
// vertex id distributions
enum id_distribution_t {
vertical,
horizontal
};
//=================================================//
template <typename PriorityQueueGenerator = boost::graph::distributed::thread_priority_queue_gen,
typename Graph, typename MISMap,
typename MessageGenerator>
time_type
run_fix_mis(amplusplus::transport& trans,
amplusplus::transport& barrier_trans,
Graph& g,
MISMap& mis,
int num_threads,
typename graph_traits<Graph>::vertices_size_type n,
bool verify,
MessageGenerator msg_gen,
int flushFreq) {
#ifdef CLONE
amplusplus::transport trans = trans.clone(); // Clone transport for this run
#endif
typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;
if (trans.rank() == 0)
std::cout << "Initializing mis map ..." << std::endl;
BGL_FORALL_VERTICES_T(v, g, Graph)
{ put(mis, v, MIS_UNFIX); }
trans.set_nthreads(num_threads);
if (trans.rank() == 0)
std::cout << "Creating algorithm instance ..." << std::endl;
boost::graph::distributed::maximal_independent_set<Graph, MISMap,
PriorityQueueGenerator, MessageGenerator>
D(g, mis, trans, flushFreq, msg_gen);
trans.set_nthreads(1);
{ amplusplus::scoped_epoch epoch(barrier_trans); }
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
epoch_times.clear();
clear_buffer_stats();
#endif
// Many threads now
trans.set_nthreads(num_threads);
if (trans.rank() == 0)
std::cout << "Invoking algorithm ..." << std::endl;
boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]);
for (int i = 0; i < num_threads - 1; ++i) {
boost::thread thr(boost::ref(D), i + 1);
threads[i].swap(thr);
}
D(0);
for (int i = 0; i < num_threads - 1; ++i)
threads[i].join();
time_type end = get_time();
if (trans.rank() == 0)
std::cout << "Algorithm done ..." << std::endl;
time_type start = D.get_start_time();
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
print_and_clear_epoch_times();
print_buffer_stats();
#endif
//#ifdef AMPLUSPLUS_PRINT_HIT_RATES
//const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats();
//print_and_accumulate_cache_stats(stats);
//#endif
// Back to one thread
trans.set_nthreads(1);
if (verify) {
if (trans.rank()==0)
std::cout << "Verifying mis ..." << std::endl;
if (!verify_mis(trans, g, mis)) {
std::cout << "MIS Verification Failed" << std::endl;
assert(false);
return 0;
}
}
vertices_size_type visited = 0;
BGL_FORALL_VERTICES_T(v, g, Graph) {
if (get(mis, v) != MIS_UNFIX)
++visited;
}
boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> >
r(trans, std::plus<vertices_size_type>());
vertices_size_type total = r(visited);
if (verify)
if (trans.rank() == 0)
std::cout << "Visited " << total << " vertices of " << n << " in " << print_time(end - start)
<< std::endl;
//if (total < 100) return -1.;
return end - start;
}
template <typename Graph, typename MISMap,
typename MessageGenerator>
time_type
run_fix_mis_bucket(amplusplus::transport& trans,
amplusplus::transport& barrier_trans,
Graph& g,
MISMap& mis,
int num_threads,
typename graph_traits<Graph>::vertices_size_type n,
bool verify,
MessageGenerator msg_gen,
int flushFreq) {
#ifdef CLONE
amplusplus::transport trans = trans.clone(); // Clone transport for this run
#endif
typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;
if (trans.rank() == 0)
std::cout << "Initializing mis-delta map ..." << std::endl;
BGL_FORALL_VERTICES_T(v, g, Graph)
{ put(mis, v, MIS_UNFIX); }
trans.set_nthreads(num_threads);
if (trans.rank() == 0)
std::cout << "Creating algorithm instance ..." << std::endl;
boost::graph::distributed::maximal_independent_set_delta<Graph, MISMap,
append_buffer<Vertex, 10u>, MessageGenerator>
D(g, mis, trans, flushFreq, msg_gen);
trans.set_nthreads(1);
{ amplusplus::scoped_epoch epoch(barrier_trans); }
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
epoch_times.clear();
clear_buffer_stats();
#endif
// Many threads now
trans.set_nthreads(num_threads);
if (trans.rank() == 0)
std::cout << "Invoking algorithm ..." << std::endl;
boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]);
for (int i = 0; i < num_threads - 1; ++i) {
boost::thread thr(boost::ref(D), i + 1);
threads[i].swap(thr);
}
D(0);
for (int i = 0; i < num_threads - 1; ++i)
threads[i].join();
time_type end = get_time();
if (trans.rank() == 0)
std::cout << "Algorithm done ..." << std::endl;
time_type start = D.get_start_time();
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
print_and_clear_epoch_times();
print_buffer_stats();
#endif
//#ifdef AMPLUSPLUS_PRINT_HIT_RATES
//const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats();
//print_and_accumulate_cache_stats(stats);
//#endif
// Back to one thread
trans.set_nthreads(1);
if (verify) {
if (trans.rank()==0)
std::cout << "Verifying delta mis ..." << std::endl;
if (!verify_mis(trans, g, mis)) {
std::cout << "Delta-MIS Verification Failed" << std::endl;
assert(false);
return 0;
}
}
vertices_size_type visited = 0;
BGL_FORALL_VERTICES_T(v, g, Graph) {
if (get(mis, v) != MIS_UNFIX)
++visited;
}
boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> >
r(trans, std::plus<vertices_size_type>());
vertices_size_type total = r(visited);
if (verify)
if (trans.rank() == 0)
std::cout << "Visited " << total << " vertices of " << n << " in " << print_time(end - start)
<< std::endl;
//if (total < 100) return -1.;
return end - start;
}
template <typename SelectGenerator, typename Graph, typename MISMap, typename MessageGenerator>
time_type
run_luby_maximal_is(amplusplus::transport& trans,
amplusplus::transport& barrier_trans,
Graph& g,
MISMap& mis,
int num_threads,
typename graph_traits<Graph>::vertices_size_type n,
bool verify,
MessageGenerator msg_gen,
int flushFreq) {
#ifdef CLONE
amplusplus::transport trans = trans.clone(); // Clone transport for this run
#endif
typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;
typedef typename property_map<Graph, vertex_index_t>::type VertexIndexMap;
typedef iterator_property_map<typename std::vector<random_t>::iterator, VertexIndexMap> RandomMap;
// create a property map
std::vector<random_t> pivec(num_vertices(g), 0);
RandomMap rmap(pivec.begin(), get(vertex_index, g)); // TODO remove copying
if (trans.rank() == 0)
std::cout << "Initializing mis map ..." << std::endl;
BGL_FORALL_VERTICES_T(v, g, Graph)
{ put(mis, v, MIS_UNFIX); }
trans.set_nthreads(num_threads);
if (trans.rank() == 0)
std::cout << "Creating algorithm instance ..." << std::endl;
boost::graph::distributed::luby_mis<Graph, MISMap, RandomMap,
// boost::graph::distributed::select_a_functor_gen,
SelectGenerator,
MessageGenerator>
D(g, mis, rmap, n, trans, flushFreq, msg_gen);
trans.set_nthreads(1);
{ amplusplus::scoped_epoch epoch(barrier_trans); }
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
epoch_times.clear();
clear_buffer_stats();
#endif
// Many threads now
trans.set_nthreads(num_threads);
if (trans.rank() == 0)
std::cout << "Invoking algorithm ..." << std::endl;
boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]);
for (int i = 0; i < num_threads - 1; ++i) {
boost::thread thr(boost::ref(D), i + 1);
threads[i].swap(thr);
}
D(0);
for (int i = 0; i < num_threads - 1; ++i)
threads[i].join();
time_type end = get_time();
if (trans.rank() == 0)
std::cout << "Algorithm done ..." << std::endl;
time_type start = D.get_start_time();
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
print_and_clear_epoch_times();
print_buffer_stats();
#endif
//#ifdef AMPLUSPLUS_PRINT_HIT_RATES
//const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats();
//print_and_accumulate_cache_stats(stats);
//#endif
// Back to one thread
trans.set_nthreads(1);
if (verify) {
if (trans.rank()==0)
std::cout << "Verifying mis ..." << std::endl;
if (!verify_mis(trans, g, mis)) {
std::cout << "MIS Verification Failed" << std::endl;
assert(false);
return 0;
}
}
vertices_size_type visited = 0;
BGL_FORALL_VERTICES_T(v, g, Graph) {
if (get(mis, v) != MIS_UNFIX)
++visited;
}
boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> >
r(trans, std::plus<vertices_size_type>());
vertices_size_type total = r(visited);
if (verify)
if (trans.rank() == 0)
std::cout << "Visited " << total << " vertices of " << n << " in " << print_time(end - start)
<< std::endl;
//if (total < 100) return -1.;
return end - start;
}
template <typename Graph, typename WeightMap, typename DistanceMap, typename MessageGenerator>
time_type
run_kla_sssp(amplusplus::transport& trans,
amplusplus::transport& barrier_trans,
Graph& g, const WeightMap& weight,
DistanceMap& distance,
typename graph_traits<Graph>::vertex_descriptor current_source,
int num_threads,
typename graph_traits<Graph>::vertices_size_type n,
bool verify, bool level_sync,
MessageGenerator msg_gen, size_t k_level) {
#ifdef CLONE
amplusplus::transport trans = trans.clone(); // Clone transport for this run
#endif
typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;
typedef typename property_traits<WeightMap>::value_type Dist;
BGL_FORALL_VERTICES_T(v, g, Graph)
{ put(distance, v, std::numeric_limits<weight_type>::max()); }
trans.set_nthreads(num_threads);
boost::graph::distributed::kla_shortest_paths_buffer<Graph, DistanceMap, WeightMap,
append_buffer<std::pair<Vertex, std::pair<Dist, size_t> >, 10u>, MessageGenerator>
D(g, distance, weight, trans, k_level, msg_gen);
trans.set_nthreads(1);
D.set_source(current_source);
if (level_sync)
D.set_level_sync();
{ amplusplus::scoped_epoch epoch(barrier_trans); }
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
epoch_times.clear();
clear_buffer_stats();
#endif
// Many threads now
trans.set_nthreads(num_threads);
boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]);
for (int i = 0; i < num_threads - 1; ++i) {
boost::thread thr(boost::ref(D), i + 1);
threads[i].swap(thr);
}
D(0);
for (int i = 0; i < num_threads - 1; ++i)
threads[i].join();
time_type end = get_time();
time_type start = D.get_start_time();
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
print_and_clear_epoch_times();
print_buffer_stats();
#endif
#ifdef AMPLUSPLUS_PRINT_HIT_RATES
const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats();
print_and_accumulate_cache_stats(stats);
#endif
#ifdef PBGL2_PRINT_WORK_STATS
size_t edges_in_comp = count_edges(trans, g, distance, weight, current_source);
work_stats_t work_stats = D.get_work_stats();
print_and_accumulate_work_stats(work_stats, ds_stats, edges_in_comp);
#endif
// Back to one thread
trans.set_nthreads(1);
unsigned long long num_levels = D.get_num_levels();
if (verify) {
verify_sssp(trans, g, distance, weight);
}
vertices_size_type visited = 0;
BGL_FORALL_VERTICES_T(v, g, Graph) {
if (get(distance, v) < std::numeric_limits<weight_type>::max())
++visited;
}
boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> >
r(trans, std::plus<vertices_size_type>());
vertices_size_type total = r(visited);
if (verify)
if (trans.rank() == 0)
std::cout << "Visited " << total << " vertices of " << n << " in " << print_time(end - start)
<< ", " << num_levels << " levels required." << std::endl;
if (total < 100) return -1.;
return end - start;
}
template <typename PriorityQueueGenerator = boost::graph::distributed::numa_priority_queue_gen,
typename Graph, typename WeightMap, typename DistanceMap, typename MessageGenerator>
time_type
run_kla_sssp_numa(amplusplus::transport& trans,
amplusplus::transport& barrier_trans,
Graph& g, const WeightMap& weight,
DistanceMap& distance,
typename graph_traits<Graph>::vertex_descriptor current_source,
int num_threads,
typename graph_traits<Graph>::vertices_size_type n,
bool verify, bool level_sync,
MessageGenerator msg_gen, size_t k_level,
int flushFreq) {
#ifdef CLONE
amplusplus::transport trans = trans.clone(); // Clone transport for this run
#endif
typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;
typedef typename property_traits<WeightMap>::value_type Dist;
BGL_FORALL_VERTICES_T(v, g, Graph)
{ put(distance, v, std::numeric_limits<weight_type>::max()); }
trans.set_nthreads(num_threads);
#ifdef LIB_CDS
// LIBCDS Stuff goes here
if (trans.rank() == 0)
std::cout << "Initializing LIBCDS .... " << std::endl;
cds::Initialize();
// Initialize Hazard Pointer singleton
cds::gc::HP hpGC;
// Attach for the main thread
cds::threading::Manager::attachThread();
#endif
boost::graph::distributed::kla_shortest_paths_numa<Graph, DistanceMap, WeightMap,
PriorityQueueGenerator, MessageGenerator>
D(g, distance, weight, trans, k_level, flushFreq, msg_gen);
trans.set_nthreads(1);
D.set_source(current_source);
if (level_sync)
D.set_level_sync();
{ amplusplus::scoped_epoch epoch(barrier_trans); }
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
epoch_times.clear();
clear_buffer_stats();
#endif
// Many threads now
trans.set_nthreads(num_threads);
boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]);
for (int i = 0; i < num_threads - 1; ++i) {
boost::thread thr(boost::ref(D), i + 1);
threads[i].swap(thr);
}
D(0);
for (int i = 0; i < num_threads - 1; ++i)
threads[i].join();
time_type end = get_time();
time_type start = D.get_start_time();
#ifdef LIB_CDS
if (trans.rank() == 0)
std::cout << "Termminating LIBCDS .... " << std::endl;
cds::Terminate();
#endif
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
print_and_clear_epoch_times();
print_buffer_stats();
#endif
#ifdef AMPLUSPLUS_PRINT_HIT_RATES
const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats();
print_and_accumulate_cache_stats(stats);
#endif
#ifdef PBGL2_PRINT_WORK_STATS
size_t edges_in_comp = count_edges(trans, g, distance, weight, current_source);
work_stats_t work_stats = D.get_work_stats();
print_and_accumulate_work_stats(work_stats, ds_stats, edges_in_comp);
#endif
// Back to one thread
trans.set_nthreads(1);
unsigned long long num_levels = D.get_num_levels();
if (verify) {
verify_sssp(trans, g, distance, weight);
}
vertices_size_type visited = 0;
BGL_FORALL_VERTICES_T(v, g, Graph) {
if (get(distance, v) < std::numeric_limits<weight_type>::max())
++visited;
}
boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> >
r(trans, std::plus<vertices_size_type>());
vertices_size_type total = r(visited);
if (verify)
if (trans.rank() == 0)
std::cout << "Visited " << total << " vertices of " << n << " in " << print_time(end - start)
<< ", " << num_levels << " levels required." << std::endl;
if (total < 100) return -1.;
return end - start;
}
template <typename PriorityQueueGenerator = boost::graph::distributed::numa_priority_queue_gen,
typename Graph, typename WeightMap, typename DistanceMap, typename MessageGenerator>
time_type
run_kla_sssp_thread(amplusplus::transport& trans,
amplusplus::transport& barrier_trans,
Graph& g, const WeightMap& weight,
DistanceMap& distance,
typename graph_traits<Graph>::vertex_descriptor current_source,
int num_threads,
typename graph_traits<Graph>::vertices_size_type n,
bool verify, bool level_sync,
MessageGenerator msg_gen, size_t k_level,
int flushFreq) {
#ifdef CLONE
amplusplus::transport trans = trans.clone(); // Clone transport for this run
#endif
typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;
typedef typename property_traits<WeightMap>::value_type Dist;
BGL_FORALL_VERTICES_T(v, g, Graph)
{ put(distance, v, std::numeric_limits<weight_type>::max()); }
trans.set_nthreads(num_threads);
boost::graph::distributed::kla_shortest_paths_thread<Graph, DistanceMap, WeightMap,
PriorityQueueGenerator, MessageGenerator>
D(g, distance, weight, trans, k_level,flushFreq, msg_gen);
trans.set_nthreads(1);
D.set_source(current_source);
if (level_sync)
D.set_level_sync();
{ amplusplus::scoped_epoch epoch(barrier_trans); }
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
epoch_times.clear();
clear_buffer_stats();
#endif
// Many threads now
trans.set_nthreads(num_threads);
boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]);
for (int i = 0; i < num_threads - 1; ++i) {
boost::thread thr(boost::ref(D), i + 1);
threads[i].swap(thr);
}
D(0);
for (int i = 0; i < num_threads - 1; ++i)
threads[i].join();
time_type end = get_time();
time_type start = D.get_start_time();
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
print_and_clear_epoch_times();
print_buffer_stats();
#endif
#ifdef AMPLUSPLUS_PRINT_HIT_RATES
const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats();
print_and_accumulate_cache_stats(stats);
#endif
#ifdef PBGL2_PRINT_WORK_STATS
size_t edges_in_comp = count_edges(trans, g, distance, weight, current_source);
work_stats_t work_stats = D.get_work_stats();
print_and_accumulate_work_stats(work_stats, ds_stats, edges_in_comp);
#endif
// Back to one thread
trans.set_nthreads(1);
unsigned long long num_levels = D.get_num_levels();
if (verify) {
verify_sssp(trans, g, distance, weight);
}
vertices_size_type visited = 0;
BGL_FORALL_VERTICES_T(v, g, Graph) {
if (get(distance, v) < std::numeric_limits<weight_type>::max())
++visited;
}
boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> >
r(trans, std::plus<vertices_size_type>());
vertices_size_type total = r(visited);
if (verify)
if (trans.rank() == 0)
std::cout << "Visited " << total << " vertices of " << n << " in " << print_time(end - start)
<< ", " << num_levels << " levels required." << std::endl;
if (total < 100) return -1.;
return end - start;
}
template <typename PriorityQueueGenerator = boost::graph::distributed::numa_priority_queue_gen,
typename Graph, typename WeightMap, typename DistanceMap, typename MessageGenerator>
time_type
run_kla_sssp_node(amplusplus::transport& trans,
amplusplus::transport& barrier_trans,
Graph& g, const WeightMap& weight,
DistanceMap& distance,
typename graph_traits<Graph>::vertex_descriptor current_source,
int num_threads,
typename graph_traits<Graph>::vertices_size_type n,
bool verify, bool level_sync,
MessageGenerator msg_gen, size_t k_level,
int flushFreq) {
#ifdef CLONE
amplusplus::transport trans = trans.clone(); // Clone transport for this run
#endif
typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;
typedef typename property_traits<WeightMap>::value_type Dist;
BGL_FORALL_VERTICES_T(v, g, Graph)
{ put(distance, v, std::numeric_limits<weight_type>::max()); }
trans.set_nthreads(num_threads);
#ifdef LIB_CDS
// LIBCDS Stuff goes here
if (trans.rank() == 0)
std::cout << "Initializing LIBCDS .... " << std::endl;
cds::Initialize();
// Initialize Hazard Pointer singleton
cds::gc::HP hpGC;
// Attach for the main thread
cds::threading::Manager::attachThread();
#endif
boost::graph::distributed::kla_shortest_paths_node<Graph, DistanceMap, WeightMap,
PriorityQueueGenerator, MessageGenerator>
D(g, distance, weight, trans, k_level, flushFreq, msg_gen);
trans.set_nthreads(1);
D.set_source(current_source);
if (level_sync)
D.set_level_sync();
{ amplusplus::scoped_epoch epoch(barrier_trans); }
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
epoch_times.clear();
clear_buffer_stats();
#endif
// Many threads now
trans.set_nthreads(num_threads);
boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]);
for (int i = 0; i < num_threads - 1; ++i) {
boost::thread thr(boost::ref(D), i + 1);
threads[i].swap(thr);
}
D(0);
for (int i = 0; i < num_threads - 1; ++i)
threads[i].join();
time_type end = get_time();
time_type start = D.get_start_time();
#ifdef LIB_CDS
if (trans.rank() == 0)
std::cout << "Termminating LIBCDS .... " << std::endl;
cds::Terminate();
#endif
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
print_and_clear_epoch_times();
print_buffer_stats();
#endif
#ifdef AMPLUSPLUS_PRINT_HIT_RATES
const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats();
print_and_accumulate_cache_stats(stats);
#endif
#ifdef PBGL2_PRINT_WORK_STATS
size_t edges_in_comp = count_edges(trans, g, distance, weight, current_source);
work_stats_t work_stats = D.get_work_stats();
print_and_accumulate_work_stats(work_stats, ds_stats, edges_in_comp);
#endif
// Back to one thread
trans.set_nthreads(1);
unsigned long long num_levels = D.get_num_levels();
if (verify) {
verify_sssp(trans, g, distance, weight);
}
vertices_size_type visited = 0;
BGL_FORALL_VERTICES_T(v, g, Graph) {
if (get(distance, v) < std::numeric_limits<weight_type>::max())
++visited;
}
boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> >
r(trans, std::plus<vertices_size_type>());
vertices_size_type total = r(visited);
if (verify)
if (trans.rank() == 0)
std::cout << "Visited " << total << " vertices of " << n << " in " << print_time(end - start)
<< ", " << num_levels << " levels required." << std::endl;
if (total < 100) return -1.;
return end - start;
}
template <typename Graph, typename WeightMap, typename DistanceMap, typename MessageGenerator>
time_type
run_delta_stepping(amplusplus::transport& trans, amplusplus::transport& barrier_trans, Graph& g, const WeightMap& weight, DistanceMap& distance, typename graph_traits<Graph>::vertex_descriptor current_source, weight_type delta, int num_threads, typename graph_traits<Graph>::vertices_size_type n, bool verify, bool level_sync, MessageGenerator msg_gen) {
#ifdef CLONE
amplusplus::transport trans = trans.clone(); // Clone transport for this run
#endif
typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;
BGL_FORALL_VERTICES_T(v, g, Graph)
{ put(distance, v, std::numeric_limits<weight_type>::max()); }
trans.set_nthreads(num_threads);
boost::graph::distributed::delta_stepping_shortest_paths<Graph, DistanceMap, WeightMap,
append_buffer<Vertex, 10u>, MessageGenerator>
D(g, distance, weight, trans, delta, msg_gen);
trans.set_nthreads(1);
D.set_source(current_source);
if (level_sync)
D.set_level_sync();
{ amplusplus::scoped_epoch epoch(barrier_trans); }
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
epoch_times.clear();
clear_buffer_stats();
#endif
// Many threads now
trans.set_nthreads(num_threads);
boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]);
for (int i = 0; i < num_threads - 1; ++i) {
boost::thread thr(boost::ref(D), i + 1);
threads[i].swap(thr);
}
D(0);
for (int i = 0; i < num_threads - 1; ++i)
threads[i].join();
time_type end = get_time();
time_type start = D.get_start_time();
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
print_and_clear_epoch_times();
print_buffer_stats();
#endif
#ifdef AMPLUSPLUS_PRINT_HIT_RATES
const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats();
print_and_accumulate_cache_stats(stats);
#endif
#ifdef PBGL2_PRINT_WORK_STATS
size_t edges_in_comp = count_edges(trans, g, distance, weight, current_source);
work_stats_t work_stats = D.get_work_stats();
print_and_accumulate_work_stats(work_stats, ds_stats, edges_in_comp);
#endif
// Back to one thread
trans.set_nthreads(1);
unsigned long long num_levels = D.get_num_levels();
if (verify) verify_sssp(trans, g, distance, weight);
vertices_size_type visited = 0;
BGL_FORALL_VERTICES_T(v, g, Graph) {
if (get(distance, v) < std::numeric_limits<weight_type>::max())
++visited;
}
boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> >
r(trans, std::plus<vertices_size_type>());
vertices_size_type total = r(visited);
if (verify)
if (trans.rank() == 0)
std::cout << "Visited " << total << " vertices of " << n << " in " << print_time(end - start)
<< ", " << num_levels << " levels required." << std::endl;
if (total < 100) return -1.;
return end - start;
}
template <typename PriorityQueueGenerator = boost::graph::distributed::default_priority_queue_gen,
typename Graph, typename WeightMap, typename DistanceMap, typename MessageGenerator>
time_type
run_delta_stepping_node(amplusplus::transport& trans,
amplusplus::transport& barrier_trans,
Graph& g, const WeightMap& weight,
DistanceMap& distance,
typename graph_traits<Graph>::vertex_descriptor current_source,
weight_type delta, int num_threads, typename graph_traits<Graph>::
vertices_size_type n, bool verify, bool level_sync, MessageGenerator msg_gen,
int flushFreq) {
#ifdef CLONE
amplusplus::transport trans = trans.clone(); // Clone transport for this run
#endif
typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;
BGL_FORALL_VERTICES_T(v, g, Graph)
{ put(distance, v, std::numeric_limits<weight_type>::max()); }
trans.set_nthreads(num_threads);
#ifdef LIB_CDS
// LIBCDS Stuff goes here
if (trans.rank() == 0)
std::cout << "Initializing LIBCDS .... " << std::endl;
cds::Initialize();
// Initialize Hazard Pointer singleton
cds::gc::HP hpGC;
// Attach for the main thread
cds::threading::Manager::attachThread();
#endif
boost::graph::distributed::delta_stepping_shortest_paths_node<Graph, DistanceMap, WeightMap,
PriorityQueueGenerator, MessageGenerator>
D(g, distance, weight, trans, delta, flushFreq, msg_gen);
trans.set_nthreads(1);
D.set_source(current_source);
if (level_sync)
D.set_level_sync();
{ amplusplus::scoped_epoch epoch(barrier_trans); }
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
epoch_times.clear();
clear_buffer_stats();
#endif
// Many threads now
trans.set_nthreads(num_threads);
boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]);
for (int i = 0; i < num_threads - 1; ++i) {
boost::thread thr(boost::ref(D), i + 1);
threads[i].swap(thr);
}
D(0);
for (int i = 0; i < num_threads - 1; ++i)
threads[i].join();
time_type end = get_time();
time_type start = D.get_start_time();
#ifdef LIB_CDS
if (trans.rank() == 0)
std::cout << "Termminating LIBCDS .... " << std::endl;
cds::Terminate();
#endif
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
print_and_clear_epoch_times();
print_buffer_stats();
#endif
#ifdef AMPLUSPLUS_PRINT_HIT_RATES
const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats();
print_and_accumulate_cache_stats(stats);
#endif
#ifdef PBGL2_PRINT_WORK_STATS
size_t edges_in_comp = count_edges(trans, g, distance, weight, current_source);
work_stats_t work_stats = D.get_work_stats();
print_and_accumulate_work_stats(work_stats, ds_stats, edges_in_comp);
#endif
// Back to one thread
trans.set_nthreads(1);
unsigned long long num_levels = D.get_num_levels();
if (verify) verify_sssp(trans, g, distance, weight);
vertices_size_type visited = 0;
BGL_FORALL_VERTICES_T(v, g, Graph) {
if (get(distance, v) < std::numeric_limits<weight_type>::max())
++visited;
}
boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> >
r(trans, std::plus<vertices_size_type>());
vertices_size_type total = r(visited);
if (verify)
if (trans.rank() == 0)
std::cout << "Visited " << total << " vertices of " << n << " in " << print_time(end - start)
<< ", " << num_levels << " levels required." << std::endl;
if (total < 100) return -1.;
return end - start;
}
template <typename PriorityQueueGenerator = boost::graph::distributed::default_priority_queue_gen,
typename Graph, typename WeightMap, typename DistanceMap, typename MessageGenerator>
time_type
run_delta_stepping_numa(amplusplus::transport& trans,
amplusplus::transport& barrier_trans,
Graph& g, const WeightMap& weight,
DistanceMap& distance,
typename graph_traits<Graph>::vertex_descriptor current_source,
weight_type delta, int num_threads, typename graph_traits<Graph>::
vertices_size_type n, bool verify, bool level_sync, MessageGenerator msg_gen,
int flushFreq) {
#ifdef CLONE
amplusplus::transport trans = trans.clone(); // Clone transport for this run
#endif
typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;
BGL_FORALL_VERTICES_T(v, g, Graph)
{ put(distance, v, std::numeric_limits<weight_type>::max()); }
trans.set_nthreads(num_threads);
#ifdef LIB_CDS
// LIBCDS Stuff goes here
if (trans.rank() == 0)
std::cout << "Initializing LIBCDS .... " << std::endl;
cds::Initialize();
// Initialize Hazard Pointer singleton
cds::gc::HP hpGC;
// Attach for the main thread
cds::threading::Manager::attachThread();
#endif
boost::graph::distributed::delta_stepping_shortest_paths_numa<Graph, DistanceMap, WeightMap,
PriorityQueueGenerator, MessageGenerator>
D(g, distance, weight, trans, delta, flushFreq, msg_gen);
trans.set_nthreads(1);
D.set_source(current_source);
if (level_sync)
D.set_level_sync();
{ amplusplus::scoped_epoch epoch(barrier_trans); }
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
epoch_times.clear();
clear_buffer_stats();
#endif
// Many threads now
trans.set_nthreads(num_threads);
boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]);
for (int i = 0; i < num_threads - 1; ++i) {
boost::thread thr(boost::ref(D), i + 1);
threads[i].swap(thr);
}
D(0);
for (int i = 0; i < num_threads - 1; ++i)
threads[i].join();
time_type end = get_time();
time_type start = D.get_start_time();
#ifdef LIB_CDS
if (trans.rank() == 0)
std::cout << "Termminating LIBCDS .... " << std::endl;
cds::Terminate();
#endif
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
print_and_clear_epoch_times();
print_buffer_stats();
#endif
#ifdef AMPLUSPLUS_PRINT_HIT_RATES
const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats();
print_and_accumulate_cache_stats(stats);
#endif
#ifdef PBGL2_PRINT_WORK_STATS
size_t edges_in_comp = count_edges(trans, g, distance, weight, current_source);
work_stats_t work_stats = D.get_work_stats();
print_and_accumulate_work_stats(work_stats, ds_stats, edges_in_comp);
#endif
// Back to one thread
trans.set_nthreads(1);
unsigned long long num_levels = D.get_num_levels();
if (verify) verify_sssp(trans, g, distance, weight);
vertices_size_type visited = 0;
BGL_FORALL_VERTICES_T(v, g, Graph) {
if (get(distance, v) < std::numeric_limits<weight_type>::max())
++visited;
}
boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> >
r(trans, std::plus<vertices_size_type>());
vertices_size_type total = r(visited);
if (verify)
if (trans.rank() == 0)
std::cout << "Visited " << total << " vertices of " << n << " in " << print_time(end - start)
<< ", " << num_levels << " levels required." << std::endl;
if (total < 100) return -1.;
return end - start;
}
template <typename PriorityQueueGenerator = boost::graph::distributed::default_priority_queue_gen,
typename Graph, typename WeightMap, typename DistanceMap, typename MessageGenerator>
time_type
run_delta_stepping_thread(amplusplus::transport& trans,
amplusplus::transport& barrier_trans,
Graph& g, const WeightMap& weight,
DistanceMap& distance,
typename graph_traits<Graph>::vertex_descriptor current_source,
weight_type delta, int num_threads, typename graph_traits<Graph>::
vertices_size_type n, bool verify, bool level_sync, MessageGenerator msg_gen,
int flushFreq) {
#ifdef CLONE
amplusplus::transport trans = trans.clone(); // Clone transport for this run
#endif
typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;
BGL_FORALL_VERTICES_T(v, g, Graph)
{ put(distance, v, std::numeric_limits<weight_type>::max()); }
trans.set_nthreads(num_threads);
boost::graph::distributed::delta_stepping_shortest_paths_thread<Graph, DistanceMap, WeightMap,
PriorityQueueGenerator, MessageGenerator>
D(g, distance, weight, trans, delta, flushFreq, msg_gen);
trans.set_nthreads(1);
D.set_source(current_source);
if (level_sync)
D.set_level_sync();
{ amplusplus::scoped_epoch epoch(barrier_trans); }
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
epoch_times.clear();
clear_buffer_stats();
#endif
// Many threads now
trans.set_nthreads(num_threads);
boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]);
for (int i = 0; i < num_threads - 1; ++i) {
boost::thread thr(boost::ref(D), i + 1);
threads[i].swap(thr);
}
D(0);
for (int i = 0; i < num_threads - 1; ++i)
threads[i].join();
time_type end = get_time();
time_type start = D.get_start_time();
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
print_and_clear_epoch_times();
print_buffer_stats();
#endif
#ifdef AMPLUSPLUS_PRINT_HIT_RATES
const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats();
print_and_accumulate_cache_stats(stats);
#endif
#ifdef PBGL2_PRINT_WORK_STATS
size_t edges_in_comp = count_edges(trans, g, distance, weight, current_source);
work_stats_t work_stats = D.get_work_stats();
print_and_accumulate_work_stats(work_stats, ds_stats, edges_in_comp);
#endif
// Back to one thread
trans.set_nthreads(1);
unsigned long long num_levels = D.get_num_levels();
if (verify) verify_sssp(trans, g, distance, weight);
vertices_size_type visited = 0;
BGL_FORALL_VERTICES_T(v, g, Graph) {
if (get(distance, v) < std::numeric_limits<weight_type>::max())
++visited;
}
boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> >
r(trans, std::plus<vertices_size_type>());
vertices_size_type total = r(visited);
if (verify)
if (trans.rank() == 0)
std::cout << "Visited " << total << " vertices of " << n << " in " << print_time(end - start)
<< ", " << num_levels << " levels required." << std::endl;
if (total < 100) return -1.;
return end - start;
}
template <typename PriorityQueueGenerator = boost::graph::distributed::pheet_priority_queue_gen_128, typename Graph, typename WeightMap, typename DistanceMap, typename MessageGenerator>
time_type
run_distributed_control_pheet(amplusplus::transport& trans,
amplusplus::transport& barrier_trans,
Graph& g, const WeightMap& weight,
DistanceMap& distance,
typename graph_traits<Graph>::vertex_descriptor current_source,
int num_threads, typename graph_traits<Graph>::vertices_size_type n,
bool verify, MessageGenerator msg_gen,
MessageGenerator priority_msg_gen,
unsigned int flushFreq,
unsigned int eager_limit) {
#ifdef CLONE
amplusplus::transport trans = trans.clone(); // Clone transport for this run
#endif
typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;
// Initialize with infinite (max) distance
BGL_FORALL_VERTICES_T(v, g, Graph)
{ put(distance, v, std::numeric_limits<weight_type>::max()); }
trans.set_nthreads(num_threads);
boost::graph::distributed::distributed_control_pheet<Graph, DistanceMap, WeightMap, PriorityQueueGenerator, MessageGenerator>
D(g, distance, weight, trans, msg_gen, priority_msg_gen, flushFreq, eager_limit);
trans.set_nthreads(1);
//trans.set_recvdepth(recvDepth);
D.set_source(current_source);
{ amplusplus::scoped_epoch epoch(barrier_trans); }
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
epoch_times.clear();
clear_buffer_stats();
#endif
// Many threads now
trans.set_nthreads(num_threads);
boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]);
for (int i = 0; i < num_threads - 1; ++i) {
boost::thread thr(boost::ref(D), i + 1);
threads[i].swap(thr);
}
D(0);
// TODO: Add exception handling. Excptions should be caught in every thread and checked in the main thread.
for (int i = 0; i < num_threads - 1; ++i)
threads[i].join();
time_type end = get_time();
time_type start = D.get_start_time();
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
print_and_clear_epoch_times();
print_buffer_stats();
#endif
#ifdef AMPLUSPLUS_PRINT_HIT_RATES
const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats();
print_and_accumulate_cache_stats(stats);
#endif
#ifdef PBGL2_PRINT_WORK_STATS
// calculate the number of edges
size_t edges_in_comp = count_edges(trans, g, distance, weight, current_source);
work_stats_t work_stats = D.get_work_stats();
print_and_accumulate_work_stats(work_stats, dc_stats, edges_in_comp);
#endif
// Back to one thread
trans.set_nthreads(1);
#ifdef PBGL2_PRINT_WORK_STATS
//get the queue size
size_t local_q_size = D.get_max_q_size();
print_q_stats(local_q_size);
#endif
if (verify) verify_sssp(trans, g, distance, weight);
vertices_size_type visited = 0;
BGL_FORALL_VERTICES_T(v, g, Graph) {
if (get(distance, v) < std::numeric_limits<weight_type>::max())
++visited;
}
boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> >
r(trans, std::plus<vertices_size_type>());
vertices_size_type total = r(visited);
if (verify)
if (trans.rank() == 0)
std::cout << "Visited " << total << " vertices of " << n << " in " << print_time(end - start) << "\n" << std::endl;
if (total < 100) return -1.;
return end - start;
}
template <typename PriorityQueueGenerator = boost::graph::distributed::default_priority_queue_gen, typename Graph, typename WeightMap, typename DistanceMap, typename MessageGenerator>
time_type
run_distributed_control_node(amplusplus::transport& trans,
amplusplus::transport& barrier_trans,
Graph& g, const WeightMap& weight,
DistanceMap& distance,
typename graph_traits<Graph>::vertex_descriptor current_source,
int num_threads, typename graph_traits<Graph>::vertices_size_type n,
bool verify, MessageGenerator msg_gen,
MessageGenerator priority_msg_gen,
unsigned int flushFreq,
unsigned int eager_limit,
bool numa=false) {
#ifdef CLONE
amplusplus::transport trans = trans.clone(); // Clone transport for this run
#endif
typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;
// Initialize with infinite (max) distance
BGL_FORALL_VERTICES_T(v, g, Graph)
{ put(distance, v, std::numeric_limits<weight_type>::max()); }
trans.set_nthreads(num_threads);
#ifdef LIB_CDS
// LIBCDS Stuff goes here
if (trans.rank() == 0)
std::cout << "Initializing LIBCDS .... " << std::endl;
cds::Initialize();
// Initialize Hazard Pointer singleton
cds::gc::HP hpGC;
// Attach for the main thread
cds::threading::Manager::attachThread();
#endif
boost::graph::distributed::distributed_control_node<Graph, DistanceMap, WeightMap, PriorityQueueGenerator, MessageGenerator>
D(g, distance, weight, trans, msg_gen, priority_msg_gen, flushFreq, eager_limit, numa);
trans.set_nthreads(1);
//trans.set_recvdepth(recvDepth);
D.set_source(current_source);
{ amplusplus::scoped_epoch epoch(barrier_trans); }
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
epoch_times.clear();
clear_buffer_stats();
#endif
// Many threads now
trans.set_nthreads(num_threads);
boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]);
for (int i = 0; i < num_threads - 1; ++i) {
boost::thread thr(boost::ref(D), i + 1);
threads[i].swap(thr);
}
D(0);
// TODO: Add exception handling. Excptions should be caught in every thread and checked in the main thread.
for (int i = 0; i < num_threads - 1; ++i)
threads[i].join();
time_type end = get_time();
time_type start = D.get_start_time();
#ifdef LIB_CDS
if (trans.rank() == 0)
std::cout << "Termminating LIBCDS .... " << std::endl;
cds::Terminate();
#endif
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
print_and_clear_epoch_times();
print_buffer_stats();
#endif
#ifdef AMPLUSPLUS_PRINT_HIT_RATES
const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats();
print_and_accumulate_cache_stats(stats);
#endif
#ifdef PBGL2_PRINT_WORK_STATS
size_t edges_in_comp = count_edges(trans, g, distance, weight, current_source);
work_stats_t work_stats = D.get_work_stats();
print_and_accumulate_work_stats(work_stats, dc_stats, edges_in_comp);
#endif
// Back to one thread
trans.set_nthreads(1);
#ifdef PBGL2_PRINT_WORK_STATS
//get the queue size
size_t local_q_size = D.get_max_q_size();
print_q_stats(local_q_size);
#endif
if (verify) verify_sssp(trans, g, distance, weight);
vertices_size_type visited = 0;
BGL_FORALL_VERTICES_T(v, g, Graph) {
if (get(distance, v) < std::numeric_limits<weight_type>::max())
++visited;
}
boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> >
r(trans, std::plus<vertices_size_type>());
vertices_size_type total = r(visited);
if (verify)
if (trans.rank() == 0)
std::cout << "Visited " << total << " vertices of " << n << " in " << print_time(end - start) << "\n" << std::endl;
if (total < 100) return -1.;
return end - start;
}
// Duplicating code; pretty bad ....
// TODO find the metaprogramming way to add cds initialization code
template <typename PriorityQueueGenerator = boost::graph::distributed::default_priority_queue_gen, typename Graph, typename WeightMap, typename DistanceMap, typename MessageGenerator>
time_type
run_distributed_control(amplusplus::transport& trans, amplusplus::transport& barrier_trans, Graph& g, const WeightMap& weight, DistanceMap& distance, typename graph_traits<Graph>::vertex_descriptor current_source, int num_threads, typename graph_traits<Graph>::vertices_size_type n, bool verify, MessageGenerator msg_gen, MessageGenerator priority_msg_gen, unsigned int flushFreq, unsigned int eager_limit) {
#ifdef CLONE
amplusplus::transport trans = trans.clone(); // Clone transport for this run
#endif
typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;
// Initialize with infinite (max) distance
BGL_FORALL_VERTICES_T(v, g, Graph)
{ put(distance, v, std::numeric_limits<weight_type>::max()); }
trans.set_nthreads(num_threads);
boost::graph::distributed::distributed_control<Graph, DistanceMap, WeightMap, PriorityQueueGenerator, MessageGenerator>
D(g, distance, weight, trans, msg_gen, priority_msg_gen, flushFreq, eager_limit);
trans.set_nthreads(1);
//trans.set_recvdepth(recvDepth);
D.set_source(current_source);
{ amplusplus::scoped_epoch epoch(barrier_trans); }
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
epoch_times.clear();
clear_buffer_stats();
#endif
// Many threads now
trans.set_nthreads(num_threads);
boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]);
for (int i = 0; i < num_threads - 1; ++i) {
boost::thread thr(boost::ref(D), i + 1);
threads[i].swap(thr);
}
D(0);
// TODO: Add exception handling. Excptions should be caught in every thread and checked in the main thread.
for (int i = 0; i < num_threads - 1; ++i)
threads[i].join();
time_type end = get_time();
time_type start = D.get_start_time();
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
print_and_clear_epoch_times();
print_buffer_stats();
#endif
#ifdef AMPLUSPLUS_PRINT_HIT_RATES
const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats();
print_and_accumulate_cache_stats(stats);
#endif
#ifdef PBGL2_PRINT_WORK_STATS
work_stats_t work_stats = D.get_work_stats();
size_t edges_in_comp = count_edges(trans, g, distance, weight, current_source);
print_and_accumulate_work_stats(work_stats, dc_stats, edges_in_comp);
// print q stats
print_q_stats(D.get_max_q_size(), D.get_avg_max_q_size());
#endif
// Back to one thread
trans.set_nthreads(1);
if (verify) verify_sssp(trans, g, distance, weight);
vertices_size_type visited = 0;
BGL_FORALL_VERTICES_T(v, g, Graph) {
if (get(distance, v) < std::numeric_limits<weight_type>::max())
++visited;
}
boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> >
r(trans, std::plus<vertices_size_type>());
vertices_size_type total = r(visited);
if (verify)
if (trans.rank() == 0)
std::cout << "Visited " << total << " vertices of " << n << " in " << print_time(end - start) << "\n" << std::endl;
if (total < 100) return -1.;
return end - start;
}
// Duplicating code; pretty bad ....
// TODO find the metaprogramming way to add cds initialization code
template <typename Graph, typename WeightMap, typename DistanceMap, typename MessageGenerator>
time_type
run_distributed_control_chaotic(amplusplus::transport& trans, amplusplus::transport& barrier_trans, Graph& g, const WeightMap& weight, DistanceMap& distance, typename graph_traits<Graph>::vertex_descriptor current_source, int num_threads, typename graph_traits<Graph>::vertices_size_type n, bool verify, MessageGenerator msg_gen, unsigned int flushFreq, unsigned int eager_limit) {
#ifdef CLONE
amplusplus::transport trans = trans.clone(); // Clone transport for this run
#endif
typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;
// Initialize with infinite (max) distance
BGL_FORALL_VERTICES_T(v, g, Graph)
{ put(distance, v, std::numeric_limits<weight_type>::max()); }
trans.set_nthreads(num_threads);
boost::graph::distributed::distributed_control_chaotic<Graph, DistanceMap, WeightMap, MessageGenerator>
D(g, distance, weight, trans, msg_gen, flushFreq, eager_limit);
trans.set_nthreads(1);
//trans.set_recvdepth(recvDepth);
D.set_source(current_source);
{ amplusplus::scoped_epoch epoch(barrier_trans); }
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
epoch_times.clear();
clear_buffer_stats();
#endif
// Many threads now
trans.set_nthreads(num_threads);
boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]);
for (int i = 0; i < num_threads - 1; ++i) {
boost::thread thr(boost::ref(D), i + 1);
threads[i].swap(thr);
}
D(0);
// TODO: Add exception handling. Excptions should be caught in every thread and checked in the main thread.
for (int i = 0; i < num_threads - 1; ++i)
threads[i].join();
time_type end = get_time();
time_type start = D.get_start_time();
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
print_and_clear_epoch_times();
print_buffer_stats();
#endif
#ifdef AMPLUSPLUS_PRINT_HIT_RATES
const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats();
print_and_accumulate_cache_stats(stats);
#endif
#ifdef PBGL2_PRINT_WORK_STATS
size_t edges_in_comp = count_edges(trans, g, distance, weight, current_source);
work_stats_t work_stats = D.get_work_stats();
print_and_accumulate_work_stats(work_stats, dc_stats, edges_in_comp);
#endif
// Back to one thread
trans.set_nthreads(1);
if (verify) verify_sssp(trans, g, distance, weight);
vertices_size_type visited = 0;
BGL_FORALL_VERTICES_T(v, g, Graph) {
if (get(distance, v) < std::numeric_limits<weight_type>::max())
++visited;
}
boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> >
r(trans, std::plus<vertices_size_type>());
vertices_size_type total = r(visited);
if (verify)
if (trans.rank() == 0)
std::cout << "Visited " << total << " vertices of " << n << " in " << print_time(end - start) << "\n" << std::endl;
if (total < 100) return -1.;
return end - start;
}
template <typename Graph, typename MessageGenerator>
time_type
run_ps_sv_cc(amplusplus::transport& trans,
Graph& g,
int num_threads,
bool verify,
bool level_sync,
MessageGenerator msg_gen,
size_t vertices_per_lock) {
#ifdef CLONE
amplusplus::transport trans = trans.clone(); // Clone transport for this run
#endif
if (trans.rank() == 0) std::cout << "Initializing PS-SV-CC algorithm ... " << std::endl;
// Instantiate algorithms used later here so we don't time their constructions
typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;
typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
typedef typename property_map<Graph, vertex_index_t>::type VertexIndexMap;
// Parent, component, and lock maps for SV CC
std::vector<Vertex> parentS(num_vertices(g), graph_traits<Graph>::null_vertex());
typedef iterator_property_map<typename std::vector<Vertex>::iterator, VertexIndexMap> ParentMap;
ParentMap parent(parentS.begin(), get(vertex_index, g));
std::vector<int> sv_componentS(num_vertices(g), std::numeric_limits<int>::max());
typedef iterator_property_map<std::vector<int>::iterator, VertexIndexMap> ComponentMap;
ComponentMap component(sv_componentS.begin(), get(vertex_index, g));
typedef boost::parallel::lock_map<VertexIndexMap> LockMap;
LockMap locks(get(vertex_index, g), num_vertices(g) / vertices_per_lock);
BGL_FORALL_VERTICES_T(v, g, Graph) {
put(parent, v, v);
}
using boost::parallel::all_reduce;
using boost::parallel::maximum;
all_reduce<vertices_size_type, maximum<vertices_size_type> >
reduce_max(trans, maximum<vertices_size_type>());
// TODO: If level_sync we should make the PS below a BFS
boost::graph::distributed::parallel_search<Graph, ParentMap, MessageGenerator>
PS(g, parent, graph_traits<Graph>::null_vertex(), msg_gen);
trans.set_nthreads(num_threads);
boost::graph::distributed::connected_components<Graph, ParentMap, MessageGenerator>
CC(trans, g, parent, locks, msg_gen);
trans.set_nthreads(1);
if (level_sync)
CC.set_level_sync();
// Less than on vertices w/ special casing for null_vertex() so we start parallel
// search from the same vertex below
typedef typename property_map<Graph, vertex_owner_t>::const_type OwnerMap;
typedef typename property_map<Graph, vertex_local_t>::const_type LocalMap;
typedef graph::distributed::cc_vertex_compare<OwnerMap, LocalMap> VertexLessThan;
VertexLessThan vertex_lt(get(vertex_owner, g), get(vertex_local, g));
//
// Start timing loop
//
{ amplusplus::scoped_epoch epoch(trans); }
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
epoch_times.clear();
clear_buffer_stats();
#endif
if (trans.rank() == 0) std::cout << "Starting PS-SV-CC algorithm ... " << std::endl;
time_type start = get_time();
//
// Find max-degree vertex (gotta time this part too)
//
Vertex max_v = graph_traits<Graph>::null_vertex(); // Avoid uninitialized warning
{
vertices_size_type degree = 0;
BGL_FORALL_VERTICES_T(v, g, Graph) {
if (out_degree(v, g) > degree) {
degree = out_degree(v, g);
max_v = v;
}
}
using boost::parallel::all_reduce;
using boost::parallel::maximum;
vertices_size_type max = reduce_max(degree);
// If the max-degree vertex is somewhere else then clear local max v
// Note: This fails to handle two vertices with the same degree... in
// that case the parallel search may start from more than one
// vertex, which is perfectly acceptable provided they're in the
// same component... a reasonable but not fool-proof assumption
if (max != degree)
max_v = graph_traits<Graph>::null_vertex();
}
// Find global minimum vertex w/ max degree as source so all procs start
// at the same place
all_reduce<Vertex, VertexLessThan> min_vertex(trans, vertex_lt);
max_v = min_vertex(max_v);
//
// Run parallel search from max_v, this will mark all reachable vertices with
// null_vertex() in parent map
//
PS.run(max_v);
#ifdef PRINT_STATS
all_reduce<vertices_size_type, std::plus<vertices_size_type> >
reduce_plus(trans, std::plus<vertices_size_type>());
vertices_size_type giant_component_count = 0;
BGL_FORALL_VERTICES_T(v, g, Graph) {
if (get(parent, v) == graph_traits<Graph>::null_vertex())
++giant_component_count;
}
vertices_size_type total = reduce_plus(giant_component_count);
if (verify)
if (trans.rank() == 0)
std::cout << total << " vertices in giant component\n";
#endif
//
// Run SV CC on filtered graph
//
trans.set_nthreads(num_threads);
boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]);
for (int i = 0; i < num_threads - 1; ++i) {
boost::thread thr(boost::ref(CC), i + 1);
threads[i].swap(thr);
}
CC(0);
for (int i = 0; i < num_threads - 1; ++i)
threads[i].join();
time_type end = get_time();
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
print_and_clear_epoch_times();
print_buffer_stats();
#endif
if (trans.rank() == 0) std::cout << "Done with PS-SV-CC algorithm in : " << (end-start) << std::endl;
// Back to one thread
trans.set_nthreads(1);
#ifdef NUMBER_COMPONENTS
#error "Should be disabled for performance testing"
int num_components = CC.template number_components<ComponentMap>(component);
if (trans.rank() == 0)
std::cout << num_components << " components found\n";
#endif
if (verify) {
if (trans.rank() == 0) std::cout << "Verifying PS-SV-CC algorithm ... " << std::endl;
parent.set_consistency_model(boost::parallel::cm_forward);
parent.set_max_ghost_cells(0);
{
amplusplus::scoped_epoch epoch(g.transport());
BGL_FORALL_VERTICES_T(v, g, Graph) {
BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {
get(parent, source(e, g));
get(parent, target(e, g));
}
}
}
BGL_FORALL_VERTICES_T(v, g, Graph) {
BGL_FORALL_ADJ_T(v, u, g, Graph) {
#ifdef PRINT_DEBUG
if (get(parent, v) != get(parent, u))
std::cout << trans.rank() << ": parent(" << get(get(vertex_local, g), v) << "@"
<< get(get(vertex_owner, g), v) << ") = " << get(get(vertex_local, g), get(parent, v))
<< "@" << get(get(vertex_owner, g), get(parent, v)) << " parent("
<< get(get(vertex_local, g), u) << "@" << get(get(vertex_owner, g), u)
<< ") = " << get(get(vertex_local, g), get(parent, u))
<< "@" << get(get(vertex_owner, g), get(parent, u)) << std::endl;
#else
assert(get(parent, v) == get(parent, u));
#endif
}
}
parent.clear(); // Clear memory used by ghost cells
}
return time_type(end - start);
}
template <typename Graph, typename MessageGenerator>
time_type
run_sv_c_c(amplusplus::transport& trans, Graph& g,
int num_threads,
bool verify,
bool level_sync,
MessageGenerator msg_gen,
size_t vertices_per_lock) {
#ifdef CLONE
amplusplus::transport trans = trans_passed.clone(); // Clone transport for this run
#endif
if (trans.rank() == 0) std::cout << "Initializing SV-CC algorithm ... " << std::endl;
// Instantiate algorithms used later here so we don't time their constructions
typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;
typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
typedef typename property_map<Graph, vertex_index_t>::type VertexIndexMap;
// Parent, component, and lock maps for SV CC
std::vector<Vertex> parentS(num_vertices(g), graph_traits<Graph>::null_vertex());
typedef iterator_property_map<typename std::vector<Vertex>::iterator, VertexIndexMap> ParentMap;
ParentMap parent(parentS.begin(), get(vertex_index, g));
std::vector<int> sv_componentS(num_vertices(g), std::numeric_limits<int>::max());
typedef iterator_property_map<std::vector<int>::iterator, VertexIndexMap> ComponentMap;
ComponentMap component(sv_componentS.begin(), get(vertex_index, g));
typedef boost::parallel::lock_map<VertexIndexMap> LockMap;
LockMap locks(get(vertex_index, g), num_vertices(g) / vertices_per_lock);
if (trans.rank() == 0) std::cout << "Number of vertices : " << num_vertices(g) << std::endl;
BGL_FORALL_VERTICES_T(v, g, Graph) {
put(parent, v, v);
}
trans.set_nthreads(num_threads);
boost::graph::distributed::sv_cc<Graph, ParentMap, MessageGenerator>
CC(trans, g, parent, locks, msg_gen);
trans.set_nthreads(1);
if (level_sync)
CC.set_level_sync();
{ amplusplus::scoped_epoch epoch(trans); }
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
epoch_times.clear();
clear_buffer_stats();
#endif
if (trans.rank() == 0) std::cout << "Starting SV-CC algorithm ... " << std::endl;
time_type start = get_time();
// Many threads now
trans.set_nthreads(num_threads);
boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]);
for (int i = 0; i < num_threads - 1; ++i) {
boost::thread thr(boost::ref(CC), i + 1);
threads[i].swap(thr);
}
CC(0);
for (int i = 0; i < num_threads - 1; ++i)
threads[i].join();
time_type end = get_time();
// Back to one thread
trans.set_nthreads(1);
if (trans.rank() == 0) std::cout << "Done with SV-CC algorithm in : " << (end-start) << std::endl;
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
print_and_clear_epoch_times();
print_buffer_stats();
#endif
#ifdef NUMBER_COMPONENTS
int num_components = CC.template number_components<ComponentMap>(component);
if (trans.rank() == 0)
std::cout << num_components << " components found\n";
#endif
CC.print_stats();
if (verify) {
if (trans.rank() == 0) std::cout << "Verifying SV-CC algorithm ... " << std::endl;
parent.set_consistency_model(boost::parallel::cm_forward);
parent.set_max_ghost_cells(0);
{
amplusplus::scoped_epoch epoch(g.transport());
BGL_FORALL_VERTICES_T(v, g, Graph) {
BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {
get(parent, source(e, g));
get(parent, target(e, g));
}
}
}
{
amplusplus::scoped_epoch epoch(trans); // at the moment get() sends a message
BGL_FORALL_VERTICES_T(v, g, Graph) {
if (out_degree(v, g) == 0) {
assert(get(parent, v) == v);
}
BGL_FORALL_ADJ_T(v, u, g, Graph) {
#ifdef PRINT_DEBUG
if (get(parent, v) != get(parent, u))
std::cout << trans.rank() << ": parent(" << get(get(vertex_local, g), v) << "@"
<< get(get(vertex_owner, g), v) << ") = " << get(get(vertex_local, g), get(parent, v))
<< "@" << get(get(vertex_owner, g), get(parent, v)) << " parent("
<< get(get(vertex_local, g), u) << "@" << get(get(vertex_owner, g), u)
<< ") = " << get(get(vertex_local, g), get(parent, u))
<< "@" << get(get(vertex_owner, g), get(parent, u)) << std::endl;
#else
assert(get(parent, v) == get(parent, u));
#endif
}
}
}
parent.clear(); // Clear memory used by ghost cells
}
return time_type(end - start);
}
template <typename Graph, typename MessageGenerator>
time_type
run_sv_cc_optimized(amplusplus::transport& trans, Graph& g,
int num_threads,
bool verify,
bool level_sync,
MessageGenerator msg_gen,
size_t vertices_per_lock) {
#ifdef CLONE
amplusplus::transport trans = trans_passed.clone(); // Clone transport for this run
#endif
if (trans.rank() == 0) std::cout << "Initializing SV-CC algorithm ... " << std::endl;
// Instantiate algorithms used later here so we don't time their constructions
typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;
typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
typedef typename property_map<Graph, vertex_index_t>::type VertexIndexMap;
// Parent, component, and lock maps for SV CC
std::vector<Vertex> parentS(num_vertices(g), graph_traits<Graph>::null_vertex());
typedef iterator_property_map<typename std::vector<Vertex>::iterator, VertexIndexMap> ParentMap;
ParentMap parent(parentS.begin(), get(vertex_index, g));
std::vector<int> sv_componentS(num_vertices(g), std::numeric_limits<int>::max());
typedef iterator_property_map<std::vector<int>::iterator, VertexIndexMap> ComponentMap;
ComponentMap component(sv_componentS.begin(), get(vertex_index, g));
typedef boost::parallel::lock_map<VertexIndexMap> LockMap;
LockMap locks(get(vertex_index, g), num_vertices(g) / vertices_per_lock);
if (trans.rank() == 0) std::cout << "Number of vertices : " << num_vertices(g) << std::endl;
BGL_FORALL_VERTICES_T(v, g, Graph) {
put(parent, v, v);
}
trans.set_nthreads(num_threads);
boost::graph::distributed::connected_components<Graph, ParentMap, MessageGenerator>
CC(trans, g, parent, locks, msg_gen);
trans.set_nthreads(1);
if (level_sync)
CC.set_level_sync();
{ amplusplus::scoped_epoch epoch(trans); }
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
epoch_times.clear();
clear_buffer_stats();
#endif
if (trans.rank() == 0) std::cout << "Starting SV-CC-Opt algorithm ... " << std::endl;
time_type start = get_time();
// Many threads now
trans.set_nthreads(num_threads);
boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]);
for (int i = 0; i < num_threads - 1; ++i) {
boost::thread thr(boost::ref(CC), i + 1);
threads[i].swap(thr);
}
CC(0);
for (int i = 0; i < num_threads - 1; ++i)
threads[i].join();
time_type end = get_time();
// Back to one thread
trans.set_nthreads(1);
if (trans.rank() == 0) std::cout << "Done with SV-CC algorithm in : " << (end-start) << std::endl;
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
print_and_clear_epoch_times();
print_buffer_stats();
#endif
#ifdef NUMBER_COMPONENTS
int num_components = CC.template number_components<ComponentMap>(component);
if (trans.rank() == 0)
std::cout << num_components << " components found\n";
#endif
if (verify) {
if (trans.rank() == 0) std::cout << "Verifying SV-CC algorithm ... " << std::endl;
parent.set_consistency_model(boost::parallel::cm_forward);
parent.set_max_ghost_cells(0);
{
amplusplus::scoped_epoch epoch(g.transport());
BGL_FORALL_VERTICES_T(v, g, Graph) {
BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {
get(parent, source(e, g));
get(parent, target(e, g));
}
}
}
{
amplusplus::scoped_epoch epoch(trans); // at the moment get() sends a message
BGL_FORALL_VERTICES_T(v, g, Graph) {
if (out_degree(v, g) == 0) {
assert(get(parent, v) == v);
}
BGL_FORALL_ADJ_T(v, u, g, Graph) {
#ifdef PRINT_DEBUG
if (get(parent, v) != get(parent, u))
std::cout << trans.rank() << ": parent(" << get(get(vertex_local, g), v) << "@"
<< get(get(vertex_owner, g), v) << ") = " << get(get(vertex_local, g), get(parent, v))
<< "@" << get(get(vertex_owner, g), get(parent, v)) << " parent("
<< get(get(vertex_local, g), u) << "@" << get(get(vertex_owner, g), u)
<< ") = " << get(get(vertex_local, g), get(parent, u))
<< "@" << get(get(vertex_owner, g), get(parent, u)) << std::endl;
#else
assert(get(parent, v) == get(parent, u));
#endif
}
}
}
parent.clear(); // Clear memory used by ghost cells
}
return time_type(end - start);
}
template <typename PriorityQueueGenerator = boost::graph::distributed::cc_default_priority_queue_gen,
typename Graph,
typename MessageGenerator>
time_type
run_data_driven_cc(amplusplus::transport& trans,
amplusplus::transport& barrier_trans,
Graph& g,
int num_threads,
typename graph_traits<Graph>::vertices_size_type n,
bool verify,
bool print_stats,
bool allstats,
MessageGenerator msg_gen,
MessageGenerator priority_msg_gen,
unsigned int flushFreq,
unsigned int eager_limit) {
#ifdef CLONE
amplusplus::transport trans = trans.clone(); // Clone transport for this run
#endif
if (trans.rank() == 0) std::cout << "Initializing data driven connected components ..." << std::endl;
typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;
std::vector<Vertex> componentS(num_vertices(g), std::numeric_limits<Vertex>::max());
typedef typename property_map<Graph, vertex_index_t>::type VertexIndexMap;
typedef iterator_property_map<typename std::vector<Vertex>::iterator, VertexIndexMap> ComponentsMap;
ComponentsMap components(componentS.begin(), get(vertex_index, g));
//#ifndef CC_PRIORITY
BGL_FORALL_VERTICES_T(v, g, Graph) {
put(components, v, v);
}
//#endif
std::cout << "Rank: " << trans.rank() << ", Number of vertices : " << num_vertices(g)
<< "Number of edges : " << num_edges(g) << " total vertices : " << n << std::endl;
trans.set_nthreads(num_threads);
boost::graph::distributed::data_driven_cc<Graph, ComponentsMap, PriorityQueueGenerator, MessageGenerator>
D(g, components, trans, msg_gen, priority_msg_gen, flushFreq, eager_limit);
trans.set_nthreads(1);
{ amplusplus::scoped_epoch epoch(barrier_trans); }
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
epoch_times.clear();
clear_buffer_stats();
#endif
if (trans.rank() == 0) std::cout << "Invoking DD-CC algorithm ......" << std::endl;
// Many threads now
trans.set_nthreads(num_threads);
boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]);
for (int i = 0; i < num_threads - 1; ++i) {
boost::thread thr(boost::ref(D), i + 1);
threads[i].swap(thr);
}
D(0);
for (int i = 0; i < num_threads - 1; ++i)
threads[i].join();
time_type start = D.get_start_time();
time_type end = D.get_end_time();
if (trans.rank() == 0) std::cout << "Done with DD-CC algorithm in : " << (end-start) << std::endl;
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
print_and_clear_epoch_times();
print_buffer_stats();
#endif
#ifdef AMPLUSPLUS_PRINT_HIT_RATES
//const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats();
//print_and_accumulate_cache_stats(stats);
#endif
#ifdef PBGL2_PRINT_WORK_STATS
//work_stats_t work_stats = D.get_work_stats();
//print_and_accumulate_work_stats(work_stats, dc_stats);
#endif
// Back to one thread
trans.set_nthreads(1);
if (verify) {
verify_cc(g, components);
}
if (print_stats)
calculate_cc_stats(g, components, n, allstats);
if (trans.rank() == 0) std::cout << "End invoking algorithm ..." << std::endl;
return end - start;
}
// Run chaotic CC
template <typename Graph, typename MessageGenerator>
time_type
run_chaotic_cc(amplusplus::transport& trans,
amplusplus::transport& barrier_trans,
Graph& g,
int num_threads,
typename graph_traits<Graph>::vertices_size_type n,
bool verify,
bool print_stats,
bool allstats,
MessageGenerator msg_gen) {
#ifdef CLONE
amplusplus::transport trans = trans.clone(); // Clone transport for this run
#endif
if (trans.rank() == 0) std::cout << "Initializing data driven connected components ..." << std::endl;
typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;
std::vector<Vertex> componentS(num_vertices(g), std::numeric_limits<Vertex>::max());
typedef typename property_map<Graph, vertex_index_t>::type VertexIndexMap;
typedef iterator_property_map<typename std::vector<Vertex>::iterator, VertexIndexMap> ComponentsMap;
ComponentsMap components(componentS.begin(), get(vertex_index, g));
if (trans.rank() == 0) std::cout << "Number of vertices : " << num_vertices(g) << " total : " << n << std::endl;
trans.set_nthreads(num_threads);
boost::graph::distributed::chaotic_cc<Graph, ComponentsMap, MessageGenerator>
D(g, components, trans, n, msg_gen);
trans.set_nthreads(1);
{ amplusplus::scoped_epoch epoch(barrier_trans); }
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
epoch_times.clear();
clear_buffer_stats();
#endif
if (trans.rank() == 0) std::cout << "Invoking DD-CC algorithm ......" << std::endl;
time_type start = get_time();
// Many threads now
trans.set_nthreads(num_threads);
boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]);
for (int i = 0; i < num_threads - 1; ++i) {
boost::thread thr(boost::ref(D), i + 1);
threads[i].swap(thr);
}
D(0);
// TODO: Add exception handling. Excptions should be caught in every thread and checked in the main thread.
for (int i = 0; i < num_threads - 1; ++i)
threads[i].join();
time_type end = get_time();
if (trans.rank() == 0) std::cout << "Done with Chaotic-CC algorithm in : " << (end-start) << std::endl;
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
print_and_clear_epoch_times();
print_buffer_stats();
#endif
#ifdef AMPLUSPLUS_PRINT_HIT_RATES
//const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats();
//print_and_accumulate_cache_stats(stats);
#endif
// Back to one thread
trans.set_nthreads(1);
if (verify) {
verify_cc(g, components);
} // end verify
if (print_stats)
calculate_cc_stats(g, components, n, allstats);
if (trans.rank() == 0) std::cout << "End invoking algorithm ..." << std::endl;
return end - start;
}
/**
* One-to-one mapping of vertices. In this case
* vertex is mapped to running id. Id is increase column wise.
* 1 4
* 2 5
* 3 6
*/
template<typename Graph>
struct block_id_distribution {
typedef typename graph_traits<Graph>::vertices_size_type VerticesSzType;
public:
block_id_distribution(Graph& _pg, VerticesSzType& pn):g(_pg), n(pn) {
if (_RANK == 0)
std::cout << "[INFO] Using vertical id distribution" << std::endl;
}
template<typename SizeType>
SizeType operator()(SizeType k) {
SizeType blocksz = g.distribution().block_size(0, n);
return (get(get(vertex_owner, g), k))*blocksz + g.distribution().local(k);
}
private:
Graph& g;
VerticesSzType n;
};
/**
* One-to-one mapping of vertices. In this case
* vertex is mapped to running id. Id is increase row wise.
* 1 2
* 3 4
* 5 6
*/
template<typename Graph>
struct row_id_distribution {
public:
row_id_distribution(Graph& _pg, int ranks):g(_pg), totalranks(ranks) {
if (_RANK == 0)
std::cout << "[INFO] Using horizontal id distribution" << std::endl;
}
template<typename SizeType>
SizeType operator()(SizeType k) {
auto offset = g.distribution().local(k) * totalranks;
return offset + get(get(vertex_owner, g), k);
}
private:
Graph& g;
int totalranks;
};
// Run delta-stepping CC
template <typename Graph, typename MessageGenerator, typename IdDistribution>
time_type
run_delta_cc(amplusplus::transport& trans,
amplusplus::transport& barrier_trans,
Graph& g,
int num_threads,
typename graph_traits<Graph>::vertices_size_type n,
size_t nbuckets,
IdDistribution idd,
bool verify,
bool print_stats,
bool allstats,
MessageGenerator msg_gen) {
#ifdef CLONE
amplusplus::transport trans = trans.clone(); // Clone transport for this run
#endif
if (trans.rank() == 0)
std::cout << "Initializing delta connected components with buckets = "
<< nbuckets << "..." << std::endl;
typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
#ifdef PRINT_DEBUG
block_id_distribution<Graph> logical_block_id(g, n);
row_id_distribution<Graph> logical_row_block_id(g, trans.size());
if (trans.rank()==0) {
std::cout << "Printing vertex information in rank " << trans.rank() << std::endl;
std::cout << "==========================================================" << std::endl;
BGL_FORALL_VERTICES_T(v, g, Graph) {
std::cout << "vid: " << v << ", local id : " << g.distribution().local(v)
<< ", logical block id: " << logical_block_id(v)
<< ", logical row block id : " << logical_row_block_id(v)
<< std::endl;
/* BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {
Vertex u = target(e, g);
std::cout << "neighbor vid: " << u << ", local id : " << g.distribution().local(u)
<< ", logical block id: " << logical_block_id(u, g, n)
<< ", logical row block id : " << logical_row_block_id(u, g, trans.size())
<< std::endl;
}*/
}
}
MPI_Barrier(MPI_COMM_WORLD);
if (trans.rank()==1) {
std::cout << "Printing vertex information in rank " << trans.rank() << std::endl;
std::cout << "==========================================================" << std::endl;
BGL_FORALL_VERTICES_T(v, g, Graph) {
std::cout << "vid: " << v << ", local id : " << g.distribution().local(v)
<< ", logical block id: " << logical_block_id(v)
<< ", logical row block id : " << logical_row_block_id(v)
<< std::endl;
}
}
MPI_Barrier(MPI_COMM_WORLD);
if (trans.rank()==2) {
std::cout << "Printing vertex information in rank " << trans.rank() << std::endl;
std::cout << "==========================================================" << std::endl;
BGL_FORALL_VERTICES_T(v, g, Graph) {
std::cout << "vid: " << v << ", local id : " << g.distribution().local(v)
<< ", logical block id: " << logical_block_id(v, g, n)
<< ", logical row block id : " << logical_row_block_id(v, g, trans.size())
<< std::endl;
BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {
Vertex u = target(e, g);
std::cout << "neighbor vid: " << u << ", local id : " << g.distribution().local(u)
<< ", logical block id: " << logical_block_id(u, g, n)
<< ", logical row block id : " << logical_row_block_id(u, g, trans.size())
<< std::endl;
}
}
}
MPI_Barrier(MPI_COMM_WORLD);
if (trans.rank()==3) {
std::cout << "Printing vertex information in rank " << trans.rank() << std::endl;
std::cout << "==========================================================" << std::endl;
BGL_FORALL_VERTICES_T(v, g, Graph) {
std::cout << "vid: " << v << ", local id" << g.distribution().local(v)
<< ", logical block id: " << logical_block_id(v, g, n)
<< ", logical row block id : " << logical_row_block_id(v, g, trans.size())
<< std::endl;
}
}
MPI_Barrier(MPI_COMM_WORLD);
#endif
typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;
std::vector<Vertex> componentS(num_vertices(g), std::numeric_limits<Vertex>::max());
typedef typename property_map<Graph, vertex_index_t>::type VertexIndexMap;
typedef iterator_property_map<typename std::vector<Vertex>::iterator, VertexIndexMap> ComponentsMap;
ComponentsMap components(componentS.begin(), get(vertex_index, g));
BGL_FORALL_VERTICES_T(v, g, Graph) {
put(components, v, v);
}
if (trans.rank() == 0) std::cout << "Number of vertices : " << num_vertices(g) << " total : " << n << std::endl;
trans.set_nthreads(num_threads);
boost::graph::distributed::delta_stepping_cc<Graph,
ComponentsMap,
IdDistribution,
MessageGenerator>
D(g, components, trans, nbuckets, idd, msg_gen);
trans.set_nthreads(1);
{ amplusplus::scoped_epoch epoch(barrier_trans); }
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
epoch_times.clear();
clear_buffer_stats();
#endif
if (trans.rank() == 0) std::cout << "Invoking Delta-CC algorithm ......" << std::endl;
time_type start = get_time();
// Many threads now
trans.set_nthreads(num_threads);
boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]);
for (int i = 0; i < num_threads - 1; ++i) {
boost::thread thr(boost::ref(D), i + 1);
threads[i].swap(thr);
}
D(0);
// TODO: Add exception handling. Excptions should be caught in every thread and checked in the main thread.
for (int i = 0; i < num_threads - 1; ++i)
threads[i].join();
time_type end = get_time();
if (trans.rank() == 0) std::cout << "Done with Delta-CC algorithm in : " << (end-start) << std::endl;
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
print_and_clear_epoch_times();
print_buffer_stats();
#endif
#ifdef AMPLUSPLUS_PRINT_HIT_RATES
//const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats();
//print_and_accumulate_cache_stats(stats);
#endif
// Back to one thread
trans.set_nthreads(1);
if (verify) {
verify_cc(g, components);
}
if (print_stats)
calculate_cc_stats(g, components, n, allstats);
if (trans.rank() == 0) std::cout << "End invoking algorithm ..." << std::endl;
return end - start;
}
// Run level CC
template <typename Graph, typename MessageGenerator>
time_type
run_level_sync_cc(amplusplus::transport& trans,
amplusplus::transport& barrier_trans,
Graph& g,
int num_threads,
typename graph_traits<Graph>::vertices_size_type n,
bool verify,
bool print_stats,
bool allstats,
MessageGenerator msg_gen) {
#ifdef CLONE
amplusplus::transport trans = trans.clone(); // Clone transport for this run
#endif
if (trans.rank() == 0)
std::cout << "Initializing level sync connected components... "
<< std::endl;
typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;
std::vector<Vertex> componentS(num_vertices(g), std::numeric_limits<Vertex>::max());
typedef typename property_map<Graph, vertex_index_t>::type VertexIndexMap;
typedef iterator_property_map<typename std::vector<Vertex>::iterator, VertexIndexMap> ComponentsMap;
ComponentsMap components(componentS.begin(), get(vertex_index, g));
BGL_FORALL_VERTICES_T(v, g, Graph) {
put(components, v, v);
}
if (trans.rank() == 0) std::cout << "Number of vertices : " << num_vertices(g) << " total : " << n << std::endl;
trans.set_nthreads(num_threads);
boost::graph::distributed::level_sync_cc<Graph,
ComponentsMap,
MessageGenerator>
D(g, components, trans, n, msg_gen);
trans.set_nthreads(1);
{ amplusplus::scoped_epoch epoch(barrier_trans); }
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
epoch_times.clear();
clear_buffer_stats();
#endif
if (trans.rank() == 0) std::cout << "Invoking level-sync-CC algorithm ......" << std::endl;
// Many threads now
trans.set_nthreads(num_threads);
boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]);
for (int i = 0; i < num_threads - 1; ++i) {
boost::thread thr(boost::ref(D), i + 1);
threads[i].swap(thr);
}
D(0);
for (int i = 0; i < num_threads - 1; ++i)
threads[i].join();
time_type end = get_time();
time_type start = D.get_start_time();
if (trans.rank() == 0)
std::cout << "Done with level-sync-CC algorithm in : " << (end-start)
<< ", buckets(levels) processed : "
<< D.get_num_levels() << std::endl;
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
print_and_clear_epoch_times();
print_buffer_stats();
#endif
#ifdef AMPLUSPLUS_PRINT_HIT_RATES
//const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats();
//print_and_accumulate_cache_stats(stats);
#endif
// Back to one thread
trans.set_nthreads(1);
if (verify) {
verify_cc(g, components);
}
if (print_stats)
calculate_cc_stats(g, components, n, allstats);
if (trans.rank() == 0) std::cout << "End invoking algorithm ..." << std::endl;
return end - start;
}
enum mode_type {mode_none, mode_self, mode_async_bfs, mode_ds_async_bfs, mode_level_synchronized_bfs, mode_delta_stepping, mode_dc, mode_connected_components, mode_page_rank};
enum routing_type {rt_none, rt_hypercube, rt_rook};
// functions to separate edge weight and edge
// separating edge
template<typename t1, typename t2>
struct select_edge : std::unary_function< std::pair<t1, std::pair<t1, t2> >, std::pair<t1, t1> > {
public:
select_edge() {}
std::pair<t1, t1> operator()(std::pair<t1, std::pair<t1, t2> >& ew) const {
return std::make_pair(ew.first, ew.second.first);
}
};
// separating edge weight
template<typename t1, typename t2>
struct select_edge_weight : std::unary_function< std::pair<t1, std::pair<t1, t2> >, t2 > {
public:
select_edge_weight() {}
t2 operator()(std::pair<t1, std::pair<t1, t2> >& ew) const {
return ew.second.second;
}
};
template<typename T>
void time_statistics(std::vector<T>& data,
T& m,
T& minimum,
T& q1,
T& median,
T& q3,
T& maximum,
T& stddev) {
using namespace boost::accumulators;
accumulator_set<T, stats<tag::variance> > acc;
for_each(data.begin(), data.end(), bind<void>(ref(acc), _1));
m = mean(acc);
stddev = sqrt(variance(acc));
auto const min = 0;
auto const Q1 = data.size() / 4;
auto const Q2 = data.size() / 2;
auto const Q3 = Q1 + Q2;
auto const max = data.size() - 1;
std::nth_element(data.begin(), data.begin() + min, data.end());
minimum = data[min];
std::nth_element(data.begin(), data.begin() + Q1, data.end());
q1 = data[Q1];
std::nth_element(data.begin() + Q1 + 1, data.begin() + Q2, data.end());
median = data[Q2];
std::nth_element(data.begin() + Q2 + 1, data.begin() + Q3, data.end());
q3 = data[Q3];
std::nth_element(data.begin() + Q3 + 1, data.begin() + max, data.end());
maximum = data[max];
}
class dc_test {
private:
std::vector<int> thread_num_vals;
size_t scale = 20, num_sources = 64, iterations = 20;
double edgefactor = 16;
unsigned long long n = static_cast<unsigned long long>(floor(pow(2, scale)));
bool verify = false, level_sync = false, stats = true;
uint64_t seed64 = 12345;
weight_type C = 100;
weight_type delta_min = 1, delta_max = 1, delta_step = 1;
unsigned int levels_min = 1, levels_max = 1, levels_step = 1;
mode_type mode = mode_none;
std::vector<routing_type> routing;
double edge_list_reserve_factor = 1.15;
bool no_reductions = false, per_thread_reductions = true;
std::vector<size_t> coalescing_size;
size_t distribution_coalescing_size = 1 << 17;
std::vector<size_t> reduction_cache_size;
std::vector<unsigned int> number_poll_task;
std::vector<std::string> dc_data_structures;
std::vector<unsigned int> flushFreq;
std::vector<unsigned int> eager_limit;
std::vector<unsigned int> recvDepth;
std::vector<unsigned int> delta;
std::vector<unsigned int> k_levels = {1};
std::vector<unsigned int> priority_coalescing_size_v = {40000};
bool run_dc = false, run_chaotic = false, run_ds = false, run_kla = false;
// distributions
enum distribution_t {
block,
cyclic
};
size_t block_size = 10;
// default block distribution
distribution_t distribution_type = block;
id_distribution_t id_distribution;
// mis
bool run_ss_mis = false;
bool run_bucket_mis = false;
bool run_luby_mis = false;
std::vector<std::string> luby_algorithms;
// connected components
bool run_cc = false;
std::vector<std::string> cc_algorithms;
// Available CC algorithms
// 1. run_sv_cc
// 2. run_sv_cc_level_sync
// 3. run_sv_cc_opt
// 4. run_sv_cc_opt_level_sync
// 5. run_sv_ps_cc // optimized version
// 6. run_sv_ps_cc_level_sync // optmized version
// 7. run_dd_cc
// 8. run_cc_chaotic
// 9. run_cc_ds // delta stepping cc
// 10. run_level_sync_cc // level sync agm
// data driven connected components
size_t vertices_per_lock = 64;
std::vector<size_t> nbuckets;
size_t cutoff_degree = 0;
// CC stats
// print CC stats
bool print_cc_stats = false;
// print all CC stats (otherwise limited to 5)
bool allstats = false;
// read graph from file
std::string graph_file;
bool read_graph = false;
bool gen_graph = false;
bool with_weight = false;
public:
dc_test(int argc, char* argv[]) {
for (int i = 1; i < argc; ++i) {
std::string arg = argv[i];
if(arg == "--receive-depth") {
recvDepth = extract_params<unsigned int>( argv[i+1] );
//std::cerr<<"receiveDepth from main"<<recvDepth<<std::endl;
}
if (arg == "--threads") {
thread_num_vals = extract_params<int>(argv[i+1]);
}
if (arg == "--graph-file") {
graph_file = argv[i+1];
read_graph = true;
}
if (arg == "--with-weight") {
// read the graph file with weight
with_weight = true;
}
if (arg == "--seed") {
seed64 = boost::lexical_cast<uint64_t>( argv[i+1] );
}
if (arg == "--scale") {
scale = boost::lexical_cast<size_t>( argv[i+1] );
n = (unsigned long long)(1) << scale;
gen_graph = true;
}
if (arg == "--degree")
edgefactor = boost::lexical_cast<double>( argv[i+1] );
if (arg == "--num-sources")
num_sources = boost::lexical_cast<size_t>( argv[i+1] );
if (arg == "--iterations")
iterations = boost::lexical_cast<size_t>( argv[i+1] );
if (arg == "--verify")
verify = true;
if (arg == "--stats")
stats = true;
if (arg == "--coalescing-size") {
coalescing_size = extract_params<size_t>( argv[i+1] );
}
if (arg == "--reduction-cache-size")
reduction_cache_size = extract_params<size_t>( argv[i+1] );
if (arg == "--distribution-coalescing-size")
distribution_coalescing_size = boost::lexical_cast<size_t>( argv[i+1] );
if (arg == "--distribution") {
if (strcmp(argv[i+1],"block") == 0)
distribution_type = block;
else if (strcmp(argv[i+1],"cyclic") == 0)
distribution_type = cyclic;
else {
std::cout << "Invalid distribution type. Available types are block and cyclic" << std::endl;
// abort = true;
}
}
if (arg == "--block-size") {
block_size = boost::lexical_cast<size_t>( argv[i+1] );
}
if (arg == "--id-distribution") {
if (strcmp(argv[i+1],"vertical") == 0)
id_distribution = vertical;
else if (strcmp(argv[i+1],"horizontal") == 0)
id_distribution = horizontal;
else {
std::cout << "Invalid id distribution type. Available types are vertical and horizontal"
<< std::endl;
// abort = true;
}
}
if (arg == "--max-weight")
C = boost::lexical_cast<weight_type>( argv[i+1] );
if(arg == "--poll-task"){
number_poll_task = extract_params<unsigned int>( argv[i+1] );
//std::cerr<<"poll task number:" <<number_poll_task<<"\n";
}
if (arg == "--flush") {
flushFreq = extract_params<unsigned int> ( argv[i+1] );
}
if (arg == "--eager-limit") {
eager_limit = extract_params<unsigned int> ( argv[i+1] );
}
if (arg == "--priority_coalescing_size") {
priority_coalescing_size_v = extract_params<unsigned int> ( argv[i+1] );
}
if(arg == "--ds"){
dc_data_structures = extract_params<std::string> ( argv[i+1] );
}
if (arg == "--rook")
routing.push_back(rt_rook);
if (arg == "--rt_none")
routing.push_back(rt_none);
if (arg == "--with-no-reductions")
no_reductions = true;
if (arg == "--without-no-reductions")
no_reductions = false;
if (arg == "--with-per-thread-reductions")
per_thread_reductions = true;
if (arg == "--without-per-thread-reductions")
per_thread_reductions = false;
if (arg == "--run_dc")
run_dc = true;
if (arg == "--run_chaotic")
run_chaotic = true;
// CC
if (arg == "--run_cc")
run_cc = true;
if (arg == "--cc_algorithms") {
cc_algorithms = extract_params<std::string> ( argv[i+1] );
}
if (arg == "--vertices-per-lock") {
if (!run_cc) {
std::cerr << "Vertices per lock is only allowed for Shiloach-Vishky connected components."
<< std::endl;
}
vertices_per_lock = boost::lexical_cast<size_t>( argv[i+1] );
}
if (arg == "--level-sync") {
if (!run_cc) {
std::cerr << "Level synch is only allowed for Shiloach-Vishky connected components."
<< std::endl;
return;
}
level_sync = true;
}
if (arg == "--buckets") {
nbuckets = extract_params<size_t> ( argv[i+1] );
}
if (arg == "--print_cc_stats")
print_cc_stats = true;
if (arg == "--allstats")
allstats = true;
if (arg == "--cutoff_degree") {
cutoff_degree = boost::lexical_cast<size_t>( argv[i+1] );
}
// MIS
if (arg == "--run_ss_mis")
run_ss_mis = true;
if (arg == "--run_bucket_mis")
run_bucket_mis = true;
if (arg == "--run_luby_mis") {
run_luby_mis = true;
}
if (arg == "--luby_algorithms") {
luby_algorithms = extract_params<std::string> ( argv[i+1] );
}
if (arg == "--run_ds")
run_ds = true;
if (arg == "--run_kla")
run_kla = true;
if (arg == "--klevel")
k_levels = extract_params<unsigned int> ( argv[i+1] );
if (arg == "--delta") {
delta = extract_params<unsigned int> ( argv[i+1] );
}
}
if (thread_num_vals.empty()) thread_num_vals.push_back(1);
if (routing.empty()) routing.push_back(rt_none);
// Check for necessary parameters
bool abort = false;
if (read_graph && gen_graph) {
std::cout << "Both generate graph and read graph from file options are specified. Aborting !"
<< std::endl;
abort = true;
}
if(coalescing_size.empty()) {
std::cerr << "Provide a list of coalescing sizes: --coalescing-size x,y,..." << std::endl;
abort = true;
}
if(recvDepth.empty()) {
std::cerr << "Provide a list of receive depths: --receive-depth x,y,..." << std::endl;
abort = true;
}
if(number_poll_task.empty()) {
std::cerr << "Provide a list of poll tasks: --poll-task x,y,..." << std::endl;
abort = true;
}
if(flushFreq.empty()) {
std::cerr << "Provide a list of flush frequencies: --flush x,y,..." << std::endl;
abort = true;
}
if(!(run_dc || run_ds || run_kla || run_cc || run_chaotic ||
run_ss_mis || run_luby_mis || run_bucket_mis)) {
std::cerr << "Select at least one algorithm (--run_dc or --run_ds or"
<< " --run_kla or --run_cc or --run_chaotic or"
<< " --run_ss_mis or --run_luby_mis or --run_bucket_mis)." << std::endl;
abort = true;
} else if (run_cc) {
if (cc_algorithms.empty()) {
std::cerr << "Must specify atleast one connected component algorithms to run. Options : "
<< "run_sv_cc, run_sv_ps_cc, run_sv_cc_level_sync, run_sv_ps_cc_level_sync, run_dd_cc, run_cc_chaotic, run_cc_ds, run_level_sync_cc"
<< ", run_sv_cc_opt, run_sv_cc_opt_level_sync"
<< std::endl;
abort = true;
}
}
if (run_luby_mis && luby_algorithms.empty()) {
std::cerr << "Select at least one Luby algorithm using --luby_algorithms. "
<< "Available algorithms are A, AV1,AV2, B"
<< std::endl;
abort = true;
}
if(abort) std::abort();
}
typedef unsigned long long block_node_t;
void test_main(int argc, char* argv[]) {
amplusplus::environment env = amplusplus::mpi_environment(argc, argv, true);
amplusplus::transport trans = env.create_transport();
amplusplus::transport barrier_trans = trans.clone();
_RANK = trans.rank(); // For performance counter output
if (_RANK == 0) {
#ifdef NEW_GRAPH500_SPEC
std::cout << "Synthetic graph generator used -- RMAT-2" << std::endl;
#else
std::cout << "Synthetic graph generator used -- RMAT-1" << std::endl;
#endif
}
typedef amplusplus::transport::rank_type rank_type;
typedef compressed_sparse_row_graph<directedS, no_property, WeightedEdge, no_property, distributedS<unsigned long long> > Digraph;
typedef graph_traits<Digraph>::vertex_descriptor Vertex;
typedef graph_traits<Digraph>::edges_size_type edges_size_type;
typedef graph_traits<Digraph>::vertices_size_type vertices_size_type;
typedef property_map<Digraph, vertex_index_t>::type VertexIndexMap;
typedef property_map<Digraph, vertex_owner_t>::const_type OwnerMap;
// Output of permutation
// edge is expressed as source_vertex, target_vertex
// But in the distribution we need source vertex as first element in the pair
// Therefore we are putting source vertex first and then another pair with target and weight
// So it will be pair<source, pair<target, weight> >.
typedef std::vector<std::pair<edges_size_type, std::pair<edges_size_type, weight_type> > > edge_with_weight_t;
edge_with_weight_t edges;
parallel::variant_distribution<vertices_size_type> distrib;
time_type gen_start;
// Seed general-purpose RNG
rand48 gen, synch_gen;
gen.seed(seed64);
synch_gen.seed(seed64);
typedef generator_iterator<uniform_int<weight_type>, rand48> weight_iterator_t;
weight_iterator_t gi
= make_generator_iterator(gen, uniform_int<weight_type>(1, C));
if (read_graph) {
gen_start = get_time();
std::cout << "Reading graph from file : " << graph_file << std::endl;
graph_reader<block_node_t> gr(graph_file.c_str());
gr.read_header();
n = gr.get_num_vertices();
edges_size_type m = gr.get_num_edges();
// reserve space for edges
std::cout << "Reserving space for edges : " << m << std::endl;
edges.reserve(m);
std::cout << "Reserved space for edges." << std::endl;
auto bdist = parallel::block<vertices_size_type>(trans, n);
// starting position for current rank
block_node_t start_index = bdist.start(trans.rank());
// locally stored ids in current rank
block_node_t local_count = bdist.block_size(n);
distrib = bdist;
if (with_weight) {
if (_RANK == 0)
std::cout << "Reading edges with weights ..." << std::endl;
if (!gr.read_edges_with_weight<edges_size_type, weight_type,
edge_with_weight_t>(start_index, local_count, edges))
return;
} else {
if (_RANK == 0)
std::cout << "Reading edges with generated weights ..." << std::endl;
if (!gr.read_edges_wo_weight<edges_size_type,edge_with_weight_t,
weight_iterator_t>(start_index,
local_count,
edges,
gi))
return;
}
std::cout << "Total number of edges read : " << edges.size()
<< std::endl;
} else {
assert(gen_graph);
edges_size_type m = static_cast<edges_size_type>(floor(n * edgefactor));
gen_start = get_time();
edges.reserve(static_cast<edges_size_type>(floor(edge_list_reserve_factor * 2 * m / trans.size())));
if (distribution_type == cyclic) {
distrib = parallel::oned_block_cyclic<vertices_size_type>(trans, block_size);
std::cout << "Distribution is cyclic. block size : " << block_size << std::endl;
} else //(distribution_type == block)
distrib = parallel::block<vertices_size_type>(trans, n);
{
boost::uniform_int<uint64_t> rand_64(0, std::numeric_limits<uint64_t>::max());
#ifdef CLONE
amplusplus::transport trans = trans.clone(); // Clone transport for distribution
#endif
edges_size_type e_start = trans.rank() * (m + trans.size() - 1) / trans.size();
edges_size_type e_count = (std::min)((m + trans.size() - 1) / trans.size(), m - e_start);
// Permute and redistribute copy constructs the input iterator
uint64_t a = rand_64(gen);
uint64_t b = rand_64(gen);
// Build a graph to test with
typedef graph500_iterator<Digraph, generator_iterator<uniform_int<weight_type>, rand48>, weight_type > Graph500Iter;
// Select the highest thread val
int num_threads = 1;
for(unsigned int thread_choice : thread_num_vals) {
if (num_threads < thread_choice)
num_threads = thread_choice;
}
// As for now, we assume that only the first routing from the list is used to generate the graph. It seems that it does not really matter which routing we use here since generation of the graph is not a part of the performance test.
if (routing[0] == rt_none) {
do_distribute<Graph500Iter, amplusplus::no_routing>(distrib, trans, e_start, e_count, a, b, edges, gi, num_threads);
} else if (routing[0] == rt_hypercube) {
do_distribute<Graph500Iter, amplusplus::hypercube_routing>(distrib, trans, e_start, e_count, a, b, edges, gi, num_threads);
} else if (routing[0] == rt_rook) {
do_distribute<Graph500Iter, amplusplus::rook_routing>(distrib, trans, e_start, e_count, a, b, edges, gi, num_threads);
}
}
}
typedef select_edge<edges_size_type, weight_type> EdgeSelectFunction;
typedef transform_iterator<EdgeSelectFunction, edge_with_weight_t::iterator> edge_only_iterator;
typedef select_edge_weight<edges_size_type, weight_type> WeightSelectFunction;
typedef transform_iterator<WeightSelectFunction, edge_with_weight_t::iterator> weight_only_iterator;
edge_only_iterator edge_begin(edges.begin(), EdgeSelectFunction()),
edge_end(edges.end(), EdgeSelectFunction());
weight_only_iterator weight_begin(edges.begin(), WeightSelectFunction());
std::cout << "rank -- " << trans.rank() << ", total edges received=" << edges.size() << std::endl;
time_type gt1 = get_time();
Digraph g(edges_are_unsorted_multi_pass, edge_begin, edge_end,
weight_begin, n, trans, distrib);
//Digraph g(edges_are_sorted, edge_begin, edge_end,
// weight_begin, n, trans, distrib);
time_type gt2 = get_time();
std::cout << "Local graph creation time : " << (gt2-gt1)
<< std::endl;
// Clear edge array above
edges.clear();
//============= run some stats ===================//
run_grah_stats(g);
//Generate sources
boost::uniform_int<uint64_t> rand_vertex(0, n-1);
{ amplusplus::scoped_epoch epoch(trans); }
time_type gen_end = get_time();
if (trans.rank() == 0) {
std::cout << "Graph generation took " << print_time(gen_end - gen_start) << "s\n";
#ifdef PRINT_DEBUG
// Printing graph edges and edge weights
// Property maps
typedef property_map<Digraph, weight_type WeightedEdge::*>::type WeightMap;
WeightMap weight = get(&WeightedEdge::weight, g);
typename graph_traits < Digraph >::edge_iterator ei, ei_end;
for (boost::tie(ei, ei_end) = boost::edges(g); ei != ei_end; ++ei) {
weight_type we = get(weight, *ei);
Vertex v = source(*ei, g);
std::cout << " Weight - " << we << " edge source : " << boost::source(*ei, g)
<< " edge target : " << boost::target(*ei, g) << std::endl;
}
#endif
}
// Max degree computation and printout
/*{
typedef typename graph_traits<Digraph>::degree_size_type Degree;
// Compute the maximum edge degree
Degree max_degree = 0;
BGL_FORALL_VERTICES_T(u, g, Digraph) {
max_degree = max BOOST_PREVENT_MACRO_SUBSTITUTION (max_degree, out_degree(u, g));
}
// max_degree = all_reduce(process_group(g), max_degree, maximum<Degree>());
all_reduce<Degree, maximum<Degree> > r(trans, maximum<Degree>());
max_degree = r(max_degree);
if(trans.rank() == 0)
std::cout << "Maximum Degree is " << max_degree << std::endl;
}*/
// Property maps
typedef property_map<Digraph, weight_type WeightedEdge::*>::type WeightMap;
WeightMap weight = get(&WeightedEdge::weight, g);
// Distance map
std::vector<weight_type> distanceS(num_vertices(g), std::numeric_limits<weight_type>::max());
typedef iterator_property_map<std::vector<weight_type>::iterator, VertexIndexMap> DistanceMap;
DistanceMap distance(distanceS.begin(), get(vertex_index, g));
std::string empty_ds = "";
for(unsigned int thread_choice : thread_num_vals) {
for(unsigned int coalescing_choice : coalescing_size) {
for(unsigned int depth_choice : recvDepth) {
for(unsigned int poll_choice : number_poll_task) {
for(routing_type routing_choice : routing) {
// First print the configuration
if(run_dc) {
for(unsigned int flush_choice : flushFreq) {
for(unsigned int eager_choice : eager_limit) {
for(unsigned int priority_coalescing_size : priority_coalescing_size_v) {
for (std::string dc_ds : dc_data_structures) {
if (trans.rank() == 0) std::cout << "[DC]"
<< " Data Structure :" << dc_ds
<< " Threads: " << thread_choice
<< " Coalescing: " << coalescing_choice
<< " Poll: " << poll_choice
<< " Routing: " << routing_choice
<< " Depth: " << depth_choice;
select_alg(env,
thread_choice,
coalescing_choice,
priority_coalescing_size,
depth_choice,
poll_choice,
routing_choice,
g,
distance,
weight,
thread_choice,
flush_choice,
eager_choice,
0,
dc_ds,
synch_gen,
rand_vertex,
false, //kla
true, //dc
false, //ds
false, //cc
false, //chaotic
false, //ss-mis
false, // bucket mis
false, //luby-mis
(size_t)1);
}
}
}
}
}
if (run_ss_mis || run_luby_mis || run_bucket_mis) {
for(unsigned int flush_choice : flushFreq) {
for (std::string dc_ds : dc_data_structures) {
if (run_ss_mis) {
if (trans.rank() == 0) std::cout << "[MIS-SS]"
<< " Data Structure :" << dc_ds
<< " Threads: " << thread_choice
<< " Coalescing: " << coalescing_choice
<< " Poll: " << poll_choice
<< " Routing: " << routing_choice
<< " Depth: " << depth_choice
<< " Flush: " << flush_choice;
select_alg(env,
thread_choice,
coalescing_choice,
10000,
depth_choice,
poll_choice,
routing_choice,
g,
distance,
weight,
thread_choice,
flush_choice,
0,
0,
dc_ds,
synch_gen,
rand_vertex,
false, //kla
false, // dc
false, // ds
false, // cc
false, // chaotic
true, // ss-mis
false, // bucket-mis
false, // luby-mis
1);
}
if (run_bucket_mis) {
if (trans.rank() == 0) std::cout << "[MIS-BUCKET]"
<< " Data Structure :" << dc_ds
<< " Threads: " << thread_choice
<< " Coalescing: " << coalescing_choice
<< " Poll: " << poll_choice
<< " Routing: " << routing_choice
<< " Depth: " << depth_choice
<< " Flush: " << flush_choice;
select_alg(env,
thread_choice,
coalescing_choice,
10000,
depth_choice,
poll_choice,
routing_choice,
g,
distance,
weight,
thread_choice,
flush_choice,
0,
0,
dc_ds,
synch_gen,
rand_vertex,
false, //kla
false, // dc
false, // ds
false, // cc
false, // chaotic
false, // ss-mis
true, //bucket-mis
false, // luby-mis
1);
}
if (run_luby_mis) {
for (std::string luby_algo : luby_algorithms) {
if (trans.rank() == 0) std::cout << "[MIS-LUBY]"
<< " Luby Algorithm :" << luby_algo
<< " Data Structure :" << dc_ds
<< " Threads: " << thread_choice
<< " Coalescing: " << coalescing_choice
<< " Poll: " << poll_choice
<< " Routing: " << routing_choice
<< " Depth: " << depth_choice
<< " Flush: " << flush_choice;
select_alg(env,
thread_choice,
coalescing_choice,
10000,
depth_choice,
poll_choice,
routing_choice,
g,
distance,
weight,
thread_choice,
flush_choice,
0,
0,
dc_ds,
synch_gen,
rand_vertex,
false, //kla
false, // dc
false, // ds
false, // cc
false, // chaotic
false, // ss-mis
false, //bucket mis
true, // luby-mis
1,
luby_algo);
}
}
}
}
}
if(run_chaotic) {
for(unsigned int flush_choice : flushFreq) {
for(unsigned int eager_choice : eager_limit) {
if (trans.rank() == 0) std::cout << "[Chaotic]"
<< " Threads: " << thread_choice
<< " Coalescing: " << coalescing_choice
<< " Poll: " << poll_choice
<< " Routing: " << routing_choice
<< " Depth: " << depth_choice;
select_alg(env,
thread_choice,
coalescing_choice,
coalescing_choice,
depth_choice,
poll_choice,
routing_choice,
g,
distance,
weight,
thread_choice,
flush_choice,
eager_choice,
0,
empty_ds,
synch_gen,
rand_vertex,
false, //kla
false, // dc
false, // ds
false, // cc
true, // chaotic
false, //ss-mis
false, // bucket mis
false, //luby-mis
1);
}
}
}
if(run_ds) { // run_ds
for(unsigned int delta_choice : delta) {
for (std::string dc_ds : dc_data_structures) {
for(unsigned int flush_choice : flushFreq) {
if (trans.rank() == 0) std::cout << "[Delta]"
<< " Data Structure :" << dc_ds
<< " Threads: " << thread_choice
<< " Flush : " << flush_choice
<< " Coalescing: " << coalescing_choice
<< " Poll: " << poll_choice
<< " Routing: " << routing_choice
<< " Depth: " << depth_choice;
select_alg(env,
thread_choice,
coalescing_choice,
0,
depth_choice,
poll_choice,
routing_choice,
g,
distance,
weight,
thread_choice,
flush_choice,
0,
delta_choice,
dc_ds,
synch_gen,
rand_vertex,
false, //kla
false, //dc
true, // ds
false, // cc
false, // chaotic
false, //ss-mis
false, // bucket mis
false, //ss-luby
1);
}
}
}
}
if(run_kla) {
unsigned int delta_choice = 1;
for(unsigned int k_level : k_levels) {
for (std::string dc_ds : dc_data_structures) {
for(unsigned int flush_choice : flushFreq) {
if (trans.rank() == 0) std::cout << "[KLA]"
<< " Data Structure :" << dc_ds
<< " Threads: " << thread_choice
<< " Flush : " << flush_choice
<< " Coalescing: " << coalescing_choice
<< " Poll: " << poll_choice
<< " Routing: " << routing_choice
<< " Depth: " << depth_choice
<< "k_level: " << k_level;
select_alg(env,
thread_choice,
coalescing_choice,
0,
depth_choice,
poll_choice,
routing_choice,
g,
distance,
weight,
thread_choice,
flush_choice,
0,
delta_choice,
dc_ds,
synch_gen,
rand_vertex,
true, //kla
false, //dc
false, //ds
false, //cc
false, //chaotic
false, //ss-mis
false, // bucket mis
false, //luby
k_level);
}
}
}
}
if (run_cc) {
for (std::string algorithm : cc_algorithms) {
if (algorithm == "run_dd_cc") {
for(unsigned int flush_choice : flushFreq) {
if (trans.rank() == 0) std::cout << "[CC]"
<< " Algorithm : " << algorithm
<< " Threads: " << thread_choice
<< " Coalescing: " << coalescing_choice
<< " Poll: " << poll_choice
<< " Routing: " << routing_choice
<< " Depth: " << depth_choice
<< " Flush: " << flush_choice;
unsigned int delta_choice = 1;
select_alg(env,
thread_choice,
coalescing_choice,
1,
depth_choice,
poll_choice,
routing_choice,
g,
distance,
weight,
thread_choice,
0,
0,
delta_choice,
empty_ds,
synch_gen,
rand_vertex,
false, //kla
false, //dc
false, //ds
true, //cc
false, //chaotic
false, //ss-mis
false, //bucket mis
false, //luby
0, // k-level
"", // luby algo
algorithm);
}
} else {
if (trans.rank() == 0) std::cout << "[CC]"
<< " Algorithm : " << algorithm
<< " Threads: " << thread_choice
<< " Coalescing: " << coalescing_choice
<< " Poll: " << poll_choice
<< " Routing: " << routing_choice
<< " Depth: " << depth_choice;
if ("run_cc_ds" == algorithm) {
unsigned int delta_choice = 1; // ignore
for(size_t bucketsz : nbuckets) {
select_alg(env,
thread_choice,
coalescing_choice,
1,
depth_choice,
poll_choice,
routing_choice,
g,
distance,
weight,
thread_choice,
0,
0,
delta_choice,
empty_ds,
synch_gen,
rand_vertex,
false, //kla
false, //dc
false, //ds
true, //cc
false, //chaotic
false, //ss-mis
false, // bucket mis
false, //luby
0, // k-level
"", // luby algo
algorithm,
bucketsz);
}
} else {
// delta is ignored
unsigned int delta_choice = 1;
select_alg(env,
thread_choice,
coalescing_choice,
1,
depth_choice,
poll_choice,
routing_choice,
g,
distance,
weight,
thread_choice,
0,
0,
delta_choice,
empty_ds,
synch_gen,
rand_vertex,
false, //kla
false, //dc
false, //ds
true, //cc
false, //chaotic
false, //ss-mis
false, // bucket mis
false, //luby
0, // k-level
"", // luby algo
algorithm);
}
}
}
}
}
}
}
}
}
}
private:
template<typename Result>
std::vector<Result> extract_params(const std::string args) {
size_t d = 0, d2;
std::vector<Result> r;
while ((d2 = args.find(',', d)) != std::string::npos) {
r.push_back(boost::lexical_cast<Result>(args.substr(d, d2 - d)));
d = d2 + 1;
}
r.push_back(boost::lexical_cast<Result>(args.substr(d, args.length())));
return r;
}
template<typename Digraph, typename DistanceMap, typename WeightMap, typename RNG, typename RandVertex>
void select_alg(amplusplus::environment& env,
unsigned int thread_choice,
unsigned int coalescing_choice,
unsigned int priority_coalescing_size,
unsigned int depth_choice,
unsigned int poll_choice,
routing_type routing_choice,
Digraph &g,
DistanceMap &distance,
WeightMap &weight,
unsigned int num_threads,
unsigned int flush_choice,
unsigned int eager_choice,
unsigned int delta_choice,
std::string& dc_ds_choice,
RNG synch_gen,
RandVertex rand_vertex,
bool run_kla,
bool run_dc,
bool run_ds,
bool run_cc,
bool run_chaotic,
bool run_ss_mis,
bool run_bucket_mis,
bool run_luby_mis,
size_t k_level,
std::string luby_algo="",
std::string cc_algo="",
size_t bucket_choice=0) {
//run_ds = !run_dc;
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
flushes.reset(new atomic_flush_type[coalescing_choice]);
flushes_size = coalescing_choice;
all_flushes.resize(coalescing_choice);
cumulative_flushes.resize(coalescing_choice);
#endif
// We will not run two algorithms at once since they have disjoint sets of parameters
if(run_dc && run_ds && run_kla) abort();
amplusplus::transport trans = env.create_transport();
amplusplus::transport barrier_trans = trans.clone();
if(run_dc && trans.rank() == 0) {
std::cout << " Priority: " << priority_coalescing_size << " Flush: " << flush_choice << " Eager: " << eager_choice;
}
if(run_ds && trans.rank() == 0) {
std::cout << " Delta: " << delta_choice;
}
if(run_kla && trans.rank() == 0) {
std::cout << " k_level: " << k_level<<std::endl;
}
// Create transport for the algorithm
env.template downcast_to_impl<amplusplus::detail::mpi_environment_obj>()->set_poll_tasks(poll_choice);
env.template downcast_to_impl<amplusplus::detail::mpi_environment_obj>()->set_recv_depth(depth_choice);
if (trans.rank() == 0)
std::cout << "per_thread_reductions - " << per_thread_reductions << " no_reductions : " << no_reductions << std::endl;
if(per_thread_reductions) {
for(unsigned int reduction_choice : reduction_cache_size) {
if (trans.rank() == 0) std::cout << " Reduction: " << reduction_choice << std::endl;
if (routing_choice == rt_none) {
typedef amplusplus::per_thread_cache_generator<amplusplus::counter_coalesced_message_type_gen, amplusplus::no_routing> MessageGenerator;
MessageGenerator msg_gen(amplusplus::counter_coalesced_message_type_gen(coalescing_choice), reduction_choice, amplusplus::no_routing(trans.rank(), trans.size()));
MessageGenerator priority_msg_gen(amplusplus::counter_coalesced_message_type_gen(priority_coalescing_size, 1), reduction_choice, amplusplus::no_routing(trans.rank(), trans.size()));
select_msg_gen(msg_gen, priority_msg_gen, trans, barrier_trans, g, distance, weight, thread_choice, flush_choice, eager_choice, delta_choice, dc_ds_choice, synch_gen,
rand_vertex,
run_kla,
run_dc,
run_ds,
run_cc,
run_chaotic,
run_ss_mis,
run_bucket_mis,
run_luby_mis,
k_level,
luby_algo,
cc_algo,
bucket_choice);
}
if(routing_choice == rt_hypercube) {
typedef amplusplus::per_thread_cache_generator<amplusplus::counter_coalesced_message_type_gen, amplusplus::hypercube_routing> MessageGenerator;
MessageGenerator msg_gen(amplusplus::counter_coalesced_message_type_gen(coalescing_choice), reduction_choice, amplusplus::hypercube_routing(trans.rank(), trans.size()));
MessageGenerator priority_msg_gen(amplusplus::counter_coalesced_message_type_gen(priority_coalescing_size, 1), reduction_choice, amplusplus::hypercube_routing(trans.rank(), trans.size()));
select_msg_gen(msg_gen, priority_msg_gen, trans, barrier_trans, g, distance, weight, thread_choice, flush_choice, eager_choice, delta_choice, dc_ds_choice, synch_gen,
rand_vertex,
run_kla,
run_dc,
run_ds,
run_cc,
run_chaotic,
run_ss_mis,
run_bucket_mis,
run_luby_mis,
k_level,
luby_algo,
cc_algo,
bucket_choice);
}
if(routing_choice == rt_rook) {
typedef amplusplus::per_thread_cache_generator<amplusplus::counter_coalesced_message_type_gen, amplusplus::rook_routing> MessageGenerator;
MessageGenerator msg_gen(amplusplus::counter_coalesced_message_type_gen(coalescing_choice), reduction_choice, amplusplus::rook_routing(trans.rank(), trans.size()));
MessageGenerator priority_msg_gen(amplusplus::counter_coalesced_message_type_gen(priority_coalescing_size, 1), reduction_choice, amplusplus::rook_routing(trans.rank(), trans.size()));
select_msg_gen(msg_gen, priority_msg_gen, trans, barrier_trans, g, distance, weight, thread_choice, flush_choice, eager_choice, delta_choice, dc_ds_choice, synch_gen,
rand_vertex,
run_kla,
run_dc,
run_ds,
run_cc,
run_chaotic,
run_ss_mis,
run_bucket_mis,
run_luby_mis,
k_level,
luby_algo,
cc_algo,
bucket_choice);
}
}
}
if(no_reductions) {
if (trans.rank() == 0) std::cout << " Reduction: 0 " << "coalescing " << coalescing_choice << " pri coalescing "
<< priority_coalescing_size
<< " routing " << routing_choice
<< " run_cc " << run_cc
<< std::endl;
if(routing_choice == rt_none) {
typedef amplusplus::simple_generator<amplusplus::counter_coalesced_message_type_gen> MessageGenerator;
MessageGenerator msg_gen((amplusplus::counter_coalesced_message_type_gen(coalescing_choice)));
MessageGenerator priority_msg_gen((amplusplus::counter_coalesced_message_type_gen(priority_coalescing_size, 1)));
select_msg_gen(msg_gen, priority_msg_gen, trans, barrier_trans, g, distance, weight, thread_choice, flush_choice, eager_choice, delta_choice, dc_ds_choice, synch_gen,
rand_vertex,
run_kla,
run_dc,
run_ds,
run_cc,
run_chaotic,
run_ss_mis,
run_bucket_mis,
run_luby_mis,
k_level,
luby_algo,
cc_algo,
bucket_choice);
}
if(routing_choice == rt_hypercube) {
typedef amplusplus::routing_generator<amplusplus::counter_coalesced_message_type_gen, amplusplus::hypercube_routing> MessageGenerator;
MessageGenerator msg_gen(amplusplus::counter_coalesced_message_type_gen(coalescing_choice), amplusplus::hypercube_routing(trans.rank(), trans.size()));
MessageGenerator priority_msg_gen(amplusplus::counter_coalesced_message_type_gen(priority_coalescing_size, 1), amplusplus::hypercube_routing(trans.rank(), trans.size()));
select_msg_gen(msg_gen, priority_msg_gen, trans, barrier_trans, g, distance, weight, thread_choice, flush_choice, eager_choice, delta_choice, dc_ds_choice, synch_gen,
rand_vertex,
run_kla,
run_dc,
run_ds,
run_cc,
run_chaotic,
run_ss_mis,
run_bucket_mis,
run_luby_mis,
k_level,
luby_algo,
cc_algo,
bucket_choice);
}
if(routing_choice == rt_rook) {
typedef amplusplus::routing_generator<amplusplus::counter_coalesced_message_type_gen, amplusplus::rook_routing> MessageGenerator;
MessageGenerator msg_gen(amplusplus::counter_coalesced_message_type_gen(coalescing_choice), amplusplus::rook_routing(trans.rank(), trans.size()));
MessageGenerator priority_msg_gen(amplusplus::counter_coalesced_message_type_gen(priority_coalescing_size, 1), amplusplus::rook_routing(trans.rank(), trans.size()));
select_msg_gen(msg_gen, priority_msg_gen, trans, barrier_trans, g, distance, weight, thread_choice, flush_choice, eager_choice, delta_choice, dc_ds_choice, synch_gen,
rand_vertex,
run_kla,
run_dc,
run_ds,
run_cc,
run_chaotic,
run_ss_mis,
run_bucket_mis,
run_luby_mis,
k_level,
luby_algo,
cc_algo,
bucket_choice);
}
}
}
template<typename MessageGenerator, typename Digraph, typename DistanceMap, typename WeightMap, typename RNG, typename RandVertex>
void select_msg_gen(MessageGenerator &msg_gen,
MessageGenerator &priority_msg_gen,
amplusplus::transport &trans,
amplusplus::transport &barrier_trans,
Digraph &g,
DistanceMap &distance,
WeightMap &weight,
unsigned int num_threads,
unsigned int flushFreq,
unsigned int eager_limit,
unsigned int delta,
std::string& dc_ds,
RNG synch_gen,
RandVertex rand_vertex,
bool run_kla,
bool run_dc,
bool run_ds,
bool run_cc,
bool run_chaotic,
bool run_ss_mis,
bool run_bucket_mis,
bool run_luby_mis,
size_t k_level,
std::string luby_algo,
std::string cc_algo,
size_t bucket_choice) {
//run_ds = !run_dc;
typedef typename graph_traits<Digraph>::vertex_descriptor Vertex;
time_type total_time = 0;
std::vector<time_type> all_times(num_sources);
std::vector<state_t> misvec(num_vertices(g), MIS_UNFIX);
typedef typename property_map<Digraph, vertex_index_t>::type VertexIndexMap;
typedef iterator_property_map<typename std::vector<state_t>::iterator, VertexIndexMap> MISMap;
MISMap mis(misvec.begin(), get(vertex_index, g));
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
clear_cumulative_buffer_stats();
#endif
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
cumulative_hits = 0; cumulative_tests = 0;
#endif
#ifdef PBGL2_PRINT_WORK_STATS
clear_cumulative_work_stats();
#endif
// For GTEPS
double total_elapsed_time = 0.0;
size_t *edge_traversed =(size_t *) calloc(num_sources, sizeof(size_t));
double *elapsed_time = (double *) calloc(num_sources, sizeof(double));
for (unsigned int source_i = 0; source_i < num_sources; ++source_i) {
#ifdef PRINT_ET
if (trans.rank() == 0)
std::cout << print_time(get_time() - job_start) << "s elapsed since job start\n";
#endif
Vertex current_source = vertex(rand_vertex(synch_gen), g);
time_type time;
if(run_dc) {
if(dc_ds == "vector") {
// Note : We need to modify vector data srtucture to accomadate new interface
std::cout << " This (vector data structure) option is not supported."
<< " We need to change vector implementation to satisfy new interface"
<< std::endl;
exit(1);
/*
time = run_distributed_control<boost::graph::distributed::vector_of_vector_gen>
(trans, barrier_trans, g, weight, distance, current_source, num_threads, n, verify, msg_gen, priority_msg_gen, flushFreq, eager_limit);
*/
} else if (dc_ds == "nodeq") { // priority queue per node
time = run_distributed_control_node<boost::graph::distributed::node_priority_queue_gen>
(trans, barrier_trans, g, weight, distance, current_source, num_threads, n, verify, msg_gen, priority_msg_gen, flushFreq, eager_limit);
} else if (dc_ds == "ms_nodeq"){ // priority queue per node
time = run_distributed_control_node<boost::graph::distributed::ms_node_priority_queue_gen>
(trans, barrier_trans, g, weight, distance, current_source, num_threads, n, verify, msg_gen, priority_msg_gen, flushFreq, eager_limit);
} else if (dc_ds == "numaq") { // priority queue per numa node
time = run_distributed_control_node<boost::graph::distributed::numa_priority_queue_gen>
(trans, barrier_trans, g, weight, distance,
current_source, num_threads, n,
verify, msg_gen, priority_msg_gen,
flushFreq, eager_limit,
true); // numa true
} else if (dc_ds == "ms_numaq") { // priority queue per numa node
time = run_distributed_control_node<boost::graph::distributed::ms_numa_priority_queue_gen>
(trans, barrier_trans, g, weight, distance,
current_source, num_threads, n,
verify, msg_gen, priority_msg_gen,
flushFreq, eager_limit,
true); // numa true
} else if (dc_ds == "pheet64q"){
time = run_distributed_control_pheet<boost::graph::distributed::pheet_priority_queue_gen_64>
(trans, barrier_trans, g, weight, distance,
current_source, num_threads, n,
verify, msg_gen, priority_msg_gen,
flushFreq, eager_limit);
} else if (dc_ds == "pheet128q"){
time = run_distributed_control_pheet<boost::graph::distributed::pheet_priority_queue_gen_128>
(trans, barrier_trans, g, weight, distance,
current_source, num_threads, n,
verify, msg_gen, priority_msg_gen,
flushFreq, eager_limit);
} else if (dc_ds == "pheet256q"){
time = run_distributed_control_pheet<boost::graph::distributed::pheet_priority_queue_gen_256>
(trans, barrier_trans, g, weight, distance,
current_source, num_threads, n,
verify, msg_gen, priority_msg_gen,
flushFreq, eager_limit);
} else if (dc_ds == "pheet512q"){
time = run_distributed_control_pheet<boost::graph::distributed::pheet_priority_queue_gen_512>
(trans, barrier_trans, g, weight, distance,
current_source, num_threads, n,
verify, msg_gen, priority_msg_gen,
flushFreq, eager_limit);
} else if (dc_ds == "pheet1024q"){
time = run_distributed_control_pheet<boost::graph::distributed::pheet_priority_queue_gen_1024>
(trans, barrier_trans, g, weight, distance,
current_source, num_threads, n,
verify, msg_gen, priority_msg_gen,
flushFreq, eager_limit);
} else if (dc_ds == "threadq"){
time = run_distributed_control(trans, barrier_trans, g, weight, distance, current_source, num_threads, n, verify, msg_gen, priority_msg_gen, flushFreq, eager_limit);
} else if (dc_ds == "buffer") {
std::cout << "Ignoring buffer data structure for Distirbuted Cotrol ..." << std::endl;
} else {
std::cout << "Data structure not specified ! " << std::endl;
assert(false);
}
} else if (run_cc) {
if (cc_algo == "run_dd_cc") {
time = run_data_driven_cc(trans,
barrier_trans,
g,
num_threads, n,
verify,
print_cc_stats,
allstats,
msg_gen,
priority_msg_gen, flushFreq, eager_limit);
{ amplusplus::scoped_epoch epoch(barrier_trans); }
}
if (cc_algo == "run_sv_cc") {
time = run_sv_c_c(trans,
g,
num_threads,
verify,
false, // level_sync
msg_gen,
vertices_per_lock);
{ amplusplus::scoped_epoch epoch(barrier_trans); }
}
if (cc_algo == "run_sv_cc_level_sync") {
time = run_sv_c_c(trans,
g,
num_threads,
verify,
true, // level_sync
msg_gen,
vertices_per_lock);
{ amplusplus::scoped_epoch epoch(barrier_trans); }
}
if (cc_algo == "run_sv_cc_opt") {
time = run_sv_cc_optimized(trans,
g,
num_threads,
verify,
false, // level_sync
msg_gen,
vertices_per_lock);
{ amplusplus::scoped_epoch epoch(barrier_trans); }
}
if (cc_algo == "run_sv_cc_opt_level_sync") {
time = run_sv_cc_optimized(trans,
g,
num_threads,
verify,
true, // level_sync
msg_gen,
vertices_per_lock);
{ amplusplus::scoped_epoch epoch(barrier_trans); }
}
if (cc_algo == "run_sv_ps_cc") {
time = run_ps_sv_cc(trans,
g,
num_threads,
verify,
false, // level_sync
msg_gen,
vertices_per_lock);
{ amplusplus::scoped_epoch epoch(barrier_trans); }
}
if (cc_algo == "run_sv_ps_cc_level_sync") {
time = run_ps_sv_cc(trans,
g,
num_threads,
verify,
true, // level_sync
msg_gen,
vertices_per_lock);
{ amplusplus::scoped_epoch epoch(barrier_trans); }
}
if (cc_algo == "run_cc_chaotic") {
time = run_chaotic_cc(trans,
barrier_trans,
g,
num_threads,
n,
verify,
print_cc_stats,
allstats,
msg_gen);
{ amplusplus::scoped_epoch epoch(barrier_trans); }
}
if (cc_algo == "run_cc_ds") {
if (id_distribution == vertical)
time = run_delta_cc(trans,
barrier_trans,
g,
num_threads,
n,
bucket_choice,
block_id_distribution<Digraph>(g, n),
verify,
print_cc_stats,
allstats,
msg_gen);
else
time = run_delta_cc(trans,
barrier_trans,
g,
num_threads,
n,
bucket_choice,
row_id_distribution<Digraph>(g, trans.size()),
verify,
print_cc_stats,
allstats,
msg_gen);
{ amplusplus::scoped_epoch epoch(barrier_trans); }
}
if (cc_algo == "run_level_sync_cc") {
time = run_level_sync_cc(trans,
barrier_trans,
g,
num_threads,
n,
verify,
print_cc_stats,
allstats,
msg_gen);
{ amplusplus::scoped_epoch epoch(barrier_trans); }
}
} else if(run_ds) { // run_ds
// For now we don't have the parameter for level_sync. It can be added later on.
if (dc_ds == "buffer") {
time = run_delta_stepping(trans,
barrier_trans,
g,
weight,
distance,
current_source,
delta,
num_threads, n, verify, false, msg_gen);
} else if (dc_ds == "nodeq") {
time = run_delta_stepping_node<boost::graph::distributed::node_priority_queue_gen>(trans,
barrier_trans, g,
weight, distance,
current_source, delta,
num_threads, n, verify, false, msg_gen,
flushFreq);
} else if (dc_ds == "ms_nodeq") {
time = run_delta_stepping_node<boost::graph::distributed::ms_node_priority_queue_gen>(trans,
barrier_trans, g,
weight, distance,
current_source, delta,
num_threads, n, verify, false, msg_gen,
flushFreq);
} else if (dc_ds == "threadq") {
time = run_delta_stepping_thread<boost::graph::distributed::thread_priority_queue_gen>(trans,
barrier_trans, g,
weight, distance,
current_source, delta,
num_threads, n, verify, false, msg_gen,
flushFreq);
} else if (dc_ds == "mtthreadq") {
time = run_delta_stepping_thread<boost::graph::distributed::multi_priority_queue_gen>(trans,
barrier_trans, g,
weight, distance,
current_source, delta,
num_threads, n, verify, false, msg_gen,
flushFreq);
} else if (dc_ds == "numaq") {
time = run_delta_stepping_numa<boost::graph::distributed::numa_priority_queue_gen>(trans,
barrier_trans, g,
weight, distance,
current_source, delta,
num_threads, n, verify, false, msg_gen,
flushFreq);
} else if (dc_ds == "ms_numaq") {
time = run_delta_stepping_numa<boost::graph::distributed::ms_numa_priority_queue_gen>(trans,
barrier_trans, g,
weight, distance,
current_source, delta,
num_threads, n, verify, false, msg_gen,
flushFreq);
} else {
std::cout << "Data structure not specified ! " << std::endl;
assert(false);
}
} else if(run_chaotic) {
// chaotic SSSP
time = run_distributed_control_chaotic(trans, barrier_trans, g, weight, distance, current_source, num_threads, n, verify, msg_gen, flushFreq, eager_limit);
} else if(run_kla) {
if (dc_ds == "buffer") {
time = run_kla_sssp(trans, barrier_trans,
g, weight, distance,
current_source,
num_threads, n, verify,
false, msg_gen, k_level);
} else if (dc_ds == "numaq") {
time = run_kla_sssp_numa<boost::graph::distributed::numa_priority_queue_gen>(trans,
barrier_trans,
g, weight, distance,
current_source,
num_threads, n, verify,
false, msg_gen, k_level, flushFreq);
} else if (dc_ds == "ms_numaq") {
time = run_kla_sssp_numa<boost::graph::distributed::ms_numa_priority_queue_gen>(trans,
barrier_trans,
g, weight, distance,
current_source,
num_threads, n, verify,
false, msg_gen, k_level,
flushFreq);
} else if (dc_ds == "nodeq") {
time = run_kla_sssp_node<boost::graph::distributed::node_priority_queue_gen>(trans,
barrier_trans,
g, weight, distance,
current_source,
num_threads, n, verify,
false, msg_gen, k_level, flushFreq);
} else if (dc_ds == "ms_nodeq") {
time = run_kla_sssp_node<boost::graph::distributed::ms_node_priority_queue_gen>(trans,
barrier_trans,
g, weight, distance,
current_source,
num_threads, n, verify,
false, msg_gen, k_level, flushFreq);
} else if (dc_ds == "threadq"){
time = run_kla_sssp_thread<boost::graph::distributed::thread_priority_queue_gen>(trans,
barrier_trans,
g, weight, distance,
current_source,
num_threads, n, verify,
false, msg_gen, k_level,
flushFreq);
} else {
assert(false);
}
} else if(run_ss_mis) {
time = run_fix_mis<boost::graph::distributed::thread_priority_queue_gen>(trans,
barrier_trans,
g,
mis,
num_threads,
n,
verify,
msg_gen,
flushFreq);
} else if(run_bucket_mis) {
time = run_fix_mis_bucket(trans,
barrier_trans,
g,
mis,
num_threads,
n,
verify,
msg_gen,
flushFreq);
} else if(run_luby_mis) {
if (luby_algo == "A") {
time = run_luby_maximal_is<boost::graph::distributed::select_a_functor_gen>(trans,
barrier_trans,
g,
mis,
num_threads,
n,
verify,
msg_gen,
flushFreq);
} else if (luby_algo == "AV1") {
time = run_luby_maximal_is<boost::graph::distributed::select_a_vertex_functor_gen>(trans,
barrier_trans,
g,
mis,
num_threads,
n,
verify,
msg_gen,
flushFreq);
} else if (luby_algo == "AV2"){
time = run_luby_maximal_is<boost::graph::distributed::select_a_v2_functor_gen>(trans,
barrier_trans,
g,
mis,
num_threads,
n,
verify,
msg_gen,
flushFreq);
} else if (luby_algo == "B") {
time = run_luby_maximal_is<boost::graph::distributed::select_b_functor_gen>(trans,
barrier_trans,
g,
mis,
num_threads,
n,
verify,
msg_gen,
flushFreq);
} else {
std::cerr << "Invalid algorithm type for Luby MIS."
<< " Available algorithms are A, AV1, AV2 and B"
<< std::endl;
assert(false);
}
} else {
assert(false);
}
#ifdef CALCULATE_GTEPS
if (!run_cc) {
elapsed_time[source_i] = time;
edge_traversed[source_i] = get_gteps(trans, g, distance, weight);
}
#endif
if (time == -1.) { // Not enough vertices visited
--source_i; continue;
}
total_time += time;
all_times[source_i] = time;
}
if (trans.rank() == 0) {
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
unsigned long long buffers{}, messages{};
for(unsigned int i = 0; i < cumulative_flushes.size(); ++i) {
buffers += cumulative_flushes[i];
messages += cumulative_flushes[i] * i;
}
float msg_per_buf = -1;
if (buffers != 0) {
msg_per_buf = messages/buffers;
}
#endif
if(run_dc) {
std::cout << "Total Distributed Control (DC)-(" << dc_ds
<< ") time for " << num_sources << " sources = "
<< print_time(total_time) << " ("
<< print_time(total_time / num_sources) << " per source), "
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
<< "messages = " << cumulative_messages << " (" << (cumulative_messages / num_sources) << " per source), "
<< " full buffers = " << cumulative_full << " (" << (cumulative_full / num_sources) << " per source)"
<< " partial flushes = " << buffers << " (" << (buffers / num_sources) << " per source) with "
<< msg_per_buf << " messages per buffer on average (-1 means buffer size is 0)."
#endif
#ifdef AMPLUSPLUS_PRINT_HIT_RATES
<< "\nTests = " << (cumulative_tests / num_sources) << " (per source), hits = " << (cumulative_hits / num_sources)
<< " (per source), hit rate = " << (double(cumulative_hits) / double(cumulative_tests) * 100.) << "%"
#endif
#ifdef PBGL2_PRINT_WORK_STATS
PBGL2_DC_PRINT // The print macro for work stats
#endif
<< std::endl;
} else if(run_chaotic) {
std::cout << "Total Chaotic SSSP "
<< "time for " << num_sources << " sources = "
<< print_time(total_time) << " ("
<< print_time(total_time / num_sources) << " per source), "
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
<< "messages = " << cumulative_messages << " (" << (cumulative_messages / num_sources) << " per source), "
<< " full buffers = " << cumulative_full << " (" << (cumulative_full / num_sources) << " per source)"
<< " partial flushes = " << buffers << " (" << (buffers / num_sources) << " per source) with "
<< msg_per_buf << " messages per buffer on average (-1 means buffer size is 0)."
#endif
#ifdef AMPLUSPLUS_PRINT_HIT_RATES
<< "\nTests = " << (cumulative_tests / num_sources) << " (per source), hits = " << (cumulative_hits / num_sources)
<< " (per source), hit rate = " << (double(cumulative_hits) / double(cumulative_tests) * 100.) << "%"
#endif
#ifdef PBGL2_PRINT_WORK_STATS
PBGL2_DC_PRINT // The print macro for work stats
#endif
<< std::endl;
} else if(run_ds) { // run_ds
std::cout << "Total Delta-Stepping (DS-" << dc_ds
<< ") time for " << num_sources << " sources = "
<< print_time(total_time) << " ("
<< print_time(total_time / num_sources) << " per source), delta = " << delta
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
<< ", messages = " << cumulative_messages << " (" << (cumulative_messages / num_sources) << " per source), "
<< " full buffers = " << cumulative_full << " (" << (cumulative_full / num_sources) << " per source)"
<< " partial flushes = " << buffers << " (" << (buffers / num_sources) << " per source) with "
<< msg_per_buf << " messages per buffer on average (-1 means buffer size is 0)."
#endif
#ifdef AMPLUSPLUS_PRINT_HIT_RATES
<< "\nTests = " << (cumulative_tests / num_sources) << " (per source), hits = " << (cumulative_hits / num_sources)
<< " (per source), hit rate = " << (double(cumulative_hits) / double(cumulative_tests) * 100.) << "%"
#endif
#ifdef PBGL2_PRINT_WORK_STATS
PBGL2_DS_PRINT // The print macro for work stats
#endif
<< std::endl;
} /*else if (run_cc) { // run connected components
#ifdef CC_ALGORITHMS
std::cout << "Total data driven cc time for " << num_sources << " sources = "
<< print_time(total_cc_dd_time) << " ("
<< print_time(total_cc_dd_time / num_sources) << " per source)"
<< " Total shiloach-vishkin time " << print_time(total_cc_sv_time) << " ("
<< print_time(total_cc_sv_time / num_sources) << " per source)"
<< " Total parallel shiloach-vishkin time " << print_time(total_cc_sv_ps_time) << " ("
<< print_time(total_cc_sv_ps_time / num_sources) << " per source)"
<< " Total local difference time " << print_time(total_cc_ld_time) << " ("
<< print_time(total_cc_ld_time / num_sources) << " per source)."
<< " Running Scale : " << scale
#ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS
<< ", messages = " << cumulative_messages << " (" << (cumulative_messages / num_sources) << " per source), "
<< " full buffers = " << cumulative_full << " (" << (cumulative_full / num_sources) << " per source)"
<< " partial flushes = " << buffers << " (" << (buffers / num_sources) << " per source) with "
<< msg_per_buf << " messages per buffer on average (-1 means buffer size is 0)."
#endif
#ifdef AMPLUSPLUS_PRINT_HIT_RATES
<< "\nTests = " << (cumulative_tests / num_sources) << " (per source), hits = " << (cumulative_hits / num_sources)
<< " (per source), hit rate = " << (double(cumulative_hits) / double(cumulative_tests) * 100.) << "%"
#endif
#ifdef PBGL2_PRINT_WORK_STATS
PBGL2_DS_PRINT // The print macro for work stats
#endif
<< std::endl;
#endif // end of CC_ALGORITHMS
}*/ else if(run_kla) { // run_kla
std::cout << "Total kla-sssp time for " << num_sources << " sources = "
<< print_time(total_time) << " ("
<< print_time(total_time / num_sources) << " per source), klevel = "
<< k_level << "%"
#ifdef PBGL2_PRINT_WORK_STATS
PBGL2_DS_PRINT // The print macro for work stats
#endif
<< std::endl;
}
time_type mean = total_time / num_sources;
time_type min = 0;
time_type q1 = 0;
time_type median = 0;
time_type q3 = 0;
time_type max = 0;
time_type stddev = 0;
time_statistics(all_times,
mean,
min,
q1,
median,
q3,
max,
stddev);
std::cout << "MEAN : " << print_time(mean)
<< " STDDEV : " << print_time(stddev)
<< " MIN : " << print_time(min)
<< " Q1 : " << print_time(q1)
<< " MEDIAN : " << print_time(median)
<< " Q3 : " << print_time(q3)
<< " MAX : " << print_time(max)
<< std::endl;
#ifdef CALCULATE_GTEPS
std::cout << "==============TEPS Statistics=================" << std::endl;
double *tm = (double*)malloc(sizeof(double)*num_sources);
double *stats = (double*)malloc(sizeof(double)*9);
// TODO We need to fix stat when num_sources < 4
if (!run_cc && num_sources > 4) {
for(int i = 0; i < num_sources; i++)
tm[i] = edge_traversed[i]/elapsed_time[i];
statistics (stats, tm, num_sources);
PRINT_GRAPH500_STATS("TEPS", 1);
}
free(tm);
free(stats);
#endif
free(edge_traversed);
free(elapsed_time);
}
}
template<typename Graph500Iter, typename Routing, typename Distribution, typename Trans, typename EdgeSize, typename UInt, typename Edges, typename WeightIterator>
void do_distribute(Distribution &distrib, Trans &trans, EdgeSize e_start, EdgeSize e_count, UInt a, UInt b, Edges &edges, WeightIterator weight_iter,
int num_threads) {
typedef amplusplus::routing_generator<amplusplus::counter_coalesced_message_type_gen, Routing> MessageGenerator;
MessageGenerator msg_gen(amplusplus::counter_coalesced_message_type_gen(distribution_coalescing_size), Routing(trans.rank(), trans.size()));
time_type start = get_time();
// Multithreaded distribution
trans.set_nthreads(num_threads);
#ifdef PRINT_DEBUG
std::cout << "Thread start : " << e_start << "Total edge count : " << e_count
<< " for rank :" << trans.rank()
<< std::endl;
#endif
Edges* thread_edges = new Edges[num_threads];
EdgeSize std_count_per_thread = (e_count + num_threads - 1) / num_threads;
// EdgeSize remainder = e_count % num_threads;
#ifdef PRINT_DEBUG
std::cout << "std_count_per_thread : " << std_count_per_thread << std::endl;
#endif
EdgeSize thread_start = e_start;
EdgeSize count_per_thread = std_count_per_thread;
// create message type
typedef typename std::iterator_traits<Graph500Iter>::value_type value_type;
typedef detail::vector_write_handler<Edges> vec_write_handler;
// not sure we need this here
amplusplus::register_mpi_datatype<value_type>();
typedef typename MessageGenerator::template call_result<value_type, vec_write_handler,
detail::distrib_to_pair_owner_map_t<Distribution>, amplusplus::no_reduction_t>::type
write_msg_type;
write_msg_type write_msg(msg_gen, trans, detail::distrib_to_pair_owner_map<Distribution>(distrib),
amplusplus::no_reduction);
// set the handler (must be in main thread)
write_msg.set_handler(vec_write_handler(thread_edges));
threaded_distributor<write_msg_type> td(write_msg);
boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]);
for (int i = 0; i < num_threads - 1; ++i) {
#ifdef PRINT_DEBUG
if (_RANK == 0) {
std::cout << "Thread : " << i+1 << " start : " << thread_start
<< " thread end : " << (thread_start + count_per_thread)
<< std::endl;
}
#endif
boost::thread thr(boost::ref(td), i+1, Graph500Iter(scale, thread_start, a, b, weight_iter),
Graph500Iter(scale, thread_start + count_per_thread, a, b, weight_iter),
flip_pair(), trans);
thread_start = thread_start + count_per_thread;
threads[i].swap(thr);
}
// Allocate remainder to main thread
count_per_thread = std::min(std_count_per_thread, (e_count-thread_start));
#ifdef PRINT_DEBUG
std::cout << "Thread : " << 0 << " start : " << thread_start
<< " thread end : " << (thread_start + count_per_thread)
<< std::endl;
#endif
td(0, Graph500Iter(scale, thread_start, a, b, weight_iter),
Graph500Iter(scale, thread_start + count_per_thread, a, b, weight_iter),
flip_pair(), trans);
// Wait till all threads finish
for (int i = 0; i < num_threads - 1; ++i)
threads[i].join();
// Merge all edges - in threads
// time_type m_start = get_time();
typename Edges::size_type total_sz = 0;
std::vector<typename Edges::size_type> positions(num_threads);
for (int i = 0; i < num_threads; ++i) {
positions[i] = total_sz;
total_sz += thread_edges[i].size();
}
edges.resize(total_sz);
threaded_merger<Edges> tm(edges);
boost::scoped_array<boost::thread> m_threads(new boost::thread[num_threads - 1]);
for (int i = 0; i < num_threads - 1; ++i) {
typename Edges::iterator pos_ite = edges.begin();
std::advance(pos_ite, positions[i+1]);
boost::thread thr(boost::ref(tm), pos_ite,
thread_edges[i+1].begin(), thread_edges[i+1].end());
m_threads[i].swap(thr);
}
tm(edges.begin(), thread_edges[0].begin(), thread_edges[0].end());
// Wait till all threads finish
for (int i = 0; i < num_threads - 1; ++i)
m_threads[i].join();
//time_type m_end = get_time();
trans.set_nthreads(1);
delete[] thread_edges;
{ amplusplus::scoped_epoch epoch(trans); }
time_type end = get_time();
std::cout << "Graph distribution permutation took " << (end-start)
<< " time" << std::endl;
// sort edges in parallel
//__gnu_parallel::sort(edges.begin(), edges.end());
}
};
void q_test() {
typedef std::pair<int, int> vertex_distance_data;
struct default_comparer {
bool operator()(const vertex_distance_data& vd1, const vertex_distance_data& vd2) {
return vd1.second > vd2.second;
}
};
cds::Initialize();
{
// Initialize Hazard Pointer singleton
cds::gc::HP hpGC(72);
// Attach for the main thread
cds::threading::Manager::attachThread();
// template<typename vertex_distance, typename Compare>
/* struct reverse_compare {
private:
default_comparer c;
public:
inline bool operator()(const vertex_distance_data& vd1, const vertex_distance_data& vd2) {
return c(vd2, vd1);
}
};*/
graph::distributed::ms_node_priority_queue<vertex_distance_data, default_comparer> npq(10);
graph::distributed::node_priority_queue<vertex_distance_data, default_comparer> pq(10);
// graph::distributed::ellen_bin_priority_queue<vertex_distance_data, default_comparer> epq(10);
std::priority_queue<vertex_distance_data, std::vector<vertex_distance_data>, default_comparer> dpq;
vertex_distance_data vd1(10, 22);
vertex_distance_data vd2(1, 23);
vertex_distance_data vd3(5, 34);
vertex_distance_data vd4(8, 12);
vertex_distance_data vd5(11, 210);
vertex_distance_data vd6(7, 2);
vertex_distance_data vd7(8, 650);
vertex_distance_data vd8(5, 30);
vertex_distance_data vd9(2, 22);
vertex_distance_data vd10(9, 21);
npq.put(vd1,0);
npq.put(vd2,1);
npq.put(vd3,0);
npq.put(vd4,2);
npq.put(vd5,3);
npq.put(vd6,4);
npq.put(vd7,5);
npq.put(vd8,6);
npq.put(vd9,2);
npq.put(vd10,4);
pq.put(vd1,0);
pq.put(vd2,1);
pq.put(vd3,0);
pq.put(vd4,2);
pq.put(vd5,3);
pq.put(vd6,4);
pq.put(vd7,5);
pq.put(vd8,6);
pq.put(vd9,2);
pq.put(vd10,4);
/* epq.put(vd1,0);
epq.put(vd2,1);
epq.put(vd3,0);
epq.put(vd4,2);
epq.put(vd5,3);
epq.put(vd6,4);
epq.put(vd7,5);
epq.put(vd8,6);
epq.put(vd9,2);
epq.put(vd10,4);*/
dpq.push(vd1);
dpq.push(vd2);
dpq.push(vd3);
dpq.push(vd4);
dpq.push(vd5);
dpq.push(vd6);
dpq.push(vd7);
dpq.push(vd8);
dpq.push(vd9);
dpq.push(vd10);
std::cout << "========== cds :: mspq ===========" << std::endl;
// should give the shortest distance first
vertex_distance_data vdx1;
while(npq.pop(vdx1, 0)) {
std::cout << vdx1.second << std::endl;
}
assert(npq.empty());
std::cout << "========== cds :: fcpq ===========" << std::endl;
// should give the shortest distance first
vertex_distance_data vdx2;
while(pq.pop(vdx2, 0)) {
std::cout << vdx2.second << std::endl;
}
assert(pq.empty());
/* std::cout << "========== cds :: ellenbin ===========" << std::endl;
// should give the shortest distance first
vertex_distance_data vdx3;
while(epq.pop(vdx3, 0)) {
std::cout << vdx3.second << std::endl;
}
assert(epq.empty());*/
std::cout << "========== std::queue===========" << std::endl;
while(!dpq.empty()) {
std::cout << dpq.top().second << std::endl;
dpq.pop();
}
cds::threading::Manager::detachThread();
}
cds::Terminate();
exit(0);
}
int main(int argc, char* argv[]) {
// q_test();
dc_test t(argc, argv);
t.test_main(argc, argv);
}
| 31.594864 | 637 | 0.650848 |
9a790e854bb7dd080b0f2c05900dcf25ae79e48e | 1,049 | cpp | C++ | ColliderBit/src/models/SUSY.cpp | GambitBSM/gambit_2.0 | a4742ac94a0352585a3b9dcb9b222048a5959b91 | [
"Unlicense"
] | 1 | 2021-09-17T22:53:26.000Z | 2021-09-17T22:53:26.000Z | ColliderBit/src/models/SUSY.cpp | GambitBSM/gambit_2.0 | a4742ac94a0352585a3b9dcb9b222048a5959b91 | [
"Unlicense"
] | 3 | 2021-07-22T11:23:48.000Z | 2021-08-22T17:24:41.000Z | ColliderBit/src/models/SUSY.cpp | GambitBSM/gambit_2.0 | a4742ac94a0352585a3b9dcb9b222048a5959b91 | [
"Unlicense"
] | 1 | 2021-08-14T10:31:41.000Z | 2021-08-14T10:31:41.000Z | // GAMBIT: Global and Modular BSM Inference Tool
// *********************************************
/// \file
///
/// SUSY-specific sources for ColliderBit.
///
/// *********************************************
///
/// Authors (add name and date if you modify):
///
/// \author Pat Scott
/// (p.scott@imperial.ac.uk)
/// \date 2019 Jan
///
/// \author Anders Kvellestad
/// (anders.kvellestad@fys.uio.no)
/// \date 2019
///
/// *********************************************
#include "gambit/ColliderBit/getPy8Collider.hpp"
#include "gambit/ColliderBit/generateEventPy8Collider.hpp"
namespace Gambit
{
namespace ColliderBit
{
// Get spectrum and decays for Pythia
GET_SPECTRUM_AND_DECAYS_FOR_PYTHIA_SUSY(getSpectrumAndDecaysForPythia, MSSM_spectrum)
// Get Monte Carlo event generator
GET_SPECIFIC_PYTHIA(getPythia, Pythia_default, /* blank MODEL_EXTENSION argument */ )
GET_PYTHIA_AS_BASE_COLLIDER(getPythiaAsBase)
// Run event generator
GET_PYTHIA_EVENT(generateEventPythia)
}
}
| 25.585366 | 89 | 0.602479 |