hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 77k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 653k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bbc512ed68463d935ede3a4f15d7ad35183f3eec | 310 | hxx | C++ | src/common.hxx | scuisdc/iojxd | 6ced0d5983a8075c313869791f7295b98ce3f174 | [
"BSD-2-Clause"
] | 1 | 2015-05-18T00:02:13.000Z | 2015-05-18T00:02:13.000Z | src/common.hxx | scuisdc/iojxd | 6ced0d5983a8075c313869791f7295b98ce3f174 | [
"BSD-2-Clause"
] | null | null | null | src/common.hxx | scuisdc/iojxd | 6ced0d5983a8075c313869791f7295b98ce3f174 | [
"BSD-2-Clause"
] | null | null | null | //
// Created by secondwtq <lovejay-lovemusic@outlook.com> 2015/05/18.
// Copyright (c) 2015 SCU ISDC All rights reserved.
//
// This file is part of ISDCNext.
//
// We have always treaded the borderland.
//
#ifndef IOJXD_COMMON_HXX
#define IOJXD_COMMON_HXX
#include "context.hxx"
#endif //IOJXD_COMMON_HXX
| 19.375 | 67 | 0.735484 |
bbc5e81a9964600eb7019aeadcbff4cb0a8329ec | 1,961 | cpp | C++ | OpenCV/gray_image.cpp | vladiant/color2gray | 372283ae67b0dfb41745108f67cc714efc7b3d7a | [
"MIT"
] | null | null | null | OpenCV/gray_image.cpp | vladiant/color2gray | 372283ae67b0dfb41745108f67cc714efc7b3d7a | [
"MIT"
] | null | null | null | OpenCV/gray_image.cpp | vladiant/color2gray | 372283ae67b0dfb41745108f67cc714efc7b3d7a | [
"MIT"
] | null | null | null | #include "gray_image.hpp"
#include <opencv2/imgcodecs.hpp>
GrayImage::GrayImage(ColorImage &s) : data(s.N), w(s.w), h(s.h), N(s.N) {
for (int i = 0; i < N; i++) data[i] = (s.data)[i].l;
}
void GrayImage::r_solve(const float *d, int r) {
const int iters = 30;
int k, x, y;
for (k = 0; k < iters; k++) {
// printf("iter %d\n", k);
// perform a Gauss-Seidel relaxation.
for (x = 0; x < w; x++)
for (y = 0; y < h; y++) {
float sum = 0;
int count = 0;
int xx, yy;
for (xx = x - r; xx <= x + r; xx++) {
if (xx < 0 || xx >= w) continue;
for (yy = y - r; yy <= y + r; yy++) {
if (yy >= h || yy < 0) continue;
sum += data[xx + yy * w];
count++;
}
}
data[x + y * w] = (d[x + w * y] + sum) / (float)count;
}
}
}
void GrayImage::complete_solve(const float *d) {
for (int i = 1; i < N; i++) {
data[i] = d[i] - d[i - 1] + N * data[i - 1];
data[i] /= (float)N;
}
}
void GrayImage::post_solve(const ColorImage &s) {
float error = 0;
for (int i = 0; i < N; i++) error += data[i] - (s.data)[i].l;
error /= N;
for (int i = 0; i < N; i++) data[i] = data[i] - error;
}
cv::Mat GrayImage::save(const char *fname) const {
cv::Mat3b out_image(h, w);
auto it = out_image.begin();
for (int i = 0; i < N; i++, ++it) {
const sven::rgb rval = amy_lab(data[i], 0, 0).to_rgb();
*it = cv::Vec3b(rval.r, rval.g, rval.b);
}
cv::imwrite(fname, out_image);
return out_image;
}
cv::Mat GrayImage::saveColor(const char *fname,
const ColorImage &source) const {
cv::Mat3b out_image(h, w);
auto it = out_image.begin();
for (int i = 0; i < N; i++, ++it) {
const sven::rgb rval =
amy_lab(data[i], ((source.data)[i]).a, ((source.data)[i]).b).to_rgb();
*it = cv::Vec3b(rval.b, rval.g, rval.r);
}
cv::imwrite(fname, out_image);
return out_image;
}
| 25.802632 | 78 | 0.494646 |
bbc685778822168fdfc95254155507c30e9efd6e | 6,505 | cpp | C++ | DrunkEngine/ComponentTransform.cpp | MarcFly/Fly3D-Engine | e8da09a63c7c3d991b8f25c346798ee230593e78 | [
"Unlicense"
] | null | null | null | DrunkEngine/ComponentTransform.cpp | MarcFly/Fly3D-Engine | e8da09a63c7c3d991b8f25c346798ee230593e78 | [
"Unlicense"
] | 3 | 2018-09-27T17:00:14.000Z | 2018-12-19T13:30:25.000Z | DrunkEngine/ComponentTransform.cpp | MarcFly/Fly3D-Engine | e8da09a63c7c3d991b8f25c346798ee230593e78 | [
"Unlicense"
] | null | null | null | #include "ComponentTransform.h"
#include "GameObject.h"
#include "Assimp/include/scene.h"
#include "GameObject.h"
#include "Application.h"
ComponentTransform::ComponentTransform(const aiMatrix4x4 * t, GameObject* par)
{
SetBaseVals();
SetFromMatrix(t);
parent = par;
SetLocalTransform();
}
void ComponentTransform::SetFromMatrix(const aiMatrix4x4* t)
{
aiVector3D local_scale;
aiVector3D pos;
aiQuaternion rot;
t->Decompose(local_scale, rot, pos);
scale = float3(local_scale.x, local_scale.y, local_scale.z);
rotate_quat = Quat(rot.x, rot.y, rot.z, rot.w);
position = float3(pos.x, pos.y, pos.z);
SetTransformRotation(rotate_quat);
}
void ComponentTransform::SetFromMatrix(const float4x4 * t)
{
float3 local_scale;
float3 pos;
Quat rot;
t->Decompose(position, rotate_quat, scale);
SetTransformRotation(rotate_quat);
}
void ComponentTransform::SetTransformPosition(const float pos_x, const float pos_y, const float pos_z)
{
position.x = pos_x;
position.y = pos_y;
position.z = pos_z;
SetLocalTransform();
}
void ComponentTransform::SetTransformRotation(const Quat rot_quat)
{
rotate_quat = rot_quat;
rotate_euler = RadToDeg(rotate_quat.ToEulerXYZ());
SetLocalTransform();
}
void ComponentTransform::SetTransformRotation(const float3 rot_vec)
{
rotate_quat = Quat::FromEulerXYZ(DegToRad(rot_vec.x), DegToRad(rot_vec.y), DegToRad(rot_vec.z));
rotate_euler = rot_vec;
SetLocalTransform();
}
void ComponentTransform::SetTransformScale(const float scale_x, const float scale_y, const float scale_z)
{
if (scale.x != scale_x && scale_x > 0.1f)
scale.x = scale_x;
if (scale.y != scale_y && scale_y > 0.1f)
scale.y = scale_y;
if (scale.z != scale_z && scale_z > 0.1f)
scale.z = scale_z;
SetLocalTransform();
}
void ComponentTransform::SetLocalTransform()
{
local_transform = float4x4::FromTRS(position, rotate_quat, scale);
}
void ComponentTransform::SetWorldPos(const float4x4 new_transform)
{
aux_world_pos = aux_world_pos * new_transform;
world_pos = world_pos * new_transform;
}
void ComponentTransform::SetWorldRot(const Quat new_rot)
{
world_rot = world_rot * world_rot.FromQuat(new_rot, aux_world_pos.Col3(3) - world_pos.Col3(3));
//world_rot[0][0] = 1.f;
//world_rot[1][1] = 1.f;
//world_rot[2][2] = 1.f;
//world_rot[3][3] = 1.f;
}
void ComponentTransform::CalculateGlobalTransforms()
{
if (parent->parent != nullptr)
global_transform = world_pos * world_rot * parent->parent->GetTransform()->global_transform * local_transform;
else
global_transform = local_transform;
global_transform.Decompose(global_pos, global_rot, global_scale);
//global_pos = global_transform.Col3(3);
//global_rot = GetRotFromMat(global_transform);
//global_scale = global_transform.GetScale();
if (parent->children.size() > 0)
{
for (std::vector<GameObject*>::iterator it = parent->children.begin(); it != parent->children.end(); it++)
{
(*it)->GetTransform()->CalculateGlobalTransforms();
}
}
SetAuxWorldPos();
}
void ComponentTransform::SetAuxWorldPos()
{
aux_world_pos = float4x4::FromTRS(float3(float3::zero - global_transform.Col3(3)), Quat::identity.Neg(), float3::one);
aux_world_pos = -aux_world_pos;
}
Quat ComponentTransform::GetRotFromMat(float4x4 mat)
{
Quat rot;
rot.w = Sqrt(max(0, 1 + mat.Diagonal3().x + mat.Diagonal3().y + mat.Diagonal3().z)) / 2;
rot.x = Sqrt(max(0, 1 + mat.Diagonal3().x - mat.Diagonal3().y - mat.Diagonal3().z)) / 2;
rot.y = Sqrt(max(0, 1 - mat.Diagonal3().x + mat.Diagonal3().y - mat.Diagonal3().z)) / 2;
rot.z = Sqrt(max(0, 1 - mat.Diagonal3().x - mat.Diagonal3().y + mat.Diagonal3().z)) / 2;
rot.x *= sgn(rot.x * (mat.Col3(2).y - mat.Col3(1).z));
rot.y *= sgn(rot.y * (mat.Col3(0).z - mat.Col3(2).x));
rot.z *= sgn(rot.z * (mat.Col3(1).x - mat.Col3(0).y));
rot.x = -rot.x;
rot.y = -rot.y;
rot.z = -rot.z;
return rot;
}
void ComponentTransform::CleanUp()
{
parent = nullptr;
}
void ComponentTransform::Load(const JSON_Object* comp)
{
position.x = json_object_dotget_number(comp, "position.x");
position.y = json_object_dotget_number(comp, "position.y");
position.z = json_object_dotget_number(comp, "position.z");
scale.x = json_object_dotget_number(comp, "scale.x");
scale.y = json_object_dotget_number(comp, "scale.y");
scale.z = json_object_dotget_number(comp, "scale.z");
rotate_quat.w = json_object_dotget_number(comp, "rotate_quat.w");
rotate_quat.x = json_object_dotget_number(comp, "rotate_quat.x");
rotate_quat.y = json_object_dotget_number(comp, "rotate_quat.y");
rotate_quat.z = json_object_dotget_number(comp, "rotate_quat.z");
SetTransformRotation(rotate_quat);
SetLocalTransform();
bool fromAINode = json_object_dotget_boolean(comp, "fromAINode");
std::string setname;
if (!fromAINode)
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
setname = "world_pos." + std::to_string(j + i * 4);
world_pos.v[i][j] = json_object_dotget_number(comp, setname.c_str());
setname = "world_rot." + std::to_string(j + i * 4);
world_rot.v[i][j] = json_object_dotget_number(comp, setname.c_str());
}
}
}
}
void ComponentTransform::Save(JSON_Array* comps)
{
JSON_Value* append = json_value_init_object();
JSON_Object* curr = json_value_get_object(append);
json_object_dotset_number(curr, "properties.type", type);
json_object_dotset_number(curr, "properties.position.x", position.x);
json_object_dotset_number(curr, "properties.position.y", position.y);
json_object_dotset_number(curr, "properties.position.z", position.z);
json_object_dotset_number(curr, "properties.scale.x", scale.x);
json_object_dotset_number(curr, "properties.scale.y", scale.y);
json_object_dotset_number(curr, "properties.scale.z", scale.z);
json_object_dotset_number(curr, "properties.rotate_quat.w", rotate_quat.w);
json_object_dotset_number(curr, "properties.rotate_quat.x", rotate_quat.x);
json_object_dotset_number(curr, "properties.rotate_quat.y", rotate_quat.y);
json_object_dotset_number(curr, "properties.rotate_quat.z", rotate_quat.z);
json_object_dotset_boolean(curr, "properties.fromAINode", false);
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
std::string setname = "properties.world_pos." + std::to_string(j + i*4);
json_object_dotset_number(curr, setname.c_str(), world_pos.v[i][j]);
setname = "properties.world_rot." + std::to_string(j + i*4);
json_object_dotset_number(curr, setname.c_str(), world_rot.v[i][j]);
}
}
json_array_append_value(comps, append);
} | 28.656388 | 119 | 0.719139 |
bbc92a9fb0faf00781a7425569972ea028a65eb4 | 447 | cpp | C++ | Day 5/CoreTeam/Prateek.cpp | insigne10/MarchCode | 7cca5cfe7175ee4fcdad58016227a623f6c860cd | [
"MIT"
] | null | null | null | Day 5/CoreTeam/Prateek.cpp | insigne10/MarchCode | 7cca5cfe7175ee4fcdad58016227a623f6c860cd | [
"MIT"
] | null | null | null | Day 5/CoreTeam/Prateek.cpp | insigne10/MarchCode | 7cca5cfe7175ee4fcdad58016227a623f6c860cd | [
"MIT"
] | null | null | null | /*-------------To print all the natural numbers between n and m------------*/
#include <stdio.h>
int main()
{
int n=0, m=0;
int i=0;
printf("Enter n: ");
scanf("%d", &n);
printf("Enter m: ");
scanf("%d", &m);
if(m<0 || n<0)
printf("Input positive values only.\n");
else{
for(i =n; i<=m && i>=n; i++)
printf("%d ", i);
}
printf("\n");
return 0;
}
| 17.88 | 78 | 0.404922 |
bbccc72caa4293248053db27c43b3e2d27cf3e40 | 16,419 | cpp | C++ | WaveEngine.Vuforia/Projects/Libs/VuforiaAdapter/VuforiaAdapter.Shared/VuforiaAdapter.cpp | WaveEngine/Extensions-2.5 | 6ad1271d444d08ad3ac07bdb1b3e50eddbf89ef5 | [
"MIT"
] | 14 | 2015-01-22T19:52:36.000Z | 2020-06-21T22:31:27.000Z | WaveEngine.Vuforia/Projects/Libs/VuforiaAdapter/VuforiaAdapter.Shared/VuforiaAdapter.cpp | WaveEngine/Extensions-2.5 | 6ad1271d444d08ad3ac07bdb1b3e50eddbf89ef5 | [
"MIT"
] | 1 | 2016-09-05T23:01:20.000Z | 2016-09-05T23:01:20.000Z | WaveEngine.Vuforia/Projects/Libs/VuforiaAdapter/VuforiaAdapter.Shared/VuforiaAdapter.cpp | WaveEngine/Extensions | 6ad1271d444d08ad3ac07bdb1b3e50eddbf89ef5 | [
"MIT"
] | 6 | 2015-04-05T14:49:31.000Z | 2016-09-05T21:12:52.000Z | //-----------------------------------------------------------------------------
// VuforiaAdapter.cpp
//
// Copyright © 2010 - 2013 Wave Coorporation. All rights reserved.
// Use is subject to license terms.
//-----------------------------------------------------------------------------
#include "VuforiaAdapter.h"
int gFrameWidth;
int gFrameHeight;
QCAR_State gState = QCAR_State::QCAR_STOPPED;
Vuforia::DataSet* currentDataset;
void ConfigureVideoBackground(bool isPortrait);
void PrintInitError(int errorCode);
bool InternalStartTracking();
// QCAR State
QCAR_State QCAR_getState()
{
return gState;
}
void QCAR_getVideoMesh(VideoMesh* mesh)
{
}
void QCAR_getVideoInfo(int* textureWidth, int* textureHeight, VideoMesh* videoMesh)
{
if (gState != QCAR_State::QCAR_STOPPED)
{
auto renderingPrimitives = new Vuforia::RenderingPrimitives(Vuforia::Device::getInstance().getRenderingPrimitives());
const Vuforia::Vec2I texSize = renderingPrimitives->getVideoBackgroundTextureSize();
// Initialize the video background mesh
const Vuforia::Mesh &vbMesh = renderingPrimitives->getVideoBackgroundMesh(Vuforia::VIEW_SINGULAR);
const Vuforia::Vec3F *vbVertices = vbMesh.getPositions();
const Vuforia::Vec2F *vbTexCoords = vbMesh.getUVs();
const unsigned short *vbIndices = vbMesh.getTriangles();
*textureWidth = texSize.data[0];
*textureHeight = texSize.data[1];
// Vertex poositions
videoMesh->v1.posX = vbVertices[0].data[0];
videoMesh->v1.posY = vbVertices[0].data[1];
videoMesh->v1.posZ = vbVertices[0].data[2];
videoMesh->v1.texCoordX = vbTexCoords[0].data[0];
videoMesh->v1.texCoordY = vbTexCoords[0].data[1];
videoMesh->v2.posX = vbVertices[1].data[0];
videoMesh->v2.posY = vbVertices[1].data[1];
videoMesh->v2.posZ = vbVertices[1].data[2];
videoMesh->v2.texCoordX = vbTexCoords[1].data[0];
videoMesh->v2.texCoordY = vbTexCoords[1].data[1];
videoMesh->v3.posX = vbVertices[2].data[0];
videoMesh->v3.posY = vbVertices[2].data[1];
videoMesh->v3.posZ = vbVertices[2].data[2];
videoMesh->v3.texCoordX = vbTexCoords[2].data[0];
videoMesh->v3.texCoordY = vbTexCoords[2].data[1];
videoMesh->v4.posX = vbVertices[3].data[0];
videoMesh->v4.posY = vbVertices[3].data[1];
videoMesh->v4.posZ = vbVertices[3].data[2];
videoMesh->v4.texCoordX = vbTexCoords[3].data[0];
videoMesh->v4.texCoordY = vbTexCoords[3].data[1];
videoMesh->indices[0] = vbIndices[0];
videoMesh->indices[1] = vbIndices[1];
videoMesh->indices[2] = vbIndices[2];
videoMesh->indices[3] = vbIndices[3];
videoMesh->indices[4] = vbIndices[4];
videoMesh->indices[5] = vbIndices[5];
delete renderingPrimitives;
renderingPrimitives = nullptr;
}
}
#ifdef DX11
void QCAR_setVideoTexture(ID3D11Texture2D* texture)
{
Vuforia::Renderer &vuforiaRenderer = Vuforia::Renderer::getInstance();
vuforiaRenderer.setVideoBackgroundTexture(Vuforia::DXTextureData(texture));
}
void QCAR_updateVideoTexture(ID3D11Device* device)
{
Vuforia::Renderer &vuforiaRenderer = Vuforia::Renderer::getInstance();
Vuforia::DXRenderData dxRenderData(device);
vuforiaRenderer.begin(&dxRenderData);
vuforiaRenderer.updateVideoBackgroundTexture(nullptr);
vuforiaRenderer.end();
};
bool QCAR_setHolographicAppCS(void* appSpecifiedCS)
{
return Vuforia::setHolographicAppCS(appSpecifiedCS);
}
#endif
#ifdef OPENGL
void QCAR_setVideoTexture(int textureId)
{
Vuforia::Renderer &vuforiaRenderer = Vuforia::Renderer::getInstance();
vuforiaRenderer.setVideoBackgroundTexture(Vuforia::GLTextureData(textureId));
}
void QCAR_updateVideoTexture()
{
Vuforia::Renderer &vuforiaRenderer = Vuforia::Renderer::getInstance();
vuforiaRenderer.begin();
vuforiaRenderer.updateVideoBackgroundTexture(nullptr);
vuforiaRenderer.end();
};
#endif
// Init QCAR
#if ANDROID
void QCAR_setInitState()
{
// Initialized through Java binding
gState = QCAR_State::QCAR_INITIALIZED;
}
#else
bool InternalInit()
{
// Vuforia::init() will return positive numbers up to 100 as it progresses towards success
// and negative numbers for error indicators
int progress = 0;
while (progress >= 0 && progress < 100)
{
progress = Vuforia::init();
}
if (progress < 0)
{
PrintInitError(progress);
return false;
}
gState = QCAR_State::QCAR_INITIALIZED;
return true;
}
void QCAR_init(const char* licenseKey, InitCallback callback)
{
#if UWP
Vuforia::setInitParameters(licenseKey);
Concurrency::create_task([callback]()
{
bool result = InternalInit();
callback(result);
});
#else
Vuforia::setInitParameters(Vuforia::GL_20, licenseKey);
bool result = InternalInit();
callback(result);
#endif
}
#endif
// ShutDown QCAR
bool QCAR_shutDown()
{
if (gState == QCAR_State::QCAR_TRACKING)
{
QCAR_stopTrack();
}
else if (gState == QCAR_State::QCAR_STOPPED)
{
return false;
}
// shutdown QCAR
Vuforia::deinit();
gState = QCAR_State::QCAR_STOPPED;
return true;
}
// Set camera orientation
void QCAR_setOrientation(int frameWidth, int frameHeight, QCAR_Orientation orientation)
{
if (gState != QCAR_State::QCAR_TRACKING)
{
return;
}
#if IOS
Vuforia::IOS_INIT_FLAGS orientationFlag;
switch (orientation) {
case QCAR_ORIENTATION_PORTRAIT:
orientationFlag = Vuforia::ROTATE_IOS_90;
break;
case QCAR_ORIENTATION_PORTRAIT_UPSIDEDOWN:
orientationFlag = Vuforia::ROTATE_IOS_270;
break;
case QCAR_ORIENTATION_LANDSCAPE_LEFT:
orientationFlag = Vuforia::ROTATE_IOS_0;
break;
default:
orientationFlag = Vuforia::ROTATE_IOS_180;
break;
}
Vuforia::setRotation(orientationFlag);
#elif UWP
DisplayOrientations orientationFlag;
switch (orientation) {
case QCAR_ORIENTATION_PORTRAIT:
orientationFlag = DisplayOrientations::Portrait;
break;
case QCAR_ORIENTATION_PORTRAIT_UPSIDEDOWN:
orientationFlag = DisplayOrientations::PortraitFlipped;
break;
case QCAR_ORIENTATION_LANDSCAPE_LEFT:
orientationFlag = DisplayOrientations::Landscape;
break;
default:
orientationFlag = DisplayOrientations::LandscapeFlipped;
break;
}
Vuforia::setCurrentOrientation(orientationFlag);
#endif
gFrameWidth = frameWidth;
gFrameHeight = frameHeight;
bool isPortrait =
(orientation == QCAR_ORIENTATION_PORTRAIT) ||
(orientation == QCAR_ORIENTATION_PORTRAIT_UPSIDEDOWN);
Vuforia::onSurfaceChanged(gFrameWidth, gFrameHeight);
ConfigureVideoBackground(isPortrait);
}
bool QCAR_setHint(unsigned int hint, int value)
{
return Vuforia::setHint(hint, value);
}
// Initializes the QCAR tracking with a datase
int QCAR_loadDataSet(const char* dataSetPath, bool extendedTracking, LoadDataSetResult* trackables)
{
// If QCAR is not in initialized state...
if (gState != QCAR_State::QCAR_INITIALIZED)
{
LogMessage("QCAR has not been initialized.\n");
return 200;
}
// Get the image tracker:
Vuforia::TrackerManager& trackerManager = Vuforia::TrackerManager::getInstance();
Vuforia::ObjectTracker* tracker = static_cast<Vuforia::ObjectTracker*> (trackerManager.initTracker(Vuforia::ObjectTracker::getClassType()));
if (tracker == NULL)
{
LogMessage("Failed to load tracking data set because the ImageTracker has not been initialized.\n");
return 100;
}
if (currentDataset != nullptr)
{
tracker->destroyDataSet(currentDataset);
}
// Create the data set:
currentDataset = tracker->createDataSet();
if (currentDataset == 0)
{
LogMessage("Failed to create a new tracking data.\n");
return 101;
}
// Load the data set:
if (!currentDataset->load(dataSetPath, Vuforia::STORAGE_APPRESOURCE))
{
LogMessage("Failed to load data set.\n");
return 102;
}
// Activate the data set:
if (!tracker->activateDataSet(currentDataset))
{
LogMessage("Failed to activate data set.\n");
return 103;
}
trackables->NumTrackables = currentDataset->getNumTrackables();
for (int i = 0; i < trackables->NumTrackables; i++)
{
Vuforia::Trackable* trackable = currentDataset->getTrackable(i);
trackables->trackableResults[i].id = trackable->getId();
strcpy(trackables->trackableResults[i].trackName, trackable->getName());
if (trackable->isOfType(Vuforia::VuMarkTemplate::getClassType()))
{
trackables->trackableResults[i].targetType = QCAR_TargetTypes::VuMark;
}
else
{
trackables->trackableResults[i].targetType = QCAR_TargetTypes::ImageTarget;
}
if (extendedTracking)
{
trackable->startExtendedTracking();
}
else
{
trackable->stopExtendedTracking();
}
}
return 0;
}
// Start AR track
void QCAR_startTrack(StartTrackCallback callback)
{
#if UWP
Concurrency::create_task([callback]()
{
bool result = InternalStartTracking();
callback(result);
});
#else
bool result = InternalStartTracking();
callback(result);
#endif
}
// Stop AR track
bool QCAR_stopTrack()
{
if (gState != QCAR_State::QCAR_TRACKING)
{
return false;
}
// Stop the tracker:
Vuforia::TrackerManager& trackerManager = Vuforia::TrackerManager::getInstance();
Vuforia::Tracker* tracker = trackerManager.getTracker(Vuforia::ObjectTracker::getClassType());
if (tracker != 0)
{
tracker->stop();
}
Vuforia::CameraDevice::getInstance().stop();
gState = QCAR_State::QCAR_INITIALIZED;
return true;
}
// Update
void QCAR_update(UpdateResult* updateResult)
{
if (gState == QCAR_State::QCAR_TRACKING)
{
// Get the state from Vuforia and mark the beginning of a rendering section
auto state = Vuforia::Renderer::getInstance().begin();
updateResult->numTrackableResults = state.getNumTrackableResults();
for (int tIdx = 0; tIdx < updateResult->numTrackableResults; tIdx++)
{
// Get the trackable
const Vuforia::TrackableResult* result = state.getTrackableResult(tIdx);
QCAR_TrackableResult* trackResult = &updateResult->trackableResults[tIdx];
*((Vuforia::Matrix44F*)&trackResult->trackPose) = Vuforia::Tool::convertPose2GLMatrix(result->getPose());
trackResult->status = (QCAR_TrackableResultStatus)result->getStatus();
const Vuforia::Trackable& trackable = result->getTrackable();
trackResult->id = trackable.getId();
if (result->isOfType(Vuforia::VuMarkTargetResult::getClassType()))
{
const Vuforia::VuMarkTarget& vmTarget = (Vuforia::VuMarkTarget&)trackable;
trackResult->templateId = vmTarget.getTemplate().getId();
const Vuforia::InstanceId & vmId = vmTarget.getInstanceId();
trackResult->dataType = (QCAR_VuMarkDataType)vmId.getDataType();
trackResult->dataSize = (unsigned int)vmId.getLength();
trackResult->numericValue = (unsigned int)vmId.getNumericValue();
memcpy(trackResult->data, vmId.getBuffer(), vmId.getLength());
}
else
{
trackResult->templateId = trackResult->id;
}
}
auto renderingPrimitives = new Vuforia::RenderingPrimitives(Vuforia::Device::getInstance().getRenderingPrimitives());
// Get the Vuforia video-background projection matrix
Vuforia::Matrix34F vbProjection = renderingPrimitives->getVideoBackgroundProjectionMatrix(Vuforia::VIEW::VIEW_SINGULAR, Vuforia::COORDINATE_SYSTEM_CAMERA);
*((Vuforia::Matrix44F*)&updateResult->videoBackgroundProjection) = Vuforia::Tool::convert2GLMatrix(vbProjection);
Vuforia::Renderer::getInstance().end();
}
}
// Get Camera projection with its near/far plane
void QCAR_getCameraProjection(float nearPlane, float farPlane, QCAR_Matrix4x4* result)
{
if (gState != QCAR_State::QCAR_TRACKING)
{
return;
}
auto renderingPrimitives = new Vuforia::RenderingPrimitives(Vuforia::Device::getInstance().getRenderingPrimitives());
// Calculate the DX Projection matrix
Vuforia::Matrix44F projection = Vuforia::Tool::convertPerspectiveProjection2GLMatrix(
renderingPrimitives->getProjectionMatrix(Vuforia::VIEW_SINGULAR, Vuforia::COORDINATE_SYSTEM_CAMERA),
nearPlane, farPlane);
delete renderingPrimitives;
renderingPrimitives = nullptr;
memcpy(result, &projection, sizeof(Vuforia::Matrix44F));
}
// Configure the video background
void ConfigureVideoBackground(bool isPortrait)
{
// Get the default video mode
Vuforia::CameraDevice& cameraDevice = Vuforia::CameraDevice::getInstance();
Vuforia::VideoMode videoMode = cameraDevice.getVideoMode(Vuforia::CameraDevice::MODE_DEFAULT);
// Configure the video background
Vuforia::VideoBackgroundConfig config;
config.mEnabled = true;
config.mPosition.data[0] = 0;
config.mPosition.data[1] = 0;
if (isPortrait)
{
config.mSize.data[0] = (int)(videoMode.mHeight * (gFrameHeight / (float)videoMode.mWidth));
config.mSize.data[1] = (int)gFrameHeight;
if (config.mSize.data[0] < gFrameWidth)
{
config.mSize.data[0] = (int)gFrameWidth;
config.mSize.data[1] = (int)(gFrameWidth * (videoMode.mWidth / (float)videoMode.mHeight));
}
}
else
{
config.mSize.data[0] = (int)gFrameWidth;
config.mSize.data[1] = (int)(videoMode.mHeight * (gFrameWidth / (float)videoMode.mWidth));
if (config.mSize.data[1] < gFrameHeight)
{
config.mSize.data[0] = (int)(gFrameHeight * (videoMode.mWidth / (float)videoMode.mHeight));
config.mSize.data[1] = (int)gFrameHeight;
}
}
// Set the config
Vuforia::Renderer::getInstance().setVideoBackgroundConfig(config);
}
void PrintInitError(int errorCode)
{
if (errorCode >= 0)
return;// not an error, do nothing
switch (errorCode)
{
case Vuforia::INIT_ERROR:
LogMessage("Failed to initialize Vuforia.\n");
break;
case Vuforia::INIT_LICENSE_ERROR_INVALID_KEY:
LogMessage("Invalid Key used. Please make sure you are using a valid Vuforia App Key\n");
break;
case Vuforia::INIT_LICENSE_ERROR_CANCELED_KEY:
LogMessage("This App license key has been cancelled and may no longer be used. "
"Please get a new license key.\n");
break;
case Vuforia::INIT_LICENSE_ERROR_MISSING_KEY:
LogMessage("Vuforia App key is missing. Please get a valid key, by logging"
" into your account at developer.vuforia.com and creating a new project\n");
break;
case Vuforia::INIT_LICENSE_ERROR_PRODUCT_TYPE_MISMATCH:
LogMessage("Vuforia App key is not valid for this product."
" Please get a valid key, by logging into your account at developer.vuforia.com and choosing "
"the right product type during project creation\n");
break;
case Vuforia::INIT_LICENSE_ERROR_NO_NETWORK_TRANSIENT:
LogMessage("Unable to contact server. Please try again later.\n");
break;
case Vuforia::INIT_LICENSE_ERROR_NO_NETWORK_PERMANENT:
LogMessage("No network available. Please make sure you are connected to the internet.\n");
break;
case Vuforia::INIT_DEVICE_NOT_SUPPORTED:
LogMessage("Failed to initialize Vuforia because this device is not supported.\n");
break;
case Vuforia::INIT_EXTERNAL_DEVICE_NOT_DETECTED:
LogMessage("Failed to initialize Vuforia because this device is not docked with required external hardware.\n");
break;
case Vuforia::INIT_NO_CAMERA_ACCESS:
LogMessage("Camera Access was denied to this App. \n"
"When running on iOS8 devices, \n"
"users must explicitly allow the App to access the camera.\n"
"To restore camera access on your device, go to: \n"
"Settings > Privacy > Camera > [This App Name] and switch it ON.\n");
break;
default:
LogMessage("Vuforia init error. Unknown error.\n");
}
}
bool InternalStartTracking()
{
if (gState == QCAR_State::QCAR_TRACKING)
{
return true;
}
else if (gState == QCAR_State::QCAR_STOPPED)
{
return false;
}
Vuforia::Device::getInstance().setMode(Vuforia::Device::MODE_VR);
// Initialise the camera
if (!Vuforia::CameraDevice::getInstance().init(Vuforia::CameraDevice::CAMERA_DIRECTION_DEFAULT))
{
LogMessage("Failed to init camera.\n");
return false;
}
if (!Vuforia::CameraDevice::getInstance().selectVideoMode(Vuforia::CameraDevice::MODE_DEFAULT))
{
LogMessage("Failed to set camera video mode.\n");
return false;
}
// Configure video background
ConfigureVideoBackground(false);
Vuforia::CameraDevice::getInstance().setFocusMode(Vuforia::CameraDevice::FOCUS_MODE_CONTINUOUSAUTO);
// Start camera capturing
if (!Vuforia::CameraDevice::getInstance().start())
{
LogMessage("Failed to start camera capture.\n");
return false;
}
// Start the tracker
Vuforia::TrackerManager& trackerManager = Vuforia::TrackerManager::getInstance();
Vuforia::Tracker* tracker = trackerManager.getTracker(Vuforia::ObjectTracker::getClassType());
if (tracker == 0)
{
LogMessage("Cannot start tracker, tracker is null.\n");
return false;
}
if (!tracker->start())
{
LogMessage("Failed to start tracker.\n");
return false;
}
gState = QCAR_State::QCAR_TRACKING;
return true;
}
| 27.781726 | 157 | 0.736464 |
bbd3514f31648310f957b4b1fcb9c0c7b60f944c | 3,199 | hpp | C++ | src/Base/TaskProcessors/ThreadedTaskProcessor/ThreadedTaskProcessor.hpp | PhilipVinc/PincoSimulator | 562192cf3b09d0e67be7e6fee67ff9b59fbc3fd3 | [
"MIT"
] | 1 | 2017-10-23T13:22:01.000Z | 2017-10-23T13:22:01.000Z | src/Base/TaskProcessors/ThreadedTaskProcessor/ThreadedTaskProcessor.hpp | PhilipVinc/PincoSimulator | 562192cf3b09d0e67be7e6fee67ff9b59fbc3fd3 | [
"MIT"
] | null | null | null | src/Base/TaskProcessors/ThreadedTaskProcessor/ThreadedTaskProcessor.hpp | PhilipVinc/PincoSimulator | 562192cf3b09d0e67be7e6fee67ff9b59fbc3fd3 | [
"MIT"
] | null | null | null | //
// Created by Filippo Vicentini on 20/12/2017.
//
#ifndef SIMULATOR_THREADEDTASKPROCESSOR_HPP
#define SIMULATOR_THREADEDTASKPROCESSOR_HPP
#include "Base/TaskProcessor.hpp"
#include "Libraries/concurrentqueue.h"
#include <chrono>
#include <stdio.h>
#include <queue>
#include <vector>
#include <thread>
class Settings;
class WorkerThread;
class ThreadedTaskProcessor : public TaskProcessor
{
public:
ThreadedTaskProcessor(std::string solverName, int _processes, int _max_processes = 0);
virtual ~ThreadedTaskProcessor();
virtual void Setup() final;
virtual void Update() final;
// -------- Called From Workers ---------- //
// Take a task from dispatchedTasks to execute it (called by a worker)
std::vector<std::unique_ptr<TaskData>> GetDispatchedTasks(size_t th_id, size_t maxTasks =1);
void GiveCompletedResults(size_t th_id, std::vector<TaskResults*> res);
void GiveCompletedResults(size_t th_id, TaskResults* res);
// -------------------------------------- //
// Return a completed task, to add it to elaboratedTasks
void GiveResults(size_t th_id, std::unique_ptr<TaskResults> task);
void GiveResults(size_t th_id, std::vector<std::unique_ptr<TaskResults>>&& tasks);
// Method called by a thread to inform the manager that he is now dead
// and can be joined.
void ReportThreadTermination(size_t th_id);
virtual void AllProducersHaveBeenTerminated() final;
void Terminate();
void TerminateWhenDone();
protected:
// Redef
size_t nTasksEnqueued = 0;
// Threading support
size_t nThreads = 1;
#ifdef GPU_SUPPORT
size_t nGPUThreads = 0;
size_t nAvailableGPUs = 0;
#endif
// --- old---
size_t nTasksLeftToEnqueue = 0;
size_t nTasksToSave = 0;
size_t nTasksFillCapacity = 1;
mutable size_t nCompletedTasks = 0;
size_t nTotalTasks = 0;
private:
size_t nextWorkerId = 0;
std::vector<size_t> activeThreads;
std::queue<size_t> unactivatedThreadPool;
moodycamel::ConcurrentQueue<size_t> threadsToJoin;
std::vector<std::thread> threads;
std::vector<WorkerThread*> workers;
std::vector<size_t> workerProducerID;
std::vector<size_t> workerCompletedTasks;
bool terminate = false;
bool terminateWhenDone = false;
void CreateWorker(Solver* solver);
void TerminateWorker(size_t i);
void TerminateWorkerWhenDone(size_t i);
void TerminateAllWorkers();
void TerminateAllWorkersWhenDone();
void JoinThread(size_t th_id);
// Optimizer Stuff
void EnableProfilingInWorkers();
void DisableProfilingInWorkers();
void ComputeAverageSpeed();
bool profiling = true;
size_t maxProcesses = 0;
float averageTaskComputationTime = 0.0;
int sleepTimeMs = 1000;
std::chrono::system_clock::time_point lastOptTime;
std::chrono::system_clock::time_point lastPrintTime;
std::chrono::system_clock::time_point startTime;
std::chrono::system_clock::duration deltaTOpt;
std::chrono::system_clock::duration deltaTPrint;
// Printing stuff
size_t lastMsgLength = 0;
public:
void ReportAverageSpeed(float speed) ;
virtual size_t NumberOfCompletedTasks() const final;
virtual float Progress() const final;
};
#endif //SIMULATOR_THREADEDTASKPROCESSOR_HPP
| 27.577586 | 93 | 0.732416 |
bbd738324e4aa104eacdeb3a196245928d193a91 | 624 | cpp | C++ | HackerRank Solutions/C++/STL/Sets-STL.cpp | UtkarshPathrabe/Competitive-Coding | ba322fbb1b88682d56a9b80bdd92a853f1caa84e | [
"MIT"
] | 13 | 2021-09-02T07:30:02.000Z | 2022-03-22T19:32:03.000Z | HackerRank Solutions/C++/STL/Sets-STL.cpp | UtkarshPathrabe/Competitive-Coding | ba322fbb1b88682d56a9b80bdd92a853f1caa84e | [
"MIT"
] | null | null | null | HackerRank Solutions/C++/STL/Sets-STL.cpp | UtkarshPathrabe/Competitive-Coding | ba322fbb1b88682d56a9b80bdd92a853f1caa84e | [
"MIT"
] | 3 | 2021-08-24T16:06:22.000Z | 2021-09-17T15:39:53.000Z | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <set>
#include <algorithm>
using namespace std;
int main() {
set<int> Set;
set<int>::iterator it;
int Q, y, x;
scanf("%d", &Q);
for (int i = 0; i < Q; i++) {
scanf("%d %d", &y, &x);
if (y == 1) {
Set.insert(x);
} else if (y == 2) {
Set.erase(x);
} else if (y == 3) {
it = Set.find(x);
if (it == Set.end()) {
printf("No\n");
} else {
printf("Yes\n");
}
}
}
return 0;
}
| 19.5 | 34 | 0.400641 |
bbda486237cfc47243b3368e168b444f0844ff77 | 441 | cpp | C++ | Src/common/utils/AppWriter.cpp | JerryYan97/PD_PN_DataGenerators | 14ccc5abd183576305c5f6a05c793fba9a510cc6 | [
"MIT"
] | null | null | null | Src/common/utils/AppWriter.cpp | JerryYan97/PD_PN_DataGenerators | 14ccc5abd183576305c5f6a05c793fba9a510cc6 | [
"MIT"
] | null | null | null | Src/common/utils/AppWriter.cpp | JerryYan97/PD_PN_DataGenerators | 14ccc5abd183576305c5f6a05c793fba9a510cc6 | [
"MIT"
] | null | null | null | //
// Created by jiaruiyan on 1/19/21.
//
#include "AppWriter.h"
#include <igl/writeOBJ.h>
void AppWriter::write_anim_seq(int frame_id, std::string& filename,
Eigen::MatrixXd& X, Eigen::MatrixXi& BTri){
// Fill the boundary structure -- it should also have a wiser way to output used X and BTri.
// Output to .obj file
std::string obj_path = "./Data/PNData/tmp.obj";
igl::writeOBJ(obj_path, X, BTri);
}
| 29.4 | 96 | 0.653061 |
bbdd1c2c1435f0fe5ac925a4c85998505813e3aa | 53 | cpp | C++ | HttpFramework/HttpCookieStorage.cpp | a1q123456/HttpFramework | debefffbb1283ae0f0277cc1b597237933bb47f7 | [
"MIT"
] | null | null | null | HttpFramework/HttpCookieStorage.cpp | a1q123456/HttpFramework | debefffbb1283ae0f0277cc1b597237933bb47f7 | [
"MIT"
] | null | null | null | HttpFramework/HttpCookieStorage.cpp | a1q123456/HttpFramework | debefffbb1283ae0f0277cc1b597237933bb47f7 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "HttpCookieStorage.h"
| 10.6 | 30 | 0.735849 |
bbde255d3ee786dd9769151baaf8467fd96095d5 | 8,793 | cpp | C++ | src/main.cpp | JimothyJohn/uServer | 11e4db58f9a957f4603eb6c8454ba1f8214de2be | [
"MIT"
] | 1 | 2021-01-24T01:20:00.000Z | 2021-01-24T01:20:00.000Z | src/main.cpp | JimothyJohn/uServer | 11e4db58f9a957f4603eb6c8454ba1f8214de2be | [
"MIT"
] | null | null | null | src/main.cpp | JimothyJohn/uServer | 11e4db58f9a957f4603eb6c8454ba1f8214de2be | [
"MIT"
] | null | null | null |
// Load relevant libraries
#include <Arduino.h> //Base framework
#include <ESP_WiFiManager.h> // AP login and maintenance
#include <AsyncTCP.h> // Generic async library
#include <ESPAsyncWebServer.h> // ESP32 async library
#include <ArduinoOTA.h> // Enable OTA updates
#include <ESPmDNS.h> // Connect by hostname
#include <SPIFFS.h> // Enable file system
#include <PubSubClient.h> // Enable MQTT
#include <ArduinoJson.h> // Handle JSON messages
// Variables for "Digital I/O" page, change to match your configuration
const uint8_t buttonPin = 2; // the number of the pushbutton pin
const uint8_t ledPin = 13; // the number of the LED pin
String outputState = "None"; // output state
// Variables for "Variables" example, change to match your configuration
String postMsg = "None";
// Variables for "MQTT" example, change to match your configuration
String pubMsg = "None";
String pubTopic = "None";
String subTopic = "None";
// Library classes
AsyncWebServer server(80);
WiFiClient espClient;
PubSubClient client(espClient);
StaticJsonDocument<200> doc;
void notFound(AsyncWebServerRequest *request) {
request->send(404, "text/plain", "Not found");
}
// SPIFFS uses processor to replace HTML text with variables
String processor(const String& var) {
if(var == "INPUT_NUMBER") { return String(buttonPin); }
if(var == "INPUT_STATE") { return String(digitalRead(buttonPin)); }
if(var == "OUTPUT_NUMBER") { return String(ledPin); }
if(var == "OUTPUT_STATE") { return outputState; }
if(var == "POST_INT") { return postMsg; }
}
// Set up server callback functions
void SetupServer() {
Serial.print('Configuring webserver...');
// Index/home page
server.on("^\/$|^(\/index\.html)$", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(SPIFFS, "/index.html");
});
// Route to load style.css file
server.on("/style.css", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(SPIFFS, "/style.css", "text/css");
});
// Route to load script.js file
server.on("/script.js", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(SPIFFS, "/script.js", "text/js");
});
// Route to load I/O page
server.on("^\/io$|^(\/io\.html)$", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(SPIFFS, "/io.html", String(), false, processor);
});
// Send a POST request to <IP>/post with a form field message set to <message>
server.on("^\/io$", HTTP_POST, [](AsyncWebServerRequest *request){
if (request->hasParam("output", true)) {
outputState = request->getParam("output", true)->value();
}
request->send(SPIFFS, "/io.html", String(), false, processor);
});
server.on("^\/web$|^(\/web\.html)$", HTTP_GET, [] (AsyncWebServerRequest *request) {
request->send(SPIFFS, "/web.html", String(), false, processor);
});
// Route to load variable page
server.on("^\/variables$|^(\/variables\.html)$", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(SPIFFS, "/variables.html", String(), false, processor);
});
// Route to load variable page
server.on("^\/mqtt$|^(\/mqtt\.html)$", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(SPIFFS, "/mqtt.html", String(), false, processor);
});
server.on("^\/variables$", HTTP_POST, [](AsyncWebServerRequest *request){
if (request->hasParam("postInt", true)) {
postMsg = request->getParam("postInt", true)->value();
}
request->send(SPIFFS, "/variables.html", String(), false, processor);
});
server.on("^\/mqtt\/pub$", HTTP_POST, [](AsyncWebServerRequest *request){
if (request->hasParam("pubmsg", true)) {
pubMsg = request->getParam("pubmsg", true)->value();
} else {
Serial.println('No message entered');
return;
}
if (request->hasParam("pubtopic", true)) {
pubTopic = request->getParam("pubtopic", true)->value();
} else {
Serial.println('No topic entered');
return;
}
bool published = client.publish(pubTopic.c_str(), pubMsg.c_str());
if(!published) { Serial.println('Failed to publish!'); }
request->send(SPIFFS, "/mqtt.html", String(), false, processor);
});
server.on("^\/mqtt\/sub$", HTTP_POST, [](AsyncWebServerRequest *request){
if (request->hasParam("subtopic", true)) {
subTopic = request->getParam("subtopic", true)->value();
bool subscribed = client.subscribe(subTopic.c_str());
if(!subscribed) { Serial.println('Failed to subscribe!'); }
} else { return; }
request->send(SPIFFS, "/mqtt.html", String(), false, processor);
});
server.onNotFound(notFound);
server.begin();
}
// Enable OTA updates
void SetupOTA() {
Serial.print('Configuring OTA...');
ArduinoOTA
.onStart([]() {
String type;
if (ArduinoOTA.getCommand() == U_FLASH)
type = "sketch";
else // U_SPIFFS
type = "filesystem";
// NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
Serial.println("Start updating " + type);
})
.onEnd([]() {
Serial.println("\nEnd");
})
.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
})
.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
else if (error == OTA_END_ERROR) Serial.println("End Failed");
ESP.restart();
});
ArduinoOTA.begin();
}
// Initialize Wi-Fi manager and connect to Wi-Fi
// https://github.com/khoih-prog/ESP_WiFiManager
void SetupWiFi() {
Serial.print('Configuring WiFi...');
Serial.print(F("\nStarting AutoConnect_ESP32_minimal on ")); Serial.println(ARDUINO_BOARD);
Serial.println(ESP_WIFIMANAGER_VERSION);
ESP_WiFiManager wm("uServer");
wm.autoConnect("uServer");
if (WiFi.status() == WL_CONNECTED) {
Serial.print(F("Connected. Local IP: "));
Serial.println(WiFi.localIP());
}
else {
Serial.println(wm.getStatus(WiFi.status()));
}
}
// MQTT Handling functions
// https://github.com/knolleary/pubsubclient/blob/master/examples/mqtt_basic/mqtt_basic.ino
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
char message[length + 1];
strncpy(message, (char*)payload, length);
message[length] = '\0';
DeserializationError error = deserializeJson(doc, message);
if (error) {
Serial.println(error.f_str());
return;
}
//const char* current_time = doc["time"];
Serial.print("Message: ");
Serial.println(message);
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP32-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("/home/status/esp32", "Hello world!");
// ... and resubscribe
client.subscribe("/home/status/time");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
// Initialize and setup MQTT client then connect
// https://pubsubclient.knolleary.net/
void SetupMQTT() {
client.setServer("192.168.1.45",1883);
client.setCallback(callback);
reconnect();
}
// Setup sequence
void setup() {
delay(5000); // pwrLevel-up safety delay
// Start serial server and connect to WiFi
Serial.begin(115200);
while (!Serial);
Serial.print('Serial alive!');
// Uses soft AP to connect to Wi-Fi (if saved credentials aren't valid)
SetupWiFi();
// Configures Async web server
SetupServer();
// Configures over-the-air updates
SetupOTA();
// mDNS allows for connection at http://userver.local/
if(!MDNS.begin("userver")) {
Serial.println("Error starting mDNS!");
ESP.restart();
}
// Initialize SPIFFS
if(!SPIFFS.begin(true)) {
Serial.println("An error has occurred while mounting SPIFFS");
ESP.restart();
}
// Subscribe to home MQTT broker
SetupMQTT();
pinMode(ledPin, OUTPUT); // initialize the LED pin as an output:
pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input:
}
// Main loop
void loop() {
ArduinoOTA.handle();
if (!client.connected()) { reconnect(); }
else { client.loop(); }
}
| 32.932584 | 96 | 0.657227 |
bbe130758cf8f984e00194113eb3eb9b908ba256 | 7,001 | hpp | C++ | include/CPreProcessor.hpp | icebreakersentertainment/ice_engine | 52a8313bc266c053366bdf554b5dc27a54ddcb25 | [
"MIT"
] | null | null | null | include/CPreProcessor.hpp | icebreakersentertainment/ice_engine | 52a8313bc266c053366bdf554b5dc27a54ddcb25 | [
"MIT"
] | null | null | null | include/CPreProcessor.hpp | icebreakersentertainment/ice_engine | 52a8313bc266c053366bdf554b5dc27a54ddcb25 | [
"MIT"
] | 1 | 2019-06-11T03:41:48.000Z | 2019-06-11T03:41:48.000Z | #ifndef CPREPROCESSOR_H
#define CPREPROCESSOR_H
#if !defined(BOOST_WAVE_CUSTOM_DIRECTIVES_HOOKS_INCLUDED)
#define BOOST_WAVE_CUSTOM_DIRECTIVES_HOOKS_INCLUDED
#include <cstdio>
#include <iostream>
#include <ostream>
#include <string>
#include <algorithm>
#include <utility>
#include <unordered_map>
#include <boost/algorithm/string.hpp>
#include <boost/assert.hpp>
#include <boost/config.hpp>
// Need to include this before other wave/phoenix includes
// @see https://groups.google.com/forum/#!msg/boost-list/3xZDWUyTJG0/IEF2wTy1EIsJ
#include <boost/phoenix/core/limits.hpp>
#include <boost/wave/token_ids.hpp>
#include <boost/wave/util/macro_helpers.hpp>
#include <boost/wave/preprocessing_hooks.hpp>
#include <boost/wave/cpp_iteration_context.hpp>
#include <iterator>
#include <fstream>
#if defined(BOOST_NO_TEMPLATED_ITERATOR_CONSTRUCTORS)
#include <sstream>
#endif
#include <boost/wave/wave_config.hpp>
#include <boost/wave/cpp_exceptions.hpp>
#include <boost/wave/language_support.hpp>
#include <boost/wave/util/file_position.hpp>
#include "Types.hpp"
#include "fs/IFileSystem.hpp"
#include "logger/ILogger.hpp"
namespace wave = boost::wave;
namespace alg = boost::algorithm;
namespace ice_engine
{
/**
* This class is a generic pre processor for C like code.
*/
class CPreProcessor : public wave::context_policies::default_preprocessing_hooks
{
public:
CPreProcessor(fs::IFileSystem* fileSystem, logger::ILogger* logger, const std::unordered_map<std::string, std::string>& includeOverrides = {});
/**
* Processess the source code.
*
* @param defineMap this is an optional map that can contain any extra/special #defines that have been
* defined.
*/
std::string process(std::string source, const std::unordered_map<std::string, std::string>& defineMap = {}, const bool autoIncludeGuard = false, const bool preserveLineNumbers = false);
/* Below is a bunch of Boost Wave call-back functions */
template <typename ContextT, typename ContainerT>
bool found_unknown_directive(ContextT const& ctx, ContainerT const& line, ContainerT& pending);
template <typename ContextT, typename ContainerT>
bool emit_line_directive(ContextT const & ctx, ContainerT & pending, typename ContextT::token_type const & act_token);
template <typename ContextT>
bool locate_include_file(ContextT& ctx, std::string&file_path, bool is_system, char const*current_name, std::string&dir_path, std::string&native_name);
template <typename ContextT>
void opened_include_file(ContextT const& ctx, std::string const& relname, std::string const& filename, bool is_system_include);
template <typename ContextT>
void returning_from_include_file(ContextT const& ctx);
template <typename ContextT>
bool found_include_directive(ContextT const& ctx, std::string const& filename, bool include_next);
template <typename ContextT, typename TokenT>
void
skipped_token(ContextT const& ctx, TokenT const& token);
template <typename ContextT, typename TokenT>
TokenT const& generated_token(ContextT const &ctx, TokenT const& token);
template <typename ContextT, typename TokenT, typename ContainerT>
bool evaluated_conditional_expression(
ContextT const &ctx, TokenT const& directive,
ContainerT const& expression, bool expression_value);
template <typename ContextT, typename TokenT>
bool found_directive(ContextT const& ctx, TokenT const& directive);
/**
* Inner class to do the loading of a file.
*/
template <typename IterContextT>
class inner {
public:
template <typename PositionT>
static void init_iterators(IterContextT& iter_ctx, PositionT const& act_pos, wave::language_support language)
{
typedef typename IterContextT::iterator_type iterator_type;
// std::cout << "init_iterators: " << iter_ctx.filename << std::endl;
const auto filename = std::string(iter_ctx.filename.c_str());
{
const auto it = CPreProcessor::staticIncludeOverrides_.find(filename);
if (it != CPreProcessor::staticIncludeOverrides_.end())
{
iter_ctx.instring = it->second;
} else
{
iter_ctx.instring = CPreProcessor::staticFileSystem_->readAll(filename);
}
}
// read in the file
// std::ifstream instream(iter_ctx.filename.c_str());
// if ( !instream.is_open())
// {
//// BOOST_WAVE_THROW_CTX(iter_ctx.ctx, wave::preprocess_exception, wave::bad_include_file, iter_ctx.filename.c_str(), act_pos);
// return;
// }
// instream.unsetf(std::ios::skipws);
//
// iter_ctx.instring.assign(
// std::istreambuf_iterator<char>(instream.rdbuf()),
// std::istreambuf_iterator<char>()
// );
// ensure our input string ends with a newline (if we don't then boost wave generates a newline token after the include directive finishes)
auto it = iter_ctx.instring.end();
if (*(--it) != *boost::wave::get_token_value(boost::wave::T_NEWLINE))
{
iter_ctx.instring += boost::wave::get_token_value(boost::wave::T_NEWLINE);
}
iter_ctx.first = iterator_type(
iter_ctx.instring.begin(),
iter_ctx.instring.end(),
PositionT(iter_ctx.filename),
language
);
iter_ctx.last = iterator_type();
}
private:
std::string instring;
};
private:
protected:
bool preserveLineNumbers_ = false;
bool autoIncludeGuard_ = false;
uint32 conditionalDepth_ = 0;
uint32 conditionalAllowNewlineDepth_ = 0;
bool inDefine_ = false;
uint32 numIncludes_ = 0;
std::unordered_map<std::string, bool> includedFiles_;
std::unordered_map<std::string, std::string> includeOverrides_;
fs::IFileSystem* fileSystem_;
logger::ILogger* logger_;
static std::unordered_map<std::string, std::string> staticIncludeOverrides_;
static fs::IFileSystem* staticFileSystem_;
static logger::ILogger* staticLogger_;
/*
* We make this a shared pointer so that when the context object makes a copy of `this`,
* it will be using the same outputStringStream_.
*/
std::shared_ptr<std::stringstream> outputStringStream_;
bool locateIncludeFile(const std::string& currentDirectory, /*const std::string& basePath,*/ std::string& filePath, bool isSystem, char const* currentName, std::string& dirPath, std::string& nativeName);
std::string toCanonicalPath(const std::string& currentDirectory, const std::string& filename);
};
}
#include "CPreProcessor.inl"
#endif // !defined(BOOST_WAVE_ADVANCED_PREPROCESSING_HOOKS_INCLUDED)
#endif /* CPREPROCESSOR_H */ | 35.180905 | 207 | 0.682474 |
bbe2cb86a39c0e9f769e98353c3d5a8c69a8506b | 920 | cpp | C++ | SE/Source/Maths/Vector4D.cpp | NahuCF/SE | 6b17be4bc05b114a9090da35756a587693cc00e5 | [
"WTFPL"
] | 1 | 2021-04-23T14:53:42.000Z | 2021-04-23T14:53:42.000Z | SE/Source/Maths/Vector4D.cpp | NahuCF/SE | 6b17be4bc05b114a9090da35756a587693cc00e5 | [
"WTFPL"
] | null | null | null | SE/Source/Maths/Vector4D.cpp | NahuCF/SE | 6b17be4bc05b114a9090da35756a587693cc00e5 | [
"WTFPL"
] | null | null | null | #include "pch.h"
#include "Vector4D.h"
namespace lptm {
Vector4D::Vector4D()
{
x = 0.0f;
y = 0.0f;
z = 0.0f;
w = 0.0f;
};
Vector4D::Vector4D(float x, float y, float z, float w)
{
this->x = x;
this->y = y;
this->z = z;
this->w = w;
}
Vector4D& Vector4D::Add(const Vector4D& other)
{
x += other.x;
y += other.y;
z += other.z;
w += other.w;
return *this;
}
Vector4D& Vector4D::Multiply(const Vector4D& other)
{
return *this;
}
Vector4D Vector4D::operator+(const Vector4D& other)
{
return Vector4D(x + other.x, y + other.y, z + other.z, w + other.w);
}
Vector4D& Vector4D::operator+=(const Vector4D& other)
{
x += other.x;
y += other.y;
z += other.z;
w += other.w;
return *this;
}
Vector4D Vector4D::operator*(const Vector4D& other)
{
return Multiply(other);
}
Vector4D& Vector4D::operator*=(const Vector4D& other)
{
return Multiply(other);
}
} | 14.83871 | 70 | 0.596739 |
bbe35a73de57f0577e102744972e21562c62f203 | 6,586 | cpp | C++ | cpp/src/msg_server/FileServConn.cpp | KevinHM/TTServer | c3a8dcb7e0d2dd0d3fc88ff919019ca5f0a81306 | [
"Apache-2.0"
] | 22 | 2015-05-02T11:21:32.000Z | 2022-03-04T09:58:19.000Z | cpp/src/msg_server/FileServConn.cpp | luyongfugx/TTServer | c3a8dcb7e0d2dd0d3fc88ff919019ca5f0a81306 | [
"Apache-2.0"
] | null | null | null | cpp/src/msg_server/FileServConn.cpp | luyongfugx/TTServer | c3a8dcb7e0d2dd0d3fc88ff919019ca5f0a81306 | [
"Apache-2.0"
] | 21 | 2015-01-02T01:21:04.000Z | 2021-05-12T09:52:54.000Z | //
// FileServConn.cpp
// public_TTServer
//
// Created by luoning on 14-8-19.
// Copyright (c) 2014年 luoning. All rights reserved.
//
#include "FileServConn.h"
#include "FileHandler.h"
#include "util.h"
#include "ImUser.h"
#include "AttachData.h"
#include "RouteServConn.h"
#include "MsgConn.h"
static ConnMap_t g_file_server_conn_map;
static serv_info_t* g_file_server_list;
static uint32_t g_file_server_count;
static CFileHandler* s_file_handler = NULL;
void file_server_conn_timer_callback(void* callback_data, uint8_t msg, uint32_t handle, void* pParam)
{
ConnMap_t::iterator it_old;
CFileServConn* pConn = NULL;
uint64_t cur_time = get_tick_count();
for (ConnMap_t::iterator it = g_file_server_conn_map.begin(); it != g_file_server_conn_map.end();
)
{
it_old = it;
it++;
pConn = (CFileServConn*)it_old->second;
pConn->OnTimer(cur_time);
}
// reconnect FileServer
serv_check_reconnect<CFileServConn>(g_file_server_list, g_file_server_count);
}
void init_file_serv_conn(serv_info_t* server_list, uint32_t server_count)
{
g_file_server_list = server_list;
g_file_server_count = server_count;
serv_init<CFileServConn>(g_file_server_list, g_file_server_count);
netlib_register_timer(file_server_conn_timer_callback, NULL, 1000);
s_file_handler = CFileHandler::getInstance();
}
bool is_file_server_available()
{
CFileServConn* pConn = NULL;
for (uint32_t i = 0; i < g_file_server_count; i++) {
pConn = (CFileServConn*)g_file_server_list[i].serv_conn;
if (pConn && pConn->IsOpen()) {
return true;
}
}
return false;
}
//
CFileServConn* get_random_file_serv_conn()
{
CFileServConn* pConn = NULL;
CFileServConn* pConnTmp = NULL;
if (0 == g_file_server_count) {
return pConn;
}
int32_t random_num = rand() % g_file_server_count;
pConnTmp = (CFileServConn*)g_file_server_list[random_num].serv_conn;
if (pConnTmp && pConnTmp->IsOpen())
{
pConn = pConnTmp;
}
else
{
for (uint32_t i = 0; i < g_file_server_count; i++)
{
int j = (random_num + 1) % g_file_server_count;
pConnTmp = (CFileServConn*)g_file_server_list[j].serv_conn;
if (pConnTmp && pConnTmp->IsOpen())
{
pConn = pConnTmp;
}
}
}
return pConn;
}
CFileServConn::CFileServConn()
{
m_bOpen = false;
m_serv_idx = 0;
}
CFileServConn::~CFileServConn()
{
}
void CFileServConn::Connect(const char* server_ip, uint16_t server_port, uint32_t idx)
{
log("Connecting to FileServer %s:%d\n", server_ip, server_port);
m_serv_idx = idx;
m_handle = netlib_connect(server_ip, server_port, imconn_callback, (void*)&g_file_server_conn_map);
if (m_handle != NETLIB_INVALID_HANDLE) {
g_file_server_conn_map.insert(make_pair(m_handle, this));
}
}
void CFileServConn::Close()
{
serv_reset<CFileServConn>(g_file_server_list, g_file_server_count, m_serv_idx);
m_bOpen = false;
if (m_handle != NETLIB_INVALID_HANDLE) {
netlib_close(m_handle);
g_file_server_conn_map.erase(m_handle);
}
ReleaseRef();
}
void CFileServConn::OnConfirm()
{
log("connect to file server success\n");
m_bOpen = true;
m_connect_time = get_tick_count();
g_file_server_list[m_serv_idx].reconnect_cnt = MIN_RECONNECT_CNT / 2;
CImPduFileServerIPReq pdu;
//SendPdu(&pdu);
}
void CFileServConn::OnClose()
{
log("onclose from file server handle=%d\n", m_handle);
Close();
}
void CFileServConn::OnTimer(uint64_t curr_tick)
{
if (curr_tick > m_last_send_tick + SERVER_HEARTBEAT_INTERVAL) {
CImPduHeartbeat pdu;
SendPdu(&pdu);
}
if (curr_tick > m_last_recv_tick + SERVER_TIMEOUT) {
log("conn to file server timeout\n");
Close();
}
}
void CFileServConn::HandlePdu(CImPdu* pPdu)
{
switch (pPdu->GetPduType()) {
case IM_PDU_TYPE_HEARTBEAT:
break;
case IM_PDU_TYPE_MSG_FILE_TRANSFER_RSP:
_HandleFileMsgTransRsp((CImPduMsgFileTransferRsp*) pPdu);
break;
case IM_PDU_TYPE_FILE_SERVER_IP_REQUEST:
_HandleFileServerIPRsp((CImPduFileServerIPRsp*)pPdu);
break;
default:
log("unknown pdu_type=%d\n", pPdu->GetPduType());
break;
}
}
void CFileServConn::_HandleFileMsgTransRsp(CImPduMsgFileTransferRsp* pPdu)
{
uint32_t result = pPdu->GetResult();
uint32_t from_id = pPdu->GetFromId();
uint32_t to_id = pPdu->GetToId();
string file_name(pPdu->GetFileName(), pPdu->GetFileNameLength());
uint32_t file_size = pPdu->GetFileLength();
string listen_ip(pPdu->GetFileServerIp(), pPdu->GetFileServerIpLength());
uint16_t listen_port = pPdu->GetFileServerPort();
string task_id(pPdu->GetTaskId(), pPdu->GetTaskIdLen());
CPduAttachData attach(pPdu->GetAttachData(), pPdu->GetAttachLen());
CImPduClientFileResponse pdu(result, idtourl(from_id), idtourl(to_id), file_name.c_str(),
task_id.c_str(), listen_ip.c_str(), listen_port);
pdu.SetReserved(pPdu->GetReserved());
uint32_t handle = attach.GetHandle();
log("HandleFileMsgTransRsp, result: %u, from_user_id: %u, to_user_id: %u, file_name: %s, \
task_id: %s, listen_ip: %s, listen_port: %u.\n", result, from_id, to_id, file_name.c_str(),
task_id.c_str(), listen_ip.c_str(), listen_port);
CMsgConn* pFromConn = CImUserManager::GetInstance()->GetMsgConnByHandle(from_id, handle);
if (pFromConn)
{
pFromConn->SendPdu(&pdu);
}
if (result == 0)
{
//send notify to target user
CImUser* pToUser = CImUserManager::GetInstance()->GetImUserById(to_id);
if (pToUser)
{
CImPduClientFileNotify pdu2(idtourl(from_id), idtourl(to_id), file_name.c_str(), file_size,
task_id.c_str(), listen_ip.c_str(), listen_port);
pToUser->BroadcastPdu(&pdu2);
}
//send to route server
CRouteServConn* pRouteConn = get_route_serv_conn();
if (pRouteConn) {
CImPduFileNotify pdu3(from_id, to_id, file_name.c_str(), file_size, task_id.c_str(),
listen_ip.c_str(), listen_port);
pRouteConn->SendPdu(&pdu3);
}
}
}
void CFileServConn::_HandleFileServerIPRsp(CImPduFileServerIPRsp* pPdu)
{
uint32_t ip_addr_cnt = pPdu->GetIPCnt();
ip_addr_t* ip_addr_list = pPdu->GetIPList();
for (uint32_t i = 0; i < ip_addr_cnt ; i++) {
m_ip_list.push_back(ip_addr_list[i]);
}
} | 28.387931 | 103 | 0.669602 |
bbeb3552b80935887cbfb333214abf80ac19950b | 21,059 | hpp | C++ | polympc/src/solvers/admm.hpp | alexandreguerradeoliveira/rocket_gnc | 164e96daca01d9edbc45bfaac0f6b55fe7324f24 | [
"MIT"
] | null | null | null | polympc/src/solvers/admm.hpp | alexandreguerradeoliveira/rocket_gnc | 164e96daca01d9edbc45bfaac0f6b55fe7324f24 | [
"MIT"
] | null | null | null | polympc/src/solvers/admm.hpp | alexandreguerradeoliveira/rocket_gnc | 164e96daca01d9edbc45bfaac0f6b55fe7324f24 | [
"MIT"
] | null | null | null | // This file is part of PolyMPC, a lightweight C++ template library
// for real-time nonlinear optimization and optimal control.
//
// Copyright (C) 2020 Listov Petr <petr.listov@epfl.ch>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef ADMM_HPP
#define ADMM_HPP
#include "qp_base.hpp"
template<int N, int M, typename Scalar = double, int MatrixType = DENSE,
template <typename, int, typename... Args> class LinearSolver = linear_solver_traits<DENSE>::default_solver,
int LinearSolver_UpLo = Eigen::Lower, typename ...Args>
class ADMM : public QPBase<ADMM<N, M, Scalar, MatrixType, LinearSolver, LinearSolver_UpLo>, N, M, Scalar, MatrixType, LinearSolver, LinearSolver_UpLo>
{
using Base = QPBase<ADMM<N, M, Scalar, MatrixType, LinearSolver, LinearSolver_UpLo>, N, M, Scalar, MatrixType, LinearSolver, LinearSolver_UpLo>;
public:
using scalar_t = typename Base::scalar_t;
using qp_var_t = typename Base::qp_var_t;
using qp_dual_t = typename Base::qp_dual_t;
using qp_dual_a_t = typename Base::qp_dual_a_t;
using qp_constraint_t = typename Base::qp_constraint_t;
using qp_hessian_t = typename Base::qp_hessian_t;
/** specific for OSQP splitting */
using kkt_mat_t = typename std::conditional<MatrixType == SPARSE, Eigen::SparseMatrix<scalar_t>,
typename dense_matrix_type_selector<scalar_t, 2 * N + M, 2 * N + M>::type>::type;
using kkt_vec_t = typename dense_matrix_type_selector<scalar_t, 2 * N + M, 1>::type;
using linear_solver_t = LinearSolver<kkt_mat_t, LinearSolver_UpLo, Args...>; //typename Base::linear_solver_t;
using admm_dual_t = typename dense_matrix_type_selector<scalar_t, N + M, 1>::type;
using admm_constraint_t = typename std::conditional<MatrixType == SPARSE, Eigen::SparseMatrix<scalar_t>,
typename dense_matrix_type_selector<scalar_t, N + M, N>::type>::type;
template<int MatrixFMT = MatrixType>
EIGEN_STRONG_INLINE typename std::enable_if<MatrixFMT == DENSE>::type allocate_kkt_matrix() noexcept
{
if(m_K.RowsAtCompileTime == Eigen::Dynamic) m_K = kkt_mat_t::Zero(2 * N + M, 2 * N + M);
}
/** no pre-allocate needed for sparse KKT system */
template<int MatrixFMT = MatrixType>
EIGEN_STRONG_INLINE typename std::enable_if<MatrixFMT == SPARSE>::type allocate_kkt_matrix() const noexcept
{}
template<int MatrixFMT = MatrixType>
EIGEN_STRONG_INLINE typename std::enable_if<MatrixFMT == DENSE>::type allocate_jacobian() noexcept
{
if(m_A.RowsAtCompileTime == Eigen::Dynamic) m_A = admm_constraint_t::Zero(N + M, N);
}
template<int MatrixFMT = MatrixType>
EIGEN_STRONG_INLINE typename std::enable_if<MatrixFMT == SPARSE>::type allocate_jacobian() const noexcept
{}
public:
ADMM() : Base()
{
/** intialise some variables */
m_rho_vec = admm_dual_t::Constant(this->m_settings.rho);
m_rho_inv_vec = admm_dual_t::Constant(scalar_t(1/this->m_settings.rho));
/** allocate space for the KKT matrix if necessary */
allocate_kkt_matrix();
/** allocate memory for Jacobian */
allocate_jacobian();
}
~ADMM() = default;
/** ADMM specific */
qp_var_t m_x_tilde;
admm_dual_t m_z, m_z_tilde, m_z_prev;
admm_dual_t m_rho_vec, m_rho_inv_vec;
scalar_t rho;
int iter{0};
scalar_t res_prim;
scalar_t res_dual;
/** ADMM specific */
static constexpr scalar_t RHO_MIN = 1e-6;
static constexpr scalar_t RHO_MAX = 1e+6;
static constexpr scalar_t RHO_TOL = 1e-4;
static constexpr scalar_t RHO_EQ_FACTOR = 1e+3;
/** ADMM specific */
scalar_t m_max_Ax_z_norm;
scalar_t m_max_Hx_ATy_h_norm;
/** solver part */
kkt_mat_t m_K;
admm_constraint_t m_A;
linear_solver_t linear_solver;
Eigen::VectorXi _kkt_mat_nnz, _A_mat_nnz;
status_t solve_impl(const Eigen::Ref<const qp_hessian_t>& H, const Eigen::Ref<const qp_var_t>& h, const Eigen::Ref<const qp_constraint_t>& A,
const Eigen::Ref<const qp_dual_a_t>& Alb, const Eigen::Ref<const qp_dual_a_t>& Aub,
const Eigen::Ref<const qp_var_t>& xl, const Eigen::Ref<const qp_var_t>& xu) noexcept
{
return solve_impl(H, h, A, Alb, Aub, xl, xu, qp_var_t::Zero(N,1), qp_dual_t::Zero(M+N,1));
}
status_t solve_impl(const Eigen::Ref<const qp_hessian_t>& H, const Eigen::Ref<const qp_var_t>& h, const Eigen::Ref<const qp_constraint_t>& A,
const Eigen::Ref<const qp_dual_a_t>& Alb, const Eigen::Ref<const qp_dual_a_t>& Aub,
const Eigen::Ref<const qp_var_t>& xl, const Eigen::Ref<const qp_var_t>& xu,
const Eigen::Ref<const qp_var_t>& x_guess, const Eigen::Ref<const qp_dual_t>& y_guess) noexcept
{
/** setup part */
kkt_vec_t rhs, x_tilde_nu;
bool check_termination = false;
this->m_x = x_guess;
this->m_y = y_guess;
/** @bug : create Sparse m_A matrix */
construct_A(A);
this->m_z.noalias() = m_A * x_guess;
/** Set QP constraint type */
this->parse_constraints_bounds(Alb, Aub, xl, xu);
/** initialize step size (rho) vector */
rho_vec_update(this->m_settings.rho);
/** construct KKT matrix (m_K) and compute decomposition */
construct_kkt_matrix(H, m_A);
factorise_kkt_matrix();
this->m_info.status = UNSOLVED;
/** run ADMM iterations */
for (iter = 1; iter <= this->m_settings.max_iter; iter++)
{
m_z_prev = m_z;
/** update x_tilde z_tilde */
compute_kkt_rhs(h, rhs);
x_tilde_nu = linear_solver.solve(rhs);
m_x_tilde = x_tilde_nu.template head<N>();
m_z_tilde = m_z_prev + m_rho_inv_vec.cwiseProduct(x_tilde_nu.template tail<M + N>() - this->m_y);
/** update x */
this->m_x.noalias() = this->m_settings.alpha * m_x_tilde + (1 - this->m_settings.alpha) * this->m_x;
/** update z */
m_z.noalias() = this->m_settings.alpha * m_z_tilde;
m_z.noalias() += (1 - this->m_settings.alpha) * m_z_prev + m_rho_inv_vec.cwiseProduct(this->m_y);
box_projection(m_z, Alb, Aub, xl, xu); // euclidean projection
/** update y (dual) */
this->m_y.noalias() += m_rho_vec.cwiseProduct(this->m_settings.alpha * m_z_tilde +
(1 - this->m_settings.alpha) * m_z_prev - m_z);
if (this->m_settings.check_termination != 0 && iter % this->m_settings.check_termination == 0)
check_termination = true;
else
check_termination = false;
/** check convergence */
if (check_termination)
{
residuals_update(H, h, A);
if (termination_criteria())
{
this->m_info.status = SOLVED;
break;
}
}
if (this->m_settings.adaptive_rho && iter % this->m_settings.adaptive_rho_interval == 0)
{
// state was not yet updated
if (!check_termination)
residuals_update(H, h, A);
/** adjust rho value and refactorise the KKT matrix */
scalar_t new_rho = estimate_rho(rho);
new_rho = fmax(RHO_MIN, fmin(new_rho, RHO_MAX));
this->m_info.rho_estimate = new_rho;
if (new_rho < rho / this->m_settings.adaptive_rho_tolerance ||
new_rho > rho * this->m_settings.adaptive_rho_tolerance)
{
rho_vec_update(new_rho);
update_kkt_rho();
/* Note: KKT Sparsity pattern unchanged by rho update. Only factorize. */
factorise_kkt_matrix();
}
}
/**
std::cout << "admm iter: " << iter << " | " << this->m_x.transpose() << " | " << this->m_y.transpose() <<
" | " << this->m_info.res_prim << " | " << this->m_info.res_dual << " | " << m_rho_vec.transpose() << "\n";
*/
}
if (iter > this->m_settings.max_iter)
this->m_info.status = MAX_ITER_EXCEEDED;
this->m_info.iter = iter;
return this->m_info.status;
}
/** construct extended A matrix: Ae = [A E] */
template<int T = MatrixType>
EIGEN_STRONG_INLINE typename std::enable_if<T == DENSE>::type
construct_A(const Eigen::Ref<const qp_constraint_t>& A) noexcept
{
m_A.template block<M, N>(0,0) = A;
m_A.template block<N,N>(M,0).setIdentity();
}
template<int T = MatrixType>
EIGEN_STRONG_INLINE typename std::enable_if<T == SPARSE>::type
construct_A(const Eigen::Ref<const qp_constraint_t>& A) noexcept
{
if(this->settings().reuse_pattern)
{
/** copy the new A block */
for(Eigen::Index k = 0; k < N; ++k)
std::copy_n(A.valuePtr() + A.outerIndexPtr()[k], A.innerNonZeroPtr()[k], m_A.valuePtr() + m_A.outerIndexPtr()[k]);
}
else
{
m_A.resize(N + M, N);
_A_mat_nnz = Eigen::VectorXi::Constant(N, 1); // allocate box constraints
std::transform(_A_mat_nnz.data(), _A_mat_nnz.data() + N, A.innerNonZeroPtr(), _A_mat_nnz.data(), std::plus<scalar_t>());
// reserve the memory
m_A.reserve(_A_mat_nnz);
block_insert_sparse(m_A, 0, 0, A); //insert A matrix
for(Eigen::Index i = 0; i < N; ++i)
m_A.coeffRef(i + M, i) = scalar_t(1); // insert identity matrix
}
}
template<int T = MatrixType>
EIGEN_STRONG_INLINE typename std::enable_if<T == DENSE>::type
construct_kkt_matrix(const Eigen::Ref<const qp_hessian_t>& H, const Eigen::Ref<const admm_constraint_t>& A) noexcept
{
eigen_assert(LinearSolver_UpLo == Eigen::Lower ||
LinearSolver_UpLo == (Eigen::Upper|Eigen::Lower));
m_K.template topLeftCorner<N, N>() = H;
m_K.template topLeftCorner<N, N>().diagonal() += qp_var_t::Constant(N, this->m_settings.sigma);
if (LinearSolver_UpLo == (Eigen::Upper|Eigen::Lower))
m_K.template topRightCorner<N, M + N>() = A.transpose();
m_K.template bottomLeftCorner<M + N, N>() = A;
m_K.template bottomRightCorner<M + N, M + N>() = scalar_t(-1) * m_rho_inv_vec.asDiagonal();
}
/** sparse implementation */
template<int T = MatrixType>
EIGEN_STRONG_INLINE typename std::enable_if<T == SPARSE>::type
construct_kkt_matrix(const Eigen::Ref<const qp_hessian_t>& H, const Eigen::Ref<const admm_constraint_t>& A) noexcept
{
if(this->settings().reuse_pattern)
construct_kkt_matrix_same_pattern(H,A);
else
{
construct_kkt_matrix_sparse(H, A);
linear_solver.analyzePattern(m_K);
}
}
template<int T = MatrixType>
EIGEN_STRONG_INLINE typename std::enable_if<T == SPARSE>::type
construct_kkt_matrix_sparse(const Eigen::Ref<const qp_hessian_t>& H, const Eigen::Ref<const admm_constraint_t>& A) noexcept
{
/** worst case scenario */
const int kkt_size = 2 * N + M;
m_K.resize(kkt_size, kkt_size);
/** estimate number of nonzeros */
_kkt_mat_nnz = Eigen::VectorXi::Constant(kkt_size, 1);
// add nonzeros from H
std::transform(_kkt_mat_nnz.data(), _kkt_mat_nnz.data() + N, H.innerNonZeroPtr(), _kkt_mat_nnz.data(), std::plus<scalar_t>());
// add nonzeros from A
std::transform(_kkt_mat_nnz.data(), _kkt_mat_nnz.data() + N, A.innerNonZeroPtr(), _kkt_mat_nnz.data(), std::plus<scalar_t>());
// reserve the space and insert values from H and A
if(LinearSolver_UpLo == (Eigen::Upper|Eigen::Lower))
{
// reserve more memory
_estimate_nnz_in_row(_kkt_mat_nnz, A);
m_K.reserve(_kkt_mat_nnz);
block_insert_sparse(m_K, 0, 0, H);
block_insert_sparse(m_K, N, 0, A);
block_insert_sparse(m_K, 0, N, A.transpose());
}
else
{
m_K.reserve(_kkt_mat_nnz);
block_insert_sparse(m_K, 0, 0, H);
block_insert_sparse(m_K, N, 0, A);
}
// add diagonal blocks*/
for(Eigen::Index i = 0; i < N; ++i)
m_K.coeffRef(i, i) += this->m_settings.sigma;
for(Eigen::Index i = 0; i < N + M; ++i)
m_K.coeffRef(N + i, N + i) = -m_rho_inv_vec(i);
}
/** make faster update if sparsity pattern has not changed */
template<int T = MatrixType>
EIGEN_STRONG_INLINE typename std::enable_if<T == SPARSE>::type
construct_kkt_matrix_same_pattern(const Eigen::Ref<const qp_hessian_t>& H, const Eigen::Ref<const admm_constraint_t>& A) noexcept
{
/** just copy content of nonzero vectors*/
// copy H and A blocks
for(Eigen::Index k = 0; k < N; ++k)
{
std::copy_n(H.valuePtr() + H.outerIndexPtr()[k], H.innerNonZeroPtr()[k], m_K.valuePtr() + m_K.outerIndexPtr()[k]);
std::copy_n(A.valuePtr() + A.outerIndexPtr()[k], A.innerNonZeroPtr()[k], m_K.valuePtr() + m_K.outerIndexPtr()[k] + H.innerNonZeroPtr()[k]);
}
// reserve the space and insert values from H and A
if(LinearSolver_UpLo == (Eigen::Upper|Eigen::Lower))
block_set_sparse(m_K, N, 0, A.transpose());
// add diagonal blocks*/
m_K.diagonal(). template head<N>() += qp_var_t::Constant(this->m_settings.sigma);
m_K.diagonal(). template tail<M + N>() = -m_rho_inv_vec;
}
template<int T = MatrixType>
EIGEN_STRONG_INLINE typename std::enable_if<T == SPARSE>::type
block_insert_sparse(Eigen::SparseMatrix<scalar_t>& dst, const Eigen::Index &row_offset,
const Eigen::Index &col_offset, const Eigen::SparseMatrix<scalar_t>& src) const noexcept
{
// assumes enough spase is allocated in the dst matrix
for(Eigen::Index k = 0; k < src.outerSize(); ++k)
for (typename Eigen::SparseMatrix<scalar_t>::InnerIterator it(src, k); it; ++it)
dst.insert(row_offset + it.row(), col_offset + it.col()) = it.value();
}
template<int T = MatrixType>
EIGEN_STRONG_INLINE typename std::enable_if<T == SPARSE>::type
block_set_sparse(Eigen::SparseMatrix<scalar_t>& dst, const Eigen::Index &row_offset,
const Eigen::Index &col_offset, const Eigen::SparseMatrix<scalar_t>& src) const noexcept
{
// assumes enough spase is allocated in the dst matrix
for(Eigen::Index k = 0; k < src.outerSize(); ++k)
for (typename Eigen::SparseMatrix<scalar_t>::InnerIterator it(src, k); it; ++it)
dst.insert(row_offset + it.row(), col_offset + it.col()) = it.value();
}
/** workaround function to estimate number of nonzeros */
template<int T = MatrixType>
EIGEN_STRONG_INLINE typename std::enable_if<T == SPARSE>::type
_estimate_nnz_in_row(Eigen::Ref<Eigen::VectorXi> nnz, const qp_constraint_t& A) const noexcept
{
for (Eigen::Index k = 0; k < A.outerSize(); ++k)
for(typename qp_constraint_t::InnerIterator it(A, k); it; ++it)
nnz(it.row() + N) += scalar_t(1);
}
template<int T = MatrixType>
EIGEN_STRONG_INLINE typename std::enable_if<T == DENSE>::type factorise_kkt_matrix() noexcept
{
/** try implace decomposition */
linear_solver.compute(m_K);
eigen_assert(linear_solver.info() == Eigen::Success);
}
template<int T = MatrixType>
EIGEN_STRONG_INLINE typename std::enable_if<T == SPARSE>::type factorise_kkt_matrix() noexcept
{
/** try implace decomposition */
linear_solver.factorize(m_K);
eigen_assert(linear_solver.info() == Eigen::Success);
}
EIGEN_STRONG_INLINE void compute_kkt_rhs(const Eigen::Ref<const qp_var_t>& h, Eigen::Ref<kkt_vec_t> rhs) const noexcept
{
rhs.template head<N>() = this->m_settings.sigma * this->m_x - h;
rhs.template tail<M + N>() = m_z - m_rho_inv_vec.cwiseProduct(this->m_y);
}
EIGEN_STRONG_INLINE void box_projection(Eigen::Ref<admm_dual_t> x, const Eigen::Ref<const qp_dual_a_t>& lba,
const Eigen::Ref<const qp_dual_a_t>& uba,
const Eigen::Ref<const qp_var_t>& lbx, const Eigen::Ref<const qp_var_t>& ubx) const noexcept
{
x.template head<M>() = x.template head<M>().cwiseMax(lba).cwiseMin(uba);
x.template tail<N>() = x.template tail<N>().cwiseMax(lbx).cwiseMin(ubx);
}
EIGEN_STRONG_INLINE void rho_vec_update(const scalar_t& rho0) noexcept
{
for (int i = 0; i < qp_dual_a_t::RowsAtCompileTime; i++)
{
switch (this->constr_type[i])
{
case Base::constraint_type::LOOSE_BOUNDS:
m_rho_vec(i) = RHO_MIN;
break;
case Base::constraint_type::EQUALITY_CONSTRAINT:
m_rho_vec(i) = RHO_EQ_FACTOR * rho0;
break;
case Base::constraint_type::INEQUALITY_CONSTRAINT: /* fall through */
default:
m_rho_vec(i) = rho0;
};
}
/** box constraints */
for (int i = 0; i < qp_var_t::RowsAtCompileTime; i++)
{
switch (this->box_constr_type[i])
{
case Base::constraint_type::LOOSE_BOUNDS:
m_rho_vec(i + M) = RHO_MIN;
break;
case Base::constraint_type::EQUALITY_CONSTRAINT:
m_rho_vec(i + M) = RHO_EQ_FACTOR * rho0;
break;
case Base::constraint_type::INEQUALITY_CONSTRAINT: /* fall through */
default:
m_rho_vec(i + M) = rho0;
};
}
m_rho_inv_vec = m_rho_vec.cwiseInverse();
rho = rho0;
this->m_info.rho_updates += 1;
}
void residuals_update(const Eigen::Ref<const qp_hessian_t>& H, const Eigen::Ref<const qp_var_t>& h,
const Eigen::Ref<const qp_constraint_t>& A) noexcept
{
scalar_t norm_Ax, norm_z;
norm_Ax = (A * this->m_x).template lpNorm<Eigen::Infinity>();
norm_Ax = fmax(norm_Ax, this->m_x.template tail<N>().template lpNorm<Eigen::Infinity>());
norm_z = m_z.template lpNorm<Eigen::Infinity>();
m_max_Ax_z_norm = fmax(norm_Ax, norm_z);
scalar_t norm_Hx, norm_ATy, norm_h, norm_y_box;
norm_Hx = (H * this->m_x).template lpNorm<Eigen::Infinity>();
norm_ATy = (this->m_y.template head<M>().transpose() * A).template lpNorm<Eigen::Infinity>();
norm_h = h.template lpNorm<Eigen::Infinity>();
norm_y_box = this->m_y.template tail<N>().template lpNorm<Eigen::Infinity>();
m_max_Hx_ATy_h_norm = fmax(norm_Hx, fmax(norm_ATy, fmax(norm_h, norm_y_box)));
this->m_info.res_prim = this->primal_residual(A, this->m_x, m_z.template head<M>());
scalar_t box_norm = (this->m_x - m_z.template tail<N>()).template lpNorm<Eigen::Infinity>();
this->m_info.res_prim = fmax(this->m_info.res_prim, box_norm);
this->m_info.res_dual = this->dual_residual(H, h, A, this->m_x, this->m_y);
}
EIGEN_STRONG_INLINE scalar_t eps_prim() const noexcept
{
return this->m_settings.eps_abs + this->m_settings.eps_rel * m_max_Ax_z_norm;
}
EIGEN_STRONG_INLINE scalar_t eps_dual() const noexcept
{
return this->m_settings.eps_abs + this->m_settings.eps_rel * m_max_Hx_ATy_h_norm;
}
EIGEN_STRONG_INLINE bool termination_criteria() const noexcept
{
// check residual norms to detect optimality
return (this->m_info.res_prim <= eps_prim() && this->m_info.res_dual <= eps_dual()) ? true : false;
}
EIGEN_STRONG_INLINE scalar_t estimate_rho(const scalar_t& rho0) const noexcept
{
scalar_t rp_norm, rd_norm;
rp_norm = this->m_info.res_prim / (m_max_Ax_z_norm + this->DIV_BY_ZERO_REGUL);
rd_norm = this->m_info.res_dual / (m_max_Hx_ATy_h_norm + this->DIV_BY_ZERO_REGUL);
scalar_t rho_new = rho0 * sqrt(rp_norm / (rd_norm + this->DIV_BY_ZERO_REGUL));
return rho_new;
}
EIGEN_STRONG_INLINE void update_kkt_rho() noexcept
{
m_K.diagonal(). template tail<N + M>() = -m_rho_inv_vec;
//m_K.template bottomRightCorner<M + N, M + N>() = -1.0 * m_rho_inv_vec.asDiagonal();
}
};
#endif // ADMM_HPP
| 41.373281 | 151 | 0.605632 |
bbeee5ce3406395fe23c446204cec8e2508686a3 | 2,495 | cc | C++ | chrome/renderer/plugins/pdf_plugin_placeholder.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | chrome/renderer/plugins/pdf_plugin_placeholder.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | chrome/renderer/plugins/pdf_plugin_placeholder.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/plugins/pdf_plugin_placeholder.h"
#include "chrome/common/pdf_uma.h"
#include "chrome/common/render_messages.h"
#include "chrome/grit/renderer_resources.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/renderer/render_thread.h"
#include "gin/object_template_builder.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/webui/jstemplate_builder.h"
#include "ui/base/webui/web_ui_util.h"
gin::WrapperInfo PDFPluginPlaceholder::kWrapperInfo = {gin::kEmbedderNativeGin};
PDFPluginPlaceholder::PDFPluginPlaceholder(content::RenderFrame* render_frame,
const blink::WebPluginParams& params,
const std::string& html_data)
: plugins::PluginPlaceholderBase(render_frame, params, html_data) {}
PDFPluginPlaceholder::~PDFPluginPlaceholder() {}
PDFPluginPlaceholder* PDFPluginPlaceholder::CreatePDFPlaceholder(
content::RenderFrame* render_frame,
const blink::WebPluginParams& params) {
std::string template_html = ui::ResourceBundle::GetSharedInstance()
.GetRawDataResource(IDR_PDF_PLUGIN_HTML)
.as_string();
webui::AppendWebUiCssTextDefaults(&template_html);
base::DictionaryValue values;
values.SetString("fileName", GURL(params.url).ExtractFileName());
values.SetString("open", l10n_util::GetStringUTF8(IDS_ACCNAME_OPEN));
std::string html_data = webui::GetI18nTemplateHtml(template_html, &values);
return new PDFPluginPlaceholder(render_frame, params, html_data);
}
v8::Local<v8::Value> PDFPluginPlaceholder::GetV8Handle(v8::Isolate* isolate) {
return gin::CreateHandle(isolate, this).ToV8();
}
gin::ObjectTemplateBuilder PDFPluginPlaceholder::GetObjectTemplateBuilder(
v8::Isolate* isolate) {
return gin::Wrappable<PDFPluginPlaceholder>::GetObjectTemplateBuilder(isolate)
.SetMethod<void (PDFPluginPlaceholder::*)()>(
"openPDF", &PDFPluginPlaceholder::OpenPDFCallback);
}
void PDFPluginPlaceholder::OpenPDFCallback() {
ReportPDFLoadStatus(PDFLoadStatus::kViewPdfClickedInPdfPluginPlaceholder);
content::RenderThread::Get()->Send(
new ChromeViewHostMsg_OpenPDF(routing_id(), GetPluginParams().url));
}
| 42.288136 | 80 | 0.739479 |
bbeee88e430aeae5c0b205f0569d88271a17eb23 | 5,730 | cpp | C++ | Remixed/CompositorBase.cpp | LukeRoss00/Revive | 09b1c59dfbff8abc06194809ec680b990b2cf21c | [
"MIT"
] | 1 | 2021-10-18T19:43:06.000Z | 2021-10-18T19:43:06.000Z | Remixed/CompositorBase.cpp | LukeRoss00/Revive | 09b1c59dfbff8abc06194809ec680b990b2cf21c | [
"MIT"
] | null | null | null | Remixed/CompositorBase.cpp | LukeRoss00/Revive | 09b1c59dfbff8abc06194809ec680b990b2cf21c | [
"MIT"
] | 1 | 2020-02-03T22:45:41.000Z | 2020-02-03T22:45:41.000Z | #include "CompositorBase.h"
#include "Session.h"
#include "FrameList.h"
#include "OVR_CAPI.h"
#include "microprofile.h"
#include <vector>
#include <algorithm>
#include <winrt/Windows.Graphics.Holographic.h>
using namespace winrt::Windows::Graphics::Holographic;
MICROPROFILE_DEFINE(WaitToBeginFrame, "Compositor", "WaitFrame", 0x00ff00);
MICROPROFILE_DEFINE(BeginFrame, "Compositor", "BeginFrame", 0x00ff00);
MICROPROFILE_DEFINE(EndFrame, "Compositor", "EndFrame", 0x00ff00);
MICROPROFILE_DEFINE(SubmitFovLayer, "Compositor", "SubmitFovLayer", 0x00ff00);
CompositorBase::CompositorBase()
: m_MirrorTexture(nullptr)
, m_ChainCount(0)
{
}
CompositorBase::~CompositorBase()
{
if (m_MirrorTexture)
delete m_MirrorTexture;
}
ovrResult CompositorBase::CreateTextureSwapChain(const ovrTextureSwapChainDesc* desc, ovrTextureSwapChain* out_TextureSwapChain)
{
ovrTextureSwapChain swapChain = new ovrTextureSwapChainData(*desc);
swapChain->Identifier = m_ChainCount++;
for (int i = 0; i < swapChain->Length; i++)
{
TextureBase* texture = CreateTexture();
bool success = texture->Init(desc->Type, desc->Width, desc->Height, desc->MipLevels,
desc->ArraySize, desc->Format, desc->MiscFlags, desc->BindFlags);
if (!success)
return ovrError_RuntimeException;
swapChain->Textures[i].reset(texture);
}
*out_TextureSwapChain = swapChain;
return ovrSuccess;
}
ovrResult CompositorBase::CreateMirrorTexture(const ovrMirrorTextureDesc* desc, ovrMirrorTexture* out_MirrorTexture)
{
// There can only be one mirror texture at a time
if (m_MirrorTexture)
return ovrError_RuntimeException;
// TODO: Support ovrMirrorOptions
ovrMirrorTexture mirrorTexture = new ovrMirrorTextureData(*desc);
TextureBase* texture = CreateTexture();
bool success = texture->Init(ovrTexture_2D, desc->Width, desc->Height, 1, 1, desc->Format,
desc->MiscFlags | ovrTextureMisc_AllowGenerateMips, ovrTextureBind_DX_RenderTarget);
if (!success)
return ovrError_RuntimeException;
mirrorTexture->Texture.reset(texture);
m_MirrorTexture = mirrorTexture;
*out_MirrorTexture = mirrorTexture;
return ovrSuccess;
}
ovrResult CompositorBase::WaitToBeginFrame(ovrSession session, long long frameIndex)
{
MICROPROFILE_SCOPE(WaitToBeginFrame);
session->Frames->GetFrame(frameIndex).WaitForFrameToFinish();
session->Frames->PopFrame(frameIndex);
return ovrSuccess;
}
ovrResult CompositorBase::BeginFrame(ovrSession session, long long frameIndex)
{
MICROPROFILE_SCOPE(BeginFrame);
session->CurrentFrame = session->Frames->GetFrame(frameIndex);
return ovrSuccess;
}
ovrResult CompositorBase::EndFrame(ovrSession session, long long frameIndex, ovrLayerHeader const * const * layerPtrList, unsigned int layerCount)
{
MICROPROFILE_SCOPE(EndFrame);
if (layerCount == 0 || !layerPtrList)
return ovrError_InvalidParameter;
// Flush all pending draw calls.
Flush();
ovrLayerEyeFov baseLayer;
bool baseLayerFound = false;
for (uint32_t i = 0; i < layerCount; i++)
{
if (layerPtrList[i] == nullptr)
continue;
// TODO: Support ovrLayerType_Quad, ovrLayerType_Cylinder and ovrLayerType_Cube
if (layerPtrList[i]->Type == ovrLayerType_EyeFov ||
layerPtrList[i]->Type == ovrLayerType_EyeFovDepth ||
layerPtrList[i]->Type == ovrLayerType_EyeFovMultires)
{
ovrLayerEyeFov* layer = (ovrLayerEyeFov*)layerPtrList[i];
SubmitFovLayer(session, frameIndex, layer);
baseLayerFound = true;
}
else if (layerPtrList[i]->Type == ovrLayerType_EyeMatrix)
{
ovrLayerEyeFov layer = ToFovLayer((ovrLayerEyeMatrix*)layerPtrList[i]);
SubmitFovLayer(session, frameIndex, &layer);
baseLayerFound = true;
}
}
HolographicFrame frame = session->Frames->GetFrame(frameIndex);
HolographicFramePrediction prediction = frame.CurrentPrediction();
HolographicCameraPose pose = prediction.CameraPoses().GetAt(0);
HolographicCamera cam = pose.HolographicCamera();
//cam.IsPrimaryLayerEnabled(baseLayerFound);
HolographicFramePresentResult result = frame.PresentUsingCurrentPrediction(HolographicFramePresentWaitBehavior::DoNotWaitForFrameToFinish);
if (result == HolographicFramePresentResult::DeviceRemoved)
return ovrError_DisplayLost;
// TODO: Mirror textures
//if (m_MirrorTexture && success)
// RenderMirrorTexture(m_MirrorTexture);
MicroProfileFlip();
return ovrSuccess;
}
ovrLayerEyeFov CompositorBase::ToFovLayer(ovrLayerEyeMatrix* matrix)
{
ovrLayerEyeFov layer = { ovrLayerType_EyeFov };
layer.Header.Flags = matrix->Header.Flags;
layer.SensorSampleTime = matrix->SensorSampleTime;
for (int i = 0; i < ovrEye_Count; i++)
{
layer.Fov[i].LeftTan = layer.Fov[i].RightTan = .5f / matrix->Matrix[i].M[0][0];
layer.Fov[i].UpTan = layer.Fov[i].DownTan = -.5f / matrix->Matrix[i].M[1][1];
layer.ColorTexture[i] = matrix->ColorTexture[i];
layer.Viewport[i] = matrix->Viewport[i];
layer.RenderPose[i] = matrix->RenderPose[i];
}
return layer;
}
void CompositorBase::SubmitFovLayer(ovrSession session, long long frameIndex, ovrLayerEyeFov* fovLayer)
{
MICROPROFILE_SCOPE(SubmitFovLayer);
ovrTextureSwapChain swapChain[ovrEye_Count] = {
fovLayer->ColorTexture[ovrEye_Left],
fovLayer->ColorTexture[ovrEye_Right]
};
// If the right eye isn't set use the left eye for both
if (!swapChain[ovrEye_Right])
swapChain[ovrEye_Right] = swapChain[ovrEye_Left];
// Submit the scene layer.
for (int i = 0; i < ovrEye_Count; i++)
{
RenderTextureSwapChain(session, frameIndex, (ovrEyeType)i, swapChain[i], fovLayer->Viewport[i]);
}
swapChain[ovrEye_Left]->Submit();
if (swapChain[ovrEye_Left] != swapChain[ovrEye_Right])
swapChain[ovrEye_Right]->Submit();
}
void CompositorBase::SetMirrorTexture(ovrMirrorTexture mirrorTexture)
{
m_MirrorTexture = mirrorTexture;
}
| 30.478723 | 146 | 0.766492 |
bbf56d131e20fcbaf358a4c5a8f8f0ff091d0bc7 | 1,522 | hpp | C++ | SCLT/Color/CIEColorSpaces/CIEUCS.hpp | chicio/Multispectral-Ray-tracing | ea5b399770eddd1927aae8a8ae4640dead42c48c | [
"MIT"
] | 95 | 2016-05-05T10:46:49.000Z | 2021-12-20T12:51:41.000Z | SCLT/Color/CIEColorSpaces/CIEUCS.hpp | chicio/Multispectral-Ray-tracing | ea5b399770eddd1927aae8a8ae4640dead42c48c | [
"MIT"
] | 1 | 2021-12-06T03:21:32.000Z | 2021-12-06T03:21:32.000Z | SCLT/Color/CIEColorSpaces/CIEUCS.hpp | chicio/Multispectral-Ray-tracing | ea5b399770eddd1927aae8a8ae4640dead42c48c | [
"MIT"
] | 8 | 2017-03-12T03:04:08.000Z | 2022-03-17T01:27:41.000Z | //
// CIE1960UCS.hpp
// Spectral Clara Lux tracer
//
// Created by Fabrizio Duroni on 24/12/15.
// Copyright © 2015 Fabrizio Duroni. All rights reserved.
//
#ifndef CIE1960UCS_hpp
#define CIE1960UCS_hpp
#include "Vector3D.hpp"
struct CIEUCSChromaticities {
/// u coordinate.
float u;
/// v coordinate
float v;
/*!
Constructor that init a CIE1960UCSChromaticities object.
@param u u coordinate.
@param v v coordinate.
*/
CIEUCSChromaticities(float u, float v) : u{u}, v{v} {};
};
class CIEUCS {
public:
/*!
Convert CIE XYZ chromaticity values to CIE UCS 1960 chromaticity values.
@param tristimulusChromaticity CIE XYZ tristimulus chromaticity coordinate.
@returns CIE 1960 chromaticity values.
*/
static CIEUCSChromaticities chromaticity(const Vector3D& tristimulusChromaticity);
/*!
Convert CIE XYZ tristimulus values to CIE UCS 1960 chromaticity values.
@param tristilusValues CIE XYZ tristimulus values.
@returns CIE 1960 chromaticity values.
*/
static CIEUCSChromaticities chromaticityFromTristimulus(const Vector3D& tristimulusValues);
/*!
Calculate CIE 1960 chromaticity values using color correleated temperature (CCT).
Useful for black body chromaticity calculation.
@param CCT black body temperature.
@returns
*/
static CIEUCSChromaticities chromaticityForBlackBodyUsingCCT(float CCT);
};
#endif /* CIEUCS_hpp */
| 24.15873 | 95 | 0.685283 |
bbfc733ec98b5bbb144bd301d8aee1e9761dbbfa | 689 | cpp | C++ | ITP2/ITP2_5_D.cpp | felixny/AizuOnline | 8ff399d60077e08961845502d4a99244da580cd2 | [
"MIT"
] | null | null | null | ITP2/ITP2_5_D.cpp | felixny/AizuOnline | 8ff399d60077e08961845502d4a99244da580cd2 | [
"MIT"
] | null | null | null | ITP2/ITP2_5_D.cpp | felixny/AizuOnline | 8ff399d60077e08961845502d4a99244da580cd2 | [
"MIT"
] | null | null | null | // ITP2_5_D
#include <algorithm>
#include <iostream>
#include <numeric>
#include <tuple>
#include <utility>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> v(n);
iota(v.begin(), v.end(), 1);
do {
for (int i = 0; i < n; i++) { // cout<<(i?" ":"")<<v[i];
if (i) { // zero is used to represent false so the first value i = 0 is
// always false which prints no empty string. ""
cout << " [value i: ]" << i;
cout << " " << v[i];
} else {
cout << "" << v[i];
cout << " [value i: ]" << i;
}
}
cout << endl;
} while (next_permutation(v.begin(), v.end()));
return 0;
}
| 22.225806 | 78 | 0.489115 |
bbfc9a10011ebe085ef224beb130ea6fdfc7f0f2 | 3,204 | hpp | C++ | src/core/RegionHash.hpp | gyzhangqm/overkit-1 | 490aa77a79bd9708d7f2af0f3069b86545a2cebc | [
"MIT"
] | null | null | null | src/core/RegionHash.hpp | gyzhangqm/overkit-1 | 490aa77a79bd9708d7f2af0f3069b86545a2cebc | [
"MIT"
] | null | null | null | src/core/RegionHash.hpp | gyzhangqm/overkit-1 | 490aa77a79bd9708d7f2af0f3069b86545a2cebc | [
"MIT"
] | 1 | 2021-07-21T06:48:19.000Z | 2021-07-21T06:48:19.000Z | // Copyright (c) 2020 Matthew J. Smith and Overkit contributors
// License: MIT (http://opensource.org/licenses/MIT)
#ifndef OVK_CORE_REGION_HASH_HPP_INCLUDED
#define OVK_CORE_REGION_HASH_HPP_INCLUDED
#include <ovk/core/Array.hpp>
#include <ovk/core/ArrayView.hpp>
#include <ovk/core/Box.hpp>
#include <ovk/core/Field.hpp>
#include <ovk/core/Global.hpp>
#include <ovk/core/HashableRegionTraits.hpp>
#include <ovk/core/Math.hpp>
#include <ovk/core/Range.hpp>
#include <ovk/core/Set.hpp>
#include <ovk/core/Tuple.hpp>
#include <cmath>
#include <memory>
#include <type_traits>
#include <utility>
namespace ovk {
namespace core {
template <typename RegionType> class region_hash {
public:
static_assert(IsHashableRegion<RegionType>(), "Invalid region type (not hashable).");
using region_type = RegionType;
using region_traits = hashable_region_traits<region_type>;
using coord_type = typename region_traits::coord_type;
static_assert(std::is_same<coord_type, int>::value || std::is_same<coord_type, double>::value,
"Coord type must be int or double.");
using extents_type = interval<coord_type,MAX_DIMS>;
explicit region_hash(int NumDims);
region_hash(int NumDims, const tuple<int> &NumBins, array_view<const region_type> Regions);
long long MapToBin(const tuple<coord_type> &Point) const;
array_view<const long long> RetrieveBin(long long iBin) const;
int Dimension() const { return NumDims_; }
const range &BinRange() const { return BinRange_; }
const extents_type &Extents() const { return Extents_; }
private:
int NumDims_;
range BinRange_;
field_indexer BinIndexer_;
extents_type Extents_;
tuple<double> BinSize_;
array<long long> BinRegionIndicesStarts_;
array<long long> BinRegionIndices_;
void MapToBins_(const region_type &Region, range &Bins) const;
void MapToBins_(const region_type &Region, set<long long> &Bins) const;
void AccumulateBinRegionCounts_(const range &Bins, field<long long> &NumRegionsInBin) const;
void AccumulateBinRegionCounts_(const set<long long> &Bins, field<long long> &NumRegionsInBin)
const;
void AddToBins_(int iRegion, const range &Bins, const array<long long> &BinRegionIndicesStarts,
array<long long> &BinRegionIndices, field<long long> &NumRegionsAddedToBin) const;
void AddToBins_(int iRegion, const set<long long> &Bins, const array<long long>
&BinRegionIndicesStarts, array<long long> &BinRegionIndices, field<long long>
&NumRegionsAddedToBin) const ;
template <typename T> struct coord_type_tag {};
interval<int,MAX_DIMS> MakeEmptyExtents_(int NumDims, coord_type_tag<int>);
interval<double,MAX_DIMS> MakeEmptyExtents_(int NumDims, coord_type_tag<double>);
interval<int,MAX_DIMS> UnionExtents_(const interval<int,MAX_DIMS> &Left, const
interval<int,MAX_DIMS> &Right);
interval<double,MAX_DIMS> UnionExtents_(const interval<double,MAX_DIMS> &Left, const
interval<double,MAX_DIMS> &Right);
static tuple<int> GetBinSize_(const interval<int,MAX_DIMS> &Extents, const tuple<int> &NumBins);
static tuple<double> GetBinSize_(const interval<double,MAX_DIMS> &Extents, const tuple<int>
&NumBins);
};
}}
#include <ovk/core/RegionHash.inl>
#endif
| 32.693878 | 98 | 0.762172 |
bbfce24d15d965501e8ff85e1b32fe028b4ebc16 | 7,517 | cpp | C++ | bocom/Wiodb.cpp | tomasbrod/tbboinc | c125cc355b2dc9a1e536b5e5ded028d4e7f4613a | [
"MIT"
] | null | null | null | bocom/Wiodb.cpp | tomasbrod/tbboinc | c125cc355b2dc9a1e536b5e5ded028d4e7f4613a | [
"MIT"
] | 4 | 2020-09-07T15:54:45.000Z | 2020-09-27T16:47:16.000Z | bocom/Wiodb.cpp | tomasbrod/tbboinc | c125cc355b2dc9a1e536b5e5ded028d4e7f4613a | [
"MIT"
] | null | null | null |
int create_work4(
DB_WORKUNIT& wu,
const char* result_template_filename,
SCHED_CONFIG& config_loc
) {
int retval;
wu.create_time = time(0);
// check for presence of result template.
// we don't need to actually look at it.
//
const char* p = config_loc.project_path(result_template_filename);
if (!boinc_file_exists(p)) {
fprintf(stderr,
"create_work: result template file %s doesn't exist\n", p
);
return retval;
}
if (strlen(result_template_filename) > sizeof(wu.result_template_file)-1) {
fprintf(stderr,
"result template filename is too big: %d bytes, max is %d\n",
(int)strlen(result_template_filename),
(int)sizeof(wu.result_template_file)-1
);
return ERR_BUFFER_OVERFLOW;
}
strncpy(wu.result_template_file, result_template_filename, sizeof(wu.result_template_file));
if (wu.rsc_fpops_est == 0) {
fprintf(stderr, "no rsc_fpops_est given; can't create job\n");
return ERR_NO_OPTION;
}
if (wu.rsc_fpops_bound == 0) {
fprintf(stderr, "no rsc_fpops_bound given; can't create job\n");
return ERR_NO_OPTION;
}
if (wu.rsc_disk_bound == 0) {
fprintf(stderr, "no rsc_disk_bound given; can't create job\n");
return ERR_NO_OPTION;
}
if (wu.target_nresults == 0) {
fprintf(stderr, "no target_nresults given; can't create job\n");
return ERR_NO_OPTION;
}
if (wu.max_error_results == 0) {
fprintf(stderr, "no max_error_results given; can't create job\n");
return ERR_NO_OPTION;
}
if (wu.max_total_results == 0) {
fprintf(stderr, "no max_total_results given; can't create job\n");
return ERR_NO_OPTION;
}
if (wu.max_success_results == 0) {
fprintf(stderr, "no max_success_results given; can't create job\n");
return ERR_NO_OPTION;
}
if (wu.max_success_results > wu.max_total_results) {
fprintf(stderr, "max_success_results > max_total_results; can't create job\n");
return ERR_INVALID_PARAM;
}
if (wu.max_error_results > wu.max_total_results) {
fprintf(stderr, "max_error_results > max_total_results; can't create job\n");
return ERR_INVALID_PARAM;
}
if (wu.target_nresults > wu.max_success_results) {
fprintf(stderr, "target_nresults > max_success_results; can't create job\n");
return ERR_INVALID_PARAM;
}
/*
auto prev_transitioner_flags= wu.transitioner_flags;
wu.transitioner_flags= 1;
*/
if (wu.transitioner_flags) {
wu.transition_time = INT_MAX;
} else {
wu.transition_time = time(0);
}
retval = wu.insert();
if (retval) {
fprintf(stderr,
"create_work4: workunit.insert() %s\n", boincerror(retval)
);
return retval;
}
wu.id = boinc_db.insert_id();
/*
wu.transitioner_flags= prev_transitioner_flags;
if (wu.transitioner_flags) {
wu.transition_time = INT_MAX;
} else {
wu.transition_time = time(0);
}
wu.update();
*/
return 0;
}
int create_work3(
DB_WORKUNIT& wu,
const char* result_template_filename,
// relative to project root; stored in DB
SCHED_CONFIG& config_loc,
const CStream& input_data
) {
int retval;
unsigned long in_len = input_data.pos();
char in_md5[256];
md5_block((const unsigned char*)input_data.getbase(), in_len, in_md5);
snprintf(wu.xml_doc, sizeof(wu.xml_doc),
"<file_info>\n<name>%s.in</name>\n"
"<url>https://boinc.tbrada.eu/tbrada_cgi/fuh?%s.in</url>\n"
"<md5_cksum>%s</md5_cksum>\n<nbytes>%lu</nbytes>\n</file_info>\n"
"<workunit>\n<file_ref>\n<file_name>%s.in</file_name>\n"
"<open_name>input.dat</open_name>\n</file_ref>\n</workunit>\n"
, wu.name, wu.name
, in_md5, in_len
, wu.name
);
retval = create_work4(wu, result_template_filename, config_loc);
if(retval) return retval;
//insert input_file
MYSQL_STMT* insert_stmt = 0;
insert_stmt = mysql_stmt_init(boinc_db.mysql);
char stmt[] = "insert into input_file SET wu=?, data=?";
void* in_data= (void*)input_data.getbase();
MYSQL_BIND bind[] = {
{.buffer=&wu.id, .buffer_type=MYSQL_TYPE_LONG, 0},
{.length=&in_len, .buffer=in_data, .buffer_type=MYSQL_TYPE_BLOB, 0},
};
if(!insert_stmt
|| mysql_stmt_prepare(insert_stmt, stmt, sizeof stmt )
|| mysql_stmt_bind_param(insert_stmt, bind)
|| mysql_stmt_execute(insert_stmt)
) {
mysql_stmt_close(insert_stmt);
fprintf(stderr,
"create_work: insert of input_data failed %s\n", mysql_error(boinc_db.mysql) );
//wu.delete_from_db();
return -1;
}
mysql_stmt_close(insert_stmt);
return 0;
}
int read_output_file(RESULT const& result, CDynamicStream& buf) {
char path[MAXPATHLEN];
path[0]=0;
std::string name;
double usize = 0;
double usize_max = 0;
MIOFILE mf;
mf.init_buf_read(result.xml_doc_out);
XML_PARSER xp(&mf);
while (!xp.get_tag()) {
if (!xp.is_tag) continue;
if (xp.match_tag("file_info")) {
while(!xp.get_tag()) {
if (!xp.is_tag) continue;
if(xp.parse_string("name",name)) continue;
if(xp.parse_double("nbytes",usize)) continue;
if(xp.parse_double("max_nbytes",usize_max)) continue;
if (xp.match_tag("/file_info")) {
if(!name[0] || !usize) {
return ERR_XML_PARSE;
}
dir_hier_path(
name.c_str(), config.upload_dir,
config.uldl_dir_fanout, path
);
FILE* f = boinc_fopen(path, "r");
if(!f && ENOENT==errno) return ERR_FILE_MISSING;
if(!f) return ERR_READ;
struct stat stat_buf;
if(fstat(fileno(f), &stat_buf)<0) return ERR_READ;
buf.setpos(0);
buf.reserve(stat_buf.st_size);
if( fread(buf.getbase(), 1, stat_buf.st_size, f) !=stat_buf.st_size)
return ERR_READ;
buf.setpos(0);
fclose(f);
return 0;
}
}
}
}
return ERR_XML_PARSE;
}
int read_output_file_db(RESULT const& result, CDynamicStream& buf) {
char sql[MAX_QUERY_LEN];
sprintf(sql, "select id, data from result_file where res='%lu' order by id desc limit 1", result.id);
int retval=boinc_db.do_query(sql);
if(retval) return retval;
MYSQL_RES* enum_res= mysql_use_result(boinc_db.mysql);
if(!enum_res) return -1;
MYSQL_ROW row=mysql_fetch_row(enum_res);
if (row == 0) {
mysql_free_result(enum_res);
return ERR_FILE_MISSING;
}
unsigned long *enum_len= mysql_fetch_lengths(enum_res);
buf.setpos(0);
//buf.reserve(enum_len[1]);
buf.write(row[1], enum_len[1]);
buf.setpos(0);
mysql_free_result(enum_res);
return 0;
}
void set_result_invalid(DB_RESULT& result) {
DB_WORKUNIT wu;
if(wu.lookup_id(result.workunitid)) throw EDatabase("Workunit not found");
DB_HOST_APP_VERSION hav, hav0;
retval = hav_lookup(hav0, result.hostid,
generalized_app_version_id(result.app_version_id, result.appid)
);
hav= hav0;
hav.consecutive_valid = 0;
if (hav.max_jobs_per_day > config.daily_result_quota) {
hav.max_jobs_per_day--;
}
result.validate_state=VALIDATE_STATE_INVALID;
result.outcome=6;
wu.transition_time = time(0);
//result.file_delete_state=FILE_DELETE_READY; - keep for analysis
if(result.update()) throw EDatabase("Result update error");
if(wu.update()) throw EDatabase("Workunit update error");
if (hav.host_id && hav.update_validator(hav0)) throw EDatabase("Host-App-Version update error");
}
| 31.190871 | 102 | 0.65731 |
bbfd1811564296095ed432bef91b5052577a8328 | 52,456 | cpp | C++ | src/llreplace.cpp | landenlabs2/llfile | 83d071412467742fcf9611ee0b10e41b6ea19728 | [
"MIT"
] | 1 | 2017-01-26T13:48:35.000Z | 2017-01-26T13:48:35.000Z | src/llreplace.cpp | landenlabs2/llfile | 83d071412467742fcf9611ee0b10e41b6ea19728 | [
"MIT"
] | null | null | null | src/llreplace.cpp | landenlabs2/llfile | 83d071412467742fcf9611ee0b10e41b6ea19728 | [
"MIT"
] | null | null | null | //-----------------------------------------------------------------------------
// llreplace - Replace file data or Grep.
//
// Author: Dennis Lang - 2015
// http://landenlabs.com/
//
// This file is part of LLFile project.
//
// ----- License ----
//
// Copyright (c) 2015 Dennis Lang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include <iostream>
#include <string.h>
#include <assert.h>
#include <fcntl.h>
#include <io.h>
#include <map>
#include <algorithm>
#define ZipLib
#ifdef ZipLib
// https://bitbucket.org/wbenny/ziplib/wiki/Home
#include "../ZipLib/ZipFile.h"
// #pragma comment(lib, "zlib.lib")
// #pragma comment(lib, "lzma.lib")
// #pragma comment(lib, "bzip2.lib")
#endif
#include "LLReplace.h"
#include "MemMapFile.h"
#ifdef ZipLib
int LLReplace::ZipListArchive(const char* zipArchiveName)
{
// ZipArchive::Ptr archive = ZipFile::Open(zipArchiveName);
std::ifstream* zipFile = new std::ifstream();
zipFile->open(zipArchiveName, std::ios::binary);
if (!zipFile->is_open())
return -1;
ZipArchive::Ptr archive = ZipArchive::Create(zipFile, true);
if (archive == nullptr)
return -1;
size_t entries = archive->GetEntriesCount();
if (m_verbose)
{
LLMsg::Out() << zipArchiveName << ", Entries:" << entries << std::endl;
LLMsg::Out() << archive->GetComment() << std::endl;
}
for (size_t idx = 0; idx < entries; ++idx)
{
auto entry = archive->GetEntry(int(idx));
if (m_zipList.size() == 1 && m_zipList[0] == "-")
{
std::stringstream in(entry->GetFullName());
m_matchCnt += FindGrep(in);
m_totalInSize += entry->GetSize();
m_countInFiles++;
}
else if (LLSup::PatternListMatches(m_zipList, entry->GetFullName().c_str(), true))
{
if (m_verbose)
{
LLMsg::Out() << std::setw(3) << idx << ":"
<< std::setw(8) << entry->GetSize() << " "
<< entry->GetFullName() << std::endl;
/*
uncompressed size entry->GetSize());
compressed size: entry->GetCompressedSize());
password protected: entry->IsPasswordProtected() ? "yes" : "no");
compression method: entry->GetCompressionMethod()
comment: entry->GetComment()
crc32: entry->GetCrc32());
*/
}
std::istream* decompressStream = entry->GetDecompressionStream();
#if 1
if (decompressStream != nullptr)
{
m_matchCnt += FindGrep(*decompressStream);
m_totalInSize += entry->GetSize();
m_countInFiles++;
}
#else
std::string line;
while (std::getline(*decompressStream, line))
{
LLMsg::Out() << line << std::endl;
}
#endif
}
}
return sOkay;
}
int LLReplace::ZipReadFile(
const char* zipFilename,
const char* fileToExtract,
const char* password)
{
ZipArchive::Ptr archive = ZipFile::Open(zipFilename);
ZipArchiveEntry::Ptr entry = archive->GetEntry(fileToExtract);
assert(entry != nullptr);
entry->SetPassword(password);
std::istream* decompressStream = entry->GetDecompressionStream();
assert(decompressStream == nullptr);
std::string line;
while (std::getline(*decompressStream, line))
{
LLMsg::Out() << line << std::endl;
}
return sIgnore;
}
#endif
// ---------------------------------------------------------------------------
// Add regular expression to help document
// https://msdn.microsoft.com/en-us/library/bb982727.aspx#regexgrammar
// http://www.cplusplus.com/reference/regex/ECMAScript/
static const char sHelp[] =
" Replace " LLVERSION "\n"
" Replace a file[s] data\n"
"\n"
" !0eSyntax:!0f\n"
" [<switches>] <Pattern>... \n"
"\n"
" !0eWhere switches are:!0f\n"
" -? ; Show this help\n"
" -A=[nrhs] ; Limit files by attribute (n=normal r=readonly, h=hidden, s=system)\n"
" -D ; Only directories in matching, default is all types\n"
" -p ; Search PATH environment directories for pattern\n"
" -e=<envName>[,...] ; Search env environment directories for pattern\n"
" -F ; Only files in matching, default is all types\n"
" -F=<filePat>,... ; Limit to matching file patterns \n"
" -G=<grepPattern> ; Return line matching grepPattern \n"
" -g=<grepOptions> ; Use with -G \n"
" ; Default is search entire file \n"
" ; Ln=first n lines \n"
" ; Mn=first n matches \n"
" ; H(c|f|l|m|t) Hide color|filename|Line#|MatchCnt|Text \n"
" ; I=ignore case \n"
" ; R=repeat replace \n"
" ; Bn=show before n lines \n"
" ; An=show after n lines \n"
" ; F(l|f) force byLine or byFile \n"
" ; U(i|b) update inline or backup \n"
" -i ; Ignore case, same as -g=I \n"
" -I=<file> ; Read list of files from this file\n"
" -M=<file> ; Match (and replace) list of patterns in file \n"
" ; First Line Seperator:<char> like , \n"
" ; Remainder <findPat><seperator><replacePat>[,<filePathPat>] \n"
" -p ; Short cut for -e=PATH, search path \n"
" -P=<srcPathPat> ; Optional regular expression pattern on source files full path\n"
" -q ; Quiet, default is echo command\n"
" -Q=n ; Quit after 'n' file matches\n"
" -r ; Recurse into subdirectories\n"
" -R=<replacePattern> ; Use with -G to replace match\n"
#if 0
" -Rbefore=<pattern> ; TODO Use with -R to move a replacement\n"
" -Rafter=<pattern> ; TODO Use with -R to move a replacement\n"
#endif
" -s ; Show file size size\n"
" -t[acm] ; Show Time a=access, c=creation, m=modified, n=none\n"
" -X=<pathPat>,... ; Exclude patterns -X=*.lib,*.obj,*.exe\n"
" ; No space in patterns. Pattern applied against fullpath\n"
" ; So *\\ma will exclude a directory ma or file ma \n"
" -v ; Verbose \n"
" -V=<grepPattern> ; Return inverse line matching grep matches \n"
" -w=<width> ; Limit output to width characters per match \n"
" -z=<filePattern> ; Limit zip/jar/gz file match, use - to search names \n"
"\n"
" -E=[cFDdsamlL] ; Return exit code, c=File+Dir count, F=file count, D=dir Count\n"
" ; d=depth, s=size, a=age, m=#matches, l=#lines, L=list of matching files \n"
" -1=<file> ; Redirect output to append to file \n"
" -3=<file> ; Tee output to append to file \n"
"\n"
" !0eWhere Pattern is:!0f\n"
" <file|Pattern> \n"
" [<directory|pattern> \\]... <file|Pattern|#n> \n"
"\n"
" !0ePattern:!0f\n"
" * = zero or more characters\n"
" ? = any character\n"
"\n"
" !0eExample:!0f\n"
" llfile -xG \"-G=(H|h)ello\\r\\n\" *.txt ; -xG force grep command\n"
" lg '-G=String' -g=I -r -F=*.cpp src ; Ignore case String in cpp files \n"
" lg -Ar -i=c:\\fileList.txt >nul ; check for non-readonly files from list \n"
"\n"
" lg -F=*.txt,*.log '-G=[0-9]+' .\\* ; search files for numbers \n"
" lg -X=*.obj,*.exe -G=foo build\\* ; search none object or exe files\n"
" lg -z=* -G=class java\\*.jar ; search jar internal files for class \n"
" lg -z=foo* -G=class java\\*.jar ; search jar internal foo* files for class \n"
" lg -z=- -G=class java\\*.jar ; search filenames in jar files for class \n"
" lg -z -G=hello -r libs ; search files for hello and look inside any archive \n"
" lg \"-G= foo \" *.txt | lg -G=bar ; Same as following\n"
" lg \"-G= foo \" -G=bar *.txt ; two -G, either can match per line\n"
"\n"
" ; Use -E=L to match multiple words in same file but not same line \n"
" lg -G=foo -r -F=*.txt -E=L | lg -I=- -G=bar \n"
"\n"
" lg -G=\"'([^']+)',.*\" -R=\"$1');\" foo.txt ; Grep and Replace \n"
" lg -G=\\n\\n -R=\\n -g=R foo.txt ; remove blank lines \n"
" !0ePattern across multiple lines:!0f\n"
" The pattern engine does not match line terminators with . so use some group\n"
" which does not appear in the normal text, like [^?]* \n"
" Example to remove XML tag group. \n"
" \"-G= *<SurveySettings\\>[^?]*\\</SurveySettings>\" \"-R=\" file.xml \n"
"\n"
" lg \"-G=( *)if \\(AppConfigInfo\\.DEBUG\\) \\{[\\r\\n]\\s*Log[.]([^;]+);\\s*[\\r\\n]\\s*\\}\" \"-R=$1WLog.$2\" \n"
"\n";
LLReplaceConfig LLReplace::sConfig;
WORD FILE_COLOR = FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
WORD MATCH_COLOR = FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN;
WORD MATCH_COLORS[] =
{
FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN,
FOREGROUND_INTENSITY | FOREGROUND_RED,
FOREGROUND_INTENSITY | FOREGROUND_GREEN,
FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_BLUE,
};
const char sForceByLine = 'l';
const char sForceByFile = 'f';
///////////////////////////////////////////////////////////////////////////////
// Expands c-style character constants in the input string; returns new size
// (strlen won't work, since the string may contain premature \0's)
static std::string ConvertSpecialChar(std::string& inOut)
{
int len = 0;
int x, n;
const char *inPtr = inOut.c_str();
char* outPtr = (char*)inPtr;
while (*inPtr)
{
if (*inPtr == '\\')
{
inPtr++;
switch (*inPtr)
{
case 'n': *outPtr++ = '\n'; break;
case 't': *outPtr++ = '\t'; break;
case 'v': *outPtr++ = '\v'; break;
case 'b': *outPtr++ = '\b'; break;
case 'r': *outPtr++ = '\r'; break;
case 'f': *outPtr++ = '\f'; break;
case 'a': *outPtr++ = '\a'; break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
sscanf(inPtr,"%3o%n",&x,&n);
inPtr += n-1;
*outPtr++ = (char)x;
break;
case 'x': // hexadecimal
sscanf(inPtr+1,"%2x%n",&x,&n);
if (n>0)
{
inPtr += n;
*outPtr++ = (char)x;
break;
}
// seep through
default:
throw( "Warning: unrecognized escape sequence" );
case '\\':
case '\?':
case '\'':
case '\"':
*outPtr++ = *inPtr;
}
inPtr++;
}
else
*outPtr++ = *inPtr++;
len++;
}
inOut.resize(len);
return inOut;;
}
// ---------------------------------------------------------------------------
// Return true if character in pattern string is part of regular expression
// and not escaped out or inside a closour group []
static bool isPattern(std::string str, int pos)
{
if (pos < 0)
return false;
if (pos == 0)
return true;
if (str[pos-1] == '\\')
return false;
while (--pos >= 0)
{
if (str[pos] == ']')
return true;
if (str[pos] == '[')
return false;
}
return true;
}
// ---------------------------------------------------------------------------
LLReplace::LLReplace() :
m_force(false),
m_totalInSize(0),
m_countInFiles(0),
m_lineCnt(0),
m_matchCnt(0),
m_width(0),
m_zipFile(false)
{
m_exitOpts = "c";
m_showAttr =
m_showCtime =
m_showMtime =
m_showAtime =
m_showPath =
m_showSize =
m_allMustMatch = false;
memset(&m_fileData, 0, sizeof(m_fileData));
m_dirScan.m_recurse = false;
sConfigp = &GetConfig();
}
// ---------------------------------------------------------------------------
LLConfig& LLReplace::GetConfig()
{
return sConfig;
}
// ---------------------------------------------------------------------------
int LLReplace::StaticRun(const char* cmdOpts, int argc, const char* pDirs[])
{
LLReplace llFind;
return llFind.Run(cmdOpts, argc, pDirs);
}
// ---------------------------------------------------------------------------
int LLReplace::Run(const char* cmdOpts, int argc, const char* pDirs[])
{
const char missingRetMsg[] = "Missing return value, c=file count, d=depth, s=size, a=age, syntax -0=<code>";
const char missingEnvMsg[] = "Environment variable name, syntax -E=<envName> ";
const char optReplaceMsg[] = "Replace matches (see -G=grepPattern) with replacement, -R=<replacement>";
const char optGrepMsg[] = "Find in file grepPattern, -G=<grepPattern>" ;
const char missingRepGrp[] = "Replace (-R=replace) must follow Grep (-G=patttern)";
const char widthErrMsg[] = "missing width, syntax -w=<#width>";
const std::string endPathStr(";");
LLSup::StringList envList;
std::string str;
// Initialize stuff
size_t nFiles = 0;
bool sortNeedAllData = m_showSize;
#if 0
// Try and detect redirection and auto disable File, Match and Line numbers.
bool isOutConsole = _isatty(_fileno(stdout));
HANDLE stdoutHnd = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD outType = GetFileType(stdoutHnd); // FILE_TYPE_PIPE
if (outType == FILE_TYPE_PIPE)
isOutConsole = false;
if (outType == FILE_TYPE_DISK)
isOutConsole = false;
#endif
#if 0
// Setup default as needed.
if (argc == 0 && strstr(cmdOpts, "I=") == 0)
{
const char* sDefDir[] = {"*"};
argc = sizeof(sDefDir)/sizeof(sDefDir[0]);
pDirs = sDefDir;
}
#endif
std::string matchFilename;
GrepReplaceItem grepRep;
unsigned findCnt = 0;
unsigned replaceCnt = 0;
// Parse options
while (*cmdOpts)
{
grepRep.m_onMatch = true;
switch (*cmdOpts)
{
case 'C': // -C=none or -C=0 disable colors
if (cmdOpts[1] == sEQchr)
{
cmdOpts += 2;
switch (ToLower(*cmdOpts))
{
case '0':
case 'n':
sConfig.m_colorOn = false;
break;
default:
ErrorMsg() << "Unknown color option: -C" << *cmdOpts << std::endl;
}
// Move to end of color options
while(*cmdOpts > sEOCchr)
cmdOpts++;
}
break;
case 'i': // ignore case, same as =g=I
m_grepOpt.ignoreCase = true;
break;
case 'V': // inverse grep pattern -V=<grepPattern>, show if lines does not contain grepPattern
grepRep.m_onMatch = false;
m_byLine = true;
m_allMustMatch = true;
case 'G': // grep pattern -G=<grepPattern>, show if line contains grepPattern
cmdOpts = LLSup::ParseString(cmdOpts+1, str, optGrepMsg);
if (str.length() != 0) {
if (replaceCnt != 0 && findCnt != replaceCnt)
{
LLMsg::PresentError(0, missingRepGrp, "\n");
return sError;
}
try {
findCnt++;
grepRep.m_grepLineStr = str;
grepRep.m_grepLinePat = std::tr1::regex(str /* , regex_constants::ECMAScript */);
m_grepReplaceList.push_back(grepRep);
// If pattern has explict test for beginning or end of line
// process search/replace byLine rather then byEntireFile.
if (!m_byLine && isPattern(str, str.find('^')))
m_byLine = true;
if (!m_byLine && isPattern(str, str.find('$')))
m_byLine = true;
if (!m_byLine && isPattern(str, str.find('(')))
m_backRef = true;
}
catch (std::regex_error& ex)
{
LLMsg::PresentError(ex.code(), ex.what(), str.c_str());
return sError;
}
}
break;
case 'R': // Get Replacement string
if (isalpha(cmdOpts[1]))
{
// Check for special case -Rafter=... or -Rbefore=...
const char* eqPos = strchr(cmdOpts+2, '=');
if (eqPos != NULL)
{
int len = int(eqPos - cmdOpts + 2);
if (_strnicmp(cmdOpts+2, "after", len) == 0)
{
cmdOpts = LLSup::ParseString(cmdOpts+1, str, optReplaceMsg);
m_grepReplaceList.back().m_afterStr = str;
m_grepOpt.force ='l'; // force by-line
break;
}
else if (_strnicmp(cmdOpts+2, "before", len) == 0)
{
cmdOpts = LLSup::ParseString(cmdOpts+1, str, optReplaceMsg);
m_grepReplaceList.back().m_beforeStr = str;
m_grepOpt.force ='l'; // force by-line
break;
}
}
}
cmdOpts = LLSup::ParseString(cmdOpts+1, str, optReplaceMsg);
if (replaceCnt + 1 == findCnt)
{
replaceCnt++;
m_grepReplaceList.back().m_replace = true;
m_grepReplaceList.back().m_replaceStr = ConvertSpecialChar(str);
}
else
{
LLMsg::PresentError(0, missingRepGrp, "\n");
return sError;
}
break;
case 'm': // Reverse match using file list
grepRep.m_onMatch = false;
m_allMustMatch = true;
case 'M': // Match file list
cmdOpts = LLSup::ParseString(cmdOpts+1, matchFilename, missingInFileMsg);
if (matchFilename.length() != 0)
{
FILE* fin = stdin;
if (strcmp(matchFilename.c_str(), "-") == 0 ||
0 == fopen_s(&fin, matchFilename.c_str(), "rt"))
{
const char sepTag[] = "Seperator:";
const unsigned sepLen = sizeof(sepTag) - 1;
char userSep[] = ",";
char lineBuf[MAX_PATH];
if (fgets(lineBuf, ARRAYSIZE(lineBuf), fin))
{
unsigned lineLen = strlen(lineBuf);
if (strncmp(sepTag, lineBuf, sepLen) == 0 && lineLen > sepLen)
{
userSep[0] = lineBuf[sepLen]; // TODO - support multiple separators
if (!fgets(lineBuf, ARRAYSIZE(lineBuf), fin))
return sError;
}
else
{
LLMsg::PresentError(0, "Match file should start with Seperator:<char>", " Assuming comma separator \n");
// return sError;
}
do
{
// TrimString(lineBuf); // remove extra space or control characters.
if (*lineBuf == '\0')
continue;
unsigned len = strlen(lineBuf);
lineBuf[len - 1] = '\0'; // remove EOL
Split fields(lineBuf, userSep);
if (fields.size() > 0)
{
if (replaceCnt != 0 && findCnt != replaceCnt)
{
LLMsg::PresentError(0, missingRepGrp, "\n");
return sError;
}
findCnt++;
grepRep.m_grepLinePat = grepRep.m_grepLineStr = fields[0];
if (fields.size() > 1)
{
replaceCnt++;
grepRep.m_grepLinePat = ConvertSpecialChar(fields[1]); // Should this be the replacement pattern ?
}
if (fields.size() > 2)
{
grepRep.m_filePathPat = std::tr1::regex(fields[2], regex_constants::icase);
grepRep.m_haveFilePat = true;
}
m_grepReplaceList.push_back(grepRep);
}
} while (fgets(lineBuf, ARRAYSIZE(lineBuf), fin));
std::cerr << " Grep patterns:" << m_grepReplaceList.size() << std::endl;
}
}
}
break;
case 's': // Toggle showing size.
sortNeedAllData |= m_showSize = !m_showSize;
// m_dirSort.SetSortData(sortNeedAllData);
break;
case 't': // Display Time selection
{
bool unknownOpt = false;
while (cmdOpts[1] && !unknownOpt)
{
cmdOpts++;
switch (ToLower(*cmdOpts))
{
case 'a':
sortNeedAllData = m_showAtime = true;
break;
case 'c':
sortNeedAllData = m_showCtime = true;
break;
case 'm':
sortNeedAllData = m_showMtime = true;
break;
case 'n': // NoTime
sortNeedAllData = false;
m_showAtime = m_showCtime = m_showMtime = false;
break;
default:
cmdOpts--;
unknownOpt = true;
break;
}
}
// m_dirSort.SetSortData(sortNeedAllData);
}
break;
case 'z': // Limit zip files, -z or z=<filePat>[,<filePat>]...
cmdOpts = LLSup::ParseList(cmdOpts + 1, m_zipList, NULL);
m_zipFile = true;
break;
case 'w': // Width
cmdOpts = LLSup::ParseNum(cmdOpts+1, m_width, widthErrMsg);
break;
case '?':
Colorize(std::cout, sHelp);
return sIgnore;
case 'E':
if ( !ParseBaseCmds(cmdOpts))
return sError;
if (m_exitOpts.find_first_of("L") != string::npos)
m_grepOpt.hideFilename = m_grepOpt.hideLineNum = m_grepOpt.hideMatchCnt = m_grepOpt.hideText = true;
if (m_exitOpts.find_first_of("l") != string::npos)
m_grepOpt.force = sForceByLine;
break;
default:
if ( !ParseBaseCmds(cmdOpts))
return sError;
}
// Advance to next parameter
LLSup::AdvCmd(cmdOpts);
}
if (m_grepOpt.ignoreCase && !m_grepReplaceList.empty())
{
for (unsigned idx = 0; idx != m_grepReplaceList.size(); idx++)
{
GrepReplaceItem& grepReplaceItem = m_grepReplaceList[idx];
grepReplaceItem.m_grepLinePat =
std::tr1::regex(grepReplaceItem.m_grepLineStr, regex_constants::icase);
}
}
if (m_grepReplaceList.empty())
{
Colorize(std::cout, sHelp);
return sIgnore;
}
// Move arguments and input files into inFileList.
std::vector<std::string> inFileList;
for (int argn=0; argn < argc; argn++)
{
inFileList.push_back(pDirs[argn]);
}
if (m_inFile.length() != 0)
{
FILE* fin = stdin;
if (strcmp(m_inFile.c_str(), "-") == 0 ||
0 == fopen_s(&fin, m_inFile.c_str(), "rt"))
{
char fileName[MAX_PATH];
while (fgets(fileName, ARRAYSIZE(fileName), fin))
{
TrimString(fileName); // remove extra space or control characters.
if (*fileName == '\0')
continue;
inFileList.push_back(fileName);
}
}
}
if (m_grepOpt.force != 0)
{
if (m_grepOpt.force == sForceByLine)
m_byLine = true;
else if (m_grepOpt.force == sForceByFile)
m_byLine = false;
}
if (inFileList.empty())
{
// Grep from standard-in
_setmode(_fileno(stdin), _O_BINARY);
_setmode(_fileno(stdout), _O_BINARY);
m_matchCnt += FindGrep(cin);
}
else
{
// Iterate over dir patterns.
for (unsigned argn=0; argn < inFileList.size(); argn++)
{
VerboseMsg() <<" Dir:" << inFileList[argn] << std::endl;
m_dirScan.Init(inFileList[argn].c_str(), NULL);
nFiles += m_dirScan.GetFilesInDirectory();
}
}
if (m_verbose)
{
// InfoMsg() << ";Matches:" << m_matchCnt << ", Files:" << m_countOutFiles << std::endl;
SetGrepColor(MATCH_COLOR);
LLMsg::Out() << ";Matches:" << m_matchCnt << ", MatchFiles:" << m_countOutFiles
<< ", ScanFiles:" << m_countInFiles
<< std::endl;
ResetGrepColor();
}
// Return status, c=file count, d=depth, s=size, a=age
if (m_exitOpts.length() != 0)
switch ((char)m_exitOpts[0u])
{
case 'a': // age, -0=a
{
FILETIME ltzFT;
SYSTEMTIME sysTime;
FileTimeToLocalFileTime(&m_fileData.ftLastWriteTime, <zFT); // convert UTC to local Timezone
FileTimeToSystemTime(<zFT, &sysTime);
// TODO - compare to local time and return age.
return 0;
}
break;
case 'm': // matchCnt -g=<grepPat>
VerboseMsg() << ";Matches:" << m_matchCnt << std::endl;
return (int)m_matchCnt;
case 's': // file size, -0=s
VerboseMsg() << ";Size:" << m_totalInSize << std::endl;
return (int)m_totalInSize;
// case 'd': // file depth, -o=d
// VerboseMsg() << ";Depth (-E=d depth currently not implemented,use -E=D for #directories):" << 0 << std::endl;
// return 0; // TODO - return maximum file depth.
// case 'D': // Directory count, -o=D
// VerboseMsg() << ";Directory Count:" << m_countOutDir << std::endl;
// return m_countOutDir;
case 'F': // File count, -o=F
VerboseMsg() << ";File Count:" << m_countOutFiles << std::endl;
return m_countOutFiles;
case 'l': // #lines
LLMsg::Out() << ";Line Count:" << m_lineCnt << std::endl;
break;
case 'L': // List of matching files
for (unsigned idx = 0; idx != m_matchFiles.size(); idx++)
LLMsg::Out() << m_matchFiles[idx] << std::endl;
return m_matchFiles.size();
case 'c': // File and directory count, -o=c
default:
VerboseMsg() << ";File + Directory Count:" << (m_countOutDir + m_countOutFiles) << std::endl;
return (int)(m_countOutDir + m_countOutFiles);
}
return ExitStatus(0);
}
// ---------------------------------------------------------------------------
int LLReplace::ProcessEntry(
const char* pDir,
const WIN32_FIND_DATA* pFileData,
int depth) // 0...n is directory depth, -n end-of nth diretory
{
if (depth < 0)
return sIgnore; // ignore end-of-directory
// Filter on:
// m_onlyAttr File or Directory, -F or -D
// m_onlyRhs Attributes, -A=rhs
// m_includeList File patterns, -F=<filePat>[,<filePat>]...
// m_onlySize File size, -Z op=(Greater|Less|Equal) value=num<units G|M|K>, ex -Zg100M
// m_excludeList Exclude path patterns, -X=<pathPat>[,<pathPat>]...
// m_timeOp Time, -T[acm]<op><value> ; Test Time a=access, c=creation, m=modified\n
//
// If pass, populate m_srcPath
if ( !FilterDir(pDir, pFileData, depth))
return sIgnore;
VerboseMsg() << m_srcPath << "\n";
if (m_isDir)
return sIgnore;
if (m_zipFile)
{
int matchStatus = ZipListArchive(m_srcPath);
if (matchStatus >= 0)
return matchStatus;
}
unsigned matchCnt = FindReplace(pFileData);
if ( matchCnt != 0)
m_matchFiles.push_back(m_srcPath);
#if 0
if (m_echo && !IsQuit())
{
if (m_showAttr)
{
// ShowAttributes(LLMsg::Out(), pDir, *pFileData, false);
LLMsg::Out() << LLReplace::sConfig.m_dirFieldSep;
}
if (m_showCtime)
LLSup::Format(LLMsg::Out(), pFileData->ftCreationTime) << LLReplace::sConfig.m_dirFieldSep ;
if (m_showMtime)
LLSup::Format(LLMsg::Out(), pFileData->ftLastWriteTime) << LLReplace::sConfig.m_dirFieldSep;
if (m_showAtime)
LLSup::Format(LLMsg::Out(), pFileData->ftLastAccessTime) << LLReplace::sConfig.m_dirFieldSep;
if (m_showSize)
LLMsg::Out() << std::setw(LLReplace::sConfig.m_fzWidth) << m_fileSize << LLReplace::sConfig.m_dirFieldSep;
LLMsg::Out() << m_srcPath << std::endl;
}
#endif
m_matchCnt += matchCnt;
m_fileData = *pFileData;
m_totalInSize += m_fileSize;
m_countInFiles++;
if (matchCnt != 0)
m_countOutFiles++;
return (matchCnt != 0) ? sOkay : sIgnore;
}
// ---------------------------------------------------------------------------
void LLReplace::OutFileLine(size_t lineNum, unsigned matchCnt, size_t filePos)
{
if (m_echo)
{
SetGrepColor(FILE_COLOR);
if (!m_grepOpt.hideFilename)
LLMsg::Out() << m_srcPath << ":";
if (lineNum != 0 && !m_grepOpt.hideLineNum)
LLMsg::Out() << lineNum << "L:";
if (matchCnt != 0 && !m_grepOpt.hideMatchCnt)
LLMsg::Out() << matchCnt << "M:";
if (filePos != 0 && !m_grepOpt.hideLineNum)
LLMsg::Out() << filePos << "P:";
ResetGrepColor();
if (m_grepOpt.hideText && !(m_grepOpt.hideFilename && m_grepOpt.hideLineNum && m_grepOpt.hideMatchCnt))
LLMsg::Out() << std::endl;
}
}
// ---------------------------------------------------------------------------
// Determine if input stream is binary.
class BinaryState
{
public:
size_t binaryCnt = 0;
size_t printCnt = 0;
const size_t minCnt = 1024;
bool isBinary(const std::string& str)
{
for (unsigned idx = 0; idx != str.length(); idx++)
{
char c = str[idx];
if (isprint(c) || c == '\r' || c == '\n' || c == '\t')
printCnt++;
else
binaryCnt++;
if (binaryCnt + printCnt > minCnt)
break;
}
return binaryCnt > printCnt;
}
bool isBinary(const char* strBeg, const char* strEnd)
{
while (strBeg != strEnd)
{
char c = *strBeg++;
if (isprint(c) || c == '\r' || c == '\n' || c == '\t')
printCnt++;
else
binaryCnt++;
if (binaryCnt + printCnt > minCnt)
break;
}
return binaryCnt > printCnt;
}
};
// ---------------------------------------------------------------------------
unsigned LLReplace::FindGrep()
{
unsigned matchCnt = 0;
if (!m_grepReplaceList.empty())
{
size_t lineCnt = 0;
try
{
if (m_byLine || m_grepReplaceList.size() > 1)
{
EnableFiltersForFile(m_srcPath);
int inMode = std::ios::in | std::ios::binary;
std::ifstream in(m_srcPath, inMode, _SH_DENYNO);
matchCnt += FindGrep(in);
}
else
{
std::regex_constants::match_flag_type flags =
std::regex_constants::match_flag_type(std::regex_constants::match_default
+ std::regex_constants::match_not_eol + std::regex_constants::match_not_bol);
BinaryState binaryState;
MemMapFile mapFile;
void* mapPtr;
SIZE_T viewLength = INT_MAX;
if (mapFile.Open(m_srcPath) && (mapPtr = mapFile.MapView(0, viewLength)) != NULL)
{
std::tr1::match_results <const char*> match;
const char* begPtr = (const char*)mapPtr;
const char* endPtr = begPtr + viewLength;
const char* strPtr = begPtr;
std::tr1::regex grepLinePat = m_grepReplaceList[0].m_grepLinePat;
if (binaryState.isBinary(strPtr, min(strPtr+256, endPtr)))
{
if (m_verbose)
LLMsg::Out() << "Ignore Binary\n";
return matchCnt;
}
while (std::tr1::regex_search(strPtr, endPtr, match, grepLinePat, flags))
{
matchCnt++;
const char* begLine = match.prefix().second;
while (begLine -1 >= begPtr && begLine[-1] != '\n')
begLine--;
const char* endLine = match.suffix().first;
while (*endLine != '\n' && endLine < endPtr)
endLine++;
if (m_echo)
{
OutFileLine(0, matchCnt);
if (!m_grepOpt.hideText)
{
do {
std::string prefix = std::string(begLine, match.prefix().second);
// std::string suffix = std::string(match.suffix().first, endLine);;
LLMsg::Out() << prefix;
SetGrepColor(MATCH_COLOR);
LLMsg::Out() << match.str();
ResetGrepColor();
begLine = strPtr = match.suffix().first;
} while (std::tr1::regex_search(strPtr, endLine, match, grepLinePat, flags));
std::string suffix = std::string(match.suffix().first, endLine);
LLMsg::Out() << suffix << std::endl;
}
}
strPtr = endLine;
if (matchCnt >= m_grepOpt.matchCnt)
break;
}
}
else
{
LLMsg::PresentError(GetLastError(), "Open failed,", m_srcPath);
}
}
}
catch (...)
{
}
m_lineCnt += lineCnt;
}
return matchCnt;
}
// ---------------------------------------------------------------------------
struct ColorInfo
{
uint len;
WORD color;
ColorInfo() :
len(0), color(0)
{ }
ColorInfo(uint _len, WORD _color) :
len(_len), color(_color)
{ }
};
typedef std::map<uint, ColorInfo> ColorMap;
// ---------------------------------------------------------------------------
unsigned LLReplace::FindGrep(std::istream& in)
{
unsigned matchCnt = 0;
unsigned lineCnt = 0;
std::tr1::smatch match;
std::regex_constants::match_flag_type flags = std::regex_constants::match_default;
std::vector<string> beforeLines(m_grepOpt.beforeCnt);
unsigned addBeforeIdx = 0;
unsigned afterLines = 0;
BinaryState binaryState;
std::string str;
while (std::getline(in, str))
{
lineCnt++;
if (binaryState.isBinary(str))
{
if (m_verbose)
LLMsg::Out() << "Ignore Binary\n";
return matchCnt;
}
// All patterns have to match for the line to match.
ColorMap colorMap;
unsigned itemMatchCnt = 0;
std::tr1::regex grepLinePat;
for (unsigned patIdx = 0; patIdx != m_grepReplaceList.size(); patIdx++)
{
GrepReplaceItem& grepRepItem = m_grepReplaceList[patIdx];
if (grepRepItem.m_enabled)
{
bool itemMatches = false;
grepLinePat = grepRepItem.m_grepLinePat;
std::string replaceStr = grepRepItem.m_replaceStr;
if (grepRepItem.m_replace)
{
// Loop to get multiple matches on a line.
size_t off = 0;
do
{
std::string::const_iterator begIter = str.begin();
std::string::const_iterator endIter = str.end();
std::advance(begIter, off);
if (begIter < endIter &&
std::tr1::regex_search(begIter, endIter, match, grepLinePat, flags|std::regex_constants::format_first_only))
{
std::string subStr = str.substr(off);
std::string newStr = std::regex_replace(subStr, grepLinePat, replaceStr, flags|std::regex_constants::format_first_only);
int repLen = match.length() + newStr.length() - str.length();
if (newStr != subStr)
{
// str.swap(newStr);
unsigned begPos = off + match.position();
str.replace(begPos, str.length() - begPos, newStr, match.position(), newStr.length() - match.position());
itemMatches = true;
if (repLen > 0)
colorMap[(uint)match.position()] = ColorInfo((uint)repLen, MATCH_COLORS[patIdx % ARRAYSIZE(MATCH_COLORS)]);
else
colorMap[0] = ColorInfo(str.length(), MATCH_COLORS[patIdx % ARRAYSIZE(MATCH_COLORS)]);
// std::advance (begIter, grepLinePat.length());
// off += grepLinePat.length();
off += match.position() + 1;
} else
off = 0;
} else
off = 0;
} while (off != 0);
}
else if (grepRepItem.m_onMatch)
{
// Loop to get multiple matches on a line.
std::string::const_iterator begIter = str.begin();
std::string::const_iterator endIter = str.end();
size_t off = 0;
while (off < str.length() &&
std::tr1::regex_search(begIter, endIter, match, grepLinePat, flags))
{
itemMatches = true;
colorMap[uint(match.position() + off)] = ColorInfo((uint)match.length(), MATCH_COLORS[patIdx % ARRAYSIZE(MATCH_COLORS)]);
std::advance (begIter, match.length());
off += match.length();
}
}
else
{
// Reverse match
if (std::tr1::regex_search(str, match, grepLinePat, flags) == false)
{
itemMatches = true;
if (m_grepReplaceList.size() == 1)
colorMap[0] = ColorInfo(str.length(), MATCH_COLORS[patIdx % ARRAYSIZE(MATCH_COLORS)]);
}
}
if (itemMatches)
itemMatchCnt++;
}
}
if (m_allMustMatch && itemMatchCnt != m_grepReplaceList.size())
colorMap.clear();
else if (m_allMustMatch && colorMap.size() == 0)
LLMsg::Out() << str << std::endl;
if (colorMap.size() != 0)
{
matchCnt++;
if (m_echo)
{
if (m_width != 0)
{
// Clamp output to user desired width.
for (ColorMap::iterator iter = colorMap.begin(); iter != colorMap.end(); iter++)
iter->second.len = min(iter->second.len, (uint)m_width);
}
OutFileLine(lineCnt, matchCnt);
if (!m_grepOpt.hideText)
{
afterLines = m_grepOpt.afterCnt;
for (unsigned bidx = 0; bidx != beforeLines.size(); bidx++)
{
std::string beforeStr = beforeLines[(bidx + addBeforeIdx) % m_grepOpt.beforeCnt];
if (beforeStr.length() != 0)
LLMsg::Out() << beforeStr << std::endl;
}
ColorMap::const_iterator iter = colorMap.begin();
uint pos = 0;
const char* cstr = str.c_str();
while (iter != colorMap.end())
{
if (iter->first >= pos)
{
LLMsg::Out().write(cstr + pos, iter->first - pos);
pos = iter->first;
SetGrepColor(iter->second.color);
LLMsg::Out().write(cstr + iter->first, iter->second.len);
ResetGrepColor();
pos = iter->first + iter->second.len;
}
iter++;
}
LLMsg::Out() << (cstr + pos);
LLMsg::Out() << std::endl;
}
}
if (matchCnt >= m_grepOpt.matchCnt)
break;
}
else if (afterLines != 0)
{
if (!m_grepOpt.hideText)
LLMsg::Out() << str << std::endl;
afterLines--;
}
if (m_grepOpt.beforeCnt > 0)
beforeLines[addBeforeIdx++ % m_grepOpt.beforeCnt] = str;
str.clear();
}
m_lineCnt += lineCnt;
return matchCnt;
}
// ---------------------------------------------------------------------------
void LLReplace::EnableFiltersForFile(const std::string& filePath)
{
std::tr1::smatch match;
std::regex_constants::match_flag_type flags = std::regex_constants::match_default;
for (unsigned patIdx = 0; patIdx != m_grepReplaceList.size(); patIdx++)
{
GrepReplaceItem& item = m_grepReplaceList[patIdx];
item.m_enabled = !item.m_haveFilePat || std::tr1::regex_match(filePath, match, item.m_filePathPat, flags);
}
}
// ---------------------------------------------------------------------------
void LLReplace::ColorizeReplace(const std::string& str)
{
ColorMap colorMap;
std::string replaceStr;
for (unsigned patIdx = 0; patIdx != m_grepReplaceList.size(); patIdx++)
{
if (m_grepReplaceList[patIdx].m_enabled)
{
replaceStr = m_grepReplaceList[patIdx].m_replaceStr;
if (replaceStr.length() != 0)
{
int pos = -1;
while ((pos = (int)str.find(replaceStr, pos+1)) != (int)std::string::npos)
{
colorMap[pos] = ColorInfo(replaceStr.length(), MATCH_COLORS[patIdx % ARRAYSIZE(MATCH_COLORS)]);
}
}
}
}
if (colorMap.size() != 0)
{
ColorMap::const_iterator iter = colorMap.begin();
uint pos = 0;
const char* cstr = str.c_str();
while (iter != colorMap.end())
{
if (iter->first >= pos)
{
LLMsg::Out().write(cstr + pos, iter->first - pos);
pos = iter->first;
SetGrepColor(iter->second.color);
LLMsg::Out().write(cstr + iter->first, iter->second.len);
ResetGrepColor();
pos = iter->first + iter->second.len;
}
iter++;
}
LLMsg::Out() << (cstr + pos);
}
}
// ---------------------------------------------------------------------------
unsigned LLReplace::FindReplace(const WIN32_FIND_DATA* pFileData)
{
if (pFileData->nFileSizeLow == 0 && pFileData->nFileSizeHigh == 0)
return 0;
if (m_grepReplaceList[0].m_replace == false)
return FindGrep();
unsigned matchCnt = 0;
// U(i|b) Update inplace or make backup.
bool okayToWrite = (m_grepOpt.update != 'i') || (m_force || LLPath::IsWriteable(pFileData->dwFileAttributes));
if (okayToWrite)
{
std::regex_constants::match_flag_type flags = std::regex_constants::match_default;
size_t lineCnt = 0;
try
{
int inMode = std::ios::in | std::ios::binary;
if (m_byLine || m_grepReplaceList.size() > 1)
{
EnableFiltersForFile(m_srcPath);
// ----- Find and Replace by line -----
std::tr1::smatch match;
std::ifstream in(m_srcPath, inMode, _SH_DENYNO);
std::ofstream out;
std::streampos inPos = in.tellg();
std::string str;
while (std::getline(in, str))
{
lineCnt++;
if (lineCnt < m_grepOpt.lineCnt)
{
for (unsigned patIdx = 0; patIdx != m_grepReplaceList.size(); patIdx++)
{
if (m_grepReplaceList[patIdx].m_enabled)
{
std::tr1::regex grepLinePat = m_grepReplaceList[patIdx].m_grepLinePat;
if (std::tr1::regex_search(str, match, grepLinePat, flags))
{
std::string replaceStr = m_grepReplaceList[patIdx].m_replaceStr;
matchCnt++;
if (matchCnt == 1)
OpenOutput(out, in, inPos);
std::string newStr = std::regex_replace(str, grepLinePat, replaceStr, flags);
str.swap(newStr);
if (m_echo)
{
OutFileLine(lineCnt, matchCnt);
if (!m_grepOpt.hideText)
{
ColorizeReplace(str);
LLMsg::Out() << std::endl;
}
}
if (matchCnt >= m_grepOpt.matchCnt)
break;
}
}
}
}
else if (!out)
{
break;
}
if (out)
out << str << std::endl;
inPos = in.tellg();
}
in.close();
if (out)
{
out.close();
BackupAndRenameFile();
}
}
else
{
// ----- Find and Replace by memory mapped file -----
bool didReplace;
do {
didReplace = false;
std::ifstream in;
std::streampos inPos(0);
std::ofstream out;
MemMapFile mapFile;
void* mapPtr;
SIZE_T viewLength = INT_MAX;
if (mapFile.Open(m_srcPath) && (mapPtr = mapFile.MapView(0, viewLength)) != NULL)
{
std::tr1::match_results <const char*> match;
const char* begPtr = (const char*)mapPtr;
const char* endPtr = begPtr + viewLength;
const char* strPtr = begPtr;
std::tr1::regex grepLinePat = m_grepReplaceList[0].m_grepLinePat;
std::string replaceStr = m_grepReplaceList[0].m_replaceStr;
if (std::tr1::regex_search(strPtr, endPtr, match, grepLinePat, flags))
{
matchCnt++;
didReplace = true;
if (m_echo)
{
OutFileLine(lineCnt, matchCnt, match.position(0));
if (!m_grepOpt.hideText)
LLMsg::Out() << std::endl;
}
OpenOutput(out, in, inPos);
out.write(begPtr, match.position(0));
begPtr = (const char*)mapPtr;
begPtr += match.position(0);
std::regex_replace(
std::ostreambuf_iterator<char>(out),
begPtr,
endPtr,
grepLinePat, replaceStr, flags);
mapFile.Close();
if (out)
{
out.close();
if (!BackupAndRenameFile())
break;
}
}
}
else
{
LLMsg::PresentError(GetLastError(), "Open failed,", m_srcPath);
}
} while (didReplace && m_grepOpt.repeatReplace);
}
}
catch (...)
{
}
}
else
{
LLMsg::PresentError(0, "Replace ignored,", pFileData->cFileName, " Not writeable\n");
}
return matchCnt;
}
// ---------------------------------------------------------------------------
bool LLReplace::BackupAndRenameFile()
{
// U(i|b) Update inplace or make backup.
if (m_grepOpt.update == 'b')
{
int error = rename(m_srcPath, (m_srcPath + ".bak").c_str());
if (error != 0)
{
LLMsg::PresentError(GetLastError(), "Failed to make backup\n", m_srcPath);
RemoveTmpFile();
return false;
}
}
if (!m_tmpOutFilename.empty() && m_tmpOutFilename != m_srcPath)
{
// int error = renameFiles(m_tmpOutFilename.c_str(), m_srcPath.c_str());
if (0 == MoveFileEx(m_tmpOutFilename.c_str(), m_srcPath.c_str(), MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING))
{
DWORD lastError = GetLastError();
LLMsg::PresentError(lastError, "Renaming tmp failed\n", m_srcPath);
RemoveTmpFile();
return false;
}
}
return true;
}
// ---------------------------------------------------------------------------
void LLReplace::RemoveTmpFile()
{
if (m_tmpOutFilename != m_srcPath)
DeleteFile(m_tmpOutFilename.c_str());
}
// ---------------------------------------------------------------------------
std::ofstream& LLReplace::OpenOutput(
std::ofstream& out, std::ifstream& in, std::streampos& inPos)
{
int outMode = std::ios::out | std::ios::binary;
// U(i|b) Update inplace or make backup.
if (m_grepOpt.update == 'i')
{
m_tmpOutFilename = m_srcPath;
out.open(m_srcPath, outMode, _SH_DENYNO);
out.seekp(inPos);
}
else
{
m_tmpOutFilename = m_srcPath + "_tmp_XXXXXX";
m_tmpOutFilename.push_back('\0');
_mktemp_s((char*)m_tmpOutFilename.c_str(), m_tmpOutFilename.length());
out.open(m_tmpOutFilename, outMode, _SH_DENYNO);
}
streamoff inOff = inPos;
if (out && in && inOff > 0)
{
size_t inLen = (size_t)inOff;
m_tmpBuffer.resize(min(8192, inLen));
std::streamsize inCnt = 1;
while (inLen > 0 && inCnt > 0)
{
inCnt = in.read(m_tmpBuffer.data(), m_tmpBuffer.size()).gcount();
if (inCnt > 0)
{
out.write(m_tmpBuffer.data(), inCnt);
inLen -= (size_t)inCnt;
m_tmpBuffer.resize(min(8192, inLen));
}
}
}
return out;
}
// ---------------------------------------------------------------------------
void LLReplace::ResetGrepColor()
{
if (!m_grepOpt.hideColor)
SetColor(sConfig.m_colorNormal);
}
// ---------------------------------------------------------------------------
void LLReplace::SetGrepColor(WORD color)
{
if (!m_grepOpt.hideColor)
SetColor(color);
} | 34.624422 | 145 | 0.487285 |
bbfee8b354473cc0810a75cd95d35b2a0f88ad3c | 169 | hpp | C++ | src/uproar/config/version.hpp | tiger-chan/lib-gradient-noise | 66eb8186b10f7507b437a81a4c6be16fcad5ccaf | [
"MIT"
] | null | null | null | src/uproar/config/version.hpp | tiger-chan/lib-gradient-noise | 66eb8186b10f7507b437a81a4c6be16fcad5ccaf | [
"MIT"
] | null | null | null | src/uproar/config/version.hpp | tiger-chan/lib-gradient-noise | 66eb8186b10f7507b437a81a4c6be16fcad5ccaf | [
"MIT"
] | null | null | null | #ifndef UPROAR_CONFIG_VERSION_HPP
#define UPROAR_CONFIG_VERSION_HPP
#define UPROAR_VERSION_MAJOR 0
#define UPROAR_VERSION_MINOR 1
#define UPROAR_VERSION_PATCH 0
#endif | 21.125 | 33 | 0.87574 |
bbffb946d5ad4823637f463fcf7240bff13b2bc7 | 1,736 | cpp | C++ | src/MapEditor/Controls/ResourcePreview.cpp | vitek-karas/WarPlusPlus | 3abb26ff30dc0e93de906ab6141b89c2fa301ae4 | [
"MIT"
] | 4 | 2019-06-17T13:44:49.000Z | 2021-01-19T10:39:48.000Z | src/MapEditor/Controls/ResourcePreview.cpp | vitek-karas/WarPlusPlus | 3abb26ff30dc0e93de906ab6141b89c2fa301ae4 | [
"MIT"
] | null | null | null | src/MapEditor/Controls/ResourcePreview.cpp | vitek-karas/WarPlusPlus | 3abb26ff30dc0e93de906ab6141b89c2fa301ae4 | [
"MIT"
] | 4 | 2019-06-17T16:03:20.000Z | 2020-02-15T09:14:30.000Z | // ResourcePreview.cpp : implementation file
//
#include "stdafx.h"
#include "..\MapEditor.h"
#include "ResourcePreview.h"
#include "Common\Map\Map.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CResourcePreview
CResourcePreview::CResourcePreview()
{
m_pResource = NULL;
}
CResourcePreview::~CResourcePreview()
{
}
BEGIN_MESSAGE_MAP(CResourcePreview, CStatic)
//{{AFX_MSG_MAP(CResourcePreview)
ON_WM_DESTROY()
ON_WM_PAINT()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CResourcePreview message handlers
void CResourcePreview::Create(CRect &rcBound, DWORD dwStyle, CWnd *pParent, UINT nID)
{
m_Buffer.SetWidth(RESOURCE_ICON_WIDTH);
m_Buffer.SetHeight(RESOURCE_ICON_HEIGHT);
m_Buffer.Create();
CStatic::Create("", dwStyle, rcBound, pParent, nID);
m_Clipper.Create(this);
}
void CResourcePreview::SetResource(CEResource *pResource)
{
m_pResource = pResource;
Invalidate();
}
void CResourcePreview::OnDestroy()
{
CStatic::OnDestroy();
m_Buffer.Delete();
m_Clipper.Delete();
}
void CResourcePreview::OnPaint()
{
CPaintDC dc(this); // device context for painting
g_pDDPrimarySurface->SetClipper(&m_Clipper);
CRect rcClient;
GetClientRect(&rcClient);
CBrush brush;
brush.CreateSolidBrush(RGB(192, 192, 192));
dc.FillRect(&rcClient, &brush);
brush.DeleteObject();
ClientToScreen(&rcClient);
if(m_pResource != NULL){
m_Buffer.Fill(RGB32(192, 192, 192));
m_Buffer.Paste(0, 0, m_pResource->GetIcon());
g_pDDPrimarySurface->Paste(rcClient.TopLeft(), &m_Buffer);
}
}
| 21.170732 | 85 | 0.667051 |
0101c7cc5a35666aa58f8b361d345d6940eb6749 | 562 | cpp | C++ | dlls/wined3d/dxvk/dxvk.cpp | berarma/wine | 213905a322620eb326b655ab89fbca07316e6357 | [
"MIT"
] | 1 | 2020-03-02T14:44:56.000Z | 2020-03-02T14:44:56.000Z | dlls/wined3d/dxvk/dxvk.cpp | berarma/wine | 213905a322620eb326b655ab89fbca07316e6357 | [
"MIT"
] | null | null | null | dlls/wined3d/dxvk/dxvk.cpp | berarma/wine | 213905a322620eb326b655ab89fbca07316e6357 | [
"MIT"
] | null | null | null | /* C-lang interface to DXVK's C++ implementation */
#include "config.h"
extern "C" {
#include "dxvk.h"
void dxvk_get_options(struct DXVKOptions *opts)
{
dxvk::Config config(dxvk::Config::getUserConfig());
config.merge(dxvk::Config::getAppConfig(dxvk::getExePath()));
opts->nvapiHack = config.getOption<bool>("dxgi.nvapiHack", true) ? 1 : 0;
opts->customVendorId = dxvk::parsePciId(config.getOption<std::string>("dxgi.customVendorId"));
opts->customDeviceId = dxvk::parsePciId(config.getOption<std::string>("dxgi.customDeviceId"));
}
}
| 26.761905 | 98 | 0.702847 |
0101e91b7672bcb40bcd0c23fffae67aab0ac75b | 1,013 | cpp | C++ | Examples/HttpRequest/HttpRequest.cpp | Rprop/RLib | bb94d51d69a2207b073a779a871336288ca733d1 | [
"Unlicense"
] | 23 | 2018-04-23T15:46:24.000Z | 2022-01-10T14:03:57.000Z | Examples/HttpRequest/HttpRequest.cpp | boyliang/RLib | bb94d51d69a2207b073a779a871336288ca733d1 | [
"Unlicense"
] | 1 | 2017-07-24T05:13:03.000Z | 2017-07-24T08:59:48.000Z | Examples/HttpRequest/HttpRequest.cpp | boyliang/RLib | bb94d51d69a2207b073a779a871336288ca733d1 | [
"Unlicense"
] | 13 | 2018-05-11T15:53:12.000Z | 2021-09-29T11:57:16.000Z | /********************************************************************
Created: 2016/07/18 19:15
Filename: HttpRequest.cpp
Author: rrrfff
Url: http://blog.csdn.net/rrrfff
*********************************************************************/
#include <RLib_Import.h>
//-------------------------------------------------------------------------
int __stdcall WinMain(__in HINSTANCE /*hInstance*/, __in_opt HINSTANCE /*hPrevInstance*/,
__in LPSTR /*lpCmdLine*/, __in int /*nShowCmd*/)
{
// WebClient is a wrapper class for HttpRequest/HttpResponse,
// and platform-independent in a sense.
// performs a HTTP GET request and gets response as string
String page = WebClient::GetResponseText(_R("http://rlib.cf/"));
// also, HTTPS/SSL is supported.
String ssl_page = WebClient::GetResponseText(_R("https://www.alipay.com/"));
// performs a HTTP POST request with string data
String post_page = WebClient::PostResponseText(_R("http://rlib.cf/"), _R("post data"));
return STATUS_SUCCESS;
} | 37.518519 | 89 | 0.564659 |
0103f8b329e5a819235bf2666b085c39756a107b | 411 | cpp | C++ | enduser/zone_internetgames/src/client/shell/zonecli/debug.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | enduser/zone_internetgames/src/client/shell/zonecli/debug.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | enduser/zone_internetgames/src/client/shell/zonecli/debug.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | #include "zui.h"
#ifdef _DEBUG
#undef CreatePen
#undef CreateSolidBrush
HPEN MyCreatePen(int fnPenStyle, int nWidth, COLORREF crColor)
{
HPEN hPen = CreatePen(fnPenStyle, nWidth, crColor);
if (!hPen) {
_asm {int 3};
}
return hPen;
}
HBRUSH MyCreateSolidBrush(COLORREF crColor)
{
HBRUSH hBr = CreateSolidBrush(crColor);
if (!hBr) {
_asm {int 3};
}
return hBr;
}
#endif
| 15.222222 | 63 | 0.659367 |
010667525fb6e5965c1a1815abb558c4e033d42a | 574 | hpp | C++ | src/menu.hpp | matyalatte/2dPolyTo3d | be5ed4e871bd65c704ff12664f44e1aae5c89b24 | [
"MIT"
] | null | null | null | src/menu.hpp | matyalatte/2dPolyTo3d | be5ed4e871bd65c704ff12664f44e1aae5c89b24 | [
"MIT"
] | null | null | null | src/menu.hpp | matyalatte/2dPolyTo3d | be5ed4e871bd65c704ff12664f44e1aae5c89b24 | [
"MIT"
] | null | null | null | /*
* File: menu.hpp
* --------------------
* @author Matyalatte
* @version 2021/09/14
* - initial commit
*/
#pragma once
#include <GL/glut.h>
#include "2dpoly_to_3d/2dpoly_to_3d.hpp"
#include "2dpoly_to_3d/utils.hpp"
namespace openglHandler {
//functions for popup menu in glut
void menu(int item);
void menuInit();
void checkUpdateMenu();
void connectPolyTo3D(sketch3D::poly_to_3D* p_to_3d);
bool getSetModelFlag();
void resetSetModelFlag();
bool getShowNormal();
bool getShow2DPoly();
bool getShowModel();
bool getExitFlag();
void resetExitFlag();
} | 19.133333 | 53 | 0.698606 |
01069effde8f24ee53ea22b955062e516f748cc6 | 551 | hpp | C++ | libadb/include/libadb/api/rate/data/rate-limit-scope.hpp | faserg1/adb | 65507dc17589ac6ec00caf2ecd80f6dbc4026ad4 | [
"MIT"
] | 1 | 2022-03-10T15:14:13.000Z | 2022-03-10T15:14:13.000Z | libadb/include/libadb/api/rate/data/rate-limit-scope.hpp | faserg1/adb | 65507dc17589ac6ec00caf2ecd80f6dbc4026ad4 | [
"MIT"
] | 9 | 2022-03-07T21:00:08.000Z | 2022-03-15T23:14:52.000Z | libadb/include/libadb/api/rate/data/rate-limit-scope.hpp | faserg1/adb | 65507dc17589ac6ec00caf2ecd80f6dbc4026ad4 | [
"MIT"
] | null | null | null | #pragma once
#include <libadb/libadb.hpp>
#include <string>
namespace adb::api
{
/**
* @brief Rate Limit Scope
* @details https://discord.com/developers/docs/topics/rate-limits#header-format
*/
enum class RateLimitScope
{
/// per bot or user limit
User,
/// per bot or user global limit
Global,
/// per resource limit
Shared
};
LIBADB_API void from_string(const std::string &str, RateLimitScope &limit);
LIBADB_API std::string to_string(RateLimitScope limit);
} | 22.958333 | 84 | 0.627949 |
010bb5f3e0d991ec046b566798542dabef4e5cdf | 5,071 | cpp | C++ | dev/velocities_sidecar/VelocitySideCar.cpp | nyue/SegmentedInterpolativeMotionBlurAlembic | 1f02ff5516b6e114410b5977885133bb4b5bb490 | [
"Apache-2.0"
] | 1 | 2020-12-28T23:33:00.000Z | 2020-12-28T23:33:00.000Z | dev/velocities_sidecar/VelocitySideCar.cpp | nyue/SegmentedInterpolativeMotionBlurAlembic | 1f02ff5516b6e114410b5977885133bb4b5bb490 | [
"Apache-2.0"
] | null | null | null | dev/velocities_sidecar/VelocitySideCar.cpp | nyue/SegmentedInterpolativeMotionBlurAlembic | 1f02ff5516b6e114410b5977885133bb4b5bb490 | [
"Apache-2.0"
] | 1 | 2018-10-10T11:49:02.000Z | 2018-10-10T11:49:02.000Z | #include "VelocitySideCar.h"
#include <boost/tokenizer.hpp>
#include <cryptopp/sha.h>
#include <cryptopp/hex.h>
#include <cryptopp/files.h>
VelocitySideCar::VelocitySideCar()
{
}
VelocitySideCar::~VelocitySideCar()
{
}
const std::string& VelocitySideCar::get_sha() const
{
return _source_sha;
};
bool VelocitySideCar::compute(const std::string& i_alembic_source, const std::string& i_regex_pattern)
{
compute_sha(i_alembic_source, _source_sha);
Alembic::AbcCoreFactory::IFactory factory;
Alembic::AbcCoreFactory::IFactory::CoreType oType;
_archive_ptr.reset(new Alembic::Abc::IArchive(factory.getArchive(i_alembic_source, oType)));
Alembic::Abc::IObject top = _archive_ptr->getTop();
size_t top_num_children = top.getNumChildren();
std::cout << "top_num_children = " << top_num_children << std::endl;
std::string top_name = top.getName();
std::cout << "top_name = " << top_name << std::endl;
PathList path;
TokenizePath( std::string("/grid_object1/grid1"), path );
PathList::const_iterator I = path.begin();
const Alembic::Abc::ObjectHeader *nextChildHeader = top.getChildHeader (*I);
for ( size_t i = 0; i < top.getNumChildren(); ++i )
{
iterate_iobject( top, top.getChildHeader(i),i_regex_pattern, I+1,path.end());
}
return true;
}
void VelocitySideCar::ProcessIPolyMesh(const Alembic::AbcGeom::IPolyMesh& i_polymesh,
const std::string& i_regex_pattern)
{
// Alembic::Abc::ISampleSelector next_sample_selector(requested_index+1);
//
// Alembic::AbcGeom::IPolyMeshSchema::Sample next_sample;
// pmesh.getSchema().get( next_sample, next_sample_selector );
}
void VelocitySideCar::iterate_iobject(Alembic::Abc::IObject parent,
const Alembic::Abc::ObjectHeader& ohead,
const std::string& i_regex_pattern,
PathList::const_iterator I,
PathList::const_iterator E)
{
std::cout << "iterate_iobject ohead's name = " << ohead.getName().c_str() << std::endl;
std::cout << "iterate_iobject ohead's full name = " << ohead.getFullName().c_str() << std::endl;
//set this if we should continue traversing
Alembic::Abc::IObject nextParentObject;
if ( Alembic::AbcGeom::IXform::matches( ohead ) )
{
std::cout << "iterate_iobject match IXform" << std::endl;
Alembic::AbcGeom::IXform xform( parent, ohead.getName() );
nextParentObject = xform;
}
else if ( Alembic::AbcGeom::ISubD::matches( ohead ) )
{
std::cout << "iterate_iobject match ISubD" << std::endl;
Alembic::AbcGeom::ISubD subd( parent, ohead.getName() );
nextParentObject = subd;
}
else if ( Alembic::AbcGeom::IPolyMesh::matches( ohead ) )
{
std::cout << "iterate_iobject match IPolyMesh" << std::endl;
Alembic::AbcGeom::IPolyMesh polymesh( parent, ohead.getName() );
ProcessIPolyMesh(polymesh, i_regex_pattern);
nextParentObject = polymesh;
}
else if ( Alembic::AbcGeom::INuPatch::matches( ohead ) )
{
std::cout << "iterate_iobject match INuPatch" << std::endl;
}
else if ( Alembic::AbcGeom::IPoints::matches( ohead ) )
{
std::cout << "iterate_iobject match IPoints" << std::endl;
Alembic::AbcGeom::IPoints points( parent, ohead.getName() );
// ProcessIPoints(points);
nextParentObject = points;
}
else if ( Alembic::AbcGeom::ICurves::matches( ohead ) )
{
std::cout << "iterate_iobject match ICurves" << std::endl;
}
else if ( Alembic::AbcGeom::IFaceSet::matches( ohead ) )
{
std::cout << "iterate_iobject match IFaceSet" << std::endl;
std::cerr << "DOH !" << std::endl;
}
// Recursion
if ( nextParentObject.valid() )
{
for ( size_t i = 0; i < nextParentObject.getNumChildren() ; ++i )
{
iterate_iobject( nextParentObject, nextParentObject.getChildHeader( i ), i_regex_pattern, I, E);
}
}
}
void VelocitySideCar::TokenizePath( const std::string &path, PathList& result ) const
{
typedef boost::char_separator<char> Separator;
typedef boost::tokenizer<Separator> Tokenizer;
Tokenizer tokenizer( path, Separator( "/" ) );
for ( Tokenizer::iterator iter = tokenizer.begin() ; iter != tokenizer.end() ;
++iter )
{
if ( (*iter).empty() )
{
continue;
}
std::cout << "*iter = " << *iter << std::endl;
result.push_back( *iter );
}
}
void compute_sha(const std::string& i_filename, std::string& o_sha)
{
CryptoPP::SHA1 hash;
CryptoPP::FileSource(i_filename.c_str(),true,
new CryptoPP::HashFilter(hash, new CryptoPP::HexEncoder(
new CryptoPP::StringSink(o_sha), true)));
}
// == Emacs ================
// -------------------------
// Local variables:
// tab-width: 4
// indent-tabs-mode: t
// c-basic-offset: 4
// end:
//
// == vi ===================
// -------------------------
// Format block
// ex:ts=4:sw=4:expandtab
// -------------------------
| 30.733333 | 108 | 0.622165 |
010f361df1b18f8efcd37aec4d5169dcb9350ed1 | 5,117 | cpp | C++ | src/Snake.cpp | robifr/snake | 611c6cc0460a92cca7e033108be13510aeba6b69 | [
"MIT"
] | null | null | null | src/Snake.cpp | robifr/snake | 611c6cc0460a92cca7e033108be13510aeba6b69 | [
"MIT"
] | null | null | null | src/Snake.cpp | robifr/snake | 611c6cc0460a92cca7e033108be13510aeba6b69 | [
"MIT"
] | null | null | null | #include <cmath> //floor
#include "Snake.hpp"
#include "Game.hpp"
#include "View.hpp"
Snake::Snake(Game& game) :
game_(game) {
}
void Snake::changeDirection(int keyCode) {
int deltaX = 0, deltaY = 0;
switch (keyCode) {
case SDLK_UP:
case SDLK_w:
deltaX = 0;
deltaY = -this->game_.gridHeight;
break;
case SDLK_DOWN:
case SDLK_s:
deltaX = 0;
deltaY = this->game_.gridHeight;
break;
case SDLK_LEFT:
case SDLK_a:
deltaX = -this->game_.gridWidth;
deltaY = 0;
break;
case SDLK_RIGHT:
case SDLK_d:
deltaX = this->game_.gridWidth;
deltaY = 0;
break;
default: return;
}
const bool isTryingToMoveDownWhileMovingUp = deltaY > this->deltaY_ && this->deltaY_ < 0;
const bool isTryingToMoveUpWhileMovingDown = deltaY < this->deltaY_ && this->deltaY_ >= 0;
const bool isTryingToMoveRightWhileMovingLeft = deltaX > this->deltaY_ && this->deltaX_ < 0;
const bool isTryingToMoveLeftWhileMovingRight = deltaX < this->deltaX_ && this->deltaX_ >= 0;
//disallow snake to move towards their current opposite direction.
//e.g. if the snake is currently moving up, user shouldn't be able to move down, and vice versa.
if (!isTryingToMoveUpWhileMovingDown
|| !isTryingToMoveDownWhileMovingUp
|| !isTryingToMoveLeftWhileMovingRight
|| !isTryingToMoveRightWhileMovingLeft) {
//compute next head position ahead before doing movement.
//ensuring the head won't eat its own neck,
//because of user changing direction way too fast.
if (this->body_.size() >= 1) {
std::pair<int, int> nextPosition = this->nextHeadPosition_(deltaX, deltaY);
if (nextPosition.first == this->body_[1].x
&& nextPosition.second == this->body_[1].y) {
return;
}
}
this->deltaX_ = deltaX;
this->deltaY_ = deltaY;
}
}
void Snake::move() {
for (int i = this->body_.size() - 1; i >= 0; i--) {
//snake head.
if (i == 0) {
std::pair<int, int> position = this->nextHeadPosition_(this->deltaX_, this->deltaY_);
this->body_[i].x = position.first;
this->body_[i].y = position.second;
if (this->isEatingOwnBody_(this->body_[i].x, this->body_[i].y)) this->isAlive = false;
if (this->isEatingFood_(this->body_[i].x, this->body_[i].y, this->game_.food)) {
this->foodEaten_++;
this->addBody(
this->body_.back().x + this->deltaX_,
this->body_.back().y + this->deltaY_
);
this->game_.inGameView->setScore(this->foodEaten_);
this->game_.food->spawnRandom();
i--;
}
//every snake body follow their previous segment position.
} else if (i > 0) {
this->body_[i].x = this->body_[i - 1].x;
this->body_[i].y = this->body_[i - 1].y;
}
}
}
void Snake::addBody(int x, int y) {
SDL_Rect newBody = { x, y, this->game_.gridWidth, this->game_.gridHeight };
this->body_.push_back(newBody);
}
void Snake::respawn() {
const int gridWidth = this->game_.gridWidth;
const int gridHeight = this->game_.gridHeight;
const int x = std::floor(this->game_.windowSurface->w / 2 / gridWidth) * gridWidth;
const int y = std::floor(this->game_.windowSurface->h / 2 / gridHeight) * gridHeight;
this->deltaX_ = 0;
this->deltaY_ = -15; //move to top as the default position.
this->foodEaten_ = 0;
this->body_.clear();
for (int i = 0; i < 3; i++) {
this->addBody(x, y + (gridHeight * i));
}
}
void Snake::render() {
for (int i = 0; i < this->body_.size(); i++) {
SDL_SetRenderDrawColor(this->game_.renderer().get(), 220, 20, 60, 225); //red.
SDL_RenderFillRect(this->game_.renderer().get(), &this->body_[i]);
}
}
bool Snake::isEatingFood_(int x, int y, const std::unique_ptr<Food>& food) {
if (x == food->body().x && y == food->body().y) return true;
return false;
}
bool Snake::isEatingOwnBody_(int x, int y) {
for (int i = 1; i < this->body_.size(); i++) {
if (x == this->body_[i].x
&& y == this->body_[i].y) {
return true;
}
}
return false;
}
std::pair<int, int> Snake::nextHeadPosition_(int deltaX, int deltaY) {
const int yMin = this->game_.inGameView->scoreContainer.h;
const int xMax = this->game_.windowSurface->w - this->game_.gridWidth;
const int yMax = this->game_.windowSurface->h - this->game_.gridHeight;
int x = this->body_[0].x + deltaX;
int y = this->body_[0].y + deltaY;
if (x > xMax) {
x = 0;
} else if (x < 0) {
x = xMax;
}
if (y > yMax) {
y = yMin;
} else if (y < yMin) {
y = yMax;
}
return std::make_pair(x, y);
} | 31.392638 | 100 | 0.555599 |
0113774bc56dbc38bad5b3751e4987a5c42fbff2 | 1,534 | hpp | C++ | src/messaging/MessageHandler.hpp | Fabi2607/MazeNet-Client | 1fcb0b3cbeeab123cb69cd18070e0bbf4907130c | [
"MIT"
] | null | null | null | src/messaging/MessageHandler.hpp | Fabi2607/MazeNet-Client | 1fcb0b3cbeeab123cb69cd18070e0bbf4907130c | [
"MIT"
] | null | null | null | src/messaging/MessageHandler.hpp | Fabi2607/MazeNet-Client | 1fcb0b3cbeeab123cb69cd18070e0bbf4907130c | [
"MIT"
] | null | null | null | #ifndef MAZENET_CLIENT_MESSAGEHANDLER_HPP
#define MAZENET_CLIENT_MESSAGEHANDLER_HPP
#include <string>
#include <player/IPlayerStrategy.hpp>
#include "../messaging/mazeCom.hxx"
#include "../player/GameSituation.hpp"
#include "../util/logging/Log.hpp"
#include "MessageDispatcher.hpp"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Weffc++" //Ignoring the warning.
class MessageHandler {
public:
MessageHandler(std::shared_ptr<IPlayerStrategy> strategy, MessageDispatcher& dispatcher);
void handle_incoming_message(const std::string& message);
private:
void handle_login_reply(const LoginReplyMessageType& reply);
void handle_await_move(const AwaitMoveMessageType& await_move);
void handle_accept_message(const AcceptMessageType& accept_message);
void handle_win_message(const WinMessageType& win_message);
void handle_disconnect_message(const DisconnectMessageType& disconnect_message);
void update_model(const AwaitMoveMessageType& message);
void update_board(const boardType& board);
std::shared_ptr<MazeCom> deserialize(const std::string& msg);
std::shared_ptr<IPlayerStrategy> strategy_;
mazenet::util::logging::Log logger_;
MessageDispatcher& dispatcher_;
xsd::cxx::tree::error_handler<char> eh;
xsd::cxx::xml::dom::bits::error_handler_proxy<char> ehp;
xercesc::DOMImplementation* impl;
xml_schema::dom::unique_ptr<xercesc::DOMLSParser> parser;
xercesc::DOMConfiguration* conf_r;
};
#pragma GCC diagnostic pop
#endif /* MAZENET_CLIENT_MESSAGEHANDLER_HPP */
| 27.392857 | 91 | 0.789439 |
011567e9d19e6b5d02b15b496bc71cf9d07e8bf7 | 7,215 | hpp | C++ | scicpp/core/meta.hpp | tvanderbruggen/SciCpp | 09408506c8d0b49ca5dadb8cd1f3cb4db41c8c46 | [
"MIT"
] | 2 | 2021-08-02T09:03:30.000Z | 2022-02-17T11:58:05.000Z | scicpp/core/meta.hpp | tvanderbruggen/SciCpp | 09408506c8d0b49ca5dadb8cd1f3cb4db41c8c46 | [
"MIT"
] | null | null | null | scicpp/core/meta.hpp | tvanderbruggen/SciCpp | 09408506c8d0b49ca5dadb8cd1f3cb4db41c8c46 | [
"MIT"
] | null | null | null | // SPDX-License-Identifier: MIT
// Copyright (c) 2019-2021 Thomas Vanderbruggen <th.vanderbruggen@gmail.com>
#ifndef SCICPP_CORE_META
#define SCICPP_CORE_META
#include <Eigen/Dense>
#include <array>
#include <complex>
#include <ratio>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
namespace scicpp::meta {
//---------------------------------------------------------------------------------
// is_complex
//---------------------------------------------------------------------------------
namespace detail {
template <class T>
struct is_complex : std::false_type {};
template <class T>
struct is_complex<std::complex<T>> : std::true_type {};
} // namespace detail
template <class T>
constexpr bool is_complex_v = detail::is_complex<T>::value;
template <typename T>
using enable_if_complex = std::enable_if_t<is_complex_v<T>, int>;
template <typename T>
using disable_if_complex = std::enable_if_t<!is_complex_v<T>, int>;
//---------------------------------------------------------------------------------
// is_iterable
//---------------------------------------------------------------------------------
// https://stackoverflow.com/questions/13830158/check-if-a-variable-is-iterable
namespace detail {
// To allow ADL with custom begin/end
using std::begin;
using std::end;
template <typename T>
auto is_iterable_impl(int) -> decltype(
begin(std::declval<T &>()) !=
end(std::declval<T &>()), // begin/end and operator !=
void(), // Handle evil operator ,
++std::declval<decltype(begin(std::declval<T &>())) &>(), // operator ++
void(*begin(std::declval<T &>())), // operator*
std::true_type{});
template <typename T>
std::false_type is_iterable_impl(...);
template <typename T>
using is_iterable = decltype(detail::is_iterable_impl<T>(0));
} // namespace detail
template <typename T>
constexpr bool is_iterable_v = detail::is_iterable<T>::value;
template <typename T>
using enable_if_iterable = std::enable_if_t<is_iterable_v<T>, int>;
template <typename T>
using disable_if_iterable = std::enable_if_t<!is_iterable_v<T>, int>;
//---------------------------------------------------------------------------------
// std::vector traits
//---------------------------------------------------------------------------------
namespace detail {
template <class T>
struct is_std_vector : std::false_type {};
template <typename Scalar>
struct is_std_vector<std::vector<Scalar>> : std::true_type {};
} // namespace detail
template <class T>
constexpr bool is_std_vector_v = detail::is_std_vector<T>::value;
//---------------------------------------------------------------------------------
// std::array traits
//---------------------------------------------------------------------------------
namespace detail {
template <class T>
struct is_std_array : std::false_type {};
template <typename Scalar, std::size_t N>
struct is_std_array<std::array<Scalar, N>> : std::true_type {};
} // namespace detail
template <class T>
constexpr bool is_std_array_v = detail::is_std_array<T>::value;
//---------------------------------------------------------------------------------
// std::tuple traits
//---------------------------------------------------------------------------------
namespace detail {
template <class T>
struct is_std_tuple : std::false_type {};
template <typename... Args>
struct is_std_tuple<std::tuple<Args...>> : std::true_type {};
} // namespace detail
template <class T>
constexpr bool is_std_tuple_v = detail::is_std_tuple<T>::value;
//---------------------------------------------------------------------------------
// std::pair traits
//---------------------------------------------------------------------------------
namespace detail {
template <class T>
struct is_std_pair : std::false_type {};
template <typename T1, typename T2>
struct is_std_pair<std::pair<T1, T2>> : std::true_type {};
} // namespace detail
template <class T>
constexpr bool is_std_pair_v = detail::is_std_pair<T>::value;
//---------------------------------------------------------------------------------
// subtuple
// https://stackoverflow.com/questions/17854219/creating-a-sub-tuple-starting-from-a-stdtuplesome-types
//---------------------------------------------------------------------------------
namespace detail {
template <typename... T, std::size_t... I>
constexpr auto subtuple_(const std::tuple<T...> &t,
std::index_sequence<I...> /*unused*/) {
return std::make_tuple(std::get<I>(t)...);
}
} // namespace detail
template <int Trim, typename... T>
constexpr auto subtuple(const std::tuple<T...> &t) {
return detail::subtuple_(t,
std::make_index_sequence<sizeof...(T) - Trim>());
}
template <int Trim = 1, typename T1, typename T2>
constexpr auto subtuple(const std::pair<T1, T2> &t) {
return std::make_tuple(t.first);
}
//---------------------------------------------------------------------------------
// is_ratio
//---------------------------------------------------------------------------------
namespace detail {
template <class T>
struct is_ratio : std::false_type {};
template <intmax_t num, intmax_t den>
struct is_ratio<std::ratio<num, den>> : std::true_type {};
} // namespace detail
template <class T>
constexpr bool is_ratio_v = detail::is_ratio<T>::value;
//---------------------------------------------------------------------------------
// Eigen type traits
//---------------------------------------------------------------------------------
namespace detail {
template <class T>
struct is_eigen_matrix : std::false_type {};
template <typename Scalar, int RowsAtCompileTime, int ColsAtCompileTime>
struct is_eigen_matrix<
Eigen::Matrix<Scalar, RowsAtCompileTime, ColsAtCompileTime>>
: std::true_type {};
template <class T>
struct is_eigen_array : std::false_type {};
template <typename Scalar, int RowsAtCompileTime, int ColsAtCompileTime>
struct is_eigen_array<
Eigen::Array<Scalar, RowsAtCompileTime, ColsAtCompileTime>>
: std::true_type {};
} // namespace detail
template <class T>
constexpr bool is_eigen_matrix_v = detail::is_eigen_matrix<T>::value;
template <class T>
constexpr bool is_eigen_array_v = detail::is_eigen_array<T>::value;
template <class T>
constexpr bool is_eigen_container_v =
is_eigen_matrix_v<T> || is_eigen_array_v<T>;
//---------------------------------------------------------------------------------
// is_predicate
//---------------------------------------------------------------------------------
template <class Predicate, class... Args>
constexpr bool is_predicate =
std::is_integral_v<std::invoke_result_t<Predicate, Args...>>;
//---------------------------------------------------------------------------------
// is_string
//---------------------------------------------------------------------------------
template <class T>
constexpr bool is_string_v =
std::is_same_v<const char *, typename std::decay_t<T>> ||
std::is_same_v<char *, typename std::decay_t<T>> ||
std::is_same_v<std::string, typename std::decay_t<T>>;
} // namespace scicpp::meta
#endif // SCICPP_CORE_META | 30.315126 | 103 | 0.527235 |
01164e1a7b0fb27f09b533c80c93d554c7f8dd74 | 2,332 | cpp | C++ | mini/io/path.cpp | stevefan1999/mini-tor | fbf82a5a394f15b68fc356c5a71af47a3e3863d3 | [
"MIT"
] | 2 | 2018-03-30T22:29:23.000Z | 2019-04-22T11:46:29.000Z | mini/io/path.cpp | FingerLeakers/mini-tor | fbf82a5a394f15b68fc356c5a71af47a3e3863d3 | [
"MIT"
] | null | null | null | mini/io/path.cpp | FingerLeakers/mini-tor | fbf82a5a394f15b68fc356c5a71af47a3e3863d3 | [
"MIT"
] | 1 | 2019-12-29T17:53:05.000Z | 2019-12-29T17:53:05.000Z | #include "path.h"
namespace mini::io {
string
path::combine(
const string_ref p1,
const string_ref p2
)
{
string result = p1;
if (!p1.ends_with(directory_separator) && !p1.ends_with(alternative_directory_separator))
{
result += directory_separator;
}
result += p2;
return result;
}
string_collection
path::split(
const string_ref p
)
{
//
// TODO:
// take alternative_directory_separator into account.
//
auto result = p.split(directory_separator);
//
// always end drive letter with '\'.
//
if (result.get_size() > 0 && result[0].get_size() > 1)
{
string& drive_letter = result[0];
if (drive_letter[1] == ':')
{
drive_letter += directory_separator;
}
}
return result;
}
string_ref
path::get_file_name(
const string_ref p
)
{
size_type name_offset = p.last_index_of(directory_separator);
if (name_offset == string_ref::not_found)
{
name_offset = p.last_index_of(alternative_directory_separator);
}
if (name_offset == string_ref::not_found || (name_offset + 1) >= p.get_size())
{
return string_ref::empty;
}
return p.substring(name_offset + 1);
}
string_ref
path::get_directory_name(
const string_ref p
)
{
size_type name_offset = p.last_index_of(directory_separator);
if (name_offset == string_ref::not_found)
{
name_offset = p.last_index_of(alternative_directory_separator);
}
return p.substring(0, name_offset);
}
string_ref
path::get_filename_without_extension(
const string_ref p
)
{
size_type name_offset = p.last_index_of(directory_separator);
if (name_offset == string_ref::not_found)
{
name_offset = p.last_index_of(alternative_directory_separator);
}
if (name_offset == string_ref::not_found || (name_offset + 1) >= p.get_size())
{
return string_ref::empty;
}
string_ref result = p.substring(name_offset + 1);
size_type extension_offset = result.last_index_of(extension_separator);
return result.substring(0, extension_offset);
}
string_ref
path::get_extension(
const string_ref p
)
{
string_ref file_name = get_file_name(p);
size_type extension_offset = file_name.last_index_of(extension_separator);
if (extension_offset != string_ref::not_found)
{
return file_name.substring(extension_offset);
}
return string_ref::empty;
}
}
| 18.656 | 91 | 0.701115 |
011928a30f96a3f6ebfb64f374f0d4bf5bebeaba | 11,070 | cpp | C++ | src/caffe/test/test_serialization_blob_codec.cpp | shayanshams66/caffe | 3b031d59cd6a419b433e9fe05c9fe4bfc3060f4e | [
"Intel",
"BSD-2-Clause"
] | 1 | 2017-01-04T03:35:46.000Z | 2017-01-04T03:35:46.000Z | src/caffe/test/test_serialization_blob_codec.cpp | shayanshams66/caffe | 3b031d59cd6a419b433e9fe05c9fe4bfc3060f4e | [
"Intel",
"BSD-2-Clause"
] | null | null | null | src/caffe/test/test_serialization_blob_codec.cpp | shayanshams66/caffe | 3b031d59cd6a419b433e9fe05c9fe4bfc3060f4e | [
"Intel",
"BSD-2-Clause"
] | null | null | null | #include <boost/assign.hpp>
#include <glog/logging.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <vector>
#include "caffe/internode/configuration.hpp"
#include "caffe/serialization/BlobCodec.hpp"
#include "caffe/test/test_caffe_main.hpp"
#include "caffe/util/math_functions.hpp"
namespace caffe {
namespace {
using ::testing::_;
using ::testing::Return;
template <typename TypeParam>
class BlobCodecTest : public MultiDeviceTest<TypeParam> {
typedef typename TypeParam::Dtype Dtype;
};
TYPED_TEST_CASE(BlobCodecTest, TestDtypesAndDevices);
TYPED_TEST(BlobCodecTest, encode_4321_diff) {
BlobUpdate msg;
Blob<float> srcblob;
vector<int> v = boost::assign::list_of(4)(3)(2)(1);
srcblob.Reshape(v);
vector<float> diff = boost::assign::list_of(999.99)(12.3)(0.1)(-3.3)
(+2.0)(12.3)(10.2)(FLT_MAX)
(+4.4)(12.3)(0.0)(-1.3)
(+6.5)(12.3)(24.42)(1010.10)
(FLT_MIN)(12.3)(66.6)(133.1)
(12.4)(12.3)(0.0001)(100.3);
ASSERT_EQ(diff.size(), srcblob.count());
caffe_copy(srcblob.count(),
&diff.front(),
srcblob.mutable_cpu_diff());
shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec(
MultinodeParameter::default_instance(), true);
codec->encode(&msg, &srcblob, BlobEncoding::GRADS, msg.info().part());
EXPECT_EQ(0, memcmp(msg.data().c_str(), &diff.front(),
sizeof(float)*diff.size()));
}
TYPED_TEST(BlobCodecTest, encode_decode_2222_data) {
BlobUpdate msg;
Blob<float> srcblob;
Blob<float> dstblob;
vector<int> v = boost::assign::list_of(2)(2)(2)(2);
srcblob.Reshape(v);
dstblob.Reshape(v);
vector<float> data = boost::assign::list_of(1.1)(-2.2)(3.3)(5.5)
(6.6)(-7.7)(8.8)(9.9)
(13.13)(-12.12)(12.12)(11.11)
(128.128)(-132.312)(1.1)(-10.10);
vector<float> data_zero = boost::assign::list_of(0.0)(0.0)(0.0)(0.0)
(0.0)(0.0)(0.0)(0.0)
(0.0)(0.0)(0.0)(0.0)
(0.0)(0.0)(0.0)(0.0);
ASSERT_EQ(data.size(), srcblob.count());
ASSERT_EQ(data_zero.size(), dstblob.count());
caffe_copy<float>(srcblob.count(),
&data.front(),
srcblob.mutable_cpu_data());
caffe_copy<float>(dstblob.count(),
&data_zero.front(),
dstblob.mutable_cpu_diff());
shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec(
MultinodeParameter::default_instance(), true);
codec->encode(&msg, &srcblob, BlobEncoding::PARAMS, msg.info().part());
codec->decode(msg, &dstblob, BlobEncoding::PARAMS, 1.0f, 0.0f);
EXPECT_EQ(0, memcmp(dstblob.cpu_data(), &data.front(),
sizeof(float)*dstblob.count()));
}
TYPED_TEST(BlobCodecTest, encode_8width_data_) {
BlobUpdate msg;
Blob<float> srcblob;
vector<int> v = boost::assign::list_of(1)(1)(1)(8);
srcblob.Reshape(v);
vector<float> data = boost::assign::list_of(-0.0)(-0.3)(-2.2)(-3.3)
(+0.0)(12.3)(10.2)(-1.3);
ASSERT_EQ(data.size(), srcblob.count());
caffe_copy<float>(srcblob.count(),
&data.front(),
srcblob.mutable_cpu_data());
shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec(
MultinodeParameter::default_instance(), true);
codec->encode(&msg, &srcblob, BlobEncoding::PARAMS, msg.info().part());
EXPECT_EQ(0, memcmp(msg.data().c_str(), &data.front(),
sizeof(float)*data.size()));
}
TYPED_TEST(BlobCodecTest, encode_4width_diff) {
BlobUpdate msg;
Blob<float> srcblob;
vector<int> v = boost::assign::list_of(1)(1)(1)(4);
srcblob.Reshape(v);
vector<float> diff = boost::assign::list_of(-0.0)(-99.99)(-0.3)(0.4);
ASSERT_EQ(diff.size(), srcblob.count());
caffe_copy<float>(srcblob.count(),
&diff.front(),
srcblob.mutable_cpu_diff());
shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec(
MultinodeParameter::default_instance(), true);
codec->encode(&msg, &srcblob, BlobEncoding::GRADS, msg.info().part());
EXPECT_EQ(0, memcmp(msg.data().c_str(), &diff.front(),
sizeof(float)*diff.size()));
}
TYPED_TEST(BlobCodecTest, encode_decode_4width_diff) {
BlobUpdate msg;
Blob<float> srcblob;
Blob<float> dstblob;
vector<int> v = boost::assign::list_of(1)(1)(1)(4);
srcblob.Reshape(v);
dstblob.Reshape(v);
vector<float> diff_zero = boost::assign::list_of(0.0)(0.0)(0.0)(0.0);
vector<float> diff = boost::assign::list_of(1.0)(2.2)(3.3)(4.4);
ASSERT_EQ(diff.size(), srcblob.count());
ASSERT_EQ(diff_zero.size(), srcblob.count());
caffe_copy<float>(srcblob.count(),
&diff.front(),
srcblob.mutable_cpu_diff());
caffe_copy<float>(dstblob.count(),
&diff_zero.front(),
dstblob.mutable_cpu_diff());
shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec(
MultinodeParameter::default_instance(), true);
codec->encode(&msg, &srcblob, BlobEncoding::GRADS, msg.info().part());
codec->decode(msg, &dstblob, BlobEncoding::GRADS, 1.0f, 0.0f);
EXPECT_EQ(0, memcmp(dstblob.cpu_diff(), &diff.front(),
sizeof(float)*dstblob.count()));
}
TYPED_TEST(BlobCodecTest, encode_decode_4width_data) {
BlobUpdate msg;
Blob<float> srcblob;
Blob<float> dstblob;
vector<int> v = boost::assign::list_of(1)(1)(1)(4);
srcblob.Reshape(v);
dstblob.Reshape(v);
vector<float> data_zero = boost::assign::list_of(0.0)(0.0)(0.0)(0.0);
vector<float> data = boost::assign::list_of(4.0)(3.2)(2.3)(1.4);
ASSERT_EQ(data.size(), srcblob.count());
ASSERT_EQ(data_zero.size(), srcblob.count());
caffe_copy<float>(srcblob.count(),
&data.front(),
srcblob.mutable_cpu_data());
caffe_copy<float>(dstblob.count(),
&data_zero.front(),
dstblob.mutable_cpu_data());
shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec(
MultinodeParameter::default_instance(), true);
codec->encode(&msg, &srcblob, BlobEncoding::PARAMS, msg.info().part());
codec->decode(msg, &dstblob, BlobEncoding::PARAMS, 1.0f, 0.0f);
EXPECT_EQ(0, memcmp(dstblob.cpu_data(), &data.front(),
sizeof(float)*dstblob.count()));
}
TYPED_TEST(BlobCodecTest, encode_decode_4width_data_alpha_0_5) {
BlobUpdate msg;
Blob<float> srcblob;
Blob<float> dstblob;
vector<int> v = boost::assign::list_of(1)(1)(1)(4);
srcblob.Reshape(v);
dstblob.Reshape(v);
vector<float> data_zero = boost::assign::list_of(0.0)(0.0)(0.0)(0.0);
vector<float> data = boost::assign::list_of(4.0)(3.2)(2.4)(1.4);
vector<float> data_expected = boost::assign::list_of(2.0)(1.6)(1.2)(0.7);
ASSERT_EQ(data.size(), srcblob.count());
ASSERT_EQ(data_zero.size(), srcblob.count());
caffe_copy<float>(srcblob.count(),
&data.front(),
srcblob.mutable_cpu_data());
caffe_copy<float>(dstblob.count(),
&data_zero.front(),
dstblob.mutable_cpu_data());
shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec(
MultinodeParameter::default_instance(), true);
codec->encode(&msg, &srcblob, BlobEncoding::PARAMS, msg.info().part());
codec->decode(msg, &dstblob, BlobEncoding::PARAMS, 0.5f, 0.0f);
EXPECT_EQ(0, memcmp(dstblob.cpu_data(), &data_expected.front(),
sizeof(float)*dstblob.count()));
}
TYPED_TEST(BlobCodecTest, encode_decode_4width_data_beta_0_5) {
BlobUpdate msg;
Blob<float> srcblob;
Blob<float> dstblob;
vector<int> v = boost::assign::list_of(1)(1)(1)(4);
srcblob.Reshape(v);
dstblob.Reshape(v);
vector<float> data_one = boost::assign::list_of(1.0)(1.0)(1.0)(1.0);
vector<float> data = boost::assign::list_of(4.0)(3.2)(2.4)(1.4);
vector<float> data_expected = boost::assign::list_of(4.5)(3.7)(2.9)(1.9);
ASSERT_EQ(data.size(), srcblob.count());
ASSERT_EQ(data_one.size(), srcblob.count());
caffe_copy<float>(srcblob.count(), &data.front(),
srcblob.mutable_cpu_data());
caffe_copy<float>(dstblob.count(), &data_one.front(),
dstblob.mutable_cpu_data());
shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec(
MultinodeParameter::default_instance(), true);
codec->encode(&msg, &srcblob, BlobEncoding::PARAMS, msg.info().part());
codec->decode(msg, &dstblob, BlobEncoding::PARAMS, 1.0f, 0.5f);
EXPECT_EQ(0, memcmp(dstblob.cpu_data(), &data_expected.front(),
sizeof(float)*dstblob.count()));
}
TYPED_TEST(BlobCodecTest, encode_decode_4width_data_alpha_0_5_beta_0_5) {
BlobUpdate msg;
Blob<float> srcblob;
Blob<float> dstblob;
vector<int> v = boost::assign::list_of(1)(1)(1)(4);
srcblob.Reshape(v);
dstblob.Reshape(v);
vector<float> data_one = boost::assign::list_of(1.0)(1.0)(1.0)(1.0);
vector<float> data = boost::assign::list_of(4.0)(3.2)(2.4)(1.4);
vector<float> data_expected = boost::assign::list_of(2.5)(2.1)(1.7)(1.2);
ASSERT_EQ(data.size(), srcblob.count());
ASSERT_EQ(data_one.size(), srcblob.count());
caffe_copy<float>(srcblob.count(), &data.front(),
srcblob.mutable_cpu_data());
caffe_copy<float>(dstblob.count(), &data_one.front(),
dstblob.mutable_cpu_data());
shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec(
MultinodeParameter::default_instance(), true);
codec->encode(&msg, &srcblob, BlobEncoding::PARAMS, msg.info().part());
codec->decode(msg, &dstblob, BlobEncoding::PARAMS, 0.5f, 0.5f);
EXPECT_EQ(0, memcmp(dstblob.cpu_data(), &data_expected.front(),
sizeof(float)*dstblob.count()));
}
TYPED_TEST(BlobCodecTest, encode_decode_4width_data_alpha_0_beta_1) {
BlobUpdate msg;
Blob<float> srcblob;
Blob<float> dstblob;
vector<int> v = boost::assign::list_of(1)(1)(1)(4);
srcblob.Reshape(v);
dstblob.Reshape(v);
vector<float> data_one = boost::assign::list_of(1.1)(2.3)(1.4)(0.01);
vector<float> data = boost::assign::list_of(4.0)(3.2)(2.4)(1.4);
vector<float> data_expected = boost::assign::list_of(1.1)(2.3)(1.4)(0.01);
ASSERT_EQ(data.size(), srcblob.count());
ASSERT_EQ(data_one.size(), srcblob.count());
caffe_copy<float>(srcblob.count(), &data.front(),
srcblob.mutable_cpu_data());
caffe_copy<float>(dstblob.count(), &data_one.front(),
dstblob.mutable_cpu_data());
shared_ptr<BlobCodec<float> > codec = BlobCodec<float>::create_codec(
MultinodeParameter::default_instance(), true);
codec->encode(&msg, &srcblob, BlobEncoding::PARAMS, msg.info().part());
codec->decode(msg, &dstblob, BlobEncoding::PARAMS, 0.0f, 1.0f);
EXPECT_EQ(0, memcmp(dstblob.cpu_data(), &data_expected.front(),
sizeof(float)*dstblob.count()));
}
} // namespace
} // namespace caffe
| 35.594855 | 78 | 0.629901 |
011b4ba53fe34216618e95c8053a379494fc392c | 935 | cpp | C++ | rnn++/utils/math.cpp | uphere-co/nlp-prototype | c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3 | [
"BSD-3-Clause"
] | null | null | null | rnn++/utils/math.cpp | uphere-co/nlp-prototype | c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3 | [
"BSD-3-Clause"
] | null | null | null | rnn++/utils/math.cpp | uphere-co/nlp-prototype | c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3 | [
"BSD-3-Clause"
] | null | null | null | #include "utils/math.h"
namespace util{
namespace math{
template<>
float_t Fun<FunName::alog>(float_t x){auto one=decltype(x){1}; return std::log(std::abs(x)+one);}
template<>
float_t Fun<FunName::d_alog>(float_t x){auto one=decltype(x){1}; return one/(std::abs(x)+one);}
template<>
float_t Fun<FunName::tanh>(float_t x){return std::tanh(x);}
template<>
float_t Fun<FunName::d_tanh>(float_t x){auto fx=std::cosh(x);return decltype(x){1}/(fx*fx);}
template<>
float_t Fun<FunName::sig>(float_t x){return float_t{1}/(float_t{1}+std::exp(-x));}
template<>
float_t Fun<FunName::ax>(float_t x){return float_t{0.5}*x;}
template<>
float_t Fun<FunName::d_ax>(float_t ){return float_t{0.5};}
template<>
float_t Fun<FunName::test>(float_t x){return x>0?std::sqrt(x):-std::sqrt(-x);}
template<>
float_t Fun<FunName::d_test>(float_t x){return x>0?float_t{0.5}/std::sqrt(x):float_t{0.5}/std::sqrt(-x);}
}//namespace util::math
}//namespace util
| 33.392857 | 105 | 0.702674 |
011c439dc7e8a25e5bc7e16891e280f726793e53 | 24,133 | hpp | C++ | ddbtoaster/experiments/src/tpch/codegen_initial_submission_r3391/Tpch13VCpp.hpp | szarnyasg/dbtoaster-backend | 24d43034fa3a5a4f6ab4f1de3e2d83a7ca80be73 | [
"Apache-2.0"
] | 38 | 2017-09-29T08:12:31.000Z | 2022-03-31T03:56:20.000Z | ddbtoaster/experiments/src/tpch/codegen_initial_submission_r3391/Tpch13VCpp.hpp | szarnyasg/dbtoaster-backend | 24d43034fa3a5a4f6ab4f1de3e2d83a7ca80be73 | [
"Apache-2.0"
] | 33 | 2018-04-05T02:42:39.000Z | 2022-02-18T02:13:57.000Z | ddbtoaster/experiments/src/tpch/codegen_initial_submission_r3391/Tpch13VCpp.hpp | szarnyasg/dbtoaster-backend | 24d43034fa3a5a4f6ab4f1de3e2d83a7ca80be73 | [
"Apache-2.0"
] | 17 | 2017-09-29T08:16:00.000Z | 2022-02-18T04:22:29.000Z | #include <sys/time.h>
#include "macro.hpp"
#include "types.hpp"
#include "functions.hpp"
#include "hash.hpp"
#include "hashmap.hpp"
#include "serialization.hpp"
#define ELEM_SEPARATOR "\n\t\t\t"
namespace dbtoaster {
/* Definitions of auxiliary maps for storing materialized views. */
struct CUSTDIST_entry {
long C_ORDERS_C_COUNT; long __av;
explicit CUSTDIST_entry() { /*C_ORDERS_C_COUNT = 0L; __av = 0L; */ }
explicit CUSTDIST_entry(const long c0, const long c1) { C_ORDERS_C_COUNT = c0; __av = c1; }
CUSTDIST_entry(const CUSTDIST_entry& other) : C_ORDERS_C_COUNT( other.C_ORDERS_C_COUNT ), __av( other.__av ) {}
FORCE_INLINE CUSTDIST_entry& modify(const long c0) { C_ORDERS_C_COUNT = c0; return *this; }
template<class Archive>
void serialize(Archive& ar, const unsigned int version) const
{
ar << ELEM_SEPARATOR;
DBT_SERIALIZATION_NVP(ar, C_ORDERS_C_COUNT);
ar << ELEM_SEPARATOR;
DBT_SERIALIZATION_NVP(ar, __av);
}
};
struct CUSTDIST_mapkey0_idxfn {
FORCE_INLINE static size_t hash(const CUSTDIST_entry& e) {
size_t h = 0;
hash_combine(h, e.C_ORDERS_C_COUNT);
return h;
}
FORCE_INLINE static bool equals(const CUSTDIST_entry& x, const CUSTDIST_entry& y) {
return x.C_ORDERS_C_COUNT == y.C_ORDERS_C_COUNT;
}
};
typedef MultiHashMap<CUSTDIST_entry,long,
HashIndex<CUSTDIST_entry,long,CUSTDIST_mapkey0_idxfn,true>
> CUSTDIST_map;
typedef HashIndex<CUSTDIST_entry,long,CUSTDIST_mapkey0_idxfn,true> HashIndex_CUSTDIST_map_0;
struct CUSTDIST_mCUSTOMER_IVC1_E1_1_entry {
long C_ORDERS_C_CUSTKEY; long __av;
explicit CUSTDIST_mCUSTOMER_IVC1_E1_1_entry() { /*C_ORDERS_C_CUSTKEY = 0L; __av = 0L; */ }
explicit CUSTDIST_mCUSTOMER_IVC1_E1_1_entry(const long c0, const long c1) { C_ORDERS_C_CUSTKEY = c0; __av = c1; }
CUSTDIST_mCUSTOMER_IVC1_E1_1_entry(const CUSTDIST_mCUSTOMER_IVC1_E1_1_entry& other) : C_ORDERS_C_CUSTKEY( other.C_ORDERS_C_CUSTKEY ), __av( other.__av ) {}
FORCE_INLINE CUSTDIST_mCUSTOMER_IVC1_E1_1_entry& modify(const long c0) { C_ORDERS_C_CUSTKEY = c0; return *this; }
template<class Archive>
void serialize(Archive& ar, const unsigned int version) const
{
ar << ELEM_SEPARATOR;
DBT_SERIALIZATION_NVP(ar, C_ORDERS_C_CUSTKEY);
ar << ELEM_SEPARATOR;
DBT_SERIALIZATION_NVP(ar, __av);
}
};
struct CUSTDIST_mCUSTOMER_IVC1_E1_1_mapkey0_idxfn {
FORCE_INLINE static size_t hash(const CUSTDIST_mCUSTOMER_IVC1_E1_1_entry& e) {
size_t h = 0;
hash_combine(h, e.C_ORDERS_C_CUSTKEY);
return h;
}
FORCE_INLINE static bool equals(const CUSTDIST_mCUSTOMER_IVC1_E1_1_entry& x, const CUSTDIST_mCUSTOMER_IVC1_E1_1_entry& y) {
return x.C_ORDERS_C_CUSTKEY == y.C_ORDERS_C_CUSTKEY;
}
};
typedef MultiHashMap<CUSTDIST_mCUSTOMER_IVC1_E1_1_entry,long,
HashIndex<CUSTDIST_mCUSTOMER_IVC1_E1_1_entry,long,CUSTDIST_mCUSTOMER_IVC1_E1_1_mapkey0_idxfn,true>
> CUSTDIST_mCUSTOMER_IVC1_E1_1_map;
typedef HashIndex<CUSTDIST_mCUSTOMER_IVC1_E1_1_entry,long,CUSTDIST_mCUSTOMER_IVC1_E1_1_mapkey0_idxfn,true> HashIndex_CUSTDIST_mCUSTOMER_IVC1_E1_1_map_0;
struct CUSTDIST_mCUSTOMER1_L1_1_entry {
long CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY; long __av;
explicit CUSTDIST_mCUSTOMER1_L1_1_entry() { /*CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY = 0L; __av = 0L; */ }
explicit CUSTDIST_mCUSTOMER1_L1_1_entry(const long c0, const long c1) { CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY = c0; __av = c1; }
CUSTDIST_mCUSTOMER1_L1_1_entry(const CUSTDIST_mCUSTOMER1_L1_1_entry& other) : CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY( other.CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY ), __av( other.__av ) {}
FORCE_INLINE CUSTDIST_mCUSTOMER1_L1_1_entry& modify(const long c0) { CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY = c0; return *this; }
template<class Archive>
void serialize(Archive& ar, const unsigned int version) const
{
ar << ELEM_SEPARATOR;
DBT_SERIALIZATION_NVP(ar, CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY);
ar << ELEM_SEPARATOR;
DBT_SERIALIZATION_NVP(ar, __av);
}
};
struct CUSTDIST_mCUSTOMER1_L1_1_mapkey0_idxfn {
FORCE_INLINE static size_t hash(const CUSTDIST_mCUSTOMER1_L1_1_entry& e) {
size_t h = 0;
hash_combine(h, e.CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY);
return h;
}
FORCE_INLINE static bool equals(const CUSTDIST_mCUSTOMER1_L1_1_entry& x, const CUSTDIST_mCUSTOMER1_L1_1_entry& y) {
return x.CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY == y.CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY;
}
};
typedef MultiHashMap<CUSTDIST_mCUSTOMER1_L1_1_entry,long,
HashIndex<CUSTDIST_mCUSTOMER1_L1_1_entry,long,CUSTDIST_mCUSTOMER1_L1_1_mapkey0_idxfn,true>
> CUSTDIST_mCUSTOMER1_L1_1_map;
typedef HashIndex<CUSTDIST_mCUSTOMER1_L1_1_entry,long,CUSTDIST_mCUSTOMER1_L1_1_mapkey0_idxfn,true> HashIndex_CUSTDIST_mCUSTOMER1_L1_1_map_0;
struct CUSTDIST_mCUSTOMER1_L1_2_entry {
long CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY; long __av;
explicit CUSTDIST_mCUSTOMER1_L1_2_entry() { /*CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY = 0L; __av = 0L; */ }
explicit CUSTDIST_mCUSTOMER1_L1_2_entry(const long c0, const long c1) { CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY = c0; __av = c1; }
CUSTDIST_mCUSTOMER1_L1_2_entry(const CUSTDIST_mCUSTOMER1_L1_2_entry& other) : CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY( other.CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY ), __av( other.__av ) {}
FORCE_INLINE CUSTDIST_mCUSTOMER1_L1_2_entry& modify(const long c0) { CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY = c0; return *this; }
template<class Archive>
void serialize(Archive& ar, const unsigned int version) const
{
ar << ELEM_SEPARATOR;
DBT_SERIALIZATION_NVP(ar, CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY);
ar << ELEM_SEPARATOR;
DBT_SERIALIZATION_NVP(ar, __av);
}
};
struct CUSTDIST_mCUSTOMER1_L1_2_mapkey0_idxfn {
FORCE_INLINE static size_t hash(const CUSTDIST_mCUSTOMER1_L1_2_entry& e) {
size_t h = 0;
hash_combine(h, e.CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY);
return h;
}
FORCE_INLINE static bool equals(const CUSTDIST_mCUSTOMER1_L1_2_entry& x, const CUSTDIST_mCUSTOMER1_L1_2_entry& y) {
return x.CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY == y.CUSTDIST_mCUSTOMERCUSTOMER_CUSTKEY;
}
};
typedef MultiHashMap<CUSTDIST_mCUSTOMER1_L1_2_entry,long,
HashIndex<CUSTDIST_mCUSTOMER1_L1_2_entry,long,CUSTDIST_mCUSTOMER1_L1_2_mapkey0_idxfn,true>
> CUSTDIST_mCUSTOMER1_L1_2_map;
typedef HashIndex<CUSTDIST_mCUSTOMER1_L1_2_entry,long,CUSTDIST_mCUSTOMER1_L1_2_mapkey0_idxfn,true> HashIndex_CUSTDIST_mCUSTOMER1_L1_2_map_0;
struct tuple2_L_L {
long _1; long __av;
explicit tuple2_L_L() { }
explicit tuple2_L_L(const long c1, long c__av=0L) { _1 = c1; __av = c__av;}
int operator==(const tuple2_L_L &rhs) const { return ((this->_1==rhs._1)); }
FORCE_INLINE tuple2_L_L& modify(const long c0, long c__av) { _1 = c0; __av = c__av; return *this; }
static bool equals(const tuple2_L_L &x, const tuple2_L_L &y) { return ((x._1==y._1)); }
static long hash(const tuple2_L_L &e) {
size_t h = 0;
hash_combine(h, e._1);
return h;
}
};
/* Type definition providing a way to access the results of the sql program */
struct tlq_t{
struct timeval t0,t; long tT,tN,tS;
tlq_t(): tN(0), tS(0) { gettimeofday(&t0,NULL); }
/* Serialization Code */
template<class Archive>
void serialize(Archive& ar, const unsigned int version) const {
ar << "\n";
const CUSTDIST_map& _CUSTDIST = get_CUSTDIST();
dbtoaster::serialize_nvp_tabbed(ar, STRING_TYPE(CUSTDIST), _CUSTDIST, "\t");
}
/* Functions returning / computing the results of top level queries */
const CUSTDIST_map& get_CUSTDIST() const {
return CUSTDIST;
}
protected:
/* Data structures used for storing / computing top level queries */
CUSTDIST_map CUSTDIST;
};
/* Type definition providing a way to incrementally maintain the results of the sql program */
struct data_t : tlq_t{
data_t(): tlq_t(), agg2(16U), agg4(16U), agg1(16U), agg3(16U) {
/* regex_t init */
if(regcomp(&preg1, "^.*special.*requests.*$", REG_EXTENDED | REG_NOSUB)){
cerr << "Error compiling regular expression: /^.*special.*requests.*$/" << endl;
exit(-1);
}
}
~data_t() {
regfree(&preg1);
}
/* Trigger functions for table relations */
/* Trigger functions for stream relations */
void on_insert_ORDERS(const long orders_orderkey, const long orders_custkey, const STRING_TYPE& orders_orderstatus, const DOUBLE_TYPE orders_totalprice, const date orders_orderdate, const STRING_TYPE& orders_orderpriority, const STRING_TYPE& orders_clerk, const long orders_shippriority, const STRING_TYPE& orders_comment) {
{ if (tS>0) { ++tS; return; } if ((tN&127)==0) { gettimeofday(&(t),NULL); tT=((t).tv_sec-(t0).tv_sec)*1000000L+((t).tv_usec-(t0).tv_usec); if (tT>3600000000L) { tS=1; return; } } ++tN;
agg1.clear();
{ // foreach
const HashIndex_CUSTDIST_mCUSTOMER_IVC1_E1_1_map_0* i1 = static_cast<HashIndex_CUSTDIST_mCUSTOMER_IVC1_E1_1_map_0*>(CUSTDIST_mCUSTOMER_IVC1_E1_1.index[0]);
HashIndex_CUSTDIST_mCUSTOMER_IVC1_E1_1_map_0::IdxNode* n1;
CUSTDIST_mCUSTOMER_IVC1_E1_1_entry* e1;
for (size_t i = 0; i < i1->size_; i++)
{
n1 = i1->buckets_ + i;
while (n1 && (e1 = n1->obj))
{
long c_orders_c_custkey = e1->C_ORDERS_C_CUSTKEY;
long v1 = e1->__av;
long l1 = CUSTDIST_mCUSTOMER_IVC1_E1_1.getValueOrDefault(se2.modify(c_orders_c_custkey));
agg1.addOrDelOnZero(st1.modify(l1,(v1 != 0 ? 1L : 0L)), (v1 != 0 ? 1L : 0L));
n1 = n1->nxt;
}
}
}{ // temp foreach
const HashIndex<tuple2_L_L, long>* i2 = static_cast<HashIndex<tuple2_L_L, long>*>(agg1.index[0]);
HashIndex<tuple2_L_L, long>::IdxNode* n2;
tuple2_L_L* e2;
for (size_t i = 0; i < i2->size_; i++)
{
n2 = i2->buckets_ + i;
while (n2 && (e2 = n2->obj))
{
long c_orders_c_count = e2->_1;
long v2 = e2->__av;
if (CUSTDIST.getValueOrDefault(se1.modify(c_orders_c_count))==0) CUSTDIST.setOrDelOnZero(se1, v2);
n2 = n2->nxt;
}
}
}long l2 = (CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se3.modify(orders_custkey)) * CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se4.modify(orders_custkey)));
CUSTDIST.addOrDelOnZero(se1.modify(l2),(((CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se5.modify(orders_custkey)) * CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se6.modify(orders_custkey))) != 0 ? 1L : 0L) * -1L));
long l3 = (CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se7.modify(orders_custkey)) * (CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se8.modify(orders_custkey)) + (/*if */(0L == Upreg_match(preg1,orders_comment)) ? 1L : 0L)));
CUSTDIST.addOrDelOnZero(se1.modify(l3),((CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se9.modify(orders_custkey)) * (CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se10.modify(orders_custkey)) + (/*if */(0L == Upreg_match(preg1,orders_comment)) ? 1L : 0L))) != 0 ? 1L : 0L));
(/*if */(0L == Upreg_match(preg1,orders_comment)) ? CUSTDIST_mCUSTOMER_IVC1_E1_1.addOrDelOnZero(se11.modify(orders_custkey),CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se12.modify(orders_custkey))) : (void)0);
(/*if */(0L == Upreg_match(preg1,orders_comment)) ? CUSTDIST_mCUSTOMER1_L1_2.addOrDelOnZero(se13.modify(orders_custkey),1L) : (void)0);
}
}
void on_delete_ORDERS(const long orders_orderkey, const long orders_custkey, const STRING_TYPE& orders_orderstatus, const DOUBLE_TYPE orders_totalprice, const date orders_orderdate, const STRING_TYPE& orders_orderpriority, const STRING_TYPE& orders_clerk, const long orders_shippriority, const STRING_TYPE& orders_comment) {
{ if (tS>0) { ++tS; return; } if ((tN&127)==0) { gettimeofday(&(t),NULL); tT=((t).tv_sec-(t0).tv_sec)*1000000L+((t).tv_usec-(t0).tv_usec); if (tT>3600000000L) { tS=1; return; } } ++tN;
agg2.clear();
{ // foreach
const HashIndex_CUSTDIST_mCUSTOMER_IVC1_E1_1_map_0* i3 = static_cast<HashIndex_CUSTDIST_mCUSTOMER_IVC1_E1_1_map_0*>(CUSTDIST_mCUSTOMER_IVC1_E1_1.index[0]);
HashIndex_CUSTDIST_mCUSTOMER_IVC1_E1_1_map_0::IdxNode* n3;
CUSTDIST_mCUSTOMER_IVC1_E1_1_entry* e3;
for (size_t i = 0; i < i3->size_; i++)
{
n3 = i3->buckets_ + i;
while (n3 && (e3 = n3->obj))
{
long c_orders_c_custkey = e3->C_ORDERS_C_CUSTKEY;
long v3 = e3->__av;
long l4 = CUSTDIST_mCUSTOMER_IVC1_E1_1.getValueOrDefault(se15.modify(c_orders_c_custkey));
agg2.addOrDelOnZero(st2.modify(l4,(v3 != 0 ? 1L : 0L)), (v3 != 0 ? 1L : 0L));
n3 = n3->nxt;
}
}
}{ // temp foreach
const HashIndex<tuple2_L_L, long>* i4 = static_cast<HashIndex<tuple2_L_L, long>*>(agg2.index[0]);
HashIndex<tuple2_L_L, long>::IdxNode* n4;
tuple2_L_L* e4;
for (size_t i = 0; i < i4->size_; i++)
{
n4 = i4->buckets_ + i;
while (n4 && (e4 = n4->obj))
{
long c_orders_c_count = e4->_1;
long v4 = e4->__av;
if (CUSTDIST.getValueOrDefault(se14.modify(c_orders_c_count))==0) CUSTDIST.setOrDelOnZero(se14, v4);
n4 = n4->nxt;
}
}
}long l5 = (CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se16.modify(orders_custkey)) * CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se17.modify(orders_custkey)));
CUSTDIST.addOrDelOnZero(se14.modify(l5),(((CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se18.modify(orders_custkey)) * CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se19.modify(orders_custkey))) != 0 ? 1L : 0L) * -1L));
long l6 = (CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se20.modify(orders_custkey)) * (CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se21.modify(orders_custkey)) + (/*if */(0L == Upreg_match(preg1,orders_comment)) ? -1L : 0L)));
CUSTDIST.addOrDelOnZero(se14.modify(l6),((CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se22.modify(orders_custkey)) * (CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se23.modify(orders_custkey)) + (/*if */(0L == Upreg_match(preg1,orders_comment)) ? -1L : 0L))) != 0 ? 1L : 0L));
(/*if */(0L == Upreg_match(preg1,orders_comment)) ? CUSTDIST_mCUSTOMER_IVC1_E1_1.addOrDelOnZero(se24.modify(orders_custkey),(CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se25.modify(orders_custkey)) * -1L)) : (void)0);
(/*if */(0L == Upreg_match(preg1,orders_comment)) ? CUSTDIST_mCUSTOMER1_L1_2.addOrDelOnZero(se26.modify(orders_custkey),-1L) : (void)0);
}
}
void on_insert_CUSTOMER(const long customer_custkey, const STRING_TYPE& customer_name, const STRING_TYPE& customer_address, const long customer_nationkey, const STRING_TYPE& customer_phone, const DOUBLE_TYPE customer_acctbal, const STRING_TYPE& customer_mktsegment, const STRING_TYPE& customer_comment) {
{ if (tS>0) { ++tS; return; } if ((tN&127)==0) { gettimeofday(&(t),NULL); tT=((t).tv_sec-(t0).tv_sec)*1000000L+((t).tv_usec-(t0).tv_usec); if (tT>3600000000L) { tS=1; return; } } ++tN;
agg3.clear();
{ // foreach
const HashIndex_CUSTDIST_mCUSTOMER_IVC1_E1_1_map_0* i5 = static_cast<HashIndex_CUSTDIST_mCUSTOMER_IVC1_E1_1_map_0*>(CUSTDIST_mCUSTOMER_IVC1_E1_1.index[0]);
HashIndex_CUSTDIST_mCUSTOMER_IVC1_E1_1_map_0::IdxNode* n5;
CUSTDIST_mCUSTOMER_IVC1_E1_1_entry* e5;
for (size_t i = 0; i < i5->size_; i++)
{
n5 = i5->buckets_ + i;
while (n5 && (e5 = n5->obj))
{
long c_orders_c_custkey = e5->C_ORDERS_C_CUSTKEY;
long v5 = e5->__av;
long l7 = CUSTDIST_mCUSTOMER_IVC1_E1_1.getValueOrDefault(se28.modify(c_orders_c_custkey));
agg3.addOrDelOnZero(st3.modify(l7,(v5 != 0 ? 1L : 0L)), (v5 != 0 ? 1L : 0L));
n5 = n5->nxt;
}
}
}{ // temp foreach
const HashIndex<tuple2_L_L, long>* i6 = static_cast<HashIndex<tuple2_L_L, long>*>(agg3.index[0]);
HashIndex<tuple2_L_L, long>::IdxNode* n6;
tuple2_L_L* e6;
for (size_t i = 0; i < i6->size_; i++)
{
n6 = i6->buckets_ + i;
while (n6 && (e6 = n6->obj))
{
long c_orders_c_count = e6->_1;
long v6 = e6->__av;
if (CUSTDIST.getValueOrDefault(se27.modify(c_orders_c_count))==0) CUSTDIST.setOrDelOnZero(se27, v6);
n6 = n6->nxt;
}
}
}long l8 = (CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se29.modify(customer_custkey)) * CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se30.modify(customer_custkey)));
CUSTDIST.addOrDelOnZero(se27.modify(l8),(((CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se31.modify(customer_custkey)) * CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se32.modify(customer_custkey))) != 0 ? 1L : 0L) * -1L));
long l9 = (CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se33.modify(customer_custkey)) * (CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se34.modify(customer_custkey)) + 1L));
CUSTDIST.addOrDelOnZero(se27.modify(l9),((CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se35.modify(customer_custkey)) * (CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se36.modify(customer_custkey)) + 1L)) != 0 ? 1L : 0L));
CUSTDIST_mCUSTOMER_IVC1_E1_1.addOrDelOnZero(se37.modify(customer_custkey),CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se38.modify(customer_custkey)));
CUSTDIST_mCUSTOMER1_L1_1.addOrDelOnZero(se39.modify(customer_custkey),1L);
}
}
void on_delete_CUSTOMER(const long customer_custkey, const STRING_TYPE& customer_name, const STRING_TYPE& customer_address, const long customer_nationkey, const STRING_TYPE& customer_phone, const DOUBLE_TYPE customer_acctbal, const STRING_TYPE& customer_mktsegment, const STRING_TYPE& customer_comment) {
{ if (tS>0) { ++tS; return; } if ((tN&127)==0) { gettimeofday(&(t),NULL); tT=((t).tv_sec-(t0).tv_sec)*1000000L+((t).tv_usec-(t0).tv_usec); if (tT>3600000000L) { tS=1; return; } } ++tN;
agg4.clear();
{ // foreach
const HashIndex_CUSTDIST_mCUSTOMER_IVC1_E1_1_map_0* i7 = static_cast<HashIndex_CUSTDIST_mCUSTOMER_IVC1_E1_1_map_0*>(CUSTDIST_mCUSTOMER_IVC1_E1_1.index[0]);
HashIndex_CUSTDIST_mCUSTOMER_IVC1_E1_1_map_0::IdxNode* n7;
CUSTDIST_mCUSTOMER_IVC1_E1_1_entry* e7;
for (size_t i = 0; i < i7->size_; i++)
{
n7 = i7->buckets_ + i;
while (n7 && (e7 = n7->obj))
{
long c_orders_c_custkey = e7->C_ORDERS_C_CUSTKEY;
long v7 = e7->__av;
long l10 = CUSTDIST_mCUSTOMER_IVC1_E1_1.getValueOrDefault(se41.modify(c_orders_c_custkey));
agg4.addOrDelOnZero(st4.modify(l10,(v7 != 0 ? 1L : 0L)), (v7 != 0 ? 1L : 0L));
n7 = n7->nxt;
}
}
}{ // temp foreach
const HashIndex<tuple2_L_L, long>* i8 = static_cast<HashIndex<tuple2_L_L, long>*>(agg4.index[0]);
HashIndex<tuple2_L_L, long>::IdxNode* n8;
tuple2_L_L* e8;
for (size_t i = 0; i < i8->size_; i++)
{
n8 = i8->buckets_ + i;
while (n8 && (e8 = n8->obj))
{
long c_orders_c_count = e8->_1;
long v8 = e8->__av;
if (CUSTDIST.getValueOrDefault(se40.modify(c_orders_c_count))==0) CUSTDIST.setOrDelOnZero(se40, v8);
n8 = n8->nxt;
}
}
}long l11 = (CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se42.modify(customer_custkey)) * CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se43.modify(customer_custkey)));
CUSTDIST.addOrDelOnZero(se40.modify(l11),(((CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se44.modify(customer_custkey)) * CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se45.modify(customer_custkey))) != 0 ? 1L : 0L) * -1L));
long l12 = (CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se46.modify(customer_custkey)) * (CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se47.modify(customer_custkey)) + -1L));
CUSTDIST.addOrDelOnZero(se40.modify(l12),((CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se48.modify(customer_custkey)) * (CUSTDIST_mCUSTOMER1_L1_1.getValueOrDefault(se49.modify(customer_custkey)) + -1L)) != 0 ? 1L : 0L));
CUSTDIST_mCUSTOMER_IVC1_E1_1.addOrDelOnZero(se50.modify(customer_custkey),(CUSTDIST_mCUSTOMER1_L1_2.getValueOrDefault(se51.modify(customer_custkey)) * -1L));
CUSTDIST_mCUSTOMER1_L1_1.addOrDelOnZero(se52.modify(customer_custkey),-1L);
}
}
void on_system_ready_event() {
{
}
}
private:
/* Sample entries for avoiding recreation of temporary objects */
CUSTDIST_entry se1;
CUSTDIST_mCUSTOMER_IVC1_E1_1_entry se2;
tuple2_L_L st1;
CUSTDIST_mCUSTOMER1_L1_1_entry se3;
CUSTDIST_mCUSTOMER1_L1_2_entry se4;
CUSTDIST_mCUSTOMER1_L1_1_entry se5;
CUSTDIST_mCUSTOMER1_L1_2_entry se6;
CUSTDIST_mCUSTOMER1_L1_1_entry se7;
CUSTDIST_mCUSTOMER1_L1_2_entry se8;
CUSTDIST_mCUSTOMER1_L1_1_entry se9;
CUSTDIST_mCUSTOMER1_L1_2_entry se10;
CUSTDIST_mCUSTOMER_IVC1_E1_1_entry se11;
CUSTDIST_mCUSTOMER1_L1_1_entry se12;
CUSTDIST_mCUSTOMER1_L1_2_entry se13;
CUSTDIST_entry se14;
CUSTDIST_mCUSTOMER_IVC1_E1_1_entry se15;
tuple2_L_L st2;
CUSTDIST_mCUSTOMER1_L1_1_entry se16;
CUSTDIST_mCUSTOMER1_L1_2_entry se17;
CUSTDIST_mCUSTOMER1_L1_1_entry se18;
CUSTDIST_mCUSTOMER1_L1_2_entry se19;
CUSTDIST_mCUSTOMER1_L1_1_entry se20;
CUSTDIST_mCUSTOMER1_L1_2_entry se21;
CUSTDIST_mCUSTOMER1_L1_1_entry se22;
CUSTDIST_mCUSTOMER1_L1_2_entry se23;
CUSTDIST_mCUSTOMER_IVC1_E1_1_entry se24;
CUSTDIST_mCUSTOMER1_L1_1_entry se25;
CUSTDIST_mCUSTOMER1_L1_2_entry se26;
CUSTDIST_entry se27;
CUSTDIST_mCUSTOMER_IVC1_E1_1_entry se28;
tuple2_L_L st3;
CUSTDIST_mCUSTOMER1_L1_1_entry se29;
CUSTDIST_mCUSTOMER1_L1_2_entry se30;
CUSTDIST_mCUSTOMER1_L1_1_entry se31;
CUSTDIST_mCUSTOMER1_L1_2_entry se32;
CUSTDIST_mCUSTOMER1_L1_2_entry se33;
CUSTDIST_mCUSTOMER1_L1_1_entry se34;
CUSTDIST_mCUSTOMER1_L1_2_entry se35;
CUSTDIST_mCUSTOMER1_L1_1_entry se36;
CUSTDIST_mCUSTOMER_IVC1_E1_1_entry se37;
CUSTDIST_mCUSTOMER1_L1_2_entry se38;
CUSTDIST_mCUSTOMER1_L1_1_entry se39;
CUSTDIST_entry se40;
CUSTDIST_mCUSTOMER_IVC1_E1_1_entry se41;
tuple2_L_L st4;
CUSTDIST_mCUSTOMER1_L1_1_entry se42;
CUSTDIST_mCUSTOMER1_L1_2_entry se43;
CUSTDIST_mCUSTOMER1_L1_1_entry se44;
CUSTDIST_mCUSTOMER1_L1_2_entry se45;
CUSTDIST_mCUSTOMER1_L1_2_entry se46;
CUSTDIST_mCUSTOMER1_L1_1_entry se47;
CUSTDIST_mCUSTOMER1_L1_2_entry se48;
CUSTDIST_mCUSTOMER1_L1_1_entry se49;
CUSTDIST_mCUSTOMER_IVC1_E1_1_entry se50;
CUSTDIST_mCUSTOMER1_L1_2_entry se51;
CUSTDIST_mCUSTOMER1_L1_1_entry se52;
/* regex_t temporary objects */
regex_t preg1;
/* Data structures used for storing materialized views */
CUSTDIST_mCUSTOMER_IVC1_E1_1_map CUSTDIST_mCUSTOMER_IVC1_E1_1;
CUSTDIST_mCUSTOMER1_L1_1_map CUSTDIST_mCUSTOMER1_L1_1;
CUSTDIST_mCUSTOMER1_L1_2_map CUSTDIST_mCUSTOMER1_L1_2;
MultiHashMap<tuple2_L_L,long,HashIndex<tuple2_L_L,long> > agg2;
MultiHashMap<tuple2_L_L,long,HashIndex<tuple2_L_L,long> > agg4;
MultiHashMap<tuple2_L_L,long,HashIndex<tuple2_L_L,long> > agg1;
MultiHashMap<tuple2_L_L,long,HashIndex<tuple2_L_L,long> > agg3;
};
}
| 52.463043 | 328 | 0.695852 |
0120cb3c518dc7e577506ec76c317ca23a2c125f | 412 | cpp | C++ | a/a216.cpp | mirkat1206/zerojudge_cpp | 263cd51f4eee4acec8396f6c069bba540ac15e96 | [
"BSD-2-Clause"
] | 1 | 2019-12-27T03:03:50.000Z | 2019-12-27T03:03:50.000Z | a/a216.cpp | mirkat1206/zerojudge_cpp | 263cd51f4eee4acec8396f6c069bba540ac15e96 | [
"BSD-2-Clause"
] | null | null | null | a/a216.cpp | mirkat1206/zerojudge_cpp | 263cd51f4eee4acec8396f6c069bba540ac15e96 | [
"BSD-2-Clause"
] | null | null | null | // a216 : 數數愛明明
#include <cstdio>
#define N 30010
int main()
{
// f[n] = n + f[n-1], g[n] = f[n] + g[n-1], f[1] = g[1] = 1
// f[i], g[i] is on day i !!!
long long int f[N] = { 0 , 1 , 3 }, g[N] = { 0 , 1 } ;
for( int i=3 ; i<N ; i++ )
{
f[i] = i + f[i-1] ;
g[i-1] = f[i-1] + g[i-2] ;
}
int n;
while( scanf("%lld", &n )!=EOF )
printf("%lld %lld\n", f[n] , g[n] );
return 0;
} | 19.619048 | 61 | 0.393204 |
01215b320c80daaf94dc18a75469ceeffbd1cd72 | 7,317 | cc | C++ | ARM/NXP/Flash/FCB.cc | JohnAdriaan/RTX2C3 | 833cfa45ece56a1516cb743c6bafa7c916451e55 | [
"BSD-3-Clause"
] | null | null | null | ARM/NXP/Flash/FCB.cc | JohnAdriaan/RTX2C3 | 833cfa45ece56a1516cb743c6bafa7c916451e55 | [
"BSD-3-Clause"
] | null | null | null | ARM/NXP/Flash/FCB.cc | JohnAdriaan/RTX2C3 | 833cfa45ece56a1516cb743c6bafa7c916451e55 | [
"BSD-3-Clause"
] | null | null | null | // © 2019 John Adriaan. Licensed under the "3-clause BSD License"
///
/// \file ARM/NXP/Flash/FCB.cc
///
/// This file defines and instantiates the Flash Control Block at a known address.
/// The FCB is used by the i.MX RT10xx to best configure the Flash for use.
/// Note that this is completely self-contained - no external reference needs
/// to be made to this module.
///
#include <ARM/NXP/NXP.hh>
namespace ARM::NXP::Flash {
/// FlexSPI Configuration Block
struct FlexSPIConfig {
struct Version {
byte bugfix;
byte minor;
byte major;
const char v = 'V';
}; // Version
static_assert(sizeof(Version)==4, "Incorrect Version size");
enum SampleClkSrcs : byte {
Internal = 0,
Loopback = 1,
FlashDQS = 3
}; // SampleClkSrcs
struct LUTs {
byte number; ///< Number of LUT sequences
byte index; ///< Starting LUT index
const word x2 = Rsvd16; ///< Reserved
}; // LUTs
static_assert(sizeof(LUTs)==4, "Incorrect LUTs size");
struct MiscOptions {
bit diffClkEnable : 1;
unsigned : 1;
bit parallelModeEnable : 1;
bit wordAddressableEnable : 1;
bit safeConfigFreqEnable : 1;
bit padSettingOverrideEnable : 1;
bit ddrModeEnable : 1;
unsigned : 2;
bit secondDQSPinMux : 1;
unsigned : 22;
unsigned : 0;
}; // MiscOptions
static_assert(sizeof(MiscOptions)==sizeof(unsigned), "Incorrect MiscOptions size");
enum DeviceTypes : byte {
DeviceUnknown = 0, ///< *** Examples have this value
SerialNOR = 1 ///< *** Documents show this is only valid option
}; // DeviceTypes
enum Pads : byte {
SinglePad = 1,
DualPads = 2,
QuadPads = 4,
OctalPads = 8
}; // Pads
enum ClockFreqs : byte {
Freq30MHz = 1,
Freq50MHz = 2,
Freq60MHz = 3,
Freq75MHz = 4,
Freq80MHz = 5,
Freq100MHz = 6,
Freq120MHz = 7,
Freq133MHz = 8
}; // ClockFreqs
struct ValidTimes {
word dllA;
word dllB;
}; // ValidTimes
static_assert(sizeof(ValidTimes)==sizeof(unsigned), "Incorrect ValidTimes size");
enum Busys : word {
Busy1 = 0, ///< 0: "Busy Bit==1 when busy
Busy0 = 1 ///< 1: "Busy Bit==0 when busy
}; // Busys
enum LUTPads {
Pad1 = 0,
Pad2 = 1,
Pad4 = 2,
Pad8 = 3
}; // LUTPads
enum Instructions {
STOP = 0,
JMP = 9,
CMD = 1,
ADDR = 2,
DUMMY = 3,
MODE = 4,
MODE2 = 5,
MODE4 = 6,
READ = 7,
WRITE = 8,
CMD_DDR = 0x11,
ADDR_DDR = 0x0A,
MODE_DDR = 0x0B,
MODE2_DDR = 0x0C,
MODE4_DDR = 0x0D,
READ_DDR = 0x0E,
WRITE_DDR = 0x0F
}; // Instructions
struct LUTCommand {
byte operand : 8;
LUTPads pad : 2;
Instructions instruction : 6;
word : 0;
}; // LUTCommand
static_assert(sizeof(LUTCommand)==2, "Incorrect LUTCommand size");
typedef LUTCommand LUTSequence[8];
static_assert(sizeof(LUTSequence)==16, "Incorrect LUTCommand size");
const char tag[4] = { 'F', 'C', 'F', 'B' }; ///< Tag to identify block
Version version = { .bugfix=0, .minor=4, .major=1 };
const unsigned x008 = Rsvd32; ///< Reserved
SampleClkSrcs readSampleClkSrc = Loopback; ///< Sample DQS Pad
byte csHoldTime = 3; ///< Column Select Hold Time. Recommended value
byte csSetupTime = 3; ///< Column Select Setup Time. Recommended value
byte columnAddressWidth = 0; ///< Not HyperFlash
byte deviceModeCfgEnable = No; ///< Don't enable Config
const byte x011 = Rsvd8; ///< Reserved
word waitTimeCfgCommands = 0; ///< in 100us. Note v1.1.0 minimum
LUTs deviceModeSeq = { .number=0, .index=0 };
unsigned deviceModeArg = 0; ///< `deviceModeCfgEnable` must be `1`
byte configCmdEnable = No;
const byte x01D[3] = { Rsvd8, Rsvd8, Rsvd8 }; ///< Reserved
unsigned configCmdSeqs[3] = { 0, 0, 0 };
const unsigned x02C = Rsvd8; ///< Reserved
unsigned cfgCmdArgs[3] = { 0, 0, 0 };
const unsigned x03C = Rsvd8; ///< Reserved
MiscOptions controllerMiscOption = { };
DeviceTypes deviceType = SerialNOR;
Pads sflashPadType = QuadPads;
ClockFreqs serialClkFreq = Freq100MHz;
byte lutCustomSeqEnable = No;
const unsigned x048[2] = { Rsvd32, Rsvd32 };
unsigned sflashA1Size = 0x0100'0000;
unsigned sflashA2Size = 0x0000'0000;
unsigned sflashB1Size = 0x0000'0000;
unsigned sflashB2Size = 0x0000'0000;
unsigned csPadSettingOverride = No;
unsigned sclkPadSettingOverride = No;
unsigned dataPadSettingOverride = No;
unsigned dqsPadSettingOverride = No;
unsigned timeoutInMs = 0;
unsigned commandInterval = 0; ///< in ns
ValidTimes dataValidTimes = { .dllA = 0, .dllB = 0 };
word busyOffset = 0; ///< Valid range: 0-31
Busys busyBitPolarity = Busy1;
LUTSequence lookupTable[16] = { { { .operand = 0xEB, .pad = Pad1, .instruction = CMD }, ///< 4xI/O, READ
{ .operand = 24, .pad = Pad4, .instruction = ADDR }, ///< 24 bits
{ .operand = 6, .pad = Pad4, .instruction = MODE2_DDR }, ///< 6 Dummy cycles
// { .operand = 0, .pad = Pad1, .instruction = STOP } } }; ///< And STOP
/*** This final command could simply be STOP? ***/ { .operand = 1<<2, .pad = Pad4, .instruction = JMP } } }; ///< JMP LUT[1]
LUTSequence lutCustomSeq[3] = { };
unsigned reserved[4] = { Rsvd32, Rsvd32, Rsvd32, Rsvd32 };
}; // FlexSPIConfig
static_assert(sizeof(FlexSPIConfig)==0x1C0, "Incorrect FlexSPIConfig size");
struct SerialNORConfig {
enum ClockFreqs {
ClockUnchanged = 0,
Clock30MHz = 1,
Clock50MHz = 2,
Clock60MHz = 3,
Clock75MHz = 4,
Clock80MHz = 5,
Clock100MHz = 6,
Clock133MHz = 7
}; // ClockFreqs
FlexSPIConfig fcb = { };
unsigned pageSize = 0x0100;
unsigned sectorSize = 0x1000;
ClockFreqs ipCmdSerialClockFreq = ClockUnchanged;
unsigned reserved[13] = { Rsvd32, Rsvd32, Rsvd32, Rsvd32, Rsvd32, Rsvd32, Rsvd32,
Rsvd32, Rsvd32, Rsvd32, Rsvd32, Rsvd32, Rsvd32 };
}; // SerialNORConfigBlock
static_assert(sizeof(SerialNORConfig)==0x200, "Incorrect SerialNORConfig size");
SECTION(".FCB")
const SerialNORConfig serialNORConfig;
} // namespace ARM::NXP::Flash
| 36.402985 | 129 | 0.531502 |
0125409ff226d969876cee1c1b41b80f3bdcfc9e | 8,747 | hh | C++ | aku/FeatureModules.hh | lingsoft/AaltoASR | 40343e215a6cf1b7d5ed41a53095495567b0ab01 | [
"BSD-3-Clause"
] | 78 | 2015-01-07T14:33:47.000Z | 2022-03-15T09:01:30.000Z | aku/FeatureModules.hh | ufukhurriyetoglu/AaltoASR | 02b23d374ab9be9b0fd5d8159570b509ede066f3 | [
"BSD-3-Clause"
] | 4 | 2015-05-19T13:00:34.000Z | 2016-07-26T12:29:32.000Z | aku/FeatureModules.hh | ufukhurriyetoglu/AaltoASR | 02b23d374ab9be9b0fd5d8159570b509ede066f3 | [
"BSD-3-Clause"
] | 32 | 2015-01-16T08:16:24.000Z | 2021-04-02T21:26:22.000Z | #ifndef FEATUREMODULES_HH
#define FEATUREMODULES_HH
#include <vector>
#include "ModuleConfig.hh"
#include "FeatureModule.hh"
#include "BaseFeaModule.hh"
#include "AudioFileModule.hh"
#include "FFTModule.hh"
namespace aku {
class FeatureGenerator;
//////////////////////////////////////////////////////////////////
// Feature module implementations
//////////////////////////////////////////////////////////////////
class PreModule : public BaseFeaModule {
public:
PreModule();
static const char *type_str() { return "pre"; }
virtual void set_fname(const char *fname);
virtual void set_file(FILE *fp, bool stream=false);
virtual void discard_file(void);
virtual bool eof(int frame);
virtual int sample_rate(void) { return m_sample_rate; }
virtual float frame_rate(void) { return m_frame_rate; }
virtual int last_frame(void);
private:
virtual void get_module_config(ModuleConfig &config);
virtual void set_module_config(const ModuleConfig &config);
virtual void reset_module();
virtual void generate(int frame);
private:
int m_sample_rate;
float m_frame_rate;
int m_eof_frame;
int m_legacy_file; //!< If nonzero, the dimension in the file is a byte
int m_file_offset;
int m_cur_pre_frame;
bool m_close_file;
FILE *m_fp;
std::vector<double> m_first_feature; //!< Feature returned for negative frames
std::vector<double> m_last_feature; //!< Feature returned after EOF
int m_last_feature_frame; //!< The frame of the feature returned after EOF
std::vector<float> m_temp_fea_buf; //!< Need a float buffer for reading
};
class MelModule : public FeatureModule {
public:
MelModule(FeatureGenerator *fea_gen);
static const char *type_str() { return "mel"; }
private:
virtual void get_module_config(ModuleConfig &config);
virtual void set_module_config(const ModuleConfig &config);
virtual void generate(int frame);
void create_mel_bins(void);
private:
FeatureGenerator *m_fea_gen;
int m_bins;
int m_root; //!< If nonzero, take 10th root of the output instead of logarithm
std::vector<float> m_bin_edges;
};
class PowerModule : public FeatureModule {
public:
PowerModule();
static const char *type_str() { return "power"; }
private:
virtual void get_module_config(ModuleConfig &config);
virtual void set_module_config(const ModuleConfig &config);
virtual void generate(int frame);
};
class MelPowerModule : public FeatureModule {
public:
MelPowerModule();
static const char *type_str() { return "mel_power"; }
private:
virtual void get_module_config(ModuleConfig &config);
virtual void set_module_config(const ModuleConfig &config);
virtual void generate(int frame);
};
class DCTModule : public FeatureModule {
public:
DCTModule();
static const char *type_str() { return "dct"; }
private:
virtual void get_module_config(ModuleConfig &config);
virtual void set_module_config(const ModuleConfig &config);
virtual void generate(int frame);
private:
int m_zeroth_comp; //!< If nonzero, output includes zeroth component
};
class DeltaModule : public FeatureModule {
public:
DeltaModule();
static const char *type_str() { return "delta"; }
private:
virtual void get_module_config(ModuleConfig &config);
virtual void set_module_config(const ModuleConfig &config);
virtual void generate(int frame);
private:
int m_delta_width;
float m_delta_norm;
};
class NormalizationModule : public FeatureModule {
public:
NormalizationModule();
static const char *type_str() { return "normalization"; }
void set_normalization(const std::vector<float> &mean,
const std::vector<float> &scale);
private:
virtual void get_module_config(ModuleConfig &config);
virtual void set_module_config(const ModuleConfig &config);
virtual void set_parameters(const ModuleConfig &config);
virtual void get_parameters(ModuleConfig &config);
virtual void generate(int frame);
private:
std::vector<float> m_mean;
std::vector<float> m_scale;
};
class LinTransformModule : public FeatureModule {
public:
LinTransformModule();
static const char *type_str() { return "lin_transform"; }
const std::vector<float> *get_transformation_matrix(void) { return &m_transform; }
const std::vector<float> *get_transformation_bias(void) { return &m_bias; }
void set_transformation_matrix(std::vector<float> &t);
void set_transformation_bias(std::vector<float> &b);
virtual void set_parameters(const ModuleConfig &config);
virtual void get_parameters(ModuleConfig &config);
private:
virtual void get_module_config(ModuleConfig &config);
virtual void set_module_config(const ModuleConfig &config);
virtual void generate(int frame);
void check_transform_parameters(void);
private:
std::vector<float> m_transform;
std::vector<float> m_bias;
std::vector<float> m_original_transform;
std::vector<float> m_original_bias;
bool m_matrix_defined, m_bias_defined;
int m_src_dim;
public:
virtual bool is_defined() { return m_matrix_defined && m_bias_defined; }
};
class MergerModule : public FeatureModule {
public:
MergerModule();
static const char *type_str() { return "merge"; }
virtual void add_source(FeatureModule *source);
private:
virtual void get_module_config(ModuleConfig &config);
virtual void set_module_config(const ModuleConfig &config);
virtual void generate(int frame);
};
class MeanSubtractorModule : public FeatureModule {
public:
MeanSubtractorModule();
static const char *type_str() { return "mean_subtractor"; }
private:
virtual void get_module_config(ModuleConfig &config);
virtual void set_module_config(const ModuleConfig &config);
virtual void reset_module();
virtual void generate(int frame);
private:
std::vector<double> m_cur_mean;
int m_cur_frame;
int m_width;
};
class ConcatModule : public FeatureModule {
public:
ConcatModule();
static const char *type_str() { return "concat"; }
private:
virtual void get_module_config(ModuleConfig &config);
virtual void set_module_config(const ModuleConfig &config);
virtual void generate(int frame);
private:
int left, right;
};
class VtlnModule : public FeatureModule {
public:
VtlnModule();
static const char *type_str() { return "vtln"; }
void set_warp_factor(float factor);
void set_slapt_warp(std::vector<float> ¶ms);
float get_warp_factor(void) { return m_warp_factor; }
virtual void set_parameters(const ModuleConfig &config);
virtual void get_parameters(ModuleConfig &config);
private:
virtual void get_module_config(ModuleConfig &config);
virtual void set_module_config(const ModuleConfig &config);
virtual void generate(int frame);
void create_pwlin_bins(void);
void create_blin_bins(void);
void create_slapt_bins(void);
void create_sinc_coef_table(void);
void create_all_pass_blin_transform(void);
void create_all_pass_slapt_transform(void);
void set_all_pass_transform(Matrix &trmat);
private:
int m_use_pwlin;
float m_pwlin_turn_point;
int m_use_slapt;
int m_sinc_interpolation_rad;
int m_all_pass;
bool m_lanczos_window;
std::vector<float> m_vtln_bins;
std::vector< std::vector<float> > m_sinc_coef;
std::vector<int> m_sinc_coef_start;
float m_warp_factor;
std::vector<float> m_slapt_params;
};
class SRNormModule : public FeatureModule {
public:
SRNormModule();
static const char *type_str() { return "sr_norm"; }
void set_speech_rate(float factor);
float get_speech_rate(void) { return m_speech_rate; }
virtual void set_parameters(const ModuleConfig &config);
virtual void get_parameters(ModuleConfig &config);
private:
virtual void get_module_config(ModuleConfig &config);
virtual void set_module_config(const ModuleConfig &config);
virtual void generate(int frame);
private:
int m_in_frames;
int m_out_frames;
int m_frame_dim;
int m_lanczos_order;
float m_speech_rate;
std::vector< std::vector<float> > m_coef;
std::vector<int> m_interpolation_start;
};
class QuantEqModule : public FeatureModule {
public:
QuantEqModule();
static const char *type_str() { return "quanteq"; }
void set_alpha(std::vector<float> &alpha);
void set_gamma(std::vector<float> &gamma);
void set_quant_max(std::vector<float> &quant_max);
std::vector<float> get_quant_train(void) { return m_quant_train; }
virtual void set_parameters(const ModuleConfig &config);
virtual void get_parameters(ModuleConfig &config);
private:
virtual void get_module_config(ModuleConfig &config);
virtual void set_module_config(const ModuleConfig &config);
virtual void generate(int frame);
private:
std::vector<float> m_quant_train;
std::vector<float> m_alpha;
std::vector<float> m_gamma;
std::vector<float> m_quant_max;
};
}
#endif /* FEATUREMODULES_HH */
| 28.584967 | 84 | 0.745627 |
01255311cfc3027c017846c9e92e7b40af6bc7e5 | 7,212 | cpp | C++ | Plugin_Kade/Kade_Thread.cpp | ChaseBro/MMDAgent | 779cd3035954c27016333a2186896e1870e9ee54 | [
"Libpng",
"Zlib",
"Unlicense"
] | 9 | 2017-08-17T01:01:55.000Z | 2022-02-02T09:50:09.000Z | Plugin_Kade/Kade_Thread.cpp | ChaseBro/MMDAgent | 779cd3035954c27016333a2186896e1870e9ee54 | [
"Libpng",
"Zlib",
"Unlicense"
] | null | null | null | Plugin_Kade/Kade_Thread.cpp | ChaseBro/MMDAgent | 779cd3035954c27016333a2186896e1870e9ee54 | [
"Libpng",
"Zlib",
"Unlicense"
] | 4 | 2017-08-17T01:01:57.000Z | 2021-06-28T08:30:17.000Z | /* ----------------------------------------------------------------- */
/* The Toolkit for Building Voice Interaction Systems */
/* "MMDAgent" developed by MMDAgent Project Team */
/* http://www.mmdagent.jp/ */
/* ----------------------------------------------------------------- */
/* */
/* Copyright (c) 2009-2011 Nagoya Institute of Technology */
/* Department of Computer Science */
/* */
/* 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 MMDAgent project team 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. */
/* ----------------------------------------------------------------- */
/* headers */
#include "MMDAgent.h"
#include "Kade_Thread.h"
#include <Python.h>
/* File Globals */
PyObject *pModule;
PyObject *pProcPlainText, *pProcParse;
bool m_pause;
/* mainThread: main thread */
static void mainThread(void *param)
{
Kade_Thread *kade_thread = (Kade_Thread *) param;
kade_thread->run();
}
/* Kade_Thread::initialize: initialize thread */
void Kade_Thread::initialize()
{
m_mmdagent = NULL;
m_thread = -1;
m_configFile = NULL;
pModule = NULL;
pProcPlainText = NULL;
pProcParse = NULL;
}
/* Kade_Thread::clear: free thread */
void Kade_Thread::clear()
{
if(m_thread >= 0) {
glfwWaitThread(m_thread, GLFW_WAIT);
glfwDestroyThread(m_thread);
glfwTerminate();
}
if(m_configFile != NULL)
free(m_configFile);
if (pProcParse)
Py_DECREF(pProcParse);
if (pModule)
Py_DECREF(pModule);
Py_Finalize();
initialize();
}
/* Kade_Thread::Kade_Thread: thread constructor */
Kade_Thread::Kade_Thread()
{
initialize();
}
/* Kade_Thread::~Kade_Thread: thread destructor */
Kade_Thread::~Kade_Thread()
{
clear();
}
/* Kade_Thread::load: load models and start thread */
void Kade_Thread::load(MMDAgent *mmdagent, const char *configFile)
{
PyObject *pName;
char name[MMDAGENT_MAXBUFLEN];
Py_Initialize();
m_mmdagent = mmdagent;
m_configFile = MMDAgent_strdup(configFile);
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append(\"/home/robocep/MMDAgent/Release/AppData/Kade\")");
sprintf(name, "%s%c%s%c%s", mmdagent->getAppDirName(), MMDAGENT_DIRSEPARATOR, "Kade",MMDAGENT_DIRSEPARATOR, "kade");
pName = PyString_FromString("kade");
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule == NULL) {
printf("Error Loading python module: %s\n", PyString_AsString(pName));
return;
}
pProcParse = PyObject_GetAttrString(pModule, "procParse");
if (pProcParse == NULL) {
Py_DECREF(pModule);
printf("Error Loading procParse Function.\n");
return;
}
if(m_configFile == NULL) {
Py_DECREF(pProcParse);
Py_DECREF(pModule);
clear();
printf("Error Loading Config File.\n");
return;
}
m_pause = false;
/* create recognition thread
glfwInit();
m_thread = glfwCreateThread(mainThread, this);
if(m_thread < 0) {
clear();
return;
}
*/
}
/* Kade_Thread::run: main loop */
void Kade_Thread::run()
{
}
/* Kade_Thread::pause: pause recognition process */
void Kade_Thread::pause()
{
m_pause = true;
}
/* Kade_Thread::resume: resume recognition process */
void Kade_Thread::resume()
{
m_pause = false;
}
/* Kade_Thread::sendMessage: send message to MMDAgent */
void Kade_Thread::sendMessage(const char *str1, const char *str2)
{
m_mmdagent->sendEventMessage(str1, str2);
}
char* Kade_Thread::procParse(const char *plainText, const char *parse)
{
PyObject *pParse, *pAnswer, *pAnswerStr, *pArgs, *pPlain;
char *answerStr;
if (!pProcParse || !PyCallable_Check(pProcParse)) {
printf("procParse does not exists or is not callable.\n");
if (PyErr_Occurred())
PyErr_Print();
return NULL;
}
pParse = PyString_FromString(parse);
pPlain = PyString_FromString(plainText);
if (pParse != NULL && pPlain != NULL) {
pArgs = PyTuple_New(2);
if (pArgs != NULL) {
PyTuple_SetItem(pArgs, 0, pPlain);
PyTuple_SetItem(pArgs, 1, pParse);
pAnswer = PyObject_CallObject(pProcParse, pArgs);
if (pAnswer != NULL) {
pAnswerStr = PyObject_Str(pAnswer);
Py_DECREF(pAnswer);
Py_DECREF(pArgs);
answerStr = PyString_AsString(pAnswerStr);
Py_DECREF(pAnswerStr);
printf("Answer: %s\n", answerStr);
return answerStr;
}
Py_DECREF(pArgs);
} else
Py_DECREF(pParse);
Py_DECREF(pPlain);
}
printf("Error\n");
if (PyErr_Occurred())
PyErr_Print();
return NULL;
}
char* Kade_Thread::procPlainText(char *text)
{
return NULL;
}
| 31.631579 | 120 | 0.555047 |
012aaddbb70b4812f6398f41c04ebaeef57ce201 | 5,777 | cpp | C++ | ConvertTrips/Table_Process.cpp | kravitz/transims4 | ea0848bf3dc71440d54724bb3ecba3947b982215 | [
"NASA-1.3"
] | 2 | 2018-04-27T11:07:02.000Z | 2020-04-24T06:53:21.000Z | ConvertTrips/Table_Process.cpp | idkravitz/transims4 | ea0848bf3dc71440d54724bb3ecba3947b982215 | [
"NASA-1.3"
] | null | null | null | ConvertTrips/Table_Process.cpp | idkravitz/transims4 | ea0848bf3dc71440d54724bb3ecba3947b982215 | [
"NASA-1.3"
] | null | null | null | //*********************************************************
// Table_Process.cpp - Trip Table Processing
//*********************************************************
#include "ConvertTrips.hpp"
//---------------------------------------------------------
// Table_Processing
//---------------------------------------------------------
void ConvertTrips::Table_Processing (File_Group *group)
{
int num_share, tod, t, t1, t2, num_t, trp, o, d, period, current, first_t, last_t;
int total, stat, errors, org, des, trips, num, num_shares, duration, even_bucket, even;
bool share_flag, factor_flag, period_flag, scale_flag, return_flag;
double trip, factor, added, deleted, bucket;
Diurnal_Data *diurnal_ptr;
Matrix_File *file;
Factor_Data *factor_ptr;
static char *error_msg = "%d Trip%sbetween TAZs %d and %d could not be allocated";
//---- read the trip table ----
total = errors = 0;
added = deleted = 0.0;
file = group->Trip_File ();
return_flag = (group->Duration () > 0);
even_bucket = 1;
bucket = 0.45;
factor_flag = (group->Trip_Factor () != NULL);
period_flag = (group->Factor_Periods () > 0);
scale_flag = (group->Scaling_Factor () != 1.0);
num_shares = group->Num_Shares ();
share_flag = (num_shares > 0);
if (!share_flag) num_share = 1;
duration = group->Duration ();
first_t = t1 = 1;
last_t = t2 = num_t = diurnal_data.Num_Records ();
period = 0;
Show_Message (0, "\tReading %s -- Record", file->File_Type ());
Set_Progress (500);
while (file->Read ()) {
Show_Progress ();
org = file->Origin ();
if (org == 0) continue;
if (org < 1 || org > num_zone) {
Warning ("Origin TAZ %d is Out of Range (1-%d)", org, num_zone);
continue;
}
des = file->Destination ();
if (des < 1 || des > num_zone) {
Warning ("Destination TAZ %d is Out of Range (1-%d)", des, num_zone);
continue;
}
//---- check for a time period ----
if (file->Period_Flag () && period_flag) {
period = file->Period ();
if (period > 0) {
first_t = last_t = 0;
for (t=1; t <= num_t; t++) {
diurnal_ptr = diurnal_data [t];
tod = (diurnal_ptr->Start_Time () + diurnal_ptr->End_Time ()) / 2;
if (group->Factor_Period (tod) == period) {
if (first_t == 0) first_t = t;
last_t = t;
}
}
if (last_t == 0) {
first_t = 1;
last_t = num_t;
period = 0;
}
} else {
first_t = 1;
last_t = num_t;
period = 0;
}
}
trips = file->Data ();
if (trips < 0) {
Warning ("Number of Trips is Out of Range (%d < 0)", trips);
continue;
}
//---- apply the scaling factor ----
if (scale_flag) {
trip = trips * group->Scaling_Factor () + bucket;
trips = (int) trip;
if (trips < 0) trips = 0;
bucket = trip - trips;
}
if (trips == 0) continue;
total += trips;
//---- apply the selection script ----
if (share_flag) {
num = group->Execute ();
if (num < 1 || num > num_shares) {
Error ("Diurnal Selection Value %d is Out of Range (1..%d)", num, num_shares);
}
} else {
num = num_share;
}
//---- get the travel time ----
if (skim_flag) {
skim_ptr = ttime_skim.Get (org, des);
}
//---- apply adjustment factors ----
if (factor_flag) {
o = (equiv_flag) ? zone_equiv.Zone_Group (org) : org;
d = (equiv_flag) ? zone_equiv.Zone_Group (des) : des;
if (period_flag) {
period = -1;
t1 = t2 = 1;
trip = 0.0;
for (t=first_t; t <= last_t; t++) {
diurnal_ptr = diurnal_data [t];
tod = (diurnal_ptr->Start_Time () + diurnal_ptr->End_Time ()) / 2;
current = group->Factor_Period (tod);
if (current != period) {
if (period >= 0) {
factor_ptr = factor_data.Get (o, d, period);
if (factor_ptr == NULL) {
factor_ptr = &default_factor;
}
factor = trip * factor_ptr->Factor ();
if (factor > trip) {
added += factor - trip;
} else {
deleted += trip - factor;
}
trp = factor_ptr->Bucket_Factor (trip);
if (trp > 0 && return_flag) {
even = (((trp + even_bucket) / 2) * 2);
even_bucket += trp - even;
trp = even;
}
if (trp > 0) {
if ((stat = Set_Trips (group, org, des, trp, num, t1, t2, duration))) {
errors += stat;
Print (1, error_msg, stat, ((stat > 1) ? "s " : " "), org, des);
}
}
}
period = current;
t1 = t;
trip = 0.0;
}
trip += trips * diurnal_ptr->Share (num);
t2 = t;
}
} else {
if (period == 0) period = 1;
t1 = first_t;
t2 = last_t;
trip = trips;
}
factor_ptr = factor_data.Get (o, d, period);
if (factor_ptr == NULL) {
factor_ptr = &default_factor;
}
factor = trip * factor_ptr->Factor ();
if (factor > trip) {
added += factor - trip;
} else {
deleted += trip - factor;
}
trp = factor_ptr->Bucket_Factor (trip);
} else {
t1 = first_t;
t2 = last_t;
trp = trips;
}
if (trp > 0 && return_flag) {
even = (((trp + even_bucket) / 2) * 2);
even_bucket += trp - even;
trp = even;
}
//---- process the trips ----
if (trp > 0) {
if ((stat = Set_Trips (group, org, des, trp, num, t1, t2, duration))) {
errors += stat;
Print (1, error_msg, stat, ((stat > 1) ? "s " : " "), org, des);
}
}
}
End_Progress ();
file->Close ();
Print (1, "%s has %d Records and %d Trips", file->File_Type (), Progress_Count (), total);
tot_trips += total;
if (errors > 0) {
Warning ("A Total of %d Trip%scould not be allocated", errors, ((errors > 1) ? "s " : " "));
tot_errors += errors;
}
if (factor_flag) {
Print (1, "Trip Adjustments: %.0lf trips added, %.0lf trips deleted", added, deleted);
tot_add += added;
tot_del += deleted;
}
}
| 24.070833 | 94 | 0.535053 |
012e73be64c4a50c323ab8bb2937c8b0acb608a8 | 3,009 | cpp | C++ | GPUImage-x/proj.iOS/GPUImage-x/GPUImage-x/filter/RGBFilter.cpp | antowang/GPUImage-x | 8c9237fd0bde008a69ccab5dc267871c4959f97d | [
"Apache-2.0"
] | 197 | 2017-04-04T16:49:42.000Z | 2022-02-15T10:47:24.000Z | GPUImage-x/proj.iOS/GPUImage-x/GPUImage-x/filter/RGBFilter.cpp | antowang/GPUImage-x | 8c9237fd0bde008a69ccab5dc267871c4959f97d | [
"Apache-2.0"
] | 6 | 2017-10-04T13:23:11.000Z | 2018-09-26T06:18:11.000Z | GPUImage-x/proj.iOS/GPUImage-x/GPUImage-x/filter/RGBFilter.cpp | antowang/GPUImage-x | 8c9237fd0bde008a69ccab5dc267871c4959f97d | [
"Apache-2.0"
] | 53 | 2017-08-07T14:55:30.000Z | 2022-02-25T09:55:25.000Z | /*
* GPUImage-x
*
* Copyright (C) 2017 Yijin Wang, Yiqian Wang
*
* 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 "RGBFilter.hpp"
USING_NS_GI
REGISTER_FILTER_CLASS(RGBFilter)
const std::string kRGBFragmentShaderString = SHADER_STRING
(
uniform sampler2D colorMap;
uniform highp float redAdjustment;
uniform highp float greenAdjustment;
uniform highp float blueAdjustment;
varying highp vec2 vTexCoord;
void main()
{
lowp vec4 color = texture2D(colorMap, vTexCoord);
gl_FragColor = vec4(color.r * redAdjustment, color.g * greenAdjustment, color.b * blueAdjustment, color.a);
}
);
RGBFilter* RGBFilter::create() {
RGBFilter* ret = new (std::nothrow) RGBFilter();
if (ret && !ret->init()) {
delete ret;
ret = 0;
}
return ret;
}
bool RGBFilter::init() {
if (!initWithFragmentShaderString(kRGBFragmentShaderString)) return false;
_redAdjustment = 1.0;
_greenAdjustment = 1.0;
_blueAdjustment = 1.0;
registerProperty("redAdjustment", _redAdjustment, "The red adjustment of the image.The range is from 0.0 up, with 1.0 as the default.", [this](float& redAdjustment){
setRedAdjustment(redAdjustment);
});
registerProperty("greenAdjustment", _greenAdjustment, "The green adjustment of the image.The range is from 0.0 up, with 1.0 as the default.", [this](float& greenAdjustment){
setGreenAdjustment(greenAdjustment);
});
registerProperty("blueAdjustment", _blueAdjustment, "The blue adjustment of the image.The range is from 0.0 up, with 1.0 as the default.", [this](float& blueAdjustment){
setBlueAdjustment(blueAdjustment);
});
return true;
}
void RGBFilter::setRedAdjustment(float redAdjustment) {
_redAdjustment = redAdjustment;
if (_redAdjustment < 0.0) _redAdjustment = 0.0;
}
void RGBFilter::setGreenAdjustment(float greenAdjustment) {
_greenAdjustment = greenAdjustment;
if (_greenAdjustment < 0.0) _greenAdjustment = 0.0;
}
void RGBFilter::setBlueAdjustment(float blueAdjustment) {
_blueAdjustment = blueAdjustment;
if (_blueAdjustment < 0.0) _blueAdjustment = 0.0;
}
bool RGBFilter::proceed(bool bUpdateTargets/* = true*/) {
_filterProgram->setUniformValue("redAdjustment", _redAdjustment);
_filterProgram->setUniformValue("greenAdjustment", _greenAdjustment);
_filterProgram->setUniformValue("blueAdjustment", _blueAdjustment);
return Filter::proceed(bUpdateTargets);
}
| 32.354839 | 177 | 0.715188 |
0130e07bf1f5706e74cab68b1c3d28619e46a356 | 4,250 | cpp | C++ | src/aimp_dotnet/SDK/MusicLibrary/InternalAimpDataFilterGroup.cpp | Smartoteka/aimp_dotnet | 544502b8d080c9280ba11917ef0cc3e8dec44234 | [
"Apache-2.0"
] | 52 | 2015-04-14T14:39:30.000Z | 2022-02-07T07:16:05.000Z | src/aimp_dotnet/SDK/MusicLibrary/InternalAimpDataFilterGroup.cpp | Smartoteka/aimp_dotnet | 544502b8d080c9280ba11917ef0cc3e8dec44234 | [
"Apache-2.0"
] | 11 | 2015-04-02T10:45:55.000Z | 2022-02-03T07:21:53.000Z | src/aimp_dotnet/SDK/MusicLibrary/InternalAimpDataFilterGroup.cpp | Smartoteka/aimp_dotnet | 544502b8d080c9280ba11917ef0cc3e8dec44234 | [
"Apache-2.0"
] | 9 | 2015-04-05T18:25:57.000Z | 2022-02-07T07:20:23.000Z | // ----------------------------------------------------
// AIMP DotNet SDK
// Copyright (c) 2014 - 2020 Evgeniy Bogdan
// https://github.com/martin211/aimp_dotnet
// Mail: mail4evgeniy@gmail.com
// ----------------------------------------------------
#include "Stdafx.h"
#include "InternalAimpDataFilterGroup.h"
using namespace AIMP::SDK;
using namespace MusicLibrary;
using namespace DataFilter;
InternalAimpDataFilterGroup::InternalAimpDataFilterGroup(gcroot<IAimpDataFilterGroup^> managed) {
_managed = managed;
}
HRESULT WINAPI InternalAimpDataFilterGroup::Add(IUnknown* Field, VARIANT* Value1, VARIANT* Value2, int Operation,
IAIMPMLDataFieldFilter** Filter) {
IAimpDataFieldFilter^ filter = nullptr;
auto result = _managed->Add(AimpConverter::ToManagedString(static_cast<IAIMPString*>(Field)),
AimpConverter::FromVaiant(Value1), AimpConverter::FromVaiant(Value2),
FieldFilterOperationType(Operation));
if (result->ResultType == ActionResultType::OK) {
// todo implement internal IAIMPMLDataFieldFilter
}
return HRESULT(result->ResultType);
}
HRESULT WINAPI InternalAimpDataFilterGroup::Add2(IUnknown* Field, VARIANT* Values, int Count,
IAIMPMLDataFieldFilterByArray** Filter) {
array<Object^>^ values = gcnew array<Object^>(Count);
IAimpDataFieldFilterByArray^ filter;
auto result = _managed->Add(AimpConverter::ToManagedString(static_cast<IAIMPString*>(Field)), values, Count);
if (result->ResultType == ActionResultType::OK) {
// todo implement IAIMPMLDataFieldFilterByArray
}
return HRESULT(result->ResultType);
}
HRESULT WINAPI InternalAimpDataFilterGroup::AddGroup(IAIMPMLDataFilterGroup** Group) {
auto result = _managed->AddGroup();
if (result->ResultType == ActionResultType::OK) {
*Group = new InternalAimpDataFilterGroup(result->Result);
}
return HRESULT(result->ResultType);
}
HRESULT WINAPI InternalAimpDataFilterGroup::Clear() {
return HRESULT(_managed->Clear()->ResultType);
}
HRESULT WINAPI InternalAimpDataFilterGroup::Delete(int Index) {
return HRESULT(_managed->Delete(Index)->ResultType);
}
HRESULT WINAPI InternalAimpDataFilterGroup::GetChild(int Index, REFIID IID, void** Obj) {
ActionResultType res = ActionResultType::Fail;
if (IID == IID_IAIMPMLDataFilterGroup) {
const auto result = _managed->GetFilterGroup(Index);
if (result->ResultType == ActionResultType::OK) {
*Obj = new InternalAimpDataFilterGroup(result->Result);
}
res = result->ResultType;
}
if (IID == IID_IAIMPMLDataFieldFilter) {
IAimpDataFieldFilter^ filter = nullptr;
const auto result = _managed->GetFilterGroup(Index);
if (result->ResultType == ActionResultType::OK) {
// TODO complete it
//*Obj = new Interna
}
res = result->ResultType;
}
return HRESULT(res);
}
int WINAPI InternalAimpDataFilterGroup::GetChildCount() {
return _managed->GetChildCount();
}
ULONG WINAPI InternalAimpDataFilterGroup::AddRef(void) {
return Base::AddRef();
}
ULONG WINAPI InternalAimpDataFilterGroup::Release(void) {
return Base::Release();
}
HRESULT WINAPI InternalAimpDataFilterGroup::QueryInterface(REFIID riid, LPVOID* ppvObject) {
const HRESULT res = Base::QueryInterface(riid, ppvObject);
if (riid == IID_IAIMPMLDataFilterGroup) {
*ppvObject = this;
AddRef();
return S_OK;
}
*ppvObject = nullptr;
return res;
}
HRESULT WINAPI InternalAimpDataFilterGroup::GetValueAsInt32(int PropertyID, int* Value) {
if (PropertyID == AIMPML_FILTERGROUP_OPERATION)
*Value = static_cast<int>(_managed->Operation);
return S_OK;
}
HRESULT WINAPI InternalAimpDataFilterGroup::SetValueAsInt32(int PropertyID, int Value) {
if (PropertyID == AIMPML_FILTERGROUP_OPERATION)
_managed->Operation = static_cast<FilterGroupOperationType>(Value);
return S_OK;
}
| 33.203125 | 114 | 0.652235 |
01319c06316ba1f9a9dcbb46f8fab72f5bed7355 | 540 | hpp | C++ | cocos2d/cocos/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_physics_manual.hpp | weiDDD/particleSystem | 32652b09da35e025956999227f08be83b5d79cb1 | [
"Apache-2.0"
] | 34 | 2017-08-16T13:58:24.000Z | 2022-03-31T11:50:25.000Z | cocos2d/cocos/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_physics_manual.hpp | weiDDD/particleSystem | 32652b09da35e025956999227f08be83b5d79cb1 | [
"Apache-2.0"
] | null | null | null | cocos2d/cocos/scripting/lua-bindings/manual/cocos2d/lua_cocos2dx_physics_manual.hpp | weiDDD/particleSystem | 32652b09da35e025956999227f08be83b5d79cb1 | [
"Apache-2.0"
] | 17 | 2017-08-18T07:42:44.000Z | 2022-01-02T02:43:06.000Z | #ifndef COCOS2DX_SCRIPT_LUA_COCOS2DX_SUPPORT_GENERATED_LUA_COCOS2DX_PHYSICS_MANUAL_H
#define COCOS2DX_SCRIPT_LUA_COCOS2DX_SUPPORT_GENERATED_LUA_COCOS2DX_PHYSICS_MANUAL_H
#if CC_USE_PHYSICS
#ifdef __cplusplus
extern "C" {
#endif
#include "tolua++.h"
#ifdef __cplusplus
}
#endif
#include "cocos2d.h"
#include "LuaScriptHandlerMgr.h"
int register_all_cocos2dx_physics_manual(lua_State* tolua_S);
#endif // CC_USE_PHYSICS
#endif // #ifndef COCOS2DX_SCRIPT_LUA_COCOS2DX_SUPPORT_GENERATED_LUA_COCOS2DX_PHYSICS_MANUAL_H
| 24.545455 | 95 | 0.824074 |
0136f6b477e8ff4a69284a42a0c410dca1029e15 | 549 | cpp | C++ | SourceCode/Chapter 15/Pr15-8.cpp | aceiro/poo2019 | 0f93d22296f43a8b024a346f510c00314817d2cf | [
"MIT"
] | 1 | 2019-04-09T18:29:38.000Z | 2019-04-09T18:29:38.000Z | SourceCode/Chapter 15/Pr15-8.cpp | aceiro/poo2019 | 0f93d22296f43a8b024a346f510c00314817d2cf | [
"MIT"
] | null | null | null | SourceCode/Chapter 15/Pr15-8.cpp | aceiro/poo2019 | 0f93d22296f43a8b024a346f510c00314817d2cf | [
"MIT"
] | null | null | null | // This program demonstrates that when a derived class function
// overrides a base class function, objects of the base class
// still call the base class version of the function.
#include <iostream>
using namespace std;
class BaseClass
{
public:
void showMessage()
{ cout << "This is the Base class.\n"; }
};
class DerivedClass : public BaseClass
{
public:
void showMessage()
{ cout << "This is the Derived class.\n"; }
};
int main()
{
BaseClass b;
DerivedClass d;
b.showMessage();
d.showMessage();
return 0;
} | 18.3 | 63 | 0.675774 |
01375227a381f8c4055b105b8570ed5ad7ee6c35 | 105,100 | cpp | C++ | Contrib/at67/functions.cpp | veekooFIN/gigatron-rom | 08c9918cc111d7d2856cecae6da4137ee4641fb2 | [
"BSD-2-Clause"
] | 172 | 2018-02-26T19:56:11.000Z | 2022-03-31T17:10:16.000Z | Contrib/at67/functions.cpp | veekooFIN/gigatron-rom | 08c9918cc111d7d2856cecae6da4137ee4641fb2 | [
"BSD-2-Clause"
] | 140 | 2018-01-13T09:57:11.000Z | 2022-02-15T13:22:05.000Z | Contrib/at67/functions.cpp | veekooFIN/gigatron-rom | 08c9918cc111d7d2856cecae6da4137ee4641fb2 | [
"BSD-2-Clause"
] | 78 | 2018-01-13T01:07:37.000Z | 2022-03-09T07:59:18.000Z | #include <ctime>
#include <random>
#include <numeric>
#include <algorithm>
#include "memory.h"
#include "cpu.h"
#include "functions.h"
#include "operators.h"
namespace Functions
{
int _nestedCount = -1;
double _umin = 0.0;
double _umax = 0.0;
double _ulen = 0.0;
double _ustp = 1.0;
uint16_t _uidx = 0;
std::vector<int16_t> _uvalues;
std::mt19937_64 _randGenerator;
std::map<std::string, std::string> _functions;
std::map<std::string, std::string> _stringFunctions;
std::map<std::string, std::string>& getFunctions(void) {return _functions; }
std::map<std::string, std::string>& getStringFunctions(void) {return _stringFunctions;}
void restart(void)
{
_nestedCount = -1;
_umin = _umax = _ulen = 0.0;
_ustp = 1.0;
_uidx = 0;
_uvalues.clear();
}
bool initialise(void)
{
restart();
// Functions
_functions["IARR" ] = "IARR";
_functions["SARR" ] = "SARR";
_functions["PEEK" ] = "PEEK";
_functions["DEEK" ] = "DEEK";
_functions["USR" ] = "USR";
_functions["RND" ] = "RND";
_functions["URND" ] = "URND";
_functions["LEN" ] = "LEN";
_functions["GET" ] = "GET";
_functions["ABS" ] = "ABS";
_functions["SGN" ] = "SGN";
_functions["ASC" ] = "ASC";
_functions["STRCMP"] = "STRCMP";
_functions["BCDCMP"] = "BCDCMP";
_functions["VAL" ] = "VAL";
_functions["LUP" ] = "LUP";
_functions["ADDR" ] = "ADDR";
_functions["POINT" ] = "POINT";
_functions["MIN" ] = "MIN";
_functions["MAX" ] = "MAX";
_functions["CLAMP" ] = "CLAMP";
// String functions
_stringFunctions["CHR$" ] = "CHR$";
_stringFunctions["SPC$" ] = "SPC$";
_stringFunctions["STR$" ] = "STR$";
_stringFunctions["STRING$"] = "STRING$";
_stringFunctions["TIME$" ] = "TIME$";
_stringFunctions["HEX$" ] = "HEX$";
_stringFunctions["LEFT$" ] = "LEFT$";
_stringFunctions["RIGHT$" ] = "RIGHT$";
_stringFunctions["MID$" ] = "MID$";
_stringFunctions["LOWER$" ] = "LOWER$";
_stringFunctions["UPPER$" ] = "UPPER$";
_stringFunctions["STRCAT$"] = "STRCAT$";
uint64_t timeSeed = time(NULL);
std::seed_seq seedSequence{uint32_t(timeSeed & 0xffffffff), uint32_t(timeSeed>>32)};
_randGenerator.seed(seedSequence);
return true;
}
void handleConstantString(const Expression::Numeric& numeric, Compiler::ConstStrType constStrType, std::string& name, int& index)
{
switch(constStrType)
{
case Compiler::StrLeft:
case Compiler::StrRight:
{
uint8_t length = uint8_t(std::lround(numeric._params[0]._value));
Compiler::getOrCreateConstString(constStrType, numeric._text, length, 0, index);
}
break;
case Compiler::StrMid:
{
uint8_t offset = uint8_t(std::lround(numeric._params[0]._value));
uint8_t length = uint8_t(std::lround(numeric._params[1]._value));
Compiler::getOrCreateConstString(constStrType, numeric._text, length, offset, index);
}
break;
case Compiler::StrLower:
case Compiler::StrUpper:
{
Compiler::getOrCreateConstString(constStrType, numeric._text, 0, 0, index);
}
break;
default: break;
}
name = Compiler::getStringVars()[index]._name;
uint16_t srcAddr = Compiler::getStringVars()[index]._address;
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(srcAddr), false);
Compiler::emitVcpuAsm("%PrintAcString", "", false);
}
else
{
uint16_t dstAddr = Compiler::getStringVars()[Expression::getOutputNumeric()._index]._address;
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(srcAddr), false);
Compiler::emitVcpuAsm("STW", "strSrcAddr", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false);
Compiler::emitVcpuAsm("%StringCopy", "", false);
}
}
void handleStringParameter(Expression::Numeric& param)
{
// Literals
if(param._varType == Expression::Number)
{
// 8bit
if(param._value >=0 && param._value <= 255)
{
Compiler::emitVcpuAsm("LDI", std::to_string(int16_t(std::lround(param._value))), false);
}
// 16bit
else
{
Compiler::emitVcpuAsm("LDWI", std::to_string(int16_t(std::lround(param._value))), false);
}
return;
}
Operators::handleSingleOp("LDW", param);
}
// Does a function contain nested functions as parameters
bool isFuncNested(void)
{
if(Expression::getOutputNumeric()._nestedCount == _nestedCount) return false;
bool codeInit = (_nestedCount == -1);
_nestedCount = Expression::getOutputNumeric()._nestedCount;
if(codeInit) return false;
return true;
}
// ********************************************************************************************
// Functions
// ********************************************************************************************
void opcodeARR(Expression::Numeric& param)
{
// Can't call Operators::handleSingleOp() here, so special case it
switch(param._varType)
{
// Temporary variable address
case Expression::TmpVar:
{
Compiler::emitVcpuAsm("LDW", Expression::byteToHexString(uint8_t(std::lround(param._value))), false);
}
break;
// User variable
case Expression::IntVar16:
{
Compiler::emitVcpuAsmUserVar("LDW", param, false);
}
break;
// Literal or constant
case Expression::Number:
{
Compiler::emitVcpuAsm("LDI", std::to_string(uint8_t(std::lround(param._value))), false);
}
break;
default: break;
}
}
Expression::Numeric IARR(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::IARR() : '%s:%d' : %s cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, numeric._name.c_str(), codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
Compiler::getNextTempVar();
int intSize = Compiler::getIntegerVars()[numeric._index]._intSize;
uint16_t arrayPtr = Compiler::getIntegerVars()[numeric._index]._address;
// Literal array index, (only optimise for 1d arrays)
if(numeric._varType == Expression::Arr1Var8 && numeric._params.size() == 1 && numeric._params[0]._varType == Expression::Number)
{
std::string operand = Expression::wordToHexString(arrayPtr + uint16_t(numeric._params[0]._value*intSize));
Compiler::emitVcpuAsm("LDWI", operand, false);
Compiler::emitVcpuAsm("PEEK", "", false);
}
else if(numeric._varType == Expression::Arr1Var16 && numeric._params.size() == 1 && numeric._params[0]._varType == Expression::Number)
{
std::string operand = Expression::wordToHexString(arrayPtr + uint16_t(numeric._params[0]._value*intSize));
// Handle .LO and .HI
switch(numeric._int16Byte)
{
case Expression::Int16Low: Compiler::emitVcpuAsm("LDWI", operand, false); Compiler::emitVcpuAsm("PEEK", "", false); break;
case Expression::Int16High: Compiler::emitVcpuAsm("LDWI", operand + " + 1", false); Compiler::emitVcpuAsm("PEEK", "", false); break;
case Expression::Int16Both: Compiler::emitVcpuAsm("LDWI", operand, false); Compiler::emitVcpuAsm("DEEK", "", false); break;
default: break;
}
}
// Variable array index or 2d/3d array
else
{
size_t numDims = 0;
if(numeric._varType >= Expression::Arr1Var8 && numeric._varType <= Expression::Arr3Var8)
{
numDims = numeric._varType - Expression::Arr1Var8 + 1;
}
else if(numeric._varType >= Expression::Arr1Var16 && numeric._varType <= Expression::Arr3Var16)
{
numDims = numeric._varType - Expression::Arr1Var16 + 1;
}
if(numDims != numeric._params.size())
{
fprintf(stderr, "Functions::IARR() : '%s:%d' : %s() expects %d dimension/s, found %d : %s\n", moduleName.c_str(), codeLineStart, numeric._name.c_str(), int(numDims), int(numeric._params.size()), codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Generate array indices
for(size_t i=0; i<numeric._params.size(); i++)
{
Expression::Numeric param = numeric._params[i];
opcodeARR(param);
Compiler::emitVcpuAsm("STW", "memIndex" + std::to_string(i), false);
}
// Handle 1d/2d/3d arrays
switch(numeric._varType)
{
case Expression::Arr1Var8:
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(arrayPtr), false);
Compiler::emitVcpuAsm("ADDW", "memIndex0", false);
}
break;
case Expression::Arr2Var8:
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(arrayPtr), false);
(Compiler::getCodeRomType() >= Cpu::ROMv5a) ? Compiler::emitVcpuAsm("CALLI", "convert8Arr2d", false) : Compiler::emitVcpuAsm("CALL", "convert8Arr2dAddr", false);
}
break;
case Expression::Arr3Var8:
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(arrayPtr), false);
(Compiler::getCodeRomType() >= Cpu::ROMv5a) ? Compiler::emitVcpuAsm("CALLI", "convert8Arr3d", false) : Compiler::emitVcpuAsm("CALL", "convert8Arr3dAddr", false);
}
break;
case Expression::Arr1Var16:
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(arrayPtr), false);
Compiler::emitVcpuAsm("ADDW", "memIndex0", false);
Compiler::emitVcpuAsm("ADDW", "memIndex0", false);
}
break;
case Expression::Arr2Var16:
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(arrayPtr), false);
(Compiler::getCodeRomType() >= Cpu::ROMv5a) ? Compiler::emitVcpuAsm("CALLI", "convert16Arr2d", false) : Compiler::emitVcpuAsm("CALL", "convert16Arr2dAddr", false);
}
break;
case Expression::Arr3Var16:
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(arrayPtr), false);
(Compiler::getCodeRomType() >= Cpu::ROMv5a) ? Compiler::emitVcpuAsm("CALLI", "convert16Arr3d", false) : Compiler::emitVcpuAsm("CALL", "convert16Arr3dAddr", false);
}
break;
default: break;
}
// Functions like LEN() and ADDR() require IARR() to return the address rather than the value
if(!numeric._returnAddress)
{
// Bytes
if(numeric._varType >= Expression::Arr1Var8 && numeric._varType <= Expression::Arr3Var8)
{
Compiler::emitVcpuAsm("PEEK", "", false);
}
// Words, handle .LO and .HI
else
{
switch(numeric._int16Byte)
{
case Expression::Int16Low: Compiler::emitVcpuAsm("PEEK", "", false); break;
case Expression::Int16High: Compiler::emitVcpuAsm("ADDI", "1", false); Compiler::emitVcpuAsm("PEEK", "", false); break;
case Expression::Int16Both: Compiler::emitVcpuAsm("DEEK", "", false); break;
default: break;
}
}
}
}
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
numeric._params.clear();
return numeric;
}
Expression::Numeric SARR(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::SARR() : '%s:%d' : %s cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, numeric._name.c_str(), codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params.size() != 1)
{
fprintf(stderr, "Functions::SARR() : '%s:%d' : %s() expects 1 dimension, found %d : %s\n", moduleName.c_str(), codeLineStart, numeric._name.c_str(), int(numeric._params.size()), codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// String addresses cannot be combined using boolean expressions, so no need to increment temporary var
//Compiler::getNextTempVar();
uint16_t arrayPtr = Compiler::getStringVars()[numeric._index]._address;
// Literal array index
if(numeric._params[0]._varType == Expression::Number)
{
std::string operand = Expression::wordToHexString(arrayPtr + uint16_t(numeric._params[0]._value)*2);
Compiler::emitVcpuAsm("LDWI", operand, false);
Compiler::emitVcpuAsm("DEEK", "", false);
}
// Variable array index
else
{
Expression::Numeric param = numeric._params[0];
opcodeARR(param);
Compiler::emitVcpuAsm("STW", "memIndex0", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(arrayPtr), false);
Compiler::emitVcpuAsm("ADDW", "memIndex0", false);
Compiler::emitVcpuAsm("ADDW", "memIndex0", false);
Compiler::emitVcpuAsm("DEEK", "", false);
}
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
numeric._varType = Expression::Str2Var;
numeric._params.clear();
return numeric;
}
Expression::Numeric PEEK(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::PEEK() : '%s:%d' : PEEK() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._varType == Expression::Number)
{
// Optimise for page 0
if(numeric._value >= 0 && numeric._value <= 255)
{
Compiler::emitVcpuAsm("LD", Expression::byteToHexString(uint8_t(std::lround(numeric._value))), false);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
Operators::changeToTmpVar(numeric);
return numeric;
}
else
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(int16_t(std::lround(numeric._value))), false);
}
}
Compiler::getNextTempVar();
Operators::handleSingleOp("LDW", numeric);
Compiler::emitVcpuAsm("PEEK", "", false);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
return numeric;
}
Expression::Numeric DEEK(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::PEEK() : '%s:%d' : PEEK() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._varType == Expression::Number)
{
// Optimise for page 0
if(numeric._value >= 0 && numeric._value <= 255)
{
Compiler::emitVcpuAsm("LDW", Expression::byteToHexString(uint8_t(std::lround(numeric._value))), false);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
Operators::changeToTmpVar(numeric);
return numeric;
}
else
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(int16_t(std::lround(numeric._value))), false);
}
}
Compiler::getNextTempVar();
Operators::handleSingleOp("LDW", numeric);
Compiler::emitVcpuAsm("DEEK", "", false);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
return numeric;
}
Expression::Numeric USR(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::USR() : '%s:%d' : USR() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._varType == Expression::Number)
{
if(Compiler::getCodeRomType() >= Cpu::ROMv5a)
{
(numeric._value >= 0 && numeric._value <= 255) ? Compiler::emitVcpuAsm("CALLI", Expression::byteToHexString(uint8_t(std::lround(numeric._value))), false) :
Compiler::emitVcpuAsm("CALLI", Expression::wordToHexString(int16_t(std::lround(numeric._value))), false);
}
else
{
(numeric._value >= 0 && numeric._value <= 255) ? Compiler::emitVcpuAsm("LDI", Expression::byteToHexString(uint8_t(std::lround(numeric._value))), false) :
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(int16_t(std::lround(numeric._value))), false);
}
}
Compiler::getNextTempVar();
if(Compiler::getCodeRomType() >= Cpu::ROMv5a)
{
Operators::handleSingleOp("CALLI", numeric);
}
else
{
Operators::handleSingleOp("LDW", numeric);
Compiler::emitVcpuAsm("CALL", "giga_vAC", false);
}
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
return numeric;
}
Expression::Numeric RND(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
UNREFERENCED_PARAM(moduleName);
UNREFERENCED_PARAM(codeLineText);
UNREFERENCED_PARAM(codeLineStart);
bool useMod = true;
if(numeric._varType == Expression::Number)
{
// No code needed for static initialisation
if(Expression::getOutputNumeric()._staticInit)
{
if(numeric._value == 0)
{
std::uniform_int_distribution<uint16_t> distribution(0, 0xFFFF);
numeric._value = distribution(_randGenerator);
}
else
{
std::uniform_int_distribution<uint16_t> distribution(0, uint16_t(numeric._value));
numeric._value = distribution(_randGenerator);
}
return numeric;
}
// RND(0) skips the MOD call and allows you to filter the output manually
if(numeric._value == 0)
{
useMod = false;
}
else
{
(numeric._value > 0 && numeric._value <= 255) ? Compiler::emitVcpuAsm("LDI", Expression::byteToHexString(uint8_t(std::lround(numeric._value))), false) :
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(int16_t(std::lround(numeric._value))), false);
}
}
Compiler::getNextTempVar();
if(useMod)
{
Operators::handleSingleOp("LDW", numeric);
Compiler::emitVcpuAsm("%RandMod", "", false);
}
else
{
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("%Rand", "", false);
}
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
return numeric;
}
Expression::Numeric URND(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
UNREFERENCED_PARAM(codeLineStart);
if(!Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::URND() : '%s:%d' : URND only works in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params.size() != 3)
{
fprintf(stderr, "Functions::URND() : '%s:%d' : URND expects 4 parameters, found %d : %s\n", moduleName.c_str(), codeLineStart, int(numeric._params.size()), codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._varType != Expression::Number || numeric._params[0]._varType != Expression::Number || numeric._params[1]._varType != Expression::Number || numeric._params[2]._varType != Expression::Number)
{
fprintf(stderr, "Functions::URND() : '%s:%d' : URND expects 4 literal parameters, 'URND(<min>, <max>, <len>, <step>) : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Initialise unique random number generator
if(numeric._value != _umin || numeric._params[0]._value != _umax || numeric._params[1]._value != _ulen || numeric._params[2]._value != _ustp)
{
_umin = _umax = _ulen = 0.0;
_ustp = 1.0;
if(abs(numeric._params[0]._value - numeric._value) < numeric._params[1]._value)
{
fprintf(stderr, "Functions::URND() : '%s:%d' : range is smaller than length : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params[0]._value <= numeric._value)
{
fprintf(stderr, "Functions::URND() : '%s:%d' : maximum must be greater than minimum : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params[1]._value <= 0.0 || std::lround(numeric._params[1]._value) > 0xFFFF)
{
fprintf(stderr, "Functions::URND() : '%s:%d' : 0x0000 < length < 0x10000 : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params[2]._value == 0.0)
{
fprintf(stderr, "Functions::URND() : '%s:%d' : step must not be equal to zero : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
_umin = numeric._value;
_umax = numeric._params[0]._value;
_ulen = numeric._params[1]._value;
_ustp = numeric._params[2]._value;
_uidx = 0;
uint16_t range = uint16_t((abs(std::lround(_umax) - std::lround(_umin))) / std::lround(abs(_ustp))) + 1;
if(range == 0)
{
fprintf(stderr, "Functions::URND() : '%s:%d' : step size is too large for range : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
_uvalues.resize(range);
for(int i=0; i<range; i++) _uvalues[i] = int16_t(std::lround(_umin)) + int16_t(i*abs(_ustp));
//std::iota(_uvalues.begin(), _uvalues.end(), int16_t(std::lround(_umin)));
std::shuffle(_uvalues.begin(), _uvalues.end(), _randGenerator);
}
if(_uidx >= uint16_t(_uvalues.size()))
{
fprintf(stderr, "Functions::URND() : '%s:%d' : length is greater than range : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
numeric._value = _uvalues[_uidx++];
return numeric;
}
Expression::Numeric LEN(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(numeric._varType == Expression::Number)
{
fprintf(stderr, "Functions::LEN() : '%s:%d' : parameter can't be a literal : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params.size() != 0)
{
fprintf(stderr, "Functions::LEN() : '%s:%d' : LEN expects 1 parameter, found %d : %s\n", moduleName.c_str(), codeLineStart, int(numeric._params.size()), codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Handle non variables
if(numeric._index == -1)
{
switch(numeric._varType)
{
// Get or create constant string
case Expression::String:
{
int index;
Compiler::getOrCreateConstString(numeric._text, index);
numeric._index = int16_t(index);
numeric._varType = Expression::StrVar;
}
break;
// Needs to pass through
case Expression::TmpStrVar:
{
}
break;
default:
{
fprintf(stderr, "Functions::LEN() : '%s:%d' : couldn't find variable name '%s' : %s\n", moduleName.c_str(), codeLineStart, numeric._name.c_str(), codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
}
}
int length = 0;
switch(numeric._varType)
{
case Expression::IntVar16:
case Expression::Arr1Var8:
case Expression::Arr2Var8:
case Expression::Arr3Var8:
case Expression::Arr1Var16:
case Expression::Arr2Var16:
case Expression::TmpVar:
case Expression::Arr3Var16: length = Compiler::getIntegerVars()[numeric._index]._intSize; break;
case Expression::Constant: length = Compiler::getConstants()[numeric._index]._size; break;
case Expression::StrVar: length = Compiler::getStringVars()[numeric._index]._size; break;
default: break;
}
// No code needed for static initialisation
if(Expression::getOutputNumeric()._staticInit)
{
numeric._value = length;
return numeric;
}
// String vars
if(numeric._varType == Expression::StrVar && !Compiler::getStringVars()[numeric._index]._constant)
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(Compiler::getStringVars()[numeric._index]._address), false);
Compiler::emitVcpuAsm("PEEK", "", false);
}
// String arrays
else if(numeric._varType == Expression::Str2Var)
{
Compiler::emitVcpuAsm("LDW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
Compiler::emitVcpuAsm("PEEK", "", false);
}
// Temp string vars
else if(numeric._varType == Expression::TmpStrVar)
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(Compiler::getStrWorkArea()), false);
Compiler::emitVcpuAsm("PEEK", "", false);
}
// Ints, int arrays and constants
else
{
// Generate code to save result into a tmp var
(length <= 255) ? Compiler::emitVcpuAsm("LDI", std::to_string(length), false) : Compiler::emitVcpuAsm("LDWI", std::to_string(length), false);
}
Compiler::getNextTempVar();
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
return numeric;
}
Expression::Numeric GET(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::GET() : '%s:%d' : GET() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._varType == Expression::String)
{
std::string sysVarName = numeric._text;
Expression::strToUpper(sysVarName);
if(sysVarName == "ROM_READ_DIR" && numeric._params.size() == 1)
{
// Literal constant
if(numeric._params[0]._varType == Expression::Number)
{
Compiler::emitVcpuAsm("LDI", Expression::byteToHexString(uint8_t(std::lround(numeric._params[0]._value))), false);
}
Compiler::getNextTempVar();
Operators::handleSingleOp("LDW", numeric._params[0]);
Compiler::emitVcpuAsm("%RomRead", "", false);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
numeric._params[0]._params.clear();
return numeric._params[0];
}
else if(sysVarName == "SPRITE_LUT" && numeric._params.size() == 1)
{
// Literal constant
if(numeric._params[0]._varType == Expression::Number)
{
Compiler::emitVcpuAsm("LDI", Expression::byteToHexString(uint8_t(std::lround(numeric._params[0]._value))), false);
}
// Look up sprite lut from sprites lut using a sprite index, (handleSingleOp LDW is skipped if above was a constant literal)
Compiler::getNextTempVar();
Operators::handleSingleOp("LDW", numeric._params[0]);
Compiler::emitVcpuAsm("STW", "spriteId", false);
Compiler::emitVcpuAsm("%GetSpriteLUT", "", false);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
numeric._params[0]._params.clear();
return numeric._params[0];
}
else if(sysVarName == "MIDI_NOTE" && numeric._params.size() == 1)
{
// Literal constant
if(numeric._params[0]._varType == Expression::Number)
{
Compiler::emitVcpuAsm("LDI", Expression::byteToHexString(uint8_t(std::lround(numeric._params[0]._value))), false);
}
// Look up a ROM note using a midi index, (handleSingleOp LDW is skipped if above was a constant literal)
Compiler::getNextTempVar();
Operators::handleSingleOp("LDW", numeric._params[0]);
Compiler::emitVcpuAsm("STW", "musicNote", false);
Compiler::emitVcpuAsm("%GetMidiNote", "", false);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
numeric._params[0]._params.clear();
return numeric._params[0];
}
else if(sysVarName == "MUSIC_NOTE" && numeric._params.size() == 1)
{
// Literal constant
if(numeric._params[0]._varType == Expression::Number)
{
Compiler::emitVcpuAsm("LDI", Expression::byteToHexString(uint8_t(std::lround(numeric._params[0]._value))), false);
}
// Look up a ROM note using a note index, (handleSingleOp LDW is skipped if above was a constant literal)
Compiler::getNextTempVar();
Operators::handleSingleOp("LDW", numeric._params[0]);
Compiler::emitVcpuAsm("STW", "musicNote", false);
Compiler::emitVcpuAsm("%GetMusicNote", "", false);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
numeric._params[0]._params.clear();
return numeric._params[0];
}
else if(numeric._params.size() == 0)
{
Compiler::getNextTempVar();
Operators::changeToTmpVar(numeric);
if(sysVarName == "TIME_MODE")
{
Compiler::emitVcpuAsm("LDWI", "handleT_mode + 1", false);
Compiler::emitVcpuAsm("PEEK", "", false);
}
if(sysVarName == "TIME_EPOCH")
{
Compiler::emitVcpuAsm("LDWI", "handleT_epoch + 1", false);
Compiler::emitVcpuAsm("PEEK", "", false);
}
else if(sysVarName == "TIME_S")
{
Compiler::emitVcpuAsm("LDWI", "_timeArray_ + 0", false);
Compiler::emitVcpuAsm("PEEK", "", false);
}
else if(sysVarName == "TIME_M")
{
Compiler::emitVcpuAsm("LDWI", "_timeArray_ + 1", false);
Compiler::emitVcpuAsm("PEEK", "", false);
}
else if(sysVarName == "TIME_H")
{
Compiler::emitVcpuAsm("LDWI", "_timeArray_ + 2", false);
Compiler::emitVcpuAsm("PEEK", "", false);
}
else if(sysVarName == "TIMER")
{
Compiler::emitVcpuAsm("LDW", "timerTick", false);
}
else if(sysVarName == "TIMER_PREV")
{
Compiler::emitVcpuAsm("LDW", "timerPrev", false);
}
else if(sysVarName == "VBLANK_PROC")
{
if(Compiler::getCodeRomType() < Cpu::ROMv5a)
{
std::string romTypeStr;
getRomTypeStr(Compiler::getCodeRomType(), romTypeStr);
fprintf(stderr, "Functions::GET() : '%s:%d' : version error, 'SET VBLANK_PROC' requires ROMv5a or higher, you are trying to link against '%s' : %s\n", moduleName.c_str(), codeLineStart, romTypeStr.c_str(), codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
else
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(VBLANK_PROC), false);
Compiler::emitVcpuAsm("DEEK", "", false);
}
}
else if(sysVarName == "VBLANK_FREQ")
{
if(Compiler::getCodeRomType() < Cpu::ROMv5a)
{
std::string romTypeStr;
getRomTypeStr(Compiler::getCodeRomType(), romTypeStr);
fprintf(stderr, "Functions::GET() : '%s:%d' : version error, 'SET VBLANK_FREQ' requires ROMv5a or higher, you are trying to link against '%s' : %s\n", moduleName.c_str(), codeLineStart, romTypeStr.c_str(), codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// (256 - n) = vblank interrupt frequency, where n = 1 to 255
else
{
Compiler::emitVcpuAsm("LDWI", "realTS_rti + 2", false);
Compiler::emitVcpuAsm("PEEK", "", false);
Compiler::emitVcpuAsm("STW", "register0", false);
Compiler::emitVcpuAsm("LDWI", "256", false);
Compiler::emitVcpuAsm("SUBW", "register0", false);
}
}
else if(sysVarName == "CURSOR_X")
{
Compiler::emitVcpuAsm("LD", "cursorXY", false);
}
else if(sysVarName == "CURSOR_Y")
{
Compiler::emitVcpuAsm("LD", "cursorXY + 1", false);
}
else if(sysVarName == "CURSOR_XY")
{
Compiler::emitVcpuAsm("LDW", "cursorXY", false);
}
else if(sysVarName == "FG_COLOUR")
{
Compiler::emitVcpuAsm("LD", "fgbgColour + 1", false);
}
else if(sysVarName == "BG_COLOUR")
{
Compiler::emitVcpuAsm("LD", "fgbgColour", false);
}
else if(sysVarName == "FGBG_COLOUR")
{
Compiler::emitVcpuAsm("LDW", "fgbgColour", false);
}
else if(sysVarName == "MIDI_STREAM")
{
Compiler::emitVcpuAsm("LDW", "midiStream", false);
}
else if(sysVarName == "LED_TEMPO")
{
Compiler::emitVcpuAsm("LD", "giga_ledTempo", false);
}
else if(sysVarName == "LED_STATE")
{
Compiler::emitVcpuAsm("LD", "giga_ledState", false);
}
else if(sysVarName == "SOUND_TIMER")
{
Compiler::emitVcpuAsm("LD", "giga_soundTimer", false);
}
else if(sysVarName == "CHANNEL_MASK")
{
Compiler::emitVcpuAsm("LD", "giga_channelMask", false);
Compiler::emitVcpuAsm("ANDI", "0x03", false);
}
else if(sysVarName == "ROM_TYPE")
{
Compiler::emitVcpuAsm("LD", "giga_romType", false);
Compiler::emitVcpuAsm("ANDI", "0xFC", false);
}
else if(sysVarName == "VSP")
{
Compiler::emitVcpuAsm("LD", "giga_vSP", false);
}
else if(sysVarName == "VLR")
{
Compiler::emitVcpuAsm("LD", "giga_vLR", false);
}
else if(sysVarName == "VAC")
{
Compiler::emitVcpuAsm("LD", "giga_vAC", false);
}
else if(sysVarName == "VPC")
{
Compiler::emitVcpuAsm("LD", "giga_vPC", false);
}
else if(sysVarName == "XOUT_MASK")
{
Compiler::emitVcpuAsm("LD", "giga_xoutMask", false);
}
else if(sysVarName == "BUTTON_STATE")
{
Compiler::emitVcpuAsm("LD", "giga_buttonState", false);
}
else if(sysVarName == "SERIAL_RAW")
{
Compiler::emitVcpuAsm("LD", "giga_serialRaw", false);
}
else if(sysVarName == "FRAME_COUNT")
{
Compiler::emitVcpuAsm("LD", "giga_frameCount", false);
}
else if(sysVarName == "VIDEO_Y")
{
Compiler::emitVcpuAsm("LD", "giga_videoY", false);
}
else if(sysVarName == "RAND2")
{
Compiler::emitVcpuAsm("LD", "giga_rand2", false);
}
else if(sysVarName == "RAND1")
{
Compiler::emitVcpuAsm("LD", "giga_rand1", false);
}
else if(sysVarName == "RAND0")
{
Compiler::emitVcpuAsm("LD", "giga_rand0", false);
}
else if(sysVarName == "MEM_SIZE")
{
Compiler::emitVcpuAsm("LD", "giga_memSize", false);
}
else if(sysVarName == "Y_RES")
{
Compiler::emitVcpuAsm("LDI", "giga_yres", false);
}
else if(sysVarName == "X_RES")
{
Compiler::emitVcpuAsm("LDI", "giga_xres", false);
}
else if(sysVarName == "SND_CHN4")
{
Compiler::emitVcpuAsm("LDWI", "giga_soundChan4", false);
}
else if(sysVarName == "SND_CHN3")
{
Compiler::emitVcpuAsm("LDWI", "giga_soundChan3", false);
}
else if(sysVarName == "SND_CHN2")
{
Compiler::emitVcpuAsm("LDWI", "giga_soundChan2", false);
}
else if(sysVarName == "SND_CHN1")
{
Compiler::emitVcpuAsm("LDWI", "giga_soundChan1", false);
}
else if(sysVarName == "V_TOP")
{
Compiler::emitVcpuAsm("LDWI", "giga_videoTop", false);
}
else if(sysVarName == "V_TABLE")
{
Compiler::emitVcpuAsm("LDWI", "giga_videoTable", false);
}
else if(sysVarName == "V_RAM")
{
Compiler::emitVcpuAsm("LDWI", "giga_vram", false);
}
else if(sysVarName == "ROM_NOTES")
{
Compiler::emitVcpuAsm("LDWI", "giga_notesTable", false);
}
else if(sysVarName == "ROM_TEXT82")
{
Compiler::emitVcpuAsm("LDWI", "giga_text82", false);
}
else if(sysVarName == "ROM_TEXT32")
{
Compiler::emitVcpuAsm("LDWI", "giga_text32", false);
}
else
{
fprintf(stderr, "Functions::GET() : '%s:%d' : system variable name '%s' does not exist : %s\n", moduleName.c_str(), codeLineStart, numeric._text.c_str(), codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
}
}
return numeric;
}
Expression::Numeric ABS(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::ABS() : '%s:%d' : ABS() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._varType != Expression::String && numeric._varType != Expression::StrVar && numeric._varType != Expression::TmpStrVar)
{
Compiler::getNextTempVar();
if(numeric._varType == Expression::Number)
{
numeric._value = abs(numeric._value);
(numeric._value >= 0 && numeric._value <= 255) ? Compiler::emitVcpuAsm("LDI", Expression::byteToHexString(uint8_t(std::lround(numeric._value))), false) :
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(int16_t(std::lround(numeric._value))), false);
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
}
else
{
Operators::handleSingleOp("LDW", numeric);
Compiler::emitVcpuAsm("%Absolute", "", false);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
}
}
return numeric;
}
Expression::Numeric SGN(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::SGN() : '%s:%d' : SGN() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._varType != Expression::String && numeric._varType != Expression::StrVar && numeric._varType != Expression::TmpStrVar)
{
Compiler::getNextTempVar();
if(numeric._varType == Expression::Number)
{
numeric._value = Expression::sgn(numeric._value);
(numeric._value >= 0 && numeric._value <= 255) ? Compiler::emitVcpuAsm("LDI", Expression::byteToHexString(uint8_t(std::lround(numeric._value))), false) :
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(int16_t(std::lround(numeric._value))), false);
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
}
else
{
Operators::handleSingleOp("LDW", numeric);
Compiler::emitVcpuAsm("%Sign", "", false);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
}
}
return numeric;
}
Expression::Numeric ASC(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(numeric._varType == Expression::Number)
{
fprintf(stderr, "Functions::ASC() : '%s:%d' : parameter can't be a literal : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
Compiler::getNextTempVar();
// Handle non variables
if(numeric._index == -1)
{
switch(numeric._varType)
{
// Get or create constant string
case Expression::String:
{
int index;
Compiler::getOrCreateConstString(numeric._text, index);
numeric._index = int16_t(index);
numeric._varType = Expression::StrVar;
}
break;
case Expression::TmpStrVar:
{
}
break;
default:
{
fprintf(stderr, "Functions::ASC() : '%s:%d' : couldn't find variable name '%s' : %s\n", moduleName.c_str(), codeLineStart, numeric._name.c_str(), codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
}
}
uint8_t ascii = 0;
switch(numeric._varType)
{
case Expression::StrVar: ascii = Compiler::getStringVars()[numeric._index]._text[0]; break;
case Expression::Constant: ascii = Compiler::getConstants()[numeric._index]._text[0]; break;
default: break;
}
// No code needed for static initialisation
if(Expression::getOutputNumeric()._staticInit)
{
numeric._value = ascii;
return numeric;
}
// Variables
if(numeric._varType == Expression::StrVar && !Compiler::getStringVars()[numeric._index]._constant)
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(Compiler::getStringVars()[numeric._index]._address) + " + 1", false);
Compiler::emitVcpuAsm("PEEK", "", false);
}
else if(numeric._varType == Expression::TmpStrVar)
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(Compiler::getStrWorkArea()) + " + 1", false);
Compiler::emitVcpuAsm("PEEK", "", false);
}
// Constants
else
{
// Generate code to save result into a tmp var
Compiler::emitVcpuAsm("LDI", std::to_string(ascii), false);
}
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
return numeric;
}
Expression::Numeric STRCMP(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(numeric._params.size() != 1)
{
fprintf(stderr, "Functions::STRCMP() : '%s:%d' : STRCMP() requires two string parameters : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Literal strings, (optimised case)
if(numeric._varType == Expression::String && numeric._params[0]._varType == Expression::String)
{
// No code needed for static initialisation
if(Expression::getOutputNumeric()._staticInit)
{
numeric._varType = Expression::Number;
numeric._value = uint8_t(numeric._text == numeric._params[0]._text) - 1;
numeric._params.clear();
return numeric;
}
// Generate code to save result into a tmp var
else
{
int result = int(numeric._text == numeric._params[0]._text) - 1;
(result >= 0 && result <= 255) ? Compiler::emitVcpuAsm("LDI", std::to_string(result), false) : Compiler::emitVcpuAsm("LDWI", std::to_string(result), false);
}
}
else
{
// Get addresses of strings to be compared
uint16_t srcAddr0 = 0x0000, srcAddr1 = 0x0000;
if(numeric._varType == Expression::TmpStrVar) srcAddr0 = Compiler::getStrWorkArea(0);
if(numeric._params[0]._varType == Expression::TmpStrVar) srcAddr1 = Compiler::getStrWorkArea(0);
if(numeric._varType == Expression::TmpStrVar && numeric._params[0]._varType == Expression::TmpStrVar)
{
// If both params are temp strs then swap them so they compare correctly
srcAddr1 = Compiler::getStrWorkArea(1);
std::swap(srcAddr0, srcAddr1);
}
if(!srcAddr0)
{
std::string name;
int index = int(numeric._index);
Compiler::getOrCreateString(numeric, name, srcAddr0, index);
}
if(!srcAddr1)
{
std::string name;
int index = int(numeric._params[0]._index);
Compiler::getOrCreateString(numeric._params[0], name, srcAddr1, index);
}
// By definition this must be a match
if(srcAddr0 == srcAddr1)
{
Compiler::emitVcpuAsm("LDI", "1", false);
}
// Compare strings, -1, 0, 1, (smaller, equal, bigger)
else
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(srcAddr0), false);
Compiler::emitVcpuAsm("STW", "strSrcAddr", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(srcAddr1), false);
Compiler::emitVcpuAsm("%StringCmp", "", false);
Compiler::emitVcpuAsm("SUBI", "1", false); // convert 0, 1, 2 to -1, 0, 1
}
}
Compiler::getNextTempVar();
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
numeric._params.clear();
return numeric;
}
Expression::Numeric BCDCMP(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::BCDCMP() : '%s:%d' : BCDCMP() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params.size() != 2)
{
fprintf(stderr, "Functions::BCDCMP() : '%s:%d' : BCDCMP() requires three string parameters : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Get addresses and length of bcd values to be compared
uint16_t srcAddr0 = uint16_t(numeric._value);
uint16_t srcAddr1 = uint16_t(numeric._params[0]._value);
uint16_t length = uint16_t(numeric._params[1]._value);
// Compare bcd values, (addresses MUST point to msd)
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(srcAddr0), false);
Compiler::emitVcpuAsm("STW", "bcdSrcAddr", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(srcAddr1), false);
Compiler::emitVcpuAsm("STW", "bcdDstAddr", false);
Compiler::emitVcpuAsm("LDI", std::to_string(length), false);
Compiler::emitVcpuAsm("%BcdCmp", "", false);
Compiler::getNextTempVar();
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
numeric._params.clear();
return numeric;
}
Expression::Numeric VAL(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(numeric._params.size() != 0)
{
fprintf(stderr, "Functions::VAL() : '%s:%d' : VAL() requires only one string parameter : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Literal strings, (optimised case)
if(numeric._varType == Expression::String)
{
int16_t val = 0;
Expression::stringToI16(numeric._text, val);
// No code needed for static initialisation
if(Expression::getOutputNumeric()._staticInit)
{
numeric._varType = Expression::Number;
numeric._value = val;
return numeric;
}
// Generate code to save result into a tmp var
else
{
(val >= 0 && val <= 255) ? Compiler::emitVcpuAsm("LDI", std::to_string(val), false) : Compiler::emitVcpuAsm("LDWI", std::to_string(val), false);
}
}
else
{
// Get addresses of src string
std::string name;
uint16_t srcAddr;
int index = int(numeric._index);
Compiler::getOrCreateString(numeric, name, srcAddr, index);
// StringVal expects srcAddr to point past the string's length byte
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(srcAddr + 1), false);
Compiler::emitVcpuAsm("%IntegerStr", "", false);
}
Compiler::getNextTempVar();
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
return numeric;
}
Expression::Numeric LUP(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::LUP() : '%s:%d' : LUP(<address>, <offset>) cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params.size() != 1)
{
fprintf(stderr, "Functions::LUP() : '%s:%d' : LUP(<address>, <offset>) missing offset : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params[0]._varType != Expression::Number)
{
fprintf(stderr, "Functions::LUP() : '%s:%d' : LUP(<address>, <offset>) offset is not a constant literal : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
std::string offset = Expression::byteToHexString(uint8_t(std::lround(numeric._params[0]._value)));
if(numeric._varType == Expression::Number)
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(uint16_t(std::lround(numeric._value))), false);
}
else
{
Operators::createSingleOp("LDW", numeric);
}
Compiler::getNextTempVar();
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("LUP", offset, false);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
numeric._params.clear();
return numeric;
}
Expression::Numeric ADDR(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(numeric._varType == Expression::Number)
{
fprintf(stderr, "Functions::ADDR() : '%s:%d' : parameter can't be a literal : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params.size() != 0)
{
fprintf(stderr, "Functions::ADDR() : '%s:%d' : expects 1 parameter, found %d : %s\n", moduleName.c_str(), codeLineStart, int(numeric._params.size()), codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Handle non variables
if(numeric._index == -1)
{
switch(numeric._varType)
{
// Get or create constant string
case Expression::String:
{
int index;
Compiler::getOrCreateConstString(numeric._text, index);
numeric._index = int16_t(index);
numeric._varType = Expression::StrVar;
}
break;
// Needs to pass through
case Expression::TmpStrVar:
{
}
break;
default:
{
fprintf(stderr, "Functions::ADDR() : '%s:%d' : couldn't find variable name '%s' : %s\n", moduleName.c_str(), codeLineStart, numeric._name.c_str(), codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
}
}
uint16_t address = 0x0000;
switch(numeric._varType)
{
case Expression::IntVar16:
case Expression::Arr1Var8:
case Expression::Arr1Var16: address = Compiler::getIntegerVars()[numeric._index]._address; break;
case Expression::Constant: address = Compiler::getConstants()[numeric._index]._address; break;
case Expression::StrVar: address = Compiler::getStringVars()[numeric._index]._address; break;
default: break;
}
// No code needed for static initialisation
if(Expression::getOutputNumeric()._staticInit)
{
switch(numeric._varType)
{
case Expression::TmpVar:
case Expression::Str2Var:
{
fprintf(stderr, "Functions::ADDR() : '%s:%d' : can't statically initialise from multi-dimensional array '%s' : %s\n", moduleName.c_str(), codeLineStart, numeric._name.c_str(), codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
default: break;
}
numeric._value = address;
return numeric;
}
// String vars
if(numeric._varType == Expression::StrVar && !Compiler::getStringVars()[numeric._index]._constant)
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(Compiler::getStringVars()[numeric._index]._address), false);
}
// Multi-dimensional arrays, (array of strings, Str2Var, is treated as a 2D array of bytes)
else if(numeric._varType == Expression::TmpVar || numeric._varType == Expression::Str2Var)
{
Compiler::emitVcpuAsm("LDW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
}
// Temp string vars
else if(numeric._varType == Expression::TmpStrVar)
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(Compiler::getStrWorkArea()), false);
}
// Ints, int arrays and constants
else
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(address), false);
}
Compiler::getNextTempVar();
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
return numeric;
}
Expression::Numeric POINT(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::POINT() : '%s:%d' : POINT() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params.size() != 1)
{
fprintf(stderr, "Functions::POINT() : '%s:%d' : syntax error, 'POINT(x, y)' requires two parameters : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._varType == Expression::Number)
{
Compiler::emitVcpuAsm("LDI", Expression::byteToHexString(uint8_t(std::lround(numeric._value))), false);
Compiler::emitVcpuAsm("ST", "readPixel_xy", false);
}
else
{
Operators::createSingleOp("LDW", numeric);
Compiler::emitVcpuAsm("ST", "readPixel_xy", false);
}
if(numeric._params[0]._varType == Expression::Number)
{
Compiler::emitVcpuAsm("LDI", Expression::byteToHexString(uint8_t(std::lround(numeric._params[0]._value))), false);
Compiler::emitVcpuAsm("ST", "readPixel_xy + 1", false);
}
else
{
Operators::createSingleOp("LDW", numeric._params[0]);
Compiler::emitVcpuAsm("ST", "readPixel_xy + 1", false);
}
Compiler::getNextTempVar();
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("%ReadPixel", "", false);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
numeric._params.clear();
return numeric;
}
Expression::Numeric MIN(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(numeric._params.size() != 1)
{
fprintf(stderr, "Functions::MIN() : '%s:%d' : syntax error, 'MIN(x, y)' requires two parameters : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._varType == Expression::Number && numeric._params[0]._varType == Expression::Number)
{
numeric._value = std::min(numeric._value, numeric._params[0]._value);
numeric._params.clear();
return numeric;
}
if(numeric._varType == Expression::Number)
{
int16_t val = int16_t(std::lround(numeric._value));
(val >= 0 && val <= 255) ? Compiler::emitVcpuAsm("LDI", std::to_string(val), false) : Compiler::emitVcpuAsm("LDWI", std::to_string(val), false);
Compiler::emitVcpuAsm("STW", "intSrcA", false);
}
else
{
Operators::createSingleOp("LDW", numeric);
Compiler::emitVcpuAsm("STW", "intSrcA", false);
}
if(numeric._params[0]._varType == Expression::Number)
{
int16_t val = int16_t(std::lround(numeric._params[0]._value));
(val >= 0 && val <= 255) ? Compiler::emitVcpuAsm("LDI", std::to_string(val), false) : Compiler::emitVcpuAsm("LDWI", std::to_string(val), false);
}
else
{
Operators::createSingleOp("LDW", numeric._params[0]);
}
Compiler::getNextTempVar();
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("%IntMin", "", false);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
numeric._params.clear();
return numeric;
}
Expression::Numeric MAX(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(numeric._params.size() != 1)
{
fprintf(stderr, "Functions::MAX() : '%s:%d' : syntax error, 'MAX(x, y)' requires two parameters : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._varType == Expression::Number && numeric._params[0]._varType == Expression::Number)
{
numeric._value = std::max(numeric._value, numeric._params[0]._value);
numeric._params.clear();
return numeric;
}
if(numeric._varType == Expression::Number)
{
int16_t val = int16_t(std::lround(numeric._value));
(val >= 0 && val <= 255) ? Compiler::emitVcpuAsm("LDI", std::to_string(val), false) : Compiler::emitVcpuAsm("LDWI", std::to_string(val), false);
Compiler::emitVcpuAsm("STW", "intSrcA", false);
}
else
{
Operators::createSingleOp("LDW", numeric);
Compiler::emitVcpuAsm("STW", "intSrcA", false);
}
if(numeric._params[0]._varType == Expression::Number)
{
int16_t val = int16_t(std::lround(numeric._params[0]._value));
(val >= 0 && val <= 255) ? Compiler::emitVcpuAsm("LDI", std::to_string(val), false) : Compiler::emitVcpuAsm("LDWI", std::to_string(val), false);
}
else
{
Operators::createSingleOp("LDW", numeric._params[0]);
}
Compiler::getNextTempVar();
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("%IntMax", "", false);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
numeric._params.clear();
return numeric;
}
Expression::Numeric CLAMP(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(numeric._params.size() != 2)
{
fprintf(stderr, "Functions::CLAMP() : '%s:%d' : syntax error, 'CLAMP(x, a, b)' requires three parameters : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._varType == Expression::Number && numeric._params[0]._varType == Expression::Number && numeric._params[1]._varType == Expression::Number)
{
numeric._value = std::min(std::max(numeric._value, numeric._params[0]._value), numeric._params[1]._value);
numeric._params.clear();
return numeric;
}
if(numeric._varType == Expression::Number)
{
int16_t val = int16_t(std::lround(numeric._value));
(val >= 0 && val <= 255) ? Compiler::emitVcpuAsm("LDI", std::to_string(val), false) : Compiler::emitVcpuAsm("LDWI", std::to_string(val), false);
Compiler::emitVcpuAsm("STW", "intSrcX", false);
}
else
{
Operators::createSingleOp("LDW", numeric);
Compiler::emitVcpuAsm("STW", "intSrcX", false);
}
if(numeric._params[0]._varType == Expression::Number)
{
int16_t val = int16_t(std::lround(numeric._params[0]._value));
(val >= 0 && val <= 255) ? Compiler::emitVcpuAsm("LDI", std::to_string(val), false) : Compiler::emitVcpuAsm("LDWI", std::to_string(val), false);
Compiler::emitVcpuAsm("STW", "intSrcA", false);
}
else
{
Operators::createSingleOp("LDW", numeric._params[0]);
Compiler::emitVcpuAsm("STW", "intSrcA", false);
}
if(numeric._params[1]._varType == Expression::Number)
{
int16_t val = int16_t(std::lround(numeric._params[1]._value));
(val >= 0 && val <= 255) ? Compiler::emitVcpuAsm("LDI", std::to_string(val), false) : Compiler::emitVcpuAsm("LDWI", std::to_string(val), false);
}
else
{
Operators::createSingleOp("LDW", numeric._params[1]);
}
Compiler::getNextTempVar();
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("%IntClamp", "", false);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
numeric._params.clear();
return numeric;
}
Expression::Numeric CHR$(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::CHR$() : '%s:%d' : CHR$() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Create a new temporary string
if(!isFuncNested()) Compiler::nextStrWorkArea();
uint16_t dstAddr = Compiler::getStrWorkArea();
if(numeric._varType == Expression::Number)
{
// Print CHR string, (without wasting memory)
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitVcpuAsm("LDI", std::to_string(int16_t(std::lround(numeric._value))), false);
Compiler::emitVcpuAsm("%PrintAcChr", "", false);
return numeric;
}
// Create CHR string
Compiler::emitVcpuAsm("LDI", std::to_string(int16_t(std::lround(numeric._value))), false);
Compiler::emitVcpuAsm("STW", "strChr", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false);
Compiler::emitVcpuAsm("%StringChr", "", false);
return Expression::Numeric(0, uint16_t(-1), true, false, false, Expression::TmpStrVar, Expression::BooleanCC, Expression::Int16Both, std::string(""), std::string(""));
}
Compiler::getNextTempVar();
Operators::handleSingleOp("LDW", numeric);
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitVcpuAsm("%PrintAcChr", "", false);
return numeric;
}
// Create CHR string
Compiler::emitVcpuAsm("STW", "strChr", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false);
Compiler::emitVcpuAsm("%StringChr", "", false);
return Expression::Numeric(0, uint16_t(-1), true, false, false, Expression::TmpStrVar, Expression::BooleanCC, Expression::Int16Both, std::string(""), std::string(""));
}
Expression::Numeric SPC$(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::SPC$() : '%s:%d' : SPC$() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Create a new temporary string
if(!isFuncNested()) Compiler::nextStrWorkArea();
uint16_t dstAddr = Compiler::getStrWorkArea();
if(numeric._varType == Expression::Number)
{
uint8_t len = uint8_t(std::lround(numeric._value));
if(len < 1 || len > 94)
{
fprintf(stderr, "Functions::SPC$() : '%s:%d' : syntax error, 'SPC$(n)', if 'n' is a literal, it MUST be <1-94> : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitVcpuAsm("LDI", std::to_string(len), false);
Compiler::emitVcpuAsm("%PrintSpc", "", false);
return numeric;
}
// Create SPC string
Compiler::emitVcpuAsm("LDI", std::to_string(len), false);
Compiler::emitVcpuAsm("STW", "strLen", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false);
Compiler::emitVcpuAsm("%StringSpc", "", false);
return Expression::Numeric(0, uint16_t(-1), true, false, false, Expression::TmpStrVar, Expression::BooleanCC, Expression::Int16Both, std::string(""), std::string(""));
}
Compiler::getNextTempVar();
Operators::handleSingleOp("LDW", numeric);
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitVcpuAsm("%PrintSpc", "", false);
return numeric;
}
// Create SPC string
Compiler::emitVcpuAsm("STW", "strLen", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false);
Compiler::emitVcpuAsm("%StringSpc", "", false);
return Expression::Numeric(0, uint16_t(-1), true, false, false, Expression::TmpStrVar, Expression::BooleanCC, Expression::Int16Both, std::string(""), std::string(""));
}
Expression::Numeric STR$(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::STR$() : '%s:%d' : STR$() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Create a new temporary string
if(!isFuncNested()) Compiler::nextStrWorkArea();
uint16_t dstAddr = Compiler::getStrWorkArea();
if(numeric._varType == Expression::Number)
{
// Print STR string, (without wasting memory)
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(int16_t(std::lround(numeric._value))), false);
Compiler::emitVcpuAsm("%PrintAcInt16", "", false);
return numeric;
}
// Create STR string
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(int16_t(std::lround(numeric._value))), false);
Compiler::emitVcpuAsm("STW", "strInteger", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false);
Compiler::emitVcpuAsm("%StringInt", "", false);
return Expression::Numeric(0, uint16_t(-1), true, false, false, Expression::TmpStrVar, Expression::BooleanCC, Expression::Int16Both, std::string(""), std::string(""));
}
Compiler::getNextTempVar();
Operators::handleSingleOp("LDW", numeric);
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitVcpuAsm("%PrintAcInt16", "", false);
return numeric;
}
// Create STR string
Compiler::emitVcpuAsm("STW", "strInteger", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false);
Compiler::emitVcpuAsm("%StringInt", "", false);
return Expression::Numeric(0, uint16_t(-1), true, false, false, Expression::TmpStrVar, Expression::BooleanCC, Expression::Int16Both, std::string(""), std::string(""));
}
Expression::Numeric STRING$(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::STRING$() : '%s:%d' : STRING$() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._varType == Expression::Number)
{
// Print STR string, (without wasting memory)
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(uint16_t(std::lround(numeric._value))), false);
Compiler::emitVcpuAsm("%PrintAcString", "", false);
return numeric;
}
// Point to STR address
return Expression::Numeric(numeric._value, uint16_t(-1), true, false, false, Expression::StrAddr, Expression::BooleanCC, Expression::Int16Both, std::string(""), std::string(""));
}
Compiler::getNextTempVar();
Operators::handleSingleOp("LDW", numeric);
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitVcpuAsm("%PrintAcString", "", false);
return numeric;
}
Operators::changeToTmpVar(numeric);
Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false);
numeric._varType = Expression::TmpStrAddr;
return numeric;
}
Expression::Numeric TIME$(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::TIME$() : '%s:%d' : TIME$() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Function with no parameters, so isValid needs to be explicitly set
numeric._isValid = true;
// Generate new time string
Compiler::emitVcpuAsm("%TimeString", "", false);
// Print it directly if able
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitVcpuAsm("%PrintString", "_timeString_", false);
return numeric;
}
// Create a new temporary string
if(!isFuncNested()) Compiler::nextStrWorkArea();
uint16_t dstAddr = Compiler::getStrWorkArea();
Compiler::emitVcpuAsm("LDWI", "_timeString_", false);
Compiler::emitVcpuAsm("STW", "strSrcAddr", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false);
Compiler::emitVcpuAsm("%StringCopy", "", false);
return Expression::Numeric(0, uint16_t(-1), true, false, false, Expression::TmpStrVar, Expression::BooleanCC, Expression::Int16Both, std::string(""), std::string(""));
}
Expression::Numeric HEX$(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::HEX$() : '%s:%d' : HEX$() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params.size() != 1)
{
fprintf(stderr, "Functions::HEX$() : '%s:%d' : syntax error, 'HEX$(x, n)' requires two parameters : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params[0]._varType == Expression::Number)
{
int16_t val = int16_t(std::lround(numeric._params[0]._value));
if(val < 1 || val > 4)
{
fprintf(stderr, "Functions::HEX$() : '%s:%d' : syntax error, 'HEX$(x, n)', if 'n' is a literal, it MUST be <1-4> : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
Compiler::emitVcpuAsm("LDI", std::to_string(val), false);
}
else
{
Operators::createSingleOp("LDW", numeric._params[0]);
}
Compiler::emitVcpuAsm("ST", "textLen", false);
// Create a new temporary string
if(!isFuncNested()) Compiler::nextStrWorkArea();
uint16_t dstAddr = Compiler::getStrWorkArea();
if(numeric._varType == Expression::Number)
{
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(uint16_t(std::lround(numeric._value))), false);
Compiler::emitVcpuAsm("STW", "textHex", false);
// Print HEX string, (without wasting memory)
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitVcpuAsm("%PrintHex", "", false);
numeric._params.clear();
return numeric;
}
// Create HEX string
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false);
Compiler::emitVcpuAsm("%StringHex", "", false);
return Expression::Numeric(0, uint16_t(-1), true, false, false, Expression::TmpStrVar, Expression::BooleanCC, Expression::Int16Both, std::string(""), std::string(""));
}
Compiler::getNextTempVar();
Operators::handleSingleOp("LDW", numeric);
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitVcpuAsm("STW", "textHex", false);
Compiler::emitVcpuAsm("%PrintHex", "", false);
numeric._params.clear();
return numeric;
}
// Create HEX string
Compiler::emitVcpuAsm("STW", "strHex", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false);
Compiler::emitVcpuAsm("%StringHex", "", false);
return Expression::Numeric(0, uint16_t(-1), true, false, false, Expression::TmpStrVar, Expression::BooleanCC, Expression::Int16Both, std::string(""), std::string(""));
}
Expression::Numeric LEFT$(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::LEFT$() : '%s:%d' : LEFT$() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params.size() != 1)
{
fprintf(stderr, "Functions::LEFT$() : '%s:%d' : syntax error, 'LEFT$(s$, n)' requires two parameters : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Literal string and parameter, (optimised case)
if(numeric._varType == Expression::String && numeric._params[0]._varType == Expression::Number)
{
int index;
std::string name;
handleConstantString(numeric, Compiler::StrLeft, name, index);
return Expression::Numeric(0, uint16_t(index), true, false, false, Expression::StrVar, Expression::BooleanCC, Expression::Int16Both, name, std::string(""));
}
// Non optimised case
std::string name;
uint16_t srcAddr;
int index = int(numeric._index);
// String input can be literal, const, var and temp
if(numeric._varType == Expression::TmpStrVar)
{
// Second parameter can never be a temp string
srcAddr = Compiler::getStrWorkArea();
}
else
{
Compiler::getOrCreateString(numeric, name, srcAddr, index);
}
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitStringAddress(numeric, srcAddr);
Compiler::emitVcpuAsm("STW", "textStr", false);
handleStringParameter(numeric._params[0]);
Compiler::emitVcpuAsm("STW", "textLen", false);
Compiler::emitVcpuAsm("%PrintAcLeft", "", false);
}
else
{
// Create a new temporary string
if(!isFuncNested()) Compiler::nextStrWorkArea();
uint16_t dstAddr = Compiler::getStrWorkArea();
// Optimise STW/LDW
if(numeric._params[0]._varType == Expression::TmpVar)
{
handleStringParameter(numeric._params[0]);
Compiler::emitVcpuAsm("STW", "strDstLen", false);
Compiler::emitStringAddress(numeric, srcAddr);
Compiler::emitVcpuAsm("STW", "strSrcAddr", false);
}
else
{
Compiler::emitStringAddress(numeric, srcAddr);
Compiler::emitVcpuAsm("STW", "strSrcAddr", false);
handleStringParameter(numeric._params[0]);
Compiler::emitVcpuAsm("STW", "strDstLen", false);
}
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false);
Compiler::emitVcpuAsm("%StringLeft", "", false);
}
return Expression::Numeric(0, uint16_t(-1), true, false, false, Expression::TmpStrVar, Expression::BooleanCC, Expression::Int16Both, name, std::string(""));
}
Expression::Numeric RIGHT$(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::RIGHT$() : '%s:%d' : RIGHT$() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params.size() != 1)
{
fprintf(stderr, "Functions::RIGHT$() : '%s:%d' : syntax error, 'RIGHT$(s$, n)' requires two parameters : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Literal string and parameter, (optimised case)
if(numeric._varType == Expression::String && numeric._params[0]._varType == Expression::Number)
{
int index;
std::string name;
handleConstantString(numeric, Compiler::StrRight, name, index);
return Expression::Numeric(0, uint16_t(index), true, false, false, Expression::StrVar, Expression::BooleanCC, Expression::Int16Both, name, std::string(""));
}
// Non optimised case
std::string name;
uint16_t srcAddr;
int index = int(numeric._index);
// String input can be literal, const, var and temp
if(numeric._varType == Expression::TmpStrVar)
{
srcAddr = Compiler::getStrWorkArea();
}
else
{
Compiler::getOrCreateString(numeric, name, srcAddr, index);
}
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitStringAddress(numeric, srcAddr);
Compiler::emitVcpuAsm("STW", "textStr", false);
handleStringParameter(numeric._params[0]);
Compiler::emitVcpuAsm("STW", "textLen", false);
Compiler::emitVcpuAsm("%PrintAcRight", "", false);
}
else
{
// Create a new temporary string
if(!isFuncNested()) Compiler::nextStrWorkArea();
uint16_t dstAddr = Compiler::getStrWorkArea();
// Optimise STW/LDW
if(numeric._params[0]._varType == Expression::TmpVar)
{
handleStringParameter(numeric._params[0]);
Compiler::emitVcpuAsm("STW", "strDstLen", false);
Compiler::emitStringAddress(numeric, srcAddr);
Compiler::emitVcpuAsm("STW", "strSrcAddr", false);
}
else
{
Compiler::emitStringAddress(numeric, srcAddr);
Compiler::emitVcpuAsm("STW", "strSrcAddr", false);
handleStringParameter(numeric._params[0]);
Compiler::emitVcpuAsm("STW", "strDstLen", false);
}
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false);
Compiler::emitVcpuAsm("%StringRight", "", false);
}
return Expression::Numeric(0, uint16_t(-1), true, false, false, Expression::TmpStrVar, Expression::BooleanCC, Expression::Int16Both, name, std::string(""));
}
Expression::Numeric MID$(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::MID$() : '%s:%d' : MID$() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params.size() != 2)
{
fprintf(stderr, "Functions::MID$() : '%s:%d' : syntax error, 'MID$(s$, i, n)' requires three parameters : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Literal string and parameters, (optimised case)
if(numeric._varType == Expression::String && numeric._params[0]._varType == Expression::Number && numeric._params[1]._varType == Expression::Number)
{
int index;
std::string name;
handleConstantString(numeric, Compiler::StrMid, name, index);
return Expression::Numeric(0, uint16_t(index), true, false, false, Expression::StrVar, Expression::BooleanCC, Expression::Int16Both, name, std::string(""));
}
// Non optimised case
std::string name;
uint16_t srcAddr;
int index = int(numeric._index);
// String input can be literal, const, var and temp
if(numeric._varType == Expression::TmpStrVar)
{
srcAddr = Compiler::getStrWorkArea();
}
else
{
Compiler::getOrCreateString(numeric, name, srcAddr, index);
}
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitStringAddress(numeric, srcAddr);
Compiler::emitVcpuAsm("STW", "textStr", false);
handleStringParameter(numeric._params[1]);
Compiler::emitVcpuAsm("STW", "textLen", false);
handleStringParameter(numeric._params[0]);
Compiler::emitVcpuAsm("STW", "textOfs", false);
Compiler::emitVcpuAsm("%PrintAcMid", "", false);
}
else
{
// Create a new temporary string
if(!isFuncNested()) Compiler::nextStrWorkArea();
uint16_t dstAddr = Compiler::getStrWorkArea();
Compiler::emitStringAddress(numeric, srcAddr);
Compiler::emitVcpuAsm("STW", "strSrcAddr", false);
handleStringParameter(numeric._params[1]);
Compiler::emitVcpuAsm("STW", "strDstLen", false);
handleStringParameter(numeric._params[0]);
Compiler::emitVcpuAsm("STW", "strOffset", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false);
Compiler::emitVcpuAsm("%StringMid", "", false);
}
return Expression::Numeric(0, uint16_t(-1), true, false, false, Expression::TmpStrVar, Expression::BooleanCC, Expression::Int16Both, name, std::string(""));
}
Expression::Numeric LOWER$(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::LOWER$() : '%s:%d' : LOWER$() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params.size() != 0)
{
fprintf(stderr, "Functions::LOWER$() : '%s:%d' : syntax error, 'LOWER$()' requires one string parameter : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Literal string and parameter, (optimised case)
if(numeric._varType == Expression::String)
{
int index;
std::string name;
handleConstantString(numeric, Compiler::StrLower, name, index);
return Expression::Numeric(0, uint16_t(index), true, false, false, Expression::StrVar, Expression::BooleanCC, Expression::Int16Both, name, std::string(""));
}
// Non optimised case
std::string name;
uint16_t srcAddr;
int index = int(numeric._index);
// String input can be literal, const, var and temp
if(numeric._varType == Expression::TmpStrVar)
{
srcAddr = Compiler::getStrWorkArea();
}
else
{
Compiler::getOrCreateString(numeric, name, srcAddr, index);
}
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitStringAddress(numeric, srcAddr);
Compiler::emitVcpuAsm("STW", "textStr", false);
Compiler::emitVcpuAsm("%PrintAcLower", "", false);
}
else
{
// Create a new temporary string
if(!isFuncNested()) Compiler::nextStrWorkArea();
uint16_t dstAddr = Compiler::getStrWorkArea();
Compiler::emitStringAddress(numeric, srcAddr);
Compiler::emitVcpuAsm("STW", "strSrcAddr", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false);
Compiler::emitVcpuAsm("%StringLower", "", false);
}
return Expression::Numeric(0, uint16_t(-1), true, false, false, Expression::TmpStrVar, Expression::BooleanCC, Expression::Int16Both, name, std::string(""));
}
Expression::Numeric UPPER$(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::UPPER$() : '%s:%d' : UPPER$() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params.size() != 0)
{
fprintf(stderr, "Functions::UPPER$() : '%s:%d' : syntax error, 'UPPER$()' requires one string parameter : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
// Literal string and parameter, (optimised case)
if(numeric._varType == Expression::String)
{
int index;
std::string name;
handleConstantString(numeric, Compiler::StrUpper, name, index);
return Expression::Numeric(0, uint16_t(index), true, false, false, Expression::StrVar, Expression::BooleanCC, Expression::Int16Both, name, std::string(""));
}
// Non optimised case
std::string name;
uint16_t srcAddr;
int index = int(numeric._index);
// String input can be literal, const, var and temp
if(numeric._varType == Expression::TmpStrVar)
{
srcAddr = Compiler::getStrWorkArea();
}
else
{
Compiler::getOrCreateString(numeric, name, srcAddr, index);
}
if(Expression::getEnableOptimisedPrint() && Expression::getOutputNumeric()._nestedCount == 0)
{
Compiler::emitStringAddress(numeric, srcAddr);
Compiler::emitVcpuAsm("STW", "textStr", false);
Compiler::emitVcpuAsm("%PrintAcUpper", "", false);
}
else
{
// Create a new temporary string
if(!isFuncNested()) Compiler::nextStrWorkArea();
uint16_t dstAddr = Compiler::getStrWorkArea();
Compiler::emitStringAddress(numeric, srcAddr);
Compiler::emitVcpuAsm("STW", "strSrcAddr", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false);
Compiler::emitVcpuAsm("%StringUpper", "", false);
}
return Expression::Numeric(0, uint16_t(-1), true, false, false, Expression::TmpStrVar, Expression::BooleanCC, Expression::Int16Both, name, std::string(""));
}
Expression::Numeric STRCAT$(Expression::Numeric& numeric, const std::string& moduleName, const std::string& codeLineText, int codeLineStart)
{
if(Expression::getOutputNumeric()._staticInit)
{
fprintf(stderr, "Functions::STRCAT$() : '%s:%d' : STRCAT$() cannot be used in static initialisation : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(Expression::getEnableOptimisedPrint())
{
fprintf(stderr, "Functions::STRCAT$() : '%s:%d' : syntax error, STRCAT$() cannot be used in PRINT statements : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._params.size() == 0)
{
fprintf(stderr, "Functions::STRCAT$() : '%s:%d' : syntax error, STRCAT$() requires at least two string parameters : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
if(numeric._varType == Expression::TmpStrVar)
{
fprintf(stderr, "Functions::STRCAT$() : '%s:%d' : syntax error, STRCAT$() requires string literals or string variables as ALL parameters : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
for(int i=0; i<int(numeric._params.size()); i++)
{
if(numeric._params[i]._varType == Expression::TmpStrVar)
{
fprintf(stderr, "Functions::STRCAT$() : '%s:%d' : syntax error, STRCAT$() requires string literals or string variables as ALL parameters : %s\n", moduleName.c_str(), codeLineStart, codeLineText.c_str());
numeric._isValid = false;
return numeric;
}
}
// Source string addresses, (extra 0x0000 delimiter used by VASM runtime)
std::string name;
int index = int(numeric._index);
std::vector<uint16_t> strAddrs(numeric._params.size() + 2, 0x0000);
Compiler::getOrCreateString(numeric, name, strAddrs[0], index);
for(int i=0; i<int(numeric._params.size()); i++)
{
index = int(numeric._params[i]._index);
Compiler::getOrCreateString(numeric._params[i], name, strAddrs[i + 1], index);
}
// Source string addresses LUT
uint16_t lutAddress;
if(!Memory::getFreeRAM(Memory::FitDescending, int(strAddrs.size()*2), USER_CODE_START, Compiler::getStringsStart(), lutAddress))
{
fprintf(stderr, "Functions::STRCAT$() : '%s:%d' : not enough RAM for string concatenation LUT of size %d : %s\n", moduleName.c_str(), codeLineStart, int(strAddrs.size()), codeLineText.c_str());
return false;
}
Compiler::getCodeLines()[Compiler::getCurrentCodeLineIndex()]._strConcatLut = {lutAddress, strAddrs};
// Concatenate multiple source strings to string work area
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(lutAddress), false);
Compiler::emitVcpuAsm("STW", "strLutAddr", false);
Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(Compiler::getStrWorkArea()), false);
Compiler::emitVcpuAsm("%StringConcatLut", "", false);
return Expression::Numeric(0, uint16_t(-1), true, false, false, Expression::TmpStrVar, Expression::BooleanCC, Expression::Int16Both, name, std::string(""));
}
} | 43.82819 | 252 | 0.557916 |
0137689f5d1a19f6f7f3b962df0f9d939eac85fd | 1,983 | cc | C++ | stapl_release/docs/reference/view/multi.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/docs/reference/view/multi.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/docs/reference/view/multi.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | // cont/multi.cc
#include <stapl/containers/multiarray/multiarray.hpp>
#include <stapl/views/multiarray_view.hpp>
#include <stapl/containers/type_traits/default_traversal.hpp>
#include <stapl/algorithms/algorithm.hpp>
#include <stapl/algorithms/functional.hpp>
#include "viewhelp.hpp"
using namespace std;
typedef int val_tp;
typedef stapl::indexed_domain<size_t> vec_dom_tp;
typedef stapl::balanced_partition<vec_dom_tp> bal_part_tp;
typedef stapl::default_traversal<3>::type trav3_tp;
typedef stapl::nd_partition<
stapl::tuple<bal_part_tp, bal_part_tp, bal_part_tp>,
trav3_tp> part3_tp;
typedef stapl::tuple<size_t, size_t, size_t> gid_tp;
typedef stapl::multiarray<3, int, trav3_tp, part3_tp> ary3_int_tp;
typedef stapl::multiarray_view<ary3_int_tp> ary3_int_vw_tp;
typedef ary3_int_vw_tp::domain_type dom_tp;
typedef stapl::plus<val_tp> add_int_wf;
stapl::exit_code stapl_main(int argc, char **argv) {
// construct container
stapl::tuple<size_t,size_t,size_t> dims = stapl::make_tuple(3,4,5);
ary3_int_tp a_ct(dims), b_ct(dims), c_ct(dims);
// construct view over container
ary3_int_vw_tp a_vw(a_ct), b_vw(b_ct), c_vw(c_ct);
auto a_lin_vw = stapl::linear_view(a_vw);
auto b_lin_vw = stapl::linear_view(b_vw);
auto c_lin_vw = stapl::linear_view(c_vw);
// initialize containers in parallel
int base = 0;
int step = 10;
typedef stapl::sequence<int> step_wf;
stapl::generate(a_lin_vw, step_wf(base,step));
int rep = 12;
typedef stapl::block_sequence<int> repeat_wf;
stapl::generate(b_lin_vw, repeat_wf(base,rep));
stapl::iota(c_lin_vw, 0);
// process elements in parallel
stapl::transform( a_lin_vw, b_lin_vw, c_lin_vw, add_int_wf() );
// print elements
stapl::stream<ofstream> zout;
zout.open("refman_multvw.txt");
stapl::serial_io( put_val_wf(zout), c_vw );
return EXIT_SUCCESS;
}
| 30.984375 | 70 | 0.704488 |
01376e57347f54f4d6ca3209bcd2429d52c0bcdc | 17,513 | hpp | C++ | include/Avocado/backend/backend_descriptors.hpp | AvocadoML/Avocado | 9595cc5994d916f0ecb24873a5afa98437977fb5 | [
"Apache-2.0"
] | null | null | null | include/Avocado/backend/backend_descriptors.hpp | AvocadoML/Avocado | 9595cc5994d916f0ecb24873a5afa98437977fb5 | [
"Apache-2.0"
] | null | null | null | include/Avocado/backend/backend_descriptors.hpp | AvocadoML/Avocado | 9595cc5994d916f0ecb24873a5afa98437977fb5 | [
"Apache-2.0"
] | null | null | null | /*
* backend_descriptors.hpp
*
* Created on: Dec 5, 2021
* Author: Maciej Kozarzewski
*/
#ifndef AVOCADO_BACKEND_BACKEND_DESCRIPTORS_HPP_
#define AVOCADO_BACKEND_BACKEND_DESCRIPTORS_HPP_
#include "backend_defs.h"
#include <type_traits>
#include <array>
#include <vector>
#include <stack>
#include <algorithm>
#include <complex>
#include <memory>
#include <cstring>
#include <cassert>
#include <mutex>
#include <iostream>
#if USE_CPU
#elif USE_CUDA
# include <cuda_runtime_api.h>
# include <cuda_fp16.h>
# include <cublas_v2.h>
#elif USE_OPENCL
# include <CL/cl.hpp>
#else
#endif
namespace avocado
{
namespace backend
{
#if USE_CPU
namespace cpu
{
#elif USE_CUDA
namespace cuda
{
#elif USE_OPENCL
namespace opencl
{
#else
namespace reference
{
#endif
int get_number_of_devices();
avDeviceType_t get_device_type(av_int64 descriptor) noexcept;
int get_descriptor_type(av_int64 descriptor) noexcept;
avDeviceIndex_t get_device_index(av_int64 descriptor) noexcept;
int get_descriptor_index(av_int64 descriptor) noexcept;
av_int64 get_current_device_type() noexcept;
av_int64 get_current_device_index() noexcept;
av_int64 create_descriptor(int index, av_int64 type);
int dataTypeSize(avDataType_t dtype) noexcept;
class MemoryDescriptor
{
#if USE_OPENCL
int8_t *m_data = nullptr;
#else
int8_t *m_data = nullptr;
#endif
avDeviceIndex_t m_device_index = AVOCADO_INVALID_DEVICE_INDEX;
av_int64 m_size = 0;
av_int64 m_offset = 0;
bool m_is_owning = false;
public:
static constexpr av_int64 descriptor_type = 1;
MemoryDescriptor() = default;
#if USE_CUDA or USE_OPENCL
MemoryDescriptor(avDeviceIndex_t index, av_int64 sizeInBytes);
#else
MemoryDescriptor(av_int64 sizeInBytes);
#endif
MemoryDescriptor(const MemoryDescriptor &other, av_int64 size, av_int64 offset);
MemoryDescriptor(const MemoryDescriptor &other) = delete;
MemoryDescriptor(MemoryDescriptor &&other);
MemoryDescriptor& operator=(const MemoryDescriptor &other) = delete;
MemoryDescriptor& operator=(MemoryDescriptor &&other);
~MemoryDescriptor();
bool isNull() const noexcept;
av_int64 size() const noexcept;
avDeviceIndex_t device() const noexcept;
static std::string className();
/**
* \brief This method allocates new memory block and sets up the descriptor.
*/
#if USE_CUDA or USE_OPENCL
void create(avDeviceIndex_t index, av_int64 sizeInBytes);
#else
void create(av_int64 sizeInBytes);
#endif
/**
* \brief Creates a non-owning view of another memory block.
*/
void create(const MemoryDescriptor &other, av_int64 size, av_int64 offset);
/**
* \brief This method deallocates underlying memory and resets the descriptor.
* Calling this method on an already destroyed descriptor has no effect.
*/
void destroy();
#if USE_OPENCL
// cl::Buffer& data(void *ptr) noexcept;
// const cl::Buffer& data(const void *ptr) const noexcept;
template<typename T = void>
T* data() noexcept
{
return reinterpret_cast<T*>(m_data + m_offset);
}
template<typename T = void>
const T* data() const noexcept
{
return reinterpret_cast<const T*>(m_data + m_offset);
}
#else
template<typename T = void>
T* data() noexcept
{
return reinterpret_cast<T*>(m_data);
}
template<typename T = void>
const T* data() const noexcept
{
return reinterpret_cast<const T*>(m_data);
}
#endif
};
class ContextDescriptor
{
#if USE_CPU
#elif USE_CUDA
cudaStream_t m_stream = nullptr;
cublasHandle_t m_handle = nullptr;
#elif USE_OPENCL
#else
#endif
avDeviceIndex_t m_device_index = AVOCADO_INVALID_DEVICE_INDEX;
mutable MemoryDescriptor m_workspace;
mutable av_int64 m_workspace_size = 0;
public:
static constexpr av_int64 descriptor_type = 2;
ContextDescriptor() = default;
ContextDescriptor(const ContextDescriptor &other) = delete;
ContextDescriptor(ContextDescriptor &&other);
ContextDescriptor& operator=(const ContextDescriptor &other) = delete;
ContextDescriptor& operator=(ContextDescriptor &&other);
~ContextDescriptor();
static std::string className();
/**
* \brief This method initializes context descriptor.
*/
#if USE_CPU
void create();
#elif USE_CUDA
void create(avDeviceIndex_t index, bool useDefaultStream = false);
#elif USE_OPENCL
void create(avDeviceIndex_t index, bool useDefaultCommandQueue);
#else
void create();
#endif
/**
* \brief This method destroys context and all its resources.
* Calling this method on an already destroyed descriptor has no effect.
*/
void destroy();
MemoryDescriptor& getWorkspace() const;
#if USE_CUDA
void setDevice() const;
avDeviceIndex_t getDevice() const noexcept;
cudaStream_t getStream() const noexcept;
cublasHandle_t getHandle() const noexcept;
#endif
};
class TensorDescriptor
{
std::array<int, AVOCADO_MAX_TENSOR_DIMENSIONS> m_dimensions;
std::array<int, AVOCADO_MAX_TENSOR_DIMENSIONS> m_strides;
int m_number_of_dimensions = 0;
avDataType_t m_dtype = AVOCADO_DTYPE_UNKNOWN;
public:
static constexpr av_int64 descriptor_type = 3;
TensorDescriptor() = default;
TensorDescriptor(std::initializer_list<int> dimensions, avDataType_t dtype);
static std::string className();
void create();
void destroy();
void set(avDataType_t dtype, int nbDims, const int dimensions[]);
void get(avDataType_t *dtype, int *nbDims, int dimensions[]) const;
int& operator[](int index);
int operator[](int index) const;
int dimension(int index) const;
int nbDims() const noexcept;
av_int64 sizeInBytes() const noexcept;
int getIndex(std::initializer_list<int> indices) const noexcept;
int firstDim() const noexcept;
int lastDim() const noexcept;
int volume() const noexcept;
int volumeWithoutFirstDim() const noexcept;
int volumeWithoutLastDim() const noexcept;
avDataType_t dtype() const noexcept;
bool equalShape(const TensorDescriptor &other) noexcept;
std::string toString() const;
private:
void setup_stride();
};
class ConvolutionDescriptor
{
public:
static constexpr av_int64 descriptor_type = 4;
avConvolutionMode_t mode = AVOCADO_CONVOLUTION_MODE;
int dimensions = 2;
std::array<int, 3> padding;
std::array<int, 3> stride;
std::array<int, 3> dilation;
std::array<uint8_t, 16> padding_value;
int groups = 1;
ConvolutionDescriptor() = default;
void create();
void destroy();
static std::string className();
void set(avConvolutionMode_t mode, int nbDims, const int padding[], const int strides[], const int dilation[], int groups,
const void *paddingValue);
void get(avConvolutionMode_t *mode, int *nbDims, int padding[], int strides[], int dilation[], int *groups,
void *paddingValue) const;
template<typename T>
T getPaddingValue() const noexcept
{
static_assert(sizeof(T) <= sizeof(padding_value), "");
T result;
std::memcpy(&result, padding_value.data(), sizeof(T));
return result;
}
bool paddingWithZeros() const noexcept;
TensorDescriptor getOutputShape(const TensorDescriptor &xDesc, const TensorDescriptor &wDesc) const;
bool isStrided() const noexcept;
bool isDilated() const noexcept;
std::string toString() const;
};
class PoolingDescriptor
{
public:
static constexpr av_int64 descriptor_type = 5;
avPoolingMode_t mode = AVOCADO_POOLING_MAX;
std::array<int, 3> filter;
std::array<int, 3> padding;
std::array<int, 3> stride;
PoolingDescriptor() = default;
void create();
void destroy();
static std::string className();
};
class OptimizerDescriptor
{
public:
static constexpr av_int64 descriptor_type = 6;
avOptimizerType_t type = AVOCADO_OPTIMIZER_SGD;
int64_t steps = 0;
double learning_rate = 0.0;
std::array<double, 4> coef;
std::array<bool, 4> flags;
OptimizerDescriptor() = default;
void create();
void destroy();
static std::string className();
void set(avOptimizerType_t optimizerType, av_int64 steps, double learningRate, const double coefficients[], const bool flags[]);
void get(avOptimizerType_t *optimizerType, av_int64 *steps, double *learningRate, double coefficients[], bool flags[]);
void get_workspace_size(av_int64 *result, const TensorDescriptor &wDesc) const;
};
class DropoutDescriptor
{
public:
static constexpr av_int64 descriptor_type = 7;
DropoutDescriptor() = default;
void create();
void destroy();
static std::string className();
};
/*
* DescriptorPool
*/
template<typename T>
class DescriptorPool
{
T m_null_descriptor;
std::vector<std::unique_ptr<T>> m_pool;
std::vector<int> m_available_descriptors;
std::mutex m_pool_mutex;
public:
DescriptorPool(size_t initialSize = 10, int numRestricted = 0)
{
m_pool.reserve(initialSize + numRestricted);
m_available_descriptors.reserve(initialSize);
for (int i = 0; i < numRestricted; i++)
m_pool.push_back(nullptr); // reserve few descriptors values for default objects
}
DescriptorPool(const DescriptorPool<T> &other) = delete;
DescriptorPool(DescriptorPool<T> &&other) :
m_pool(std::move(other.m_pool)),
m_available_descriptors(std::move(other.m_available_descriptors))
{
}
DescriptorPool& operator=(const DescriptorPool<T> &other) = delete;
DescriptorPool& operator=(DescriptorPool<T> &&other)
{
std::swap(this->m_pool, other.m_pool);
std::swap(this->m_available_descriptors, other.m_available_descriptors);
return *this;
}
~DescriptorPool() = default;
/**
* \brief Checks if the passed descriptor is valid.
* The descriptor is valid if and only if its index is within the size of m_pool vector and is not in the list of available descriptors.
*/
bool isValid(int64_t desc) const noexcept
{
// std::cout << __FUNCTION__ << "() " << __LINE__ << " : index = " << desc << '\n';
// std::cout << __FUNCTION__ << "() " << __LINE__ << " : device type = " << get_current_device_type() << '\n';
if (get_current_device_type() != get_device_type(desc))
{
// std::cout << __FUNCTION__ << "() " << __LINE__ << " : device type mismatch : " << get_current_device_type() << " vs "
// << get_device_type(desc) << std::endl;
return false;
}
if (T::descriptor_type != get_descriptor_type(desc))
{
// std::cout << __FUNCTION__ << "() " << __LINE__ << " : type mismatch : " << T::descriptor_type << " vs "
// << get_descriptor_type(desc) << std::endl;
return false;
}
int index = get_descriptor_index(desc);
// std::cout << __FUNCTION__ << "() " << __LINE__ << " object index = " << index << '\n';
if (index < 0 or index > static_cast<int>(m_pool.size()))
{
// std::cout << __FUNCTION__ << "() " << __LINE__ << " : out of bounds : " << index << " vs 0:" << m_pool.size()
// << std::endl;
return false;
}
bool asdf = std::find(m_available_descriptors.begin(), m_available_descriptors.end(), index) == m_available_descriptors.end();
if (asdf == false)
{
// std::cout << "not in available" << std::endl;
}
return asdf;
}
T& get(av_int64 desc)
{
// std::cout << __FUNCTION__ << "() " << __LINE__ << " : " << T::className() << " object index = " << get_descriptor_index(desc)
// << '\n';
if (desc == AVOCADO_NULL_DESCRIPTOR)
return m_null_descriptor;
else
{
if (isValid(desc))
return *(m_pool.at(get_descriptor_index(desc)));
else
throw std::logic_error("invalid descriptor " + std::to_string(desc) + " for pool type '" + T::className() + "'");
}
}
template<typename ... Args>
av_int64 create(Args &&... args)
{
std::lock_guard<std::mutex> lock(m_pool_mutex);
int result;
if (m_available_descriptors.size() > 0)
{
result = m_available_descriptors.back();
m_available_descriptors.pop_back();
}
else
{
m_pool.push_back(std::make_unique<T>());
result = m_pool.size() - 1;
}
m_pool.at(result)->create(std::forward<Args>(args)...);
av_int64 tmp = create_descriptor(result, T::descriptor_type);
// std::cout << __FUNCTION__ << "() " << __LINE__ << " : " << T::className() << " = " << tmp << ", object index = " << result
// << std::endl;
return tmp;
}
void destroy(av_int64 desc)
{
std::lock_guard<std::mutex> lock(m_pool_mutex);
// std::cout << __FUNCTION__ << "() " << __LINE__ << " : " << T::className() << " = " << desc << std::endl;
if (not isValid(desc))
throw std::logic_error("invalid descriptor " + std::to_string(desc) + " of type '" + T::className() + "'");
int index = get_descriptor_index(desc);
// std::cout << __FUNCTION__ << "() " << __LINE__ << " object index = " << index << std::endl;
m_pool.at(index)->destroy();
m_available_descriptors.push_back(index);
}
};
template<class T>
DescriptorPool<T>& getPool()
{
static DescriptorPool<T> result;
return result;
}
template<>
DescriptorPool<ContextDescriptor>& getPool();
template<typename T, typename ... Args>
avStatus_t create(av_int64 *result, Args &&... args)
{
if (result == nullptr)
return AVOCADO_STATUS_BAD_PARAM;
try
{
result[0] = getPool<T>().create(std::forward<Args>(args)...);
} catch (std::exception &e)
{
return AVOCADO_STATUS_INTERNAL_ERROR;
}
return AVOCADO_STATUS_SUCCESS;
}
template<typename T>
avStatus_t destroy(av_int64 desc)
{
try
{
getPool<T>().destroy(desc);
} catch (std::exception &e)
{
return AVOCADO_STATUS_FREE_FAILED;
}
return AVOCADO_STATUS_SUCCESS;
}
bool isDefault(avContextDescriptor_t desc);
MemoryDescriptor& getMemory(avMemoryDescriptor_t desc);
ContextDescriptor& getContext(avContextDescriptor_t desc);
TensorDescriptor& getTensor(avTensorDescriptor_t desc);
ConvolutionDescriptor& getConvolution(avConvolutionDescriptor_t desc);
PoolingDescriptor& getPooling(avPoolingDescriptor_t desc);
OptimizerDescriptor& getOptimizer(avOptimizerDescriptor_t desc);
DropoutDescriptor& getDropout(avDropoutDescriptor_t desc);
template<typename T = void>
T* getPointer(avMemoryDescriptor_t desc)
{
try
{
return getMemory(desc).data<T>();
} catch (std::exception &e)
{
return nullptr;
}
}
template<typename T>
void setScalarValue(void *scalar, T x) noexcept
{
assert(scalar != nullptr);
reinterpret_cast<T*>(scalar)[0] = x;
}
template<typename T>
T getScalarValue(const void *scalar) noexcept
{
assert(scalar != nullptr);
return reinterpret_cast<const T*>(scalar)[0];
}
template<typename T = float>
T getAlphaValue(const void *alpha) noexcept
{
if (alpha == nullptr)
return static_cast<T>(1);
else
return reinterpret_cast<const T*>(alpha)[0];
}
template<typename T = float>
T getBetaValue(const void *beta) noexcept
{
if (beta == nullptr)
return static_cast<T>(0);
else
return reinterpret_cast<const T*>(beta)[0];
}
#if USE_CUDA
template<>
float2 getAlphaValue<float2>(const void *alpha) noexcept;
template<>
float2 getBetaValue<float2>(const void *beta) noexcept;
template<>
double2 getAlphaValue<double2>(const void *alpha) noexcept;
template<>
double2 getBetaValue<double2>(const void *beta) noexcept;
#endif
struct BroadcastedDimensions
{
int first;
int last;
};
/**
* Only the right hand side (rhs) operand can be broadcasted into the left hand side (lhs).
* The number of dimensions of the rhs tensor must be lower or equal to the lhs tensor.
* All k dimensions of the rhs must match the last k dimensions of the lhs.
*
*/
bool isBroadcastPossible(const TensorDescriptor &lhs, const TensorDescriptor &rhs) noexcept;
int volume(const BroadcastedDimensions &dims) noexcept;
BroadcastedDimensions getBroadcastDimensions(const TensorDescriptor &lhs, const TensorDescriptor &rhs) noexcept;
bool is_transpose(avGemmOperation_t op) noexcept;
bool is_logical(avBinaryOp_t op) noexcept;
bool is_logical(avUnaryOp_t op) noexcept;
bool is_logical(avReduceOp_t op) noexcept;
template<typename T, typename U>
bool same_device_type(T lhs, U rhs)
{
return get_device_type(lhs) == get_device_type(rhs);
}
template<typename T, typename U, typename ... ARGS>
bool same_device_type(T lhs, U rhs, ARGS ... args)
{
if (get_device_type(lhs) == get_device_type(rhs))
return same_device_type(lhs, args...);
else
return false;
}
} /* namespace cpu/cuda/opencl/reference */
} /* namespace backend */
} /* namespace avocado */
#endif /* AVOCADO_BACKEND_BACKEND_DESCRIPTORS_HPP_ */
| 30.510453 | 141 | 0.661394 |
013931e763162277ef1f3cc213d891500ae16cbe | 1,925 | cc | C++ | firestore/src/jni/object.cc | oliwilkinsonio/firebase-cpp-sdk | 1a2790030e92f77ad2aaa87000a1222d12dcabfc | [
"Apache-2.0"
] | 193 | 2019-03-18T16:30:43.000Z | 2022-03-30T17:39:32.000Z | firestore/src/jni/object.cc | oliwilkinsonio/firebase-cpp-sdk | 1a2790030e92f77ad2aaa87000a1222d12dcabfc | [
"Apache-2.0"
] | 647 | 2019-03-18T20:50:41.000Z | 2022-03-31T18:32:33.000Z | firestore/src/jni/object.cc | oliwilkinsonio/firebase-cpp-sdk | 1a2790030e92f77ad2aaa87000a1222d12dcabfc | [
"Apache-2.0"
] | 86 | 2019-04-21T09:40:38.000Z | 2022-03-26T20:48:37.000Z | /*
* Copyright 2020 Google LLC
*
* 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 "firestore/src/jni/object.h"
#include "app/src/util_android.h"
#include "firestore/src/jni/class.h"
#include "firestore/src/jni/env.h"
#include "firestore/src/jni/loader.h"
namespace firebase {
namespace firestore {
namespace jni {
namespace {
Method<bool> kEquals("equals", "(Ljava/lang/Object;)Z");
Method<String> kToString("toString", "()Ljava/lang/String;");
jclass object_class = nullptr;
} // namespace
void Object::Initialize(Loader& loader) {
object_class = util::object::GetClass();
loader.LoadFromExistingClass("java/lang/Object", object_class, kEquals,
kToString);
}
Class Object::GetClass() { return Class(object_class); }
std::string Object::ToString(Env& env) const {
Local<String> java_string = env.Call(*this, kToString);
return java_string.ToString(env);
}
bool Object::Equals(Env& env, const Object& other) const {
return env.Call(*this, kEquals, other);
}
bool Object::Equals(Env& env, const Object& lhs, const Object& rhs) {
// Most likely only happens when comparing one with itself or both are null.
if (lhs.get() == rhs.get()) return true;
// If only one of them is nullptr, then they cannot equal.
if (!lhs || !rhs) return false;
return lhs.Equals(env, rhs);
}
} // namespace jni
} // namespace firestore
} // namespace firebase
| 29.615385 | 78 | 0.707532 |
01397d31fe431d899f2d2b93ba2b8846afc3137d | 175 | hpp | C++ | FootCommander.hpp | amit1021/wargame-b | 3b10fd404f7af5acfe1cfcc2c791f18afa36ab66 | [
"MIT"
] | null | null | null | FootCommander.hpp | amit1021/wargame-b | 3b10fd404f7af5acfe1cfcc2c791f18afa36ab66 | [
"MIT"
] | null | null | null | FootCommander.hpp | amit1021/wargame-b | 3b10fd404f7af5acfe1cfcc2c791f18afa36ab66 | [
"MIT"
] | null | null | null | #include <iostream>
#include "Soldier.hpp"
class FootCommander : public Soldier
{
public:
FootCommander(int player) : Soldier(150,20,player){}
~FootCommander();
};
| 15.909091 | 57 | 0.697143 |
01413df5169b1339147ff85e257547c93c4f486f | 1,975 | cpp | C++ | Demo/MdiDemo/MdiDemoView.cpp | yanlinlin82/libffc | 6e067b0840f29958b97daea38bcd61099c2a473f | [
"MIT"
] | 9 | 2017-10-31T10:15:31.000Z | 2021-08-02T20:40:45.000Z | Demo/MdiDemo/MdiDemoView.cpp | yanlinlin82/libffc | 6e067b0840f29958b97daea38bcd61099c2a473f | [
"MIT"
] | 1 | 2019-07-21T12:13:37.000Z | 2019-07-22T14:56:18.000Z | Demo/MdiDemo/MdiDemoView.cpp | yanlinlin82/libffc | 6e067b0840f29958b97daea38bcd61099c2a473f | [
"MIT"
] | 5 | 2016-07-31T09:08:18.000Z | 2022-03-22T14:28:16.000Z | // MdiDemoView.cpp : implementation of the CMdiDemoView class
//
#include "stdafx.h"
#include "MdiDemo.h"
#include "MdiDemoDoc.h"
#include "MdiDemoView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CMdiDemoView
IMPLEMENT_DYNCREATE(CMdiDemoView, CView)
BEGIN_MESSAGE_MAP(CMdiDemoView, CView)
// Standard printing commands
ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview)
END_MESSAGE_MAP()
// CMdiDemoView construction/destruction
CMdiDemoView::CMdiDemoView()
{
// TODO: add construction code here
}
CMdiDemoView::~CMdiDemoView()
{
}
BOOL CMdiDemoView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return CView::PreCreateWindow(cs);
}
// CMdiDemoView drawing
void CMdiDemoView::OnDraw(CDC* pDC)
{
CMdiDemoDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
// TODO: add draw code for native data here
pDC->TextOut(10, 10, _T("Hello, MDI!"));
}
// CMdiDemoView printing
BOOL CMdiDemoView::OnPreparePrinting(CPrintInfo* pInfo)
{
// default preparation
return DoPreparePrinting(pInfo);
}
void CMdiDemoView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add extra initialization before printing
}
void CMdiDemoView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add cleanup after printing
}
// CMdiDemoView diagnostics
#ifdef _DEBUG
void CMdiDemoView::AssertValid() const
{
CView::AssertValid();
}
void CMdiDemoView::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
CMdiDemoDoc* CMdiDemoView::GetDocument() const // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CMdiDemoDoc)));
return (CMdiDemoDoc*)m_pDocument;
}
#endif //_DEBUG
// CMdiDemoView message handlers
| 19.554455 | 78 | 0.711899 |
01417b6a4ebc01846c383ea9eb0e7fa8fbb47e23 | 396 | cpp | C++ | N0647-Palindromic-Substrings/solution1.cpp | loypt/leetcode | 4463aa17b0fb01ec6f865ea9766ccce1ab7a690a | [
"CC0-1.0"
] | null | null | null | N0647-Palindromic-Substrings/solution1.cpp | loypt/leetcode | 4463aa17b0fb01ec6f865ea9766ccce1ab7a690a | [
"CC0-1.0"
] | null | null | null | N0647-Palindromic-Substrings/solution1.cpp | loypt/leetcode | 4463aa17b0fb01ec6f865ea9766ccce1ab7a690a | [
"CC0-1.0"
] | 2 | 2022-01-25T05:31:31.000Z | 2022-02-26T07:22:23.000Z | class Solution {
public:
int countSubstrings(string s) {
int num = 0;
int n = s.size();
for(int i=0;i<n;i++)//遍历回文中心点
{
for(int j=0;j<=1;j++)//j=0,中心是一个点,j=1,中心是两个点
{
int l = i;
int r = i+j;
while(l>=0 && r<n && s[l--]==s[r++])num++;
}
}
return num;
}
};
| 22 | 58 | 0.356061 |
0149210ca73d9a9f64c0b3f739d097f86b5e5d1d | 706 | cpp | C++ | Fibonacci/Fibonacci.cpp | sounishnath003/CPP-for-beginner | d4755ab4ae098d63c9a0666d8eb4d152106d4a20 | [
"MIT"
] | 4 | 2020-05-14T04:41:04.000Z | 2021-06-13T06:42:03.000Z | Fibonacci/Fibonacci.cpp | sounishnath003/CPP-for-beginner | d4755ab4ae098d63c9a0666d8eb4d152106d4a20 | [
"MIT"
] | null | null | null | Fibonacci/Fibonacci.cpp | sounishnath003/CPP-for-beginner | d4755ab4ae098d63c9a0666d8eb4d152106d4a20 | [
"MIT"
] | null | null | null | #include<iostream>
#include<vector>
using namespace std ;
template<typename T>
void printVector(vector<T> n) {
for (auto &&i : n)
{
cout << i << " ";
}
cout << endl ;
}
class Fibonacci
{
private:
double series = 0;
vector<double> store;
public:
void getTheFibonacciUpto(int x) {
int a = 0, b = 1;
for (size_t i = 1; i <= x; i++)
{
store.push_back(series);
series = a + b;
a = b;
b = series;
}
printVector(store);
}
};
int main(int argc, char const *argv[])
{
Fibonacci obj ;
obj.getTheFibonacciUpto(20);
return 0;
}
| 17.219512 | 40 | 0.474504 |
0149e15d47dac4538dd3bdd786fc568e49e3f384 | 1,214 | cpp | C++ | 2018-2019_Term2/CSC3002-Programming_Paradigms/Course_Material/Week 04/05 Programs/CCType/TestCCType.cpp | Vito-Swift/CourseMaterials | f2799f004f4353b5f35226158c8fd9f71818810e | [
"MIT"
] | null | null | null | 2018-2019_Term2/CSC3002-Programming_Paradigms/Course_Material/Week 04/05 Programs/CCType/TestCCType.cpp | Vito-Swift/CourseMaterials | f2799f004f4353b5f35226158c8fd9f71818810e | [
"MIT"
] | null | null | null | 2018-2019_Term2/CSC3002-Programming_Paradigms/Course_Material/Week 04/05 Programs/CCType/TestCCType.cpp | Vito-Swift/CourseMaterials | f2799f004f4353b5f35226158c8fd9f71818810e | [
"MIT"
] | 2 | 2019-09-25T02:36:37.000Z | 2020-06-05T08:47:01.000Z | /*
* File: TestCCType.cpp
* --------------------
* This program tests the set-based implementation of the <cctype>
* interface.
*/
#include <iostream>
#include <string>
#include "cctype.h"
#include "simpio.h"
#include "console.h"
using namespace std;
int main() {
while (true) {
string str = getLine("Enter one or more characters: ");
if (str == "") break;
cout << boolalpha;
for (int i = 0; i < str.length(); i++) {
char ch = str[i];
cout << " isdigit('" << ch << "') -> " << isdigit(ch) << endl;
cout << " isxdigit('" << ch << "') -> " << isxdigit(ch) << endl;
cout << " islower('" << ch << "') -> " << islower(ch) << endl;
cout << " isupper('" << ch << "') -> " << isupper(ch) << endl;
cout << " isspace('" << ch << "') -> " << isspace(ch) << endl;
cout << " ispunct('" << ch << "') -> " << ispunct(ch) << endl;
cout << " isalpha('" << ch << "') -> " << isalpha(ch) << endl;
cout << " isalnum('" << ch << "') -> " << isalnum(ch) << endl;
cout << " isprint('" << ch << "') -> " << isprint(ch) << endl;
cout << endl;
}
}
return 0;
}
| 33.722222 | 74 | 0.432455 |
014c9bc06539884aed89195baa0fc6e530aafb94 | 1,943 | cpp | C++ | Graphs/KruskalMST.cpp | paras2411/Algorithms | dcb280d382fc3ee3dbaaf5f1ec2896aae2b05825 | [
"MIT"
] | 8 | 2020-09-15T17:54:12.000Z | 2022-01-20T04:04:27.000Z | Graphs/KruskalMST.cpp | paras2411/Algorithms | dcb280d382fc3ee3dbaaf5f1ec2896aae2b05825 | [
"MIT"
] | null | null | null | Graphs/KruskalMST.cpp | paras2411/Algorithms | dcb280d382fc3ee3dbaaf5f1ec2896aae2b05825 | [
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
// considering maximum no. of vertices to be 100000.
const int N = 1e5;
int parent[N];
// find the root(ancestor) of the vertex u and returns the no. of vertices in that path
int findpar(int *u){
int rank = 0;
while(*u != parent[*u]){
*u = parent[*u];
rank++;
}
return rank;
}
/*
Kruskal is the algrithm to find minimum spanning tree. It takes list
of sorted edges wrt to weight. Then iterate that list and add that
edge which do not form cycle with the added edges. For checking the
cycle we are using "Disjoint set Union" method.
Its time complexity is O(E log(E)). Space complexity is (V+E).
vector<pair<int, pair<int, int>>> edges -> list of edges with weights w {w, {u, v}}
n -> no. of vertices (V)
*/
void kruskal(vector<pair<int, pair<int, int>>> edges, int n){
// sorting that list of edges with weights
sort(edges.begin(), edges.end());
// assigning each vertices to be its parent
for(int i=0; i<n; i++){
parent[i] = i;
}
// cost -> sum of all the weights of the edges added to the MST
int cost = 0;
int edg_count = 0; // should be n-1 after iteration (Tree)
for(auto it = edges.begin(); it != edges.end() && edg_count < n-1; it++){
int weight = (*it).first;
pair<int, int> edge = (*it).second;
int u = edge.first, v = edge.second;
// find the root ancestor of the both vertex and its rank as well
int rank_u = findpar(&u);
int rank_v = findpar(&v);
// If root different then adding this edge will not form cycle.
if(u != v){
cost += weight;
edg_count += 1;
// making root ancestor of both vertex same.
if(rank_u < rank_v){
parent[u] = v;
}
else{
parent[v] = u;
}
}
}
}
| 26.256757 | 87 | 0.568194 |
014dc4cf9bbe003883e6a2bc834ec2fcc6548c06 | 1,712 | cpp | C++ | src/lcpeaks/integrator_lineTools.cpp | DanIverson/OpenVnmrJ | 0db324603dbd8f618a6a9526b9477a999c5a4cc3 | [
"Apache-2.0"
] | 32 | 2016-06-17T05:04:26.000Z | 2022-03-28T17:54:44.000Z | src/lcpeaks/integrator_lineTools.cpp | DanIverson/OpenVnmrJ | 0db324603dbd8f618a6a9526b9477a999c5a4cc3 | [
"Apache-2.0"
] | 128 | 2016-07-13T17:09:02.000Z | 2022-03-28T17:53:52.000Z | src/lcpeaks/integrator_lineTools.cpp | DanIverson/OpenVnmrJ | 0db324603dbd8f618a6a9526b9477a999c5a4cc3 | [
"Apache-2.0"
] | 102 | 2016-01-23T15:27:16.000Z | 2022-03-20T05:41:54.000Z | /*
* Varian,Inc. All Rights Reserved.
* This software contains proprietary and confidential
* information of Varian, Inc. and its contributors.
* Use, disclosure and reproduction is prohibited without
* prior consent.
*/
/* DISCLAIMER :
* ------------
*
* This is a beta version of the GALAXIE integration library.
* This code is under development and is provided for information purposes.
* The classes names and interfaces as well as the file names and
* organization is subject to changes. Moreover, this code has not been
* fully tested.
*
* For any bug report, comment or suggestion please send an email to
* gilles.orazi@varianinc.com
*
* Copyright Varian JMBS (2002)
*/
#include "common.h"
#include "integrator_lineTools.h"
#include "math.h"
#include <cassert>
//Looking for memory leaks
#ifdef __VISUAL_CPP__
#include "LeakWatcher.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#endif
TStraightLineTool::TStraightLineTool(INT_FLOAT Time1,
INT_FLOAT Value1,
INT_FLOAT Time2,
INT_FLOAT Value2)
{
assert(Time2 > Time1); // no vertical lines allowed
FTime1 = Time1 ;
FTime2 = Time2 ;
FValue1 = Value1 ;
FValue2 = Value2 ;
}
INT_FLOAT TStraightLineTool::ValueAtTime(INT_FLOAT t)
{
return FValue1 + (t - FTime1) / (FTime2 - FTime1) * (FValue2 - FValue1);
}
TExpLineTool::TExpLineTool(INT_FLOAT A,
INT_FLOAT B,
INT_FLOAT t0)
{
FA = A;
FB = B;
Ft0 = t0;
}
INT_FLOAT TExpLineTool::ValueAtTime(INT_FLOAT t)
{
INT_FLOAT result ;
try
{
result = Ft0 + FA * exp(FB * t) ;
}
catch (...)
{
result = Ft0;
}
return result ;
}
| 21.670886 | 76 | 0.674065 |
014e64b24cf4d1fe7cbcd9dd010345bd7347c848 | 1,219 | cpp | C++ | ir/src/brio/BrioMessage.cpp | wmarkow/arduino-sandbox | 2c5301aeee8811ff5f15f1edb61e313ecbcb0d5e | [
"MIT"
] | null | null | null | ir/src/brio/BrioMessage.cpp | wmarkow/arduino-sandbox | 2c5301aeee8811ff5f15f1edb61e313ecbcb0d5e | [
"MIT"
] | null | null | null | ir/src/brio/BrioMessage.cpp | wmarkow/arduino-sandbox | 2c5301aeee8811ff5f15f1edb61e313ecbcb0d5e | [
"MIT"
] | null | null | null | /*
* BrioMessage.cpp
*
* Created on: 09.05.2018
* Author: wmarkowski
*/
#include <Arduino.h>
#include "BrioMessage.h"
void brio_message_dump(BrioMessage* brioMessage)
{
switch (brioMessage->channel)
{
case BRIO_CHANNEL_A:
Serial.print(F("channel A, "));
break;
case BRIO_CHANNEL_B:
Serial.print(F("channel B, "));
break;
default:
Serial.print(F("channel "));
Serial.print(brioMessage->channel);
Serial.print(F(", "));
}
switch (brioMessage->command)
{
case BRIO_COMMAND_FAST_FORWARD:
Serial.println(F("cmd FFOR"));
break;
case BRIO_COMMAND_SLOW_FORWARD:
Serial.println(F("cmd SFOR"));
break;
case BRIO_COMMAND_STOP:
Serial.println(F("cmd STOP"));
break;
case BRIO_COMMAND_BACKWARD:
Serial.println(F("cmd BACK"));
break;
case BRIO_COMMAND_TOGGLE_LIGHT:
Serial.println(F("cmd T_LIGHT"));
break;
case BRIO_COMMAND_PLAY_SOUND:
Serial.println(F("cmd SOUND"));
break;
default:
Serial.print(F("cmd "));
Serial.println(brioMessage->command);
}
}
| 23.442308 | 48 | 0.5726 |
0151893c4ebd09de9dbcfadd024231e2e327b3a1 | 3,643 | cpp | C++ | src/prod/src/api/wrappers/ComProxyStorePostBackupHandler.cpp | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 2,542 | 2018-03-14T21:56:12.000Z | 2019-05-06T01:18:20.000Z | src/prod/src/api/wrappers/ComProxyStorePostBackupHandler.cpp | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 994 | 2019-05-07T02:39:30.000Z | 2022-03-31T13:23:04.000Z | src/prod/src/api/wrappers/ComProxyStorePostBackupHandler.cpp | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 300 | 2018-03-14T21:57:17.000Z | 2019-05-06T20:07:00.000Z | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
namespace Api
{
class ComProxyStorePostBackupHandler::PostBackupAsyncOperation
: public Common::ComProxyAsyncOperation
{
DENY_COPY(PostBackupAsyncOperation);
public:
PostBackupAsyncOperation(
__in IFabricStorePostBackupHandler & comImpl,
__in FABRIC_STORE_BACKUP_INFO const & info,
__in Common::AsyncCallback const & callback,
__in Common::AsyncOperationSPtr const & parent)
: Common::ComProxyAsyncOperation(callback, parent)
, comImpl_(comImpl)
, info_(info)
, status_(false)
{
}
static Common::ErrorCode End(Common::AsyncOperationSPtr const & operation, bool & status)
{
PostBackupAsyncOperation * casted = AsyncOperation::End<PostBackupAsyncOperation>(operation);
if (casted->Error.IsSuccess())
{
status = std::move(casted->status_);
}
return casted->Error;
}
virtual ~PostBackupAsyncOperation()
{
}
protected:
HRESULT BeginComAsyncOperation(IFabricAsyncOperationCallback * callback, IFabricAsyncOperationContext ** context)
{
HRESULT hr = comImpl_.BeginPostBackup(&info_, callback, context);
return hr;
}
HRESULT EndComAsyncOperation(IFabricAsyncOperationContext * context)
{
BOOLEAN userStatus = FALSE;
HRESULT hr = comImpl_.EndPostBackup(context, &userStatus);
status_ = SUCCEEDED(hr)
? userStatus ? true : false
: false;
return hr;
}
private:
IFabricStorePostBackupHandler & comImpl_;
FABRIC_STORE_BACKUP_INFO info_;
bool status_;
};
ComProxyStorePostBackupHandler::ComProxyStorePostBackupHandler(Common::ComPointer<IFabricStorePostBackupHandler > const & comImpl)
: ComponentRoot()
, IStorePostBackupHandler()
, comImpl_(comImpl)
{
}
ComProxyStorePostBackupHandler::~ComProxyStorePostBackupHandler()
{
}
Common::AsyncOperationSPtr ComProxyStorePostBackupHandler::BeginPostBackup(
__in FABRIC_STORE_BACKUP_INFO const & info,
__in Common::AsyncCallback const & callback,
__in Common::AsyncOperationSPtr const & parent)
{
// this should invoke the customer's COM method BeginPostBackup
// But how do we wrap the AsyncCallback and AsyncOperationSPtr into IFabricAsyncOperationCallback * and
// IFabricAsyncOperationContext **
// For this, we invoke a class derived from ComProxyAsyncOperation. This class contains two pure virtual
// methods BeginComAsyncOperation and EndComAsyncOperation which do the actual conversion.
auto operation = Common::AsyncOperation::CreateAndStart<PostBackupAsyncOperation>(
*comImpl_.GetRawPointer(),
info,
callback,
parent);
return operation;
}
Common::ErrorCode ComProxyStorePostBackupHandler::EndPostBackup(
__in Common::AsyncOperationSPtr const & operation,
__out bool & status)
{
auto error = PostBackupAsyncOperation::End(operation, status);
return error;
}
}
| 33.118182 | 134 | 0.620093 |
0152528c23cbebd0292482028545ec0aec888717 | 1,346 | cpp | C++ | liblineside/test/signalflashtests.cpp | freesurfer-rge/linesidecabinet | 8944c67fa7d340aa792e3a6e681113a4676bfbad | [
"MIT"
] | null | null | null | liblineside/test/signalflashtests.cpp | freesurfer-rge/linesidecabinet | 8944c67fa7d340aa792e3a6e681113a4676bfbad | [
"MIT"
] | 14 | 2019-11-17T14:46:25.000Z | 2021-03-10T02:48:40.000Z | liblineside/test/signalflashtests.cpp | freesurfer-rge/linesidecabinet | 8944c67fa7d340aa792e3a6e681113a4676bfbad | [
"MIT"
] | null | null | null | #include <boost/test/unit_test.hpp>
#include <boost/test/data/test_case.hpp>
#include <boost/test/data/monomorphic.hpp>
#include <sstream>
#include "lineside/signalflash.hpp"
char const* flashNames[] = { "Steady", "Flashing" };
Lineside::SignalFlash flashes[] = { Lineside::SignalFlash::Steady,
Lineside::SignalFlash::Flashing };
auto nameToFlashZip = boost::unit_test::data::make(flashNames)
^ boost::unit_test::data::make(flashes);
BOOST_AUTO_TEST_SUITE( SignalFlash )
BOOST_DATA_TEST_CASE( ToString, nameToFlashZip, name, flash )
{
BOOST_CHECK_EQUAL( name, Lineside::ToString(flash) );
}
BOOST_DATA_TEST_CASE( StreamInsertion, nameToFlashZip, name, flash )
{
std::stringstream res;
res << flash;
BOOST_CHECK_EQUAL( res.str(), name );
}
BOOST_DATA_TEST_CASE( Parse, nameToFlashZip, name, flash )
{
BOOST_CHECK_EQUAL( flash, Lineside::Parse<Lineside::SignalFlash>(name) );
}
BOOST_AUTO_TEST_CASE( BadParse )
{
const std::string badString = "SomeRandomString";
const std::string expected = "Could not parse 'SomeRandomString' to SignalFlash";
BOOST_CHECK_EXCEPTION( Lineside::Parse<Lineside::SignalFlash>(badString),
std::invalid_argument,
[=](const std::invalid_argument& ia) {
BOOST_CHECK_EQUAL( expected, ia.what() );
return expected == ia.what();
});
}
BOOST_AUTO_TEST_SUITE_END()
| 27.469388 | 83 | 0.730312 |
01542c10efe6ed2d057b98d9df5f63d29a5d3781 | 1,366 | cpp | C++ | luogu/3371_2.cpp | shorn1/OI-ICPC-Problems | 0c18b3297190a0e108c311c74d28351ebc70c3d1 | [
"MIT"
] | 1 | 2020-05-07T09:26:05.000Z | 2020-05-07T09:26:05.000Z | luogu/3371_2.cpp | shorn1/OI-ICPC-Problems | 0c18b3297190a0e108c311c74d28351ebc70c3d1 | [
"MIT"
] | null | null | null | luogu/3371_2.cpp | shorn1/OI-ICPC-Problems | 0c18b3297190a0e108c311c74d28351ebc70c3d1 | [
"MIT"
] | null | null | null | #include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<queue>
using namespace std;
const int M = 1111111;
struct Edge
{
int tow,nxt,dat;
};
Edge e[2 * M];
int n,m,s,sume = 0,dis[2 * M],vis[2 * M],hea[2 * M];
queue <int>q;
void add(int u, int v, int w)
{
sume++;
e[sume].nxt = hea[u];
hea[u] = sume;
e[sume].tow = v;
e[sume].dat = w;
}
void init()
{
for (int i = 0; i <= 2 * m + 1; i++)
{
e[i].dat = dis[i] = 2147483647;
}
memset(vis, 0, sizeof(vis));
}
void spfa(int s)
{
dis[s] = 0;
vis[s] = 1;
q.push(s);
while(!q.empty())
{
int x = q.front();
q.pop();
vis[x] = 0;
for(int now = hea[x];now;now = e[now].nxt)
{
int y = e[now].tow,z = e[now].dat;
if(dis[y] > dis[x] + z)
{
dis[y] = dis[x]+z;
if(!vis[y])
{
vis[y] = 1;
q.push(y);
}
}
}
}
}
void pans()
{
for(int i = 1;i <= n;i++)
printf("%d ", dis[i]);
}
int main()
{
scanf("%d%d%d",&n,&m,&s);
init();
for(int i=1;i<=m;i++)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
add(a,b,c);
//add(b,a,c);
}
spfa(s);
pans();
return 0;
}
| 16.658537 | 52 | 0.400439 |
01568fe4e820b402aff4f45d2fd5d36b0ffd1d9b | 1,849 | hh | C++ | include/introvirt/windows/libraries/ws2_32/types/WSABUF.hh | IntroVirt/IntroVirt | 917f735f3430d0855d8b59c814bea7669251901c | [
"Apache-2.0"
] | 23 | 2021-02-17T16:58:52.000Z | 2022-02-12T17:01:06.000Z | include/introvirt/windows/libraries/ws2_32/types/WSABUF.hh | IntroVirt/IntroVirt | 917f735f3430d0855d8b59c814bea7669251901c | [
"Apache-2.0"
] | 1 | 2021-04-01T22:41:32.000Z | 2021-09-24T14:14:17.000Z | include/introvirt/windows/libraries/ws2_32/types/WSABUF.hh | IntroVirt/IntroVirt | 917f735f3430d0855d8b59c814bea7669251901c | [
"Apache-2.0"
] | 4 | 2021-02-17T16:53:18.000Z | 2021-04-13T16:51:10.000Z | /*
* Copyright 2021 Assured Information Security, 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.
*/
#pragma once
#include <introvirt/core/memory/guest_ptr.hh>
#include <cstdint>
#include <memory>
namespace introvirt {
namespace windows {
namespace ws2_32 {
/**
* @brief
*
* @see https://docs.microsoft.com/en-us/windows/win32/api/ws2def/ns-ws2def-wsabuf
*/
class WSABUF {
public:
/**
* @brief Get the length of the buffer, in bytes
*/
virtual uint32_t len() const = 0;
/**
* @brief Set the length of the buffer, in bytes
*/
virtual void len(uint32_t len) = 0;
/**
* @brief Get the buffer
*/
virtual guest_ptr<const uint8_t[]> buf() const = 0;
virtual guest_ptr<uint8_t[]> buf() = 0;
/**
* @brief Set the buffer
*/
virtual void buf(const guest_ptr<uint8_t[]>& buf) = 0;
/**
* @brief Parse a WSABUF instance from the guest
*
* @param ptr The address of the instance
* @param x64 If the structure is 64-bit or not
* @return std::shared_ptr<WSABUF>
*/
static std::shared_ptr<WSABUF> make_shared(const guest_ptr<void>& ptr, bool x64);
/**
* @brief Get the size of the structure
*/
static size_t size(bool x64);
};
} // namespace ws2_32
} // namespace windows
} // namespace introvirt
| 25.328767 | 85 | 0.657112 |
0156b739a3e01a71a774048ffe0717ba2aa7ffef | 1,417 | cpp | C++ | others/fb/quixo4.cpp | st34-satoshi/quixo-cpp | 9d71c506bea91d8a12253d527958ac0c04d0327e | [
"MIT"
] | null | null | null | others/fb/quixo4.cpp | st34-satoshi/quixo-cpp | 9d71c506bea91d8a12253d527958ac0c04d0327e | [
"MIT"
] | null | null | null | others/fb/quixo4.cpp | st34-satoshi/quixo-cpp | 9d71c506bea91d8a12253d527958ac0c04d0327e | [
"MIT"
] | null | null | null | /*
Next player to play: X
Previous player: O
A board is a 16-tuple/list of 0,1,2
e.g.: (0,0,0,1, 1,2,0,0, 0,1,2,0, 2,1,2,1) means that the board is
...X
XO..
.XO.
OXOX
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
*/
#include <iostream>
#include "global4.h"
#include "state4.h"
#include <unordered_set>
void countReachable() {
std::unordered_set<ShortState> allStates;
std::unordered_set<ShortState> newStates;
std::unordered_set<ShortState> newNewStates;
State init(0);
ShortState init_ss = init.convert();
allStates.insert(init_ss);
newStates.insert(init_ss);
int i = 0;
while (not newStates.empty()) {
i++;
std::cout << i << " " << allStates.size() << " " << newStates.size() << std::endl;
newNewStates.clear();
for(auto ss : newStates) {
State s(ss);
ChildrenList cl = s.computeChildren();
for(int n=0; n<cl.nbChildren; ++n) {
ShortState ssc = cl.children[n].convert();
if (cl.children[n].checkLines() != 0) {
allStates.insert(ssc);
} else {
if (allStates.find(ssc) == allStates.end()) {
newNewStates.insert(ssc);
allStates.insert(ssc);
}
}
}
}
newStates = newNewStates;
}
std::cout << "There are " << allStates.size() << " reachable states" << std::endl;
return;
}
int main() {
countReachable();
return 0;
}
| 20.838235 | 86 | 0.573042 |
01594279291cd64d232ef617f493cb70ac094f93 | 7,036 | cpp | C++ | src/ZigBeeCommandLineProcessor.cpp | Suicyc1e/Sequoia | 7a31bde385673e5522373eb7a2ee33c4042c3b8d | [
"MIT"
] | null | null | null | src/ZigBeeCommandLineProcessor.cpp | Suicyc1e/Sequoia | 7a31bde385673e5522373eb7a2ee33c4042c3b8d | [
"MIT"
] | null | null | null | src/ZigBeeCommandLineProcessor.cpp | Suicyc1e/Sequoia | 7a31bde385673e5522373eb7a2ee33c4042c3b8d | [
"MIT"
] | null | null | null | #include <ZigBeeCommandLineProcessor.h>
#include <GlobalPresets.h>
int StringSplit(String sInput, char cDelim, String sParams[], int iMaxParams)
{
int iParamCount = 0;
int iPosDelim, iPosStart = 0;
do {
// Searching the delimiter using indexOf()
iPosDelim = sInput.indexOf(cDelim,iPosStart);
if (iPosDelim > (iPosStart+1)) {
// Adding a new parameter using substring()
sParams[iParamCount] = sInput.substring(iPosStart,iPosDelim-1);
iParamCount++;
// Checking the number of parameters
if (iParamCount >= iMaxParams) {
return (iParamCount);
}
iPosStart = iPosDelim + 1;
}
} while (iPosDelim >= 0);
if (iParamCount < iMaxParams) {
// Adding the last parameter as the end of the line
sParams[iParamCount] = sInput.substring(iPosStart);
iParamCount++;
}
return (iParamCount);
}
void ZigBeeCommandLineProcessor::ProcessIncomingData(String esp32Data)
{
Serial.println("ZigBee Message Data: " + esp32Data);
if (esp32Data.startsWith(_attributeMessagePrefix))
{
Serial.println("Message is ATTRIBUTE_CHANGE");
int attributeID = 0;
int attributeValue = 0;
String splitControl = _attributeMessagePrefix + "%d" + " " + "%d";
int n = sscanf(esp32Data.c_str(), splitControl.c_str(), &attributeID, &attributeValue);
if (n != 2)
{
Serial.println("WARNING! Sscanf didn't parse the message correctly!");
}
Serial.printf(" Attribute ID && Data: %d && %d \n", attributeID, attributeValue);
ZigBeeMessage_AttributeChanged message = ZigBeeMessage_AttributeChanged(attributeID, attributeValue, esp32Data);
_attributeChangedCallback(message);
}
else if (esp32Data.startsWith(_nwkSuccessMessagePrefix))
{
Serial.println("Message is NWK_SUCCESS");
int finalState = 0;
String splitControl = _nwkSuccessMessagePrefix + "%d";
int n = sscanf(esp32Data.c_str(), splitControl.c_str(), &finalState);
if (n != 1)
{
Serial.println("WARNING! Sscanf didn't parse the message correctly!");
}
Serial.printf(" Final State: %d \n", finalState);
ZigBeeMessage_NwkSuccess message = ZigBeeMessage_NwkSuccess(finalState, esp32Data);
_nwkStatusSuccededCallback(message);
}
else if (esp32Data.startsWith(_nwkFailedMessagePrefix))
{
Serial.println("Message is NWK_FAILED");
int finalState = 0;
String splitControl = _nwkFailedMessagePrefix + "%d";
int n = sscanf(esp32Data.c_str(), splitControl.c_str(), &finalState);
if (n != 1)
{
Serial.println("WARNING! Sscanf didn't parse the message correctly!");
}
Serial.printf(" Final State: %d \n", finalState);
ZigBeeMessage_NwkFailed message = ZigBeeMessage_NwkFailed(finalState, esp32Data);
_nwkStatusFailedCallback(message);
}
else
{
Serial.println("Message is UNKNOWN");
}
}
void ZigBeeCommandLineProcessor::ZigbeeCommandsReader(void *parameter)
{
ZigBeeCommandLineProcessor *processor = (ZigBeeCommandLineProcessor*) parameter;
while (1)
{
TIMERG0.wdt_wprotect=TIMG_WDT_WKEY_VALUE;
TIMERG0.wdt_feed=1;
TIMERG0.wdt_wprotect=0;
if (ZigBeePort.available())
{
String esp32Data = ZigBeePort.readStringUntil('\n');
processor->ProcessIncomingData(esp32Data);
}
// unsigned long thedelay;
// thedelay = micros() + 100;
// while (micros() < thedelay)
// {
// }
//Too short delay for music to play.
vTaskDelay(UART_COMMAND_LINE_TASK_DELAY_MS/portTICK_PERIOD_MS);
}
}
ZigBeeCommandLineProcessor::ZigBeeCommandLineProcessor( AttributeChangedCallback attrChangedCallback,
NwkStatusFailedCallback nwkFailedCallback,
NwkStatusSuccededCallback nwkOkCallback)
{
_attributeChangedCallback = attrChangedCallback;
_nwkStatusFailedCallback = nwkFailedCallback;
_nwkStatusSuccededCallback = nwkOkCallback;
//ExecuteStartUpProcedures();
}
void ZigBeeCommandLineProcessor::ExecuteStartUpProcedures()
{
//Init UART, ask ZigBee if it's ready, etc...
//ZigBee Console
ZigBeePort.begin(115200);
//DBG Message. Delete later.
ZigBeePort.println("ZigBee TEST UART Is Initialized.");
Serial.println("Starting Thread.");
xTaskCreate(
ZigbeeCommandsReader, /* Task function. */
"zigbeeCommandsReader", /* String with name of task. */
10000, /* Stack size in bytes. */
this, /* Parameter passed as input of the task */
1, /* Priority of the task. */
&ZigBeeCommandsReaderTask); /* Task handle. */
}
void ZigBeeCommandLineProcessor::CommandsTest()
{
ZigBeePort.println(ZigBeeCommand_TryToConnect(1).GetCommand());
ZigBeePort.println(ZigBeeCommand_SoundSaving(1).GetCommand());
ZigBeePort.println(ZigBeeCommand_SetSoundDetect(1).GetCommand());
ZigBeePort.println(ZigBeeCommand_SetAutoAnswer(1).GetCommand());
ZigBeePort.println(ZigBeeCommand_PhotoSaving(1).GetCommand());
ZigBeePort.println(ZigBeeCommand_MicrophoneTriggered(1).GetCommand());
ZigBeePort.println(ZigBeeCommand_ButtonTriggered(1).GetCommand());
ZigBeePort.println(ZigBeeCommand_BoxVibrationAlarmTriggered(1).GetCommand());
ZigBeePort.println(ZigBeeCommand_AdditionalSensorMapperState(19).GetCommand());
ZigBeePort.println(ZigBeeCommand_SetPlantCareDeviceEnable(1).GetCommand());
ZigBeePort.println(ZigBeeCommand_SetPlantCareFunctionalMode(1).GetCommand());
ZigBeePort.println(ZigBeeCommand_SetPlantCareWaterValvesMapper(1).GetCommand());
ZigBeePort.println(ZigBeeCommand_SetPlantCareSoilHumidityMapper(1).GetCommand());
ZigBeePort.println(ZigBeeCommand_SetPlantCareLowerPlantMapper(1).GetCommand());
ZigBeePort.println(ZigBeeCommand_SetPlantCareMiddlePlantMapper(1).GetCommand());
ZigBeePort.println(ZigBeeCommand_SetPlantCareUpperPlantMapper(1).GetCommand());
ZigBeePort.println(ZigBeeCommand_SetPlantCareNoWaterAlarm(1).GetCommand());
}
HardwareSerial ZigBeeCommandLineProcessor::ZigBeePort = Serial2;
TaskHandle_t ZigBeeCommandLineProcessor::ZigBeeCommandsReaderTask = NULL; | 38.032432 | 124 | 0.622513 |
015b2fc1bb7a3b4abc8ca03c4369020f5e67bf05 | 1,428 | cc | C++ | src/auth.cc | thejk/stuff | 67362896a37742e880025b9c85c4fe49d690ba02 | [
"BSD-3-Clause"
] | null | null | null | src/auth.cc | thejk/stuff | 67362896a37742e880025b9c85c4fe49d690ba02 | [
"BSD-3-Clause"
] | null | null | null | src/auth.cc | thejk/stuff | 67362896a37742e880025b9c85c4fe49d690ba02 | [
"BSD-3-Clause"
] | null | null | null | #include "common.hh"
#include "auth.hh"
#include "base64.hh"
#include "cgi.hh"
#include "http.hh"
#include "strutils.hh"
namespace stuff {
bool Auth::auth(CGI* cgi, const std::string& realm, const std::string& passwd,
std::string* user) {
auto auth = cgi->http_auth();
auto pos = auth.find(' ');
if (pos != std::string::npos) {
if (ascii_tolower(auth.substr(0, pos)) == "basic") {
std::string tmp;
if (Base64::decode(auth.substr(pos + 1), &tmp)) {
pos = tmp.find(':');
if (pos != std::string::npos) {
if (tmp.substr(pos + 1) == passwd) {
if (user) user->assign(tmp.substr(0, pos));
return true;
}
}
}
}
}
std::map<std::string, std::string> headers;
std::string tmp = realm;
for (auto it = tmp.begin(); it != tmp.end(); ++it) {
if (!((*it >= 'a' && *it <= 'z') ||
(*it >= 'A' && *it <= 'Z') ||
(*it >= '0' && *it <= '9') ||
*it == '-' || *it == '_' || *it == '.' || *it == ' ')) {
*it = '.';
}
}
headers.insert(std::make_pair("WWW-Authenticate",
"Basic realm=\"" + tmp + "\""));
Http::response(401, headers, "Authentication needed");
return false;
}
} // namespace stuff
| 30.382979 | 78 | 0.429272 |
015d23c359ee83b5f55b673013ed6cbdceae9f3f | 3,042 | hpp | C++ | IO/src/jpg/include/jpg.hpp | tlalexander/stitchEm | cdff821ad2c500703e6cb237ec61139fce7bf11c | [
"MIT"
] | 182 | 2019-04-19T12:38:30.000Z | 2022-03-20T16:48:20.000Z | IO/src/jpg/include/jpg.hpp | tlalexander/stitchEm | cdff821ad2c500703e6cb237ec61139fce7bf11c | [
"MIT"
] | 107 | 2019-04-23T10:49:35.000Z | 2022-03-02T18:12:28.000Z | IO/src/jpg/include/jpg.hpp | tlalexander/stitchEm | cdff821ad2c500703e6cb237ec61139fce7bf11c | [
"MIT"
] | 59 | 2019-06-04T11:27:25.000Z | 2022-03-17T23:49:49.000Z | // Copyright (c) 2012-2017 VideoStitch SAS
// Copyright (c) 2018 stitchEm
#pragma once
#include "io.hpp"
#include "libvideostitch/logging.hpp"
#include <fstream>
#include <ostream>
#include <vector>
#include <setjmp.h>
#include <jpeglib.h>
namespace VideoStitch {
namespace Input {
void my_output_message(j_common_ptr cinfo) {
char buffer[JMSG_LENGTH_MAX];
/* Create the message */
(*cinfo->err->format_message)(cinfo, buffer);
/* Send it to stderr, adding a newline */
Logger::get(Logger::Error) << buffer << std::endl;
}
class JPGReader {
public:
JPGReader(const char* filename, VideoStitch::ThreadSafeOstream* err = NULL) : hf(NULL), width(0), height(0) {
hf = VideoStitch::Io::openFile(filename, "rb");
if (!hf) {
if (err) {
*err << "Cannot open file '" << filename << "' for reading." << std::endl;
}
} else {
readHeader();
}
}
~JPGReader() {
if (hf) {
if (cinfo.output_scanline) {
// otherwise libjpeg crashes - see VSA-1326
jpeg_finish_decompress(&cinfo);
}
jpeg_destroy_decompress(&cinfo);
fclose(hf);
}
}
unsigned getWidth() const { return width; }
unsigned getHeight() const { return height; }
bool ok() const { return hf != NULL && width != 0 && height != 0; }
/**
* Fill in the given buffer with the next row (RGBRGBRGB).
* @data must be large enough to hold one row.
*/
bool getNextRow(unsigned char* data) {
JSAMPROW rowArray[1];
rowArray[0] = data;
return (cinfo.output_scanline < cinfo.output_height) && jpeg_read_scanlines(&cinfo, rowArray, 1);
}
private:
struct my_error_mgr {
struct jpeg_error_mgr pub; /* "public" fields */
jmp_buf setjmp_buffer; /* for return to caller */
};
typedef struct my_error_mgr* my_error_ptr;
/*
* Here's the routine that will replace the standard error_exit method:
*/
static void my_error_exit(j_common_ptr cinfo) {
/* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
my_error_ptr myerr = (my_error_ptr)cinfo->err;
/* Always display the message. */
/* We could postpone this until after returning, if we chose. */
(*cinfo->err->output_message)(cinfo);
/* Return control to the setjmp point */
longjmp(myerr->setjmp_buffer, 1);
}
void readHeader() {
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = my_error_exit;
jerr.pub.output_message = my_output_message;
/* Establish the setjmp return context for my_error_exit to use. */
if (setjmp(jerr.setjmp_buffer)) {
return;
}
jpeg_create_decompress(&cinfo);
jpeg_stdio_src(&cinfo, hf);
jpeg_read_header(&cinfo, TRUE);
width = cinfo.image_width;
height = cinfo.image_height;
jpeg_start_decompress(&cinfo);
// FIXME: make sure that we have RGB data
}
private:
FILE* hf;
unsigned width;
unsigned height;
struct jpeg_decompress_struct cinfo;
struct my_error_mgr jerr;
};
} // namespace Input
} // namespace VideoStitch
| 25.35 | 111 | 0.657462 |
015de0eea16ec62ebb203ca7b900d77686faa7cf | 2,037 | cc | C++ | patchpanel/mcastd/main.cc | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 4 | 2020-07-24T06:54:16.000Z | 2021-06-16T17:13:53.000Z | patchpanel/mcastd/main.cc | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 1 | 2021-04-02T17:35:07.000Z | 2021-04-02T17:35:07.000Z | patchpanel/mcastd/main.cc | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 1 | 2020-11-04T22:31:45.000Z | 2020-11-04T22:31:45.000Z | // Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <base/bind.h>
#include <base/command_line.h>
#include <base/files/scoped_file.h>
#include <base/macros.h>
#include <brillo/daemons/daemon.h>
#include "patchpanel/multicast_forwarder.h"
// Stand-alone daemon to proxy mDNS and SSDP packets between a pair of
// interfaces. Usage: mcastd $physical_ifname $guest_ifname
int main(int argc, char* argv[]) {
base::CommandLine::Init(argc, argv);
base::CommandLine* cl = base::CommandLine::ForCurrentProcess();
base::CommandLine::StringVector args = cl->GetArgs();
if (args.size() < 2) {
LOG(ERROR) << "Usage: " << cl->GetProgram().BaseName().value()
<< " [physical interface name] [guest interface name]";
return EXIT_FAILURE;
}
brillo::Daemon daemon;
auto mdns_fwd = std::make_unique<patchpanel::MulticastForwarder>(
args[0], patchpanel::kMdnsMcastAddress, patchpanel::kMdnsMcastAddress6,
patchpanel::kMdnsPort);
auto ssdp_fwd = std::make_unique<patchpanel::MulticastForwarder>(
args[0], patchpanel::kSsdpMcastAddress, patchpanel::kSsdpMcastAddress6,
patchpanel::kSsdpPort);
// Crostini depends on another daemon (LXD) creating the guest bridge
// interface. This can take a few seconds, so retry if necessary.
bool added_mdns = false, added_ssdp = false;
for (int i = 0; i < 10; i++) {
added_mdns = added_mdns || mdns_fwd->AddGuest(args[1]);
added_ssdp = added_ssdp || ssdp_fwd->AddGuest(args[1]);
if (added_mdns && added_ssdp)
break;
usleep(1000 * 1000 /* 1 second */);
}
if (!added_mdns)
LOG(ERROR) << "mDNS forwarder could not be started on " << args[0]
<< " and " << args[1];
if (!added_ssdp)
LOG(ERROR) << "SSDP forwarder could not be started on " << args[0]
<< " and " << args[1];
if (!added_mdns || !added_ssdp)
return EXIT_FAILURE;
return daemon.Run();
}
| 36.375 | 77 | 0.67403 |
015ea70b359981eae5d6213f851d444c511c4bf3 | 2,546 | hpp | C++ | cmdstan/stan/src/stan/lang/ast/fun/var_decl_dims_vis_def.hpp | yizhang-cae/torsten | dc82080ca032325040844cbabe81c9a2b5e046f9 | [
"BSD-3-Clause"
] | 1 | 2019-07-05T01:40:40.000Z | 2019-07-05T01:40:40.000Z | cmdstan/stan/src/stan/lang/ast/fun/var_decl_dims_vis_def.hpp | yizhang-cae/torsten | dc82080ca032325040844cbabe81c9a2b5e046f9 | [
"BSD-3-Clause"
] | null | null | null | cmdstan/stan/src/stan/lang/ast/fun/var_decl_dims_vis_def.hpp | yizhang-cae/torsten | dc82080ca032325040844cbabe81c9a2b5e046f9 | [
"BSD-3-Clause"
] | 1 | 2018-08-28T12:09:08.000Z | 2018-08-28T12:09:08.000Z | #ifndef STAN_LANG_AST_FUN_VAR_DECL_DIMS_VIS_DEF_HPP
#define STAN_LANG_AST_FUN_VAR_DECL_DIMS_VIS_DEF_HPP
#include <stan/lang/ast.hpp>
#include <vector>
namespace stan {
namespace lang {
var_decl_dims_vis::var_decl_dims_vis() { }
std::vector<expression> var_decl_dims_vis::operator()(const nil& /* x */)
const {
return std::vector<expression>(); // should not be called
}
std::vector<expression> var_decl_dims_vis::operator()(const int_var_decl& x)
const {
return x.dims_;
}
std::vector<expression> var_decl_dims_vis::operator()(
const double_var_decl& x)
const {
return x.dims_;
}
std::vector<expression> var_decl_dims_vis::operator()(
const vector_var_decl& x)
const {
return x.dims_;
}
std::vector<expression> var_decl_dims_vis::operator()(
const row_vector_var_decl& x) const {
return x.dims_;
}
std::vector<expression> var_decl_dims_vis::operator()(
const matrix_var_decl& x)
const {
return x.dims_;
}
std::vector<expression> var_decl_dims_vis::operator()(
const unit_vector_var_decl& x) const {
return x.dims_;
}
std::vector<expression> var_decl_dims_vis::operator()(
const simplex_var_decl& x) const {
return x.dims_;
}
std::vector<expression> var_decl_dims_vis::operator()(
const ordered_var_decl& x) const {
return x.dims_;
}
std::vector<expression> var_decl_dims_vis::operator()(
const positive_ordered_var_decl& x) const {
return x.dims_;
}
std::vector<expression> var_decl_dims_vis::operator()(
const cholesky_factor_var_decl& x) const {
return x.dims_;
}
std::vector<expression> var_decl_dims_vis::operator()(
const cholesky_corr_var_decl& x) const {
return x.dims_;
}
std::vector<expression> var_decl_dims_vis::operator()(
const cov_matrix_var_decl& x) const {
return x.dims_;
}
std::vector<expression> var_decl_dims_vis::operator()(
const corr_matrix_var_decl& x) const {
return x.dims_;
}
}
}
#endif
| 28.931818 | 80 | 0.552239 |
015f284d8abe647c16ca54578d7e48d01427cd6e | 3,698 | cpp | C++ | src/chartwork/ColorPalette.cpp | nazhor/chartwork | 20cb8df257bec39153ea408305640274c9e09d4c | [
"MIT"
] | 20 | 2018-08-29T07:33:21.000Z | 2022-03-12T05:05:54.000Z | src/chartwork/ColorPalette.cpp | nazhor/chartwork | 20cb8df257bec39153ea408305640274c9e09d4c | [
"MIT"
] | 1 | 2020-10-27T15:04:46.000Z | 2020-10-27T15:04:46.000Z | src/chartwork/ColorPalette.cpp | nazhor/chartwork | 20cb8df257bec39153ea408305640274c9e09d4c | [
"MIT"
] | 7 | 2015-07-09T20:38:28.000Z | 2021-09-27T06:38:11.000Z | #include <chartwork/ColorPalette.h>
#include <chartwork/Design.h>
namespace chartwork
{
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// ColorPalette
//
////////////////////////////////////////////////////////////////////////////////////////////////////
ColorPalette::ColorPalette()
: m_colors(std::shared_ptr<QList<QColor>>(new QList<QColor>(
{
design::blue,
design::orange,
design::green,
design::purple,
design::red,
design::yellow,
design::brown,
design::gray
})))
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const QColor &ColorPalette::color0() const
{
return (*m_colors)[0];
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ColorPalette::setColor0(const QColor &color0)
{
(*m_colors)[0] = color0;
handleColorUpdate();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const QColor &ColorPalette::color1() const
{
return (*m_colors)[1];
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ColorPalette::setColor1(const QColor &color1)
{
(*m_colors)[1] = color1;
handleColorUpdate();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const QColor &ColorPalette::color2() const
{
return (*m_colors)[2];
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ColorPalette::setColor2(const QColor &color2)
{
(*m_colors)[2] = color2;
handleColorUpdate();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const QColor &ColorPalette::color3() const
{
return (*m_colors)[3];
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ColorPalette::setColor3(const QColor &color3)
{
(*m_colors)[3] = color3;
handleColorUpdate();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const QColor &ColorPalette::color4() const
{
return (*m_colors)[4];
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ColorPalette::setColor4(const QColor &color4)
{
(*m_colors)[4] = color4;
handleColorUpdate();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const QColor &ColorPalette::color5() const
{
return (*m_colors)[5];
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ColorPalette::setColor5(const QColor &color5)
{
(*m_colors)[5] = color5;
handleColorUpdate();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const QColor &ColorPalette::color6() const
{
return (*m_colors)[6];
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ColorPalette::setColor6(const QColor &color6)
{
(*m_colors)[6] = color6;
handleColorUpdate();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
const QColor &ColorPalette::color7() const
{
return (*m_colors)[7];
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void ColorPalette::setColor7(const QColor &color7)
{
(*m_colors)[7] = color7;
handleColorUpdate();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
}
| 24.328947 | 100 | 0.330719 |
015f8fbd13144338c56420d36b5dfb1cc578986c | 1,827 | hpp | C++ | header/deps/filehelp.hpp | jonathanmarp/tfsound | 18942c35f1d3f4d335670b7d381f8a75b6a7e465 | [
"MIT"
] | 2 | 2021-06-05T10:15:53.000Z | 2021-06-06T09:51:19.000Z | header/deps/filehelp.hpp | jonathanmarp/tfsound | 18942c35f1d3f4d335670b7d381f8a75b6a7e465 | [
"MIT"
] | null | null | null | header/deps/filehelp.hpp | jonathanmarp/tfsound | 18942c35f1d3f4d335670b7d381f8a75b6a7e465 | [
"MIT"
] | 1 | 2021-06-08T05:56:35.000Z | 2021-06-08T05:56:35.000Z | // MIT License
// Copyright (c) 2021 laferenorg
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#ifndef _FILESHELP_HPP
#define _FILESHELP_HPP
/* Library C++ */
#include <ios>
#include <fstream>
// class FILESHELP
class FILESHELP {
private:
// variable settings in here
std::string namefile; // variable namefile
public:
// function constructor for fill variable FILESHELP
FILESHELP(const char* nameFile);
public:
// function open and close file
// function for open file
void F_openFile();
// function for close file
void F_closeFile();
public:
// return refrencf fstream variable
std::fstream& getVarFile();
public:
// function for check file its exist
bool itsExist();
public:
// function for get all string file
std::string getFile();
};
#endif // _FILESHELP_HPP | 33.218182 | 81 | 0.746579 |
01635e6161a725aca5e9748a3bdc8945400a2a2f | 6,958 | cxx | C++ | 3rd/fltk/src/win32/list_fonts.cxx | MarioHenze/cgv | bacb2d270b1eecbea1e933b8caad8d7e11d807c2 | [
"BSD-3-Clause"
] | 11 | 2017-09-30T12:21:55.000Z | 2021-04-29T21:31:57.000Z | 3rd/fltk/src/win32/list_fonts.cxx | MarioHenze/cgv | bacb2d270b1eecbea1e933b8caad8d7e11d807c2 | [
"BSD-3-Clause"
] | 2 | 2017-07-11T11:20:08.000Z | 2018-03-27T12:09:02.000Z | 3rd/fltk/src/win32/list_fonts.cxx | MarioHenze/cgv | bacb2d270b1eecbea1e933b8caad8d7e11d807c2 | [
"BSD-3-Clause"
] | 24 | 2018-03-27T11:46:16.000Z | 2021-05-01T20:28:34.000Z | //
// "$Id: list_fonts.cxx 5958 2007-10-17 20:21:38Z spitzak $"
//
// _WIN32 font utilities for the Fast Light Tool Kit (FLTK).
//
// Copyright 1998-2006 by Bill Spitzak and others.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 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
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA.
//
// Please report all bugs and problems to "fltk-bugs@fltk.org".
//
#include <fltk/events.h>
#include <fltk/utf.h>
#include <fltk/x.h>
#include <ctype.h>
#include <wchar.h>
#include <string.h>
#include <stdlib.h>
#include <config.h>
using namespace fltk;
extern int has_unicode();
int Font::encodings(const char**& arrayp) {
// CET - FIXME - What about this encoding stuff?
// WAS: we need some way to find out what charsets are supported
// and turn these into ISO encoding names, and return this list.
// This is a poor simulation:
static const char* simulation[] = {"iso10646-1", 0};
arrayp = simulation;
return 1;
}
////////////////////////////////////////////////////////////////
// List sizes:
static int nbSize;
//static int cyPerInch;
#define MAX_SIZES 16
static int sizes[MAX_SIZES];
static int CALLBACK EnumSizeCb(CONST LOGFONTW* lpelf,
CONST TEXTMETRICW* lpntm,
DWORD fontType,
LPARAM p)
{
if ((fontType & RASTER_FONTTYPE) == 0) {
// Scalable font
sizes[0] = 0;
nbSize = 1;
return 0;
}
int add = lpntm->tmHeight - lpntm->tmInternalLeading;
//add = MulDiv(add, 72, cyPerInch); // seems to be correct before this
int start = 0;
while ((start < nbSize) && (sizes[start] < add)) start++;
if ((start < nbSize) && (sizes[start] == add)) return (1);
for (int i=nbSize; i>start; i--) sizes[i] = sizes[i - 1];
sizes[start] = add;
nbSize++;
// Stop enum if buffer overflow
return (nbSize < MAX_SIZES);
}
int Font::sizes(int*& sizep) {
nbSize = 0;
HDC dc = getDC();
//cyPerInch = GetDeviceCaps(dc, LOGPIXELSY);
//if (cyPerInch < 1) cyPerInch = 1;
if (has_unicode()) {
wchar_t ucs[1024];
utf8towc(name_, strlen(name_), ucs, 1024);
#if defined(__BORLANDC__) || defined(__DMC__)
EnumFontFamiliesW(dc, ucs, (FONTENUMPROCA)EnumSizeCb, 0);
#else
EnumFontFamiliesW(dc, ucs, EnumSizeCb, 0);
#endif
} else {
EnumFontFamiliesA(dc, name_, (FONTENUMPROCA)EnumSizeCb, 0);
}
sizep = ::sizes;
return nbSize;
}
////////////////////////////////////////////////////////////////
// list fonts:
extern "C" {
static int sort_function(const void *aa, const void *bb) {
fltk::Font* a = *(fltk::Font**)aa;
fltk::Font* b = *(fltk::Font**)bb;
int ret = stricmp(a->name_, b->name_); if (ret) return ret;
return a->attributes_ - b->attributes_;
}}
extern Font* fl_make_font(const char* name, int attrib);
static Font** font_array = 0;
static int num_fonts = 0;
static int array_size = 0;
static int CALLBACK enumcbW(CONST LOGFONTW* lplf,
CONST TEXTMETRICW* lpntm,
DWORD fontType,
LPARAM p)
{
// we need to do something about different encodings of the same font
// in order to match X! I can't tell if each different encoding is
// returned sepeartely or not. This is what fltk 1.0 did:
if (lplf->lfCharSet != ANSI_CHARSET) return 1;
const wchar_t *name = lplf->lfFaceName;
//const char *name = (const char*)(((ENUMLOGFONT *)lplf)->elfFullName);
char buffer[1024];
utf8fromwc(buffer, 1024, name, wcslen(name));
// ignore mystery garbage font names:
if (buffer[0] == '@') return 1;
if (num_fonts >= array_size) {
array_size = array_size ? 2*array_size : 128;
font_array = (Font**)realloc(font_array, array_size*sizeof(Font*));
}
int attrib = 0;
// if (lplf->lfWeight > 400 || strstr(name, " Bold") == name+strlen(name)-5)
// attrib = BOLD;
font_array[num_fonts++] = fl_make_font(buffer, attrib);
return 1;
}
static int CALLBACK enumcbA(CONST LOGFONT* lplf,
CONST TEXTMETRIC* lpntm,
DWORD fontType,
LPARAM p)
{
// we need to do something about different encodings of the same font
// in order to match X! I can't tell if each different encoding is
// returned sepeartely or not. This is what fltk 1.0 did:
//if (lplf->lfCharSet != ANSI_CHARSET) return 1;
const char *name = lplf->lfFaceName;
if (num_fonts >= array_size) {
array_size = array_size ? 2*array_size : 128;
font_array = (Font**)realloc(font_array, array_size*sizeof(Font*));
}
int attrib = 0;
font_array[num_fonts++] = fl_make_font(name, attrib);
return 1;
}
int fltk::list_fonts(Font**& arrayp) {
if (font_array) {arrayp = font_array; return num_fonts;}
HDC dc = getDC();
if (has_unicode()) {
LOGFONTW lf;
memset(&lf, 0, sizeof(lf));
lf.lfCharSet = DEFAULT_CHARSET;
EnumFontFamiliesExW(dc, &lf, (FONTENUMPROCW)enumcbW, 0, 0);
} else {
LOGFONT lf;
memset(&lf, 0, sizeof(lf));
lf.lfCharSet = DEFAULT_CHARSET;
EnumFontFamiliesExA(dc, &lf, (FONTENUMPROCA)enumcbA, 0, 0);
}
ReleaseDC(0, dc);
qsort(font_array, num_fonts, sizeof(*font_array), sort_function);
arrayp = font_array;
return num_fonts;
}
////////////////////////////////////////////////////////////////
// This function apparently is needed to translate some font names
// stored in setup files to the actual name of a font. Currently
// font(name) calls this.
#if defined(WIN32) && !defined(__CYGWIN__)
static const char* GetFontSubstitutes(const char* name,int& len)
{
static char subst_name[1024]; //used BUFLEN from bool fltk_theme()
if ( strstr(name,"MS Shell Dlg") || strstr(name,"Helv") ||
strstr(name,"Tms Rmn")) {
DWORD type = REG_SZ;
LONG err;
HKEY key;
char truncname[1024];
strncpy(truncname, name, len);
truncname[len] = 0;
err = RegOpenKey(
HKEY_LOCAL_MACHINE,
"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\FontSubstitutes",
&key );
if (err == ERROR_SUCCESS) {
DWORD L=1024;
err = RegQueryValueEx( key, truncname, 0L, &type, (BYTE*)
subst_name, &L);
RegCloseKey(key);
if ( err == ERROR_SUCCESS ) {
len = L;
return subst_name;
}
}
}
return name;
}
#endif
//
// End of "$Id: list_fonts.cxx 5958 2007-10-17 20:21:38Z spitzak $"
//
| 29.991379 | 79 | 0.632078 |
016871b7df9e584799df839cda630bd6279531cd | 636 | hpp | C++ | Plutonium/Include/pu/overlay/Toast.hpp | Falki14/Plutonium | e39894f87b57695d4288052979e23d4115932697 | [
"MIT"
] | null | null | null | Plutonium/Include/pu/overlay/Toast.hpp | Falki14/Plutonium | e39894f87b57695d4288052979e23d4115932697 | [
"MIT"
] | null | null | null | Plutonium/Include/pu/overlay/Toast.hpp | Falki14/Plutonium | e39894f87b57695d4288052979e23d4115932697 | [
"MIT"
] | null | null | null |
/*
Plutonium library
@file Overlay.hpp
@brief TODO...
@author XorTroll
@copyright Plutonium project - an easy-to-use UI framework for Nintendo Switch homebrew
*/
#pragma once
#include <pu/overlay/Overlay.hpp>
namespace pu::overlay
{
class Toast : public Overlay
{
public:
Toast(std::string Text, u32 FontSize, draw::Color TextColor, draw::Color BaseColor);
void SetText(std::string Text);
void OnPreRender(render::Renderer *Drawer);
void OnPostRender(render::Renderer *Drawer);
private:
pu::element::TextBlock *text;
};
} | 21.931034 | 96 | 0.624214 |
6c666547fa894847a7ed3292dc3eaf8afea127da | 3,324 | cpp | C++ | kast.cpp | martinjvickers/alfsc_rewrite | a4f265fa7d30d8b98d8e5df3f0a223b0cc5a31f0 | [
"MIT"
] | null | null | null | kast.cpp | martinjvickers/alfsc_rewrite | a4f265fa7d30d8b98d8e5df3f0a223b0cc5a31f0 | [
"MIT"
] | 13 | 2017-03-08T10:05:48.000Z | 2017-03-09T12:32:31.000Z | kast.cpp | martinjvickers/alfsc_rewrite | a4f265fa7d30d8b98d8e5df3f0a223b0cc5a31f0 | [
"MIT"
] | null | null | null | /*
KAST - Kmer Alignment-free Search Tool
Version 0.0.34
Written by Dr. Martin Vickers (martin.vickers@jic.ac.uk)
*/
#include <iostream>
#include <seqan/sequence.h>
#include <seqan/stream.h>
#include <seqan/file.h>
#include <seqan/arg_parse.h>
#include <seqan/seq_io.h>
#include <math.h>
#include <string>
#include <thread>
#include <seqan/reduced_aminoacid.h>
#include "common.h"
#include "utils.h"
#include "pairwise.h"
#include "search.h"
using namespace seqan;
using namespace std;
int main(int argc, char const ** argv)
{
// parse our options
ModifyStringOptions options;
ArgumentParser::ParseResult res = parseCommandLine(options, argc, argv);
if (res != ArgumentParser::PARSE_OK)
return res == ArgumentParser::PARSE_ERROR;
// parse the mask so we know the kmer size
options.effectiveLength = options.klen;
if(parseMask(options, options.effectiveLength) == 1)
return 1;
// Running in pairwise mode
if(options.pairwiseFileName != NULL && options.type != "all" && options.type != "new")
{
if(options.sequenceType == "aa")
{
pairwise_matrix(options, AminoAcid());
}
else if(options.sequenceType == "raa")
{
pairwise_matrix(options, ReducedAminoAcidMurphy10());
}
else if(options.sequenceType == "dna")
{
pairwise_matrix(options, Dna5());
}
else
{
// there is no other mode
cerr << "Error: mode not found - " << options.sequenceType << endl;
return 1;
}
}
// Running in pairwise all mode
else if(options.pairwiseFileName != NULL && options.type == "all")
{
if(options.sequenceType == "aa")
{
pairwise_all_matrix(options, AminoAcid());
}
else if(options.sequenceType == "raa")
{
pairwise_all_matrix(options, ReducedAminoAcidMurphy10());
}
else if(options.sequenceType == "dna")
{
pairwise_all_matrix(options, Dna5());
}
else
{
// there is no other mode
cerr << "Error: mode not found - " << options.sequenceType << endl;
return 1;
}
}
// Running in interleaved mode
else if(options.interleavedFileName != NULL)
{
if(options.sequenceType == "aa")
{
interleaved(options, AminoAcid());
}
else if(options.sequenceType == "raa")
{
interleaved(options, ReducedAminoAcidMurphy10());
}
else if(options.sequenceType == "dna")
{
interleaved(options, Dna5());
}
else
{
// there is no other mode
cerr << "Error: mode not found - " << options.sequenceType << endl;
return 1;
}
}
else if (options.referenceFileName != NULL && options.queryFileName != NULL)
{
if(options.sequenceType == "aa")
{
query_ref_search(options, AminoAcid());
}
else if(options.sequenceType == "raa")
{
query_ref_search(options, ReducedAminoAcidMurphy10());
}
else if(options.sequenceType == "dna")
{
query_ref_search(options, Dna5());
}
else
{
// there is no other mode
cerr << "Error: mode not found - " << options.sequenceType << endl;
return 1;
}
}
return 0;
}
| 25.767442 | 89 | 0.588748 |
6c6a6a72bd1bbca0811508f4aae583f599f4fbec | 3,057 | cpp | C++ | demo/demo.cpp | dadocolussi/gdc-nanomap | 30ceeed508679a24d3133081a321d40ffec30cb2 | [
"MIT"
] | 2 | 2017-05-31T03:19:25.000Z | 2019-12-27T14:52:05.000Z | demo/demo.cpp | dadocolussi/gdc-nanomap | 30ceeed508679a24d3133081a321d40ffec30cb2 | [
"MIT"
] | null | null | null | demo/demo.cpp | dadocolussi/gdc-nanomap | 30ceeed508679a24d3133081a321d40ffec30cb2 | [
"MIT"
] | null | null | null | //
// Copyright (c) 2016 Dado Colussi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <vector>
#include <chrono>
#include <unordered_map>
#include <gdc/nanomap.hpp>
typedef std::unordered_map<int, int> um;
typedef gdc::nanomap<int, int> nm;
void
run_um(um& needles, const std::vector<int>& haystack)
{
for (auto hit = haystack.cbegin(); hit != haystack.cend(); ++hit)
{
auto nit = needles.find(*hit);
if (nit != needles.end())
{
++(nit->second);
}
}
}
void
run_nm(nm& needles, const std::vector<int>& haystack)
{
for (auto hit = haystack.cbegin(); hit != haystack.cend(); ++hit)
{
auto nit = needles.find(*hit);
if (nit != needles.end())
{
++(nit.value());
}
}
}
int
main(int argc, char** argv)
{
std::vector<int> input
{
1, 11, 111, 1111, 11111, 111111, 1111111, 11111111,
2, 22, 222, 2222, 22222, 222222, 2222222, 22222222
};
std::vector<int> haystack(10 * 1000 * 1000);
std::srand(9203854);
std::generate(haystack.begin(), haystack.end(), []() { return std::rand(); });
um um_needles;
gdc::nanomap_factory<int, int, 16> factory;
nm& nm_needles = factory.get();
for (auto i : input)
{
um_needles[i] = i;
nm_needles[i] = i;
}
// Warmup
run_um(um_needles, haystack);
run_um(um_needles, haystack);
// Final run
auto t0 = std::chrono::high_resolution_clock::now();
run_um(um_needles, haystack);
auto t1 = std::chrono::high_resolution_clock::now();
auto duration_um = std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0);
std::cout << "unordered_map duration: " << duration_um.count() << " ms" << std::endl;
run_nm(nm_needles, haystack);
run_nm(nm_needles, haystack);
t0 = std::chrono::high_resolution_clock::now();
run_nm(nm_needles, haystack);
t1 = std::chrono::high_resolution_clock::now();
auto duration_nm = std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0);
std::cout << "gdc::nanomap duration: " << duration_nm.count() << " ms" << std::endl;
}
| 28.570093 | 86 | 0.69349 |
6c75aa25ebca362bf52e57a3e7660b4f89500ead | 5,062 | cpp | C++ | src-plugins/reformat/resampleProcess.cpp | nebatmusic/medInria-public | 09000bd2f129692e42314a8eb1313d238603252e | [
"BSD-1-Clause"
] | 1 | 2020-11-16T13:55:45.000Z | 2020-11-16T13:55:45.000Z | src-plugins/reformat/resampleProcess.cpp | nebatmusic/medInria-public | 09000bd2f129692e42314a8eb1313d238603252e | [
"BSD-1-Clause"
] | null | null | null | src-plugins/reformat/resampleProcess.cpp | nebatmusic/medInria-public | 09000bd2f129692e42314a8eb1313d238603252e | [
"BSD-1-Clause"
] | null | null | null | #include "resampleProcess.h"
#include <dtkCore/dtkAbstractProcessFactory.h>
#include <medAbstractDataFactory.h>
#include <medAbstractProcess.h>
#include <medMetaDataKeys.h>
#include <medUtilitiesITK.h>
#include <itkResampleImageFilter.h>
#include <itkBSplineInterpolateImageFunction.h>
// /////////////////////////////////////////////////////////////////
// resampleProcessPrivate
// /////////////////////////////////////////////////////////////////
class resampleProcessPrivate
{
public:
resampleProcess *parent;
resampleProcessPrivate(resampleProcess *p)
{
parent = p;
}
medAbstractData* input;
medAbstractData* output;
int interpolator;
int dimX,dimY,dimZ;
double spacingX,spacingY,spacingZ;
};
// /////////////////////////////////////////////////////////////////
// resampleProcess
// /////////////////////////////////////////////////////////////////
resampleProcess::resampleProcess(void) : d(new resampleProcessPrivate(this))
{
d->dimX=0;
d->dimY=0;
d->dimZ=0;
d->spacingX = 0.0;
d->spacingY = 0.0;
d->spacingZ = 0.0;
}
resampleProcess::~resampleProcess(void)
{
delete d;
d = NULL;
}
bool resampleProcess::registered(void)
{
return dtkAbstractProcessFactory::instance()->registerProcessType("resampleProcess", createResampleProcess);
}
QString resampleProcess::description(void) const
{
return "resampleProcess";
}
void resampleProcess::setInput ( medAbstractData *data)
{
if ( !data )
return;
d->input = data;
}
void resampleProcess::setInput ( medAbstractData *data , int channel)
{
setInput(data);
}
void resampleProcess::setParameter ( double data, int channel)
{
switch (channel)
{
case 0:
d->dimX = (int)data;
break;
case 1:
d->dimY = (int)data;
break;
case 2:
d->dimZ = (int)data;
break;
case 3:
d->spacingX = data;
break;
case 4:
d->spacingY = data;
break;
case 5:
d->spacingZ = data;
break;
}
}
int resampleProcess::update ( void )
{
int result = DTK_FAILURE;
if (!d->input)
{
qDebug() << "in update method : d->input is NULL";
}
else
{
result = DISPATCH_ON_3D_PIXEL_TYPE(&resampleProcess::resample, this, d->input);
if (result == medAbstractProcess::PIXEL_TYPE)
{
result = DISPATCH_ON_4D_PIXEL_TYPE(&resampleProcess::resample, this, d->input);
}
}
return result;
}
template <class ImageType>
int resampleProcess::resample(medAbstractData* inputData)
{
typename ImageType::Pointer inputImage = static_cast<ImageType*>(inputData->data());
typedef typename itk::ResampleImageFilter<ImageType, ImageType,double> ResampleFilterType;
typename ResampleFilterType::Pointer resampleFilter = ResampleFilterType::New();
//// Fetch original image size.
const typename ImageType::RegionType& inputRegion = inputImage->GetLargestPossibleRegion();
const typename ImageType::SizeType& vnInputSize = inputRegion.GetSize();
unsigned int nOldX = vnInputSize[0];
unsigned int nOldY = vnInputSize[1];
unsigned int nOldZ = vnInputSize[2];
//// Fetch original image spacing.
const typename ImageType::SpacingType& vfInputSpacing = inputImage->GetSpacing();
double vfOutputSpacing[3]={d->spacingX,d->spacingY,d->spacingZ};
if (d->dimX || d->dimY || d->dimZ)
{
vfOutputSpacing[0] = vfInputSpacing[0] * (double) nOldX / (double) d->dimX;
vfOutputSpacing[1] = vfInputSpacing[1] * (double) nOldY / (double) d->dimY;
vfOutputSpacing[2] = vfInputSpacing[2] * (double) nOldZ / (double) d->dimZ;
}
else
{
d->dimX = floor((vfInputSpacing[0] * (double) nOldX / (double) vfOutputSpacing[0]) +0.5);
d->dimY = floor((vfInputSpacing[1] * (double) nOldY / (double) vfOutputSpacing[1]) +0.5);
d->dimZ = floor((vfInputSpacing[2] * (double) nOldZ / (double) vfOutputSpacing[2]) +0.5);
}
typename ImageType::SizeType vnOutputSize;
vnOutputSize[0] = d->dimX;
vnOutputSize[1] = d->dimY;
vnOutputSize[2] = d->dimZ;
resampleFilter->SetInput(inputImage);
resampleFilter->SetSize(vnOutputSize);
resampleFilter->SetOutputSpacing(vfOutputSpacing);
resampleFilter->SetOutputOrigin( inputImage->GetOrigin() );
resampleFilter->SetOutputDirection(inputImage->GetDirection() );
resampleFilter->UpdateLargestPossibleRegion();
d->output = medAbstractDataFactory::instance()->create(inputData->identifier());
d->output->setData(resampleFilter->GetOutput());
medUtilities::setDerivedMetaData(d->output, inputData, "resampled");
return DTK_SUCCEED;
}
medAbstractData * resampleProcess::output ( void )
{
return ( d->output );
}
// /////////////////////////////////////////////////////////////////
// Type instantiation
// /////////////////////////////////////////////////////////////////
dtkAbstractProcess *createResampleProcess(void)
{
return new resampleProcess;
}
| 28.925714 | 112 | 0.614184 |
6c767fd7fe905d57aad21b55162e1077581ede1f | 6,219 | hpp | C++ | libraries/chain/include/deip/chain/services/dbs_expertise_allocation_proposal.hpp | DEIPworld/deip-chain | d3fdcfdde179f700156156ea87522a807ec52532 | [
"MIT"
] | 1 | 2021-08-16T12:44:43.000Z | 2021-08-16T12:44:43.000Z | libraries/chain/include/deip/chain/services/dbs_expertise_allocation_proposal.hpp | DEIPworld/deip-chain | d3fdcfdde179f700156156ea87522a807ec52532 | [
"MIT"
] | null | null | null | libraries/chain/include/deip/chain/services/dbs_expertise_allocation_proposal.hpp | DEIPworld/deip-chain | d3fdcfdde179f700156156ea87522a807ec52532 | [
"MIT"
] | 2 | 2021-08-16T12:44:46.000Z | 2021-12-31T17:09:45.000Z | #pragma once
#include "dbs_base_impl.hpp"
#include <vector>
#include <set>
#include <functional>
#include <deip/chain/schema/expertise_allocation_proposal_object.hpp>
#include <deip/chain/schema/expertise_allocation_proposal_vote_object.hpp>
#include <deip/chain/schema/expert_token_object.hpp>
namespace deip {
namespace chain {
class dbs_expertise_allocation_proposal : public dbs_base {
friend class dbservice_dbs_factory;
dbs_expertise_allocation_proposal() = delete;
protected:
explicit dbs_expertise_allocation_proposal(database &db);
public:
using expertise_allocation_proposal_refs_type = std::vector<std::reference_wrapper<const expertise_allocation_proposal_object>>;
using expertise_allocation_proposal_optional_ref_type = fc::optional<std::reference_wrapper<const expertise_allocation_proposal_object>>;
const expertise_allocation_proposal_object& create(const account_name_type& claimer,
const discipline_id_type& discipline_id,
const string& description);
const expertise_allocation_proposal_object& get(const expertise_allocation_proposal_id_type& id) const;
const expertise_allocation_proposal_optional_ref_type get_expertise_allocation_proposal_if_exists(const expertise_allocation_proposal_id_type& id) const;
void remove(const expertise_allocation_proposal_id_type& id);
expertise_allocation_proposal_refs_type get_by_claimer(const account_name_type& claimer) const;
const expertise_allocation_proposal_object& get_by_claimer_and_discipline(const account_name_type& claimer,
const discipline_id_type& discipline_id) const;
const expertise_allocation_proposal_optional_ref_type get_expertise_allocation_proposal_by_claimer_and_discipline_if_exists(const account_name_type& claimer,
const discipline_id_type& discipline_id) const;
expertise_allocation_proposal_refs_type get_by_discipline_id(const discipline_id_type& discipline_id) const;
void check_existence_by_claimer_and_discipline(const account_name_type &claimer,
const discipline_id_type &discipline_id);
bool exists_by_claimer_and_discipline(const account_name_type &claimer,
const discipline_id_type &discipline_id);
void upvote(const expertise_allocation_proposal_object &expertise_allocation_proposal,
const account_name_type &voter,
const share_type weight);
void downvote(const expertise_allocation_proposal_object &expertise_allocation_proposal,
const account_name_type &voter,
const share_type weight);
bool is_expired(const expertise_allocation_proposal_object& expertise_allocation_proposal);
bool is_quorum(const expertise_allocation_proposal_object &expertise_allocation_proposal);
void delete_by_claimer_and_discipline(const account_name_type &claimer,
const discipline_id_type& discipline_id);
void clear_expired_expertise_allocation_proposals();
void process_expertise_allocation_proposals();
/* Expertise allocation proposal vote */
using expertise_allocation_proposal_vote_refs_type = std::vector<std::reference_wrapper<const expertise_allocation_proposal_vote_object>>;
using expertise_allocation_proposal_vote_optional_ref_type = fc::optional<std::reference_wrapper<const expertise_allocation_proposal_vote_object>>;
const expertise_allocation_proposal_vote_object& create_vote(const expertise_allocation_proposal_id_type& expertise_allocation_proposal_id,
const discipline_id_type& discipline_id,
const account_name_type &voter,
const share_type weight);
const expertise_allocation_proposal_vote_object& get_vote(const expertise_allocation_proposal_vote_id_type& id) const;
const expertise_allocation_proposal_vote_optional_ref_type get_expertise_allocation_proposal_vote_if_exists(const expertise_allocation_proposal_vote_id_type& id) const;
const expertise_allocation_proposal_vote_object& get_vote_by_voter_and_expertise_allocation_proposal_id(const account_name_type &voter,
const expertise_allocation_proposal_id_type& expertise_allocation_proposal_id) const;
const expertise_allocation_proposal_vote_optional_ref_type get_expertise_allocation_proposal_vote_by_voter_and_expertise_allocation_proposal_id_if_exists(const account_name_type &voter,
const expertise_allocation_proposal_id_type& expertise_allocation_proposal_id) const;
expertise_allocation_proposal_vote_refs_type get_votes_by_expertise_allocation_proposal_id(const expertise_allocation_proposal_id_type& expertise_allocation_proposal_id) const;
expertise_allocation_proposal_vote_refs_type get_votes_by_voter_and_discipline_id(const account_name_type& voter,
const discipline_id_type& discipline_id) const;
expertise_allocation_proposal_vote_refs_type get_votes_by_voter(const account_name_type& voter) const;
bool vote_exists_by_voter_and_expertise_allocation_proposal_id(const account_name_type &voter,
const expertise_allocation_proposal_id_type& expertise_allocation_proposal_id);
/* Adjusting */
void adjust_expert_token_vote(const expert_token_object& expert_token, share_type delta);
};
} // namespace chain
} // namespace deip
| 56.027027 | 243 | 0.705419 |
6c7737a2a29d9a93b0374dec4932899a19dd8a36 | 265 | cpp | C++ | tests/src/test.cpp | pqrs-org/cpp-environment_variable | 2b1d547603f5ce4a4455a254a4dbe514f14cd75e | [
"BSL-1.0"
] | null | null | null | tests/src/test.cpp | pqrs-org/cpp-environment_variable | 2b1d547603f5ce4a4455a254a4dbe514f14cd75e | [
"BSL-1.0"
] | null | null | null | tests/src/test.cpp | pqrs-org/cpp-environment_variable | 2b1d547603f5ce4a4455a254a4dbe514f14cd75e | [
"BSL-1.0"
] | null | null | null | #define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
#include <pqrs/environment_variable.hpp>
TEST_CASE("find") {
REQUIRE(pqrs::environment_variable::find("PATH"));
REQUIRE(pqrs::environment_variable::find("UNKNOWN_ENVIRONMENT_VARIABLE") == std::nullopt);
}
| 26.5 | 92 | 0.766038 |
6c782b8510844bec43bfbdbef92f39910506f105 | 858 | cpp | C++ | src/HostViewBHO/Factory.cpp | inria-muse/hostview-win | db890b83956081d98e64005873eb2e7e4c6891e6 | [
"MIT"
] | 1 | 2018-07-22T16:39:08.000Z | 2018-07-22T16:39:08.000Z | src/HostViewBHO/Factory.cpp | inria-muse/hostview-win | db890b83956081d98e64005873eb2e7e4c6891e6 | [
"MIT"
] | null | null | null | src/HostViewBHO/Factory.cpp | inria-muse/hostview-win | db890b83956081d98e64005873eb2e7e4c6891e6 | [
"MIT"
] | 1 | 2021-03-08T06:59:28.000Z | 2021-03-08T06:59:28.000Z | #include "common.h"
#include "Factory.h"
#include "Plugin.h"
const IID CFactory::SupportedIIDs[] = {IID_IUnknown, IID_IClassFactory};
CFactory::CFactory()
: CUnknown<IClassFactory>(SupportedIIDs, 2)
{
}
CFactory::~CFactory()
{
}
STDMETHODIMP CFactory::CreateInstance(IUnknown *pUnkOuter, REFIID riid, void **ppvObject)
{
if(pUnkOuter != NULL)
{
return CLASS_E_NOAGGREGATION;
}
if(IsBadWritePtr(ppvObject, sizeof(void*)))
{
return E_POINTER;
}
(*ppvObject) = NULL;
CBHOPlugin* pObject = new CBHOPlugin();
if(pObject == NULL)
{
return E_OUTOFMEMORY;
}
HRESULT hr = pObject->QueryInterface(riid, ppvObject);
if(FAILED(hr))
{
delete pObject;
}
return hr;
}
STDMETHODIMP CFactory::LockServer(BOOL fLock)
{
if(fLock)
{
InterlockedIncrement(&nDllRefCount);
}
else
{
InterlockedDecrement(&nDllRefCount);
}
return S_OK;
}
| 15.321429 | 89 | 0.706294 |
6c78d1de7d65ea97d301f5e18a99150380fe92d1 | 5,624 | cpp | C++ | cmdriver/src/CmXmlStringTokenizer.cpp | kit-transue/software-emancipation-discover | bec6f4ef404d72f361d91de954eae9a3bd669ce3 | [
"BSD-2-Clause"
] | 2 | 2015-11-24T03:31:12.000Z | 2015-11-24T16:01:57.000Z | cmdriver/src/CmXmlStringTokenizer.cpp | radtek/software-emancipation-discover | bec6f4ef404d72f361d91de954eae9a3bd669ce3 | [
"BSD-2-Clause"
] | null | null | null | cmdriver/src/CmXmlStringTokenizer.cpp | radtek/software-emancipation-discover | bec6f4ef404d72f361d91de954eae9a3bd669ce3 | [
"BSD-2-Clause"
] | 1 | 2019-05-19T02:26:08.000Z | 2019-05-19T02:26:08.000Z | /*************************************************************************
* Copyright (c) 2015, Synopsys, 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: *
* *
* 1. Redistributions of source code must retain the above copyright *
* notice, this list of conditions and the following disclaimer. *
* *
* 2. Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT *
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR *
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT *
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, *
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT *
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, *
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY *
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE *
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
*************************************************************************/
#include <stdlib.h>
#include <string.h>
#include "CmXmlStringTokenizer.h"
const int CmXmlStringTokenizer::ONE_SIDE_TOKEN = 0;
const int CmXmlStringTokenizer::BOTH_SIDES_TOKEN = 1;
CmXmlStringTokenizer::CmXmlStringTokenizer(const char *str, const char *delim, int mode) {
this->str = strdup(str);
this->delim = strdup(delim);
this->mode = mode;
this->curPtr = this->str;
} //constructor
CmXmlStringTokenizer::~CmXmlStringTokenizer() {
free(this->str);
free(this->delim);
} //destructor
char* CmXmlStringTokenizer::nextToken(int *begNdx) {
char *token = NULL;
if(this->mode == CmXmlStringTokenizer::ONE_SIDE_TOKEN) {
token = nextToken1();
} else if(this->mode == CmXmlStringTokenizer::BOTH_SIDES_TOKEN) {
token = nextToken2();
}
// Calculate index of the beginning of the token
if(begNdx != NULL) {
*begNdx = (token != NULL) ? (int)(token - this->str) : -1;
}
return token;
} //nextToken
int CmXmlStringTokenizer::howManyTokensLeft() {
int amount = 0;
if(this->mode == CmXmlStringTokenizer::ONE_SIDE_TOKEN) {
amount = howManyTokensLeft1();
} else if(this->mode == CmXmlStringTokenizer::BOTH_SIDES_TOKEN) {
amount = howManyTokensLeft2();
}
return amount;
} //howManyTokensLeft
char* CmXmlStringTokenizer::nextToken1() {
// Check arguments
if(this->curPtr == NULL || this->delim == NULL) {
return NULL;
}
// Token starts from current position
char *token = this->curPtr;
// Find first occurence of one of the delimeters
this->curPtr = strpbrk(this->curPtr, this->delim);
// If found -> place '\0' instead of delimeter and
// go to the beginning of the next token.
if(this->curPtr != NULL) {
this->curPtr[0] = 0;
this->curPtr++;
}
// Return pointer to the beginning of the current token
return token;
} //nextToken1
char* CmXmlStringTokenizer::nextToken2() {
// Check arguments
if(this->curPtr == NULL || this->delim == NULL) {
return NULL;
}
// Try to find the beginning of the next token
char *token = strpbrk(this->curPtr, this->delim);
// There are no more tokens
if(token == NULL) {
this->curPtr = NULL;
return NULL;
}
// This character is used as boundary for this token
char bound = token[0];
token++;
// This is expected to be a right boundary of this token
char *endPtr = strchr(token, bound);
if(endPtr == NULL) {
this->curPtr = NULL;
return NULL;
}
// Move further behind the current token
endPtr[0] = 0;
this->curPtr = endPtr + 1;
return token;
} //nextToken2
int CmXmlStringTokenizer::howManyTokensLeft1() {
// Check arguments
if(this->curPtr == NULL || this->delim == NULL) {
return 0;
}
// Number of tokens equals to number of delimeters plus 1
int amount = 0;
for(char *ptr = this->curPtr; ptr != NULL; ptr = strpbrk(ptr + 1, this->delim)) {
amount++;
}
return amount;
} //howManyTokensLeft1
int CmXmlStringTokenizer::howManyTokensLeft2() {
// Check arguments
if(this->curPtr == NULL || this->delim == NULL) {
return 0;
}
// Number of tokens equals number of pair of delimiters
int amount = 0;
for(char *ptr = this->curPtr; ptr != NULL; ptr = strpbrk(ptr, this->delim)) {
char bound = *ptr++;
char *endPtr = strchr(ptr, bound);
if(endPtr == NULL) {
break;
} else {
amount++;
ptr = endPtr + 1;
}
}
return amount;
} //howManyTokensLeft2
// END OF FILE
| 28.548223 | 90 | 0.585526 |
6c7e3a240169920f0aa7c99a2331f254a65f01bc | 421 | cpp | C++ | src/Y/Y403.cpp | wlhcode/lscct | 7fd112a9d1851ddcf41886d3084381a52e84a3ce | [
"MIT"
] | null | null | null | src/Y/Y403.cpp | wlhcode/lscct | 7fd112a9d1851ddcf41886d3084381a52e84a3ce | [
"MIT"
] | null | null | null | src/Y/Y403.cpp | wlhcode/lscct | 7fd112a9d1851ddcf41886d3084381a52e84a3ce | [
"MIT"
] | null | null | null | #include<iostream>
#include<algorithm>
using namespace std;
double arr[101];
int main(){
double a,ave=0;
cin>>a;
for(int i=0;i<a-1;i++) cin>>arr[i];
int tmp=a-1;
sort(arr,arr+tmp);
for(int i=a-2;i>0;i--) ave+=arr[i];
ave/=a-2;
if(ave>=50) cout<<"0"<<endl;
else{
ave-=arr[1]/(a-2);
for(int i=0;i<=100;i++){
if(ave+i/(a-2)>=50){
cout<<i<<endl;
return 0;
}
}cout<<"FAIL"<<endl;
return 0;
}
}
| 16.84 | 36 | 0.553444 |
6c7ead9f8211077b6a7af65c1e3b7750297ba267 | 318 | cpp | C++ | Solutions-to-Books/C++Primer/Chapter03/3.02.cpp | Horizon-Blue/playground | 4bd42bfcec60b8e89e127f4784c99f6ba669d359 | [
"MIT"
] | 2 | 2016-08-31T19:13:24.000Z | 2017-02-18T18:48:31.000Z | Solutions-to-Books/C++Primer/Chapter03/3.02.cpp | Horizon-Blue/playground | 4bd42bfcec60b8e89e127f4784c99f6ba669d359 | [
"MIT"
] | 1 | 2018-12-10T16:32:26.000Z | 2018-12-27T19:50:48.000Z | Solutions-to-Books/C++Primer/Chapter03/3.02.cpp | Horizon-Blue/playground | 4bd42bfcec60b8e89e127f4784c99f6ba669d359 | [
"MIT"
] | null | null | null | /* Exercise 3.2: Write a program to read the standard input
* a line at a time. Modify your program to read a word at
* a time
*/
// Xiaoyan Wang 10/26/2015
#include <iostream>
#include <string>
using namespace std;
int main() {
string line;
while (getline(cin, line))
cout << line << endl;
return 0;
}
| 18.705882 | 59 | 0.663522 |
6c85542f4b5405225ab1319c5da783e4c9f3123f | 281 | cpp | C++ | register_types.cpp | kamilors/Godytics | e8f079a35bf67bc6bcff36061ec173517d2433ee | [
"MIT"
] | 9 | 2017-08-08T22:18:59.000Z | 2021-11-05T03:57:43.000Z | register_types.cpp | henriquelalves/Godytics | b0ac613ff877561dc29144f04694a8bd60153042 | [
"MIT"
] | 1 | 2018-03-15T10:27:26.000Z | 2018-03-17T15:00:24.000Z | register_types.cpp | kamilors/Godytics | e8f079a35bf67bc6bcff36061ec173517d2433ee | [
"MIT"
] | 1 | 2018-07-30T21:09:33.000Z | 2018-07-30T21:09:33.000Z | #include "register_types.h"
#include "object_type_db.h"
#include "core/globals.h"
#include "ios/src/godytics.h"
void register_godytics_types() {
Globals::get_singleton()->add_singleton(Globals::Singleton("Godytics", memnew(Godytics)));
}
void unregister_godytics_types() {
}
| 23.416667 | 94 | 0.754448 |
6c8b318abf88c5b8ecc826173cb801f4a4992eec | 5,943 | hpp | C++ | src/NormalCore.hpp | munhouiani/MIDAS | c9e8c0b4d4944285b7deb43ac0447ffebc06adad | [
"Apache-2.0"
] | 2 | 2021-03-28T02:35:24.000Z | 2021-08-31T16:35:00.000Z | src/NormalCore.hpp | munhouiani/MIDAS | c9e8c0b4d4944285b7deb43ac0447ffebc06adad | [
"Apache-2.0"
] | null | null | null | src/NormalCore.hpp | munhouiani/MIDAS | c9e8c0b4d4944285b7deb43ac0447ffebc06adad | [
"Apache-2.0"
] | null | null | null | // -----------------------------------------------------------------------------
// Copyright 2020 Rui Liu (liurui39660) and Siddharth Bhatia (bhatiasiddharth)
//
// 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.
// -----------------------------------------------------------------------------
#pragma once
#include <cmath>
#include <string>
#include "CountMinSketch.hpp"
namespace MIDAS {
struct NormalCore {
const int numRow, numColumn;
unsigned long timestamp = 1;
unsigned long *const index; // Pre-compute the index to-be-modified, thanks to the same structure of CMSs
CountMinSketch numCurrent, numTotal;
NormalCore(int numRow, int numColumn) :
numRow(numRow),
numColumn(numColumn),
index(new unsigned long[numRow]),
numCurrent(numRow, numColumn),
numTotal(numCurrent) {}
NormalCore(int numRow, int numColumn, unsigned long timestamp, std::vector<unsigned long> index, CountMinSketch *numCurrent,
CountMinSketch *numTotal) :
numRow(numRow),
numColumn(numColumn),
timestamp(timestamp),
index(new unsigned long[numRow]),
numCurrent(*numCurrent),
numTotal(*numTotal) {
std::copy(index.begin(), index.end(), this->index);
}
virtual ~NormalCore() {
delete[] index;
}
static double ComputeScore(double a, double s, double t) {
return s == 0 || t - 1 == 0 ? 0 : pow((a - s / t) * t, 2) / (s * (t - 1));
}
static unsigned long HashStr(const std::string &str) {
unsigned long hash = 5381;
for (auto c: str) {
hash = ((hash << 5) + hash) + (unsigned long) c; /* hash * 33 + c */
}
return hash;
}
double operator()(const std::string &source, const std::string &destination, unsigned long timestamp) {
unsigned long intSource = HashStr(source);
unsigned long intDestination = HashStr(destination);
return this->operator()(intSource, intDestination, timestamp);
}
double operator()(unsigned long source, unsigned long destination, unsigned long timestamp) {
if (this->timestamp < timestamp) {
numCurrent.ClearAll();
this->timestamp = timestamp;
}
numCurrent.Hash(index, source, destination);
numCurrent.Add(index);
numTotal.Add(index);
return ComputeScore(numCurrent(index), numTotal(index), timestamp);
}
json SerializeAsJson() {
json model = json();
auto copyIndex = json::array();
std::copy(index, index + numRow, std::back_inserter(copyIndex));
model["numRow"] = numRow;
model["numColumn"] = numColumn;
model["timestamp"] = timestamp;
model["index"] = copyIndex;
model["numCurrent"] = numCurrent.SerializeAsJson();
model["numTotal"] = numTotal.SerializeAsJson();
return model;
}
int DumpToFile(const std::string &path) {
int rc = 0;
std::ofstream out(path);
try {
json model = SerializeAsJson();
out << model.dump(4);
}
catch (std::exception &e) {
std::cout << e.what() << std::endl;
}
catch (...) {
rc = -1;
}
return rc;
}
static NormalCore *LoadFromJson(json model) {
NormalCore *ret = nullptr;
try {
// extracting elements
int numRow = model["numRow"];
int numColumn = model["numColumn"];
unsigned long timestamp = model["timestamp"];
std::vector<unsigned long> tempIndex = model["index"];
json numCurrentJson = model["numCurrent"];
json numTotalJson = model["numTotal"];
// verify number of elements
if (tempIndex.size() == numRow) {
CountMinSketch *numCurrent = CountMinSketch::LoadFromJson(numCurrentJson);
CountMinSketch *numTotal = CountMinSketch::LoadFromJson(numTotalJson);
if (
numCurrent != nullptr
&& numTotal != nullptr
) {
ret = new NormalCore(numRow, numColumn, timestamp, tempIndex, numCurrent, numTotal);
}
delete numCurrent;
delete numTotal;
}
}
catch (std::exception &e) {
std::cout << e.what() << std::endl;
}
catch (...) {}
return ret;
}
static NormalCore *LoadFromFile(const std::string &path) {
std::ifstream in(path);
NormalCore *ret = nullptr;
try {
json model = json::parse(in);
ret = NormalCore::LoadFromJson(model);
}
catch (std::exception &e) {
std::cout << e.what() << std::endl;
}
catch (...) {}
return ret;
}
};
}
| 34.552326 | 132 | 0.50917 |
6c8ce34734194fcd195d7131f5bf7e060a2a4107 | 947 | cpp | C++ | apps/2d/euler/test_exact1/AfterQinit.cpp | dcseal/finess | 766e583ae9e84480640c7c3b3c157bf40ab87fe4 | [
"BSD-3-Clause"
] | null | null | null | apps/2d/euler/test_exact1/AfterQinit.cpp | dcseal/finess | 766e583ae9e84480640c7c3b3c157bf40ab87fe4 | [
"BSD-3-Clause"
] | null | null | null | apps/2d/euler/test_exact1/AfterQinit.cpp | dcseal/finess | 766e583ae9e84480640c7c3b3c157bf40ab87fe4 | [
"BSD-3-Clause"
] | null | null | null | /*
#include <iostream>
#include <iomanip>
#include "dogdefs.h"
#include "IniParams.h"
*/
#include "DogSolverCart2.h"
#include <string.h> // For strcpy and strcat (some compilers don't need this)
#include "IniParams.h"
// Function that is called after initial condition
void AfterQinit(DogSolverCart2& solver)
{
// DogStateCart2& state = solver.fetch_state();
// dTensorBC4& aux = state.fetch_aux();
// dTensorBC4& q = state.fetch_q();
// const int mx = q.getsize(1);
// const int my = q.getsize(2);
// const int meqn = q.getsize(3);
// const int kmax = q.getsize(4);
// const int mbc = q.getmbc();
// const int maux = aux.getsize(3);
// const int space_order = global_ini_params.get_space_order();
// Output parameters to file in outputdir
char eulerhelp[200];
strcpy( eulerhelp, solver.get_outputdir() );
strcat( eulerhelp, "/eulerhelp.dat");
eulerParams.write_eulerhelp( eulerhelp );
}
| 27.852941 | 86 | 0.669483 |
6c8dbddac1c11a71d1f0bf12b64a9e7b95a05d59 | 691 | hpp | C++ | Public/Ava/Private/Platform/Arch.hpp | vasama/Ava | c1e6fb87a493dc46ce870220c632069f00875d2c | [
"MIT"
] | null | null | null | Public/Ava/Private/Platform/Arch.hpp | vasama/Ava | c1e6fb87a493dc46ce870220c632069f00875d2c | [
"MIT"
] | null | null | null | Public/Ava/Private/Platform/Arch.hpp | vasama/Ava | c1e6fb87a493dc46ce870220c632069f00875d2c | [
"MIT"
] | null | null | null | #pragma once
#if defined(Ava_X86) \
|| defined(__i386__) \
|| defined(__i486__) \
|| defined(__i586__) \
|| defined(__i686__) \
|| defined(_M_IX86)
# ifndef Ava_X86
# define Ava_X86 1
# endif
# define Ava_32 1
# define Ava_ARCH x86
#elif defined(Ava_X64) \
|| defined(__x86_64) \
|| defined(__x86_64__) \
|| defined(__amd64) \
|| defined(__amd64__) \
|| defined(_M_X64)
# ifndef Ava_X64
# define Ava_X64 1
# endif
# define Ava_64 1
# define Ava_ARCH x64
#else
# error Unsupported architecture
#endif
#ifndef Ava_32
# define Ava_32 0
#endif
#ifndef Ava_64
# define Ava_64 0
#endif
#ifndef Ava_X86
# define Ava_X86 0
#endif
#ifndef Ava_X64
# define Ava_X64 0
#endif
| 15.704545 | 32 | 0.691751 |
6c8e13b5d49c84522cb7a74452c7f089529ce49c | 841 | cpp | C++ | OJ/LeetCode/leetcode/problems/offer39.cpp | ONGOING-Z/DataStructure | 9099393d1c7dfabc3e2939586ea6d1d254631eb2 | [
"MIT"
] | null | null | null | OJ/LeetCode/leetcode/problems/offer39.cpp | ONGOING-Z/DataStructure | 9099393d1c7dfabc3e2939586ea6d1d254631eb2 | [
"MIT"
] | 2 | 2021-10-31T10:05:45.000Z | 2022-02-12T15:17:53.000Z | OJ/LeetCode/leetcode/offer39.cpp | ONGOING-Z/Learn-Algorithm-and-DataStructure | 3a512bd83cc6ed5035ac4550da2f511298b947c0 | [
"MIT"
] | null | null | null | #include <iostream>
#include <stdio.h>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
/* Offer */
/* Type: */
/* 题目信息 */
/*
*剑指 Offer 39. 数组中出现次数超过一半的数字
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2
限制: 1 <= 数组长度 <= 50000
*/
/* my solution */
// solution-1, 44ms, defeat 75.70%
// 使用map找每个数字的频次,然后再遍历,找到频次符号条件的数字返回。
// O(n)
class Solution {
public:
int majorityElement(vector<int>& nums) {
map<int, int> mp;
for (int num : nums)
mp[num]++;
for (auto e : mp)
{
if (e.second > nums.size() / 2)
return e.first;
}
return -1;
}
};
/* better solution */
// solution-x, ms, defeat %
/* 一些总结 */
// 1. 题意:
//
// 需要注意的点:
// 1.
// 2.
// 3.
| 13.786885 | 44 | 0.530321 |
6c915f68204c33100c70f4ef5405fb1b844abbf3 | 1,205 | cpp | C++ | src/engine/test/maptest.cpp | eXl-Nic/eXl | a5a0f77f47db3179365c107a184bb38b80280279 | [
"MIT"
] | null | null | null | src/engine/test/maptest.cpp | eXl-Nic/eXl | a5a0f77f47db3179365c107a184bb38b80280279 | [
"MIT"
] | null | null | null | src/engine/test/maptest.cpp | eXl-Nic/eXl | a5a0f77f47db3179365c107a184bb38b80280279 | [
"MIT"
] | null | null | null |
#include <gtest/gtest.h>
#include <gen/floodfill.hpp>
using namespace eXl;
TEST(DunAtk, FloodFillTest)
{
AABB2Di box(Vector2i::ZERO, Vector2i::ONE * 8);
{
Vector<char> testVec =
{ -1, -1, -1, -1, -1, -1, -1, -1,
-1, 0, 0, -1, -1, 0, 0, -1,
-1, 0, 0, 0, -1, -1, 0, 0,
-1, -1, -1, 0, -1, -1, -1, 0,
-1, 0, 0, 0, -1, -1, -1, 0,
-1, -1, -1, 0, 0, 0, 0, 0,
0, 0, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
};
Vector<uint32_t> out_comps;
uint32_t numComps = FloodFill::ExtractComponents(testVec, box, out_comps);
ASSERT_EQ(numComps, 2);
Vector<AABB2DPolygoni> polys;
FloodFill::MakePolygons(testVec, box, [](char iVal) { return iVal == 0; }, polys);
ASSERT_EQ(polys.size(), 2);
}
Vector<bool> testVec =
{ 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 1, 1, 0, 1, 1, 1,
0, 1, 0, 1, 0, 1, 0, 1,
0, 1, 0, 1, 0, 1, 1, 1,
0, 1, 1, 1, 0, 0, 1, 0,
0, 0, 0, 0, 1, 0, 1, 0,
0, 0, 0, 0, 1, 0, 1, 0,
0, 0, 0, 0, 1, 1, 1, 0,
};
Vector<AABB2DPolygoni> polys;
FloodFill::MakePolygons(testVec, box, FloodFill::ValidOperator<bool>(), polys);
ASSERT_EQ(polys.size(), 2);
} | 23.627451 | 86 | 0.483817 |
6c95b467682542463fdbce08ee620d070e45c08d | 6,096 | cc | C++ | RecoLocalCalo/HGCalRecAlgos/src/ClusterTools.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | RecoLocalCalo/HGCalRecAlgos/src/ClusterTools.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | RecoLocalCalo/HGCalRecAlgos/src/ClusterTools.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #include "RecoLocalCalo/HGCalRecAlgos/interface/ClusterTools.h"
#include "DataFormats/DetId/interface/DetId.h"
#include "DataFormats/ForwardDetId/interface/ForwardSubdetector.h"
#include "DataFormats/HcalDetId/interface/HcalSubdetector.h"
#include "Geometry/HGCalGeometry/interface/HGCalGeometry.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "DataFormats/Common/interface/Handle.h"
#include "vdt/vdtMath.h"
#include <iostream>
using namespace hgcal;
ClusterTools::ClusterTools() {}
ClusterTools::ClusterTools(const edm::ParameterSet& conf, edm::ConsumesCollector& sumes)
: eetok(sumes.consumes<HGCRecHitCollection>(conf.getParameter<edm::InputTag>("HGCEEInput"))),
fhtok(sumes.consumes<HGCRecHitCollection>(conf.getParameter<edm::InputTag>("HGCFHInput"))),
bhtok(sumes.consumes<HGCRecHitCollection>(conf.getParameter<edm::InputTag>("HGCBHInput"))),
caloGeometryToken_{sumes.esConsumes()} {}
void ClusterTools::getEvent(const edm::Event& ev) {
eerh_ = &ev.get(eetok);
fhrh_ = &ev.get(fhtok);
bhrh_ = &ev.get(bhtok);
}
void ClusterTools::getEventSetup(const edm::EventSetup& es) { rhtools_.setGeometry(es.getData(caloGeometryToken_)); }
float ClusterTools::getClusterHadronFraction(const reco::CaloCluster& clus) const {
float energy = 0.f, energyHad = 0.f;
const auto& hits = clus.hitsAndFractions();
for (const auto& hit : hits) {
const auto& id = hit.first;
const float fraction = hit.second;
if (id.det() == DetId::HGCalEE) {
energy += eerh_->find(id)->energy() * fraction;
} else if (id.det() == DetId::HGCalHSi) {
const float temp = fhrh_->find(id)->energy();
energy += temp * fraction;
energyHad += temp * fraction;
} else if (id.det() == DetId::HGCalHSc) {
const float temp = bhrh_->find(id)->energy();
energy += temp * fraction;
energyHad += temp * fraction;
} else if (id.det() == DetId::Forward) {
switch (id.subdetId()) {
case HGCEE:
energy += eerh_->find(id)->energy() * fraction;
break;
case HGCHEF: {
const float temp = fhrh_->find(id)->energy();
energy += temp * fraction;
energyHad += temp * fraction;
} break;
default:
throw cms::Exception("HGCalClusterTools") << " Cluster contains hits that are not from HGCal! " << std::endl;
}
} else if (id.det() == DetId::Hcal && id.subdetId() == HcalEndcap) {
const float temp = bhrh_->find(id)->energy();
energy += temp * fraction;
energyHad += temp * fraction;
} else {
throw cms::Exception("HGCalClusterTools") << " Cluster contains hits that are not from HGCal! " << std::endl;
}
}
float fraction = -1.f;
if (energy > 0.f) {
fraction = energyHad / energy;
}
return fraction;
}
math::XYZPoint ClusterTools::getMultiClusterPosition(const reco::HGCalMultiCluster& clu) const {
if (clu.clusters().empty())
return math::XYZPoint();
double acc_x = 0.0;
double acc_y = 0.0;
double acc_z = 0.0;
double totweight = 0.;
double mcenergy = getMultiClusterEnergy(clu);
for (const auto& ptr : clu.clusters()) {
if (mcenergy != 0) {
if (ptr->energy() < .01 * mcenergy)
continue; //cutoff < 1% layer contribution
}
const double weight = ptr->energy(); // weigth each corrdinate only by the total energy of the layer cluster
acc_x += ptr->x() * weight;
acc_y += ptr->y() * weight;
acc_z += ptr->z() * weight;
totweight += weight;
}
if (totweight != 0) {
acc_x /= totweight;
acc_y /= totweight;
acc_z /= totweight;
}
// return x/y/z in absolute coordinates
return math::XYZPoint(acc_x, acc_y, acc_z);
}
int ClusterTools::getLayer(const DetId detid) const { return rhtools_.getLayerWithOffset(detid); }
double ClusterTools::getMultiClusterEnergy(const reco::HGCalMultiCluster& clu) const {
double acc = 0.0;
for (const auto& ptr : clu.clusters()) {
acc += ptr->energy();
}
return acc;
}
bool ClusterTools::getWidths(const reco::CaloCluster& clus,
double& sigmaetaeta,
double& sigmaphiphi,
double& sigmaetaetal,
double& sigmaphiphil) const {
if (getLayer(clus.hitsAndFractions()[0].first) > (int)rhtools_.lastLayerEE())
return false;
const math::XYZPoint& position(clus.position());
unsigned nhit = clus.hitsAndFractions().size();
sigmaetaeta = 0.;
sigmaphiphi = 0.;
sigmaetaetal = 0.;
sigmaphiphil = 0.;
double sumw = 0.;
double sumlogw = 0.;
for (unsigned int ih = 0; ih < nhit; ++ih) {
const DetId& id = (clus.hitsAndFractions())[ih].first;
if ((clus.hitsAndFractions())[ih].second == 0.)
continue;
if ((id.det() == DetId::HGCalEE) || (id.det() == DetId::Forward && id.subdetId() == HGCEE)) {
const HGCRecHit* theHit = &(*eerh_->find(id));
GlobalPoint cellPos = rhtools_.getPosition(id);
double weight = theHit->energy();
// take w0=2 To be optimized
double logweight = 0;
if (clus.energy() != 0) {
logweight = std::max(0., 2 + log(theHit->energy() / clus.energy()));
}
double deltaetaeta2 = (cellPos.eta() - position.eta()) * (cellPos.eta() - position.eta());
double deltaphiphi2 = (cellPos.phi() - position.phi()) * (cellPos.phi() - position.phi());
sigmaetaeta += deltaetaeta2 * weight;
sigmaphiphi += deltaphiphi2 * weight;
sigmaetaetal += deltaetaeta2 * logweight;
sigmaphiphil += deltaphiphi2 * logweight;
sumw += weight;
sumlogw += logweight;
}
}
if (sumw <= 0.)
return false;
sigmaetaeta /= sumw;
sigmaetaeta = std::sqrt(sigmaetaeta);
sigmaphiphi /= sumw;
sigmaphiphi = std::sqrt(sigmaphiphi);
if (sumlogw != 0) {
sigmaetaetal /= sumlogw;
sigmaetaetal = std::sqrt(sigmaetaetal);
sigmaphiphil /= sumlogw;
sigmaphiphil = std::sqrt(sigmaphiphil);
}
return true;
}
| 34.055866 | 119 | 0.636975 |
6c966b5fa941144b13f247c752bb089933b97764 | 18,592 | cpp | C++ | src/gpu/vk/GrVkGpuCommandBuffer.cpp | juanpca12/Google-Skia | 42e6798696ac3a93a2b7ba7a9d6a84b77eba0116 | [
"Apache-2.0"
] | null | null | null | src/gpu/vk/GrVkGpuCommandBuffer.cpp | juanpca12/Google-Skia | 42e6798696ac3a93a2b7ba7a9d6a84b77eba0116 | [
"Apache-2.0"
] | null | null | null | src/gpu/vk/GrVkGpuCommandBuffer.cpp | juanpca12/Google-Skia | 42e6798696ac3a93a2b7ba7a9d6a84b77eba0116 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrVkGpuCommandBuffer.h"
#include "GrMesh.h"
#include "GrPipeline.h"
#include "GrRenderTargetPriv.h"
#include "GrTextureAccess.h"
#include "GrTexturePriv.h"
#include "GrVkCommandBuffer.h"
#include "GrVkGpu.h"
#include "GrVkPipeline.h"
#include "GrVkRenderPass.h"
#include "GrVkRenderTarget.h"
#include "GrVkResourceProvider.h"
#include "GrVkTexture.h"
void get_vk_load_store_ops(const GrGpuCommandBuffer::LoadAndStoreInfo& info,
VkAttachmentLoadOp* loadOp, VkAttachmentStoreOp* storeOp) {
switch (info.fLoadOp) {
case GrGpuCommandBuffer::LoadOp::kLoad:
*loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
break;
case GrGpuCommandBuffer::LoadOp::kClear:
*loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
break;
case GrGpuCommandBuffer::LoadOp::kDiscard:
*loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
break;
default:
SK_ABORT("Invalid LoadOp");
*loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
}
switch (info.fStoreOp) {
case GrGpuCommandBuffer::StoreOp::kStore:
*storeOp = VK_ATTACHMENT_STORE_OP_STORE;
break;
case GrGpuCommandBuffer::StoreOp::kDiscard:
*storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
break;
default:
SK_ABORT("Invalid StoreOp");
*storeOp = VK_ATTACHMENT_STORE_OP_STORE;
}
}
GrVkGpuCommandBuffer::GrVkGpuCommandBuffer(GrVkGpu* gpu,
GrVkRenderTarget* target,
const LoadAndStoreInfo& colorInfo,
const LoadAndStoreInfo& stencilInfo)
: fGpu(gpu)
, fRenderTarget(target)
, fIsEmpty(true) {
VkAttachmentLoadOp vkLoadOp;
VkAttachmentStoreOp vkStoreOp;
get_vk_load_store_ops(colorInfo, &vkLoadOp, &vkStoreOp);
GrVkRenderPass::LoadStoreOps vkColorOps(vkLoadOp, vkStoreOp);
get_vk_load_store_ops(stencilInfo, &vkLoadOp, &vkStoreOp);
GrVkRenderPass::LoadStoreOps vkStencilOps(vkLoadOp, vkStoreOp);
GrVkRenderPass::LoadStoreOps vkResolveOps(VK_ATTACHMENT_LOAD_OP_LOAD,
VK_ATTACHMENT_STORE_OP_STORE);
const GrVkResourceProvider::CompatibleRPHandle& rpHandle = target->compatibleRenderPassHandle();
if (rpHandle.isValid()) {
fRenderPass = fGpu->resourceProvider().findRenderPass(rpHandle,
vkColorOps,
vkResolveOps,
vkStencilOps);
} else {
fRenderPass = fGpu->resourceProvider().findRenderPass(*target,
vkColorOps,
vkResolveOps,
vkStencilOps);
}
GrColorToRGBAFloat(colorInfo.fClearColor, fColorClearValue.color.float32);
fCommandBuffer = GrVkSecondaryCommandBuffer::Create(gpu, gpu->cmdPool(), fRenderPass);
fCommandBuffer->begin(gpu, target->framebuffer());
}
GrVkGpuCommandBuffer::~GrVkGpuCommandBuffer() {
fCommandBuffer->unref(fGpu);
fRenderPass->unref(fGpu);
}
GrGpu* GrVkGpuCommandBuffer::gpu() { return fGpu; }
void GrVkGpuCommandBuffer::end() {
fCommandBuffer->end(fGpu);
}
void GrVkGpuCommandBuffer::onSubmit(const SkIRect& bounds) {
// Change layout of our render target so it can be used as the color attachment
fRenderTarget->setImageLayout(fGpu,
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
false);
// If we are using a stencil attachment we also need to update its layout
if (GrStencilAttachment* stencil = fRenderTarget->renderTargetPriv().getStencilAttachment()) {
GrVkStencilAttachment* vkStencil = (GrVkStencilAttachment*)stencil;
vkStencil->setImageLayout(fGpu,
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
false);
}
if (GrVkImage* msaaImage = fRenderTarget->msaaImage()) {
msaaImage->setImageLayout(fGpu,
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
false);
}
for (int i = 0; i < fSampledImages.count(); ++i) {
fSampledImages[i]->setImageLayout(fGpu,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_ACCESS_SHADER_READ_BIT,
VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT,
false);
}
fGpu->submitSecondaryCommandBuffer(fCommandBuffer, fRenderPass, &fColorClearValue,
fRenderTarget, bounds);
}
void GrVkGpuCommandBuffer::discard(GrRenderTarget* target) {
if (fIsEmpty) {
// We will change the render pass to do a clear load instead
GrVkRenderPass::LoadStoreOps vkColorOps(VK_ATTACHMENT_LOAD_OP_DONT_CARE,
VK_ATTACHMENT_STORE_OP_STORE);
GrVkRenderPass::LoadStoreOps vkStencilOps(VK_ATTACHMENT_LOAD_OP_DONT_CARE,
VK_ATTACHMENT_STORE_OP_STORE);
GrVkRenderPass::LoadStoreOps vkResolveOps(VK_ATTACHMENT_LOAD_OP_DONT_CARE,
VK_ATTACHMENT_STORE_OP_STORE);
const GrVkRenderPass* oldRP = fRenderPass;
GrVkRenderTarget* vkRT = static_cast<GrVkRenderTarget*>(target);
const GrVkResourceProvider::CompatibleRPHandle& rpHandle =
vkRT->compatibleRenderPassHandle();
if (rpHandle.isValid()) {
fRenderPass = fGpu->resourceProvider().findRenderPass(rpHandle,
vkColorOps,
vkResolveOps,
vkStencilOps);
} else {
fRenderPass = fGpu->resourceProvider().findRenderPass(*vkRT,
vkColorOps,
vkResolveOps,
vkStencilOps);
}
SkASSERT(fRenderPass->isCompatible(*oldRP));
oldRP->unref(fGpu);
}
}
void GrVkGpuCommandBuffer::onClearStencilClip(GrRenderTarget* target,
const SkIRect& rect,
bool insideClip) {
SkASSERT(target);
GrVkRenderTarget* vkRT = static_cast<GrVkRenderTarget*>(target);
GrStencilAttachment* sb = target->renderTargetPriv().getStencilAttachment();
// this should only be called internally when we know we have a
// stencil buffer.
SkASSERT(sb);
int stencilBitCount = sb->bits();
// The contract with the callers does not guarantee that we preserve all bits in the stencil
// during this clear. Thus we will clear the entire stencil to the desired value.
VkClearDepthStencilValue vkStencilColor;
memset(&vkStencilColor, 0, sizeof(VkClearDepthStencilValue));
if (insideClip) {
vkStencilColor.stencil = (1 << (stencilBitCount - 1));
} else {
vkStencilColor.stencil = 0;
}
VkClearRect clearRect;
// Flip rect if necessary
SkIRect vkRect = rect;
if (kBottomLeft_GrSurfaceOrigin == vkRT->origin()) {
vkRect.fTop = vkRT->height() - rect.fBottom;
vkRect.fBottom = vkRT->height() - rect.fTop;
}
clearRect.rect.offset = { vkRect.fLeft, vkRect.fTop };
clearRect.rect.extent = { (uint32_t)vkRect.width(), (uint32_t)vkRect.height() };
clearRect.baseArrayLayer = 0;
clearRect.layerCount = 1;
uint32_t stencilIndex;
SkAssertResult(fRenderPass->stencilAttachmentIndex(&stencilIndex));
VkClearAttachment attachment;
attachment.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
attachment.colorAttachment = 0; // this value shouldn't matter
attachment.clearValue.depthStencil = vkStencilColor;
fCommandBuffer->clearAttachments(fGpu, 1, &attachment, 1, &clearRect);
fIsEmpty = false;
}
void GrVkGpuCommandBuffer::onClear(GrRenderTarget* target, const SkIRect& rect, GrColor color) {
// parent class should never let us get here with no RT
SkASSERT(target);
VkClearColorValue vkColor;
GrColorToRGBAFloat(color, vkColor.float32);
GrVkRenderTarget* vkRT = static_cast<GrVkRenderTarget*>(target);
if (fIsEmpty && rect.width() == target->width() && rect.height() == target->height()) {
// We will change the render pass to do a clear load instead
GrVkRenderPass::LoadStoreOps vkColorOps(VK_ATTACHMENT_LOAD_OP_CLEAR,
VK_ATTACHMENT_STORE_OP_STORE);
GrVkRenderPass::LoadStoreOps vkStencilOps(VK_ATTACHMENT_LOAD_OP_LOAD,
VK_ATTACHMENT_STORE_OP_STORE);
GrVkRenderPass::LoadStoreOps vkResolveOps(VK_ATTACHMENT_LOAD_OP_LOAD,
VK_ATTACHMENT_STORE_OP_STORE);
const GrVkRenderPass* oldRP = fRenderPass;
const GrVkResourceProvider::CompatibleRPHandle& rpHandle =
vkRT->compatibleRenderPassHandle();
if (rpHandle.isValid()) {
fRenderPass = fGpu->resourceProvider().findRenderPass(rpHandle,
vkColorOps,
vkResolveOps,
vkStencilOps);
} else {
fRenderPass = fGpu->resourceProvider().findRenderPass(*vkRT,
vkColorOps,
vkResolveOps,
vkStencilOps);
}
SkASSERT(fRenderPass->isCompatible(*oldRP));
oldRP->unref(fGpu);
GrColorToRGBAFloat(color, fColorClearValue.color.float32);
return;
}
// We always do a sub rect clear with clearAttachments since we are inside a render pass
VkClearRect clearRect;
// Flip rect if necessary
SkIRect vkRect = rect;
if (kBottomLeft_GrSurfaceOrigin == vkRT->origin()) {
vkRect.fTop = vkRT->height() - rect.fBottom;
vkRect.fBottom = vkRT->height() - rect.fTop;
}
clearRect.rect.offset = { vkRect.fLeft, vkRect.fTop };
clearRect.rect.extent = { (uint32_t)vkRect.width(), (uint32_t)vkRect.height() };
clearRect.baseArrayLayer = 0;
clearRect.layerCount = 1;
uint32_t colorIndex;
SkAssertResult(fRenderPass->colorAttachmentIndex(&colorIndex));
VkClearAttachment attachment;
attachment.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
attachment.colorAttachment = colorIndex;
attachment.clearValue.color = vkColor;
fCommandBuffer->clearAttachments(fGpu, 1, &attachment, 1, &clearRect);
fIsEmpty = false;
return;
}
////////////////////////////////////////////////////////////////////////////////
void GrVkGpuCommandBuffer::bindGeometry(const GrPrimitiveProcessor& primProc,
const GrNonInstancedMesh& mesh) {
// There is no need to put any memory barriers to make sure host writes have finished here.
// When a command buffer is submitted to a queue, there is an implicit memory barrier that
// occurs for all host writes. Additionally, BufferMemoryBarriers are not allowed inside of
// an active RenderPass.
GrVkVertexBuffer* vbuf;
vbuf = (GrVkVertexBuffer*)mesh.vertexBuffer();
SkASSERT(vbuf);
SkASSERT(!vbuf->isMapped());
fCommandBuffer->bindVertexBuffer(fGpu, vbuf);
if (mesh.isIndexed()) {
GrVkIndexBuffer* ibuf = (GrVkIndexBuffer*)mesh.indexBuffer();
SkASSERT(ibuf);
SkASSERT(!ibuf->isMapped());
fCommandBuffer->bindIndexBuffer(fGpu, ibuf);
}
}
sk_sp<GrVkPipelineState> GrVkGpuCommandBuffer::prepareDrawState(
const GrPipeline& pipeline,
const GrPrimitiveProcessor& primProc,
GrPrimitiveType primitiveType,
const GrVkRenderPass& renderPass) {
sk_sp<GrVkPipelineState> pipelineState =
fGpu->resourceProvider().findOrCreateCompatiblePipelineState(pipeline,
primProc,
primitiveType,
renderPass);
if (!pipelineState) {
return pipelineState;
}
pipelineState->setData(fGpu, primProc, pipeline);
pipelineState->bind(fGpu, fCommandBuffer);
GrVkPipeline::SetDynamicState(fGpu, fCommandBuffer, pipeline);
return pipelineState;
}
static void append_sampled_images(const GrProcessor& processor,
const GrVkGpu* gpu,
SkTArray<GrVkImage*>* sampledImages) {
if (int numTextures = processor.numTextures()) {
GrVkImage** images = sampledImages->push_back_n(numTextures);
int i = 0;
do {
const GrTextureAccess& texAccess = processor.textureAccess(i);
GrVkTexture* vkTexture = static_cast<GrVkTexture*>(processor.texture(i));
SkASSERT(vkTexture);
const GrTextureParams& params = texAccess.getParams();
// Check if we need to regenerate any mip maps
if (GrTextureParams::kMipMap_FilterMode == params.filterMode()) {
if (vkTexture->texturePriv().mipMapsAreDirty()) {
gpu->generateMipmap(vkTexture);
vkTexture->texturePriv().dirtyMipMaps(false);
}
}
images[i] = vkTexture;
} while (++i < numTextures);
}
}
void GrVkGpuCommandBuffer::onDraw(const GrPipeline& pipeline,
const GrPrimitiveProcessor& primProc,
const GrMesh* meshes,
int meshCount) {
if (!meshCount) {
return;
}
GrRenderTarget* rt = pipeline.getRenderTarget();
GrVkRenderTarget* vkRT = static_cast<GrVkRenderTarget*>(rt);
const GrVkRenderPass* renderPass = vkRT->simpleRenderPass();
SkASSERT(renderPass);
GrPrimitiveType primitiveType = meshes[0].primitiveType();
sk_sp<GrVkPipelineState> pipelineState = this->prepareDrawState(pipeline,
primProc,
primitiveType,
*renderPass);
if (!pipelineState) {
return;
}
append_sampled_images(primProc, fGpu, &fSampledImages);
for (int i = 0; i < pipeline.numFragmentProcessors(); ++i) {
append_sampled_images(pipeline.getFragmentProcessor(i), fGpu, &fSampledImages);
}
append_sampled_images(pipeline.getXferProcessor(), fGpu, &fSampledImages);
for (int i = 0; i < meshCount; ++i) {
const GrMesh& mesh = meshes[i];
GrMesh::Iterator iter;
const GrNonInstancedMesh* nonIdxMesh = iter.init(mesh);
do {
if (nonIdxMesh->primitiveType() != primitiveType) {
// Technically we don't have to call this here (since there is a safety check in
// pipelineState:setData but this will allow for quicker freeing of resources if the
// pipelineState sits in a cache for a while.
pipelineState->freeTempResources(fGpu);
SkDEBUGCODE(pipelineState = nullptr);
primitiveType = nonIdxMesh->primitiveType();
pipelineState = this->prepareDrawState(pipeline,
primProc,
primitiveType,
*renderPass);
if (!pipelineState) {
return;
}
}
SkASSERT(pipelineState);
this->bindGeometry(primProc, *nonIdxMesh);
if (nonIdxMesh->isIndexed()) {
fCommandBuffer->drawIndexed(fGpu,
nonIdxMesh->indexCount(),
1,
nonIdxMesh->startIndex(),
nonIdxMesh->startVertex(),
0);
} else {
fCommandBuffer->draw(fGpu,
nonIdxMesh->vertexCount(),
1,
nonIdxMesh->startVertex(),
0);
}
fIsEmpty = false;
fGpu->stats()->incNumDraws();
} while ((nonIdxMesh = iter.next()));
}
// Technically we don't have to call this here (since there is a safety check in
// pipelineState:setData but this will allow for quicker freeing of resources if the
// pipelineState sits in a cache for a while.
pipelineState->freeTempResources(fGpu);
}
| 42.447489 | 100 | 0.554862 |
6c972bda8864d4c341abda36d045af3774fc6f79 | 3,151 | cpp | C++ | main.cpp | fogwizard/fillsize | 54928fbd50989beb92676e4d6703b3b18ab93eed | [
"Apache-2.0"
] | null | null | null | main.cpp | fogwizard/fillsize | 54928fbd50989beb92676e4d6703b3b18ab93eed | [
"Apache-2.0"
] | null | null | null | main.cpp | fogwizard/fillsize | 54928fbd50989beb92676e4d6703b3b18ab93eed | [
"Apache-2.0"
] | null | null | null | #include <unistd.h>
#include <string.h>
#include "iostream"
#include "stdio.h"
#include "stdint.h"
#include "fillsize.h"
#include "mergebin.h"
#include "alignbin.h"
#include "ddbin.h"
using namespace std;
int usage(void)
{
cout << "Usage: fillsize <filename> [address]" << endl;
return 0;
}
int usage_merge(void)
{
cout << "Usage: fillsize -merge <loader> <offset> <app>" << endl;
return 0;
}
int usage_align(void)
{
cout << "Usage: fillsize -align <inFile> <alignValue>" << endl;
return 0;
}
int usage_dd(void)
{
cout << "Usage: fillsize -dd <inFile> <outFile> [skip] [out_length]" << endl;
return 0;
}
int main(int argc, const char *argv[])
{
if((argc >= 2) && (0 == strcmp("-merge", argv[1]))) {
cout << "merge function active" << endl;
mergeBin *mf = NULL;
if(argc != 5) {
return usage_merge();
}
/* check input file */
if (-1 == access(argv[2], 0)) {
cout << "file:" << argv[2] << " not exist" << endl;
return usage_merge();
}
if (-1 == access(argv[4], 0)) {
cout << "file:" << argv[4] << " not exist" << endl;
return usage_merge();
}
mf = new mergeBin(argv[2], argv[3], argv[4]);
mf->fill_loader();
mf->fill_app();
mf->fill_magic();
cout << "merge function end..." << endl;
return 0;
}
/* align tool */
if((argc >= 2) && (0 == strcmp("-align", argv[1]))) {
if((argc != 4) &&(argc != 5)) {
return usage_align();
}
/* check input file */
if (-1 == access(argv[2], 0)) {
cout << "file:" << argv[2] << " not exist" << endl;
return usage_align();
}
alignBin *ab;
if(4 == argc) {
ab = new alignBin(argv[2], argv[3]);
} else {
ab = new alignBin(argv[2], argv[3], argv[4]);
}
ab->do_align();
return 0;
}
/* dd tool */
if((argc >= 2) && (0 == strcmp("-dd", argv[1]))) {
if((4 != argc) && (5 != argc) &&(6 != argc)) {
return usage_dd();
}
/* check input file */
if (-1 == access(argv[2], 0)) {
cout << "file:" << argv[2] << " not exist" << endl;
return usage_dd();
}
ddBin *dd;
switch(argc) {
case 4:
dd = new ddBin(argv[2], argv[3]);
break;
case 5:
dd = new ddBin(argv[2], argv[3], argv[4]);
break;
case 6:
dd = new ddBin(argv[2], argv[3], argv[4], argv[5]);
break;
}
dd->dd();
return 0;
}
/* check argc */
if((2 != argc) && (3 != argc)) {
return usage();
}
/* check input file */
if (-1 == access(argv[1], 0)) {
cout << "file:" << argv[1] << " not exist" << endl;
return 0;
}
fillVal * pf = NULL;
if(argc == 3) {
pf = new fillVal(argv[1], argv[2]);
} else {
pf = new fillVal(argv[1]);
}
pf->fill_size();
pf->fill_version();
return 0;
}
| 23.514925 | 81 | 0.449064 |
6c97f885ad15183170d14e65e2a69c1f73357736 | 3,632 | cpp | C++ | src/kgw.cpp | Warants/whosa | ff46f1e5158c29601f8a83f9de77be1eca95f9f2 | [
"MIT"
] | 13 | 2017-09-17T16:54:25.000Z | 2021-03-19T11:58:16.000Z | src/kgw.cpp | Warants/whosa | ff46f1e5158c29601f8a83f9de77be1eca95f9f2 | [
"MIT"
] | 7 | 2015-01-20T07:44:53.000Z | 2021-11-26T18:58:38.000Z | src/kgw.cpp | Warants/whosa | ff46f1e5158c29601f8a83f9de77be1eca95f9f2 | [
"MIT"
] | 2 | 2018-01-02T16:49:00.000Z | 2018-05-17T10:58:28.000Z | // Copyright (c) 2015-2015 The e-Gulden developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <math.h>
#include "chain.h"
#include "chainparams.h"
#include "primitives/block.h"
#include "uint256.h"
#include "util.h"
unsigned int KimotoGravityWell(const CBlockIndex* pindexLast, uint64_t TargetBlockSpacingSeconds, uint64_t PastBlocksMin, uint64_t PastBlocksMax, const Consensus::Params& params)
{
const CBlockIndex *BlockLastSolved = pindexLast;
const CBlockIndex *BlockReading = pindexLast;
uint64_t PastBlocksMass = 0;
int64_t PastRateActualSeconds = 0;
int64_t PastRateTargetSeconds = 0;
double PastRateAdjustmentRatio = double(1);
arith_uint256 PastDifficultyAverage, PastDifficultyAveragePrev;
double EventHorizonDeviation, EventHorizonDeviationFast, EventHorizonDeviationSlow;
if(BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || (uint64_t) BlockLastSolved->nHeight < PastBlocksMin)
return UintToArith256(params.powLimit).GetCompact();
for(unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++)
{
if(PastBlocksMax > 0 && i > PastBlocksMax) break;
PastBlocksMass++;
PastDifficultyAverage.SetCompact(BlockReading->nBits);
if(i > 1) {
if(PastDifficultyAverage >= PastDifficultyAveragePrev) {
PastDifficultyAverage = ((PastDifficultyAverage - PastDifficultyAveragePrev) / i) + PastDifficultyAveragePrev;
} else {
PastDifficultyAverage = PastDifficultyAveragePrev - ((PastDifficultyAveragePrev - PastDifficultyAverage) / i);
}
}
PastDifficultyAveragePrev = PastDifficultyAverage;
PastRateActualSeconds = BlockLastSolved->GetBlockTime() - BlockReading->GetBlockTime();
PastRateTargetSeconds = TargetBlockSpacingSeconds * PastBlocksMass;
PastRateActualSeconds = (PastRateActualSeconds < 0) ? 0 : PastRateActualSeconds;
PastRateAdjustmentRatio = (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0)
? double(PastRateTargetSeconds) / double(PastRateActualSeconds)
: double(1);
EventHorizonDeviation = 1 + (0.7084 * pow((double(PastBlocksMass) / double(144)), -1.228));
EventHorizonDeviationFast = EventHorizonDeviation;
EventHorizonDeviationSlow = 1 / EventHorizonDeviation;
if((PastBlocksMass >= PastBlocksMin
&& (PastRateAdjustmentRatio <= EventHorizonDeviationSlow || PastRateAdjustmentRatio >= EventHorizonDeviationFast))
|| (BlockReading->pprev == NULL)) {
assert(BlockReading);
break;
}
BlockReading = BlockReading->pprev;
}
arith_uint256 bnNew(PastDifficultyAverage);
if(PastRateActualSeconds != 0 && PastRateTargetSeconds != 0)
{
bnNew *= PastRateActualSeconds;
bnNew /= PastRateTargetSeconds;
}
const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);
if(bnNew > bnPowLimit) {
bnNew = bnPowLimit;
}
// Debug
/*
LogPrintf("Difficulty Retarget - Kimoto Gravity Well [Block: %d]\n", pindexLast->nHeight);
LogPrintf("PastRateAdjustmentRatio = %g\n", PastRateAdjustmentRatio);
LogPrintf("Before: %08x %s\n", pindexLast->nBits, uint256().SetCompact(pindexLast->nBits).ToString().c_str());
LogPrintf("After: %08x %s\n", bnNew.GetCompact(), bnNew.ToString().c_str());
*/
return bnNew.GetCompact();
}
| 39.912088 | 178 | 0.683645 |
6c9c7eeaeeae6c6002e13a0d123fb399a645e383 | 414 | hpp | C++ | addons/handhelds/rf7800/CfgVehicles.hpp | MrDj200/task-force-arma-3-radio | 21bb54d5d0e0b31b0522dc67e6923edb9ad85247 | [
"RSA-MD"
] | 300 | 2015-01-14T11:19:48.000Z | 2022-01-18T19:46:55.000Z | addons/handhelds/rf7800/CfgVehicles.hpp | MrDj200/task-force-arma-3-radio | 21bb54d5d0e0b31b0522dc67e6923edb9ad85247 | [
"RSA-MD"
] | 742 | 2015-01-07T05:25:39.000Z | 2022-03-15T17:06:34.000Z | addons/handhelds/rf7800/CfgVehicles.hpp | MrDj200/task-force-arma-3-radio | 21bb54d5d0e0b31b0522dc67e6923edb9ad85247 | [
"RSA-MD"
] | 280 | 2015-01-01T08:58:00.000Z | 2022-03-23T12:37:38.000Z | class Item_TFAR_rf7800str: Item_Base_F {
scope = PUBLIC;
scopeCurator = PUBLIC;
displayName = "RF-7800S-TR";
author = "Nkey";
vehicleClass = "Items";
class TransportItems {
MACRO_ADDITEM(TFAR_rf7800str,1);
};
#include "\z\tfar\addons\static_radios\edenAttributes.hpp"
};
HIDDEN_CLASS(Item_tf_rf7800str : Item_TFAR_rf7800str); //#Deprecated dummy class for backwards compat
| 31.846154 | 101 | 0.705314 |
6c9c9307cbb8f2accc00f4d6c2b95e578f656b53 | 499 | cpp | C++ | acmicpc/2216.cpp | juseongkr/BOJ | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 7 | 2020-02-03T10:00:19.000Z | 2021-11-16T11:03:57.000Z | acmicpc/2216.cpp | juseongkr/Algorithm-training | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 1 | 2021-01-03T06:58:24.000Z | 2021-01-03T06:58:24.000Z | acmicpc/2216.cpp | juseongkr/Algorithm-training | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 1 | 2020-01-22T14:34:03.000Z | 2020-01-22T14:34:03.000Z | #include <iostream>
using namespace std;
#define MAX 3001
int dp[MAX][MAX];
int main()
{
string s, r;
int a, b, c;
cin >> a >> b >> c >> s >> r;
for (int i=1; i<MAX; ++i)
dp[i][0] = dp[0][i] = i*b;
for (int i=1; i<=s.length(); ++i) {
for (int j=1; j<=r.length(); ++j) {
if (s[i-1] == r[j-1])
dp[i][j] = dp[i-1][j-1] + a;
else
dp[i][j] = max(dp[i-1][j-1] + max(b * 2, c), max(dp[i][j-1], dp[i-1][j]) + b);
}
}
cout << dp[s.length()][r.length()] << '\n';
return 0;
}
| 17.206897 | 82 | 0.452906 |
6c9e0c8de1a52f1b2c3ede08a3d2cecc3760e90f | 2,052 | hpp | C++ | include/example.hpp | m1nuz/modern-cpp-opengl-examples | 6e79d772b12201f5be791d5c00622b0e4ccfe2ea | [
"MIT"
] | null | null | null | include/example.hpp | m1nuz/modern-cpp-opengl-examples | 6e79d772b12201f5be791d5c00622b0e4ccfe2ea | [
"MIT"
] | null | null | null | include/example.hpp | m1nuz/modern-cpp-opengl-examples | 6e79d772b12201f5be791d5c00622b0e4ccfe2ea | [
"MIT"
] | null | null | null | #pragma once
#include <application.hpp>
#include <graphics.hpp>
struct RunExampleAppInfo {
std::string_view title;
std::function<void( )> on_init = []( ) {};
std::function<void( )> on_update = []( ) {};
std::function<void( int, int )> on_present;
std::function<void( )> on_cleanup = []( ) {};
};
class ExampleApp {
public:
ExampleApp( ) = default;
ExampleApp( const ExampleApp& ) = delete;
auto operator=( const ExampleApp& ) -> ExampleApp& = delete;
auto run( const RunExampleAppInfo& info ) -> int {
return _run( info.title, info.on_init, info.on_update, info.on_present, info.on_cleanup );
}
private:
template <typename OnInit, typename OnUpdate, typename OnPresent, typename OnCleanup>
auto _run( std::string_view title, OnInit on_init, OnUpdate on_update, OnPresent on_present, OnCleanup on_cleanup )
-> int {
using namespace std::literals;
glfwSetErrorCallback(
[]( int error, const char* description ) { journal::error( _tag, "Error {} {}", error, description ); } );
if ( !glfwInit( ) )
return EXIT_FAILURE;
atexit( glfwTerminate );
auto window = application::create_window( { .width = 1440, .height = 1080, .title = title } );
if ( !window ) {
journal::error( _tag, "Couldn't create window" );
return EXIT_FAILURE;
}
graphics::default_framebuffer.width = window->width;
graphics::default_framebuffer.height = window->height;
on_init( );
_mainloop.run( std::chrono::milliseconds { 16ms }, on_update, [&]( ) {
if ( application::is_window_closed( *window ) ) {
_mainloop.stop( );
}
on_present( window->width, window->height );
application::process_window( *window );
} );
on_cleanup( );
return EXIT_SUCCESS;
}
static constexpr std::string_view _tag = "Example";
application::Window _window;
application::Mainloop _mainloop;
}; | 31.090909 | 119 | 0.60575 |
6ca08faebb0efa76551de501597b813846bbab56 | 10,679 | cpp | C++ | 3rdparty/openmm/serialization/src/TabulatedFunctionProxies.cpp | merkys/MMB | 0531385b8367405e1188e31c3eef7aa4cc50170b | [
"MIT"
] | 5 | 2020-07-31T17:33:03.000Z | 2022-01-01T19:24:37.000Z | 3rdparty/openmm/serialization/src/TabulatedFunctionProxies.cpp | merkys/MMB | 0531385b8367405e1188e31c3eef7aa4cc50170b | [
"MIT"
] | 11 | 2020-06-16T05:05:42.000Z | 2022-03-30T09:59:14.000Z | 3rdparty/openmm/serialization/src/TabulatedFunctionProxies.cpp | merkys/MMB | 0531385b8367405e1188e31c3eef7aa4cc50170b | [
"MIT"
] | 9 | 2020-01-24T12:02:37.000Z | 2020-10-16T06:23:56.000Z | /* -------------------------------------------------------------------------- *
* OpenMM *
* -------------------------------------------------------------------------- *
* This is part of the OpenMM molecular simulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2014 Stanford University and the Authors. *
* Authors: Peter Eastman *
* Contributors: *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the *
* Software is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *
* THE AUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, *
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR *
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE *
* USE OR OTHER DEALINGS IN THE SOFTWARE. *
* -------------------------------------------------------------------------- */
#include "openmm/serialization/TabulatedFunctionProxies.h"
#include "openmm/serialization/SerializationNode.h"
#include "openmm/TabulatedFunction.h"
#include <sstream>
using namespace OpenMM;
using namespace std;
Continuous1DFunctionProxy::Continuous1DFunctionProxy() : SerializationProxy("Continuous1DFunction") {
}
void Continuous1DFunctionProxy::serialize(const void* object, SerializationNode& node) const {
node.setIntProperty("version", 1);
const Continuous1DFunction& function = *reinterpret_cast<const Continuous1DFunction*>(object);
double min, max;
vector<double> values;
function.getFunctionParameters(values, min, max);
node.setDoubleProperty("min", min);
node.setDoubleProperty("max", max);
SerializationNode& valuesNode = node.createChildNode("Values");
for (auto v : values)
valuesNode.createChildNode("Value").setDoubleProperty("v", v);
}
void* Continuous1DFunctionProxy::deserialize(const SerializationNode& node) const {
if (node.getIntProperty("version") != 1)
throw OpenMMException("Unsupported version number");
const SerializationNode& valuesNode = node.getChildNode("Values");
vector<double> values;
for (auto& child : valuesNode.getChildren())
values.push_back(child.getDoubleProperty("v"));
return new Continuous1DFunction(values, node.getDoubleProperty("min"), node.getDoubleProperty("max"));
}
Continuous2DFunctionProxy::Continuous2DFunctionProxy() : SerializationProxy("Continuous2DFunction") {
}
void Continuous2DFunctionProxy::serialize(const void* object, SerializationNode& node) const {
node.setIntProperty("version", 1);
const Continuous2DFunction& function = *reinterpret_cast<const Continuous2DFunction*>(object);
int xsize, ysize;
double xmin, xmax, ymin, ymax;
vector<double> values;
function.getFunctionParameters(xsize, ysize, values, xmin, xmax, ymin, ymax);
node.setDoubleProperty("xsize", xsize);
node.setDoubleProperty("ysize", ysize);
node.setDoubleProperty("xmin", xmin);
node.setDoubleProperty("xmax", xmax);
node.setDoubleProperty("ymin", ymin);
node.setDoubleProperty("ymax", ymax);
SerializationNode& valuesNode = node.createChildNode("Values");
for (auto v : values)
valuesNode.createChildNode("Value").setDoubleProperty("v", v);
}
void* Continuous2DFunctionProxy::deserialize(const SerializationNode& node) const {
if (node.getIntProperty("version") != 1)
throw OpenMMException("Unsupported version number");
const SerializationNode& valuesNode = node.getChildNode("Values");
vector<double> values;
for (auto& child : valuesNode.getChildren())
values.push_back(child.getDoubleProperty("v"));
return new Continuous2DFunction(node.getIntProperty("xsize"), node.getIntProperty("ysize"), values,
node.getDoubleProperty("xmin"), node.getDoubleProperty("xmax"), node.getDoubleProperty("ymin"), node.getDoubleProperty("ymax"));
}
Continuous3DFunctionProxy::Continuous3DFunctionProxy() : SerializationProxy("Continuous3DFunction") {
}
void Continuous3DFunctionProxy::serialize(const void* object, SerializationNode& node) const {
node.setIntProperty("version", 1);
const Continuous3DFunction& function = *reinterpret_cast<const Continuous3DFunction*>(object);
int xsize, ysize, zsize;
double xmin, xmax, ymin, ymax, zmin, zmax;
vector<double> values;
function.getFunctionParameters(xsize, ysize, zsize, values, xmin, xmax, ymin, ymax, zmin, zmax);
node.setDoubleProperty("xsize", xsize);
node.setDoubleProperty("ysize", ysize);
node.setDoubleProperty("zsize", zsize);
node.setDoubleProperty("xmin", xmin);
node.setDoubleProperty("xmax", xmax);
node.setDoubleProperty("ymin", ymin);
node.setDoubleProperty("ymax", ymax);
node.setDoubleProperty("zmin", zmin);
node.setDoubleProperty("zmax", zmax);
SerializationNode& valuesNode = node.createChildNode("Values");
for (auto v : values)
valuesNode.createChildNode("Value").setDoubleProperty("v", v);
}
void* Continuous3DFunctionProxy::deserialize(const SerializationNode& node) const {
if (node.getIntProperty("version") != 1)
throw OpenMMException("Unsupported version number");
const SerializationNode& valuesNode = node.getChildNode("Values");
vector<double> values;
for (auto& child : valuesNode.getChildren())
values.push_back(child.getDoubleProperty("v"));
return new Continuous3DFunction(node.getIntProperty("xsize"), node.getIntProperty("ysize"), node.getIntProperty("zsize"), values,
node.getDoubleProperty("xmin"), node.getDoubleProperty("xmax"), node.getDoubleProperty("ymin"), node.getDoubleProperty("ymax"),
node.getDoubleProperty("zmin"), node.getDoubleProperty("zmax"));
}
Discrete1DFunctionProxy::Discrete1DFunctionProxy() : SerializationProxy("Discrete1DFunction") {
}
void Discrete1DFunctionProxy::serialize(const void* object, SerializationNode& node) const {
node.setIntProperty("version", 1);
const Discrete1DFunction& function = *reinterpret_cast<const Discrete1DFunction*>(object);
vector<double> values;
function.getFunctionParameters(values);
SerializationNode& valuesNode = node.createChildNode("Values");
for (auto v : values)
valuesNode.createChildNode("Value").setDoubleProperty("v", v);
}
void* Discrete1DFunctionProxy::deserialize(const SerializationNode& node) const {
if (node.getIntProperty("version") != 1)
throw OpenMMException("Unsupported version number");
const SerializationNode& valuesNode = node.getChildNode("Values");
vector<double> values;
for (auto& child : valuesNode.getChildren())
values.push_back(child.getDoubleProperty("v"));
return new Discrete1DFunction(values);
}
Discrete2DFunctionProxy::Discrete2DFunctionProxy() : SerializationProxy("Discrete2DFunction") {
}
void Discrete2DFunctionProxy::serialize(const void* object, SerializationNode& node) const {
node.setIntProperty("version", 1);
const Discrete2DFunction& function = *reinterpret_cast<const Discrete2DFunction*>(object);
int xsize, ysize;
vector<double> values;
function.getFunctionParameters(xsize, ysize, values);
node.setDoubleProperty("xsize", xsize);
node.setDoubleProperty("ysize", ysize);
SerializationNode& valuesNode = node.createChildNode("Values");
for (auto v : values)
valuesNode.createChildNode("Value").setDoubleProperty("v", v);
}
void* Discrete2DFunctionProxy::deserialize(const SerializationNode& node) const {
if (node.getIntProperty("version") != 1)
throw OpenMMException("Unsupported version number");
const SerializationNode& valuesNode = node.getChildNode("Values");
vector<double> values;
for (auto& child : valuesNode.getChildren())
values.push_back(child.getDoubleProperty("v"));
return new Discrete2DFunction(node.getIntProperty("xsize"), node.getIntProperty("ysize"), values);
}
Discrete3DFunctionProxy::Discrete3DFunctionProxy() : SerializationProxy("Discrete3DFunction") {
}
void Discrete3DFunctionProxy::serialize(const void* object, SerializationNode& node) const {
node.setIntProperty("version", 1);
const Discrete3DFunction& function = *reinterpret_cast<const Discrete3DFunction*>(object);
int xsize, ysize, zsize;
vector<double> values;
function.getFunctionParameters(xsize, ysize, zsize, values);
node.setDoubleProperty("xsize", xsize);
node.setDoubleProperty("ysize", ysize);
node.setDoubleProperty("zsize", zsize);
SerializationNode& valuesNode = node.createChildNode("Values");
for (auto v : values)
valuesNode.createChildNode("Value").setDoubleProperty("v", v);
}
void* Discrete3DFunctionProxy::deserialize(const SerializationNode& node) const {
if (node.getIntProperty("version") != 1)
throw OpenMMException("Unsupported version number");
const SerializationNode& valuesNode = node.getChildNode("Values");
vector<double> values;
for (auto& child : valuesNode.getChildren())
values.push_back(child.getDoubleProperty("v"));
return new Discrete3DFunction(node.getIntProperty("xsize"), node.getIntProperty("ysize"), node.getIntProperty("zsize"), values);
}
| 51.095694 | 140 | 0.679183 |
6cab74507e15993510bc4f9bf6f18d5cd7894d44 | 1,227 | cpp | C++ | spicetrade/playaction.cpp | mvaganov/spicetrade | 123b009365deb5b8dcdfc4a2f2dd7b28fa2f024e | [
"Unlicense"
] | null | null | null | spicetrade/playaction.cpp | mvaganov/spicetrade | 123b009365deb5b8dcdfc4a2f2dd7b28fa2f024e | [
"Unlicense"
] | null | null | null | spicetrade/playaction.cpp | mvaganov/spicetrade | 123b009365deb5b8dcdfc4a2f2dd7b28fa2f024e | [
"Unlicense"
] | null | null | null | #include "playaction.h"
#include "game.h"
#include "playerstate.h"
void PlayAction::PrintAction (Game& g, const PlayAction* a, int bg) {
int ofcolor = CLI::getFcolor (), obcolor = CLI::getBcolor ();
CLI::setColor (CLI::COLOR::LIGHT_GRAY, bg);
const int width = 5;
std::string str = a?a->input:"";
int leadSpace = width - str.length ();
for (int i = 0; i < leadSpace; ++i) { CLI::putchar (' '); }
for (int i = 0; i < str.length (); ++i) {
CLI::setColor (g.ColorOfRes (str[i]), bg);
CLI::putchar (str[i]);
}
CLI::setColor (CLI::COLOR::LIGHT_GRAY, bg);
CLI::putchar (':');
str = a?a->output:"";
leadSpace = width - str.length ();
for (int i = 0; i < str.length (); ++i) {
CLI::setColor (g.ColorOfRes (str[i]), bg);
CLI::putchar (str[i]);
}
CLI::setColor (CLI::COLOR::LIGHT_GRAY, bg);
for (int i = 0; i < leadSpace; ++i) { CLI::putchar (' '); }
CLI::setColor (ofcolor, obcolor);
}
void PlayAction::DoIt(Game& g, Player& p, const PlayAction* a) {
Player::SubtractResources (g, a->input, p.inventory);
Player::AddResources (g, p.upgradeChoices, a->output, p.inventory, p.hand, p.played);
p.hand.RemoveAt (p.currentRow);
if (a->output == "cards") {
p.hand.Add (a);
} else {
p.played.Add (a);
}
}
| 30.675 | 86 | 0.613692 |
6cab7fa05d581a570217933c054ae37ae60cda3c | 2,236 | cpp | C++ | ege/ege3d/tests/Primitives.cpp | sppmacd/ege | a82ff6fccc8ac1bce5a50ed5a8f101b63f58b020 | [
"MIT"
] | 1 | 2020-12-30T17:21:11.000Z | 2020-12-30T17:21:11.000Z | ege/ege3d/tests/Primitives.cpp | sppmacd/ege | a82ff6fccc8ac1bce5a50ed5a8f101b63f58b020 | [
"MIT"
] | 20 | 2020-09-02T08:37:13.000Z | 2021-09-02T06:47:08.000Z | ege/ege3d/tests/Primitives.cpp | sppmacd/ege | a82ff6fccc8ac1bce5a50ed5a8f101b63f58b020 | [
"MIT"
] | null | null | null | #include "ege3d/window/GLError.h"
#include <ege3d/window/RenderingState.h>
#include <ege3d/window/SystemEvent.h>
#include <ege3d/window/Renderable.h>
#include <ege3d/window/Renderer.h>
#include <ege/debug/Logger.h>
#include <GL/gl.h>
class MyRenderable : public EGE3d::Renderable
{
public:
virtual void render(EGE3d::RenderingState const& state) override
{
EGE3d::Renderer renderer(state);
renderer.renderRectangle({10, 10, 20, 20}, EGE::Colors::red);
renderer.renderCircle({45, 20}, 10, EGE::Colors::red);
renderer.renderCircle({70, 20}, 10, EGE::Colors::red, 5);
renderer.renderTexturedRectangle({90, 10, 16, 16}, texture, {0, 0, 32, 32});
renderer.renderTexturedRectangle({120, 10, 32, 32}, texture, {0, 0, 32, 32});
}
virtual void updateGeometry() override
{
image = makeUnique<EGE::ColorRGBA[]>(32*32);
for(unsigned x = 0; x < 32; x++)
{
for(unsigned y = 0; y < 32; y++)
{
image[y * 32 + x] = (x+y) % 2 == 0 ? EGE::Colors::green : EGE::Colors::red;
}
}
texture = EGE3d::Texture::createFromColorArray({32, 32}, image.get());
}
private:
EGE3d::Texture texture;
// TODO: Add some EGE3d::Image wrapper for this!!
EGE::UniquePtr<EGE::ColorRGBA[]> image;
};
int main()
{
EGE3d::Window window;
window.create(500, 500, "EGE3d Test", EGE3d::WindowSettings());
glClearColor(0.0, 0.1, 0.0, 0.0);
MyRenderable renderable;
while(window.isOpen())
{
while(true)
{
auto event = window.nextEvent(false);
if(!event.hasValue())
break;
if(event.value().getEventType() == EGE3d::SystemEventType::EClose)
{
window.close();
break;
}
}
// Clear the window
// TODO: Maybe this should also go to states?
glClear(GL_COLOR_BUFFER_BIT);
// Ortho test.
EGE3d::RenderingState state(window);
state.applyClip({500, 500}); // No clip
renderable.fullRender(state);
// Flush the back buffer
window.display();
}
window.close();
return 0;
}
| 27.604938 | 91 | 0.568426 |
6cac158add29e0233fccedc7182d74b1daa8631f | 696 | cpp | C++ | src/acpi/apic/apic.cpp | AlexandreArduino/mykernel | 488a947c87457b11471a06f3fd0544d6145806d7 | [
"BSD-3-Clause"
] | 9 | 2022-01-30T12:54:58.000Z | 2022-01-30T16:51:45.000Z | src/acpi/apic/apic.cpp | AlexandreArduino/mykernel | 488a947c87457b11471a06f3fd0544d6145806d7 | [
"BSD-3-Clause"
] | null | null | null | src/acpi/apic/apic.cpp | AlexandreArduino/mykernel | 488a947c87457b11471a06f3fd0544d6145806d7 | [
"BSD-3-Clause"
] | null | null | null | #include "apic.h"
APIC apic;
void APIC::init(uint64_t *apic_address)
{
if(apic_address == NULL) Exceptions::panic("No APIC table found!");
else this->apic = (struct MADTDescriptor*)apic_address;
log.log("APIC::init", "MADT table located at 0x");
log.logln(String((uint64_t)this->apic, HEXADECIMAL));
// this->mask_all_interrupts();
log.log("APIC::init", "Local APIC address : 0x");
log.logln(String((uint64_t)this->apic->lapic_address, HEXADECIMAL));
}
void APIC::mask_all_interrupts(){
log.logln("APIC::mask_all_interrupts", "Masking all PIC Interrupts...");
asm ("cli");
outb(PIC1_DATA, 0b11111111);
outb(PIC2_DATA, 0b11111111);
asm ("sti");
} | 31.636364 | 76 | 0.672414 |
6cadf170e2336281579a3af94cc8bfd4947efb1f | 2,380 | hpp | C++ | modules/core/base/include/nt2/predicates/functions/arecatcompatible.hpp | psiha/nt2 | 5e829807f6b57b339ca1be918a6b60a2507c54d0 | [
"BSL-1.0"
] | null | null | null | modules/core/base/include/nt2/predicates/functions/arecatcompatible.hpp | psiha/nt2 | 5e829807f6b57b339ca1be918a6b60a2507c54d0 | [
"BSL-1.0"
] | null | null | null | modules/core/base/include/nt2/predicates/functions/arecatcompatible.hpp | psiha/nt2 | 5e829807f6b57b339ca1be918a6b60a2507c54d0 | [
"BSL-1.0"
] | null | null | null | //==============================================================================
// Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2014 LRI UMR 8623 CNRS/Univ Paris Sud XI
// Copyright 2012 - 2014 MetaScale SAS
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_PREDICATES_FUNCTIONS_ARECATCOMPATIBLE_HPP_INCLUDED
#define NT2_PREDICATES_FUNCTIONS_ARECATCOMPATIBLE_HPP_INCLUDED
#include <nt2/include/functor.hpp>
namespace nt2
{
namespace tag
{
/*!
@brief Tag for arecatcompatible functor
**/
struct arecatcompatible_ : ext::abstract_<arecatcompatible_>
{
typedef ext::abstract_<arecatcompatible_> parent;
template<class... Args>
static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args)
BOOST_AUTO_DECLTYPE_BODY( dispatching_arecatcompatible_( ext::adl_helper(), static_cast<Args&&>(args)... ) )
};
}
namespace ext
{
template<class Site, class... Ts>
BOOST_FORCEINLINE generic_dispatcher<tag::arecatcompatible_, Site> dispatching_arecatcompatible_(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...)
{
return generic_dispatcher<tag::arecatcompatible_, Site>();
}
template<class... Args>
struct impl_arecatcompatible_;
}
/*!
@brief Check for concatenation compatibility
For two given expressions and a given dimension, arecatcompatible verifies
that the concatenation of both table along the chosen dimension is valid.
@param a0 First expression to concatenate
@param a1 Second expression to concatenate
@param dim Dimension along which the concatenation is tested
@return a boolean value that evaluates to true if @c a0 and @c a1 can be
concatenated along thier @c dim dimension.
**/
template< class A0, class A1,class D>
BOOST_FORCEINLINE
typename meta::call<tag::arecatcompatible_(A0 const&, A1 const&, D const&)>::type
arecatcompatible(A0 const& a0, A1 const& a1, D const& dim)
{
return typename make_functor<tag::arecatcompatible_,A0>::type()(a0,a1,dim);
}
}
#endif
| 37.1875 | 191 | 0.657563 |
6cb6ea097e8db7ecef00a4aa0fe85d64aeb3890c | 2,569 | cpp | C++ | qfontdialog_c.cpp | mariuszmaximus/qt5pas-aarch64-linux-gnu | c60bbcfa5b0d7c4fe18bb21e5f2f424a5b658c1b | [
"Apache-2.0"
] | null | null | null | qfontdialog_c.cpp | mariuszmaximus/qt5pas-aarch64-linux-gnu | c60bbcfa5b0d7c4fe18bb21e5f2f424a5b658c1b | [
"Apache-2.0"
] | null | null | null | qfontdialog_c.cpp | mariuszmaximus/qt5pas-aarch64-linux-gnu | c60bbcfa5b0d7c4fe18bb21e5f2f424a5b658c1b | [
"Apache-2.0"
] | null | null | null | //******************************************************************************
// Copyright (c) 2005-2013 by Jan Van hijfte
//
// See the included file COPYING.TXT for details about the copyright.
//
// 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.
//******************************************************************************
#include "qfontdialog_c.h"
QFontDialogH QFontDialog_Create(QWidgetH parent)
{
return (QFontDialogH) new QFontDialog((QWidget*)parent);
}
void QFontDialog_Destroy(QFontDialogH handle)
{
delete (QFontDialog *)handle;
}
QFontDialogH QFontDialog_Create2(const QFontH initial, QWidgetH parent)
{
return (QFontDialogH) new QFontDialog(*(const QFont*)initial, (QWidget*)parent);
}
void QFontDialog_setCurrentFont(QFontDialogH handle, const QFontH font)
{
((QFontDialog *)handle)->setCurrentFont(*(const QFont*)font);
}
void QFontDialog_currentFont(QFontDialogH handle, QFontH retval)
{
*(QFont *)retval = ((QFontDialog *)handle)->currentFont();
}
void QFontDialog_selectedFont(QFontDialogH handle, QFontH retval)
{
*(QFont *)retval = ((QFontDialog *)handle)->selectedFont();
}
void QFontDialog_setOption(QFontDialogH handle, QFontDialog::FontDialogOption option, bool on)
{
((QFontDialog *)handle)->setOption(option, on);
}
bool QFontDialog_testOption(QFontDialogH handle, QFontDialog::FontDialogOption option)
{
return (bool) ((QFontDialog *)handle)->testOption(option);
}
void QFontDialog_setOptions(QFontDialogH handle, unsigned int options)
{
((QFontDialog *)handle)->setOptions((QFontDialog::FontDialogOptions)options);
}
unsigned int QFontDialog_options(QFontDialogH handle)
{
return (unsigned int) ((QFontDialog *)handle)->options();
}
void QFontDialog_open(QFontDialogH handle, QObjectH receiver, const char* member)
{
((QFontDialog *)handle)->open((QObject*)receiver, member);
}
void QFontDialog_setVisible(QFontDialogH handle, bool visible)
{
((QFontDialog *)handle)->setVisible(visible);
}
void QFontDialog_getFont(QFontH retval, bool* ok, QWidgetH parent)
{
*(QFont *)retval = QFontDialog::getFont(ok, (QWidget*)parent);
}
void QFontDialog_getFont2(QFontH retval, bool* ok, const QFontH initial, QWidgetH parent, PWideString title, unsigned int options)
{
QString t_title;
copyPWideStringToQString(title, t_title);
*(QFont *)retval = QFontDialog::getFont(ok, *(const QFont*)initial, (QWidget*)parent, t_title, (QFontDialog::FontDialogOptions)options);
}
| 29.872093 | 137 | 0.718178 |
6cb73fda4716b5a9fa5f0a3c719dce99a1759de1 | 21,058 | cpp | C++ | apiwznm/PnlWznmNavJob.cpp | mpsitech/wznm-WhizniumSBE | 4911d561b28392d485c46e98fb915168d82b3824 | [
"MIT"
] | 3 | 2020-09-20T16:24:48.000Z | 2021-12-01T19:44:51.000Z | apiwznm/PnlWznmNavJob.cpp | mpsitech/wznm-WhizniumSBE | 4911d561b28392d485c46e98fb915168d82b3824 | [
"MIT"
] | null | null | null | apiwznm/PnlWznmNavJob.cpp | mpsitech/wznm-WhizniumSBE | 4911d561b28392d485c46e98fb915168d82b3824 | [
"MIT"
] | null | null | null | /**
* \file PnlWznmNavJob.cpp
* API code for job PnlWznmNavJob (implementation)
* \copyright (C) 2016-2020 MPSI Technologies GmbH
* \author Alexander Wirthmueller (auto-generation)
* \date created: 5 Dec 2020
*/
// IP header --- ABOVE
#include "PnlWznmNavJob.h"
using namespace std;
using namespace Sbecore;
using namespace Xmlio;
/******************************************************************************
class PnlWznmNavJob::VecVDo
******************************************************************************/
uint PnlWznmNavJob::VecVDo::getIx(
const string& sref
) {
string s = StrMod::lc(sref);
if (s == "butjobviewclick") return BUTJOBVIEWCLICK;
if (s == "butjobnewcrdclick") return BUTJOBNEWCRDCLICK;
if (s == "butsgeviewclick") return BUTSGEVIEWCLICK;
if (s == "butsgenewcrdclick") return BUTSGENEWCRDCLICK;
if (s == "butmtdviewclick") return BUTMTDVIEWCLICK;
if (s == "butmtdnewcrdclick") return BUTMTDNEWCRDCLICK;
if (s == "butblkviewclick") return BUTBLKVIEWCLICK;
if (s == "butblknewcrdclick") return BUTBLKNEWCRDCLICK;
if (s == "butcalviewclick") return BUTCALVIEWCLICK;
if (s == "butcalnewcrdclick") return BUTCALNEWCRDCLICK;
return(0);
};
string PnlWznmNavJob::VecVDo::getSref(
const uint ix
) {
if (ix == BUTJOBVIEWCLICK) return("ButJobViewClick");
if (ix == BUTJOBNEWCRDCLICK) return("ButJobNewcrdClick");
if (ix == BUTSGEVIEWCLICK) return("ButSgeViewClick");
if (ix == BUTSGENEWCRDCLICK) return("ButSgeNewcrdClick");
if (ix == BUTMTDVIEWCLICK) return("ButMtdViewClick");
if (ix == BUTMTDNEWCRDCLICK) return("ButMtdNewcrdClick");
if (ix == BUTBLKVIEWCLICK) return("ButBlkViewClick");
if (ix == BUTBLKNEWCRDCLICK) return("ButBlkNewcrdClick");
if (ix == BUTCALVIEWCLICK) return("ButCalViewClick");
if (ix == BUTCALNEWCRDCLICK) return("ButCalNewcrdClick");
return("");
};
/******************************************************************************
class PnlWznmNavJob::ContIac
******************************************************************************/
PnlWznmNavJob::ContIac::ContIac(
const uint numFLstJob
, const uint numFLstSge
, const uint numFLstMtd
, const uint numFLstBlk
, const uint numFLstCal
) :
Block()
{
this->numFLstJob = numFLstJob;
this->numFLstSge = numFLstSge;
this->numFLstMtd = numFLstMtd;
this->numFLstBlk = numFLstBlk;
this->numFLstCal = numFLstCal;
mask = {NUMFLSTJOB, NUMFLSTSGE, NUMFLSTMTD, NUMFLSTBLK, NUMFLSTCAL};
};
bool PnlWznmNavJob::ContIac::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "ContIacWznmNavJob");
else
basefound = checkXPath(docctx, basexpath);
string itemtag = "ContitemIacWznmNavJob";
if (basefound) {
if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFLstJob", numFLstJob)) add(NUMFLSTJOB);
if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFLstSge", numFLstSge)) add(NUMFLSTSGE);
if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFLstMtd", numFLstMtd)) add(NUMFLSTMTD);
if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFLstBlk", numFLstBlk)) add(NUMFLSTBLK);
if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFLstCal", numFLstCal)) add(NUMFLSTCAL);
};
return basefound;
};
void PnlWznmNavJob::ContIac::writeXML(
xmlTextWriter* wr
, string difftag
, bool shorttags
) {
if (difftag.length() == 0) difftag = "ContIacWznmNavJob";
string itemtag;
if (shorttags) itemtag = "Ci";
else itemtag = "ContitemIacWznmNavJob";
xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str());
writeUintAttr(wr, itemtag, "sref", "numFLstJob", numFLstJob);
writeUintAttr(wr, itemtag, "sref", "numFLstSge", numFLstSge);
writeUintAttr(wr, itemtag, "sref", "numFLstMtd", numFLstMtd);
writeUintAttr(wr, itemtag, "sref", "numFLstBlk", numFLstBlk);
writeUintAttr(wr, itemtag, "sref", "numFLstCal", numFLstCal);
xmlTextWriterEndElement(wr);
};
set<uint> PnlWznmNavJob::ContIac::comm(
const ContIac* comp
) {
set<uint> items;
if (numFLstJob == comp->numFLstJob) insert(items, NUMFLSTJOB);
if (numFLstSge == comp->numFLstSge) insert(items, NUMFLSTSGE);
if (numFLstMtd == comp->numFLstMtd) insert(items, NUMFLSTMTD);
if (numFLstBlk == comp->numFLstBlk) insert(items, NUMFLSTBLK);
if (numFLstCal == comp->numFLstCal) insert(items, NUMFLSTCAL);
return(items);
};
set<uint> PnlWznmNavJob::ContIac::diff(
const ContIac* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {NUMFLSTJOB, NUMFLSTSGE, NUMFLSTMTD, NUMFLSTBLK, NUMFLSTCAL};
for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it);
return(diffitems);
};
/******************************************************************************
class PnlWznmNavJob::StatApp
******************************************************************************/
PnlWznmNavJob::StatApp::StatApp(
const uint ixWznmVExpstate
, const bool LstJobAlt
, const bool LstSgeAlt
, const bool LstMtdAlt
, const bool LstBlkAlt
, const bool LstCalAlt
, const uint LstJobNumFirstdisp
, const uint LstSgeNumFirstdisp
, const uint LstMtdNumFirstdisp
, const uint LstBlkNumFirstdisp
, const uint LstCalNumFirstdisp
) :
Block()
{
this->ixWznmVExpstate = ixWznmVExpstate;
this->LstJobAlt = LstJobAlt;
this->LstSgeAlt = LstSgeAlt;
this->LstMtdAlt = LstMtdAlt;
this->LstBlkAlt = LstBlkAlt;
this->LstCalAlt = LstCalAlt;
this->LstJobNumFirstdisp = LstJobNumFirstdisp;
this->LstSgeNumFirstdisp = LstSgeNumFirstdisp;
this->LstMtdNumFirstdisp = LstMtdNumFirstdisp;
this->LstBlkNumFirstdisp = LstBlkNumFirstdisp;
this->LstCalNumFirstdisp = LstCalNumFirstdisp;
mask = {IXWZNMVEXPSTATE, LSTJOBALT, LSTSGEALT, LSTMTDALT, LSTBLKALT, LSTCALALT, LSTJOBNUMFIRSTDISP, LSTSGENUMFIRSTDISP, LSTMTDNUMFIRSTDISP, LSTBLKNUMFIRSTDISP, LSTCALNUMFIRSTDISP};
};
bool PnlWznmNavJob::StatApp::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
string srefIxWznmVExpstate;
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StatAppWznmNavJob");
else
basefound = checkXPath(docctx, basexpath);
string itemtag = "StatitemAppWznmNavJob";
if (basefound) {
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "srefIxWznmVExpstate", srefIxWznmVExpstate)) {
ixWznmVExpstate = VecWznmVExpstate::getIx(srefIxWznmVExpstate);
add(IXWZNMVEXPSTATE);
};
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "LstJobAlt", LstJobAlt)) add(LSTJOBALT);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "LstSgeAlt", LstSgeAlt)) add(LSTSGEALT);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "LstMtdAlt", LstMtdAlt)) add(LSTMTDALT);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "LstBlkAlt", LstBlkAlt)) add(LSTBLKALT);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "LstCalAlt", LstCalAlt)) add(LSTCALALT);
if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "LstJobNumFirstdisp", LstJobNumFirstdisp)) add(LSTJOBNUMFIRSTDISP);
if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "LstSgeNumFirstdisp", LstSgeNumFirstdisp)) add(LSTSGENUMFIRSTDISP);
if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "LstMtdNumFirstdisp", LstMtdNumFirstdisp)) add(LSTMTDNUMFIRSTDISP);
if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "LstBlkNumFirstdisp", LstBlkNumFirstdisp)) add(LSTBLKNUMFIRSTDISP);
if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "LstCalNumFirstdisp", LstCalNumFirstdisp)) add(LSTCALNUMFIRSTDISP);
};
return basefound;
};
set<uint> PnlWznmNavJob::StatApp::comm(
const StatApp* comp
) {
set<uint> items;
if (ixWznmVExpstate == comp->ixWznmVExpstate) insert(items, IXWZNMVEXPSTATE);
if (LstJobAlt == comp->LstJobAlt) insert(items, LSTJOBALT);
if (LstSgeAlt == comp->LstSgeAlt) insert(items, LSTSGEALT);
if (LstMtdAlt == comp->LstMtdAlt) insert(items, LSTMTDALT);
if (LstBlkAlt == comp->LstBlkAlt) insert(items, LSTBLKALT);
if (LstCalAlt == comp->LstCalAlt) insert(items, LSTCALALT);
if (LstJobNumFirstdisp == comp->LstJobNumFirstdisp) insert(items, LSTJOBNUMFIRSTDISP);
if (LstSgeNumFirstdisp == comp->LstSgeNumFirstdisp) insert(items, LSTSGENUMFIRSTDISP);
if (LstMtdNumFirstdisp == comp->LstMtdNumFirstdisp) insert(items, LSTMTDNUMFIRSTDISP);
if (LstBlkNumFirstdisp == comp->LstBlkNumFirstdisp) insert(items, LSTBLKNUMFIRSTDISP);
if (LstCalNumFirstdisp == comp->LstCalNumFirstdisp) insert(items, LSTCALNUMFIRSTDISP);
return(items);
};
set<uint> PnlWznmNavJob::StatApp::diff(
const StatApp* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {IXWZNMVEXPSTATE, LSTJOBALT, LSTSGEALT, LSTMTDALT, LSTBLKALT, LSTCALALT, LSTJOBNUMFIRSTDISP, LSTSGENUMFIRSTDISP, LSTMTDNUMFIRSTDISP, LSTBLKNUMFIRSTDISP, LSTCALNUMFIRSTDISP};
for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it);
return(diffitems);
};
/******************************************************************************
class PnlWznmNavJob::StatShr
******************************************************************************/
PnlWznmNavJob::StatShr::StatShr(
const bool LstJobAvail
, const bool ButJobViewActive
, const bool ButJobNewcrdActive
, const bool LstSgeAvail
, const bool ButSgeViewActive
, const bool ButSgeNewcrdActive
, const bool LstMtdAvail
, const bool ButMtdViewActive
, const bool ButMtdNewcrdActive
, const bool LstBlkAvail
, const bool ButBlkViewActive
, const bool ButBlkNewcrdActive
, const bool LstCalAvail
, const bool ButCalViewActive
, const bool ButCalNewcrdActive
) :
Block()
{
this->LstJobAvail = LstJobAvail;
this->ButJobViewActive = ButJobViewActive;
this->ButJobNewcrdActive = ButJobNewcrdActive;
this->LstSgeAvail = LstSgeAvail;
this->ButSgeViewActive = ButSgeViewActive;
this->ButSgeNewcrdActive = ButSgeNewcrdActive;
this->LstMtdAvail = LstMtdAvail;
this->ButMtdViewActive = ButMtdViewActive;
this->ButMtdNewcrdActive = ButMtdNewcrdActive;
this->LstBlkAvail = LstBlkAvail;
this->ButBlkViewActive = ButBlkViewActive;
this->ButBlkNewcrdActive = ButBlkNewcrdActive;
this->LstCalAvail = LstCalAvail;
this->ButCalViewActive = ButCalViewActive;
this->ButCalNewcrdActive = ButCalNewcrdActive;
mask = {LSTJOBAVAIL, BUTJOBVIEWACTIVE, BUTJOBNEWCRDACTIVE, LSTSGEAVAIL, BUTSGEVIEWACTIVE, BUTSGENEWCRDACTIVE, LSTMTDAVAIL, BUTMTDVIEWACTIVE, BUTMTDNEWCRDACTIVE, LSTBLKAVAIL, BUTBLKVIEWACTIVE, BUTBLKNEWCRDACTIVE, LSTCALAVAIL, BUTCALVIEWACTIVE, BUTCALNEWCRDACTIVE};
};
bool PnlWznmNavJob::StatShr::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StatShrWznmNavJob");
else
basefound = checkXPath(docctx, basexpath);
string itemtag = "StatitemShrWznmNavJob";
if (basefound) {
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "LstJobAvail", LstJobAvail)) add(LSTJOBAVAIL);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButJobViewActive", ButJobViewActive)) add(BUTJOBVIEWACTIVE);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButJobNewcrdActive", ButJobNewcrdActive)) add(BUTJOBNEWCRDACTIVE);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "LstSgeAvail", LstSgeAvail)) add(LSTSGEAVAIL);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButSgeViewActive", ButSgeViewActive)) add(BUTSGEVIEWACTIVE);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButSgeNewcrdActive", ButSgeNewcrdActive)) add(BUTSGENEWCRDACTIVE);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "LstMtdAvail", LstMtdAvail)) add(LSTMTDAVAIL);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButMtdViewActive", ButMtdViewActive)) add(BUTMTDVIEWACTIVE);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButMtdNewcrdActive", ButMtdNewcrdActive)) add(BUTMTDNEWCRDACTIVE);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "LstBlkAvail", LstBlkAvail)) add(LSTBLKAVAIL);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButBlkViewActive", ButBlkViewActive)) add(BUTBLKVIEWACTIVE);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButBlkNewcrdActive", ButBlkNewcrdActive)) add(BUTBLKNEWCRDACTIVE);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "LstCalAvail", LstCalAvail)) add(LSTCALAVAIL);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButCalViewActive", ButCalViewActive)) add(BUTCALVIEWACTIVE);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButCalNewcrdActive", ButCalNewcrdActive)) add(BUTCALNEWCRDACTIVE);
};
return basefound;
};
set<uint> PnlWznmNavJob::StatShr::comm(
const StatShr* comp
) {
set<uint> items;
if (LstJobAvail == comp->LstJobAvail) insert(items, LSTJOBAVAIL);
if (ButJobViewActive == comp->ButJobViewActive) insert(items, BUTJOBVIEWACTIVE);
if (ButJobNewcrdActive == comp->ButJobNewcrdActive) insert(items, BUTJOBNEWCRDACTIVE);
if (LstSgeAvail == comp->LstSgeAvail) insert(items, LSTSGEAVAIL);
if (ButSgeViewActive == comp->ButSgeViewActive) insert(items, BUTSGEVIEWACTIVE);
if (ButSgeNewcrdActive == comp->ButSgeNewcrdActive) insert(items, BUTSGENEWCRDACTIVE);
if (LstMtdAvail == comp->LstMtdAvail) insert(items, LSTMTDAVAIL);
if (ButMtdViewActive == comp->ButMtdViewActive) insert(items, BUTMTDVIEWACTIVE);
if (ButMtdNewcrdActive == comp->ButMtdNewcrdActive) insert(items, BUTMTDNEWCRDACTIVE);
if (LstBlkAvail == comp->LstBlkAvail) insert(items, LSTBLKAVAIL);
if (ButBlkViewActive == comp->ButBlkViewActive) insert(items, BUTBLKVIEWACTIVE);
if (ButBlkNewcrdActive == comp->ButBlkNewcrdActive) insert(items, BUTBLKNEWCRDACTIVE);
if (LstCalAvail == comp->LstCalAvail) insert(items, LSTCALAVAIL);
if (ButCalViewActive == comp->ButCalViewActive) insert(items, BUTCALVIEWACTIVE);
if (ButCalNewcrdActive == comp->ButCalNewcrdActive) insert(items, BUTCALNEWCRDACTIVE);
return(items);
};
set<uint> PnlWznmNavJob::StatShr::diff(
const StatShr* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {LSTJOBAVAIL, BUTJOBVIEWACTIVE, BUTJOBNEWCRDACTIVE, LSTSGEAVAIL, BUTSGEVIEWACTIVE, BUTSGENEWCRDACTIVE, LSTMTDAVAIL, BUTMTDVIEWACTIVE, BUTMTDNEWCRDACTIVE, LSTBLKAVAIL, BUTBLKVIEWACTIVE, BUTBLKNEWCRDACTIVE, LSTCALAVAIL, BUTCALVIEWACTIVE, BUTCALNEWCRDACTIVE};
for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it);
return(diffitems);
};
/******************************************************************************
class PnlWznmNavJob::Tag
******************************************************************************/
PnlWznmNavJob::Tag::Tag(
const string& Cpt
, const string& CptJob
, const string& CptSge
, const string& CptMtd
, const string& CptBlk
, const string& CptCal
) :
Block()
{
this->Cpt = Cpt;
this->CptJob = CptJob;
this->CptSge = CptSge;
this->CptMtd = CptMtd;
this->CptBlk = CptBlk;
this->CptCal = CptCal;
mask = {CPT, CPTJOB, CPTSGE, CPTMTD, CPTBLK, CPTCAL};
};
bool PnlWznmNavJob::Tag::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "TagWznmNavJob");
else
basefound = checkXPath(docctx, basexpath);
string itemtag = "TagitemWznmNavJob";
if (basefound) {
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "Cpt", Cpt)) add(CPT);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptJob", CptJob)) add(CPTJOB);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptSge", CptSge)) add(CPTSGE);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptMtd", CptMtd)) add(CPTMTD);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptBlk", CptBlk)) add(CPTBLK);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptCal", CptCal)) add(CPTCAL);
};
return basefound;
};
/******************************************************************************
class PnlWznmNavJob::DpchAppData
******************************************************************************/
PnlWznmNavJob::DpchAppData::DpchAppData(
const string& scrJref
, ContIac* contiac
, const set<uint>& mask
) :
DpchAppWznm(VecWznmVDpch::DPCHAPPWZNMNAVJOBDATA, scrJref)
{
if (find(mask, ALL)) this->mask = {SCRJREF, CONTIAC};
else this->mask = mask;
if (find(this->mask, CONTIAC) && contiac) this->contiac = *contiac;
};
string PnlWznmNavJob::DpchAppData::getSrefsMask() {
vector<string> ss;
string srefs;
if (has(SCRJREF)) ss.push_back("scrJref");
if (has(CONTIAC)) ss.push_back("contiac");
StrMod::vectorToString(ss, srefs);
return(srefs);
};
void PnlWznmNavJob::DpchAppData::writeXML(
xmlTextWriter* wr
) {
xmlTextWriterStartElement(wr, BAD_CAST "DpchAppWznmNavJobData");
xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/wznm");
if (has(SCRJREF)) writeString(wr, "scrJref", scrJref);
if (has(CONTIAC)) contiac.writeXML(wr);
xmlTextWriterEndElement(wr);
};
/******************************************************************************
class PnlWznmNavJob::DpchAppDo
******************************************************************************/
PnlWznmNavJob::DpchAppDo::DpchAppDo(
const string& scrJref
, const uint ixVDo
, const set<uint>& mask
) :
DpchAppWznm(VecWznmVDpch::DPCHAPPWZNMNAVJOBDO, scrJref)
{
if (find(mask, ALL)) this->mask = {SCRJREF, IXVDO};
else this->mask = mask;
this->ixVDo = ixVDo;
};
string PnlWznmNavJob::DpchAppDo::getSrefsMask() {
vector<string> ss;
string srefs;
if (has(SCRJREF)) ss.push_back("scrJref");
if (has(IXVDO)) ss.push_back("ixVDo");
StrMod::vectorToString(ss, srefs);
return(srefs);
};
void PnlWznmNavJob::DpchAppDo::writeXML(
xmlTextWriter* wr
) {
xmlTextWriterStartElement(wr, BAD_CAST "DpchAppWznmNavJobDo");
xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/wznm");
if (has(SCRJREF)) writeString(wr, "scrJref", scrJref);
if (has(IXVDO)) writeString(wr, "srefIxVDo", VecVDo::getSref(ixVDo));
xmlTextWriterEndElement(wr);
};
/******************************************************************************
class PnlWznmNavJob::DpchEngData
******************************************************************************/
PnlWznmNavJob::DpchEngData::DpchEngData() :
DpchEngWznm(VecWznmVDpch::DPCHENGWZNMNAVJOBDATA)
{
feedFLstBlk.tag = "FeedFLstBlk";
feedFLstCal.tag = "FeedFLstCal";
feedFLstJob.tag = "FeedFLstJob";
feedFLstMtd.tag = "FeedFLstMtd";
feedFLstSge.tag = "FeedFLstSge";
};
string PnlWznmNavJob::DpchEngData::getSrefsMask() {
vector<string> ss;
string srefs;
if (has(SCRJREF)) ss.push_back("scrJref");
if (has(CONTIAC)) ss.push_back("contiac");
if (has(FEEDFLSTBLK)) ss.push_back("feedFLstBlk");
if (has(FEEDFLSTCAL)) ss.push_back("feedFLstCal");
if (has(FEEDFLSTJOB)) ss.push_back("feedFLstJob");
if (has(FEEDFLSTMTD)) ss.push_back("feedFLstMtd");
if (has(FEEDFLSTSGE)) ss.push_back("feedFLstSge");
if (has(STATAPP)) ss.push_back("statapp");
if (has(STATSHR)) ss.push_back("statshr");
if (has(TAG)) ss.push_back("tag");
StrMod::vectorToString(ss, srefs);
return(srefs);
};
void PnlWznmNavJob::DpchEngData::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchEngWznmNavJobData");
else
basefound = checkXPath(docctx, basexpath);
if (basefound) {
if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) add(SCRJREF);
if (contiac.readXML(docctx, basexpath, true)) add(CONTIAC);
if (feedFLstBlk.readXML(docctx, basexpath, true)) add(FEEDFLSTBLK);
if (feedFLstCal.readXML(docctx, basexpath, true)) add(FEEDFLSTCAL);
if (feedFLstJob.readXML(docctx, basexpath, true)) add(FEEDFLSTJOB);
if (feedFLstMtd.readXML(docctx, basexpath, true)) add(FEEDFLSTMTD);
if (feedFLstSge.readXML(docctx, basexpath, true)) add(FEEDFLSTSGE);
if (statapp.readXML(docctx, basexpath, true)) add(STATAPP);
if (statshr.readXML(docctx, basexpath, true)) add(STATSHR);
if (tag.readXML(docctx, basexpath, true)) add(TAG);
} else {
contiac = ContIac();
feedFLstBlk.clear();
feedFLstCal.clear();
feedFLstJob.clear();
feedFLstMtd.clear();
feedFLstSge.clear();
statapp = StatApp();
statshr = StatShr();
tag = Tag();
};
};
| 36.495667 | 269 | 0.693181 |