hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
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
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
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
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
d8a4a799392ed4bd39f2c65c64010475ee5bc0c0
4,935
hpp
C++
planning/lib/helpers.hpp
Ewenwan/Path-Planning
2b3e6e566933dbb40261e16bd97f0dbc2b9ef847
[ "MIT" ]
82
2015-09-04T08:42:44.000Z
2022-03-12T12:10:47.000Z
planning/lib/helpers.hpp
etarakci-hvl/Path-Planning
2b3e6e566933dbb40261e16bd97f0dbc2b9ef847
[ "MIT" ]
25
2015-09-07T14:11:33.000Z
2015-09-26T08:06:06.000Z
planning/lib/helpers.hpp
etarakci-hvl/Path-Planning
2b3e6e566933dbb40261e16bd97f0dbc2b9ef847
[ "MIT" ]
39
2015-09-04T04:46:48.000Z
2022-03-25T14:36:21.000Z
#pragma once #include <limits> #include <algorithm> #include <vector> #include <map> #include <functional> #include <unordered_map> #include <unordered_set> #include <string> using std::max; using std::make_pair; using std::min; using std::abs; using std::hypot; using std::vector; using std::map; using std::function; using std::unordered_map; using std::unordered_set; using std::string; using std::to_string; using std::hash; namespace search { constexpr auto huge() { return 10'000; } constexpr auto cost() { return 1; } struct Cell { int row, col; friend auto operator== (Cell l, Cell r) { return l.row == r.row && l.col == r.col; } friend auto operator!= (Cell l, Cell r) { return !(l == r); } auto to_string() const { using std::to_string; return string{ "[r=" + to_string(row) + ",c=" + to_string(col) + "]" }; } struct Hasher { auto operator()(Cell c) const { return hash<string>{}(c.to_string()); } }; }; const static map< char, function< Cell(Cell) >> DIRECTIONS { { '1', [](Cell c) { return Cell{ c.row - 1, c.col - 1 }; } }, { '2', [](Cell c) { return Cell{ c.row - 1, c.col - 0 }; } }, { '3', [](Cell c) { return Cell{ c.row - 1, c.col + 1 }; } }, { '4', [](Cell c) { return Cell{ c.row - 0, c.col - 1 }; } }, { '5', [](Cell c) { return Cell{ c.row + 0, c.col + 1 }; } }, { '6', [](Cell c) { return Cell{ c.row + 1, c.col - 1 }; } }, { '7', [](Cell c) { return Cell{ c.row + 1, c.col + 0 }; } }, { '8', [](Cell c) { return Cell{ c.row + 1, c.col + 1 }; } } }; using Cells = unordered_set<Cell, Cell::Hasher>; struct LpState { Cell cell; int g, r, h; bool bad; auto to_string() const { using std::to_string; return "{" + cell.to_string() + "|g:" + to_string(g) + "|r:" + to_string(r) + "|h:" + to_string(h) + "|b:" + (bad ? "t" : "f") + "}"; } friend auto operator==(LpState const& l, LpState const& r) { return l.cell == r.cell && l.g == r.g && l.r == r.r && l.h == r.h && l.bad == r.bad; } }; class Matrix { public: auto rows() const { return _data.size(); } auto cols() const { return _data.front().size(); } template<typename Func> auto each_cell(Func && func) { for (auto r = 0; r != rows(); ++r) for (auto c = 0; c != cols(); ++c) func(Cell{ r, c }); } template<typename Func> auto each_cell(Func && func) const { for (auto r = 0; r != rows(); ++r) for (auto c = 0; c != cols(); ++c) func(Cell{ r, c }); } auto at(Cell c) -> LpState& { return{ _data[c.row][c.col] }; } auto at(Cell c) const -> LpState const& { return{ _data[c.row][c.col] }; } auto to_string() const { string result; for (auto r = 0; r != rows(); ++r) { for (auto c = 0; c != cols(); ++c) result += at({ r, c }).to_string(); result += "+++"; } return result; } // // Ctor // Matrix(unsigned rows, unsigned cols) : _data{ rows, vector<LpState>(cols) } { auto init_state = [this](Cell c) { at(c).cell = c, at(c).g = at(c).r = huge(); }; each_cell(init_state); } private: vector<vector<LpState>> _data; }; const static unordered_map < string, function<int(Cell, Cell)> > HEURISTICS { { "manhattan", [](Cell l, Cell r) { return max(abs(l.row - r.row), abs(l.col - r.col)); } }, { "euclidean", [](Cell l, Cell r) { return static_cast<int>(round(hypot(abs(l.row - r.row), abs(l.col - r.col)))); } } }; struct Key { const int fst, snd; Key(int fst, int snd) : fst{ fst }, snd{ snd } { } Key(LpState const& s) : Key{ min(s.g, s.r) + s.h, min(s.g, s.r) } // CalculateKey for LPA { } Key(LpState const& s, int km) : Key{ min(s.g, s.r) + s.h + km, min(s.g, s.r) } // CalculateKey for Dstar { } friend auto operator== (Key l, Key r) { return l.fst == r.fst && l.snd == r.snd; } friend auto operator < (Key l, Key r) { return (l.fst < r.fst) || (l.fst == r.fst && l.snd < r.snd); } }; }
26.675676
145
0.435664
[ "vector" ]
d8ab93c908459227d30da2ef4ca44f2e0324b855
17,299
cpp
C++
engine/src/graphics/GizmoRenderer.cpp
jsandham/PhysicsEngine
51115ee9a59f3bc6e0895113c67563cfd4a1ef3c
[ "MIT" ]
2
2018-12-19T01:52:39.000Z
2022-03-29T16:04:15.000Z
engine/src/graphics/GizmoRenderer.cpp
jsandham/PhysicsEngine
51115ee9a59f3bc6e0895113c67563cfd4a1ef3c
[ "MIT" ]
null
null
null
engine/src/graphics/GizmoRenderer.cpp
jsandham/PhysicsEngine
51115ee9a59f3bc6e0895113c67563cfd4a1ef3c
[ "MIT" ]
null
null
null
#include "../../include/graphics/GizmoRenderer.h" #include "../../include/core/World.h" #include <GL/glew.h> #include <gl/gl.h> using namespace PhysicsEngine; GizmoRenderer::GizmoRenderer() { } GizmoRenderer::~GizmoRenderer() { destroyGizmoRenderer(mState); } void GizmoRenderer::init(World *world) { mWorld = world; initializeGizmoRenderer(mWorld, mState); } void GizmoRenderer::update(Camera *camera) { renderLineGizmos(mWorld, camera, mState, mLines); renderPlaneGizmos(mWorld, camera, mState, mPlanes); renderAABBGizmos(mWorld, camera, mState, mAABBs); renderSphereGizmos(mWorld, camera, mState, mSpheres); renderFrustumGizmos(mWorld, camera, mState, mFrustums); } void GizmoRenderer::drawGrid(Camera* camera) { renderGridGizmo(mWorld, camera, mState); } void GizmoRenderer::addToDrawList(const Line &line, const Color &color) { mLines.push_back(LineGizmo(line, color)); } void GizmoRenderer::addToDrawList(const Ray &ray, float t, const Color &color) { Line line; line.mStart = ray.mOrigin; line.mEnd = ray.mOrigin + t * ray.mDirection; mLines.push_back(LineGizmo(line, color)); } void GizmoRenderer::addToDrawList(const Sphere& sphere, const Color& color) { mSpheres.push_back(SphereGizmo(sphere, color)); } void GizmoRenderer::addToDrawList(const AABB &aabb, const Color &color, bool wireframe) { mAABBs.push_back(AABBGizmo(aabb, color, wireframe)); } void GizmoRenderer::addToDrawList(const Frustum &frustum, const Color &color, bool wireframe) { mFrustums.push_back(FrustumGizmo(frustum, color, wireframe)); } void GizmoRenderer::addToDrawList(const Plane &plane, const glm::vec3 &extents, const Color &color, bool wireframe) { mPlanes.push_back(PlaneGizmo(plane, extents, color, wireframe)); } void GizmoRenderer::clearDrawList() { mLines.clear(); mAABBs.clear(); mSpheres.clear(); mFrustums.clear(); mPlanes.clear(); } void PhysicsEngine::initializeGizmoRenderer(World *world, GizmoRendererState &state) { Graphics::compileLineShader(state); Graphics::compileGizmoShader(state); Graphics::compileGridShader(state); state.mGridColor = Color(1.0f, 1.0f, 1.0f, 1.0f); state.mFrustumVertices.resize(108, 0.0f); state.mFrustumNormals.resize(108, 0.0f); Graphics::createFrustum(state.mFrustumVertices, state.mFrustumNormals, &state.mFrustumVAO, &state.mFrustumVBO[0], &state.mFrustumVBO[1]); for (int i = -100; i < 100; i++) { glm::vec3 start = glm::vec3(i, 0.0f, -100.0f); glm::vec3 end = glm::vec3(i, 0.0f, 100.0f); state.mGridVertices.push_back(start); state.mGridVertices.push_back(end); } for (int i = -100; i < 100; i++) { glm::vec3 start = glm::vec3(-100.0f, 0.0f, i); glm::vec3 end = glm::vec3(100.0f, 0.0f, i); state.mGridVertices.push_back(start); state.mGridVertices.push_back(end); } Graphics::createGrid(state.mGridVertices, &state.mGridVAO, &state.mGridVBO); } void PhysicsEngine::destroyGizmoRenderer(GizmoRendererState &state) { Graphics::destroyFrustum(&state.mFrustumVAO, &state.mFrustumVBO[0], &state.mFrustumVBO[1]); Graphics::destroyGrid(&state.mGridVAO, &state.mGridVBO); } void PhysicsEngine::renderLineGizmos(World *world, Camera *camera, GizmoRendererState &state, const std::vector<LineGizmo> &gizmos) { if (gizmos.empty()) { return; } std::vector<float> vertices(6 * gizmos.size()); for (size_t i = 0; i < gizmos.size(); i++) { vertices[6 * i + 0] = gizmos[i].mLine.mStart.x; vertices[6 * i + 1] = gizmos[i].mLine.mStart.y; vertices[6 * i + 2] = gizmos[i].mLine.mStart.z; vertices[6 * i + 3] = gizmos[i].mLine.mEnd.x; vertices[6 * i + 4] = gizmos[i].mLine.mEnd.y; vertices[6 * i + 5] = gizmos[i].mLine.mEnd.z; } std::vector<float> colors(8 * gizmos.size()); for (size_t i = 0; i < gizmos.size(); i++) { colors[8 * i + 0] = gizmos[i].mColor.r; colors[8 * i + 1] = gizmos[i].mColor.g; colors[8 * i + 2] = gizmos[i].mColor.b; colors[8 * i + 3] = gizmos[i].mColor.a; colors[8 * i + 4] = gizmos[i].mColor.r; colors[8 * i + 5] = gizmos[i].mColor.g; colors[8 * i + 6] = gizmos[i].mColor.b; colors[8 * i + 7] = gizmos[i].mColor.a; } unsigned int lineVAO; unsigned int lineVBO[2]; Graphics::createLine(vertices, colors, &lineVAO, &lineVBO[0], &lineVBO[1]); Graphics::bindFramebuffer(camera->getNativeGraphicsMainFBO()); Graphics::setViewport(camera->getViewport().mX, camera->getViewport().mY, camera->getViewport().mWidth, camera->getViewport().mHeight); glm::mat4 mvp = camera->getProjMatrix() * camera->getViewMatrix(); Graphics::use(state.mLineShaderProgram); Graphics::setMat4(state.mLineShaderMVPLoc, mvp); glBindVertexArray(lineVAO); glDrawArrays(GL_LINES, 0, (GLsizei)(vertices.size() / 3)); glBindVertexArray(0); Graphics::unbindFramebuffer(); Graphics::destroyLine(&lineVAO, &lineVBO[0], &lineVBO[1]); Graphics::checkError(__LINE__, __FILE__); } void PhysicsEngine::renderSphereGizmos(World *world, Camera *camera, GizmoRendererState &state, const std::vector<SphereGizmo> &gizmos) { if (gizmos.empty()) { return; } Graphics::turnOn(Capability::Blending); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); Transform *transform = camera->getComponent<Transform>(); Mesh *mesh = world->getAssetById<Mesh>(world->getAssetId("data\\meshes\\sphere.mesh")); Graphics::bindFramebuffer(camera->getNativeGraphicsMainFBO()); Graphics::setViewport(camera->getViewport().mX, camera->getViewport().mY, camera->getViewport().mWidth, camera->getViewport().mHeight); Graphics::bindVertexArray(mesh->getNativeGraphicsVAO()); Graphics::use(state.mGizmoShaderProgram); Graphics::setVec3(state.mGizmoShaderLightPosLoc, transform->mPosition); Graphics::setMat4(state.mGizmoShaderViewLoc, camera->getViewMatrix()); Graphics::setMat4(state.mGizmoShaderProjLoc, camera->getProjMatrix()); for (size_t i = 0; i < gizmos.size(); i++) { glm::mat4 model = glm::translate(glm::mat4(), gizmos[i].mSphere.mCentre); model = glm::scale(model, glm::vec3(gizmos[i].mSphere.mRadius, gizmos[i].mSphere.mRadius, gizmos[i].mSphere.mRadius)); Graphics::setColor(state.mGizmoShaderColorLoc, gizmos[i].mColor); Graphics::setMat4(state.mGizmoShaderModelLoc, model); glDrawArrays(GL_TRIANGLES, 0, (GLsizei)(mesh->getVertices().size() / 3)); } Graphics::unbindVertexArray(); Graphics::unbindFramebuffer(); Graphics::turnOff(Capability::Blending); Graphics::checkError(__LINE__, __FILE__); } void PhysicsEngine::renderAABBGizmos(World *world, Camera *camera, GizmoRendererState &state, const std::vector<AABBGizmo> &gizmos) { if (gizmos.empty()) { return; } Graphics::turnOn(Capability::Blending); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); Transform *transform = camera->getComponent<Transform>(); Mesh *mesh = world->getAssetById<Mesh>(world->getAssetId("data\\meshes\\cube.mesh")); Graphics::bindFramebuffer(camera->getNativeGraphicsMainFBO()); Graphics::setViewport(camera->getViewport().mX, camera->getViewport().mY, camera->getViewport().mWidth, camera->getViewport().mHeight); Graphics::bindVertexArray(mesh->getNativeGraphicsVAO()); Graphics::use(state.mGizmoShaderProgram); Graphics::setVec3(state.mGizmoShaderLightPosLoc, transform->mPosition); Graphics::setMat4(state.mGizmoShaderViewLoc, camera->getViewMatrix()); Graphics::setMat4(state.mGizmoShaderProjLoc, camera->getProjMatrix()); for (size_t i = 0; i < gizmos.size(); i++) { glm::mat4 model = glm::translate(glm::mat4(), gizmos[i].mAABB.mCentre); model = glm::scale(model, gizmos[i].mAABB.mSize); Graphics::setColor(state.mGizmoShaderColorLoc, gizmos[i].mColor); Graphics::setMat4(state.mGizmoShaderModelLoc, model); glDrawArrays(GL_TRIANGLES, 0, (GLsizei)(mesh->getVertices().size() / 3)); } Graphics::unbindVertexArray(); Graphics::unbindFramebuffer(); Graphics::turnOff(Capability::Blending); Graphics::checkError(__LINE__, __FILE__); } void PhysicsEngine::renderPlaneGizmos(World *world, Camera *camera, GizmoRendererState &state, const std::vector<PlaneGizmo> &gizmos) { if (gizmos.empty()) { return; } Graphics::turnOn(Capability::Blending); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); Transform *transform = camera->getComponent<Transform>(); Mesh *mesh = world->getAssetById<Mesh>(world->getAssetId("data\\meshes\\plane.mesh")); Graphics::bindFramebuffer(camera->getNativeGraphicsMainFBO()); Graphics::setViewport(camera->getViewport().mX, camera->getViewport().mY, camera->getViewport().mWidth, camera->getViewport().mHeight); Graphics::bindVertexArray(mesh->getNativeGraphicsVAO()); Graphics::use(state.mGizmoShaderProgram); Graphics::setVec3(state.mGizmoShaderLightPosLoc, transform->mPosition); Graphics::setMat4(state.mGizmoShaderViewLoc, camera->getViewMatrix()); Graphics::setMat4(state.mGizmoShaderProjLoc, camera->getProjMatrix()); for (size_t i = 0; i < gizmos.size(); i++) { glm::mat4 model = glm::translate(glm::mat4(), gizmos[i].mPlane.mX0); glm::vec3 a = glm::vec3(0, 0, 1); glm::vec3 b = gizmos[i].mPlane.mNormal; float d = glm::dot(a, b); glm::vec3 c = glm::cross(a, b); float angle = glm::atan(glm::length(c), d); model = glm::rotate(model, angle, c); Graphics::setColor(state.mGizmoShaderColorLoc, gizmos[i].mColor); Graphics::setMat4(state.mGizmoShaderModelLoc, model); glDrawArrays(GL_TRIANGLES, 0, (GLsizei)(mesh->getVertices().size() / 3)); } Graphics::unbindVertexArray(); Graphics::unbindFramebuffer(); Graphics::turnOff(Capability::Blending); Graphics::checkError(__LINE__, __FILE__); } void PhysicsEngine::renderShadedFrustumGizmo(World *world, Camera *camera, GizmoRendererState &state, const FrustumGizmo &gizmo) { glm::vec3 temp[36]; temp[0] = gizmo.mFrustum.mNtl; temp[1] = gizmo.mFrustum.mNtr; temp[2] = gizmo.mFrustum.mNbr; temp[3] = gizmo.mFrustum.mNtl; temp[4] = gizmo.mFrustum.mNbr; temp[5] = gizmo.mFrustum.mNbl; temp[6] = gizmo.mFrustum.mFtl; temp[7] = gizmo.mFrustum.mFtr; temp[8] = gizmo.mFrustum.mFbr; temp[9] = gizmo.mFrustum.mFtl; temp[10] = gizmo.mFrustum.mFbr; temp[11] = gizmo.mFrustum.mFbl; temp[12] = gizmo.mFrustum.mNtl; temp[13] = gizmo.mFrustum.mFtl; temp[14] = gizmo.mFrustum.mFtr; temp[15] = gizmo.mFrustum.mNtl; temp[16] = gizmo.mFrustum.mFtr; temp[17] = gizmo.mFrustum.mNtr; temp[18] = gizmo.mFrustum.mNbl; temp[19] = gizmo.mFrustum.mFbl; temp[20] = gizmo.mFrustum.mFbr; temp[21] = gizmo.mFrustum.mNbl; temp[22] = gizmo.mFrustum.mFbr; temp[23] = gizmo.mFrustum.mNbr; temp[24] = gizmo.mFrustum.mNbl; temp[25] = gizmo.mFrustum.mFbl; temp[26] = gizmo.mFrustum.mFtl; temp[27] = gizmo.mFrustum.mNbl; temp[28] = gizmo.mFrustum.mFtl; temp[29] = gizmo.mFrustum.mNtl; temp[30] = gizmo.mFrustum.mNbr; temp[31] = gizmo.mFrustum.mFbr; temp[32] = gizmo.mFrustum.mFtr; temp[33] = gizmo.mFrustum.mNbr; temp[34] = gizmo.mFrustum.mFtr; temp[35] = gizmo.mFrustum.mNtr; for (int j = 0; j < 36; j++) { state.mFrustumVertices[3 * j + 0] = temp[j].x; state.mFrustumVertices[3 * j + 1] = temp[j].y; state.mFrustumVertices[3 * j + 2] = temp[j].z; } for (int j = 0; j < 6; j++) { glm::vec3 a = temp[6 * j + 1] - temp[6 * j]; glm::vec3 b = temp[6 * j + 2] - temp[6 * j]; glm::vec3 normal = glm::cross(a, b); for (int k = 0; k < 6; k++) { state.mFrustumNormals[18 * j + 3 * k + 0] = normal.x; state.mFrustumNormals[18 * j + 3 * k + 1] = normal.y; state.mFrustumNormals[18 * j + 3 * k + 2] = normal.z; } } Transform *transform = camera->getComponent<Transform>(); Graphics::use(state.mGizmoShaderProgram); Graphics::setVec3(state.mGizmoShaderLightPosLoc, transform->mPosition); Graphics::setMat4(state.mGizmoShaderModelLoc, glm::mat4(1.0f)); Graphics::setMat4(state.mGizmoShaderViewLoc, camera->getViewMatrix()); Graphics::setMat4(state.mGizmoShaderProjLoc, camera->getProjMatrix()); Graphics::setColor(state.mGizmoShaderColorLoc, gizmo.mColor); glBindBuffer(GL_ARRAY_BUFFER, state.mFrustumVBO[0]); glBufferSubData(GL_ARRAY_BUFFER, 0, state.mFrustumVertices.size() * sizeof(float), &state.mFrustumVertices[0]); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, state.mFrustumVBO[1]); glBufferSubData(GL_ARRAY_BUFFER, 0, state.mFrustumNormals.size() * sizeof(float), &state.mFrustumNormals[0]); glBindBuffer(GL_ARRAY_BUFFER, 0); glDrawArrays(GL_TRIANGLES, 0, (GLsizei)(state.mFrustumVertices.size() / 3)); } void PhysicsEngine::renderWireframeFrustumGizmo(World *world, Camera *camera, GizmoRendererState &state, const FrustumGizmo &gizmo) { glm::vec3 temp[24]; temp[0] = gizmo.mFrustum.mNtl; temp[1] = gizmo.mFrustum.mFtl; temp[2] = gizmo.mFrustum.mNtr; temp[3] = gizmo.mFrustum.mFtr; temp[4] = gizmo.mFrustum.mNbl; temp[5] = gizmo.mFrustum.mFbl; temp[6] = gizmo.mFrustum.mNbr; temp[7] = gizmo.mFrustum.mFbr; temp[8] = gizmo.mFrustum.mNtl; temp[9] = gizmo.mFrustum.mNtr; temp[10] = gizmo.mFrustum.mNtr; temp[11] = gizmo.mFrustum.mNbr; temp[12] = gizmo.mFrustum.mNbr; temp[13] = gizmo.mFrustum.mNbl; temp[14] = gizmo.mFrustum.mNbl; temp[15] = gizmo.mFrustum.mNtl; temp[16] = gizmo.mFrustum.mFtl; temp[17] = gizmo.mFrustum.mFtr; temp[18] = gizmo.mFrustum.mFtr; temp[19] = gizmo.mFrustum.mFbr; temp[20] = gizmo.mFrustum.mFbr; temp[21] = gizmo.mFrustum.mFbl; temp[22] = gizmo.mFrustum.mFbl; temp[23] = gizmo.mFrustum.mFtl; for (int j = 0; j < 24; j++) { state.mFrustumVertices[3 * j + 0] = temp[j].x; state.mFrustumVertices[3 * j + 1] = temp[j].y; state.mFrustumVertices[3 * j + 2] = temp[j].z; } glm::mat4 mvp = camera->getProjMatrix() * camera->getViewMatrix(); Graphics::use(state.mLineShaderProgram); Graphics::setMat4(state.mLineShaderMVPLoc, mvp); glBindBuffer(GL_ARRAY_BUFFER, state.mFrustumVBO[0]); glBufferSubData(GL_ARRAY_BUFFER, 0, 24 * 3 * sizeof(float), &state.mFrustumVertices[0]); glBindBuffer(GL_ARRAY_BUFFER, 0); glDrawArrays(GL_LINES, 0, (GLsizei)(24)); } void PhysicsEngine::renderFrustumGizmos(World *world, Camera *camera, GizmoRendererState &state, const std::vector<FrustumGizmo> &gizmos) { if (gizmos.empty()) { return; } Graphics::turnOn(Capability::Blending); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); Graphics::bindFramebuffer(camera->getNativeGraphicsMainFBO()); Graphics::setViewport(camera->getViewport().mX, camera->getViewport().mY, camera->getViewport().mWidth, camera->getViewport().mHeight); Graphics::bindVertexArray(state.mFrustumVAO); for (size_t i = 0; i < gizmos.size(); i++) { if (!gizmos[i].mWireFrame) { renderShadedFrustumGizmo(world, camera, state, gizmos[i]); } else { renderWireframeFrustumGizmo(world, camera, state, gizmos[i]); } } Graphics::unbindVertexArray(); Graphics::unbindFramebuffer(); Graphics::turnOff(Capability::Blending); Graphics::checkError(__LINE__, __FILE__); } void PhysicsEngine::renderGridGizmo(World *world, Camera *camera, GizmoRendererState &state) { Graphics::turnOn(Capability::Blending); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); Graphics::bindFramebuffer(camera->getNativeGraphicsMainFBO()); Graphics::setViewport(camera->getViewport().mX, camera->getViewport().mY, camera->getViewport().mWidth, camera->getViewport().mHeight); glm::mat4 mvp = camera->getProjMatrix() * camera->getViewMatrix(); Graphics::use(state.mGridShaderProgram); Graphics::setMat4(state.mGridShaderMVPLoc, mvp); Graphics::setColor(state.mGridShaderColorLoc, state.mGridColor); glBindVertexArray(state.mGridVAO); glDrawArrays(GL_LINES, 0, (GLsizei)(state.mGridVertices.size())); glBindVertexArray(0); Graphics::unbindFramebuffer(); Graphics::turnOff(Capability::Blending); Graphics::checkError(__LINE__, __FILE__); }
32.45591
119
0.650905
[ "mesh", "vector", "model", "transform" ]
d8b365f497c257015ebab0fd007bf7e984c3d267
9,591
cpp
C++
src/storm/graphics/cAnimationManager.cpp
master312/quantum-kidney
042e97e9a9998be4fc062eb703c51141ea7bd2e4
[ "MIT" ]
null
null
null
src/storm/graphics/cAnimationManager.cpp
master312/quantum-kidney
042e97e9a9998be4fc062eb703c51141ea7bd2e4
[ "MIT" ]
null
null
null
src/storm/graphics/cAnimationManager.cpp
master312/quantum-kidney
042e97e9a9998be4fc062eb703c51141ea7bd2e4
[ "MIT" ]
null
null
null
#include "cAnimationManager.h" cAnimationManager::cAnimationManager(cTextureManager *_textureManager){ tManager = _textureManager; } cAnimationManager::~cAnimationManager(){ RemoveAll(); } uint cAnimationManager::CreateAnimation(std::vector<uint> frames, int fps, bool _useTextures){ cAnimation tmpAnim; for(int i = 0; i < (int)frames.size(); i++){ tmpAnim.AddFrame(frames[i]); } tmpAnim.SetFps(fps); tmpAnim.SetLastFrame(frames.size()); tmpAnim.SetUseTextures(_useTextures); int toReturn = 0; if(animations.size() > 0){ std::map<uint, cAnimation>::iterator i = animations.end(); --i; animations[i->first + 1] = tmpAnim; toReturn = i->first + 1; }else{ animations[1] = tmpAnim; toReturn = 1; } return toReturn; } uint cAnimationManager::LoadAnimation(std::string _filename){ std::string fullFile = (char*)STORM_DIR_ANIMS + _filename; cBinaryFile tmpFile; tmpFile.Open(fullFile); if(!tmpFile.IsOpen()){ StormPrintLog(STORM_LOG_ERROR, "cAnimation", "Could not open file %s for loading", fullFile.c_str()); return 0; } int tmpInt = 0; int tmpFps = 0; bool isUseTextures = true; //Beginning of file float tmpFloat = tmpFile.ReadFloat(); if(tmpFloat != 16.20f){ StormPrintLog(STORM_LOG_ERROR, "cAnimation", "Invalid file format %s %f", fullFile.c_str(), tmpFloat); tmpFile.Close(); return 0; } //File version if(tmpFile.ReadInt() != (int)STORM_ANIM_FILEVER){ StormPrintLog(STORM_LOG_ERROR, "cAnimation", "Invalid file version %s", fullFile.c_str()); tmpFile.Close(); return 0; } //FPS tmpFps = tmpFile.ReadInt(); //Frames count tmpInt = tmpFile.ReadInt(); //Is texture made from texture sections, or multiple textures if(tmpFile.ReadByte() == '1'){ //Animations is made from multiple textures isUseTextures = true; }else{ //Animations is made form texture sections isUseTextures = false; } //Load frames std::vector<uint> tmpFrames; //Used if animations is created from texture sections std::vector<sTextureSection> tmpSections; for(int i = 0; i < tmpInt; i++){ if(!isUseTextures){ //Animation is made from texture sections sTextureSection tmpS; tmpS.x = tmpFile.ReadInt(); tmpS.y = tmpFile.ReadInt(); tmpS.width = tmpFile.ReadInt(); tmpS.height = tmpFile.ReadInt(); tmpSections.push_back(tmpS); }else{ //Animations is made from multiple textures std::string txFilename = tmpFile.ReadString(); uint tmpFrame = tManager->LoadTexture(txFilename); if(tmpFrame == 0){ StormPrintLog(STORM_LOG_ERROR, "cAnimation", "Frame %s is missing. Animation can not be loaded", txFilename.c_str()); tmpFile.Close(); return 0; } tmpFrames.push_back(tmpFrame); } } if(!isUseTextures){ //Animations is made from texture sections //Load texture here std::string txFilename = tmpFile.ReadString(); uint tmpTexture = tManager->LoadTexture(txFilename); if(tmpTexture == 0){ StormPrintLog(STORM_LOG_ERROR, "cAnimation", "Texture %s is missing. Animation can not be loaded", txFilename.c_str()); tmpFile.Close(); tmpSections.clear(); return 0; } for(int i = 0; i < (int)tmpSections.size(); i++){ tmpSections[i].texture = tmpTexture; tmpFrames.push_back(tManager->CreateSection(tmpSections[i])); } } //Create new animation uint animId = CreateAnimation(tmpFrames, tmpFps, isUseTextures); cAnimation *tmpAnim = GetAnimation(animId); //Read frame groups int grCount = tmpFile.ReadInt(); if(grCount > 0){ for (int i = 0; i < grCount; i++) { std::string tmpStr = tmpFile.ReadString(); int tmpSt = tmpFile.ReadInt(); int tmpEn = tmpFile.ReadInt(); tmpAnim->AddFrameGroup(tmpStr, tmpSt, tmpEn); } } tmpFile.Close(); tmpAnim->SetFilename(_filename); tmpAnim->SetIsLoadedFromFile(true); StormPrintLog(STORM_LOG_INFO, "cAnimation", "Animation %s loaded", _filename.c_str()); return animId; } void cAnimationManager::SaveAnimation(std::string _filename, uint animationId){ cAnimation *tmpAni = GetAnimation(animationId); if(_filename == ""){ StormPrintLog(STORM_LOG_ERROR, "cAnimation", "Could not save animation. Filename name not specified"); return; } if(tmpAni->GetFramesCount() == 0){ StormPrintLog(STORM_LOG_ERROR, "cAnimation", "Could not save animation. There are not any frames in this animation"); return; } tmpAni->SetFilename(_filename); std::string fullFile = (char*)STORM_DIR_ANIMS + _filename; cBinaryFile tmpFile; std::ofstream a_file(fullFile); a_file.clear(); tmpFile.Open(fullFile); if(!tmpFile.IsOpen()){ StormPrintLog(STORM_LOG_ERROR, "cAnimation", "Could not open file %s for saving", fullFile.c_str()); return; } //Storm animation file always begin with 16.16 float tmpFile.WriteFloat(16.20f); //File version tmpFile.WriteInt((int)STORM_ANIM_FILEVER); //FPS tmpFile.WriteInt(tmpAni->GetFps()); //Frames count tmpFile.WriteInt(tmpAni->GetFramesCount()); //Use textures, or sections if(tmpAni->IsUseTextures()){ tmpFile.WriteByte('1'); }else{ tmpFile.WriteByte('0'); } //Write frames sTexture *tmpTexture = NULL; for(int i = 0; i < tmpAni->GetFramesCount(); i++){ if(!tmpAni->IsUseTextures()){ //Animation is made using texture sections sTextureSection *tmpSec = tManager->GetSection(tmpAni->GetFrame(i)); tmpTexture = tManager->GetTexture(tmpSec->texture); //Write section details tmpFile.WriteInt(tmpSec->x); tmpFile.WriteInt(tmpSec->y); tmpFile.WriteInt(tmpSec->width); tmpFile.WriteInt(tmpSec->height); // // // }else{ //Animation is made using multiple textures tmpTexture = tManager->GetTexture(tmpAni->GetFrame(i)); //Filename length tmpFile.WriteString(tmpTexture->filename); } } if(!tmpAni->IsUseTextures()){ //Animation is made using texture sections //Save texture filename tmpFile.WriteString(tmpTexture->filename.c_str()); } //Write all frame gropus std::map<std::string, sAnimFrameGroup> *groups = tmpAni->GetFrameGroups(); tmpFile.WriteInt((int)groups->size()); if(groups->size() > 0){ for (auto& kv : *groups) { tmpFile.WriteString(kv.first); tmpFile.WriteInt(kv.second.start); tmpFile.WriteInt(kv.second.end); } } //Integer 777 marks EOF tmpFile.WriteInt(777); tmpFile.Close(); StormPrintLog(STORM_LOG_INFO, "cAnimation", "Animation %s saved", fullFile.c_str()); } void cAnimationManager::UpdateAll(){ std::map<uint, cAnimation>::iterator iter; for(iter = animations.begin(); iter != animations.end(); ++iter){ iter->second.Update(); } } void cAnimationManager::Remove(uint animationId){ if(animations.count(animationId) == 0) return; if(animations[animationId].IsLoadedFromFile()){ cAnimation *tmpAni = &animations[animationId]; if(tmpAni->IsUseTextures()){ //Animation is made from multiple textures for(int i = 0; i < tmpAni->GetFramesCount(); i++){ tManager->UnloadTexture(tmpAni->GetFrame(i)); } }else{ //Animation is made from texture sections uint toRem = 0; toRem = tManager->GetSection(tmpAni->GetFrame(0))->texture; tManager->UnloadTexture(toRem); } } animations.erase(animationId); } void cAnimationManager::RemoveAll(){ animations.clear(); } void cAnimationManager::Pause(uint animationId){ cAnimation *tmpA = GetAnimation(animationId); if(tmpA != NULL){ tmpA->Pause(); } } void cAnimationManager::PauseAll(){ std::map<uint, cAnimation>::iterator iter; for(iter = animations.begin(); iter != animations.end(); ++iter){ iter->second.Pause(); } } void cAnimationManager::Resume(uint animationId){ cAnimation *tmpA = GetAnimation(animationId); if(tmpA != NULL){ tmpA->Resume(); } } void cAnimationManager::ResumeAll(){ std::map<uint, cAnimation>::iterator iter; for(iter = animations.begin(); iter != animations.end(); ++iter){ iter->second.Resume(); } } uint cAnimationManager::CloneAnimation(uint animationId){ if(animations.count(animationId) == 0) return 0; cAnimation tmpA = animations[animationId]; std::map<uint, cAnimation>::iterator i = animations.end(); --i; animations[i->first + 1] = tmpA; return i->first + 1; } void cAnimationManager::SetRepetitions(uint animationId, int reps){ cAnimation *tmpA = GetAnimation(animationId); if(tmpA != NULL){ tmpA->SetRepetitions(reps); } } void cAnimationManager::Reset(uint animationId){ cAnimation *tmpA = GetAnimation(animationId); if(tmpA != NULL){ tmpA->Reset(); } } void cAnimationManager::ResetAll(){ std::map<uint, cAnimation>::iterator iter; for(iter = animations.begin(); iter != animations.end(); ++iter){ iter->second.Reset(); } } void cAnimationManager::JumpToFrame(uint animationId, int frame){ cAnimation *tmpA = GetAnimation(animationId); if(tmpA != NULL){ tmpA->JumpToFrame(frame); } } void cAnimationManager::DrawAnimation(uint animationId, int x, int y, float scale, float rotation){ cAnimation *tmpA = GetAnimation(animationId); if(tmpA == NULL) return; if(tmpA->IsUseTextures()){ tManager->DrawTexture(tmpA->GetCurTexture(), x, y, scale, rotation); }else{ tManager->DrawSection(tmpA->GetCurTexture(), x, y, scale, rotation); } } cAnimation *cAnimationManager::GetAnimation(uint animationId){ if(animations.count(animationId) == 0){ return NULL; } return &animations[animationId]; }
29.420245
87
0.680117
[ "vector" ]
d8b532c05bfbb3130bd9a1246a736860a0ab0292
28,935
cpp
C++
BenchElise/export_skel_vein.cpp
kikislater/micmac
3009dbdad62b3ad906ec882b74b85a3db86ca755
[ "CECILL-B" ]
451
2016-11-25T09:40:28.000Z
2022-03-30T04:20:42.000Z
BenchElise/export_skel_vein.cpp
kikislater/micmac
3009dbdad62b3ad906ec882b74b85a3db86ca755
[ "CECILL-B" ]
143
2016-11-25T20:35:57.000Z
2022-03-01T11:58:02.000Z
BenchElise/export_skel_vein.cpp
kikislater/micmac
3009dbdad62b3ad906ec882b74b85a3db86ca755
[ "CECILL-B" ]
139
2016-12-02T10:26:21.000Z
2022-03-10T19:40:29.000Z
/*eLiSe06/05/99 Copyright (C) 1999 Marc PIERROT DESEILLIGNY eLiSe : Elements of a Linux Image Software Environment 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., 675 Mass Ave, Cambridge, MA 02139, USA. Author: Marc PIERROT DESEILLIGNY IGN/MATIS Internet: Marc.Pierrot-Deseilligny@ign.fr Phone: (33) 01 43 98 81 28 eLiSe06/05/99*/ /* Copyright (C) 1998 Marc PIERROT DESEILLIGNY Skeletonization by veinerization. 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., 675 Mass Ave, Cambridge, MA 02139, USA. Author: Marc PIERROT DESEILLIGNY IGN/MATIS Internet: Marc.Pierrot-Deseilligny@ign.fr Phone: (33) 01 43 98 81 28 Detail of the algoprithm in Deseilligny-Stamon-Suen "Veinerization : a New Shape Descriptor for Flexible Skeletonization" in IEEE-PAMI Vol 20 Number 5, pp 505-521 It also give the signification of main parameters. */ #include <math.h> #include <stdlib.h> #include <iostream> #include <stdio.h> #include <limits> #include <string> #include <new> #include <assert.h> #include <float.h> #include <sys/types.h> #include <sys/stat.h> #include "export_skel_vein.h" template <class Type> class SkVFifo; template <class Type> class SkVeinIm; class SkVein { public : typedef int INT4; typedef unsigned char U_INT1; typedef unsigned short U_INT2; typedef signed char INT1; static void toto(); // protected : SkVein(); static inline int abs(int v){ return (v<0) ? -v : v;} static inline int min(int v1,int v2) {return (v1<v2) ? v1 : v2;} static inline int max(int v1,int v2) {return (v1>v2) ? v1 : v2;} static inline void set_min(int &v1,int v2) {if (v1 > v2) v1 = v2;} static inline int square(int x) {return x*x;} enum { sz_brd = 3 }; enum { pds_x = 3, pds_y = pds_x * 3, pds_tr_x = pds_y * 3, pds_tr_y = pds_tr_x * 7, pds_moy = pds_tr_y * 7, pds_cent = pds_moy * 29, pds_Mtrx = pds_moy + pds_tr_x, pds_Mtry = pds_moy + pds_tr_y, fact_corr_diag = pds_cent / 3, pds_out = -1000 }; // Data structure to have list of direction class ldir { public : ldir (ldir * next,int dir); ldir * _next; int _dir; int _x; int _y; int _flag_dsym; int _flag; }; // for a given flag, gives the list of active bits static ldir * (BitsOfFlag[256]); // for a given flag, the number of bits active static U_INT1 NbBitFlag[256]; // for a given flag, =1 if NbBitFlag == 1 and 0 elsewhere static U_INT1 FlagIsSing[256]; static U_INT1 UniqueBits[256]; class cc_vflag { public : ldir * _dirs; cc_vflag * _next; cc_vflag(cc_vflag * next,int flag); static cc_vflag * lcc_of_flag(int & flag,bool cx8,cc_vflag *); }; static cc_vflag * (CC_cx8[256]); static cc_vflag * (CC_cx4[256]); static void flag_cc(int & cc,int b,int flag); static int v8x[8]; static int v8y[8]; static int v4x[4]; static int v4y[4]; static U_INT1 flag_dsym[8]; static U_INT1 dir_sym[8]; static U_INT1 dir_suc[8]; static U_INT1 dir_pred[8]; class Pt { public : bool operator != (const Pt & p) { return (x != p.x) || (y != p.y); } Pt(INT4 X,INT4 Y) : x ((U_INT2) X), y ((U_INT2) Y) {} Pt(): x(0),y(0) {} U_INT2 x,y; }; class Pt3 { public : Pt3(INT4 X,INT4 Y,INT4 Z) : x ((U_INT2) X), y ((U_INT2) Y) , z (Z) {} Pt3(): x(0),y(0), z(0) {} U_INT2 x,y; INT4 z; }; // Bench purpose static void show(ldir *); static void show(cc_vflag *); static void showcc(int i,bool cx8); private : static bool _init; }; template <class Type> class SkVeinIm : public SkVein { static const int max_val; static const int min_val; public : SkVeinIm(Type ** d,int tx,int ty); ~SkVeinIm(); void close_sym(); void open_sym(); void set_brd(Type val,int width); void binarize(Type val); void d32(int vmax = max_val-1); void pdsd32vein1l(SkVein::INT4 * pds,SkVein::INT4 y); void d32_veinerize (SkVeinIm<U_INT1> veines,bool cx8); void reset(); void perm_circ_lines(); void push_extr(SkVFifo<Pt> &); void push_extr(SkVFifo<Pt> &,U_INT2 ** som); void get_arc_sym(SkVFifo<Pt> &); bool get_arc_sym(INT4 x,INT4 y); void prolong_extre(); Pt prolong_extre(int x,int y,int k); void prolong_extre_rec(int x,int y,int k,int & nb,SkVFifo<Pt3> &f); void pruning ( SkVeinIm<U_INT1> veines, U_INT2 ** som, double ang, INT4 surf, bool skp, SkVFifo<Pt3> & Fgermes ); void isolated_points ( SkVeinIm<U_INT1> veines, SkVFifo<Pt3> & Fgermes ); int calc_surf(Pt ); // private : Type ** _d; SkVein::INT4 _tx; SkVein::INT4 _ty; bool _free; // to pass as paremeter in calc_surf double _ang; INT4 _surf; U_INT1 ** _dvein; }; template <class Type> class SkVFifo : public SkVein { public : SkVFifo(int capa); bool empty() const {return _nb == 0;} int nb () { return _nb;} Type & operator [] (int k) { assert ((k>=0)&&(k<_nb)); return _tab[(k+_begin)%_capa]; } inline Type getfirst(); inline void pushlast(Type); ~SkVFifo(); // private : void incr_capa(); Type * _tab; int _nb; int _capa; int _begin; SkVFifo(const SkVFifo<Type>&); }; /***************************************************************************/ /* */ /* SkVFifo */ /* */ /***************************************************************************/ template <class Type> SkVFifo<Type>::SkVFifo(int capa) : _tab (new Type [capa]) , _nb (0), _capa (capa), _begin (0) { }; /* template <class Type> SkVFifo<Type>::SkVFifo(const SkVFifo<Type>& f) : _tab (new Type [f._capa]) , _nb (f._nb), _capa (f._capa), _begin (f._begin) { memcpy(_tab,f._tab,_capa*sizeof(Type)); } */ template <class Type> Type SkVFifo<Type>::getfirst() { assert(_nb !=0); Type res = _tab[_begin]; _begin = (_begin+1)%_capa; _nb--; return res; } template <class Type> void SkVFifo<Type>::incr_capa() { Type * newtab = new Type [2*_capa]; int nb_at_end = _capa-_begin; memcpy(newtab,_tab+_begin,nb_at_end*sizeof(Type)); memcpy(newtab+nb_at_end,_tab,_begin*sizeof(Type)); delete [] _tab; _tab = newtab; _begin = 0; _capa *= 2; } template <class Type> void SkVFifo<Type>::pushlast(Type p) { if (_nb == _capa) incr_capa(); _tab[(_begin+_nb++)%_capa] = p; } template <class Type> SkVFifo<Type>::~SkVFifo() { delete [] _tab; } /***************************************************************************/ /* */ /* SkVein */ /* */ /***************************************************************************/ int SkVein::v8x[8] = { 1, 1, 0,-1,-1,-1, 0, 1}; int SkVein::v8y[8] = { 0, 1, 1, 1, 0,-1,-1,-1}; int SkVein::v4x[4] = { 1, 0,-1, 0}; int SkVein::v4y[4] = { 0, 1, 0,-1}; SkVein::U_INT1 SkVein::dir_sym[8]; SkVein::U_INT1 SkVein::dir_suc[8]; SkVein::U_INT1 SkVein::dir_pred[8]; SkVein::U_INT1 SkVein::flag_dsym[8]; SkVein::ldir * (SkVein::BitsOfFlag[256]); SkVein::cc_vflag * (SkVein::CC_cx8[256]); SkVein::cc_vflag * (SkVein::CC_cx4[256]); SkVein::U_INT1 SkVein::NbBitFlag[256]; SkVein::U_INT1 SkVein::FlagIsSing[256]; SkVein::U_INT1 SkVein::UniqueBits[256]; bool SkVein::_init = false; SkVein::ldir::ldir(ldir * next,int dir) : _next (next), _dir (dir) , _x (v8x[dir]), _y (v8y[dir]), _flag_dsym (flag_dsym[dir]), _flag (1<<dir) {} /* Given a "flag" corresponding to a set of bits of V8+, given an initial bit "b", put in cc the flag of the connected component of "b". */ void SkVein::flag_cc(int & cc,int b,int flag) { if ( (cc & (1<<b)) || (! (flag & (1<<b))) ) return; cc |= (1<<b); flag_cc(cc,dir_suc[b],flag); flag_cc(cc,dir_pred[b],flag); if (! (b%2)) { flag_cc(cc,dir_suc[dir_suc[b]],flag); flag_cc(cc,dir_pred[dir_pred[b]],flag); } } SkVein::cc_vflag::cc_vflag(cc_vflag * next,int flag) : _dirs (BitsOfFlag[flag]), _next (next) { } SkVein::cc_vflag * SkVein::cc_vflag::lcc_of_flag ( int & flag, bool cx8, cc_vflag * res ) { for (int b=0 ; b<8 ; b++) if ( (flag & (1<<b)) && ( cx8 || (! (b%2))) ) { int cc = 0; flag_cc(cc,b,flag); flag &= ~cc; res = new cc_vflag(res,cc); } return res; } SkVein::SkVein() { if (_init) return ; _init = true; // Then, init all tabulations required by algorithm { // Stupid "{}" to please FUCKING visual c++ for (int b=0; b<8 ; b++) { dir_sym[b] = (U_INT1)((b+4)%8); flag_dsym[b] = (U_INT1)(1 << dir_sym[b]); dir_suc[b] = (U_INT1)((b+1)%8); dir_pred[b] = (U_INT1) ((b+7)%8); } } { // Stupid "{}" to please FUCKING visual c++ for (int f=0; f<256; f++) { UniqueBits[f] = 255; BitsOfFlag[f] = 0; NbBitFlag[f] = 0; for (int b=0; b<8; b++) if (f&(1<<b)) { BitsOfFlag[f] = new ldir (BitsOfFlag[f],b); NbBitFlag[f]++; } FlagIsSing[f] = (NbBitFlag[f]==1); } } { for (int f=0; f<256; f++) { int flag = f; CC_cx4[f] = cc_vflag::lcc_of_flag(flag,false,0); CC_cx8[f] = cc_vflag::lcc_of_flag(flag,true,CC_cx4[f]); } } for (int b=0; b<8 ; b++) UniqueBits[1<<b] = (U_INT1) b; } //============================ // Just for verifiication //============================ void SkVein::show(ldir * l) { cout << "("; for (int i=0; l; i++,l = l->_next) { if (i) cout << " "; cout << l->_dir; } cout << ")"; } void SkVein::show(cc_vflag * l) { cout << "("; for (int i=0; l; i++,l=l->_next) { if (i) cout << " "; show (l->_dirs); } cout << ")"; } void SkVein::showcc(int i,bool cx8) { cout << i << " ;"; cout << (cx8 ? " [V8] ;" : " [V4] ;"); for (int b =0; b<8; b++) cout << ((i &(1<<b)) ? "*" : "."); cout << " ; "; show(cx8 ? CC_cx8[i] : CC_cx4[i]); cout << "\n"; } /***************************************************************************/ /* */ /* SkVeinIm<Type> */ /* */ /***************************************************************************/ const int SkVeinIm<SkVein::U_INT1>::min_val = 0; const int SkVeinIm<SkVein::U_INT1>::max_val = 255; const int SkVeinIm<SkVein::INT4>::min_val = -0x7fffffff; const int SkVeinIm<SkVein::INT4>::max_val = 0x7fffffff; template <class Type> void SkVeinIm<Type>::close_sym() { set_brd((Type)0,1); for (int y=0; y<_ty ; y++) for (int x=0; x<_tx ; x++) for (ldir * l = BitsOfFlag[_d[y][x]]; l; l=l->_next) _d[y+l->_y][x+l->_x] |= (U_INT1)(l->_flag_dsym); } template <class Type> void SkVeinIm<Type>::open_sym() { set_brd((Type)0,1); for (int y=0; y<_ty ; y++) for (int x=0; x<_tx ; x++) for (ldir * l = BitsOfFlag[_d[y][x]]; l; l=l->_next) if (! (_d[y+l->_y][x+l->_x]&l->_flag_dsym)) _d[y][x] ^= (U_INT1)(l->_flag); } template <class Type> void SkVeinIm<Type>::pdsd32vein1l ( SkVein::INT4 * pds, SkVein::INT4 y ) { Type * lm1 = _d[y-1]; Type * l = _d[y]; Type * lp1 = _d[y+1]; for (INT4 x=0; x<_tx; x++) { if (l[x]) pds[x] = pds_x * x + pds_y * y + pds_Mtrx * l[x+1] + pds_Mtry * lp1[x] + pds_moy * (l[x-1] + lm1[x]) + pds_cent * l[x]; else pds[x] = pds_out; } } template <class Type> void SkVeinIm<Type>::perm_circ_lines() { Type * l0 = _d[0]; for (int y = 1; y<_ty ; y++) _d[y-1] = _d[y]; _d[_ty-1] = l0; } template <class Type> void SkVeinIm<Type>::d32_veinerize ( SkVeinIm<SkVein::U_INT1> veines , bool cx8 ) { set_brd((Type)0,1); cc_vflag ** tab_CC = cx8 ? &CC_cx8[0] : &CC_cx4[0]; assert((veines._tx==_tx)&&(veines._ty==_ty)); veines.reset(); U_INT1 ** _dv = veines._d; SkVeinIm<INT4> ipds(0,_tx,3); INT4 ** pds = ipds._d+1; pdsd32vein1l(pds[-1],1); pdsd32vein1l(pds[0],2); INT4 pk[8]; for(INT4 y=2; y<_ty-2;y++) { pdsd32vein1l(pds[1],y+1); for (INT4 x = 2; x<_tx-2; x++) { if (pds[0][x] > 0) { INT4 flag = 0; INT4 vc = pds[0][x]; for (INT4 k=0; k<8 ; k++) { pk[k] = pds[v8y[k]][x+v8x[k]]-vc; if (pk[k]>0) { if (k&1) pk[k] += (_d[y][x]-_d[y+v8y[k]][x+v8x[k]])*fact_corr_diag; flag |= (1<<k); } } for (cc_vflag * cc = tab_CC[flag]; cc; cc = cc->_next) { int pmax = pds_out; int k_max = -1; for (ldir * l = cc->_dirs;l;l=l->_next) { if (pk[l->_dir] > pmax) { pmax = pk[l->_dir]; k_max = l->_dir; } } _dv[y][x] |= (U_INT1)(1<<k_max); } } } ipds.perm_circ_lines(); } } template <class Type> void SkVeinIm<Type>::reset() { for (int y=0; y<_ty ; y++) memset(_d[y],0,sizeof(Type)*_tx); } template <class Type> void SkVeinIm<Type>::d32(int vmax) { assert((vmax<=max_val) && (vmax>=min_val)); binarize((Type)vmax); set_brd((Type)0,2); { for (INT4 y =0; y< _ty; y++) { Type * l0 = _d[y]; for ( INT4 x = 0; x< _tx ; x++) if (l0[x]) { Type * l = l0 +x; int v = l[0]-2; SkVein::set_min(v,l[-1]); Type * lp = _d[y-1]+x; SkVein::set_min(v,lp[0]); v--; SkVein::set_min(v,lp[1]); SkVein::set_min(v,lp[-1]); l[0] = (Type)(v+3); } } } { for (INT4 y =_ty-1; y>=0; y--) { Type * l0 = _d[y]; for ( INT4 x =_tx-1 ; x>=0 ; x--) if (l0[x]) { Type * l = l0 +x; int v = l[0]-2; SkVein::set_min(v,l[1]); Type * lp = _d[y+1]+x; SkVein::set_min(v,lp[0]); v--; SkVein::set_min(v,lp[1]); SkVein::set_min(v,lp[-1]); l[0] = (Type)(v+3); } } } } template <class Type> void SkVeinIm<Type>::binarize(Type val) { for (INT4 y =0; y<_ty ; y++) { Type * line = _d[y]; for (INT4 x =0; x<_tx ; x++) if(line[x]) line[x] = val; } } template <class Type> void SkVeinIm<Type>::set_brd(Type val,int width) { width = SkVein::max(width,0); width = SkVein::min(width,(_tx+1)/2); width = SkVein::min(width,(_ty+1)/2); for (int w=0 ; w<width ; w++) { { int tyMw = _ty-w-1; for (int x = 0 ; x < _tx ; x++) _d[w][x] = _d[tyMw][x] = val; } { int txMw = _tx-w-1; for (int y=0 ; y<_ty ; y++) _d[y][w] = _d[y][txMw] = val; } } } template <class Type> SkVeinIm<Type>::SkVeinIm(Type ** d,int tx,int ty) : _d (d), _tx (tx), _ty (ty), _free (false) { if (!_d) { _free = true; _d = new Type * [_ty]; for (int y=0; y<_ty ; y++) _d[y] = new Type [_tx]; } } template <class Type> void SkVeinIm<Type>::push_extr(SkVFifo<SkVein::Pt> &PF,SkVein::U_INT2 ** som) { for (int y=0 ; y<_ty ; y++) { Type * l = _d[y]; U_INT2 * s = som[y]; for (int x=0 ; x<_tx ; x++) { if (FlagIsSing[l[x]]) PF.pushlast(Pt(x,y)); s[x] = (l[x] != 0); } } } template <class Type> void SkVeinIm<Type>::push_extr(SkVFifo<SkVein::Pt> &PF) { for (int y=0 ; y<_ty ; y++) { Type * l = _d[y]; for (int x=0 ; x<_tx ; x++) if (FlagIsSing[l[x]]) PF.pushlast(Pt(x,y)); } } template <class Type> SkVein::INT4 SkVeinIm<Type>::calc_surf(SkVein::Pt p) { bool acons = false; INT4 som = 1; for (INT4 k=0 ; k<8 ; k++) { if ( (_dvein[p.y+v8y[k]][p.x+v8x[k]] & flag_dsym[k]) && (! (_dvein[p.y][p.x] & (1<<k))) ) { INT4 somv = calc_surf(Pt(p.x+v8x[k],p.y+v8y[k])); if (somv == -1) { _dvein[p.y][p.x] |= (U_INT1)(1<<k); acons = true; } else som += somv; } } if (acons) return -1; if ( ( som < _surf) || ((INT4)som < (INT4) (_ang * square(_d[p.y][p.x]))) ) return som; else return -1; } template <class Type> bool SkVeinIm<Type>::get_arc_sym(SkVein::INT4 x,SkVein::INT4 y) { for (ldir * l = BitsOfFlag[_d[y][x]]; l; l=l->_next) if( _d[y+l->_y][x+l->_x] & l->_flag_dsym) return true; return false; } template <class Type> void SkVeinIm<Type>::get_arc_sym(SkVFifo< SkVein::Pt> & P) { for (INT4 y=0; y<_ty ; y++) for (INT4 x=0; x<_tx ; x++) if (get_arc_sym(x,y)) P.pushlast(Pt(x,y)); } template <class Type> void SkVeinIm<Type>::isolated_points ( SkVeinIm<SkVein::U_INT1> veines, SkVFifo<SkVein::Pt3> & FGermes ) { U_INT1 ** dv = veines._d; for (int y=0 ; y<_ty ; y++) for (int x=0 ; x<_tx ; x++) if (_d[y][x] && (! dv[y][x])) { bool got8 = false; for (int k8 =0; (k8<8) && (!got8); k8++) if (_d[y+v8y[k8]][x+v8x[k8]]) got8 = true; if (! got8) FGermes.pushlast(Pt3(x,y,0)); } } template <class Type> void SkVeinIm<Type>::pruning ( SkVeinIm<SkVein::U_INT1> veines, SkVein::U_INT2 ** som, double ang, SkVein::INT4 surf, bool skgermes, SkVFifo<SkVein::Pt3> & FGermes ) { ang /= 8.0; SkVFifo<Pt> FS(4*(_tx+_ty)); // for singleton // for centers of "empty" shades SkVFifo<Pt3> FCent(_tx+_ty); if (som) veines.push_extr(FS,som); else veines.push_extr(FS); U_INT1 ** dv = veines._d; U_INT2 * sv=0; _ang = ang; _surf = surf; _dvein = veines._d; while (! FS.empty()) { Pt p = FS.getfirst(); INT4 flag = dv[p.y][p.x]; if (flag) { assert(FlagIsSing[flag]); INT4 k = UniqueBits[flag]; INT4 xv = p.x + v8x[k]; INT4 yv = p.y + v8y[k]; if (som) { sv = som[yv]+xv; *sv += som[p.y][p.x]; } U_INT1 & fv = dv[yv][xv] ; fv ^= flag_dsym[k]; // Kill arc from xv,yv to p bool suppres = true; switch(NbBitFlag[fv]) { case 1 : if (som) suppres = (*sv < surf) || (*sv < ang * square(_d[yv][xv])); if (suppres) FS.pushlast(Pt(xv,yv)); break; case 0 : FCent.pushlast(Pt3(xv,yv,k)); break; } } } if (! som) { { SkVFifo<Pt> Cycles(4 *(_tx+_ty)); veines.get_arc_sym(Cycles); while(! Cycles.empty()) calc_surf(Cycles.getfirst()); } for (int i=0 ; i<FCent.nb() ; i++) { Pt3 p = FCent[i]; calc_surf(Pt(p.x,p.y)); } } while (! FCent.empty()) { Pt3 p = FCent.getfirst(); if (! veines.get_arc_sym(p.x,p.y)) FGermes.pushlast(p); } if (skgermes) { while (! FGermes.empty()) { Pt3 p = FGermes.getfirst(); dv[p.y][p.x] |= flag_dsym[p.z]; } } } template <class Type> SkVeinIm<Type>::~SkVeinIm() { if (_free) { for (int y=_ty-1; y>=0 ; y--) { delete [] _d[y]; } delete [] _d; } }; template <class Type> void SkVeinIm<Type>::prolong_extre () { SkVFifo<Pt> F(_tx+_ty); for (INT4 y = 0; y<_ty; y++) for (INT4 x = 0; x<_tx; x++) if(FlagIsSing[_d[y][x]]) { INT4 k = UniqueBits[_d[y][x]]; if (_d[y+v8y[k]][x+v8x[k]] & flag_dsym[k]) { F.pushlast (Pt(x,y)); Pt extre = prolong_extre(x,y,k); F.pushlast (extre); } } SkVFifo<Pt3> Chem(100); while (! F.empty()) { Pt singl = F.getfirst(); Pt extr = F.getfirst(); while (extr != singl) { INT4 k = UniqueBits[_d[extr.y][extr.x]]; assert(k<8); extr =Pt(extr.x+v8x[k],extr.y+v8y[k]); Chem.pushlast(Pt3(extr.x,extr.y,k)); } while(! Chem.empty()) { Pt3 p = Chem.getfirst(); _d[p.y][p.x] |= flag_dsym[p.z]; } } } template <class Type> void SkVeinIm<Type>::prolong_extre_rec ( int x, int y, int kpere, int &nb, SkVFifo<SkVein::Pt3> &f ) { nb++; bool got4 = false; for (INT4 k4 =0; (!got4)&&(k4<4); k4++) if (_d[y+v4y[k4]][x+v4x[k4]]==0) got4 = true; bool dead_end = true; for (INT4 k8 =1; (k8<8); k8++) { int k = (k8+kpere) %8; if (_d[y+v8y[k]][x+v8x[k]] &flag_dsym[k]) { dead_end = false; prolong_extre_rec ( x+v8x[k], y+v8y[k], dir_sym[k], nb, f ); } } if (got4 && dead_end) f.pushlast(Pt3(x,y,nb)); nb++; } template <class Type> SkVein::Pt SkVeinIm<Type>::prolong_extre(int x,int y,int k) { int nb = 0; SkVFifo<Pt3> F(100); prolong_extre_rec(x,y,k,nb,F); INT4 dif_min = nb; nb /= 2; Pt res (x,y); while (! F.empty()) { Pt3 p = F.getfirst(); INT4 dif = abs(p.z-nb); if (dif < dif_min) { res = Pt(p.x,p.y); dif_min = dif; } } return res; } ResultVeinSkel VeinerizationSkeleton ( unsigned char ** result, unsigned char ** image, int tx, int ty, int surf_threshlod, double angular_threshlod, bool skel_of_disk, bool prolgt_extre, bool with_result, unsigned short ** tmp ) { bool mode_veine = (surf_threshlod<0) &&(angular_threshlod<0); SkVeinIm<unsigned char> DistSV(image,tx,ty); SkVeinIm<unsigned char> VeinSV(result,tx,ty); DistSV.d32(); DistSV.d32_veinerize(VeinSV,true); VeinSV.close_sym(); SkVFifo<SkVein::Pt3> FGermes(tx+ty); if (! mode_veine) { DistSV.pruning ( VeinSV, tmp, angular_threshlod, surf_threshlod, skel_of_disk, FGermes ); if (prolgt_extre) VeinSV.prolong_extre(); } ResultVeinSkel res; res.x = 0; res.y = 0; res.nb = 0; if (with_result) { DistSV.isolated_points(VeinSV,FGermes); res.nb = FGermes.nb(); res.x = new unsigned short [res.nb]; res.y = new unsigned short [res.nb]; for (int k=0; k< res.nb; k++) { SkVein::Pt3 p= FGermes[k]; res.x[k] = p.x; res.y[k] = p.y; } } if (! mode_veine) VeinSV.open_sym(); return res; } void freeResultVeinSkel(ResultVeinSkel * res) { if (res->x) { delete [] res->y; delete [] res->x; } res->x=0; res->y=0; res->nb = 0; } const unsigned char * NbBitsOfFlag() { return SkVein::NbBitFlag; }
24.072379
80
0.433247
[ "shape" ]
d8bc5d7011726cbff25deef4f24359af01fda16f
649
cpp
C++
leetcode/array/array_nesting.cpp
codingpotato/algorithm-cpp
793dc9e141000f48ea19c77ef0047923a7667358
[ "MIT" ]
null
null
null
leetcode/array/array_nesting.cpp
codingpotato/algorithm-cpp
793dc9e141000f48ea19c77ef0047923a7667358
[ "MIT" ]
null
null
null
leetcode/array/array_nesting.cpp
codingpotato/algorithm-cpp
793dc9e141000f48ea19c77ef0047923a7667358
[ "MIT" ]
null
null
null
#include <doctest/doctest.h> #include <vector> // 565. Array Nesting class Solution { public: int arrayNesting(std::vector<int>& nums) { auto index = 0; auto max_len = 0; auto current_len = 1; while (index < static_cast<int>(nums.size())) { if (nums[index] != index) { std::swap(nums[index], nums[nums[index]]); ++current_len; } else { max_len = std::max(max_len, current_len); current_len = 1; ++index; } } return max_len; } }; TEST_CASE("Array Nesting") { Solution s; std::vector<int> nums{5, 4, 0, 3, 1, 6, 2}; REQUIRE_EQ(s.arrayNesting(nums), 4); }
20.935484
51
0.57319
[ "vector" ]
d8c0c8517e1f42ccd9b0faf947e21ddcab208547
945
cpp
C++
convex_hull/convex_hull.cpp
ryanmcdermott/katas
d23b8c131f03e4df0a3a5268de4b63c5b35058a1
[ "MIT" ]
46
2017-06-26T15:09:10.000Z
2022-03-19T04:21:32.000Z
convex_hull/convex_hull.cpp
ryanmcdermott/katas
d23b8c131f03e4df0a3a5268de4b63c5b35058a1
[ "MIT" ]
null
null
null
convex_hull/convex_hull.cpp
ryanmcdermott/katas
d23b8c131f03e4df0a3a5268de4b63c5b35058a1
[ "MIT" ]
13
2017-10-18T05:30:18.000Z
2021-10-04T22:46:35.000Z
// Time complexity: O(m*n) // Space complexity: O(1) #include "./convex_hull.hpp" #include <vector> using std::vector; // Find orientation of Point triplet: (p, q, r) // Returns values as so: // 0: p, q and r are colinear // 1: Clockwise // 2: Counterclockwise int orientation(Point p, Point q, Point r) { // clang-format off int value = ((r.x - q.x) * (q.y - p.y)) - ((r.y - q.y) * (q.x - p.x)); // clang-format on if (value == 0) return 0; return value > 0 ? 1 : 2; } vector<Point> convex_hull(Point points[], int n) { vector<Point> hull; int l = 0; for (int i = 1; i < n; i++) { if (points[i].x < points[l].x) { l = i; } } int p; int q; p = l; do { q = (p + 1) % n; hull.push_back(points[p]); for (int i = 0; i < n; i++) { if (orientation(points[p], points[i], points[q]) == 2) { q = i; } } p = q; } while (p != l); return hull; }
17.5
62
0.506878
[ "vector" ]
d8c3a94d0aac1ecfb92af788df03935e9cab0c59
3,476
cc
C++
server.cc
maxcong001/grpcTest
545d2b24a316f4693215f0667d7ce828e2cd321f
[ "MIT" ]
null
null
null
server.cc
maxcong001/grpcTest
545d2b24a316f4693215f0667d7ce828e2cd321f
[ "MIT" ]
null
null
null
server.cc
maxcong001/grpcTest
545d2b24a316f4693215f0667d7ce828e2cd321f
[ "MIT" ]
null
null
null
#include "information.grpc.pb.h" #include <grpcpp/grpcpp.h> #include <vector> #include <mutex> #include <thread> #include <algorithm> class InfoServiceImpl final : public info::Manager::Service { public: grpc::Status AddRecord(grpc::ServerContext* context, const info::Person* person, google::protobuf::Empty* /*response*/) override { addPerson(*person); return grpc::Status::OK; } grpc::Status DeleteRecords(grpc::ServerContext* context, grpc::ServerReader<info::ReqName>* reader, google::protobuf::Empty* /*response*/) override { info::ReqName request; while(reader->Read(&request)) { auto name = request.name(); deletePerson(name); } return grpc::Status::OK; } grpc::Status GetRecordsByAge(grpc::ServerContext * context, const info::AgeRange * range, grpc::ServerWriter<info::Person> * writer) override { int min = range->minimal(); int max = range->maximal(); for(const auto & person : person_list_) { auto age = person.age(); if (age >= min && age <= max ) { writer->Write(person); } } return grpc::Status::OK; } grpc::Status GetRecordsByNames(grpc::ServerContext * context, grpc::ServerReaderWriter<info::Person, info::ReqName> * stream) override { info::ReqName request; while(stream->Read(&request)) { auto name = request.name(); for (const auto & person : person_list_) { if (person.name() == name) { stream->Write(person); } } } return grpc::Status::OK; } private: void addPerson(const info::Person & person) { std::lock_guard<std::mutex> lock(person_list_mutex_); auto iter = std::find_if(person_list_.begin(), person_list_.end(), [&person](const info::Person & internal) -> bool { return person.name() == internal.name(); }); if (iter == person_list_.end()) { person_list_.emplace_back(person); } else { *iter = person; } } void deletePerson(const std::string & name) { std::lock_guard<std::mutex> lock(person_list_mutex_); auto iter = std::find_if(person_list_.begin(), person_list_.end(), [&name](const info::Person & person) -> bool { return person.name() == name; }); if (iter != person_list_.end()) { person_list_.erase(iter); } } std::mutex person_list_mutex_; std::vector<info::Person> person_list_; }; int main() { InfoServiceImpl service; grpc::ServerBuilder builder; std::unique_ptr<grpc::Server> server; std::string address("0.0.0.0:30003"); builder.AddListeningPort(address, grpc::InsecureServerCredentials()); builder.RegisterService(&service); server = builder.BuildAndStart(); std::cout << "server started, listening on " << address << std::endl; server->Wait(); }
34.415842
109
0.516398
[ "vector" ]
d8ce6187e142c23aa12494ce037402bc0b96199d
3,804
hpp
C++
include/Main.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/Main.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/Main.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
#include "codegen/include/GlobalNamespace/BeatmapObjectManager.hpp" #include "codegen/include/GlobalNamespace/NoteData.hpp" #include "codegen/include/GlobalNamespace/NoteJump.hpp" #include "codegen/include/GlobalNamespace/NoteType.hpp" #include "codegen/include/GlobalNamespace/AudioTimeSyncController.hpp" #include "codegen/include/GlobalNamespace/NoteMovement.hpp" #include "codegen/include/GlobalNamespace/PlayerController.hpp" #include "codegen/include/GlobalNamespace/NoteBasicCutInfo.hpp" #include "codegen/include/GlobalNamespace/SaberType.hpp" #include "codegen/include/GlobalNamespace/INoteController.hpp" #include "codegen/include/GlobalNamespace/NoteCutInfo.hpp" #include "codegen/include/GlobalNamespace/Saber.hpp" #include "codegen/include/GlobalNamespace/NoteCutEffectSpawner.hpp" #include "codegen/include/GlobalNamespace/FlyingObjectEffect.hpp" #include "codegen/include/GlobalNamespace/MainMenuViewController.hpp" #include "codegen/include/GlobalNamespace/SaberClashChecker.hpp" #include "codegen/include/GlobalNamespace/SaberBurnMarkArea.hpp" #include "codegen/include/GlobalNamespace/SaberBurnMarkSparkles.hpp" #include "codegen/include/GlobalNamespace/GameEnergyCounter.hpp" #include "codegen/include/Xft/XWeaponTrail.hpp" #include "codegen/include/GlobalNamespace/XWeaponTrailRenderer.hpp" #include "codegen/include/OnlineServices/LevelScoreUploader.hpp" #include "codegen/include/OnlineServices/LevelScoreResultsData.hpp" #include "codegen/include/UnityEngine/Vector3.hpp" #include "codegen/include/UnityEngine/Mathf.hpp" #include "codegen/include/UnityEngine/Transform.hpp" #include "codegen/include/UnityEngine/Resources.hpp" #include "codegen/include/UnityEngine/Space.hpp" #include "codegen/include/UnityEngine/AudioSource.hpp" #include "codegen/include/UnityEngine/GameObject.hpp" #include "codegen/include/UnityEngine/Object.hpp" #include "codegen/include/UnityEngine/MeshFilter.hpp" #include "codegen/include/UnityEngine/UI/Button.hpp" #include "codegen/include/TMPro/TextMeshProUGUI.hpp" #include "codegen/include/Polyglot/LocalizedTextMeshProUGUI.hpp" #include "codegen/include/HMUI/ViewController.hpp" #include "codegen/include/HMUI/ViewController_ActivationType.hpp" #include "../extern/bs-utils/shared/utils.hpp" #include <unordered_set> // specific types that you might want here // Any beatsaber-hook specific includes here #include "../extern/beatsaber-hook/shared/utils/utils.h" #include "../extern/beatsaber-hook/shared/utils/logging.hpp" // For displaying modloader information (ex: Modloader.getInfo().name) #include "../extern/modloader/shared/modloader.hpp" // For using il2cpp_utils:: methods #include "../extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" // For using il2cpp_functions:: methods #include "../extern/beatsaber-hook/shared/utils/il2cpp-functions.hpp" // For using commonly used types (such as Vector2, UnityEngine::Vector3, Color, Scene, etc.) #include "../extern/beatsaber-hook/shared/utils/typedefs.h" // For using configuration #include "../extern/beatsaber-hook/shared/config/config-utils.hpp" #include <stdlib.h> static ModInfo modInfo; static Configuration& getConfig() { static Configuration config(modInfo); return config; } static const Logger& getLogger() { static const Logger logger(modInfo); return logger; } static struct Config_t { bool parabola = false; float parabolaOffsetY = 1.8000000000f; bool noBlue = false; bool noRed = false; bool redToBlue = false; bool blueToRed = false; bool Vaccum = false; bool Centering = false; bool BoxingMode = false; bool SuperHot = true; bool Headbang = false; bool RotateController180 = false; bool HideSabers = false; bool HideSaberEffects = false; } Config; extern void SaveConfig(); extern bool LoadConfig();
39.625
92
0.79837
[ "object", "transform" ]
d8d229419a635e45571a5ecb2fd2a1fd3c5c3483
403
cpp
C++
C++/0944-Delete-Columns-to-Make-Sorted/soln.cpp
wyaadarsh/LeetCode-Solutions
3719f5cb059eefd66b83eb8ae990652f4b7fd124
[ "MIT" ]
5
2020-07-24T17:48:59.000Z
2020-12-21T05:56:00.000Z
C++/0944-Delete-Columns-to-Make-Sorted/soln.cpp
zhangyaqi1989/LeetCode-Solutions
2655a1ffc8678ad1de6c24295071308a18c5dc6e
[ "MIT" ]
null
null
null
C++/0944-Delete-Columns-to-Make-Sorted/soln.cpp
zhangyaqi1989/LeetCode-Solutions
2655a1ffc8678ad1de6c24295071308a18c5dc6e
[ "MIT" ]
2
2020-07-24T17:49:01.000Z
2020-08-31T19:57:35.000Z
class Solution { public: int minDeletionSize(vector<string>& A) { int nwords = A.size(), len = A[0].size(); int ans = 0; for (int i = 0; i < len; ++i) { for(int j = 0; j < nwords - 1; ++j) { if (A[j + 1][i] < A[j][i]) { ans += 1; break; } } } return ans; } };
25.1875
49
0.33995
[ "vector" ]
d8d31349e29dde330b1b36f79e04dbb2fc631da8
556
cpp
C++
001_GFG/Data-Structures-And-Algorithms-Self-Paced/0020_Dynamic_Programming/003_print_fibo_vector.cpp
Sahil1515/coding
2bd2a2257c8cac5a5c00b37e79bbb68a24e186d4
[ "RSA-MD" ]
null
null
null
001_GFG/Data-Structures-And-Algorithms-Self-Paced/0020_Dynamic_Programming/003_print_fibo_vector.cpp
Sahil1515/coding
2bd2a2257c8cac5a5c00b37e79bbb68a24e186d4
[ "RSA-MD" ]
null
null
null
001_GFG/Data-Structures-And-Algorithms-Self-Paced/0020_Dynamic_Programming/003_print_fibo_vector.cpp
Sahil1515/coding
2bd2a2257c8cac5a5c00b37e79bbb68a24e186d4
[ "RSA-MD" ]
null
null
null
// vector<long long> printFibb(int n) { // vector<long long> fibo; // fibo.reserve(n); // if(n==0) // return fibo; // fibo.push_back(1); // if(n==1) // return fibo; // fibo.push_back(1); // for(int i=2;i<n;i++) // { // fibo.push_back(fibo[i-1]+fibo[i-2]); // } // return fibo; // } #include<bits/stdc++.h> using namespace std; int main() { long long int n; cin>>n; if(n%2==1 || n<=2) cout<<"NO"; else cout<<"YES"; return 0; }
13.560976
47
0.442446
[ "vector" ]
d8da95f73aa89164f7ac30fa05c3afd4a903218a
955
hpp
C++
libfma/include/fma/interpret/CallStack.hpp
BenjaminSchulte/fma
df2aa5b0644c75dd34a92defeff9beaa4a32ffea
[ "MIT" ]
14
2018-01-25T10:31:05.000Z
2022-02-19T13:08:11.000Z
libfma/include/fma/interpret/CallStack.hpp
BenjaminSchulte/fma
df2aa5b0644c75dd34a92defeff9beaa4a32ffea
[ "MIT" ]
1
2020-12-24T10:10:28.000Z
2020-12-24T10:10:28.000Z
libfma/include/fma/interpret/CallStack.hpp
BenjaminSchulte/fma
df2aa5b0644c75dd34a92defeff9beaa4a32ffea
[ "MIT" ]
null
null
null
#ifndef __FMA_INTERPRET_CALLSTACK_H__ #define __FMA_INTERPRET_CALLSTACK_H__ #include <vector> #include <memory> #include <fma/Reference.hpp> namespace FMA { namespace interpret { struct CallStackItem { CallStackItem(const CodeReference &ref) : ref(ref) {} CodeReference ref; }; typedef std::vector<CallStackItem> CallStackItemList; class CallStack; struct CallStackContext { CallStackContext(CallStack &stack) : stack(stack) {} ~CallStackContext(); protected: CallStack &stack; }; typedef std::shared_ptr<CallStackContext> CallStackContextPtr; class CallStack { public: CallStack() {} ~CallStack() {} inline CallStackContextPtr enter(const CodeReference &ref) { stack.push_back(CallStackItem(ref)); return CallStackContextPtr(new CallStackContext(*this)); } inline void leave() { stack.pop_back(); } inline CallStackItemList &all() { return stack; } protected: CallStackItemList stack; }; } } #endif
17.053571
62
0.740314
[ "vector" ]
d8dc94033d64d846fa0dd73c32d0ee99f9fd020f
1,577
cpp
C++
torchshapelets/src/discrepancies.cpp
patrick-kidger/generalised_shapelets
04930c89dc4673e2af402895fe67655f8375a808
[ "MIT" ]
32
2020-05-31T17:41:58.000Z
2022-03-28T18:38:11.000Z
torchshapelets/src/discrepancies.cpp
patrick-kidger/generalised_shapelets
04930c89dc4673e2af402895fe67655f8375a808
[ "MIT" ]
1
2022-02-09T22:13:03.000Z
2022-02-09T23:55:28.000Z
torchshapelets/src/discrepancies.cpp
patrick-kidger/generalised_shapelets
04930c89dc4673e2af402895fe67655f8375a808
[ "MIT" ]
9
2020-07-17T16:50:24.000Z
2021-12-13T11:29:12.000Z
#include <torch/extension.h> #include <cstdint> // int64_t #include <functional> // std::function #include "discrepancies.hpp" namespace torchshapelets { torch::Tensor l2_discrepancy(torch::Tensor times, torch::Tensor path1, torch::Tensor path2, torch::Tensor linear) { // times has shape (length,) // path1 and path2 have shape (..., length, channels) // linear has shape (channels, channels), or should just be passed as an empty Tensor(). auto path = path1 - path2; if (linear.ndimension() == 2) { path = torch::matmul(path, linear); } else if (linear.ndimension() == 1) { path = path * linear; } auto length = path.size(-2) - 1; auto next_path = path.narrow(/*dim=*/-2, /*start=*/1, /*length=*/length); auto prev_path = path.narrow(/*dim=*/-2, /*start=*/0, /*length=*/length); auto next_times = times.narrow(/*dim=*/0, /*start=*/1, /*length=*/length); auto prev_times = times.narrow(/*dim=*/0, /*start=*/0, /*length=*/length); auto first_term = (next_path - prev_path).pow(2).sum(/*dim=*/-1) / 3; // sum down channel dim auto second_term = (next_path * prev_path).sum(/*dim=*/-1); // sum down channel dim auto combine = (first_term + second_term) * (next_times - prev_times); auto out = combine.sum(/*dim=*/-1); // sum down length dim return out.relu().sqrt(); // Just in case floating point errors could result in something slightly negative here? } } // namespace torchshapelets
43.805556
122
0.601141
[ "shape" ]
d8ea37fde93ab906f85089d7d02c5ec3f3d4b76f
1,580
hpp
C++
time_independent/include/stn.hpp
Kei18/time-independent-planning
8540a2fa836f077406cbca7f6e442fdd7d2f840b
[ "MIT" ]
6
2021-02-01T07:51:30.000Z
2021-12-22T12:52:00.000Z
time_independent/include/stn.hpp
nobodyczcz/time-independent-planning
92ec87de867e1f190c0c80a66c4a410a12da4821
[ "MIT" ]
null
null
null
time_independent/include/stn.hpp
nobodyczcz/time-independent-planning
92ec87de867e1f190c0c80a66c4a410a12da4821
[ "MIT" ]
2
2021-06-20T05:41:28.000Z
2021-09-14T13:19:51.000Z
/* * Simple Temporal Network * * used to convert time-independent planning to MAPF execution * * ref * Hönig, W., Kumar, T. S., Cohen, L., Ma, H., Xu, H., Ayanian, N., & Koenig, S. (2016, June). * Multi-Agent Path Finding with Kinematic Constraints. * In ICAPS (Vol. 16, pp. 477-485). */ #pragma once #include "agent.hpp" #include <unordered_map> struct Event; using Events = std::vector<Event*>; using Realization = std::vector<Events>; struct Event { int id; // event id int t; // timestep State* s; // agent's state Events parents; // parents, i.e., temporal dependencies Event* earliest; // used when finding minimum path }; class STN { private: Graph* G; // graph Agents A; // agents int elapsed; // time (ms) int cnt_id; // used for event id Event* XF; // initial events Realization realization; // MAPF execution // register all events std::unordered_map<int, Event*> event_table; // distance to the initial event std::unordered_map<int, int> event_dists; void createDiagram(); // create space-time diagram int getTimestep(Event* e); // get earliest timestep int getDist(Event* e); // recursive func, used in getTimestep void findRealization(); // get MAPF execution static int edgeWeight(Event* child, Event* parent); // used in getDist static Events getLocalExec(Event* last_event); static Events getLocalExecPos(Event* last_event); public: STN(Graph* G, Agents _A); ~STN(); int getMakespan(); int getSOC(); std::string strMAPFExecution(); };
26.779661
94
0.660127
[ "vector" ]
2b033b048ff4e38c853874605c57f8a89b6a3bb1
699
cpp
C++
leetcode/890. Find and Replace Pattern.cpp
chamow97/Interview-Prep
9ce13afef6090b1604f72bf5f80a6e1df65be24f
[ "MIT" ]
1
2018-09-13T12:16:42.000Z
2018-09-13T12:16:42.000Z
leetcode/890. Find and Replace Pattern.cpp
chamow97/Interview-Prep
9ce13afef6090b1604f72bf5f80a6e1df65be24f
[ "MIT" ]
null
null
null
leetcode/890. Find and Replace Pattern.cpp
chamow97/Interview-Prep
9ce13afef6090b1604f72bf5f80a6e1df65be24f
[ "MIT" ]
null
null
null
class Solution { public: string patternize(string str) { unordered_map<char, string> m; int curr = 11; string pattern = ""; for(auto i : str) { if(m.find(i) == m.end()) { m[i] = (to_string(curr)); curr++; } pattern += (m[i] + "|"); } return pattern; } vector<string> findAndReplacePattern(vector<string>& words, string pattern) { string output = patternize(pattern); vector<string> result; for(auto i : words) { if(patternize(i) == output) { result.push_back(i); } } return result; } };
25.888889
81
0.463519
[ "vector" ]
2b0dfc13a0acd99016554485bf390009bef10a80
1,111
cpp
C++
LeetCodeCPP/_1042. Flower Planting With No Adjacent/main.cpp
18600130137/leetcode
fd2dc72c0b85da50269732f0fcf91326c4787d3a
[ "Apache-2.0" ]
1
2019-03-29T03:33:56.000Z
2019-03-29T03:33:56.000Z
LeetCodeCPP/_1042. Flower Planting With No Adjacent/main.cpp
18600130137/leetcode
fd2dc72c0b85da50269732f0fcf91326c4787d3a
[ "Apache-2.0" ]
null
null
null
LeetCodeCPP/_1042. Flower Planting With No Adjacent/main.cpp
18600130137/leetcode
fd2dc72c0b85da50269732f0fcf91326c4787d3a
[ "Apache-2.0" ]
null
null
null
// // main.cpp // _1042. Flower Planting With No Adjacent // // Created by admin on 2019/5/13. // Copyright © 2019年 liu. All rights reserved. // #include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> gardenNoAdj(int N, vector<vector<int>>& paths) { vector<vector<int>> helper(N); for(auto p:paths){ helper[p[0]-1].push_back(p[1]-1); helper[p[1]-1].push_back(p[0]-1); } vector<int> ret(N,0); for(int i=0;i<N;i++){ vector<bool> status(5,false); for(auto j:helper[i]){ status[ret[j]]=true; } for(int j=1;j<=4;j++){ if(!status[j]){ ret[i]=j; break; } } } return ret; } }; int main(int argc, const char * argv[]) { vector<vector<int>> input={{1,2},{3,4}}; Solution so=Solution(); vector<int> ret=so.gardenNoAdj(4, input); for(auto r:ret){ cout<<r<<" "; } cout<<endl; return 0; }
22.22
64
0.475248
[ "vector" ]
2b1641d905d20d7a799b8093b7a279e03b67808a
6,830
hpp
C++
src/libraries/core/interpolation/surfaceInterpolation/schemes/CentredFitScheme/CentredFitScheme.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/interpolation/surfaceInterpolation/schemes/CentredFitScheme/CentredFitScheme.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/interpolation/surfaceInterpolation/schemes/CentredFitScheme/CentredFitScheme.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) 2011 OpenFOAM Foundation ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>. Class CML::CentredFitScheme Description Centred fit surface interpolation scheme which applies an explicit correction to linear. \*---------------------------------------------------------------------------*/ #ifndef CentredFitScheme_H #define CentredFitScheme_H #include "CentredFitData.hpp" #include "linear.hpp" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace CML { /*---------------------------------------------------------------------------*\ Class CentredFitScheme Declaration \*---------------------------------------------------------------------------*/ template<class Type, class Polynomial, class Stencil> class CentredFitScheme : public linear<Type> { // Private Data //- Factor the fit is allowed to deviate from linear. // This limits the amount of high-order correction and increases // stability on bad meshes const scalar linearLimitFactor_; //- Weights for central stencil const scalar centralWeight_; // Private Member Functions //- Disallow default bitwise copy construct CentredFitScheme(const CentredFitScheme&); //- Disallow default bitwise assignment void operator=(const CentredFitScheme&); public: //- Runtime type information TypeName("CentredFitScheme"); // Constructors //- Construct from mesh and Istream CentredFitScheme(const fvMesh& mesh, Istream& is) : linear<Type>(mesh), linearLimitFactor_(readScalar(is)), centralWeight_(1000) {} //- Construct from mesh, faceFlux and Istream CentredFitScheme ( const fvMesh& mesh, const surfaceScalarField& faceFlux, Istream& is ) : linear<Type>(mesh), linearLimitFactor_(readScalar(is)), centralWeight_(1000) {} // Member Functions //- Return true if this scheme uses an explicit correction virtual bool corrected() const { return true; } //- Return the explicit correction to the face-interpolate virtual tmp<GeometricField<Type, fvsPatchField, surfaceMesh> > correction ( const GeometricField<Type, fvPatchField, volMesh>& vf ) const { const fvMesh& mesh = this->mesh(); const extendedCentredCellToFaceStencil& stencil = Stencil::New ( mesh ); const CentredFitData<Polynomial>& cfd = CentredFitData<Polynomial>::New ( mesh, stencil, linearLimitFactor_, centralWeight_ ); const List<scalarList>& f = cfd.coeffs(); return stencil.weightedSum(vf, f); } }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace CML // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // Add the patch constructor functions to the hash tables #define makeCentredFitSurfaceInterpolationTypeScheme\ ( \ SS, \ POLYNOMIAL, \ STENCIL, \ TYPE \ ) \ \ typedef CentredFitScheme<TYPE, POLYNOMIAL, STENCIL> \ CentredFitScheme##TYPE##POLYNOMIAL##STENCIL##_; \ defineTemplateTypeNameAndDebugWithName \ (CentredFitScheme##TYPE##POLYNOMIAL##STENCIL##_, #SS, 0); \ \ surfaceInterpolationScheme<TYPE>::addMeshConstructorToTable \ <CentredFitScheme<TYPE, POLYNOMIAL, STENCIL> > \ add##SS##STENCIL##TYPE##MeshConstructorToTable_; \ \ surfaceInterpolationScheme<TYPE>::addMeshFluxConstructorToTable \ <CentredFitScheme<TYPE, POLYNOMIAL, STENCIL> > \ add##SS##STENCIL##TYPE##MeshFluxConstructorToTable_; #define makeCentredFitSurfaceInterpolationScheme(SS, POLYNOMIAL, STENCIL) \ \ makeCentredFitSurfaceInterpolationTypeScheme(SS,POLYNOMIAL,STENCIL,scalar) \ makeCentredFitSurfaceInterpolationTypeScheme(SS,POLYNOMIAL,STENCIL,vector) \ makeCentredFitSurfaceInterpolationTypeScheme \ ( \ SS, \ POLYNOMIAL, \ STENCIL, \ sphericalTensor \ ) \ makeCentredFitSurfaceInterpolationTypeScheme(SS,POLYNOMIAL,STENCIL,symmTensor)\ makeCentredFitSurfaceInterpolationTypeScheme(SS,POLYNOMIAL,STENCIL,tensor) // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
36.524064
79
0.448463
[ "mesh", "vector" ]
2b29ca9d6f9efbea3d0b38d18bf61a2525a4e6d1
4,716
cpp
C++
benchmarks/ovs/verif_ovs_list_test.cpp
Nic30/pclass-vectorized
33bc92c66f717896fb48bd5c382729f8c76bc882
[ "MIT" ]
1
2020-07-14T17:24:33.000Z
2020-07-14T17:24:33.000Z
benchmarks/ovs/verif_ovs_list_test.cpp
Nic30/pclass-vectorized
33bc92c66f717896fb48bd5c382729f8c76bc882
[ "MIT" ]
14
2019-03-14T09:24:37.000Z
2019-12-19T17:44:21.000Z
benchmarks/ovs/verif_ovs_list_test.cpp
Nic30/pclass-vectorized
33bc92c66f717896fb48bd5c382729f8c76bc882
[ "MIT" ]
null
null
null
#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE pcv_test #include "test_common.h" #include <limits> #include <vector> #include <pcv/partition_sort/b_tree.h> #include <pcv/partition_sort/b_tree_search.h> #include <pcv/partition_sort/b_tree_insert.h> #include <pcv/partition_sort/b_tree_remove.h> #include <pcv/partition_sort/b_tree_to_rules.h> #include <pcv/partition_sort/b_tree_impl.h> #include <pcv/partition_sort/rule_value_int.h> #include <pcv/rule_parser/classbench_rule_parser.h> #include <pcv/rule_parser/trace_tools.h> #include <pcv/partition_sort/partition_sort_classifier.h> #include <pcv/utils/benchmark_common.h> #include <pcv/rule_parser/rule.h> #include "../list/list_classifier.h" #include "ovs_wrap.h" #include "ovs_api/classifier-private.h" #include "ovs_api/struct_flow_conversions.h" BOOST_AUTO_TEST_SUITE(pcv__testsuite) using namespace std; using namespace pcv; using namespace pcv::rule_conv_fn; using namespace pcv::ovs; void init_cls_from_file(OvsWrap & cls, const std::string & ruleset_file_name) { auto _rules = parse_ruleset_file(ruleset_file_name); for (auto _r : _rules) { auto r = reinterpret_cast<Rule_Ipv4_ACL*>(_r.first); cls.insert(*r, _r.second); } } void check_matches_rule(OvsWrap & cls, packet_t & _p, struct cls_rule* rule) { struct flow p = OvsWrap::flow_from_packet(_p); auto res = cls.search(p); BOOST_CHECK_EQUAL(res, rule); // auto r = cls.flow_to_Rule_Ipv4_ACL(p); // auto r_i = distance(cls.ovs_rules.begin(), // std::find(cls.ovs_rules.begin(), cls.ovs_rules.end(), res) // ); // std::cout << r_i << "> " << r << std::endl; } size_t index_of_name(const std::string &elm) { auto & arr = struct_flow_packet_names; auto it = std::find(arr.begin(), arr.end(), elm); assert(it != arr.end()); return distance(arr.begin(), it); } void rule_formater(std::ofstream & str, const Classifier::rule_spec_t & _r) { //auto _r = OvsWrap::flow_to_Rule_Ipv4_ACL(r); Rule_Ipv4_ACL r; auto a = &_r.first[0]; //size_t i = index_of_name("nw_src-2"); //vec_build::pop_32be(r.sip, i, a); // //i = index_of_name("nw_dst-2"); //vec_build::pop_32be(r.dip, i, a); // //i = index_of_name("tp_src"); //vec_build::pop_16be(r.sport, i, a); // //i = index_of_name("tp_dst"); //vec_build::pop_16be(r.dport, i , a); // //i = index_of_name("nw_proto"); //r.proto = a[i]; str << r; } void dump_trees(const OvsWrap & _cls) { auto & cls = static_cast<const classifier_priv*>(_cls.cls.priv)->cls; size_t tree_i = 0; for (auto & t : cls.trees) { if (t->rules.size()) { { std::ofstream of; of.exceptions(std::ofstream::failbit | std::ofstream::badbit); of.open(string("dump/tree_") + to_string(tree_i) + ".dot"); of << t->tree; of.close(); } { ofstream of(string("dump/tree_") + to_string(tree_i) + ".txt", ofstream::out); std::vector<Classifier::rule_spec_t> tmp; BTree::ToRules tc(t->tree, tmp); tc.to_rules(); for (auto d: t->tree.dimension_order) of << unsigned(d) << ": " << struct_flow_packet_names[d] << " "; of << endl; for (const auto & r : tmp) { rule_formater(of, r); of << std::endl; } of.close(); } } tree_i++; } } BOOST_AUTO_TEST_CASE( basic_simple1_3 ) { // @0.0.0.1/32 0.0.0.0/32 0 : 65535 0 : 65535 0x00/0xFF // @0.0.1.0/32 0.0.0.0/32 0 : 65535 0 : 65535 0x00/0xFF // @0.1.0.0/32 0.0.0.0/32 0 : 65535 0 : 65535 0x00/0xFF OvsWrap cls; init_cls_from_file(cls, "tests/data/simple1_3"); std::vector<packet_t> _packets = { { 0x0000, 0x0100, 0, 0, 0, 0, 0 }, { 0x0000, 0x0001, 0, 0, 0, 0, 0 }, { 0x0100, 0x0000, 0, 0, 0, 0, 0 }, }; for (size_t i = 0; i < _packets.size(); i++) { check_matches_rule(cls, _packets[i], cls.ovs_rules[i]); } { packet_t p_invalid = { 0x0001, 0x0000, 0, 0, 0, 0, 0 }; check_matches_rule(cls, p_invalid, nullptr); } dump_trees(cls); } BOOST_AUTO_TEST_CASE( basic_simple2_3 ) { // @0.0.0.1/32 0.0.0.0/32 0 : 65535 0 : 65535 0x00/0xFF // @0.0.1.0/24 0.0.0.0/32 0 : 65535 0 : 65535 0x00/0xFF // @0.1.0.0/16 0.0.0.0/32 0 : 65535 0 : 65535 0x00/0xFF OvsWrap cls; init_cls_from_file(cls, "tests/data/simple2_3"); std::vector<std::pair<packet_t, size_t>> _packets = { {{ 0x0000, 0x0100, 0, 0, 0, 0, 0 }, 0}, {{ 0x0000, 0x0100, 0, 0, 0, 12, 0 }, 0}, {{ 0x0000, 0x0100, 0, 0, 12, 0, 0 }, 0}, {{ 0x0000, 0x0001, 0, 0, 0, 0, 0 }, 1}, {{ 0x0000, 0x0101, 0, 0, 0, 0, 0 }, 1}, {{ 0x0000, 0x0901, 0, 0, 12, 0, 0 }, 1}, {{ 0x0100, 0x0000, 0, 0, 0, 0, 0 }, 2}, {{ 0x0100, 0x1234, 0, 0, 0, 0, 0 }, 2}, }; for (auto & p: _packets) { check_matches_rule(cls, p.first, cls.ovs_rules[p.second]); } //dump_trees(cls); } BOOST_AUTO_TEST_SUITE_END()
29.291925
79
0.649915
[ "vector" ]
1a7ea8d9db25f45b204882e926e77d70d3f09c6c
5,608
cpp
C++
nucleus/library/application/hoople_service.cpp
fredhamster/feisty_meow
66dc4221dc485a5cf9e28b724fe36268e8843043
[ "Apache-2.0" ]
2
2019-01-22T23:34:37.000Z
2021-10-31T15:44:15.000Z
nucleus/library/application/hoople_service.cpp
fredhamster/feisty_meow
66dc4221dc485a5cf9e28b724fe36268e8843043
[ "Apache-2.0" ]
2
2020-06-01T16:35:46.000Z
2021-10-05T21:02:09.000Z
nucleus/library/application/hoople_service.cpp
fredhamster/feisty_meow
66dc4221dc485a5cf9e28b724fe36268e8843043
[ "Apache-2.0" ]
null
null
null
////////////// // Name : hoople_service // Author : Chris Koeritz ////////////// // Copyright (c) 2000-$now By Author. 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: // http://www.gnu.org/licenses/gpl.html // or under the terms of the GNU Library license: // http://www.gnu.org/licenses/lgpl.html // at your preference. Those licenses describe your legal rights to this // software, and no other rights or warranties apply. // Please send updates for this code to: fred@gruntose.com -- Thanks, fred. ////////////// #include "hoople_service.h" #include <basis/array.h> #include <basis/mutex.h> #include <filesystem/filename.h> #include <loggers/program_wide_logger.h> #include <loggers/critical_events.h> #include <processes/process_control.h> #include <processes/process_entry.h> #include <structures/set.h> #include <structures/static_memory_gremlin.h> #include <timely/time_control.h> #include <timely/time_stamp.h> #include <timely/timer_driver.h> #include <signal.h> using namespace basis; using namespace filesystem; using namespace loggers; using namespace processes; using namespace structures; using namespace timely; //#define DEBUG_HOOPLE_SERVICE // uncomment for noisy version. #undef LOG #define LOG(s) CLASS_EMERGENCY_LOG(program_wide_logger::get(), s) namespace application { ////////////// SAFE_STATIC(astring, hoople_service::_app_name, ) bool &hoople_service::_defunct() { static bool _defu = false; return _defu; } bool &hoople_service::_saw_interrupt() { static bool _saw = false; return _saw; } int &hoople_service::_timer_period() { static int _tim = 0; return _tim; } ////////////// static hoople_service *_global_hoople_service = NULL_POINTER; // this static object is set by the setup() method. it should only come // into existence once during a program's lifetime. hoople_service::hoople_service() { } hoople_service::~hoople_service() { make_defunct(); if (_global_hoople_service) { program_wide_timer().zap_timer(_global_hoople_service); } } void hoople_service::handle_startup() { /* nothing for base class. */ } void hoople_service::handle_shutdown() { /* nothing for base class. */ } void hoople_service::handle_timer() { /* nothing for base class. */ } void hoople_service::handle_timer_callback() { // don't invoke the user's timer unless the object is still alive. if (!is_defunct()) handle_timer(); } void hoople_service::close_this_program() { make_defunct(); } bool hoople_service::close_application(const astring &app_name) { FUNCDEF("close_application"); process_entry_array procs; process_control querier; // lookup process ids of apps. bool got_list = querier.query_processes(procs); if (!got_list) { LOG(astring("couldn't get process list.")); return false; } int_set pids; got_list = querier.find_process_in_list(procs, app_name, pids); if (!got_list) { LOG(astring("couldn't find process in the list of active ones.")); return true; } // zap all of them using our signal. for (int i = 0; i < pids.length(); i++) { //would linux be better served with sigterm also? #ifndef _MSC_VER kill(pids[i], SIGHUP); #else //lame--goes to whole program. raise(SIGTERM); #endif //hmmm: check results... } return true; } void hoople_service::handle_OS_signal(int formal(sig_id)) { _saw_interrupt() = true; // save the status. if (_global_hoople_service) { _global_hoople_service->close_this_program(); } } void hoople_service::make_defunct() { _defunct() = true; } bool hoople_service::setup(const astring &app_name, int timer_period) { //hmmm: make sure not already initted. // simple initializations first... _timer_period() = timer_period; _app_name() = app_name; _global_hoople_service = this; // setup signal handler for HUP signal. this is the one used to tell us // to leave. #ifndef _MSC_VER signal(SIGHUP, handle_OS_signal); #endif // setup a handler for interrupt (e.g. ctrl-C) also. signal(SIGINT, handle_OS_signal); #ifdef _MSC_VER signal(SIGBREAK, handle_OS_signal); #endif return true; } bool hoople_service::launch_console(hoople_service &alert, const astring &app_name, int timer_period) { #ifdef DEBUG_HOOPLE_SERVICE FUNCDEF("launch_console"); #endif if (!alert.setup(app_name, timer_period)) return false; alert.handle_startup(); // tell the program it has started up. // start a timer if they requested one. if (_timer_period()) { program_wide_timer().set_timer(_timer_period(), &alert); } #ifdef DEBUG_HOOPLE_SERVICE time_stamp next_report(10 * SECOND_ms); #endif while (!alert.is_defunct()) { #ifdef DEBUG_HOOPLE_SERVICE if (time_stamp() >= next_report) { printf("%s: shout out from my main thread yo.\n", _global_argv[0]); next_report.reset(10 * SECOND_ms); } #endif time_control::sleep_ms(42); } alert.handle_shutdown(); return true; } /* #ifdef __WIN32__ bool hoople_service::launch_event_loop(hoople_service &alert, const astring &app_name, int timer_period) { if (!alert.setup(app_name, timer_period)) return false; alert.handle_startup(); if (timer_period) program_wide_timer().set_timer(timer_period, this); MSG msg; msg.hwnd = 0; msg.message = 0; msg.wParam = 0; msg.lParam = 0; while (!alert.is_defunct() && (GetMessage(&msg, NULL_POINTER, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } alert.handle_shutdown(); return true; } #endif */ } //namespace.
25.035714
77
0.713802
[ "object" ]
1a847195caadbf7254cfb27cecaa84820e4bb08d
655
cpp
C++
InterviewBit/Two Pointers/3_sum.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
InterviewBit/Two Pointers/3_sum.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
InterviewBit/Two Pointers/3_sum.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
// https://www.interviewbit.com/problems/3-sum/ int Solution::threeSumClosest(vector<int> &A, int B) { int n = A.size(); int minDiff = INT_MAX; int bestSum = 0; sort(A.begin(), A.end()); for(int i=0;i<n-2;i++) { int j=i+1; int k=n-1; while(j<k) { int sum = A[i]+A[j]+A[k]; if(minDiff > abs(sum-B)) { minDiff = abs(sum-B); bestSum = sum; } if(sum==B) return bestSum; else if(sum > B) k--; else j++; } } return bestSum; }
21.129032
54
0.392366
[ "vector" ]
1a8bdcc18fde7f8de2778be5ec3b0517bf284512
6,976
cc
C++
compy/representations/extractors/clang_ast/clang_graph_frontendaction.cc
AndersonFaustino/compy-learn
24a394bd1ddc109a37b348c3de440389fa9a1f23
[ "Apache-2.0" ]
12
2020-09-17T07:57:13.000Z
2022-03-16T03:42:58.000Z
compy/representations/extractors/clang_ast/clang_graph_frontendaction.cc
bennofs/compy-learn
b8674e2c59a2abca98d9e2a3d49e073ca3ae91af
[ "Apache-2.0" ]
11
2020-10-26T09:39:11.000Z
2021-12-04T18:31:25.000Z
compy/representations/extractors/clang_ast/clang_graph_frontendaction.cc
bennofs/compy-learn
b8674e2c59a2abca98d9e2a3d49e073ca3ae91af
[ "Apache-2.0" ]
10
2020-12-30T18:06:04.000Z
2022-02-25T00:11:57.000Z
#include "clang_graph_frontendaction.h" #include <exception> #include <iostream> #include <utility> #include "clang/AST/ASTConsumer.h" #include "clang/AST/Decl.h" #include "clang/Analysis/CFG.h" #include "clang/Frontend/ASTConsumers.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/MultiplexConsumer.h" #include "clang/StaticAnalyzer/Core/Checker.h" #include "llvm/Support/raw_ostream.h" using namespace ::clang; using namespace ::llvm; namespace compy { namespace clang { namespace graph { bool ExtractorASTVisitor::VisitStmt(Stmt *s) { // Collect child stmts std::vector<OperandInfoPtr> ast_relations; for (auto it : s->children()) { if (it) { StmtInfoPtr childInfo = getInfo(*it); ast_relations.push_back(childInfo); } } if (auto *ds = dyn_cast<DeclStmt>(s)) { for (const Decl *decl : ds->decls()) { ast_relations.push_back(getInfo(*decl, false)); } } StmtInfoPtr info = getInfo(*s); info->ast_relations.insert(info->ast_relations.end(), ast_relations.begin(), ast_relations.end()); return RecursiveASTVisitor<ExtractorASTVisitor>::VisitStmt(s); } bool ExtractorASTVisitor::VisitFunctionDecl(FunctionDecl *f) { // Only proceed on function definitions, not declarations. Otherwise, all // function declarations in headers are traversed also. if (!f->hasBody() || !f->getDeclName().isIdentifier()) { // throw away the tokens tokenQueue_.popTokensForRange(f->getSourceRange()); return true; } // ::llvm::errs() << f->getNameAsString() << "\n"; FunctionInfoPtr functionInfo = getInfo(*f); extractionInfo_->functionInfos.push_back(functionInfo); // Add entry stmt. functionInfo->entryStmt = getInfo(*f->getBody()); // Add args. for (auto it : f->parameters()) { functionInfo->args.push_back(getInfo(*it, true)); } // Dump CFG. std::unique_ptr<CFG> cfg = CFG::buildCFG(f, f->getBody(), &context_, CFG::BuildOptions()); // cfg->dump(LangOptions(), true); // Create CFG Blocks. for (CFG::iterator it = cfg->begin(), Eb = cfg->end(); it != Eb; ++it) { CFGBlock *B = *it; functionInfo->cfgBlocks.push_back(getInfo(*B)); } return RecursiveASTVisitor<ExtractorASTVisitor>::VisitFunctionDecl(f); } CFGBlockInfoPtr ExtractorASTVisitor::getInfo(const ::clang::CFGBlock &block) { auto it = cfgBlockInfos_.find(&block); if (it != cfgBlockInfos_.end()) return it->second; CFGBlockInfoPtr info(new CFGBlockInfo); cfgBlockInfos_[&block] = info; // Collect name. info->name = "cfg_" + std::to_string(block.getBlockID()); // Collect statements. for (CFGBlock::const_iterator it = block.begin(), Es = block.end(); it != Es; ++it) { if (Optional<CFGStmt> CS = it->getAs<CFGStmt>()) { const Stmt *S = CS->getStmt(); info->statements.push_back(getInfo(*S)); } } if (block.getTerminatorStmt()) { const Stmt *S = block.getTerminatorStmt(); info->statements.push_back(getInfo(*S)); } // Collect successors. for (CFGBlock::const_succ_iterator it = block.succ_begin(), Es = block.succ_end(); it != Es; ++it) { CFGBlock *B = *it; if (B) info->successors.push_back(getInfo(*B)); } return info; } FunctionInfoPtr ExtractorASTVisitor::getInfo(const FunctionDecl &func) { FunctionInfoPtr info(new FunctionInfo()); // Collect name. info->name = func.getNameAsString(); // Collect type. info->type = func.getType().getAsString(); // Collect tokens info->tokens = tokenQueue_.popTokensForRange(func.getSourceRange()); return info; } StmtInfoPtr ExtractorASTVisitor::getInfo(const Stmt &stmt) { auto it = stmtInfos_.find(&stmt); if (it != stmtInfos_.end()) return it->second; StmtInfoPtr info(new StmtInfo); stmtInfos_[&stmt] = info; // Collect name. info->name = stmt.getStmtClassName(); // Collect referencing targets. if (const DeclRefExpr *de = dyn_cast<DeclRefExpr>(&stmt)) { info->ref_relations.push_back(getInfo(*de->getDecl(), false)); } // Collect tokens info->tokens = tokenQueue_.popTokensForRange(stmt.getSourceRange()); return info; } DeclInfoPtr ExtractorASTVisitor::getInfo(const Decl &decl, bool consumeTokens) { auto it = declInfos_.find(&decl); if (it != declInfos_.end()) { if (consumeTokens) { auto tokens = tokenQueue_.popTokensForRange(decl.getSourceRange()); it->second->tokens.insert(it->second->tokens.end(), tokens.begin(), tokens.end()); } return it->second; } DeclInfoPtr info(new DeclInfo); declInfos_[&decl] = info; info->kind = decl.getDeclKindName(); // Collect name. if (const ValueDecl *vd = dyn_cast<ValueDecl>(&decl)) { info->name = vd->getQualifiedNameAsString(); if (const auto nameTokenPtr = tokenQueue_.getTokenAt(vd->getLocation())) { info->nameToken = *nameTokenPtr; } } // Collect type. if (const ValueDecl *vd = dyn_cast<ValueDecl>(&decl)) { info->type = vd->getType().getAsString(); } // Collect tokens if (consumeTokens) { info->tokens = tokenQueue_.popTokensForRange(decl.getSourceRange()); } return info; } ExtractorASTConsumer::ExtractorASTConsumer(CompilerInstance &CI, ExtractionInfoPtr extractionInfo) : visitor_(CI.getASTContext(), std::move(extractionInfo), tokenQueue_), tokenQueue_(CI.getPreprocessor()) {} bool ExtractorASTConsumer::HandleTopLevelDecl(DeclGroupRef DR) { for (auto it = DR.begin(), e = DR.end(); it != e; ++it) { visitor_.TraverseDecl(*it); } return true; } std::unique_ptr<ASTConsumer> ExtractorFrontendAction::CreateASTConsumer( CompilerInstance &CI, StringRef file) { extractionInfo.reset(new ExtractionInfo()); // CI.getASTContext().getLangOpts().OpenCL return std::make_unique<ExtractorASTConsumer>(CI, extractionInfo); } std::vector<TokenInfo> TokenQueue::popTokensForRange( ::clang::SourceRange range) { std::vector<TokenInfo> result; auto startPos = token_index_[range.getBegin().getRawEncoding()]; auto endPos = token_index_[range.getEnd().getRawEncoding()]; for (std::size_t i = startPos; i <= endPos; ++i) { if (token_consumed_[i]) continue; result.push_back(tokens_[i]); token_consumed_[i] = true; } return result; } void TokenQueue::addToken(::clang::Token token) { TokenInfo info; info.index = nextIndex++; info.kind = token.getName(); info.name = pp_.getSpelling(token, nullptr); info.location = token.getLocation(); tokens_.push_back(info); token_consumed_.push_back(false); token_index_[info.location.getRawEncoding()] = tokens_.size() - 1; } TokenInfo *TokenQueue::getTokenAt(SourceLocation loc) { auto pos = token_index_.find(loc.getRawEncoding()); if (pos == token_index_.end()) return nullptr; return &tokens_[pos->second]; } } // namespace graph } // namespace clang } // namespace compy
28.242915
80
0.674025
[ "vector" ]
1a8cb167d4a1fb445bcc51452c527ed71b5dc176
694
cpp
C++
Classes/Model/LoadModel.cpp
jacket-code/Cocos3DEditor
89b3542192de893a48c45e47e2fa3b183ca04c7b
[ "MIT" ]
1
2020-05-14T05:52:34.000Z
2020-05-14T05:52:34.000Z
Classes/Model/LoadModel.cpp
jacket-code/Cocos3DEditor
89b3542192de893a48c45e47e2fa3b183ca04c7b
[ "MIT" ]
null
null
null
Classes/Model/LoadModel.cpp
jacket-code/Cocos3DEditor
89b3542192de893a48c45e47e2fa3b183ca04c7b
[ "MIT" ]
1
2020-10-31T11:59:48.000Z
2020-10-31T11:59:48.000Z
#include "../Global/GlobalDefine.h" #include "../MyLibrary/MyLibrary.h" #include "./LoadModel.h" USING_NS_CC; USING_NS_C3E; USING_NS_STD; LoadModel::LoadModel() { } LoadModel::~LoadModel() { } Sprite3D* LoadModel::loadModelData( const string& filePath ) { string str = MyLibrary::StringUtility::getFileName( filePath ); Sprite3D* model = Sprite3D::create( filePath ); return model; } Sprite3D* LoadModel::loadModelData( const string& filePath, const string& extension ) { Sprite3D* sprite3D = nullptr; if( extension == ".fbx" ) { } else if( extension == ".c3b" || extension == ".c3t" || extension == ".obj" ) { sprite3D = Sprite3D::create( filePath ); } return sprite3D; }
17.794872
85
0.68732
[ "model" ]
1a92812a14c7201c94cc8310890afcc29edc3eba
3,074
cpp
C++
modules/Stubs/testing/source/StubMeshTests.cpp
nasa/swSim
348ba39ea149711a2285916a2dcddc2c71da4859
[ "Apache-2.0" ]
5
2021-02-21T09:49:11.000Z
2022-02-01T09:54:54.000Z
modules/Stubs/testing/source/StubMeshTests.cpp
ElsevierSoftwareX/SOFTX-D-21-00042
348ba39ea149711a2285916a2dcddc2c71da4859
[ "Apache-2.0" ]
null
null
null
modules/Stubs/testing/source/StubMeshTests.cpp
ElsevierSoftwareX/SOFTX-D-21-00042
348ba39ea149711a2285916a2dcddc2c71da4859
[ "Apache-2.0" ]
4
2021-04-27T09:52:17.000Z
2022-03-29T07:22:16.000Z
// #include "StubMesh.hpp" #include "gtest/gtest.h" void boundingBoxCheck(double currentBox[6],double newPoint[3]); class StubMeshTests : public ::testing::Test { protected: void SetUp() override { mesh=std::make_shared<Stubs::StubMesh>(Stubs::StubMesh(ds,Nx,Ny,Nz)); }; void TearDown() override { }; std::shared_ptr<Stubs::StubMesh> mesh; int Nx=16,Ny=8,Nz=4; double ds=0.25; }; void boundingBoxCheck(double currentBox[6],double newPoint[3]){ for(int k=0;k<3;k++){ currentBox[k]=(currentBox[k]<=newPoint[k])?currentBox[k]:newPoint[k]; currentBox[k+3]=(currentBox[k+3]>=newPoint[k])?currentBox[k+3]:newPoint[k]; }; }; TEST_F(StubMeshTests,Nothing){}; TEST_F(StubMeshTests,Counts){ EXPECT_EQ(Nx*Ny*Nz,mesh->nodeCount()); EXPECT_EQ((Nx-1)*(Ny-1)*(Nz-1),mesh->cellCount()); }; TEST_F(StubMeshTests,boundingBox){ double coordinate[3]; double aabb[6]; mesh->nodeCoordinate(0,coordinate); for(int k=0;k<3;k++){ aabb[k]=coordinate[k]; aabb[k+3]=coordinate[k]; }; for(int idx=1;idx<mesh->nodeCount();idx++){ mesh->nodeCoordinate(idx,coordinate); boundingBoxCheck(aabb,coordinate); }; for(int k=0;k<3;k++){EXPECT_DOUBLE_EQ(0.0,aabb[k]);}; EXPECT_DOUBLE_EQ(ds*(double(Nx-1)),aabb[3]); EXPECT_DOUBLE_EQ(ds*(double(Ny-1)),aabb[4]); EXPECT_DOUBLE_EQ(ds*(double(Nz-1)),aabb[5]); }; TEST_F(StubMeshTests,cellBBChecks){ double aabb[6]; double coordinate[3]; int cell[8]; for(int idx=0;idx<mesh->cellCount();idx++){ mesh->cell(idx,cell); mesh->nodeCoordinate(cell[0],coordinate); for(int k=0;k<3;k++){ aabb[k]=coordinate[k]; aabb[k+3]=coordinate[k]; }; for(int k=1;k<8;k++){ mesh->nodeCoordinate(cell[k],coordinate); boundingBoxCheck(aabb,coordinate); }; for(int k=0;k<3;k++){ EXPECT_DOUBLE_EQ(ds,aabb[k+3]-aabb[k]); }; }; }; TEST_F(StubMeshTests,cellCoordCheck){ double coord[3]; for(int idx=0;idx<mesh->cellCount();idx++){ mesh->cellCoordinate(idx,coord); for(int k=0;k<3;k++){ EXPECT_LT(0.0,coord[k]); }; }; }; TEST_F(StubMeshTests,nodeBBChecks){ double aabb[6]; double coordinate[3]; int node[8]; int cell[8]; for(int idx=0;idx<mesh->nodeCount();idx++){ mesh->nodeCoordinate(idx,coordinate); for(int k=0;k<3;k++){ aabb[k]=coordinate[k]; aabb[k+3]=coordinate[k]; } mesh->node(idx,node); for(int k=0;k<8;k++){ if(node[k]!=-1){ mesh->cell(node[k],cell); for(int kk=0;kk<8;kk++){ mesh->nodeCoordinate(cell[kk],coordinate); boundingBoxCheck(aabb,coordinate); }; }; }; for(int k=0;k<3;k++){ double val=((aabb[k+3]-aabb[k])/ds); double ival=(double)(int(val)); val-=ival; EXPECT_DOUBLE_EQ(0.0,val); EXPECT_LE(1,ival); EXPECT_GE(2,ival); }; }; }; TEST_F(StubMeshTests,checkCellSize){ double extents[3]; for(int idx=0;idx<mesh->cellCount();idx++){ mesh->cellExtents(idx,extents); for(int k=0;k<3;k++){ EXPECT_DOUBLE_EQ(ds,extents[k]); }; }; };
24.592
79
0.614834
[ "mesh" ]
1a960108694f1aa9a69d7ad3cfa2cd2c112f8f85
26,807
cc
C++
orly/data/twitter_live.cc
orlyatomics/orly
d413f999f51a8e553832dab4e3baa7ca68928840
[ "Apache-2.0" ]
69
2015-01-06T05:12:57.000Z
2021-11-06T20:34:10.000Z
orly/data/twitter_live.cc
mpark/orly
9d5033bb6034e97ebf944ab25398c6879709cc32
[ "Apache-2.0" ]
5
2015-07-09T02:21:50.000Z
2021-08-13T11:10:26.000Z
orly/data/twitter_live.cc
mpark/orly
9d5033bb6034e97ebf944ab25398c6879709cc32
[ "Apache-2.0" ]
15
2015-01-23T13:34:05.000Z
2020-06-15T16:46:50.000Z
/* <orly/data/twitter_live.cc> Copyright 2010-2014 OrlyAtomics, Inc. 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 <iostream> #include <syslog.h> #include <base/cmd.h> #include <base/glob.h> #include <base/log.h> #include <base/opt.h> #include <orly/csv_to_bin/field.h> #include <orly/csv_to_bin/json_iter.h> #include <orly/csv_to_bin/translate.h> #include <orly/data/core_vector_generator.h> #include <orly/desc.h> #include <util/io.h> using namespace std; using namespace Base::Chrono; using namespace Orly; using namespace Orly::CsvToBin; using namespace Orly::Data; // {"follower_id":107618080,"followed_screen_name":"kf","follower_screen_name":"christensenp","followed_id":7178502} struct TFollowObj : public Orly::CsvToBin::TObj { int64_t follower_id; std::string follower_screen_name; int64_t followed_id; std::string followed_screen_name; virtual const TAnyFields &GetFields() const override { static const TFields<TFollowObj> fields { NEW_FIELD(TFollowObj, follower_id), NEW_FIELD(TFollowObj, follower_screen_name), NEW_FIELD(TFollowObj, followed_id), NEW_FIELD(TFollowObj, followed_screen_name) }; return fields; } }; // https://dev.twitter.com/docs/platform-objects/users struct TUserObj : public Orly::CsvToBin::TObj { bool contributors_enabled; Base::Chrono::TTimePnt created_at; bool default_profile; bool default_profile_image; Base::TOpt<std::string> description; // TEntities entities; TODO int64_t favourites_count; bool follow_request_sent; int64_t followers_count; int64_t friends_count; bool geo_enabled; int64_t id; //std::string id_str; We don't really need the string version... bool is_translator; std::string lang; int64_t listed_count; Base::TOpt<std::string> location; std::string name; std::string profile_background_color; std::string profile_background_image_url; std::string profile_background_image_url_https; bool profile_background_tile; //std::string profile_banner_url; TODO another "sometimes present field" std::string profile_image_url; std::string profile_image_url_https; std::string profile_link_color; std::string profile_sidebar_border_color; std::string profile_sidebar_fill_color; std::string profile_text_color; bool profile_use_background_image; bool _protected; std::string screen_name; // bool show_all_inline_media; TODO: a "not present field"? //TStatus status; // TODO: sometimes ommited, empty, null? int64_t statuses_count; Base::TOpt<std::string> time_zone; Base::TOpt<std::string> url; Base::TOpt<int64_t> utc_offset; bool verified; //std::string withheld_in_countries; // TODO: another "when present" field //std::string withheld_scope; // TODO: another "when present" field virtual const TAnyFields &GetFields() const override { static const TFields<TUserObj> fields { NEW_FIELD(TUserObj, contributors_enabled), NEW_FIELD(TUserObj, created_at), NEW_FIELD(TUserObj, default_profile), NEW_FIELD(TUserObj, default_profile_image), NEW_FIELD(TUserObj, description), NEW_FIELD(TUserObj, favourites_count), NEW_FIELD(TUserObj, follow_request_sent), NEW_FIELD(TUserObj, followers_count), NEW_FIELD(TUserObj, friends_count), NEW_FIELD(TUserObj, geo_enabled), NEW_FIELD(TUserObj, id), NEW_FIELD(TUserObj, is_translator), NEW_FIELD(TUserObj, lang), NEW_FIELD(TUserObj, listed_count), NEW_FIELD(TUserObj, location), NEW_FIELD(TUserObj, name), NEW_FIELD(TUserObj, profile_background_color), NEW_FIELD(TUserObj, profile_background_image_url), NEW_FIELD(TUserObj, profile_background_image_url_https), NEW_FIELD(TUserObj, profile_background_tile), NEW_FIELD(TUserObj, profile_image_url), NEW_FIELD(TUserObj, profile_image_url_https), NEW_FIELD(TUserObj, profile_link_color), NEW_FIELD(TUserObj, profile_sidebar_border_color), NEW_FIELD(TUserObj, profile_sidebar_fill_color), NEW_FIELD(TUserObj, profile_text_color), NEW_FIELD(TUserObj, profile_use_background_image), ::Orly::CsvToBin::NewField("protected", &TUserObj::_protected), NEW_FIELD(TUserObj, screen_name), NEW_FIELD(TUserObj, statuses_count), NEW_FIELD(TUserObj, time_zone), NEW_FIELD(TUserObj, url), NEW_FIELD(TUserObj, utc_offset), NEW_FIELD(TUserObj, verified) }; return fields; } }; struct TStatusObj : public Orly::CsvToBin::TObj { struct TContributorObj : public Orly::CsvToBin::TObj { int64_t id; std::string screen_name; virtual const TAnyFields &GetFields() const override { static const TFields<TContributorObj> fields { NEW_FIELD(TContributorObj, id), NEW_FIELD(TContributorObj, screen_name) }; return fields; } }; struct TCoordinateObj : public Orly::CsvToBin::TObj { std::vector<double> coordinates; std::string type; virtual const TAnyFields &GetFields() const override { static const TFields<TCoordinateObj> fields { NEW_FIELD(TCoordinateObj, coordinates), NEW_FIELD(TCoordinateObj, type) }; return fields; } }; struct TEntitiesObj : public Orly::CsvToBin::TObj { struct THashTagObj : public Orly::CsvToBin::TObj { std::vector<int> indices; std::string text; virtual const TAnyFields &GetFields() const override { static const TFields<THashTagObj> fields { NEW_FIELD(THashTagObj, indices), NEW_FIELD(THashTagObj, text) }; return fields; } }; struct TUserMentionObj : public Orly::CsvToBin::TObj { int64_t id; std::vector<int> indices; std::string name; std::string screen_name; virtual const TAnyFields &GetFields() const override { static const TFields<TUserMentionObj> fields { NEW_FIELD(TUserMentionObj, id), NEW_FIELD(TUserMentionObj, indices), NEW_FIELD(TUserMentionObj, name), NEW_FIELD(TUserMentionObj, screen_name) }; return fields; } }; std::vector<THashTagObj> hashtags; std::vector<TUserMentionObj> user_mentions; virtual const TAnyFields &GetFields() const override { static const TFields<TEntitiesObj> fields { NEW_FIELD(TEntitiesObj, hashtags), NEW_FIELD(TEntitiesObj, user_mentions) }; return fields; } }; //Base::TOpt<std::vector<TContributorObj>> contributors; // TODO: issue parsing contributors for now Base::TOpt<TCoordinateObj> coordinates; Base::Chrono::TTimePnt created_at; TEntitiesObj entities; Base::TOpt<int64_t> favorite_count; Base::TOpt<bool> favorited; //std::string filter_level; // this field doesn't seem to exist in the data int64_t id; Base::TOpt<std::string> in_reply_to_screen_name; Base::TOpt<int64_t> in_reply_to_status_id; Base::TOpt<int64_t> in_reply_to_user_id; Base::TOpt<std::string> lang; // Base::TOpt<TPlaceObj> place; // TODO: place //Base::TOpt<bool> possibly_sensitive; // This field is not always present // TScopesObj scopes; // TODO: scopes int64_t retweet_count; bool retweeted; std::unique_ptr<TStatusObj> retweeted_status; // TODO: retweeted tweets std::string source; std::string text; bool truncated; TUserObj user; //bool withheld_copyright; // this field does not seem to be present //std::vector<std::string> withheld_in_countries; // this field does not seem to be present //std::string withheld_scope; // this field does not seem to be present virtual const TAnyFields &GetFields() const override { static const TFields<TStatusObj> fields { //NEW_FIELD(TStatusObj, contributors), NEW_FIELD(TStatusObj, coordinates), NEW_FIELD(TStatusObj, created_at), NEW_FIELD(TStatusObj, entities), NEW_FIELD(TStatusObj, favorite_count), NEW_FIELD(TStatusObj, favorited), NEW_FIELD(TStatusObj, id), NEW_FIELD(TStatusObj, in_reply_to_screen_name), NEW_FIELD(TStatusObj, in_reply_to_status_id), NEW_FIELD(TStatusObj, in_reply_to_user_id), NEW_FIELD(TStatusObj, lang), NEW_FIELD(TStatusObj, retweet_count), NEW_FIELD(TStatusObj, retweeted), NEW_FIELD(TStatusObj, retweeted_status), NEW_FIELD(TStatusObj, source), NEW_FIELD(TStatusObj, text), NEW_FIELD(TStatusObj, truncated), NEW_FIELD(TStatusObj, user), }; return fields; } }; constexpr int64_t ReplyToTweet = 0; constexpr int64_t ReplyToUser = 1; constexpr int64_t ReplyFromUser = 2; constexpr int64_t DidMentionUser = 3; constexpr int64_t MentionedByUser = 4; constexpr int64_t PersonUsedTag = 5; constexpr int64_t TagUsedByPerson = 6; constexpr int64_t PersonLocation = 7; constexpr int64_t Following = 8; constexpr int64_t FollowedBy = 9; constexpr int64_t PersonRetweeted = 10; constexpr int64_t PersonRetweetedTweet = 11; constexpr int64_t PersonWasRetweeted = 12; constexpr int64_t TweetWasRetweeted = 13; constexpr int64_t PersonGeoGridSmall = 14; constexpr int64_t PersonGeoGridBig = 15; void TranslateFollow(TJsonIter &input, const std::string &username) { assert(&input); // following using t_person_following_key = std::tuple<int64_t, int64_t, int64_t>; // IndexId, follower user id, followed user id using t_person_following_val = std::tuple<std::string, std::string>; // user handle (following), user handle (followed) TCoreVectorGenerator<t_person_following_key, t_person_following_val> person_following_cvg("person_following", username); // followed by using t_person_followed_by_key = std::tuple<int64_t, int64_t, int64_t>; // IndexId, followed user id, follower user id using t_person_followed_by_val = std::tuple<std::string, std::string>; // user handle (followed), user handle (following) TCoreVectorGenerator<t_person_followed_by_key, t_person_followed_by_val> person_followed_by_cvg("person_followed_by", username); for (; input; ++input) { const TJson &follow_obj_json = *input; TFollowObj follow_obj; TranslateJson(follow_obj, follow_obj_json); person_following_cvg.Push(t_person_following_key(Following, follow_obj.follower_id, follow_obj.followed_id), t_person_following_val(follow_obj.follower_screen_name, follow_obj.followed_screen_name)); person_followed_by_cvg.Push(t_person_followed_by_key(FollowedBy, follow_obj.followed_id, follow_obj.follower_id), t_person_followed_by_val(follow_obj.followed_screen_name, follow_obj.follower_screen_name)); } } void TranslateUser(TJsonIter &input, const std::string &username) { assert(&input); // user screen name -> id using t_user_by_screen_key = std::tuple<std::string>; // screen name using t_user_by_screen_val = int64_t; // user_id TCoreVectorGenerator<t_user_by_screen_key, t_user_by_screen_val> user_by_screen_cvg("user_by_screen", username); // user id -> screen name using t_screen_by_user_key = std::tuple<int64_t>; // user id using t_screen_by_user_val = std::string; // screen name TCoreVectorGenerator<t_screen_by_user_key, t_screen_by_user_val> screen_by_user_cvg("screen_by_user", username); for (; input; ++input) { const TJson &user_obj_json = *input; TUserObj user_obj; TranslateJson(user_obj, user_obj_json); user_by_screen_cvg.Push(t_user_by_screen_key(user_obj.screen_name), user_obj.id); screen_by_user_cvg.Push(t_screen_by_user_key(user_obj.id), user_obj.screen_name); } } struct TPersonTweetedVal { using TCoord = Base::TOpt<std::tuple<double, double>>; TPersonTweetedVal(int64_t reply_to_status, int64_t reply_to_user, int64_t _retweet_count, const Base::Chrono::TTimePnt &_date, const std::string &_text, const Base::TOpt<TStatusObj::TCoordinateObj> &coord) : reply_to_tweet_id(reply_to_status), reply_to_user_id(reply_to_user), retweet_count(_retweet_count), date(_date), text(_text), coordinates(coord ? TCoord(make_tuple(coord->coordinates[0], coord->coordinates[1])) : TCoord()) {} int64_t reply_to_tweet_id; int64_t reply_to_user_id; int64_t retweet_count; Base::Chrono::TTimePnt date; std::string text; TCoord coordinates; }; RECORD_ELEM(TPersonTweetedVal, int64_t, reply_to_tweet_id); RECORD_ELEM(TPersonTweetedVal, int64_t, reply_to_user_id); RECORD_ELEM(TPersonTweetedVal, Base::Chrono::TTimePnt, date); RECORD_ELEM(TPersonTweetedVal, std::string, text); RECORD_ELEM(TPersonTweetedVal, TPersonTweetedVal::TCoord, coordinates); void TranslateStatus(TJsonIter &input, const std::string &username) { assert(&input); // person tweeted using t_person_tweeted_key = std::tuple<int64_t, int64_t>; // user id, tweet id using t_person_tweeted_val = TPersonTweetedVal; // text TCoreVectorGenerator<t_person_tweeted_key, t_person_tweeted_val> person_tweeted_cvg("person_tweeted", username); using t_person_tweeted_tweet_key = std::tuple<int64_t, int64_t, int64_t, int64_t>; // IndexId, id of replied to tweet, id of user who replied to it, tweet id of reply using t_person_tweeted_tweet_val = std::tuple<std::string, Base::Chrono::TTimePnt>; // user handle, date TCoreVectorGenerator<t_person_tweeted_tweet_key, t_person_tweeted_tweet_val> person_tweeted_tweet_cvg("person_tweeted_in_reply_to_tweet", username); using t_person_tweeted_user_key = std::tuple<int64_t, int64_t, int64_t, int64_t>; // IndexId, id of user who replied to it, id of replied to user, tweet id of reply using t_person_tweeted_user_val = std::tuple<std::string, std::string, Base::Chrono::TTimePnt>; // user handle (of person that made reply) user handle (of replied), date TCoreVectorGenerator<t_person_tweeted_user_key, t_person_tweeted_user_val> person_tweeted_user_cvg("person_tweeted_in_reply_to_user", username); using t_user_received_reply_key = std::tuple<int64_t, int64_t, int64_t, int64_t>; // IndexId, id of replied to user, id of user who replied, tweet id of reply using t_user_received_reply_val = std::tuple<std::string, std::string, Base::Chrono::TTimePnt>; // user handle (of replied) user handle (of person that made reply), date TCoreVectorGenerator<t_user_received_reply_key, t_user_received_reply_val> user_received_reply_cvg("user_received_reply", username); using t_person_location_key = std::tuple<int64_t, int64_t, Base::Chrono::TTimePnt, double, double>; // IndexId, id of user, user handle, date, longitude, latitude using t_person_location_val = std::tuple<std::string, int64_t>; // user handle, tweet id TCoreVectorGenerator<t_person_location_key, t_person_location_val> person_location_cvg("person_location", username); using t_person_geo_grid_key = std::tuple<int64_t, int64_t, int64_t, Base::Chrono::TTimePnt, int64_t>; // IndexId, longitude grid, latitude grid, date, id of user using t_person_geo_grid_val = std::tuple<std::string, int64_t, double, double>; // user handle, tweet id, longitude, latitude TCoreVectorGenerator<t_person_geo_grid_key, t_person_geo_grid_val> person_geo_grid_cvg("person_geo_grid", username); auto person_tweeted = [&](int64_t uid, const std::string &handle, int64_t tid, const Base::TOpt<int64_t> &reply_to_tweet_id, const Base::TOpt<int64_t> &reply_to_user_id, const Base::TOpt<std::string> &reply_to_screen_name, int64_t retweet_count, const Base::Chrono::TTimePnt &date, const std::string &text, const Base::TOpt<TStatusObj::TCoordinateObj> &coordinates) { person_tweeted_cvg.Push(t_person_tweeted_key(uid, tid), t_person_tweeted_val(reply_to_tweet_id ? *reply_to_tweet_id : -1, reply_to_user_id ? *reply_to_user_id : -1, retweet_count, date, text, coordinates)); if (reply_to_tweet_id) { person_tweeted_tweet_cvg.Push(t_person_tweeted_tweet_key(ReplyToTweet, *reply_to_tweet_id, uid, tid), t_person_tweeted_tweet_val(handle, date)); } if (reply_to_user_id) { assert(reply_to_screen_name); person_tweeted_user_cvg.Push(t_person_tweeted_user_key(ReplyToUser, uid, *reply_to_user_id, tid), t_person_tweeted_user_val(handle, *reply_to_screen_name, date)); user_received_reply_cvg.Push(t_user_received_reply_key(ReplyFromUser, *reply_to_user_id, uid, tid), t_user_received_reply_val(*reply_to_screen_name, handle, date)); } if (coordinates) { person_location_cvg.Push(t_person_location_key(PersonLocation, uid, date, coordinates->coordinates[0], coordinates->coordinates[1]), t_person_location_val(handle, tid)); const int64_t lon_grid_small = coordinates->coordinates[0] * 1000; const int64_t lat_grid_small = coordinates->coordinates[1] * 1000; const int64_t lon_grid_big = coordinates->coordinates[0] * 10; const int64_t lat_grid_big = coordinates->coordinates[1] * 10; person_geo_grid_cvg.Push(t_person_geo_grid_key(PersonGeoGridSmall, lon_grid_small, lat_grid_small, date, uid), t_person_geo_grid_val(handle, tid, coordinates->coordinates[0], coordinates->coordinates[1])); person_geo_grid_cvg.Push(t_person_geo_grid_key(PersonGeoGridBig, lon_grid_big, lat_grid_big, date, uid), t_person_geo_grid_val(handle, tid, coordinates->coordinates[0], coordinates->coordinates[1])); } }; // person mentioned using t_person_did_mention_key = std::tuple<int64_t, int64_t, int64_t, int64_t>; // IndexId, user id, mentioned user id, tweet id using t_person_did_mention_val = std::tuple<std::string, std::string, Base::Chrono::TTimePnt>; // user handle (did mention), user handle (mentioned), date TCoreVectorGenerator<t_person_did_mention_key, t_person_did_mention_val> person_did_mention_cvg("person_did_mention", username); using t_person_mentioned_by_key = std::tuple<int64_t, int64_t, int64_t, int64_t>; // IndexId, mentioned user id, user id, tweet id using t_person_mentioned_by_val = std::tuple<std::string, std::string, Base::Chrono::TTimePnt>; // user handle (mentioned), user handle (did mention), date TCoreVectorGenerator<t_person_mentioned_by_key, t_person_mentioned_by_val> person_mentioned_by_cvg("person_mentioned_by", username); auto person_mentioned = [&](int64_t uid, const std::string &handle, int64_t muid, const std::string &mhandle, int64_t tid, const Base::Chrono::TTimePnt &date) { person_did_mention_cvg.Push(t_person_did_mention_key(DidMentionUser, uid, muid, tid), t_person_did_mention_val(handle, mhandle, date)); person_mentioned_by_cvg.Push(t_person_mentioned_by_key(MentionedByUser, muid, uid, tid), t_person_mentioned_by_val(mhandle, handle, date)); }; // person used hashtag using t_person_used_tag_key = std::tuple<int64_t, int64_t, std::string, int64_t>; // IndexId, user id, hashtag, tweet id using t_person_used_tag_val = std::tuple<std::string, Base::Chrono::TTimePnt>; // user handle, date TCoreVectorGenerator<t_person_used_tag_key, t_person_used_tag_val> person_used_tag_cvg("person_used_tag", username); using t_tag_used_by_key = std::tuple<int64_t, std::string, int64_t, int64_t>; // IndexId, hashtag, user id, user handle, tweet id using t_tag_used_by_val = std::tuple<std::string, Base::Chrono::TTimePnt>; // user handle, date TCoreVectorGenerator<t_tag_used_by_key, t_tag_used_by_val> tag_used_by_cvg("tag_used_by", username); auto person_tagged = [&](int64_t uid, const std::string &handle, const std::string &hashtag, int64_t tid, const Base::Chrono::TTimePnt &date) { person_used_tag_cvg.Push(t_person_used_tag_key(PersonUsedTag, uid, hashtag, tid), t_person_used_tag_val(handle, date)); tag_used_by_cvg.Push(t_tag_used_by_key(TagUsedByPerson, hashtag, uid, tid), t_tag_used_by_val(handle, date)); }; // person retweeted using t_person_retweet_key = std::tuple<int64_t, int64_t, int64_t, int64_t>; // IndexId, user id, id of original tweet user , tweet id using t_person_retweet_val = std::tuple<std::string, std::string, int64_t, Base::Chrono::TTimePnt>; // user handle, user handle of originator, original tweet id, date TCoreVectorGenerator<t_person_retweet_key, t_person_retweet_val> person_retweet_cvg("person_retweet_user", username); using t_person_retweet_tweet_key = std::tuple<int64_t, int64_t, int64_t, int64_t>; // IndexId, user id, original tweet id, tweet id using t_person_retweet_tweet_val = std::tuple<std::string, std::string, int64_t, Base::Chrono::TTimePnt>; // user handle, user handle of originator, user id of originator, date TCoreVectorGenerator<t_person_retweet_tweet_key, t_person_retweet_tweet_val> person_retweet_tweet_cvg("person_retweet_tweet", username); using t_person_was_retweeted_key = std::tuple<int64_t, int64_t, int64_t, int64_t>; // IndexId, user id of original user, user who retweeted , tweet id using t_person_was_retweeted_val = std::tuple<std::string, std::string, int64_t, Base::Chrono::TTimePnt>; // user handle of original user, user handle of retweeter, original tweet id, date TCoreVectorGenerator<t_person_was_retweeted_key, t_person_was_retweeted_val> person_was_retweeted_cvg("person_was_retweeted", username); using t_tweet_was_retweeted_key = std::tuple<int64_t, int64_t, int64_t, int64_t>; // IndexId, original tweet id, user id who retweeted , tweet id using t_tweet_was_retweeted_val = std::tuple<std::string, std::string, int64_t, Base::Chrono::TTimePnt>; // user handle of original user, user handle of retweeter, user id of original user, date TCoreVectorGenerator<t_tweet_was_retweeted_key, t_tweet_was_retweeted_val> tweet_was_retweeted_cvg("tweet_was_retweeted", username); auto person_retweeted = [&](int64_t uid, const std::string &handle, int64_t ouid, const std::string &ohandle, int64_t tid, int64_t otid, const Base::Chrono::TTimePnt &date) { person_retweet_cvg.Push(t_person_retweet_key(PersonRetweeted, uid, ouid, tid), t_person_retweet_val(handle, ohandle, otid, date)); person_retweet_tweet_cvg.Push(t_person_retweet_tweet_key(PersonRetweetedTweet, uid, otid, tid), t_person_retweet_tweet_val(handle, ohandle, ouid, date)); person_was_retweeted_cvg.Push(t_person_was_retweeted_key(PersonWasRetweeted, ouid, uid, tid), t_person_was_retweeted_val(ohandle, handle, otid, date)); tweet_was_retweeted_cvg.Push(t_tweet_was_retweeted_key(TweetWasRetweeted, otid, uid, tid), t_tweet_was_retweeted_val(ohandle, handle, ouid, date)); }; for (; input; ++input) { const TJson &status_obj_json = *input; TStatusObj obj; TranslateJson(obj, status_obj_json); person_tweeted(obj.user.id, obj.user.screen_name, obj.id, obj.in_reply_to_status_id, obj.in_reply_to_user_id, obj.in_reply_to_screen_name, obj.retweet_count, obj.created_at, obj.text, obj.coordinates); stringstream ss; ss << obj.created_at; for (const auto &mention : obj.entities.user_mentions) { person_mentioned(obj.user.id, obj.user.screen_name, mention.id, mention.screen_name, obj.id, obj.created_at); } for (const auto &tag : obj.entities.hashtags) { person_tagged(obj.user.id, obj.user.screen_name, tag.text, obj.id, obj.created_at); } if (obj.retweeted_status) { person_retweeted(obj.user.id, obj.user.screen_name, obj.retweeted_status->user.id, obj.retweeted_status->user.screen_name, obj.id, obj.retweeted_status->id, obj.created_at); } } } class TCmd final : public Base::TLog::TCmd { public: TCmd(int argc, char *argv[]) { Parse(argc, argv, TMeta()); } string Username; private: class TMeta final : public Base::TLog::TCmd::TMeta { public: TMeta() : Base::TLog::TCmd::TMeta("CSV to Orly binary converter generator.") { Param(&TCmd::Username, "username", Required, "The user whose json we should read"); } }; // TMeta }; // TCmd int main(int argc, char *argv[]) { TCmd cmd(argc, argv); Base::TLog log(cmd); const vector<string> datasets = {"users", "follows", "statuses"}; for (const string &dataset: datasets) { stringstream ss; ss << cmd.Username << '.' << dataset << ".json"; Base::Glob(ss.str().c_str(), [&](const char *name) -> bool { std::string username(name, strchr(name, '.')); try { ifstream in; Util::OpenFile(in, name); TJsonIter json_iter(in); if (dataset == "users") { TranslateUser(json_iter, username); } else if (dataset == "follows") { TranslateFollow(json_iter, username); } else if (dataset == "statuses") { TranslateStatus(json_iter, username); } } catch (const Util::TOpenFileError &ex) { cout << "ERROR: Processing dataset " << quoted(dataset) << " for user " << quoted(username) << " file " << quoted(ss.str()) << endl; cout << ex.what() << endl; } catch (const std::exception &ex) { cout << "ERROR: Processing dataset " << quoted(dataset) << " for user " << quoted(username) << " file " << quoted(ss.str()) << endl; cout << ex.what() << endl; throw ex; } return true; }); } }
49.734694
211
0.702802
[ "vector" ]
1a9662b73606f6a504d58a1fc8d9f8f1395147e6
633
cc
C++
test/mdlConvert.cc
cwsmith/core
840fbf6ec49a63aeaa3945f11ddb224f6055ac9f
[ "BSD-3-Clause" ]
1
2021-12-02T09:25:32.000Z
2021-12-02T09:25:32.000Z
test/mdlConvert.cc
cwsmith/core
840fbf6ec49a63aeaa3945f11ddb224f6055ac9f
[ "BSD-3-Clause" ]
null
null
null
test/mdlConvert.cc
cwsmith/core
840fbf6ec49a63aeaa3945f11ddb224f6055ac9f
[ "BSD-3-Clause" ]
null
null
null
#include <stdio.h> #include <SimUtil.h> #include <MeshSim.h> #include <SimModel.h> #include "gmi_sim.h" #include "gmi_mesh.h" int main(int argc, char** argv) { if (argc != 3) { printf("Convert simmetrix smd model to a gmi dmg model\n"); printf("Usage: %s <simmetrix smd model> <gmi dmg model>\n", argv[0]); return 0; } MS_init(); SimModel_start(); Sim_readLicenseFile(0); gmi_sim_start(); gmi_register_mesh(); gmi_register_sim(); gmi_model* m = gmi_load(argv[1]); gmi_write_dmg(m, argv[2]); gmi_destroy(m); gmi_sim_stop(); Sim_unregisterAllKeys(); SimModel_stop(); MS_exit(); return 0; }
21.1
73
0.660348
[ "model" ]
1a9bbf60ab340367dd5350bdf48c55cc34fa4fba
6,209
cpp
C++
core/model/src/xml_annotation_t.cpp
lkeegan/spatial-model-editor
5dcb06550607b0a734acddd8b719035b68e35307
[ "MIT" ]
4
2019-07-18T15:05:09.000Z
2020-03-14T09:50:07.000Z
core/model/src/xml_annotation_t.cpp
lkeegan/spatial-model-editor
5dcb06550607b0a734acddd8b719035b68e35307
[ "MIT" ]
328
2019-06-30T12:03:01.000Z
2020-10-05T15:56:35.000Z
core/model/src/xml_annotation_t.cpp
lkeegan/spatial-model-editor
5dcb06550607b0a734acddd8b719035b68e35307
[ "MIT" ]
1
2019-06-08T22:47:14.000Z
2019-06-08T22:47:14.000Z
#include "catch_wrapper.hpp" #include "model_test_utils.hpp" #include "sme/simulate_options.hpp" #include "sme/xml_annotation.hpp" #include <QFile> using namespace sme; using namespace sme::test; TEST_CASE("XML Annotations", "[core/model/xml_annotation][core/" "model][core][model][xml_annotation][xml][annotation]") { SECTION("Settings annotations") { auto doc{test::getExampleSbmlDoc(Mod::ABtoC)}; auto *model{doc->getModel()}; auto settings{model::getSbmlAnnotation(model)}; // set some options & save auto &displayOptions{settings.displayOptions}; displayOptions.showMinMax = false; displayOptions.showSpecies = {true, false, true, true, false}; displayOptions.normaliseOverAllSpecies = true; displayOptions.normaliseOverAllTimepoints = false; auto &simulationSettings{settings.simulationSettings}; simulationSettings.times.clear(); simulationSettings.times.push_back({1, 0.2}); simulationSettings.times.push_back({5, 0.25}); simulationSettings.options.pixel.maxThreads = 4; simulationSettings.options.dune.dt = 0.0123; auto &meshParameters{settings.meshParameters}; meshParameters.boundarySimplifierType = 1; auto &optimizeOptions{settings.optimizeOptions}; optimizeOptions.optAlgorithm.islands = 3; optimizeOptions.optAlgorithm.population = 7; auto &optCost{optimizeOptions.optCosts.emplace_back()}; optCost.name = "myOptCost"; optCost.targetValues = {1.0, 3.0, 5.0}; auto &optParam{optimizeOptions.optParams.emplace_back()}; optParam.name = "myOptParam"; // todo: populate all fields above model::setSbmlAnnotation(model, settings); // load them from sbml auto newSettings{model::getSbmlAnnotation(model)}; auto &newDisplayOpts{newSettings.displayOptions}; REQUIRE(newDisplayOpts.showMinMax == displayOptions.showMinMax); REQUIRE(newDisplayOpts.showSpecies == displayOptions.showSpecies); REQUIRE(newDisplayOpts.normaliseOverAllSpecies == displayOptions.normaliseOverAllSpecies); REQUIRE(newDisplayOpts.normaliseOverAllTimepoints == displayOptions.normaliseOverAllTimepoints); auto &newSimulationSettings{newSettings.simulationSettings}; REQUIRE(newSimulationSettings.times.size() == 2); REQUIRE(newSimulationSettings.options.pixel.maxThreads == 4); REQUIRE(newSimulationSettings.options.dune.dt == dbl_approx(0.0123)); auto &newMeshParameters{newSettings.meshParameters}; REQUIRE(newMeshParameters.boundarySimplifierType == 1); auto &newOptimizeOptions{newSettings.optimizeOptions}; REQUIRE(optimizeOptions.optAlgorithm.islands == 3); REQUIRE(optimizeOptions.optAlgorithm.population == 7); REQUIRE(newOptimizeOptions.optCosts.size() == 1); REQUIRE(newOptimizeOptions.optCosts[0].name == "myOptCost"); REQUIRE(newOptimizeOptions.optCosts[0].targetValues.size() == 3); REQUIRE(newOptimizeOptions.optCosts[0].targetValues[0] == dbl_approx(1.0)); REQUIRE(newOptimizeOptions.optCosts[0].targetValues[1] == dbl_approx(3.0)); REQUIRE(newOptimizeOptions.optCosts[0].targetValues[2] == dbl_approx(5.0)); REQUIRE(newOptimizeOptions.optParams.size() == 1); REQUIRE(newOptimizeOptions.optParams[0].name == "myOptParam"); // change options, save & write to file newSimulationSettings.times.push_back({7, 0.33}); newSimulationSettings.options.pixel.maxThreads = 16; newOptimizeOptions.optAlgorithm.islands = 2; newOptimizeOptions.optAlgorithm.population = 4; newOptimizeOptions.optCosts.emplace_back().name = "optCost2"; newOptimizeOptions.optParams[0].name = "newOptParamName"; model::setSbmlAnnotation(model, newSettings); libsbml::writeSBMLToFile(doc.get(), "tmpxmlsettings.xml"); // load saved model with annotations QFile f2("tmpxmlsettings.xml"); f2.open(QIODevice::ReadOnly); std::unique_ptr<libsbml::SBMLDocument> doc2( libsbml::readSBMLFromString(f2.readAll().toStdString().c_str())); auto settings2{model::getSbmlAnnotation(doc2->getModel())}; auto &displayOptions2{settings2.displayOptions}; REQUIRE(displayOptions2.showMinMax == displayOptions.showMinMax); REQUIRE(displayOptions2.showSpecies == displayOptions.showSpecies); REQUIRE(displayOptions2.normaliseOverAllSpecies == displayOptions.normaliseOverAllSpecies); REQUIRE(displayOptions2.normaliseOverAllTimepoints == displayOptions.normaliseOverAllTimepoints); auto &simulationSettings2{settings2.simulationSettings}; REQUIRE(simulationSettings2.times.size() == 3); REQUIRE(simulationSettings2.options.pixel.maxThreads == 16); REQUIRE(simulationSettings2.options.dune.dt == dbl_approx(0.0123)); auto &optimizeOptions2{settings2.optimizeOptions}; REQUIRE(optimizeOptions2.optAlgorithm.islands == 2); REQUIRE(optimizeOptions2.optAlgorithm.population == 4); REQUIRE(optimizeOptions2.optCosts.size() == 2); REQUIRE(optimizeOptions2.optCosts[0].name == "myOptCost"); REQUIRE(optimizeOptions2.optCosts[0].targetValues.size() == 3); REQUIRE(optimizeOptions2.optCosts[0].targetValues[0] == dbl_approx(1.0)); REQUIRE(optimizeOptions2.optCosts[0].targetValues[1] == dbl_approx(3.0)); REQUIRE(optimizeOptions2.optCosts[0].targetValues[2] == dbl_approx(5.0)); REQUIRE(optimizeOptions2.optCosts[1].name == "optCost2"); REQUIRE(optimizeOptions2.optCosts[1].targetValues.empty()); REQUIRE(optimizeOptions2.optParams.size() == 1); REQUIRE(optimizeOptions2.optParams[0].name == "newOptParamName"); } SECTION("Invalid settings annotations") { auto doc{getTestSbmlDoc("ABtoC-invalid-annotation")}; auto settings{model::getSbmlAnnotation(doc->getModel())}; // default-constructed Settings is returned if xml annotation is invalid REQUIRE(settings.meshParameters.maxPoints.empty()); REQUIRE(settings.meshParameters.maxAreas.empty()); REQUIRE(settings.displayOptions.showSpecies.empty()); REQUIRE(settings.simulationSettings.times.empty()); REQUIRE(settings.optimizeOptions.optCosts.empty()); REQUIRE(settings.optimizeOptions.optParams.empty()); REQUIRE(settings.speciesColours.empty()); } }
49.672
79
0.744242
[ "model" ]
1a9c7e5d4bb6b4ee63cf48664064c350850df5ec
28,222
cpp
C++
src/ExpressionMatrixLshGpu.cpp
iosonofabio/ExpressionMatrix2
a6fc6938fe857fe1bd6a9200071957691295ba3c
[ "MIT" ]
null
null
null
src/ExpressionMatrixLshGpu.cpp
iosonofabio/ExpressionMatrix2
a6fc6938fe857fe1bd6a9200071957691295ba3c
[ "MIT" ]
null
null
null
src/ExpressionMatrixLshGpu.cpp
iosonofabio/ExpressionMatrix2
a6fc6938fe857fe1bd6a9200071957691295ba3c
[ "MIT" ]
null
null
null
#if CZI_EXPRESSION_MATRIX2_BUILD_FOR_GPU #include "ExpressionMatrix.hpp" #include "ExpressionMatrixSubset.hpp" #include "heap.hpp" #include "Lsh.hpp" #include "SimilarPairs.hpp" #include "timestamp.hpp" using namespace ChanZuckerberg; using namespace ExpressionMatrix2; void ExpressionMatrix::findSimilarPairs4Gpu( const string& geneSetName, // The name of the gene set to be used. const string& cellSetName, // The name of the cell set to be used. const string& lshName, // The name of the Lsh object to be used. const string& similarPairsName, // The name of the SimilarPairs object to be created. size_t k, // The maximum number of similar pairs to be stored for each cell. double similarityThreshold, // The minimum similarity for a pair to be stored. size_t lshCount, // The number of LSH vectors to use. unsigned int seed, // The seed used to generate the LSH vectors. unsigned int kernel, // The GPU kernel (algorithm) to use. CellId blockSize // The number of cells processed by each kernel instance. ) { cout << timestamp << "ExpressionMatrix::findSimilarPairs4Gpu begins." << endl; const auto t0 = std::chrono::steady_clock::now(); // Locate the gene set and verify that it is not empty. const auto itGeneSet = geneSets.find(geneSetName); if(itGeneSet == geneSets.end()) { throw runtime_error("Gene set " + geneSetName + " does not exist."); } const GeneSet& geneSet = itGeneSet->second; if(geneSet.size() == 0) { throw runtime_error("Gene set " + geneSetName + " is empty."); } // Locate the cell set and verify that it is not empty. const auto& it = cellSets.cellSets.find(cellSetName); if(it == cellSets.cellSets.end()) { throw runtime_error("Cell set " + cellSetName + " does not exist."); } const MemoryMapped::Vector<CellId>& cellSet = *(it->second); const CellId cellCount = CellId(cellSet.size()); if(cellCount == 0) { throw runtime_error("Cell set " + cellSetName + " is empty."); } // Create the expression matrix subset for this gene set and cell set. cout << timestamp << "Creating expression matrix subset." << endl; const string expressionMatrixSubsetName = directoryName + "/tmp-ExpressionMatrixSubset-" + similarPairsName; ExpressionMatrixSubset expressionMatrixSubset( expressionMatrixSubsetName, geneSet, cellSet, cellExpressionCounts); // Create the Lsh object that will do the computation. Lsh lsh(directoryName + "/Lsh-" + lshName); if(lsh.cellCount() != cellSet.size()) { throw runtime_error("LSH object " + lshName + " has a number of cells inconsistent with cell set " + cellSetName); } lsh.initializeGpu(); cout << "GPU computing will use " << lsh.getGpuName() << "." << endl; // Load the LSH signatures to the GPU. const auto t1 = std::chrono::steady_clock::now(); lsh.loadSignaturesToGpu(); const auto t2 = std::chrono::steady_clock::now(); const double t12 = 1.e-9 * double((std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1)).count()); cout << "Loading cell signatures to GPU took " << t12 << " s at "; cout << (double(cellCount)*double(lsh.wordCount())*sizeof(uint64_t) / (t12*1024.*1024.)) << " MB/s." << endl; // Create the SimilarPairs object that will store the results. SimilarPairs similarPairs(directoryName + "/SimilarPairs-" + similarPairsName, k, geneSet, cellSet); // Call the appropriate lower level function. switch(kernel) { case 0: findSimilarPairs4GpuKernel0(k, similarityThreshold, lsh, similarPairs); break; case 1: findSimilarPairs4GpuKernel1(k, similarityThreshold, lsh, similarPairs, blockSize); break; case 2: findSimilarPairs4GpuKernel2(k, similarityThreshold, lsh, similarPairs, blockSize); break; default: throw runtime_error( "Invalid kernel " + std::to_string(kernel) + " specified in findSimilarPairs4Gpu call. "); } const auto t3 = std::chrono::steady_clock::now(); const double t03 = 1.e-9 * double((std::chrono::duration_cast<std::chrono::nanoseconds>(t3 - t0)).count()); cout << timestamp << "ExpressionMatrix::findSimilarPairs4Gpu ends. Took " << t03 << " s." << endl; } // Kernel 0: compute the number of mismatches between the signature // of cell cellId0 and the signatures of all other cells. // This is a simple but working kernel. // It has high overhead and low performance // because of the small amount of work done by each instance. void ExpressionMatrix::findSimilarPairs4GpuKernel0( size_t k, double similarityThreshold, Lsh& lsh, SimilarPairs& similarPairs) { const CellId cellCount = lsh.cellCount(); // Vectors reused for each cell in the loop over cells below. vector<uint16_t> mismatchCounts(cellCount); vector< pair<uint16_t, CellId> > neighbors; // pair(mismatchCount, cellId1) // Compute the threshold on the number of mismatches. const size_t mismatchCountThreshold = lsh.computeMismatchCountThresholdFromSimilarityThreshold(similarityThreshold); // Loop over all cells. lsh.setupGpuKernel0(mismatchCounts); const auto t0 = std::chrono::steady_clock::now(); for(CellId cellId0=0; cellId0!=cellCount; cellId0++) { // Use gpuKernel0 to compute the number of mismatches with all cells. lsh.gpuKernel0(cellId0); // Candidate neighbors are the ones where the number of mismatches is small. neighbors.clear(); for(CellId cellId1=0; cellId1!=cellCount; cellId1++) { if(cellId1 == cellId0) { continue; } const uint16_t mismatchCount = mismatchCounts[cellId1]; if(mismatchCount <= mismatchCountThreshold) { neighbors.push_back(make_pair(mismatchCount, cellId1)); } } // Only keep the k best neighbors, then sort them. // This is faster than sorting, then keeping the k best, // because it avoids doing a complete sorting of all of the neighbors. // Instead, keepBest uses std::nth_element, which does a partial sorting. keepBest(neighbors, k, std::less< pair<uint16_t, CellId> >()); sort(neighbors.begin(), neighbors.end()); // Store. for(const auto& neighbor: neighbors) { const CellId cellId1 = neighbor.second; const uint16_t mismatchCount = neighbor.first; const double similarity = lsh.getSimilarity(mismatchCount); similarPairs.addUnsymmetricNoCheck(cellId0, cellId1, similarity); } } const auto t1 = std::chrono::steady_clock::now(); const double t01 = 1.e-9 * double((std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0)).count()); cout << "Similar pairs computation on GPU took " << t01 << " s at "; cout << 1.e9*t01/(double(cellCount)*double(cellCount)) << " ns/pair" << endl; lsh.cleanupGpuKernel0(); } // Kernel 1: compute the number of mismatches between the signature // of cells in range [cellId0Begin, cellId0End] // and the signatures of all other cells. // This is parallelized over cellId1. // This has lower overhead than kernel 0 // because each kernel instance does more work // (processes n0 values of cellId0 instead of just one). // For efficient memory access, the blockSize mismatch counts // for each cellId1 are stored contiguously. void ExpressionMatrix::findSimilarPairs4GpuKernel1( size_t k, // The maximum number of similar pairs to be stored for each cell. double similarityThreshold, // The minimum similarity for a pair to be stored. Lsh& lsh, SimilarPairs& similarPairs, CellId blockSize) { const CellId cellCount = lsh.cellCount(); // Vectors reused for each cell in the loop over cells below. vector<uint16_t> mismatchCounts(cellCount * blockSize); vector< pair<uint16_t, CellId> > neighbors; // pair(mismatchCount, cellId1) // Compute the threshold on the number of mismatches. const size_t mismatchCountThreshold = lsh.computeMismatchCountThresholdFromSimilarityThreshold(similarityThreshold); // Loop over all cells. lsh.setupGpuKernel1(mismatchCounts, blockSize); const auto t0 = std::chrono::steady_clock::now(); uint64_t blockId = 0; for(CellId cellId0Begin=0; cellId0Begin<cellCount; cellId0Begin+=blockSize, ++blockId) { if((blockId%1000) == 0) { cout << timestamp << " Working on cell " << cellId0Begin << " of " << cellCount << endl; } const CellId cellId0End = min(cellCount, cellId0Begin + blockSize); // Use gpuKernel0 to compute the number of mismatches // of cells in range [cellId0Begin, cellId0End) with all cells. // For efficient memory access in the GPU, the mismatch counts // for each cellId1 are stored contiguously, // with stride blockSize between consecutive values of cellId1. // const auto tA = std::chrono::steady_clock::now(); lsh.gpuKernel1(cellId0Begin, cellId0End); // const auto tB = std::chrono::steady_clock::now(); // Process the results for all the cellId0 values in this block. for(CellId cellId0=cellId0Begin; cellId0!=cellId0End; ++cellId0) { // const auto tt0 = std::chrono::steady_clock::now(); // Candidate neighbors are the ones where the number of mismatches is small. neighbors.clear(); // const auto tt1 = std::chrono::steady_clock::now(); for(CellId cellId1=0; cellId1!=cellCount; cellId1++) { if(cellId1 == cellId0) { continue; } const uint16_t mismatchCount = mismatchCounts[cellId1*blockSize + (cellId0-cellId0Begin)]; if(mismatchCount <= mismatchCountThreshold) { neighbors.push_back(make_pair(mismatchCount, cellId1)); } } // const auto tt2 = std::chrono::steady_clock::now(); // Only keep the k best neighbors, then sort them. // This is faster than sorting, then keeping the k best, // because it avoids doing a complete sorting of all of the neighbors. // Instead, keepBest uses std::nth_element, which does a partial sorting. keepBest(neighbors, k, std::less< pair<uint16_t, CellId> >()); // const auto tt3 = std::chrono::steady_clock::now(); sort(neighbors.begin(), neighbors.end()); // const auto tt4 = std::chrono::steady_clock::now(); // Store. for(const auto& neighbor: neighbors) { const CellId cellId1 = neighbor.second; const uint16_t mismatchCount = neighbor.first; const double similarity = lsh.getSimilarity(mismatchCount); similarPairs.addUnsymmetricNoCheck(cellId0, cellId1, similarity); } /* const auto tt5 = std::chrono::steady_clock::now(); cout << (tt1-tt0).count() << " "; cout << (tt2-tt1).count() << " "; cout << (tt3-tt2).count() << " "; cout << (tt4-tt3).count() << " "; cout << (tt5-tt4).count() << "\n"; */ } // const auto tC = std::chrono::steady_clock::now(); // cout << (tB-tA).count() << " " << (tC-tB).count() << "\n"; } const auto t1 = std::chrono::steady_clock::now(); const double t01 = 1.e-9 * double((std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0)).count()); cout << "Similar pairs computation on GPU took " << t01 << " s at "; cout << 1.e9*t01/(double(cellCount)*double(cellCount)) << " ns/pair" << endl; lsh.cleanupGpuKernel1(); } void ExpressionMatrix::findSimilarPairs4GpuKernel2( size_t k, // The maximum number of similar pairs to be stored for each cell. double similarityThreshold, // The minimum similarity for a pair to be stored. Lsh& lsh, SimilarPairs& similarPairs, CellId blockSize) { const CellId cellCount = lsh.cellCount(); // Compute the threshold on the number of mismatches. const size_t mismatchCountThreshold = lsh.computeMismatchCountThresholdFromSimilarityThreshold(similarityThreshold); // Vectors reused for each block in the loop below. vector<CellId> neighbors(k * (mismatchCountThreshold+1) * blockSize); vector<CellId> neighborCounts((mismatchCountThreshold+1) * blockSize); // Loop over blocks of cells. lsh.setupGpuKernel2(neighbors, neighborCounts, blockSize, k, mismatchCountThreshold); const auto t0 = std::chrono::steady_clock::now(); uint64_t blockId = 0; for(CellId cellId0Begin=0; cellId0Begin<cellCount; cellId0Begin+=blockSize, ++blockId) { if(true /*(blockId%1000) == 0*/) { cout << timestamp << " Working on cell " << cellId0Begin << " of " << cellCount << endl; } const CellId cellId0End = min(cellCount, cellId0Begin + blockSize); // Run GPU kernel 2 for this block. const auto tA = std::chrono::steady_clock::now(); lsh.gpuKernel2(cellId0Begin, cellId0End); const auto tB = std::chrono::steady_clock::now(); // Process the results of this block. // Loop over cells in this block. for(CellId cellId0=cellId0Begin; cellId0!=cellId0End; cellId0++) { // Pointers to the portions of the neighbors and neighborCounts // buffer that belong to this cell. const uint32_t* neighbors0 = neighbors.data() + k * (mismatchCountThreshold+1) * (cellId0-cellId0Begin); const uint32_t* neighborCounts0 = neighborCounts.data() + (mismatchCountThreshold+1) * (cellId0-cellId0Begin); // TGotal number of neighbors we already stored for this cell, // for all mismatch counts. size_t totalNeighborCount = 0; // Loop over mismatch counts. for(size_t mismatchCount=0; mismatchCount<=mismatchCountThreshold; mismatchCount++, neighbors0+=k, neighborCounts0++) { const double similarity = lsh.getSimilarity(mismatchCount); // Loop over neighbors for this mismatch count. for(size_t i=0; i<*neighborCounts0; i++) { const CellId cellId1 = neighbors0[i]; if(cellId1 == cellId0) { continue; } similarPairs.addUnsymmetricNoCheck(cellId0, cellId1, similarity); ++totalNeighborCount; if(totalNeighborCount == k) { break; } } if(totalNeighborCount == k) { break; } } } const auto tC = std::chrono::steady_clock::now(); cout << (tB-tA).count() << " " << (tC-tB).count() << endl; } const auto t1 = std::chrono::steady_clock::now(); const double t01 = 1.e-9 * double((std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0)).count()); cout << "Similar pairs computation on GPU took " << t01 << " s at "; cout << 1.e9*t01/(double(cellCount)*double(cellCount)) << " ns/pair" << endl; lsh.cleanupGpuKernel2(); } // GPU version of findSimilarPairs7. See Lsh.cl for details. void ExpressionMatrix::findSimilarPairs7Gpu( const string& geneSetName, // The name of the gene set to be used. const string& cellSetName, // The name of the cell set to be used. const string& lshName, // The name of the Lsh object to be used. const string& similarPairsName, // The name of the SimilarPairs object to be created. size_t k, // The maximum number of similar pairs to be stored for each cell. double similarityThreshold, // The minimum similarity for a pair to be stored. const vector<int>& lshSliceLengths, // The number of bits in each LSH signature slice, in decreasing order. CellId maxCheck, // Maximum number of candidate neighbors to consider for each cell. size_t log2BucketCount, CellId blockSize // The number of cells processed by each kernel instance on the GPU. ) { cout << timestamp << "ExpressionMatrix::findSimilarPairs7Gpu begins." << endl; const auto t0 = std::chrono::steady_clock::now(); // Locate the gene set and verify that it is not empty. const auto itGeneSet = geneSets.find(geneSetName); if(itGeneSet == geneSets.end()) { throw runtime_error("Gene set " + geneSetName + " does not exist."); } const GeneSet& geneSet = itGeneSet->second; if(geneSet.size() == 0) { throw runtime_error("Gene set " + geneSetName + " is empty."); } // Locate the cell set and verify that it is not empty. const auto& it = cellSets.cellSets.find(cellSetName); if(it == cellSets.cellSets.end()) { throw runtime_error("Cell set " + cellSetName + " does not exist."); } const MemoryMapped::Vector<CellId>& cellSet = *(it->second); const CellId cellCount = CellId(cellSet.size()); if(cellCount == 0) { throw runtime_error("Cell set " + cellSetName + " is empty."); } // Create the Lsh object that will do the computation. Lsh lsh(directoryName + "/Lsh-" + lshName); if(lsh.cellCount() != cellSet.size()) { throw runtime_error("LSH object " + lshName + " has a number of cells inconsistent with cell set " + cellSetName); } lsh.initializeGpu(); cout << "GPU computing will use " << lsh.getGpuName() << "." << endl; // Load the LSH signatures to the GPU. const auto t1 = std::chrono::steady_clock::now(); lsh.loadSignaturesToGpu(); const auto t2 = std::chrono::steady_clock::now(); const double t12 = 1.e-9 * double((std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1)).count()); cout << "Loading cell signatures to GPU took " << t12 << " s at "; cout << (double(cellCount)*double(lsh.wordCount())*sizeof(uint64_t) / (t12*1024.*1024.)) << " MB/s." << endl; // Create the SimilarPairs object that will store the results. SimilarPairs similarPairs(directoryName + "/SimilarPairs-" + similarPairsName, k, geneSet, cellSet); // Call the appropriate lower level function. // For now we only have kernel 3, but this allows for // alternate kernels, to facilitate experimenting. const int kernel = 3; switch(kernel) { case 3: findSimilarPairs7GpuKernel3( k, similarityThreshold, lsh, similarPairs, lshSliceLengths, maxCheck, size_t(blockSize), log2BucketCount); break; default: throw runtime_error( "Invalid kernel " + std::to_string(kernel) + " specified in findSimilarPairs7Gpu call. "); } const auto t3 = std::chrono::steady_clock::now(); const double t03 = 1.e-9 * double((std::chrono::duration_cast<std::chrono::nanoseconds>(t3 - t0)).count()); cout << timestamp << "ExpressionMatrix::findSimilarPairs7Gpu ends. Took " << t03 << " s." << endl; } void ExpressionMatrix::findSimilarPairs7GpuKernel3( size_t k, // The maximum number of similar pairs to be stored for each cell. double similarityThreshold, // The minimum similarity for a pair to be stored. Lsh& lsh, SimilarPairs& similarPairs, const vector<int>& lshSliceLengths, // The number of bits in each LSH signature slice, in decreasing order. CellId maxCheck, CellId blockSize, size_t log2BucketCount) { const CellId cellCount = lsh.cellCount(); const size_t lshBitCount = lsh.lshCount(); const size_t sliceLengthCount = lshSliceLengths.size(); const uint64_t bucketCount = (1ULL << log2BucketCount); const uint64_t bucketMask = bucketCount - 1ULL; // Compute the threshold on the number of mismatches. const size_t mismatchCountThreshold = lsh.computeMismatchCountThresholdFromSimilarityThreshold(similarityThreshold); // For each slice length and signature slice of that length, // each cell is assigned to a bucket // based on the value of its signature slice. // The cells in each bucket will be stored in // tables4[sliceLengthId][sliceId][bucketId], // where: // - sliceLengthId corresponds to the slice lengths to be used, // stored in lshSliceLengths in decreasing order. // - sliceId identifies the particular slice of that length // (we have a total lshBitCount bits, which can be used // to form lshBitCount/lshSliceLength possible signature // slices each lshSliceLength bits in length). // - bucketId identifies the bucket. vector< vector< vector< vector<CellId> > > > table4; // Vector to contain the signature bits of each signature slice. // Indexed by [sliceLengthId][sliceId]. vector< vector< vector< size_t > > > sliceBits3; // Assign cells to buckets. findSimilarPairs7AssignCellsToBuckets(lsh, lshSliceLengths, sliceBits3, table4, log2BucketCount); // Vectors reused for each block in the loop below. // Each of these corresponds to a buffer in the GPU. vector<CellId> neighbors(k * (mismatchCountThreshold+1) * blockSize); vector<CellId> neighborCounts((mismatchCountThreshold+1) * blockSize); vector<CellId> cellId1s(maxCheck * blockSize); vector<CellId> cellId1Counts(blockSize); // Set up corresponding buffers in the GPU. cout << timestamp << "Setting up buffers in the GPU." << endl; lsh.setupGpuKernel3( k, mismatchCountThreshold, maxCheck, blockSize, cellId1s, cellId1Counts, neighbors, neighborCounts); // Bit set to keep track which cellId1 cells we have already // added as a candidate neighbor, for a given cellId0. BitSet cellMap(cellCount); // Loop over blocks of cells. cout << timestamp << "Similar pairs computation begins." << endl; const auto t0 = std::chrono::steady_clock::now(); uint64_t blockId = 0; for(CellId cellId0Begin=0; cellId0Begin<cellCount; cellId0Begin+=blockSize, ++blockId) { const auto tA = std::chrono::steady_clock::now(); if(true /*(blockId%1000) == 0*/) { cout << timestamp << " Working on cell " << cellId0Begin << " of " << cellCount << endl; } const CellId cellId0End = min(cellCount, cellId0Begin + blockSize); // Find the candidate neighbor cellId1s for each value of cellId0 in this block. // For each cell, look at cells in the same bucket. for(CellId cellId0=cellId0Begin; cellId0!=cellId0End; cellId0++) { const size_t i0 = cellId0 - cellId0Begin; CellId count0 = 0; CellId* const candidates0 = cellId1s.data() + maxCheck * i0; const BitSetPointer signature = lsh.getSignature(cellId0); // Loop over slice lengths. for(size_t sliceLengthId=0; sliceLengthId<sliceLengthCount; sliceLengthId++) { const auto& table3 = table4[sliceLengthId]; const auto& sliceBits2 = sliceBits3[sliceLengthId]; // Extract the slice length. const size_t sliceLength = lshSliceLengths[sliceLengthId]; // Compute the number of possible slices for this length. const size_t sliceCount = lshBitCount / sliceLength; // Loop over all possible signature slices of this length. for(size_t sliceId=0; sliceId<sliceCount; sliceId++) { // const auto tt0 = std::chrono::steady_clock::now(); const auto& table2 = table3[sliceId]; const auto& sliceBits1 = sliceBits2[sliceId]; // Extract this signature slice for this cell. const uint64_t signatureSlice = signature.getBits(sliceBits1); // Find the bucket that corresponds to this signature slice. const uint64_t bucketId = (sliceLength<log2BucketCount) ? signatureSlice : (MurmurHash64A(&signatureSlice, 8, 231) & bucketMask); CZI_ASSERT(bucketId < table2.size()); const auto& table1 = table2[bucketId]; // Loop over cells in the same bucket. for(const CellId cellId1: table1) { if(cellId1 == cellId0){ continue; } if(cellMap.get(cellId1)) { continue; // We already added this one. } cellMap.set(cellId1); candidates0[count0++] = cellId1; if(count0 == maxCheck) { break; } } if(count0 == maxCheck) { break; } } if(count0 == maxCheck) { break; } } // Store the number of candidate neighbors. cellId1Counts[i0] = count0; // Clean up our bit set so we can reuse it for the next cell. for(size_t i1=0; i1<count0; i1++) { cellMap.clear(candidates0[i1]); } } // Run GPU kernel 3 for this block. const auto tB = std::chrono::steady_clock::now(); lsh.gpuKernel3(cellId0Begin, cellId0End); const auto tC = std::chrono::steady_clock::now(); // Process the results of this block. // Loop over cells in this block. for(CellId cellId0=cellId0Begin; cellId0!=cellId0End; cellId0++) { // Pointers to the portions of the neighbors and neighborCounts // buffer that belong to this cell. const uint32_t* neighbors0 = neighbors.data() + k * (mismatchCountThreshold+1) * (cellId0-cellId0Begin); const uint32_t* neighborCounts0 = neighborCounts.data() + (mismatchCountThreshold+1) * (cellId0-cellId0Begin); // Total number of neighbors we already stored for this cell, // for all mismatch counts. size_t totalNeighborCount = 0; // Loop over mismatch counts. for(size_t mismatchCount=0; mismatchCount<=mismatchCountThreshold; mismatchCount++, neighbors0+=k, neighborCounts0++) { const double similarity = lsh.getSimilarity(mismatchCount); // Loop over neighbors for this mismatch count. for(size_t i=0; i<*neighborCounts0; i++) { const CellId cellId1 = neighbors0[i]; if(cellId1 == cellId0) { continue; } similarPairs.addUnsymmetricNoCheck(cellId0, cellId1, similarity); ++totalNeighborCount; if(totalNeighborCount == k) { break; } } if(totalNeighborCount == k) { break; } } } const auto tD = std::chrono::steady_clock::now(); cout << (tB-tA).count() << " " << (tC-tB).count() << " " << (tD-tC).count() << endl; } const auto t1 = std::chrono::steady_clock::now(); const double t01 = 1.e-9 * double((std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0)).count()); cout << timestamp << "Similar pairs computation on GPU took " << t01 << " s at "; cout << 1.e9*t01/(double(cellCount)*double(cellCount)) << " ns/pair" << endl; lsh.cleanupGpuKernel3(); } #endif
44.23511
122
0.616753
[ "object", "vector" ]
1a9d7a5aca20b70ebba52d74d144531007237089
8,230
cpp
C++
src/data/datasets/datasettensor.cpp
mhough/braingl
53e2078adc10731ee62feec11dcb767c4c6c0d35
[ "MIT" ]
5
2016-03-17T07:02:11.000Z
2021-12-12T14:43:58.000Z
src/data/datasets/datasettensor.cpp
mhough/braingl
53e2078adc10731ee62feec11dcb767c4c6c0d35
[ "MIT" ]
null
null
null
src/data/datasets/datasettensor.cpp
mhough/braingl
53e2078adc10731ee62feec11dcb767c4c6c0d35
[ "MIT" ]
3
2015-10-29T15:21:01.000Z
2020-11-25T09:41:21.000Z
/* * dataset3d.cpp * * Created on: May 9, 2012 * @author Ralph Schurade */ #include "datasettensor.h" #include "../models.h" #include "../../algos/fmath.h" #include "../../gui/gl/tensorrenderer.h" #include "../../gui/gl/tensorrendererev.h" DatasetTensor::DatasetTensor( QDir filename, std::vector<Matrix> data, nifti_image* header ) : DatasetNifti( filename, Fn::DatasetType::NIFTI_TENSOR, header ), m_data( data ), m_logData( 0 ), m_renderer( 0 ), m_rendererEV( 0 ), m_renderGlpyhs( false ) { m_properties["maingl"].createFloat( Fn::Property::D_FA_THRESHOLD, 0.01f, 0.0f, 1.0f, "general" ); m_properties["maingl"].createFloat( Fn::Property::D_EV_THRESHOLD, 10.0f, 0.0f, 10.f, "general" ); m_properties["maingl"].createFloat( Fn::Property::D_GAMMA, 0.1f, 0.0f, 10.0f, "general" ); m_properties["maingl"].createFloat( Fn::Property::D_OFFSET, 0.0f, -1.0f, 1.0f, "general" ); m_properties["maingl"].createFloat( Fn::Property::D_SCALING, 0.5f, 0.0f, 2.0f, "general" ); m_properties["maingl"].createList( Fn::Property::D_TENSOR_RENDERMODE, { "superquadric", "1st ev", "2nd ev", "3rd ev" }, 0, "general" ); m_properties["maingl"].createBool( Fn::Property::D_RENDER_SAGITTAL, false, "general" ); m_properties["maingl"].createBool( Fn::Property::D_RENDER_CORONAL, false, "general" ); m_properties["maingl"].createBool( Fn::Property::D_RENDER_AXIAL, true, "general" ); examineDataset(); PropertyGroup props2( m_properties["maingl"] ); m_properties.insert( "maingl2", props2 ); m_properties["maingl2"].getProperty( Fn::Property::D_ACTIVE )->setPropertyTab( "general" ); } DatasetTensor::DatasetTensor( QDir filename, std::vector<std::vector<float> > data, nifti_image* header ) : DatasetNifti( filename, Fn::DatasetType::NIFTI_TENSOR, header ), m_renderer( 0 ), m_rendererEV( 0 ), m_renderGlpyhs( false ) { for ( unsigned int i = 0; i < data.size(); ++i ) { Matrix m( 3, 3 ); m( 1, 1 ) = data.at( i )[0]; m( 1, 2 ) = data.at( i )[1]; m( 1, 3 ) = data.at( i )[2]; m( 2, 1 ) = data.at( i )[1]; m( 2, 2 ) = data.at( i )[3]; m( 2, 3 ) = data.at( i )[4]; m( 3, 1 ) = data.at( i )[2]; m( 3, 2 ) = data.at( i )[4]; m( 3, 3 ) = data.at( i )[5]; m_data.push_back( m ); } m_properties["maingl"].createInt( Fn::Property::D_CREATED_BY, (int)Fn::Algo::TENSORFIT ); m_properties["maingl"].createFloat( Fn::Property::D_FA_THRESHOLD, 0.01f, 0.0f, 1.0f, "general" ); m_properties["maingl"].createFloat( Fn::Property::D_EV_THRESHOLD, 10.0f, 0.0f, 10.f, "general" ); m_properties["maingl"].createFloat( Fn::Property::D_GAMMA, 0.1f, 0.0f, 10.0f, "general" ); m_properties["maingl"].createFloat( Fn::Property::D_OFFSET, 0.0f, -0.5f, 0.5f, "general" ); m_properties["maingl"].createFloat( Fn::Property::D_SCALING, 0.5f, 0.0f, 2.0f, "general" ); m_properties["maingl"].createInt( Fn::Property::D_TENSOR_RENDERMODE, 0, 0, 3, "general" ); m_properties["maingl"].createBool( Fn::Property::D_RENDER_SAGITTAL, false, "general" ); m_properties["maingl"].createBool( Fn::Property::D_RENDER_CORONAL, false, "general" ); m_properties["maingl"].createBool( Fn::Property::D_RENDER_AXIAL, true, "general" ); examineDataset(); PropertyGroup props2( m_properties["maingl"] ); m_properties.insert( "maingl2", props2 ); m_properties["maingl2"].getProperty( Fn::Property::D_ACTIVE )->setPropertyTab( "general" ); } DatasetTensor::~DatasetTensor() { m_data.clear(); } void DatasetTensor::examineDataset() { int nx = m_properties["maingl"].get( Fn::Property::D_NX ).toInt(); int ny = m_properties["maingl"].get( Fn::Property::D_NY ).toInt(); int nz = m_properties["maingl"].get( Fn::Property::D_NZ ).toInt(); int size = nx * ny * nz; m_properties["maingl"].createInt( Fn::Property::D_SIZE, static_cast<int>( 9 * size * sizeof(float) ) ); m_properties["maingl"].createFloat( Fn::Property::D_LOWER_THRESHOLD, m_properties["maingl"].get( Fn::Property::D_MIN ).toFloat() ); m_properties["maingl"].createFloat( Fn::Property::D_UPPER_THRESHOLD, m_properties["maingl"].get( Fn::Property::D_MAX ).toFloat() ); m_properties["maingl"].createInt( Fn::Property::D_RENDER_SLICE, 1 ); m_properties["maingl"].createFloat( Fn::Property::D_SCALING, 1.0f ); m_properties["maingl"].createInt( Fn::Property::D_DIM, 9 ); float min = std::numeric_limits<float>::max(); float max = std::numeric_limits<float>::min(); for ( int i = 0; i < size; ++i ) { min = qMin( min, (float) m_data.at( i )( 1, 1 ) ); max = qMax( max, (float) m_data.at( i )( 1, 1 ) ); min = qMin( min, (float) m_data.at( i )( 1, 2 ) ); max = qMax( max, (float) m_data.at( i )( 1, 2 ) ); min = qMin( min, (float) m_data.at( i )( 1, 3 ) ); max = qMax( max, (float) m_data.at( i )( 1, 3 ) ); min = qMin( min, (float) m_data.at( i )( 2, 2 ) ); max = qMax( max, (float) m_data.at( i )( 2, 2 ) ); min = qMin( min, (float) m_data.at( i )( 2, 3 ) ); max = qMax( max, (float) m_data.at( i )( 2, 3 ) ); min = qMin( min, (float) m_data.at( i )( 3, 3 ) ); max = qMax( max, (float) m_data.at( i )( 3, 3 ) ); } m_properties["maingl"].createFloat( Fn::Property::D_MIN, min ); m_properties["maingl"].createFloat( Fn::Property::D_MAX, max ); } void DatasetTensor::createTexture() { } std::vector<Matrix>* DatasetTensor::getData() { return &m_data; } std::vector<Matrix>* DatasetTensor::getLogData() { if ( m_logData.empty() ) { createLogTensors(); } return &m_logData; } void DatasetTensor::createLogTensors() { qDebug() << "create log tensors..."; int blockSize = m_data.size(); m_logData.resize( blockSize ); std::vector<QVector3D> evec1( blockSize ); std::vector<float> eval1( blockSize ); std::vector<QVector3D> evec2( blockSize ); std::vector<float> eval2( blockSize ); std::vector<QVector3D> evec3( blockSize ); std::vector<float> eval3( blockSize ); FMath::evecs( m_data, evec1, eval1, evec2, eval2, evec3, eval3 ); //log(M) =Ulog(D)UT Matrix U(3,3); DiagonalMatrix D(3); Matrix logM(3,3); for ( unsigned int i = 0; i < m_logData.size(); ++i ) { U( 1, 1 ) = evec1[i].x(); U( 2, 1 ) = evec1[i].y(); U( 3, 1 ) = evec1[i].z(); U( 1, 2 ) = evec2[i].x(); U( 2, 2 ) = evec2[i].y(); U( 3, 2 ) = evec2[i].z(); U( 1, 3 ) = evec3[i].x(); U( 2, 3 ) = evec3[i].y(); U( 3, 3 ) = evec3[i].z(); D(1) = log( eval1[i] ); D(2) = log( eval2[i] ); D(3) = log( eval3[i] ); logM = U*D*U.t(); m_logData[i] = logM; } qDebug() << "create log tensors done!"; } void DatasetTensor::draw( QMatrix4x4 pMatrix, QMatrix4x4 mvMatrix, int width, int height, int renderMode, QString target ) { if ( !properties( target ).get( Fn::Property::D_ACTIVE ).toBool() ) { return; } if ( properties( target ).get( Fn::Property::D_TENSOR_RENDERMODE ).toInt() == 0 ) { if ( m_renderer == 0 ) { m_renderer = new TensorRenderer( &m_data ); m_renderer->init(); } m_renderer->draw( pMatrix, mvMatrix, width, height, renderMode, properties( target ) ); } else { if ( m_rendererEV == 0 ) { m_rendererEV = new TensorRendererEV( &m_data ); m_rendererEV->init(); } m_rendererEV->draw( pMatrix, mvMatrix, width, height, renderMode, properties( target ) ); } } QString DatasetTensor::getValueAsString( int x, int y, int z ) { Matrix data = m_data.at( getId( x, y, z ) ); QString out( "" ); out += QString::number( data( 1, 1 ) ) + ", " + QString::number( data( 2, 2 ) ) + ", " + QString::number( data( 3, 3 ) ) + ", " + QString::number( data( 1, 2 ) ) + ", " + QString::number( data( 1, 3 ) ) + ", " + QString::number( data( 2, 3 ) ); return out; } void DatasetTensor::flipX() { } void DatasetTensor::flipY() { } void DatasetTensor::flipZ() { }
34.008264
139
0.590036
[ "vector" ]
1aa4ac34c76862c5c12db3dea8b033868460e37f
16,192
cpp
C++
mcp/src/include_manager.cpp
mvidelgauz/ferret
3da27b1020e23d9f01a36a410622cdbad7e46b70
[ "MIT" ]
null
null
null
mcp/src/include_manager.cpp
mvidelgauz/ferret
3da27b1020e23d9f01a36a410622cdbad7e46b70
[ "MIT" ]
null
null
null
mcp/src/include_manager.cpp
mvidelgauz/ferret
3da27b1020e23d9f01a36a410622cdbad7e46b70
[ "MIT" ]
null
null
null
#include <iostream> #include <cassert> #include <cstdlib> #include <sstream> #include "include_manager.h" #include "glob_utility.h" #include "engine.h" #include "base_node.h" #include "hash_set.h" using namespace std; static bool isCppFile( const string &ext ) { return ext == ".cpp" || ext == ".c" || ext == ".cc" || ext == ".h" || ext == ".hpp" || ext == ".C" || ext == ".cxx"; // || // ext == ".nsmap"; } // ----------------------------------------------------------------------------- IncludeManager *IncludeManager::theIncludeManager = 0; IncludeManager *IncludeManager::getTheIncludeManager() { if( theIncludeManager == 0 ) theIncludeManager = new IncludeManager; return theIncludeManager; } IncludeManager::IncludeManager() : fileRemoved(false) { unsat_set = new_hash_set( 101 ); } void IncludeManager::readUnsatSet( bool initMode ) { unsat_set_fn = stackPath( dbProjDir, "ferret_unsat"); if( !initMode ) { FILE *fp = fopen( unsat_set_fn.c_str(), "r"); if( fp ) { hash_set_read( fp, unsat_set); fclose( fp ); } } } void IncludeManager::createMissingDepFiles( FileManager &fileDb, Executor &executor, bool printTimes) { FileMap::Iterator it; while( fileDb.hasNext( it ) ) { const BaseNode *node = it.getBaseNode(); if( node ) { string dummy, bn, ext; breakPath( it.getFile(), dummy, bn, ext); if( isCppFile( ext ) ) { if( blockedIds.find( it.getId() ) != blockedIds.end() ) { if( verbosity > 0 ) cout << "inc mananger dep file for '" << it.getFile() << "' blocked.\n"; } else { string depfn = tempDepDir + "/" + node->getDir() + "/" + bn + ".d"; if( uniqueBasenames.find( bn ) == uniqueBasenames.end() ) uniqueBasenames[ bn ] = it.getId(); else uniqueBasenames[ bn ] = -1; // found it twice bool do_dep = false; if( FindFiles::exists( depfn ) ) { if( !FindFiles::exists( it.getFile() ) ) do_dep = false; else { File f = FindFiles::getCachedFile( it.getFile() ); File depFile = FindFiles::getCachedFile( depfn ); if( f.isNewerThan( depFile ) ) do_dep = true; } } else if( FindFiles::exists( it.getFile() ) ) { mkdir_p( tempDepDir + "/" + node->getDir() ); do_dep = true; } else do_dep = false; if( do_dep ) { vector<string> args; args.push_back( it.getFile() ); args.push_back( depfn ); ExecutorCommand ec = ExecutorCommand( args ); ec.addFileToRemoveAfterSignal( depfn ); FindFiles::remove( depfn.c_str() ); depEngine.addDepCommand( ec ); filesWithUpdate.push_back( it.getFile() ); depFilesWithUpdate.push_back( depfn ); hash_set_add( unsat_set, it.getId()); } } } } } if( filesWithUpdate.size() > 0 ) { if( verbosity > 0 ) cout << "inc mananger " << filesWithUpdate.size() << " dep file missing or needs update.\n"; depEngine.doWork( executor, printTimes); // create all missing .d files } } void IncludeManager::resolve( FileManager &fileDb, bool initMode, bool writeIgnHdr) { if( !writeIgnHdr ) { FILE *fp = fopen( "ferret_ignhdr", "r"); if( fp ) { while( !feof( fp ) ) { char buf[512]; if( fscanf( fp, "%511s\n", buf) != EOF ) ignoreHeaders.insert( string(buf) ); else break; } fclose( fp ); } } if( initMode ) readDepFiles( fileDb, writeIgnHdr); if( hash_set_get_size( unsat_set ) > 0 ) { unsigned int i, s; int *a = hash_set_get_as_array( unsat_set, &s); for( i = 0; i < s; i++) { file_id_t from_id = a[i]; if( fileDb.hasId( from_id ) && blockedIds.find( from_id ) == blockedIds.end() ) { string from_fn = fileDb.getFileForId( from_id ); BaseNode *node = fileDb.getBaseNodeFor( from_id ); if( node ) { string dummy, bn, ext; breakPath( from_fn, dummy, bn, ext); string depfn = tempDepDir + "/" + node->getDir() + "/" + bn + ".d"; const map<string,Seeker>::const_iterator &mit = seekerMap.find( from_fn ); int notFound = 0; if( mit != seekerMap.end() ) { if( mit->second.lookingFor.size() > 0 ) { resolveFile( fileDb, from_id, mit->second, writeIgnHdr, notFound); } else hash_set_remove( unsat_set, from_id); } else if( readDepFile( from_fn, depfn, node) > 0 ) resolveFile( fileDb, from_id, seekerMap.at( from_fn ), writeIgnHdr, notFound); if( notFound == 0 ) hash_set_remove( unsat_set, from_id); } } else hash_set_remove( unsat_set, from_id); } free( a ); } if( writeIgnHdr ) { FILE *fp = fopen( "ferret_ignhdr", "w"); if( fp ) { set<string>::const_iterator ihit = ignoreHeaders.begin(); for( ; ihit != ignoreHeaders.end(); ihit++) fprintf( fp, "%s\n", ihit->c_str()); fclose( fp ); } } FILE *fp = fopen( unsat_set_fn.c_str(), "w"); if( fp ) { hash_set_write( fp, unsat_set); fclose( fp ); } const unsigned int treshold = 10; stringstream fw; if( hash_set_get_size( unsat_set ) > 0 ) { unsigned int i, s; int *a = hash_set_get_as_array( unsat_set, &s); fw << "File(s) with unmet dependencies (listing at most " << treshold << "):\n"; for( i = 0; i < s && i < treshold; i++) { file_id_t id = a[i]; if( fileDb.hasId( id ) ) fw << " " << fileDb.getFileForId( id ) << "\n"; else fw << " ???" << "\n"; } free( a ); } if( hash_set_get_size( unsat_set ) > (int)treshold ) { fw << "\nYou have more than " << treshold << " source files with unsatisfied dependencies. So, either\n" << "these are real and have to be fixed, or use --ignhdr once.\n" << "Using --ignhdr every time you call ferret will break the dependency analysis.\n\n"; } finalWords = fw.str(); } void IncludeManager::printFinalWords() const { cout << finalWords; } int IncludeManager::readDepFile( const string &fn, const string &depfn, const BaseNode *node) { int entries = 0; FILE *fp = fopen( depfn.c_str(), "r"); if( fp ) { ParseDep pd( fp ); if( verbosity > 0 ) cout << "Reading dependency file " << depfn << " ...\n"; pd.parse(); fclose( fp ); const vector<DepFileEntry> dfe = pd.getDepEntries(); size_t j; for( j = 0; j < dfe.size(); j++) // should be only one { const DepFileEntry &df = dfe[j]; if( fn != df.target ) cerr << "warning: unexpected target file name in dependency file '" << df.target << "', expected '" << fn << "'\n"; addSeeker( fn, node->getSrcDir(), node->searchIncDirs, // it.getFile() should be equal to df.target df.depIncludes); entries++; } } else cerr << "error: could not open dependency file '" << depfn << "'\n"; return entries; } bool IncludeManager::readDepFiles( FileManager &fileDb, bool writeIgnHdr) { FileMap::Iterator it; while( fileDb.hasNext( it ) ) { const BaseNode *node = it.getBaseNode(); if( node ) { string dummy, bn, ext; breakPath( it.getFile(), dummy, bn, ext); //string cmd = it.getCmd(); if( isCppFile( ext ) ) { if( blockedIds.find( it.getId() ) != blockedIds.end() ) { if( verbosity > 0 ) cout << "Includes from '" << it.getFile() << "' blocked.\n"; } else if( seekerMap.find( it.getFile() ) == seekerMap.end() ) { string depfn = tempDepDir + "/" + node->getDir() + "/" + bn + ".d"; if( FindFiles::existsUncached( depfn ) ) { readDepFile( it.getFile(), depfn, node); hash_set_add( unsat_set, it.getId()); } else cerr << "warning: file " << depfn << " must exist at this point.\n"; } } } } return true; } void IncludeManager::addSeeker( const string &from, const string &localDir, const vector<string> &searchIncDirs, const vector<string> &lookingFor) { assert( from != "" ); map<string,Seeker>::iterator mit = seekerMap.find( from ); if( mit != seekerMap.end() ) { Seeker &s = mit->second; if( verbosity > 1 ) cout << "inc mananger seeker '" << from << "' additionally looking for " << join( ", ", lookingFor, false) << ".\n"; for( size_t i = 0; i < lookingFor.size(); i++) if( localDir != searchIncDirs[i] ) s.lookingFor.push_back( lookingFor[i] ); } else { Seeker s; s.from = from; s.lookingFor = lookingFor; s.searchIncDirs.push_back( localDir ); for( size_t i = 0; i < searchIncDirs.size(); i++) if( localDir != searchIncDirs[i] ) s.searchIncDirs.push_back( searchIncDirs[i] ); seekerMap[ from ] = s; if( verbosity > 1 ) { cout << "inc mananger adding new seeker '" << s.from << "'.\n"; cout << "inc mananger seeker '" << s.from << "' looking for " << join( ", ", s.lookingFor, false) << ".\n"; if( verbosity > 2 ) { cout << "inc mananger '" << s.from << "' seeking in"; cout << " " << join( ", ", s.searchIncDirs, false); cout << "\n"; } } } } void IncludeManager::addBlockedId( file_id_t id ) { blockedIds.insert( id ); } void IncludeManager::addBlockedIds( const set<file_id_t> &blids ) { blockedIds.insert( blids.begin(), blids.end()); } void IncludeManager::removeFile( FileManager &fileDb, file_id_t id, const string &fn, const BaseNode *node, const set<file_id_t> &prereqs) { string dummy, bn, ext; breakPath( fn, dummy, bn, ext); string depfn = tempDepDir + "/" + node->getDir() + "/" + bn + ".d"; fileRemoved = true; if( verbosity > 0 ) cout << "Removing dep file " << depfn << "\n"; ::remove( depfn.c_str() ); hash_set_remove( unsat_set, id); set<file_id_t>::const_iterator sit = prereqs.begin(); for( ; sit != prereqs.end(); sit++) { file_id_t pre_id = *sit; if( fileDb.getCmdForId( pre_id ) == "D" ) { hash_set_add( unsat_set, pre_id); } } } set<string> blockDoubleWarn; bool IncludeManager::resolveFile( FileManager &fileDb, file_id_t from_id, const Seeker &s, bool writeIgnHdr, int &notFound) { hash_set_t *new_deps_set = new_hash_set( 37 ); size_t i,j; notFound = 0; for( i = 0; i < s.lookingFor.size(); i++) { string lookingFor = s.lookingFor[i]; if( lookingFor != "" && lookingFor[0] != '/' ) { int found = 0; for( j = 0; j < s.searchIncDirs.size(); j++) // order matters { string tryfn = stackPath( s.searchIncDirs[j], lookingFor); file_id_t to_id = fileDb.getIdForFile( tryfn ); if( to_id != -1 ) { if( !fileDb.hasBlockedDependency( from_id, to_id) && found == 0 ) hash_set_add( new_deps_set, to_id); found++; if( verbosity > 1 ) cout << "inc mananger resolved dep " << fileDb.getFileForId( from_id ) << " (" << from_id << ") -> " << tryfn << " (" << to_id << ")\n"; if( !show_info ) break; // first wins } } if( show_info && found > 1 ) cout << "info: include '" << lookingFor << "' found more than once, for " << fileDb.getFileForId( from_id ) << "\n"; if( found == 0 ) { // try "guessing" the header in case the looked for file name is unique map<string,file_id_t>::const_iterator lgit = uniqueBasenames.find( lookingFor ); if( lgit != uniqueBasenames.end() && lgit->second != -1 ) { file_id_t to_id = lgit->second; if( !fileDb.hasBlockedDependency( from_id, to_id) ) hash_set_add( new_deps_set, to_id); found++; if( verbosity > 1 ) cout << "inc mananger resolved dep " << fileDb.getFileForId( from_id ) << " (" << from_id << ") -> " << fileDb.getFileForId( to_id ) << " (" << to_id << ") but only by using the unique basename technique\n"; } } if( found == 0 ) { if( ignoreHeaders.find( lookingFor ) == ignoreHeaders.end() ) { notFound++; if( blockDoubleWarn.find( lookingFor ) == blockDoubleWarn.end() ) { cerr << "warning: " << s.from << " includes " << lookingFor << ", but ferret wasn't able to find it.\n"; blockDoubleWarn.insert( lookingFor ); } if( writeIgnHdr ) ignoreHeaders.insert( lookingFor ); } } } } bool repl = fileDb.compareAndReplaceDependencies( from_id, new_deps_set); if( repl ) cout << "Replaced dependencies for '" << s.from << "'.\n"; delete_hash_set( new_deps_set ); return repl; }
32
138
0.443738
[ "vector" ]
1ab16749b856f5f32db73d4720f2f229925a2dc1
3,315
cpp
C++
Samples/Win32/ThunderRumble/Common/MineProjectile.cpp
yazhenchua/PlayFab-Samples
85d1d252bd21d050575c382628caa6d0c9785ff7
[ "MIT" ]
160
2016-05-26T09:30:20.000Z
2022-03-31T08:05:56.000Z
Samples/Win32/ThunderRumble/Common/MineProjectile.cpp
srivers8424/PlayFab-Samples
9fe465858e7f9bae3250dfe77d4500bb57d9e7fd
[ "MIT" ]
17
2016-03-22T17:37:16.000Z
2021-11-20T23:20:07.000Z
Samples/Win32/ThunderRumble/Common/MineProjectile.cpp
srivers8424/PlayFab-Samples
9fe465858e7f9bae3250dfe77d4500bb57d9e7fd
[ "MIT" ]
204
2016-05-14T22:46:51.000Z
2022-03-04T00:45:56.000Z
//-------------------------------------------------------------------------------------- // MineProjectile.cpp // // Advanced Technology Group (ATG) // Copyright (C) Microsoft Corporation. All rights reserved. //-------------------------------------------------------------------------------------- #include "pch.h" #include "MineProjectile.h" #include "Managers.h" #include "Ship.h" using namespace ThunderRumble; using namespace DirectX; namespace { /// The initial life of this projectile. constexpr float c_initialLife = 150.0f; /// The initial speed of this projectile. constexpr float c_initialSpeed = 80.0f; /// The amount of drag applied to velocity per second, /// as a percentage of velocity. constexpr float c_dragPerSecond = 0.9f; /// The radians-per-second that this object rotates at. constexpr float c_rotationRadiansPerSecond = 1.0f; } MineProjectile::MineProjectile(std::shared_ptr<Ship> owner, DirectX::SimpleMath::Vector2 direction) : Projectile(owner, direction), anchored(false) { // set the gameplay data Velocity.x = c_initialSpeed * direction.x; Velocity.y = c_initialSpeed * direction.y; // set the collision data Radius = 10.0f; Mass = 5.0f; // set the projectile data m_duration = 20.0f; m_damageAmount = 200.0f; m_damageRadius = 300.0f; m_damageOwner = false; Life = c_initialLife; m_texture = Managers::Get<ContentManager>()->LoadTexture(L"Assets\\Textures\\mine.png"); } MineProjectile::~MineProjectile() { } void MineProjectile::Update(float elapsedTime) { Projectile::Update(elapsedTime); Velocity.x -= Velocity.x * elapsedTime * c_dragPerSecond; Velocity.y -= Velocity.y * elapsedTime * c_dragPerSecond; // once mines near stop after their initial release, they become anchored and unmovable if (!anchored) { float speedSquared = 0.0f; XMStoreFloat(&speedSquared, XMVector2LengthSq(XMLoadFloat2(&Velocity))); if (speedSquared < 100.0f) { anchored = true; } } if (anchored) { Velocity.x = 0.0f; Velocity.y = 0.0f; } Rotation += elapsedTime * c_rotationRadiansPerSecond; } void MineProjectile::Draw(float elapsedTime, std::shared_ptr<RenderContext> renderContext) { // ignore the parameter color if we have an owner GameplayObject::Draw(elapsedTime, renderContext, m_texture, (anchored && m_owner != nullptr) ? m_owner->Color : Colors::White); } bool MineProjectile::TakeDamage(std::shared_ptr<GameplayObject> source, float damageAmount) { if (source->GetType() == GameplayObjectType::Projectile) { Life -= damageAmount; } else { Life = 0.0f; } if (Life <= 0.0f) { Die(source, false); } return true; } void MineProjectile::Die(std::shared_ptr<GameplayObject> source, bool cleanupOnly) { if (m_active) { if (!cleanupOnly) { // play the mine explosion sound Managers::Get<AudioManager>()->PlaySound(L"explosion_large"); // display the mine explosion Managers::Get<ParticleEffectManager>()->SpawnEffect(ParticleEffectType::MineExplosion, Position); } } Projectile::Die(source, cleanupOnly); }
25.898438
131
0.625943
[ "object" ]
1acab83eb466e23deaf51e6498c69ea82874b2ce
2,178
cpp
C++
clients/cpp-tizen/generated/src/ClockDifference.cpp
cliffano/jenkins-api-clients-generator
522d02b3a130a29471df5ec1d3d22c822b3d0813
[ "MIT" ]
23
2017-08-01T12:25:26.000Z
2022-01-25T03:44:11.000Z
clients/cpp-tizen/generated/src/ClockDifference.cpp
cliffano/jenkins-api-clients-generator
522d02b3a130a29471df5ec1d3d22c822b3d0813
[ "MIT" ]
35
2017-06-14T03:28:15.000Z
2022-02-14T10:25:54.000Z
clients/cpp-tizen/generated/src/ClockDifference.cpp
cliffano/jenkins-api-clients-generator
522d02b3a130a29471df5ec1d3d22c822b3d0813
[ "MIT" ]
11
2017-08-31T19:00:20.000Z
2021-12-19T12:04:12.000Z
#include <map> #include <cstdlib> #include <glib-object.h> #include <json-glib/json-glib.h> #include "Helpers.h" #include "ClockDifference.h" using namespace std; using namespace Tizen::ArtikCloud; ClockDifference::ClockDifference() { //__init(); } ClockDifference::~ClockDifference() { //__cleanup(); } void ClockDifference::__init() { //_class = std::string(); //diff = int(0); } void ClockDifference::__cleanup() { //if(_class != NULL) { // //delete _class; //_class = NULL; //} //if(diff != NULL) { // //delete diff; //diff = NULL; //} // } void ClockDifference::fromJson(char* jsonStr) { JsonObject *pJsonObject = json_node_get_object(json_from_string(jsonStr,NULL)); JsonNode *node; const gchar *_classKey = "_class"; node = json_object_get_member(pJsonObject, _classKey); if (node !=NULL) { if (isprimitive("std::string")) { jsonToValue(&_class, node, "std::string", ""); } else { } } const gchar *diffKey = "diff"; node = json_object_get_member(pJsonObject, diffKey); if (node !=NULL) { if (isprimitive("int")) { jsonToValue(&diff, node, "int", ""); } else { } } } ClockDifference::ClockDifference(char* json) { this->fromJson(json); } char* ClockDifference::toJson() { JsonObject *pJsonObject = json_object_new(); JsonNode *node; if (isprimitive("std::string")) { std::string obj = getClass(); node = converttoJson(&obj, "std::string", ""); } else { } const gchar *_classKey = "_class"; json_object_set_member(pJsonObject, _classKey, node); if (isprimitive("int")) { int obj = getDiff(); node = converttoJson(&obj, "int", ""); } else { } const gchar *diffKey = "diff"; json_object_set_member(pJsonObject, diffKey, node); node = json_node_alloc(); json_node_init(node, JSON_NODE_OBJECT); json_node_take_object(node, pJsonObject); char * ret = json_to_string(node, false); json_node_free(node); return ret; } std::string ClockDifference::getClass() { return _class; } void ClockDifference::setClass(std::string _class) { this->_class = _class; } int ClockDifference::getDiff() { return diff; } void ClockDifference::setDiff(int diff) { this->diff = diff; }
16.014706
80
0.668962
[ "object" ]
1ad4bed618e361e83e33017d1c4348c781a26984
686
cpp
C++
data/train/cpp/1ad4bed618e361e83e33017d1c4348c781a26984ModelNode.cpp
harshp8l/deep-learning-lang-detection
2a54293181c1c2b1a2b840ddee4d4d80177efb33
[ "MIT" ]
84
2017-10-25T15:49:21.000Z
2021-11-28T21:25:54.000Z
data/train/cpp/1ad4bed618e361e83e33017d1c4348c781a26984ModelNode.cpp
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
5
2018-03-29T11:50:46.000Z
2021-04-26T13:33:18.000Z
data/train/cpp/1ad4bed618e361e83e33017d1c4348c781a26984ModelNode.cpp
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
24
2017-11-22T08:31:00.000Z
2022-03-27T01:22:31.000Z
// Copyright © 2008-2014 Pioneer Developers. See AUTHORS.txt for details // Licensed under the terms of the GPL v3. See licenses/GPL-3.txt #include "ModelNode.h" #include "Model.h" namespace SceneGraph { ModelNode::ModelNode(Model *m) : Node(m->GetRenderer()) , m_model(m) { } ModelNode::ModelNode(const ModelNode &modelNode, NodeCopyCache *cache) : Node(modelNode, cache) , m_model(modelNode.m_model) { } Node* ModelNode::Clone(NodeCopyCache *cache) { return this; //modelnodes are shared } void ModelNode::Render(const matrix4x4f &trans, const RenderData *rd) { //slight hack here RenderData newrd = *rd; newrd.nodemask |= MASK_IGNORE; m_model->Render(trans, &newrd); } }
19.6
72
0.731778
[ "render", "model" ]
1ad96c98e9acb5c8fd593545e9cfca172fd8e794
3,051
cpp
C++
src/fileio.cpp
sus304/ForRocket
10fdcd0ce5a30fbbb4fec6315bcd64314bec6c12
[ "MIT" ]
21
2015-12-17T14:19:24.000Z
2021-09-09T07:17:17.000Z
src/fileio.cpp
sus304/ForRocket
10fdcd0ce5a30fbbb4fec6315bcd64314bec6c12
[ "MIT" ]
2
2015-12-17T19:45:50.000Z
2021-02-07T05:28:34.000Z
src/fileio.cpp
sus304/ForRocket
10fdcd0ce5a30fbbb4fec6315bcd64314bec6c12
[ "MIT" ]
10
2015-12-17T19:13:51.000Z
2021-09-27T01:14:14.000Z
// ****************************************************** // Project Name : ForRocket // File Name : fileio.cpp // Creation Date : 2019/11/24 // // Copyright (c) 2019 Susumu Tanaka. All rights reserved. // ****************************************************** #include "fileio.hpp" #include <iostream> #include <fstream> #include <sstream> std::vector<std::vector<double>> forrocket::LoadCsvLog(std::string file_path, int skip_rows) { std::ifstream ifs(file_path); std::vector<std::vector<double>> res_vectors; std::string line; std::getline(ifs, line); auto str = split(line, ','); int n_cols = str.size(); for (int i=0; i < n_cols; ++i) { std::vector<double> temp1; res_vectors.push_back(temp1); } ifs.seekg(0, std::ios_base::beg); // skip rows for (int i=0; i < skip_rows; ++i) std::getline(ifs, line); while (std::getline(ifs, line)) { auto str = split(line, ','); for (int i=0; i < n_cols; ++i) { res_vectors[i].push_back(std::stod(str[i])); } } // if (n_cols == 2) { // std::vector<double> temp1; // std::vector<double> temp2; // while (std::getline(ifs, line)) { // auto str = split(line, ','); // temp1.push_back(std::stod(str[0])); // temp1.push_back(std::stod(str[1])); // } // res_vectors.push_back(temp1); // res_vectors.push_back(temp2); // } else if (n_cols == 3) { // std::vector<double> temp1; // std::vector<double> temp2; // std::vector<double> temp3; // while (std::getline(ifs, line)) { // auto str = split(line, ','); // temp1.push_back(std::stod(str[0])); // temp1.push_back(std::stod(str[1])); // temp1.push_back(std::stod(str[2])); // } // res_vectors.push_back(temp1); // res_vectors.push_back(temp2); // res_vectors.push_back(temp3); // } else if (n_cols == 4) { // std::vector<double> temp1; // std::vector<double> temp2; // std::vector<double> temp3; // std::vector<double> temp4; // while (std::getline(ifs, line)) { // auto str = split(line, ','); // temp1.push_back(std::stod(str[0])); // temp1.push_back(std::stod(str[1])); // temp1.push_back(std::stod(str[2])); // temp1.push_back(std::stod(str[3])); // } // res_vectors.push_back(temp1); // res_vectors.push_back(temp2); // res_vectors.push_back(temp3); // res_vectors.push_back(temp4); // } return res_vectors; }; std::vector<std::string> forrocket::split(std::string& line, char delimiter) { std::istringstream stream(line); std::string field; std::vector<std::string> res; while (getline(stream, field, delimiter)) { res.push_back(field); } return res; };
33.163043
95
0.504425
[ "vector" ]
1adc9fc7234038f27aecc71dde55fdf9ad9daeff
4,952
cpp
C++
src/player.cpp
liu-chien/LoveLetter-BoardGame
7609b2c763b4f109f54b7a14d48ade914088f35e
[ "MIT" ]
null
null
null
src/player.cpp
liu-chien/LoveLetter-BoardGame
7609b2c763b4f109f54b7a14d48ade914088f35e
[ "MIT" ]
1
2021-04-02T22:24:20.000Z
2021-04-02T22:24:20.000Z
src/player.cpp
liu-chien/LoveLetter-BoardGame
7609b2c763b4f109f54b7a14d48ade914088f35e
[ "MIT" ]
1
2021-03-15T18:17:19.000Z
2021-03-15T18:17:19.000Z
#include "player.h" #include <assert.h> #include <stdio.h> #include <unistd.h> #include <algorithm> #include <iostream> #include <random> #include "card.h" #define KEY_UP 65 #define KEY_DOWN 66 #define KEY_RIGHT 67 #define KEY_LEFT 68 namespace loveletter { void Player::draw(Card card) { assert(handCards.size() < 2 && "Draw a card when already having two cards."); handCards.push_back(card); } void Player::discard() { assert(handCards.size() < 2 && "Cannot discard when holding two cards."); if (handCards[0] == Card(8)) { isAlive = false; std::cout << "[Game info] Player " << id << " discard the princess." << std::endl << "[Game info] Player " << id << " is dead" << std::endl; } handCards.pop_back(); } void Player::switchCard(Card other) { handCards.pop_back(); draw(other); assert(handCards.size() == 1); } std::vector<int> Player::getAvailCardId() { // princess if (handCards[0] == Card(8)) return {1}; else if (handCards[1] == Card(8)) return {0}; // countess if (handCards[0] == Card(7) && (handCards[1] == Card(5) || handCards[1] == Card(6))) return {0}; else if (handCards[1] == Card(7) && (handCards[0] == Card(5) || handCards[0] == Card(6))) return {1}; // else return {0, 1}; } PlayerAction AI::executeAction(std::vector<int> avail_playerId) { assert(handCards.size() == 2 && "Execute an action when holding cards less than 2."); sleep(3); std::vector<int> avail_card = getAvailCardId(); PlayerAction action; // PlayerAction.playCard random_shuffle(avail_card.begin(), avail_card.end()); action.playCard = handCards.at(avail_card.back()); handCards.erase(handCards.begin() + avail_card.back()); // PlayerAction.playerId random_shuffle(avail_playerId.begin(), avail_playerId.end()); if (!avail_playerId.empty()) { action.playerId = avail_playerId.back(); } // PlayerAction.guessCard action.guessCard = Card(rand() % 7 + 2); return action; } static int HumanChooseCardInterface() { int id; char c; system("stty raw"); while (1) { if (getchar() == 27) if (getchar() == 91) { c = getchar(); if (c == KEY_LEFT) { id = 0; break; } else if (c == KEY_RIGHT) { id = 1; break; } } } system("stty cooked"); return id; } static int HumanChoosePlayerInterface(std::vector<int> avail_playerId) { assert(!avail_playerId.empty() && "No any available players to be chosen"); if (avail_playerId.size() == 1) { std::cout << "Only one player can be chosen: Player " << avail_playerId.back() << std::endl; // system("pause"); return avail_playerId.back(); } int playerId; while (1) { std::cout << "Select a player: (" << avail_playerId.at(0); for (auto it = avail_playerId.begin() + 1; it != avail_playerId.end(); it++) { std::cout << ", " << *it; } std::cout << ")" << std::endl; std::cin >> playerId; if (std::cin.fail()) { std::cin.clear(); std::cin.ignore(256, '\n'); } if (std::find(avail_playerId.begin(), avail_playerId.end(), playerId) != avail_playerId.end()) break; std::cout << "Invalid player id: " << playerId << ". "; } return playerId; } Card HumanChooseGuessCardInterface(std::vector<Card> remainCard) { int cardId; while (1) { std::cout << "Select a card: (2-8)" << std::endl; std::cin >> cardId; if (std::find(remainCard.begin(), remainCard.end(), Card(cardId)) != remainCard.end()) break; std::cout << "Invalid card: " << cardId << ". "; } return Card(cardId); } PlayerAction Human::executeAction(std::vector<int> avail_playerId) { assert(handCards.size() == 2 && "Execute an action when holding cards less than 2."); std::vector<int> avail_card = getAvailCardId(); PlayerAction action; // Choice.card std::cout << "Your turn." << std::endl << "Left arrow: " << handCards[0] << ", Right arrow: " << handCards[1] << std::endl; int id = HumanChooseCardInterface(); // either 0 or 1 std::cout << "\r"; action.playCard = handCards.at(id); handCards.erase(handCards.begin() + id); // Further decision if (avail_playerId.empty()) { std::cout << "No any available player to be chosen. "; // system("pause"); // Press any key to continue . . . return action; } switch (action.playCard.getNum()) { case 1: action.playerId = HumanChoosePlayerInterface(avail_playerId); action.guessCard = HumanChooseGuessCardInterface({2, 3, 4, 5, 6, 7, 8}); break; case 2: case 3: case 5: case 6: action.playerId = HumanChoosePlayerInterface(avail_playerId); default: break; } assert(handCards.size() == 1 && "Two cards remains after execute an action."); return action; } } // namespace loveletter
25.926702
80
0.599556
[ "vector" ]
1ae18e5cb99740a5c60bd22d0e9f5d4029cf6626
9,579
cpp
C++
geomic.cpp
deevroman/algorithms-tasks
2c854a0033eacb42a454dabec1ecb63461e8cb53
[ "MIT" ]
null
null
null
geomic.cpp
deevroman/algorithms-tasks
2c854a0033eacb42a454dabec1ecb63461e8cb53
[ "MIT" ]
null
null
null
geomic.cpp
deevroman/algorithms-tasks
2c854a0033eacb42a454dabec1ecb63461e8cb53
[ "MIT" ]
null
null
null
namespace Geomic{ const ld eps = 1e-12; bool eq(ld x, ld y){ return x == y; return fabs(x - y) < eps; } struct Point{ ld x, y; Point(ld x_, ld y_) { x = x_; y = y_; } Point() { x = 0.0; y = 0.0; } ld dist(const Point& oth) const { return hypotf(x - oth.x, y - oth.y); } ld evklid_dist(const Point& oth) const{ return fabs(x - oth.x) + fabs(y - oth.y); } friend std::istream& operator >> (std::istream &in, Point &P) { in >> P.x >> P.y; return in; } friend std::ostream& operator << (std::ostream &out, const Point &P) { out << P.x << ' ' << P.y; return out; } bool operator< (const Point &oth) const { return x < oth.x || (eq(x, oth.x) && y < oth.y); } bool operator== (const Point &oth) const { return eq(x, oth.x) && eq(y, oth.y); } }; struct Vector{ ld x, y; Vector(ld x_, ld y_) { x = x_; y = y_; } Vector(const Point& A, const Point& B) { x = B.x - A.x; y = B.y - A.y; } Vector() { x = 0; y = 0; } Vector operator +(const Vector& oth) const { return Vector(x + oth.x, y + oth.y); } Vector operator *(ld k) const { return Vector(x * k, y * k); } ld operator %(const Vector& oth) const { return x * oth.y - y * oth.x; } ld operator *(const Vector& oth) const { return x * oth.x + y * oth.y; } ld length() const { return hypotl(x, y); } Vector standart() const { return Vector(x / length(), y / length()); } Vector normal() const { return Vector(-y, x); } bool is_parallel(const Vector& oth) const{ return eq(normal() % oth.normal(), 0); } friend std::istream & operator >> (std::istream & in, Vector& V) { in >> V.x >> V.y; return in; } friend std::ostream & operator << (std::ostream & out, const Vector& V) { out << V.x << ' ' << V.y; return out; } }; struct LineABC { ld a, b, c; LineABC(){} LineABC(ld a_, ld b_, ld c_){ a = a_; b = b_; c = c_; } LineABC(const Point& A, const Point& B) { a = A.y - B.y; b = B.x - A.x; c = -(a * A.x + b * A.y); } void normalization(){ ld d = hypotf(a, b); a /= d; b /= d; c /= d; } Vector normal() const{ return Vector(a, b); } Point intersection(const LineABC& oth) const { ld q = a * oth.b - b * oth.a; return Point((b * oth.c - c * oth.b) / q, (c * oth.a - a * oth.c) / q); } bool is_parallel(const LineABC &oth){ return eq(normal() % oth.normal(), 0); } int in(Point A){ // TODo Vector v(Point(0, c/(-b)), Point(1000, (a*1000 + c)/(-b))); Vector v2(Point(0, c/(-b)), Point(A.x, A.y)); ld ps = v % v2; if(eq(ps, 0)) return 0; else if(ps > eps) return 1; else return -1; } friend std::istream & operator >> (std::istream & in, LineABC& L) { in >> L.a >> L.b >> L.c; return in; } friend std::ostream & operator << (std::ostream & out, const LineABC& L) { out << L.a << ' ' << L.b << ' ' << L.c; return out; } }; struct Line { Point A; Point B; Line(const Point& A_, const Point& B_) { A = A_; B = B_; } Vector direction() const { return Vector(A, B); } bool is_parallel(const Line& oth) const { return eq(direction() % oth.direction(), 0); } bool is_coincide(const Line& oth) const { return eq(is_parallel(oth) && direction() % Vector(A, oth.A), 0); } Point intersection(const Line& oth) const { if (is_parallel(oth)) { // throw exception return Point(INF, INF); } return LineABC(A, B).intersection(LineABC(oth.A, oth.B)); } }; struct Polygon {// thanks to Mike Mirzayanov vector<Point> vertex; int size; Polygon(){} Polygon(vector<Point> &p){ vertex = p; // can optimize vertex.push_back(vertex[0]); size = p.size(); } vector<Polygon> split(LineABC line){ int i1 = -1, i2 = -1; vector<Point> now_vertex = vertex; for(int i = 0; i < size; i++){ LineABC seg = LineABC(vertex[i], vertex[i+1]); if(!seg.is_parallel(line)){ Point p = seg.intersection(line); if(eq(Vector(vertex[i], p) % Vector(vertex[i], vertex[i+1]), 0)){ if(min(vertex[i].x, vertex[i+1].x) <= p.x && p.x <= max(vertex[i].x, vertex[i+1].x) && min(vertex[i].y, vertex[i+1].y) <= p.y && p.y <= max(vertex[i].y, vertex[i+1].y)){ // FIXME if(i1 == -1){ i1 = i + 1; } else{ i2 = i + 1; } i++; now_vertex.insert(now_vertex.begin() + i, p); } } } } if(i2 == -1){ vector<Polygon> ans = {*this}; return ans; } else{ vector<Point> p1; for(int i = i1; i <= i2; i++){ p1.push_back(now_vertex[i]); } p1.push_back(now_vertex[i1]); vector<Point> p2; for(int i = i2; i <= i1; (i++)%now_vertex.size()){ p1.push_back(now_vertex[i]); } p1.push_back(now_vertex[i2]); vector<Polygon> ans = {Polygon(p1), Polygon(p2)}; return ans; } } bool vip(){ ll DIR = Vector(vertex[size-2], vertex[0]) % Vector(vertex[0], vertex[1]); for(int i = 0; i < size - 2; i++){ ll dir = Vector(vertex[i], vertex[i+1]) % Vector(vertex[i+1], vertex[i+2]); if(dir * DIR < 0){ return false; } } return true; } bool in(Point p){ ld sum = 0; for (int i = 0; i < size; ++i) { auto v1 = Vector(p, vertex[i]); auto v2 = Vector(p, vertex[i+1]); sum += asin((v1 % v2) / v1.length() / v2.length()); } return !eq(sum, 0.0); } ld get_sq(){ ld S = 0; for(int i = 2; i < size; i++){ S += Vector(vertex[1], vertex[i]) % Vector(vertex[1], vertex[i+1]); } return S / 2.0; } friend std::ostream & operator << (std::ostream & out, const Polygon& P) { for (int i = 0; i < P.size; ++i) { out << P.vertex[i] << "\n"; } return out; } }; Polygon get_ch(vector<Point> v){ sort(v.begin(), v.end()); auto left = v[0], right = v.back(); auto terminator = Vector(left, right); vector<Point> up = {left}, down = {left}; for(int i = 1; i < (int)v.size(); i++){ if(terminator % Vector(left, v[i]) >= 0){ while(true){ if(up.size() == 1){ up.push_back(v[i]); break; } auto prev = Vector(up[up.size()-2], up[up.size()-1]); auto now = Vector(up.back(), v[i]); if(prev % now >= 0){ up.pop_back(); } else { up.push_back(v[i]); break; } } } if (terminator % Vector(left, v[i]) <= 0) { while(true) { if (down.size() == 1) { down.push_back(v[i]); break; } auto prev = Vector(down[down.size() - 2], down[down.size() - 1]); auto now = Vector(down.back(), v[i]); if (prev % now <= 0) { down.pop_back(); } else { down.push_back(v[i]); break; } } } } down.reserve(down.size() + up.size() - 2); for(int i = (int)up.size() - 2; i > 0; i--){ down.push_back(up[i]); } return Polygon(down); } }
32.471186
118
0.371751
[ "vector" ]
1aec2ef2a64495834e6e574686e70c652ea4057d
8,497
cc
C++
xdl-algorithm-solution/TDM/src/tdm/dist_tree_test.cc
hitflame/x-deeplearning
c8029396c6ae6dbf397a34a1801ceadc824e4f8d
[ "Apache-2.0" ]
4,071
2018-12-13T04:17:38.000Z
2022-03-30T03:29:35.000Z
xdl-algorithm-solution/TDM/src/tdm/dist_tree_test.cc
laozhuang727/x-deeplearning
781545783a4e2bbbda48fc64318fb2c6d8bbb3cc
[ "Apache-2.0" ]
359
2018-12-21T01:14:57.000Z
2022-02-15T07:18:02.000Z
xdl-algorithm-solution/TDM/src/tdm/dist_tree_test.cc
laozhuang727/x-deeplearning
781545783a4e2bbbda48fc64318fb2c6d8bbb3cc
[ "Apache-2.0" ]
1,054
2018-12-20T09:57:42.000Z
2022-03-29T07:16:53.000Z
/* Copyright (C) 2016-2018 Alibaba Group Holding Limited 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. ==============================================================================*/ // Copyright 2018 Alibaba Inc. All Rights Reserved. #include "tdm/dist_tree.h" #include "gtest/gtest.h" #include "tdm/local_store.h" #include "tdm/tree.pb.h" namespace tdm { class MockStore: public Store { public: bool Get(const std::string& key, std::string* value) override { if (key == "root.tree_meta") { TreeMeta meta; meta.set_max_level(20); auto part_id = meta.mutable_id_code_part()->Add(); part_id->assign("part"); meta.SerializeToString(value); } else if (key == "part") { IdCodePart part; part.set_part_id("part"); for (size_t i = (1 << 10); i < (1 << 11); ++i) { auto id_code = part.mutable_id_code_list()->Add(); id_code->set_id(i); id_code->set_code(i); } part.SerializeToString(value); } else { value->assign(key); } return true; } bool Put(const std::string& key, const std::string& value) override { (void) key; (void) value; return true; } std::vector<bool> MGet(const std::vector<std::string>& keys, std::vector<std::string>* values) override { std::vector<bool> ret(keys.size(), true); for (size_t i = 0; i < keys.size(); ++i) { (*values)[i].assign(keys[i]); } return ret; } std::vector<bool> MPut(const std::vector<std::string>& keys, const std::vector<std::string>& values) override { (void) values; std::vector<bool> ret(keys.size(), true); return ret; } bool Remove(const std::string& key) { return true; } bool Dump(const std::string& filename) { (void) filename; return true; } }; std::string MakeKey(const std::string& prefix, size_t key_no) { std::string key(prefix); unsigned char buffer[sizeof(size_t)]; memset(buffer, 0x00, sizeof(buffer)); unsigned char* ptr = buffer + sizeof(size_t) - 1; while (key_no != 0) { *ptr = key_no & 0xFF; key_no >>= 8; --ptr; } key.append(reinterpret_cast<char*>(buffer), sizeof(size_t)); return key; } TEST(DistTree, TestNode) { MockStore store; DistTree tree("root", 2, &store); std::string key = MakeKey("root", 0); TreeNode root = tree.Node(key); ASSERT_TRUE(root.valid()); } TEST(DistTree, TestParent) { MockStore store; DistTree tree("root", 2, &store); std::string key = MakeKey("root", 0); TreeNode root = tree.Node(key); ASSERT_TRUE(root.valid()); TreeNode parent = tree.Parent(root); ASSERT_FALSE(parent.valid()); std::vector<TreeNode> children = tree.Children(root); ASSERT_EQ(2ul, children.size()); ASSERT_TRUE(children[0].valid() && children[1].valid()); std::string key0 = MakeKey("root", 1); ASSERT_EQ(children[0].key, key0); std::string key1 = MakeKey("root", 2); ASSERT_EQ(children[1].key, key1); parent = tree.Parent(children[0]); ASSERT_EQ(parent.key, root.key); } TEST(DistTree, TestChildren) { MockStore store; DistTree tree("root", 4, &store); std::string key = MakeKey("root", 0); TreeNode root = tree.Node(key); std::vector<TreeNode> children = tree.Children(root); ASSERT_EQ(2ul, children.size()); key = MakeKey("root", 1); ASSERT_EQ(key, children[0].key); key = MakeKey("root", 4); ASSERT_EQ(key, children[1].key); } TEST(DistTree, TestAncestors) { MockStore store; DistTree tree("root", 4, &store); TreeNode node = tree.Node(MakeKey("root", 500)); ASSERT_TRUE(node.valid()); std::vector<TreeNode> ancestors = tree.Ancestors(node); ASSERT_EQ(5, ancestors.size()); ASSERT_EQ(MakeKey("root", 124), ancestors[1].key); } TEST(DistTree, TestSilbings) { MockStore store; DistTree tree("root", 4, &store); TreeNode node = tree.Node(MakeKey("root", 121)); ASSERT_TRUE(node.valid()); std::vector<TreeNode> silbings = tree.Silbings(node); ASSERT_EQ(3ul, silbings.size()); ASSERT_EQ(MakeKey("root", 122), silbings[0].key); ASSERT_EQ(MakeKey("root", 123), silbings[1].key); ASSERT_EQ(MakeKey("root", 124), silbings[2].key); } TEST(DistTree, TestRandNeighbors) { MockStore store; DistTree tree("root", 4, &store); TreeNode node = tree.Node(MakeKey("root", 121)); ASSERT_TRUE(node.valid()); std::vector<TreeNode> neighbors = tree.RandNeighbors(node, 5); ASSERT_EQ(5ul, neighbors.size()); for (auto it = neighbors.begin(); it != neighbors.end(); ++it) { std::cout << it->key << std::endl; } } TEST(DistTree, TestSelectNeighbors) { MockStore store; DistTree tree("root", 4, &store); TreeNode node = tree.Node(MakeKey("root", 121)); ASSERT_TRUE(node.valid()); std::vector<int> indice = {1, 3, 5, 7, 9}; std::vector<TreeNode> neighbors = tree.SelectNeighbors(node, indice); ASSERT_EQ(5ul, neighbors.size()); ASSERT_EQ(MakeKey("root", 86), neighbors[0].key); ASSERT_EQ(MakeKey("root", 88), neighbors[1].key); ASSERT_EQ(MakeKey("root", 90), neighbors[2].key); ASSERT_EQ(MakeKey("root", 92), neighbors[3].key); } TEST(DistTree, TestBuild) { LocalStore store; ASSERT_TRUE(store.Init("")); DistTree tree("root", 2, &store); size_t level = 20; size_t max_id = (1 << level) - 1; size_t first_leaf_id = (1 << (level - 1)) - 1; std::cout << "Max id: " << max_id << ", First leaf id: " << first_leaf_id << std::endl; Node node; TreeMeta meta; std::vector<IdCodePart*> id_code_part; meta.set_max_level(level); std::vector<std::string> keys; std::vector<std::string> values; for (size_t i = 0; i < max_id; ++i) { std::string code = tree.MakeKey(i); std::string value; node.set_id(i); node.set_probality(0.0); node.set_leaf_cate_id(0); node.set_is_leaf(i >= first_leaf_id); ASSERT_TRUE(node.SerializeToString(&value)); keys.push_back(code); values.push_back(value); if (keys.size() >= 128) { auto vec = store.MPut(keys, values); for (auto it = vec.begin(); it != vec.end(); ++it) { ASSERT_TRUE(*it); } keys.clear(); values.clear(); } // ASSERT_TRUE(store.Put(code, value)); IdCodePart* part = NULL; if (id_code_part.empty() || id_code_part.back()->id_code_list().size() == 512) { auto part = new IdCodePart(); part->set_part_id(MakeKey("Part_", id_code_part.size() + 1)); id_code_part.push_back(part); } part = id_code_part.back(); auto id_code = part->mutable_id_code_list()->Add(); id_code->set_id(i); id_code->set_code(i); } if (!keys.empty()) { auto vec = store.MPut(keys, values); for (auto it = vec.begin(); it != vec.end(); ++it) { ASSERT_TRUE(*it); } keys.clear(); values.clear(); } for (size_t i = 0; i < id_code_part.size(); ++i) { auto part_id = meta.mutable_id_code_part()->Add(); auto part = id_code_part[i]; part_id->assign(part->part_id()); std::string value; ASSERT_TRUE(part->SerializeToString(&value)); ASSERT_TRUE(store.Put(part->part_id(), value)); delete part; } std::string meta_str; ASSERT_TRUE(meta.SerializeToString(&meta_str)); ASSERT_TRUE(store.Put("root.tree_meta", meta_str)); ASSERT_TRUE(store.Dump("local_store.pb")); } TEST(DistTree, TestLoad) { LocalStore store; ASSERT_TRUE(store.Init("")); store.LoadData("local_store.pb"); DistTree tree("root", 2, &store); TreeNode root = tree.Node(tree.MakeKey(0)); ASSERT_TRUE(tree.Valid(root)); } TEST(DistTree, TesLevelTraverse) { LocalStore store; ASSERT_TRUE(store.Init("")); store.LoadData("local_store.pb"); DistTree tree("root", 2, &store); for (int i = 0; i < tree.max_level(); ++i) { auto it = tree.LevelIterator(i); size_t level_key_no = tree.KeyNo(it->key); auto end = tree.LevelEnd(i); while (it != end) { auto& node = *it; ASSERT_EQ(level_key_no, tree.KeyNo(node.key)); it.Next(); ++level_key_no; } } } } // namespace tdm
27.767974
80
0.633165
[ "vector" ]
8c28f265fab58b8ef1b604dc11bfdb0235ac02ca
12,639
cpp
C++
src/explore.cpp
Henryyy-Hung/LinuxTerminalGame-TheFission
6309f4629fd219f04c10ac728ad8744c1ec78c99
[ "Apache-2.0" ]
11
2021-05-27T06:20:55.000Z
2022-01-30T12:58:43.000Z
src/explore.cpp
Henryyy-Hung/TheFission
6309f4629fd219f04c10ac728ad8744c1ec78c99
[ "Apache-2.0" ]
null
null
null
src/explore.cpp
Henryyy-Hung/TheFission
6309f4629fd219f04c10ac728ad8744c1ec78c99
[ "Apache-2.0" ]
null
null
null
// File name: explore.cpp // Author: Hung Ka Hing // UID: 3035782750 // Description: To hold functions regarding explore (i.e. map, move, bag). #include "explore.h" // include self defined structures, external library, and function header of explore.cpp #include "interface.h" // include function header in interface.h // items can be found during explore // define items and their attribute const Item unknown_potion = {"Unknown Potion", "HP", "+50", "Hr", "+100", "It sounds magic right? But it is science!!!"}; const Item bondage = { "Bondage", "HP", "+30", "", "", "Become a mummy or corpse? Well you have made your choice."}; const Item meat = {"Meat", "HP", "+20", "Hr", "-50", "Want some black pepper? You think too much boy, this is Waste Land!"}; const Item radiated_meat = {"Radiated Meat", "Hr", "-50", "HP", "-20", "Aha, you feel like superman."}; const Item radiated_cake = {"Radiated Cake", "Hr", "-30", "HP", "-15", "Why not eat cake bro?"}; const Item pure_water = {"Pure Water", "Hr", "-10", "", "", "You feel full after drinking it. How melancholy."}; const Item adrenaline = {"Adrenaline", "SP", "+100", "", "", "Fight or Fligh? You decide it."}; const Item radiated_water = {"Radiated Water", "SP", "+30", "HP", "-10", "You feel like superman! But your body don't think so."}; const Item iodophor = {"Iodophor", "SP", "+20", "", "", "Woo hoo, radiation-free!"}; // arrange items in an array Item items[9] = {unknown_potion, bondage, meat, radiated_meat, radiated_cake, pure_water, adrenaline, radiated_water, iodophor}; void event_allocator(int & event, const double & prosperity, const bool & resource_only) { short randint = (rand() % 1001) / prosperity; if ( randint > 100 ) event = 0; else if ( randint > 50 ) event = 1; else if ( randint > 30 ) event = 2; else if ( randint > 20 ) event = 3; else if ( randint > 10 ) event = 4; else event = 5; if ( ! resource_only ) { randint = (rand() % 1001) / prosperity; if ( randint > 300 ) return; else if ( randint > 10 ) event = 10; else event = 11; } } // Input: A int dynamic 2D array map, the side length of the map. // Return: Void. // Function: randomly allocate buildings, monsters, and events on the map by changing the value of array(map) element and set obstacle in boundary. // Meaning: Make the game more fun with random element and prevent bug. void map_generator(int ** map, int map_len) { int min = 0, max = map_len - 1; for (int i = 0; i < map_len; i++) { for (int j = 0; j < map_len; j++) // iterate through all element of map { if ( i <= min + 10 || i >= max - 10 || j <= min + 10 || j >= max - 10 ) { map[i][j] = 999; // set the boundary part to be wall(999) } else if ( i <= min + 15 || i >= max - 15 || j <= min + 15 || j >= max - 15 ) { event_allocator(map[i][j], 1, 1); } else { event_allocator(map[i][j], 1, 0); } } } } // Input: a dynamic 2D array map, side length of the map, actual location of player. // Return: void // Function: extend the map by 4 times and shift the actual location of player into center of new map while keeping the buildings in orginal map. // Meaning: Reduce the occupation of memory when it is no necessary. void extend_map(int** & map, int & map_len, Point& location) { int new_len = map_len * 2; // side length of new map int **new_map = new int *[new_len]; // declare a new 2D dynamic array map with doubled side length for (int row = 0; row < new_len; row++) new_map[row] = new int [new_len]; map_generator(new_map, new_len); // initialize the new map with random buildings,monsters, and events int x_diff = map_len - (location.x + 1); int y_diff = map_len - (location.y + 1); // shifting distance on x,y axis of original map on new map location.set(x_diff + location.x, y_diff + location.y); // shift actual location of player new_map[location.x][location.y] = 0; // label the area to be safe for (int i = 0; i < map_len; i++) // shift all element of original map to new map according to above rules for (int j = 0; j < map_len; j++) if ( (i + x_diff) < new_len && (j + y_diff) < new_len ) if (map[i][j] != 999 && new_map[i + x_diff][j + y_diff] != 999) new_map[i + x_diff][j + y_diff] = map[i][j]; for (int i = 0; i < map_len; i++) // release the origal map delete[] map[i]; delete[] map; map = new_map; // copy the new map to original map map_len = new_len; // update the length to new length } // Input: a dynamic 2D array map, int x and y that symbolize the current coordinate on map // Return: void // Function: develop a maze within the pre-processed map. void maze_generator(int** map, int x, int y) { vector<char> direction{'w','a','s','d'}; // vectors containing path-developing direction random_shuffle( direction.begin(), direction.end() ); // set random conbination for the direction const int wall = 998; const int node = -1; const int path = 0; int grid = path; event_allocator(grid, 4, 1); for (int i = 0; i < 4; i++) // iterate through the directions { switch ( direction[i] ) // develop the route to top { case 'w': if ( map[x][y+1] == wall && map[x][y+2] == node ) // check whether there is a wall and node that not been modified { // in this direction map[x][y+1] = grid; // set route map[x][y+2] = grid; maze_generator(map, x, y+2); // keep generating route at the next node } break; case 'a': if ( map[x-1][y] == wall && map[x-2][y] == node ) { map[x-1][y] = grid; map[x-2][y] = grid; maze_generator(map, x-2, y); } break; case 's': if ( map[x][y-1] == wall && map[x][y-2] == node ) { map[x][y-1] = grid; map[x][y-2] = grid; maze_generator(map, x, y-2); } break; case 'd': if ( map[x+1][y] == wall && map[x+2][y] == node ) { map[x+1][y] = grid; map[x+2][y] = grid; maze_generator(map, x+2, y); } break; } } return; // stop the function after processing all four direction } // Input: a dynamic 2D array map, the location of player // Return: void // Function: generate random maze on map by breaking wall between nodes void maze(int** map, Point location) { const int size = 15 * 2 + 1; const int x_origin = location.x - size / 2; // the origin of maze const int y_origin = location.y - size / 2; // centered the player const int wall = 998; const int node = -1; const int path = 0; for (int i = 0; i < size; i++) // iterate through maze grids on map and set walls and nodes { for (int j = 0; j < size; j++) // that is, pre-process the map { if ( i % 2 == 0 ) map[x_origin + i][y_origin + j] = wall; // set walls that surrounding nodes else if ( j % 2 == 0 ) map[x_origin + i][y_origin + j] = wall; // set walls that surrounding nodes else map[x_origin + i][y_origin + j] = node; // set nodes } } maze_generator(map, x_origin + 1, y_origin + 1); // generate paths by breaking walls between nodes map[x_origin][y_origin + 1] = path; // set a oping in bottom-left corner of maze map[x_origin + size - 1][y_origin + size - 2] = path; // set a opening in top-right corner of maze } // Input: Profile of player, a dynamic 2D array map, location of player, command from keyboard. // Return: If success to move, return true, else, return false. // Function: determine whether the movement is valid, if yes, change the virtual location(story dependent) and actual location(map dependent). // Meaning: Allow movement of player and set the condition of movement. bool moved(Profile & player, int ** map, Point & location, char direction) { int x = 0, y = 0; // movement in x and y direction. switch ( direction ) { case 'w': y += 1; break; case 's': y -= 1; break; case 'a': x -= 1; break; case 'd': x += 1; break; } switch ( map[location.x+x][location.y+y] < 100 ) { case true: player.location.change(x, y); location.change(x, y); return true; case false: return false; } } // Input: Profile of player. // Return: void. // Function: refresh the interface and print the status interface and bag interface. // Meaning: For better modularization. void default_page_b(Profile player) { refresh(100); // refresh the interface status_interface(player); // print status interface bag_interface(items, player.item); // print bag interface } // Input: void // Return: void // Function: print the text interface with some default text, which is the command instruction. // Meaning: better modularization void default_text_b(void) { string line_1 = " Command list:"; string line_2 = " Use item: 0 - 8"; string line_3 = " Back: b"; text_interface( format_lines(line_1, line_2, line_3) ); // format the output text in text interface separate into 3 line and keep left. } // Input: Profile of player, type of effect of item, value of effect of item. // Return: void. // Function: modify player's status according to attribute of item. // Meaning: better modularization. void buff(Profile& player, string type, int value) { if ( type == "HP" ) player.hp.change(value); // change hp else if ( type == "SP" ) player.sp.change(value); // change sp else if ( type == "Hr" ) player.hr.change(value); // change hr } // Input: Profile of player, mode of game(explore/battle). // Return: void. // Function: provide a interface to show no. and effect and quantity of items, to allow player to consume items to modify their status. // Meaning: increase elements that is fun, as there is often positive and negative effect on same item. User have to evaluate it. bool bag_manipulation(Profile& player, char mode) { bool hold = true; default_page_b(player); // print status and bag interface default_text_b(); // print command instruction while (true) { char command = input(); // receive input char as command string lines[3]; if ( command == 'b' || ! hold ) // quit the bag interface and return to the map interface { break; } else if ( command >= '0' && command <= '8' ) // use items numbered 0 to 8. { int index = (int) command - '0'; // convert the input char into int if (player.item[index] > 0) // check the quantity of item { if ( ! items[index].type_1.empty() && ! items[index].effect_1.empty() ) // modify status base on effect 1 { buff( player, items[index].type_1, atoi(items[index].effect_1.c_str()) ); } if ( ! items[index].type_2.empty() && ! items[index].effect_2.empty() ) // modify status base on efefct 2 { buff(player, items[index].type_2, atoi(items[index].effect_2.c_str()) ); } lines[0] = " " + items[index].name + " is used."; // show the thing has been used lines[1] = " " + items[index].annotation; // show the annotation of developer lines[2] = ANY_KEY; player.item[index] -= 1; // decrease the quantity of item by 1. if ( mode != 'e' ) // if not in exploration mode, teminate the page.(allow 1 act only). { hold = false; } } else // if quantity is 0, notice the user. { lines[0] = " You don't have this item."; lines[1] = ANY_KEY; } } default_page_b(player); // show default page of bag interface if ( ! lines[0].empty() || ! lines[1].empty() || ! lines[2].empty() ) { text_interface(format_lines(lines[0], lines[1], lines[2])); } else // show command instruction. { default_text_b(); } } return ! hold; // indicate whether a item is used } void detect(Profile player, int ** map, Point location) { string lines[3]; int monster = 0; for (int i = location.x - 1; i <= location.x + 1; i++) for (int j = location.y - 1; j <= location.y + 1; j++) if ( map[i][j] == 10 || map[i][j] == 99) { monster++; map[i][j] = 99; } lines[0] = " There are " + itoa(monster, 'u') + " monster is found around 3 x 3 grids."; lines[1] = " Dangerous area has been labelled."; lines[2] = ANY_KEY; refresh(100); status_interface(player); map_interface(map, location); text_interface( format_lines( lines[0], lines[1], lines[2]) ); input(); } void herbination_base(int ** map, Point location) { for (int i = location.x - 4; i <= location.x + 4; i++) for (int j = location.y - 3; j <= location.y + 3; j++) if ( i == location.x - 4 || i == location.x + 4 || j == location.y - 3 || j == location.y + 3) map[i][j] = 999; else map[i][j] = 0; map[location.x][location.y + 3] = 10; map[location.x][location.y + 4] = 11; }
32.828571
147
0.622834
[ "vector" ]
8c329d9ce811ec53e94081a6f0368e5150022f00
6,548
cpp
C++
Netcode/Network/NetworkCommon.cpp
tyekx/netcode
c46fef1eeb33ad029d0c262d39309dfa83f76c4d
[ "MIT" ]
null
null
null
Netcode/Network/NetworkCommon.cpp
tyekx/netcode
c46fef1eeb33ad029d0c262d39309dfa83f76c4d
[ "MIT" ]
null
null
null
Netcode/Network/NetworkCommon.cpp
tyekx/netcode
c46fef1eeb33ad029d0c262d39309dfa83f76c4d
[ "MIT" ]
null
null
null
#include <algorithm> #include "NetworkCommon.h" #include "../Logger.h" #include "Macros.h" #include <NetcodeFoundation/Exceptions.h> #include <string> #include <iphlpapi.h> #include <WinSock2.h> namespace Netcode::Network { NetworkContext::~NetworkContext() { Stop(); } NetworkContext::NetworkContext() : ioc{}, work{ std::make_unique<boost::asio::io_context::work>(ioc) }, workers{} { } uint8_t NetworkContext::GetActiveThreadCount() const { return static_cast<uint8_t>(workers.size()); } void NetworkContext::Start(uint8_t numThreads) { if(!workers.empty()) { return; } numThreads = std::clamp(numThreads, static_cast<uint8_t>(1), static_cast<uint8_t>(4)); workers.reserve(numThreads); for(uint8_t i = 0; i < numThreads; ++i) { workers.emplace_back([this]() -> void { ioc.run(); }); } } void NetworkContext::Stop() { if(workers.empty()) { return; } if(work) { work.reset(); } int32_t numThreads = static_cast<int32_t>(workers.size()); ioc.stop(); for(auto & thread : workers) { thread.join(); } workers.clear(); Log::Info("[Network] ({0}) I/O threads were joined successfully", numThreads); } boost::asio::io_context & NetworkContext::GetImpl() { return ioc; } ErrorCode Bind(const boost::asio::ip::address & selfAddr, UdpSocket & udpSocket, uint32_t & port) { uint32_t portHint = port; port = std::numeric_limits<uint32_t>::max(); if(portHint < 1024 || portHint > 49151) { portHint = (49151 - 1024) / 2; } boost::system::error_code ec; const uint32_t range = 49151 - 1024; const int32_t start = static_cast<int32_t>(portHint); int32_t sign = 1; UdpEndpoint endpoint{ selfAddr, 0 }; udpSocket.open(endpoint.protocol(), ec); if(ec) { return ec; } for(int32_t i = 0; i < range; ++i, sign = -sign) { uint32_t portToTest = static_cast<uint32_t>(start + sign * i / 2); if(portToTest < 1024 || portToTest > 49151) { continue; } endpoint.port(portToTest); udpSocket.bind(endpoint, ec); if(ec == boost::asio::error::bad_descriptor) { // expected error continue; } if(ec) { // unexpected error return ec; } port = portToTest; return Errc::make_error_code(Errc::success); } return ec; } static IpAddress ConvertToAsioAddress(SOCKET_ADDRESS addr) { /* * copying bytes would be faster but this is ABI agnostic */ wchar_t buffer[64]; char narrowBuffer[64]; DWORD s = 64; WSAAddressToStringW(addr.lpSockaddr, addr.iSockaddrLength, nullptr, buffer, &s); int dstSize = WideCharToMultiByte(CP_UTF8, 0, buffer, s, narrowBuffer, 64, nullptr, nullptr); return boost::asio::ip::make_address(std::string_view{ narrowBuffer, static_cast<size_t>(dstSize) }); } static std::vector<Interface> GetNativeNetworkInterfaces(DWORD addrFamily) { ULONG workingBufferSize = 65536; std::unique_ptr<BYTE[]> workingBuffer = std::make_unique<BYTE[]>(workingBufferSize); std::vector<Interface> ifaces; ifaces.reserve(4); IP_ADAPTER_ADDRESSES * currentAdapter = reinterpret_cast<IP_ADAPTER_ADDRESSES *>(workingBuffer.get()); ULONG status = GetAdaptersAddresses(addrFamily, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST, nullptr, currentAdapter, &workingBufferSize); if(status == ERROR_BUFFER_OVERFLOW) { throw OutOfRangeException{ "Query buffer is insufficient" }; } if(status != NO_ERROR) { return std::vector<Interface>{}; } while(currentAdapter != nullptr) { if(currentAdapter->FirstUnicastAddress == nullptr) { currentAdapter = currentAdapter->Next; continue; } Interface neti; neti.address = ConvertToAsioAddress(currentAdapter->FirstUnicastAddress->Address); neti.description = currentAdapter->Description; neti.friendlyName = currentAdapter->FriendlyName; neti.uplinkSpeedBps = currentAdapter->TransmitLinkSpeed; neti.downlinkSpeedBps = currentAdapter->ReceiveLinkSpeed; neti.mtu = currentAdapter->Mtu; /* * Rank should be non zero if IPv4, IPv6 is enabled and its operating */ ULONG rank = currentAdapter->Ipv6Enabled * currentAdapter->Ipv4Enabled * (!currentAdapter->ReceiveOnly) * (currentAdapter->OperStatus == IfOperStatusUp); switch(currentAdapter->IfType) { case IF_TYPE_ETHERNET_CSMACD: neti.netcodeRank = 10 * rank; break; case IF_TYPE_IEEE80211: neti.netcodeRank = 5 * rank; break; default: { /* * not the most common WIFI/ethernet case, try it from the DHCP direction */ IP_PREFIX_ORIGIN prefixOrigin = currentAdapter->FirstUnicastAddress->PrefixOrigin; switch(prefixOrigin) { // DHCP is a good candidate case IpPrefixOriginDhcp: neti.netcodeRank = 3 * rank; break; // manual could be an okay one case IpPrefixOriginManual: neti.netcodeRank = 2 * rank; break; // meh candidates default: neti.netcodeRank = rank; break; } } break; } ifaces.emplace_back(std::move(neti)); currentAdapter = currentAdapter->Next; } // order by netcode rank std::sort(std::begin(ifaces), std::end(ifaces), [](const Interface & a, const Interface & b) -> bool { return a.netcodeRank > b.netcodeRank; }); return ifaces; } bool SetDontFragmentBit(UdpSocket & socket) { if(!socket.is_open()) { return false; } SOCKET s = socket.native_handle(); int value = 1; int status = -1; boost::system::error_code ec; auto endpoint = socket.local_endpoint(ec); if(ec) { return false; } auto addr = endpoint.address(); if(addr.is_v4()) { status = setsockopt(s, IPPROTO_IP, IP_DONTFRAGMENT, reinterpret_cast<char *>(&value), sizeof(value)); } if(addr.is_v6()) { status = setsockopt(s, IPPROTO_IPV6, IPV6_DONTFRAG, reinterpret_cast<char *>(&value), sizeof(value)); } return status == 0; } std::vector<Interface> GetCompatibleInterfaces(const IpAddress & forThisAddress) { if(forThisAddress.is_multicast()) { return std::vector<Interface>{}; } std::vector<Interface> netifaces; if(forThisAddress.is_v4()) { netifaces = GetNativeNetworkInterfaces(AF_INET); } else if(forThisAddress.is_v6()) { netifaces = GetNativeNetworkInterfaces(AF_INET6); } auto it = std::remove_if(std::begin(netifaces), std::end(netifaces), [&forThisAddress](const Interface & neti) -> bool { return neti.address.is_loopback() != forThisAddress.is_loopback(); }); if(it != std::end(netifaces)) { netifaces.erase(it, std::end(netifaces)); } return netifaces; } }
24.709434
144
0.680055
[ "vector" ]
8c38c15f9a21b335254dda19aeeacc26521066c6
1,340
cpp
C++
octopuses with watches(full score)/octopus.cpp
papachristoumarios/IEEEXtreme11.0
4c3b5aaa71641a6d0b3e9823c4738050f2553b27
[ "MIT" ]
13
2018-10-11T14:13:56.000Z
2022-02-17T18:30:17.000Z
octopuses with watches(full score)/octopus.cpp
papachristoumarios/IEEEXtreme11.0-PComplete
4c3b5aaa71641a6d0b3e9823c4738050f2553b27
[ "MIT" ]
null
null
null
octopuses with watches(full score)/octopus.cpp
papachristoumarios/IEEEXtreme11.0-PComplete
4c3b5aaa71641a6d0b3e9823c4738050f2553b27
[ "MIT" ]
7
2018-10-24T08:36:59.000Z
2021-07-19T18:16:53.000Z
#include <cstdio> #include <algorithm> #include <vector> #define MAXN 10 using namespace std; int grid[ MAXN + 1 ][ MAXN + 1 ]; int main( void ) { int N, M; scanf("%d%d", &N, &M ); for( int i = 0; i < N; i++ ) { for( int j = 0; j < M; j++ ) { scanf("%d", &grid[ i ][ j ] ); grid[ i ][ j ] %= 3; } } int ans = 0, bound = 1; for( int i = 1; i <= M; i++ ) bound *= 3; for( int num = 0; num < bound; num++ ) { int res = 0; int grid2[ MAXN + 1 ][ MAXN + 1 ], add[ MAXN + 1 ]; for( int i = 0; i < N; i++ ) { for( int j = 0; j < M; j++ ) { grid2[ i ][ j ] = grid[ i ][ j ]; } } int num2 = num; for( int i = 0; i < M; i++ ) { add[ i ] = num2 % 3; num2 /= 3; } for( int j = 0; j < M; j++ ) { for( int i = 0; i < N; i++ ) { grid2[ i ][ j ] = ( grid2[ i ][ j ] + add[ j ] ) % 3; } } for( int i = 0; i < N; i++ ) { int cl[ 3 ] = { 0 }; for( int j = 0; j < M; j++ ) { cl[ grid2[ i ][ j ] ]++; } res += max( max( cl[ 0 ], cl[ 1 ] ), cl[ 2 ] ); } ans = max( ans, res ); } printf("%d\n", ans ); return 0; }
25.283019
69
0.324627
[ "vector" ]
8c3ba7dd0a3e87128a940dcbc794c93d05495fea
23,776
cpp
C++
11_learning_materials/stanford_self_driving_car/perception/chamfer_matching/src/chamfer_matching.cpp
EatAllBugs/autonomous_learning
02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47
[ "MIT" ]
14
2021-09-01T14:25:45.000Z
2022-02-21T08:49:57.000Z
11_learning_materials/stanford_self_driving_car/perception/chamfer_matching/src/chamfer_matching.cpp
yinflight/autonomous_learning
02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47
[ "MIT" ]
null
null
null
11_learning_materials/stanford_self_driving_car/perception/chamfer_matching/src/chamfer_matching.cpp
yinflight/autonomous_learning
02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47
[ "MIT" ]
3
2021-10-10T00:58:29.000Z
2022-01-23T13:16:09.000Z
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2008, Willow Garage, 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 the Willow Garage 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. *********************************************************************/ // Author: Marius Muja #include <cstdio> #include <queue> #include <algorithm> #include "opencv/cxcore.h" #include "opencv/cv.h" #include "opencv/highgui.h" #include <chamfer_matching/chamfer_matching.h> #define CV_PIXEL(type,img,x,y) (((type*)(img->imageData+y*img->widthStep))+x*img->nChannels) class SlidingWindowImageIterator : public ImageIterator { int x_; int y_; float scale_; float scale_step_; int scale_cnt_; bool has_next_; int width_; int height_; int x_step_; int y_step_; int scales_; float min_scale_; float max_scale_; public: SlidingWindowImageIterator(int width, int height, int x_step = 3, int y_step = 3, int scales = 5, float min_scale = 0.6, float max_scale = 1.6) : width_(width), height_(height), x_step_(x_step),y_step_(y_step), scales_(scales), min_scale_(min_scale), max_scale_(max_scale) { x_ = 0; y_ = 0; scale_cnt_ = 0; scale_ = min_scale_; has_next_ = true; scale_step_ = (max_scale_-min_scale_)/scales_; } bool hasNext() const { return has_next_; } location_scale_t next() { location_scale_t next_val = make_pair(cvPoint(x_,y_),scale_); x_ += x_step_; if (x_ >= width_) { x_ = 0; y_ += y_step_; if (y_ >= height_) { y_ = 0; scale_ += scale_step_; scale_cnt_++; if (scale_cnt_ == scales_) { has_next_ = false; scale_cnt_ = 0; scale_ = min_scale_; } } } return next_val; } }; ImageIterator* SlidingWindowImageRange::iterator() const { return new SlidingWindowImageIterator(width_, height_, x_step_, y_step_, scales_, min_scale_, max_scale_); } class LocationImageIterator : public ImageIterator { const vector<CvPoint>& locations_; size_t iter_; int scales_; float min_scale_; float max_scale_; float scale_; float scale_step_; int scale_cnt_; bool has_next_; public: LocationImageIterator(const vector<CvPoint>& locations, int scales = 5, float min_scale = 0.6, float max_scale = 1.6) : locations_(locations), scales_(scales), min_scale_(min_scale), max_scale_(max_scale) { iter_ = 0; scale_cnt_ = 0; scale_ = min_scale_; has_next_ = (locations_.size()==0 ? false : true); scale_step_ = (max_scale_-min_scale_)/scales_; } bool hasNext() const { return has_next_; } location_scale_t next() { location_scale_t next_val = make_pair(locations_[iter_],scale_); iter_ ++; if (iter_==locations_.size()) { iter_ = 0; scale_ += scale_step_; scale_cnt_++; if (scale_cnt_ == scales_) { has_next_ = false; scale_cnt_ = 0; scale_ = min_scale_; } } return next_val; } }; ImageIterator* LocationImageRange::iterator() const { return new LocationImageIterator(locations_, scales_, min_scale_, max_scale_); } class LocationScaleImageIterator : public ImageIterator { const vector<CvPoint>& locations_; const vector<float>& scales_; size_t iter_; bool has_next_; public: LocationScaleImageIterator(const vector<CvPoint>& locations, const vector<float>& scales) : locations_(locations), scales_(scales) { assert(locations.size()==scales.size()); reset(); } void reset() { iter_ = 0; has_next_ = (locations_.size()==0 ? false : true); } bool hasNext() const { return has_next_; } location_scale_t next() { location_scale_t next_val = make_pair(locations_[iter_],scales_[iter_]); iter_ ++; if (iter_==locations_.size()) { iter_ = 0; has_next_ = false; } return next_val; } }; ImageIterator* LocationScaleImageRange::iterator() const { return new LocationScaleImageIterator(locations_, scales_); } /** * Finds a point in the image from which to start contour following. * @param templ_img * @param p * @return */ bool findFirstContourPoint(IplImage* templ_img, coordinate_t& p) { unsigned char* ptr = (unsigned char*) templ_img->imageData; for (int y=0;y<templ_img->height;++y) { for (int x=0;x<templ_img->width;++x) { if (*(ptr+y*templ_img->widthStep+x)!=0) { p.first = x; p.second = y; return true; } } } return false; } /** * Method that extracts a single continuous contour from an image given a starting point. * When it extracts the contour it tries to maintain the same direction (at a T-join for example). * * @param templ_ * @param coords * @param crt */ void followContour(IplImage* templ_img, template_coords_t& coords, int direction = -1) { const int dir[][2] = { {-1,-1}, {-1,0}, {-1,1}, {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1} }; coordinate_t next; coordinate_t next_temp; unsigned char* ptr; assert (direction==-1 || !coords.empty()); coordinate_t crt = coords.back(); // printf("Enter followContour, point: (%d,%d)\n", crt.first, crt.second); // mark the current pixel as visited CV_PIXEL(unsigned char, templ_img, crt.first, crt.second)[0] = 0; if (direction==-1) { for (int j = 0; j<7; ++j) { next.first = crt.first + dir[j][1]; next.second = crt.second + dir[j][0]; ptr = CV_PIXEL(unsigned char, templ_img, next.first, next.second); if (*ptr!=0) { coords.push_back(next); followContour(templ_img, coords,j); // try to continue contour in the other direction reverse(coords.begin(), coords.end()); followContour(templ_img, coords, (j+4)%8); break; } } } else { int k = direction; int k_cost = 3; next.first = crt.first + dir[k][1]; next.second = crt.second + dir[k][0]; ptr = CV_PIXEL(unsigned char, templ_img, next.first, next.second); if (*ptr!=0) { k_cost = abs(dir[k][1])+abs(dir[k][0]); } int p = k; int n = k; for (int j = 0 ;j<3; ++j) { p = (p + 7) % 8; n = (n + 1) % 8; next.first = crt.first + dir[p][1]; next.second = crt.second + dir[p][0]; ptr = CV_PIXEL(unsigned char, templ_img, next.first, next.second); if (*ptr!=0) { int p_cost = abs(dir[p][1])+abs(dir[p][0]); if (p_cost<k_cost) { k_cost = p_cost; k = p; } } next.first = crt.first + dir[n][1]; next.second = crt.second + dir[n][0]; ptr = CV_PIXEL(unsigned char, templ_img, next.first, next.second); if (*ptr!=0) { int n_cost = abs(dir[n][1])+abs(dir[n][0]); if (n_cost<k_cost) { k_cost = n_cost; k = n; } } } if (k_cost!=3) { next.first = crt.first + dir[k][1]; next.second = crt.second + dir[k][0]; coords.push_back(next); followContour(templ_img, coords, k); } } } /** * Finds a contour in an edge image. The original image is altered by removing the found contour. * @param templ_img Edge image * @param coords Coordinates forming the contour. * @return True while a contour is still found in the image. */ bool findContour(IplImage* templ_img, template_coords_t& coords) { coordinate_t start_point; bool found = findFirstContourPoint(templ_img,start_point); if (found) { coords.push_back(start_point); followContour(templ_img, coords); return true; } return false; } /** * Computes the angle of a line segment. * * @param a One end of the line segment * @param b The other end. * @param dx * @param dy * @return Angle in radians. */ float getAngle(coordinate_t a, coordinate_t b, int& dx, int& dy) { dx = b.first-a.first; dy = -(b.second-a.second); // in image coordinated Y axis points downward float angle = atan2(dy,dx); if (angle<0) { angle+=M_PI; } return angle; } /** * Computes contour points orientations using the approach from: * * Matas, Shao and Kittler - Estimation of Curvature and Tangent Direction by * Median Filtered Differencing * * @param coords Contour points * @param orientations Contour points orientations */ void findContourOrientations(const template_coords_t& coords, template_orientations_t& orientations) { const int M = 5; int coords_size = coords.size(); vector<float> angles(2*M); orientations.insert(orientations.begin(), coords_size, float(-3*M_PI)); // mark as invalid in the beginning if (coords_size<2*M+1) { // if contour not long enough to estimate orientations, abort return; } for (int i=M;i<coords_size-M;++i) { coordinate_t crt = coords[i]; coordinate_t other; int k = 0; int dx, dy; // compute previous M angles for (int j=M;j>0;--j) { other = coords[i-j]; angles[k++] = getAngle(other,crt, dx, dy); } // compute next M angles for (int j=1;j<=M;++j) { other = coords[i+j]; angles[k++] = getAngle(crt, other, dx, dy); } // get the middle two angles nth_element(angles.begin(), angles.begin()+M-1, angles.end()); nth_element(angles.begin()+M-1, angles.begin()+M, angles.end()); // sort(angles.begin(), angles.end()); // average them to compute tangent orientations[i] = (angles[M-1]+angles[M])/2; } } //////////////////////// ChamferTemplate ///////////////////////////////////// ChamferTemplate::ChamferTemplate(IplImage* edge_image, float scale_) : addr_width(-1), scale(scale_) { template_coords_t local_coords; template_orientations_t local_orientations; while (findContour(edge_image, local_coords)) { findContourOrientations(local_coords, local_orientations); coords.insert(coords.end(), local_coords.begin(), local_coords.end()); orientations.insert(orientations.end(), local_orientations.begin(), local_orientations.end()); local_coords.clear(); local_orientations.clear(); } size = cvGetSize(edge_image); CvPoint min, max; min.x = size.width; min.y = size.height; max.x = 0; max.y = 0; center = cvPoint(0,0); for (size_t i=0;i<coords.size();++i) { center.x += coords[i].first; center.y += coords[i].second; if (min.x>coords[i].first) min.x = coords[i].first; if (min.y>coords[i].second) min.y = coords[i].second; if (max.x<coords[i].first) max.x = coords[i].first; if (max.y<coords[i].second) max.y = coords[i].second; } size.width = max.x - min.x; size.height = max.y - min.y; center.x /= coords.size(); center.y /= coords.size(); for (size_t i=0;i<coords.size();++i) { coords[i].first -= center.x; coords[i].second -= center.y; } // printf("Template coords\n"); // for (size_t i=0;i<coords.size();++i) { // printf("(%d,%d), ", coords[i].first, coords[i].second); // } // printf("\n"); } vector<int>& ChamferTemplate::getTemplateAddresses(int width) { if (addr_width!=width) { addr.resize(coords.size()); addr_width = width; for (size_t i=0; i<coords.size();++i) { addr[i] = coords[i].second*width+coords[i].first; // printf("Addr: %d, (%d,%d), %d\n", addr[i], coords[i].first, coords[i].second, width); } // printf("%d,%d\n", center.x, center.y); } return addr; } /** * Resizes a template * * @param scale Scale to be resized to */ ChamferTemplate* ChamferTemplate::rescale(float new_scale) { if (fabs(scale-new_scale)<1e-6) return this; for (size_t i=0;i<scaled_templates.size();++i) { if (fabs(scaled_templates[i]->scale-new_scale)<1e-6) { return scaled_templates[i]; } } float scale_factor = new_scale/scale; ChamferTemplate* tpl = new ChamferTemplate(); tpl->scale = new_scale; tpl->center.x = int(center.x*scale_factor+0.5); tpl->center.y = int(center.y*scale_factor+0.5); tpl->size.width = int(size.width*scale_factor+0.5); tpl->size.height = int(size.height*scale_factor+0.5); tpl->coords.resize(coords.size()); tpl->orientations.resize(orientations.size()); for (size_t i=0;i<coords.size();++i) { tpl->coords[i].first = int(coords[i].first*scale_factor+0.5); tpl->coords[i].second = int(coords[i].second*scale_factor+0.5); tpl->orientations[i] = orientations[i]; } scaled_templates.push_back(tpl); return tpl; } void ChamferTemplate::show() const { IplImage* templ_color = cvCreateImage(size, IPL_DEPTH_8U, 3); for (size_t i=0;i<coords.size();++i) { int x = center.x+coords[i].first; int y = center.y+coords[i].second; CV_PIXEL(unsigned char, templ_color,x,y)[1] = 255; if (i%3==0) { if (orientations[i] < -M_PI) { continue; } CvPoint p1; p1.x = x; p1.y = y; CvPoint p2; p2.x = x + 10*sin(orientations[i]); p2.y = y + 10*cos(orientations[i]); cvLine(templ_color, p1,p2, CV_RGB(255,0,0)); } } cvCircle(templ_color, center, 1, CV_RGB(0,255,0)); cvNamedWindow("templ",1); cvShowImage("templ",templ_color); // cvWaitKey(0); cvReleaseImage(&templ_color); } //////////////////////// ChamferMatching ///////////////////////////////////// void ChamferMatching::addTemplateFromImage(IplImage* templ, float scale) { ChamferTemplate* cmt = new ChamferTemplate(templ, scale); templates.push_back(cmt); // printf("Added a new template\n"); // cmt->show(); } /** * Alternative version of computeDistanceTransform, will probably be used to compute distance * transform annotated with edge orientation. */ void computeDistanceTransform(IplImage* edges_img, IplImage* dist_img, IplImage* annotate_img, float truncate_dt, float a = 1.0, float b = 1.5) { int d[][2] = { {-1,-1}, { 0,-1}, { 1,-1}, {-1,0}, { 1,0}, {-1,1}, { 0,1}, { 1,1} }; CvSize s = cvGetSize(edges_img); int w = s.width; int h = s.height; // set distance to the edge pixels to 0 and put them in the queue queue<pair<int,int> > q; for (int y=0;y<h;++y) { for (int x=0;x<w;++x) { unsigned char edge_val = CV_PIXEL(unsigned char, edges_img, x,y)[0]; // float orientation_val = CV_PIXEL(float, orientation_img, x,y)[0]; // if ( (edge_val!=0) && !(orientation_val<-M_PI) ) { if ( (edge_val!=0) ) { q.push(make_pair(x,y)); CV_PIXEL(float, dist_img, x, y)[0] = 0; if (annotate_img!=NULL) { int *aptr = CV_PIXEL(int,annotate_img,x,y); aptr[0] = x; aptr[1] = y; } } else { CV_PIXEL(float, dist_img, x, y)[0] = -1; } } } // breadth first computation of distance transform pair<int,int> crt; while (!q.empty()) { crt = q.front(); q.pop(); int x = crt.first; int y = crt.second; float dist_orig = CV_PIXEL(float, dist_img, x, y)[0]; float dist; for (size_t i=0;i<sizeof(d)/sizeof(d[0]);++i) { int nx = x + d[i][0]; int ny = y + d[i][1]; if (nx<0 || ny<0 || nx>=w || ny>=h) continue; if (abs(d[i][0]+d[i][1])==1) { dist = dist_orig+a; } else { dist = dist_orig+b; } float* dt = CV_PIXEL(float, dist_img, nx, ny); if (*dt==-1 || *dt>dist) { *dt = dist; q.push(make_pair(nx,ny)); if (annotate_img!=NULL) { int *aptr = CV_PIXEL(int,annotate_img,nx,ny); int *optr = CV_PIXEL(int,annotate_img,x,y); aptr[0] = optr[0]; aptr[1] = optr[1]; } } } } // truncate dt if (truncate_dt>0) { cvMinS(dist_img, truncate_dt, dist_img); } } void computeEdgeOrientations(IplImage* edge_img, IplImage* orientation_img) { IplImage* contour_img = cvCreateImage(cvGetSize(edge_img), IPL_DEPTH_8U, 1); template_coords_t coords; template_orientations_t orientations; while (findContour(edge_img, coords)) { findContourOrientations(coords, orientations); // set orientation pixel in orientation image for (size_t i = 0; i<coords.size();++i) { int x = coords[i].first; int y = coords[i].second; // if (orientations[i]>-M_PI) { CV_PIXEL(unsigned char, contour_img, x, y)[0] = 255; } CV_PIXEL(float, orientation_img, x, y)[0] = orientations[i]; } // cvNamedWindow("contours"); cvShowImage("contours", contour_img); // cvWaitKey(0); coords.clear(); orientations.clear(); } cvSaveImage("contours.pgm", contour_img); } void fillNonContourOrientations(IplImage* annotated_img, IplImage* orientation_img) { int width = annotated_img->width; int height = annotated_img->height; assert(orientation_img->width==width && orientation_img->height==height); for (int y=0;y<height;++y) { for (int x=0;x<width;++x) { int* ptr = CV_PIXEL(int, annotated_img, x,y); int xorig = ptr[0]; int yorig = ptr[1]; if (x!=xorig || y!=yorig) { float val = CV_PIXEL(float,orientation_img,xorig,yorig)[0]; CV_PIXEL(float,orientation_img,x,y)[0] = val; } } } } static float orientation_diff(float o1, float o2) { return fabs(o1-o2); } void ChamferMatching::localChamferDistance(CvPoint offset, IplImage* dist_img, IplImage* orientation_img, ChamferTemplate* tpl, ChamferMatch& cm, float alpha) { int x = offset.x; int y = offset.y; float beta = 1-alpha; vector<int>& addr = tpl->getTemplateAddresses(dist_img->width); vector<float> costs(addr.size()); float* ptr = CV_PIXEL(float, dist_img, x, y); float sum_distance = 0; for (size_t i=0;i<addr.size();++i) { // if (x==279 && y==176 && fabs(tpl.template_scale-0.7)<0.01) { // printf("%g, ", *(ptr+templ_addr[i])); // } sum_distance += *(ptr+addr[i]); costs[i] = *(ptr+addr[i]); } float cost = (sum_distance/truncate_)/addr.size(); // prinddrtf("%d,%d\n", tpl->center.x, tpl->center.y); if (orientation_img!=NULL) { float* optr = CV_PIXEL(float, orientation_img, x, y); float sum_orientation = 0; int cnt_orientation = 0; for (size_t i=0;i<addr.size();++i) { if (tpl->orientations[i]>=-M_PI && *(optr+addr[i])>=-M_PI) { sum_orientation += orientation_diff(tpl->orientations[i], *(optr+addr[i])); cnt_orientation++; // costs[i] = orientation_diff(tpl.orientations[i], *(optr+addr[i])); } } // printf("\n"); if (cnt_orientation>0) { cost = beta*cost+alpha*(sum_orientation/(2*M_PI))/cnt_orientation; } } // if (x>260 && x<300 && y>160 && y<190 && fabs(tpl->scale-1.0)<0.01) { // printf("\nCost: %g\n", cost); // } cm.addMatch(cost, offset, tpl, addr, costs); } void ChamferMatching::matchTemplates(IplImage* dist_img, IplImage* orientation_img, ChamferMatch& cm, const ImageRange& range, float orientation_weight) { // try each template for(size_t i = 0; i < templates.size(); i++) { ImageIterator* it = range.iterator(); while (it->hasNext()) { location_scale_t crt = it->next(); CvPoint loc = crt.first; float scale = crt.second; ChamferTemplate* tpl = templates[i]->rescale(scale); // printf("Location: (%d,%d), template: (%d,%d), img: (%d,%d)\n",loc.x,loc.y, // templates[i]->size.width,templates[i]->size.height, // dist_img->width, dist_img->height); // if (loc.x-tpl->center.x<0 || loc.x+tpl->size.width-tpl->center.x>=dist_img->width) continue; // if (loc.y-tpl->center.y<0 || loc.y+tpl->size.height-tpl->center.y>=dist_img->height) continue; if (loc.x-tpl->center.x<0 || loc.x+tpl->size.width>=dist_img->width) continue; if (loc.y-tpl->center.y<0 || loc.y+tpl->size.height>=dist_img->height) continue; // printf("%d,%d - %d,%d\n", loc.x, loc.y, templates[i]->center.x, templates[i]->center.y); localChamferDistance(loc, dist_img, orientation_img, tpl, cm, orientation_weight); } delete it; } } /** * Run matching using an edge image. * @param edge_img Edge image * @return a match object */ ChamferMatch ChamferMatching::matchEdgeImage(IplImage* edge_img, const ImageRange& range, float orientation_weight, int max_matches, float min_match_distance) { CV_Assert(edge_img->nChannels==1); IplImage* dist_img; IplImage* annotated_img; IplImage* orientation_img; ChamferMatch cm (max_matches, min_match_distance); dist_img = cvCreateImage(cvSize(edge_img->width, edge_img->height), IPL_DEPTH_32F, 1); annotated_img = cvCreateImage(cvSize(edge_img->width, edge_img->height), IPL_DEPTH_32S, 2); // Computing distance transform computeDistanceTransform(edge_img,dist_img, annotated_img, truncate_); orientation_img = NULL; if (use_orientation_) { orientation_img = cvCreateImage(cvSize(edge_img->width, edge_img->height), IPL_DEPTH_32F, 1); IplImage* edge_clone = cvCloneImage(edge_img); computeEdgeOrientations(edge_clone, orientation_img ); cvReleaseImage(&edge_clone); fillNonContourOrientations(annotated_img, orientation_img); } // Template matching matchTemplates(dist_img, orientation_img, cm, range, orientation_weight); cvReleaseImage(&dist_img); cvReleaseImage(&annotated_img); if (use_orientation_) { cvReleaseImage(&orientation_img); } return cm; } void ChamferMatch::addMatch(float cost, CvPoint offset, ChamferTemplate* tpl, const vector<int>& addr, const vector<float>& costs) { bool new_match = true; for (int i=0; i<count; ++i) { if (abs(matches[i].offset.x-offset.x)+abs(matches[i].offset.y-offset.y)<min_match_distance_) { // too close, not a new match new_match = false; // if better cost, replace existing match if (cost<matches[i].cost) { matches[i].cost = cost; matches[i].offset = offset; matches[i].tpl = tpl; // matches[i].costs = costs; // matches[i].img_offs = addr; } // re-bubble to keep ordered int k = i; while (k>0) { if (matches[k-1].cost>matches[k].cost) { swap(matches[k-1],matches[k]); } k--; } break; } } if (new_match) { // if we don't have enough matches yet, add it to the array if (count<max_matches_) { matches[count].cost = cost; matches[count].offset = offset; matches[count].tpl = tpl; // matches[count].costs = costs; // matches[count].img_offs = addr; count++; } // otherwise find the right position to insert it else { // if higher cost than the worst current match, just ignore it if (matches[count-1].cost<cost) { return; } int j = 0; // skip all matches better than current one while (matches[j].cost<cost) j++; // shift matches one position int k = count-2; while (k>=j) { matches[k+1] = matches[k]; k--; } matches[j].cost = cost; matches[j].offset = offset; matches[j].tpl = tpl; // matches[j].costs = costs; // matches[j].img_offs = addr; } } } void ChamferMatch::showMatch(IplImage* img, int index) { if (index>=count) { printf("Index too big.\n"); } assert(img->nChannels==3); ChamferMatchInstance match = matches[index]; const template_coords_t& templ_coords = match.tpl->coords; for (size_t i=0;i<templ_coords.size();++i) { // printf("%g, ", match.costs[i]); int x = match.offset.x + templ_coords[i].first; int y = match.offset.y + templ_coords[i].second; unsigned char *p = CV_PIXEL(unsigned char, img,x,y); p[0] = p[2] = 0; p[1] = 255; } }
24.740895
158
0.657386
[ "object", "vector", "transform" ]
8c3d32b676e17e69210320d135d3a9471337c34d
987
cpp
C++
problems/665-non-decreasing-array.cpp
ZhongRuoyu/leetcode
a905ec08e9b8ad8931d09e03efb154a648790c78
[ "MIT" ]
1
2022-01-11T06:32:41.000Z
2022-01-11T06:32:41.000Z
problems/665-non-decreasing-array.cpp
ZhongRuoyu/LeetCode
7472ef8b868165b485e5ce0676226bbe95561b73
[ "MIT" ]
null
null
null
problems/665-non-decreasing-array.cpp
ZhongRuoyu/LeetCode
7472ef8b868165b485e5ce0676226bbe95561b73
[ "MIT" ]
null
null
null
// Solved 2021-03-03 18:29 // Runtime: 16 ms (99.70%) // Memory Usage: 26.9 MB (84.29%) class Solution { public: bool checkPossibility(vector<int> &nums) { bool modified = false; int prev = nums[0]; for (int i = 1; i < nums.size(); ++i) { if (prev > nums[i]) { if (modified) return false; modified = true; if (i - 2 >= 0 && nums[i - 2] > nums[i]) continue; } prev = nums[i]; } return true; } }; /** * Note on how to modify the array: * * i * nums 0 1 2 4 2 ... (don't care) * [2] * In the case where nums[i - 2] <= nums[i], * we update nums[i - 1] to nums[i], i.e. update prev to nums[i]. * * i * nums 0 1 2 3 1 ... (don't care) * [3] * Conversely, in the case where nums[i - 2] > nums[i], * we update nums[i] to nums[i - 1], and hence leave prev unchanged. */
26.675676
68
0.454914
[ "vector" ]
8c409242021e8a7b8147a7a0c6aa65c4ddb51aae
1,381
cpp
C++
Frunze/main.cpp
rusucosmin/Cplusplus
0e95cd01d20b22404aa4166c71d5a9e834a5a21b
[ "MIT" ]
11
2015-08-29T13:41:22.000Z
2020-01-08T20:34:06.000Z
Frunze/main.cpp
rusucosmin/Cplusplus
0e95cd01d20b22404aa4166c71d5a9e834a5a21b
[ "MIT" ]
null
null
null
Frunze/main.cpp
rusucosmin/Cplusplus
0e95cd01d20b22404aa4166c71d5a9e834a5a21b
[ "MIT" ]
5
2016-01-20T18:17:01.000Z
2019-10-30T11:57:15.000Z
#include <fstream> #include <iostream> #include <vector> #include <bitset> #include <string.h> #include <algorithm> #include <iomanip> #include <math.h> #include <time.h> #include <stdlib.h> #include <set> #include <map> #include <string> #include <queue> #include <deque> using namespace std; const char infile[] = "frunze.in"; const char outfile[] = "frunze.out"; ifstream fin(infile); ofstream fout(outfile); const int MAXN = 100005; const int MOD = 29989; const int oo = 0x3f3f3f3f; typedef vector<int> Graph[MAXN]; typedef vector<int> :: iterator It; const inline int min(const int &a, const int &b) { if( a > b ) return b; return a; } const inline int max(const int &a, const int &b) { if( a < b ) return b; return a; } const inline void Get_min(int &a, const int b) { if( a > b ) a = b; } const inline void Get_max(int &a, const int b) { if( a < b ) a = b; } int N, P, a[55][55]; inline int Stirling(int n, int m) { if(m <= 1 || m == n) { a[n][m] = 1; return 1; } if(a[n][m]) return a[n][m]; a[n][m] = (Stirling(n - 1, m - 1) + 1LL * m * Stirling(n - 1, m) % MOD) % MOD; return a[n][m]; } int main() { fin >> N >> P; int tmp = Stirling(N - 2, N - P); for(int i = P + 1 ; i <= N ; ++ i) tmp = (1LL * tmp * i) % MOD; fout << tmp << '\n'; fin.close(); fout.close(); return 0; }
23.016667
86
0.569153
[ "vector" ]
8c4771f5accba0e5f20eb6f67feddf16bfada8ee
1,453
cpp
C++
Graphs/colouring_slip.cpp
sanjay-rishi/ProgrammingHub
459944ee9da7f25af7bd358b61b350678ee53882
[ "MIT" ]
10
2018-10-25T17:47:24.000Z
2020-05-11T15:04:28.000Z
Graphs/colouring_slip.cpp
sanjay-rishi/ProgrammingHub
459944ee9da7f25af7bd358b61b350678ee53882
[ "MIT" ]
22
2018-10-25T17:33:51.000Z
2019-11-15T03:50:12.000Z
Graphs/colouring_slip.cpp
sanjay-rishi/ProgrammingHub
459944ee9da7f25af7bd358b61b350678ee53882
[ "MIT" ]
150
2018-10-25T17:49:26.000Z
2020-10-28T14:59:19.000Z
#include<iostream> #include "bits/stdc++.h" // #include<vector> using namespace std; queue <int> q; int flag=0; long long n=100000; int v, e, v1,v2, visited[10000],level[100000], pop=1, colour[100000],c=1; vector<int> g[100000]; void bfs(int i) { level[1]=1; //cout<<i<<" at level = "<<level[i]<<endl; visited[i]=1; colour[i]=c; c=0; q.push(i); while(!q.empty()) { for(int j=0; j<g[q.front()].size(); j++) { if(visited[g[q.front()][j]]!=1) { //cout<<g[q.front()][j]<<" at level = "<<level[q.front()]+1<<endl; level[g[q.front()][j]]=level[q.front()]+1; q.push(g[q.front()][j]); visited[g[q.front()][j]]=1; colour[g[q.front()][j]]=1 - colour[q.front()]; } else { if(colour[g[q.front()][j]]==c) { cout<<"-1"; flag=-1; return; } } } q.pop(); } } int main(){ int v, e, v1,v2; cin>>v>>e; g[v+1].resize(v+1); for(int i=0;i<e;i++) { cin>>v1>>v2; g[v1].push_back(v2); g[v2].push_back(v1); } for(int i=1;i<v+1;i++) { cout<<i<<": "; for( vector<int>::iterator it=g[i].begin(); it!=g[i].end(); it++) cout<<(*it)<<" "; cout<<endl; } // cout<<g[1].size(); cout<<"BFS"<<endl; bfs(1); if(flag==-1) cout <<"\nNot possible\n"; else{ cout<<"COLOURING\n"; for(int i=1; i<=v;i++) { cout<<i<<":"<<colour[i]<<endl; } } }
15.135417
75
0.462491
[ "vector" ]
8c566d3726a7c21ed12d1add4dd0473e72d4d4aa
12,075
cpp
C++
soapy/src/test/test_client.cpp
siglabsoss/s-modem
0a259b4f3207dd043c198b76a4bc18c8529bcf44
[ "BSD-3-Clause" ]
null
null
null
soapy/src/test/test_client.cpp
siglabsoss/s-modem
0a259b4f3207dd043c198b76a4bc18c8529bcf44
[ "BSD-3-Clause" ]
null
null
null
soapy/src/test/test_client.cpp
siglabsoss/s-modem
0a259b4f3207dd043c198b76a4bc18c8529bcf44
[ "BSD-3-Clause" ]
null
null
null
#include <netinet/ip.h> #include <sys/socket.h> #include <arpa/inet.h> #include <string.h> #include <unistd.h> #include <iostream> #include <fstream> #include <vector> #include <cstring> #include <unistd.h> #include <chrono> #include <queue> #include "cpp_utils.hpp" #include "driver/AirPacket.hpp" #define BITS_PER_MEGABIT 1048576.0 #define PORT 40001 #define DATA_SIZE 20 #define HEADER_SIZE 16 #define PACKET_SIZE 368 #define HEADER_SEQ_NUM_INDEX 5 #define MAX_MBPS 15.625 #define MAXLINE (PACKET_SIZE * 4) /** * */ int update_data_stream(std::queue<uint32_t> &data_stream, std::vector<uint32_t> &input_data, std::vector<uint32_t> &header, int header_seq_number); /** * */ int _add_header(std::queue<uint32_t> &data_stream, std::vector<uint32_t> &header, int header_seq_number); /** * */ void _add_data(std::queue<uint32_t> &data_stream, std::vector<uint32_t> &input_data, int section); /** * */ int create_data_stream(double mbps, std::queue<uint32_t> &data_stream, std::vector<uint32_t> &input_data, std::vector<uint32_t> &header, int header_seq_number, uint32_t iteration); /** * */ void create_data_packet(std::vector<uint32_t> &data_packet, std::queue<uint32_t> &data_stream, int section); /** * */ int append_zeros(std::queue<uint32_t> &data_stream, std::vector<uint32_t> &header, uint32_t packet_count, int header_seq_number); /** * */ void get_file_data(std::string filepath, std::vector<uint32_t> file_data); /** * */ template<class T> void setup_air_packet(T *air_packet); /** * */ void create_counter(std::vector<uint32_t> &counter_data, uint32_t counter_size); /** * */ void get_sliced_data(AirPacketOutbound &air_packet, std::vector<uint32_t> &sliced_data, uint32_t counter_size); /** * */ int create_tx_socket(sockaddr_in &serv_addr); int main(int argc, char const *argv[]) { AirPacketOutbound tx_packet; int seq_number = 0xBB; int header_seq_number = 0xA; int sock_fd; uint32_t packet_num = 0; uint32_t start_data = 0; uint32_t iteration = 40; double mbps = 15.625; double sleep_us = 417; double data_rate; uint32_t counter_size = 10000; char hello[MAXLINE] = ""; struct sockaddr_in serv_addr; std::queue<uint32_t> data_stream; std::vector<uint32_t> file_data; std::vector<uint32_t> sliced_data; std::vector<uint32_t> data_packet(PACKET_SIZE, 0); std::string filepath = "../sim/data/mapmov_320_qpsk_1_sliced.hex"; std::vector<uint32_t> header = {0x00000002, 0x00000024, 0x00000001, 0x40000000, 0x00000006, header_seq_number, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000}; data_packet[0] = seq_number; setup_air_packet(&tx_packet); sock_fd = create_tx_socket(serv_addr); get_sliced_data(tx_packet, sliced_data, counter_size); get_file_data(filepath, file_data); header_seq_number = create_data_stream(mbps, data_stream, sliced_data, header, header_seq_number, iteration); packet_num = data_stream.size() / (PACKET_SIZE - 1); // Calculates index when a UDP data packet is sent start_data = (MAX_MBPS/mbps - 1) * sliced_data.size() / DATA_SIZE * (DATA_SIZE + HEADER_SIZE) / (PACKET_SIZE - 1); std::cout << "Data stream size: " << data_stream.size() << "\n"; std::cout << "Packet count: " << packet_num << "\n"; auto begin = std::chrono::steady_clock::now(); for (uint32_t i = 0; i < packet_num; i++) { auto start = std::chrono::steady_clock::now(); create_data_packet(data_packet, data_stream, i); memcpy(hello, &data_packet[0], MAXLINE); seq_number++; data_packet[0] = seq_number; auto end = std::chrono::steady_clock::now(); std::chrono::duration<double, std::micro> diff = end - start; usleep(sleep_us - diff.count()); sendto(sock_fd, (const char *) hello, PACKET_SIZE * 4, MSG_CONFIRM, (const struct sockaddr *) &serv_addr, sizeof(serv_addr)); if (i == start_data) { std::chrono::milliseconds ms = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::system_clock::now().time_since_epoch()); std::cout << "Sent data packet at " << ms.count() << "\n"; // Calculates index when next UDP data packet is sent start_data += sliced_data.size() / DATA_SIZE * (DATA_SIZE + HEADER_SIZE) / (PACKET_SIZE - 1); start_data += (MAX_MBPS/mbps - 1) * sliced_data.size() / DATA_SIZE * (DATA_SIZE + HEADER_SIZE) / (PACKET_SIZE - 1); } } auto complete = std::chrono::steady_clock::now(); std::chrono::duration<double> t = complete - begin; double total_bits = sliced_data.size() * 32 * iteration; data_rate = total_bits / t.count() / BITS_PER_MEGABIT; std::cout << "\n"; std::cout << "Total Time: " << t.count() << " s\n" << "Packet Size: " << sliced_data.size() << " words\n" << "Total Words: " << sliced_data.size() * iteration << " words\n" << "Total Bits: " << total_bits << " bits\n" << "Data Rate: " << data_rate << " Mbps\n"; close(sock_fd); return 0; } int update_data_stream(std::queue<uint32_t> &data_stream, std::vector<uint32_t> &input_data, std::vector<uint32_t> &header, int header_seq_number) { int n = input_data.size() / DATA_SIZE; if ((input_data.size() % DATA_SIZE)) { std::cout << "Input data not a multiple of data size: " << DATA_SIZE << "\n"; } for (std::size_t i = 0; i < n; i++) { header_seq_number = _add_header(data_stream, header, header_seq_number); _add_data(data_stream, input_data, i); } return header_seq_number; } int _add_header(std::queue<uint32_t> &data_stream, std::vector<uint32_t> &header, int header_seq_number) { header[HEADER_SEQ_NUM_INDEX] = header_seq_number; header_seq_number++; for (std::size_t i = 0; i < header.size(); i++) { data_stream.push(header[i]); } return header_seq_number; } void _add_data(std::queue<uint32_t> &data_stream, std::vector<uint32_t> &input_data, int section) { for (std::size_t i = 0; i < DATA_SIZE; i++) { data_stream.push(input_data[i + section*DATA_SIZE]); } } int create_data_stream(double mbps, std::queue<uint32_t> &data_stream, std::vector<uint32_t> &input_data, std::vector<uint32_t> &header, int header_seq_number, uint32_t iteration) { double append_zero = (MAX_MBPS/mbps - 1) * input_data.size() / DATA_SIZE; std::cout << "Append " << append_zero << " packets of zero for a data " << "rate of " << mbps << " Mbps\n"; for (std::size_t i = 0; i < iteration; i++) { header_seq_number = append_zeros(data_stream, header, (int) append_zero, header_seq_number); header_seq_number = update_data_stream(data_stream, input_data, header, header_seq_number); } return header_seq_number; } void create_data_packet(std::vector<uint32_t> &data_packet, std::queue<uint32_t> &data_stream, int section) { bool debug = false; for (std::size_t i = 1; i < PACKET_SIZE; i++) { if (!data_stream.empty()) { data_packet[i] = data_stream.front(); data_stream.pop(); } } if (debug) { std::cout << "Data Packet " << section << ": \n"; for (uint32_t x : data_packet) { std::cout << std::hex << x << std::dec <<"\n"; } } } int append_zeros(std::queue<uint32_t> &data_stream, std::vector<uint32_t> &header, uint32_t packet_count, int header_seq_number) { std::vector<uint32_t> zero(DATA_SIZE, 0); for (uint32_t i = 0; i < packet_count; i++) { header_seq_number = update_data_stream(data_stream, zero, header, header_seq_number); } return header_seq_number; } void get_file_data(std::string filepath, std::vector<uint32_t> file_data) { std::string hex_value; std::ifstream input_file(filepath); while (std::getline(input_file, hex_value)) { file_data.push_back((uint32_t) std::stoul(hex_value, nullptr, 16)); } } template<class T> void setup_air_packet(T *air_packet) { uint32_t code_length = 255; uint32_t fec_length = 48; uint32_t interleave_length = 64; int code_bad; air_packet->set_modulation_schema(FEEDBACK_MAPMOV_QPSK); air_packet->set_subcarrier_allocation(MAPMOV_SUBCARRIER_320); air_packet->set_interleave(interleave_length); code_bad = air_packet->set_code_type(AIRPACKET_CODE_REED_SOLOMON, code_length, fec_length); } void create_counter(std::vector<uint32_t> &counter_data, uint32_t counter_size) { for (std::size_t i = 0; i < counter_size; i++) { counter_data.push_back(i); } } void get_sliced_data(AirPacketOutbound &air_packet, std::vector<uint32_t> &sliced_data, uint32_t counter_size) { uint8_t seq; std::vector<uint32_t> modulated_data; std::vector<uint32_t> counter_data; std::vector<std::vector<uint32_t>> sliced_words; create_counter(counter_data, counter_size); modulated_data = air_packet.transform(counter_data, seq, 0); air_packet.padData(modulated_data); sliced_words = air_packet.emulateHiggsToHiggs(modulated_data); sliced_data = sliced_words[1]; } int create_tx_socket(sockaddr_in &serv_addr) { int sock_fd; // Create socket file descriptor sock_fd = socket(AF_INET, SOCK_DGRAM, 0); if (sock_fd < 0) { std::cout << "ERROR: Socket file descriptor was not allocated\n"; return -1; } else { std::cout << "Socket construction complete\n"; } memset(&serv_addr, 0, sizeof(serv_addr)); // Filling server information serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(PORT); serv_addr.sin_addr.s_addr = INADDR_ANY; return sock_fd; }
34.110169
80
0.544845
[ "vector", "transform" ]
8c6df31ba20dc16dc40e1e95fc472701d87df807
1,635
hpp
C++
include/depthai/pipeline/host_pipeline.hpp
rapyuta-robotics/depthai-core
785c1c3a3a006d4ccc83c796ea205262a33a702a
[ "MIT" ]
null
null
null
include/depthai/pipeline/host_pipeline.hpp
rapyuta-robotics/depthai-core
785c1c3a3a006d4ccc83c796ea205262a33a702a
[ "MIT" ]
null
null
null
include/depthai/pipeline/host_pipeline.hpp
rapyuta-robotics/depthai-core
785c1c3a3a006d4ccc83c796ea205262a33a702a
[ "MIT" ]
null
null
null
#pragma once #include <list> #include <memory> #include <set> #include <tuple> #include <vector> #include <mutex> #include <boost/lockfree/spsc_queue.hpp> #include <boost/lockfree/queue.hpp> #include "depthai/host_data_packet.hpp" #include "depthai-shared/stream/stream_info.hpp" #include "depthai-shared/general/data_observer.hpp" #include "depthai-shared/stream/stream_data.hpp" //project #include "depthai/LockingQueue.hpp" class HostPipeline : public DataObserver<StreamInfo, StreamData> { protected: const unsigned c_data_queue_size = 30; LockingQueue<std::shared_ptr<HostDataPacket>> _data_queue_lf; std::list<std::shared_ptr<HostDataPacket>> _consumed_packets; // TODO: temporary solution std::set<std::string> _public_stream_names; // streams that are passed to public methods std::set<std::string> _observing_stream_names; // all streams that pipeline is subscribed public: using DataObserver<StreamInfo, StreamData>::observe; HostPipeline(); virtual ~HostPipeline() {} std::list<std::shared_ptr<HostDataPacket>> getAvailableDataPackets(bool blocking = false); void makeStreamPublic(const std::string& stream_name) { _public_stream_names.insert(stream_name); } // TODO: temporary solution void consumePackets(bool blocking); std::list<std::shared_ptr<HostDataPacket>> getConsumedDataPackets(); private: // from DataObserver<StreamInfo, StreamData> virtual void onNewData(const StreamInfo& info, const StreamData& data) final; // from DataObserver<StreamInfo, StreamData> virtual void onNewDataSubject(const StreamInfo &info) final; };
29.196429
103
0.75474
[ "vector" ]
8c81c3845076d614419f2d82fcb5cab4fbda35ae
3,208
hpp
C++
include/LiveProfiler/Collectors/CpuSampleLinuxCollector.hpp
cpv-project/live-profiler
1ee3e2a8fa4de5c17d834ceaf69e63917e40093c
[ "MIT" ]
19
2017-11-29T09:11:12.000Z
2022-03-01T16:33:46.000Z
include/LiveProfiler/Collectors/CpuSampleLinuxCollector.hpp
cpv-project/live-profiler
1ee3e2a8fa4de5c17d834ceaf69e63917e40093c
[ "MIT" ]
9
2017-12-06T03:21:40.000Z
2018-08-23T10:41:29.000Z
include/LiveProfiler/Collectors/CpuSampleLinuxCollector.hpp
cpv-project/live-profiler
1ee3e2a8fa4de5c17d834ceaf69e63917e40093c
[ "MIT" ]
7
2017-11-29T11:13:11.000Z
2019-12-18T22:21:51.000Z
#pragma once #include "BasePerfLinuxCollector.hpp" #include "../Models/CpuSampleModel.hpp" namespace LiveProfiler { /** * Collector for collecting cpu samples on linux, based on perf_events * * Q: Why callchain is incomplete for my program? * A: Backtrace is based on frame pointer, please compile with -fno-omit-frame-pointer option. */ class CpuSampleLinuxCollector : public BasePerfLinuxCollector<CpuSampleModel> { public: /** * Set whether to include callchain in samples. * Exclude callchain in samples will improve performance. * Default value is true. */ void setIncludeCallChain(bool includeCallChain) { if (includeCallChain) { sampleType_ |= PERF_SAMPLE_CALLCHAIN; } else { sampleType_ &= ~PERF_SAMPLE_CALLCHAIN; } } /** Constructor */ CpuSampleLinuxCollector() : BasePerfLinuxCollector( PERF_TYPE_SOFTWARE, PERF_COUNT_SW_CPU_CLOCK, PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_CALLCHAIN) { } protected: /** Take samples for executing instruction (actually is the next instruction) */ void takeSamples(std::unique_ptr<LinuxPerfEntry>& entry) override { assert(entry != nullptr); auto& records = entry->getRecords(); for (auto* record : records) { // check if the record is sample if (record->type != PERF_RECORD_SAMPLE) { continue; } auto* data = reinterpret_cast<const CpuSampleRawData*>(record); // setup model data auto result = resultAllocator_.allocate(); auto ip = data->ip; result->setIp(ip); result->setPid(data->pid); result->setTid(data->tid); result->setSymbolName(nullptr); auto& callChainIps = result->getCallChainIps(); auto& callChainSymbolNames = result->getCallChainSymbolNames(); if (data->header.size >= sizeof(CpuSampleRawDataWithCallChain)) { auto* dataWithCallChain = reinterpret_cast<const CpuSampleRawDataWithCallChain*>(data); for (std::size_t i = 0; i < dataWithCallChain->nr; ++i) { auto callChainIp = dataWithCallChain->ips[i]; // don't include special instruction pointer if ((callChainIp & SpecialInstructionPointerMask) == SpecialInstructionPointerMask) { continue; } // don't include self if (callChainIp == ip) { continue; } callChainIps.emplace_back(callChainIp); callChainSymbolNames.emplace_back(nullptr); } } // append model data results_.emplace_back(std::move(result)); } // all records handled, update read offset entry->updateReadOffset(); } /** * There some instruction pointer should be exclude from callchain like 0xfffffffffffffe00. * They looks like a switch between kernel space and user space. * This mask works with both x64 and i386. */ static const std::uint64_t SpecialInstructionPointerMask = 0xffffffffffff0000; /** See man perf_events, section PERF_RECORD_SAMPLE */ struct CpuSampleRawData { ::perf_event_header header; std::uint64_t ip; std::uint32_t pid; std::uint32_t tid; }; /** See man perf_events, section PERF_RECORD_SAMPLE */ struct CpuSampleRawDataWithCallChain { CpuSampleRawData data; std::uint64_t nr; std::uint64_t ips[]; }; }; }
32.08
95
0.70106
[ "model" ]
8c847f73b6376ec1ffb9040aef14c4743445f8ed
1,818
cpp
C++
GRAPH ALGORITHM/WEEK 2 DECOMPOSITION 2/3 STRONGLY CONNECTED/strongly_connected.cpp
Mohit-007/DSA-UCDS-COURSERA
f5826a6f393e3b69ed8cf1c47df4d7a319b2d1fd
[ "MIT" ]
null
null
null
GRAPH ALGORITHM/WEEK 2 DECOMPOSITION 2/3 STRONGLY CONNECTED/strongly_connected.cpp
Mohit-007/DSA-UCDS-COURSERA
f5826a6f393e3b69ed8cf1c47df4d7a319b2d1fd
[ "MIT" ]
null
null
null
GRAPH ALGORITHM/WEEK 2 DECOMPOSITION 2/3 STRONGLY CONNECTED/strongly_connected.cpp
Mohit-007/DSA-UCDS-COURSERA
f5826a6f393e3b69ed8cf1c47df4d7a319b2d1fd
[ "MIT" ]
null
null
null
#include <algorithm> #include <iostream> #include <vector> #include <stack> using std::vector; using std::pair; using std::stack; vector<vector<int> > reverse_edges(vector<vector<int> > &adjacency_list) { vector<vector<int> > reverse_adj(adjacency_list.size(), vector<int>()); int i,j; for(i=0;i<adjacency_list.size();i++) { for(j=0;j<adjacency_list[i].size();j++) { reverse_adj[adjacency_list[i][j]].push_back(i); } } return reverse_adj; } void depth_first_search(vector<vector<int> > &adjacency_list, int x, vector<int> &visited, stack<int> &stack) { visited[x] = 1; int i; for(i=0;i<adjacency_list[x].size();i++) { if(!visited[adjacency_list[x][i]]) { visited[adjacency_list[x][i]] = 1; depth_first_search(adjacency_list, adjacency_list[x][i], visited, stack); } } stack.push(x); } int number_of_strongly_connected_components(vector<vector<int> > adjacency_list) { int result = 0; //write your code here stack<int> s; vector<int> visited(adjacency_list.size(), 0); int i; for(i=0;i<adjacency_list.size();i++) { if(!visited[i]) { depth_first_search(adjacency_list, i, visited, s); } } vector<vector<int> > reverse_adj = reverse_edges(adjacency_list); for(i=0;i<adjacency_list.size();i++) { visited[i] = 0; } while(!s.empty()) { int x = s.top(); s.pop(); if (!visited[x]) { stack<int> stack_component; depth_first_search(reverse_adj, x, visited, stack_component); result = result + 1; } } return result; } int main() { size_t n, m; std::cin >> n >> m; vector<vector<int> > adj(n, vector<int>()); for (size_t i = 0; i < m; i++) { int x, y; std::cin >> x >> y; adj[x - 1].push_back(y - 1); } std::cout << number_of_strongly_connected_components(adj); }
19.340426
110
0.628163
[ "vector" ]
8c8d4001c14374d509e23ca5181a7600b66fa2b0
19,134
cxx
C++
PWGLF/SPECTRA/PiKaPr/TestAOD/AliAnalysisTaskSpectraBoth.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
114
2017-03-03T09:12:23.000Z
2022-03-03T20:29:42.000Z
PWGLF/SPECTRA/PiKaPr/TestAOD/AliAnalysisTaskSpectraBoth.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
19,637
2017-01-16T12:34:41.000Z
2022-03-31T22:02:40.000Z
PWGLF/SPECTRA/PiKaPr/TestAOD/AliAnalysisTaskSpectraBoth.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
1,021
2016-07-14T22:41:16.000Z
2022-03-31T05:15:51.000Z
/************************************************************************** * Copyright(c) 1998-2009, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ //----------------------------------------------------------------- // AliAnalysisTaskSpectraBoth class //----------------------------------------------------------------- #include "TChain.h" #include "TTree.h" #include "TLegend.h" #include "TH1F.h" #include "TH2F.h" #include "TH3F.h" #include "TCanvas.h" #include "AliAnalysisTask.h" #include "AliAnalysisManager.h" #include "AliAODTrack.h" #include "AliAODMCParticle.h" #include "AliVParticle.h" #include "AliAODEvent.h" #include "AliAODInputHandler.h" #include "AliAnalysisTaskSpectraBoth.h" #include "AliAnalysisTaskESDfilter.h" #include "AliAnalysisDataContainer.h" #include "AliSpectraBothHistoManager.h" #include "AliSpectraBothTrackCuts.h" #include "AliSpectraBothEventCuts.h" #include "AliCentrality.h" #include "TProof.h" #include "AliPID.h" #include "AliVEvent.h" #include "AliESDEvent.h" #include "AliPIDResponse.h" #include "AliStack.h" #include "AliSpectraBothPID.h" #include "AliGenEventHeader.h" #include <TMCProcess.h> #include <iostream> using namespace AliSpectraNameSpaceBoth; using namespace std; ClassImp(AliAnalysisTaskSpectraBoth) //________________________________________________________________________ AliAnalysisTaskSpectraBoth::AliAnalysisTaskSpectraBoth(const char *name) : AliAnalysisTaskSE(name), fAOD(0), fHistMan(0), fTrackCuts(0), fEventCuts(0), fPID(0), fIsMC(0), fNRebin(0),fUseMinSigma(0),fCuts(0),fdotheMCLoopAfterEventCuts(0),fmakePIDQAhisto(1),fMotherWDPDGcode(-1),fUseEtaCut(kFALSE),fIncludecorrectlyidentifiedinMCtemplates(kFALSE) { // Default constructor DefineInput(0, TChain::Class()); DefineOutput(1, AliSpectraBothHistoManager::Class()); DefineOutput(2, AliSpectraBothEventCuts::Class()); DefineOutput(3, AliSpectraBothTrackCuts::Class()); DefineOutput(4, AliSpectraBothPID::Class()); fNRebin=0; } //________________________________________________________________________ //________________________________________________________________________ void AliAnalysisTaskSpectraBoth::UserCreateOutputObjects() { // create output objects fHistMan = new AliSpectraBothHistoManager("SpectraHistos",fNRebin,fmakePIDQAhisto); fHistMan->SetIncludecorrectlyidentifiedinMCtemplates(fIncludecorrectlyidentifiedinMCtemplates); if (!fTrackCuts) AliFatal("Track Cuts should be set in the steering macro"); if (!fEventCuts) AliFatal("Event Cuts should be set in the steering macro"); if (!fPID) AliFatal("PID object should be set in the steering macro"); fTrackCuts->SetAliESDtrackCuts(fCuts); fEventCuts->InitHisto(); fTrackCuts->InitHisto(); if(fTrackCuts->GetYMax()<fTrackCuts->GetYMin()) fUseEtaCut=kTRUE; Printf(" eta cut %d Will be used lack of Y cut",fUseEtaCut); PostData(1, fHistMan ); PostData(2, fEventCuts); PostData(3, fTrackCuts); PostData(4, fPID ); } //________________________________________________________________________ void AliAnalysisTaskSpectraBoth::UserExec(Option_t *) { // main event loop Int_t ifAODEvent=AliSpectraBothTrackCuts::kotherobject; fAOD = dynamic_cast<AliVEvent*>(InputEvent()); // AliESDEvent* esdevent=0x0; // AliAODEvent* aodevent=0x0; TString nameoftrack(fAOD->ClassName()); if(!nameoftrack.CompareTo("AliESDEvent")) { ifAODEvent=AliSpectraBothTrackCuts::kESDobject; //esdevent=dynamic_cast<AliESDEvent*>(fAOD); } else if(!nameoftrack.CompareTo("AliAODEvent")) { ifAODEvent=AliSpectraBothTrackCuts::kAODobject; //aodevent=dynamic_cast<AliAODEvent*>(fAOD); } else AliFatal("Not processing AODs or ESDS") ; if(fIsMC) { if(!fEventCuts->CheckMCProcessType(MCEvent())) return ; } if(fdotheMCLoopAfterEventCuts) if(!fEventCuts->IsSelected(fAOD,fTrackCuts,fIsMC,-100,fHistMan->GetEventStatHist())) return;//event selection TClonesArray *arrayMC = 0; Int_t npar=0; AliStack* stack=0x0; Double_t mcZ=-100; if (fIsMC) { TArrayF mcVertex(3); mcVertex[0]=9999.; mcVertex[1]=9999.; mcVertex[2]=9999.; AliMCEvent* mcEvent=(AliMCEvent*)MCEvent(); if (!mcEvent) { AliFatal("Error: MC particles branch not found!\n"); } AliHeader* header = mcEvent->Header(); if (!header) { AliDebug(AliLog::kError, "Header not available"); return; } AliGenEventHeader* genHeader = header->GenEventHeader(); if(genHeader) { genHeader->PrimaryVertex(mcVertex); mcZ=mcVertex[2]; } if(ifAODEvent==AliSpectraBothTrackCuts::kAODobject) { arrayMC = (TClonesArray*) fAOD->GetList()->FindObject(AliAODMCParticle::StdBranchName()); if (!arrayMC) { AliFatal("Error: MC particles branch not found!\n"); } Int_t nMC = arrayMC->GetEntries(); for (Int_t iMC = 0; iMC < nMC; iMC++) { AliAODMCParticle *partMC = (AliAODMCParticle*) arrayMC->At(iMC); if(!partMC->Charge()) continue;//Skip neutrals //if(partMC->Eta() > fTrackCuts->GetEtaMin() && partMC->Eta() < fTrackCuts->GetEtaMax()){//charged hadron are filled inside the eta acceptance //Printf("%f %f-%f",partMC->Eta(),fTrackCuts->GetEtaMin(),fTrackCuts->GetEtaMax()); if(partMC->Eta() > fTrackCuts->GetEtaMin() && partMC->Eta() < fTrackCuts->GetEtaMax()) { fHistMan->GetPtHistogram(kHistPtGen)->Fill(partMC->Pt(),partMC->IsPhysicalPrimary()); } else { if(fUseEtaCut) continue; } //rapidity cut if(!fUseEtaCut) { if(partMC->Y() > fTrackCuts->GetYMax()|| partMC->Y() < fTrackCuts->GetYMin() ) continue; } if(partMC->IsPhysicalPrimary()) npar++; // check for true PID + and fill P_t histos Int_t chargetmp = partMC->Charge() > 0 ? kChPos : kChNeg ; Int_t id = fPID->GetParticleSpecie(partMC); if(id != kSpUndefined) { fHistMan->GetHistogram2D(kHistPtGenTruePrimary,id,chargetmp)->Fill(partMC->Pt(),partMC->IsPhysicalPrimary()); } } } if(ifAODEvent==AliSpectraBothTrackCuts::kESDobject) { stack = mcEvent->Stack(); Int_t nMC = stack->GetNtrack(); for (Int_t iMC = 0; iMC < nMC; iMC++) { TParticle *partMC = stack->Particle(iMC); if(!partMC) continue; if(!partMC->GetPDG(0)) continue; if(TMath::Abs(partMC->GetPDG(0)->Charge()/3.0)<0.01) continue;//Skip neutrals if(partMC->Eta() > fTrackCuts->GetEtaMin() && partMC->Eta() < fTrackCuts->GetEtaMax()) { fHistMan->GetPtHistogram(kHistPtGen)->Fill(partMC->Pt(),stack->IsPhysicalPrimary(iMC)); } else { if(fUseEtaCut) continue; } if(!fUseEtaCut) { if(partMC->Y()>fTrackCuts->GetYMax() ||partMC->Y()< fTrackCuts->GetYMin() ) continue; } if(stack->IsPhysicalPrimary(iMC)) npar++; // check for true PID + and fill P_t histos Int_t chargetmp = partMC->GetPDG(0)->Charge()/3.0 > 0 ? kChPos : kChNeg ; Int_t id = fPID->GetParticleSpecie(partMC); if(id != kSpUndefined) { fHistMan->GetHistogram2D(kHistPtGenTruePrimary,id,chargetmp)->Fill(partMC->Pt(),stack->IsPhysicalPrimary(iMC)); } } } } if(!fdotheMCLoopAfterEventCuts) if(!fEventCuts->IsSelected(fAOD,fTrackCuts,fIsMC,mcZ,fHistMan->GetEventStatHist())) return;//event selection //main loop on tracks Int_t ntracks=0; //cout<<fAOD->GetNumberOfTracks()<<endl; for (Int_t iTracks = 0; iTracks < fAOD->GetNumberOfTracks(); iTracks++) { AliVTrack* track = dynamic_cast<AliVTrack*>(fAOD->GetTrack(iTracks)); AliAODTrack* aodtrack=0; AliESDtrack* esdtrack=0; Float_t dca=-999.; Float_t dcaz=-999.; Short_t ncls=-1; Float_t chi2perndf=-1.0; if(ifAODEvent==AliSpectraBothTrackCuts::kESDobject) { esdtrack=dynamic_cast<AliESDtrack*>(track); if(!esdtrack) continue; esdtrack->GetImpactParameters(dca,dcaz); ncls=esdtrack->GetTPCNcls(); if ( ncls > 5) chi2perndf=(esdtrack->GetTPCchi2()/Float_t(ncls - 5)); else chi2perndf=-1; } else if (ifAODEvent==AliSpectraBothTrackCuts::kAODobject) { aodtrack=dynamic_cast<AliAODTrack*>(track); if(!aodtrack) continue; dca=aodtrack->DCA(); dcaz=aodtrack->ZAtDCA(); ncls=aodtrack->GetTPCNcls(); chi2perndf=aodtrack->Chi2perNDF(); } else continue; if (!fTrackCuts->IsSelected(track,kTRUE)) continue; ntracks++; //calculate DCA for AOD track if(dca==-999.) {// track->DCA() does not work in old AOD production Double_t d[2], covd[3]; AliVTrack* track_clone=(AliVTrack*)track->Clone("track_clone"); // need to clone because PropagateToDCA updates the track parameters Bool_t isDCA = track_clone->PropagateToDCA(fAOD->GetPrimaryVertex(),fAOD->GetMagneticField(),9999.,d,covd); delete track_clone; if(!isDCA) d[0]=-999.; dca=d[0]; dcaz=d[1]; } fHistMan->GetPtHistogram(kHistPtRec)->Fill(track->Pt(),dca); // PT histo // get identity and charge Bool_t rec[3]={false,false,false}; Bool_t sel[3]={false,false,false}; Int_t idRec = fPID->GetParticleSpecie(fHistMan,track, fTrackCuts,rec); Int_t idGen =kSpUndefined; Bool_t isPrimary = kFALSE; Bool_t isSecondaryMaterial = kFALSE; Bool_t isSecondaryWeak = kFALSE; for(int irec=kSpPion;irec<kNSpecies;irec++) { if(fUseMinSigma) { if(irec>kSpPion) break; } else { if(!rec[irec]) idRec = kSpUndefined; else idRec=irec; } Int_t charge = track->Charge() > 0 ? kChPos : kChNeg; // Fill histograms, only if inside y and nsigma acceptance if(idRec != kSpUndefined && fTrackCuts->CheckYCut ((BothParticleSpecies_t)idRec)) { fHistMan->GetHistogram2D(kHistPtRecSigma,idRec,charge)->Fill(track->Pt(),dca); if(fTrackCuts->GetMakeQAhisto()) { fTrackCuts->GetHistoDCAzQA()->Fill(idRec,track->Pt(),dcaz); fTrackCuts->GetHistoNclustersQA()->Fill(idRec,track->Pt(),ncls); fTrackCuts->GetHistochi2perNDFQA()->Fill(idRec,track->Pt(),chi2perndf); } sel[idRec]=true; } //can't put a continue because we still have to fill allcharged primaries, done later /* MC Part */ if (arrayMC||stack) { //Bool_t isPrimary = kFALSE; // Bool_t isSecondaryMaterial = kFALSE; // Bool_t isSecondaryWeak = kFALSE; // Int_t idGen =kSpUndefined; Int_t pdgcode=0; Int_t motherpdg=-1; Int_t chargeMC=-2; if (ifAODEvent==AliSpectraBothTrackCuts::kAODobject) { AliAODMCParticle *partMC = (AliAODMCParticle*) arrayMC->At(TMath::Abs(track->GetLabel())); if (!partMC) { AliError("Cannot get MC particle"); continue; } // Check if it is primary, secondary from material or secondary from weak decay isPrimary = partMC->IsPhysicalPrimary(); isSecondaryWeak = partMC->IsSecondaryFromWeakDecay(); isSecondaryMaterial = partMC->IsSecondaryFromMaterial(); //cout<<"AOD tagging "<<isPrimary<<" "<<isSecondaryWeak<<isSecondaryMaterial<<" "<<partMC->GetMCProcessCode()<<endl; if(!isPrimary&&!isSecondaryWeak&&!isSecondaryMaterial)//old tagging for old AODs { AliError("old tagging"); Int_t mfl=-999,codemoth=-999; Int_t indexMoth=partMC->GetMother(); // FIXME ignore fakes? TO BE CHECKED, on ESD is GetFirstMother() if(indexMoth>=0) {//is not fake AliAODMCParticle* moth = (AliAODMCParticle*) arrayMC->At(indexMoth); codemoth = TMath::Abs(moth->GetPdgCode()); mfl = Int_t (codemoth/ TMath::Power(10, Int_t(TMath::Log10(codemoth)))); } //Int_t uniqueID = partMC->GetUniqueID(); //cout<<"uniqueID: "<<partMC->GetUniqueID()<<" "<<kPDecay<<endl; //cout<<"status: "<<partMC->GetStatus()<<" "<<kPDecay<<endl; // if(uniqueID == kPDecay)Printf("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); if(mfl==3) isSecondaryWeak = kTRUE; // add if(partMC->GetStatus() & kPDecay)? FIXME else isSecondaryMaterial = kTRUE; } //cout<<"AOD 2 tagging "<<isPrimary<<" "<<isSecondaryWeak<<isSecondaryMaterial<<" "<<partMC->GetMCProcessCode()<<endl; if(isSecondaryWeak) { Int_t indexMoth=partMC->GetMother(); // FIXME ignore fakes? TO BE CHECKED, on ESD is GetFirstMother() if(indexMoth>=0) { AliAODMCParticle* moth = (AliAODMCParticle*) arrayMC->At(indexMoth); if(moth) motherpdg=TMath::Abs(moth->GetPdgCode()); } } idGen = fPID->GetParticleSpecie(partMC); pdgcode=partMC->GetPdgCode(); chargeMC=partMC->Charge() > 0 ? kChPos : kChNeg ; } else if (ifAODEvent==AliSpectraBothTrackCuts::kESDobject) { TParticle *partMC =stack->Particle(TMath::Abs(track->GetLabel())); if (!partMC) { AliError("Cannot get MC particle"); continue; } isPrimary = stack->IsPhysicalPrimary(TMath::Abs(track->GetLabel())); isSecondaryWeak = stack->IsSecondaryFromWeakDecay(TMath::Abs(track->GetLabel())); isSecondaryMaterial = stack->IsSecondaryFromMaterial(TMath::Abs(track->GetLabel())); //cout<<"ESD tagging "<<isPrimary<<" "<<isSecondaryWeak<<isSecondaryMaterial<<endl; if(isSecondaryWeak) { TParticle* moth=stack->Particle(TMath::Abs(partMC->GetFirstMother())); if(moth) motherpdg = TMath::Abs(moth->GetPdgCode()); } idGen = fPID->GetParticleSpecie(partMC); pdgcode=partMC->GetPdgCode(); chargeMC = partMC->GetPDG(0)->Charge()/3.0 > 0 ? kChPos : kChNeg ; } else return; // cout<<isPrimary<<" "<<isSecondaryWeak<<" "<<isSecondaryMaterial<<endl; // cout<<" functions "<<partMC->IsPhysicalPrimary()<<" "<<partMC->IsSecondaryFromWeakDecay()<<" "<<partMC->IsSecondaryFromMaterial()<<endl; if (isPrimary&&irec==kSpPion) { fHistMan->GetPtHistogram(kHistPtRecPrimaryAll)->Fill(track->Pt(),dca); // PT histo of reconstrutsed primaries in defined eta if(chargeMC!=charge) fHistMan->GetPtHistogram("hHistDoubleCounts")->Fill(track->Pt(),4); } if(track->Pt()>fTrackCuts->GetPtTOFMatching(irec)&&(!fTrackCuts->CheckTOFMatchingParticleType(irec))) continue; //in case of pt depended TOF cut we have to remove particles with pt above their TOF cut but below max TOF cut if(fUseMinSigma) { if(idRec == kSpUndefined) continue; if(!fTrackCuts->CheckYCut ((BothParticleSpecies_t)idRec)) continue; } else { if(!fTrackCuts->CheckYCut ((BothParticleSpecies_t)irec)) continue; } // rapidity cut (reconstructed pt and identity) // if(!fTrackCuts->CheckYCut ((BothParticleSpecies_t)idRec)) continue; // Get true ID if ((idRec == idGen)&&(idGen != kSpUndefined)) fHistMan->GetHistogram2D(kHistPtRecTrue, idGen, charge)->Fill(track->Pt(),dca); if (isPrimary) { if(idRec!= kSpUndefined) // any primary fHistMan->GetHistogram2D(kHistPtRecSigmaPrimary, idRec, charge)->Fill(track->Pt(),dca); //if(idGen != kSpUndefined) //{ if((idGen != kSpUndefined) &&(irec == idGen)) // genereated primary but does not have to be selected useless for min sigma fHistMan->GetHistogram2D(kHistPtRecPrimary, idGen, charge)->Fill(track->Pt(),dca); if ((idGen != kSpUndefined) &&(idRec == idGen)) // genereated and selected correctly fHistMan->GetHistogram2D(kHistPtRecTruePrimary, idGen, charge)->Fill(track->Pt(),dca); //} } //25th Apr - Muons are added to Pions -- FIXME if ( pdgcode == 13 && idRec == kSpPion) { fHistMan->GetPtHistogram(kHistPtRecTrueMuonPlus)->Fill(track->Pt(),dca); if(isPrimary) fHistMan->GetPtHistogram(kHistPtRecTruePrimaryMuonPlus)->Fill(track->Pt(),dca); } if ( pdgcode == -13 && idRec == kSpPion) { fHistMan->GetPtHistogram(kHistPtRecTrueMuonMinus)->Fill(track->Pt(),dca); if (isPrimary) { fHistMan->GetPtHistogram(kHistPtRecTruePrimaryMuonMinus)->Fill(track->Pt(),dca); } } if(idRec == kSpUndefined) continue; //here we can use idGen in case of fit approach // Fill secondaries if(fMotherWDPDGcode>0) // if the Mother pdg is set we undo the Secondary flag in case it dose not match { if(motherpdg!=fMotherWDPDGcode) isSecondaryWeak=kFALSE; } if(fHistMan->GetIncludecorrectlyidentifiedinMCtemplates())// we have to check if genereted is the same as reconstructed { if(idRec!=idGen) continue; } if(isSecondaryWeak) fHistMan->GetHistogram2D(kHistPtRecSigmaSecondaryWeakDecay, idRec, charge)->Fill(track->Pt(),dca); if(isSecondaryMaterial) fHistMan->GetHistogram2D(kHistPtRecSigmaSecondaryMaterial , idRec, charge)->Fill(track->Pt(),dca); }//end if(arrayMC) } if(sel[0]&&sel[1]&&sel[2])//pi+k+p fHistMan->GetPtHistogram("hHistDoubleCounts")->Fill(track->Pt(),0); else if(sel[0]&&sel[1]) //pi+k fHistMan->GetPtHistogram("hHistDoubleCounts")->Fill(track->Pt(),1); else if(sel[0]&&sel[2]) //pi+k fHistMan->GetPtHistogram("hHistDoubleCounts")->Fill(track->Pt(),2); else if(sel[1]&&sel[2]) //p+k fHistMan->GetPtHistogram("hHistDoubleCounts")->Fill(track->Pt(),3); if(fmakePIDQAhisto) fPID->FillQAHistos(fHistMan, track, fTrackCuts,idGen); } // end loop on tracks // cout<< ntracks<<endl; fHistMan->GetGenMulvsRawMulHistogram("hHistGenMulvsRawMul")->Fill(npar,ntracks); fPID->SetoldT0(); PostData(1, fHistMan ); PostData(2, fEventCuts); PostData(3, fTrackCuts); PostData(4, fPID ); } //_________________________________________________________________ void AliAnalysisTaskSpectraBoth::Terminate(Option_t *) { // Terminate }
34.537906
345
0.63996
[ "object" ]
8c8ef5da8dac0a5f2f1bb2f33d5d8c311b9b5739
1,917
cpp
C++
test/doge/meta/partial_sum.cpp
cjdb/doge
421e1dce86df0eb73a6907408e93d0982adf057d
[ "Apache-2.0" ]
6
2017-10-13T23:01:29.000Z
2019-07-05T16:04:51.000Z
test/doge/meta/partial_sum.cpp
cjdb/doge
421e1dce86df0eb73a6907408e93d0982adf057d
[ "Apache-2.0" ]
46
2018-02-05T21:54:11.000Z
2018-03-12T10:00:08.000Z
test/doge/meta/partial_sum.cpp
cjdb/doge
421e1dce86df0eb73a6907408e93d0982adf057d
[ "Apache-2.0" ]
3
2018-02-07T14:15:51.000Z
2018-03-01T11:40:54.000Z
// // Copyright 2018 Christopher Di Bella // // 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 "doge/meta/partial_sum.hpp" #include <array> #include <vector> #include <utility> template <std::size_t... Sequence, std::size_t... Actual> constexpr bool test_partial_sum2(std::index_sequence<Sequence...>, std::index_sequence<Actual...>) noexcept { auto const sequence = std::array{Sequence...}; auto const actual = std::array{Actual...}; auto sum = std::size_t{}; for (auto i = decltype(actual.size()){}; i < size(actual); ++i) { sum += sequence[i]; if (sum != actual[i]) { return false; } } return true; } template <typename... Ts> constexpr bool test_partial_sum(Ts&&...) noexcept { return test_partial_sum2(std::index_sequence<sizeof(Ts)...>{}, doge::meta::partial_sum_t<sizeof(Ts)...>{}); } int main() { static_assert(test_partial_sum(0)); static_assert(test_partial_sum(0, 0)); static_assert(test_partial_sum(0, 0, 0)); static_assert(test_partial_sum(0, 0, 0, 0)); static_assert(test_partial_sum(0, 0, 0, 0, 0)); static_assert(test_partial_sum(0, 0, 0, 0, 0, 0)); static_assert(test_partial_sum(0, 0, 0, 0, 0, 0, 0)); static_assert(test_partial_sum(0, 0.0, 'a', L'a', U'a', "foo bar")); static_assert(test_partial_sum(std::vector<double>{}, 0.0f, 0, "foo, bar")); }
34.854545
111
0.663015
[ "vector" ]
8c9a8d20777d78c5c025e9831bfe87a782c430f7
5,016
cpp
C++
smtp-mail.cpp
foglamp/foglamp-notif-email
4cfe91614e8f9691f52a23a37215fe355349f296
[ "Apache-2.0" ]
null
null
null
smtp-mail.cpp
foglamp/foglamp-notif-email
4cfe91614e8f9691f52a23a37215fe355349f296
[ "Apache-2.0" ]
3
2019-01-17T09:02:22.000Z
2019-03-28T07:56:21.000Z
smtp-mail.cpp
foglamp/foglamp-notif-email
4cfe91614e8f9691f52a23a37215fe355349f296
[ "Apache-2.0" ]
null
null
null
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include <iostream> #include <cstring> #include <vector> #include <ctime> #include <curl/curl.h> #include <email_config.h> #include <logger.h> using namespace std; extern "C" { struct upload_status { int lines_read; vector<std::string>* payload; }; char *getCurrTime() { time_t rawtime; struct tm * timeinfo; static char buffer[80]; time (&rawtime); timeinfo = localtime (&rawtime); strftime (buffer, 80, "%a, %e %G %X %z", timeinfo); return buffer; } void compose_payload(vector<std::string>* &payload, const EmailCfg *emailCfg, const char* msg) { payload->push_back("Date: " + string(getCurrTime()) + "\r\n"); payload->push_back("To: " + emailCfg->email_to_name + " <" + emailCfg->email_to + "> \r\n"); payload->push_back("From: " + emailCfg->email_from_name + " <" + emailCfg->email_from + "> \r\n"); //payload->push_back("Message-ID: <" + emailCfg->messageId + ">\r\n"); payload->push_back("Subject: " + emailCfg->subject + "\r\n"); payload->push_back("\r\n"); payload->push_back(msg); payload->push_back("\r\n"); } static size_t payload_source(void *ptr, size_t size, size_t nmemb, void *userp) { struct upload_status *upload_ctx = (struct upload_status *)userp; if((size == 0) || (nmemb == 0) || ((size*nmemb) < 1)) { return 0; } if (upload_ctx->lines_read >= upload_ctx->payload->size()) return 0; std::string s = (*upload_ctx->payload)[upload_ctx->lines_read]; size_t len = s.length(); memcpy(ptr, s.c_str(), len); upload_ctx->payload->erase(upload_ctx->payload->begin()+upload_ctx->lines_read); return len; } int sendEmailMsg(const EmailCfg *emailCfg, const char *msg) { CURL *curl; CURLcode res = CURLE_OK; struct curl_slist *recipients = NULL; struct upload_status upload_ctx; upload_ctx.lines_read = 0; upload_ctx.payload = new vector<std::string>; compose_payload(upload_ctx.payload, emailCfg, msg); curl = curl_easy_init(); if(curl) { if(emailCfg->use_ssl_tls) { /* Set username and password */ curl_easy_setopt(curl, CURLOPT_USERNAME, emailCfg->username.c_str()); curl_easy_setopt(curl, CURLOPT_PASSWORD, emailCfg->password.c_str()); } /* This is the URL for your mailserver */ string proto = ""; if (emailCfg->server.find("smtp://") == std::string::npos) proto = "smtp://"; string server_url = proto + emailCfg->server + ":" + to_string(emailCfg->port); curl_easy_setopt(curl, CURLOPT_URL, server_url.c_str()); /* We'll start with a plain text connection, and upgrade * to Transport Layer Security (TLS) using the STARTTLS command. */ if(emailCfg->use_ssl_tls) { curl_easy_setopt(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_ALL); //curl_easy_setopt(curl, CURLOPT_CAINFO, "/path/to/certificate.pem"); } string email_from = "<" + emailCfg->email_from + ">"; curl_easy_setopt(curl, CURLOPT_MAIL_FROM, email_from.c_str()); string email_to = "<" + emailCfg->email_to + ">"; recipients = curl_slist_append(recipients, email_to.c_str()); //recipients = curl_slist_append(recipients, CC_ADDR); curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients); /* We're using a callback function to specify the payload (the headers and * body of the message). You could just use the CURLOPT_READDATA option to * specify a FILE pointer to read from. */ curl_easy_setopt(curl, CURLOPT_READFUNCTION, payload_source); curl_easy_setopt(curl, CURLOPT_READDATA, &upload_ctx); curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L); //curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); /* Send the message */ res = curl_easy_perform(curl); /* Check for errors */ if(res != CURLE_OK) fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); /* Free the list of recipients */ curl_slist_free_all(recipients); curl_easy_cleanup(curl); } delete upload_ctx.payload; return (int)res; } const char *errorString(int result) { return curl_easy_strerror((CURLcode)result); } };
30.962963
99
0.642344
[ "vector" ]
8ca99edac144b3a84a1dc484847c2228e5bba733
1,235
hh
C++
src/c++/include/workflow/MergeReferencesWorkflow.hh
Illumina/Isaac4
0924fba8b467868da92e1c48323b15d7cbca17dd
[ "BSD-3-Clause" ]
13
2018-02-09T22:59:39.000Z
2021-11-29T06:33:22.000Z
src/c++/include/workflow/MergeReferencesWorkflow.hh
Illumina/Isaac4
0924fba8b467868da92e1c48323b15d7cbca17dd
[ "BSD-3-Clause" ]
17
2018-01-26T11:36:07.000Z
2022-02-03T18:48:43.000Z
src/c++/include/workflow/MergeReferencesWorkflow.hh
Illumina/Isaac4
0924fba8b467868da92e1c48323b15d7cbca17dd
[ "BSD-3-Clause" ]
4
2018-10-19T20:00:00.000Z
2020-10-29T14:44:06.000Z
/** ** Isaac Genome Alignment Software ** Copyright (c) 2010-2017 Illumina, Inc. ** All rights reserved. ** ** This software is provided under the terms and conditions of the ** GNU GENERAL PUBLIC LICENSE Version 3 ** ** You should have received a copy of the GNU GENERAL PUBLIC LICENSE Version 3 ** along with this program. If not, see ** <https://github.com/illumina/licenses/>. ** ** \file MergeReferencesWorkflow.hh ** ** \brief merge multiple reference metadata into one ** ** \author Roman Petrovski **/ #ifndef iSAAC_WORKFLOW_MERGE_REFERENCES_WORKFLOW_HH #define iSAAC_WORKFLOW_MERGE_REFERENCES_WORKFLOW_HH #include "reference/SortedReferenceXml.hh" namespace isaac { namespace workflow { namespace bfs = boost::filesystem; class MergeReferencesWorkflow: boost::noncopyable { private: const std::vector<bfs::path> &filesToMerge_; const bfs::path &outputFilePath_; const bool makeAbsolutePaths_; public: MergeReferencesWorkflow( const std::vector<bfs::path> &filesToMerge, const bfs::path &outputFilePath, const bool bmakeAbsolutePaths); void run(); }; } // namespace workflow } // namespace isaac #endif // #ifndef iSAAC_WORKFLOW_MERGE_REFERENCES_WORKFLOW_HH
24.215686
79
0.734413
[ "vector" ]
8cbb062e6fd8228d3bfc3d09e5065e4179300bf7
25,239
cpp
C++
src/RobustDubins_Solver.cpp
CRL-Technion/Variable-speed-Dubins-with-wind
4c0cf8bb1ae11bcd78bffbba5392b892fee53608
[ "MIT" ]
null
null
null
src/RobustDubins_Solver.cpp
CRL-Technion/Variable-speed-Dubins-with-wind
4c0cf8bb1ae11bcd78bffbba5392b892fee53608
[ "MIT" ]
null
null
null
src/RobustDubins_Solver.cpp
CRL-Technion/Variable-speed-Dubins-with-wind
4c0cf8bb1ae11bcd78bffbba5392b892fee53608
[ "MIT" ]
null
null
null
#include<iostream> // std::cout, std::endl #include<cmath> #include<math.h> #include<RobustDubins_Solver.h> #include<MathTools.h> // constructor RobustDubins::Solver::Solver() { m_distanceErrorTolerance = 0.001; m_thetaErrorTolerance = 0.001; m_costTolerance = 0.0001; m_psNormalizedFlag = false; m_optimalSolutionID = -1; } // set functions void RobustDubins::Solver::set_problemStatement(RobustDubins::Problem& problemStatement) { // check if input problem is defined #ifndef NDEBUG if (!problemStatement.isDefined()) { throw std::runtime_error("RobustDubins::Solver::set_problemStatement: invalid entry"); } #endif m_problemStatementInput = problemStatement; // check if input problem is normalized if ((problemStatement.get_startPtInputFlag() == true) || (problemStatement.get_minTurningRadiusInputFlag() == true)) { normalizeProblem(); } else { // problem is already normalized, nothing to do m_problemStatementNorm = problemStatement; } // for convenience define these m_cth = cos(m_problemStatementNorm.get_hFinal()); m_sth = sin(m_problemStatementNorm.get_hFinal()); } void RobustDubins::Solver::set_distanceErrorTolerance(const double& distanceErrorTolerance) { #ifndef NDEBUG if (m_distanceErrorTolerance <= 0) { throw std::runtime_error("RobustDubins::Solver::set_distanceErrorTolerance: invalid value."); } #endif m_distanceErrorTolerance = distanceErrorTolerance; } void RobustDubins::Solver::set_thetaErrorTolerance(const double& thetaErrorTolerance) { #ifndef NDEBUG if (m_thetaErrorTolerance <= 0) { throw std::runtime_error("RobustDubins::Solver::set_thetaErrorTolerance: invalid value."); } #endif m_thetaErrorTolerance = thetaErrorTolerance; } void RobustDubins::Solver::set_costTolerance(const double& costTolerance) { #ifndef NDEBUG if (m_costTolerance <= 0) { throw std::runtime_error("RobustDubins::Solver::set_costTolerance: invalid value."); } #endif m_costTolerance = costTolerance; } // main functions void RobustDubins::Solver::normalizeProblem() { // translate double xFinalTranslated = m_problemStatementInput.get_xFinal() - m_problemStatementInput.get_xInitial(); double yFinalTranslated = m_problemStatementInput.get_yFinal() - m_problemStatementInput.get_yInitial(); // scale double R = m_problemStatementInput.get_minTurnRadius(); double xFinalScaled = xFinalTranslated / R; double yFinalScaled = yFinalTranslated / R; double hInitial = m_problemStatementInput.get_hInitial(); // rotate double xFinalRotated = xFinalScaled * cos(-hInitial) - yFinalScaled * sin(-hInitial); double yFinalRotated = xFinalScaled * sin(-hInitial) + yFinalScaled * cos(-hInitial); // adjust final heading double hFinalRotated = MathTools::mod(m_problemStatementInput.get_hFinal() - hInitial, 2.0 * M_PI); // define the normalized problem m_problemStatementNorm.set_stateInitial(0.0, 0.0, 0.0); m_problemStatementNorm.set_stateFinal(xFinalRotated, yFinalRotated, hFinalRotated); // TODO - normalize wind m_problemStatementNorm.wind_x = m_problemStatementInput.wind_x; m_problemStatementNorm.wind_y = m_problemStatementInput.wind_y; // flag indicating problem was normalized m_psNormalizedFlag = true; } void RobustDubins::Solver::solve() { m_LSL.set_pathType("LSL"); m_LSR.set_pathType("LSR"); m_RSL.set_pathType("RSL"); m_RSR.set_pathType("RSR"); m_LRL.set_pathType("LRL"); m_RLR.set_pathType("RLR"); // we operate on the normalized problem first // check if initial state is eq. to final state (in this case, no solving) if (compareEndpoints(m_problemStatementNorm.get_stateInitial(), m_problemStatementNorm.get_stateFinal())) { std::cout << "RobustDubins::Solver: start/endpoint are equal!" << std::endl; m_optimalSolutionType = "LSL"; // default choice m_optimalSolutionID = 0; m_LSL.set_solutionStatus("optimal"); m_LSL.set_cost(); m_optCost = 0; } else { solveBSB(); solveBBB(); if (m_psNormalizedFlag) { transformSolutions(); } compareCandidates(); // compare results to find optimal } } void RobustDubins::Solver::solveBBB() { // terminal conditions double x = m_problemStatementNorm.get_xFinal(); // final planar positions double y = m_problemStatementNorm.get_yFinal(); double h = MathTools::mod(m_problemStatementNorm.get_hFinal(), 2.0 * M_PI); // initialize variables vd bCandidate(2); vd aCandidate(4); double A, B, arg_atan_y, arg_atan_x, a, aSmall, aBig, c; bool endPtSat, condBBBSat; bool solutionFound = false; double v, w; for (int k = 4; k < 6; k++) { m_solnPtrs[k]->set_solutionStatus("infeasible"); m_solnPtrs[k]->set_cost(); } /* for (int k = 4; k < 6; k++) { std::string pathType = m_solnPtrs[k]->get_pathType(); if (pathType.compare("RLR") == 0) { v = (x + sin(h)) / 2.0; /// see Tang p.3 w = (-y - 1.0 + cos(h)) / 2.0; } else if (pathType.compare("LRL") == 0) { v = (x - sin(h)) / 2.0; /// see Tang p.3 w = (y - 1.0 + cos(h)) / 2.0; } bCandidate.at(0) = (acos(1 - (v * v + w * w) / 2.0)); // returns a soln [-pi/2,pi/2]; // check if bCandidate is "nan". if so, we do not proceed if (std::isnan(bCandidate.at(0))) { m_solnPtrs[k]->set_solutionStatus("infeasible"); m_solnPtrs[k]->set_cost(); } else { // otherwise continue if (bCandidate.at(0) < 0) { // make positive bCandidate.at(0) = -bCandidate.at(0); } bCandidate.at(1) = (2.0 * M_PI - bCandidate[0]); for (int i = 0; i < 2; i++) { // for each b candidate A = (v * v - w * w) / (2.0 * (1.0 - cos(bCandidate[i]))); B = v * w / (1.0 - cos(bCandidate[i])); arg_atan_y = (B * cos(bCandidate[i]) + A * sin(bCandidate[i])); arg_atan_x = (A * cos(bCandidate[i]) - B * sin(bCandidate[i])); a = 1.0 / 2.0 * atan2(arg_atan_y, arg_atan_x); // returns val from [-pi,pi] // check if aCandidate is "nan". if so, we do not proceed if (std::isnan(a)) { m_solnPtrs[k]->set_solutionStatus("infeasible"); m_solnPtrs[k]->set_cost(); } else { while (a < 0) { a = a + M_PI / 2; } // four possible values on the interval [0, 2*pi] aCandidate.at(0) = MathTools::mod(a, 2.0 * M_PI); aCandidate.at(1) = MathTools::mod(a + M_PI / 2.0, 2.0 * M_PI); aCandidate.at(2) = MathTools::mod(a + M_PI, 2.0 * M_PI); aCandidate.at(3) = MathTools::mod(a + 3.0 * M_PI / 2.0, 2.0 * M_PI); for (int j = 0; j < 4; j++) { // for each a candidate if (pathType.compare("RLR") == 0) { c = MathTools::mod(-h - aCandidate[j] + bCandidate[i], 2.0 * M_PI); } else if (pathType.compare("LRL") == 0) { c = MathTools::mod(h - aCandidate[j] + bCandidate[i], 2.0 * M_PI); } //check if this triple (a,b,c) satisfies endpoint endPtSat = RobustDubins::Solver::checkCandidateEndpoint(pathType, std::abs(aCandidate[j]), std::abs(bCandidate[i]), std::abs(c)); // also check if the triple satisfies additional BBB conditions condBBBSat = RobustDubins::Solver::checkBBBconditions(aCandidate[j], bCandidate[i], c); // if both satisfied, then declare this as a candidate Dubins path if (endPtSat && condBBBSat) { solutionFound = true; m_solnPtrs[k]->set_aParamUnsigned(std::abs(aCandidate[j])); m_solnPtrs[k]->set_bParamUnsigned(std::abs(bCandidate[i])); m_solnPtrs[k]->set_cParamUnsigned(std::abs(c)); m_solnPtrs[k]->set_solutionStatus("feasible"); m_solnPtrs[k]->set_wind(m_problemStatementNorm.wind_x, m_problemStatementNorm.wind_y); m_solnPtrs[k]->computeEndpoint(); m_solnPtrs[k]->set_cost(); } if (!solutionFound) { m_solnPtrs[k]->set_solutionStatus("infeasible"); m_solnPtrs[k]->set_cost(); } } } } } }*/ } double mod2pi(double x){ while(x >= 2*M_PI) x -= 2*M_PI; while(x < 0) x += 2*M_PI; return x; } double getGroundSpeed(double dir_x, double dir_y, double wind_x, double wind_y, double speed){ // normalize dir vector double tmp_len = sqrt(dir_x * dir_x + dir_y * dir_y); dir_x /= tmp_len; dir_y /= tmp_len; double b = wind_x * dir_x + wind_y * dir_y; double c = wind_x * wind_x + wind_y * wind_y - speed * speed; return (b + sqrt(b*b - c)); } double getHeadingFromDirection(double dir_x, double dir_y, double wind_x, double wind_y, double speed){ double groudSpeed = getGroundSpeed(dir_x, dir_y, wind_x, wind_y, speed); // normalize dir vector double tmp_len = sqrt(dir_x * dir_x + dir_y * dir_y); dir_x /= tmp_len; dir_y /= tmp_len; double air_x = dir_x * groudSpeed - wind_x; double air_y = dir_y * groudSpeed - wind_y; //air = normalize(dir) .* groudSpeed .- wind return atan2(air_y, air_x); } void RobustDubins::Solver::solveBSB() { // terminal conditions double x = m_problemStatementNorm.get_xFinal(); // final planar positions double y = m_problemStatementNorm.get_yFinal(); double h = MathTools::mod(m_problemStatementNorm.get_hFinal(), 2.0 * M_PI); double xi = m_problemStatementInput.get_xInitial(); double yi = m_problemStatementInput.get_yInitial(); double hi = m_problemStatementInput.get_hInitial(); double xf = m_problemStatementInput.get_xFinal(); double yf = m_problemStatementInput.get_yFinal(); double hf = m_problemStatementInput.get_hFinal(); double wind_x = m_problemStatementInput.wind_x; double wind_y = m_problemStatementInput.wind_y; double si = sin(hi); double ci = cos(hi); double sf = sin(hf); double cf = cos(hf); double a, b, c; double arg_atan_y, arg_atan_x; for (int k = 0; k < 4; k++) { // solnPtrs[2-6] : LSL, LSR, RSL, RSR std::string pathType = m_solnPtrs[k]->get_pathType(); if (pathType.compare("LSL") == 0) { for(int loop = 0; loop <= 2; loop++){ double turn = mod2pi(hf - hi) + loop * 2 * M_PI; // difference of turn origins double o_dx = si -sf +xf -xi -turn*wind_x; double o_dy = -ci +cf +yf -yi -turn*wind_y; double dir = getHeadingFromDirection(o_dx, o_dy, wind_x, wind_y, 1.); // compute lengths of the segments a = mod2pi(-hi + dir); b = sqrt(o_dx*o_dx + o_dy*o_dy) * 1 / getGroundSpeed(o_dx, o_dy, wind_x, wind_y, 1.); //TODO flag to find it c = turn - a; if(c > 0.){ m_solnPtrs[k]->set_aParamUnsigned(a); m_solnPtrs[k]->set_bParamUnsigned(b); m_solnPtrs[k]->set_cParamUnsigned(c); m_solnPtrs[k]->set_solutionStatus("feasible"); m_solnPtrs[k]->set_wind(wind_x, wind_y); m_solnPtrs[k]->computeEndpoint(); m_solnPtrs[k]->set_cost(); m_solnPtrs[k]->print(); break; } } } else if (pathType.compare("RSR") == 0) { for(int loop = 0; loop <= 2; loop++){ double turn = -mod2pi(-hf + hi) - loop * 2 * M_PI; // difference of turn origins double o_dx = -si +sf +xf -xi +turn*wind_x; double o_dy = ci -cf +yf -yi +turn*wind_y; double dir = getHeadingFromDirection(o_dx, o_dy, wind_x, wind_y, 1.); // compute lengths of the segments a = -mod2pi(hi - dir); b = sqrt(o_dx*o_dx + o_dy*o_dy) * 1 / getGroundSpeed(o_dx, o_dy, wind_x, wind_y, 1.); c = turn - a; if(c < 0.){ m_solnPtrs[k]->set_aParamUnsigned(-a); m_solnPtrs[k]->set_bParamUnsigned(b); m_solnPtrs[k]->set_cParamUnsigned(-c); m_solnPtrs[k]->set_solutionStatus("feasible"); m_solnPtrs[k]->set_wind(wind_x, wind_y); m_solnPtrs[k]->computeEndpoint(); m_solnPtrs[k]->set_cost(); m_solnPtrs[k]->print(); break; } } } else if (pathType.compare("LSR") == 0) { // TODO - here m_solnPtrs[k]->set_solutionStatus("infeasible"); m_solnPtrs[k]->set_cost(); } else if (pathType.compare("RSL") == 0) { // TODO - here m_solnPtrs[k]->set_solutionStatus("infeasible"); m_solnPtrs[k]->set_cost(); } else { m_solnPtrs[k]->set_solutionStatus("infeasible"); m_solnPtrs[k]->set_cost(); } } // end of candidate loop } bool RobustDubins::Solver::checkCandidateEndpoint(const std::string& pathType, const double& aCandidate, const double& bCandidate, const double& cCandidate) { // generate test endpoint using radius R = 1 vd testEndpoint(3); computeDubinsEndpoint(pathType, std::abs(aCandidate), std::abs(bCandidate), std::abs(cCandidate), 0.0, 0.0, 0.0, 1.0, testEndpoint); // return true if testEndpoint = stateFinal return compareEndpoints(testEndpoint, m_problemStatementNorm.get_stateFinal()); } bool RobustDubins::Solver::compareEndpoints(const vd& testState, const vd& trueState) { // compute distance error vd trueEndpoint = { trueState[0], trueState[1] }; vd testEndpoint = { testState[0], testState[1] }; double distance_error = MathTools::distance(trueEndpoint, testEndpoint); // compute heading error double theta_error = MathTools::polarDistance(trueState[2], testState[2]); if ((distance_error <= m_distanceErrorTolerance) && (theta_error <= m_thetaErrorTolerance)) return true; else return false; } bool RobustDubins::Solver::checkBBBconditions(const double& aCandidate, const double& bCandidate, const double& cCandidate) { // check magnitude conditions bool condition1 = std::max(aCandidate, cCandidate) < bCandidate; bool condition2 = std::min(aCandidate, cCandidate) < bCandidate + M_PI; return (condition1 && condition2); } void RobustDubins::Solver::transformSolutions() { double R = m_problemStatementInput.get_minTurnRadius(); for (int k = 0; k < 6; k++) { m_solnPtrs[k]->set_initialState(m_problemStatementInput.get_xInitial(), m_problemStatementInput.get_yInitial(), m_problemStatementInput.get_hInitial()); // if feasible or optimal (i.e., *not* infeasible) if (!(m_solnPtrs[k]->get_solutionStatus()).compare("infeasible") == 0) { m_solnPtrs[k]->set_minTurnRadius(R); double a = m_solnPtrs[k]->get_aParamUnsigned() * R; double b = m_solnPtrs[k]->get_bParamUnsigned() * R; double c = m_solnPtrs[k]->get_cParamUnsigned() * R; m_solnPtrs[k]->set_abcParamVectorUnsigned(a, b, c); // endpoint should be equal (approx.) to problem statement final point // if the path was computed correctly m_solnPtrs[k]->computeEndpoint(); } } } void RobustDubins::Solver::compareCandidates() { // store costs m_costVector.push_back(m_LSL.get_cost()); m_costVector.push_back(m_LSR.get_cost()); m_costVector.push_back(m_RSL.get_cost()); m_costVector.push_back(m_RSR.get_cost()); m_costVector.push_back(m_LRL.get_cost()); m_costVector.push_back(m_RLR.get_cost()); // compare costs m_minCostPaths = MathTools::minIndicesWithTolerance(m_costVector, m_costTolerance); m_numMinCostPaths = m_minCostPaths.size(); determineSolutionType(); } // determineSolutionType void RobustDubins::Solver::determineSolutionType() { // assume that: 0-LSL, 1-LSR, 2-RSL, 3-RSR, 4-LRL, 5-RLR, 6-LSR/RSR, 7-LRL/RLR if (m_numMinCostPaths == 1) { if (m_minCostPaths[0] == 0) { // LSL (only) m_optimalSolutionType = "LSL"; m_optimalSolutionID = 0; m_LSL.set_solutionStatus("optimal"); m_optCost = m_LSL.get_cost(); } else if (m_minCostPaths[0] == 1) { // LSR (only) m_optimalSolutionType = "LSR"; m_optimalSolutionID = 1; m_LSR.set_solutionStatus("optimal"); m_optCost = m_LSR.get_cost(); } else if (m_minCostPaths[0] == 2) { // RSL (only) m_optimalSolutionType = "RSL"; m_optimalSolutionID = 2; m_RSL.set_solutionStatus("optimal"); m_optCost = m_RSL.get_cost(); } else if (m_minCostPaths[0] == 3) { // RSR (only) m_optimalSolutionType = "RSR"; m_optimalSolutionID = 3; m_RSR.set_solutionStatus("optimal"); m_optCost = m_RSR.get_cost(); } else if (m_minCostPaths[0] == 4) { // LRL (only) m_optimalSolutionType = "LRL"; m_optimalSolutionID = 4; m_LRL.set_solutionStatus("optimal"); m_optCost = m_LRL.get_cost(); } else if (m_minCostPaths[0] == 5) { // RLR (only) m_optimalSolutionType = "RLR"; m_optimalSolutionID = 5; m_RLR.set_solutionStatus("optimal"); m_optCost = m_RLR.get_cost(); } } // if two paths have same cost they are either "LSL/RSR" or "LRL/RLR" else if (m_numMinCostPaths >= 2) { // Case: Two Optimal Solutions if ((m_minCostPaths[0] == 0 || m_minCostPaths[0] == 3) && (m_minCostPaths[1] == 0 || m_minCostPaths[1] == 3)) { // LSL-RSR m_optimalSolutionType = "LSL-RSR"; m_optimalSolutionID = 6; m_LSL.set_solutionStatus("optimal"); m_RSR.set_solutionStatus("optimal"); m_optCost = m_LSL.get_cost(); } else if ((m_minCostPaths[0] == 4 || m_minCostPaths[0] == 5) && (m_minCostPaths[1] == 4 || m_minCostPaths[1] == 5)) { // LRL-RLR m_optimalSolutionType = "LRL-RLR"; m_optimalSolutionID = 7; m_LRL.set_solutionStatus("optimal"); m_RLR.set_solutionStatus("optimal"); m_optCost = m_LRL.get_cost(); } // Case: Degenerate, some parameters are zero, we default to the first // min cost path else { m_optimalSolutionType = "degenerate"; m_optimalSolutionID = m_minCostPaths[0]; if (m_optimalSolutionID == 0) { m_LSL.set_solutionStatus("optimal"); m_optCost = m_LSL.get_cost(); } else if (m_optimalSolutionID == 1) { m_LSR.set_solutionStatus("optimal"); m_optCost = m_LSR.get_cost(); } else if (m_optimalSolutionID == 2) { m_RSL.set_solutionStatus("optimal"); m_optCost = m_RSL.get_cost(); } else if (m_optimalSolutionID == 3) { m_RSR.set_solutionStatus("optimal"); m_optCost = m_RSR.get_cost(); } else if (m_optimalSolutionID == 4) { m_LRL.set_solutionStatus("optimal"); m_optCost = m_LRL.get_cost(); } else if (m_optimalSolutionID == 5) { m_RLR.set_solutionStatus("optimal"); m_optCost = m_RLR.get_cost(); } } } } void RobustDubins::Solver::print() { printf("-------------------------------------------------\n"); printf(" RobustDubins::Solver Output \n"); printf("-------------------------------------------------\n"); printf("Type, Status, Cost, a, b, c\n"); for (int i = 0; i < 6; i++) { // get solution status and path type if ((m_solnPtrs[i]->get_solutionStatus()).compare("infeasible") == 0) { printf("%i) %s , %s , inf , %3.3f, %3.3f, %3.3f \n", i, (m_solnPtrs[i]->get_solutionStatus()).c_str(), (m_solnPtrs[i]->get_pathType()).c_str(), m_solnPtrs[i]->get_aParamUnsigned(), m_solnPtrs[i]->get_bParamUnsigned(), m_solnPtrs[i]->get_cParamUnsigned()); } else { printf("%i) %s , %s , %3.3f , %3.3f, %3.3f, %3.3f \n", i, (m_solnPtrs[i]->get_solutionStatus()).c_str(), (m_solnPtrs[i]->get_pathType()).c_str(), m_solnPtrs[i]->get_cost(), m_solnPtrs[i]->get_aParamUnsigned(), m_solnPtrs[i]->get_bParamUnsigned(), m_solnPtrs[i]->get_cParamUnsigned()); } } } void RobustDubins::Solver::writeOctaveCommandsToPlotSolution( const std::string& fileName, const int& figNum) { // iterate through the elements of m_solnPtrs for (int i = 0; i < 6; i++) { // get solution status and path type std::string solnStatus = m_solnPtrs[i]->get_solutionStatus(); std::string pathType = m_solnPtrs[i]->get_pathType(); // if solution found, compute path if (solnStatus.compare("feasible") == 0 || solnStatus.compare("optimal") == 0) { m_solnPtrs[i]->computePathHistory(); // if optimal, plot as solid red line if (solnStatus.compare("optimal") == 0) { m_solnPtrs[i]->writePathOctavePlotCommands(fileName, figNum, "x_" + pathType + "_opt", "y_" + pathType + "_opt", "r"); } // if suboptimal, plot as dashed black line else { m_solnPtrs[i]->writePathOctavePlotCommands(fileName, figNum, "x_" + pathType, "y_" + pathType, "k--"); } } } } // get functions RobustDubins::Path RobustDubins::Solver::get_optimalPath() { // assume that: // 0-LSL, // 1-LSR, // 2-RSL, // 3-RSR, // 4-LRL, // 5-RLR, // 6-LSL/RSR (both optimal, but we default to LSL) // 7-LRL/RLR (both optimal, but we default to LRL) if (m_optimalSolutionID == 0) { return m_LSL; } else if (m_optimalSolutionID == 1) { return m_LSR; } else if (m_optimalSolutionID == 2) { return m_RSL; } else if (m_optimalSolutionID == 3) { return m_RSR; } else if (m_optimalSolutionID == 4) { return m_LRL; } else if (m_optimalSolutionID == 5) { return m_RLR; } // when two solutions exist the one beginning with a left turn is returned else if (m_optimalSolutionID == 6) { return m_LSL; } else if (m_optimalSolutionID == 7) { return m_LRL; } } void RobustDubins::Solver::get_optimalWaypoints(vd& x, vd& y, vd& h) { int optSolnID; // if there are two solutions, return the left handed one if (m_optimalSolutionID == 6) { optSolnID = 0; // LSL } else if (m_optimalSolutionID == 7) { optSolnID = 4; // LRL } else { optSolnID = m_optimalSolutionID; } m_solnPtrs[optSolnID]->computePathHistory(); x = m_solnPtrs[optSolnID]->get_xHistory(); y = m_solnPtrs[optSolnID]->get_yHistory(); h = m_solnPtrs[optSolnID]->get_hHistory(); } void RobustDubins::Solver::get_optimalWaypointsSetSpacing(vd& x, vd& y, vd& h, double spacing) { int optSolnID; // if there are two solutions, return the left handed one if (m_optimalSolutionID == 6) { optSolnID = 0; // LSL } else if (m_optimalSolutionID == 7) { optSolnID = 4; // LRL } else { optSolnID = m_optimalSolutionID; } m_solnPtrs[optSolnID]->set_spacing(spacing); m_solnPtrs[optSolnID]->computePathHistory(); x = m_solnPtrs[optSolnID]->get_xHistory(); y = m_solnPtrs[optSolnID]->get_yHistory(); h = m_solnPtrs[optSolnID]->get_hHistory(); }
39.251944
124
0.569832
[ "vector", "solid" ]
8cbce4037a2a9962d2bbd9e40f4aeda3b776a176
11,768
hpp
C++
include/standard_hough_transform.hpp
yirami/hough-transform
5d74b8d267d448bf2c0fe52cbfe1f99a7e626e43
[ "MIT" ]
null
null
null
include/standard_hough_transform.hpp
yirami/hough-transform
5d74b8d267d448bf2c0fe52cbfe1f99a7e626e43
[ "MIT" ]
null
null
null
include/standard_hough_transform.hpp
yirami/hough-transform
5d74b8d267d448bf2c0fe52cbfe1f99a7e626e43
[ "MIT" ]
null
null
null
/** * Copyright (C) 2019 Yirami . * All rights reserved. * @file standard_hough_transform.hpp * @brief Template class for Standard Hough Transform(SHT) . * @author [Tang zhiyong](https://yirami.xyz) * @date 2019-06-25 * @version 1.0 * @note * @history **/ #ifndef _STANDARD_HOUGH_TRANSFORM_HPP_ #define _STANDARD_HOUGH_TRANSFORM_HPP_ #include <cmath> #include <array> #include <vector> #include <list> #include <cstring> #include "singleton.hpp" namespace YHoughTransform { using std::vector; using std::array; using std::list; template <typename T> struct TriMap { T angle; T sin; T cos; }; template <typename T=int> struct Point2D { T x; // along columns T y; // along rows }; template <typename T> struct HoughLine { T rho; // 0 is top-left corner T theta; // [-pi/2, pi/2) 0 for horizontal(right), positive(anti-clockwise) Point2D<> start_pt; Point2D<> end_pt; }; template <typename T, size_t PI_DIV=180> // [-pi/2, pi/2) class SHT { public: SHT(); ~SHT() {if (vote_map_) delete [] vote_map_;}; virtual void FeedImage(const unsigned char *img, const array<size_t, 2> &size_wh); inline void SetAngleFilter(); void SetAngleFilter(list<size_t> &filt) {theta_filter_ = filt;}; virtual void Vote(); // the only one to be invoked while debug vote map size_t GetThetaDiv() const {return theta_div_;}; // for debug vote map size_t GetRhoDiv() const {return rho_div_;}; // for debug vote map const size_t *GetVotePtr() const {return vote_map_;}; // for debug vote map void FindPeaks(const list<size_t> &angle_filter, size_t max_lines, vector<HoughLine<T>> &lines); inline void FindPeaks(size_t max_lines, vector<HoughLine<T>> &lines); inline void FindPeaksS(const list<size_t> &angle_filter, size_t max_lines, vector<HoughLine<T>> &lines); void FindLines(HoughLine<T> &line) const; void FindLines(vector<HoughLine<T>> &lines) const; inline void Radian2Degree(HoughLine<T> &line) const; inline void Radian2Degree(vector<HoughLine<T>> &lines) const; protected: T Rad2Deg_(T radian) const{return 180*radian/PI;}; T Deg2Rad_(T degree) const{return PI*degree/180;}; public: constexpr static T PI = 3.14159265358979; T NOISE_SCALE = 0.1; // give up short lines [scale*height] T SUPPRESS_THETA = 2; // degree T SUPPRESS_RHO = 3; size_t LINE_GAP = 5; protected: const unsigned char *img_ = nullptr; array<size_t, 2> img_size_wh_ = {{0}}; // [columns, rows] list<size_t> theta_filter_; T theta_res_ = PI/PI_DIV; // resolution of theta T rho_res_ = 1; // resolution of rho size_t theta_div_ = PI_DIV; size_t rho_div_ = 0; size_t *vote_map_ = nullptr; // FindPeaks() will modify vote map !!! static bool tri_map_init_; static array<TriMap<T>, PI_DIV> *tri_map_; }; template <typename T, size_t PI_DIV> bool SHT<T, PI_DIV>::tri_map_init_ = false; template <typename T, size_t PI_DIV> array<TriMap<T>, PI_DIV> * SHT<T, PI_DIV>::tri_map_ = \ YPattern::Singleton<array<TriMap<T>, PI_DIV>>::Get(); template <typename T, size_t PI_DIV> SHT<T, PI_DIV>::SHT() { SetAngleFilter(); if (!tri_map_init_) { for (size_t i=0; i<PI_DIV; i++) { tri_map_->at(i).angle = theta_res_*i-PI/2; tri_map_->at(i).sin = sin(tri_map_->at(i).angle); tri_map_->at(i).cos = cos(tri_map_->at(i).angle); } tri_map_init_ = true; } } template <typename T, size_t PI_DIV> void SHT<T, PI_DIV>::SetAngleFilter() { for (size_t i=0; i<PI_DIV; i++) // for (size_t i=30; i<PI_DIV-30; i++) theta_filter_.push_back(i); } template <typename T, size_t PI_DIV> void SHT<T, PI_DIV>::FeedImage(const unsigned char *img, const array<size_t, 2> &size_wh) { img_ = img; img_size_wh_ = size_wh; T rho_max = (T)sqrt(pow(size_wh[0]-1,2)+pow(size_wh[1]-1,2)); rho_div_ = (size_t)floor(rho_max/rho_res_+0.5)*2+1; // rho may be negative if (vote_map_) {delete [] vote_map_; vote_map_ = nullptr;} vote_map_ = new size_t[rho_div_*theta_div_]; std::memset(vote_map_, 0, rho_div_*theta_div_*sizeof(size_t)); } template <typename T, size_t PI_DIV> inline void SHT<T, PI_DIV>::Radian2Degree(HoughLine<T> &line) const{ line.theta = Rad2Deg_(line.theta); } template <typename T, size_t PI_DIV> inline void SHT<T, PI_DIV>::Radian2Degree(vector<HoughLine<T>> &lines) const{ for (auto &line:lines) line.theta = Rad2Deg_(line.theta); } template <typename T, size_t PI_DIV> void SHT<T, PI_DIV>::Vote() { const TriMap<T> *map_h = tri_map_->data(); T rho_shift = ((T)rho_div_-1)/2; for (size_t c=0; c<img_size_wh_[0]; c++) { for (size_t r=0; r<img_size_wh_[1]; r++) { if (img_[r*img_size_wh_[0]+c]) for (auto th:theta_filter_) { const T rho = floor((r*map_h[th].cos+c*map_h[th].sin)/rho_res_+0.5); vote_map_[PI_DIV*(size_t)(rho+rho_shift)+th]++; } } } } template <typename T, size_t PI_DIV> void SHT<T, PI_DIV>::FindPeaks(const list<size_t> &angle_filter, size_t max_lines, vector<HoughLine<T>> &lines) { array<int, 2> suppress = {(int)ceil(Deg2Rad_(SUPPRESS_THETA)/theta_res_), (int)ceil(SUPPRESS_RHO/rho_res_)}; lines.clear(); for (size_t i=0; i<max_lines; i++) { // search maximum vote size_t max_vote = 0; int max_r = 0, max_c = 0; for (auto c:angle_filter) { for (int r=0; r<(int)rho_div_; r++) if (vote_map_[(size_t)r*PI_DIV+c]>max_vote) { max_vote = vote_map_[(size_t)r*PI_DIV+c]; max_r = r; max_c = (int)c; } } if (max_vote<size_t(img_size_wh_[0]*NOISE_SCALE)) break; HoughLine<T> line = {0}; line.rho = rho_res_*(max_r-((T)rho_div_-1)/2); line.theta = tri_map_->at(max_c).angle; lines.push_back(line); // suppress in vote space const int start_r = max_r>suppress[1]?max_r-suppress[1]:0; const int end_r = max_r+suppress[1]<(int)rho_div_?max_r+suppress[1]+1:\ (int)rho_div_; // columns are handled differently because of angle's head-tail closure vector<int> theta_list; theta_list.push_back(max_c); for (int i=1; i<=suppress[0]; i++) { if (max_c<i) theta_list.push_back((int)theta_div_+max_c-i); else theta_list.push_back(max_c-i); if (max_c+i>=(int)theta_div_) theta_list.push_back(max_c+i-(int)theta_div_); else theta_list.push_back(max_c+i); } for (int c:theta_list) for (int r=start_r; r<end_r; r++) vote_map_[r*(int)theta_div_+c] = 0; } } template <typename T, size_t PI_DIV> inline void SHT<T, PI_DIV>::FindPeaks(size_t max_lines, vector<HoughLine<T>> &lines) { FindPeaks(theta_filter_, max_lines, lines); } template <typename T, size_t PI_DIV> inline void SHT<T, PI_DIV>::FindPeaksS(const list<size_t> &angle_filter, size_t max_lines, vector<HoughLine<T>> &lines) { // puppet for vote_map_ size_t *vote_map_puppet = new size_t[rho_div_*theta_div_]; std::memcpy(vote_map_puppet, vote_map_, rho_div_*theta_div_*sizeof(size_t)); size_t *vote_map_swap = vote_map_; vote_map_ = vote_map_puppet; FindPeaks(angle_filter, max_lines, lines); vote_map_ = vote_map_swap; delete [] vote_map_puppet; } template <typename T, size_t PI_DIV> void SHT<T, PI_DIV>::FindLines(HoughLine<T> &line) const { constexpr int shift = 16; const T rho = line.rho; const T theta = Rad2Deg_(line.theta); const T curr_sin = sin(line.theta); const T curr_cos = cos(line.theta); int r_start = 0; int c_start = (int)floor((rho-(T)r_start*curr_cos)/curr_sin); // determine whether the c_start overflows the boundary if (c_start<0) { c_start = 0; r_start = (int)floor((rho-(T)c_start*curr_sin)/curr_cos); } else if (c_start>=(int)img_size_wh_[0]) { c_start = (int)img_size_wh_[0]-1; r_start = (int)floor((rho-(T)c_start*curr_sin)/curr_cos); } bool bias_flag = false; int r0 = r_start, c0 = c_start, dr0, dc0; if (fabs(theta)>45) { bias_flag = true; dr0 = 1; dc0 = (int)floor(curr_cos*(T)(1 << shift)/fabs(curr_sin)+0.5); c0 = (c0 << shift)+(1 << (shift-1)); } else { dc0 = 1; dr0 = (int)floor(fabs(curr_sin)*(T)(1 << shift)/curr_cos+0.5); r0 = (r0 << shift)+(1 << (shift-1)); } if (theta>0) dc0 = -dc0; // walk along the line using fixed-point arithmetics, // ... stop at the image border int last_length = 0; Point2D<> line_start = {0}, line_end = {0}; for (int gap=0, c=c0, r=r0, start_p_flag =1; ; c+=dc0, r+=dr0) { int r1, c1; if (bias_flag) { c1 = c >> shift; r1 = r; } else { c1 = c; r1 = r >> shift; } if (c1<0||c1>=(int)img_size_wh_[0]||r1<0||r1>=(int)img_size_wh_[1]) { // ensure last_length has been update before exit int this_length = (int)floor(sqrt( pow((T)line_start.x-(T)line_end.x,2) + pow((T)line_start.y-(T)line_end.y,2))); if (this_length > last_length) { last_length = this_length; line.start_pt.x = line_start.x; line.start_pt.y = line_start.y; line.end_pt.x = line_end.x; line.end_pt.y = line_end.y; } break; } if (img_[r1*img_size_wh_[0]+c1]) { gap = 0; if (start_p_flag) { start_p_flag = 0; line_start.x = c1; line_start.y = r1; line_end.x = c1; line_end.y = r1; } else { line_end.x = c1; line_end.y = r1; } } else if (!start_p_flag) { // fuzzy processing the points beside line int left_p_flag = 0, right_p_flag = 0; if (c1>0 && img_[r1*img_size_wh_[0]+(c1-1)]) left_p_flag = 1; if (c1<(int)img_size_wh_[0]-1 && img_[r1*img_size_wh_[0]+(c1+1)]) right_p_flag = 1; if (left_p_flag || right_p_flag) { gap = 0; line_end.x = c1; line_end.y = r1; continue; } // end of line segment if (++gap > (int)LINE_GAP) { start_p_flag = 1; int this_length = (int)floor(sqrt( pow((T)line_start.x-(T)line_end.x,2) + pow((T)line_start.y-(T)line_end.y,2))); if (this_length > last_length) { last_length = this_length; // coordinate transformation line.start_pt.x = line_start.x; line.start_pt.y = line_start.y; line.end_pt.x = line_end.x; line.end_pt.y = line_end.y; } } } } // enhanced the robustness: none line segment are detected if (!last_length) { line.start_pt.x = r_start; line.start_pt.y = c_start; line.end_pt.x = r_start; line.end_pt.y = c_start; } } template <typename T, size_t PI_DIV> void SHT<T, PI_DIV>::FindLines(vector<HoughLine<T>> &lines) const{ for (auto &line:lines) FindLines(line); } } #endif
33.149296
86
0.580812
[ "vector", "transform" ]
8cbdb4f87370bf8911562d8f330262c2b4b027f5
9,251
cpp
C++
sensors/radars/echodyne/radar.cpp
mission-systems-pty-ltd/snark
2bc8a20292ee3684d3a9897ba6fee43fed8d89ae
[ "BSD-3-Clause" ]
1
2022-03-27T00:24:37.000Z
2022-03-27T00:24:37.000Z
sensors/radars/echodyne/radar.cpp
NEU-LC/snark
db890f73f4c4bbe679405f3a607fd9ea373deb2c
[ "BSD-3-Clause" ]
null
null
null
sensors/radars/echodyne/radar.cpp
NEU-LC/snark
db890f73f4c4bbe679405f3a607fd9ea373deb2c
[ "BSD-3-Clause" ]
1
2020-10-30T02:11:55.000Z
2020-10-30T02:11:55.000Z
// This file is part of snark, a generic and flexible library for robotics research // Copyright (c) 2020 Mission Systems Pty Ltd // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of the copyright owner nor the names of the contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE // GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT // HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE // OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN // IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <chrono> #include <vector> #include <comma/string/split.h> #include "echodyne.h" #include "types.h" #include "radar.h" namespace snark { namespace echodyne { radar::radar( const std::string& log_dir ) : connected( false ) { if( chdir( log_dir.c_str() ) != 0 ) { std::cerr << comma::verbose.app_name() << ": couldn't change to " << log_dir << std::endl; } radar_ = std::make_unique< bnet_interface >(); } radar::~radar() { if( connected ) { comma::verbose << "disconnecting from radar" << std::endl; radar_->disconnect(); } } void radar::connect( const std::string& address, int port, const std::string& log_dir ) { comma::verbose << "connecting to " << address << ":" << port << std::endl; radar_->connect( address.c_str(), port, log_dir ); connected = true; } void radar::command( const std::string& cmd ) { std::vector< std::string > cmd_words = comma::split( cmd ); if( cmd.empty() ) { return; } else if( cmd == "API:BUFFERS" ) { show_buffer_states(); } else if( cmd == "API:SYS_STATE" ) { show_system_state(); } else if( cmd_words[0] == "API:ENABLE_BUFFER" ) { try { enable_buffer( snark::echodyne::mesa_data_from_string( cmd_words[1] )); } catch( std::invalid_argument& ex ) { std::cerr << comma::verbose.app_name() << ": " << ex.what() << std::endl; } } else if( cmd_words[0] == "API:DISABLE_BUFFER" ) { try { disable_buffer( snark::echodyne::mesa_data_from_string( cmd_words[1] )); } catch( std::invalid_argument& ex ) { std::cerr << comma::verbose.app_name() << ": " << ex.what() << std::endl; } } else if( cmd == "CMD:SET_TIME" ) { set_time(); } else { send_command( cmd, true ); } } std::pair< unsigned int, unsigned int > radar::get_time() { auto [ success, response ] = send_command( "SYS:TIME?", comma::verbose ); if( !success ) { throw std::runtime_error( "" ); } std::vector< std::string > lines = comma::split( response, '\n' ); if( lines.size() == 0 ) { throw std::runtime_error( "tried to get time offset, got no response" ); } std::vector< std::string > words = comma::split( lines[0], ',' ); if( words.size() != 2 ) { throw std::runtime_error( "tried to get time offset, got \"" + lines[0] + "\"" ); } unsigned int days; unsigned int milliseconds; try { days = std::stoul( words[0] ); milliseconds = std::stoul( words[1] ); } catch( ... ) { throw std::runtime_error( "tried to read time offset, got \"" + lines[0] + "\"" ); } return std::pair( days, milliseconds ); } void radar::set_time_offset( unsigned int days, unsigned int milliseconds ) { bool success; std::string response; std::tie( success, response ) = send_command( "SYS:TIME " + std::to_string( days ) + "," + std::to_string( milliseconds ), comma::verbose ); if( !success ) { throw std::runtime_error( "" ); } } // see section 8.9 of the User Manual for the algorithm // essentially we are setting the offset to be from unix epoch rather than radar boot time void radar::set_time() { using namespace std::chrono; comma::verbose << "setting time" << std::endl; // clear any existing offsets and get the time from boot set_time_offset( 0, 0 ); auto [ days, ms ] = get_time(); system_clock::duration current_offset( seconds( days * 86400 )); current_offset += milliseconds( ms ); // get the current system time, calculate the offset required for that time, and set that offset system_clock::time_point now = system_clock::now(); system_clock::time_point required_offset = now - current_offset; auto required_offset_days( time_point_cast< seconds >( required_offset ).time_since_epoch().count() / 86400 ); auto required_offset_ms( time_point_cast< milliseconds >( required_offset ).time_since_epoch().count() - required_offset_days * 86400000 ); comma::verbose << "sending offset to set time to " << boost::posix_time::to_iso_string( boost::posix_time::from_time_t( system_clock::to_time_t( now ))) << " (plus some milliseconds)" << std::endl; set_time_offset( required_offset_days, required_offset_ms ); // check that the radar now reports the correct time in unix epoch std::tie( days, ms ) = get_time(); now = system_clock::now(); comma::verbose << "time set to days = " << days << "; milliseconds = " << ms << std::endl; system_clock::time_point radar_time( seconds( days * 86400 )); radar_time += milliseconds( ms ); auto error_ms = duration_cast< milliseconds >( radar_time - now ).count(); if( std::abs( error_ms ) < 10 ) { comma::verbose << "error with respect to system time = " << error_ms << "ms" << std::endl; } else { std::cerr << comma::verbose.app_name() << ": *WARNING* error with respect to system time = " << error_ms << "ms" << std::endl; } } std::pair< bool, std::string > radar::send_command( const std::string& cmd, bool verbose ) { comma::verbose << "sending " << cmd << std::endl; auto [ status, response ] = radar_->send_command( cmd ); if( status != MESA_OK ) { auto response_lines = comma::split( response, '\n' ); for( auto& s : response_lines ) { s.insert( 0, " " ); } std::cerr << comma::verbose.app_name() << ": " << "send_command: \"" << cmd << "\"" << "\n failed with status " << mesa_command_status_to_string( status ) << ", response was:\n" << comma::join( response_lines, '\n' ) << std::endl; } if( verbose ) { std::cerr << response << std::endl; } return std::pair( status == MESA_OK, response ); } void radar::show_buffer_state( mesa_data_t d_type ) { std::cerr << radar_->get_n_buffered( d_type ) << " / " << radar_->get_buffer_length( d_type ); if( radar_->get_collect( d_type )) { std::cerr << " collecting"; } if( radar_->get_save( d_type )) { std::cerr << " saving"; } } void radar::show_buffer_states() { std::cerr << "buffers:"; std::cerr << "\n status: "; show_buffer_state( STATUS_DATA ); std::cerr << "\n rvmap: "; show_buffer_state( RVMAP_DATA ); std::cerr << "\n detection: "; show_buffer_state( DETECTION_DATA ); std::cerr << "\n track: "; show_buffer_state( TRACK_DATA ); std::cerr << "\n meas: "; show_buffer_state( MEAS_DATA ); std::cerr << std::endl; } void radar::show_system_state() { MESAK_Status data_status_packet = radar_->get_status(); std::cerr << "system state queried at " << data_status_packet.data->sys_time_ms << "ms" << std::endl; std::cerr << " system state = " << snark::echodyne::system_state_to_string( data_status_packet.data->sys_state ) << " (" << data_status_packet.data->sys_state << ")" << std::endl; } // a single packet from the echodyne API might end up as multiple entries in the comma world template<> std::vector< status_data_t > radar::output_packet() { return from_packet( radar_->get_status() ); } template<> std::vector< rvmap_data_t > radar::output_packet() { return from_packet( radar_->get_rvmap() ); } template<> std::vector< detection_data_t > radar::output_packet() { return from_packet( radar_->get_detection() ); } template<> std::vector< track_data_t > radar::output_packet() { return from_packet( radar_->get_track() ); } template<> std::vector< meas_data_t > radar::output_packet() { return from_packet( radar_->get_meas() ); } } } // namespace snark { namespace echodyne {
47.685567
201
0.656902
[ "vector" ]
bc653ecb048e1c44725e21a254f367b7bd12de3f
2,541
cpp
C++
UKIEPC2020/l.cpp
JackBai0914/Competitive-Programming-Codebase
a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9
[ "MIT" ]
null
null
null
UKIEPC2020/l.cpp
JackBai0914/Competitive-Programming-Codebase
a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9
[ "MIT" ]
null
null
null
UKIEPC2020/l.cpp
JackBai0914/Competitive-Programming-Codebase
a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> #include <cmath> #include <vector> #include <cstring> #include <algorithm> using namespace std; const int N = 1 << 20; const double PI=acos(-1); struct cp { double re,im; cp(double _re=0.0,double _im=0.0) { re=_re; im=_im; } cp operator+(const cp& b) const { return cp(re+b.re,im+b.im); } cp operator-(const cp& b) const { return cp(re-b.re,im-b.im); } cp operator*(const cp& b) const { return cp(re*b.re-im*b.im,re*b.im+im*b.re); } } a[N],a2[N],a3[N],b[N],b2[N],b3[N],c1[N],c2[N],c3[N]; void fft(cp* A,int type); int n,m,lim,L,r[N]; int s[N],t[N]; vector<int> ans; int main() { int i; cin >> n >> m; string x; int y; for (i=0;i<n;++i) { cin >> x; if (x == "?") t[i] = 0; else { if (x == "n") t[i] = 1; if (x == "s") t[i] = 2; if (x == "e") t[i] = 3; if (x == "w") t[i] = 4; cin >> y; t[i] += 4 * y; } } for (i=0;i<m;++i) { cin >> x; if (x == "?") s[i] = 0; else { if (x == "n") s[i] = 1; if (x == "s") s[i] = 2; if (x == "e") s[i] = 3; if (x == "w") s[i] = 4; cin >> y; s[i] += 4 * y; } } for (i=0;i<n;++i) { if (m-i>0&&s[m-i-1]!=0) { a[i].re=s[m-i-1]; a2[i].re=a[i].re*a[i].re; a3[i].re=a[i].re*a2[i].re; } if (t[i]!=0) { b[i].re=t[i]; b2[i].re=b[i].re*b[i].re; b3[i].re=b[i].re*b2[i].re; } } for (lim=0,L=1;L<=n;++lim,L<<=1); for (i=1;i<L;++i) r[i]=(r[i>>1]>>1)|((i&1)<<(lim-1)); fft(a,1); fft(a2,1); fft(a3,1); fft(b,1); fft(b2,1); fft(b3,1); for (i=0;i<L;++i) { c1[i]=a[i]*b3[i]; c2[i]=a2[i]*b2[i]; c3[i]=a3[i]*b[i]; } fft(c1,-1); fft(c2,-1); fft(c3,-1); for (i=m-1;i<n;++i) { if (c1[i].re-2*c2[i].re+c3[i].re<0.5) { ans.push_back(i-m+2); } } printf("%d\n",int(ans.size())); // for (i=0;i<ans.size();++i) printf("%d ",ans[i]); return 0; } void fft(cp* A,int type) { int i,j,k; for (i=1;i<L;++i) if (i<r[i]) swap(A[i],A[r[i]]); for (i=1;i<L;i<<=1) { cp w1(cos(PI/i),type*sin(PI/i)); for (j=0;j<L;j+=2*i) { cp w(1,0); for (k=j;k<i+j;++k,w=w*w1) { cp t=A[k+i]*w; A[k+i]=A[k]-t; A[k]=A[k]+t; } } } if (type==-1) for (i=0;i<L;++i) A[i].re=A[i].re/L; }
18.962687
83
0.385675
[ "vector" ]
bc6e8bc68a308b5e3b5569b0636666d3ac16fcbb
614
cpp
C++
trview.graphics/PixelShader.cpp
sapper-trle/trview
dc9f945355a5976f2a539316a5dbf8323bb75064
[ "MIT" ]
null
null
null
trview.graphics/PixelShader.cpp
sapper-trle/trview
dc9f945355a5976f2a539316a5dbf8323bb75064
[ "MIT" ]
null
null
null
trview.graphics/PixelShader.cpp
sapper-trle/trview
dc9f945355a5976f2a539316a5dbf8323bb75064
[ "MIT" ]
null
null
null
#include "PixelShader.h" namespace trview { namespace graphics { PixelShader::PixelShader(const graphics::Device& device, const std::vector<uint8_t>& data) { if (data.empty()) { throw std::exception("Data for PixelShader cannot be empty"); } device.device()->CreatePixelShader(&data[0], data.size(), nullptr, &_pixel_shader); } void PixelShader::apply(const Microsoft::WRL::ComPtr<ID3D11DeviceContext>& context) { context->PSSetShader(_pixel_shader.Get(), nullptr, 0); } } }
26.695652
98
0.578176
[ "vector" ]
bc7aacb08777e410fb1639d3fcb016086c01ae86
8,657
cpp
C++
src/runjs_sm.cpp
kurazu/bridge
b44e4179233536f78f9161862655fe8527a01424
[ "MIT" ]
null
null
null
src/runjs_sm.cpp
kurazu/bridge
b44e4179233536f78f9161862655fe8527a01424
[ "MIT" ]
null
null
null
src/runjs_sm.cpp
kurazu/bridge
b44e4179233536f78f9161862655fe8527a01424
[ "MIT" ]
null
null
null
#include "runjs.hpp" #include <cstring> #include <string> /* The class of the global object. */ JSClass global_class = { "global", JSCLASS_GLOBAL_FLAGS }; void JSError::reset() { occured = false; if (message != NULL) { delete [] message; } message = NULL; if (file_name != NULL) { delete [] file_name; } file_name = NULL; line_no = 0; } static inline char * s_cpy(const char * str) { const size_t length = std::strlen(str); char * result = new char[length + 1]; std::strcpy(result, str); return result; } void JSError::set(const char * n_message, const char * n_file_name, unsigned n_line_no) { occured = true; message = s_cpy(n_message); file_name = s_cpy(n_file_name); line_no = n_line_no; } inline static JSError * get_js_error(const RunJSModuleState * module_state) { return (JSError *)JS_GetContextPrivate(module_state->context); } static void error_reporter(JSContext *context, const char *message, JSErrorReport *report) { JSError * context_data = (JSError *)JS_GetContextPrivate(context); context_data->set(message, report->filename, report->lineno); } static void enable_error_reporter(const RunJSModuleState * module_state) { JSError * context_data = get_js_error(module_state); context_data->reset(); JS_SetErrorReporter(module_state->runtime, error_reporter); } static void disable_error_reporter(const RunJSModuleState * module_state) { JS_SetErrorReporter(module_state->runtime, NULL); } void compile_js_func( const RunJSModuleState * module_state, const char * function_name, const char * file_name, const int line_no, const unsigned arg_count, const char *argnames[], const char * code, JS::MutableHandleFunction compiled_function ) { bool ok; JSAutoCompartment ac(module_state->context, module_state->global); JS::AutoObjectVector empty_scope_chain(module_state->context); JS::CompileOptions compile_options(module_state->context); compile_options.setFileAndLine(file_name, line_no); enable_error_reporter(module_state); ok = JS::CompileFunction( module_state->context, empty_scope_chain, compile_options, function_name, arg_count, argnames, code, strlen(code), compiled_function ); disable_error_reporter(module_state); if (!ok) { JSError * error = get_js_error(module_state); if (error->occured) { throw error; } else { throw "Failed to compile"; } } } static JS::HandleValueArray array_to_vector( const RunJSModuleState * module_state, JS::HandleValue array_value ) { bool ok; if (!array_value.isObject()) { throw "Expected parameter to be object"; } if (array_value.isNullOrUndefined()) { throw "Parameter is null or undefined"; } JS::RootedObject array_object(module_state->context, &array_value.toObject()); JS::AutoValueVector result(module_state->context); JS::RootedValue length_value(module_state->context); ok = JS_GetProperty(module_state->context, array_object, "length", &length_value); if (!ok) { throw "Couldn't get length"; } if (!length_value.isNumber()) { throw "Length is not a number"; } const int32_t length = length_value.toInt32(); for (int32_t i = 0; i < length; i++) { JS::RootedValue element(module_state->context); std::string key_string = std::to_string(i); const char * key_cstring = key_string.c_str(); ok = JS_GetProperty( module_state->context, array_object, key_cstring, &element ); if (!ok) { throw "Failed to get array element"; } result.append(element); } return result; } const char * run_js_func( const RunJSModuleState * module_state, JS::HandleFunction js_func, const char * arguments_json_cstring ) { bool ok; JSAutoCompartment ac(module_state->context, module_state->global); JS::RootedValue json(module_state->context); ok = JS_GetProperty(module_state->context, module_state->global, "JSON", &json); if (!ok) { throw "Failed to get JSON literal"; } if (!json.isObject()) { throw "JSON is not an object"; } if (json.isNullOrUndefined()) { throw "JSON is null or undefined"; } JS::RootedObject json_object(module_state->context, &json.toObject()); JS::RootedString arguments_json_string(module_state->context); JSString * arguments_json_jsstring = JS_NewStringCopyZ(module_state->context, arguments_json_cstring); if (arguments_json_jsstring == NULL) { throw "Couldn't convert arguments to JSString"; } arguments_json_string = arguments_json_jsstring; JS::RootedValue arguments_json_value(module_state->context, STRING_TO_JSVAL(arguments_json_string)); JS::AutoValueVector parse_args(module_state->context); parse_args.append(arguments_json_value); JS::RootedValue parse_result(module_state->context); ok = JS_CallFunctionName( module_state->context, json_object, "parse", parse_args, &parse_result ); if (!ok) { throw "Failed to parse arguments JSON"; } JS::HandleValueArray arguments = array_to_vector(module_state, parse_result); JS::RootedValue result(module_state->context); enable_error_reporter(module_state); ok = JS_CallFunction( module_state->context, JS::NullPtr(), js_func, arguments, &result ); disable_error_reporter(module_state); if (!ok) { JSError * error = get_js_error(module_state); if (error->occured) { throw error; } else { throw "JS function call failed"; } } if (result.isUndefined()) { /* Special case - undefined value cannot be serialized as JSON. * We will be treating it as null, so it can be serialized. */ result.setNull(); } JS::AutoValueVector stringify_args(module_state->context); stringify_args.append(result); JS::RootedValue stringify_result(module_state->context); ok = JS_CallFunctionName( module_state->context, json_object, "stringify", stringify_args, &stringify_result ); if (!ok) { throw "Couldn't covert result to JSON - stringify call failed"; } if (stringify_result.isNullOrUndefined()) { throw "Couldn't covert result to JSON - stringify result is null or undefined"; } if (!stringify_result.isString()) { throw "Couldn't covert result to JSON - stringify result is not a string"; } JS::RootedString stringify_result_string( module_state->context, stringify_result.toString() ); const char * result_cstring = JS_EncodeStringToUTF8( module_state->context, stringify_result_string ); if (result_cstring == NULL) { throw "Failed to convert stringify result to cstring"; } return result_cstring; } /* Initialize Spider Monkey JS engine and populate given module state struct */ void initialize_sm(RunJSModuleState * module_state) { JS_Init(); JSRuntime * runtime = JS_NewRuntime(8L * 1024 * 1024); if (!runtime) { throw "Failed to create JS runtime"; } module_state->runtime = runtime; JSContext * context = JS_NewContext(runtime, 8192); if (!context) { throw "Failed to create JS context"; } module_state->context = context; /* Allocate space for storing information about exceptions. */ JSError * js_error = new JSError(); JS_SetContextPrivate(context, (void *)js_error); JS::RootedObject global(context, JS_NewGlobalObject( context, &global_class, nullptr, JS::FireOnNewGlobalHook )); if (!global) { throw "Failed to create JS global object"; } module_state->global = global; JSAutoCompartment ac(module_state->context, module_state->global); bool ok = JS_InitStandardClasses(module_state->context, module_state->global); if (!ok) { throw "Failed to initialize standard JS classes"; } } /* Shutdown Spider Monkey JS engine */ void shutdown_sm(RunJSModuleState * module_state) { JSError * js_error = (JSError *)JS_GetContextPrivate(module_state->context); js_error->reset(); delete js_error; JS_SetContextPrivate(module_state->context, NULL); module_state->global.set(NULL); JS_DestroyContext(module_state->context); module_state->context = NULL; JS_DestroyRuntime(module_state->runtime); module_state->runtime = NULL; JS_ShutDown(); }
30.163763
106
0.673559
[ "object" ]
bc7f865b69c570d45c1b20713b3c2cd36f0da502
1,146
cc
C++
src/dependencies/libarchive-3.5.2/contrib/oss-fuzz/libarchive_fuzzer.cc
okaits/rpi-imager
7ff45328400104e3a2f9ca520572712ed0186766
[ "Apache-2.0" ]
107
2020-03-05T11:50:42.000Z
2020-03-09T10:40:49.000Z
src/dependencies/libarchive-3.5.2/contrib/oss-fuzz/libarchive_fuzzer.cc
okaits/rpi-imager
7ff45328400104e3a2f9ca520572712ed0186766
[ "Apache-2.0" ]
20
2020-03-05T15:20:18.000Z
2020-03-09T13:28:42.000Z
src/dependencies/libarchive-3.5.2/contrib/oss-fuzz/libarchive_fuzzer.cc
okaits/rpi-imager
7ff45328400104e3a2f9ca520572712ed0186766
[ "Apache-2.0" ]
14
2020-03-05T11:55:52.000Z
2020-03-08T12:16:19.000Z
#include <stddef.h> #include <stdint.h> #include <vector> #include "archive.h" struct Buffer { const uint8_t *buf; size_t len; }; ssize_t reader_callback(struct archive *a, void *client_data, const void **block) { Buffer *buffer = reinterpret_cast<Buffer *>(client_data); *block = buffer->buf; ssize_t len = buffer->len; buffer->len = 0; return len; } extern "C" int LLVMFuzzerTestOneInput(const uint8_t *buf, size_t len) { int ret; ssize_t r; struct archive *a = archive_read_new(); archive_read_support_filter_all(a); archive_read_support_format_all(a); Buffer buffer = {buf, len}; archive_read_open(a, &buffer, NULL, reader_callback, NULL); std::vector<uint8_t> data_buffer(getpagesize(), 0); struct archive_entry *entry; while(1) { ret = archive_read_next_header(a, &entry); if (ret == ARCHIVE_EOF || ret == ARCHIVE_FATAL) break; if (ret == ARCHIVE_RETRY) continue; while ((r = archive_read_data(a, data_buffer.data(), data_buffer.size())) > 0) ; if (r == ARCHIVE_FATAL) break; } archive_read_free(a); return 0; }
22.92
71
0.653578
[ "vector" ]
bc89c9fe53f2ce73618bc84661dc86948b785878
78,596
cpp
C++
src/sexp/Ast.cpp
WebAssembly/decompressor-prototype
44075ebeef75b950fdd9c0cd0b369928ef05a09c
[ "Apache-2.0" ]
11
2016-07-08T20:43:29.000Z
2021-05-09T21:43:34.000Z
src/sexp/Ast.cpp
DalavanCloud/decompressor-prototype
44075ebeef75b950fdd9c0cd0b369928ef05a09c
[ "Apache-2.0" ]
62
2016-06-07T15:21:24.000Z
2017-05-18T15:51:04.000Z
src/sexp/Ast.cpp
DalavanCloud/decompressor-prototype
44075ebeef75b950fdd9c0cd0b369928ef05a09c
[ "Apache-2.0" ]
5
2016-06-07T15:05:32.000Z
2020-01-06T17:21:43.000Z
// -*- C++ -*- // // Copyright 2016 WebAssembly Community Group participants // // 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. // // Implements AST's for modeling filter s-expressions #include "sexp/Ast.h" #include <algorithm> #include "interp/IntFormats.h" #include "sexp/TextWriter.h" #include "stream/WriteUtils.h" #include "utils/Casting.h" #include "utils/Trace.h" #include "sexp/Ast-templates.h" #define DEBUG_FILE 0 namespace wasm { using namespace decode; using namespace filt; using namespace interp; using namespace utils; namespace utils { void TraceClass::trace_node_ptr(const char* Name, const Node* Nd) { indent(); trace_value_label(Name); TextWriter Writer; Writer.writeAbbrev(File, Nd); } } // end of namespace utils. namespace filt { namespace { void errorDescribeContext(ConstNodeVectorType& Parents, const char* Context = "Context", bool Abbrev = true) { if (Parents.empty()) return; TextWriter Writer; FILE* Out = Parents[0]->getErrorFile(); fprintf(Out, "%s:\n", Context); for (size_t i = Parents.size() - 1; i > 0; --i) if (Abbrev) Writer.writeAbbrev(Out, Parents[i - 1]); else Writer.write(Out, Parents[i - 1]); } void errorDescribeNode(const char* Message, const Node* Nd, bool Abbrev = true) { TextWriter Writer; FILE* Out = Nd->getErrorFile(); if (Message) fprintf(Out, "%s:\n", Message); if (Abbrev) Writer.writeAbbrev(Out, Nd); else Writer.write(Out, Nd); } void errorDescribeNodeContext(const char* Message, const Node* Nd, ConstNodeVectorType& Parents, bool Abbrev = true) { errorDescribeNode(Message, Nd, Abbrev); errorDescribeContext(Parents, "Context", Abbrev); } void errorDescribeDuplicate(charstring Concept, const Node* New, const Node* Old, bool Abbrev = true) { fprintf(New->error(), "Duplicate %s entries:\n", Concept); errorDescribeNode("Duplicate", New, Abbrev); errorDescribeNode("Previous", Old, Abbrev); } static const char* PredefinedName[NumPredefinedSymbols]{"Unknown" #define X(NAME, name) , name PREDEFINED_SYMBOLS_TABLE #undef X }; bool extractIntTypeFormat(const Node* Nd, IntTypeFormat& Format) { Format = IntTypeFormat::Uint8; if (Nd == nullptr) return false; switch (Nd->getType()) { case NodeType::U8Const: Format = IntTypeFormat::Uint8; return true; case NodeType::I32Const: Format = IntTypeFormat::Varint32; return true; case NodeType::U32Const: Format = IntTypeFormat::Uint32; return true; case NodeType::I64Const: Format = IntTypeFormat::Varint64; return true; case NodeType::U64Const: Format = IntTypeFormat::Uint64; return true; default: return false; } } bool compareSymbolNodesLt(const Symbol* S1, const Symbol* S2) { return S1->getName() < S2->getName(); } } // end of anonymous namespace PredefinedSymbol toPredefinedSymbol(uint32_t Value) { if (Value < NumPredefinedSymbols) return PredefinedSymbol(Value); return PredefinedSymbol::Unknown; } const char* getName(PredefinedSymbol Sym) { uint32_t Index = uint32_t(Sym); assert(Index < NumPredefinedSymbols); return PredefinedName[Index]; } AstTraitsType AstTraits[NumNodeTypes] = { #define X(NAME, opcode, sexp_name, text_num_args, text_max_args, NSL, hidden) \ {NodeType::NAME, #NAME, sexp_name, text_num_args, text_max_args, NSL, hidden}, AST_OPCODE_TABLE #undef X }; const AstTraitsType* getAstTraits(NodeType Type) { static std::unordered_map<int, AstTraitsType*> Mapping; if (Mapping.empty()) { for (size_t i = 0; i < NumNodeTypes; ++i) { AstTraitsType* Traits = &AstTraits[i]; Mapping[size_t(Traits->Type)] = Traits; } } AstTraitsType* Traits = Mapping[size_t(Type)]; if (Traits) return Traits; // Unknown case, make up entry Traits = new AstTraitsType(); Traits->Type = Type; std::string NewName(std::string("NodeType::") + std::to_string(static_cast<int>(Type))); char* Name = new char[NewName.size() + 1]; Name[NewName.size()] = '\0'; memcpy(Name, NewName.data(), NewName.size()); Traits->TypeName = Name; Traits->SexpName = Name; Traits->NumTextArgs = 1; Traits->AdditionalTextArgs = 0; Traits->NeverSameLineInText = false; Traits->HidesSeqInText = false; Mapping[size_t(Type)] = Traits; return Traits; } const char* getNodeSexpName(NodeType Type) { const AstTraitsType* Traits = getAstTraits(Type); charstring Name = Traits->SexpName; if (Name) return Name; Name = Traits->TypeName; if (Name) return Name; return "?Unknown?"; } const char* getNodeTypeName(NodeType Type) { const AstTraitsType* Traits = getAstTraits(Type); charstring Name = Traits->TypeName; if (Name) return Name; Name = Traits->SexpName; if (Name) return Name; return "?Unknown?"; } Node::Iterator::Iterator(const Node* Nd, int Index) : Nd(Nd), Index(Index) {} Node::Iterator::Iterator(const Iterator& Iter) : Nd(Iter.Nd), Index(Iter.Index) {} bool Node::isTextVisible() const { switch (getType()) { default: return true; #define X(NAME) case NodeType::NAME: AST_TEXTINVISIBLE_TABLE #undef X return false; } } Node::Iterator& Node::Iterator::operator=(const Iterator& Iter) { Nd = Iter.Nd; Index = Iter.Index; return *this; } bool Node::Iterator::operator==(const Iterator& Iter) { return Nd == Iter.Nd && Index == Iter.Index; } bool Node::Iterator::operator!=(const Iterator& Iter) { return Nd != Iter.Nd || Index != Iter.Index; } Node* Node::Iterator::operator*() const { return Nd->getKid(Index); } Node::Node(SymbolTable& Symtab, NodeType Type) : Type(Type), Symtab(Symtab), CreationIndex(Symtab.getNextCreationIndex()) {} Node::~Node() {} int Node::compare(const Node* Nd) const { if (this == Nd) return 0; int Diff = nodeCompare(Nd); if (Diff != 0) return Diff; // Structurally compare subtrees. Note; we assume that if nodeCompare()==0, // the node must have the same number of children. std::vector<const Node*> Frontier; Frontier.push_back(this); Frontier.push_back(Nd); while (!Frontier.empty()) { const Node* Nd2 = Frontier.back(); Frontier.pop_back(); assert(!Frontier.empty()); const Node* Nd1 = Frontier.back(); Frontier.pop_back(); assert(Nd1->getNumKids() == Nd2->getNumKids()); for (int i = 0, Size = Nd1->getNumKids(); i < Size; ++i) { const Node* Kid1 = Nd1->getKid(i); const Node* Kid2 = Nd2->getKid(i); if (Kid1 == Kid2) continue; Diff = Kid1->nodeCompare(Kid2); if (Diff != 0) return Diff; Frontier.push_back(Kid1); Frontier.push_back(Kid2); } } return 0; } int Node::nodeCompare(const Node* Nd) const { return int(Type) - int(Nd->Type); } int Node::compareIncomparable(const Node* Nd) const { // First use creation index to try and make value consistent between runs. int Diff = getCreationIndex() - Nd->getCreationIndex(); if (Diff != 0) return Diff; // At this point, drop to implementation detail. if (this < Nd) return -1; if (this > Nd) return 1; return 0; } bool Node::definesIntTypeFormat() const { IntTypeFormat Format; return extractIntTypeFormat(this, Format); } const char* Node::getName() const { return getNodeSexpName(getType()); } const char* Node::getNodeName() const { return getNodeTypeName(getType()); } void Node::setLastKid(Node* N) { setKid(getNumKids() - 1, N); } Node* Node::getLastKid() const { if (int Size = getNumKids()) return getKid(Size - 1); return nullptr; } Node::Iterator Node::begin() const { return Iterator(this, 0); } Node::Iterator Node::end() const { return Iterator(this, getNumKids()); } Node::Iterator Node::rbegin() const { return Iterator(this, getNumKids() - 1); } Node::Iterator Node::rend() const { return Iterator(this, -1); } IntTypeFormat Node::getIntTypeFormat() const { IntTypeFormat Format; extractIntTypeFormat(this, Format); return Format; } size_t Node::getTreeSize() const { size_t Count = 0; std::vector<const Node*> ToVisit; ToVisit.push_back(this); while (!ToVisit.empty()) { const Node* Nd = ToVisit.back(); ToVisit.pop_back(); ++Count; for (const Node* Kid : *Nd) ToVisit.push_back(Kid); } return Count; } IntegerValue::IntegerValue() : Type(NodeType::NO_SUCH_NODETYPE), Value(0), Format(decode::ValueFormat::Decimal), isDefault(false) {} IntegerValue::IntegerValue(decode::IntType Value, decode::ValueFormat Format) : Type(NodeType::NO_SUCH_NODETYPE), Value(Value), Format(Format), isDefault(false) {} IntegerValue::IntegerValue(NodeType Type, decode::IntType Value, decode::ValueFormat Format, bool isDefault) : Type(Type), Value(Value), Format(Format), isDefault(isDefault) {} IntegerValue::IntegerValue(const IntegerValue& V) : Type(V.Type), Value(V.Value), Format(V.Format), isDefault(V.isDefault) {} void IntegerValue::describe(FILE* Out) const { fprintf(Out, "%s<", getNodeSexpName(Type)); writeInt(Out, Value, Format); fprintf(Out, ", %s>", getName(Format)); } IntegerValue::~IntegerValue() {} int IntegerValue::compare(const IntegerValue& V) const { if (Type < V.Type) return -1; if (Type > V.Type) return 1; if (Value < V.Value) return -1; if (Value > V.Value) return 1; if (Format < V.Format) return -1; if (Format > V.Format) return 1; return int(isDefault) - int(V.isDefault); } void Node::append(Node*) { decode::fatal("Node::append not supported for ast node!"); } bool Node::validateKid(ConstNodeVectorType& Parents, const Node* Kid) const { Parents.push_back(this); bool Result = Kid->validateSubtree(Parents); Parents.pop_back(); return Result; } bool Node::validateKids(ConstNodeVectorType& Parents) const { if (!hasKids()) return true; TRACE(int, "NumKids", getNumKids()); for (auto* Kid : *this) if (!validateKid(Parents, Kid)) return false; return true; } bool Node::validateSubtree(ConstNodeVectorType& Parents) const { TRACE_METHOD("validateSubtree"); TRACE(node_ptr, nullptr, this); if (!validateNode(Parents)) return false; return validateKids(Parents); } bool Node::validateNode(ConstNodeVectorType& Scope) const { TRACE_METHOD("validateNode"); return true; } Cached::Cached(SymbolTable& Symtab, NodeType Type) : Nullary(Symtab, Type) {} Cached::~Cached() {} int Cached::nodeCompare(const Node* Nd) const { int Diff = Nullary::nodeCompare(Nd); if (Diff != 0) return Diff; return compareIncomparable(Nd); } bool Cached::implementsClass(NodeType Type) { switch (Type) { default: return false; #define X(NAME) case NodeType::NAME: AST_CACHEDNODE_TABLE #undef X return true; } } IntLookup::IntLookup(SymbolTable& Symtab) : Cached(Symtab, NodeType::IntLookup) {} IntLookup::~IntLookup() {} const Node* IntLookup::get(decode::IntType Value) { if (Lookup.count(Value)) return Lookup[Value]; return nullptr; } bool IntLookup::add(decode::IntType Value, const Node* Nd) { if (Lookup.count(Value)) return false; Lookup[Value] = Nd; return true; } SymbolDefn::SymbolDefn(SymbolTable& Symtab) : Cached(Symtab, NodeType::SymbolDefn), ForSymbol(nullptr), DefineDefinition(nullptr), LiteralDefinition(nullptr), LiteralActionDefinition(nullptr) {} SymbolDefn::~SymbolDefn() {} const std::string& SymbolDefn::getName() const { if (ForSymbol) return ForSymbol->getName(); static std::string Unknown("???"); return Unknown; } const Define* SymbolDefn::getDefineDefinition() const { if (DefineDefinition) return DefineDefinition; // Not defined locally, find enclosing definition. if (ForSymbol == nullptr) return nullptr; const std::string& Name = ForSymbol->getName(); for (SymbolTable* Scope = &Symtab; Scope != nullptr; Scope = Scope->getEnclosingScope().get()) { SymbolDefn* SymDef = Scope->getSymbolDefn(Scope->getOrCreateSymbol(Name)); if (SymDef == nullptr) continue; if (SymDef->DefineDefinition) return DefineDefinition = SymDef->DefineDefinition; } return nullptr; } void SymbolDefn::setDefineDefinition(const Define* Defn) { if (DefineDefinition) { errorDescribeNode("Old", DefineDefinition); errorDescribeNode("New", Defn); fatal("Multiple defines for symbol: " + getName()); return; } DefineDefinition = Defn; } void SymbolDefn::setLiteralDefinition(const LiteralDef* Defn) { if (LiteralDefinition) { errorDescribeNode("Old", LiteralDefinition); errorDescribeNode("New", Defn); fatal("Multiple defines for symbol: " + getName()); return; } LiteralDefinition = Defn; } const LiteralDef* SymbolDefn::getLiteralDefinition() const { if (LiteralDefinition) return LiteralDefinition; // Not defined locally, find enclosing definition. if (ForSymbol == nullptr) return nullptr; const std::string& Name = ForSymbol->getName(); for (SymbolTable* Scope = &Symtab; Scope != nullptr; Scope = Scope->getEnclosingScope().get()) { SymbolDefn* SymDef = Scope->getSymbolDefn(Scope->getOrCreateSymbol(Name)); if (SymDef == nullptr) continue; if (SymDef->LiteralDefinition) return LiteralDefinition = SymDef->LiteralDefinition; } return nullptr; } void SymbolDefn::setLiteralActionDefinition(const LiteralActionDef* Defn) { if (LiteralActionDefinition) { errorDescribeNode("Old", LiteralActionDefinition); errorDescribeNode("New", Defn); fatal("Multiple action defines for symbol: " + getName()); return; } LiteralActionDefinition = Defn; } const LiteralActionDef* SymbolDefn::getLiteralActionDefinition() const { if (LiteralActionDefinition) return LiteralActionDefinition; // Not defined locally, find enclosing definition. if (ForSymbol == nullptr) return nullptr; const std::string& Name = ForSymbol->getName(); for (SymbolTable* Scope = &Symtab; Scope != nullptr; Scope = Scope->getEnclosingScope().get()) { SymbolDefn* SymDef = Scope->getSymbolDefn(Scope->getOrCreateSymbol(Name)); if (SymDef == nullptr) continue; if (SymDef->LiteralActionDefinition) return LiteralActionDefinition = SymDef->LiteralActionDefinition; } return nullptr; } Symbol::Symbol(SymbolTable& Symtab, const std::string& Name) : Nullary(Symtab, NodeType::Symbol), Name(Name) { init(); } Symbol::~Symbol() {} void Symbol::init() { PredefinedValue = PredefinedSymbol::Unknown; PredefinedValueIsCached = false; } int Symbol::nodeCompare(const Node* Nd) const { int Diff = Nullary::nodeCompare(Nd); if (Diff != 0) return Diff; assert(isa<Symbol>(Nd)); const auto* SymNd = cast<Symbol>(Nd); return Name.compare(SymNd->Name); } SymbolDefn* Symbol::getSymbolDefn() const { SymbolDefn* Defn = cast<SymbolDefn>(Symtab.getCachedValue(this)); if (Defn == nullptr) { Defn = Symtab.create<SymbolDefn>(); Defn->setSymbol(this); Symtab.setCachedValue(this, Defn); } return Defn; } void Symbol::setPredefinedSymbol(PredefinedSymbol NewValue) { if (PredefinedValueIsCached) fatal(std::string("Can't define \"") + filt::getName(PredefinedValue) + " and " + filt::getName(NewValue)); PredefinedValue = NewValue; PredefinedValueIsCached = true; } std::map<std::string, SymbolTable::SharedPtr>* SymbolTable::AlgorithmRegistry = nullptr; SymbolTable::SymbolTable(std::shared_ptr<SymbolTable> EnclosingScope) : EnclosingScope(EnclosingScope) { init(); } SymbolTable::SymbolTable() { init(); } void SymbolTable::init() { Alg = nullptr; setAlgorithm(nullptr); NextCreationIndex = 0; ActionBase = 0; Err = create<Error>(); BlockEnterCallback = nullptr; BlockExitCallback = nullptr; CachedSourceHeader = nullptr; CachedReadHeader = nullptr; CachedWriteHeader = nullptr; } SymbolTable::~SymbolTable() { clearSymbols(); deallocateNodes(); } SymbolTable::SharedPtr SymbolTable::getRegisteredAlgorithm(std::string Name) { if (AlgorithmRegistry == nullptr) AlgorithmRegistry = new std::map<std::string, SharedPtr>(); if (AlgorithmRegistry->count(Name) > 0) return (*AlgorithmRegistry)[Name]; return SymbolTable::SharedPtr(); } void SymbolTable::registerAlgorithm(SharedPtr Alg) { if (AlgorithmRegistry == nullptr) AlgorithmRegistry = new std::map<std::string, SharedPtr>(); std::string AlgName; if (const Symbol* AlgSym = Alg->getAlgorithmName()) AlgName = AlgSym->getName(); (*AlgorithmRegistry)[AlgName] = Alg; } const Callback* SymbolTable::getBlockEnterCallback() { if (BlockEnterCallback == nullptr) BlockEnterCallback = create<Callback>(getPredefined(PredefinedSymbol::Block_enter)); return BlockEnterCallback; } const Callback* SymbolTable::getBlockExitCallback() { if (BlockExitCallback == nullptr) BlockExitCallback = create<Callback>(getPredefined(PredefinedSymbol::Block_exit)); return BlockExitCallback; } FILE* SymbolTable::getErrorFile() const { return stderr; } FILE* SymbolTable::error() const { FILE* Out = getErrorFile(); fputs("Error: ", Out); return Out; } const Symbol* SymbolTable::getAlgorithmName() const { if (Alg == nullptr) return nullptr; return Alg->getName(); } Symbol* SymbolTable::getSymbol(const std::string& Name) { if (SymbolMap.count(Name)) return SymbolMap[Name]; return nullptr; } SymbolDefn* SymbolTable::getSymbolDefn(const Symbol* Sym) { SymbolDefn* Defn = cast<SymbolDefn>(getCachedValue(Sym)); if (Defn == nullptr) { Defn = create<SymbolDefn>(); Defn->setSymbol(Sym); setCachedValue(Sym, Defn); } return Defn; } void SymbolTable::insertCallbackLiteral(const LiteralActionDef* Defn) { CallbackLiterals.insert(Defn); } void SymbolTable::insertCallbackValue(const IntegerNode* IntNd) { CallbackValues.insert(IntNd); } void SymbolTable::collectActionDefs(ActionDefSet& DefSet) { SymbolTable* Scope = this; while (Scope) { for (const LiteralActionDef* Def : Scope->CallbackLiterals) DefSet.insert(Def); Scope = Scope->getEnclosingScope().get(); } } void SymbolTable::clearSymbols() { SymbolMap.clear(); } void SymbolTable::setTraceProgress(bool NewValue) { if (!NewValue && !Trace) return; getTrace().setTraceProgress(NewValue); } void SymbolTable::setTrace(std::shared_ptr<TraceClass> NewTrace) { Trace = NewTrace; } std::shared_ptr<TraceClass> SymbolTable::getTracePtr() { if (!Trace) setTrace(std::make_shared<TraceClass>("SymbolTable")); return Trace; } void SymbolTable::deallocateNodes() { for (Node* Nd : Allocated) delete Nd; } Symbol* SymbolTable::getOrCreateSymbol(const std::string& Name) { Symbol* Nd = SymbolMap[Name]; if (Nd == nullptr) { Nd = new Symbol(*this, Name); Allocated.push_back(Nd); SymbolMap[Name] = Nd; } return Nd; } Symbol* SymbolTable::getPredefined(PredefinedSymbol Sym) { Symbol* Nd = PredefinedMap[Sym]; if (Nd != nullptr) return Nd; Nd = getOrCreateSymbol(PredefinedName[uint32_t(Sym)]); Nd->setPredefinedSymbol(Sym); PredefinedMap[Sym] = Nd; return Nd; } #define X(NAME, FORMAT, DEFAULT, MERGE, BASE, DECLS, INIT) \ template <> \ NAME* SymbolTable::create<NAME>(IntType Value, ValueFormat Format) { \ if (MERGE) { \ IntegerValue I(NodeType::NAME, Value, Format, false); \ BASE* Nd = IntMap[I]; \ if (Nd == nullptr) { \ Nd = new NAME(*this, Value, Format); \ Allocated.push_back(Nd); \ IntMap[I] = Nd; \ } \ return dyn_cast<NAME>(Nd); \ } \ NAME* Nd = new NAME(*this, Value, Format); \ Allocated.push_back(Nd); \ return Nd; \ } \ template <> \ NAME* SymbolTable::create<NAME>() { \ if (MERGE) { \ IntegerValue I(NodeType::NAME, (DEFAULT), ValueFormat::Decimal, true); \ BASE* Nd = IntMap[I]; \ if (Nd == nullptr) { \ Nd = new NAME(*this); \ Allocated.push_back(Nd); \ IntMap[I] = Nd; \ } \ return dyn_cast<NAME>(Nd); \ } \ NAME* Nd = new NAME(*this); \ Allocated.push_back(Nd); \ return Nd; \ } AST_INTEGERNODE_TABLE #undef X #define X(NAME, BASE, VALUE, FORMAT, DECLS, INIT) \ template <> \ NAME* SymbolTable::create<NAME>() { \ IntegerValue I(NodeType::NAME, (VALUE), ValueFormat::FORMAT, true); \ BASE* Nd = IntMap[I]; \ if (Nd == nullptr) { \ Nd = new NAME(*this); \ Allocated.push_back(Nd); \ IntMap[I] = Nd; \ } \ return dyn_cast<NAME>(Nd); \ } AST_LITERAL_TABLE #undef X bool SymbolTable::areActionsConsistent() { #if DEBUG_FILE // Debugging information. fprintf(stderr, "******************\n"); fprintf(stderr, "Symbolic actions:\n"); TextWriter Writer; for (const LiteralActionDef* Def : CallbackLiterals) { Writer.write(stderr, Def); } fprintf(stderr, "Hard coded actions:\n"); for (const IntegerNode* Val : CallbackValues) { Writer.write(stderr, Val); } fprintf(stderr, "Undefined actions:\n"); for (const Symbol* Sym : UndefinedCallbacks) { Writer.write(stderr, Sym); } fprintf(stderr, "******************\n"); #endif std::map<IntType, const Node*> DefMap; // First install hard coded (ignoring duplicates). for (const IntegerNode* IntNd : CallbackValues) { DefMap[IntNd->getValue()] = IntNd; } // Create values for undefined actions. bool IsValid = true; // Until proven otherwise. constexpr IntType EnumGap = 100; // gap for future expansion IntType NextEnumValue = ActionBase ? ActionBase : NumPredefinedSymbols + EnumGap; for (const LiteralActionDef* Def : CallbackLiterals) { const IntegerNode* IntNd = dyn_cast<IntegerNode>(Def->getKid(1)); if (IntNd == nullptr) { errorDescribeNode("Unable to extract action value", Def); IsValid = false; } IntType Value = IntNd->getValue(); if (Value >= NextEnumValue) NextEnumValue = Value + 1; } std::vector<const Symbol*> SortedSyms(UndefinedCallbacks.begin(), UndefinedCallbacks.end()); std::sort(SortedSyms.begin(), SortedSyms.end(), compareSymbolNodesLt); for (const Symbol* Sym : SortedSyms) { SymbolDefn* SymDef = getSymbolDefn(Sym); const LiteralActionDef* LitDef = SymDef->getLiteralActionDefinition(); if (LitDef != nullptr) { errorDescribeNode("Malformed undefined action", LitDef); IsValid = false; continue; } Node* SymNd = const_cast<Symbol*>(Sym); auto* Def = create<LiteralActionDef>( SymNd, create<U64Const>(NextEnumValue++, ValueFormat::Decimal)); installDefinitions(Def); CallbackLiterals.insert(Def); } // Now see if conflicting definitions. for (const LiteralActionDef* Def : CallbackLiterals) { const auto* IntNd = dyn_cast<IntegerNode>(Def->getKid(1)); if (IntNd == nullptr) { errorDescribeNode("Unable to extract action value", Def); IsValid = false; continue; } IntType Value = IntNd->getValue(); if (DefMap.count(Value) == 0) { DefMap[Value] = Def; continue; } const Node* IntDef = DefMap[Value]; // Before complaining about conflicting action values, ignore predefined // symbols. We do this because we always define them so that the predefined // actions will always work. if (const auto* Sym = dyn_cast<Symbol>(Def->getKid(0))) { if (Sym->isPredefinedSymbol()) continue; } FILE* Out = IntNd->getErrorFile(); fprintf(Out, "Conflicting action values:\n"); TextWriter Writer; Writer.write(Out, IntDef); fprintf(Out, "and\n"); Writer.write(Out, Def); IsValid = false; } return IsValid; } void SymbolTable::setEnclosingScope(SharedPtr Symtab) { EnclosingScope = Symtab; clearCaches(); } void SymbolTable::clearCaches() { if (Alg) Alg->clearCaches(); IsAlgInstalled = false; CachedValue.clear(); UndefinedCallbacks.clear(); CallbackValues.clear(); CallbackLiterals.clear(); ActionBase = 0; CachedSourceHeader = nullptr; CachedReadHeader = nullptr; CachedWriteHeader = nullptr; } void SymbolTable::setAlgorithm(const Algorithm* NewAlg) { if (Alg == NewAlg) return; if (IsAlgInstalled) clearCaches(); Alg = const_cast<Algorithm*>(NewAlg); Alg->clearCaches(); } bool SymbolTable::standardizeAlgorithm() { std::vector<Node*> OtherNodes; Node* Source = nullptr; Node* Read = nullptr; Node* Write = nullptr; Node* Name = nullptr; Node* Enclosing = nullptr; bool Success = true; for (Node* Kid : *Alg) { switch (Kid->getType()) { default: OtherNodes.push_back(Kid); break; case NodeType::SourceHeader: if (Source != nullptr) { errorDescribeDuplicate("source header", Kid, Source); Success = false; } Source = Kid; break; case NodeType::ReadHeader: if (Read != nullptr) { errorDescribeDuplicate("read header", Kid, Read); Success = false; } Read = Kid; break; case NodeType::WriteHeader: if (Write != nullptr) { errorDescribeDuplicate("write header", Kid, Write); Success = false; } Write = Kid; break; case NodeType::AlgorithmName: if (Name != nullptr) { errorDescribeDuplicate("algorithm name", Kid, Name); Success = false; } Name = Kid; break; case NodeType::EnclosingAlgorithms: if (Enclosing != nullptr) { errorDescribeDuplicate("enclosing algorithms", Kid, Enclosing, false); Success = false; } Enclosing = Kid; break; } } if (!Success) return false; Alg->clearKids(); if (Source) Alg->append(Source); if (Read) Alg->append(Read); if (Write) Alg->append(Write); if (Name) Alg->append(Name); if (Enclosing) Alg->append(Enclosing); for (Node* Kid : OtherNodes) Alg->append(Kid); // Before returning, verify that enclosing clause is good. if (Enclosing) { SymbolTable* Last = this; SymbolTable* Next = Last->getEnclosingScope().get(); std::set<const Symbol*> AlgSymbols; if (const Symbol* AlgName = Alg->getName()) AlgSymbols.insert(AlgName); for (const Node* Kid : *Enclosing) { const Symbol* Sym = dyn_cast<Symbol>(Kid); if (Sym == nullptr) { errorDescribeNode("Context", Kid); errorDescribeNode("in", Enclosing); fprintf(error(), "Can't find enclosing: not algorithm name\n"); return false; } if (AlgSymbols.count(Sym)) { errorDescribeNode("Context", Kid); errorDescribeNode("in", Enclosing); fprintf(error(), "Circular definition for algorithms!\n"); return false; } AlgSymbols.insert(Sym); if (Next == nullptr) { // See if registered. If so, use it. SymbolTable::SharedPtr Enc = SymbolTable::getRegisteredAlgorithm(Sym->getName()); if (Enc) { if (Enc && !isAlgorithmInstalled()) { if (!Enc->install()) { errorDescribeNode("Context", Kid); errorDescribeNode("in", Enclosing); fprintf(error(), "Problems installing registered algorithm\n"); return false; } } Last->setEnclosingScope(Enc); Next = Enc.get(); } } if (Next == nullptr) { errorDescribeNode("Context", Kid); errorDescribeNode("in", Enclosing); fprintf(error(), "Can't find enclosing: no such algorithm!\n"); return false; } const Symbol* EncName = Next->getAlgorithmName(); if (EncName == nullptr) { errorDescribeNode("Context", Kid); errorDescribeNode("in", Enclosing); fprintf(error(), "Can't find enclosing: enclosing doesn't have name!\n"); return false; } if (Sym->getName() != EncName->getName()) { errorDescribeNode("Context", Kid); errorDescribeNode("in", Enclosing); fprintf(error(), "Can't find enclosing: enclosing named '%s'\n", EncName->getName().c_str()); return false; } Last = Next; Next = Last->getEnclosingScope().get(); } } return true; } bool SymbolTable::install() { TRACE_METHOD("install"); if (IsAlgInstalled) return true; if (Alg == nullptr) return false; if (EnclosingScope && !EnclosingScope->isAlgorithmInstalled()) { if (!EnclosingScope->install()) return false; } if (!standardizeAlgorithm()) return false; installPredefined(); installDefinitions(Alg); ConstNodeVectorType Parents; bool IsValid = Alg->validateSubtree(Parents); Parents.push_back(Alg); if (IsValid) IsValid = areActionsConsistent(); if (!IsValid) fatal("Unable to install algorthms, validation failed!"); return IsAlgInstalled = true; } const Header* SymbolTable::getSourceHeader() const { if (CachedSourceHeader != nullptr) return CachedSourceHeader; if (Alg == nullptr) return nullptr; return CachedSourceHeader = Alg->getSourceHeader(); } const Header* SymbolTable::getReadHeader() const { if (CachedReadHeader != nullptr) return CachedReadHeader; if (Alg == nullptr) return nullptr; return CachedReadHeader = Alg->getReadHeader(); } const Header* SymbolTable::getWriteHeader() const { if (CachedWriteHeader != nullptr) return CachedWriteHeader; if (Alg == nullptr) return nullptr; return CachedWriteHeader = Alg->getWriteHeader(); } bool SymbolTable::specifiesAlgorithm() const { if (Alg == nullptr) return false; return Alg->isAlgorithm(); } void SymbolTable::installPredefined() { for (uint32_t i = 0; i < NumPredefinedSymbols; ++i) { Symbol* Sym = getPredefined(toPredefinedSymbol(i)); U32Const* Const = create<U32Const>(i, ValueFormat::Decimal); const auto* Def = create<LiteralActionDef>(Sym, Const); Sym->setLiteralActionDefinition(Def); insertCallbackLiteral(Def); } } void SymbolTable::installDefinitions(const Node* Nd) { TRACE_METHOD("installDefinitions"); TRACE(node_ptr, nullptr, Nd); if (Nd == nullptr) return; switch (Nd->getType()) { default: return; case NodeType::Algorithm: for (Node* Kid : *Nd) installDefinitions(Kid); return; case NodeType::Define: { if (auto* DefineSymbol = dyn_cast<Symbol>(Nd->getKid(0))) return DefineSymbol->setDefineDefinition(cast<Define>(Nd)); errorDescribeNode("Malformed define", Nd); fatal("Malformed define s-expression found!"); return; } case NodeType::LiteralDef: { if (auto* LiteralSymbol = dyn_cast<Symbol>(Nd->getKid(0))) return LiteralSymbol->setLiteralDefinition(cast<LiteralDef>(Nd)); errorDescribeNode("Malformed", Nd); fatal("Malformed literal s-expression found!"); return; } case NodeType::LiteralActionBase: { const auto* IntNd = cast<IntegerNode>(Nd->getKid(0)); if (IntNd == nullptr) errorDescribeNode("Unable to extract literal action base", Nd); IntType Base = IntNd->getValue(); if (ActionBase != 0) { fprintf(Nd->getErrorFile(), "Literal action base was: %" PRIuMAX "\n", uintmax_t(ActionBase)); errorDescribeNode("Redefining to", Nd); fatal("Duplicate literal action bases defined!"); } ActionBase = Base; for (int i = 1, NumKids = Nd->getNumKids(); i < NumKids; ++i) { auto* Sym = dyn_cast<Symbol>(Nd->getKid(i)); if (Sym == nullptr) { errorDescribeNode("Symbol expected", Nd->getKid(1)); errorDescribeNode("In", Nd); return fatal("Unable to install algorithm"); } Node* Value = create<U64Const>(Base, IntNd->getFormat()); Node* Lit = create<LiteralActionDef>(Sym, Value); installDefinitions(Lit); ++Base; } return; } case NodeType::LiteralActionDef: { if (auto* LiteralSymbol = dyn_cast<Symbol>(Nd->getKid(0))) { if (LiteralSymbol->isPredefinedSymbol()) { errorDescribeNode("In", Nd); return fatal("Can't redefine predefined symbol"); } const auto* Def = cast<LiteralActionDef>(Nd); insertCallbackLiteral(Def); return LiteralSymbol->setLiteralActionDefinition(Def); } errorDescribeNode("Malformed", Nd); return fatal("Malformed literal s-expression found!"); } case NodeType::Rename: { SymbolTable::SharedPtr EncSymtab = Nd->Symtab.getEnclosingScope(); if (!EncSymtab) { errorDescribeNode("Bad rename", Nd); fatal("Rename without enclosing scope"); } if (auto* OldSymbol = dyn_cast<Symbol>(Nd->getKid(0))) { if (auto* EncSymbol = EncSymtab->getSymbol(OldSymbol->getName())) { if (auto* NewSymbol = dyn_cast<Symbol>(Nd->getKid(1))) { const Define* OldDefn = EncSymbol->getDefineDefinition(); Define* NewDefn = create<Define>(); NewDefn->append(NewSymbol); for (int i = 1; i < OldDefn->getNumKids(); ++i) NewDefn->append(OldDefn->getKid(i)); installDefinitions(NewDefn); if (!NewDefn->getDefineFrame()->isConsistent()) return fatal("Can't install rename!"); return; } } } errorDescribeNode("Malformed", Nd); fatal("Malformed rename s-expression found!"); return; } case NodeType::Undefine: { if (auto* UndefineSymbol = dyn_cast<Symbol>(Nd->getKid(0))) { UndefineSymbol->setDefineDefinition(nullptr); return; } errorDescribeNode("Can't undefine", Nd); fatal("Malformed undefine s-expression found!"); return; } } } TraceClass& SymbolTable::getTrace() { return *getTracePtr(); } void SymbolTable::describe(FILE* Out, bool ShowInternalStructure) { TextWriter Writer; Writer.setShowInternalStructure(ShowInternalStructure); Writer.write(Out, this); } void SymbolTable::stripCallbacksExcept(std::set<std::string>& KeepActions) { setAlgorithm(dyn_cast<Algorithm>(stripCallbacksExcept(KeepActions, Alg))); } void SymbolTable::stripSymbolicCallbacks() { setAlgorithm(dyn_cast<Algorithm>(stripSymbolicCallbackUses(Alg))); if (Alg != nullptr) setAlgorithm(dyn_cast<Algorithm>(stripSymbolicCallbackDefs(Alg))); } void SymbolTable::stripLiterals() { stripLiteralUses(); stripLiteralDefs(); } void SymbolTable::stripLiteralUses() { setAlgorithm(dyn_cast<Algorithm>(stripLiteralUses(Alg))); } void SymbolTable::stripLiteralDefs() { SymbolSet DefSyms; collectLiteralUseSymbols(DefSyms); setAlgorithm(dyn_cast<Algorithm>(stripLiteralDefs(Alg, DefSyms))); } Node* SymbolTable::stripUsing(Node* Nd, std::function<Node*(Node*)> stripKid) { switch (Nd->getType()) { default: for (int i = 0; i < Nd->getNumKids(); ++i) Nd->setKid(i, stripKid(Nd->getKid(i))); return Nd; #define X(NAME, BASE, DECLS, INIT) case NodeType::NAME: AST_NARYNODE_TABLE #undef X { // TODO: Make strip functions return nullptr to remove! std::vector<Node*> Kids; int index = 0; int limit = Nd->getNumKids(); // Simplify kids, removing "void" operations from the nary node. for (; index < limit; ++index) { Node* Kid = stripKid(Nd->getKid(index)); if (!isa<Void>(Kid)) Kids.push_back(Kid); } if (Kids.size() == size_t(Nd->getNumKids())) { // Replace kids in place. for (size_t i = 0; i < Kids.size(); ++i) Nd->setKid(i, Kids[i]); return Nd; } if (Kids.empty()) break; if (Kids.size() == 1 && Nd->getType() == NodeType::Sequence) return Kids[0]; Nary* NaryNd = dyn_cast<Nary>(Nd); if (NaryNd == nullptr) break; NaryNd->clearKids(); for (auto Kid : Kids) NaryNd->append(Kid); return NaryNd; } } return create<Void>(); } Node* SymbolTable::stripCallbacksExcept(std::set<std::string>& KeepActions, Node* Nd) { switch (Nd->getType()) { default: return stripUsing(Nd, [&](Node* Kid) -> Node* { return stripCallbacksExcept(KeepActions, Kid); }); case NodeType::Callback: { Node* Action = Nd->getKid(0); switch (Action->getType()) { default: return Nd; case NodeType::LiteralActionUse: { auto* Sym = dyn_cast<Symbol>(Action->getKid(0)); if (Sym == nullptr) return Nd; if (Sym->isPredefinedSymbol() || KeepActions.count(Sym->getName())) return Nd; break; } } break; } case NodeType::LiteralActionDef: if (const auto* Sym = dyn_cast<Symbol>(Nd->getKid(0))) { if (KeepActions.count(Sym->getName())) return Nd; } break; case NodeType::LiteralActionBase: { bool CanRemove = true; for (int i = 1; i < Nd->getNumKids(); ++i) { if (const auto* Sym = dyn_cast<Symbol>(Nd->getKid(i))) { if (KeepActions.count(Sym->getName())) { CanRemove = false; break; } } } if (!CanRemove) return Nd; break; } } return create<Void>(); } Node* SymbolTable::stripSymbolicCallbackUses(Node* Nd) { switch (Nd->getType()) { default: return stripUsing(Nd, [&](Node* Kid) -> Node* { return stripSymbolicCallbackUses(Kid); }); case NodeType::LiteralActionUse: { const auto* Sym = dyn_cast<Symbol>(Nd->getKid(0)); if (Sym == nullptr) return Nd; const auto* Def = Sym->getLiteralActionDefinition(); if (Def == nullptr) break; return Def->getKid(1); } } // If reached, this is a symbolic action use without a def, so remove. TextWriter Writer; FILE* Out = error(); fprintf(Out, "No action definition for: "); Writer.write(Out, Nd); return create<Void>(); } Node* SymbolTable::stripSymbolicCallbackDefs(Node* Nd) { switch (Nd->getType()) { default: return stripUsing(Nd, [&](Node* Kid) -> Node* { return stripSymbolicCallbackDefs(Kid); }); case NodeType::LiteralActionDef: break; case NodeType::LiteralActionBase: break; } return create<Void>(); } Node* SymbolTable::stripLiteralUses(Node* Nd) { switch (Nd->getType()) { default: return stripUsing( Nd, [&](Node* Kid) -> Node* { return stripLiteralUses(Kid); }); case NodeType::LiteralActionUse: return Nd; case NodeType::LiteralUse: { const auto* Use = cast<LiteralUse>(Nd); const auto* Sym = dyn_cast<Symbol>(Use->getKid(0)); if (Sym == nullptr) break; const auto* Def = Sym->getLiteralDefinition(); if (Def == nullptr) break; return Def->getKid(1); } } // If reached, this is a use without a def, so remove. TextWriter Writer; FILE* Out = error(); fprintf(Out, "No literal definition for: "); Writer.write(Out, Nd); return create<Void>(); } void SymbolTable::collectLiteralUseSymbols(SymbolSet& Symbols) { ConstNodeVectorType ToVisit; ToVisit.push_back(Alg); while (!ToVisit.empty()) { const Node* Nd = ToVisit.back(); ToVisit.pop_back(); for (const Node* Kid : *Nd) ToVisit.push_back(Kid); const auto* Use = dyn_cast<LiteralUse>(Nd); if (Use == nullptr) continue; const Node* Sym = Use->getKid(0); assert(isa<Symbol>(Sym)); Symbols.insert(cast<Symbol>(Sym)); } } Node* SymbolTable::stripLiteralDefs(Node* Nd, SymbolSet& DefSyms) { switch (Nd->getType()) { default: return stripUsing(Nd, [&](Node* Kid) -> Node* { return stripLiteralDefs(Kid, DefSyms); }); case NodeType::LiteralDef: if (DefSyms.count(dyn_cast<Symbol>(Nd->getKid(0)))) return Nd; break; case NodeType::LiteralActionDef: if (CallbackLiterals.count(cast<LiteralActionDef>(Nd))) return Nd; break; } return create<Void>(); } Nullary::Nullary(SymbolTable& Symtab, NodeType Type) : Node(Symtab, Type) {} Nullary::~Nullary() {} int Nullary::getNumKids() const { return 0; } Node* Nullary::getKid(int) const { return nullptr; } void Nullary::setKid(int, Node*) { decode::fatal("Nullary::setKid not allowed"); } bool Nullary::implementsClass(NodeType Type) { switch (Type) { default: return false; #define X(NAME, BASE, DECLS, INIT) \ case NodeType::NAME: \ return true; AST_NULLARYNODE_TABLE #undef X } } #define X(NAME, BASE, DECLS, INIT) \ NAME::NAME(SymbolTable& Symtab) : BASE(Symtab, NodeType::NAME) { INIT } AST_NULLARYNODE_TABLE #undef X #define X(NAME, BASE, DECLS, INIT) template NAME* SymbolTable::create<NAME>(); AST_NULLARYNODE_TABLE #undef X #define X(NAME, BASE, DECLS, INIT) \ NAME::~NAME() {} AST_NULLARYNODE_TABLE #undef X Unary::Unary(SymbolTable& Symtab, NodeType Type, Node* Kid) : Node(Symtab, Type) { Kids[0] = Kid; } Unary::~Unary() {} int Unary::getNumKids() const { return 1; } Node* Unary::getKid(int Index) const { if (Index < 1) return Kids[0]; return nullptr; } void Unary::setKid(int Index, Node* NewValue) { assert(Index < 1); Kids[0] = NewValue; } bool Unary::implementsClass(NodeType Type) { switch (Type) { default: return false; case NodeType::BinaryEval: #define X(NAME, BASE, DECLS, INIT) \ case NodeType::NAME: \ return true; AST_UNARYNODE_TABLE #undef X } } #define X(NAME, BASE, DECLS, INIT) \ NAME::NAME(SymbolTable& Symtab, Node* Kid) \ : BASE(Symtab, NodeType::NAME, Kid) { \ INIT \ } AST_UNARYNODE_TABLE #undef X #define X(NAME, BASE, DECLS, INIT) \ template NAME* SymbolTable::create<NAME>(Node * Nd); AST_UNARYNODE_TABLE #undef X #define X(NAME, BASE, DECLS, INIT) \ NAME::~NAME() {} AST_UNARYNODE_TABLE #undef X const LiteralDef* LiteralUse::getDef() const { return cast<Symbol>(getKid(0))->getLiteralDefinition(); } const LiteralActionDef* LiteralActionUse::getDef() const { return cast<Symbol>(getKid(0))->getLiteralActionDefinition(); } bool LiteralUse::validateNode(ConstNodeVectorType& Parents) const { TRACE_METHOD("validateNode"); TRACE(node_ptr, nullptr, this); if (getDef()) return true; fprintf(getErrorFile(), "No corresponding literal definition found\n"); return false; } bool LiteralActionUse::validateNode(ConstNodeVectorType& Parents) const { TRACE_METHOD("validateNode"); TRACE(node_ptr, nullptr, this); if (const LiteralActionDef* Def = getDef()) { getSymtab().insertCallbackLiteral(Def); return true; } const Node* SymNd = getKid(0); assert(isa<Symbol>(SymNd)); getSymtab().insertUndefinedCallback(cast<Symbol>(SymNd)); return true; } const IntegerNode* LiteralUse::getIntNode() const { const LiteralDef* Def = getDef(); assert(Def != nullptr); const IntegerNode* IntNd = dyn_cast<IntegerNode>(Def->getKid(1)); assert(IntNd != nullptr); return IntNd; } const IntegerNode* LiteralActionUse::getIntNode() const { const LiteralActionDef* Def = getDef(); assert(Def != nullptr); const IntegerNode* IntNd = dyn_cast<IntegerNode>(Def->getKid(1)); assert(IntNd != nullptr); return IntNd; } bool Callback::validateNode(ConstNodeVectorType& Parents) const { TRACE_METHOD("validateNode"); TRACE(node_ptr, nullptr, this); const Node* Action = getKid(0); if (const auto* IntNd = dyn_cast<IntegerNode>(Action)) { getSymtab().insertCallbackValue(IntNd); return true; } const auto* Use = dyn_cast<LiteralActionUse>(Action); if (Use == nullptr) { errorDescribeNodeContext("Malformed callback", this, Parents); return false; } return true; } const IntegerNode* Callback::getIntNode() const { const Node* Val = getKid(0); if (const auto* IntNd = dyn_cast<IntegerNode>(Val)) return IntNd; if (const auto* Use = dyn_cast<LiteralActionUse>(Val)) return Use->getIntNode(); return nullptr; } IntegerNode::IntegerNode(SymbolTable& Symtab, NodeType Type, decode::IntType Value, decode::ValueFormat Format, bool isDefault) : Nullary(Symtab, Type), Value(Type, Value, Format, isDefault) {} IntegerNode::~IntegerNode() {} int IntegerNode::nodeCompare(const Node* Nd) const { int Diff = Nullary::nodeCompare(Nd); if (Diff != 0) return Diff; assert(isa<IntegerNode>(Nd)); const auto* IntNd = cast<IntegerNode>(Nd); return Value.compare(IntNd->Value); } bool IntegerNode::implementsClass(NodeType Type) { switch (Type) { default: return false; case NodeType::BinaryAccept: #define X(NAME, FORMAT, DEFAULT, MEGE, BASE, DECLS, INIT) case NodeType::NAME: AST_INTEGERNODE_TABLE #undef X #define X(NAME, BASE, VALUE, FORMAT, DECLS, INIT) case NodeType::NAME: AST_LITERAL_TABLE #undef X return true; } } #define X(NAME, FORMAT, DEFAULT, MERGE, BASE, DECLS, INIT) \ NAME::NAME(SymbolTable& Symtab, decode::IntType Value, \ decode::ValueFormat Format) \ : BASE(Symtab, NodeType::NAME, Value, Format, false) { \ INIT \ } AST_INTEGERNODE_TABLE #undef X #define X(NAME, FORMAT, DEFAULT, MERGE, BASE, DECLS, INIT) \ NAME::NAME(SymbolTable& Symtab) \ : BASE(Symtab, NodeType::NAME, (DEFAULT), decode::ValueFormat::Decimal, \ true) { \ INIT \ } AST_INTEGERNODE_TABLE #undef X #define X(NAME, FORMAT, DEFAULT, MERGE, BASE, DECLS, INIT) \ NAME::~NAME() {} AST_INTEGERNODE_TABLE #undef X #define X(NAME, BASE, VALUE, FORMAT, DECLS, INIT) \ NAME::NAME(SymbolTable& Symtab) \ : BASE(Symtab, NodeType::NAME, (VALUE), decode::ValueFormat::FORMAT, \ true) { \ INIT \ } AST_LITERAL_TABLE #undef X #define X(NAME, BASE, VALUE, FORMAT, DECLS, INIT) \ NAME::~NAME() {} AST_LITERAL_TABLE #undef X bool Local::validateNode(ConstNodeVectorType& Parents) const { TRACE_METHOD("validateNode"); TRACE(node_ptr, nullptr, this); for (const Node* Nd : Parents) { if (const auto* Def = dyn_cast<Define>(Nd)) { TRACE(node_ptr, "Enclosing define", Def); if (Def->isValidLocalIndex(getValue())) return true; errorDescribeNodeContext("Invalid local usage", this, Parents); return false; } } errorDescribeNodeContext("Not used within a define", this, Parents); return false; } bool Param::validateNode(ConstNodeVectorType& Parents) const { TRACE_METHOD("validateNode"); TRACE(node_ptr, nullptr, this); for (const Node* Nd : Parents) { if (const auto* Def = dyn_cast<Define>(Nd)) { TRACE(node_ptr, "Enclosing define", Def); if (Def->isValidArgIndex(getValue())) return true; errorDescribeNodeContext("Invalid parameter usage", this, Parents); return false; } return true; } errorDescribeNodeContext("Not used within a define", this, Parents); return false; } BinaryAccept::BinaryAccept(SymbolTable& Symtab) : IntegerNode(Symtab, NodeType::BinaryAccept, 0, decode::ValueFormat::Hexidecimal, true) {} BinaryAccept::BinaryAccept(SymbolTable& Symtab, decode::IntType Value, unsigned NumBits) : IntegerNode(Symtab, NodeType::BinaryAccept, Value, decode::ValueFormat::Hexidecimal, NumBits) {} BinaryAccept* SymbolTable::createBinaryAccept(IntType Value, unsigned NumBits) { BinaryAccept* Nd = new BinaryAccept(*this, Value, NumBits); Allocated.push_back(Nd); return Nd; } template BinaryAccept* SymbolTable::create<BinaryAccept>(); BinaryAccept::~BinaryAccept() {} int BinaryAccept::nodeCompare(const Node* Nd) const { int Diff = IntegerNode::nodeCompare(Nd); if (Diff != 0) return Diff; assert(isa<BinaryAccept>(Nd)); const auto* BaNd = cast<BinaryAccept>(Nd); return int(NumBits) - int(BaNd->NumBits); } bool BinaryAccept::validateNode(ConstNodeVectorType& Parents) const { // Defines path (value) from leaf to algorithm root node, // guaranteeing each accept node has a unique value that can be case // selected. TRACE_METHOD("validateNode"); TRACE(node_ptr, nullptr, this); IntType MyValue = 0; unsigned MyNumBits = 0; const Node* LastNode = this; for (size_t i = Parents.size(); i > 0; --i) { const Node* Nd = Parents[i - 1]; switch (Nd->getType()) { case NodeType::BinaryEval: { bool Success = true; if (!Value.isDefault && (MyValue != Value.Value || MyNumBits != NumBits)) { FILE* Out = error(); fprintf(Out, "Expected (%s ", getName()); writeInt(Out, MyValue, ValueFormat::Hexidecimal); fprintf(Out, ":%u)\n", MyNumBits); errorDescribeNode("Malformed", this); Success = false; } TRACE(IntType, "Value", MyValue); TRACE(unsigned_int, "Bits", MyNumBits); Value.Value = MyValue; NumBits = MyNumBits; Value.isDefault = false; Value.Format = ValueFormat::Hexidecimal; if (!cast<BinaryEval>(Nd)->addEncoding(this)) { fprintf(error(), "Can't install opcode, malformed: %s\n", getName()); Success = false; } return Success; } case NodeType::BinarySelect: if (MyNumBits >= sizeof(IntType) * CHAR_BIT) { FILE* Out = error(); fprintf(Out, "Binary path too long for %s node\n", getName()); return false; } MyValue <<= 1; if (LastNode == Nd->getKid(1)) MyValue |= 1; LastNode = Nd; MyNumBits++; break; default: { // Exit loop and fail. FILE* Out = error(); TextWriter Writer; Writer.write(Out, this); fprintf(Out, "Doesn't appear under %s\n", getNodeSexpName(NodeType::BinaryEval)); fprintf(Out, "Appears in:\n"); Writer.write(Out, Nd); return false; } } } fprintf(error(), "%s can't appear at top level\n", getName()); return false; } Binary::Binary(SymbolTable& Symtab, NodeType Type, Node* Kid1, Node* Kid2) : Node(Symtab, Type) { Kids[0] = Kid1; Kids[1] = Kid2; } Binary::~Binary() {} int Binary::getNumKids() const { return 2; } Node* Binary::getKid(int Index) const { if (Index < 2) return Kids[Index]; return nullptr; } void Binary::setKid(int Index, Node* NewValue) { assert(Index < 2); Kids[Index] = NewValue; } bool Binary::implementsClass(NodeType Type) { switch (Type) { default: return false; #define X(NAME, BASE, DECLS, INIT) \ case NodeType::NAME: \ return true; AST_BINARYNODE_TABLE #undef X } } #define X(NAME, BASE, DECLS, INIT) \ NAME::NAME(SymbolTable& Symtab, Node* Kid1, Node* Kid2) \ : BASE(Symtab, NodeType::NAME, Kid1, Kid2) { \ INIT \ } AST_BINARYNODE_TABLE #undef X #define X(NAME, BASE, DECLS, INIT) \ template NAME* SymbolTable::create<NAME>(Node * Nd1, Node * Nd2); AST_BINARYNODE_TABLE #undef X #define X(NAME, BASE, DECLS, INIT) \ NAME::~NAME() {} AST_BINARYNODE_TABLE #undef X Ternary::Ternary(SymbolTable& Symtab, NodeType Type, Node* Kid1, Node* Kid2, Node* Kid3) : Node(Symtab, Type) { Kids[0] = Kid1; Kids[1] = Kid2; Kids[2] = Kid3; } Ternary::~Ternary() {} int Ternary::getNumKids() const { return 3; } Node* Ternary::getKid(int Index) const { if (Index < 3) return Kids[Index]; return nullptr; } void Ternary::setKid(int Index, Node* NewValue) { assert(Index < 3); Kids[Index] = NewValue; } bool Ternary::implementsClass(NodeType Type) { switch (Type) { default: return false; #define X(NAME, BASE, DECLS, INIT) \ case NodeType::NAME: \ return true; AST_TERNARYNODE_TABLE #undef X } } #define X(NAME, BASE, DECLS, INIT) \ NAME::NAME(SymbolTable& Symtab, Node* Kid1, Node* Kid2, Node* Kid3) \ : BASE(Symtab, NodeType::NAME, Kid1, Kid2, Kid3) { \ INIT \ } AST_TERNARYNODE_TABLE #undef X #define X(NAME, BASE, DECLS, INIT) \ template NAME* SymbolTable::create<NAME>(Node * Nd1, Node * Nd2, Node * Nd3); AST_TERNARYNODE_TABLE #undef X #define X(NAME, BASE, DECLS, INIT) \ NAME::~NAME() {} AST_TERNARYNODE_TABLE #undef X DefineFrame::DefineFrame(const Define* Def) : NumValueArgs(0), NumExprArgs(0), NumLocals(0), NumCached(0), InitSuccessful(false) { init(Def); } DefineFrame::~DefineFrame() {} size_t DefineFrame::addSizedArg(const Node* Arg) { if (!isa<IntegerNode>(Arg)) { ParamTypes.push_back(Arg->getType()); return 1; } const auto* Val = cast<IntegerNode>(Arg); size_t Count = Val->getValue(); NodeType Ty = Arg->getType(); for (size_t i = 0; i < Count; ++i) ParamTypes.push_back(Ty); return Count; } size_t DefineFrame::getValueArgIndex(size_t Index) const { // TODO(karlschimpf): Speed up? assert(Index < ParamTypes.size()); size_t ArgIndex = 0; for (NodeType Ty : ParamTypes) switch (Ty) { default: break; case NodeType::ParamCached: case NodeType::ParamValues: if (Index == 0) return ArgIndex; ++ArgIndex; --Index; break; } WASM_RETURN_UNREACHABLE(0); } NodeType DefineFrame::getArgType(size_t Index) const { return ParamTypes[Index]; } void DefineFrame::init(const Define* Def) { if (Def->getNumKids() != 4) { errorDescribeNode("Malformed define", Def); return; } bool ParamsValidate = true; const Node* ParamsRoot = Def->getKid(1); std::vector<const Node*> Args; Args.push_back(ParamsRoot); for (size_t NextIndex = 0; NextIndex < Args.size(); ++NextIndex) { const Node* Arg = Args[NextIndex]; switch (Arg->getType()) { case NodeType::ParamExprsCached: default: errorDescribeNode("Parameter argument implemented!", Arg); ParamsValidate = false; break; case NodeType::NoParams: break; case NodeType::ParamCached: NumCached += addSizedArg(Arg); if (!ParamTypes.empty()) { errorDescribeNode("Cached parameter must be first arugment!", Arg); ParamsValidate = false; } break; case NodeType::ParamExprs: NumExprArgs += addSizedArg(Arg); break; case NodeType::ParamValues: if (NumExprArgs > 0) { errorDescribeNode("Value arguments must preceed Expr arguments!", Arg); ParamsValidate = false; } NumValueArgs += addSizedArg(Arg); break; case NodeType::ParamArgs: for (const Node* Kid : *Arg) Args.push_back(Kid); break; } } if (!ParamsValidate) { errorDescribeNode("In", Def); return; } // Check local declarations. const Node* LocalDecl = Def->getKid(2); switch (LocalDecl->getType()) { default: errorDescribeNode("Malformed locals declaration", LocalDecl, false); errorDescribeNode("In", Def); return; case NodeType::Locals: NumLocals = dyn_cast<Locals>(LocalDecl)->getValue(); break; case NodeType::NoLocals: break; } InitSuccessful = true; return; } DefineFrame* Define::getDefineFrame() const { if (!MyDefineFrame) MyDefineFrame = utils::make_unique<DefineFrame>(this); return MyDefineFrame.get(); } bool Define::validateNode(ConstNodeVectorType& Parents) const { MyDefineFrame.reset(); return getDefineFrame()->isConsistent(); } const std::string Define::getName() const { assert(getNumKids() == 4); assert(isa<Symbol>(getKid(0))); return cast<Symbol>(getKid(0))->getName(); } Node* Define::getBody() const { if (getNumKids() < 4) return nullptr; return getKid(3); } Nary::Nary(SymbolTable& Symtab, NodeType Type) : Node(Symtab, Type) {} Nary::~Nary() {} int Nary::nodeCompare(const Node* Nd) const { int Diff = Node::nodeCompare(Nd); if (Diff != 0) return Diff; return getNumKids() - Nd->getNumKids(); } int Nary::getNumKids() const { return Kids.size(); } Node* Nary::getKid(int Index) const { return Kids[Index]; } void Nary::setKid(int Index, Node* N) { Kids[Index] = N; } void Nary::clearKids() { Kids.clear(); } void Nary::append(Node* Kid) { Kids.emplace_back(Kid); } bool Nary::implementsClass(NodeType Type) { switch (Type) { default: return false; #define X(NAME, BASE, DECLS, INIT) \ case NodeType::NAME: \ return true; AST_NARYNODE_TABLE #undef X } } #define X(NAME, BASE, DECLS, INIT) \ NAME::NAME(SymbolTable& Symtab) : BASE(Symtab, NodeType::NAME) { INIT } AST_NARYNODE_TABLE #undef X #define X(NAME, BASE, DECLS, INIT) template NAME* SymbolTable::create<NAME>(); AST_NARYNODE_TABLE #undef X #define X(NAME, BASE, DECLS, INIT) \ NAME::~NAME() {} AST_NARYNODE_TABLE #undef X Header::Header(SymbolTable& Symtab, NodeType Type) : Nary(Symtab, Type) {} Header::~Header() {} bool Header::implementsClass(NodeType Type) { return Type == NodeType::SourceHeader || Type == NodeType::ReadHeader || Type == NodeType::WriteHeader; } Eval::Eval(SymbolTable& Symtab, NodeType Type) : Nary(Symtab, Type) {} Eval::~Eval() {} bool Eval::implementsClass(NodeType Type) { return Type == NodeType::EvalVirtual; } Symbol* Eval::getCallName() const { return dyn_cast<Symbol>(getKid(0)); } bool Eval::validateNode(ConstNodeVectorType& Parents) const { TRACE_METHOD("validateNodeEval"); TRACE(node_ptr, nullptr, this); const auto* Sym = dyn_cast<Symbol>(getKid(0)); assert(Sym); const auto* Defn = dyn_cast<Define>(Sym->getDefineDefinition()); if (Defn == nullptr) { fprintf(error(), "Can't find define for symbol!\n"); errorDescribeNode("In", this); return false; } size_t NumParms = Defn->getNumArgs(); if (NumParms != size_t(getNumKids() - 1)) { fprintf(error(), "Eval called with wrong number of arguments!\n"); errorDescribeNode("bad eval", this); errorDescribeNode("called define", Defn); return false; } return true; } void Algorithm::init() { SourceHdr = nullptr; ReadHdr = nullptr; WriteHdr = nullptr; Name = nullptr; IsAlgorithmSpecified = false; IsValidated = false; } bool Algorithm::isAlgorithm() const { if (IsAlgorithmSpecified || IsValidated) return IsAlgorithmSpecified; for (const Node* Kid : *this) if (const_cast<Algorithm*>(this)->setIsAlgorithm(Kid)) return IsAlgorithmSpecified; return false; } bool Algorithm::setIsAlgorithm(const Node* Nd) { if (!isa<AlgorithmFlag>(Nd) || !isa<IntegerNode>(Nd->getKid(0))) return false; auto* Int = cast<IntegerNode>(Nd->getKid(0)); IsAlgorithmSpecified = (Int->getValue() != 0); return true; } const Header* Algorithm::getSourceHeader(bool UseEnclosing) const { if (SourceHdr != nullptr) return SourceHdr; if (UseEnclosing) { for (SymbolTable* Sym = Symtab.getEnclosingScope().get(); Sym != nullptr; Sym = Sym->getEnclosingScope().get()) { const Algorithm* Alg = Sym->getAlgorithm(); if (Alg->SourceHdr) return Alg->SourceHdr; } } if (IsValidated) return nullptr; // Note: this function must work, even if not installed. The // reason is that the decompressor must look up the read header to // find the appropriate enclosing algorithm, which must be bound // before the algorithm is installed. for (const Node* Kid : *this) { if (!isa<SourceHeader>(Kid)) continue; return cast<SourceHeader>(Kid); } return nullptr; } const Header* Algorithm::getReadHeader(bool UseEnclosing) const { if (ReadHdr) return ReadHdr; if (UseEnclosing) { for (SymbolTable* Sym = Symtab.getEnclosingScope().get(); Sym != nullptr; Sym = Sym->getEnclosingScope().get()) { const Algorithm* Alg = Sym->getAlgorithm(); if (Alg->ReadHdr) return Alg->ReadHdr; } } if (IsValidated) return getSourceHeader(UseEnclosing); // Note: this function must work, even if not installed. The // reason is that the decompressor must look up the read header to // find the appropriate enclosing algorithm, which must be bound // before the algorithm is installed. for (const Node* Kid : *this) { if (!isa<ReadHeader>(Kid)) continue; return cast<ReadHeader>(Kid); } return getSourceHeader(UseEnclosing); } const Header* Algorithm::getWriteHeader(bool UseEnclosing) const { if (WriteHdr) return WriteHdr; if (UseEnclosing) { for (SymbolTable* Sym = Symtab.getEnclosingScope().get(); Sym != nullptr; Sym = Sym->getEnclosingScope().get()) { const Algorithm* Alg = Sym->getAlgorithm(); if (Alg->WriteHdr) return Alg->WriteHdr; } } if (IsValidated) return getReadHeader(UseEnclosing); // Note: this function must work, even if not installed. The // reason is that the decompressor must look up the read header to // find the appropriate enclosing algorithm, which must be bound // before the algorithm is installed. for (const Node* Kid : *this) { if (!isa<WriteHeader>(Kid)) continue; return cast<WriteHeader>(Kid); } return getReadHeader(UseEnclosing); } const Symbol* Algorithm::getName() const { if (Name || IsValidated) return Name; // Note: This function must work, even if not installed. The reason // is that algorithms may get registered before they have been // installed. for (const Node* Kid : *this) { if (!isa<AlgorithmName>(Kid)) continue; Name = dyn_cast<Symbol>(Kid->getKid(0)); return Name; } return nullptr; } bool Algorithm::validateNode(ConstNodeVectorType& Parents) const { TRACE_METHOD("validateNode"); TRACE(node_ptr, nullptr, this); if (!Parents.empty()) { fprintf(error(), "Algorithm nodes can only appear as a top-level s-expression\n"); errorDescribeNode("Bad algorithm node", this); errorDescribeContext(Parents); return false; } IsValidated = false; SourceHdr = nullptr; ReadHdr = nullptr; WriteHdr = nullptr; Name = nullptr; IsAlgorithmSpecified = false; const Node* OldAlgorithmFlag = nullptr; for (const Node* Kid : *this) { switch (Kid->getType()) { case NodeType::SourceHeader: if (SourceHdr) { errorDescribeNode("Duplicate source header", Kid); errorDescribeNode("Original", SourceHdr); return false; } SourceHdr = cast<SourceHeader>(Kid); break; case NodeType::ReadHeader: if (ReadHdr) { errorDescribeNode("Duplicate read header", Kid); errorDescribeNode("Original", ReadHdr); return false; } ReadHdr = cast<ReadHeader>(Kid); break; case NodeType::WriteHeader: if (WriteHdr) { errorDescribeNode("Duplicate read header", Kid); errorDescribeNode("Original", WriteHdr); return false; } WriteHdr = cast<WriteHeader>(Kid); break; case NodeType::AlgorithmFlag: if (OldAlgorithmFlag != nullptr) { errorDescribeNode("Duplicate flag", Kid); errorDescribeNode("Original flag ", OldAlgorithmFlag); return false; } OldAlgorithmFlag = Kid; if (auto* Int = cast<IntegerNode>(Kid->getKid(0))) { if (Int->getValue() != 0) IsAlgorithmSpecified = true; } else { errorDescribeNode("Malformed flag", Kid); return false; } break; case NodeType::AlgorithmName: if (Name != nullptr) { errorDescribeDuplicate("algorithm name", Name, Kid); return false; } Name = dyn_cast<Symbol>(Kid->getKid(0)); if (Name) break; errorDescribeNode("Malformed algorithm name", Kid); return false; default: break; } } if (SourceHdr == nullptr) { errorDescribeNode("Algorithm doesn't have a source header", this); return false; } IsValidated = true; return true; } SelectBase::~SelectBase() {} bool SelectBase::implementsClass(NodeType Type) { switch (Type) { default: return false; #define X(NAME, BASE, DECLS, INIT) \ case NodeType::NAME: \ return true; AST_SELECTNODE_TABLE #undef X } } SelectBase::SelectBase(SymbolTable& Symtab, NodeType Type) : Nary(Symtab, Type) {} IntLookup* SelectBase::getIntLookup() const { IntLookup* Lookup = cast<IntLookup>(Symtab.getCachedValue(this)); if (Lookup == nullptr) { Lookup = Symtab.create<IntLookup>(); Symtab.setCachedValue(this, Lookup); } return Lookup; } const Case* SelectBase::getCase(IntType Key) const { IntLookup* Lookup = getIntLookup(); return dyn_cast<Case>(Lookup->get(Key)); } bool SelectBase::addCase(const Case* Case) const { return getIntLookup()->add(Case->getValue(), Case); } bool Case::validateNode(ConstNodeVectorType& Parents) const { TRACE_METHOD("validateNode"); TRACE(node_ptr, nullptr, this); // Install quick lookup to CaseBody. CaseBody = getKid(1); while (isa<Case>(CaseBody)) CaseBody = CaseBody->getKid(1); // Cache value. Value = 0; const auto* CaseExp = getKid(0); if (const auto* LitUse = dyn_cast<LiteralUse>(CaseExp)) { Symbol* Sym = dyn_cast<Symbol>(LitUse->getKid(0)); if (const auto* LitDef = Sym->getLiteralDefinition()) { CaseExp = LitDef->getKid(1); } } if (const auto* Key = dyn_cast<IntegerNode>(CaseExp)) { Value = Key->getValue(); } else { errorDescribeNode("Case", this); errorDescribeNode("Case key", CaseExp); fprintf(error(), "Case value not found\n"); return false; } // Install case on enclosing selector. for (size_t i = Parents.size(); i > 0; --i) { auto* Nd = Parents[i - 1]; if (auto* Sel = dyn_cast<SelectBase>(Nd)) { if (Sel->addCase(this)) return true; FILE* Out = error(); fprintf(Out, "Duplicate case entries for value: %" PRIuMAX "\n", uintmax_t(Value)); TextWriter Writer; Writer.write(Out, Sel->getCase(Value)); fputs("vs\n", Out); Writer.write(Out, this); return false; } } fprintf(error(), "Case not enclosed in corresponding selector\n"); return false; } namespace { constexpr uint32_t MaxOpcodeWidth = 64; IntType getWidthMask(uint32_t BitWidth) { return std::numeric_limits<IntType>::max() >> (MaxOpcodeWidth - BitWidth); } IntType getIntegerValue(Node* Nd) { if (auto* IntVal = dyn_cast<IntegerNode>(Nd)) return IntVal->getValue(); errorDescribeNode("Integer value expected but not found", Nd); return 0; } bool getCaseSelectorWidth(const Node* Nd, uint32_t& Width) { switch (Nd->getType()) { default: // Not allowed in opcode cases. errorDescribeNode("Non-fixed width opcode format", Nd); return false; case NodeType::Bit: Width = 1; if (Width >= MaxOpcodeWidth) { errorDescribeNode("Bit size not valid", Nd); return false; } return true; case NodeType::Uint8: case NodeType::Uint32: case NodeType::Uint64: break; } Width = getIntegerValue(Nd->getKid(0)); if (Width == 0 || Width >= MaxOpcodeWidth) { errorDescribeNode("Bit size not valid", Nd); return false; } return true; } bool addFormatWidth(const Node* Nd, std::unordered_set<uint32_t>& CaseWidths) { uint32_t Width; if (!getCaseSelectorWidth(Nd, Width)) return false; CaseWidths.insert(Width); return true; } bool collectCaseWidths(IntType Key, const Node* Nd, std::unordered_set<uint32_t>& CaseWidths) { switch (Nd->getType()) { default: // Not allowed in opcode cases. errorDescribeNode("Non-fixed width opcode format", Nd); return false; case NodeType::Opcode: if (isa<LastRead>(Nd->getKid(0))) { for (int i = 1, NumKids = Nd->getNumKids(); i < NumKids; ++i) { Node* Kid = Nd->getKid(i); assert(isa<Case>(Kid)); const Case* C = cast<Case>(Kid); IntType CKey = getIntegerValue(C->getKid(0)); const Node* Body = C->getKid(1); if (CKey == Key) // Already handled by outer case. continue; if (!collectCaseWidths(CKey, Body, CaseWidths)) { errorDescribeNode("Inside", Nd); return false; } } } else { uint32_t Width; if (!getCaseSelectorWidth(Nd->getKid(0), Width)) { errorDescribeNode("Inside", Nd); return false; } if (Width >= MaxOpcodeWidth) { errorDescribeNode("Bit width(s) too big", Nd); return false; } CaseWidths.insert(Width); for (int i = 1, NumKids = Nd->getNumKids(); i < NumKids; ++i) { Node* Kid = Nd->getKid(i); assert(isa<Case>(Kid)); const Case* C = cast<Case>(Kid); IntType CKey = getIntegerValue(C->getKid(0)); const Node* Body = C->getKid(1); std::unordered_set<uint32_t> LocalCaseWidths; if (!collectCaseWidths(CKey, Body, LocalCaseWidths)) { errorDescribeNode("Inside", Nd); return false; } for (uint32_t CaseWidth : LocalCaseWidths) { uint32_t CombinedWidth = Width + CaseWidth; if (CombinedWidth >= MaxOpcodeWidth) { errorDescribeNode("Bit width(s) too big", Nd); return false; } CaseWidths.insert(CombinedWidth); } } } return true; case NodeType::Uint8: case NodeType::Uint32: case NodeType::Uint64: return addFormatWidth(Nd, CaseWidths); } } } // end of anonymous namespace #define X(NAME, BASE, DECLS, INIT) \ NAME::NAME(SymbolTable& Symtab) : BASE(Symtab, NodeType::NAME) { INIT } AST_SELECTNODE_TABLE #undef X #define X(NAME, BASE, DECLS, INIT) template NAME* SymbolTable::create<NAME>(); AST_SELECTNODE_TABLE #undef X #define X(NAME, BASE, DECLS, INIT) \ NAME::~NAME() {} AST_SELECTNODE_TABLE #undef X Opcode::Opcode(SymbolTable& Symtab) : SelectBase(Symtab, NodeType::Opcode) {} template Opcode* SymbolTable::create<Opcode>(); Opcode::~Opcode() {} bool Opcode::validateNode(ConstNodeVectorType& Parents) const { TRACE_METHOD("validateNode"); TRACE(node_ptr, nullptr, this); CaseRangeVector.clear(); uint32_t InitialWidth; if (!getCaseSelectorWidth(getKid(0), InitialWidth)) { errorDescribeNode("Inside", this); errorDescribeNode("Opcode value doesn't have fixed width", getKid(0)); return false; } for (int i = 1, NumKids = getNumKids(); i < NumKids; ++i) { assert(isa<Case>(Kids[i])); const Case* C = cast<Case>(Kids[i]); std::unordered_set<uint32_t> CaseWidths; IntType Key = getIntegerValue(C->getKid(0)); if (!collectCaseWidths(Key, C->getKid(1), CaseWidths)) { errorDescribeNode("Unable to install caches for opcode s-expression", this); return false; } for (uint32_t NestedWidth : CaseWidths) { uint32_t Width = InitialWidth + NestedWidth; if (Width > MaxOpcodeWidth) { errorDescribeNode("Bit width(s) too big", this); return false; } IntType Min = Key << NestedWidth; IntType Max = Min + getWidthMask(NestedWidth); WriteRange Range(C, Min, Max, NestedWidth); CaseRangeVector.push_back(Range); } } // Validate that ranges are not overlapping. std::sort(CaseRangeVector.begin(), CaseRangeVector.end()); for (size_t i = 0, Last = CaseRangeVector.size() - 1; i < Last; ++i) { const WriteRange& R1 = CaseRangeVector[i]; const WriteRange& R2 = CaseRangeVector[i + 1]; if (R1.getMax() >= R2.getMin()) { errorDescribeNode("Range 1", R1.getCase()); errorDescribeNode("Range 2", R2.getCase()); errorDescribeNode("Opcode case ranges not unique", this); return false; } } return true; } const Case* Opcode::getWriteCase(decode::IntType Value, uint32_t& SelShift, IntType& CaseMask) const { // TODO(kschimf): Find a faster lookup (use at least binary search). for (const auto& Range : CaseRangeVector) { if (Value < Range.getMin()) { SelShift = 0; return nullptr; } else if (Value <= Range.getMax()) { SelShift = Range.getShiftValue(); CaseMask = getWidthMask(SelShift); return Range.getCase(); } } SelShift = 0; return nullptr; } Opcode::WriteRange::WriteRange() : C(nullptr), Min(0), Max(0), ShiftValue(0) {} Opcode::WriteRange::WriteRange(const Case* C, decode::IntType Min, decode::IntType Max, uint32_t ShiftValue) : C(C), Min(Min), Max(Max), ShiftValue(ShiftValue) {} Opcode::WriteRange::WriteRange(const WriteRange& R) : C(R.C), Min(R.Min), Max(R.Max), ShiftValue(R.ShiftValue) {} Opcode::WriteRange::~WriteRange() {} void Opcode::WriteRange::assign(const WriteRange& R) { C = R.C; Min = R.Min; Max = R.Max; ShiftValue = R.ShiftValue; } int Opcode::WriteRange::compare(const WriteRange& R) const { if (Min < R.Min) return -1; if (Min > R.Min) return 1; if (Max < R.Max) return -1; if (Max > R.Max) return 1; if ((void*)C < (void*)R.C) return -1; if ((void*)C > (void*)R.C) return 1; return 0; } utils::TraceClass& Opcode::WriteRange::getTrace() const { return C->getTrace(); } BinaryEval::BinaryEval(SymbolTable& Symtab, Node* Encoding) : Unary(Symtab, NodeType::BinaryEval, Encoding) {} template BinaryEval* SymbolTable::create<BinaryEval>(Node* Kid); BinaryEval::~BinaryEval() {} IntLookup* BinaryEval::getIntLookup() const { IntLookup* Lookup = cast<IntLookup>(Symtab.getCachedValue(this)); if (Lookup == nullptr) { Lookup = Symtab.create<IntLookup>(); Symtab.setCachedValue(this, Lookup); } return Lookup; } const Node* BinaryEval::getEncoding(IntType Value) const { IntLookup* Lookup = getIntLookup(); const Node* Nd = Lookup->get(Value); if (Nd == nullptr) Nd = Symtab.getError(); return Nd; } bool BinaryEval::addEncoding(const BinaryAccept* Encoding) const { return getIntLookup()->add(Encoding->getValue(), Encoding); } } // end of namespace filt } // end of namespace wasm
28.874357
80
0.615502
[ "vector" ]
bc963bc70cd49c6de36654f841d59ba3e2774019
2,817
hpp
C++
libraries/include/Engine/UI/Text.hpp
kermado/Total-Resistance
debaf40ba3be6590a70c9922e1d1a5e075f4ede3
[ "MIT" ]
3
2015-04-25T22:57:58.000Z
2019-11-05T18:36:31.000Z
libraries/include/Engine/UI/Text.hpp
kermado/Total-Resistance
debaf40ba3be6590a70c9922e1d1a5e075f4ede3
[ "MIT" ]
1
2016-06-23T15:22:41.000Z
2016-06-23T15:22:41.000Z
libraries/include/Engine/UI/Text.hpp
kermado/Total-Resistance
debaf40ba3be6590a70c9922e1d1a5e075f4ede3
[ "MIT" ]
null
null
null
#ifndef TEXT_H #define TEXT_H #include <string> #include <vector> #include <glm/glm.hpp> #include <Engine/UI/IShape.hpp> #include <Engine/UI/Font.hpp> namespace Engine { namespace UI { class Text : public IShape { public: /** * Constructor. */ Text(); /** * Destructor. */ virtual ~Text(); /** * Returns the dimensions for the text. * * @return Text dimensions (width, height). */ glm::vec2 GetDimensions() const; /** * Returns the width of the text. * * @return Text width. */ float GetWidth() const; /** * Returns the height of the text. * * @return Text height. */ float GetHeight() const; /** * Sets the specified font to be used for rendering the text. * * @param font Font to use for rendering the text. */ void SetFont(const Font& font); /** * Returns the current text string. * * @return Current text string. */ std::string GetString() const; /** * Sets the string to be displayed. * * @param string String to be displayed. */ void SetString(std::string string); /** * Sets the character size for the text. * * @param characterSize Character size (in pixels). */ void SetCharacterSize(unsigned int characterSize); /** * Returns the number of vertices that compose the text. * * @return Number of vertices that compose the text. */ virtual unsigned int GetVertexCount() const; protected: /** * Returns the position of the vertex specified by the supplied * index. * * @param index Index for the vertex position to retrieve. This must * be in the range [0, GetVertexCount() - 1]. * @return The position of the index-th vertex. */ virtual glm::vec2 GetVertexPosition(unsigned int index) const; /** * Returns the UV texture coordinates for the vertex specified by * the provided index. * * @param index Vertex index for the UV coordinate to return. * @return UV texture coordinate for the specified vertex index. */ virtual glm::vec2 GetTextureCoordinate(unsigned int index) const; private: /** * Updates the text's geometry. */ void UpdateGeometry(); private: /** * The font to use for rendering the text. */ const Font* m_font; /** * The text string to be displayed. */ std::string m_string; /** * The character size (in pixels). */ unsigned int m_characterSize; /** * The vertex positions. */ std::vector<glm::vec2> m_vertexPositions; /** * The texture coordinates. */ std::vector<glm::vec2> m_textureCoordinates; /** * Bounding rectangle for the text. */ IntRectangle m_boundingRectangle; }; } } #endif
19.294521
71
0.611644
[ "geometry", "vector" ]
bca642013289d453be88015f7e322eb04edd01a9
2,017
cpp
C++
Praktikum5/Praktikum5/Praktikum5/main.cpp
dekorlp/Codingtheory
94c2caf72df73550b115bd5a53fc719d5932cfbc
[ "Apache-2.0" ]
null
null
null
Praktikum5/Praktikum5/Praktikum5/main.cpp
dekorlp/Codingtheory
94c2caf72df73550b115bd5a53fc719d5932cfbc
[ "Apache-2.0" ]
null
null
null
Praktikum5/Praktikum5/Praktikum5/main.cpp
dekorlp/Codingtheory
94c2caf72df73550b115bd5a53fc719d5932cfbc
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <vector> struct RM { unsigned int r; unsigned int m; }; std::vector<std::vector<int>> ReedMuellerAlgorithm(RM rm); void PrintMatrix(int rowCount, int columnCount, std::vector<std::vector<int>> matrix); std::vector<std::vector<int>> ReedMuellerAlgorithm(RM rm) { std::vector<std::vector<int>> result; RM work = rm; if (work.r > work.m) { work.r = work.m; } if (work.r == 0) { std::vector<int> value; for (int i = 0; i < std::pow(2, work.m); i++) { value.push_back(1); } result.push_back(value); } else { std::vector<std::vector<int>> matrix00 = ReedMuellerAlgorithm({ work.r, work.m - 1}); std::vector<std::vector<int>> matrix11 = ReedMuellerAlgorithm({ work.r - 1, work.m - 1}); for (int i = 0; i < matrix00.size(); i++) { std::vector<int> value; for (int j = 0; j < matrix00[i].size(); j++) { value.push_back(matrix00[i][j]); } for (int j = 0; j < matrix00[i].size(); j++) { value.push_back(matrix00[i][j]); } result.push_back(value); } for (int i = 0; i < matrix11.size(); i++) { std::vector<int> value; for (int j = 0; j < matrix11[i].size(); j++) { value.push_back(0); } for (int j = 0; j < matrix11[i].size(); j++) { value.push_back(matrix11[i][j]); } result.push_back(value); } } return result; } void PrintMatrix(int rowCount, int columnCount, std::vector<std::vector<int>> matrix) { for (int i = 0; i < rowCount; i++) { for (int j = 0; j < columnCount; j++) { std::cout << matrix[i][j] << " "; } std::cout << std::endl; } } int main() { unsigned int r = 1, m = 3; //unsigned int r = 1, m = 5; //unsigned int r = 2, m = 3; std::cout << "Reed-Muller Code with Parameters: r = " << r << " and m = " << m << std::endl; std::cout << "-------------------------------------------------" << std::endl; std::vector<std::vector<int>> matrix = ReedMuellerAlgorithm({r, m}); PrintMatrix(matrix.size(), matrix[0].size(), matrix); int test = 0; }
21.010417
93
0.562717
[ "vector" ]
bca7b9ec7bca94bd92b73b9268fc624343dedcaa
2,447
cpp
C++
using-cpp-standard-template-libraries-master/Chapter 8/Ex8_09.cpp
ai-chen2050/book-code
74676efa50ef9e8a4a40b97978d9d42f18070102
[ "MIT" ]
null
null
null
using-cpp-standard-template-libraries-master/Chapter 8/Ex8_09.cpp
ai-chen2050/book-code
74676efa50ef9e8a4a40b97978d9d42f18070102
[ "MIT" ]
null
null
null
using-cpp-standard-template-libraries-master/Chapter 8/Ex8_09.cpp
ai-chen2050/book-code
74676efa50ef9e8a4a40b97978d9d42f18070102
[ "MIT" ]
null
null
null
// Ex8_09.cpp // Demonstrating the piecewise linear distribution #include <random> // For distributions and random number generator #include <vector> // For vector container #include <map> // For map container #include <utility> // For pair type #include <algorithm> // For copy(), count(), remove() #include <iostream> // For standard streams #include <iterator> // For stream iterators #include <iomanip> // For stream manipulators #include <string> // For string class using std::string; int main() { std::vector<double> v {10, 30, 40, 55, 60}; // Sample values std::vector<double> w {6, 12, 9, 6, 0}; // Weights for the samples std::piecewise_linear_distribution<> d {std::begin(v), std::end(v), std::begin(w)}; // Output the interval boundaries and the interval probabilities auto values = d.intervals(); std::cout << "Sample values: "; std::copy(std::begin(values), std::end(values), std::ostream_iterator<double>{std::cout, " "}); std::cout << " probability densities: "; auto probs = d.densities(); std::copy(std::begin(probs), std::end(probs), std::ostream_iterator<double>{std::cout, " "}); std::cout << '\n' << std::endl; std::random_device rd; std::default_random_engine rng {rd()}; std::map<int, size_t> results; //Stores and counts random values as integers // Generate a lot of random values... for(size_t i {}; i < 20000; ++i) ++results[static_cast<int>(std::round(d(rng)))]; // Plot the integer values auto max_count = std::max_element(std::begin(results), std::end(results), [](const std::pair<int, size_t>& pr1, const std::pair<int, size_t>& pr2) { return pr1.second < pr2.second; })->second; std::for_each(std::begin(results), std::end(results), [max_count](const std::pair<int, size_t>& pr) { if(!(pr.first % 10)) // Display value if multiple of 10 std::cout << std::setw(3) << pr.first << "-|"; else std::cout << " |"; std::cout << std::string(pr.second * 80 / max_count, '*') << '\n'; }); }
50.979167
105
0.531671
[ "vector" ]
bcb54babce1db34e1d1b3b9e33cac34c6391e212
13,545
cpp
C++
proj6/light_source.cpp
sumnerjj/6.172
53d22fe5f043f8170a426f167d32b648d7d4ee67
[ "MIT" ]
null
null
null
proj6/light_source.cpp
sumnerjj/6.172
53d22fe5f043f8170a426f167d32b648d7d4ee67
[ "MIT" ]
null
null
null
proj6/light_source.cpp
sumnerjj/6.172
53d22fe5f043f8170a426f167d32b648d7d4ee67
[ "MIT" ]
null
null
null
#include <cmath> #include <iostream> #include <assert.h> #include "light_source.h" #include "photonmap.h" #include "raytracer.h" #include "random.h" #include "config.h" SquarePhotonLight::SquarePhotonLight(Colour col, Raytracer *raytracer ) : col(col), raytracer(raytracer), icache(ICACHE_TOLERANCE, ICACHE_MIN_SPACING) { light_col = col; } SquarePhotonLight::~SquarePhotonLight() { destroyPhotonMap(bmap); destroyPhotonMap(cmap); } void SquarePhotonLight::initTransformMatrix(Matrix4x4 mat, Vector3D& w) { Vector3D u, v; if ((fabs(w.x) < fabs(w.y)) && (fabs(w.x) < fabs(w.z))) { v.x = 0; v.y = w.z; v.z = -w.y; } else if (fabs(w.y) < fabs(w.z)) { v.x = w.z; v.y = 0; v.z = -w.x; } else { v.x = w.y; v.y = -w.x; v.z = 0; } v.normalize(); u = v.cross(w); mat[0][0] = u.x; mat[1][0] = u.y; mat[2][0] = u.z; mat[0][1] = v.x; mat[1][1] = v.y; mat[2][1] = v.z; mat[0][2] = w.x; mat[1][2] = w.y; mat[2][2] = w.z; } void SquarePhotonLight::globalIllumination(Ray3D& ray, bool getDirectly) { // If we're not already in the irradiance cache, compute the irradiance via // monte carlo methods. if (!icache.getIrradiance(ray.intersection.point, ray.intersection.normal, &ray.col)) { Colour c; ray.col = Colour(0, 0, 0); int N = MONTE_CARLO_STRATIFICATION_N; int M = MONTE_CARLO_STRATIFICATION_M; int hits = 0; double r0 = 0; Matrix4x4 basis; initTransformMatrix(basis, ray.intersection.normal); // Stratification for (int i = 0; i < N; i++) { double phi = 2 * M_PI * ((double) i + r.Random1()) / N; double sinPhi = sin(phi); double cosPhi = cos(phi); for (int j = 0; j < M; j++) { double cosTheta = sqrt(1 - (((double) j + r.Random1()) / M)); double theta = acos(cosTheta); double sinTheta = sin(theta); Vector3D v = Vector3D(cosPhi * sinTheta, sinPhi * sinTheta, cosTheta); v = v.transform(basis); v.normalize(); Ray3D new_ray = Ray3D(ray.intersection.point, v); raytracer->traverseEntireScene(new_ray, true); if (!new_ray.intersection.none) { raytracer->computeShading(new_ray, 3, true); ray.col += new_ray.col; r0 += 1 / new_ray.intersection.t_value; hits++; } } } ray.col *= 1.0 / hits; r0 = 1 / r0; if (hits == N * M) { icache.insert(ray.intersection.point, ray.intersection.normal, r0, ray.col); } } ray.col *= ray.intersection.mat->diffuse; } void SquarePhotonLight::causticIllumination(Ray3D& ray) { // Caustics Colour caus_col; Vector3D normal = ray.intersection.normal; normal.normalize(); if (raytracer->soft_shadows) { irradianceEstimate(cmap, &caus_col, ray.intersection.point, normal, CAUSTICS_SOFT_MAX_DISTANCE, CAUSTIC_SOFT_MAX_PHOTONS); } else { irradianceEstimate(cmap, &caus_col, ray.intersection.point, normal, CAUSTICS_MAX_DISTANCE, CAUSTIC_MAX_PHOTONS); } double cosTheta12 = sqrt(-(ray.dir.dot(ray.intersection.normal))); caus_col *= ray.intersection.mat->diffuse; ray.col += caus_col * cosTheta12; } void SquarePhotonLight::directIllumination(Ray3D& ray) { // Direct illumination int N = 1; int M = 1; if (raytracer->soft_shadows) { N = NUM_SOFT_SHADOW_RAYS_IN_EACH_DIM; M = NUM_SOFT_SHADOW_RAYS_IN_EACH_DIM; } Colour direct_col = Colour(0, 0, 0); double dx = 1.0 / (N + 1); double dz = 1.0 / (M + 1); // Loop for soft shadows for (int i = 1; i <= N; i++) { double x; if (raytracer->soft_shadows) { double rand = r.Random1(); double dx_rand = rand - floor(rand); x = ((i + dx_rand) * dx) * 30 - 15; } else { x = i * dx * 30 - 15; } for (int j = 1; j <= M; j++) { double z; if (raytracer->soft_shadows) { double rand = r.Random1(); double dz_rand = rand - floor(rand); z = (((double) j + dz_rand) * dz) * 30 - 15; } else { z = i * dz * 30 - 15; } Vector3D L = Point3D(0 + x, 50, 0 + z) - ray.intersection.point; double l = sqrt(L.x * L.x + L.z * L.z + L.y * L.y); L.normalize(); Vector3D LN = Vector3D(0, -1, 0); double scale = -LN.dot(L); scale = scale < 0 ? 0 : scale; scale /= l * l * 1.5 * M_PI; Ray3D new_ray = Ray3D(ray.intersection.point, L); raytracer->traverseEntireScene(new_ray, false); if (!new_ray.intersection.none && new_ray.intersection.mat->light) { Vector3D R = 2.0 * ray.intersection.normal.dot(L) * ray.intersection.normal - L; double NdotL = L.dot(ray.intersection.normal); double RdotV = -(R.dot(ray.dir)); NdotL = NdotL < 0 ? 0 : NdotL; RdotV = RdotV < 0 ? 0 : RdotV; if (ray.dir.dot(ray.intersection.normal) > 0) { RdotV = 0; } direct_col += (light_col * scale * (ray.intersection.mat->diffuse * NdotL + ray.intersection.mat->specular * pow(RdotV, ray.intersection.mat->specular_exp))); } } } direct_col = direct_col / (N * M); ray.col += direct_col; } void SquarePhotonLight::shade(Ray3D& ray, bool getDirectly) { // Don't bother shading lights, just give it the color of the light source. if (ray.intersection.mat->light) { ray.col = ray.intersection.mat->diffuse; return; } // getDirectly means we visualize the photon map directly. if (getDirectly) { Vector3D normal = ray.intersection.normal; normal.normalize(); irradianceEstimate(bmap, &ray.col, ray.intersection.point, normal, INDIRECT_MAX_DISTANCE, INDIRECT_MAX_PHOTONS); ray.col = ray.col * ray.intersection.mat->diffuse; return; } // Only look at objects in the photon map if (ray.intersection.mat->isDiffuse) { if (raytracer->global_illumination) globalIllumination(ray, getDirectly); if (raytracer->caustics) causticIllumination(ray); } if (raytracer->direct_illumination) directIllumination(ray); } Vector3D SquarePhotonLight::getRandLambertianDir(Vector3D& normal) { Vector3D v; double phi = 2 * M_PI * r.Random1(); double sinPhi = sin(phi); double cosPhi = cos(phi); double cosTheta = sqrt(r.Random1()); double theta = acos(cosTheta); double sinTheta = sin(theta); Matrix4x4 basis; initTransformMatrix(basis, normal); v = Vector3D(cosPhi * sinTheta, sinPhi * sinTheta, cosTheta); v = v.transform(basis); v.normalize(); return v; } void SquarePhotonLight::tracePhotons(int num, int caustics_num) { PhotonMap *map = createPhotonMap(num * 4); cout << "Emitting global illumination photons: 0%% "; int i = 0; while (i < num) { // Calculate the start pos and direction of the photon Point3D p = Point3D(r.Random2() * 16, 49.99, r.Random2() * 16); Vector3D v = Vector3D(0, -1, 0); v = getRandLambertianDir(v); Ray3D ray = Ray3D(p, v); ray.col = col; int count = 0; while (ray.col.max() > 0.1 && count++ < 100) { raytracer->traverseEntireScene(ray, true); if (ray.intersection.none) { i--; break; } Vector3D dir_norm = ray.dir; dir_norm.normalize(); if (ray.intersection.mat->isDiffuse) { storePhoton(map, ray.col, ray.intersection.point, dir_norm); } double ran = r.Random1(); Colour c = ray.col * ray.intersection.mat->diffuse; double P = c.max() / ray.col.max(); if (ran < P) { // Diffuse reflection v = getRandLambertianDir(ray.intersection.normal); } else { ran -= P; c = ray.col * ray.intersection.mat->specular; P = c.max() / ray.col.max(); if (ran < P) { // Specular reflection v = ray.dir - (2 * ray.dir.dot(ray.intersection.normal)) * ray.intersection.normal; } else { ran -= P; c = ray.col * ray.intersection.mat->refractive; P = c.max() / ray.col.max(); if (ran < P) { // Refraction double n; if (ray.dir.dot(ray.intersection.normal) < 0) { n = 1 / ray.intersection.mat->refr_index; } else { ray.intersection.normal = -ray.intersection.normal; n = ray.intersection.mat->refr_index; } double cosI = ray.intersection.normal.dot(ray.dir); double sinT2 = n * n * (1.0 - cosI * cosI); if (sinT2 < 1.0) { v = n * ray.dir - (n * cosI + sqrt(1.0 - sinT2)) * ray.intersection.normal; } else { // Total internal reflection v = ray.dir - (2 * ray.dir.dot(ray.intersection.normal)) * ray.intersection.normal; } } else { // Absorption break; } } } ray.origin = ray.intersection.point; ray.dir = v; ray.col = c / P; ray.intersection.none = true; ray.intersection.t_value = FLT_MAX; } raytracer->printProgress((int) (((i + 1) * 100.0) / num)); i++; } scalePhotonPower(map, 1.0 / i); bmap = balancePhotonMap(map); // Caustics map = createPhotonMap(caustics_num); int emitted = 0; i = 0; cout << endl << "Emitting caustics illumination photons: 0%% "; while (i < caustics_num) { // Calculate the start pos and direction of the photon Point3D p; if (raytracer->soft_shadows) { p = Point3D(r.Random2() * 18, 49.99, r.Random2() * 18); } else { p = Point3D(0, 49.99, 0); } Vector3D v = Vector3D(0, -1, 0); v = getRandLambertianDir(v); Ray3D ray = Ray3D(p, v); ray.col = col; emitted++; raytracer->traverseEntireScene(ray, true); if (!ray.intersection.none && ray.intersection.mat->isSpecular) { while (1) { raytracer->traverseEntireScene(ray, true); if (ray.intersection.none) break; Vector3D dir_norm = ray.dir; dir_norm.normalize(); if (ray.intersection.mat->isDiffuse) { storePhoton(map, ray.col, ray.intersection.point, dir_norm); i++; break; } double ran = r.Random1(); Colour c = ray.col * ray.intersection.mat->specular; double P = c.max() / ray.col.max(); // Specular reflection if (ran < P) { ray.intersection.normal = -ray.intersection.normal; v = ray.dir - (2 * ray.dir.dot(ray.intersection.normal)) * ray.intersection.normal; } else { ran -= P; c = ray.col * ray.intersection.mat->refractive; P = c.max() / ray.col.max(); if (ran < P) { // Refraction double n; if (ray.dir.dot(ray.intersection.normal) < 0) { n = 1 / ray.intersection.mat->refr_index; } else { ray.intersection.normal = -ray.intersection.normal; n = ray.intersection.mat->refr_index; } double cosI = ray.intersection.normal.dot(ray.dir); double sinT2 = n * n * (1.0 - cosI * cosI); if (sinT2 < 1.0) { v = n * ray.dir - (n * cosI + sqrt(1.0 - sinT2)) * ray.intersection.normal; } else { // Total internal reflection. v = ray.dir - (2 * ray.dir.dot(ray.intersection.normal)) * ray.intersection.normal; } } else { // Absorption i++; break; } } ray.origin = ray.intersection.point; ray.dir = v; ray.col = c / P; ray.intersection.none = true; ray.intersection.t_value = FLT_MAX; } raytracer->printProgress((int) (((i + 1) * 100.0) / caustics_num)); } } cout << endl; scalePhotonPower(map, 1.0 / emitted); cmap = balancePhotonMap(map); }
29.509804
92
0.501661
[ "transform" ]
bcc2f3d265bfd4eae0f97c36528e0adc8b095134
9,186
cpp
C++
compiler/html.cpp
iamrekcah/clay
dad107fd190da9a4a1e1f6d0c14927f1960d46e9
[ "BSD-2-Clause" ]
5
2015-06-05T17:48:58.000Z
2015-10-03T22:20:12.000Z
compiler/html.cpp
iamrekcah/clay
dad107fd190da9a4a1e1f6d0c14927f1960d46e9
[ "BSD-2-Clause" ]
7
2015-03-22T06:13:42.000Z
2015-12-28T19:07:24.000Z
compiler/html.cpp
iamrekcah/clay
dad107fd190da9a4a1e1f6d0c14927f1960d46e9
[ "BSD-2-Clause" ]
1
2018-10-20T20:38:31.000Z
2018-10-20T20:38:31.000Z
#include "claydoc.hpp" #include <fstream> #include <sstream> #include <errno.h> using namespace clay; using namespace std; static string getCssStyle() { return "* { padding: 0; margin: 0 }\n" "body { background: #fff; font-family: sans-serif; font-size: 0.8em; }\n" "#mainContentInner { margin-left: 10%; }\n" "#navigation { background: #999; }\n" "#navigation li { list-style: none; }\n" "#navigation li a { " "display: block;" "padding: 0.5em;" "float: left;" "background: #999;" "text-decoration: underline;" "color: #000;" "font-weight: bold;" "}\n" "#navigation .post-ul { clear: both; }\n" "#main h1 { background: #aaa; padding-left: 10% }\n" "#mainContentHeader { background: #aaa; border-bottom: 1px solid black; }\n" "#mainContentHeader .inlinedoc { padding-left: 11%; }\n" "h2 { padding-bottom: 0.5em; }\n" "section { padding: 2em; }\n" "section h2 { " "width: 80%;" "display: block;" "border-bottom: 1pxsolid #aaa;" "padding: 0;" "margin-bottom: 1.5em;" "font-size: 1em;" "}\n" "h3 { font-weight: normal; }\n" ".functionPredicate { display: block; font-size: 0.8em; margin-left: 0.7em; }\n" ".keyword { " "font-weight: bold;" "width: 5em;" "display: inline-block;" "text-align: right;" "padding-right: 0.5em;" "color: #522;" "line-height: 1.4em;" "}\n" ".identifier { height: 1.4em; line-height: 1.4em; display: inline-block }\n" ".definition , .overload { margin-top: 0.5em; }\n" ".inlinedoc { padding-bottom: 1em; padding-left: 1em }\n" "a.reference { text-decoration: none; color: #000 }\n" "a.reference:hover { text-decoration: underline; color: #00f; }\n" ".brokenreference { background: url(underline.gif) bottom repeat-x; }\n" "#moduleIndexOuter {}\n" "#moduleIndexOuter li { list-style: none; }\n" ",moduleIndexSectionHeader { margin-bottom: 1em; padding-top: 2em; clear: both; }\n" ".moduleIndexItem { display: block; float: left; width: 49%; }\n" ".moduleIndexItem a { text-decoration: none; color: #000; }\n" ".moduleIndexItem a:hover { text-decoration: underline; color: #00f; }\n" ; } static void htmlEncode(std::string& data) { std::string buffer; buffer.reserve(data.size()); for(size_t pos = 0; pos != data.size(); ++pos) { switch(data[pos]) { case '&': buffer.append("&amp;"); break; case '\"': buffer.append("&quot;"); break; case '\'': buffer.append("&apos;"); break; case '<': buffer.append("&lt;"); break; case '>': buffer.append("&gt;"); break; default: buffer.append(1, data[pos]); break; } } data.swap(buffer); } static void emitInlineDoc(std::ostream &o, const std::string &str) { if (str.empty()) return; std::istringstream lines(str); std::string line; o << "<div class='inlinedoc'>\n"; while (getline(lines, line )) { o << "<p class='inlinedocLine'>" << line << "</p>\n"; } o << "</div>\n"; } static void emitHtmlOverload(std::ostream &o, DocState *state, DocObject *item) { clay::OverloadPtr overload = (clay::Overload *)item->item.ptr(); std::string htmlName(item->name); htmlEncode(htmlName); o << "<div class='overload'> <h3> "; clay::CodePtr code = overload->code; if (!!code->predicate) { std::string pred = code->predicate->asString(); htmlEncode(pred); o << "<span class='functionPredicate'>[ " << pred<< " ]</span> "; } if (state->references[item->name]) o << "<a class='reference' href='" << state->references[item->name]->fqn << ".html#" << htmlName << "'> "; else o << "<span class='brokenreference'>"; o << "<span class='keyword'> overload </span>"; o << "<span class='identifier'>"; o << htmlName; o << "</span>"; if (state->references[item->name]) o << "</a>"; else o << "</span>"; o << " ( "; o << "<span class='functionSignature'>\n"; for (vector<FormalArgPtr>::iterator it = code->formalArgs.begin(); it != code->formalArgs.end(); it++){ FormalArgPtr arg = *it; if (!!arg->name) { std::string name = identifierString(arg->name); htmlEncode(name); o << " <span class='functionArgumentName' > " << name << "</span>"; } if (!!arg->type) { std::string type = arg->type->asString(); htmlEncode(type); o << " : "; o << "<span class='functionArgumentType' > " << type << "</span>\n"; } if (it + 1 != code->formalArgs.end()) o << " , "; } o << " </span> ) </span> </h3>"; emitInlineDoc(o, item->description); o << "</div>" << endl; } static void emitHtmlProcedure(std::ostream &o, DocState *state, DocObject *item) { std::string htmlName(item->name); htmlEncode(htmlName); o << "<div class='definition'> " << "<h3>" << "<a name='" << htmlName << "'>" << "<span class='keyword'> public </span>" << "<span class='identifier'>" << htmlName << "</span> </a> </h3>"; emitInlineDoc(o, item->description); o << "</div>" << endl; } static void emitHtmlRecord(std::ostream &o, DocState *state, DocObject *item) { std::string htmlName(item->name); htmlEncode(htmlName); o << "<div class='record'> " << "<h3>" << "<a name='" << htmlName << "'>" << "<span class='keyword'> record </span>" << "<span class='identifier'>" << htmlName << "</span> </a> </h3>"; emitInlineDoc(o, item->description); o << "</div>" << endl; } static void emitHtmlHeader(std::ostream &o, std::string title) { o << "<!doctype html>\n" << "<html lang='en'>\n" << "<head>\n" << "<title>" << title << "</title>\n" << "<style>\n" << getCssStyle() << "</style>\n" << "</head><body>" << "<div id='navigation'><ul>\n" << " <li><a href='index.html'> Module Index </a> </li>\n" << "</ul><div class='post-ul'></div></div> \n" << "<div id='main'> \n" ; } static void emitHtmlFooter(std::ostream &o) { o << "\n</div>\n" << "\n</body>\n</html>\n"; } void emitHtmlModule(std::string outpath, DocState *state, DocModule *mod) { ofstream o; std::string outFileName = outpath + "/" + string(mod->fqn) + ".html"; o.open (outFileName.c_str(), ios::trunc); if (!o.is_open()) { llvm::errs() << "failed to open " << outFileName << "\n"; exit(errno); } emitHtmlHeader(o, mod->fqn); o << "<div id='mainContentOuter'> <div id='mainContentHeader'> \n<h1>" << mod->fqn << "</h1> \n"; emitInlineDoc(o, mod->description); o << "</div><div id='mainContentInner'>"; for (std::vector<DocSection*>::iterator it = mod->sections.begin(); it != mod->sections.end(); it++) { o << "<section>" << endl; if (!(*it)->name.empty()) o << "<h2> " << (*it)->name << "</h2>" << endl; emitInlineDoc(o, (*it)->description); for (std::vector<DocObject *>::iterator i2 = (*it)->objects.begin(); i2 != (*it)->objects.end(); i2++) { switch ((*i2)->item->objKind) { case clay::PROCEDURE: emitHtmlProcedure(o, state, *i2); break; case clay::RECORD_DECL: emitHtmlRecord(o, state, *i2); break; case clay::OVERLOAD: emitHtmlOverload(o, state, *i2); break; default: {} // make compiler happy } } o << "</section>" << endl; } o << "</div></div>" << endl; emitHtmlFooter(o); o.close(); } void emitHtmlIndex(std::string outpath, DocState *state) { ofstream index; index.open ((outpath + "/index.html").c_str(), ios::trunc); if (!index.is_open()) { llvm::errs() << "failed to open " << (outpath + "/index.html")<< "\n"; exit(errno); } emitHtmlHeader(index, state->name); index << "<div id='mainContentOuter'>\n<h1> " << state->name << "</h1> \n"; index << "<div id='mainContentInner'>\n"; char a = 0; for (std::map<std::string, DocModule*>::iterator j = state->modules.begin(); j != state->modules.end(); j++) { if (j->first.empty()) continue; if (j->first.at(0) != a ) { if (a != 0) index << "</ul></section>"; a = j->first.at(0); index << "<section class='moduleIndexSection' ><h2 class='moduleIndexSectionHeader'>" << a << "</h2> <ul>"; } index << "<li class='moduleIndexItem'> <a href='" << string(j->first) + ".html" << "'> " << string(j->first) << " </a> </li>\n"; emitHtmlModule(outpath, state, j->second); } index << "</ul></section>"; index << "</div></div>" << endl; index.close(); }
32.231579
136
0.515676
[ "vector", "solid" ]
bcc45d1c4e288f401c606f3073236780528cdc04
2,415
cc
C++
cpp_src/core/ft/filters/kblayout.cc
SolovyovAlexander/reindexer
2c6fcd957c1743b57a4ce9a7963b52dffc13a519
[ "Apache-2.0" ]
695
2017-07-07T16:54:23.000Z
2022-03-19T09:48:30.000Z
cpp_src/core/ft/filters/kblayout.cc
SolovyovAlexander/reindexer
2c6fcd957c1743b57a4ce9a7963b52dffc13a519
[ "Apache-2.0" ]
63
2018-01-18T02:57:48.000Z
2022-03-04T10:28:05.000Z
cpp_src/core/ft/filters/kblayout.cc
SolovyovAlexander/reindexer
2c6fcd957c1743b57a4ce9a7963b52dffc13a519
[ "Apache-2.0" ]
72
2017-07-12T21:12:59.000Z
2021-11-28T14:35:06.000Z
#include "kblayout.h" #include <assert.h> namespace reindexer { void KbLayout::GetVariants(const std::wstring& data, std::vector<std::pair<std::wstring, int>>& result) { std::wstring result_string; result_string.reserve(data.length()); for (size_t i = 0; i < data.length(); ++i) { auto sym = data[i]; if (sym >= ruLettersStartUTF16 && sym <= ruLettersStartUTF16 + ruAlfavitSize - 1) { // russian layout assert(sym >= ruLettersStartUTF16 && sym - ruLettersStartUTF16 < ruAlfavitSize); result_string.push_back(ru_layout_[sym - ruLettersStartUTF16]); } else if (sym >= allSymbolStartUTF16 && sym < allSymbolStartUTF16 + engAndAllSymbols) { // en symbol assert(sym >= allSymbolStartUTF16 && sym - allSymbolStartUTF16 < engAndAllSymbols); result_string.push_back(all_symbol_[sym - allSymbolStartUTF16]); } else { result_string.push_back(sym); } } result.push_back({std::move(result_string), 90}); } void KbLayout::setEnLayout(wchar_t sym, wchar_t data) { assert(((sym >= allSymbolStartUTF16) && (sym - allSymbolStartUTF16 < engAndAllSymbols))); all_symbol_[sym - allSymbolStartUTF16] = data; // ' } void KbLayout::PrepareEnLayout() { for (int i = 0; i < engAndAllSymbols; ++i) { all_symbol_[i] = i + allSymbolStartUTF16; } for (int i = 0; i < ruAlfavitSize; ++i) { setEnLayout(ru_layout_[i], i + ruLettersStartUTF16); } } void KbLayout::PrepareRuLayout() { ru_layout_[0] = L'f'; //а ru_layout_[1] = L','; //б ru_layout_[2] = L'd'; //в ru_layout_[3] = L'u'; //г ru_layout_[4] = L'l'; //д ru_layout_[5] = L't'; //е ru_layout_[6] = L';'; //ж ru_layout_[7] = L'p'; //з ru_layout_[8] = L'b'; //и ru_layout_[9] = L'q'; //й ru_layout_[10] = L'r'; //к ru_layout_[11] = L'k'; //л ru_layout_[12] = L'v'; //м ru_layout_[13] = L'y'; //н ru_layout_[14] = L'j'; //о ru_layout_[15] = L'g'; //п ru_layout_[16] = L'h'; //р ru_layout_[17] = L'c'; //с ru_layout_[18] = L'n'; //т ru_layout_[19] = L'e'; //у ru_layout_[20] = L'a'; //ф ru_layout_[21] = L'['; //х ru_layout_[22] = L'w'; //ц ru_layout_[23] = L'x'; //ч ru_layout_[24] = L'i'; //ш ru_layout_[25] = L'o'; //щ ru_layout_[26] = L']'; //ъ ru_layout_[27] = L's'; //ы ru_layout_[28] = L'm'; //ь ru_layout_[29] = L'\''; //э ru_layout_[30] = L'.'; //ю ru_layout_[31] = L'z'; //я } KbLayout::KbLayout() { PrepareRuLayout(); PrepareEnLayout(); } } // namespace reindexer
29.814815
105
0.627743
[ "vector" ]
344d5af9a202736dfe8f06a5e09a62b980da4d91
1,355
hpp
C++
libraries/PrinterAPI/include/printer/JsonPrinter.hpp
StratifyLabs/API
ca0bf670653b78da43ad416cd1c5e977c8549eeb
[ "MIT" ]
7
2020-12-15T14:27:02.000Z
2022-03-23T12:00:13.000Z
libraries/PrinterAPI/include/printer/JsonPrinter.hpp
StratifyLabs/API
ca0bf670653b78da43ad416cd1c5e977c8549eeb
[ "MIT" ]
null
null
null
libraries/PrinterAPI/include/printer/JsonPrinter.hpp
StratifyLabs/API
ca0bf670653b78da43ad416cd1c5e977c8549eeb
[ "MIT" ]
1
2021-01-06T14:51:51.000Z
2021-01-06T14:51:51.000Z
// Copyright 2011-2021 Tyler Gilbert and Stratify Labs, Inc; see LICENSE.md #ifndef PRINTER_API_PRINTER_JSONPRINTER_HPP_ #define PRINTER_API_PRINTER_JSONPRINTER_HPP_ #include "var/Vector.hpp" #include "Printer.hpp" namespace printer { class JsonPrinter : public Printer { public: JsonPrinter(); private: enum class ContainerType { array, object }; using Container = ContainerAccess<ContainerType>; var::Vector<Container> m_container_list; var::Vector<Container> &container_list() { return m_container_list; } API_NO_DISCARD const var::Vector<Container> &container_list() const { return m_container_list; } // re-implemented virtual functions from Printer void print_open_object(Level level, var::StringView key) override; void print_close_object() override; void print_open_array(Level level, var::StringView key) override; void print_close_array() override { return print_close_object(); } void print(Level level, var::StringView key, var::StringView value, IsNewline is_newline) override; Container &container() { return m_container_list.back(); } API_NO_DISCARD const Container &container() const { return m_container_list.back(); } void insert_comma(); API_NO_DISCARD bool is_level_filtered() const; }; } // namespace printer #endif // PRINTER_API_PRINTER_JSONPRINTER_HPP_
28.829787
87
0.757196
[ "object", "vector" ]
345208328f90cb5a138e19a846cd3ccdf9db5811
2,585
cc
C++
workload/stat/result_collect.cc
satorikoishi/ford
ed3ccc4120c914d1b9b5464e4bdc459802a52b74
[ "Apache-2.0" ]
1
2022-02-22T05:04:45.000Z
2022-02-22T05:04:45.000Z
workload/stat/result_collect.cc
yhuacode/ford
0d966cfea8b859d69ef8c88252e841d01f134051
[ "Apache-2.0" ]
null
null
null
workload/stat/result_collect.cc
yhuacode/ford
0d966cfea8b859d69ef8c88252e841d01f134051
[ "Apache-2.0" ]
null
null
null
// Author: Ming Zhang // Copyright (c) 2021 #include "stat/result_collect.h" std::atomic<uint64_t> tx_id_generator; std::atomic<uint64_t> connected_t_num; std::mutex mux; std::vector<t_id_t> tid_vec; std::vector<double> attemp_tp_vec; std::vector<double> tp_vec; std::vector<double> medianlat_vec; std::vector<double> taillat_vec; std::vector<double> lock_durations; void CollectResult(std::string workload_name, std::string system_name) { std::ofstream of, of_detail; std::string res_file = "../../../bench_results/" + workload_name + "/result.txt"; std::string detail_res_file = "../../../bench_results/" + workload_name + "/detail_result.txt"; of.open(res_file.c_str(), std::ios::app); of_detail.open(detail_res_file.c_str(), std::ios::app); of_detail << system_name << std::endl; of_detail << "tid attemp_tp tp 50lat 99lat" << std::endl; double total_attemp_tp = 0; double total_tp = 0; double total_median = 0; double total_tail = 0; for (int i = 0; i < tid_vec.size(); i++) { of_detail << tid_vec[i] << " " << attemp_tp_vec[i] << " " << tp_vec[i] << " " << medianlat_vec[i] << " " << taillat_vec[i] << std::endl; total_attemp_tp += attemp_tp_vec[i]; total_tp += tp_vec[i]; total_median += medianlat_vec[i]; total_tail += taillat_vec[i]; } size_t thread_num = tid_vec.size(); double avg_median = total_median / thread_num; double avg_tail = total_tail / thread_num; std::sort(medianlat_vec.begin(), medianlat_vec.end()); std::sort(taillat_vec.begin(), taillat_vec.end()); of_detail << total_attemp_tp << " " << total_tp << " " << medianlat_vec[0] << " " << medianlat_vec[thread_num - 1] << " " << avg_median << " " << taillat_vec[0] << " " << taillat_vec[thread_num - 1] << " " << avg_tail << std::endl; of << system_name << " " << total_attemp_tp / 1000 << " " << total_tp / 1000 << " " << avg_median << " " << avg_tail << std::endl; of_detail << std::endl; of.close(); of_detail.close(); // Open it when testing the duration #if TEST_DURATION if (workload_name == "MICRO") { // print avg lock duration std::string file = "../../../bench_results/" + workload_name + "/avg_lock_duration.txt"; of.open(file.c_str(), std::ios::app); double total_lock_dur = 0; for (int i = 0; i < lock_durations.size(); i++) { total_lock_dur += lock_durations[i]; } of << system_name << " " << total_lock_dur / lock_durations.size() << std::endl; std::cerr << system_name << " avg_lock_dur: " << total_lock_dur / lock_durations.size() << std::endl; } #endif }
34.466667
140
0.641779
[ "vector" ]
345210b8eed4fa38e44c1d47cc62f20a8435c671
2,668
hpp
C++
Hildr.hpp
Mizugola/HildrGUI
b69a5e78174ae9af6dd132b6ae024950846cdbf6
[ "MIT" ]
1
2016-10-31T16:33:11.000Z
2016-10-31T16:33:11.000Z
Hildr.hpp
Mizugola/HildrGUI
b69a5e78174ae9af6dd132b6ae024950846cdbf6
[ "MIT" ]
null
null
null
Hildr.hpp
Mizugola/HildrGUI
b69a5e78174ae9af6dd132b6ae024950846cdbf6
[ "MIT" ]
null
null
null
#pragma once #include <iostream> #include <string> #include <future> #include <algorithm> #include <vector> #include <chrono> #include <thread> #include <map> #include <SFML/Graphics.hpp> namespace hg { class GraphicalElement; class Container; class Panel; namespace Type { enum ElementType { Element = 0x0, GraphicalElement = 0x1, Container = 0x2, Panel = 0x3, Widget = 0x4 }; } class AlreadyOwnedException : public std::exception { public: AlreadyOwnedException(std::string elementId); virtual const char* what() const throw(); }; class Size { public: Size(int width = 0, int height = 0); int width = 0; int height = 0; }; class Position { public: Position(int x = 0, int y = 0); int x = 0; int y = 0; } class Element { private: std::string id; Container* parent = nullptr; Type type = Type::Element; public: Element(std::string id); virtual std::string getID(); virtual Container* getParent(); }; class GraphicalElement : public Element { private: Size size; Position position; public: GraphicalElement(std:::string id, Position position = Position(), Size size = Size()); virtual Size getSize(); virtual void setSize(Size size); virtual Position getPosition(); virtual void setPosition(Position position); }; class Container : public GraphicalElement { private: std::map<std::string, Element*> childs; public: Container(std::string id, Position position = Position(), Size size = Size()); virtual void addChild(Element* child); template <typename T> virtual void ElementType getChild(std::string id); }; class Panel : public Container { public: Panel(std::string id, Position position = Position(), Size size = Size()); }; class Widget : public GraphicalElement { }; class Window { private: std::string title; Panel root; bool update(); void handleEvents(); friend void StartApp(); public: std::string getTitle(); void setTitle(std::string title); }; extern std::map<std::string, Window*> Containers; void StartApp(); }
22.420168
98
0.527361
[ "vector" ]
34590f9f2f8cea0ac8d7113caffd985606fc044b
11,708
hpp
C++
dakota-6.3.0.Windows.x86/include/HOPSPACK_SolveLinConstrProj.hpp
seakers/ExtUtils
b0186098063c39bd410d9decc2a765f24d631b25
[ "BSD-2-Clause" ]
null
null
null
dakota-6.3.0.Windows.x86/include/HOPSPACK_SolveLinConstrProj.hpp
seakers/ExtUtils
b0186098063c39bd410d9decc2a765f24d631b25
[ "BSD-2-Clause" ]
null
null
null
dakota-6.3.0.Windows.x86/include/HOPSPACK_SolveLinConstrProj.hpp
seakers/ExtUtils
b0186098063c39bd410d9decc2a765f24d631b25
[ "BSD-2-Clause" ]
1
2022-03-18T14:13:14.000Z
2022-03-18T14:13:14.000Z
// $Id: HOPSPACK_SolveLinConstrProj.hpp 164 2010-03-15 18:53:15Z tplante $ // $URL: https://software.sandia.gov/svn/hopspack/tags/dakota-6.3/src/src-shared/HOPSPACK_SolveLinConstrProj.hpp $ //@HEADER // ************************************************************************ // // HOPSPACK: Hybrid Optimization Parallel Search Package // Copyright 2009-2010 Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // This file is part of HOPSPACK. // // HOPSPACK 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, see http://www.gnu.org/licenses/. // // Questions? Contact Tammy Kolda (tgkolda@sandia.gov) // or Todd Plantenga (tplante@sandia.gov) // // ************************************************************************ //@HEADER /*! @file HOPSPACK_SolveLinConstrProj.hpp @brief Class declaration for HOPSPACK::SolveLinConstrProj. */ #ifndef HOPSPACK_SOLVELINCONSTRPROJ_HPP #define HOPSPACK_SOLVELINCONSTRPROJ_HPP #include "HOPSPACK_common.hpp" #include "HOPSPACK_LinConstr.hpp" #include "HOPSPACK_Matrix.hpp" #include "HOPSPACK_ProblemDef.hpp" #include "HOPSPACK_Vector.hpp" namespace HOPSPACK { //---------------------------------------------------------------------- //! Provides a method for solving the linear constraint projection problem. /*! * The goal is to find the nearest feasible point to a given point \f$ y \f$ * that satisfies all linear constraints. Mathematically: * * \f[ * \begin{array}{ccl} * \mbox{minimize} & || y - x ||_2 \\ * \mbox{s.t.} & A_{eq} x = b_{eq} * & \mbox{(linear equalities)} \\ * & A_{ineq} x >= b_{ineq} * & \mbox{(linear inequalities)} \\ * & b_{up} >= x >= b_{lo} * & \mbox{(variable bounds)} * \end{array} * \f] * * All variables are assumed continuous. * * There are many possible ways to solve the problem. The default * implementation is a standard active set method that solves equality * constrained subproblems using LAPACK dgglse. Thus, computations use * dense matrices and performance does not scale well for large numbers * of variables. Furthermore, the algorithm assumes linear independence * of the active set of constraints at the solution and all intermediate * iterates. */ //---------------------------------------------------------------------- class SolveLinConstrProj { public: //! Constructor. SolveLinConstrProj (void); //! Destructor. ~SolveLinConstrProj (void); //! Solve to project a given point onto all linear constraints. /*! * Linear equalities and inequalities are passed in cLinConstr, and * variables bounds are passed in cProbDef. * The test for constraint satisfaction is delegated to cLinConstr, which * makes use of the "Active Tolerance" configuration parameter. * * @param[in] cProbDef Problem definition, including variable bounds. * @param[in] cLinConstr Linear constraints object. * @param[in] vX The point to project, unscaled. * @param[out] vProjection The projected point, unscaled. * @return True if successful. */ bool solve (const ProblemDef & cProbDef, const LinConstr & cLinConstr, const Vector & vX, Vector & vProjection); private: //! By design, there is no copy constructor. SolveLinConstrProj (const SolveLinConstrProj &); //! By design, there is no assignment operator. SolveLinConstrProj & operator= (const SolveLinConstrProj &); //! Find an inequality feasible point (ignore equalities). /*! * Formulate a subproblem with violation variables \f$ v \f$ for all general * inequalities. Assume the initial point is already feasible with * respect to variable bounds. Equalities are ignored. * * Solve the subproblem with an active set method to minimize * \f$ || v ||_2 \f$ subject to inequalities. A simpler linear objective * \f$ \sum v_i \f$ would work, but LAPACK provides only a least squares * solver. Initialize violation variables to make the subproblem's * initial point feasible. * * The method fails if constraints are inconsistent or linearly dependent. * * @param[in] cLinConstr Linear constraints for testing feasibility. * @param[in] mMatIneqs Matrix of linear inequality constraints. * @param[in] vLoIneqs Lower bounds on cMatIneqs. * @param[in] vUpIneqs Upper bounds on cMatIneqs. * @param[in,out] vX On entry this is the initial point. * On exit this is a feasible point, assuming * the method returns true. * @return True if successful. */ bool findFeasibleIneqPoint_ (const LinConstr & cLinConstr, const Matrix & mMatIneqs, const Vector & vLoIneqs, const Vector & vUpIneqs, Vector & vX) const; //! Starting from an inequality feasible point, find the closest point to the target. /*! * Use an active set method to minimize \f$ || x_{target} - x ||_2 \f$ * subject to all constraints. Note that \f$ x \f$ must be feasible * with respect to all inequalities on entry. * The method fails if constraints are linearly dependent. * * @param[in] mMatEqs Matrix of linear equality constraints. * @param[in] vRhsEqs Right-hand side of mMatEqs. * @param[in] mMatIneqs Matrix of linear inequality constraints. * @param[in] vLoIneqs Lower bounds on cMatIneqs. * @param[in] vUpIneqs Upper bounds on cMatIneqs. * @param[in] vXtarget Target to get close to. * @param[in,out] vX On entry this is the initial point. * On exit this is an optimal point, assuming * the method returns true. * @return True if successful. */ bool findClosestPoint_ (const Matrix & mMatEqs, const Vector & vRhsEqs, const Matrix & mMatIneqs, const Vector & vLoIneqs, const Vector & vUpIneqs, const Vector & vXtarget, Vector & vX) const; //! Minimize \f$ ||c - d^T x||_2 \f$ subject to equalities and inequalities. /*! * The initial point must be feasible with respect to all inequalities. * The method can fail if constraints are linearly dependent at an iterate. * * @param[in] vC Fixed cost vector. * @param[in] vD Scaling cost vector. * @param[in] vXinit Feasible initial point. * @param[in] mMatEqs Matrix of linear equality constraints. * @param[in] vRhsEqs Right-hand side on mMatEqs. * @param[in] mMatIneqs Matrix of linear inequality constraints. * @param[in] vLoIneqs Lower bounds on cMatIneqs. * @param[in] vUpIneqs Upper bounds on cMatIneqs. * @param[out] vXsol Solution point. * @return True if successful. */ bool computeActiveSetSolution_ (const Vector & vC, const Vector & vD, const Vector & vXinit, const Matrix & mMatEqs, const Vector & vRhsEqs, const Matrix & mMatIneqs, const Vector & vLoIneqs, const Vector & vUpIneqs, Vector & vXsol) const; //! Calculate the unconstrained solution to min \f$ ||c - d^T x||_2 \f$. /*! * If a component d_i is zero, then use c_i for that variable. * * @param[in] vC Fixed cost vector. * @param[in] vD Scaling cost vector. * @param[out] vXsol Solution point. */ void calcUnconstrainedSolution_ (const Vector & vC, const Vector & vD, Vector & vXsol) const; //! Compute Lagrange multipliers for the active set. /*! * This method is called by computeActiveSetSolution_ to help solve * the constrained least squares problem. * * Multipliers are found by solving the overdetermined least squares * problem \f$ A^T \lambda = \nabla f \f$, where \f$ A \f$ is the matrix * of active constraints. * If an inequality multiplier is negative, it means the constraint * should be removed so the objective can be reduced. The method * computes all multipliers and returns the index of the most negative * multiplier for an inequality. * * @param[in] vC Fixed cost vector. * @param[in] vD Scaling cost vector. * @param[in] mMatCons Matrix of active constraints, eqs before ineqs. * @param[in] nNumEqs Number of equalities in mMatCons. * @param[in] vX Feasible point at which to compute multipliers. * @param[out] nConIndex Index of most negative inequality multiplier, * or -1 if none are negative. * @return True if successful. */ bool computeMultipliers_ (const Vector & vC, const Vector & vD, const Matrix & mMatCons, const int nNumEqs, const Vector & vX, int & nConIndex) const; //! Return true if the point roughly satisfies a set of inequalities. /*! * The feasibility tolerance in this method is somewhat loose and not * configurable. The intent is to provide a sanity check while solving * scaled subproblems. * * @param[in] vX Point to check. * @param[in] mMatIneqs Matrix of linear inequality constraints. * @param[in] vLoIneqs Lower bounds on cMatIneqs. * @param[in] vUpIneqs Upper bounds on cMatIneqs. * @return True if feasible. */ bool isIneqFeasible_ (const Vector & vX, const Matrix & mMatIneqs, const Vector & vLoIneqs, const Vector & vUpIneqs) const; //! Tolerance for assessing bad steps in computeActiveSetSolution_. double _dActiveTol; }; } //-- namespace HOPSPACK #endif //-- HOPSPACK_SOLVELINCONSTRPROJ_HPP
44.687023
114
0.5726
[ "object", "vector" ]
3459b47cf375b1a6bc5b0b96d1279cd5511a21c5
430
cc
C++
ompa.cc
bitsofcotton/OMPA
39044749cbeb5ecbcf9d34a9c82db41bd8f8b6fe
[ "BSD-3-Clause" ]
null
null
null
ompa.cc
bitsofcotton/OMPA
39044749cbeb5ecbcf9d34a9c82db41bd8f8b6fe
[ "BSD-3-Clause" ]
null
null
null
ompa.cc
bitsofcotton/OMPA
39044749cbeb5ecbcf9d34a9c82db41bd8f8b6fe
[ "BSD-3-Clause" ]
null
null
null
#include <cstdio> #include <cstring> #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <map> #include <iomanip> #include <algorithm> #include <assert.h> #include "lieonn.hh" typedef myfloat num_t; #include "ompa.hh" vector<SimpleVector<myfloat> > filterM; int main(int argc, const char* argv[]) { // if we have pre observed samples for this, we don't need to calculate them. return 0; }
18.695652
79
0.716279
[ "vector" ]
345aa1c76af6c2b855f43dd3049d0f4b74d6a142
1,132
cpp
C++
WindowsProgram/PCore.cpp
bear1704/WindowsProgramming_Portfolio
83f1d763c73d08b82291aa894ef246558fdf0198
[ "Apache-2.0" ]
null
null
null
WindowsProgram/PCore.cpp
bear1704/WindowsProgramming_Portfolio
83f1d763c73d08b82291aa894ef246558fdf0198
[ "Apache-2.0" ]
null
null
null
WindowsProgram/PCore.cpp
bear1704/WindowsProgramming_Portfolio
83f1d763c73d08b82291aa894ef246558fdf0198
[ "Apache-2.0" ]
null
null
null
#include "PCore.h" PCore::PCore() { } PCore::~PCore() { } bool PCore::Init() { return true; } bool PCore::Frame() { return true; } bool PCore::Render() { return true; } bool PCore::Release() { return true; } bool PCore::PCoreInit() { timer.Init(); PInput::GetInstance().Init(); PSoundMgr::GetInstance().Init(); return Init(); } bool PCore::PCoreFrame() { timer.Frame(); PInput::GetInstance().Frame(); PSoundMgr::GetInstance().Frame(); return Frame(); } bool PCore::PCoreRender() { timer.Frame(); PInput::GetInstance().Render(); PSoundMgr::GetInstance().Render(); return Render(); } bool PCore::PCoreRelease() { timer.Release(); PInput::GetInstance().Release(); PSoundMgr::GetInstance().Release(); return true; } void PCore::MessageProc(MSG msg) { PInput::GetInstance().MsgProc(msg); } bool PCore::Run() { PCoreInit(); MSG msg = { 0, }; while (msg.message != WM_QUIT) { if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); MessageProc(msg); } else { PCoreFrame(); PCoreRender(); } } PCoreRelease(); return true; }
11.791667
50
0.636042
[ "render" ]
345c3b6655ef61a4ed4912716547928918050253
5,214
cpp
C++
libs/fastflow/tests/ocl/testRelease.cpp
GMAP/NPB-CPP
2f77a1bce83c4efda56c4bafb555bcf9abe85dd2
[ "MIT" ]
11
2020-12-16T22:44:08.000Z
2022-03-30T00:52:58.000Z
libs/fastflow/tests/ocl/testRelease.cpp
GMAP/NPB-CPP
2f77a1bce83c4efda56c4bafb555bcf9abe85dd2
[ "MIT" ]
1
2021-04-01T09:07:52.000Z
2021-07-21T22:10:07.000Z
libs/fastflow/tests/ocl/testRelease.cpp
GMAP/NPB-CPP
2f77a1bce83c4efda56c4bafb555bcf9abe85dd2
[ "MIT" ]
3
2020-12-21T18:47:43.000Z
2021-11-20T19:48:45.000Z
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* *************************************************************************** * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * 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. * * As a special exception, you may use this file as part of a free software * library without restriction. Specifically, if other files instantiate * templates or use macros or inline functions from this file, or you compile * this file and link it with other files to produce an executable, this * file does not by itself cause the resulting executable to be covered by * the GNU General Public License. This exception does not however * invalidate any other reasons why the executable file might be covered by * the GNU General Public License. * **************************************************************************** */ /* * Author: Massimo Torquati (August 2015) * */ /* * This simple example shows how to use the "setTask" and "releaseTask" methods * when input data to the OpenCL node has a non-contiguous memory layout. * */ #if !defined(FF_OPENCL) #define FF_OPENCL #endif #include <vector> #include <iostream> #include <ff/pipeline.hpp> #include <ff/stencilReduceOCL.hpp> #include <math.h> using namespace ff; #define CHECK 1 #ifdef CHECK #include "ctest.h" #else #define NACC 1 #endif FF_OCL_MAP_ELEMFUNC(mapf, float, elem, idx, return elem + idx ); // default parameters const size_t N = 20; const size_t M = 30; const size_t streamLength = 10; struct myTask { myTask(const size_t N, const size_t M, std::vector<std::vector<float> > &A):N(N),M(M),A(A) {} myTask(const size_t N, const size_t M):N(N),M(M) {} const size_t N; const size_t M; std::vector<std::vector<float> > A; // non-contigous memory layout // std::string command; }; struct oclTask: baseOCLTask<myTask, float> { void setTask(myTask *task) { const size_t N = task->N; const size_t M = task->M; const size_t size = N * M; // allocate a local buffer of correct size buffer = new float[size]; // copy the data into the buffer for(size_t i=0;i<N;++i) for(size_t j=0;j<M;++j) buffer[i*M+j] = task->A[i][j]; // set host input and output pointers to the OpenCL device setInPtr(buffer, size); setOutPtr(buffer, size); } // this method is called when the device computation is finished void releaseTask(myTask *task) { const size_t N = task->N; const size_t M = task->M; std::vector<std::vector<float> > &A = task->A; // copy back the device output data into A for(size_t i=0;i<N;++i) for(size_t j=0;j<M;++j) A[i][j] = buffer[i*M+j]; // remove the local buffer delete [] buffer; } float *buffer; }; // first stage of the pipeline. It generates 'slen' myTask objects struct First: ff_node_t<myTask> { First(const size_t N, const size_t M, const size_t slen):N(N),M(M),slen(slen) {} myTask *svc(myTask*) { for(size_t k=0;k<slen;++k) { myTask *t = new myTask(N,M); t->A.resize(N); for(size_t i=0;i<N;++i) { t->A[i].resize(M); for(size_t j=0;j<M;++j) t->A[i][j] = k+i+j; } ff_send_out(t); } return EOS; } const size_t N,M,slen; }; // last stage of the pipeline. It simply gathers the stream elements and checks correctness. struct Last: ff_node_t<myTask> { myTask *svc(myTask *task) { #if defined(CHECK) static size_t counter = 0; bool wrong = false; const size_t N = task->N; const size_t M = task->M; const std::vector<std::vector<float> > &A = task->A; for(size_t i=0;i<N;++i) { for(size_t j=0;j<M;++j) if (A[i][j] != counter + (i+j + i*M+j)) { std::cerr << "Wrong value (" << i << ","<<j<<"), expected " << (i+j + i*M+j) << " obtained " << A[i][j] << "\n"; wrong = true; } } if (!wrong) std::cerr << "OK!\n"; else exit(1); //ctest ++counter; #endif return GO_ON; } }; int main(int argc, char * argv[]) { First first(N,M, streamLength); ff_mapOCL_1D<myTask, oclTask> mapocl(mapf); Last last; ff_Pipe<> pipe(first, mapocl, last); if (pipe.run_and_wait_end()<0) { error("pipeline"); return -1; } return 0; }
30.138728
132
0.578443
[ "vector" ]
345e61f2e91cd780bcacc02dd6f2d7e9ae2ba43a
692
cc
C++
Question/计算日期到天数转换.cc
lkimprove/Study_C
ee1153536f28e160d5daad4ddebaa547c3941ee7
[ "MIT" ]
null
null
null
Question/计算日期到天数转换.cc
lkimprove/Study_C
ee1153536f28e160d5daad4ddebaa547c3941ee7
[ "MIT" ]
null
null
null
Question/计算日期到天数转换.cc
lkimprove/Study_C
ee1153536f28e160d5daad4ddebaa547c3941ee7
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; bool IsLeapYear(int year){ if(year % 4 == 0 && year % 100 != 0){ return true; } else if(year % 400 == 0){ return true; } return false; } int main(){ vector<int> monthDay = {0, 31, 28, 31, 30, 31, 30 ,31, 31, 30, 31, 30, 31}; int year, month, day; while(cin >> year >> month >> day){ int ret = 0; for(int i = 1; i < month; i++){ if(i == 2 && IsLeapYear(year)){ ret += 1; } ret += monthDay[i]; } ret += day; cout << ret << endl; } return 0; }
18.702703
79
0.42052
[ "vector" ]
345fdee0a49da35fdbc6adae03eaefb8d7e71bee
1,858
cpp
C++
windows-client/src/Macro/MacroCollection.cpp
Drew-j-Smith/switch-controller
ad4baec93fa99553a82c0f2aa3716b9a0caea45f
[ "MIT" ]
1
2022-02-20T21:20:09.000Z
2022-02-20T21:20:09.000Z
windows-client/src/Macro/MacroCollection.cpp
Drew-j-Smith/switch-controller
ad4baec93fa99553a82c0f2aa3716b9a0caea45f
[ "MIT" ]
null
null
null
windows-client/src/Macro/MacroCollection.cpp
Drew-j-Smith/switch-controller
ad4baec93fa99553a82c0f2aa3716b9a0caea45f
[ "MIT" ]
null
null
null
#include "MacroCollection.h" MacroCollection::MacroCollection(const std::vector<std::shared_ptr<Macro>> & macros, const std::shared_ptr<DeciderCollectionBase> & deciders) { this->macros = macros; this->deciders = deciders; } MacroCollection::MacroCollection(const boost::property_tree::ptree & tree, const std::shared_ptr<DeciderCollectionBase> & deciders) { this->deciders = deciders; std::map<std::string, std::shared_ptr<Macro>> macroMap; auto deciderMap = deciders->generateMap(); for (auto macro : tree) { macros.push_back(std::make_shared<Macro>(macro.second, deciderMap)); macroMap.insert({macros.back()->getName(), macros.back()}); } for (auto macro : macros) { macro->setNextMacroLists(tree, macroMap); } } void MacroCollection::getData(unsigned char data[8]) { if(activeMacros.size()){ auto now = std::chrono::steady_clock::now(); std::vector<std::shared_ptr<Macro>> toAdd; std::vector<std::shared_ptr<Macro>> toRemove; for (auto it : activeMacros) { unsigned long long time = std::chrono::duration_cast<std::chrono::milliseconds>(now - it.second).count(); it.first->getDataframe(time, data); if (it.first->lastTime() < time){ toAdd.push_back(it.first->getNextMacro()); toRemove.push_back(it.first); } } for (auto m : toRemove) activeMacros.erase(m); for (auto m : toAdd) if (m) activeMacros.insert({m, std::chrono::steady_clock::now()}); } } void MacroCollection::activateMacros() { for(auto m : macros){ if(activeMacros.find(m) == activeMacros.end() && m->getInputEvent()->getInputValue()) { activeMacros.insert({m, std::chrono::steady_clock::now()}); } } }
35.056604
143
0.618407
[ "vector" ]
346a2cf0fe0e98d9fef3c5c9f913ab4b0da4100e
997
cpp
C++
leetcode/819.most-common-word.cpp
ANONYMOUS609/Competitive-Programming
d3753eeee24a660963f1d8911bf887c8f41f5677
[ "MIT" ]
2
2019-01-30T12:45:18.000Z
2021-05-06T19:02:51.000Z
leetcode/819.most-common-word.cpp
ANONYMOUS609/Competitive-Programming
d3753eeee24a660963f1d8911bf887c8f41f5677
[ "MIT" ]
null
null
null
leetcode/819.most-common-word.cpp
ANONYMOUS609/Competitive-Programming
d3753eeee24a660963f1d8911bf887c8f41f5677
[ "MIT" ]
3
2020-10-02T15:42:04.000Z
2022-03-27T15:14:16.000Z
/* * @lc app=leetcode id=819 lang=cpp * * [819] Most Common Word */ // @lc code=start class Solution { public: string mostCommonWord(string p, vector<string>& banned) { transform(p.begin(), p.end(),p.begin(),::tolower); string tmp=""; for(char ch: p) { if((ch>='a' and ch<='z')) { tmp += ch; } else if(ch==',' or ch==' ') { if(tmp.back()!=' ') tmp+=' '; } } // cout<<tmp; unordered_map<string, int> hm; stringstream check1(tmp); string token; while(getline(check1,token,' ')) { hm[token]++; } for(string s: banned) { hm.erase(s); } string res = ""; int deside = -1; for(auto it: hm) { if(it.second > deside) { res = it.first; deside = it.second; } } return res; } }; // @lc code=end
22.155556
61
0.414243
[ "vector", "transform" ]
346f0c767aa8a89967165b0e62a15548852c0403
84,309
cxx
C++
StRoot/StMtdQAMaker/StMtdQAMaker.cxx
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
2
2018-12-24T19:37:00.000Z
2022-02-28T06:57:20.000Z
StRoot/StMtdQAMaker/StMtdQAMaker.cxx
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
null
null
null
StRoot/StMtdQAMaker/StMtdQAMaker.cxx
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
null
null
null
#include <iostream> #include <math.h> #include <vector> #include <stdlib.h> #include <iterator> #include "TTree.h" #include "TH1F.h" #include "TH2F.h" #include "StEventTypes.h" #include "StThreeVectorF.hh" #include "PhysicalConstants.h" #include "StMemoryInfo.hh" #include "StMessMgr.h" #include "StTimer.hh" #include "StEnumerations.h" #include "StEvent.h" #include "StVertex.h" #include "StTriggerData.h" #include "StTrack.h" #include "StDcaGeometry.h" #include "StDedxPidTraits.h" #include "StTrackPidTraits.h" #include "StBTofPidTraits.h" #include "StBTofCollection.h" #include "StBTofHit.h" #include "StBTofRawHit.h" #include "StBTofHeader.h" #include "StMtdCollection.h" #include "StMtdHeader.h" #include "StMtdRawHit.h" #include "StMtdHit.h" #include "StMtdPidTraits.h" #include "StTpcDedxPidAlgorithm.h" #include "StMuDSTMaker/COMMON/StMuBTofPidTraits.h" #include "StMuDSTMaker/COMMON/StMuBTofHit.h" #include "StarClassLibrary/StParticleDefinition.hh" #include "StMuDSTMaker/COMMON/StMuDstMaker.h" #include "StMuDSTMaker/COMMON/StMuDst.h" #include "StMuDSTMaker/COMMON/StMuEvent.h" #include "StMuDSTMaker/COMMON/StMuPrimaryVertex.h" #include "StMuDSTMaker/COMMON/StMuTrack.h" #include "StMuDSTMaker/COMMON/StMuMtdCollection.h" #include "StMuDSTMaker/COMMON/StMuMtdHeader.h" #include "StMuDSTMaker/COMMON/StMuMtdRawHit.h" #include "StMuDSTMaker/COMMON/StMuMtdHit.h" #include "StMuDSTMaker/COMMON/StMuMtdPidTraits.h" #include "StMtdUtil/StMtdGeometry.h" #include "StMtdQAMaker.h" #include "tables/St_mtdModuleToQTmap_Table.h" #include "tables/St_mtdQTSlewingCorr_Table.h" #include "tables/St_mtdQTSlewingCorrPart2_Table.h" ClassImp(StMtdQAMaker) //_____________________________________________________________________________ StMtdQAMaker::StMtdQAMaker(const Char_t *name) : StMaker(name), mIsCosmic(kFALSE), mStEvent(0), mMuDst(0), mVertexMode(0), mVertexIndex(-1), mRunId(-1), mRunYear(-1), mCollisionSystem("pp"), mStartRun(0), mEndRun(999999), mTriggerData(0), mMuDstIn(kFALSE), mPrintMemory(kFALSE), mPrintCpu(kFALSE), mPrintConfig(kFALSE), mTriggerIDs(0), mApplyQTTacOffset(kFALSE), mFileQTTacOffset(""), mMaxVtxZ(100.), mMaxVtxDz(5.), mMinTrkPt(0.2), mMaxTrkPt(1e4), mMinTrkPhi(0.), mMaxTrkPhi(2*pi), mMinTrkEta(-1), mMaxTrkEta(1), mMinNHitsFit(15), mMinNHitsDedx(10), mMinFitHitsFraction(0), mMaxDca(3.), mMinNsigmaPi(-10), mMaxNsigmaPi(10), mMatchToTof(false), mMtd_qt_tac_min(80), mMtd_qt_tac_max(4096), mMtd_qt_tac_diff_range_abs(600), mHistoInit(kFALSE), mFillTree(kFALSE), fOutTreeFile(0), mOutTreeFileName(""), mQATree(NULL) { // default constructor mTrigTime[0] = -1; mTrigTime[1] = -1; for(int im=0; im<kNQTboard; im++) { for(int j=0; j<16; j++) mQTTacOffset[im][j] = 0; } memset(&mMtdData, 0, sizeof(mMtdData)); mhEventTrig = NULL; mhEventCuts = NULL; mhRunId = NULL; mhRefMult = NULL; mhgRefMult = NULL; mhVertexXY = NULL; mhVertexXZ = NULL; mhVertexYZ = NULL; mhVertexZ = NULL; mhVtxZvsVpdVzDefault = NULL; mhVtxZDiffDefault = NULL; mhVtxZvsVpdVzClosest = NULL; mhVtxZDiffClosest = NULL; mhVtxClosestIndex = NULL; mhTofStartTime = NULL; mhVpdQTadc = NULL; mhVpdQTtac = NULL; mhNTrk = NULL; mhTrkPt = NULL; mhTrkDcaVsPt = NULL; mhTrkPhiVsPt = NULL; mhTrkEtaVsPt = NULL; mhTrkPhiEta = NULL; mhTrkNHitsFitVsPt = NULL; mhTrkNHitsDedxVsPt = NULL; mhTrkDedxVsPt = NULL; mhTrkNsigmaPiVsPt = NULL; mhTrkNsigmaPiVsPhi = NULL; mhTrkNsigmaPiVsEta = NULL; mhTofMthTrkLocaly = NULL; mhTofMthTrkLocalz = NULL; mhMtdTrackProjMap = NULL; mhMtdQTAdcAll = NULL; mhMtdQTAdcMth = NULL; mhMtdQTAdcMthTof = NULL; mhMtdQTAdcMuon = NULL; mhMtdQTTacAll = NULL; mhMtdQTAdcMth = NULL; mhMtdQTAdcMthTof = NULL; mhMtdQTAdcMuon = NULL; mhMtdQTAdcVsTacAll = NULL; mhMtdQTJ2J3Diff = NULL; mhMtdVpdTacDiffMT001 = NULL; mhMtdVpdTacDiffMT001Mth = NULL; mhMtdVpdTacDiffMT001MthTof = NULL; mhMtdVpdTacDiffMT001Muon = NULL; mhMtdVpdTacDiffMT101 = NULL; mhMtdVpdTacDiffMT101Mth = NULL; mhMtdVpdTacDiffMT101MthTof= NULL; mhMtdVpdTacDiffMT101Muon = NULL; for(int i=0; i<kNQTboard; i++) { for(int j=0; j<2; j++) mhMixMtdTacSumvsMxqMtdTacSum[i][j] = NULL; } for(int j=0; j<2; j++) mhMtdTriggerTime[j] = NULL; mhMtdNRawHits = NULL; mhMtdRawHitMap = NULL; mhMtdRawHitLeTime = NULL; mhMtdRawHitTrTime = NULL; mhMtdRawHitLeNEast = NULL; mhMtdRawHitLeNWest = NULL; mhMtdRawHitTrNEast = NULL; mhMtdRawHitTrNWest = NULL; mhMtdRawHitLeNDiff = NULL; mhMtdRawHitTrNDiff = NULL; mhMtdNHits = NULL; mhMtdHitMap = NULL; mhMtdHitLeTimeDiff = NULL; mhMtdHitTotWest = NULL; mhMtdHitTotEast = NULL; mhMtdHitTrigTime = NULL; mhMtdHitTrigTimeTrkMth = NULL; mhMtdHitTrigTimeTrkMthTof= NULL; mhMtdHitTrigTimeMuon = NULL; mhMtdHitTrigTimeGoodQT = NULL; mhMtdHitTrigTimeTrig = NULL; mhMtdHitTrigTimeVsQtAdc[0]= NULL; mhMtdHitTrigTimeVsQtAdc[1]= NULL; mhMtdHitTrigTimeVsQtTac[0]= NULL; mhMtdHitTrigTimeVsQtTac[1]= NULL; mhMtdNMatchHits = NULL; mhMtdMatchHitMap = NULL; mhMtdMatchTrkPt = NULL; mhMtdMatchTrkPhiEta = NULL; mhMtdMatchDzVsChan = NULL; mhMtdMatchDzVsPtPos = NULL; mhMtdMatchDzVsPtNeg = NULL; mhMtdMatchDyVsChan = NULL; mhMtdMatchDyVsPtPos = NULL; mhMtdMatchDyVsPtNeg = NULL; mhMtdMatchDtofVsPt = NULL; mhMtdMatchMtdTofVsChan = NULL; mhMtdMatchExpTofVsChan = NULL; mhMtdMatchDtofVsChan = NULL; mhMtdMatchLocalyVsChan = NULL; mhMtdMatchLocalzVsChan = NULL; mhNQtSignal = NULL; mhNMT101Signal = NULL; mhNTF201Signal = NULL; mhMtdTrigNHits = NULL; mhMtdTrigHitMap = NULL; mhMtdTrigMthNHits = NULL; mhMtdTrigMthHitMap = NULL; } //_____________________________________________________________________________ StMtdQAMaker::~StMtdQAMaker() { // default destructor if(mQATree) delete mQATree; if(fOutTreeFile) delete fOutTreeFile; } //_____________________________________________________________________________ Int_t StMtdQAMaker::InitRun(const Int_t runNumber) { mRunYear = runNumber / 1e6 + 1999; if(!mHistoInit) { mHistoInit = true; initHistos(); readQTTacOffsetFile(); } // initialize maps memset(mModuleToQT,-1,sizeof(mModuleToQT)); memset(mModuleToQTPos,-1,sizeof(mModuleToQTPos)); memset(mQTtoModule,-1,sizeof(mQTtoModule)); // obtain maps from DB LOG_INFO << "Retrieving mtdModuleToQTmap table from database ..." << endm; TDataSet *dataset = GetDataBase("Geometry/mtd/mtdModuleToQTmap"); St_mtdModuleToQTmap *mtdModuleToQTmap = static_cast<St_mtdModuleToQTmap*>(dataset->Find("mtdModuleToQTmap")); if(!mtdModuleToQTmap) { LOG_ERROR << "No mtdModuleToQTmap table found in database" << endm; return kStErr; } mtdModuleToQTmap_st *mtdModuleToQTtable = static_cast<mtdModuleToQTmap_st*>(mtdModuleToQTmap->GetTable()); for(Int_t i=0; i<gMtdNBacklegs; i++) { for(Int_t j=0; j<gMtdNModules; j++) { Int_t index = i*5 + j; Int_t qt = mtdModuleToQTtable->qtBoardId[index]; Int_t channel = mtdModuleToQTtable->qtChannelId[index]; mModuleToQT[i][j] = qt; if(channel<0) { mModuleToQTPos[i][j] = channel; } else { if(channel%8==1) mModuleToQTPos[i][j] = 1 + channel/8 * 2; else mModuleToQTPos[i][j] = 2 + channel/8 * 2; } if(mModuleToQT[i][j]>0 && mModuleToQTPos[i][j]>0) mQTtoModule[mModuleToQT[i][j]-1][mModuleToQTPos[i][j]-1] = j + 1; } } // online slewing correction for QT board memset(mQTSlewBinEdge,-1,sizeof(mQTSlewBinEdge)); memset(mQTSlewCorr,-1,sizeof(mQTSlewCorr)); LOG_INFO << "Retrieving mtdQTSlewingCorr table from database ..." << endm; dataset = GetDataBase("Calibrations/mtd/mtdQTSlewingCorr"); St_mtdQTSlewingCorr *mtdQTSlewingCorr = static_cast<St_mtdQTSlewingCorr*>(dataset->Find("mtdQTSlewingCorr")); if(!mtdQTSlewingCorr) { LOG_ERROR << "No mtdQTSlewingCorr table found in database" << endm; return kStErr; } mtdQTSlewingCorr_st *mtdQTSlewingCorrtable = static_cast<mtdQTSlewingCorr_st*>(mtdQTSlewingCorr->GetTable()); for(int j=0; j<4; j++) { for(int i=0; i<16; i++) { for(Int_t k=0; k<8; k++) { Int_t index = j*16*8 + i*8 + k; mQTSlewBinEdge[j][i][k] = (int) mtdQTSlewingCorrtable->slewingBinEdge[index]; mQTSlewCorr[j][i][k] = (int) mtdQTSlewingCorrtable->slewingCorr[index]; } } } dataset = GetDataBase("Calibrations/mtd/mtdQTSlewingCorrPart2"); if(dataset) { St_mtdQTSlewingCorrPart2 *mtdQTSlewingCorr2 = static_cast<St_mtdQTSlewingCorrPart2*>(dataset->Find("mtdQTSlewingCorrPart2")); mtdQTSlewingCorrPart2_st *mtdQTSlewingCorrtable2 = static_cast<mtdQTSlewingCorrPart2_st*>(mtdQTSlewingCorr2->GetTable()); for(int j=0; j<4; j++) { for(int i=0; i<16; i++) { for(Int_t k=0; k<8; k++) { Int_t index = j*16*8 + i*8 + k; mQTSlewBinEdge[j+4][i][k] = (int) mtdQTSlewingCorrtable2->slewingBinEdge[index]; mQTSlewCorr[j+4][i][k] = (int) mtdQTSlewingCorrtable2->slewingCorr[index]; } } } } LOG_INFO << "===== End retrieving mtdQTSlewingCorr =====" << endm; return kStOK; } //_____________________________________________________________________________ Int_t StMtdQAMaker::Init() { return kStOK; } //_____________________________________________________________________________ Int_t StMtdQAMaker::readQTTacOffsetFile() { // Read in QT tac offset if needed if(mApplyQTTacOffset) { if(mFileQTTacOffset.Length()==0) { LOG_ERROR << "QT tac offset file not set but required!" << endm; return kStWarn; } ifstream infile; infile.open(mFileQTTacOffset.Data()); char tmp[256]; int board, chan, pedestal, gain; for(int im=0; im<kNQTboard; im++) { if(mRunYear!=2016 && im>3) continue; infile.getline(tmp,256); for(int j=0; j<16; j++) { infile >> board >> chan >> pedestal >> gain; mQTTacOffset[im][j] = pedestal; LOG_DEBUG << im << " " << j << " " << mQTTacOffset[im][j] << endm; } infile.getline(tmp,256); } } return kStOK; } //_____________________________________________________________________________ Int_t StMtdQAMaker::initHistos() { if(mRunYear<=2014) mMtd_qt_tac_min = 100; else if(mRunYear>=2017) mMtd_qt_tac_min = 150; if(mRunYear==2015) mMtd_qt_tac_diff_range_abs = 1023; mStartRun = (mRunYear-1999)*1e6; mEndRun = mStartRun + 200000; if(mPrintConfig) printConfig(); if(mFillTree) bookTree(); bookHistos(); return kStOK; } //_____________________________________________________________________________ Int_t StMtdQAMaker::Finish() { if(fOutTreeFile) { fOutTreeFile->Write(); fOutTreeFile->Close(); LOG_INFO << "StMtdQAMaker::Finish() -> write out tree in " << mOutTreeFileName.Data() << endm; } return kStOK; } //_____________________________________________________________________________ Int_t StMtdQAMaker::Make() { StTimer timer; if (mPrintMemory) StMemoryInfo::instance()->snapshot(); if (mPrintCpu) timer.start(); // reset the structure memset(&mMtdData, 0, sizeof(mMtdData)); // Check the availability of input data Int_t iret; StMuDstMaker *muDstMaker = (StMuDstMaker*) GetMaker("MuDst"); if(muDstMaker) { mMuDst = muDstMaker->muDst(); if(mMuDst) { LOG_DEBUG << "Running on MuDst ..." << endm; mMuDstIn = kTRUE; iret = processMuDst(); } else { LOG_ERROR << "No muDST is available ... "<< endm; return kStErr; } } else { mStEvent = (StEvent*) GetInputDS("StEvent"); if(mStEvent) { LOG_DEBUG << "Running on StEvent ..." << endm; mMuDstIn = kFALSE; iret = processStEvent(); } else { LOG_ERROR << "No StEvent is available ..." << endm; return kStErr; } } if(iret == kStOK) { if(mFillTree) mQATree->Fill(); fillHistos(); } if (mPrintMemory) { StMemoryInfo::instance()->snapshot(); StMemoryInfo::instance()->print(); } if (mPrintCpu) { timer.stop(); LOG_INFO << "CPU time for StMtdQAMaker::Make(): " << timer.elapsedTime() << "sec " << endm; } return kStOK; } //_____________________________________________________________________________ Int_t StMtdQAMaker::processStEvent() { // Event statistics mhEventTrig->Fill(0.5); return kStOK; } //_____________________________________________________________________________ Int_t StMtdQAMaker::processMuDst() { //cout << "New Event !" << endl; // Run statistics mRunId = mMuDst->event()->runId(); mhRunId->Fill(mRunId + 0.5); int mass_east = mMuDst->event()->runInfo().beamMassNumber(east); int mass_west = mMuDst->event()->runInfo().beamMassNumber(west); if(mass_east == mass_west) { if(mass_east == 1) mCollisionSystem = "pp"; else mCollisionSystem = "AA"; } else mCollisionSystem = "pA"; // Event statistics mhEventTrig->Fill(0.5); // select valid triggers mTriggerData = 0; Bool_t isGoodTrigger = kFALSE; Int_t nTrig = mTriggerIDs.size(); if(nTrig==0) { isGoodTrigger = kTRUE; } else { for(Int_t i=0; i<nTrig; i++) { if(mMuDst->event()->triggerIdCollection().nominal().isTrigger(mTriggerIDs[i])) { isGoodTrigger = kTRUE; break; } } } if(!isGoodTrigger) { LOG_WARN << "No valid trigger in MuDst... " << endm; return kStWarn; } mhEventTrig->Fill(1.5); //========== Select vertex ========== mVertexIndex = -1; Int_t nPrim = mMuDst->numberOfPrimaryVertices(); StMuPrimaryVertex* priVertex = NULL; mMtdData.vertexX = -999.; mMtdData.vertexY = -999.; mMtdData.vertexZ = -999.; if(mIsCosmic) { if(nPrim>=1) { mVertexIndex = 0; priVertex = mMuDst->primaryVertex(mVertexIndex); if(priVertex) { StThreeVectorF verPos = priVertex->position(); mMtdData.vertexX = verPos.x(); mMtdData.vertexY = verPos.y(); mMtdData.vertexZ = verPos.z(); } } } else { if(nPrim == 0) { LOG_WARN << "No reconstructed vertex in MuDst... " << endm; return kStWarn; } // start time & VPD vz StBTofHeader *tofHeader = mMuDst->btofHeader(); Double_t tStart = -999; Double_t vpdz = -999; if(tofHeader) { tStart = tofHeader->tStart(); vpdz = tofHeader->vpdVz(); } mMtdData.tofStartTime = tStart; mMtdData.vpdVz = vpdz; Int_t index = -1; if(tofHeader) { // constrain vertex with VPD Double_t min_dz = 999; for(Int_t i=0; i<nPrim; i++) { StMuPrimaryVertex *vertex = mMuDst->primaryVertex(i); double ranking = vertex->ranking(); if(mCollisionSystem=="pp" && ranking<0) continue; Double_t dz = fabs(vertex->position().z()-mMtdData.vpdVz); if(dz<min_dz) { min_dz = dz; index = i; } } mhVtxClosestIndex->Fill(index); double default_z = mMuDst->primaryVertex(0)->position().z(); mhVtxZvsVpdVzDefault->Fill(default_z, mMtdData.vpdVz); mhVtxZDiffDefault->Fill(default_z - mMtdData.vpdVz); if(index>-1) { double cloest_z = mMuDst->primaryVertex(index)->position().z(); mhVtxZvsVpdVzClosest->Fill(cloest_z, mMtdData.vpdVz); mhVtxZDiffClosest->Fill(cloest_z - mMtdData.vpdVz); } } if(mVertexMode==0) mVertexIndex = 0; else if(mVertexMode==1) mVertexIndex = index; else { LOG_WARN << "No vertex mode is set. Use default vertex!" << endm; mVertexIndex = 0; } if(mVertexIndex<0) return kStWarn; priVertex = mMuDst->primaryVertex(mVertexIndex); if(!priVertex) return kStWarn; StThreeVectorF verPos = priVertex->position(); mMtdData.vertexX = verPos.x(); mMtdData.vertexY = verPos.y(); mMtdData.vertexZ = verPos.z(); if(TMath::Abs(mMtdData.vertexZ)>mMaxVtxZ) return kStWarn; if(fabs(mMtdData.vpdVz-mMtdData.vertexZ)>mMaxVtxDz) return kStWarn; } mhEventTrig->Fill(2.5); //==================================== mMtdData.runId = mRunId; mMtdData.eventId = mMuDst->event()->eventId(); mMtdData.refMult = mMuDst->event()->refMult(mVertexIndex); mMtdData.gRefMult = mMuDst->event()->grefmult(mVertexIndex); // collect trigger information Int_t nTrigger = 0; for(UInt_t i=0; i<mTriggerIDs.size(); i++) { if(mMuDst->event()->triggerIdCollection().nominal().isTrigger(mTriggerIDs[i])) { mMtdData.triggerId[nTrigger] = mTriggerIDs[i]; mhEventTrig->Fill(3.5+i); nTrigger++; } } mMtdData.nTrigger = nTrigger; mTriggerData = const_cast<StTriggerData*>(mMuDst->event()->triggerData()); if(mTriggerData) processTriggerData(mTriggerData); // MTD trigger time StMuMtdHeader *muMtdHeader = mMuDst->mtdHeader(); if(muMtdHeader) { mMtdData.mtdTriggerTime[0] = 25.*(muMtdHeader->triggerTime(1)&0xfff); mMtdData.mtdTriggerTime[1] = 25.*(muMtdHeader->triggerTime(2)&0xfff); } else { mMtdData.mtdTriggerTime[0] = -99999; mMtdData.mtdTriggerTime[1] = -99999; } for(Int_t i=0; i<2; i++) mTrigTime[i] = mMtdData.mtdTriggerTime[i]; // MTD raw hits Int_t nMtdRawHits = mMuDst->numberOfBMTDRawHit(); LOG_DEBUG << nMtdRawHits << " raw MTD hits" << endm; for(Int_t i=0; i<nMtdRawHits; i++) { StMuMtdRawHit *rawHit = (StMuMtdRawHit*)mMuDst->mtdRawHit(i); if(!rawHit) continue; Int_t backleg = rawHit->backleg(); if(backleg<1 || backleg>30) continue; mMtdData.mtdRawHitFlag[i] = rawHit->flag(); mMtdData.mtdRawHitBackleg[i] = backleg; mMtdData.mtdRawHitChan[i] = rawHit->channel(); mMtdData.mtdRawHitModule[i] = (rawHit->channel()-1)/gMtdNChannels+1; mMtdData.mtdRawHitTdc[i] = rawHit->tdc()*gMtdConvertTdcToNs; Double_t tDiff = mMtdData.mtdRawHitTdc[i] - mMtdData.mtdTriggerTime[rawHit->fiberId()]; while(tDiff<0) tDiff += 51200; mMtdData.mtdRawHitTimdDiff[i] = tDiff; } mMtdData.nMtdRawHits = nMtdRawHits; // Tracks Int_t goodTrack = 0; Double_t projPhi = -999, projZ = -999; Int_t backleg = -1, module = -1, cell = -1; map<Short_t, UShort_t> primaryIndex; Int_t nPrimTrks = mMuDst->numberOfPrimaryTracks(); for(Int_t i=0; i<nPrimTrks; i++) { StMuTrack* pTrack = mMuDst->primaryTracks(i); if(!pTrack) continue; primaryIndex[pTrack->id()] = i; if(!isValidTrack(pTrack)) continue; mMtdData.trkPt[goodTrack] = pTrack->pt(); mMtdData.trkEta[goodTrack] = pTrack->eta(); mMtdData.trkPhi[goodTrack] = rotatePhi(pTrack->phi()); mMtdData.trkDca[goodTrack] = pTrack->dcaGlobal().mag(); mMtdData.trkNHitsFit[goodTrack] = pTrack->nHitsFit(kTpcId); mMtdData.trkNHitsDedx[goodTrack] = pTrack->nHitsDedx(); mMtdData.trkDedx[goodTrack] = pTrack->dEdx() * 1e6; mMtdData.trkNsigmaPi[goodTrack] = pTrack->nSigmaPion(); // TOF matching mMtdData.isTrkTofMatched[goodTrack] = kFALSE; const StMuBTofHit *tofHit = pTrack->tofHit(); if(tofHit) { const StMuBTofPidTraits &tofPid = pTrack->btofPidTraits(); mMtdData.isTrkTofMatched[goodTrack] = kTRUE; mMtdData.trkMthTofTray[goodTrack] = tofHit->tray(); mMtdData.trkMthTofModule[goodTrack] = tofHit->module(); mMtdData.trkMthTofCell[goodTrack] = tofHit->cell(); mMtdData.trkMthTofLocaly[goodTrack] = tofPid.yLocal(); mMtdData.trkMthTofLocalz[goodTrack] = tofPid.zLocal(); LOG_DEBUG << "TOF tray = " << tofHit->tray() << ", module = " << tofHit->module() << ", cell = " << tofHit->cell() << ", local y = " << tofPid.yLocal() << ", local z = " << tofPid.zLocal() << endm; } // MTD matching mMtdData.isTrkProjected[goodTrack] = kFALSE; mMtdData.isTrkMtdMatched[goodTrack] = kFALSE; StPhysicalHelixD gHelix = pTrack->outerHelix(); if(propagateHelixToMtd(gHelix, projPhi, projZ)) { getMtdPosFromProj(projPhi, projZ, backleg, module, cell); mMtdData.isTrkProjected[goodTrack] = kTRUE; mMtdData.trkProjPhi[goodTrack] = projPhi; mMtdData.trkProjZ[goodTrack] = projZ; mMtdData.trkProjBackleg[goodTrack] = backleg; mMtdData.trkProjModule[goodTrack] = module; mMtdData.trkProjChannel[goodTrack] = cell; Int_t iMtd = pTrack->index2MtdHit(); backleg = -1, module = -1, cell = -1; if(iMtd>-1) { mMtdData.isTrkMtdMatched[goodTrack] = kTRUE; StMuMtdHit *hit = mMuDst->mtdHit(iMtd); if(hit) { backleg = hit->backleg(); module = hit->module(); cell = hit->cell(); LOG_DEBUG << "Track " << i << " is matched to MTD hit " << iMtd << endm; } } mMtdData.trkMthBackleg[goodTrack] = backleg; mMtdData.trkMthModule[goodTrack] = module; mMtdData.trkMthChannel[goodTrack] = cell; } goodTrack++; } mMtdData.nGoodTrack = goodTrack; // MTD hits Int_t nMtdHits = mMuDst->numberOfMTDHit(); Int_t nMatchMtdHit = 0; LOG_DEBUG << "# of mtd hits: " << nMtdHits << endm; for(Int_t i=0; i<nMtdHits; i++) { StMuMtdHit *hit = mMuDst->mtdHit(i); if(!hit) continue; Int_t backleg = hit->backleg(); if(backleg<1 || backleg>30) continue; mMtdData.mtdHitBackleg[i] = backleg; mMtdData.mtdHitModule[i] = hit->module(); mMtdData.mtdHitChan[i] = hit->cell(); mMtdData.mtdHitLeTimeWest[i] = hit->leadingEdgeTime().first; mMtdData.mtdHitLeTimeEast[i] = hit->leadingEdgeTime().second; mMtdData.mtdHitTotWest[i] = hit->tot().first; mMtdData.mtdHitTotEast[i] = hit->tot().second; Int_t tHub = getMtdHitTHUB(backleg); Double_t tDiff = (mMtdData.mtdHitLeTimeWest[i]+mMtdData.mtdHitLeTimeEast[i])/2 - mMtdData.mtdTriggerTime[tHub-1]; while(tDiff<0) tDiff += 51200; mMtdData.mtdHitTrigTime[i] = tDiff; mMtdData.mtdHitPhi[i] = getMtdHitGlobalPhi(hit); mMtdData.mtdHitZ[i] = getMtdHitGlobalZ(hit); // check if the hit fires the MTD trigger mMtdData.isMtdTrig[i] = kFALSE; int qt = mModuleToQT[backleg-1][hit->module()-1]; int qt_pos = mModuleToQTPos[backleg-1][hit->module()-1]; if(qt_pos==mTrigQTpos[qt-1][0] || qt_pos==mTrigQTpos[qt-1][1]) mMtdData.isMtdTrig[i] = kTRUE; // check if the hit matches to a TPC track mMtdData.isMatched[i] = kFALSE; Short_t trackId = hit->associatedTrackKey(); if(trackId<1) continue; Int_t index = (primaryIndex.find(trackId)!=primaryIndex.end()) ? primaryIndex.find(trackId)->second : -1; if(index<0) continue; StMuTrack *pTrack = mMuDst->primaryTracks(index); if(!pTrack || !isValidTrack(pTrack) || pTrack->vertexIndex()!=mVertexIndex) continue; mMtdData.isMatched[i] = kTRUE; StThreeVectorF trkMom = pTrack->momentum(); const StMuMtdPidTraits mtdPid = pTrack->mtdPidTraits(); StThreeVectorF gPos = mtdPid.position(); mMtdData.mtdMatchTrkPathLength[i] = mtdPid.pathLength(); mMtdData.mtdMatchTrkTof[i] = mtdPid.timeOfFlight(); mMtdData.mtdMatchTrkExpTof[i] = mtdPid.expTimeOfFlight(); mMtdData.mtdMatchTrkLocaly[i] = mtdPid.yLocal(); mMtdData.mtdMatchTrkLocalz[i] = mtdPid.zLocal(); mMtdData.mtdMatchTrkDeltay[i] = mtdPid.deltaY(); mMtdData.mtdMatchTrkDeltaz[i] = mtdPid.deltaZ(); mMtdData.mtdMatchTrkProjPhi[i] = rotatePhi(gPos.phi()); mMtdData.mtdMatchTrkProjZ[i] = gPos.z(); mMtdData.mtdMatchTrkPt[i] = trkMom.perp(); mMtdData.mtdMatchTrkDca[i] = pTrack->dcaGlobal().mag(); mMtdData.mtdMatchTrCharge[i] = pTrack->charge(); mMtdData.mtdMatchTrkEta[i] = trkMom.pseudoRapidity(); mMtdData.mtdMatchTrkPhi[i] = rotatePhi(trkMom.phi()); mMtdData.mtdMatchTrkNsigmaPi[i] = pTrack->nSigmaPion(); mMtdData.mtdMatchTrkTofHit[i] = pTrack->tofHit() ? true: false; nMatchMtdHit++; LOG_DEBUG << "MTD hit " << i << ", and is matched to track " << index << endm; } mMtdData.nMtdHits = nMtdHits; mMtdData.nMatchMtdHits = nMatchMtdHit; return kStOK; } //_____________________________________________________________________________ void StMtdQAMaker::processTriggerData(StTriggerData *trigData) { if(!trigData) return; Int_t pre = trigData->numberOfPreXing(); Int_t post = trigData->numberOfPostXing(); Int_t prepost = pre + post + 1; mMtdData.pre = pre; mMtdData.post = post; mMtdData.prepost = prepost; // VPD tac information const Int_t ip = 0; mMtdData.vpdTacSum = trigData->vpdEarliestTDCHighThr(east,ip)+trigData->vpdEarliestTDCHighThr(west,ip); for(Int_t i=0; i<kMaxVpdChan/4; i++) { mMtdData.vpdHi[i/8*8+i] = trigData->vpdADCHighThr(east,i+1,ip); mMtdData.vpdHi[i/8*8+8+i] = trigData->vpdTDCHighThr(east,i+1,ip); mMtdData.vpdHi[i/8*8+32+i] = trigData->vpdADCHighThr(west,i+1,ip); mMtdData.vpdHi[i/8*8+40+i] = trigData->vpdTDCHighThr(west,i+1,ip); } // MTD QT information for(Int_t i=0; i<kMaxMtdQTchan; i++) { Int_t type = (i/4)%2; if(mRunYear<=2015) { if(type==1) { mMtdData.mtdQTtac[0][i-i/4*2-2] = trigData->mtdAtAddress(i,0); mMtdData.mtdQTtac[1][i-i/4*2-2] = trigData->mtdgemAtAddress(i,0); mMtdData.mtdQTtac[2][i-i/4*2-2] = trigData->mtd3AtAddress(i,0); mMtdData.mtdQTtac[3][i-i/4*2-2] = trigData->mtd4AtAddress(i,0); } else { mMtdData.mtdQTadc[0][i-i/4*2] = trigData->mtdAtAddress(i,0); mMtdData.mtdQTadc[1][i-i/4*2] = trigData->mtdgemAtAddress(i,0); mMtdData.mtdQTadc[2][i-i/4*2] = trigData->mtd3AtAddress(i,0); mMtdData.mtdQTadc[3][i-i/4*2] = trigData->mtd4AtAddress(i,0); } } else { for(int im=0; im<kNQTboard; im++) { if(mRunYear!=2016 && im>=4) continue; if(type==0) mMtdData.mtdQTadc[im][i-i/4*2] = trigData->mtdQtAtCh(im+1,i,0); else mMtdData.mtdQTtac[im][i-i/4*2-2] = trigData->mtdQtAtCh(im+1,i,0); } } } UShort_t mxq_mtdtacsum[kNQTboard][2]; for(int im=0; im<kNQTboard; im++) { for(int j=0; j<kMaxMtdQTchan/4; j++) { mMtdData.mtdQTtacSum[im][j] = 0; } for(int j=0; j<2; j++) { mMtdData.mtdQThigh2Pos[im][j] = -1; mxq_mtdtacsum[im][j] = 0; } } Int_t j[2], a[2]; for(Int_t im=0; im<kNQTboard; im++) { for(Int_t i=0; i<8; i++) { if(mRunYear!=2016 && im>=4) continue; if(mRunYear==2016 && i%2==0) continue; for(Int_t k=0; k<2; k++) { j[k] = mMtdData.mtdQTtac[im][i*2+k]; a[k] = mMtdData.mtdQTadc[im][i*2+k]; // TAC offset if(mApplyQTTacOffset) { j[k] -= mQTTacOffset[im][i*2+k]; if(j[k]<0) j[k] = 0; } // slewing correction int slew_bin = -1; if(a[k]>=0 && a[k]<=mQTSlewBinEdge[im][i*2+k][0]) slew_bin = 0; else { for(int l=1; l<8; l++) { if(a[k]>mQTSlewBinEdge[im][i*2+k][l-1] && a[k]<=mQTSlewBinEdge[im][i*2+k][l]) { slew_bin = l; break; } } } if(slew_bin>=0) j[k] += mQTSlewCorr[im][i*2+k][slew_bin]; } if(j[0]<mMtd_qt_tac_min || j[0]>mMtd_qt_tac_max || j[1]<mMtd_qt_tac_min || j[1]>mMtd_qt_tac_max || TMath::Abs(j[0]-j[1])>mMtd_qt_tac_diff_range_abs) continue; // position correction int module = mQTtoModule[im][i]; Int_t sumTac = int( j[0] + j[1] + abs(module-3)*1./8 * (j[0]-j[1]) ); mMtdData.mtdQTtacSum[im][i] = sumTac; if(mxq_mtdtacsum[im][0] < sumTac) { mxq_mtdtacsum[im][1] = mxq_mtdtacsum[im][0]; mxq_mtdtacsum[im][0] = sumTac; mMtdData.mtdQThigh2Pos[im][1] = mMtdData.mtdQThigh2Pos[im][0]; mMtdData.mtdQThigh2Pos[im][0] = i+1; } else if (mxq_mtdtacsum[im][1] < sumTac) { mxq_mtdtacsum[im][1] = sumTac; mMtdData.mtdQThigh2Pos[im][1] = i+1; } int bin = 0; if(mRunYear!=2016) bin = im*8+i+1; else bin = im*4+i/2+1; mhMtdQTJ2J3Diff->Fill(bin,j[1]-j[0]); } } // MTD MIX trigger information for(Int_t im=0; im<kNQTboard; im++) { if(mRunYear!=2016 && im>=4) continue; int idx = 0; if(mRunYear == 2016) idx = im/2*3 + im%2*16; else idx = im*3; mMtdData.mixMtdTacSum[im][0] = (trigData->mtdDsmAtCh(idx,ip)) + ((trigData->mtdDsmAtCh(idx+1,ip)&0x3)<<8); mMtdData.mixMtdTacSum[im][1] = (trigData->mtdDsmAtCh(idx+1,ip)>>4) + ((trigData->mtdDsmAtCh(idx+2,ip)&0x3f)<<4); } // TF201 for(int im=0; im<kNQTboard; im++) { for(int j=0; j<2; j++) { mTrigQTpos[im][j] = -1; } } mMtdData.TF201Bit = trigData->dsmTF201Ch(0); mMtdData.TF201Bit2 = 0; if(mRunYear==2016) mMtdData.TF201Bit2 = trigData->dsmTF201Ch(6); for(Int_t i = 0; i < 4; i++) { for(Int_t j=0; j<2; j++) { if(mRunYear==2016) { if((mMtdData.TF201Bit>>(i*2+j+4))&0x1) { int qt = i*2; mTrigQTpos[qt][j] = mMtdData.mtdQThigh2Pos[qt][j]; } if((mMtdData.TF201Bit2>>(i*2+j+4))&0x1) { int qt = i*2+1; mTrigQTpos[qt][j] = mMtdData.mtdQThigh2Pos[qt][j]; } } else { if((mMtdData.TF201Bit>>(i*2+j+4))&0x1) { mTrigQTpos[i][j] = mMtdData.mtdQThigh2Pos[i][j]; } } } } } //_____________________________________________________________________________ void StMtdQAMaker::fillHistos() { // event mhRefMult->Fill(mMtdData.refMult); mhgRefMult->Fill(mMtdData.gRefMult); // vertex mhVertexZ->Fill(mMtdData.vertexZ); mhVertexXY->Fill(mMtdData.vertexX,mMtdData.vertexY); mhVertexXZ->Fill(mMtdData.vertexZ,mMtdData.vertexX); mhVertexYZ->Fill(mMtdData.vertexZ,mMtdData.vertexY); // TOF mhTofStartTime->Fill(mMtdData.tofStartTime); // VPD for(Int_t i=0; i<kMaxVpdChan; i++) { Int_t type = (i/8)%2; if(type==0) mhVpdQTadc->Fill(i+1,mMtdData.vpdHi[i]); else mhVpdQTtac->Fill(i+1,mMtdData.vpdHi[i]); } // MTD trigger Int_t vpdTacSum = mMtdData.vpdTacSum; Int_t nQTsignal = 0; for(Int_t im=0; im<kNQTboard; im++) { for(Int_t i=0; i<8; i++) { if(mRunYear!=2016 && im>=4) continue; if(mRunYear==2016 && i%2==0) continue; for(Int_t k=0; k<2; k++) { int index = 0; if(mRunYear!=2016) index = im*16 + i*2 + k + 1; else index = im*8 + (i/2)*2 + k + 1; if(mMtdData.mtdQTtac[im][i*2+k]>mMtd_qt_tac_min) { mhMtdQTAdcAll->Fill(index,mMtdData.mtdQTadc[im][i*2+k]); mhMtdQTTacAll->Fill(index,mMtdData.mtdQTtac[im][i*2+k]); } mhMtdQTAdcVsTacAll->Fill(mMtdData.mtdQTtac[im][i*2+k],mMtdData.mtdQTadc[im][i*2+k]); } Int_t mtdTacSum = mMtdData.mtdQTtacSum[im][i]; int bin = 0; if(mRunYear!=2016) bin = im*8+i+1; else bin = im*4+i/2+1; if(mtdTacSum>0) { nQTsignal++; mhMtdVpdTacDiffMT001->Fill(bin,mtdTacSum-vpdTacSum); } } } mhNQtSignal->Fill(nQTsignal); Int_t nMT101signal = 0; for(Int_t im=0; im<kNQTboard; im++) { if(mRunYear!=2016 && im>=4) continue; for(Int_t j=0; j<2; j++) { Int_t mix_tacSum = mMtdData.mixMtdTacSum[im][j]; if(mix_tacSum>0) { nMT101signal++; Int_t mxq_tacPos = mMtdData.mtdQThigh2Pos[im][j]; Int_t mxq_tacSum = mMtdData.mtdQTtacSum[im][mxq_tacPos-1]; mhMixMtdTacSumvsMxqMtdTacSum[im][j]->Fill(mxq_tacSum/8,mix_tacSum); int bin = 0; if(mRunYear!=2016) bin = im*8+mxq_tacPos; else bin = im*4+mxq_tacPos/2; mhMtdVpdTacDiffMT101->Fill(bin,mix_tacSum-vpdTacSum/8+1024); } } } mhNMT101Signal->Fill(nMT101signal); Int_t nTF201signal = 0; for(int im=0; im<kNQTboard; im++) { for(int j=0; j<2; j++) { if(mTrigQTpos[im][j]>0) nTF201signal++; } } mhNTF201Signal->Fill(nTF201signal); // TPC tracks int nGoodTracks = mMtdData.nGoodTrack; mhNTrk->Fill(nGoodTracks); for(int i=0; i<nGoodTracks; i++) { double pt = mMtdData.trkPt[i]; mhTrkPt ->Fill(pt); mhTrkDcaVsPt ->Fill(pt, mMtdData.trkDca[i]); mhTrkPhiVsPt ->Fill(pt, mMtdData.trkPhi[i]); mhTrkEtaVsPt ->Fill(pt, mMtdData.trkEta[i]); mhTrkNHitsFitVsPt ->Fill(pt, mMtdData.trkNHitsFit[i]); mhTrkNHitsDedxVsPt->Fill(pt, mMtdData.trkNHitsDedx[i]); mhTrkDedxVsPt ->Fill(pt, mMtdData.trkDedx[i]); mhTrkNsigmaPiVsPt ->Fill(pt, mMtdData.trkNsigmaPi[i]); if(pt>1) { mhTrkPhiEta ->Fill(mMtdData.trkEta[i], mMtdData.trkPhi[i]); mhTrkNsigmaPiVsPhi->Fill(mMtdData.trkPhi[i], mMtdData.trkNsigmaPi[i]); mhTrkNsigmaPiVsEta->Fill(mMtdData.trkEta[i], mMtdData.trkNsigmaPi[i]); } if(mMtdData.isTrkTofMatched[i]) { Int_t tofTray = mMtdData.trkMthTofTray[i]; Int_t tofModule = mMtdData.trkMthTofModule[i]; if(tofTray>60 && tofTray<=120) tofModule += 32; mhTofMthTrkLocaly->Fill(tofTray,mMtdData.trkMthTofLocaly[i]); mhTofMthTrkLocalz->Fill(tofModule,mMtdData.trkMthTofLocalz[i]); } Int_t backleg = mMtdData.trkProjBackleg[i]; Int_t module = mMtdData.trkProjModule[i]; Int_t cell = mMtdData.trkProjChannel[i]; if(backleg>0 && backleg<=30 && module>=1 && module<=5 && cell>=0 && cell<=11) { mhMtdTrackProjMap->Fill(backleg, (module-1)*12+cell); } } // MTD raw hits mhMtdTriggerTime[0]->Fill(mMtdData.mtdTriggerTime[0]); mhMtdTriggerTime[1]->Fill(mMtdData.mtdTriggerTime[1]); Int_t nMtdRawHits = mMtdData.nMtdRawHits; mhMtdNRawHits->Fill(nMtdRawHits); Int_t nDiffLe[kNTotalCells] = {0}; Int_t nDiffTr[kNTotalCells] = {0}; for(Int_t i=0; i<nMtdRawHits; i++) { Int_t backleg = (Int_t)mMtdData.mtdRawHitBackleg[i]; if(backleg<1 || backleg>30) continue; Int_t gChan = (backleg-1)*120 + mMtdData.mtdRawHitChan[i]; mhMtdRawHitMap->Fill(backleg,mMtdData.mtdRawHitChan[i]); Int_t flag = (Int_t)mMtdData.mtdRawHitFlag[i]; if(flag>0) mhMtdRawHitLeTime->Fill(gChan,mMtdData.mtdRawHitTdc[i]); else mhMtdRawHitTrTime->Fill(gChan,mMtdData.mtdRawHitTdc[i]); Int_t localChan = mMtdData.mtdRawHitChan[i] - (mMtdData.mtdRawHitModule[i]-1) * 24; Int_t gCell = (backleg-1)*60 + (mMtdData.mtdRawHitModule[i]-1)*12 + localChan; if(localChan <= 12) { if(flag>0) { mhMtdRawHitLeNWest->Fill(gCell); nDiffLe[gCell-1]++; } else { mhMtdRawHitTrNWest->Fill(gCell); nDiffTr[gCell-1]++; } } else if (localChan > 12 && localChan <= 24) { gCell -= 12; if(flag>0) { mhMtdRawHitLeNEast->Fill(gCell); nDiffLe[gCell-1]--; } else { mhMtdRawHitTrNEast->Fill(gCell); nDiffTr[gCell-1]--; } } else { LOG_WARN << "Weird local channel number: " << localChan << " from global channel " << (Int_t)mMtdData.mtdRawHitChan[i] << " and module " << (Int_t)mMtdData.mtdRawHitModule[i] << endm; } } for(Int_t i=0; i<kNTotalCells; i++) { mhMtdRawHitLeNDiff->Fill(i+1,nDiffLe[i]); mhMtdRawHitTrNDiff->Fill(i+1,nDiffTr[i]); } LOG_DEBUG << "+++++ New event +++++\n" << endm; // MTD hits int nMtdHits = mMtdData.nMtdHits; int nTrigMtdHit = 0, nTrigMtdHitMth = 0; mhMtdNHits->Fill(nMtdHits); mhMtdNMatchHits->Fill(mMtdData.nMatchMtdHits); for(Int_t i=0; i<nMtdHits; i++) { Int_t backleg = mMtdData.mtdHitBackleg[i]; Int_t module = mMtdData.mtdHitModule[i]; Int_t lChan = (module-1)*12+mMtdData.mtdHitChan[i]; Int_t gChan = (backleg-1)*60 + lChan; Int_t qt = mModuleToQT[backleg-1][module-1]; Int_t pos = mModuleToQTPos[backleg-1][module-1]; double trigTime = mMtdData.mtdHitTrigTime[i]; bool isMatched = mMtdData.isMatched[i]; bool isTrig = mMtdData.isMtdTrig[i]; double dz = mMtdData.mtdMatchTrkDeltaz[i]; double dy = mMtdData.mtdMatchTrkDeltay[i]; double dtof = mMtdData.mtdMatchTrkTof[i]-mMtdData.mtdMatchTrkExpTof[i]; double nsigPi = mMtdData.mtdMatchTrkNsigmaPi[i]; double dca = mMtdData.mtdMatchTrkDca[i]; bool isMthTof = (isMatched && mMtdData.mtdMatchTrkTofHit[i]); bool isMuon = false; if(isMatched == 1 && fabs(dca) < 1 && fabs(dz) < 20 && fabs(dy) < 20 && nsigPi > -1 && nsigPi < 3 && dtof < 1) { isMuon = true; } mhMtdHitMap ->Fill(backleg,lChan); mhMtdHitLeTimeDiff->Fill(gChan,mMtdData.mtdHitLeTimeEast[i]-mMtdData.mtdHitLeTimeWest[i]); mhMtdHitTotWest ->Fill(gChan,mMtdData.mtdHitTotWest[i]); mhMtdHitTotEast ->Fill(gChan,mMtdData.mtdHitTotEast[i]); mhMtdHitTrigTime ->Fill(gChan,mMtdData.mtdHitTrigTime[i]); if(isMatched) mhMtdHitTrigTimeTrkMth->Fill(gChan,trigTime); if(isMthTof) mhMtdHitTrigTimeTrkMthTof->Fill(gChan,trigTime); if(isMuon) mhMtdHitTrigTimeMuon->Fill(gChan,trigTime); if(isTrig==1) mhMtdHitTrigTimeTrig->Fill(gChan,trigTime); if(qt>=1 && qt<=kNQTboard && pos>=1 && pos<=8) { Int_t tHub = getMtdHitTHUB(backleg); double mtdTime[2]; mtdTime[0] = mMtdData.mtdHitLeTimeEast[i]-mMtdData.mtdTriggerTime[tHub-1]; if(mtdTime[0]<0) mtdTime[0] += 51200; mtdTime[1] = mMtdData.mtdHitLeTimeWest[i]-mMtdData.mtdTriggerTime[tHub-1]; if(mtdTime[1]<0) mtdTime[1] += 51200; for(int k=0; k<2; k++) { if(module<4) { if(mMtdData.mtdQTtac[(qt-1)][(pos-1)*2+k]>mMtd_qt_tac_min) { mhMtdHitTrigTimeVsQtAdc[k]->Fill(mMtdData.mtdQTadc[(qt-1)][(pos-1)*2+k], mtdTime[k]); mhMtdHitTrigTimeVsQtTac[k]->Fill(mMtdData.mtdQTtac[(qt-1)][(pos-1)*2+k], mtdTime[k]); } } else { if(mMtdData.mtdQTtac[(qt-1)][(pos-1)*2+1-k]>mMtd_qt_tac_min) { mhMtdHitTrigTimeVsQtAdc[k]->Fill(mMtdData.mtdQTadc[(qt-1)][(pos-1)*2+1-k], mtdTime[k]); mhMtdHitTrigTimeVsQtTac[k]->Fill(mMtdData.mtdQTtac[(qt-1)][(pos-1)*2+1-k], mtdTime[k]); } } } if(mMtdData.mtdQTadc[(qt-1)][(pos-1)*2]>100 && mMtdData.mtdQTadc[(qt-1)][(pos-1)*2+1]>100 && mMtdData.mtdQTtac[(qt-1)][(pos-1)*2]>mMtd_qt_tac_min && mMtdData.mtdQTtac[(qt-1)][(pos-1)*2+1]>mMtd_qt_tac_min) { mhMtdHitTrigTimeGoodQT->Fill(gChan,trigTime); } } if(isMatched == 1) { double trkPt = mMtdData.mtdMatchTrkPt[i]; int charge = mMtdData.mtdMatchTrCharge[i]; mhMtdMatchHitMap ->Fill(backleg,lChan); mhMtdMatchTrkPt ->Fill(trkPt); mhMtdMatchTrkPhiEta ->Fill(mMtdData.mtdMatchTrkEta[i],mMtdData.mtdMatchTrkPhi[i]); mhMtdMatchDzVsChan ->Fill(gChan, dz); mhMtdMatchDyVsChan ->Fill(gChan, dy); mhMtdMatchDtofVsPt ->Fill(trkPt,dtof); mhMtdMatchMtdTofVsChan ->Fill(gChan, mMtdData.mtdMatchTrkTof[i]); mhMtdMatchExpTofVsChan ->Fill(gChan, mMtdData.mtdMatchTrkExpTof[i]); mhMtdMatchDtofVsChan ->Fill(gChan,dtof); mhMtdMatchLocalyVsChan ->Fill(gChan,mMtdData.mtdMatchTrkLocaly[i]); mhMtdMatchLocalzVsChan ->Fill(gChan,mMtdData.mtdMatchTrkLocalz[i]); if(charge>0) mhMtdMatchDzVsPtPos->Fill(trkPt,dz); else mhMtdMatchDzVsPtNeg->Fill(trkPt,dz); if(charge>0) mhMtdMatchDyVsPtPos->Fill(trkPt,dy); else mhMtdMatchDyVsPtNeg->Fill(trkPt,dy); if(qt>=1 && qt<=kNQTboard && pos>=1 && pos<=8) { for(Int_t k=0; k<2; k++) { int bin = 0; if(mRunYear!=2016) bin = (qt-1)*16 + (pos-1)*2 + k + 1; else bin = (qt-1)*8 + ((pos-1)/2)*2 + k + 1; int adc = mMtdData.mtdQTadc[(qt-1)][(pos-1)*2+k]; int tac = mMtdData.mtdQTtac[(qt-1)][(pos-1)*2+k]; if(tac>mMtd_qt_tac_min) { mhMtdQTAdcMth->Fill(bin,adc); mhMtdQTTacMth->Fill(bin,tac); if(isMthTof) { mhMtdQTAdcMthTof->Fill(bin,adc); mhMtdQTTacMthTof->Fill(bin,tac); } if(isMuon) { mhMtdQTAdcMuon->Fill(bin,adc); mhMtdQTTacMuon->Fill(bin,tac); } } } int mtdTacSum = mMtdData.mtdQTtacSum[qt-1][pos-1]; int bin = 0; if(mRunYear!=2016) bin = (qt-1)*8+pos; else bin = (qt-1)*4+pos/2; if(mtdTacSum>0) { mhMtdVpdTacDiffMT001Mth->Fill(bin,mtdTacSum-vpdTacSum); if(isMthTof) mhMtdVpdTacDiffMT001MthTof->Fill(bin,mtdTacSum-vpdTacSum); if(isMuon) mhMtdVpdTacDiffMT001Muon->Fill(bin,mtdTacSum-vpdTacSum); } Int_t index = -1; if(pos == mMtdData.mtdQThigh2Pos[qt-1][0]) index = 0; if(pos == mMtdData.mtdQThigh2Pos[qt-1][1]) index = 1; if( index>=0 && mMtdData.mixMtdTacSum[qt-1][index]>0 ) { mhMtdVpdTacDiffMT101Mth->Fill(bin, mMtdData.mixMtdTacSum[qt-1][index]-vpdTacSum/8+1024); if(isMthTof) mhMtdVpdTacDiffMT101MthTof->Fill(bin, mMtdData.mixMtdTacSum[qt-1][index]-vpdTacSum/8+1024); if(isMuon) mhMtdVpdTacDiffMT101Muon->Fill(bin, mMtdData.mixMtdTacSum[qt-1][index]-vpdTacSum/8+1024); } } } if(isTrig == 1) { nTrigMtdHit ++; mhMtdTrigHitMap->Fill(backleg,lChan); if(isMatched==1) { nTrigMtdHitMth++; mhMtdTrigMthHitMap->Fill(backleg,lChan); } } } mhMtdTrigNHits->Fill(nTrigMtdHit); mhMtdTrigMthNHits->Fill(nTrigMtdHitMth); } //_____________________________________________________________________________ void StMtdQAMaker::bookHistos() { // event histograms //this array describe the Channel input from which backleg & position & direction const char qtlabel[64][100] = {"QT1-1 25-1-J2","QT1-1 25-1-J3","QT1-2 25-5-J2","QT1-2 25-5-J3","QT1-3 25-2-J2","QT1-3 25-2-J3","QT1-4 25-4-J2","QT1-4 25-4-J3","QT1-5 25-3-J2","QT1-5 25-3-J3","QT1-6 30-3-J2","QT1-6 30-3-J3","QT1-7 30-1-J2","QT1-7 30-1-J3","QT1-8 30-5-J2","QT1-8 30-5-J3","QT2-1 05-1-J2","QT2-1 05-1-J3","QT2-2 05-5-J2","QT2-2 05-5-J3","QT2-3 05-2-J2","QT2-3 05-2-J3","QT2-4 05-4-J2","QT2-4 05-4-J3","QT2-5 05-3-J2","QT2-5 05-3-J3","QT2-6 ","QT2-6 ","QT2-7 30-2-J2","QT2-7 30-2-J3","QT2-8 30-4-J2","QT2-8 30-4-J3","QT3-1 10-1-J2","QT3-1 10-1-J3","QT3-2 10-5-J2","QT3-2 10-5-J3","QT3-3 10-2-J2","QT3-3 10-2-J3","QT3-4 10-4-J2","QT3-4 10-4-J3","QT3-5 10-3-J2","QT3-5 10-3-J3","QT3-6 15-3-J2","QT3-6 15-3-J3","QT3-7 ","QT3-7 ","QT3-8 ","QT3-8 ","QT4-1 21-1-J2","QT4-1 21-1-J3","QT4-2 21-5-J2","QT4-2 21-5-J3","QT4-3 20-2-J2","QT4-3 20-2-J3","QT4-4 20-4-J2","QT4-4 20-4-J3","QT4-5 20-3-J2","QT4-5 20-3-J3","QT4-6 ","QT4-6 ","QT4-7 15-2-J2","QT4-7 15-2-J3","QT4-8 15-4-J2","QT4-8 15-4-J3"}; const char qtlabel2[32][100] = {"QT1-1 25-1","QT1-2 25-5","QT1-3 25-2","QT1-4 25-4","QT1-5 25-3","QT1-6 30-3","QT1-7 30-1","QT1-8 30-5","QT2-1 05-1","QT2-2 05-5","QT2-3 05-2","QT2-4 05-4","QT2-5 05-3","QT2-6 ","QT2-7 30-2","QT2-8 30-4","QT3-1 10-1","QT3-2 10-5","QT3-3 10-2","QT3-4 10-4","QT3-5 10-3","QT3-6 15-3","QT3-7 ","QT3-8 ","QT4-1 21-1","QT4-2 21-5","QT4-3 20-2","QT4-4 20-4","QT4-5 20-3","QT4-6 ","QT4-7 15-2","QT4-8 15-4"}; mhEventCuts = new TH1F("hEventCuts","Cuts used for analysis",20,0,20); AddHist(mhEventCuts); mhEventCuts->GetXaxis()->SetBinLabel(1,"|vtx_z|"); mhEventCuts->SetBinContent(1,mMaxVtxZ); mhEventCuts->GetXaxis()->SetBinLabel(2,"trk_pt_min"); mhEventCuts->SetBinContent(2,mMinTrkPt); mhEventCuts->GetXaxis()->SetBinLabel(3,"trk_pt_max"); mhEventCuts->SetBinContent(3,mMaxTrkPt); mhEventCuts->GetXaxis()->SetBinLabel(4,"trk_eta"); mhEventCuts->SetBinContent(4,mMaxTrkEta); mhEventCuts->GetXaxis()->SetBinLabel(5,"MinNHitsFit"); mhEventCuts->SetBinContent(5,mMinNHitsFit); mhEventCuts->GetXaxis()->SetBinLabel(6,"MinNHitsDedx"); mhEventCuts->SetBinContent(6,mMinNHitsDedx); mhEventCuts->GetXaxis()->SetBinLabel(7,"mtd_qt_tac_min"); mhEventCuts->SetBinContent(7,mMtd_qt_tac_min); mhEventCuts->GetXaxis()->SetBinLabel(8,"mtd_qt_tac_max"); mhEventCuts->SetBinContent(8,mMtd_qt_tac_max); mhEventCuts->GetXaxis()->SetBinLabel(9,"mtd_qt_tac_diff_range_abs"); mhEventCuts->SetBinContent(9,mMtd_qt_tac_diff_range_abs); mhEventCuts->GetXaxis()->SetBinLabel(12,"mMaxDca"); mhEventCuts->SetBinContent(12,mMaxDca); mhEventCuts->GetXaxis()->SetBinLabel(13,"mMinNsigmaPi"); mhEventCuts->SetBinContent(13,mMinNsigmaPi); mhEventCuts->GetXaxis()->SetBinLabel(14,"mMaxNsigmaPi"); mhEventCuts->SetBinContent(14, mMaxNsigmaPi); mhEventCuts->GetXaxis()->SetBinLabel(15,"mMinFitHitsFraction"); mhEventCuts->SetBinContent(15, mMinFitHitsFraction); mhEventCuts->GetXaxis()->SetBinLabel(16,"mMaxVtxDz"); mhEventCuts->SetBinContent(16, mMaxVtxDz); mhEventCuts->GetXaxis()->SetBinLabel(17,"mVertexMode"); mhEventCuts->SetBinContent(17, mVertexMode); const Int_t nbins = 3 + mTriggerIDs.size(); mhEventTrig = new TH1F("hEventStat","Event statistics",nbins,0.,(Float_t)nbins); mhEventTrig->GetXaxis()->SetBinLabel(1,"All events"); mhEventTrig->GetXaxis()->SetBinLabel(2,"Good trigger"); mhEventTrig->GetXaxis()->SetBinLabel(3,"Vtx Cuts"); for(UInt_t i=0; i<mTriggerIDs.size(); i++) { mhEventTrig->GetXaxis()->SetBinLabel(i+4,Form("%d",mTriggerIDs[i])); } AddHist(mhEventTrig); mhRunId = new TH1F("hRunId","Statistics per run",mEndRun-mStartRun,mStartRun,mEndRun); AddHist(mhRunId); mhRefMult = new TH1F("hRefMult","RefMult distribution;RefMult",1000,0,1000); AddHist(mhRefMult); mhgRefMult = new TH1F("hgRefMult","gRefMult distribution;gRefMult",1000,0,1000); AddHist(mhgRefMult); mhVertexXY = new TH2F("hVertexXY","Primary vertex y vs x (TPC);x (cm);y (cm)",100,-5,5,100,-5,5); AddHist(mhVertexXY); mhVertexXZ = new TH2F("hVertexXZ","Primary vertex x vs z (TPC);z (cm);x (cm)",200,-200,200,100,-5,5); AddHist(mhVertexXZ); mhVertexYZ = new TH2F("hVertexYZ","Primary vertex y vs z (TPC);z (cm);y (cm)",200,-200,200,100,-5,5); AddHist(mhVertexYZ); mhVertexZ = new TH1F("hVertexZ","Primary vertex z (TPC); z",200,-200,200); AddHist(mhVertexZ); mhVtxZvsVpdVzDefault = new TH2F("hVtxZvsVpdVzDefault","Primary vertex z: VPD vs TPC (default);TPC z_{vtx} (cm);VPD z_{vtx} (cm)",201,-201,201,201,-201,201); AddHist(mhVtxZvsVpdVzDefault); mhVtxZDiffDefault = new TH1F("hVtxZDiffDefault","TPC vz - VPD vz (default); #Deltavz (cm)",400,-20,20); AddHist(mhVtxZDiffDefault); mhVtxClosestIndex = new TH1F("hVtxClosestIndex","Index of TPC vertex closest to VPD vertex (ranking>0)",50,0,50); AddHist(mhVtxClosestIndex); mhVtxZvsVpdVzClosest = new TH2F("hVtxZvsVpdVzClosest","Primary vertex z: VPD vs TPC (closest);TPC z_{vtx} (cm);VPD z_{vtx} (cm)",201,-201,201,201,-201,201); AddHist(mhVtxZvsVpdVzClosest); mhVtxZDiffClosest = new TH1F("hVtxZDiffClosest","TPC vz - VPD vz (closest); #Deltavz (cm)",400,-20,20); AddHist(mhVtxZDiffClosest); // TOF histograms mhTofStartTime = new TH1F("hTofStartTime","Start time from TOF; t_{start}",40,0,2e5); AddHist(mhTofStartTime); // VPD QT information mhVpdQTadc = new TH2F("hVpdQTadc","VPD QT: ADC vs channel;channel;ADC",64,0.5,64.5,250,0,2500); AddHist(mhVpdQTadc); mhVpdQTtac = new TH2F("hVpdQTtac","VPD QT: TAC vs channel;channel;TAC",64,0.5,64.5,200,500,2500); AddHist(mhVpdQTtac); // Primary tracks mhNTrk = new TH1F("hNTrk","Number of good primary tracks per event;N",1000,0,1000); AddHist(mhNTrk); mhTrkPt = new TH1F("hTrkPt","p_{T} of primary tracks;p_{T} (GeV/c)",100,0,20); AddHist(mhTrkPt); mhTrkDcaVsPt = new TH2F("hTrkDcaVsPt","Dca vs p_{T} of primary tracks;p_{T} (GeV/c);dca (cm)",100,0,20,35,0,3.5); AddHist(mhTrkDcaVsPt); mhTrkPhiVsPt = new TH2F("hTrkPhiVsPt","#varphi vs p_{T} of primary tracks;p_{T} (GeV/c);#varphi",100,0,20,150,0,2*pi); AddHist(mhTrkPhiVsPt); mhTrkEtaVsPt = new TH2F("hTrkEtaVsPt","#eta vs p_{T} of primary tracks;p_{T} (GeV/c);#eta",100,0,20,50,-1,1); AddHist(mhTrkEtaVsPt); mhTrkPhiEta = new TH2F("hTrkPhiEta","#varphi vs #eta of primary tracks (p_{T} > 1 GeV/c);#eta;#varphi",50,-1,1,150,0,2*pi); AddHist(mhTrkPhiEta); mhTrkNHitsFitVsPt = new TH2F("hTrkNHitsFitVsPt","NHitsFit vs p_{T} of primary tracks;p_{T} (GeV/c);NHitsFit",100,0,20,45,0,45); AddHist(mhTrkNHitsFitVsPt); mhTrkNHitsDedxVsPt = new TH2F("hTrkNHitsDedxVsPt","NHitsDedx vs p_{T} of primary tracks;p_{T} (GeV/c);NHitsDedx",100,0,20,45,0,45); AddHist(mhTrkNHitsDedxVsPt); mhTrkDedxVsPt = new TH2F("hTrkDedxVsPt","dE/dx vs p_{T} of primary tracks;p_{T} (GeV/c);dE/dx (keV/cm)",100,0,20,100,0,10); AddHist(mhTrkDedxVsPt); mhTrkNsigmaPiVsPt = new TH2F("hTrkNsigmaPiVsPt","n#sigma_{#pi} vs p_{T} of primary tracks;p_{T} (GeV/c);n#sigma_{#pi}",100,0,20,100,-5,5); AddHist(mhTrkNsigmaPiVsPt); mhTrkNsigmaPiVsPhi = new TH2F("hTrkNsigmaPiVsPhi","n#sigma_{#pi} vs #varphi of primary tracks (p_{T} > 1 GeV/c);#varphi;n#sigma_{#pi}",150,0,2*pi,100,-5,5); AddHist(mhTrkNsigmaPiVsPhi); mhTrkNsigmaPiVsEta = new TH2F("hTrkNsigmaPiVsEta","n#sigma_{#pi} vs #eta of primary tracks (p_{T} > 1 GeV/c);#eta;n#sigma_{#pi}",50,-1,1,100,-5,5); AddHist(mhTrkNsigmaPiVsEta); mhTofMthTrkLocaly = new TH2F("hTofMthTrkLocaly","TOF match: local y vs tray;tray;local y (cm)",120,0.5,120.5,100,-5,5); AddHist(mhTofMthTrkLocaly); mhTofMthTrkLocalz = new TH2F("hTofMthTrkLocalz","TOF match: local z vs module;module;local z (cm)",64,0.5,64.5,100,-5,5); AddHist(mhTofMthTrkLocalz); mhMtdTrackProjMap = new TH2F("hMtdTrackProjMap","MTD: channel vs backleg of projected primary tracks;backleg;channel",30,0.5,30.5,60,-0.5,59.5); AddHist(mhMtdTrackProjMap); // MTD QT information mhMtdQTAdcAll = new TH2F("hMtdQTAdcAll","MTD QT: ADC vs channel (All);;ADC",64,0.5,64.5,350,0,3500); AddHist(mhMtdQTAdcAll); mhMtdQTAdcMth = new TH2F("hMtdQTAdcMth","MTD QT: ADC vs channel (Track matched);;ADC",64,0.5,64.5,350,0,3500); AddHist(mhMtdQTAdcMth); mhMtdQTAdcMthTof = new TH2F("hMtdQTAdcMthTof","MTD QT: ADC vs channel (TOF track matched);;ADC",64,0.5,64.5,350,0,3500); AddHist(mhMtdQTAdcMthTof); mhMtdQTAdcMuon = new TH2F("hMtdQTAdcMuon","MTD QT: ADC vs channel (Muon PID);;ADC",64,0.5,64.5,350,0,3500); AddHist(mhMtdQTAdcMuon); mhMtdQTTacAll = new TH2F("hMtdQTTacAll","MTD QT: TAC vs channel (All);;TAC",64,0.5,64.5,300,0,3000); AddHist(mhMtdQTTacAll); mhMtdQTTacMth = new TH2F("hMtdQTTacMth","MTD QT: TAC vs channel (Track matched);;TAC",64,0.5,64.5,300,0,3000); AddHist(mhMtdQTTacMth); mhMtdQTTacMthTof = new TH2F("hMtdQTTacMthTof","MTD QT: TAC vs channel (TOF track matched);;TAC",64,0.5,64.5,300,0,3000); AddHist(mhMtdQTTacMthTof); mhMtdQTTacMuon = new TH2F("hMtdQTTacMuon","MTD QT: TAC vs channel (Muon PID);;TAC",64,0.5,64.5,300,0,3000); AddHist(mhMtdQTTacMuon); mhMtdQTAdcVsTacAll = new TH2F("hMtdQTAdcVsTacAll","MTD QT: ADC vs. TAC (All);TAC;ADC",350,0,3500,350,0,3500); AddHist(mhMtdQTAdcVsTacAll); mhMtdQTJ2J3Diff = new TH2F("hMtdQTJ2J3Diff","MTD QT: J3-J2 TAC vs channel;;TAC (J3-J2)",32,0.5,32.5,160,-800,800); AddHist(mhMtdQTJ2J3Diff); mhMtdVpdTacDiffMT001 = new TH2F("hMtdVpdTacDiffMT001","QT: MTD-VPD tac difference (All);;tac_{MTD}-tac_{VPD}",32,0.5,32.5,600,-6000,6000); AddHist(mhMtdVpdTacDiffMT001); mhMtdVpdTacDiffMT001Mth = new TH2F("hMtdVpdTacDiffMT001Mth","QT: MTD-VPD tac difference (Track matched);;tac_{MTD}-tac_{VPD}",32,0.5,32.5,600,-6000,6000); AddHist(mhMtdVpdTacDiffMT001Mth); mhMtdVpdTacDiffMT001MthTof = new TH2F("hMtdVpdTacDiffMT001MthTof","QT: MTD-VPD tac difference (TOF track matched);;tac_{MTD}-tac_{VPD}",32,0.5,32.5,600,-6000,6000); AddHist(mhMtdVpdTacDiffMT001MthTof); mhMtdVpdTacDiffMT001Muon = new TH2F("hMtdVpdTacDiffMT001Muon","QT: MTD-VPD tac difference (Muon PID);;tac_{MTD}-tac_{VPD}",32,0.5,32.5,600,-6000,6000); AddHist(mhMtdVpdTacDiffMT001Muon); mhMtdVpdTacDiffMT101 = new TH2F("hMtdVpdTacDiffMT101","MT101: MTD-VPD tac difference;;tac_{MTD}-tac_{VPD}+1024",32,0.5,32.5,1024,0,2048); AddHist(mhMtdVpdTacDiffMT101); mhMtdVpdTacDiffMT101Mth = new TH2F("hMtdVpdTacDiffMT101Mth","MT101: MTD-VPD tac difference (Track matched);;tac_{MTD}-tac_{VPD}+1024",32,0.5,32.5,1024,0,2048); AddHist(mhMtdVpdTacDiffMT101Mth); mhMtdVpdTacDiffMT101MthTof = new TH2F("hMtdVpdTacDiffMT101MthTof","MT101: MTD-VPD tac difference (TOF track matched);;tac_{MTD}-tac_{VPD}+1024",32,0.5,32.5,1024,0,2048); AddHist(mhMtdVpdTacDiffMT101MthTof); mhMtdVpdTacDiffMT101Muon = new TH2F("hMtdVpdTacDiffMT101Muon","MT101: MTD-VPD tac difference (Muon PID);;tac_{MTD}-tac_{VPD}+1024",32,0.5,32.5,1024,0,2048); AddHist(mhMtdVpdTacDiffMT101Muon); for(Int_t i=0; i<64; i++) { mhMtdQTAdcAll->GetXaxis()->SetBinLabel(i+1,qtlabel[i]); mhMtdQTAdcMth->GetXaxis()->SetBinLabel(i+1,qtlabel[i]); mhMtdQTAdcMthTof->GetXaxis()->SetBinLabel(i+1,qtlabel[i]); mhMtdQTAdcMuon->GetXaxis()->SetBinLabel(i+1,qtlabel[i]); mhMtdQTTacAll->GetXaxis()->SetBinLabel(i+1,qtlabel[i]); mhMtdQTTacMth->GetXaxis()->SetBinLabel(i+1,qtlabel[i]); mhMtdQTTacMthTof->GetXaxis()->SetBinLabel(i+1,qtlabel[i]); mhMtdQTTacMuon->GetXaxis()->SetBinLabel(i+1,qtlabel[i]); } for(Int_t i=0; i<32; i++) { mhMtdVpdTacDiffMT001->GetXaxis()->SetBinLabel(i+1,qtlabel2[i]); mhMtdVpdTacDiffMT001Mth->GetXaxis()->SetBinLabel(i+1,qtlabel2[i]); mhMtdVpdTacDiffMT001MthTof->GetXaxis()->SetBinLabel(i+1,qtlabel2[i]); mhMtdVpdTacDiffMT001Muon->GetXaxis()->SetBinLabel(i+1,qtlabel2[i]); mhMtdVpdTacDiffMT101->GetXaxis()->SetBinLabel(i+1,qtlabel2[i]); mhMtdVpdTacDiffMT101Mth->GetXaxis()->SetBinLabel(i+1,qtlabel2[i]); mhMtdVpdTacDiffMT101MthTof->GetXaxis()->SetBinLabel(i+1,qtlabel2[i]); mhMtdVpdTacDiffMT101Muon->GetXaxis()->SetBinLabel(i+1,qtlabel2[i]); mhMtdQTJ2J3Diff->GetXaxis()->SetBinLabel(i+1,qtlabel2[i]); } for(Int_t i=0; i<kNQTboard; i++) { for(Int_t j=0; j<2; j++) { mhMixMtdTacSumvsMxqMtdTacSum[i][j] = new TH2F(Form("hMixMtdTacSumvsMxqMtdTacSum_QT%d_%d",i+1,j),Form("MTD QT%d: MIX vs MXQ at %d;mxq_mtdtacsum;mix_mtdtacsum",i+1,j),1024,0,1024,1024,0,1024); AddHist(mhMixMtdTacSumvsMxqMtdTacSum[i][j]); } } // MTD histograms mhMtdTriggerTime[0] = new TH1F("hMtdTriggerTime0","MTD: trigger time for backleg 16-30;t",120,0,1.2e5); AddHist(mhMtdTriggerTime[0]); mhMtdTriggerTime[1] = new TH1F("hMtdTriggerTime1","MTD: trigger time for backleg 1-15;t",120,0,1.2e5); AddHist(mhMtdTriggerTime[1]); // ===== raw hits mhMtdNRawHits = new TH1F("hMtdNRawHits","Number of raw MTD hits per event;N",100,0,100); AddHist(mhMtdNRawHits); mhMtdRawHitMap = new TH2F("hMtdRawHitMap","MTD: channel vs backleg of raw hits;backleg;channel",30,0.5,30.5,120,0.5,120.5); AddHist(mhMtdRawHitMap); mhMtdRawHitLeTime = new TH2F("hMtdRawHitLeTime","MTD: leading time of raw hit;channel;t_{leading} (ns)",3601,-0.5,3600.5,128,0,51200); AddHist(mhMtdRawHitLeTime); mhMtdRawHitTrTime = new TH2F("hMtdRawHitTrTime","MTD: trailing time of raw hit;channel;t_{trailing} (ns)",3601,-0.5,3600.5,128,0,51200); AddHist(mhMtdRawHitTrTime); mhMtdRawHitLeNDiff = new TH2F("hMtdRawHitLeNDiff","MTD: difference in leading raw hit rates (west-east);channel;nLeRawHit: West - East",1801,-0.5,1800.5,11,-5.5,5.5); AddHist(mhMtdRawHitLeNDiff); mhMtdRawHitTrNDiff = new TH2F("hMtdRawHitTrNDiff","MTD: difference in trailing raw hit rates (west-east);channel;nTrRawHit: West - East",1801,-0.5,1800.5,11,-5.5,5.5); AddHist(mhMtdRawHitTrNDiff); mhMtdRawHitLeNEast = new TH1F("hMtdRawHitLeNEast","MTD: number of leading raw hit (east);channel;N_{leading,east}",1801,-0.5,1800.5); AddHist(mhMtdRawHitLeNEast); mhMtdRawHitLeNWest = new TH1F("hMtdRawHitLeNWest","MTD: number of leading raw hit (west);channel;N_{leading,west}",1801,-0.5,1800.5); AddHist(mhMtdRawHitLeNWest); mhMtdRawHitTrNEast = new TH1F("hMtdRawHitTrNEast","MTD: number of trailing raw hit (east);channel;N_{trailing,east}",1801,-0.5,1800.5); AddHist(mhMtdRawHitTrNEast); mhMtdRawHitTrNWest = new TH1F("hMtdRawHitTrNWest","MTD: number of trailing raw hit (west);channel;N_{trailing,west}",1801,-0.5,1800.5); AddHist(mhMtdRawHitTrNWest); // ===== hits mhMtdNHits = new TH1F("hMtdNHits","Number of MTD hits per event;N",10,0,10); AddHist(mhMtdNHits); mhMtdHitMap = new TH2F("hMtdHitMap","MTD: channel vs backleg of hits;backleg;channel",30,0.5,30.5,60,-0.5,59.5); AddHist(mhMtdHitMap); mhMtdHitLeTimeDiff = new TH2F("hMtdHitLeTimeDiff","MTD: (east-west) leading time of hits;channel;#Deltat_{leading} (ns)",1801,-0.5,1800.5,41,-20.5,20.5); AddHist(mhMtdHitLeTimeDiff); mhMtdHitTotWest = new TH2F("hMtdHitTotWest","MTD: west TOT of hits;channel;tot (ns)",1801,-0.5,1800.5,50,0,50); AddHist(mhMtdHitTotWest); mhMtdHitTotEast = new TH2F("hMtdHitTotEast","MTD: east TOT of hits;channel;tot (ns)",1801,-0.5,1800.5,50,0,50); AddHist(mhMtdHitTotEast); const int nBinsTrigTime = 750; const double minTrigTime = 2000, maxTrigTime = 3500; mhMtdHitTrigTime = new TH2F("hMtdHitTrigTime","MTD: trigger time of hit (west+east)/2;channel;tdc-t_{trigger} (ns)",1801,-0.5,1800.5,nBinsTrigTime,minTrigTime,maxTrigTime); AddHist(mhMtdHitTrigTime); mhMtdHitTrigTimeTrkMth = new TH2F("hMtdHitTrigTimeTrkMth","MTD: trigger time of hits (Track matched);channel;tdc-t_{trigger} (ns)",1801,-0.5,1800.5,nBinsTrigTime,minTrigTime,maxTrigTime); AddHist(mhMtdHitTrigTimeTrkMth); mhMtdHitTrigTimeTrkMthTof = new TH2F("hMtdHitTrigTimeTrkMthTof","MTD: trigger time of hits (TOF track matched);channel;tdc-t_{trigger} (ns)",1801,-0.5,1800.5,nBinsTrigTime,minTrigTime,maxTrigTime); AddHist(mhMtdHitTrigTimeTrkMthTof); mhMtdHitTrigTimeMuon = new TH2F("hMtdHitTrigTimeMuon","MTD: trigger time of hits (Muon PID);channel;tdc-t_{trigger} (ns)",1801,-0.5,1800.5,nBinsTrigTime,minTrigTime,maxTrigTime); AddHist(mhMtdHitTrigTimeMuon); mhMtdHitTrigTimeGoodQT = new TH2F("hMtdHitTrigTimeGoodQT","MTD: trigger time of hits (Good QT);channel;tdc-t_{trigger} (ns)",1801,-0.5,1800.5,nBinsTrigTime,minTrigTime,maxTrigTime); AddHist(mhMtdHitTrigTimeGoodQT); mhMtdHitTrigTimeTrig = new TH2F("hMtdHitTrigTimeTrig","MTD: trigger time of triggering hits;channel;tdc-t_{trigger} (ns)",1801,-0.5,1800.5,nBinsTrigTime,minTrigTime,maxTrigTime); AddHist(mhMtdHitTrigTimeTrig); mhMtdHitTrigTimeVsQtAdc[0] = new TH2F("hMtdHitTrigTimeVsQtAdcE","MTD: trigger time vs. QT ADC (East);QT Adc;tdc_{east}-t_{trigger} (ns)",350,0,3500,nBinsTrigTime,minTrigTime,maxTrigTime); AddHist(mhMtdHitTrigTimeVsQtAdc[0]); mhMtdHitTrigTimeVsQtAdc[1] = new TH2F("hMtdHitTrigTimeVsQtAdcW","MTD: trigger time vs. QT ADC (West);QT Adc;tdc_{west}-t_{trigger} (ns)",350,0,3500,nBinsTrigTime,minTrigTime,maxTrigTime); AddHist(mhMtdHitTrigTimeVsQtAdc[1]); mhMtdHitTrigTimeVsQtTac[0] = new TH2F("hMtdHitTrigTimeVsQtTacE","MTD: trigger time vs. QT TAC (East);QT Tac;tdc_{east}-t_{trigger} (ns)",300,0,3000,nBinsTrigTime,minTrigTime,maxTrigTime); AddHist(mhMtdHitTrigTimeVsQtTac[0]); mhMtdHitTrigTimeVsQtTac[1] = new TH2F("hMtdHitTrigTimeVsQtTacW","MTD: trigger time vs. QT TAC (West);QT Tac;tdc_{west}-t_{trigger} (ns)",300,0,3000,nBinsTrigTime,minTrigTime,maxTrigTime); AddHist(mhMtdHitTrigTimeVsQtTac[1]); // ===== matched hits mhMtdNMatchHits = new TH1F("mhMtdNMatchHits","Number of matched MTD hits per event;N",100,0,100); AddHist(mhMtdNMatchHits); mhMtdMatchHitMap = new TH2F("hMtdMatchHitMap","MTD: channel vs backleg of matched hits;backleg;channel",30,0.5,30.5,60,-0.5,59.5); AddHist(mhMtdMatchHitMap); mhMtdMatchTrkPt = new TH1F("hMtdMatchTrkPt","MTD: p_{T} of matched primary tracks;p_{T} (GeV/c)",100,0,20); AddHist(mhMtdMatchTrkPt); mhMtdMatchTrkPhiEta = new TH2F("hMtdMatchTrkPhiEta","MTD: #varphi vs #eta of matched primary tracks;#eta;#varphi",50,-1,1,150,0,2*pi); AddHist(mhMtdMatchTrkPhiEta); mhMtdMatchDzVsChan = new TH2F("hMtdMatchDzVsChan","MTD: #Deltaz distribution;channel;#Deltaz = z_{proj}-z_{hit} (cm)",1801,-0.5,1800.5,200,-100,100); AddHist(mhMtdMatchDzVsChan); mhMtdMatchDzVsPtPos = new TH2F("hMtdMatchDzVsPtPos","MTD: #Deltaz vs p_{T} for positive tracks;p_{T} (GeV/c);#Deltaz (cm)",100,0,20,200,-100,100); AddHist(mhMtdMatchDzVsPtPos); mhMtdMatchDzVsPtNeg = new TH2F("hMtdMatchDzVsPtNeg","MTD: #Deltaz vs p_{T} for negative tracks;p_{T} (GeV/c);#Deltaz (cm)",100,0,20,200,-100,100); AddHist(mhMtdMatchDzVsPtNeg); mhMtdMatchDyVsChan = new TH2F("hMtdMatchDyVsChan","MTD: #Deltay distribution;channel;#Deltay = y_{proj}-y_{hit} (cm)",1801,-0.5,1800.5,200,-100,100); AddHist(mhMtdMatchDyVsChan); mhMtdMatchDyVsPtPos = new TH2F("hMtdMatchDyVsPtPos","MTD: #Deltay vs p_{T} for positive tracks;p_{T} (GeV/c);#Deltay (cm)",100,0,20,200,-100,100); AddHist(mhMtdMatchDyVsPtPos); mhMtdMatchDyVsPtNeg = new TH2F("hMtdMatchDyVsPtNeg","MTD: #Deltay vs p_{T} for negative tracks;p_{T} (GeV/c);#Deltay (cm)",100,0,20,200,-100,100); AddHist(mhMtdMatchDyVsPtNeg); mhMtdMatchDtofVsPt = new TH2F("hMtdMatchDtofVsPt","MTD: #Deltatof vs p_{T} distribution;p_{T} (GeV/c);#Deltatof (ns)",100,0,20,1000,-5,5); AddHist(mhMtdMatchDtofVsPt); mhMtdMatchMtdTofVsChan = new TH2F("hMtdMatchMtdTofVsChan","MTD: MTD time vs channel of primary tracks;channel;tof_{MTD} (ns)",1800,-0.5,1799.5,300,0,30); AddHist(mhMtdMatchMtdTofVsChan); mhMtdMatchExpTofVsChan = new TH2F("hMtdMatchExpTofVsChan","MTD: TPC time vs channel of primary tracks;channel;tof_{expected} (ns)",1800,-0.5,1799.5,300,0,30); AddHist(mhMtdMatchExpTofVsChan); mhMtdMatchDtofVsChan = new TH2F("hMtdMatchDtofVsChan","MTD: #Deltatof distribution;channel;#Deltatof (ns)",1801,-0.5,1800.5,1000,-5,5); AddHist(mhMtdMatchDtofVsChan); mhMtdMatchLocalyVsChan = new TH2F("hMtdMatchLocalyVsChan","MTD: local y of matched tracks;channel;y (cm)",1801,-0.5,1800.5,100,-50.5,49.5); AddHist(mhMtdMatchLocalyVsChan); mhMtdMatchLocalzVsChan = new TH2F("hMtdMatchLocalzVsChan","MTD: local z of matched tracks;channel;z (cm)",1801,-0.5,1800.5,100,-50.5,49.5); AddHist(mhMtdMatchLocalzVsChan); mhNQtSignal = new TH1F("hNQtSignal","Number of good QT signals;N",10,0,10); AddHist(mhNQtSignal); mhNMT101Signal = new TH1F("hNMT101Signal","Number of good MT101 signals;N",10,0,10); AddHist(mhNMT101Signal); mhNTF201Signal = new TH1F("hNTF201Signal","Number of good TF201 signals;N",10,0,10); AddHist(mhNTF201Signal); mhMtdTrigNHits = new TH1F("hMtdTrigNHits","Number of triggering MTD hits per event;N",10,0,10); AddHist(mhMtdTrigNHits); mhMtdTrigHitMap = new TH2F("hMtdTrigHitMap","MTD: channel vs backleg of triggering hits;backleg;channel",30,0.5,30.5,60,-0.5,59.5); AddHist(mhMtdTrigHitMap); mhMtdTrigMthNHits = new TH1F("hMtdTrigMthNHits","Number of triggering MTD hits matched to tracks;N",10,0,10); AddHist(mhMtdTrigMthNHits); mhMtdTrigMthHitMap = new TH2F("hMtdTrigMthHitMap","MTD: channel vs backleg of triggering hits matched to tracks;backleg;channel",30,0.5,30.5,60,-0.5,59.5); AddHist(mhMtdTrigMthHitMap); } //_____________________________________________________________________________ void StMtdQAMaker::bookTree() { if(!mOutTreeFileName.Length()) { LOG_ERROR << "StMtdQAMaker:: no output file specified for trees." << endm; return; } fOutTreeFile = new TFile(mOutTreeFileName.Data(),"recreate"); LOG_INFO << "StMtdQAMaker:: create the output to store the QA tree: " << mOutTreeFileName.Data() << endm; LOG_INFO << "StMtdQAMaker:: book the QA trees to be filled." << endm; mQATree = new TTree("mtdQAData","Mtd QA data"); mQATree->SetAutoSave(100000); // 100 MB // event information mQATree->Branch("runId", &mMtdData.runId, "runId/I"); mQATree->Branch("eventId", &mMtdData.eventId, "eventId/I"); mQATree->Branch("nTrigger", &mMtdData.nTrigger, "nTrigger/I"); mQATree->Branch("triggerId", &mMtdData.triggerId, "triggerId[nTrigger]/I"); mQATree->Branch("refMult", &mMtdData.refMult, "refMult/I"); mQATree->Branch("gRefMult", &mMtdData.gRefMult, "gRefMult/I"); mQATree->Branch("vertexX", &mMtdData.vertexX, "vertexX/F"); mQATree->Branch("vertexY", &mMtdData.vertexY, "vertexY/F"); mQATree->Branch("vertexZ", &mMtdData.vertexZ, "vertexZ/F"); mQATree->Branch("vpdVz", &mMtdData.vpdVz, "vpdVz/F"); // VPD information mQATree->Branch("pre", &mMtdData.pre, "pre/B"); mQATree->Branch("post", &mMtdData.post, "post/B"); mQATree->Branch("prepost", &mMtdData.prepost, "prepost/B"); mQATree->Branch("vpdTacSum", &mMtdData.vpdTacSum, "vpdTacSum/s"); mQATree->Branch("vpdHi", &mMtdData.vpdHi, "vpdHi[64]/s"); mQATree->Branch("mtdQTadc", &mMtdData.mtdQTadc, "mtdQTadc[128]/s"); mQATree->Branch("mtdQTtac", &mMtdData.mtdQTtac, "mtdQTtac[128]/s"); mQATree->Branch("mtdQTtacSum", &mMtdData.mtdQTtacSum, "mtdQTtacSum[64]/s"); mQATree->Branch("mtdQThigh2Pos", &mMtdData.mtdQThigh2Pos, "mtdQThigh2Pos[16]/s"); mQATree->Branch("mixMtdTacSum", &mMtdData.mixMtdTacSum, "mixMtdTacSum[16]/s"); mQATree->Branch("TF201Bit", &mMtdData.TF201Bit, "TF201Bit/I"); mQATree->Branch("TF201Bit2", &mMtdData.TF201Bit2, "TF201Bit2/I"); // TOF information mQATree->Branch("tofStartTime", &mMtdData.tofStartTime, "tofStartTime/I"); // Tracks mQATree->Branch("nGoodTrack", &mMtdData.nGoodTrack, "nGoodTrack/I"); mQATree->Branch("trkPt", &mMtdData.trkPt, "trkPt[nGoodTrack]/D"); mQATree->Branch("trkEta", &mMtdData.trkEta, "trkEta[nGoodTrack]/D"); mQATree->Branch("trkPhi", &mMtdData.trkPhi, "trkPhi[nGoodTrack]/D"); mQATree->Branch("trkDca", &mMtdData.trkDca, "trkDca[nGoodTrack]/D"); mQATree->Branch("trkNHitsFit", &mMtdData.trkNHitsFit, "trkNHitsFit[nGoodTrack]/I"); mQATree->Branch("trkNHitsDedx", &mMtdData.trkNHitsDedx, "trkNHitsDedx[nGoodTrack]/I"); mQATree->Branch("trkNsigmaPi", &mMtdData.trkNsigmaPi, "trkNsigmaPi[nGoodTrack]/D"); mQATree->Branch("trkDedx", &mMtdData.trkDedx, "trkDedx[nGoodTrack]/D"); mQATree->Branch("isTrkTofMatched", &mMtdData.isTrkTofMatched, "isTrkTofMatched[nGoodTrack]/O"); mQATree->Branch("trkMthTofTray", &mMtdData.trkMthTofTray, "trkMthTofTray[nGoodTrack]/I"); mQATree->Branch("trkMthTofModule", &mMtdData.trkMthTofModule, "trkMthTofModule[nGoodTrack]/I"); mQATree->Branch("trkMthTofCell", &mMtdData.trkMthTofCell, "trkMthTofCell[nGoodTrack]/I"); mQATree->Branch("trkMthTofLocaly", &mMtdData.trkMthTofLocaly, "trkMthTofLocaly[nGoodTrack]/D"); mQATree->Branch("trkMthTofLocalz", &mMtdData.trkMthTofLocalz, "trkMthTofLocalz[nGoodTrack]/D"); mQATree->Branch("isTrkProjected", &mMtdData.isTrkProjected, "isTrkProjected[nGoodTrack]/O"); mQATree->Branch("trkProjPhi", &mMtdData.trkProjPhi, "trkProjPhi[nGoodTrack]/D"); mQATree->Branch("trkProjZ", &mMtdData.trkProjZ, "trkProjZ[nGoodTrack]/D"); mQATree->Branch("trkProjBackleg", &mMtdData.trkProjBackleg, "trkProjBackleg[nGoodTrack]/B"); mQATree->Branch("trkProjModule", &mMtdData.trkProjModule, "trkProjModule[nGoodTrack]/B"); mQATree->Branch("trkProjChannel", &mMtdData.trkProjChannel, "trkProjChannel[nGoodTrack]/B"); mQATree->Branch("isTrkMtdMatched", &mMtdData.isTrkMtdMatched, "isTrkMtdMatched[nGoodTrack]/O"); mQATree->Branch("trkMthBackleg", &mMtdData.trkMthBackleg, "trkMthBackleg[nGoodTrack]/B"); mQATree->Branch("trkMthModule", &mMtdData.trkMthModule, "trkMthModule[nGoodTrack]/B"); mQATree->Branch("trkMthChannel", &mMtdData.trkMthChannel, "trkMthChannel[nGoodTrack]/B"); // MTD information mQATree->Branch("mtdTriggerTime", &mMtdData.mtdTriggerTime, "mtdTriggerTime[2]/D"); //raw hit mQATree->Branch("mMtdRawHits", &mMtdData.nMtdRawHits, "nMtdRawHits/I"); mQATree->Branch("mtdRawHitFlag", &mMtdData.mtdRawHitFlag, "mtdRawHitFlag[nMtdRawHits]/B"); mQATree->Branch("mtdRawHitBackleg", &mMtdData.mtdRawHitBackleg, "mtdRawHitBackleg[nMtdRawHits]/B"); mQATree->Branch("mtdRawHitModule", &mMtdData.mtdRawHitModule, "mtdRawHitModule[nMtdRawHits]/B"); mQATree->Branch("mtdRawHitChan", &mMtdData.mtdRawHitChan, "mtdRawHitChan[nMtdRawHits]/B"); mQATree->Branch("mtdRawHitTdc", &mMtdData.mtdRawHitTdc, "mtdRawHitTdc[nMtdRawHits]/D"); mQATree->Branch("mtdRawHitTimdDiff", &mMtdData.mtdRawHitTimdDiff, "mtdRawHitTimdDiff[nMtdRawHits]/D"); // hit mQATree->Branch("nMtdHits", &mMtdData.nMtdHits, "nMtdHits/I"); mQATree->Branch("mtdHitBackleg", &mMtdData.mtdHitBackleg, "mtdHitBackleg[nMtdHits]/B"); mQATree->Branch("mtdHitModule", &mMtdData.mtdHitModule, "mtdHitModule[nMtdHits]/B"); mQATree->Branch("mtdHitChan", &mMtdData.mtdHitChan, "mtdHitChan[nMtdHits]/B"); mQATree->Branch("mtdHitLeTimeWest", &mMtdData.mtdHitLeTimeWest, "mtdHitLeTimeWest[nMtdHits]/D"); mQATree->Branch("mtdHitLeTimeEast", &mMtdData.mtdHitLeTimeEast, "mtdHitLeTimeEast[nMtdHits]/D"); mQATree->Branch("mtdHitTotWest", &mMtdData.mtdHitTotWest, "mtdHitTotWest[nMtdHits]/D"); mQATree->Branch("mtdHitTotEast", &mMtdData.mtdHitTotEast, "mtdHitTotEast[nMtdHits]/D"); mQATree->Branch("mtdHitTrigTime", &mMtdData.mtdHitTrigTime, "mtdHitTrigTime[nMtdHits]/D"); mQATree->Branch("mtdHitPhi", &mMtdData.mtdHitPhi, "mtdHitPhi[nMtdHits]/D"); mQATree->Branch("mtdHitZ", &mMtdData.mtdHitZ, "mtdHitZ[nMtdHits]/D"); // matching mQATree->Branch("isMatched", &mMtdData.isMatched, "isMatched[nMtdHits]/O"); mQATree->Branch("isMtdTrig", &mMtdData.isMtdTrig, "isMtdTrig[nMtdHits]/O"); mQATree->Branch("nMatchMtdHits", &mMtdData.nMatchMtdHits, "nMatchMtdHits/I"); mQATree->Branch("mtdMatchTrkPathLength",&mMtdData.mtdMatchTrkPathLength,"mtdMatchTrkPathLength[nMtdHits]/D"); mQATree->Branch("mtdMatchTrkExpTof", &mMtdData.mtdMatchTrkExpTof, "mtdMatchTrkExpTof[nMtdHits]/D"); mQATree->Branch("mtdMatchTrkTof", &mMtdData.mtdMatchTrkTof, "mtdMatchTrkTof[nMtdHits]/D"); mQATree->Branch("mtdMatchTrkLocaly", &mMtdData.mtdMatchTrkLocaly, "mtdMatchTrkLocaly[nMtdHits]/D"); mQATree->Branch("mtdMatchTrkLocalz", &mMtdData.mtdMatchTrkLocalz, "mtdMatchTrkLocalz[nMtdHits]/D"); mQATree->Branch("mtdMatchTrkDeltay", &mMtdData.mtdMatchTrkDeltay, "mtdMatchTrkDeltay[nMtdHits]/D"); mQATree->Branch("mtdMatchTrkDeltaz", &mMtdData.mtdMatchTrkDeltaz, "mtdMatchTrkDeltaz[nMtdHits]/D"); mQATree->Branch("mtdMatchTrkProjPhi",&mMtdData.mtdMatchTrkProjPhi,"mtdMatchTrkProjPhi[nMtdHits]/D"); mQATree->Branch("mtdMatchTrkProjZ", &mMtdData.mtdMatchTrkProjZ, "mtdMatchTrkProjZ[nMtdHits]/D"); mQATree->Branch("mtdMatchTrkPt", &mMtdData.mtdMatchTrkPt, "mtdMatchTrkPt[nMtdHits]/D"); mQATree->Branch("mtdMatchTrkDca", &mMtdData.mtdMatchTrkDca, "mtdMatchTrkDca[nMtdHits]/D"); mQATree->Branch("mtdMatchTrCharge", &mMtdData.mtdMatchTrCharge, "mtdMatchTrCharge[nMtdHits]/I"); mQATree->Branch("mtdMatchTrkPhi", &mMtdData.mtdMatchTrkPhi, "mtdMatchTrkPhi[nMtdHits]/D"); mQATree->Branch("mtdMatchTrkEta", &mMtdData.mtdMatchTrkEta, "mtdMatchTrkEta[nMtdHits]/D"); mQATree->Branch("mtdMatchTrkNsigmaPi",&mMtdData.mtdMatchTrkNsigmaPi,"mtdMatchTrkNsigmaPi[nMtdHits]/D"); mQATree->Branch("mtdMatchTrkTofHit", &mMtdData.mtdMatchTrkTofHit, "mtdMatchTrkTofHit[nMtdHits]/O"); return; } //_____________________________________________________________________________ void StMtdQAMaker::printConfig() { const char *decision[2] = {"no","yes"}; const char *runtype[2] = {"Physics","Cosmic"}; const char *vtxmode[2] = {"default","closest to VPD"}; printf("=== Configuration for StMtdQAMaker ===\n"); printf("Data type: %s\n",runtype[mIsCosmic]); printf("Use vertex that is %s\n",vtxmode[mVertexMode]); printf("Fill the QA tree: %s\n",decision[mFillTree]); printf("Maximum vertex z: %1.0f\n",mMaxVtxZ); printf("Maximum vz diff: %1.0f\n",mMaxVtxDz); printf("Track pt range: [%1.2f, %1.2f]\n",mMinTrkPt,mMaxTrkPt); printf("Track phi range: [%1.2f, %1.2f]\n",mMinTrkPhi,mMaxTrkPhi); printf("Track eta range: [%1.2f, %1.2f]\n",mMinTrkEta,mMaxTrkEta); printf("Minimum number of fit hits: %d\n",mMinNHitsFit); printf("Minimum number of dedx hits: %d\n",mMinNHitsDedx); printf("Minimum fraction of fit hits: %4.2f\n",mMinFitHitsFraction); printf("Maximum dca: %1.2f\n",mMaxDca); printf("NsigmaPi range: [%1.2f, %1.2f]\n",mMinNsigmaPi,mMaxNsigmaPi); printf("Match to TOF: %s\n",decision[mMatchToTof]); printf("=======================================\n"); } //_____________________________________________________________________________ Bool_t StMtdQAMaker::propagateHelixToMtd(StPhysicalHelixD helix, Double_t &projPhi, Double_t &projZ) const { // helix extrapolation // no energy loss projPhi = -999; projZ = -999; pairD sMtd = helix.pathLength(gMtdMinRadius); if(sMtd.first<=0 && sMtd.second<=0) return kFALSE; Double_t rMtd = (sMtd.first<0 || sMtd.second<0) ? max(sMtd.first,sMtd.second) : min(sMtd.first,sMtd.second); StThreeVector<double> pMtd = helix.at(rMtd); projPhi = rotatePhi(pMtd.phi()); projZ = pMtd.z(); return kTRUE; } //_____________________________________________________________________________ Int_t StMtdQAMaker::getMtdHitTHUB(const Int_t backleg) const { if(backleg>=1 && backleg<=15) return 2; else if (backleg>=16 && backleg<=30) return 1; else return -1; } //_____________________________________________________________________________ Double_t StMtdQAMaker::getMtdHitGlobalZ(StMuMtdHit *hit) const { Int_t backleg = hit->backleg(); if(backleg<1 || backleg>30) { LOG_WARN << "Wrong backleg id: " << backleg << endm; return -999; } return getMtdHitGlobalZ(hit->leadingEdgeTime().first, hit->leadingEdgeTime().second, hit->module()); } //_____________________________________________________________________________ Double_t StMtdQAMaker::getMtdHitGlobalZ(StMtdHit *hit) const { Int_t backleg = hit->backleg(); if(backleg<1 || backleg>30) { LOG_WARN << "Wrong backleg id: " << backleg << endm; return -999; } return getMtdHitGlobalZ(hit->leadingEdgeTime().first, hit->leadingEdgeTime().second, hit->module()); } //_____________________________________________________________________________ Double_t StMtdQAMaker::getMtdHitGlobalZ(Double_t leadingWestTime, Double_t leadingEastTime, Int_t module) const { Double_t z = (module-3)*gMtdCellLength - (leadingWestTime-leadingEastTime)/2./gMtdCellDriftV*1e3; return z; } //_____________________________________________________________________________ Double_t StMtdQAMaker::getMtdHitGlobalPhi(StMuMtdHit *hit) const { Int_t backleg = hit->backleg(); if(backleg<1 || backleg>30) { LOG_WARN << "Wrong backleg id: " << backleg << endm; return -999; } return getMtdHitGlobalPhi(backleg, hit->module(), hit->cell()); } //_____________________________________________________________________________ Double_t StMtdQAMaker::getMtdHitGlobalPhi(StMtdHit *hit) const { Int_t backleg = hit->backleg(); if(backleg<1 || backleg>30) { LOG_WARN << "Wrong backleg id: " << backleg << endm; return -999; } return getMtdHitGlobalPhi(backleg, hit->module(), hit->cell()); } //_____________________________________________________________________________ Double_t StMtdQAMaker::getMtdHitGlobalPhi(Int_t backleg, Int_t module, Int_t channel) const { Double_t backlegPhiCen = gMtdFirstBacklegPhiCenter + (backleg-1) * (gMtdBacklegPhiWidth+gMtdBacklegPhiGap); if(backlegPhiCen>2*pi) backlegPhiCen -= 2*pi; Double_t stripPhiCen = 0; if(module>0 && module<4) { stripPhiCen = backlegPhiCen - (gMtdNChannels/4.-0.5-channel)*(gMtdCellWidth+gMtdCellGap)/gMtdMinRadius; } else { stripPhiCen = backlegPhiCen + (gMtdNChannels/4.-0.5-channel)*(gMtdCellWidth+gMtdCellGap)/gMtdMinRadius; } return rotatePhi(stripPhiCen); } //_____________________________________________________________________________ Int_t StMtdQAMaker::getMtdBackleg(const Double_t projPhi) const { Double_t phi = rotatePhi(projPhi); Int_t backleg = (Int_t)(phi/(gMtdBacklegPhiWidth+gMtdBacklegPhiGap)); backleg += 24; if(backleg>30) backleg -= 30; if(backleg>=1 && backleg<=30) return backleg; else return -1; } //_____________________________________________________________________________ Int_t StMtdQAMaker::getMtdModule(const Double_t projZ) const { Int_t module = -1; Double_t temp = (projZ+2.5*gMtdCellLength)/gMtdCellLength; if(temp>0) module = (Int_t)temp + 1; return module; } //_____________________________________________________________________________ Int_t StMtdQAMaker::getMtdCell(const Double_t projPhi, const Double_t projZ) const { Int_t backleg = getMtdBackleg(projPhi); Int_t module = getMtdModule(projZ); return getMtdCell(projPhi,backleg,module); } //_____________________________________________________________________________ Int_t StMtdQAMaker::getMtdCell(const Double_t projPhi, const Int_t backleg, const Int_t module) const { // module: 1-5 Double_t lowEdge = gMtdFirstBacklegPhiCenter + (backleg-1)*(gMtdBacklegPhiWidth+gMtdBacklegPhiGap) - (gMtdNChannels/4.)*(gMtdCellWidth+gMtdCellGap)/gMtdMinRadius; //approximation lowEdge = rotatePhi(lowEdge); Double_t cellPhi = projPhi - lowEdge; cellPhi = rotatePhi(cellPhi); Int_t cell = (Int_t) ( cellPhi/((gMtdCellWidth+gMtdCellGap)/gMtdMinRadius)); if(module>3) cell = 11 - cell; if(cell>=0 && cell<=11) return cell; else return -1; } //_____________________________________________________________________________ void StMtdQAMaker::getMtdPosFromProj(const Double_t projPhi, const Double_t projZ, Int_t &backleg, Int_t &module, Int_t&cell) const { backleg = getMtdBackleg(projPhi); module = getMtdModule(projZ); cell = getMtdCell(projPhi,backleg,module); } //_____________________________________________________________________________ Bool_t StMtdQAMaker::isValidTrack(StTrack *track, StVertex *vtx) const { StThreeVectorF mom = track->geometry()->momentum(); Float_t pt = mom.perp(); Float_t eta = mom.pseudoRapidity(); Float_t phi = mom.phi(); if(phi<0) phi += 2*pi; if(pt < mMinTrkPt || pt > mMaxTrkPt) return kFALSE; if(eta < mMinTrkEta || eta > mMaxTrkEta) return kFALSE; if(phi < mMinTrkPhi || phi > mMaxTrkPhi) return kFALSE; Int_t nHitsFit = track->fitTraits().numberOfFitPoints(kTpcId); if(nHitsFit<mMinNHitsFit) return kFALSE; Int_t nHitsPoss = track->numberOfPossiblePoints(kTpcId); if(nHitsFit/(1.0*nHitsPoss)<mMinFitHitsFraction) return kFALSE; StTpcDedxPidAlgorithm pidAlgorithm; const StParticleDefinition *pd = track->pidTraits(pidAlgorithm); if(!pd || !pidAlgorithm.traits()) return kFALSE; if(pidAlgorithm.traits()->numberOfPoints()<mMinNHitsDedx) return kFALSE; static StPionPlus* Pion = StPionPlus::instance(); Double_t nSigmaPi = pidAlgorithm.numberOfSigma(Pion); if(nSigmaPi<mMinNsigmaPi || nSigmaPi>mMaxNsigmaPi) return kFALSE; if(!mIsCosmic) { StGlobalTrack *globalTrack = dynamic_cast<StGlobalTrack*>(track); if(!globalTrack) return kFALSE; THelixTrack thelix = globalTrack->dcaGeometry()->thelix(); const Double_t *pos = thelix.Pos(); StThreeVectorF dcaGlobal = StThreeVectorF(pos[0],pos[1],pos[2]) - vtx->position(); if(dcaGlobal.mag()>mMaxDca) return kFALSE; } return kTRUE; } //_____________________________________________________________________________ Bool_t StMtdQAMaker::isValidTrack(const StMuTrack *track) const { StThreeVectorF mom = track->momentum(); Float_t pt = mom.perp(); Float_t eta = mom.pseudoRapidity(); Float_t phi = mom.phi(); if(phi<0) phi += 2*pi; Double_t nSigmaPi = track->nSigmaPion(); if(pt < mMinTrkPt || pt > mMaxTrkPt) return kFALSE; if(eta < mMinTrkEta || eta > mMaxTrkEta) return kFALSE; if(phi < mMinTrkPhi || phi > mMaxTrkPhi) return kFALSE; if(track->nHitsFit(kTpcId)<mMinNHitsFit) return kFALSE; if(track->nHitsDedx()<mMinNHitsDedx) return kFALSE; if(!mIsCosmic && track->dcaGlobal().mag()>mMaxDca) return kFALSE; if(nSigmaPi<mMinNsigmaPi || nSigmaPi>mMaxNsigmaPi) return kFALSE; if(track->nHitsFit(kTpcId)/(1.0*track->nHitsPoss(kTpcId))<mMinFitHitsFraction) return kFALSE; return kTRUE; } //_____________________________________________________________________________ Double_t StMtdQAMaker::rotatePhi(Double_t phi) const { Double_t outPhi = phi; while(outPhi<0) outPhi += 2*pi; while(outPhi>2*pi) outPhi -= 2*pi; return outPhi; } // //// $Id: StMtdQAMaker.cxx,v 1.17 2018/02/20 19:46:48 marr Exp $ //// $Log: StMtdQAMaker.cxx,v $ //// Revision 1.17 2018/02/20 19:46:48 marr //// Major update with more histograms //// //// Revision 1.16 2017/03/10 20:16:42 marr //// 1) Remove the function to apply trigger time window cuts since they are applied //// already during reconstruction. //// 2) Accommodate 8-QT system used in 2016 //// 3) Remove the implementation for StEvent QA since it is not maintained //// 4) Vertex selection for cosmic ray: default one if available //// //// Revision 1.15 2017/03/01 20:23:59 marr //// 1) Add option to select different vertex //// 2) More QA plots for PID variables //// //// Revision 1.14 2016/08/04 21:26:36 marr //// Add histograms for vertex QA, and dTof calibration //// //// Revision 1.13 2016/07/28 14:33:23 marr //// Fix coverity check: initialization of data member //// //// Revision 1.12 2016/07/27 16:03:51 marr //// Fix coverity check: initialization of data member //// //// Revision 1.11 2015/10/28 19:51:10 marr //// Remove printout //// //// Revision 1.10 2015/10/28 19:50:23 marr //// Add a new data member: mMaxVtxDz //// //// Revision 1.9 2015/10/23 02:18:51 marr //// 1) Add histogram for global T0 alignment calibration using primary tracks //// 2) Add mMaxVtxDz to cut on vz difference between TPC and VPD //// //// Revision 1.8 2015/04/08 14:03:17 marr //// change to use gMtdCellDriftV from StMtdConstants.h //// //// Revision 1.7 2015/02/01 16:26:31 marr //// 1) Add a new histogram to store the run indices //// 2) Change the titles of some histograms for better readability //// //// Revision 1.6 2014/12/11 21:14:13 marr //// Use (leadTimeW+leadTimeE)/2 instead of leadTimeW for MTD hit time //// //// Revision 1.5 2014/11/12 18:11:01 marr //// Minor bug fix //// //// Revision 1.4 2014/11/12 17:50:11 marr //// Check the validity of the matched MTD hit //// //// Revision 1.3 2014/09/19 18:34:55 marr //// Add histograms for LocalY, LocalZ, DeltaY, DeltaZ //// //// Revision 1.2 2014/09/16 23:48:58 marr //// Minor fix such that it compiles under SL5.3, gcc 4.3.2 (rplay17) //// //// Revision 1.1 2014/09/12 17:13:13 marr //// Add StMtdQAMaker class for MTD QA analysis ////
39.470506
1,131
0.667805
[ "geometry", "vector" ]
347b01cafe718e2be005c78fab5aaf766bb373a9
91
cpp
C++
10/suit.cpp
itiszac/CS1B
6d523fe93b047d0c8872fda68ae079e4ffaf1c2f
[ "CC0-1.0" ]
null
null
null
10/suit.cpp
itiszac/CS1B
6d523fe93b047d0c8872fda68ae079e4ffaf1c2f
[ "CC0-1.0" ]
null
null
null
10/suit.cpp
itiszac/CS1B
6d523fe93b047d0c8872fda68ae079e4ffaf1c2f
[ "CC0-1.0" ]
null
null
null
#include "hw10.h" void guessSuit(std::vector<Card> deck) { std::cout << "guessSuit\n"; }
15.166667
38
0.648352
[ "vector" ]
3488a2c442e071884b0c73f8a1f6a9650f103b2a
582
hpp
C++
modules/Core/include/CuteVR/Components/Geometry/ConeFrustum.hpp
marmot722/CuteVR
6be38dc3fa492dd08c4921bfe9e043708f61c946
[ "BSD-3-Clause" ]
null
null
null
modules/Core/include/CuteVR/Components/Geometry/ConeFrustum.hpp
marmot722/CuteVR
6be38dc3fa492dd08c4921bfe9e043708f61c946
[ "BSD-3-Clause" ]
null
null
null
modules/Core/include/CuteVR/Components/Geometry/ConeFrustum.hpp
marmot722/CuteVR
6be38dc3fa492dd08c4921bfe9e043708f61c946
[ "BSD-3-Clause" ]
null
null
null
/// @file /// @author Marcus Meeßen /// @copyright Copyright (c) 2017-2018 Marcus Meeßen /// @copyright Copyright (c) 2018 MASKOR Institute FH Aachen #ifndef CUTE_VR_COMPONENTS_GEOMETRY_CONE_FRUSTUM #define CUTE_VR_COMPONENTS_GEOMETRY_CONE_FRUSTUM #include <CuteVR/Component.hpp> namespace CuteVR { namespace Components { namespace Geometry { /// @brief This class is currently only a placeholder. struct ConeFrustum : public CategorizedComponent<Component::Category::geometry, Component> { }; }}} #endif // CUTE_VR_COMPONENTS_GEOMETRY_CONE_FRUSTUM
30.631579
83
0.752577
[ "geometry" ]
348cea0002ce63d12a546b2d9fe599bcf1d6a37d
3,166
hpp
C++
generators.hpp
else-engine/ee_math
2610f5d05263a35274f3aa1163f292e70f15452c
[ "Zlib" ]
null
null
null
generators.hpp
else-engine/ee_math
2610f5d05263a35274f3aa1163f292e70f15452c
[ "Zlib" ]
null
null
null
generators.hpp
else-engine/ee_math
2610f5d05263a35274f3aa1163f292e70f15452c
[ "Zlib" ]
null
null
null
/** * Copyright (c) 2017 Gauthier ARNOULD * This file is released under the zlib License (Zlib). * See file LICENSE or go to https://opensource.org/licenses/Zlib * for full license details. */ #pragma once #include <cstddef> #include <utility> #include <ee_utils/templates.hpp> #include "common.hpp" #include "vec.hpp" #include "mat.hpp" namespace ee { namespace math { using tutil::eif; using tutil::all_same; /** * Creates a vec object, deducing type and size from arguments. */ template <typename F, typename... Rs, typename = eif<all_same<std::decay_t<F>, std::decay_t<Rs>...>>> constexpr auto make_vec(F&& f, Rs&&... rs) { return vec<std::decay_t<F>, sizeof...(rs) + 1>{ std::forward<F>(f), std::forward<Rs>(rs)...}; } /** * Returns a mat, vec or quat filled with input value. */ namespace detail { template <typename O, std::size_t... Is> constexpr auto fill(typename O::value_type v, std::index_sequence<Is...>) { return O{(static_cast<void>(Is), v)...}; } } // namespace detail template <typename O> constexpr auto fill(typename O::value_type v) { return detail::fill<O>(v, std::make_index_sequence<O::size>{}); } /** * Returns a mat, vec or quat, depending of what O is, with as many values as * required from a given pointer. */ namespace detail { template <typename O, typename T, std::size_t... Is> constexpr auto as_ptr(const T* const ptr, std::index_sequence<Is...>) { return O{static_cast<typename O::value_type>(ptr[Is])...}; } } // namespace detail template <typename O, typename T> constexpr auto as_ptr(const T* const ptr) { return detail::as_ptr<O>(ptr, std::make_index_sequence<O::size>()); } /** * Returns a mat, vec or quat, depending of what O is, based on a list composed * of mat, vec and/or arithmetic elements. */ namespace detail { template <typename O, std::size_t I, typename... Ts, typename = eif<I == 0>, typename = eif<sizeof...(Ts) == O::size>> constexpr auto as(Ts&&... ts) { return O{ts...}; } template <typename, std::size_t I, typename T, typename... Rs, typename = eif<I != 0 && (is_mat<T> || is_vec<T>)>> constexpr auto as(const T&, Rs&&...); template <typename O, std::size_t I, typename F, typename... Rs, typename = eif<I != 0>, typename = eif<is_num<F>>> constexpr auto as(F&& f, Rs&&... rs) { return as<O, I - 1>(std::forward<Rs>(rs)..., static_cast<typename O::value_type>(f)); } template <typename O, std::size_t I, std::size_t... Is, typename F, typename... Rs> constexpr auto as(std::index_sequence<Is...>, const F* const f, Rs&&... rs) { return as<O, I - 1>(std::forward<Rs>(rs)..., static_cast<typename O::value_type>(f[Is])...); } template <typename O, std::size_t I, typename T, typename... Rs, typename> constexpr auto as(const T& f, Rs&&... rs) { return as<O, I>(std::make_index_sequence<T::size>{}, f.data, std::forward<Rs>(rs)...); } } // namespace detail template <typename O, typename F, typename... Rs> constexpr auto as(F&& f, Rs&&... ts) { return detail::as<O, sizeof...(Rs) + 1>(std::forward<F>(f), std::forward<Rs>(ts)...); } } // namespace math } // namespace ee
29.045872
118
0.642135
[ "object" ]
349203756ed436add2005f698e4881e000f6fc8e
1,312
cpp
C++
isBipartite.cpp
DeeptanshuM/Algorithms
48f91e952b71370127db33fa42d642062690f9d9
[ "MIT" ]
null
null
null
isBipartite.cpp
DeeptanshuM/Algorithms
48f91e952b71370127db33fa42d642062690f9d9
[ "MIT" ]
null
null
null
isBipartite.cpp
DeeptanshuM/Algorithms
48f91e952b71370127db33fa42d642062690f9d9
[ "MIT" ]
null
null
null
/* Used BFS to determine if graph is bipartite. */ #include <iostream> #include <vector> #include <queue> using std::vector; using std::queue; int is_bipartite(vector<vector<int> > &adj) { vector <int> color (adj.size(), -1); // -1 represents no color int s = adj[0][0]; //arbitrarilty choosing this as a source vertex color[s] = 0; //let 0 represent white and 1 black queue<int> Q; Q.push(s); while(!Q.empty()){ int u = Q.front(); Q.pop(); for(int i = 0; i < adj[u].size(); i++){ int v = adj[u][i]; //if v has no color, then color it differently than its ancestor if(color[v] == -1){ Q.push(v); if(color[u] == 0) color[v] = 1; if(color[u] == 1) color[v] = 0; } //else check if v and its ancestor have same color //if this is the case then the graph is not bipartite else{ if(color[u] == color[v]) //graph is not bipartite return 0; } } } //graph is bipartite return 1; } int main() { int n, m; std::cin >> n >> m; vector<vector<int> > adj(n, vector<int>()); for (int i = 0; i < m; i++) { int x, y; std::cin >> x >> y; adj[x - 1].push_back(y - 1); adj[y - 1].push_back(x - 1); } std::cout << is_bipartite(adj); }
21.508197
70
0.529726
[ "vector" ]
349353056adafe5140ea16d36ff47ec9fb163627
18,526
cpp
C++
auxprogs/utrrnaseq/src/Genomic_Data.cpp
sestaton/Augustus
893e0b21fa90bd57fcd0dff2c1e849e88bb02049
[ "Artistic-1.0" ]
178
2018-05-25T09:51:13.000Z
2022-03-30T13:55:58.000Z
auxprogs/utrrnaseq/src/Genomic_Data.cpp
sestaton/Augustus
893e0b21fa90bd57fcd0dff2c1e849e88bb02049
[ "Artistic-1.0" ]
249
2018-07-02T07:03:12.000Z
2022-03-30T00:01:01.000Z
auxprogs/utrrnaseq/src/Genomic_Data.cpp
sestaton/Augustus
893e0b21fa90bd57fcd0dff2c1e849e88bb02049
[ "Artistic-1.0" ]
95
2018-08-21T21:33:19.000Z
2022-03-30T13:56:00.000Z
/* * \file Genomic_Data.cpp */ #include "Genomic_Data.hpp" #include "Global.hpp" #include "Supporting_Methods.hpp" #include "Splice_Sites.hpp" #include "Error.hpp" #include <string> #include <vector> #include <utility> #include <iostream> #include <fstream> #include <sstream> #include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <iterator> #include <boost/assign/std/vector.hpp> #include <boost/foreach.hpp> #include <boost/lexical_cast.hpp> std::vector<Genomic_Data::Scaff_plus_Gen_Data> Genomic_Data::s_all_genes; std::vector< std::pair <std::string, std::string> > Genomic_Data::s_sp_sites; using namespace std; using namespace boost; using namespace boost::assign; // Determine the start and end positions of runs (i.e. stretches) of lower case letters vector< pair<unsigned, unsigned> > lower_case_runs(string str) { // Iterate through the string, storing runs on the fly vector< pair<unsigned, unsigned> > ret; unsigned i = 0; bool prev_lc = false; // Was the previous character lower case? unsigned start; while (i < str.length()) { bool curr_lc = islower( char( str[i] ) ); // Is the current character lower case if (prev_lc) { if (!curr_lc) { unsigned end = i - 1; ret += make_pair(start, end); prev_lc = false; } } else { if (curr_lc) { start = i; prev_lc = true; } } ++i; } if (prev_lc) { // Is the last character of the string lower case? unsigned end = i - 1; ret += make_pair(start, end); } return ret; } void Genomic_Data::initialize(string scaff_fname, string crb_fname, string intron_fname, string repeat_fname, vector< pair<string, string> > sp_sites, bool use_repeat_file) { s_all_genes.clear(); s_sp_sites = sp_sites; read_scaff_file(scaff_fname); read_crb_file(crb_fname); read_intron_file(intron_fname); if (use_repeat_file) read_repeat_file(repeat_fname); cout << "Input Data processing finished successfully!" << endl; //cout << __FILE__ << " " << __FUNCTION__ << " " << __LINE__ << endl; } void Genomic_Data::read_scaff_file(string scaff_fname) { ifstream scaff_ifstream(scaff_fname.c_str()); if (!scaff_ifstream) { ERR_STRM << "Error in scaffold file: Could not open '" << scaff_fname << "'!" << endl; cout << __FILE__ << " " << __FUNCTION__ << " " << __LINE__ << endl; abort(); } Scaff_plus_Gen_Data seq; string str; string gene; string scaffold_name; bool first_scaff = true; bool corrupted_scaff = false; unsigned curr_scaff_row_idx = 0; while (getline(scaff_ifstream, str)) { ++curr_scaff_row_idx; if (str.empty()) { continue; } if (str[0] == ';') { continue; //comment } int position = str.find(">"); switch (position) { case 0: scaffold_name = str.substr(1); //line only includes ">Name", uses string from Position 1 until the end of scaffold name if (first_scaff) { seq.name = scaffold_name; first_scaff = false; } else { if (gene.empty()) { ERR_STRM << "Error in scaffold file (line " << curr_scaff_row_idx - 1 << "): Empty scaffold found in '" << seq.name << "'!" << endl; cout << __FILE__ << " " << __FUNCTION__ << " " << __LINE__ << endl; seq.name = scaffold_name; } else { if (!corrupted_scaff) { // One whole scaffold finished -> saved and new scaffold started -> scaffold name saved seq.sequence = gene; s_all_genes += seq; gene.clear(); seq.name = scaffold_name; } else { corrupted_scaff = false; //scaffold is invalid, it will not be saved gene.clear(); seq.name = scaffold_name; } } } break; case -1: //> not found, scaffold in this line gene += str; break; default: //> in position other than the first -> Error if (gene.empty()) { ERR_STRM << "Error in scaffold file (line " << curr_scaff_row_idx - 1 << "): Empty scaffold found in '" << seq.name << "'!" << endl; cout << __FILE__ << " " << __FUNCTION__ << " " << __LINE__ << endl; } else { if (!corrupted_scaff) { seq.sequence = gene; s_all_genes += seq; gene.clear(); } else { corrupted_scaff = false; //scaffold is invalid, it will not be saved gene.clear(); } } ERR_STRM << "Error in scaffold file (line " << curr_scaff_row_idx << "): > in '" << str << "' is not first character in its line!" << endl; cout << __FILE__ << " " << __FUNCTION__ << " " << __LINE__ << endl; corrupted_scaff = true; //continue; } } if (gene.empty()) { ERR_STRM << "Error in scaffold file (line " << curr_scaff_row_idx - 1 << "): Empty scaffold found in '" << seq.name << "'!" << endl; cout << __FILE__ << " " << __FUNCTION__ << " " << __LINE__ << endl; } else { if (!corrupted_scaff) { vector< pair<unsigned, unsigned> > v = lower_case_runs(gene); typedef pair<unsigned, unsigned> pr_type; BOOST_FOREACH(pr_type pr, v) { Repeat r = { pr.first + 1, pr.second + 1 }; // Strings are 0-based, gene coordinates are 1-based seq.repeats += r; } seq.sequence = gene; s_all_genes += seq; gene.clear(); seq.name = scaffold_name; } } //else unnecessary, because it was the last scaffold in the file and this last gene was corrupted scaff_ifstream.close(); cout << "Read in of scaffold file finished successfully!" << endl; } void Genomic_Data::read_crb_file(string crb_fname) { ifstream crb_ifstream(crb_fname.c_str()); if (!crb_ifstream) { ERR_STRM << "Error (in coding region file): Could not open '" << crb_fname << "'!" << endl; abort(); } //Fields of the GFF Format const unsigned COLUMN_NO = 9; const unsigned SEQNAME_IDX = 0; const unsigned FEATURE_IDX = 2; const unsigned STOP_CODON_IDX = 4; const unsigned STRAND_IDX = 6; const unsigned GROUP_IDX = 8; //including transcript_id and gene_id string str; CRB curr_crb_row; unsigned idx_curr_crb_row = 0; while (getline(crb_ifstream, str)) { ++idx_curr_crb_row; if (str.empty()) { continue; } if ( (str[0] == '#') && (str[1] == '#') ) { continue; //comment } vector<string> tokens = tokenize("\t", str); if (tokens.size() != COLUMN_NO) { ERR_STRM << "Error in coding region file (line " << idx_curr_crb_row << "): '" << str << "' does not have the right number of columns!" << endl; cout << __FILE__ << " " << __FUNCTION__ << " " << __LINE__ << endl; continue; } //=======SEQ_NAME======= bool seqname_in_scaff_file = false; unsigned scaff_idx_curr_crb; unsigned idx_curr_scaff = 0; while ( ( !seqname_in_scaff_file ) && ( idx_curr_scaff < s_all_genes.size() ) ) { const Scaff_plus_Gen_Data& curr_scaff = s_all_genes[idx_curr_scaff]; if (curr_scaff.name == tokens[SEQNAME_IDX] ) { seqname_in_scaff_file = true; scaff_idx_curr_crb = idx_curr_scaff; } ++idx_curr_scaff; } if (!seqname_in_scaff_file) { ERR_STRM << "Error in coding region file (line " << idx_curr_crb_row << "): '" << str << "' contains a sequence name, which is not in the scaffold file!" << endl; cout << __FILE__ << " " << __FUNCTION__ << " " << __LINE__ << endl; continue; } //======FEATURE======== if (tokens[FEATURE_IDX] == "start_codon") { curr_crb_row.feature = "start"; } else { if (tokens[FEATURE_IDX] == "stop_codon") { curr_crb_row.feature = "stop"; } else { ERR_STRM << "Error in coding region file (line " << idx_curr_crb_row << "): In '" << str << "' only start_codon or stop_codon are allowed as features!" << endl; cout << __FILE__ << " " << __FUNCTION__ << " " << __LINE__ << endl; continue; //Feature is not "stop_codon" nor "start_codon" } } //======CODON/STRAND======== try { curr_crb_row.codon_pos = lexical_cast<unsigned>( tokens[STOP_CODON_IDX] ); } catch (bad_lexical_cast const&) { ERR_STRM << "Error in coding region file (line " << idx_curr_crb_row << "): '" << str << "' contains a codon position which is not an integer!" << endl; cout << __FILE__ << " " << __FUNCTION__ << " " << __LINE__ << endl; continue; } //could also use start_codon => tokens[3] if ( (tokens[STRAND_IDX] != "+" ) && ( tokens[STRAND_IDX] != "-" ) ) { ERR_STRM << "Error in coding region file (line " << idx_curr_crb_row << "): '" << str << "' contains a strand other than '+' and '-'" << endl; cout << __FILE__ << " " << __FUNCTION__ << " " << __LINE__ << endl; continue; } curr_crb_row.strand = tokens[STRAND_IDX]; if ( ( (curr_crb_row.strand == "+") && (curr_crb_row.feature == "start") ) || ( (curr_crb_row.strand == "-") && (curr_crb_row.feature == "stop") ) ) { curr_crb_row.codon_pos -= 2; } //=============GROUP=========== curr_crb_row.grp_att = tokens[GROUP_IDX]; s_all_genes[scaff_idx_curr_crb].crbs += curr_crb_row; } crb_ifstream.close(); cout << "Read in of coding region file finished successfully!" << endl; } void Genomic_Data::read_intron_file(string intron_fname) { ifstream intron_ifstream(intron_fname.c_str()); if (!intron_ifstream) { ERR_STRM << "Error in intron file: Could not open '" << intron_fname << "'!" << endl; cout << __FILE__ << " " << __FUNCTION__ << " " << __LINE__ << endl; abort(); } //necessary fields of GFF Format const unsigned COLUMN_NO = 9; const unsigned SEQNAME_IDX = 0; const unsigned FEATURE_IDX = 2; const unsigned START_IDX = 3; const unsigned END_IDX = 4; const unsigned STRAND_IDX = 6; const unsigned MULT_IDX = 8; string str; Intron curr_intron_row; unsigned curr_intron_row_idx = 0; bool intron_accepted; while (getline(intron_ifstream, str)) { ++curr_intron_row_idx; intron_accepted = true; if (str.empty()) { continue; } if ( (str[0] == '#') && (str[1] == '#')) { continue; //comment } vector<string> tokens = tokenize("\t", str); if (tokens.size() != COLUMN_NO) { ERR_STRM << "Error in intron file (line " << curr_intron_row_idx << "): '" << str << "' does not have the right number of columns!" << endl; cout << __FILE__ << " " << __FUNCTION__ << " " << __LINE__ << endl; continue; } //=========SEQ_NAME============= bool seqname_in_scaff_file = false; unsigned scaff_idx_curr_intron; unsigned idx_curr_scaff = 0; while ( ( !seqname_in_scaff_file ) && ( idx_curr_scaff < s_all_genes.size() ) ) { const Scaff_plus_Gen_Data& curr_scaff = s_all_genes[idx_curr_scaff]; if (curr_scaff.name == tokens[SEQNAME_IDX] ) { seqname_in_scaff_file = true; scaff_idx_curr_intron = idx_curr_scaff; } ++idx_curr_scaff; } if (!seqname_in_scaff_file) { ERR_STRM << "Error in intron file (line " << curr_intron_row_idx << "): '" << str << "' contains a sequence name, which is not in the scaffold file!" << endl; cout << __FILE__ << " " << __FUNCTION__ << " " << __LINE__ << endl; continue; } //======FEATURE (only test) ======= if (tokens[FEATURE_IDX] != "intron") { ERR_STRM << "Error in intron file (line " << curr_intron_row_idx << "): Feature in line '" << str << "' does not have the feature type 'intron'!" << endl; cout << __FILE__ << " " << __FUNCTION__ << " " << __LINE__ << endl; continue; } //=======START/END/STRAND========== unsigned start; unsigned end; try { start = lexical_cast<unsigned>(tokens[START_IDX]); end = lexical_cast<unsigned>(tokens[END_IDX]); } catch (bad_lexical_cast const&) { ERR_STRM << "Error in intron file (line " << curr_intron_row_idx << "): '" << str << "' contains a coordinate which is not an integer!" << endl; cout << __FILE__ << " " << __FUNCTION__ << " " << __LINE__ << endl; continue; } if ( (tokens[STRAND_IDX] != "+" ) && ( tokens[STRAND_IDX] != "-" ) && ( tokens[STRAND_IDX] != "." ) ) { ERR_STRM << "Error in intron file (line " << curr_intron_row_idx << "): '" << str << "' contains a strand other than '+', '-' and '.' ." << endl; cout << __FILE__ << " " << __FUNCTION__ << " " << __LINE__ << endl; continue; } pair<bool, string> intron_valid; bool strand_defined = tokens[STRAND_IDX] != "." ? true : false; if (!s_sp_sites.empty() && !strand_defined) { //if empty no splice site filtering, intron_accepted always true intron_valid = check_sp_sites(s_sp_sites, s_all_genes[scaff_idx_curr_intron].sequence, start, end, strand_defined, tokens[STRAND_IDX] ); } else { if (s_sp_sites.empty() && !strand_defined) { ERR_STRM << "Error in intron file (line " << curr_intron_row_idx << "): '" << str << "' contains an undefined strand '.'. In this case at least one splice site " << "must be given to check for splice sites and define the strand." << endl; cout << __FILE__ << " " << __FUNCTION__ << " " << __LINE__ << endl; throw Error(); } else { intron_valid.first = true; } } if (!intron_valid.first) { continue; //intron not accepted } if (tokens[STRAND_IDX] == ".") { curr_intron_row.strand = intron_valid.second; } else { curr_intron_row.strand = tokens[STRAND_IDX]; } if (curr_intron_row.strand == "+") { curr_intron_row.start = start; curr_intron_row.end = end; } else { //minus strand curr_intron_row.start = end; curr_intron_row.end = start; } //============MULT=================== string mult_str = tokens[MULT_IDX]; string::size_type pos_grp, pos_group; pos_grp = mult_str.find("grp="); pos_group = mult_str.find("group="); string mult_value_str; if ( (pos_grp != mult_str.npos) || (pos_group != mult_str.npos) ) { mult_value_str = "1"; } else { unsigned pos = mult_str.find("mult="); unsigned mult_length = 0; unsigned mult_pos = pos + 5; bool mult_found = false; while ( (!mult_found) && ( (mult_pos + mult_length) < mult_str.length()) ) { char tested_char = mult_str[mult_pos + mult_length]; if ( isdigit(tested_char) ) { mult_length++; } else { mult_found = true; } } mult_value_str = mult_str.substr(mult_pos, mult_length); } try { curr_intron_row.mult = lexical_cast<unsigned>( mult_value_str ); } catch (bad_lexical_cast const&) { ERR_STRM << "Error in intron file (line " << curr_intron_row_idx << "): '" << str << "' contains a multiplicity which is not an integer!" << endl; cout << __FILE__ << " " << __FUNCTION__ << " " << __LINE__ << endl; continue; } if (intron_accepted) { s_all_genes[scaff_idx_curr_intron].introns += curr_intron_row; } //else intron not accepted, because of a wrong or unaccepted splice site } intron_ifstream.close(); cout << "Read in of intron file finished successfully!" << endl; } void Genomic_Data::read_repeat_file(string repeat_fname) { ifstream repeat_ifstream( repeat_fname.c_str() ); if (!repeat_ifstream) { ERR_STRM << "Error in repeat file: Could not open '" << repeat_fname << "'!" << endl; cout << __FILE__ << " " << __FUNCTION__ << " " << __LINE__ << endl; abort(); } //necessary fields of GFF Format const unsigned COLUMN_NO = 9; const unsigned SEQNAME_IDX = 0; const unsigned FEATURE_IDX = 2; const unsigned START_IDX = 3; const unsigned END_IDX = 4; string str; Repeat curr_repeat_row; unsigned curr_repeat_row_idx = 0; while (getline(repeat_ifstream, str)) { ++curr_repeat_row_idx; if (str.empty()) { continue; } if ( (str[0] == '#') && (str[1] == '#')) { continue; //comment } vector<string> tokens = tokenize("\t", str); if (tokens.size() != COLUMN_NO) { ERR_STRM << "Error in repeat file (line " << curr_repeat_row_idx << "): '" << str << "' does not have the right number of columns!" << endl; cout << __FILE__ << " " << __FUNCTION__ << " " << __LINE__ << endl; continue; } //=========SEQ_NAME============= bool seqname_in_scaff_file = false; unsigned scaff_idx_curr_repeat; unsigned idx_curr_scaff = 0; while ( ( !seqname_in_scaff_file ) && ( idx_curr_scaff < s_all_genes.size() ) ) { const Scaff_plus_Gen_Data& curr_scaff = s_all_genes[idx_curr_scaff]; if (curr_scaff.name == tokens[SEQNAME_IDX] ) { seqname_in_scaff_file = true; scaff_idx_curr_repeat = idx_curr_scaff; } ++idx_curr_scaff; } if (!seqname_in_scaff_file) { ERR_STRM << "Error in repeat file (line " << curr_repeat_row_idx << "): '" << str << "' contains a sequence name, which is not in the scaffold file!" << endl; cout << __FILE__ << " " << __FUNCTION__ << " " << __LINE__ << endl; continue; } //======FEATURE (only test) ======= if (tokens[FEATURE_IDX] != "nonexonpart") { ERR_STRM << "Error in repeat (line " << curr_repeat_row_idx << "): Feature in line '" << str << "' is not 'nonexonpart'!" << endl; cout << __FILE__ << " " << __FUNCTION__ << " " << __LINE__ << endl; continue; } //===============START/END=================== try { curr_repeat_row.start = lexical_cast<unsigned>(tokens[START_IDX]); curr_repeat_row.end = lexical_cast<unsigned>(tokens[END_IDX]); } catch (bad_lexical_cast const&) { ERR_STRM << "Error in repeat file (line " << curr_repeat_row_idx << "): '" << str << "' contains a coordinate which is not an integer!" << endl; cout << __FILE__ << " " << __FUNCTION__ << " " << __LINE__ << endl; continue; } s_all_genes[scaff_idx_curr_repeat].repeats += curr_repeat_row; } repeat_ifstream.close(); cout << "Read in of repeat file finished successfully!" << endl; } bool Genomic_Data::Intron::is_overlapping(Intron i, Intron j) { int i_first = (i.strand == "+") ? i.start : i.end; int i_second = (i.strand == "+") ? i.end : i.start; int j_first = (j.strand == "+") ? j.start : j.end; int j_second = (j.strand == "+") ? j.end : j.start; bool first_opt = (j_first <= i_second) && (j_first >= i_first); bool second_opt = (j_second <= i_second) && (j_second >= i_first); bool third_opt = (j_first <= i_first) && (j_second >= i_second); // introns are not allowed to be immediate neighbours without spacer (this is not an overlap) bool fourth_opt = (i_second == (j_first - 1)) || (j_second == (i_first - 1)); return first_opt || second_opt || third_opt || fourth_opt; } bool Genomic_Data::Repeat::operator==(const Repeat &r) const { return (start == r.start) && (end == r.end); } ostream& operator<<(ostream& os, const Genomic_Data::Repeat& r) { os << "[" << r.start << "," << r.end << "]"; return os; }
29.6416
152
0.619994
[ "vector" ]
34957473c5142f81c1f299765ba057e28bda5415
11,138
cpp
C++
src/dispatcher.cpp
hugo19941994/SpaceInvaders-Emu
cdff147ac1eb6fb5da8d0242e23015f9270a9cbd
[ "MIT" ]
1
2020-03-02T23:28:57.000Z
2020-03-02T23:28:57.000Z
src/dispatcher.cpp
hugo19941994/SpaceInvaders-Emu
cdff147ac1eb6fb5da8d0242e23015f9270a9cbd
[ "MIT" ]
null
null
null
src/dispatcher.cpp
hugo19941994/SpaceInvaders-Emu
cdff147ac1eb6fb5da8d0242e23015f9270a9cbd
[ "MIT" ]
1
2020-03-02T23:28:58.000Z
2020-03-02T23:28:58.000Z
#include "emu.h" #include <array> #include <cstdio> #include <cstdlib> #include <iostream> #include <map> #include <vector> // Macro to avoid verbose switch syntax // https://gitlab.com/higan/higan/blob/master/higan/processor/mos6502/disassembler.cpp #define op(id, oper) \ case id: \ oper; \ break; void intel8080::emulateCycle() { uint8_t *opcode = &memory.at(pc); switch (*opcode) { op(0x00, NOP()); op(0x08, NOP()); op(0x10, NOP()); op(0x18, NOP()); op(0x20, NOP()); op(0x28, NOP()); op(0x30, NOP()); op(0x38, NOP()); op(0x01, LXI(&B, &C)); op(0x11, LXI(&D, &E)); op(0x21, LXI(&H, &L)); op(0x31, LXI(&sp)); op(0x05, DCR(&B, 5)); op(0x0d, DCR(&C, 5)); op(0x15, DCR(&D, 5)); op(0x1D, DCR(&E, 5)); op(0x25, DCR(&H, 5)); op(0x2D, DCR(&L, 5)); op(0x35, DCR(memHL(), 10)); op(0x3d, DCR(&A, 5)); op(0x02, STAX(&B, &C)); op(0x12, STAX(&D, &E)); op(0x03, INX(&B, &C)); op(0x13, INX(&D, &E)); op(0x23, INX(&H, &L)); op(0x33, INX(&sp)); op(0x40, MOV(&B, &B, 5)); op(0x41, MOV(&B, &C, 5)); op(0x42, MOV(&B, &D, 5)); op(0x43, MOV(&B, &E, 5)); op(0x44, MOV(&B, &H, 5)); op(0x45, MOV(&B, &L, 5)); op(0x46, MOV(&B, memHL(), 7)); op(0x47, MOV(&B, &A, 5)); op(0x48, MOV(&C, &B, 5)); op(0x49, MOV(&C, &C, 5)); op(0x4A, MOV(&C, &D, 5)); op(0x4B, MOV(&C, &E, 5)); op(0x4C, MOV(&C, &H, 5)); op(0x4D, MOV(&C, &L, 5)); op(0x4E, MOV(&C, memHL(), 7)); op(0x4F, MOV(&C, &A, 5)); op(0x50, MOV(&D, &B, 5)); op(0x51, MOV(&D, &C, 5)); op(0x52, MOV(&D, &D, 5)); op(0x53, MOV(&D, &E, 5)); op(0x54, MOV(&D, &H, 5)); op(0x55, MOV(&D, &L, 5)); op(0x56, MOV(&D, memHL(), 7)); op(0x57, MOV(&D, &A, 5)); op(0x58, MOV(&E, &B, 5)); op(0x59, MOV(&E, &C, 5)); op(0x5A, MOV(&E, &D, 5)); op(0x5B, MOV(&E, &E, 5)); op(0x5C, MOV(&E, &H, 5)); op(0x5D, MOV(&E, &L, 5)); op(0x5E, MOV(&E, memHL(), 7)); op(0x5F, MOV(&E, &A, 5)); op(0x60, MOV(&H, &B, 5)); op(0x61, MOV(&H, &C, 5)); op(0x62, MOV(&H, &D, 5)); op(0x63, MOV(&H, &E, 5)); op(0x64, MOV(&H, &H, 5)); op(0x65, MOV(&H, &L, 5)); op(0x66, MOV(&H, memHL(), 7)); op(0x67, MOV(&H, &A, 5)); op(0x68, MOV(&L, &B, 5)); op(0x69, MOV(&L, &C, 5)); op(0x6A, MOV(&L, &D, 5)); op(0x6B, MOV(&L, &E, 5)); op(0x6C, MOV(&L, &H, 5)); op(0x6D, MOV(&L, &L, 5)); op(0x6E, MOV(&L, memHL(), 7)); op(0x6F, MOV(&L, &A, 5)); op(0x70, MOV(memHL(), &B, 7)); op(0x71, MOV(memHL(), &C, 7)); op(0x72, MOV(memHL(), &D, 7)); op(0x73, MOV(memHL(), &E, 7)); op(0x74, MOV(memHL(), &H, 7)); op(0x75, MOV(memHL(), &L, 7)); op(0x77, MOV(memHL(), &A, 7)); op(0x78, MOV(&A, &B, 5)); op(0x79, MOV(&A, &C, 5)); op(0x7A, MOV(&A, &D, 5)); op(0x7B, MOV(&A, &E, 5)); op(0x7C, MOV(&A, &H, 5)); op(0x7D, MOV(&A, &L, 5)); op(0x7E, MOV(&A, memHL(), 7)); op(0x7F, MOV(&A, &A, 5)); op(0x04, INR(&B, 5)); op(0x0C, INR(&C, 5)); op(0x14, INR(&D, 5)); op(0x1C, INR(&E, 5)); op(0x24, INR(&H, 5)); op(0x2C, INR(&L, 5)); op(0x34, INR(memHL(), 10)); op(0x3C, INR(&A, 5)); op(0x0B, DCX(&B, &C)); op(0x1B, DCX(&D, &E)); op(0x2B, DCX(&H, &L)); op(0x3B, DCX(&sp)); op(0x06, MVI(&B, 7)); op(0x0E, MVI(&C, 7)); op(0x16, MVI(&D, 7)); op(0x1E, MVI(&E, 7)); op(0x26, MVI(&H, 7)); op(0x2E, MVI(&L, 7)); op(0x36, MVI(memHL(), 10)); op(0x3E, MVI(&A, 7)); op(0x09, DAD(&B, &C)); op(0x19, DAD(&D, &E)); op(0x29, DAD(&H, &L)); op(0x39, DAD(&sp)); op(0x0A, LDAX(&B, &C)); op(0x1A, LDAX(&D, &E)); op(0x80, ADD(&B, 4)); op(0x81, ADD(&C, 4)); op(0x82, ADD(&D, 4)); op(0x83, ADD(&E, 4)); op(0x84, ADD(&H, 4)); op(0x85, ADD(&L, 4)); op(0x86, ADD(memHL(), 7)); op(0x87, ADD(&A, 4)); op(0x88, ADC(&B, 4)); op(0x89, ADC(&C, 4)); op(0x8A, ADC(&D, 4)); op(0x8B, ADC(&E, 4)); op(0x8C, ADC(&H, 4)); op(0x8D, ADC(&L, 4)); op(0x8E, ADC(memHL(), 7)); op(0x8F, ADC(&A, 4)); op(0x90, SUB(&B, 4)); op(0x91, SUB(&C, 4)); op(0x92, SUB(&D, 4)); op(0x93, SUB(&E, 4)); op(0x94, SUB(&H, 4)); op(0x95, SUB(&L, 4)); op(0x96, SUB(memHL(), 7)); op(0x97, SUB(&A, 4)); op(0x98, SBB(&B, 4)); op(0x99, SBB(&C, 4)); op(0x9A, SBB(&D, 4)); op(0x9B, SBB(&E, 4)); op(0x9C, SBB(&H, 4)); op(0x9D, SBB(&L, 4)); op(0x9E, SBB(memHL(), 7)); op(0x9F, SBB(&A, 4)); op(0xA0, ANA(&B, 4)); op(0xA1, ANA(&C, 4)); op(0xA2, ANA(&D, 4)); op(0xA3, ANA(&E, 4)); op(0xA4, ANA(&H, 4)); op(0xA5, ANA(&L, 4)); op(0xA6, ANA(memHL(), 7)); op(0xA7, ANA(&A, 4)); op(0xA8, XRA(&B, 4)); op(0xA9, XRA(&C, 4)); op(0xAA, XRA(&D, 4)); op(0xAB, XRA(&E, 4)); op(0xAC, XRA(&H, 4)); op(0xAD, XRA(&L, 4)); op(0xAE, XRA(memHL(), 7)); op(0xAF, XRA(&A, 4)); op(0xB0, ORA(&B, 4)); op(0xB1, ORA(&C, 4)); op(0xB2, ORA(&D, 4)); op(0xB3, ORA(&E, 4)); op(0xB4, ORA(&H, 4)); op(0xB5, ORA(&L, 4)); op(0xB6, ORA(memHL(), 7)); op(0xB7, ORA(&A, 4)); op(0xB8, CMP(&B, 4)); op(0xB9, CMP(&C, 4)); op(0xBA, CMP(&D, 4)); op(0xBB, CMP(&E, 4)); op(0xBC, CMP(&H, 4)); op(0xBD, CMP(&L, 4)); op(0xBE, CMP(memHL(), 7)); op(0xBF, CMP(&A, 4)); op(0xC2, jump(!f.Z)); // JNZ op(0xC3, jump(true)); // JMP op(0xCA, jump(f.Z)); // JZ op(0xCB, jump(true)); // JZ op(0xD2, jump(!f.CY)); // JNC op(0xDA, jump(f.CY)); // JC op(0xE2, jump(!f.P)); // JNC op(0xEA, jump(f.P)); // JNC op(0xF2, jump(!f.S)); // JM op(0xFA, jump(f.S)); // JM op(0xC0, ret(!f.Z)); op(0xC8, ret(f.Z)); op(0xC9, ret(true)); op(0xD0, ret(!f.CY)); op(0xD8, ret(f.CY)); op(0xD9, ret(true)); op(0xE0, ret(!f.P)); op(0xE8, ret(f.P)); op(0xF0, ret(!f.S)); op(0xFF, ret(f.S)); op(0xC4, call(!f.Z)); op(0xCC, call(f.Z)); op(0xCD, call(true)); op(0xD4, call(!f.CY)); op(0xDC, call(f.CY)); op(0xDD, call(true)); op(0xE4, call(!f.P)); op(0xEC, call(f.P)); op(0xED, call(true)); op(0xF4, call(!f.S)); op(0xFC, call(f.S)); op(0xFD, call(true)); op(0xC1, POP(&B, &C)); op(0xD1, POP(&D, &E)); op(0xE1, POP(&H, &L)); op(0xF1, POP(&A, &f)); op(0xC5, PUSH(&B, C)); op(0xD5, PUSH(&D, E)); op(0xE5, PUSH(&H, L)); op(0xF5, PUSH(&A, f.psw())); op(0xEB, exchange(&H, &L, &D, &E, 5)); // XCHG op(0xE3, exchange(&H, &L, &memory.at(sp + 1), &memory.at(sp), 18)); // XTHL op(0x22, storeLoadHL(true)); // SHLD op(0x2A, storeLoadHL(false)); // LHLD op(0xE9, putHL(&pc)); op(0xF9, putHL(&sp)); op(0x37, enableDisableCY(true)); // STC op(0x3F, enableDisableCY(false)); // CMC op(0xFB, enableDisableInterrupts(true)); // EI op(0xF3, enableDisableInterrupts(false)); // DI case (0x2f): // CMA A = ~A; cycles += 4; pc += 1; break; case (0x1f): { // RAR auto CYValue = static_cast<uint8_t>(f.CY); uint16_t result = (CYValue << 7) | (A >> 1); f.CY = static_cast<bool>(A & 0x1); A = result & 0x00FF; pc += 1; cycles += 4; break; } case (0x0f): { // RRC uint16_t result = ((A & 0x1) << 7) | (A >> 1); f.CY = static_cast<bool>(A & 0x1); A = result & 0x00FF; pc += 1; cycles += 4; break; } case (0x32): { // STA adr // (adr) <- A uint16_t adr = (memory.at(pc + 2) << 8) | memory.at(pc + 1); memory.at(adr) = A; pc += 3; cycles += 13; break; } case (0x3a): { // LDA adr // A <- (adr) uint16_t adr = (memory.at(pc + 2) << 8) | memory.at(pc + 1); A = memory.at(adr); pc += 3; cycles += 13; break; } case (0xc6): // ADI D8 // A <- A + byte f.CY = A > (0xFF - memory.at(pc + 1)); A += memory.at(pc + 1); f.Z = zero(A); f.S = sign(A); f.P = parity(A); // Auxiliary flag - NOT IMPLEMENTED pc += 2; cycles += 7; break; case (0xdb): { // IN para input if (memory.at(pc + 1) == 0x01) { A = Read0; } else if (memory.at(pc + 1) == 0x02) { A = Read1; } else if (memory.at(pc + 1) == 0x03) { int dwval = (shift1 << 8) | shift0; A = dwval >> (8 - noOfBitsToShift); } pc += 2; cycles += 10; break; } case (0xd3): // OUT D8 if (memory.at(pc + 1) == 0x02) { noOfBitsToShift = A & 0x7; } else if (memory.at(pc + 1) == 0x04) { shift0 = shift1; shift1 = A; } pc += 2; cycles += 10; break; case (0xe6): // ANI D8 // A <-A & data A &= memory.at(pc + 1); f.Z = zero(A); f.S = sign(A); f.P = parity(A); f.CY = false; // Carry bit is reset to zero // Auxiliary flag - NOT IMPLEMENTED pc += 2; cycles += 7; break; case (0xfe): { // CPI D8 uint8_t res = A - memory.at(pc + 1); f.CY = A < memory.at(pc + 1); f.Z = zero(res); f.S = sign(res); f.P = parity(res); pc += 2; cycles += 7; break; } case (0x27): { // DAA uint8_t ls = A & 0xf; if (ls > 9) { // Or AC A += 6; } uint8_t ms = (A & 0xf0) >> 4; if (ms > 9 || f.CY) { ms += 6; f.CY = ms > 0xf; ms &= 0xf; A &= 0xf; A |= (ms << 4); } f.Z = zero(A); f.S = sign(A); f.P = parity(A); pc += 1; cycles += 4; break; } case (0x17): { // RAL auto CYValue = static_cast<uint8_t>(f.CY); uint16_t result = (A << 1) | CYValue; f.CY = static_cast<bool>((A & 0x80) >> 7); A = result & 0x00FF; pc += 1; cycles += 4; break; } case (0x07): { // RLC uint16_t result = (A << 1) | ((A & 0x08) >> 7); f.CY = static_cast<bool>((A & 0x80) >> 7); A = result & 0x00FF; pc += 1; cycles += 4; break; } case (0xf6): // ORI d8 f.CY = A > (0xFF - memory.at(pc + 1)); A |= memory.at(pc + 1); f.Z = zero(A); f.S = sign(A); f.P = parity(A); // Auxiliary flag - NOT IMPLEMENTED pc += 2; cycles += 7; break; case (0xd6): // SUI d8 // Carry flag f.CY = A < memory.at(pc + 1); A -= memory.at(pc + 1); f.Z = zero(A); f.S = sign(A); f.P = parity(A); // Auxiliary flag - NOT IMPLEMENTED pc += 2; cycles += 7; break; case (0xde): { // SBI d8 auto CYValue = static_cast<uint8_t>(f.CY); uint16_t result = memory.at(pc + 1) + CYValue; f.CY = A < result; A -= result; f.Z = zero(A); f.S = sign(A); f.P = parity(A); // Auxiliary flag - NOT IMPLEMENTED pc += 2; cycles += 7; break; } default: std::cout << "ERROR " << std::bitset<8>(*opcode) << std::endl; cycles += 4; break; } } #undef op
21.796477
86
0.442539
[ "vector" ]
3495c7179314f654b3a3757dd2d166647e430265
3,102
cpp
C++
Examples/source/ManageBarcodeImages/SaveBarcodeImageToStreams.cpp
aspose-barcode/Aspose.Barcode-for-C
9741636d98a148d7438cc6ee790dc3c4bcc5a1e8
[ "MIT" ]
3
2018-12-07T18:39:59.000Z
2021-06-08T13:08:29.000Z
Examples/source/ManageBarcodeImages/SaveBarcodeImageToStreams.cpp
aspose-barcode/Aspose.Barcode-for-C
9741636d98a148d7438cc6ee790dc3c4bcc5a1e8
[ "MIT" ]
null
null
null
Examples/source/ManageBarcodeImages/SaveBarcodeImageToStreams.cpp
aspose-barcode/Aspose.Barcode-for-C
9741636d98a148d7438cc6ee790dc3c4bcc5a1e8
[ "MIT" ]
1
2018-07-13T14:22:11.000Z
2018-07-13T14:22:11.000Z
/* This project uses Automatic Package Restore feature of NuGet to resolve Aspose.BarCode for .NET API reference when the project is build. Please check https://docs.nuget.org/consume/nuget-faq for more information. If you do not wish to use NuGet, you can manually download Aspose.BarCode for .NET API from http://www.aspose.com/downloads, install it and then add its reference to this project. For any issues, questions or suggestions please feel free to contact us using http://www.aspose.com/community/forums/default.aspx */ #include "SaveBarcodeImageToStreams.h" #include <system/string.h> #include <system/shared_ptr.h> #include <system/object.h> #include <system/environment.h> #include <system/console.h> #include <system/io/memory_stream.h> #include <BarCodeRecognition/Recognition/RecognitionSession/DecodeTypes/SingleDecodeType.h> #include <BarCodeRecognition/Recognition/RecognitionSession/DecodeTypes/DecodeType.h> #include <BarCodeRecognition/Recognition/RecognitionSession/BarCodeReader.h> #include <Generation/EncodeTypes/SymbologyEncodeType.h> #include <Generation/EncodeTypes/EncodeTypes.h> #include <BarCode.Generation/BarcodeGenerator.h> #include <Generation/BarCodeImageFormat.h> #include <drawing/imaging/image_format.h> #include <drawing/bitmap.h> #include "RunExamples.h" using namespace Aspose::BarCode::Generation; using namespace Aspose::BarCode::BarCodeRecognition; namespace Aspose { namespace BarCode { namespace Examples { namespace CSharp { namespace ManageBarCodeImages { RTTI_INFO_IMPL_HASH(2389916122u, ::Aspose::BarCode::Examples::CSharp::ManageBarCodeImages::SaveBarcodeImageToStreams, ThisTypeBaseTypesInfo); void SaveBarcodeImageToStreams::Run() { //ExStart:SaveBarcodeImageToStreams // The path to the documents directory. System::String dataDir = RunExamples::GetDataDir_ManageBarCodesImages(); // Instantiate barcode object and set CodeText & Barcode Symbology System::SharedPtr<BarcodeGenerator> generator = System::MakeObject<BarcodeGenerator>(EncodeTypes::Code128, u"1234567"); // Create a memory stream object that would store barcode image in binary form System::SharedPtr<System::IO::MemoryStream> ms = System::MakeObject<System::IO::MemoryStream>(); // Call save method of BarCodeImage to store Png barcode image to memory stream generator->Save(ms, BarCodeImageFormat::Png); ms->set_Position(0); System::SharedPtr<BarCodeReader> reader = System::MakeObject<BarCodeReader>(ms, DecodeType::Code128); if(reader->Read()) System::Console::WriteLine(u"Barcode from stream recognized as " + reader->GetCodeText()); else System::Console::WriteLine(u"Barcode from stream failed to recognize"); //ExEnd:SaveBarcodeImageToStreams } } // namespace ManageBarCodeImages } // namespace CSharp } // namespace Examples } // namespace BarCode } // namespace Aspose
41.918919
146
0.727273
[ "object" ]
3496742989131efad2558f51bb3e905ad2cf3d03
8,012
cpp
C++
test/istrings.t.cpp
goto40/textx-cpp
1d8ea2802c99e0ec145f843e7fe1c23e3cc076d1
[ "MIT" ]
3
2021-12-08T14:42:04.000Z
2022-03-04T19:51:11.000Z
test/istrings.t.cpp
goto40/textx-cpp
1d8ea2802c99e0ec145f843e7fe1c23e3cc076d1
[ "MIT" ]
null
null
null
test/istrings.t.cpp
goto40/textx-cpp
1d8ea2802c99e0ec145f843e7fe1c23e3cc076d1
[ "MIT" ]
null
null
null
#include "catch.hpp" #include "textx/istrings.h" namespace { auto get_example_model() { auto mm = textx::metamodel_from_str(R"#( Model: 'shapes' info=STRING ':' shapes+=Shape[',']; Shape: Point|ComplexShape; ComplexShape: Circle|Line; Point: type_name="Point" '(' x=NUMBER ',' y=NUMBER ')'; Circle: type_name="Circle" '(' center=Point ',' r=NUMBER ')'; Line: type_name='Line' '(' p1=Point ',' p2=Point ')'; )#"); auto m = mm->model_from_str(R"( shapes "My Shapes": Point(1,2), Circle(Point(333,4.5),9), Line(Point(0,0),Point(1,1)) )"); return m; } } TEST_CASE("istrings_metamodel0", "[textx/istrings]") { auto model_text = R"( Hello World 123 )"; auto m = textx::istrings::get_istrings_metamodel_workspace()->model_from_str(model_text); CHECK( (*m)["parts"].size()==0 ); std::ostringstream s; for (auto &t: (*m)["text"]) { s << t["text"].str(); } CHECK( s.str() == model_text ); //std::cout << m->val() << "\n"; } TEST_CASE("istrings_metamodel1", "[textx/istrings]") { auto model_text = R"( Hello World {% model.x %} 123 )"; auto mm = textx::istrings::get_istrings_metamodel_workspace(); mm->get_metamodel_by_shortcut("ISTRINGS")->clear_builtin_models(); mm->get_metamodel_by_shortcut("ISTRINGS")->add_builtin_model( mm->model_from_str("EXTERNAL_LINKAGE","object model") ); auto m = mm->model_from_str(model_text); std::ostringstream s; for (auto &p: (*m)["parts"]) { for (auto &t: p["text"]) { s << t["text"].str(); } } for (auto &t: (*m)["text"]) { s << t["text"].str(); } CHECK( s.str().find("Hello World")>0 ); CHECK( s.str().find("123")>0 ); //std::cout << m->val() << "\n"; } TEST_CASE("istrings_metamodel2_str", "[textx/istrings]") { auto model = get_example_model(); auto res = textx::istrings::i( R"(info="{% model.info %}")", { {"model", model->val().obj()} } ); CHECK( res.size()>0 ); CHECK( res == "info=\"My Shapes\""); // res = textx::istrings::i( // R"(info='{% model.info %}\n123')", // { {"model", model->val().obj()} } // ); // CHECK( res.size()>0 ); // CHECK( res == "info='My"Shapes"\n123"); } TEST_CASE("istrings_metamodel3_forloop", "[textx/istrings]") { auto model = get_example_model(); auto res = textx::istrings::i( R"( info="{% model.info %}" -0------ {% FOR o: model.shapes %} inner_type: {% o.type_name %} {% ENDFOR %} ------- )", { {"model", model->val().obj()} } ); CHECK( res.size()>0 ); //std::cout << res << "\n"; CHECK( res == R"( info="My Shapes" -0------ inner_type: Point inner_type: Circle inner_type: Line ------- )"); } TEST_CASE("istrings_metamodel3_forloop_indent_removed", "[textx/istrings]") { auto model = get_example_model(); auto res = textx::istrings::i( R"( info="{% model.info %}" -1------ {% FOR o: model.shapes %} inner_type: {% o.type_name %} {% ENDFOR %} ------- )", { {"model", model->val().obj()} } ); CHECK( res.size()>0 ); //std::cout << res << "\n"; CHECK( res == R"( info="My Shapes" -1------ inner_type: Point inner_type: Circle inner_type: Line ------- )"); } TEST_CASE("istrings_metamodel3_forloop_indent_active", "[textx/istrings]") { auto model = get_example_model(); auto res = textx::istrings::i( R"( info="{% model.info %}" -2------ {% FOR o: model.shapes %} inner_type: {% o.type_name %} {% ENDFOR %} ------- )", { {"model", model->val().obj()} } ); CHECK( res.size()>0 ); //std::cout << res << "\n"; CHECK( res == R"( info="My Shapes" -2------ inner_type: Point inner_type: Circle inner_type: Line ------- )"); } TEST_CASE("istrings_metamodel3_forloop_inline", "[textx/istrings]") { auto model = get_example_model(); auto res = textx::istrings::i( R"( info="{% model.info %}" ------- inline:{% FOR o: model.shapes %} {% o.type_name %}{% ENDFOR %} ------- )", { {"model", model->val().obj()} } ); CHECK( res.size()>0 ); //std::cout << res << "\n"; CHECK( res == R"( info="My Shapes" ------- inline: Point Circle Line ------- )"); } TEST_CASE("istrings_metamodel4_functions", "[textx/istrings]") { auto model = get_example_model(); auto res = textx::istrings::i( R"( info="{% model.info %}" ------- {% FOR o: model.shapes %} {% print(o) %} {% ENDFOR %} ------- )", { {"model", model->val().obj()}, {"print", [](std::shared_ptr<textx::object::Object> o) -> std::string { std::ostringstream s; o->print(s); return s.str(); } } } ); //std::cout << res << "\n"; CHECK( res == R"( info="My Shapes" ------- Point{ type_name= "Point" x= 1 y= 2 } Circle{ type_name= "Circle" center= Point{ type_name= "Point" x= 333 y= 4.5 } r= 9 } Line{ type_name= "Line" p1= Point{ type_name= "Point" x= 0 y= 0 } p2= Point{ type_name= "Point" x= 1 y= 1 } } ------- )"); } TEST_CASE("istrings_metamodel4_functions_plus_newline", "[textx/istrings]") { auto model = get_example_model(); auto res = textx::istrings::i( R"( info="{% model.info %}" ------- {% FOR o: model.shapes %} {% print(o) %} x {% ENDFOR %} ------- )", { {"model", model->val().obj()}, {"print", [](std::shared_ptr<textx::object::Object> o) -> std::string { std::ostringstream s; o->print(s); return s.str(); } } } ); //std::cout << res << "\n"; CHECK( res == R"( info="My Shapes" ------- Point{ type_name= "Point" x= 1 y= 2 } x Circle{ type_name= "Circle" center= Point{ type_name= "Point" x= 333 y= 4.5 } r= 9 } x Line{ type_name= "Line" p1= Point{ type_name= "Point" x= 0 y= 0 } p2= Point{ type_name= "Point" x= 1 y= 1 } } x ------- )"); } TEST_CASE("istrings_array_access", "[textx/istrings]") { auto model = get_example_model(); auto res = textx::istrings::i( R"( shape[1]="{% model.shapes[1].type_name %}" {% print(model.shapes[1]) %} )", { {"model", model->val().obj()}, {"print", [](std::shared_ptr<textx::object::Object> o) -> std::string { std::ostringstream s; o->print(s); return s.str(); } } } ); //std::cout << res; CHECK( res == R"#( shape[1]="Circle" Circle{ type_name= "Circle" center= Point{ type_name= "Point" x= 333 y= 4.5 } r= 9 } )#"); }
20.283544
93
0.432351
[ "object", "shape", "model" ]
34a8df10ac13852bba10d7f05779a8125bf9730b
6,607
cc
C++
browser_project/handlers/render_handler.cc
jsgrowing315/crawling
e75e7559cf4a7010dde423a23d01d7653e06dbff
[ "BSD-3-Clause" ]
null
null
null
browser_project/handlers/render_handler.cc
jsgrowing315/crawling
e75e7559cf4a7010dde423a23d01d7653e06dbff
[ "BSD-3-Clause" ]
null
null
null
browser_project/handlers/render_handler.cc
jsgrowing315/crawling
e75e7559cf4a7010dde423a23d01d7653e06dbff
[ "BSD-3-Clause" ]
null
null
null
#include "../browser_handler.h" #include "../global.h" #include <sys/stat.h> #include <png.h> bool write_png_for_image(unsigned char* buffer, int width, int height,const char *filename) { FILE *fp; png_structp png_ptr; png_infop png_info_ptr; png_bytep png_row; fp = fopen(filename, "wb"); if (fp == NULL) { fprintf(stderr, "Could not open file for writing\n"); return false; } // Initialize write structure png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (png_ptr == NULL) { fprintf(stderr, "Could not allocate write struct\n"); return false; } // Initialize info structure png_info_ptr = png_create_info_struct(png_ptr); if (png_info_ptr == NULL) { fprintf(stderr, "Could not allocate info struct\n"); return false; } // Setup Exception handling if (setjmp(png_jmpbuf (png_ptr))) { fprintf(stderr, "Error during png creation\n"); return false; } png_init_io(png_ptr, fp); // Write header (8 bit colour depth) png_set_IHDR(png_ptr, png_info_ptr, width, height, 8, PNG_COLOR_TYPE_RGBA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); png_write_info(png_ptr, png_info_ptr); // Allocate memory for one row (4 bytes per pixel - RGBA) png_row = (png_bytep) malloc(4 * width * sizeof(png_byte)); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { unsigned char blue = buffer[width * y * 4 + x*4]; unsigned char green = buffer[width * y * 4 + x*4 +1]; unsigned char red = buffer[width * y * 4 + x*4 + 2]; unsigned char alpha = buffer[width * y * 4 + x*4 + 3]; png_byte *ptr = &(png_row[x * 4]); ptr[0] = red; ptr[1] = green; ptr[2] = blue; ptr[3] = alpha; } png_write_row(png_ptr, png_row); } png_write_end(png_ptr, NULL); fclose(fp); if (png_info_ptr != NULL) png_free_data(png_ptr, png_info_ptr, PNG_FREE_ALL, -1); if (png_ptr != NULL) png_destroy_write_struct(&png_ptr, (png_infopp) NULL); if (png_row != NULL) free(png_row); return true; } ///// for render handler ///////////// bool BrowserHandler::GetRootScreenRect(CefRefPtr<CefBrowser> browser, CefRect& rect) { //cerr << "render handler get root screen rect" << endl; CEF_REQUIRE_UI_THREAD(); return false; } bool BrowserHandler::GetScreenPoint(CefRefPtr<CefBrowser> browser, int viewX, int viewY, int& screenX, int& screenY) { //cerr << "render handler get screen point" << endl; CEF_REQUIRE_UI_THREAD(); return false; } bool BrowserHandler::GetScreenInfo(CefRefPtr<CefBrowser> browser, CefScreenInfo& screen_info) { //cerr << "render handler get screen info" << endl; CEF_REQUIRE_UI_THREAD(); return false; } void BrowserHandler::OnPopupShow(CefRefPtr<CefBrowser> browser, bool show) { //cerr << "render handler on popup show" << endl; CEF_REQUIRE_UI_THREAD(); } void BrowserHandler::OnPopupSize(CefRefPtr<CefBrowser> browser, const CefRect& rect) { //cerr << "render handler on popup size" << endl; CEF_REQUIRE_UI_THREAD(); } void BrowserHandler::GetViewRect(CefRefPtr<CefBrowser> browser, CefRect& rect) { CEF_REQUIRE_UI_THREAD(); if(view_content_height > 0 ) rect.height = view_content_height; else rect.height = view_port_height; rect.width = view_port_width; } void BrowserHandler::OnPaint(CefRefPtr<CefBrowser> browser, PaintElementType type, const RectList& dirtyRects, const void* buffer, int width, int height) { CEF_REQUIRE_UI_THREAD(); if(type == PET_VIEW && requireCapture){ srand(time(NULL)); mkdir(std::string(work_path + "/screenshot/").c_str(),S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); string filename = work_path + "/screenshot/screenshot_" + std::to_string(rand()) + std::string(".png"); bool ret = write_png_for_image((unsigned char*)buffer,width,height,filename.c_str()); if(ret){ string msg = "{\"action\":\"getScreenshot\",\"result\":\"" + filename + "\"}"; sendMessageToClient(msg.c_str()); } else sendMessageToClient("{\"action\":\"getScreenshot\",\"result\":\"fail\"}"); requireCapture = false; view_content_height = view_port_height; browser->GetHost()->NotifyScreenInfoChanged(); } } void BrowserHandler::OnAcceleratedPaint( CefRefPtr<CefBrowser> browser, CefRenderHandler::PaintElementType type, const CefRenderHandler::RectList& dirtyRects, void* share_handle) { //cerr << "accelerated render handler" << endl; CEF_REQUIRE_UI_THREAD(); } /*void BrowserHandler::OnCursorChange(CefRefPtr<CefBrowser> browser, CefCursorHandle cursor, CursorType type, const CefCursorInfo& custom_cursor_info) { //cerr << "render handler on curor change" << endl; CEF_REQUIRE_UI_THREAD(); }*/ bool BrowserHandler::StartDragging( CefRefPtr<CefBrowser> browser, CefRefPtr<CefDragData> drag_data, CefRenderHandler::DragOperationsMask allowed_ops, int x, int y) { //cerr << "render handler start dragging" << endl; CEF_REQUIRE_UI_THREAD(); return false; } void BrowserHandler::UpdateDragCursor( CefRefPtr<CefBrowser> browser, CefRenderHandler::DragOperation operation) { //cerr << "render handler update drage cursor" << endl; CEF_REQUIRE_UI_THREAD(); } void BrowserHandler::OnImeCompositionRangeChanged( CefRefPtr<CefBrowser> browser, const CefRange& selection_range, const CefRenderHandler::RectList& character_bounds) { //cerr << "render handler ime OnImeCompositionRangeChanged" << endl; CEF_REQUIRE_UI_THREAD(); }
29.627803
110
0.583018
[ "render" ]
34aca76901e32ae1fd7e860ccdbb086f8798243c
8,563
hpp
C++
src/assembler/mechanics/latin_matrix.hpp
dbeurle/neon
63cd2929a6eaaa0e1654c729cd35a9a52a706962
[ "MIT" ]
9
2018-07-12T17:06:33.000Z
2021-11-20T23:13:26.000Z
src/assembler/mechanics/latin_matrix.hpp
dbeurle/neon
63cd2929a6eaaa0e1654c729cd35a9a52a706962
[ "MIT" ]
119
2016-06-22T07:36:04.000Z
2019-03-10T19:38:12.000Z
src/assembler/mechanics/latin_matrix.hpp
dbeurle/neon
63cd2929a6eaaa0e1654c729cd35a9a52a706962
[ "MIT" ]
9
2017-10-08T16:51:38.000Z
2021-03-15T08:08:04.000Z
#pragma once /// @file #include "static_matrix.hpp" namespace neon::mechanics { /// Generic latin matrix designed for solid mechanics problems using the /// LATIN method for the solution of nonlinear equations. /// This class is responsible for the assembly of the process stiffness matrix, /// residual force vector and solution of the incremental displacement. template <class MeshType> class latin_matrix : public static_matrix<MeshType> { public: using mesh_type = MeshType; using base_type = static_matrix<mesh_type>; private: // use base class variables and methods using base_type::adaptive_load; using base_type::apply_displacement_boundaries; using base_type::assemble_stiffness; using base_type::compute_external_force; using base_type::compute_internal_force; using base_type::delta_d; using base_type::displacement; using base_type::displacement_old; using base_type::f_ext; using base_type::f_int; using base_type::is_iteration_converged; using base_type::Kt; using base_type::maximum_iterations; using base_type::mesh; using base_type::minus_residual; using base_type::norm_initial_residual; using base_type::print_convergence_progress; using base_type::solver; using base_type::update_relative_norms; private: /// LATIN residual vector vector latin_residual; /// LATIN search direction scaling factor \f$ \alpha \ \mathbb{C} \f$ double latin_search_direction = 0.0; public: explicit latin_matrix(mesh_type& mesh, json const& simulation); /// Solve the nonlinear system of equations void solve(); private: void perform_equilibrium_iterations(); /// Gathers latin internal force vector using current and old Cauchy stresses void compute_incremental_latin_internal_force(); /// Apply dirichlet conditions to the system defined by A, x, and (b or c). /// This method sets the incremental displacements to zero for the given /// load increment such that incremental displacements are zero void enforce_dirichlet_conditions(sparse_matrix& A, vector& b, vector& c) const; }; template <class MeshType> latin_matrix<MeshType>::latin_matrix(mesh_type& mesh, json const& simulation) : base_type::static_matrix(mesh, simulation) { auto const& nonlinear_options = simulation["nonlinear_options"]; if (nonlinear_options.find("latin_search_direction") == nonlinear_options.end()) { throw std::domain_error("latin_search_direction not specified in nonlinear_options"); } latin_search_direction = nonlinear_options["latin_search_direction"]; latin_residual = vector::Zero(mesh.active_dofs()); } template <class MeshType> void latin_matrix<MeshType>::compute_incremental_latin_internal_force() { latin_residual.setZero(); for (auto const& submesh : mesh.meshes()) { for (std::int64_t element{0}; element < submesh.elements(); ++element) { auto const & [dofs, fe_int] = submesh.incremental_latin_internal_force(element, latin_search_direction); latin_residual(dofs) += fe_int; } } } template <class MeshType> void latin_matrix<MeshType>::enforce_dirichlet_conditions(sparse_matrix& A, vector& b, vector& c) const { for (auto const& [name, boundaries] : mesh.dirichlet_boundaries()) { for (auto const& boundary : boundaries) { if (boundary.is_not_active(adaptive_load.step_time())) { continue; } for (auto const& fixed_dof : boundary.dof_view()) { auto const diagonal_entry = A.coeff(fixed_dof, fixed_dof); b(fixed_dof) = 0.0; c(fixed_dof) = 0.0; std::vector<std::int32_t> non_zero_visitor; // Zero the rows and columns for (sparse_matrix::InnerIterator it(A, fixed_dof); it; ++it) { // Set the value of the col or row resp. to zero it.valueRef() = 0.0; non_zero_visitor.push_back(A.IsRowMajor ? it.col() : it.row()); } // Zero the row or col respectively for (auto const& non_zero : non_zero_visitor) { const auto row = A.IsRowMajor ? non_zero : fixed_dof; const auto col = A.IsRowMajor ? fixed_dof : non_zero; A.coeffRef(row, col) = 0.0; } // Reset the diagonal to the same value to preserve conditioning A.coeffRef(fixed_dof, fixed_dof) = diagonal_entry; } } } } template <class MeshType> void latin_matrix<MeshType>::solve() { try { // Initialise the mesh with zero displacements mesh.update_internal_variables(displacement); mesh.update_internal_forces(f_int); mesh.write(adaptive_load.step(), adaptive_load.time()); while (!adaptive_load.is_fully_applied()) { std::cout << "\n" << std::string(4, ' ') << termcolor::magenta << termcolor::bold << "Performing equilibrium iterations for time " << adaptive_load.step_time() << termcolor::reset << std::endl; compute_external_force(); perform_equilibrium_iterations(); } } catch (computational_error& comp_error) { // A numerical error has been reported that is able to be recovered // by resetting the state std::cout << std::endl << std::string(6, ' ') << termcolor::bold << termcolor::yellow << comp_error.what() << termcolor::reset << std::endl; adaptive_load.update_convergence_state(false); mesh.save_internal_variables(false); displacement = displacement_old; this->solve(); } catch (...) { throw; } } template <class MeshType> void latin_matrix<MeshType>::perform_equilibrium_iterations() { displacement = displacement_old; mesh.update_internal_variables(displacement, adaptive_load.increment()); // Full LATIN iteration to solve nonlinear equations auto current_iteration{0}; while (current_iteration < maximum_iterations) { auto const start = std::chrono::steady_clock::now(); std::cout << std::string(4, ' ') << termcolor::blue << termcolor::bold << "LATIN iteration " << current_iteration << termcolor::reset << "\n"; assemble_stiffness(); compute_internal_force(); compute_incremental_latin_internal_force(); minus_residual = f_ext - f_int; if (current_iteration == 0) { apply_displacement_boundaries(); norm_initial_residual = minus_residual.norm(); // start with an elastic initialisation latin_residual = minus_residual; } // TODO: the convergence may be measure by the minus_residual = latin_residual. However, this // will not ensure the balance of forces anymore. Also, the stifness matrix may be scaled by // `latin_search_direction` but this did not improve the convergence of the incremental LATIN scheme enforce_dirichlet_conditions(Kt, minus_residual, latin_residual); solver->solve(Kt, delta_d, latin_residual); displacement += delta_d; mesh.update_internal_variables(displacement, 0.0); update_relative_norms(); print_convergence_progress(); auto const end = std::chrono::steady_clock::now(); std::chrono::duration<double> const elapsed_seconds = end - start; std::cout << std::string(6, ' ') << "Equilibrium iteration required " << elapsed_seconds.count() << "s\n"; if (is_iteration_converged()) break; current_iteration++; } if (current_iteration == maximum_iterations) { throw computational_error("Reached LATIN iteration limit"); } if (current_iteration != maximum_iterations) { displacement_old = displacement; adaptive_load.update_convergence_state(current_iteration != maximum_iterations); mesh.save_internal_variables(current_iteration != maximum_iterations); mesh.update_internal_forces(f_int); mesh.write(adaptive_load.step(), adaptive_load.time()); } } }
32.071161
108
0.639379
[ "mesh", "vector", "solid" ]
34b8db3a5add73dcda0aa5049ffe67b29c8b7979
2,410
cpp
C++
samples/gl/AdvancedGLSL.cpp
kunka/SoftRender
8089844e9ab00ab71ef1a820641ec07ae8df248d
[ "MIT" ]
6
2019-01-25T08:41:14.000Z
2021-08-22T07:06:11.000Z
samples/gl/AdvancedGLSL.cpp
kunka/SoftRender
8089844e9ab00ab71ef1a820641ec07ae8df248d
[ "MIT" ]
null
null
null
samples/gl/AdvancedGLSL.cpp
kunka/SoftRender
8089844e9ab00ab71ef1a820641ec07ae8df248d
[ "MIT" ]
3
2019-01-25T08:41:16.000Z
2020-09-04T06:04:29.000Z
// // Created by huangkun on 2018/4/11. // #include "AdvancedGLSL.h" TEST_NODE_IMP_BEGIN AdvancedGLSL::AdvancedGLSL() { const char *vert = R"( #version 330 core layout (location = 0) in vec3 a_position; uniform mat4 model; uniform mat4 view; uniform mat4 projection; void main() { gl_Position = projection * view * model * vec4(a_position, 1.0); gl_PointSize = gl_Position.z; } )"; const char *frag = R"( #version 330 core out vec4 FragColor; void main() { if(gl_FragCoord.x < 400) FragColor = vec4(1.0, 0.0, 0.0, 1.0); else FragColor = vec4(0.0, 1.0, 0.0, 1.0); } )"; shader.loadStr(vert, frag); float vertices[] = { 0.0f, 0.0f, 0.0f, }; glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void *) 0); glEnableVertexAttribArray(0); } void AdvancedGLSL::draw(const mat4 &transform) { glEnable(GL_PROGRAM_POINT_SIZE); glClearColor(0.1f, 0.2f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); shader.use(); view = glm::lookAt(cameraPos, cameraPos + cameraDir, cameraUp); shader.setMat4("view", view); shader.setMat4("projection", projection); glm::vec3 positions[] = { glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(2.0f, 5.0f, -15.0f), glm::vec3(-1.5f, -2.2f, -2.5f), glm::vec3(-3.8f, -2.0f, -12.3f), glm::vec3(2.4f, -0.4f, -3.5f), glm::vec3(-1.7f, 3.0f, -7.5f), glm::vec3(1.3f, -2.0f, -2.5f), glm::vec3(1.5f, 2.0f, -2.5f), glm::vec3(1.5f, 0.2f, -1.5f), glm::vec3(-1.3f, 1.0f, -1.5f) }; glBindVertexArray(VAO); for (unsigned int i = 0; i < 10; i++) { model = glm::mat4(); model = glm::translate(model, positions[i]); shader.setMat4("model", model); glDrawArrays(GL_POINTS, 0, 1); } glDisable(GL_PROGRAM_POINT_SIZE); } AdvancedGLSL::~AdvancedGLSL() { glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); } TEST_NODE_IMP_END
26.195652
82
0.542739
[ "model", "transform" ]
34bb3cf5bf33c7686e1429095afedddbc3ea0881
6,171
cpp
C++
src/ga/GAList.cpp
yuriyvolkov/galib
f3ca97f74f8a0318f3c0068006ea6cc0ae2adcd9
[ "BSD-3-Clause" ]
6
2017-12-07T16:19:08.000Z
2022-03-23T09:22:11.000Z
src/ga/GAList.cpp
yuriyvolkov/galib
f3ca97f74f8a0318f3c0068006ea6cc0ae2adcd9
[ "BSD-3-Clause" ]
3
2016-11-12T17:36:02.000Z
2018-07-13T09:07:07.000Z
src/ga/GAList.cpp
yuriyvolkov/galib
f3ca97f74f8a0318f3c0068006ea6cc0ae2adcd9
[ "BSD-3-Clause" ]
4
2015-09-20T18:24:39.000Z
2021-04-09T18:26:55.000Z
// $Header$ /* ---------------------------------------------------------------------------- listtmpl.C mbwall 25feb95 Copyright 1995 Massachusetts Institute of Technology DESCRIPTION: This defines the templatized list objects. TO DO: Make insert work better with size and depth so not so many recalcs needed. Implement better memory mangement, faster allocation, referencing. Use array representation of nodes so we don't have to do so much recursion. ---------------------------------------------------------------------------- */ #ifndef _ga_listtmpl_C_ #define _ga_listtmpl_C_ #include <ga/GAList.h> extern GANodeBASE *_GAListTraverse(unsigned int index, unsigned int &cur, GANodeBASE *node); // template <class T> GANode<T> * _GAListCopy(GANode<T> *, GANode<T> *); /* ---------------------------------------------------------------------------- List ---------------------------------------------------------------------------- */ // The destructor just goes through the list and deletes every node. template <class T> GAList<T>::~GAList() { while (hd) delete GAListBASE::remove(DYN_CAST(GANode<T> *, hd)); iter.node = (GANodeBASE *)0; } // Yes, this is really ugly. We do a complete destruction of the existing list // then we copy the new one. No caching, no nothing. Oh well. We set the // iterator to the head node - it should be set to the corresponding node, but // I won't do that right now. THIS IS A BUG! template <class T> void GAList<T>::copy(const GAList<T> &orig) { while (hd) delete GAListBASE::remove(DYN_CAST(GANode<T> *, hd)); hd = _GAListCopy(DYN_CAST(GANode<T> *, orig.hd), DYN_CAST(GANode<T> *, orig.hd)); iter.node = hd; sz = orig.sz; csz = orig.csz; } // This remove method returns a pointer to the contents of the node that was // removed. The node itself is destroyed. // The iterator gets set to the next node toward the head of the list. // This routine makes a copy of the node contents using the copy initializer // of the T object, so the copy initializer MUST be defined and accessible. // We return a pointer to the contents rather than the contenst for the same // reason we return a pointer from all the iter routines - we don't want to // pass big objects around. template <class T> T *GAList<T>::remove() { GANode<T> *node = DYN_CAST(GANode<T> *, iter.node); if (!node) return (T *)0; if (node->prev != node) iter.node = node->prev; else iter.node = (GANodeBASE *)0; node = DYN_CAST(GANode<T> *, GAListBASE::remove(node)); T *contents = new T(node->contents); delete node; return contents; } // Make a copy of a list and return the pointer to the new list. The cloning // is based on the value passed to this routine. A value of 0 will clone the // entire list. Any other value will clone the list from the index to the end // of the list. This routine has no effect on the iterator in the original // list. template <class T> GAList<T> *GAList<T>::clone(unsigned int i) const { GAList<T> *t = new GAList<T>; GANode<T> *node; unsigned int w = 0; if (i == 0) node = DYN_CAST(GANode<T> *, hd); else node = DYN_CAST(GANode<T> *, _GAListTraverse(i, w, hd)); if (!node) return t; GANode<T> *newnode = _GAListCopy(node, DYN_CAST(GANode<T> *, hd)); t->insert(newnode, (GANode<T> *)0, GAListBASE::HEAD); // need to set iterator to right spot in the clone!! for now its at the head return t; } // Destroy the specified node. This uses the current node as the one to // destroy, so be sure to use the iteration methods to move to the node you // want to destroy. Once the node is gone, we set the current node to the // prev node of the one that was destroyed. If the node that was nuked was the // head node then we set the current node to the new head. template <class T> int GAList<T>::destroy() { GANodeBASE *node = iter.node; if (!node) return GAListBASE::NO_ERR; if (node->prev && node->prev != node) if (hd == node) iter.node = node->next; else iter.node = node->prev; else iter.node = (GANodeBASE *)0; delete GAListBASE::remove(node); return GAListBASE::NO_ERR; } // Swap two nodes in the list. This has no effect on the size or the iterator. // If either index is out of bounds then we don't do anything. template <class T> int GAList<T>::swap(unsigned int a, unsigned int b) { if (a == b || a > (unsigned int)size() || b > (unsigned int)size()) return GAListBASE::NO_ERR; GANodeBASE *tmp = hd, *anode = (GANodeBASE *)0, *bnode = (GANodeBASE *)0; unsigned int cur = 0; while (tmp && tmp->next != hd) { if (a == cur) anode = tmp; if (b == cur) bnode = tmp; tmp = tmp->next; cur++; } if (a == cur) anode = tmp; if (b == cur) bnode = tmp; return GAListBASE::swapnode(anode, bnode); } /* ---------------------------------------------------------------------------- Utility routines for the List objects ---------------------------------------------------------------------------- */ // Copy a node, including all of its siblings up to the end of the list. We do // NOT wrap around the list until we return the first node - we stop at the // tail of the list. Return the pointer to the first node in the list. template <class T> GANode<T> *_GAListCopy(GANode<T> *node, GANode<T> *head) { if (!node) return (GANode<T> *)0; GANode<T> *newnode = new GANode<T>(node->contents); GANode<T> *lasttmp = newnode, *newtmp = (GANode<T> *)0; GANode<T> *tmp = DYN_CAST(GANode<T> *, node->next); while (tmp && tmp != head) { newtmp = new GANode<T>(tmp->contents); newtmp->prev = lasttmp; lasttmp->next = newtmp; lasttmp = newtmp; tmp = DYN_CAST(GANode<T> *, tmp->next); } if (newtmp) { newtmp->next = newnode; newnode->prev = newtmp; } else { newnode->next = newnode; newnode->prev = newnode; } return newnode; } #endif
34.093923
92
0.590342
[ "object" ]
34c6532cfacea1d792825911339d6ecc8564afbe
4,444
cpp
C++
testbed/car.cpp
DomiKoPL/BoxCar2D.cpp
a3bbb80304bccf7a8a232bfb8fe78718c47e03f7
[ "MIT" ]
null
null
null
testbed/car.cpp
DomiKoPL/BoxCar2D.cpp
a3bbb80304bccf7a8a232bfb8fe78718c47e03f7
[ "MIT" ]
null
null
null
testbed/car.cpp
DomiKoPL/BoxCar2D.cpp
a3bbb80304bccf7a8a232bfb8fe78718c47e03f7
[ "MIT" ]
null
null
null
#include "car.h" #include <exception> #include <iostream> Car::Car() { } Car::Car(Chromosome& chromosome, b2World* world, float init_speed) { m_world = world; chrom = chromosome; m_done = false; prev_step_count = -1; best_x = -1e9; b2PolygonShape chassis; b2Vec2 vertices[8]; for(int i = 0; i < 8; i++) { float r = chromosome.GetVertexMagnitude(i); float angle = chromosome.GetVertexAngle(i); vertices[i].Set(cos(angle) * r, sin(angle) * r); } chassis.Set(vertices, 8); float min_y = vertices[0].y; for(int i = 1; i < 8; i++) { min_y = std::min(min_y, vertices[i].y); } int number_of_wheels{0}; for(int i = 0; i < 8; i++) { if(chromosome.GetVertexWhell(i)) { const float r{chromosome.GetVertexWhellRadius(i)}; min_y = std::min(min_y, vertices[i].y - r); number_of_wheels++; } } b2CircleShape circle; b2BodyDef bd; bd.type = b2_dynamicBody; bd.position.Set(0.0f, -min_y); m_body = world->CreateBody(&bd); b2FixtureDef bodyDef; bodyDef.shape = &chassis; bodyDef.density = 30.0; //TODO: into chromosome bodyDef.restitution = 0.2; bodyDef.friction = 10.0; bodyDef.filter.groupIndex = -1; m_body->CreateFixture(&bodyDef); b2FixtureDef fd; fd.shape = &circle; fd.density = 100.f; // TODO: into chromosome fd.restitution = 0.2; fd.friction = 1.f; fd.filter.groupIndex = -1; b2WheelJointDef jd; b2Vec2 axis(0.0f, 1.0f); float hertz = 4.0f; float dampingRatio = 0.7f; float omega = 2.0f * b2_pi * hertz; m_wheels.fill(nullptr); m_springs.fill(nullptr); float car_mass = m_body->GetMass(); int whells_cnt = 0; for(int i = 0; i < 8; i++) { if(chromosome.GetVertexWhell(i)) { whells_cnt++; } } if(whells_cnt >= 2) { for(int i = 0; i < 8; i++) { if(chromosome.GetVertexWhell(i)) { circle.m_radius = chromosome.GetVertexWhellRadius(i); bd.position.Set(vertices[i].x, vertices[i].y - min_y); m_wheels[i] = world->CreateBody(&bd); m_wheels[i]->CreateFixture(&fd); car_mass += m_wheels[i]->GetMass(); } } } for(int i = 0; i < 8; i++) { if(m_wheels[i] != nullptr) { float torque = car_mass * -m_world->GetGravity().y / chromosome.GetVertexWhellRadius(i); float mass = m_wheels[i]->GetMass(); jd.Initialize(m_body, m_wheels[i], m_wheels[i]->GetPosition(), axis); jd.motorSpeed = -init_speed; jd.maxMotorTorque = torque; jd.enableMotor = true; jd.stiffness = mass * omega * omega; jd.damping = 2.0f * mass * dampingRatio * omega; jd.lowerTranslation = -0.25f; jd.upperTranslation = 0.25f; jd.enableLimit = true; m_springs[i] = (b2WheelJoint*)world->CreateJoint(&jd); } } } void Car::update(int step_count) { if(m_done) return; float x = m_body->GetPosition().x; // std::cerr << "DONE " << x << " " << best_x << " " << step_count << " " << prev_step_count << "\n"; float delta_x = std::max(5.f, 20.f - step_count / 60.f); if(prev_step_count >= 0) { if(x < best_x - delta_x) { m_done = true; } if(x <= best_x + 10.f and step_count - prev_step_count > 3 * 60) { m_done = true; } } if(prev_step_count == -1 or best_x < x) { best_x = x; prev_step_count = step_count; } } bool Car::is_done() const { return m_done; } void Car::set_done(bool done) { m_done = done; } float Car::get_best_x() const { return best_x; } float Car::eval(float map_width, int max_time) const { if(best_x > map_width) { return -(100 + max_time - prev_step_count); } return map_width - best_x; } Car::~Car() { assert(not m_world->IsLocked()); m_world->DestroyBody(m_body); for(auto& whell : m_wheels) { if(whell != nullptr) { m_world->DestroyBody(whell); } } m_body = nullptr; for(auto& whell : m_wheels) { whell = nullptr; } for(auto& spring : m_springs) { spring = nullptr; } }
23.892473
105
0.541854
[ "shape" ]
34c78e5c7bd2e1f044d7feb8ae227a92cfcc4b0b
4,829
hpp
C++
frame/aio/aioobject.hpp
joydit/solidframe
0539b0a1e77663ac4c701a88f56723d3e3688e8c
[ "BSL-1.0" ]
null
null
null
frame/aio/aioobject.hpp
joydit/solidframe
0539b0a1e77663ac4c701a88f56723d3e3688e8c
[ "BSL-1.0" ]
null
null
null
frame/aio/aioobject.hpp
joydit/solidframe
0539b0a1e77663ac4c701a88f56723d3e3688e8c
[ "BSL-1.0" ]
null
null
null
// frame/aio/aioobject.hpp // // Copyright (c) 2007, 2008 Valentin Palade (vipalade @ gmail . com) // // This file is part of SolidFrame framework. // // 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 SOLID_FRAME_AIO_OBJECT_HPP #define SOLID_FRAME_AIO_OBJECT_HPP #include "system/timespec.hpp" #include "frame/object.hpp" namespace solid{ namespace frame{ namespace aio{ class Socket; class SocketPointer; class Selector; //! aio::Object is the base class for all classes doing asynchronous socket io /*! Although it can be inherited directly, one should use the extended classes aio::SingleObject or aio::MultiObject. It is designed together with aio::Selector so the objects shoud stay within a SelectorPool\<aio::Selector>. It allows for multiple sockets but this is only from the aio::Selector side, as actual support for single/multiple sockets must came from upper levels, i.e. inheritants - see aio::SingleObject or aio::MultiObject. */ class Object: public Dynamic<Object, frame::Object>{ public: virtual ~Object(); protected: //! Returns true if there are pending io requests /*! Notable is that the method is thought to be called from execute callback, and that its status is reseted after exiting from execute. */ bool hasPendingRequests()const{return reqbeg != reqpos;} protected: friend class Selector; //! A stub struncture for sockets struct SocketStub{ enum{ //Requests from multiconnection to selector //Response = 1, IORequest = 4, UnregisterRequest = 8, RegisterRequest = 16, AllRequests = 1 + 4 + 8 + 16, AllResponses = 2 }; SocketStub(Socket *_psock = NULL): psock(_psock), itimepos(TimeSpec::maximum), otimepos(TimeSpec::maximum), itoutpos(-1), otoutpos(-1), hasresponse(false),requesttype(0), chnevents(0), selevents(0){} ~SocketStub(); void reset(){ psock = NULL; itimepos = TimeSpec::maximum; otimepos = TimeSpec::maximum; itoutpos = -1; otoutpos = -1; hasresponse = false; requesttype = 0; chnevents = 0; selevents = 0; } Socket *psock; TimeSpec itimepos; TimeSpec otimepos; size_t itoutpos; //-1 or position in toutvec size_t otoutpos; //-1 or position in toutvec uint8 hasresponse;//the socket is in response queue uint8 requesttype; int16 state; //An associated state for the socket uint32 chnevents; //the event from selector to connection: //INDONE, OUTDONE, TIMEOUT, ERRDONE uint32 selevents; //used by selector - current io requests }; //!Constructor /*! Constructor setting all needed data. The data is not dealocated, it is the responsability of inheritants. E.g. some classes may avoid "new" allocation by holding the table within the class (as aio::SingleObject). Others may do a single allocation of a big chunck to hold all the tables and just set the pointers to offsets within. \param _pstubs A table with allocated stubs, can be changed after \param _stubcp The capacity of the table \param _reqbeg A table of size_t[_stubcp] \param _resbeg A table of size_t[_stubcp] \param _toutbeg A table of size_t[_stubcp] */ Object( SocketStub *_pstubs = NULL, const size_t _stubcp = 0, size_t *_reqbeg = NULL, size_t *_resbeg = NULL, size_t *_itoutbeg = NULL, size_t *_otoutbeg = NULL ): pitimepos(NULL), potimepos(NULL), pstubs(_pstubs), stubcp(_stubcp), reqbeg(_reqbeg), reqpos(_reqbeg), resbeg(_resbeg), respos(0), ressize(0), itoutbeg(_itoutbeg), itoutpos(_itoutbeg), otoutbeg(_otoutbeg), otoutpos(_otoutbeg){ } void socketPushRequest(const size_t _pos, const uint8 _req); void socketPostEvents(const size_t _pos, const uint32 _evs); private: void doPrepare(TimeSpec *_pitimepos, TimeSpec *_potimepos); void doUnprepare(); /*virtual*/void doStop(); void doClearRequests(); size_t doOnTimeoutRecv(const TimeSpec &_timepos); size_t doOnTimeoutSend(const TimeSpec &_timepos); void doPopTimeoutRecv(const size_t _pos); void doPopTimeoutSend(const size_t _pos); protected: void doPushTimeoutRecv(const size_t _pos, const TimeSpec &_crttime, const ulong _addsec, const ulong _addnsec); void doPushTimeoutSend(const size_t _pos, const TimeSpec &_crttime, const ulong _addsec, const ulong _addnsec); void setSocketPointer(const SocketPointer &_rsp, Socket *_ps); Socket* getSocketPointer(const SocketPointer &_rsp); protected: TimeSpec *pitimepos; TimeSpec *potimepos; SocketStub *pstubs; size_t stubcp; size_t *reqbeg; size_t *reqpos; size_t *resbeg; size_t respos; size_t ressize; size_t *itoutbeg; size_t *itoutpos; size_t *otoutbeg; size_t *otoutpos; }; }//namespace aio }//namespace frame }//namespace solid #endif
30.563291
112
0.730172
[ "object", "solid" ]
34c7c59a3e4739f143cf7880e52c115005a53537
13,142
cxx
C++
main/slideshow/source/engine/shapes/appletshape.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/slideshow/source/engine/shapes/appletshape.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/slideshow/source/engine/shapes/appletshape.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_slideshow.hxx" // must be first #include <canvas/debug.hxx> #include <canvas/verbosetrace.hxx> #include <canvas/canvastools.hxx> #include <boost/shared_ptr.hpp> #include "appletshape.hxx" #include "externalshapebase.hxx" #include "vieweventhandler.hxx" #include "viewappletshape.hxx" #include "tools.hxx" #include <boost/bind.hpp> #include <algorithm> using namespace ::com::sun::star; namespace slideshow { namespace internal { /** Represents an applet shape. This implementation offers support for applet shapes (both Java applets, and Netscape plugins). Such shapes need special treatment. */ class AppletShape : public ExternalShapeBase { public: /** Create a shape for the given XShape for a applet object @param xShape The XShape to represent. @param nPrio Externally-determined shape priority (used e.g. for paint ordering). This number _must be_ unique! @param rServiceName Service name to use, when creating the actual viewer component @param pPropCopyTable Table of plain ASCII property names, to copy from xShape to applet. @param nNumPropEntries Number of property table entries (in pPropCopyTable) */ AppletShape( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >& xShape, double nPrio, const ::rtl::OUString& rServiceName, const char** pPropCopyTable, sal_Size nNumPropEntries, const SlideShowContext& rContext ); // throw ShapeLoadFailedException; private: // View layer methods //------------------------------------------------------------------ virtual void addViewLayer( const ViewLayerSharedPtr& rNewLayer, bool bRedrawLayer ); virtual bool removeViewLayer( const ViewLayerSharedPtr& rNewLayer ); virtual bool clearAllViewLayers(); // ExternalShapeBase methods //------------------------------------------------------------------ virtual bool implRender( const ::basegfx::B2DRange& rCurrBounds ) const; virtual void implViewChanged( const UnoViewSharedPtr& rView ); virtual void implViewsChanged(); virtual bool implStartIntrinsicAnimation(); virtual bool implEndIntrinsicAnimation(); virtual bool implPauseIntrinsicAnimation(); virtual bool implIsIntrinsicAnimationPlaying() const; virtual void implSetIntrinsicAnimationTime(double); const ::rtl::OUString maServiceName; const char** mpPropCopyTable; const sal_Size mnNumPropEntries; /// the list of active view shapes (one for each registered view layer) typedef ::std::vector< ViewAppletShapeSharedPtr > ViewAppletShapeVector; ViewAppletShapeVector maViewAppletShapes; bool mbIsPlaying; }; AppletShape::AppletShape( const uno::Reference< drawing::XShape >& xShape, double nPrio, const ::rtl::OUString& rServiceName, const char** pPropCopyTable, sal_Size nNumPropEntries, const SlideShowContext& rContext ) : ExternalShapeBase( xShape, nPrio, rContext ), maServiceName( rServiceName ), mpPropCopyTable( pPropCopyTable ), mnNumPropEntries( nNumPropEntries ), maViewAppletShapes(), mbIsPlaying(false) { } // --------------------------------------------------------------------- void AppletShape::implViewChanged( const UnoViewSharedPtr& rView ) { // determine ViewAppletShape that needs update ViewAppletShapeVector::const_iterator aIter(maViewAppletShapes.begin()); ViewAppletShapeVector::const_iterator const aEnd (maViewAppletShapes.end()); while( aIter != aEnd ) { if( (*aIter)->getViewLayer()->isOnView(rView) ) (*aIter)->resize(getBounds()); ++aIter; } } // --------------------------------------------------------------------- void AppletShape::implViewsChanged() { // resize all ViewShapes ::std::for_each( maViewAppletShapes.begin(), maViewAppletShapes.end(), ::boost::bind( &ViewAppletShape::resize, _1, ::boost::cref( AppletShape::getBounds())) ); } // --------------------------------------------------------------------- void AppletShape::addViewLayer( const ViewLayerSharedPtr& rNewLayer, bool bRedrawLayer ) { try { maViewAppletShapes.push_back( ViewAppletShapeSharedPtr( new ViewAppletShape( rNewLayer, getXShape(), maServiceName, mpPropCopyTable, mnNumPropEntries, mxComponentContext ))); // push new size to view shape maViewAppletShapes.back()->resize( getBounds() ); // render the Shape on the newly added ViewLayer if( bRedrawLayer ) maViewAppletShapes.back()->render( getBounds() ); } catch(uno::Exception&) { // ignore failed shapes - slideshow should run with // the remaining content } } // --------------------------------------------------------------------- bool AppletShape::removeViewLayer( const ViewLayerSharedPtr& rLayer ) { const ViewAppletShapeVector::iterator aEnd( maViewAppletShapes.end() ); OSL_ENSURE( ::std::count_if(maViewAppletShapes.begin(), aEnd, ::boost::bind<bool>( ::std::equal_to< ViewLayerSharedPtr >(), ::boost::bind( &ViewAppletShape::getViewLayer, _1 ), ::boost::cref( rLayer ) ) ) < 2, "AppletShape::removeViewLayer(): Duplicate ViewLayer entries!" ); ViewAppletShapeVector::iterator aIter; if( (aIter=::std::remove_if( maViewAppletShapes.begin(), aEnd, ::boost::bind<bool>( ::std::equal_to< ViewLayerSharedPtr >(), ::boost::bind( &ViewAppletShape::getViewLayer, _1 ), ::boost::cref( rLayer ) ) )) == aEnd ) { // view layer seemingly was not added, failed return false; } // actually erase from container maViewAppletShapes.erase( aIter, aEnd ); return true; } // --------------------------------------------------------------------- bool AppletShape::clearAllViewLayers() { maViewAppletShapes.clear(); return true; } // --------------------------------------------------------------------- bool AppletShape::implRender( const ::basegfx::B2DRange& rCurrBounds ) const { // redraw all view shapes, by calling their update() method if( ::std::count_if( maViewAppletShapes.begin(), maViewAppletShapes.end(), ::boost::bind<bool>( ::boost::mem_fn( &ViewAppletShape::render ), _1, ::boost::cref( rCurrBounds ) ) ) != static_cast<ViewAppletShapeVector::difference_type>(maViewAppletShapes.size()) ) { // at least one of the ViewShape::update() calls did return // false - update failed on at least one ViewLayer return false; } return true; } // --------------------------------------------------------------------- bool AppletShape::implStartIntrinsicAnimation() { ::std::for_each( maViewAppletShapes.begin(), maViewAppletShapes.end(), ::boost::bind( &ViewAppletShape::startApplet, _1, ::boost::cref( getBounds() ))); mbIsPlaying = true; return true; } // --------------------------------------------------------------------- bool AppletShape::implEndIntrinsicAnimation() { ::std::for_each( maViewAppletShapes.begin(), maViewAppletShapes.end(), ::boost::mem_fn( &ViewAppletShape::endApplet ) ); mbIsPlaying = false; return true; } // --------------------------------------------------------------------- bool AppletShape::implPauseIntrinsicAnimation() { // TODO(F1): any way of temporarily disabling/deactivating // applets? return true; } // --------------------------------------------------------------------- bool AppletShape::implIsIntrinsicAnimationPlaying() const { return mbIsPlaying; } // --------------------------------------------------------------------- void AppletShape::implSetIntrinsicAnimationTime(double) { // No way of doing this, or? } boost::shared_ptr<Shape> createAppletShape( const uno::Reference< drawing::XShape >& xShape, double nPrio, const ::rtl::OUString& rServiceName, const char** pPropCopyTable, sal_Size nNumPropEntries, const SlideShowContext& rContext ) { boost::shared_ptr< AppletShape > pAppletShape( new AppletShape(xShape, nPrio, rServiceName, pPropCopyTable, nNumPropEntries, rContext) ); return pAppletShape; } } }
40.189602
114
0.439203
[ "render", "object", "shape", "vector" ]
34c8084fcc156e637a42553828f476f1a4d06d7b
6,041
cpp
C++
src/libs/qlib/qvector.cpp
3dhater/Racer
d7fe4014b1efefe981528547649dc397da7fa780
[ "Unlicense" ]
null
null
null
src/libs/qlib/qvector.cpp
3dhater/Racer
d7fe4014b1efefe981528547649dc397da7fa780
[ "Unlicense" ]
null
null
null
src/libs/qlib/qvector.cpp
3dhater/Racer
d7fe4014b1efefe981528547649dc397da7fa780
[ "Unlicense" ]
1
2021-01-03T16:16:47.000Z
2021-01-03T16:16:47.000Z
/* * QVector3 - a 3D vector class * 28-08-00: Created! (based on prof. Kenneth I. Joy's Vector.C) * (C) MarketGraph/Ruud van Gaal */ #include <qlib/vector.h> #include <math.h> #include <qlib/debug.h> DEBUG_ENABLE // // Constructors // QVector3::QVector3() // Empty constructor gives 0 vector { x=y=z=0; } QVector3::QVector3(const double _x,const double _y,const double _z) { x=_x; y=_y; z=_z; } QVector3::QVector3(const QVector3& b) // Construct based on other QVector3 { x=b.GetX(); y=b.GetY(); z=b.GetZ(); } double QVector3::Length() const { double len; len=sqrt(x*x+y*y+z*z); return len; } void QVector3::SetToZero() { x=y=z=0.0; } /************ * Operators * ************/ QVector3 operator*(const QVector3 &a,const double &s) { QVector3 v; v.x=s*a.x; v.y=s*a.y; v.z=s*a.z; return v; } QVector3 operator*(const double &s,const QVector3 &a) { QVector3 v; v.x=s*a.x; v.y=s*a.y; v.z=s*a.z; return v; } QVector3 operator+(const QVector3 &a,const QVector3 &b) { QVector3 v; v.x=a.x+b.x; v.y=a.y+b.y; v.z=a.z+b.z; return v; } /************* * Assignment * *************/ QVector3& QVector3::operator=(const QVector3& v) { // Avoid assigning to one's self if(this==&v)return *this; x=v.x; y=v.y; z=v.z; return *this; } QVector3& QVector3::operator=(const double& v) { qwarn("QVector3 assign to double is undefined\n"); return *this; } /********* * Output * *********/ ostream& operator<< ( ostream& co, const QVector3& v ) { co << "< " << v.x << ", " << v.y << ", " << v.z << " >" ; return co ; } /************* * Comparison * *************/ int operator== ( const QVector3& v1, const QVector3& v2 ) // Very dubious, because of floating point arithmetic { if((v1.x==v2.x) && (v1.y==v2.y) && (v1.z==v2.z)) return TRUE; else return FALSE; } int operator!= ( const QVector3& v1, const QVector3& v2 ) { if((v1.x!=v2.x) || (v1.y!=v2.y) || (v1.z!=v2.z)) return TRUE; else return FALSE; } /************* * Arithmetic * *************/ QVector3 operator-(const QVector3& v1,const QVector3& v2) { QVector3 vv ; vv.x = v1.x - v2.x; vv.y = v1.y - v2.y; vv.z = v1.z - v2.z; return vv; } QVector3 operator-(const QVector3& v) { QVector3 vv ; vv.x=-v.x; vv.y=-v.y; vv.z=-v.z; return vv; } QVector3 operator/(const QVector3& v,const double& c) { QVector3 vv; vv.x=v.x/c; vv.y=v.y/c; vv.z=v.z/c; return vv; } /*********************** * Immediate arithmetic * ***********************/ QVector3& QVector3 :: operator+=(const QVector3& v) { x+=v.x; y+=v.y; z+=v.z; return *this; } QVector3& QVector3::operator-=(const QVector3& v) { x-=v.x; y-=v.y; z-=v.z; return *this; } QVector3& QVector3::operator*=(const double &s) { x*=s; y*=s; z*=s; return *this; } QVector3& QVector3::operator/=(const double& c) { x/=c; y/=c; z/=c; return *this; } /************ * Normalize * ************/ void QVector3::Normalize() // Make the vector length 1 { double l=Length(); // Avoid normalize zero vector if(l==0.0)return; x=x/l; y=y/l; z=z/l; } /************** * Dot product * **************/ double QVector3::Dot(const QVector3 &v1) // Returns dot product with another vector { return v1.x*x+v1.y*y+v1.z*z; } double QVector3::DotSelf() // Returns dot product of vector with itself // Could also just call v.Dot(v), but this is perhaps nicer { return x*x+y*y+z*z; } /**************** * Cross product * ****************/ QVector3 operator*(const QVector3& v1,const QVector3& v2) { QVector3 vv; vv.x=v1.y*v2.z-v1.z*v2.y; vv.y=-v1.x*v2.z+v1.z*v2.x; vv.z=v1.x*v2.y-v1.y*v2.x; return vv; } #ifdef OBS_PERHAPS_FUTURE_STUFF // // Operators // QVector3& QVector3::operator=(const char* s) { //qdbg("QVector3 op=const\n"); //qdbg(" s='%s', p=%p, refs=%d\n",s,p,p->refs); if(p->refs>1) { // Detach our buffer; contents are being modified p->refs--; p=new srep; } else { // Delete old string buffer //qdbg(" delete[] old p->s=%p (p=%p)\n",p->s,p); p->Free(); //delete[] p->s; } // Copy in new string p->Resize(strlen(s)+1); //p->s=new char[strlen(s)+1]; //qdbg(" p->s=%p, len=%d (%s)\n",p->s,strlen(s)+1,p->s); strcpy(p->s,s); return *this; } QVector3& QVector3::operator=(const QVector3& x) { x.p->refs++; // Protect against 's==s' if(--p->refs==0) { // Remove our own rep //delete[] p->s; p->Free(); delete p; } p=x.p; // Take over new string's rep return *this; } char& QVector3::operator[](int i) { if(i<0||i>=strlen(p->s)) { qwarn("QVector3(%s): ([]) index %d out of range (0..%d)", p->s,i,strlen(p->s)); i=strlen(p->s); // Return the 0 (reference) } if(p->refs>1) { // Detach to avoid 2 string rep's mixing srep* np=new srep; //np->s=new char[strlen(p->s)+1]; np->Resize(strlen(p->s)+1); strcpy(np->s,p->s); p->refs--; p=np; } return p->s[i]; } const char& QVector3::operator[](int i) const // Subscripting const strings { if(i<0||i>=strlen(p->s)) { qwarn("QVector3(%s): (const[]) index %d out of range (0..%d)", p->s,i,strlen(p->s)); i=strlen(p->s); // Return the 0 (reference) } return p->s[i]; } // // Type conversions // QVector3::operator const char *() const { return p->s; } #ifdef ND_NO_MODIFIABLE_STRING_PLEASE // This typecast cut out on 27-8-99, because it delivered too many // late-captured problems QVector3::operator char *() // const { // Check refs if(p->refs>1) { // Detach; the returned pointer may be used to modify the buffer! qdbg("QVector3 op char* detach\n"); srep* np=new srep; //np->s=new char[strlen(p->s)+1]; np->Resize(strlen(p->s)+1); strcpy(np->s,p->s); p->refs--; p=np; } return p->s; } #endif /************ * COMPARIONS * *************/ bool QVector3::operator==(const char *s) { return (strcmp(p->s,s)==0); } // Information bool QVector3::IsEmpty() { if(*p->s)return FALSE; return TRUE; } #endif
17.161932
69
0.557027
[ "vector", "3d" ]
34d40618f66aba430c0711425b9618d2b287b603
21,188
cpp
C++
simularcorte.cpp
hectorratia/chipor
7c4aa1cd4dc40f9032ec642d4851dead37ac27f7
[ "MIT" ]
null
null
null
simularcorte.cpp
hectorratia/chipor
7c4aa1cd4dc40f9032ec642d4851dead37ac27f7
[ "MIT" ]
null
null
null
simularcorte.cpp
hectorratia/chipor
7c4aa1cd4dc40f9032ec642d4851dead37ac27f7
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <cmath> #include <cstdlib> #include <ctime> using namespace std; vector<string> colarchivo; vector<double> probabilidades; int n_col=0; bool **relaciones; double apostados[14][3]; double porcentajes[14][3]; double premios14[5][4782969]; double probs[4782969]; int aciertos[5][4782969]; double ganado[4782969]; double emtotal; double prentable; double pdepremios; double ppremios[5]; double ppremiosm[5]; double ppremiosmc[5]; bool corteok; double pcorte; //Para el grafico de simulacion tren int simtren[1001]; int simulaciones=10000; bool CORTATREN=false; bool FULLPREMIOS=false; //Variables para grafico premio vs prob vector<vector<double> > grafico; vector<double> elem_grafico; int *indices; double recaudacion; int columnas_deseadas; ifstream fin; ofstream fout; string nombre_archivo; string linea; int mr_fallos; int pot3[]={1,3,9,27,81,243,729,2187,6561,19683,59049,177147,531441,1594323}; int stoin(string& columna) { int tstoin=0; for(int i=0 ;i<14 ; i++){ switch(columna[i]){ case '1':{ break;} case 'X':{ tstoin+=pot3[i]; break;} case 'x':{ tstoin+=pot3[i]; break;} case '2':{ tstoin+=2*pot3[i]; break;} } } return tstoin; } int stoinn(string& columna,int n) { int tstoin=0; for(int i=0 ;i<n ; i++){ switch(columna[i]){ case '1':{ break;} case 'X':{ tstoin+=pot3[i]; break;} case 'x':{ tstoin+=pot3[i]; break;} case '2':{ tstoin+=2*pot3[i]; break;} } } return tstoin; } string intos(int index) { string tintos=""; for(int i=0; i<14 ; i++){ switch((index / pot3[i])%3){ case 0:{ tintos+="1"; break;} case 1:{ tintos+="X"; break;} case 2:{ tintos+="2"; break;} } } return tintos; } string intosn(int index, int n) { string tintos=""; for(int i=0; i<n ; i++){ switch((index / pot3[i])%3){ case 0:{ tintos+="1"; break;} case 1:{ tintos+="X"; break;} case 2:{ tintos+="2"; break;} } } return tintos; } double azar(){ return (double)rand()/RAND_MAX; } int generar_col(){ double a; string col; for(int i=0; i<14; i++){ a=azar(); if(a<porcentajes[i][0]){ col+='1';} else{ if(a<porcentajes[i][0]+porcentajes[i][1]){ col+='X';} else{ col+='2';}} } return stoin(col); } int fallos(int& index1, int& index2){ int tfallos=0; int bit1; int bit2; for(int i=13; i>=0 ; i--){ bit1=(index1/pot3[i])%3; bit2=(index2/pot3[i])%3; tfallos+= (bit1!=bit2); } return tfallos; } bool leer_porcentajes(){ linea="bets.pct"; fin.open(linea.c_str()); if(fin.is_open()){ for(int i=0 ;i<14 ; i++){ fin >> porcentajes[i][0]; fin >> porcentajes[i][1]; fin >> porcentajes[i][2]; porcentajes[i][0]/=100; porcentajes[i][1]/=100; porcentajes[i][2]/=100; } fin.close(); return true; }else{ return false; } } bool leer_apostados(){ linea="lae.pct"; fin.open(linea.c_str()); if(fin.is_open()){ for(int i=0 ;i<14 ; i++){ fin >> apostados[i][0]; fin >> apostados[i][1]; fin >> apostados[i][2]; apostados[i][0]/=100; apostados[i][1]/=100; apostados[i][2]/=100; } fin.close(); return true; }else{ return false; } } bool leer_recaudacion(){ linea="recaudacion.txt"; fin.open(linea.c_str()); if(fin.is_open()){ fin >> recaudacion; fin.close(); return true; }else{ return false; } } bool leer_columnas(){ linea=nombre_archivo; fin.open(linea.c_str()); if(fin.is_open()){ while(getline(fin,linea)){ colarchivo.push_back(linea); n_col++; } fin.close(); return true; }else{ return false; } } double probabilidad_col(int que_col){ double prob=1.0; for(int i=0; i<14; i++){ switch(colarchivo[que_col][i]){ case '1':{ prob*=porcentajes[i][0]/apostados[i][0]; break;} case 'X':{ prob*=porcentajes[i][1]/apostados[i][1]; break;} case '2':{ prob*=porcentajes[i][2]/apostados[i][2]; break;} } } return prob; } void calcular_probs(){ for(int i=0; i<n_col; i++){ probabilidades.push_back(probabilidad_col(i)); } return; } void crear_indices(){ indices=new int[n_col]; for(int i=0; i<n_col; i++){ indices[i]=stoin(colarchivo[i]); } return; } void calcular_premios(int columna[]){ double p14=1.0; double p13=1.0; double p12=1.0; double p11=1.0; double p10=1.0; double cr[14]; double suma[14]; double suma13=0; double suma12=0; double suma11=0; double suma10=0; double premio14; double premio13; double premio12; double premio11; double premio10; int a14; //Acertantes de 14 int a13; int a12; int a11; int a10; double apuestas; double prob=1; for(int i=0; i<14; i++){ switch(columna[i]){ case 0:{ prob*=porcentajes[i][0]; p14*=apostados[i][0]; cr[i]=(1-apostados[i][0])/apostados[i][0]; break;} case 1:{ prob*=porcentajes[i][1]; p14*=apostados[i][1]; cr[i]=(1-apostados[i][1])/apostados[i][1]; break;} case 2:{ prob*=porcentajes[i][2]; p14*=apostados[i][2]; cr[i]=(1-apostados[i][2])/apostados[i][2]; break;} } suma13+=cr[i]; } p13=p14*suma13; suma[0]=suma13; for(int i=1; i<14; i++){ suma[i]=suma[i-1]-cr[i-1]; suma12+=suma[i]*cr[i-1]; } p12=p14*suma12; suma[0]=suma12; for(int i=1; i<13; i++){ suma[i]=suma[i-1]-cr[i-1]*suma[i]; suma11+=suma[i]*cr[i-1]; } p11=p14*suma11; suma[0]=suma11; for(int i=1; i<12; i++){ suma[i]=suma[i-1]-cr[i-1]*suma[i]; suma10+=suma[i]*cr[i-1]; } p10=p14*suma10; apuestas=recaudacion*2; a14=ceil(apuestas*p14); a13=ceil(apuestas*p13); a12=ceil(apuestas*p12); a11=ceil(apuestas*p11); a10=ceil(apuestas*p10); premio14=recaudacion*0.12/a14; premio13=recaudacion*0.08/a13; premio12=recaudacion*0.08/a12; premio11=recaudacion*0.08/a11; premio10=recaudacion*0.09/a10; /* premio14=0.06/p14; premio13=0.04/p13; premio12=0.04/p12; premio11=0.04/p11; premio10=0.045/p10;*/ // if(premio14>recaudacion*0.12) premio14=recaudacion*0.12; // if(premio13>recaudacion*0.08) premio13=recaudacion*0.08; if(premio10<1){ premio10=0;} if(premio11<1){ premio11=0; premio12=recaudacion*0.16/a12;} int index=0; for(int i=13; i>0; i--){ index+=columna[i]; index*=3; } index+=columna[0]; if(premio10>=2500) premio10=premio10-(premio10-2500)*0.2; if(premio11>=2500) premio11=premio11-(premio11-2500)*0.2; if(premio12>=2500) premio12=premio12-(premio12-2500)*0.2; if(premio13>=2500) premio13=premio13-(premio13-2500)*0.2; if(premio14>=2500) premio14=premio14-(premio14-2500)*0.2; premios14[0][index]=premio14; premios14[1][index]=premio13; premios14[2][index]=premio12; premios14[3][index]=premio11; premios14[4][index]=premio10; probs[index]=prob; return; } void calcular_todos(){ int lacolumna[14]; int ganadora[14]; // cout << "Calculando premios." << endl; fin.open("ganadora.txt"); getline(fin,linea); fin.close(); for(int i=0; i<14; i++){ if(linea[i]=='1'){ porcentajes[i][0]=1; porcentajes[i][1]=0; porcentajes[i][2]=0;} if(linea[i]=='2'){ porcentajes[i][0]=0; porcentajes[i][1]=0; porcentajes[i][2]=1;} if(linea[i]=='X'){ porcentajes[i][0]=0; porcentajes[i][1]=1; porcentajes[i][2]=0;} } for(int i=0; i<14; i++) lacolumna[i]=0; while(1){ calcular_premios(lacolumna); lacolumna[0]++; for(int i=0; i<13; i++){ if(lacolumna[i]==3){ lacolumna[i+1]++; lacolumna[i]=0;} } if(lacolumna[13]==3) break; } // cout << "Calculados todos los premios." << endl; return; } void calcular_escrut(){ // cout << "Simulando." << endl; //contar premios for(int i=0; i<n_col; i++){ aciertos[0][indices[i]]++; { int tindex[4]; int cambios[4]; int tbit[4]; //premios 13 for(cambios[0]=0; cambios[0]<14; cambios[0]++){ tbit[0]=(indices[i]/pot3[cambios[0]])%3; for(int j=0; j<3; j++){ if(tbit[0]==j) continue; tindex[0]=indices[i]+(j-tbit[0])*pot3[cambios[0]]; aciertos[1][tindex[0]]++; //premios 12 for(cambios[1]=cambios[0]+1; cambios[1]<14; cambios[1]++){ tbit[1]=(tindex[0]/pot3[cambios[1]])%3; for(int k=0; k<3; k++){ if(tbit[1]==k) continue; tindex[1]=tindex[0]+(k-tbit[1])*pot3[cambios[1]]; aciertos[2][tindex[1]]++; //premios 11 for(cambios[2]=cambios[1]+1; cambios[2]<14; cambios[2]++){ tbit[2]=(tindex[1]/pot3[cambios[2]])%3; for(int l=0; l<3; l++){ if(tbit[2]==l) continue; tindex[2]=tindex[1]+(l-tbit[2])*pot3[cambios[2]]; aciertos[3][tindex[2]]++; //premios 10 for(cambios[3]=cambios[2]+1; cambios[3]<14; cambios[3]++){ tbit[3]=(tindex[2]/pot3[cambios[3]])%3; for(int m=0; m<3; m++){ if(tbit[3]==m) continue; tindex[3]=tindex[2]+(m-tbit[3])*pot3[cambios[3]]; aciertos[4][tindex[3]]++; } } } } } } } } } // Calcular premios, rentabilidad, porcentajes // if( i % 100000 == 0) cout << "Pasadas " << i << " columnas." << endl; } emtotal=0; pdepremios=0; for(int i=0; i<4782969; i++){ ganado[i]=0; bool maxp=true; for(int j=0; j<5; j++){ ganado[i]+=premios14[j][i]*aciertos[j][i]; if(aciertos[j][i]>0) ppremios[j]+=probs[i]; if(aciertos[j][i]>0 && maxp && premios14[j][i]>0){ ppremiosmc[j]+=probs[i];} if(aciertos[j][i]>0 && maxp){ ppremiosm[j]+=probs[i]; maxp=false;} } if(ganado[i]>(n_col/2)) prentable+=probs[i]; if(ganado[i]>0){ pdepremios+=probs[i]; elem_grafico.clear(); elem_grafico.push_back(ganado[i]); elem_grafico.push_back(probs[i]); grafico.push_back(elem_grafico); } emtotal+=ganado[i]*probs[i]; } // cout << "Simulacion terminada." << endl; return; } void sacar_resultados(){ cout << "Resultados de la simulacion." << endl; cout << endl; cout << "Premio Probabilidad"<< endl; for(int i=0; i<5; i++){ if(FULLPREMIOS){ cout << 14-i << " " << ppremios[i]*100 << " " << ppremiosm[i]*100 << " " << ppremiosmc[i]*100 << endl; }else{ cout << 14-i << " " << ppremios[i]*100 << endl; } } if(FULLPREMIOS){ cout << "Sin cobrar: " << (1-ppremiosmc[0]-ppremiosmc[1]-ppremiosmc[2]-ppremiosmc[3]-ppremiosmc[4])*100 << endl;} cout << endl; cout << "Probabilidad de rentabilizar: " << prentable*100 << endl; cout << "Probabilidad de premios: " << pdepremios*100 << endl; if(corteok) cout << "Probabilidad de pasar el corte: " << pcorte*100 << endl; cout << "EM total: " << emtotal << " gastando " << (double)n_col/2 << endl; cout << "Rentabilidad total: " << 200*emtotal/n_col << endl; return; } void diferencias2(int maxfallos){ vector<int> elegidas; bool entra; elegidas.push_back(indices[n_col-1]); for(int i=n_col-2; i>=0; i--){ entra=true; for(int j=0; j<elegidas.size(); j++){ if(fallos(elegidas[j],indices[i])<=maxfallos){ entra=false; break; } } if(entra) elegidas.push_back(indices[i]); } switch(maxfallos){ case 1: linea=nombre_archivo+".c13"; break; case 2: linea=nombre_archivo+".c12"; break; case 3: linea=nombre_archivo+".c11"; break; case 4: linea=nombre_archivo+".c10"; break; case 5: linea=nombre_archivo+".c09"; break; } fout.open(linea.c_str()); for(int i=0; i<elegidas.size(); i++) fout << intos(elegidas[i]) << endl; fout.close(); cout << "Al " << 14-maxfallos << " se jugarian " << elegidas.size() << "/"<< n_col << "("<< (int)100*elegidas.size()/n_col << "%) por " << (double)elegidas.size()/2 << " euros." << endl; return; } bool funcionordena (vector<double> i,vector<double> j) { return (i[0]>j[0]); } void sacar_tren(){ fout.open("tren.txt"); double totalsimtren=0; for(int i=0; i<=1000; i++){ totalsimtren+=(double)simtren[i]/simulaciones; fout << i << " " << (double)simtren[i]/simulaciones << " " << totalsimtren << endl; } fout.close(); return; } void sacar_grafico(){ sort(grafico.begin(),grafico.end(),funcionordena); fout.open("grafico.txt"); double total=0; for(int i=0; i<grafico.size(); i++){ if(grafico[i][1]>0.00000001) fout << total << " " << grafico[i][0] << endl; total+=grafico[i][1]; } fout << total << " 0" << endl; fout.close(); return; } bool funcionordena2 (double i,double j) { return (i>j); } void sacar_grafico2(){ cout << "Simulacion temporada(50jor). Cuantos ciclos aleatorios?" << endl; int n_temp; double p_temp; vector<double> rentabilidades; cin >> n_temp; p_temp=1/(double)n_temp; double gasto; gasto=50*n_col/2; for(int i=0; i<n_temp; i++){ double premio=0; for(int j=0; j<50; j++){ int col; col=generar_col(); premio+=ganado[col]; } rentabilidades.push_back(premio/gasto*100); } cout << "Simulacion terminada." << endl; sort(rentabilidades.begin(),rentabilidades.end(),funcionordena2); fout.open("grafico1T.txt"); double total=0; fout << total << " " << rentabilidades[0] << endl; for(int i=0; i<rentabilidades.size(); i++){ total+=p_temp; fout << total << " " << rentabilidades[i] << endl; } fout.close(); return; } void sacar_grafico3(){ cout << "Simulacion 10 temporada(500jor). Cuantos ciclos aleatorios?" << endl; int n_temp; double p_temp; vector<double> rentabilidades; cin >> n_temp; p_temp=1/(double)n_temp; double gasto; gasto=500*n_col/2; for(int i=0; i<n_temp; i++){ double premio=0; for(int j=0; j<500; j++){ int col; col=generar_col(); premio+=ganado[col]; } rentabilidades.push_back(premio/gasto*100); } cout << "Simulacion terminada." << endl; sort(rentabilidades.begin(),rentabilidades.end(),funcionordena2); fout.open("grafico10T.txt"); double total=0; fout << total << " " << rentabilidades[0] << endl; for(int i=0; i<rentabilidades.size(); i++){ total+=p_temp; fout << total << " " << rentabilidades[i] << endl; } fout.close(); return; } void simulacion_tren(){ int isimtren; double jornadas=0; double valoracion; double oldvaloracion; double iprecision; double sigma; double X2; double X; double EX2; double EX; vector<double> Xi; int rent10=0; int rent50=0; // cout << "Empiezo simulacion tren." << endl; srand ( time(NULL) ); for(int i=0; i<simulaciones; i++){ double gasto=0; double ganancia=0; isimtren=0; do{ int col=generar_col(); gasto+=n_col/2; ganancia+=ganado[col]; jornadas++; isimtren++; if(isimtren==1000){ break;} // if(CORTATREN && isimtren==1000){ break;} // cout << gasto << " " << ganancia << endl; }while(gasto>ganancia); if(isimtren<=10) rent10++; if(isimtren<=50) rent50++; if(isimtren<=1000){ simtren[isimtren]++;}else{ simtren[1000]++;} // cout << jornadas << endl; } jornadas=jornadas/simulaciones; /* iprecision=0; X=0; X2=0; do{ X=0; for(int i=0; i<10000; i++){ double gasto=0; double ganancia=0; isimtren=0; do{ int col=generar_col(); gasto+=n_col/2; ganancia+=ganado[col]; jornadas++; isimtren++; if(CORTATREN && isimtren==1000){ break;} // cout << gasto << " " << ganancia << endl; }while(gasto>ganancia); if(isimtren<=10) rent10++; if(isimtren<=50){ rent50++; X++;} if(isimtren<=1000){ simtren[isimtren]++;}else{ simtren[1000]++;} // X+=isimtren; // cout << jornadas << endl; } iprecision++; // oldvaloracion=valoracion; // valoracion=jornadas/(iprecision*1000); // }while(iprecision<5 || abs(valoracion-oldvaloracion)>0.00001); X=X/10000; X2=(X2*(iprecision-1)+X)/(iprecision); Xi.push_back(X); // EX2=X2/pow(iprecision*1000); // sigma=sqrt(abs(EX2-pow(EX,2))); if(iprecision>10){ sigma=0; for(int i=0; i<Xi.size(); i++){ sigma+=pow(Xi[i]-X2,2); } sigma=sqrt(sigma/(Xi.size()-1)); cout << 2*sigma << " " << X << endl;}else{sigma=1;} }while(2*sigma>0.001); // cout << X << " " << X2 << endl; simulaciones=iprecision*10000;*/ // cout << iprecision << endl; cout << "Rent10: " << (double)rent10/simulaciones << " Rent50: " << (double)rent50/simulaciones << " Media: " << jornadas << endl; // if(CORTATREN){ cout << simtren[1000] << " ";} cout << simtren[1000] << " "; // cout << "Necesarias de media " << jornadas << " para llegar a rentabilidad." << endl; return; } void especial_tren(){ int isimtren; double jornadas=0; double valoracion; double oldvaloracion; double iprecision; double sigma; double X2; double X; double EX2; double EX; vector<double> Xi; int rent10=0; int rent50=0; int rent100=0; // cout << "Empiezo simulacion tren." << endl; srand ( time(NULL) ); simulaciones=100000; for(int i=0; i<simulaciones; i++){ double gasto=0; double ganancia=0; isimtren=0; do{ int col=generar_col(); gasto+=n_col/2; ganancia+=ganado[col]; jornadas++; isimtren++; if(isimtren==101){ break;} // if(CORTATREN && isimtren==1000){ break;} // cout << gasto << " " << ganancia << endl; }while(gasto>ganancia); if(isimtren<=10) rent10++; if(isimtren<=50) rent50++; if(isimtren<=100) rent100++; // cout << jornadas << endl; } jornadas=jornadas/simulaciones; cout << "Rent10: " << (double)rent10/simulaciones << " Rent50: " << (double)rent50/simulaciones << " Rent100: " << (double)rent100/simulaciones << endl; return; } bool calcular_corte(){ int ncorte; int ndistintas; int icorte[14]; double *probscorte; bool *estan; string col; linea="corte.txt"; fin.open(linea.c_str()); if(fin.is_open()){ // cout << "Empiezo calculo del corte." << endl; getline(fin,linea); fin.close(); ncorte=0; for(int i=0; i<14; i++){ if(linea[i]=='X'){ icorte[ncorte]=i; ncorte++; } } ndistintas=pow(3,ncorte); //cout << ndistintas << endl; probscorte=new double[ndistintas]; estan=new bool[ndistintas]; double ptotal=0; for(int i=0; i<ndistintas; i++){ estan[i]=false; linea=intosn(i,ncorte); probscorte[i]=1; for(int j=0; j<ncorte; j++){ switch(linea[j]){ case '1':{ probscorte[i]*=porcentajes[icorte[j]][0]; break;} case 'X':{ probscorte[i]*=porcentajes[icorte[j]][1]; break;} case '2':{ probscorte[i]*=porcentajes[icorte[j]][2]; break;} } } //cout << probscorte[i] << endl; ptotal+=probscorte[i]; } //cout << ptotal << " TOTAL" << endl; for(int i=0; i<n_col; i++){ linea=""; for(int j=0; j<ncorte; j++){ linea+=colarchivo[i][icorte[j]]; } //cout << linea << endl; estan[stoinn(linea,ncorte)]=true; //cout << stoinn(linea,ncorte) << endl; } pcorte=0; for(int i=0; i<ndistintas; i++){ pcorte+=probscorte[i]*estan[i]; } return true; }else{ return false; } } int main(int argc, char* argv[]) { if(not leer_porcentajes()) return 0; if(not leer_apostados()) return 0; nombre_archivo=argv[1]; if(not leer_recaudacion()){ cout << "Recaudacion esperada en la jornada? "; cin >> recaudacion; } if(nombre_archivo[0]=='-'){ nombre_archivo=argv[2]; leer_columnas(); calcular_todos(); crear_indices(); calcular_escrut(); if(2*emtotal/n_col<1.1){CORTATREN=true;}{ simulacion_tren(); sacar_tren();} if(CORTATREN) cout << "TREN CORTADO" << endl; return 0; } if(nombre_archivo[0]=='s'){ nombre_archivo=argv[2]; leer_columnas(); calcular_todos(); crear_indices(); calcular_escrut(); especial_tren(); sacar_tren(); return 0; } if(nombre_archivo[0]=='f'){FULLPREMIOS=true; nombre_archivo=argv[2];} { leer_columnas(); calcular_todos(); crear_indices(); calcular_escrut(); corteok=calcular_corte(); sacar_resultados(); char c; cout << "Simulacion tren? "; cin >> c; if(c=='s') {if(2*emtotal/n_col<1.1){CORTATREN=true;}{ simulacion_tren(); sacar_tren();}} if(CORTATREN) cout << "TREN CORTADO" << endl; cout << "Grafico jornada? "; cin >> c; if(c=='s') sacar_grafico(); cout << "Grafico temporada? "; cin >> c; if(c=='s') sacar_grafico2(); cout << "Grafico 10 temporadas? "; cin >> c; if(c=='s') sacar_grafico3(); return 0; } }
22.831897
188
0.571644
[ "vector" ]
34dbbd072626602962161fec4bb165dd0e64b781
44,515
cpp
C++
Tools/KFModTool/core/prettynames.cpp
IvanDSM/KingsFieldRE
b22549a7e93e3c0e77433d7bea8bbde6a5b9f6a3
[ "MIT" ]
16
2020-07-09T15:38:41.000Z
2022-03-03T19:05:24.000Z
Tools/KFModTool/core/prettynames.cpp
IvanDSM/KingsFieldRE
b22549a7e93e3c0e77433d7bea8bbde6a5b9f6a3
[ "MIT" ]
7
2020-07-03T22:38:24.000Z
2022-01-09T18:25:22.000Z
Tools/KFModTool/core/prettynames.cpp
IvanDSM/KingsFieldRE
b22549a7e93e3c0e77433d7bea8bbde6a5b9f6a3
[ "MIT" ]
2
2021-08-23T08:25:44.000Z
2022-01-09T16:05:46.000Z
#include "prettynames.h" namespace PrettyNames { const QHash<const QString, QString> prettyKF2{ {QStringLiteral("FDAT.T0"), QStringLiteral("Western Shore Tilemap")}, {QStringLiteral("FDAT.T1"), QStringLiteral("Western Shore Map DB")}, {QStringLiteral("FDAT.T2"), QStringLiteral("Western Shore Script")}, {QStringLiteral("FDAT.T3"), QStringLiteral("Garrison Tilemap")}, {QStringLiteral("FDAT.T4"), QStringLiteral("Garrison Map DB")}, {QStringLiteral("FDAT.T5"), QStringLiteral("Garrison Script")}, {QStringLiteral("FDAT.T6"), QStringLiteral("Central Village Tilemap")}, {QStringLiteral("FDAT.T7"), QStringLiteral("Central Village Map DB")}, {QStringLiteral("FDAT.T8"), QStringLiteral("Central Village Script")}, {QStringLiteral("FDAT.T9"), QStringLiteral("East Village Tilemap")}, {QStringLiteral("FDAT.T10"), QStringLiteral("East Village Map DB")}, {QStringLiteral("FDAT.T11"), QStringLiteral("East Village Script")}, {QStringLiteral("FDAT.T12"), QStringLiteral("Cathedral Tilemap")}, {QStringLiteral("FDAT.T13"), QStringLiteral("Cathedral Map DB")}, {QStringLiteral("FDAT.T14"), QStringLiteral("Cathedral Script")}, {QStringLiteral("FDAT.T15"), QStringLiteral("Big Mine Tilemap")}, {QStringLiteral("FDAT.T16"), QStringLiteral("Big Mine Map DB")}, {QStringLiteral("FDAT.T17"), QStringLiteral("Big Mine Script")}, {QStringLiteral("FDAT.T18"), QStringLiteral("Necron's Coliseum Tilemap")}, {QStringLiteral("FDAT.T19"), QStringLiteral("Necron's Coliseum Map DB")}, {QStringLiteral("FDAT.T20"), QStringLiteral("Necron's Coliseum Script")}, {QStringLiteral("FDAT.T21"), QStringLiteral("Guyra's Lair Tilemap")}, {QStringLiteral("FDAT.T22"), QStringLiteral("Guyra's Lair Map DB")}, {QStringLiteral("FDAT.T23"), QStringLiteral("Guyra's Lair Script")}, {QStringLiteral("FDAT.T24"), QStringLiteral("Weird Debug Map Tilemap")}, {QStringLiteral("FDAT.T25"), QStringLiteral("Weird Debug Map Map DB")}, {QStringLiteral("FDAT.T26"), QStringLiteral("Weird Debug Map Script")}, {QStringLiteral("FDAT.T27"), QStringLiteral("Texture Database")}, {QStringLiteral("FDAT.T28"), QStringLiteral("Game Database")}, {QStringLiteral("FDAT.T29"), QStringLiteral("Dagger Viewmodel")}, {QStringLiteral("FDAT.T30"), QStringLiteral("Short Sword Viewmodel")}, {QStringLiteral("FDAT.T31"), QStringLiteral("Knight Sword Viewmodel")}, {QStringLiteral("FDAT.T32"), QStringLiteral("Morning Star Viewmodel")}, {QStringLiteral("FDAT.T33"), QStringLiteral("Battle Hammer Viewmodel")}, {QStringLiteral("FDAT.T34"), QStringLiteral("Bastard Sword Viewmodel")}, {QStringLiteral("FDAT.T35"), QStringLiteral("Crescent Axe Viewmodel")}, {QStringLiteral("FDAT.T36"), QStringLiteral("Flame Sword Viewmodel")}, {QStringLiteral("FDAT.T37"), QStringLiteral("Shiden Viewmodel")}, {QStringLiteral("FDAT.T38"), QStringLiteral("Spider Viewmodel")}, {QStringLiteral("FDAT.T39"), QStringLiteral("Ice Blade Viewmodel")}, {QStringLiteral("FDAT.T40"), QStringLiteral("Seath's Sword Viewmodel")}, {QStringLiteral("FDAT.T41"), QStringLiteral("Moonlight Sword Viewmodel")}, {QStringLiteral("FDAT.T42"), QStringLiteral("Dark Slayer Viewmodel")}, {QStringLiteral("FDAT.T43"), QStringLiteral("Bow Viewmodel")}, {QStringLiteral("FDAT.T44"), QStringLiteral("Arbalest Viewmodel")}, {QStringLiteral("ITEM.T0"), QStringLiteral("Dagger Model")}, {QStringLiteral("ITEM.T1"), QStringLiteral("Short Sword Model")}, {QStringLiteral("ITEM.T2"), QStringLiteral("Knight Sword Model")}, {QStringLiteral("ITEM.T3"), QStringLiteral("Morning Star Model")}, {QStringLiteral("ITEM.T4"), QStringLiteral("Battle Hammer Model")}, {QStringLiteral("ITEM.T5"), QStringLiteral("Bastard Sword Model")}, {QStringLiteral("ITEM.T6"), QStringLiteral("Crescent Axe Model")}, {QStringLiteral("ITEM.T7"), QStringLiteral("Flame Sword Model")}, {QStringLiteral("ITEM.T8"), QStringLiteral("Shiden Model")}, {QStringLiteral("ITEM.T9"), QStringLiteral("Spider Model")}, {QStringLiteral("ITEM.T10"), QStringLiteral("Ice Blade Model")}, {QStringLiteral("ITEM.T11"), QStringLiteral("Seath's Sword Model")}, {QStringLiteral("ITEM.T12"), QStringLiteral("Moonlight Sword Model")}, {QStringLiteral("ITEM.T13"), QStringLiteral("Dark Slayer Model")}, {QStringLiteral("ITEM.T14"), QStringLiteral("Bow Model")}, {QStringLiteral("ITEM.T15"), QStringLiteral("Arbalest Model")}, {QStringLiteral("ITEM.T16"), QStringLiteral("Iron Mask Model")}, {QStringLiteral("ITEM.T17"), QStringLiteral("Knight Helm Model")}, {QStringLiteral("ITEM.T18"), QStringLiteral("Great Helm Model")}, {QStringLiteral("ITEM.T19"), QStringLiteral("Blood Crown Model")}, {QStringLiteral("ITEM.T20"), QStringLiteral("Lightning Helm Model")}, {QStringLiteral("ITEM.T21"), QStringLiteral("Seath's Helm Model")}, {QStringLiteral("ITEM.T22"), QStringLiteral("Breast Plate Model")}, {QStringLiteral("ITEM.T23"), QStringLiteral("Knight Plate Model")}, {QStringLiteral("ITEM.T24"), QStringLiteral("Ice Armor Model")}, {QStringLiteral("ITEM.T25"), QStringLiteral("Dark Armor Model")}, {QStringLiteral("ITEM.T26"), QStringLiteral("Seath's Armor Model")}, {QStringLiteral("ITEM.T27"), QStringLiteral("Leather Shield Model")}, {QStringLiteral("ITEM.T28"), QStringLiteral("Large Shield Model")}, {QStringLiteral("ITEM.T29"), QStringLiteral("Moon Guard Model")}, {QStringLiteral("ITEM.T30"), QStringLiteral("Crystal Guard Model")}, {QStringLiteral("ITEM.T31"), QStringLiteral("Skull Shield Model")}, {QStringLiteral("ITEM.T32"), QStringLiteral("Seath's Shield Model")}, {QStringLiteral("ITEM.T33"), QStringLiteral("Iron Gloves Model")}, {QStringLiteral("ITEM.T34"), QStringLiteral("Stone Hands Model")}, {QStringLiteral("ITEM.T35"), QStringLiteral("Silver Arms Model")}, {QStringLiteral("ITEM.T36"), QStringLiteral("Demon's Hands Model")}, {QStringLiteral("ITEM.T37"), QStringLiteral("Ruinous Gloves Model")}, {QStringLiteral("ITEM.T38"), QStringLiteral("Iron Boots Model")}, {QStringLiteral("ITEM.T39"), QStringLiteral("Leg Guarders Model")}, {QStringLiteral("ITEM.T40"), QStringLiteral("Silver Boots Model")}, {QStringLiteral("ITEM.T41"), QStringLiteral("Death Walkers Model")}, {QStringLiteral("ITEM.T42"), QStringLiteral("Ruinous Boots Model")}, {QStringLiteral("ITEM.T43"), QStringLiteral("Scorpion's Bracelet Model")}, {QStringLiteral("ITEM.T44"), QStringLiteral("Seath's Tear Model")}, {QStringLiteral("ITEM.T45"), QStringLiteral("Seath's Bracelet Model")}, {QStringLiteral("ITEM.T46"), QStringLiteral("Earth Ring Model")}, {QStringLiteral("ITEM.T47"), QStringLiteral("Psycpros Collar Model")}, {QStringLiteral("ITEM.T48"), QStringLiteral("Amulet Of Mist Model")}, {QStringLiteral("ITEM.T49"), QStringLiteral("Lightwave Ring Model")}, {QStringLiteral("ITEM.T50"), QStringLiteral("Pirate's Map Model")}, {QStringLiteral("ITEM.T51"), QStringLiteral("Miner's Map Model")}, {QStringLiteral("ITEM.T52"), QStringLiteral("Necron's Map Model")}, {QStringLiteral("ITEM.T53"), QStringLiteral("Gold Coin Model")}, {QStringLiteral("ITEM.T54"), QStringLiteral("Blood Stone Model")}, {QStringLiteral("ITEM.T55"), QStringLiteral("Moon Stone Model")}, {QStringLiteral("ITEM.T56"), QStringLiteral("Verdite Model")}, {QStringLiteral("ITEM.T57"), QStringLiteral("Earth Herb Model")}, {QStringLiteral("ITEM.T58"), QStringLiteral("Antidote Model")}, {QStringLiteral("ITEM.T59"), QStringLiteral("Dragon Crystal Model")}, {QStringLiteral("ITEM.T60"), QStringLiteral("Blue Potion Model")}, {QStringLiteral("ITEM.T61"), QStringLiteral("Red Potion Model")}, {QStringLiteral("ITEM.T62"), QStringLiteral("Green Potion Model")}, {QStringLiteral("ITEM.T63"), QStringLiteral("Gold Potion Model")}, {QStringLiteral("ITEM.T64"), QStringLiteral("\"A\" Potion Model")}, {QStringLiteral("ITEM.T65"), QStringLiteral("Crystal Flask Model")}, {QStringLiteral("ITEM.T66"), QStringLiteral("Figure Of Seath Model")}, {QStringLiteral("ITEM.T67"), QStringLiteral("Phantom Rod Model")}, {QStringLiteral("ITEM.T68"), QStringLiteral("Truth Glass Model")}, {QStringLiteral("ITEM.T69"), QStringLiteral("Seath's Plume Model")}, {QStringLiteral("ITEM.T70"), QStringLiteral("Demon's Pick Model")}, {QStringLiteral("ITEM.T71"), QStringLiteral("Harvine's Flute Model")}, {QStringLiteral("ITEM.T72"), QStringLiteral("Ground Bell Model")}, {QStringLiteral("ITEM.T73"), QStringLiteral("Fire Crystal Model")}, {QStringLiteral("ITEM.T74"), QStringLiteral("Water Crystal Model")}, {QStringLiteral("ITEM.T75"), QStringLiteral("Earth Crystal Model")}, {QStringLiteral("ITEM.T76"), QStringLiteral("Wind Crystal Model")}, {QStringLiteral("ITEM.T77"), QStringLiteral("Light Crystal Model")}, {QStringLiteral("ITEM.T78"), QStringLiteral("Dark Crystal Model")}, {QStringLiteral("ITEM.T79"), QStringLiteral("Crystal Model")}, {QStringLiteral("ITEM.T80"), QStringLiteral("Crystal Shard Model")}, {QStringLiteral("ITEM.T81"), QStringLiteral("\"A\" Ring Model")}, {QStringLiteral("ITEM.T82"), QStringLiteral("Elf's Key Model")}, {QStringLiteral("ITEM.T83"), QStringLiteral("Pirate's Key Model")}, {QStringLiteral("ITEM.T84"), QStringLiteral("Skull Key Model")}, {QStringLiteral("ITEM.T85"), QStringLiteral("Jail Key Model")}, {QStringLiteral("ITEM.T86"), QStringLiteral("Rhombus Key Model")}, {QStringLiteral("ITEM.T87"), QStringLiteral("Harvine's Key Model")}, {QStringLiteral("ITEM.T88"), QStringLiteral("Dragon Stone Model")}, {QStringLiteral("ITEM.T89"), QStringLiteral("Magician's Key Model")}, {QStringLiteral("ITEM.T90"), QStringLiteral("Silver Key Model")}, {QStringLiteral("ITEM.T91"), QStringLiteral("Gold Key Model")}, {QStringLiteral("ITEM.T92"), QStringLiteral("Shrine Key Model")}, {QStringLiteral("ITEM.T93"), QStringLiteral("\"A\" Herb Model")}, {QStringLiteral("ITEM.T94"), QStringLiteral("Moon Gate Model")}, {QStringLiteral("ITEM.T95"), QStringLiteral("Star Gate Model")}, {QStringLiteral("ITEM.T96"), QStringLiteral("Sun Gate Model")}, {QStringLiteral("ITEM.T97"), QStringLiteral("Moon Key Model")}, {QStringLiteral("ITEM.T98"), QStringLiteral("Star Key Model")}, {QStringLiteral("ITEM.T99"), QStringLiteral("Sun Key Model")}, {QStringLiteral("ITEM.T100"), QStringLiteral("Arrow For The Bow Model")}, {QStringLiteral("ITEM.T101"), QStringLiteral("Elf's Bolt Model")}, {QStringLiteral("ITEM.T102"), QStringLiteral("\"A\" Herb 2 Model")}, {QStringLiteral("ITEM.T103"), QStringLiteral("Text: Al Hunt")}, {QStringLiteral("ITEM.T104"), QStringLiteral("Text: Nola Bagil")}, {QStringLiteral("ITEM.T105"), QStringLiteral("Text: Mark Wozz")}, {QStringLiteral("ITEM.T106"), QStringLiteral("Text: Rand Ferrer")}, {QStringLiteral("ITEM.T107"), QStringLiteral("Text: Radd Bilheim")}, {QStringLiteral("ITEM.T108"), QStringLiteral("Text: Kehl Hunt")}, {QStringLiteral("ITEM.T109"), QStringLiteral("Text: Krola Sandler Amgun")}, {QStringLiteral("ITEM.T110"), QStringLiteral("Text: Cliff Lore")}, {QStringLiteral("ITEM.T111"), QStringLiteral("Text: David Tabler")}, {QStringLiteral("ITEM.T112"), QStringLiteral("Text: Dalf Vice")}, {QStringLiteral("ITEM.T113"), QStringLiteral("Text: Harris Carvitto")}, {QStringLiteral("ITEM.T114"), QStringLiteral("Text: Teo Gigi Budwell")}, {QStringLiteral("ITEM.T115"), QStringLiteral("Text: Karen Leon Shore")}, {QStringLiteral("ITEM.T116"), QStringLiteral("Text: Base No1")}, {QStringLiteral("ITEM.T117"), QStringLiteral("Text: Base No2")}, {QStringLiteral("ITEM.T118"), QStringLiteral("Text: Base No3")}, {QStringLiteral("ITEM.T119"), QStringLiteral("Text: Base No4")}, {QStringLiteral("ITEM.T120"), QStringLiteral("Text: Base No5")}, {QStringLiteral("ITEM.T121"), QStringLiteral("Text: Base No6")}, {QStringLiteral("ITEM.T122"), QStringLiteral("Text: The Magic Cave Of Ice")}, {QStringLiteral("ITEM.T123"), QStringLiteral("Text: Base No7")}, {QStringLiteral("ITEM.T124"), QStringLiteral("Text: The Entrance To The North Village")}, {QStringLiteral("ITEM.T125"), QStringLiteral("Text: The Entrance To The South Village")}, {QStringLiteral("ITEM.T126"), QStringLiteral("Text: The Space For Completion No Trespassing")}, {QStringLiteral("ITEM.T127"), QStringLiteral("Text: The Entrance To The Central Village")}, {QStringLiteral("ITEM.T128"), QStringLiteral("Text: The Entrance To The Big Mine")}, {QStringLiteral("ITEM.T129"), QStringLiteral("Text: The Underworld Prison No1")}, {QStringLiteral("ITEM.T130"), QStringLiteral("Text: The Underworld Prison No2")}, {QStringLiteral("ITEM.T131"), QStringLiteral("Text: The Cemetery For The Military Guards Of King Harvine III")}, {QStringLiteral("ITEM.T132"), QStringLiteral("Text: Royal Treasure House")}, {QStringLiteral("ITEM.T133"), QStringLiteral("Text: The Magic Cave Of Fire")}, {QStringLiteral("ITEM.T134"), QStringLiteral("Text: Warriors Who Were Killed By Guyras Legion Are Buried Here")}, {"ITEM.T135", "Text: The Souls Of The Guards Who Were Killed Are Waiting To Watch The Next Fight"}, {"ITEM.T136", "Text: The King Of Winds King Harvine IIIHad Started To Construct His Castle Here"}, {QStringLiteral("ITEM.T137"), QStringLiteral( "Text: The Castle Of The Great Ruler Of The Northern Continent King Harvine III")}, {QStringLiteral("ITEM.T138"), QStringLiteral("Text: Danger Ahead")}, {QStringLiteral("ITEM.T139"), QStringLiteral( "Text: In The Name Of The Great Mage No One Can Enter This Cave Of Earth Soul")}, {"ITEM.T140", "Text: Galth Free The Demon Of The Darkside Died With The High Elves He Is A Phantom Of " "The " "World"}, {QStringLiteral("ITEM.T141"), QStringLiteral("Text: A Message From The East Land Rest In Peace Here")}, {"ITEM.T142", "Text: Most Soldiers Have Already Died There Is No Way To Leave The Island We Realize " "That " "There Is No Way Back Home"}, {"ITEM.T143", "Text: In The Name Of Tsedeck The Mage Of Fire Who Defeated King Harvine III And Ruled " "The " "Northern Continent"}, {QStringLiteral("ITEM.T144"), QStringLiteral("Text: Gigis House Sandler")}, {QStringLiteral("ITEM.T145"), QStringLiteral("Text: They Can Be Attacked By Bows Take Good Aim")}, {QStringLiteral("ITEM.T146"), QStringLiteral("Text: Do Not Enter Old Hand")}, {QStringLiteral("ITEM.T147"), QStringLiteral("Text: Medical Herbs For Sale Al Hunt")}, {QStringLiteral("ITEM.T148"), QStringLiteral("Text: The South Graveyard To The Small Mine")}, {QStringLiteral("ITEM.T149"), QStringLiteral("Text: Termites Nest Ahead Watch Your Step")}, {"ITEM.T150", "Text: My Beloved Son You Have Fought For Me And Have Lost Your Life For Me May You Rest " "In " "Peace"}, {QStringLiteral("ITEM.T151"), QStringLiteral("Text: Do Not Get Closer Krakens Nest")}, {QStringLiteral("ITEM.T152"), QStringLiteral("Text: Dangerous No Exit")}, {QStringLiteral("ITEM.T153"), QStringLiteral("Text: The Elf Cave")}, {"ITEM.T154", "Text: By And By A Man Who Comes Here Beats The Black Dragon With The Blessing Of Seath"}, {QStringLiteral("ITEM.T155"), QStringLiteral("Text: The Cave Of The Darkside This Is Hell")}, {QStringLiteral("ITEM.T156"), QStringLiteral("Text: Offer Everything To Guyra Who Rules The Light And The Dark")}, {QStringLiteral("ITEM.T157"), QStringLiteral("Text: They Are Creating Devils Be Careful")}, {QStringLiteral("ITEM.T158"), QStringLiteral("Text: When The Warriors Stand Up The Great Door Will Be Opened Again")}, {QStringLiteral("ITEM.T159"), QStringLiteral("Text: The Entrance To The Small Mine")}, {QStringLiteral("ITEM.T160"), QStringLiteral("Text: The Poisoned Cave Dangerous")}, {QStringLiteral("ITEM.T161"), QStringLiteral("Text: The Great Demon's Grave")}, {QStringLiteral("ITEM.T162"), QStringLiteral("Text: Earnests Body")}, {QStringLiteral("ITEM.T163"), QStringLiteral("Text: The Picture Of Warriors")}, {QStringLiteral("ITEM.T164"), QStringLiteral("Text: Truth Glass Green Slime")}, {QStringLiteral("ITEM.T165"), QStringLiteral("Text: Truth Glass Poison Slime")}, {QStringLiteral("ITEM.T166"), QStringLiteral("Text: Truth Glass Sigill")}, {QStringLiteral("ITEM.T167"), QStringLiteral("Text: Truth Glass Sigill 2")}, {QStringLiteral("ITEM.T168"), QStringLiteral("Text: Truth Glass Baltail")}, {QStringLiteral("ITEM.T169"), QStringLiteral("Text: Truth Glass Baltail 2")}, {QStringLiteral("ITEM.T170"), QStringLiteral("Text: Truth Glass Poison Baltail")}, {QStringLiteral("ITEM.T171"), QStringLiteral("Text: Truth Glass Poison Baltail 2")}, {QStringLiteral("ITEM.T172"), QStringLiteral("Text: Truth Glass Fire Elemental")}, {QStringLiteral("ITEM.T173"), QStringLiteral("Text: Truth Glass Fire Elemental 2")}, {QStringLiteral("ITEM.T174"), QStringLiteral("Text: Truth Glass Ghosts")}, {QStringLiteral("ITEM.T175"), QStringLiteral("Text: Truth Glass Reiks")}, {QStringLiteral("ITEM.T176"), QStringLiteral("Text: Truth Glass Head Eater")}, {QStringLiteral("ITEM.T177"), QStringLiteral("Text: Truth Glass Mogle")}, {QStringLiteral("ITEM.T178"), QStringLiteral("Text: Truth Glass S-Knight")}, {QStringLiteral("ITEM.T179"), QStringLiteral("Text: Truth Glass Necron's Soldiers")}, {QStringLiteral("ITEM.T180"), QStringLiteral("Text: Truth Glass Archers")}, {QStringLiteral("ITEM.T181"), QStringLiteral("Text: Truth Glass Skeleton")}, {QStringLiteral("ITEM.T182"), QStringLiteral("Text: Truth Glass Termite")}, {QStringLiteral("ITEM.T183"), QStringLiteral("Text: Truth Glass Kald")}, {QStringLiteral("ITEM.T184"), QStringLiteral("Text: Truth Glass Psythe")}, {QStringLiteral("ITEM.T185"), QStringLiteral("Text: Truth Glass Queen Termite")}, {QStringLiteral("ITEM.T186"), QStringLiteral("Text: Truth Glass Freeze Ball")}, {QStringLiteral("ITEM.T187"), QStringLiteral("Text: Truth Glass Log Stalker")}, {QStringLiteral("ITEM.T188"), QStringLiteral("Text: Truth Glass Demon Lord")}, {QStringLiteral("ITEM.T189"), QStringLiteral("Text: Truth Glass Kraken")}, {QStringLiteral("ITEM.T190"), QStringLiteral("Text: Truth Glass Kraken 2")}, {QStringLiteral("ITEM.T191"), QStringLiteral("Text: Truth Glass Earth Elemental")}, {QStringLiteral("ITEM.T192"), QStringLiteral("Text: Truth Glass Refma")}, {QStringLiteral("ITEM.T193"), QStringLiteral("Text: Truth Glass Tarn")}, {QStringLiteral("ITEM.T194"), QStringLiteral("Text: Truth Glass Copper Knight")}, {QStringLiteral("ITEM.T195"), QStringLiteral("Text: Truth Glass Dias Bagil")}, {QStringLiteral("ITEM.T196"), QStringLiteral("Text: Truth Glass Guyra")}, {QStringLiteral("ITEM.T197"), QStringLiteral("Text: Truth Glass Salamander")}, {QStringLiteral("ITEM.T198"), QStringLiteral("Text: Truth Glass Flame Spirit")}, {QStringLiteral("ITEM.T199"), QStringLiteral("Text: Truth Glass Billent")}, {QStringLiteral("ITEM.T200"), QStringLiteral("Text: Truth Glass Skeleton Of One Eyed Giant")}, {QStringLiteral("ITEM.T201"), QStringLiteral("Text: Truth Glass The Picture Of A King")}, {QStringLiteral("ITEM.T201"), QStringLiteral("Text: Truth Glass The Picture Of A King")}, {QStringLiteral("ITEM.T202"), QStringLiteral("Text: Truth Glass Mecha Demon Lord")}, {QStringLiteral("ITEM.T203"), QStringLiteral("Text: Truth Glass Mecha Termite")}, {QStringLiteral("ITEM.T204"), QStringLiteral("Text: Truth Glass Mecha Reiks")}, {QStringLiteral("ITEM.T205"), QStringLiteral("Text: Truth Glass Mages Candlesticks")}, {QStringLiteral("ITEM.T206"), QStringLiteral("Text: Truth Glass Bitt")}, {QStringLiteral("ITEM.T207"), QStringLiteral("Text: Truth Glass Refma 2")}, {QStringLiteral("ITEM.T208"), QStringLiteral("Text: Truth Glass Celffy Foss")}, {QStringLiteral("ITEM.T209"), QStringLiteral("Text: Truth Glass Celffy Foss 2")}, {QStringLiteral("ITEM.T210"), QStringLiteral("Text: Truth Glass Raffy Foss")}, {QStringLiteral("ITEM.T211"), QStringLiteral("Text: Truth Glass Jose Harven")}, {QStringLiteral("ITEM.T212"), QStringLiteral("Text: Truth Glass Nola Bagil")}, {QStringLiteral("ITEM.T213"), QStringLiteral("Text: Truth Glass Meryl")}, {QStringLiteral("ITEM.T214"), QStringLiteral("Text: Truth Glass Gigi Budwell")}, {QStringLiteral("ITEM.T215"), QStringLiteral("Text: Truth Glass Gigi Budwell 2")}, {QStringLiteral("ITEM.T216"), QStringLiteral("Text: Truth Glass Teo Budwell")}, {QStringLiteral("ITEM.T217"), QStringLiteral("Text: Truth Glass Teo Budwell 2")}, {QStringLiteral("ITEM.T218"), QStringLiteral("Text: Truth Glass Teo Budwell 3")}, {QStringLiteral("ITEM.T219"), QStringLiteral("Text: Truth Glass Karen Shore")}, {QStringLiteral("ITEM.T220"), QStringLiteral("Text: Truth Glass Leon Shore")}, {QStringLiteral("ITEM.T221"), QStringLiteral("Text: Truth Glass Leon Shore 2")}, {QStringLiteral("ITEM.T222"), QStringLiteral("Text: Truth Glass Al Hunt")}, {QStringLiteral("ITEM.T223"), QStringLiteral("Text: Truth Glass Harris Carvitto")}, {QStringLiteral("ITEM.T224"), QStringLiteral("Text: Truth Glass Fai Fadlin")}, {QStringLiteral("ITEM.T225"), QStringLiteral("Text: Truth Glass Cliff Lore")}, {QStringLiteral("ITEM.T226"), QStringLiteral("Text: Truth Glass Rand Ferrer")}, {QStringLiteral("ITEM.T227"), QStringLiteral("Text: Truth Glass David Tabler")}, {QStringLiteral("ITEM.T228"), QStringLiteral("Text: Truth Glass Dalf Vice")}, {QStringLiteral("ITEM.T229"), QStringLiteral("Text: Truth Glass Radd Bilheim")}, {QStringLiteral("ITEM.T230"), QStringLiteral("Text: Truth Glass Krola Amgun")}, {QStringLiteral("ITEM.T231"), QStringLiteral("Text: Truth Glass Krola Amgun 2")}, {QStringLiteral("ITEM.T232"), QStringLiteral("Text: Truth Glass Sandler Amgun")}, {QStringLiteral("ITEM.T233"), QStringLiteral("Text: Truth Glass Sandler Amgun 2")}, {QStringLiteral("ITEM.T234"), QStringLiteral("Text: Truth Glass Mark Wozz")}, {QStringLiteral("ITEM.T235"), QStringLiteral("Text: Truth Glass Earnest Clyde")}, {QStringLiteral("ITEM.T236"), QStringLiteral("Text: Truth Glass Kehl Hunt")}, {QStringLiteral("ITEM.T237"), QStringLiteral("Text: Truth Glass Kehl Hunt 2")}, {QStringLiteral("ITEM.T238"), QStringLiteral("Text: Truth Glass Karen Shore 2")}, {QStringLiteral("ITEM.T239"), QStringLiteral("Text: Truth Glass The Grave Of A Saint")}, {QStringLiteral("ITEM.T240"), QStringLiteral("Text: Truth Glass Earnest Clyde 2")}, {QStringLiteral("ITEM.T241"), QStringLiteral("Text: Truth Glass Dragon Grass")}, {QStringLiteral("ITEM.T242"), QStringLiteral("Text: Truth Glass Miria")}, {QStringLiteral("ITEM.T243"), QStringLiteral("Text: Meryl Dagger")}, {QStringLiteral("ITEM.T244"), QStringLiteral("Text: Meryl Short Sword")}, {QStringLiteral("ITEM.T245"), QStringLiteral("Text: Meryl Knight Sword")}, {QStringLiteral("ITEM.T246"), QStringLiteral("Text: Meryl Morning Star")}, {QStringLiteral("ITEM.T247"), QStringLiteral("Text: Meryl Battle Hammer")}, {QStringLiteral("ITEM.T248"), QStringLiteral("Text: Meryl Bastard Sword")}, {QStringLiteral("ITEM.T249"), QStringLiteral("Text: Meryl Crescent Axe")}, {QStringLiteral("ITEM.T250"), QStringLiteral("Text: Meryl Flame Sword")}, {QStringLiteral("ITEM.T251"), QStringLiteral("Text: Meryl Shiden")}, {QStringLiteral("ITEM.T252"), QStringLiteral("Text: Meryl Spider")}, {QStringLiteral("ITEM.T253"), QStringLiteral("Text: Meryl Ice Blade")}, {QStringLiteral("ITEM.T254"), QStringLiteral("Text: Meryl Seath's Sword")}, {QStringLiteral("ITEM.T255"), QStringLiteral("Text: Meryl Moonlight Sword")}, {QStringLiteral("ITEM.T256"), QStringLiteral("Text: Meryl Dark Slayer")}, {QStringLiteral("ITEM.T257"), QStringLiteral("Text: Meryl Bow")}, {QStringLiteral("ITEM.T258"), QStringLiteral("Text: Meryl Arbalest")}, {QStringLiteral("ITEM.T259"), QStringLiteral("Text: Meryl Iron Mask")}, {QStringLiteral("ITEM.T260"), QStringLiteral("Text: Meryl Knight Helm")}, {QStringLiteral("ITEM.T261"), QStringLiteral("Text: Meryl Great Helm")}, {QStringLiteral("ITEM.T262"), QStringLiteral("Text: Meryl Blood Crown")}, {QStringLiteral("ITEM.T263"), QStringLiteral("Text: Meryl Lightning Helm")}, {QStringLiteral("ITEM.T264"), QStringLiteral("Text: Meryl Seath's Helm")}, {QStringLiteral("ITEM.T265"), QStringLiteral("Text: Meryl Breast Plate")}, {QStringLiteral("ITEM.T266"), QStringLiteral("Text: Meryl Knight Plate")}, {QStringLiteral("ITEM.T267"), QStringLiteral("Text: Meryl Ice Armor")}, {QStringLiteral("ITEM.T268"), QStringLiteral("Text: Meryl Dark Armor")}, {QStringLiteral("ITEM.T269"), QStringLiteral("Text: Meryl Seath's Armor")}, {QStringLiteral("ITEM.T270"), QStringLiteral("Text: Meryl Leather Shield")}, {QStringLiteral("ITEM.T271"), QStringLiteral("Text: Meryl Large Shield")}, {QStringLiteral("ITEM.T272"), QStringLiteral("Text: Meryl Moon Guard")}, {QStringLiteral("ITEM.T273"), QStringLiteral("Text: Meryl Crystal Guard")}, {QStringLiteral("ITEM.T274"), QStringLiteral("Text: Meryl Skull Shield")}, {QStringLiteral("ITEM.T275"), QStringLiteral("Text: Meryl Seaths Shield")}, {QStringLiteral("ITEM.T276"), QStringLiteral("Text: Meryl Iron Gloves")}, {QStringLiteral("ITEM.T277"), QStringLiteral("Text: Meryl Stone Hands")}, {QStringLiteral("ITEM.T278"), QStringLiteral("Text: Meryl Silver Arms")}, {QStringLiteral("ITEM.T279"), QStringLiteral("Text: Meryl Demon's Hands")}, {QStringLiteral("ITEM.T280"), QStringLiteral("Text: Meryl Ruinous Gloves")}, {QStringLiteral("ITEM.T281"), QStringLiteral("Text: Meryl Iron Boots")}, {QStringLiteral("ITEM.T282"), QStringLiteral("Text: Meryl Leg Guarders")}, {QStringLiteral("ITEM.T283"), QStringLiteral("Text: Meryl Silver Boots")}, {QStringLiteral("ITEM.T284"), QStringLiteral("Text: Meryl Death Walkers")}, {QStringLiteral("ITEM.T285"), QStringLiteral("Text: Meryl Ruinous Boots")}, {QStringLiteral("ITEM.T286"), QStringLiteral("Text: Meryl Scorpion's Bracelet")}, {QStringLiteral("ITEM.T287"), QStringLiteral("Text: Meryl Seath's Tear")}, {QStringLiteral("ITEM.T288"), QStringLiteral("Text: Meryl Seath's Bracelet")}, {QStringLiteral("ITEM.T289"), QStringLiteral("Text: Meryl Earth Ring")}, {QStringLiteral("ITEM.T290"), QStringLiteral("Text: Meryl Psycpros Collar")}, {QStringLiteral("ITEM.T291"), QStringLiteral("Text: Meryl Amulet Of Mist")}, {QStringLiteral("ITEM.T292"), QStringLiteral("Text: Meryl Lightwave Ring")}, {QStringLiteral("ITEM.T293"), QStringLiteral("Text: Meryl Pirate's Map")}, {QStringLiteral("ITEM.T294"), QStringLiteral("Text: Meryl Miner's Map")}, {QStringLiteral("ITEM.T295"), QStringLiteral("Text: Meryl Necron's Map")}, {QStringLiteral("ITEM.T296"), QStringLiteral("Text: Meryl Blood Stone")}, {QStringLiteral("ITEM.T297"), QStringLiteral("Text: Meryl Moon Stone")}, {QStringLiteral("ITEM.T298"), QStringLiteral("Text: Meryl Verdite")}, {QStringLiteral("ITEM.T299"), QStringLiteral("Text: Meryl Earth Herb")}, {QStringLiteral("ITEM.T300"), QStringLiteral("Text: Meryl Antidote")}, {QStringLiteral("ITEM.T301"), QStringLiteral("Text: Meryl Dragon Crystal")}, {QStringLiteral("ITEM.T302"), QStringLiteral("Text: Meryl Blue Potion")}, {QStringLiteral("ITEM.T303"), QStringLiteral("Text: Meryl Red Potion")}, {QStringLiteral("ITEM.T304"), QStringLiteral("Text: Meryl Green Potion")}, {QStringLiteral("ITEM.T305"), QStringLiteral("Text: Meryl Gold Potion")}, {QStringLiteral("ITEM.T306"), QStringLiteral("Text: Meryl Crystal Flask")}, {QStringLiteral("ITEM.T307"), QStringLiteral("Text: Meryl Figure Of Seath")}, {QStringLiteral("ITEM.T308"), QStringLiteral("Text: Meryl Phantom Rod")}, {QStringLiteral("ITEM.T309"), QStringLiteral("Text: Meryl Truth Glass")}, {QStringLiteral("ITEM.T310"), QStringLiteral("Text: Meryl Seath's Plume")}, {QStringLiteral("ITEM.T311"), QStringLiteral("Text: Meryl Demon's Pick")}, {QStringLiteral("ITEM.T312"), QStringLiteral("Text: Meryl Harvine's Flute")}, {QStringLiteral("ITEM.T313"), QStringLiteral("Text: Meryl Ground Bell")}, {QStringLiteral("ITEM.T314"), QStringLiteral("Text: Meryl Fire Crystal")}, {QStringLiteral("ITEM.T315"), QStringLiteral("Text: Meryl Water Crystal")}, {QStringLiteral("ITEM.T316"), QStringLiteral("Text: Meryl Earth Crystal")}, {QStringLiteral("ITEM.T317"), QStringLiteral("Text: Meryl Wind Crystal")}, {QStringLiteral("ITEM.T318"), QStringLiteral("Text: Meryl Light Crystal")}, {QStringLiteral("ITEM.T319"), QStringLiteral("Text: Meryl Dark Crystal")}, {QStringLiteral("ITEM.T320"), QStringLiteral("Text: Meryl Crystal")}, {QStringLiteral("ITEM.T321"), QStringLiteral("Text: Meryl Crystal Shard")}, {QStringLiteral("ITEM.T322"), QStringLiteral("Text: Meryl Elf's Key")}, {QStringLiteral("ITEM.T323"), QStringLiteral("Text: Meryl Pirates Key")}, {QStringLiteral("ITEM.T324"), QStringLiteral("Text: Meryl Skull Key")}, {QStringLiteral("ITEM.T325"), QStringLiteral("Text: Meryl Jail Key")}, {QStringLiteral("ITEM.T326"), QStringLiteral("Text: Meryl Rhombus Key")}, {QStringLiteral("ITEM.T327"), QStringLiteral("Text: Meryl Harvine's Key")}, {QStringLiteral("ITEM.T328"), QStringLiteral("Text: Meryl Dragon Stone")}, {QStringLiteral("ITEM.T329"), QStringLiteral("Text: Meryl Magician's Key")}, {QStringLiteral("ITEM.T330"), QStringLiteral("Text: Meryl Silver Key")}, {QStringLiteral("ITEM.T331"), QStringLiteral("Text: Meryl Gold Key")}, {QStringLiteral("ITEM.T332"), QStringLiteral("Text: Meryl Shrine Key")}, {QStringLiteral("ITEM.T333"), QStringLiteral("Text: Meryl Moon Gate")}, {QStringLiteral("ITEM.T334"), QStringLiteral("Text: Meryl Star Gate")}, {QStringLiteral("ITEM.T335"), QStringLiteral("Text: Meryl Sun Gate")}, {QStringLiteral("ITEM.T336"), QStringLiteral("Text: Meryl Moon Key")}, {QStringLiteral("ITEM.T337"), QStringLiteral("Text: Meryl Star Key")}, {QStringLiteral("ITEM.T338"), QStringLiteral("Text: Meryl Sun Key")}, {QStringLiteral("ITEM.T339"), QStringLiteral("Text: Meryl Arrow For The Bow")}, {QStringLiteral("ITEM.T340"), QStringLiteral("Text: Meryl Elf's Bolt")}, {QStringLiteral("ITEM.T365"), QStringLiteral("Text: Truth Glass West Seaside")}, {QStringLiteral("ITEM.T366"), QStringLiteral("Text: Truth Glass The Pirate's Cave")}, {QStringLiteral("ITEM.T367"), QStringLiteral("Text: Truth Glass Cave Of Old Hand")}, {QStringLiteral("ITEM.T368"), QStringLiteral("Text: Truth Glass The Mage's Lighthouse")}, {QStringLiteral("ITEM.T369"), QStringLiteral("Text: Truth Glass The North Village")}, {QStringLiteral("ITEM.T370"), QStringLiteral("Text: Truth Glass The South Village")}, {QStringLiteral("ITEM.T371"), QStringLiteral("Text: Truth Glass ASmall Mine")}, {QStringLiteral("ITEM.T372"), QStringLiteral("Text: Truth Glass The North Graveyard")}, {QStringLiteral("ITEM.T373"), QStringLiteral("Text: Truth Glass Base No 1")}, {QStringLiteral("ITEM.T374"), QStringLiteral("Text: Truth Glass Base No 2")}, {QStringLiteral("ITEM.T375"), QStringLiteral("Text: Truth Glass Base No 3")}, {QStringLiteral("ITEM.T376"), QStringLiteral("Text: Truth Glass Base No 4")}, {QStringLiteral("ITEM.T377"), QStringLiteral("Text: Truth Glass Base No 5")}, {QStringLiteral("ITEM.T378"), QStringLiteral("Text: Truth Glass Base No 6")}, {QStringLiteral("ITEM.T379"), QStringLiteral("Text: Truth Glass The Ruins Of King Harvine's Castle")}, {QStringLiteral("ITEM.T380"), QStringLiteral("Text: Truth Glass The Termite's Nest")}, {QStringLiteral("ITEM.T381"), QStringLiteral("Text: Truth Glass The Cemetery")}, {QStringLiteral("ITEM.T382"), QStringLiteral("Text: Truth Glass The Soldier's Cemetery")}, {QStringLiteral("ITEM.T383"), QStringLiteral("Text: Truth Glass The Window Of Homesickness")}, {QStringLiteral("ITEM.T384"), QStringLiteral("Text: Truth Glass The Elf Graveyard")}, {QStringLiteral("ITEM.T385"), QStringLiteral("Text: Truth Glass The East Village")}, {QStringLiteral("ITEM.T386"), QStringLiteral("Text: Truth Glass The Elf Shrine")}, {QStringLiteral("ITEM.T387"), QStringLiteral("Text: Truth Glass Seath's Fountain")}, {QStringLiteral("ITEM.T388"), QStringLiteral("Text: Truth Glass The Magic Palace Of Fire")}, {QStringLiteral("ITEM.T389"), QStringLiteral("Text: Truth Glass The Magic Palace Of Ice")}, {QStringLiteral("ITEM.T390"), QStringLiteral("Text: Truth Glass The Demon's Grave")}, {QStringLiteral("ITEM.T391"), QStringLiteral("Text: Truth Glass The South Graveyard")}, {QStringLiteral("ITEM.T392"), QStringLiteral("Text: Truth Glass The Big Mine")}, {QStringLiteral("ITEM.T393"), QStringLiteral("Text: Truth Glass The Poisoned Cave")}, {QStringLiteral("ITEM.T394"), QStringLiteral("Text: Truth Glass The Cave Of The Darkside")}, {QStringLiteral("ITEM.T395"), QStringLiteral("Text: Truth Glass The Elf Cave")}, {QStringLiteral("ITEM.T396"), QStringLiteral("Text: Truth Glass The Cave Of The Earth Soul")}, {QStringLiteral("ITEM.T397"), QStringLiteral("Text: Truth Glass The Lookout")}, {QStringLiteral("ITEM.T398"), QStringLiteral("Text: Truth Glass Necron's Coliseum")}, {QStringLiteral("ITEM.T399"), QStringLiteral("Text: Truth Glass The Warriors Graveyard")}, {QStringLiteral("ITEM.T400"), QStringLiteral("Text: Truth Glass The Research Office")}, {QStringLiteral("ITEM.T401"), QStringLiteral("Text: Truth Glass The Village Of The Wind")}, {QStringLiteral("ITEM.T402"), QStringLiteral("Text: Truth Glass The East Seaside")}, {QStringLiteral("MO.T0"), QStringLiteral("Slime")}, {QStringLiteral("MO.T1"), QStringLiteral("Poison Slime")}, {QStringLiteral("MO.T2"), QStringLiteral("Sigill")}, {QStringLiteral("MO.T3"), QStringLiteral("Baltail (Body)")}, {QStringLiteral("MO.T4"), QStringLiteral("Baltail (Tail)")}, {QStringLiteral("MO.T5"), QStringLiteral("Sting Fly (Body)")}, {QStringLiteral("MO.T6"), QStringLiteral("Sting Fly (Tail)")}, {QStringLiteral("MO.T7"), QStringLiteral("Fire Elemental")}, {QStringLiteral("MO.T8"), QStringLiteral("Ghost")}, {QStringLiteral("MO.T9"), QStringLiteral("Reik")}, {QStringLiteral("MO.T10"), QStringLiteral("Slime")}, {QStringLiteral("MO.T11"), QStringLiteral("Slime")}, {QStringLiteral("MO.T12"), QStringLiteral("Head Eater")}, {QStringLiteral("MO.T13"), QStringLiteral("Mogle")}, {QStringLiteral("MO.T14"), QStringLiteral("S-Knight")}, {QStringLiteral("MO.T15"), QStringLiteral("Necron's Soldier")}, {QStringLiteral("MO.T16"), QStringLiteral("Archer")}, {QStringLiteral("MO.T17"), QStringLiteral("Slime")}, {QStringLiteral("MO.T18"), QStringLiteral("Skeleton")}, {QStringLiteral("MO.T19"), QStringLiteral("Termite")}, {QStringLiteral("MO.T20"), QStringLiteral("Kald")}, {QStringLiteral("MO.T21"), QStringLiteral("Psythe")}, {QStringLiteral("MO.T22"), QStringLiteral("Termite Queen")}, {QStringLiteral("MO.T23"), QStringLiteral("Spike Ball (trap)")}, {QStringLiteral("MO.T24"), QStringLiteral("Log Stalker")}, {QStringLiteral("MO.T25"), QStringLiteral("Demon Lord")}, {QStringLiteral("MO.T26"), QStringLiteral("Kraken (Body)")}, {QStringLiteral("MO.T27"), QStringLiteral("Kraken (Shell)")}, {QStringLiteral("MO.T28"), QStringLiteral("Earth Elemental")}, {QStringLiteral("MO.T29"), QStringLiteral("Refma")}, {QStringLiteral("MO.T30"), QStringLiteral("Tarn")}, {QStringLiteral("MO.T31"), QStringLiteral("Copper Knight")}, {QStringLiteral("MO.T32"), QStringLiteral("Necron")}, {QStringLiteral("MO.T33"), QStringLiteral("Slime")}, {QStringLiteral("MO.T34"), QStringLiteral("Slime")}, {QStringLiteral("MO.T35"), QStringLiteral("Slime")}, {QStringLiteral("MO.T36"), QStringLiteral("Guyra")}, {QStringLiteral("MO.T37"), QStringLiteral("Salamander")}, {QStringLiteral("MO.T38"), QStringLiteral("Flame Spirit")}, {QStringLiteral("MO.T39"), QStringLiteral("Billent")}, {QStringLiteral("MO.T40"), QStringLiteral("Slime")}, {QStringLiteral("MO.T41"), QStringLiteral("Skeleton of One Eyed Giant")}, {QStringLiteral("MO.T42"), QStringLiteral("Picture of a King")}, {QStringLiteral("MO.T43"), QStringLiteral("Mecha Demon Lord")}, {QStringLiteral("MO.T44"), QStringLiteral("Mecha Termite")}, {QStringLiteral("MO.T45"), QStringLiteral("Mecha Reik")}, {QStringLiteral("MO.T46"), QStringLiteral("Magician's Lamp")}, {QStringLiteral("MO.T47"), QStringLiteral("Bitt")}, {QStringLiteral("MO.T48"), QStringLiteral("Refma")}, {QStringLiteral("MO.T49"), QStringLiteral("Cellfy Foss")}, {QStringLiteral("MO.T50"), QStringLiteral("Cellfy Foss")}, {QStringLiteral("MO.T51"), QStringLiteral("Raffy Foss")}, {QStringLiteral("MO.T52"), QStringLiteral("Jose Harven")}, {QStringLiteral("MO.T53"), QStringLiteral("Nola Bagil")}, {QStringLiteral("MO.T54"), QStringLiteral("Meryl")}, {QStringLiteral("MO.T55"), QStringLiteral("Gigi Budwell")}, {QStringLiteral("MO.T56"), QStringLiteral("Gigi Budwell (Watering)")}, {QStringLiteral("MO.T57"), QStringLiteral("Teo Budwell")}, {QStringLiteral("MO.T58"), QStringLiteral("Teo Budwell (With Gigi)")}, {QStringLiteral("MO.T59"), QStringLiteral("Teo Budwell (Mowing)")}, {QStringLiteral("MO.T60"), QStringLiteral("Karen Shore")}, {QStringLiteral("MO.T61"), QStringLiteral("Leon Shore")}, {QStringLiteral("MO.T62"), QStringLiteral("Leon Shore (Watering)")}, {QStringLiteral("MO.T63"), QStringLiteral("Al Hunt")}, {QStringLiteral("MO.T64"), QStringLiteral("Harris Carvitto")}, {QStringLiteral("MO.T65"), QStringLiteral("Fai Fadlin")}, {QStringLiteral("MO.T66"), QStringLiteral("Cliff Lore")}, {QStringLiteral("MO.T67"), QStringLiteral("Rand Ferrer")}, {QStringLiteral("MO.T68"), QStringLiteral("David Tabler")}, {QStringLiteral("MO.T69"), QStringLiteral("Dalf Vice")}, {QStringLiteral("MO.T70"), QStringLiteral("Radd Bilheim")}, {QStringLiteral("MO.T71"), QStringLiteral("Krola Amgun")}, {QStringLiteral("MO.T72"), QStringLiteral("Krola Amgun (Cooking)")}, {QStringLiteral("MO.T73"), QStringLiteral("Sandler Amgun")}, {QStringLiteral("MO.T74"), QStringLiteral("Sandler Amgun")}, {QStringLiteral("MO.T75"), QStringLiteral("Mark Wozz")}, {QStringLiteral("MO.T76"), QStringLiteral("Earnest Clyde")}, {QStringLiteral("MO.T77"), QStringLiteral("Kehl Hunt")}, {QStringLiteral("MO.T78"), QStringLiteral("Kehl Hunt")}, {QStringLiteral("MO.T79"), QStringLiteral("Karen Shore (Chair)")}, {QStringLiteral("MO.T80"), QStringLiteral("Jose Haven (Death)")}, {QStringLiteral("MO.T81"), QStringLiteral("Saint Grave")}, {QStringLiteral("MO.T82"), QStringLiteral("Earnest Clyde (Sitting)")}, {QStringLiteral("MO.T83"), QStringLiteral("Dragon Grass")}, {QStringLiteral("MO.T84"), QStringLiteral("Jose Haven (Death)")}, {QStringLiteral("MO.T85"), QStringLiteral("Miria")}, {QStringLiteral("MO.T86"), QStringLiteral("Dagger")}, {QStringLiteral("MO.T87"), QStringLiteral("Short Sword")}, {QStringLiteral("MO.T88"), QStringLiteral("Knight Sword")}, {QStringLiteral("MO.T89"), QStringLiteral("Morning Star")}, {QStringLiteral("MO.T90"), QStringLiteral("Battle Hammer")}, {QStringLiteral("MO.T91"), QStringLiteral("Bastard Sword")}, {QStringLiteral("MO.T92"), QStringLiteral("Crescent Axe")}, {QStringLiteral("MO.T93"), QStringLiteral("Default Model")}, {QStringLiteral("MO.T94"), QStringLiteral("Seath's Sword (And Wall)")}, {QStringLiteral("MO.T95"), QStringLiteral("Flame Sword")}, {QStringLiteral("MO.T96"), QStringLiteral("Shiden")}, {QStringLiteral("MO.T97"), QStringLiteral("Spider")}, {QStringLiteral("MO.T98"), QStringLiteral("Ice Blade")}, {QStringLiteral("MO.T99"), QStringLiteral("Seath's Sword")}, {QStringLiteral("MO.T100"), QStringLiteral("Moonlight Sword")}, {QStringLiteral("MO.T101"), QStringLiteral("Dark Slayer")}, {QStringLiteral("MO.T102"), QStringLiteral("Bow")}, {QStringLiteral("MO.T103"), QStringLiteral("Arbalest")}, {QStringLiteral("MO.T104"), QStringLiteral("Seath's Sword (Broken)")}, {QStringLiteral("MO.T105"), QStringLiteral("Default Model")}, {QStringLiteral("MO.T106"), QStringLiteral("Default Model")}, {QStringLiteral("MO.T107"), QStringLiteral("Iron Mask")}, {QStringLiteral("MO.T108"), QStringLiteral("Knight Helm")}, {QStringLiteral("MO.T109"), QStringLiteral("Great Helm")}, {QStringLiteral("MO.T110"), QStringLiteral("Blood Crown")}, {QStringLiteral("MO.T111"), QStringLiteral("Lightning Helm")}, {QStringLiteral("MO.T112"), QStringLiteral("Seath's Helm")}, {QStringLiteral("MO.T113"), QStringLiteral("Default Model")}, {QStringLiteral("RTIM.T0"), QStringLiteral("Western Shore Texture Database")}, {QStringLiteral("RTIM.T1"), QStringLiteral("Garrison Texture Database")}, {QStringLiteral("RTIM.T2"), QStringLiteral("Central Village Texture Database")}, {QStringLiteral("RTIM.T3"), QStringLiteral("East Village Texture Database")}, {QStringLiteral("RTIM.T4"), QStringLiteral("Cathedral Texture Database")}, {QStringLiteral("RTIM.T5"), QStringLiteral("Big Mine Texture Database")}, {QStringLiteral("RTIM.T6"), QStringLiteral("Necron's Coliseum Texture Database")}, {QStringLiteral("RTIM.T7"), QStringLiteral("Guyra's Lair Texture Database")}, {QStringLiteral("RTIM.T8"), QStringLiteral("Weird Debug Map Texture Database")}, {QStringLiteral("RTIM.T16"), QStringLiteral("Picture of a King")}, {QStringLiteral("RTIM.T23"), QStringLiteral("Village House 01")}, {QStringLiteral("RTIM.T24"), QStringLiteral("Village House 02")}, {QStringLiteral("RTIM.T28"), QStringLiteral("Seath's Door")}, {QStringLiteral("RTIM.T29"), QStringLiteral("The Picture of Warriors")}, {QStringLiteral("RTIM.T65"), QStringLiteral("Seath's Floor and Door")}, {QStringLiteral("RTMD.T0"), QStringLiteral("Western Shore Tileset")}, {QStringLiteral("RTMD.T1"), QStringLiteral("Garrison Tileset")}, {QStringLiteral("RTMD.T2"), QStringLiteral("Central Village Tileset")}, {QStringLiteral("RTMD.T3"), QStringLiteral("East Village Tileset")}, {QStringLiteral("RTMD.T4"), QStringLiteral("Cathedral Tileset")}, {QStringLiteral("RTMD.T5"), QStringLiteral("Big Mine Tileset")}, {QStringLiteral("RTMD.T6"), QStringLiteral("Necron's Coliseum Tileset")}, {QStringLiteral("RTMD.T7"), QStringLiteral("Guyra's Lair Tileset")}, {QStringLiteral("RTMD.T8"), QStringLiteral("Weird Debug Map Tileset")}, {QStringLiteral("TALK.T58"), QStringLiteral("Jose Harven Dialogue 1")}, {QStringLiteral("TALK.T59"), QStringLiteral("Jose Harven Dialogue 2")}, {QStringLiteral("TALK.T60"), QStringLiteral("Jose Harven Dialogue 3")}, {QStringLiteral("TALK.T61"), QStringLiteral("Jose Harven Dialogue 4")}, {QStringLiteral("TALK.T62"), QStringLiteral("Jose Harven Dialogue 5")}, {QStringLiteral("TALK.T63"), QStringLiteral("Jose Harven Dialogue 6")}, {QStringLiteral("TALK.T64"), QStringLiteral("Jose Harven Dialogue 7")}, {QStringLiteral("VAB.T1"), QStringLiteral("Sound Effects Waveforms")}, {QStringLiteral("VAB.T112"), QStringLiteral("Western Shore Sequence")}, {QStringLiteral("VAB.T113"), QStringLiteral("Garrison Sequence")}, {QStringLiteral("VAB.T114"), QStringLiteral("Central Village Sequence")}, {QStringLiteral("VAB.T115"), QStringLiteral("East Village Sequence")}, {QStringLiteral("VAB.T116"), QStringLiteral("Cathedral Sequence")}, {QStringLiteral("VAB.T117"), QStringLiteral("Big Mine Sequence")}, {QStringLiteral("VAB.T118"), QStringLiteral("Necrons Coliseum Sequence")}, {QStringLiteral("VAB.T119"), QStringLiteral("Guyras Lair Sequence")}, {QStringLiteral("VAB.T121"), QStringLiteral("Central Village 2 Sequence")}, }; } // namespace PrettyNames
71.914378
99
0.701696
[ "model" ]
34de0cea24cf0164a07eb33343c4b2360ab44141
3,264
cpp
C++
render/SpriteBuffer.cpp
yuriks/libyuriks
e80c599cdfe6294df8ce58ad5570af20e50b1072
[ "Apache-2.0" ]
6
2015-02-13T20:58:28.000Z
2020-10-02T02:38:13.000Z
libyuriks/render/SpriteBuffer.cpp
yuriks/super-match-5-dx
47d53b99cc8f93f7cd63a7b11b380ba935739662
[ "Apache-2.0" ]
null
null
null
libyuriks/render/SpriteBuffer.cpp
yuriks/super-match-5-dx
47d53b99cc8f93f7cd63a7b11b380ba935739662
[ "Apache-2.0" ]
2
2016-10-03T18:50:27.000Z
2018-12-12T22:14:58.000Z
#include "SpriteBuffer.hpp" #include "gl/gl_1_5.h" #include "gl/gl_assert.hpp" #include <cassert> namespace yks { void VertexData::setupVertexAttribs() { YKS_CHECK_GL_PARANOID; glVertexPointer(2, GL_FLOAT, sizeof(VertexData), reinterpret_cast<void*>(offsetof(VertexData, pos_x))); glEnableClientState(GL_VERTEX_ARRAY); glTexCoordPointer(2, GL_FLOAT, sizeof(VertexData), reinterpret_cast<void*>(offsetof(VertexData, tex_s))); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(VertexData), reinterpret_cast<void*>(offsetof(VertexData, color))); glEnableClientState(GL_COLOR_ARRAY); YKS_CHECK_GL_PARANOID; } SpriteBufferIndices::SpriteBufferIndices() { YKS_CHECK_GL_PARANOID; glGenBuffers(1, &ibo.name); YKS_CHECK_GL_PARANOID; } void SpriteBufferIndices::update(unsigned int sprite_count) { YKS_CHECK_GL_PARANOID; glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo.name); if (index_count >= sprite_count) return; indices.reserve(sprite_count * 6); for (unsigned int i = index_count; i < sprite_count; ++i) { uint16_t base_i = uint16_t(i * 4); indices.push_back(base_i + 0); indices.push_back(base_i + 1); indices.push_back(base_i + 3); indices.push_back(base_i + 3); indices.push_back(base_i + 1); indices.push_back(base_i + 2); } index_count = sprite_count; glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLushort) * indices.size(), indices.data(), GL_STREAM_DRAW); YKS_CHECK_GL_PARANOID; } SpriteBuffer::SpriteBuffer() { YKS_CHECK_GL_PARANOID; glGenBuffers(1, &vbo.name); YKS_CHECK_GL_PARANOID; } void SpriteBuffer::clear() { vertices.clear(); sprite_count = 0; } void SpriteBuffer::append(const Sprite& spr) { assert(texture_size[0] >= 0 && texture_size[1] >= 0); float spr_w = static_cast<float>(spr.img.w); float spr_h = static_cast<float>(spr.img.h); float img_x = spr.img.x / static_cast<float>(texture_size[0]); float img_w = spr.img.w / static_cast<float>(texture_size[0]); float img_y = spr.img.y / static_cast<float>(texture_size[1]); float img_h = spr.img.h / static_cast<float>(texture_size[1]); VertexData v; v.color[0] = spr.color.r; v.color[1] = spr.color.g; v.color[2] = spr.color.b; v.color[3] = spr.color.a; auto p = spr.mat.transform(mvec2(0.f, 0.f)); v.pos_x = p[0]; v.pos_y = p[1]; v.tex_s = img_x; v.tex_t = img_y; vertices.push_back(v); p = spr.mat.transform(mvec2(spr_w, 0.f)); v.pos_x = p[0]; v.pos_y = p[1]; v.tex_s = img_x + img_w; vertices.push_back(v); p = spr.mat.transform(mvec2(spr_w, spr_h)); v.pos_x = p[0]; v.pos_y = p[1]; v.tex_t = img_y + img_h; vertices.push_back(v); p = spr.mat.transform(mvec2(0.f, spr_h)); v.pos_x = p[0]; v.pos_y = p[1]; v.tex_s = img_x; vertices.push_back(v); sprite_count += 1; } void SpriteBuffer::draw(SpriteBufferIndices& indices) const { YKS_CHECK_GL_PARANOID; indices.update(sprite_count); glBindBuffer(GL_ARRAY_BUFFER, vbo.name); glBufferData(GL_ARRAY_BUFFER, sizeof(VertexData) * vertices.size(), vertices.data(), GL_STREAM_DRAW); VertexData::setupVertexAttribs(); glDrawElements(GL_TRIANGLES, sprite_count * 6, GL_UNSIGNED_SHORT, nullptr); YKS_CHECK_GL_PARANOID; } }
25.5
112
0.708027
[ "transform" ]
34e3c7c44c9f6bed97fbf8d38e4e5ebe028d7af8
1,637
cpp
C++
Typon/src/tools.cpp
ihsuy/Typon
55aa2d82ed3aecf10b88891e5b962daf5944b6f3
[ "MIT" ]
65
2019-03-06T15:47:27.000Z
2022-03-05T09:14:29.000Z
Typon/src/tools.cpp
ihsuy/Typon
55aa2d82ed3aecf10b88891e5b962daf5944b6f3
[ "MIT" ]
null
null
null
Typon/src/tools.cpp
ihsuy/Typon
55aa2d82ed3aecf10b88891e5b962daf5944b6f3
[ "MIT" ]
5
2019-04-11T01:15:04.000Z
2021-11-21T18:57:47.000Z
#include "tools.hpp" bool isShifted(const int& key) { return ((key >= 65 and key <= 90) or (key >= 33 and key <= 38) or (key >= 40 and key <= 43) or (key == 58) or (key == 60) or (key >= 62 and key <= 64) or (key >= 94 and key <= 95) or (key == 123) or (key == 125)); } string d_to_string(const double& d, const int& decimal) { stringstream ss; ss << setprecision(decimal) << fixed << d; return ss.str(); } double s_to_double(const string& s) { stringstream ss{s}; double d; ss >> d; return d; } void reformat_spacedTokens(vector<string>& items, const vector<int>& width, ios_base& (*flag)(ios_base&)) { stringstream buffer; string token; const unsigned long n = width.size(); for (auto& item : items) { vector<string> tokens; buffer = stringstream(item); for (auto i = 0; i < n - 1; ++i) { buffer >> token; tokens.push_back(token); } buffer >> token; while (!buffer.eof()) { string piece; buffer >> piece; token += " " + piece; } tokens.push_back(token); assert(tokens.size() == n); stringstream washer; for (auto i = 0; i < n; ++i) { washer << flag << setw(width[i]) << tokens[i]; } item = washer.str(); } } void Exit(int n, const string& msg) { // quit curses endwin(); // throw an message if given if (msg != "") { cout << "" << msg << endl; } // quit program exit(n); }
25.184615
70
0.48931
[ "vector" ]
34e89b81d8f178054aad8c53b6eedf61757a12b9
2,999
cxx
C++
smtk/attribute/ItemDefinition.cxx
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
null
null
null
smtk/attribute/ItemDefinition.cxx
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
4
2016-11-10T15:49:51.000Z
2017-02-06T23:24:16.000Z
smtk/attribute/ItemDefinition.cxx
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
null
null
null
//========================================================================= // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //========================================================================= #include "smtk/attribute/ItemDefinition.h" #include <iostream> using namespace smtk::attribute; //---------------------------------------------------------------------------- ItemDefinition::ItemDefinition(const std::string &myName) : m_name(myName) { this->m_version = 0; this->m_advanceLevel[0] = 0; this->m_advanceLevel[1] = 0; this->m_isOptional = false; this->m_isEnabledByDefault = false; } //---------------------------------------------------------------------------- ItemDefinition::~ItemDefinition() { } //---------------------------------------------------------------------------- bool ItemDefinition::isMemberOf(const std::vector<std::string> &inCategories) const { std::size_t i, n = inCategories.size(); for (i = 0; i < n; i++) { if (this->isMemberOf(inCategories[i])) { return true; } } return false; } //---------------------------------------------------------------------------- void ItemDefinition::updateCategories() { } //---------------------------------------------------------------------------- void ItemDefinition::addCategory(const std::string &category) { this->m_categories.insert(category); } //---------------------------------------------------------------------------- void ItemDefinition::removeCategory(const std::string &category) { this->m_categories.erase(category); } //---------------------------------------------------------------------------- void ItemDefinition::setAdvanceLevel(int mode, int level) { if ((mode < 0) || (mode > 1)) { return; } this->m_advanceLevel[mode] = level; } //---------------------------------------------------------------------------- void ItemDefinition::setAdvanceLevel(int level) { this->m_advanceLevel[0] = level; this->m_advanceLevel[1] = level; } //---------------------------------------------------------------------------- void ItemDefinition::copyTo(ItemDefinitionPtr def) const { def->setLabel(m_label); def->setVersion(m_version); def->setIsOptional(m_isOptional); def->setIsEnabledByDefault(m_isEnabledByDefault); std::set<std::string>::const_iterator categoryIter = m_categories.begin(); for (; categoryIter != m_categories.end(); categoryIter++) { def->addCategory(*categoryIter); } def->setAdvanceLevel(0, m_advanceLevel[0]); def->setAdvanceLevel(1, m_advanceLevel[1]); def->setDetailedDescription(m_detailedDescription); def->setBriefDescription(m_briefDescription); } //----------------------------------------------------------------------------
32.247312
83
0.48883
[ "vector" ]
34ec093050534c733074f3cdc3e72d717fdce153
1,237
hpp
C++
src/abnf/Rule_extension_identifier.hpp
medooze/sdp-
4bf23de4cf6ade65fedb68a8c8a5baf4bd6a3e6d
[ "MIT" ]
32
2018-01-01T17:01:19.000Z
2022-02-25T10:30:47.000Z
src/abnf/Rule_extension_identifier.hpp
medooze/sdp-
4bf23de4cf6ade65fedb68a8c8a5baf4bd6a3e6d
[ "MIT" ]
4
2018-01-08T16:13:05.000Z
2021-01-25T11:47:44.000Z
src/abnf/Rule_extension_identifier.hpp
medooze/sdp-
4bf23de4cf6ade65fedb68a8c8a5baf4bd6a3e6d
[ "MIT" ]
13
2018-09-30T05:59:24.000Z
2022-02-24T08:58:36.000Z
/* ----------------------------------------------------------------------------- * Rule_extension_identifier.hpp * ----------------------------------------------------------------------------- * * Producer : com.parse2.aparse.Parser 2.5 * Produced : Mon Jan 08 13:30:55 CET 2018 * * ----------------------------------------------------------------------------- */ #ifndef Rule_extension_identifier_hpp #define Rule_extension_identifier_hpp #include <string> #include <vector> #include "Rule.hpp" namespace abnf { class Visitor; class ParserContext; class Rule_extension_identifier : public Rule { public: Rule_extension_identifier(const std::string& spelling, const std::vector<Rule*>& rules); Rule_extension_identifier(const Rule_extension_identifier& rule); Rule_extension_identifier& operator=(const Rule_extension_identifier& rule); virtual Rule* clone(void) const; static Rule_extension_identifier* parse(ParserContext& context); virtual void* accept(Visitor& visitor); }; } #endif /* ----------------------------------------------------------------------------- * eof * ----------------------------------------------------------------------------- */
26.891304
91
0.48747
[ "vector" ]
34f7f7f3612b0dbbef4f42b15c426a12b1d7bbbe
1,531
cpp
C++
src/analysis/linpred/burg.cpp
dequis/in-formant
129b9b399c75cdbd834b68f04dabcb1d406af250
[ "Apache-2.0" ]
null
null
null
src/analysis/linpred/burg.cpp
dequis/in-formant
129b9b399c75cdbd834b68f04dabcb1d406af250
[ "Apache-2.0" ]
null
null
null
src/analysis/linpred/burg.cpp
dequis/in-formant
129b9b399c75cdbd834b68f04dabcb1d406af250
[ "Apache-2.0" ]
null
null
null
#include "linpred.h" #include <cmath> using namespace Analysis::LP; std::vector<double> Burg::solve(const double *x, int length, int lpcOrder, double *pGain) { int n = length, m = lpcOrder; std::vector<double> a(m, 0.0); b1.resize(n + 1, 0.0); b2.resize(n + 1, 0.0); aa.resize(m + 1, 0.0); double p = 0.0; for (int j = 0; j < n; ++j) p += x[j] * x[j]; double xms = p / static_cast<double>(n); if (xms <= 0.0) goto end; b1[1] = x[0]; b2[n - 1] = x[n - 1]; for (int j = 2; j <= n; ++j) b1[j] = b2[j - 1] = x[j - 1]; for (int i = 1; i <= m; ++i) { double num = 0.0, denom = 0.0; for (int j = 1; j <= n - i; ++j) { num += b1[j] * b2[j]; denom += b1[j] * b1[j] + b2[j] * b2[j]; } if (denom <= 0.0) goto end; a[i - 1] = (2.0 * num) / denom; xms *= 1.0 - a[i - 1] * a[i - 1]; for (int j = 1; j <= i - 1; ++j) a[j - 1] = aa[j] - a[i - 1] * aa[i - j]; if (i < m) { for (int j = 1; j <= i; ++j) aa[j] = a[j - 1]; for (int j = 1; j <= n - i - 1; ++j) { b1[j] -= aa[i] * b2[j]; b2[j] = b2[j + 1] - aa[i] * b1[j + 1]; } } } end: if (xms <= 0.0) { a.resize(0); xms = 0.0; } std::vector<double> lpc(a.size()); for (int i = 0; i < a.size(); ++i) { lpc[i] = -a[i]; } *pGain = xms; return lpc; }
21.56338
89
0.36904
[ "vector" ]
5a510d79bacb264290324bdfe229e36d8053365b
2,789
cpp
C++
src/Component/AOCS/InitGnssReceiver.cpp
ut-issl/s2e-core
900fae6b738eb8765cd98c48acb2b74f05dcc68c
[ "MIT" ]
16
2021-12-28T18:30:01.000Z
2022-03-26T12:59:48.000Z
src/Component/AOCS/InitGnssReceiver.cpp
ut-issl/s2e-core
900fae6b738eb8765cd98c48acb2b74f05dcc68c
[ "MIT" ]
61
2022-01-04T22:56:36.000Z
2022-03-31T13:19:29.000Z
src/Component/AOCS/InitGnssReceiver.cpp
ut-issl/s2e-core
900fae6b738eb8765cd98c48acb2b74f05dcc68c
[ "MIT" ]
2
2022-03-03T03:39:25.000Z
2022-03-12T04:50:30.000Z
#include "InitGnssReceiver.hpp" #include <string.h> #include "Interface/InitInput/IniAccess.h" typedef struct _gnssrecever_param { int prescaler; AntennaModel antenna_model; Vector<3> antenna_pos_b; Quaternion q_b2c; double half_width; std::string gnss_id; int ch_max; Vector<3> noise_std; } GNSSReceiverParam; GNSSReceiverParam ReadGNSSReceiverIni(const std::string fname, const GnssSatellites* gnss_satellites) { GNSSReceiverParam gnssreceiver_param; IniAccess gnssr_conf(fname); char GSection[30] = "GNSSReceiver"; int prescaler = gnssr_conf.ReadInt(GSection, "prescaler"); if (prescaler <= 1) prescaler = 1; gnssreceiver_param.prescaler = prescaler; gnssreceiver_param.antenna_model = static_cast<AntennaModel>(gnssr_conf.ReadInt(GSection, "antenna_model")); if (!gnss_satellites->IsCalcEnabled() && gnssreceiver_param.antenna_model == CONE) { std::cout << "Calculation of GNSS SATELLITES is DISABLED, so the antenna " "model of GNSS Receiver is automatically set to SIMPLE model." << std::endl; gnssreceiver_param.antenna_model = SIMPLE; } gnssr_conf.ReadVector(GSection, "antenna_pos_b", gnssreceiver_param.antenna_pos_b); gnssr_conf.ReadQuaternion(GSection, "q_b2c", gnssreceiver_param.q_b2c); gnssreceiver_param.half_width = gnssr_conf.ReadDouble(GSection, "half_width"); gnssreceiver_param.gnss_id = gnssr_conf.ReadString(GSection, "gnss_id"); gnssreceiver_param.ch_max = gnssr_conf.ReadInt(GSection, "ch_max"); gnssr_conf.ReadVector(GSection, "nr_stddev_eci", gnssreceiver_param.noise_std); return gnssreceiver_param; } GNSSReceiver InitGNSSReceiver(ClockGenerator* clock_gen, int id, const std::string fname, const Dynamics* dynamics, const GnssSatellites* gnss_satellites, const SimTime* simtime) { GNSSReceiverParam gr_param = ReadGNSSReceiverIni(fname, gnss_satellites); GNSSReceiver gnss_r(gr_param.prescaler, clock_gen, id, gr_param.gnss_id, gr_param.ch_max, gr_param.antenna_model, gr_param.antenna_pos_b, gr_param.q_b2c, gr_param.half_width, gr_param.noise_std, dynamics, gnss_satellites, simtime); return gnss_r; } GNSSReceiver InitGNSSReceiver(ClockGenerator* clock_gen, PowerPort* power_port, int id, const std::string fname, const Dynamics* dynamics, const GnssSatellites* gnss_satellites, const SimTime* simtime) { GNSSReceiverParam gr_param = ReadGNSSReceiverIni(fname, gnss_satellites); GNSSReceiver gnss_r(gr_param.prescaler, clock_gen, power_port, id, gr_param.gnss_id, gr_param.ch_max, gr_param.antenna_model, gr_param.antenna_pos_b, gr_param.q_b2c, gr_param.half_width, gr_param.noise_std, dynamics, gnss_satellites, simtime); return gnss_r; }
44.269841
139
0.756902
[ "vector", "model" ]
5a596bb29bcc31c8d8bc3608e8d6f90842888a70
17,002
cpp
C++
indra/newview/llchatbar.cpp
SaladDais/LLUDP-Encryption
8a426cd0dd154e1a10903e0e6383f4deb2a6098a
[ "ISC" ]
1
2022-01-29T07:10:03.000Z
2022-01-29T07:10:03.000Z
indra/newview/llchatbar.cpp
SaladDais/LLUDP-Encryption
8a426cd0dd154e1a10903e0e6383f4deb2a6098a
[ "ISC" ]
null
null
null
indra/newview/llchatbar.cpp
SaladDais/LLUDP-Encryption
8a426cd0dd154e1a10903e0e6383f4deb2a6098a
[ "ISC" ]
1
2021-10-01T22:22:27.000Z
2021-10-01T22:22:27.000Z
/** * @file llchatbar.cpp * @brief LLChatBar class implementation * * $LicenseInfo:firstyear=2002&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * 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; * version 2.1 of the License only. * * 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 * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #if 0 #include "llchatbar.h" #include "llfontgl.h" #include "llrect.h" #include "llerror.h" #include "llparcel.h" #include "llstring.h" #include "message.h" #include "llfocusmgr.h" #include "llagent.h" #include "llbutton.h" #include "llcombobox.h" #include "llcommandhandler.h" // secondlife:///app/chat/ support #include "llviewercontrol.h" #include "llgesturemgr.h" #include "llkeyboard.h" #include "lllineeditor.h" #include "llstatusbar.h" #include "lltextbox.h" #include "lluiconstants.h" #include "llviewergesture.h" // for triggering gestures #include "llviewermenu.h" // for deleting object with DEL key #include "llviewerstats.h" #include "llviewerwindow.h" #include "llframetimer.h" #include "llresmgr.h" #include "llworld.h" #include "llinventorymodel.h" #include "llmultigesture.h" #include "llui.h" #include "lluictrlfactory.h" // // Globals // const F32 AGENT_TYPING_TIMEOUT = 5.f; // seconds LLChatBar *gChatBar = NULL; class LLChatBarGestureObserver : public LLGestureManagerObserver { public: LLChatBarGestureObserver(LLChatBar* chat_barp) : mChatBar(chat_barp){} virtual ~LLChatBarGestureObserver() {} virtual void changed() { mChatBar->refreshGestures(); } private: LLChatBar* mChatBar; }; extern void send_chat_from_viewer(const std::string& utf8_out_text, EChatType type, S32 channel); // // Functions // LLChatBar::LLChatBar() : LLPanel(), mInputEditor(NULL), mGestureLabelTimer(), mLastSpecialChatChannel(0), mIsBuilt(FALSE), mGestureCombo(NULL), mObserver(NULL) { //setIsChrome(TRUE); } LLChatBar::~LLChatBar() { LLGestureMgr::instance().removeObserver(mObserver); delete mObserver; mObserver = NULL; // LLView destructor cleans up children } BOOL LLChatBar::postBuild() { getChild<LLUICtrl>("Say")->setCommitCallback(boost::bind(&LLChatBar::onClickSay, this, _1)); // * NOTE: mantipov: getChild with default parameters returns dummy widget. // Seems this class will be completle removed // attempt to bind to an existing combo box named gesture setGestureCombo(findChild<LLComboBox>( "Gesture")); mInputEditor = getChild<LLLineEditor>("Chat Editor"); mInputEditor->setKeystrokeCallback(&onInputEditorKeystroke, this); mInputEditor->setFocusLostCallback(boost::bind(&LLChatBar::onInputEditorFocusLost)); mInputEditor->setFocusReceivedCallback(boost::bind(&LLChatBar::onInputEditorGainFocus)); mInputEditor->setCommitOnFocusLost( FALSE ); mInputEditor->setRevertOnEsc( FALSE ); mInputEditor->setIgnoreTab(TRUE); mInputEditor->setPassDelete(TRUE); mInputEditor->setReplaceNewlinesWithSpaces(FALSE); mInputEditor->setMaxTextLength(DB_CHAT_MSG_STR_LEN); mInputEditor->setEnableLineHistory(TRUE); mIsBuilt = TRUE; return TRUE; } //----------------------------------------------------------------------- // Overrides //----------------------------------------------------------------------- // virtual BOOL LLChatBar::handleKeyHere( KEY key, MASK mask ) { BOOL handled = FALSE; if( KEY_RETURN == key ) { if (mask == MASK_CONTROL) { // shout sendChat(CHAT_TYPE_SHOUT); handled = TRUE; } else if (mask == MASK_NONE) { // say sendChat( CHAT_TYPE_NORMAL ); handled = TRUE; } } // only do this in main chatbar else if ( KEY_ESCAPE == key && gChatBar == this) { stopChat(); handled = TRUE; } return handled; } void LLChatBar::refresh() { // HACK: Leave the name of the gesture in place for a few seconds. const F32 SHOW_GESTURE_NAME_TIME = 2.f; if (mGestureLabelTimer.getStarted() && mGestureLabelTimer.getElapsedTimeF32() > SHOW_GESTURE_NAME_TIME) { LLCtrlListInterface* gestures = mGestureCombo ? mGestureCombo->getListInterface() : NULL; if (gestures) gestures->selectFirstItem(); mGestureLabelTimer.stop(); } if ((gAgent.getTypingTime() > AGENT_TYPING_TIMEOUT) && (gAgent.getRenderState() & AGENT_STATE_TYPING)) { gAgent.stopTyping(); } getChildView("Say")->setEnabled(mInputEditor->getText().size() > 0); } void LLChatBar::refreshGestures() { if (mGestureCombo) { //store current selection so we can maintain it std::string cur_gesture = mGestureCombo->getValue().asString(); mGestureCombo->selectFirstItem(); std::string label = mGestureCombo->getValue().asString();; // clear mGestureCombo->clearRows(); // collect list of unique gestures std::map <std::string, BOOL> unique; LLGestureMgr::item_map_t::const_iterator it; const LLGestureMgr::item_map_t& active_gestures = LLGestureMgr::instance().getActiveGestures(); for (it = active_gestures.begin(); it != active_gestures.end(); ++it) { LLMultiGesture* gesture = (*it).second; if (gesture) { if (!gesture->mTrigger.empty()) { unique[gesture->mTrigger] = TRUE; } } } // add unique gestures std::map <std::string, BOOL>::iterator it2; for (it2 = unique.begin(); it2 != unique.end(); ++it2) { mGestureCombo->addSimpleElement((*it2).first); } mGestureCombo->sortByName(); // Insert label after sorting, at top, with separator below it mGestureCombo->addSeparator(ADD_TOP); mGestureCombo->addSimpleElement(getString("gesture_label"), ADD_TOP); if (!cur_gesture.empty()) { mGestureCombo->selectByValue(LLSD(cur_gesture)); } else { mGestureCombo->selectFirstItem(); } } } // Move the cursor to the correct input field. void LLChatBar::setKeyboardFocus(BOOL focus) { if (focus) { if (mInputEditor) { mInputEditor->setFocus(TRUE); mInputEditor->selectAll(); } } else if (gFocusMgr.childHasKeyboardFocus(this)) { if (mInputEditor) { mInputEditor->deselect(); } setFocus(FALSE); } } // Ignore arrow keys in chat bar void LLChatBar::setIgnoreArrowKeys(BOOL b) { if (mInputEditor) { mInputEditor->setIgnoreArrowKeys(b); } } BOOL LLChatBar::inputEditorHasFocus() { return mInputEditor && mInputEditor->hasFocus(); } std::string LLChatBar::getCurrentChat() { return mInputEditor ? mInputEditor->getText() : LLStringUtil::null; } void LLChatBar::setGestureCombo(LLComboBox* combo) { mGestureCombo = combo; if (mGestureCombo) { mGestureCombo->setCommitCallback(boost::bind(&LLChatBar::onCommitGesture, this, _1)); // now register observer since we have a place to put the results mObserver = new LLChatBarGestureObserver(this); LLGestureMgr::instance().addObserver(mObserver); // refresh list from current active gestures refreshGestures(); } } //----------------------------------------------------------------------- // Internal functions //----------------------------------------------------------------------- // If input of the form "/20foo" or "/20 foo", returns "foo" and channel 20. // Otherwise returns input and channel 0. LLWString LLChatBar::stripChannelNumber(const LLWString &mesg, S32* channel) { if (mesg[0] == '/' && mesg[1] == '/') { // This is a "repeat channel send" *channel = mLastSpecialChatChannel; return mesg.substr(2, mesg.length() - 2); } else if (mesg[0] == '/' && mesg[1] && (LLStringOps::isDigit(mesg[1]) || (mesg[1] == '-' && mesg[2] && LLStringOps::isDigit(mesg[2])))) { // This a special "/20" speak on a channel S32 pos = 0; // Copy the channel number into a string LLWString channel_string; llwchar c; do { c = mesg[pos+1]; channel_string.push_back(c); pos++; } while(c && pos < 64 && (LLStringOps::isDigit(c) || (pos == 1 && c == '-'))); // Move the pointer forward to the first non-whitespace char // Check isspace before looping, so we can handle "/33foo" // as well as "/33 foo" while(c && iswspace(c)) { c = mesg[pos+1]; pos++; } mLastSpecialChatChannel = strtol(wstring_to_utf8str(channel_string).c_str(), NULL, 10); *channel = mLastSpecialChatChannel; return mesg.substr(pos, mesg.length() - pos); } else { // This is normal chat. *channel = 0; return mesg; } } void LLChatBar::sendChat( EChatType type ) { if (mInputEditor) { LLWString text = mInputEditor->getConvertedText(); if (!text.empty()) { // store sent line in history, duplicates will get filtered if (mInputEditor) mInputEditor->updateHistory(); // Check if this is destined for another channel S32 channel = 0; stripChannelNumber(text, &channel); std::string utf8text = wstring_to_utf8str(text); // Try to trigger a gesture, if not chat to a script. std::string utf8_revised_text; if (0 == channel) { // discard returned "found" boolean LLGestureMgr::instance().triggerAndReviseString(utf8text, &utf8_revised_text); } else { utf8_revised_text = utf8text; } utf8_revised_text = utf8str_trim(utf8_revised_text); if (!utf8_revised_text.empty()) { // Chat with animation sendChatFromViewer(utf8_revised_text, type, gSavedSettings.getBOOL("PlayChatAnim")); } } } getChild<LLUICtrl>("Chat Editor")->setValue(LLStringUtil::null); gAgent.stopTyping(); // If the user wants to stop chatting on hitting return, lose focus // and go out of chat mode. if (gChatBar == this && gSavedSettings.getBOOL("CloseChatOnReturn")) { stopChat(); } } //----------------------------------------------------------------------- // Static functions //----------------------------------------------------------------------- // static void LLChatBar::startChat(const char* line) { //TODO* remove DUMMY chat //if(gBottomTray && gBottomTray->getChatBox()) //{ // gBottomTray->setVisible(TRUE); // gBottomTray->getChatBox()->setFocus(TRUE); //} // *TODO Vadim: Why was this code commented out? // gChatBar->setVisible(TRUE); // gChatBar->setKeyboardFocus(TRUE); // gSavedSettings.setBOOL("ChatVisible", TRUE); // // if (line && gChatBar->mInputEditor) // { // std::string line_string(line); // gChatBar->mInputEditor->setText(line_string); // } // // always move cursor to end so users don't obliterate chat when accidentally hitting WASD // gChatBar->mInputEditor->setCursorToEnd(); } // Exit "chat mode" and do the appropriate focus changes // static void LLChatBar::stopChat() { //TODO* remove DUMMY chat //if(gBottomTray && gBottomTray->getChatBox()) ///{ // gBottomTray->getChatBox()->setFocus(FALSE); //} // *TODO Vadim: Why was this code commented out? // // In simple UI mode, we never release focus from the chat bar // gChatBar->setKeyboardFocus(FALSE); // // // If we typed a movement key and pressed return during the // // same frame, the keyboard handlers will see the key as having // // gone down this frame and try to move the avatar. // gKeyboard->resetKeys(); // gKeyboard->resetMaskKeys(); // // // stop typing animation // gAgent.stopTyping(); // // // hide chat bar so it doesn't grab focus back // gChatBar->setVisible(FALSE); // gSavedSettings.setBOOL("ChatVisible", FALSE); } // static void LLChatBar::onInputEditorKeystroke( LLLineEditor* caller, void* userdata ) { LLChatBar* self = (LLChatBar *)userdata; LLWString raw_text; if (self->mInputEditor) raw_text = self->mInputEditor->getWText(); // Can't trim the end, because that will cause autocompletion // to eat trailing spaces that might be part of a gesture. LLWStringUtil::trimHead(raw_text); S32 length = raw_text.length(); if( (length > 0) && (raw_text[0] != '/') ) // forward slash is used for escape (eg. emote) sequences { gAgent.startTyping(); } else { gAgent.stopTyping(); } /* Doesn't work -- can't tell the difference between a backspace that killed the selection vs. backspace at the end of line. if (length > 1 && text[0] == '/' && key == KEY_BACKSPACE) { // the selection will already be deleted, but we need to trim // off the character before std::string new_text = raw_text.substr(0, length-1); self->mInputEditor->setText( new_text ); self->mInputEditor->setCursorToEnd(); length = length - 1; } */ KEY key = gKeyboard->currentKey(); // Ignore "special" keys, like backspace, arrows, etc. if (length > 1 && raw_text[0] == '/' && key < KEY_SPECIAL) { // we're starting a gesture, attempt to autocomplete std::string utf8_trigger = wstring_to_utf8str(raw_text); std::string utf8_out_str(utf8_trigger); if (LLGestureMgr::instance().matchPrefix(utf8_trigger, &utf8_out_str)) { if (self->mInputEditor) { std::string rest_of_match = utf8_out_str.substr(utf8_trigger.size()); self->mInputEditor->setText(utf8_trigger + rest_of_match); // keep original capitalization for user-entered part S32 outlength = self->mInputEditor->getLength(); // in characters // Select to end of line, starting from the character // after the last one the user typed. self->mInputEditor->setSelection(length, outlength); } } //LL_INFOS() << "GESTUREDEBUG " << trigger // << " len " << length // << " outlen " << out_str.getLength() // << LL_ENDL; } } // static void LLChatBar::onInputEditorFocusLost() { // stop typing animation gAgent.stopTyping(); } // static void LLChatBar::onInputEditorGainFocus() { //LLFloaterChat::setHistoryCursorAndScrollToEnd(); } void LLChatBar::onClickSay( LLUICtrl* ctrl ) { std::string cmd = ctrl->getValue().asString(); e_chat_type chat_type = CHAT_TYPE_NORMAL; if (cmd == "shout") { chat_type = CHAT_TYPE_SHOUT; } else if (cmd == "whisper") { chat_type = CHAT_TYPE_WHISPER; } sendChat(chat_type); } void LLChatBar::sendChatFromViewer(const std::string &utf8text, EChatType type, BOOL animate) { sendChatFromViewer(utf8str_to_wstring(utf8text), type, animate); } void LLChatBar::sendChatFromViewer(const LLWString &wtext, EChatType type, BOOL animate) { // as soon as we say something, we no longer care about teaching the user // how to chat gWarningSettings.setBOOL("FirstOtherChatBeforeUser", FALSE); // Look for "/20 foo" channel chats. S32 channel = 0; LLWString out_text = stripChannelNumber(wtext, &channel); std::string utf8_out_text = wstring_to_utf8str(out_text); if (!utf8_out_text.empty()) { utf8_out_text = utf8str_truncate(utf8_out_text, MAX_MSG_STR_LEN); } std::string utf8_text = wstring_to_utf8str(wtext); utf8_text = utf8str_trim(utf8_text); if (!utf8_text.empty()) { utf8_text = utf8str_truncate(utf8_text, MAX_STRING - 1); } // Don't animate for chats people can't hear (chat to scripts) if (animate && (channel == 0)) { if (type == CHAT_TYPE_WHISPER) { LL_DEBUGS() << "You whisper " << utf8_text << LL_ENDL; gAgent.sendAnimationRequest(ANIM_AGENT_WHISPER, ANIM_REQUEST_START); } else if (type == CHAT_TYPE_NORMAL) { LL_DEBUGS() << "You say " << utf8_text << LL_ENDL; gAgent.sendAnimationRequest(ANIM_AGENT_TALK, ANIM_REQUEST_START); } else if (type == CHAT_TYPE_SHOUT) { LL_DEBUGS() << "You shout " << utf8_text << LL_ENDL; gAgent.sendAnimationRequest(ANIM_AGENT_SHOUT, ANIM_REQUEST_START); } else { LL_INFOS() << "send_chat_from_viewer() - invalid volume" << LL_ENDL; return; } } else { if (type != CHAT_TYPE_START && type != CHAT_TYPE_STOP) { LL_DEBUGS() << "Channel chat: " << utf8_text << LL_ENDL; } } send_chat_from_viewer(utf8_out_text, type, channel); } void LLChatBar::onCommitGesture(LLUICtrl* ctrl) { LLCtrlListInterface* gestures = mGestureCombo ? mGestureCombo->getListInterface() : NULL; if (gestures) { S32 index = gestures->getFirstSelectedIndex(); if (index == 0) { return; } const std::string& trigger = gestures->getSelectedValue().asString(); // pretend the user chatted the trigger string, to invoke // substitution and logging. std::string text(trigger); std::string revised_text; LLGestureMgr::instance().triggerAndReviseString(text, &revised_text); revised_text = utf8str_trim(revised_text); if (!revised_text.empty()) { // Don't play nodding animation sendChatFromViewer(revised_text, CHAT_TYPE_NORMAL, FALSE); } } mGestureLabelTimer.start(); if (mGestureCombo != NULL) { // free focus back to chat bar mGestureCombo->setFocus(FALSE); } } #endif
25.917683
116
0.683861
[ "object" ]