hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6b486945bff46f9ca1f77fd28cefac913519ad71 | 1,963 | cpp | C++ | src/iotjs_debuglog.cpp | chivalry02/iotjs | a7007b88120a020c5ece835811cec9ded48f9f2b | [
"Apache-2.0"
] | null | null | null | src/iotjs_debuglog.cpp | chivalry02/iotjs | a7007b88120a020c5ece835811cec9ded48f9f2b | [
"Apache-2.0"
] | null | null | null | src/iotjs_debuglog.cpp | chivalry02/iotjs | a7007b88120a020c5ece835811cec9ded48f9f2b | [
"Apache-2.0"
] | 1 | 2021-01-16T18:15:34.000Z | 2021-01-16T18:15:34.000Z | /* Copyright 2015 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <stdlib.h>
#include "iotjs_debuglog.h"
#ifdef ENABLE_DEBUG_LOG
int iotjs_debug_level = DBGLEV_ERR;
FILE *iotjs_log_stream = stderr;
const char* iotjs_debug_prefix[4] = { "", "ERR", "WRN", "INF" };
#endif // ENABLE_DEBUG_LOG
namespace iotjs {
void InitDebugSettings() {
#ifdef ENABLE_DEBUG_LOG
const char* dbglevel = NULL;
const char* dbglogfile = NULL;
#if defined(__LINUX__)
dbglevel = getenv("IOTJS_DEBUG_LEVEL");
dbglogfile = getenv("IOTJS_DEBUG_LOGFILE");
#endif // defined(__LINUX__)
if (dbglevel) {
iotjs_debug_level = atoi(dbglevel);
if (iotjs_debug_level < 0) iotjs_debug_level = 0;
if (iotjs_debug_level > DBGLEV_INFO) iotjs_debug_level = DBGLEV_INFO;
}
if (dbglogfile) {
FILE* logstream;
logstream = fopen(dbglogfile, "w+");
if (logstream != NULL)
iotjs_log_stream = logstream;
}
//fprintf(stderr, "DBG LEV = %d", iotjs_debug_level);
//fprintf(stderr, "DBG OUT = %s", (dbglogfile==NULL?"(stderr)":dbglogfile));
#endif // ENABLE_DEBUG_LOG
}
void ReleaseDebugSettings() {
#ifdef ENABLE_DEBUG_LOG
if (iotjs_log_stream != stderr || iotjs_log_stream != stdout) {
fclose(iotjs_log_stream);
}
// some embed systems(ex, nuttx) may need this
iotjs_log_stream = stderr;
iotjs_debug_level = DBGLEV_ERR;
#endif // ENABLE_DEBUG_LOG
}
} // namespace iotjs
| 29.298507 | 78 | 0.715741 | chivalry02 |
6b49546ec6903b975f88349a4d398c7fab8a221f | 7,373 | hpp | C++ | ThirdParty-mod/java2cpp/android/content/pm/PackageStats.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | 1 | 2019-04-03T01:53:28.000Z | 2019-04-03T01:53:28.000Z | ThirdParty-mod/java2cpp/android/content/pm/PackageStats.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | null | null | null | ThirdParty-mod/java2cpp/android/content/pm/PackageStats.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | null | null | null | /*================================================================================
code generated by: java2cpp
author: Zoran Angelov, mailto://baldzar@gmail.com
class: android.content.pm.PackageStats
================================================================================*/
#ifndef J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_ANDROID_CONTENT_PM_PACKAGESTATS_HPP_DECL
#define J2CPP_ANDROID_CONTENT_PM_PACKAGESTATS_HPP_DECL
namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace java { namespace lang { class String; } } }
namespace j2cpp { namespace android { namespace os { class Parcel; } } }
namespace j2cpp { namespace android { namespace os { class Parcelable; } } }
namespace j2cpp { namespace android { namespace os { namespace Parcelable_ { class Creator; } } } }
#include <android/os/Parcel.hpp>
#include <android/os/Parcelable.hpp>
#include <java/lang/Object.hpp>
#include <java/lang/String.hpp>
namespace j2cpp {
namespace android { namespace content { namespace pm {
class PackageStats;
class PackageStats
: public object<PackageStats>
{
public:
J2CPP_DECLARE_CLASS
J2CPP_DECLARE_METHOD(0)
J2CPP_DECLARE_METHOD(1)
J2CPP_DECLARE_METHOD(2)
J2CPP_DECLARE_METHOD(3)
J2CPP_DECLARE_METHOD(4)
J2CPP_DECLARE_METHOD(5)
J2CPP_DECLARE_METHOD(6)
J2CPP_DECLARE_FIELD(0)
J2CPP_DECLARE_FIELD(1)
J2CPP_DECLARE_FIELD(2)
J2CPP_DECLARE_FIELD(3)
J2CPP_DECLARE_FIELD(4)
explicit PackageStats(jobject jobj)
: object<PackageStats>(jobj)
, packageName(jobj)
, codeSize(jobj)
, dataSize(jobj)
, cacheSize(jobj)
{
}
operator local_ref<java::lang::Object>() const;
operator local_ref<android::os::Parcelable>() const;
PackageStats(local_ref< java::lang::String > const&);
PackageStats(local_ref< android::os::Parcel > const&);
PackageStats(local_ref< android::content::pm::PackageStats > const&);
local_ref< java::lang::String > toString();
jint describeContents();
void writeToParcel(local_ref< android::os::Parcel > const&, jint);
field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(0), J2CPP_FIELD_SIGNATURE(0), local_ref< java::lang::String > > packageName;
field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(1), J2CPP_FIELD_SIGNATURE(1), jlong > codeSize;
field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(2), J2CPP_FIELD_SIGNATURE(2), jlong > dataSize;
field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(3), J2CPP_FIELD_SIGNATURE(3), jlong > cacheSize;
static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(4), J2CPP_FIELD_SIGNATURE(4), local_ref< android::os::Parcelable_::Creator > > CREATOR;
}; //class PackageStats
} //namespace pm
} //namespace content
} //namespace android
} //namespace j2cpp
#endif //J2CPP_ANDROID_CONTENT_PM_PACKAGESTATS_HPP_DECL
#else //J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_ANDROID_CONTENT_PM_PACKAGESTATS_HPP_IMPL
#define J2CPP_ANDROID_CONTENT_PM_PACKAGESTATS_HPP_IMPL
namespace j2cpp {
android::content::pm::PackageStats::operator local_ref<java::lang::Object>() const
{
return local_ref<java::lang::Object>(get_jobject());
}
android::content::pm::PackageStats::operator local_ref<android::os::Parcelable>() const
{
return local_ref<android::os::Parcelable>(get_jobject());
}
android::content::pm::PackageStats::PackageStats(local_ref< java::lang::String > const &a0)
: object<android::content::pm::PackageStats>(
call_new_object<
android::content::pm::PackageStats::J2CPP_CLASS_NAME,
android::content::pm::PackageStats::J2CPP_METHOD_NAME(0),
android::content::pm::PackageStats::J2CPP_METHOD_SIGNATURE(0)
>(a0)
)
, packageName(get_jobject())
, codeSize(get_jobject())
, dataSize(get_jobject())
, cacheSize(get_jobject())
{
}
android::content::pm::PackageStats::PackageStats(local_ref< android::os::Parcel > const &a0)
: object<android::content::pm::PackageStats>(
call_new_object<
android::content::pm::PackageStats::J2CPP_CLASS_NAME,
android::content::pm::PackageStats::J2CPP_METHOD_NAME(1),
android::content::pm::PackageStats::J2CPP_METHOD_SIGNATURE(1)
>(a0)
)
, packageName(get_jobject())
, codeSize(get_jobject())
, dataSize(get_jobject())
, cacheSize(get_jobject())
{
}
android::content::pm::PackageStats::PackageStats(local_ref< android::content::pm::PackageStats > const &a0)
: object<android::content::pm::PackageStats>(
call_new_object<
android::content::pm::PackageStats::J2CPP_CLASS_NAME,
android::content::pm::PackageStats::J2CPP_METHOD_NAME(2),
android::content::pm::PackageStats::J2CPP_METHOD_SIGNATURE(2)
>(a0)
)
, packageName(get_jobject())
, codeSize(get_jobject())
, dataSize(get_jobject())
, cacheSize(get_jobject())
{
}
local_ref< java::lang::String > android::content::pm::PackageStats::toString()
{
return call_method<
android::content::pm::PackageStats::J2CPP_CLASS_NAME,
android::content::pm::PackageStats::J2CPP_METHOD_NAME(3),
android::content::pm::PackageStats::J2CPP_METHOD_SIGNATURE(3),
local_ref< java::lang::String >
>(get_jobject());
}
jint android::content::pm::PackageStats::describeContents()
{
return call_method<
android::content::pm::PackageStats::J2CPP_CLASS_NAME,
android::content::pm::PackageStats::J2CPP_METHOD_NAME(4),
android::content::pm::PackageStats::J2CPP_METHOD_SIGNATURE(4),
jint
>(get_jobject());
}
void android::content::pm::PackageStats::writeToParcel(local_ref< android::os::Parcel > const &a0, jint a1)
{
return call_method<
android::content::pm::PackageStats::J2CPP_CLASS_NAME,
android::content::pm::PackageStats::J2CPP_METHOD_NAME(5),
android::content::pm::PackageStats::J2CPP_METHOD_SIGNATURE(5),
void
>(get_jobject(), a0, a1);
}
static_field<
android::content::pm::PackageStats::J2CPP_CLASS_NAME,
android::content::pm::PackageStats::J2CPP_FIELD_NAME(4),
android::content::pm::PackageStats::J2CPP_FIELD_SIGNATURE(4),
local_ref< android::os::Parcelable_::Creator >
> android::content::pm::PackageStats::CREATOR;
J2CPP_DEFINE_CLASS(android::content::pm::PackageStats,"android/content/pm/PackageStats")
J2CPP_DEFINE_METHOD(android::content::pm::PackageStats,0,"<init>","(Ljava/lang/String;)V")
J2CPP_DEFINE_METHOD(android::content::pm::PackageStats,1,"<init>","(Landroid/os/Parcel;)V")
J2CPP_DEFINE_METHOD(android::content::pm::PackageStats,2,"<init>","(Landroid/content/pm/PackageStats;)V")
J2CPP_DEFINE_METHOD(android::content::pm::PackageStats,3,"toString","()Ljava/lang/String;")
J2CPP_DEFINE_METHOD(android::content::pm::PackageStats,4,"describeContents","()I")
J2CPP_DEFINE_METHOD(android::content::pm::PackageStats,5,"writeToParcel","(Landroid/os/Parcel;I)V")
J2CPP_DEFINE_METHOD(android::content::pm::PackageStats,6,"<clinit>","()V")
J2CPP_DEFINE_FIELD(android::content::pm::PackageStats,0,"packageName","Ljava/lang/String;")
J2CPP_DEFINE_FIELD(android::content::pm::PackageStats,1,"codeSize","J")
J2CPP_DEFINE_FIELD(android::content::pm::PackageStats,2,"dataSize","J")
J2CPP_DEFINE_FIELD(android::content::pm::PackageStats,3,"cacheSize","J")
J2CPP_DEFINE_FIELD(android::content::pm::PackageStats,4,"CREATOR","Landroid/os/Parcelable$Creator;")
} //namespace j2cpp
#endif //J2CPP_ANDROID_CONTENT_PM_PACKAGESTATS_HPP_IMPL
#endif //J2CPP_INCLUDE_IMPLEMENTATION
| 34.134259 | 146 | 0.722094 | kakashidinho |
6b495bf056d46a6feec39ffa963396592ec72858 | 1,393 | cpp | C++ | BZOJ/BZOJ1589.cpp | xehoth/OnlineJudgeCodes | 013d31cccaaa1d2b6d652c2f5d5d6cb2e39884a7 | [
"Apache-2.0"
] | 7 | 2017-09-21T13:20:05.000Z | 2020-03-02T03:03:04.000Z | BZOJ/BZOJ1589.cpp | xehoth/OnlineJudgeCodes | 013d31cccaaa1d2b6d652c2f5d5d6cb2e39884a7 | [
"Apache-2.0"
] | null | null | null | BZOJ/BZOJ1589.cpp | xehoth/OnlineJudgeCodes | 013d31cccaaa1d2b6d652c2f5d5d6cb2e39884a7 | [
"Apache-2.0"
] | 3 | 2019-01-05T07:02:57.000Z | 2019-06-13T08:23:13.000Z | #include <algorithm>
#include <cstdio>
using namespace std;
const int maxn = 100005;
int n, dp[maxn], size[maxn], belong[maxn], next[maxn], to[maxn], dfn[maxn],
low[maxn], clo, tot;
bool ins[maxn];
inline int iread() {
int f = 1, x = 0;
char ch = getchar();
for (; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
for (; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
return f * x;
}
int sta[maxn], top;
inline void tarjan(int x) {
dfn[x] = low[x] = ++clo;
ins[sta[++top] = x] = 1;
if (!dfn[next[x]])
tarjan(next[x]), low[x] = min(low[x], low[next[x]]);
else if (ins[next[x]])
low[x] = min(low[x], dfn[next[x]]);
if (low[x] == dfn[x]) {
tot++;
while (1) {
int u = sta[top--];
belong[u] = tot;
size[tot]++;
ins[u] = 0;
if (u == x) break;
}
}
}
inline int dfs(int x) {
if (dp[x]) return dp[x];
dp[x] = size[x];
if (to[x]) dp[x] += dfs(to[x]);
return dp[x];
}
int main() {
n = iread();
for (int i = 1; i <= n; i++) next[i] = iread();
for (int i = 1; i <= n; i++)
if (!dfn[i]) tarjan(i);
for (int i = 1; i <= n; i++)
if (belong[i] != belong[next[i]]) to[belong[i]] = belong[next[i]];
for (int i = 1; i <= n; i++) printf("%d\n", dfs(belong[i]));
return 0;
} | 24.438596 | 75 | 0.4458 | xehoth |
6b4a4d491d0868c2677c2e25712f00bcda7f9592 | 23,449 | cpp | C++ | CKGfx/NodeRenderer.cpp | samkusin/overview | affddf0b21f7e76ad9dae1425a4f5ac6a29a24c1 | [
"MIT"
] | null | null | null | CKGfx/NodeRenderer.cpp | samkusin/overview | affddf0b21f7e76ad9dae1425a4f5ac6a29a24c1 | [
"MIT"
] | null | null | null | CKGfx/NodeRenderer.cpp | samkusin/overview | affddf0b21f7e76ad9dae1425a4f5ac6a29a24c1 | [
"MIT"
] | null | null | null | //
// NodeRenderer.cpp
// GfxPrototype
//
// Created by Samir Sinha on 10/5/15.
//
//
#include "NodeRenderer.hpp"
#include "ShaderLibrary.hpp"
#include "VertexTypes.hpp"
#include "Material.hpp"
#include "Texture.hpp"
#include "Mesh.hpp"
#include "Animation.hpp"
#include "AnimationController.hpp"
#include "Light.hpp"
#include "RenderTarget.hpp"
#include "Shaders/ckgfx.sh"
#include <ckm/math.hpp>
#include <ckm/geometry.hpp>
#include <bgfx/bgfx.h>
#include <bgfx/bgfx_shader.sh>
#include <bx/fpumath.h>
namespace bx {
inline void mtxQuatRCS(float* __restrict _result, const float* __restrict _quat)
{
const float x = _quat[0];
const float y = _quat[1];
const float z = _quat[2];
const float w = _quat[3];
const float x2 = x + x;
const float y2 = y + y;
const float z2 = z + z;
const float x2x = x2 * x;
const float x2y = x2 * y;
const float x2z = x2 * z;
const float x2w = x2 * w;
const float y2y = y2 * y;
const float y2z = y2 * z;
const float y2w = y2 * w;
const float z2z = z2 * z;
const float z2w = z2 * w;
_result[ 0] = 1.0f - (y2y + z2z);
_result[ 1] = x2y + z2w;
_result[ 2] = x2z - y2w;
_result[ 3] = 0.0f;
_result[ 4] = x2y - z2w;
_result[ 5] = 1.0f - (x2x + z2z);
_result[ 6] = y2z + x2w;
_result[ 7] = 0.0f;
_result[ 8] = x2z + y2w;
_result[ 9] = y2z - x2w;
_result[10] = 1.0f - (x2x + y2y);
_result[11] = 0.0f;
_result[12] = 0.0f;
_result[13] = 0.0f;
_result[14] = 0.0f;
_result[15] = 1.0f;
}
}
namespace cinek {
namespace gfx {
inline void mtxQuatRCS(float* __restrict _result, const float* __restrict _quat)
{
const float x = _quat[0];
const float y = _quat[1];
const float z = _quat[2];
const float w = _quat[3];
const float x2 = x + x;
const float y2 = y + y;
const float z2 = z + z;
const float x2x = x2 * x;
const float x2y = x2 * y;
const float x2z = x2 * z;
const float x2w = x2 * w;
const float y2y = y2 * y;
const float y2z = y2 * z;
const float y2w = y2 * w;
const float z2z = z2 * z;
const float z2w = z2 * w;
_result[ 0] = 1.0f - (y2y + z2z);
_result[ 1] = x2y + z2w;
_result[ 2] = x2z - y2w;
_result[ 3] = 0.0f;
_result[ 4] = x2y - z2w;
_result[ 5] = 1.0f - (x2x + z2z);
_result[ 6] = y2z + x2w;
_result[ 7] = 0.0f;
_result[ 8] = x2z + y2w;
_result[ 9] = y2z - x2w;
_result[10] = 1.0f - (x2x + y2y);
_result[11] = 0.0f;
_result[12] = 0.0f;
_result[13] = 0.0f;
_result[14] = 0.0f;
_result[15] = 1.0f;
}
/*
* Rendering a Node Graph
*
* Given a root Node reference to the contents to be rendered, and a Camera
* used to select nodes for rendering, the renderNodeGraph function generates
* commands executed by the low-level renderer.
*
* Summary
* --------------------------------------------------------------------------
* The function traverses the Node tree pointed to by 'root'. Rendering State
* such as current Transform, Material, etc. is pushed to and popped from
* various stacks during Node traversal.
*
* A Node contributes to current state. Leaf nodes usually point to mesh or
* other primitive data that's sent to the low-level renderer. For example,
* one node may set the current transform, pushing the prior transform to the
* stack. That Transform Node has two Mesh child Nodes. The Render method
* draws each Mesh using the current Transform.
*
* The above demonstrates a *very simple* use case. As the renderer grows,
* we'll add more use-cases.
*
*/
NodeRenderer::NodeRenderer()
{
_nodeStack.reserve(32);
_transformStack.reserve(32);
_armatureStack.reserve(4);
Vector4 zero = Vector4::kZero;
_lightColors.resize(CKGFX_SHADERS_LIGHT_COUNT, zero);
_lightParams.resize(CKGFX_SHADERS_LIGHT_COUNT, zero);
_lightDirs.resize(CKGFX_SHADERS_LIGHT_COUNT, zero);
_lightCoeffs.resize(CKGFX_SHADERS_LIGHT_COUNT, zero);
_lightOrigins.resize(CKGFX_SHADERS_LIGHT_COUNT, zero);
_globalLights.reserve(8);
_directionalLights.reserve(64);
}
void NodeRenderer::setPlaceholderDiffuseTexture(TextureHandle diffuseTexHandle)
{
_placeholderDiffuseTex = diffuseTexHandle;
}
void NodeRenderer::operator()
(
const ProgramMap& programs,
const UniformMap& uniforms,
const Camera& camera,
NodeHandle root,
uint32_t stages /*=kStageAll */
)
{
(*this)(programs, uniforms, RenderTarget(), camera, root, stages);
}
void NodeRenderer::operator()
(
const ProgramMap& programs,
const UniformMap& uniforms,
const RenderTarget& renderTarget,
const Camera& camera,
NodeHandle root,
uint32_t stages /*=kStageAll */
)
{
uint32_t currentStage = 1;
_camera = &camera;
while (stages) {
if ((stages & 0x01)!=0) {
NodeHandle node = root;
Matrix4 topTransform;
bx::mtxIdentity(topTransform);
pushTransform(topTransform);
switch (currentStage) {
case kStageFlagRender: {
bgfx::setViewRect(_camera->viewIndex,
_camera->viewportRect.x, _camera->viewportRect.y,
_camera->viewportRect.w ,_camera->viewportRect.h);
if (renderTarget) {
bgfx::setViewFrameBuffer(_camera->viewIndex, renderTarget.bgfxHandle());
}
bgfx::setViewTransform(_camera->viewIndex,
_camera->viewMtx.comp,
_camera->projMtx.comp);
memcpy(_viewProjMtx.comp, _camera->viewProjMtx.comp, sizeof(_viewProjMtx.comp));
}
break;
case kStageFlagLightEnum: {
_globalLights.clear();
_directionalLights.clear();
}
break;
default:
break;
}
while (!_nodeStack.empty() || node) {
if (node) {
// parse current node
if (currentStage == kStageFlagLightEnum) {
//
// Lighting Pass
//
if (node->elementType() == Node::kElementTypeLight) {
const LightElement* e = node->light();
Matrix4 lightMtx;
bx::mtxMul(lightMtx, node->transform(), _transformStack.back());
if (e->light->type == LightType::kAmbient
|| e->light->type == LightType::kDirectional) {
_globalLights.emplace_back(LightState{ lightMtx, e->light } );
}
else {
_directionalLights.emplace_back(LightState{ lightMtx, e->light });
}
}
}
else if (currentStage == kStageFlagRender) {
//
// Render Pass
//
switch (node->elementType()) {
case Node::kElementTypeArmature: {
const ArmatureElement* armature = node->armature();
ArmatureState state { armature };
bx::mtxMul(state.armatureToWorldMtx, node->transform(),
_transformStack.back());
_armatureStack.emplace_back(state);
}
break;
case Node::kElementTypeMesh: {
const MeshElement* mesh = node->mesh();
while (mesh) {
renderMeshElement(programs, uniforms, node->transform(), *mesh);
mesh = mesh->next;
}
}
break;
case Node::kElementTypeCustom:
break;
default:
break;
}
}
pushTransform(node->transform());
_nodeStack.emplace_back(node);
node = node->firstChildHandle();
}
else {
node = _nodeStack.back();
_nodeStack.pop_back();
popTransform();
// execute cleanup of the parent node
if (currentStage == kStageFlagRender) {
switch (node->elementType()) {
case Node::kElementTypeArmature:
_armatureStack.pop_back();
break;
default:
break;
}
}
node = node->nextSiblingHandle();
}
}
}
popTransform(); // cleanup default top-level transform
stages >>= 1;
currentStage <<= 1;
}
CK_ASSERT(_transformStack.empty());
CK_ASSERT(_nodeStack.empty());
CK_ASSERT(_armatureStack.empty());
}
void NodeRenderer::pushTransform(const Matrix4& mtx)
{
// calculate new transform and set as current state.
if (_transformStack.empty()) {
_transformStack.emplace_back(mtx);
}
else {
// make space for our new transformation matrix and use our
// prior matrix as a basis modified by 'mtx'.
_transformStack.emplace_back();
bx::mtxMul(_transformStack.back().comp,
mtx,
_transformStack[_transformStack.size()-2].comp);
}
}
void NodeRenderer::popTransform()
{
CK_ASSERT(!_transformStack.empty());
_transformStack.pop_back();
}
void NodeRenderer::renderMeshElement
(
const ProgramMap& programs,
const UniformMap& uniforms,
const Matrix4& localTransform,
const MeshElement& element
)
{
// determine program
NodeProgramSlot programSlot = kNodeProgramNone;
const Mesh* mesh = element.mesh.resource();
const bgfx::VertexDecl& meshVertexDecl = VertexTypes::declaration(mesh->format());
if (!_armatureStack.empty()) {
if (mesh->format() == VertexTypes::kVNormal_Tex0_Weights) {
programSlot = kNodeProgramBoneMeshUV;
}
else if (mesh->format() == VertexTypes::kVNormal_Weights) {
programSlot = kNodeProgramBoneMeshColor;
}
}
else {
if (mesh->format() == VertexTypes::kVPosition) {
programSlot = kNodeProgramFlat;
}
else if (mesh->format() == VertexTypes::kVPositionNormal) {
programSlot = kNodeProgramMeshColor;
}
else if (mesh->format() == VertexTypes::kVNormal_Tex0) {
programSlot = kNodeProgramMeshUV;
}
}
CK_ASSERT_RETURN(programSlot != kNodeProgramNone);
// setup rendering state
bgfx::setUniform(uniforms[kNodeUniformColor], element.material->diffuseColor, 1);
// diffuse texture selection
if (element.material->diffuseTex) {
bgfx::TextureHandle texDiffuse = element.material->diffuseTex->bgfxHandle();
bgfx::setTexture(0, uniforms[kNodeUniformTexDiffuse], texDiffuse,
BGFX_TEXTURE_MIN_POINT | BGFX_TEXTURE_MAG_ANISOTROPIC);
}
else {
// if our mesh has uvs but no material texture? use a placeholder
// texture
if (meshVertexDecl.has(bgfx::Attrib::TexCoord0)) {
bgfx::setTexture(0, uniforms[kNodeUniformTexDiffuse],
_placeholderDiffuseTex->bgfxHandle(),
BGFX_TEXTURE_MIN_POINT | BGFX_TEXTURE_MAG_ANISOTROPIC);
}
}
// TODO - include specular color?
Vector4 specular;
specular.x = element.material->specularIntensity;
specular.y = element.material->specularPower;
specular.z = 0;
specular.w = 0;
bgfx::setUniform(uniforms[kNodeUniformMatSpecular], specular);
Matrix4 worldTransform;
// setup lighting
setupLightUniforms(uniforms, worldTransform);
// setup mesh rendering
bgfx::setVertexBuffer(mesh->vertexBuffer());
bgfx::setIndexBuffer(mesh->indexBuffer());
if (!_armatureStack.empty()) {
const ArmatureState& armatureState = _armatureStack.back();
Matrix4 worldViewProjMtx;
bx::mtxMul(worldViewProjMtx, armatureState.armatureToWorldMtx,
_viewProjMtx);
bgfx::setUniform(uniforms[kNodeUniformWorldMtx],
armatureState.armatureToWorldMtx.comp, 1);
bgfx::setUniform(uniforms[kNodeUniformWorldViewProjMtx],
worldViewProjMtx.comp, 1);
bgfx::Transform boneTransforms;
int transformCacheIndex =
bgfx::allocTransform(&boneTransforms, BGFX_CONFIG_MAX_BONES);
//printf("Kf=%d\n", (int)(armatureState.armature->animController->animationTime() * 24));
// worldTransform in this case is to mesh to armature/skeleton transform
// used as the basis for armature to bone transformations
// we reuse rootTransform as both an intermediate matrix for calculation
// and as the root bone transformation
Matrix4 rootTransform;
bx::mtxIdentity(rootTransform);
buildBoneTransforms(armatureState, 0, rootTransform, boneTransforms.data);
bgfx::setTransform(transformCacheIndex,
armatureState.armature->animSet->boneCount());
}
else
{
bx::mtxMul(worldTransform, localTransform, _transformStack.back());
bgfx::setTransform(worldTransform);
}
auto state = BGFX_STATE_RGB_WRITE
| BGFX_STATE_ALPHA_WRITE
| BGFX_STATE_DEPTH_WRITE
| BGFX_STATE_DEPTH_TEST_LESS
| BGFX_STATE_MSAA;
if (mesh->primitiveType() == PrimitiveType::kTriangles) {
state |= BGFX_STATE_CULL_CW;
}
else if (mesh->primitiveType() == PrimitiveType::kLines) {
state |= BGFX_STATE_PT_LINES;
}
else {
CK_ASSERT(false);
}
bgfx::setState(state);
bgfx::submit(_camera->viewIndex, programs[programSlot]);
}
void NodeRenderer::setupLightUniforms
(
const UniformMap& uniforms,
const Matrix4& objWorldMtx
)
{
// reset uniforms generated during the stack traversal
_lightColors.clear();
_lightDirs.clear();
_lightParams.clear();
_lightCoeffs.clear();
_lightOrigins.clear();
for (auto& light : _globalLights) {
const Light* l = light.light.resource();
_lightCoeffs.emplace_back(0.0f, 0.0f, 0.0f, 0.0f);
_lightOrigins.emplace_back(0.0f, 0.0f, 0.0f, 0.0f);
Vector4 color;
_lightColors.emplace_back(fromABGR(l->color));
_lightParams.emplace_back(l->ambientComp, l->diffuseComp, 0.0f, 0.0f);
if (l->type == LightType::kDirectional) {
Vector4 dir;
bx::vec4MulMtx(dir, Vector4::kUnitZ, light.worldMtx);
//bx::vec3Norm(dir, dir);
bx::vec3Neg(dir, dir);
_lightDirs.emplace_back(dir);
}
else {
_lightDirs.emplace_back(0.0f, 0.0f, 0.0f, 0.0f);
}
}
for (auto& light : _directionalLights) {
const Light* l = light.light.resource();
float dist = 0.0f;
float span = 0.0f;
if (l->type == LightType::kPoint || l->type == LightType::kSpot) {
dist = l->distance;
_lightOrigins.emplace_back(light.worldMtx[12],
light.worldMtx[13],
light.worldMtx[14],
0.0f);
if (l->type == LightType::kSpot) {
span = l->cutoff;
}
_lightCoeffs.emplace_back(l->coeff.x, l->coeff.y, l->coeff.z, 0.0f);
}
Vector4 color;
_lightColors.emplace_back(fromABGR(l->color));
_lightParams.emplace_back(l->ambientComp, l->diffuseComp, dist, span);
if (l->type == LightType::kSpot) {
Vector4 dir;
bx::vec4MulMtx(dir, Vector4::kUnitZ, light.worldMtx);
bx::vec3Neg(dir, dir);
_lightDirs.emplace_back(dir);
}
else {
_lightDirs.emplace_back(0.0f, 0.0f, 0.0f, 0.0f);
}
}
if (!_lightColors.empty()) {
bgfx::setUniform(uniforms[kNodeUniformLightColor], _lightColors.data(), (uint16_t)_lightColors.size());
}
if (!_lightParams.empty()) {
bgfx::setUniform(uniforms[kNodeUniformLightParam], _lightParams.data(), (uint16_t)_lightParams.size());
}
if (!_lightDirs.empty()) {
bgfx::setUniform(uniforms[kNodeUniformLightDir], _lightDirs.data(), (uint16_t)_lightDirs.size());
}
if (!_lightOrigins.empty()) {
bgfx::setUniform(uniforms[kNodeUniformLightOrigin], _lightOrigins.data(), (uint16_t)_lightOrigins.size());
}
if (!_lightCoeffs.empty()) {
bgfx::setUniform(uniforms[kNodeUniformLightCoeffs], _lightCoeffs.data(), (uint16_t)_lightCoeffs.size());
}
}
void NodeRenderer::buildBoneTransforms
(
const ArmatureState& armatureState,
int boneIndex,
const Matrix4& parentBoneTransform,
float* outTransforms
)
{
const AnimationSet* animSet = armatureState.armature->animSet.resource();
auto bone = animSet->boneFromIndex(boneIndex);
const AnimationController* animController = armatureState.armature->animController.resource();
const Animation* animation = animController ?
armatureState.armature->animController->animation() :
nullptr;
Matrix4 boneTransform { bone->mtx };
if (animation) {
if (animation->channels[boneIndex].animatedSeqMask) {
//
// Bone transform adjusted by animation
//
const SequenceChannel& seqForBone = animation->channels[boneIndex];
Vector3 scale = { 1.0f, 1.0f, 1.0f };
interpScaleFromSequenceChannel(scale, seqForBone, animController->animationTime());
Matrix4 multMtx;
bx::mtxScale(multMtx, scale.x, scale.y, scale.z);
Matrix4 rotMtx;
if (animation->channels[boneIndex].hasQuaternions()) {
Vector4 boneRotQuat;
bx::quatIdentity(boneRotQuat);
float t = animController->animationTime();
interpQuatRotationFromSequenceChannel(boneRotQuat, seqForBone, t);
//printf("t:%.4f b[%d] => (w,x,y,z)= %.4f, %.4f, %.4f, %.4f\n", t, boneIndex, boneRotQuat[3], boneRotQuat[0], boneRotQuat[1], boneRotQuat[2]);
//boneRotQuat[0] *= -1;
//boneRotQuat[1] *= -1;
//boneRotQuat[2] *= -1;
bx::mtxQuat(rotMtx, boneRotQuat);
}
else if (animation->channels[boneIndex].hasEulers()) {
Vector3 boneRot = { 0,0,0 };
interpEulerRotationFromSequenceChannel(boneRot, seqForBone, animController->animationTime());
//boneRot.x *= -1;
//boneRot.y *= -1;
//boneRot.z *= -1;
bx::mtxRotateXYZ(rotMtx, boneRot.x, boneRot.y, boneRot.z);
}
else {
bx::mtxIdentity(rotMtx);
}
Vector3 translate;
translate.x = 0;
translate.y = 0;
translate.z = 0;
interpTranslateFromSequenceChannel(translate, seqForBone, animController->animationTime());
// Mint = Mrot * Mscale
// Mint = Mint + translate
Matrix4 animMtx;
bx::mtxMul(animMtx, multMtx, rotMtx);
animMtx[12] = translate.x;
animMtx[13] = translate.y;
animMtx[14] = translate.z;
/*
printf("BOld: [%6.4f, %6.4f, %6.4f, %6.4f]\n"
" [%6.4f, %6.4f, %6.4f, %6.4f]\n"
" [%6.4f, %6.4f, %6.4f, %6.4f]\n"
" [%6.4f, %6.4f, %6.4f, %6.4f]\n",
boneTransform[0],boneTransform[4],boneTransform[8],boneTransform[12],
boneTransform[1],boneTransform[5],boneTransform[9],boneTransform[13],
boneTransform[2],boneTransform[6],boneTransform[10],boneTransform[14],
boneTransform[3],boneTransform[7],boneTransform[11],boneTransform[15]);
printf("Anim: [%6.4f, %6.4f, %6.4f, %6.4f]\n"
" [%6.4f, %6.4f, %6.4f, %6.4f]\n"
" [%6.4f, %6.4f, %6.4f, %6.4f]\n"
" [%6.4f, %6.4f, %6.4f, %6.4f]\n",
animMtx[0],animMtx[4],animMtx[8],animMtx[12],
animMtx[1],animMtx[5],animMtx[9],animMtx[13],
animMtx[2],animMtx[6],animMtx[10],animMtx[14],
animMtx[3],animMtx[7],animMtx[11],animMtx[15]);
*/
multMtx = boneTransform;
bx::mtxMul(boneTransform, animMtx, multMtx);
/*
Matrix4 invBoneTransform;
bx::mtxInverse(invBoneTransform, boneTransform);
Matrix4 animLocalMtx;
bx::mtxMul(animLocalMtx, invBoneTransform, animMtx);
Matrix4 tempMtx = boneTransform;
bx::mtxMul(boneTransform, animLocalMtx, tempMtx);
printf("BNew: [%6.4f, %6.4f, %6.4f, %6.4f]\n"
" [%6.4f, %6.4f, %6.4f, %6.4f]\n"
" [%6.4f, %6.4f, %6.4f, %6.4f]\n"
" [%6.4f, %6.4f, %6.4f, %6.4f]\n",
boneTransform[0],boneTransform[4],boneTransform[8],boneTransform[12],
boneTransform[1],boneTransform[5],boneTransform[9],boneTransform[13],
boneTransform[2],boneTransform[6],boneTransform[10],boneTransform[14],
boneTransform[3],boneTransform[7],boneTransform[11],boneTransform[15]);
printf("\n");
*/
}
}
Matrix4 armatureTransform;
bx::mtxMul(armatureTransform, boneTransform, parentBoneTransform);
bx::mtxMul(outTransforms + boneIndex*16, bone->offset, armatureTransform);
for (int childBoneIndex = bone->firstChild;
childBoneIndex >= 0;
childBoneIndex = animSet->boneFromIndex(childBoneIndex)->nextSibling) {
buildBoneTransforms(armatureState, childBoneIndex, armatureTransform, outTransforms);
}
}
} // namespace gfx
} // namespace cinek
| 33.836941 | 159 | 0.541174 | samkusin |
6b4da9c530096baa58f9a044f3be038db9b63f34 | 5,114 | cpp | C++ | lldb/source/Symbol/SymbolFile.cpp | bytesnake/Enzyme | 247606c279920d476645d2e319e574bf8be10fc9 | [
"Apache-2.0"
] | null | null | null | lldb/source/Symbol/SymbolFile.cpp | bytesnake/Enzyme | 247606c279920d476645d2e319e574bf8be10fc9 | [
"Apache-2.0"
] | null | null | null | lldb/source/Symbol/SymbolFile.cpp | bytesnake/Enzyme | 247606c279920d476645d2e319e574bf8be10fc9 | [
"Apache-2.0"
] | null | null | null | //===-- SymbolFile.cpp ------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/Symbol/SymbolFile.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Symbol/TypeMap.h"
#include "lldb/Symbol/TypeSystem.h"
#include "lldb/Symbol/VariableList.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/StreamString.h"
#include "lldb/lldb-private.h"
using namespace lldb_private;
void SymbolFile::PreloadSymbols() {
// No-op for most implementations.
}
SymbolFile *SymbolFile::FindPlugin(ObjectFile *obj_file) {
std::unique_ptr<SymbolFile> best_symfile_ap;
if (obj_file != nullptr) {
// We need to test the abilities of this section list. So create what it
// would be with this new obj_file.
lldb::ModuleSP module_sp(obj_file->GetModule());
if (module_sp) {
// Default to the main module section list.
ObjectFile *module_obj_file = module_sp->GetObjectFile();
if (module_obj_file != obj_file) {
// Make sure the main object file's sections are created
module_obj_file->GetSectionList();
obj_file->CreateSections(*module_sp->GetUnifiedSectionList());
}
}
// TODO: Load any plug-ins in the appropriate plug-in search paths and
// iterate over all of them to find the best one for the job.
uint32_t best_symfile_abilities = 0;
SymbolFileCreateInstance create_callback;
for (uint32_t idx = 0;
(create_callback = PluginManager::GetSymbolFileCreateCallbackAtIndex(
idx)) != nullptr;
++idx) {
std::unique_ptr<SymbolFile> curr_symfile_ap(create_callback(obj_file));
if (curr_symfile_ap.get()) {
const uint32_t sym_file_abilities = curr_symfile_ap->GetAbilities();
if (sym_file_abilities > best_symfile_abilities) {
best_symfile_abilities = sym_file_abilities;
best_symfile_ap.reset(curr_symfile_ap.release());
// If any symbol file parser has all of the abilities, then we should
// just stop looking.
if ((kAllAbilities & sym_file_abilities) == kAllAbilities)
break;
}
}
}
if (best_symfile_ap.get()) {
// Let the winning symbol file parser initialize itself more completely
// now that it has been chosen
best_symfile_ap->InitializeObject();
}
}
return best_symfile_ap.release();
}
TypeList *SymbolFile::GetTypeList() {
if (m_obj_file)
return m_obj_file->GetModule()->GetTypeList();
return nullptr;
}
TypeSystem *SymbolFile::GetTypeSystemForLanguage(lldb::LanguageType language) {
TypeSystem *type_system =
m_obj_file->GetModule()->GetTypeSystemForLanguage(language);
if (type_system)
type_system->SetSymbolFile(this);
return type_system;
}
uint32_t SymbolFile::ResolveSymbolContext(const FileSpec &file_spec,
uint32_t line, bool check_inlines,
uint32_t resolve_scope,
SymbolContextList &sc_list) {
return 0;
}
uint32_t
SymbolFile::FindGlobalVariables(const ConstString &name,
const CompilerDeclContext *parent_decl_ctx,
uint32_t max_matches, VariableList &variables) {
return 0;
}
uint32_t SymbolFile::FindGlobalVariables(const RegularExpression ®ex,
uint32_t max_matches,
VariableList &variables) {
return 0;
}
uint32_t SymbolFile::FindFunctions(const ConstString &name,
const CompilerDeclContext *parent_decl_ctx,
uint32_t name_type_mask,
bool include_inlines, bool append,
SymbolContextList &sc_list) {
if (!append)
sc_list.Clear();
return 0;
}
uint32_t SymbolFile::FindFunctions(const RegularExpression ®ex,
bool include_inlines, bool append,
SymbolContextList &sc_list) {
if (!append)
sc_list.Clear();
return 0;
}
void SymbolFile::GetMangledNamesForFunction(
const std::string &scope_qualified_name,
std::vector<ConstString> &mangled_names) {
return;
}
uint32_t SymbolFile::FindTypes(
const SymbolContext &sc, const ConstString &name,
const CompilerDeclContext *parent_decl_ctx, bool append,
uint32_t max_matches,
llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
TypeMap &types) {
if (!append)
types.Clear();
return 0;
}
size_t SymbolFile::FindTypes(const std::vector<CompilerContext> &context,
bool append, TypeMap &types) {
if (!append)
types.Clear();
return 0;
}
| 33.424837 | 80 | 0.62632 | bytesnake |
6b4ed243dbe916a9d29bc62f50aec92c78146786 | 4,734 | cpp | C++ | code archive/codechef/ROBAGAIN.cpp | brianbbsu/program | c4505f2b8c0b91010e157db914a63c49638516bc | [
"MIT"
] | 4 | 2018-04-08T08:07:58.000Z | 2021-06-07T14:55:24.000Z | code archive/codechef/ROBAGAIN.cpp | brianbbsu/program | c4505f2b8c0b91010e157db914a63c49638516bc | [
"MIT"
] | null | null | null | code archive/codechef/ROBAGAIN.cpp | brianbbsu/program | c4505f2b8c0b91010e157db914a63c49638516bc | [
"MIT"
] | 1 | 2018-10-29T12:37:25.000Z | 2018-10-29T12:37:25.000Z | //{
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef double lf;
typedef pair<ll,ll> ii;
#define REP(i,n) for(ll i=0;i<n;i++)
#define REP1(i,n) for(ll i=1;i<=n;i++)
#define FILL(i,n) memset(i,n,sizeof i)
#define X first
#define Y second
#define SZ(_a) (int)_a.size()
#define ALL(_a) _a.begin(),_a.end()
#define pb push_back
#ifdef brian
#define debug(...) do{\
fprintf(stderr,"%s - %d (%s) = ",__PRETTY_FUNCTION__,__LINE__,#__VA_ARGS__);\
_do(__VA_ARGS__);\
}while(0)
template<typename T>void _do(T &&_x){cerr<<_x<<endl;}
template<typename T,typename ...S> void _do(T &&_x,S &&..._t){cerr<<_x<<" ,";_do(_t...);}
template<typename _a,typename _b> ostream& operator << (ostream &_s,const pair<_a,_b> &_p){return _s<<"("<<_p.X<<","<<_p.Y<<")";}
template<typename It> ostream& _OUTC(ostream &_s,It _ita,It _itb)
{
_s<<"{";
for(It _it=_ita;_it!=_itb;_it++)
{
_s<<(_it==_ita?"":",")<<*_it;
}
_s<<"}";
return _s;
}
template<typename _a> ostream &operator << (ostream &_s,vector<_a> &_c){return _OUTC(_s,ALL(_c));}
template<typename _a> ostream &operator << (ostream &_s,set<_a> &_c){return _OUTC(_s,ALL(_c));}
template<typename _a,typename _b> ostream &operator << (ostream &_s,map<_a,_b> &_c){return _OUTC(_s,ALL(_c));}
template<typename _t> void pary(_t _a,_t _b){_OUTC(cerr,_a,_b);cerr<<endl;}
#define IOS()
#else
#define debug(...)
#define pary(...)
#define endl '\n'
#define IOS() ios_base::sync_with_stdio(0);cin.tie(0);
#endif // brian
//}
const ll MAXn=1e5+5,MAXlg=__lg(MAXn)+2;
const ll MOD=1000000007;
const ll INF=ll(1e15);
ll run(ll l1,ll r1,ll l2,ll r2,ll da,ll db,ll dis)
{
ll a = 0,b = 0;
ll ct = 0;
while(1)
{
if(a == -l1)da = 1;
else if(a == r1)da = -1;
if(b == -l2)db = 1;
else if(b == r2)db = -1;
a += da;
b += db;
if(l1 == 0 && r1 == 0)a = 0;
if(l2 == 0 && r2 == 0)b = 0;
if(a == dis + b){
return 1;
}
if(a == 0 && b == 0)ct++;
if(ct == 4)break;
}
return 0;
}
ll f[10][10][2][2][25];
ll d[MAXn],g[MAXn],vis[MAXn],git;
vector<ll> v[MAXn],vr[MAXn],tp;
void dfs1(ll now)
{
vis[now] = 1;
for(ll k:vr[now])if(!vis[k])dfs1(k);
tp.pb(now);
}
void dfs2(ll now)
{
vis[now] = 1;
g[now] = git;
for(ll k:v[now])if(!vis[k])dfs2(k);
}
int main()
{
IOS();
debug(run(0,1,2,2,1,1,2));
REP(i,10)REP(j,10)REP(k,2)REP(l,2)REP1(d,20)
{
ll a = 0,b = 0,da,db;
if(!k)da = -1;
else da = 1;
if(!l)db = -1;
else db = 1;/*
while(1)
{
if(a == -i)da = 1;
else if(a == i)da = -1;
if(b == -j)db = 1;
else if(b == j)db = -1;
a += da;
b += db;
if(!i)a = 0;
if(!j)b = 0;
if(a == d + b){
f[i][j][k][l][d] = 1;
break;
}
if(a == 0 && b == 0)break;
}*/
f[i][j][k][l][d] = run(i,i,j,j,da,db,d);
}
ll T;
cin>>T;
while(T--)
{
ll n;
string s;
cin>>s;
n = SZ(s);
REP(i,n)
{
if(s[i] == '.')d[i] = -1;
else d[i] = s[i] - '0';
}
REP(i,2 * n)v[i].clear(),vr[i].clear();
git = 0;
REP(i,n)if(d[i] != -1)REP1(j,20)if(i + j < n && d[i+j] != -1)
{
ll t = i + j;
if(i - 9 < 0 || t + 9 >= n)
{
if(run(min(i,d[i]),min(n-i-1,d[i]),min(t,d[t]),min(n-t-1,d[t]),-1,-1,j))v[i].pb(t+n),v[t].pb(i+n);
if(run(min(i,d[i]),min(n-i-1,d[i]),min(t,d[t]),min(n-t-1,d[t]), 1,-1,j))v[i+n].pb(t+n),v[t].pb(i);
if(run(min(i,d[i]),min(n-i-1,d[i]),min(t,d[t]),min(n-t-1,d[t]),-1, 1,j))v[i].pb(t),v[t+n].pb(i+n);
if(run(min(i,d[i]),min(n-i-1,d[i]),min(t,d[t]),min(n-t-1,d[t]), 1, 1,j))v[i+n].pb(t),v[t+n].pb(i);
}
else
{
if(f[d[i]][d[t]][0][0][j])v[i].pb(t+n),v[t].pb(i+n);
if(f[d[i]][d[t]][1][0][j])v[i+n].pb(t+n),v[t].pb(i);
if(f[d[i]][d[t]][0][1][j])v[i].pb(t),v[t+n].pb(i+n);
if(f[d[i]][d[t]][1][1][j])v[i+n].pb(t),v[t+n].pb(i);
}
}
REP(i,2 * n)for(ll x:v[i])vr[x].pb(i);
tp.clear();
REP(i,2*n)vis[i] = 0;
REP(i,2 * n)if(!vis[i])dfs1(i);
reverse(ALL(tp));
REP(i,2*n)vis[i] = 0;
for(ll x:tp)if(!vis[x])
{
dfs2(x);
git ++;
}
bool fg = 0;
REP(i,n)if(g[i] == g[i + n])fg = 1;
if(fg)cout<<"unsafe"<<endl;
else cout<<"safe"<<endl;
}
}
| 27.523256 | 129 | 0.440642 | brianbbsu |
6b4f526ab4dd550cd487e3a3beab70bba9f6d573 | 1,300 | cpp | C++ | src/Tokenizer.cpp | Kahsolt/TuringMachine | a24b4b1c7eca0b89cca228af8f61210d917130ca | [
"WTFPL"
] | null | null | null | src/Tokenizer.cpp | Kahsolt/TuringMachine | a24b4b1c7eca0b89cca228af8f61210d917130ca | [
"WTFPL"
] | null | null | null | src/Tokenizer.cpp | Kahsolt/TuringMachine | a24b4b1c7eca0b89cca228af8f61210d917130ca | [
"WTFPL"
] | null | null | null | #include <iostream>
#include "utils.h"
#include "Exception.h"
#include "Tokenizer.h"
Token Token::EMPTY_TOKEN = Token();
Tokenizer::Tokenizer() : line(nullptr), p(nullptr), use_last_token(false), last_token(Token::EMPTY_TOKEN) { }
void Tokenizer::tokenize(char* line) { this->line = p = line; }
Token Tokenizer::next() {
if (isnull()) return Token::EMPTY_TOKEN;
if (use_last_token) { use_last_token = false; return last_token; }
skip_nonsense(); if (iseol()) return Token::EMPTY_TOKEN;
if (iscmt()) { while (!iseol()) nxt(); return Token::EMPTY_TOKEN; }
else if (ishash()) { nxt(); return Token(ITEM, extract_literal()); }
else if (isliteral()) { return Token(LITERAL, extract_literal()); }
else if (issep()) { nxt(); return Token(SEPERATOR, to_string(ITEM_SEPERATOR)); }
else if (isequal()) { nxt(); return Token(EQUAL, to_string('=')); }
else if (islbracket()) { nxt(); return Token(LBRACKET, to_string('{')); }
else if (isrbracket()) { nxt(); return Token(RBRACKET, to_string('}')); }
throw new SyntaxError("illegal char " + quote(cur()), "?:" + to_string(offset()));
}
inline string Tokenizer::extract_literal() {
sb.str(""); sb.clear();
while (isliteral()) { sb << cur(); nxt(); }
return sb.str();
} | 41.935484 | 110 | 0.626154 | Kahsolt |
6b4ff13897b20a91e4b15ae42f9123a65c01e46c | 279 | hpp | C++ | src/rpc.hpp | skybon/boinc-rpc-cpp | bfb7e238d815167c438a26cdb5cdcd31d0d9acdc | [
"Apache-2.0"
] | 1 | 2016-10-11T06:58:38.000Z | 2016-10-11T06:58:38.000Z | src/rpc.hpp | skybon/boinc-rpc-cpp | bfb7e238d815167c438a26cdb5cdcd31d0d9acdc | [
"Apache-2.0"
] | null | null | null | src/rpc.hpp | skybon/boinc-rpc-cpp | bfb7e238d815167c438a26cdb5cdcd31d0d9acdc | [
"Apache-2.0"
] | null | null | null | #ifndef _RPC_HPP_
#define _RPC_HPP_
#include <string>
#include <glibmm.h>
#include "util.hpp"
namespace Boinc
{
std::string compute_nonce_hash(std::string, std::string);
void query_boinc_daemon(Glib::ustring, int, Glib::ustring, XMLCallback, XMLCallback = nullptr);
}
#endif
| 17.4375 | 95 | 0.756272 | skybon |
6b513ba71885aa370cf6f4d7db79a3a4c821c80a | 3,465 | cxx | C++ | src/core/BeaconSender.cxx | dlopes7/openkit-native | 669871b0f48d85534c3ecfdfca2c9fb6de5811f9 | [
"Apache-2.0"
] | null | null | null | src/core/BeaconSender.cxx | dlopes7/openkit-native | 669871b0f48d85534c3ecfdfca2c9fb6de5811f9 | [
"Apache-2.0"
] | null | null | null | src/core/BeaconSender.cxx | dlopes7/openkit-native | 669871b0f48d85534c3ecfdfca2c9fb6de5811f9 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2018-2019 Dynatrace 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 "BeaconSender.h"
#include <memory>
#include <chrono>
#include "communication/BeaconSendingInitialState.h"
#include "communication/BeaconSendingContext.h"
using namespace core;
using namespace core::communication;
using namespace providers;
constexpr int32_t SHUTDOWN_TIMEOUT_MILLISECONDS = 10 * 1000;
constexpr int32_t SHUTDOWN_SLICED_WAIT_TIME_MILLISECONDS = 100;
BeaconSender::BeaconSender
(
std::shared_ptr<openkit::ILogger> logger,
std::shared_ptr<core::configuration::IHTTPClientConfiguration> httpClientConfiguration,
std::shared_ptr<providers::IHTTPClientProvider> httpClientProvider,
std::shared_ptr<providers::ITimingProvider> timingProvider
)
: mLogger(logger)
, mBeaconSendingContext(
std::make_shared<BeaconSendingContext>(
logger,
httpClientConfiguration,
httpClientProvider,
timingProvider
)
)
, mSendingThread()
, mTimingProvider(timingProvider)
{
}
bool BeaconSender::initialize()
{
mSendingThread = std::async(std::launch::async, [this] {
// run the loop as long as OpenKit does not get shutdown or ends itself.
if (mLogger->isDebugEnabled())
{
mLogger->debug("BeaconSender thread started");
}
while (mBeaconSendingContext != nullptr && !mBeaconSendingContext->isInTerminalState())
{
mBeaconSendingContext->executeCurrentState();
}
if (mLogger->isDebugEnabled())
{
mLogger->debug("BeaconSender thread stopped");
}
return mBeaconSendingContext->isShutdownRequested();
});
return true;
}
bool BeaconSender::waitForInit() const
{
return mBeaconSendingContext->waitForInit();
}
bool BeaconSender::waitForInit(int64_t timeoutMillis) const
{
return mBeaconSendingContext->waitForInit(timeoutMillis);
}
bool BeaconSender::isInitialized() const
{
return mBeaconSendingContext->isInitialized();
}
void BeaconSender::shutdown()
{
if (mLogger->isDebugEnabled())
{
mLogger->debug("BeaconSender thread request shutdown");
}
mBeaconSendingContext->requestShutdown();
auto start = mTimingProvider->provideTimestampInMilliseconds();
int64_t timePassed = 0;
while (timePassed < SHUTDOWN_TIMEOUT_MILLISECONDS)
{
//sleep in slices of 100ms
auto threadStatus = mSendingThread.wait_for(std::chrono::milliseconds(SHUTDOWN_SLICED_WAIT_TIME_MILLISECONDS));
if (threadStatus == std::future_status::ready)
{
return;//thread finished before timeout occurs
}
timePassed = mTimingProvider->provideTimestampInMilliseconds() - start;
}
// if the thread is still running here it will either finish later or killed when the main process is ended
}
int32_t BeaconSender::getCurrentServerID() const
{
return mBeaconSendingContext->getCurrentServerID();
}
void BeaconSender::addSession(std::shared_ptr<core::objects::SessionInternals> session)
{
if (mLogger->isDebugEnabled())
{
mLogger->debug("BeaconSender addSession");
}
mBeaconSendingContext->addSession(session);
}
| 26.450382 | 113 | 0.768831 | dlopes7 |
6b52546edc14d096a393a08a2d8b8909a7e615d4 | 607 | cpp | C++ | XSoftRenderer/src/main.cpp | hovhannest/XSoftRenderer_old | 94458b36998376011ec62f878aac52195a3b414e | [
"MIT"
] | null | null | null | XSoftRenderer/src/main.cpp | hovhannest/XSoftRenderer_old | 94458b36998376011ec62f878aac52195a3b414e | [
"MIT"
] | null | null | null | XSoftRenderer/src/main.cpp | hovhannest/XSoftRenderer_old | 94458b36998376011ec62f878aac52195a3b414e | [
"MIT"
] | null | null | null | //============================================================================
// Name : XSoftwareRenderer.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
using namespace std;
#include "CApp.h"
#include "OpenGlRenderer.h"
int main(int argc, char** argv) {
cout << "Hello World!?" << endl; // prints Hello World!!!
main1(argc, argv);
// CApp app;
//
// app.Init();
//
// app.Run();
//
// app.Release();
return 0;
}
| 20.233333 | 78 | 0.444811 | hovhannest |
6b563fbc9736dc85dbafbdbd9778a831cca39bc9 | 351 | cpp | C++ | 6. Polymorphism/1. Function Overloading/4.OverloadingParameterNumber.cpp | Imran4424/C-Plus-Plus-Object-Oriented | a9c16ce6506b4cc0f3ec82fdf2e750bec50aab79 | [
"MIT"
] | 3 | 2019-11-06T15:43:06.000Z | 2020-06-05T10:47:28.000Z | 6. Polymorphism/1. Function Overloading/4.OverloadingParameterNumber.cpp | Imran4424/C-Plus-Plus-Object-Oriented | a9c16ce6506b4cc0f3ec82fdf2e750bec50aab79 | [
"MIT"
] | null | null | null | 6. Polymorphism/1. Function Overloading/4.OverloadingParameterNumber.cpp | Imran4424/C-Plus-Plus-Object-Oriented | a9c16ce6506b4cc0f3ec82fdf2e750bec50aab79 | [
"MIT"
] | 1 | 2019-09-06T03:37:08.000Z | 2019-09-06T03:37:08.000Z | #include <iostream>
using namespace std;
int Add(int a, int b)
{
return a + b;
}
int Add(int a, int b, int c)
{
return a + b + c;
}
int Add(int a, int b, int c, int d)
{
return a + b + c + d;
}
int main(int argc, char const *argv[])
{
cout << Add(7, 4) << endl;
cout << Add(4, 9, 1) << endl;
cout << Add(1, 11, 9, 8) << endl;
return 0;
} | 12.535714 | 38 | 0.541311 | Imran4424 |
6b58f092dae6be00a0d8c399ca19b210f0d9eac1 | 5,805 | hpp | C++ | lg/solvers/htd-master/include/htd/IteratorWrapper.hpp | vuphan314/dpo | e24fe63fc3321c0cd6d2179c3300596b91082ab5 | [
"MIT"
] | 14 | 2020-01-31T23:02:39.000Z | 2021-12-26T06:00:13.000Z | lg/solvers/htd-master/include/htd/IteratorWrapper.hpp | vuphan314/dpo | e24fe63fc3321c0cd6d2179c3300596b91082ab5 | [
"MIT"
] | 3 | 2020-06-27T21:11:46.000Z | 2020-06-27T21:11:47.000Z | lg/solvers/htd-master/include/htd/IteratorWrapper.hpp | vuphan314/dpo | e24fe63fc3321c0cd6d2179c3300596b91082ab5 | [
"MIT"
] | 2 | 2020-08-08T03:04:30.000Z | 2021-05-21T04:56:02.000Z | /*
* File: IteratorWrapper.hpp
*
* Author: ABSEHER Michael (abseher@dbai.tuwien.ac.at)
*
* Copyright 2015-2017, Michael Abseher
* E-Mail: <abseher@dbai.tuwien.ac.at>
*
* This file is part of htd.
*
* htd is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* htd is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
* License for more details.
* You should have received a copy of the GNU General Public License
* along with htd. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef HTD_HTD_ITERATORWRAPPER_HPP
#define HTD_HTD_ITERATORWRAPPER_HPP
#include <htd/Globals.hpp>
#include <htd/IteratorBase.hpp>
#include <htd/ConstIteratorBase.hpp>
#include <iterator>
namespace htd
{
/**
* Implementation of a wrapper for iterators of mutable collections.
*/
template <typename Iter, typename T = typename Iter::value_type>
class IteratorWrapper : public std::iterator<std::forward_iterator_tag, T>, public htd::IteratorBase<T>
{
public:
/**
* Constructor for an iterator wrapper.
*
* @param[in] baseIterator The underlying iterator which shall be wrapped.
*/
IteratorWrapper(Iter baseIterator) : baseIterator_(baseIterator)
{
}
/**
* Copy constructor for an iterator wrapper.
*
* @param[in] original The original iterator wrapper.
*/
IteratorWrapper<Iter, T>(const IteratorWrapper<Iter, T> & original) : baseIterator_(original.baseIterator_)
{
}
/**
* Move constructor for an iterator wrapper.
*
* @param[in] original The original iterator wrapper.
*/
IteratorWrapper<Iter, T>(IteratorWrapper<Iter, T> && original) : baseIterator_(std::move(original.baseIterator_))
{
}
virtual ~IteratorWrapper()
{
}
/**
* Copy assignment operator for an iterator wrapper.
*
* @param[in] original The original iterator wrapper.
*/
IteratorWrapper & operator=(const IteratorWrapper & original)
{
baseIterator_ = original.baseIterator_;
return *this;
}
IteratorWrapper<Iter, T> & operator++(void) HTD_OVERRIDE
{
++baseIterator_;
return *this;
}
/**
* Increment the iterator.
*
* @return A copy of the iterator reflecting the state before the increment operation took place.
*/
IteratorWrapper<Iter, T> operator++(int)
{
IteratorWrapper<Iter, T> ret(*this);
operator++();
return ret;
}
bool operator==(const htd::IteratorBase<T> & rhs) const HTD_OVERRIDE
{
return baseIterator_ == static_cast<const IteratorWrapper<Iter, T> *>(&rhs)->baseIterator_;
}
/**
* Equality operator for an iterator.
*
* @param[in] rhs The iterator at the right-hand side of the operator.
*
* @return True if the iterator points to the same element as the iterator at the right-hand side of the operator, false otherwise.
*/
bool operator==(const IteratorWrapper<Iter, T> & rhs) const
{
return baseIterator_ == rhs.baseIterator_;
}
bool operator!=(const htd::IteratorBase<T> & rhs) const HTD_OVERRIDE
{
return baseIterator_ != static_cast<const IteratorWrapper<Iter, T> *>(&rhs)->baseIterator_;
}
/**
* Inequality operator for an iterator.
*
* @param[in] rhs The iterator at the right-hand side of the operator.
*
* @return True if the iterator does not point to the same element as the iterator at the right-hand side of the operator, false otherwise.
*/
bool operator!=(const IteratorWrapper<Iter, T> & rhs) const
{
return baseIterator_ != rhs.baseIterator_;
}
T * operator->(void) HTD_OVERRIDE
{
return &(*baseIterator_);
}
/**
* Dereference the iterator.
*
* @return A pointer to the element at the current iterator position.
*/
const T * operator->(void) const
{
return &(*baseIterator_);
}
T & operator*(void) HTD_OVERRIDE
{
return *baseIterator_;
}
/**
* Dereference the iterator.
*
* @return A reference to the element at the current iterator position.
*/
const T & operator*(void) const
{
return *baseIterator_;
}
IteratorWrapper<Iter, T> * clone(void) const HTD_OVERRIDE
{
return new IteratorWrapper<Iter, T>(*this);
}
private:
Iter baseIterator_;
};
}
#endif /* HTD_HTD_ITERATORWRAPPER_HPP */
| 30.87766 | 152 | 0.538157 | vuphan314 |
6b598cd646e7f3c28876d57101b088975900e82b | 831 | hpp | C++ | src/statements/SpawnStatement.hpp | vgsantoniazzi/TinyInterpreter | c7269d50b47a1318989a43d807a40896f182ed16 | [
"MIT"
] | 29 | 2015-11-14T12:26:48.000Z | 2021-01-02T12:47:37.000Z | src/statements/SpawnStatement.hpp | vgsantoniazzi/TinyInterpreter | c7269d50b47a1318989a43d807a40896f182ed16 | [
"MIT"
] | 9 | 2015-06-12T13:58:54.000Z | 2016-06-07T03:00:41.000Z | src/statements/SpawnStatement.hpp | vgsantoniazzi/TinyInterpreter | c7269d50b47a1318989a43d807a40896f182ed16 | [
"MIT"
] | 6 | 2015-06-14T20:39:32.000Z | 2020-07-27T01:14:48.000Z | /**
* @file src/statements/SpawnStatement.hpp
* @author Victor Antoniazzi <vgsantoniazzi@gmail.com>
* @brief Implements threads.
*
* @details Spawn statement will run inside a thread. It will load only the
* next statement.
*/
#ifndef _SPAWN_STATEMENT_
#define _SPAWN_STATEMENT_
#include "Statement.hpp"
#include "../token/Token.hpp"
#include "../tokenizer/Tokenizer.hpp"
class SpawnStatement : public Statement {
public:
/**
* @brief Read a Spawn Statement.
*
* @code
* > spawn < int x = 10;
* @endcode
*
* @param program The tokenizer to understand next steps and eat some tokens.
*/
void Read(Tokenizer &program);
/**
* @brief execute spawn statement.
*/
void Execute() const;
private:
/**
* @brief the statement to be executed in a new thread.
*/
Statement *statement;
};
#endif
| 19.785714 | 78 | 0.68231 | vgsantoniazzi |
6b5a5b0f56816ac5317992325c5dbc5fe05adfa5 | 717 | cpp | C++ | src/effects/effect.cpp | mikelukas/errantry | e1c09ca5ef8bc9ef32cf8bcb86306a1415ddd37c | [
"MIT"
] | 1 | 2018-05-11T16:09:35.000Z | 2018-05-11T16:09:35.000Z | src/effects/effect.cpp | mikelukas/errantry | e1c09ca5ef8bc9ef32cf8bcb86306a1415ddd37c | [
"MIT"
] | null | null | null | src/effects/effect.cpp | mikelukas/errantry | e1c09ca5ef8bc9ef32cf8bcb86306a1415ddd37c | [
"MIT"
] | null | null | null | #include "effect.h"
EffectParams::EffectParams(Element element, Character& applier, Character& target)
: element(element),
applier(applier),
target(target)
{
}
Effect::Effect(const EffectParams& effectParams)
: element(effectParams.element),
applier(effectParams.applier),
target(effectParams.target),
used(false)
{
}
bool Effect::isExpired() const
{
//postcondition: returns true if Effect has been used and is eligible to be
//deallocated, false otherwise.
return used;
}
void Effect::apply()
{
//postcondition: calls runTurnEffect() to run Effect subclasses specific actions
//then sets used to true so callers can know they can delete this Effect.
runTurnEffect();
used = true;
}
| 19.378378 | 82 | 0.736402 | mikelukas |
6b5bb909ae0a4c09fed69e1c452ead29aee4ad66 | 305 | cc | C++ | source/day-22/main.cc | raphaelmeyer/advent-of-code-2020 | c9d2eea98667c03a29ec6f0681ac733455df9dbd | [
"MIT"
] | null | null | null | source/day-22/main.cc | raphaelmeyer/advent-of-code-2020 | c9d2eea98667c03a29ec6f0681ac733455df9dbd | [
"MIT"
] | null | null | null | source/day-22/main.cc | raphaelmeyer/advent-of-code-2020 | c9d2eea98667c03a29ec6f0681ac733455df9dbd | [
"MIT"
] | null | null | null | #include "cards.h"
#include <iostream>
int main() {
auto const start = parse_input(std::cin);
auto const game1 = play(start);
std::cout << "Part I : " << calculate_score(game1) << "\n";
auto const game2 = play_recursive(start);
std::cout << "Part II : " << calculate_score(game2) << "\n";
}
| 21.785714 | 62 | 0.619672 | raphaelmeyer |
6b5da9e300fc148d634211450d21043a68492f12 | 14,273 | cpp | C++ | src/liboslexec/batched_rendservices.cpp | LongerVision/OpenShadingLanguage | 30d2a4a089c5c9d521b27519329c205763dfe483 | [
"BSD-3-Clause"
] | 5 | 2016-04-18T20:25:17.000Z | 2021-09-22T23:36:17.000Z | src/liboslexec/batched_rendservices.cpp | LongerVision/OpenShadingLanguage | 30d2a4a089c5c9d521b27519329c205763dfe483 | [
"BSD-3-Clause"
] | 1 | 2018-05-18T00:19:04.000Z | 2018-05-18T00:19:04.000Z | src/liboslexec/batched_rendservices.cpp | LongerVision/OpenShadingLanguage | 30d2a4a089c5c9d521b27519329c205763dfe483 | [
"BSD-3-Clause"
] | 2 | 2021-08-04T22:07:22.000Z | 2021-08-06T20:20:22.000Z | // Copyright Contributors to the Open Shading Language project.
// SPDX-License-Identifier: BSD-3-Clause
// https://github.com/AcademySoftwareFoundation/OpenShadingLanguage
#include <cstdio>
#include <string>
#include "oslexec_pvt.h"
#include <OSL/batched_rendererservices.h>
using namespace OSL;
using namespace OSL::pvt;
OSL_NAMESPACE_ENTER
template<int WidthT>
BatchedRendererServices<WidthT>::BatchedRendererServices(TextureSystem* texsys)
: m_texturesys(texsys)
{
if (!m_texturesys) {
#if OSL_NO_DEFAULT_TEXTURESYSTEM
// This build option instructs OSL to never create a TextureSystem
// itself. (Most likely reason: this build of OSL is for a renderer
// that replaces OIIO's TextureSystem with its own, and therefore
// wouldn't want to accidentally make an OIIO one here.
OSL_ASSERT(
0 && "RendererServices was not passed a working TextureSystem*");
#else
m_texturesys = TextureSystem::create(true /* shared */);
// Make some good guesses about default options
m_texturesys->attribute("automip", 1);
m_texturesys->attribute("autotile", 64);
#endif
}
}
template<int WidthT>
Mask<WidthT>
BatchedRendererServices<WidthT>::get_matrix(BatchedShaderGlobals* bsg,
Masked<Matrix44> wresult,
Wide<const ustring> wfrom,
Wide<const float> wtime)
{
OSL_ASSERT(
0
&& "UNREACHABLE: BatchedRendererServices<WidthT>::get_matrix calls should be overridden or the target specific version in wide_opmatrix.cpp should be called");
return Mask(false);
}
template<int WidthT>
Mask<WidthT>
BatchedRendererServices<WidthT>::get_inverse_matrix(
BatchedShaderGlobals* bsg, Masked<Matrix44> wresult,
Wide<const TransformationPtr> wxform, Wide<const float> wtime)
{
OSL_ASSERT(
0
&& "UNREACHABLE: BatchedRendererServices<WidthT>::get_inverse_matrix calls should be overridden or the target specific version in wide_opmatrix.cpp should be called");
return Mask(false);
}
template<int WidthT>
Mask<WidthT>
BatchedRendererServices<WidthT>::get_inverse_matrix(BatchedShaderGlobals* bsg,
Masked<Matrix44> wresult,
ustring to,
Wide<const float> wtime)
{
OSL_ASSERT(
0
&& "UNREACHABLE: BatchedRendererServices<WidthT>::get_inverse_matrix calls should be overridden or the target specific version in wide_opmatrix.cpp should be called");
return Mask(false);
}
template<int WidthT>
Mask<WidthT>
BatchedRendererServices<WidthT>::get_inverse_matrix(BatchedShaderGlobals* bsg,
Masked<Matrix44> wresult,
Wide<const ustring> wto,
Wide<const float> wtime)
{
OSL_ASSERT(
0
&& "UNREACHABLE: BatchedRendererServices<WidthT>::get_inverse_matrix calls should be overridden or the target specific version in wide_opmatrix.cpp should be called");
return Mask(false);
}
template<int WidthT>
TextureSystem*
BatchedRendererServices<WidthT>::texturesys() const
{
return m_texturesys;
}
template<int WidthT>
Mask<WidthT>
BatchedRendererServices<WidthT>::get_texture_info(
BatchedShaderGlobals* bsg, TexturePerthread* /*texture_thread_info*/,
Wide<const ustring> wfilename, int subimage, ustring dataname,
MaskedData wval)
{
Mask success(false);
#define TEXTURE_INFO_FOR_TYPE(data_type) \
if (Masked<data_type>::is(wval)) { \
Masked<data_type> out(wval); \
wval.mask().foreach ([=, &success](ActiveLane l) -> void { \
data_type data; \
bool status = texturesys()->get_texture_info(wfilename[l], \
subimage, dataname, \
wval.type(), &data); \
if (status) { \
/* masked assignment */ \
out[l] = data; \
success.set_on(l); \
} else { \
std::string err = texturesys()->geterror(); \
if (err.size() && bsg) { \
/* TODO: enable in future pull request */ \
/* bsg->uniform.context->template batched<WidthT>().errorf (Mask(Lane(l)), "[BatchRendererServices::get_texture_info] %s", err); */ \
} \
} \
}); \
return success; \
}
#define TEXTURE_INFO_FOR_ARRAY(data_type) \
if (Masked<data_type[]>::is(wval)) { \
Masked<data_type[]> out(wval); \
wval.mask().foreach ([=, &success](ActiveLane l) -> void { \
auto arrayData = out[l]; \
OSL_STACK_ARRAY(data_type, data, arrayData.length()); \
bool status = texturesys()->get_texture_info(wfilename[l], \
subimage, dataname, \
wval.type(), data); \
if (status) { \
success.set_on(l); \
/* masked assignment */ \
for (int i = 0; i < arrayData.length(); ++i) { \
arrayData[i] = data[i]; \
} \
} else { \
std::string err = texturesys()->geterror(); \
if (err.size() && bsg) { \
/* TODO: enable in future pull request */ \
/* bsg->uniform.context->template batched<WidthT>().errorf (Mask(Lane(l)), "[BatchRendererServices::get_texture_info] %s", err); */ \
} \
} \
}); \
return success; \
}
TEXTURE_INFO_FOR_TYPE(int);
TEXTURE_INFO_FOR_ARRAY(int);
TEXTURE_INFO_FOR_TYPE(float);
TEXTURE_INFO_FOR_ARRAY(float);
TEXTURE_INFO_FOR_TYPE(Vec2);
TEXTURE_INFO_FOR_TYPE(Vec3);
TEXTURE_INFO_FOR_TYPE(Color3);
TEXTURE_INFO_FOR_TYPE(Matrix44);
TEXTURE_INFO_FOR_TYPE(ustring);
return success;
}
template<int WidthT>
bool
BatchedRendererServices<WidthT>::get_texture_info_uniform(
BatchedShaderGlobals* bsg, TexturePerthread* /*texture_thread_info*/,
ustring filename, TextureSystem::TextureHandle* texture_handle,
int subimage, ustring dataname, RefData val)
{
bool status;
if (texture_handle)
status = texturesys()->get_texture_info(texture_handle, NULL, subimage,
dataname, val.type(),
val.ptr());
else
status = texturesys()->get_texture_info(filename, subimage, dataname,
val.type(), val.ptr());
if (!status) {
std::string err = texturesys()->geterror();
if (err.size() && bsg) {
// TODO: enable in future pull request
// bsg->uniform().context->errorf ("[BatchRendererServices::get_texture_info_uniform] %s", err);
}
}
return status;
}
template<int WidthT>
Mask<WidthT>
BatchedRendererServices<WidthT>::texture(
ustring filename, TextureSystem::TextureHandle* texture_handle,
TextureSystem::Perthread* texture_thread_info,
const BatchedTextureOptions& options, BatchedShaderGlobals* bsg,
Wide<const float> ws, Wide<const float> wt, Wide<const float> wdsdx,
Wide<const float> wdtdx, Wide<const float> wdsdy, Wide<const float> wdtdy,
BatchedTextureOutputs& outputs)
{
OSL_ASSERT(
0
&& "UNREACHABLE: BatchedRendererServices<WidthT>::texture calls should be overridden or the target specific version in wide_optexture.cpp should be called");
return Mask(false);
}
template<int WidthT>
Mask<WidthT>
BatchedRendererServices<WidthT>::texture3d(
ustring filename, TextureSystem::TextureHandle* texture_handle,
TextureSystem::Perthread* texture_thread_info,
const BatchedTextureOptions& options, BatchedShaderGlobals* bsg,
Wide<const Vec3> wP, Wide<const Vec3> wdPdx, Wide<const Vec3> wdPdy,
Wide<const Vec3> wdPdz, BatchedTextureOutputs& outputs)
{
OSL_ASSERT(
0
&& "UNREACHABLE: BatchedRendererServices<WidthT>::texture calls should be overridden or the target specific version in wide_optexture.cpp should be called");
return Mask(false);
}
template<int WidthT>
void
BatchedRendererServices<WidthT>::trace(
TraceOpt& options, BatchedShaderGlobals* bsg, Masked<int> wresult,
Wide<const Vec3> wP, Wide<const Vec3> wdPdx, Wide<const Vec3> wdPdy,
Wide<const Vec3> wR, Wide<const Vec3> wdRdx, Wide<const Vec3> wdRdy)
{
for (int lane = 0; lane < WidthT; ++lane) {
wresult[lane] = 0;
}
}
template<int WidthT>
void
BatchedRendererServices<WidthT>::getmessage(BatchedShaderGlobals* bsg,
Masked<int> wresult, ustring source,
ustring name, MaskedData wval)
{
// Currently this code path should only be followed when source == "trace"
OSL_DASSERT(wresult.mask() == wval.mask());
for (int lane = 0; lane < WidthT; ++lane) {
wresult[lane] = 0;
}
}
// Explicitly instantiate BatchedRendererServices template
template class OSLEXECPUBLIC BatchedRendererServices<16>;
template class OSLEXECPUBLIC BatchedRendererServices<8>;
OSL_NAMESPACE_EXIT
| 55.753906 | 176 | 0.407903 | LongerVision |
6b5ed3e733b74c67687873037bbb2b92a3852506 | 952 | cpp | C++ | chapter19/local_class.cpp | iwiniwin/learncpp | b346c886364c8829647c3359f23a4a7f06989a4d | [
"MIT"
] | null | null | null | chapter19/local_class.cpp | iwiniwin/learncpp | b346c886364c8829647c3359f23a4a7f06989a4d | [
"MIT"
] | null | null | null | chapter19/local_class.cpp | iwiniwin/learncpp | b346c886364c8829647c3359f23a4a7f06989a4d | [
"MIT"
] | null | null | null | /*
* @Author: iwiniwin
* @Date: 2020-12-24 21:36:32
* @Last Modified by: iwiniwin
* @Last Modified time: 2020-12-24 22:34:05
* @Description: 局部类
*/
#include <string>
#include <iostream>
using namespace std;
int a, val;
void test1(int val){
static int si;
enum Loc {a = 1024, b};
// Bar是test1的局部类
struct Bar {
Loc locVal; // 正确,可以使用一个局部类型名
int barVal;
// static int c; // error : 局部类不能含有静态成员,因为没法定义这样的成员
void foo(Loc l = a) { // 正确,默认实参是Loc::a
// barVal = val; // error : val是test1的局部变量,不能访问
barVal = ::val; // 正确,可以及使用全局对象
barVal = si; // 正确,可以使用一个局部静态对象
locVal = b; // 正确,使用一个枚举成员
}
void foo2();
class Nested; // 嵌套类
};
// void Bar::foo2() { // erorr : 局部类的所有成员(包括函数在内)必须完整定义在类的内部
// }
class Bar::Nested {
};
}
int main(){
test1(3);
system("pause");
return 0;
} | 17.962264 | 65 | 0.526261 | iwiniwin |
6b63d2dc1b00073200da3e0d3aab6861f338af5d | 6,142 | hpp | C++ | ql/cashflows/zcinflationcapfloor.hpp | universe1987/QuantLib | bbb0145aff285853755b9f6ed013f53a41163acb | [
"BSD-3-Clause"
] | 4 | 2016-03-28T15:05:23.000Z | 2020-02-17T23:05:57.000Z | ql/cashflows/zcinflationcapfloor.hpp | universe1987/QuantLib | bbb0145aff285853755b9f6ed013f53a41163acb | [
"BSD-3-Clause"
] | 1 | 2015-02-02T20:32:43.000Z | 2015-02-02T20:32:43.000Z | ql/cashflows/zcinflationcapfloor.hpp | pcaspers/quantlib | bbb0145aff285853755b9f6ed013f53a41163acb | [
"BSD-3-Clause"
] | 10 | 2015-01-26T14:50:24.000Z | 2015-10-23T07:41:30.000Z | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2012 Peter Caspers
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*! \file zcinflationcapfloor.hpp
\brief Zero coupon cap / floor
*/
#ifndef quantlib_inflcf_hpp
#define quantlib_inflcf_hpp
#include <ql/cashflow.hpp>
#include <ql/index.hpp>
#include <ql/indexes/inflationindex.hpp>
#include <ql/handle.hpp>
#include <ql/option.hpp>
#include <ql/termstructures/yieldtermstructure.hpp>
#include <ql/termstructures/inflationtermstructure.hpp>
#include <ql/termstructures/volatility/equityfx/blackvoltermstructure.hpp>
#include <ql/math/distributions/normaldistribution.hpp>
namespace QuantLib {
//! Cash flow dependent on an index ratio with cap floor payoff.
/*! This cash flow is not a coupon, i.e., there's no accrual. The
amount is E( max (i(T)/i(0) - (1 + k)^T , 0) ), i.e. the strike
is annualized.
WARNING the volatility is taken from the black vol term structure
naively using strikeand lastFixingDate. If the firstFixingDate is
not the same as for quoted instruments (e.g. evalDate - 3m), this
leads to wrong results. Todo - adjust strike in this case before
reading off the vol from the ts
*/
class ZCInflationCapFloor : public CashFlow, public Observer {
public:
ZCInflationCapFloor(Real notional,
const boost::shared_ptr<ZeroInflationIndex> &index,
const Handle<YieldTermStructure> &nominalYts,
const Handle<ZeroInflationTermStructure> &inflationYts,
const Handle<BlackVolTermStructure> &inflationVol,
const Date &firstFixingDate, const Date &lastFixingDate,
const Date &paymentDate, const Real strike,
const Option::Type type,
const DayCounter &dc = Actual365Fixed(),
const Date &lastKnownFixingDate = Null<Date>()) // if not set, use base date from inflation ts
: notional_(notional), index_(index), firstFixingDate_(firstFixingDate),
lastFixingDate_(lastFixingDate), paymentDate_(paymentDate),
nominalYts_(nominalYts), inflationYts_(inflationYts),
inflationVol_(inflationVol), strike_(strike), type_(type),
dc_(dc) {
// compute actual fixing dates out of first and last fixing dates
if (index_->interpolated()) {
actualFirstFixingDate_ = inflationYts_->calendar().advance(
firstFixingDate_, -inflationYts_->observationLag());
actualLastFixingDate_ = inflationYts_->calendar().advance(
lastFixingDate_, -inflationYts_->observationLag());
} else {
std::pair<Date, Date> dd =
inflationPeriod(firstFixingDate_ - inflationYts_->observationLag(),
index_->frequency());
actualFirstFixingDate_ = dd.first;
dd = inflationPeriod(lastFixingDate_ -
inflationYts_->observationLag(),
index_->frequency());
actualLastFixingDate_ = dd.first;
}
fixingTime_ = inflationVol_->dayCounter().yearFraction(
lastKnownFixingDate == Null<Date>() ? inflationYts_->baseDate()
: lastKnownFixingDate,
actualLastFixingDate_);
// registerWith(index);
registerWith(nominalYts);
registerWith(inflationYts);
}
//! \name Event interface
//@{
Date date() const { return paymentDate_; }
//@}
virtual Real notional() const { return notional_; }
virtual Date actualFirstFixingDate() const { return actualFirstFixingDate_; }
virtual Date actualLastFixingDate() const { return actualLastFixingDate_; }
// virtual boost::shared_ptr<Index> index() const { return index_; }
//! \name CashFlow interface
//@{
Real amount() const; // already virtual
//@}
// return implied unit displaced vol from undiscounted option price
Real impliedTotalVariance(Real undeflatedPrice) const;
// return implied vol
Real impliedVolatility(Real undeflatedPrice) const;
//! \name Visitability
//@{
virtual void accept(AcyclicVisitor &);
//@}
//! \name Observer interface
//@{
void update() { notifyObservers(); }
//@}
private:
Real amount(Real totalVariance) const;
Real notional_;
boost::shared_ptr<ZeroInflationIndex> index_;
Date firstFixingDate_, lastFixingDate_, paymentDate_;
Date actualFirstFixingDate_, actualLastFixingDate_;
Real fixingTime_;
Handle<YieldTermStructure> nominalYts_;
Handle<ZeroInflationTermStructure> inflationYts_;
Handle<BlackVolTermStructure> inflationVol_;
Real strike_;
Option::Type type_;
DayCounter dc_;
class ImpliedVarianceHelper {
public:
ImpliedVarianceHelper(const ZCInflationCapFloor *h, Real target)
: h_(h), target_(target) {}
Real operator()(Real v) const { return target_ - h_->amount(v); }
private:
const ZCInflationCapFloor *h_;
Real target_;
};
};
// inline definitions
inline void ZCInflationCapFloor::accept(AcyclicVisitor &v) {
Visitor<ZCInflationCapFloor> *v1 =
dynamic_cast<Visitor<ZCInflationCapFloor> *>(&v);
if (v1 != 0)
v1->visit(*this);
else
CashFlow::accept(v);
}
}
#endif
| 38.149068 | 118 | 0.659557 | universe1987 |
6b64abbfe35597f2c2ffd39bbd38fa21d2b9f778 | 358 | cpp | C++ | 942-di-string-match/942-di-string-match.cpp | Edith-panda/leetcode | 175b4cbcd25b95b4863d793c876719eabb94dafc | [
"Apache-2.0"
] | null | null | null | 942-di-string-match/942-di-string-match.cpp | Edith-panda/leetcode | 175b4cbcd25b95b4863d793c876719eabb94dafc | [
"Apache-2.0"
] | null | null | null | 942-di-string-match/942-di-string-match.cpp | Edith-panda/leetcode | 175b4cbcd25b95b4863d793c876719eabb94dafc | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
vector<int> diStringMatch(string s) {
int n = s.size();
int k=0, j=n;
vector<int> v;
for(int i=0;i<=n;i++){
if(s[i] == 'I')
v.push_back(k++);
else
v.push_back(j--);
}
return v;
}
};
| 18.842105 | 41 | 0.343575 | Edith-panda |
6b6602c7556eb0928d3233517724e393a65ba09e | 14,717 | cpp | C++ | driver/src/oasis_hid.cpp | mmmspatz/wumbo_mr | 7dfecd4cb824ad2268f6f9208e3fe6c9510fb097 | [
"BSL-1.0"
] | 1 | 2021-02-12T06:54:53.000Z | 2021-02-12T06:54:53.000Z | driver/src/oasis_hid.cpp | mmmspatz/wumbo_mr | 7dfecd4cb824ad2268f6f9208e3fe6c9510fb097 | [
"BSL-1.0"
] | null | null | null | driver/src/oasis_hid.cpp | mmmspatz/wumbo_mr | 7dfecd4cb824ad2268f6f9208e3fe6c9510fb097 | [
"BSL-1.0"
] | null | null | null | // Copyright Mark H. Spatz 2021-present
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE or copy at
// https://www.boost.org/LICENSE_1_0.txt)
#include "oasis_hid.hpp"
#include <spdlog/spdlog.h>
#include <algorithm>
#include <cassert>
#include <chrono>
#include <cstddef>
#include <exception>
#include <future>
#include <mutex>
#include <stdexcept>
#include "oasis_hid_calibration_key.hpp"
namespace wmr {
OasisHid::OasisHid(std::unique_ptr<HidDevice> hid_dev)
: hid_dev_(std::move(hid_dev)), imu_frame_pool_(kFramePoolSize) {
fw_log_report_reader_ = std::make_shared<FwLogReportReader>();
hid_dev_->RegisterReportReader(FwLogReportReader::FwLogReport::kReportId, fw_log_report_reader_);
// mc_event_report_reader_ = std::make_shared<McEventReportReader>();
// hid_dev_->RegisterReportReader(McEventReportReader::McEventReport::kReportId,
// mc_event_report_reader_);
command_report_reader_ = std::make_shared<CommandReportReader>();
hid_dev_->RegisterReportReader(CommandReport::kReportId, command_report_reader_);
wiced_report_reader_ = std::make_shared<WicedReportReader>();
hid_dev_->RegisterReportReader(WicedReportReader::WicedReport::kReportId, wiced_report_reader_);
WriteFwCmdWaitAck(FwReport::kCmdImuStop);
}
OasisHid::~OasisHid() { WriteFwCmdWaitAck(FwReport::kCmdImuStop); }
void OasisHid::StartImu() {
imu_report_reader_ = std::make_shared<ImuReportReader>();
imu_report_reader_->parent_ = this; // Safe-ish, since it's among the first members destructed
hid_dev_->RegisterReportReader(ImuReportReader::ImuReport::kReportId, imu_report_reader_);
WriteFwCmdWaitAck(OasisHid::FwReport::kCmdImuInit);
}
void OasisHid::StopImu() {
WriteFwCmdWaitAck(OasisHid::FwReport::kCmdImuStop);
imu_report_reader_.reset();
}
void OasisHid::RegisterImuFrameCallback(ImuFrameCallback cb) {
std::lock_guard l{imu_frame_callbacks_m_};
imu_frame_callbacks_.push_back(std::move(cb));
}
std::string OasisHid::ReadCalibration() {
auto payload = ReadFirmwarePayload(PayloadType::kCalibration);
auto header = reinterpret_cast<const CalibrationHeader *>(payload.data());
auto json_offset = header->header_size + sizeof(header->header_size);
BufferView scrambled_json = BufferView(payload).substr(json_offset);
return UnscrambleCalibration(scrambled_json);
}
std::basic_string<uint8_t> OasisHid::ReadDeviceInfo() {
return ReadFirmwarePayload(PayloadType::kDeviceInfo);
}
std::string OasisHid::UnscrambleCalibration(BufferView scrambled_json) {
// Credit here goes to Max Thomas, who figured this out for OpenHMD
// see: https://github.com/OpenHMD/OpenHMD/issues/179#issuecomment-433687825
std::string json(scrambled_json.size(), '\0');
for (std::size_t i = 0; i < scrambled_json.size(); ++i) {
json[i] = scrambled_json[i] ^ kCalibrationKey[i % kCalibrationKey.size()];
}
return json;
}
std::basic_string<uint8_t> OasisHid::ReadFirmwarePayload(PayloadType type) {
// Set up callback
auto reader = std::make_shared<FwPayloadReader>();
reader->parent_ = this; // Safe, since reader goes out of scope at return
reader->payload_type_ = type;
hid_dev_->RegisterReportReader(FwReport::kReportId, reader);
// LUT mapping payload type to a payload read start command
static constexpr std::array<uint8_t, 3> type_to_cmd{FwReport::kCmdStartDeviceInfoRead,
FwReport::kCmdStartCalibrationRead,
FwReport::kCmdStartFlashLogRead};
// Start payload read
WriteFwCmd(type_to_cmd.at(static_cast<std::size_t>(type)));
// Wait for read to complete
auto fut = reader->payload_promise_.get_future();
if (fut.wait_for(std::chrono::seconds(1)) == std::future_status::ready) {
return fut.get();
} else {
throw std::runtime_error("OasisHid::ReadFirmwarePayload: Timeout");
}
}
void OasisHid::FwPayloadReader::Update(Report report) {
try {
if (report.size() < 2) {
throw std::runtime_error("Report too short");
}
enum class FwPayloadTxState {
kDataReadStart = 0,
kDataReadPayload = 1,
kDataReadEnd = 2,
};
// Byte 1 indicates the state of the transmitter
switch (static_cast<FwPayloadTxState>(report[1])) {
case FwPayloadTxState::kDataReadStart: {
if (got_data_read_start_) {
throw std::runtime_error("Repeated DATA_READ_START");
}
got_data_read_start_ = true;
if (report.size() < 7) {
throw std::runtime_error("DATA_READ_START report too short");
}
// Byte 2 mirrors the payload type of the command that started the read
if (static_cast<PayloadType>(report[2]) != payload_type_) {
throw std::runtime_error("DATA_READ_START indicates wrong payload type");
}
// Bytes 3-6 are big-endian size of the payload
payload_size_ = (report[3] << 24) | (report[4] << 16) | (report[5] << 8) | (report[6] << 0);
payload_rbuff_.reserve(payload_size_);
parent_->WriteFwCmd(FwReport::kCmdAckDataReceived);
} break;
case FwPayloadTxState::kDataReadPayload: {
if (!got_data_read_start_) {
throw std::runtime_error("DATA_READ_PAYLOAD came before DATA_READ_START");
}
if (report.size() < 3) {
throw std::runtime_error("DATA_READ_PAYLOAD report too short");
}
std::size_t chunk_size = report[2];
if (chunk_size + 3 > report.size()) {
throw std::runtime_error("chunk_size larger than remainder of report");
}
if (payload_rbuff_.size() + chunk_size > payload_size_) {
throw std::runtime_error("chunk_size implies too-large payload");
}
payload_rbuff_.append(report, 3, chunk_size);
parent_->WriteFwCmd(FwReport::kCmdAckDataReceived);
} break;
case FwPayloadTxState::kDataReadEnd: {
if (!got_data_read_start_) {
throw std::runtime_error("DATA_READ_END came before DATA_READ_START");
}
if (payload_rbuff_.size() != payload_size_) {
throw std::runtime_error("DATA_READ_END before payload complete");
}
// Success!
payload_promise_.set_value(std::move(payload_rbuff_));
finished_ = true;
// Note: Don't ACK DATA_READ_END
} break;
default:
throw std::runtime_error("Unknown FwPayloadTxState");
}
} catch (...) {
finished_ = true;
payload_promise_.set_exception(std::current_exception());
}
}
void OasisHid::WriteFwCmd(uint8_t command, BufferView data) {
// Marshal buffer
FwReport buff{};
buff.report_id = FwReport::kReportId;
buff.command = command;
assert(data.size() <= sizeof(buff.data));
std::copy(data.begin(), data.end(), buff.data);
// Do write
hid_dev_->WriteReport({reinterpret_cast<uint8_t *>(&buff), sizeof(FwReport)});
}
void OasisHid::WriteFwCmdWaitAck(uint8_t command, BufferView data, int timeout_ms) {
// Set up callback
auto reader = std::make_shared<FwCmdAckReader>();
hid_dev_->RegisterReportReader(FwReport::kReportId, reader);
// Do write
WriteFwCmd(command, data);
// Wait for ACK
auto fut = reader->got_ack_.get_future();
if (fut.wait_for(std::chrono::milliseconds(timeout_ms)) == std::future_status::ready) {
fut.get();
} else {
throw std::runtime_error("OasisHid::WriteFwCmdWaitAck: Timeout");
}
}
void OasisHid::WriteHidCmd(uint8_t command, uint8_t mystery_byte) {
// Marshal buffer
CommandReport buff{};
buff.report_id = CommandReport::kReportId;
buff.command_id = command;
// TODO Some commands have other mystery bytes
// Do write
hid_dev_->SetFeatureReport({reinterpret_cast<uint8_t *>(&buff), sizeof(CommandReport)});
}
void OasisHid::RunCallbacks(ImuFrameHandle frame) {
// Run callbacks
std::lock_guard l{imu_frame_callbacks_m_};
auto it = imu_frame_callbacks_.begin();
while (it != imu_frame_callbacks_.end()) {
ImuFrameCallback &cb = *it;
auto prev = it++;
if (!cb(frame)) {
imu_frame_callbacks_.erase(prev);
}
}
}
void OasisHid::ImuReportReader::Update(Report report) {
assert(report[0] == ImuReport::kReportId);
auto as_struct = reinterpret_cast<const ImuReport *>(report.data());
if (report.size() != ImuReport::kReportSize) {
spdlog::warn("ImuReport has wrong size ({})", report.size());
return;
}
if (as_struct->magic != ImuReport::kMagic) {
spdlog::warn("ImuReport has bad magic ({:04x})", as_struct->magic);
return;
}
sample_count_ += ImuFrame::kSamplesPerFrame;
if (sample_count_ < kImuStartupDiscardNSamples) return;
auto frame = parent_->imu_frame_pool_.Allocate();
// Sanitize the one buffer we might not completely overwrite
frame->magneto_samples = {};
frame->magneto_sample_count = 0;
for (std::size_t smp_idx = 0; true; ++smp_idx) {
// Run callbacks and break when frame is complete
if (smp_idx == ImuFrame::kSamplesPerFrame) {
parent_->RunCallbacks(frame);
break;
}
Timestamp sample_time(as_struct->accel_timestamp[smp_idx]);
Timestamp delta_t =
(prev_sample_time_.count() > 0) ? sample_time - prev_sample_time_ : kSamplePeriod;
prev_sample_time_ = sample_time;
if (delta_t.count() <= 0) {
stale_frame_count_++;
break;
}
if (delta_t > 2 * kSamplePeriod) {
spdlog::warn(
"OasisHid::ImuReportReader: encountered gap sample_count_={}, sample_time={}*100ns "
"delta_t={}*100ns",
sample_count_, prev_sample_time_.count(), delta_t.count());
delta_t = 2 * kSamplePeriod;
}
// Accelerometer
frame->accel_samples[smp_idx].timestamp = Timestamp(as_struct->accel_timestamp[smp_idx]);
frame->accel_samples[smp_idx].temperature = as_struct->temperature[smp_idx] * kTempPrecision;
frame->accel_samples[smp_idx].axes[0] = as_struct->accel[0][smp_idx] * kAccelPrecision;
frame->accel_samples[smp_idx].axes[1] = as_struct->accel[1][smp_idx] * kAccelPrecision;
frame->accel_samples[smp_idx].axes[2] = as_struct->accel[2][smp_idx] * kAccelPrecision;
// Gyro
auto gyro_delta_t = delta_t / ImuFrame::kGyroOversampling;
for (std::size_t j = 0; j < ImuFrame::kGyroOversampling; ++j) {
auto gyro_idx = smp_idx * ImuFrame::kGyroOversampling + j;
// gyro_timestamp[smp_idx] corresponds to the last of the kGyroOversampling gyro samples in
// this adc sample period.
frame->gyro_samples[gyro_idx].timestamp =
Timestamp(as_struct->gyro_timestamp[smp_idx]) -
(ImuFrame::kGyroOversampling - 1 - j) * gyro_delta_t;
frame->gyro_samples[gyro_idx].temperature = as_struct->temperature[smp_idx] * kTempPrecision;
frame->gyro_samples[gyro_idx].axes[0] = as_struct->gyro[0][gyro_idx] * kGyroPrecision;
frame->gyro_samples[gyro_idx].axes[1] = as_struct->gyro[1][gyro_idx] * kGyroPrecision;
frame->gyro_samples[gyro_idx].axes[2] = as_struct->gyro[2][gyro_idx] * kGyroPrecision;
}
// Magnetometer
// Frame contains up to ImuFrame::kSamplesPerFrame magneto samples.
// Valid samples have nonzero timestamps.
if (as_struct->magneto_timestamp[smp_idx]) {
auto m = frame->magneto_sample_count++;
frame->magneto_samples[m].timestamp = Timestamp(as_struct->magneto_timestamp[smp_idx]);
frame->magneto_samples[m].axes[0] = as_struct->magneto[0][smp_idx] * kMagnetoPrecision;
frame->magneto_samples[m].axes[1] = as_struct->magneto[1][smp_idx] * kMagnetoPrecision;
frame->magneto_samples[m].axes[2] = as_struct->magneto[2][smp_idx] * kMagnetoPrecision;
}
}
// Heartbeat
if (sample_count_ % 6000 == 0) {
spdlog::info("OasisHid::ImuReportReader: sample_count_ = {}", sample_count_);
}
// Report stale samples once per second
if (sample_count_ % 1000 == 0 && stale_frame_count_) {
spdlog::warn("OasisHid::ImuReportReader: Dropped {} stale frames", stale_frame_count_);
stale_frame_count_ = 0;
}
}
void OasisHid::FwLogReportReader::Update(Report report) {
assert(report[0] == FwLogReport::kReportId);
auto as_struct = reinterpret_cast<const FwLogReport *>(report.data());
if (report.size() != FwLogReport::kReportSize) {
spdlog::warn("FwLogReport has wrong size ({})", report.size());
} else if (as_struct->magic != FwLogReport::kMagic) {
spdlog::warn("FwLogReport has bad magic ({:04x})", as_struct->magic);
} else {
for (auto &log : as_struct->logs) {
if (log.msg[0] == 0) break;
spdlog::debug("[FWLogReport] [time={} level={}] {:.{}s}", log.time, log.level, log.msg.data(),
log.msg.size());
}
}
}
void OasisHid::McEventReportReader::Update(Report report) {
assert(report[0] == McEventReport::kReportId);
auto as_struct = reinterpret_cast<const McEventReport *>(report.data());
if (report.size() != McEventReport::kReportSize) {
spdlog::warn("McEventReport has wrong size ({})", report.size());
} else {
spdlog::info("[McEventReport] {:x} {:x} {:02x} {:02x}", as_struct->unknown8_1,
as_struct->unknown8_2, as_struct->unknown16_3, as_struct->unknown16_5);
}
}
void OasisHid::CommandReportReader::Update(Report report) {
assert(report[0] == CommandReport::kReportId);
auto as_struct = reinterpret_cast<const CommandReport *>(report.data());
if (report.size() != CommandReport::kReportSize) {
spdlog::warn("CommandReport has wrong size ({})", report.size());
} else if (as_struct->command_id != 8 && as_struct->command_id != 9) {
spdlog::warn("CommandReport has unexpected command_id {}", as_struct->command_id);
} else {
spdlog::info(
"[CommandReport] [command_id = {:x}] {:x} {:04x} {:02x} {:02x} {:02x} "
"{:02x}",
as_struct->command_id, as_struct->unknown8_2, as_struct->unknown32_3,
as_struct->unknown16_7, as_struct->unknown16_9, as_struct->unknown16_b,
as_struct->unknown16_d);
}
}
void OasisHid::WicedReportReader::Update(Report report) {
assert(report[0] == WicedReport::kReportId);
auto as_struct = reinterpret_cast<const WicedReport *>(report.data());
if (report.size() != WicedReport::kReportSize) {
// FIXME this always fires
spdlog::warn("WicedReport has wrong size ({})", report.size());
} else if (as_struct->hci_group != 2) {
// ignore
} else if (as_struct->size + 1U > WicedReport::kMaxDebugPrintSize) {
spdlog::warn("WicedReport has invalid size field ({})", as_struct->size);
} else {
spdlog::info("[WicedReport] [hci_group = {}] {:.{}s}", as_struct->hci_group,
as_struct->msg.data(), as_struct->size);
}
}
} // namespace wmr
| 34.957245 | 100 | 0.684311 | mmmspatz |
6b69591128a9b33277073ebe2c3f8d8e621d4839 | 1,423 | cpp | C++ | dev/Basic/long/database/entity/CreateOutputSchema.cpp | gusugusu1018/simmobility-prod | d30a5ba353673f8fd35f4868c26994a0206a40b6 | [
"MIT"
] | 50 | 2018-12-21T08:21:38.000Z | 2022-01-24T09:47:59.000Z | dev/Basic/long/database/entity/CreateOutputSchema.cpp | gusugusu1018/simmobility-prod | d30a5ba353673f8fd35f4868c26994a0206a40b6 | [
"MIT"
] | 2 | 2018-12-19T13:42:47.000Z | 2019-05-13T04:11:45.000Z | dev/Basic/long/database/entity/CreateOutputSchema.cpp | gusugusu1018/simmobility-prod | d30a5ba353673f8fd35f4868c26994a0206a40b6 | [
"MIT"
] | 27 | 2018-11-28T07:30:34.000Z | 2022-02-05T02:22:26.000Z | //Copyright (c) 2013 Singapore-MIT Alliance for Research and Technology
//Licensed under the terms of the MIT License, as described in the file:
// license.txt (http://opensource.org/licenses/MIT)
/*
* CreateOutputSchema.cpp
*
* Created on: Nov 23, 2015
* Author: gishara
*/
#include "CreateOutputSchema.hpp"
#include "util/Utils.hpp"
using namespace sim_mob::long_term;
CreateOutputSchema::CreateOutputSchema(BigSerial id, const std::string& tableName,
const std::string& query) : id(id), tableName(tableName), query(query) {
}
CreateOutputSchema::~CreateOutputSchema() {
}
BigSerial CreateOutputSchema::getId() const {
return id;
}
const std::string& CreateOutputSchema::getTableName() const {
return tableName;
}
const std::string& CreateOutputSchema::getQuery() const {
return query;
}
void CreateOutputSchema::setTableName(const std::string& name) {
this->tableName = name;
}
void CreateOutputSchema::setQuery(const std::string& queryStr) {
this->query = queryStr;
}
namespace sim_mob {
namespace long_term {
std::ostream& operator<<(std::ostream& strm, const CreateOutputSchema& data) {
return strm << "{"
<< "\"id\":\"" << data.id << "\","
<< "\"tableName\":\"" << data.tableName << "\","
<< "\"query\":\"" << data.query << "\""
<< "}";
}
}
}
| 24.534483 | 86 | 0.624034 | gusugusu1018 |
6b6a9ee9c8275c7b664b18ee06b41487632400c8 | 18,695 | cp | C++ | Linux/Sources/Application/Rules/Dialog/CRulesDialog.cp | mbert/mulberry-main | 6b7951a3ca56e01a7be67aa12e55bfeafc63950d | [
"ECL-2.0",
"Apache-2.0"
] | 12 | 2015-04-21T16:10:43.000Z | 2021-11-05T13:41:46.000Z | Linux/Sources/Application/Rules/Dialog/CRulesDialog.cp | SpareSimian/mulberry-main | e868f3f4d86efae3351000818a3cb2d72ae5eac3 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2015-11-02T13:32:11.000Z | 2019-07-10T21:11:21.000Z | Linux/Sources/Application/Rules/Dialog/CRulesDialog.cp | SpareSimian/mulberry-main | e868f3f4d86efae3351000818a3cb2d72ae5eac3 | [
"ECL-2.0",
"Apache-2.0"
] | 6 | 2015-01-12T08:49:12.000Z | 2021-03-27T09:11:10.000Z | /*
Copyright (c) 2007 Cyrus Daboo. All rights reserved.
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.
*/
// CRulesDialog.cpp : implementation file
//
#include "CRulesDialog.h"
#include "CActionItem.h"
#include "CBetterScrollbarSet.h"
#include "CBlankScrollable.h"
#include "CFilterItem.h"
#include "CFilterManager.h"
#include "CMulberryApp.h"
#include "CMulberryCommon.h"
#include "CMultibitPopup.h"
#include "CPreferences.h"
#include "CResizeNotifier.h"
#include "CRulesAction.h"
#include "CRulesActionLocal.h"
#include "CRulesActionSIEVE.h"
#include "CSearchCriteria.h"
#include "CTargetItem.h"
#include "CTextDisplay.h"
#include "CTextField.h"
#include <JXColormap.h>
#include <JXDisplay.h>
#include <JXDownRect.h>
#include <JXEngravedRect.h>
#include <JXStaticText.h>
#include <JXTextButton.h>
#include <JXTextCheckbox.h>
#include <JXUpRect.h>
#include <JXWindow.h>
#include <jXGlobals.h>
#include <cassert>
enum
{
eTriggersMenu_Apply = 1,
//eTriggersMenuSeparator,
eTriggersFirst
};
const char* cTriggers =
"Apply Rules Menu %b %l";
/////////////////////////////////////////////////////////////////////////////
// CRulesDialog dialog
CRulesDialog::CRulesDialog(JXDirector* supervisor)
: CDialogDirector(supervisor), CSearchBase(true)
{
mChangedTriggers = false;
}
// Default destructor
CRulesDialog::~CRulesDialog()
{
SaveDefaultState();
}
/////////////////////////////////////////////////////////////////////////////
// CRulesDialog message handlers
void CRulesDialog::OnCreate()
{
// begin JXLayout
JXWindow* window = new JXWindow(this, 550,315, "");
assert( window != NULL );
SetWindow(window);
CResizeNotifier* container =
new CResizeNotifier(window,
JXWidget::kHElastic, JXWidget::kVElastic, 0,0, 550,315);
assert( container != NULL );
JXStaticText* obj1 =
new JXStaticText("Name:", container,
JXWidget::kFixedLeft, JXWidget::kFixedTop, 10,12, 50,20);
assert( obj1 != NULL );
mName =
new CTextInputField(container,
JXWidget::kFixedLeft, JXWidget::kFixedTop, 65,10, 170,20);
assert( mName != NULL );
JXStaticText* obj2 =
new JXStaticText("Triggered by:", container,
JXWidget::kFixedLeft, JXWidget::kFixedTop, 250,10, 85,20);
assert( obj2 != NULL );
mTriggers =
new CMultibitPopup("",container,
JXWidget::kFixedLeft, JXWidget::kFixedTop, 335,10, 30,20);
assert( mTriggers != NULL );
mEditScript =
new JXTextCheckbox("Edit as Text", container,
JXWidget::kFixedLeft, JXWidget::kFixedTop, 395,10, 95,20);
assert( mEditScript != NULL );
mScriptEdit =
new CTextInputDisplay(container,
JXWidget::kHElastic, JXWidget::kVElastic, 10,40, 530,240);
assert( mScriptEdit != NULL );
mScroller =
new CBetterScrollbarSet(container,
JXWidget::kHElastic, JXWidget::kVElastic, 10,40, 530,240);
assert( mScroller != NULL );
mScrollPane =
new CBlankScrollable(mScroller, mScroller->GetScrollEnclosure(), // mScriptEdit,
JXWidget::kHElastic, JXWidget::kVElastic, 5,5, 510,135);
assert( mScrollPane != NULL );
mCriteria =
new JXEngravedRect(mScrollPane,
JXWidget::kHElastic, JXWidget::kFixedTop, 3,10, 495,10);
assert( mCriteria != NULL );
JXStaticText* obj3 =
new JXStaticText("Find Messages whose", mScrollPane,
JXWidget::kFixedLeft, JXWidget::kFixedTop, 10,1, 136,14);
assert( obj3 != NULL );
mCriteriaMove =
new JXWidgetSet(mScrollPane,
JXWidget::kHElastic, JXWidget::kFixedTop, 0,30, 510,105);
assert( mCriteriaMove != NULL );
mMoreBtn =
new JXTextButton("More Choices", mCriteriaMove,
JXWidget::kFixedLeft, JXWidget::kFixedTop, 5,0, 105,26);
assert( mMoreBtn != NULL );
mFewerBtn =
new JXTextButton("Fewer Choices", mCriteriaMove,
JXWidget::kFixedLeft, JXWidget::kFixedTop, 120,0, 105,26);
assert( mFewerBtn != NULL );
mClearBtn =
new JXTextButton("Reset", mCriteriaMove,
JXWidget::kFixedRight, JXWidget::kFixedTop, 430,0, 70,26);
assert( mClearBtn != NULL );
JXDownRect* obj4 =
new JXDownRect(mCriteriaMove,
JXWidget::kHElastic, JXWidget::kFixedTop, 5,30, 495,3);
assert( obj4 != NULL );
mActions =
new JXEngravedRect(mCriteriaMove,
JXWidget::kHElastic, JXWidget::kVElastic, 3,49, 495,10);
assert( mActions != NULL );
JXStaticText* obj5 =
new JXStaticText("Actions", mCriteriaMove,
JXWidget::kFixedLeft, JXWidget::kFixedTop, 10,40, 56,14);
assert( obj5 != NULL );
mMoreActionsBtn =
new JXTextButton("More Actions", mCriteriaMove,
JXWidget::kFixedLeft, JXWidget::kFixedBottom, 5,68, 105,26);
assert( mMoreActionsBtn != NULL );
mFewerActionsBtn =
new JXTextButton("FewerActions", mCriteriaMove,
JXWidget::kFixedLeft, JXWidget::kFixedBottom, 120,68, 105,26);
assert( mFewerActionsBtn != NULL );
mStop =
new JXTextCheckbox("Stop if Matched", mCriteriaMove,
JXWidget::kFixedLeft, JXWidget::kFixedBottom, 230,70, 125,20);
assert( mStop != NULL );
mClearActionsBtn =
new JXTextButton("Reset", mCriteriaMove,
JXWidget::kFixedRight, JXWidget::kFixedBottom, 430,68, 70,26);
assert( mClearActionsBtn != NULL );
JXDownRect* obj6 =
new JXDownRect(mCriteriaMove,
JXWidget::kHElastic, JXWidget::kFixedBottom, 5,99, 495,3);
assert( obj6 != NULL );
mBottomArea =
new JXWidgetSet(container,
JXWidget::kHElastic, JXWidget::kFixedBottom, 2,282, 546,33);
assert( mBottomArea != NULL );
mCancelBtn =
new JXTextButton("Cancel", mBottomArea,
JXWidget::kFixedRight, JXWidget::kFixedTop, 368,0, 70,25);
assert( mCancelBtn != NULL );
mCancelBtn->SetShortcuts("^[");
mOKBtn =
new JXTextButton("OK", mBottomArea,
JXWidget::kFixedRight, JXWidget::kFixedTop, 458,0, 70,25);
assert( mOKBtn != NULL );
mOKBtn->SetShortcuts("^M");
// end JXLayout
// Do scroll pane init
mScrollPane->Init();
mScroller->SetAllowScroll(false, true);
window->SetTitle("Edit Rules");
SetButtons(mOKBtn, mCancelBtn);
mTriggers->SetMenuItems(cTriggers);
mTriggers->SetValue(eTriggersMenu_Apply);
mScriptEdit->Hide();
ListenTo(container);
ListenTo(mTriggers);
ListenTo(mEditScript);
ListenTo(mMoreBtn);
ListenTo(mFewerBtn);
ListenTo(mClearBtn);
ListenTo(mMoreActionsBtn);
ListenTo(mFewerActionsBtn);
ListenTo(mClearActionsBtn);
// Turn off auto-place and lock
UseModalPlacement(kFalse);
// Set current width and height as minimum
window->SetMinSize(550, 315);
ResetState();
}
#pragma mark ____________________________Commands
void CRulesDialog::OnSetTrigger(JIndex index)
{
// The multibit menu takes care of changing its own state
mChangedTriggers = true;
}
// Handle buttons
void CRulesDialog::Receive(JBroadcaster* sender, const Message& message)
{
if (message.Is(JXButton::kPushed))
{
if (sender == mMoreBtn)
{
OnMore();
return;
}
else if (sender == mFewerBtn)
{
OnFewer();
return;
}
else if (sender == mClearBtn)
{
OnClear();
return;
}
else if (sender == mMoreActionsBtn)
{
OnMoreActions();
return;
}
else if (sender == mFewerActionsBtn)
{
OnFewerActions();
return;
}
else if (sender == mClearActionsBtn)
{
OnClearActions();
return;
}
}
else if (message.Is(JXCheckbox::kPushed))
{
if (sender == mEditScript)
{
OnEditScript(mEditScript->IsChecked());
return;
}
}
else if (message.Is(JXMenu::kItemSelected))
{
JIndex index = dynamic_cast<const JXMenu::ItemSelected*>(&message)->GetIndex();
if (sender == mTriggers)
{
OnSetTrigger(index);
return;
}
}
CDialogDirector::Receive(sender, message);
}
void CRulesDialog::Activate()
{
// When activating do modal dialog window placement
if (!IsActive())
{
JXWindow* window = GetWindow();
window->PlaceAsDialogWindow();
}
// Do inherited
CDialogDirector::Activate();
}
void CRulesDialog::OnMoreActions()
{
AddAction();
}
void CRulesDialog::OnFewerActions()
{
RemoveAction();
}
void CRulesDialog::OnClearActions()
{
// Remove all but the first one
if (mActionItems.size() > 1)
RemoveAction(mActionItems.size() - 1);
// Reset the first one
CRulesAction* action = static_cast<CRulesAction*>(mActionItems.at(0));
action->SetActionItem(NULL);
}
void CRulesDialog::OnEditScript(bool edit)
{
if (mEditScript->IsChecked())
{
// Convert current items to script
CFilterItem spec(CFilterItem::eSIEVE);
ConstructFilter(&spec, false, false);
spec.SetUseScript(true);
// Set script in display
mScriptEdit->SetText(spec.GetScript());
// Switch to script display
mScroller->Hide();
mScriptEdit->Show();
}
else
{
mScriptEdit->Hide();
mScroller->Show();
}
// Always force reset
OnClear();
OnClearActions();
}
void CRulesDialog::SetFilter(CFilterItem* filter)
{
if (filter)
{
mName->SetText(filter->GetName());
mFilterType = filter->GetType();
if (filter->GetType() == CFilterItem::eSIEVE)
mEditScript->Show();
else
mEditScript->Hide();
StopListening(mEditScript);
mEditScript->SetState(JBoolean(filter->GetUseScript()));
ListenTo(mEditScript);
mStop->SetState(JBoolean(filter->Stop()));
}
// Remove existing
RemoveAllCriteria();
RemoveAction(mActionItems.size());
InitTriggers(filter);
InitCriteria(filter ? filter->GetCriteria() : NULL);
InitActions(filter ? filter->GetActions() : NULL);
if (filter && filter->GetUseScript())
{
// Set script in display
mScriptEdit->SetText(filter->GetScript());
// Switch to script display
mScroller->Hide();
mScriptEdit->Show();
}
}
void CRulesDialog::InitTriggers(CFilterItem* filter)
{
bool has_manual = filter && (filter->GetType() == CFilterItem::eLocal);
// Remove any existing items from main menu
mTriggers->RemoveAllItems();
// Set Apply item check mark
if (has_manual)
{
mTriggers->SetMenuItems(cTriggers);
mTriggers->InitBits();
if (filter->GetManual())
mTriggers->SetBit(eTriggersMenu_Apply);
}
// Add all triggers/scripts
if (filter)
{
JIndex index = (has_manual ? eTriggersFirst : eTriggersMenu_Apply);
if (filter->GetType() == CFilterItem::eLocal)
{
for(CTargetItemList::iterator iter = CPreferences::sPrefs->GetFilterManager()->GetTargets(filter->GetType()).begin();
iter != CPreferences::sPrefs->GetFilterManager()->GetTargets(filter->GetType()).end(); iter++, index++)
{
// Add menu item
mTriggers->AppendItem((*iter)->GetName(), kTrue, kFalse);
mTriggers->InitBits();
// Determine if this rule is in the trigger
if ((*iter)->ContainsFilter(filter))
mTriggers->SetBit(index);
}
}
else
{
for(CFilterScriptList::iterator iter = CPreferences::sPrefs->GetFilterManager()->GetScripts(filter->GetType()).begin();
iter != CPreferences::sPrefs->GetFilterManager()->GetScripts(filter->GetType()).end(); iter++, index++)
{
// Add menu item
mTriggers->AppendItem((*iter)->GetName(), kTrue, kFalse);
mTriggers->InitBits();
// Determine if this rule is in the trigger
if ((*iter)->ContainsFilter(filter))
mTriggers->SetBit(index);
}
}
}
// Force max/min update
mTriggers->SetValue(0);
}
#pragma mark ____________________________Criteria
void CRulesDialog::Resized(int dy)
{
// Adjust scroll pane and scroll to bottom if scroller active
mScrollPane->AdjustBounds(0, dy);
if (dy > 0)
mScrollPane->Scroll(0, -dy);
mCriteria->AdjustSize(0, dy);
mCriteriaMove->Move(0, dy);
}
#pragma mark ____________________________Actions
void CRulesDialog::InitActions(const CActionItemList* actions)
{
// Add each action
if (actions && actions->size())
{
for(CActionItemList::const_iterator iter = actions->begin(); iter != actions->end(); iter++)
AddAction(*iter);
}
else
AddAction();
}
const int cActionHOffset = 4;
const int cActionVInitOffset = 5;
const int cActionVOffset = 0;
const int cActionHeight = 25;
const int cActionWidth = 492;
void CRulesDialog::AddAction(const CActionItem* spec)
{
// Create a new search criteria panel
JRect r = mActions->GetFrame();
r.Shift(-r.left, -r.top);
r.left += cActionHOffset;
r.right -= cActionHOffset;
r.top = cActionVInitOffset + mActionItems.size() * (cActionHeight + cActionVOffset);
r.bottom = r.top + cActionHeight;
CRulesAction* action = NULL;
switch(mFilterType)
{
case CFilterItem::eLocal:
default:
action = new CRulesActionLocal(mActions, JXWidget::kHElastic, JXWidget::kFixedTop, r.left, r.top, cActionWidth, cActionHeight);
break;
case CFilterItem::eSIEVE:
action = new CRulesActionSIEVE(mActions, JXWidget::kHElastic, JXWidget::kFixedTop, r.left, r.top, cActionWidth, cActionHeight);
break;
}
// Create actual items
action->OnCreate(this);
// Adjust size to actual width of parent
action->AdjustSize(r.width() - cActionWidth, 0);
// Set any input spec
if (spec)
action->SetActionItem(spec);
// Get last view in criteria bottom
if (mActionItems.size())
{
CRulesAction* prev = static_cast<CRulesAction*>(mActionItems.back());
prev->SetBottom(false);
// Change current to add Or/And menu
action->SetBottom(true);
}
else
{
action->SetTop(true);
action->SetBottom(true);
}
// Add to list
mActionItems.push_back(action);
// Now adjust sizes
ResizedActions(cActionHeight + cActionVOffset);
// Do button state
mFewerActionsBtn->Show();
}
void CRulesDialog::RemoveAction(unsigned long num)
{
for(unsigned long i = 1; i <= num; i++)
{
// Get last view in criteria
JXWidget* action = mActionItems.back();
mActionItems.pop_back();
action->Hide();
// Now delete the pane
delete action;
}
// Now adjust sizes
ResizedActions((-cActionHeight - cActionVOffset) * num);
// Set up/down button state
if (mActionItems.size())
{
CRulesAction* prev = static_cast<CRulesAction*>(mActionItems.back());
prev->SetBottom(true);
}
// Do button state
if (mActionItems.size() == 0)
mFewerActionsBtn->Hide();
}
void CRulesDialog::ResizedActions(int dy)
{
// Adjust scroll pane and scroll to bottom if scroller active
mScrollPane->AdjustBounds(0, dy);
if (dy > 0)
mScrollPane->Scroll(0, -dy);
mCriteriaMove->AdjustSize(0, dy);
//mActions->AdjustSize(0, dy);
}
#pragma mark ____________________________Build
void CRulesDialog::ConstructFilter(CFilterItem* spec, bool script, bool change_triggers) const
{
spec->SetName(mName->GetText());
// Get triggers
if (change_triggers)
{
bool has_manual = (spec->GetType() == CFilterItem::eLocal);
if (has_manual)
spec->SetManual(mTriggers->GetBit(eTriggersMenu_Apply));
JSize num_menu = mTriggers->GetItemCount();
JIndex index = 0;
for(JIndex i = has_manual ? eTriggersFirst : eTriggersMenu_Apply; i <= num_menu; i++, index++)
{
// Check mark state and set the appropriate item
if (mTriggers->GetBit(i))
{
if (spec->GetType() == CFilterItem::eLocal)
CPreferences::sPrefs->GetFilterManager()->GetTargets(spec->GetType()).at(index)->AddFilter(spec);
else
CPreferences::sPrefs->GetFilterManager()->GetScripts(spec->GetType()).at(index)->AddFilter(spec);
}
else
{
if (spec->GetType() == CFilterItem::eLocal)
CPreferences::sPrefs->GetFilterManager()->GetTargets(spec->GetType()).at(index)->RemoveFilter(spec);
else
CPreferences::sPrefs->GetFilterManager()->GetScripts(spec->GetType()).at(index)->RemoveFilter(spec);
}
}
}
// Get details
if (script)
{
spec->SetUseScript(script);
// Copy info from panel into prefs
spec->SetScript(mScriptEdit->GetText());
}
else
{
spec->SetUseScript(false);
spec->SetCriteria(ConstructSearch());
spec->SetActions(ConstructActions());
spec->SetStop(mStop->IsChecked());
}
}
CActionItemList* CRulesDialog::ConstructActions() const
{
CActionItemList* actions = new CActionItemList;
// Count items
long num = mActionItems.size();
for(long i = 0; i < num; i++)
actions->push_back(static_cast<CRulesAction*>(mActionItems.at(i))->GetActionItem());
return actions;
}
bool CRulesDialog::PoseDialog(CFilterItem* spec, bool& trigger_change)
{
bool result = false;
// Create the dialog
CRulesDialog* dlog = new CRulesDialog(JXGetApplication());
dlog->OnCreate();
dlog->SetFilter(spec);
// Let DialogHandler process events
if (dlog->DoModal(false) == kDialogClosed_OK)
{
// Lock to prevent filter manager changes whilst running
cdmutex::lock_cdmutex _lock(CPreferences::sPrefs->GetFilterManager()->RunningLock());
dlog->ConstructFilter(spec, dlog->mEditScript->IsChecked());
trigger_change = dlog->mChangedTriggers;
result = true;
dlog->Close();
}
return result;
}
#pragma mark ____________________________Window State
// Reset state from prefs
void CRulesDialog::ResetState()
{
// Get name as cstr
char name = 0;
// Get default state
CWindowState* state = &CPreferences::sPrefs->mRulesDialogDefault.Value();
// Do not set if empty
JRect set_rect = state->GetBestRect(*state);
if (set_rect.left && set_rect.top)
{
// Clip to screen
::RectOnScreen(set_rect);
// Reset position
GetWindow()->Place(set_rect.left, set_rect.top);
GetWindow()->SetSize(set_rect.width(), set_rect.height());
}
}
// Save current state in prefs
void CRulesDialog::SaveDefaultState(void)
{
// Get bounds - convert to position only
JPoint p = GetWindow()->GetDesktopLocation();
JCoordinate w = GetWindow()->GetFrameWidth();
JCoordinate h = GetWindow()->GetFrameHeight();
JRect bounds(p.y, p.x, p.y + h, p.x + w);
// Add info to prefs
CWindowState state(NULL, &bounds, eWindowStateNormal);
if (CPreferences::sPrefs->mRulesDialogDefault.Value().Merge(state))
CPreferences::sPrefs->mRulesDialogDefault.SetDirty();
}
| 25.750689 | 129 | 0.671891 | mbert |
6b6ca32553a3f511a5c8d23c7a1a0f3d7a024d6e | 3,407 | cpp | C++ | qtmultimedia/src/plugins/android/src/common/qandroidmultimediautils.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | 1 | 2020-04-30T15:47:35.000Z | 2020-04-30T15:47:35.000Z | qtmultimedia/src/plugins/android/src/common/qandroidmultimediautils.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | qtmultimedia/src/plugins/android/src/common/qandroidmultimediautils.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qandroidmultimediautils.h"
#include <qlist.h>
QT_BEGIN_NAMESPACE
int qt_findClosestValue(const QList<int> &list, int value)
{
if (list.size() < 2)
return 0;
int begin = 0;
int end = list.size() - 1;
int pivot = begin + (end - begin) / 2;
int v = list.at(pivot);
while (end - begin > 1) {
if (value == v)
return pivot;
if (value > v)
begin = pivot;
else
end = pivot;
pivot = begin + (end - begin) / 2;
v = list.at(pivot);
}
return value - v >= list.at(pivot + 1) - value ? pivot + 1 : pivot;
}
bool qt_sizeLessThan(const QSize &s1, const QSize &s2)
{
return s1.width() * s1.height() < s2.width() * s2.height();
}
QVideoFrame::PixelFormat qt_pixelFormatFromAndroidImageFormat(AndroidCamera::ImageFormat f)
{
switch (f) {
case AndroidCamera::NV21:
return QVideoFrame::Format_NV21;
case AndroidCamera::YV12:
return QVideoFrame::Format_YV12;
case AndroidCamera::RGB565:
return QVideoFrame::Format_RGB565;
case AndroidCamera::YUY2:
return QVideoFrame::Format_YUYV;
case AndroidCamera::JPEG:
return QVideoFrame::Format_Jpeg;
default:
return QVideoFrame::Format_Invalid;
}
}
AndroidCamera::ImageFormat qt_androidImageFormatFromPixelFormat(QVideoFrame::PixelFormat f)
{
switch (f) {
case QVideoFrame::Format_NV21:
return AndroidCamera::NV21;
case QVideoFrame::Format_YV12:
return AndroidCamera::YV12;
case QVideoFrame::Format_RGB565:
return AndroidCamera::RGB565;
case QVideoFrame::Format_YUYV:
return AndroidCamera::YUY2;
case QVideoFrame::Format_Jpeg:
return AndroidCamera::JPEG;
default:
return AndroidCamera::UnknownImageFormat;
}
}
QT_END_NAMESPACE
| 31.546296 | 91 | 0.65835 | wgnet |
6b6fb696342f23f890bca26716a01d374d7bf01d | 1,664 | hpp | C++ | src/cxx/ctul/cfg/mutex.hpp | c0de4un/cxx-thread-util | 3b7f85e32370cfeb699d7a7d3c8bf08ca99acbe5 | [
"MIT"
] | 1 | 2020-01-30T15:13:37.000Z | 2020-01-30T15:13:37.000Z | src/cxx/ctul/cfg/mutex.hpp | c0de4un/cxx-thread-util | 3b7f85e32370cfeb699d7a7d3c8bf08ca99acbe5 | [
"MIT"
] | null | null | null | src/cxx/ctul/cfg/mutex.hpp | c0de4un/cxx-thread-util | 3b7f85e32370cfeb699d7a7d3c8bf08ca99acbe5 | [
"MIT"
] | null | null | null | /**
* 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 CTUL_CFG_MUTEX_HPP
#define CTUL_CFG_MUTEX_HPP
// -----------------------------------------------------------
// ===========================================================
// INCLUDES
// ===========================================================
// Include C++ mutex
#include <mutex>
// Include ctul::core::SMutex
#ifndef CTUL_CORE_SMUTEX_HPP
#include "../core/utils/SMutex.hpp"
#endif // !CTUL_CORE_SMUTEX_HPP
// ===========================================================
// FORWARD-DECLARATIONS
// ===========================================================
// Forward-Declaration of ctul::core::SMutex (required by compiler to prevent type-error).
#ifndef CTUL_CORE_SMUTEX_DECL
#define CTUL_CORE_SMUTEX_DECL
namespace ctul
{
namespace core
{
class SMutex;
}
}
#endif // !CTUL_CORE_SMUTEX_DECL
// ===========================================================
// TYPES
// ===========================================================
using ctul_mutex_t = ctul::core::SMutex;// std::mutex;
using ctul_ulock = std::unique_lock<ctul_mutex_t>;
// -----------------------------------------------------------
#endif // !CTUL_CFG_MUTEX_HPP | 29.192982 | 90 | 0.519231 | c0de4un |
6b7609c25d10b3adf3ea816d2b7b295b0d76a31c | 2,866 | cpp | C++ | src/sd/FileListIterator.cpp | r4dx/sentinel-hill | 9b5770240f2d603da08925e86460925799a91bc9 | [
"Apache-2.0"
] | 1 | 2019-12-27T20:07:45.000Z | 2019-12-27T20:07:45.000Z | src/sd/FileListIterator.cpp | r4dx/sentinel-hill | 9b5770240f2d603da08925e86460925799a91bc9 | [
"Apache-2.0"
] | 25 | 2016-10-21T04:44:34.000Z | 2017-08-18T20:54:22.000Z | src/sd/FileListIterator.cpp | r4dx/sentinel-hill | 9b5770240f2d603da08925e86460925799a91bc9 | [
"Apache-2.0"
] | null | null | null | #include "FileListIterator.h"
#include "File.h"
#include "logger/ConsoleFileLoggerWrapper.h"
#include <assert.h>
namespace sentinel {
namespace sd {
namespace file {
FileListIterator::FileListIterator(File& folder)
: folder(&folder), current(nullptr), isEnd(false),
end_iterator(std::shared_ptr<FileListIterator>(
new FileListIterator())) {
folder.rewindDirectory();
next();
}
FileListIterator::FileListIterator() : folder(nullptr),
current(nullptr), isEnd(true), end_iterator(nullptr) { }
FileListIterator& FileListIterator::operator++ () {
next();
return *this;
}
void FileListIterator::next() {
if (isEnd)
return;
File entry = folder->openNextFile();
bool isValid = valid(entry);
bool isDir = entry.isDirectory();
char* name = entry.name();
entry.close();
if (!isValid) {
isEnd = true;
current = std::shared_ptr<FileEntry>(nullptr);
return;
}
if (current == nullptr)
current = std::shared_ptr<FileEntry>(new FileEntry());
current->fileName = std::shared_ptr<std::string>(new std::string(name));
current->isDirectory = isDir;
}
FileEntry& FileListIterator::operator* () const {
assert(current != nullptr && "Invalid iterator dereference");
return *current;
}
FileEntry* FileListIterator::operator-> () const {
assert(current != nullptr && "Invalid iterator dereference");
return current.get();
}
FileListIterator FileListIterator::operator++ (int) {
FileListIterator tmp(*this);
next();
return tmp;
}
bool FileListIterator::operator== (
const FileListIterator& rhs) const {
return equals(rhs);
}
bool FileListIterator::operator!= (
const FileListIterator& rhs) const {
return !equals(rhs);
}
bool FileListIterator::equals(
const FileListIterator& rhs) const {
return current == rhs.current && isEnd == rhs.isEnd;
}
const FileListIterator& FileListIterator::end() const {
return end_iterator == nullptr ? *this : *end_iterator;
}
}
}
} | 33.717647 | 89 | 0.474529 | r4dx |
6b780e45f353ee9e9b5288bce4ef6ed2b49003f1 | 881 | cpp | C++ | duds/data/Int128.cpp | jjackowski/duds | 0fc4eec0face95c13575672f2a2d8625517c9469 | [
"BSD-2-Clause"
] | null | null | null | duds/data/Int128.cpp | jjackowski/duds | 0fc4eec0face95c13575672f2a2d8625517c9469 | [
"BSD-2-Clause"
] | null | null | null | duds/data/Int128.cpp | jjackowski/duds | 0fc4eec0face95c13575672f2a2d8625517c9469 | [
"BSD-2-Clause"
] | null | null | null | /*
* This file is part of the DUDS project. It is subject to the BSD-style
* license terms in the LICENSE file found in the top-level directory of this
* distribution and at https://github.com/jjackowski/duds/blob/master/LICENSE.
* No part of DUDS, including this file, may be copied, modified, propagated,
* or distributed except according to the terms contained in the LICENSE file.
*
* Copyright (C) 2017 Jeff Jackowski
*/
#include <duds/BuildConfig.h>
#ifdef HAVE_INT128
#include <boost/multiprecision/cpp_int.hpp>
#include <sstream>
namespace duds { namespace data {
std::istream &operator >> (std::istream &is, __int128 &b) {
boost::multiprecision::int128_t mpi;
is >> mpi;
b = static_cast<__int128>(mpi);
return is;
}
std::ostream &operator << (std::ostream &os, __int128 const &b) {
boost::multiprecision::int128_t mpi(b);
return os << mpi;
}
} }
#endif
| 28.419355 | 78 | 0.721907 | jjackowski |
6b783e448c1307903bf75d9c2b6e6d518fb32b39 | 17,384 | cpp | C++ | OledDisplay.cpp | Hans-Beerman/CompressorNodeSoftware-main | fea1e6ff31fe20c2aa0eda00284652a2a31f0b96 | [
"Apache-2.0"
] | null | null | null | OledDisplay.cpp | Hans-Beerman/CompressorNodeSoftware-main | fea1e6ff31fe20c2aa0eda00284652a2a31f0b96 | [
"Apache-2.0"
] | null | null | null | OledDisplay.cpp | Hans-Beerman/CompressorNodeSoftware-main | fea1e6ff31fe20c2aa0eda00284652a2a31f0b96 | [
"Apache-2.0"
] | null | null | null | #include "OledDisplay.h"
#include <U8x8lib.h> // install U8g2 library by oliver
// for I2C display
#ifndef I2C_SDA
#define I2C_SDA (13) // I2C SDA = GPIO 13
#endif
#ifndef I2C_SCL
#define I2C_SCL (16) // I2C SCL = GPIO 16
#endif
// oled display
#define DISPLAY_WINDOW (1000) // in ms, update display time
#define KEEP_STATUS_LINE_TIME (5000) // in ms, default = 5 s (5000), the time certain status messages are shown on the bottom line of the display
typedef enum {
NORMALDISPLAY, // Normal display shown when there is no error, showing current compressor state etc.
ERRORDISPLAY
} displaystates_t;
struct {
const char * statusmessage;
int y;
bool temporarily;
} dispstatus[ERRORHIGHTEMP2 + 1] =
{
{ " ", 15, false },
{ "Release button ", 15, false },
{ "Node will reboot", 15, false },
{ "Manual poweron ", 15, true },
{ "Manual override ", 15, true },
{ "Manual off ", 15, true },
{ "Auto Power on ", 15, true },
{ "Auto on denied ", 15, true },
{ "Automatic Stop ", 15, true },
{ "Poweron disabled", 15, true },
{ "Timout extended ", 15, true },
{ "Timeout ==> off ", 15, true },
{ "Pressure toohigh", 15, false},
{ "OilLevel too low", 7, false },
{ "OilLevel OK! ", 7, false },
{ "Warning ", 15, false },
{ "ERROR ", 15, false },
{ "Warning ", 15, false },
{ "ERROR ", 15, false },
};
bool nextTimeDisplay = true;
bool showStatusTemporarily = false;
unsigned long clearStatusLineTime = 0;
machinestates_t laststateDisplayed = BOOTING;
displaystates_t currentDisplayState = NORMALDISPLAY;
unsigned long updateDisplayTime = 0;
bool lastOilLevelDisplayed = false;
float lastTempDisplayed1 = -500;
float lastTempDisplayed2 = -500;
bool previousTempIsHigh1 = false;
bool previousErrorTempIsTooHigh1 = false;
bool previousTempIsHigh2 = false;
bool previousErrorTempIsTooHigh2 = false;
bool previousErrorOilLevelIsTooLow = false;
float lastPressureDisplayed = -1;
float poweredTime = 0.0;
float lastPoweredDisplayed = 0.0;
float runningTime = 0.0;
float lastRunningDisplayed = 0.0;
// for 1.5 inch OLED Display 128*128 pixels wit - I2C
U8X8_SSD1327_WS_128X128_SW_I2C u8x8(I2C_SCL, I2C_SDA, U8X8_PIN_NONE);
OledDisplay::OledDisplay() {
return;
}
void OledDisplay::begin(float tempIsHighLevel1, float tempIsTooHighLevel1, float tempIsHighLevel2, float tempIsTooHighLevel2) {
// for 1.5 inch OLED Display 128*128 pixels wit - I2C
pinMode(I2C_SDA, OUTPUT);
pinMode(I2C_SCL, OUTPUT);
digitalWrite(I2C_SDA, 0);
digitalWrite(I2C_SCL, 0);
theTempIsHighLevel1 = tempIsHighLevel1;
theTempIsTooHighLevel1 = tempIsTooHighLevel1;
theTempIsHighLevel2 = tempIsHighLevel2;
theTempIsTooHighLevel2 = tempIsTooHighLevel2;
u8x8.begin();
u8x8.clear();
u8x8.setCursor(0, 0);
u8x8.setFont(u8x8_font_px437wyse700a_2x2_r);
u8x8.drawString(0, 0, "CompNode");
u8x8.setFont(u8x8_font_px437wyse700b_2x2_r);
u8x8.drawString(0, 2, SOFTWARE_VERSION);
u8x8.setFont(u8x8_font_chroma48medium8_r);
u8x8.drawString(0, 4, " c Hans Beerman ");
u8x8.drawString(0, 6, "Booting, please ");
u8x8.drawString(0, 7, " wait ");
}
void OledDisplay::clearDisplay() {
u8x8.clearDisplay();
}
void OledDisplay::showStatus(statusdisplay_t statusMessage) {
char outputStr[20];
switch (statusMessage) {
case NOSTATUS:
case ERRORLOWOILLEVEL:
case NOLOWOILLEVEL:
u8x8.setFont(u8x8_font_amstrad_cpc_extended_f);
u8x8.drawString(0, dispstatus[statusMessage].y, dispstatus[statusMessage].statusmessage);
break;
case WARNINGHIGHTEMP1:
u8x8.setFont(u8x8_font_amstrad_cpc_extended_f);
sprintf(outputStr, "WARNING >%4.0f %cC", theTempIsHighLevel1, 176);
u8x8.drawString(0, dispstatus[statusMessage].y, outputStr);
break;
case ERRORHIGHTEMP1:
u8x8.setFont(u8x8_font_amstrad_cpc_extended_f);
sprintf(outputStr, "ERROR 1 >%4.0f %cC", theTempIsTooHighLevel1, 176);
u8x8.drawString(0, dispstatus[statusMessage].y, outputStr);
break;
case WARNINGHIGHTEMP2:
u8x8.setFont(u8x8_font_amstrad_cpc_extended_f);
sprintf(outputStr, "WARNING >%4.0f %cC", theTempIsHighLevel2, 176);
u8x8.drawString(0, dispstatus[statusMessage].y, outputStr);
break;
case ERRORHIGHTEMP2:
u8x8.setFont(u8x8_font_amstrad_cpc_extended_f);
sprintf(outputStr, "ERROR 2 >%4.0f %cC", theTempIsTooHighLevel2, 176);
u8x8.drawString(0, dispstatus[statusMessage].y, outputStr);
break;
default:
u8x8.setFont(u8x8_font_chroma48medium8_r);
u8x8.drawString(0, dispstatus[statusMessage].y, dispstatus[statusMessage].statusmessage);
break;
}
showStatusTemporarily = dispstatus[statusMessage].temporarily;
clearStatusLineTime = millis() + KEEP_STATUS_LINE_TIME;
}
void OledDisplay::clearEEPromWarning() {
u8x8.setFont(u8x8_font_chroma48medium8_r);
u8x8.drawString(0, 9, "Keep Olimex BUT2");
u8x8.drawString(0, 10, "pressed for at ");
u8x8.drawString(0, 11, "least 4 seconds ");
u8x8.drawString(0, 12, "to clear EEProm ");
u8x8.drawString(0, 13, "and cache memory");
}
void OledDisplay::clearEEPromMessage() {
u8x8.setFont(u8x8_font_chroma48medium8_r);
u8x8.drawString(0, 9, "EEProm and cache");
u8x8.drawString(0, 10, "will be cleared ");
u8x8.drawString(0, 11, " ");
u8x8.drawString(0, 12, " ");
u8x8.drawString(0, 13, " ");
}
void OledDisplay::EEPromCleared() {
u8x8.setFont(u8x8_font_chroma48medium8_r);
u8x8.drawString(0, 12, "EEProm cleared ");
}
void OledDisplay::cacheCleared() {
u8x8.setFont(u8x8_font_chroma48medium8_r);
u8x8.drawString(0, 13, "Cache cleared ");
}
void OledDisplay::loop(bool oilLevelIsTooLow, bool ErrorOilLevelIsTooLow, float temperature1, bool tempIsHigh1,
bool ErrorTempIsTooHigh1, float temperature2, bool tempIsHigh2, bool ErrorTempIsTooHigh2, bool ErrorPressureIsToHigh,
float pressure, machinestates_t machinestate,
unsigned long powered_total, unsigned long powered_last,
unsigned long running_total, unsigned long running_last) {
char outputStr[20];
bool temp1PrintAll = false;
bool temp2PrintAll = false;
if (!ErrorOilLevelIsTooLow && !ErrorTempIsTooHigh1 && !ErrorTempIsTooHigh2) {
if (currentDisplayState == ERRORDISPLAY) {
nextTimeDisplay = true;
previousTempIsHigh1 = !tempIsHigh1;
previousTempIsHigh2 = !tempIsHigh2;
u8x8.clearDisplay();
currentDisplayState = NORMALDISPLAY;
}
} else {
if (currentDisplayState == NORMALDISPLAY) {
nextTimeDisplay = true;
u8x8.clearDisplay();
currentDisplayState = ERRORDISPLAY;
}
}
switch (currentDisplayState)
{
case NORMALDISPLAY:
if (millis() > updateDisplayTime)
{
updateDisplayTime = millis() + DISPLAY_WINDOW;
if ((pressure != lastPressureDisplayed) || nextTimeDisplay) {
lastPressureDisplayed = pressure;
u8x8.setFont(u8x8_font_px437wyse700b_2x2_f);
if (nextTimeDisplay) {
u8x8.drawString(0, 0, "Pressure");
sprintf(outputStr, "%4.1f bar", pressure);
} else {
sprintf(outputStr, "%4.1f", pressure);
}
u8x8.drawString(0, 2, outputStr);
}
if ((temperature1 != lastTempDisplayed1) || nextTimeDisplay) {
lastTempDisplayed1 = temperature1;
u8x8.setFont(u8x8_font_amstrad_cpc_extended_f);
if (nextTimeDisplay) {
if (temperature1 < -100) {
sprintf(outputStr, "Temp1: N.A. ");
} else {
sprintf(outputStr, "Temp1:%7.2f %cC", temperature1, 176);
}
u8x8.drawString(0, 5, outputStr);
} else {
if (temperature1 < -100) {
sprintf(outputStr, " N.A. ");
temp1PrintAll = true;
} else {
if (temp1PrintAll) {
sprintf(outputStr, "%7.2f %cC", temperature1, 176);
} else {
sprintf(outputStr, "%7.2f", temperature1);
}
temp1PrintAll = false;
}
u8x8.drawString(6, 5, outputStr);
}
if ((previousTempIsHigh1 != tempIsHigh1) || (previousErrorTempIsTooHigh1 != ErrorTempIsTooHigh1) || nextTimeDisplay) {
if (ErrorTempIsTooHigh1) {
showStatus(ERRORHIGHTEMP1);
} else {
if (tempIsHigh1) {
showStatus(WARNINGHIGHTEMP1);
} else {
if (!tempIsHigh2) {
showStatus(NOSTATUS);
}
}
}
previousErrorTempIsTooHigh1 = ErrorTempIsTooHigh1;
previousTempIsHigh1 = tempIsHigh1;
}
}
if ((temperature2 != lastTempDisplayed2) || nextTimeDisplay) {
lastTempDisplayed2 = temperature2;
u8x8.setFont(u8x8_font_amstrad_cpc_extended_f);
if (nextTimeDisplay) {
if (temperature2 < -100) {
sprintf(outputStr, "Temp2: N.A. ");
} else {
sprintf(outputStr, "Temp2:%7.2f %cC", temperature2, 176);
}
u8x8.drawString(0, 6, outputStr);
} else {
if (temperature2 < -100) {
sprintf(outputStr, " N.A. ");
temp2PrintAll = true;
} else {
if (temp2PrintAll) {
sprintf(outputStr, "%7.2f %cC", temperature2, 176);
} else {
sprintf(outputStr, "%7.2f", temperature2);
}
temp2PrintAll = false;
}
u8x8.drawString(6, 6, outputStr);
}
if ((previousTempIsHigh2 != tempIsHigh2) || (previousErrorTempIsTooHigh2 != ErrorTempIsTooHigh2) || nextTimeDisplay) {
if (ErrorTempIsTooHigh2) {
showStatus(ERRORHIGHTEMP2);
} else {
if (tempIsHigh2) {
showStatus(WARNINGHIGHTEMP2);
} else {
if (!tempIsHigh1) {
showStatus(NOSTATUS);
}
}
}
previousErrorTempIsTooHigh2 = ErrorTempIsTooHigh2;
previousTempIsHigh2 = tempIsHigh2;
}
}
if ((machinestate != laststateDisplayed) || nextTimeDisplay) {
laststateDisplayed = machinestate;
u8x8.setFont(u8x8_font_amstrad_cpc_extended_f);
if (nextTimeDisplay) {
u8x8.drawString(0, 9, "Machine state: ");
}
switch (machinestate) {
case BOOTING:
sprintf(outputStr, "Booting ");
break;
case OUTOFORDER:
sprintf(outputStr, "Out of order ");
break;
case REBOOT:
sprintf(outputStr, "Reboot ");
break;
case TRANSIENTERROR:
sprintf(outputStr, "Transient error ");
break;
case NOCONN:
sprintf(outputStr, "No connection ");
break;
case SWITCHEDOFF:
sprintf(outputStr, "Switched off ");
break;
case POWERED:
sprintf(outputStr, "On, motor off ");
break;
case RUNNING:
sprintf(outputStr, "Motor is running");
break;
}
u8x8.setFont(u8x8_font_amstrad_cpc_extended_f);
u8x8.drawString(0, 10, outputStr);
}
if ((oilLevelIsTooLow != lastOilLevelDisplayed) || nextTimeDisplay) {
lastOilLevelDisplayed = oilLevelIsTooLow;
if (oilLevelIsTooLow) {
showStatus(ERRORLOWOILLEVEL);
} else {
showStatus(NOLOWOILLEVEL);
}
}
if ((machinestate >= POWERED) || nextTimeDisplay) {
if (machinestate < POWERED) {
poweredTime = (float)powered_total / 3600.0;
} else {
poweredTime = ((float)powered_total + ((float)millis() - float(powered_last)) / 1000.0) / 3600.0;
}
if ((poweredTime != lastPoweredDisplayed) || nextTimeDisplay) {
lastPoweredDisplayed = poweredTime;
u8x8.setFont(u8x8_font_amstrad_cpc_extended_f);
if (nextTimeDisplay) {
sprintf(outputStr, "On: %9.2f hr", poweredTime);
u8x8.drawString(0, 12, outputStr);
} else {
sprintf(outputStr, "%9.2f", poweredTime);
u8x8.drawString(4, 12, outputStr);
}
}
}
if ((machinestate == RUNNING) || nextTimeDisplay) {
if (machinestate < RUNNING) {
runningTime = (float)running_total / 3600.0;
} else {
runningTime = ((float)running_total + ((float)millis() - (float)running_last) / 1000.0) / 3600.0;
}
if ((runningTime != lastRunningDisplayed) || nextTimeDisplay) {
lastRunningDisplayed = runningTime;
u8x8.setFont(u8x8_font_amstrad_cpc_extended_f);
if (nextTimeDisplay) {
sprintf(outputStr, "Run:%9.2f hr", runningTime);
u8x8.drawString(0, 13, outputStr);
} else {
sprintf(outputStr, "%9.2f", runningTime);
u8x8.drawString(4, 13, outputStr);
}
}
}
nextTimeDisplay = false;
}
if (showStatusTemporarily && (millis() > clearStatusLineTime)) {
if (tempIsHigh1 || tempIsHigh2) {
showStatus(WARNINGHIGHTEMP1);
} else {
if (ErrorTempIsTooHigh1) {
showStatus(ERRORHIGHTEMP1);
} else {
if (ErrorTempIsTooHigh2) {
showStatus(ERRORHIGHTEMP2);
} else {
if (ErrorPressureIsToHigh) {
showStatus(ERRORPRESSUREISTOOHIGH);
} else {
showStatus(NOSTATUS);
}
}
}
}
showStatusTemporarily = false;
}
break;
case ERRORDISPLAY:
if (millis() > updateDisplayTime)
{
updateDisplayTime = millis() + DISPLAY_WINDOW;
if (nextTimeDisplay) {
u8x8.setFont(u8x8_font_px437wyse700a_2x2_r);
u8x8.drawString(0, 0, "MAINTAIN");
u8x8.drawString(0, 2, "COMPRSR.");
u8x8.setFont(u8x8_font_px437wyse700a_2x2_r);
u8x8.drawString(0, 12, "COMPRSR.");
u8x8.drawString(0, 14, "DISABLED");
}
if ((previousErrorTempIsTooHigh1 != ErrorTempIsTooHigh1) || (previousErrorTempIsTooHigh2 != ErrorTempIsTooHigh2) || nextTimeDisplay) {
previousErrorTempIsTooHigh1 = ErrorTempIsTooHigh1;
previousErrorTempIsTooHigh2 = ErrorTempIsTooHigh2;
if ((ErrorTempIsTooHigh1) || (ErrorTempIsTooHigh2)) {
u8x8.setFont(u8x8_font_chroma48medium8_r);
if (!ErrorTempIsTooHigh2) {
u8x8.drawString(0, 8, "TEMPERATURE 1 ");
u8x8.drawString(0, 9, "IS TOO HIGH ");
} else {
if (!ErrorTempIsTooHigh1) {
u8x8.drawString(0, 8, "TEMPERATURE 2 ");
u8x8.drawString(0, 9, "IS TOO HIGH ");
} else {
u8x8.drawString(0, 8, "TEMPERATURE 1+2 ");
u8x8.drawString(0, 9, "ARE TOO HIGH ");
}
}
} else {
u8x8.setFont(u8x8_font_chroma48medium8_r);
u8x8.drawString(0, 8, " ");
u8x8.drawString(0, 9, " ");
}
}
if (ErrorTempIsTooHigh1) {
if ((temperature1 != lastTempDisplayed1) || nextTimeDisplay) {
lastTempDisplayed1 = temperature1;
u8x8.setFont(u8x8_font_amstrad_cpc_extended_f);
sprintf(outputStr, "Temp1:%7.2f %cC", temperature1, 176);
u8x8.drawString(0, 10, outputStr);
}
} else {
u8x8.setFont(u8x8_font_amstrad_cpc_extended_f);
u8x8.drawString(0, 10, " ");
}
if (ErrorTempIsTooHigh2) {
if ((temperature2 != lastTempDisplayed2) || nextTimeDisplay) {
lastTempDisplayed2 = temperature2;
u8x8.setFont(u8x8_font_amstrad_cpc_extended_f);
sprintf(outputStr, "Temp2:%7.2f %cC", temperature2, 176);
u8x8.drawString(0, 11, outputStr);
}
} else {
u8x8.setFont(u8x8_font_amstrad_cpc_extended_f);
u8x8.drawString(0, 11, " ");
}
if ((ErrorOilLevelIsTooLow != previousErrorOilLevelIsTooLow) || nextTimeDisplay) {
previousErrorOilLevelIsTooLow = ErrorOilLevelIsTooLow;
if (ErrorOilLevelIsTooLow) {
u8x8.setFont(u8x8_font_chroma48medium8_r);
u8x8.drawString(0, 5, "OIL LEVEL ");
u8x8.drawString(0, 6, "IS TOO LOW ");
} else {
u8x8.setFont(u8x8_font_chroma48medium8_r);
u8x8.drawString(0, 5, " ");
u8x8.drawString(0, 6, " ");
}
}
nextTimeDisplay = false;
}
break;
}
}
| 34.837675 | 145 | 0.583928 | Hans-Beerman |
6b78b03f02739f08f517d4a3b7bac2249562fc2d | 7,330 | cpp | C++ | rtree-run-dataset.cpp | jyuatsfl/avatar | 8bbb5d72fda0857e04d0c76329f32162f6d98a92 | [
"Apache-2.0"
] | 53 | 2020-06-10T09:47:02.000Z | 2022-02-09T01:41:28.000Z | rtree-run-dataset.cpp | SFM2020/avatar | 8c03dbdf4eed15219797285dbac6ca04e8f1b6f4 | [
"Apache-2.0"
] | 5 | 2020-07-08T03:40:34.000Z | 2021-12-22T12:24:33.000Z | rtree-run-dataset.cpp | SFM2020/avatar | 8c03dbdf4eed15219797285dbac6ca04e8f1b6f4 | [
"Apache-2.0"
] | 16 | 2020-06-10T09:47:04.000Z | 2021-12-23T09:54:46.000Z | #include <iostream>
#include <iomanip>
#include <cstring>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include <Eigen/Core>
#include "RTree.h"
namespace {
constexpr char WIND_NAME[] = "Image";
cv::Vec3b paletteColor(int color_index, bool bgr)
{
using cv::Vec3b;
static const Vec3b palette[] = {
Vec3b(0, 220, 255), Vec3b(177, 13, 201), Vec3b(94, 255, 34),
Vec3b(54, 65, 255), Vec3b(64, 255, 255), Vec3b(217, 116, 0),
Vec3b(27, 133, 255), Vec3b(190, 18, 240), Vec3b(20, 31, 210),
Vec3b(75, 20, 133), Vec3b(255, 219, 127), Vec3b(204, 204, 57),
Vec3b(112, 153, 61), Vec3b(64, 204, 46), Vec3b(112, 255, 1),
Vec3b(170, 170, 170), Vec3b(225, 30, 42), Vec3b(255, 255, 32),
Vec3b(255, 45, 250), Vec3b(101, 0, 209), Vec3b(40, 70, 50),
Vec3b(100, 100, 100), Vec3b(105, 200, 120), Vec3b(150,150,150)
};
if (color_index == 255) return Vec3b(0, 0, 0);
Vec3b color = palette[color_index % (int)(sizeof palette / sizeof palette[0])];
return bgr ? color : Vec3b(color[2], color[1], color[0]);
}
}
int main(int argc, char** argv) {
std::vector<std::string> model_paths;
std::string dataset_path;
int image_index;
namespace po = boost::program_options;
po::options_description desc("Option arguments");
po::options_description descPositional("OpenARK Random Tree/Forest empirical validation tool, for directly loading avatar dataset v0.1 (c) Alex Yu 2019\nPositional arguments");
po::options_description descCombined("");
desc.add_options()
("help", "Produce help message")
;
descPositional.add_options()
("dataset", po::value<std::string>(&dataset_path)->required(), "Dataset root path (should have depth_exr, part_mask subdirs)")
("image", po::value<int>(&image_index)->required(), "Image index to use")
("models", po::value<std::vector<std::string> >(&model_paths)->required(), "Model path (from rtree-train)")
;
descCombined.add(descPositional);
descCombined.add(desc);
po::variables_map vm;
po::positional_options_description posopt;
posopt.add("dataset", 1);
posopt.add("image", 1);
posopt.add("models", -1);
try {
po::store(po::command_line_parser(argc, argv).options(descCombined)
.positional(posopt).run(),
vm);
} catch (std::exception& e) {
std::cerr << "Error: " << e.what() << "\n";
std::cerr << descPositional << "\n" << desc << "\n";
return 1;
}
if ( vm.count("help") )
{
std::cout << descPositional << "\n" << desc << "\n";
return 0;
}
try {
po::notify(vm);
} catch (std::exception& e) {
std::cerr << "Error: " << e.what() << "\n";
std::cerr << descPositional << "\n" << desc << "\n";
return 1;
}
if (model_paths.empty()) {
std::cerr << "Error: please specify at least one model path" << "\n";
std::cerr << descPositional << "\n" << desc << "\n";
return 1;
}
using boost::filesystem::path;
using boost::filesystem::exists;
std::vector<ark::RTree> rtrees;
for (auto& model_path: model_paths) {
rtrees.emplace_back(model_path);
}
bool show_mask = false;
while (true) {
std::cerr << image_index << " LOAD\n";
std::stringstream ss_img_id;
ss_img_id << std::setw(8) << std::setfill('0') << std::to_string(image_index);
if (show_mask) {
std::string mask_path = (path(dataset_path) / "part_mask" / ("part_mask_" + ss_img_id.str() + ".tiff")).string();
if (!exists(mask_path)) {
mask_path = (path(dataset_path) / "part_mask" / ("part_mask_" + ss_img_id.str() + ".png")).string();
}
cv::Mat mask = cv::imread(mask_path, cv::IMREAD_GRAYSCALE);
cv::Mat mask_color = cv::imread(mask_path);
for (int r = 0; r < mask.rows; ++r) {
auto* maskPtr = mask.ptr<uint8_t>(r);
auto* outPtr = mask_color.ptr<cv::Vec3b>(r);
for (int c = 0; c < mask.cols; ++c){
outPtr[c] = paletteColor(maskPtr[c], true);
}
}
cv::imshow(WIND_NAME, mask_color);
} else {
std::string image_path = (path(dataset_path) / "depth_exr" / ("depth_" + ss_img_id.str() + ".exr")).string();
cv::Mat image = cv::imread(image_path, cv::IMREAD_ANYCOLOR | cv::IMREAD_ANYDEPTH);
cv::Mat visual = cv::Mat::zeros(image.size(), CV_8UC3);
if (rtrees.size() > 1) {
std::vector<cv::Mat> result;
for (auto& rtree : rtrees) {
std::vector<cv::Mat> model_results = rtree.predict(image);
if (result.empty()) result = model_results;
else {
for (size_t i = 0; i < result.size(); ++i) {
result[i] += model_results[i];
}
}
}
// for (size_t i = 0; i < result.size(); ++i) {
// result[i] /= model_paths.size();
// }
cv::Mat maxVals(image.size(), CV_32F);
maxVals.setTo(0);
for (size_t i = 0; i < result.size(); ++i) {
for (int r = 0; r < image.rows; ++r) {
auto* imPtr = image.ptr<float>(r);
auto* inPtr = result[i].ptr<float>(r);
auto* maxValPtr = maxVals.ptr<float>(r);
auto* visualPtr = visual.ptr<cv::Vec3b>(r);
for (int c = 0; c < image.cols; ++c){
if (imPtr[c] == 0.0) continue;
if (inPtr[c] > maxValPtr[c]) {
maxValPtr[c] = inPtr[c];
visualPtr[c] = paletteColor(i, true);
}
}
}
}
} else {
cv::Mat result = rtrees[0].predictBest(image, std::thread::hardware_concurrency());
for (int r = 0; r < image.rows; ++r) {
auto* inPtr = result.ptr<uint8_t>(r);
auto* visualPtr = visual.ptr<cv::Vec3b>(r);
for (int c = 0; c < image.cols; ++c){
if (inPtr[c] == 255) continue;
visualPtr[c] = paletteColor(inPtr[c], true);
}
}
}
cv::imshow(WIND_NAME, visual);
}
int k = cv::waitKey(0);
if (k == 'q' || k == 27) break;
else if (k == 'a' && image_index >= 0) {
--image_index;
} else if (k == 'd') {
++image_index;
} else if (k == 'm') {
show_mask = !show_mask;
}
}
/*
for (size_t i = 0; i < result.size(); ++i) {
std::cerr << i << "\n";
cv::normalize(result[i], result[i], 0.0, 1.0, cv::NORM_MINMAX);
cv::imshow(WIND_NAME, result[i]);
cv::waitKey(0);
}
*/
return 0;
}
| 37.589744 | 180 | 0.499181 | jyuatsfl |
6b78f2bbe172f47b2f3292a5fc446c833d8d57c0 | 1,250 | hpp | C++ | src/main/cpp/pistis/json/util/Utf8CharEncoder.hpp | tomault/pistis-json | db39580d3e905dc4fbdbb22b06f4670cc3d76b04 | [
"Apache-2.0"
] | null | null | null | src/main/cpp/pistis/json/util/Utf8CharEncoder.hpp | tomault/pistis-json | db39580d3e905dc4fbdbb22b06f4670cc3d76b04 | [
"Apache-2.0"
] | null | null | null | src/main/cpp/pistis/json/util/Utf8CharEncoder.hpp | tomault/pistis-json | db39580d3e905dc4fbdbb22b06f4670cc3d76b04 | [
"Apache-2.0"
] | null | null | null | #ifndef __PISTIS__JSON__UTIL__UTF8CHARENCODER_HPP__
#define __PISTIS__JSON__UTIL__UTF8CHARENCODER_HPP__
#include <pistis/exceptions/IllegalValueError.hpp>
#include <iomanip>
#include <sstream>
namespace pistis {
namespace json {
namespace util {
class Utf8CharEncoder {
public:
template <typename Buffer>
void encodeChar(Buffer& buffer, uint32_t c) const {
if (c < 0x80) {
buffer.write((char)c);
} else if (c < 0x800) {
buffer.write((char)(0xC0 | (c >> 6)));
buffer.write((char)(0x80 | (c & 0x3F)));
} else if (c < 0x10000) {
buffer.write((char)(0xE0 | (c >> 12)));
buffer.write((char)(0x80 | ((c >> 6) & 0x3F)));
buffer.write((char)(0x80 | (c & 0x3F)));
} else if (c < 0x200000) {
buffer.write((char)(0xF0 | (c >> 18)));
buffer.write((char)(0x80 | ((c >> 12) & 0x3F)));
buffer.write((char)(0x80 | ((c >> 6) & 0x3F)));
buffer.write((char)(0x80 | (c & 0x3F)));
} else {
std::ostringstream msg;
msg << "Cannot encode character 0x" << std::width(4)
<< std::fill('0') << std::hex << c
<< ", which has more than 21 bits";
throw pistis::exceptions::IllegalValueError(msg.str(),
PISTIS_EX_HERE);
}
}
};
}
}
}
#endif
| 26.041667 | 59 | 0.5864 | tomault |
6b7a9c6c404706d744b31eb8b2213748ac982b19 | 751 | cpp | C++ | CPP/Leet Code Solutions/add-two-numbers/add-two-numbers.cpp | thefool76/hacktoberfest2021 | 237751e17a4fc325ded29fca013fb9f5853cd27c | [
"CC0-1.0"
] | 448 | 2021-10-01T04:24:14.000Z | 2022-03-06T14:34:20.000Z | CPP/Leet Code Solutions/add-two-numbers/add-two-numbers.cpp | Chanaka-Madushan-Herath/hacktoberfest2021 | 8473df9e058ccb6049720dd372342e0ea60f0e59 | [
"CC0-1.0"
] | 282 | 2021-10-01T04:29:06.000Z | 2022-03-07T12:42:57.000Z | CPP/Leet Code Solutions/add-two-numbers/add-two-numbers.cpp | Chanaka-Madushan-Herath/hacktoberfest2021 | 8473df9e058ccb6049720dd372342e0ea60f0e59 | [
"CC0-1.0"
] | 1,807 | 2021-10-01T04:24:02.000Z | 2022-03-28T04:51:25.000Z | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode preNode(-1), *p = &preNode;
int carry = 0, sum;
while(l1 || l2 || carry){
sum = (l1?l1->val:0) + (l2?l2->val:0) + carry;
p->next = new ListNode(sum%10);
carry = sum/10;
p = p->next;
l1 = l1?l1->next:l1;
l2 = l2?l2->next:l2;
}
return preNode.next;
}
}; | 26.821429 | 62 | 0.478029 | thefool76 |
6b7b4f0f7e85896b28c57915ef7f051fa7a6da73 | 4,979 | cpp | C++ | entity_manager.cpp | jasonhutchens/kranzky_ice | 8b1cf40f7948ac8811cdf49729d1df0acb7fc611 | [
"Unlicense"
] | 4 | 2016-06-05T04:36:12.000Z | 2016-08-21T20:11:49.000Z | entity_manager.cpp | kranzky/kranzky_ice | 8b1cf40f7948ac8811cdf49729d1df0acb7fc611 | [
"Unlicense"
] | null | null | null | entity_manager.cpp | kranzky/kranzky_ice | 8b1cf40f7948ac8811cdf49729d1df0acb7fc611 | [
"Unlicense"
] | null | null | null | //==============================================================================
#include <entity_manager.hpp>
#include <entity.hpp>
#include <engine.hpp>
#include <hgeResource.h>
#include <sstream>
#include <cstdarg>
//------------------------------------------------------------------------------
EntityManager::EntityManager()
:
m_registry(),
m_entities(),
m_sprites(),
m_names(),
m_new_entities()
{
}
//------------------------------------------------------------------------------
EntityManager::~EntityManager()
{
fini();
}
//------------------------------------------------------------------------------
void
EntityManager::init()
{
}
//------------------------------------------------------------------------------
void
EntityManager::update( float dt )
{
std::vector< Entity * >::iterator i( m_entities.begin() );
while ( i != m_entities.end() )
{
( * i )->update( dt );
if ( ( * i )->isGone() )
{
delete ( * i );
i = m_entities.erase( i );
}
else
{
++i;
}
}
while ( m_new_entities.size() > 0 )
{
m_entities.push_back( m_new_entities.back() );
m_new_entities.pop_back();
}
}
//------------------------------------------------------------------------------
void
EntityManager::fini()
{
while ( m_entities.size() > 0 )
{
delete m_entities.back();
m_entities.pop_back();
}
while ( m_new_entities.size() > 0 )
{
delete m_new_entities.back();
m_new_entities.pop_back();
}
m_registry.clear();
m_sprites.clear();
m_names.clear();
}
//------------------------------------------------------------------------------
void
EntityManager::registerEntity( unsigned int type, Entity * ( * factory )(),
const char * table, const char * query )
{
std::map< unsigned int, EntityData >::iterator i( m_registry.find( type ) );
if ( i != m_registry.end() )
{
Engine::hge()->System_Log( "Cannot register same entity twice." );
return;
}
EntityData data;
data.m_factory = factory;
data.m_table = table;
data.m_query = query;
m_registry.insert( std::pair< unsigned int, EntityData >( type, data ) );
}
//------------------------------------------------------------------------------
sqlite_int64
EntityManager::registerSprite( const char * cname )
{
std::string name( cname );
std::map< std::string, sqlite_int64 >::iterator i( m_names.find( name ) );
if ( i != m_names.end() )
{
return m_names[name];
}
sqlite_int64 id( 0 );
for ( id = 0; m_sprites.find( id ) != m_sprites.end(); ++id );
m_names[name] = id;
m_sprites[id] = Engine::rm()->GetSprite( cname );
return id;
}
//------------------------------------------------------------------------------
Entity *
EntityManager::factory( unsigned int type, bool add )
{
std::map< unsigned int, EntityData >::iterator i( m_registry.find( type ) );
if ( i == m_registry.end() )
{
Engine::hge()->System_Log( "Tried to create unregistered entity." );
return 0;
}
Entity * entity( i->second.m_factory() );
entity->setType( type );
if ( add )
{
m_new_entities.push_back( entity );
}
return entity;
}
//------------------------------------------------------------------------------
std::vector< Entity * >
EntityManager::databaseFactory( unsigned int type )
{
std::vector< Entity * > retval;
return retval;
}
//------------------------------------------------------------------------------
sqlite_int64
EntityManager::persistToDatabase( Entity * entity, char * rows[], ... )
{
return 0;
}
//------------------------------------------------------------------------------
void
EntityManager::deleteFromDatabase( Entity * entity )
{
}
//------------------------------------------------------------------------------
hgeSprite *
EntityManager::getSprite( sqlite_int64 sprite_id )
{
std::map< sqlite_int64,hgeSprite * >::iterator i(m_sprites.find(sprite_id));
if ( i == m_sprites.end() )
{
Engine::hge()->System_Log( "Cannot find referenced sprite." );
return 0;
}
return m_sprites[sprite_id];
}
//------------------------------------------------------------------------------
std::vector<Entity*>
EntityManager::getEntities(unsigned int type)
{
std::vector< Entity * > entities;
std::vector< Entity * >::iterator i;
for ( i = m_entities.begin(); i != m_entities.end(); ++i )
{
Entity* ent = (*i);
if (ent->getType() == type)
{
entities.push_back(ent);
}
}
return entities;
}
//==============================================================================
| 26.625668 | 81 | 0.420165 | jasonhutchens |
6b7c08973280db624a523f6c53e5003ed6ac2865 | 3,957 | cpp | C++ | Spark/ShapeCreator.cpp | MickAlmighty/SparkRenderer | 0e30e342c7cf4003da54e9ce191fead647a868eb | [
"MIT"
] | 1 | 2022-02-15T19:50:01.000Z | 2022-02-15T19:50:01.000Z | Spark/ShapeCreator.cpp | MickAlmighty/SparkRenderer | 0e30e342c7cf4003da54e9ce191fead647a868eb | [
"MIT"
] | null | null | null | Spark/ShapeCreator.cpp | MickAlmighty/SparkRenderer | 0e30e342c7cf4003da54e9ce191fead647a868eb | [
"MIT"
] | null | null | null | #include "ShapeCreator.h"
#include <cstring>
#include <glm/gtx/rotate_vector.hpp>
constexpr double pi = 3.14159265358979323846;
namespace spark
{
std::vector<glm::vec3> ShapeCreator::createSphere(float radius, int precision, glm::vec3 centerPoint)
{
if(radius < 0.0f)
return {};
if(precision < 3)
return {};
std::vector<glm::vec3> vertices;
const float radStep = 2.0f * static_cast<float>(pi) / static_cast<float>(precision);
float angle = 0.0f;
for(int i = 0; i < precision; ++i)
{
createSphereSegment(&vertices, angle, i == precision - 1 ? 2.0f * static_cast<float>(pi) - angle : radStep, radius, precision, centerPoint);
angle += radStep;
}
return vertices;
}
void ShapeCreator::createSphereSegment(std::vector<glm::vec3>* vertices, float angle, float radStep, float radius, int precision,
glm::vec3 centerPoint)
{
std::vector<glm::vec3> circle(precision);
float circleAngle = -pi / 2.0f;
const float vertRadStep = pi / (static_cast<float>(precision) - 1.0f);
for(int i = 0; i < precision; ++i)
{
if(i == precision - 1)
{
circle[i].x = 0.0f;
circle[i].y = radius;
}
else if(i == 0)
{
circle[i].x = 0.0f;
circle[i].y = -radius;
}
else
{
circle[i].x = radius * cos(circleAngle);
circle[i].y = radius * sin(circleAngle);
}
circle[i].z = 0.0f;
circleAngle += vertRadStep;
}
const glm::vec3 rotateAxis(0.0f, 1.0f, 0.0f);
for(int i = 0; i < precision; i++)
{
circle[i] = rotate(circle[i], angle, rotateAxis);
}
std::vector<glm::vec3> circle2(precision);
std::memcpy(circle2.data(), circle.data(), precision * sizeof(glm::vec3));
for(int i = 0; i < precision; ++i)
{
circle2[i] = rotate(circle2[i], radStep, rotateAxis);
}
for(int i = 0; i < precision - 1; ++i)
{
if(i == 0)
{
createTriangle(vertices, circle[i], circle[i + 1], circle2[i + 1], centerPoint);
}
else if(i == precision - 2)
{
createTriangle(vertices, circle[i + 1], circle2[i], circle[i], centerPoint);
}
else
{
createRectangle(vertices, circle[i], circle2[i], circle2[i + 1], circle[i + 1], centerPoint);
}
}
}
void ShapeCreator::createRectangle(std::vector<glm::vec3>* vertices, const glm::vec3& tL, const glm::vec3& tR, const glm::vec3& dR,
const glm::vec3& dL, glm::vec3 centerPoint)
{
const glm::vec3 horizontal = dR - dL;
const glm::vec3 vertical = tL - dL;
// glm::vec3 normal = cross(vertical, horizontal);
glm::vec3 output[4];
/*for (int i = 0; i < 4; i++) {
output[i].Normal = normal;
}*/
output[0] = tL + centerPoint;
output[1] = tR + centerPoint;
output[2] = dR + centerPoint;
output[3] = dL + centerPoint;
vertices->push_back(output[0]);
vertices->push_back(output[2]);
vertices->push_back(output[3]);
vertices->push_back(output[0]);
vertices->push_back(output[1]);
vertices->push_back(output[2]);
}
void ShapeCreator::createTriangle(std::vector<glm::vec3>* vertices, const glm::vec3& up, const glm::vec3& right, const glm::vec3& left,
glm::vec3 centerPoint)
{
const glm::vec3 horizontal = right - left;
const glm::vec3 vertical = up - left;
// const glm::vec3 normal = cross(horizontal, vertical);
glm::vec3 output[3];
/*for (int i = 0; i < 3; i++) {
output[i].Normal = normal;
}*/
output[0] = up + centerPoint;
output[1] = right + centerPoint;
output[2] = left + centerPoint;
vertices->push_back(output[0]);
vertices->push_back(output[2]);
vertices->push_back(output[1]);
}
} // namespace spark
| 28.06383 | 148 | 0.564064 | MickAlmighty |
6b7c3b1188b77990433a6f6ce8f5a8a43f6367c2 | 1,863 | cc | C++ | tf_euler/utils/init_nebula_graph.cc | MMyheart/euler | d5910cec735daa7b2f94dc7675a376ffc649b128 | [
"Apache-2.0"
] | null | null | null | tf_euler/utils/init_nebula_graph.cc | MMyheart/euler | d5910cec735daa7b2f94dc7675a376ffc649b128 | [
"Apache-2.0"
] | null | null | null | tf_euler/utils/init_nebula_graph.cc | MMyheart/euler | d5910cec735daa7b2f94dc7675a376ffc649b128 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2021 Alibaba Group Holding Limited. All Rights Reserved.
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 "nebula/NebulaClient.h"
void splitString(const std::string &s, std::vector<std::string> &v,
const std::string &c)
{
std::string::size_type pos1, pos2;
pos2 = s.find(c);
pos1 = 0;
while (std::string::npos != pos2)
{
v.push_back(s.substr(pos1, pos2 - pos1));
pos1 = pos2 + c.size();
pos2 = s.find(c, pos1);
}
if (pos1 != s.length())
{
v.push_back(s.substr(pos1));
}
}
extern "C"
{
bool InitNebulaGraph(char *arg, uint32_t port, int32_t timeout, uint32_t minConnectionNum, uint32_t maxConnectionNum)
{
std::string str = arg;
std::vector<std::string> vec;
splitString(str, vec, ",");
std::vector<std::pair<std::string, uint32_t>> addrs;
addrs.reserve(vec.size());
for (int i = 0; i < vec.size(); i++)
{
std::string ip = vec[i];
addrs.emplace_back(ip, port);
}
nebula::ConnectionInfo connectionInfo;
connectionInfo.addrs = std::move(addrs);
connectionInfo.timeout = timeout;
connectionInfo.minConnectionNum = minConnectionNum;
connectionInfo.maxConnectionNum = maxConnectionNum;
nebula::NebulaClient::initConnectionPool(connectionInfo);
return true;
}
}
| 31.05 | 119 | 0.661299 | MMyheart |
6b7c98ce8f1ae5ba9c190e80bbcccd50fc74afc3 | 620 | cpp | C++ | Engine/Source/Editor/AudioEditor/Private/Factories/SoundConcurrencyFactory.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Editor/AudioEditor/Private/Factories/SoundConcurrencyFactory.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Editor/AudioEditor/Private/Factories/SoundConcurrencyFactory.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "Factories/SoundConcurrencyFactory.h"
#include "Sound/SoundConcurrency.h"
USoundConcurrencyFactory::USoundConcurrencyFactory(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
SupportedClass = USoundConcurrency::StaticClass();
bCreateNew = true;
bEditorImport = false;
bEditAfterNew = true;
}
UObject* USoundConcurrencyFactory::FactoryCreateNew(UClass* Class, UObject* InParent, FName Name, EObjectFlags Flags, UObject* Context, FFeedbackContext* Warn)
{
return NewObject<USoundConcurrency>(InParent, Name, Flags);
}
| 31 | 159 | 0.803226 | windystrife |
6b7f7e2fe5c718d23ef535be5580e276a4f357bc | 1,951 | cpp | C++ | packages/ogdf.js/src/module/src/InitialPlacer.cpp | ZJUVAI/ogdf.js | 6670d20b6c630a46593ac380d1edf91d2c9aabe8 | [
"MIT"
] | 3 | 2021-09-14T08:11:37.000Z | 2022-03-04T15:42:07.000Z | packages/ogdf.js/src/module/src/InitialPlacer.cpp | JackieAnxis/ogdf.js | 6670d20b6c630a46593ac380d1edf91d2c9aabe8 | [
"MIT"
] | 2 | 2021-12-04T17:09:53.000Z | 2021-12-16T08:57:25.000Z | packages/ogdf.js/src/module/src/InitialPlacer.cpp | ZJUVAI/ogdf.js | 6670d20b6c630a46593ac380d1edf91d2c9aabe8 | [
"MIT"
] | 2 | 2021-06-22T08:21:54.000Z | 2021-07-07T06:57:22.000Z | #include "../main.h"
#include <ogdf/energybased/multilevel_mixer/BarycenterPlacer.h>
#include <ogdf/energybased/multilevel_mixer/CirclePlacer.h>
#include <ogdf/energybased/multilevel_mixer/MedianPlacer.h>
#include <ogdf/energybased/multilevel_mixer/RandomPlacer.h>
#include <ogdf/energybased/multilevel_mixer/SolarPlacer.h>
#include <ogdf/energybased/multilevel_mixer/ZeroPlacer.h>
EM_PORT_API(BarycenterPlacer *)
InitialPlacer_BarycenterPlacer(bool randomOffset, bool weightedPositionPriority)
{
BarycenterPlacer *placer = new BarycenterPlacer();
placer->setRandomOffset(randomOffset);
placer->weightedPositionPriority(weightedPositionPriority);
return placer;
}
EM_PORT_API(CirclePlacer *)
InitialPlacer_CirclePlacer(float circleSize, int nodeSelection, bool radiusFixed, bool randomOffset)
{
CirclePlacer *placer = new CirclePlacer();
placer->setCircleSize(circleSize);
placer->setNodeSelection(static_cast<CirclePlacer::NodeSelection>(nodeSelection));
placer->setRadiusFixed(radiusFixed);
placer->setRandomOffset(randomOffset);
return placer;
}
EM_PORT_API(MedianPlacer *)
InitialPlacer_MedianPlacer(bool randomOffset)
{
MedianPlacer *placer = new MedianPlacer();
placer->setRandomOffset(randomOffset);
return placer;
}
EM_PORT_API(RandomPlacer *)
InitialPlacer_RandomPlacer(bool randomOffset, double circleSize)
{
RandomPlacer *placer = new RandomPlacer();
placer->setRandomOffset(randomOffset);
placer->setCircleSize(circleSize);
return placer;
}
EM_PORT_API(SolarPlacer *)
InitialPlacer_SolarPlacer(bool randomOffset)
{
SolarPlacer *placer = new SolarPlacer();
placer->setRandomOffset(randomOffset);
return placer;
}
EM_PORT_API(ZeroPlacer *)
InitialPlacer_ZeroPlacer(double randomRange, bool randomOffset)
{
ZeroPlacer *placer = new ZeroPlacer();
placer->setRandomRange(randomRange);
placer->setRandomOffset(randomOffset);
return placer;
}
| 30.968254 | 100 | 0.785751 | ZJUVAI |
6b812e16b1b874e106d2f3934e718069d869b33a | 1,361 | cpp | C++ | LightOJ/1191 - Bar Codes.cpp | shamiul94/Problem-Solving-Online-Judges | 0387ccd02cc692c70429b4683311070dc9d69b28 | [
"MIT"
] | 2 | 2019-11-10T18:42:11.000Z | 2020-07-04T07:05:22.000Z | LightOJ/1191 - Bar Codes.cpp | shamiul94/Problem-Solving-Online-Judges | 0387ccd02cc692c70429b4683311070dc9d69b28 | [
"MIT"
] | null | null | null | LightOJ/1191 - Bar Codes.cpp | shamiul94/Problem-Solving-Online-Judges | 0387ccd02cc692c70429b4683311070dc9d69b28 | [
"MIT"
] | 1 | 2019-11-04T11:05:17.000Z | 2019-11-04T11:05:17.000Z | // LightOJ always needs this format for sure..so I made a copy of it...
#include <bits/stdc++.h>
#include<vector>
#define ll long long int
#define fi freopen("in.txt", "r", stdin)
#define fo freopen("out.txt", "w", stdout)
#define m0(a) memset(a , 0 , sizeof(a))
#define m1(a) memset(a , -1 , sizeof(a))
#define inf LLONG_MAX
#define min3(a, b, c) min(a,min(b,c))
#define max3(a, b, c) max(a,max(b,c))
#define ones(mask) __builtin_popcount(mask) /// __builtin_popcount : it's a built in function of GCC. Finds out the numbers of 1 in binary representation.
#define mx 150000
#define mod 10056
using namespace std;
ll N, K, Max;
ll dp[60][60][60];
ll solve(ll n, ll k, ll M) {
if (n == 0 && k == 0) return 1;
if (n <= 0 || k <= 0) return 0;
if (dp[n][k][M] != -1) return dp[n][k][M];
ll ans = 0;
for (ll i = 1; i <= M; i++) {
ans += solve(n - i, k - 1, M);
}
dp[n][k][M] = ans;
return dp[n][k][M];
}
int main() {
// fi;
// fo;
m1(dp);
ll T, t = 0;
scanf("%lld", &T);
while (T--) {
t++;
scanf("%lld %lld %lld", &N, &K, &Max);
printf("Case %lld: ", t);
ll ans;
ans = solve(N, K, Max);
printf("%lld\n", ans);
}
return 0;
}
| 23.877193 | 155 | 0.486407 | shamiul94 |
6b86d28ee53ed184f4f4c4741fa63e439e49332e | 399 | cpp | C++ | diag.cpp | kaushalvivek/programming-practice | 23cb71b7c9a5144926ce472294d8f4113bcc5086 | [
"MIT"
] | null | null | null | diag.cpp | kaushalvivek/programming-practice | 23cb71b7c9a5144926ce472294d8f4113bcc5086 | [
"MIT"
] | null | null | null | diag.cpp | kaushalvivek/programming-practice | 23cb71b7c9a5144926ce472294d8f4113bcc5086 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main() {
int n,temp;
cin >> n;
int d1 = 0, d2 = 0;
for(int j = 1,i = 1;i < n || j < n+1 ; i++) {
cin >> temp;
if(i>n)i%=n;
if (i == j) d1 += temp;
if (i == n-j+1) d2+=temp;
if (i == n) j++;
//cout << "i is " << i <<" ||| j is " << j << " ||| d1 is " << d1 << " ||| d2 is " << d2 << endl;
}
cout << abs(d1-d2) << endl;
return 0;
} | 22.166667 | 99 | 0.418546 | kaushalvivek |
6b87577d459e6ac851f43a6e95106c6b94b68af4 | 25 | cpp | C++ | Source/Utility/TextureLoader.cpp | reo-prg/TurnZ_code | f079c27921e2597bb824eba416b8b9a31258580c | [
"Unlicense"
] | null | null | null | Source/Utility/TextureLoader.cpp | reo-prg/TurnZ_code | f079c27921e2597bb824eba416b8b9a31258580c | [
"Unlicense"
] | null | null | null | Source/Utility/TextureLoader.cpp | reo-prg/TurnZ_code | f079c27921e2597bb824eba416b8b9a31258580c | [
"Unlicense"
] | null | null | null | #include <DirectXTex.h>
| 8.333333 | 23 | 0.72 | reo-prg |
6b897acf6092080c0e6a1ce1abe3cc23b2c68296 | 2,191 | cpp | C++ | Scene.cpp | KosukeTakahashi/CoSDL | 9e7ae8e2f9f2434eca2236e25c6bcf54d5af716e | [
"MIT"
] | null | null | null | Scene.cpp | KosukeTakahashi/CoSDL | 9e7ae8e2f9f2434eca2236e25c6bcf54d5af716e | [
"MIT"
] | null | null | null | Scene.cpp | KosukeTakahashi/CoSDL | 9e7ae8e2f9f2434eca2236e25c6bcf54d5af716e | [
"MIT"
] | null | null | null | #include <SDL.h>
#include "./Scene.hpp"
#include "evcodes.hpp"
#include "logger.hpp"
Scene::Scene() {
}
Scene::~Scene() {
}
bool Scene::run(int fps, SDL_Renderer *renderer) {
auto intervalMs = fps <= 0 ? 0 : 1000 / fps;
SDL_Event ev;
while (true) {
auto start = SDL_GetTicks();
while (SDL_PollEvent(&ev)) {
if (ev.type == SDL_QUIT)
return true;
if (ev.type == SDL_USEREVENT) {
if (ev.user.code == static_cast<int>(EventCodes::QUIT))
return true;
else if (ev.user.code == static_cast<int>(EventCodes::EXIT_SCENE))
return false;
}
}
for (const auto &obj : this->objects) {
obj->update();
}
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_RenderClear(renderer);
for (const auto &obj : this->objects) {
obj->render(renderer);
}
SDL_RenderPresent(renderer);
auto end = SDL_GetTicks();
auto elapsed = end - start;
if (elapsed < intervalMs) {
SDL_Delay(intervalMs - elapsed);
}
}
}
std::shared_ptr<GameObject> Scene::addGameObject(std::string label) {
// Check if a object of the same label exists
for (auto obj : this->objects) {
if (obj->label == label) {
Logger::warn("Scene#addGameObject", "A object of the same label found. Abort.");
return nullptr;
}
}
auto obj = std::make_shared<GameObject>();
obj->label = label;
obj->parent = this;
obj->start();
this->objects.push_back(obj);
return obj;
}
std::shared_ptr<GameObject> Scene::getGameObject(std::string label) {
for (auto obj : this->objects) {
if (obj->label == label) {
return obj;
}
}
return nullptr;
}
bool Scene::removeGameObject(std::string label) {
auto targetIter = this->objects.begin();
for (; targetIter != this->objects.end(); targetIter++) {
if ((*targetIter)->label == label) {
this->objects.erase(targetIter);
return true;
}
}
return false;
}
| 25.776471 | 92 | 0.545413 | KosukeTakahashi |
6b951db2f0edf984e31abad90d864157ad8bb550 | 568 | cpp | C++ | template/specialization.cpp | 0iui0/Cpp-Primer | ff8530a202ac0340a3e8de6bb9726cf0516c50fc | [
"CC0-1.0"
] | null | null | null | template/specialization.cpp | 0iui0/Cpp-Primer | ff8530a202ac0340a3e8de6bb9726cf0516c50fc | [
"CC0-1.0"
] | null | null | null | template/specialization.cpp | 0iui0/Cpp-Primer | ff8530a202ac0340a3e8de6bb9726cf0516c50fc | [
"CC0-1.0"
] | null | null | null | //
// Created by iouoi on 2021/5/29.
//
//1.full specialization
//指定任意类型会走这里
template<class Key>
struct hash {
};
//指定以下类型会走这里
template<>
struct hash<int> {
size_t operator(
int x){ return x; };
}
template<>
//cout<<hash<long>()(1000)<<endl;
struct hash<long> {
size_t operator(
long x){ return x; };
}
//2.partial specialization 个数偏
template<typename T, typename Alloc= ...>
class vector {
};
template<typename Alloc= ...>
class vector<bool, Alloc> {
};
//范围偏 任意类型-->指针类型
template<typename T>
class C {
};
template<typename U>
class C<U *> {
}; | 13.853659 | 41 | 0.646127 | 0iui0 |
6b96be766f6f9d3cd5fba220af39669fa1a5ab3b | 4,369 | hpp | C++ | PCL SAC + Boost/SampleConsensusProblem.hpp | erfannoury/sac | 7e4c183a91bf16803bc78536476bba594bfba109 | [
"MIT"
] | 7 | 2016-10-19T12:35:06.000Z | 2019-06-26T08:19:24.000Z | PCL SAC + Boost/SampleConsensusProblem.hpp | erfannoury/sac | 7e4c183a91bf16803bc78536476bba594bfba109 | [
"MIT"
] | null | null | null | PCL SAC + Boost/SampleConsensusProblem.hpp | erfannoury/sac | 7e4c183a91bf16803bc78536476bba594bfba109 | [
"MIT"
] | null | null | null | #ifndef ASLAM_SAMPLE_CONSENSUS_PROBLEM_HPP
#define ASLAM_SAMPLE_CONSENSUS_PROBLEM_HPP
#include <boost/random.hpp>
#include <boost/shared_ptr.hpp>
#include <ctime>
namespace aslam {
template<typename MODEL_T>
class SampleConsensusProblem
{
public:
typedef MODEL_T model_t;
SampleConsensusProblem(bool randomSeed = true);
virtual ~SampleConsensusProblem();
virtual void getSamples(int &iterations, std::vector<int> &samples);
virtual bool isSampleGood(const std::vector<int> & sample) const;
/** \brief Get a pointer to the vector of indices used. */
boost::shared_ptr <std::vector<int> > getIndices() const;
void drawIndexSample (std::vector<int> & sample);
virtual int getSampleSize() const = 0;
virtual bool computeModelCoefficients( const std::vector<int> & indices, model_t & outModel) const = 0;
/** \brief Recompute the model coefficients using the given inlier set
* and return them to the user. Pure virtual.
*
* @note: these are the coefficients of the model after refinement
* (e.g., after a least-squares optimization)
*
* \param[in] inliers the data inliers supporting the model
* \param[in] model_coefficients the initial guess for the model coefficients
* \param[out] optimized_coefficients the resultant recomputed coefficients after non-linear optimization
*/
virtual void optimizeModelCoefficients (const std::vector<int> & inliers,
const model_t & model_coefficients,
model_t & optimized_coefficients) = 0;
/// \brief evaluate the score for the elements at indices based on this model.
/// low scores mean a good fit.
virtual void getSelectedDistancesToModel( const model_t & model,
const std::vector<int> & indices,
std::vector<double> & scores) const = 0;
/** \brief Compute all distances from the cloud data to a given model. Pure virtual.
*
* \param[in] model_coefficients the coefficients of a model that we need to compute distances to
* \param[out] distances the resultant estimated distances
*/
virtual void getDistancesToModel (const model_t & model_coefficients,
std::vector<double> &distances);
/** \brief Select all the points which respect the given model
* coefficients as inliers. Pure virtual.
*
* \param[in] model_coefficients the coefficients of a model that we need to compute distances to
* \param[in] threshold a maximum admissible distance threshold for determining the inliers from
* the outliers
* \param[out] inliers the resultant model inliers
*/
virtual void selectWithinDistance (const model_t &model_coefficients,
const double threshold,
std::vector<int> &inliers);
/** \brief Count all the points which respect the given model
* coefficients as inliers. Pure virtual.
*
* \param[in] model_coefficients the coefficients of a model that we need to
* compute distances to
* \param[in] threshold a maximum admissible distance threshold for
* determining the inliers from the outliers
* \return the resultant number of inliers
*/
virtual int countWithinDistance (const model_t &model_coefficients,
const double threshold);
void setIndices(const std::vector<int> & indices);
void setUniformIndices(int N);
int rnd();
int max_sample_checks_;
boost::shared_ptr< std::vector<int> > indices_;
std::vector<int> shuffled_indices_;
/** \brief Boost-based random number generator algorithm. */
boost::mt19937 rng_alg_;
/** \brief Boost-based random number generator distribution. */
boost::shared_ptr<boost::uniform_int<> > rng_dist_;
/** \brief Boost-based random number generator. */
boost::shared_ptr<boost::variate_generator< boost::mt19937&, boost::uniform_int<> > > rng_gen_;
};
} // namespace aslam
#include "implementation/SampleConsensusProblem.hpp"
#endif /* ASLAM_SAMPLE_CONSENSUS_PROBLEM_HPP */
| 37.025424 | 109 | 0.650721 | erfannoury |
6b9786f5b54b7a2bd3419b0ce0f4ab580f992559 | 1,074 | cpp | C++ | Backtracking/Graph Coloring.cpp | Sakshi14-code/CompetitiveCodingQuestions | 2b23bb743106df2178f2832d5b4c8d7601127c91 | [
"MIT"
] | null | null | null | Backtracking/Graph Coloring.cpp | Sakshi14-code/CompetitiveCodingQuestions | 2b23bb743106df2178f2832d5b4c8d7601127c91 | [
"MIT"
] | null | null | null | Backtracking/Graph Coloring.cpp | Sakshi14-code/CompetitiveCodingQuestions | 2b23bb743106df2178f2832d5b4c8d7601127c91 | [
"MIT"
] | null | null | null | #include<stdio.h>
#include<stdlib.h>
#define n 4
#define m 3
int *node;
int adj[4][4]={{0, 1, 1, 1},
{1, 0, 1, 0},
{1, 1, 0, 1},
{1, 0, 1, 0},
};
void printSoln()
{
int i;
for(i=0;i<n;i++)
{
printf("Node %d is colored with color %d.\n",(i+1),node[i]);
}
printf("\n");
}
int canicolor(int k, int color ) // checking whether kth node can be colored with a particular color.
{
int j;
for(j=0;j<n;j++)
if(adj[k][j]==1 && color==node[j])
return 0;
return 1;
}
void ncoloring(int k)
{
if(k==n)
{
printSoln();
return;
}
int i;
for(i=1;i<=m;i++) //running through all the colors as i was running through all columns in nqueens.
{
if(canicolor(k,i))
{
node[k]=i;
ncoloring(k+1);
}
}
}
int main()
{
int i;
node= (int*)calloc(n,sizeof(int)); // all nodes filled with 0 color i.e invalid color or no colour.
// adj=(int**)malloc(n*sizeof(int*));
// for(i=0;i<n;i++)
// adj[i]=(int*)malloc(n*sizeof(int));
ncoloring(0);
return 0;
}
| 17.047619 | 103 | 0.522346 | Sakshi14-code |
6b99e439e31c0d2d76002a320af24055df0c3361 | 657 | cpp | C++ | module-utils/log/tests/RandomStringGenerator.cpp | bitigchi/MuditaOS | 425d23e454e09fd6ae274b00f8d19c57a577aa94 | [
"BSL-1.0"
] | 369 | 2021-11-10T09:20:29.000Z | 2022-03-30T06:36:58.000Z | module-utils/log/tests/RandomStringGenerator.cpp | bitigchi/MuditaOS | 425d23e454e09fd6ae274b00f8d19c57a577aa94 | [
"BSL-1.0"
] | 149 | 2021-11-10T08:38:35.000Z | 2022-03-31T23:01:52.000Z | module-utils/log/tests/RandomStringGenerator.cpp | bitigchi/MuditaOS | 425d23e454e09fd6ae274b00f8d19c57a577aa94 | [
"BSL-1.0"
] | 41 | 2021-11-10T08:30:37.000Z | 2022-03-29T08:12:46.000Z | // Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#include <algorithm>
#include "RandomStringGenerator.hpp"
std::string RandomStringGenerator::getRandomString()
{
const size_t length = lengthDist(rng);
std::string str(length, 0);
std::generate_n(str.begin(), length, [this]() { return charSet[charDist(rng)]; });
return str;
}
std::vector<std::string> RandomStringGenerator::createRandomStringVector(size_t size)
{
std::vector<std::string> vec(size);
std::generate_n(vec.begin(), size, [this]() { return getRandomString(); });
return vec;
}
| 31.285714 | 86 | 0.700152 | bitigchi |
6ba2be1caddcdfc24816fcbc4821a7d1f3081fc3 | 10,665 | hpp | C++ | Runtime/World/CAi.hpp | jackoalan/urde | 413483a996805a870f002324ee46cfc123f4df06 | [
"MIT"
] | null | null | null | Runtime/World/CAi.hpp | jackoalan/urde | 413483a996805a870f002324ee46cfc123f4df06 | [
"MIT"
] | null | null | null | Runtime/World/CAi.hpp | jackoalan/urde | 413483a996805a870f002324ee46cfc123f4df06 | [
"MIT"
] | null | null | null | #pragma once
#include <string_view>
#include "Runtime/GCNTypes.hpp"
#include "Runtime/RetroTypes.hpp"
#include "Runtime/World/CDamageVulnerability.hpp"
#include "Runtime/World/CEntity.hpp"
#include "Runtime/World/CHealthInfo.hpp"
#include "Runtime/World/CKnockBackController.hpp"
#include "Runtime/World/CPhysicsActor.hpp"
#include "Runtime/World/CStateMachine.hpp"
#include "Runtime/World/ScriptObjectSupport.hpp"
#include <zeus/zeus.hpp>
namespace urde {
enum class EListenNoiseType { PlayerFire, BombExplode, ProjectileExplode };
class CAiFuncMap;
class CStateManager;
class CScriptWater;
class CTeamAiRole;
class CAi : public CPhysicsActor {
static CAiFuncMap* m_FuncMap;
protected:
CHealthInfo x258_healthInfo;
CDamageVulnerability x260_damageVulnerability;
TLockedToken<CStateMachine> x2c8_stateMachine;
public:
CAi(TUniqueId uid, bool active, std::string_view name, const CEntityInfo& info, const zeus::CTransform& xf,
CModelData&& mData, const zeus::CAABox& box, float mass, const CHealthInfo& hInfo, const CDamageVulnerability&,
const CMaterialList& list, CAssetId fsm, const CActorParameters&, float f1, float f2);
static void CreateFuncLookup(CAiFuncMap* funcMap);
static CAiStateFunc GetStateFunc(const char* func);
static CAiTriggerFunc GetTrigerFunc(const char* func);
const CStateMachine* GetStateMachine() const;
void AcceptScriptMsg(EScriptObjectMessage, TUniqueId, CStateManager&) override;
CHealthInfo* HealthInfo(CStateManager&) override { return &x258_healthInfo; }
const CDamageVulnerability* GetDamageVulnerability() const override { return &x260_damageVulnerability; }
EWeaponCollisionResponseTypes GetCollisionResponseType(const zeus::CVector3f&, const zeus::CVector3f&,
const CWeaponMode&, EProjectileAttrib) const override;
void FluidFXThink(EFluidState, CScriptWater&, CStateManager&) override;
virtual void Death(CStateManager& mgr, const zeus::CVector3f& direction, EScriptObjectState state) = 0;
virtual void KnockBack(const zeus::CVector3f&, CStateManager&, const CDamageInfo& info, EKnockBackType type,
bool inDeferred, float magnitude) = 0;
virtual void TakeDamage(const zeus::CVector3f& direction, float magnitude) {}
virtual bool CanBeShot(const CStateManager&, int) { return true; }
virtual bool IsListening() const { return false; }
virtual bool Listen(const zeus::CVector3f&, EListenNoiseType) { return false; }
virtual zeus::CVector3f GetOrigin(const CStateManager& mgr, const CTeamAiRole& role,
const zeus::CVector3f& aimPos) const {
return x34_transform.origin;
}
virtual void Patrol(CStateManager&, EStateMsg, float) {}
virtual void FollowPattern(CStateManager&, EStateMsg, float) {}
virtual void Dead(CStateManager&, EStateMsg, float) {}
virtual void PathFind(CStateManager&, EStateMsg, float) {}
virtual void Start(CStateManager&, EStateMsg, float) {}
virtual void SelectTarget(CStateManager&, EStateMsg, float) {}
virtual void TargetPatrol(CStateManager&, EStateMsg, float) {}
virtual void TargetPlayer(CStateManager&, EStateMsg, float) {}
virtual void TargetCover(CStateManager&, EStateMsg, float) {}
virtual void Halt(CStateManager&, EStateMsg, float) {}
virtual void Walk(CStateManager&, EStateMsg, float) {}
virtual void Run(CStateManager&, EStateMsg, float) {}
virtual void Generate(CStateManager&, EStateMsg, float) {}
virtual void Deactivate(CStateManager&, EStateMsg, float) {}
virtual void Attack(CStateManager&, EStateMsg, float) {}
virtual void LoopedAttack(CStateManager&, EStateMsg, float) {}
virtual void JumpBack(CStateManager&, EStateMsg, float) {}
virtual void DoubleSnap(CStateManager&, EStateMsg, float) {}
virtual void Shuffle(CStateManager&, EStateMsg, float) {}
virtual void TurnAround(CStateManager&, EStateMsg, float) {}
virtual void Skid(CStateManager&, EStateMsg, float) {}
virtual void Active(CStateManager&, EStateMsg, float) {}
virtual void InActive(CStateManager&, EStateMsg, float) {}
virtual void CoverAttack(CStateManager&, EStateMsg, float) {}
virtual void Crouch(CStateManager&, EStateMsg, float) {}
virtual void FadeIn(CStateManager&, EStateMsg, float) {}
virtual void FadeOut(CStateManager&, EStateMsg, float) {}
virtual void GetUp(CStateManager&, EStateMsg, float) {}
virtual void Taunt(CStateManager&, EStateMsg, float) {}
virtual void Suck(CStateManager&, EStateMsg, float) {}
virtual void Flee(CStateManager&, EStateMsg, float) {}
virtual void Lurk(CStateManager&, EStateMsg, float) {}
virtual void ProjectileAttack(CStateManager&, EStateMsg, float) {}
virtual void Flinch(CStateManager&, EStateMsg, float) {}
virtual void Hurled(CStateManager&, EStateMsg, float) {}
virtual void TelegraphAttack(CStateManager&, EStateMsg, float) {}
virtual void Jump(CStateManager&, EStateMsg, float) {}
virtual void Explode(CStateManager&, EStateMsg, float) {}
virtual void Dodge(CStateManager&, EStateMsg, float) {}
virtual void Retreat(CStateManager&, EStateMsg, float) {}
virtual void Cover(CStateManager&, EStateMsg, float) {}
virtual void Approach(CStateManager&, EStateMsg, float) {}
virtual void WallHang(CStateManager&, EStateMsg, float) {}
virtual void WallDetach(CStateManager&, EStateMsg, float) {}
virtual void Enraged(CStateManager&, EStateMsg, float) {}
virtual void SpecialAttack(CStateManager&, EStateMsg, float) {}
virtual void Growth(CStateManager&, EStateMsg, float) {}
virtual void Faint(CStateManager&, EStateMsg, float) {}
virtual void Land(CStateManager&, EStateMsg, float) {}
virtual void Bounce(CStateManager&, EStateMsg, float) {}
virtual void PathFindEx(CStateManager&, EStateMsg, float) {}
virtual void Dizzy(CStateManager&, EStateMsg, float) {}
virtual void CallForBackup(CStateManager&, EStateMsg, float) {}
virtual void BulbAttack(CStateManager&, EStateMsg, float) {}
virtual void PodAttack(CStateManager&, EStateMsg, float) {}
virtual bool InAttackPosition(CStateManager&, float) { return false; }
virtual bool Leash(CStateManager&, float) { return false; }
virtual bool OffLine(CStateManager&, float) { return false; }
virtual bool Attacked(CStateManager&, float) { return false; }
virtual bool PathShagged(CStateManager&, float) { return false; }
virtual bool PathOver(CStateManager&, float) { return false; }
virtual bool PathFound(CStateManager&, float) { return false; }
virtual bool TooClose(CStateManager&, float) { return false; }
virtual bool InRange(CStateManager&, float) { return false; }
virtual bool InMaxRange(CStateManager&, float) { return false; }
virtual bool InDetectionRange(CStateManager&, float) { return false; }
virtual bool SpotPlayer(CStateManager&, float) { return false; }
virtual bool PlayerSpot(CStateManager&, float) { return false; }
virtual bool PatternOver(CStateManager&, float) { return false; }
virtual bool PatternShagged(CStateManager&, float) { return false; }
virtual bool HasAttackPattern(CStateManager&, float) { return false; }
virtual bool HasPatrolPath(CStateManager&, float) { return false; }
virtual bool HasRetreatPattern(CStateManager&, float) { return false; }
virtual bool Delay(CStateManager&, float) { return false; }
virtual bool RandomDelay(CStateManager&, float) { return false; }
virtual bool FixedDelay(CStateManager&, float) { return false; }
virtual bool Default(CStateManager&, float) { return false; }
virtual bool AnimOver(CStateManager&, float) { return false; }
virtual bool ShouldAttack(CStateManager&, float) { return false; }
virtual bool ShouldDoubleSnap(CStateManager&, float) { return false; }
virtual bool InPosition(CStateManager&, float) { return false; }
virtual bool ShouldTurn(CStateManager&, float) { return false; }
virtual bool HitSomething(CStateManager&, float) { return false; }
virtual bool ShouldJumpBack(CStateManager&, float) { return false; }
virtual bool Stuck(CStateManager&, float) { return false; }
virtual bool NoPathNodes(CStateManager&, float) { return false; }
virtual bool Landed(CStateManager&, float) { return false; }
virtual bool HearShot(CStateManager&, float) { return false; }
virtual bool HearPlayer(CStateManager&, float) { return false; }
virtual bool CoverCheck(CStateManager&, float) { return false; }
virtual bool CoverFind(CStateManager&, float) { return false; }
virtual bool CoverBlown(CStateManager&, float) { return false; }
virtual bool CoverNearlyBlown(CStateManager&, float) { return false; }
virtual bool CoveringFire(CStateManager&, float) { return false; }
virtual bool GotUp(CStateManager&, float) { return false; }
virtual bool LineOfSight(CStateManager&, float) { return false; }
virtual bool AggressionCheck(CStateManager&, float) { return false; }
virtual bool AttackOver(CStateManager&, float) { return false; }
virtual bool ShouldTaunt(CStateManager&, float) { return false; }
virtual bool Inside(CStateManager&, float) { return false; }
virtual bool ShouldFire(CStateManager&, float) { return false; }
virtual bool ShouldFlinch(CStateManager&, float) { return false; }
virtual bool PatrolPathOver(CStateManager&, float) { return false; }
virtual bool ShouldDodge(CStateManager&, float) { return false; }
virtual bool ShouldRetreat(CStateManager&, float) { return false; }
virtual bool ShouldCrouch(CStateManager&, float) { return false; }
virtual bool ShouldMove(CStateManager&, float) { return false; }
virtual bool ShotAt(CStateManager&, float) { return false; }
virtual bool HasTargetingPoint(CStateManager&, float) { return false; }
virtual bool ShouldWallHang(CStateManager&, float) { return false; }
virtual bool SetAIStage(CStateManager&, float) { return false; }
virtual bool AIStage(CStateManager&, float) { return false; }
virtual bool StartAttack(CStateManager&, float) { return false; }
virtual bool BreakAttack(CStateManager&, float) { return false; }
virtual bool ShouldStrafe(CStateManager&, float) { return false; }
virtual bool ShouldSpecialAttack(CStateManager&, float) { return false; }
virtual bool LostInterest(CStateManager&, float) { return false; }
virtual bool CodeTrigger(CStateManager&, float) { return false; }
virtual bool BounceFind(CStateManager&, float) { return false; }
virtual bool Random(CStateManager&, float) { return false; }
virtual bool FixedRandom(CStateManager&, float) { return false; }
virtual bool IsDizzy(CStateManager&, float) { return false; }
virtual bool ShouldCallForBackup(CStateManager&, float) { return false; }
};
} // namespace urde
| 55.837696 | 117 | 0.751524 | jackoalan |
6ba30af97637070ff4419988180d966e19938234 | 3,949 | cpp | C++ | src/CopyConstructors.cpp | jonathan-santos/learning-cpp | 321208f8e7064c0efd86ce060b41bdb97f9ede7f | [
"MIT"
] | null | null | null | src/CopyConstructors.cpp | jonathan-santos/learning-cpp | 321208f8e7064c0efd86ce060b41bdb97f9ede7f | [
"MIT"
] | null | null | null | src/CopyConstructors.cpp | jonathan-santos/learning-cpp | 321208f8e7064c0efd86ce060b41bdb97f9ede7f | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstring>
void ValuesDoCopy()
{
int a = 1;
int b = a;
b++;
std::cout << "Value do not copy[a]: " << a << std::endl; // 1
std::cout << "Value do not copy[b]: " << b << std::endl; // 2
}
struct VectorCopy
{
float x, y;
};
void ClassesAndStructsDoCopy()
{
VectorCopy a = { 1, 3 };
VectorCopy b = a;
b.x = 10;
b.y = 30;
std::cout << "Classes and structs do not copy[Vector a]: (x): " << a.x << ", (y): " << a.y << std::endl;
std::cout << "Classes and structs do not copy[Vector b]: (x): " << b.x << ", (y): " << b.y << std::endl;
}
void PointersCopyThePointerNotTheValue()
{
int* a = new int(1);
int* b = a;
(*b)++;
std::cout << "Pointers copy the pointer, not the value[a]: " << *a << std::endl; // 2
std::cout << "Pointers copy the pointer, not the value[b]: " << *b << std::endl; // 2
delete a;
VectorCopy* c = new VectorCopy();
(*c).x = 1;
(*c).y = 3;
VectorCopy* d = c;
(*d).x = 10;
(*d).y = 30;
std::cout << "Pointers copy the pointer, not the value[Vector c]: (x): " << c->x << ", (y): " << c->y << std::endl;
std::cout << "Pointers copy the pointer, not the value[Vector d]: (x): " << d->x << ", (y): " << d->y << std::endl;
delete c;
}
class BasicString
{
private:
char* m_Buffer;
unsigned int m_Size;
public:
BasicString(const char* string)
{
m_Size = strlen(string);
m_Buffer = new char[m_Size + 1];
memcpy(m_Buffer, string, m_Size);
m_Buffer[m_Size] = 0;
}
~BasicString()
{
delete[] m_Buffer;
}
//BasicString(const BasicString& other); // Copy constructor
//BasicString(const BasicString& other) = delete; // Disable Copy constructor
BasicString(const BasicString& other) // Deep copy. As in it guarantees that when being copied, BasicString will not copy m_Buffer as a pointer, but it will copy the value inside m_Buffer from the copied object to the new, while them both having different memory locations
: m_Size(other.m_Size)
{
std::cout << "Copied BasicString" << std::endl;
m_Buffer = new char[m_Size + 1];
memcpy(m_Buffer, other.m_Buffer, m_Size + 1);
}
char& operator[](unsigned int index)
{
return m_Buffer[index];
}
friend std::ostream& operator<<(std::ostream& stream, const BasicString& string);
};
std::ostream& operator<<(std::ostream& stream, const BasicString& string)
{
stream << string.m_Buffer;
return stream;
}
void CopyOperator()
{
BasicString string = "Jhow";
BasicString secondString = string;
secondString[0] = 'j';
std::cout << "string: " << string << std::endl;
std::cout << "secondString: " << secondString << std::endl;
}
void PrintByValue(BasicString e)
{
std::cout << "By Value: " << e << std::endl;
}
void PrintByPointer(BasicString* e)
{
std::cout << "By pointer: " << *e << std::endl;
}
void PrintByReference(BasicString& e)
{
std::cout << "By reference: " << e << std::endl;
}
// When passing a object as a parameter to a function, you gotta be careful as how it is defined in the function. In the example bellow, when we pass the variable string to function PrintByValue, the variable string is actually being copied in memory to the function. The other two don't have the same behavior, saving memory and processing
void FunctionCopy()
{
BasicString string = "Jhow";
PrintByValue(string); // Will appear "Copied BasicString" in console, because the Copy constructor was called
PrintByPointer(&string); // No duplication
PrintByReference(string); // No duplication
}
void ExecuteCopyConstructors()
{
ValuesDoCopy();
std::cout << std::endl;
ClassesAndStructsDoCopy();
std::cout << std::endl;
PointersCopyThePointerNotTheValue();
std::cout << std::endl;
CopyOperator();
std::cout << std::endl;
FunctionCopy();
}
| 28.615942 | 340 | 0.610028 | jonathan-santos |
6ba47d5d3947f9fc8055d86f5092314861d21602 | 11,764 | cpp | C++ | third_party/WebKit/Source/platform/bindings/V8PerIsolateData.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/platform/bindings/V8PerIsolateData.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/platform/bindings/V8PerIsolateData.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2009 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 "platform/bindings/V8PerIsolateData.h"
#include <memory>
#include "platform/ScriptForbiddenScope.h"
#include "platform/WebTaskRunner.h"
#include "platform/bindings/DOMDataStore.h"
#include "platform/bindings/V8Binding.h"
#include "platform/bindings/V8ObjectConstructor.h"
#include "platform/bindings/V8PrivateProperty.h"
#include "platform/bindings/V8ValueCache.h"
#include "platform/wtf/LeakAnnotations.h"
#include "platform/wtf/PtrUtil.h"
#include "public/platform/Platform.h"
#include "v8/include/v8-debug.h"
namespace blink {
static V8PerIsolateData* g_main_thread_per_isolate_data = 0;
static void BeforeCallEnteredCallback(v8::Isolate* isolate) {
// TODO(jochen): Re-enable this once https://crbug.com/728583
// CHECK(!ScriptForbiddenScope::IsScriptForbidden());
}
static void MicrotasksCompletedCallback(v8::Isolate* isolate) {
V8PerIsolateData::From(isolate)->RunEndOfScopeTasks();
}
V8PerIsolateData::V8PerIsolateData(WebTaskRunner* task_runner)
: isolate_holder_(
task_runner ? task_runner->ToSingleThreadTaskRunner() : nullptr,
gin::IsolateHolder::kSingleThread,
IsMainThread() ? gin::IsolateHolder::kDisallowAtomicsWait
: gin::IsolateHolder::kAllowAtomicsWait),
string_cache_(WTF::WrapUnique(new StringCache(GetIsolate()))),
private_property_(V8PrivateProperty::Create()),
constructor_mode_(ConstructorMode::kCreateNewObject),
use_counter_disabled_(false),
is_handling_recursion_level_error_(false),
is_reporting_exception_(false) {
// FIXME: Remove once all v8::Isolate::GetCurrent() calls are gone.
GetIsolate()->Enter();
GetIsolate()->AddBeforeCallEnteredCallback(&BeforeCallEnteredCallback);
GetIsolate()->AddMicrotasksCompletedCallback(&MicrotasksCompletedCallback);
if (IsMainThread())
g_main_thread_per_isolate_data = this;
}
V8PerIsolateData::~V8PerIsolateData() {}
v8::Isolate* V8PerIsolateData::MainThreadIsolate() {
DCHECK(g_main_thread_per_isolate_data);
return g_main_thread_per_isolate_data->GetIsolate();
}
v8::Isolate* V8PerIsolateData::Initialize(WebTaskRunner* task_runner) {
V8PerIsolateData* data = new V8PerIsolateData(task_runner);
v8::Isolate* isolate = data->GetIsolate();
isolate->SetData(gin::kEmbedderBlink, data);
return isolate;
}
void V8PerIsolateData::EnableIdleTasks(
v8::Isolate* isolate,
std::unique_ptr<gin::V8IdleTaskRunner> task_runner) {
From(isolate)->isolate_holder_.EnableIdleTasks(std::move(task_runner));
}
// willBeDestroyed() clear things that should be cleared before
// ThreadState::detach() gets called.
void V8PerIsolateData::WillBeDestroyed(v8::Isolate* isolate) {
V8PerIsolateData* data = From(isolate);
data->thread_debugger_.reset();
// Clear any data that may have handles into the heap,
// prior to calling ThreadState::detach().
data->ClearEndOfScopeTasks();
data->active_script_wrappables_.Clear();
}
// destroy() clear things that should be cleared after ThreadState::detach()
// gets called but before the Isolate exits.
void V8PerIsolateData::Destroy(v8::Isolate* isolate) {
isolate->RemoveBeforeCallEnteredCallback(&BeforeCallEnteredCallback);
isolate->RemoveMicrotasksCompletedCallback(&MicrotasksCompletedCallback);
V8PerIsolateData* data = From(isolate);
// Clear everything before exiting the Isolate.
if (data->script_regexp_script_state_)
data->script_regexp_script_state_->DisposePerContextData();
data->private_property_.reset();
data->string_cache_->Dispose();
data->string_cache_.reset();
data->interface_template_map_for_non_main_world_.clear();
data->interface_template_map_for_main_world_.clear();
data->operation_template_map_for_non_main_world_.clear();
data->operation_template_map_for_main_world_.clear();
if (IsMainThread())
g_main_thread_per_isolate_data = 0;
// FIXME: Remove once all v8::Isolate::GetCurrent() calls are gone.
isolate->Exit();
delete data;
}
V8PerIsolateData::V8FunctionTemplateMap&
V8PerIsolateData::SelectInterfaceTemplateMap(const DOMWrapperWorld& world) {
return world.IsMainWorld() ? interface_template_map_for_main_world_
: interface_template_map_for_non_main_world_;
}
V8PerIsolateData::V8FunctionTemplateMap&
V8PerIsolateData::SelectOperationTemplateMap(const DOMWrapperWorld& world) {
return world.IsMainWorld() ? operation_template_map_for_main_world_
: operation_template_map_for_non_main_world_;
}
v8::Local<v8::FunctionTemplate> V8PerIsolateData::FindOrCreateOperationTemplate(
const DOMWrapperWorld& world,
const void* key,
v8::FunctionCallback callback,
v8::Local<v8::Value> data,
v8::Local<v8::Signature> signature,
int length) {
auto& map = SelectOperationTemplateMap(world);
auto result = map.find(key);
if (result != map.end())
return result->value.Get(GetIsolate());
v8::Local<v8::FunctionTemplate> templ = v8::FunctionTemplate::New(
GetIsolate(), callback, data, signature, length);
templ->RemovePrototype();
map.insert(key, v8::Eternal<v8::FunctionTemplate>(GetIsolate(), templ));
return templ;
}
v8::Local<v8::FunctionTemplate> V8PerIsolateData::FindInterfaceTemplate(
const DOMWrapperWorld& world,
const void* key) {
auto& map = SelectInterfaceTemplateMap(world);
auto result = map.find(key);
if (result != map.end())
return result->value.Get(GetIsolate());
return v8::Local<v8::FunctionTemplate>();
}
void V8PerIsolateData::SetInterfaceTemplate(
const DOMWrapperWorld& world,
const void* key,
v8::Local<v8::FunctionTemplate> value) {
auto& map = SelectInterfaceTemplateMap(world);
map.insert(key, v8::Eternal<v8::FunctionTemplate>(GetIsolate(), value));
}
const v8::Eternal<v8::Name>* V8PerIsolateData::FindOrCreateEternalNameCache(
const void* lookup_key,
const char* const names[],
size_t count) {
auto it = eternal_name_cache_.find(lookup_key);
const Vector<v8::Eternal<v8::Name>>* vector = nullptr;
if (UNLIKELY(it == eternal_name_cache_.end())) {
v8::Isolate* isolate = this->GetIsolate();
Vector<v8::Eternal<v8::Name>> new_vector(count);
std::transform(
names, names + count, new_vector.begin(), [isolate](const char* name) {
return v8::Eternal<v8::Name>(isolate, V8AtomicString(isolate, name));
});
vector = &eternal_name_cache_.Set(lookup_key, std::move(new_vector))
.stored_value->value;
} else {
vector = &it->value;
}
DCHECK_EQ(vector->size(), count);
return vector->data();
}
v8::Local<v8::Context> V8PerIsolateData::EnsureScriptRegexpContext() {
if (!script_regexp_script_state_) {
LEAK_SANITIZER_DISABLED_SCOPE;
v8::Local<v8::Context> context(v8::Context::New(GetIsolate()));
script_regexp_script_state_ = ScriptState::Create(
context, DOMWrapperWorld::Create(GetIsolate(),
DOMWrapperWorld::WorldType::kRegExp));
}
return script_regexp_script_state_->GetContext();
}
void V8PerIsolateData::ClearScriptRegexpContext() {
if (script_regexp_script_state_)
script_regexp_script_state_->DisposePerContextData();
script_regexp_script_state_.Clear();
}
bool V8PerIsolateData::HasInstance(
const WrapperTypeInfo* untrusted_wrapper_type_info,
v8::Local<v8::Value> value) {
RUNTIME_CALL_TIMER_SCOPE(GetIsolate(),
RuntimeCallStats::CounterId::kHasInstance);
return HasInstance(untrusted_wrapper_type_info, value,
interface_template_map_for_main_world_) ||
HasInstance(untrusted_wrapper_type_info, value,
interface_template_map_for_non_main_world_);
}
bool V8PerIsolateData::HasInstance(
const WrapperTypeInfo* untrusted_wrapper_type_info,
v8::Local<v8::Value> value,
V8FunctionTemplateMap& map) {
auto result = map.find(untrusted_wrapper_type_info);
if (result == map.end())
return false;
v8::Local<v8::FunctionTemplate> templ = result->value.Get(GetIsolate());
return templ->HasInstance(value);
}
v8::Local<v8::Object> V8PerIsolateData::FindInstanceInPrototypeChain(
const WrapperTypeInfo* info,
v8::Local<v8::Value> value) {
v8::Local<v8::Object> wrapper = FindInstanceInPrototypeChain(
info, value, interface_template_map_for_main_world_);
if (!wrapper.IsEmpty())
return wrapper;
return FindInstanceInPrototypeChain(
info, value, interface_template_map_for_non_main_world_);
}
v8::Local<v8::Object> V8PerIsolateData::FindInstanceInPrototypeChain(
const WrapperTypeInfo* info,
v8::Local<v8::Value> value,
V8FunctionTemplateMap& map) {
if (value.IsEmpty() || !value->IsObject())
return v8::Local<v8::Object>();
auto result = map.find(info);
if (result == map.end())
return v8::Local<v8::Object>();
v8::Local<v8::FunctionTemplate> templ = result->value.Get(GetIsolate());
return v8::Local<v8::Object>::Cast(value)->FindInstanceInPrototypeChain(
templ);
}
void V8PerIsolateData::AddEndOfScopeTask(std::unique_ptr<EndOfScopeTask> task) {
end_of_scope_tasks_.push_back(std::move(task));
}
void V8PerIsolateData::RunEndOfScopeTasks() {
Vector<std::unique_ptr<EndOfScopeTask>> tasks;
tasks.swap(end_of_scope_tasks_);
for (const auto& task : tasks)
task->Run();
DCHECK(end_of_scope_tasks_.IsEmpty());
}
void V8PerIsolateData::ClearEndOfScopeTasks() {
end_of_scope_tasks_.clear();
}
void V8PerIsolateData::SetThreadDebugger(
std::unique_ptr<V8PerIsolateData::Data> thread_debugger) {
DCHECK(!thread_debugger_);
thread_debugger_ = std::move(thread_debugger);
}
V8PerIsolateData::Data* V8PerIsolateData::ThreadDebugger() {
return thread_debugger_.get();
}
void V8PerIsolateData::AddActiveScriptWrappable(
ActiveScriptWrappableBase* wrappable) {
if (!active_script_wrappables_)
active_script_wrappables_ = new ActiveScriptWrappableSet();
active_script_wrappables_->insert(wrappable);
}
void V8PerIsolateData::TemporaryScriptWrappableVisitorScope::
SwapWithV8PerIsolateDataVisitor(
std::unique_ptr<ScriptWrappableVisitor>& visitor) {
ScriptWrappableVisitor* current = CurrentVisitor();
if (current)
current->PerformCleanup();
V8PerIsolateData::From(isolate_)->script_wrappable_visitor_.swap(
saved_visitor_);
isolate_->SetEmbedderHeapTracer(CurrentVisitor());
}
} // namespace blink
| 37.346032 | 80 | 0.743285 | metux |
6ba589f3afecb475eca6d0e39f67292118a50415 | 4,546 | cc | C++ | chrome/worker/webworkerclient_proxy.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | 11 | 2015-03-20T04:08:08.000Z | 2021-11-15T15:51:36.000Z | chrome/worker/webworkerclient_proxy.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | null | null | null | chrome/worker/webworkerclient_proxy.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2009 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/worker/webworkerclient_proxy.h"
#include "base/command_line.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/webmessageportchannel_impl.h"
#include "chrome/common/worker_messages.h"
#include "chrome/renderer/webworker_proxy.h"
#include "chrome/worker/webworker_stub_base.h"
#include "chrome/worker/worker_thread.h"
#include "ipc/ipc_logging.h"
#include "third_party/WebKit/WebKit/chromium/public/WebString.h"
#include "third_party/WebKit/WebKit/chromium/public/WebURL.h"
#include "third_party/WebKit/WebKit/chromium/public/WebWorker.h"
using WebKit::WebMessagePortChannel;
using WebKit::WebMessagePortChannelArray;
using WebKit::WebString;
using WebKit::WebWorker;
using WebKit::WebWorkerClient;
// How long to wait for worker to finish after it's been told to terminate.
#define kMaxTimeForRunawayWorkerMs 3000
WebWorkerClientProxy::WebWorkerClientProxy(int route_id,
WebWorkerStubBase* stub)
: route_id_(route_id),
stub_(stub),
ALLOW_THIS_IN_INITIALIZER_LIST(kill_process_factory_(this)) {
}
WebWorkerClientProxy::~WebWorkerClientProxy() {
}
void WebWorkerClientProxy::postMessageToWorkerObject(
const WebString& message,
const WebMessagePortChannelArray& channels) {
std::vector<int> message_port_ids(channels.size());
std::vector<int> routing_ids(channels.size());
for (size_t i = 0; i < channels.size(); ++i) {
WebMessagePortChannelImpl* webchannel =
static_cast<WebMessagePortChannelImpl*>(channels[i]);
message_port_ids[i] = webchannel->message_port_id();
webchannel->QueueMessages();
DCHECK(message_port_ids[i] != MSG_ROUTING_NONE);
routing_ids[i] = MSG_ROUTING_NONE;
}
Send(new WorkerMsg_PostMessage(
route_id_, message, message_port_ids, routing_ids));
}
void WebWorkerClientProxy::postExceptionToWorkerObject(
const WebString& error_message,
int line_number,
const WebString& source_url) {
Send(new WorkerHostMsg_PostExceptionToWorkerObject(
route_id_, error_message, line_number, source_url));
}
void WebWorkerClientProxy::postConsoleMessageToWorkerObject(
int destination,
int source,
int type,
int level,
const WebString& message,
int line_number,
const WebString& source_url) {
WorkerHostMsg_PostConsoleMessageToWorkerObject_Params params;
params.destination_identifier = destination;
params.source_identifier = source;
params.message_type = type;
params.message_level = level;
params.message = message;
params.line_number = line_number;
params.source_url = source_url;
Send(new WorkerHostMsg_PostConsoleMessageToWorkerObject(route_id_, params));
}
void WebWorkerClientProxy::confirmMessageFromWorkerObject(
bool has_pending_activity) {
Send(new WorkerHostMsg_ConfirmMessageFromWorkerObject(
route_id_, has_pending_activity));
}
void WebWorkerClientProxy::reportPendingActivity(bool has_pending_activity) {
Send(new WorkerHostMsg_ReportPendingActivity(
route_id_, has_pending_activity));
}
void WebWorkerClientProxy::workerContextClosed() {
Send(new WorkerHostMsg_WorkerContextClosed(route_id_));
}
void WebWorkerClientProxy::workerContextDestroyed() {
Send(new WorkerHostMsg_WorkerContextDestroyed(route_id_));
// Tell the stub that the worker has shutdown - frees this object.
if (stub_)
stub_->Shutdown();
}
WebKit::WebWorker* WebWorkerClientProxy::createWorker(
WebKit::WebWorkerClient* client) {
return new WebWorkerProxy(client, WorkerThread::current(), 0);
}
bool WebWorkerClientProxy::Send(IPC::Message* message) {
return WorkerThread::current()->Send(message);
}
void WebWorkerClientProxy::EnsureWorkerContextTerminates() {
// Avoid a worker doing a while(1) from never exiting.
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kWebWorkerShareProcesses)) {
// Can't kill the process since there could be workers from other
// renderer process.
NOTIMPLEMENTED();
return;
}
// This shuts down the process cleanly from the perspective of the browser
// process, and avoids the crashed worker infobar from appearing to the new
// page.
MessageLoop::current()->PostDelayedTask(FROM_HERE,
kill_process_factory_.NewRunnableMethod(
&WebWorkerClientProxy::workerContextDestroyed),
kMaxTimeForRunawayWorkerMs);
}
| 34.180451 | 78 | 0.763088 | rwatson |
6ba6411940d40ce526dd9a3cf369fe1edb1ec492 | 3,260 | cxx | C++ | pandatool/src/dxfegg/dxfToEggConverter.cxx | cmarshall108/panda3d-python3 | 8bea2c0c120b03ec1c9fd179701fdeb7510bb97b | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | pandatool/src/dxfegg/dxfToEggConverter.cxx | cmarshall108/panda3d-python3 | 8bea2c0c120b03ec1c9fd179701fdeb7510bb97b | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | pandatool/src/dxfegg/dxfToEggConverter.cxx | cmarshall108/panda3d-python3 | 8bea2c0c120b03ec1c9fd179701fdeb7510bb97b | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | /**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file dxfToEggConverter.cxx
* @author drose
* @date 2004-05-04
*/
#include "dxfToEggConverter.h"
#include "dxfToEggLayer.h"
#include "eggData.h"
/**
*
*/
DXFToEggConverter::
DXFToEggConverter() {
}
/**
*
*/
DXFToEggConverter::
DXFToEggConverter(const DXFToEggConverter ©) :
SomethingToEggConverter(copy)
{
}
/**
*
*/
DXFToEggConverter::
~DXFToEggConverter() {
}
/**
* Allocates and returns a new copy of the converter.
*/
SomethingToEggConverter *DXFToEggConverter::
make_copy() {
return new DXFToEggConverter(*this);
}
/**
* Returns the English name of the file type this converter supports.
*/
std::string DXFToEggConverter::
get_name() const {
return "DXF";
}
/**
* Returns the common extension of the file type this converter supports.
*/
std::string DXFToEggConverter::
get_extension() const {
return "dxf";
}
/**
* Returns true if this file type can transparently load compressed files
* (with a .pz extension), false otherwise.
*/
bool DXFToEggConverter::
supports_compressed() const {
return true;
}
/**
* Handles the reading of the input file and converting it to egg. Returns
* true if successful, false otherwise.
*/
bool DXFToEggConverter::
convert_file(const Filename &filename) {
clear_error();
if (_egg_data->get_coordinate_system() == CS_default) {
_egg_data->set_coordinate_system(CS_zup_right);
}
process(filename);
return !had_error();
}
/**
*
*/
DXFLayer *DXFToEggConverter::
new_layer(const std::string &name) {
return new DXFToEggLayer(name, get_egg_data());
}
/**
* If the entity is a polygon, creates the corresponding egg polygon.
*/
void DXFToEggConverter::
done_entity() {
if (_entity == EN_polyline) {
// A Polyline is either an unclosed series of connected line segments, or
// a closed polygon of arbitrary complexity.
if ((_flags & PF_3d) == 0) {
// it's a 2-d polygon; convert it to 3-d coordinates.
ocs_2_wcs();
}
if (_flags & PF_closed) {
// it's closed; create a polygon.
nassertv(_layer!=nullptr);
((DXFToEggLayer *)_layer)->add_polygon(this);
} else {
// It's open; create a series of line segments.
nassertv(_layer!=nullptr);
((DXFToEggLayer *)_layer)->add_line(this);
}
} else if (_entity == EN_3dface) {
// DXF can also represent a polygon as a 3DFace. This might be either a
// quad or a triangle (if two of the vertices are the same). We'll add
// the vertices to our list of vertices and then define the polygon.
_verts.clear();
_verts.push_back(DXFVertex(_s));
_verts.push_back(DXFVertex(_r));
_verts.push_back(DXFVertex(_q));
_verts.push_back(DXFVertex(_p));
nassertv(_layer!=nullptr);
((DXFToEggLayer *)_layer)->add_polygon(this);
}
}
/**
* A hook for user code, if desired. This function is called when some
* unexpected error occurs while reading the DXF file.
*/
void DXFToEggConverter::
error() {
_error = true;
}
| 22.328767 | 77 | 0.684969 | cmarshall108 |
6baa8aaebc87835c39186149cca16792ca3e6c4f | 15,081 | cpp | C++ | source/backend/cpu/compute/DenseConvolutionTiledExecutor.cpp | foreverlms/MNN | 8f9d3e3331fb54382bb61ac3a2087637a161fec5 | [
"Apache-2.0"
] | null | null | null | source/backend/cpu/compute/DenseConvolutionTiledExecutor.cpp | foreverlms/MNN | 8f9d3e3331fb54382bb61ac3a2087637a161fec5 | [
"Apache-2.0"
] | null | null | null | source/backend/cpu/compute/DenseConvolutionTiledExecutor.cpp | foreverlms/MNN | 8f9d3e3331fb54382bb61ac3a2087637a161fec5 | [
"Apache-2.0"
] | null | null | null | //
// DenseConvolutionTiledExecutor.cpp
// MNN
//
// Created by MNN on 2018/07/16.
// Copyright © 2018, Alibaba Group Holding Limited
//
#include "DenseConvolutionTiledExecutor.hpp"
#include <MNN/AutoTime.hpp>
#include "backend/cpu/CPUBackend.hpp"
#include "CommonOptFunction.h"
#include "core/Concurrency.h"
#include "ConvOpt.h"
#include "core/Macro.h"
#include "core/TensorUtils.hpp"
#include "math/Vec.hpp"
#include "core/BufferAllocator.hpp"
#include "core/MemoryFormater.h"
using Vec4 = MNN::Math::Vec<float, 4>;
namespace MNN {
void DenseConvolutionTiledExecutor::initWeight(float *dest, const float *source, float* cache, int depth, int outputCount, int kernelSize, const CoreFunctions* function) {
ConvolutionTiledExecutor::initWeight(source, cache, depth, outputCount, kernelSize, function);
function->MNNPackForMatMul_B(dest, cache, outputCount, kernelSize * depth, true);
/*MNN_PRINT("dense weight matrix tile:");
formatMatrix(dest, {UP_DIV(outputCount, 4), kernelSize * depth, 4});*/
}
DenseConvolutionTiledExecutor::DenseConvolutionTiledExecutor(const Convolution2DCommon* common, Backend* b,
const float* originWeight, size_t originWeightSize,
const float* bias, size_t biasSize)
: ConvolutionTiledExecutor(b, bias, biasSize) {
auto outputCount = (int)biasSize;
int eP, lP, hP;
auto core = static_cast<CPUBackend*>(b)->functions();
int bytes = core->bytes;
core->MNNGetMatMulPackMode(&eP, &lP, &hP);
// Don't use common->inputCount for old model common->inputCount is zero
auto srcCount = (int)originWeightSize / outputCount / common->kernelX() / common->kernelY();
auto lSize = srcCount * common->kernelX() * common->kernelY();
mResource->mWeight.reset(Tensor::createDevice<uint8_t>(
{UP_DIV(outputCount, hP) * UP_DIV(lSize, lP) * hP * lP * bytes}));
std::shared_ptr<Tensor> cache(Tensor::createDevice<uint8_t>({outputCount * srcCount * common->kernelX() * common->kernelY() * (int)sizeof(float)})); // cache must be float
mValid = mValid && backend()->onAcquireBuffer(mResource->mWeight.get(), Backend::STATIC);
mValid = mValid && backend()->onAcquireBuffer(cache.get(), Backend::STATIC);
if (!mValid) {
return;
}
initWeight(mResource->mWeight->host<float>(), originWeight, cache->host<float>(), srcCount, outputCount, common->kernelX() * common->kernelY(), core);
backend()->onReleaseBuffer(cache.get(), Backend::STATIC);
mProxy.reset(new DenseConvolutionTiledImpl(common, b));
}
DenseConvolutionTiledExecutor::DenseConvolutionTiledExecutor(std::shared_ptr<CPUConvolution::Resource> res, const Convolution2DCommon* common, Backend* b) : ConvolutionTiledExecutor(res, b) {
mProxy.reset(new DenseConvolutionTiledImpl(common, b));
}
DenseConvolutionTiledExecutor::~DenseConvolutionTiledExecutor() {
// Do nothing
}
bool DenseConvolutionTiledExecutor::onClone(Backend* bn, const Op* op, Execution** dst) {
if (!mValid) {
return false;
}
if (nullptr == dst) {
return true;
}
*dst = new DenseConvolutionTiledExecutor(mResource, op->main_as_Convolution2D()->common(), bn);
return true;
}
ErrorCode ConvolutionTiledExecutorMultiInput::onExecute(const std::vector<Tensor*>& inputs,
const std::vector<Tensor*>& outputs) {
int depth = inputs[1]->channel();
int outputCount = inputs[1]->batch();
auto function = static_cast<CPUBackend*>(backend())->functions();
if (nullptr != mTempBias) {
::memset(mTempBias->host<float>(), 0, mTempBias->elementSize() * function->bytes);
if (inputs.size() > 2) {
::memcpy(mTempBias->host<float>(), inputs[2]->host<float>(), inputs[2]->elementSize() * function->bytes);
}
}
auto cache = mTempWeightCache->host<float>();
auto source = inputs[1]->host<float>();
auto kernelSize = inputs[1]->stride(1);
// Swap k, ic
int dims[4] = {
depth,
kernelSize,
kernelSize,
depth
};
if (function->bytes < 4) {
// TODO: Opt it
// Lowp
source = mTempWeightCache->host<float>() + mTempWeightCache->stride(0);
function->MNNLowpToFp32(inputs[1]->host<int16_t>(), source, inputs[1]->elementSize());
for (int o=0; o<outputCount; ++o) {
auto dO = cache + o * depth * kernelSize;
auto sO = source + o * depth * kernelSize;
MNNTranspose32Bit((int32_t*)dO, (const int32_t*)sO, &dims[0]);
}
function->MNNFp32ToLowp(cache, (int16_t*)cache, inputs[1]->elementSize());
} else {
for (int o=0; o<outputCount; ++o) {
auto dO = cache + o * depth * kernelSize;
auto sO = source + o * depth * kernelSize;
MNNTranspose32Bit((int32_t*)dO, (const int32_t*)sO, &dims[0]);
}
}
function->MNNPackForMatMul_B(mTempWeight->host<float>(), mTempWeightCache->host<float>(), outputCount, kernelSize * depth, true);
return mProxy->onExecute(mInputs, outputs);
}
ErrorCode ConvolutionTiledExecutorMultiInput::onResize(const std::vector<Tensor*>& inputs,
const std::vector<Tensor*>& outputs) {
int depth = inputs[1]->channel();
int outputCount = outputs[0]->channel();
auto function = static_cast<CPUBackend*>(backend())->functions();
int eP, lP, hP;
function->MNNGetMatMulPackMode(&eP, &lP, &hP);
auto kernelSize = depth * inputs[1]->stride(1);
mTempWeight.reset(Tensor::createDevice<float>(
{UP_DIV(outputCount, hP), UP_DIV(kernelSize, lP), lP * hP}));
if (function->bytes < 4) {
mTempWeightCache.reset(Tensor::createDevice<int32_t>({2, outputCount * kernelSize}));
} else {
mTempWeightCache.reset(Tensor::createDevice<float>({outputCount * kernelSize}));
}
auto res = backend()->onAcquireBuffer(mTempWeight.get(), Backend::DYNAMIC);
res = res && backend()->onAcquireBuffer(mTempWeightCache.get(), Backend::DYNAMIC);
mTempBias.reset();
if (!res) {
return OUT_OF_MEMORY;
}
if (inputs.size() > 2 && inputs[2]->elementSize() % function->pack == 0) {
mInputs = {inputs[0], mTempWeight.get(), inputs[2]};
} else {
mTempBias.reset(Tensor::createDevice<float>({UP_DIV(outputCount, function->pack) * function->pack}));
backend()->onAcquireBuffer(mTempBias.get(), Backend::DYNAMIC);
mInputs = {inputs[0], mTempWeight.get(), mTempBias.get()};
}
backend()->onReleaseBuffer(mTempWeightCache.get(), Backend::DYNAMIC);
auto errorCode = mProxy->onResize(mInputs, outputs);
backend()->onReleaseBuffer(mTempWeight.get(), Backend::DYNAMIC);
if (nullptr != mTempBias) {
backend()->onReleaseBuffer(mTempBias.get(), Backend::DYNAMIC);
}
return errorCode;
}
void DenseConvolutionTiledImpl::getPackParameter(int* eP, int* lP, int* hP, const CoreFunctions* core) {
core->MNNGetMatMulPackMode(eP, lP, hP);
return;
}
ErrorCode DenseConvolutionTiledImpl::onResize(const std::vector<Tensor*>& inputs,
const std::vector<Tensor*>& outputs) {
CPUConvolution::onResize(inputs, outputs);
auto input = inputs[0];
auto weight = inputs[1];
Tensor *bias = nullptr;
auto core = static_cast<CPUBackend *>(backend())->functions();
int bytes = core->bytes;
int unit = core->pack;
auto packA = core->MNNPackC4ForMatMul_A;
int eP, lP, hP;
getPackParameter(&eP, &lP, &hP, core);
auto matmulUnit = core->MNNPackedMatMul;
auto matmulRemain = core->MNNPackedMatMulRemain;
auto strideX = mCommon->strideX();
auto strideY = mCommon->strideY();
auto dilateX = mCommon->dilateX();
auto dilateY = mCommon->dilateY();
auto padY = mPadY;
auto padX = mPadX;
auto kernel_width = mCommon->kernelX();
auto kernel_height = mCommon->kernelY();
auto output = outputs[0];
auto batch = output->batch();
auto width = output->width();
auto height = output->height();
int threadNumber = ((CPUBackend *)backend())->threadNumber();
auto weightPtr = weight->host<float>();
auto src_width = input->width();
auto src_height = input->height();
auto icC4 = UP_DIV(input->channel(), unit);
auto ic = input->channel();
auto L = ic * mCommon->kernelY() * mCommon->kernelX();
if (src_width == 1 && width == 1 && height > 1) {
/* Swap x, y*/
width = height;
height = 1;
padX = mPadY;
padY = mPadX;
strideX = strideY;
strideY = 1; /* Don't need stride */
src_width = src_height;
src_height = 1;
dilateX = dilateY;
dilateY = 1;
kernel_width = kernel_height;
kernel_height = 1;
}
const float *biasPtr = nullptr;
if (inputs.size() > 2) {
bias = inputs[2];
biasPtr = bias->host<float>();
}
auto kernelSize = mCommon->kernelX() * mCommon->kernelY();
mTempBufferTranspose.buffer().type = halide_type_of<uint8_t>();
mTempBufferTranspose.buffer().dimensions = 2;
mTempBufferTranspose.buffer().dim[0].extent = threadNumber;
mTempBufferTranspose.buffer().dim[1].extent = UP_DIV(L, lP) * lP * eP * bytes;
TensorUtils::setLinearLayout(&mTempBufferTranspose);
auto plane = width * height * batch;
int tileCount = UP_DIV(plane, eP);
bool success = backend()->onAcquireBuffer(&mTempBufferTranspose, Backend::DYNAMIC);
if (!success) {
return OUT_OF_MEMORY;
}
auto outputChannel = output->channel();
auto oC4 = UP_DIV(outputChannel, unit);
auto bufferAlloc = static_cast<CPUBackend *>(backend())->getBufferAllocator();
auto maxLine = UP_DIV(eP, width) + 1;
auto tempPtr = bufferAlloc->alloc(kernelSize * maxLine * threadNumber * (4 * sizeof(int32_t) + sizeof(float *)));
if (nullptr == tempPtr.first) {
return OUT_OF_MEMORY;
}
backend()->onReleaseBuffer(&mTempBufferTranspose, Backend::DYNAMIC);
bufferAlloc->free(tempPtr);
auto threadNumberFirst = std::min(threadNumber, tileCount);
auto postParameters = getPostParameters();
mFunction.first = threadNumberFirst;
mFunction.second = [=](int tId) {
auto gemmBuffer = mTempBufferTranspose.host<uint8_t>() + mTempBufferTranspose.stride(0) * tId;
auto srcPtr = (float const **)((uint8_t *)tempPtr.first + tempPtr.second +
tId * kernelSize * maxLine * (4 * sizeof(int32_t) + sizeof(float *)));
auto el = (int32_t *)(srcPtr + kernelSize * maxLine);
int32_t info[4];
info[1] = src_width * src_height * batch;
info[2] = eP;
info[3] = strideX;
size_t parameters[6];
parameters[0] = eP * bytes;
parameters[1] = L;
parameters[2] = outputChannel;
parameters[3] = plane * unit * bytes;
parameters[4] = 0;
parameters[5] = 0;
auto dstOrigin = output->host<uint8_t>();
auto srcOrigin = input->host<uint8_t>();
for (int x = (int)tId; x < tileCount; x += threadNumberFirst) {
int start = (int)x * eP;
int remain = plane - start;
int xC = remain > eP ? eP : remain;
/* Compute Pack position */
int oyBegin = start / width;
int oxBegin = start % width;
int oyEnd = (start + xC - 1) / width;
remain = xC;
int number = 0;
bool needZero = false;
int eStart = 0;
for (int oyb = oyBegin; oyb <= oyEnd; ++oyb) {
int step = std::min(width - oxBegin, remain);
int oy = oyb % height;
int ob = oyb / height;
int sySta = oy * strideY - padY;
int kyStart = std::max(0, UP_DIV(-sySta, dilateY));
int kyEnd = std::min(kernel_height, UP_DIV(src_height - sySta, dilateY));
if (kyEnd - kyStart < kernel_height) {
needZero = true;
}
auto srcStart = srcOrigin + ((ob * src_height + sySta) * src_width) * bytes * unit;
for (int ky = kyStart; ky < kyEnd; ++ky) {
auto lKYOffset = ky * kernel_width * ic;
auto srcKy = srcStart + ky * dilateY * src_width * bytes * unit;
for (int kx = 0; kx < kernel_width; ++kx) {
/* Compute x range:*/
/* 0 <= (oxBegin + x) * strideX - padX + dilateX * kx < src_width*/
/* 0 <= x <= step*/
int end = std::min(
step, (src_width - oxBegin * strideX - dilateX * kx + padX + strideX - 1) / strideX);
int sta = std::max(0, UP_DIV((padX - oxBegin * strideX - dilateX * kx), strideX));
if (end - sta < step) {
needZero = true;
}
if (end > sta) {
auto lOffset = lKYOffset + (kx * ic);
auto srcKx = srcKy + ((oxBegin + sta) * strideX + dilateX * kx - padX) * bytes * unit;
srcPtr[number] = (const float *)srcKx;
el[4 * number + 0] = end - sta;
el[4 * number + 1] = ic;
el[4 * number + 2] = eStart + sta;
el[4 * number + 3] = lOffset;
number++;
}
}
}
oxBegin = 0;
remain -= step;
eStart += step;
}
info[0] = number;
if (needZero || lP != 1) {
::memset(gemmBuffer, 0, mTempBufferTranspose.stride(0));
}
if (number > 0) {
packA((float *)gemmBuffer, srcPtr, info, el);
}
if (xC == eP) {
matmulUnit((float*)(dstOrigin + start * unit * bytes), (float*)gemmBuffer, weightPtr, parameters,postParameters.data(), biasPtr);
} else {
matmulRemain((float*)(dstOrigin + start * unit * bytes), (float*)gemmBuffer, weightPtr, xC, parameters,postParameters.data(), biasPtr);
}
}
};
return NO_ERROR;
}
} // namespace MNN
| 45.561934 | 191 | 0.562496 | foreverlms |
6baac81394bddd9d2004eed038e8f2c76543a91d | 5,054 | cpp | C++ | src/SortVisualizer.cpp | NFWSA/SortVisualizer | 32ce9b42d0c50b5ebca47169b5a9cc6eecec292b | [
"MIT"
] | null | null | null | src/SortVisualizer.cpp | NFWSA/SortVisualizer | 32ce9b42d0c50b5ebca47169b5a9cc6eecec292b | [
"MIT"
] | null | null | null | src/SortVisualizer.cpp | NFWSA/SortVisualizer | 32ce9b42d0c50b5ebca47169b5a9cc6eecec292b | [
"MIT"
] | null | null | null | #include "DataLine.h"
#include "SortView.h"
#include <ege.h>
#include <string>
#include <algorithm>
#include <map>
#include <exception>
using namespace ege;
using namespace SurgeNight;
class sort_break : std::logic_error {
public:
sort_break(const std::string &msg) : std::logic_error(msg) {}
};
void countSort(DataLine *beg, DataLine *end, SortView *view = nullptr)
{
unsigned int max = view->getMax();
auto count = new unsigned int[max + 1]();
std::fill(count, count + max + 1, 0);
try {
for (auto i = beg; i < end; ++i) {
i->setAccessed();
++count[i->getKey()];
}
for (auto i = 1u; i <= max; ++i) {
count[i] += count[i-1];
view->paint(static_cast<float>(i) / max * 100.0f);
}
}
catch (const sort_break &e) {
delete[] count;
throw;
}
auto ndata = new DataLine[end - beg];
view->setData(ndata);
try {
for (auto i = beg; i < end; ++i) {
ndata[--count[i->getKey()]] = *i;
}
}
catch (const sort_break &e) {
view->setData(nullptr);
delete[] ndata;
delete[] count;
throw;
}
view->setData(nullptr);
delete[] ndata;
delete[] count;
}
void selectSort(DataLine *beg, DataLine *end, SortView *view = nullptr)
{
for (auto i = beg; i < end; ++i) {
auto key = i;
for (auto j = i + 1; j < end; ++j) {
if (*j < *key)
key = j;
}
std::swap(*key, *i);
}
}
void bubbleSort(DataLine *beg, DataLine *end, SortView *view = nullptr)
{
for (auto i = beg; i < end; ++i) {
for (auto j = end - 1; j > i; --j) {
if (*(j - 1) > *j) {
std::swap(*(j - 1), *j);
}
}
}
}
void quickSort(DataLine *beg, DataLine *end, SortView *view = nullptr)
{
if (end <= beg)
return;
auto t = end - 1;
auto i = beg;
for (auto j = beg; j < end - 1; ++j) {
if (*j <= *t)
std::swap(*i++, *j);
}
std::swap(*i, *t);
quickSort(beg, i);
quickSort(i + 1, end);
}
void insertSort(DataLine *beg, DataLine *end, SortView *view = nullptr)
{
DataLine t;
for (auto i = beg; i < end; ++i) {
t = *i;
auto j = i;
for (; j > beg; --j) {
if (*(j - 1) > t)
*j = *(j - 1);
else
break;
}
std::swap(*j, t);
}
}
void stdSort(DataLine *beg, DataLine *end, SortView *view = nullptr)
{
std::sort(beg, end);
}
void show(const std::string &name, std::function<void(DataLine*, DataLine*, SortView*)> &func)
{
cleardevice();
SortView view(name, "in.txt", 0, 0, getwidth(), getheight());
try {
DataLine::setDrawFunc([&]() {
cleardevice();
view.paint();
if (ege::kbhit() && ege::getch() == ege::key_esc) {
sort_break a("Sort Break");
throw a;
}
});
func(view.begin(), view.end(), &view);
xyprintf(20, 20, "Sort finish, press any key to continue...");
}
catch (const sort_break &e) {
xyprintf(20, 20, "Sort break, press any key to continue...");
}
DataLine::setDrawFunc(nullptr);
getch();
}
int main()
{
setinitmode( INIT_NOFORCEEXIT | INIT_RENDERMANUAL );
//setinitmode( INIT_RENDERMANUAL | INIT_NOBORDER | INIT_NOFORCEEXIT );
initgraph(1300, 320);
setcaption("Sort Visualizer by SurgeNight");
std::string str[] = {
"bubble sort",
"insert sort",
"select sort",
"quick sort",
"count sort",
"std sort",
"exit"
};
typedef std::pair< std::string, std::function<void(DataLine*, DataLine*, SortView*)> > Algo;
typedef std::map< int, Algo > AlgoTab;
AlgoTab algo = {
{ key_1, { "Bubble", bubbleSort } },
{ key_2, { "Insert", insertSort } },
{ key_3, { "Select", selectSort } },
{ key_4, { "Quick", quickSort } },
{ key_5, { "Count", countSort } },
{ key_6, { "Std", stdSort } }
};
setfont(30, 0, "Arial");
setcolor(LIGHTGREEN);
while (is_run()) {
cleardevice();
xyprintf(20, 20, "Please press key to start to sort:");
auto menuNum = sizeof(str) / sizeof(std::string);
for(auto i = 0u; i < menuNum; ++i)
xyprintf(20, 50 + i * 30, "\t%d. %s", (i + 1) % menuNum, str[i].c_str());
int key = getch();
if (key_0 == key)
break;
auto it = algo.find(key);
if (it != algo.end()){
show((*it).second.first, (*it).second.second);
}
else {
xyprintf(20, 20, "Select error! Press any key to continue...");
getch();
continue;
}
}
closegraph();
return 0;
}
| 27.318919 | 97 | 0.475069 | NFWSA |
6bab921d21ad76d971808fd81abb4f1875381fa3 | 11,206 | cpp | C++ | src/qt/qtbase/src/widgets/dialogs/qerrormessage.cpp | chihlee/phantomjs | 644e0b3a6c9c16bcc6f7ce2c24274bf7d764f53c | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtbase/src/widgets/dialogs/qerrormessage.cpp | chihlee/phantomjs | 644e0b3a6c9c16bcc6f7ce2c24274bf7d764f53c | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtbase/src/widgets/dialogs/qerrormessage.cpp | chihlee/phantomjs | 644e0b3a6c9c16bcc6f7ce2c24274bf7d764f53c | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtWidgets module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qerrormessage.h"
#ifndef QT_NO_ERRORMESSAGE
#include "qapplication.h"
#include "qcheckbox.h"
#include "qlabel.h"
#include "qlayout.h"
#include "qmessagebox.h"
#include "qpushbutton.h"
#include "qstringlist.h"
#include "qtextedit.h"
#include "qdialog_p.h"
#include "qpixmap.h"
#include "qmetaobject.h"
#include "qthread.h"
#include "qqueue.h"
#include "qset.h"
#include <stdio.h>
#include <stdlib.h>
#ifdef Q_OS_WINCE
extern bool qt_wince_is_mobile(); //defined in qguifunctions_wince.cpp
extern bool qt_wince_is_high_dpi(); //defined in qguifunctions_wince.cpp
#endif
QT_BEGIN_NAMESPACE
class QErrorMessagePrivate : public QDialogPrivate
{
Q_DECLARE_PUBLIC(QErrorMessage)
public:
QPushButton * ok;
QCheckBox * again;
QTextEdit * errors;
QLabel * icon;
QQueue<QPair<QString, QString> > pending;
QSet<QString> doNotShow;
QSet<QString> doNotShowType;
QString currentMessage;
QString currentType;
bool nextPending();
void retranslateStrings();
};
class QErrorMessageTextView : public QTextEdit
{
public:
QErrorMessageTextView(QWidget *parent)
: QTextEdit(parent) { setReadOnly(true); }
virtual QSize minimumSizeHint() const;
virtual QSize sizeHint() const;
};
QSize QErrorMessageTextView::minimumSizeHint() const
{
#ifdef Q_OS_WINCE
if (qt_wince_is_mobile())
if (qt_wince_is_high_dpi())
return QSize(200, 200);
else
return QSize(100, 100);
else
return QSize(70, 70);
#else
return QSize(50, 50);
#endif
}
QSize QErrorMessageTextView::sizeHint() const
{
#ifdef Q_OS_WINCE
if (qt_wince_is_mobile())
if (qt_wince_is_high_dpi())
return QSize(400, 200);
else
return QSize(320, 120);
else
return QSize(300, 100);
#else
return QSize(250, 75);
#endif //Q_OS_WINCE
}
/*!
\class QErrorMessage
\brief The QErrorMessage class provides an error message display dialog.
\ingroup standard-dialog
\inmodule QtWidgets
An error message widget consists of a text label and a checkbox. The
checkbox lets the user control whether the same error message will be
displayed again in the future, typically displaying the text,
"Show this message again" translated into the appropriate local
language.
For production applications, the class can be used to display messages which
the user only needs to see once. To use QErrorMessage like this, you create
the dialog in the usual way, and show it by calling the showMessage() slot or
connecting signals to it.
The static qtHandler() function installs a message handler
using qInstallMessageHandler() and creates a QErrorMessage that displays
qDebug(), qWarning() and qFatal() messages. This is most useful in
environments where no console is available to display warnings and
error messages.
In both cases QErrorMessage will queue pending messages and display
them in order, with each new message being shown as soon as the user
has accepted the previous message. Once the user has specified that a
message is not to be shown again it is automatically skipped, and the
dialog will show the next appropriate message in the queue.
The \l{dialogs/standarddialogs}{Standard Dialogs} example shows
how to use QErrorMessage as well as other built-in Qt dialogs.
\image qerrormessage.png
\sa QMessageBox, QStatusBar::showMessage(), {Standard Dialogs Example}
*/
static QErrorMessage * qtMessageHandler = 0;
static void deleteStaticcQErrorMessage() // post-routine
{
if (qtMessageHandler) {
delete qtMessageHandler;
qtMessageHandler = 0;
}
}
static bool metFatal = false;
static void jump(QtMsgType t, const QMessageLogContext & /*context*/, const QString &m)
{
if (!qtMessageHandler)
return;
QString rich;
switch (t) {
case QtDebugMsg:
default:
rich = QErrorMessage::tr("Debug Message:");
break;
case QtWarningMsg:
rich = QErrorMessage::tr("Warning:");
break;
case QtFatalMsg:
rich = QErrorMessage::tr("Fatal Error:");
}
rich = QString::fromLatin1("<p><b>%1</b></p>").arg(rich);
rich += Qt::convertFromPlainText(m, Qt::WhiteSpaceNormal);
// ### work around text engine quirk
if (rich.endsWith(QLatin1String("</p>")))
rich.chop(4);
if (!metFatal) {
if (QThread::currentThread() == qApp->thread()) {
qtMessageHandler->showMessage(rich);
} else {
QMetaObject::invokeMethod(qtMessageHandler,
"showMessage",
Qt::QueuedConnection,
Q_ARG(QString, rich));
}
metFatal = (t == QtFatalMsg);
}
}
/*!
Constructs and installs an error handler window with the given \a
parent.
*/
QErrorMessage::QErrorMessage(QWidget * parent)
: QDialog(*new QErrorMessagePrivate, parent)
{
Q_D(QErrorMessage);
QGridLayout * grid = new QGridLayout(this);
d->icon = new QLabel(this);
#ifndef QT_NO_MESSAGEBOX
d->icon->setPixmap(QMessageBox::standardIcon(QMessageBox::Information));
d->icon->setAlignment(Qt::AlignHCenter | Qt::AlignTop);
#endif
grid->addWidget(d->icon, 0, 0, Qt::AlignTop);
d->errors = new QErrorMessageTextView(this);
grid->addWidget(d->errors, 0, 1);
d->again = new QCheckBox(this);
d->again->setChecked(true);
grid->addWidget(d->again, 1, 1, Qt::AlignTop);
d->ok = new QPushButton(this);
#if defined(Q_OS_WINCE)
d->ok->setFixedSize(0,0);
#endif
connect(d->ok, SIGNAL(clicked()), this, SLOT(accept()));
d->ok->setFocus();
grid->addWidget(d->ok, 2, 0, 1, 2, Qt::AlignCenter);
grid->setColumnStretch(1, 42);
grid->setRowStretch(0, 42);
d->retranslateStrings();
}
/*!
Destroys the error message dialog.
*/
QErrorMessage::~QErrorMessage()
{
if (this == qtMessageHandler) {
qtMessageHandler = 0;
QtMessageHandler tmp = qInstallMessageHandler(0);
// in case someone else has later stuck in another...
if (tmp != jump)
qInstallMessageHandler(tmp);
}
}
/*! \reimp */
void QErrorMessage::done(int a)
{
Q_D(QErrorMessage);
if (!d->again->isChecked() && !d->currentMessage.isEmpty() && d->currentType.isEmpty()) {
d->doNotShow.insert(d->currentMessage);
}
if (!d->again->isChecked() && !d->currentType.isEmpty()) {
d->doNotShowType.insert(d->currentType);
}
d->currentMessage.clear();
d->currentType.clear();
if (!d->nextPending()) {
QDialog::done(a);
if (this == qtMessageHandler && metFatal)
exit(1);
}
}
/*!
Returns a pointer to a QErrorMessage object that outputs the
default Qt messages. This function creates such an object, if there
isn't one already.
*/
QErrorMessage * QErrorMessage::qtHandler()
{
if (!qtMessageHandler) {
qtMessageHandler = new QErrorMessage(0);
qAddPostRoutine(deleteStaticcQErrorMessage); // clean up
qtMessageHandler->setWindowTitle(QApplication::applicationName());
qInstallMessageHandler(jump);
}
return qtMessageHandler;
}
/*! \internal */
bool QErrorMessagePrivate::nextPending()
{
while (!pending.isEmpty()) {
QPair<QString,QString> pendingMessage = pending.dequeue();
QString message = pendingMessage.first;
QString type = pendingMessage.second;
if (!message.isEmpty() && ((type.isEmpty() && !doNotShow.contains(message)) || (!type.isEmpty() && !doNotShowType.contains(type)))) {
#ifndef QT_NO_TEXTHTMLPARSER
errors->setHtml(message);
#else
errors->setPlainText(message);
#endif
currentMessage = message;
currentType = type;
return true;
}
}
return false;
}
/*!
Shows the given message, \a message, and returns immediately. If the user
has requested for the message not to be shown again, this function does
nothing.
Normally, the message is displayed immediately. However, if there are
pending messages, it will be queued to be displayed later.
*/
void QErrorMessage::showMessage(const QString &message)
{
Q_D(QErrorMessage);
if (d->doNotShow.contains(message))
return;
d->pending.enqueue(qMakePair(message,QString()));
if (!isVisible() && d->nextPending())
show();
}
/*!
\since 4.5
\overload
Shows the given message, \a message, and returns immediately. If the user
has requested for messages of type, \a type, not to be shown again, this
function does nothing.
Normally, the message is displayed immediately. However, if there are
pending messages, it will be queued to be displayed later.
\sa showMessage()
*/
void QErrorMessage::showMessage(const QString &message, const QString &type)
{
Q_D(QErrorMessage);
if (d->doNotShow.contains(message) && d->doNotShowType.contains(type))
return;
d->pending.push_back(qMakePair(message,type));
if (!isVisible() && d->nextPending())
show();
}
/*!
\reimp
*/
void QErrorMessage::changeEvent(QEvent *e)
{
Q_D(QErrorMessage);
if (e->type() == QEvent::LanguageChange) {
d->retranslateStrings();
}
QDialog::changeEvent(e);
}
void QErrorMessagePrivate::retranslateStrings()
{
again->setText(QErrorMessage::tr("&Show this message again"));
ok->setText(QErrorMessage::tr("&OK"));
}
QT_END_NAMESPACE
#endif // QT_NO_ERRORMESSAGE
| 28.807198 | 141 | 0.664465 | chihlee |
6babdeee115e810008549689e67d33f8cd193da3 | 7,294 | cpp | C++ | user/simple_shell/simple_shell.cpp | martin-hughes/project_azalea | 28aa0183cde350073cf0167df3f51435ea409c8b | [
"MIT"
] | 13 | 2017-12-20T00:02:38.000Z | 2022-01-07T11:18:36.000Z | user/simple_shell/simple_shell.cpp | martin-hughes/project_azalea | 28aa0183cde350073cf0167df3f51435ea409c8b | [
"MIT"
] | 21 | 2016-09-21T16:50:39.000Z | 2020-04-12T12:58:19.000Z | user/simple_shell/simple_shell.cpp | martin-hughes/project_azalea | 28aa0183cde350073cf0167df3f51435ea409c8b | [
"MIT"
] | 6 | 2017-12-20T00:02:27.000Z | 2019-03-21T16:28:24.000Z | #include <azalea/azalea.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <stdio.h>
#include <time.h>
#define SC_DEBUG_MSG(string) \
syscall_debug_output((string), strlen((string)) )
extern "C" int main (int argc, char **argv, char **env_p);
// #define OUTPUT_PARSE_RESULTS
char **child_argv = nullptr;
uint64_t child_argv_size = 0;
char *child_args_buffer = nullptr;
uint64_t child_args_buffer_size = 0;
bool is_command_char(char c);
void execute_command(char *command);
bool parse_command(char *command,
char** &argv_table,
char * &argv_buffer,
uint64_t &argv_table_size,
uint64_t argv_buffer_size);
bool count_command_details(char *command, uint64_t &num_args, uint64_t &argument_space_reqd);
int main (int argc, char **argv, char **env_p)
{
SC_DEBUG_MSG("Welcome to simple shell\n");
char *command_buffer;
uint8_t buffer_offset = 0;
int version = azalea_version();
size_t command_len;
const uint8_t MAX_CMD_LEN = 80;
size_t result_len;
time_expanded t;
ERR_CODE result;
printf("Azalea simple shell. OS Version: %d\n", version);
command_buffer = (char *)malloc(MAX_CMD_LEN + 1);
// Main command loop
while (1)
{
//time_t rawtime;
//struct tm * timeinfo;
//time (&rawtime);
//timeinfo = localtime (&rawtime);
//printf("%02u:%02u:%02u ", (unsigned int)timeinfo->tm_hour, (unsigned int)timeinfo->tm_min, (unsigned int)timeinfo->tm_sec);
result = syscall_get_system_clock(&t);
if (result == ERR_CODE::NO_ERROR)
{
printf("%02u:%02u:%02u ", (unsigned int)t.hours, (unsigned int)t.minutes, (unsigned int)t.seconds);
}
else
{
printf("--:--:-- ");
}
printf("> ");
fflush(stdout);
buffer_offset = 0;
memset(command_buffer, 0, sizeof(MAX_CMD_LEN + 1));
result_len = MAX_CMD_LEN;
command_len = getline(&command_buffer, &result_len, stdin);
command_buffer[command_len - 1] = 0;
if (command_len > 0 )
{
execute_command(command_buffer);
}
else
{
printf("Abort command\n");
}
};
return 0;
}
bool is_command_char(char c)
{
return (((c >= 'a') && (c <= 'z')) ||
((c >= 'A') && (c <= 'Z')) ||
((c >= '0') && (c <= '9')) ||
(c == '\\') ||
(c == ' '));
}
void execute_command(char *command)
{
GEN_HANDLE proc_handle;
object_properties props;
#ifdef OUTPUT_PARSE_RESULTS
printf("Execute: %s\n", command);
#endif
ERR_CODE result;
int i;
if (strlen(command) == 0)
{
printf("No command entered\n");
}
else
{
if (!parse_command(command, child_argv, child_args_buffer, child_argv_size, child_args_buffer_size))
{
printf("Unable to parse command\n");
}
else
{
i = 0;
#ifdef OUTPUT_PARSE_RESULTS
while(child_argv[i] != nullptr)
{
printf("Arg %d: %s\n", i, child_argv[i]);
i++;
}
#endif
if (strcmp(command, "exit") == 0)
{
printf("Exiting.\n");
exit(0);
}
else
{
result = exec_file(child_argv[0],
strlen(child_argv[0]),
&proc_handle,
(char * const *)(&child_argv[1]),
nullptr);
switch(result)
{
case ERR_CODE::NO_ERROR:
//SC_DEBUG_MSG("Program running\n");
syscall_wait_for_object(proc_handle, SC_MAX_WAIT);
if (syscall_get_object_properties(proc_handle, nullptr, 0, &props) == ERR_CODE::NO_ERROR)
{
printf("Exit code: %lu\n", props.additional_status);
}
else
{
printf("Didn't receive exit code\n");
}
syscall_close_handle(proc_handle);
break;
case ERR_CODE::NOT_FOUND:
printf("Command not found\n");
break;
case ERR_CODE::UNRECOGNISED:
printf("Command file not a recognised format.\n");
break;
default:
printf("Unknown error.\n");
break;
}
}
}
}
}
bool parse_command(char *command,
char** &argv_table,
char * &argv_buffer,
uint64_t &argv_table_size,
uint64_t argv_buffer_size)
{
uint64_t reqd_space = 0;
uint64_t num_args = 0;
char *write_ptr;
uint64_t cur_arg;
bool is_in_quote = false;
count_command_details(command, num_args, reqd_space);
#ifdef OUTPUT_PARSE_RESULTS
printf("Num args: %d, space: %d\n", num_args, reqd_space);
#endif
if ((num_args + 1) > argv_table_size)
{
if (argv_table != nullptr)
{
free(argv_table);
}
argv_table = reinterpret_cast<char **>(malloc(sizeof(char *) * (num_args + 1)));
argv_table_size = num_args + 1;
}
if (reqd_space > argv_buffer_size)
{
if (argv_buffer != nullptr)
{
free(argv_buffer);
}
argv_buffer = reinterpret_cast<char *>(malloc(reqd_space));
argv_buffer_size = reqd_space;
}
write_ptr = argv_buffer;
argv_table[0] = write_ptr;
argv_table[num_args] = nullptr;
cur_arg = 0;
// Skip leading spaces.
while (*command == ' ')
{
command++;
}
while (*command != 0)
{
*(write_ptr + 1) = 0;
if (*command == '\'')
{
if (*(command + 1) == '\'')
{
*write_ptr = '\'';
command++;
write_ptr++;
}
else
{
is_in_quote = !is_in_quote;
}
command++;
}
else
{
if ((*command == ' ') && !is_in_quote)
{
// Skip consecutive spaces.
while (*(command + 1) == ' ')
{
command++;
}
// Strip trailing spaces.
if (*(command + 1) == 0)
{
break;
}
// Otherwise begin a new argument.
*write_ptr = 0;
write_ptr++;
command++;
cur_arg++;
argv_table[cur_arg] = write_ptr;
}
else
{
*write_ptr = *command;
write_ptr++;
command++;
}
}
}
return !is_in_quote;
}
bool count_command_details(char *command, uint64_t &num_args, uint64_t &argument_space_reqd)
{
bool is_in_quote = false;
argument_space_reqd = 1; // Add an extra one to allow a trailing 0.
num_args = 1;
if (command == nullptr)
{
return false;
}
// Skip leading spaces.
while (*command == ' ')
{
command++;
}
while(*command != 0)
{
if(*command == '\'')
{
if (*(command + 1) == '\'')
{
argument_space_reqd++;
command++;
}
else
{
is_in_quote = !is_in_quote;
}
}
else
{
if ((*command == ' ') && !is_in_quote)
{
// Skip consecutive spaces.
while (*(command + 1) == ' ')
{
command++;
}
// Ignore trailing spaces.
if (*(command + 1) == 0)
{
break;
}
num_args++;
argument_space_reqd++;
}
else
{
argument_space_reqd++;
}
}
command++;
}
if (is_in_quote)
{
#ifdef OUTPUT_PARSE_RESULTS
printf("Unmatched quote symbols\n");
#endif
return false;
}
return true;
}
| 20.95977 | 129 | 0.541815 | martin-hughes |
6babe9b2516f92e9e3db90d77a034a4747cd90b5 | 14,283 | cpp | C++ | DeepSkyDad.AF2.ESP32/src/Motor_AF2.cpp | DeepSkyDad/AF2 | 126bb3e09c76fd83932dd60cf9df8ba7ddc1df7e | [
"MIT"
] | null | null | null | DeepSkyDad.AF2.ESP32/src/Motor_AF2.cpp | DeepSkyDad/AF2 | 126bb3e09c76fd83932dd60cf9df8ba7ddc1df7e | [
"MIT"
] | 1 | 2019-09-09T23:56:16.000Z | 2019-09-22T08:15:27.000Z | DeepSkyDad.AF2.ESP32/src/Motor_AF2.cpp | DeepSkyDad/AF2 | 126bb3e09c76fd83932dd60cf9df8ba7ddc1df7e | [
"MIT"
] | null | null | null | #include <Arduino.h>
#include "Motor_AF2.h"
void Motor_AF2::_writeCoilsMode()
{
//Serial.println(_eeprom->getIsManualControl());
if (isMoving())
return;
unsigned short coilsMode = _eeprom->getIsManualControl() ? _eeprom->getManualCoilsMode() : _eeprom->getCoilsMode();
unsigned int holdCurrent = _eeprom->getIsManualControl() ? _eeprom->getManualCoilsCurrentHold() : _eeprom->getCoilsCurrentHold();
unsigned int timeoutMs = _eeprom->getIsManualControl() ? _eeprom->getManualCoilsIdleTimeoutMs() : _eeprom->getCoilsIdleTimeoutMs();
if (coilsMode == (unsigned short)COILS_MODE::IDLE_OFF)
{
//Serial.println("off");
digitalWrite(MP6500_PIN_SLP, LOW);
_coilsOn = false;
}
//Always on
else if (coilsMode == (unsigned short)COILS_MODE::ALWAYS_ON)
{
//Serial.println("Always on");
digitalWrite(MP6500_PIN_SLP, HIGH);
ledcWrite(MP6500_PIN_I1_CHANNEL, holdCurrent);
_coilsOn = true;
}
//Idle - coils timeout (ms)
else if (coilsMode == (unsigned short)COILS_MODE::IDLE_TIMEOUT_OFF)
{
//Serial.println("Timeout");
if ((millis() - _lastStopMs) <= timeoutMs)
{
digitalWrite(MP6500_PIN_SLP, HIGH);
ledcWrite(MP6500_PIN_I1_CHANNEL, holdCurrent);
_coilsOn = true;
}
else
{
digitalWrite(MP6500_PIN_SLP, LOW);
_coilsOn = false;
}
}
}
void Motor_AF2::_writeStepMode(unsigned short stepMode)
{
switch (stepMode)
{
case (unsigned short)STEP_MODE::FULL:
digitalWrite(MP6500_PIN_MS1, 0);
digitalWrite(MP6500_PIN_MS2, 0);
break;
case (unsigned short)STEP_MODE::HALF:
digitalWrite(MP6500_PIN_MS1, 1);
digitalWrite(MP6500_PIN_MS2, 0);
break;
case (unsigned short)STEP_MODE::QUARTER:
digitalWrite(MP6500_PIN_MS1, 0);
digitalWrite(MP6500_PIN_MS2, 1);
break;
case (unsigned short)STEP_MODE::EIGHT:
digitalWrite(MP6500_PIN_MS1, 1);
digitalWrite(MP6500_PIN_MS2, 1);
break;
default: // half step by default
digitalWrite(MP6500_PIN_MS1, 1);
digitalWrite(MP6500_PIN_MS2, 0);
break;
}
}
void Motor_AF2::init(EEPROM_AF2 &eeprom)
{
pinMode(MP6500_PIN_DIR, OUTPUT);
pinMode(MP6500_PIN_STEP, OUTPUT);
pinMode(MP6500_PIN_MS1, OUTPUT);
pinMode(MP6500_PIN_MS2, OUTPUT);
pinMode(MP6500_PIN_SLP, OUTPUT);
pinMode(MP6500_PIN_EN, OUTPUT);
digitalWrite(MP6500_PIN_EN, LOW);
ledcAttachPin(MP6500_PIN_I1, 1);
// Initialize channels
// channels 0-15, resolution 1-16 bits, freq limits depend on resolution
// ledcSetup(uint8_t channel, uint32_t freq, uint8_t resolution_bits);
ledcSetup(1, 64000, 12); // 12 kHz PWM, 12-bit resolution
// set direction and step to low
digitalWrite(MP6500_PIN_DIR, LOW);
digitalWrite(MP6500_PIN_STEP, LOW);
digitalWrite(MP6500_PIN_SLP, LOW);
_eeprom = &eeprom;
_writeStepMode(_eeprom->getStepMode());
_writeCoilsMode();
}
//GENERAL
void Motor_AF2::handleMove()
{
if (_movementStatus != MOVEMENT_STATUS::STOP)
{
digitalWrite(MP6500_PIN_SLP, HIGH);
ledcWrite(MP6500_PIN_I1_CHANNEL, _eeprom->getIsManualControl() ? _eeprom->getManualCoilsCurrentMove() : _eeprom->getCoilsCurrentMove());
unsigned short sm = _eeprom->getIsManualControl() ? _eeprom->getManualStepMode() : _eeprom->getStepMode();
bool reverseDirection = _eeprom->getIsManualControl() ? _eeprom->getManualReverseDirection() : _eeprom->getReverseDirection();
unsigned int speedFactor = 1;
switch (_eeprom->getIsManualControl() ? _eeprom->getManualSpeedMode() : _eeprom->getSpeedMode())
{
case (unsigned short)SPEED_MODE::SLOW:
speedFactor = 30;
break;
case (unsigned short)SPEED_MODE::MEDIUM:
speedFactor = 12;
break;
case (unsigned short)SPEED_MODE::FAST:
speedFactor = 1;
break;
}
if (_eeprom->getTargetPosition() < _eeprom->getPosition())
{
digitalWrite(MP6500_PIN_DIR, reverseDirection ? LOW : HIGH);
while (_eeprom->getPosition() > _eeprom->getTargetPosition())
{
digitalWrite(MP6500_PIN_STEP, 1);
delayMicroseconds(1);
digitalWrite(MP6500_PIN_STEP, 0);
_eeprom->setPosition(_eeprom->getPosition() - 1);
delayMicroseconds(speedFactor * (1600 / sm));
if (_movementStatus == MOVEMENT_STATUS::MOVING_MANUAL_CONTINUOUS)
_eeprom->setTargetPosition(_eeprom->getTargetPosition() - 2);
}
}
else if (_eeprom->getTargetPosition() > _eeprom->getPosition())
{
digitalWrite(MP6500_PIN_DIR, reverseDirection ? HIGH : LOW);
while (_eeprom->getPosition() < _eeprom->getTargetPosition())
{
digitalWrite(MP6500_PIN_STEP, 1);
delayMicroseconds(1);
digitalWrite(MP6500_PIN_STEP, 0);
_eeprom->setPosition(_eeprom->getPosition() + 1);
delayMicroseconds(speedFactor * (1600 / sm));
if (_movementStatus == MOVEMENT_STATUS::MOVING_MANUAL_CONTINUOUS)
_eeprom->setTargetPosition(_eeprom->getTargetPosition() + 2);
}
}
stop();
}
else
{
unsigned short coilsMode = _eeprom->getIsManualControl() ? _eeprom->getManualCoilsMode() : _eeprom->getCoilsMode();
if (_coilsOn && coilsMode == (unsigned short)COILS_MODE::IDLE_TIMEOUT_OFF)
{
//auto-off coils after timeout
unsigned int timeoutMs = _eeprom->getIsManualControl() ? _eeprom->getManualCoilsIdleTimeoutMs() : _eeprom->getCoilsIdleTimeoutMs();
if ((millis() - _lastStopMs) > timeoutMs)
{
_writeCoilsMode();
}
}
}
}
void Motor_AF2::stop()
{
if (_movementStatus != MOVEMENT_STATUS::STOP)
{
_movementStatus = MOVEMENT_STATUS::STOP;
_eeprom->setTargetPosition(_eeprom->getPosition());
_lastStopMs = millis();
_settled = _eeprom->getSettleBufferMs() == 0;
_writeCoilsMode();
}
}
bool Motor_AF2::isMoving()
{
if (_movementStatus != MOVEMENT_STATUS::STOP)
{
return true;
}
else
{
/*
if your focuser has any play, this can affect the autofocuser performance. SGP for example goes aways from current position and
than starts traversing back. When it changes focus direction (traverse back), focuser play can cause FOV to wiggle just a bit,
which causes enlongated stars on the next exposure. Settle buffer option returns IsMoving as TRUE after focuser reaches target position,
letting it to settle a bit. Advices by Jared Wellman of SGP.
*/
if (!_settled)
{
if ((millis() - _lastStopMs) > _eeprom->getSettleBufferMs())
{
_settled = true;
return false;
}
else
{
return true;
}
}
else
{
return false;
}
}
}
MOVEMENT_STATUS Motor_AF2::getMovementStatus()
{
return _movementStatus;
}
void Motor_AF2::resetToDefaults() {
_writeStepMode(_eeprom->getStepMode());
_writeCoilsMode();
}
//EXTERNAL (ASCOM or INDI via Serial/Wifi)
void Motor_AF2::move()
{
if (_eeprom->getTargetPosition() == _eeprom->getPosition())
return;
_writeStepMode(_eeprom->getStepMode());
digitalWrite(MP6500_PIN_SLP, HIGH);
ledcWrite(MP6500_PIN_I1_CHANNEL, _eeprom->getCoilsCurrentMove());
/*
When waking up from sleep mode,
approximately 1ms of time must pass before a
STEP command can be issued to allow the
internal circuitry to stabilize.
*/
delayMicroseconds(1000);
_movementStatus = MOVEMENT_STATUS::MOVING;
_eeprom->setIsManualControl(false);
_eeprom->delayEepromWrite();
}
void Motor_AF2::setCoilsMode(unsigned short mode)
{
_eeprom->setIsManualControl(false);
_eeprom->setCoilsMode(mode);
_writeCoilsMode();
}
int Motor_AF2::getMoveCurrentPercent()
{
return (int)((float)MP6500_PIN_I1_MOVE_MAX - (float)_eeprom->getCoilsCurrentMove()) / (float)MP6500_PIN_I1_MOVE_RANGE * 100;
}
void Motor_AF2::setMoveCurrentPercent(float percent)
{
percent = percent / 100.0;
_eeprom->setCoilsCurrentMove((unsigned short)MP6500_PIN_I1_MOVE_MAX - MP6500_PIN_I1_MOVE_RANGE * percent);
}
void Motor_AF2::setMoveCurrent(unsigned int value)
{
_eeprom->setIsManualControl(false);
if (value > MP6500_PIN_I1_MOVE_MAX)
value = MP6500_PIN_I1_MOVE_MAX;
else if (value < MP6500_PIN_I1_MOVE_MIN)
value = MP6500_PIN_I1_MOVE_MIN;
_eeprom->setCoilsCurrentMove(value);
_writeCoilsMode();
}
int Motor_AF2::getHoldCurrentPercent()
{
return (int)((float)MP6500_PIN_I1_HOLD_MAX - (float)_eeprom->getCoilsCurrentHold()) / (float)MP6500_PIN_I1_HOLD_RANGE * 100;
}
void Motor_AF2::setHoldCurrentPercent(float percent)
{
percent = percent / 100.0;
_eeprom->setCoilsCurrentHold((unsigned short)(MP6500_PIN_I1_HOLD_MAX - MP6500_PIN_I1_HOLD_RANGE * percent));
_writeCoilsMode();
}
void Motor_AF2::setHoldCurrent(unsigned int value)
{
_eeprom->setIsManualControl(false);
if (value > MP6500_PIN_I1_HOLD_MAX)
value = MP6500_PIN_I1_HOLD_MAX;
else if (value < MP6500_PIN_I1_HOLD_MIN)
value = MP6500_PIN_I1_HOLD_MIN;
_eeprom->setCoilsCurrentHold(value);
_writeCoilsMode();
}
//MANUAL MOVEMENT
void Motor_AF2::moveManual()
{
if (_eeprom->getTargetPosition() == _eeprom->getPosition())
return;
_writeStepMode(_eeprom->getManualStepMode());
digitalWrite(MP6500_PIN_SLP, HIGH);
ledcWrite(MP6500_PIN_I1_CHANNEL, _eeprom->getManualCoilsCurrentMove());
/*
When waking up from sleep mode,
approximately 1ms of time must pass before a
STEP command can be issued to allow the
internal circuitry to stabilize.
*/
delayMicroseconds(1000);
_movementStatus = MOVEMENT_STATUS::MOVING_MANUAL;
_eeprom->setIsManualControl(true);
_eeprom->delayEepromWrite();
}
void Motor_AF2::moveManual(MOVEMENT_MANUAL_DIR dir)
{
_eeprom->setIsManualControl(true);
int diff = _eeprom->getManualFineMoveSteps();
if (_eeprom->getManualStepSize() == (unsigned short)MANUAL_STEP_SIZE::COARSE)
{
diff = _eeprom->getManualCoarseMoveSteps();
}
if (dir == MOVEMENT_MANUAL_DIR::CW)
_eeprom->setTargetPosition(_eeprom->getPosition() + diff);
else
{
if (diff > _eeprom->getPosition())
_eeprom->setTargetPosition(0);
else
_eeprom->setTargetPosition(_eeprom->getPosition() - diff);
}
if (_eeprom->getTargetPosition() == _eeprom->getPosition())
return;
//Serial.println(_eeprom->getPosition());
//Serial.println(_eeprom->getTargetPosition());
_writeStepMode(_eeprom->getManualStepMode());
digitalWrite(MP6500_PIN_SLP, HIGH);
ledcWrite(MP6500_PIN_I1_CHANNEL, _eeprom->getManualCoilsCurrentMove());
/*
When waking up from sleep mode,
approximately 1ms of time must pass before a
STEP command can be issued to allow the
internal circuitry to stabilize.
*/
delayMicroseconds(1000);
_movementStatus = MOVEMENT_STATUS::MOVING_MANUAL;
_eeprom->delayEepromWrite();
}
void Motor_AF2::moveManualContinuous(MOVEMENT_MANUAL_DIR dir)
{
_eeprom->setIsManualControl(true);
_writeStepMode(_eeprom->getManualStepMode());
digitalWrite(MP6500_PIN_SLP, HIGH);
ledcWrite(MP6500_PIN_I1_CHANNEL, _eeprom->getManualCoilsCurrentMove());
/*
When waking up from sleep mode,
approximately 1ms of time must pass before a
STEP command can be issued to allow the
internal circuitry to stabilize.
*/
delayMicroseconds(1000);
if (dir == MOVEMENT_MANUAL_DIR::CW)
{
_eeprom->setTargetPosition(_eeprom->getTargetPosition() + 1);
_movementStatus = MOVEMENT_STATUS::MOVING_MANUAL_CONTINUOUS;
}
else
{
_eeprom->setTargetPosition(_eeprom->getTargetPosition() - 1);
_movementStatus = MOVEMENT_STATUS::MOVING_MANUAL_CONTINUOUS;
}
_eeprom->delayEepromWrite();
}
void Motor_AF2::setManualCoilsMode(unsigned short mode)
{
_eeprom->setIsManualControl(true);
_eeprom->setManualCoilsMode(mode);
_writeCoilsMode();
}
int Motor_AF2::getManualMoveCurrentPercent()
{
return (int)((float)MP6500_PIN_I1_MOVE_MAX - (float)_eeprom->getManualCoilsCurrentMove()) / (float)MP6500_PIN_I1_MOVE_RANGE * 100;
}
void Motor_AF2::setManualMoveCurrentPercent(float percent)
{
percent = percent / 100.0;
_eeprom->setManualCoilsCurrentMove((unsigned short)MP6500_PIN_I1_MOVE_MAX - MP6500_PIN_I1_MOVE_RANGE * percent);
}
void Motor_AF2::setManualMoveCurrent(unsigned int value)
{
_eeprom->setIsManualControl(true);
if (value > MP6500_PIN_I1_MOVE_MAX)
value = MP6500_PIN_I1_MOVE_MAX;
else if (value < MP6500_PIN_I1_MOVE_MIN)
value = MP6500_PIN_I1_MOVE_MIN;
_eeprom->setManualCoilsCurrentMove(value);
_writeCoilsMode();
}
int Motor_AF2::getManualHoldCurrentPercent()
{
return (int)((float)MP6500_PIN_I1_HOLD_MAX - (float)_eeprom->getManualCoilsCurrentHold()) / (float)MP6500_PIN_I1_HOLD_RANGE * 100;
}
void Motor_AF2::setManualHoldCurrentPercent(float percent)
{
percent = percent / 100.0;
_eeprom->setManualCoilsCurrentHold((unsigned short)MP6500_PIN_I1_HOLD_MAX - MP6500_PIN_I1_HOLD_RANGE * percent);
_writeCoilsMode();
}
void Motor_AF2::setManualHoldCurrent(unsigned int value)
{
_eeprom->setIsManualControl(true);
if (value > MP6500_PIN_I1_HOLD_MAX)
value = MP6500_PIN_I1_HOLD_MAX;
else if (value < MP6500_PIN_I1_HOLD_MIN)
value = MP6500_PIN_I1_HOLD_MIN;
_eeprom->setManualCoilsCurrentHold(value);
_writeCoilsMode();
} | 31.669623 | 148 | 0.660505 | DeepSkyDad |
6bb0458ab4e21e879de84213c10e3435ea28d335 | 1,394 | cc | C++ | dyn/src/main.cc | balayette/saphIR-project | 18da494ac21e5433fdf1c646be02c9bf25177d7d | [
"MIT"
] | 14 | 2020-07-31T09:35:23.000Z | 2021-11-15T11:18:35.000Z | dyn/src/main.cc | balayette/saphIR-project | 18da494ac21e5433fdf1c646be02c9bf25177d7d | [
"MIT"
] | null | null | null | dyn/src/main.cc | balayette/saphIR-project | 18da494ac21e5433fdf1c646be02c9bf25177d7d | [
"MIT"
] | null | null | null | #include <iostream>
#include <getopt.h>
#include "utils/fs.hh"
#include "dyn/emu.hh"
#include "dyn/unicorn-emu.hh"
#include "fmt/format.h"
#include <string>
#include <optional>
struct options {
std::optional<std::string> coverage_file;
std::string binary;
bool help;
bool singlestep;
};
options parse_options(int argc, char **argv)
{
int opt = 0;
options ret{};
while ((opt = getopt(argc, argv, "shc:")) != -1 && !ret.help) {
if (opt == 'c')
ret.coverage_file = optarg;
else if (opt == 'h')
ret.help = true;
else if (opt == 's')
ret.singlestep = true;
else {
fmt::print("option '{}' not recognized\n", (char)opt);
ret.help = true;
}
}
if (optind == argc)
ret.help = true;
else
ret.binary = argv[optind];
return ret;
}
int main(int argc, char *argv[])
{
auto opts = parse_options(argc, argv);
if (opts.help) {
fmt::print("{} [-c coverage_output] [-s] [-h] binary\n",
argv[0]);
return 1;
}
utils::mapped_file file(opts.binary);
dyn::emu emu(file, dyn::emu_params(opts.singlestep));
std::ofstream coverage_file;
if (opts.coverage_file) {
coverage_file.open(*opts.coverage_file);
emu.add_on_entry_callback([&](uint64_t pc, uint64_t end) {
for (uint64_t i = pc; i <= end; i += 4)
coverage_file << fmt::format("{:#x}\n", i);
});
}
emu.init();
emu.setup();
emu.run();
fmt::print("Exited: {}\n", emu.exit_code());
}
| 19.633803 | 64 | 0.621951 | balayette |
6bb2533d765f7526f977de70830165c431947c14 | 9,305 | cpp | C++ | core/fileManager.cpp | n3on/revisy | f69f778563776ae463505baf9835820704e72bd4 | [
"MIT"
] | 1 | 2020-02-18T22:59:20.000Z | 2020-02-18T22:59:20.000Z | core/fileManager.cpp | n3on/revisy | f69f778563776ae463505baf9835820704e72bd4 | [
"MIT"
] | null | null | null | core/fileManager.cpp | n3on/revisy | f69f778563776ae463505baf9835820704e72bd4 | [
"MIT"
] | null | null | null | /***************************************************************************
* This file is part of the ReViSy project
* Copyright (C) 2007 by Neon
***************************************************************************/
#include "fileManager.h"
FileManager* FileManager::m_instance = NULL;
FileManager::FileManager()
{
//this->m_fileModel.loadFile();
this->m_list = 0;
this->m_initFolder = false;
this->m_hdc = GetDC(Config->getHWND());
m_font = new OutFont(this->m_hdc);
}
FileManager::~FileManager()
{
ReleaseDC(Config->getHWND(),this->m_hdc);
}
FileManager* FileManager::getInstance()
{
if(FileManager::m_instance==NULL)
FileManager::m_instance = new FileManager();
return FileManager::m_instance;
}
void FileManager::renderFiles()
{
//glPushMatrix();
//if(!this->m_list)
//{
// this->m_list = glGenLists(1);
// glNewList(this->m_list, GL_COMPILE);
//glScalef(this->m_files[0].width,this->m_files[0].height,this->m_files[0].depth);
//this->m_file.render();
//printf("pos: x = %f, y = %f, z = %f\n",camera->getPosition().x, camera->getPosition().y,camera->getPosition().z);
for(int i=0; i<this->m_files.size(); i++)
{
//glPushMatrix();
//glRotatef(180.0f,0.0f,1.0f,0.0f);
if(frustum->boxCheck(this->m_files[i].getPosition().x,
this->m_files[i].getPosition().y,
this->m_files[i].getPosition().z,
this->m_files[i].width,
this->m_files[i].height,
this->m_files[i].depth))
{
glPushMatrix();
/* printf("pos: x = %f, y = %f, z = %f\n",camera->getPosition().x, camera->getPosition().y,camera->getPosition().z);
printf("render: i = %d, x1 = %f, y2 = %f, z3 = %f\n",i,this->m_files[i].getPosition().x,
this->m_files[i].getPosition().y,
this->m_files[i].getPosition().z);*/
//glPopMatrix();
//glPushMatrix();
this->m_files[i].render();
glColor3f(0.0f,1.0f,0.0f);
this->m_font->setBody(this->m_files[i].width,
this->m_files[i].height,
this->m_files[i].depth);
this->m_font->print(this->m_files[i].getPosition().x,
this->m_files[i].getPosition().y+this->m_files[i].height+1,
this->m_files[i].getPosition().z,
this->m_files[i].getFileName());
/*if(((abs(camera->getPosition().x-this->m_files[i].getPosition().x))<=this->m_files[i].width) &&
((abs(camera->getPosition().y-this->m_files[i].getPosition().y))<=this->m_files[i].height) &&
((abs(camera->getPosition().z-this->m_files[i].getPosition().z))<=this->m_files[i].depth))
{*/
if(this->m_files[i].objectCollision(camera->getPosition()))
{
if(this->m_files[i].getFileType()==FILE_TYPE_DIR)
{
this->m_initFolder = false;
//MessageBox(NULL,Config->getValue("StartPath"),"BeforePath",MB_OK);
char *newPath;
newPath = new char[1024];
//char *oldPath;
//memset(newPath,0,sizeof(newPath));
//oldPath = new char[1024];
strncpy(newPath, Config->getValue("StartPath"),strlen(Config->getValue("StartPath")));
newPath[strlen(Config->getValue("StartPath"))-1] = '\0';
//MessageBox(NULL,newPath,"NewPath",MB_OK);
sprintf(newPath,"%s%s\\*",newPath,this->m_files[i].getFileName());
//Config->makeEntry("StartPath",newPath);
Config->makeEntry("StartPath",newPath);
//MessageBox(NULL,Config->getValue("StartPath"),"StartPath",MB_OK);
camera->SetCamera(0,
0,
0,
1,
0,
-1);
this->m_files.clear();
}
else
{
if(GetKeyState('W') & 0x80) camera->Move(DIR_DOWN, fps->getSpeedFactor(60));
if(GetKeyState('S') & 0x80) camera->Move(DIR_UP, fps->getSpeedFactor(60));
if(GetKeyState('D') & 0x80) camera->RotateY(DIR_LEFT, fps->getSpeedFactor(60));
if(GetKeyState('A') & 0x80) camera->RotateY(DIR_RIGHT, fps->getSpeedFactor(60));
}
}
// printf("pos: x = %f, y = %f, z = %f\n",camera->getPosition().x, camera->getPosition().y,camera->getPosition().z);
glPopMatrix();
}
else
{
//this->m_files[i].moveObject(this->m_files[i].getPosition().x,
// this->m_files[i].getPosition().y+30.0f,
// this->m_files[i].getPosition().z);
/*glPushMatrix();
glColor3f(1.0f,0.0f,0.0f);
this->m_files[i].render();
glPopMatrix();*/
}
}
//glPopMatrix();
// glEndList();
//}
//else
// glCallList(this->m_list);
}
bool FileManager::isInitialized()
{
return this->m_initFolder;
}
void FileManager::GetFilesInFolder(const char *path)
{
//File fileModel;
WIN32_FIND_DATA fileData;
//glPushMatrix();
//if(!this->m_list)
//{
// glPushMatrix();
// this->m_list = glGenLists(1);
// glNewList(this->m_list, GL_COMPILE);
this->m_fileHandle = FindFirstFile(path, &fileData);
//fileModel.setPosition(0.0f,0.0f,0.0f);
//glTranslatef(0.0f,0.0f,0.0f);
float x = 160.0f;
float y = 130.0f;
float z = -100.0f;
float posX = 0;
float posY = 0;
float posZ = 0;
int numRowX = 0;
int numRowZ = 0;
do
{
File fileModel;
fileModel.setFileName(fileData.cFileName);
switch(fileData.dwFileAttributes)
{
case FILE_ATTRIBUTE_SYSTEM:
case FILE_ATTRIBUTE_READONLY:
case FILE_ATTRIBUTE_ARCHIVE:
case FILE_ATTRIBUTE_NORMAL:
case FILE_ATTRIBUTE_COMPRESSED:
case FILE_ATTRIBUTE_TEMPORARY:
case FILE_ATTRIBUTE_SPARSE_FILE:
case FILE_ATTRIBUTE_REPARSE_POINT:
case FILE_ATTRIBUTE_OFFLINE:
case FILE_ATTRIBUTE_HIDDEN:
case FILE_ATTRIBUTE_ENCRYPTED:
case FILE_ATTRIBUTE_DIRECTORY:
{
fileModel.width = 8;
fileModel.height = 16;
fileModel.depth = 8;
fileModel.setFileType(FILE_TYPE_DIR);
}break;
default:
{
fileModel.width = 16;
fileModel.height = 16;
fileModel.depth = 16;
fileModel.setFileType(FILE_TYPE_NON);
}break;
}
//if (!(((m_fileData.cFileName[0]=='.') && (m_fileData.cFileName[1]=='.')||(m_fileData.cFileName[1]==0))))
//{
if(numRowX<10)
{
/* if(numRowZ>=10)
{
this->m_file.moveObject(0.0f,20.0f,0.0f);
//glTranslatef(0.0f,100.0f,0.0f);
z = -z;
numRowZ = 0;
}
else*/
posX += x;
fileModel.moveObject(posX,posY,posZ);
//glTranslatef(x,0.0f,0.0f);
}
else
{
//glTranslatef(0.0f,0.0f,z);
//x = -10*x;
numRowZ++;
numRowX = 0;
//z = 20.0f;
posX = x;
posZ += z;
fileModel.moveObject(posX,posY,posZ);
}
if(numRowZ>=10)
{
numRowZ = 0;
posZ = z;
posY += y;
}
//MessageBox(NULL,"File Found","Info",MB_OK);
//glTranslatef(x,0.0f,z);
//this->renderFiles();
//i+=0.5;
numRowX++;
//this->m_file.moveObject(x,0.0f,0.0f);
//this->m_file.moveObject(200.0f,0.0f,0.0f);
this->m_files.push_back(fileModel);
//this->renderFiles();
//}
}while(FindNextFile(this->m_fileHandle,&fileData));
//i=0.0f;
// glPopMatrix();
FindClose(this->m_fileHandle);
//glEndList();
//}
//else
// glCallList(this->m_list);
this->m_initFolder = true;
}
| 32.309028 | 138 | 0.450188 | n3on |
6bb3e07fc264cfe462095b63872339a0d6fc0e7e | 5,833 | cpp | C++ | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_spirit_corehelper_cfg.cpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 17 | 2016-12-02T05:45:49.000Z | 2022-02-10T19:32:54.000Z | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_spirit_corehelper_cfg.cpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2017-03-27T15:22:38.000Z | 2019-11-05T08:30:16.000Z | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_spirit_corehelper_cfg.cpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 11 | 2016-12-02T05:45:52.000Z | 2019-11-07T08:28:17.000Z |
#include <sstream>
#include <iostream>
#include <ydk/entity_util.hpp>
#include "bundle_info.hpp"
#include "generated_entity_lookup.hpp"
#include "Cisco_IOS_XR_spirit_corehelper_cfg.hpp"
using namespace ydk;
namespace cisco_ios_xr {
namespace Cisco_IOS_XR_spirit_corehelper_cfg {
Exception::Exception()
:
file(std::make_shared<Exception::File>())
{
file->parent = this;
yang_name = "exception"; yang_parent_name = "Cisco-IOS-XR-spirit-corehelper-cfg"; is_top_level_class = true; has_list_ancestor = false;
}
Exception::~Exception()
{
}
bool Exception::has_data() const
{
if (is_presence_container) return true;
return (file != nullptr && file->has_data());
}
bool Exception::has_operation() const
{
return is_set(yfilter)
|| (file != nullptr && file->has_operation());
}
std::string Exception::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-spirit-corehelper-cfg:exception";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Exception::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Exception::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "file")
{
if(file == nullptr)
{
file = std::make_shared<Exception::File>();
}
return file;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Exception::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(file != nullptr)
{
_children["file"] = file;
}
return _children;
}
void Exception::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Exception::set_filter(const std::string & value_path, YFilter yfilter)
{
}
std::shared_ptr<ydk::Entity> Exception::clone_ptr() const
{
return std::make_shared<Exception>();
}
std::string Exception::get_bundle_yang_models_location() const
{
return ydk_cisco_ios_xr_models_path;
}
std::string Exception::get_bundle_name() const
{
return "cisco_ios_xr";
}
augment_capabilities_function Exception::get_augment_capabilities_function() const
{
return cisco_ios_xr_augment_lookup_tables;
}
std::map<std::pair<std::string, std::string>, std::string> Exception::get_namespace_identity_lookup() const
{
return cisco_ios_xr_namespace_identity_lookup;
}
bool Exception::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "file")
return true;
return false;
}
Exception::File::File()
:
choice2{YType::str, "choice2"},
choice1{YType::str, "choice1"},
choice3{YType::str, "choice3"}
{
yang_name = "file"; yang_parent_name = "exception"; is_top_level_class = false; has_list_ancestor = false;
}
Exception::File::~File()
{
}
bool Exception::File::has_data() const
{
if (is_presence_container) return true;
return choice2.is_set
|| choice1.is_set
|| choice3.is_set;
}
bool Exception::File::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(choice2.yfilter)
|| ydk::is_set(choice1.yfilter)
|| ydk::is_set(choice3.yfilter);
}
std::string Exception::File::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-spirit-corehelper-cfg:exception/" << get_segment_path();
return path_buffer.str();
}
std::string Exception::File::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "file";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Exception::File::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (choice2.is_set || is_set(choice2.yfilter)) leaf_name_data.push_back(choice2.get_name_leafdata());
if (choice1.is_set || is_set(choice1.yfilter)) leaf_name_data.push_back(choice1.get_name_leafdata());
if (choice3.is_set || is_set(choice3.yfilter)) leaf_name_data.push_back(choice3.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Exception::File::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Exception::File::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Exception::File::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "choice2")
{
choice2 = value;
choice2.value_namespace = name_space;
choice2.value_namespace_prefix = name_space_prefix;
}
if(value_path == "choice1")
{
choice1 = value;
choice1.value_namespace = name_space;
choice1.value_namespace_prefix = name_space_prefix;
}
if(value_path == "choice3")
{
choice3 = value;
choice3.value_namespace = name_space;
choice3.value_namespace_prefix = name_space_prefix;
}
}
void Exception::File::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "choice2")
{
choice2.yfilter = yfilter;
}
if(value_path == "choice1")
{
choice1.yfilter = yfilter;
}
if(value_path == "choice3")
{
choice3.yfilter = yfilter;
}
}
bool Exception::File::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "choice2" || name == "choice1" || name == "choice3")
return true;
return false;
}
}
}
| 24.508403 | 161 | 0.688496 | CiscoDevNet |
6bb89fe1087399aa9b253295809e2906d107c237 | 4,558 | cpp | C++ | src/appleseed/renderer/modeling/project/regexrenderlayerrule.cpp | istemi-bahceci/appleseed | 2db1041acb04bad4742cf7826ce019f0e623fe35 | [
"MIT"
] | 1 | 2021-04-02T10:51:57.000Z | 2021-04-02T10:51:57.000Z | src/appleseed/renderer/modeling/project/regexrenderlayerrule.cpp | istemi-bahceci/appleseed | 2db1041acb04bad4742cf7826ce019f0e623fe35 | [
"MIT"
] | null | null | null | src/appleseed/renderer/modeling/project/regexrenderlayerrule.cpp | istemi-bahceci/appleseed | 2db1041acb04bad4742cf7826ce019f0e623fe35 | [
"MIT"
] | null | null | null |
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "regexrenderlayerrule.h"
// appleseed.renderer headers.
#include "renderer/global/globallogger.h"
#include "renderer/modeling/project/renderlayerrule.h"
#include "renderer/utility/messagecontext.h"
#include "renderer/utility/paramarray.h"
// appleseed.foundation headers.
#include "foundation/utility/api/apistring.h"
#include "foundation/utility/api/specializedapiarrays.h"
#include "foundation/utility/containers/dictionary.h"
#include "foundation/utility/filter/regexfilter.h"
// Standard headers.
#include <string>
using namespace foundation;
using namespace std;
namespace renderer
{
namespace
{
//
// Render layer rule based on regular expressions.
//
const char* Model = "regex";
class RegExRenderLayerRule
: public RenderLayerRule
{
public:
RegExRenderLayerRule(
const char* name,
const ParamArray& params)
: RenderLayerRule(name, params)
{
const EntityDefMessageContext context("render layer rule", this);
const string pattern = params.get_required<string>("pattern", "", context);
m_filter.set_pattern(pattern.c_str());
if (!m_filter.is_valid())
RENDERER_LOG_ERROR("%s: invalid regular expression pattern: %s", context.get(), pattern.c_str());
}
virtual void release() APPLESEED_OVERRIDE
{
delete this;
}
virtual const char* get_model() const APPLESEED_OVERRIDE
{
return Model;
}
virtual bool applies(const Entity& entity) const APPLESEED_OVERRIDE
{
return
m_filter.is_valid()
? m_filter.accepts(entity.get_path().c_str())
: false;
}
private:
RegExFilter m_filter;
};
}
//
// RegExRenderLayerRuleFactory class implementation.
//
const char* RegExRenderLayerRuleFactory::get_model() const
{
return Model;
}
Dictionary RegExRenderLayerRuleFactory::get_model_metadata() const
{
return
Dictionary()
.insert("name", Model)
.insert("label", "Regular Expression")
.insert("default_model", "true");
}
DictionaryArray RegExRenderLayerRuleFactory::get_input_metadata() const
{
DictionaryArray metadata = RenderLayerRuleFactory::get_input_metadata();
metadata.push_back(
Dictionary()
.insert("name", "pattern")
.insert("label", "Pattern")
.insert("type", "text")
.insert("use", "required"));
return metadata;
}
auto_release_ptr<RenderLayerRule> RegExRenderLayerRuleFactory::create(
const char* name,
const ParamArray& params) const
{
return
auto_release_ptr<RenderLayerRule>(
new RegExRenderLayerRule(name, params));
}
auto_release_ptr<RenderLayerRule> RegExRenderLayerRuleFactory::static_create(
const char* name,
const ParamArray& params)
{
return
auto_release_ptr<RenderLayerRule>(
new RegExRenderLayerRule(name, params));
}
} // namespace renderer
| 29.217949 | 113 | 0.679026 | istemi-bahceci |
6bb8d53f360caca99c16992039093cd54edb784f | 7,103 | cpp | C++ | object_analytics_nodelet/src/segmenter/organized_multi_plane_segmenter.cpp | Zippen-Huang/ros_object_analytics | eb0208edbb6da67e5d5c4092fd2964a2c8d9838e | [
"Apache-2.0"
] | 186 | 2017-11-30T14:08:54.000Z | 2022-02-24T19:17:20.000Z | object_analytics_nodelet/src/segmenter/organized_multi_plane_segmenter.cpp | Zippen-Huang/ros_object_analytics | eb0208edbb6da67e5d5c4092fd2964a2c8d9838e | [
"Apache-2.0"
] | 38 | 2017-12-06T12:03:22.000Z | 2021-10-18T13:38:10.000Z | object_analytics_nodelet/src/segmenter/organized_multi_plane_segmenter.cpp | Zippen-Huang/ros_object_analytics | eb0208edbb6da67e5d5c4092fd2964a2c8d9838e | [
"Apache-2.0"
] | 58 | 2017-11-30T07:37:35.000Z | 2022-02-04T20:45:59.000Z | /*
* Copyright (c) 2017 Intel Corporation
*
* 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 <vector>
#include <pcl/common/time.h>
#include <pcl/filters/impl/conditional_removal.hpp>
#include <pcl/filters/impl/filter.hpp>
#include <pcl/search/impl/organized.hpp>
#include <pcl/segmentation/impl/organized_connected_component_segmentation.hpp>
#include "object_analytics_nodelet/const.h"
#include "object_analytics_nodelet/segmenter/organized_multi_plane_segmenter.h"
namespace object_analytics_nodelet
{
namespace segmenter
{
using pcl::Label;
using pcl::Normal;
using pcl::PointCloud;
using pcl::PointIndices;
using pcl::PlanarRegion;
OrganizedMultiPlaneSegmenter::OrganizedMultiPlaneSegmenter(ros::NodeHandle& nh)
: plane_comparator_(new pcl::PlaneCoefficientComparator<PointT, Normal>)
, euclidean_comparator_(new pcl::EuclideanPlaneCoefficientComparator<PointT, Normal>)
, rgb_comparator_(new pcl::RGBPlaneCoefficientComparator<PointT, Normal>)
, edge_aware_comparator_(new pcl::EdgeAwarePlaneComparator<PointT, Normal>)
, euclidean_cluster_comparator_(new pcl::EuclideanClusterComparator<PointT, Normal, Label>)
, conf_(nh, "OrganizedMultiPlaneSegmenter")
{
}
void OrganizedMultiPlaneSegmenter::segment(const PointCloudT::ConstPtr& cloud, PointCloudT::Ptr& cloud_segment,
std::vector<PointIndices>& cluster_indices)
{
double start = pcl::getTime();
ROS_DEBUG_STREAM("Total original point size = " << cloud->size());
pcl::copyPointCloud(*cloud, *cloud_segment); // cloud_segment is same as cloud for this algorithm
applyConfig();
PointCloud<Normal>::Ptr normal_cloud(new PointCloud<Normal>);
estimateNormal(cloud, normal_cloud);
std::vector<PlanarRegion<PointT>, Eigen::aligned_allocator<PlanarRegion<PointT>>> regions;
PointCloud<Label>::Ptr labels(new PointCloud<Label>);
std::vector<PointIndices> label_indices;
segmentPlanes(cloud, normal_cloud, regions, labels, label_indices);
segmentObjects(cloud, regions, labels, label_indices, cluster_indices);
double end = pcl::getTime();
ROS_DEBUG_STREAM("Segmentation : " << double(end - start));
}
void OrganizedMultiPlaneSegmenter::estimateNormal(const PointCloudT::ConstPtr& cloud,
PointCloud<Normal>::Ptr& normal_cloud)
{
double start = pcl::getTime();
normal_estimation_.setInputCloud(cloud);
normal_estimation_.compute(*normal_cloud);
float* distance_map = normal_estimation_.getDistanceMap();
boost::shared_ptr<pcl::EdgeAwarePlaneComparator<PointT, Normal>> eapc =
boost::dynamic_pointer_cast<pcl::EdgeAwarePlaneComparator<PointT, Normal>>(edge_aware_comparator_);
eapc->setDistanceMap(distance_map);
eapc->setDistanceThreshold(0.01f, false);
double end = pcl::getTime();
ROS_DEBUG_STREAM("Calc normal : " << double(end - start));
}
void OrganizedMultiPlaneSegmenter::segmentPlanes(
const PointCloudT::ConstPtr& cloud, const pcl::PointCloud<Normal>::Ptr& normal_cloud,
std::vector<PlanarRegion<PointT>, Eigen::aligned_allocator<PlanarRegion<PointT>>>& regions,
pcl::PointCloud<Label>::Ptr labels, std::vector<PointIndices>& label_indices)
{
double start = pcl::getTime();
std::vector<pcl::ModelCoefficients> model_coefficients;
std::vector<PointIndices> inlier_indices;
std::vector<PointIndices> boundary_indices;
plane_segmentation_.setInputNormals(normal_cloud);
plane_segmentation_.setInputCloud(cloud);
plane_segmentation_.segmentAndRefine(regions, model_coefficients, inlier_indices, labels, label_indices,
boundary_indices);
double end = pcl::getTime();
ROS_DEBUG_STREAM("Plane detection : " << double(end - start));
}
void OrganizedMultiPlaneSegmenter::segmentObjects(
const PointCloudT::ConstPtr& cloud,
std::vector<PlanarRegion<PointT>, Eigen::aligned_allocator<PlanarRegion<PointT>>>& regions,
PointCloud<Label>::Ptr labels, std::vector<PointIndices>& label_indices, std::vector<PointIndices>& cluster_indices)
{
double start = pcl::getTime();
std::vector<bool> plane_labels;
plane_labels.resize(label_indices.size(), false);
for (size_t i = 0; i < label_indices.size(); i++)
{
if (label_indices[i].indices.size() > plane_minimum_points_)
{
plane_labels[i] = true;
}
}
euclidean_cluster_comparator_->setInputCloud(cloud);
euclidean_cluster_comparator_->setLabels(labels);
euclidean_cluster_comparator_->setExcludeLabels(plane_labels);
PointCloud<Label> euclidean_labels;
pcl::OrganizedConnectedComponentSegmentation<PointT, Label> euclidean_segmentation(euclidean_cluster_comparator_);
euclidean_segmentation.setInputCloud(cloud);
euclidean_segmentation.segment(euclidean_labels, cluster_indices);
auto func = [this](PointIndices indices) { return indices.indices.size() < this->object_minimum_points_; };
cluster_indices.erase(std::remove_if(cluster_indices.begin(), cluster_indices.end(), func), cluster_indices.end());
double end = pcl::getTime();
ROS_DEBUG_STREAM("Cluster : " << double(end - start));
}
void OrganizedMultiPlaneSegmenter::applyConfig()
{
OrganizedMultiPlaneSegmentationConfig conf = conf_.getConfig();
plane_minimum_points_ = static_cast<size_t>(conf.plane_minimum_points);
object_minimum_points_ = static_cast<size_t>(conf.object_minimum_points);
normal_estimation_.setNormalEstimationMethod(normal_estimation_.SIMPLE_3D_GRADIENT);
normal_estimation_.setNormalEstimationMethod(normal_estimation_.COVARIANCE_MATRIX);
normal_estimation_.setMaxDepthChangeFactor(conf.normal_max_depth_change);
normal_estimation_.setNormalSmoothingSize(conf.normal_smooth_size);
euclidean_cluster_comparator_->setDistanceThreshold(conf.euclidean_distance_threshold, false);
plane_segmentation_.setMinInliers(conf.min_plane_inliers);
plane_segmentation_.setAngularThreshold(pcl::deg2rad(conf.normal_angle_threshold));
plane_segmentation_.setDistanceThreshold(conf.normal_distance_threshold);
if (conf.comparator == kPlaneCoefficientComparator)
{
plane_segmentation_.setComparator(plane_comparator_);
}
else if (conf.comparator == kEuclideanPlaneCoefficientComparator)
{
plane_segmentation_.setComparator(euclidean_comparator_);
}
else if (conf.comparator == kRGBPlaneCoefficientComparator)
{
plane_segmentation_.setComparator(rgb_comparator_);
}
else if (conf.comparator == kEdgeAwarePlaneComaprator)
{
plane_segmentation_.setComparator(edge_aware_comparator_);
}
}
} // namespace segmenter
} // namespace object_analytics_nodelet
| 40.129944 | 120 | 0.770801 | Zippen-Huang |
6bba5c3ae4bcc603f36e8c0bdceaec11b201d83d | 1,231 | cpp | C++ | src/controllerNode.cpp | amrish1222/intelli_bot | 8bfa25296d942c9b79a828788a19ff8f0d0dac34 | [
"MIT"
] | null | null | null | src/controllerNode.cpp | amrish1222/intelli_bot | 8bfa25296d942c9b79a828788a19ff8f0d0dac34 | [
"MIT"
] | null | null | null | src/controllerNode.cpp | amrish1222/intelli_bot | 8bfa25296d942c9b79a828788a19ff8f0d0dac34 | [
"MIT"
] | 1 | 2018-12-05T01:07:40.000Z | 2018-12-05T01:07:40.000Z | #include "ros/ros.h"
#include "std_msgs/String.h"
#include "geometry_msgs/Twist.h"
#include "nav_msgs/Odometry.h"
#include "../include/Control.h"
#include "std_msgs/Empty.h"
#include <sstream>
int main(int argc, char **argv) {
ros::init(argc, argv, "intelli_bot");
ros::NodeHandle n;
Control _control;
_control.setPathPts();
ros::Subscriber sub = n.subscribe("/ground_truth/state", 1000,
&Control::navMessageReceived, &_control);
ros::Publisher takeOff_msg = n.advertise<std_msgs::Empty>("/ardrone/takeoff",
1, true);
std_msgs::Empty emptyMsg;
takeOff_msg.publish(emptyMsg);
ros::Publisher vel_pub = n.advertise<geometry_msgs::Twist>("cmd_vel", 1);
ros::Rate loop_rate(10);
int count = 0;
while (ros::ok()) {
geometry_msgs::Twist new_vel;
// get Twist msg from control class algorithm
new_vel = _control.getVelocityPose();
ROS_INFO_STREAM(
"vel_pub = " << new_vel.linear.x << "," << new_vel.linear.y << ","<< new_vel.linear.z);
// Publish the computed velocity
vel_pub.publish(new_vel);
ros::spinOnce();
loop_rate.sleep();
++count;
}
return 0;
}
| 23.226415 | 95 | 0.618197 | amrish1222 |
6bbad17aeb39418aa1dac2e26916013680bd97dd | 9,527 | cpp | C++ | src/textfile.cpp | alexezh/trv | 1dd97096ed9f60ffb64c4e44e2e309e9c5002224 | [
"MIT"
] | null | null | null | src/textfile.cpp | alexezh/trv | 1dd97096ed9f60ffb64c4e44e2e309e9c5002224 | [
"MIT"
] | 2 | 2016-11-25T19:52:09.000Z | 2017-04-15T14:49:52.000Z | src/textfile.cpp | alexezh/trv | 1dd97096ed9f60ffb64c4e44e2e309e9c5002224 | [
"MIT"
] | null | null | null | // Copyright (c) 2013 Alexandre Grigorovitch (alexezh@gmail.com).
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "stdafx.h"
#include "traceapp.h"
#include "textfile.h"
#include "log.h"
///////////////////////////////////////////////////////////////////////////////
//
CTextTraceFile::CTextTraceFile()
{
LineInfoDesc::Reset(m_Desc);
SYSTEM_INFO si;
GetSystemInfo(&si);
m_PageSize = si.dwPageSize;
}
CTextTraceFile::~CTextTraceFile()
{
}
void WINAPI CTextTraceFile::LoadThreadInit(void * pCtx)
{
CTextTraceFile * pFile = (CTextTraceFile*) pCtx;
pFile->LoadThread();
}
HRESULT CTextTraceFile::Open(LPCWSTR pszFile, CTraceFileLoadCallback * pCallback, bool bReverse)
{
HRESULT hr = S_OK;
LOG("@%p open $S", this, pszFile);
m_pCallback = pCallback;
m_bReverse = bReverse;
m_hFile = CreateFile(pszFile,
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_FLAG_NO_BUFFERING,
NULL);
if (m_hFile == INVALID_HANDLE_VALUE)
{
hr = HRESULT_FROM_WIN32(GetLastError());
goto Cleanup;
}
if (!GetFileSizeEx(m_hFile, &m_FileSize))
{
hr = HRESULT_FROM_WIN32(GetLastError());
goto Cleanup;
}
Cleanup:
return hr;
}
HRESULT CTextTraceFile::Close()
{
if (m_hFile != INVALID_HANDLE_VALUE)
{
CloseHandle(m_hFile);
}
return S_OK;
}
void CTextTraceFile::Load(uint64_t nStop)
{
if (m_bLoading)
{
return;
}
if (m_bReverse)
{
ATLASSERT(false);
}
else
{
if (nStop > m_FileSize.QuadPart)
{
nStop = (QWORD) m_FileSize.QuadPart;
}
if (m_nStop > nStop)
{
return;
}
}
m_nStop = nStop;
m_bLoading = true;
QueueUserWorkItem((LPTHREAD_START_ROUTINE) LoadThreadInit, this, 0);
}
///////////////////////////////////////////////////////////////////////////////
//
void CTextTraceFile::LoadThread()
{
HRESULT hr = S_OK;
DWORD cbRead;
DWORD cbToRead;
LARGE_INTEGER liPos;
m_pCallback->OnLoadBegin();
for (;; )
{
LoadBlock * pNew = nullptr;
if (m_bReverse)
{
ATLASSERT(false);
}
else
{
DWORD cbRollover = 0;
if (m_Blocks.size() > 0)
{
LoadBlock * pEnd = m_Blocks.back();
if (pEnd->nFileStop > m_nStop)
{
break;
}
// copy end of line from previous buffer
// we have to copy page aligned block and record the start of next data
assert(pEnd->cbBuf >= pEnd->cbLastFullLineEnd);
cbRollover = pEnd->cbBuf - pEnd->cbLastFullLineEnd;
DWORD cbRolloverRounded = (cbRollover + m_PageSize - 1) & (~(m_PageSize - 1));
IFC(AllocBlock(cbRolloverRounded + m_BlockSize, &pNew));
pNew->cbFirstFullLineStart = cbRolloverRounded - cbRollover;
memcpy(pNew->pbBuf + pNew->cbFirstFullLineStart, pEnd->pbBuf + pEnd->cbLastFullLineEnd, cbRollover);
// at this point we can decommit unnecessary pages for unicode
// this will waste address space but keep memory usage low
// nFileStart is in file offset
// cbLastFullLineEnd is in buffer
pNew->nFileStart = pEnd->nFileStop;
pNew->cbWriteStart = cbRolloverRounded;
// if we are in unicode mode, trim previous block
if (m_bUnicode)
TrimBlock(pEnd);
}
else
{
IFC(AllocBlock(m_BlockSize, &pNew));
// we are going forward so start pos is null
pNew->cbWriteStart = 0;
}
pNew->nFileStop = pNew->nFileStart + m_BlockSize;
// we actually have data in the buffer, so set cbData
pNew->cbData = cbRollover;
}
liPos.QuadPart = (__int64) pNew->nFileStart;
SetFilePointerEx(m_hFile, liPos, NULL, FILE_BEGIN);
cbToRead = m_BlockSize;
if (m_bReverse)
{
ATLASSERT(false);
}
else
{
// append data after rollover string
if (!ReadFile(m_hFile, pNew->pbBuf + pNew->cbWriteStart, cbToRead, &cbRead, NULL))
{
hr = HRESULT_FROM_WIN32(GetLastError());
goto Cleanup;
}
}
pNew->cbData = cbRead + pNew->cbData;
// parse data
IFC(ParseBlock(pNew,
pNew->cbFirstFullLineStart,
pNew->cbData,
&pNew->cbDataEnd,
&pNew->cbLastFullLineEnd));
{
LockGuard guard(m_Lock);
// append block
m_Blocks.push_back(pNew);
}
m_pCallback->OnLoadBlock();
if (cbRead != m_BlockSize)
{
break;
}
}
Cleanup:
m_pCallback->OnLoadEnd(hr);
}
HRESULT CTextTraceFile::AllocBlock(DWORD cbSize, LoadBlock ** ppBlock)
{
LoadBlock * b = new LoadBlock;
b->cbBuf = cbSize;
b->pbBuf = (BYTE*) VirtualAlloc(NULL, cbSize, MEM_COMMIT, PAGE_READWRITE);
if (b->pbBuf == NULL)
{
return HRESULT_FROM_WIN32(GetLastError());
}
m_cbTotalAlloc += cbSize;
*ppBlock = b;
return S_OK;
}
void CTextTraceFile::TrimBlock(LoadBlock* pBlock)
{
if (pBlock->isTrimmed)
return;
// unmap unnecessary space
DWORD cbUsedAligned = ((pBlock->cbDataEnd) / m_PageSize + 1) * m_PageSize;
if (cbUsedAligned < pBlock->cbBuf)
{
VirtualFree(pBlock->pbBuf + cbUsedAligned, pBlock->cbBuf - cbUsedAligned, MEM_DECOMMIT);
m_cbTotalAlloc -= (pBlock->cbBuf - cbUsedAligned);
}
pBlock->isTrimmed = true;
}
HRESULT CTextTraceFile::ParseBlock(LoadBlock * pBlock, DWORD nStart, DWORD nStop, DWORD * pnStop, DWORD * pnLineEnd)
{
HRESULT hr = S_OK;
char * pszCur;
char * pszEnd;
char * pszLine = NULL;
WORD crcn = 0;
BOOL fSkipSpace = FALSE;
DWORD nVal = 0;
LockGuard guard(m_Lock);
// test unicode file
pszCur = (char*) (pBlock->pbBuf + nStart);
pszEnd = (char*) (pBlock->pbBuf + nStop);
if (pBlock->nFileStart == 0 && pBlock->cbData > 2)
{
if (pBlock->pbBuf[0] == 0xff && pBlock->pbBuf[1] == 0xfe)
{
LOG("@%p unicode mode");
m_bUnicode = true;
pszCur += 2;
}
}
if (m_bUnicode)
{
wchar_t c;
wchar_t* pszCurW = reinterpret_cast<wchar_t*>(pszCur);
wchar_t* pszEndW = reinterpret_cast<wchar_t*>(pszEnd);
wchar_t* pszLineW = reinterpret_cast<wchar_t*>(pszCur);
for (; pszCurW < pszEndW; pszCurW++)
{
c = *pszCurW;
crcn <<= 8;
crcn |= (char) c;
if (crcn == 0x0d0a)
{
// for now just drop first bytes
char* pszLine = pszCur;
for (wchar_t* p = pszLineW; p <= pszCurW; p++, pszCur++)
{
*pszCur = (char) *p;
}
// pszCur points after pszCurW so we do not need +1
m_Lines.Add(LineInfo(CStringRef(pszLine, pszCur - pszLine), m_Lines.GetSize()));
pszLineW = pszCurW + 1;
}
}
(*pnStop) = ((BYTE*) pszCur - pBlock->pbBuf);
(*pnLineEnd) = (pszLineW) ? ((BYTE*) pszLineW - pBlock->pbBuf) : ((BYTE*) pszEndW - pBlock->pbBuf);
}
else
{
pszLine = pszCur;
char c;
for (; pszCur < pszEnd; pszCur++)
{
c = *pszCur;
crcn <<= 8;
crcn |= c;
if (crcn == 0x0d0a)
{
m_Lines.Add(LineInfo(CStringRef(pszLine, pszCur - pszLine + 1), m_Lines.GetSize()));
pszLine = pszCur + 1;
}
}
(*pnStop) = nStop;
(*pnLineEnd) = (pszLine) ? ((BYTE*) pszLine - pBlock->pbBuf) : ((BYTE*) pszEnd - pBlock->pbBuf);
}
// we are parsing under lock; it is safe to adjust the size
m_LineParsed.Resize(m_Lines.GetSize());
//Cleanup:
return hr;
}
///////////////////////////////////////////////////////////////////////////////
//
const LineInfo& CTextTraceFile::GetLine(DWORD nIndex)
{
LockGuard guard(m_Lock);
if (nIndex >= m_Lines.GetSize())
{
static LineInfo line;
return line;
}
LineInfo& line = m_Lines.GetAt(nIndex);
if (!m_LineParsed.GetBit(nIndex))
{
m_LineParsed.SetBit(nIndex);
if (m_Parser == nullptr || !m_Parser->ParseLine(line.Content.psz, line.Content.cch, line))
{
// just set msg as content
line.Msg = line.Content;
}
}
return line;
}
bool CTextTraceFile::SetTraceFormat(const char * pszFormat, const char* pszSep)
{
LockGuard guard(m_Lock);
LineInfoDesc::Reset(m_Desc);
m_Parser.reset(new TraceLineParser());
try
{
std::vector<char> sep;
if (pszSep == nullptr)
{
sep.push_back('\t');
}
else
{
sep.assign(pszSep, pszSep + strlen(pszSep));
}
m_Parser->SetFormat(pszFormat, 0, sep);
}
catch (std::invalid_argument&)
{
return false;
}
// check what we captured
for (auto it = m_Parser->GetFields().begin(); it != m_Parser->GetFields().end(); ++it)
{
if (*it == TraceLineParser::FieldId::ThreadId)
{
m_Desc.Tid = true;
}
else if (*it == TraceLineParser::FieldId::Time)
{
m_Desc.Time = true;
}
else if (*it == TraceLineParser::FieldId::User1)
{
m_Desc.SetUser(0);
}
else if (*it == TraceLineParser::FieldId::User2)
{
m_Desc.SetUser(1);
}
else if (*it == TraceLineParser::FieldId::User3)
{
m_Desc.SetUser(2);
}
else if (*it == TraceLineParser::FieldId::User4)
{
m_Desc.SetUser(3);
}
}
// reset all parsed bits
m_LineParsed.Fill(false);
return true;
}
| 21.554299 | 116 | 0.651622 | alexezh |
6bbb18d6f4cb21042af6175e1c7804f23212f82c | 11,366 | cpp | C++ | private/tst/debugFascadeTest/src/SmartXDebugFacadeTest.cpp | juimonen/SmartXbar | 033f521a5dba5bce5e097df9c98af5b2cc2636dd | [
"BSD-3-Clause"
] | 5 | 2018-11-05T07:37:58.000Z | 2022-03-04T06:40:09.000Z | private/tst/debugFascadeTest/src/SmartXDebugFacadeTest.cpp | juimonen/SmartXbar | 033f521a5dba5bce5e097df9c98af5b2cc2636dd | [
"BSD-3-Clause"
] | null | null | null | private/tst/debugFascadeTest/src/SmartXDebugFacadeTest.cpp | juimonen/SmartXbar | 033f521a5dba5bce5e097df9c98af5b2cc2636dd | [
"BSD-3-Clause"
] | 7 | 2018-12-04T07:32:19.000Z | 2021-02-17T11:28:28.000Z | /*
* Copyright (C) 2018 Intel Corporation.All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
/*
* @file SmartXDebugFascadeTest.cpp
* @date 2017
* @brief
*/
#include <functional>
#include <gtest/gtest.h>
#include <dlt/dlt.h>
#include "boost/filesystem.hpp"
#include "audio/configparser/IasSmartXDebugFacade.hpp"
#include "audio/configparser/IasSmartXconfigParser.hpp"
#include "audio/smartx/IasProperties.hpp"
#include "rtprocessingfwx/IasPluginEngine.hpp"
#include "rtprocessingfwx/IasCmdDispatcher.hpp"
#include "SmartXDebugFacadeTest.hpp"
#include "rtprocessingfwx/IasAudioChain.hpp"
#include "rtprocessingfwx/IasGenericAudioCompConfig.hpp"
#include "gtest/gtest.h"
#include <sndfile.h>
#include <string.h>
#include <iostream>
#include "audio/testfwx/IasTestFramework.hpp"
#include "audio/testfwx/IasTestFrameworkSetup.hpp"
#include "audio/smartx/IasProperties.hpp"
#include "audio/smartx/IasIProcessing.hpp"
#include "audio/smartx/IasIDebug.hpp"
#include "model/IasAudioPin.hpp"
#include "volume/IasVolumeLoudnessCore.hpp"
#include "audio/volumex/IasVolumeCmd.hpp"
#include "mixer/IasMixerCore.hpp"
#include "audio/mixerx/IasMixerCmd.hpp"
#include "audio/smartx/IasSetupHelper.hpp"
#include <libxml/encoding.h>
#include <libxml/xmlwriter.h>
#include <libxml/parser.h>
using namespace std;
using namespace IasAudio;
namespace fs = boost::filesystem;
static const Ias::String validXmlFilesPath = "/nfs/ka/disks/ias_organisation_disk001/teams/audio/TestXmlFiles/2017-12-01/valid/";
static const auto PARSER_SUCCESS = true;
namespace IasAudio {
std::vector<Ias::String> SmartXDebugFacadeTest::getValidXmlFiles()
{
return validXmlFiles;
}
std::vector<Ias::String> SmartXDebugFacadeTest::getFileList(const std::string& path)
{
std::vector<Ias::String> files;
if (!path.empty())
{
fs::path apk_path(path);
fs::recursive_directory_iterator end;
for (fs::recursive_directory_iterator i(apk_path); i != end; ++i)
{
const fs::path cp = (*i);
files.emplace_back(cp.string());
}
}
return files;
}
void SmartXDebugFacadeTest::SetUp()
{
setenv("AUDIO_PLUGIN_DIR", "../../..", true);
validXmlFiles = getFileList(validXmlFilesPath);
}
void SmartXDebugFacadeTest::TearDown()
{
}
SmartXDebugFacadeTest::WrapperSmartX::WrapperSmartX()
{
mSmartx = IasAudio::IasSmartX::create();
if (mSmartx == nullptr)
{
EXPECT_TRUE(false) << "Create smartx error\n";
}
if (mSmartx->isAtLeast(SMARTX_API_MAJOR, SMARTX_API_MINOR, SMARTX_API_PATCH) == false)
{
std::cerr << "SmartX API version does not match" << std::endl;
IasAudio::IasSmartX::destroy(mSmartx);
EXPECT_TRUE(false);
}
}
IasSmartX* SmartXDebugFacadeTest::WrapperSmartX::getSmartX()
{
return mSmartx;
}
SmartXDebugFacadeTest::WrapperSmartX::~WrapperSmartX()
{
const IasSmartX::IasResult smres = mSmartx->stop();
EXPECT_EQ(IasSmartX::eIasOk, smres);
IasSmartX::destroy(mSmartx);
mSmartx = nullptr;
}
TEST_F(SmartXDebugFacadeTest, ValidTopologyXmlAllocationFails)
{
for(int i = 0; i < 4; i++)
{
const char* file = "/nfs/ka/disks/ias_organisation_disk001/teams/audio/TestXmlFiles/2017-12-01/valid/pipeline_sxb_topology_06.xml";
WrapperSmartX wrapperSmartX{};
auto smartx = wrapperSmartX.getSmartX();
EXPECT_EQ(parseConfig(smartx, file), PARSER_SUCCESS) << "File : " << file;
EXPECT_NE(wrapperSmartX.getSmartX(), nullptr);
IasSmartXDebugFacade debugFascade {smartx};
Ias::String topology;
const auto result = debugFascade.getSmartxTopology(topology);
EXPECT_EQ(IasSmartXDebugFacade::IasResult::eIasFailed, result);
}
}
TEST_F(SmartXDebugFacadeTest, ValidTopology)
{
for(const auto& file : getValidXmlFiles())
{
WrapperSmartX wrapperSmartX{};
auto smartx = wrapperSmartX.getSmartX();
EXPECT_EQ(parseConfig(smartx, file.c_str()), PARSER_SUCCESS) << "File : " << file;
EXPECT_NE(wrapperSmartX.getSmartX(), nullptr);
IasSmartXDebugFacade debugFascade {smartx};
Ias::String topology;
const auto result = debugFascade.getSmartxTopology(topology);
EXPECT_EQ(IasSmartXDebugFacade::IasResult::eIasOk, result);
EXPECT_NE("",topology);
}
}
TEST_F(SmartXDebugFacadeTest, getVersion)
{
WrapperSmartX wrapperSmartX{};
auto smartx = wrapperSmartX.getSmartX();
auto file = getValidXmlFiles()[0].c_str();
EXPECT_EQ(parseConfig(smartx, file), PARSER_SUCCESS) << "File : " << file;
EXPECT_NE(wrapperSmartX.getSmartX(), nullptr);
IasSmartXDebugFacade debugFascade {smartx};
const auto result = debugFascade.getVersion();
EXPECT_NE("", result);
}
TEST_F(SmartXDebugFacadeTest, setParameterFailed)
{
WrapperSmartX wrapperSmartX{};
auto smartx = wrapperSmartX.getSmartX();
auto file = getValidXmlFiles()[0].c_str();
EXPECT_EQ(parseConfig(smartx, file), PARSER_SUCCESS) << "File : " << file;
EXPECT_NE(wrapperSmartX.getSmartX(), nullptr);
IasSmartXDebugFacade debugFascade {smartx};
IasProperties properties;
const auto result = debugFascade.setParameters("invalid", properties);
EXPECT_EQ(IasSmartXDebugFacade::IasResult::eIasFailed, result);
}
TEST_F(SmartXDebugFacadeTest, getParameterFailed)
{
WrapperSmartX wrapperSmartX{};
auto smartx = wrapperSmartX.getSmartX();
auto file = getValidXmlFiles()[0].c_str();
EXPECT_EQ(parseConfig(smartx, file), PARSER_SUCCESS) << "File : " << file;
EXPECT_NE(wrapperSmartX.getSmartX(), nullptr);
IasSmartXDebugFacade debugFascade {smartx};
IasProperties properties;
const auto result = debugFascade.getParameters("invalid", properties);
EXPECT_EQ(IasSmartXDebugFacade::IasResult::eIasFailed, result);
}
TEST_F(SmartXDebugFacadeTest, setParameterOk)
{
WrapperSmartX wrapperSmartX{};
auto smartx = wrapperSmartX.getSmartX();
EXPECT_NE(wrapperSmartX.getSmartX(), nullptr);
auto setup = smartx->setup();
IasSmartXDebugFacade debugFascade {smartx};
IasRoutingZonePtr rzn = nullptr;
// create sink device
IasAudioDeviceParams sinkParam;
sinkParam.clockType = IasAudio::eIasClockProvided;
sinkParam.dataFormat = IasAudio::eIasFormatInt16;
sinkParam.name = "mono";
sinkParam.numChannels = 1;
sinkParam.numPeriods = 4;
sinkParam.periodSize = 192;
sinkParam.samplerate = 48000;
IasAudioSinkDevicePtr monoSink;
auto setupRes = IasSetupHelper::createAudioSinkDevice(setup, sinkParam, 0, &monoSink,&rzn);
EXPECT_EQ(setupRes, IasISetup::eIasOk) << "Error creating " << sinkParam.name << ": " << toString(setupRes) << "\n";
// Create the pipeline
IasPipelineParams pipelineParams;
pipelineParams.name ="ExamplePipeline";
pipelineParams.samplerate = sinkParam.samplerate;
pipelineParams.periodSize = sinkParam.periodSize;
IasPipelinePtr pipeline = nullptr;
IasISetup::IasResult res = setup->createPipeline(pipelineParams, &pipeline);
EXPECT_EQ(res, IasISetup::eIasOk) << "Error creating example pipeline (please review DLT output for details)\n";
// create pin
IasAudioPinPtr pipelineInputMonoPin = nullptr;
IasAudioPinPtr monoPin = nullptr;
IasAudioPinParams pipelineInputMonoParams;
pipelineInputMonoParams.name = "pipeInputMono";
pipelineInputMonoParams.numChannels = 1;
res = setup->createAudioPin(pipelineInputMonoParams, &pipelineInputMonoPin);
EXPECT_EQ(res, IasISetup::eIasOk) << "Error creating pipeline input mono pin\n";
/// create volume module
IasProcessingModuleParams volumeModuleParams;
volumeModuleParams.typeName = "ias.volume";
volumeModuleParams.instanceName = "VolumeLoudness";
IasProcessingModulePtr volume = nullptr;
IasAudioPinPtr volumeMonoPin = nullptr;
IasAudioPinParams volumeMonoPinParams;
volumeMonoPinParams.name = "Volume_InOutMonoPin";
volumeMonoPinParams.numChannels = 1;
res = setup->createProcessingModule(volumeModuleParams, &volume);
EXPECT_EQ(res, IasISetup::eIasOk) << "Error creating volume module\n";
//// create volume loundness
IasProperties volumeProperties;
volumeProperties.set<Ias::Int32>("numFilterBands",1);
IasStringVector activePins;
activePins.push_back("Volume_InOutMonoPin");
volumeProperties.set("activePinsForBand.0", activePins);
Ias::Int32 tempVol = 0;
Ias::Int32 tempGain = 0;
IasInt32Vector ldGains;
IasInt32Vector ldVolumes;
for(Ias::UInt32 i=0; i< 8; i++)
{
ldVolumes.push_back(tempVol);
ldGains.push_back(tempGain);
tempVol-= 60;
tempGain+= 30;
}
volumeProperties.set("ld.volumes.0", ldVolumes);
volumeProperties.set("ld.gains.0", ldGains);
volumeProperties.set("ld.volumes.1", ldVolumes);
volumeProperties.set("ld.gains.1", ldGains);
volumeProperties.set("ld.volumes.2", ldVolumes);
volumeProperties.set("ld.gains.2", ldGains);
IasInt32Vector freqOrderType;
IasFloat32Vector gainQual;
freqOrderType.resize(3);
gainQual.resize(2);
freqOrderType[0] = 100;
freqOrderType[1] = 2;
freqOrderType[2] = eIasFilterTypeLowShelving;
gainQual[0] = 1.0f; // gain
gainQual[1] = 2.0f; // quality
volumeProperties.set("ld.freq_order_type.0", freqOrderType);
volumeProperties.set("ld.gain_quality.0", gainQual);
freqOrderType[0] = 8000;
freqOrderType[1] = 2;
freqOrderType[2] = eIasFilterTypeHighShelving;
gainQual[0] = 1.0f; // gain
gainQual[1] = 2.0f; // quality
volumeProperties.set("ld.freq_order_type.1", freqOrderType);
volumeProperties.set("ld.gain_quality.1", gainQual);
setup->setProperties(volume,volumeProperties);
res = setup->addProcessingModule(pipeline,volume);
EXPECT_EQ(res, IasISetup::eIasOk) << "Error adding volume module to pipeline\n";
res = setup->createAudioPin(volumeMonoPinParams,&volumeMonoPin);
EXPECT_EQ(res, IasISetup::eIasOk) << "Error creating volume mono pin\n";
res = setup->addAudioInOutPin(volume, volumeMonoPin);
EXPECT_EQ(res, IasISetup::eIasOk) << "Error adding volume mono pin\n";
res = setup->addAudioInputPin(pipeline,pipelineInputMonoPin);
EXPECT_EQ(res, IasISetup::eIasOk) << "Error adding pipeline input mono pin\n";
res = setup->link(pipelineInputMonoPin, volumeMonoPin, eIasAudioPinLinkTypeImmediate);
EXPECT_EQ(res, IasISetup::eIasOk) << "Error linking pipe input to mono volume mono input\n";
res = setup->initPipelineAudioChain(pipeline);
EXPECT_EQ(res, IasISetup::eIasOk) << "Error init pipeline chain - Please check DLT output for additional info\n";
res = setup->addPipeline(rzn, pipeline);
EXPECT_EQ(res, IasISetup::eIasOk) << "Error adding pipeline to zone\n";
IasProperties volCmdProperties;
volCmdProperties.set("cmd",static_cast<Ias::Int32>(IasAudio::IasVolume::eIasSetVolume));
volCmdProperties.set<Ias::String>("pin","Volume_InOutMonoPin");
volCmdProperties.set("volume",0);
IasAudio::IasInt32Vector ramp;
ramp.push_back(100);
ramp.push_back(0);
volCmdProperties.set("ramp",ramp);
Ias::Int32 minVol = 2;
Ias::Int32 maxVol = 10;
volCmdProperties.set<Ias::Int32>("cmd", 201);
volCmdProperties.set("MinVol", minVol);
volCmdProperties.set("MaxVol", maxVol);
IasProperties returnProps;
auto result = debugFascade.setParameters("VolumeLoudness", volCmdProperties);
EXPECT_EQ(IasSmartXDebugFacade::IasResult::eIasOk, result);
IasProperties cmdReturnProperties;
cmdReturnProperties.set<Ias::Int32>("cmd", 200);
result = debugFascade.getParameters("VolumeLoudness", cmdReturnProperties);
EXPECT_EQ(IasSmartXDebugFacade::IasResult::eIasOk, result);
}
} /* namespace IasAudio */
| 32.381766 | 135 | 0.747668 | juimonen |
6bbd9a23b1dbf317a5fa62b99f3f5118ecf642d0 | 3,087 | cpp | C++ | samples/roulette/wheel.cpp | sarvex/wallaroo | 6a1fa4241b982b5901df3137d2db4ca0c653565a | [
"BSL-1.0"
] | 3 | 2016-05-10T08:21:21.000Z | 2021-05-03T12:38:09.000Z | samples/roulette/wheel.cpp | sarvex/wallaroo | 6a1fa4241b982b5901df3137d2db4ca0c653565a | [
"BSL-1.0"
] | null | null | null | samples/roulette/wheel.cpp | sarvex/wallaroo | 6a1fa4241b982b5901df3137d2db4ca0c653565a | [
"BSL-1.0"
] | 2 | 2015-09-08T13:25:28.000Z | 2016-04-06T12:29:37.000Z | /*******************************************************************************
* wallaroo - A library for configurable creation and wiring of C++ classes.
* Copyright (C) 2012 Daniele Pallastrelli
*
* This file is part of wallaroo.
* For more information, see http://wallaroo.googlecode.com/
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
******************************************************************************/
#include <cstdlib>
#include <ctime>
#include "wheel.h"
WALLAROO_REGISTER( Wheel );
Wheel::Wheel()
{
bins.push_back( _0 );
bins.push_back( _1 );
bins.push_back( _2 );
bins.push_back( _3 );
bins.push_back( _4 );
bins.push_back( _5 );
bins.push_back( _6 );
bins.push_back( _7 );
bins.push_back( _8 );
bins.push_back( _9 );
bins.push_back( _10 );
bins.push_back( _11 );
bins.push_back( _12 );
bins.push_back( _13 );
bins.push_back( _14 );
bins.push_back( _15 );
bins.push_back( _16 );
bins.push_back( _17 );
bins.push_back( _18 );
bins.push_back( _19 );
bins.push_back( _20 );
bins.push_back( _21 );
bins.push_back( _22 );
bins.push_back( _23 );
bins.push_back( _24 );
bins.push_back( _25 );
bins.push_back( _26 );
bins.push_back( _27 );
bins.push_back( _28 );
bins.push_back( _29 );
bins.push_back( _30 );
bins.push_back( _31 );
bins.push_back( _32 );
bins.push_back( _33 );
bins.push_back( _34 );
bins.push_back( _35 );
bins.push_back( _36 );
bins.push_back( _00 );
srand( static_cast< unsigned int >( time( NULL ) ) );
}
Wheel::~Wheel()
{
}
Bin Wheel::Spin()
{
std::size_t index = rand() % ( bins.size() );
return bins[ index ];
}
| 33.554348 | 80 | 0.650794 | sarvex |
6bbe9daba875ff05d39bdab9508820e0a4c12542 | 9,837 | cpp | C++ | Modules/Core/test/mitkPropertyPersistenceTest.cpp | samsmu/MITK | c93dce6dc38d8f4c961de4440e4dd113b9841c8c | [
"BSD-3-Clause"
] | 5 | 2015-02-05T10:58:41.000Z | 2019-04-17T15:04:07.000Z | Modules/Core/test/mitkPropertyPersistenceTest.cpp | kometa-dev/MITK | 984b5f7ac8ea614e80f303381ef1fc77d8ca4c3d | [
"BSD-3-Clause"
] | 141 | 2015-03-03T06:52:01.000Z | 2020-12-10T07:28:14.000Z | Modules/Core/test/mitkPropertyPersistenceTest.cpp | kometa-dev/MITK | 984b5f7ac8ea614e80f303381ef1fc77d8ca4c3d | [
"BSD-3-Clause"
] | 4 | 2015-02-19T06:48:13.000Z | 2020-06-19T16:20:25.000Z | /*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkPropertyPersistence.h"
#include "mitkTestFixture.h"
#include "mitkTestingMacros.h"
#include "mitkStringProperty.h"
#include "mitkIOMimeTypes.h"
#include <mitkNumericConstants.h>
#include <mitkEqual.h>
#include <algorithm>
#include <limits>
class mitkPropertyPersistenceTestSuite : public mitk::TestFixture
{
CPPUNIT_TEST_SUITE(mitkPropertyPersistenceTestSuite);
MITK_TEST(AddInfo);
MITK_TEST(GetInfos);
MITK_TEST(GetInfo);
MITK_TEST(GetInfosByKey);
MITK_TEST(HasInfos);
MITK_TEST(RemoveAllInfos);
MITK_TEST(RemoveInfos);
MITK_TEST(RemoveInfos_withMime);
CPPUNIT_TEST_SUITE_END();
private:
mitk::PropertyPersistenceInfo::Pointer info1;
mitk::PropertyPersistenceInfo::Pointer info2;
mitk::PropertyPersistenceInfo::Pointer info3;
mitk::PropertyPersistenceInfo::Pointer info4;
mitk::PropertyPersistenceInfo::Pointer info5;
mitk::PropertyPersistenceInfo::Pointer info6;
std::string prop1;
std::string prop2;
std::string prop3;
std::string prop4;
std::string prop5;
std::string prop6;
mitk::IPropertyPersistence* service;
static bool checkExistance(const mitk::PropertyPersistence::InfoMapType& infos, const std::string& name, const mitk::PropertyPersistenceInfo* info)
{
auto infoRange = infos.equal_range(name);
auto predicate = [info](const std::pair<const std::string, mitk::PropertyPersistenceInfo::Pointer>& x){return infosAreEqual(info, x.second); };
auto finding = std::find_if(infoRange.first, infoRange.second, predicate);
bool result = finding != infoRange.second;
return result;
}
static bool infosAreEqual(const mitk::PropertyPersistenceInfo* ref, const mitk::PropertyPersistenceInfo* info)
{
bool result = true;
if (!info || !ref)
{
return false;
}
result = result && ref->GetKey() == info->GetKey();
result = result && ref->GetMimeTypeName() == info->GetMimeTypeName();
return result;
}
public:
void setUp() override
{
service = mitk::CreateTestInstancePropertyPersistence();
info1 = mitk::PropertyPersistenceInfo::New("key1");
info2 = mitk::PropertyPersistenceInfo::New("key2", "mime2");
info3 = mitk::PropertyPersistenceInfo::New("key3", "mime3");
info4 = mitk::PropertyPersistenceInfo::New("key2", "mime2");
info5 = mitk::PropertyPersistenceInfo::New("key5", "mime5");
prop1 = "prop1";
prop2 = "prop1";
prop3 = "prop1";
prop4 = "prop4";
prop5 = "prop5";
service->AddInfo(prop1, info1, false);
service->AddInfo(prop2, info2, false);
service->AddInfo(prop3, info3, false);
service->AddInfo(prop4, info4, false);
service->AddInfo(prop5, info5, false);
}
void tearDown() override
{
delete service;
}
void AddInfo()
{
mitk::PropertyPersistenceInfo::Pointer info2_new = mitk::PropertyPersistenceInfo::New("newKey", "otherMime");
mitk::PropertyPersistenceInfo::Pointer info2_otherKey = mitk::PropertyPersistenceInfo::New("otherKey", "mime2");
CPPUNIT_ASSERT_MESSAGE("Testing addinfo of already existing info (no overwrite) -> no adding", !service->AddInfo(prop2, info2_otherKey, false));
CPPUNIT_ASSERT_MESSAGE("Testing addinfo of already existing info (no overwrite) -> no adding -> key should not be changed.", service->GetInfo(prop2, "mime2", false)->GetKey() == "key2");
CPPUNIT_ASSERT_MESSAGE("Testing addinfo of already existing info (overwrite) -> adding", service->AddInfo(prop2, info2_otherKey, true));
CPPUNIT_ASSERT_MESSAGE("Testing addinfo of already existing info (no overwrite) -> adding -> key should be changed.", service->GetInfo(prop2, "mime2", false)->GetKey() == "otherKey");
CPPUNIT_ASSERT_MESSAGE("Testing addinfo of info (other mime type; no overwrite) -> adding", service->AddInfo(prop2, info2_new, false));
CPPUNIT_ASSERT_MESSAGE("Testing addinfo of info (other mime type; no overwrite) -> adding -> info exists.", service->GetInfo(prop2, "otherMime", false).IsNotNull());
CPPUNIT_ASSERT_MESSAGE("Testing addinfo of info (new prop name; no overwrite) -> adding", service->AddInfo("newProp", info2_new, false));
CPPUNIT_ASSERT_MESSAGE("Testing addinfo of info (new prop name; no overwrite) -> adding ->info exists.", service->GetInfo("newProp", "otherMime", false).IsNotNull());
}
void GetInfos()
{
mitk::PropertyPersistence::InfoMapType infos = service->GetInfos(prop1);
CPPUNIT_ASSERT(infos.size() == 3);
CPPUNIT_ASSERT_MESSAGE("Check expected element 1.", checkExistance(infos, prop1, info1));
CPPUNIT_ASSERT_MESSAGE("Check expected element 1.", checkExistance(infos, prop2, info2));
CPPUNIT_ASSERT_MESSAGE("Check expected element 1.", checkExistance(infos, prop3, info3));
infos = service->GetInfos(prop4);
CPPUNIT_ASSERT(infos.size() == 1);
CPPUNIT_ASSERT_MESSAGE("Check expected element 1.", checkExistance(infos, prop4, info4));
infos = service->GetInfos("unkown");
CPPUNIT_ASSERT_MESSAGE("Check size of result for unkown prop.", infos.empty());
}
void GetInfosByKey()
{
mitk::PropertyPersistence::InfoMapType infos = service->GetInfosByKey("key2");
CPPUNIT_ASSERT(infos.size() == 2);
CPPUNIT_ASSERT_MESSAGE("Check expected element 1.", checkExistance(infos, prop2, info2));
CPPUNIT_ASSERT_MESSAGE("Check expected element 2.", checkExistance(infos, prop4, info4));
infos = service->GetInfosByKey("key5");
CPPUNIT_ASSERT(infos.size() == 1);
CPPUNIT_ASSERT_MESSAGE("Check expected element 1.", checkExistance(infos, prop5, info5));
infos = service->GetInfosByKey("unkownkey");
CPPUNIT_ASSERT_MESSAGE("Check size of result for unkown key.", infos.empty());
}
void GetInfo()
{
mitk::PropertyPersistenceInfo::Pointer foundInfo = service->GetInfo(prop1, "mime2", false);
CPPUNIT_ASSERT_MESSAGE("Check GetInfo (existing element, no wildcard allowed, wildcard exists).", infosAreEqual(info2, foundInfo));
foundInfo = service->GetInfo(prop1, "mime2", true);
CPPUNIT_ASSERT_MESSAGE("Check GetInfo (existing element, wildcard allowed, wildcard exists).", infosAreEqual(info2, foundInfo));
foundInfo = service->GetInfo(prop1, "unknownmime", false);
CPPUNIT_ASSERT_MESSAGE("Check GetInfo (inexisting element, no wildcard allowed, wildcard exists).", foundInfo.IsNull());
foundInfo = service->GetInfo(prop1, "unknownmime", true);
CPPUNIT_ASSERT_MESSAGE("Check GetInfo (inexisting element, wildcard allowed, wildcard exists).", infosAreEqual(info1, foundInfo));
foundInfo = service->GetInfo(prop4, "unknownmime", false);
CPPUNIT_ASSERT_MESSAGE("Check GetInfo (inexisting element, no wildcard allowed).", foundInfo.IsNull());
foundInfo = service->GetInfo(prop4, "unknownmime", true);
CPPUNIT_ASSERT_MESSAGE("Check GetInfo (inexisting element, wildcard allowed).", foundInfo.IsNull());
}
void HasInfos()
{
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop1)", service->HasInfos(prop1));
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop4)", service->HasInfos(prop4));
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (unkown prop)", !service->HasInfos("unkownProp"));
}
void RemoveAllInfos()
{
CPPUNIT_ASSERT_NO_THROW(service->RemoveAllInfos());
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop1)", !service->HasInfos(prop1));
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop4)", !service->HasInfos(prop4));
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop5)", !service->HasInfos(prop5));
}
void RemoveInfos()
{
CPPUNIT_ASSERT_NO_THROW(service->RemoveInfos(prop1));
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop1)", !service->HasInfos(prop1));
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop4)", service->HasInfos(prop4));
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop5)", service->HasInfos(prop5));
CPPUNIT_ASSERT_NO_THROW(service->RemoveInfos(prop4));
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop4)", !service->HasInfos(prop4));
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop5)", service->HasInfos(prop5));
CPPUNIT_ASSERT_NO_THROW(service->RemoveInfos(prop5));
CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop5)", !service->HasInfos(prop5));
CPPUNIT_ASSERT_NO_THROW(service->RemoveInfos("unknown_prop"));
}
void RemoveInfos_withMime()
{
CPPUNIT_ASSERT_NO_THROW(service->RemoveInfos(prop1, "mime2"));
CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos if info was removed",service->GetInfo(prop1, "mime2", false).IsNull());
CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos, if other info of same property name still exists", service->GetInfo(prop1, "mime3", false).IsNotNull());
CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos, if other info of other property name but same mime still exists", service->GetInfo(prop4, "mime2", false).IsNotNull());
CPPUNIT_ASSERT_NO_THROW(service->RemoveInfos(prop5, "wrongMime"));
CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos on prop 5 with wrong mime", service->HasInfos(prop5));
CPPUNIT_ASSERT_NO_THROW(service->RemoveInfos(prop5, "mime5"));
CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos on prop 5", !service->HasInfos(prop5));
CPPUNIT_ASSERT_NO_THROW(service->RemoveInfos("unkown_prop", "mime2"));
CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos, if unkown property name but exting mime was used", service->HasInfos(prop4));
}
};
MITK_TEST_SUITE_REGISTRATION(mitkPropertyPersistence)
| 41.506329 | 190 | 0.723391 | samsmu |
6bbf6df0693d77d43c19578f830f171975dfd6d4 | 17,009 | cpp | C++ | settingsHelper/SettingsHelperLib/Payload.cpp | stegru/windows | 6e113cb192fe8360a697657d0221c8b4e771e506 | [
"BSD-3-Clause"
] | 12 | 2015-06-03T18:30:06.000Z | 2021-12-07T12:22:25.000Z | settingsHelper/SettingsHelperLib/Payload.cpp | GPII/windows | d5a5a66059c308729ca6f8099e06819f77fdddb9 | [
"BSD-3-Clause"
] | 271 | 2015-01-28T13:24:59.000Z | 2020-11-23T13:46:43.000Z | settingsHelper/SettingsHelperLib/Payload.cpp | stegru/windows | 6e113cb192fe8360a697657d0221c8b4e771e506 | [
"BSD-3-Clause"
] | 31 | 2015-04-16T20:09:12.000Z | 2022-01-19T14:29:05.000Z | /**
* Datatypes representing payload and functions.
*
* Copyright 2019 Raising the Floor - US
*
* Licensed under the New BSD license. You may not use this file except in
* compliance with this License.
*
* You may obtain a copy of the License at
* https://github.com/GPII/universal/blob/master/LICENSE.txt
*/
#include "stdafx.h"
#include "Payload.h"
#include "IPropertyValueUtils.h"
#include <windows.foundation.h>
#include <windows.foundation.collections.h>
#include <windows.data.json.h>
#include <atlbase.h>
#include <utility>
#include <iostream>
using namespace ABI::Windows::Foundation;
using namespace ABI::Windows::Foundation::Collections;
using namespace ABI::Windows::Data::Json;
using std::pair;
#pragma comment (lib, "WindowsApp.lib")
// -----------------------------------------------------------------------------
// Parameter
// -----------------------------------------------------------------------------
// --------------------------- Public ---------------------------------------
Parameter::Parameter() {}
Parameter::Parameter(pair<wstring, ATL::CComPtr<IPropertyValue>> _objIdVal) :
oIdVal(_objIdVal), isObject(true), isEmpty(false) {}
Parameter::Parameter(ATL::CComPtr<IPropertyValue> _iPropVal) :
iPropVal(_iPropVal), isObject(false), isEmpty(false) {}
// -----------------------------------------------------------------------------
// Action
// -----------------------------------------------------------------------------
/// <summary>
/// Check that the members with which an action is going to be constructed are
/// valid.
/// </summary>
/// <param name="method">The method for the action.</param>
/// <param name="params">The parameters for the action</param>
/// <returns>
/// ERROR_SUCCESS in case of success or E_INVALIDARG in case of invalid
/// action members.
/// </returns>
HRESULT checkActionMembers(wstring method, vector<Parameter> params) {
if (method != L"GetValue" && method != L"SetValue") {
return E_INVALIDARG;
}
HRESULT errCode { ERROR_SUCCESS };
if (params.size() > 1) {
for (const auto& param : params) {
bool validParam =
param.isEmpty == false &&
param.isObject == true &&
param.oIdVal.first.empty() == false;
if (validParam == false) {
errCode = E_INVALIDARG;
break;
}
}
}
return errCode;
}
/// <summary>
/// Helper function to create an action that ensure that it doens't contradict
/// the expected payload format.
/// </summary>
/// <param name="sId">The action target setting id.</param>
/// <param name="sMethod">The action target method.</param>
/// <param name="params">The action parameters</param>
/// <param name="rAction">A reference to the action to be filled.</param>
/// <returns>
/// ERROR_SUCCESS in case of success or E_INVALIDARG in case of parameters
/// not passing format checking.
/// </returns>
HRESULT createAction(wstring sId, wstring sMethod, vector<Parameter> params, Action& rAction) {
HRESULT errCode { checkActionMembers(sMethod, params) };
if (errCode == ERROR_SUCCESS) {
rAction = Action { sId, sMethod, params };
}
return errCode;
}
// -----------------------------------------------------------------------------
// Parsing & Serialization Functions
// -----------------------------------------------------------------------------
// --------------------------- Parsing --------------------------------------
enum class OpType {
Get,
Set
};
HRESULT getValueParam(ATL::CComPtr<IJsonValue> jValue, ATL::CComPtr<IPropertyValue>& jPropVal) {
HRESULT res = ERROR_SUCCESS;
ATL::CComPtr<IPropertyValueStatics> pValueFactory;
HSTRING rTimeClass = NULL;
JsonValueType jElemValueType = JsonValueType::JsonValueType_Null;
res = WindowsCreateString(
RuntimeClass_Windows_Foundation_PropertyValue,
static_cast<UINT32>(wcslen(RuntimeClass_Windows_Foundation_PropertyValue)),
&rTimeClass
);
if (res != ERROR_SUCCESS) goto cleanup;
res = GetActivationFactory(rTimeClass, &pValueFactory);
if (res != ERROR_SUCCESS) goto cleanup;
res = jValue->get_ValueType(&jElemValueType);
if (res != ERROR_SUCCESS) goto cleanup;
if (jElemValueType == JsonValueType::JsonValueType_Boolean) {
boolean elemValue;
ATL::CComPtr<IPropertyValue> value;
res = jValue->GetBoolean(&elemValue);
if (res == ERROR_SUCCESS) {
res = pValueFactory->CreateBoolean(elemValue, reinterpret_cast<IInspectable**>(&value));
if (res == ERROR_SUCCESS) {
jPropVal = value;
}
}
} else if (jElemValueType == JsonValueType::JsonValueType_String) {
HSTRING elemValue;
ATL::CComPtr<IPropertyValue> value;
res = jValue->GetString(&elemValue);
if (res == ERROR_SUCCESS) {
UINT32 bufSize { 0 };
PCWSTR bufWSTR { WindowsGetStringRawBuffer(elemValue, &bufSize) };
wstring elemValueStr { bufWSTR, bufSize };
VARIANT vElemVal;
vElemVal.vt = VARENUM::VT_BSTR;
vElemVal.bstrVal = const_cast<BSTR>( elemValueStr.c_str() );
res = createPropertyValue(vElemVal, value);
if (res == ERROR_SUCCESS) {
jPropVal = value;
}
}
} else if (jElemValueType == JsonValueType::JsonValueType_Number) {
DOUBLE elemValue;
ATL::CComPtr<IPropertyValue> value;
res = jValue->GetNumber(&elemValue);
if (res == ERROR_SUCCESS) {
res = pValueFactory->CreateDouble(elemValue, reinterpret_cast<IInspectable**>(&value));
if (res == ERROR_SUCCESS) {
jPropVal = value;
}
}
} else {
res = E_INVALIDARG;
}
cleanup:
return res;
}
HRESULT getObjectParam(OpType opType, ATL::CComPtr<IJsonObject> jObject, Parameter& param) {
HRESULT res = ERROR_SUCCESS;
// Tags
HSTRING hElemIdTag = NULL;
PCWSTR pElemIdTag = L"elemId";
HSTRING hElemValTag = NULL;
PCWSTR pElemValTag = L"elemVal";
// Values
UINT32 hElemIdSize = 0;
HSTRING hElemId = NULL;
ATL::CComPtr<IJsonValue> jElemVal;
ATL::CComPtr<IPropertyValue> pElemVal;
res = WindowsCreateString(pElemIdTag, static_cast<UINT32>(wcslen(pElemIdTag)), &hElemIdTag);
if (res != ERROR_SUCCESS) goto cleanup;
res = WindowsCreateString(pElemValTag, static_cast<UINT32>(wcslen(pElemValTag)), &hElemValTag);
if (res != ERROR_SUCCESS) goto cleanup;
res = jObject->GetNamedString(hElemIdTag, &hElemId);
if (res != ERROR_SUCCESS) goto cleanup;
if (opType == OpType::Get) {
VARIANT emptyVar;
emptyVar.vt = VARENUM::VT_EMPTY;
res = createPropertyValue(emptyVar, pElemVal);
} else {
res = jObject->GetNamedValue(hElemValTag, &jElemVal);
if (res == ERROR_SUCCESS) {
res = getValueParam(jElemVal, pElemVal);
}
}
if (res == ERROR_SUCCESS) {
param = Parameter {
pair<wstring, ATL::CComPtr<IPropertyValue>> {
wstring { WindowsGetStringRawBuffer(hElemId, &hElemIdSize) },
pElemVal
}
};
}
cleanup:
if (hElemIdTag != NULL) WindowsDeleteString(hElemIdTag);
if (hElemValTag != NULL) WindowsDeleteString(hElemValTag);
if (hElemId != NULL) WindowsDeleteString(hElemId);
return res;
}
HRESULT getMatchingType(OpType type, const ATL::CComPtr<IJsonArray> arrayObj, const UINT32 index, Parameter& param) {
HRESULT res = ERROR_SUCCESS;
ATL::CComPtr<IVector<IJsonValue*>> jVectorValue;
ATL::CComPtr<IJsonValue> jValue;
JsonValueType jElemValueType = JsonValueType::JsonValueType_Null;
boolean isValueType = false;
res = arrayObj->QueryInterface(__uuidof(__FIVector_1_Windows__CData__CJson__CIJsonValue_t), reinterpret_cast<void**>(&jVectorValue));
if (res != ERROR_SUCCESS) goto cleanup;
res = jVectorValue->GetAt(index, &jValue);
if (res != ERROR_SUCCESS) goto cleanup;
res = jValue->get_ValueType(&jElemValueType);
if (res != ERROR_SUCCESS) goto cleanup;
isValueType = jElemValueType == JsonValueType::JsonValueType_Boolean ||
jElemValueType == JsonValueType::JsonValueType_Number ||
jElemValueType == JsonValueType::JsonValueType_String;
if (isValueType) {
ATL::CComPtr<IPropertyValue> jPropVal;
res = getValueParam(jValue, jPropVal);
if (res == ERROR_SUCCESS) {
param = Parameter{ jPropVal };
}
} else if (jElemValueType == JsonValueType::JsonValueType_Object) {
ATL::CComPtr<IJsonObject> jObjVal;
res = jValue->GetObject(&jObjVal);
if (res == ERROR_SUCCESS) {
res = getObjectParam(type, jObjVal, param);
}
} else {
res = E_INVALIDARG;
}
cleanup:
return res;
}
HRESULT parseParameters(OpType type, const ATL::CComPtr<IJsonArray> arrayObj, vector<Parameter>& params) {
if (arrayObj == NULL) { return E_INVALIDARG; };
HRESULT res = ERROR_SUCCESS;
HRESULT nextElemErr = ERROR_SUCCESS;
UINT32 jElemIndex = 0;
vector<Parameter> _params {};
while (nextElemErr == ERROR_SUCCESS) {
Parameter curParam {};
nextElemErr = getMatchingType(type, arrayObj, jElemIndex, curParam);
if (curParam.isEmpty == false && nextElemErr == ERROR_SUCCESS) {
_params.push_back(curParam);
} else if (nextElemErr != E_BOUNDS) {
res = nextElemErr;
}
jElemIndex++;
}
if (res == ERROR_SUCCESS) {
params = _params;
}
return res;
}
HRESULT parseAction(const ATL::CComPtr<IJsonObject> elemObj, Action& action) {
if (elemObj == NULL) { return E_INVALIDARG; }
HRESULT errCode = ERROR_SUCCESS;
UINT32 bufLength = 0;
// Required fields vars
// ========================================================================
HSTRING hSettingId = NULL;
PCWSTR pSettingId = L"settingID";
PCWSTR pSettingRawBuf = NULL;
HSTRING hMethod = NULL;
PCWSTR pMethod = L"method";
PCWSTR pMethodRawBuf = NULL;
HSTRING hSettingIdVal = NULL;
HSTRING hMethodVal = NULL;
wstring sSettingId {};
wstring sMethod {};
vector<Parameter> params {};
// Optional fields vars
// ========================================================================
HRESULT getArrayErr = ERROR_SUCCESS;
HSTRING hParams = NULL;
PCWSTR pParams = L"parameters";
ATL::CComPtr<IJsonArray> jParamsArray = NULL;
// Extract required fields
// ========================================================================
errCode = WindowsCreateString(pSettingId, static_cast<UINT32>(wcslen(pSettingId)), &hSettingId);
if (errCode != ERROR_SUCCESS) goto cleanup;
errCode = WindowsCreateString(pMethod, static_cast<UINT32>(wcslen(pMethod)), &hMethod);
if (errCode != ERROR_SUCCESS) goto cleanup;
errCode = elemObj->GetNamedString(hSettingId, &hSettingIdVal);
if (errCode != ERROR_SUCCESS) goto cleanup;
errCode = elemObj->GetNamedString(hMethod, &hMethodVal);
if (errCode != ERROR_SUCCESS) goto cleanup;
pSettingRawBuf = WindowsGetStringRawBuffer(hSettingIdVal, &bufLength);
pMethodRawBuf = WindowsGetStringRawBuffer(hMethodVal, &bufLength);
if (pSettingRawBuf != NULL && pMethodRawBuf != NULL) {
sSettingId = wstring(pSettingRawBuf);
sMethod = wstring(pMethodRawBuf);
} else {
errCode = E_INVALIDARG;
goto cleanup;
}
// Extract optional fields
// ========================================================================
errCode = WindowsCreateString(pParams, static_cast<UINT32>(wcslen(pParams)), &hParams);
if (errCode != ERROR_SUCCESS) goto cleanup;
getArrayErr = elemObj->GetNamedArray(hParams, &jParamsArray);
// Check that the payload ins't of type "SetValue" if "parameters" isn't present.
if (getArrayErr != ERROR_SUCCESS) {
if (sMethod == L"SetValue") {
errCode = WEB_E_JSON_VALUE_NOT_FOUND;
goto cleanup;
} else if (sMethod == L"GetValue") {
action = Action { sSettingId, sMethod, params };
} else {
// TODO: Change with a more meaningful message
errCode = E_INVALIDARG;
}
} else {
if (sMethod == L"SetValue") {
errCode = parseParameters(OpType::Set, jParamsArray, params);
if (errCode == ERROR_SUCCESS) {
Action _action {};
errCode = createAction(sSettingId, sMethod, params, _action);
if (errCode == ERROR_SUCCESS) {
action = _action;
}
}
} else {
errCode = parseParameters(OpType::Get, jParamsArray, params);
if (errCode == ERROR_SUCCESS) {
Action _action {};
errCode = createAction(sSettingId, sMethod, params, _action);
if (errCode == ERROR_SUCCESS) {
action = _action;
}
}
}
}
cleanup:
if (hSettingId != NULL) { WindowsDeleteString(hSettingId); }
if (hMethod != NULL) { WindowsDeleteString(hMethod); }
if (hSettingIdVal != NULL) { WindowsDeleteString(hSettingIdVal); }
if (hMethodVal != NULL ) { WindowsDeleteString(hMethodVal); }
if (hParams != NULL) { WindowsDeleteString(hParams); }
return errCode;
}
HRESULT parsePayload(const wstring & payload, vector<pair<Action, HRESULT>>& actions) {
HRESULT res = ERROR_SUCCESS;
vector<pair<Action, HRESULT>> _actions {};
ATL::CComPtr<IJsonArrayStatics> jsonArrayFactory = NULL;
HSTRING rJSONClass = NULL;
res = WindowsCreateString(
RuntimeClass_Windows_Data_Json_JsonArray,
static_cast<UINT32>(wcslen(RuntimeClass_Windows_Data_Json_JsonArray)),
&rJSONClass
);
GetActivationFactory(rJSONClass, &jsonArrayFactory);
HSTRING hPayload = NULL;
WindowsCreateString(payload.c_str(), static_cast<UINT32>(payload.size()), &hPayload);
ATL::CComPtr<IJsonArray> jActionsArray = NULL;
HRESULT nextElemErr = ERROR_SUCCESS;
UINT32 jElemIndex = 0;
res = jsonArrayFactory->Parse(hPayload, &jActionsArray);
if (res != ERROR_SUCCESS) goto cleanup;
while (nextElemErr == ERROR_SUCCESS) {
IJsonObject* curElem = NULL;
nextElemErr = jActionsArray->GetObjectAt(jElemIndex, &curElem);
if (curElem != NULL && nextElemErr == ERROR_SUCCESS) {
Action curAction {};
ATL::CComPtr<IJsonObject> cCurElem { curElem };
HRESULT errCode = parseAction(cCurElem, curAction);
if (errCode == ERROR_SUCCESS) {
_actions.push_back({ curAction, ERROR_SUCCESS });
} else {
_actions.push_back({ Action {}, errCode });
}
};
jElemIndex++;
}
for (const auto& action : _actions) {
if (action.second != ERROR_SUCCESS) {
res = E_INVALIDARG;
break;
}
}
actions = _actions;
cleanup:
if (rJSONClass) {
WindowsDeleteString(rJSONClass);
}
if (hPayload) {
WindowsDeleteString(hPayload);
}
return res;
}
// ------------------------ Serialization ----------------------------------
HRESULT serializeResult(const Result& result, std::wstring& str) {
std::wstring resultStr {};
HRESULT res = ERROR_SUCCESS;
try {
// JSON object start
resultStr.append(L"{");
// SettingId
resultStr.append(L"\"settingID\": ");
if (result.settingID.empty()) {
resultStr.append(L"null");
} else {
resultStr.append(L"\"" + result.settingID + L"\"");
}
resultStr.append(L", ");
// IsError
resultStr.append(L"\"isError\": ");
if (result.isError) {
resultStr.append(L"true");
} else {
resultStr.append(L"false");
}
resultStr.append(L", ");
// ErrorMessage
resultStr.append(L"\"errorMessage\": ");
if (result.errorMessage.empty()) {
resultStr.append(L"null");
} else {
resultStr.append(L"\"" + result.errorMessage + L"\"");
}
resultStr.append(L", ");
// ReturnValue
resultStr.append(L"\"returnValue\": ");
if (result.returnValue.empty()) {
resultStr.append(L"null");
} else {
resultStr.append(result.returnValue);
}
// JSON object end
resultStr.append(L"}");
// Communicate back the result
str = resultStr;
} catch(std::bad_alloc&) {
res = E_OUTOFMEMORY;
}
return res;
} | 31.324125 | 137 | 0.587454 | stegru |
6bc0b00fdb774b8a05fe9c9b6a2f1b72447027f5 | 10,897 | hpp | C++ | parser/ParseCaseExpressions.hpp | Hacker0912/quickstep-datalog | 1de22e7ab787b5efa619861a167a097ff6a4f549 | [
"Apache-2.0"
] | 82 | 2016-04-18T03:59:06.000Z | 2019-02-04T11:46:08.000Z | parser/ParseCaseExpressions.hpp | Hacker0912/quickstep-datalog | 1de22e7ab787b5efa619861a167a097ff6a4f549 | [
"Apache-2.0"
] | 265 | 2016-04-19T17:52:43.000Z | 2018-10-11T17:55:08.000Z | parser/ParseCaseExpressions.hpp | Hacker0912/quickstep-datalog | 1de22e7ab787b5efa619861a167a097ff6a4f549 | [
"Apache-2.0"
] | 68 | 2016-04-18T05:00:34.000Z | 2018-10-30T12:41:02.000Z | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
**/
#ifndef QUICKSTEP_PARSER_PARSE_CASE_EXPRESSIONS_HPP_
#define QUICKSTEP_PARSER_PARSE_CASE_EXPRESSIONS_HPP_
#include <memory>
#include <string>
#include <vector>
#include "parser/ParseExpression.hpp"
#include "parser/ParsePredicate.hpp"
#include "parser/ParseTreeNode.hpp"
#include "utility/Macros.hpp"
#include "utility/PtrVector.hpp"
namespace quickstep {
/** \addtogroup Parser
* @{
*/
/**
* @brief The parsed representation of a WHEN clause in a simple CASE
* expression (WHEN <condition operand> THEN <result expression>).
*/
class ParseSimpleWhenClause : public ParseTreeNode {
public:
/**
* @brief Constructor. Takes ownership of all pointers.
*
* @param line_number The line number of "WHEN" in the SQL statement.
* @param column_number The column number of "WHEN" in the SQL statement.
* @param check_operand The condition operand to be compared with the
* CASE operand (not in this class) of the CASE
* expression.
* @param result_expression The result expression for this condition.
*/
ParseSimpleWhenClause(int line_number,
int column_number,
ParseExpression *condition_operand,
ParseExpression *result_expression)
: ParseTreeNode(line_number, column_number),
condition_operand_(condition_operand),
result_expression_(result_expression) {
}
std::string getName() const override {
return "SimpleWhenClause";
}
/**
* @return The condition operand.
*/
const ParseExpression* condition_operand() const {
return condition_operand_.get();
}
/**
* @return The result expression for this condition.
*/
const ParseExpression* result_expression() const {
return result_expression_.get();
}
protected:
void getFieldStringItems(
std::vector<std::string> *inline_field_names,
std::vector<std::string> *inline_field_values,
std::vector<std::string> *non_container_child_field_names,
std::vector<const ParseTreeNode*> *non_container_child_fields,
std::vector<std::string> *container_child_field_names,
std::vector<std::vector<const ParseTreeNode*>> *container_child_fields) const override;
private:
std::unique_ptr<ParseExpression> condition_operand_;
std::unique_ptr<ParseExpression> result_expression_;
DISALLOW_COPY_AND_ASSIGN(ParseSimpleWhenClause);
};
/**
* @brief The parsed representation of a WHEN clause in a searched CASE
* expression (WHEN <condition predicate> THEN <result expression>).
*
*/
class ParseSearchedWhenClause : public ParseTreeNode {
public:
/**
* @brief Constructor. Takes ownership of all pointers.
*
* @param line_number The line number of "WHEN" in the SQL statement.
* @param column_number The column number of "WHEN" in the SQL statement.
* @param condition_predicate The condition predicate.
* @param result_expression The result expression for this condition.
*/
ParseSearchedWhenClause(int line_number,
int column_number,
ParsePredicate *condition_predicate,
ParseExpression *result_expression)
: ParseTreeNode(line_number, column_number),
condition_predicate_(condition_predicate),
result_expression_(result_expression) {
}
std::string getName() const override {
return "SearchedWhenClause";
}
/**
* @return The condition predicate.
*/
const ParsePredicate* condition_predicate() const {
return condition_predicate_.get();
}
/**
* @return The result expression.
*/
const ParseExpression* result_expression() const {
return result_expression_.get();
}
protected:
void getFieldStringItems(
std::vector<std::string> *inline_field_names,
std::vector<std::string> *inline_field_values,
std::vector<std::string> *non_container_child_field_names,
std::vector<const ParseTreeNode*> *non_container_child_fields,
std::vector<std::string> *container_child_field_names,
std::vector<std::vector<const ParseTreeNode*>> *container_child_fields) const override;
private:
std::unique_ptr<ParsePredicate> condition_predicate_;
std::unique_ptr<ParseExpression> result_expression_;
DISALLOW_COPY_AND_ASSIGN(ParseSearchedWhenClause);
};
/**
* @brief The parsed representation of a simple CASE expression:
* CASE <case operand>
* WHEN <condition_operand> THEN <result_expression>
* [...n]
* [ELSE <else_result_expression>]
* END
* It returns the <result_expression> of the first <case operand> = <when_operand>
* that evaluates to true; if none is found and <else_result_expression> exists,
* returns <else_result_expression>; otherwise, returns NULL.
**/
class ParseSimpleCaseExpression : public ParseExpression {
public:
/**
* @brief Constructor. Takes ownership of all pointers.
*
* @param line_number The line number of "CASE" in the SQL statement.
* @param column_number The column number of "CASE" in the SQL statement.
* @param case_operand The CASE operand.
* @param when_clauses A vector of WHEN clauses, each having a check operand to
* be compared with the CASE operand and a result expression
* to be evaluated if the condition is satisfied.
* @param else_result_expression Optional ELSE result expression.
*/
ParseSimpleCaseExpression(int line_number,
int column_number,
ParseExpression *case_operand,
PtrVector<ParseSimpleWhenClause> *when_clauses,
ParseExpression *else_result_expression)
: ParseExpression(line_number, column_number),
case_operand_(case_operand),
when_clauses_(when_clauses),
else_result_expression_(else_result_expression) {
}
std::string getName() const override {
return "SimpleCaseExpression";
}
ExpressionType getExpressionType() const override {
return kSimpleCaseExpression;
}
/**
* @return The CASE operand.
*/
const ParseExpression* case_operand() const {
return case_operand_.get();
}
/**
* @return The vector of WHEN clauses.
*/
const PtrVector<ParseSimpleWhenClause>* when_clauses() const {
return when_clauses_.get();
}
/**
* @return The ELSE result expression. Can be NULL.
*/
const ParseExpression* else_result_expression() const {
return else_result_expression_.get();
}
std::string generateName() const override;
protected:
void getFieldStringItems(
std::vector<std::string> *inline_field_names,
std::vector<std::string> *inline_field_values,
std::vector<std::string> *non_container_child_field_names,
std::vector<const ParseTreeNode*> *non_container_child_fields,
std::vector<std::string> *container_child_field_names,
std::vector<std::vector<const ParseTreeNode*>> *container_child_fields) const override;
private:
std::unique_ptr<ParseExpression> case_operand_;
std::unique_ptr<PtrVector<ParseSimpleWhenClause>> when_clauses_;
std::unique_ptr<ParseExpression> else_result_expression_;
DISALLOW_COPY_AND_ASSIGN(ParseSimpleCaseExpression);
};
/**
* @brief The parsed representation of a searched CASE expression:
* CASE
* WHEN <condition_predicate> THEN <result_expression>
* [...n]
* [ELSE <else_result_expression>]
* END
* It returns the <result_expression> of the first <condition_predicate>
* that evaluates to true; if none is found and <else_result_expression> exists,
* returns <else_result_expression>; otherwise, returns NULL.
*/
class ParseSearchedCaseExpression : public ParseExpression {
public:
/**
* @brief Constructor. Takes ownership of all pointers.
*
* @param line_number The line number of "CASE" in the SQL statement.
* @param column_number The column number of "CASE" in the SQL statement.
* @param when_clauses A vector of WHEN clauses, each having a predicate
* and a result expression to be evaluate if
* the predicate evaluates to true.
* @param else_result_expression Optional ELSE result expression.
*/
ParseSearchedCaseExpression(int line_number,
int column_number,
PtrVector<ParseSearchedWhenClause> *when_clauses,
ParseExpression *else_result_expression)
: ParseExpression(line_number, column_number),
when_clauses_(when_clauses),
else_result_expression_(else_result_expression) {
}
std::string getName() const override {
return "SearchedCaseExpression";
}
ExpressionType getExpressionType() const override {
return kSearchedCaseExpression;
}
/**
* @return The vector of WHEN clauses.
*/
const PtrVector<ParseSearchedWhenClause>* when_clauses() const {
return when_clauses_.get();
}
/**
* @return The ELSE result expression. Can be NULL.
*/
const ParseExpression* else_result_expression() const {
return else_result_expression_.get();
}
std::string generateName() const override;
protected:
void getFieldStringItems(
std::vector<std::string> *inline_field_names,
std::vector<std::string> *inline_field_values,
std::vector<std::string> *non_container_child_field_names,
std::vector<const ParseTreeNode*> *non_container_child_fields,
std::vector<std::string> *container_child_field_names,
std::vector<std::vector<const ParseTreeNode*>> *container_child_fields) const override;
private:
std::unique_ptr<PtrVector<ParseSearchedWhenClause>> when_clauses_;
std::unique_ptr<ParseExpression> else_result_expression_;
DISALLOW_COPY_AND_ASSIGN(ParseSearchedCaseExpression);
};
/** @} */
} // namespace quickstep
#endif /* QUICKSTEP_PARSER_PARSE_CASE_EXPRESSIONS_HPP_ */
| 34.484177 | 93 | 0.696706 | Hacker0912 |
6bc210a3465b5cd4ef962cb2b8e18d8913cbf87a | 6,724 | cpp | C++ | Coin3D/src/Inventor/Xt/devices/SoXtMouse.cpp | pniaz20/inventor-utils | 2306b758b15bd1a0df3fb9bd250215b7bb7fac3f | [
"MIT"
] | null | null | null | Coin3D/src/Inventor/Xt/devices/SoXtMouse.cpp | pniaz20/inventor-utils | 2306b758b15bd1a0df3fb9bd250215b7bb7fac3f | [
"MIT"
] | null | null | null | Coin3D/src/Inventor/Xt/devices/SoXtMouse.cpp | pniaz20/inventor-utils | 2306b758b15bd1a0df3fb9bd250215b7bb7fac3f | [
"MIT"
] | null | null | null | /**************************************************************************\
*
* This file is part of the Coin 3D visualization library.
* Copyright (C) by Kongsberg Oil & Gas Technologies.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* ("GPL") version 2 as published by the Free Software Foundation.
* See the file LICENSE.GPL at the root directory of this source
* distribution for additional information about the GNU GPL.
*
* For using Coin with software that can not be combined with the GNU
* GPL, and for taking advantage of the additional benefits of our
* support services, please contact Kongsberg Oil & Gas Technologies
* about acquiring a Coin Professional Edition License.
*
* See http://www.coin3d.org/ for more information.
*
* Kongsberg Oil & Gas Technologies, Bygdoy Alle 5, 0257 Oslo, NORWAY.
* http://www.sim.no/ sales@sim.no coin-support@coin3d.org
*
\**************************************************************************/
// Class documentation in common code file.
// *************************************************************************
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif // HAVE_CONFIG_H
#include <X11/X.h>
#include <Inventor/errors/SoDebugError.h>
#include <Inventor/events/SoLocation2Event.h>
#include <Inventor/events/SoMouseButtonEvent.h>
#include <Inventor/Xt/devices/SoXtMouse.h>
#include <Inventor/Xt/devices/SoGuiMouseP.h>
#include <soxtdefs.h>
#define PRIVATE(p) (p->pimpl)
#define PUBLIC(p) (p->pub)
// *************************************************************************
class SoXtMouseP : public SoGuiMouseP {
public:
SoXtMouseP(SoXtMouse * p) : SoGuiMouseP(p) { }
SoLocation2Event * makeLocationEvent(XMotionEvent * event);
SoMouseButtonEvent * makeButtonEvent(XButtonEvent * event, SoButtonEvent::State state);
};
// *************************************************************************
// Doc in common code file.
SoXtMouse::SoXtMouse(int events)
{
PRIVATE(this) = new SoXtMouseP(this);
PRIVATE(this)->eventmask = events;
}
// Doc in common code file.
SoXtMouse::~SoXtMouse()
{
delete PRIVATE(this);
}
// *************************************************************************
// Doc in superclass.
void
SoXtMouse::enable(Widget widget, SoXtEventHandler * handler, void * closure)
{
// FIXME: should explicitly convert eventmask to bitmask with X11/Xt
// bitflag values, just in case either our or X11's enum values
// should ever change (yeah, I know, slim chance, but still.. that'd
// be better design). 20020625 mortene.
XtAddEventHandler(widget, PRIVATE(this)->eventmask, FALSE, handler, closure);
}
// Doc in superclass.
void
SoXtMouse::disable(Widget widget, SoXtEventHandler * handler, void * closure)
{
XtRemoveEventHandler(widget, PRIVATE(this)->eventmask, FALSE, handler, closure);
}
// *************************************************************************
// Doc in common code file.
const SoEvent *
SoXtMouse::translateEvent(XAnyEvent * event)
{
SoEvent * soevent = (SoEvent *) NULL;
SoButtonEvent::State state = SoButtonEvent::UNKNOWN;
switch (event->type) {
// events we should catch:
case ButtonPress:
if (! (PRIVATE(this)->eventmask & SoXtMouse::BUTTON_PRESS)) break;
state = SoButtonEvent::DOWN;
soevent = PRIVATE(this)->makeButtonEvent((XButtonEvent *) event, state);
break;
case ButtonRelease:
if (! (PRIVATE(this)->eventmask & SoXtMouse::BUTTON_RELEASE)) break;
state = SoButtonEvent::UP;
soevent = PRIVATE(this)->makeButtonEvent((XButtonEvent *) event, state);
break;
case MotionNotify:
if (! (PRIVATE(this)->eventmask & SoXtMouse::POINTER_MOTION)) break;
soevent = PRIVATE(this)->makeLocationEvent((XMotionEvent *) event);
break;
// FIXME: implement BUTTON_MOTION filtering. larsa.
case EnterNotify:
case LeaveNotify:
// should we make location-events for these?
do {
SOXT_STUB();
} while (FALSE);
break;
// events we should ignore:
default:
break;
}
return (SoEvent *) soevent;
}
// *************************************************************************
#ifndef DOXYGEN_SKIP_THIS
// This method translates from X motion events to Open Inventor
// SoLocation2Event events.
SoLocation2Event *
SoXtMouseP::makeLocationEvent(XMotionEvent * event)
{
#if SOXT_DEBUG && 0
SoDebugError::postInfo("SoXtMouse::makeLocationEvent",
"pointer at (%d, %d)", event->x, PUBLIC(this)->getWindowSize()[1] - event->y);
#endif // 0 was SOXT_DEBUG
delete this->locationevent;
this->locationevent = new SoLocation2Event;
PUBLIC(this)->setEventPosition(this->locationevent, event->x, event->y);
this->locationevent->setShiftDown((event->state & ShiftMask) ? TRUE : FALSE);
this->locationevent->setCtrlDown((event->state & ControlMask) ? TRUE : FALSE);
this->locationevent->setAltDown((event->state & Mod1Mask) ? TRUE : FALSE);
SbTime stamp;
stamp.setMsecValue(event->time);
this->locationevent->setTime(stamp);
return this->locationevent;
}
// This method translates from X button events (mouse/pointer) to
// Open Inventor SoMouseButtonEvent events.
SoMouseButtonEvent *
SoXtMouseP::makeButtonEvent(XButtonEvent * event, SoButtonEvent::State state)
{
#if 0 // SOXT_DEBUG
SoDebugError::postInfo("SoXtMouse::makeButtonEvent",
"button %d, state %d", event->button, (int) state);
#endif // 0 was SOXT_DEBUG
delete this->buttonevent;
this->buttonevent = new SoMouseButtonEvent;
this->buttonevent->setState(state);
SoMouseButtonEvent::Button button = SoMouseButtonEvent::ANY;
switch (event->button) {
case 1: button = SoMouseButtonEvent::BUTTON1; break;
case 3: button = SoMouseButtonEvent::BUTTON2; break;
case 2: button = SoMouseButtonEvent::BUTTON3; break;
#ifdef HAVE_SOMOUSEBUTTONEVENT_BUTTON5
case 4: button = SoMouseButtonEvent::BUTTON4; break;
case 5: button = SoMouseButtonEvent::BUTTON5; break;
#endif // HAVE_SOMOUSEBUTTONEVENT_BUTTON5
default:
break;
}
this->buttonevent->setButton(button);
PUBLIC(this)->setEventPosition(this->buttonevent, event->x, event->y);
this->buttonevent->setShiftDown((event->state & ShiftMask) ? TRUE : FALSE);
this->buttonevent->setCtrlDown((event->state & ControlMask) ? TRUE : FALSE);
this->buttonevent->setAltDown((event->state & Mod1Mask) ? TRUE : FALSE);
SbTime stamp;
stamp.setMsecValue(event->time);
this->buttonevent->setTime(stamp);
return this->buttonevent;
}
#endif // DOXYGEN_SKIP_THIS
// *************************************************************************
#undef PRIVATE
#undef PUBLIC
| 31.716981 | 103 | 0.644259 | pniaz20 |
6bc2e5171220162347f5c4700c7a2e61d36db9f1 | 3,161 | hpp | C++ | libvast/vast/arrow_table_slice.hpp | frerich/vast | decac739ea4782ab91a1cee791ecd754b066419f | [
"BSD-3-Clause"
] | null | null | null | libvast/vast/arrow_table_slice.hpp | frerich/vast | decac739ea4782ab91a1cee791ecd754b066419f | [
"BSD-3-Clause"
] | null | null | null | libvast/vast/arrow_table_slice.hpp | frerich/vast | decac739ea4782ab91a1cee791ecd754b066419f | [
"BSD-3-Clause"
] | null | null | null | /******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#pragma once
#include "vast/fwd.hpp"
#include "vast/table_slice.hpp"
#include "vast/view.hpp"
#include <caf/fwd.hpp>
#include <caf/intrusive_cow_ptr.hpp>
#include <arrow/api.h>
#include <memory>
namespace vast {
/// A table slice that stores elements encoded in the
/// [Arrow](https://arrow.org) format. The implementation stores data in
/// column-major order.
class arrow_table_slice final : public vast::table_slice {
public:
// -- friends ----------------------------------------------------------------
friend arrow_table_slice_builder;
// -- constants --------------------------------------------------------------
static constexpr caf::atom_value class_id = caf::atom("arrow");
// -- member types -----------------------------------------------------------
/// Base type.
using super = vast::table_slice;
/// Unsigned integer type.
using size_type = super::size_type;
/// Smart pointer to an Arrow record batch.
using record_batch_ptr = std::shared_ptr<arrow::RecordBatch>;
// -- constructors, destructors, and assignment operators --------------------
/// @pre `batch != nullptr`
arrow_table_slice(vast::table_slice_header header, record_batch_ptr batch);
// -- factories --------------------------------------------------------------
static vast::table_slice_ptr make(vast::table_slice_header header);
// -- properties -------------------------------------------------------------
arrow_table_slice* copy() const override;
caf::error serialize(caf::serializer& sink) const override;
caf::error deserialize(caf::deserializer& source) override;
void append_column_to_index(size_type col, value_index& idx) const override;
caf::atom_value implementation_id() const noexcept override;
vast::data_view at(size_type row, size_type col) const override;
record_batch_ptr batch() const {
return batch_;
}
private:
using table_slice::table_slice;
caf::error serialize_impl(caf::binary_serializer& sink) const;
/// The Arrow table containing all elements.
record_batch_ptr batch_;
};
/// @relates arrow_table_slice
using arrow_table_slice_ptr = caf::intrusive_cow_ptr<arrow_table_slice>;
} // namespace vast
| 33.989247 | 80 | 0.53211 | frerich |
6bc422c93e0de3c9491a71ed7ac33d3810efeee0 | 2,022 | cpp | C++ | src/Example/project_WhiteBoxStudio/code/ModelTest/ObjectSerDef/_tagDirectoryInfoSetSoap_StructInfo.cpp | yds086/HereticOS-ObjectSystem | bdbf48bc3a5ef96c54b3d1652b90740c28c5cf49 | [
"Apache-2.0"
] | 5 | 2017-09-07T06:58:34.000Z | 2021-07-21T08:41:26.000Z | src/Example/project_WhiteBoxStudio/code/ModelTest/ObjectSerDef/_tagDirectoryInfoSetSoap_StructInfo.cpp | yds086/HereticOS-ObjectSystem | bdbf48bc3a5ef96c54b3d1652b90740c28c5cf49 | [
"Apache-2.0"
] | null | null | null | src/Example/project_WhiteBoxStudio/code/ModelTest/ObjectSerDef/_tagDirectoryInfoSetSoap_StructInfo.cpp | yds086/HereticOS-ObjectSystem | bdbf48bc3a5ef96c54b3d1652b90740c28c5cf49 | [
"Apache-2.0"
] | 2 | 2017-09-27T06:31:11.000Z | 2020-05-13T12:29:58.000Z | #include "stdafx.h"
#include "CommonTypeDef.h"
#include "_tagDirectoryInfoSetSoap_StructInfo.h"
Serialize__tagDirectoryInfoSetSoap::_Myt& Serialize__tagDirectoryInfoSetSoap::operator=(_tagDirectoryInfoSetSoap & _X)
{
SetData(_X);
return *this;
}
void Serialize__tagDirectoryInfoSetSoap::GetData()
{
m_Val.ObjectName=ObjectName;
m_Val.ObjectType=ObjectType;
m_Val.OtherInfo=OtherInfo;
}
BOOL Serialize__tagDirectoryInfoSetSoap::Construct(StorageObjectInterface * pOutObject)
{
ObjectName.init(this,_T("ObjectName"),0,pOutObject);
ObjectType.init(this,_T("ObjectType"),0,pOutObject);
OtherInfo.init(this,_T("OtherInfo"),0,pOutObject);
return TRUE;
}
void Serialize__tagDirectoryInfoSetSoap::SetData(_tagDirectoryInfoSetSoap & _X)
{
ObjectName=_X.ObjectName;
ObjectType=_X.ObjectType;
OtherInfo=_X.OtherInfo;
}
BOOL Serialize__tagDirectoryInfoSetSoap::LoadGetCurSerializeObject(FieldAddr & CurFieldAddr, SerializeLoadSaveInterface * * RetObj)
{
*RetObj=0;
if(tstring(CurFieldAddr.pFieldName)==tstring(_T("ObjectName")))
{
*RetObj=&ObjectName;
} else if(tstring(CurFieldAddr.pFieldName)==tstring(_T("ObjectType")))
{
*RetObj=&ObjectType;
} else if(tstring(CurFieldAddr.pFieldName)==tstring(_T("OtherInfo")))
{
*RetObj=&OtherInfo;
}
if(*RetObj) return TRUE;
return FALSE;
}
BOOL Serialize__tagDirectoryInfoSetSoap::Save(StorageObjectInterface * pStorageObject)
{
pStorageObject->PushNodeCtlBegin(_T("_tagDirectoryInfoSetSoap"),this);
ObjectName.Save(pStorageObject);
ObjectType.Save(pStorageObject);
OtherInfo.Save(pStorageObject);
pStorageObject->PushNodeCtlEnd(_T("_tagDirectoryInfoSetSoap"),this);
return TRUE;
}
BOOL Serialize__tagDirectoryInfoSetSoap::GetObjectMap(IN OUT vector<SerializeObjectInterface *> & ObjectInterfaceMap)
{
ObjectInterfaceMap.push_back((SerializeObjectInterface *)&ObjectName);
ObjectInterfaceMap.push_back((SerializeObjectInterface *)&ObjectType);
ObjectInterfaceMap.push_back((SerializeObjectInterface *)&OtherInfo);
return TRUE;
}
| 27.324324 | 131 | 0.794263 | yds086 |
6bc4970846db1d0b632b6bcc7c103ab94da08e19 | 5,003 | cpp | C++ | client/dll/offset.cpp | Nullptr-Archives/CSNS-SoftON-Hack | d68ee3c577181ef3b2910b413203aa9fc36e7c70 | [
"MIT"
] | 13 | 2021-03-14T11:34:29.000Z | 2021-04-13T03:20:19.000Z | client/dll/offset.cpp | Nullptr-Archives/CSNS-SoftON-Hack | d68ee3c577181ef3b2910b413203aa9fc36e7c70 | [
"MIT"
] | 1 | 2021-03-26T17:03:50.000Z | 2021-03-26T17:03:50.000Z | client/dll/offset.cpp | Nullptr-Archives/CSNS-SoftON-Hack | d68ee3c577181ef3b2910b413203aa9fc36e7c70 | [
"MIT"
] | 9 | 2021-03-14T11:35:19.000Z | 2021-04-21T08:12:47.000Z | #include "offset.h"
#include <unordered_map>
#include "globals.h"
#include "utils.h"
// universal representation for game modules
struct GameModule {
DWORD start, end;
GameModule() = default;
// construct module with its start and end address
GameModule(DWORD start_, DWORD end_) :
start(start_),
end(end_)
{}
// construct module with its name
GameModule(const std::string& name) {
auto get_module_size = [](DWORD address) -> DWORD {
return PIMAGE_NT_HEADERS(address + (DWORD)PIMAGE_DOS_HEADER(address)->e_lfanew)->OptionalHeader.SizeOfImage;
};
start = (DWORD)GetModuleHandleA(std::string(name + ".dll").c_str());
if (start == NULL)
utils::TerminateGame("Module", name, "isn't loaded");
end = start + get_module_size(start) - 1;
}
};
// GameModules is a wrapper-class to make
// work with game modules more comfortable.
// to get module by name overloaded 'operator[]' is used.
// that operator also constructs module if there is no module with given name
class GameModules {
public:
const GameModule& operator [] (const std::string& name) {
auto el = this->modules.find(name);
if (el != this->modules.end())
return el->second;
this->modules[name] = { name };
return this->modules[name];
}
private:
std::unordered_map<std::string, GameModule> modules;
};
#define CompareMemory(Buff1, Buff2, Size) __comparemem((const UCHAR *)Buff1, (const UCHAR *)Buff2, (UINT)Size)
#define FindMemoryClone(Module, Clone, Size) __findmemoryclone((const ULONG)Module.start, (const ULONG)Module.end, (const ULONG)Clone, (UINT)Size)
#define FindReference(Module, Address) __findreference((const ULONG)Module.start, (const ULONG)Module.end, (const ULONG)Address)
BOOL __comparemem(const UCHAR* buff1, const UCHAR* buff2, UINT size) {
for (UINT i = 0; i < size; i++, buff1++, buff2++)
{
if ((*buff1 != *buff2) && (*buff2 != 0xFF))
return FALSE;
}
return TRUE;
}
ULONG __findmemoryclone(const ULONG start, const ULONG end, const ULONG clone, UINT size) {
for (ULONG ul = start; (ul + size) < end; ul++) {
if (CompareMemory(ul, clone, size))
return ul;
}
return NULL;
}
ULONG __findreference(const ULONG start, const ULONG end, const ULONG address) {
UCHAR Pattern[5];
Pattern[0] = 0x68;
*(ULONG*)& Pattern[1] = address;
GameModule tmp = { static_cast<DWORD>(start), static_cast<DWORD>(end) };
return FindMemoryClone(tmp, Pattern, sizeof(Pattern) - 1);
}
DWORD FindPattern(PCHAR pattern, PCHAR mask, const GameModule & mod) {
size_t patternLength = strlen(pattern);
bool found = false;
for (DWORD i = mod.start; i < mod.end - patternLength; i++) {
found = true;
for (size_t idx = 0; idx < patternLength; idx++) {
if (mask[idx] == 'x' && pattern[idx] != *(PCHAR)(i + idx)) {
found = false;
break;
}
}
if (found)
return i;
}
return 0;
}
// offsets by: Eugene Golubev, Hardee, Jusic
namespace offset {
GameModules modules;
DWORD ClientTable() {
DWORD addr = (DWORD)FindMemoryClone(modules["hw"], "ScreenFade", strlen("ScreenFade"));
return *(DWORD*)(FindReference(modules["hw"], addr) + 0x13);
}
DWORD EngineTable() {
DWORD addr = (DWORD)FindMemoryClone(modules["hw"], "ScreenFade", strlen("ScreenFade"));
return *(DWORD*)(FindReference(modules["hw"], addr) + 0x0D);
}
DWORD StudioTable() {
return *(DWORD*)((DWORD)g::pClient->HUD_GetStudioModelInterface + 0x34);
}
DWORD StudioAPITable() {
return *(DWORD*)((DWORD)g::pClient->HUD_GetStudioModelInterface + 0x3A);
}
DWORD UserMsgBase() {
DWORD addr = (DWORD)FindMemoryClone(modules["hw"], "UserMsg: Not Present on Client %d", strlen("UserMsg: Not Present on Client %d"));
return *(DWORD*)* (DWORD*)(FindReference(modules["hw"], addr) - 0x14);
}
DWORD EventBase() {
return *(DWORD*)(*(DWORD*)((DWORD)g::pEngine->HookEvent + 0x77));
}
DWORD Speed() {
DWORD addr = (DWORD)FindMemoryClone(modules["hw"], "Texture load: %6.1fms", strlen("Texture load: %6.1fms"));
DWORD ptr = *(DWORD*)(FindReference(modules["hw"], addr) - 0x09);
DWORD old_prot;
VirtualProtect((void*)ptr, sizeof(double), PAGE_READWRITE, &old_prot);
return ptr;
}
DWORD ButtonsBase() {
return *(DWORD*)(FindPattern((PCHAR)"\x0F\x44\xCA\x8B\xD1\x83\xCA\x20\x24\x03\x0F\x44\xD1\x83\x3D\x00\x00\x00\x00\x00\x74",
(PCHAR)"xxxxxxxxxxxxxxx?????x", modules["client"]) - 0x04) - 0x08;
}
DWORD PlayerMove() {
DWORD addr = (DWORD)FindMemoryClone(modules["hw"], "ScreenFade", strlen("ScreenFade"));
return *(DWORD*)(FindReference(modules["hw"], addr) + 0x24);
}
DWORD ClientState() {
return *(DWORD*)((DWORD)g::pEngine->SetScreenFade + 0x26) - 0x44C;
}
DWORD ClientStatic() {
DWORD addr = (DWORD)FindMemoryClone(modules["hw"], "WARNING: Connection Problem", strlen("WARNING: Connection Problem"));
return *(DWORD*)(FindReference(modules["hw"], addr) + 0xDE) - 0x08;
}
} | 30.693252 | 147 | 0.658605 | Nullptr-Archives |
6bc59a6e13328a2f0907c60638b45d5eb1a2b01c | 1,773 | hpp | C++ | genfile/include/genfile/SNPDataSinkChain.hpp | gavinband/bingwa | d52e166b3bb6bc32cd32ba63bf8a4a147275eca1 | [
"BSL-1.0"
] | 3 | 2021-04-21T05:42:24.000Z | 2022-01-26T14:59:43.000Z | genfile/include/genfile/SNPDataSinkChain.hpp | gavinband/bingwa | d52e166b3bb6bc32cd32ba63bf8a4a147275eca1 | [
"BSL-1.0"
] | 2 | 2020-04-09T16:11:04.000Z | 2020-11-10T11:18:56.000Z | genfile/include/genfile/SNPDataSinkChain.hpp | gavinband/qctool | 8d8adb45151c91f953fe4a9af00498073b1132ba | [
"BSL-1.0"
] | null | null | null |
// Copyright Gavin Band 2008 - 2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SNPDATAsinkCHAIN_HPP
#define SNPDATAsinkCHAIN_HPP
#include <iostream>
#include <string>
#include "genfile/snp_data_utils.hpp"
#include "genfile/SNPDataSink.hpp"
namespace genfile {
// class SNPDataSinkChain represents a SNPDataSink
// which outputs its data sequentially to a collection of other SNPDataSinks
class SNPDataSinkChain: public SNPDataSink
{
public:
SNPDataSinkChain() ;
~SNPDataSinkChain() ;
void add_sink( SNPDataSink::UniquePtr sink ) ;
operator bool() const ;
void move_to_next_sink() ;
std::size_t number_of_sinks() const ;
SNPDataSink const& sink( std::size_t i ) const ;
std::size_t index_of_current_sink() const ;
std::string get_spec() const ;
SinkPos get_stream_pos() const ;
private:
void set_metadata_impl( Metadata const& metadata ) ;
void set_sample_names_impl( std::size_t number_of_samples, SampleNameGetter name_getter ) ;
void write_snp_impl(
uint32_t number_of_samples,
std::string SNPID,
std::string RSID,
Chromosome chromosome,
uint32_t SNP_position,
std::string first_allele,
std::string second_allele,
GenotypeProbabilityGetter const& get_AA_probability,
GenotypeProbabilityGetter const& get_AB_probability,
GenotypeProbabilityGetter const& get_BB_probability,
Info const& info
) ;
void write_variant_data_impl(
VariantIdentifyingData const& id_data,
VariantDataReader& data_reader,
Info const& info
) ;
void finalise_impl() ;
private:
std::vector< SNPDataSink* > m_sinks ;
std::size_t m_current_sink ;
} ;
}
#endif
| 26.462687 | 93 | 0.744501 | gavinband |
6bc60dd1c75c0af46927f6ff45b986130514f09c | 544 | cpp | C++ | trace_server/dock/dock.cpp | mojmir-svoboda/DbgToolkit | 590887987d0856032be906068a3103b6ce31d21c | [
"MIT"
] | null | null | null | trace_server/dock/dock.cpp | mojmir-svoboda/DbgToolkit | 590887987d0856032be906068a3103b6ce31d21c | [
"MIT"
] | null | null | null | trace_server/dock/dock.cpp | mojmir-svoboda/DbgToolkit | 590887987d0856032be906068a3103b6ce31d21c | [
"MIT"
] | null | null | null | #include "dock.h"
#include <QCloseEvent>
#include <QMainWindow>
#include "mainwindow.h"
#include "dockwidget.h"
#include <QApplication>
DockedWidgetBase::DockedWidgetBase (MainWindow * mw, QStringList const & path)
: ActionAble(path)
, m_main_window(mw)
, m_dockwidget(0)
{
qDebug("%s this=0x%08x", __FUNCTION__, this);
}
DockedWidgetBase::~DockedWidgetBase ()
{
qDebug("%s this=0x%08x", __FUNCTION__, this);
m_main_window->dockManager().removeActionAble(*this);
m_dockwidget->setWidget(0);
delete m_dockwidget;
m_dockwidget = 0;
}
| 21.76 | 78 | 0.738971 | mojmir-svoboda |
6bceede515f48fe461a8df7ab13cfb97ee20f3eb | 1,743 | cpp | C++ | src/cckVec3.cpp | frmr/cck | 0528157c6439057077547418c22e7977927c29f7 | [
"MIT"
] | 1 | 2015-10-02T17:00:18.000Z | 2015-10-02T17:00:18.000Z | src/cckVec3.cpp | frmr/cck | 0528157c6439057077547418c22e7977927c29f7 | [
"MIT"
] | null | null | null | src/cckVec3.cpp | frmr/cck | 0528157c6439057077547418c22e7977927c29f7 | [
"MIT"
] | null | null | null | #include "cckVec3.h"
#include "cckMath.h"
#include <cmath>
cck::GeoCoord cck::Vec3::ToGeographic() const
{
double lonRadians = atan2( y, x );
if ( lonRadians < -cck::pi )
{
lonRadians += cck::twoPi;
}
else if ( lonRadians > cck::pi )
{
lonRadians -= cck::twoPi;
}
return cck::GeoCoord( atan2( z, sqrt( x * x + y * y ) ), lonRadians );
}
cck::Vec3 cck::Vec3::Unit() const
{
const double length = sqrt( x * x + y * y + z * z );
return cck::Vec3( x / length, y / length, z / length );
}
cck::Vec3 cck::Vec3::operator+( const Vec3& rhs ) const
{
return cck::Vec3( x + rhs.x, y + rhs.y, z + rhs.z );
}
cck::Vec3 cck::Vec3::operator-( const Vec3& rhs ) const
{
return cck::Vec3( x - rhs.x, y - rhs.y, z - rhs.z );
}
cck::Vec3 cck::Vec3::operator*( const double& rhs ) const
{
return cck::Vec3( x * rhs, y * rhs, z * rhs );
}
cck::Vec3 cck::Vec3::operator/( const double& rhs ) const
{
return cck::Vec3( x / rhs, y / rhs, z / rhs );
}
cck::Vec3& cck::Vec3::operator+=( const Vec3& rhs )
{
x += rhs.x;
y += rhs.y;
z += rhs.z;
return *this;
}
cck::Vec3& cck::Vec3::operator-=( const Vec3& rhs )
{
x -= rhs.x;
y -= rhs.y;
z -= rhs.z;
return *this;
}
cck::Vec3& cck::Vec3::operator*=( const double& rhs )
{
x *= rhs;
y *= rhs;
z *= rhs;
return *this;
}
cck::Vec3& cck::Vec3::operator/=( const double& rhs )
{
x /= rhs;
y /= rhs;
z /= rhs;
return *this;
}
cck::Vec3::Vec3()
: x( 0.0 ), y( 0.0 ), z( 0.0 )
{
}
cck::Vec3::Vec3( const double x, const double y, const double z )
: x( x ), y( y ), z( z )
{
}
| 19.58427 | 75 | 0.500287 | frmr |
6bcfbac38550d8b76a7e14d1c84c7987cff6c711 | 7,372 | cpp | C++ | src/planner/insert_plan.cpp | vittvolt/15721-peloton | 3394c745ce5f3d71d1d71a09c700d5e367345e2e | [
"Apache-2.0"
] | 7 | 2017-03-12T01:57:48.000Z | 2022-03-16T12:44:07.000Z | src/planner/insert_plan.cpp | vittvolt/15721-peloton | 3394c745ce5f3d71d1d71a09c700d5e367345e2e | [
"Apache-2.0"
] | null | null | null | src/planner/insert_plan.cpp | vittvolt/15721-peloton | 3394c745ce5f3d71d1d71a09c700d5e367345e2e | [
"Apache-2.0"
] | 2 | 2017-03-30T00:43:50.000Z | 2021-07-21T06:27:44.000Z |
//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// insert_plan.cpp
//
// Identification: /peloton/src/planner/insert_plan.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "planner/insert_plan.h"
#include "catalog/catalog.h"
#include "catalog/column.h"
#include "type/value.h"
#include "parser/insert_statement.h"
#include "parser/select_statement.h"
#include "planner/project_info.h"
#include "storage/data_table.h"
#include "storage/tuple.h"
namespace peloton {
namespace planner {
InsertPlan::InsertPlan(storage::DataTable *table, oid_t bulk_insert_count)
: target_table_(table), bulk_insert_count(bulk_insert_count) {}
// This constructor takes in a project info
InsertPlan::InsertPlan(
storage::DataTable *table,
std::unique_ptr<const planner::ProjectInfo> &&project_info,
oid_t bulk_insert_count)
: target_table_(table),
project_info_(std::move(project_info)),
bulk_insert_count(bulk_insert_count) {}
// This constructor takes in a tuple
InsertPlan::InsertPlan(storage::DataTable *table,
std::unique_ptr<storage::Tuple> &&tuple,
oid_t bulk_insert_count)
: target_table_(table), bulk_insert_count(bulk_insert_count) {
tuples_.push_back(std::move(tuple));
LOG_TRACE("Creating an Insert Plan");
}
InsertPlan::InsertPlan(
storage::DataTable *table, std::vector<char *> *columns,
std::vector<std::vector<peloton::expression::AbstractExpression *> *> *
insert_values)
: bulk_insert_count(insert_values->size()) {
parameter_vector_.reset(new std::vector<std::tuple<oid_t, oid_t, oid_t>>());
params_value_type_.reset(new std::vector<type::Type::TypeId>);
target_table_ = table;
if (target_table_) {
const catalog::Schema *table_schema = target_table_->GetSchema();
// INSERT INTO table_name VALUES (val2, val2, ...)
if (columns == NULL) {
for (uint32_t tuple_idx = 0; tuple_idx < insert_values->size();
tuple_idx++) {
auto values = (*insert_values)[tuple_idx];
PL_ASSERT(values->size() == table_schema->GetColumnCount());
std::unique_ptr<storage::Tuple> tuple(
new storage::Tuple(table_schema, true));
int col_cntr = 0;
int param_index = 0;
for (expression::AbstractExpression *elem : *values) {
if (elem->GetExpressionType() == ExpressionType::VALUE_PARAMETER) {
std::tuple<oid_t, oid_t, oid_t> pair =
std::make_tuple(tuple_idx, col_cntr, param_index++);
parameter_vector_->push_back(pair);
params_value_type_->push_back(
table_schema->GetColumn(col_cntr).GetType());
} else {
expression::ConstantValueExpression *const_expr_elem =
dynamic_cast<expression::ConstantValueExpression *>(elem);
type::Value const_expr_elem_val = (const_expr_elem->GetValue());
switch (const_expr_elem->GetValueType()) {
case type::Type::VARCHAR:
case type::Type::VARBINARY:
tuple->SetValue(col_cntr, const_expr_elem_val, GetPlanPool());
break;
default: {
tuple->SetValue(col_cntr, const_expr_elem_val, nullptr);
}
}
}
++col_cntr;
}
tuples_.push_back(std::move(tuple));
}
}
// INSERT INTO table_name (col1, col2, ...) VALUES (val1, val2, ...);
else {
// columns has to be less than or equal that of schema
for (uint32_t tuple_idx = 0; tuple_idx < insert_values->size();
tuple_idx++) {
auto values = (*insert_values)[tuple_idx];
PL_ASSERT(columns->size() <= table_schema->GetColumnCount());
std::unique_ptr<storage::Tuple> tuple(
new storage::Tuple(table_schema, true));
int col_cntr = 0;
int param_index = 0;
auto &table_columns = table_schema->GetColumns();
auto query_columns = columns;
for (catalog::Column const &elem : table_columns) {
std::size_t pos = std::find(query_columns->begin(),
query_columns->end(), elem.GetName()) -
query_columns->begin();
// If the column does not exist, insert a null value
if (pos >= query_columns->size()) {
tuple->SetValue(col_cntr, type::ValueFactory::GetNullValueByType(
elem.GetType()),
nullptr);
} else {
// If it's varchar or varbinary then use data pool, otherwise
// allocate
// inline
auto data_pool = GetPlanPool();
if (elem.GetType() != type::Type::VARCHAR &&
elem.GetType() != type::Type::VARBINARY)
data_pool = nullptr;
LOG_TRACE(
"Column %d found in INSERT query, ExpressionType: %s", col_cntr,
ExpressionTypeToString(values->at(pos)->GetExpressionType())
.c_str());
if (values->at(pos)->GetExpressionType() ==
ExpressionType::VALUE_PARAMETER) {
std::tuple<oid_t, oid_t, oid_t> pair =
std::make_tuple(tuple_idx, col_cntr, param_index);
parameter_vector_->push_back(pair);
params_value_type_->push_back(
table_schema->GetColumn(col_cntr).GetType());
++param_index;
} else {
expression::ConstantValueExpression *const_expr_elem =
dynamic_cast<expression::ConstantValueExpression *>(
values->at(pos));
type::Value val = (const_expr_elem->GetValue());
tuple->SetValue(col_cntr, val, data_pool);
}
}
++col_cntr;
}
LOG_TRACE("Tuple to be inserted: %s", tuple->GetInfo().c_str());
tuples_.push_back(std::move(tuple));
}
}
} else {
LOG_TRACE("Table does not exist!");
}
}
type::AbstractPool *InsertPlan::GetPlanPool() {
// construct pool if needed
if (pool_.get() == nullptr)
pool_.reset(new type::EphemeralPool());
// return pool
return pool_.get();
}
void InsertPlan::SetParameterValues(std::vector<type::Value> *values) {
PL_ASSERT(values->size() == parameter_vector_->size());
LOG_TRACE("Set Parameter Values in Insert");
for (unsigned int i = 0; i < values->size(); ++i) {
auto param_type = params_value_type_->at(i);
auto &put_loc = parameter_vector_->at(i);
auto value = values->at(std::get<2>(put_loc));
// LOG_TRACE("Setting value of type %s",
// ValueTypeToString(param_type).c_str());
switch (param_type) {
case type::Type::VARBINARY:
case type::Type::VARCHAR: {
type::Value val = (value.CastAs(param_type));
tuples_[std::get<0>(put_loc)]
->SetValue(std::get<1>(put_loc), val, GetPlanPool());
break;
}
default: {
type::Value val = (value.CastAs(param_type));
tuples_[std::get<0>(put_loc)]
->SetValue(std::get<1>(put_loc), val, nullptr);
}
}
}
}
}
}
| 37.42132 | 80 | 0.582339 | vittvolt |
6bd1f664608392956ecb975849d95fe25a09be4b | 144 | cpp | C++ | src/app.cpp | overworks/MhGameLib | 87973e29633ed09a3fa51eb27ea7fc8af5e9d71b | [
"MIT"
] | null | null | null | src/app.cpp | overworks/MhGameLib | 87973e29633ed09a3fa51eb27ea7fc8af5e9d71b | [
"MIT"
] | null | null | null | src/app.cpp | overworks/MhGameLib | 87973e29633ed09a3fa51eb27ea7fc8af5e9d71b | [
"MIT"
] | null | null | null | #include <mh/app.hpp>
namespace Mh
{
App::App()
: m_client_width(0), m_client_height(0), m_current_renderer(nullptr)
{}
App::~App()
{}
} | 13.090909 | 70 | 0.652778 | overworks |
6bd2150707a370bf4806990ee933594e166545c9 | 19,085 | hpp | C++ | include/asioex/async.hpp | madmongo1/asio_experiments | 4ed09b5fc1e3fe2597346d87cdcccc11f70d7d7f | [
"BSL-1.0"
] | 1 | 2022-01-25T04:10:59.000Z | 2022-01-25T04:10:59.000Z | include/asioex/async.hpp | madmongo1/asio_experiments | 4ed09b5fc1e3fe2597346d87cdcccc11f70d7d7f | [
"BSL-1.0"
] | null | null | null | include/asioex/async.hpp | madmongo1/asio_experiments | 4ed09b5fc1e3fe2597346d87cdcccc11f70d7d7f | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2022 Klemens D. Morgenstern
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef ASIO_EXPERIMENTS_ASYNC_HPP
#define ASIO_EXPERIMENTS_ASYNC_HPP
#include <asio/compose.hpp>
#include <asio/post.hpp>
#include <asio/dispatch.hpp>
#include <asio/experimental/deferred.hpp>
#include <asio/use_awaitable.hpp>
#include <asio/experimental/as_tuple.hpp>
#include <asio/this_coro.hpp>
#include <coroutine>
#include <boost/mp11/algorithm.hpp>
#include <boost/mp11/list.hpp>
#include <boost/preprocessor/repeat.hpp>
#include <boost/preprocessor/repeat_2nd.hpp>
#include <optional>
#include <variant>
namespace asio
{
template<typename E>
struct use_awaitable_t;
namespace experimental
{
template<typename E>
struct use_coro_t;
}
}
namespace asioex
{
template < typename... Signatures >
struct compose_tag
{
};
namespace detail
{
template < typename T >
constexpr auto
compose_token_impl(const T *)
{
return asio::experimental::deferred;
}
template < typename Executor >
constexpr auto
compose_token_impl(const asio::use_awaitable_t< Executor > *)
{
return asio::experimental::as_tuple(asio::use_awaitable_t< Executor >());
}
template < typename T >
constexpr auto
compose_token_impl(const asio::experimental::use_coro_t< T > *)
{
return asio::experimental::as_tuple(asio::experimental::use_coro_t< T >());
}
template < template < class Token, class... > class Modifier,
class Token,
class... Ts >
constexpr auto
compose_token_impl(
const Modifier< Token, Ts... > *,
typename asio::constraint< !std::is_void< Token >::value >::type = 0)
{
return compose_token_impl(static_cast< const Token * >(nullptr));
}
}
template < typename T >
constexpr auto
compose_token(const T & val)
{
return detail::compose_token_impl(&val);
}
namespace detail
{
template<typename T>
auto foo(T&&);
template<typename Token>
auto pick_executor(Token && token)
{
return asio::get_associated_executor(token);
}
template<typename Token,
typename First,
typename ... IoObjectsOrExecutors>
auto pick_executor(Token && token,
const First & first,
IoObjectsOrExecutors && ... io_objects_or_executors)
-> typename std::enable_if<
asio::is_executor<First>::value || asio::execution::is_executor<First>::value
,First >::type
{
return first;
}
template<typename Token,
typename First,
typename ... IoObjectsOrExecutors>
auto pick_executor(Token && token,
First & first,
IoObjectsOrExecutors && ... io_objects_or_executors)
-> typename First::executor_type
{
return first.get_executor();
}
template<typename Token,
typename First,
typename ... IoObjectsOrExecutors>
auto pick_executor(Token && token,
First &&,
IoObjectsOrExecutors && ... io_objects_or_executors)
{
return pick_executor(std::forward<Token>(token),
std::forward<IoObjectsOrExecutors>(io_objects_or_executors)...);
}
template<typename Derived, typename Signature>
struct compose_promise_base;
template<typename Derived, typename ... Args>
struct compose_promise_base<Derived, void(Args...)>
{
void return_value(std::tuple<Args...> args)
{
static_cast<Derived*>(this)->result_ = std::move(args);
}
using tuple_type = std::tuple<Args...>;
};
template<typename Return, typename Tag, typename Token, typename ... Args>
struct compose_promise;
template<typename Allocator, typename Tag, typename Token, typename ... Args>
struct compose_promise_alloc_base
{
using allocator_type = Allocator;
void* operator new(const std::size_t size,
Args & ... args, Token & tk,
Tag)
{
using alloc_type = typename std::allocator_traits<allocator_type>:: template rebind_alloc<unsigned char>;
alloc_type alloc{asio::get_associated_allocator(tk)};
const auto align_needed = size % alignof(alloc_type);
const auto align_offset = align_needed != 0 ? alignof(alloc_type) - align_needed : 0ull;
const auto alloc_size = size + sizeof(alloc_type) + align_offset;
const auto raw = std::allocator_traits<alloc_type>::allocate(alloc, alloc_size);
new (raw + size + align_offset) alloc_type(std::move(alloc));
return raw;
}
void operator delete(void * raw_,
std::size_t size)
{
using alloc_type = typename std::allocator_traits<allocator_type>:: template rebind_alloc<unsigned char>;
const auto raw = static_cast<unsigned char *>(raw_);
const auto align_needed = size % alignof(alloc_type);
const auto align_offset = align_needed != 0 ? alignof(alloc_type) - align_needed : 0ull;
const auto alloc_size = size + sizeof(alloc_type) + align_offset;
auto alloc_p = reinterpret_cast<alloc_type*>(raw + size + align_offset);
auto alloc = std::move(*alloc_p);
alloc_p->~alloc_type();
std::allocator_traits<alloc_type>::deallocate(alloc, raw, alloc_size);
}
};
template<typename Tag, typename Token, typename ... Args>
struct compose_promise_alloc_base<std::allocator<void>, Tag, Token, Args...>
{
};
template<typename Return, typename ...Sigs, typename Token, typename ... Args>
struct compose_promise<Return, compose_tag<Sigs...>, Token, Args...>
:
compose_promise_alloc_base<
asio::associated_allocator_t<std::decay_t<Token>>, compose_tag<Sigs...>, Token, Args...>,
compose_promise_base<compose_promise<Return, compose_tag<Sigs...>, Token, Args...>, Sigs> ...
{
using my_type = compose_promise<Return, compose_tag<Sigs...>, Token, Args...>;
using compose_promise_base<my_type, Sigs> ::return_value ...;
using result_type = std::variant<typename compose_promise_base<my_type, Sigs>::tuple_type ...>;
using token_type = std::decay_t<Token>;
std::optional<result_type> result_;
token_type token;
using allocator_type = asio::associated_allocator_t<token_type>;
asio::cancellation_state state{
asio::get_associated_cancellation_slot(token),
asio::enable_terminal_cancellation()
};
using executor_type =
typename asio::prefer_result<
decltype(pick_executor(std::declval<Token>(), std::declval<Args>()...)),
asio::execution::outstanding_work_t::tracked_t>::type;
executor_type executor_;
bool did_suspend = false;
#if defined(__clang__) || defined(_MSC_FULL_VER)
compose_promise(Args &... args, Token & tk, const compose_tag<Sigs...> &)
: token(static_cast<Token>(tk)), executor_(
asio::prefer(
pick_executor(token, args...),
asio::execution::outstanding_work.tracked))
{
}
#else
compose_promise(Args &... args, Token && tk, const compose_tag<Sigs...> &)
: token(static_cast<Token>(tk)), executor_(
asio::prefer(
pick_executor(token, args...),
asio::execution::outstanding_work.tracked))
{
}
#endif
~compose_promise()
{
if (completion && result_)
std::visit(
[this](auto & tup)
{
auto cpl =
[tup = std::move(tup),
completion = std::move(*completion)]() mutable
{
std::apply(std::move(completion), std::move(tup));
};
if (did_suspend)
asio::dispatch(executor_, std::move(cpl));
else
asio::post(executor_, std::move(cpl));
}, *result_);
}
constexpr static std::suspend_never initial_suspend() noexcept { return {}; }
constexpr static std::suspend_never final_suspend() noexcept { return {}; }
template<typename ... Args_, typename ... Ts>
auto await_transform(asio::experimental::deferred_async_operation<void(Args_...), Ts...> op)
{
struct result
{
asio::experimental::deferred_async_operation<void(Args_...), Ts...> op;
compose_promise * self;
std::tuple<Args_...> res;
struct completion
{
compose_promise * self;
std::tuple<Args_...> &result;
std::unique_ptr<void, coro_delete> coro_handle;
using cancellation_slot_type = asio::cancellation_slot;
cancellation_slot_type get_cancellation_slot() const noexcept
{
return self->state.slot();
}
using executor_type = typename compose_promise::executor_type;
executor_type get_executor() const noexcept
{
return self->executor_;
}
using allocator_type = typename compose_promise::allocator_type;
allocator_type get_allocator() const noexcept
{
return asio::get_associated_allocator(self->token);
}
void operator()(Args_ ... args)
{
self->did_suspend = true;
result = {std::move(args)...};
std::coroutine_handle<compose_promise>::from_address(coro_handle.release()).resume();
}
};
bool await_ready() { return false; }
void await_suspend( std::coroutine_handle<compose_promise> h)
{
std::move(op)(completion{self, res, {h.address(), coro_delete{}}});
}
std::tuple<Args_...> await_resume()
{
return std::move(res);
}
};
return result{std::move(op), this};
};
struct coro_delete
{
void operator()(void * c)
{
if (c != nullptr)
std::coroutine_handle<compose_promise>::from_address(c).destroy();
}
};
auto await_transform(asio::this_coro::executor_t) const
{
struct exec_helper
{
const executor_type& value;
constexpr static bool await_ready() noexcept
{
return true;
}
constexpr static void await_suspend(std::coroutine_handle<>) noexcept
{
}
executor_type await_resume() const noexcept
{
return value;
}
};
return exec_helper{executor_};
}
auto await_transform(asio::this_coro::cancellation_state_t) const
{
struct exec_helper
{
const asio::cancellation_state& value;
constexpr static bool await_ready() noexcept
{
return true;
}
constexpr static void await_suspend(std::coroutine_handle<>) noexcept
{
}
asio::cancellation_state await_resume() const noexcept
{
return value;
}
};
return exec_helper{state};
}
// This await transformation resets the associated cancellation state.
auto await_transform(asio::this_coro::reset_cancellation_state_0_t) noexcept
{
struct result
{
asio::cancellation_state &state;
token_type & token;
bool await_ready() const noexcept
{
return true;
}
void await_suspend(std::coroutine_handle<void>) noexcept
{
}
auto await_resume() const
{
state = asio::cancellation_state(asio::get_associated_cancellation_slot(token));
}
};
return result{state, token};
}
// This await transformation resets the associated cancellation state.
template <typename Filter>
auto await_transform(
asio::this_coro::reset_cancellation_state_1_t<Filter> reset) noexcept
{
struct result
{
asio::cancellation_state & state;
Filter filter_;
token_type & token;
bool await_ready() const noexcept
{
return true;
}
void await_suspend(std::coroutine_handle<void>) noexcept
{
}
auto await_resume()
{
state = asio::cancellation_state(
asio::get_associated_cancellation_slot(token),
ASIO_MOVE_CAST(Filter)(filter_));
}
};
return result{state, ASIO_MOVE_CAST(Filter)(reset.filter), token};
}
// This await transformation resets the associated cancellation state.
template <typename InFilter, typename OutFilter>
auto await_transform(
asio::this_coro::reset_cancellation_state_2_t<InFilter, OutFilter> reset)
noexcept
{
struct result
{
asio::cancellation_state & state;
InFilter in_filter_;
OutFilter out_filter_;
token_type & token;
bool await_ready() const noexcept
{
return true;
}
void await_suspend(std::coroutine_handle<void>) noexcept
{
}
auto await_resume()
{
state = asio::cancellation_state(
asio::get_associated_cancellation_slot(token),
ASIO_MOVE_CAST(InFilter)(in_filter_),
ASIO_MOVE_CAST(OutFilter)(out_filter_));
}
};
return result{state,
ASIO_MOVE_CAST(InFilter)(reset.in_filter),
ASIO_MOVE_CAST(OutFilter)(reset.out_filter),
token};
}
auto get_return_object() -> Return
{
return asio::async_initiate<Token, Sigs...>(
[this](auto tk)
{
completion.emplace(std::move(tk));
}, token);
}
void unhandled_exception()
{
// mangle it onto the executor so the coro dies safely
asio::post(executor_,
[ex = std::current_exception()]
{
std::rethrow_exception(ex);
});
}
// TODO implement for overloads
using completion_type = typename asio::async_completion<Token, Sigs...>::completion_handler_type;
std::optional<completion_type> completion;
};
template<typename Return, typename Executor, typename Tag, typename Token, typename ... Args>
struct awaitable_compose_promise;
template<typename Return, typename Executor, typename ... Args_, typename Token, typename ... Args>
struct awaitable_compose_promise<Return, Executor, compose_tag<void(Args_...)>, Token, Args...>
: std::coroutine_traits<asio::awaitable<Return, Executor>>::promise_type
{
using base_type = typename std::coroutine_traits<asio::awaitable<Return, Executor>>::promise_type;
void return_value_impl(asio::error_code ec, Return && result)
{
if (ec)
this->set_error(ec);
else
this->base_type::return_value(std::move(result));
}
void return_value_impl(std::exception_ptr e, Return && result)
{
if (e)
this->set_except(e);
else
this->base_type::return_value(std::move(result));
}
auto return_value(std::tuple<Args_ ...> result)
{
if constexpr (std::is_same_v<Return, std::tuple<Args_...>>)
this->base_type::return_value(std::forward<Return>(result));
else
std::apply(
[this](auto ... args)
{
return_value_impl(std::move(args)...);
}, std::move(result));
}
void unhandled_exception()
{
throw ;
}
};
struct void_t {};
template<typename Executor, typename ... Args_, typename Token, typename ... Args>
struct awaitable_compose_promise<void, Executor, compose_tag<void(Args_...)>, Token, Args...>
: std::coroutine_traits<asio::awaitable<void_t, Executor>>::promise_type
{
using base_type = typename std::coroutine_traits<asio::awaitable<void_t, Executor>>::promise_type;
asio::awaitable<void, Executor> get_return_object() noexcept
{
co_await base_type::get_return_object();
};
void return_value_impl(asio::error_code ec)
{
if (ec)
this->set_error(ec);
else
this->base_type::return_value(void_t{});
}
template<typename = void>
void return_value_impl(std::exception_ptr e)
{
if (e)
this->set_except(e);
else
this->base_type::return_value(void_t{});
}
auto return_value(std::tuple<Args_ ...> result)
{
if constexpr (sizeof...(Args_))
this->base_type::return_value(void_t{});
else
std::apply(
[this](auto ... args)
{
return_value_impl(std::move(args)...);
}, std::move(result));
}
void unhandled_exception()
{
throw ;
}
};
}
}
namespace std
{
// this is hack AF
template<typename Return, typename Executor, typename Tag, typename Token, typename ... Args>
struct coroutine_handle<asioex::detail::awaitable_compose_promise<Return, Executor, Tag, Token, Args...>>
: coroutine_handle<typename std::coroutine_traits<asio::awaitable<Return, Executor>>::promise_type>
{
};
#define ASIOEX_TYPENAME(z, n, text) , typename T##n
#define ASIOEX_SPEC(z, n, text) , T##n
#define ASIOEX_TRAIT_DECL(z, n, text) \
template<typename Return BOOST_PP_REPEAT_2ND(n, ASIOEX_TYPENAME, ), typename Token, typename ... Sigs > \
struct coroutine_traits<Return BOOST_PP_REPEAT_2ND(n, ASIOEX_SPEC, ), Token, asioex::compose_tag<Sigs...>> \
{ \
using promise_type = asioex::detail::compose_promise< \
Return, asioex::compose_tag<Sigs...>, Token \
BOOST_PP_REPEAT_2ND(n, ASIOEX_SPEC, )>; \
};
BOOST_PP_REPEAT(24, ASIOEX_TRAIT_DECL, );
#define ASIOEX_AW_TRAIT_DECL(z, n, text) \
template<typename Return, typename Executor BOOST_PP_REPEAT_2ND(n, ASIOEX_TYPENAME, ), typename Token, typename ... Sigs > \
struct coroutine_traits<asio::awaitable<Return, Executor> BOOST_PP_REPEAT_2ND(n, ASIOEX_SPEC, ), Token, asioex::compose_tag<Sigs...>> \
{ \
using promise_type = asioex::detail::awaitable_compose_promise< \
Return, Executor, asioex::compose_tag<Sigs...>, Token \
BOOST_PP_REPEAT_2ND(n, ASIOEX_SPEC, )>; \
};
BOOST_PP_REPEAT(24, ASIOEX_AW_TRAIT_DECL, );
#undef ASIOEX_TYPENAME
#undef ASIOEX_SPEC
#undef ASIOEX_TRAIT_DECL
}
#endif // ASIO_EXPERIMENTS_ASYNC_HPP
| 29.316436 | 135 | 0.599266 | madmongo1 |
6bd67c6ee4af56160e99eb4384240e18ddaa27d0 | 3,491 | cc | C++ | chromium/ui/views/widget/desktop_widget_unittest.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | 27 | 2016-04-27T01:02:03.000Z | 2021-12-13T08:53:19.000Z | chromium/ui/views/widget/desktop_widget_unittest.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | 2 | 2017-03-09T09:00:50.000Z | 2017-09-21T15:48:20.000Z | chromium/ui/views/widget/desktop_widget_unittest.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | 17 | 2016-04-27T02:06:39.000Z | 2019-12-18T08:07:00.000Z | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/test/views_test_base.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/dialog_delegate.h"
namespace views {
typedef ViewsTestBase DesktopScreenPositionClientTest;
// Verifies setting the bounds of a dialog parented to a Widget with a
// PlatformDesktopNativeWidget is positioned correctly.
TEST_F(DesktopScreenPositionClientTest, PositionDialog) {
Widget parent_widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.bounds = gfx::Rect(10, 11, 200, 200);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.native_widget = new PlatformDesktopNativeWidget(&parent_widget);
parent_widget.Init(params);
// Owned by |dialog|.
DialogDelegateView* dialog_delegate_view = new DialogDelegateView;
// Owned by |parent_widget|.
Widget* dialog = DialogDelegate::CreateDialogWidget(
dialog_delegate_view, NULL, parent_widget.GetNativeView());
dialog->SetBounds(gfx::Rect(11, 12, 200, 200));
EXPECT_EQ("11,12", dialog->GetWindowBoundsInScreen().origin().ToString());
}
// Verifies that setting the bounds of a control parented to something other
// than the root window is positioned correctly.
TEST_F(DesktopScreenPositionClientTest, PositionControlWithNonRootParent) {
Widget widget1;
Widget widget2;
Widget widget3;
gfx::Point origin = gfx::Point(16, 16);
// Use a custom frame type. By default we will choose a native frame when
// aero glass is enabled, and this complicates the logic surrounding origin
// computation, making it difficult to compute the expected origin location.
widget1.set_frame_type(Widget::FRAME_TYPE_FORCE_CUSTOM);
widget2.set_frame_type(Widget::FRAME_TYPE_FORCE_CUSTOM);
widget3.set_frame_type(Widget::FRAME_TYPE_FORCE_CUSTOM);
// Create 3 windows. A root window, an arbitrary window parented to the root
// but NOT positioned at (0,0) relative to the root, and then a third window
// parented to the second, also not positioned at (0,0).
Widget::InitParams params1 =
CreateParams(Widget::InitParams::TYPE_WINDOW);
params1.bounds = gfx::Rect(origin, gfx::Size(700, 600));
params1.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params1.native_widget = new PlatformDesktopNativeWidget(&widget1);
widget1.Init(params1);
Widget::InitParams params2 =
CreateParams(Widget::InitParams::TYPE_WINDOW);
params2.bounds = gfx::Rect(origin, gfx::Size(600, 500));
params2.parent = widget1.GetNativeView();
params2.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params2.child = true;
widget2.Init(params2);
Widget::InitParams params3 =
CreateParams(Widget::InitParams::TYPE_CONTROL);
params3.parent = widget2.GetNativeView();
params3.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params3.child = true;
params3.bounds = gfx::Rect(origin, gfx::Size(500, 400));
widget3.Init(params3);
// The origin of the 3rd window should be the sum of all parent origins.
gfx::Point expected_origin(origin.x() * 3, origin.y() * 3);
gfx::Rect expected_bounds(expected_origin, gfx::Size(500, 400));
gfx::Rect actual_bounds(widget3.GetWindowBoundsInScreen());
EXPECT_EQ(expected_bounds.ToString(), actual_bounds.ToString());
}
} // namespace views
| 42.573171 | 79 | 0.761386 | wedataintelligence |
6bd6b2d10da7b45da59bc08522f75daf082cae37 | 950 | cpp | C++ | src/rtcore/ICamera.cpp | potato3d/rtrt2 | 5c135c1aea0ded2898e16220cec5ed2860dcc9b3 | [
"MIT"
] | 1 | 2021-11-06T06:13:05.000Z | 2021-11-06T06:13:05.000Z | src/rtcore/ICamera.cpp | potato3d/rtrt2 | 5c135c1aea0ded2898e16220cec5ed2860dcc9b3 | [
"MIT"
] | null | null | null | src/rtcore/ICamera.cpp | potato3d/rtrt2 | 5c135c1aea0ded2898e16220cec5ed2860dcc9b3 | [
"MIT"
] | null | null | null | #include <rti/ICamera.h>
using namespace rti;
void ICamera::translate( float x, float y, float z )
{
// avoid warnings
x;y;z;
}
void ICamera::rotate( float radians, uint32 axis )
{
// avoid warnings
radians;axis;
}
void ICamera::setLookAt( float eyeX, float eyeY, float eyeZ,
float centerX, float centerY, float centerZ,
float upX, float upY, float upZ )
{
// avoid warnings
eyeX;eyeY;eyeZ;centerX;centerY;centerZ;upX;upY;upZ;
}
void ICamera::setPerspective( float fovY, float zNear, float zFar )
{
// avoid warnings
fovY;zNear;zFar;
}
void ICamera::setViewport( uint32 width, uint32 height )
{
// avoid warnings
width;height;
}
void ICamera::getViewport( uint32& width, uint32& height )
{
width = 0;
height = 0;
}
void ICamera::getRayOrigin( vr::vec3f& origin, float x, float y )
{
origin.set( 0, 0, 0 );
}
void ICamera::getRayDirection( vr::vec3f& dir, float x, float y )
{
dir.set( 0, 0, 0 );
}
| 18.269231 | 67 | 0.670526 | potato3d |
6bd710168637674b6d3df69830b4e992e2140114 | 1,736 | cpp | C++ | test/main.cpp | tdegeus/VTKHighFive | c92a00a778f37432142f70075f2c736aedad7f5c | [
"MIT"
] | 2 | 2021-02-21T21:23:11.000Z | 2021-02-24T09:00:01.000Z | test/main.cpp | tdegeus/VTKHighFive | c92a00a778f37432142f70075f2c736aedad7f5c | [
"MIT"
] | 6 | 2020-06-09T11:24:50.000Z | 2021-02-22T13:37:17.000Z | test/main.cpp | tdegeus/VTKHighFive | c92a00a778f37432142f70075f2c736aedad7f5c | [
"MIT"
] | null | null | null |
#define CATCH_CONFIG_MAIN // tells Catch to provide a main() - only do this in one cpp file
#include <catch2/catch.hpp>
#include <GooseFEM/GooseFEM.h>
#include <highfive/H5Easy.hpp>
#define XDMFWRITE_HIGHFIVE_INDENT 0
#include <XDMFWrite_HighFive.hpp>
namespace xh = XDMFWrite_HighFive;
TEST_CASE("XDMFWrite_HighFive", "Basic")
{
SECTION("version")
{
std::cout << xh::version() << std::endl;
}
SECTION("GooseFEM - detail")
{
{
auto t = GooseFEM::Mesh::ElementType::Tri3;
REQUIRE(xh::detail::to<decltype(t)>::str(t) == "Triangle");
}
{
auto t = GooseFEM::Mesh::ElementType::Quad4;
REQUIRE(xh::detail::to<decltype(t)>::str(t) == "Quadrilateral");
}
{
auto t = GooseFEM::Mesh::ElementType::Hex8;
REQUIRE(xh::detail::to<decltype(t)>::str(t) == "Hexahedron");
}
}
SECTION("GooseFEM - mesh")
{
H5Easy::File file("tmp.h5", H5Easy::File::Overwrite);
GooseFEM::Mesh::Quad4::Regular mesh(3, 3);
H5Easy::dump(file, "/coor", mesh.coor());
H5Easy::dump(file, "/conn", mesh.conn());
std::vector<std::string> t = {
"<Topology NumberOfElements=\"9\" TopologyType=\"Quadrilateral\">",
"<DataItem Dimensions=\"9 4\" Format=\"HDF\">tmp.h5:/conn</DataItem>",
"</Topology>"};
std::vector<std::string> g = {
"<Geometry GeometryType=\"XY\">",
"<DataItem Dimensions=\"16 2\" Format=\"HDF\">tmp.h5:/coor</DataItem>",
"</Geometry>"};
REQUIRE(t == xh::Topology(file, "/conn", mesh.getElementType()));
REQUIRE(g == xh::Geometry(file, "/coor"));
}
}
| 28.459016 | 92 | 0.554724 | tdegeus |
6bd7be057a7b8fc1ffa799e2aeb17f7b363b1d33 | 16,353 | cpp | C++ | src/ARIA/ArRangeBuffer.cpp | rzsavilla/Robot_PathPlanning | 7ca805b917824ecaf8f12a950b1f77bd76ac5836 | [
"MIT"
] | 1 | 2018-10-13T02:50:25.000Z | 2018-10-13T02:50:25.000Z | src/ARIA/ArRangeBuffer.cpp | rzsavilla/Robot_PathPlanning | 7ca805b917824ecaf8f12a950b1f77bd76ac5836 | [
"MIT"
] | null | null | null | src/ARIA/ArRangeBuffer.cpp | rzsavilla/Robot_PathPlanning | 7ca805b917824ecaf8f12a950b1f77bd76ac5836 | [
"MIT"
] | 1 | 2018-10-13T02:50:26.000Z | 2018-10-13T02:50:26.000Z | /*
MobileRobots Advanced Robotics Interface for Applications (ARIA)
Copyright (C) 2004, 2005 ActivMedia Robotics LLC
Copyright (C) 2006, 2007, 2008, 2009 MobileRobots Inc.
Copyright (C) 2010, 2011 Adept Technology, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
robots@mobilerobots.com or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; 800-639-9481
*/
#include "ArExport.h"
#include "ariaOSDef.h"
#include "ArRangeBuffer.h"
#include "ArLog.h"
/** @param size The size of the buffer, in number of readings */
AREXPORT ArRangeBuffer::ArRangeBuffer(int size)
{
mySize = size;
}
AREXPORT ArRangeBuffer::~ArRangeBuffer()
{
ArUtil::deleteSet(myBuffer.begin(), myBuffer.end());
ArUtil::deleteSet(myInvalidBuffer.begin(), myInvalidBuffer.end());
}
AREXPORT size_t ArRangeBuffer::getSize(void) const
{
return mySize;
}
AREXPORT ArPose ArRangeBuffer::getPoseTaken() const
{
return myBufferPose;
}
AREXPORT void ArRangeBuffer::setPoseTaken(ArPose p)
{
myBufferPose = p;
}
AREXPORT ArPose ArRangeBuffer::getEncoderPoseTaken() const
{
return myEncoderBufferPose;
}
AREXPORT void ArRangeBuffer::setEncoderPoseTaken(ArPose p)
{
myEncoderBufferPose = p;
}
/**
If the new size is smaller than the current buffer it chops off the
readings that are excess from the oldest readings... if the new size
is larger then it just leaves room for the buffer to grow
@param size number of readings to set the buffer to
*/
AREXPORT void ArRangeBuffer::setSize(size_t size)
{
mySize = size;
// if its smaller then chop the lists down to size
while (myInvalidBuffer.size() + myBuffer.size() > mySize)
{
if ((myRevIterator = myInvalidBuffer.rbegin()) != myInvalidBuffer.rend())
{
myReading = (*myRevIterator);
myInvalidBuffer.pop_back();
delete myReading;
}
else if ((myRevIterator = myBuffer.rbegin()) != myBuffer.rend())
{
myReading = (*myRevIterator);
myBuffer.pop_back();
delete myReading;
}
}
}
/**
This function returns a pointer to a list that has all of the readings
in it. This list is mostly for reference, ie for finding some
particular value or for using the readings to draw them. Don't do
any modification at all to the list unless you really know what you're
doing... and if you do you'd better lock the rangeDevice this came from
so nothing messes with the list while you are doing so.
@return the list of positions this range buffer has
*/
AREXPORT const std::list<ArPoseWithTime *> *ArRangeBuffer::getBuffer(void) const
{
return &myBuffer;
}
/**
This function returns a pointer to a list that has all of the readings
in it. This list is mostly for reference, ie for finding some
particular value or for using the readings to draw them. Don't do
any modification at all to the list unless you really know what you're
doing... and if you do you'd better lock the rangeDevice this came from
so nothing messes with the list while you are doing so.
@return the list of positions this range buffer has
*/
AREXPORT std::list<ArPoseWithTime *> *ArRangeBuffer::getBuffer(void)
{
return &myBuffer;
}
/**
Gets the closest reading in a region defined by startAngle going to
endAngle... going counterclockwise (neg degrees to poseitive... with
how the robot is set up, thats counterclockwise)... from -180 to 180...
this means if you want the slice between 0 and 10 degrees,
you must enter it as 0, 10, if you do 10, 0 you'll get the 350 degrees
between 10 and 0... be especially careful with negative... for example
-30 to -60 is everything from -30, around through 0, 90, and 180 back to
-60... since -60 is actually to clockwise of -30
@param startAngle where to start the slice
@param endAngle where to end the slice, going clockwise from startAngle
@param startPos the position to find the closest reading to (usually
the robots position)
@param maxRange the maximum range to return (and what to return if nothing
found)
@param angle a pointer return of the angle to the found reading
@return if the return is >= 0 and <= maxRange then this is the distance
to the closest reading, if it is >= maxRange, then there was no reading
in the given section
*/
AREXPORT double ArRangeBuffer::getClosestPolar(double startAngle,
double endAngle,
ArPose startPos,
unsigned int maxRange,
double *angle) const
{
return getClosestPolarInList(startAngle, endAngle,
startPos, maxRange, angle, &myBuffer);
}
AREXPORT double ArRangeBuffer::getClosestPolarInList(
double startAngle, double endAngle, ArPose startPos,
unsigned int maxRange, double *angle,
const std::list<ArPoseWithTime *> *buffer)
{
double closest;
bool foundOne = false;
std::list<ArPoseWithTime *>::const_iterator it;
ArPoseWithTime *reading;
double th;
double closeTh;
double dist;
double angle1, angle2;
startAngle = ArMath::fixAngle(startAngle);
endAngle = ArMath::fixAngle(endAngle);
for (it = buffer->begin(); it != buffer->end(); ++it)
{
reading = (*it);
angle1=startPos.findAngleTo(*reading);
angle2=startPos.getTh();
th = ArMath::subAngle(angle1, angle2);
if (ArMath::angleBetween(th, startAngle, endAngle))
{
if (!foundOne || (dist = reading->findDistanceTo(startPos)) < closest)
{
closeTh = th;
if (!foundOne)
closest = reading->findDistanceTo(startPos);
else
closest = dist;
foundOne = true;
}
}
}
if (!foundOne)
return maxRange;
if (angle != NULL)
*angle = closeTh;
if (closest > maxRange)
return maxRange;
else
return closest;
}
/**
Gets the closest reading in a region defined by two points (opposeite points
of a rectangle).
@param x1 the x coordinate of one of the rectangle points
@param y1 the y coordinate of one of the rectangle points
@param x2 the x coordinate of the other rectangle point
@param y2 the y coordinate of the other rectangle point
@param startPos the position to find the closest reading to (usually
the robots position)
@param maxRange the maximum range to return (and what to return if nothing
found)
@param readingPos a pointer to a position in which to store the location of
the closest position
@param targetPose the origin of the local coords for the definition of the
coordinates, e.g. ArRobot::getPosition() to center the box on the robot
@return if the return is >= 0 and <= maxRange then this is the distance
to the closest reading, if it is >= maxRange, then there was no reading
in the given section
*/
AREXPORT double ArRangeBuffer::getClosestBox(double x1, double y1, double x2,
double y2, ArPose startPos,
unsigned int maxRange,
ArPose *readingPos,
ArPose targetPose) const
{
return getClosestBoxInList(x1, y1, x2, y2, startPos, maxRange, readingPos,
targetPose, &myBuffer);
}
/**
Get closest reading in a region defined by two points (opposeite points
of a rectangle) from a given list readings (rather than the readings
stored in an ArRangeBuffer)
@param x1 the x coordinate of one of the rectangle points
@param y1 the y coordinate of one of the rectangle points
@param x2 the x coordinate of the other rectangle point
@param y2 the y coordinate of the other rectangle point
@param startPos the position to find the closest reading to (usually
the robots position)
@param maxRange the maximum range to return (and what to return if nothing
found)
@param readingPos a pointer to a position in which to store the location of
the closest position
@param targetPose the origin of the local coords for the definition of the
coordinates, normally just ArRobot::getPosition()
@param buffer Use the reading positions from this list
@param targetPose the pose to see if we're closest too (in local coordinates), this should nearly always be the default of 0 0 0
@return if the return is >= 0 and <= maxRange then this is the distance
to the closest reading, if it is >= maxRange, then there was no reading
in the given section
*/
AREXPORT double ArRangeBuffer::getClosestBoxInList(
double x1, double y1, double x2, double y2, ArPose startPos,
unsigned int maxRange, ArPose *readingPos, ArPose targetPose,
const std::list<ArPoseWithTime *> *buffer)
{
double closest = maxRange;
double dist;
ArPose closestPos;
std::list<ArPoseWithTime *>::const_iterator it;
ArTransform trans;
ArPoseWithTime pose;
ArPose zeroPos;
double temp;
zeroPos.setPose(0, 0, 0);
trans.setTransform(startPos, zeroPos);
if (x1 >= x2)
{
temp = x1,
x1 = x2;
x2 = temp;
}
if (y1 >= y2)
{
temp = y1,
y1 = y2;
y2 = temp;
}
for (it = buffer->begin(); it != buffer->end(); ++it)
{
pose = trans.doTransform(*(*it));
// see if its in the box
if (pose.getX() >= x1 && pose.getX() <= x2 &&
pose.getY() >= y1 && pose.getY() <= y2)
{
dist = pose.findDistanceTo(targetPose);
//pose.log();
if (dist < closest)
{
closest = dist;
closestPos = pose;
}
}
}
if (readingPos != NULL)
*readingPos = closestPos;
if (closest > maxRange)
return maxRange;
else
return closest;
}
/**
Applies a transform to the buffers.. this is mostly useful for translating
to/from local/global coords, but may have other uses
@param trans the transform to apply to the data
*/
AREXPORT void ArRangeBuffer::applyTransform(ArTransform trans)
{
trans.doTransform(&myBuffer);
}
AREXPORT void ArRangeBuffer::clear(void)
{
beginRedoBuffer();
endRedoBuffer();
}
AREXPORT void ArRangeBuffer::reset(void)
{
clear();
}
AREXPORT void ArRangeBuffer::clearOlderThan(int milliSeconds)
{
std::list<ArPoseWithTime *>::iterator it;
beginInvalidationSweep();
for (it = myBuffer.begin(); it != myBuffer.end(); ++it)
{
if ((*it)->getTime().mSecSince() > milliSeconds)
invalidateReading(it);
}
endInvalidationSweep();
}
AREXPORT void ArRangeBuffer::clearOlderThanSeconds(int seconds)
{
clearOlderThan(seconds*1000);
}
/**
To redo the buffer means that you want to replace all
of the readings in the buffer with new pose values, and get rid of the
readings that you didn't update with new values (invalidate them).
The three functions beginRedoBuffer(),
redoReading(), and endRedoBuffer() are all made to enable you to do this.
First call beginRedoBuffer(). Then for each reading you want
to update in the buffer, call redoReading(double x, double y), then
when you are done, call endRedoBuffer().
**/
AREXPORT void ArRangeBuffer::beginRedoBuffer(void)
{
myRedoIt = myBuffer.begin();
myHitEnd = false;
myNumRedone = 0;
}
/**
For a description of how to use this, see beginRedoBuffer()
@param x the x param of the coord to add to the buffer
@param y the x param of the coord to add to the buffer
*/
AREXPORT void ArRangeBuffer::redoReading(double x, double y)
{
if (myRedoIt != myBuffer.end() && !myHitEnd)
{
(*myRedoIt)->setPose(x, y);
myRedoIt++;
}
// if we don't, add more (its just moving from buffers here,
//but let the class for this do the work
else
{
addReading(x,y);
myHitEnd = true;
}
myNumRedone++;
}
/**
For a description of how to use this, see beginRedoBuffer()
**/
AREXPORT void ArRangeBuffer::endRedoBuffer(void)
{
if (!myHitEnd)
{
// now we get rid of the extra readings on the end
beginInvalidationSweep();
while (myRedoIt != myBuffer.end())
{
invalidateReading(myRedoIt);
myRedoIt++;
}
endInvalidationSweep();
}
}
/**
@param x the x position of the reading
@param y the y position of the reading
@param closeDistSquared if the new reading is within
closeDistSquared distanceSquared of an old point the old point is
just updated for time
*/
AREXPORT void ArRangeBuffer::addReadingConditional(double x, double y,
double closeDistSquared)
{
if (closeDistSquared >= 0)
{
std::list<ArPoseWithTime *>::iterator it;
ArPoseWithTime *pose;
for (it = myBuffer.begin(); it != myBuffer.end(); ++it)
{
pose = (*it);
if (ArMath::squaredDistanceBetween(pose->getX(), pose->getX(),
x, y) < closeDistSquared)
{
pose->setTimeToNow();
return;
}
}
}
addReading(x, y);
}
/**
@param x the x position of the reading
@param y the y position of the reading
*/
AREXPORT void ArRangeBuffer::addReading(double x, double y)
{
if (myBuffer.size() < mySize)
{
if ((myIterator = myInvalidBuffer.begin()) != myInvalidBuffer.end())
{
myReading = (*myIterator);
myReading->setPose(x, y);
myReading->setTimeToNow();
myBuffer.push_front(myReading);
myInvalidBuffer.pop_front();
}
else
myBuffer.push_front(new ArPoseWithTime(x, y));
}
else if ((myRevIterator = myBuffer.rbegin()) != myBuffer.rend())
{
myReading = (*myRevIterator);
myReading->setPose(x, y);
myReading->setTimeToNow();
myBuffer.pop_back();
myBuffer.push_front(myReading);
}
}
/**
This is a set of funkiness used to invalid readings in the buffer.
It is fairly complicated. But what you need to do, is set up the invalid
sweeping with beginInvalidationSweep, then walk through the list of
readings, and pass the iterator to a reading you want to invalidate to
invalidateReading, then after you are all through walking the list call
endInvalidationSweep. Look at the description of getBuffer for additional
warnings.
@see invalidateReading
@see endInvalidationSweep
*/
void ArRangeBuffer::beginInvalidationSweep(void)
{
myInvalidSweepList.clear();
}
/**
See the description of beginInvalidationSweep, it describes how to use
this function.
@param readingIt the ITERATOR to the reading you want to get rid of
@see beginInvaladationSweep
@see endInvalidationSweep
*/
AREXPORT void ArRangeBuffer::invalidateReading(
std::list<ArPoseWithTime*>::iterator readingIt)
{
myInvalidSweepList.push_front(readingIt);
}
/**
See the description of beginInvalidationSweep, it describes how to use
this function.
@see beginInvalidationSweep
@see invalidateReading
*/
void ArRangeBuffer::endInvalidationSweep(void)
{
while ((myInvalidIt = myInvalidSweepList.begin()) !=
myInvalidSweepList.end())
{
//printf("nuked one before %d %d\n", myBuffer.size(), myInvalidBuffer.size());
myReading = (*(*myInvalidIt));
myInvalidBuffer.push_front(myReading);
myBuffer.erase((*myInvalidIt));
myInvalidSweepList.pop_front();
//printf("after %d %d\n", myBuffer.size(), myInvalidBuffer.size());
}
}
/**
Copy the readings from this buffer to a vector stored within
this object, and return a pointer to that vector.
Note that the actual vector object is stored within ArRangeBuffer,
be careful if accessing it from multiple threads.
@return Pointer to reading vector.
*/
AREXPORT std::vector<ArPoseWithTime> *ArRangeBuffer::getBufferAsVector(void)
{
std::list<ArPoseWithTime *>::iterator it;
myVector.reserve(myBuffer.size());
myVector.clear();
// start filling the array with the buffer until we run out of
// readings or its full
for (it = myBuffer.begin(); it != myBuffer.end(); it++)
{
myVector.insert(myVector.begin(), *(*it));
}
return &myVector;
}
| 30.395911 | 131 | 0.699077 | rzsavilla |
6bd87ff8e4fc490d9868b273cdec7dd49e3c96c2 | 706 | cc | C++ | tensorflow/core/kernels/relu_op_gpu.cu.cc | vsilyaev/tensorflow | f41959ccb2d9d4c722fe8fc3351401d53bcf4900 | [
"Apache-2.0"
] | 4 | 2021-06-11T09:43:32.000Z | 2021-11-17T11:15:52.000Z | tensorflow/core/kernels/relu_op_gpu.cu.cc | cleargraphinc/tensorflow | 21fac39c471dede0e4ae62dd60e2b0b85db48415 | [
"Apache-2.0"
] | null | null | null | tensorflow/core/kernels/relu_op_gpu.cu.cc | cleargraphinc/tensorflow | 21fac39c471dede0e4ae62dd60e2b0b85db48415 | [
"Apache-2.0"
] | 2 | 2016-05-18T12:48:06.000Z | 2019-03-30T03:56:31.000Z | #if GOOGLE_CUDA
#define EIGEN_USE_GPU
#include <stdio.h>
#include "tensorflow/core/kernels/relu_op.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor_types.h"
namespace tensorflow {
typedef Eigen::GpuDevice GPUDevice;
// Definition of the GPU implementations declared in relu_op.cc.
#define DEFINE_GPU_KERNELS(T) \
template struct functor::Relu<GPUDevice, T>; \
template struct functor::ReluGrad<GPUDevice, T>; \
template struct functor::Relu6<GPUDevice, T>; \
template struct functor::Relu6Grad<GPUDevice, T>;
TF_CALL_GPU_NUMBER_TYPES(DEFINE_GPU_KERNELS);
} // end namespace tensorflow
#endif // GOOGLE_CUDA
| 25.214286 | 64 | 0.743626 | vsilyaev |
6bd9433f6e8f80ed996d8fc39bde31b6267e9efe | 932 | hpp | C++ | includes/firework.hpp | Penaz91/firework_demo | 4ec185583d1b3db2b147fb25557effdf3e49f66e | [
"Unlicense"
] | null | null | null | includes/firework.hpp | Penaz91/firework_demo | 4ec185583d1b3db2b147fb25557effdf3e49f66e | [
"Unlicense"
] | null | null | null | includes/firework.hpp | Penaz91/firework_demo | 4ec185583d1b3db2b147fb25557effdf3e49f66e | [
"Unlicense"
] | null | null | null | #ifndef FIREWORK_H
#define FIREWORK_H
#include<SFML/Graphics.hpp>
#include<SFML/Audio.hpp>
#include "particle.hpp"
#include <cmath>
#include <list>
#include <vector>
class Firework: public sf::Drawable {
private:
sf::Vector2f vDestination;
sf::Vector2f vOrigin;
sf::Vector2f vPosition;
float fLifetime;
float fFuse;
sf::CircleShape shape;
sf::Color cColor;
bool bExploded;
std::list<particle*> particles;
float fScale;
std::vector<sf::Image*>* imageHandle;
float fAngle;
public:
Firework(const sf::Vector2f& origin, const sf::Vector2f& destination, std::vector<sf::Image*>* patterns);
void draw(sf::RenderTarget& target, sf::RenderStates states) const override;
void update(sf::Time timeElapsed);
virtual ~Firework() = default;
bool isExtinguished() const;
};
#endif /* FIREWORK_H */
| 26.628571 | 113 | 0.638412 | Penaz91 |
6bda31de544e5c9f02f100ab88930531faa26073 | 1,186 | cpp | C++ | Framework/ML/Src/Datasets.cpp | TheJimmyGod/JimmyGod_Engine | b9752c6fbd9db17dc23f03330b5e4537bdcadf8e | [
"MIT"
] | null | null | null | Framework/ML/Src/Datasets.cpp | TheJimmyGod/JimmyGod_Engine | b9752c6fbd9db17dc23f03330b5e4537bdcadf8e | [
"MIT"
] | null | null | null | Framework/ML/Src/Datasets.cpp | TheJimmyGod/JimmyGod_Engine | b9752c6fbd9db17dc23f03330b5e4537bdcadf8e | [
"MIT"
] | null | null | null | #include "Precompiled.h"
#include "Datasets.h"
using namespace JimmyGod::ML;
using namespace JimmyGod::Math;
Dataset Datasets::MakeLinear(size_t samples, float b0, float b1, float minX, float maxX, float noise)
{
Dataset dataset;
dataset.x0.reserve(samples);
dataset.y.reserve(samples);
for (size_t i = 0; i < samples; i++)
{
float x = RandomFloat(minX, maxX);
float y = b0 + (b1 * x) + RandomNormal(0.0f, noise);
dataset.x0.push_back(x);
dataset.y.push_back(y);
}
return dataset;
}
Dataset Datasets::MakeLogistic(size_t samples, float b0, float b1, float b2, float minX, float maxX, float noise)
{
Dataset dataset;
dataset.x0.reserve(samples);
dataset.x1.reserve(samples);
dataset.y.reserve(samples);
const float m = -b1 / b2;
const float b = -b0 / b2;
for (size_t i = 0; i < samples; i++)
{
const float x0 = RandomFloat(minX, maxX);
const float point = (m * x0) + b;
const float delta = RandomNormal(0.0f, noise);
const float x1 = point + delta;
const float y = (delta > 0.0f) ? 1.0f : 0.0f;
dataset.x0.push_back(x0);
dataset.x1.push_back(x1);
dataset.y.push_back(y);
}
return dataset;
} | 24.708333 | 114 | 0.652614 | TheJimmyGod |
6bda6936d265fff3d320b0b4ef4b7ffbe1d5f45c | 11,098 | cc | C++ | spectator/http_client.cc | copperlight/spectatord | dfc0ec35bc027d090f1d71a3f067fe164ef84b56 | [
"Apache-2.0"
] | null | null | null | spectator/http_client.cc | copperlight/spectatord | dfc0ec35bc027d090f1d71a3f067fe164ef84b56 | [
"Apache-2.0"
] | null | null | null | spectator/http_client.cc | copperlight/spectatord | dfc0ec35bc027d090f1d71a3f067fe164ef84b56 | [
"Apache-2.0"
] | null | null | null | #include "http_client.h"
#include "gzip.h"
#include "log_entry.h"
#include "version.h"
#include <algorithm>
#include <utility>
#include <curl/curl.h>
namespace spectator {
class CurlHeaders {
public:
CurlHeaders() = default;
~CurlHeaders() { curl_slist_free_all(list_); }
CurlHeaders(const CurlHeaders&) = delete;
CurlHeaders(CurlHeaders&&) = delete;
auto operator=(const CurlHeaders&) -> CurlHeaders& = delete;
auto operator=(CurlHeaders &&) -> CurlHeaders& = delete;
void append(const std::string& string) {
list_ = curl_slist_append(list_, string.c_str());
}
auto headers() -> curl_slist* { return list_; }
private:
curl_slist* list_{nullptr};
};
namespace {
auto curl_ignore_output_fun(char* /*unused*/, size_t size, size_t nmemb, void *
/*unused*/) -> size_t {
return size * nmemb;
}
auto curl_capture_output_fun(char* contents, size_t size, size_t nmemb,
void* userp) -> size_t {
auto real_size = size * nmemb;
auto* resp = static_cast<std::string*>(userp);
resp->append(contents, real_size);
return real_size;
}
auto curl_capture_headers_fun(char* contents, size_t size, size_t nmemb,
void* userp) -> size_t {
auto real_size = size * nmemb;
auto end = contents + real_size;
auto* headers = static_cast<HttpHeaders*>(userp);
// see if it's a proper header and not HTTP/xx or the final \n
auto p = static_cast<char*>(memchr(contents, ':', real_size));
if (p != nullptr && p + 2 < end) {
std::string key{contents, p};
std::string value{p + 2, end - 1}; // drop last lf
headers->emplace(std::make_pair(std::move(key), std::move(value)));
}
return real_size;
}
class CurlHandle {
public:
CurlHandle() noexcept : handle_{curl_easy_init()} {
auto user_agent = fmt::format("spectatord/{}", VERSION);
curl_easy_setopt(handle_, CURLOPT_USERAGENT, user_agent.c_str());
}
CurlHandle(const CurlHandle&) = delete;
auto operator=(const CurlHandle&) -> CurlHandle& = delete;
CurlHandle(CurlHandle&& other) = delete;
auto operator=(CurlHandle&& other) -> CurlHandle& = delete;
~CurlHandle() {
// nullptr is handled by curl
curl_easy_cleanup(handle_);
}
auto handle() const noexcept -> CURL* { return handle_; }
auto perform() -> CURLcode { return curl_easy_perform(handle()); }
auto set_opt(CURLoption option, const void* param) -> CURLcode {
return curl_easy_setopt(handle(), option, param);
}
[[nodiscard]] auto status_code() const -> int {
// curl requires this to be a long
long http_code = 400;
curl_easy_getinfo(handle(), CURLINFO_RESPONSE_CODE, &http_code);
return static_cast<int>(http_code);
}
[[nodiscard]] auto response() const -> std::string { return response_; }
void move_response(std::string* out) { *out = std::move(response_); }
[[nodiscard]] auto headers() const -> HttpHeaders { return resp_headers_; }
void move_headers(HttpHeaders* out) { *out = std::move(resp_headers_); }
void set_url(const std::string& url) { set_opt(CURLOPT_URL, url.c_str()); }
void set_headers(std::shared_ptr<CurlHeaders> headers) {
headers_ = std::move(headers);
set_opt(CURLOPT_HTTPHEADER, headers_->headers());
}
void set_connect_timeout(absl::Duration connect_timeout) {
auto millis = absl::ToInt64Milliseconds(connect_timeout);
curl_easy_setopt(handle_, CURLOPT_CONNECTTIMEOUT_MS, millis);
}
void set_timeout(absl::Duration total_timeout) {
auto millis = absl::ToInt64Milliseconds(total_timeout);
curl_easy_setopt(handle_, CURLOPT_TIMEOUT_MS, millis);
}
void post_payload(const void* payload, size_t size) {
payload_ = payload;
curl_easy_setopt(handle_, CURLOPT_POST, 1L);
curl_easy_setopt(handle_, CURLOPT_POSTFIELDS, payload_);
curl_easy_setopt(handle_, CURLOPT_POSTFIELDSIZE, size);
}
void custom_request(const char* method) {
curl_easy_setopt(handle_, CURLOPT_CUSTOMREQUEST, method);
}
void ignore_output() {
curl_easy_setopt(handle_, CURLOPT_WRITEFUNCTION, curl_ignore_output_fun);
}
void capture_output() {
curl_easy_setopt(handle_, CURLOPT_WRITEFUNCTION, curl_capture_output_fun);
curl_easy_setopt(handle_, CURLOPT_WRITEDATA,
static_cast<void*>(&response_));
}
void capture_headers() {
curl_easy_setopt(handle_, CURLOPT_HEADERDATA,
static_cast<void*>(&resp_headers_));
curl_easy_setopt(handle_, CURLOPT_HEADERFUNCTION, curl_capture_headers_fun);
}
void trace_requests() {
// we log to stdout - might need to make it configurable
// in the future. For now let's keep it simple
curl_easy_setopt(handle_, CURLOPT_STDERR, stdout);
curl_easy_setopt(handle_, CURLOPT_VERBOSE, 1L);
}
private:
CURL* handle_;
std::shared_ptr<CurlHeaders> headers_;
const void* payload_ = nullptr;
std::string response_;
HttpHeaders resp_headers_;
};
} // namespace
HttpClient::HttpClient(Registry* registry, HttpClientConfig config)
: registry_(registry), config_{config} {}
auto HttpClient::Get(const std::string& url) const -> HttpResponse {
return perform("GET", url, std::make_shared<CurlHeaders>(), nullptr, 0u, 0);
}
auto HttpClient::Get(const std::string& url,
const std::vector<std::string>& headers) const
-> HttpResponse {
return method_header("GET", url, headers);
}
auto HttpClient::Put(const std::string& url,
const std::vector<std::string>& headers) const
-> HttpResponse {
return method_header("PUT", url, headers);
}
auto HttpClient::method_header(const char* method, const std::string& url,
const std::vector<std::string>& headers) const
-> HttpResponse {
auto curl_headers = std::make_shared<CurlHeaders>();
for (const auto& h : headers) {
curl_headers->append(h);
}
return perform(method, url, std::move(curl_headers), nullptr, 0u, 0);
}
inline auto is_retryable_error(int http_code) -> bool {
return http_code == 429 || (http_code / 100) == 5;
}
auto HttpClient::perform(const char* method, const std::string& url,
std::shared_ptr<CurlHeaders> headers,
const void* payload, size_t size,
int attempt_number) const -> HttpResponse {
LogEntry entry{registry_, method, url};
CurlHandle curl;
auto total_timeout = config_.connect_timeout + config_.read_timeout;
curl.set_timeout(total_timeout);
curl.set_connect_timeout(config_.connect_timeout);
auto logger = registry_->GetLogger();
curl.set_url(url);
curl.set_headers(headers);
if (strcmp("POST", method) == 0) {
curl.post_payload(payload, size);
} else if (strcmp("GET", method) != 0) {
curl.custom_request(method);
}
if (config_.read_body) {
curl.capture_output();
} else {
curl.ignore_output();
}
if (config_.read_headers) {
curl.capture_headers();
}
if (config_.verbose_requests) {
curl.trace_requests();
}
auto curl_res = curl.perform();
int http_code;
if (curl_res != CURLE_OK) {
logger->error("Failed to {} {}: {}", method, url,
curl_easy_strerror(curl_res));
switch (curl_res) {
case CURLE_COULDNT_CONNECT:
entry.set_error("connection_error");
break;
case CURLE_OPERATION_TIMEDOUT:
entry.set_error("timeout");
break;
default:
entry.set_error("unknown");
}
auto elapsed = absl::Now() - entry.start();
// retry connect timeouts if possible, not read timeouts
logger->info(
"HTTP timeout to {}: {}ms elapsed - connect_to={} read_to={}", url,
absl::ToInt64Milliseconds(elapsed),
absl::ToInt64Milliseconds(config_.connect_timeout),
absl::ToInt64Milliseconds(total_timeout - config_.connect_timeout));
if (elapsed < total_timeout && attempt_number < 2) {
entry.set_attempt(attempt_number, false);
entry.log();
return perform(method, url, std::move(headers), payload, size,
attempt_number + 1);
}
http_code = -1;
entry.set_status_code(-1);
} else {
http_code = curl.status_code();
entry.set_status_code(http_code);
if (http_code / 100 == 2) {
entry.set_success();
} else {
entry.set_error("http_error");
}
if (is_retryable_error(http_code) && attempt_number < 2) {
logger->info("Got a retryable http code from {}: {} (attempt {})", url,
http_code, attempt_number);
entry.set_attempt(attempt_number, false);
entry.log();
auto sleep_ms = uint32_t(200) << attempt_number; // 200, 400ms
std::this_thread::sleep_for(std::chrono::milliseconds(sleep_ms));
return perform(method, url, std::move(headers), payload, size,
attempt_number + 1);
}
logger->debug("{} {} - status code: {}", method, url, http_code);
}
entry.set_attempt(attempt_number, true);
entry.log();
std::string resp;
curl.move_response(&resp);
HttpHeaders resp_headers;
curl.move_headers(&resp_headers);
return HttpResponse{http_code, std::move(resp), std::move(resp_headers)};
}
static constexpr const char* const kGzipEncoding = "Content-Encoding: gzip";
auto HttpClient::Post(const std::string& url, const char* content_type,
const CompressedResult& payload) const -> HttpResponse {
auto headers = std::make_shared<CurlHeaders>();
headers->append(content_type);
headers->append(kGzipEncoding);
return perform("POST", url, std::move(headers), payload.data, payload.size,
0);
}
auto HttpClient::Post(const std::string& url, const char* content_type,
const void* payload, size_t size) const -> HttpResponse {
auto logger = registry_->GetLogger();
auto headers = std::make_shared<CurlHeaders>();
headers->append(content_type);
if (config_.compress) {
headers->append(kGzipEncoding);
auto compressed_size = compressBound(size) + kGzipHeaderSize;
auto compressed_payload =
std::unique_ptr<char[]>(new char[compressed_size]);
auto compress_res = gzip_compress(compressed_payload.get(),
&compressed_size, payload, size);
if (compress_res != Z_OK) {
logger->error(
"Failed to compress payload: {}, while posting to {} - uncompressed "
"size: {}",
compress_res, url, size);
HttpResponse err{};
err.status = -1;
return err;
}
return perform("POST", url, std::move(headers), compressed_payload.get(),
compressed_size, 0);
}
// no compression
return perform("POST", url, std::move(headers), payload, size, 0);
}
void HttpClient::GlobalInit() noexcept {
static bool init = false;
if (init) {
return;
}
init = true;
curl_global_init(CURL_GLOBAL_ALL);
}
void HttpClient::GlobalShutdown() noexcept {
static bool shutdown = false;
if (shutdown) {
return;
}
shutdown = true;
curl_global_cleanup();
}
} // namespace spectator
| 31.439093 | 80 | 0.66138 | copperlight |
6bdba0acdd1a4fda91ae31329a1dc36cdf6581c3 | 6,737 | cpp | C++ | src/bin/license_checker/callback.cpp | opengauss-mirror/openGauss-graph | 6beb138fd00abdbfddc999919f90371522118008 | [
"MulanPSL-1.0"
] | 360 | 2020-06-30T14:47:34.000Z | 2022-03-31T15:21:53.000Z | src/bin/license_checker/callback.cpp | opengauss-mirror/openGauss-graph | 6beb138fd00abdbfddc999919f90371522118008 | [
"MulanPSL-1.0"
] | 4 | 2020-06-30T15:09:16.000Z | 2020-07-14T06:20:03.000Z | src/bin/license_checker/callback.cpp | opengauss-mirror/openGauss-graph | 6beb138fd00abdbfddc999919f90371522118008 | [
"MulanPSL-1.0"
] | 133 | 2020-06-30T14:47:36.000Z | 2022-03-25T15:29:00.000Z | /*
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
*
* openGauss is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
* ---------------------------------------------------------------------------------------
*
* callback.cpp
*
*
*
* IDENTIFICATION
* src/bin/license_checker/callback.cpp
*
* ---------------------------------------------------------------------------------------
*/
#include "callback.h"
#include <string.h>
#include <errno.h>
#ifdef __cplusplus
extern "C" {
#endif
/************************************************************************/
/* LIC_CALLBACK_TYPE_DYNAMIC_MALLOC */
/************************************************************************/
LIC_VOID* OS_DynMalloc(LIC_ULONG ulSize)
{
return (LIC_VOID*)malloc(ulSize);
}
/************************************************************************/
/* LIC_CALLBACK_TYPE_DYNAMIC_FREE */
/************************************************************************/
LIC_VOID OS_DynFree(LIC_VOID* pAddr)
{
free(pAddr);
}
/************************************************************************/
/* LIC_CALLBACK_TYPE_MUTEX_CREATE */
/************************************************************************/
LIC_ULONG OS_SmMCreate(LIC_CHAR* pszName, LIC_ULONG* pSm)
{
pSm = (LIC_ULONG*)sem_open(pszName, O_CREAT | O_RDWR, 0600, 1);
if (pSm == (LIC_ULONG*)SEM_FAILED) {
return LIC_ERROR;
}
return LIC_OK;
}
/************************************************************************/
/* LIC_CALLBACK_TYPE_MUTEX_DELETE */
/************************************************************************/
LIC_ULONG OS_SmDelete(LIC_ULONG ulSmID)
{
if (sem_close((sem_t*)&ulSmID) == -1)
return LIC_ERROR;
return LIC_OK;
}
/************************************************************************/
/* LIC_CALLBACK_TYPE_MUTEX_ACQUIRE */
/************************************************************************/
LIC_ULONG OS_SmP(LIC_ULONG ulSem, LIC_ULONG ulTimeOutInMillSec)
{
if (sem_wait((sem_t*)&ulSem) == -1)
return LIC_ERROR;
return LIC_OK;
}
/************************************************************************/
/* LIC_CALLBACK_TYPE_MUTEX_RELEASE */
/************************************************************************/
LIC_ULONG OS_SmV(LIC_ULONG ulSmID)
{
if (sem_post((sem_t*)&ulSmID) == -1)
return LIC_ERROR;
return LIC_OK;
}
/************************************************************************/
/* LIC_CALLBACK_TYPE_GET_TIME */
/************************************************************************/
LIC_ULONG OS_GetSysTime(LIC_SYS_T_STRU* pSysTime)
{
time_t t;
struct tm* area;
t = time(NULL);
area = localtime(&t);
if (area == NULL)
return LIC_ERROR;
pSysTime->uwYear = 1900 + area->tm_year;
pSysTime->ucMonth = area->tm_mon + 1;
pSysTime->ucDate = area->tm_mday;
pSysTime->ucHour = area->tm_hour;
pSysTime->ucMinute = area->tm_min;
pSysTime->ucSecond = area->tm_sec;
pSysTime->ucWeek = area->tm_wday;
return LIC_OK;
}
/************************************************************************/
/* LIC_CALLBACK_TYPE_START_TIMER */
/************************************************************************/
LIC_ULONG OS_StartTimer(LIC_ULONG* pTmHandler, LIC_ULONG ulLength, LIC_SYS_T_STRU* pTime,
LIC_TIMER_CALLBACK_FUNC pTmCallBack, LIC_ULONG ulMode, LIC_ULONG ulType, LIC_ULONG ulTimerId)
{
if (ulType != LIC_TIMER_TYPE_REL)
return LIC_ERROR;
struct itimerval tick = {0};
signal(SIGALRM, (void (*)(int))pTmCallBack);
errno_t ss_rc = 0;
ss_rc = memset_s(&tick, sizeof(tick), 0x0, sizeof(tick));
securec_check_c(ss_rc, "\0", "\0");
if (ulMode == LIC_TIMER_MODE_ONCE) {
tick.it_value.tv_sec = ulLength / 1000;
tick.it_value.tv_usec = (ulLength % 1000) * 1000;
}
if (ulMode == LIC_TIMER_MODE_REPEAT) {
tick.it_value.tv_sec = ulLength / 1000;
tick.it_value.tv_usec = (ulLength % 1000) * 1000;
tick.it_interval.tv_sec = ulLength / 1000;
tick.it_interval.tv_usec = (ulLength % 1000) * 1000;
}
if (setitimer(ITIMER_REAL, &tick, NULL) < 0)
return LIC_ERROR;
*pTmHandler = (LIC_ULONG)random();
return LIC_OK;
}
/************************************************************************/
/* LIC_CALLBACK_TYPE_STOP_TIMER */
/************************************************************************/
LIC_ULONG OS_StopTimer(LIC_ULONG ulTmHandler)
{
struct itimerval tick = {0};
errno_t ss_rc = 0;
ss_rc = memset_s(&tick, sizeof(tick), 0x0, sizeof(tick));
securec_check_c(ss_rc, "\0", "\0");
if (setitimer(ITIMER_REAL, &tick, NULL) < 0)
return LIC_ERROR;
return LIC_OK;
}
/***********************************************************************************************/
/*
ALM_CALLBACK_TYPE_GET_MACHINE_ESN
ALM_CALLBACK_TYPE_IO_READ_FUNC
ALM_CALLBACK_TYPE_IO_WRITE_FUNC
*/
/***********************************************************************************************/
/************************************************************************/
/* ALM_CALLBACK_TYPE_GET_MACHINE_ESN */
/************************************************************************/
LIC_ULONG APP_GetMachineEsn(LIC_ULONG* pulCount, LIC_MACHINEID_STRU* pstMachineId)
{
errno_t ss_rc = 0;
*pulCount = 1;
ss_rc = strncpy_s(
(char*)(pstMachineId->custom_machineprint), LIC_LONG_STREAM_LEN, "GAUSSMPPDB", LIC_LONG_STREAM_LEN - 1);
securec_check_c(ss_rc, "\0", "\0");
pstMachineId->custom_machineprint[LIC_LONG_STREAM_LEN - 1] = '\0';
return LIC_OK;
}
/************************************************************************/
/************************************************************************/
LIC_ULONG APP_IOReadCallback(LIC_ULONG ulType, LIC_VOID* pBuf, LIC_ULONG* pulLen, LIC_ULONG ulOffSet)
{
return LIC_OK;
}
/************************************************************************/
/* ALM_CALLBACK_TYPE_IO_WRITE_FUNC */
/************************************************************************/
LIC_ULONG APP_IOWriteCallback(LIC_ULONG ulType, LIC_VOID* pBuf, LIC_ULONG ulLen, LIC_ULONG ulOffSet)
{
return LIC_OK;
}
#ifdef __cplusplus
}
#endif /* __cpluscplus */
| 33.517413 | 112 | 0.464895 | opengauss-mirror |
6bdc38145a33e2bce6e327a72f86e72f4dbde44d | 1,961 | hpp | C++ | examples/toy/bnsl_state.hpp | kp1181/scool | 296cd49a0d62de609d681b3ec3d7019b3d2c7c30 | [
"MIT"
] | 1 | 2022-03-14T05:23:51.000Z | 2022-03-14T05:23:51.000Z | examples/toy/bnsl_state.hpp | kp1181/scool | 296cd49a0d62de609d681b3ec3d7019b3d2c7c30 | [
"MIT"
] | null | null | null | examples/toy/bnsl_state.hpp | kp1181/scool | 296cd49a0d62de609d681b3ec3d7019b3d2c7c30 | [
"MIT"
] | null | null | null | /***
* $Id$
**
* File: bnsl_state.hpp
* Created: Jan 13, 2022
*
* Author: Jaroslaw Zola <jaroslaw.zola@hush.com>
* Distributed under the MIT License.
* See accompanying file LICENSE.
*
* This file is part of SCoOL.
*/
#ifndef BNSL_STATE_HPP
#define BNSL_STATE_HPP
#include <istream>
#include <ostream>
#include <vector>
#include "bit_util.hpp"
#include "limits.hpp"
template <typename set_type> struct bnsl_state {
bnsl_state() = default;
void identity() { }
void operator+=(const bnsl_state& st) {
if (st.score < score) {
score = st.score;
path = st.path;
}
} // operator+=
bool operator==(const bnsl_state& st) const { return (tid == st.tid); }
void print(std::ostream& os) const {
os << "score: " << score << ", order:";
for (int x : path) os << " " << x;
os << std::endl;
} // print
set_type tid = set_empty<set_type>();
double score = SABNA_DBL_INFTY;
std::vector<uint8_t> path;
}; // struct bnsl_state
template <typename set_type>
inline std::ostream& operator<<(std::ostream& os, const bnsl_state<set_type>& st) {
int n = st.path.size();
os.write(reinterpret_cast<const char*>(&st.tid), sizeof(st.tid));
os.write(reinterpret_cast<const char*>(&st.score), sizeof(st.score));
os.write(reinterpret_cast<const char*>(&n), sizeof(n));
os.write(reinterpret_cast<const char*>(st.path.data()), n * sizeof(uint8_t));
return os;
} // operator<<
template <typename set_type>
inline std::istream& operator>>(std::istream& is, bnsl_state<set_type>& st) {
int n = 0;
is.read(reinterpret_cast<char*>(&st.tid), sizeof(st.tid));
is.read(reinterpret_cast<char*>(&st.score), sizeof(st.score));
is.read(reinterpret_cast<char*>(&n), sizeof(n));
st.path.resize(n);
is.read(reinterpret_cast<char*>(st.path.data()), n * sizeof(uint8_t));
return is;
} // operator>>
#endif // BNSL_STATE_HPP
| 26.863014 | 83 | 0.627231 | kp1181 |
6be3d1104b8a3558401ebea570dab62f6a9821fd | 5,740 | cpp | C++ | nifti_user/ogre_tools_diamond_back/src/ogre_tools/fps_camera.cpp | talkingrobots/NIFTi_OCU | 017a36cd98f4302ebcd0f024a6c0c517b044bac7 | [
"BSD-3-Clause"
] | 1 | 2019-08-14T09:59:21.000Z | 2019-08-14T09:59:21.000Z | nifti_user/ogre_tools_diamond_back/src/ogre_tools/fps_camera.cpp | talkingrobots/NIFTi_OCU | 017a36cd98f4302ebcd0f024a6c0c517b044bac7 | [
"BSD-3-Clause"
] | null | null | null | nifti_user/ogre_tools_diamond_back/src/ogre_tools/fps_camera.cpp | talkingrobots/NIFTi_OCU | 017a36cd98f4302ebcd0f024a6c0c517b044bac7 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "fps_camera.h"
#include <OGRE/OgreCamera.h>
#include <OGRE/OgreSceneManager.h>
#include <OGRE/OgreSceneNode.h>
#include <OGRE/OgreVector3.h>
#include <OGRE/OgreQuaternion.h>
#include <stdint.h>
#include <sstream>
namespace ogre_tools
{
static const float PITCH_LIMIT_LOW = -Ogre::Math::HALF_PI + 0.001;
static const float PITCH_LIMIT_HIGH = Ogre::Math::HALF_PI - 0.001;
FPSCamera::FPSCamera( Ogre::SceneManager* scene_manager )
: CameraBase( scene_manager )
, pitch_(0.0f)
, yaw_(0.0f)
{
}
FPSCamera::~FPSCamera()
{
}
void FPSCamera::relativeNodeChanged()
{
if ( relative_node_ )
{
relative_node_->attachObject( camera_ );
}
}
void FPSCamera::update()
{
Ogre::Matrix3 pitch, yaw;
yaw.FromAxisAngle( Ogre::Vector3::UNIT_Y, Ogre::Radian( yaw_ ) );
pitch.FromAxisAngle( Ogre::Vector3::UNIT_X, Ogre::Radian( pitch_ ) );
camera_->setOrientation( yaw * pitch );
}
void FPSCamera::normalizePitch()
{
if ( pitch_ < PITCH_LIMIT_LOW )
{
pitch_ = PITCH_LIMIT_LOW;
}
else if ( pitch_ > PITCH_LIMIT_HIGH )
{
pitch_ = PITCH_LIMIT_HIGH;
}
}
void FPSCamera::normalizeYaw()
{
yaw_ = fmod( yaw_, Ogre::Math::TWO_PI );
if ( yaw_ < 0.0f )
{
yaw_ = Ogre::Math::TWO_PI + yaw_;
}
}
void FPSCamera::yaw( float angle )
{
yaw_ += angle;
normalizeYaw();
update();
}
void FPSCamera::pitch( float angle )
{
pitch_ += angle;
normalizePitch();
update();
}
void FPSCamera::roll( float angle )
{
}
void FPSCamera::setFrom( CameraBase* camera )
{
CameraBase::setPosition( camera->getPosition() );
CameraBase::setOrientation( camera->getOrientation() );
}
void FPSCamera::setOrientation( float x, float y, float z, float w )
{
Ogre::Quaternion quat( w, x, y, z );
yaw_ = quat.getYaw( false ).valueRadians();
pitch_ = quat.getPitch( false ).valueRadians();
Ogre::Vector3 direction = quat * Ogre::Vector3::NEGATIVE_UNIT_Z;
if ( direction.dotProduct( Ogre::Vector3::NEGATIVE_UNIT_Z ) < 0 )
{
if ( pitch_ > Ogre::Math::HALF_PI )
{
pitch_ = -Ogre::Math::HALF_PI + (pitch_ - Ogre::Math::HALF_PI);
}
else if ( pitch_ < -Ogre::Math::HALF_PI )
{
pitch_ = Ogre::Math::HALF_PI - (-pitch_ - Ogre::Math::HALF_PI);
}
yaw_ = -yaw_;
if ( direction.dotProduct( Ogre::Vector3::UNIT_X ) < 0 )
{
yaw_ -= Ogre::Math::PI;
}
else
{
yaw_ += Ogre::Math::PI;
}
}
normalizePitch();
normalizeYaw();
update();
}
Ogre::Quaternion FPSCamera::getOrientation()
{
return camera_->getOrientation();
}
void FPSCamera::move( float x, float y, float z )
{
Ogre::Vector3 translate( x, y, z );
camera_->setPosition( camera_->getPosition() + getOrientation() * translate );
}
void FPSCamera::setPosition( float x, float y, float z )
{
camera_->setPosition( x, y, z );
}
Ogre::Vector3 FPSCamera::getPosition()
{
return camera_->getPosition();
}
void FPSCamera::lookAt( const Ogre::Vector3& point )
{
camera_->lookAt( point );
CameraBase::setOrientation( camera_->getOrientation() );
update();
}
void FPSCamera::mouseLeftDrag( int diff_x, int diff_y, bool ctrl, bool alt, bool shift )
{
yaw( -diff_x*0.005 );
pitch( -diff_y*0.005 );
}
void FPSCamera::mouseMiddleDrag( int diff_x, int diff_y, bool ctrl, bool alt, bool shift )
{
move( diff_x*0.01, -diff_y*0.01, 0.0f );
}
void FPSCamera::mouseRightDrag( int diff_x, int diff_y, bool ctrl, bool alt, bool shift )
{
move( 0.0f, 0.0f, diff_y*0.1 );
}
void FPSCamera::scrollWheel( int diff, bool ctrl, bool alt, bool shift )
{
move( 0.0f, 0.0f, -diff * 0.01 );
}
void FPSCamera::fromString(const std::string& str)
{
std::istringstream iss(str);
iss >> pitch_;
iss.ignore();
iss >> yaw_;
iss.ignore();
Ogre::Vector3 vec;
iss >> vec.x;
iss.ignore();
iss >> vec.y;
iss.ignore();
iss >> vec.z;
iss.ignore();
camera_->setPosition(vec);
update();
}
std::string FPSCamera::toString()
{
std::ostringstream oss;
oss << pitch_ << " " << yaw_ << " " << camera_->getPosition().x << " " << camera_->getPosition().y << " " << camera_->getPosition().z;
return oss.str();
}
} // namespace ogre_tools
| 23.52459 | 136 | 0.676481 | talkingrobots |
6be4cd9a50a13a41540512bd06b0f1974356c5b7 | 5,376 | cpp | C++ | 3rdparty/meshlab-master/src/sampleplugins/sample_pclfilter/sample_pclfilter.cpp | HoEmpire/slambook2 | 96d360f32aa5d8b5c5dcbbf9ee7ba865e84409f4 | [
"MIT"
] | 4 | 2016-03-30T14:31:52.000Z | 2019-02-02T05:01:32.000Z | graphics/meshlab/src/sampleplugins/sample_pclfilter/sample_pclfilter.cpp | hlzz/dotfiles | 0591f71230c919c827ba569099eb3b75897e163e | [
"BSD-3-Clause"
] | null | null | null | graphics/meshlab/src/sampleplugins/sample_pclfilter/sample_pclfilter.cpp | hlzz/dotfiles | 0591f71230c919c827ba569099eb3b75897e163e | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************
* MeshLab o o *
* A versatile mesh processing toolbox o o *
* _ O _ *
* Copyright(C) 2005 \/)\/ *
* Visual Computing Lab /\/| *
* ISTI - Italian National Research Council | *
* \ *
* All rights reserved. *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License (http://www.gnu.org/licenses/gpl.txt) *
* for more details. *
* *
****************************************************************************/
#include "sample_pclfilter.h"
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
// Constructor usually performs only two simple tasks of filling the two lists
// - typeList: with all the possible id of the filtering actions
// - actionList with the corresponding actions. If you want to add icons to your filtering actions you can do here by construction the QActions accordingly
SamplePCLFilterPlugin::SamplePCLFilterPlugin()
:MeshFilterInterface()
{
typeList << FP_PCL_SAMPLE;
foreach(FilterIDType tt , types())
actionList << new QAction(filterName(tt), this);
}
// ST() must return the very short string describing each filtering action
// (this string is used also to define the menu entry)
QString SamplePCLFilterPlugin::filterName(FilterIDType filterId) const
{
switch(filterId) {
case FP_PCL_SAMPLE : return QString("Point Cloud Library Filter Example");
default : assert(0);
}
return QString();
}
// Info() must return the longer string describing each filtering action
// (this string is used in the About plugin dialog)
QString SamplePCLFilterPlugin::filterInfo(FilterIDType filterId) const
{
switch(filterId) {
case FP_PCL_SAMPLE : return QString("Small useless filter added only to show how to work with a Point Cloud Library with MeshLab.");
default : assert(0);
}
return QString("Unknown Filter");
}
// The FilterClass describes in which generic class of filters it fits.
// This choice affect the submenu in which each filter will be placed
// More than a single class can be choosen.
SamplePCLFilterPlugin::FilterClass SamplePCLFilterPlugin::getClass(QAction *a)
{
switch(ID(a))
{
case FP_PCL_SAMPLE : return MeshFilterInterface::Generic;
default : assert(0);
}
return MeshFilterInterface::Generic;
}
// This function define the needed parameters for each filter. Return true if the filter has some parameters
// it is called every time, so you can set the default value of parameters according to the mesh
// For each parameter you need to define,
// - the name of the parameter,
// - the string shown in the dialog
// - the default value
// - a possibly long string describing the meaning of that parameter (shown as a popup help in the dialog)
void SamplePCLFilterPlugin::initParameterSet(QAction * action, MeshModel & m, RichParameterSet & parlst)
{
(void)m;
switch(ID(action))
{
case FP_PCL_SAMPLE :
{
break;
}
default : assert(0);
}
}
// The Real Core Function doing the actual mesh processing.
// Move Vertex of a random quantity
bool SamplePCLFilterPlugin::applyFilter(QAction * a, MeshDocument & md , RichParameterSet & par, vcg::CallBackPos * /*cb*/)
{
switch(ID(a))
{
case FP_PCL_SAMPLE:
{
pcl::PointCloud<pcl::PointXYZ> cloud;
// Fill in the cloud data
cloud.width = 5;
cloud.height = 1;
cloud.is_dense = false;
cloud.points.resize (cloud.width * cloud.height);
for (size_t i = 0; i < cloud.points.size (); ++i)
{
cloud.points[i].x = 1024 * rand () / (RAND_MAX + 1.0f);
cloud.points[i].y = 1024 * rand () / (RAND_MAX + 1.0f);
cloud.points[i].z = 1024 * rand () / (RAND_MAX + 1.0f);
}
pcl::io::savePCDFileASCII ("test_pcd.pcd", cloud);
std::cerr << "Saved " << cloud.points.size () << " data points to test_pcd.pcd." << std::endl;
for (size_t i = 0; i < cloud.points.size (); ++i)
std::cerr << " " << cloud.points[i].x << " " << cloud.points[i].y << " " << cloud.points[i].z << std::endl;
break;
}
}
return true;
}
MESHLAB_PLUGIN_NAME_EXPORTER(SamplePCLFilterPlugin)
| 40.727273 | 157 | 0.56622 | HoEmpire |
6be5bdf8ee06389987bc2aec558020fc8ab87a24 | 270 | hpp | C++ | gnet/include/noncopyable.hpp | gapry/GNet | 4d63540e1f532fae1a44a97f9b2d74a6754f2513 | [
"MIT"
] | 1 | 2021-05-19T03:56:47.000Z | 2021-05-19T03:56:47.000Z | gnet/include/noncopyable.hpp | gapry/GNet | 4d63540e1f532fae1a44a97f9b2d74a6754f2513 | [
"MIT"
] | null | null | null | gnet/include/noncopyable.hpp | gapry/GNet | 4d63540e1f532fae1a44a97f9b2d74a6754f2513 | [
"MIT"
] | null | null | null | #pragma once
namespace gnet {
template<class T>
class noncopyable {
protected:
noncopyable() = default;
~noncopyable() noexcept = default;
private:
noncopyable(noncopyable const&) = delete;
auto operator=(T const&) -> void = delete;
};
} // namespace gnet
| 14.210526 | 44 | 0.692593 | gapry |
6be829fa560ac84566ad8005667e51f92788d306 | 3,795 | cpp | C++ | Core/src/DoubleBufferWithAllocs.cpp | int-Frank/BSR | 16310147281c76ca37836b07aff2974234e09a47 | [
"Apache-2.0"
] | 1 | 2020-01-04T20:17:42.000Z | 2020-01-04T20:17:42.000Z | Core/src/DoubleBufferWithAllocs.cpp | int-Frank/BSR | 16310147281c76ca37836b07aff2974234e09a47 | [
"Apache-2.0"
] | null | null | null | Core/src/DoubleBufferWithAllocs.cpp | int-Frank/BSR | 16310147281c76ca37836b07aff2974234e09a47 | [
"Apache-2.0"
] | null | null | null | #include "DoubleBufferWithAllocs.h"
//------------------------------------------------------------------------------------------
// DoubleBufferWithAllocs::Ref
//------------------------------------------------------------------------------------------
DoubleBufferWithAllocs::Ref::Ref()
: m_nProdRefs(nullptr)
, m_buf(nullptr)
{
}
DoubleBufferWithAllocs::Ref::Ref(std::atomic<size_t>* a_nProdRefs, void* a_buf)
: m_nProdRefs(a_nProdRefs)
, m_buf(a_buf)
{
BSR_ASSERT(a_nProdRefs && a_buf, "");
(*m_nProdRefs)++;
}
DoubleBufferWithAllocs::Ref::~Ref()
{
if (m_nProdRefs)
(*m_nProdRefs)--;
}
DoubleBufferWithAllocs::Ref::Ref(Ref const& a_other)
: m_nProdRefs(a_other.m_nProdRefs)
, m_buf(a_other.m_buf)
{
if (m_nProdRefs)
(*m_nProdRefs)++;
}
typename DoubleBufferWithAllocs::Ref&
DoubleBufferWithAllocs::Ref::operator=(Ref const& a_other)
{
if (this != &a_other)
{
m_buf = a_other.m_buf;
if (m_nProdRefs)
(*m_nProdRefs)--;
m_nProdRefs = a_other.m_nProdRefs;
if (m_nProdRefs)
(*m_nProdRefs)++;
}
return *this;
}
DoubleBufferWithAllocs::Ref::Ref(Ref&& a_other)
: m_nProdRefs(a_other.m_nProdRefs)
, m_buf(a_other.m_buf)
{
a_other.m_buf = nullptr;
a_other.m_nProdRefs = nullptr;
}
typename DoubleBufferWithAllocs::Ref&
DoubleBufferWithAllocs::Ref::operator=(Ref&& a_other)
{
if (this != &a_other)
{
if (m_nProdRefs)
(*m_nProdRefs)--;
m_buf = a_other.m_buf;
m_nProdRefs = a_other.m_nProdRefs;
a_other.m_buf = nullptr;
a_other.m_nProdRefs = nullptr;
}
return *this;
}
//------------------------------------------------------------------------------------------
// DoubleBufferWithAllocs
//------------------------------------------------------------------------------------------
void* DoubleBufferWithAllocs::Ref::GetBuffer() const
{
return m_buf;
}
DoubleBufferWithAllocs::DoubleBufferWithAllocs(size_t a_size)
: m_producerIndex(0)
, m_nProdRefs{0, 0}
, m_buffer{MemBuffer(a_size), MemBuffer(a_size)}
{
}
DoubleBufferWithAllocs::DoubleBufferWithAllocs(size_t a_size, size_t a_alignment)
: m_producerIndex(0)
, m_nProdRefs{0, 0}
, m_buffer{MemBuffer(a_size, a_alignment), MemBuffer(a_size, a_alignment)}
{
}
DoubleBufferWithAllocs::DoubleBufferWithAllocs()
: m_producerIndex(0)
, m_nProdRefs{0, 0}
{
}
DoubleBufferWithAllocs::~DoubleBufferWithAllocs()
{
//Producer threads should have been terminated before buffer is destroyed.
BSR_ASSERT(m_nProdRefs[0] == 0 && m_nProdRefs[1] == 0, "");
}
typename DoubleBufferWithAllocs::Ref
DoubleBufferWithAllocs::Allocate(size_t a_size)
{
std::lock_guard<std::mutex> lock(m_mutex);
void* ptr = m_buffer[m_producerIndex].Allocate(a_size);
m_allocations[m_producerIndex].push_back(ptr);
return Ref(&m_nProdRefs[m_producerIndex], ptr);
}
void DoubleBufferWithAllocs::Swap()
{
//Save the to-be consumer index
int ind = m_producerIndex;
//Set new threads to allocate on the new buffer
m_mutex.lock();
m_producerIndex = (m_producerIndex + 1) % 2;
m_nProdRefs[m_producerIndex] = 0;
m_allocations[m_producerIndex].clear();
m_mutex.unlock();
//Wait until no thread is accessing the now consumer buffer.
if (m_nProdRefs[ind] != 0)
{
std::mutex mut;
std::unique_lock<std::mutex> lock(mut);
m_cv.wait(lock, [this, ind = ind]
{
return m_nProdRefs[ind] == 0;
});
}
}
MemBuffer& DoubleBufferWithAllocs::GetBuffer()
{
size_t ind = (m_producerIndex + 1) % 2;
return m_buffer[ind];
}
PODArray<void*>& DoubleBufferWithAllocs::GetAllocations()
{
size_t ind = (m_producerIndex + 1) % 2;
return m_allocations[ind];
}
size_t DoubleBufferWithAllocs::GetCurrentRefCount()
{
std::lock_guard<std::mutex> lock(m_mutex);
return m_nProdRefs[m_producerIndex];
}
| 22.861446 | 92 | 0.637418 | int-Frank |
6be89af3018eb4f867beea416f18d83030109bd9 | 236 | cpp | C++ | chapter-11/11.21.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | chapter-11/11.21.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | chapter-11/11.21.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | // map<string, size_t> word_count
// string word
// while(cin >> word) ++word_count.insert({word, 0}).first->second;
// see the privileges of operators in P147
// while(cin >> word) ++((((word_count.insert)({word, 0})).first)->second)
| 33.714286 | 74 | 0.661017 | zero4drift |
6bf0bb379c365859d6061f42d6779c6c8348871b | 259 | hpp | C++ | legacy/include/distconv/tensor/stream.hpp | benson31/DiHydrogen | f12d1e0281ae58e40eadf98b3e2209208c82f5e2 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | legacy/include/distconv/tensor/stream.hpp | benson31/DiHydrogen | f12d1e0281ae58e40eadf98b3e2209208c82f5e2 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | legacy/include/distconv/tensor/stream.hpp | benson31/DiHydrogen | f12d1e0281ae58e40eadf98b3e2209208c82f5e2 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | #pragma once
namespace distconv {
namespace tensor {
template <typename Allocator>
struct Stream;
struct DefaultStream {
DefaultStream() = default;
DefaultStream(int v) {}
static DefaultStream value;
};
} // namespace tensro
} // namespae distconv
| 14.388889 | 29 | 0.733591 | benson31 |
6bf3f4b4e1214252547d37aa3bf1d9163f695b8b | 254 | cpp | C++ | day-10-4-1.cpp | duasong111/c_lang_learn | 4a939204a9d12a1fd0a6ca4ff36ed3bfdfb97482 | [
"BSD-2-Clause"
] | null | null | null | day-10-4-1.cpp | duasong111/c_lang_learn | 4a939204a9d12a1fd0a6ca4ff36ed3bfdfb97482 | [
"BSD-2-Clause"
] | null | null | null | day-10-4-1.cpp | duasong111/c_lang_learn | 4a939204a9d12a1fd0a6ca4ff36ed3bfdfb97482 | [
"BSD-2-Clause"
] | null | null | null | //字符串数组
#include <stdio.h>
int main(void)
{
int i;
char cs[][6] = { "turbo","naaaa","dohc" };
//此处的数组[6]则是限制括号内的数字
for (i = 0; i < 3; i++)
printf("cs[%d] = \"%s\"\n", i, cs[i]);
//其实那个\"%s\"的作用就是为了多出 " "的,因为单个斜杠不显示
return 0;
} | 19.538462 | 44 | 0.488189 | duasong111 |
6bf56b249cc3bc231b7d3a2df80328da24fb04d7 | 7,718 | cpp | C++ | src/fileutils.cpp | sdclarke/recc | df8e1dd3c9b5e9d1a46ebdc4f74dce0241a3cb1b | [
"Apache-2.0"
] | null | null | null | src/fileutils.cpp | sdclarke/recc | df8e1dd3c9b5e9d1a46ebdc4f74dce0241a3cb1b | [
"Apache-2.0"
] | null | null | null | src/fileutils.cpp | sdclarke/recc | df8e1dd3c9b5e9d1a46ebdc4f74dce0241a3cb1b | [
"Apache-2.0"
] | null | null | null | // Copyright 2018 Bloomberg Finance L.P
//
// 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 <fileutils.h>
#include <buildboxcommon_fileutils.h>
#include <buildboxcommon_logging.h>
#include <cstring>
#include <env.h>
#include <fstream>
#include <sstream>
#include <unistd.h>
namespace BloombergLP {
namespace recc {
bool FileUtils::isRegularFileOrSymlink(const struct stat &s)
{
return (S_ISREG(s.st_mode) || S_ISLNK(s.st_mode));
}
struct stat FileUtils::getStat(const std::string &path,
const bool followSymlinks)
{
if (path.empty()) {
const std::string error = "invalid args: path empty";
BUILDBOX_LOG_ERROR(error);
throw std::runtime_error(error);
}
struct stat statResult;
const int rc = (followSymlinks ? stat(path.c_str(), &statResult)
: lstat(path.c_str(), &statResult));
if (rc < 0) {
BUILDBOX_LOG_ERROR("Error calling "
<< (followSymlinks ? "stat()" : "lstat()")
<< " for path \"" << path << "\": "
<< "rc = " << rc << ", errno = [" << errno << ":"
<< strerror(errno) << "]");
throw std::system_error(errno, std::system_category());
}
return statResult;
}
bool FileUtils::isExecutable(const struct stat &s)
{
return s.st_mode & S_IXUSR;
}
bool FileUtils::isSymlink(const struct stat &s) { return S_ISLNK(s.st_mode); }
std::string FileUtils::getSymlinkContents(const std::string &path,
const struct stat &statResult)
{
if (path.empty()) {
const std::string error = "invalid args: path is empty";
BUILDBOX_LOG_ERROR(error);
throw std::runtime_error(error);
}
if (!S_ISLNK(statResult.st_mode)) {
std::ostringstream oss;
oss << "file \"" << path << "\" is not a symlink";
BUILDBOX_LOG_ERROR(oss.str());
throw std::runtime_error(oss.str());
}
std::string contents(static_cast<size_t>(statResult.st_size), '\0');
const ssize_t rc = readlink(path.c_str(), &contents[0], contents.size());
if (rc < 0) {
std::ostringstream oss;
oss << "readlink failed for \"" << path << "\", rc = " << rc
<< ", errno = [" << errno << ":" << strerror(errno) << "]";
BUILDBOX_LOG_ERROR(oss.str());
throw std::runtime_error(oss.str());
}
return contents;
}
bool FileUtils::hasPathPrefix(const std::string &path,
const std::string &prefix)
{
/* A path can never have the empty path as a prefix */
if (prefix.empty()) {
return false;
}
if (path == prefix) {
return true;
}
/*
* Make sure prefix ends in a slash.
* This is so we don't return true if path = /foo and prefix = /foobar
*/
std::string tmpPrefix(prefix);
if (tmpPrefix.back() != '/') {
tmpPrefix.push_back('/');
}
return path.substr(0, tmpPrefix.length()) == tmpPrefix;
}
bool FileUtils::hasPathPrefixes(const std::string &path,
const std::set<std::string> &pathPrefixes)
{
for (const auto &prefix : pathPrefixes) {
if (FileUtils::hasPathPrefix(path, prefix)) {
return true;
}
}
return false;
}
std::string FileUtils::getCurrentWorkingDirectory()
{
unsigned int bufferSize = 1024;
while (true) {
std::unique_ptr<char[]> buffer(new char[bufferSize]);
char *cwd = getcwd(buffer.get(), bufferSize);
if (cwd != nullptr) {
return std::string(cwd);
}
else if (errno == ERANGE) {
bufferSize *= 2;
}
else {
const std::string errorReason = strerror(errno);
BUILDBOX_LOG_ERROR(
"Warning: could not get current working directory: "
<< errorReason);
return std::string();
}
}
}
int FileUtils::parentDirectoryLevels(const std::string &path)
{
int currentLevel = 0;
int lowestLevel = 0;
const char *path_p = path.c_str();
while (*path_p != 0) {
const char *slash = strchr(path_p, '/');
if (!slash) {
break;
}
const auto segmentLength = slash - path_p;
if (segmentLength == 0 || (segmentLength == 1 && path_p[0] == '.')) {
// Empty or dot segments don't change the level.
}
else if (segmentLength == 2 && path_p[0] == '.' && path_p[1] == '.') {
currentLevel--;
lowestLevel = std::min(lowestLevel, currentLevel);
}
else {
currentLevel++;
}
path_p = slash + 1;
}
if (strcmp(path_p, "..") == 0) {
currentLevel--;
lowestLevel = std::min(lowestLevel, currentLevel);
}
return -lowestLevel;
}
std::string FileUtils::lastNSegments(const std::string &path, const int n)
{
if (n == 0) {
return "";
}
const char *path_p = path.c_str();
const auto pathLength = strlen(path_p);
const char *substringStart = path_p + pathLength - 1;
unsigned int substringLength = 1;
int slashesSeen = 0;
if (path_p[pathLength - 1] == '/') {
substringLength = 0;
}
while (substringStart != path_p) {
if (*(substringStart - 1) == '/') {
slashesSeen++;
if (slashesSeen == n) {
return std::string(substringStart, substringLength);
}
}
substringStart--;
substringLength++;
}
// The path might only be one segment (no slashes)
if (slashesSeen == 0 && n == 1) {
return std::string(path_p, pathLength);
}
throw std::logic_error("Not enough segments in path");
}
bool FileUtils::isAbsolutePath(const std::string &path)
{
return ((!path.empty()) && path[0] == '/');
}
std::string FileUtils::resolvePathFromPrefixMap(const std::string &path)
{
if (RECC_PREFIX_REPLACEMENT.empty()) {
return path;
}
// Iterate through dictionary, replacing path if it includes key, with
// value.
for (const auto &pair : RECC_PREFIX_REPLACEMENT) {
// Check if prefix is found in the path, and that it is a prefix.
if (FileUtils::hasPathPrefix(path, pair.first)) {
// Append a trailing slash to the replacement, in cases of
// replacing `/` Double slashes will get removed during
// normalization.
const std::string replaced_path =
pair.second + '/' + path.substr(pair.first.length());
const std::string newPath =
buildboxcommon::FileUtils::normalizePath(
replaced_path.c_str());
return newPath;
}
}
return path;
}
std::vector<std::string> FileUtils::parseDirectories(const std::string &path)
{
std::vector<std::string> result;
char *token = std::strtok((char *)path.c_str(), "/");
while (token != nullptr) {
result.emplace_back(token);
token = std::strtok(nullptr, "/");
}
return result;
}
} // namespace recc
} // namespace BloombergLP
| 29.346008 | 78 | 0.570744 | sdclarke |
6bf8fca4274fc3f829148363b44e5efb165ce604 | 8,476 | cc | C++ | modules/task_1/danshin_g_matrix_max_by_rows/main.cc | Gekata-2/pp_2021_autumn | caeac9a213e9b0c9fe1ed877d43d1eae5a1bb2cf | [
"BSD-3-Clause"
] | 1 | 2021-12-09T17:20:25.000Z | 2021-12-09T17:20:25.000Z | modules/task_1/danshin_g_matrix_max_by_rows/main.cc | Gekata-2/pp_2021_autumn | caeac9a213e9b0c9fe1ed877d43d1eae5a1bb2cf | [
"BSD-3-Clause"
] | null | null | null | modules/task_1/danshin_g_matrix_max_by_rows/main.cc | Gekata-2/pp_2021_autumn | caeac9a213e9b0c9fe1ed877d43d1eae5a1bb2cf | [
"BSD-3-Clause"
] | 3 | 2022-02-23T14:20:50.000Z | 2022-03-30T09:00:02.000Z | // Copyright 2021 Gleb "belgad" Danshin
#include <gtest/gtest.h>
#include <cstring>
#include "../../../modules/task_1/danshin_g_matrix_max_by_rows/matrix_max_by_rows.h"
#include <gtest-mpi-listener.hpp>
TEST(DanshinGMatrixMaxByRow, ConstMatrixSize5x5) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int *matrix = nullptr, row_num = 0, col_num = 0;
int *answer_sequence = nullptr, *answer_parallel = nullptr;
if (rank == 0) {
row_num = 5;
col_num = 5;
matrix = new int[row_num * col_num] {
1, 3, 5, 4, 2,
1, 13, 45, 67, 89,
-1, 1, -1, 1, -1,
0, 0, 0, 0, 0,
-1, -2, -3, -4, -5
};
answer_sequence = GetMatrixRowMaxSequence(matrix, row_num, col_num);
}
answer_parallel = GetMatrixRowMaxParallel(matrix, row_num, col_num);
if (rank == 0) {
EXPECT_EQ(0, std::memcmp(answer_sequence, answer_parallel, row_num * sizeof(int)));
delete [] matrix;
delete [] answer_sequence;
}
delete [] answer_parallel;
}
TEST(DanshinGMatrixMaxByRow, ConstMatrixSize10x5) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int *matrix = nullptr, row_num = 0, col_num = 0;
int *answer_sequence = nullptr, *answer_parallel = nullptr;
if (rank == 0) {
row_num = 10;
col_num = 5;
matrix = new int[row_num * col_num] {
1, 3, 5, 4, 2,
1, 13, 45, 67, 89,
-1, 1, -1, 1, -1,
0, 0, 0, 0, 0,
-1, -2, -3, -4, -5,
-1, 3, -5, 4, -2,
99, 78, 57, 36, 15,
2, 2, 2, 2, 6,
-100000000, 100000000, 0, 0, 0,
-1000, 1000, -1000, 1000, -2000
};
answer_sequence = GetMatrixRowMaxSequence(matrix, row_num, col_num);
}
answer_parallel = GetMatrixRowMaxParallel(matrix, row_num, col_num);
if (rank == 0) {
EXPECT_EQ(0, std::memcmp(answer_sequence, answer_parallel, row_num * sizeof(int)));
delete [] matrix;
delete [] answer_sequence;
}
delete [] answer_parallel;
}
TEST(DanshinGMatrixMaxByRow, ConstMatrixSize5x10) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int *matrix = nullptr, row_num = 0, col_num = 0;
int *answer_sequence = nullptr, *answer_parallel = nullptr;
if (rank == 0) {
row_num = 5;
col_num = 10;
matrix = new int[row_num * col_num] {
1, 3, 5, 4, 2, -1, 3, -5, 4, -2,
1, 13, 45, 67, 89, 99, 78, 57, 36, 15,
-1, 1, -1, 1, -1, 2, 2, 2, 2, 6,
0, 0, 0, 0, 0, -100000000, 100000000, 0, 0, 0,
-1, -2, -3, -4, -5, -1000, 1000, -1000, 1000, -2000
};
answer_sequence = GetMatrixRowMaxSequence(matrix, row_num, col_num);
}
answer_parallel = GetMatrixRowMaxParallel(matrix, row_num, col_num);
if (rank == 0) {
EXPECT_EQ(0, std::memcmp(answer_sequence, answer_parallel, row_num * sizeof(int)));
delete [] matrix;
delete [] answer_sequence;
}
delete [] answer_parallel;
}
TEST(DanshinGMatrixMaxByRow, ConstMatrixSize10x10) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int *matrix = nullptr, row_num = 0, col_num = 0;
int *answer_sequence = nullptr, *answer_parallel = nullptr;
if (rank == 0) {
row_num = 10;
col_num = 10;
matrix = new int[row_num * col_num] {
1, 3, 5, 4, 2, -1, 3, -5, 4, -2,
1, 13, 45, 67, 89, 99, 78, 57, 36, 15,
-1, 1, -1, 1, -1, 2, 2, 2, 2, 6,
0, 0, 0, 0, 0, -100000000, 100000000, 0, 0, 0,
-1, -2, -3, -4, -5, -1000, 1000, -1000, 1000, -2000,
-1, 3, -5, 4, -2, 6, -8, 9, -10, 9,
99, 78, 57, 36, 15, -6, -27, -48, -69, -90,
2, 2, 2, 2, 6, 6, 6, 6, 2, 2,
-100000000, 100000000, 0, 0, 0, -100000000, 100000000, -100000000, 100000000, 1000000000,
-1000, 1000, -1000, 1000, -2000, -1000, 2000, 1000, -2000, 2000
};
answer_sequence = GetMatrixRowMaxSequence(matrix, row_num, col_num);
}
answer_parallel = GetMatrixRowMaxParallel(matrix, row_num, col_num);
if (rank == 0) {
EXPECT_EQ(0, std::memcmp(answer_sequence, answer_parallel, row_num * sizeof(int)));
delete [] matrix;
delete [] answer_sequence;
}
delete [] answer_parallel;
}
TEST(DanshinGMatrixMaxByRow, RandMatrixSize100x100) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int *matrix = nullptr, row_num = 0, col_num = 0;
int *answer_sequence = nullptr, *answer_parallel = nullptr;
if (rank == 0) {
row_num = 100;
col_num = 100;
matrix = GetRandomMatrix(row_num, col_num);
answer_sequence = GetMatrixRowMaxSequence(matrix, row_num, col_num);
}
answer_parallel = GetMatrixRowMaxParallel(matrix, row_num, col_num);
if (rank == 0) {
EXPECT_EQ(0, std::memcmp(answer_sequence, answer_parallel, row_num * sizeof(int)));
delete [] matrix;
delete [] answer_sequence;
}
delete [] answer_parallel;
}
TEST(DanshinGMatrixMaxByRow, RandMatrixSize250x250) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int *matrix = nullptr, row_num = 0, col_num = 0;
int *answer_sequence = nullptr, *answer_parallel = nullptr;
if (rank == 0) {
row_num = 250;
col_num = 250;
matrix = GetRandomMatrix(row_num, col_num);
answer_sequence = GetMatrixRowMaxSequence(matrix, row_num, col_num);
}
answer_parallel = GetMatrixRowMaxParallel(matrix, row_num, col_num);
if (rank == 0) {
EXPECT_EQ(0, std::memcmp(answer_sequence, answer_parallel, row_num * sizeof(int)));
delete [] matrix;
delete [] answer_sequence;
}
delete [] answer_parallel;
}
TEST(DanshinGMatrixMaxByRow, RandMatrixSize250x500) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int *matrix = nullptr, row_num = 0, col_num = 0;
int *answer_sequence = nullptr, *answer_parallel = nullptr;
if (rank == 0) {
row_num = 250;
col_num = 500;
matrix = GetRandomMatrix(row_num, col_num);
answer_sequence = GetMatrixRowMaxSequence(matrix, row_num, col_num);
}
answer_parallel = GetMatrixRowMaxParallel(matrix, row_num, col_num);
if (rank == 0) {
EXPECT_EQ(0, std::memcmp(answer_sequence, answer_parallel, row_num * sizeof(int)));
delete [] matrix;
delete [] answer_sequence;
}
delete [] answer_parallel;
}
TEST(DanshinGMatrixMaxByRow, RandMatrixSize500x250) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int *matrix = nullptr, row_num = 0, col_num = 0;
int *answer_sequence = nullptr, *answer_parallel = nullptr;
if (rank == 0) {
row_num = 500;
col_num = 250;
matrix = GetRandomMatrix(row_num, col_num);
answer_sequence = GetMatrixRowMaxSequence(matrix, row_num, col_num);
}
answer_parallel = GetMatrixRowMaxParallel(matrix, row_num, col_num);
if (rank == 0) {
EXPECT_EQ(0, std::memcmp(answer_sequence, answer_parallel, row_num * sizeof(int)));
delete [] matrix;
delete [] answer_sequence;
}
delete [] answer_parallel;
}
TEST(DanshinGMatrixMaxByRow, RandMatrixSize500x500) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int *matrix = nullptr, row_num = 0, col_num = 0;
int *answer_sequence = nullptr, *answer_parallel = nullptr;
if (rank == 0) {
row_num = 500;
col_num = 500;
matrix = GetRandomMatrix(row_num, col_num);
answer_sequence = GetMatrixRowMaxSequence(matrix, row_num, col_num);
}
answer_parallel = GetMatrixRowMaxParallel(matrix, row_num, col_num);
if (rank == 0) {
EXPECT_EQ(0, std::memcmp(answer_sequence, answer_parallel, row_num * sizeof(int)));
delete [] matrix;
delete [] answer_sequence;
}
delete [] answer_parallel;
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
MPI_Init(&argc, &argv);
::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment);
::testing::TestEventListeners& listeners =
::testing::UnitTest::GetInstance()->listeners();
listeners.Release(listeners.default_result_printer());
listeners.Release(listeners.default_xml_generator());
listeners.Append(new GTestMPIListener::MPIMinimalistPrinter);
return RUN_ALL_TESTS();
}
| 36.068085 | 101 | 0.604412 | Gekata-2 |
6bfb55de8e0dcf938ed071f55e5f640d3bed28e7 | 995 | cxx | C++ | panda/src/express/p3express_composite1.cxx | cmarshall108/panda3d-python3 | 8bea2c0c120b03ec1c9fd179701fdeb7510bb97b | [
"PHP-3.0",
"PHP-3.01"
] | 3 | 2018-03-09T12:07:29.000Z | 2021-02-25T06:50:25.000Z | panda/src/express/p3express_composite1.cxx | cmarshall108/panda3d-python3 | 8bea2c0c120b03ec1c9fd179701fdeb7510bb97b | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | panda/src/express/p3express_composite1.cxx | cmarshall108/panda3d-python3 | 8bea2c0c120b03ec1c9fd179701fdeb7510bb97b | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | #include "buffer.cxx"
#include "checksumHashGenerator.cxx"
#include "config_express.cxx"
#include "compress_string.cxx"
#include "copy_stream.cxx"
#include "datagram.cxx"
#include "datagramGenerator.cxx"
#include "datagramIterator.cxx"
#include "datagramSink.cxx"
#include "dcast.cxx"
#include "encrypt_string.cxx"
#include "error_utils.cxx"
#include "fileReference.cxx"
#include "hashGeneratorBase.cxx"
#include "hashVal.cxx"
#include "memoryInfo.cxx"
#include "memoryUsage.cxx"
#include "memoryUsagePointerCounts.cxx"
#include "memoryUsagePointers.cxx"
#include "multifile.cxx"
#include "namable.cxx"
#include "nodePointerToBase.cxx"
#include "nodePointerTo.cxx"
#include "nodeReferenceCount.cxx"
#include "openSSLWrapper.cxx"
#include "ordered_vector.cxx"
#include "patchfile.cxx"
#include "password_hash.cxx"
#include "pointerTo.cxx"
#include "pointerToArray.cxx"
#include "pointerToBase.cxx"
#include "pointerToVoid.cxx"
#include "profileTimer.cxx"
#include "pStatCollectorForwardBase.cxx"
| 28.428571 | 40 | 0.794975 | cmarshall108 |
6bfee5ce76617eed17113adf139adbd41ca03e6b | 1,405 | hh | C++ | src/bugengine/meta/include/builtin-ubytex.script.hh | bugengine/BugEngine | 1b3831d494ee06b0bd74a8227c939dd774b91226 | [
"BSD-3-Clause"
] | 4 | 2015-05-13T16:28:36.000Z | 2017-05-24T15:34:14.000Z | src/bugengine/meta/include/builtin-ubytex.script.hh | bugengine/BugEngine | 1b3831d494ee06b0bd74a8227c939dd774b91226 | [
"BSD-3-Clause"
] | null | null | null | src/bugengine/meta/include/builtin-ubytex.script.hh | bugengine/BugEngine | 1b3831d494ee06b0bd74a8227c939dd774b91226 | [
"BSD-3-Clause"
] | 1 | 2017-03-21T08:28:07.000Z | 2017-03-21T08:28:07.000Z | /* BugEngine <bugengine.devel@gmail.com>
see LICENSE for detail */
#ifndef BE_META_BUILTIN_UBYTEX_SCRIPT_HH_
#define BE_META_BUILTIN_UBYTEX_SCRIPT_HH_
/**************************************************************************************************/
#include <bugengine/meta/stdafx.h>
#include <bugengine/meta/builtin.hh>
#include <bugengine/meta/classinfo.script.hh>
#if 0
namespace BugEngine
{
be_tag(Index(BugEngine::Meta::ClassType_Vector2
+ (BugEngine::Meta::ClassIndex_u8 << 16)))
be_pod ubyte2
{
u8 operator[](u32) const;
u8& operator[](u32);
};
be_tag(Index(BugEngine::Meta::ClassType_Vector3
+ (BugEngine::Meta::ClassIndex_u8 << 16)))
be_pod ubyte3
{
u8 operator[](u32) const;
u8& operator[](u32);
};
be_tag(Index(BugEngine::Meta::ClassType_Vector4
+ (BugEngine::Meta::ClassIndex_u8 << 16)))
be_pod ubyte4
{
u8 operator[](u32) const;
u8& operator[](u32);
};
be_tag(Index(BugEngine::Meta::ClassType_Vector8
+ (BugEngine::Meta::ClassIndex_u8 << 16)))
be_pod ubyte8
{
u8 operator[](u32) const;
u8& operator[](u32);
};
be_tag(Index(BugEngine::Meta::ClassType_Vector16
+ (BugEngine::Meta::ClassIndex_u8 << 16)))
be_pod ubyte16
{
u8 operator[](u32) const;
u8& operator[](u32);
};
}
#endif
/**************************************************************************************************/
#endif
| 23.032787 | 100 | 0.579359 | bugengine |
6bffc1817191a100adbdbd8d9e9fc9f454789e06 | 10,343 | cpp | C++ | includes/textureLoading.cpp | MuUusta/Hello-GFX | c707570207a2db638458352c2de6c03bce5a6759 | [
"MIT"
] | 2 | 2019-05-20T11:12:07.000Z | 2021-03-25T04:24:57.000Z | includes/textureLoading.cpp | MuUusta/Hello-GFX | c707570207a2db638458352c2de6c03bce5a6759 | [
"MIT"
] | null | null | null | includes/textureLoading.cpp | MuUusta/Hello-GFX | c707570207a2db638458352c2de6c03bce5a6759 | [
"MIT"
] | null | null | null | #include <textureLoading.h>
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
static unsigned int getint(FILE *fp)
{
int c, c1, c2, c3;
// get 4 bytes
c = getc(fp);
c1 = getc(fp);
c2 = getc(fp);
c3 = getc(fp);
return ((unsigned int) c) +
(((unsigned int) c1) << 8) +
(((unsigned int) c2) << 16) +
(((unsigned int) c3) << 24);
}
static unsigned int getshort(FILE *fp)
{
int c, c1;
//get 2 bytes
c = getc(fp);
c1 = getc(fp);
return ((unsigned int) c) + (((unsigned int) c1) << 8);
}
// quick and dirty bitmap loader...for 24 bit bitmaps with 1 plane only.
// See http://www.dcs.ed.ac.uk/~mxr/gfx/2d/BMP.txt for more info.
int ImageLoad(const char *filename, Image *image)
{
FILE *file;
unsigned long size; // size of the image in bytes.
unsigned long i; // standard counter.
unsigned short int planes; // number of planes in image (must be 1)
unsigned short int bpp; // number of bits per pixel (must be 24)
char temp; // used to convert bgr to rgb color.
// make sure the file is there.
if ((file = fopen(filename, "rb"))==NULL) {
printf("File Not Found : %s\n",filename);
return 0;
}
// seek through the bmp header, up to the width/height:
fseek(file, 18, SEEK_CUR);
// No 100% errorchecking anymore!!!
// read the width
image->sizeX = getint (file);
//printf("Width of %s: %lu\n", filename, image->sizeX);
// read the height
image->sizeY = getint (file);
//printf("Height of %s: %lu\n", filename, image->sizeY);
// calculate the size (assuming 24 bits or 3 bytes per pixel).
size = image->sizeX * image->sizeY * 3;
// read the planes
planes = getshort(file);
if (planes != 1) {
printf("Planes from %s is not 1: %u\n", filename, planes);
return 0;
}
// read the bpp
bpp = getshort(file);
if (bpp != 24) {
printf("Bpp from %s is not 24: %u\n", filename, bpp);
return 0;
}
// seek past the rest of the bitmap header.
fseek(file, 24, SEEK_CUR);
// read the data.
image->data = (char *) malloc(size);
if (image->data == NULL) {
printf("Error allocating memory for color-corrected image data");
return 0;
}
if ((i = fread(image->data, size, 1, file)) != 1) {
printf("Error reading image data from %s.\n", filename);
return 0;
}
for (i=0;i<size;i+=3) { // reverse all of the colors. (bgr -> rgb)
temp = image->data[i];
image->data[i] = image->data[i+2];
image->data[i+2] = temp;
}
// we're done.
return 1;
}
// Load Bitmaps And Convert To Textures
unsigned int LoadGLTextures(const char* path)
{
// Load Texture
Image *image1;
unsigned int texterID;
// allocate space for texture
image1 = (Image *) malloc(sizeof(Image));
if (image1 == NULL) {
printf("Error allocating space for image");
exit(0);
}
if (!ImageLoad(path, image1)) {
exit(1);
}
// Create Textures
glGenTextures(1, &texterID);
// texture 1 (poor quality scaling)
glBindTexture(GL_TEXTURE_2D, texterID); // 2d texture (x and y size)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE); // for this tutorial: use GL_CLAMP_TO_EDGE to prevent semi-transparent borders. Due to interpolation it takes texels from next repeat
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// 2d texture, level of detail 0 (normal), 3 components (red, green, blue), x size from image, y size from image,
// border 0 (normal), rgb color data, unsigned byte data, and finally the data itself.
glTexImage2D(GL_TEXTURE_2D, 0, 3, image1->sizeX, image1->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, image1->data);
return texterID;
};
GLuint loadTex_stb(const char *path)
{
int my_image_width, my_image_height;
unsigned char* my_image_data;
if(stbi_load(path, &my_image_width, &my_image_height, NULL, 4))
my_image_data = stbi_load(path, &my_image_width, &my_image_height, NULL, 4);
else
cout<<"Can't find file > :"<<path<<endl;
// Turn the RGBA pixel data into an OpenGL texture:
GLuint my_opengl_texture;
glGenTextures(1, &my_opengl_texture);
glBindTexture(GL_TEXTURE_2D, my_opengl_texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE); // for this tutorial: use GL_CLAMP_TO_EDGE to prevent semi-transparent borders. Due to interpolation it takes texels from next repeat
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, my_image_width, my_image_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, my_image_data);
stbi_set_flip_vertically_on_load(true);
return my_opengl_texture;
}
GLuint logl_loadTex_stb(const char *path, bool gammaCorrection)
{
GLuint textureID;
glGenTextures(1, &textureID);
int width, height, nrComponents;
unsigned char *data = stbi_load(path, &width, &height, &nrComponents, 0);
if (data)
{
GLenum internalFormat;
GLenum dataFormat;
if (nrComponents == 1)
{
internalFormat = dataFormat = GL_RED;
}
else if (nrComponents == 3)
{
internalFormat = gammaCorrection ? GL_SRGB : GL_RGB;
dataFormat = GL_RGB;
}
else if (nrComponents == 4)
{
internalFormat = gammaCorrection ? GL_SRGB_ALPHA : GL_RGBA;
dataFormat = GL_RGBA;
}
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, width, height, 0, dataFormat, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, dataFormat == GL_RGBA ? GL_CLAMP_TO_EDGE : GL_REPEAT); // for this tutorial: use GL_CLAMP_TO_EDGE to prevent semi-transparent borders. Due to interpolation it takes texels from next repeat
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, dataFormat == GL_RGBA ? GL_CLAMP_TO_EDGE : GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
stbi_image_free(data);
}
else
{
std::cout << "Texture failed to load at path: " << path << std::endl;
stbi_image_free(data);
}
return textureID;
}
unsigned int logl_loadTex_stb(char const * path)
{
unsigned int textureID;
glGenTextures(1, &textureID);
int width, height, nrComponents;
unsigned char *data = stbi_load(path, &width, &height, &nrComponents, 0);
if (data)
{
GLenum format;
if (nrComponents == 1)
format = GL_RED;
else if (nrComponents == 3)
format = GL_RGB;
else if (nrComponents == 4)
format = GL_RGBA;
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, format == GL_RGBA ? GL_CLAMP_TO_EDGE : GL_REPEAT); // for this tutorial: use GL_CLAMP_TO_EDGE to prevent semi-transparent borders. Due to interpolation it takes texels from next repeat
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, format == GL_RGBA ? GL_CLAMP_TO_EDGE : GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
stbi_image_free(data);
}
else
{
std::cout << "Texture failed to load at path: " << path << std::endl;
stbi_image_free(data);
}
return textureID;
}
GLuint loadTex_stb(const char *path, int &my_image_width, int &my_image_height)
{
//int my_image_width, my_image_height;
unsigned char* my_image_data;
if(stbi_load(path, &my_image_width, &my_image_height, NULL, 4))
my_image_data = stbi_load(path, &my_image_width, &my_image_height, NULL, 4);
else
cout<<"Can't find file > :"<<path<<endl;
stbi_set_flip_vertically_on_load(false);
// Turn the RGBA pixel data into an OpenGL texture:
GLuint my_opengl_texture;
glGenTextures(1, &my_opengl_texture);
glBindTexture(GL_TEXTURE_2D, my_opengl_texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE); // for this tutorial: use GL_CLAMP_TO_EDGE to prevent semi-transparent borders. Due to interpolation it takes texels from next repeat
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, my_image_width, my_image_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, my_image_data);
return my_opengl_texture;
}
unsigned int loadCubemap(vector<std::string> faces)
{
unsigned int textureID;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);
stbi_set_flip_vertically_on_load(false);
int width, height, nrChannels;
for (unsigned int i = 0; i < faces.size(); i++)
{
unsigned char *data = stbi_load(faces[i].c_str(), &width, &height, &nrChannels, 0);
if (data)
{
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
stbi_image_free(data);
}
else
{
std::cout << "Cubemap texture failed to load at path: " << faces[i] << std::endl;
stbi_image_free(data);
}
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
return textureID;
}
| 34.023026 | 246 | 0.685101 | MuUusta |
d4031270386dc644c650974438d059ec12860c2d | 666 | cpp | C++ | solutions/25.reverse-nodes-in-k-group.228894559.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | 78 | 2020-10-22T11:31:53.000Z | 2022-02-22T13:27:49.000Z | solutions/25.reverse-nodes-in-k-group.228894559.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | null | null | null | solutions/25.reverse-nodes-in-k-group.228894559.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | 26 | 2020-10-23T15:10:44.000Z | 2021-11-07T16:13:50.000Z | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *reverseKGroup(ListNode *head, int k) {
int c = k;
ListNode *temp = head;
while (c && temp) {
c--;
temp = temp->next;
}
if (c)
return head;
ListNode *first = head;
ListNode *t1 = NULL;
for (int i = 0; i < k && head != NULL; i++) {
ListNode *t2 = head->next;
head->next = t1;
t1 = head;
head = t2;
}
if (head) {
first->next = reverseKGroup(head, k);
}
return t1;
}
};
| 16.65 | 50 | 0.493994 | satu0king |
d4038ade082441b5b466d996370b16dd01f5ce14 | 5,006 | cpp | C++ | pwiz/data/vendor_readers/Waters/Reader_Waters_Detail.cpp | austinkeller/pwiz | aa8e575cb40fd5e97cc7d922e4d8da44c9277cca | [
"Apache-2.0"
] | null | null | null | pwiz/data/vendor_readers/Waters/Reader_Waters_Detail.cpp | austinkeller/pwiz | aa8e575cb40fd5e97cc7d922e4d8da44c9277cca | [
"Apache-2.0"
] | null | null | null | pwiz/data/vendor_readers/Waters/Reader_Waters_Detail.cpp | austinkeller/pwiz | aa8e575cb40fd5e97cc7d922e4d8da44c9277cca | [
"Apache-2.0"
] | null | null | null | //
// $Id$
//
//
// Original author: Matt Chambers <matt.chambers .@. vanderbilt.edu>
//
// Copyright 2009 Vanderbilt University - Nashville, TN 37232
//
// 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.
//
#define PWIZ_SOURCE
#include "Reader_Waters_Detail.hpp"
#include "pwiz/utility/misc/Container.hpp"
#include "pwiz/utility/misc/String.hpp"
namespace pwiz {
namespace msdata {
namespace detail {
namespace Waters {
PWIZ_API_DECL
vector<InstrumentConfiguration> createInstrumentConfigurations(RawDataPtr rawdata)
{
return vector<InstrumentConfiguration>();
}
PWIZ_API_DECL CVID translateAsInstrumentModel(RawDataPtr rawdata)
{
return CVID_Unknown;
}
PWIZ_API_DECL
void translateFunctionType(PwizFunctionType functionType,
int& msLevel,
CVID& spectrumType)
{
switch (functionType)
{
/*case FunctionType_MSMSMS:
msLevel = 3;
spectrumType = MS_MSn_spectrum;
break;*/
case FunctionType_Daughters:
//case FunctionType_MSMS:
case FunctionType_MS2:
case FunctionType_TOF_Daughter:
case FunctionType_Auto_Daughters:
msLevel = 2;
spectrumType = MS_MSn_spectrum;
break;
case FunctionType_SIR:
msLevel = 1;
spectrumType = MS_SIM_spectrum;
break;
case FunctionType_MRM:
case FunctionType_AutoSpec_MRM:
case FunctionType_AutoSpec_Q_MRM_Quad:
case FunctionType_AutoSpec_MIKES_Scan:
msLevel = 2;
spectrumType = MS_SRM_spectrum;
break;
case FunctionType_Neutral_Loss:
msLevel = 2;
spectrumType = MS_constant_neutral_loss_spectrum;
break;
case FunctionType_Neutral_Gain:
msLevel = 2;
spectrumType = MS_constant_neutral_gain_spectrum;
break;
case FunctionType_Parents:
case FunctionType_Scan:
case FunctionType_Q1F:
case FunctionType_TOF:
case FunctionType_TOF_MS:
case FunctionType_TOF_Survey:
case FunctionType_TOF_Parent:
case FunctionType_MALDI_TOF:
msLevel = 1;
spectrumType = MS_MS1_spectrum;
break;
// these functions are not mass spectra
case FunctionType_Diode_Array:
msLevel = 0;
spectrumType = MS_EMR_spectrum;
break;
case FunctionType_Off:
case FunctionType_Voltage_Scan:
case FunctionType_Magnetic_Scan:
case FunctionType_Voltage_SIR:
case FunctionType_Magnetic_SIR:
msLevel = 0;
spectrumType = CVID_Unknown;
break;
/* TODO: figure out what these function types translate to
FunctionType_Delay
FunctionType_Concatenated
FunctionType_TOF_PSD
FunctionType_AutoSpec_B_E_Scan
FunctionType_AutoSpec_B2_E_Scan
FunctionType_AutoSpec_CNL_Scan
FunctionType_AutoSpec_MIKES_Scan
FunctionType_AutoSpec_NRMS_Scan
*/
default:
throw std::runtime_error("[translateFunctionType] Unable to translate function type.");
}
}
PWIZ_API_DECL CVID translateAsIonizationType(PwizIonizationType ionizationType)
{
/*switch (ionizationType)
{
case IonizationType_EI = 0, // Electron Ionization
case IonizationType_CI, // Chemical Ionization
case IonizationType_FB, // Fast Atom Bombardment
case IonizationType_TS, // Thermospray
case IonizationType_ES, // Electrospray Ionization
case IonizationType_AI, // Atmospheric Ionization
case IonizationType_LD, // Laser Desorption Ionization
case IonizationType_FI, // ?
case IonizationType_Generic,
case IonizationType_Count*/
return CVID_Unknown;
}
PWIZ_API_DECL CVID translate(PwizPolarityType polarityType)
{
switch (polarityType)
{
case PolarityType_Positive: return MS_positive_scan;
case PolarityType_Negative: return MS_negative_scan;
default: return CVID_Unknown;
}
}
} // Waters
} // detail
} // msdata
} // pwiz
| 29.621302 | 100 | 0.628046 | austinkeller |
d4056c16701e69db4fbd6b7b219e5fbbe02b674d | 3,358 | cpp | C++ | qt-ticket/src/useruletablemodel.cpp | waitWindComing/QT | c8401679b7265785ec8c7e97eea7e1e37631f37d | [
"Apache-2.0"
] | null | null | null | qt-ticket/src/useruletablemodel.cpp | waitWindComing/QT | c8401679b7265785ec8c7e97eea7e1e37631f37d | [
"Apache-2.0"
] | null | null | null | qt-ticket/src/useruletablemodel.cpp | waitWindComing/QT | c8401679b7265785ec8c7e97eea7e1e37631f37d | [
"Apache-2.0"
] | null | null | null | #include "useruletablemodel.h"
#include <qDebug>
UseRuleTableModel::UseRuleTableModel(const QList<UseRule *> &useRules, QObject* parent)
:_useRules(useRules),
QAbstractTableModel(parent)
{
_header << trUtf8("名称") << trUtf8("最低消费") << trUtf8("最大抵扣") << trUtf8("类型") << trUtf8("信息") << trUtf8("选择");
}
int UseRuleTableModel::rowCount(const QModelIndex& parent) const
{
return _useRules.size();
}
int UseRuleTableModel::columnCount(const QModelIndex& parent) const
{
return 6;
}
QVariant UseRuleTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (section < 6 && role == Qt::DisplayRole) {
return _header[section];
} else {
return QVariant();
}
}
QVariant UseRuleTableModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid()) return QVariant();
if (index.row() >= _useRules.size()) return QVariant();
UseRule *useRule = _useRules.at(index.row());
if (role == Qt::DisplayRole) {
if (index.column() == 0) {
return useRule->getRuleName();
} else if (index.column() == 1) {
QString rst;
return rst.setNum(useRule->getLeastConsume() / 100.0, 'f', 2);
} else if (index.column() == 2) {
QString rst;
return rst.setNum(useRule->getMaxDeduction() / 100.0, 'f', 2);
} else if (index.column() == 3) {
if (UseRule::Discount == useRule->getType()) {
return trUtf8("折扣券");
} else {
return trUtf8("代金券");
}
} else if (index.column() == 4) {
QString ruleinfo;
if (UseRule::Discount == useRule->getType()) {
if (useRule->getDiscountType() == 0) {
ruleinfo = QString("%1:%2").arg(trUtf8("折扣转换系数")).arg(useRule->getConvertRate());
} else {
ruleinfo = QString("%1:%2%").arg(trUtf8("新折扣率")).arg(useRule->getDiscount());
}
} else {
ruleinfo = QString("%1:%2%").arg(trUtf8("抵扣率")).arg(useRule->getRate());
}
return ruleinfo;
} else { // radiobox
return QVariant();
}
}
if (role == Qt::CheckStateRole) {
return useRule->getCheckState();
}
return QVariant();
}
Qt::ItemFlags UseRuleTableModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return 0;
if (index.column() == 5) {
return Qt::ItemIsEnabled | Qt::ItemIsEditable;
} else {
return Qt::ItemIsEnabled;
}
}
bool UseRuleTableModel::setData ( const QModelIndex & index, const QVariant & value, int role )
{
Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
UseRule *useRule = _useRules.at(index.row());
useRule->setCheckState(state);
emit dataChanged(createIndex(index.row(), 0), createIndex(index.row(), 6));
return true;
}
void UseRuleTableModel::clearChecked()
{
for (QList<UseRule *>::const_iterator i = _useRules.begin(); i != _useRules.end(); ++i) {
(*i)->setCheckState(Qt::Unchecked);
}
}
void UseRuleTableModel::itemAppended()
{
beginInsertRows(QModelIndex(), _useRules.size(), _useRules.size());
endInsertRows();
}
void UseRuleTableModel::refresh()
{
emit layoutChanged();
}
| 29.45614 | 112 | 0.581298 | waitWindComing |